Facturacion, se agrega PropiedadUnidad

This commit is contained in:
2023-11-29 20:09:08 -03:00
parent 094209823a
commit 39048e12b3
24 changed files with 716 additions and 55 deletions

View File

@ -3,5 +3,6 @@ use Incoviba\Controller\API\Money;
$app->group('/money', function($app) {
$app->post('/ipc[/]', [Money::class, 'ipc']);
$app->post('/uf[/]', [Money::class, 'uf']);
$app->post('[/]', [Money::class, 'get']);
});

View File

@ -0,0 +1,10 @@
<?php
$app->group('/propiedades', function($app) {
$files = new FilesystemIterator(implode(DIRECTORY_SEPARATOR, [__DIR__, 'propiedades']));
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
include_once $file->getRealPath();
}
});

View File

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

View File

@ -4,3 +4,6 @@ use Incoviba\Controller\Ventas\Facturacion;
$app->group('/facturacion', function($app) {
$app->get('[/]', Facturacion::class);
});
$app->group('/factura/{venta_id}', function($app) {
$app->get('[/]', [Facturacion::class, 'show']);
});

View File

@ -45,9 +45,8 @@
if (typeof this.sent.uf[date.toISOString()] !== 'undefined') {
return this.sent.uf[date.toISOString()]
}
const url = '{{$urls->api}}/money'
const url = '{{$urls->api}}/money/uf'
const data = new FormData()
data.set('provider', 'uf')
data.set('fecha', date.toISOString())
const options = {
method: 'post',
@ -68,7 +67,6 @@
}
const url = '{{$urls->api}}/money/ipc'
const data = new FormData()
data.set('provider', 'ipc')
data.set('start', start.toISOString())
data.set('end', end.toISOString())
const options = {

View File

@ -2,10 +2,313 @@
@section('page_content')
<div class="ui container">
<form id="venta_form">
<div class="field">
<label for=""></label>
<h2 class="ui header">
Facturación -
<a href="{{$urls->base}}/proyecto/{{$venta->proyecto()->id}}">
{{$venta->proyecto()->descripcion}}<span class="ui tiny text"><sub><i
class="search icon"></i></sub></span>
</a>
-
<a href="{{$urls->base}}/venta/{{$venta->id}}">
{{$venta->propiedad()->summary()}}
</a>
</h2>
<form id="venta_form" class="ui form">
<div class="two wide field">
<label for="proporcion">Proporción Factura</label>
<div class="ui right labeled input">
<input type="number" name="proporcion" id="proporcion" value="100" max="100" min="0"/>
<div class="ui basic icon label">
<i class="percent icon"></i>
</div>
</div>
</div>
<div class="fields">
@foreach ($venta->propiedad()->unidades as $unidad)
<div class="three wide field">
<label for="precio{{$unidad->pu_id}}">Precio {{ucwords($unidad->proyectoTipoUnidad->tipoUnidad->descripcion)}} {{$unidad->descripcion}}</label>
<div class="ui right labeled input">
<input class="price" type="text" name="precio{{$unidad->pu_id}}" id="precio{{$unidad->pu_id}}" data-id="{{$unidad->pu_id}}" value="{{($unidad->valor > 0) ? $unidad->valor : $unidad->precio($venta->currentEstado()->fecha)->valor}}" />
<div class="ui basic label">UF</div>
</div>
</div>
@endforeach
</div>
</form>
<div class="ui divider"></div>
<div id="factura">
<div class="ui compact grid">
<div class="two columns row">
<div class="twelve wide column">
<strong>
{{mb_strtoupper($venta->proyecto()->inmobiliaria()->nombreCompleto())}}
</strong><br/>
GIRO: <br/>
Dirección:
</div>
<div class="four wide column">
<div class="ui center aligned red segment">
<strong>
RUT: {{$venta->proyecto()->inmobiliaria()->rut()}}<br/>
FACTURA ELECTRÓNICA<br/>
#
</strong>
</div>
</div>
</div>
<div class="row">
<table class="ui table">
<tr>
<td class="grey"><strong>Señor(es)</strong></td>
<td>{{$venta->propietario()->nombreCompleto()}}</td>
<td class="grey"><strong>RUT</strong></td>
<td>{{$venta->propietario()->rut()}}</td>
</tr>
<tr>
<td class="grey"><strong>Giro</strong></td>
<td>Otras Actividades Profesionales</td>
<td class="grey"><strong>Fecha Emisión</strong></td>
<td>{{(new IntlDateFormatter('es-CL', IntlDateFormatter::LONG, IntlDateFormatter::NONE))->format($venta->currentEstado()->fecha)}}</td>
</tr>
<tr>
<td class="grey"><strong>Dirección</strong></td>
<td>{{$venta->propietario()->datos->direccion->simple()}}</td>
<td class="grey"><strong>Comuna</strong></td>
<td>{{mb_strtoupper($venta->propietario()->datos->direccion->comuna->descripcion)}}</td>
</tr>
</table>
</div>
<div class="row">
<table class="ui celled table">
<thead>
<tr class="grey">
<th class="center aligned" colspan="6">DETALLES</th>
</tr>
<tr class="grey">
<th></th>
<th class="center aligned">Descripción</th>
<th class="center aligned">Cant/Unidad</th>
<th class="center aligned">Prec. Unit.</th>
<th class="center aligned">Ind</th>
<th class="center aligned">Total</th>
</tr>
</thead>
<tbody id="unidades"></tbody>
<tfoot>
<tr>
<td colspan="6">
<br />
<br />
<br />
<br />
</td>
</tr>
</tfoot>
</table>
</div>
<div class="row">
<div class="ten wide column"></div>
<div class="six wide column">
<table class="ui celled very compact table">
<thead>
<tr>
<th class="center aligned grey" colspan="2">TOTALES</th>
</tr>
</thead>
<tbody>
<tr>
<td class="grey">Monto Neto</td>
<td class="right aligned" id="neto"></td>
</tr>
<tr>
<td class="grey">Monto Exento</td>
<td class="right aligned" id="exento"></td>
</tr>
<tr>
<td class="grey">19% IVA</td>
<td class="right aligned" id="iva"></td>
</tr>
<tr>
<td class="grey">Monto Total</td>
<td class="right aligned"><strong id="total"></strong></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
@endsection
@push('page_scripts')
<script>
const factura = {
id: '#unidades',
totales: {},
proporcion: 1,
precio: {{$UF->transform($venta->currentEstado()->fecha, $venta->valor)}},
terreno: {{$IPC->readjust($venta->proyecto()->terreno->valor, $venta->proyecto()->terreno->date, $venta->currentEstado()->fecha)}},
uf: {{$UF->get($venta->currentEstado()->fecha)}},
unidades: JSON.parse('{!! json_encode(array_map(function(Incoviba\Model\Venta\PropiedadUnidad $unidad) use ($venta, $UF, $format) {
$precio = $unidad->valor;
return [
'pu_id' => $unidad->pu_id,
'descripcion' => ucwords($unidad->proyectoTipoUnidad->tipoUnidad->descripcion) . ' ' . $unidad->descripcion,
'precio' => $precio,
'base' => $UF->transform($venta->currentEstado()->fecha, $precio),
'prorrateo' => $unidad->prorrateo,
];
}, $venta->propiedad()->unidades)) !!}'),
build: function() {
const tbody = $(this.id)
tbody.html('')
const pesoFormatter = new Intl.NumberFormat('es-CL', {maximumFractionDigits: 0, minimumFractionDigits: 0})
const ufFormatter = new Intl.NumberFormat('es-CL', {maximumFractionDigits: 2, minimumFractionDigits: 2})
const percentFormatter = new Intl.NumberFormat('es-CL', {maximumFractionDigits: 5, minimumFractionDigits: 5})
let terreno = 0
let c = 1
const classes = [
'',
'',
'center aligned',
'right aligned',
'center aligned',
'right aligned'
]
this.unidades.forEach(unidad => {
const descuento = this.terreno * unidad.prorrateo
terreno += descuento
const bruto = unidad.base - descuento
const neto = bruto / 1.19
const data = [
c ++,
unidad.descripcion + ' (UF ' + ufFormatter.format(unidad.precio * this.proporcion) + ')',
'1 UNID',
pesoFormatter.format(neto * this.proporcion),
'AF',
pesoFormatter.format(neto * this.proporcion)
]
const row = $('<tr></tr')
data.forEach((value, i) => {
const cell = $('<td></td>')
if (classes[i] !== '') {
cell.addClass(classes[i])
}
cell.html(value)
row.append(cell)
})
tbody.append(row)
})
const bruto = this.precio - terreno
const base = bruto / 1.19
const iva = base * .19
const subtotal = base + iva
const total = subtotal + terreno
const totalUF = total / this.uf
const descuento = terreno / base
const data = [
c,
'Valor con Terreno ' + pesoFormatter.format((base + terreno) * this.proporcion) + ' - Menos valor terreno ' + pesoFormatter.format(-terreno * this.proporcion) + '<br />' +
'Base imponible ' + pesoFormatter.format(base * this.proporcion) + '<br />' +
'IVA ' + pesoFormatter.format(iva * this.proporcion) + '<br />' +
'SUBTOTAL ' + pesoFormatter.format(subtotal * this.proporcion) + '<br />' +
'Mas valor terreno ' + pesoFormatter.format(terreno * this.proporcion) + '<br />' +
'TOTAL ' + pesoFormatter.format(total * this.proporcion) + ';' + ufFormatter.format(totalUF * this.proporcion) + ' UF<br /><br />' +
'Descuento Terreno: ' + percentFormatter.format(descuento) + '%<br /><br />' +
'UF: ' + ufFormatter.format(this.uf),
'1 UNID',
pesoFormatter.format(terreno * this.proporcion),
'EX',
pesoFormatter.format(terreno * this.proporcion)
]
const row = $('<tr></tr>').addClass('top aligned')
data.forEach((value, i) => {
const cell = $('<td></td>')
if (classes[i] !== '') {
cell.addClass(classes[i])
}
cell.html(value)
row.append(cell)
})
tbody.append(row)
$(this.totales.afecto).html(pesoFormatter.format(base * this.proporcion))
$(this.totales.exento).html(pesoFormatter.format(terreno * this.proporcion))
$(this.totales.iva).html(pesoFormatter.format(iva * this.proporcion))
$(this.totales.total).html(pesoFormatter.format(total * this.proporcion))
},
update: function() {
return {
price: (id, value) => {
const idx = this.unidades.findIndex(unidad => unidad.pu_id === id)
const old_value = this.unidades[idx].precio
if (old_value === parseFloat(value)) {
return
}
const url = '{{$urls->api}}/ventas/propiedades/unidad/' + id + '/edit'
const data = new FormData()
data.set('valor', value)
return fetchAPI(url, {method: 'post', body: data}).then(response => {
if (response.ok) {
return response.json()
}
}).then(json => {
if (!json.edited) {
return
}
const idx = this.unidades.findIndex(unidad => unidad.pu_id === json.propiedad_unidad_id)
this.unidades[idx].precio = parseInt(json.input.valor)
this.unidades[idx].base = parseFloat(json.input.valor * this.unidades[idx].base / old_value)
this.build()
})
}
}
},
watch: function() {
return {
proporcion: id => {
$(id).change(event => {
const val = $(event.currentTarget).val()
if (val / 100 === this.proporcion) {
return
}
this.proporcion = val / 100
this.build()
})
},
prices: (class_name) => {
$(class_name).change(event => {
const val = $(event.currentTarget).val()
const id = $(event.currentTarget).data('id')
this.update().price(id, val)
})
}
}
},
setup: function({form_id, tbody_id, input_id, prices_class, totales_ids}) {
$(form_id).submit(event => {
event.preventDefault()
return false
})
this.id = tbody_id
this.totales = totales_ids
this.proporcion = $(input_id).val() / 100
this.watch().proporcion(input_id)
this.watch().prices(prices_class)
this.build()
}
}
$(document).ready(() => {
factura.setup({form_id: '#venta_form', tbody_id: '#unidades', input_id: '#proporcion',
prices_class: '.price', totales_ids: {
afecto: '#neto',
exento: '#exento',
iva: '#iva',
total: '#total'
}})
})
</script>
@endpush

