Venta->Listado->Cierres

This commit is contained in:
Juan Pablo Vial
2023-07-25 17:03:57 -04:00
parent 1a7b10ce3c
commit 43cd955061
12 changed files with 596 additions and 5 deletions

View File

@ -0,0 +1,6 @@
<?php
use Incoviba\Controller\Ventas\Cierres;
$app->group('/cierres', function($app) {
$app->post('[/]', [Cierres::class, 'proyecto']);
});

View File

@ -0,0 +1,6 @@
<?php
use Incoviba\Controller\Ventas\Cierres;
$app->group('/cierres', function($app) {
$app->get('[/]', Cierres::class);
});

View File

@ -0,0 +1,360 @@
@extends('layout.base')
@section('page_title')
Cierres - Listado
@endsection
@section('page_content')
<div class="ui container">
<h2 class="ui header">Listado de Cierres</h2>
<table class="ui striped table" id="cierres">
<thead>
<tr>
<th colspan="5">Proyecto</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
@endsection
@push('page_styles')
<style>
.proyecto, .estado-cierres {
cursor: pointer;
}
</style>
@endpush
@push('page_scripts')
<script type="text/javascript">
class Cierre {
id
proyecto_id
estado = {
id: 0,
descripcion: '',
titulo: ''
}
departamento
tipologia
vendible
fecha
valor
unitario() {
return this.valor / this.vendible
}
draw(formatter) {
const date = new Date(this.fecha)
const dateFormatter = new Intl.DateTimeFormat('es-CL')
const estado = this.estado.titulo.charAt(0).toUpperCase() + this.estado.titulo.slice(1)
return $('<tr></tr>').addClass('cierre ' + this.estado.descripcion).attr('data-proyecto', this.proyecto_id).attr('data-estado', this.estado.id).append(
$('<td></td>')
).append(
$('<td></td>').append(
$('<a></a>').attr('href', '{{$urls->base}}/ventas/cierre/' + this.id).html(this.departamento + ' (' + this.tipologia + ')')
)
).append(
$('<td></td>').html(dateFormatter.format(date))
).append(
$('<td></td>').html(formatter.format(this.valor) + ' UF (' + formatter.format(this.unitario()) + ' UF/m²)')
).append(
$('<td></td>').html(estado)
)
}
}
class Estado {
id
proyecto_id
title
descripcion
cierres = []
total = 0
proporcion() {
return this.cierres.length / this.total * 100
}
add(data) {
let cierre = this.cierres.find(cierre => cierre.id === data.id)
if (typeof cierre !== 'undefined') {
return
}
cierre = new Cierre()
cierre.id = data.id
cierre.proyecto_id = this.proyecto_id
cierre.departamento = ''
cierre.tipologia = ''
cierre.vendible = 0
const departamento = data.unidades.filter(unidad => unidad.proyecto_tipo_unidad.tipo_unidad.descripcion === 'departamento')[0]
if (typeof departamento !== 'undefined') {
cierre.departamento = departamento.descripcion
cierre.tipologia = departamento.proyecto_tipo_unidad.abreviacion
cierre.vendible = departamento.proyecto_tipo_unidad.vendible
}
cierre.fecha = data.date_time
cierre.valor = data.precio
cierre.estado.id = this.id
cierre.estado.descripcion = this.descripcion
cierre.estado.titulo = data.estado_cierre.tipo_estado_cierre.descripcion
this.cierres.push(cierre)
}
draw(tbody, formatter) {
tbody.append(
$('<tr></tr>').addClass('estado-cierres ' + this.descripcion).attr('data-proyecto', this.proyecto_id).attr('data-estado', this.id).attr('data-status', 'closed').append(
$('<th></th>')
).append(
$('<th></th>').attr('colspan', 4).html(this.title).append(
$('<i></i>').addClass('right caret icon')
).append(' [' + this.cierres.length + '] ' + formatter.format(this.proporcion()) + '%')
)
)
tbody.append(
$('<tr></tr>').addClass('cierre').attr('data-proyecto', this.proyecto_id).attr('data-estado', this.id).append(
$('<th></th>')
).append(
$('<th></th>').html('Departamento')
).append(
$('<th></th>').html('Fecha')
).append(
$('<th></th>').html('Valor')
).append(
$('<th></th>').html('Estado')
)
)
this.cierres.forEach(cierre => {
tbody.append(cierre.draw(formatter))
})
}
}
class Proyecto {
id
descripcion
total = 0
estados
constructor({id, descripcion}) {
this.id = id
this.descripcion = descripcion
this.estados = {
aprobado: new Estado(),
promesado: new Estado(),
rechazado: new Estado()
}
this.estados.aprobado.id = 1
this.estados.aprobado.proyecto_id = this.id
this.estados.aprobado.title = 'Aprobado'
this.estados.aprobado.descripcion = 'warning'
this.estados.promesado.id = 2
this.estados.promesado.proyecto_id = this.id
this.estados.promesado.title = 'Promesado'
this.estados.promesado.descripcion = 'positive'
this.estados.rechazado.id = 3
this.estados.rechazado.proyecto_id = this.id
this.estados.rechazado.title = 'Abandonado/Rechazado'
this.estados.rechazado.descripcion = 'error'
}
add(data) {
if (data.proyecto.id !== this.id) {
return
}
this.total ++
if (['revisado', 'aprobado'].includes(data.estado_cierre.tipo_estado_cierre.descripcion)) {
return this.estados.aprobado.add(data)
}
if (['vendido', 'promesado'].includes(data.estado_cierre.tipo_estado_cierre.descripcion)) {
return this.estados.promesado.add(data)
}
this.estados.rechazado.add(data)
}
draw(tbody, formatter) {
tbody.append(
$('<tr></tr>').append(
$('<td></td>').addClass('proyecto').attr('data-proyecto', this.id).attr('data-status', 'closed').attr('colspan', 5).html(this.descripcion).append(
$('<i></i>').addClass('right caret icon')
).append(' [' + this.total + ']')
)
)
Object.keys(this.estados).forEach(key => {
this.estados[key].total = this.total
this.estados[key].draw(tbody, formatter)
})
}
}
const cierres = {
ids: {
table: '',
},
data: {
proyectos: []
},
get: function() {
return {
proyectos: () => {
this.data.proyectos = []
this.draw().loading()
return fetch('{{$urls->api}}/proyectos').then(response => {
if (response.ok) {
return response.json()
}
}).then(data => {
const promises = []
if (data.total > 0) {
data.proyectos.forEach(proyecto => {
promises.push(this.get().cierres(proyecto.id))
})
return promises
}
}).then(promises => {
Promise.all(promises).then(() => {
this.data.proyectos.sort((a, b) => {
return a.descripcion.localeCompare(b.descripcion)
})
this.draw().proyectos()
})
})
},
cierres: proyecto_id => {
return fetch('{{$urls->api}}/ventas/cierres',
{method: 'post', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({proyecto_id})}).then(response => {
if (response.ok) {
return response.json()
}
}).then(data => {
if (data.total > 0) {
data.cierres.forEach(cierre => {
this.add().cierre(cierre)
})
}
})
},
}
},
add: function() {
return {
cierre: data => {
let proyecto = this.data.proyectos.find(proyecto => proyecto.id === data.proyecto.id)
if (this.data.proyectos.length === 0 || typeof proyecto === 'undefined') {
proyecto = new Proyecto({
id: data.proyecto.id,
descripcion: data.proyecto.descripcion
})
this.data.proyectos.push(proyecto)
}
proyecto.add(data)
}
}
},
draw: function() {
return {
proyectos: () => {
const parent = $(this.ids.table)
const formatter = new Intl.NumberFormat('es-CL', {minimumFractionDigits: 2, maximumFractionDigits: 2})
const tbody = parent.find('tbody')
tbody.html('')
this.data.proyectos.forEach(proyecto => {
proyecto.draw(tbody, formatter)
})
tbody.find('.estado-cierres, .cierre').hide()
tbody.find('.proyecto').click(this.actions().proyectos().toggle)
tbody.find('.estado-cierres').click(this.actions().estados().toggle)
},
loading: () => {
const parent = $(this.ids.table)
const tbody = parent.find('tbody')
tbody.append(
$('<tr></tr>').append(
$('<td></td>').attr('colspan', 5).append(
$('<div></div>').addClass('ui basic segment').append(
$('<div></div>').addClass('ui active dimmer').append(
$('<div></div>').addClass('ui loader')
)
).append(
$('<div></div>').addClass('ui fluid placeholder').append(
$('<div></div>').addClass('image')
)
)
)
)
)
}
}
},
actions: function() {
return {
proyectos: () => {
return {
open: event => {
const th = $(event.currentTarget)
const proyecto_id = th.data('proyecto')
th.find('.icon').removeClass('right').addClass('down')
$(".estado-cierres[data-proyecto='" + proyecto_id + "']").show()
th.attr('data-status', 'open')
},
close: event => {
const th = $(event.currentTarget)
const proyecto_id = th.data('proyecto')
th.find('.icon').removeClass('down').addClass('right')
$(".estado-cierres[data-proyecto='" + proyecto_id + "']").hide()
$(".cierre[data-proyecto='" + proyecto_id + "']").hide()
th.attr('data-status', 'closed')
},
toggle: event => {
const th = $(event.currentTarget)
const status = th.attr('data-status')
if (status === 'closed') {
return this.actions().proyectos().open(event)
}
return this.actions().proyectos().close(event)
}
}
},
estados: () => {
return {
open: event => {
const tr = $(event.currentTarget)
const proyecto_id = tr.data('proyecto')
const estado_id = tr.data('estado')
tr.find('.icon').removeClass('right').addClass('down')
$(".cierre[data-proyecto='" + proyecto_id + "'][data-estado='" + estado_id + "']").show()
tr.attr('data-status', 'open')
},
close: event => {
const tr = $(event.currentTarget)
const proyecto_id = tr.data('proyecto')
const estado_id = tr.data('estado')
tr.find('.icon').removeClass('down').addClass('right')
$(".cierre[data-proyecto='" + proyecto_id + "'][data-estado='" + estado_id + "']").hide()
tr.attr('data-status', 'closed')
},
toggle: event => {
const tr = $(event.currentTarget)
const status = tr.attr('data-status')
if (status === 'closed') {
return this.actions().estados().open(event)
}
return this.actions().estados().close(event)
}
}
}
}
},
setup: function() {
this.get().proyectos()
}
}
$(document).ready(() => {
cierres.ids.table = '#cierres'
cierres.setup()
})
</script>
@endpush

