Search update and optimization

This commit is contained in:
2023-11-23 23:35:19 -03:00
parent bf03e85975
commit e1ef31dccd
10 changed files with 232 additions and 36 deletions

View File

@ -45,6 +45,7 @@
draw() { draw() {
const tipo = this.unidad.proyecto_tipo_unidad.tipo_unidad.descripcion const tipo = this.unidad.proyecto_tipo_unidad.tipo_unidad.descripcion
let unidad = tipo.charAt(0).toUpperCase() + tipo.slice(1) + ' ' + this.unidad.descripcion let unidad = tipo.charAt(0).toUpperCase() + tipo.slice(1) + ' ' + this.unidad.descripcion
let precio = 0
let propietario = '' let propietario = ''
let fecha = '' let fecha = ''
let fecha_entrega = '' let fecha_entrega = ''
@ -61,8 +62,10 @@
if (typeof this.venta.entrega !== 'undefined') { if (typeof this.venta.entrega !== 'undefined') {
fecha_entrega = dateFormatter.format(new Date(this.venta.entrega.fecha)) fecha_entrega = dateFormatter.format(new Date(this.venta.entrega.fecha))
} }
precio = this.venta.valor
} else { } else {
unidad += '<i class="ban icon"></i>' unidad += '<i class="ban icon"></i>'
precio = this.unidad.current_precio.valor
} }
const numberFormat = new Intl.NumberFormat('es-CL', {minimumFractionDigits: 2, maximumFractionDigits: 2}) const numberFormat = new Intl.NumberFormat('es-CL', {minimumFractionDigits: 2, maximumFractionDigits: 2})
@ -81,7 +84,7 @@
).append( ).append(
$('<td></td>').addClass('right aligned').html(superficie + ' m&#0178;') $('<td></td>').addClass('right aligned').html(superficie + ' m&#0178;')
).append( ).append(
$('<td></td>').addClass('right aligned').html(numberFormat.format(this.unidad.precio)) $('<td></td>').addClass('right aligned').html(numberFormat.format(precio))
).append( ).append(
$('<td></td>').html(fecha) $('<td></td>').html(fecha)
).append( ).append(
@ -104,29 +107,84 @@
const uri = '{{$urls->api}}/search' const uri = '{{$urls->api}}/search'
this.data = [] this.data = []
return fetch(uri, {method: 'post', body: data}).then(response => { return fetch(uri, {method: 'post', body: data}).then(response => {
this.draw().clear()
if (response.ok) { if (response.ok) {
return response.json() return response.json()
} }
}).catch(error => {
this.draw().clear()
this.draw().error(error)
}).then(data => { }).then(data => {
if (typeof data.results !== 'undefined' && data.results.length > 0) { this.draw().clear()
data.results.forEach(row => { if (typeof data.results === 'undefined' || data.results.length === 0) {
if (typeof row.proyecto_tipo_unidad === 'undefined') { this.draw().empty()
const r = new Row({unidad: row.propiedad.departamentos[0], proyecto: row.proyecto})
r.venta = row
this.data.push(r)
} else {
this.data.push(new Row({unidad: row, proyecto: row.proyecto_tipo_unidad.proyecto}))
}
})
this.draw().table()
return return
} }
this.draw().empty() const progress = this.draw().progress(data.results.length)
const promises = []
data.results.forEach(row => {
if (row.tipo === 'venta') {
promises.push(this.get().venta(row.id).then(json => {
const venta = json.venta
progress.progress('increment')
const r = new Row({unidad: venta.propiedad.unidades[0], proyecto: venta.proyecto})
r.venta = venta
this.data.push(r)
}).catch(error => {
progress.progress('increment')
console.error(row)
console.error(error)
}))
return
}
promises.push(this.get().unidad(row.id).then(json => {
const unidad = json.unidad
progress.progress('increment')
this.data.push(new Row({unidad: unidad, proyecto: unidad.proyecto_tipo_unidad.proyecto}))
}).catch(error => {
progress.progress('increment')
console.error(row)
console.error(error)
}))
})
Promise.all(promises).then(() => {
this.sort()
this.draw().clear()
this.draw().table()
})
})
},
unidad: id => {
const url = '{{$urls->api}}/ventas/unidad/' + id
return fetch(url).then(response => {
if (response.ok) {
return response.json()
}
})
},
venta: id => {
const url = '{{$urls->api}}/venta/' + id
return fetch(url).then(response => {
if (response.ok) {
return response.json()
}
}) })
} }
} }
}, },
sort: function() {
this.data.sort((a, b) => {
const p = a.proyecto.descripcion.localeCompare(b.proyecto.descripcion)
if (p === 0) {
const t = a.unidad.proyecto_tipo_unidad.tipo_unidad.descripcion
.localeCompare(b.unidad.proyecto_tipo_unidad.tipo_unidad.descripcion)
if (t === 0) {
return a.unidad.descripcion.localeCompare(b.unidad.descripcion)
}
return t
}
return p
})
},
draw: function() { draw: function() {
return { return {
clear: () => { clear: () => {
@ -213,6 +271,35 @@
$('<div></div>').addClass('content').html('No se han encontrado resultados.') $('<div></div>').addClass('content').html('No se han encontrado resultados.')
) )
) )
},
error: error => {
this.draw().separator()
$(this.id).append(
$('<div></div>').addClass('ui icon error message').append(
$('<i></i>').addClass('exclamation triangle icon')
).append(
$('<div></div>').addClass('content').html(error)
)
)
},
progress: cantidad => {
this.draw().separator()
const progress = $('<div></div>').addClass('ui active progress').append(
$('<div></div>').addClass('bar').append(
$('<div></div>').addClass('centered progress')
)
).append(
$('<div></div>').addClass('label').html('Cargando datos')
)
progress.progress({
total: cantidad,
label: 'ratio',
text: {
ratio: '{value} de {total} ({percent}%)'
}
})
$(this.id).append(progress)
return progress
} }
} }
}, },

