7 Commits

35 changed files with 1261 additions and 51 deletions

0
app/bin/console Normal file → Executable file
View File

0
app/bin/integration_tests Normal file → Executable file
View File

0
app/bin/performance_tests Normal file → Executable file
View File

0
app/bin/unit_tests Normal file → Executable file
View File

View File

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class ChangeTelefonoSizeInPropietario extends AbstractMigration
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change(): void
{
$this->table('propietario')
->changeColumn('telefono', 'biginteger', ['null' => true, 'signed' => false, 'default' => null])
->update();
}
}

View File

@ -2,6 +2,7 @@
use Incoviba\Controller\API\Ventas\Precios; use Incoviba\Controller\API\Ventas\Precios;
$app->group('/precios', function($app) { $app->group('/precios', function($app) {
$app->post('/import[/]', [Precios::class, 'import']);
$app->post('[/]', [Precios::class, 'proyecto']); $app->post('[/]', [Precios::class, 'proyecto']);
}); });
$app->group('/precio', function($app) { $app->group('/precio', function($app) {

View File

@ -2,5 +2,5 @@
use Incoviba\Controller\Ventas\Precios; use Incoviba\Controller\Ventas\Precios;
$app->group('/precios', function($app) { $app->group('/precios', function($app) {
$app->get('[/]', Precios::class); $app->get('[/{project_id}[/]]', Precios::class);
}); });

View File

@ -156,7 +156,7 @@
<script> <script>
const regiones = [ const regiones = [
@foreach ($regiones as $region) @foreach ($regiones as $region)
'<div class="item" data-value="{{$region->id}}">{{$region->descripcion}}</div>', '<div class="item" data-value="{{$region->id}}">{{$region->numeral}} - {{$region->descripcion}}</div>',
@endforeach @endforeach
] ]

View File

@ -54,22 +54,23 @@
} }
$(document).ready(() => { $(document).ready(() => {
const url = '{{$urls->api}}/ventas/pago/{{$venta->resciliacion()->id}}' const url = '{{$urls->api}}/ventas/pago/{{$venta->resciliacion()->id}}'
let old = new Date({{$venta->resciliacion()?->fecha->format('Y') ?? date('Y')}}, let old = new Date(Date.parse('{{$venta->resciliacion()?->fecha->format('Y-m-d') ?? $venta->currentEstado()->fecha->format('Y-m-d') ?? $venta->fecha->format('Y-m-d')}}') + 24 * 60 * 60 * 1000)
{{$venta->resciliacion()?->fecha->format('n') ?? date('n')}}-1, {{$venta->resciliacion()?->fecha->format('j') ?? date('j')}})
calendar_date_options['initialDate'] = old calendar_date_options['initialDate'] = old
calendar_date_options['onChange'] = function(date, text, mode) { calendar_date_options['onChange'] = function(date, text, mode) {
if (date.getTime() === old.getTime()) { if (date.getTime() === old.getTime()) {
return return
} }
const body = new FormData() const body = new FormData()
body.set('fecha', date.toISOString()) const fecha = new Date(date.getTime())
fecha.setDate(fecha.getDate() - 1)
body.set('fecha', fecha.toISOString())
$('#loading-spinner-fecha').show() $('#loading-spinner-fecha').show()
APIClient.fetch(url, {method: 'post', body}).then(response => { APIClient.fetch(url, {method: 'post', body}).then(response => {
$('#loading-spinner-fecha').hide() $('#loading-spinner-fecha').hide()
if (!response) { if (!response) {
return return
} }
old = date old = new Date(date.getTime())
alertResponse('Fecha cambiada correctamente.') alertResponse('Fecha cambiada correctamente.')
}) })
} }

View File

@ -6,6 +6,7 @@
@section('venta_content') @section('venta_content')
<div class="ui list"> <div class="ui list">
@if (isset($venta->formaPago()->pie))
<div class="item"> <div class="item">
<div class="header">Valor Pagado</div> <div class="header">Valor Pagado</div>
<div class="content"> <div class="content">
@ -15,6 +16,16 @@
</div> </div>
</div> </div>
</div> </div>
@else
<div class="item">
<div class="ui compact warning message">
<div class="content">
<i class="exclamation triangle icon"></i>
No tiene valor pagado
</div>
</div>
</div>
@endif
<div class="item"> <div class="item">
<div class="header"> <div class="header">
Multa Estandar Multa Estandar

View File

@ -24,6 +24,9 @@
<button class="ui tiny green icon button" id="add_button"> <button class="ui tiny green icon button" id="add_button">
<i class="plus icon"></i> <i class="plus icon"></i>
</button> </button>
<button class="ui tiny green icon button" id="import_button">
<i class="upload icon"></i>
</button>
</div> </div>
</div> </div>
</h4> </h4>
@ -31,6 +34,7 @@
<table class="ui table" id="list_data"></table> <table class="ui table" id="list_data"></table>
</div> </div>
</div> </div>
@include('ventas.precios.modal.import')
<div class="ui modal" id="list_modal"> <div class="ui modal" id="list_modal">
<div class="header"> <div class="header">
Actualizar <span id="modal_title"></span> Actualizar <span id="modal_title"></span>
@ -97,7 +101,8 @@
return this.precio / this.superficie return this.precio / this.superficie
} }
draw(formatter) { draw(formatter) {
const date = new Date(this.fecha) const dateParts = this.fecha.split('-')
const date = new Date(dateParts[0], dateParts[1] - 1, dateParts[2])
const dateFormatter = new Intl.DateTimeFormat('es-CL') const dateFormatter = new Intl.DateTimeFormat('es-CL')
return $('<tr></tr>').addClass('unidad').attr('data-linea', this.linea).append( return $('<tr></tr>').addClass('unidad').attr('data-linea', this.linea).append(
$('<td></td>').html(this.nombre) $('<td></td>').html(this.nombre)
@ -317,7 +322,8 @@
buttons: { buttons: {
add: '', add: '',
up: '', up: '',
refresh: '' refresh: '',
import: ''
} }
}, },
data: { data: {
@ -330,6 +336,11 @@
loading: { loading: {
precios: false precios: false
}, },
components: {
modals: {
import: null
}
},
get: function() { get: function() {
return { return {
proyectos: () => { proyectos: () => {
@ -378,6 +389,24 @@
} }
} }
}, },
url() {
return {
proyectos: () => {
const currentUrl = window.location.href
const newUrl = `{{ $urls->base }}/ventas/precios`
if (newUrl !== currentUrl) {
window.history.replaceState(null, null, newUrl)
}
},
precios: proyecto_id => {
const currentUrl = window.location.href
const newUrl = `{{ $urls->base }}/ventas/precios/${proyecto_id}`
if (newUrl !== currentUrl) {
window.history.replaceState(null, null, newUrl)
}
}
}
},
add: function() { add: function() {
return { return {
precio: data => { precio: data => {
@ -400,6 +429,7 @@
draw: function() { draw: function() {
return { return {
proyectos: () => { proyectos: () => {
this.url().proyectos()
const parent = $(this.ids.list) const parent = $(this.ids.list)
const header = parent.find('#list_title') const header = parent.find('#list_title')
const list = parent.find('.list') const list = parent.find('.list')
@ -408,6 +438,7 @@
$(this.ids.buttons.add).hide() $(this.ids.buttons.add).hide()
$(this.ids.buttons.add).attr('data-id', '') $(this.ids.buttons.add).attr('data-id', '')
$(this.ids.buttons.add).attr('data-proyecto', '') $(this.ids.buttons.add).attr('data-proyecto', '')
$(`#${this.ids.buttons.import}`).hide()
header.html('Proyectos') header.html('Proyectos')
table.hide() table.hide()
@ -415,7 +446,8 @@
this.data.proyectos.forEach(proyecto => { this.data.proyectos.forEach(proyecto => {
list.append( list.append(
$('<div></div>').addClass('item proyecto').attr('data-proyecto', proyecto.id).html(proyecto.descripcion).css('cursor', 'pointer') $('<div></div>').addClass('item proyecto').attr('data-proyecto', proyecto.id)
.html(proyecto.descripcion).css('cursor', 'pointer')
) )
}) })
list.show() list.show()
@ -431,6 +463,7 @@
}) })
}, },
precios: () => { precios: () => {
this.url().precios(this.data.id)
const parent = $(this.ids.list) const parent = $(this.ids.list)
const header = parent.find('#list_title') const header = parent.find('#list_title')
const list = parent.find('.list') const list = parent.find('.list')
@ -440,6 +473,8 @@
$(this.ids.buttons.add).attr('data-proyecto', this.data.proyecto) $(this.ids.buttons.add).attr('data-proyecto', this.data.proyecto)
$(this.ids.buttons.add).show() $(this.ids.buttons.add).show()
$(`#${this.ids.buttons.import}`).show()
header.html('Precios de ' + this.data.proyecto) header.html('Precios de ' + this.data.proyecto)
list.hide() list.hide()
table.html('') table.html('')
@ -581,18 +616,27 @@
} }
} }
}, },
import: event => {
event.preventDefault()
precios.components.modals.import.show(this.data.id)
return false
}
} }
}, },
setup: function({list, proyectos, buttons_up, buttons_refresh, buttons_add}) { setup: function({list, proyectos, buttons_up, buttons_refresh, buttons_add, buttons_import}) {
this.ids.list = list this.ids.list = list
this.ids.proyectos = proyectos this.ids.proyectos = proyectos
this.ids.buttons.up = buttons_up this.ids.buttons.up = buttons_up
this.ids.buttons.refresh = buttons_refresh this.ids.buttons.refresh = buttons_refresh
this.ids.buttons.add = buttons_add this.ids.buttons.add = buttons_add
this.ids.buttons.import = buttons_import
$(this.ids.buttons.up).click(this.actions().up) $(this.ids.buttons.up).click(this.actions().up)
$(this.ids.buttons.refresh).click(this.actions().refresh) $(this.ids.buttons.refresh).click(this.actions().refresh)
$(this.ids.buttons.add).click(this.actions().add().list) $(this.ids.buttons.add).click(this.actions().add().list)
document.getElementById(this.ids.buttons.import).addEventListener('click', this.actions().import)
this.components.modals.import = new ImportModal()
this.draw().proyectos() this.draw().proyectos()
} }
@ -674,6 +718,10 @@
$(this.ids.button).click(this.actions().send) $(this.ids.button).click(this.actions().send)
} }
} }
function selectProject(projectId) {
const $project = $(`.item.proyecto[data-proyecto="${projectId}"]`)
$project.click()
}
$(document).ready(() => { $(document).ready(() => {
precios.setup({ precios.setup({
@ -681,7 +729,8 @@
proyectos: '#proyectos', proyectos: '#proyectos',
buttons_up: '#up_button', buttons_up: '#up_button',
buttons_refresh: '#refresh_button', buttons_refresh: '#refresh_button',
buttons_add: '#add_button' buttons_add: '#add_button',
buttons_import: 'import_button'
}) })
list_modal.setup({ list_modal.setup({
modal: '#list_modal', modal: '#list_modal',
@ -692,6 +741,10 @@
fields_valor: '#valor', fields_valor: '#valor',
button: '#send' button: '#send'
}) })
@if (isset($project_id))
selectProject({{$project_id}})
@endif
}) })
</script> </script>
@endpush @endpush

View File

@ -0,0 +1,120 @@
<div class="ui modal" id="import_modal">
<div class="header">
Importar Precios
</div>
<div class="content">
<div class="ui form">
<input type="hidden" id="import_project_id" name="import_project_id" value="" />
<div class="three wide field">
<div class="ui calendar" id="import_date">
<div class="ui left icon input">
<i class="calendar icon"></i>
<input type="text" name="fecha" />
</div>
</div>
</div>
<input class="ui invisible file input" type="file" id="import_file" name="file" />
<label class="ui placeholder segment" for="import_file">
<div class="ui icon header">
<i class="upload icon"></i>
Archivo de Precios
</div>
</label>
</div>
</div>
<div class="actions">
<div class="ui red cancel icon button">
<i class="remove icon"></i>
</div>
<div class="ui green ok icon button">
<i class="checkmark icon"></i>
Importar
</div>
</div>
@push('page_scripts')
<script>
class ImportModal {
ids = {
modal: '',
project: '',
calendar: '',
file: ''
}
components = {
$modal: null,
form: null,
project: null,
$calendar: null,
file: null,
$file: null
}
constructor() {
this.ids.modal = 'import_modal'
this.ids.project = 'import_project_id'
this.ids.calendar = 'import_date'
this.ids.file = 'import_file'
this.setup()
}
show(project_id) {
this.components.project.value = project_id
this.components.$modal.modal('show')
}
dragDrop(event) {
event.preventDefault()
if (event.originalEvent.dataTransfer && event.originalEvent.dataTransfer.files.length > 0) {
this.components.file.files = event.originalEvent.dataTransfer.files
}
}
import() {
const url = '{{ $urls->api }}/ventas/precios/import'
const method = 'post'
const body = new FormData()
body.set('project_id', this.components.project.value)
const date = this.components.$calendar.calendar('get date')
body.set('date', [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('-'))
body.set('file', this.components.file.files[0])
APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
if (json.status === true) {
window.location.reload()
return
}
console.debug(json)
})
}
setup() {
this.components.$modal = $(`#${this.ids.modal}`)
this.components.$modal.modal({
onApprove: () => {
this.import()
}
})
this.components.form = this.components.$modal.find('form')
this.components.form.submit(event => {
event.preventDefault()
this.import()
return false
})
this.components.project = document.getElementById(this.ids.project)
this.components.$calendar = $(`#${this.ids.calendar}`)
const cdo = structuredClone(calendar_date_options)
cdo['maxDate'] = new Date()
this.components.$calendar.calendar(cdo)
this.components.file = document.getElementById(this.ids.file)
this.components.$file = $(this.components.file.parentNode.querySelector('label'))
this.components.$file.css('cursor', 'pointer')
this.components.$file.on('dragover', event => {
event.preventDefault()
event.stopPropagation()
})
this.components.$file.on('dragenter', event => {
event.preventDefault()
event.stopPropagation()
})
this.components.$file.on('drop', this.dragDrop.bind(this))
}
}
</script>
@endpush

View File

@ -116,7 +116,18 @@ return [
->registerSub($container->get(Incoviba\Service\Contabilidad\Cartola\BCI\Mes::class)); ->registerSub($container->get(Incoviba\Service\Contabilidad\Cartola\BCI\Mes::class));
}, },
'TokuClient' => function(ContainerInterface $container) { 'TokuClient' => function(ContainerInterface $container) {
$logger = $container->get('externalLogger');
$stack = GuzzleHttp\HandlerStack::create();
$stack->push(GuzzleHttp\Middleware::mapRequest(function(Psr\Http\Message\RequestInterface $request) use ($logger) {
$logger->info('Toku Request', [
'method' => $request->getMethod(),
'uri' => (string) $request->getUri(),
'headers' => $request->getHeaders(),
'body' => $request->getBody()->getContents(),
]);
}));
return new GuzzleHttp\Client([ return new GuzzleHttp\Client([
'handler' => $stack,
'base_uri' => $container->get('TOKU_URL'), 'base_uri' => $container->get('TOKU_URL'),
'headers' => [ 'headers' => [
'x-api-key' => $container->get('TOKU_TOKEN'), 'x-api-key' => $container->get('TOKU_TOKEN'),
@ -213,5 +224,9 @@ return [
$container->get(Incoviba\Service\Queue::class) $container->get(Incoviba\Service\Queue::class)
) )
->register($container->get(Incoviba\Service\Venta\MediosPago\Toku::class)); ->register($container->get(Incoviba\Service\Venta\MediosPago\Toku::class));
},
Incoviba\Service\FileUpload::class => function(ContainerInterface $container) {
return new Incoviba\Service\FileUpload($container->get(Psr\Log\LoggerInterface::class))
->register($container->get(Incoviba\Service\FileUpload\ExcelBase::class));
} }
]; ];

View File

@ -1,13 +1,16 @@
<?php <?php
namespace Incoviba\Controller\API\Ventas; namespace Incoviba\Controller\API\Ventas;
use DateTime;
use Exception;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Implement\Exception\EmptyRedis; use Incoviba\Common\Implement\Exception\{EmptyRedis,EmptyResult};
use Incoviba\Common\Implement\Exception\EmptyResult; use Psr\Log\LoggerInterface;
use Incoviba\Controller\API\{withJson,emptyBody}; use Incoviba\Controller\API\{withJson,emptyBody};
use Incoviba\Service;
use Incoviba\Controller\withRedis; use Incoviba\Controller\withRedis;
use Incoviba\Exception\ServiceAction\Create;
use Incoviba\Service;
class Precios class Precios
{ {
@ -51,4 +54,29 @@ class Precios
} }
} }
} }
public function import(ServerRequestInterface $request, ResponseInterface $response,
LoggerInterface $logger,
Service\Venta\Precio $precioService): ResponseInterface
{
$body = $request->getParsedBody();
$projectId = $body['project_id'];
$date = $body['date'];
$file = $request->getUploadedFiles()['file'];
$output = [
'input' => $body,
'total' => 0,
'precios' => [],
'status' => false
];
$date = DateTime::createFromFormat('Y-m-d', $date);
try {
$output['precios'] = $precioService->import($projectId, $date, $file);
$output['total'] = count($output['precios']);
$output['status'] = true;
} catch (Create | Exception $exception) {
$logger->warning($exception);
}
return $this->withJson($response, $output);
}
} }