View File

@ -16,8 +16,11 @@ return [
'base_uri' => 'https://mindicador.cl/api/',
'headers' => ['Accept' => 'application/json']
]));
$ine = new Incoviba\Service\Money\Ine(new GuzzleHttp\Client([
'base_uri' => 'https://api-calculadora.ine.cl/ServiciosCalculadoraVariacion'
]));
return (new Incoviba\Service\Money())->register('uf', $mindicador)
->register('ipc', $mindicador);
->register('ipc', $ine);
},
Predis\Client::class => function(ContainerInterface $container) {
return new Predis\Client([

View File

@ -10,6 +10,8 @@ return [
'login' => $container->get(Incoviba\Service\Login::class),
'format' => $container->get(Incoviba\Service\Format::class),
'API_KEY' => $container->get('API_KEY'),
'UF' => $container->get(Incoviba\Service\UF::class),
'IPC' => $container->get(Incoviba\Service\IPC::class)
];
if ($global_variables['login']->isIn()) {
$global_variables['user'] = $global_variables['login']->getUser();

View File

@ -62,34 +62,23 @@ class Money
}
return $this->data[$provider][$date->format('Y-m-d')];
}
/*public function uf(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService, Service\Money $moneyService): ResponseInterface
public function uf(ServerRequestInterface $request, ResponseInterface $response, Service\UF $ufService): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'input' => $body,
'uf' => 0
];
$redisKey = 'uf';
$date = new DateTimeImmutable($body['fecha']);
try {
$ufs = $this->fetchRedis($redisService, $redisKey);
if (!isset($ufs[$date->format('Y-m-d')])) {
throw new EmptyRedis($redisKey);
}
} catch (EmptyRedis) {
error_log(var_export($ufs,true));
if (!isset($ufs)) {
$ufs = [];
}
$uf = $moneyService->getUF($date);
$ufs[$date->format('Y-m-d')] = $uf;
$this->saveRedis($redisService, $redisKey, $ufs, 60 * 60 * 24 * 30);
$now = new DateTimeImmutable();
if ($date > $now) {
return $this->withJson($response, $output);
}
$output['uf'] = $ufs[$date->format('Y-m-d')];
$output['uf'] = $ufService->get($date);
return $this->withJson($response, $output);
}*/
public function ipc(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
Service\Money $moneyService): ResponseInterface
}
public function ipc(ServerRequestInterface $request, ResponseInterface $response,
Service\IPC $ipcService): ResponseInterface
{
$data = $request->getParsedBody();
$output = [
@ -97,7 +86,6 @@ class Money
'date_string' => '',
'ipc' => 0
];
$redisKey = 'ipc';
$start = new DateTimeImmutable($data['start']);
$end = new DateTimeImmutable($data['end']);
$now = new DateTimeImmutable();
@ -105,23 +93,8 @@ class Money
return $this->withJson($response, $output);
}
$dateKey = "{$start->format('Y-m')}-{$end->format('Y-m')}";
$months = $start->diff($end)->m;
$current = new DateTimeImmutable((($start <= $end) ? $start : $end)->format('Y-m-15'));
$value = 0;
$ipcs = [];
try {
$ipcs = (array) $this->fetchRedis($redisService, $redisKey);
} catch (EmptyRedis) {}
for ($i = 1; $i < $months; $i ++) {
$current = $current->add(new DateInterval("P1M"));
if (!isset($ipcs[$current->format('Y-m')])) {
$ipcs[$current->format('Y-m')] = $moneyService->getIPC($current);
$this->saveRedis($redisService, $redisKey, $ipcs, $this->time);
}
$value += $ipcs[$current->format('Y-m')];
}
$output['date_string'] = $dateKey;
$output['ipc'] = $value;
$output['ipc'] = $ipcService->get($start, $end);
return $this->withJson($response, $output);
}
}

