199 Commits

Author SHA1 Message Date
1d20d63294 Merge pull request 'feature/cuotas-abono-escritura' (#2) from feature/cuotas-abono-escritura into develop
Reviewed-on: #2
2024-11-29 17:24:16 +00:00
39da754d8b FIX: Cuotas se agregan sin UF, desface en la tabla 2024-11-29 14:22:05 -03:00
02fc372610 Merge branch 'develop' into feature/cuotas-abono-escritura 2024-11-29 14:13:42 -03:00
8aa1c787f4 Merge pull request 'feature/cuotas-abono-escritura' (#1) from feature/cuotas-abono-escritura into develop
Reviewed-on: #1
2024-11-28 22:24:48 +00:00
8028b673fb FIX: Editar cuotas 2024-11-28 19:14:14 -03:00
52de72b507 Sumar cuotas. 2024-11-28 17:38:21 -03:00
f4b8634cb4 Agregar y editar abono cuotas. 2024-11-28 17:12:35 -03:00
4f0a56c711 FIX: migracion 2024-11-28 15:12:30 -03:00
3ff5f3f1a6 Vistas 2024-11-28 14:07:07 -03:00
151d1d0209 Rutoa 2024-11-28 14:06:58 -03:00
b13f8a5b20 Numero de cuota 2024-11-28 14:06:44 -03:00
1d268f9a94 Controlador 2024-11-28 14:06:12 -03:00
a844589d7f Creacion de tabla 2024-11-28 14:06:00 -03:00
83ea955d89 Cuota abono en venta 2024-11-28 12:02:49 -03:00
4392f61db9 Cuota abono a escritura 2024-11-28 12:02:02 -03:00
a2352d79f9 Testing conectado a adminer 2024-11-28 11:41:19 -03:00
56d3a26cff Datos Persona 2024-11-28 11:41:03 -03:00
cc5c90e2c0 Cleanup tests 2024-11-28 11:40:53 -03:00
f9e079cc42 Migraciones 2024-11-20 21:26:03 -03:00
3f65a5dbd9 Composer mas libre 2024-11-20 20:49:32 -03:00
28036fdd05 FIX: Si no conecta con Nubox solo se reajusta el terreno. 2024-11-20 20:49:05 -03:00
54f3b95b88 FIX: Fecha comparación para terreno a fin de diciembre 2024-11-20 17:11:03 -03:00
1e2bd617fa FIX: Fecha comparación para terreno 2024-11-20 12:19:04 -03:00
62e7001fba FIX: Problemas de curl 2024-11-20 11:51:06 -03:00
bc8aa02236 FIX: Problemas de curl 2024-11-20 11:29:02 -03:00
5b30c0e36c FIX: Revert 2024-11-20 10:59:21 -03:00
da1fb26647 FIX: SSL Nubox mas antiguo 2024-11-20 10:52:55 -03:00
b1609465a9 FIX: Search venta 2024-11-19 15:54:14 -03:00
cb2edb1543 Agregar Bono Pie 2024-11-18 23:25:20 -03:00
1e1994264e Search con resumen de tipologias 2024-11-18 22:25:42 -03:00
f2cc0a8c47 Actualizacion de PHP 2024-11-12 21:52:43 -03:00
e474123699 Merge remote-tracking branch 'origin/develop' into develop 2024-11-12 21:52:25 -03:00
c3a99d5939 Migraciones y testeo 2024-11-12 21:52:10 -03:00
0212b3e405 Migraciones y testeo 2024-11-12 21:51:56 -03:00
e4ffcb52d8 FIX: eventos no se actualizaban con cambio de pagina en DataTables 2024-11-12 21:27:33 -03:00
37c28c3080 Editar estado cuota 2024-11-06 21:28:36 -03:00
d154212732 FIX: Editar pago 2024-11-06 19:55:49 -03:00
be410daa8b Datos para manejar mejor los requests externos. 2024-11-01 17:04:24 -03:00
38202d1382 FIX: UF despues de obtener estado. 2024-10-31 17:15:51 -03:00
1b99358597 Eliminar log innecesario 2024-10-31 17:15:38 -03:00
6107861381 Login log independiente 2024-10-31 17:15:23 -03:00
3d5799ae58 HTTPS 2024-10-31 16:31:42 -03:00
d649e03684 Logout en valod uris 2024-10-28 13:10:49 -03:00
fc3d25dd18 FIX: Cuotas hoy y pendientes. 2024-10-25 21:48:19 -03:00
532e0ec601 FIX: Reorden CORS 2024-10-25 18:56:14 -03:00
3e9f9a3fef FIX: CORS other requests 2024-10-25 18:40:59 -03:00
d1b255aa8b FIX: CORS headers 2024-10-25 18:38:23 -03:00
93a0832800 CORS authorization 2024-10-25 18:37:05 -03:00
4894809105 No usar schema para revision de url 2024-10-25 18:33:50 -03:00
389e60980e Editar cuota 2024-10-23 08:39:11 -03:00
fe6a01b2fb Redis options 2024-10-18 21:21:35 -03:00
2b6a8b35a5 Redis parameters 2024-10-18 21:15:13 -03:00
30a4d66be5 Redis username 2024-10-18 21:01:41 -03:00
089579f39f Redis password 2024-10-18 20:57:48 -03:00
63ea21f105 Comparar glosa en 75% 2024-10-10 18:48:44 -03:00
33409a18e3 Comparar glosa en mismo tamaño 2024-10-08 18:57:19 -03:00
2592794a49 Alertas 2024-10-03 21:11:06 -03:00
196c5b947f Modernizacion de repo Cuota 2024-10-03 20:38:35 -03:00
b9c2972fe9 Cuando existen cuotas asociadas a algun pie distintas al pie asociado 2024-10-01 17:35:23 -03:00
37015f7e95 PHP 8 2024-10-01 17:34:43 -03:00
c3b36dcdf7 Optimizacion 2024-10-01 17:34:27 -03:00
c68b773cbb FIX: Banco vacio 2024-10-01 17:33:29 -03:00
933e652dac FIX: centro_costo undefined 2024-10-01 13:20:23 -03:00
ff1e9ebb53 Optimizaciones 2024-10-01 13:11:46 -03:00
599880ae27 Editar movimientos 2024-10-01 13:11:15 -03:00
a4da8d8624 FIX: mes se ve raro 2024-09-24 21:10:57 -03:00
87dfb0ae6e Listar movimientos y exportar
TODO: editar
2024-09-24 21:02:28 -03:00
afbac7259a FIX: evitar correr funcion con valor vacio en Mapper 2024-09-24 13:26:41 -03:00
e2573f35d1 FIX: Officebanking mensual 2024-09-18 13:43:23 -03:00
b8d4b260b6 Timezone 2024-09-16 22:20:22 -03:00
ff06e70869 OfficeBanking usando isExcel y correccion en procesamiento de valores. 2024-09-16 22:13:38 -03:00
5e7326a4b6 Limpieza 2024-09-16 22:12:30 -03:00
26a227c8ae Itau funcionando para ByV BCI 2024-09-12 18:08:48 -03:00
5defd2b564 Itau funcionando para ByV y Vialcorp 2024-09-12 16:41:57 -03:00
74b15add36 Cartolas Security 2024-09-03 00:10:46 -04:00
d8d2cba308 Excel functions for Cartola Banco Service 2024-09-03 00:07:52 -04:00
5983a4b20f Parse rut and 0 centro_costo 2024-09-03 00:07:06 -04:00
6e4dd8180e FIX: Cartola::import string date 2024-08-27 18:17:59 -04:00
7447579ef0 Try Token 2024-08-27 14:51:54 -04:00
ccd5b296f3 Descriptions 2024-08-27 14:51:06 -04:00
095c33e8aa Command ContainerLoader 2024-08-27 14:50:45 -04:00
4604a9af48 Update Cartolas 2024-08-27 14:50:11 -04:00
55d879274c Try Tokens rout 2024-08-27 14:49:27 -04:00
85b529c22d Try Token 2024-08-27 14:49:15 -04:00
3ba45c48f5 Update Cartolas 2024-08-27 14:48:47 -04:00
552a4c7aca Update Cartolas 2024-08-27 14:48:21 -04:00
2070987403 Fetch by Cuenta 2024-08-27 14:47:21 -04:00
d9dab9c88d Configuracion de API 2024-08-27 14:46:57 -04:00
f9f133d3a9 Se extra getKey y configuraciones the paths 2024-08-27 14:46:03 -04:00
f85af642d2 API Service para manejo de token 2024-08-27 14:45:21 -04:00
f3d9b58ffb Agregar Cartolas al importar, y chequeo de Cartolas faltantes 2024-08-27 14:44:40 -04:00
8f682f7f13 Se agrega chequeo para cartola diaria 2024-08-27 14:43:17 -04:00
26e626074a Add sub Bancos to BCI and Santander 2024-08-26 15:26:10 -04:00
478b407646 Sub Banco for the Cartola Services 2024-08-26 15:25:45 -04:00
7d210601da Clean up 2024-08-26 15:25:13 -04:00
9563876b36 Process errors 2024-08-26 15:25:02 -04:00
d9e27d5af7 Move Cartola::import into the Service and added errors 2024-08-26 15:24:42 -04:00
936830ae64 Separate Banco::process pipe to be able to intervene in the middle 2024-08-26 15:23:22 -04:00
e93149456a FIX: API not added by git 2024-07-26 23:57:04 -04:00
93a15ef1e4 Add UF Update 2024-07-26 23:33:40 -04:00
6950413eec FIX: logger in API Middleware 2024-07-26 23:31:08 -04:00
9162ed240e FIX: testing 2024-07-26 23:20:17 -04:00
84861b5e57 Cli user 2024-07-26 23:15:48 -04:00
43bb7a83c8 FIX: tesoreria no cargaba datos 2024-07-25 12:52:48 -04:00
081187e3d3 Mensaje de error 2024-07-25 12:51:25 -04:00
b2f1bd5ba0 FIX: Importar cartolas correctamente. 2024-07-18 21:25:10 -04:00
a471a1083e Merge branch 'temp' into develop 2024-07-17 22:34:20 -04:00
8e7f43e487 Subir cartolas procesadas 2024-07-17 22:33:33 -04:00
390e79ad6d 2024-06-18 2024-07-16 16:17:24 -04:00
6169089475 FIX: Cambio fecha factura 2024-07-10 15:40:59 -04:00
a7ce78a3fb FIX: IPC asociado a fecha de UF 2024-07-10 15:32:05 -04:00
6f023928e8 FIX: Actualizacion de IPC al cambiar fecha facturas 2024-07-09 19:52:39 -04:00
a4b7183de1 FIX: UF para Pago actualizado 2024-07-09 11:58:49 -04:00
a428aeebe1 Agregar, editar y borrar comentarios 2024-07-04 18:09:25 -04:00
fc543729d2 FIX: Propietario no tomaba en consideracion comuna para direccion 2024-07-04 16:28:01 -04:00
8cec046d66 FIX 2024-07-04 16:23:39 -04:00
1f730fb7f3 FIX: comentario en redirect y cleanup 2024-07-04 16:19:54 -04:00
964d8d4237 Poder editar propietario de ventas, cambiando el propietario en si 2024-07-04 15:42:10 -04:00
0d5c9efd68 FIX: Mostrar unidad principal en busqueda 2024-07-03 17:20:26 -04:00
d68eba5697 Limpieza de input de valor y filtro de datos a nivel Repo 2024-07-03 15:13:13 -04:00
d5b9be0196 FIX: Division por 0 2024-07-03 12:19:44 -04:00
d0d99eaa81 FIX: IPC terreno hasta 2 meses antes de factura 2024-06-27 12:33:02 -04:00
15e9a54c7e FIX: venta sin departamentos 2024-06-11 18:16:34 -04:00
b7e9a17586 Se cambia el total de acuerdo a informacion de Contador 2024-06-11 18:07:12 -04:00
61533b5a4c Cambio en diseño de inicio 2024-06-11 13:21:50 -04:00
5864e7ee94 Mapper default null 2024-06-11 12:07:57 -04:00
3fc7aa88dc FIX: IPC en factura 2024-06-10 21:41:11 -04:00
1caa62500a FIX: unidadService -> propiedadUnidadService 2024-06-10 15:53:05 -04:00
27e88761e0 Mysql log retain 2024-06-07 17:18:20 -04:00
b27a6fab33 Propiedad con unidad_principal 2024-06-07 17:16:58 -04:00
fa978728ce Optimizacion de monedas 2024-05-16 21:23:24 -04:00
256a3d2459 Fechas 2024-05-14 19:43:14 -04:00
f8f5796a66 FIX: columnas al exportar 2024-05-14 13:09:59 -04:00
0e0b783a80 Sigla sociedad 2024-05-13 16:58:33 -04:00
a5125aff74 Movimientos filtrados y editables 2024-05-13 16:54:59 -04:00
71bbe7f2d7 Cuotas compactas 2024-05-10 10:48:19 -04:00
e2c68a14d1 FIX: removed self in asociados 2024-05-09 21:04:51 -04:00
5e51562aec FIX: proporcion pie pagado 2024-05-09 21:00:49 -04:00
7719a5c614 Una fecha para facturas por venta 2024-04-30 20:27:05 -04:00
05b9a3ad8a FIX: valor vacio 2024-04-30 11:35:04 -04:00
665bed8553 Propiedad principal 2024-04-30 11:28:18 -04:00
9c024d1ef7 Matriz facturacion 2024-04-29 18:35:44 -04:00
94d618b2a1 Factura con fecha de UF 2024-04-29 10:45:19 -04:00
4786ee2552 Factura multiple con cambio de fecha 2024-04-28 23:01:55 -04:00
39d8d4943e FIX: No estaban todas las disponibles 2024-04-25 21:00:14 -04:00
e63a3d0077 Disable submit button 2024-04-25 19:56:35 -04:00
d580cc1a11 Favicon 2024-04-25 19:07:21 -04:00
86034a6349 FIX: objeto ->array 2024-04-23 15:35:51 -04:00
97ab5acf3e Agregar usuario a log 2024-04-23 14:35:04 -04:00
435180ebaf Ids de ventas 2024-04-23 14:22:32 -04:00
d2511901ec Facturacion 2024-04-19 23:19:35 -04:00
9388dc17fc Facturacion y Terreno 2024-04-18 20:30:26 -04:00
a33dd341cd Facturacion 2024-04-15 20:13:15 -04:00
8e4b5eaaf8 Listado de Movimientos 2024-04-10 21:18:33 -04:00
91679b164f DAP y saldo anterior 2024-04-05 20:23:58 -03:00
3c7e4b9ef4 Orden sociedades 2024-04-05 17:13:21 -03:00
20045c9a64 Formatos 2024-04-05 16:35:18 -03:00
47d43f504d Informes anteriores y siguientes 2024-04-05 14:48:17 -03:00
0502b8e735 agentes -> proveedores 2024-04-05 14:45:54 -03:00
905e8263bc Login redirect 307 (temporary) 2024-04-03 13:26:12 -03:00
8710c8a111 Agentes 2024-04-02 23:02:52 -03:00
5d9ac2bc51 Tests results in cache 2024-04-02 20:19:59 -03:00
062e0543e4 Ignore app/bin 2024-04-02 19:58:58 -03:00
b97916cfc4 Menu 2024-04-02 19:04:57 -03:00
7af9cafdb6 Moderno 2024-04-02 19:04:26 -03:00
84a2fbd119 Log DB 2024-04-02 13:50:08 -03:00
bc9c71870c No remove nocache 2024-03-26 17:09:43 -03:00
912e8624b2 Nocache after ready 2024-03-26 16:57:07 -03:00
86406bf027 Fecha cuota 2024-03-26 16:41:33 -03:00
7b8d44e8c8 Reordenar 2024-03-26 13:59:18 -03:00
c10f2e5912 Cuotas con detalle de UF y de Pies asociados 2024-03-26 13:21:47 -03:00
bef0a22758 Bin folder 2024-03-26 13:17:08 -03:00
092eb95f06 Cache phpunit 2024-03-26 09:38:35 -03:00
5f56022109 Restructura contabilidad 2024-03-26 09:38:20 -03:00
4b3397dd63 Estado cuenta 2024-03-21 23:10:18 -03:00
529f9e32a1 Inmobiliarias por razon y cuadratura 2024-03-21 22:09:15 -03:00
939adf126f FIX: multiples cartolas 2024-03-21 22:08:30 -03:00
63400af1db Cartola diaria adds all cartolas 2024-03-21 21:57:32 -03:00
019974614c FIX: Saldos cartola diaria 2024-03-21 21:18:40 -03:00
735c341729 FIX: Login, change in separator defined 2024-03-20 23:29:09 -03:00
444ff687fc Base API, and more solid key and check 2024-03-20 23:07:49 -03:00
f3a5fa2cdc Tests 2024-03-20 23:06:38 -03:00
2ed265dcf1 Merge branch 'testing' into develop 2024-03-20 21:11:32 -03:00
dbae630fdd Bold footer 2024-03-20 21:04:43 -03:00
d69976d015 FIX: Remove cache from login when redirecting 2024-03-20 20:55:34 -03:00
2ccbc31ae0 FIX: Auth had all paths starting with slash as valid 2024-03-20 20:48:05 -03:00
e50d80560c FIX: Auth missing from some routes 2024-03-20 20:43:53 -03:00
7cc0333876 Informe tesoreria busca ultima cartola ingresada 2024-03-20 20:22:54 -03:00
eb38236926 FIX: cartola BCI 2024-03-20 17:52:34 -03:00
85ef4dd60e Ignore testing cache 2024-03-20 15:00:54 -03:00
f1e29e3b0b Ignore testing results 2024-03-20 13:50:04 -03:00
6617a92f5f Tests 2024-03-20 13:49:58 -03:00
ca958b8a88 Testing dependencies 2024-03-20 13:45:53 -03:00
dc2e2c7f71 Cartola BCI 2024-03-18 17:54:27 -03:00
936fd2d1e1 Cuota vacia 2024-03-18 18:06:32 +00:00
7c6a397e31 CORS 2024-03-18 14:58:54 -03:00
7385225a2e FIX: Venta cargada sin formaPago 2024-03-15 13:09:58 -03:00
9c335fd350 FIX: Venta 2024-03-13 22:43:37 -03:00
57f9169cc7 Encriptar clave 2024-03-13 21:24:52 -03:00
341 changed files with 37037 additions and 2428 deletions

2
.gitignore vendored
View File

@ -10,3 +10,5 @@
**/.idea/
**/upload?/
**/informe?/
**/.phpunit.cache/
**/coverage/

View File

@ -1,14 +1,18 @@
FROM php:8.1-fpm
FROM php:8.2-fpm
ENV TZ=America/Santiago
RUN apt-get update && apt-get install -y --no-install-recommends libzip-dev libicu-dev git libpng-dev unzip tzdata \
&& rm -r /var/lib/apt/lists/*
RUN docker-php-ext-install pdo pdo_mysql zip intl gd bcmath
RUN pecl install xdebug-3.1.3 \
&& docker-php-ext-enable xdebug
&& rm -r /var/lib/apt/lists/* \
&& docker-php-ext-install pdo pdo_mysql zip intl gd bcmath \
&& pecl install xdebug-3.3.2 \
&& docker-php-ext-enable xdebug \
&& echo $TZ > /etc/timezone
COPY ./php-errors.ini /usr/local/etc/php/conf.d/docker-php-errors.ini
COPY ./php-xdebug.ini /usr/local/etc/php/conf.d/docker-php-xdebug.ini
COPY ./php-memory.ini /usr/local/etc/php/conf.d/docker-php-memory.ini
COPY ./php-timezone.ini /usr/local/etc/php/conf.d/docker-php-timezone.ini
COPY --from=composer /usr/bin/composer /usr/bin/composer

9
api.compose.yml Normal file
View File

@ -0,0 +1,9 @@
services:
httpclient:
profiles:
- testing
container_name: incoviba_client
image: flawiddsouza/restfox
restart: unless-stopped
ports:
- "${HTTPCLIENT_PORT:-4004}:4004"

1
app/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
**/bin

14
app/.phpunit-watcher.yml Normal file
View File

@ -0,0 +1,14 @@
watch:
directories:
- src
- tests
- common
- resources
fileMask: '*.php'
notifications:
passingTests: false
failingTests: false
hideManual: true
phpunit:
arguments: '--log-events-text /logs/output.txt --stop-on-failure'
timeout: 180

View File

@ -5,6 +5,11 @@ use Psr\Http\Message\UploadedFileInterface;
interface Banco
{
/**
* Process bank movements for database inserts
* @param UploadedFileInterface $file
* @return array
*/
public function process(UploadedFileInterface $file): array;
}

View File

@ -6,5 +6,5 @@ use Incoviba\Model;
interface Exporter
{
public function export(Model\Inmobiliaria $inmobiliaria, Model\Banco $banco, DateTimeInterface $mes, array $movimientos): string;
public function export(Model\Inmobiliaria $inmobiliaria, Model\Contabilidad\Banco $banco, DateTimeInterface $mes, array $movimientos): string;
}

View File

@ -9,9 +9,55 @@ abstract class Banco extends Service implements Define\Cartola\Banco
{
public function process(UploadedFileInterface $file): array
{
$data = $this->parseFile($file);
$filename = $this->processUploadedFile($file);
$data = $this->processFile($filename);
return $this->mapColumns($data);
}
/**
* There are banks that need some post-processing
* @param array $movimientos
* @return array
*/
public function processMovimientosDiarios(array $movimientos): array
{
return $movimientos;
}
/**
* Move the UploadedFile into a temp file from getFilename
* @param UploadedFileInterface $uploadedFile
* @return string
*/
protected function processUploadedFile(UploadedFileInterface $uploadedFile): string
{
$filename = $this->getFilename($uploadedFile);
$uploadedFile->moveTo($filename);
return $filename;
}
/**
* Process the temp file from getFilename and remove it
* @param string $filename
* @return array
*/
protected function processFile(string $filename): array
{
$data = $this->parseFile($filename);
unlink($filename);
return $data;
}
/**
* Map columns from uploaded file data to database columns
* @param array $data
* @return array
*/
protected function mapColumns(array $data): array
{
$temp = [];
$columns = $this->columnMap();
foreach ($data as $row) {
$r = [];
foreach ($columns as $old => $new) {
@ -24,11 +70,24 @@ abstract class Banco extends Service implements Define\Cartola\Banco
}
return $temp;
}
public function processMovimientosDiarios(array $movimientos): array
{
return $movimientos;
}
/**
* Get filename where to move UploadedFile
* @param UploadedFileInterface $uploadedFile
* @return string
*/
abstract protected function getFilename(UploadedFileInterface $uploadedFile): string;
/**
* Mapping of uploaded file data columns to database columns
* @return array
*/
abstract protected function columnMap(): array;
abstract protected function parseFile(UploadedFileInterface $uploadedFile): array;
/**
* Translate uploaded file data to database data
* @param string $filename
* @return array
*/
abstract protected function parseFile(string $filename): array;
}

View File

@ -37,6 +37,9 @@ abstract class Repository implements Define\Repository
$this->connection->execute($query, [$model->id]);
}
/**
* @throws EmptyResult
*/
public function fetchById(int $id): Define\Model
{
$query = $this->connection->getQueryBuilder()
@ -45,6 +48,10 @@ abstract class Repository implements Define\Repository
->where("{$this->getKey()} = ?");
return $this->fetchOne($query, [$id]);
}
/**
* @throws EmptyResult
*/
public function fetchAll(null|string|array $ordering = null): array
{
$query = $this->connection->getQueryBuilder()
@ -161,4 +168,9 @@ abstract class Repository implements Define\Repository
}
return $results;
}
public function filterData(array $data): array
{
return $data;
}
}

