2023-09-12

This commit is contained in:
Juan Pablo Vial
2023-09-13 18:51:46 -03:00
parent fa15da1ee2
commit 0cd357b6cb
47 changed files with 1225 additions and 102 deletions

View File

@ -0,0 +1,9 @@
<?php
namespace Incoviba\Common\Define\Money;
use DateTimeInterface;
interface Provider
{
public function get(string $money_symbol, DateTimeInterface $dateTime): float;
}

View File

@ -17,7 +17,10 @@ abstract class Model implements Define\Model
protected function runFactory(string $property): mixed
{
return $this->factories[$property]->run();
if (isset($this->factories[$property])) {
return $this->factories[$property]->run();
}
return null;
}
public function jsonSerialize(): mixed

View File

@ -112,14 +112,15 @@ abstract class Repository implements Define\Repository
$values []= $data[$column];
}
}
if (count($changes) === 0) {
return $model;
}
$columns_string = implode(', ', array_map(function($property) {return "`{$property}` = ?";}, $changes));
$query = "UPDATE `{$this->getTable()}` SET {$columns_string} WHERE `{$this->getKey()}` = ?";
$values []= $model->id;
$values []= $model->{$this->getKey()};
$this->connection->execute($query, $values);
return $this->fetchById($model->id);
return $this->fetchById($model->{$this->getKey()});
}
protected function fetchOne(string $query, ?array $data = null): Define\Model
{

View File

@ -0,0 +1,15 @@
<?php
namespace Incoviba\Common\Implement\Exception;
use Exception;
use Throwable;
class EmptyResponse extends Exception
{
public function __construct(string $uri = "", ?Throwable $previous = null)
{
$message = "Empty Response from {$uri}";
$code = 800;
parent::__construct($message, $code, $previous);
}
}

View File

@ -5,11 +5,12 @@ use Incoviba\Common\Implement\Repository\Mapper;
class Boolean extends Mapper
{
public function __construct(string $column, ?string $property = null)
public function __construct(string $column, ?string $property = null, bool $default = false)
{
$this->setFunction(function($data) use ($column) {
return $data[$column] !== 0;
});
$this->setDefault($default);
if ($property !== null) {
$this->setProperty($property);
}

View File

@ -2,13 +2,14 @@
"name": "incoviba/web",
"type": "project",
"require": {
"slim/slim": "^4.11",
"php-di/php-di": "^7.0",
"php-di/slim-bridge": "^3.4",
"berrnd/slim-blade-view": "^1.0",
"guzzlehttp/guzzle": "^7.8",
"monolog/monolog": "^3.4",
"nyholm/psr7": "^1.8",
"nyholm/psr7-server": "^1.0"
"nyholm/psr7-server": "^1.0",
"php-di/php-di": "^7.0",
"php-di/slim-bridge": "^3.4",
"slim/slim": "^4.11"
},
"require-dev": {
"phpunit/phpunit": "^10.2"

View File

@ -9,7 +9,10 @@ $app->group('/ventas', function($app) {
}
include_once $file->getRealPath();
}
$app->get('/add', [Ventas::class, 'add']);
$app->group('/add', function($app) {
$app->post('[/]', [Ventas::class, 'doAdd']);
$app->get('[/]', [Ventas::class, 'add']);
});
$app->get('[/]', Ventas::class);
});
$app->group('/venta/{proyecto_nombre:[A-za-zÑñ\+\ %0-9]+}/{unidad_descripcion:[0-9]+}', function($app) {
@ -22,6 +25,11 @@ $app->group('/venta/{venta_id:[0-9]+}', function($app) {
$app->group('/propiedad', function($app) {
$app->get('[/]', [Ventas::class, 'propiedad']);
});
$app->group('/pie', function($app) {
$app->group('/cuotas', function($app) {
$app->get('[/]', [Ventas::class, 'cuotas']);
});
});
$app->get('/edit[/]', [Ventas::class, 'edit']);
$app->get('[/]', [Ventas::class, 'show']);
});

View File

@ -0,0 +1,13 @@
<?php
use Incoviba\Controller\Ventas\Pies;
use Incoviba\Controller\Ventas\Cuotas;
$app->group('/pie/{pie_id}', function($app) {
$app->group('/cuotas', function($app) {
$app->group('/add', function($app) {
$app->get('[/]', [Cuotas::class, 'add']);
$app->post('[/]', [Cuotas::class, 'doAdd']);
});
$app->get('[/]', [Pies::class, 'cuotas']);
});
});

View File

@ -1,4 +1,22 @@
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js" integrity="sha512-3gJwYpMe3QewGELv8k/BX9vcqhryRdzRMxVfq6ngyWXwo03GFEzjsUm8Q7RZcHPHksttq7/GFoxjCVUjkjvPdw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fomantic-ui/2.9.2/semantic.min.js" integrity="sha512-5cguXwRllb+6bcc2pogwIeQmQPXEzn2ddsqAexIBhh7FO1z5Hkek1J9mrK2+rmZCTU6b6pERxI7acnp1MpAg4Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
const calendar_date_options = {
type: 'date',
firstDayOfWeek: 1,
today: true,
monthFirst: false,
text: {
days: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
months: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
monthsShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
today: 'Hoy'
},
formatter: {
date: 'DD-MM-YYYY'
},
}
</script>
@stack('page_scripts')

View File

@ -0,0 +1 @@
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>

View File

@ -3,7 +3,7 @@
@section('page_content')
<div class="ui container">
<h2 class="ui header">Nueva Venta</h2>
<form class="ui form" action="{{$urls->base}}/ventas/add" method="post">
<form class="ui form" id="add_form" action="{{$urls->base}}/ventas/add" method="post">
<label for="fecha_venta">Fecha de Venta</label>
<div class="inline field">
<div class="ui calendar" id="fecha_venta_calendar">
@ -57,7 +57,7 @@
<i class="warehouse icon"></i>
{{--Bodega--}}
</button>
<table id="unidades" class="ui very basic compact collapsing table"></table>
<div id="unidades" class="ui ordered list"></div>
<h4 class="ui dividing header">FORMA DE PAGO</h4>
<label for="valor">Valor</label>
<div class="inline field">
@ -605,7 +605,6 @@
}
}
}
console.debug(data)
})
}
}
@ -683,12 +682,10 @@
const unidad = new Unidad({number})
this.added.push(unidad)
$(this.ids.unidades).append(
$('<tr></tr>').attr('data-number', number).append(
$('<td></td>').append(
$('<div></div>').addClass('item').attr('data-number', number).append(
$('<div></div>').addClass('content').append(tipo.charAt(0).toUpperCase() + tipo.slice(1) + ' ').append(
unidad.draw(this.unidades[tipo])
)
).append(
$('<td></td>').append(
).append(
$('<button></button>').addClass('ui icon button').attr('type', 'button').attr('data-number', number).append(
$('<i></i>').addClass('remove icon')
).click(event => {
@ -705,7 +702,7 @@
if (index === -1) {
return
}
$(this.ids.unidades).find("tr[data-number='" + number + "']").remove()
$(this.ids.unidades).find("div.item[data-number='" + number + "']").remove()
this.added.splice(index, 1)
}
reset() {
@ -737,14 +734,10 @@
})
dropdown.append(menu)
dropdown.dropdown()
return $('<div></div>').addClass('inline fields').attr('data-number', this.number).append(dropdown)
return dropdown
}
}
const unidades = {
data: []
}
class Payment {
ids
@ -754,10 +747,10 @@
checkbox: checkbox_id
}
$(this.ids.base).hide()
document.getElementById(this.ids.checkbox).onchange = event => {
this.toggle()
}
this.toggle()
}
get status() {
@ -772,13 +765,12 @@
}
}
function showErrors(errors) {
console.debug(errors)
}
$(document).ready(() => {
$('#fecha_venta_calendar').calendar({
type: 'date',
formatter: {
date: 'DD-MM-YYYY'
}
})
$('#fecha_venta_calendar').calendar(calendar_date_options)
new Propietario({id: '#propietario', id_tipo: 'persona_propietario', id_cantidad: 'cantidad_propietario'})
new Proyecto({unidades_id: '#unidades', proyecto_id: '#proyecto'})
@ -794,6 +786,24 @@
checkbox_id: 'has_' + payment
})
})
$('#add_form').submit(event => {
event.preventDefault()
const data = new FormData(event.currentTarget)
const uri = $(event.currentTarget).attr('action')
fetch(uri, {method: 'post', body: data}).then(response => {
if (response.ok) {
return response.json()
}
}).then(data => {
if (data.status) {
window.location = '{{$urls->base}}'
return true
}
showErrors(data.errors)
})
return false
})
})
</script>
@endpush