View File

@ -16,6 +16,24 @@ class Unidades
{ {
use withJson, withRedis; use withJson, withRedis;
public function get(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
Service\Venta\Unidad $unidadService, int $unidad_id): ResponseInterface
{
$output = [
'unidad_id' => $unidad_id,
'unidad' => null
];
$redisKey = "unidad:{$unidad_id}";
try {
$output['unidad'] = $this->fetchRedis($redisService, $redisKey);
} catch (EmptyRedis) {
try {
$output['unidad'] = $unidadService->getById($unidad_id);
$this->saveRedis($redisService, $redisKey, $output['unidad']);
} catch (EmptyResult) {}
}
return $this->withJson($response, $output);
}
public function disponibles(ServerRequestInterface $request, ResponseInterface $response, Repository\Venta\Unidad $unidadRepository, Repository\Proyecto\TipoUnidad $tipoUnidadRepository, Service\Redis $redisService): ResponseInterface public function disponibles(ServerRequestInterface $request, ResponseInterface $response, Repository\Venta\Unidad $unidadRepository, Repository\Proyecto\TipoUnidad $tipoUnidadRepository, Service\Redis $redisService): ResponseInterface
{ {
$body = $request->getBody(); $body = $request->getBody();

View File

@ -20,7 +20,7 @@ class Ventas
{ {
$redisKey = "proyectos:vendibles"; $redisKey = "proyectos:vendibles";
try { try {
$proyectos = $proyectoService->process($proyectoRepository->load((array) $this->fetchRedis($redisService, $redisKey))); $proyectos = $this->fetchRedis($redisService, $redisKey);
} catch (EmptyRedis) { } catch (EmptyRedis) {
$proyectos = array_map(function(Model\Proyecto $proyecto) { $proyectos = array_map(function(Model\Proyecto $proyecto) {
return ['id' => $proyecto->id, 'descripcion' => $proyecto->descripcion]; return ['id' => $proyecto->id, 'descripcion' => $proyecto->descripcion];

View File

@ -66,7 +66,7 @@ class Venta extends Ideal\Model
public function proyecto(): Proyecto public function proyecto(): Proyecto
{ {
return $this->propiedad()->departamentos()[0]->proyectoTipoUnidad->proyecto; return $this->propiedad()->proyecto();
} }
protected float $valor_util; protected float $valor_util;

View File

@ -2,22 +2,40 @@
namespace Incoviba\Model\Venta; namespace Incoviba\Model\Venta;
use Incoviba\Common\Ideal; use Incoviba\Common\Ideal;
use Incoviba\Model;
class Propiedad extends Ideal\Model class Propiedad extends Ideal\Model
{ {
public array $unidades; public array $unidades;
protected array $departamentos;
public function departamentos(): array public function departamentos(): array
{ {
return array_values(array_filter($this->unidades, function(Unidad $unidad) {return $unidad->proyectoTipoUnidad->tipoUnidad->descripcion === 'departamento';})); if (!isset($this->departamentos)) {
$this->departamentos = array_values(array_filter($this->unidades, function(Unidad $unidad) {return $unidad->proyectoTipoUnidad->tipoUnidad->descripcion === 'departamento';}));
} }
return $this->departamentos;
}
protected array $estacionamientos;
public function estacionamientos(): array public function estacionamientos(): array
{ {
return array_values(array_filter($this->unidades, function(Unidad $unidad) {return $unidad->proyectoTipoUnidad->tipoUnidad->descripcion === 'estacionamiento';})); if (!isset($this->estacionamientos)) {
$this->estacionamientos = array_values(array_filter($this->unidades, function(Unidad $unidad) {return $unidad->proyectoTipoUnidad->tipoUnidad->descripcion === 'estacionamiento';}));
} }
return $this->estacionamientos;
}
protected array $bodegas;
public function bodegas(): array public function bodegas(): array
{ {
return array_values(array_filter($this->unidades, function(Unidad $unidad) {return $unidad->proyectoTipoUnidad->tipoUnidad->descripcion === 'bodega';})); if (!isset($this->bodegas)) {
$this->bodegas = array_values(array_filter($this->unidades, function(Unidad $unidad) {return $unidad->proyectoTipoUnidad->tipoUnidad->descripcion === 'bodega';}));
}
return $this->bodegas;
}
public function proyecto(): Model\Proyecto
{
return $this->unidades[0]->proyectoTipoUnidad->proyecto;
} }
protected float $vendible; protected float $vendible;
@ -46,6 +64,7 @@ class Propiedad extends Ideal\Model
public function jsonSerialize(): mixed public function jsonSerialize(): mixed
{ {
return [ return [
'unidades' => $this->unidades,
'departamentos' => $this->departamentos(), 'departamentos' => $this->departamentos(),
'estacionamientos' => $this->estacionamientos(), 'estacionamientos' => $this->estacionamientos(),
'bodegas' => $this->bodegas(), 'bodegas' => $this->bodegas(),

View File

@ -46,7 +46,7 @@ class Unidad extends Ideal\Model
public function jsonSerialize(): mixed public function jsonSerialize(): mixed
{ {
return array_merge(parent::jsonSerialize(), [ $output = array_merge(parent::jsonSerialize(), [
'subtipo' => $this->subtipo, 'subtipo' => $this->subtipo,
'piso' => $this->piso, 'piso' => $this->piso,
'descripcion' => $this->descripcion, 'descripcion' => $this->descripcion,
@ -54,5 +54,10 @@ class Unidad extends Ideal\Model
'proyecto_tipo_unidad' => $this->proyectoTipoUnidad, 'proyecto_tipo_unidad' => $this->proyectoTipoUnidad,
'prorrateo' => $this->prorrateo 'prorrateo' => $this->prorrateo
]); ]);
if (isset($this->precios)) {
$output['precios'] = $this->precios;
$output['current_precio'] = $this->currentPrecio;
}
return $output;
} }
} }

View File

@ -1,7 +1,7 @@
<?php <?php
namespace Incoviba\Repository; namespace Incoviba\Repository;
use DateTimeImmutable; use PDO;
use Incoviba\Common\Ideal; use Incoviba\Common\Ideal;
use Incoviba\Common\Define; use Incoviba\Common\Define;
use Incoviba\Common\Implement; use Incoviba\Common\Implement;
@ -155,6 +155,19 @@ WHERE ptu.`proyecto` = ? AND tev.`activa`
GROUP BY a.`id`"; GROUP BY a.`id`";
return $this->fetchMany($query, [$proyecto_id]); return $this->fetchMany($query, [$proyecto_id]);
} }
public function fetchIdsByProyecto(int $proyecto_id): array
{
$query = "SELECT a.`id`
FROM `{$this->getTable()}` a
JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad`
JOIN `unidad` ON `unidad`.`id` = pu.`unidad` AND pu.`principal` = 1
JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = `unidad`.`pt`
JOIN (SELECT e1.* FROM `estado_venta` e1 JOIN (SELECT MAX(`id`) AS 'id', `venta` FROM `estado_venta` GROUP BY `venta`) e0 ON e0.`id` = e1.`id`) ev ON ev.`venta` = a.`id`
JOIN `tipo_estado_venta` tev ON tev.`id` = ev.`estado`
WHERE ptu.`proyecto` = ? AND tev.`activa`
GROUP BY a.`id`";
return $this->connection->execute($query, [$proyecto_id])->fetchAll(PDO::FETCH_ASSOC);
}
public function fetchActivaByProyecto(int $proyecto_id): array public function fetchActivaByProyecto(int $proyecto_id): array
{ {
$query = "SELECT a.* $query = "SELECT a.*
@ -197,11 +210,27 @@ FROM `{$this->getTable()}` a
WHERE `unidad`.`descripcion` LIKE ? AND tu.`descripcion` = ?"; WHERE `unidad`.`descripcion` LIKE ? AND tu.`descripcion` = ?";
return $this->fetchMany($query, [$unidad, $tipo]); return $this->fetchMany($query, [$unidad, $tipo]);
} }
public function fetchIdsByUnidad(string $unidad, string $tipo): array
{
$query = "SELECT a.id
FROM `{$this->getTable()}` a
JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad`
JOIN `unidad` ON `unidad`.`id` = pu.`unidad`
JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = `unidad`.`pt`
JOIN `tipo_unidad` tu ON tu.`id` = ptu.`tipo`
WHERE `unidad`.`descripcion` LIKE ? AND tu.`descripcion` = ?";
return $this->connection->execute($query, [$unidad, $tipo])->fetchAll(PDO::FETCH_ASSOC);
}
public function fetchByPrecio(string $precio): array public function fetchByPrecio(string $precio): array
{ {
$query = "SELECT * FROM `{$this->getTable()}` WHERE `valor_uf` = ?"; $query = "SELECT * FROM `{$this->getTable()}` WHERE `valor_uf` = ?";
return $this->fetchMany($query, [$precio]); return $this->fetchMany($query, [$precio]);
} }
public function fetchIdsByPrecio(string $precio): array
{
$query = "SELECT `id` FROM `{$this->getTable()}` WHERE `valor_uf` = ?";
return $this->connection->execute($query, [$precio])->fetchAll(PDO::FETCH_ASSOC);
}
public function fetchByPropietario(string $propietario): array public function fetchByPropietario(string $propietario): array
{ {
$query = "SELECT a.* $query = "SELECT a.*
@ -212,6 +241,16 @@ WHERE CONCAT_WS('-', `propietario`.`rut`, `propietario`.`dv`) LIKE :propietario
OR CONCAT_WS(' ', `propietario`.`nombres`, `propietario`.`apellido_paterno`, `propietario`.`apellido_materno`) LIKE :propietario"; OR CONCAT_WS(' ', `propietario`.`nombres`, `propietario`.`apellido_paterno`, `propietario`.`apellido_materno`) LIKE :propietario";
return $this->fetchMany($query, [':propietario' => "%{$propietario}%"]); return $this->fetchMany($query, [':propietario' => "%{$propietario}%"]);
} }
public function fetchIdsByPropietario(string $propietario): array
{
$query = "SELECT a.id
FROM `{$this->getTable()}` a
JOIN `propietario` ON `propietario`.`rut` = a.`propietario`
WHERE CONCAT_WS('-', `propietario`.`rut`, `propietario`.`dv`) LIKE :propietario OR `propietario`.`nombres` LIKE :propietario
OR `propietario`.`apellido_paterno` LIKE :propietario OR `propietario`.`apellido_materno` LIKE :propietario
OR CONCAT_WS(' ', `propietario`.`nombres`, `propietario`.`apellido_paterno`, `propietario`.`apellido_materno`) LIKE :propietario";
return $this->connection->execute($query, [':propietario' => "%{$propietario}%"])->fetchAll(PDO::FETCH_ASSOC);
}
public function fetchByPropietarioNombreCompleto(string $propietario): array public function fetchByPropietarioNombreCompleto(string $propietario): array
{ {
$query = "SELECT a.* $query = "SELECT a.*

View File

@ -1,6 +1,7 @@
<?php <?php
namespace Incoviba\Repository\Venta; namespace Incoviba\Repository\Venta;
use PDO;
use Incoviba\Common\Ideal; use Incoviba\Common\Ideal;
use Incoviba\Common\Define; use Incoviba\Common\Define;
use Incoviba\Common\Implement; use Incoviba\Common\Implement;
@ -117,6 +118,20 @@ class Unidad extends Ideal\Repository
->where("a.`descripcion` LIKE ? AND tu.`descripcion` = ? AND (pu.`id` IS NULL OR `venta`.`id` IS NULL OR tev.`activa` = 0)"); ->where("a.`descripcion` LIKE ? AND tu.`descripcion` = ? AND (pu.`id` IS NULL OR `venta`.`id` IS NULL OR tev.`activa` = 0)");
return $this->fetchMany($query, [$descripcion, $tipo]); return $this->fetchMany($query, [$descripcion, $tipo]);
} }
public function fetchDisponiblesIdsByDescripcionAndTipo(string $descripcion, string $tipo): array
{
$query = $this->connection->getQueryBuilder()
->select('a.id')
->from("{$this->getTable()} a")
->joined("JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = a.`pt`
JOIN `tipo_unidad` tu ON tu.`id` = ptu.`tipo`
LEFT OUTER JOIN `propiedad_unidad` pu ON pu.`unidad` = a.`id`
LEFT OUTER JOIN `venta` ON `venta`.`propiedad` = pu.`propiedad`
LEFT OUTER JOIN (SELECT ev1.* FROM `estado_venta` ev1 JOIN (SELECT MAX(`id`) as 'id', `venta` FROM `estado_venta`) ev0 ON ev0.`id` = ev1.`id`) ev ON ev.`venta` = `venta`.`id`
LEFT OUTER JOIN `tipo_estado_venta` tev ON tev.`id` = ev.`estado`")
->where("a.`descripcion` LIKE ? AND tu.`descripcion` = ? AND (pu.`id` IS NULL OR `venta`.`id` IS NULL OR tev.`activa` = 0)");
return $this->connection->execute($query, [$descripcion, $tipo])->fetchAll(PDO::FETCH_ASSOC);
}
protected function joinProrrateo(): string protected function joinProrrateo(): string
{ {

View File

@ -22,7 +22,8 @@ class Search
} else { } else {
$results = $this->find($query, $tipo); $results = $this->find($query, $tipo);
} }
return $this->sort($results); return $results;
//return $this->sort($results);
} }
protected function findCualquiera(string $query): array protected function findCualquiera(string $query): array
@ -45,7 +46,7 @@ class Search
} }
protected function find(string $query, string $tipo): array protected function find(string $query, string $tipo): array
{ {
preg_match_all('/["\']([\s\w]+)["\']|(\w+)/i', $query, $matches, PREG_SET_ORDER | PREG_UNMATCHED_AS_NULL); preg_match_all('/["\']([\s\w]+)["\']|(\w+)/iu', $query, $matches, PREG_SET_ORDER | PREG_UNMATCHED_AS_NULL);
$queries = array_map(function($match) { $queries = array_map(function($match) {
array_shift($match); array_shift($match);
$valid = array_filter($match, function($line) {return $line !== null;}); $valid = array_filter($match, function($line) {return $line !== null;});
@ -56,7 +57,7 @@ class Search
foreach ($queries as $q) { foreach ($queries as $q) {
$this->add($results, $this->findVentas($q, $tipo)); $this->add($results, $this->findVentas($q, $tipo));
if (in_array($tipo, $tiposUnidades)) { if (in_array($tipo, $tiposUnidades)) {
$this->add($results, $this->findUnidadesDisponibles($q, $tipo)); $this->add($results, $this->findUnidadesDisponibles($q, $tipo), false);
} }
} }
return $results; return $results;
@ -91,7 +92,7 @@ class Search
protected function findUnidadesDisponibles(string $query, string $tipo): array protected function findUnidadesDisponibles(string $query, string $tipo): array
{ {
try { try {
return $this->unidadRepository->fetchDisponiblesByDescripcionAndTipo($query, $tipo); return $this->unidadRepository->fetchDisponiblesIdsByDescripcionAndTipo($query, $tipo);
} catch (EmptyResponse) { } catch (EmptyResponse) {
return []; return [];
} }
@ -99,7 +100,7 @@ class Search
protected function findUnidad(string $query, string $tipo): array protected function findUnidad(string $query, string $tipo): array
{ {
try { try {
return $this->ventaService->getByUnidad($query, $tipo); return $this->ventaRepository->fetchIdsByUnidad($query, $tipo);
} catch (EmptyResult) { } catch (EmptyResult) {
return []; return [];
} }
@ -107,7 +108,7 @@ class Search
protected function findPropietario(string $query): array protected function findPropietario(string $query): array
{ {
try { try {
return $this->ventaService->getByPropietario($query); return $this->ventaRepository->fetchIdsByPropietario($query);
} catch (EmptyResult) { } catch (EmptyResult) {
return []; return [];
} }
@ -116,7 +117,7 @@ class Search
{ {
try { try {
$precio = str_replace(['$', '.', ','], ['', '', '.'], $query); $precio = str_replace(['$', '.', ','], ['', '', '.'], $query);
return $this->ventaService->getByPrecio($precio); return $this->ventaRepository->fetchIdsByPrecio($precio);
} catch (EmptyResult) { } catch (EmptyResult) {
return []; return [];
} }
@ -125,7 +126,7 @@ class Search
{ {
try { try {
$proyecto = $this->proyectoService->getByName($query); $proyecto = $this->proyectoService->getByName($query);
return $this->ventaService->getByProyecto($proyecto->id); return $this->ventaRepository->fetchIdsByProyecto($proyecto->id);
} catch (EmptyResult) { } catch (EmptyResult) {
return []; return [];
} }
@ -145,22 +146,21 @@ class Search
} }
return $this->tipos; return $this->tipos;
} }
protected function add(array &$results, array $found): void protected function add(array &$results, array $found, bool $is_venta = true): void
{ {
foreach ($found as $item) { foreach ($found as $item) {
if (!$this->inResults($item, $results)) { if (!$this->inResults($item, $results)) {
$item['tipo'] = 'venta';
if (!$is_venta) {
$item['tipo'] = 'unidad';
}
$results []= $item; $results []= $item;
} }
} }
} }
protected function inResults($item, array $results): bool protected function inResults($item, array $results): bool
{ {
foreach ($results as $result) { return in_array($item, $results, true);
if (get_class($item) === get_class($result) and $item->id === $result->id) {
return true;
}
}
return false;
} }
protected function sort(&$results): array protected function sort(&$results): array
{ {

13
cli/bin/index.php Normal file
View File

@ -0,0 +1,13 @@
<?php
$app = require_once implode(DIRECTORY_SEPARATOR, [
dirname(__FILE__, 2),
'setup',
'app.php'
]);
try {
$app->run();
} catch (Error $error) {
$app->getContainer()->get(Psr\Log\LoggerInterface::class)->error($error);
} catch (Exception $exception) {
$app->getContainer()->get(Psr\Log\LoggerInterface::class)->notice($exception);
}