View File

@ -6,7 +6,7 @@ use Throwable;
class EmptyResult extends Exception
{
public function __construct(string $query, ?Throwable $previous = null)
public function __construct(public string $query, ?Throwable $previous = null)
{
$message = "Empty results for {$query}";
$code = 700;

View File

@ -0,0 +1,19 @@
<?php
namespace Incoviba\Common\Implement\Exception;
use Throwable;
use Exception;
class HttpResponse extends Exception
{
public function __construct($reason = "", $message = "", $code = 0, Throwable $previous = null)
{
$this->reason = "HTTP Reason: {$reason}";
parent::__construct($message, $code, $previous);
}
protected string $reason;
public function getReason(): string
{
return $this->reason;
}
}

View File

@ -0,0 +1,60 @@
<?php
namespace Incoviba\Common\Implement\Log;
use PDOStatement;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\LogRecord;
use Monolog\Level;
use Incoviba\Common\Define\Connection;
class MySQLHandler extends AbstractProcessingHandler
{
private bool $initialized = false;
private PDOStatement $statement;
public function __construct(protected Connection $connection, protected int $retainDays = 90, int|string|Level $level = Level::Debug, bool $bubble = true)
{
parent::__construct($level, $bubble);
}
public function write(LogRecord $record): void
{
if (!$this->initialized) {
$this->initialized();
}
$this->cleanup();
$this->statement->execute([
'channel' => $record->channel,
'level' => $record->level->getName(),
'message' => $record->formatted,
'time' => $record->datetime->format('Y-m-d H:i:s.u'),
'context' => (count($record->context) > 0) ? json_encode($record->context, JSON_UNESCAPED_SLASHES) : '',
'extra' => (count($record->extra) > 0) ? json_encode($record->extra, JSON_UNESCAPED_SLASHES) : ''
]);
}
private function initialized(): void
{
$query = <<<QUERY
CREATE TABLE IF NOT EXISTS monolog (
channel VARCHAR(255),
level VARCHAR(100),
message LONGTEXT,
time DATETIME,
context LONGTEXT,
extra LONGTEXT
)
QUERY;
$this->connection->getPDO()->exec($query);
$query = <<<QUERY
INSERT INTO monolog (channel, level, message, time, context, extra)
VALUES (:channel, :level, :message, :time, :context, :extra)
QUERY;
$this->statement = $this->connection->getPDO()->prepare($query);
$this->initialized = true;
}
private function cleanup(): void
{
$query = "DELETE FROM monolog WHERE time < DATE_SUB(CURDATE(), INTERVAL {$this->retainDays} DAY)";
$this->connection->query($query);
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace Incoviba\Common\Implement\Log;
use Monolog\Formatter\JsonFormatter;
use Monolog\LogRecord;
class PDOFormatter extends JsonFormatter
{
public function __construct(int $batchMode = self::BATCH_MODE_JSON, bool $appendNewline = false, bool $ignoreEmptyContextAndExtra = false, bool $includeStacktraces = true)
{
parent::__construct($batchMode, $appendNewline, $ignoreEmptyContextAndExtra, $includeStacktraces);
}
public function format(LogRecord $record): string
{
$normalized = $this->normalize($record);
return $normalized['message'];
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace Incoviba\Common\Implement\Log;
use Monolog\LogRecord;
use Monolog\Processor\ProcessorInterface;
use Incoviba\Service;
class UserProcessor implements ProcessorInterface
{
public function __construct(protected Service\Login $loginService) {}
public function __invoke(LogRecord $record): LogRecord
{
if ($this->loginService->isIn()) {
$record->extra['user'] = $this->loginService->getUser()->name;
}
return $record;
}
}

View File

@ -1,8 +1,10 @@
<?php
namespace Incoviba\Common\Implement\Repository;
use Error;
use Closure;
use Incoviba\Common\Define;
use Incoviba\Common\Implement\Exception\EmptyResult;
class Mapper implements Define\Repository\Mapper
{
@ -46,7 +48,11 @@ class Mapper implements Define\Repository\Mapper
}
public function hasDefault(): bool
{
return isset($this->default);
try {
return isset($this->default) or $this->default === null;
} catch (Error) {
return false;
}
}
public function parse(Define\Model &$model, string $column, ?array $data): bool
@ -62,8 +68,16 @@ class Mapper implements Define\Repository\Mapper
}
$value = $data[$column];
if ($this->hasFunction()) {
if ($value !== null) {
if ($value !== null and $value !== '') {
try {
$value = ($this->function)($data);
} catch (EmptyResult $exception) {
if ($this->hasDefault()) {
$value = $this->default;
} else {
throw $exception;
}
}
} elseif ($this->hasDefault()) {
$value = $this->default;
}

View File

@ -1,21 +1,30 @@
{
"name": "incoviba/web",
"version": "2.0.0",
"type": "project",
"require": {
"berrnd/slim-blade-view": "^1.0",
"guzzlehttp/guzzle": "^7.8",
"monolog/monolog": "^3.4",
"nyholm/psr7": "^1.8",
"nyholm/psr7-server": "^1.0",
"php-di/php-di": "^7.0",
"php-di/slim-bridge": "^3.4",
"phpoffice/phpspreadsheet": "^1.29",
"predis/predis": "^2.2",
"slim/slim": "^4.11"
"ext-curl": "*",
"ext-gd": "*",
"ext-openssl": "*",
"ext-pdo": "*",
"berrnd/slim-blade-view": "^1",
"guzzlehttp/guzzle": "^7",
"monolog/monolog": "^3",
"nyholm/psr7": "^1",
"nyholm/psr7-server": "^1",
"php-di/php-di": "^7",
"php-di/slim-bridge": "^3",
"phpoffice/phpspreadsheet": "^3",
"predis/predis": "^2",
"robmorgan/phinx": "^0.16",
"slim/slim": "^4"
},
"require-dev": {
"kint-php/kint": "^5.1",
"phpunit/phpunit": "^10.2"
"fakerphp/faker": "^1",
"kint-php/kint": "^5",
"odan/phinx-migrations-generator": "^6",
"phpunit/phpunit": "^11",
"spatie/phpunit-watcher": "^1"
},
"authors": [
{
@ -30,6 +39,8 @@
}
},
"config": {
"sort-packages": true
"sort-packages": true,
"process-timeout": 0,
"bin-dir": "bin"
}
}

46
app/phinx.php Normal file
View File

@ -0,0 +1,46 @@
<?php
return
[
'paths' => [
'migrations' => '%%PHINX_CONFIG_DIR%%/resources/database/migrations',
'seeds' => '%%PHINX_CONFIG_DIR%%/resources/database/seeds'
],
'environments' => [
'default_migration_table' => 'phinxlog',
'default_environment' => 'development',
'production' => [
'adapter' => 'mysql',
'host' => $_ENV['DB_HOST'] ?? 'localhost',
'name' => $_ENV['DB_DATABASE'],
'user' => $_ENV['DB_USER'],
'pass' => $_ENV['DB_PASSWORD'],
'port' => '3306',
'charset' => 'utf8',
],
'development' => [
'adapter' => 'mysql',
'host' => $_ENV['DB_HOST'] ?? 'localhost',
'name' => $_ENV['DB_DATABASE'],
'user' => $_ENV['DB_USER'],
'pass' => $_ENV['DB_PASSWORD'],
'port' => '3306',
'charset' => 'utf8',
],
'testing' => [
'adapter' => 'mysql',
'host' => $_ENV['DB_HOST'] ?? 'localhost',
'name' => $_ENV['DB_DATABASE'],
'user' => $_ENV['DB_USER'],
'pass' => $_ENV['DB_PASSWORD'],
'port' => '3306',
'charset' => 'utf8',
]
],
'version_order' => 'creation',
'schema_file' => '%%PHINX_CONFIG_DIR%%/resources/database/schema.php',
'foreign_keys' => true,
'generate_migration_name' => true,
'default_migration_prefix' => 'incoviba_',
'mark_generated_migration' => true
];

43
app/phpunit.xml Normal file
View File

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/11.4/phpunit.xsd"
bootstrap="test.bootstrap.php"
cacheDirectory="/code/cache/tests"
executionOrder="depends,defects"
requireCoverageMetadata="false"
beStrictAboutCoverageMetadata="false"
beStrictAboutOutputDuringTests="true"
colors="true"
failOnRisky="false"
failOnWarning="false">
<testsuites>
<testsuite name="unit">
<directory>tests/unit</directory>
</testsuite>
<testsuite name="acceptance">
<directory>tests/integration</directory>
</testsuite>
<testsuite name="performance">
<directory>tests/performance</directory>
</testsuite>
</testsuites>
<source restrictNotices="true" restrictWarnings="true" ignoreIndirectDeprecations="true">
<include>
<directory>src</directory>
<directory>common</directory>
</include>
</source>
<coverage pathCoverage="false" ignoreDeprecatedCodeUnits="true" disableCodeCoverageIgnore="true">
<report>
<html outputDirectory="/code/public/coverage/html"/>
<php outputFile="/code/public/coverage/coverage.php"/>
</report>
</coverage>
<logging>
<junit outputFile="/code/cache/tests/junit.xml"/>
<teamcity outputFile="/code/cache/tests/teamcity.txt"/>
<testdoxHtml outputFile="/code/cache/tests/testdox.html"/>
<testdoxText outputFile="/code/cache/tests/testdox.txt"/>
</logging>
</phpunit>

BIN
app/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 894 B

View File

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreatePersonas extends AbstractMigration
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change(): void
{
$this->table('personas', ['id' => false, 'primary_key' => ['rut', 'digito']])
->addColumn('rut', 'integer', ['identity' => true, 'signed' => false, 'null' => false])
->addColumn('digito', 'string', ['limit' => 1, 'null' => false])
->addColumn('nombres', 'string', ['limit' => 255, 'null' => false])
->addColumn('apellido_paterno', 'string', ['limit' => 255, 'null' => false])
->addColumn('apellido_materno', 'string', ['limit' => 255, 'null' => false])
->create();
}
}

View File

@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateProveedores extends AbstractMigration
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change(): void
{
$this->table('proveedores', ['id' => false, 'primary_key' => ['rut', 'digito']])
->addColumn('rut', 'integer', ['identity' => true, 'signed' => false, 'null' => false])
->addColumn('digito', 'string', ['limit' => 1, 'null' => false])
->addColumn('nombre', 'string', ['limit' => 255, 'null' => false])
->addColumn('razon', 'string', ['limit' => 255, 'null' => true])
->addColumn('contacto_rut', 'integer', ['signed' => false, 'null' => true])
->addForeignKey('contacto_rut', 'personas', ['rut'], ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->create();
}
}

View File

@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateDatosProveedores extends AbstractMigration
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change(): void
{
$this->table('datos_proveedores')
->addColumn('proveedor_rut', 'integer', ['signed' => false, 'null' => false])
->addForeignKey('proveedor_rut', 'proveedores', ['rut'], ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->addColumn('direccion_id', 'integer', ['signed' => false, 'null' => true])
->addForeignKey('direccion_id', 'direccion', ['id'], ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->addColumn('telefono', 'string', ['limit' => 255, 'null' => true])
->addColumn('giro', 'string', ['limit' => 255, 'null' => true])
->create();
}
}

View File

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateDatosPersonas extends AbstractMigration
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change(): void
{
$this->table('datos_personas')
->addColumn('persona_rut', 'integer', ['signed' => false, 'null' => false])
->addForeignKey('persona_rut', 'personas', ['rut'], ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->addColumn('direccion_id', 'integer', ['signed' => false, 'null' => true])
->addForeignKey('direccion_id', 'direccion', ['id'], ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->addColumn('telefono', 'string', ['limit' => 255, 'null' => true])
->addColumn('email', 'string', ['limit' => 255, 'null' => true])
->addColumn('fecha_nacimiento', 'datetime', ['null' => true])
->addColumn('sexo', 'string', ['limit' => 255, 'null' => true])
->addColumn('estado_civil', 'string', ['limit' => 255, 'null' => true])
->addColumn('nacionalidad', 'string', ['limit' => 255, 'null' => true])
->addColumn('ocupacion', 'string', ['limit' => 255, 'null' => true])
->create();
}
}

View File

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateVentaAbonoCuota extends AbstractMigration
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change(): void
{
$this->table('venta_abono_cuotas')
->addColumn('venta_id', 'integer', ['signed' => false, 'null' => false])
->addForeignKey('venta_id', 'venta', ['id'], ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->addColumn('pago_id', 'integer', ['signed' => false, 'null' => false])
->addForeignKey('pago_id', 'pago', ['id'], ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->addColumn('numero', 'integer', ['signed' => false, 'null' => false, 'default' => 1])
->create();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,677 @@
-- Adminer 4.8.1 MySQL 11.5.2-MariaDB-ubu2404 dump
SET NAMES utf8;
SET time_zone = '+00:00';
SET foreign_key_checks = 0;
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
USE `incoviba`;
SET NAMES utf8mb4;
DROP TABLE IF EXISTS `action`;
CREATE TABLE `action` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`description` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `agente`;
CREATE TABLE `agente` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`tipo` int(11) DEFAULT NULL,
`rut` int(11) DEFAULT NULL,
`descripcion` varchar(100) DEFAULT NULL,
`representante` varchar(100) DEFAULT NULL,
`telefono` int(11) DEFAULT NULL,
`correo` varchar(50) DEFAULT NULL,
`direccion` int(11) DEFAULT NULL,
`giro` mediumtext DEFAULT NULL,
`abreviacion` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_tipo` (`tipo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `agente_tipo`;
CREATE TABLE `agente_tipo` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`agente` int(10) unsigned NOT NULL,
`tipo` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `agente` (`agente`),
KEY `tipo` (`tipo`),
CONSTRAINT `agente_tipo_ibfk_1` FOREIGN KEY (`agente`) REFERENCES `agente` (`id`) ON DELETE NO ACTION,
CONSTRAINT `agente_tipo_ibfk_2` FOREIGN KEY (`tipo`) REFERENCES `tipo_agente` (`id`) ON DELETE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `avance_construccion`;
CREATE TABLE `avance_construccion` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`proyecto` int(10) unsigned NOT NULL,
`fecha` date NOT NULL,
`numero` int(10) unsigned NOT NULL,
`avance` double unsigned NOT NULL,
`estado_pago` double unsigned NOT NULL,
`pagado` int(10) unsigned DEFAULT NULL,
`uf` double unsigned DEFAULT NULL,
`fecha_pagado` date DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `proyecto` (`proyecto`),
CONSTRAINT `avance_construccion_ibfk_1` FOREIGN KEY (`proyecto`) REFERENCES `proyecto` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `backup`;
CREATE TABLE `backup` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`date` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `banco`;
CREATE TABLE `banco` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`nombre` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `bono_pie`;
CREATE TABLE `bono_pie` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`valor` float DEFAULT NULL,
`pago` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `pago` (`pago`),
CONSTRAINT `bono_pie_ibfk_1` FOREIGN KEY (`pago`) REFERENCES `pago` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `cartolas`;
CREATE TABLE `cartolas` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`cuenta_id` int(10) unsigned NOT NULL,
`fecha` date NOT NULL,
`cargos` bigint(20) unsigned NOT NULL DEFAULT 0,
`abonos` bigint(20) unsigned NOT NULL DEFAULT 0,
`saldo` bigint(20) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY `cuenta_id` (`cuenta_id`),
CONSTRAINT `cartolas_ibfk_2` FOREIGN KEY (`cuenta_id`) REFERENCES `cuenta` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `categorias_centros_costos`;
CREATE TABLE `categorias_centros_costos` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`descripcion` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `centros_costos`;
CREATE TABLE `centros_costos` (
`id` int(10) unsigned NOT NULL,
`tipo_centro_id` int(10) unsigned NOT NULL,
`categoria_id` int(10) unsigned NOT NULL,
`tipo_cuenta_id` int(10) unsigned DEFAULT NULL,
`cuenta_contable` varchar(100) NOT NULL,
`descripcion` mediumtext NOT NULL,
PRIMARY KEY (`id`),
KEY `tipo_centro_id` (`tipo_centro_id`),
KEY `categoria_id` (`categoria_id`),
KEY `tipo_cuenta_id` (`tipo_cuenta_id`),
CONSTRAINT `centros_costos_ibfk_3` FOREIGN KEY (`tipo_centro_id`) REFERENCES `tipos_centros_costos` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `centros_costos_ibfk_4` FOREIGN KEY (`categoria_id`) REFERENCES `categorias_centros_costos` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `cierre`;
CREATE TABLE `cierre` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`proyecto` int(10) unsigned NOT NULL,
`precio` double NOT NULL,
`fecha` date NOT NULL,
`relacionado` int(1) DEFAULT 0,
`propietario` int(10) unsigned DEFAULT 0,
PRIMARY KEY (`id`),
KEY `proyecto` (`proyecto`),
CONSTRAINT `cierre_ibfk_2` FOREIGN KEY (`proyecto`) REFERENCES `proyecto` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `cobro`;
CREATE TABLE `cobro` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`proyecto` int(11) DEFAULT NULL,
`agente` int(11) DEFAULT NULL,
`tipo` int(11) DEFAULT NULL,
`fecha` date DEFAULT NULL,
`valor` float DEFAULT NULL,
`iva` float DEFAULT 0,
`uf` float DEFAULT NULL,
`identificador` varchar(50) DEFAULT NULL,
`glosa` mediumtext DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `comentario`;
CREATE TABLE `comentario` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`venta` int(10) unsigned DEFAULT NULL,
`fecha` datetime DEFAULT NULL,
`texto` blob DEFAULT NULL,
`estado` int(11) DEFAULT 1,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `comuna`;
CREATE TABLE `comuna` (
`id` int(11) unsigned NOT NULL,
`descripcion` varchar(50) NOT NULL,
`provincia` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_provincia` (`provincia`),
CONSTRAINT `comuna_ibfk_1` FOREIGN KEY (`provincia`) REFERENCES `provincia` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `configurations`;
CREATE TABLE `configurations` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`value` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `costo`;
CREATE TABLE `costo` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`proyecto` int(11) DEFAULT NULL,
`tipo` int(11) DEFAULT NULL,
`valor` float DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `credito`;
CREATE TABLE `credito` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`banco` varchar(50) DEFAULT NULL,
`valor` float DEFAULT NULL,
`fecha` date DEFAULT NULL,
`uf` float DEFAULT NULL,
`abonado` int(1) DEFAULT 0,
`fecha_abono` date DEFAULT NULL,
`pago` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `cuenta`;
CREATE TABLE `cuenta` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`inmobiliaria` int(8) unsigned NOT NULL,
`banco` int(10) unsigned NOT NULL,
`cuenta` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
KEY `inmobiliaria` (`inmobiliaria`),
KEY `banco` (`banco`),
CONSTRAINT `cuenta_ibfk_1` FOREIGN KEY (`inmobiliaria`) REFERENCES `inmobiliaria` (`rut`) ON DELETE NO ACTION,
CONSTRAINT `cuenta_ibfk_2` FOREIGN KEY (`banco`) REFERENCES `banco` (`id`) ON DELETE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `cuota`;
CREATE TABLE `cuota` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`pie` int(10) unsigned NOT NULL,
`fecha` date NOT NULL,
`valor_$` int(10) unsigned NOT NULL,
`estado` tinyint(1) DEFAULT 0,
`banco` varchar(20) NOT NULL,
`fecha_pago` date DEFAULT NULL,
`abonado` tinyint(1) DEFAULT 0,
`fecha_abono` date DEFAULT NULL,
`uf` double DEFAULT 0,
`pago` int(10) unsigned DEFAULT NULL,
`numero` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_pago_cuota` (`pago`),
KEY `pie` (`pie`),
CONSTRAINT `cuota_ibfk_1` FOREIGN KEY (`pago`) REFERENCES `pago` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `cuota_ibfk_2` FOREIGN KEY (`pie`) REFERENCES `pie` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `depositos`;
CREATE TABLE `depositos` (
`id` int(10) unsigned NOT NULL,
`cuenta_id` int(10) unsigned NOT NULL,
`capital` int(10) unsigned NOT NULL,
`futuro` int(10) unsigned NOT NULL,
`inicio` date NOT NULL,
`termino` date NOT NULL,
PRIMARY KEY (`id`),
KEY `cuenta_id` (`cuenta_id`),
CONSTRAINT `depositos_ibfk_2` FOREIGN KEY (`cuenta_id`) REFERENCES `cuenta` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `direccion`;
CREATE TABLE `direccion` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`calle` varchar(255) NOT NULL,
`numero` int(10) unsigned NOT NULL,
`extra` varchar(255) NOT NULL,
`comuna` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_comuna` (`comuna`),
CONSTRAINT `direccion_ibfk_1` FOREIGN KEY (`comuna`) REFERENCES `comuna` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `entrega`;
CREATE TABLE `entrega` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`fecha` date NOT NULL,
`fondo_operacion` int(11) DEFAULT 0,
`fondo_reserva` int(11) DEFAULT 0,
`fecha_fondo_operacion` date DEFAULT NULL,
`fecha_fondo_reserva` date DEFAULT NULL,
`pago_operacion` int(11) DEFAULT NULL,
`pago_reserva` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `escritura`;
CREATE TABLE `escritura` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`valor` bigint(20) NOT NULL,
`fecha` date NOT NULL,
`uf` float DEFAULT NULL,
`abonado` int(11) DEFAULT 0,
`fecha_abono` date DEFAULT NULL,
`pago` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `estados_cuentas`;
CREATE TABLE `estados_cuentas` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`cuenta_id` int(10) unsigned NOT NULL,
`fecha` date NOT NULL,
`active` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `cuenta_id` (`cuenta_id`),
CONSTRAINT `estados_cuentas_ibfk_2` FOREIGN KEY (`cuenta_id`) REFERENCES `cuenta` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `estado_cierre`;
CREATE TABLE `estado_cierre` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`cierre` int(10) unsigned NOT NULL,
`tipo` int(10) unsigned NOT NULL,
`fecha` date NOT NULL,
PRIMARY KEY (`id`),
KEY `cierre` (`cierre`),
KEY `tipo` (`tipo`),
CONSTRAINT `estado_cierre_ibfk_3` FOREIGN KEY (`cierre`) REFERENCES `cierre` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `estado_cierre_ibfk_4` FOREIGN KEY (`tipo`) REFERENCES `tipo_estado_cierre` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `estado_cobro`;
CREATE TABLE `estado_cobro` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`cobro` int(10) unsigned NOT NULL,
`fecha` date NOT NULL,
`estado` int(11) NOT NULL,
PRIMARY KEY (`id`,`cobro`,`estado`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `estado_pago`;
CREATE TABLE `estado_pago` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`pago` int(11) unsigned NOT NULL,
`fecha` date NOT NULL,
`estado` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `estado` (`estado`),
CONSTRAINT `estado_pago_ibfk_1` FOREIGN KEY (`estado`) REFERENCES `tipo_estado_pago` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `estado_precio`;
CREATE TABLE `estado_precio` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`precio` int(10) unsigned NOT NULL,
`fecha` date NOT NULL,
`estado` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `precio` (`precio`),
KEY `estado` (`estado`),
CONSTRAINT `estado_precio_ibfk_3` FOREIGN KEY (`precio`) REFERENCES `precio` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `estado_precio_ibfk_4` FOREIGN KEY (`estado`) REFERENCES `tipo_estado_precio` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `estado_problema`;
CREATE TABLE `estado_problema` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`problema` int(11) DEFAULT NULL,
`fecha` date DEFAULT NULL,
`estado` enum('ingreso','revision','correccion','ok') DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `estado_proyecto`;
CREATE TABLE `estado_proyecto` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`proyecto` int(10) unsigned NOT NULL,
`estado` int(11) unsigned NOT NULL,
`fecha` date NOT NULL,
PRIMARY KEY (`id`),
KEY `proyecto` (`proyecto`),
KEY `estado` (`estado`),
CONSTRAINT `estado_proyecto_ibfk_1` FOREIGN KEY (`proyecto`) REFERENCES `proyecto` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `estado_proyecto_ibfk_3` FOREIGN KEY (`estado`) REFERENCES `tipo_estado_proyecto` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `estado_proyecto_agente`;
CREATE TABLE `estado_proyecto_agente` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`agente` int(10) unsigned NOT NULL,
`fecha` date NOT NULL,
`tipo` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `estado_unidad_bloqueada`;
CREATE TABLE `estado_unidad_bloqueada` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`unidad` int(10) unsigned NOT NULL,
`fecha` date NOT NULL,
`tipo` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `estado_venta`;
CREATE TABLE `estado_venta` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`venta` int(10) unsigned NOT NULL,
`estado` int(11) unsigned NOT NULL DEFAULT 1,
`fecha` date NOT NULL,
PRIMARY KEY (`id`),
KEY `escritura` (`venta`),
KEY `estado` (`estado`),
CONSTRAINT `estado_venta_ibfk_1` FOREIGN KEY (`estado`) REFERENCES `tipo_estado_venta` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `estado_venta_ibfk_2` FOREIGN KEY (`venta`) REFERENCES `venta` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `etapa_proyecto`;
CREATE TABLE `etapa_proyecto` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`descripcion` varchar(20) DEFAULT NULL,
`orden` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `facturas`;
CREATE TABLE `facturas` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`venta_id` int(10) unsigned NOT NULL,
`index` int(10) unsigned NOT NULL,
`proporcion` double unsigned NOT NULL,
`data` text NOT NULL,
PRIMARY KEY (`id`),
KEY `venta_id` (`venta_id`),
CONSTRAINT `facturas_ibfk_2` FOREIGN KEY (`venta_id`) REFERENCES `venta` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `factura_proyecto_operador`;
CREATE TABLE `factura_proyecto_operador` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`proyecto_id` int(10) unsigned NOT NULL,
`operador_id` int(10) unsigned NOT NULL,
`factura` int(10) unsigned NOT NULL,
`valor_uf` double unsigned NOT NULL,
`valor_neto` int(10) unsigned NOT NULL,
`iva` int(10) unsigned DEFAULT 0,
PRIMARY KEY (`id`),
KEY `proyecto_id` (`proyecto_id`),
KEY `operador_id` (`operador_id`),
CONSTRAINT `factura_proyecto_operador_ibfk_1` FOREIGN KEY (`proyecto_id`) REFERENCES `proyecto` (`id`) ON DELETE CASCADE,
CONSTRAINT `factura_proyecto_operador_ibfk_2` FOREIGN KEY (`operador_id`) REFERENCES `agente` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `factura_venta`;
CREATE TABLE `factura_venta` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`factura_id` int(10) unsigned NOT NULL,
`venta_id` int(10) unsigned NOT NULL,
`valor` double NOT NULL,
PRIMARY KEY (`id`),
KEY `factura_id` (`factura_id`),
KEY `venta_id` (`venta_id`),
CONSTRAINT `factura_venta_ibfk_1` FOREIGN KEY (`factura_id`) REFERENCES `factura_proyecto_operador` (`id`) ON DELETE CASCADE,
CONSTRAINT `factura_venta_ibfk_2` FOREIGN KEY (`venta_id`) REFERENCES `venta` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `inmobiliaria`;
CREATE TABLE `inmobiliaria` (
`rut` int(8) unsigned NOT NULL,
`dv` char(1) DEFAULT NULL,
`razon` varchar(255) DEFAULT NULL,
`abreviacion` varchar(50) DEFAULT NULL,
`cuenta` varchar(50) DEFAULT NULL,
`banco` int(11) DEFAULT NULL,
`sociedad` int(10) unsigned DEFAULT NULL,
`sigla` varchar(4) DEFAULT NULL,
PRIMARY KEY (`rut`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `inmobiliarias_nubox`;
CREATE TABLE `inmobiliarias_nubox` (
`inmobiliaria_rut` int(8) unsigned NOT NULL,
`alias` varchar(100) NOT NULL,
`usuario` varchar(100) NOT NULL,
`contraseña` varchar(100) NOT NULL,
KEY `inmobiliaria_rut` (`inmobiliaria_rut`),
CONSTRAINT `inmobiliarias_nubox_ibfk_2` FOREIGN KEY (`inmobiliaria_rut`) REFERENCES `inmobiliaria` (`rut`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `locations`;
CREATE TABLE `locations` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`controller` varchar(50) NOT NULL,
`action` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `logins`;
CREATE TABLE `logins` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned NOT NULL,
`time` datetime NOT NULL,
`selector` varchar(255) NOT NULL,
`token` varchar(255) NOT NULL,
`status` int(1) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
KEY `fk_logins_users` (`user_id`),
CONSTRAINT `fk_logins_users` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `monolog`;
CREATE TABLE `monolog` (
`channel` varchar(255) DEFAULT NULL,
`level` varchar(100) DEFAULT NULL,
`message` longtext DEFAULT NULL,
`time` datetime DEFAULT NULL,
`context` longtext DEFAULT NULL,
`extra` longtext DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `movimientos`;
CREATE TABLE `movimientos` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`cuenta_id` int(10) unsigned NOT NULL,
`fecha` date NOT NULL,
`glosa` text NOT NULL,
`documento` varchar(50) NOT NULL,
`cargo` bigint(20) unsigned NOT NULL DEFAULT 0,
`abono` bigint(20) unsigned NOT NULL DEFAULT 0,
`saldo` bigint(20) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY `cuenta_id` (`cuenta_id`),
CONSTRAINT `movimientos_ibfk_2` FOREIGN KEY (`cuenta_id`) REFERENCES `cuenta` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `movimientos_detalles`;
CREATE TABLE `movimientos_detalles` (
`movimiento_id` int(10) unsigned NOT NULL,
`centro_costo_id` int(10) unsigned DEFAULT NULL,
`categoria` varchar(100) DEFAULT NULL,
`detalle` text DEFAULT NULL,
`rut` int(11) DEFAULT NULL,
`digito` varchar(1) DEFAULT NULL,
`nombres` varchar(255) DEFAULT NULL,
`identificador` varchar(100) DEFAULT NULL,
KEY `movimiento_id` (`movimiento_id`),
KEY `centro_costo_id` (`centro_costo_id`),
CONSTRAINT `movimientos_detalles_ibfk_3` FOREIGN KEY (`movimiento_id`) REFERENCES `movimientos` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `movimientos_detalles_ibfk_5` FOREIGN KEY (`centro_costo_id`) REFERENCES `centros_costos` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `pagare`;
CREATE TABLE `pagare` (
`id` int(10) unsigned NOT NULL,
`proyecto` int(10) unsigned NOT NULL,
`moneda` int(10) unsigned NOT NULL,
`capital` double unsigned NOT NULL DEFAULT 0,
`tasa` double unsigned NOT NULL DEFAULT 0,
`fecha` date NOT NULL,
`fecha_banco` date NOT NULL DEFAULT '0000-00-00',
`duracion` int(10) unsigned NOT NULL DEFAULT 0,
`uf` double unsigned NOT NULL DEFAULT 0,
`abonado` int(10) unsigned NOT NULL DEFAULT 0,
`estado_pago` int(10) unsigned NOT NULL DEFAULT 99999999,
PRIMARY KEY (`id`),
KEY `moneda` (`moneda`),
KEY `proyecto` (`proyecto`),
CONSTRAINT `pagare_ibfk_1` FOREIGN KEY (`moneda`) REFERENCES `tipo_moneda_pagare` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `pagare_ibfk_2` FOREIGN KEY (`proyecto`) REFERENCES `proyecto` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `pago`;
CREATE TABLE `pago` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`valor` double NOT NULL,
`banco` int(11) DEFAULT NULL,
`tipo` int(11) DEFAULT NULL,
`identificador` varchar(50) DEFAULT NULL,
`fecha` date DEFAULT NULL,
`uf` double DEFAULT NULL,
`pagador` varchar(50) DEFAULT NULL,
`asociado` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `pagos_centros_costos`;
CREATE TABLE `pagos_centros_costos` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`pago_id` int(11) unsigned NOT NULL,
`centro_costo_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `pago_id` (`pago_id`),
KEY `centro_costo_id` (`centro_costo_id`),
CONSTRAINT `pagos_centros_costos_ibfk_3` FOREIGN KEY (`pago_id`) REFERENCES `pago` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `pagos_centros_costos_ibfk_4` FOREIGN KEY (`centro_costo_id`) REFERENCES `centros_costos` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `permissions`;
CREATE TABLE `permissions` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`type` int(1) unsigned NOT NULL,
`ext_id` int(10) unsigned NOT NULL,
`action_id` int(10) unsigned NOT NULL,
`status` int(1) unsigned NOT NULL DEFAULT 1,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `phinxlog`;
CREATE TABLE `phinxlog` (
`version` bigint(20) NOT NULL,
`migration_name` varchar(100) DEFAULT NULL,
`start_time` timestamp NULL DEFAULT NULL,
`end_time` timestamp NULL DEFAULT NULL,
`breakpoint` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`version`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `pie`;
CREATE TABLE `pie` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`fecha` date NOT NULL,
`valor` double unsigned NOT NULL,
`uf` double unsigned DEFAULT NULL,
`cuotas` int(10) unsigned NOT NULL,
`asociado` int(11) DEFAULT 0,
`reajuste` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `precio`;
CREATE TABLE `precio` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`unidad` int(10) unsigned NOT NULL,
`valor` double NOT NULL,
PRIMARY KEY (`id`),
KEY `unidad` (`unidad`),
CONSTRAINT `precio_ibfk_2` FOREIGN KEY (`unidad`) REFERENCES `unidad` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
DROP TABLE IF EXISTS `problema`;
CREATE TABLE `problema` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`venta` int(11) DEFAULT NULL,
`descripcion` mediumtext DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-- 2024-11-12 15:11:54

View File

@ -1,4 +1,6 @@
<?php
use Incoviba\Controller\API\Base;
$app->group('/api', function($app) {
$folder = implode(DIRECTORY_SEPARATOR, [__DIR__, 'api']);
if (file_exists($folder)) {
@ -10,4 +12,5 @@ $app->group('/api', function($app) {
include_once $file->getRealPath();
}
}
$app->get('[/]', Base::class);
})->add($app->getContainer()->get(Incoviba\Middleware\API::class));

View File

@ -2,5 +2,15 @@
use Incoviba\Controller\Inmobiliarias;
$app->group('/inmobiliarias', function($app) {
$folder = implode(DIRECTORY_SEPARATOR, [__DIR__, 'inmobiliarias']);
if (file_exists($folder)) {
$files = new FilesystemIterator($folder);
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
include_once $file->getRealPath();
}
}
$app->get('[/]', Inmobiliarias::class);
})->add($app->getContainer()->get(Incoviba\Middleware\Authentication::class));

View File

@ -28,8 +28,15 @@ $app->group('/venta/{venta_id:[0-9]+}', function($app) {
});
$app->get('[/]', [Ventas::class, 'pie']);
});
$app->group('/bono_pie', function($app) {
$app->get('/add[/]', [Ventas\Bonos::class, 'add']);
});
$app->group('/escritura', function($app) {
$app->group('/cuotas', function($app) {
$app->get('[/]', Ventas\Abono\Cuotas::class);
});
$app->get('/add[/]', [Ventas\Escrituras::class, 'add']);
$app->get('[/]', [Ventas\Escrituras::class, 'show']);
});
$app->group('/credito', function($app) {
$app->get('[/]', [Ventas\Creditos::class, 'show']);

View File

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

View File

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

View File

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

View File

@ -0,0 +1,6 @@
<?php
use Incoviba\Controller\API\Admin\Users;
$app->group('/users', function($app) {
$app->post('/add[/]', Users::class . ':add');
});

View File

@ -3,6 +3,8 @@ use Incoviba\Controller\API\Contabilidad\Cartolas;
$app->group('/cartolas', function($app) {
$app->post('/procesar[/]', [Cartolas::class, 'procesar']);
$app->post('/importar[/]', [Cartolas::class, 'importar']);
$app->get('/update[/]', [Cartolas::class, 'update']);
});
$app->group('/cartola', function($app) {
$app->group('/diaria', function($app) {

View File

@ -1,5 +1,6 @@
<?php
use Incoviba\Controller\API\CentrosCostos;
use Incoviba\Controller\API\Contabilidad\CentrosCostos;
$app->group('/centros_costos', function($app) {
$app->post('/add[/]', [CentrosCostos::class, 'add']);

View File

@ -1,6 +1,13 @@
<?php
use Incoviba\Controller\API\Contabilidad\Movimientos;
$app->group('/movimiento/{movimiento_id}', function($app) {
$app->post('/detalles', [Movimientos::class, 'detalles']);
$app->group('/movimientos', function($app) {
$app->post('/sociedad/mes[/]', [Movimientos::class, 'sociedad']);
$app->post('/edit[/]', [Movimientos::class, 'edit']);
$app->post('/segment[/]', [Movimientos::class, 'segment']);
$app->get('[/]', Movimientos::class);
});
$app->group('/movimiento/{movimiento_id}', function($app) {
$app->post('/detalles[/]', [Movimientos::class, 'detalles']);
$app->delete('[/]', [Movimientos::class, 'remove']);
});

View File

@ -1,11 +1,14 @@
<?php
use Incoviba\Controller\API\Nubox;
use Incoviba\Controller\API\Contabilidad\Nubox;
$app->group('/nubox/{inmobiliaria_rut}', function($app) {
$app->get('/token[/]', [Nubox::class, 'token']);
$app->get('/sistemas[/]', [Nubox::class, 'sistemas']);
$app->get('/cuentas[/]', [Nubox::class, 'cuentas']);
$app->group('/libro', function($app) {
$app->post('/mayor[/]', [Nubox::class, 'libroMayor']);
$app->post('/diario[/]', [Nubox::class, 'libroDiario']);
});
$app->get('/facturas/{dia}[/]', [Nubox::class, 'facturas']);
$app->post('/cuenta', [Nubox::class, 'cuenta']);
});

View File

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

View File

@ -2,9 +2,20 @@
use Incoviba\Controller\API\Inmobiliarias;
$app->group('/inmobiliarias', function($app) {
$folder = implode(DIRECTORY_SEPARATOR, [__DIR__, 'inmobiliarias']);
if (file_exists($folder)) {
$files = new FilesystemIterator($folder);
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
include_once $file->getRealPath();
}
}
$app->get('[/]', Inmobiliarias::class);
});
$app->group('/inmobiliaria/{inmobiliaria_rut}', function($app) {
$app->post('/proveedores', [Inmobiliarias::class, 'proveedores']);
$app->get('/cuentas[/]', [Inmobiliarias::class, 'cuentas']);
$app->get('/proyectos[/]', [Inmobiliarias::class, 'proyectos']);
});

View File

@ -0,0 +1,11 @@
<?php
use Incoviba\Controller\API\Inmobiliarias\Agentes;
$app->group('/proveedores', function($app) {
$app->post('/add[/]', [Agentes::class, 'add']);
$app->post('/register[/]', [Agentes::class, 'register']);
$app->get('[/]', Agentes::class);
});
$app->group('/proveedor/{agente_id}', function($app) {
$app->post('/edit[/]', [Agentes::class, 'edit']);
});

View File

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

View File

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

View File

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

View File

@ -0,0 +1,17 @@
<?php
use Incoviba\Controller\API\Sociedades;
$app->group('/sociedades', function($app) {
$app->group('/add', function($app) {
$app->post('/one[/]', Sociedades::class . ':add');
$app->post('[/]', Sociedades::class . ':addMany');
});
$app->post('/get[/]', [Sociedades::class, 'getMany']);
$app->post('/edit[/]', [Sociedades::class, 'edit']);
$app->post('/delete[/]', [Sociedades::class, 'delete']);
$app->post('/asisgnar[/]', [Sociedades::class, 'asignar']);
$app->get('[/]', Sociedades::class);
});
$app->group('/sociedad/{sociedad_rut}', function($app) {
$app->get('[/]', Sociedades::class . ':get');
});

View File

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

View File

@ -27,8 +27,20 @@ $app->group('/ventas', function($app) {
});
$app->group('/venta/{venta_id}', function($app) {
$app->get('/unidades[/]', [Ventas::class, 'unidades']);
$app->get('/comentarios[/]', [Ventas::class, 'comentarios']);
$app->group('/comentarios', function($app) {
$app->post('/add[/]', [Ventas::class, 'addComentario']);
$app->get('[/]', [Ventas::class, 'comentarios']);
});
$app->group('/bono_pie', function($app) {
$app->post('/add[/]', [Ventas\Bonos::class, 'add']);
});
$app->group('/escritura', function($app) {
$app->group('/cuotas', function($app) {
$app->post('/add[/]', [Ventas\Abonos\Cuotas::class, 'add']);
});
$app->group('/cuota/{cuota_id:[0-9]+}', function($app) {
$app->post('/edit[/]', [Ventas\Abonos\Cuotas::class, 'edit']);
});
$app->post('/add[/]', [Ventas\Escrituras::class, 'add']);
});
$app->group('/credito', function($app) {
@ -39,6 +51,9 @@ $app->group('/venta/{venta_id}', function($app) {
$app->get('/eliminar[/]', [Ventas::class, 'insistir']);
$app->post('[/]', [Ventas::class, 'desistir']);
});
$app->group('/propietario', function($app) {
$app->put('/edit[/]', [Ventas::class, 'propietario']);
});
$app->post('[/]', [Ventas::class, 'edit']);
$app->get('[/]', [Ventas::class, 'get']);
});

View File

@ -0,0 +1,8 @@
<?php
use Incoviba\Controller\API\Ventas\Comentarios;
$app->group('/comentario/{comentario_id}', function($app) {
$app->post('/edit[/]', [Comentarios::class, 'edit']);
$app->delete('/remove[/]', [Comentarios::class, 'remove']);
//$app->get('[/]', [Comentarios::class, 'get']);
});

View File

@ -3,4 +3,5 @@ use Incoviba\Controller\API\Ventas\Facturacion;
$app->group('/facturacion', function($app) {
$app->get('/proyecto/{proyecto_id}[/]', [Facturacion::class, 'proyecto']);
$app->post('/get[/]', [Facturacion::class, 'ventas']);
});

View File

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

View File

@ -11,5 +11,6 @@ $app->group('/pago/{pago_id:[0-9]+}', function($app) {
$app->post('/abonar[/]', [Pagos::class, 'abonar']);
$app->post('/devolver[/]', [Pagos::class, 'devolver']);
$app->get('/anular[/]', [Pagos::class, 'anular']);
$app->post('/estado[/]', [Pagos::class, 'estado']);
$app->post('[/]', [Pagos::class, 'edit']);
});

View File

@ -3,4 +3,5 @@ use Incoviba\Controller\Contabilidad;
$app->group('/cartolas', function($app) {
$app->get('/diaria[/]', [Contabilidad::class, 'diaria']);
$app->get('/importar[/]', [Contabilidad::class, 'importar']);
});

View File

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

View File

@ -0,0 +1,4 @@
<?php
use Incoviba\Controller\Contabilidad;
$app->get('/cuadratura[/]', [Contabilidad::class, 'cuadratura']);

View File

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

View File

@ -0,0 +1,4 @@
<?php
use Incoviba\Controller\Contabilidad\Movimientos;
$app->get('/movimientos', Movimientos::class);

View File

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

View File

@ -10,4 +10,11 @@ $app->group('/pie/{pie_id}', function($app) {
});
$app->get('[/]', [Pies::class, 'cuotas']);
});
$files = new FilesystemIterator(implode(DIRECTORY_SEPARATOR, [__DIR__, 'pies']));
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
include_once $file->getRealPath();
}
});

View File

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

View File

@ -0,0 +1,100 @@
@extends('layout.base')
@section('page_content')
<div class="ui container">
<h2 class="ui header">Usuarios</h2>
<table class="ui table">
<thead>
<tr>
<th>Nombre</th>
<th class="right aligned">
<button class="ui mini green icon button" id="create-user-button">
<i class="plus icon"></i>
</button>
</th>
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td class="right aligned">
<button class="ui mini blue icon button">
<i class="edit icon"></i>
</button>
<button class="ui mini red icon button">
<i class="trash icon"></i>
</button>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<div class="ui modal" id="create-user-modal">
<i class="close icon"></i>
<div class="header">
Crear usuario
</div>
<div class="content">
<form class="ui form">
<div class="field">
<label>Nombre</label>
<input type="text" name="name" placeholder="Nombre">
</div>
<div class="field">
<label>Correo</label>
<input type="email" name="email" placeholder="Correo">
</div>
<div class="field">
<label>Contraseña</label>
<input type="password" name="password" placeholder="Contraseña">
</div>
</form>
</div>
<div class="actions">
<div class="ui black deny button">
Cancelar
</div>
<div class="ui positive right labeled icon button">
Crear
<i class="checkmark icon"></i>
</div>
</div>
</div>
@endsection
@include('layout.body.scripts.cryptojs')
@push('page_scripts')
<script>
function encryptPassword(password) {
const passphrase = Math.floor(Math.random() * Date.now()).toString()
const encrypted = CryptoJS.AES.encrypt(password, passphrase)
return [passphrase, encrypted.toString()].join('')
}
$(document).ready(function () {
$('#create-user-modal').modal({
onApprove: function() {
const url = '{{$urls->api}}/admin/users/add'
const method = 'post'
const body = new FormData(document.querySelector('#create-user-modal form'))
body.set('password', encryptPassword(body.get('password')))
fetchAPI(url, {method, body}).then(response => {
if (!response) {
return;
}
response.json().then(result => {
if (result.success) {
location.reload()
}
})
})
}
})
$('#create-user-button').on('click', function () {
$('#create-user-modal').modal('show')
})
});
</script>
@endpush

View File

@ -10,5 +10,23 @@
<i class="hammer icon"></i>
Esta parte del sitio está en construcción.
</div>
@if (isset($exception))
<div class="ui warning message">
<i class="exclamation triangle icon"></i>
<div class="content">
<div class="header">Error</div>
<p>{{$message}}</p>
</div>
</div>
@endif
@if (isset($error))
<div class="ui error message">
<i class="exclamation triangle icon"></i>
<div class="content">
<div class="header">Error</div>
<p>{{$message}}</p>
</div>
</div>
@endif
</div>
@endsection

View File

@ -52,8 +52,7 @@
<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 class="right aligned"></th>
<th>Orden</th>
</tr>
</thead>
@ -115,10 +114,85 @@
</div>
</div>
</div>
<div class="ui modal" id="edit_modal" data-cartola="">
<div class="header">
Movimiento
<div class="meta">
<span id="edit_inmobiliaria"></span> |
<span id="edit_cuenta"></span> |
<span id="edit_fecha"></span> |
<span id="edit_glosa"></span> |
<span id="edit_cargo"></span> |
<span id="edit_abono"></span> |
<span id="edit_saldo"></span>
</div>
</div>
<div class="content">
<form class="ui form" id="edit_form">
<input type="hidden" name="movimiento_id" value="" />
<div class="equal width fields">
<div class="field">
<label>Centro de Costo</label>
<div class="ui search selection dropdown">
<input type="hidden" name="centro_costo_id" />
<i class="dropdown icon"></i>
<div class="default text">Centro de Costo</div>
<div class="menu">
@foreach($centrosCostos as $centro)
<div class="item" data-value="{{$centro->id}}">
{{$centro->id}} - {{$centro->descripcion}}
</div>
@endforeach
</div>
</div>
</div>
<div class="field">
<label>Categoría</label>
<div class="ui input">
<input type="text" name="categoria" />
</div>
</div>
<div class="field">
<label>Detalle</label>
<div class="ui input">
<input type="text" name="detalle" />
</div>
</div>
</div>
<div class="equal width fields">
<div class="field">
<label>RUT</label>
<div class="ui right labeled input">
<input type="text" name="rut" />
<div class="ui basic label">-<span id="digito"></span></div>
</div>
</div>
<div class="field">
<label>Nombres</label>
<div class="ui input">
<input type="text" name="nombres" />
</div>
</div>
<div class="field">
<label>Identificador</label>
<div class="ui input">
<input type="text" name="identificador" />
</div>
</div>
</div>
</form>
</div>
<div class="actions">
<button class="ui approve button">
Editar
</button>
</div>
</div>
@endsection
@include('layout.head.styles.datatables')
@include('layout.body.scripts.datatables')
@include('layout.body.scripts.rut')
@push('page_scripts')
<script>
@ -126,7 +200,8 @@
idx
inmobiliaria = {
rut: 0,
razon: ''
razon: '',
sigla: ''
}
cuenta = {
id: 0,
@ -187,46 +262,6 @@
}
}
}
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) => {
@ -326,6 +361,10 @@
onChange: (value, text, $choice) => {
this.inmobiliaria.rut = value
this.inmobiliaria.razon = text
const inmobiliaria = diaria.data.inmobiliarias.find(inmobiliaria => inmobiliaria.rut === parseInt(value))
if (typeof inmobiliaria !== 'undefined') {
this.inmobiliaria.sigla = inmobiliaria.sigla
}
this.get().bancos(value).then(() => {
$cuentas_dropdown.dropdown('change values', this.bancos)
})
@ -380,74 +419,42 @@
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)
)
[
'<tr>',
`<td>${this.inmobiliaria.sigla ?? this.inmobiliaria.razon}</td>`,
`<td>${this.cuenta.descripcion}</td>`,
`<td>${dateFormatter.format(row.fecha)}</td>`,
`<td>${row.glosa}</td>`,
`<td class="right aligned">${row.cargo === 0 ? '' : numberFormatter.format(row.cargo)}</td>`,
`<td class="right aligned">${row.abono === 0 ? '' : numberFormatter.format(row.abono)}</td>`,
`<td class="right aligned">${row.saldo === 0 ? '' : numberFormatter.format(row.saldo)}</td>`,
'<td class="center aligned">',
`<button class="ui icon button edit_movimiento" data-movimiento="${idx}">`,
'<i class="edit icon"></i>',
'</button>',
'</td>',
`<td>${(idx + 1).toString()}</td>`,
].join("\n")
)
})
Array.from(document.getElementsByClassName('edit_movimiento')).forEach(button => {
button.addEventListener('click', function(clickEvent) {
const idx = clickEvent.currentTarget.dataset['movimiento']
const movimiento = this.movimientos[idx]
const $modal = $('#edit_modal')
$modal.attr('data-cartola', this.idx)
$modal.find('#edit_inmobiliaria').html(this.inmobiliaria.razon)
$modal.find('#edit_cuenta').html(this.cuenta.descripcion)
$modal.find('#edit_fecha').html(dateFormatter.format(movimiento.fecha))
$modal.find('#edit_glosa').html(movimiento.glosa)
$modal.find('#edit_cargo').html(numberFormatter.format(movimiento.cargo))
$modal.find('#edit_abono').html(numberFormatter.format(movimiento.abono))
$modal.find('#edit_saldo').html(numberFormatter.format(movimiento.saldo))
$modal.find('input[name="movimiento_id"]').val(movimiento.id)
$modal.modal('show')
}.bind(this))
})
},
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)
}
}
}
}
@ -460,8 +467,7 @@
'cargo',
'abono',
'saldo',
'centro',
'detalle',
'edit',
'orden'
];
@endphp
@ -471,17 +477,18 @@
inmobiliarias: JSON.parse('{!! json_encode($inmobiliarias) !!}'),
cartolasIdx: [],
cartolas: [],
movimientos: [],
},
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, ['fecha', 'cargo', 'abono', 'saldo', 'edit']);})))}}],
width: '{{round((1/(count($columns) + 2)) * 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: [{{implode(',', array_keys(array_filter($columns, function($column) {return in_array($column, ['sociedad', 'cuenta', 'glosa']);})))}}],
width: '{{round((1/(count($columns) + 2)) * 2 * 100, 2)}}%'
},
{
targets: [{{array_search('orden', $columns)}}],
@ -605,8 +612,12 @@
cargo: row.cargo,
abono: row.abono,
saldo: row.saldo,
centro: row.detalles?.centro_costo.descripcion ?? '',
detalle: row.detalles?.detalle ?? ''
centro: row.detalles?.centro_costo?.id ?? '',
detalle: row.detalles?.detalle ?? '',
categoria: row.detalles?.categoria ?? '',
rut: row.detalles?.rut ?? '',
nombres: row.detalles?.nombres ?? '',
identificador: row.detalles?.identificador ?? ''
}
})
const ayer = new Date(this.data.cartolas[cartolaIdx].fecha.getTime())
@ -638,6 +649,51 @@
$(this.ids.table.base).DataTable(this.dataTableConfig)
this.cartolas().add()
$(this.ids.editModal).modal({
onApprove: $element => {
const idx = $(this.ids.editModal).data('cartola')
const id = $(this.ids.editModal).find('input[name="movimiento_id"]').val()
const body = new FormData($(this.ids.editModal).find('form')[0])
body.set('idx', idx)
if (body.has('rut')) {
body.set('rut', body.get('rut').replace(/\D/g, ''))
body.set('digito', Rut.digitoVerificador(body.get('rut')))
}
const url = '{{$urls->api}}/contabilidad/movimiento/' + id + '/detalles'
return fetchAPI(url, {method: 'post', body}).then(response => {
if (!response) {
return
}
response.json().then(json => {
if (!json.status || json.movimiento === null || json.movimiento.detalles === null) {
return
}
const idx = diaria.data.cartolas.findIndex(cartola => cartola.idx = json.input.idx)
const movimiento = diaria.data.cartolas[idx].movimientos.find(movimiento => movimiento.id === id)
movimiento.centro = json.movimiento.detalles.centro_costo.id
movimiento.categoria = json.movimiento.detalles.categoria
movimiento.detalle = json.movimiento.detalles.detalle
movimiento.rut = json.movimiento.detalles.rut
movimiento.digito = json.movimiento.detalles.digito
movimiento.nombres = json.movimiento.detalles.nombres
movimiento.identificador = json.movimiento.detalles.identificador
})
})
}
})
$(this.ids.editModal).find('.dropdown').dropdown()
$(this.ids.editModal).find('[name="rut"]').on('input', function(event) {
const rut = event.currentTarget.value
const rut_clean = rut.replace(/\D/g, '')
event.currentTarget.value = Rut.format(rut_clean)
document.getElementById('digito').innerHTML = Rut.digitoVerificador(rut_clean)
}.bind(this))
const rut = $(this.ids.editModal).find('[name="rut"]')
const rut_clean = rut.val().replace(/\D/g, '')
rut.val(Rut.format(rut_clean))
document.getElementById('digito').innerHTML = Rut.digitoVerificador(rut_clean)
}
}
const manual = {
@ -807,7 +863,8 @@
add: '#add_button',
process: '#process_button'
},
loader: '#loader'
loader: '#loader',
editModal: '#edit_modal'
})
manual.setup({
modal: '#manual_modal',

View File

@ -0,0 +1,345 @@
@extends('layout.base')
@section('page_content')
<div class="ui container">
<h1 class="ui header">
Importar 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">
</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>
</div>
<table class="ui celled table" id="movimientos" style="display: none;">
<thead>
<tr>
<th>Sigla</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 class="center aligned">Centro de Costo</th>
<th>Categoría</th>
<th>Detalle</th>
<th>RUT</th>
<th>Nombres</th>
<th class="center aligned">Identificador</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
@endsection
@push('page_scripts')
<script>
class Cartola {
props
ids
constructor({index, ids}) {
this.props = {
index
}
this.ids = ids
}
get sociedad() {
return $(`#${this.ids.sociedad}${this.props.index}`).dropdown('get value')
}
get banco() {
return $(`#${this.ids.banco}${this.props.index}`).dropdown('get value')
}
get mes() {
return $(`#${this.ids.mes}${this.props.index}`).calendar('get date')
}
get file() {
return $(`#archivo${this.props.index}`)[0].files[0]
}
get data() {
return {
sociedad_rut: this.sociedad,
cuenta_id: this.banco,
mes: [this.mes.getFullYear(), this.mes.getMonth() + 1, 1].join('-'),
file: this.file,
index: this.props.index
}
}
draw({sociedades}) {
const output = [
`<div class="fields" data-idx="${this.props.index}">`,
'<div class="five wide field">',
'<label>Sociedad</label>',
`<div class="ui search selection dropdown" id="${this.ids.sociedad}${this.props.index}">`,
`<input type="hidden" name="sociedad_rut${this.props.index}" />`,
'<i class="dropdown icon"></i>',
'<div class="default text">Sociedad</div>',
'<div class="menu">',
...sociedades.map(sociedad => {
return [
`<div class="item" data-value="${sociedad.rut}">${sociedad.razon}</div>`
].join("\n")
}),
'</div>',
'</div>',
'</div>',
'<div class="four wide field">',
'<label>Banco</label>',
`<div class="ui search selection dropdown" id="${this.ids.banco}${this.props.index}">`,
`<input type="hidden" name="banco_id${this.props.index}" />`,
'<i class="dropdown icon"></i>',
'<div class="default text">Banco</div>',
'<div class="menu"></div>',
'</div>',
'</div>',
'<div class="field">',
'<label>Mes</label>',
`<div class="ui calendar" id="${this.ids.mes}${this.props.index}">`,
'<div class="ui input left icon">',
'<i class="calendar icon"></i>',
`<input type="text" name="mes${this.props.index}" placeholder="Mes" />`,
'</div>',
'</div>',
'</div>',
'<div class="field">',
'<label>Archivo</label>',
`<input type="file" class="ui invisible file input" name="archivo${this.props.index}" id="archivo${this.props.index}" />`,
`<label for="archivo${this.props.index}" class="ui icon button" id="archivo_button">`,
'<i class="file icon"></i>',
'</label>',
'</div>',
]
if (this.props.index > 1) {
output.push(...[
'<div class="field">',
'<label>&nbsp;</label>',
`<button class="ui red icon button remove" data-idx="${this.props.index}">`,
'<i class="trash icon"></i>',
'</button>',
'</div>',
])
}
output.push('</div>')
return output.join("\n")
}
activate() {
$(`#${this.ids.sociedad}${this.props.index}`).dropdown({
onChange: (value, text, $choice) => {
cartolas.fetch().bancos(value).then(response => {
if (!response) {
return
}
return response.json().then(data => {
const dropdown = $(`#${this.ids.banco}${this.props.index}`)
dropdown.dropdown('clear')
dropdown.dropdown('change values', data.cuentas.map(cuenta => {
const desc = [cuenta.banco.nombre, cuenta.cuenta].join(' - ')
return {
name: desc,
value: cuenta.id,
text: desc
}
}))
})
})
}
})
$(`#${this.ids.banco}${this.props.index}`).dropdown()
const cdo = structuredClone(calendar_date_options)
cdo.type = 'month'
$(`#${this.ids.mes}${this.props.index}`).calendar(cdo)
if (this.props.index > 1) {
$(`.${this.ids.buttons.remove}[data-idx="${this.props.index}"]`).click(clickEvent => {
const index = $(clickEvent.currentTarget).data('idx')
this.remove(index)
})
}
}
remove(idx) {
$(`.fields[data-idx=${idx}]`).remove()
cartolas.data.cartolas = cartolas.data.cartolas.filter(cartola => cartola.props.index !== idx)
cartolas.draw().form()
}
}
class Movimiento {
props
constructor({sociedad, fecha, glosa, cargo, abono, saldo, categoria, detalle, centro_costo, rut, nombres, identificador}) {
this.props = {
sociedad,
fecha,
glosa,
cargo,
abono,
saldo,
categoria,
detalle,
centro_costo,
rut,
nombres,
identificador
}
}
draw({formatters}) {
const fecha = new Date(this.props.fecha)
return [
'<tr>',
`<td>${this.props.sociedad.sigla}</td>`,
`<td>${formatters.date.format(fecha)}</td>`,
`<td>${this.props.glosa}</td>`,
`<td class="right aligned">${formatters.number.format(this.props.cargo ?? 0)}</td>`,
`<td class="right aligned">${formatters.number.format(this.props.abono ?? 0)}</td>`,
`<td class="right aligned">${formatters.number.format(this.props.saldo)}</td>`,
`<td class="center aligned">${this.props.centro_costo ?? ''}</td>`,
`<td>${this.props.categoria ?? ''}</td>`,
`<td>${this.props.detalle ?? ''}</td>`,
`<td>${this.props.rut ?? ''}</td>`,
`<td>${this.props.nombres ?? ''}</td>`,
`<td class="center aligned">${this.props.identificador ?? ''}</td>`,
'</tr>'
].join("\n")
}
}
const cartolas = {
ids: {},
data: {
sociedades: {!! json_encode($inmobiliarias) !!},
bancos: {!! json_encode($bancos) !!},
cartolas: [],
movimientos: [],
},
formatters: {
number: new Intl.NumberFormat('es-CL', {minimumFractionDigits: 0, maximumFractionDigits: 0}),
date: new Intl.DateTimeFormat('es-CL', {dateStyle: 'short', timeStyle: 'short'})
},
add() {
return {
cartola: () => {
const idx = cartolas.data.cartolas.length + 1
const cartola = new Cartola({index: idx, ids: cartolas.ids.cartolas})
cartolas.data.cartolas.push(cartola)
cartolas.draw().form()
}
}
},
draw() {
return {
form: () => {
const form = $(this.ids.form)
form.empty()
form.append(`<input type="hidden" name="cartolas" value="${this.data.cartolas.length}" />`)
this.data.cartolas.forEach(cartola => {
form.append(cartola.draw({sociedades: this.data.sociedades, bancos: this.data.bancos}))
cartola.activate()
})
},
movimientos: () => {
const table = $(this.ids.movimientos)
const tbody = table.find('tbody')
tbody.empty()
this.data.movimientos.forEach(movimiento => {
tbody.append(movimiento.draw({formatters: this.formatters}))
})
table.show()
}
}
},
fetch() {
return {
bancos: sociedad_rut => {
const url = `{{$urls->api}}/inmobiliaria/${sociedad_rut}/cuentas`
return fetchAPI(url)
}
}
},
import() {
return {
cartolas: () => {
const url = '{{$urls->api}}/contabilidad/cartolas/importar'
const method = 'post'
const body = new FormData()
this.data.cartolas.forEach(cartola => {
Object.entries(cartola.data).forEach(([key, value]) => {
const name = `${key}[${cartola.props.index - 1}]`
body.append(name, value)
})
})
fetchAPI(url, {method, body}).then(response => {
if (!response) {
return
}
return response.json().then(data => {
if (data.errors.length > 0) {
data.errors.forEach(errorData => {
console.error(errorData)
})
}
this.data.movimientos = data.movimientos.map(movimiento => new Movimiento(movimiento))
this.draw().movimientos()
})
}).catch(error => {
const table = $(this.ids.movimientos)
const tbody = table.find('tbody')
tbody.empty()
table.hide()
}).finally(() => {
$(this.ids.loader).hide()
})
}
}
},
setup(ids) {
this.ids = ids
this.add().cartola()
$(this.ids.buttons.add).click(() => {
this.add().cartola()
})
$(this.ids.loader).hide()
$(this.ids.form).submit(submitEvent => {
submitEvent.preventDefault()
$(this.ids.loader).show()
this.import().cartolas()
return false
})
$(this.ids.buttons.process).click(() => {
$(this.ids.form).submit()
})
}
}
$(document).ready(() => {
cartolas.setup({
form: '#cartola_form',
buttons: {
add: '#add_button',
process: '#process_button'
},
movimientos: '#movimientos',
loader: '#loader',
cartolas: {
sociedad: 'sociedad',
banco: 'banco',
mes: 'mes',
buttons: {
remove: 'remove'
}
}
})
})
</script>
@endpush

View File

@ -15,7 +15,8 @@
<div class="default text">Inmobiliaria</div>
<div class="menu">
@foreach ($inmobiliarias as $inmobiliaria)
<div class="item" data-value="{{$inmobiliaria->rut}}">{{$inmobiliaria->razon}}</div>
<div class="item"
data-value="{{$inmobiliaria->rut}}">{{$inmobiliaria->razon}}</div>
@endforeach
</div>
</div>
@ -119,20 +120,20 @@
mes: '',
movimientos: [],
centrosCostos: {
ingresos: JSON.parse('{!! json_encode(array_values(array_map(function(\Incoviba\Model\CentroCosto $centroCosto) {
ingresos: JSON.parse('{!! json_encode(array_values(array_map(function(\Incoviba\Model\Contabilidad\CentroCosto $centroCosto) {
return [
'id' => $centroCosto->id,
'descripcion' => $centroCosto->descripcion
];
}, array_filter($centrosCostos, function(\Incoviba\Model\CentroCosto $centroCosto) {
}, array_filter($centrosCostos, function(\Incoviba\Model\Contabilidad\CentroCosto $centroCosto) {
return $centroCosto->tipoCentro->descripcion === 'Ingreso';
})))) !!}'),
egresos: JSON.parse('{!! json_encode(array_values(array_map(function(\Incoviba\Model\CentroCosto $centroCosto) {
egresos: JSON.parse('{!! json_encode(array_values(array_map(function(\Incoviba\Model\Contabilidad\CentroCosto $centroCosto) {
return [
'id' => $centroCosto->id,
'descripcion' => $centroCosto->descripcion
];
}, array_filter($centrosCostos, function(\Incoviba\Model\CentroCosto $centroCosto) {
}, array_filter($centrosCostos, function(\Incoviba\Model\Contabilidad\CentroCosto $centroCosto) {
return $centroCosto->tipoCentro->descripcion === 'Egreso';
})))) !!}'),
}
@ -170,7 +171,11 @@
return
}
$(this.ids.form.banco).dropdown('change values', json.cuentas.map(cuenta => {
return {value: cuenta.banco.id, text: cuenta.banco.nombre, name: cuenta.banco.nombre}
return {
value: cuenta.banco.id,
text: cuenta.banco.nombre,
name: cuenta.banco.nombre
}
})).dropdown('refresh')
})
})
@ -294,7 +299,10 @@
month: 'numeric',
day: 'numeric'
})
const numberFormatter = new Intl.NumberFormat('es-CL', {minimumFractionDigits: 0, maximumFractionDigits: 0})
const numberFormatter = new Intl.NumberFormat('es-CL', {
minimumFractionDigits: 0,
maximumFractionDigits: 0
})
this.data.movimientos.forEach((row, idx) => {
tbody.append(
$('<tr></tr>').append(

View File

@ -0,0 +1,225 @@
@extends('layout.base')
@section('page_content')
<div class="ui container">
<h1 class="ui header">
Cuadratura de Cartola Mensual
</h1>
<form class="ui form" id="cuadratura_form">
<div class="ui grid">
<div class="fourteen wide column">
<div class="fields">
<div class="five wide field">
<label>Inmobiliaria</label>
<div class="ui selection search dropdown" id="inmobiliaria">
<input type="hidden" name="inmobiliaria"/>
<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="two wide field">
<label>Banco</label>
<div class="ui selection search dropdown" id="banco">
<input type="hidden" name="banco"/>
<i class="dropdown icon"></i>
<div class="default text">Banco</div>
<div class="menu"></div>
</div>
</div>
<div class="field">
<label>Mes</label>
<div class="ui calendar" id="mes">
<div class="ui icon input">
<i class="calendar icon"></i>
<input type="text" name="mes"/>
</div>
</div>
</div>
<div class="field">
<label for="file">Cartola</label>
<input type="file" name="file" id="file" class="ui invisible file input" />
<label for="file" class="ui icon button">
<i class="file icon"></i>
Cargar
</label>
</div>
</div>
</div>
<div class="two wide middle aligned column">
<button class="ui icon button">
Procesar
<i class="sync icon"></i>
</button>
</div>
</div>
</form>
<div class="ui two columns grid">
<div class="column"></div>
<div class="right aligned column">
<div class="ui inline active loader" id="loader"></div>
</div>
</div>
</div>
<div class="ui fluid container" id="movimientos"></div>
@endsection
@include('layout.head.styles.datatables')
@include('layout.body.scripts.datatables')
@push('page_scripts')
<script>
class LibroMayor {
props
constructor(props) {
this.props = props
}
}
class Cartola {
}
const movimientos = {
ids: {},
data: {
inmobiliaria: {
rut: '',
razon: ''
},
banco: {
id: '',
nombre: ''
}
},
get() {
return {
bancos: inmobiliaria_rut => {
const url = '{{$urls->api}}/inmobiliaria/' + inmobiliaria_rut + '/cuentas'
$(this.ids.loader).show()
return fetchAPI(url).then(response => {
$(this.ids.loader).hide()
if (!response) {
return
}
return response.json().then(json => {
if (json.cuentas.length === 0) {
return
}
$(this.ids.inputs.banco).dropdown('change values', json.cuentas.map(cuenta => {
return {value: cuenta.banco.id, text: cuenta.banco.nombre, name: cuenta.banco.nombre}
})).dropdown('refresh')
})
})
},
firstDate: inmobiliaria_rut => {
const url = '{{$urls->api}}/inmobiliaria/' + inmobiliaria_rut + '/proyectos'
$(this.ids.loader).show()
return fetchAPI(url).then(response => {
$(this.ids.loader).hide()
if (!response) {
return
}
return response.json().then(json => {
if (json.proyectos.length === 0) {
return
}
const min = json.proyectos.reduce((min, proyecto) => {
const date = new Date(proyecto.current_estado.fecha.date)
if (min > date.getTime()) {
return date.getTime()
}
return min
}, (new Date()).getTime())
$(this.ids.inputs.mes).calendar('set minDate', new Date(min))
})
})
}
}
},
parse() {
return {
cartola: submitEvent => {
submitEvent.preventDefault()
const body = new FormData(document.getElementById('asignar_form'))
body.set('mes', $(this.ids.inputs.mes).calendar('get date').toISOString())
const url = '{{$urls->api}}/contabilidad/cartolas/procesar'
$(this.ids.loader).show()
fetchAPI(url, {method: 'post', body}).then(response => {
$(this.ids.loader).hide()
if (!response) {
return
}
return response.json().then(json => {
if (json.movimientos.length === 0) {
return
}
this.data.movimientos = []
json.movimientos.forEach((row, idx) => {
const fecha = new Date(row.fecha)
fecha.setDate(fecha.getDate() + 1)
this.data.movimientos[idx] = {
fecha: fecha,
glosa: row.glosa,
documento: row.documento,
cargo: row.cargo,
abono: row.abono,
}
})
this.draw().cartola()
})
})
return false
}
}
},
setup(ids) {
this.ids = ids
$(this.ids.inputs.inmobiliaria).dropdown({
fireOnInit: true,
onChange: (value, text, $choice) => {
this.data.inmobiliaria.rut = value
this.data.inmobiliaria.razon = text
this.get().bancos(value)
this.get().firstDate(value)
},
})
$(this.ids.inputs.banco).dropdown({
fireOnInit: true,
onChange: (value, text, $choice) => {
this.data.banco.id = value
this.data.banco.nombre = text
}
})
$(this.ids.loader).hide()
calendar_date_options['type'] = 'month'
const lastMonth = new Date()
lastMonth.setDate(0)
calendar_date_options['maxDate'] = lastMonth
calendar_date_options['onChange'] = (date, text, mode) => {
this.data.mes = text
}
$(this.ids.inputs.mes).calendar(calendar_date_options)
$(this.ids.form).submit(this.parse().cartola)
//$(this.ids.button).click(this.export().cartola)
}
}
$(document).ready(() => {
movimientos.setup({
movimientos: '#movimientos',
form: '#cuadratura_form',
loader: '#loader',
inputs: {
inmobiliaria: '#inmobiliaria',
banco: '#banco',
mes: '#mes',
cartola: '#file'
}
})
})
</script>
@endpush

View File

@ -1,12 +1,21 @@
@extends('layout.base')
@push('page_styles')
<style>
tr.bold > th {
font-weight: bold !important;
}
</style>
@endpush
@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;">
<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>
@ -19,7 +28,11 @@
<table class="ui collapsing simple table">
<tr>
<td>Informe anterior</td>
<td>{{$anterior->format('d/m/Y')}}</td>
<td>
<a href="{{$urls->base}}/contabilidad/informes/tesoreria/{{$anterior->format('Y-m-d')}}">
{{$anterior->format('d/m/Y')}}
</a>
</td>
</tr>
<tr>
<td>Informe actual</td>
@ -40,6 +53,17 @@
</tr>
</table>
</div>
@if ($siguiente !== null)
<div class="five wide column"></div>
<div class="right aligned two wide column">
<div class="ui segment">
Siguiente
<a href="{{$urls->base}}/contabilidad/informes/tesoreria/{{$siguiente->format('Y-m-d')}}">
{{$siguiente->format('d/m/Y')}} >>
</a>
</div>
</div>
@endif
</div>
<table class="ui striped table">
<thead>
@ -60,11 +84,11 @@
</tr>
</thead>
<tbody>
@foreach ($informes['inmobiliarias'] as $inmobiliaria_rut => $informe)
@foreach ($informes['sociedades'] as $sociedad_rut => $informe)
@foreach ($informe->cuentas as $i => $cuenta)
<tr>
@if ($i === 0)
<td rowspan="{{count($informe->cuentas)}}">{{$informe->inmobiliaria->razon}}</td>
<td rowspan="{{count($informe->cuentas)}}">{{$informe->sociedad->razon}}</td>
@endif
<td>{{$cuenta->banco}}</td>
<td>{{$cuenta->numero}}</td>
@ -75,10 +99,14 @@
<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>
<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

View File

@ -0,0 +1,136 @@
@extends('layout.base')
@include('layout.head.styles.datatables')
@include('layout.head.styles.datatables.searchbuilder')
@include('layout.head.styles.datatables.buttons')
@push('page_styles')
<style>
#table_container {
margin-left: 1rem;
margin-right: 1rem;
}
</style>
@endpush
@section('page_content')
<div class="ui container">
<h1 class="ui header">Movimientos Contables</h1>
<form class="ui form" id="movimientos_form">
<div class="fields">
<div class="six wide field">
<label for="sociedad">Sociedad</label>
<div class="ui selection search multiple dropdown" id="sociedades">
<input type="hidden" name="sociedad[]"/>
<i class="dropdown icon"></i>
<div class="default text">Sociedad</div>
<div class="menu">
@foreach($sociedades as $sociedad)
<div class="item" data-value="{{$sociedad->rut}}">{{$sociedad->razon}}</div>
@endforeach
</div>
</div>
</div>
<div class="three wide field">
<label for="mes">Mes</label>
<div class="ui calendar" id="mes">
<div class="ui right icon input">
<input type="text" name="mes"/>
<i class="calendar icon"></i>
</div>
</div>
</div>
<div class="field">
<label></label>
<button class="ui circular icon button">
<i class="sync alternate icon"></i>
</button>
</div>
</div>
</form>
</div>
<div id="table_container">
<table id="tabla_movimientos" class="ui compact table">
<thead>
<tr>
<th>Sigla</th>
<th>Banco</th>
<th>Cuenta</th>
<th>Fecha</th>
<th>ISO Fecha</th>
<th>Mes</th>
<th>Año</th>
<th class="right aligned">Valor</th>
<th>Valor</th>
<th>Glosa</th>
<th>Centro de Costo</th>
<th>Detalle</th>
<th>Editar</th>
</tr>
</thead>
<tbody id="movimientos"></tbody>
</table>
</div>
@include('contabilidad.movimientos.edit_modal')
@endsection
@include('layout.body.scripts.datatables')
@include('layout.body.scripts.datatables.searchbuilder')
@include('layout.body.scripts.datatables.buttons')
@include('layout.body.scripts.rut')
@push('page_scripts')
<script>
class CentrosCostos {
static data = []
static get() {
if (this.data.length === 0) {
this.data = JSON.parse('{!! json_encode($centros) !!}')
}
return this.data
}
}
</script>
@endpush
@push('page_scripts')
@include('contabilidad.movimientos.scripts.event_handler')
@include('contabilidad.movimientos.scripts.loading_handler')
@include('contabilidad.movimientos.scripts.control_form')
@include('contabilidad.movimientos.scripts.movimientos_table')
@include('contabilidad.movimientos.scripts.edit_modal')
@include('contabilidad.movimientos.scripts.edit_form')
@include('contabilidad.movimientos.scripts.movimientos_handler')
@include('contabilidad.movimientos.scripts.results_handler')
<script>
const app = {
handlers: {},
setup() {
this.handlers.results = new ResultsHandler()
this.handlers.loading = new LoadingHandler({id: '#movimientos_form'})
this.handlers.movimientos = new MovimientosHandler({
urls: {
get: '{{$urls->api}}/contabilidad/movimientos/sociedad/mes',
edit: '{{$urls->api}}/contabilidad/movimientos/edit',
remove: '{{$urls->api}}/contabilidad/movimiento',
},
loadingHandler: this.handlers.loading,
resultsHandler: this.handlers.results
})
this.handlers.forms = {
edit: new EditForm({ids: {modal: '#movimientos_modal', data: '#movimientos_data', form: '#movimientos_edit',}})
}
this.handlers.modals = {
edit: new EditModal({ids: {modal: '#movimientos_modal'}, editForm: this.handlers.forms.edit})
}
this.handlers.events = new EventHandler({movimientosHandler: this.handlers.movimientos, modalHandler: this.handlers.modals.edit})
this.handlers.table = new MovimientosTable({ids: {table: '#tabla_movimientos', buttons: {edit: '.edit_button', remove: '.remove_button'}}, eventHandler: this.handlers.events})
this.handlers.forms.control = new ControlForm({ids: {form: '#movimientos_form', sociedades: '#sociedades', mes: '#mes',},})
this.handlers.forms.edit.setup()
}
}
$(document).ready(() => {
app.setup()
})
</script>
@endpush

View File

@ -0,0 +1,67 @@
<div class="ui fluid modal" id="movimientos_modal">
<div class="content">
<h3 class="header">
Editar Movimiento
</h3>
<div class="ui divider"></div>
<div class="ui grid container" id="modal_info">
<div class="column sociedad"></div>
<div class="column banco"></div>
<div class="column cuenta"></div>
<div class="column fecha"></div>
<div class="column valor"></div>
<div class="column glosa"></div>
</div>
<div class="ui divider"></div>
<form class="ui form" id="movimientos_edit">
<input type="hidden" name="index"/>
<input type="hidden" name="id"/>
<div class="fields">
<div class="field">
<label for="centro_costo">Centro de Costo</label>
<div class="ui selection search dropdown" id="centro_costo">
<input type="hidden" name="centro_id"/>
<i class="dropdown icon"></i>
<div class="default text">Centro de Costo</div>
<div class="menu">
@foreach($centros as $centroCosto)
<div class="item" data-value="{{$centroCosto->id}}">{{$centroCosto->id}} - {{$centroCosto->descripcion}}</div>
@endforeach
</div>
</div>
</div>
<div class="field">
<label>Categoría</label>
<input type="text" name="categoria" placeholder="Categoría" />
</div>
<div class="field">
<label>Identificador</label>
<input type="text" name="identificador" placeholder="Identificador" />
</div>
</div>
<div class="fields">
<div class="field">
<label>RUT</label>
<div class="ui right labeled input">
<input type="text" name="rut" placeholder="RUT" />
<div class="ui basic label">-<span id="digito"></span></div>
</div>
</div>
<div class="field">
<label>Nombre</label>
<input type="text" name="nombre" placeholder="Nombre" />
</div>
</div>
<div class="field">
<label for="detalle">Detalle</label>
<div class="ui input">
<textarea id="detalle" name="detalle"></textarea>
</div>
</div>
</form>
</div>
<div class="actions">
<div class="ui red cancel button">Cancelar</div>
<div class="ui green approve success button">Guardar</div>
</div>
</div>

View File

@ -0,0 +1,22 @@
<script>
class ControlForm {
props
constructor({ids,}) {
this.props = {
ids,
}
$(this.props.ids.sociedades).dropdown()
const cdo = structuredClone(calendar_date_options)
cdo['type'] = 'month'
cdo['maxDate'] = new Date()
$(this.props.ids.mes).calendar(cdo)
$(this.props.ids.form).on('submit', {
sociedades_id: this.props.ids.sociedades,
mes_id: this.props.ids.mes,
handler: app.handlers.events
}, app.handlers.events.get().movimientos)
}
}
</script>

View File

@ -0,0 +1,98 @@
<script>
class EditForm {
props
fields
constructor({ids}) {
this.props = {
ids,
movimientos: []
}
this.fields = [
{
name: 'index',
value: index => index
},
{
name: 'id',
value: movimiento => movimiento.id
},
{
id: 'centro_costo',
name: 'centro_id',
type: 'dropdown',
value: movimiento => movimiento.detalles.centro_costo.id ?? '',
values: CentrosCostos.get().map(centroCosto => {
return {
value: centroCosto.id,
name: `${centroCosto.id} - ${centroCosto.descripcion}`,
text: `${centroCosto.id} - ${centroCosto.descripcion}`,
}
})
},
{
name: 'rut',
type: 'text',
value: movimiento => movimiento.detalles.rut ?? ''
},
{
id: 'digito',
value: movimiento => movimiento.detalles.digito ?? ''
},
{
name: 'nombre',
type: 'text',
value: movimiento => movimiento.detalles.nombres ?? ''
},
{
name: 'categoria',
type: 'text',
value: movimiento => movimiento.detalles.categoria ?? ''
},
{
name: 'detalle',
type: 'text',
value: movimiento => movimiento.detalles.detalle ?? ''
},
{
name: 'identificador',
type: 'text',
value: movimiento => movimiento.detalles.identificador ?? ''
}
]
this.fields.filter(field => typeof field.values !== 'undefined').forEach(field => {
$(this.props.ids.form).find(`#${field.id}`).dropdown('change values', field.values)
})
}
reset() {
$(this.props.ids.form).form('reset')
}
show({modal, movimiento, index}) {
modal.find(this.props.ids.data).show()
this.fields.forEach(field => {
if (typeof field.name !== 'undefined') {
switch (field.type) {
case 'dropdown':
modal.find(`#${field.id}`).dropdown('set selected', field.value(movimiento))
break
default:
if (field.name === 'index') {
modal.find(`[name='${field.name}']`).val(index)
return
}
modal.find(`[name='${field.name}']`).val(field.value(movimiento))
break
}
return
}
modal.find(`#${field.id}`).text(field.value(movimiento))
})
}
setup() {
$(this.props.ids.form).on('submit', {
form_id: this.props.ids.form,
}, app.handlers.events.edit().modal)
}
}
</script>

View File

@ -0,0 +1,74 @@
<script>
class EditModal {
props
info
constructor({ids, editForm}) {
this.props = {
ids,
editForm,
movimientos: []
}
this.info = [
{
className: 'sociedad',
width: 'three wide',
value: movimiento => `<b>Sociedad</b>: ${movimiento.cuenta.inmobiliaria.sigla}`
},
{
className: 'banco',
width: 'three wide',
value: movimiento => `<b>Banco</b>: ${movimiento.cuenta.banco.nombre}`
},
{
className: 'cuenta',
width: 'three wide',
value: movimiento => `<b>Cuenta</b>: ${movimiento.cuenta.cuenta}`
},
{
className: 'fecha',
width: 'three wide',
value: movimiento => `<b>Fecha</b>: ${movimiento.fecha}`
},
{
className: 'valor',
width: 'three wide',
value: movimiento => `<b>Valor</b>: ${movimiento.abono - movimiento.cargo}`
},
{
className: 'glosa',
width: 'ten wide',
value: movimiento => `<b>Glosa</b>: ${movimiento.glosa}`
},
]
const $info = $(this.props.ids.modal).find('#modal_info')
$info.empty()
this.info.forEach(field => {
$info.append(`<div class="${field.width} column ${field.className}"></div>`)
})
$(this.props.ids.modal).modal({
onApprove: $element => {
$(this.props.editForm.props.ids.form).submit()
}
})
}
reset() {
this.info.forEach(info => {
$(this.props.ids.modal).find(`.${info.className}`).text('')
})
this.props.editForm.reset()
}
show({movimiento, index}) {
$(this.props.ids.modal).modal('show')
this.info.forEach(info => {
$(this.props.ids.modal).find(`.${info.className}`).html(info.value(movimiento))
})
this.props.editForm.show({modal: $(this.props.ids.modal), movimiento, index})
}
hide() {
$(this.props.ids.modal).modal('hide')
this.reset()
}
}
</script>

View File

@ -0,0 +1,54 @@
<script>
class EventHandler {
props
constructor({movimientosHandler, modalHandler}) {
this.props = {
movimientosHandler,
modalHandler
}
}
get() {
return {
movimientos: submitEvent => {
submitEvent.preventDefault()
submitEvent.data.handler.props.movimientosHandler.get().movimientos({
sociedades_ruts: $(submitEvent.data.sociedades_id).dropdown('get values'),
mes: $(submitEvent.data.mes_id).calendar('get date')
}).then(() => {
app.handlers.table.draw().table(app.handlers.results.props.parsed)
})
return false
}
}
}
edit() {
return {
movimiento: clickEvent => {
const id = $(clickEvent.currentTarget).data('id')
const index = $(clickEvent.currentTarget).data('index')
const movimiento = this.props.movimientosHandler.find().id(id)
clickEvent.data.handler.props.modalHandler.show({movimiento, index})
},
modal: submitEvent => {
submitEvent.preventDefault()
const form = submitEvent.currentTarget
const data = new FormData(form)
app.handlers.movimientos.edit().movimiento(data).then(() => {
app.handlers.table.draw().table(app.handlers.results.props.parsed)
})
return false
}
}
}
remove() {
return {
movimiento: clickEvent => {
const id = $(clickEvent.currentTarget).data('id')
app.handlers.movimientos.remove().movimiento(id).then(() => {
app.handlers.table.draw().table(app.handlers.results.props.parsed)
})
}
}
}
}
</script>

View File

@ -0,0 +1,16 @@
<script>
class LoadingHandler {
props
constructor(ids) {
this.props = {
...ids
}
}
show() {
$(this.props.id).addClass('loading')
}
hide() {
$(this.props.id).removeClass('loading')
}
}
</script>

View File

@ -0,0 +1,86 @@
<script>
class MovimientosHandler {
props
constructor({urls, loadingHandler, resultsHandler}) {
this.props = {
urls,
loadingHandler,
resultsHandler
}
}
get() {
return {
movimientos: ({sociedades_ruts, mes}) => {
this.props.loadingHandler.show()
const method = 'post'
const body = new FormData()
sociedades_ruts.forEach(sociedad_rut => {
body.append('sociedades_ruts[]', sociedad_rut)
})
body.set('mes', [mes.getFullYear(), mes.getMonth() + 1, mes.getDate()].join('-'))
return APIClient.fetch(this.props.urls.get, {method, body}).then(response => {
if (!response) {
throw new Error('No se pudo obtener los movimientos')
}
return response.json().then(json => {
this.movimientos = json.movimientos
this.props.resultsHandler.props.movimientos = json.movimientos
this.props.resultsHandler.parse().movimientos()
return json.movimientos
})
}).catch(error => {
console.error(error)
}).finally(() => {
this.props.loadingHandler.hide()
})
}
}
}
edit() {
return {
movimiento: (data) => {
data.set('digito', Rut.digitoVerificador(data.get('rut')))
const method = 'post'
return APIClient.fetch(this.props.urls.edit, {method, body: data}).then(response => {
if (!response) {
throw new Error('No se pudo editar el movimiento')
}
return response.json().then(json => {
this.props.resultsHandler.props.movimientos = this.props.resultsHandler.props.movimientos.map(movimiento => {
if (movimiento.id === json.movimiento.id) {
movimiento.detalles = json.movimiento.detalles
}
return movimiento
})
this.props.resultsHandler.parse().movimientos()
})
})
}
}
}
remove() {
return {
movimiento: id => {
const method = 'delete'
const url = this.props.urls.remove.replace(/\/$/, '') + '/' + id
return APIClient.fetch(url, {method}).then(response => {
if (!response) {
throw new Error('No se pudo eliminar el movimiento')
}
return response.json().then(json => {
this.props.resultsHandler.props.movimientos = this.props.resultsHandler.props.movimientos.filter(movimiento => movimiento.id !== id)
this.props.resultsHandler.parse().movimientos()
})
})
}
}
}
find() {
return {
id: id => {
return this.props.resultsHandler.props.movimientos.find(movimiento => movimiento.id === id)
}
}
}
}
</script>

View File

@ -0,0 +1,234 @@
<script>
class MovimientosTable {
props
columns
constructor({ids, eventHandler}) {
this.props = {
ids,
eventHandler,
movimientos: [],
formatters: {
number: new Intl.NumberFormat('es-CL'),
date: new Intl.DateTimeFormat('es-CL', {
day: '2-digit',
month: '2-digit',
year: 'numeric'
}),
},
}
this.columns = [
{title: 'Sigla', defs: {width: 'short', type: 'string'}, searchable: true, export: true}, //0
{title: 'Banco', defs: {width: 'long', type: 'string'}, searchable: true, export: true},
{title: 'Cuenta', defs: {width: 'short', type: 'string'}, searchable: true, export: true},
{title: 'Fecha', defs: {width: 'long', type: 'string'}, searchable: true, export: true},
{title: 'ISO Fecha', defs: {visible: false}},
{title: 'Mes', defs: {width: 'short', type: 'string'}, searchable: true}, //5
{title: 'Año', defs: {width: 'long', type: 'string'}, searchable: true},
{title: 'Valor', defs: {className: 'dt-right', width: 'long', type: 'num'}, export: true},
{title: 'ISO Valor', defs: {visible: false, type: 'num'}},
{title: 'Glosa', defs: {width: 'short', type: 'string'}, export: true},
{title: 'Centro de Costo', defs: {width: 'short', type: 'string'}, searchable: true, export: true}, //10
{title: 'Categoria', defs: {width: 'short', type: 'string'}},
{title: 'Detalle', defs: {width: 'long', type: 'string'}, export: true},
{title: 'RUT', defs: {width: 'short', type: 'string'}, export: true},
{title: 'Nombre', defs: {width: 'short', type: 'string'}, export: true},
{title: 'Identificador', defs: {width: 'short', type: 'string'}, export: true}, //15
{title: 'Editar', defs: {width: 'short', type: 'string'}},
]
const N = this.columns.filter(column => typeof column.defs.visible === 'undefined' || column.defs.visible).length
const nShort = this.columns.filter(column => column.defs.width === 'short').length
const nLong = this.columns.filter(column => column.defs.width === 'long').length
const short = `${(nShort / N).toFixed(2)}%`
const long = `${(nLong / N).toFixed(2)}%`
this.columns = this.columns.map(column => {
if (typeof column.defs.width === 'undefined') {
return column
}
switch (column.defs.width) {
case 'short':
column.defs.width = short
break
case 'long':
column.defs.width = long
break
}
return column
})
const tr = $(this.props.ids.table).find('thead tr')
tr.empty()
this.columns.forEach(column => {
if (typeof column.defs.className === 'undefined') {
tr.append(`<th>${column.title}</th>`)
return
}
switch (column.defs.className) {
case 'dt-right':
tr.append(`<th class="right aligned">${column.title}</th>`)
break
case 'dt-center':
tr.append(`<th class="center aligned">${column.title}</th>`)
break
default:
tr.append(`<th>${column.title}</th>`)
break
}
})
let dtD = structuredClone(datatables_defaults)
const groupedColumns = Object.groupBy(this.columns, ({defs}) => Object.entries(defs).map((field, value) => `${field}: ${value}`).join(' - '))
const columnDefs = Object.values(groupedColumns).map(group => {
return {
targets: group.map(({title}) => title).map(title => this.columns.map(column => column.title).indexOf(title)),
...group[0].defs
}
})
const searchBuilderColumns = this.columns.filter(column => column.searchable)
.map(column => column.title).map(title => this.columns.map(column => column.title).indexOf(title))
const exportColumns = this.columns.filter(column => column.export)
.map(column => column.title).map(title => this.columns.map(column => column.title).indexOf(title))
const order = ['Sigla', 'Banco', 'ISO Fecha'].map(title => {
return [this.columns.map(column => column.title).indexOf(title), 'asc']
})
dtD = Object.assign(dtD, {
columnDefs,
order,
language: Object.assign(dtD.language, {
searchBuilder: {
add: 'Filtrar',
condition: 'Comparador',
clearAll: 'Resetear',
delete: 'Eliminar',
deleteTitle: 'Eliminar Titulo',
data: 'Columna',
left: 'Izquierda',
leftTitle: 'Titulo Izquierdo',
logicAnd: 'Y',
logicOr: 'O',
right: 'Derecha',
rightTitle: 'Titulo Derecho',
title: {
0: 'Filtros',
_: 'Filtros (%d)'
},
value: 'Opciones',
valueJoiner: 'y'
}
}),
layout: {
top1: {
searchBuilder: {
columns: searchBuilderColumns,
}
},
top1End: {
buttons: [
{
extend: 'excelHtml5',
className: 'green',
text: 'Exportar a Excel <i class="file excel icon"></i>',
title: 'Movimientos Contables',
download: 'open',
exportOptions: {
columns: exportColumns,
format: {
body: (data, row, column, node) => {
if (column === this.columns.map(({title}) => title).indexOf('Fecha')) {
return data.split('-').reverse().join('-')
}
if (column === this.columns.map(({title}) => title).indexOf('Valor')) {
return data.replace(/\./g, '')
}
return data
}
}
},
customize: xlsx => {
const sheet = xlsx.xl.worksheets['sheet1.xml']
const columns = Object.values($('row[r="2"] t', sheet).map((idx, column) => column.textContent))
const columnStylesMap = {
Valor: '63',
Fecha: '15'
}
Object.entries(columnStylesMap).forEach((column, style) => {
const columnIndex = String.fromCharCode('A'.charCodeAt(0) + columns.indexOf(column))
$(`c[r^="${columnIndex}"]`, sheet).attr('s', style)
})
}
}
]
}
},
data: this.props.movimientos,
rowCallback: (row, data) => {
$(row).find(this.props.ids.buttons.edit).on('click', {handler: this.props.eventHandler}, this.props.eventHandler.edit().movimiento)
$(row).find(this.props.ids.buttons.remove).on('click', {handler: this.props.eventHandler}, this.props.eventHandler.remove().movimiento)
}
})
this.props.table = new DataTable(this.props.ids.table, dtD)
}
draw() {
return {
table: (movimientos) => {
const info = this.props.table.page.info()
this.props.table.clear().rows.add(this.draw().movimientos(movimientos)).draw()
this.props.table.page(info.page).draw(false)
$(this.props.ids.buttons.edit).on('click', {handler: this.props.eventHandler}, this.props.eventHandler.edit().movimiento)
$(this.props.ids.buttons.remove).on('click', {handler: this.props.eventHandler}, this.props.eventHandler.remove().movimiento)
},
movimientos: (movimientos) => {
const output = []
movimientos.forEach(movimiento => {
this.draw().movimiento({movimiento, output})
})
return output
},
movimiento: ({movimiento, output}) => {
const valor = movimiento.abono - movimiento.cargo
const fecha = movimiento.fecha
const buttons = {
edit: {
icon: 'edit'
},
remove: {
color: ' red',
icon: 'trash'
}
}
const buttonsHTML = Object.entries(buttons).map(([action, {color='', icon}]) => {
const className = this.props.ids.buttons[action].replace('.', '')
return `<button class="ui${color} icon button ${className}" data-id="${movimiento.id}" data-index="${movimiento.index}" data-type="movimiento"><i class="${icon} icon"></i></button>`
}).join('')
const data = {
Sigla: movimiento.cuenta.inmobiliaria.sigla,
Banco: movimiento.cuenta.banco.nombre,
Cuenta: movimiento.cuenta.cuenta,
Fecha: this.props.formatters.date.format(fecha),
'ISO Fecha': [fecha.getFullYear(), fecha.getMonth() + 1, fecha.getDate()].join('-'),
Mes: fecha.getMonth() + 1,
'Año': fecha.getFullYear(),
Valor: this.props.formatters.number.format(valor),
'ISO Valor': valor,
Glosa: movimiento.glosa,
'Centro de Costo': (movimiento.detalles && movimiento.detalles.centro_costo) ? movimiento.detalles.centro_costo.id : '',
Categoria: (movimiento.detalles) ? movimiento.detalles.categoria : '',
Detalle: (movimiento.detalles) ? movimiento.detalles.detalle : '',
RUT: (movimiento.detalles && movimiento.detalles.digito) ? `${this.props.formatters.number.format(movimiento.detalles.rut)}-${movimiento.detalles.digito}` : '',
Nombre: (movimiento.detalles) ? movimiento.detalles.nombres : '',
Identificador: (movimiento.detalles) ? movimiento.detalles.identificador : '',
Editar: buttonsHTML,
}
const values = []
this.columns.forEach(column => {
values.push(data[column.title])
})
output.push(values)
}
}
}
}
</script>

View File

@ -0,0 +1,37 @@
<script>
class ResultsHandler {
props
constructor() {
this.props = {
movimientos: [],
timezone: ((new Date()).getTimezoneOffset()) / -60
}
}
parse() {
return {
movimientos: () => {
const movimientos = this.props.movimientos
const data = []
movimientos.forEach((movimiento, index) => {
this.parse().movimiento({data, movimiento, index})
})
this.props.parsed = data
},
movimiento: ({data, movimiento, index}) => {
const fecha = new Date(movimiento.fecha + 'Z' + this.props.timezone)
data.push({
tipo: 'movimiento',
id: movimiento.id,
index,
cuenta: movimiento.cuenta,
fecha,
cargo: movimiento.cargo,
abono: movimiento.abono,
glosa: movimiento.glosa,
detalles: movimiento.detalles,
})
}
}
}
}
</script>

View File

@ -0,0 +1,53 @@
@extends('layout.base')
@section('page_content')
<div class="ui container">
<h1 class="ui header">Importar Informe de Tesorería</h1>
<form class="ui form" id="import_form" enctype="multipart/form-data">
<div class="ten wide field">
<label>Informe</label>
<div class="ui file action input">
<input type="file" name="file[]" id="file" accept=".xlsx" multiple placeholder="Informe" />
<label for="file" class="ui icon button">
<i class="file icon"></i>
</label>
</div>
</div>
<button class="ui icon button">
<i class="arrow up icon"></i>
Subir
</button>
</form>
</div>
@endsection
@push('page_scripts')
<script>
$(document).ready(() => {
$('#import_form').submit(submitEvent => {
submitEvent.preventDefault()
let formData = new FormData()
formData.append('file', $('#file')[0].files[0])
const url = '{{$urls->api}}/contabilidad/tesoreria/import'
const method = 'post'
const body = new FormData(submitEvent.currentTarget)
fetchAPI(url, {method, body}).then(response => {
if (!response) {
return
}
return response.json().then(data => {
console.log(data)
})
}).catch(error => {
console.error(error)
})
return false
})
})
</script>
@endpush

View File

@ -10,13 +10,11 @@
<div class="ui two column grid">
<div class="column">
@include('home.cuotas_por_vencer')
@include('home.cierres_vigentes')
</div>
<div class="column">
@include('home.alertas')
</div>
<div class="column">
@include('home.cierres_vigentes')
</div>
</div>
</div>
@endsection

View File

@ -68,21 +68,6 @@
const index = this.data.proyectos.findIndex(proyecto => proyecto.id === data.proyecto_id)
this.data.proyectos[index].escrituras = data.escrituras
})
/*const index = this.data.proyectos.findIndex(proyecto => proyecto.id === proyecto_id)
if (proyecto_id === 3) {
this.data.proyectos[index].escrituras = {
firmar: 20,
pagar: 70,
abonar: 3
}
}
if (proyecto_id === 4) {
this.data.proyectos[index].escrituras = {
firmar: 0,
pagar: 0,
abonar: 2
}
}*/
}
}
},
@ -132,7 +117,7 @@
$('<div></div>').addClass('event').append(
$('<div></div>').addClass('content').html(tipo)
).append(
$('<div></div>').addClass('meta').html(total + '/' + full + ' ' + formatter.format(Math.round(total / full * 10000) / 100).padStart(2, ' ') + '%')
$('<div></div>').addClass('meta').html(total + '/' + full + ' [' + formatter.format(Math.round(total / full * 10000) / 100).padStart(2, ' ') + '%]')
)
)
})