View File

@ -4,6 +4,9 @@ namespace Incoviba\Controller;
use Incoviba\Common\Alias\View; use Incoviba\Common\Alias\View;
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\Exception\ServiceAction\Create;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Exception\ServiceAction\Update;
use Incoviba\Model; use Incoviba\Model;
use Incoviba\Repository; use Incoviba\Repository;
use Incoviba\Service; use Incoviba\Service;
@ -142,9 +145,24 @@ class Ventas
return $view->render($response, 'ventas.desistir', compact('venta')); return $view->render($response, 'ventas.desistir', compact('venta'));
} }
public function desistida(ServerRequestInterface $request, ResponseInterface $response, Service\Venta $ventaService, public function desistida(ServerRequestInterface $request, ResponseInterface $response, Service\Venta $ventaService,
Service\Venta\Pago $pagoService,
View $view, int $venta_id): ResponseInterface View $view, int $venta_id): ResponseInterface
{ {
try {
$venta = $ventaService->getById($venta_id); $venta = $ventaService->getById($venta_id);
} catch (Read) {
return $view->render($response->withStatus(404), 'not_found');
}
if ($venta->resciliacion() === null) {
$pagoData = [
'fecha' => $venta->currentEstado()->fecha->format('Y-m-d'),
'valor' => 0
];
try {
$pago = $pagoService->add($pagoData);
$venta = $ventaService->edit($venta, ['resciliacion' => $pago->id]);
} catch (Create | Update) {}
}
return $view->render($response, 'ventas.desistida', compact('venta')); return $view->render($response, 'ventas.desistida', compact('venta'));
} }
} }

