<?php
namespace Noahtech\Sistemas\InterjamaBundle\Handler;
use Noahtech\Sistemas\InterjamaBundle\Entity\McCaja;
use Noahtech\Sistemas\InterjamaBundle\Utils\Constants;
use Noahtech\Sistemas\InterjamaBundle\Utils\EmailsMessages;
use Noahtech\Sistemas\InterjamaBundle\Utils\Encrypt;
use DateInterval;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpFoundation\Request;
use Noahtech\Sistemas\InterjamaBundle\Utils\PDF;
use Symfony\Component\HttpFoundation\Response;
class McCajaHandler extends BaseHandler {
public function __construct(ContainerInterface $container, EntityManagerInterface $entityManager) {
$this->container = $container;
$this->entityManager = $entityManager;
$this->repository = $entityManager->getRepository(McCaja::class);
}
public function search($offset, $limit, $sortField, $sortDirection, $searchParam) {
$lp = $this->repository->search($offset, $limit, $sortField, $sortDirection, $searchParam);
$cajas = $this->toarray($lp->getListado(), 'caja');
foreach ($cajas as &$caja) {
$caja['caja_monedas'] = [];
$monedas = $this->container->get("Noahtech\Sistemas\InterjamaBundle\Handler\McCajaMonedaHandler")->getAllMonedasByCaja((int)$caja['id']);
foreach ($monedas as $moneda) {
array_push($caja['caja_monedas'], $moneda);
}
}
$lp->setListado($cajas);
return $lp;
}
public function getCajaFromRequest(Request $request, $operador, $tipo, int $id = null):McCaja {
$cerrado = ($request->request->get('derrado') ? true : false);
$fechaCreacion = $request->request->get('fecha_creacion');
$caja = $this->repository->getCajaByTipoCerrada($tipo, $id);
if (COUNT($caja) > 0) {
throw new HttpException(409, "Ya existe una caja abierta. Recuerde que solo puede haber una sola caja abierta.");
}
if (is_null($id)) {
$caja = new McCaja();
$caja->setFechaCreacion(new DateTime());
} else {
$caja = $this->repository->findOneById($id);
$caja->setFechaActualizacion(new DateTime());
}
$caja->setTipo($tipo);
$caja->setCerrado($cerrado);
$caja->setUsuarioOpen($operador);
return $caja;
}
public function save(Request $request, McCaja $caja) {
$cajaMonedas = $request->request->get('monedas');
$caja = $this->repository->save($caja);
//Guardo los datos de las monedas para la caja
if (COUNT($cajaMonedas) > 0) {
$this->container->get("Noahtech\Sistemas\InterjamaBundle\Handler\McCajaMonedaHandler")->saveOrUpdateCajaMoneda($caja, $cajaMonedas);
}
$caja = $this->toarray($caja, "caja");
return $caja;
}
public function getById($id) {
$caja = $this->repository->findOneById($id);
$caja = $this->toarray($caja, "caja");
$caja['caja_monedas'] = [];
$monedas = $this->container->get("Noahtech\Sistemas\InterjamaBundle\Handler\McCajaMonedaHandler")->getAllMonedasByCaja((int)$caja['id']);
foreach ($monedas as $moneda) {
array_push($caja['caja_monedas'], $moneda);
}
return $caja;
}
public function update(Request $request, McCaja $caja, int $id) {
$cajaMonedas = $request->request->get('monedas');
$cajaMonedasRemover = $request->request->get('monedasRemover');
$caja = $this->repository->save($caja);
// Elimino las monedas que se sacaron en la edicion
if (!is_null($cajaMonedasRemover)) {
if (COUNT($cajaMonedasRemover) > 0) {
$this->container->get("Noahtech\Sistemas\InterjamaBundle\Handler\McCajaMonedaHandler")->removeCajaMoneda($cajaMonedasRemover);
}
}
// Guardo los datos de las monedas para la caja
if (!is_null($cajaMonedas)) {
if (COUNT($cajaMonedas) > 0) {
$this->container->get("Noahtech\Sistemas\InterjamaBundle\Handler\McCajaMonedaHandler")->saveOrUpdateCajaMoneda($caja, $cajaMonedas);
}
}
$caja = $this->toarray($caja, "caja");
return $caja;
}
public function getCajaEstadoFromRequest(Request $request, $operador, $tipo, int $id):McCaja {
$cerrado = ($request->request->get('cerrado') ? true : false);
$caja = $this->repository->findOneById($id);
if (!$cerrado) {
$fechaCreacion = $caja->getFechaCreacion();
$today = new DateTime();
if ($today->format('d/m/Y') == $fechaCreacion->format('d/m/Y')) {
$cajaAux = $this->repository->getCajaByFechaAndTipo($today->format('Y-m-d'), $tipo, $id);
if (COUNT($cajaAux) > 0) {
throw new HttpException(409, "Ya existe una caja para la fecha de hoy.");
}
} else {
throw new HttpException(409, "No se puede crear/modificar una caja para la fecha seleccionada.");
}
}
$caja->setFechaActualizacion(new DateTime());
$caja->setCerrado($cerrado);
if ($cerrado) {
$caja->setUsuarioClose($operador);
} else {
$caja->setUsuarioClose(null);
}
return $caja;
}
public function getCajaById($id) {
return $this->repository->findOneById($id);
}
public function numeroAddZero($nro) {
$numero = "";
$nro1 = strlen((string)$nro);
switch($nro1) {
case 1:
$numero = "000000" . $nro;
break;
case 2:
$numero = "00000" . $nro;
break;
case 3:
$numero = "0000" . $nro;
break;
case 4:
$numero = "000" . $nro;
break;
case 5:
$numero = "00" . $nro;
break;
case 6:
$numero = "0" . $nro;
break;
case 7:
$numero = $nro;
break;
}
return $numero;
}
public function descargaReciboCajaPdf($id) {
$caja = $this->getById($id);
$caja['caja_monedas'] = [];
$monedas = $this->container->get("Noahtech\Sistemas\InterjamaBundle\Handler\McCajaMonedaHandler")->getAllMonedasByCaja((int)$caja['id']);
foreach ($monedas as $moneda) {
array_push($caja['caja_monedas'], $moneda);
}
$numero = $this->numeroAddZero($caja['id']);
$fecha = date("d/m/Y H:m", strtotime($caja['fecha_actualizacion']));
$usuarioClose = $caja['usuario_close']['persona']['nombre'] ." ". $caja['usuario_close']['persona']['apellido'];
// Obtengo losmovimientos de la caja
$movimientos = $this->container->get("Noahtech\Sistemas\InterjamaBundle\Handler\McMovimientoHandler")->getAllMovimientosByCaja($id);
// Calculos de los monto por moneda
$totales = [];
foreach ($monedas as $moneda) {
$nombreMoneda = $moneda['moneda']['nombre'];
$montoTotalEfectivo = 0;
$montoTotalTransferencia = 0;
$montoTotalPorConvenio = 0;
$montoTotalCuentaCorriente = 0;
if (COUNT($movimientos) > 0) {
foreach ($movimientos as $movimiento) {
if ((int)$moneda['moneda']['id'] == (int)$movimiento['moneda']['id']) {
if (strtolower($movimiento['modalidad']) == 'contado/efectivo') {
if ($movimiento['tipo'] == 'Ingreso') {
$montoTotalEfectivo = $montoTotalEfectivo + $movimiento['monto'];
} else if ($movimiento['tipo'] == 'Egreso' || $movimiento['tipo'] == 'Anulacion') {
$montoTotalEfectivo = $montoTotalEfectivo - $movimiento['monto'];
}
}
if (strtolower($movimiento['modalidad']) == 'transferencia') {
if ($movimiento['tipo'] == 'Ingreso') {
$montoTotalTransferencia = $montoTotalTransferencia + $movimiento['monto'];
} else if ($movimiento['tipo'] == 'Egreso' || $movimiento['tipo'] == 'Anulacion') {
$montoTotalTransferencia = $montoTotalTransferencia - $movimiento['monto'];
}
}
if (strtolower($movimiento['modalidad']) == 'pago por convenio') {
if ($movimiento['tipo'] == 'Ingreso') {
$montoTotalPorConvenio = $montoTotalPorConvenio + $movimiento['monto'];
} else if ($movimiento['tipo'] == 'Egreso' || $movimiento['tipo'] == 'Anulacion') {
$montoTotalPorConvenio = $montoTotalPorConvenio - $movimiento['monto'];
}
}
if (strtolower($movimiento['modalidad']) == 'cuenta corriente') {
if ($movimiento['tipo'] == 'Ingreso') {
$montoTotalCuentaCorriente = $montoTotalCuentaCorriente + $movimiento['monto'];
} else if ($movimiento['tipo'] == 'Egreso' || $movimiento['tipo'] == 'Anulacion') {
$montoTotalCuentaCorriente = $montoTotalCuentaCorriente - $movimiento['monto'];
}
}
}
}
}
$totales[] = array(
'nombreMoneda' => $nombreMoneda,
'montoTotalEfectivo' => $montoTotalEfectivo,
'montoTotalTransferencia' => $montoTotalTransferencia,
'montoTotalPorConvenio' => $montoTotalPorConvenio,
'montoTotalCuentaCorriente' => $montoTotalCuentaCorriente
);
}
// create new PDF document
$pdf = new PDF();
$pdf->SetTitle("Comprobante Caja Cerrada");
$pdf->SetSubject("Comprobante Caja Cerrada");
$pdf->setFontSubsetting(true);
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
$pdf->SetFont('helvetica', '', 11, '', true);
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$pdf->setPrintFooter(false);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->AddPage('P', 'A4');
$html = <<<EOD
<h1> Comprobante - Cierre de Caja</h1>
<table table border="0.5">
<tr>
<th style="background-color: grey;"> Caja Nº</th>
<td><b> {$numero}</b></td>
</tr>
<tr>
<th style="background-color: grey;"> Tipo</th>
<td><b> {$caja['tipo']}</b></td>
</tr>
<tr>
<th style="background-color: grey;"> Fecha</th>
<td><b> {$fecha}</b></td>
</tr>
<tr>
<th style="background-color: grey;"> Usuario responsable</th>
<td><b> {$usuarioClose}</b></td>
</tr>
</table>
<br/>
<br/>
<br/>
<table border="0.5">
<tr style="background-color: grey;">
<th> Fecha</th>
<th> Monto</th>
<th> Moneda</th>
<th> Modalidad</th>
<th> Transacción</th>
</tr>
EOD;
if (COUNT($movimiento) > 0) {
foreach ($movimientos as $movimiento) {
$fecha = date("d/m/Y H:m", strtotime($movimiento['fecha_creacion']));
$html .= <<<EOD
<tr>
<td> {$fecha}</td>
<td> $ {$movimiento['monto']}</td>
<td> {$movimiento['moneda']['nombre']}</td>
<td> {$movimiento['modalidad']}</td>
<td> {$movimiento['tipo']}</td>
</tr>
EOD;
}
}
$html .= <<<EOD
</table>
<br/>
<br/>
<br/>
<table border="0.5">
<tr style="background-color: grey;">
<th> Moneda</th>
<th> Total Efectivo/Contado</th>
<th> Total Transferencia</th>
<th> Total Por Convenio</th>
<th> Total Cuenta Corriente</th>
</tr>
EOD;
if (COUNT($totales) > 0) {
foreach ($totales as $total) {
$fecha = date("d/m/Y H:m", strtotime($movimiento['fecha_creacion']));
$html .= <<<EOD
<tr>
<td> {$total['nombreMoneda']}</td>
<td> $ {$total['montoTotalEfectivo']}</td>
<td> $ {$total['montoTotalTransferencia']}</td>
<td> $ {$total['montoTotalPorConvenio']}</td>
<td> $ {$total['montoTotalCuentaCorriente']}</td>
</tr>
EOD;
}
}
$html .= <<<EOD
</table>
<br/>
<br/>
<br/>
<table border="0.5">
<tr style="background-color: grey;">
<th> Moneda</th>
<th> Monto inicial</th>
<th> Monto final</th>
</tr>
EOD;
foreach ($caja['caja_monedas'] as $moneda) {
$html .= <<<EOD
<tr>
<td> {$moneda['moneda']['nombre']}</td>
<td> $ {$moneda['monto_inicial']}</td>
<td> $ {$moneda['monto_final']}</td>
</tr>
EOD;
}
$html .= <<<EOD
</table>
EOD;
$pdf->writeHTML($html, true, false, false, false, '');
return new Response($pdf->Output("Comprobante", "S"), 200, array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="Caja-Comprobante.pdf"'
)
);
}
public function saveOperacionCaja($caja, $tipo, $monto, $modalidad, $monedaId) {
if ($modalidad == 'Contado/Efectivo') {
$cajaMoneda = $this->container->get("Noahtech\Sistemas\InterjamaBundle\Handler\McCajaMonedaHandler")->getByCajaAndMoneda($caja->getId(), $monedaId);
if ($tipo == 'Egreso') {
if ($cajaMoneda->getMontoFinal() > 0) {
if ($cajaMoneda->getMontoFinal() >= $monto) {
$montoFinal = $cajaMoneda->getMontoFinal();
$cajaMoneda->setMontoFinal($montoFinal - $monto);
} else {
throw new HttpException(409, "El monto de egreso es mayor al saldo de la caja.");
}
} else {
throw new HttpException(409, "La caja no cuenta con el saldo suficiente.");
}
} else if($tipo == 'Ingreso' || $tipo == 'Ingreso-Devolución') {
$montoFinal = $cajaMoneda->getMontoFinal();
$cajaMoneda->setMontoFinal($montoFinal + $monto);
}
$cajaMoneda->setFechaActualizacion(new DateTime());
return $this->container->get("Noahtech\Sistemas\InterjamaBundle\Handler\McCajaMonedaHandler")->save($cajaMoneda);
}
}
public function saveOperacionDivisasCaja($caja, $tipo, $tipoDetalle, $monto, $modalidad, $monedaId, float $cotizacion) {
if ($modalidad == 'Contado/efectivo') {
$cajaMonedaNacional = $this->container->get("Noahtech\Sistemas\InterjamaBundle\Handler\McCajaMonedaHandler")->getByCajaAndMoneda($caja->getId(), 1);
$cajaMonedaExtranjero = $this->container->get("Noahtech\Sistemas\InterjamaBundle\Handler\McCajaMonedaHandler")->getByCajaAndMoneda($caja->getId(), $monedaId);
//Si se compra moneda extranjera, validamos si tenemos los pesos argentinos para poder comprar.
if ($tipoDetalle == 'Compra') {
if ($cajaMonedaNacional->getMontoFinal() > 0) {
if ($cajaMonedaNacional->getMontoFinal() >= $cotizacion) {
//Egreso de la caja nacional
$montoFinalNacional = $cajaMonedaNacional->getMontoFinal();
$cajaMonedaNacional->setMontoFinal($montoFinalNacional - $cotizacion);
//Ingreso de la caja extranjera
$montoFinalExtranjero = $cajaMonedaExtranjero->getMontoFinal();
$cajaMonedaExtranjero->setMontoFinal($montoFinalExtranjero + $monto);
} else {
throw new HttpException(409, "El monto de egreso es mayor al saldo de la caja.");
}
} else {
throw new HttpException(409, "La caja no cuenta con el saldo suficiente.");
}
} else {
//Si se vende moneda extranjera, validamos si tenemos la cantidad a vender.
if ($cajaMonedaExtranjero->getMontoFinal() > 0) {
if ($cajaMonedaExtranjero->getMontoFinal() >= $monto) {
//Egreso de la caja extranjera
$montoFinalExtranjero = $cajaMonedaExtranjero->getMontoFinal();
$cajaMonedaExtranjero->setMontoFinal($montoFinalExtranjero - $monto);
//Ingreso de la caja nacional
$montoFinalNacional = $cajaMonedaNacional->getMontoFinal();
$cajaMonedaNacional->setMontoFinal($montoFinalNacional + $cotizacion);
} else {
throw new HttpException(409, "El monto de egreso es mayor al saldo de la caja.");
}
} else {
throw new HttpException(409, "La caja no cuenta con el saldo suficiente.");
}
}
}
}
public function getCajaAbierta($tipo) {
$caja = $this->repository->getCajaAbierta($tipo);
if (!is_null($caja)) {
$caja = $this->toarray($caja, 'caja');
$caja['caja_monedas'] = [];
$monedas = $this->container->get("Noahtech\Sistemas\InterjamaBundle\Handler\McCajaMonedaHandler")->getAllMonedasByCaja((int)$caja['id']);
foreach ($monedas as $moneda) {
array_push($caja['caja_monedas'], $moneda);
}
} else {
$caja = [];
}
return $caja;
}
}