63 Commits

Author SHA1 Message Date
6ddc48ec60 Merge branch 'develop' 2024-03-13 16:31:34 -03:00
8caa80459e Accelerar listado ventas 2024-03-13 16:17:14 -03:00
98953cce42 FormaPago Service 2024-03-13 14:38:44 -03:00
c7dd309185 Movimiento + Detalles 2024-03-04 19:55:49 -03:00
48bfe5d8ab Mejora en velocidad de busqueda 2024-02-28 21:44:37 -03:00
d9b5bc6507 Procesar otras cartolas Santander 2024-02-28 17:02:04 -03:00
21d1ef653f FIX: Saldo actual informe tesoreria 2024-02-28 13:53:53 -03:00
e8d43e43ff FIX: fecha saldo consolidado 2024-02-28 13:45:20 -03:00
fc9788a1cd FIX: Mostrar pie con cuotas vigentes 2024-02-28 10:37:51 -03:00
02dcc950f4 FIX: Editar credito, valor mandaba fecha 2024-02-28 10:33:34 -03:00
370b6714bc Excel button in datatables 2024-02-27 16:49:39 -03:00
dc7a9f9e7a Buscar por rut 2024-02-27 16:11:48 -03:00
cfe18c1909 Informe tesoreria en excel 2024-02-23 22:37:09 -03:00
5156858205 Update Fomantic-UI 2024-02-23 10:20:58 -03:00
415ba31270 Cartola Diaria Manual 2024-02-23 10:20:44 -03:00
c784d1bee9 Fix informes 2024-02-21 21:22:04 +00:00
a1ade5c2c7 Merge branch 'develop' of http://git.provm.cl/Incoviba/oficial into develop 2024-02-20 01:54:05 +00:00
879b612493 Cartola Diaria 2024-02-19 22:39:22 -03:00
b4cdd2d5f7 Merge branch 'develop' of http://git.provm.cl/Incoviba/oficial into develop 2024-02-15 21:59:47 +00:00
51cabee824 Editar credito 2024-02-15 18:57:56 -03:00
d2e51e76f8 Merge branch 'develop' of http://git.provm.cl/Incoviba/oficial into develop 2024-02-14 16:54:10 +00:00
1621d6fe30 Implementacion agregar abono a escritura 2024-02-14 13:54:01 -03:00
0e32512adc Merge branch 'develop' of http://git.provm.cl/Incoviba/oficial into develop 2024-02-13 21:18:11 +00:00
338f290539 FIX: logged en debug 2024-02-13 18:13:53 -03:00
2aad7e1152 Merge branch 'develop' of http://git.provm.cl/Incoviba/oficial into develop 2024-02-13 21:00:02 +00:00
e542615128 FIX: Venta nueva no se ingresaba 2024-02-13 17:59:46 -03:00
1c7797b1b1 Merge branch 'develop' of http://git.provm.cl/Incoviba/oficial into develop 2024-02-13 15:13:06 +00:00
ba0d4073d7 FIX: All sociedades 2024-02-13 12:12:54 -03:00
faac3874a8 Merge branch 'develop' of http://git.provm.cl/Incoviba/oficial into develop 2024-02-13 15:11:33 +00:00
ade107ab3c Stackable grid 2024-02-13 12:11:26 -03:00
c192cf1883 Merge branch 'develop' of http://git.provm.cl/Incoviba/oficial into develop 2024-02-13 15:08:31 +00:00
4fb75b11c4 Mejora en look de depositos y vencidos 2024-02-13 12:08:25 -03:00
ccbb71d875 Merge branch 'develop' of http://git.provm.cl/Incoviba/oficial into develop 2024-02-13 14:26:36 +00:00
7f25b4b5e1 FIX: all sociedades & allActive depositos 2024-02-13 11:26:28 -03:00
f0b26a251b Merge branch 'develop' of http://git.provm.cl/Incoviba/oficial into develop 2024-02-13 14:17:08 +00:00
ea068d95d0 FIX: DAPs -> Depositos routes 2024-02-13 11:17:01 -03:00
1ccc9ab3d4 Cambio a proyectos:activos 2024-02-13 14:12:19 +00:00
5cd19bcdce Merge branch 'develop' of http://git.provm.cl/Incoviba/oficial into develop 2024-02-13 14:11:45 +00:00
712c70b34d FIX: DAPs -> Depositos 2024-02-13 11:11:30 -03:00
35ab7e7e8b Depositos vencidos no suman ni restan 2024-02-13 11:10:26 -03:00
4b39f93f30 Update permissions for cli 2024-02-13 04:30:54 +00:00
d3f188684a Increase update of proyectos 2024-02-13 04:30:29 +00:00
82647a171d Merge branch 'feature/DAPs' into develop 2024-02-13 01:16:58 -03:00
e44ab30665 Informe Tesoreria 2024-02-13 01:16:17 -03:00
19333bc338 Merge branch 'feature/dap' into develop 2024-02-12 10:00:42 -03:00
4738dae7c8 DAPs API 2024-02-12 10:00:17 -03:00
a370ffff43 Cleanup 2024-02-12 09:59:47 -03:00
88f9e539f7 Merge branch 'develop' of http://git.provm.cl/Incoviba/oficial into develop 2024-02-12 09:53:52 -03:00
671b26f038 Merge branch 'feature/Movimientos' into develop 2024-02-12 09:53:18 -03:00
e133bd36cf Cartola diaria 2024-02-12 09:52:48 -03:00
251dbbe0f0 FIX: cron ENV vars 2024-02-10 10:37:45 -03:00
e1eb2c4c56 Cleanup 2024-02-08 13:04:05 -03:00
1078f4c188 Simplificacion de Cartola diaria 2024-02-08 00:06:29 -03:00
38962cb9cf API Movimientos y cartola diaria 2024-02-07 23:48:31 -03:00
3cd699d2e2 Merge branch 'develop' of http://git.provm.cl/Incoviba/oficial into develop 2024-02-07 18:37:13 -03:00
d8b8787be9 FIX: Find Pago 2024-02-07 18:35:28 -03:00
62edca5335 Simplify set post or query 2024-01-23 20:41:52 -03:00
ac6c5b7d3d FIX: activar busqueda cuando tiene query definido 2024-01-23 20:18:02 -03:00
5b5a0ed1f5 FIX: Link a buscar propietario 2024-01-23 20:07:34 -03:00
331ee1e584 Merge branch 'develop' 2023-06-22 23:18:13 -04:00
24c17debf3 Merge branch 'develop' 2023-02-15 18:30:09 -03:00
552fd0aa06 Merge branch 'develop' 2023-02-14 20:50:42 -03:00
60faf293d4 Merge branch 'develop' 2023-02-13 17:18:41 -03:00
106 changed files with 4817 additions and 346 deletions

1
.gitignore vendored
View File

@ -9,3 +9,4 @@
**/modules/
**/.idea/
**/upload?/
**/informe?/

View File