View File

@ -9,9 +9,9 @@ use Incoviba\Model;
class Precios class Precios
{ {
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, View $view, Service\Proyecto $proyectoService): ResponseInterface public function __invoke(ServerRequestInterface $request, ResponseInterface $response, View $view, Service\Proyecto $proyectoService, ?int $project_id = null): ResponseInterface
{ {
$proyectos = array_map(function(Model\Proyecto $proyecto) {return ['id' => $proyecto->id, 'descripcion' => $proyecto->descripcion];}, $proyectoService->getVendibles()); $proyectos = array_map(function(Model\Proyecto $proyecto) {return ['id' => $proyecto->id, 'descripcion' => $proyecto->descripcion];}, $proyectoService->getVendibles());
return $view->render($response, 'ventas.precios.list', compact('proyectos')); return $view->render($response, 'ventas.precios.list', compact('proyectos', 'project_id'));
} }
} }

View File

@ -43,6 +43,11 @@ class Inmobiliaria extends Ideal\Repository
return $this->update($model, ['dv', 'razon', 'abreviacion', 'cuenta', 'banco', 'sociedad'], $new_data); return $this->update($model, ['dv', 'razon', 'abreviacion', 'cuenta', 'banco', 'sociedad'], $new_data);
} }
/**
* @param string|array|null $sorting
* @return array
* @throws Implement\Exception\EmptyResult
*/
public function fetchAllActive(null|string|array $sorting = null): array public function fetchAllActive(null|string|array $sorting = null): array
{ {
$query = $this->connection->getQueryBuilder() $query = $this->connection->getQueryBuilder()
@ -58,4 +63,18 @@ class Inmobiliaria extends Ideal\Repository
} }
return $this->fetchMany($query, [1, 8]); return $this->fetchMany($query, [1, 8]);
} }
/**
* @param string $name
* @return Model\Inmobiliaria
* @throws Implement\Exception\EmptyResult
*/
public function fetchByName(string $name): Model\Inmobiliaria
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('razon LIKE :name OR abreviacion LIKE :name');
return $this->fetchOne($query, ['name' => "%{$name}%"]);
}
} }

View File