View File

@ -79,7 +79,8 @@
columnDefs: [
{
target: 6,
visible: false
visible: false,
searchable: false
},
{
target: 2,

View File

@ -0,0 +1,79 @@
@extends('layout.base')
@section('page_content')
<div class="ui container">
<div class="ui two column grid">
<h1 class="four wide column header">
<div class="content">
<div class="ui dividing sub header">{{$venta->proyecto()->descripcion}}</div>
{{$venta->propiedad()->summary()}}
</div>
</h1>
</div>
<h2>Cuotas - Pie</h2>
<table class="ui table" id="cuotas">
<thead>
<tr>
<th>#</th>
<th>Fecha</th>
<th>Fecha ISO</th>
<th>Banco</th>
<th>Identificador</th>
<th>Valor</th>
</tr>
</thead>
<tbody>
@foreach ($venta->formaPago()->pie->cuotas() as $cuota)
<tr>
<td>{{$cuota->numero}}</td>
<td>
{{$cuota->pago->fecha->format('d-m-Y')}}
</td>
<td>
{{$cuota->pago->fecha->format('Y-m-d')}}
</td>
<td>
{{$cuota->pago->banco->nombre}}
</td>
<td>
{{$cuota->pago->identificador}}
</td>
<td>
{{$format->pesos($cuota->pago->valor)}}
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endsection
@include('layout.body.scripts.datatables')
@push('page_scripts')
<script type="text/javascript">
$(document).ready(() => {
new DataTable('#cuotas', {
language: {
info: 'Mostrando página _PAGE_ de _PAGES_',
infoEmpty: 'No hay cuotas ingresadas',
infoFiltered: '(filtrado de _MAX_ cuotas)',
lengthMenu: 'Mostrando de a _MENU_ cuotas',
zeroRecords: 'No se encotró cuotas con ese criterio',
search: 'Buscar: '
},
columnDefs: [
{
target: 2,
visible: false,
searchable: false
}
],
order: [
[0, 'asc'],
[2, 'asc']
]
})
})
</script>
@endpush

View File

@ -0,0 +1,142 @@
@extends('layout.base')
@section('page_content')
<div class="ui container">
<div class="ui two column grid">
<h1 class="four wide column header">
<div class="content">
<div class="ui dividing sub header">{{$venta->proyecto()->descripcion}}</div>
{{$venta->propiedad()->summary()}}
</div>
</h1>
</div>
<h2>Agregar Cuotas - Pie</h2>
<form class="ui form" id="add_form" action="{{$urls->base}}/ventas/pie/{{$pie->id}}/cuotas/add" method="post">
<table class="ui table">
<thead>
<tr>
<th>#</th>
<th>Fecha</th>
<th>Banco</th>
<th>Identificador</th>
<th>Valor</th>
</tr>
</thead>
<tbody id="cuotas">
@for ($i = count($pie->cuotas()); $i < $pie->cuotas - count($pie->cuotas()); $i ++)
<tr>
<td>{{$i + 1}}</td>
<td>
<div class="inline field">
<div class="ui calendar fecha" data-index="{{$i}}">
<div class="ui icon input">
<input type="text" name="fecha{{$i}}" />
<i class="calendar icon"></i>
</div>
</div>
<button class="ui mini compact basic icon button copy fecha" type="button" data-index="{{$i}}">
<i class="down arrow icon"></i>
</button>
</div>
</td>
<td>
<div class="ui search selection dropdown banco" data-index="{{$i}}">
<input type="hidden" name="banco{{$i}}" />
<i class="dropdown icon"></i>
<div class="default text">Banco</div>
<div class="menu">
@foreach ($bancos as $banco)
@if ($banco->nombre === '')
@continue
@endif
<div class="item" data-value="{{$banco->id}}">{{$banco->nombre}}</div>
@endforeach
</div>
</div>
<button class="ui mini compact basic icon button copy banco" type="button" data-index="{{$i}}">
<i class="down arrow icon"></i>
</button>
</td>
<td>
<div class="ui input">
<input type="text" name="identificador{{$i}}" />
</div>
</td>
<td>
<div class="inline field">
<div class="ui left labeled input">
<div class="ui label">$</div>
<input type="text" name="valor{{$i}}" />
</div>
<button class="ui mini compact basic icon button copy valor" type="button" data-index="{{$i}}">
<i class="down arrow icon"></i>
</button>
</div>
</td>
</tr>
@endfor
</tbody>
<tfoot>
<tr>
<td colspan="5">
<button class="ui button" type="submit">
Agregar
</button>
</td>
</tr>
</tfoot>
</table>
</form>
</div>
@endsection
@include('layout.body.scripts.dayjs')
@push('page_scripts')
<script type="text/javascript">
function setDate(index, calendar, date = new Date()) {
const d = dayjs(date)
$(calendar).calendar('set date', new Date(d.add(index, 'M').valueOf()))
}
function formatValor(valor) {
if (valor.length < 3) {
return valor
}
let new_valor = parseInt(valor.split('.').join(''))
const formatter = new Intl.NumberFormat('es-CL', {style: 'decimal', maximumFractionDigits: 0})
return formatter.format(new_valor)
}
$(document).ready(() => {
$('.fecha.calendar').calendar(calendar_date_options).each(setDate)
$('.copy.fecha').click(event => {
const index = $(event.currentTarget).data('index')
const calendar = $(".fecha.calendar[data-index='" + index + "']")
const fecha = calendar.calendar('get date')
for (let i = index + 1; i < {{$pie->cuotas - count($pie->cuotas())}}; i ++) {
setDate(i - index, $(".fecha.calendar[data-index='" + i + "']"), fecha)
}
})
$('.banco.ui.dropdown').dropdown()
$('.copy.banco').click(event => {
const index = $(event.currentTarget).data('index')
const banco = $(".banco.dropdown[data-index='" + index + "']").dropdown('get value')
for (let i = index + 1; i < {{$pie->cuotas - count($pie->cuotas())}}; i ++) {
$(".banco.dropdown[data-index='" + i + "']").dropdown('set selected', banco)
}
})
$("input[name^='valor']").each((index, input) => {
$(input).change(event => {
const valor = $(event.currentTarget).val()
$(event.currentTarget).val(formatValor(valor))
})
})
$('.copy.valor').click(event => {
const index = $(event.currentTarget).data('index')
const valor = $("[name='valor" + index + "']").val()
for (let i = index + 1; i < {{$pie->cuotas - count($pie->cuotas())}}; i ++) {
$("[name='valor" + i + "']").val(valor)
}
})
})
</script>
@endpush

View File

@ -10,5 +10,13 @@ return [
$container->has('COOKIE_DOMAIN') ? $container->get('COOKIE_DOMAIN') : '',
$container->has('COOKIE_PATH') ? $container->get('COOKIE_PATH') : ''
);
}
},
Incoviba\Service\Money::class => function(ContainerInterface $container) {
$mindicador = new Incoviba\Service\Money\MiIndicador(new GuzzleHttp\Client([
'base_uri' => 'https://mindicador.cl/api/',
'headers' => ['Accept' => 'application/json']
]));
return (new Incoviba\Service\Money())->register('uf', $mindicador)
->register('ipc', $mindicador);
},
];

View File