@ -1,16 +1,19 @@
FROM php:8.2-fpm
FROM php:8.2-cli
ENV TZ "America/Santiago"
ENV TZ "${TZ}"
ENV APP_NAME "${APP_NAME}"
ENV API_URL "${API_URL}"
RUN apt-get update && apt-get install -y --no-install-recommends cron && rm -r /var/lib/apt/lists/*
RUN apt-get update && apt-get install -y --no-install-recommends cron rsyslog nano && rm -r /var/lib/apt/lists/*
RUN pecl install xdebug-3.2.2 \
&& docker-php-ext-enable xdebug
&& docker-php-ext-enable xdebug \
&& echo "#/bin/bash\nprintenv >> /etc/environment\ncron -f -L 11" > /root/entrypoint && chmod a+x /root/entrypoint
COPY ./php-errors.ini /usr/local/etc/php/conf.d/docker-php-errors.ini
WORKDIR /code/bin
COPY ./cli/crontab /var/spool/cron/crontabs/root
COPY --chmod=644 ./cli/crontab /var/spool/cron/crontabs/root
CMD ["cron", "-f"]
CMD [ "/root/entrypoint" ]

View File

@ -0,0 +1,10 @@
<?php
namespace Incoviba\Common\Define;
interface Informe
{
public function setTitle(string $title): Informe;
public function setFilename(string $filename): Informe;
public function addData(array $rows): Informe;
public function build(): void;
}

View File

@ -2,9 +2,10 @@
namespace Incoviba\Common\Ideal\Cartola;
use Incoviba\Common\Define;
use Incoviba\Common\Ideal\Service;
use Psr\Http\Message\UploadedFileInterface;
abstract class Banco implements Define\Cartola\Banco
abstract class Banco extends Service implements Define\Cartola\Banco
{
public function process(UploadedFileInterface $file): array
{
@ -14,12 +15,19 @@ abstract class Banco implements Define\Cartola\Banco
foreach ($data as $row) {
$r = [];
foreach ($columns as $old => $new) {
if (!isset($row[$old])) {
continue;
}
$r[$new] = $row[$old];
}
$temp []= $r;
}
return $temp;
}
public function processMovimientosDiarios(array $movimientos): array
{
return $movimientos;
}
abstract protected function columnMap(): array;
abstract protected function parseFile(UploadedFileInterface $uploadedFile): array;

View File

View File

@ -28,6 +28,12 @@ $app->group('/venta/{venta_id:[0-9]+}', function($app) {
});
$app->get('[/]', [Ventas::class, 'pie']);
});
$app->group('/escritura', function($app) {
$app->get('/add[/]', [Ventas\Escrituras::class, 'add']);
});
$app->group('/credito', function($app) {
$app->get('[/]', [Ventas\Creditos::class, 'show']);
});
$app->get('/escriturar[/]', [Ventas::class, 'escriturar']);
$app->get('/desistir[/]', [Ventas::class, 'desistir']);
$app->get('/desistida[/]', [Ventas::class, 'desistida']);

View File

@ -1,9 +1,13 @@
<?php
use Incoviba\Controller\API\Contabilidad;
use Incoviba\Controller\API\Contabilidad\Cartolas;
$app->group('/cartolas', function($app) {
$app->post('/procesar[/]', [Contabilidad::class, 'procesarCartola']);
$app->post('/procesar[/]', [Cartolas::class, 'procesar']);
});
$app->group('/cartola', function($app) {
$app->post('/exportar[/]', [Contabilidad::class, 'exportarCartola']);
$app->group('/diaria', function($app) {
$app->post('/ayer[/]', [Cartolas::class, 'ayer']);
$app->post('/procesar[/]', [Cartolas::class, 'diaria']);
});
$app->post('/exportar[/]', [Cartolas::class, 'exportar']);
});

View File

@ -0,0 +1,7 @@
<?php
use Incoviba\Controller\API\Contabilidad\Depositos;
$app->group('/depositos', function($app) {
$app->post('/add[/]', [Depositos::class, 'add']);
$app->get('/inmobiliaria/{inmobiliaria_rut}[/]', [Depositos::class, 'inmobiliaria']);
});

View File

@ -0,0 +1,6 @@
<?php
use Incoviba\Controller\API\Contabilidad\Movimientos;
$app->group('/movimiento/{movimiento_id}', function($app) {
$app->post('/detalles', [Movimientos::class, 'detalles']);
});

View File

@ -1,4 +1,12 @@
<?php
use Incoviba\Controller\API\Search;
$app->post('/search', [Search::class, 'query']);
$app->group('/search', function($app) {
$app->group('/ventas', function($app) {
$app->post('/unidades', [Search::class, 'unidades']);
$app->get('/unidad/{unidad_id}', [Search::class, 'unidad']);
$app->post('[/]', [Search::class, 'ventas']);
});
$app->get('/venta/{venta_id}', [Search::class, 'venta']);
$app->post('[/]', [Search::class, 'query']);
});

View File

@ -19,11 +19,21 @@ $app->group('/ventas', function($app) {
$app->group('/escrituras', function($app) {
$app->post('/estados[/]', [Ventas::class, 'escrituras']);
});
$app->group('/by', function($app) {
$app->get('/unidad/{unidad_id}', [Ventas::class, 'unidad']);
});
$app->post('/get[/]', [Ventas::class, 'getMany']);
$app->post('[/]', [Ventas::class, 'proyecto']);
});
$app->group('/venta/{venta_id}', function($app) {
$app->get('/unidades[/]', [Ventas::class, 'unidades']);
$app->get('/comentarios[/]', [Ventas::class, 'comentarios']);
$app->group('/escritura', function($app) {
$app->post('/add[/]', [Ventas\Escrituras::class, 'add']);
});
$app->group('/credito', function($app) {
$app->post('[/]', [Ventas\Creditos::class, 'edit']);
});
$app->post('/escriturar[/]', [Ventas::class, 'escriturar']);
$app->group('/desistir', function($app) {
$app->get('/eliminar[/]', [Ventas::class, 'insistir']);

View File

@ -0,0 +1,6 @@
<?php
use Incoviba\Controller\Contabilidad;
$app->group('/cartolas', function($app) {
$app->get('/diaria[/]', [Contabilidad::class, 'diaria']);
});

View File

@ -0,0 +1,6 @@
<?php
use Incoviba\Controller\Contabilidad;
$app->group('/depositos', function($app) {
$app->get('[/]', [Contabilidad::class, 'depositos']);
});

View File

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

View File

@ -0,0 +1,6 @@
<?php
use Incoviba\Controller\Contabilidad;
$app->group('/tesoreria', function($app) {
$app->get('[/[{fecha}[/]]]', [Contabilidad::class, 'tesoreria']);
});

View File

@ -0,0 +1,6 @@
<?php
use Incoviba\Controller\Contabilidad\Informes;
$app->group('/xlsx', function($app) {
$app->get('/tesoreria/{fecha}[/]', [Informes::class, 'tesoreria']);
});

View File

@ -0,0 +1,823 @@
@extends('layout.base')
@section('page_content')
<div class="ui container">
<h1 class="ui header">
Cartola Diaria
</h1>
<div class="ui grid">
<div class="right aligned sixteen wide column">
<button class="ui green icon button" id="add_button">
Agregar
<i class="plus icon"></i>
</button>
</div>
</div>
<form class="ui form" id="cartola_form">
<input type="hidden" id="fields" name="fields" value="0" />
</form>
<div class="ui two columns grid">
<div class="column">
<button class="ui icon button" id="process_button">
<i class="file excel icon"></i>
Procesar
</button>
</div>
<div class="right aligned column">
<div class="ui inline active loader" id="loader"></div>
</div>
</div>
<table class="ui table" id="diferencia">
<thead>
<tr>
<th>Sociedad</th>
<th>Banco - Cuenta</th>
<th>Hoy</th>
<th>Último Saldo</th>
<th>Saldo Actual</th>
<th>Diferencia</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="ui fluid container">
<table class="ui table" id="tabla_movimientos">
<thead>
<tr>
<th>Sociedad</th>
<th>Banco - Cuenta</th>
<th>Fecha</th>
<th>Glosa</th>
<th class="right aligned">Cargo</th>
<th class="right aligned">Abono</th>
<th class="right aligned">Saldo</th>
<th>Centro de Costo</th>
<th>Detalle</th>
<th>Orden</th>
</tr>
</thead>
<tbody id="movimientos"></tbody>
</table>
</div>
<div class="ui modal" id="manual_modal">
<div class="content">
<div class="header">
Movimientos |
<span id="modal_inmobiliaria"></span> |
<span id="modal_cuenta"></span> |
<span id="modal_fecha"></span>
</div>
<div class="ui one column grid">
<div class="right aligned column">
<button class="ui green icon button" id="add_manual">
<i class="plus icon"></i>
</button>
</div>
</div>
<form class="ui form" id="modal_form">
<input type="hidden" name="movimientos" value="[1]" />
<div id="modal_movimientos">
<div class="fields" data-movimiento="1">
<div class="field">
<label>Glosa</label>
<input type="text" name="glosa1" />
</div>
<div class="field">
<label>Cargo</label>
<div class="ui left labeled input">
<div class="ui basic label">$</div>
<input type="text" name="cargo1" />
</div>
</div>
<div class="field">
<label>Abono</label>
<div class="ui left labeled input">
<div class="ui basic label">$</div>
<input type="text" name="abono1" />
</div>
</div>
<div class="field">
<label>Saldo</label>
<div class="ui left labeled input">
<div class="ui basic label">$</div>
<input type="text" name="saldo1" />
</div>
</div>
<div class="field"></div>
</div>
</div>
</form>
<div class="actions">
<button class="ui approve button">
Procesar
</button>
</div>
</div>
</div>
@endsection
@include('layout.head.styles.datatables')
@include('layout.body.scripts.datatables')
@push('page_scripts')
<script>
class Cartola {
idx
inmobiliaria = {
rut: 0,
razon: ''
}
cuenta = {
id: 0,
descripcion: ''
}
fecha = ''
bancos = []
movimientos = []
saldo = 0
ayer = 0
constructor(idx) {
this.idx = idx
}
get() {
return {
bancos: () => {
const url = '{{$urls->api}}/inmobiliaria/' + this.inmobiliaria.rut + '/cuentas'
diaria.loader().show()
return fetchAPI(url).then(response => {
diaria.loader().hide()
if (!response) {
this.bancos = []
return
}
return response.json().then(json => {
if (json.cuentas.length === 0) {
this.bancos = []
return
}
this.bancos = json.cuentas.map(cuenta => {
return {
value: cuenta.id,
text: cuenta.banco.nombre + ' - ' + cuenta.cuenta,
name: cuenta.banco.nombre + ' - ' + cuenta.cuenta
}
})
})
})
},
ayer: (fecha) => {
const url = '{{$urls->api}}/contabilidad/cartola/diaria/ayer'
const body = new FormData()
body.set('cuenta_id', this.cuenta.id)
body.set('fecha', fecha.toISOString())
return fetchAPI(url, {method: 'post', body}).then(response => {
if (!response) {
return
}
return response.json().then(json => {
if (json.cartola.length === 0) {
return
}
this.ayer = json.cartola.saldo
})
})
}
}
}
update() {
return {
centro: (idx, centro_id) => {
const id = this.movimientos[idx].id
const url = '{{$urls->api}}/contabilidad/movimiento/' + id + '/detalles'
const body = new FormData()
body.set('centro_id', centro_id)
return fetchAPI(url, {method: 'post', body}).then(response => {
if (!response) {
return
}
response.json().then(json => {
if (!json.status) {
return
}
const dropdown = $(".dropdown[data-idx='" + idx + "']")
dropdown.dropdown('set selected', json.centro.id, true)
})
})
},
detalle: (idx, detalle) => {
const id = this.movimientos[idx].id
const url = '{{$urls->api}}/contabilidad/movimiento/' + id + '/detalles'
const body = new FormData()
body.set('detalle', detalle)
return fetchAPI(url, {method: 'post', body}).then(response => {
if (!response) {
return
}
response.json().then(json => {
if (!json.status) {
return
}
const input = $("input[data-idx='" + idx + "']")
input.val(json.detalle)
})
})
}
}
}
draw() {
return {
form: ($form, inmobiliarias, first = false) => {
const $fields = $('<div></div>').addClass('fields cartola').attr('data-cartola', this.idx)
const $inmobiliarias_menu = $('<div></div>').addClass('menu')
inmobiliarias.forEach(inmobiliaria => {
$inmobiliarias_menu.append(
$('<div></div>').addClass('item').attr('data-value', inmobiliaria.rut).html(inmobiliaria.razon)
)
})
const $inmobiliarias_dropdown = $('<div></div>').addClass('ui search selection dropdown').attr('id', 'inmobiliaria' + this.idx).append(
$('<input />').attr('type', 'hidden')//.attr('name', 'inmobiliaria_rut' + this.idx)
).append(
$('<i></i>').addClass('dropdown icon')
).append(
$('<div></div>').addClass('default text').html('Inmobiliaria')
).append($inmobiliarias_menu)
$fields.append(
$('<div></div>').addClass('six wide field').append(
$('<label></label>').attr('for', 'inmobiliaria' + this.idx).html('Sociedad')
).append($inmobiliarias_dropdown)
)
const $cuentas_dropdown = $('<div></div>').addClass('ui search selection dropdown').attr('id', 'cuenta' + this.idx).append(
$('<input />').attr('type', 'hidden').attr('name', 'cuenta_id' + this.idx)
).append(
$('<i></i>').addClass('dropdown icon')
).append(
$('<div></div>').addClass('default text').html('Banco - Cuenta')
).append(
$('<div></div>').addClass('menu')
)
$fields.append(
$('<div></div>').addClass('four wide field').append(
$('<label></label>').html('Banco - Cuenta')
).append($cuentas_dropdown)
)
const $fecha_calendar = $('<div></div>').addClass('ui calendar').attr('id', 'fecha' + this.idx).append(
$('<div></div>').addClass('ui left icon input').append(
$('<i></i>').addClass('calendar icon')
).append(
$('<input />').attr('type', 'text')
)
)
$fields.append(
$('<div></div>').addClass('three wide field').append(
$('<label></label>').attr('for', 'fecha' + this.idx).html('Fecha')
).append($fecha_calendar)
)
$fields.append(
$('<div></div>').addClass('field').append(
$('<label></label>').html('Cartola')
).append(
$('<input />').addClass('ui invisible file input').attr('type', 'file').attr('name', 'file' + this.idx).attr('id', 'file' + this.idx)
).append(
$('<label></label>').addClass('ui icon button').attr('for', 'file' + this.idx).append(
$('<i></i>').addClass('file icon')
).append('Cargar')
)
)
const $manual_checkbox = $('<div></div>').addClass('ui invisible checkbox').append(
$('<input />').attr('type', 'checkbox').attr('name', 'manual' + this.idx).attr('id', 'manual' + this.idx)
).append(
$('<label></label>').addClass('image').attr('for', 'manual' + this.idx).append(
$('<i></i>').addClass('large orange keyboard icon')
)
)
$fields.append($('<div></div>').addClass('field').append(
$('<label></label>').html('Manual')
).append($manual_checkbox))
if (!first) {
$fields.append(
$('<div></div>').addClass('field').append(
$('<label></label>').html('Eliminar')
).append(
$('<button></button>').addClass('ui red icon button').attr('data-cartola', this.idx).append(
$('<i></i>').addClass('remove icon')
).click(event => {
const idx = $(event.currentTarget).data('cartola')
diaria.cartolas().remove(idx)
})
)
)
}
$form.append($fields)
const cdo = JSON.parse(JSON.stringify(calendar_date_options))
cdo['initialDate'] = new Date()
cdo['maxDate'] = cdo['initialDate']
cdo['onChange'] = (date, text, mode) => {
this.fecha = date
}
this.fecha = cdo['initialDate']
$inmobiliarias_dropdown.dropdown({
fireOnInit: true,
onChange: (value, text, $choice) => {
this.inmobiliaria.rut = value
this.inmobiliaria.razon = text
this.get().bancos(value).then(() => {
$cuentas_dropdown.dropdown('change values', this.bancos)
})
},
})
$cuentas_dropdown.dropdown({
fireOnInit: true,
onChange: (value, text, $choice) => {
this.cuenta.id = value
this.cuenta.descripcion = text
}
})
$fecha_calendar.calendar(cdo)
$manual_checkbox.change(event => {
const $element = $(event.currentTarget)
const status = $element.checkbox('is checked')
const $field = $element.parent().parent()
const $file = $field.find('#file' + this.idx).parent()
if (status) {
$file.find('input').attr('type', 'hidden')
$file.hide()
manual.data.inmobiliaria = $inmobiliarias_dropdown.dropdown('get text')
manual.data.cuenta = $cuentas_dropdown.dropdown('get text')
const fecha = $fecha_calendar.calendar('get date')
manual.data.fecha = [fecha.getDate(), (fecha.getMonth()+1).toString().padStart(2, '0'), fecha.getFullYear()].join('-')
manual.data.field = this.idx
manual.$modal.modal('show')
return
}
$file.find('input').attr('type', 'file')
$file.show()
})
},
diferencia: ($tbody, dateFormatter, numberFormatter) => {
$tbody.append(
$('<tr></tr>').append(
$('<td></td>').html(this.inmobiliaria.razon)
).append(
$('<td></td>').html(this.cuenta.descripcion)
).append(
$('<td></td>').html(dateFormatter.format(this.fecha))
).append(
$('<td></td>').html(numberFormatter.format(this.ayer))
).append(
$('<td></td>').html(numberFormatter.format(this.saldo))
).append(
$('<td></td>').html(numberFormatter.format(this.saldo - this.ayer))
)
)
},
cartola: ($tbody, dateFormatter, numberFormatter) => {
this.movimientos.forEach((row, idx) => {
$tbody.append(
$('<tr></tr>').append(
'<td>' + this.inmobiliaria.razon + '</td>' + "\n"
+ '<td>' + this.cuenta.descripcion + '</td>' + "\n"
+ '<td>' + dateFormatter.format(row.fecha) + '</td>' + "\n"
+ '<td>' + row.glosa + '</td>' + "\n"
+ '<td class="right aligned">' + (row.cargo === 0 ? '' : numberFormatter.format(row.cargo)) + '</td>' + "\n"
+ '<td class="right aligned">' + (row.abono === 0 ? '' : numberFormatter.format(row.abono)) + '</td>' + "\n"
+ '<td class="right aligned">' + (row.saldo === 0 ? '' : numberFormatter.format(row.saldo)) + '</td>' + "\n"
).append(
$('<td></td>').append(
this.draw().centroCosto(idx)
)
).append(
$('<td></td>').append(
this.draw().detalle(idx)
)
).append(
$('<td></td>').html(idx + 1)
)
)
})
},
centroCosto: idx => {
const centros = JSON.parse('{!! json_encode($centrosCostos) !!}')
const menu = $('<div></div>').addClass('menu')
centros.forEach(centro => {
menu.append(
'<div class="item" data-value="' + centro.id + '">'
+ centro.id + ' - ' + centro.descripcion
+ '</div>'
)
})
const dropdown = $('<div></div>').addClass('ui search selection dropdown').attr('data-idx', idx).html(
'<input type="hidden" name="centro" />' + "\n" +
'<i class="dropdown icon"></i>' + "\n" +
'<div class="default text">Centro de Costo</div>' + "\n"
).append(menu)
dropdown.dropdown({
onChange: (value, text, $element) => {
const idx = $element.parent().parent().data('idx')
this.update().centro(idx, value)
}
})
if (this.movimientos[idx].centro !== '') {
const cid = centros.findIndex(centro => centro.descripcion === this.movimientos[idx].centro)
dropdown.dropdown('set selected', centros[cid].id, true)
}
return dropdown
},
detalle: idx => {
const detalle = document.createElement('input')
detalle.type = 'text'
detalle.name = 'detalle' + idx
detalle.placeholder = 'Detalle'
detalle.setAttribute('data-idx', idx)
const input = document.createElement('div')
input.className = 'ui input'
input.appendChild(detalle)
if (this.movimientos[idx].detalle !== '') {
detalle.value = this.movimientos[idx].detalle
}
detalle.addEventListener('blur', event => {
const idx = event.currentTarget.dataset['idx']
this.update().detalle(idx, event.currentTarget.value)
})
return $(input)
}
}
}
}
@php
$columns = [
'sociedad',
'cuenta',
'fecha',
'glosa',
'cargo',
'abono',
'saldo',
'centro',
'detalle',
'orden'
];
@endphp
const diaria = {
ids: {},
data: {
inmobiliarias: JSON.parse('{!! json_encode($inmobiliarias) !!}'),
cartolasIdx: [],
cartolas: [],
},
dataTableConfig: {
order: [[{{array_search('orden', $columns)}}, 'asc']],
columnDefs: [
{
targets: [{{implode(',', array_keys(array_filter($columns, function($column) {return in_array($column, ['fecha', 'cargo', 'abono', 'saldo']);})))}}],
width: '{{round((1/(count($columns) + 3 - 1)) * 100,2)}}%'
},
{
targets: [{{implode(',', array_keys(array_filter($columns, function($column) {return in_array($column, ['sociedad', 'cuenta', 'glosa', 'centro', 'detalle']);})))}}],
width: '{{round((1/(count($columns) + 3 - 1)) * 2 * 100, 2)}}%'
},
{
targets: [{{array_search('orden', $columns)}}],
visible: false
}
],
},
loaderStatus: true,
loader() {
return {
show: () => {
if (!this.loaderStatus) {
$(this.ids.loader).show()
this.loaderStatus = true
}
},
hide: () => {
if (this.loaderStatus) {
$(this.ids.loader).hide()
this.loaderStatus = false
}
}
}
},
cartolas() {
return {
add: () => {
let first = false
if (this.data.cartolas.length === 0) {
first = true
}
const idx = this.data.cartolas.reduce((prev, cartola) => Math.max(prev, cartola.idx), 0) + 1
const cartola = new Cartola(idx)
this.data.cartolas.push(cartola)
this.data.cartolasIdx.push(idx)
const form = $(this.ids.form)
cartola.draw().form(form, this.data.inmobiliarias, first)
$(this.ids.fields).attr('value', JSON.stringify(this.data.cartolasIdx))
},
remove: idx => {
if (this.data.cartolas.length === 1) {
return
}
const i = this.data.cartolasIdx.findIndex(value => value === idx)
const cartolaIdx = this.data.cartolas.findIndex(cartola => cartola.idx === idx)
$("div.cartola[data-cartola='" + idx + "']").remove()
this.data.cartolasIdx.splice(i,1)
this.data.cartolas.splice(cartolaIdx,1)
$(this.ids.fields).attr('value', JSON.stringify(this.data.cartolasIdx))
}
}
},
draw() {
return {
empty: () => {
Object.values(this.ids.table).forEach(id => $(id).find('tbody').html(''))
},
diferencia: () => {
const $table = $(this.ids.table.diferencia)
const $tbody = $table.find('tbody')
$tbody.html('')
const dateFormatter = new Intl.DateTimeFormat('es-CL', {
year: 'numeric',
month: 'numeric',
day: 'numeric'
})
const numberFormatter = new Intl.NumberFormat('es-CL', {minimumFractionDigits: 0, maximumFractionDigits: 0})
this.data.cartolas.forEach(cartola => {
cartola.draw().diferencia($tbody, dateFormatter, numberFormatter)
})
},
cartola: () => {
const $table = $(this.ids.table.base)
$table.DataTable().clear()
$table.DataTable().destroy()
const $tbody = $(this.ids.table.body)
$tbody.html('')
const dateFormatter = new Intl.DateTimeFormat('es-CL', {
year: 'numeric',
month: 'numeric',
day: 'numeric'
})
const numberFormatter = new Intl.NumberFormat('es-CL', {minimumFractionDigits: 0, maximumFractionDigits: 0})
this.data.cartolas.forEach(cartola => {
cartola.draw().cartola($tbody, dateFormatter, numberFormatter)
})
$table.DataTable(this.dataTableConfig)
},
}
},
parse() {
return {
cartola: event => {
const body = new FormData($(this.ids.form)[0])
this.data.cartolas.forEach(cartola => {
body.set('fecha' + cartola.idx, [cartola.fecha.getFullYear(), cartola.fecha.getMonth()+1, cartola.fecha.getDate()].join('-'))
})
const url = '{{$urls->api}}/contabilidad/cartola/diaria/procesar'
diaria.loader().show()
fetchAPI(url, {method: 'post', body}).then(response => {
diaria.loader().hide()
this.draw().empty()
if (!response) {
return
}
return response.json().then(json => {
if (json.cartolas.length === 0) {
return
}
Object.entries(json.cartolas).forEach(entry => {
const cartolaIdx = this.data.cartolas.findIndex(cartola => cartola.idx === parseInt(entry[0]))
this.data.cartolas[cartolaIdx].movimientos = []
entry[1].movimientos.forEach((row, idx) => {
const fecha = new Date(row.fecha)
fecha.setDate(fecha.getDate() + 1)
this.data.cartolas[cartolaIdx].movimientos[idx] = {
id: row.id,
fecha: fecha,
glosa: row.glosa,
documento: row.documento,
cargo: row.cargo,
abono: row.abono,
saldo: row.saldo,
centro: row.detalles?.centro_costo.descripcion ?? '',
detalle: row.detalles?.detalle ?? ''
}
})
const ayer = new Date(this.data.cartolas[cartolaIdx].fecha.getTime())
ayer.setDate(this.data.cartolas[cartolaIdx].fecha.getDate() - 1)
this.data.cartolas[cartolaIdx].saldo = entry[1].cartola.saldo
this.data.cartolas[cartolaIdx].get().ayer(ayer)
})
this.draw().diferencia()
this.draw().cartola()
})
})
return false
}
}
},
setup(ids) {
this.ids = ids
this.loader().hide()
$(this.ids.form).submit(event => {
event.preventDefault()
return false
})
$(this.ids.buttons.add).click(event => {
this.cartolas().add()
})
$(this.ids.buttons.process).click(this.parse().cartola)
$(this.ids.table.base).DataTable(this.dataTableConfig)
this.cartolas().add()
}
}
const manual = {
ids: {},
$modal: null,
data: {
inmobiliaria: '',
cuenta: '',
fecha: '',
field: 0,
movimientos: [
{idx: 1}
]
},
get movimientosIdx() {
const $movimientosIdx = $(this.ids.form).find("[name='movimientos']")
return JSON.parse($movimientosIdx.val())
},
set movimientosIdx(list) {
const $movimientosIdx = $(this.ids.form).find("[name='movimientos']")
$movimientosIdx.val(JSON.stringify(list))
},
update() {
return {
file: movimientos => {
const $file = $("[name='file" + this.data.field + "']")
$file.val(JSON.stringify(movimientos))
}
}
},
parse() {
return {
movimientos: () => {
const $fields = $(this.ids.movimientos).find('.fields')
const movimientos = []
$fields.each((i, fields) => {
const idx = $(fields).data('movimiento')
const inputs = [
'glosa',
'cargo',
'abono',
'saldo'
]
const data = {}
inputs.forEach(name => {
data[name] = $(fields).find("[name='"+name+idx+"']").val()
if (name !== 'glosa') {
data[name] = parseInt(data[name]) || 0
}
})
movimientos.push(data)
})
this.update().file(movimientos)
}
}
},
movimiento() {
return {
add: () => {
const idx = this.data.movimientos.reduce((prev, movimiento) => Math.max(prev, movimiento.idx), 0) + 1
const movimiento = {
idx
}
this.data.movimientos.push(movimiento)
const movimientosidx = this.movimientosIdx
movimientosidx.push(idx)
this.movimientosIdx = movimientosidx
this.draw().movimiento(idx)
},
remove: idx => {
const movimientosIdx = this.movimientosIdx
const i = movimientosIdx.findIndex(n => n === idx)
movimientosIdx.splice(i, 1)
const movimientoIdx = this.data.movimientos.findIndex(movimiento => movimiento.idx === idx)
this.data.movimientos.splice(movimientoIdx, 1)
$(this.ids.movimientos).find("[data-idx='"+idx+"']").parent().parent().remove()
this.movimientosIdx = movimientosIdx
}
}
},
draw() {
return {
movimiento: idx => {
$(this.ids.movimientos).append(
$('<div></div>').addClass('fields').attr('data-movimiento', idx).append(
'<div class="field">' + "\n"
+ '<label>Glosa</label>' + "\n"
+ '<input type="text" name="glosa' + idx + '" />' + "\n"
+ '</div>' + "\n" +
'<div class="field">' + "\n"
+ '<label>Cargo</label>' + "\n"
+ '<div class="ui left labeled input">' + "\n"
+ '<div class="ui basic label">$</div>' + "\n"
+ '<input type="text" name="cargo' + idx + '" />' + "\n"
+ '</div>' + "\n"
+ '</div>' + "\n" +
'<div class="field">' + "\n"
+ '<label>Abono</label>' + "\n"
+ '<div class="ui left labeled input">' + "\n"
+ '<div class="ui basic label">$</div>' + "\n"
+ '<input type="text" name="abono' + idx + '" />' + "\n"
+ '</div>' + "\n"
+ '</div>' + "\n" +
'<div class="field">' + "\n"
+ '<label>Saldo</label>' + "\n"
+ '<div class="ui left labeled input">' + "\n"
+ '<div class="ui basic label">$</div>' + "\n"
+ '<input type="text" name="saldo' + idx + '" />' + "\n"
+ '</div>' + "\n"
+ '</div>'
).append(
$('<div></div>').addClass('field').append(
$('<label></label>').html('Eliminar')
).append(
$('<button></button>').addClass('ui red icon button').attr('type', 'button').attr('data-idx', idx).append(
$('<i></i>').addClass('remove icon')
).click(event => {
const idx = $(event.currentTarget).data('idx')
manual.movimiento().remove(idx)
})
)
)
)
}
}
},
setup(ids) {
this.ids = ids
$(this.ids.modal).modal({
onShow: () => {
$(this.ids.inmobiliaria).html(this.data.inmobiliaria)
$(this.ids.cuenta).html(this.data.cuenta)
$(this.ids.fecha).html(this.data.fecha)
this.movimientos = []
$(this.ids.form).trigger('reset')
},
onApprove: $element => {
this.parse().movimientos()
},
onHide: $element => {
this.parse().movimientos()
}
})
this.$modal = $(this.ids.modal)
$(this.ids.button).click(event => {
this.movimiento().add()
})
$(this.ids.form).submit(event => {
event.preventDefault()
this.$modal.modal('hide')
return false
})
}
}
$(document).ready(() => {
diaria.setup({
table: {
base: '#tabla_movimientos',
body: '#movimientos',
diferencia: '#diferencia'
},
form: '#cartola_form',
fields: '#fields',
buttons: {
add: '#add_button',
process: '#process_button'
},
loader: '#loader'
})
manual.setup({
modal: '#manual_modal',
button: '#add_manual',
inmobiliaria: '#modal_inmobiliaria',
cuenta: '#modal_cuenta',
fecha: '#modal_fecha',
form: '#modal_form',
movimientos: '#modal_movimientos'
})
})
</script>
@endpush

View File

@ -0,0 +1,263 @@
@extends('layout.base')
@section('page_content')
<div class="ui container">
<h1 class="ui header">Depósitos a Plazo</h1>
</div>
<div class="ui stackable grid">
<div class="two wide column"></div>
<div class="twelve wide column">
<table class="ui table" id="depositos">
<thead>
<tr>
<th>Inmobiliaria</th>
<th>Banco</th>
<th> Depósito</th>
<th>Capital</th>
<th>Inicio</th>
<th>Plazo</th>
<th>Vencimiento</th>
<th>Vencimiento ISO</th>
<th>Monto al Vencimiento</th>
<th>Tasa</th>
<th>
<button class="ui green icon button" id="add_button">
<i class="plus icon"></i>
</button>
</th>
</tr>
</thead>
<tbody>
@foreach ($activos as $deposito)
<tr>
<td>{{$deposito->cuenta->inmobiliaria->razon}}</td>
<td>{{$deposito->cuenta->banco->nombre}}</td>
<td>{{$deposito->id}}</td>
<td>{{$format->pesos($deposito->capital)}}</td>
<td>{{$deposito->inicio->format('d-m-Y')}}</td>
<td>{{$deposito->plazo()}}</td>
<td>{{$deposito->termino->format('d-m-Y')}}</td>
<td>{{$deposito->termino->format('Y-m-d')}}</td>
<td>{{$format->pesos($deposito->futuro)}}</td>
<td>{{$format->percent($deposito->tasa() * 100, 4)}}</td>
<td>
<button class="ui red icon button remove_button" data-deposito="{{$deposito->id}}">
<i class="remove icon"></i>
</button>
</td>
</tr>
@endforeach
@foreach ($vencidos as $deposito)
<tr class="yellow">
<td>{{$deposito->cuenta->inmobiliaria->razon}}</td>
<td>{{$deposito->cuenta->banco->nombre}}</td>
<td>{{$deposito->id}}</td>
<td>{{$format->pesos($deposito->capital)}}</td>
<td>{{$deposito->inicio->format('d-m-Y')}}</td>
<td>{{$deposito->plazo()}}</td>
<td>{{$deposito->termino->format('d-m-Y')}}</td>
<td>{{$deposito->termino->format('Y-m-d')}}</td>
<td>{{$format->pesos($deposito->futuro)}}</td>
<td>{{$format->percent($deposito->tasa() * 100, 4)}}</td>
<td>
<button class="ui red icon button remove_button" data-deposito="{{$deposito->id}}">
<i class="remove icon"></i>
</button>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
<div class="ui modal" id="add_modal">
<div class="content">
<form class="ui form" id="add_form">
<div class="two fields">
<div class="field">
<label for="inmobiliaria">Inmobiliaria</label>
<div class="ui search selection dropdown" id="inmobiliaria">
<input type="hidden" name="inmobiliaria_rut" />
<i class="dropdown icon"></i>
<div class="default text">Inmobiliaria</div>
<div class="menu">
@foreach ($inmobiliarias as $inmobiliaria)
<div class="item" data-value="{{$inmobiliaria->rut}}">{{$inmobiliaria->razon}}</div>
@endforeach
</div>
</div>
</div>
<div class="field">
<label for="banco">Banco</label>
<div class="ui search selection dropdown" id="banco">
<input type="hidden" name="banco_id" />
<i class="dropdown icon"></i>
<div class="default text">Banco</div>
<div class="menu"></div>
</div>
</div>
</div>
<div class="three wide field">
<label for="identificador"> Depósito</label>
<input type="text" id="identificador" name="id" />
</div>
<div class="three fields">
<div class="field">
<label for="capital">Capital</label>
<input type="number" id="capital" name="capital" />
</div>
<div class="field">
<label for="futuro">Monto al Vencimiento</label>
<input type="number" id="futuro" name="futuro" />
</div>
</div>
<div class="two fields">
<div class="field">
<label for="inicio">Inicio</label>
<div class="ui calendar" id="inicio">
<div class="ui left icon input">
<i class="calendar icon"></i>
<input type="text" name="inicio" />
</div>
</div>
</div>
<div class="field">
<label for="termino">Vencimiento</label>
<div class="ui calendar" id="termino">
<div class="ui left icon input">
<i class="calendar icon"></i>
<input type="text" name="termino" />
</div>
</div>
</div>
</div>
</form>
</div>
<div class="actions">
<button class="ui approve button">Agregar</button>
</div>
</div>
@endsection
@include('layout.head.styles.datatables')
@include('layout.body.scripts.datatables')
@push('page_scripts')
<script>
const depositos = {
ids: {},
data: {
inmobiliaria: {
rut: 0,
razon: ''
},
banco: {
id: 0,
nombre: ''
}
},
get() {
return {
bancos: inmobiliaria_rut => {
const url = '{{$urls->api}}/inmobiliaria/' + inmobiliaria_rut + '/cuentas'
return fetchAPI(url).then(response => {
if (!response) {
return
}
return response.json().then(json => {
if (json.cuentas.length === 0) {
return
}
$(this.ids.forms.add.bancos).dropdown('change values', json.cuentas.map(cuenta => {
return {value: cuenta.banco.id, text: cuenta.banco.nombre, name: cuenta.banco.nombre}
})).dropdown('refresh')
})
})
},
}
},
add() {
return {
deposito: form => {
const url = '{{$urls->api}}/contabilidad/depositos/add'
const body = new FormData(form)
const inicio = $(this.ids.forms.add.inicio).calendar('get date')
const termino = $(this.ids.forms.add.termino).calendar('get date')
body.set('inicio', [inicio.getFullYear(), inicio.getMonth()+1, inicio.getDate()].join('-'))
body.set('termino', [termino.getFullYear(), termino.getMonth()+1, termino.getDate()].join('-'))
return fetchAPI(url, {method: 'post', body}).then(response => {
if (!response) {
return
}
return response.json().then(json => {
if (json.status) {
window.location.reload()
}
})
})
}
}
},
setup(ids) {
this.ids = ids
$(this.ids.buttons.add).click(event => {
$(this.ids.modals.add).modal('show')
})
$(this.ids.modals.add).modal({
onApprove: $element => {
$(this.ids.forms.add.base).submit()
}
})
$(this.ids.forms.add.base).submit(event => {
event.preventDefault()
this.add().deposito(event.currentTarget)
return false
})
$(this.ids.forms.add.inmobiliarias).dropdown({
fireOnInit: true,
onChange: (value, text, $choice) => {
this.data.inmobiliaria.rut = value
this.data.inmobiliaria.razon = text
this.get().bancos(value)
}
})
$(this.ids.forms.add.banco).dropdown({
fireOnInit: true,
onChange: (value, text, $choice) => {
this.data.banco.id = value
this.data.banco.nombre = text
}
})
$(this.ids.forms.add.inicio).calendar(calendar_date_options)
$(this.ids.forms.add.termino).calendar(calendar_date_options)
$(this.ids.table).dataTable({
columnDefs: [{target: 7, visible: false, searchable: false}],
order: [[7, 'desc'], [0, 'asc']]
})
}
}
$(document).ready(() => {
depositos.setup({
table: '#depositos',
buttons: {
add: '#add_button'
},
modals: {
add: '#add_modal'
},
forms: {
add: {
base: '#add_form',
inmobiliarias: '#inmobiliaria',
bancos: '#banco',
inicio: '#inicio',
termino: '#termino'
}
}
})
})
</script>
@endpush

View File

@ -0,0 +1,156 @@
@extends('layout.base')
@section('page_content')
<div class="ui container">
<h1 class="ui centered header">Informe de Tesorería</h1>
<h4 class="ui centered sub header">{{$fecha->format('d M Y')}}</h4>
<div class="ui grid">
<div class="three wide column">
<a href="/contabilidad/informes/xlsx/tesoreria/{{$fecha->format('Y-m-d')}}" target="_blank" style="color: inherit;">
<div class="ui inverted green center aligned segment">
Descargar en Excel <i class="file excel icon"></i>
</div>
</a>
</div>
</div>
</div>
<div class="ui grid">
<div class="four wide column">
<table class="ui collapsing simple table">
<tr>
<td>Informe anterior</td>
<td>{{$anterior->format('d/m/Y')}}</td>
</tr>
<tr>
<td>Informe actual</td>
<td>{{$fecha->format('d/m/Y')}}</td>
</tr>
</table>
</div>
<div class="column"></div>
<div class="four wide column">
<table class="ui collapsing simple table">
<tr>
<td>Valor UF</td>
<td class="right aligned">{{$format->pesos($UF->get($fecha), 2)}}</td>
</tr>
<tr>
<td>Valor Dólar</td>
<td class="right aligned">{{$format->pesos($USD->get($fecha), 2)}}</td>
</tr>
</table>
</div>
</div>
<table class="ui striped table">
<thead>
<tr>
<th>EMPRESA</th>
<th>Banco</th>
<th>Cuenta</th>
<th class="right aligned">Saldo Anterior</th>
<th class="right aligned">Saldo Actual</th>
<th class="right aligned">Diferencia</th>
<th class="right aligned">FFMM</th>
<th class="right aligned">DAP</th>
<th class="right aligned">Saldo Empresa</th>
<th class="right aligned">Total Cuentas</th>
<th class="right aligned">Total FFMM</th>
<th class="right aligned">Total DAP</th>
<th class="right aligned">Caja Total</th>
</tr>
</thead>
<tbody>
@foreach ($informes['inmobiliarias'] as $inmobiliaria_rut => $informe)
@foreach ($informe->cuentas as $i => $cuenta)
<tr>
@if ($i === 0)
<td rowspan="{{count($informe->cuentas)}}">{{$informe->inmobiliaria->razon}}</td>
@endif
<td>{{$cuenta->banco}}</td>
<td>{{$cuenta->numero}}</td>
<td class="right aligned">{{$format->pesos($cuenta->anterior)}}</td>
<td class="right aligned">{{$format->pesos($cuenta->actual)}}</td>
<td class="right aligned">{{$format->pesos($cuenta->diferencia())}}</td>
<td class="right aligned">{{$format->pesos($cuenta->ffmm)}}</td>
<td class="right aligned">{{$format->pesos($cuenta->deposito)}}</td>
<td class="right aligned">{{$format->pesos($cuenta->saldo())}}</td>
@if ($i === 0)
<td class="right aligned" rowspan="{{count($informe->cuentas)}}">{{$format->pesos($informe->total())}}</td>
<td class="right aligned" rowspan="{{count($informe->cuentas)}}">{{$format->pesos($informe->ffmm())}}</td>
<td class="right aligned" rowspan="{{count($informe->cuentas)}}">{{$format->pesos($informe->deposito())}}</td>
<td class="right aligned" rowspan="{{count($informe->cuentas)}}">{{$format->pesos($informe->caja())}}</td>
@endif
</tr>
@endforeach
@endforeach
</tbody>
<tfoot>
<tr class="bold">
<th colspan="3">TOTAL</th>
<th class="right aligned">{{$format->pesos($informes['totales']->anterior)}}</th>
<th class="right aligned">{{$format->pesos($informes['totales']->actual)}}</th>
<th class="right aligned">{{$format->pesos($informes['totales']->diferencia())}}</th>
<th class="right aligned">{{$format->pesos($informes['totales']->ffmm)}}</th>
<th class="right aligned">{{$format->pesos($informes['totales']->deposito)}}</th>
<th class="right aligned">{{$format->pesos($informes['totales']->saldo())}}</th>
<th class="right aligned">{{$format->pesos($informes['totales']->cuentas())}}</th>
<th class="right aligned">{{$format->pesos($informes['totales']->ffmms())}}</th>
<th class="right aligned">{{$format->pesos($informes['totales']->depositos())}}</th>
<th class="right aligned">{{$format->pesos($informes['totales']->caja())}}</th>
</tr>
</tfoot>
</table>
<table class="ui table">
<thead>
<tr>
<th>EMPRESA</th>
<th class="right aligned">INGRESOS</th>
<th class="right aligned">EGRESOS</th>
<th>FECHA</th>
<th>BANCO</th>
<th>DESCRIPCIÓN</th>
</tr>
</thead>
<tbody>
@foreach ($informes['movimientos'] as $tipo => $movimientos)
@if ($tipo === 'capital dap')
@if (count($movimientos['ingresos']) === 0 and count($movimientos['egresos']) === 0)
@continue
@endif
<tr class="grey">
<td colspan="6">{{strtoupper($tipo)}}</td>
</tr>
@foreach ($movimientos as $ms)
@foreach ($ms as $movimiento)
<tr>
<td >{{$movimiento->cuenta->inmobiliaria->razon}}</td>
<td class="right aligned">{{$format->pesos($movimiento->abono)}}</td>
<td class="right aligned">{{$format->pesos($movimiento->cargo)}}</td>
<td>{{$movimiento->fecha->format('d/m/Y')}}</td>
<td>{{$movimiento->cuenta->banco->nombre}}</td>
<td>{{$movimiento->glosa}}</td>
</tr>
@endforeach
@endforeach
@continue
@endif
@if (count($movimientos) === 0)
@continue
@endif
<tr class="grey">
<td colspan="6">{{strtoupper($tipo)}}</td>
</tr>
@foreach ($movimientos as $movimiento)
<tr>
<td >{{$movimiento->cuenta->inmobiliaria->razon}}</td>
<td class="right aligned">{{$format->pesos($movimiento->abono)}}</td>
<td class="red right aligned">{{$format->pesos($movimiento->cargo)}}</td>
<td>{{$movimiento->fecha->format('d/m/Y')}}</td>
<td>{{$movimiento->cuenta->banco->nombre}}</td>
<td>{{$movimiento->glosa}}</td>
</tr>
@endforeach
@endforeach
</tbody>
</table>
@endsection

View File

@ -2,6 +2,13 @@
Contabilidad
<i class="dropdown icon"></i>
<div class="menu">
<div class="item">
<i class="dropdown icon"></i>
Informes
<div class="menu">
<a class="item" href="{{$urls->base}}/contabilidad/informes/tesoreria/{{$hoy->sub(new DateInterval('P1D'))->format('Y-m-d')}}">Tesorería</a>
</div>
</div>
<div class="item">
<i class="dropdown icon"></i>
<a class="text" href="{{$urls->base}}/contabilidad/centros_costos">Centros de Costos</a>
@ -9,5 +16,7 @@
<a class="item" href="{{$urls->base}}/contabilidad/centros_costos/asignar">Asignar en Cartola</a>
</div>
</div>
<a class="item" href="{{$urls->base}}/contabilidad/cartolas/diaria">Cartola Diaria</a>
<a class="item" href="{{$urls->base}}/contabilidad/depositos">Depósitos a Plazo</a>
</div>
</div>

View File

@ -1,5 +1,5 @@
<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 src="https://cdnjs.cloudflare.com/ajax/libs/fomantic-ui/2.9.3/semantic.min.js" integrity="sha512-gnoBksrDbaMnlE0rhhkcx3iwzvgBGz6mOEj4/Y5ZY09n55dYddx6+WYc72A55qEesV8VX2iMomteIwobeGK1BQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
function fetchAPI(url, options=null) {

View File

@ -1,4 +1,5 @@
@push('page_scripts')
<script type="text/javascript" src="https://cdn.datatables.net/1.13.5/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.13.5/js/dataTables.semanticui.min.js"></script>
{{--<script type="text/javascript" src="https://cdn.datatables.net/2.0.1/js/jquery.dataTables.min.js"></script>--}}
<script type="text/javascript" src="https://cdn.datatables.net/2.0.1/js/dataTables.min.js"></script>
<script src="https://cdn.datatables.net/2.0.1/js/dataTables.semanticui.min.js"></script>
@endpush

View File

@ -0,0 +1,9 @@
@push('page_scripts')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.9/pdfmake.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.datatables.net/buttons/3.0.0/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/3.0.0/js/buttons.semanticui.min.js"></script>
<script src="https://cdn.datatables.net/buttons/3.0.0/js/buttons.colVis.min.js"></script>
<script src="https://cdn.datatables.net/buttons/3.0.0/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/3.0.0/js/buttons.print.min.js"></script>
@endpush

View File

@ -1,3 +1,3 @@
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fomantic-ui/2.9.2/semantic.min.css" integrity="sha512-n//BDM4vMPvyca4bJjZPDh7hlqsQ7hqbP9RH18GF2hTXBY5amBwM2501M0GPiwCU/v9Tor2m13GOTFjk00tkQA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fomantic-ui/2.9.3/semantic.min.css" integrity="sha512-3quBdRGJyLy79hzhDDcBzANW+mVqPctrGCfIPosHQtMKb3rKsCxfyslzwlz2wj1dT8A7UX+sEvDjaUv+WExQrA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
@stack('page_styles')

View File

@ -1,3 +1,3 @@
@push('page_styles')
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.5/css/dataTables.semanticui.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/2.0.1/css/dataTables.semanticui.min.css" />
@endpush

View File

@ -0,0 +1,3 @@
@push('page_styles')
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/3.0.0/css/buttons.semanticui.min.css" />
@endpush

View File

@ -6,7 +6,7 @@
<form id="search_form" class="ui form" action="{{$urls->base}}/search" method="post">
<div class="field">
<div class="ui fluid input" data-tooltip="Para buscar frases se deben encerrar entre comillas. ej, 'portal la viña' o &quot;portal la viña&quot;" data-position="bottom left">
<div class="ui fluid input" data-tooltip="Para buscar frases se deben encerrar entre comillas. ej, 'portal la viña' o &quot;portal la viña&quot;" data-position="top right">
<input type="text" name="query" />
</div>
</div>
@ -56,7 +56,7 @@
unidad.html(unidad.html() + ' (I)')
}
propietario = $('<a></a>')
.attr('href','{{$urls->base}}/search/' + encodeURIComponent(this.venta.propietario.nombre_completo) + '/propietario')
.attr('href','{{$urls->base}}/search/"' + encodeURIComponent(this.venta.propietario.nombre_completo) + '"/propietario')
.html(this.venta.propietario.nombre_completo)
fecha = dateFormatter.format(new Date(this.venta.fecha))
if (typeof this.venta.entrega !== 'undefined') {
@ -96,6 +96,10 @@
id: '',
data: [],
table: null,
queues: {
unidades: [],
ventas: []
},
get: function() {
return {
results: () => {
@ -122,34 +126,33 @@
}
const progress = this.draw().progress(data.results.length)
const promises = []
data.results.forEach(row => {
if (row.tipo === 'venta') {
return promises.push(this.get().venta(row.id).then(json => {
if (json.venta === null) {
console.debug(json)
return
}
const venta = json.venta
this.queues.ventas = data.results.filter(row => row.tipo === 'venta').map(row => row.id)
this.queues.unidades = data.results.filter(row => row.tipo !== 'venta').map(row => row.id)
promises.push(this.get().ventas().then(arrays => {
arrays.forEach(json => {
if (json.ventas.length === 0) {
console.debug(json)
return
}
json.ventas.forEach(venta => {
progress.progress('increment')
const r = new Row({unidad: venta.propiedad.unidades[0], proyecto: venta.proyecto})
r.venta = venta
this.data.push(r)
}).catch(error => {
})
})
}))
promises.push(this.get().unidades().then(arrays => {
arrays.forEach(json => {
if (json.unidades.length === 0) {
return
}
json.unidades.forEach(unidad => {
progress.progress('increment')
console.error(row)
console.error(error)
}))
}
promises.push(this.get().unidad(row.id).then(json => {
const unidad = json.unidad
progress.progress('increment')
this.data.push(new Row({unidad: unidad, proyecto: unidad.proyecto_tipo_unidad.proyecto}))
}).catch(error => {
progress.progress('increment')
console.error(row)
console.error(error)
}))
})
this.data.push(new Row({unidad: unidad, proyecto: unidad.proyecto_tipo_unidad.proyecto}))
})
})
}))
Promise.all(promises).then(() => {
this.sort()
this.draw().clear()
@ -157,22 +160,43 @@
})
})
},
unidad: id => {
const url = '{{$urls->api}}/ventas/unidad/' + id
return fetchAPI(url).then(response => {
if (response.ok) {
unidades: () => {
const url = '{{$urls->api}}/search/ventas/unidades'
const chunks = []
for (let i = 0; i < this.queues.unidades.length; i += 100) {
chunks.push(this.queues.unidades.slice(i, i + 100))
}
const promises = []
chunks.forEach(ids => {
const body = new FormData()
body.set('unidades', ids)
promises.push(fetchAPI(url, {method: 'post', body}).then(response => {
if (!response) {
return
}
return response.json()
}
}))
})
return Promise.all(promises)
},
venta: id => {
const url = '{{$urls->api}}/venta/' + id
return fetchAPI(url).then(response => {
if (!response) {
return
}
return response.json()
ventas: () => {
const url = '{{$urls->api}}/search/ventas'
const chunks = []
for (let i = 0; i < this.queues.ventas.length; i += 100) {
chunks.push(this.queues.ventas.slice(i, i + 100))
}
const promises = []
chunks.forEach(ids => {
const body = new FormData()
body.set('ventas', ids)
promises.push(fetchAPI(url, {method: 'post', body}).then(response => {
if (!response) {
return
}
return response.json()
}))
})
return Promise.all(promises)
}
}
},
@ -309,15 +333,23 @@
}
}
},
set: function() {
return {
query: value => {
$("[name='query']").val(value)
this.get().results()
}
}
},
setup: function(id) {
this.id = id
this.get().results()
$('#tipo').dropdown().dropdown('set selected', '*')
@if (trim($post) !== '')
$("[name='query']").val('{{$post}}')
this.set().query('{!! $post !!}')
@elseif (trim($query) !== '')
$("[name='query']").val('{{$query}}')
this.set().query('{!! $query !!}')
@endif
@if (trim($tipo) !== '')
$('#tipo').dropdown('set selected', '{{$tipo}}')

View File

@ -349,7 +349,7 @@
const lines = [
'<label for="rut">RUT</label>',
'<div class="inline field">',
'<input type="text" id="rut" name="rut" />',
'<input type="text" id="rut" name="rut" placeholder="00000000-0" />',
'<span class="ui error message" id="alert_rut">',
'<i class="exclamation triangle icon"></i>',
'RUT Inválido',
@ -358,25 +358,25 @@
'<label for="nombres">Nombre</label>',
'<div class="inline fields">',
'<div class="field">',
'<input type="text" name="nombres" id="nombres" />',
'<input type="text" name="nombres" id="nombres" placeholder="Nombre(s)" />',
'</div>',
'<div class="field">',
'<input type="text" name="apellido_paterno" />',
'<input type="text" name="apellido_paterno" placeholder="Apellido Paterno" />',
'</div>',
'<div class="field">',
'<input type="text" name="apellido_materno" />',
'<input type="text" name="apellido_materno" placeholder="Apellido Materno" />',
'</div>',
'</div>',
'<label for="calle">Dirección</label>',
'<div class="inline fields">',
'<div class="eight wide field">',
'<input type="text" name="calle" id="calle" size="16" />',
'<input type="text" name="calle" id="calle" size="16" placeholder="Calle" />',
'</div>',
'<div class="field">',
'<input type="text" name="numero" size="5" />',
'<input type="text" name="numero" size="5" placeholder="Número" />',
'</div>',
'<div class="field">',
'<input type="text" name="extra" />',
'<input type="text" name="extra" placeholder="Otros Detalles" />',
'</div>',
'</div>',
'<div class="inline fields">',

View File

@ -0,0 +1,294 @@
@extends('ventas.base')
@section('venta_subtitle')
Crédito
@endsection
@section('venta_content')
@php($credito = $venta->formaPago()->credito)
<div class="ui grid">
<div class="row">
<div class="two wide column">Fecha</div>
<div class="six wide column" id="fecha" data-status="static">
<span id="fecha_data">
{{$credito->pago->fecha->format('d-m-Y')}}
</span>
<a href="#" id="fecha_edit">
<i class="edit icon"></i>
</a>
<div class="ui calendar hidden" id="fecha_input">
<div class="ui left icon input">
<i class="calendar icon"></i>
<input type="text" name="fecha" />
</div>
</div>
</div>
</div>
<div class="row">
<div class="two wide column">Banco</div>
<div class="six wide column" id="banco" data-status="static">
<span id="banco_data">
@if (isset($credito->pago->banco))
{{$credito->pago->banco->nombre}}
@else
No definido
@endif
</span>
<a href="#" id="banco_edit">
<i class="edit icon"></i>
</a>
<div class="ui search selection dropdown hidden" id="banco_input">
<input type="hidden" name="banco" />
<i class="dropdown icon"></i>
<div class="default text">Banco</div>
<div class="menu">
@foreach ($bancos as $banco)
<div class="item" data-value="{{$banco->id}}">{{$banco->nombre}}</div>
@endforeach
</div>
</div>
</div>
</div>
<div class="row">
<div class="two wide column">Valor</div>
<div class="six wide column" id="valor" data-status="static">
<span id="valor_data">
{{$format->ufs($credito->pago->valor())}}
</span>
<a href="#" id="valor_edit">
<i class="edit icon"></i>
</a>
<div class="ui right labeled input hidden" id="valor_input">
<input type="text" name="valor" />
<div class="ui basic label">UF</div>
</div>
</div>
</div>
</div>
@endsection
@push('page_styles')
<style>
.hidden {
display: none !important;
}
</style>
@endpush
@push('page_scripts')
<script>
const credito = {
ids: {},
data: {
venta: {{$venta->id}},
credito: {{$credito->id}},
fecha: new Date({{$credito->pago->fecha->format('Y')}},
{{$credito->pago->fecha->format('m')}}+1,
{{$credito->pago->fecha->format('d')}}),
banco: {
@if (isset($credito->pago->banco))
id: {{$credito->pago->banco->id}},
nombre: '{{$credito->pago->banco->nombre}}'
@else
id: 0,
nombre: ''
@endif
},
valor: {{$credito->pago->valor()}},
bancos: JSON.parse('{!! json_encode($bancos) !!}')
},
elements: {},
change() {
return {
status: (id, status) => {
this.elements[id].dataset.status = status
}
}
},
hide() {
return {
data: id => {
this.elements[id + '.data'].innerHTML = ''
this.elements[id + '.data'].classList.add('hidden')
this.elements[id + '.data'].hidden = true
},
input: id => {
this.elements[id + '.input'].classList.add('hidden')
this.elements[id + '.input'].hidden = true
}
}
},
show() {
return {
data: id => {
this.elements[id + '.data'].classList.remove('hidden')
this.elements[id + '.data'].hidden = false
},
input: id => {
this.elements[id + '.input'].classList.remove('hidden')
this.elements[id + '.input'].hidden = false
}
}
},
draw() {
return {
edit: (id) => {
this.change().status(id, 'edit')
this.show().input(id)
this.update()[id]()
},
static: (id, text) => {
this.change().status(id, 'static')
this.hide().input(id)
this.elements[this.ids.fields[id] + '.data'].innerHTML = this.format()[id](text)
}
}
},
send(id, value) {
const url = '{{$urls->api}}/venta/{{$venta->id}}/credito'
const body = new FormData()
body.set(id, value)
return fetchAPI(url, {method: 'post', body}).then(response => {
if (!response) {
return
}
return response.json().then(json => {
if (!json.status) {
return
}
this.data.fecha = new Date(json.credito.pago.fecha)
this.data.banco.id = json.credito.pago.banco.id
this.data.banco.nombre = json.credito.pago.banco.nombre
this.data.valor = json.credito.pago.valor / json.credito.pago.uf
})
})
},
edit() {
return {
fecha: fecha => {
this.send('fecha', fecha).then(() => {
this.draw().static('fecha', this.data.fecha)
})
},
banco: banco_id => {
this.send('banco', banco_id).then(() => {
this.draw().static('banco', this.data.banco.nombre)
})
},
valor: valor => {
this.send('valor', valor).then(() => {
this.draw().static('valor', this.data.valor)
})
}
}
},
format() {
return {
fecha: value => {
const dateFormatter = new Intl.DateTimeFormat('es-CL', {year: 'numeric', month: 'numeric', day: 'numeric'})
return dateFormatter.format(value)
},
banco: value => {
if (value === '') {
value = 'No definido'
}
return value
},
valor: value => {
const numberFormatter = new Intl.NumberFormat('es-CL', {minimumFractionDigits: 2, maximumFractionDigits: 2})
return numberFormatter.format(value) + ' UF'
}
}
},
update() {
return {
fecha: () => {
const $fecha = $(this.elements.fecha.querySelector('div.ui.calendar'))
$fecha.calendar('set date', this.data.fecha)
$fecha.calendar('focus')
},
banco: () => {
const $dropdown = $(this.elements.banco.querySelector('div.ui.dropdown'))
$dropdown.dropdown('clear')
if (this.data.banco.id !== 0) {
$dropdown.dropdown('set selected', this.data.banco.id)
}
$dropdown.dropdown('toggle')
},
valor: () => {
const input = this.elements.valor.querySelector('input')
input.value = this.data.valor ?? ''
input.focus()
}
}
},
watch(id) {
this.elements[id + '.edit'].addEventListener('click', event => {
const elem = event.currentTarget.parentNode
const id = elem.id
const status = elem.dataset.status
if (status !== 'static') {
return
}
this.draw().edit(id)
})
},
register(name, elem_id) {
this.elements[name] = document.getElementById(elem_id)
},
setup(ids) {
this.ids = ids
Object.entries(this.ids.fields).forEach(entry => {
const name = entry[0]
const field = entry[1]
this.register(name, field)
this.register(name + '.data', field + '_data')
this.register(name + '.input', field + '_input')
this.register(name + '.edit', field + '_edit')
this.watch(field)
})
calendar_date_options['onChange'] = (date, text, mode) => {
if (date === this.data.fecha) {
return
}
this.edit().fecha([date.getFullYear(), date.getMonth()+1, date.getDate()].join('-'))
}
calendar_date_options['onHide'] = () => {
this.draw().static('fecha', this.data.fecha)
}
$(this.elements.fecha).find('div.ui.calendar').calendar(calendar_date_options)
$(this.elements.banco).find('div.ui.dropdown').dropdown({
onChange: (value, text, $element) => {
if (value === '' || value === this.data.banco.id) {
return
}
this.edit().banco(value)
},
onHide: () => {
this.draw().static('banco', this.data.banco.nombre)
}
})
this.elements.valor.querySelector('input').addEventListener('blur', event => {
let valor = event.currentTarget.value
if (valor.includes(',')) {
valor = valor.replaceAll('.', '').replace(',', '.')
}
if (parseFloat(valor) === this.data.valor) {
this.draw().static('valor', this.data.valor)
return
}
this.edit().valor(valor)
})
}
}
$(document).ready(() => {
credito.setup({
fields: {
fecha: 'fecha',
banco: 'banco',
valor: 'valor'
}
})
})
</script>
@endpush

View File

@ -0,0 +1,153 @@
@extends('ventas.base')
@section('venta_subtitle')
Agregar Abono en Escritura
@endsection
@section('venta_content')
<div class="ui basic segment">
<p>Valor Promesa {{$format->ufs($venta->valor)}}</p>
@if (isset($venta->formaPago()->pie))
<p>Valor Anticipo {{$format->ufs($venta->formaPago()->pie->valor)}}</p>
@endif
@if (isset($venta->formaPago()->credito))
<p>Crédito {{$format->ufs($venta->formaPago()->credito->pago->valor())}}</p>
@endif
</div>
<form class="ui form" id="add_form">
<div class="three wide field">
<label for="fecha">Fecha</label>
<div class="ui calendar" id="fecha">
<div class="ui left icon input">
<i class="calendar icon"></i>
<input type="text" name="fecha" />
</div>
</div>
</div>
<div class="fields">
<div class="field">
<label for="valor">Valor</label>
<div class="ui labeled input" id="valor">
<div class="ui basic label">$</div>
<input type="text" name="valor" />
</div>
</div>
<div class="field">
<div class="ui checkbox" id="uf">
<input type="checkbox" name="uf" />
<label>Valor en UFs</label>
</div>
</div>
</div>
<div class="fields">
<div class="three wide field">
<label for="bancos">Banco</label>
<div class="ui search selection dropdown" id="bancos">
<input type="hidden" name="banco" />
<i class="dropdown icon"></i>
<div class="default text">Banco</div>
<div class="menu">
@foreach ($bancos as $banco)
<div class="item" data-value="{{$banco->id}}">{{$banco->nombre}}</div>
@endforeach
</div>
</div>
</div>
<div class="fields">
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="tipo" value="1" checked="checked" />
<label>Cheque</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="tipo" value="3" />
<label>Vale Vista</label>
</div>
</div>
</div>
</div>
<button class="ui button">Agregar</button>
</form>
@endsection
@push('page_scripts')
<script>
const escritura = {
ids: {},
add() {
return {
escritura: event => {
event.preventDefault()
const body = new FormData(event.currentTarget)
const fecha = $(this.ids.fecha).calendar('get date')
body.set('fecha', [fecha.getFullYear(), fecha.getMonth()+1, fecha.getDate()].join('-'))
const status = $(this.ids.checkbox).checkbox('is checked')
body.set('uf', status)
const url = '{{$urls->api}}/venta/{{$venta->id}}/escritura/add'
fetchAPI(url, {method: 'post', body}).then(response => {
if (!response) {
return
}
return response.json().then(json => {
if (json.status) {
window.location = '{{$urls->base}}/venta/{{$venta->id}}'
}
})
})
return false
}
}
},
toggle() {
return {
checkbox: () => {
const status = $(this.ids.checkbox).checkbox('is checked')
if (status) {
return this.toggle().uf()
}
return this.toggle().pesos()
},
uf: () => {
const valor = $(this.ids.valor)
valor.attr('class', 'ui right labeled input')
valor.find('.label').remove()
valor.append(
$('<div></div>').addClass('ui basic label').html('UF')
)
},
pesos: () => {
const valor = $(this.ids.valor)
valor.attr('class', 'ui labeled input')
valor.find('.label').remove()
valor.prepend(
$('<div></div>').addClass('ui basic label').html('$')
)
}
}
},
setup(ids) {
this.ids = ids
$(this.ids.fecha).calendar(calendar_date_options)
$(this.ids.checkbox).checkbox({
fireOnInit: true,
onChange: this.toggle().checkbox
})
$(this.ids.bancos).dropdown()
$(this.ids.form).submit(this.add().escritura)
}
}
$(document).ready(() => {
escritura.setup({
form: '#add_form',
fecha: '#fecha',
checkbox: '#uf',
valor: '#valor',
bancos: '#bancos'
})
})
</script>
@endpush

View File

@ -116,10 +116,15 @@
this.data.id = data.proyecto.id
this.data.proyecto = data.proyecto.descripcion
this.data.venta_ids = data.ventas
const chunkSize = 50
const chunks = []
for (let i = 0; i < data.ventas.length; i += chunkSize) {
chunks.push(data.ventas.splice(i, i + chunkSize))
}
const promises = []
data.ventas.forEach(venta_id => {
const promise = this.get().venta(venta_id).then(() => {
progress.progress('increment')
chunks.forEach(chunk => {
const promise = this.get().venta(chunk).then(count => {
progress.progress('increment', count)
})
promises.push(promise)
})
@ -129,17 +134,22 @@
}
})
},
venta: venta_id => {
return fetchAPI('{{$urls->api}}/venta/' + venta_id).then(response => {
venta: chunk => {
const body = new FormData()
body.set('ventas', chunk.join(','))
return fetchAPI('{{$urls->api}}/ventas/get', {method: 'post', body}).then(response => {
if (response.ok) {
return response.json()
}
}).then(data => {
if (typeof data.venta === 'undefined') {
console.error(venta_id, data.error)
if (data.ventas.length === 0) {
console.error(chunk, data.error)
return
}
this.add().venta(data.venta)
data.ventas.forEach(venta_id => {
this.add().venta(venta_id)
})
return data.ventas.length
})
}
}

View File

@ -136,7 +136,10 @@
</table>
@endsection
@include('layout.head.styles.datatables')
@include('layout.head.styles.datatables.buttons')
@include('layout.body.scripts.datatables')
@include('layout.body.scripts.datatables.buttons')
@push('page_scripts')
<script type="text/javascript">
@ -210,11 +213,6 @@
return
}
updateRow({pago_id: json.pago_id, fecha: json.fecha, estado: 'Anulado', color: 'red', remove_fecha: true, disable: true})
/*const tr = $("button[data-id='" + json.pago_id + "']").parent().parent()
tr.addClass('disabled')
tr.find(':nth-child(7)').addClass('red').html('Anulado')
tr.find(':nth-child(8)').html(json.fecha)
tr.find(':nth-child(9)').html('')*/
})
})
}
@ -296,7 +294,23 @@
order: [
[0, 'asc'],
[2, 'asc']
]
],
layout: {
top2End: {
buttons: [
{
extend: 'excel',
className: 'green',
text: 'Exportar a Excel <i class="file excel icon"></i>',
title: 'Cuotas - {{$venta->proyecto()->descripcion}} - {{$venta->propiedad()->summary()}}',
download: 'open',
exportOptions: {
columns: ':visible'
}
}
]
}
}
})
})
</script>