@ -85,6 +85,11 @@ class Proyecto extends Ideal\Repository
return $this->fetchOne($query, [$id]); return $this->fetchOne($query, [$id]);
} }
/**
* @param string $name
* @return Model\Proyecto
* @throws Implement\Exception\EmptyResult
*/
public function fetchByName(string $name): Model\Proyecto public function fetchByName(string $name): Model\Proyecto
{ {
$query = $this->connection->getQueryBuilder() $query = $this->connection->getQueryBuilder()

View File

@ -7,6 +7,8 @@ use Incoviba\Common\Define;
use Incoviba\Common\Implement; use Incoviba\Common\Implement;
use Incoviba\Model; use Incoviba\Model;
use Incoviba\Repository; use Incoviba\Repository;
use PDO;
use PDOException;
class EstadoPrecio extends Ideal\Repository class EstadoPrecio extends Ideal\Repository
{ {
@ -44,11 +46,24 @@ class EstadoPrecio extends Ideal\Repository
return $this->update($model, ['precio', 'estado', 'fecha'], $new_data); return $this->update($model, ['precio', 'estado', 'fecha'], $new_data);
} }
/**
* @param int $precio_id
* @return array
* @throws Implement\Exception\EmptyResult
*/
public function fetchByPrecio(int $precio_id): array public function fetchByPrecio(int $precio_id): array
{ {
$query = "SELECT * FROM `{$this->getTable()}` WHERE `precio` = ?"; $query = "SELECT * FROM `{$this->getTable()}` WHERE `precio` = ?";
error_log($query.PHP_EOL,3,'/logs/query.log');
error_log($precio_id.PHP_EOL,3,'/logs/query.log');
return $this->fetchMany($query, [$precio_id]); return $this->fetchMany($query, [$precio_id]);
} }
/**
* @param int $precio_id
* @return Define\Model
* @throws Implement\Exception\EmptyResult
*/
public function fetchCurrentByPrecio(int $precio_id): Define\Model public function fetchCurrentByPrecio(int $precio_id): Define\Model
{ {
$query = "SELECT e1.* $query = "SELECT e1.*

View File

@ -1,6 +1,7 @@
<?php <?php
namespace Incoviba\Repository\Venta; namespace Incoviba\Repository\Venta;
use Incoviba\Common\Implement\Exception\EmptyResult;
use PDO; use PDO;
use PDOException; use PDOException;
use Incoviba\Common\Ideal; use Incoviba\Common\Ideal;

View File

@ -4,6 +4,7 @@ namespace Incoviba\Repository\Venta;
use Incoviba\Common\Ideal; use Incoviba\Common\Ideal;
use Incoviba\Common\Define; use Incoviba\Common\Define;
use Incoviba\Common\Implement; use Incoviba\Common\Implement;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Model; use Incoviba\Model;
class TipoEstadoPrecio extends Ideal\Repository class TipoEstadoPrecio extends Ideal\Repository
@ -31,4 +32,18 @@ class TipoEstadoPrecio extends Ideal\Repository
{ {
return $this->update($model, ['descripcion'], $new_data); return $this->update($model, ['descripcion'], $new_data);
} }
/**
* @param string $descripcion
* @return Model\Venta\TipoEstadoPrecio
* @throws EmptyResult
*/
public function fetchByDescripcion(string $descripcion): Model\Venta\TipoEstadoPrecio
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('descripcion = ?');
return $this->fetchOne($query, [$descripcion]);
}
} }

View File

@ -0,0 +1,59 @@
<?php
namespace Incoviba\Service;
use InvalidArgumentException;
use Psr\Http\Message\UploadedFileInterface;
use Incoviba\Common\Ideal;
use Incoviba\Exception\ServiceAction;
use Incoviba\Service\FileUpload\FileUploadInterface;
class FileUpload extends Ideal\Service implements FileUploadInterface
{
protected array $uploads = [];
public function register(FileUploadInterface $fileUpload, string $filetype = 'default'): self
{
$this->uploads [$filetype]= $fileUpload;
return $this;
}
/**
* @param UploadedFileInterface $uploadedFile
* @return array
* @throws ServiceAction\Read
*/
public function getData(UploadedFileInterface $uploadedFile): array
{
try {
$type = $this->getFileType($uploadedFile);
} catch (InvalidArgumentException $exception) {
throw new ServiceAction\Read(__CLASS__, $exception);
}
$uploader = $this->getUploader($type);
return $uploader->getData($uploadedFile);
}
/**
* @param UploadedFileInterface $uploadedFile
* @return string|null
*/
protected function getFileType(UploadedFileInterface $uploadedFile): ?string
{
$fileType = $uploadedFile->getClientMediaType();
$typesMap = [
'text/csv' => 'csv',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
'application/vnd.ms-excel' => 'xls',
];
if (!array_key_exists($fileType, $typesMap)) {
throw new InvalidArgumentException("File type {$fileType} not supported.");
}
return $typesMap[$fileType];
}
protected function getUploader(string $type): FileUploadInterface
{
if (!array_key_exists($type, $this->uploads)) {
return $this->uploads['default'];
}
return $this->uploads[$type];
}
}

View File

@ -0,0 +1,147 @@
<?php
namespace Incoviba\Service\FileUpload;
use InvalidArgumentException;
use OutOfBoundsException;
use Psr\Http\Message\UploadedFileInterface;
use PhpOffice\PhpSpreadsheet;
use Incoviba\Common\Ideal;
use Incoviba\Exception\ServiceAction\Read;
class ExcelBase extends Ideal\Service implements FileUploadInterface
{
/**
* @param UploadedFileInterface $uploadedFile
* @return array
* @throws Read
*/
public function getData(UploadedFileInterface $uploadedFile): array
{
$tempFilename = $this->createTempFile($uploadedFile);
$reader = PhpSpreadsheet\IOFactory::createReaderForFile($tempFilename);
$reader->setReadDataOnly(true);
$workbook = $reader->load($tempFilename);
try {
$sheet = $this->findSheet($workbook);
} catch (OutOfBoundsException $exception) {
throw new Read(__CLASS__, $exception);
}
$titles = $this->extractTitles($sheet);
$data = $this->extractData($sheet, $titles);
unlink($tempFilename);
return $data;
}
/**
* @param PhpSpreadsheet\Spreadsheet $workbook
* @return PhpSpreadsheet\Worksheet\Worksheet
* @throws OutOfBoundsException
*/
protected function findSheet(PhpSpreadsheet\Spreadsheet $workbook): PhpSpreadsheet\Worksheet\Worksheet
{
$sheet = $workbook->getActiveSheet();
if ($this->findTable($sheet)) {
return $sheet;
}
$sheets = $workbook->getAllSheets();
foreach ($sheets as $sheet) {
if ($this->findTable($sheet)) {
return $sheet;
}
}
throw new OutOfBoundsException('No table found in the workbook.');
}
protected function findTable(PhpSpreadsheet\Worksheet\Worksheet $sheet): bool
{
$rowIterator = $sheet->getRowIterator();
foreach ($rowIterator as $row) {
if ($row->isEmpty()) {
continue;
}
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
if ($cellIterator->valid()) {
return true;
}
foreach ($cellIterator as $cell) {
if ($cell->getCalculatedValue() !== '') {
return true;
}
}
}
return false;
}
protected function createTempFile(UploadedFileInterface $uploadedFile): string
{
$filename = $uploadedFile->getClientFilename();
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$tempFilename = tempnam(sys_get_temp_dir(), $extension);
$uploadedFile->moveTo($tempFilename);
return $tempFilename;
}
protected function extractTitles(PhpSpreadsheet\Worksheet\Worksheet $sheet): array
{
$titles = [];
$iterator = $sheet->getRowIterator();
foreach ($iterator as $row) {
if ($row->isEmpty()) {
continue;
}
$titles = $this->getRowData($row);
break;
}
return $titles;
}
protected function extractData(PhpSpreadsheet\Worksheet\Worksheet $sheet, array $titles): array
{
$data = [];
$rowIterator = $sheet->getRowIterator();
foreach ($rowIterator as $row) {
if ($row->isEmpty()) {
continue;
}
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
if ($cellIterator->current() === $titles[0]) {
continue;
}
try {
$rowData = $this->getRowData($row, $titles);
} catch (InvalidArgumentException $exception) {
if ($exception->getCode() === 1000) {
continue;
}
throw $exception;
}
$data []= array_combine($titles, $rowData);
}
return $data;
}
protected function getRowData(PhpSpreadsheet\Worksheet\Row $row, ?array $titles = null): array
{
$data = [];
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $cell) {
if ($cell->getCalculatedValue() === null) {
continue;
}
$value = $cell->getCalculatedValue();
if ($value === null) {
continue;
}
$value = mb_strtolower($value);
if ($titles !== null and in_array($value, $titles)) {
throw new InvalidArgumentException('Row matches title', 1000);
}
$data []= $value;
}
return $data;
}
}

View File

@ -0,0 +1,9 @@
<?php
namespace Incoviba\Service\FileUpload;
use Psr\Http\Message\UploadedFileInterface;
interface FileUploadInterface
{
public function getData(UploadedFileInterface $uploadedFile): array;
}

View File