@ -29,7 +29,7 @@ class Proyectos
{
$output = ['proyecto_id' => $proyecto_id, 'unidades' => [], 'total' => 0];
try {
$unidades = $unidadRepository->fetchByProyecto($proyecto_id);
$unidades = $unidadRepository->fetchDisponiblesByProyecto($proyecto_id);
$tipos = [];
foreach ($unidades as $unidad) {
if (!isset($tipos[$unidad->proyectoTipoUnidad->tipoUnidad->descripcion])) {

View File

@ -111,4 +111,25 @@ class Ventas
$proyectos = $proyectoRepository->fetchAllActive();
return $view->render($response, 'ventas.add', compact('regiones', 'proyectos'));
}
public function doAdd(ServerRequestInterface $request, ResponseInterface $response, Service\Venta $ventaService): ResponseInterface
{
$data = $request->getParsedBody();
$output = [
'status' => false,
'errors' => []
];
try {
$ventaService->add($data);
$output['status'] = true;
} catch (\Exception $exception) {
$output['errors'] = $exception;
}
$response->getBody()->write(json_encode($output));
return $response->withHeader('Content-Type', 'application/json');
}
public function cuotas(ServerRequestInterface $request, ResponseInterface $response, Service\Venta $ventaService, View $view, int $venta_id): ResponseInterface
{
$venta = $ventaService->getById($venta_id);
return $view->render($response, 'ventas.pies.cuotas', compact('venta'));
}
}

View File

@ -8,6 +8,7 @@ use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Common\Alias\View;
use Incoviba\Repository;
use Incoviba\Service;
use Incoviba\Model;
class Cuotas
{
@ -72,4 +73,34 @@ class Cuotas
$response->getBody()->write(json_encode($output));
return $response->withHeader('Content-Type', 'application/json');
}
public function add(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Pie $pieService, Repository\Venta $ventaRepository, Repository\Banco $bancoRepository, View $view, int $pie_id): ResponseInterface
{
$pie = $pieService->getById($pie_id);
$venta = $ventaRepository->fetchByPie($pie_id);
$bancos = $bancoRepository->fetchAll();
usort($bancos, function(Model\Banco $a, Model\Banco $b) {
return strcmp($a->nombre, $b->nombre);
});
return $view->render($response, 'ventas.pies.cuotas.add', compact('pie', 'venta', 'bancos'));
}
public function doAdd(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Pie $pieService, Repository\Venta $ventaRepository, int $pie_id): ResponseInterface
{
$body = $request->getParsedBody();
$pie = $pieService->getById($pie_id);
$venta = $ventaRepository->fetchByPie($pie_id);
$total = $pie->cuotas - count($pie->cuotas());
$start = count($pie->cuotas());
for ($i = $start; $i < $total; $i ++) {
$data = [
'pie' => $pie->id,
'fecha' => $body["fecha{$i}"],
'banco' => $body["banco{$i}"],
'identificador' => $body["identificador{$i}"],
'valor' => str_replace(['.', ','], ['', ''], $body["valor{$i}"]),
'numero' => $i + 1,
];
$pieService->addCuota($data);
}
return $response->withHeader('Location', "/venta/{$venta->id}");
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Incoviba\Controller\Ventas;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Service;
use Incoviba\Repository;
use Incoviba\Model;
class Pies
{
public function cuotas(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Pie $pieService, Repository\Venta $ventaRepository, Repository\Banco $bancoRepository, View $view, int $pie_id): ResponseInterface
{
$pie = $pieService->getById($pie_id);
$venta = $ventaRepository->fetchByPie($pie_id);
$bancos = $bancoRepository->fetchAll();
usort($bancos, function(Model\Banco $a, Model\Banco $b) {
return strcmp($a->nombre, $b->nombre);
});
return $view->render($response, 'ventas.pies.cuotas', compact('pie', 'venta', 'bancos'));
}
}

View File

@ -15,6 +15,7 @@ class Venta extends Ideal\Model
public float $valor;
public bool $relacionado;
protected ?Venta\Entrega $entrega;
public float $uf;
public array $estados;
public Venta\EstadoVenta $currentEstado;

View File

@ -5,11 +5,13 @@ use Incoviba\Common\Ideal;
class Credito extends Ideal\Model
{
public ?float $valor;
public Pago $pago;
public function jsonSerialize(): mixed
{
return array_merge(parent::jsonSerialize(), [
'valor' => $this->valor,
'pago' => $this->pago
]);
}

View File

@ -3,6 +3,7 @@ namespace Incoviba\Model\Venta;
use DateTimeInterface;
use Incoviba\Common\Ideal\Model;
use Incoviba\Model\Venta;
class Pie extends Model
{

View File

@ -12,7 +12,7 @@ class Propietario extends Model
public array $apellidos;
public Datos $datos;
public ?Propietario $representante;
public ?bool $otro;
public ?Propietario $otro;
public function rut(): string
{

View File

@ -40,4 +40,9 @@ class Direccion extends Ideal\Repository
$query = "SELECT * FROM `{$this->getTable()}` WHERE `calle` = ? AND `numero` = ?";
return $this->fetchMany($query, [$calle, $numero]);
}
public function fetchByCalleAndNumeroAndExtra(string $calle, int $numero, string $extra): Model\Direccion
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `calle` = ? AND `numero` = ? AND `extra` = ?";
return $this->fetchOne($query, [$calle, $numero, $extra]);
}
}

View File

@ -27,9 +27,9 @@ class Venta extends Ideal\Repository
$this->setTable('venta');
}
public function create(?array $data = null): Define\Model
public function create(?array $data = null): Model\Venta
{
$map = (new Implement\Repository\MapperParser())
$map = (new Implement\Repository\MapperParser(['uf']))
->register('propietario', (new Implement\Repository\Mapper())
->setFactory((new Implement\Repository\Factory())
->setCallable([$this->propietarioRepository, 'fetchById'])
@ -65,7 +65,7 @@ class Venta extends Ideal\Repository
]
];
foreach ($map as $column => $settings) {
if ($data[$column] !== null and $data[$column] !== 0) {
if (isset($data[$column]) and $data[$column] !== 0) {
if (isset($settings['repository'])) {
$fp->{$settings['property'] ?? $column} = $settings['repository']->fetchById($data[$column]);
continue;
@ -89,7 +89,7 @@ class Venta extends Ideal\Repository
->setFunction(function($data) {
return $data['escritura'] !== null;
}))*/
->register('entrega', (new Implement\Repository\Mapper())
/*->register('entrega', (new Implement\Repository\Mapper())
->setFactory((new Implement\Repository\Factory())
->setCallable(function($entrega_id) {
if ($entrega_id !== null and $entrega_id !== 0) {
@ -97,7 +97,8 @@ class Venta extends Ideal\Repository
}
return null;
})
->setArgs([$data['entrega']])))
->setArgs([$data['entrega']]))
->setDefault(null))*/
/*->register('entregado', (new Implement\Repository\Mapper())
->setFactory((new Implement\Repository\Factory())
->setCallable(function($entrega_id) {
@ -114,28 +115,27 @@ class Venta extends Ideal\Repository
->register('fecha_ingreso', new Implement\Repository\Mapper\DateTime('fecha_ingreso', 'fechaIngreso'))
//->register('avalchile')
//->register('agente')
//->register('uf')
->register('relacionado', new Implement\Repository\Mapper\Boolean('relacionado'));
//->register('promocion')
//->register('resciliacion')
//->register('devolucion');
return $this->parseData(new Model\Venta(), $data, $map);
}
public function save(Define\Model $model): Define\Model
public function save(Define\Model $model): Model\Venta
{
$model->id = $this->saveNew(
['propietario', 'propiedad', 'pie', 'bono_pie', 'credito', 'escritura', 'subsidio', 'escriturado',
'entrega', 'entregado', 'fecha', 'valor_uf', 'estado', 'fecha_ingreso', 'avalchile', 'agente', 'uf',
'relacionado', 'promocion', 'resciliacion', 'devolucion'],
[$model->propietario->rut, $model->propiedad()->id, $model->formaPago()->Pie?->id, $model->formaPago()->bonoPie?->id,
[$model->propietario()->rut, $model->propiedad()->id, $model->formaPago()->pie?->id, $model->formaPago()->bonoPie?->id,
$model->formaPago()->credito?->id, $model->formaPago()->escritura?->id, $model->formaPago()->subsidio?->id,
$model->formaPago()->escritura !== null ? 1 : 0, null, 0, $model->fecha->format('Y-m-d'), $model->valor,
$model->currentEstado->vigente ? 1 : 0, $model->fechaIngreso->format('Y-m-d'), '', null, 0,
$model->relacionado ? 1 : 0, null, null, null]
$model->formaPago()->escritura !== null ? $model->formaPago()->escritura->pago->fecha->format('Y-m-d') : null,
null, null, $model->fecha->format('Y-m-d'), $model->valor, 1, $model->fechaIngreso->format('Y-m-d'),
null, null, $model->uf, $model->relacionado ? 1 : 0, null, null, null]
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Define\Model
public function edit(Define\Model $model, array $new_data): Model\Venta
{
return $this->update($model, ['propietario', 'propiedad', 'pie', 'bono_pie', 'credito', 'escritura', 'subsidio', 'escriturado',
'entrega', 'entregado', 'fecha', 'valor_uf', 'estado', 'fecha_ingreso', 'avalchile', 'agente', 'uf',
@ -155,7 +155,7 @@ WHERE ptu.`proyecto` = ? AND tev.`activa`
GROUP BY a.`id`";
return $this->fetchMany($query, [$proyecto_id]);
}
public function fetchByProyectoAndUnidad(string $proyecto_nombre, int $unidad_descripcion): Define\Model
public function fetchByProyectoAndUnidad(string $proyecto_nombre, int $unidad_descripcion): Model\Venta
{
$query = "SELECT a.*
FROM `{$this->getTable()}` a
@ -168,4 +168,9 @@ FROM `{$this->getTable()}` a
WHERE `proyecto`.`descripcion` = ? AND `unidad`.`descripcion` = ? AND tev.`activa`";
return $this->fetchOne($query, [$proyecto_nombre, $unidad_descripcion]);
}
public function fetchByPie(int $pie_id): Model\Venta
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `pie` = ?";
return $this->fetchOne($query, [$pie_id]);
}
}

View File

@ -15,7 +15,7 @@ class Credito extends Ideal\Repository
$this->setTable('credito');
}
public function create(?array $data = null): Define\Model
public function create(?array $data = null): Model\Venta\Credito
{
$map = (new Implement\Repository\MapperParser())
->register('pago', (new Implement\Repository\Mapper())
@ -24,15 +24,15 @@ class Credito extends Ideal\Repository
}));
return $this->parseData(new Model\Venta\Credito(), $data, $map);
}
public function save(Define\Model $model): Define\Model
public function save(Define\Model $model): Model\Venta\Credito
{
$model->id = $this->saveNew(
['banco', 'valor', 'fecha', 'uf', 'abonado', 'fecha_abono', 'pago'],
[$model->pago->banco->id, $model->pago->valor, $model->pago->fecha->format('Y-m-d'), $model->pago->uf, null, null, $model->pago->id]
[$model->pago->banco?->id, $model->valor ?? (($model->pago->uf > 0) ? $model->pago->valor / $model->pago->uf : null), $model->pago->fecha->format('Y-m-d'), $model->pago->uf, null, null, $model->pago->id]
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Define\Model
public function edit(Define\Model $model, array $new_data): Model\Venta\Credito
{
return $this->update($model, ['banco', 'valor', 'fecha', 'uf', 'abonado', 'fecha_abono', 'pago'], $new_data);
}

View File

@ -23,14 +23,17 @@ class Cuota extends Ideal\Repository
$this->setTable('cuota');
}
public function create(?array $data = null): Define\Model
public function create(?array $data = null): Model\Venta\Cuota
{
$map = (new Implement\Repository\MapperParser(['valor', 'uf', 'numero']))
$map = (new Implement\Repository\MapperParser(['uf', 'numero']))
->register('pie', (new Implement\Repository\Mapper())
->setFunction(function($data) {
return $this->pieRepository->fetchById($data['pie']);
}))
->register('fecha', new Implement\Repository\Mapper\DateTime('fecha'))
->register('valor_$', (new Implement\Repository\Mapper())
->setProperty('valor')
)
->register('estado', new Implement\Repository\Mapper\Boolean('estado'))
->register('banco', (new Implement\Repository\Mapper())
->setFunction(function($data) {
@ -55,18 +58,18 @@ class Cuota extends Ideal\Repository
return $this->parseData(new Model\Venta\Cuota(), $data, $map);
}
public function save(Define\Model $model): Define\Model
public function save(Define\Model $model): Model\Venta\Cuota
{
$model->id = $this->saveNew(
['pie', 'fecha', 'valor', 'estado', 'banco', 'fecha_pago', 'abonado', 'fecha_abonado', 'uf', 'pago', 'numero'],
[$model->pie->id, $model->fecha->format('Y-m-d H:i:s'), $model->valor, $model->estado ? 1 : 0, $model?->banco->id,
$model?->fechaPago->format('Y-m-d H:i:s'), $model?->abonado ? 1 : 0, $model?->fechaAbonado->format('Y-m-d H:i:s'),
$model?->uf, $model?->pago->id, $model?->numero]
['pie', 'fecha', 'valor_$', 'estado', 'banco', 'fecha_pago', 'abonado', 'fecha_abono', 'uf', 'pago', 'numero'],
[$model->pie->id, $model->fecha->format('Y-m-d H:i:s'), $model->valor, $model->estado ? 1 : 0, $model->banco?->id,
null, null, null,
$model->uf, $model->pago->id, $model->numero]
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Define\Model
public function edit(Define\Model $model, array $new_data): Model\Venta\Cuota
{
return $this->update($model, ['pie', 'fecha', 'valor', 'estado', 'banco', 'fecha_pago', 'abonado', 'fecha_abonado', 'uf', 'pago', 'numero'], $new_data);
}

View File

@ -18,7 +18,7 @@ class EstadoPago extends Ideal\Repository
$this->setTable('estado_pago');
}
public function create(?array $data = null): Define\Model
public function create(?array $data = null): Model\Venta\EstadoPago
{
$map = (new Implement\Repository\MapperParser())
->register('pago', (new Implement\Repository\Mapper())
@ -34,7 +34,7 @@ class EstadoPago extends Ideal\Repository
return $this->parseData(new Model\Venta\EstadoPago(), $data, $map);
}
public function save(Define\Model $model): Define\Model
public function save(Define\Model $model): Model\Venta\EstadoPago
{
$model->id = $this->saveNew(
['pago', 'estado', 'fecha'],
@ -43,7 +43,7 @@ class EstadoPago extends Ideal\Repository
return $model;
}
public function edit(Define\Model $model, array $new_data): Define\Model
public function edit(Define\Model $model, array $new_data): Model\Venta\EstadoPago
{
return $this->update($model, ['pago', 'estado', 'fecha'], $new_data);
}
@ -53,7 +53,7 @@ class EstadoPago extends Ideal\Repository
$query = "SELECT * FROM `{$this->getTable()}` WHERE `pago` = ?";
return $this->fetchMany($query, [$pago_id]);
}
public function fetchCurrentByPago(int $pago_id): Define\Model
public function fetchCurrentByPago(int $pago_id): Model\Venta\EstadoPago
{
$query = "SELECT a.*
FROM `{$this->getTable()}` a
@ -61,7 +61,7 @@ FROM `{$this->getTable()}` a
WHERE a.`pago` = ?";
return $this->fetchOne($query, [$pago_id]);
}
public function fetchByPagoAndEstado(int $pago_id, int $estado_id): Define\Model
public function fetchByPagoAndEstado(int $pago_id, int $estado_id): Model\Venta\EstadoPago
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `pago` = ? AND `estado` = ?";
return $this->fetchOne($query, [$pago_id, $estado_id]);

View File

@ -1,7 +1,6 @@
<?php
namespace Incoviba\Repository\Venta;
use DateTimeImmutable;
use Incoviba\Common\Define;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
@ -10,13 +9,17 @@ use Incoviba\Repository;
class Pago extends Ideal\Repository
{
public function __construct(Define\Connection $connection, protected Repository\Banco $bancoRepository, protected TipoPago $tipoPagoRepository)
public function __construct(
Define\Connection $connection,
protected Repository\Banco $bancoRepository,
protected TipoPago $tipoPagoRepository
)
{
parent::__construct($connection);
$this->setTable('pago');
}
public function create(?array $data = null): Define\Model
public function create(?array $data = null): Model\Venta\Pago
{
$map = (new Implement\Repository\MapperParser(['valor', 'identificador', 'uf', 'pagador']))
->register('banco', (new Implement\Repository\Mapper())
@ -45,15 +48,15 @@ class Pago extends Ideal\Repository
}));
return $this->parseData(new Model\Venta\Pago(), $data, $map);
}
public function save(Define\Model $model): Define\Model
public function save(Define\Model $model): Model\Venta\Pago
{
$model->id = $this->saveNew(
['valor', 'banco', 'tipo', 'identificador', 'fecha', 'uf', 'pagador', 'asociado'],
[$model->valor, $model?->banco->id, $model?->tipoPago->id, $model?->identificador, $model?->fecha->format('Y-m-d H:i:s'), $model?->uf, $model?->pagador, $model?->asociado->id]
[$model->valor, $model->banco?->id, $model->tipoPago?->id, $model->identificador, $model->fecha?->format('Y-m-d H:i:s'), $model->uf, $model->pagador, $model->asociado?->id]
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Define\Model
public function edit(Define\Model $model, array $new_data): Model\Venta\Pago
{
return $this->update($model, ['valor', 'banco', 'tipo', 'identificador', 'fecha', 'uf', 'pagador', 'asociado'], $new_data);
}

View File

@ -15,7 +15,7 @@ class Pie extends Ideal\Repository
$this->setTable('pie');
}
public function create(?array $data = null): Define\Model
public function create(?array $data = null): Model\Venta\Pie
{
$map = (new Implement\Repository\MapperParser(['valor', 'uf', 'cuotas']))
->register('fecha', new Implement\Repository\Mapper\DateTime('fecha'))
@ -35,15 +35,15 @@ class Pie extends Ideal\Repository
}));
return $this->parseData(new Model\Venta\Pie(), $data, $map);
}
public function save(Define\Model $model): Define\Model
public function save(Define\Model $model): Model\Venta\Pie
{
$model->id = $this->saveNew(
['fecha', 'valor', 'uf', 'cuotas', 'asociado', 'reajuste'],
[$model->fecha->format('Y-m-d H:i:s'), $model->valor, $model?->uf, $model->cuotas, $model?->asociado->id, $model?->reajuste->id]
[$model->fecha->format('Y-m-d H:i:s'), $model->valor, $model->uf, $model->cuotas, $model->asociado?->id, $model->reajuste?->id]
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Define\Model
public function edit(Define\Model $model, array $new_data): Model\Venta\Pie
{
return $this->update($model, ['fecha', 'valor', 'uf', 'cuotas', 'asociado', 'reajuste'], $new_data);
}

View File

@ -15,27 +15,39 @@ class Propiedad extends Ideal\Repository
$this->setTable('propiedad');
}
public function create(?array $data = null): Define\Model
public function create(?array $data = null): Model\Venta\Propiedad
{
$map = (new Implement\Repository\MapperParser())
->register('unidad_principal', (new Implement\Repository\Mapper())
->setProperty('unidades')
->setFunction(function($data) {
return $this->unidadService->getByPropiedad($data['id']);
if (isset($data['id'])) {
return $this->unidadService->getByPropiedad($data['id']);
}
return [$this->unidadService->getById($data['unidad_principal'])];
}))
->register('estado', new Implement\Repository\Mapper\Boolean('estado'));
return $this->parseData(new Model\Venta\Propiedad(), $data, $map);
}
public function save(Define\Model $model): Define\Model
public function save(Define\Model $model): Model\Venta\Propiedad
{
$model->id = $this->saveNew(
['unidad_principal', 'estacionamientos', 'bodegas', 'estado'],
[$model->departamentos()[0]->id, null, null, 1]
[$model->departamentos()[0]->id,
implode(',', array_map(function(Model\Venta\Unidad $unidad) {return $unidad->id;}, $model->estacionamientos())),
implode(',', array_map(function(Model\Venta\Unidad $unidad) {return $unidad->id;}, $model->bodegas())),
1]
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Define\Model
public function edit(Define\Model $model, array $new_data): Model\Venta\Propiedad
{
return $this->update($model, ['unidad_principal', 'estacionamientos', 'bodegas', 'estado'], $new_data);
}
public function fetchVigenteByUnidad(int $unidad_id): Model\Venta\Propiedad
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `unidad_principal` = ?";
return $this->fetchOne($query, [$unidad_id]);
}
}

View File

@ -50,7 +50,13 @@ class Propietario extends Ideal\Repository
}
return $this->fetchById($data['representante']);
}))
->register('otro', (new Implement\Repository\Mapper\Boolean('otro'))
->register('otro', (new Implement\Repository\Mapper())
->setFunction(function($data) {
if ($data['otro'] === null or $data['otro'] === 0) {
return null;
}
return $this->fetchById($data['otro']);
})
->setDefault(null));
return $this->parseData(new Model\Venta\Propietario(), $data, $map);
}
@ -58,14 +64,14 @@ class Propietario extends Ideal\Repository
public function save(Define\Model $model): Define\Model
{
$model->rut = $this->saveNew(
['dv', 'nombres', 'apellido_paterno', 'apellido_materno'],
[$model->dv, $model->nombres, $model->apellidos['paterno'], $model->apellidos['materno']]
['dv', 'nombres', 'apellido_paterno', 'apellido_materno', 'direccion', 'otro', 'representante'],
[$model->dv, $model->nombres, $model->apellidos['paterno'], $model->apellidos['materno'], $model->datos->direccion->id, $model->otro->rut ?? 0, $model->representante->rut ?? 0]
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Define\Model
{
return $this->update($model, ['dv', 'nombres', 'apellido_paterno', 'apellido_materno'], $new_data);
return $this->update($model, ['dv', 'nombres', 'apellido_paterno', 'apellido_materno', 'direccion', 'otro', 'representante'], $new_data);
}
}

View File

@ -14,12 +14,12 @@ class Subsidio extends Ideal\Repository
$this->setTable('subsidio');
}
public function create(?array $data = null): Define\Model
public function create(?array $data = null): Model\Venta\Subsidio
{
$map = new Implement\Repository\MapperParser(['pago', 'subsidio']);
return $this->parseData(new Model\Venta\Subsidio(), $data, $map);
}
public function save(Define\Model $model): Define\Model
public function save(Define\Model $model): Model\Venta\Subsidio
{
$model->id = $this->saveNew(
['pago', 'subsidio'],
@ -27,7 +27,7 @@ class Subsidio extends Ideal\Repository
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Define\Model
public function edit(Define\Model $model, array $new_data): Model\Venta\Subsidio
{
return $this->update($model, ['pago', 'subsidio'], $new_data);
}

View File

@ -14,13 +14,13 @@ class TipoEstadoVenta extends Ideal\Repository
$this->setTable('tipo_estado_venta');
}
public function create(?array $data = null): Define\Model
public function create(?array $data = null): Model\Venta\TipoEstadoVenta
{
$map = (new Implement\Repository\MapperParser(['descripcion']))
->register('activa', new Implement\Repository\Mapper\Boolean('activa'));
return $this->parseData(new Model\Venta\TipoEstadoVenta(), $data, $map);
}
public function save(Define\Model $model): Define\Model
public function save(Define\Model $model): Model\Venta\TipoEstadoVenta
{
$model->id = $this->saveNew(
['descripcion', 'activa'],
@ -28,8 +28,14 @@ class TipoEstadoVenta extends Ideal\Repository
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Define\Model
public function edit(Define\Model $model, array $new_data): Model\Venta\TipoEstadoVenta
{
return $this->update($model, ['descripcion', 'activa'], $new_data);
}
public function fetchByDescripcion(string $descripcion): Model\Venta\TipoEstadoVenta
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `descripcion` = ?";
return $this->fetchOne($query, [$descripcion]);
}
}

View File

@ -14,12 +14,12 @@ class TipoPago extends Ideal\Repository
$this->setTable('tipo_pago');
}
public function create(?array $data = null): Define\Model
public function create(?array $data = null): Model\Venta\TipoPago
{
$map = new Implement\Repository\MapperParser(['descripcion']);
return $this->parseData(new Model\Venta\TipoPago(), $data, $map);
}
public function save(Define\Model $model): Define\Model
public function save(Define\Model $model): Model\Venta\TipoPago
{
$model->id = $this->saveNew(
['descripcion'],
@ -27,8 +27,14 @@ class TipoPago extends Ideal\Repository
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Define\Model
public function edit(Define\Model $model, array $new_data): Model\Venta\TipoPago
{
return $this->update($model, ['descripcion'], $new_data);
}
public function fetchByDescripcion(string $descripcion): Model\Venta\TipoPago
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `descripcion` = ?";
return $this->fetchOne($query, [$descripcion]);
}
}

41
app/src/Service/Money.php Normal file
View File

@ -0,0 +1,41 @@
<?php
namespace Incoviba\Service;
use DateTimeInterface;
use Incoviba\Common\Define\Money\Provider;
use Incoviba\Common\Implement\Exception\EmptyResponse;
use Incoviba\Service\Money\MiIndicador;
class Money
{
protected array $providers;
public function register(string $name, Provider $provider): Money
{
if (isset($this->providers) and isset($this->providers[$name]) and $this->providers[$name] === $provider) {
return $this;
}
$this->providers[$name] = $provider;
return $this;
}
public function getProvider(string $name): Provider
{
return $this->providers[$name];
}
public function getUF(DateTimeInterface $dateTime): float
{
try {
return $this->getProvider('uf')->get(MiIndicador::UF, $dateTime);
} catch (EmptyResponse) {
return 0;
}
}
public function getIPC(DateTimeInterface $dateTime): float
{
try {
return $this->getProvider('ipc')->get(MiIndicador::IPC, $dateTime);
} catch (EmptyResponse) {
return 0;
}
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace Incoviba\Service\Money;
use DateTimeInterface;
use Psr\Http\Client\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use Incoviba\Common\Define\Money\Provider;
use Incoviba\Common\Implement\Exception\EmptyResponse;
class MiIndicador implements Provider
{
const UF = 'uf';
const IPC = 'ipc';
const USD = 'dolar_intercambio';
public function __construct(protected ClientInterface $client) {}
public function get(string $money_symbol, DateTimeInterface $dateTime): float
{
$request_uri = "{$money_symbol}/{$dateTime->format('d-m-Y')}";
try {
$response = $this->client->get($request_uri);
} catch (GuzzleException) {
throw new EmptyResponse($request_uri);
}
if ((int) floor($response->getStatusCode() / 100) !== 2) {
throw new EmptyResponse($request_uri);
}
$body = $response->getBody();
$json = json_decode($body->getContents());
if ($json->codigo !== $money_symbol or count($json->serie) === 0) {
throw new EmptyResponse($request_uri);
}
return $json->serie[0]->valor;
}
}

View File

@ -1,6 +1,7 @@
<?php
namespace Incoviba\Service;
use DateTimeImmutable;
use Incoviba\Common\Implement;
use Incoviba\Repository;
use Incoviba\Model;
@ -9,7 +10,15 @@ class Venta
{
public function __construct(
protected Repository\Venta $ventaRepository,
protected Repository\Venta\EstadoVenta $estadoVentaRepository
protected Repository\Venta\EstadoVenta $estadoVentaRepository,
protected Repository\Venta\TipoEstadoVenta $tipoEstadoVentaRepository,
protected Venta\Propietario $propietarioService,
protected Venta\Propiedad $propiedadService,
protected Venta\Pie $pieService,
protected Venta\Subsidio $subsidioService,
protected Venta\Credito $creditoService,
protected Venta\BonoPie $bonoPieService,
protected Money $moneyService
) {}
public function getById(int $venta_id): Model\Venta
@ -34,8 +43,220 @@ class Venta
public function getByProyectoAndUnidad(string $proyecto_nombre, int $unidad_descripcion): Model\Venta
{
$venta = $this->ventaRepository->fetchByProyectoAndUnidad($proyecto_nombre, $unidad_descripcion);
$venta->addFactory('estados', ['callable' => [$this->estadoVentaRepository, 'fetchByVenta'], 'args' => [$venta->id]]);
$venta->addFactory('currentEstado', ['callable' => [$this->estadoVentaRepository, 'fetchCurrentByVenta'], 'args' => [$venta->id]]);
$venta->addFactory('estados', (new Implement\Repository\Factory())->setCallable([$this->estadoVentaRepository, 'fetchByVenta'])->setArgs([$venta->id]));
$venta->addFactory('currentEstado', (new Implement\Repository\Factory())->setCallable([$this->estadoVentaRepository, 'fetchCurrentByVenta'])->setArgs([$venta->id]));
return $venta;
}
public function add(array $data): void
{
$fecha = new DateTimeImmutable($data['fecha_venta']);
$data['uf'] = $this->moneyService->getUF($fecha);
$propietario = $this->addPropietario($data);
$propiedad = $this->addPropiedad($data);
$forma_pago = $this->addFormaPago($data);
$venta_data = [
'propietario' => $propietario->rut,
'propiedad' => $propiedad->id,
'fecha' => $fecha->format('Y-m-d'),
'valor_uf' => $data['valor'],
'fecha_ingreso' => (new DateTimeImmutable())->format('Y-m-d'),
'uf' => $data['uf']
];
$map = ['pie', 'subsidio', 'credito', 'bono_pie'];
foreach ($map as $field) {
$name = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $field))));
if (isset($forma_pago->{$name})) {
$venta_data[$field] = $forma_pago->{$name}->id;
}
}
$venta = $this->ventaRepository->create($venta_data);
$venta = $this->ventaRepository->save($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);
}
protected function addPropietario(array $data): Model\Venta\Propietario
{
if (isset($data['natural_uno'])) {
if (isset($data['natural_multiple'])) {
return $this->addDosPropietarios($data);
}
return $this->addUnPropietario($data);
}
return $this->addSociedad($data);
}
protected function addUnPropietario(array $data): Model\Venta\Propietario
{
$fields = array_fill_keys([
'rut',
'nombres',
'apellido_paterno',
'apellido_materno',
'calle',
'numero',
'extra',
'comuna'
], 0);
$filtered_data = array_intersect_key($data, $fields);
return $this->propietarioService->addPropietario($filtered_data);
}
protected function addDosPropietarios(array $data): Model\Venta\Propietario
{
$fields = array_fill_keys([
'rut_otro',
'nombres_otro',
'apellido_paterno_otro',
'apellido_materno_otro',
'calle_otro',
'numero_otro',
'extra_otro',
'comuna_otro'
], 0);
$filtered_data = array_intersect_key($data, $fields);
$mapped_data = array_combine([
'rut',
'nombres',
'apellido_paterno',
'apellido_materno',
'calle',
'numero',
'extra',
'comuna'
], $filtered_data);
$otro = $this->propietarioService->addPropietario($mapped_data);
$data['otro'] = $otro->rut;
$fields = array_fill_keys([
'rut',
'nombres',
'apellido_paterno',
'apellido_materno',
'calle',
'numero',
'extra',
'comuna',
'otro'
], 0);
$filtered_data = array_intersect_key($data, $fields);
return $this->propietarioService->addPropietario($filtered_data);
}
protected function addSociedad(array $data): Model\Venta\Propietario
{
$representante = $this->addUnPropietario($data);
$data['representante'] = $representante->rut;
$fields = array_fill_keys([
'rut_sociedad',
'razon_social',
'calle_comercial',
'numero_comercial',
'extra_comercial',
'comuna_comercial',
'representante'
], 0);
$filtered_data = array_intersect_key($data, $fields);
$mapped_data = array_combine([
'rut',
'razon_social',
'calle',
'numero',
'extra',
'comuna',
'representante'
], $filtered_data);
return $this->propietarioService->addSociedad($mapped_data);
}
protected function addPropiedad(array $data): Model\Venta\Propiedad
{
$ids = array_filter($data, function($key) {
return str_contains($key, 'unidad');
}, ARRAY_FILTER_USE_KEY);
return $this->propiedadService->addPropiedad($ids);
}
protected function addFormaPago(array $data): Model\Venta\FormaPago
{
$fields = [
'pie',
'subsidio',
'credito',
'bono_pie'
];
$forma_pago = new Model\Venta\FormaPago();
foreach ($fields as $name) {
if (isset($data["has_{$name}"])) {
$method = 'add' . str_replace(' ', '', ucwords(str_replace('_', ' ', $name)));
$obj = $this->{$method}($data);
$forma_pago->{$name} = $obj;
}
}
return $forma_pago;
}
protected function addPie(array $data): Model\Venta\Pie
{
$fields = array_fill_keys([
'fecha_venta',
'pie',
'cuotas',
'uf'
], 0);
$filtered_data = array_intersect_key($data, $fields);
$mapped_data = array_combine([
'fecha',
'valor',
'cuotas',
'uf'
], $filtered_data);
return $this->pieService->add($mapped_data);
}
protected function addSubsidio(array $data): Model\Venta\Subsidio
{
$fields = array_fill_keys([
'fecha_venta',
'ahorro',
'subsidio',
'uf'
], 0);
$filtered_data = array_intersect_key($data, $fields);
$mapped_data = array_combine([
'fecha',
'ahorro',
'subsidio',
'uf'
], $filtered_data);
return $this->subsidioService->add($mapped_data);
}
protected function addCredito(array $data): Model\Venta\Credito
{
$fields = array_fill_keys([
'fecha_venta',
'credito',
'uf'
], 0);
$filtered_data = array_intersect_key($data, $fields);
$mapped_data = array_combine([
'fecha',
'valor',
'uf'
], $filtered_data);
return $this->creditoService->add($mapped_data);
}
protected function addBonoPie(array $data): Model\Venta\BonoPie
{
$fields = array_fill_keys([
'fecha_venta',
'bono_pie'
], 0);
$filtered_data = array_intersect_key($data, $fields);
$mapped_data = array_combine([
'fecha',
'valor'
], $filtered_data);
return $this->bonoPieService->add($mapped_data);
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Incoviba\Service\Venta;
use Incoviba\Repository;
use Incoviba\Model;
class BonoPie
{
public function __construct(protected Repository\Venta\BonoPie $bonoPieRepository) {}
public function add(array $data): Model\Venta\BonoPie
{
return new Model\Venta\BonoPie();
}
}

View File

@ -0,0 +1,47 @@
<?php
namespace Incoviba\Service\Venta;
use DateTimeImmutable;
use Incoviba\Repository;
use Incoviba\Model;
use Incoviba\Service\Money;
class Credito
{
public function __construct(
protected Repository\Venta\Credito $creditoRepository,
protected Repository\Venta\Pago $pagoRepository,
protected Repository\Venta\TipoPago $tipoPagoRepository,
protected Repository\Venta\EstadoPago $estadoPagoRepository,
protected Repository\Venta\TipoEstadoPago $tipoEstadoPagoRepository,
protected Money $moneyService
) {}
public function add(array $data): Model\Venta\Credito
{
$fecha = new DateTimeImmutable($data['fecha']);
$uf = $data['uf'] ?? $this->moneyService->getUF($fecha);
$tipoPago = $this->tipoPagoRepository->fetchByDescripcion('carta de resguardo');
$pago = $this->addPago(['fecha' => $fecha->format('Y-m-d'), 'valor' => $data['valor'] * $uf, 'uf' => $uf, 'tipo' => $tipoPago->id]);
$credito = $this->creditoRepository->create([
'valor' => $data['valor'],
'fecha' => $fecha->format('Y-m-d'),
'pago' => $pago->id
]);
return $this->creditoRepository->save($credito);
}
protected function addPago(array $data): Model\Venta\Pago
{
$pago = $this->pagoRepository->create($data);
$pago = $this->pagoRepository->save($pago);
$tipoEstado = $this->tipoEstadoPagoRepository->fetchByDescripcion('no pagado');
$data = [
'pago' => $pago->id,
'fecha' => $pago->fecha->format('Y-m-d'),
'estado' => $tipoEstado->id
];
$estado = $this->estadoPagoRepository->create($data);
$this->estadoPagoRepository->save($estado);
return $pago;
}
}

View File

@ -5,10 +5,15 @@ use DateTimeImmutable;
use DateInterval;
use IntlDateFormatter;
use Incoviba\Repository;
use Incoviba\Model;
class Cuota
{
public function __construct(protected Repository\Venta\Cuota $cuotaRepository) {}
public function __construct(
protected Repository\Venta\Cuota $cuotaRepository,
protected Pago $pagoService,
protected Repository\Venta\TipoPago $tipoPagoRepository
) {}
public function pendientes(): array
{
@ -68,4 +73,41 @@ class Cuota
}
return $cuotas_depositadas;
}
public function getVigenteByPie(int $pie_id): array
{
return $this->cuotaRepository->fetchVigenteByPie($pie_id);
}
public function add(array $data): Model\Venta\Cuota
{
$tipoPago = $this->tipoPagoRepository->fetchByDescripcion('cheque');
$fields = array_fill_keys([
'fecha',
'banco',
'valor',
'identificador'
], 0);
$filtered_data = array_intersect_key($data, $fields);
$pago_data = array_merge($filtered_data, ['tipo' => $tipoPago->id]);
$pago = $this->pagoService->add($pago_data);
$data['pago'] = $pago->id;
$data['estado'] = $pago->currentEstado->tipoEstadoPago->id;
$fields = array_fill_keys([
'pie',
'fecha',
'valor',
'estado',
'banco',
'uf',
'pago',
'numero'
], 0);
$filtered_data = array_intersect_key($data, $fields);
$mapped_data = $filtered_data;
$mapped_data['valor_$'] = $mapped_data['valor'];
unset($mapped_data['valor']);
$cuota = $this->cuotaRepository->create($mapped_data);
$this->cuotaRepository->save($cuota);
return $cuota;
}
}

View File

@ -3,15 +3,20 @@ namespace Incoviba\Service\Venta;
use DateTimeInterface;
use DateTimeImmutable;
use Incoviba\Service\Money;
use PDOException;
use Incoviba\Repository;
use Incoviba\Model;
use Incoviba\Service;
class Pago
{
public function __construct(protected Repository\Venta\Pago $pagoRepository,
protected Repository\Venta\EstadoPago $estadoPagoRepository,
protected Repository\Venta\TipoEstadoPago $tipoEstadoPagoRepository) {}
public function __construct(
protected Repository\Venta\Pago $pagoRepository,
protected Repository\Venta\EstadoPago $estadoPagoRepository,
protected Repository\Venta\TipoEstadoPago $tipoEstadoPagoRepository,
protected Service\Money $moneyService
) {}
public function depositar(Model\Venta\Pago $pago, DateTimeInterface $fecha): bool
{
@ -66,6 +71,12 @@ class Pago
$pago = $this->pagoRepository->fetchById($pago_id);
$pago->estados = $this->estadoPagoRepository->fetchByPago($pago_id);
$pago->currentEstado = $this->estadoPagoRepository->fetchCurrentByPago($pago_id);
if (($pago->uf === null or $pago->uf === 0.0) and $pago->fecha < new DateTimeImmutable()) {
$pago->uf = $this->moneyService->getUF($pago->fecha);
if ($pago->uf !== 0.0) {
$this->pagoRepository->edit($pago, ['uf' => $pago->uf]);
}
}
return $pago;
}
@ -81,4 +92,33 @@ class Pago
{
return [];
}
public function add(array $data): Model\Venta\Pago
{
if (!isset($data['uf'])) {
$data['uf'] = $this->moneyService->getUF(new DateTimeImmutable($data['fecha']));
}
$fields = array_fill_keys([
'valor',
'banco',
'tipo',
'identificador',
'fecha',
'uf',
'pagador',
'asociado'
], 0);
$filtered_data = array_intersect_key($data, $fields);
$pago = $this->pagoRepository->create($filtered_data);
$pago = $this->pagoRepository->save($pago);
$tipoEstado = $this->tipoEstadoPagoRepository->fetchByDescripcion('no pagado');
$estado = $this->estadoPagoRepository->create([
'pago' => $pago->id,
'fecha' => $pago->fecha->format('Y-m-d'),
'estado' => $tipoEstado->id
]);
$estado = $this->estadoPagoRepository->save($estado);
$pago->currentEstado = $estado;
return $pago;
}
}

View File

@ -8,13 +8,23 @@ class Pie
{
public function __construct(
protected Repository\Venta\Pie $pieRepository,
protected Repository\Venta\Cuota $cuotaRepository
protected Cuota $cuotaService
) {}
public function getById(int $pie_id): Model\Venta\Pie
{
$pie = $this->pieRepository->fetchById($pie_id);
$pie->cuotasArray = $this->cuotaRepository->fetchVigenteByPie($pie_id);
$pie->cuotasArray = $this->cuotaService->getVigenteByPie($pie_id);
return $pie;
}
public function add(array $data): Model\Venta\Pie
{
$pie = $this->pieRepository->create($data);
return $this->pieRepository->save($pie);
}
public function addCuota(array $data): Model\Venta\Cuota
{
return $this->cuotaService->add($data);
}
}

View File

@ -0,0 +1,87 @@
<?php
namespace Incoviba\Service\Venta;
use PDO;
use PDOException;
use Incoviba\Common\Define;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Repository;
use Incoviba\Model;
class Propiedad
{
public function __construct(
protected Repository\Venta\Propiedad $propiedadRepository,
protected Repository\Venta\Unidad $unidadRepository,
protected Define\Connection $connection
) {}
public function addPropiedad(array $ids): Model\Venta\Propiedad
{
$unidades = [];
foreach ($ids as $unidad_id) {
$unidades []= $this->unidadRepository->fetchById($unidad_id);
}
usort($unidades, function(Model\Venta\Unidad $a, Model\Venta\Unidad $b) {
$t = $a->proyectoTipoUnidad->tipoUnidad->orden - $b->proyectoTipoUnidad->tipoUnidad->orden;
if ($t === 0) {
return strcmp(str_pad($a->descripcion, 4, '0', STR_PAD_LEFT), str_pad($b->descripcion, 4, '0', STR_PAD_LEFT));
}
return $t;
});
try {
$propiedad = $this->propiedadRepository->fetchVigenteByUnidad($unidades[0]->id);
} catch (EmptyResult) {
$propiedad = $this->propiedadRepository->create([
'unidad_principal' => $unidades[0]->id,
'estado' => 1
]);
$propiedad = $this->propiedadRepository->save($propiedad);
}
$this->addUnidades($propiedad, $unidades);
$this->cleanUpUnidades($propiedad, $unidades);
return $propiedad;
}
protected function addUnidades(Model\Venta\Propiedad $propiedad, array $unidades): void
{
$query = "SELECT 1 FROM `propiedad_unidad` WHERE `propiedad` = ? AND `unidad` = ?";
$statement = $this->connection->prepare($query);
$query2 = "INSERT INTO `propiedad_unidad` (`propiedad`, `unidad`, `principal`) VALUES (?, ?, ?)";
$insert = $this->connection->prepare($query2);
foreach ($unidades as $ix => $unidad) {
try {
$statement->execute([$propiedad->id, $unidad->id]);
$result = $statement->fetch(PDO::FETCH_ASSOC);
if (!$result) {
throw new EmptyResult($query);
}
} catch (PDOException|EmptyResult) {
$insert->execute([$propiedad->id, $unidad->id, ($ix === 0) ? 1 : 0]);
}
}
}
protected function cleanUpUnidades(Model\Venta\Propiedad $propiedad, array $unidades): void
{
$query = "SELECT `unidad` FROM `propiedad_unidad` WHERE `propiedad` = ?";
$statement = $this->connection->prepare($query);
$statement->execute([$propiedad->id]);
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!$results) {
return;
}
$all_ids = array_map(function($row) {return $row['unidad'];}, $results);
$new_ids = array_map(function(Model\Venta\Unidad $unidad) {return $unidad->id;}, $unidades);
$diff = array_diff($all_ids, $new_ids);
if (count($diff) === 0) {
return;
}
$query = "DELECT FROM `propiedad_unidad` WHERE `propiedad` = ? AND `unidad` = ?";
$statement = $this->connection->prepare($query);
foreach ($diff as $id) {
$statement->execute([$propiedad->id, $id]);
}
}
}

View File

@ -0,0 +1,102 @@
<?php
namespace Incoviba\Service\Venta;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Repository;
use Incoviba\Model;
class Propietario
{
public function __construct(
protected Repository\Venta\Propietario $propietarioRepository,
protected Repository\Direccion $direccionRepository
) {}
public function addPropietario(array $data): Model\Venta\Propietario
{
$direccion = $this->addDireccion($data);
$data['direccion'] = $direccion->id;
if (str_contains($data['rut'], '-')) {
$data['rut'] = explode('-', $data['rut'])[0];
}
$fields = array_fill_keys([
'rut',
'nombres',
'apellido_paterno',
'apellido_materno',
'direccion'
], 0);
$filtered_data = array_intersect_key($data, $fields);
try {
$propietario = $this->propietarioRepository->fetchById($data['rut']);
$edits = [];
if ($propietario->datos->direccion->id !== $filtered_data['direccion']) {
$edits['direccion'] = $filtered_data['direccion'];
}
$propietario = $this->propietarioRepository->edit($propietario, $edits);
} catch (EmptyResult) {
$propietario = $this->propietarioRepository->create($filtered_data);
$propietario = $this->propietarioRepository->save($propietario);
}
return $propietario;
}
public function addSociedad(array $data): Model\Venta\Propietario
{
$direccion = $this->addDireccion($data);
$data['direccion'] = $direccion->id;
if (str_contains($data['rut'], '-')) {
$data['rut'] = explode('-', $data['rut'])[0];
}
$fields = array_fill_keys([
'rut',
'razon_social',
'direccion',
'representante'
], 0);
$filtered_data = array_intersect_key($data, $fields);
$mapped_data = array_combine([
'rut',
'nombres',
'direccion',
'representante'
], $filtered_data);
try {
$sociedad = $this->propietarioRepository->fetchById($data['rut']);
$edits = [];
if ($sociedad->datos->direccion->id !== $mapped_data['direccion']) {
$edits['direccion'] = $mapped_data['direccion'];
}
if ($sociedad->representante->rut !== $mapped_data['representante']) {
$edits['representante'] = $mapped_data['representante'];
}
$sociedad = $this->propietarioRepository->edit($sociedad, $edits);
} catch (EmptyResult) {
$sociedad = $this->propietarioRepository->create($mapped_data);
$sociedad = $this->propietarioRepository->save($sociedad);
}
return $sociedad;
}
protected function addDireccion(array $data): Model\Direccion
{
$fields = array_fill_keys([
'calle',
'numero',
'extra',
'comuna'
], 0);
$filtered_data = array_intersect_key($data, $fields);
try {
$direccion = $this->direccionRepository->fetchByCalleAndNumeroAndExtra($filtered_data['calle'], $filtered_data['numero'], $filtered_data['extra']);
} catch (EmptyResult) {
$direccion = $this->direccionRepository->create($filtered_data);
$direccion = $this->direccionRepository->save($direccion);
}
return $direccion;
}
}

View File

@ -0,0 +1,44 @@
<?php
namespace Incoviba\Service\Venta;
use DateTimeImmutable;
use Incoviba\Repository;
use Incoviba\Model;
use Incoviba\Service;
class Subsidio
{
public function __construct(
protected Repository\Venta\Subsidio $subsidioRepository,
protected Repository\Venta\Pago $pagoRepository,
protected Repository\Venta\TipoPago $tipoPagoRepository,
protected Repository\Venta\EstadoPago $estadoPagoRepository,
protected Repository\Venta\TipoEstadoPago $tipoEstadoPagoRepository,
protected Service\Money $moneyService
) {}
public function add(array $data): Model\Venta\Subsidio
{
$fecha = new DateTimeImmutable($data['fecha']);
$uf = $data['uf'] ?? $this->moneyService->getUF($fecha);
$tipoPago = $this->tipoPagoRepository->fetchByDescripcion('vale vista');
$ahorro = $this->addPago(['fecha' => $fecha->format('Y-m-d'), 'valor' => $data['ahorro'] * $uf, 'uf' => $uf, 'tipo' => $tipoPago->id]);
$subsidio = $this->addPago(['fecha' => $fecha->format('Y-m-d'), 'valor' => $data['subsidio'] * $uf, 'uf' => $uf, 'tipo' => $tipoPago->id]);
$subsidio = $this->subsidioRepository->create(['pago' => $ahorro->id, 'subsidio' => $subsidio->id]);
return $this->subsidioRepository->save($subsidio);
}
protected function addPago(array $data): Model\Venta\Pago
{
$pago = $this->pagoRepository->create($data);
$pago = $this->pagoRepository->save($pago);
$tipoEstado = $this->tipoEstadoPagoRepository->fetchByDescripcion('no pagado');
$data = [
'pago' => $pago->id,
'fecha' => $pago->fecha->format('Y-m-d'),
'estado' => $tipoEstado->id
];
$estado = $this->estadoPagoRepository->create($data);
$this->estadoPagoRepository->save($estado);
return $pago;
}
}