View File

@ -1,16 +1,17 @@
<?php
namespace Incoviba\Controller\API\Ventas;
use Incoviba\Common\Implement\Exception\EmptyRedis;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Controller\API;
use Incoviba\Service;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Implement\Exception\EmptyRedis;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Controller\API\{withJson,emptyBody};
use Incoviba\Service;
use Incoviba\Controller\withRedis;
class Precios
{
use API\withJson, API\emptyBody, \Incoviba\Controller\withRedis;
use withJson, emptyBody, withRedis;
public function proyecto(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
Service\Venta\Precio $precioService): ResponseInterface

View File

@ -0,0 +1,32 @@
<?php
namespace Incoviba\Controller\API\Ventas;
use PDOException;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Incoviba\Controller\API\{withJson, emptyBody};
use Incoviba\Controller\withRedis;
use Incoviba\Common\Implement\Exception\{EmptyResult,EmptyRedis};
use Incoviba\Service;
class PropiedadesUnidades
{
use emptyBody, withJson, withRedis;
public function edit(ServerRequestInterface $request, ResponseInterface $response,
Service\Venta\PropiedadUnidad $propiedadUnidadService, int $pu_id): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'propiedad_unidad_id' => $pu_id,
'input' => $body,
'edited' => false
];
try {
$pu = $propiedadUnidadService->getById($pu_id);
$propiedadUnidadService->edit($pu, (array) $body);
$output['edited'] = true;
} catch (PDOException | EmptyResult) {}
return $this->withJson($response, $output);
}
}