@ -59,6 +59,8 @@ class Queue extends Ideal\Service
try { try {
if (!$worker->execute($job)) { if (!$worker->execute($job)) {
$this->logger->debug("Could not execute job {$job->id}"); $this->logger->debug("Could not execute job {$job->id}");
$job->retries++;
$this->jobService->update($job);
return false; return false;
} }
if (!$this->jobService->execute($job)) { if (!$this->jobService->execute($job)) {
@ -67,6 +69,12 @@ class Queue extends Ideal\Service
} }
} catch (Exception $exception) { } catch (Exception $exception) {
$this->logger->warning("Could not run job {$job->id}", ['exception' => $exception]); $this->logger->warning("Could not run job {$job->id}", ['exception' => $exception]);
$job->retries++;
try {
$this->jobService->update($job);
} catch (Update $exception) {
$this->logger->error($exception->getMessage(), ['job' => $job, 'exception' => $exception]);
}
return false; return false;
} }
return true; return true;

View File

@ -4,7 +4,7 @@ namespace Incoviba\Service;
use DateTimeInterface; use DateTimeInterface;
use DateTimeImmutable; use DateTimeImmutable;
use DateMalformedStringException; use DateMalformedStringException;
use function PHPUnit\Framework\countOf; use Incoviba\Service\Valor\Phone;
class Valor class Valor
{ {
@ -40,6 +40,14 @@ class Valor
} }
return $value / $this->ufService->get($date); return $value / $this->ufService->get($date);
} }
public function phone(): Phone
{
return new Phone();
}
public function telefono(): Phone
{
return $this->phone();
}
protected function getDateTime(null|string|DateTimeInterface $date): DateTimeInterface protected function getDateTime(null|string|DateTimeInterface $date): DateTimeInterface
{ {

View File

@ -0,0 +1,28 @@
<?php
namespace Incoviba\Service\Valor;
class Phone
{
public function toDatabase(?string $phone): ?int
{
if ($phone === null) {
return null;
}
return (int) str_replace([' ', '+'], '', $phone) ?? null;
}
public function toDisplay(?int $phone): ?string
{
if ($phone === null) {
return null;
}
$parts = preg_split('/(?=<country>\d{2})?(?=<area>\d)(?=<first>\d{4})(?=<last>\d{4})/', $phone);
$output = [];
if (array_key_exists('country', $parts)) {
$output [] = "+{$parts[0]}";
}
$output [] = $parts[1] ?? '';
$output [] = $parts[2] ?? '';
$output [] = $parts[3] ?? '';
return implode(' ', $output);
}
}

View File

@ -1,19 +1,31 @@
<?php <?php
namespace Incoviba\Service\Venta; namespace Incoviba\Service\Venta;
use DateTimeInterface;
use PDOException;
use Psr\Http\Message\UploadedFileInterface;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement\Exception\EmptyResult; use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\Read; use Incoviba\Exception\ServiceAction;
use Incoviba\Repository;
use Incoviba\Model; use Incoviba\Model;
use Incoviba\Repository;
class Precio class Precio extends Ideal\Service
{ {
public function __construct(protected Repository\Venta\Precio $precioRepository, protected Repository\Venta\EstadoPrecio $estadoPrecioRepository) {} public function __construct(LoggerInterface $logger,
protected Repository\Venta\Precio $precioRepository,
protected Repository\Venta\EstadoPrecio $estadoPrecioRepository,
protected Precio\Estado $estadoPrecioService,
protected Precio\Import $importService)
{
parent::__construct($logger);
}
/** /**
* @param int $proyecto_id * @param int $proyecto_id
* @return array * @return array
* @throws Read * @throws ServiceAction\Read
*/ */
public function getByProyecto(int $proyecto_id): array public function getByProyecto(int $proyecto_id): array
{ {
@ -25,14 +37,14 @@ class Precio
} }
return $precios; return $precios;
} catch (EmptyResult $exception) { } catch (EmptyResult $exception) {
throw new Read(__CLASS__, $exception); throw new ServiceAction\Read(__CLASS__, $exception);
} }
} }
/** /**
* @param int $unidad_id * @param int $unidad_id
* @return Model\Venta\Precio * @return Model\Venta\Precio
* @throws Read * @throws ServiceAction\Read
*/ */
public function getVigenteByUnidad(int $unidad_id): Model\Venta\Precio public function getVigenteByUnidad(int $unidad_id): Model\Venta\Precio
{ {
@ -42,14 +54,14 @@ class Precio
$precio->current = $this->estadoPrecioRepository->fetchCurrentByPrecio($precio->id); $precio->current = $this->estadoPrecioRepository->fetchCurrentByPrecio($precio->id);
return $precio; return $precio;
} catch (EmptyResult $exception) { } catch (EmptyResult $exception) {
throw new Read(__CLASS__, $exception); throw new ServiceAction\Read(__CLASS__, $exception);
} }
} }
/** /**
* @param int $unidad_id * @param int $unidad_id
* @return array * @return array
* @throws Read * @throws ServiceAction\Read
*/ */
public function getByUnidad(int $unidad_id): array public function getByUnidad(int $unidad_id): array
{ {
@ -61,7 +73,51 @@ class Precio
} }
return $precios; return $precios;
} catch (EmptyResult $exception) { } catch (EmptyResult $exception) {
throw new Read(__CLASS__, $exception); throw new ServiceAction\Read(__CLASS__, $exception);
} }
} }
/**
* @param int $projectId
* @param DateTimeInterface $date
* @param UploadedFileInterface $uploadedFile
* @return array
* @throws ServiceAction\Create
*/
public function import(int $projectId, DateTimeInterface $date, UploadedFileInterface $uploadedFile): array
{
$pricesData = $this->importService->importData($projectId, $date, $uploadedFile);
$prices = [];
foreach ($pricesData as $data) {
try {
$price = $this->precioRepository->create($data);
$price = $this->precioRepository->save($price);
$prices[] = $price;
} catch (EmptyResult | PDOException $exception) {
$this->logger->error('Problemas para agregar precio', ['data' => $data, 'exception' => $exception]);
}
}
foreach ($prices as $price) {
$idx = array_search($price->unidad->id, array_column($pricesData, 'unidad'));
$row = $pricesData[$idx];
try {
$this->estadoPrecioService->replacePrices($price->unidad, $date, $price);
} catch (ServiceAction\Update $exception) {
$this->logger->error('Problemas para reemplazar precios', [
'data' => $row,
'exception' => $exception
]);
}
try {
$this->estadoPrecioService->updatePrice($price, $row['fecha']);
} catch (ServiceAction\Update $exception) {
$this->logger->error('Problemas para actualizar estado de precio', [
'data' => $row,
'exception' => $exception
]);
}
}
return $prices;
}
} }

View File

