<?php
namespace App\Controller\higotrigo;
use App\Entity\Client;
use App\Entity\HtProforma;
use App\Entity\HtProformaItems;
use App\Entity\Supplier;
use App\Entity\Country;
use App\Entity\HtExtra;
use App\Entity\HtFile;
use App\Entity\HtInvoice;
use App\Entity\HtInvoiceItems;
use App\Entity\HtItem;
use App\Entity\HtMenu;
use App\Service\HtService;
use App\Form\HtInvoiceType;
use App\Repository\HtInvoiceRepository;
use Google\Service\Dfareporting\Resource\Countries;
use Google\Service\MigrationCenterAPI\DateTime;
use Monolog\DateTimeImmutable;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\SettingsCompany;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* @Route("/higotrigo/ht/invoice")
*/
class HtInvoiceController extends AbstractController
{
/**
* @Route("/", name="app_ht_invoice_index", methods={"GET"})
*/
public function index(HtInvoiceRepository $htInvoiceRepository): Response
{
$htInvoices = $htInvoiceRepository->findAll();
foreach ($htInvoices as $invoice) {
// Formatear el campo vatTotalGroup
$invoice->setVatTotalGroup($this->formatVatTotalGroup($invoice->getVatTotalGroup()));
}
return $this->render('higotrigo/ht_invoice/index.html.twig', [
'ht_invoices' => $htInvoices,
]);
}
/**
* @Route("/new", name="app_ht_invoice_new", methods={"GET", "POST"})
*/
public function new(Request $request, HtInvoiceRepository $htInvoiceRepository): Response
{
$htInvoice = new HtInvoice();
$form = $this->createForm(HtInvoiceType::class, $htInvoice);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$htInvoiceRepository->add($htInvoice, true);
return $this->redirectToRoute('app_ht_invoice_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('higotrigo/ht_invoice/new.html.twig', [
'ht_invoice' => $htInvoice,
'form' => $form,
]);
}
/**
* @Route("/{id}", name="app_ht_invoice_show", methods={"GET"})
*/
public function show(HtInvoice $htInvoice): Response
{
$em = $this->getDoctrine()->getManager();
$company = $em->getRepository(SettingsCompany::class)->findOneByPriority('5');
$currency = '€';
$boolToRec = false;
return $this->render('higotrigo/ht_invoice/show.html.twig', [
'ht_invoice' => $htInvoice,
'company' => $company,
'currency' => $currency,
'boolToRec' => $boolToRec,
]);
}
/**
* @Route("/{id}/edit", name="app_ht_invoice_edit", methods={"GET", "POST"})
*/
public function edit(Request $request, HtInvoice $htInvoice, HtInvoiceRepository $htInvoiceRepository): Response
{
$form = $this->createForm(HtInvoiceType::class, $htInvoice);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$htInvoiceRepository->add($htInvoice, true);
return $this->redirectToRoute('app_ht_invoice_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('higotrigo/ht_invoice/edit.html.twig', [
'ht_invoice' => $htInvoice,
'form' => $form,
]);
}
/**
* @Route("/{id}", name="app_ht_invoice_delete", methods={"POST"})
*/
public function delete(Request $request, HtInvoice $htInvoice, HtInvoiceRepository $htInvoiceRepository): Response
{
if ($this->isCsrfTokenValid('delete'.$htInvoice->getId(), $request->request->get('_token'))) {
$htInvoiceRepository->remove($htInvoice, true);
}
return $this->redirectToRoute('app_ht_invoice_index', [], Response::HTTP_SEE_OTHER);
}
/**
* @Route("/selinvoice/{id}", name="ht_select_invoice")
* Seleccionar los elementos que pasaran a la proforma o factura
*/
public function selectItemsInvoiceAction(HtFile $htFile, EntityManagerInterface $em, Request $request)
{
$beneficio = $request->query->get('bn');
// hfile => htitem => htMenu => htExtra ; htMenu => htMenuEscandallo => escandallo
$data = array();
$data['file'] = $htFile;
$allHtItems = $htFile->getHtItems();
$allHtMenus = array();
$allHtExtrasinFile = array();
$allHtEscandallos = array();
$beneficioItem = 0;
$indiceBeneficio = -1;
foreach ($allHtItems as $item) {
$indiceBeneficio ++;
$data['items'][$item->getId()]['item'] = $item;
$data['items'][$item->getId()]['item_beneficio'] = $beneficio[$indiceBeneficio];
$allHtExtras = $item->getHtExtras();
foreach ($allHtExtras as $htSinlgeExtra){
$htExtraIsInvoiced = $em->getRepository(HtInvoiceItems::class)->findBy(array('itemType' => 'htExtra', 'itemIdOrigin' => $htSinlgeExtra->getId()));
$boolIsInvoiced = ((count($htExtraIsInvoiced)) % 2 == 0) ? false : true;
$data['items'][$item->getId()]['extras'][] = $htSinlgeExtra;
if ($htSinlgeExtra->isAppearInvoice()) {
$extra_price_no_vat = $htSinlgeExtra->isOpOverCommission() ? $htSinlgeExtra->getPrice() * (1 + $htSinlgeExtra->getOverCommission() /100) : ($htSinlgeExtra->getPrice() + $htSinlgeExtra->getOverCommission());
$extra_price = $extra_price_no_vat * (1 + ($htSinlgeExtra->getVat()/100));
$allHtExtrasinFile[] = array(
'enabledToInvoice' => !$boolIsInvoiced,
'extra' => $htSinlgeExtra,
'extra_price_no_vat' => ($boolIsInvoiced) ? 0: $extra_price_no_vat,
'extra_price' => ($boolIsInvoiced) ? 0: $extra_price,
);
}
}
$htMenus = $item->getHtMenus();
if (!empty($htMenus)){
foreach ($htMenus as $htMenu) {
$allHtMenus[] = $htMenu;
$data['items'][$item->getId()]['menus'][$htMenu->getId()]['menu']['menu_info'] = $htMenu;
$htExtras = $htMenu->getHtExtras();
if (!empty($htExtras)) {
foreach ($htExtras as $elem) {
$data['items'][$item->getId()]['menus'][$htMenu->getId()]['menu']['extras'][] = $elem;
$allHtExtras[] = $elem;
}
}
$escandallo = $htMenu->getEscandallo();
if (!empty($escandallo)) {
$data['items'][$item->getId()]['menus'][$htMenu->getId()]['menu']['escandallos_names'] = null;
foreach ($escandallo as $escan) {
$data['items'][$item->getId()]['menus'][$htMenu->getId()]['menu']['escandallos'][] = $escan;
$allHtEscandallos[] = $escan;
$data['items'][$item->getId()]['menus'][$htMenu->getId()]['menu']['escandallos_names'] = (empty($data['items'][$item->getId()]['menus'][$htMenu->getId()]['menu']['escandallos_names'])) ? ($escan->getNombre()) : ($data['items'][$item->getId()]['menus'][$htMenu->getId()]['menu']['escandallos_names'] . ', ' . $escan->getNombre());
}
}
}
}
}
$data['company'] = $em->getRepository(SettingsCompany::class)->findOneByPriority('5');
$data['client'] = $em->getRepository(Client::class)->findOneById($htFile->getClient());
$data_iva = array();
$data_iva['ivaMontoVeintiUno'] = 0;
$data_iva['ivaMontoDiez'] = 0;
$data_iva['ivaMontoCero'] = 0;
$netoSum = 0; $totalSum = 0;
$indiceBeneficio = -1;
if (array_key_exists("items", $data)) {
foreach ($data['items'] as $itemFac) {
if (array_key_exists("menus", $itemFac)) {
$indiceBeneficio++;
foreach ($itemFac['menus'] as $htMenu) {
$productName = $htMenu['menu']['menu_info']->getName() . ' ( ' . $htMenu['menu']['escandallos_names'] . ' )';
$servicePrice = (($htMenu['menu']['menu_info']->getTotalPrice() * 100) / (100 + $htMenu['menu']['menu_info']->getIva()));
$subTotalPrice = round((($htMenu['menu']['menu_info']->getTotalPrice() * 100) / (100 + $htMenu['menu']['menu_info']->getIva())), 2) * $itemFac['item']->getPax();
$subtotalProduct = $subTotalPrice * (1 + ($htMenu['menu']['menu_info']->getIva() / 100));
$ivaAmount = ($htMenu['menu']['menu_info']->getIva() * $subTotalPrice) / 100;
$htMenuIsInvoiced = $em->getRepository(HtInvoiceItems::class)->findBy(array('itemType' => 'htMenu', 'itemIdOrigin' => $htMenu['menu']['menu_info']->getId()));
$boolIsInvoiced = ((count($htMenuIsInvoiced)) % 2 == 0) ? false : true;
if (!$boolIsInvoiced) {
$netoSum += $subTotalPrice;
$totalSum += $subtotalProduct;
switch ($htMenu['menu']['menu_info']->getIva()) {
case 10: $data_iva['ivaMontoDiez'] += $ivaAmount; break;
case 21: $data_iva['ivaMontoVeintiUno'] += $ivaAmount; break;
default: break;
}
}
$data['product'][] = array(
'id' => $htMenu['menu']['menu_info']->getId(), // Id del Menu
'idHtItem' => $itemFac['item']->getId(), // Id del Servicio (HtItem) que contiene el Menu
'enabledToInvoice' => !$boolIsInvoiced,
'productName' => $productName,
'type' => null,
'servicePrice' => $servicePrice,
'qty' => $itemFac['item']->getPax(),
'days' => $itemFac['item']->getDateStart()->format('d/m/Y'),
'subTotalPrice' => ($boolIsInvoiced) ? 0 : $subTotalPrice,
'iva' => $htMenu['menu']['menu_info']->getIva(),
'ivaAmount' => $ivaAmount,
'subtotalProduct' => ($boolIsInvoiced) ? 0 : $subtotalProduct,
'beneficio' => $beneficio[$indiceBeneficio],
'productSubTotal' => array(
'neto' => null,
'sumSubT' => null,
),
);
}
}
}
}
$netoAllSum = $netoSum;
$totalSumItems = $totalSum;
// SERVICIOS ADICIONALES
$data_extras = array();
if (!empty($allHtExtrasinFile)){ $data_extras['allHtExtrasinFile'] = $allHtExtrasinFile; }
$data_extras_sum = array('extra_price_no_vat' => 0, 'extra_price' => 0,);
foreach ($allHtExtrasinFile as $item){
$data_extras_sum['extra_price_no_vat'] += $item['extra_price_no_vat'];
$data_extras_sum['extra_price'] += $item['extra_price'];
$montoIva = $item['extra_price'] - $item['extra_price_no_vat'];
switch ($item['extra']->getVat()) {
case 10: $data_iva['ivaMontoDiez'] += $montoIva; break;
case 21: $data_iva['ivaMontoVeintiUno'] += $montoIva; break;
default: break;
}
$netoAllSum += $item['extra_price_no_vat'];
$totalSum += $item['extra_price'];
}
$clientType = 'client';
$clientAddress = (array_key_exists("client", $data) and !empty($data['client'])) ? $data['client']->getAddress() : 'No se ha podido determinar la dirección';
$country = (array_key_exists("client", $data) and !empty($data['client'])) ? $em->getRepository(Country::class)->findOneById($data['client']->getCountry()) : $em->getRepository(Country::class)->findOneById(62);
$country = $country->getCountry();
if ($country == 'Spain'){ $country = 'España'; }
$clientAddress = $clientAddress . ', '. $country;
$clientDocument = $data['client']->getIdDocument();
return $this->render('higotrigo/ht_invoice/invoice-select-items.html.twig',
array(
'id' => $htFile->getId(),
'htFile' => $htFile,
'prefix' => null,
'date' => null,
'company' => $data['company'],
'clientAddress' => $clientAddress,
'clientType' => $clientType,
'clientDocument' => $clientDocument,
'client' => $data['client'],
'clients' => null,
'datasupplier' => $data,
'data_extras' => $data_extras,
'data_extras_sum' => $data_extras_sum,
'currency' => '€',
'totales_coniva_items' => $totalSumItems,
'totales_coniva' => $totalSum,
'totales_neto_items' => $netoSum,
'totales_neto' => $netoAllSum,
'bases_imponibles' => $data_iva,
)
);
}
/**
* @Route("/selinvoicesp/{id}", name="ht_select_invoice_special")
* Vista previa para selecionar a quien se le va a facturar (proveedor - factura de comisión)
*/
public function generateSpecialInvoiceAction($id, EntityManagerInterface $em, Request $request)
{
//Buscamos los proveedores
$suppliers = $em->getRepository(Supplier::class)->findAll();
$arrayClients = array();
foreach ($suppliers as $item){
$arrayClients[] = array(
'nombre' => $item->getCompany(),
'id' => $item->getId(),
'tipo' => 'PROVEEDOR',
'indice' => 'S'.$item->getId(),
);
}
return $this->render('higotrigo/ht_invoice/invoice-select-client-supplier.html.twig',
array(
'id' => $id,
'clients' => $arrayClients,
)
);
}
/**
* @Route("/selinvoicecom/{id}", name="ht_select_commision_invoice")
* Seleccionar los elementos que pasaran a la factura de comision
*/
public function selectItemsCommisionInvoiceAction($id, HtFile $htFile, HtService $htService, EntityManagerInterface $em, Request $request)
{
$supId = $request->request->get('reservation');
$supId = $supId['client'];
$supId = substr($supId,1);
$supplier = $em->getRepository(Supplier::class)->findOneById($supId);
// El beneficio será del 100% por ser factura de comisión
$beneficio = $request->query->get('bn');
// hfile => htitem => htMenu => htExtra ; htMenu => htMenuEscandallo => escandallo
$data = array();
$data['file'] = $em->getRepository(HtFile::class)->findOneById($id);
$htFile = $data['file'];
$allHtItems = $htFile->getHtItems();
$allHtMenus = array(); $allHtExtrasinFile = array(); $allHtEscandallos = array();
$beneficioItem = 0;
$indiceBeneficio = -1;
$dataBen = $htService->CalcTotals($htFile);
foreach ($allHtItems as $item) {
$indiceBeneficio ++;
$data['items'][$item->getId()]['item'] = $item;
$data['items'][$item->getId()]['item_beneficio'] = $dataBen['htItem'][$item->getId()]['precioNeto'] - $dataBen['htItem'][$item->getId()]['coste'];
$allHtExtras = $item->getHtExtras();
foreach ($allHtExtras as $htSinlgeExtra){
$htExtraIsInvoiced = $em->getRepository(HtInvoiceItems::class)->findBy(array('itemType' => 'htExtra', 'itemIdOrigin' => $htSinlgeExtra->getId()));
$boolIsInvoiced = ((count($htExtraIsInvoiced)) % 2 == 0) ? false : true;
$data['items'][$item->getId()]['extras'][] = $htSinlgeExtra;
if ($htSinlgeExtra->isAppearInvoice()) {
$extra_price_no_vat = $htSinlgeExtra->isOpOverCommission() ? $htSinlgeExtra->getPrice() * (1 + $htSinlgeExtra->getOverCommission() /100) : ($htSinlgeExtra->getPrice() + $htSinlgeExtra->getOverCommission());
$extra_price = $extra_price_no_vat * (1 + ($htSinlgeExtra->getVat()/100));
$allHtExtrasinFile[] = array(
'enabledToInvoice' => !$boolIsInvoiced,
'extra' => $htSinlgeExtra,
'extra_price_no_vat' => ($boolIsInvoiced) ? 0: $extra_price_no_vat,
'extra_price' => ($boolIsInvoiced) ? 0: $extra_price,
);
}
}
$htMenus = $item->getHtMenus();
if (!empty($htMenus)){
foreach ($htMenus as $htMenu) {
$allHtMenus[] = $htMenu;
$data['items'][$item->getId()]['menus'][$htMenu->getId()]['menu']['menu_info'] = $htMenu;
$htExtras = $htMenu->getHtExtras();
if (!empty($htExtras)) {
foreach ($htExtras as $elem) {
$data['items'][$item->getId()]['menus'][$htMenu->getId()]['menu']['extras'][] = $elem;
$allHtExtras[] = $elem;
}
}
$escandallo = $htMenu->getEscandallo();
if (!empty($escandallo)) {
$data['items'][$item->getId()]['menus'][$htMenu->getId()]['menu']['escandallos_names'] = null;
foreach ($escandallo as $escan) {
$data['items'][$item->getId()]['menus'][$htMenu->getId()]['menu']['escandallos'][] = $escan;
$allHtEscandallos[] = $escan;
$data['items'][$item->getId()]['menus'][$htMenu->getId()]['menu']['escandallos_names'] = (empty($data['items'][$item->getId()]['menus'][$htMenu->getId()]['menu']['escandallos_names'])) ? ($escan->getNombre()) : ($data['items'][$item->getId()]['menus'][$htMenu->getId()]['menu']['escandallos_names'] . ', ' . $escan->getNombre());
}
}
}
}
}
$data['company'] = $em->getRepository(SettingsCompany::class)->findOneByPriority('5');
$data['client'] = $supplier;
$data_iva = array();
$data_iva['ivaMontoVeintiUno'] = 0;
$data_iva['ivaMontoDiez'] = 0;
$data_iva['ivaMontoCero'] = 0;
$netoSum = 0; $totalSum = 0;
$indiceBeneficio = -1;
if (array_key_exists("items", $data)) {
foreach ($data['items'] as $itemFac) {
if (array_key_exists("menus", $itemFac)) {
$indiceBeneficio++;
foreach ($itemFac['menus'] as $htMenu) {
$productName = $htMenu['menu']['menu_info']->getName() . ' ( ' . $htMenu['menu']['escandallos_names'] . ' )';
$servicePrice = (($htMenu['menu']['menu_info']->getTotalPrice() * 100) / (100 + $htMenu['menu']['menu_info']->getIva()));
$subTotalPrice = round((($htMenu['menu']['menu_info']->getTotalPrice() * 100) / (100 + $htMenu['menu']['menu_info']->getIva())), 2) * $itemFac['item']->getPax();
$subtotalProduct = $subTotalPrice * (1 + ($htMenu['menu']['menu_info']->getIva() / 100));
$ivaAmount = ($htMenu['menu']['menu_info']->getIva() * $subTotalPrice) / 100;
$htMenuIsInvoiced = $em->getRepository(HtInvoiceItems::class)->findBy(array('itemType' => 'htMenu', 'itemIdOrigin' => $htMenu['menu']['menu_info']->getId()));
$boolIsInvoiced = ((count($htMenuIsInvoiced)) % 2 == 0) ? false : true;
if (!$boolIsInvoiced) {
$netoSum += $subTotalPrice;
$totalSum += $subtotalProduct;
switch ($htMenu['menu']['menu_info']->getIva()) {
case 10: $data_iva['ivaMontoDiez'] += $ivaAmount; break;
case 21: $data_iva['ivaMontoVeintiUno'] += $ivaAmount; break;
default: break;
}
}
$data['product'][] = array(
'id' => $htMenu['menu']['menu_info']->getId(), // Id del Menu
'idHtItem' => $itemFac['item']->getId(), // Id del Servicio (HtItem) que contiene el Menu
'enabledToInvoice' => !$boolIsInvoiced,
'productName' => $productName,
'type' => null,
'servicePrice' => $servicePrice,
'qty' => $itemFac['item']->getPax(),
'days' => $itemFac['item']->getDateStart()->format('d/m/Y'),
'subTotalPrice' => ($boolIsInvoiced) ? 0 : $subTotalPrice,
'iva' => $htMenu['menu']['menu_info']->getIva(),
'ivaAmount' => $ivaAmount,
'subtotalProduct' => ($boolIsInvoiced) ? 0 : $subtotalProduct,
// 'beneficio' => $beneficio[$indiceBeneficio],
'beneficio' => $dataBen['htItem'][$itemFac['item']->getId()]['precioNeto'] - $dataBen['htItem'][$itemFac['item']->getId()]['coste'], // Se lleva al 100% antes de impuestos ya que es factura de comision
);
}
}
}
}
$netoAllSum = $netoSum;
$totalSumItems = $totalSum;
// SERVICIOS ADICIONALES
$data_extras = array();
if (!empty($allHtExtrasinFile)){ $data_extras['allHtExtrasinFile'] = $allHtExtrasinFile; }
$data_extras_sum = array('extra_price_no_vat' => 0, 'extra_price' => 0,);
foreach ($allHtExtrasinFile as $item){
$data_extras_sum['extra_price_no_vat'] += $item['extra_price_no_vat'];
$data_extras_sum['extra_price'] += $item['extra_price'];
$montoIva = $item['extra_price'] - $item['extra_price_no_vat'];
switch ($item['extra']->getVat()) {
case 10: $data_iva['ivaMontoDiez'] += $montoIva; break;
case 21: $data_iva['ivaMontoVeintiUno'] += $montoIva; break;
default: break;
}
$netoAllSum += $item['extra_price_no_vat'];
$totalSum += $item['extra_price'];
}
$clientType = 'supplier';
$clientAddress = (array_key_exists("client", $data) and !empty($data['client'])) ? $data['client']->getAddress() : 'No se ha podido determinar la dirección';
$country = (array_key_exists("client", $data) and !empty($data['client'])) ? $em->getRepository(Country::class)->findOneById($data['client']->getCountry()) : $em->getRepository(Country::class)->findOneById(62);
$country = $country->getCountry();
if ($country == 'Spain'){ $country = 'España'; }
$clientAddress = $clientAddress . ', '. $country;
$clientDocument = $data['client']->getIdDocument();
return $this->render('higotrigo/ht_invoice/invoice-select-items.html.twig',
array(
'id' => $htFile->getId(),
'htFile' => $htFile,
'prefix' => null,
'date' => null,
'company' => $data['company'],
'clientAddress' => $clientAddress,
'clientDocument' => $clientDocument,
'clientType' => $clientType,
'client' => $data['client'],
'clients' => null,
'datasupplier' => $data,
'data_extras' => $data_extras,
'data_extras_sum' => $data_extras_sum,
'currency' => '€',
'totales_coniva_items' => $totalSumItems,
'totales_coniva' => $totalSum,
'totales_neto_items' => $netoSum,
'totales_neto' => $netoAllSum,
'bases_imponibles' => $data_iva,
)
);
}
/**
* @Route("/createinvoice/{id}", name="ht_create_invoice")
* Generar factura en el expediente ID
*/
public function createInvoiceHtAction($id, EntityManagerInterface $em, Request $request)
{
$req = $request->request->get('invoiced_item');
$req_extra = $request->request->get('invoiced_extra');
$htFile = $em->getRepository(HtFile::class)->findOneById($id);
$beneficio_total = 0;
// El break es necesario ya que el beneficio fue concebido para ser por servicios, luego con el cambio de multi menus en un servicio se debe sumar solamente una vez
foreach ($req as $itemServ){
foreach ($itemServ as $item) {
if ($item['boolToInvoice'] == 'true') { $beneficio_total += $item['benefit']; break; }
}
}
$boolSeleccionados = false;
// Si no hay elemento seleccionados se vuelve a la pantalla de seleccion
if ($boolSeleccionados){ return $this->redirectToRoute('ht_select_invoice', ['id' => $htFile->getId()], Response::HTTP_SEE_OTHER); }
// Se genera la factura
// buscamos por el prefijo de cada linea de facturacion para saber el ultimo ID
$invoiceLineGp = $em->getRepository(HtInvoice::class)->findByPrefix('GP');
$invoiceLineCvr = $em->getRepository(HtInvoice::class)->findByPrefix('CV');
$invoiceLineOther = $em->getRepository(HtInvoice::class)->findByPrefix('F');
$lastGp = end($invoiceLineGp);
$lastCvr = end($invoiceLineCvr);
$lastOther = end($invoiceLineOther);
// Buscamos los HtIemts del HtFile para saber la sala del servicio para determinar la línea de facturación ($prefix)
$htItems = $em->getRepository(HtItem::class)->findByHtFile($htFile);
$lounge = $htItems[0]->getLoungeGp();
$prefix = (empty($lounge) ? 'F' : (($lounge->getId() < 22) ? 'GP' : 'CV'));
switch ($prefix) {
case 'F': $idNum = (empty($lastOther)) ? 1 : $lastOther->getIdNum() + 1; break;
case 'CV': $idNum = (empty($lastCvr)) ? 1 : $lastCvr->getIdNum() + 1; break;
default:
// Por defecto Green Patio.
// Esteban Rincon comenta que en caso de un expediente tener salas de GP y CVR deberiamos tener un expediente por linea de facturación
$idNum = (empty($lastGp)) ? 1 : $lastGp->getIdNum() + 1;
break;
}
$client = (empty($htFile->getClient())) ? null : $htFile->getClient();
// Si no hay cliente no se puede facturar, se vuelve a la pantalla de seleccion
if (empty($client)){ return $this->redirectToRoute('ht_select_invoice', ['id' => $htFile->getId()], Response::HTTP_SEE_OTHER); }
$dateAt = new DateTimeImmutable('now');
$type = 'Invoice';
$totalNet = 0; $vatTotalGroup = 0; $total = 0;
$clientName = $client->getName();
$clientAddress = $request->request->get('clientAddress');
$clientDocument = empty($client->getIdDocument()) ? ' ' : $client->getIdDocument();
$clientType = $request->request->get('clientType');
if ($clientType == 'supplier'){
$type = 'commission invoice';
$clientName = $request->request->get('clientName');
$clientDocument = $request->request->get('clientDocument');
}
$invoice = new HtInvoice();
$invoice->setIdNum($idNum);
$invoice->setPrefix($prefix);
$invoice->setDateAt($dateAt);
$invoice->setType($type);
$invoice->setTotalNet($totalNet);
$invoice->setVatTotalGroup($vatTotalGroup);
$invoice->setTotal($total);
$invoice->setClientName($clientName);
$invoice->setClientAddress($clientAddress);
$invoice->setClientDocument($clientDocument);
$invoice->setClientType($clientType);
$invoice->setHtFile($htFile);
$invoice->setBenefit($beneficio_total);
$em->persist($invoice);
$em->flush();
$data_iva = array(); $data_iva['ivaMontoVeintiUno'] = 0; $data_iva['ivaMontoDiez'] = 0;
// Se crean los Menus en los HtInvoiceItems
foreach ($req as $itemServ){
foreach ($itemServ as $item) {
if ($item['boolToInvoice'] == 'true') {
$htMenu = $em->getRepository(HtMenu::class)->findOneByHtItem($item['idHtService']);
$itemType = 'htMenu';
$itemIdOrigin = $htMenu->getId();
$itemName = $item['name'];
$htItem = $em->getRepository(HtItem::class)->findOneById($htMenu->getHtItem());
$dateStart = ($htItem->getDateStart())->format('Y-m-d');
$hourEnd = ($htItem->getHourEnd())->format('Y-m-d');
$dateTimeString = $dateStart . ' ' . $hourEnd;
$dateEnd = new DateTimeImmutable($dateTimeString);
$iva = $htMenu->getIva();
switch ($iva) {
case 10: $data_iva['ivaMontoDiez'] += ($item['subTotalPrice'] * 0.1); break;
case 21: $data_iva['ivaMontoVeintiUno'] += ($item['subTotalPrice'] * 0.21); break;
default: break;
}
$itemCommission = 0; // Solo htExtra maneja el concepto de over o comision.
$itemOver = 0; // Solo htExtra maneja el concepto de over o comision.
$costeDirecto = $item['subTotalPrice'] - $item['benefit'];
$totalNet += round($item['subTotalPrice'], 2);
$total += round($item['subTotalPrice'], 2) + (round($item['subTotalPrice'], 2) * ($iva / 100));
$xPax = empty($item['qty']) ? 1 : $item['qty'];
$htInvItem = new HtInvoiceItems();
$htInvItem->setInvoice($invoice);
$htInvItem->setHtFile($htFile);
$htInvItem->setItemType($itemType);
$htInvItem->setItemIdOrigin($itemIdOrigin);
$htInvItem->setItemName($itemName);
$htInvItem->setItemDateStart($htItem->getDateStart());
$htInvItem->setItemDateEnd($dateEnd);
$htInvItem->setItemPrice(round($item['servicePrice'], 2));
$htInvItem->setItemUnits(1);
$htInvItem->setItemPax($xPax);
$htInvItem->setItemKgLt(1);
$htInvItem->setItemRank(1);
$htInvItem->setItemLocation(0);
$htInvItem->setItemIva($iva);
$htInvItem->setItemOpIva(0); // +
$htInvItem->setItemCommission($itemCommission);
$htInvItem->setItemOpCommission(0);
$htInvItem->setItemOver($itemOver);
$htInvItem->setItemOpOver(0);
$htInvItem->setItemSubTotalPrice(round($item['subTotalPrice'], 2));
$htInvItem->setItemCosteDirecto(round($costeDirecto, 2));
$htInvItem->setItemBeneficio(round($item['benefit'], 2));
$em->persist($htInvItem);
$em->flush();
}
}
}
// Se crean los Extras en los HtInvoiceItems
if (!empty($req_extra)) {
foreach ($req_extra as $item) {
if($item['boolToInvoice'] == 'true') {
$htExtra = $em->getRepository(HtExtra::class)->findOneById($item['idHtExtra']);
if ($htExtra->isAppearInvoice()) {
$itemType = 'htExtra';
$itemIdOrigin = $htExtra->getId();
$itemName = $htExtra->getConcept();
$htItem = $em->getRepository(HtItem::class)->findOneById($htExtra->getHtItem());
$dateStart = ($htItem->getDateStart())->format('Y-m-d');
$hourEnd = ($htItem->getHourEnd())->format('Y-m-d');
$dateTimeString = $dateStart . ' ' . $hourEnd;
$dateEnd = new DateTimeImmutable($dateTimeString);
$iva = $htExtra->getVat();
$itemCommission = (($htExtra->isOpOverCommission() == 0) ? 0 : $htExtra->getOverCommission());
$itemOver = (($htExtra->isOpOverCommission() == 1) ? 0 : $htExtra->getOverCommission());
$costeDirecto = 0;
$benefit = $itemOver + ($item['price'] * ($itemCommission / 100));
$totalPrice = $item['price'] + $benefit;
switch ($iva) {
case 10: $data_iva['ivaMontoDiez'] += ($totalPrice * 0.1); break;
case 21: $data_iva['ivaMontoVeintiUno'] += ($totalPrice * 0.21); break;
default: break;
}
$totalNet += round($totalPrice, 2);
$total += round($totalPrice, 2) + (round($totalPrice, 2) * ($iva / 100));
$htInvItem = new HtInvoiceItems();
$htInvItem->setInvoice($invoice);
$htInvItem->setHtFile($htFile);
$htInvItem->setItemType($itemType);
$htInvItem->setItemIdOrigin($itemIdOrigin);
$htInvItem->setItemName($itemName);
$htInvItem->setItemDateStart($htItem->getDateStart());
$htInvItem->setItemDateEnd($dateEnd);
$htInvItem->setItemPrice(round($item['price'], 2));
$htInvItem->setItemUnits(1);
$htInvItem->setItemPax(1);
$htInvItem->setItemKgLt(1);
$htInvItem->setItemRank(1);
$htInvItem->setItemLocation(0);
$htInvItem->setItemIva($iva);
$htInvItem->setItemOpIva(0); // +
$htInvItem->setItemCommission($itemCommission);
$htInvItem->setItemOpCommission(0);
$htInvItem->setItemOver($itemOver);
$htInvItem->setItemOpOver(0);
$htInvItem->setItemSubTotalPrice(round($totalPrice, 2));
$htInvItem->setItemCosteDirecto(round($costeDirecto, 2));
$htInvItem->setItemBeneficio(round($benefit, 2));
$em->persist($htInvItem);
$em->flush();
}
}
}
}
$string_data_iva = '[21]'.round($data_iva['ivaMontoVeintiUno'],2).'[21]'.'[10]'.round($data_iva['ivaMontoDiez'],2).'[10]';
// Se actualiza la factura con los datos globales
$invoice->setTotalNet($totalNet);
$invoice->setVatTotalGroup($string_data_iva);
$invoice->setTotal(round($total,2));
$em->persist($invoice);
$em->flush();
return $this->redirectToRoute('ht_view_invoice', ['id' => $invoice->getPrefix(). $invoice->getIdNum()], Response::HTTP_SEE_OTHER);
}
/**
* @Route("/viewinvoice/{id}", name="ht_view_invoice")
* Ver la factura con el ID
*/
public function showInvoiceHtAction($id, EntityManagerInterface $em, Request $request)
{
$idNum = (substr($id, 0, 1) == 'F') ? substr($id, 1) : substr($id, 2); // F1, GP1, CV1
$prefix = (substr($id, 0, 1) == 'F') ? 'F' : substr($id, 0, 2);
$user = $this->getUser();
$parameters = array( 'idNum' => $idNum, 'prefix' => $prefix, );
$dql = 'SELECT p
FROM App\Entity\HtInvoice p
WHERE p.idNum = :idNum AND p.prefix = :prefix';
$query = $em->createQuery($dql)->setParameters($parameters);
$invoice = $query->getResult();
$invoice = (!empty($invoice)) ? $invoice[0] : null;
// $id = $invoice->getPrefix() . $invoice->getIdNum();
// Si no consigue la factura redirige al listado de expedientes
if (empty($invoice)){ return $this->redirectToRoute('app_ht_file_index', [], Response::HTTP_SEE_OTHER); }
$datAt = (!empty($invoice)) ? $invoice->getDateAt() : null;
$totales_neto = (!empty($invoice)) ? $invoice->getTotalNet() : 0;
$totales_iva = (!empty($invoice)) ? $invoice->getVatTotalGroup() : 0;
$totales = (!empty($invoice)) ? $invoice->getTotal() : 0;
$htInvoiceItems = $em->getRepository(HtInvoiceItems::class)->findByInvoice($invoice);
$htFile = $em->getRepository(HtFile::class)->findOneById(($invoice->getHtFile())->getId());
$clientName = (!empty($invoice)) ? $invoice->getClientName() : 'No se pudo determinar el cliente';
$clientAddress = (!empty($invoice)) ? $invoice->getClientAddress() : 'No se pudo determinar la dirección';
$clientDocument = (!empty($invoice)) ? $invoice->getClientDocument() : 'No se pudo determinar';
$type = $invoice->getType();
$company = $em->getRepository(SettingsCompany::class)->findOneByPriority('5');
$bases_imponibles = array('21'=> 0,'10'=> 0,'0'=> 0,);
$datasupplier = array(); $netoSumItems = 0; $totalSumItems = 0;
$data_iva = array('ivaMontoDiez' => 0, 'ivaMontoVeintiUno' => 0);
$datasupplier['invoice_item_net_sum'] = 0; $datasupplier['invoice_item_sum'] = 0;
$datasupplier['invoice_extra_net_sum'] = 0; $datasupplier['invoice_extra_sum'] = 0;
foreach ($htInvoiceItems as $key => $item){
if ($item->getItemType()=='htMenu') {
$datasupplier['invoice_item'][] = array(
'id' => $item->getId(),
'itemName' => $item->getItemName(),
'itemPrice' => $item->getItemPrice(),
'itemPax' => $item->getItemPax(),
'itemDateStart' => $item->getItemDateStart(),
'itemDateEnd' => $item->getItemDateEnd(),
'itemIva' => $item->getItemIva(),
'itemSubTotalPrice' => round($item->getItemSubTotalPrice() * (1 + ($item->getItemIva()/100)),2),
);
$netoSumItems += $item->getItemSubTotalPrice();
$datasupplier['invoice_item_net_sum'] += $item->getItemSubTotalPrice();
$datasupplier['invoice_item_sum'] += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$totalSumItems += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$montoIva = $item->getItemSubTotalPrice() * ($item->getItemIva() / 100);
switch ($item->getItemIva()) {
case 10: $data_iva['ivaMontoDiez'] += $montoIva; break;
case 21: $data_iva['ivaMontoVeintiUno'] += $montoIva; break;
default: break;
}
}
if ($item->getItemType()=='htExtra') {
$datasupplier['invoice_extra'][] = array(
'id' => $item->getId(),
'itemType' => $item->getItemType(),
'itemIdOrigin' => $item->getItemIdOrigin(),
'itemName' => $item->getItemName(),
'itemPrice' => $item->getItemSubTotalPrice(),
'itemPax' => $item->getItemPax(),
'itemDateStart' => $item->getItemDateStart(),
'itemDateEnd' => $item->getItemDateEnd(),
'itemIva' => $item->getItemIva(),
'itemSubTotalPrice' => round($item->getItemSubTotalPrice() * (1 + ($item->getItemIva()/100)),2),
);
$netoSumItems += $item->getItemSubTotalPrice();
$datasupplier['invoice_extra_net_sum'] += $item->getItemSubTotalPrice();
$datasupplier['invoice_extra_sum'] += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$totalSumItems += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$montoIva = $item->getItemSubTotalPrice() * ($item->getItemIva() / 100);
switch ($item->getItemIva()) {
case 10: $data_iva['ivaMontoDiez'] += $montoIva; break;
case 21: $data_iva['ivaMontoVeintiUno'] += $montoIva; break;
default: break;
}
}
}
$allInvoices = $em->getRepository(HtInvoice::class)->findByHtFile($htFile);
$invoiceRec = $em->getRepository(HtInvoice::class)->findByInvoiceToRec($id);
$boolToRec = ($invoice->getType() == 'Invoice Rec') ? false : empty($invoiceRec);
return $this->render('higotrigo/ht_invoice/show-invoice.html.twig',
array(
'id' => $htFile->getId(),
'cid' => '',
'fid' => $id,
'invoice' => $invoice,
'allInvoices' => $allInvoices,
'proformas' => null,
'numberadmin' => '',
'type' => $type,
'number' => $id,
'prefix' => $prefix,
'date' => $datAt,
'reservation' => $htFile,
'company' => $company,
'user' => $user,
'boolToRec' => $boolToRec,
'invoicedeposititems' => '',
'datasupplier' => $datasupplier,
'totales_neto' => $netoSumItems,
'totales_iva' => $totales_iva,
'totales' => $totalSumItems,
'bases_imponibles' => $data_iva,
'paymentInvoice' => null,
'currency' => '€',
'clientName' => $clientName,
'clientAddress' => $clientAddress,
'clientDocument' => $clientDocument,
)
);
}
/**
* @Route("/viewinvoicerec/{id}", name="ht_view_invoice_rec")
* Ver la factura rectificativa con el ID
*/
public function showInvoiceRecHtAction($id, EntityManagerInterface $em, Request $request)
{
$idNum = (substr($id, 0, 2) == 'RF') ? substr($id, 2) : substr($id, 3); // RF1, RGP1, RCV1
$prefix = (substr($id, 0, 2) == 'RF') ? 'RF' : substr($id, 0, 3);
$user = $this->getUser();
$parameters = array( 'idNum' => $idNum, 'prefix' => $prefix, );
$dql = 'SELECT p
FROM App\Entity\HtInvoice p
WHERE p.idNum = :idNum AND p.prefix = :prefix';
$query = $em->createQuery($dql)->setParameters($parameters);
$invoice = $query->getResult();
$invoice = (!empty($invoice)) ? $invoice[0] : null;
// Si no consigue la factura redirige al listado de expedientes
if (empty($invoice)){ return $this->redirectToRoute('app_ht_file_index', [], Response::HTTP_SEE_OTHER); }
$datAt = (!empty($invoice)) ? $invoice->getDateAt() : null;
$totales_neto = (!empty($invoice)) ? $invoice->getTotalNet() : 0;
$totales_iva = (!empty($invoice)) ? $invoice->getVatTotalGroup() : 0;
$totales = (!empty($invoice)) ? $invoice->getTotal() : 0;
$htInvoiceItems = $em->getRepository(HtInvoiceItems::class)->findByInvoice($invoice);
$htFile = $em->getRepository(HtFile::class)->findOneById(($invoice->getHtFile())->getId());
$clientName = (!empty($invoice)) ? $invoice->getClientName() : 'No se pudo determinar el cliente';
$clientAddress = (!empty($invoice)) ? $invoice->getClientAddress() : 'No se pudo determinar la dirección';
$clientDocument = (!empty($invoice)) ? $invoice->getClientDocument() : 'No se pudo determinar';
$type = $invoice->getType();
$company = $em->getRepository(SettingsCompany::class)->findOneByPriority('5');
$bases_imponibles = array('21'=> 0,'10'=> 0,'0'=> 0,);
$datasupplier = array(); $netoSumItems = 0; $totalSumItems = 0;
$data_iva = array('ivaMontoDiez' => 0, 'ivaMontoVeintiUno' => 0);
$datasupplier['invoice_item_net_sum'] = 0; $datasupplier['invoice_item_sum'] = 0;
$datasupplier['invoice_extra_net_sum'] = 0; $datasupplier['invoice_extra_sum'] = 0;
foreach ($htInvoiceItems as $key => $item){
if ($item->getItemType()=='htMenu') {
$datasupplier['invoice_item'][] = $item;
$netoSumItems += $item->getItemSubTotalPrice();
$datasupplier['invoice_item_net_sum'] += $item->getItemSubTotalPrice();
$datasupplier['invoice_item_sum'] += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$totalSumItems += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$montoIva = $item->getItemSubTotalPrice() * ($item->getItemIva() / 100);
switch ($item->getItemIva()) {
case 10: $data_iva['ivaMontoDiez'] += $montoIva; break;
case 21: $data_iva['ivaMontoVeintiUno'] += $montoIva; break;
default: break;
}
}
if ($item->getItemType()=='htExtra') {
// $datasupplier['invoice_extra'][] = $item;
$datasupplier['invoice_extra'][] = array(
'id' => $item->getId(),
'itemType' => $item->getItemType(),
'itemIdOrigin' => $item->getItemIdOrigin(),
'itemName' => $item->getItemName(),
'itemPrice' => $item->getItemSubTotalPrice(),
'itemPax' => $item->getItemPax(),
'itemDateStart' => $item->getItemDateStart(),
'itemDateEnd' => $item->getItemDateEnd(),
'itemIva' => $item->getItemIva(),
'itemSubTotalPrice' => round($item->getItemSubTotalPrice() * (1 + ($item->getItemIva()/100)),2),
);
$netoSumItems += $item->getItemSubTotalPrice();
$datasupplier['invoice_extra_net_sum'] += $item->getItemSubTotalPrice();
$datasupplier['invoice_extra_sum'] += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$totalSumItems += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$montoIva = $item->getItemSubTotalPrice() * ($item->getItemIva() / 100);
switch ($item->getItemIva()) {
case 10: $data_iva['ivaMontoDiez'] += $montoIva; break;
case 21: $data_iva['ivaMontoVeintiUno'] += $montoIva; break;
default: break;
}
}
}
$allInvoices = $em->getRepository(HtInvoice::class)->findByHtFile($htFile);
return $this->render('higotrigo/ht_invoice/show-invoice.html.twig',
array(
'id' => $htFile->getId(),
'cid' => '',
'fid' => $id,
'invoice' => $invoice,
'invoiceIdToRec' => $invoice->getInvoiceToRec(),
'allInvoices' => $allInvoices,
'proformas' => null,
'boolToRec' => false,
'numberadmin' => '',
'type' => $type,
'number' => $id,
'prefix' => $prefix,
'date' => $datAt,
'reservation' => $htFile,
'company' => $company,
'user' => $user,
'invoicedeposititems' => '',
'datasupplier' => $datasupplier,
'totales_neto' => $netoSumItems,
'totales_iva' => $totales_iva,
'totales' => $totalSumItems,
'bases_imponibles' => $data_iva,
'paymentInvoice' => null,
'currency' => '€',
'clientName' => $clientName,
'clientAddress' => $clientAddress,
'clientDocument' => $clientDocument,
)
);
}
/**
* @Route("/htexternal/viewprintinvoice/{id}", name="ht_view_print_invoice")
* Ver la factura con el ID en modalidad de impresion
*/
public function printInvoiceHtAction($id, EntityManagerInterface $em, Request $request)
{
$idNum = (substr($id, 0, 1) == 'F') ? substr($id, 1) : substr($id, 2); // F1, GP1, CV1
$prefix = (substr($id, 0, 1) == 'F') ? 'F' : substr($id, 0, 2);
$user = $this->getUser();
$parameters = array( 'idNum' => $idNum, 'prefix' => $prefix, );
$dql = 'SELECT p
FROM App\Entity\HtInvoice p
WHERE p.idNum = :idNum AND p.prefix = :prefix';
$query = $em->createQuery($dql)->setParameters($parameters);
$invoice = $query->getResult();
$invoice = (!empty($invoice)) ? $invoice[0] : null;
// Si no consigue la factura redirige al listado de expedientes
if (empty($invoice)){ return $this->redirectToRoute('app_ht_file_index', [], Response::HTTP_SEE_OTHER); }
$datAt = (!empty($invoice)) ? $invoice->getDateAt() : null;
$totales_neto = (!empty($invoice)) ? $invoice->getTotalNet() : 0;
$totales_iva = (!empty($invoice)) ? $invoice->getVatTotalGroup() : 0;
$totales = (!empty($invoice)) ? $invoice->getTotal() : 0;
$htInvoiceItems = $em->getRepository(HtInvoiceItems::class)->findByInvoice($invoice);
$htFile = $em->getRepository(HtFile::class)->findOneById(($invoice->getHtFile())->getId());
$clientName = (!empty($invoice)) ? $invoice->getClientName() : 'No se pudo determinar el cliente';
$clientAddress = (!empty($invoice)) ? $invoice->getClientAddress() : 'No se pudo determinar la dirección';
$clientDocument = (!empty($invoice)) ? $invoice->getClientDocument() : 'No se pudo determinar';
$type = $invoice->getType();
$company = $em->getRepository(SettingsCompany::class)->findOneByPriority('5');
$bases_imponibles = array('21'=> 0,'10'=> 0,'0'=> 0,);
$datasupplier = array(); $netoSumItems = 0; $totalSumItems = 0;
$data_iva = array('ivaMontoDiez' => 0, 'ivaMontoVeintiUno' => 0);
$datasupplier['invoice_item_net_sum'] = 0; $datasupplier['invoice_item_sum'] = 0;
$datasupplier['invoice_extra_net_sum'] = 0; $datasupplier['invoice_extra_sum'] = 0;
foreach ($htInvoiceItems as $key => $item){
if ($item->getItemType()=='htMenu') {
$datasupplier['invoice_item'][] = array(
'id' => $item->getId(),
'itemName' => $item->getItemName(),
'itemPrice' => $item->getItemPrice(),
'itemPax' => $item->getItemPax(),
'itemDateStart' => $item->getItemDateStart(),
'itemDateEnd' => $item->getItemDateEnd(),
'itemIva' => $item->getItemIva(),
'itemSubTotalPrice' => round($item->getItemSubTotalPrice() * (1 + ($item->getItemIva()/100)),2),
);
$netoSumItems += $item->getItemSubTotalPrice();
$datasupplier['invoice_item_net_sum'] += $item->getItemSubTotalPrice();
$datasupplier['invoice_item_sum'] += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$totalSumItems += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$montoIva = $item->getItemSubTotalPrice() * ($item->getItemIva() / 100);
switch ($item->getItemIva()) {
case 10: $data_iva['ivaMontoDiez'] += $montoIva; break;
case 21: $data_iva['ivaMontoVeintiUno'] += $montoIva; break;
default: break;
}
}
if ($item->getItemType()=='htExtra') {
// $datasupplier['invoice_extra'][] = $item;
$datasupplier['invoice_extra'][] = array(
'id' => $item->getId(),
'itemType' => $item->getItemType(),
'itemIdOrigin' => $item->getItemIdOrigin(),
'itemName' => $item->getItemName(),
'itemPrice' => $item->getItemSubTotalPrice(),
'itemPax' => $item->getItemPax(),
'itemDateStart' => $item->getItemDateStart(),
'itemDateEnd' => $item->getItemDateEnd(),
'itemIva' => $item->getItemIva(),
'itemSubTotalPrice' => round($item->getItemSubTotalPrice() * (1 + ($item->getItemIva()/100)),2),
);
$netoSumItems += $item->getItemSubTotalPrice();
$datasupplier['invoice_extra_net_sum'] += $item->getItemSubTotalPrice();
$datasupplier['invoice_extra_sum'] += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$totalSumItems += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$montoIva = $item->getItemSubTotalPrice() * ($item->getItemIva() / 100);
switch ($item->getItemIva()) {
case 10: $data_iva['ivaMontoDiez'] += $montoIva; break;
case 21: $data_iva['ivaMontoVeintiUno'] += $montoIva; break;
default: break;
}
}
}
return $this->render('higotrigo/ht_invoice/invoice-print.html.twig',
array(
'id' => $htFile->getId(),
'cid' => '',
'fid' => $id,
'invoice' => $invoice,
'proformas' => null,
'boolToRec' => true,
'numberadmin' => '',
'type' => $type,
'number' => $id,
'prefix' => $prefix,
'date' => $datAt,
'reservation' => $htFile,
'company' => $company,
'user' => $user,
'invoicedeposititems' => '',
'datasupplier' => $datasupplier,
'totales_neto' => $netoSumItems,
'totales_iva' => $totales_iva,
'totales' => $totalSumItems,
'bases_imponibles' => $data_iva,
'paymentInvoice' => null,
'currency' => '€',
'clientName' => $clientName,
'clientAddress' => $clientAddress,
'clientDocument' => $clientDocument,
)
);
}
/**
* @Route("/htexternal/viewprintinvoicerec/{id}", name="ht_view_print_invoicerec")
* Ver la factura rectificativa con el ID en modalidad de impresion
*/
public function printInvoiceRecHtAction($id, EntityManagerInterface $em, Request $request)
{
$idNum = (substr($id, 0, 2) == 'RF') ? substr($id, 2) : substr($id, 3); // RF1, RGP1, RCV1
$prefix = (substr($id, 0, 2) == 'RF') ? 'RF' : substr($id, 0, 3);
$user = $this->getUser();
$parameters = array( 'idNum' => $idNum, 'prefix' => $prefix, );
$dql = 'SELECT p
FROM App\Entity\HtInvoice p
WHERE p.idNum = :idNum AND p.prefix = :prefix';
$query = $em->createQuery($dql)->setParameters($parameters);
$invoice = $query->getResult();
$invoice = (!empty($invoice)) ? $invoice[0] : null;
// Si no consigue la factura redirige al listado de expedientes
if (empty($invoice)){ return $this->redirectToRoute('app_ht_file_index', [], Response::HTTP_SEE_OTHER); }
$datAt = (!empty($invoice)) ? $invoice->getDateAt() : null;
$totales_neto = (!empty($invoice)) ? $invoice->getTotalNet() : 0;
$totales_iva = (!empty($invoice)) ? $invoice->getVatTotalGroup() : 0;
$totales = (!empty($invoice)) ? $invoice->getTotal() : 0;
$htInvoiceItems = $em->getRepository(HtInvoiceItems::class)->findByInvoice($invoice);
$htFile = $em->getRepository(HtFile::class)->findOneById(($invoice->getHtFile())->getId());
$clientName = (!empty($invoice)) ? $invoice->getClientName() : 'No se pudo determinar el cliente';
$clientAddress = (!empty($invoice)) ? $invoice->getClientAddress() : 'No se pudo determinar la dirección';
$clientDocument = (!empty($invoice)) ? $invoice->getClientDocument() : 'No se pudo determinar';
$type = $invoice->getType();
$company = $em->getRepository(SettingsCompany::class)->findOneByPriority('5');
$invoiceIdToRec = $invoice->getInvoiceToRec();
$bases_imponibles = array('21'=> 0,'10'=> 0,'0'=> 0,);
$datasupplier = array(); $netoSumItems = 0; $totalSumItems = 0;
$data_iva = array('ivaMontoDiez' => 0, 'ivaMontoVeintiUno' => 0);
$datasupplier['invoice_item_net_sum'] = 0; $datasupplier['invoice_item_sum'] = 0;
$datasupplier['invoice_extra_net_sum'] = 0; $datasupplier['invoice_extra_sum'] = 0;
foreach ($htInvoiceItems as $key => $item){
if ($item->getItemType()=='htMenu') {
$datasupplier['invoice_item'][] = array(
'id' => $item->getId(),
'itemName' => $item->getItemName(),
'itemPrice' => $item->getItemPrice(),
'itemPax' => $item->getItemPax(),
'itemDateStart' => $item->getItemDateStart(),
'itemDateEnd' => $item->getItemDateEnd(),
'itemIva' => $item->getItemIva(),
'itemSubTotalPrice' => round($item->getItemSubTotalPrice() * (1 + ($item->getItemIva()/100)),2),
);
$netoSumItems += $item->getItemSubTotalPrice();
$datasupplier['invoice_item_net_sum'] += $item->getItemSubTotalPrice();
$datasupplier['invoice_item_sum'] += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$totalSumItems += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$montoIva = $item->getItemSubTotalPrice() * ($item->getItemIva() / 100);
switch ($item->getItemIva()) {
case 10: $data_iva['ivaMontoDiez'] += $montoIva; break;
case 21: $data_iva['ivaMontoVeintiUno'] += $montoIva; break;
default: break;
}
}
if ($item->getItemType()=='htExtra') {
// $datasupplier['invoice_extra'][] = $item;
$datasupplier['invoice_extra'][] = array(
'id' => $item->getId(),
'itemType' => $item->getItemType(),
'itemIdOrigin' => $item->getItemIdOrigin(),
'itemName' => $item->getItemName(),
'itemPrice' => $item->getItemSubTotalPrice(),
'itemPax' => $item->getItemPax(),
'itemDateStart' => $item->getItemDateStart(),
'itemDateEnd' => $item->getItemDateEnd(),
'itemIva' => $item->getItemIva(),
'itemSubTotalPrice' => round($item->getItemSubTotalPrice() * (1 + ($item->getItemIva()/100)),2),
);
$netoSumItems += $item->getItemSubTotalPrice();
$datasupplier['invoice_extra_net_sum'] += $item->getItemSubTotalPrice();
$datasupplier['invoice_extra_sum'] += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$totalSumItems += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$montoIva = $item->getItemSubTotalPrice() * ($item->getItemIva() / 100);
switch ($item->getItemIva()) {
case 10: $data_iva['ivaMontoDiez'] += $montoIva; break;
case 21: $data_iva['ivaMontoVeintiUno'] += $montoIva; break;
default: break;
}
}
}
return $this->render('higotrigo/ht_invoice/invoice-print.html.twig',
array(
'id' => $htFile->getId(),
'cid' => '',
'fid' => $id,
'invoice' => $invoice,
'proformas' => null,
'boolToRec' => true,
'numberadmin' => '',
'type' => $type,
'number' => $id,
'prefix' => $prefix,
'date' => $datAt,
'reservation' => $htFile,
'company' => $company,
'user' => $user,
'invoicedeposititems' => '',
'datasupplier' => $datasupplier,
'totales_neto' => $netoSumItems,
'totales_iva' => $totales_iva,
'totales' => $totalSumItems,
'bases_imponibles' => $data_iva,
'paymentInvoice' => null,
'currency' => '€',
'clientName' => $clientName,
'clientAddress' => $clientAddress,
'clientDocument' => $clientDocument,
'invoiceIdToRec' => $invoiceIdToRec,
)
);
}
/**
* @Route("/createrecinvoice/{id}", name="ht_create_rec_invoice")
* Generar factura rectificativa de la factura ID
*/
public function createRecInvoiceHtAction($id, EntityManagerInterface $em, Request $request)
{
$idNum = (substr($id, 0, 1) == 'F') ? substr($id, 1) : substr($id, 2); // F1, GP1, CV1
$prefix = (substr($id, 0, 1) == 'F') ? 'F' : substr($id, 0, 2);
$parameters = array( 'idNum' => $idNum, 'prefix' => $prefix, );
$dql = 'SELECT p
FROM App\Entity\HtInvoice p
WHERE p.idNum = :idNum AND p.prefix = :prefix';
$query = $em->createQuery($dql)->setParameters($parameters);
$invoice = $query->getResult();
$invoice = (!empty($invoice)) ? $invoice[0] : null;
// Si no consigue la factura redirige al listado de expedientes
if (empty($invoice)){ return $this->redirectToRoute('app_ht_file_index', [], Response::HTTP_SEE_OTHER); }
// Buscamos el ID para la nueva rectificativa
$parameters = array( 'prefix' => 'R'.$prefix, );
$dql = 'SELECT p
FROM App\Entity\HtInvoice p
WHERE p.prefix = :prefix';
$query = $em->createQuery($dql)->setParameters($parameters);
$invoiceRec = $query->getResult();
$invoiceRec = (!empty($invoiceRec)) ? end($invoiceRec) : null;
$idNewRec = empty($invoiceRec) ? 1 : ($invoiceRec->getIdNum() + 1) ;
$dateAt = new DateTimeImmutable('now');
$invoiceItems = $em->getRepository(HtInvoiceItems::class)->findByInvoice($invoice);
// Creamos la factura rectificativa
$oldIvas = $invoice->getVatTotalGroup();
$newIvas = $this->transformarString($oldIvas);
$invoiceRec = new HtInvoice();
$invoiceRec->setIdNum($idNewRec);
$invoiceRec->setPrefix('R'. $prefix);
$invoiceRec->setDateAt($dateAt);
$invoiceRec->setType('Invoice Rec');
$invoiceRec->setClientName($invoice->getClientName());
$invoiceRec->setClientAddress($invoice->getClientAddress());
$invoiceRec->setClientDocument($invoice->getClientDocument());
$invoiceRec->setClientType($invoice->getClientType());
$invoiceRec->setHtFile($invoice->getHtFile());
$invoiceRec->setBenefit((-1) * $invoice->getBenefit());
$invoiceRec->setTotalNet((-1) * $invoice->getTotalNet());
$invoiceRec->setVatTotalGroup($newIvas);
$invoiceRec->setTotal((-1) * $invoice->getTotal());
$invoiceRec->setInvoiceToRec($id);
$em->persist($invoiceRec);
$em->flush();
// Creamos los Items de la factura rectificativa
foreach ($invoiceItems as $item){
$htInvItem = new HtInvoiceItems();
$htInvItem->setInvoice($invoiceRec);
$htInvItem->setHtFile($item->getHtFile());
$htInvItem->setItemType($item->getItemType());
$htInvItem->setItemIdOrigin($item->getItemIdOrigin());
$htInvItem->setItemName($item->getItemName());
$htInvItem->setItemDateStart($item->getItemDateStart());
$htInvItem->setItemDateEnd($item->getItemDateEnd());
$htInvItem->setItemPrice((-1) * $item->getItemPrice());
$htInvItem->setItemUnits($item->getItemUnits());
$htInvItem->setItemPax($item->getItemPax());
$htInvItem->setItemKgLt($item->getItemKgLt());
$htInvItem->setItemRank($item->getItemRank());
$htInvItem->setItemLocation($item->getItemLocation());
$htInvItem->setItemIva($item->getItemIva());
$htInvItem->setItemOpIva($item->isItemOpIva());
$htInvItem->setItemCommission((-1) * $item->getItemCommission());
$htInvItem->setItemOpCommission($item->isItemOpCommission());
$htInvItem->setItemOver((-1) * $item->getItemOver());
$htInvItem->setItemOpOver($item->isItemOpOver());
$htInvItem->setItemSubTotalPrice((-1) * $item->getItemSubTotalPrice());
$htInvItem->setItemCosteDirecto((-1) * $item->getItemCosteDirecto());
$htInvItem->setItemBeneficio((-1) * $item->getItemBeneficio());
$em->persist($htInvItem);
$em->flush();
}
return $this->redirectToRoute('ht_view_invoice_rec', ['id' => $invoiceRec->getPrefix(). $invoiceRec->getIdNum()], Response::HTTP_SEE_OTHER);
}
/**
* @Route("/createproforma/{id}", name="ht_create_proforma")
* Generar proforma en el expediente ID
*/
public function createProformaHtAction($id, EntityManagerInterface $em, Request $request)
{
$req = $request->request->get('invoiced_item');
$clientName = $request->request->get('clientName');
$req_extra = $request->request->get('invoiced_extra');
$htFile = $em->getRepository(HtFile::class)->findOneById($id);
$beneficio_total = 0;
foreach ($req as $itemServ){
foreach ($itemServ as $item) {
if ($item['boolToInvoice'] == 'true') {
$beneficio_total += $item['benefit'];
}
}
}
// Se genera la proforma
// buscamos por el prefijo de cada linea de facturacion para saber el ultimo ID
$invoiceLineGp = $em->getRepository(HtInvoice::class)->findByPrefix('GP');
$invoiceLineCvr = $em->getRepository(HtInvoice::class)->findByPrefix('CV');
$invoiceLineOther = $em->getRepository(HtInvoice::class)->findByPrefix('F');
$lastGp = end($invoiceLineGp);
$lastCvr = end($invoiceLineCvr);
$lastOther = end($invoiceLineOther);
// Buscamos los HtIemts del HtFile para saber la sala del servicio para determinar la línea de facturación ($prefix)
$htItems = $em->getRepository(HtItem::class)->findByHtFile($htFile);
$lounge = $htItems[0]->getLoungeGp();
$prefix = (empty($lounge) ? 'F' : (($lounge->getId() < 22) ? 'GP' : 'CV'));
switch ($prefix) {
case 'F': $idNum = (empty($lastOther)) ? 1 : $lastOther->getIdNum() + 1; break;
case 'CV': $idNum = (empty($lastCvr)) ? 1 : $lastCvr->getIdNum() + 1; break;
default:
// Por defecto Green Patio.
// Esteban Rincon comenta que en caso de un expediente tener salas de GP y CVR deberiamos tener un expediente por linea de facturación
$idNum = (empty($lastGp)) ? 1 : $lastGp->getIdNum() + 1;
break;
}
$client = (empty($htFile->getClient())) ? null : $htFile->getClient();
// Si no hay cliente no se puede facturar, se vuelve a la pantalla de seleccion
if (empty($client)){ return $this->redirectToRoute('ht_select_invoice', ['id' => $htFile->getId()], Response::HTTP_SEE_OTHER); }
$dateAt = new DateTimeImmutable('now');
$type = 'Proforma';
$totalNet = 0; $vatTotalGroup = 0; $total = 0;
if (empty($clientName)){ $clientName = $client->getName(); }
$clientAddress = $request->request->get('clientAddress');
$clientDocument = $request->request->get('clientDocument');
if (empty($clientDocument)){ $clientDocument = empty($client->getIdDocument()) ? ' ' : $client->getIdDocument(); }
$clientType = $request->request->get('clientType');
if ($clientType == 'supplier'){
$type = 'Proforma de Factura de Comision';
$clientName = $request->request->get('clientName');
$clientDocument = $request->request->get('clientDocument');
}
$proforma = new HtProforma();
$proforma->setIdNum($idNum);
$proforma->setPrefix($prefix);
$proforma->setDateAt($dateAt);
$proforma->setType($type);
$proforma->setTotalNet($totalNet);
$proforma->setVatTotalGroup($vatTotalGroup);
$proforma->setTotal($total);
$proforma->setClientName($clientName);
$proforma->setClientAddress($clientAddress);
$proforma->setClientDocument($clientDocument);
$proforma->setClientType($clientType);
$proforma->setHtFile($htFile->getId());
$proforma->setBenefit($beneficio_total);
$em->persist($proforma);
$em->flush();
$data_iva = array(); $data_iva['ivaMontoVeintiUno'] = 0; $data_iva['ivaMontoDiez'] = 0;
// Se crean los Menus en los HtInvoiceItems
foreach ($req as $itemServ){
foreach ($itemServ as $item) {
if ($item['boolToInvoice'] == 'true') {
$htMenu = $em->getRepository(HtMenu::class)->findOneByHtItem($item['idHtService']);
$itemType = 'htMenu';
$itemIdOrigin = $htMenu->getId();
$itemName = $item['name'];
$htItem = $em->getRepository(HtItem::class)->findOneById($htMenu->getHtItem());
$dateStart = ($htItem->getDateStart())->format('Y-m-d');
$hourEnd = ($htItem->getHourEnd())->format('Y-m-d');
$dateTimeString = $dateStart . ' ' . $hourEnd;
$dateEnd = new DateTimeImmutable($dateTimeString);
$iva = $htMenu->getIva();
switch ($iva) {
case 10: $data_iva['ivaMontoDiez'] += ($item['subTotalPrice'] * 0.1); break;
case 21: $data_iva['ivaMontoVeintiUno'] += ($item['subTotalPrice'] * 0.21); break;
default: break;
}
$itemCommission = 0; // Solo htExtra maneja el concepto de over o comision.
$itemOver = 0; // Solo htExtra maneja el concepto de over o comision.
$costeDirecto = $item['subTotalPrice'] - $item['benefit'];
$totalNet += round($item['subTotalPrice'], 2);
$total += round($item['subTotalPrice'], 2) + (round($item['subTotalPrice'], 2) * ($iva / 100));
$htInvItem = new HtProformaItems();
$htInvItem->setProforma($proforma);
$htInvItem->setHtFile($htFile->getId());
$htInvItem->setItemType($itemType);
$htInvItem->setItemIdOrigin($itemIdOrigin);
$htInvItem->setItemName($itemName);
$htInvItem->setItemDateStart($htItem->getDateStart());
$htInvItem->setItemDateEnd($dateEnd);
$htInvItem->setItemPrice(round($item['servicePrice'], 2));
$htInvItem->setItemUnits(1);
$htInvItem->setItemPax($item['qty']);
$htInvItem->setItemKgLt(1);
$htInvItem->setItemRank(1);
$htInvItem->setItemLocation(0);
$htInvItem->setItemIva($iva);
$htInvItem->setItemOpIva(0); // +
$htInvItem->setItemCommission($itemCommission);
$htInvItem->setItemOpCommission(0);
$htInvItem->setItemOver($itemOver);
$htInvItem->setItemOpOver(0);
$htInvItem->setItemSubTotalPrice(round($item['subTotalPrice'], 2));
$htInvItem->setItemCosteDirecto(round($costeDirecto, 2));
$htInvItem->setItemBeneficio(round($item['benefit'], 2));
$em->persist($htInvItem);
$em->flush();
}
}
}
// Se crean los Extras en los HtInvoiceItems
if (!empty($req_extra)) {
foreach ($req_extra as $item) {
if($item['boolToInvoice'] == 'true') {
$htExtra = $em->getRepository(HtExtra::class)->findOneById($item['idHtExtra']);
if ($htExtra->isAppearInvoice()) {
$itemType = 'htExtra';
$itemIdOrigin = $htExtra->getId();
$itemName = $htExtra->getConcept();
$htItem = $em->getRepository(HtItem::class)->findOneById($htExtra->getHtItem());
$dateStart = ($htItem->getDateStart())->format('Y-m-d');
$hourEnd = ($htItem->getHourEnd())->format('Y-m-d');
$dateTimeString = $dateStart . ' ' . $hourEnd;
$dateEnd = new DateTimeImmutable($dateTimeString);
$iva = $htExtra->getVat();
$itemCommission = (($htExtra->isOpOverCommission() == 0) ? 0 : $htExtra->getOverCommission());
$itemOver = (($htExtra->isOpOverCommission() == 1) ? 0 : $htExtra->getOverCommission());
$costeDirecto = 0;
$benefit = $itemOver + ($item['price'] * ($itemCommission / 100));
$totalPrice = $item['price'] + $benefit;
switch ($iva) {
case 10: $data_iva['ivaMontoDiez'] += ($totalPrice * 0.1); break;
case 21: $data_iva['ivaMontoVeintiUno'] += ($totalPrice * 0.21); break;
default: break;
}
$totalNet += round($totalPrice, 2);
$total += round($totalPrice, 2) + (round($totalPrice, 2) * ($iva / 100));
$htInvItem = new HtProformaItems();
$htInvItem->setProforma($proforma);
$htInvItem->setHtFile($htFile->getId());
$htInvItem->setItemType($itemType);
$htInvItem->setItemIdOrigin($itemIdOrigin);
$htInvItem->setItemName($itemName);
$htInvItem->setItemDateStart($htItem->getDateStart());
$htInvItem->setItemDateEnd($dateEnd);
$htInvItem->setItemPrice(round($item['price'], 2));
$htInvItem->setItemUnits(1);
$htInvItem->setItemPax(1);
$htInvItem->setItemKgLt(1);
$htInvItem->setItemRank(1);
$htInvItem->setItemLocation(0);
$htInvItem->setItemIva($iva);
$htInvItem->setItemOpIva(0); // +
$htInvItem->setItemCommission($itemCommission);
$htInvItem->setItemOpCommission(0);
$htInvItem->setItemOver($itemOver);
$htInvItem->setItemOpOver(0);
$htInvItem->setItemSubTotalPrice(round($totalPrice, 2));
$htInvItem->setItemCosteDirecto(round($costeDirecto, 2));
$htInvItem->setItemBeneficio(round($benefit, 2));
$em->persist($htInvItem);
$em->flush();
}
}
}
}
$string_data_iva = '[21]'.round($data_iva['ivaMontoVeintiUno'],2).'[21]'.'[10]'.round($data_iva['ivaMontoDiez'],2).'[10]';
// Se actualiza la factura con los datos globales
$proforma->setTotalNet($totalNet);
$proforma->setVatTotalGroup($string_data_iva);
$proforma->setTotal(round($total,2));
$em->persist($proforma);
$em->flush();
return $this->redirectToRoute('ht_view_proforma', ['id' => $proforma->getId()], Response::HTTP_SEE_OTHER);
}
/**
* @Route("/viewproforma/{id}", name="ht_view_proforma")
* Ver la proforma número ID
*/
public function showProformaHtAction($id, EntityManagerInterface $em, Request $request)
{
$user = $this->getUser();
$proforma = $em->getRepository(HtProforma::class)->findOneById($id);
// Si no consigue la proforma redirige al listado de expedientes
if (empty($proforma)){ return $this->redirectToRoute('app_ht_file_index', [], Response::HTTP_SEE_OTHER); }
$datAt = (!empty($proforma)) ? $proforma->getDateAt() : null;
$totales_neto = (!empty($proforma)) ? $proforma->getTotalNet() : 0;
$totales_iva = (!empty($proforma)) ? $proforma->getVatTotalGroup() : 0;
$totales = (!empty($proforma)) ? $proforma->getTotal() : 0;
$htProformaItems = $em->getRepository(HtProformaItems::class)->findByProforma($proforma);
$htFile = $em->getRepository(HtFile::class)->findOneById($proforma->getHtFile());
$clientName = (!empty($proforma)) ? $proforma->getClientName() : 'No se pudo determinar el cliente';
$clientAddress = (!empty($proforma)) ? $proforma->getClientAddress() : 'No se pudo determinar la dirección';
$clientDocument = (!empty($proforma)) ? $proforma->getClientDocument() : 'No se pudo determinar';
$type = $proforma->getType();
$company = $em->getRepository(SettingsCompany::class)->findOneByPriority('5');
$bases_imponibles = array('21'=> 0,'10'=> 0,'0'=> 0,);
$datasupplier = array(); $netoSumItems = 0; $totalSumItems = 0;
$data_iva = array('ivaMontoDiez' => 0, 'ivaMontoVeintiUno' => 0);
$datasupplier['invoice_item_net_sum'] = 0; $datasupplier['invoice_item_sum'] = 0;
$datasupplier['invoice_extra_net_sum'] = 0; $datasupplier['invoice_extra_sum'] = 0;
foreach ($htProformaItems as $key => $item){
if ($item->getItemType()=='htMenu') {
$datasupplier['invoice_item'][] = array(
'id' => $item->getId(),
'itemName' => $item->getItemName(),
'itemPrice' => $item->getItemPrice(),
'itemPax' => $item->getItemPax(),
'itemDateStart' => $item->getItemDateStart(),
'itemDateEnd' => $item->getItemDateEnd(),
'itemIva' => $item->getItemIva(),
'itemSubTotalPrice' => round($item->getItemSubTotalPrice() * (1 + ($item->getItemIva()/100)),2),
);
$netoSumItems += $item->getItemSubTotalPrice();
$datasupplier['invoice_item_net_sum'] += $item->getItemSubTotalPrice();
$datasupplier['invoice_item_sum'] += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$totalSumItems += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$montoIva = $item->getItemSubTotalPrice() * ($item->getItemIva() / 100);
switch ($item->getItemIva()) {
case 10: $data_iva['ivaMontoDiez'] += $montoIva; break;
case 21: $data_iva['ivaMontoVeintiUno'] += $montoIva; break;
default: break;
}
}
if ($item->getItemType()=='htExtra') {
$datasupplier['invoice_extra'][] = array(
'id' => $item->getId(),
'itemType' => $item->getItemType(),
'itemIdOrigin' => $item->getItemIdOrigin(),
'itemName' => $item->getItemName(),
'itemPrice' => $item->getItemSubTotalPrice(),
'itemPax' => $item->getItemPax(),
'itemDateStart' => $item->getItemDateStart(),
'itemDateEnd' => $item->getItemDateEnd(),
'itemIva' => $item->getItemIva(),
'itemSubTotalPrice' => round($item->getItemSubTotalPrice() * (1 + ($item->getItemIva()/100)),2),
);
$netoSumItems += $item->getItemSubTotalPrice();
$datasupplier['invoice_extra_net_sum'] += $item->getItemSubTotalPrice();
$datasupplier['invoice_extra_sum'] += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$totalSumItems += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$montoIva = $item->getItemSubTotalPrice() * ($item->getItemIva() / 100);
switch ($item->getItemIva()) {
case 10: $data_iva['ivaMontoDiez'] += $montoIva; break;
case 21: $data_iva['ivaMontoVeintiUno'] += $montoIva; break;
default: break;
}
}
}
$allInvoices = $em->getRepository(HtInvoice::class)->findByHtFile($htFile);
$boolToRec = false;
$proformas = $em->getRepository(HtProforma::class)->findByHtFile($htFile->getId());
$fid = $proforma->getId();
return $this->render('higotrigo/ht_invoice/show-invoice.html.twig',
array(
'id' => $htFile->getId(),
'cid' => '',
'fid' => $fid,
'invoice' => $proforma,
'allInvoices' => $allInvoices,
'proformas' => $proformas,
'numberadmin' => '',
'type' => $type,
'number' => $proforma->getId(),
'prefix' => $proforma->getPrefix(),
'date' => $datAt,
'reservation' => $htFile,
'company' => $company,
'user' => $user,
'boolToRec' => $boolToRec,
'invoicedeposititems' => '',
'datasupplier' => $datasupplier,
'totales_neto' => $netoSumItems,
'totales_iva' => $totales_iva,
'totales' => $totalSumItems,
'bases_imponibles' => $data_iva,
'paymentInvoice' => null,
'currency' => '€',
'clientName' => $clientName,
'clientAddress' => $clientAddress,
'clientDocument' => $clientDocument,
)
);
}
/**
* @Route("/htexternal/viewprintproforma/{id}", name="ht_view_print_proforma")
* Ver la proforma del expediente ID en modalidad de impresion
*/
public function printProformaHtAction($id, EntityManagerInterface $em, Request $request)
{
$proforma = $em->getRepository(HtProforma::class)->findOneById($id);
// Si no consigue la proforma redirige al listado de expedientes
if (empty($proforma)){ return $this->redirectToRoute('app_ht_file_index', [], Response::HTTP_SEE_OTHER); }
$datAt = (!empty($proforma)) ? $proforma->getDateAt() : null;
$totales_neto = (!empty($proforma)) ? $proforma->getTotalNet() : 0;
$totales_iva = (!empty($proforma)) ? $proforma->getVatTotalGroup() : 0;
$totales = (!empty($proforma)) ? $proforma->getTotal() : 0;
$htProformaItems = $em->getRepository(HtProformaItems::class)->findByProforma($proforma);
$htFile = $em->getRepository(HtFile::class)->findOneById($id);
$clientName = (!empty($proforma)) ? $proforma->getClientName() : 'No se pudo determinar el cliente';
$clientAddress = (!empty($proforma)) ? $proforma->getClientAddress() : 'No se pudo determinar la dirección';
$clientDocument = (!empty($proforma)) ? $proforma->getClientDocument() : 'No se pudo determinar';
$type = $proforma->getType();
$company = $em->getRepository(SettingsCompany::class)->findOneByPriority('5');
$bases_imponibles = array('21'=> 0,'10'=> 0,'0'=> 0,);
$datasupplier = array(); $netoSumItems = 0; $totalSumItems = 0;
$data_iva = array('ivaMontoDiez' => 0, 'ivaMontoVeintiUno' => 0);
$datasupplier['invoice_item_net_sum'] = 0; $datasupplier['invoice_item_sum'] = 0;
$datasupplier['invoice_extra_net_sum'] = 0; $datasupplier['invoice_extra_sum'] = 0;
foreach ($htProformaItems as $key => $item){
if ($item->getItemType()=='htMenu') {
$datasupplier['invoice_item'][] = array(
'id' => $item->getId(),
'itemName' => $item->getItemName(),
'itemPrice' => $item->getItemPrice(),
'itemPax' => $item->getItemPax(),
'itemDateStart' => $item->getItemDateStart(),
'itemDateEnd' => $item->getItemDateEnd(),
'itemIva' => $item->getItemIva(),
'itemSubTotalPrice' => round($item->getItemSubTotalPrice() * (1 + ($item->getItemIva()/100)),2),
);
$netoSumItems += $item->getItemSubTotalPrice();
$datasupplier['invoice_item_net_sum'] += $item->getItemSubTotalPrice();
$datasupplier['invoice_item_sum'] += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$totalSumItems += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$montoIva = $item->getItemSubTotalPrice() * ($item->getItemIva() / 100);
switch ($item->getItemIva()) {
case 10: $data_iva['ivaMontoDiez'] += $montoIva; break;
case 21: $data_iva['ivaMontoVeintiUno'] += $montoIva; break;
default: break;
}
}
if ($item->getItemType()=='htExtra') {
$datasupplier['invoice_extra'][] = array(
'id' => $item->getId(),
'itemType' => $item->getItemType(),
'itemIdOrigin' => $item->getItemIdOrigin(),
'itemName' => $item->getItemName(),
'itemPrice' => $item->getItemSubTotalPrice(),
'itemPax' => $item->getItemPax(),
'itemDateStart' => $item->getItemDateStart(),
'itemDateEnd' => $item->getItemDateEnd(),
'itemIva' => $item->getItemIva(),
'itemSubTotalPrice' => round($item->getItemSubTotalPrice() * (1 + ($item->getItemIva()/100)),2),
);
$netoSumItems += $item->getItemSubTotalPrice();
$datasupplier['invoice_extra_net_sum'] += $item->getItemSubTotalPrice();
$datasupplier['invoice_extra_sum'] += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$totalSumItems += $item->getItemSubTotalPrice() * (1 + ($item->getItemIva() / 100));
$montoIva = $item->getItemSubTotalPrice() * ($item->getItemIva() / 100);
switch ($item->getItemIva()) {
case 10: $data_iva['ivaMontoDiez'] += $montoIva; break;
case 21: $data_iva['ivaMontoVeintiUno'] += $montoIva; break;
default: break;
}
}
}
$allInvoices = $em->getRepository(HtInvoice::class)->findByHtFile($htFile);
$boolToRec = false;
$fid = $proforma->getPrefix() . $proforma->getIdNum();
return $this->render('higotrigo/ht_invoice/proforma-print.html.twig',
array(
'id' => $id,
'fid' => $fid,
'type' => 'Proforma',
'number' => $id,
'date' => $datAt,
'company' => $company,
'invoicedeposititems' => '',
'datasupplier' => $datasupplier,
'totales_neto' => $netoSumItems,
'totales' => $totalSumItems,
'bases_imponibles' => $data_iva,
'currency' => '€',
'clientName' => $clientName,
'clientAddress' => $clientAddress,
'clientDocument' => $clientDocument,
)
);
}
private function transformarString($input) {
// Expresión regular para encontrar números entre los delimitadores [21] y [10]
$pattern = '/\[21\](\d+\.?\d*)\[21\]|\[10\](\d+\.?\d*)\[10\]/';
// Función de reemplazo que multiplica los números por -1
$callback = function ($matches) {
if (isset($matches[1]) && $matches[1] !== '') { return '[21]' . (-1 * $matches[1]) . '[21]'; } elseif (isset($matches[2]) && $matches[2] !== '') { return '[10]' . (-1 * $matches[2]) . '[10]'; }
return $matches[0]; // No debería llegar aquí
};
// Realizar el reemplazo en el string original
$output = preg_replace_callback($pattern, $callback, $input);
return $output;
}
/**
* Formatea el campo vatTotalGroup a una cadena como "157.00 (21%)"
*/
private function formatVatTotalGroup($vatTotalGroup): string
{
// Regex para extraer valores, porcentajes y manejar valores negativos
preg_match_all('/\[(\d+)\](-?\d+(\.\d+)?)/', $vatTotalGroup, $matches);
$formattedVat = '';
foreach ($matches[1] as $index => $percentage) {
// Asegurarse de que los números se formateen correctamente
$amount = number_format((float)$matches[2][$index], 2, ',', '.');
$formattedVat .= "$amount ({$percentage}%)<br>";
}
return $formattedVat;
}
}