View File

@ -32,46 +32,3 @@ $showPropietario = true;
@include('ventas.show.comentarios')
</div>
@endsection
{{--@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 class="right floated column">
@include('ventas.show.propietario')
</div>
</div>
<br />
<div class="ui fitted basic mini segment">
@if ($venta->currentEstado()->tipoEstadoVenta->activa)
<a href="{{$urls->base}}/venta/{{$venta->id}}/desistir">
Desistir <i class="minus icon"></i>
</a>
<a href="{{$urls->base}}/venta/{{$venta->id}}/ceder">
Ceder <i clasS="right chevron icon"></i>
</a>
@else
<div class="ui red icon label">
<i class="ban icon"></i>
{{ucwords($venta->currentEstado()->tipoEstadoVenta->descripcion)}}
(<a href="{{$urls->base}}/venta/{{$venta->id}}/desistida">
{{$format->pesos($venta->resciliacion()->valor)}}
</a>)
</div>
@endif
</div>
<div class="ui segments">
@include('ventas.show.propiedad')
@include('ventas.show.detalle')
@include('ventas.show.forma_pago', ['formaPago' => $venta->formaPago()])
@include('ventas.show.escritura')
@include('ventas.show.entrega')
@include('ventas.show.comentarios')
</div>
</div>
@endsection--}}

