Cleanup logs, fixed add Venta, fixed search

This commit is contained in:
2024-01-19 23:10:20 -03:00
parent f55e4dbd5f
commit fa11f5b240
15 changed files with 238 additions and 91 deletions

View File

@ -1,4 +1,4 @@
<?php <?php
use Incoviba\Controller\Search; use Incoviba\Controller\API\Search;
$app->post('/search', [Search::class, 'query']); $app->post('/search', [Search::class, 'query']);

View File

@ -8,4 +8,5 @@ $app->group('/unidad/{unidad_id}', function($app) {
$app->group('/prorrateo', function($app) { $app->group('/prorrateo', function($app) {
$app->post('[/]', [Unidades::class, 'prorrateo']); $app->post('[/]', [Unidades::class, 'prorrateo']);
}); });
$app->get('[/]', [Unidades::class, 'get']);
}); });

View File

@ -107,9 +107,10 @@
const uri = '{{$urls->api}}/search' const uri = '{{$urls->api}}/search'
this.data = [] this.data = []
return fetchAPI(uri, {method: 'post', body: data}).then(response => { return fetchAPI(uri, {method: 'post', body: data}).then(response => {
if (response.ok) { if (!response) {
return response.json() return
} }
return response.json()
}).catch(error => { }).catch(error => {
this.draw().clear() this.draw().clear()
this.draw().error(error) this.draw().error(error)
@ -123,7 +124,11 @@
const promises = [] const promises = []
data.results.forEach(row => { data.results.forEach(row => {
if (row.tipo === 'venta') { if (row.tipo === 'venta') {
promises.push(this.get().venta(row.id).then(json => { return promises.push(this.get().venta(row.id).then(json => {
if (json.venta === null) {
console.debug(json)
return
}
const venta = json.venta const venta = json.venta
progress.progress('increment') progress.progress('increment')
const r = new Row({unidad: venta.propiedad.unidades[0], proyecto: venta.proyecto}) const r = new Row({unidad: venta.propiedad.unidades[0], proyecto: venta.proyecto})
@ -134,7 +139,6 @@
console.error(row) console.error(row)
console.error(error) console.error(error)
})) }))
return
} }
promises.push(this.get().unidad(row.id).then(json => { promises.push(this.get().unidad(row.id).then(json => {
const unidad = json.unidad const unidad = json.unidad
@ -164,9 +168,10 @@
venta: id => { venta: id => {
const url = '{{$urls->api}}/venta/' + id const url = '{{$urls->api}}/venta/' + id
return fetchAPI(url).then(response => { return fetchAPI(url).then(response => {
if (response.ok) { if (!response) {
return response.json() return
} }
return response.json()
}) })
} }
} }

View File

@ -3,7 +3,7 @@
@section('page_content') @section('page_content')
<div class="ui container"> <div class="ui container">
<h2 class="ui header">Nueva Venta</h2> <h2 class="ui header">Nueva Venta</h2>
<form class="ui form" id="add_form" action="{{$urls->api}}/ventas/add" method="post"> <form class="ui form" id="add_form" method="post">
<label for="fecha_venta">Fecha de Venta</label> <label for="fecha_venta">Fecha de Venta</label>
<div class="inline field"> <div class="inline field">
<div class="ui calendar" id="fecha_venta_calendar"> <div class="ui calendar" id="fecha_venta_calendar">
@ -686,7 +686,7 @@
$('<div></div>').addClass('content').append(tipo.charAt(0).toUpperCase() + tipo.slice(1) + ' ').append( $('<div></div>').addClass('content').append(tipo.charAt(0).toUpperCase() + tipo.slice(1) + ' ').append(
unidad.draw(this.unidades[tipo]) unidad.draw(this.unidades[tipo])
).append( ).append(
$('<button></button>').addClass('ui icon button').attr('type', 'button').attr('data-number', number).append( $('<button></button>').addClass('ui basic red icon button').attr('type', 'button').attr('data-number', number).append(
$('<i></i>').addClass('remove icon') $('<i></i>').addClass('remove icon')
).click(event => { ).click(event => {
const number = $(event.currentTarget).attr('data-number') const number = $(event.currentTarget).attr('data-number')
@ -766,7 +766,7 @@
} }
function showErrors(errors) { function showErrors(errors) {
console.debug(errors) console.error(errors)
} }
$(document).ready(() => { $(document).ready(() => {
@ -789,20 +789,21 @@
$('#add_form').submit(event => { $('#add_form').submit(event => {
event.preventDefault() event.preventDefault()
const data = new FormData(event.currentTarget) const body = new FormData(event.currentTarget)
const uri = $(event.currentTarget).attr('action') const uri = '{{$urls->api}}/ventas/add'
fetch(uri, {method: 'post', body: data}).then(response => { return fetchAPI(uri, {method: 'post', body}).then(response => {
if (response.ok) { if (!response) {
return response.json() return false
} }
}).then(data => { return response.json().then(data => {
if (data.status) { if (data.status) {
window.location = '{{$urls->base}}' window.location = '{{$urls->base}}/venta/' + data.venta_id
return true return true
} }
showErrors(data.errors) showErrors(data.errors)
return false
})
}) })
return false
}) })
}) })
</script> </script>

View File

@ -8,12 +8,18 @@ return [
(new Monolog\Handler\RotatingFileHandler('/logs/debug.log', 10)) (new Monolog\Handler\RotatingFileHandler('/logs/debug.log', 10))
->setFormatter(new Monolog\Formatter\LineFormatter(null, null, false, false, true)), ->setFormatter(new Monolog\Formatter\LineFormatter(null, null, false, false, true)),
Monolog\Level::Debug, Monolog\Level::Debug,
Monolog\Level::Notice Monolog\Level::Debug
),
new Monolog\Handler\FilterHandler(
(new Monolog\Handler\RotatingFileHandler('/logs/info.log', 10))
->setFormatter(new Monolog\Formatter\LineFormatter(null, null, false, false, true)),
Monolog\Level::Info,
Monolog\Level::Warning,
), ),
new Monolog\Handler\FilterHandler( new Monolog\Handler\FilterHandler(
(new Monolog\Handler\RotatingFileHandler('/logs/error.log', 10)) (new Monolog\Handler\RotatingFileHandler('/logs/error.log', 10))
->setFormatter(new Monolog\Formatter\LineFormatter(null, null, false, false, true)), ->setFormatter(new Monolog\Formatter\LineFormatter(null, null, false, false, true)),
Monolog\Level::Warning, Monolog\Level::Error,
Monolog\Level::Error Monolog\Level::Error
), ),
new Monolog\Handler\FilterHandler( new Monolog\Handler\FilterHandler(

View File

@ -0,0 +1,20 @@
<?php
namespace Incoviba\Controller\API;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Service;
class Search
{
use withJson;
public function query(ServerRequestInterface $request, ResponseInterface $response,
Service\Search $service): ResponseInterface
{
$data = $request->getParsedBody();
$results = $service->query($data['query'], $data['tipo']);
$output = compact('results');
return $this->withJson($response, $output);
}
}

View File

@ -1,17 +1,19 @@
<?php <?php
namespace Incoviba\Controller\API; namespace Incoviba\Controller\API;
use PDOException;
use DateTimeImmutable; use DateTimeImmutable;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Ideal\Controller;
use Incoviba\Common\Implement\Exception\EmptyRedis; use Incoviba\Common\Implement\Exception\EmptyRedis;
use Incoviba\Common\Implement\Exception\EmptyResult; use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Controller\withRedis; use Incoviba\Controller\withRedis;
use Incoviba\Model; use Incoviba\Model;
use Incoviba\Repository; use Incoviba\Repository;
use Incoviba\Service; use Incoviba\Service;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class Ventas class Ventas extends Controller
{ {
use withJson, withRedis; use withJson, withRedis;
@ -55,6 +57,9 @@ class Ventas
Service\Venta $service, int $venta_id): ResponseInterface Service\Venta $service, int $venta_id): ResponseInterface
{ {
$redisKey = "venta:{$venta_id}"; $redisKey = "venta:{$venta_id}";
$output = [
'venta' => null
];
try { try {
$venta = $this->fetchRedis($redisService, $redisKey); $venta = $this->fetchRedis($redisService, $redisKey);
$output = compact('venta'); $output = compact('venta');
@ -64,12 +69,7 @@ class Ventas
$output = compact('venta'); $output = compact('venta');
$this->saveRedis($redisService, $redisKey, $venta); $this->saveRedis($redisService, $redisKey, $venta);
} catch (EmptyResult $exception) { } catch (EmptyResult $exception) {
$output = [ $this->logger->notice($exception);
'error' => [
'code' => $exception->getCode(),
'message' => str_replace([PHP_EOL, "\r"], [' ', ''], $exception->getMessage())
]
];
} }
} }
return $this->withJson($response, $output); return $this->withJson($response, $output);
@ -178,14 +178,20 @@ class Ventas
$data = $request->getParsedBody(); $data = $request->getParsedBody();
$output = [ $output = [
'status' => false, 'status' => false,
'venta_id' => null,
'errors' => [] 'errors' => []
]; ];
try { try {
$venta = $ventaService->add($data); $venta = $ventaService->add($data);
$this->saveRedis($redisService, "venta:{$venta->id}", $venta); $this->saveRedis($redisService, "venta:{$venta->id}", $venta);
$output['venta_id'] = $venta->id;
$output['status'] = true; $output['status'] = true;
} catch (\Exception $exception) { } catch (EmptyResult | PDOException $exception) {
$output['errors'] = $exception; $output['errors'] = [
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
'stack' => $exception->getTraceAsString()
];
} }
return $this->withJson($response, $output); return $this->withJson($response, $output);
} }

View File

@ -13,11 +13,4 @@ class Search
$post = $request->getParsedBody() ?? ''; $post = $request->getParsedBody() ?? '';
return $view->render($response, 'search', compact('post', 'query', 'tipo')); return $view->render($response, 'search', compact('post', 'query', 'tipo'));
} }
public function query(ServerRequestInterface $request, ResponseInterface $response, Service\Search $service): ResponseInterface
{
$data = $request->getParsedBody();
$results = $service->query($data['query'], $data['tipo']);
$response->getBody()->write(json_encode(compact('results')));
return $response->withHeader('Content-Type', 'application/json');
}
} }

View File

@ -17,7 +17,7 @@ class NotFound
try { try {
return $handler->handle($request); return $handler->handle($request);
} catch (HttpNotFoundException $exception) { } catch (HttpNotFoundException $exception) {
$this->logger->warning($exception); $this->logger->notice($exception);
$response = $this->responseFactory->createResponse(404); $response = $this->responseFactory->createResponse(404);
if (str_contains($request->getUri()->getPath(), '/api')) { if (str_contains($request->getUri()->getPath(), '/api')) {
return $response; return $response;

View File

@ -19,8 +19,8 @@ class Venta extends Ideal\Model
public float $uf; public float $uf;
protected ?Pago $resciliacion; protected ?Pago $resciliacion;
public array $estados; public ?array $estados;
public Venta\EstadoVenta $currentEstado; public ?Venta\EstadoVenta $currentEstado;
public function propietario(): Venta\Propietario public function propietario(): Venta\Propietario
{ {
@ -63,7 +63,7 @@ class Venta extends Ideal\Model
if (!isset($this->estados)) { if (!isset($this->estados)) {
$this->estados = $this->runFactory('estados'); $this->estados = $this->runFactory('estados');
} }
return $this->estados; return $this->estados ?? [];
} }
public function currentEstado(): ?Venta\EstadoVenta public function currentEstado(): ?Venta\EstadoVenta
{ {

View File

@ -115,13 +115,15 @@ class Venta extends Ideal\Repository
->register('fecha_ingreso', new Implement\Repository\Mapper\DateTime('fecha_ingreso', 'fechaIngreso')) ->register('fecha_ingreso', new Implement\Repository\Mapper\DateTime('fecha_ingreso', 'fechaIngreso'))
//->register('avalchile') //->register('avalchile')
//->register('agente') //->register('agente')
->register('resciliacion', (new Implement\Repository\Mapper())
->setFactory((new Implement\Repository\Factory())
->setCallable([$this->pagoService, 'getById'])
->setArgs(['pago_id' => $data['resciliacion']])))
->register('relacionado', new Implement\Repository\Mapper\Boolean('relacionado')); ->register('relacionado', new Implement\Repository\Mapper\Boolean('relacionado'));
//->register('promocion') //->register('promocion')
//->register('devolucion'); //->register('devolucion');
if (array_key_exists('resciliacion', $data)) {
$map = $map->register('resciliacion', (new Implement\Repository\Mapper())
->setFactory((new Implement\Repository\Factory())
->setCallable([$this->pagoService, 'getById'])
->setArgs(['pago_id' => $data['resciliacion']])));
}
return $this->parseData(new Model\Venta(), $data, $map); return $this->parseData(new Model\Venta(), $data, $map);
} }
public function save(Define\Model $model): Model\Venta public function save(Define\Model $model): Model\Venta
@ -147,7 +149,17 @@ class Venta extends Ideal\Repository
public function fetchByProyecto(int $proyecto_id): array public function fetchByProyecto(int $proyecto_id): array
{ {
$query = "SELECT a.* $query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('JOIN propiedad_unidad pu ON pu.propiedad = a.propiedad')
->joined('JOIN unidad ON unidad.id = pu.unidad AND pu.principal = 1')
->joined('JOIN proyecto_tipo_unidad ptu ON ptu.id = unidad.pt')
->joined('JOIN (SELECT ev1.* FROM estado_venta ev1 JOIN (SELECT MAX(id) AS id, venta FROM estado_venta GROUP BY venta) ev0 ON ev0.id = ev1.id) ev ON ev.venta = a.id')
->joined('JOIN tipo_estado_venta tev ON tev.id = ev.estado')
->where('ptu.proyecto = ? AND tev.activa')
->group('a.id');
/*$query = "SELECT a.*
FROM `{$this->getTable()}` a FROM `{$this->getTable()}` a
JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad` JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad`
JOIN `unidad` ON `unidad`.`id` = pu.`unidad` AND pu.`principal` = 1 JOIN `unidad` ON `unidad`.`id` = pu.`unidad` AND pu.`principal` = 1
@ -155,12 +167,22 @@ FROM `{$this->getTable()}` a
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 (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` JOIN `tipo_estado_venta` tev ON tev.`id` = ev.`estado`
WHERE ptu.`proyecto` = ? AND tev.`activa` 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 public function fetchIdsByProyecto(int $proyecto_id): array
{ {
$query = "SELECT a.`id` $query = $this->connection->getQueryBuilder()
->select('a.id')
->from("{$this->getTable()} a")
->joined('JOIN propiedad_unidad pu ON pu.propiedad = a.propiedad')
->joined('JOIN unidad ON unidad.id = pu.unidad AND unidad.pt')
->joined('proyecto_tipo_unidad ptu ON ptu.id = unidad.pt')
->joined('JOIN (SELECT ev1.* FROM estado_venta ev1 JOIN (SELECT MAX(id) AS id, venta FROM estado_venta GROUP BY venta) ev0 ON ev0.id = ev1.id) ev ON ev.venta = a.id')
->joined('JOIN tipo_estado_venta tev ON tev.id = ev.estado')
->where('ptu.proyecto = ? AND tev.activa')
->group('a.id');
/*$query = "SELECT a.`id`
FROM `{$this->getTable()}` a FROM `{$this->getTable()}` a
JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad` JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad`
JOIN `unidad` ON `unidad`.`id` = pu.`unidad` AND pu.`principal` = 1 JOIN `unidad` ON `unidad`.`id` = pu.`unidad` AND pu.`principal` = 1
@ -168,12 +190,22 @@ FROM `{$this->getTable()}` a
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 (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` JOIN `tipo_estado_venta` tev ON tev.`id` = ev.`estado`
WHERE ptu.`proyecto` = ? AND tev.`activa` WHERE ptu.`proyecto` = ? AND tev.`activa`
GROUP BY a.`id`"; GROUP BY a.`id`";*/
return $this->connection->execute($query, [$proyecto_id])->fetchAll(PDO::FETCH_ASSOC); 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 = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad`')
->joined('JOIN `unidad` ON `unidad`.`id` = pu.`unidad` AND pu.`principal` = 1')
->joined('JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = `unidad`.`pt`')
->joined("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`")
->joined('JOIN `tipo_estado_venta` tev ON tev.`id` = ev.`estado`')
->where('WHERE ptu.`proyecto` = ? AND tev.`activa`')
->group('a.id');
/*$query = "SELECT a.*
FROM `{$this->getTable()}` a FROM `{$this->getTable()}` a
JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad` JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad`
JOIN `unidad` ON `unidad`.`id` = pu.`unidad` AND pu.`principal` = 1 JOIN `unidad` ON `unidad`.`id` = pu.`unidad` AND pu.`principal` = 1
@ -181,12 +213,22 @@ FROM `{$this->getTable()}` a
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 (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` JOIN `tipo_estado_venta` tev ON tev.`id` = ev.`estado`
WHERE ptu.`proyecto` = ? AND tev.`activa` 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 fetchByProyectoAndUnidad(string $proyecto_nombre, int $unidad_descripcion): Model\Venta public function fetchByProyectoAndUnidad(string $proyecto_nombre, int $unidad_descripcion): Model\Venta
{ {
$query = "SELECT a.* $query = $this->connection->getQueryBuilder()
->select("a.*")
->from("`{$this->getTable()}` a")
->joined('JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad`')
->joined('JOIN `unidad` ON `unidad`.`id` = pu.`unidad` AND pu.`principal` = 1')
->joined('JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = `unidad`.`pt`')
->joined('JOIN `proyecto` ON `proyecto`.`id` = ptu.`proyecto`')
->joined("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`")
->joined('JOIN `tipo_estado_venta` tev ON tev.`id` = ev.`estado`')
->where('WHERE `proyecto`.`descripcion` = ? AND `unidad`.`descripcion` = ? AND tev.`activa`');
/*$query = "SELECT a.*
FROM `{$this->getTable()}` a FROM `{$this->getTable()}` a
JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad` JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad`
JOIN `unidad` ON `unidad`.`id` = pu.`unidad` AND pu.`principal` = 1 JOIN `unidad` ON `unidad`.`id` = pu.`unidad` AND pu.`principal` = 1
@ -194,82 +236,147 @@ FROM `{$this->getTable()}` a
JOIN `proyecto` ON `proyecto`.`id` = ptu.`proyecto` JOIN `proyecto` ON `proyecto`.`id` = ptu.`proyecto`
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 (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` JOIN `tipo_estado_venta` tev ON tev.`id` = ev.`estado`
WHERE `proyecto`.`descripcion` = ? AND `unidad`.`descripcion` = ? AND tev.`activa`"; WHERE `proyecto`.`descripcion` = ? AND `unidad`.`descripcion` = ? AND tev.`activa`";*/
return $this->fetchOne($query, [$proyecto_nombre, $unidad_descripcion]); return $this->fetchOne($query, [$proyecto_nombre, $unidad_descripcion]);
} }
public function fetchByPie(int $pie_id): Model\Venta public function fetchByPie(int $pie_id): Model\Venta
{ {
$query = "SELECT * FROM `{$this->getTable()}` WHERE `pie` = ?"; $query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('pie = ?');
return $this->fetchOne($query, [$pie_id]); return $this->fetchOne($query, [$pie_id]);
} }
public function fetchIdByPie(int $pie_id): array public function fetchIdByPie(int $pie_id): array
{ {
$query = "SELECT `id` FROM `{$this->getTable()}` WHERE `pie` = ?"; $query = $this->connection->getQueryBuilder()
->select('id')
->from($this->getTable())
->where('pie = ?');
return $this->connection->execute($query, [$pie_id])->fetch(PDO::FETCH_ASSOC); return $this->connection->execute($query, [$pie_id])->fetch(PDO::FETCH_ASSOC);
} }
public function fetchByUnidad(string $unidad, string $tipo): array public function fetchByUnidad(string $unidad, string $tipo): array
{ {
$query = "SELECT a.* $query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad`')
->joined('JOIN `unidad` ON `unidad`.`id` = pu.`unidad`')
->joined('JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = `unidad`.`pt`')
->joined('JOIN `tipo_unidad` tu ON tu.`id` = ptu.`tipo`')
->where('`unidad`.`descripcion` LIKE ? AND tu.`descripcion` = ?');
/*$query = "SELECT a.*
FROM `{$this->getTable()}` a FROM `{$this->getTable()}` a
JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad` JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad`
JOIN `unidad` ON `unidad`.`id` = pu.`unidad` JOIN `unidad` ON `unidad`.`id` = pu.`unidad`
JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = `unidad`.`pt` JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = `unidad`.`pt`
JOIN `tipo_unidad` tu ON tu.`id` = ptu.`tipo` JOIN `tipo_unidad` tu ON tu.`id` = ptu.`tipo`
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 public function fetchIdsByUnidad(string $unidad, string $tipo): array
{ {
$query = "SELECT a.id $query = $this->connection->getQueryBuilder()
->select('a.id')
->from("{$this->getTable()} a")
->joined('JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad`')
->joined('JOIN `unidad` ON `unidad`.`id` = pu.`unidad`')
->joined('JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = `unidad`.`pt`')
->joined('JOIN `tipo_unidad` tu ON tu.`id` = ptu.`tipo`')
->where('`unidad`.`descripcion` LIKE ? AND tu.`descripcion` = ?');
/*$query = "SELECT a.id
FROM `{$this->getTable()}` a FROM `{$this->getTable()}` a
JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad` JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad`
JOIN `unidad` ON `unidad`.`id` = pu.`unidad` JOIN `unidad` ON `unidad`.`id` = pu.`unidad`
JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = `unidad`.`pt` JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = `unidad`.`pt`
JOIN `tipo_unidad` tu ON tu.`id` = ptu.`tipo` JOIN `tipo_unidad` tu ON tu.`id` = ptu.`tipo`
WHERE `unidad`.`descripcion` LIKE ? AND tu.`descripcion` = ?"; WHERE `unidad`.`descripcion` LIKE ? AND tu.`descripcion` = ?";*/
return $this->connection->execute($query, [$unidad, $tipo])->fetchAll(PDO::FETCH_ASSOC); 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 = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('valor_uf = ?');
return $this->fetchMany($query, [$precio]); return $this->fetchMany($query, [$precio]);
} }
public function fetchIdsByPrecio(string $precio): array public function fetchIdsByPrecio(string $precio): array
{ {
$query = "SELECT `id` FROM `{$this->getTable()}` WHERE `valor_uf` = ?"; $query = $this->connection->getQueryBuilder()
->select('id')
->from($this->getTable())
->where('valor_uf = ?');
return $this->connection->execute($query, [$precio])->fetchAll(PDO::FETCH_ASSOC); return $this->connection->execute($query, [$precio])->fetchAll(PDO::FETCH_ASSOC);
} }
public function fetchByPropietarioAndPropiedad(int $propietario_rut, int $propiedad_id): Model\Venta
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('propietario = ? AND propiedad = ?');
return $this->fetchOne($query, [$propietario_rut, $propiedad_id]);
}
public function fetchByPropietario(string $propietario): array public function fetchByPropietario(string $propietario): array
{ {
$query = "SELECT a.* $query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('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");
/*$query = "SELECT a.*
FROM `{$this->getTable()}` a FROM `{$this->getTable()}` a
JOIN `propietario` ON `propietario`.`rut` = a.`propietario` JOIN `propietario` ON `propietario`.`rut` = a.`propietario`
WHERE CONCAT_WS('-', `propietario`.`rut`, `propietario`.`dv`) LIKE :propietario OR `propietario`.`nombres` LIKE :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 `propietario`.`apellido_paterno` LIKE :propietario OR `propietario`.`apellido_materno` 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 public function fetchIdsByPropietario(string $propietario): array
{ {
$query = "SELECT a.id $query = $this->connection->getQueryBuilder()
->select('a.id')
->from("{$this->getTable()} a")
->joined('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");
/*$query = "SELECT a.id
FROM `{$this->getTable()}` a FROM `{$this->getTable()}` a
JOIN `propietario` ON `propietario`.`rut` = a.`propietario` JOIN `propietario` ON `propietario`.`rut` = a.`propietario`
WHERE CONCAT_WS('-', `propietario`.`rut`, `propietario`.`dv`) LIKE :propietario OR `propietario`.`nombres` LIKE :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 `propietario`.`apellido_paterno` LIKE :propietario OR `propietario`.`apellido_materno` 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->connection->execute($query, [':propietario' => "%{$propietario}%"])->fetchAll(PDO::FETCH_ASSOC); 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 = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('JOIN `propietario` ON `propietario`.`rut` = a.`propietario`')
->where("CONCAT_WS(' ', `propietario`.`nombres`, `propietario`.`apellido_paterno`, `propietario`.`apellido_materno`) LIKE ?");
/*$query = "SELECT a.*
FROM `{$this->getTable()}` a FROM `{$this->getTable()}` a
JOIN `propietario` ON `propietario`.`rut` = a.`propietario` JOIN `propietario` ON `propietario`.`rut` = a.`propietario`
WHERE CONCAT_WS(' ', `propietario`.`nombres`, `propietario`.`apellido_paterno`, `propietario`.`apellido_materno`) LIKE ?"; WHERE CONCAT_WS(' ', `propietario`.`nombres`, `propietario`.`apellido_paterno`, `propietario`.`apellido_materno`) LIKE ?";*/
return $this->fetchMany($query, [$propietario]); return $this->fetchMany($query, [$propietario]);
} }
public function fetchEscriturasByProyecto(int $proyecto_id): array public function fetchEscriturasByProyecto(int $proyecto_id): array
{ {
$query = "SELECT DISTINCT a.* $query = $this->connection->getQueryBuilder()
->select('DISTINCT a.*')
->from("{$this->getTable()} a")
->joined('JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad`')
->joined('JOIN `unidad` ON `unidad`.`id` = pu.`unidad`')
->joined('JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = `unidad`.`id`')
->joined("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`")
->joined('JOIN `tipo_estado_venta` tev ON tev.`id` = ev.`estado`')
->where("ptu.`proyecto` = ? AND tev.`descripcion` IN ('firmado por inmobiliaria', 'escriturando')")
->group('a.id');
/*$query = "SELECT DISTINCT a.*
FROM `{$this->getTable()}` a FROM `{$this->getTable()}` a
JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad` JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad`
JOIN `unidad` ON `unidad`.`id` = pu.`unidad` JOIN `unidad` ON `unidad`.`id` = pu.`unidad`
@ -277,7 +384,7 @@ FROM `{$this->getTable()}` a
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 (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` JOIN `tipo_estado_venta` tev ON tev.`id` = ev.`estado`
WHERE ptu.`proyecto` = ? AND tev.`descripcion` IN ('firmado por inmobiliaria', 'escriturando') WHERE ptu.`proyecto` = ? AND tev.`descripcion` IN ('firmado por inmobiliaria', 'escriturando')
GROUP BY a.`id`"; GROUP BY a.`id`";*/
return $this->fetchMany($query, [$proyecto_id]); return $this->fetchMany($query, [$proyecto_id]);
} }
public function fetchIdByEscritura(int $escritura_id): array public function fetchIdByEscritura(int $escritura_id): array

View File

@ -65,7 +65,11 @@ 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), false); $disponibles = $this->findUnidadesDisponibles($q, $tipo);
if (count($disponibles) === 0) {
continue;
}
$this->add($results, $disponibles, false);
} }
} }
return $results; return $results;
@ -281,11 +285,10 @@ class Search
protected function add(array &$results, array $found, bool $is_venta = true): void protected function add(array &$results, array $found, bool $is_venta = true): void
{ {
foreach ($found as $item) { foreach ($found as $item) {
if (!isset($item['tipo'])) {
$item['tipo'] = ($is_venta) ? 'venta' : 'unidad';
}
if (!$this->inResults($item, $results)) { if (!$this->inResults($item, $results)) {
$item['tipo'] = 'venta';
if (!$is_venta) {
$item['tipo'] = 'unidad';
}
$results []= $item; $results []= $item;
} }
} }

View File

@ -100,17 +100,22 @@ class Venta
$venta_data[$field] = $forma_pago->{$name}->id; $venta_data[$field] = $forma_pago->{$name}->id;
} }
} }
$venta = $this->ventaRepository->create($venta_data); try {
$venta = $this->ventaRepository->save($venta); return $this->ventaRepository->fetchByPropietarioAndPropiedad($propietario->rut, $propiedad->id);
$tipoEstado = $this->tipoEstadoVentaRepository->fetchByDescripcion('vigente'); } catch (Implement\Exception\EmptyResult) {
$estado = $this->estadoVentaRepository->create([ $venta = $this->ventaRepository->create($venta_data);
'venta' => $venta->id, $venta = $this->ventaRepository->save($venta);
'estado' => $tipoEstado->id,
'fecha' => $venta->fecha->format('Y-m-d')
]);
$this->estadoVentaRepository->save($estado);
return $venta; $tipoEstado = $this->tipoEstadoVentaRepository->fetchByDescripcion('vigente');
$estado = $this->estadoVentaRepository->create([
'venta' => $venta->id,
'estado' => $tipoEstado->id,
'fecha' => $venta->fecha->format('Y-m-d')
]);
$this->estadoVentaRepository->save($estado);
return $venta;
}
} }
protected function addPropietario(array $data): Model\Venta\Propietario protected function addPropietario(array $data): Model\Venta\Propietario
{ {

View File

@ -78,7 +78,7 @@ class Propiedad
if (count($diff) === 0) { if (count($diff) === 0) {
return; return;
} }
$query = "DELECT FROM `propiedad_unidad` WHERE `propiedad` = ? AND `unidad` = ?"; $query = "DELETE FROM `propiedad_unidad` WHERE `propiedad` = ? AND `unidad` = ?";
$statement = $this->connection->prepare($query); $statement = $this->connection->prepare($query);
foreach ($diff as $id) { foreach ($diff as $id) {
$statement->execute([$propiedad->id, $id]); $statement->execute([$propiedad->id, $id]);

View File

@ -1,3 +1,3 @@
display_errors=no display_errors=no
log_errors=yes log_errors=yes
error_log=/logs/errors.log #error_log=/logs/errors.log