View File

@ -10,6 +10,20 @@ class Direccion extends Model
public string $extra;
public Comuna $comuna;
public function simple(): string
{
$arr = [
implode(' ', [
$this->calle,
$this->numero
])
];
if ($this->extra !== '') {
$arr []= $this->extra;
}
return implode(', ', $arr);
}
public function full(): string
{
return implode(', ', [

View File

@ -0,0 +1,16 @@
<?php
namespace Incoviba\Model\Venta;
class PropiedadUnidad extends Unidad
{
public int $pu_id;
public int $propiedad_id;
public float $valor;
public function jsonSerialize(): mixed
{
return array_merge(parent::jsonSerialize(), [
'valor' => $this->valor
]);
}
}

View File

@ -70,13 +70,24 @@ class Proyecto extends Ideal\Repository
'valor_terreno', 'corredor', 'superficie_sobre_nivel', 'superficie_bajo_nivel', 'pisos',
'subterraneos'], $new_data);
}
public function fetchById(int $id): Define\Model
{
$query = $this->connection->getQueryBuilder()
->select($this->columns())
->from("{$this->getTable()} a")
->joined($this->joinTerreno())
->where("a.id = ?");
return $this->fetchOne($query, [$id]);
}
public function fetchByName(string $name): Define\Model
{
$query = $this->connection->getQueryBuilder()
->select($this->columns())
->from("{$this->getTable()} a")
->joined($this->joinTerreno())
->where("descripcion = ?");
->where("a.descripcion = ?");
return $this->fetchOne($query, [$name]);
}
public function fetchAllActive(): array