View File

@ -0,0 +1,24 @@
<?php
namespace Incoviba\Controller\Ventas;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Service;
class Cierres
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, View $view): ResponseInterface
{
return $view->render($response, 'ventas.cierres.list');
}
public function proyecto(ServerRequestInterface $request, ResponseInterface $response, Service\Ventas\Cierre $service): ResponseInterface
{
$body = $request->getBody();
$json = json_decode($body->getContents());
$proyecto_id = $json->proyecto_id;
$cierres = $service->getByProyecto($proyecto_id);
$response->getBody()->write(json_encode(['cierres' => $cierres, 'total' => count($cierres)]));
return $response->withHeader('Content-Type', 'application/json');
}
}

View File

@ -13,14 +13,22 @@ class Cierre extends Ideal\Model
public bool $relacionado;
public Propietario $propietario;
public array $estados = [];
public ?EstadoCierre $current = null;
public array $unidades = [];
public function jsonSerialize(): mixed
{
return array_merge(parent::jsonSerialize(), [
'proyecto_id' => $this->proyecto->id,
'proyecto' => $this->proyecto,
'precio' => $this->precio,
'date_time' => $this->dateTime->format('Y-m-d H:i:s'),
'relacionado' => $this->relacionado,
'propietario' => $this->propietario->rut
'propietario' => $this->propietario->rut,
'estados' => $this->estados,
'estado_cierre' => $this->current,
'unidades' => $this->unidades
]);
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace Incoviba\Model\Venta;
use DateTimeInterface;
use Incoviba\Common\Ideal;
class EstadoCierre extends Ideal\Model
{
public Cierre $cierre;
public TipoEstadoCierre $tipoEstadoCierre;
public DateTimeInterface $fecha;
public function jsonSerialize(): mixed
{
return array_merge(parent::jsonSerialize(), [
'cierre_id' => $this->cierre->id,
'tipo_estado_cierre' => $this->tipoEstadoCierre,
'fecha' => $this->fecha->format('Y-m-d')
]);
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace Incoviba\Model\Venta;
use Incoviba\Model;
class TipoEstadoCierre extends Model\Tipo
{
public bool $vigente;
public function jsonSerialize(): mixed
{
return array_merge(parent::jsonSerialize(), [
'vigente' => $this->vigente
]);
}
}

View File

@ -71,7 +71,7 @@ FROM `{$this->getTable()}` a
FROM `estado_cierre` e1
JOIN (SELECT MAX(`id`) AS id, `cierre` FROM `estado_cierre` GROUP BY `cierre`) e0 ON e0.`id` = e1.`id`) ec ON ec.`cierre` = a.`id`
JOIN `tipo_estado_cierre` tec ON tec.`id` = ec.`tipo`
JOIN `proyecto` ON `proyecto`.`id` = a.`proyecto`
JOIN `proyecto` ON `proyecto`.`id` = a.`proyecto` AND tec.`descripcion` NOT IN ('revisado')
GROUP BY `proyecto`.`descripcion`, tec.`descripcion`";
$results = $this->connection->execute($query)->fetchAll(PDO::FETCH_ASSOC);
if ($results === false) {
@ -79,4 +79,15 @@ GROUP BY `proyecto`.`descripcion`, tec.`descripcion`";
}
return $results;
}
public function fetchByProyecto(int $proyecto_id): array
{
$query = "SELECT a.*
FROM `{$this->getTable()}` a
JOIN (SELECT e1.*
FROM `estado_cierre` e1
JOIN (SELECT MAX(`id`) AS id, `cierre` FROM `estado_cierre` GROUP BY `cierre`) e0 ON e0.`id` = e1.`id`) ec ON ec.`cierre` = a.`id`
JOIN `tipo_estado_cierre` tec ON tec.`id` = ec.`tipo`
WHERE `proyecto` = ? AND tec.`descripcion` NOT IN ('revisado')";
return $this->fetchMany($query, [$proyecto_id]);
}
}

