Files
oficial/app/Controller/Informes.php
2022-03-07 12:42:34 +00:00

920 lines
32 KiB
PHP

<?php
namespace App\Controller;
use Carbon\Carbon;
use GuzzleHttp\Client;
use App\Definition\Controller;
use App\Alias\PHPExcel;
use Incoviba\old\Proyecto\Proyecto;
use Incoviba\old\Proyecto\Agente;
use Incoviba\old\Proyecto\ProyectoAgente;
use Incoviba\old\Venta\Venta;
use Incoviba\old\Venta\Pie;
use Incoviba\old\Venta\Credito;
use Incoviba\old\Venta\Cuota;
class Informes
{
use Controller;
protected static function setDefault()
{
self::$default = view('informes.list');
}
public static function gantt_entregas()
{
if (get('proyecto')) {
$id_proyecto = get('proyecto');
$proyecto = model(Proyecto::class)->find_one($id_proyecto);
$ini = \Carbon\Carbon::parse($proyecto->estado()->fecha, config('app.timezone'));
#$informe = new Informador('Carta Gantt Proyecto - ' . $proyecto->descripcion);
$name = 'Carta Gantt Proyecto - ' . $proyecto->descripcion;
$hoy = Carbon::now(config('app.timezone'));
$filename = str_replace('ñ', 'n', $name . ' - ' . $hoy->format('Y-m-d') . '.xls');
$informe = new PHPExcel($name, $filename);
$columnas = ['Departamento', 'Propietario', 'Entrega', 'Estado'];
$today = \Carbon\Carbon::today(config('app.timezone'));
$end = $today->copy()->addDays(30);
$dif = $end->diffInDays($ini);
for ($i = 0; $i <= $dif; $i ++) {
$f = $ini->copy()->addDays($i);
if ($f->isWeekend()) {
continue;
}
$columnas []= $f->format('Y-m-d');
}
$informe->addColumns($columnas);
$data = [];
foreach ($proyecto->entregas() as $venta) {
$info = [];
$info []= $venta->unidad()->descripcion;
$info []= $venta->propietario()->findOne()->nombreCompleto();
$fe = Carbon::parse($venta->entrega()->find_one()->fecha, config('app.timezone'));
$info []= $fe->format('Y-m-d');
$info []= '';
for ($i = 0; $i <= $dif; $i ++) {
$f = $ini->copy()->addDays($i);
if ($f->isWeekend()) {
continue;
}
if ($f >= $fe and $f <= $fe->copy()->addDays(14)) {
$info []= 'X';
} else {
$info []= '';
}
}
$data []= $info;
}
$informe->addDatas($data);
return $informe->informe();
} else {
$proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many();
return view('informes.gantt_entregas', compact('proyectos'));
}
}
public static function escrituras()
{
if (get('proyecto')) {
set_time_limit(60);
$id_proyecto = get('proyecto');
$proyecto = model(Proyecto::class)->find_one($id_proyecto);
#$informe = new Informador('Escrituras - ' . $proyecto->descripcion);
$name = 'Escrituras';
$hoy = Carbon::now(config('app.timezone'));
$filename = str_replace('ñ', 'n', $name . ' - ' . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls');
$informe = new PHPExcel($name, $filename);
$columnas = [
'Departamento',
'Estacionamientos',
'Bodegas',
'Propietario',
(object) ['name' => 'Promesa', 'style' => 'number'],
['name' => 'Bono Pie', 'style' => 'amount'],
['name' => 'Pie Pagado', 'style' => 'amount'],
['name' => 'Reajuste', 'style' => 'amount'],
['name' => 'Abono Contado', 'style' => 'amount'],
['name' => 'Subsidio', 'style' => 'amount'],
'Estado Subsidio',
['name' => 'Credito', 'style' => 'amount'],
'Banco',
'Estado Credito',
['name' => 'Saldo', 'style' => 'amount'],
['name' => 'Escritura', 'style' => 'amount'],
['name' => 'Entrega', 'style' => 'date']
];
$informe->addColumns($columnas);
//$ventas = $proyecto->escrituras();
$ventas = $proyecto->ventas();
$data = [];
foreach ($ventas as $venta) {
$info = [];
$info['Departamento'] = $venta->unidad()->descripcion;
$ests = [];
foreach ($venta->propiedad()->estacionamientos() as $e) {
$ests []= $e->descripcion;
}
$bods = [];
foreach ($venta->propiedad()->bodegas() as $b) {
$bods []= $b->descripcion;
}
$info['Estacionamientos'] = implode(' - ', $ests);
$info['Bodegas'] = implode(' - ', $bods);
$info['Propietario'] = $venta->propietario()->nombreCompleto();
$info['Promesa'] = $venta->valor_uf;
$saldo = $venta->valor_uf;
$info['Bono Pie'] = '';
if ($venta->bono_pie != 0) {
$info['Bono Pie'] = $venta->bonoPie()->pago()->valor('ufs');
$saldo -= $venta->bonoPie()->pago()->valor('ufs');
}
$info['Pie'] = '';
$info['Reajuste'] = '';
if ($venta->pie != 0) {
$info['Pie'] = $venta->pie()->valorPagado();
$saldo -= $venta->pie()->valorPagado();
if ($venta->pie()->reajuste != 0) {
$info['Reajuste'] = $venta->pie()->reajuste()->valor('ufs');
$saldo -= $venta->pie()->reajuste()->valor('ufs');
}
}
$info['Abono Contado'] = '';
if ($venta->escritura != 0) {
$info['Abono Contado'] = $venta->escritura()->pago()->valor('ufs');
$saldo -= $venta->escritura()->pago()->valor('ufs');
}
$info['Subsidio'] = '';
$info['Estado Subsidio'] = '';
if ($venta->subsidio != 0) {
$info['Subsidio'] = $venta->subsidio()->total('ufs');
$info['Estado Subsidio'] = implode(' - ', [
$venta->subsidio()->subsidio()->estado()->tipo()->descripcion,
$venta->subsidio()->pago()->estado()->tipo()->descripcion
]);
$saldo -= $venta->subsidio()->total('ufs');
}
$info['Credito'] = '';
$info['Banco'] = '';
$info['Estado Credito'] = '';
if ($venta->credito != 0) {
$info['Credito'] = $venta->credito()->pago()->valor('ufs');
$saldo -= $venta->credito()->pago()->valor('ufs');
if ($venta->credito()->pago()->banco != 0) {
$info['Banco'] = $venta->credito()->pago()->banco()->nombre;
}
$info['Estado Credito'] = $venta->credito()->pago()->estado()->tipo()->descripcion;
}
$info['Saldo'] = -$saldo;
$info['Escritura'] = '';
if ($venta->escriturado != 0) {
$info['Escritura'] = $venta->escriturado;
}
$info['Entrega'] = '';
if ($venta->entregado != 0) {
$info['Entrega'] = $venta->entregado;
}
$data []= $info;
}
$informe->addData($data);
return $informe->informe();
} else {
$proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many();
return view('informes.escrituras', compact('proyectos'));
}
}
public static function consolidacion()
{
$id_proyecto = get('proyecto');
$proyecto = model(Proyecto::class)->findOne($id_proyecto);
$ventas = $proyecto->ventas();
set_time_limit(count($ventas));
$f = Carbon::today(config('app.timezone'));
setlocale(LC_TIME, 'es');
$data = [
[$proyecto->descripcion],
[strftime('%d de %B de %Y', $f->timestamp)],
[''],
['']
];
$columns = [
['name' => 'Fecha', 'style' => 'date'],
'Glosa',
['name' => 'Debe', 'style' => 'number'],
['name' => 'Haber', 'style' => 'number'],
['name' => 'Saldo', 'style' => 'number'],
'Comentario'
];
$bold_rows = [];
foreach ($ventas as $venta) {
$data []= ['Departamento ' . $venta->unidad()->descripcion . ' (' . format('ufs', $venta->valor_uf) . ' UF)'];
$data []= $columns;
$bold_rows []= count($data) - 1;
$ufs = 0;
$debe = 0;
$haber = 0;
$sum = 0;
if ($venta->pie != 0) {
$cuotas = $venta->pie()->cuotas();
foreach ($cuotas as $cuota) {
$sum += $cuota->pago()->valor();
$ufs += $cuota->pago()->valor('ufs');
$haber += $cuota->pago()->valor();
$info = [
$cuota->pago()->estado()->fecha,
'Pie - Cuota ' . $cuota->numero() . ' - ' . $venta->pie()->cuotas . ' (' . format('ufs', $cuota->pago()->valor('ufs')) . ' UF)',
'',
$cuota->pago()->valor(),
$sum
];
if ($cuota->pago()->estado()->estado < 2) {
$info []= 'No ha sido abonada.';
}
$data []= $info;
}
if ($venta->pie()->reajuste != 0) {
$sum += $venta->pie()->reajuste()->valor();
$ufs += $venta->pie()->reajuste()->valor('ufs');
$haber += $venta->pie()->reajuste()->valor();
$info = [
$venta->pie()->reajuste()->estado()->fecha,
'Reajuste (' . format('ufs', $venta->pie()->reajuste()->valor('ufs')) . ' UF)',
'',
$venta->pie()->reajuste()->valor(),
$sum
];
if ($venta->pie()->reajuste()->estado()->estado < 2) {
$info []= 'No ha sido abonado.';
}
$data []= $info;
}
}
if ($venta->escritura != 0) {
$sum += $venta->escritura()->pago()->valor();
$ufs += $venta->escritura()->pago()->valor('ufs');
$haber += $venta->escritura()->pago()->valor();
$info = [
$venta->escritura()->pago()->estado()->fecha,
'Abono Escritura (' . format('ufs', $venta->escritura()->pago()->valor('ufs')) . ' UF)',
'',
$venta->escritura()->pago()->valor(),
$sum
];
if ($venta->escritura()->pago()->estado()->estado < 2) {
$info []= 'No ha sido abonado.';
}
$data []= $info;
}
if ($venta->credito != 0) {
$sum += $venta->credito()->pago()->valor();
$ufs += $venta->credito()->pago()->valor('ufs');
$haber += $venta->credito()->pago()->valor();
$info = [
$venta->credito()->pago()->estado()->fecha,
'Crédito (' . format('ufs', $venta->credito()->pago()->valor('ufs')) . ' UF)',
'',
$venta->credito()->pago()->valor(),
$sum
];
if ($venta->credito()->pago()->estado()->estado < 2) {
$info []= 'No ha sido pagado.';
}
$data []= $info;
}
if ($venta->bono_pie != 0) {
try {
$sum -= $venta->bonoPie()->pago()->valor();
$debe += $venta->bonoPie()->pago()->valor();
$info = [
$venta->bonoPie()->pago()->estado()->fecha,
'Bono Pie (' . format('ufs', $venta->bonoPie()->pago()->valor('ufs')) . ' UF)'.
$venta->bonoPie()->pago()->valor(),
'',
$sum
];
$data []= $info;
$sum += $venta->bonoPie()->pago()->valor();
$haber += $venta->bonoPie()->pago()->valor();
$info = [
$venta->bonoPie()->pago()->estado()->fecha,
'Bono Pie (' . format('ufs', $venta->bonoPie()->pago()->valor('ufs')) . ' UF)'.
'',
$venta->bonoPie()->pago()->valor(),
$sum
];
$data []= $info;
} catch (\Exception $e) {
}
}
$info = [
'',
'TOTAL (' . format('ufs', $ufs) . ' UF)',
$debe,
$haber,
$sum
];
$data []= $info;
$bold_rows []= count($data) - 1;
$data []= [''];
}
/**
* Departamento #
* Fecha |Glosa |Debe |Haber |Saldo
* <fecha> |Pie - Cuota 1 - n (# UF) |- |$# |<sum>
* <fecha> |Reajuste (# UF) |- |$# |<sum>
* <fecha> |Abono Escritura (# UF) |- |$# |<sum>
* <fecha> |Crédito (# UF) |- |$# |<sum>
* <fecha> |Bono Pie (# UF) |$# |- |<sum>
* <fecha> |Bono Pie (# UF) |- |$# |<sum>
* <fecha> |Devolución (# UF) |$# |- |<sum>
* - |TOTAL (# UF) |<sumDebe> |<sumHaber> |<sum>
*/
array_walk($data, function(&$e, $i) use ($columns) {
if (count($e) < count($columns)) {
$n = count($columns) - count($e);
for ($j = 0; $j < $n; $j ++) {
$e []= '';
}
}
});
#$informe = new Informador('Consolidación - ' . $proyecto->descripcion);
$name = 'Consolidación';
$hoy = Carbon::now(config('app.timezone'));
$filename = str_replace('ñ', 'n', $name . ' - ' . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls');
$informe = new PHPExcel($name, $filename);
$informe->addColumns($columns);
$informe->addData($data);
return $informe->informe();
}
public static function creditos_pendientes()
{
function creditos() {
$creditos = model(Credito::class)
->select('credito.*')
->join('venta', ['venta.credito', '=', 'credito.id'])
->join('pago', ['pago.id', '=', 'credito.pago'])
->rawJoin('JOIN (SELECT ep.* FROM (SELECT pago, MAX(id) AS id FROM estado_pago GROUP BY pago) e0 JOIN estado_pago ep ON ep.id = e0.id)', ['estado_pago.pago', '=', 'pago.id'], 'estado_pago')
->whereLt('estado_pago.estado', 2)
->where('venta.estado', 1)
->orderByAsc('estado_pago.fecha')
->findMany();
foreach ($creditos as $credito) {
yield $credito;
}
}
$informe = new Informador('Créditos Pendientes');
$columnas = ['Proyecto', 'Departamento', 'Valor', 'Fecha Escritura', 'Estado'];
$informe->addColumns($columnas);
$row = 0;
foreach (creditos() as $credito) {
$informe->addData($row, $credito->venta()->proyecto()->descripcion, 'Proyecto');
$informe->addData($row, $credito->venta()->unidad()->descripcion, 'Departamento');
$informe->addData($row, $credito->pago()->valor('ufs'), 'Valor');
$informe->addData($row, (($credito->venta()->escriturado) ? $credito->venta()->escriturado : $credito->pago()->estado()->fecha), 'Fecha Escritura');
$informe->addData($row, ucwords($credito->pago()->estado()->tipo()->descripcion), 'Estado');
$row ++;
}
$date = [
'numberFormat' => ['short-date']
];
$ufs = [
'numberFormat' => ['thousands']
];
$formats = ['Valor' => $ufs, 'Fecha Escritura' => $date];
$informe->addFormats($formats);
return $informe->informe();
}
public static function ventas()
{
if (get('proyecto')) {
ini_set('memory_limit', "1G");
ini_set('max_execution_time', '3600');
$id = get('proyecto');
$proyecto = model(Proyecto::class)->findOne($id);
$ventas = $proyecto->ventas();
/*usort($ventas, function($a, $b) {
return $a->fecha()->timestamp - $b->fecha()->timestamp;
});*/
$procasa = model(Agente::class)->findOne(1);
$pa = model(ProyectoAgente::class)->where('agente', $procasa->id)->where('proyecto', $proyecto->id)->findOne();
if ($pa) {
$comision = $pa->comision / 100;
} else {
$comision = 0.03;
}
#$informe = new Informador('Ventas - ' . $proyecto->descripcion);
$name = 'Informe de Ventas';
$hoy = Carbon::now(config('app.timezone'));
$filename = str_replace('ñ', 'n', $name . ' - ' . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xlsx');
//$informe = new PHPExcel($name, $filename);
$columnas = [
'Propietario',
'Departamento',
['name' => 'Estacionamientos', 'style' => 'number'],
['name' => 'Bodegas', 'style' => 'number'],
'Fecha Venta',
['name' => 'Mes', 'style' => 'mes'],
'Tipo',
['name' => 'm² Ponderados', 'style' => 'amount'],
['name' => 'Valor Promesa', 'style' => 'amount'],
['name' => 'Pie', 'style' => 'amount'],
['name' => 'Pie Pagado', 'style' => 'amount'],
['name' => '% Pie Pagado', 'style' => 'percent'],
['name' => 'Bono Pie', 'style' => 'amount'],
'Operador',
['name' => 'Valor Operador', 'style' => 'amount'],
['name' => 'Premios', 'style' => 'amount'],
['name' => 'Subsidio', 'style' => 'amount'],
['name' => 'Ahorro', 'style' => 'amount'],
['name' => 'Credito', 'style' => 'amount'],
'Banco',
['name' => 'Valor Ests & Bods', 'style' => 'amount'],
['name' => 'Valor Neto', 'style' => 'amount'],
['name' => 'UF/m²*', 'style' => 'amount'],
['name' => 'Comision', 'style' => 'amount'],
['name' => 'Venta s/Comision', 'style' => 'amount'].
['name' => 'Precio', 'style' => 'Amount']
];
//$informe->addColumns($columnas);
$data = [];
foreach ($ventas as $venta) {
$info = [];
$info['Propietario'] = mb_strtoupper($venta->propietario()->nombreCompleto());
$info['Departamento'] = implode(' - ', array_map(function($item) {
return $item->descripcion;
}, $venta->propiedad()->departamentos()));
$es = $venta->propiedad()->estacionamientos();
$info['Estacionamientos'] = implode(', ', array_map(function($item) {
return $item->descripcion;
}, $es));
$bs = $venta->propiedad()->bodegas();
$info['Bodegas'] = implode(', ', array_map(function($item) {
return $item->descripcion;
}, $bs));
$info['Fecha Venta'] = $venta->fecha()->format('Y-m-d');
$info['Mes'] = $venta->fecha()->format('M-y');
$info['Tipo'] = $venta->unidad()->abreviacion;
$info['m² Ponderados'] = $venta->unidad()->m2('vendible');
$info['Valor Promesa'] = $venta->valor_uf;
$info['Pie'] = $venta->pie()->valor;
$info['Pie Pagado'] = 0;
$info['% Pie Pagado'] = 0;
if ($venta->pie()) {
$info['Pie Pagado'] = $venta->pie()->valorPagado('uf');
$info['% Pie Pagado'] = $venta->pie()->valorPagado('uf') / $venta->valor_uf;
}
$info['Bono Pie'] = ($venta->bono_pie == 0 or $venta->bonoPie() === false) ? '' : $venta->bonoPie()->pago()->valor('ufs');
$info['Operador'] = ($venta->agente and $venta->agente()->agente()->tipo == 19) ? $venta->agente()->agente()->descripcion : '';
$info['Valor Operador'] = $venta->valorComision();
//$promos = 0;
$ps = $venta->promociones();
$info['Premios'] = array_reduce($ps, function($sum, $item) {
return $sum + $item->valor;
});
$info['Subsidio'] = 0;
$info['Ahorro'] = 0;
if ($venta->subsidio != 0) {
$info['Subsidio'] = $venta->subsidio()->subsidio()->valor('ufs');
$info['Ahorro'] = $venta->subsidio()->pago()->valor('ufs');
}
$info['Credito'] = 0;
$info['Banco'] = '';
if ($venta->credito != 0) {
$info['Credito'] = $venta->credito()->pago()->valor('ufs');
if ($venta->credito()->pago()->banco != 0) {
$info['Banco'] = $venta->credito()->pago()->banco()->nombre;
}
}
$info['Valor Ests & Bods'] = $venta->valorEstacionamientosYBodegas();
$info['Valor Neto'] = $venta->valorFinal();
$info['UF/m²*'] = $venta->uf_m2();
$info['Comision'] = $venta->valorFinal() * $comision;
$info['Venta s/Comision'] = $venta->valorFinal() - $info['Comision'];
$fecha = $venta->fecha();
$info['Precio'] = 0;
try {
$info['Precio'] = array_reduce($venta->propiedad()->departamentos(), function($sum, $item) use ($fecha) {
return $sum + $item->precio($fecha)->valor;
});
} catch (\Exception $e) {
}
$data []= $info;
}
$body = [
"Proyecto" => $proyecto->descripcion,
"Compañía" => $proyecto->inmobiliaria()->abreviacion,
"data" => $data
];
$client = new Client(['base_uri' => 'localhost:8011']);
$response = $client->post('/ventas', ['json' => $body]);
header("Content-Type: application/octet-stream; charset=utf-8");
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: max-age=0');
return $response->getBody();
//file_put_contents('php://output', $output);
} else {
$proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many();
return view('informes.ventas', compact('proyectos'));
}
}
public static function resumen_contabilidad()
{
if (get('proyecto')) {
$id = get('proyecto');
$proyecto = model(Proyecto::class)->findOne($id);
$fecha = get('fecha');
$mes = null;
if ($fecha != null) {
$mes = Carbon::parse($fecha)->addMonths(1)->subDays(1);
}
$ventas = $proyecto->ventas();
usort($ventas, function($a, $b) {
return $a->fecha()->timestamp - $b->fecha()->timestamp;
});
$name = 'Contabilidad';
$hoy = Carbon::now(config('app.timezone'));
$filename = str_replace('ñ', 'n', $name . ' - ' . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls');
$informe = new PHPExcel($name, $filename);
$columnas = [
'Propietario',
['name' => 'Departamento', 'style' => 'general_number'],
['name' => 'Estacionamientos', 'style' => 'number'],
['name' => 'Bodegas', 'style' => 'number'],
'Fecha Venta',
['name' => 'Mes', 'style' => 'mes'],
'Tipo',
['name' => 'm² Ponderados', 'style' => 'amount'],
['name' => 'Valor Promesa', 'style' => 'amount'],
['name' => 'Pie [UF]', 'style' => 'amount'],
['name' => 'Pie [$]', 'style' => 'amount'],
['name' => 'Abono Escritura', 'style' => 'amount'],
['name' => 'Crédito', 'style' => 'amount'],
['name' => 'Cuotas', 'style' => 'number'],
['name' => 'Cuotas Pagadas', 'style' => 'number'],
['name' => 'Pie Pagado [UF]', 'style' => 'amount'],
['name' => 'Pie Pagado [$]', 'style' => 'amount']
];
$informe->addColumns($columnas);
$data = [];
foreach ($ventas as $venta) {
$info = [];
$info['Propietario'] = mb_strtoupper($venta->propietario()->nombreCompleto());
$info['Departamento'] = $venta->unidad()->descripcion;
$ests = [];
if ($venta->propiedad()->estacionamientos != '') {
$es = $venta->propiedad()->estacionamientos();
foreach ($es as $e) {
$ests []= $e->descripcion;
}
}
$info['Estacionamientos'] = implode(', ', $ests);
$bods = [];
if ($venta->propiedad()->bodegas != '') {
$bs = $venta->propiedad()->bodegas();
foreach ($bs as $b) {
$bods []= $b->descripcion;
}
}
$info['Bodegas'] = implode(', ', $bods);
$info['Fecha Venta'] = $venta->fecha()->format('d.m.Y');
$info['Mes'] = $venta->fecha()->format('M-y');
$info['Tipo'] = $venta->unidad()->abreviacion;
$info['m² Ponderados'] = $venta->unidad()->m2('vendible');
$info['Valor Promesa'] = $venta->valor_uf;
$info['Pie [UF]'] = 0;
$info['Pie [$]'] = 0;
$info['Abono Escritura'] = 0;
$info['Crédito'] = 0;
$info['Cuotas'] = 0;
$info['Cuotas Pagadas'] = 0;
$info['Pie Pagado [UF]'] = 0;
$info['Pie Pagado [$]'] = 0;
if ($venta->pie()) {
$info['Pie [UF]'] = $venta->pie()->valor;
$info['Pie [$]'] = $venta->pie()->valorPesos();
$info['Abono Escritura'] = ($venta->escritura != 0) ? $venta->escritura()->valor('ufs') : ($venta->valor_uf - $venta->pie()->valor - (($venta->credito != 0) ? $venta->credito()->pago()->valor('ufs') : 0));
$info['Crédito'] = ($venta->credito != 0) ? $venta->credito()->pago()->valor('ufs') : 0;
$info['Cuotas'] = $venta->pie()->cuotas;
$info['Cuotas Pagadas'] = count($venta->pie()->pagadas($mes));
$info['Pie Pagado [UF]'] = $venta->pie()->valorPagado('uf', $mes);
$info['Pie Pagado [$]'] = $venta->pie()->valorPagado('pesos', $mes);
}
$data []= $info;
}
$informe->addData($data);
$totals = [
'Departamento' => 'count',
'Estacionamientos' => 'count',
'Bodegas' => 'count',
'm² Ponderados' => 'sum',
'Valor Promesa' => 'sum',
'Pie' => 'sum',
'Pie Pagado' => 'sum'
];
$informe->addTotals($totals);
return $informe->informe();
} else {
$proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many();
return view('informes.resumen_contabilidad', compact('proyectos'));
}
}
public static function contabilidad()
{
if (get('proyecto')) {
$id = get('proyecto');
$fecha = get('fecha');
$mes = null;
if ($fecha != null) {
$mes = Carbon::parse($fecha);
}
$proyecto = model(Proyecto::class)->findOne($id);
$q = "SELECT pago.*, venta.id AS vid, venta.tipo AS ctipo, venta.pie AS pie
FROM (
SELECT pago.id, banco.nombre AS banco, pago.fecha, pago.valor, pago.uf, ep.estado, ep.fecha AS efecha
FROM pago JOIN banco ON banco.id = pago.banco JOIN ((
SELECT pago, MAX(id) AS id FROM estado_pago GROUP BY pago) e0 JOIN estado_pago ep ON ep.id = e0.id) ON ep.pago = pago.id
WHERE ep.estado > 0 ";
if ($mes != null) {
$q .= "AND (pago.fecha BETWEEN '" . $mes->format('Y-m-01') . "' AND '" . $mes->format('Y-m-t') . "'
OR ep.fecha BETWEEN '" . $mes->format('Y-m-01') . "' AND '" . $mes->format('Y-m-t') . "')";
}
$q .= ") pago JOIN (SELECT venta.*
FROM ((
SELECT venta.id, venta.pie, venta.propiedad, credito.pago, 'credito' AS tipo
FROM venta JOIN credito ON credito.id = venta.credito)
UNION ALL (
SELECT venta.id, venta.pie, venta.propiedad, escritura.pago, 'escritura' AS tipo
FROM venta JOIN escritura ON escritura.id = venta.escritura)
UNION ALL (
SELECT venta.id, venta.pie, venta.propiedad, cuota.pago, 'cuota' AS tipo
FROM venta JOIN cuota ON cuota.pie = venta.pie)) venta
JOIN propiedad ON propiedad.id = venta.propiedad
JOIN unidad ON unidad.id = propiedad.unidad_principal
WHERE unidad.proyecto = ?) venta
ON venta.pago = pago.id";
$st = \ORM::getDB()->prepare($q);
$st->execute([$id]);
if ($st->rowCount() > 0) {
$R = $st->fetchAll(\PDO::FETCH_OBJ);
//$informe = new Informador('Contabilidad - ' . (($mes != null) ? $mes->format('Y-m') . ' - ' : '') . $proyecto->descripcion);
$name = 'Contabilidad';
$hoy = Carbon::now(config('app.timezone'));
$filename = str_replace('ñ', 'n', 'Contabilidad - ' . (($mes != null) ? $mes->format('Y-m') . ' - ' : '') . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls');
$informe = new PHPExcel($name, $filename);
$columnas = ['Proyecto', 'Fecha', 'Banco', 'Departamento', 'RUT', 'Propietario', 'Glosa', 'Glosa2', (object) ['name' => 'Valor', 'style' => 'integer'], (object) ['name' => 'Valor UF', 'style' => 'currency']];
$informe->addColumns($columnas);
$data = [];
foreach ($R as $r) {
$info = [];
$info['Proyecto'] = $proyecto->descripcion;
$f1 = \Carbon\Carbon::parse($r->fecha, config('app.timezone'));
$f2 = \Carbon\Carbon::parse($r->efecha, config('app.timezone'));
$info['Fecha'] = ($f1->max($f2))->format('Y-m-d');
$info['Banco'] = $r->banco;
$venta = model(Venta::class)->findOne($r->vid);
$info['Departamento'] = $venta->unidad()->descripcion;
$info['RUT'] = $venta->propietario()->rut();
$info['Propietario'] = $venta->propietario()->nombreCompleto();
$info['Glosa'] = ucwords($r->ctipo);
$info['Glosa2'] = '';
if ($r->ctipo == 'cuota') {
$cuota = model(Cuota::class)->where('pago', $r->id)->findOne();
$info['Glosa'] = 'Pie - ' . format('ufs', $cuota->pie()->valor('ufs'), null, true);
$info['Glosa2'] = $cuota->numero() . ' - ' . $cuota->pie()->cuotas;
}
$info['Valor'] = $r->valor;
$info['Valor UF'] = '0';
if ($r->uf > 0) {
$info['Valor UF'] = $r->valor / $r->uf;
}
$data []= $info;
}
$informe->addData($data);
return $informe->informe();
}
} else {
setlocale(LC_TIME, 'es_ES');
$proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many();
return view('informes.contabilidad', compact('proyectos'));
}
}
public static function para_comision()
{
$proyectos = model(Proyecto::class)->orderByAsc('descripcion')->findMany();
return view('informes.para_comision', compact('proyectos'));
}
public static function comisiones()
{
$id = post('proyecto');
$proyecto = model(Proyecto::class)->findOne($id);
$unidades = explode('-', str_replace([';', '.', ':', ' ', PHP_EOL, '|', '+', ','], '-', post('unidades')));
$ventas = model(Venta::class)
->select('venta.*')
->join('propiedad', ['propiedad.id', '=', 'venta.propiedad'])
->join('unidad', ['unidad.id', '=', 'propiedad.unidad_principal'])
->where('unidad.proyecto', $proyecto->id)
->where('venta.estado', 1)
->whereIn('unidad.descripcion', $unidades)
->orderByExpr('FIELD(unidad.descripcion, ' . implode(', ', $unidades) . ')')
->findMany();
$ids = [];
$totales = (object) ['precio' => 0, 'neto' => 0, 'comision' => 0];
foreach ($ventas as $venta) {
$ids []= $venta->id;
$totales->precio += $venta->valor_uf;
$totales->neto += $venta->valorCorredora();
$totales->comision += $venta->valorCorredora() * 1.5 / 100;
}
return view('informes.comisiones', compact('ventas', 'proyecto', 'totales', 'ids'));
}
public static function comisiones_xlsx()
{
$id_ventas = explode(',', get('ventas'));
$ventas = model(Venta::class)
->whereIn('id', $id_ventas)
->orderByExpr('FIELD(id, ' . implode(', ', $id_ventas) . ')')
->findMany();
$informe = new Informador('Comisiones - ' . $ventas[0]->proyecto()->descripcion);
$columnas = ['Departamento', 'Estacionamientos', 'Bodegas', 'Propietario', 'Precio', '% Com', 'Com UF'];
$informe->addColumns($columnas);
$data = [];
foreach ($ventas as $venta) {
$info = [];
$info['Departamento'] = $venta->unidad()->descripcion;
$info['Estacionamientos'] = implode(' - ', $venta->propiedad()->estacionamientos('array'));
$info['Bodegas'] = implode(' - ', $venta->propiedad()->bodegas('array'));
$info['Propietario'] = $venta->propietario()->nombreCompleto();
$info['Precio'] = "'" . format('ufs', $venta->valorCorredora());
$info['% Com'] = '1,5 %';
$info['Com UF'] = "'" . format('ufs', $venta->valorCorredora() * 1.5 / 100);
$data []= $info;
}
$informe->addDatas($data);
return $informe->informe();
}
public static function cuotas()
{
$id_venta = get('venta');
$venta = model(Venta::class)->findOne($id_venta);
$name = 'Cuotas - ' . $venta->unidad()->descripcion;
$hoy = Carbon::now(config('app.timezone'));
$filename = str_replace('ñ', 'n', $name . ' - ' . $venta->proyecto()->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls');
$informe = new PHPExcel($name, $filename);
$columnas = [
['name' => 'Cuota', 'style' => 'number'],
['name' => 'Fecha Cuota', 'style' => 'date'],
'Banco',
'Identificador',
['name' => 'Valor $', 'style' => 'number'],
['name' => 'Valor UF', 'style' => 'currency'],
['name' => 'Fecha Pago', 'style' => 'date']
];
$informe->addColumns($columnas);
$data = [];
foreach ($venta->pie()->cuotas() as $cuota) {
$info = [];
$info['Cuota'] = $cuota->numero();
$info['Fecha Cuota'] = $cuota->pago()->fecha()->format('Y-m-d');
$info['Banco'] = $cuota->pago()->banco()->descripcion;
$info['Identificador'] = $cuota->pago()->identificador;
$info['Valor $'] = $cuota->pago()->valor();
$info['Valor UF'] = $cuota->pago()->valor('ufs');
$info['Fecha Pago'] = $cuota->pago()->estado()->fecha()->format('Y-m-d');
$data []= $info;
}
$informe->addData($data);
return $informe->informe();
}
public static function resciliaciones()
{
if (get('proyecto')) {
$id = get('proyecto');
$proyecto = model(Proyecto::class)->findOne($id);
$ventas = $proyecto->resciliaciones();
usort($ventas, function($a, $b) {
return $a->fecha()->timestamp - $b->fecha()->timestamp;
});
$name = 'Resciliaciones';
$hoy = Carbon::now(config('app.timezone'));
$filename = str_replace('ñ', 'n', $name . ' - ' . $proyecto->descripcion . ' - ' . $hoy->format('Y-m-d') . '.xls');
$informe = new PHPExcel($name, $filename);
$columnas = [
'Propietario',
['name' => 'Departamento', 'style' => 'number'],
['name' => 'Estacionamientos', 'style' => 'number'],
['name' => 'Bodegas', 'style' => 'number'],
'Fecha Venta',
'Fecha Resciliación',
['name' => 'Mes', 'style' => 'mes'],
'Tipo',
['name' => 'm² Ponderados', 'style' => 'amount'],
['name' => 'Valor Promesa', 'style' => 'amount'],
];
$informe->addColumns($columnas);
$data = [];
foreach ($ventas as $venta) {
$info = [];
$info['Propietario'] = mb_strtoupper($venta->propietario()->nombreCompleto());
$info['Departamento'] = $venta->unidad()->descripcion;
$ests = [];
if ($venta->propiedad()->estacionamientos != '') {
$es = $venta->propiedad()->estacionamientos();
foreach ($es as $e) {
$ests []= $e->descripcion;
}
}
$info['Estacionamientos'] = implode(', ', $ests);
$bods = [];
if ($venta->propiedad()->bodegas != '') {
$bs = $venta->propiedad()->bodegas();
foreach ($bs as $b) {
$bods []= $b->descripcion;
}
}
$info['Bodegas'] = implode(', ', $bods);
$info['Fecha Venta'] = $venta->fecha()->format('d.m.Y');
$info['Fecha Resciliación'] = $venta->estado()->fecha()->format('d.m.Y');
$info['Mes'] = $venta->estado()->fecha()->format('M-y');
$info['Tipo'] = $venta->unidad()->abreviacion;
$info['m² Ponderados'] = $venta->unidad()->m2('vendible');
$info['Valor Promesa'] = $venta->valor_uf;
$data []= $info;
}
$informe->addData($data);
$totals = [
'Departamento' => 'count',
'Estacionamientos' => 'count',
'Bodegas' => 'count',
'm² Ponderados' => 'sum',
'Valor Promesa' => 'sum'
];
$informe->addTotals($totals);
return $informe->informe();
} else {
$proyectos = model(Proyecto::class)->order_by_asc('descripcion')->find_many();
return view('informes.resciliaciones', compact('proyectos'));
}
}
}