@ -0,0 +1,89 @@
<?php
namespace Incoviba\Service\Venta\Precio;
use DateTimeInterface;
use Incoviba\Model\Venta\Precio;
use Incoviba\Model\Venta\Unidad;
use PDOException;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Exception\ServiceAction;
use Incoviba\Model;
use Incoviba\Repository;
class Estado extends Ideal\Service
{
public function __construct(LoggerInterface $logger,
protected Repository\Venta\Precio $precioRepository,
protected Repository\Venta\EstadoPrecio $estadoPrecioRepository,
protected Repository\Venta\TipoEstadoPrecio $tipoEstadoPrecioRepository)
{
parent::__construct($logger);
}
/**
* @param Model\Venta\Precio $price
* @param DateTimeInterface $date
* @return void
* @throws ServiceAction\Update
*/
public function updatePrice(Model\Venta\Precio $price, DateTimeInterface $date): void
{
try {
$tipoEstado = $this->tipoEstadoPrecioRepository->fetchByDescripcion('vigente');
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Update(__CLASS__, $exception);
}
$data = [
'precio' => $price->id,
'fecha' => $date->format('Y-m-d'),
'estado' => $tipoEstado->id
];
try {
$estado = $this->estadoPrecioRepository->create($data);
$this->estadoPrecioRepository->save($estado);
} catch (Implement\Exception\EmptyResult | PDOException $exception) {
throw new ServiceAction\Update(__CLASS__, $exception);
}
}
/**
* @param Unidad $unidad
* @param DateTimeInterface $date
* @param Precio $price
* @return void
* @throws ServiceAction\Update
*/
public function replacePrices(Model\Venta\Unidad $unidad, DateTimeInterface $date, Model\Venta\Precio $price): void
{
try {
$tipoEstado = $this->tipoEstadoPrecioRepository->fetchByDescripcion('reemplazado');
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Update(__CLASS__, $exception);
}
try {
$precios = $this->precioRepository->fetchByUnidad($unidad->id);
foreach ($precios as $p) {
if ($p->id === $price->id) {
continue;
}
try {
$estado = $this->estadoPrecioRepository->fetchCurrentByPrecio($p->id);
if ($estado->tipoEstadoPrecio->id === $tipoEstado->id) {
continue;
}
$data = [
'precio' => $p->id,
'estado' => $tipoEstado->id,
'fecha' => $date->format('Y-m-d')
];
$estado = $this->estadoPrecioRepository->create($data);
$this->estadoPrecioRepository->save($estado);
} catch (Implement\Exception\EmptyResult) {}
}
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Update(__CLASS__, $exception);
}
}
}

View File

@ -0,0 +1,243 @@
<?php
namespace Incoviba\Service\Venta\Precio;
use DateTime;
use DateTimeInterface;
use PDOException;
use Psr\Http\Message\UploadedFileInterface;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction;
use Incoviba\Model;
use Incoviba\Service;
use Incoviba\Repository;
class Import extends Ideal\Service
{
public function __construct(LoggerInterface $logger,
protected Repository\Venta\Precio $precioRepository,
protected Repository\Inmobiliaria $inmobiliariaRepository,
protected Repository\Proyecto $proyectoRepository,
protected Repository\Venta\Unidad $unidadRepository,
protected Service\FileUpload $fileUploadService)
{
parent::__construct($logger);
}
/**
* @param int $projectId
* @param DateTimeInterface $date
* @param UploadedFileInterface $uploadedFile
* @return array
* @throws ServiceAction\Create
*/
public function importData(int $projectId, DateTimeInterface $date, UploadedFileInterface $uploadedFile): array
{
try {
$data = $this->fileUploadService->getData($uploadedFile);
} catch (ServiceAction\Read $exception) {
throw new ServiceAction\Create(__CLASS__, $exception);
}
$mappedData = $this->mapData($data, $projectId, $date);
$pricesData = [];
foreach ($mappedData as $row) {
$pricesData[] = [
'unidad' => $row['unidad'],
'valor' => $row['precio'],
'fecha' => $row['fecha']
];
}
try {
$priceUnitIds = array_map(fn($price) => $price['unidad'], $pricesData);
$prices = $this->precioRepository->fetchVigentesByUnidades($priceUnitIds);
$priceUnitIds = array_map(fn(array $p) => $p['id'], $prices);
$pricePrices = array_map(fn(array $p) => $p['precio']->valor, $prices);
return array_filter($pricesData, function($price) use ($priceUnitIds, $pricePrices) {
$idx = array_search($price['unidad'], $priceUnitIds);
if ($idx === false) {
return true;
}
return $pricePrices[$idx] !== $price['valor'];
});
} catch (EmptyResult $exception) {
throw new ServiceAction\Create(__CLASS__, $exception);
}
}
protected array $realTitlesMap;
protected function extractTitlesFromData(array $data): array
{
if (isset($this->realTitlesMap)) {
return $this->realTitlesMap;
}
$baseTitlesMap = [
'proyecto' => [],
'precio' => [],
'unidad' => ['departamento'],
'tipo' => ['tipo unidad'],
'fecha' => []
];
$realTitlesMap = [];
$titles = array_keys($data[0]);
foreach ($baseTitlesMap as $base => $optionals) {
foreach ($titles as $title) {
if (str_contains($title, $base)) {
$realTitlesMap[$title] = $base;
break;
}
foreach ($optionals as $optional) {
if (str_contains($title, $optional)) {
$realTitlesMap[$title] = $base;
break;
}
}
}
}
return $this->realTitlesMap = $realTitlesMap;
}
protected function mapData(array $data, int $projectId, DateTimeInterface $date): array
{
$mappedData = $this->mapTitles($data);
$mappedData = $this->mapProjects($mappedData, $projectId);
$mappedData = $this->mapUnits($mappedData);
return $this->mapDates($mappedData, $date);
}
protected function mapTitles(array $data): array
{
$titlesMap = $this->extractTitlesFromData($data);
$mappedData = [];
foreach ($data as $row) {
$mappedData []= $this->mapRow($row, $titlesMap);
}
return $mappedData;
}
protected function mapProjects(array $data, int $projectId): array
{
if (!array_key_exists('proyecto', $data[0])) {
return array_map(function($row) use ($projectId) {
$row['proyecto'] = $projectId;
return $row;
},$data);
}
$projects = $this->extractProjectsFromData($data);
$mappedData = [];
foreach ($data as $row) {
$mappedRow = $row;
$mappedRow['proyecto'] = $projects[$row['proyecto']]?->id ?? $projectId;
$mappedData []= $mappedRow;
}
return $mappedData;
}
protected function mapUnits(array $data): array
{
if (!array_key_exists('unidad', $data[0]) or !array_key_exists('tipo', $data[0])) {
return $data;
}
$unidades = [];
$mappedData = [];
foreach ($data as $row) {
if (!isset($unidades[$row['proyecto']])) {
$unidades[$row['proyecto']] = $this->unidadRepository->fetchByProyecto($row['proyecto']);
}
$tipo = $this->mapTipoUnidad($row['tipo']);
$unidad = array_filter($unidades[$row['proyecto']], function(Model\Venta\Unidad $unidad) use ($row, $tipo) {
return $unidad->descripcion == $row['unidad']
and $unidad->proyectoTipoUnidad->tipoUnidad->descripcion == $tipo;
});
if (count($unidad) === 0) {
$this->logger->warning('Unidad no encontrada', ['row' => $row]);
continue;
}
$mappedRow = $row;
$mappedRow['unidad'] = array_shift($unidad)->id;
unset($mappedRow['tipo']);
$mappedData []= $mappedRow;
}
return $mappedData;
}
protected function mapDates(array $data, DateTimeInterface $date): array
{
if (!array_key_exists('fecha', $data[0])) {
return array_map(function($row) use ($date) {
$row['fecha'] = $date;
return $row;
}, $data);
}
$mappedData = [];
foreach ($data as $row) {
$mappedRow = $row;
$newDate = DateTime::createFromFormat('d/m/Y', $row['fecha']);
$mappedRow['fecha'] = $newDate;
if ($newDate === false) {
$mappedRow['fecha'] = $date;
}
$mappedData []= $mappedRow;
}
return $mappedData;
}
protected function mapRow(array $row, array $titlesMap): array
{
$mappedRow = [];
foreach ($row as $key => $value) {
$mappedRow[$titlesMap[$key]] = $value;
}
return $mappedRow;
}
protected function mapTipoUnidad(string $tipo): string
{
if (str_contains(mb_strtolower($tipo), 'bod')) {
return 'bodega';
}
if (str_contains(mb_strtolower($tipo), 'est')) {
return 'estacionamiento';
}
if (str_contains(mb_strtolower($tipo), 'terr')) {
return 'terraza';
}
return 'departamento';
}
protected array $projectsMap;
protected function extractProjectsFromData(array $data): array
{
if (isset($this->projectsMap)) {
return $this->projectsMap;
}
$projectNames = array_unique(array_map(fn($row) => $row['proyecto'], $data));
$projects = [];
foreach ($projectNames as $projectName) {
try {
$projects[$projectName] = $this->proyectoRepository->fetchByName($projectName);
} catch (EmptyResult $exception) {
try {
$inm = $this->inmobiliariaRepository->fetchByName($projectName);
$inmProjects = $this->proyectoRepository->fetchByInmobiliaria($inm->rut);
$projects[$projectName] = $inmProjects[0];
} catch (EmptyResult $exception2) {
$this->logger->warning('Neither Project nor Society found', [
'projectName' => $projectName,
'exceptions' => [
[
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'data' => $exception->getData(),
'trace' => $exception->getTraceAsString()
],
[
'code' => $exception2->getCode(),
'message' => $exception2->getMessage(),
'file' => $exception2->getFile(),
'line' => $exception2->getLine(),
'data' => $exception2->getData(),
'trace' => $exception2->getTraceAsString()
]
],
]);
}
}
}
return $this->projectsMap = $projects;
}
}