View File

@ -3,14 +3,14 @@
</div>
<div class="ui segment">
<table class="ui very basic fluid table">
@include('ventas.show.forma_pago.pie', ['pie' => $formaPago->pie])
@include('ventas.show.forma_pago.escritura', ['escritura' => $formaPago->escritura])
@include('ventas.show.forma_pago.anticipo', ['anticipo' => ['uf' => $formaPago->anticipo(), 'pesos' => $formaPago->anticipo('pesos')]])
@include('ventas.show.forma_pago.bono_pie', ['bonoPie' => $formaPago->bonoPie])
@include('ventas.show.forma_pago.subsidio', ['subsidio' => $formaPago->subsidio])
@include('ventas.show.forma_pago.credito', ['credito' => $formaPago->credito])
@include('ventas.show.forma_pago.pie', ['pie' => $formaPago?->pie])
@include('ventas.show.forma_pago.escritura', ['escritura' => $formaPago?->escritura])
@include('ventas.show.forma_pago.anticipo', ['anticipo' => ['uf' => $formaPago?->anticipo(), 'pesos' => $formaPago?->anticipo('pesos')]])
@include('ventas.show.forma_pago.bono_pie', ['bonoPie' => $formaPago?->bonoPie])
@include('ventas.show.forma_pago.subsidio', ['subsidio' => $formaPago?->subsidio])
@include('ventas.show.forma_pago.credito', ['credito' => $formaPago?->credito])
@include('ventas.show.forma_pago.total')
@include('ventas.show.forma_pago.devolucion', ['devolucion' => $formaPago->devolucion])
@include('ventas.show.forma_pago.devolucion', ['devolucion' => $formaPago?->devolucion])
</table>
</div>
<div id="pago_modal" class="ui modal">

View File

@ -16,7 +16,7 @@
<a href="{{$urls->base}}/venta/{{$venta->id}}/pie/cuotas">
<span data-tooltip="Pagadas">{{count($pie->cuotas(true))}}</span>/{{$pie->cuotas}}
</a>
@if (count($pie->cuotas()) < $pie->cuotas)
@if (count($pie->cuotas(false, true)) < $pie->cuotas)
<a href="{{$urls->base}}/ventas/pie/{{$pie->id}}/cuotas/add">
<i class="plus icon"></i>
</a>

View File

@ -8,7 +8,8 @@ return [
'cache' => DI\String('{base}/cache'),
'templates' => DI\String('{resources}/views'),
'public' => DI\String('{base}/public'),
'uploads' => DI\String('{public}/uploads')
'uploads' => DI\String('{public}/uploads'),
'informes' => DI\String('{public}/informes')
]);
}
];

View File

@ -4,10 +4,10 @@ use Psr\Container\ContainerInterface;
return [
Incoviba\Common\Define\Database::class => function(ContainerInterface $container) {
return new Incoviba\Common\Implement\Database\MySQL(
$container->has('MYSQL_HOST') ? $container->get('MYSQL_HOST') : 'db',
$container->get('MYSQL_DATABASE'),
$container->get('MYSQL_USER'),
$container->get('MYSQL_PASSWORD')
$container->has('DB_HOST') ? $container->get('DB_HOST') : 'db',
$container->get('DB_DATABASE'),
$container->get('DB_USER'),
$container->get('DB_PASSWORD')
);
},
Incoviba\Common\Define\Connection::class => function(ContainerInterface $container) {

View File

@ -20,7 +20,9 @@ return [
$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)
return (new Incoviba\Service\Money($container->get(Psr\Log\LoggerInterface::class)))
->register('uf', $mindicador)
->register('usd', $mindicador)
->register('ipc', $ine);
},
Predis\Client::class => function(ContainerInterface $container) {
@ -32,8 +34,14 @@ return [
},
Incoviba\Service\Cartola::class => function(ContainerInterface $container) {
return (new Incoviba\Service\Cartola(
$container->get(Psr\Log\LoggerInterface::class),
$container->get(Psr\Http\Message\StreamFactoryInterface::class),
$container->get(Incoviba\Common\Define\Contabilidad\Exporter::class)
$container->get(Incoviba\Common\Define\Contabilidad\Exporter::class),
$container->get(Incoviba\Repository\Inmobiliaria::class),
$container->get(Incoviba\Repository\Inmobiliaria\Cuenta::class),
$container->get(Incoviba\Repository\Movimiento::class),
$container->get(Incoviba\Service\Movimiento::class),
$container->get(Incoviba\Repository\Cartola::class)
))
->register('security', $container->get(Incoviba\Service\Cartola\Security::class))
->register('itau', $container->get(Incoviba\Service\Cartola\Itau::class))
@ -48,10 +56,26 @@ return [
},
Incoviba\Service\Contabilidad\Nubox::class => function(ContainerInterface $container) {
return new Incoviba\Service\Contabilidad\Nubox(
$container->get(Psr\Log\LoggerInterface::class),
$container->get(Incoviba\Repository\Nubox::class),
$container->get(Incoviba\Service\Redis::class),
new GuzzleHttp\Client(),
$container->get(Psr\Http\Message\RequestFactoryInterface::class),
$container->get('nubox')->get('url'));
},
Incoviba\Service\Informe::class => function(ContainerInterface $container) {
return (new Incoviba\Service\Informe(
$container->get(Psr\Log\LoggerInterface::class),
$container->get('folders')->get('informes'))
)
->register('xlsx', Incoviba\Service\Informe\Excel::class);
},
Incoviba\Service\Contabilidad\Informe\Tesoreria\Excel::class => function(ContainerInterface $container) {
return new Incoviba\Service\Contabilidad\Informe\Tesoreria\Excel(
$container->get(Psr\Log\LoggerInterface::class),
$container->get('folders')->get('informes'),
$container->get(Incoviba\Service\UF::class),
$container->get(Incoviba\Service\USD::class)
);
}
];

View File

@ -11,7 +11,9 @@ return [
'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)
'USD' => $container->get(Incoviba\Service\USD::class),
'IPC' => $container->get(Incoviba\Service\IPC::class),
'hoy' => new DateTimeImmutable()
];
if ($global_variables['login']->isIn()) {
$global_variables['user'] = $global_variables['login']->getUser();

View File

@ -2,51 +2,16 @@
namespace Incoviba\Controller\API;
use DateTimeImmutable;
use Incoviba\Common\Ideal\Controller;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Repository;
use Incoviba\Service;
class Contabilidad
class Contabilidad extends Controller
{
use withJson;
public function procesarCartola(ServerRequestInterface $request, ResponseInterface $response,
Repository\Inmobiliaria $inmobiliariaRepository,
Repository\Banco $bancoRepository,
Service\Cartola $cartolaService): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'input' => $body,
'movimientos' => []
];
try {
$inmobiliaria = $inmobiliariaRepository->fetchById($body['inmobiliaria']);
$banco = $bancoRepository->fetchById($body['banco']);
$mes = new DateTimeImmutable($body['mes']);
$file = $request->getUploadedFiles()['file'];
$output['movimientos'] = $cartolaService->process($inmobiliaria, $banco, $mes, $file);
} catch (EmptyResult) {}
return $this->withJson($response, $output);
}
public function exportarCartola(ServerRequestInterface $request, ResponseInterface $response,
Repository\Inmobiliaria $inmobiliariaRepository,
Repository\Banco $bancoRepository,
Service\Cartola $cartolaService): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'input' => $body,
'filename' => ''
];
try {
$inmobiliaria = $inmobiliariaRepository->fetchById($body['inmobiliaria']);
$banco = $bancoRepository->fetchById($body['banco']);
$mes = new DateTimeImmutable($body['mes']);
$output['filename'] = $cartolaService->export($inmobiliaria, $banco, $mes, json_decode($body['movimientos']));
} catch (EmptyResult) {}
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,99 @@
<?php
namespace Incoviba\Controller\API\Contabilidad;
use DateTimeInterface;
use DateTimeImmutable;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Incoviba\Common\Ideal\Controller;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Controller\API\withJson;
use Incoviba\Repository;
use Incoviba\Service;
class Cartolas extends Controller
{
use withJson;
public function procesar(ServerRequestInterface $request, ResponseInterface $response,
Repository\Inmobiliaria $inmobiliariaRepository,
Repository\Banco $bancoRepository,
Service\Cartola $cartolaService): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'input' => $body,
'movimientos' => []
];
try {
$inmobiliaria = $inmobiliariaRepository->fetchById($body['inmobiliaria']);
$banco = $bancoRepository->fetchById($body['banco']);
$mes = new DateTimeImmutable($body['mes']);
$file = $request->getUploadedFiles()['file'];
$output['movimientos'] = $cartolaService->process($inmobiliaria, $banco, $mes, $file);
} catch (EmptyResult) {}
return $this->withJson($response, $output);
}
public function exportar(ServerRequestInterface $request, ResponseInterface $response,
Repository\Inmobiliaria $inmobiliariaRepository,
Repository\Banco $bancoRepository,
Service\Cartola $cartolaService): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'input' => $body,
'filename' => ''
];
try {
$inmobiliaria = $inmobiliariaRepository->fetchById($body['inmobiliaria']);
$banco = $bancoRepository->fetchById($body['banco']);
$mes = new DateTimeImmutable($body['mes']);
$output['filename'] = $cartolaService->export($inmobiliaria, $banco, $mes, json_decode($body['movimientos']));
} catch (EmptyResult) {}
return $this->withJson($response, $output);
}
public function diaria(ServerRequestInterface $request, ResponseInterface $response,
Repository\Inmobiliaria\Cuenta $cuentaRepository,
Service\Cartola $cartolaService): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'input' => $body,
'cartolas' => []
];
$fields = json_decode($body['fields']);
foreach ($fields as $field) {
try {
$cuenta = $cuentaRepository->fetchById($body["cuenta_id{$field}"]);
$fecha = new DateTimeImmutable($body["fecha{$field}"]);
if (array_key_exists("manual{$field}", $body)) {
$file = json_decode($body["file{$field}"], JSON_OBJECT_AS_ARRAY);
$output['cartolas'][$field] = $cartolaService->diariaManual($cuenta, $fecha, $file);
continue;
}
$file = $request->getUploadedFiles()["file{$field}"];
$output['cartolas'][$field] = $cartolaService->diaria($cuenta, $fecha, $file);
} catch (EmptyResult $exception) {
$this->logger->debug($exception);
}
}
return $this->withJson($response, $output);
}
public function ayer(ServerRequestInterface $request, ResponseInterface $response,
Repository\Inmobiliaria\Cuenta $cuentaRepository,
Repository\Cartola $cartolaRepository): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'input' => $body,
'cartola' => []
];
try {
$cuenta = $cuentaRepository->fetchById($body['cuenta_id']);
$fecha = new DateTimeImmutable($body['fecha']);
$output['cartola'] = $cartolaRepository->fetchByCuentaAndFecha($cuenta->id, $fecha);
} catch (EmptyResult) {}
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace Incoviba\Controller\API\Contabilidad;
use DateTimeImmutable;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Controller\API\withJson;
use Incoviba\Repository;
class Depositos extends Ideal\Controller
{
use withJson;
public function inmobiliaria(ServerRequestInterface $request, ResponseInterface $response,
Repository\Inmobiliaria $inmobiliariaRepository,
Repository\Banco $bancoRepository,
Repository\Inmobiliaria\Cuenta $cuentaRepository,
Repository\Deposito $dapRepository,
int $inmobiliaria_rut): ResponseInterface
{
$output = [
'inmobiliaria_rut' => $inmobiliaria_rut,
'depositos' => []
];
try {
$inmobiliaria = $inmobiliariaRepository->fetchById($inmobiliaria_rut);
$cuentas = $cuentaRepository->fetchByInmobiliaria($inmobiliaria->rut);
foreach ($cuentas as $cuenta) {
$output['depositos'] = $dapRepository->fetchByCuenta($cuenta->id);
}
} catch (Implement\Exception\EmptyResult) {}
return $this->withJson($response, $output);
}
public function add(ServerRequestInterface $request, ResponseInterface $response,
Repository\Inmobiliaria $inmobiliariaRepository, Repository\Banco $bancoRepository,
Repository\Inmobiliaria\Cuenta $cuentaRepository,
Repository\Deposito $dapRepository): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'input' => $body,
'status' => false
];
try {
$inmobiliaria = $inmobiliariaRepository->fetchById($body['inmobiliaria_rut']);
$banco = $bancoRepository->fetchById($body['banco_id']);
$cuenta = $cuentaRepository->fetchByInmobiliariaAndBanco($inmobiliaria->rut, $banco->id);
$data = [
'id' => $body['id'],
'cuenta_id' => $cuenta->id,
'capital' => $body['capital'],
'futuro' => $body['futuro'],
'inicio' => (new DateTimeImmutable($body['inicio']))->format('Y-m-d'),
'termino' => (new DateTimeImmutable($body['termino']))->format('Y-m-d')
];
try {
$dapRepository->fetchById($body['id']);
} catch (Implement\Exception\EmptyResult) {
$dap = $dapRepository->create($data);
$dapRepository->save($dap);
}
$output['status'] = true;
} catch (Implement\Exception\EmptyResult) {}
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace Incoviba\Controller\API\Contabilidad;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Controller\API\withJson;
use Incoviba\Common\Ideal;
use Incoviba\Repository;
use Incoviba\Service;
class Movimientos extends Ideal\Controller
{
use withJson;
public function detalles(ServerRequestInterface $request, ResponseInterface $response,
Service\Movimiento $movimientoService,
Repository\CentroCosto $centroCostoRepository, int $movimiento_id): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'movimiento_id' => $movimiento_id,
'input' => $body,
'status' => false,
'movimiento' => null,
'centro' => null,
'detalle' => ''
];
try {
$movimiento = $movimientoService->getById($movimiento_id);
$output['movimiento'] = $movimiento;
$data = [];
if (isset($body['centro_id'])) {
$centro = $centroCostoRepository->fetchById($body['centro_id']);
$data['centro_costo_id'] = $centro->id;
}
if (isset($body['detalle'])) {
$data['detalle'] = $body['detalle'];
}
$movimientoService->setDetalles($movimiento, $data);
if (isset($body['centro_id'])) {
$output['centro'] = $centro;
}
if (isset($body['detalle'])) {
$output['detalle'] = $body['detalle'];
}
} catch (EmptyResult) {}
return $this->withJson($response, $output);
}
}

View File

@ -3,11 +3,13 @@ namespace Incoviba\Controller\API;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Controller\withRedis;
use Incoviba\Common\Implement\Exception;
use Incoviba\Service;
class Search
{
use withJson;
use withJson, withRedis;
public function query(ServerRequestInterface $request, ResponseInterface $response,
Service\Search $service): ResponseInterface
@ -17,4 +19,155 @@ class Search
$output = compact('results');
return $this->withJson($response, $output);
}
public function unidad(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
Service\Venta\Unidad $unidadService, int $unidad_id): ResponseInterface
{
$output = [
'unidad_id' => $unidad_id,
'unidad' => null
];
$redisKey = "search:unidad:{$unidad_id}";
try {
$output['unidad'] = $this->fetchRedis($redisService, $redisKey);
} catch (Exception\EmptyRedis) {
try {
$unidad = $unidadService->getByIdForSearch($unidad_id);
$output['unidad'] = [
'id' => $unidad['id'],
'descripcion' => $unidad['descripcion'],
'proyecto_tipo_unidad' => [
'proyecto' => [
'id' => $unidad['proyecto_id'],
'descripcion' => $unidad['proyecto_descripcion']
],
'tipo_unidad' => [
'descripcion' => $unidad['tipo_unidad_descripcion']
],
'superficie' => $unidad['superficie']
],
'current_precio' => [
'valor' => $unidad['precio']
]
];
$this->saveRedis($redisService, $redisKey, $output['unidad']);
} catch (Exception\EmptyResult) {}
}
return $this->withJson($response, $output);
}
public function unidades(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
Service\Venta\Unidad $unidadService): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'input' => $body,
'unidades' => []
];
$unidades = explode(',', $body['unidades']);
foreach ($unidades as $unidad_id) {
$redisKey = "search:unidad:{$unidad_id}";
try {
$output['unidades'] []= $this->fetchRedis($redisService, $redisKey);
} catch (Exception\EmptyRedis) {
try {
$unidad = $unidadService->getByIdForSearch($unidad_id);
$unidad = [
'id' => $unidad['id'],
'descripcion' => $unidad['descripcion'],
'proyecto_tipo_unidad' => [
'proyecto' => [
'id' => $unidad['proyecto_id'],
'descripcion' => $unidad['proyecto_descripcion']
],
'tipo_unidad' => [
'descripcion' => $unidad['tipo_unidad_descripcion']
],
'superficie' => $unidad['superficie']
],
'current_precio' => [
'valor' => $unidad['precio']
]
];
$output['unidades'] []= $unidad;
$this->saveRedis($redisService, $redisKey, $unidad);
} catch (Exception\EmptyResult) {}
}
}
return $this->withJson($response, $output);
}
public function venta(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
Service\Venta $ventaService, int $venta_id): ResponseInterface
{
$output = [
'venta_id' => $venta_id,
'venta' => null
];
$redisKey = "search:venta:{$venta_id}";
try {
$output['venta'] = $this->fetchRedis($redisService, $redisKey);
} catch (Exception\EmptyRedis) {
try {
$venta = $ventaService->getById($venta_id);
/*$output['venta'] = [
'id' => $venta->id,
''
];*/
$output['venta'] = $venta;
$this->saveRedis($redisService, $redisKey, $output['venta']);
} catch (Exception\EmptyResult) {}
}
return $this->withJson($response, $output);
}
public function ventas(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
Service\Venta $ventaService): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'input' => $body,
'ventas' => []
];
$ventas = explode(',', $body['ventas']);
foreach ($ventas as $venta_id) {
$redisKey = "search:venta:{$venta_id}";
try {
$output['ventas'] []= $this->fetchRedis($redisService, $redisKey);
} catch (Exception\EmptyRedis) {
try {
$venta = $ventaService->getByIdForSearch($venta_id);
$venta = [
'id' => $venta['id'],
'proyecto' => [
'id' => $venta['proyecto_id'],
'descripcion' => $venta['proyecto_descripcion']
],
'propietario' => [
'nombre_completo' => $venta['propietario']
],
'propiedad' => [
'unidades' => [
[
'descripcion' => $venta['unidad_descripcion'],
'proyecto_tipo_unidad' => [
'tipo_unidad' => [
'descripcion' => $venta['tipo_unidad_descripcion']
],
'superficie' => $venta['superficie']
]
]
]
],
'fecha' => $venta['fecha'],
'current_estado' => [
'tipo_estado_venta' => [
'activa' => $venta['activa']
]
],
'valor' => $venta['valor']
];
$output['ventas'] []= $venta;
$this->saveRedis($redisService, $redisKey, json_encode($venta));
} catch (Exception\EmptyResult) {}
}
}
return $this->withJson($response, $output);
}
}

View File

@ -74,6 +74,32 @@ class Ventas extends Controller
}
return $this->withJson($response, $output);
}
public function getMany(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
Service\Venta $service): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'input' => $body,
'ventas' => []
];
$ventas = explode(',', $body['ventas']);
foreach ($ventas as $venta_id) {
$redisKey = "venta:{$venta_id}";
try {
$venta = $this->fetchRedis($redisService, $redisKey);
$output['ventas'] []= $venta;
} catch (EmptyRedis) {
try {
$venta = $service->getById($venta_id);
$output['ventas'] []= $venta;
$this->saveRedis($redisService, $redisKey, $venta);
} catch (EmptyResult $exception) {
$this->logger->notice($exception);
}
}
}
return $this->withJson($response, $output);
}
public function porFirmar(ServerRequestInterface $request, ResponseInterface $response, Service\Venta $ventaService, Service\Redis $redisService): ResponseInterface
{
$body = $request->getBody();

View File

@ -0,0 +1,31 @@
<?php
namespace Incoviba\Controller\API\Ventas;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Ideal\Controller;
use Incoviba\Controller\API\withJson;
use Incoviba\Service;
class Creditos extends Controller
{
use withJson;
public function edit(ServerRequestInterface $request, ResponseInterface $response, Service\Venta $ventaService,
Service\Venta\Credito $creditoService, int $venta_id): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'input' => $body,
'credito' => null,
'status' => false
];
try {
$venta = $ventaService->getById($venta_id);
$output['credito'] = $creditoService->edit($venta->formaPago()->credito, $body);
$output['status'] = true;
} catch (EmptyResult) {}
return $this->withJson($response, $output);
}
}

View File