View File

@ -0,0 +1,66 @@
<?php
namespace Incoviba\Repository\Venta;
use DateTimeImmutable;
use Incoviba\Common\Ideal;
use Incoviba\Common\Define;
use Incoviba\Model;
use Incoviba\Repository;
class EstadoCierre extends Ideal\Repository
{
public function __construct(Define\Connection $connection, protected Repository\Venta\Cierre $cierreRepository, protected Repository\Venta\TipoEstadoCierre $tipoEstadoCierreRepository)
{
parent::__construct($connection);
$this->setTable('estado_cierre');
}
public function create(?array $data = null): Define\Model
{
$map = [
'cierre' => [
'function' => function($data) {
return $this->cierreRepository->fetchById($data['cierre']);
}
],
'tipo' => [
'property' => 'tipoEstadoCierre',
'function' => function($data) {
return $this->tipoEstadoCierreRepository->fetchById($data['tipo']);
}
],
'fecha' => [
'function' => function($data) {
return new DateTimeImmutable($data['fecha']);
}
]
];
return $this->parseData(new Model\Venta\EstadoCierre(), $data, $map);
}
public function save(Define\Model $model): Define\Model
{
$model->id = $this->saveNew(
['cierre', 'tipo', 'fecha'],
[$model->cierre->id, $model->tipoEstadoCierre->id, $model->fecha->format('Y-m-d')]
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Define\Model
{
return $this->update($model, ['cierre', 'tipo', 'fecha'], $new_data);
}
public function fetchByCierre(int $cierre_id): array
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `cierre` = ?";
return $this->fetchMany($query, [$cierre_id]);
}
public function fetchCurrentByCierre(int $cierre_id): Define\Model
{
$query = "SELECT e1.*
FROM `{$this->getTable()}` e1
JOIN (SELECT MAX(`id`) AS 'id', `cierre` FROM `{$this->getTable()}` GROUP BY `cierre`) e0 ON e0.`id` = e1.`id`
WHERE e1.`cierre` = ?";
return $this->fetchOne($query, [$cierre_id]);
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace Incoviba\Repository\Venta;
use Incoviba\Common\Ideal;
use Incoviba\Common\Define;
use Incoviba\Model;
class TipoEstadoCierre extends Ideal\Repository
{
public function __construct(Define\Connection $connection)
{
parent::__construct($connection);
$this->setTable('tipo_estado_cierre');
}
public function create(?array $data = null): Define\Model
{
$map = [
'descripcion' => [],
'vigente' => [
'function' => function($data) {
return $data['vigente'] != 0;
}
]
];
return $this->parseData(new Model\Venta\TipoEstadoCierre(), $data, $map);
}
public function save(Define\Model $model): Define\Model
{
$model->id = $this->saveNew(
['descripcion', 'vigente'],
[$model->descripcion, $model->vigente ? 1 : 0]
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Define\Model
{
return $this->update($model, ['descripcion', 'vigente'], $new_data);
}
}

View File

@ -30,7 +30,6 @@ class Unidad extends Ideal\Repository
];
return $this->parseData(new Model\Venta\Unidad(), $data, $map);
}
public function save(Define\Model $model): Define\Model
{
$model->id = $this->saveNew(
@ -39,9 +38,20 @@ class Unidad extends Ideal\Repository
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Define\Model
{
return $this->update($model, ['subtipo', 'piso', 'descripcion', 'orientacion', 'pt'], $new_data);
}
public function fetchByCierre(int $cierre_id): array
{
$query = "SELECT a.*
FROM `{$this->getTable()}` a
JOIN `unidad_cierre` uc ON uc.`unidad` = a.`id`
JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = a.`pt`
JOIN `tipo_unidad` tu ON tu.`id` = ptu.`tipo`
WHERE uc.`cierre` = ?
ORDER BY tu.`orden`, LPAD(a.`descripcion`, 4, '0')";
return $this->fetchMany($query, [$cierre_id]);
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Incoviba\Service\Ventas;
use Incoviba\Repository;
class Cierre
{
public function __construct(
protected Repository\Venta\Cierre $cierreRepository,
protected Repository\Venta\EstadoCierre $estadoCierreRepository,
protected Repository\Venta\Unidad $unidadRepository) {}
public function getByProyecto(int $proyecto_id): array
{
$cierres = $this->cierreRepository->fetchByProyecto($proyecto_id);
foreach ($cierres as &$cierre) {
$cierre->estados = $this->estadoCierreRepository->fetchByCierre($cierre->id);
$cierre->current = $this->estadoCierreRepository->fetchCurrentByCierre($cierre->id);
$cierre->unidades = $this->unidadRepository->fetchByCierre($cierre->id);
}
return $cierres;
}
}