View File

@ -10,11 +10,6 @@
<div class="column">
Inmobiliarias
</div>
{{--<div class="right aligned column">
<button class="ui icon button" type="button">
<i class="plus icon"></i>
</button>
</div>--}}
</h2>
<div class="ui divider"></div>
<div class="ui cards">
@ -23,8 +18,6 @@
<div class="content">
<div class="header">
{{$inmobiliaria->abreviacion}}
{{--<a href="{{$urls->base}}/inmobiliaria/{{$inmobiliaria->rut}}">
</a>--}}
</div>
<div class="description">{{$inmobiliaria->razon}} {{$inmobiliaria->tipoSociedad->descripcion}}</div>
<div class="meta">{{$inmobiliaria->rut()}}</div>

View File

@ -0,0 +1,330 @@
@extends('layout.base')
@section('page_content')
<div class="ui container">
<table class="ui table">
<thead>
<tr>
<th>Nombre</th>
<th>Contacto</th>
<th class="right aligned">
<button class="ui green icon button" id="add_button">
<i class="plus icon"></i>
</button>
</th>
</tr>
</thead>
<tbody id="proveedores">
@foreach ($sociedades as $sociedad)
<tr>
<td>{{$sociedad->nombre}}</td>
<td>{{$sociedad->contacto->nombreCompleto()}}</td>
<td class="right aligned">
<button class="ui icon button" data-sociedad="{{$sociedad->rut}}">
<i class="edit icon"></i>
</button>
<button class="ui red icon button" data-sociedad="{{$sociedad->rut}}">
<i class="remove icon"></i>
</button>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<div class="ui modal" id="add_modal">
<div class="content">
<form class="ui form">
<div class="three wide field">
<label for="rut">RUT</label>
<div class="ui right labeled input">
<input class="right aligned" type="text" id="rut" name="rut" placeholder="RUT" maxlength="10" required />
<div class="ui basic label">-<span id="dv"></span></div>
</div>
</div>
<div class="five wide field">
<label for="nombre">Nombre</label>
<input type="text" id="nombre" name="nombre" placeholder="Nombre" required />
</div>
<div class="field">
<label for="razon">Razón Social</label>
<input type="text" id="razon" name="razon" placeholder="Razón Social" required />
</div>
<div class="four wide field">
<label for="tipo">Tipo</label>
<div class="ui selection dropdown" id="tipo">
<input type="hidden" name="tipo" required />
<i class="dropdown icon"></i>
<div class="default text">Tipo</div>
<div class="menu">
@foreach ($tiposSociedades as $tipo)
<div class="item" data-value="{{$tipo->id}}">{{$tipo->descripcion}}</div>
@endforeach
</div>
</div>
</div>
<div class="ui divider">Contacto</div>
<div class="three wide field">
<label for="rut_contacto">RUT</label>
<div class="ui right labeled input">
<input type="text" id="rut_contacto" name="rut_contacto" placeholder="RUT" maxlength="10" required />
<div class="ui basic label">-<span id="dv_contacto"></span></div>
</div>
</div>
<div class="fields">
<div class="five wide field">
<label for="nombre_contacto">Nombre</label>
<input type="text" id="nombre_contacto" name="nombre_contacto" placeholder="Nombre" required />
</div>
<div class="field">
<label for="apellido_paterno_contacto">Apellido Paterno</label>
<input type="text" id="apellido_paterno_contacto" name="apellido_paterno_contacto" placeholder="Apellido Paterno" required />
</div>
<div class="field">
<label for="apellido_materno_contacto">Apellido Materno</label>
<input type="text" id="apellido_materno_contacto" name="apellido_materno_contacto" placeholder="Apellido Materno" />
</div>
</div>
<div class="field">
<label for="email_contacto">Email</label>
<input type="email" id="email_contacto" name="email_contacto" placeholder="Email" />
</div>
<div class="field">
<label for="telefono_contacto">Teléfono</label>
<div class="ui left labeled input">
<div class="ui basic label">+56</div>
<input type="text" id="telefono_contacto" name="telefono_contacto" placeholder="Teléfono" />
</div>
</div>
</form>
</div>
<div class="actions">
<button class="ui green approve button">Guardar</button>
</div>
</div>
@endsection
@push('page_scripts')
<script>
const proveedores = {
ids: {
modal: '',
buttons: {
add: '',
edit: '',
remove: ''
},
add: {
form: '',
rut: '',
dv: '',
nombre: '',
razon: '',
tipo: '',
contacto: {
rut: '',
dv: '',
nombre: '',
apellido_paterno: '',
apellido_materno: '',
email: '',
telefono: ''
}
},
proveedores: ''
},
data: JSON.parse('{!! json_encode($sociedades) !!}'),
add() {
return {
sociedad: () => {
const data = {
rut: $(this.ids.add.rut).val().replace(/\D/g, ''),
digito: $(this.ids.add.dv).text(),
nombre: $(this.ids.add.nombre).val(),
razon: $(this.ids.add.razon).val(),
tipo_sociedad_id: $(this.ids.add.tipo).dropdown('get value'),
contacto: {
rut: $(this.ids.add.contacto.rut).val().replace(/\D/g, ''),
digito: $(this.ids.add.contacto.dv).text(),
nombres: $(this.ids.add.contacto.nombre).val(),
apellido_paterno: $(this.ids.add.contacto.apellido_paterno).val(),
apellido_materno: $(this.ids.add.contacto.apellido_materno).val(),
email: $(this.ids.add.contacto.email).val(),
telefono: $(this.ids.add.contacto.telefono).val().replace(/\D/g, ''),
}
}
const body = new FormData()
body.append('sociedades[]', JSON.stringify(data))
const url = '{{$urls->api}}/sociedades/add'
const method = 'post'
fetchAPI(url, {method, body})
.then(response => (response) ? response.json() : null)
.then(data => {
if (data.sociedades !== null) {
data.sociedades.forEach(sociedad => {
const exists = this.data.find(s => s.rut === sociedad.rut)
if (typeof exists !== 'undefined') {
return
}
this.data.push(sociedad)
})
this.draw().sociedades()
$(this.ids.modal).find('form.form').trigger('reset')
}
})
}
}
},
edit() {},
remove() {
return {
sociedad: rut => {
const body = new FormData()
body.append('sociedades_ruts[]', rut)
const url = '{{$urls->api}}/sociedades/delete'
const method = 'post'
fetchAPI(url, {method, body})
.then(response => (response) ? response.json() : null)
.then(data => {
if (data.sociedades !== null) {
data.sociedades.forEach(sociedad => {
if (sociedad.sociedad.rut !== rut) {
return
}
if (!sociedad.deleted) {
return
}
$(this.ids.proveedores).find(`button[data-sociedad="${rut}"]`).closest('tr').remove()
})
}
})
}
}
},
draw() {
return {
sociedades: () => {
$(this.ids.proveedores).empty()
this.data.forEach(sociedad => {
$(this.ids.proveedores).append(`
<tr>
<td>${sociedad.nombre}</td>
<td>${sociedad.contacto.nombreCompleto}</td>
<td class="right aligned">
<button class="ui icon button" data-sociedad="${sociedad.rut}">
<i class="edit icon"></i>
</button>
<button class="ui red icon button" data-sociedad="${sociedad.rut}">
<i class="remove icon"></i>
</button>
</td>
</tr>
`)
})
$(this.ids.buttons.remove).click((e) => {
this.remove().sociedad($(e.target).data('sociedad'))
})
}
}
},
formatters() {
return {
rut: value => {
const rut = value.replace(/[^0-9]/g, '')
if (rut.length <= 1) {
return rut
}
return rut.replace(/\B(?=(\d{3})+(?!\d))/g, '.')
},
telefono: value => {
const phone = value.replace(/[^0-9]/g, '')
if (phone.length <= 1) {
return phone
}
return phone.replace(/(\d{2})(\d{3})(\d{4})/, '$1 $2 $3')
}
}
},
digitoVerificador(value) {
let rut = value.replace(/[^0-9kK]/g, '')
if (rut.length < 1) {
return ''
}
let suma = 0
let mul = 2
for (let i = rut.length-1; i >= 0; i--) {
suma += parseInt(rut[i]) * mul
mul = (mul + 1) % 8 || 2
}
const dv = 11 - suma % 11
return dv === 10 ? 'K' : (dv === 11 ? '0' : dv.toString())
},
setup(ids) {
this.ids = ids
$(this.ids.buttons.add).click(() => {
$(this.ids.modal).modal('show')
})
$(this.ids.add.rut).on('input', (e) => {
e.target.value = this.formatters().rut(e.target.value)
$(this.ids.add.dv).text(this.digitoVerificador(e.target.value))
})
if ($(this.ids.add.rut).val().length > 0) {
$(this.ids.add.rut).val(this.formatters().rut($(this.ids.add.rut).val()))
$(this.ids.add.dv).text(this.digitoVerificador($(this.ids.add.rut).val()))
}
$(this.ids.tipo).dropdown()
$(this.ids.add.contacto.rut).on('input', (e) => {
e.target.value = this.formatters().rut(e.target.value)
$(this.ids.add.contacto.dv).text(this.digitoVerificador(e.target.value))
})
if ($(this.ids.add.contacto.rut).val().length > 0) {
$(this.ids.add.contacto.rut).val(this.formatters().rut($(this.ids.add.contacto.rut).val()))
$(this.ids.add.contacto.dv).text(this.digitoVerificador($(this.ids.add.contacto.rut).val()))
}
$(this.ids.add.contacto.telefono).on('input', (e) => {
e.target.value = this.formatters().telefono(e.target.value)
})
if ($(this.ids.add.contacto.telefono).val().length > 0) {
$(this.ids.add.contacto.telefono).val(this.formatters().telefono($(this.ids.add.contacto.telefono).val()))
}
$(this.ids.modal).modal({
onApprove: () => {
this.add().sociedad()
}
})
$(this.ids.buttons.remove).click((e) => {
this.remove().sociedad($(e.target).data('sociedad'))
})
}
}
$(document).ready(() => {
proveedores.setup({
modal: '#add_modal',
buttons: {
add: '#add_button',
edit: '.edit',
remove: '.remove'
},
add: {
form: '#add_modal form.form',
rut: '#rut',
dv: '#dv',
nombre: '#nombre',
razon: '#razon',
tipo: '#tipo',
contacto: {
rut: '#rut_contacto',
dv: '#dv_contacto',
nombre: '#nombre_contacto',
apellido_paterno: '#apellido_paterno_contacto',
apellido_materno: '#apellido_materno_contacto',
email: '#email_contacto',
telefono: '#telefono_contacto'
}
},
proveedores: '#proveedores'
})
})
</script>
@endpush