@ -13,6 +13,50 @@ class Escrituras
{
use withJson;
public function add(ServerRequestInterface $request, ResponseInterface $response,
Repository\Venta $ventaRepository, Service\Venta $ventaService,
Repository\Venta\Escritura $escrituraRepository, Service\Venta\Pago $pagoService,
Service\UF $ufService, int $venta_id): ResponseInterface
{
$body = $request->getParsedBody();
$output = [
'venta_id' => $venta_id,
'input' => $body,
'status' => false
];
try {
$venta = $ventaService->getById($venta_id);
if (isset($venta->formaPago()->escritura)) {
throw new EmptyResult('');
}
$fecha = new DateTimeImmutable($body['fecha']);
$uf = $ufService->get($fecha);
$valor = $body['valor'];
if (str_contains($valor, ',')) {
$valor = str_replace(['.', ','], ['', '.'], $valor);
}
$valor = ((float) $valor) * (($body['uf']) ? $uf : 1);
$data = [
'fecha' => $fecha->format('Y-m-d'),
'valor' => $valor,
'banco' => $body['banco'],
'tipo' => $body['tipo'],
'uf' => $uf
];
$pago = $pagoService->add($data);
$data = [
'valor' => $valor,
'fecha' => $fecha->format('Y-m-d'),
'uf' => $uf,
'pago' => $pago->id
];
$escritura = $escrituraRepository->create($data);
$escrituraRepository->save($escritura);
$ventaRepository->edit($venta, ['escritura' => $escritura->id]);
$output['status'] = true;
} catch (EmptyResult) {}
return $this->withJson($response, $output);
}
public function edit(ServerRequestInterface $request, ResponseInterface $response,
Service\Venta $ventaService, Repository\Venta\EstadoVenta $estadoVentaRepository,
int $venta_id): ResponseInterface

View File

@ -0,0 +1,76 @@
<?php
namespace Incoviba\Controller;
use DateTimeImmutable;
use DateInterval;
use Incoviba\Common\Ideal\Controller;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Common\Implement\Exception\{EmptyResult, EmptyRedis};
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
class Contabilidad extends Controller
{
use withRedis;
public function diaria(ServerRequestInterface $request, ResponseInterface $response, View $view,
Service\Redis $redisService,
Repository\Inmobiliaria $inmobiliariaRepository,
Repository\CentroCosto $centroCostoRepository): ResponseInterface
{
$redisKey = 'inmobiliarias';
$inmobiliarias = [];
try {
$inmobiliarias = $this->fetchRedis($redisService, $redisKey);
} catch (EmptyRedis) {
try {
$inmobiliarias = $inmobiliariaRepository->fetchAll();
$this->saveRedis($redisService, $redisKey, $inmobiliarias, 30 * 24 * 60 * 60);
} catch (EmptyResult) {}
}
$centrosCostos = $centroCostoRepository->fetchAll();
return $view->render($response, 'contabilidad.cartolas.diaria', compact('inmobiliarias', 'centrosCostos'));
}
public function depositos(ServerRequestInterface $request, ResponseInterface $response, View $view,
Service\Redis $redisService,
Repository\Inmobiliaria $inmobiliariaRepository,
Repository\Deposito $dapRepository): ResponseInterface
{
$redisKey = 'inmobiliarias';
$inmobiliarias = [];
try {
$inmobiliarias = $this->fetchRedis($redisService, $redisKey);
} catch (EmptyRedis) {
try {
$inmobiliarias = $inmobiliariaRepository->fetchAll();
$this->saveRedis($redisService, $redisKey, $inmobiliarias, 30 * 24 * 60 * 60);
} catch (EmptyResult) {}
}
$depositos = [];
try {
$depositos = $dapRepository->fetchAll();
} catch (EmptyResult) {}
$fecha = new DateTimeImmutable('today');
$activos = array_filter($depositos, function(Model\Deposito $deposito) use ($fecha) {
return $deposito->termino >= $fecha;
});
$mes = $fecha->sub(new DateInterval('P1M'));
$vencidos = array_filter($depositos, function(Model\Deposito $deposito) use ($fecha, $mes) {
return $deposito->termino < $fecha and $deposito->termino >= $mes;
});
return $view->render($response, 'contabilidad.depositos', compact('inmobiliarias', 'activos', 'vencidos'));
}
public function tesoreria(ServerRequestInterface $request, ResponseInterface $response, View $view,
Service\Contabilidad\Informe\Tesoreria $contabilidadService,
string $fecha = 'today'): ResponseInterface
{
$fecha = new DateTimeImmutable($fecha);
$anterior = $contabilidadService->getAnterior($fecha);
$informes = $contabilidadService->build($fecha);
$filename = "Informe de Tesorería {$fecha->format('d.m.Y')}";
return $view->render($response, 'contabilidad.informes.tesoreria', compact('fecha', 'anterior', 'informes', 'filename'));
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace Incoviba\Controller\Contabilidad;
use DateTimeImmutable;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Ideal;
use Incoviba\Service;
class Informes extends Ideal\Controller
{
public function tesoreria(ServerRequestInterface $request, ResponseInterface $response, Service\Contabilidad\Informe\Tesoreria $tesoreriaService, string $fecha): ResponseInterface
{
$fecha = new DateTimeImmutable($fecha);
$tesoreriaService->buildInforme($fecha, $tesoreriaService->build($fecha));
$response->getBody()->write(file_get_contents('php://output'));
return $response;
}
}

View File

@ -13,7 +13,7 @@ class Login
public function form(ServerRequestInterface $request, ResponseInterface $response, View $view, Service\Login $service): ResponseInterface
{
if ($service->isIn()) {
return $response->withStatus(301)->withHeader('Location', $view->get('urls')->base);
return $response->withStatus(302)->withHeader('Location', $view->get('urls')->base);
}
return $view->render($response, 'login.form');
}

View File

@ -32,8 +32,13 @@ class Ventas
public function show(ServerRequestInterface $request, ResponseInterface $response, View $view,
Service\Venta $service, int $venta_id): ResponseInterface
{
$venta = $service->getById($venta_id);
return $view->render($response, 'ventas.show', compact('venta'));
try {
$venta = $service->getById($venta_id);
return $view->render($response, 'ventas.show', compact('venta'));
} catch (EmptyResult) {
$response = $response->withStatus(404);
return $view->render($response, 'not_found');
}
}
public function showUnidad(ServerRequestInterface $request, ResponseInterface $response, View $view,
Service\Venta $service, string $proyecto_nombre, int $unidad_descripcion): ResponseInterface

View File

@ -0,0 +1,20 @@
<?php
namespace Incoviba\Controller\Ventas;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Common\Ideal\Controller;
use Incoviba\Repository;
class Creditos extends Controller
{
public function show(ServerRequestInterface $request, ResponseInterface $response, View $view,
Repository\Venta $ventaRepository, Repository\Banco $bancoRepository,
int $venta_id): ResponseInterface
{
$venta = $ventaRepository->fetchById($venta_id);
$bancos = $bancoRepository->fetchAll('nombre');
return $view->render($response, 'ventas.creditos', compact('venta', 'bancos'));
}
}

View File

@ -4,6 +4,7 @@ namespace Incoviba\Controller\Ventas;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Repository;
use Incoviba\Service;
class Escrituras
@ -20,4 +21,12 @@ class Escrituras
$venta = $ventaService->getById($venta_id);
return $view->render($response, 'ventas.escrituras.informe', compact('venta'));
}
public function add(ServerRequestInterface $request, ResponseInterface $response, View $view,
Service\Venta $ventaService, Repository\Banco $bancoRepository,
int $venta_id): ResponseInterface
{
$venta = $ventaService->getById($venta_id);
$bancos = $bancoRepository->fetchAll('nombre');
return $view->render($response, 'ventas.escrituras.add', compact('venta', 'bancos'));
}
}

View File

@ -6,8 +6,8 @@ use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Incoviba\Service;
use Psr\Log\LoggerInterface;
use Incoviba\Service;
class Authentication
{
@ -27,7 +27,11 @@ class Authentication
$response = $this->responseFactory->createResponse(301, 'Not logged in')
->withHeader('Referer', (string) $request->getUri())
->withHeader('X-Redirected-URI', (string) $request->getUri());
return $this->view->render($response, 'login.form', ['redirect_uri' => (string) $request->getUri()]);
$url = "{$request->getUri()}";
if (str_ends_with($url, '/login')) {
$url = str_replace('/login', '', $url);
}
return $this->view->render($response, 'login.form', ['redirect_uri' => $url]);
}
protected function isValid(ServerRequestInterface $request): bool

26
app/src/Model/Cartola.php Normal file
View File

@ -0,0 +1,26 @@
<?php
namespace Incoviba\Model;
use DateTimeInterface;
use Incoviba\Common\Ideal;
class Cartola extends Ideal\Model
{
public Inmobiliaria\Cuenta $cuenta;
public DateTimeInterface $fecha;
public int $cargos = 0;
public int $abonos = 0;
public int $saldo = 0;
public function jsonSerialize(): mixed
{
return array_merge(parent::jsonSerialize(), [
'cuenta_id' => $this->cuenta->id,
'fecha' => $this->fecha->format('Y-m-d'),
'cargos' => $this->cargos,
'abonos' => $this->abonos,
'saldo' => $this->saldo
]);
}
}

View File

@ -13,7 +13,7 @@ class CentroCosto extends Ideal\Model
public function jsonSerialize(): mixed
{
return array_map(parent::jsonSerialize(), [
return array_merge(parent::jsonSerialize(), [
'tipo_centro' => $this->tipoCentro,
'categoria' => $this->categoria,
'tipo_cuenta' => $this->tipoCuenta,

View File

@ -0,0 +1,36 @@
<?php
namespace Incoviba\Model;
use DateTimeInterface;
use Incoviba\Common\Ideal;
class Deposito extends Ideal\Model
{
public Inmobiliaria\Cuenta $cuenta;
public int $capital;
public int $futuro;
public DateTimeInterface $inicio;
public DateTimeInterface $termino;
public function plazo(): int
{
return $this->termino->diff($this->inicio)->days;
}
public function tasa(): float
{
return ($this->futuro - $this->capital) / $this->capital;
}
public function jsonSerialize(): mixed
{
return array_merge(parent::jsonSerialize(), [
'cuenta_id' => $this->cuenta->id,
'capital' => $this->capital,
'futuro' => $this->futuro,
'inicio' => $this->inicio->format('Y-m-d'),
'termino' => $this->termino->format('Y-m-d'),
'plazo' => $this->plazo(),
'tasa' => $this->tasa()
]);
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace Incoviba\Model;
use DateTimeInterface;
use Incoviba\Common\Ideal;
use Incoviba\Model\Movimiento\Detalle;
class Movimiento extends Ideal\Model
{
public Inmobiliaria\Cuenta $cuenta;
public DateTimeInterface $fecha;
public string $glosa;
public string $documento;
public int $cargo;
public int $abono;
public int $saldo;
protected ?Detalle $detalles;
public function getDetalles(): ?Detalle
{
if (!isset($this->detalles)) {
$this->detalles = $this->runFactory('detalles');
}
return $this->detalles;
}
public function jsonSerialize(): mixed
{
return array_merge(parent::jsonSerialize(), [
'cuenta_id' => $this->cuenta->id,
'fecha' => $this->fecha->format('Y-m-d'),
'glosa' => $this->glosa,
'documento' => $this->documento,
'cargo' => $this->cargo,
'abono' => $this->abono,
'saldo' => $this->saldo,
'detalles' => $this->getDetalles() ?? null
]);
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace Incoviba\Model\Movimiento;
use Incoviba\Common\Ideal;
use Incoviba\Model;
class Detalle extends Ideal\Model
{
public Model\Movimiento $movimiento;
public ?Model\CentroCosto $centroCosto;
public ?string $detalle;
public function jsonSerialize(): mixed
{
return [
'movimiento_id' => $this->movimiento->id,
'centro_costo' => $this->centroCosto,
'detalle' => $this->detalle
];
}
}

View File

@ -4,13 +4,14 @@ namespace Incoviba\Model;
use DateTimeInterface;
use Incoviba\Common\Ideal;
use Incoviba\Controller\Ventas;
use Incoviba\Model\Venta\FormaPago;
use Incoviba\Model\Venta\Pago;
class Venta extends Ideal\Model
{
protected Venta\Propietario $propietario;
protected Venta\Propiedad $propiedad;
protected Venta\FormaPago $formaPago;
protected ?Venta\FormaPago $formaPago;
public DateTimeInterface $fecha;
public DateTimeInterface $fechaIngreso;
public float $valor;
@ -36,7 +37,7 @@ class Venta extends Ideal\Model
}
return $this->propiedad;
}
public function formaPago(): Venta\FormaPago
public function formaPago(): ?Venta\FormaPago
{
if (!isset($this->formaPago)) {
$this->formaPago = $this->runFactory('formaPago');
@ -104,7 +105,7 @@ class Venta extends Ideal\Model
return array_merge(parent::jsonSerialize(), [
'propietario' => $this->propietario(),
'propiedad' => $this->propiedad(),
'forma_pago' => $this->formaPago()->ids(),
'forma_pago' => $this->formaPago()?->ids(),
'fecha' => $this->fecha->format('Y-m-d'),
'fecha_ingreso' => $this->fechaIngreso->format('Y-m-d'),
'valor' => $this->valor,

View File

@ -5,12 +5,12 @@ use JsonSerializable;
class FormaPago implements JsonSerializable
{
public ?Pie $pie;
public ?Escritura $escritura;
public ?BonoPie $bonoPie;
public ?Subsidio $subsidio;
public ?Credito $credito;
public ?Pago $devolucion;
public ?Pie $pie = null;
public ?Escritura $escritura = null;
public ?BonoPie $bonoPie = null;
public ?Subsidio $subsidio = null;
public ?Credito $credito = null;
public ?Pago $devolucion = null;
public function anticipo(string $moneda = Pago::UF): float
{
@ -26,6 +26,17 @@ class FormaPago implements JsonSerializable
}
return $sum;
}
public function prometido(string $moneda = Pago::UF): float
{
$sum = 0;
if (isset($this->pie)) {
$sum += $this->pie->valor($moneda);
}
if (isset($this->escritura)) {
$sum += $this->escritura->pago->valor($moneda);
}
return $sum;
}
public function total(string $moneda = Pago::UF): float
{
$sum = $this->anticipo($moneda);

View File

@ -14,11 +14,11 @@ class Pie extends Model
public ?Pie $asociado;
public ?Pago $reajuste;
public array $cuotasArray;
public array $cuotasArray = [];
public function cuotas(bool $pagadas = false, bool $vigentes = false): array
{
if ($this->asociado !== null) {
return $this->asociado->cuotas($pagadas);
return $this->asociado->cuotas($pagadas, $vigentes);
}
if (!$pagadas and !$vigentes) {
return $this->cuotasArray;
@ -33,14 +33,19 @@ class Pie extends Model
});
}
public function valor(string $moneda = Pago::UF): float
{
$proporcion = $this->proporcion();
if ($this->asociado !== null) {
return $this->asociado->valor($moneda) * $proporcion;
}
return array_reduce($this->cuotas(), function(float $sum, Cuota $cuota) use ($moneda) {
return $sum + $cuota->pago->valor($moneda);
}, 0) * $proporcion;
}
public function pagado(string $moneda = Pago::UF): float
{
$proporcion = 1;
if (count($this->asociados()) > 0) {
$proporcion = $this->valor / ((($this->asociado) ? $this->asociado->valor : $this->valor) + array_reduce($this->asociados(), function(float $sum, Pie $pie) {
return $sum + $pie->valor;
}, 0));
}
$proporcion = $this->proporcion();
if ($this->asociado !== null) {
return $this->asociado->pagado($moneda) * $proporcion;
}
@ -49,6 +54,17 @@ class Pie extends Model
return $sum + $cuota->pago->valor($moneda);
}, 0) * $proporcion;
}
protected function proporcion(): float
{
$proporcion = 1;
if (count($this->asociados()) > 0) {
$proporcion = $this->valor / ((($this->asociado) ? $this->asociado->valor : $this->valor) + array_reduce($this->asociados(), function(float $sum, Pie $pie) {
return $sum + $pie->valor;
}, 0));
}
return $proporcion;
}
public ?array $asociados;
public function asociados(): array
{

View File

@ -0,0 +1,68 @@
<?php
namespace Incoviba\Repository;
use DateTimeInterface;
use Incoviba\Common\Define;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Model;
use Incoviba\Repository;
class Cartola extends Ideal\Repository
{
public function __construct(Define\Connection $connection, protected Repository\Inmobiliaria\Cuenta $cuentaRepository)
{
parent::__construct($connection);
$this->setTable('cartolas');
}
public function create(?array $data = null): Model\Cartola
{
$map = (new Implement\Repository\MapperParser(['cargos', 'abonos', 'saldo']))
->register('fecha', new Implement\Repository\Mapper\DateTime('fecha'))
->register('cuenta_id', (new Implement\Repository\Mapper())
->setProperty('cuenta')
->setFunction(function($data) {
return $this->cuentaRepository->fetchById($data['cuenta_id']);
}));
return $this->parseData(new Model\Cartola(), $data, $map);
}
public function save(Define\Model $model): Model\Cartola
{
$model->id = $this->saveNew([
'cuenta_id',
'fecha',
'cargos',
'abonos',
'saldo'
], [
$model->cuenta->id,
$model->fecha->format('Y-m-d'),
$model->cargos,
$model->abonos,
$model->saldo
]);
return $model;
}
public function edit(Define\Model $model, array $new_data): Model\Cartola
{
return $this->update($model, ['cuenta_id', 'fecha', 'cargos', 'abonos', 'saldo'], $new_data);
}
public function fetchByFecha(DateTimeInterface $fecha): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('fecha = ?');
return $this->fetchMany($query, [$fecha->format('Y-m-d')]);
}
public function fetchByCuentaAndFecha(int $cuenta_id, DateTimeInterface $fecha): Model\Cartola
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('cuenta_id = ? AND fecha = ?');
return $this->fetchOne($query, [$cuenta_id, $fecha->format('Y-m-d')]);
}
}

View File

@ -0,0 +1,64 @@
<?php
namespace Incoviba\Repository;
use DateTimeImmutable;
use Incoviba\Common\Define;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Repository;
use Incoviba\Model;
class Deposito extends Ideal\Repository
{
public function __construct(Define\Connection $connection, protected Repository\Inmobiliaria\Cuenta $cuentaRepository)
{
parent::__construct($connection);
$this->setTable('depositos');
}
public function create(?array $data = null): Model\Deposito
{
$map = (new Implement\Repository\MapperParser(['id', 'capital', 'futuro']))
->register('cuenta_id', (new Implement\Repository\Mapper())
->setProperty('cuenta')
->setFunction(function(array $data) {
return $this->cuentaRepository->fetchById($data['cuenta_id']);
}))
->register('inicio', new Implement\Repository\Mapper\DateTime('inicio'))
->register('termino', new Implement\Repository\Mapper\DateTime('termino'));
return $this->parseData(new Model\Deposito(), $data, $map);
}
public function save(Define\Model $model): Model\Deposito
{
$this->saveNew([
'id', 'cuenta_id', 'capital', 'futuro', 'inicio', 'termino'
], [
$model->id, $model->cuenta->id, $model->capital, $model->futuro,
$model->inicio->format('Y-m-d'), $model->termino->format('Y-m-d')
]);
return $model;
}
public function edit(Define\Model $model, array $new_data): Model\Deposito
{
return $this->update($model, ['cuenta_id', 'capital', 'futuro', 'inicio', 'termino'], $new_data);
}
public function fetchByCuenta(int $cuenta_id): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('cuenta_id = ?');
return $this->fetchMany($query, [$cuenta_id]);
}
public function fetchAllActive(): array
{
$fecha = new DateTimeImmutable();
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('inicio <= ? AND termino >= ?');
return $this->fetchMany($query, [$fecha->format('Y-m-d'), $fecha->format('Y-m-d')]);
}
}

View File

@ -6,6 +6,7 @@ use Incoviba\Common\Ideal;
use Incoviba\Repository;
use Incoviba\Model;
use Incoviba\Common\Implement;
use PhpParser\Node\Expr\BinaryOp\Mod;
class Cuenta extends Ideal\Repository
{
@ -49,4 +50,12 @@ class Cuenta extends Ideal\Repository
->where('inmobiliaria = ?');
return $this->fetchMany($query, [$inmobiliaria_rut]);
}
public function fetchByInmobiliariaAndBanco(int $inmobiliaria_rut, int $banco_id): Model\Inmobiliaria\Cuenta
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('inmobiliaria = ? AND banco = ?');
return $this->fetchOne($query, [$inmobiliaria_rut, $banco_id]);
}
}

View File

@ -0,0 +1,72 @@
<?php
namespace Incoviba\Repository;
use DateTimeInterface;
use Incoviba\Common\Define;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Model;
class Movimiento extends Ideal\Repository
{
public function __construct(Define\Connection $connection, protected Inmobiliaria\Cuenta $cuentaRepository)
{
parent::__construct($connection);
$this->setTable('movimientos');
}
public function create(?array $data = null): Model\Movimiento
{
$map = (new Implement\Repository\MapperParser(['cargo', 'abono', 'saldo', 'glosa', 'documento']))
->register('fecha', new Implement\Repository\Mapper\DateTime('fecha'))
->register('cuenta_id', (new Implement\Repository\Mapper())
->setProperty('cuenta')
->setFunction(function($data) {
return $this->cuentaRepository->fetchById($data['cuenta_id']);
})
);
return $this->parseData(new Model\Movimiento(), $data, $map);
}
public function save(Define\Model $model): Model\Movimiento
{
$model->id = $this->saveNew([
'cuenta_id',
'fecha',
'glosa',
'documento',
'cargo',
'abono',
'saldo'
], [
$model->cuenta->id,
$model->fecha->format('Y-m-d'),
$model->glosa,
$model->documento,
$model->cargo,
$model->abono,
$model->saldo
]);
return $model;
}
public function edit(Define\Model $model, array $new_data): Model\Movimiento
{
return $this->update($model, ['cuenta_id', 'fecha', 'glosa', 'documento', 'cargo', 'abono', 'saldo'], $new_data);
}
public function fetchByCuentaAndFecha(int $cuenta_id, DateTimeInterface $fecha): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('cuenta_id = ? AND fecha = ?');
return $this->fetchMany($query, [$cuenta_id, $fecha->format('Y-m-d')]);
}
public function fetchByCuentaAndFechaAndCargoAndAbonoAndSaldo(int $cuenta_id, DateTimeInterface $fecha, int $cargo, int $abono, int $saldo): Model\Movimiento
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('cuenta_id = ? AND fecha = ? AND cargo = ? AND abono = ? AND saldo = ?');
return $this->fetchOne($query, [$cuenta_id, $fecha->format('Y-m-d'), $cargo, $abono, $saldo]);
}
}

View File

@ -0,0 +1,60 @@
<?php
namespace Incoviba\Repository\Movimiento;
use Incoviba\Common\Define;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Model;
use Incoviba\Repository;
class Detalle extends Ideal\Repository
{
public function __construct(Define\Connection $connection, protected Repository\Movimiento $movimientoRepository,
protected Repository\CentroCosto $centroCostoRepository)
{
parent::__construct($connection);
$this->setTable('movimientos_detalles');
}
public function create(?array $data = null): Model\Movimiento\Detalle
{
$map = (new Implement\Repository\MapperParser(['detalle']))
->register('movimiento_id', (new Implement\Repository\Mapper())
->setProperty('movimiento')
->setFunction(function(array $data) {
return $this->movimientoRepository->fetchById($data['movimiento_id']);
}))
->register('centro_costo_id', (new Implement\Repository\Mapper())
->setProperty('centroCosto')
->setFunction(function(array $data) {
return $this->centroCostoRepository->fetchById($data['centro_costo_id']);
}));
return $this->parseData(new Model\Movimiento\Detalle(), $data, $map);
}
public function save(Define\Model $model): Model\Movimiento\Detalle
{
$this->saveNew(
['movimiento_id', 'centro_costo_id', 'detalle'],
[$model->movimiento->id, $model->centroCosto->id, $model->detalle]
);
return $model;
}
public function edit(Define\Model $model, array $new_data): Model\Movimiento\Detalle
{
return $this->update($model, ['movimiento_id', 'centro_costo_id', 'detalle'], $new_data);
}
public function fetchByMovimiento(int $movimiento_id): Model\Movimiento\Detalle
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('movimiento_id = ?');
return $this->fetchOne($query, [$movimiento_id]);
}
protected function getKey(): string
{
return 'movimiento_id';
}
}

View File

@ -38,7 +38,7 @@ class Venta extends Ideal\Repository
->setFactory((new Implement\Repository\Factory())
->setCallable([$this->propiedadRepository, 'fetchById'])
->setArgs([$data['propiedad']])))
->register('pie', (new Implement\Repository\Mapper())
/*->register('pie', (new Implement\Repository\Mapper())
->setProperty('formaPago')
->setFactory((new Implement\Repository\Factory())
->setCallable(function($repositories, $data) {
@ -84,7 +84,7 @@ class Venta extends Ideal\Repository
'escrituraRepository' => $this->escrituraRepository,
'subsidioRepository' => $this->subsidioRepository,
'pagoService' => $this->pagoService
], $data])))
], $data])))*/
/*->register('escriturado', (new Implement\Repository\Mapper())
->setFunction(function($data) {
return $data['escritura'] !== null;
@ -159,15 +159,6 @@ class Venta extends Ideal\Repository
->joined('JOIN tipo_estado_venta tev ON tev.id = ev.estado')
->where('ptu.proyecto = ? AND tev.activa')
->group('a.id');
/*$query = "SELECT a.*
FROM `{$this->getTable()}` a
JOIN `propiedad_unidad` pu ON pu.`propiedad` = a.`propiedad`
JOIN `unidad` ON `unidad`.`id` = pu.`unidad` AND pu.`principal` = 1
JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = `unidad`.`pt`
JOIN (SELECT e1.* FROM `estado_venta` e1 JOIN (SELECT MAX(`id`) AS 'id', `venta` FROM `estado_venta` GROUP BY `venta`) e0 ON e0.`id` = e1.`id`) ev ON ev.`venta` = a.`id`
JOIN `tipo_estado_venta` tev ON tev.`id` = ev.`estado`
WHERE ptu.`proyecto` = ? AND tev.`activa`
GROUP BY a.`id`";*/
return $this->fetchMany($query, [$proyecto_id]);
}
public function fetchIdsByProyecto(int $proyecto_id): array
@ -240,6 +231,15 @@ GROUP BY a.`id`";*/
->where('`unidad`.`descripcion` LIKE ? AND tu.`descripcion` = ?');
return $this->fetchMany($query, [$unidad, $tipo]);
}
public function fetchByUnidadId(int $unidad_id): Model\Venta
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('JOIN propiedad_unidad pu ON pu.propiedad = a.propiedad')
->where('pu.unidad = ?');
return $this->fetchOne($query, [$unidad_id]);
}
public function fetchIdsByUnidad(string $unidad, string $tipo): array
{
$query = $this->connection->getQueryBuilder()
@ -295,8 +295,10 @@ GROUP BY a.`id`";*/
->joined('JOIN `propietario` ON `propietario`.`rut` = a.`propietario`')
->where("CONCAT_WS('-', `propietario`.`rut`, `propietario`.`dv`) LIKE :propietario OR `propietario`.`nombres` LIKE :propietario
OR `propietario`.`apellido_paterno` LIKE :propietario OR `propietario`.`apellido_materno` LIKE :propietario
OR CONCAT_WS(' ', `propietario`.`nombres`, `propietario`.`apellido_paterno`, `propietario`.`apellido_materno`) LIKE :propietario");
return $this->fetchIds($query, [':propietario' => "%{$propietario}%"]);
OR CONCAT_WS(' ', `propietario`.`nombres`, `propietario`.`apellido_paterno`, `propietario`.`apellido_materno`) LIKE :propietario
OR rut = :rut
OR CONCAT_WS('-', rut, dv) = :rut");
return $this->fetchIds($query, [':propietario' => "%{$propietario}%", ':rut' => $propietario]);
}
public function fetchByPropietarioNombreCompleto(string $propietario): array
{
@ -353,6 +355,48 @@ GROUP BY a.`id`";*/
->where('bono_pie = ?');
return $this->fetchId($query, [$bono_id]);
}
public function fetchByIdForSearch(int $venta_id): array
{
$query = $this->connection->getQueryBuilder()
->select('venta.id AS id, venta.fecha AS fecha, venta.valor_uf AS valor')
->columns('proyecto.id AS proyecto_id, proyecto.descripcion AS proyecto_descripcion')
->columns('CONCAT_WS(" ", propietario.nombres, propietario.apellido_paterno, propietario.apellido_materno) AS propietario')
->columns('unidad.descripcion AS unidad_descripcion, tu.descripcion AS tipo_unidad_descripcion, ptu.m2 + ptu.logia + ptu.terraza AS superficie')
->columns('tev.activa')
->from($this->getTable())
->joined('JOIN propietario ON propietario.rut = venta.propietario')
->joined('JOIN propiedad_unidad pu ON pu.propiedad = venta.propiedad')
->joined('JOIN unidad ON unidad.id = pu.unidad')
->joined('JOIN proyecto_tipo_unidad ptu ON unidad.pt = ptu.id')
->joined('JOIN proyecto ON proyecto.id = ptu.proyecto')
->joined('JOIN tipo_unidad tu ON tu.id = ptu.tipo')
->joined('JOIN (SELECT ev1.* FROM estado_venta ev1 JOIN (SELECT MAX(id) AS id, venta FROM estado_venta GROUP BY venta) ev0 ON ev0.id = ev1.id) ev ON ev.venta = venta.id')
->joined('JOIN tipo_estado_venta tev ON ev.estado = tev.id')
->where('venta.id = ? AND tu.descripcion = "departamento"')
->group('venta.id');
return $this->connection->execute($query, [$venta_id])->fetch(PDO::FETCH_ASSOC);
}
public function fetchByIdForList(int $venta_id): array
{
$query = $this->connection->getQueryBuilder()
->select('venta.id AS id, venta.fecha AS fecha, venta.valor_uf AS valor')
->columns('proyecto.id AS proyecto_id, proyecto.descripcion AS proyecto_descripcion')
->columns('CONCAT_WS(" ", propietario.nombres, propietario.apellido_paterno, propietario.apellido_materno) AS propietario')
->columns("GROUP_CONCAT(unidad.descripcion SEPARATOR ' - ') AS unidad_descripcion, tu.descripcion AS tipo_unidad_descripcion, ptu.m2 + ptu.logia + ptu.terraza AS superficie")
->columns('tev.activa')
->from($this->getTable())
->joined('JOIN propietario ON propietario.rut = venta.propietario')
->joined('JOIN propiedad_unidad pu ON pu.propiedad = venta.propiedad')
->joined('JOIN unidad ON unidad.id = pu.unidad')
->joined('JOIN proyecto_tipo_unidad ptu ON unidad.pt = ptu.id')
->joined('JOIN proyecto ON proyecto.id = ptu.proyecto')
->joined('JOIN tipo_unidad tu ON tu.id = ptu.tipo')
->joined('JOIN (SELECT ev1.* FROM estado_venta ev1 JOIN (SELECT MAX(id) AS id, venta FROM estado_venta GROUP BY venta) ev0 ON ev0.id = ev1.id) ev ON ev.venta = venta.id')
->joined('JOIN tipo_estado_venta tev ON ev.estado = tev.id')
->where('venta.id = ?')
->group('venta.id');
return $this->connection->execute($query, [$venta_id])->fetch(PDO::FETCH_ASSOC);
}
protected function fetchIds(string $query, ?array $data = null): array
{

View File

@ -52,4 +52,13 @@ class BonoPie extends Ideal\Repository
->where('pago = ?');
return $this->fetchOne($query, [$pago_id]);
}
public function fetchByVenta(int $venta_id): Model\Venta\BonoPie
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('JOIN venta ON venta.bono_pie = a.id')
->where('venta.id = ?');
return $this->fetchOne($query, [$venta_id]);
}
}