View File

@ -9,7 +9,7 @@ use Incoviba\Service;
class Propiedad extends Ideal\Repository
{
public function __construct(Define\Connection $connection, protected Service\Venta\Unidad $unidadService)
public function __construct(Define\Connection $connection, protected Service\Venta\PropiedadUnidad $unidadService)
{
parent::__construct($connection);
$this->setTable('propiedad');

View File

@ -0,0 +1,118 @@
<?php
namespace Incoviba\Repository\Venta;
use Incoviba\Common\Ideal;
use Incoviba\Common\Define;
use Incoviba\Common\Implement;
use Incoviba\Model;
use Incoviba\Service;
class PropiedadUnidad extends Ideal\Repository
{
public function __construct(Define\Connection $connection,
protected Unidad $unidadRepository,
protected Service\Proyecto\ProyectoTipoUnidad $proyectoTipoUnidadService)
{
parent::__construct($connection);
$this->setTable('propiedad_unidad');
}
public function load(array $data_row): Define\Model
{
$unidad = $this->unidadRepository->fetchById($data_row['unidad']);
$data = [
'id' => $unidad->id,
'subtipo' => $unidad->subtipo,
'piso' => $unidad->piso,
'descripcion' => $unidad->descripcion,
'orientacion' => $unidad->orientacion,
'prorrateo' => $unidad->prorrateo,
'pt' => $unidad->proyectoTipoUnidad->id,
'pu_id' => $data_row['id'],
'propiedad' => $data_row['propiedad'],
'valor' => $data_row['valor']
];
return parent::load($data);
}
public function create(?array $data = null): Model\Venta\PropiedadUnidad
{
$map = (new Implement\Repository\MapperParser(['subtipo', 'piso', 'descripcion', 'orientacion', 'prorrateo', 'valor', 'id']))
->register('propiedad', (new Implement\Repository\Mapper())
->setProperty('propiedad_id'))
->register('pt', (new Implement\Repository\Mapper())
->setProperty('proyectoTipoUnidad')
->setFunction(function($data) {
return $this->proyectoTipoUnidadService->getById($data['pt']);
}));
return $this->parseData(new Model\Venta\PropiedadUnidad(), $data, $map);
}
public function save(Define\Model $model): Model\Venta\PropiedadUnidad
{
$model->pu_id = $this->saveNew(['propiedad', 'unidad', 'valor'], [$model->propiedad_id, $model->id, $model->valor]);
return $model;
}
public function edit(Define\Model $model, array $new_data): Model\Venta\PropiedadUnidad
{
return $this->update($model, ['propiedad', 'unidad', 'valor'], $new_data);
}
public function fetchById(int $id): Define\Model
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where("id = ?");
return $this->fetchOne($query, [$id]);
}
public function fetchByVenta(int $venta_id): array
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('JOIN unidad ON a.unidad = unidad.id
JOIN venta ON venta.propiedad = a.propiedad')
->where('venta.id = ?');
return $this->fetchMany($query, [$venta_id]);
}
public function fetchByPropiedad(int $propiedad_id): array
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('JOIN `unidad` ON a.`unidad` = `unidad`.`id`')
->where('a.`propiedad` = ?')
->group('`unidad`.`id`');
return $this->fetchMany($query, [$propiedad_id]);
}
protected function update(Define\Model $model, array $columns, array $data): Define\Model
{
$changes = [];
$values = [];
foreach ($columns as $column) {
if (isset($data[$column])) {
$changes []= $column;
$values []= $data[$column];
}
}
if (count($changes) === 0) {
return $model;
}
$columns_string = implode(', ', array_map(function($property) {return "`{$property}` = ?";}, $changes));
$query = $this->connection->getQueryBuilder()
->update($this->getTable())
->set($columns_string)
->where("id = ?");
$values []= $model->{$this->getKey()};
$this->connection->execute($query, $values);
return $this->fetchById($model->{$this->getKey()});
}
protected function getKey(): string
{
return 'pu_id';
}
}