View File

@ -1,22 +1,24 @@
<?php <?php
namespace Incoviba\Service\Venta; namespace Incoviba\Service\Venta;
use PDOException;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal\Service; use Incoviba\Common\Ideal\Service;
use Incoviba\Common\Implement\Exception\EmptyResult; use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\Create; use Incoviba\Exception\ServiceAction\Create;
use Incoviba\Exception\ServiceAction\Read; use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Exception\ServiceAction\Update; use Incoviba\Exception\ServiceAction\Update;
use Incoviba\Repository;
use Incoviba\Model; use Incoviba\Model;
use PDOException; use Incoviba\Repository;
use Psr\Log\LoggerInterface; use Incoviba\Service\Valor;
class Propietario extends Service class Propietario extends Service
{ {
public function __construct( public function __construct(
LoggerInterface $logger, LoggerInterface $logger,
protected Repository\Venta\Propietario $propietarioRepository, protected Repository\Venta\Propietario $propietarioRepository,
protected Repository\Direccion $direccionRepository protected Repository\Direccion $direccionRepository,
protected Valor $valorService
) { ) {
parent::__construct($logger); parent::__construct($logger);
} }
@ -49,6 +51,9 @@ class Propietario extends Service
$data['direccion'] = $direccion->id; $data['direccion'] = $direccion->id;
} }
$filteredData = $this->propietarioRepository->filterData($data); $filteredData = $this->propietarioRepository->filterData($data);
if (array_key_exists('telefono', $filteredData)) {
$filteredData['telefono'] = $this->valorService->telefono()->toDatabase($filteredData['telefono']);
}
try { try {
return $this->propietarioRepository->edit($propietario, $filteredData); return $this->propietarioRepository->edit($propietario, $filteredData);
} catch (PDOException | EmptyResult $exception) { } catch (PDOException | EmptyResult $exception) {
@ -85,6 +90,10 @@ class Propietario extends Service
]); ]);
$filtered_data = array_intersect_key($data, $fields); $filtered_data = array_intersect_key($data, $fields);
if (array_key_exists('telefono', $filtered_data)) {
$filtered_data['telefono'] = $this->valorService->telefono()->toDatabase($filtered_data['telefono']);
}
try { try {
$propietario = $this->propietarioRepository->fetchById($data['rut']); $propietario = $this->propietarioRepository->fetchById($data['rut']);
$edits = []; $edits = [];
@ -95,6 +104,7 @@ class Propietario extends Service
} catch (EmptyResult) { } catch (EmptyResult) {
try { try {
$propietario = $this->propietarioRepository->create($filtered_data); $propietario = $this->propietarioRepository->create($filtered_data);
$this->logger->info('Propietario', ['propietario' => $propietario]);
$propietario = $this->propietarioRepository->save($propietario); $propietario = $this->propietarioRepository->save($propietario);
} catch (PDOException $exception) { } catch (PDOException $exception) {
throw new Create(__CLASS__, $exception); throw new Create(__CLASS__, $exception);

View File

@ -0,0 +1,164 @@
<?php
namespace Incoviba\Test\Unit\Service\Venta\Precio;
use Psr\Log\LoggerInterface;
use PHPUnit\Framework\TestCase;
use Faker;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
class EstadoTest extends TestCase
{
protected LoggerInterface $logger;
protected Repository\Venta\Precio $precioRepository;
protected Repository\Venta\EstadoPrecio $estadoPrecioRepository;
protected Repository\Venta\TipoEstadoPrecio $tipoEstadoPrecioRepository;
protected function setUp(): void
{
$this->logger = $this->getMockBuilder(LoggerInterface::class)
->disableOriginalConstructor()
->getMock();
$this->precioRepository = $this->getMockBuilder(Repository\Venta\Precio::class)
->disableOriginalConstructor()
->getMock();
$this->estadoPrecioRepository = $this->getMockBuilder(Repository\Venta\EstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$this->tipoEstadoPrecioRepository = $this->getMockBuilder(Repository\Venta\TipoEstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
}
public function testUpdatePrice(): void
{
$uniqueElements = 1000;
$faker = Faker\Factory::create();
$tipoEstadoPrecio = $this->getMockBuilder(Model\Venta\TipoEstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$tipoEstadoPrecio->id = $faker->unique()->numberBetween(1, $uniqueElements);
$tipoEstadoPrecio->descripcion = 'vigente';
$tipoEstadoPrecioRepository = $this->getMockBuilder(Repository\Venta\TipoEstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$tipoEstadoPrecioRepository->method('fetchByDescripcion')->with('vigente')->willReturn($tipoEstadoPrecio);
$unidad = $this->getMockBuilder(Model\Venta\Unidad::class)
->disableOriginalConstructor()
->getMock();
$unidad->id = $faker->unique()->numberBetween(1, $uniqueElements);
$precio = $this->getMockBuilder(Model\Venta\Precio::class)
->disableOriginalConstructor()
->getMock();
$precio->id = $faker->unique()->numberBetween(1, $uniqueElements);
$precio->unidad = $unidad;
$estadoPrecio = $this->getMockBuilder(Model\Venta\EstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$estadoPrecio->id = $faker->unique()->numberBetween(1, $uniqueElements);
$estadoPrecio->precio = $precio;
$estadoPrecio->tipoEstadoPrecio = $tipoEstadoPrecio;
$estadoPrecioRepository = $this->getMockBuilder(Repository\Venta\EstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$estadoPrecioRepository->method('create')->willReturn($estadoPrecio);
$estadoPrecioRepository->method('save')->willReturnArgument(0);
$date = $faker->dateTimeBetween('-6 months');
$estadoPrecioService = new Service\Venta\Precio\Estado($this->logger, $this->precioRepository,
$estadoPrecioRepository, $tipoEstadoPrecioRepository);
$estadoPrecioService->updatePrice($precio, $date);
$this->assertTrue(true);
}
public function testReplacePrices(): void
{
$uniqueElements = 1000;
$faker = Faker\Factory::create();
$tipoEstadoPrecio1 = $this->getMockBuilder(Model\Venta\TipoEstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$tipoEstadoPrecio1->id = $faker->unique()->numberBetween(1, $uniqueElements);
$tipoEstadoPrecio1->descripcion = 'vigente';
$tipoEstadoPrecio = $this->getMockBuilder(Model\Venta\TipoEstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$tipoEstadoPrecio->id = $faker->unique()->numberBetween(1, $uniqueElements);
$tipoEstadoPrecio->descripcion = 'reemplazado';
$this->tipoEstadoPrecioRepository->method('fetchByDescripcion')
->willReturnCallback(function($descripcion) use ($tipoEstadoPrecio, $tipoEstadoPrecio1) {
return match ($descripcion) {
'vigente' => $tipoEstadoPrecio1,
'reemplazado' => $tipoEstadoPrecio,
};
});
$unidad = $this->getMockBuilder(Model\Venta\Unidad::class)
->disableOriginalConstructor()
->getMock();
$unidad->id = $faker->unique()->numberBetween(1, $uniqueElements);
$preciosCount = $faker->numberBetween(1, 10);
$precios = [];
$estados = [];
for ($i = 0; $i < $preciosCount; $i++) {
$precio = $this->getMockBuilder(Model\Venta\Precio::class)
->disableOriginalConstructor()
->getMock();
$precio->id = $faker->unique()->numberBetween(1, $uniqueElements);
$precios []= $precio;
$estado = $this->getMockBuilder(Model\Venta\EstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$estado->id = $faker->unique()->numberBetween(1, $uniqueElements);
$estado->precio = $precio;
$estado->tipoEstadoPrecio = $tipoEstadoPrecio1;
$estados []= $estado;
}
$this->precioRepository->method('fetchByUnidad')->with($unidad->id)->willReturn($precios);
$this->estadoPrecioRepository->method('fetchCurrentByPrecio')->willReturnCallback(function($precio_id) use ($estados) {
$idx = array_search($precio_id, array_map(fn($estado) => $estado->precio->id, $estados));
return $estados[$idx];
});
$newEstados = [];
foreach ($precios as $precio) {
$estado = $this->getMockBuilder(Model\Venta\EstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$estado->id = $faker->unique()->numberBetween(1, $uniqueElements);
$estado->precio = $precio;
$estado->tipoEstadoPrecio = $tipoEstadoPrecio;
$newEstados []= $estado;
}
$this->estadoPrecioRepository->method('create')->willReturnCallback(function($data) use ($newEstados) {
$idx = array_search($data['precio'], array_map(fn($estado) => $estado->precio->id, $newEstados));
return $newEstados[$idx];
});
$this->estadoPrecioRepository->method('save')->willReturnArgument(0);
$precio = $this->getMockBuilder(Model\Venta\Precio::class)
->disableOriginalConstructor()
->getMock();
$precio->id = $faker->unique()->numberBetween(1, $uniqueElements);
$precio->unidad = $unidad;
$date = $faker->dateTimeBetween('-6 months');
$estadoPrecioService = new Service\Venta\Precio\Estado($this->logger, $this->precioRepository,
$this->estadoPrecioRepository, $this->tipoEstadoPrecioRepository);
$estadoPrecioService->replacePrices($unidad, $date, $precio);
$this->assertTrue(true);
}
}

View File

@ -42,7 +42,14 @@ class Queue extends Command
} }
$io->title("[{$now->format('Y-m-d H:i:s e')}] Running Queue..."); $io->title("[{$now->format('Y-m-d H:i:s e')}] Running Queue...");
return $this->runJob(); $results = [];
for ($i = 0; $i < $this->batchSize; $i++) {
if ($this->jobService->getPending() === 0) {
break;
}
$results []= $this->runJob();
}
return count(array_filter($results, fn ($result) => $result === self::FAILURE)) === 0 ? self::SUCCESS : self::FAILURE;
} }
protected array $sections; protected array $sections;

View File

@ -2,13 +2,14 @@
namespace Incoviba\Command\Queue; namespace Incoviba\Command\Queue;
use Throwable; use Throwable;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console; use Symfony\Component\Console;
use Incoviba\Service; use Incoviba\Service;
#[Console\Attribute\AsCommand(name: 'queue:push', description: 'Push a job to the queue')] #[Console\Attribute\AsCommand(name: 'queue:push', description: 'Push a job to the queue')]
class Push extends Console\Command\Command class Push extends Console\Command\Command
{ {
public function __construct(protected Service\Job $jobService, ?string $name = null) public function __construct(protected LoggerInterface $logger, protected Service\Job $jobService, ?string $name = null)
{ {
parent::__construct($name); parent::__construct($name);
} }
@ -16,7 +17,7 @@ class Push extends Console\Command\Command
protected function configure(): void protected function configure(): void
{ {
$this->addOption('configurations', 'c', Console\Input\InputOption::VALUE_REQUIRED | Console\Input\InputOption::VALUE_IS_ARRAY, 'Job configuration options array, each job configuration must be in valid JSON format'); $this->addOption('configurations', 'c', Console\Input\InputOption::VALUE_REQUIRED | Console\Input\InputOption::VALUE_IS_ARRAY, 'Job configuration options array, each job configuration must be in valid JSON format');
$this->addOption('file', 'f', Console\Input\InputOption::VALUE_REQUIRED, 'Path to jobs configuration file with JSON array'); $this->addOption('files', 'f', Console\Input\InputOption::VALUE_REQUIRED | Console\Input\InputOption::VALUE_IS_ARRAY, 'Paths to jobs configurations files with JSON array content');
} }
protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output): int protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output): int
@ -49,19 +50,72 @@ class Push extends Console\Command\Command
} }
protected function getConfigurations(Console\Input\InputInterface $input): array protected function getConfigurations(Console\Input\InputInterface $input): array
{
return [
...$this->getFilesConfigurations($input),
...$this->getOptionConfigurations($input),
];
}
protected function getFilesConfigurations(Console\Input\InputInterface $input): array
{ {
$configurations = []; $configurations = [];
$filePath = $input->getOption('file'); $files = $input->getOption('files');
if ($filePath !== null and file_exists($filePath)) { if ($files === null) {
$json = file_get_contents($filePath); return $configurations;
if (json_validate($json)) {
$configurations = array_map(fn($configArray) => json_encode($configArray), json_decode($json, true));
} }
foreach ($files as $filePath) {
if (!file_exists($filePath)) {
continue;
} }
$configOptions = $input->getOption('configurations'); $configurations = array_merge($configurations, $this->getFileConfigurations($filePath));
if ($configOptions !== null) {
$configurations = array_merge($configurations, array_filter($configOptions, fn($config) => json_validate($config)));
} }
return $configurations; return $configurations;
} }
protected function getFileConfigurations(string $filePath): array
{
$configurations = [];
if (!file_exists($filePath)) {
return $configurations;
}
$json = file_get_contents($filePath);
if (!json_validate($json)) {
return $configurations;
}
$tmp = json_decode($json, true);
foreach ($tmp as $config) {
try {
$configurations []= $this->processConfiguration(json_encode($config));
} catch (Throwable $exception) {
$this->logger->warning($exception->getMessage(), ['exception' => $exception, 'config' => $config]);
}
}
return $configurations;
}
protected function getOptionConfigurations(Console\Input\InputInterface $input): array
{
$configurations = [];
$configOptions = $input->getOption('configurations');
if ($configOptions === null) {
return $configurations;
}
foreach ($configOptions as $config) {
try {
$configurations []= $this->processConfiguration($config);
} catch (Throwable $exception) {
$this->logger->warning($exception->getMessage(), ['exception' => $exception, 'config' => $config]);
}
}
return $configurations;
}
protected function processConfiguration(string $configuration): string
{
$json = json_decode($configuration, true);
if (!array_key_exists('type', $json) and !array_key_exists('configuration', $json)) {
throw new Console\Exception\InvalidArgumentException('Missing type or configuration key in JSON');
}
if (array_key_exists('type', $json)) {
return json_encode($json);
}
return json_encode($json['configuration']);
}
} }

0
cli/start_command Normal file → Executable file
View File