View File

@ -16,7 +16,14 @@
<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>
<div class="item">
<i class="dropdown icon"></i>
<a class="text" href="{{$urls->base}}/contabilidad/cartolas/diaria">Cartola Diaria</a>
<div class="menu">
<a class="item" href="{{$urls->base}}/contabilidad/cartolas/importar">Importar</a>
</div>
</div>
<a class="item" href="{{$urls->base}}/contabilidad/depositos">Depósitos a Plazo</a>
<a class="item" href="{{$urls->base}}/contabilidad/movimientos">Movimientos</a>
</div>
</div>

View File

@ -33,6 +33,7 @@
</div>--}}
{{--<a class="item" href="{{$urls->base}}/ventas/precios/importar">Importar Precios</a>--}}
{{--<a class="item" href="{{$urls->base}}/ventas/cierres/evaluar">Evaluar Cierre</a>--}}
<a class="item" href="{{$urls->base}}/ventas/facturacion">Facturación</a>
<a class="item" href="{{$urls->base}}/ventas/add">
Nueva Venta
<i class="plus icon"></i>

View File

@ -2,7 +2,12 @@
<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) {
class APIClient {
static fetch(url, options=null, showErrors=false) {
return fetchAPI(url, options, showErrors)
}
}
function fetchAPI(url, options=null, showErrors=false) {
if (options === null) {
options = {}
}
@ -10,7 +15,7 @@
options['headers'] = {}
}
if (!Object.hasOwn(options['headers'], 'Authorization')) {
options['headers']['Authorization'] = 'Bearer {{md5($API_KEY)}}'
options['headers']['Authorization'] = 'Bearer {{md5($API_KEY)}}{{($login->isIn()) ? $login->getSeparator() . $login->getToken() : ''}}'
}
return fetch(url, options).then(response => {
if (response.ok) {
@ -18,9 +23,33 @@
}
throw new Error(JSON.stringify({code: response.status, message: response.statusText, url}))
}).catch(error => {
if (showErrors) {
console.error(error)
}
})
}
const datatables_defaults = {
language: {
emptyTable: 'No hay datos disponibles',
info: 'Mostrando _START_ a _END_ de _TOTAL_ registros',
infoEmpty: 'Mostrando desde 0 a 0 de 0 registros',
infoFiltered: '(filtrado de _MAX_ registros totales)',
lengthMenu: 'Mostrar _MENU_ registros',
loadingRecords: 'Cargando...',
search: 'Buscar:',
zeroRecords: 'No se encontraron registros',
paginate: {
first: 'Primero',
last: 'Último',
next: 'Siguiente',
previous: 'Anterior',
},
aria: {
orderable: 'Ordenar por esta columna',
orderableReverse: 'Ordenar por esta columna en orden inverso',
}
}
}
const calendar_date_options = {
type: 'date',
firstDayOfWeek: 1,
@ -28,9 +57,12 @@
monthFirst: false,
text: {
days: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab'],
dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
months: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
monthsShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
today: 'Hoy'
today: 'Hoy',
now: 'Ahora',
},
formatter: {
date: 'DD-MM-YYYY'

View File

@ -0,0 +1,3 @@
@push('page_scripts')
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.2.0/crypto-js.min.js" integrity="sha512-a+SUDuwNzXDvz4XrIcXHuCf089/iJAoN4lmrXJg18XnduKK6YlDHNRalv4yd1N40OKI80tFidF+rqTFKGPoWFQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
@endpush

View File

@ -1,5 +1,4 @@
@push('page_scripts')
{{--<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>
<script type="text/javascript" src="https://cdn.datatables.net/2.0.3/js/dataTables.min.js"></script>
<script src="https://cdn.datatables.net/2.0.3/js/dataTables.semanticui.min.js"></script>
@endpush

View File

@ -1,9 +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>
<script src="https://cdn.datatables.net/buttons/3.0.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/3.0.1/js/buttons.semanticui.min.js"></script>
<script src="https://cdn.datatables.net/buttons/3.0.1/js/buttons.colVis.min.js"></script>
<script src="https://cdn.datatables.net/buttons/3.0.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/3.0.1/js/buttons.print.min.js"></script>
@endpush

View File

@ -0,0 +1,5 @@
@push('page_scripts')
<script src="https://cdn.datatables.net/datetime/1.5.2/js/dataTables.dateTime.min.js"></script>
<script src="https://cdn.datatables.net/searchbuilder/1.7.0/js/dataTables.searchBuilder.min.js"></script>
<script src="https://cdn.datatables.net/searchbuilder/1.7.0/js/searchBuilder.semanticui.js"></script>
@endpush

View File

@ -0,0 +1,3 @@
@push('page_scripts')
<script src="https://cdn.jsdelivr.net/npm/luxon@3.4.4/build/global/luxon.min.js" integrity="sha256-7NQm0bhvDJKosL8d+6ZgSi2LxZCIcA/TD087GLEBO9M=" crossorigin="anonymous"></script>
@endpush

View File

@ -0,0 +1,26 @@
@push('page_scripts')
<script>
class Rut {
static digitoVerificador(rut) {
if (rut.length === 0) {
return ''
}
let M = 0, S = 1
for (; rut; rut = Math.floor(rut / 10)) {
S = (S + rut % 10 * (9 - M++ % 6)) % 11
}
return S ? S - 1 : 'K'
}
static format(rut) {
if (rut.length === 0) {
return ''
}
rut.replace(/\D/g, '')
return rut.replace(/^(\d{1,2})(\d{3})(\d{3})$/, '$1.$2.$3')
}
static validar(rut, digito) {
return Rut.digitoVerificador(rut) === digito
}
}
</script>
@endpush

View File

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

View File

@ -0,0 +1,4 @@
@push('page_styles')
<link rel="stylesheet" href="https://cdn.datatables.net/datetime/1.5.2/css/dataTables.dateTime.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/searchbuilder/1.7.0/css/searchBuilder.dataTables.min.css" />
@endpush

View File

@ -16,29 +16,30 @@
</div>
@endsection
@include('layout.body.scripts.cryptojs')
@push('page_scripts')
<script type="text/javascript">
function encryptPassword(password) {
const passphrase = Math.floor(Math.random() * Date.now()).toString()
const encrypted = CryptoJS.AES.encrypt(password, passphrase)
return [passphrase, encrypted.toString()].join('')
}
function sendLogin(name, password) {
const data = new FormData()
data.append('name', name)
data.append('password', password)
return fetch('{{$urls->base}}/login', {
method: 'post',
headers: {
const method = 'post'
const headers = {
Accept: 'json'
},
body: data
}).then(response => {
}
const body = new FormData()
body.append('name', name)
body.append('password', encryptPassword(password))
return fetch('{{$urls->base}}/login', {method, headers, body}).then(response => {
if (response.ok) {
return response.json()
}
}).then(data => {
if (data.login === true) {
@if(isset($redirect_uri))
window.location = '{{$redirect_uri}}'
@else
window.location = '{{$urls->base}}'
@endif
window.location = '{{(isset($redirect_uri)) ? $redirect_uri : $urls->base}}'
}
})
}

View File

@ -45,6 +45,9 @@
draw() {
const tipo = this.unidad.proyecto_tipo_unidad.tipo_unidad.descripcion
let unidad = tipo.charAt(0).toUpperCase() + tipo.slice(1) + ' ' + this.unidad.descripcion
if (typeof this.venta !== 'undefined') {
unidad = this.venta.propiedad.tipologia
}
let precio = 0
let propietario = ''
let fecha = ''

View File

@ -789,6 +789,9 @@
$('#add_form').submit(event => {
event.preventDefault()
const button = $(event.currentTarget).find(".ui.button[type='submit']")
button.prop('disabled', true)
button.css('cursor', 'wait')
const body = new FormData(event.currentTarget)
const uri = '{{$urls->api}}/ventas/add'
return fetchAPI(uri, {method: 'post', body}).then(response => {
@ -800,6 +803,8 @@
window.location = '{{$urls->base}}/venta/' + data.venta_id
return true
}
button.prop('disabled', false)
button.css('cursor', 'pointer')
showErrors(data.errors)
return false
})

View File

@ -0,0 +1,166 @@
@extends('ventas.base')
@section('venta_subtitle')
Cuotas - Abono a Escritura
@endsection
@section('venta_content')
<table class="ui table">
<thead>
<tr>
<th rowspan="2">#</th>
<th rowspan="2">Fecha</th>
<th colspan="2">Valor</th>
<th rowspan="2" colspan="2">Estado</th>
<th class="right aligned" rowspan="2">
<button class="ui tertiary green icon button" id="add_button">
<i class="plus icon"></i>
</button>
</th>
</tr>
<tr>
<th class="right aligned">$</th>
<th class="right aligned">UF</th>
</tr>
</thead>
<tbody id="cuotas">
@foreach ($cuotas as $cuota)
<tr data-id="{{$cuota->id}}">
<td class="numero" data-value="{{$cuota->numero}}">{{$cuota->numero}}</td>
<td class="fecha" data-value="{{$cuota->pago->fecha->format('Y-m-d')}}">{{$cuota->pago->fecha->format('d-m-Y')}}</td>
<td class="valor right aligned" data-value="{{$cuota->pago->valor}}">{{$format->pesos($cuota->pago->valor)}}</td>
<td class="valor_uf right aligned" data-value="{{$cuota->pago->valor()}}">{{$format->ufs($cuota->pago->valor())}}</td>
<td class="estado{{$cuota->pago->currentEstado->tipoEstadoPago->descripcion === 'no pagado' ? ' warning' :
($cuota->pago->currentEstado->tipoEstadoPago->descripcion === 'abonado' ? ' positive' : '')}}"
data-value="{{$cuota->pago->currentEstado->tipoEstadoPago->id}}">
{{ucwords($cuota->pago->currentEstado->tipoEstadoPago->descripcion)}}
@if (in_array($cuota->pago->currentEstado->tipoEstadoPago->descripcion, ['abonado', 'depositado']))
<br />
{{$cuota->pago->currentEstado->fecha->format('d-m-Y')}}
@endif
</td>
<td class="collapsing">
@if (in_array($cuota->pago->currentEstado->tipoEstadoPago->descripcion, ['depositado', 'no pagado']))
<form class="ui compact form avance_pago_form" data-id="{{$cuota->id}}"
data-pago="{{$cuota->pago->id}}"
data-estado="{{$cuota->pago->currentEstado->tipoEstadoPago->descripcion}}">
<div class="inline field">
<div class="ui calendar">
<div class="ui icon input">
<input type="text" name="fecha_avance_pago{{$cuota->id}}" />
<i class="calendar icon"></i>
</div>
</div>
<button class="ui tertiary green icon button accept_button" data-id="{{$cuota->id}}"><i class="check icon"></i></button>
@if ($cuota->pago->currentEstado->tipoEstadoPago->descripcion === 'depositado')
<button class="ui tertiary red icon button cancel_button" data-id="{{$cuota->id}}"><i class="remove icon"></i></button>
@endif
</div>
</form>
@endif
</td>
<td class="right aligned">
<button class="ui tertiary icon button edit_button" data-id="{{$cuota->id}}">
<i class="edit icon"></i>
</button>
<button class="ui tertiary red icon button remove_button" data-id="{{$cuota->id}}">
<i class="remove icon"></i>
</button>
</td>
</tr>
@endforeach
</tbody>
</table>
@include('ventas.escrituras.abono.cuotas.add_modal')
@include('ventas.escrituras.abono.cuotas.edit_modal')
@endsection
@push('page_scripts')
<script>
$(document).ready(function () {
const addModal = new AddModal({
modal: '#add_cuota_modal',
form: 'add_cuota_form',
fecha: '#add_fecha',
})
const editModal = new EditModal({
table: 'cuotas',
modal: '#edit_cuota_modal',
form: 'edit_cuota_form',
fecha: '#edit_fecha',
estado: '#edit_estado'
})
document.getElementById('add_button').addEventListener('click', clickEvent => {
addModal.draw()
})
Array.from(document.getElementsByClassName('edit_button')).forEach(button => {
button.addEventListener('click', clickEvent => {
const id = $(clickEvent.currentTarget).data('id')
editModal.getData({cuota_id: id})
})
})
Array.from(document.getElementsByClassName('remove_button')).forEach(button => {
button.addEventListener('click', clickEvent => {
const id = $(clickEvent.currentTarget).data('id')
const url = `{{$urls->api}}/venta/{{$venta->id}}/cuota/${id}`
const method = 'delete'
console.debug(url)
})
})
Array.from(document.getElementsByClassName('avance_pago_form')).forEach(form => {
form.addEventListener('submit', submitEvent => {
submitEvent.preventDefault()
return false
})
const cdo = structuredClone(calendar_date_options)
cdo['initialDate'] = new Date()
cdo['maxDate'] = new Date()
@if ($cuota->pago->currentEstado->tipoEstadoPago->descripcion === 'depositado')
cdo['initialDate'] = new Date('{{$cuota->pago->currentEstado->fecha->format('Y-m-d')}}')
@endif
$(form).find('.ui.calendar').calendar(cdo)
})
Array.from(document.getElementsByClassName('accept_button')).forEach(button => {
button.addEventListener('click', clickEvent => {
const id = $(clickEvent.currentTarget).data('id')
const method = 'post'
const form = Array.from(document.getElementsByClassName('avance_pago_form')).filter(form => parseInt(form.dataset.id) === id)[0]
const pago = form.dataset.pago
const estado = form.dataset.estado
const newEstado = estado === 'depositado' ? 'abonar' : 'depositar'
const url = `{{$urls->api}}/ventas/pago/${pago}/${newEstado}`
const body = new FormData()
const fecha = $(form).find('.ui.calendar').calendar('get date')[0]
body.set('fecha', fecha.getFullYear() + '-' + (fecha.getMonth() + 1).toString().padStart(2, '0') + '-' + fecha.getDate().toString().padStart(2, '0'))
APIClient.fetch(url, {method, body}).then(response => {
if (response.ok) {
return response.json().then(json => {
if (json.success) {
window.location.reload()
}
})
}
})
})
})
Array.from(document.getElementsByClassName('cancel_button')).forEach(button => {
button.addEventListener('click', clickEvent => {
const id = $(clickEvent.currentTarget).data('id')
const method = 'post'
const form = Array.from(document.getElementsByClassName('avance_pago_form')).filter(form => parseInt(form.dataset.id) === id)[0]
const pago = form.dataset.pago
const url = `{{$urls->api}}/ventas/pago/${pago}/devolver`
const body = new FormData()
const fecha = $(form).find('.ui.calendar').calendar('get date')[0]
body.set('fecha', fecha.getFullYear() + '-' + (fecha.getMonth() + 1).toString().padStart(2, '0') + '-' + fecha.getDate().toString().padStart(2, '0'))
console.debug(url, body)
})
})
})
</script>
@endpush

View File

@ -0,0 +1,87 @@
<div class="ui modal" id="add_cuota_modal">
<div class="header">
Agregar Cuota
</div>
<div class="content">
<form class="ui form" id="add_cuota_form">
<input type="hidden" name="venta_id" value="{{$venta->id}}" />
<div class="two wide field">
<label>Número</label>
<input type="text" name="numero" />
</div>
<div class="three wide field">
<label>Fecha</label>
<div class="ui calendar" id="add_fecha">
<div class="ui icon input">
<i class="calendar icon"></i>
<input type="text" name="fecha" />
</div>
</div>
</div>
<div class="three wide field">
<label>Valor $</label>
<div class="ui left labeled input">
<div class="ui basic label">$</div>
<input type="text" name="valor" />
</div>
</div>
</form>
</div>
<div class="actions">
<div class="ui negative button">
Cancelar
</div>
<div class="ui positive right labeled icon button">
Agregar
<i class="add icon"></i>
</div>
</div>
</div>
@push('page_scripts')
<script>
class AddModal {
props
constructor(props) {
this.setup(props)
}
draw() {
$(this.props.modal).modal('show')
}
save() {
const form = document.getElementById(this.props.form)
const body = new FormData(form)
const fecha = $(this.props.fecha).calendar('get date')
body.set('fecha', fecha.getFullYear() + '-' + (fecha.getMonth() + 1).toString().padStart(2, '0') + '-' + fecha.getDate().toString().padStart(2, '0'))
const url = `{{$urls->api}}/venta/{{$venta->id}}/escritura/cuotas/add`
const method = 'post'
APIClient.fetch(url, {method, body}).then(response => {
if (!response) {
return
}
return response.json().then(json => {
if (json.success) {
window.location.reload()
}
})
})
}
setup(ids) {
this.props = ids
$(this.props.modal).modal({
onApprove: () => {
this.save()
}
})
$(this.props.form).submit(event => {
event.preventDefault()
this.save()
return false
})
$(this.props.fecha).calendar(calendar_date_options)
}
}
</script>
@endpush

View File

@ -0,0 +1,130 @@
<div class="ui modal" id="edit_cuota_modal">
<div class="header">
Editar Cuota <span class="numero"></span>
</div>
<div class="content">
<form class="ui form" id="edit_cuota_form">
<input type="hidden" name="id" />
<div class="two wide field">
<label>Número</label>
<input type="text" name="numero" />
</div>
<div class="three wide field">
<label>Fecha</label>
<div class="ui calendar" id="edit_fecha">
<div class="ui icon input">
<i class="calendar icon"></i>
<input type="text" name="fecha" />
</div>
</div>
</div>
<div class="three wide field">
<label>Valor $</label>
<div class="ui left labeled input">
<div class="ui basic label">$</div>
<input type="text" name="valor" />
</div>
</div>
<div class="three wide field">
<label>Estado</label>
<div class="ui selection search dropdown" id="edit_estado">
<i class="dropdown icon"></i>
<input type="hidden" name="tipo_estado_id" />
<div class="default text">Estado</div>
<div class="menu">
@foreach($estados as $estado)
<div class="item" data-value="{{$estado->id}}">{{$estado->descripcion}}</div>
@endforeach
</div>
</div>
</div>
</form>
</div>
<div class="actions">
<div class="ui negative button">
Cancelar
</div>
<div class="ui positive right labeled icon button">
Editar
<i class="edit icon"></i>
</div>
</div>
</div>
@push('page_scripts')
<script>
class EditModal {
props
data
constructor(props) {
this.setup(props)
this.data = null
}
getData({cuota_id}) {
const table = document.getElementById(this.props.table)
const row = table.querySelector(`tr[data-id='${cuota_id}']`)
const fecha = row.querySelector('.fecha').dataset.value.split('-')
this.data = {
id: cuota_id,
numero: row.querySelector('.numero').dataset.value,
fecha: new Date(fecha[0], fecha[1] - 1, fecha[2]),
valor: row.querySelector('.valor').dataset.value,
estado: row.querySelector('.estado').dataset.value
}
this.draw()
}
draw() {
const form = document.getElementById(this.props.form)
form.querySelector('input[name="id"]').value = this.data.id
form.querySelector('input[name="numero"]').value = this.data.numero
$(this.props.fecha).calendar('set date', this.data.fecha)
form.querySelector('input[name="valor"]').value = this.data.valor
$(this.props.estado).dropdown('set selected', this.data.estado)
$(this.props.modal).find('.header .numero').text(this.data.numero)
$(this.props.modal).modal('show')
}
save() {
const form = document.getElementById(this.props.form)
const body = new FormData(form)
const fecha = $(this.props.fecha).calendar('get date')
body.set('fecha', fecha.getFullYear() + '-' + (fecha.getMonth() + 1).toString().padStart(2, '0') + '-' + fecha.getDate().toString().padStart(2, '0'))
body.set('tipo_estado_id', $(this.props.estado).dropdown('get value'))
const url = `{{$urls->api}}/venta/{{$venta->id}}/escritura/cuota/${this.data.id}/edit`
const method = 'post'
APIClient.fetch(url, {method, body}).then(response => {
if (!response) {
return
}
return response.json().then(json => {
if (json.success) {
window.location.reload()
}
})
})
}
setup(ids) {
this.props = ids
$(this.props.modal).modal({
onApprove: () => {
this.save()
},
onHidden: () => {
this.data = null
}
})
$(this.props.form).submit(event => {
event.preventDefault()
this.save()
return false
})
$(this.props.fecha).calendar(calendar_date_options)
$(this.props.estado).dropdown()
}
}
</script>
@endpush

View File

@ -14,6 +14,7 @@
<p>Crédito {{$format->ufs($venta->formaPago()->credito->pago->valor())}}</p>
@endif
</div>
<a href="{{$urls->base}}/venta/{{$venta->id}}/escritura/cuotas" class="ui small green button"><i class="plus icon"></i> Agregar Cuotas</a>
<form class="ui form" id="add_form">
<div class="three wide field">
<label for="fecha">Fecha</label>

View File

@ -5,6 +5,24 @@
@endsection
@section('venta_content')
@if (count($venta->formaPago()->cuotasAbono) > 0)
<a href="{{$urls->base}}/venta/{{$venta->id}}/escritura/cuotas" class="ui tertiary green button">Ver Cuotas</a>
<div class="ui compact segment">
<div class="header">
Cuotas
</div>
<div class="ui horizontal list">
<div class="item">
{{$format->pesos($venta->formaPago()->cuotasAbono('pesos'))}}
</div>
<div class="item">
{{$format->ufs($venta->formaPago()->cuotasAbono())}}
</div>
</div>
</div>
@else
<a href="{{$urls->base}}/venta/{{$venta->id}}/escritura/cuotas" class="ui small green button"><i class="plus icon"></i> Agregar Cuotas</a>
@endif
<form class="ui form" id="edit_form">
<div class="three wide field">
<label for="fecha">Fecha</label>
@ -15,6 +33,26 @@
</div>
</div>
</div>
<div class="three wide field">
<label for="valor">Valor</label>
<div class="ui left labeled input">
<div class="ui basic label">$</div>
<input type="text" name="valor" value="{{$venta->formaPago()->escritura->pago->valor}}" />
</div>
</div>
<div class="three wide field">
<label>Estado</label>
<div class="ui selection dropdown" id="estado">
<input type="hidden" name="estado" />
<div class="default text">Estado</div>
<i class="dropdown icon"></i>
<div class="menu">
@foreach($estados as $estado)
<div class="item" data-value="{{$estado->id}}">{{ucwords($estado->descripcion)}}</div>
@endforeach
</div>
</div>
</div>
<button class="ui button">Guardar</button>
</form>
@endsection
@ -27,12 +65,13 @@
data.set('venta', {{$venta->id}})
const fecha = $('#fecha').calendar('get date')
data.set('fecha', fecha.toISOString())
data.set('estado', $('#estado').dropdown('get value'))
return fetchAPI(url, {method: 'post', body: data}).then(response => {
if (response.ok) {
return response.json()
}
}).then(json => {
if (!json.edited) {
if (!json.success) {
return
}
window.location = '{{$urls->base}}/venta/{{$venta->id}}'
@ -41,6 +80,8 @@
$(document).ready(() => {
calendar_date_options.initialDate = new Date({{$venta->currentEstado()->fecha->format('Y, m-1, j')}})
$('#fecha').calendar(calendar_date_options)
$('#estado').dropdown()
$('#estado').dropdown('set selected', '{{$venta->currentEstado()->id}}')
$('#edit_form').submit(event => {
event.preventDefault()
editEscritura()

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