View File

@ -39,6 +39,16 @@ class Unidad extends Ideal\Repository
return $this->update($model, ['subtipo', 'piso', 'descripcion', 'orientacion', 'pt'], $new_data);
}
public function fetchById(int $id): Model\Venta\Unidad
{
$query = $this->connection->getQueryBuilder()
->select('a.*, up.prorrateo')
->from("{$this->getTable()} a")
->joined($this->joinProrrateo())
->where('a.id = ?');
return $this->fetchOne($query, [$id]);
}
public function fetchByVenta(int $venta_id): array
{
$query = $this->connection->getQueryBuilder()

38
app/src/Service/IPC.php Normal file
View File

@ -0,0 +1,38 @@
<?php
namespace Incoviba\Service;
use DateTimeInterface;
use DateTimeImmutable;
use DateInterval;
use Incoviba\Common\Implement\Exception\EmptyRedis;
class IPC
{
protected string $redisKey = 'ipc';
public function __construct(protected Redis $redisService, protected Money $moneyService) {}
public function get(DateTimeInterface $from, DateTimeInterface $to = new DateTimeImmutable()): float
{
$now = new DateTimeImmutable();
if ($to > $now) {
return 0;
}
$dateKey = "{$from->format('Y-m')}-{$to->format('Y-m')}";
$ipcs = [];
try {
$ipcs = json_decode($this->redisService->get($this->redisKey), JSON_OBJECT_AS_ARRAY);
if (!isset($ipcs[$dateKey])) {
throw new EmptyRedis($this->redisKey);
}
} catch (EmptyRedis) {
$ipc = $this->moneyService->getIPC($from, $to);
$ipcs[$dateKey] = $ipc;
$this->redisService->set($this->redisKey, json_encode($ipcs), 60 * 60 * 24 * 30);
}
return $ipcs[$dateKey];
}
public function readjust(float $base, DateTimeInterface $from, DateTimeInterface $to = new DateTimeImmutable()):float
{
return $base * (1 + $this->get($from, $to->sub(new DateInterval('P1M'))));
}
}

View File

@ -41,10 +41,10 @@ class Money
return 0;
}
}
public function getIPC(DateTimeInterface $dateTime): float
public function getIPC(DateTimeInterface $start, DateTimeInterface $end): float
{
try {
return $this->getProvider('ipc')->get(MiIndicador::IPC, $dateTime);
return $this->getProvider('ipc')->getVar($start, $end);
} catch (EmptyResponse) {
return 0;
}

View File

@ -0,0 +1,49 @@
<?php
namespace Incoviba\Service\Money;
use DateTimeInterface;
use DateTimeImmutable;
use DateInterval;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Client\ClientInterface;
use Incoviba\Common\Implement\Exception\EmptyResponse;
use Incoviba\Common\Define\Money\Provider;
class Ine implements Provider
{
protected string $uri = 'https://api-calculadora.ine.cl/ServiciosCalculadoraVariacion';
public function __construct(protected ClientInterface $client) {}
public function get(string $money_symbol, DateTimeInterface $dateTime): float
{
$end = new DateTimeImmutable($dateTime->format('Y-m-1'));
$start = $end->sub(new DateInterval('P1M'));
return $this->getVar($start, $end);
}
public function getVar(DateTimeInterface $start, DateTimeInterface $end): float
{
$base = 1000000000;
$request_query = [
'mesInicio' => $start->format('m'),
'AnioInicio' => $start->format('Y'),
'mesTermino' => $end->format('m'),
'AnioTermino' => $end->format('Y'),
'valor_a_ajustar' => $base
];
$request_uri = implode('?', [
$this->uri,
implode('&', array_map(function($val, $key) {
return "{$key}={$val}";
}, $request_query, array_keys($request_query)))
]);
try {
$response = $this->client->get($request_uri);
} catch (GuzzleException) {
throw new EmptyResponse($request_uri);
}
$body = $response->getBody();
$json = json_decode($body->getContents());
return ((int) str_replace('.', '', $json[0]->valorajustado) - $base) / $base;
}
}

35
app/src/Service/UF.php Normal file
View File

@ -0,0 +1,35 @@
<?php
namespace Incoviba\Service;
use DateTimeInterface;
use Incoviba\Common\Implement\Exception\EmptyRedis;
class UF
{
protected string $redisKey = 'uf';
public function __construct(protected Redis $redisService, protected Money $moneyService) {}
public function get(DateTimeInterface $date): float
{
$ufs = [];
try {
$ufs = json_decode($this->redisService->get($this->redisKey), JSON_OBJECT_AS_ARRAY);
if (!isset($ufs[$date->format('Y-m-d')])) {
throw new EmptyRedis($this->redisKey);
}
$uf = $ufs[$date->format('Y-m-d')];
} catch (EmptyRedis) {
$uf = $this->moneyService->getUF($date);
$ufs[$date->format('Y-m-d')] = $uf;
$this->redisService->set($this->redisKey, json_encode($ufs), 60 * 60 * 24 * 30);
}
return $uf;
}
public function transform(DateTimeInterface $date, float $input, string $from = 'uf'): float
{
$uf = $this->get($date);
return $input * (($from === 'uf') ? $uf : 1/$uf);
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace Incoviba\Service\Venta;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Repository;
use Incoviba\Service;
use Incoviba\Model;
class PropiedadUnidad
{
public function __construct(protected Repository\Venta\PropiedadUnidad $propiedadUnidadRepository, protected Precio $precioService) {}
public function getById(int $unidad_id): Model\Venta\PropiedadUnidad
{
return $this->process($this->propiedadUnidadRepository->fetchById($unidad_id));
}
public function getByVenta(int $venta_id): array
{
return array_map([$this, 'process'], $this->propiedadUnidadRepository->fetchByVenta($venta_id));
}
public function getByPropiedad(int $propiedad_id): array
{
return array_map([$this, 'process'], $this->propiedadUnidadRepository->fetchByPropiedad($propiedad_id));
}
public function edit(Model\Venta\PropiedadUnidad $propiedadUnidad, array $data): Model\Venta\PropiedadUnidad
{
return $this->process($this->propiedadUnidadRepository->edit($propiedadUnidad, $data));
}
protected function process($unidad): Model\Venta\PropiedadUnidad
{
try {
$unidad->precios = $this->precioService->getByUnidad($unidad->id);
$unidad->currentPrecio = $this->precioService->getVigenteByUnidad($unidad->id);
} catch (EmptyResult) {
}
return $unidad;
}
}

View File

@ -10,7 +10,7 @@ class Unidad
{
public function __construct(
protected Repository\Venta\Unidad $unidadRepository,
protected Service\Venta\Precio $precioService
protected Precio $precioService
) {}
public function getById(int $unidad_id): Model\Venta\Unidad

View File

@ -14,9 +14,8 @@ class UF extends Command
{
$this->logger->debug("Running {$this->getName()}");
$now = new DateTimeImmutable();
$uri = '/api/money';
$uri = '/api/money/uf';
$data = [
'provider' => 'uf',
'fecha' => $now->format('Y-m-d')
];
$output->writeln("POST {$uri}");