View File

@ -17,7 +17,7 @@ class Credito extends Ideal\Repository
public function create(?array $data = null): Model\Venta\Credito
{
$map = (new Implement\Repository\MapperParser())
$map = (new Implement\Repository\MapperParser(['valor']))
->register('pago', (new Implement\Repository\Mapper())
->setFunction(function($data) {
return $this->pagoService->getById($data['pago']);
@ -53,4 +53,13 @@ class Credito extends Ideal\Repository
->where('pago = ?');
return $this->fetchOne($query, [$pago_id]);
}
public function fetchByVenta(int $venta_id): Model\Venta\Credito
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('JOIN venta ON venta.credito = a.id')
->where('venta.id = ?');
return $this->fetchOne($query, [$venta_id]);
}
}

View File

@ -55,4 +55,13 @@ class Escritura extends Ideal\Repository
->where('pago = ?');
return $this->fetchOne($query, [$pago_id]);
}
public function fetchByVenta(int $venta_id): Model\Venta\Escritura
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('JOIN venta ON venta.escritura = a.id')
->where('venta.id = ?');
return $this->fetchOne($query, [$venta_id]);
}
}

View File

@ -47,15 +47,19 @@ class EstadoVenta extends Ideal\Repository
public function fetchByVenta(int $venta_id): array
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `venta` = ?";
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('venta = ?');
return $this->fetchMany($query, [$venta_id]);
}
public function fetchCurrentByVenta(int $venta_id): Model\Venta\EstadoVenta
{
$query = "SELECT a.*
FROM `{$this->getTable()}` a
JOIN (SELECT MAX(`id`) AS 'id', `venta` FROM `{$this->getTable()}` GROUP BY `venta`) e0 ON e0.`id` = a.`id`
WHERE a.`venta` = ?";
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined("JOIN (SELECT MAX(id) AS id, venta FROM {$this->getTable()} GROUP BY venta) ev0 ON ev0.id = a.id")
->where('a.venta = ?');
return $this->fetchOne($query, [$venta_id]);
}
}

View File

@ -108,4 +108,13 @@ WHERE venta_id = ?";
->where('valor = ? OR ROUND(valor/uf, 3) = ?');
return $this->fetchMany($query, [$value, $value]);
}
public function fetchDevolucionByVenta(int $venta_id): Model\Venta\Pago
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('JOIN venta ON venta.devolucion = a.id')
->where('venta.id = ?');
return $this->fetchOne($query, [$venta_id]);
}
}

View File

@ -72,4 +72,13 @@ class Pie extends Ideal\Repository
->where('reajuste = ?');
return $this->fetchOne($query, [$reajuste_id]);
}
public function fetchByVenta(int $venta_id): Model\Venta\Pie
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('JOIN venta ON venta.pie = a.id')
->where('venta.id = ?');
return $this->fetchOne($query, [$venta_id]);
}
}

View File

@ -22,7 +22,7 @@ class Propietario extends Ideal\Repository
public function create(?array $data = null): Define\Model
{
$map = (new Implement\Repository\MapperParser(['dv', 'nombres']))
$map = (new Implement\Repository\MapperParser(['rut', 'dv', 'nombres']))
->register('apellido_paterno', (new Implement\Repository\Mapper())
->setProperty('apellidos')
->setFunction(function($data) {
@ -64,8 +64,8 @@ class Propietario extends Ideal\Repository
public function save(Define\Model $model): Define\Model
{
$model->rut = $this->saveNew(
['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]
['rut', 'dv', 'nombres', 'apellido_paterno', 'apellido_materno', 'direccion', 'otro', 'representante'],
[$model->rut, $model->dv, $model->nombres, $model->apellidos['paterno'], $model->apellidos['materno'], $model->datos->direccion->id, $model->otro->rut ?? 0, $model->representante->rut ?? 0]
);
return $model;
}

View File

@ -49,4 +49,13 @@ class Subsidio extends Ideal\Repository
->where('subsidio = ? OR pago = ?');
return $this->fetchOne($query, [$pago_id, $pago_id]);
}
public function fetchByVenta(int $venta_id): Model\Venta\Subsidio
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('JOIN venta ON venta.subsidio = a.id')
->where('venta.id = ?');
return $this->fetchOne($query, [$venta_id]);
}
}

View File

@ -177,6 +177,24 @@ class Unidad extends Ideal\Repository
->where("a.`descripcion` LIKE ? AND tu.`descripcion` = ? AND (pu.`id` IS NULL OR `venta`.`id` IS NULL OR tev.`activa` = 0)");
return $this->connection->execute($query, [$descripcion, $tipo])->fetchAll(PDO::FETCH_ASSOC);
}
public function fetchByIdForSearch(int $unidad_id): array
{
$query = $this->connection->getQueryBuilder()
->select('unidad.id AS id, unidad.descripcion AS descripcion')
->columns('proyecto.id AS proyecto_id, proyecto.descripcion AS proyecto_descripcion')
->columns('tu.descripcion AS tipo_unidad_descripcion')
->columns('ptu.m2 + ptu.logia + ptu.terraza AS superficie')
->columns('precio.valor AS precio')
->from($this->getTable())
->joined('JOIN proyecto_tipo_unidad ptu ON ptu.id = unidad.pt')
->joined('JOIN proyecto ON proyecto.id = ptu.proyecto')
->joined('JOIN tipo_unidad tu ON tu.id = ptu.tipo')
->joined('JOIN precio ON precio.unidad = unidad.id')
->joined('JOIN (SELECT ep1.* FROM estado_precio ep1 JOIN (SELECT MAX(id) AS id, precio FROM estado_precio GROUP BY precio) ep0 ON ep0.id = ep1.id) ep ON ep.precio = precio.id')
->where('unidad.id = ?')
->group('unidad.id');
return $this->connection->execute($query, [$unidad_id])->fetch(PDO::FETCH_ASSOC);
}
protected function joinProrrateo(): string
{

View File

@ -2,15 +2,29 @@
namespace Incoviba\Service;
use DateTimeInterface;
use DateTimeImmutable;
use DateInterval;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UploadedFileInterface;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal\Service;
use Incoviba\Common\Define\Cartola\Banco;
use Incoviba\Common\Define\Contabilidad\Exporter;
use Incoviba\Common\Implement\Exception;
use Incoviba\Model;
use Incoviba\Repository;
class Cartola
class Cartola extends Service
{
public function __construct(protected StreamFactoryInterface $streamFactory, protected Exporter $exporter) {}
public function __construct(LoggerInterface $logger,
protected StreamFactoryInterface $streamFactory, protected Exporter $exporter,
protected Repository\Inmobiliaria $inmobiliariaRepository,
protected Repository\Inmobiliaria\Cuenta $cuentaRepository,
protected Repository\Movimiento $movimientoRepository,
protected Movimiento $movimientoService,
protected Repository\Cartola $cartolaRepository) {
parent::__construct($logger);
}
protected array $bancos;
public function register(string $name, Banco $banco): Cartola
@ -26,4 +40,88 @@ class Cartola
{
return $this->exporter->export($inmobiliaria, $banco, $mes, $movimientos);
}
public function diaria(Model\Inmobiliaria\Cuenta $cuenta, DateTimeInterface $fecha, UploadedFileInterface $file): array
{
$ms = $this->getMovimientosDiarios($cuenta->banco, $file);
$cartolaData = [
'cargos' => 0,
'abonos' => 0,
'saldo' => 0
];
$movimientos = [];
foreach ($ms as $m) {
$movimiento = $this->buildMovimiento($cuenta, $m);
$movimiento = $this->movimientoService->process($movimiento);
if ($movimiento->fecha->getTimestamp() === $fecha->getTimestamp()) {
$movimientos []= $movimiento;
$cartolaData['cargos'] += $movimiento->cargo;
$cartolaData['abonos'] += $movimiento->abono;
}
if ($movimiento->fecha->getTimestamp() > $fecha->getTimestamp()) {
continue;
}
$cartolaData['saldo'] = $movimiento->saldo;
}
$cartola = $this->buildCartola($cuenta, $fecha, $cartolaData);
return compact('cartola', 'movimientos');
}
public function diariaManual(Model\Inmobiliaria\Cuenta $cuenta, DateTimeInterface $fecha, array $data): array
{
$cartolaData = [
'cargos' => 0,
'abonos' => 0,
'saldos' => 0
];
$movimientos = [];
foreach ($data as $row) {
$dataMovimiento = $row;
$dataMovimiento['fecha'] = $fecha->format('Y-m-d');
$dataMovimiento['documento'] = '';
$movimiento = $this->buildMovimiento($cuenta, $dataMovimiento);
$movimiento = $this->movimientoService->process($movimiento);
$movimientos []= $movimiento;
$cartolaData['cargos'] += $movimiento->cargo;
$cartolaData['abonos'] += $movimiento->abono;
$cartolaData['saldo'] = $movimiento->saldo;
}
$cartola = $this->buildCartola($cuenta, $fecha, $cartolaData);
return compact('cartola', 'movimientos');
}
protected function getMovimientosDiarios(Model\Banco $banco, UploadedFileInterface $file): array
{
$movimientos = $this->bancos[strtolower($banco->nombre)]->process($file);
return $this->bancos[strtolower($banco->nombre)]->processMovimientosDiarios($movimientos);
}
protected function buildCartola(Model\Inmobiliaria\Cuenta $cuenta, DateTimeInterface $fecha, array $data): Model\Cartola
{
try {
return $this->cartolaRepository->fetchByCuentaAndFecha($cuenta->id, $fecha);
} catch (Exception\EmptyResult) {
$data['cuenta_id'] = $cuenta->id;
$data['fecha'] = $fecha->format('Y-m-d');
$cartola = $this->cartolaRepository->create($data);
return $this->cartolaRepository->save($cartola);
}
}
protected function buildMovimiento(Model\Inmobiliaria\Cuenta $cuenta, array $data): Model\Movimiento
{
try {
return $this->movimientoRepository
->fetchByCuentaAndFechaAndCargoAndAbonoAndSaldo(
$cuenta->id,
new DateTimeImmutable($data['fecha']),
$data['cargo'] ?? 0,
$data['abono'] ?? 0,
$data['saldo']
);
} catch (Exception\EmptyResult $exception) {
$data['cuenta_id'] = $cuenta->id;
$movimiento = $this->movimientoRepository->create($data);
return $this->movimientoRepository->save($movimiento);
}
}
}

View File

@ -8,6 +8,14 @@ use Incoviba\Common\Ideal\Cartola\Banco;
class Itau extends Banco
{
const CUENTA_CORRIENTE = 0;
const ULTIMOS_MOVIMIENTOS = 1;
public function processMovimientosDiarios(array $movimientos): array
{
return array_reverse($movimientos);
}
protected function columnMap(): array
{
return [
@ -15,7 +23,10 @@ class Itau extends Banco
'Número de operación' => 'documento',
'Descripción' => 'glosa',
'Depósitos o abonos' => 'abono',
'Giros o cargos' => 'cargo'
'Giros o cargos' => 'cargo',
'Documentos' => 'documento',
'Movimientos' => 'glosa',
'Saldos' => 'saldo'
];
}
@ -28,53 +39,130 @@ class Itau extends Banco
$xlsx = $reader->load($filename);
$sheet = $xlsx->getActiveSheet();
$dates = explode(' - ', $sheet->getCell('C4')->getCalculatedValue());
$date = DateTimeImmutable::createFromFormat('d/m/Y', $dates[0]);
$year = $date->format('Y');
$rowIndex = 26;
$columns = [];
$row = $sheet->getRowIterator($rowIndex)->current();
$cols = $row->getColumnIterator('A','G');
foreach ($cols as $col) {
$columns []= trim($col->getCalculatedValue());
}
$rowIndex ++;
$row = $sheet->getRowIterator($rowIndex)->current();
$cols = $row->getColumnIterator('A', 'G');
$colIndex = 0;
foreach ($cols as $col) {
$value = $col->getCalculatedValue();
if ($value !== null) {
$columns[$colIndex] .= " {$value}";
}
$colIndex ++;
}
$rowIndex ++;
$data = [];
$rows = $sheet->getRowIterator($rowIndex);
foreach ($rows as $row) {
if ($sheet->getCell("A{$rowIndex}")->getCalculatedValue() === null) {
try {
switch ($this->identifySheet($sheet)) {
case self::CUENTA_CORRIENTE:
$data = $this->parseCuentaCorriente($sheet);
break;
case self::ULTIMOS_MOVIMIENTOS:
$data = $this->parseUltimosMovimientos($sheet);
break;
}
} catch (PhpSpreadsheet\Exception $exception) {
$this->logger->critical($exception);
} finally {
unlink($filename);
}
return $data;
}
protected function parseCuentaCorriente(PhpSpreadsheet\Worksheet\Worksheet $sheet): array
{
$found = false;
$year = 0;
$columns = [];
$data = [];
foreach ($sheet->getRowIterator() as $row) {
if (!$found and $sheet->getCell("A{$row->getRowIndex()}")->getCalculatedValue() === 'Cartola Histórica') {
$columnIndex = 'A';
foreach ($row->getColumnIterator() as $column) {
if ($column->getValue() !== 'Periodo') {
continue;
}
$columnIndex = $column->getColumn();
break;
}
$dates = explode(' - ', $sheet->getCell("{$columnIndex}{$row->getRowIndex()}")->getCalculatedValue());
$date = DateTimeImmutable::createFromFormat('d/m/Y', $dates[0]);
$year = $date->format('Y');
}
if (!$found and $sheet->getCell("A{$row->getRowIndex()}")->getCalculatedValue() === 'Movimientos') {
$found = true;
foreach ($row->getColumnIterator() as $column) {
if ($column->getValue() === null) {
break;
}
$columns[$column->getColumn()] = trim($column->getValue());
}
continue;
}
if (!$found) {
continue;
}
if ($sheet->getCell("A{$row->getRowIndex()}")->getValue() === null) {
break;
}
$cols = $row->getColumnIterator('A', 'G');
$colIndex = 0;
$rowData = [];
foreach ($cols as $col) {
$value = $col->getCalculatedValue();
$col = $columns[$colIndex];
if ($col === 'Fecha') {
foreach ($columns as $columnIndex => $column) {
$value = $sheet->getCell("{$columnIndex}{$row->getRowIndex()}")->getCalculatedValue();
$mapped = $this->columnMap()[$column];
if ($mapped === 'fecha') {
list($d, $m) = explode('/', $value);
$value = "{$year}-{$m}-{$d}";
}
$rowData[$col] = $value;
$colIndex ++;
if (in_array($mapped, ['cargo', 'abono', 'saldo'])) {
$value = (int) $value;
}
$rowData[$column] = $value;
}
$data []= $rowData;
$rowIndex ++;
}
unlink($filename);
return $data;
}
protected function parseUltimosMovimientos(PhpSpreadsheet\Worksheet\Worksheet $sheet): array
{
$found = false;
$data = [];
$columns = [];
foreach ($sheet->getRowIterator() as $row) {
if (!$found and $sheet->getCell("A{$row->getRowIndex()}")->getCalculatedValue() === 'Últimos Movimientos') {
$found = true;
continue;
}
if (!$found) {
continue;
}
if (count($columns) === 0) {
foreach ($row->getColumnIterator() as $cell) {
if ($cell->getValue() === null) {
break;
}
$columns[$cell->getColumn()] = trim($cell->getValue());
}
continue;
}
if ($sheet->getCell("A{$row->getRowIndex()}")->getValue() === null) {
break;
}
$rowData = [];
foreach ($columns as $columnIndex => $column) {
$value = $sheet->getCell("{$columnIndex}{$row->getRowIndex()}")->getCalculatedValue();
$mapped = $this->columnMap()[$column] ?? $column;
if ($mapped === 'fecha') {
$value = PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value, 'America/Santiago')->format('Y-m-d');
}
if (in_array($mapped, ['abono', 'cargo', 'saldo'])) {
$value = (int) $value;
}
$rowData[$column] = $value;
}
$data []= $rowData;
}
return $data;
}
protected function identifySheet(PhpSpreadsheet\Worksheet\Worksheet $sheet): int
{
foreach ($sheet->getRowIterator(1, 10) as $row) {
$value = $sheet->getCell("A{$row->getRowIndex()}")->getValue();
if ($value === 'Estado de Cuenta Corriente') {
return self::CUENTA_CORRIENTE;
}
if ($value === 'Consulta Saldos y Últimos movimientos') {
return self::ULTIMOS_MOVIMIENTOS;
}
}
throw new PhpSpreadsheet\Exception();
}
}

View File

@ -17,6 +17,12 @@ class Santander extends Banco
'DESCRIPCIÓN MOVIMIENTO' => 'glosa',
'FECHA' => 'fecha',
'N° DOCUMENTO' => 'documento',
'SALDO' => 'saldo',
'Fecha' => 'fecha',
'Cargo ($)' => 'cargo',
'Abono ($)' => 'abono',
'Descripcin' => 'glosa',
'Saldo Diario' => 'saldo'
];
}
protected function parseFile(UploadedFileInterface $uploadedFile): array
@ -25,47 +31,111 @@ class Santander extends Banco
$uploadedFile->moveTo($filename);
$reader = PhpSpreadsheet\IOFactory::createReader('Xlsx');
$xlsx = $reader->load($filename);
try {
$xlsx = $reader->load($filename);
} catch (PhpSpreadsheet\Reader\Exception) {
return $this->parseHtml($filename);
}
$sheet = $xlsx->getActiveSheet();
$rowIndex = 16;
$found = false;
$columns = [];
$row = $sheet->getRowIterator($rowIndex)->current();
$cols = $row->getColumnIterator('A', 'H');
foreach ($cols as $col) {
$columns []= $col->getCalculatedValue();
}
$rowIndex ++;
$rows = $sheet->getRowIterator($rowIndex);
$data = [];
foreach ($rows as $row) {
if ($sheet->getCell("A{$rowIndex}")->getCalculatedValue() === 'Resumen comisiones') {
foreach ($sheet->getRowIterator() as $row) {
if (!$found and $sheet->getCell("A{$row->getRowIndex()}")->getCalculatedValue() === 'MONTO') {
$found = true;
foreach ($row->getColumnIterator() as $column) {
if ($column->getValue() === null) {
break;
}
$columns[$column->getColumn()] = trim($column->getValue());
}
continue;
}
if (!$found) {
continue;
}
if ($sheet->getCell("A{$row->getRowIndex()}")->getValue() === null) {
break;
}
$cols = $row->getColumnIterator('A', 'H');
$colIndex = 0;
$rowData = [];
foreach ($cols as $col) {
$value = $col->getCalculatedValue();
$col = $columns[$colIndex];
if ($col === 'FECHA') {
list($d,$m,$Y) = explode('/', $value);
$value = "{$Y}-{$m}-{$d}";
foreach ($columns as $columnIndex => $column) {
$value = $sheet->getCell("{$columnIndex}{$row->getRowIndex()}")->getCalculatedValue();
$mapped = $this->columnMap()[$column] ?? $column;
if ($mapped === 'fecha') {
$value = implode('-', array_reverse(explode('/', $value)));
}
$rowData[$col] = $value;
$colIndex ++;
if ($column === 'MONTO') {
$value = (int) $value;
}
$rowData[$column] = $value;
}
if ($rowData['CARGO/ABONO'] === 'C') {
$rowData['cargo'] = -$rowData['MONTO'];
$rowData['MONTO'] = -$rowData['MONTO'];
$rowData['cargo'] = $rowData['MONTO'];
$rowData['abono'] = 0;
} else {
$rowData['cargo'] = 0;
$rowData['abono'] = $rowData['MONTO'];
}
$data []= $rowData;
$rowIndex ++;
}
return $data;
}
protected function parseHtml(string $filename): array
{
$data = [];
$lines = explode("\r\n", file_get_contents($filename));
$columns = [];
$found = false;
for ($rowIndex = 0; $rowIndex < count($lines); $rowIndex ++) {
if (!$found and str_contains($lines[$rowIndex], 'Cuenta Corriente: ')) {
$found = true;
$rowIndex += 2;
$columns = $this->parseHtmlRow($lines, $rowIndex);
continue;
}
if (!$found) {
continue;
}
$row = $this->parseHtmlRow($lines, $rowIndex);
if (str_contains($row[0], 'Saldo Contable')) {
break;
}
$row = array_combine($columns, $row);
$row['Fecha'] = implode('-', array_reverse(explode('-', $row['Fecha'])));
foreach (['Cargo ($)', 'Abono ($)', 'Saldo Diario'] as $column) {
$row[$column] = (int) str_replace('.', '', $row[$column]);
}
$row['Saldo Diario'] -= ($row['Abono ($)'] - $row['Cargo ($)']);
$row['N° DOCUMENTO'] = '';
$data []= $row;
}
return $data;
}
protected function parseHtmlRow(array $lines, int &$rowIndex): array
{
if (!str_contains($lines[$rowIndex ++], '<tr>')) {
return [];
}
$data = [];
while (!str_contains($lines[$rowIndex], '</tr>')) {
$tags = substr_count($lines[$rowIndex], '<') - substr_count($lines[$rowIndex], '</');
$ini = 0;
for ($t = 0; $t < $tags; $t ++) {
$ini = strpos($lines[$rowIndex], '>', $ini) + 1;
}
$end = strpos($lines[$rowIndex], '<', $ini + 1);
$cell = str_replace(' ', '', substr($lines[$rowIndex], $ini, $end - $ini));
$encoding = mb_detect_encoding($cell, ['Windows-1252', 'UTF-8']);
if ($encoding !== 'UTF-8') {
$cell = mb_convert_encoding($cell, $encoding, 'UTF-8');
$cell = str_replace('?', '', $cell);
}
$data []= $cell;
$rowIndex ++;
}
return $data;
}
}

View File

@ -9,6 +9,13 @@ use Incoviba\Common\Ideal\Cartola\Banco;
class Security extends Banco
{
public function processMovimientosDiarios(array $movimientos): array
{
$movimientos = array_reverse($movimientos);
array_shift($movimientos);
return $movimientos;
}
protected function parseFile(UploadedFileInterface $uploadedFile): array
{
$stream = $uploadedFile->getStream();
@ -24,8 +31,10 @@ class Security extends Banco
'fecha' => 'fecha',
'descripción' => 'glosa',
'número de documentos' => 'documento',
'nº documento' => 'documento',
'cargos' => 'cargo',
'abonos' => 'abono'
'abonos' => 'abono',
'saldos' => 'saldo'
];
}
@ -33,10 +42,9 @@ class Security extends Banco
{
$filename = '/tmp/cartola.xls';
$file->moveTo($filename);
$reader = PhpSpreadsheet\IOFactory::createReader('Xls');
$xlsx = $reader->load($filename);
$xlsx = @PhpSpreadsheet\IOFactory::load($filename);
$worksheet = $xlsx->getActiveSheet();
$rows = $worksheet->getRowIterator();
$rows = $worksheet->getRowIterator(3);
$dataFound = false;
$columns = [];
$data = [];
@ -44,10 +52,10 @@ class Security extends Banco
$cells = $row->getCellIterator();
$rowData = [];
foreach ($cells as $cell) {
if ($cell->getColumn() === 'A' and $cell->getCalculatedValue() === "fecha ") {
if ($cell->getColumn() === 'A' and $cell->getCalculatedValue() !== null and strtolower($cell->getCalculatedValue()) === "fecha ") {
$cols = $row->getColumnIterator();
foreach ($cols as $col) {
$columns[$col->getColumn()] = trim($col->getCalculatedValue());
$columns[$col->getColumn()] = trim(strtolower($col->getCalculatedValue()), '  ');
}
$dataFound = true;
break;
@ -62,7 +70,11 @@ class Security extends Banco
$col = $columns[$cell->getColumn()];
$value = $cell->getCalculatedValue();
if ($col === 'fecha') {
$value = PhpSpreadsheet\Shared\Date::excelToDateTimeObject($cell->getValue(), 'America/Santiago')->format('Y-m-d');
if ((int) $cell->getValue() !== $cell->getValue()) {
$value = implode('-', array_reverse(explode('-', $cell->getValue())));
} else {
$value = PhpSpreadsheet\Shared\Date::excelToDateTimeObject($cell->getValue(), 'America/Santiago')->format('Y-m-d');
}
}
$rowData[$col] = $value;
}

View File

@ -0,0 +1,20 @@
<?php
namespace Incoviba\Service;
use DateTimeInterface;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
class Contabilidad extends Ideal\Controller
{
public function __construct(LoggerInterface $logger,
protected Contabilidad\Informe\Tesoreria $tesoreriaService)
{
parent::__construct($logger);
}
public function tesoreria(DateTimeInterface $fecha): array
{
return $this->tesoreriaService->build($fecha);
}
}

View File

@ -0,0 +1,293 @@
<?php
namespace Incoviba\Service\Contabilidad\Informe;
use DateTimeInterface;
use DateInterval;
use Psr\Log\LoggerInterface;
use PhpOffice\PhpSpreadsheet;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
class Tesoreria extends Ideal\Service
{
public function __construct(LoggerInterface $logger,
protected Repository\Inmobiliaria $inmobiliariaRepository,
protected Repository\Inmobiliaria\Cuenta $cuentaRepository,
protected Repository\Deposito $depositoRepository,
protected Repository\Cartola $cartolaRepository,
protected Repository\Movimiento $movimientoRepository,
protected Service\Contabilidad\Informe\Tesoreria\Excel $excelService,
protected Service\Contabilidad\Informe\Tesoreria\PDF $pdfService)
{
parent::__construct($logger);
$this->movimientos = new class() {
public function __construct()
{
$this->dap = new class()
{
public array $ingresos = [];
public array $egresos = [];
};
}
public object $dap;
public array $ingresos = [];
public array $egresos = [];
const INGRESOS = 'ingresos';
const EGRESOS = 'egresos';
public function addDap(string $tipo, array $movimientos)
{
foreach ($movimientos as $movimiento) {
$this->dap->{$tipo} []= $movimiento;
}
return $this;
}
public function build(): array
{
return [
'capital dap' => [
'ingresos' => $this->dap->ingresos,
'egresos' => $this->dap->egresos
],
'ingresos' => $this->ingresos,
'egresos' => $this->egresos
];
}
};
$this->totales = new class() {
public int $anterior = 0;
public int $actual = 0;
public int $ffmm = 0;
public int $deposito = 0;
public function diferencia(): int
{
return $this->actual - $this->anterior;
}
public function saldo(): int
{
return $this->diferencia() + $this->ffmm + $this->deposito;
}
public function cuentas(): int
{
return $this->actual;
}
public function ffmms(): int
{
return $this->ffmm;
}
public function depositos(): int
{
return $this->deposito;
}
public function caja(): int
{
return $this->cuentas() + $this->ffmms() + $this->depositos();
}
};
}
const DAP_INGRESOS = 'dap->ingresos';
const DAP_EGRESOS = 'dap->egresos';
const INGRESOS = 'ingresos';
const EGRESOS = 'egresos';
const TOTAL_ANTERIOR = 'anterior';
const TOTAL_ACTUAL = 'actual';
const TOTAL_FFMM = 'ffmm';
const TOTAL_DAP = 'deposito';
protected DateTimeInterface $anterior;
protected object $totales;
protected object $movimientos;
public function getAnterior(DateTimeInterface $fecha): DateTimeInterface
{
if (!isset($this->anterior)) {
$this->anterior = $fecha->sub(new DateInterval('P1D'));
if ($this->anterior->format('N') === '7') {
$this->anterior = $fecha->sub(new DateInterval('P3D'));
}
}
return $this->anterior;
}
public function build(DateTimeInterface $fecha): array
{
try {
$inmobiliarias = $this->inmobiliariaRepository->fetchAll();
} catch (Implement\Exception\EmptyResult) {
return [];
}
$informe = ['inmobiliarias' => []];
foreach ($inmobiliarias as $inmobiliaria) {
$informe['inmobiliarias'][$inmobiliaria->rut] = $this->buildInmobiliaria($inmobiliaria, $fecha);
}
$informe['movimientos'] = $this->buildMovimientos();
$informe['totales'] = $this->buildTotales();
//$this->buildInforme($fecha, $informe);
return $informe;
}
public function buildInforme(DateTimeInterface $fecha, array $data, string $type = 'Xlsx', ?string $filename = 'php://output'): void
{
$informe = $this->excelService->build($fecha, $data);
$this->excelService->save($fecha, $informe, $type, $filename);
}
protected function buildInmobiliaria(Model\Inmobiliaria $inmobiliaria, DateTimeInterface $fecha): object
{
$dataInmobiliaria = new class() {
public Model\Inmobiliaria $inmobiliaria;
public array $cuentas = [];
public function total(): int
{
return array_reduce($this->cuentas, function(int $sum, $cuenta) {
return $sum + $cuenta->actual;
}, 0);
}
public function ffmm(): int
{
return array_reduce($this->cuentas, function(int $sum, $cuenta) {
return $sum + $cuenta->ffmm;
}, 0);
}
public function deposito(): int
{
return array_reduce($this->cuentas, function(int $sum, $cuenta) {
return $sum + $cuenta->deposito;
}, 0);
}
public function caja(): int
{
return array_reduce($this->cuentas, function(int $sum, $cuenta) {
return $sum + $cuenta->saldo();
}, 0);
}
};
$dataInmobiliaria->inmobiliaria = $inmobiliaria;
try {
$cuentas = $this->cuentaRepository->fetchByInmobiliaria($inmobiliaria->rut);
} catch (Implement\Exception\EmptyResult) {
return $dataInmobiliaria;
}
foreach ($cuentas as $cuenta) {
$data = new class() {
public string $banco;
public string $numero;
public int $anterior = 0;
public int $actual = 0;
public int $ffmm = 0;
public int $deposito = 0;
public function diferencia(): int
{
return $this->actual - $this->anterior;
}
public function saldo(): int
{
return $this->diferencia() + $this->ffmm + $this->deposito;
}
};
$data->banco = $cuenta->banco->nombre;
$data->numero = $cuenta->cuenta;
try {
$depositos = $this->depositoRepository->fetchByCuenta($cuenta->id);
foreach ($depositos as $deposito) {
if ($deposito->termino < $fecha) {
continue;
}
$data->deposito += $deposito->capital;
$this->addTotal(self::TOTAL_DAP, $deposito->capital);
if ($deposito->inicio === $fecha) {
$this->addMovimientos(self::DAP_EGRESOS, [(object) [
'cuenta' => $deposito->cuenta,
'fecha' => $deposito->inicio,
'cargo' => - $deposito->capital,
'abono' => 0,
'saldo' => - $deposito->capital,
'glosa' => 'INVERSION DAP'
]]);
}
if ($deposito->termino === $fecha) {
$data->deposito -= $deposito->capital;
$this->addTotal(self::TOTAL_DAP, -$deposito->capital);
$this->addMovimientos(self::DAP_INGRESOS, [(object) [
'cuenta' => $deposito->cuenta,
'fecha' => $deposito->termino,
'cargo' => 0,
'abono' => $deposito->capital,
'saldo' => $deposito->capital,
'glosa' => 'RESCATE DAP'
]]);
}
}
} catch (Implement\Exception\EmptyResult) {}
try {
$cartola = $this->cartolaRepository->fetchByCuentaAndFecha($cuenta->id, $fecha);
$data->actual = $cartola->saldo;
} catch (Implement\Exception\EmptyResult) {}
try {
$cartola = $this->cartolaRepository->fetchByCuentaAndFecha($cuenta->id, $this->getAnterior($fecha));
$data->anterior = $cartola->saldo;
} catch (Implement\Exception\EmptyResult) {}
if ($data->diferencia() !== 0) {
try {
$movimientos = $this->movimientoRepository->fetchByCuentaAndFecha($cuenta->id, $fecha);
$this->addMovimientos(self::INGRESOS,
array_filter($movimientos, function(Model\Movimiento $movimiento) {
return $movimiento->abono > 0;
}));
$this->addMovimientos(self::EGRESOS,
array_filter($movimientos, function(Model\Movimiento $movimiento) {
return $movimiento->cargo > 0;
}));
} catch (Implement\Exception\EmptyResult) {}
}
$dataInmobiliaria->cuentas []= $data;
$this->addTotal(
[self::TOTAL_ANTERIOR, self::TOTAL_ACTUAL],
[$data->anterior, $data->actual]
);
}
return $dataInmobiliaria;
}
protected function buildMovimientos(): array
{
return $this->movimientos->build();
}
protected function buildTotales(): object
{
return $this->totales;
}
protected function addMovimientos(string $tipo, array $movimientos): Tesoreria
{
if (str_contains($tipo, 'dap')) {
list($d, $t) = explode('->', $tipo);
$this->movimientos->addDap($t, $movimientos);
return $this;
}
foreach ($movimientos as $movimiento) {
$this->movimientos->{$tipo} []= $movimiento;
}
return $this;
}
protected function addTotal(string|array $tipo, int|array $total): Tesoreria
{
if (is_array($tipo)) {
foreach ($tipo as $i => $t) {
$this->addTotal($t, $total[$i]);
}
return $this;
}
$this->totales->{$tipo} += $total;
return $this;
}
}

View File

@ -0,0 +1,503 @@
<?php
namespace Incoviba\Service\Contabilidad\Informe\Tesoreria;
use DateTimeInterface;
use DateInterval;
use IntlDateFormatter;
use Psr\Log\LoggerInterface;
use PhpOffice\PhpSpreadsheet;
use Incoviba\Common\Ideal;
use Incoviba\Service;
class Excel extends Ideal\Service
{
protected const CURRENCY_CODE = '_-$* #,##0_-;-$* #,##0_-;_-$* "-"??_-;_-@_-';
public function __construct(LoggerInterface $logger, protected string $folder, protected Service\UF $ufService, protected Service\USD $usdService)
{
parent::__construct($logger);
}
public function build(DateTimeInterface $fecha, array $data): PhpSpreadsheet\Spreadsheet
{
$title = "Informe de Tesorería {$fecha->format('d.m.Y')}";
$informe = new PhpSpreadsheet\Spreadsheet();
$informe->getProperties()
->setCompany('Incoviba')
->setCreator('admin@incoviba.cl')
->setTitle($title)
->setSubject($title)
->setCreated($fecha->getTimestamp());
$styles = [
'font' => [
'name' => 'Gill Sans MT',
'size' => 12
]
];
$informe->getDefaultStyle()->applyFromArray($styles);
$sheet = $informe->getActiveSheet();
$sheet->setTitle($title);
$sheet->getColumnDimension('A')->setWidth('5.43');
$this->fillTitle($sheet, $fecha);
$this->fillFechas($sheet, $fecha);
$this->fillMonedas($sheet, $fecha);
$finalRow = $this->fillEmpresas($sheet, $data);
$finalRow = $this->fillCaja($sheet, $data, $finalRow + 2);
foreach (range('B', 'V') as $columnIndex) {
$sheet->getColumnDimension($columnIndex)->setAutoSize(true);
}
$this->setPageSetup($sheet, $finalRow);
return $informe;
}
public function save(DateTimeInterface $fecha, PhpSpreadsheet\Spreadsheet $informe, string $type = 'Xlsx', ?string $filename = null): void
{
if ($filename === null) {
$ext = strtolower($type);
$filename = implode(DIRECTORY_SEPARATOR, [$this->folder, "{$informe->getActiveSheet()->getTitle()}.{$ext}"]);
}
$writer = PhpSpreadsheet\IOFactory::createWriter($informe, $type);
if (str_starts_with($filename, 'php://')) {
$downloadFilename = "Informe de Tesorería {$fecha->format('d.m.Y')}.xlsx";
// ZipStream, used by PhpSpreadsheet when saving, sends headers
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment;filename=\"{$downloadFilename}\"");
header('Cache-Control: max-age=0');
}
$writer->save($filename);
}
protected function getAnterior(DateTimeInterface $fecha): DateTimeInterface
{
if (!isset($this->anterior)) {
$this->anterior = $fecha->sub(new DateInterval('P1D'));
if ($this->anterior->format('N') === '7') {
$this->anterior = $fecha->sub(new DateInterval('P3D'));
}
}
return $this->anterior;
}
protected function fillTitle(PhpSpreadsheet\Worksheet\Worksheet $sheet, DateTimeInterface $fecha): void
{
$intl = new IntlDateFormatter('es-CL');
$intl->setPattern('dd MMM yyyy');
$sheet->getCell('B2')->setValue('CONTROL DIARIO CAJA EMPRESAS');
$sheet->mergeCells('B2:V2');
$styles = [
'font' => [
'bold' => true,
'size' => 18
],
'fill' => [
'fillType' => PhpSpreadsheet\Style\Fill::FILL_SOLID,
'startColor' => [
'argb' => 'FFFFC000'
]
],
'alignment' => [
'horizontal' => PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER
],
'borders' => [
'outline' => [
'borderStyle' => PhpSpreadsheet\Style\Border::BORDER_THIN
]
]
];
$sheet->getStyle('B2:V2')->applyFromArray($styles);
$sheet->getCell('B3')->setValue(PhpSpreadsheet\Shared\Date::PHPToExcel($fecha));
$styles = [
'font' => [
'size' => 18
],
'alignment' => [
'horizontal' => PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER
],
'numberFormat' => [
'formatCode' => 'DD MMMM YYYY'
]
];
$sheet->getCell('B3')->getStyle()->applyFromArray($styles);
$sheet->mergeCells('B3:V3');
}
protected function fillFechas(PhpSpreadsheet\Worksheet\Worksheet $sheet, DateTimeInterface $fecha): void
{
$anterior = $this->getAnterior($fecha);
$sheet->getCell('B4')->setValue('Informe anterior');
$sheet->getCell('B5')->setValue('Informe actual');
$sheet->getCell('C4')->setValue(PhpSpreadsheet\Shared\Date::PHPToExcel($anterior));
$sheet->getCell('C5')->setValue(PhpSpreadsheet\Shared\Date::PHPToExcel($fecha));
$sheet->getStyle('C4:C5')->getNumberFormat()->setFormatCode(PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DDMMYYYY);
$sheet->getStyle('B4:C5')->getBorders()->getOutline()->setBorderStyle(PhpSpreadsheet\Style\Border::BORDER_THIN);
}
protected function fillMonedas(PhpSpreadsheet\Worksheet\Worksheet $sheet, DateTimeInterface $fecha): void
{
$sheet->getCell('E4')->setValue('Valor UF');
$sheet->getCell('E5')->setValue('Valor Dólar');
$sheet->getCell('F4')->setValue($this->ufService->get($fecha));
$sheet->getCell('F5')->setValue($this->usdService->get($fecha));
$sheet->getStyle('F4:F5')->getNumberFormat()->setFormatCode("$ #,##0.00");
$sheet->getStyle('E4:F5')->getBorders()->getOutline()->setBorderStyle(PhpSpreadsheet\Style\Border::BORDER_THIN);
}
protected function fillEmpresas(PhpSpreadsheet\Worksheet\Worksheet $sheet, array $data, int $startRow = 7): int
{
$columns = ['EMPRESA', 'Banco', 'Cuenta', 'Saldo anterior', 'Saldo actual', 'Diferencia', 'FFMM', 'DAP',
'Saldo empresa', 'Total Cuentas', 'Total FFMM', 'Total DAP', 'Caja Total'];
$styles = [
'alignment' => [
'horizontal' => PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER
],
'borders' => [
'outline' => [
'borderStyle' => PhpSpreadsheet\Style\Border::BORDER_THIN
]
],
'fill' => [
'fillType' => PhpSpreadsheet\Style\Fill::FILL_SOLID,
'color' => [
'argb' => 'FF333F4F'
]
],
'font' => [
'color' => [
'argb' => PhpSpreadsheet\Style\Color::COLOR_WHITE
]
]
];
$this->fillColumns($sheet, $columns, $styles, $startRow);
$rowIndex = $startRow + 1;
foreach ($data['inmobiliarias'] as $dataInmobiliaria) {
$rowIndex += $this->fillInmobiliaria($sheet, $dataInmobiliaria, $rowIndex);
}
$finalRow = $rowIndex;
$sheet->getStyle("B7:N{$finalRow}")->getBorders()->getAllBorders()
->setBorderStyle(PhpSpreadsheet\Style\Border::BORDER_THIN)
->getColor()->setARGB('FFD9D9D9');
$sheet->getStyle("C8:D{$finalRow}")->getAlignment()
->setHorizontal(PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
$this->fillTotals($sheet, 7, $finalRow ++);
$sheet->getStyle("E8:N{$finalRow}")->getNumberFormat()
->setFormatCode(self::CURRENCY_CODE);
return $finalRow;
}
protected function fillCaja(PhpSpreadsheet\Worksheet\Worksheet $sheet, array $data, $startRow): int
{
$sheet->getCell("B{$startRow}")->setValue('CUADRATURA CAJA DÍA ANTERIOR');
$sheet->mergeCells("B{$startRow}:V{$startRow}");
$sheet->getStyle("B{$startRow}:V{$startRow}")->applyFromArray([
'alignment' => [
'horizontal' => PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER
],
'borders' => [
'outline' => [
'borderStyle' => PhpSpreadsheet\Style\Border::BORDER_THIN
]
],
'font' => [
'bold' => true
],
'fill' => [
'fillType' => PhpSpreadsheet\Style\Fill::FILL_SOLID,
'color' => [
'argb' => 'FFFFC000'
]
]
]);
$rowIndex = $startRow;
$columns = ['EMPRESA', 'INGRESOS', 'EGRESOS', 'FECHA', 'BANCO', 'DESCRIPCIÓN', '', 'CATEGORIA', '', 'CC',
'DETALLE', '', 'N° DOC.', 'RUT', 'NOMBRES', '', '', '', '', '', ''];
$styles = [
'borders' => [
'allBorders' => [
'borderStyle' => PhpSpreadsheet\Style\Border::BORDER_THIN
]
],
'fill' => [
'fillType' => PhpSpreadsheet\Style\Fill::FILL_SOLID,
'startColor' => [
'argb' => 'FFD9D9D9'
]
]
];
$this->fillColumns($sheet, $columns, $styles, ++ $rowIndex);
$sheet->mergeCells("G{$rowIndex}:H{$rowIndex}")
->mergeCells("I{$rowIndex}:J{$rowIndex}")
->mergeCells("L{$rowIndex}:M{$rowIndex}")
->mergeCells("P{$rowIndex}:R{$rowIndex}")
->mergeCells("S{$rowIndex}:V{$rowIndex}");
$rowIndex += 2;
$sheet->getCell("T{$rowIndex}")
->setValue("Saldo Consolidado al")
->getStyle()->applyFromArray([
'alignment' => [
'horizontal' => PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT
],
'font' => [
'bold' => true
]
]);
$sheet->getCell("U{$rowIndex}")->setValue("=C4")
->getStyle()->applyFromArray([
'font' => [
'bold' => true
],
'numberFormat' => [
'formatCode' => PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DDMMYYYY
]
]);
$sheet->getCell("V{$rowIndex}")->setValue(0)->getStyle()->applyFromArray([
'font' => [
'bold' => true
],
'numberFormat' => [
'formatCode' => self::CURRENCY_CODE
]
]);
$rowSaldoAnterior = $rowIndex;
$rowIndex ++;
$styles = [
'fill' => [
'fillType' => PhpSpreadsheet\Style\Fill::FILL_SOLID,
'startColor' => [
'argb' => 'FFD9E1F2'
]
],
'font' => [
'bold' => true
]
];
$rowDap = null;
$rowIngreso = null;
$rowEgreso = null;
foreach ($data['movimientos'] as $tipo => $movimientos) {
if ($tipo === 'capital dap') {
$sheet->getCell("B{$rowIndex}")->setValue('CAPITAL DAP');
$sheet->getCell("T{$rowIndex}")->setValue('SUMA DAP');
$sheet->getStyle("B{$rowIndex}:V{$rowIndex}")->applyFromArray($styles);
$sheet->getCell("V{$rowIndex}")->getStyle()->getNumberFormat()->setFormatCode(self::CURRENCY_CODE);
$totalRow = $rowIndex;
$rowDap = $rowIndex;
$rowIndex ++;
if (count($movimientos['ingresos']) === 0 and count($movimientos['egresos']) === 0) {
$sheet->getCell("V{$totalRow}")->setValue(0);
continue;
}
$start = $rowIndex;
foreach ($movimientos as $ms) {
foreach ($ms as $movimiento) {
$sheet->getCell("B{$rowIndex}")->setValue($movimiento->cuenta->inmobiliaria->razon);
$sheet->getCell("C{$rowIndex}")->setValue($movimiento->abono);
$sheet->getCell("D{$rowIndex}")->setValue($movimiento->cargo);
$sheet->getCell("E{$rowIndex}")->setValue(PhpSpreadsheet\Shared\Date::PHPToExcel($movimiento->fecha));
$sheet->getCell("F{$rowIndex}")->setValue($movimiento->cuenta->banco->nombre);
$sheet->getCell("G{$rowIndex}")->setValue($movimiento->glosa);
$rowIndex ++;
}
}
$end = $rowIndex;
$sheet->getCell("V{$totalRow}")->setValue("=SUM(C{$start}:D{$end})");
$sheet->getStyle("C{$start}:D{$end}")->getNumberFormat()->setFormatCode(self::CURRENCY_CODE);
continue;
}
$sheet->getCell("B{$rowIndex}")->setValue(strtoupper($tipo));
$sheet->getCell("T{$rowIndex}")->setValue('SUMA '.strtoupper($tipo));
$sheet->getStyle("B{$rowIndex}:V{$rowIndex}")->applyFromArray($styles);
$sheet->getCell("V{$rowIndex}")->getStyle()->getNumberFormat()
->setFormatCode(self::CURRENCY_CODE);
$totalRow = $rowIndex;
if (!isset($rowIngreso) or $rowIngreso === null) {
$rowIngreso = $rowIndex;
} else {
$rowEgreso = $rowIndex;
}
$rowIndex ++;
if (count($movimientos) === 0) {
$sheet->getCell("V{$totalRow}")->setValue(0);
continue;
}
$start = $rowIndex;
foreach ($movimientos as $movimiento) {
$sheet->getCell("B{$rowIndex}")->setValue($movimiento->cuenta->inmobiliaria->razon);
$sheet->getCell("C{$rowIndex}")->setValue($movimiento->abono);
$sheet->getCell("D{$rowIndex}")->setValue($movimiento->cargo);
$sheet->getCell("E{$rowIndex}")->setValue(PhpSpreadsheet\Shared\Date::PHPToExcel($movimiento->fecha));
$sheet->getCell("F{$rowIndex}")->setValue($movimiento->cuenta->banco->nombre);
$sheet->getCell("G{$rowIndex}")->setValue($movimiento->glosa);
$rowIndex ++;
}
$end = $rowIndex;
$sheet->getCell("V{$totalRow}")->setValue("=SUM(C{$start}:D{$end})");
$sheet->getStyle("C{$start}:D{$end}")->getNumberFormat()
->setFormatCode(self::CURRENCY_CODE);
}
$end = $rowIndex;
$rowIndex ++;
$sheet->getCell("B{$rowIndex}")->setValue('TOTAL');
$sheet->getCell("C{$rowIndex}")->setValue("=SUM(C{$startRow}:C{$end})");
$sheet->getCell("D{$rowIndex}")->setValue("=SUM(D{$startRow}:D{$end})");
$sheet->getCell("T{$rowIndex}")->setValue('Saldo final al')
->getStyle()->applyFromArray([
'alignment' => [
'horizontal' => PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT
],
'font' => [
'bold' => true
]
]);
$sheet->getCell("U{$rowIndex}")->setValue('=C5')
->getStyle()->applyFromArray([
'font' => [
'bold' => true
],
'numberFormat' => [
'formatCode' => PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DDMMYYYY
]
]);
$sheet->getCell("V{$rowIndex}")->setValue("=V{$rowSaldoAnterior}+V{$rowDap}+V{$rowIngreso}+V{$rowEgreso}")->getStyle()->applyFromArray([
'font' => [
'bold' => true
],
'numberFormat' => [
'formatCode' => self::CURRENCY_CODE
]
]);
$sheet->getStyle("B{$rowIndex}:V{$rowIndex}")->applyFromArray([
'fill' => [
'fillType' => PhpSpreadsheet\Style\Fill::FILL_SOLID,
'startColor' => [
'argb' => 'FFD9D9D9'
]
],
'font' => [
'bold' => true
]
]);
$sheet->getStyle("C{$startRow}:D{$rowIndex}")->getNumberFormat()->setFormatCode(self::CURRENCY_CODE);
$columnRanges = [
['B', 'B'],
['C', 'C'],
['D', 'D'],
['E', 'E'],
['F', 'F'],
['G', 'H'],
['I', 'J'],
['K', 'K'],
['L', 'M'],
['N', 'N'],
['O', 'O'],
['P', 'R'],
['S', 'V']
];
foreach ($columnRanges as $range) {
$sheet->getStyle("{$range[0]}{$startRow}:{$range[1]}{$rowIndex}")->getBorders()->getOutline()
->setBorderStyle(PhpSpreadsheet\Style\Border::BORDER_THIN);
}
return $rowIndex;
}
protected function fillColumns(PhpSpreadsheet\Worksheet\Worksheet $sheet, array $columns, array $styles, $rowIndex): void
{
$columnIndex = 2;
foreach ($columns as $index => $column) {
$columnIndex = 2 + $index;
$sheet->getCell([$columnIndex, $rowIndex])->setValue($column);
}
$sheet->getStyle([2, $rowIndex, $columnIndex, $rowIndex])->applyFromArray($styles);
}
protected function fillInmobiliaria(PhpSpreadsheet\Worksheet\Worksheet $sheet, object $dataInmobiliaria, int $baseRowIndex): int
{
$rowIndex = $baseRowIndex;
$sheet->getCell("B{$rowIndex}")->setValue($dataInmobiliaria->inmobiliaria->razon);
foreach ($dataInmobiliaria->cuentas as $cuentaRowIndex => $cuenta) {
$this->fillCuenta($sheet, $cuenta, 3, $baseRowIndex + $cuentaRowIndex);
}
$sheet->getCell("K{$rowIndex}")->setValue($dataInmobiliaria->total());
$sheet->getCell("L{$rowIndex}")->setValue($dataInmobiliaria->ffmm());
$sheet->getCell("M{$rowIndex}")->setValue($dataInmobiliaria->deposito());
$sheet->getCell("N{$rowIndex}")->setValue($dataInmobiliaria->caja());
if (count($dataInmobiliaria->cuentas) > 1) {
$finalRow = $rowIndex + count($dataInmobiliaria->cuentas) - 1;
$sheet->mergeCells("B{$rowIndex}:B{$finalRow}");
$sheet->mergeCells("K{$rowIndex}:K{$finalRow}");
$sheet->mergeCells("L{$rowIndex}:L{$finalRow}");
$sheet->mergeCells("M{$rowIndex}:M{$finalRow}");
$sheet->mergeCells("N{$rowIndex}:N{$finalRow}");
}
return count($dataInmobiliaria->cuentas);
}
protected function fillCuenta(PhpSpreadsheet\Worksheet\Worksheet $sheet, object $cuenta, int $startColumnIndex, int $rowIndex): void
{
$columnIndex = $startColumnIndex;
$sheet->getCell([$columnIndex ++, $rowIndex])->setValue($cuenta->banco);
$sheet->getCell([$columnIndex ++, $rowIndex])->setValue($cuenta->numero);
$sheet->getCell([$columnIndex ++, $rowIndex])->setValue($cuenta->anterior);
$sheet->getCell([$columnIndex ++, $rowIndex])->setValue($cuenta->actual);
$sheet->getCell([$columnIndex ++, $rowIndex])->setValue("=F{$rowIndex}-E{$rowIndex}");
$sheet->getCell([$columnIndex ++, $rowIndex])->setValue($cuenta->ffmm);
$sheet->getCell([$columnIndex ++, $rowIndex])->setValue($cuenta->deposito);
$sheet->getCell([$columnIndex, $rowIndex])->setValue("=SUM(F{$rowIndex},H{$rowIndex}:I{$rowIndex})");
}
protected function fillTotals(PhpSpreadsheet\Worksheet\Worksheet $sheet, int $startRow, int $finalRow): void
{
$rowIndex = $finalRow + 1;
$sheet->getCell("B{$rowIndex}")->setValue('TOTAL');
foreach (range('E', 'N') as $columnIndex) {
$sheet->getCell("{$columnIndex}{$rowIndex}")->setValue("=SUBTOTAL(109,{$columnIndex}{$startRow}:{$columnIndex}{$finalRow})");
}
$styles = [
'font' => [
'bold' => true
],
'fill' => [
'fillType' => PhpSpreadsheet\Style\Fill::FILL_SOLID,
'startColor' => [
'argb' => 'FFD9D9D9'
]
],
'borders' => [
'outline' => [
'borderStyle' => PhpSpreadsheet\Style\Border::BORDER_THIN,
'color' => [
'argb' => PhpSpreadsheet\Style\Color::COLOR_BLACK
]
]
]
];
$sheet->getStyle("B{$rowIndex}:N{$rowIndex}")->applyFromArray($styles);
}
protected function setPageSetup(PhpSpreadsheet\Worksheet\Worksheet $sheet, int $finalRow): void
{
$sheet->getPageSetup()
->setPrintArea("B2:V{$finalRow}")
->setFitToWidth(1)
->setPaperSize(PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_LEGAL)
->setOrientation(PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE);
$sheet->setShowGridlines(false);
$sheet->getSheetView()
->setView(PhpSpreadsheet\Worksheet\SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW)
->setZoomScale(70);
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace Incoviba\Service\Contabilidad\Informe\Tesoreria;
use DateTimeInterface;
class PDF
{
public function build(DateTimeInterface $fecha, array $data): void
{
}
}

View File

@ -4,20 +4,25 @@ namespace Incoviba\Service\Contabilidad;
use DateTimeInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Implement\Exception;
use Incoviba\Repository;
use Incoviba\Service;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
use function Symfony\Component\Translation\t;
use Incoviba\Common\Ideal;
class Nubox
class Nubox extends Ideal\Service
{
public function __construct(protected Repository\Nubox $nuboxRepository,
public function __construct(protected LoggerInterface $logger,
protected Repository\Nubox $nuboxRepository,
protected Service\Redis $redisService,
protected ClientInterface $client,
protected RequestFactoryInterface $requestFactory,
protected string $api_url) {}
protected string $api_url)
{
parent::__construct($logger);
}
protected array $tokens;
public function getToken(int $inmobiliaria_rut): string
@ -120,7 +125,7 @@ class Nubox
$uri = 'contabilidad/libro-diario?' . http_build_query($query);
$response = $this->send($uri, $inmobiliaria_rut);
if ($response->getStatusCode() !== 200) {
error_log(var_export($uri,true).PHP_EOL,3,'/logs/debug');
$this->logger->debug($uri);
throw new Exception\HttpResponse($response->getReasonPhrase(), $response->getStatusCode());
}
return json_decode($response->getBody()->getContents(), JSON_OBJECT_AS_ARRAY);

View File

@ -25,12 +25,12 @@ class Format
{
return "{$this->number($number, $decimal_places)}%";
}
public function pesos(string $valor): string
public function pesos(string $valor, int $decimal_places = 0): string
{
return "$ {$this->number($valor)}";
return "$ {$this->number($valor, $decimal_places)}";
}
public function ufs(string $valor): string
public function ufs(string $valor, int $decimal_places = 2): string
{
return "{$this->number($valor, 2)} UF";
return "{$this->number($valor, $decimal_places)} UF";
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace Incoviba\Service;
use Incoviba\Common\Ideal;
use Psr\Log\LoggerInterface;
class Informe extends Ideal\Service
{
public function __construct(LoggerInterface $logger, protected string $folder)
{
parent::__construct($logger);
if (!file_exists($this->folder)) {
mkdir($this->folder);
}
}
protected array $informes;
public function register(string $name, string $informeClass): Informe
{
$this->informes[$name] = $informeClass;
return $this;
}
public function build(string $type, string $filename, string $title, array $data): void
{
$informe = new $this->informes[$type]();
$filename = implode(DIRECTORY_SEPARATOR, [$this->folder, "{$filename}.xlsx"]);
$informe->setFilename($filename);
$informe->setTitle($title);
$informe->addData($data);
$informe->build();
}
}

View File

@ -0,0 +1,63 @@
<?php
namespace Incoviba\Service\Informe;
use PhpOffice\PhpSpreadsheet;
use Incoviba\Common\Define;
class Excel implements Define\Informe
{
protected string $title;
protected string $filename;
protected array $data;
public function setTitle(string $title): Excel
{
$this->title = $title;
return $this;
}
public function setFilename(string $filename): Excel
{
$this->filename = $filename;
return $this;
}
public function addData(array $rows): Excel
{
foreach ($rows as $row) {
$this->addRow($row);
}
return $this;
}
public function addRow(array $row): Excel
{
foreach ($row as $cell) {
$this->addCell($cell);
}
return $this;
}
public function addCell(PhpSpreadsheet\Cell\Cell $cell): Excel
{
$this->data []= $cell;
return $this;
}
public function build(): void
{
$spreadsheet = new PhpSpreadsheet\Spreadsheet();
$spreadsheet->getProperties()
->setCreator('admin@incoviba.cl')
->setSubject($this->title)
->setCompany('Incoviba')
->setTitle($this->title);
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle($this->title);
foreach ($this->data as $rowIndex => $row) {
foreach ($row as $columnIndex => $cell) {
$sheet->getCell([$columnIndex + 1, $rowIndex + 1])->setValue($cell);
}
}
$writer = PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save($this->filename);
}
}

View File

@ -7,9 +7,12 @@ use DateInterval;
use Incoviba\Common\Define\Money\Provider;
use Incoviba\Common\Implement\Exception\EmptyResponse;
use Incoviba\Service\Money\MiIndicador;
use Psr\Log\LoggerInterface;
class Money
{
public function __construct(protected LoggerInterface $logger) {}
protected array $providers;
public function register(string $name, Provider $provider): Money
{
@ -49,4 +52,13 @@ class Money
return 0;
}
}
public function getUSD(DateTimeInterface $dateTime): float
{
try {
return $this->getProvider('usd')->get(MiIndicador::USD, $dateTime);
} catch (EmptyResponse $exception) {
$this->logger->critical($exception);
return 0;
}
}
}

View File

@ -11,7 +11,7 @@ class MiIndicador implements Provider
{
const UF = 'uf';
const IPC = 'ipc';
const USD = 'dolar_intercambio';
const USD = 'dolar';
public function __construct(protected ClientInterface $client) {}

View File

@ -0,0 +1,43 @@
<?php
namespace Incoviba\Service;
use DateTimeInterface;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal\Service;
use Incoviba\Common\Implement;
use Incoviba\Repository;
use Incoviba\Model;
class Movimiento extends Service
{
public function __construct(LoggerInterface $logger, protected Repository\Movimiento $movimientoRepository,
protected Repository\Movimiento\Detalle $detalleRepository)
{
parent::__construct($logger);
}
public function getById(int $movimiento_id): Model\Movimiento
{
return $this->process($this->movimientoRepository->fetchById($movimiento_id));
}
public function setDetalles(Model\Movimiento $movimiento, array $data): Model\Movimiento
{
try {
$detalles = $this->detalleRepository->fetchByMovimiento($movimiento->id);
$this->detalleRepository->edit($detalles, $data);
} catch (Implement\Exception\EmptyResult) {
$data['movimiento_id'] = $movimiento->id;
$detalles = $this->detalleRepository->create($data);
$this->detalleRepository->save($detalles);
}
return $movimiento;
}
public function process(Model\Movimiento $movimiento): Model\Movimiento
{
$movimiento->addFactory('detalles', (new Implement\Repository\Factory())->setCallable(function(int $movimiento_id) {
return $this->detalleRepository->fetchByMovimiento($movimiento_id);
})->setArgs(['movimiento_id' => $movimiento->id]));
return $movimiento;
}
}

View File

@ -54,10 +54,10 @@ class Search
}
protected function find(string $query, string $tipo): array
{
preg_match_all('/["\']([\s\w]+)["\']|(\w+)/iu', $query, $matches, PREG_SET_ORDER | PREG_UNMATCHED_AS_NULL);
preg_match_all('/["\']([\s\w\-]+)["\']|([\w\-]+)/iu', $query, $matches, PREG_SET_ORDER | PREG_UNMATCHED_AS_NULL);
$queries = array_map(function($match) {
array_shift($match);
$valid = array_filter($match, function($line) {return $line !== null;});
$valid = array_filter($match, function($line) {return $line !== null and trim($line); });
return implode(' ', $valid);
}, $matches);
$tiposUnidades = $this->getTiposUnidades();
@ -142,7 +142,7 @@ class Search
}
protected function findPago(string $query): array
{
if ($query != 0) {
if ((int) $query === 0) {
return [];
}
$methods = [

34
app/src/Service/USD.php Normal file
View File

@ -0,0 +1,34 @@
<?php
namespace Incoviba\Service;
use DateTimeInterface;
use DateTimeImmutable;
use Incoviba\Common\Implement\Exception\EmptyRedis;
class USD
{
protected string $redisKey = 'usd';
public function __construct(protected Redis $redisService, protected Money $moneyService) {}
public function get(?DateTimeInterface $date = null): float
{
if ($date === null) {
$date = new DateTimeImmutable();
}
$usds = [];
try {
$usds = json_decode($this->redisService->get($this->redisKey), JSON_OBJECT_AS_ARRAY);
if (!isset($usds[$date->format('Y-m-d')])) {
throw new EmptyRedis($this->redisKey);
}
$usd = $usds[$date->format('Y-m-d')];
} catch (EmptyRedis) {
$usd = $this->moneyService->getUSD($date);
$usds[$date->format('Y-m-d')] = $usd;
ksort($usds);
$this->redisService->set($this->redisKey, json_encode($usds), 60 * 60 * 24 * 30);
}
return $usd;
}
}

View File

@ -2,14 +2,16 @@
namespace Incoviba\Service;
use DateTimeImmutable;
use Incoviba\Common\Ideal\Service;
use Incoviba\Common\Implement;
use Incoviba\Repository;
use Incoviba\Model;
use PhpParser\Node\Expr\AssignOp\Mod;
use Psr\Log\LoggerInterface;
class Venta
class Venta extends Service
{
public function __construct(
LoggerInterface $logger,
protected Repository\Venta $ventaRepository,
protected Repository\Venta\EstadoVenta $estadoVentaRepository,
protected Repository\Venta\TipoEstadoVenta $tipoEstadoVentaRepository,
@ -17,6 +19,7 @@ class Venta
protected Repository\Venta\Escritura $escrituraRepository,
protected Repository\Venta\Pago $pagoRepository,
protected Repository\Venta\EstadoPago $estadoPagoRepository,
protected Venta\FormaPago $formaPagoService,
protected Venta\Propietario $propietarioService,
protected Venta\Propiedad $propiedadService,
protected Venta\Pie $pieService,
@ -25,7 +28,9 @@ class Venta
protected Venta\BonoPie $bonoPieService,
protected Venta\Pago $pagoService,
protected Money $moneyService
) {}
) {
parent::__construct($logger);
}
public function getById(int $venta_id): Model\Venta
{
@ -51,6 +56,10 @@ class Venta
$ventas = $this->ventaRepository->fetchByUnidad($unidad, $tipo);
return array_map([$this, 'process'], $ventas);
}
public function getByUnidadId(int $unidad_id): Model\Venta
{
return $this->process($this->ventaRepository->fetchByUnidadId($unidad_id));
}
public function getByPropietario(string $propietario): array
{
$ventas = $this->ventaRepository->fetchByPropietario($propietario);
@ -66,9 +75,20 @@ class Venta
$ventas = $this->ventaRepository->fetchEscriturasByProyecto($proyecto_id);
return array_map([$this, 'process'], $ventas);
}
public function getByIdForSearch(int $venta_id): array
{
return $this->ventaRepository->fetchByIdForSearch($venta_id);
}
public function getByIdForList(int $venta_id): array
{
return $this->ventaRepository->fetchByIdForList($venta_id);
}
protected function process(Model\Venta $venta): Model\Venta
{
$venta->addFactory('formaPago', (new Implement\Repository\Factory())
->setCallable([$this->formaPagoService, 'getByVenta'])
->setArgs(['venta_id' => $venta->id]));
$venta->addFactory('estados', (new Implement\Repository\Factory())
->setCallable([$this->estadoVentaRepository, 'fetchByVenta'])
->setArgs([$venta->id]));
@ -89,7 +109,7 @@ class Venta
'propietario' => $propietario->rut,
'propiedad' => $propiedad->id,
'fecha' => $fecha->format('Y-m-d'),
'valor_uf' => $data['valor'],
'valor_uf' => $this->cleanValue($data['valor']),
'fecha_ingreso' => (new DateTimeImmutable())->format('Y-m-d'),
'uf' => $data['uf']
];
@ -218,7 +238,8 @@ class Venta
}
protected function addFormaPago(array $data): Model\Venta\FormaPago
{
$fields = [
return $this->formaPagoService->add($data);
/*$fields = [
'pie',
'subsidio',
'credito',
@ -232,9 +253,9 @@ class Venta
$forma_pago->{$name} = $obj;
}
}
return $forma_pago;
return $forma_pago;*/
}
protected function addPie(array $data): Model\Venta\Pie
/*protected function addPie(array $data): Model\Venta\Pie
{
$fields = array_fill_keys([
'fecha_venta',
@ -249,6 +270,7 @@ class Venta
'cuotas',
'uf'
], $filtered_data);
$mapped_data['valor'] = $this->cleanValue($mapped_data['valor']);
return $this->pieService->add($mapped_data);
}
protected function addSubsidio(array $data): Model\Venta\Subsidio
@ -295,7 +317,7 @@ class Venta
'valor'
], $filtered_data);
return $this->bonoPieService->add($mapped_data);
}
}*/
protected function addEstado(Model\Venta $venta, Model\Venta\TipoEstadoVenta $tipoEstadoVenta, array $data): void
{
$fecha = new DateTimeImmutable($data['fecha']);
@ -307,6 +329,13 @@ class Venta
$estado = $this->estadoVentaRepository->create($estadoData);
$this->estadoVentaRepository->save($estado);
}
protected function cleanValue($value): float
{
if ((float) $value == $value) {
return (float) $value;
}
return (float) str_replace(['.', ','], ['', '.'], $value);
}
public function escriturar(Model\Venta $venta, array $data): bool
{

View File

@ -12,4 +12,8 @@ class BonoPie
{
return new Model\Venta\BonoPie();
}
public function getByVenta(int $venta_id): Model\Venta\BonoPie
{
return $this->bonoPieRepository->fetchByVenta($venta_id);
}
}

View File

@ -2,20 +2,30 @@
namespace Incoviba\Service\Venta;
use DateTimeImmutable;
use Incoviba\Common\Ideal\Service;
use Incoviba\Repository;
use Incoviba\Model;
use Incoviba\Service\Money;
use Psr\Log\LoggerInterface;
class Credito
class Credito extends Service
{
public function __construct(
LoggerInterface $logger,
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
) {}
) {
parent::__construct($logger);
}
public function getByVenta(int $venta_id): Model\Venta\Credito
{
return $this->creditoRepository->fetchByVenta($venta_id);
}
public function add(array $data): Model\Venta\Credito
{
@ -30,6 +40,27 @@ class Credito
]);
return $this->creditoRepository->save($credito);
}
public function edit(Model\Venta\Credito $credito, array $data): Model\Venta\Credito
{
$uf = $this->moneyService->getUF($credito->pago->fecha);
if (array_key_exists('fecha', $data)) {
$fecha = new DateTimeImmutable($data['fecha']);
$data['fecha'] = $fecha->format('Y-m-d');
$uf = $this->moneyService->getUF($fecha);
$data['uf'] = $uf;
}
if (array_key_exists('valor', $data)) {
$data['valor'] = round(((float) $data['valor']) * $uf);
}
$filteredData = array_intersect_key($data, array_fill_keys([
'fecha',
'uf',
'valor',
'banco'
], 0));
$credito->pago = $this->pagoRepository->edit($credito->pago, $filteredData);
return $this->creditoRepository->edit($credito, $filteredData);
}
protected function addPago(array $data): Model\Venta\Pago
{
$pago = $this->pagoRepository->create($data);

View File

@ -0,0 +1,143 @@
<?php
namespace Incoviba\Service\Venta;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Implement;
use Incoviba\Common\Ideal;
use Incoviba\Model;
use Incoviba\Repository;
class FormaPago extends Ideal\Service
{
public function __construct(LoggerInterface $logger,
protected Pie $pieService,
protected BonoPie $bonoPieService,
protected Credito $creditoService,
protected Repository\Venta\Escritura $escrituraRepository,
protected Subsidio $subsidioService,
protected Pago $pagoService)
{
parent::__construct($logger);
}
public function getByVenta(int $venta_id): Model\Venta\FormaPago
{
$formaPago = new Model\Venta\FormaPago();
try {
$formaPago->pie = $this->pieService->getByVenta($venta_id);
} catch (Implement\Exception\EmptyResult) {}
try {
$formaPago->bonoPie = $this->bonoPieService->getByVenta($venta_id);
} catch (Implement\Exception\EmptyResult) {}
try {
$formaPago->credito = $this->creditoService->getByVenta($venta_id);
} catch (Implement\Exception\EmptyResult) {}
try {
$formaPago->escritura = $this->escrituraRepository->fetchByVenta($venta_id);
} catch (Implement\Exception\EmptyResult) {}
try {
$formaPago->subsidio = $this->subsidioService->getByVenta($venta_id);
} catch (Implement\Exception\EmptyResult) {}
try {
$formaPago->devolucion = $this->pagoService->getDevolucionByVenta($venta_id);
} catch (Implement\Exception\EmptyResult) {}
return $formaPago;
}
public function add(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}"])) {
try {
$method = 'add' . str_replace(' ', '', ucwords(str_replace('_', ' ', $name)));
$obj = $this->{$method}($data);
$forma_pago->{$name} = $obj;
} catch (\Error $error) {
$this->logger->critical($error);
}
}
}
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);
$this->logger->critical(var_export($filtered_data,true));
$mapped_data = array_combine([
'fecha',
'valor',
'cuotas',
'uf'
], $filtered_data);
$mapped_data['valor'] = $this->cleanValue($mapped_data['valor']);
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);
}
protected function cleanValue($value): float
{
if ((float) $value == $value) {
return (float) $value;
}
return (float) str_replace(['.', ','], ['', '.'], $value);
}
}

View File

@ -109,6 +109,10 @@ class Pago
{
return [];
}
public function getDevolucionByVenta(int $venta_id): Model\Venta\Pago
{
return $this->process($this->pagoRepository->fetchDevolucionByVenta($venta_id));
}
public function add(array $data): Model\Venta\Pago
{

View File

@ -17,6 +17,10 @@ class Pie
{
return $this->process($this->pieRepository->fetchById($pie_id));
}
public function getByVenta(int $venta_id): Model\Venta\Pie
{
return $this->process($this->pieRepository->fetchByVenta($venta_id));
}
public function add(array $data): Model\Venta\Pie
{

Some files were not shown because too many files have changed in this diff Show More