446 Commits

Author SHA1 Message Date
7bd946976e Merge branch 'develop' into feature/cierres 2025-08-12 19:24:48 -04:00
27f7d1d579 Mostrar reservas 2025-08-12 19:17:32 -04:00
977b5f76f4 Mostrar reservations 2025-08-08 17:06:16 -04:00
42336133cd Reservations 2025-08-08 17:04:50 -04:00
62aa6a08a0 Listado de cierres 2025-08-05 18:18:05 -04:00
28b272bc55 Merge branch 'develop' into feature/cierres 2025-08-05 15:46:21 -04:00
909bb2b879 Mostrar reservas 2025-07-22 18:21:05 -04:00
39bc190775 Cambios a modelo Reservation 2025-07-22 18:20:48 -04:00
413709e443 Cambio a migraciones de reservation 2025-07-22 18:19:49 -04:00
808b55cf29 Merge branch 'develop' into feature/cierres 2025-07-22 18:15:55 -04:00
6c25c5f6d5 FIX: Venta no se actualizaba 2025-07-18 16:20:23 -04:00
3ce41914e5 FIX: Venta desistida pero sin resciliacion 2025-07-18 16:15:30 -04:00
56505fe519 Merge 2025-07-18 13:57:31 -04:00
c7aa731261 FIX: Desistir cuando no existe pie 2025-07-18 13:56:07 -04:00
b211af47d0 Permissions 2025-07-15 23:30:53 -04:00
fd134804a2 Queue runs batch of jobs 2025-07-15 23:18:09 -04:00
d3d6940842 Add retries when job execute failed 2025-07-15 23:07:32 -04:00
c512d7a79a FIX: sacar configuracion de json 2025-07-15 22:56:48 -04:00
9310d65d77 Push can now push json file 2025-07-15 22:19:07 -04:00
8b3cf47762 Pending now in queue 2025-07-15 22:18:45 -04:00
48f992dd47 Merge remote-tracking branch 'origin/feature/cierres' into feature/cierres 2025-07-15 19:07:03 -04:00
2f1628887e Permisos entrypoint 2025-07-15 19:06:07 -04:00
79073ebeb7 Beanstalkd -> Pheanstalk 2025-07-15 19:04:19 -04:00
501151a90e Beanstalkd for jobs 2025-07-14 14:29:41 -04:00
e6e7470bb2 Limit children 2025-07-12 11:00:08 -04:00
2efe4e4a85 Don't run all jobs directly 2025-07-12 10:48:50 -04:00
5ab94e7b2d Reset memory 2025-07-12 10:33:50 -04:00
e037c86e6f Run one job at a time. 2025-07-12 10:31:48 -04:00
595a71d7dd System info 2025-07-12 10:30:32 -04:00
8666499626 Merge remote-tracking branch 'origin/feature/cierres' into feature/cierres 2025-07-12 09:43:19 -04:00
f752256f76 Fcgi idle timeout 2025-07-12 09:43:02 -04:00
6dda5aef00 Habilitar sync 2025-07-03 17:30:58 -04:00
18e79b76d6 Better logging 2025-07-03 17:17:55 -04:00
239376fadc Send all 2025-07-03 17:13:22 -04:00
15ba23bf23 Toku update output 2025-07-03 17:06:00 -04:00
73328240cc Update invoices 2025-07-03 17:00:01 -04:00
495581de8f Update subscriptions 2025-07-03 16:59:41 -04:00
cb0731b67d Update subscriptions 2025-07-03 16:37:57 -04:00
4980839568 Merge remote-tracking branch 'origin/feature/cierres' into feature/cierres 2025-07-01 17:16:39 -04:00
7714e25270 Uso de cuenta al agregar y editar para Toku 2025-07-01 17:14:53 -04:00
8a043b21bc Migracion para guardar account-key de toku 2025-07-01 17:14:21 -04:00
925faeb6f4 Migracion para guardar account-key de toku 2025-07-01 15:28:07 -04:00
f11b7dcd9b PHP more request handlers 2025-06-30 17:25:48 -04:00
e35053edce FastCGI Command max requests 2025-06-30 17:09:45 -04:00
829ab86770 FastCGI pool 2025-06-30 16:39:55 -04:00
4b66694166 Batch queue 2025-06-30 15:52:36 -04:00
d4f8804fbb Batch queue 2025-06-30 15:52:28 -04:00
5f4d8a4bc2 FIX: separate details exception 2025-06-30 11:47:57 -04:00
1fa152c07f FIX: new line exception.log 2025-06-30 11:44:05 -04:00
7f8bd607e3 Job retries 2025-06-27 18:42:47 -04:00
1bbee1121b FIX: Authorization en FastCGI 2025-06-27 18:00:45 -04:00
352e33179c More detail 2025-06-27 17:42:09 -04:00
f34d7338f1 FIX: FasCGI Response 2025-06-27 17:35:17 -04:00
4dd83ae63d FIX: Error observado 2025-06-27 17:24:04 -04:00
e265854958 FIX: Error observado 2025-06-27 17:21:25 -04:00
174b29efff FIX: str_starts_with 2025-06-27 17:17:21 -04:00
1c0f4a5ae9 Try to register fatal errors in file 2025-06-27 17:17:06 -04:00
ccee5f9f56 FIX: more details 2025-06-27 16:58:15 -04:00
9677f11aef FIX: seguir cuando existe error. 2025-06-27 16:56:24 -04:00
c21de2848d FIX: saltarse lineas comentadas 2025-06-27 16:51:16 -04:00
348bb18654 LoggerEnabled Fix 2025-06-25 18:14:43 -04:00
a2a9f4bbb4 LoggerEnabled Fix 2025-06-25 18:11:28 -04:00
ab7328b40b FastCGI 2025-06-25 18:07:08 -04:00
7f97862324 Revisiones 2025-06-25 12:41:28 -04:00
9edf0d9120 Revisiones 2025-06-25 12:22:01 -04:00
ca1ed3f870 Pruebas de integracion con seeds 2025-06-24 21:55:02 -04:00
360537c638 Prueba de integracion para service worker 2025-06-24 14:24:47 -04:00
a6e6b8acc0 Prueba de integracion para service worker 2025-06-24 12:56:03 -04:00
a4e2b4fc7a Seed TipoEstadoPago 2025-06-24 12:55:46 -04:00
479047cd6a Dependencias para testeo 2025-06-24 12:55:02 -04:00
29d9ea8e4a Correr seeds y botar tablas al final 2025-06-24 12:54:48 -04:00
a7cd661938 Registro de worker 2025-06-24 12:54:32 -04:00
7bdcc7168a Container separado a archivo a parte para poder cargarlo en otros lados 2025-06-24 12:54:19 -04:00
d2dff57531 FIX: id de migracion 2025-06-24 12:53:56 -04:00
39198bbe7c get Uf asincronico 2025-06-24 11:20:53 -04:00
200510d60a Prueba Service Worker 2025-06-24 11:20:21 -04:00
ecc67a43c8 Service Worker, corre metodos de servicios asincronicamente, requiere parametros escalares y no retornar mas que bool o void 2025-06-24 11:19:58 -04:00
64791d1fc5 Alias enqueue 2025-06-24 11:16:29 -04:00
4053854410 Prueba UF 2025-06-24 11:16:19 -04:00
a687743762 FIX: No buscar UF para fechas mayores a hoy o día nueve del mes 2025-06-24 11:04:33 -04:00
38fb6f3bcc Pausa a external 2025-06-19 16:47:24 -04:00
1e6bac61b5 FIX: Limpiar archivos 2025-06-19 16:47:06 -04:00
a611ae247d FIX: prorrateo ingresado en valor % 2025-06-12 11:28:04 -04:00
c02c6eb15c FIX: Add custom HttpException 2025-06-10 19:36:56 -04:00
b7e0217cf3 FIX: remove ext-http 2025-06-10 19:35:17 -04:00
2fd1a44984 FIX: install ext-http with external script 2025-06-10 19:04:32 -04:00
fe912db62b Add ext-http 2025-06-10 18:20:05 -04:00
da90160a2a Add ext-http 2025-06-10 18:02:05 -04:00
64047ef577 TOKU: FIX: exceptions 2025-06-10 17:48:36 -04:00
feef90afd6 TOKU: payments loop through pages 2025-06-10 17:46:16 -04:00
32e1e49a97 FIX: cuerpo para borrar payments 2025-06-10 17:34:04 -04:00
11c64cb10f FIX: url para borrar 2025-06-10 17:29:39 -04:00
823f97ce5f FIX: log levels 2025-06-10 17:24:38 -04:00
4ae72199fc Better external logging 2025-06-10 17:00:20 -04:00
d841b1aeed FIX: url de payments en Toku 2025-06-10 16:57:34 -04:00
666cac1958 FIX: url de payments en Toku 2025-06-10 16:54:46 -04:00
71c189e236 FIX: circular dependency 2025-06-10 16:49:34 -04:00
5b6a1c42e3 Toku: reorden 2025-06-10 16:28:46 -04:00
81bce6fe7f Cleanup 2025-06-10 16:28:13 -04:00
e1072ea252 Toku: Reset payments 2025-06-10 16:26:33 -04:00
21473fe52c Valor cuota en CLP 2025-06-10 15:27:09 -04:00
7d589e0e87 Valor cuota en CLF 2025-06-10 15:24:51 -04:00
c48a0d2381 Valor cuota en CLP 2025-06-10 15:14:25 -04:00
abb1ce7299 Mas logging 2025-06-09 12:44:42 -04:00
f1ed9668fc email -> mail 2025-06-06 18:25:12 -04:00
f9ae809fc4 Data too large 2025-06-06 18:10:59 -04:00
06e5292af1 Log add response 2025-06-06 18:10:06 -04:00
47ba664142 Log customer params 2025-06-06 18:04:57 -04:00
d10ee33215 better format for mysql 2025-06-06 17:55:58 -04:00
5134630525 Correct Exceptions 2025-06-06 17:37:42 -04:00
13b246b998 Merge remote-tracking branch 'origin/feature/cierres' into feature/cierres 2025-06-06 17:11:33 -04:00
d601d7d719 Mas logs y middlewares en Guzzle 2025-06-06 17:11:22 -04:00
dc0ae2746b FIX: Correct HMAC validation 2025-06-03 23:07:47 -04:00
eb402b1b71 FIX: notice logs 2025-06-03 23:07:08 -04:00
c5188a1feb HMAC not static 2025-06-03 23:04:57 -04:00
1c3052219c Debug 2025-06-03 22:59:49 -04:00
9e8a388653 Debug 2025-06-03 22:59:03 -04:00
cbee830f7a Debug 2025-06-03 22:55:35 -04:00
d5b8c7f877 FIX: JSON_SEARCH 2025-06-03 22:51:26 -04:00
b668844fea Debug 2025-06-03 22:29:13 -04:00
f2169c9536 FIX: fetch all values in column 2025-06-03 22:27:15 -04:00
48bcb33bad FIX: event_types -> events 2025-06-03 22:24:09 -04:00
92ae0b4ac2 FIX: Missing connection 2025-06-03 22:22:33 -04:00
44540d0dc3 Validated external query log 2025-06-03 22:19:11 -04:00
d9a2f63691 Use webhook secrets to validate 2025-06-03 22:11:57 -04:00
b10accf602 Store webhooks 2025-06-03 22:01:03 -04:00
981858f251 HMAC implementation for signature validation 2025-06-03 21:53:49 -04:00
8c0bd450ef FIX: delete url 2025-06-03 21:26:10 -04:00
8996765cb4 FIX: maxLogLevel 2025-06-03 21:16:44 -04:00
ec2451cb69 FIX: maxLogLevel 2025-06-03 21:12:43 -04:00
37d30d2aec Cleanup logs 2025-06-03 21:09:13 -04:00
afb6e2526f FIX: Timezone cli 2025-06-03 20:14:15 -04:00
a9b6f2a87b FIX: Error code for missing TOKU_ENV 2025-06-03 19:58:36 -04:00
9aeb6906f6 Debug 2025-06-03 19:43:46 -04:00
879d365baf Not needed 2025-06-03 19:42:23 -04:00
1d03b262ae Debug 2025-06-03 19:35:36 -04:00
2c175c8171 Detailed login errors 2025-06-03 19:20:55 -04:00
a750bdbfaa Detailed login errors 2025-06-03 19:20:44 -04:00
7f6d0232c0 Cleanup files 2025-06-03 19:20:09 -04:00
37cff67a1c Log reseteando 2025-06-03 17:06:39 -04:00
bc3d739af9 Cleanup 2025-06-03 16:52:01 -04:00
46efbb57c1 Log body de reset 2025-06-03 16:25:07 -04:00
d71333b334 Queue cada 2 minutos 2025-06-03 16:13:04 -04:00
688b500f1e Parametros correctos 2025-06-03 16:06:14 -04:00
d4b1a66a9e FIX: ventas_ids vacios 2025-06-03 16:02:04 -04:00
e796d91d95 Si token no existe, no se puede borrar 2025-06-03 16:01:48 -04:00
2a442417ce FIX: Loop frequency 2025-06-03 13:01:40 -04:00
3c161ed4e9 Loop frequency 2025-06-03 12:58:57 -04:00
3c8822e531 FIX: Log job requests 2025-06-03 12:46:47 -04:00
b3b91d3f8f Log job requests 2025-06-03 12:45:36 -04:00
6e34a76a3f FIX: Request log processor no funciona 2025-06-03 12:34:08 -04:00
ed29dfb984 Request Log Processor 2025-06-03 12:17:52 -04:00
7f37dc76e3 Log forbidden 2025-06-03 12:06:35 -04:00
a62293e509 Mejora en separacion 2025-06-03 12:06:02 -04:00
fbfc2cb8ae Cambios de usos de env vars 2025-06-03 12:04:53 -04:00
02665ac6bd Extras ya enviados por processor 2025-06-03 11:52:31 -04:00
300d966f3f Separation of logs in cli 2025-06-03 11:49:03 -04:00
27031035ed Filtro en server params faltante 2025-06-03 11:45:36 -04:00
18fc9a76fd Filtro en server params 2025-06-03 11:37:14 -04:00
cb6fa73a21 FIX: Recargar proyectos si no se encuentra proyecto_id, si aun no existe retornar 0 2025-06-03 10:35:07 -04:00
8796762cfe Mas datos en el registro de accessos 2025-06-03 10:24:54 -04:00
99c9952c93 Mas datos en el registro de logins. 2025-06-03 10:22:52 -04:00
9895fd6a70 FIX: Mas registro de login desde cli 2025-06-02 18:45:11 -04:00
c1149d89be FIX: Cleanup after create, but before initialized query. 2025-06-02 18:03:43 -04:00
7d8e2249de FIX: Detalle en logging. 2025-06-02 17:58:24 -04:00
a54586e870 FIX: valor cuota cuando UF no existe. 2025-05-30 17:10:59 -04:00
734f258382 Validar con headers 2025-05-30 14:18:48 -04:00
f728ed0b55 FIX: Log de envio 2025-05-30 12:48:12 -04:00
6144accb8e FIX: Toku envía complejo el header 2025-05-29 19:56:43 -04:00
f399eb8d47 Validate with service 2025-05-29 19:43:06 -04:00
b4159d1417 Log external tries 2025-05-29 19:24:35 -04:00
2a792a947d More granular control of external validation configuration 2025-05-29 19:22:55 -04:00
25710d616a Registro de success entrantes 2025-05-29 19:15:17 -04:00
3197802264 Cleanup 2025-05-29 19:10:09 -04:00
6c53127c2f Body json 2025-05-29 19:06:54 -04:00
b7391a77d3 DEBUG: body 2025-05-29 17:44:30 -04:00
5b499aee75 Content-type 2025-05-29 17:43:14 -04:00
4505531c5f Output body 2025-05-29 17:42:21 -04:00
3f8adc753c Add body to Enqueue command 2025-05-29 17:40:45 -04:00
ace205798f FIX: Manejo de Errores en Ventas 2025-05-29 16:02:13 -04:00
6e0e1fc75e Parametros faltantes 2025-05-27 19:30:08 -04:00
026474c63c Enqueue ventas para enviar a Toku 2025-05-27 19:24:23 -04:00
f32204df97 FIX: Remove toku concept in database 2025-05-27 18:35:06 -04:00
2852816eae FIX: Parametros extra para Toku 2025-05-27 18:27:37 -04:00
892cdf324f Comando para resetear Toku 2025-05-27 18:17:56 -04:00
a9a10e012d Uso de external Logger para los servicios External 2025-05-27 16:28:34 -04:00
b7089f7a1c Timezone por DI 2025-05-27 16:19:47 -04:00
aed26cfcd8 FIX: Estado cuota abono 2025-05-23 12:15:51 -04:00
896dded6eb Apellido materno en blanco 2025-05-23 12:12:34 -04:00
3b03c4b64b Logging 2025-05-19 16:06:44 -04:00
f34ed03b84 Logging 2025-05-19 14:02:55 -04:00
ce75ec1548 External logs
FIX: Ofuscator
2025-05-19 13:55:59 -04:00
312baa34f6 Access Logs 2025-05-19 13:14:13 -04:00
b7c5e4ebc3 Opcion de enviar update a los servicios externos 2025-05-16 19:14:20 -04:00
105179b4ed Fixes de telefono y apellido de persona 2025-05-16 16:35:17 -04:00
16cd29635d Zona horaria en cli 2025-05-16 14:47:31 -04:00
2bdb2a0ed0 Uso de zona horaria en output de comandos 2025-05-16 14:44:48 -04:00
8ce7d2570d FIX: Check if invoice exists before sending, if exists then save
Send correct UF amount if date in future
2025-05-16 14:36:20 -04:00
8ba54fd3ad Queue command with direct redis access so it's faster 2025-05-16 13:56:32 -04:00
f47f86dd2b BaseLoop different logger 2025-05-16 12:54:52 -04:00
8ca68bf7e8 Crontab para revisar servicios externos 1 vez al dia 2025-05-15 19:33:53 -04:00
8965354528 Cambio en queue para que no quede pegado esperando respuesta en cli.
Chequeo de servicios externos para agregar elementos pendientes.
2025-05-15 19:32:25 -04:00
8d32aecd09 Zona horaria en logs 2025-05-15 16:07:29 -04:00
c8f79e076e Envio de datos editados de Propietario 2025-05-15 16:05:55 -04:00
9e0d604d79 Respuesta 200 a webhook de Toku 2025-05-15 16:05:03 -04:00
331d004040 Eliminar script::type 2025-05-15 16:04:35 -04:00
03317b3aa5 Agregar datos propietario 2025-05-15 15:23:34 -04:00
e33edc4d7b FIX: proyectos minuto 0 de cada hora, en vez de cada minuto de esa hora 2025-05-15 12:08:33 -04:00
bb459a2ff5 FIX: proxy no identificado por web 2025-05-15 11:47:28 -04:00
5e2d2e861f Logs no pasan desbordan de nivel 2025-05-15 10:53:59 -04:00
e9b2fe9963 FIX: monto enviado en UF 2025-05-15 10:12:34 -04:00
2f481ef8a9 FIX: mapeo de datos al actualizar pago 2025-05-15 10:06:35 -04:00
386fe452af Catch error 2025-05-15 10:06:00 -04:00
91ad1e39f8 Endpoint para la prueba 2025-05-14 12:41:59 -04:00
a3a5b58cfb Correctos parametros 2025-05-13 20:19:03 -04:00
1d77d65af2 Ventas con cuotas pendientes 2025-05-13 20:18:51 -04:00
0f0c81e283 Uso de request en queue 2025-05-13 20:18:40 -04:00
ac278ca690 Parametros correctos para persona. 2025-05-13 20:18:20 -04:00
97d34f9ad6 Uso de request original 2025-05-13 20:18:09 -04:00
134588c96d Envio de estado de cuotas. 2025-05-13 20:17:53 -04:00
8b6516241d Manejo de contenido 2025-05-13 20:13:15 -04:00
d6e60efcaf Parametros correctos 2025-05-13 20:12:26 -04:00
3e937ab748 Fetch ventas con cuotas pendientes 2025-05-13 20:11:49 -04:00
fa6881d0a9 Formato correcto de fecha y bool 2025-05-13 20:11:02 -04:00
f07c1f1cbd Formato correcto de fecha 2025-05-13 20:10:46 -04:00
148d08089d Estado Cuota y Pago 2025-05-13 20:10:24 -04:00
45b6ee710e Job mas completo 2025-05-13 20:10:12 -04:00
c84277fdc4 Update services 2025-05-13 20:09:50 -04:00
c0024a4a63 Parse body correctly and test fill 2025-05-13 20:03:20 -04:00
308a84a448 Send current request to queue for parameters 2025-05-13 20:02:50 -04:00
91c74bf113 Min log level 2025-05-13 16:17:47 -04:00
024a6eae54 Jobs not being updated 2025-05-13 16:06:09 -04:00
d536342425 No output on wait 2025-05-13 15:58:49 -04:00
e7f3b33850 Wait till next minute after running jobs 2025-05-13 15:53:13 -04:00
c47d94d475 FIX: missing use 2025-05-13 15:49:41 -04:00
ee74fc7588 FIX: esperar al siguiente minuto 2025-05-13 15:47:18 -04:00
5ac324de6a Hora en output 2025-05-13 15:40:32 -04:00
dfb0ff7aea Missing middlewares 2025-05-13 15:16:29 -04:00
6d1a1c914a Wait for execution 2025-05-13 15:15:20 -04:00
b45d03aa7e Reestructura APIClient 2025-05-13 09:32:48 -04:00
4e0b611bcf FIX: Mayuscula 2025-05-13 09:31:51 -04:00
20ea5d021d FIX: missing text 2025-05-12 19:58:20 -04:00
32dc24a783 Newline 2025-05-12 19:54:03 -04:00
95a6aa96e9 Queue 2025-05-12 19:46:31 -04:00
f14cdd2730 Updates 2025-05-12 19:46:09 -04:00
3006adb0f7 Configuracion servicios 2025-05-12 19:44:58 -04:00
d22480dcb8 User edit and delete 2025-05-12 19:44:16 -04:00
425b85e40d Unify cli logs 2025-05-12 19:44:00 -04:00
2c21e48562 FIX: DEPRECATED 2025-05-12 19:43:39 -04:00
8d3ce99be7 Update env sample 2025-05-12 18:32:30 -04:00
35386724b3 FIX: DEPRECATED 2025-05-12 18:07:14 -04:00
1597657f0e FIX: Toku external 2025-05-12 16:35:33 -04:00
c6bbaf3404 FIX: DEPRECATED 2025-05-12 16:08:10 -04:00
9e2d7277b0 Validacion API/external 2025-05-12 16:01:09 -04:00
abe37227ce API/external 2025-05-12 15:47:51 -04:00
32130f0bc2 Usando variables definidas 2025-05-12 14:04:58 -04:00
d78bdaa7f5 Falta ortografia 2025-05-12 13:57:43 -04:00
1266c3859d Migration for Jobs 2025-05-12 13:54:28 -04:00
c5466b2c4d Ignore optionals 2025-05-12 13:15:22 -04:00
6d8e8a9068 Env sample update 2025-05-12 13:06:44 -04:00
4d5b657b92 Manejo de trabajos en cli por php en vez de cron 2025-05-10 12:40:06 -04:00
4ca1616dfc Integracion Toku a flujo 2025-05-10 12:39:31 -04:00
fb7177fd65 Reorden Toku 2025-05-10 12:38:14 -04:00
1486d6cf38 Toku settings 2025-05-10 12:32:01 -04:00
8b2de31e02 Job Queue 2025-05-10 12:30:35 -04:00
61324f159b Toku endpoint 2025-05-10 12:30:21 -04:00
c95e74d574 Controlador Toku 2025-05-09 18:31:00 -04:00
59ecb6cc79 Se agregan fetchs 2025-05-09 18:05:40 -04:00
db84187461 Pruebas de Toku 2025-05-09 18:05:19 -04:00
c2f98c8b0d Excepcion 2025-05-09 18:04:37 -04:00
8d73987ac3 FIX: Cambios a Servicios Toku 2025-05-09 18:04:17 -04:00
400b2754bf FIX: Totales para multipropietario no sumaban correctamente 2025-05-09 13:33:08 -04:00
418becaeda FIX: onChange 2025-05-08 18:15:32 -04:00
679b401101 Servicio Toku para enviar datos 2025-05-08 17:17:49 -04:00
26b6862955 FIX: prueba Servicio Customer 2025-05-08 17:17:24 -04:00
e239669839 FIX: prueba modelo Customer 2025-05-08 17:16:55 -04:00
adc0e52c1e Fix: estructura interface 2025-05-08 17:16:32 -04:00
d1905194bd rut en Customer en formato Toku 2025-05-08 17:16:03 -04:00
a5c1d60819 Servicios para Toku 2025-05-08 16:17:26 -04:00
5ad4fc4038 Tests de Repositories 2025-05-08 16:17:14 -04:00
ca5354a3ee Cambio en namespace 2025-05-08 11:13:23 -04:00
c1ebac6c0c Pruebas de repositories 2025-05-08 11:13:06 -04:00
f742c7ddd0 Pruebas de modelos 2025-05-08 10:45:31 -04:00
5d5f9866bb Modelos para Toku 2025-05-07 20:05:00 -04:00
0866292d84 Migraciones para guardar datos de Toku 2025-05-07 20:04:27 -04:00
e02ed4684f LoggerAwareInterface abstract 2025-05-07 20:04:06 -04:00
8be5f94b7c Log solo los errores fatales. 2025-05-07 20:01:55 -04:00
878b02ee52 SII falla si fecha está en el futuro. 2025-05-07 19:42:39 -04:00
f3e15b34a8 Persona conectada con Propietario 2025-05-07 19:24:33 -04:00
3903551176 FIX: migraciones fallando 2025-05-07 19:23:37 -04:00
43eb8ec758 FIX: no borra todo 2025-05-07 19:22:39 -04:00
a405b15410 Uso de script central de Rut 2025-05-06 10:00:12 -04:00
a2f2d94e64 Docker image con tag 2025-05-06 09:47:54 -04:00
0587b64d65 Docker image 2025-05-06 09:37:23 -04:00
a6b81f1bff FIX: Not needed 2025-05-06 09:15:46 -04:00
4239bafc26 FIX: echo append 2025-05-05 19:33:46 -04:00
6591e9f80e FIX: debian ftp 2025-05-05 19:33:01 -04:00
b57f32c86b FIX: Circular dependency 2025-05-05 19:10:31 -04:00
0e903f99c4 FIX: Circular dependency 2025-05-05 19:08:44 -04:00
186cd0f5b8 Reparaciones con Prueba 2025-05-05 19:01:15 -04:00
167d8e1ab7 PHP Dom en PHP 8.4 2025-05-05 19:00:41 -04:00
46802507a7 SII como provider de UF 2025-05-05 18:16:18 -04:00
aaf2ed7612 UF service en Venta 2025-05-05 18:15:48 -04:00
3ced9e40b1 const en Money y multi provider 2025-05-05 18:15:29 -04:00
594cb68b09 Provider SII 2025-05-05 18:14:50 -04:00
af68c4b8ec Ine null date 2025-05-05 18:14:20 -04:00
ea8f483dd5 FIX: Repository UF 2025-05-05 18:13:55 -04:00
5f53c77a1f Repository::getConnection 2025-05-05 18:13:12 -04:00
b9adb9108b Provider null date 2025-05-05 18:12:58 -04:00
8be085222a Not Allowed template 2025-05-05 16:46:41 -04:00
d1e4314b35 Valor de UF de hoy cuando no se encuentra valor. 2025-05-05 16:46:14 -04:00
7d04b406ab Grabar UF y capacidad de obtener hoy. 2025-05-05 16:45:43 -04:00
972e57b6f1 Mejora en respuesta cuando no existe algun valor. 2025-05-05 16:43:24 -04:00
5f63bdbf4a Fecha maxima de venta es hoy 2025-05-05 16:41:08 -04:00
a8325c3310 Uso de NumberInput en Edit BonoPie 2025-05-05 15:55:23 -04:00
7e54b72587 NumberInput, para formateo de numeros 2025-05-05 15:45:07 -04:00
ebe31a3d3d Guardar UF en DB 2025-05-05 15:40:55 -04:00
db6445bcf3 Cleanup View 2025-05-05 15:40:26 -04:00
4e1901b7c8 FatalErrors 2025-05-05 15:40:05 -04:00
c3316029c9 Se borra migracion duplicada 2025-05-05 14:01:39 -04:00
cbfc796685 Merge remote-tracking branch 'origin/feature/cierres' into feature/cierres 2025-05-05 11:35:29 -04:00
da56192f97 Formateo de numeros en JS 2025-04-30 23:36:32 -04:00
b5d08620f9 Unidades que no son departamentos 2025-04-30 17:13:40 -04:00
c92b07ee6f Excepcion correcta 2025-04-30 17:13:26 -04:00
ee6956d417 Reorden 2025-04-30 16:18:20 -04:00
21d5e2d03b Api en archivo separado 2025-04-30 16:18:00 -04:00
73a742c01e Nada en public 2025-04-30 10:51:47 -04:00
dd42c12d49 Orden 2025-04-30 10:38:20 -04:00
41ea5f5c15 Update prueba 2025-04-30 10:38:05 -04:00
eeb6f5bcd1 Se agrega condicion 2025-04-30 10:37:57 -04:00
2680f51167 Correccion migracion 2025-04-30 10:37:41 -04:00
019d57a0b0 Nuevas pruebas 2025-04-30 01:12:23 -04:00
1a400d9a5c Watcher solo para unit tests 2025-04-30 01:12:09 -04:00
6276f87274 Pruebas nuevas 2025-04-30 00:14:38 -04:00
28c93a42bc Logs de pruebas 2025-04-30 00:14:24 -04:00
4ff5d28522 Nuevas pruebas 2025-04-29 23:57:59 -04:00
a93642c55d Actualizacion de pruebas con extensiones 2025-04-29 23:57:49 -04:00
87c0d8c8d9 Se mueve todo a extension de pruebas 2025-04-29 23:55:51 -04:00
dd1741a930 Broker test 2025-04-29 23:21:19 -04:00
ad0fd82a9e Assert nuevo 2025-04-29 23:21:13 -04:00
bae5c1740d No mas require 2025-04-29 23:19:05 -04:00
f5f1482b7a Autoload para pruebas 2025-04-29 23:18:55 -04:00
4bd5fe16df Comandos para correr pruebas y consola 2025-04-29 23:18:18 -04:00
61845fbd05 Ignorar datos de pruebas 2025-04-29 22:26:26 -04:00
f8ac0f14f0 Abstracts 2025-04-29 22:25:32 -04:00
acb7a1336d Coverage lento e innecesario 2025-04-29 22:25:11 -04:00
8af56137a8 Seeds al migrar 2025-04-29 21:51:19 -04:00
c3247838b3 Namespace test Servicio Valor 2025-04-29 21:43:21 -04:00
dd82ac6bb7 Tests Home 2025-04-29 21:42:57 -04:00
2acf0362fa Ambiente de testeo 2025-04-29 21:41:49 -04:00
e6892ee085 Valor de PU cuando unidad no tiene valor 2025-04-29 13:01:57 -04:00
86b8d6b3c7 Limpieza 2025-04-29 13:01:21 -04:00
53115b085f Asegurarse que el valor entregado a Pago es en pesos. 2025-04-29 11:29:23 -04:00
c3b7427f60 Cambio en nombre de metodo y uso de valor maximo para UF 2025-04-29 11:20:49 -04:00
5d939f970b Valor con pruebas 2025-04-28 20:20:43 -04:00
4845801b27 Uso de script central de rut 2025-04-28 19:00:40 -04:00
d5bf9a7660 Digito verificador 2025-04-28 18:59:37 -04:00
795dda868b Ya no se incluye UF/m² y se transforman en numeros las UF 2025-04-25 20:03:11 -04:00
53a3633dc7 Menu -> Agregar Venta separado 2025-04-25 20:02:24 -04:00
0143fd11ac Se pasan datos a EmptyResult en base- 2025-04-25 19:41:42 -04:00
55745a8d0a EmptyResult ahora puede llevar los datos. 2025-04-25 19:41:23 -04:00
2a1930c5f7 FIX: Propiedad con unidad_principal 2025-04-25 19:25:16 -04:00
31f49dddb6 FIX: unidad_principal no tiene valor por defecto. 2025-04-25 17:36:12 -04:00
b4ca59fb6d Optimizacion de obtencion de datos. 2025-04-24 19:23:39 -04:00
d910f3eb69 FIX: Propiedad sin unidad_principal 2025-04-24 18:54:54 -04:00
555cdb7138 Promociones en misma tabla para tipo 2025-04-24 18:50:04 -04:00
65088da2f5 Promociones en misma tabla para tipo 2025-04-23 16:49:52 -04:00
966b341b65 Listado de promociones 2025-04-22 18:34:23 -04:00
90b05ca25c Se elimina la comision del excel 2025-04-22 16:28:13 -04:00
bb3a2fffa1 Cuando no existen promociones 2025-04-22 15:38:30 -04:00
8a5e41a722 Normalizacion con profundidad 2025-04-22 15:31:55 -04:00
5736a346e7 Valor debiese ser el último precio. 2025-04-22 15:24:11 -04:00
4f4e69f0c3 FIX: no tiene precio ahora, solo valor 2025-04-22 15:19:25 -04:00
00deebeaa8 FIX: faltaba valor 2025-04-22 15:19:08 -04:00
aee0754b5a Simplificacion de retorno de ventas por unidades 2025-04-22 15:18:59 -04:00
eabdab23c3 Simplificacion de retorno de ventas por unidades 2025-04-22 13:08:15 -04:00
5147450ed6 Manejo de excepciones 2025-04-22 13:07:52 -04:00
ed96f25475 Mayor orden 2025-04-22 11:49:34 -04:00
d5a3512852 Barras de progreso 2025-04-22 11:35:56 -04:00
d6730cd020 Cambio en link 2025-04-22 09:29:14 -04:00
c7dddc818c Definicion de variables una sola vez 2025-04-22 09:28:45 -04:00
33b4182bd3 Optimizacion de queries a cargar de una sola vez 2025-04-22 09:28:12 -04:00
fc776e6cec Ruta para Ventas por unidades 2025-04-21 19:43:20 -04:00
5d79ea83c3 Mostrar valor de venta para unidades vendidas 2025-04-21 19:43:01 -04:00
c34048a53a Ventas por unidades 2025-04-21 19:41:20 -04:00
f7af93b815 Throw Read 2025-04-21 19:40:26 -04:00
993e4ff3b8 Merge branch 'develop' into feature/cierres 2025-04-11 13:35:13 -04:00
bc49ba7629 FIX: Busqueda no funcionaba 2025-04-09 09:29:53 -04:00
3c2b486083 Se agregan columnas y el calculo de promociones de tipo fijo 2025-04-08 19:04:46 -04:00
76f69f3bda Optimizacion simple 2025-04-08 18:38:18 -04:00
8ba3c456b6 Link a contrato en vez del proyecto 2025-04-08 18:35:07 -04:00
98b18fab3e Cambios solicitados 2025-04-08 18:30:14 -04:00
12a4831887 Merge branch 'develop' into feature/cierres 2025-04-04 13:23:00 -03:00
da46914de4 Promociones en Contrato 2025-04-04 12:56:49 -03:00
596bc71cf8 Mejoras UI 2025-04-04 12:54:51 -03:00
7f8e4ea943 FIX: query fallaba 2025-04-04 12:36:03 -03:00
5456485f71 FIX: ya no existe relacion con contratos 2025-04-04 12:08:46 -03:00
836503a71b Menus nuevos 2025-04-04 12:08:24 -03:00
4df0cca675 Filtro en excel 2025-04-04 11:53:25 -03:00
00a0adb4ac Espacio mas ajustado 2025-04-04 11:53:11 -03:00
037fcd60f3 Orden de queries 2025-04-04 11:52:50 -03:00
7a97fc9dfe Precios con promociones para listado brokers 2025-04-03 17:22:38 -03:00
7b2df74e4d Promociones para cada subdivicion 2025-04-03 17:22:11 -03:00
b5d6d0acb9 Mostrar porcentajes en venta 2025-04-03 13:56:11 -03:00
8a1e6a7761 Conecciones de Promociones 2025-04-03 13:15:56 -03:00
ced673e452 Correcto nombre de tabla 2025-04-03 13:12:57 -03:00
8a7a1d4e64 Merge branch 'develop' into feature/cierres 2025-03-27 11:44:54 -03:00
9be20ab1cd UF 0 o nula actualizadas para Pago y Pie 2025-03-26 16:54:53 -03:00
1c40f18624 Pagos sin uf retornan 0 2025-03-26 16:49:27 -03:00
db36549699 Agregar Pie 2025-03-26 16:41:54 -03:00
4ce83fb270 Merge branch 'develop' into feature/cierres 2025-03-26 15:42:47 -03:00
b191a01313 Promociones 2025-03-25 19:22:38 -03:00
d3b0026ca4 Agregar, editar y eliminar promociones 2025-03-18 19:13:47 -03:00
2b3f476df7 Agregar, editar y eliminar promociones 2025-03-18 19:12:59 -03:00
39c148b7b3 Cambio nombre archivo 2025-03-17 23:03:06 -03:00
bae0f1f555 Separacion de Promocion de Contrato y Precio
"Simplificacion" de datos en listado de precios
2025-03-17 22:49:48 -03:00
2e49e2c947 Listados separados por hojas (tabs) 2025-03-13 13:16:20 -03:00
68aebdb4fe Listado de Precios para Contrato Broker 2025-03-13 12:18:08 -03:00
346001db8e SearchBuilder configuration centralizada
FIX: CentroCosto TipoCuenta
2025-03-13 09:33:42 -03:00
8b04eb262f FIX: Editar datos Broker 2025-03-12 18:31:21 -03:00
7c7c8315e2 Editar Brokers y sus contratos 2025-03-11 17:41:11 -03:00
510e05e5ca FIX: rut con otros caracteres y maximo largo 2025-03-07 17:26:36 -03:00
5055d2703c Broker Contact 2025-03-07 17:11:59 -03:00
2bc30ab9e8 Formatear porcentajes menores a 1 2025-03-07 17:11:15 -03:00
c7ee440e03 Listado de brokers 2025-03-06 20:34:43 -03:00
18dd8c4ec0 Merge branch 'develop' into feature/cierres 2025-03-06 16:23:58 -03:00
8ea4995f6b Contratos desde proyectos 2025-03-03 21:46:53 -03:00
aeeca65d94 Correcciones 2025-03-03 21:41:43 -03:00
5f69069aa0 Rutas Reservations 2025-03-03 16:53:36 -03:00
095a65a643 Cleanup por recomendaciones 2025-03-03 16:37:40 -03:00
928d2e57be Merge branch 'develop' into feature/cierres 2025-03-03 15:32:25 -03:00
2a0335f834 Reservation Controller 2025-03-03 15:21:18 -03:00
9ccf53fa4e Reservation Service 2025-03-03 15:21:12 -03:00
ef54c36edc Cleanup 2025-03-03 14:56:18 -03:00
4aa88d5164 Rutas API Contratos 2025-03-03 11:26:45 -03:00
8ea13c3efd API Contratos 2025-03-03 10:47:48 -03:00
12e3d7ed3b Servicio Contratos 2025-03-01 13:26:55 -03:00
a7fc89ac29 Merge branch 'develop' into feature/cierres 2025-02-24 21:36:35 -03:00
a71df4e70d Controlador y ruta de operadores para API 2025-02-24 12:41:50 -03:00
f17b7a758a withJson con error 2025-02-24 12:41:34 -03:00
7fb28cd44c Servicio operadores 2025-02-24 12:41:13 -03:00
a44bd610ad Excepciones de servicios 2025-02-24 12:41:00 -03:00
28bba8a438 Actualizacion de Modelos 2025-02-24 12:40:40 -03:00
0ec6ebdafe Actualizacion de Repos 2025-02-24 12:39:42 -03:00
3ebe256a66 Actualizacion de migraciones 2025-02-24 12:39:25 -03:00
9d135e2c26 Base de Datos 2025-02-18 16:02:10 -03:00
31 changed files with 2237 additions and 88 deletions

View File

@ -2,7 +2,9 @@
namespace Incoviba\Common\Implement\Repository;
use Closure;
use Exception;
use Incoviba\Common\Define;
use Incoviba\Common\Implement\Exception\EmptyResult;
class Factory implements Define\Repository\Factory
{
@ -20,8 +22,16 @@ class Factory implements Define\Repository\Factory
return $this;
}
/**
* @return mixed
* @throws EmptyResult
*/
public function run(): mixed
{
return call_user_func_array($this->callable, $this->args);
try {
return call_user_func_array($this->callable, $this->args);
} catch (Exception $exception) {
throw new EmptyResult($exception->getMessage(), $exception);
}
}
}

View File

@ -4,7 +4,7 @@ declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateReservation extends AbstractMigration
final class CreateReservations extends AbstractMigration
{
/**
* Change Method.
@ -23,9 +23,11 @@ final class CreateReservation extends AbstractMigration
$this->execute("ALTER DATABASE CHARACTER SET 'utf8mb4';");
$this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");
$this->table('reservation')
$this->table('reservations')
->addColumn('project_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('buyer_rut', 'integer', ['signed' => false, 'null' => false])
->addColumn('date', 'date', ['null' => false])
->addForeignKey('project_id', 'proyecto', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->addForeignKey('buyer_rut', 'personas', 'rut', ['delete' => 'cascade', 'update' => 'cascade'])
->create();

View File

@ -4,7 +4,7 @@ declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateReservationDatas extends AbstractMigration
final class CreateReservationDetails extends AbstractMigration
{
/**
* Change Method.
@ -23,11 +23,13 @@ final class CreateReservationDatas extends AbstractMigration
$this->execute("ALTER DATABASE CHARACTER SET 'utf8mb4';");
$this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");
$this->table('reservation_data')
$this->table('reservation_details')
->addColumn('reservation_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('type', 'integer', ['length' => 1, 'signed' => false, 'null' => false])
->addColumn('reference_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('value', 'decimal', ['precision' => 10, 'scale' => 2, 'signed' => false, 'default' => 0.00, 'null' => true])
->addColumn('value', 'decimal', ['precision' => 10, 'scale' => 2, 'signed' => false, 'default' => null, 'null' => true])
->addForeignKey('reservation_id', 'reservations', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->addIndex(['reservation_id', 'type', 'reference_id'], ['unique' => true, 'name' => 'idx_reservation_details'])
->create();
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');

View File

@ -27,7 +27,7 @@ final class CreateReservationStates extends AbstractMigration
->addColumn('reservation_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('date', 'date', ['null' => false])
->addColumn('type', 'integer', ['length' => 3, 'null' => false, 'default' => 0])
->addForeignKey('reservation_id', 'reservation', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->addForeignKey('reservation_id', 'reservations', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->create();
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');

View File

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class AddCommentsToEstadoCierre 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('estado_cierre_comentarios')
->addColumn('estado_cierre_id', 'integer', ['signed' => false])
->addColumn('fecha', 'datetime', ['default' => 'CURRENT_TIMESTAMP'])
->addColumn('comments', 'text')
->addForeignKey('estado_cierre_id', 'estado_cierre', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->create();
}
}

View File

@ -0,0 +1,7 @@
<?php
use Incoviba\Controller\API\Personas;
//$app->group('/personas', function($app) {});
$app->group('/persona/{rut}', function($app) {
$app->get('[/]', [Personas::class, 'get']);
});

View File

@ -30,4 +30,5 @@ $app->group('/proyecto/{proyecto_id}', function($app) {
$app->post('/edit[/]', [Proyectos::class, 'terreno']);
});
$app->get('/brokers', [Proyectos::class, 'brokers']);
$app->get('/promotions', [Proyectos::class, 'promotions']);
});

View File

@ -3,6 +3,11 @@ use Incoviba\Controller\API\Ventas\Reservations;
$app->group('/reservations', function($app) {
$app->post('/add[/]', [Reservations::class, 'add']);
$app->group('/project/{project_id}', function($app) {
$app->get('/active[/]', [Reservations::class, 'active']);
$app->get('/pending[/]', [Reservations::class, 'pending']);
$app->get('/rejected[/]', [Reservations::class, 'rejected']);
});
$app->get('[/]', Reservations::class);
});
$app->group('/reservation/{reservation_id}', function($app) {

View File

@ -1,5 +1,6 @@
<?php
use Incoviba\Controller\Ventas\Cierres;
//use Incoviba\Controller\Ventas\Cierres;
use Incoviba\Controller\Ventas\Reservations as Cierres;
$app->group('/cierres', function($app) {
$app->get('[/]', Cierres::class);

View File

@ -0,0 +1,554 @@
@extends('layout.base')
@section('page_title')
Cierres -Reservas
@endsection
@section('page_content')
<div class="ui container">
<h2 class="ui header">Cierres - Reservas</h2>
<div class="ui compact segment" id="projects">
<div class="ui header">Proyectos</div>
@if (count($projects) == 0)
<div class="ui message">
No hay proyectos en venta.
</div>
@else
<div class="ui link list">
@foreach ($projects as $project)
<div class="item link" data-id="{{ $project->id }}">
{{ $project->descripcion }}
</div>
@endforeach
</div>
@endif
</div>
<div class="ui two column grid">
<div class="column">
<h3 class="ui header" id="project"></h3>
</div>
<div class="column">
<div class="ui active inline loader" id="loader"></div>
</div>
</div>
<div id="results">
<div class="ui right aligned top attached basic segment" id="controls">
<div class="ui tiny icon buttons">
<button class="ui button" id="up_button">
<i class="up arrow icon"></i>
</button>
<button class="ui button" id="refresh_button">
<i class="refresh icon"></i>
</button>
<button class="ui green icon button" id="add_button">
<i class="plus icon"></i>
</button>
</div>
</div>
<div class="ui top attached tabular menu" id="tabs">
<div class="yellow active item" data-tab="pending">Pendientes</div>
<div class="green item" data-tab="active">Activas</div>
<div class="red item" data-tab="rejected">Rechazadas</div>
</div>
<div class="ui bottom attached tab fitted segment active" data-tab="pending">
<table class="ui yellow striped table" id="pending_reservations">
<thead>
<tr>
<th>Unidades</th>
<th>Cliente</th>
<th>Fecha</th>
<th>Oferta</th>
<th>¿Valida?</th>
<th>Operador</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="ui bottom attached tab fitted segment" data-tab="active">
<table class="ui green striped table" id="active_reservations">
<thead>
<tr>
<th>Unidades</th>
<th>Cliente</th>
<th>Fecha</th>
<th>Oferta</th>
<th>Operador</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="ui bottom attached tab fitted segment" data-tab="rejected">
<table class="ui red striped table" id="rejected_reservations">
<thead>
<tr>
<th>Unidades</th>
<th>Cliente</th>
<th>Fecha</th>
<th>Oferta</th>
<th>Estado</th>
<th>Operador</th>
<th>Comentarios</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
@include('ventas.reservations.add_modal')
@endsection
@push('page_styles')
<style>
.item.link {
cursor: pointer;
text-decoration: underline;
}
</style>
@endpush
@push('page_scripts')
<script>
class Projects {
display = {
projects: '',
project: ''
}
component_id = ''
component = null
current_project = null;
title_id = ''
title_component = null
constructor({component_id, title_id}) {
this.component_id = component_id
this.component = document.getElementById(this.component_id)
this.display.projects = this.component.style.display
this.title_id = title_id
this.title_component = document.getElementById(this.title_id)
this.display.project = this.title_component.style.display
this.show()
this.watch()
}
select(event) {
event.preventDefault()
const project_id = event.currentTarget.dataset.id
reservations.show.results()
if (project_id === this.current_project) {
this.hide()
this.title_component.innerHTML = event.currentTarget.innerHTML
reservations.action.reservations()
return
}
this.current_project = project_id
reservations.get.reservations(project_id)
reservations.components.modals.add.load(project_id)
this.hide()
this.title_component.innerHTML = event.currentTarget.innerHTML
}
watch() {
this.component.querySelectorAll('.item.link').forEach(item => {
item.addEventListener('click', this.select.bind(this))
})
}
show() {
this.component.style.display = this.display.projects
this.title_component.style.display = 'none'
}
hide() {
this.component.style.display = 'none'
this.title_component.style.display = this.display.project
}
}
class Controls {
display = {
up: '',
reset: '',
}
component_id = ''
component = null
buttons = {
up: null,
reset: null,
add: null
}
constructor({component_id}) {
this.component_id = component_id
this.component = document.getElementById(this.component_id)
const buttons = this.component.querySelectorAll('button')
this.buttons.up = buttons[0]
this.buttons.reset = buttons[1]
this.buttons.add = buttons[2]
this.display.up = buttons[0].style.display
this.display.reset = buttons[1].style.display
this.watch()
this.hide()
}
watch() {
Object.entries(this.buttons).forEach(([key, value]) => {
const name = key.replace('_button', '')
value.addEventListener('click', this.action[name].bind(this))
})
}
hide() {
this.buttons.up.style.display = this.display.up
this.buttons.reset.style.display = this.display.reset
}
show() {
this.buttons.up.style.display = 'none'
this.buttons.reset.style.display = 'none'
}
action = {
reset: event => {
event.preventDefault()
reservations.action.reset(event)
return false
},
up: event => {
event.preventDefault()
reservations.action.up(event)
return false
},
add: event => {
event.preventDefault()
reservations.action.add(event)
return false
}
}
}
class Reservations {
display = {
reservations: '',
}
component_id = ''
component = null
formatters = {
date: null,
ufs: null
}
columnNames = []
reservations = []
constructor({component_id, formatters = {date, ufs}}) {
this.component_id = component_id
this.component = document.getElementById(this.component_id)
this.display.reservations = this.component.style.display
this.formatters = formatters
this.set().columnNames()
this.hide()
}
set() {
return {
reservations: reservations => {
this.reservations = reservations
return this
},
columnNames: () => {
const tds = this.component.querySelector('thead tr').querySelectorAll('th')
this.columnNames = []
tds.forEach(td => {
let name = td.innerHTML.toLowerCase()
if (name === '') {
return
}
if (name.includes('?')) {
name = name.replaceAll(/[¿?]/g, '')
}
this.columnNames.push(name)
})
return this
}
}
}
columnsData() {
return this.reservations.map(reservation => {
const date = new Date(Date.parse(reservation.fecha) + 24 * 60 * 60 * 1000)
return {
id: reservation.id,
unidades: reservation.summary,
cliente: reservation.buyer.nombreCompleto,
fecha: this.formatters.date.format(date),
oferta: `${this.formatters.ufs.format(reservation.offer)} UF`,
valida: reservation.valid ? '<span class="ui green text">Si</span>' : '<span class="ui red text">No</span>',
operador: reservation.broker?.name ?? '',
}
})
}
draw() {
const tbody = this.component.querySelector('tbody')
tbody.innerHTML = ''
this.columnsData().forEach(column => {
const tr = document.createElement('tr')
const contents = []
const id = column.id
this.columnNames.forEach(name => {
contents.push(`<td>${column[name]}</td>`)
})
const actions = this.drawActions(id)
if (actions !== '') {
contents.push(actions)
}
tr.innerHTML = contents.join("\n")
tbody.appendChild(tr)
})
this.show()
}
drawActions(id) {
return `
<td class="right aligned">
<button class="ui green mini icon button approve" data-id="${id}" title="Aprobar">
<i class="check icon"></i>
</button>
<button class="ui red mini icon button reject" data-id="${id}" title="Rechazar">
<i class="trash icon"></i>
</button>
</td>`
}
empty() {
const tbody = this.component.querySelector('tbody')
tbody.innerHTML = ''
const col_span = this.columnNames.length + 1
const tr = document.createElement('tr')
tr.innerHTML = `<td colspan="${col_span}">No hay cierres</td>`
tbody.appendChild(tr)
this.show()
}
show() {
this.component.style.display = this.display.reservations
}
hide() {
this.component.style.display = 'none'
}
}
class ActiveReservations extends Reservations {
constructor({component_id, formatters = {date, ufs}}) {
super({component_id, formatters})
}
columnsData() {
const data = super.columnsData();
return data.map(row => {
delete(row['valida'])
return row
})
}
drawActions(id) {
return `
<td class="right aligned">
<button class="ui green mini icon button edit" data-id="${id}" title="Promesar">
<i class="right chevron icon"></i>
</button>
<button class="ui red mini icon button remove" data-id="${id}" title="Abandonar">
<i class="trash icon"></i>
</button>
</td>`
}
}
class PendingReservations extends Reservations {
constructor({component_id, formatters = {date, ufs}}) {
super({component_id, formatters})
}
}
class RejectedReservations extends Reservations {
constructor({component_id, formatters = {date, ufs}}) {
super({component_id, formatters})
}
columnsData() {
const data = super.columnsData()
return this.reservations.map((reservation, idx) => {
data[idx]['estado'] = reservation.state.charAt(0).toUpperCase() + reservation.state.slice(1)
data[idx]['comentarios'] = reservation.comments?.join('<br />\n') ?? ''
return data[idx]
})
}
drawActions(id) {
return ''
}
}
const reservations = {
components: {
projects: null,
loader: null,
results: null,
controls: null,
reservations: {
active: null,
pending: null,
rejected: null
},
modals: {
add: null
}
},
display: {
loader: '',
results: '',
},
get: {
send: (project_id, url_segment, component) => {
const url = `/api/ventas/reservations/project/${project_id}/${url_segment}`
return APIClient.fetch(url).then(response => response.json()).then(json => {
if (json.reservations.length === 0) {
component.empty()
return
}
component.set().reservations(json.reservations).draw()
})
},
active: project_id => {
return reservations.get.send(project_id, 'active', reservations.components.reservations.active)
/*const url = `/ventas/reservations/project/${project_id}/active`
return APIClient.fetch(url).then(json => {
if (json.reservations.length === 0) {
return
}
this.components.reservations.active.set().reservations(json.reservations).draw()
})*/
},
pending: project_id => {
return reservations.get.send(project_id, 'pending', reservations.components.reservations.pending)
/*const url = `/ventas/reservations/project/${project_id}/pending`
return APIClient.fetch(url).then(json => {
if (json.reservations.length === 0) {
return
}
this.components.reservations.pending.set().reservations(json.reservations).draw()
})*/
},
rejected: project_id => {
return reservations.get.send(project_id, 'rejected', reservations.components.reservations.rejected)
/*const url = `/ventas/reservations/project/${project_id}/rejected`
return APIClient.fetch(url).then(json => {
if (json.reservations.length === 0) {
return
}
this.components.reservations.rejected.set().reservations(json.reservations).draw()
})*/
},
reservations: project_id => {
reservations.loading.show()
const promises = []
promises.push(reservations.get.active(project_id))
promises.push(reservations.get.pending(project_id))
promises.push(reservations.get.rejected(project_id))
return Promise.any(promises).then(() => {
reservations.loading.hide()
})
}
},
loading: {
show: () => {
reservations.components.loader.style.display = reservations.display.loader
},
hide: () => {
reservations.components.loader.style.display = 'none'
}
},
action: {
reset: event => {
event.preventDefault()
reservations.components.projects.current_project = null
Object.entries(reservations.components.reservations).forEach(([key, value]) => {
reservations.components.reservations[key].reservations = []
reservations.components.reservations[key].hide()
})
reservations.show.projects()
return false
},
up: event => {
event.preventDefault()
Object.values(reservations.components.reservations).forEach(reservations => reservations.hide())
reservations.show.projects()
return false
},
add: event => {
event.preventDefault()
reservations.components.modals.add.show()
return false
},
reservations: () => {
Object.values(reservations.components.reservations).forEach(reservations => {
reservations.draw()
})
}
},
show: {
projects: () => {
reservations.components.projects.show()
reservations.components.results.style.display = 'none'
},
results: () => {
reservations.components.projects.hide()
reservations.components.results.style.display = reservations.display.results
}
},
setup(configuration) {
const formatters = {
date: new Intl.DateTimeFormat('es-CL', {year: 'numeric', month: 'long', day: 'numeric'}),
ufs: new Intl.NumberFormat('es-CL', {minimumFractionDigits: 2, maximumFractionDigits: 2})
}
this.components.loader = document.getElementById(configuration.ids.loader)
this.components.projects = new Projects({component_id: configuration.ids.projects, title_id: configuration.ids.project})
this.components.controls = new Controls({component_id: configuration.ids.controls})
this.components.reservations.active = new ActiveReservations({component_id: configuration.ids.active, formatters})
this.components.reservations.pending = new PendingReservations({component_id: configuration.ids.pending, formatters})
this.components.reservations.rejected = new RejectedReservations({component_id: configuration.ids.rejected, formatters})
this.display.loader = this.components.loader.style.display
this.loading.hide()
$(`#${configuration.ids.tabs} .item`).tab()
this.components.results = document.getElementById(configuration.ids.results)
this.display.results = this.components.results.style.display
this.show.projects()
this.components.modals.add = new AddReservationModal()
}
}
$(document).ready(() => {
reservations.setup({
ids: {
projects: 'projects',
project: 'project',
results: 'results',
loader: 'loader',
controls: 'controls',
tabs: 'tabs',
active: 'active_reservations',
pending: 'pending_reservations',
rejected: 'rejected_reservations',
}
})
})
</script>
@endpush

View File

@ -0,0 +1,733 @@
<div class="ui modal" id="add_reservation_modal">
<div class="header">
Agregar Cierre
</div>
<div class="content">
<form class="ui form" id="add_reservation_form">
<input type="hidden" name="project_id" />
<div class="three wide required field">
<label>Fecha</label>
<div class="ui calendar" id="add_date">
<div class="ui icon input">
<i class="calendar icon"></i>
<input type="text" name="date" />
</div>
</div>
</div>
<div class="fields">
<div class="three wide required field">
<label>RUT</label>
<div class="ui right labeled input" id="add_rut">
<input type="text" name="rut" placeholder="RUT" />
<div class="ui basic label">-<span id="add_digit"></span></div>
</div>
</div>
<div class="field">
<label></label>
<div class="ui inline loader" id="add_rut_loader"></div>
</div>
</div>
<div class="fields">
<div class="three wide required field">
<label>Nombre</label>
<input type="text" name="name" placeholder="Nombre" />
</div>
<div class="six wide required field">
<label>Apellidos</label>
<input type="text" name="last_name" placeholder="Apellido Paterno" />
</div>
<div class="six wide field">
<label></label>
<input type="text" name="last_name2" placeholder="Apellido Materno" />
</div>
</div>
<div class="fields">
<div class="three wide field">
<label>Dirección</label>
<input type="text" name="calle" placeholder="Calle" />
</div>
<div class="field">
<label></label>
<input type="text" name="numero" placeholder="" />
</div>
<div class="three wide field">
<label></label>
<input type="text" name="extra" placeholder="Otros Detalles" />
</div>
</div>
<div class="fields">
<div class="three wide field">
<label>Comuna</label>
<div class="ui search selection dropdown" id="add_comuna">
<input type="hidden" name="comuna" />
<i class="dropdown icon"></i>
<div class="default text">Comuna</div>
<div class="menu"></div>
</div>
</div>
<div class="seven wide field">
<label>Región</label>
<div class="ui search selection dropdown" id="add_region">
<input type="hidden" name="region" />
<i class="dropdown icon"></i>
<div class="default text">Región</div>
<div class="menu">
@foreach($regions as $region)
<div class="item" data-value="{{$region->id}}">{{$region->numeral}} - {{$region->descripcion}}</div>
@endforeach
</div>
</div>
</div>
</div>
<div class="fields">
<div class="field">
<label>Telefono</label>
<input type="text" name="phone" placeholder="Telefono" />
</div>
<div class="field">
<label>Correo</label>
<div class="ui labeled input">
<input type="text" name="email_name" placeholder="Correo" />
<div class="ui basic label">@</div>
<input type="text" name="email_domain" placeholder="Dominio" />
</div>
</div>
</div>
<div class="fields">
<div class="field">
<label>Estado Civil</label>
<input type="text" name="civil_status" placeholder="Estado Civil" />
</div>
<div class="field">
<label>Profesión</label>
<input type="text" name="profession" placeholder="Profesión" />
</div>
<div class="field">
<label>Fecha de Nacimiento</label>
<div class="ui calendar" id="add_birthdate">
<div class="ui icon input">
<i class="calendar icon"></i>
<input type="text" name="birthdate" />
</div>
</div>
</div>
</div>
<div class="six wide field">
<label>Operador *</label>
<div class="ui clearable search selection dropdown" id="add_broker">
<input type="hidden" name="broker" />
<i class="dropdown icon"></i>
<div class="default text">Operador</div>
<div class="menu"></div>
</div>
</div>
<div class="field">
<label>Agregar Promoción</label>
<button type="button" class="ui icon button" id="add_promotion">
<i class="plus icon"></i>
</button>
</div>
<div id="add_promotions"></div>
<h4 class="ui dividing header">Unidades</h4>
<div class="fields" id="add_unit_buttons"></div>
<div id="add_units"></div>
</form>
</div>
<div class="actions">
<div class="ui cancel button">
Cancelar
</div>
<div class="ui green ok button">
Agregar
</div>
</div>
</div>
@include('layout.body.scripts.rut')
@push('page_scripts')
<script>
class AddModalPromotions {
ids = {
button: '',
elements: ''
}
data = {
promotions: []
}
components = {
button: null,
promotions: null,
}
display = {
button: ''
}
constructor() {
this.ids = {
button: 'add_promotion',
elements: 'add_promotions'
}
this.setup()
}
add() {
const idx = Math.max(this.data.promotions.length, 0, Math.max(...this.data.promotions) + 1)
this.data.promotions.push(idx)
this.draw.promotions()
}
reset() {
this.data.promotions = []
this.draw.promotions()
}
remove(idx) {
this.data.promotions = this.data.promotions.filter(promotion => promotion !== idx)
this.draw.promotions()
}
draw = {
promotion: idx => {
const promotions = this.data.promotions.map(promotion => {
return `<div class="item" data-value="${promotion.id}">${promotion.name}</div>`
})
return [
`<div class="fields promotion" data-id="${idx}">`,
'<div class="three wide field">',
'<label>Promoción</label>',
`<div class="ui search selection dropdown">`,
'<input type="hidden" name="promotions[]" />',
'<i class="dropdown icon"></i>',
'<div class="default text">Promoción</div>',
`<div class="menu">${promotions.join('')}</div>`,
'</div>',
'</div>',
'<div class="two wide field">',
'<label></label>',
`<button class="ui red tiny icon button remove_promotion" type="button" data-id="${idx}"><i class="trash icon"></i></button>`,
'</div>',
'</div>'
].join('')
},
promotions: () => {
if (this.data.promotions.length === 0) {
this.components.button.parentElement.style.display = 'none'
this.components.promotions.innerHTML = ''
return
}
this.components.button.parentElement.style.display = this.display.button
this.components.promotions.innerHTML = this.data.promotions.map((promotion, idx) => {
return this.draw.promotion(idx)
}).join('')
this.components.promotions.querySelectorAll('.dropdown').forEach(dropdown => {
$(dropdown).dropdown()
})
this.components.promotions.querySelectorAll('.remove_promotion').forEach(button => {
button.addEventListener('click', () => {
const idx = Number(button.dataset.id)
this.remove(idx)
})
})
}
}
setup() {
this.components.button = document.getElementById(this.ids.button)
this.components.promotions = document.getElementById(this.ids.elements)
this.components.button.addEventListener('click', () => {
this.add()
})
this.display.button = this.components.button.parentElement.style.display
this.draw.promotions()
}
}
class AddModalUnits {
ids = {
buttons_holder: '',
units: ''
}
data = {
button_map: {},
types: {},
units: [],
}
components = {
buttons_holder: null,
units: null,
}
constructor() {
this.ids = {
buttons_holder: 'add_unit_buttons',
units: 'add_units'
}
this.data.button_map = {
'departamento': 'building',
'estacionamiento': 'car',
'bodega': 'warehouse',
'terraza': 'vector square'
}
this.setup()
}
draw = {
button: type => {
return [
'<div class="field">',
`<button class="ui icon button" type="button" data-type="${type}" title="${type.charAt(0).toUpperCase() + type.slice(1)}">`,
'<i class="plus icon"></i>',
`<i class="${this.data.button_map[type]} icon"></i>`,
'</button>',
'</div>'
].join('')
},
buttons: () => {
this.components.buttons_holder.innerHTML = Object.keys(this.data.types).map(type => {
return this.draw.button(type)
}).join('')
this.components.buttons_holder.querySelectorAll('.button').forEach(button => {
button.addEventListener('click', () => {
const type = button.dataset.type
this.add(type)
})
})
},
units: () => {
if (this.data.units.length === 0) {
this.components.units.innerHTML = ''
return
}
this.components.units.innerHTML = this.data.units.map(unit => {
return [
'<div class="fields">',
'<div class="four wide field">',
`<label>${unit.type.charAt(0).toUpperCase() + unit.type.slice(1)}</label>`,
`<div class="ui search selection dropdown">`,
'<input type="hidden" name="units[]" />',
'<i class="dropdown icon"></i>',
`<div class="default text">${unit.type.charAt(0).toUpperCase() + unit.type.slice(1)}</div>`,
'<div class="menu">',
this.data.types[unit.type].map(unit => {
return `<div class="item" data-value="${unit.value}">${unit.name}</div>`
}).join(''),
'</div>',
'</div>',
'</div>',
'<div class="field">',
'<label></label>',
`<button class="ui red tiny icon button remove_unit" type="button" data-id="${unit.idx}"><i class="trash icon"></i></button>`,
'</div>',
'</div>',
].join('')
}).join('')
this.components.units.querySelectorAll('.dropdown').forEach(dropdown => {
$(dropdown).dropdown()
})
this.components.units.querySelectorAll('.remove_unit').forEach(button => {
button.addEventListener('click', () => {
const idx = Number(button.dataset.id)
this.remove(idx)
})
})
}
}
reset() {
this.data.units = []
this.draw.units()
}
add(type) {
const idx = Math.max(this.data.units.length, 0, Math.max(...this.data.units.map(unit => unit.idx)) + 1)
this.data.units.push({idx, type})
this.draw.units()
}
remove(idx) {
this.data.units = this.data.units.filter(unit => unit.idx !== idx)
this.draw.units()
}
setup() {
this.components.buttons_holder = document.getElementById(this.ids.buttons_holder)
this.components.units = document.getElementById(this.ids.units)
this.draw.buttons()
}
}
class AddReservationModal {
ids = {
modal: '',
form: '',
date: '',
rut: '',
digit: '',
birthdate: '',
comuna: '',
region: '',
broker: '',
promotion_button: '',
promotions: '',
unit_buttons: '',
units: ''
}
components = {
$modal: null,
form: null,
$date: null,
$rut: null,
rut: null,
digit: null,
$birthdate: null,
$comuna: null,
$region: null,
$broker: null,
promotion_button: null,
promotions: null,
unit_buttons: null,
units: null,
$loader: null
}
data = {
current_project: null,
comunas: {},
brokers: {},
promotions: {},
unit_buttons: [],
units: {},
added_units: {},
current_user: null
}
maps = {
unit_types: {
departamento: 'building',
estacionamiento: 'car',
bodega: 'warehouse',
terraza: 'tree',
}
}
constructor() {
this.ids = {
modal: 'add_reservation_modal',
form: 'add_reservation_form',
date: 'add_date',
rut: 'add_rut',
digit: 'add_digit',
birthdate: 'add_birthdate',
comuna: 'add_comuna',
region: 'add_region',
broker: 'add_broker',
promotion_button: 'add_promotion',
promotions: 'add_promotions',
unit_buttons: 'add_unit_buttons',
units: 'add_units',
loader: 'add_rut_loader'
}
this.setup()
}
load(project_id) {
this.reset()
this.data.current_project = project_id
this.components.form.querySelector('input[name="project_id"]').value = project_id
this.get.brokers(project_id)
this.get.promotions(project_id).then(promotions => {
this.components.promotions.data.promotions = promotions
this.components.promotions.draw.promotions()
})
this.get.units(project_id).then(units => {
this.components.units.data.types = units
this.components.units.draw.buttons()
})
}
reset() {
this.components.form.reset()
this.components.promotions.reset()
this.components.units.reset()
}
add() {
const url = '/api/ventas/reservations/add'
const form = document.getElementById(this.ids.form)
const body = new FormData(form)
const date = this.components.$date.calendar('get date')
console.debug(date)
body.set('date', [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('-'))
body.set('comuna', this.components.$comuna.dropdown('get value'))
body.set('region', this.components.$region.dropdown('get value'))
body.set('broker_rut', this.components.$broker.dropdown('get value'))
/*body.set('promotions[]', '')
this.components.promotions.forEach(promotion => {
body.append('promotions[]', promotion.querySelector('promotion').value)
})*/
/*body.set('units[]', '')
this.components.units.forEach(unit => {
body.append('units[]', unit.querySelector('unit').value)
})*/
const method = 'post'
return APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
if (json.success) {
window.location.reload()
}
})
}
get = {
comunas: region_id => {
if (region_id in this.data.comunas) {
this.components.$comuna.dropdown('change values', this.data.comunas[region_id])
if (this.data.current_user !== null && this.data.current_user?.direccion?.comuna !== null) {
this.components.$comuna.dropdown('set selected', this.data.current_user.direccion.comuna.id)
}
return
}
const uri = `/api/region/${region_id}/comunas`
return APIClient.fetch(uri).then(response => response.json()).then(json => {
if (json.comunas.length === 0) {
return
}
this.data.comunas[region_id] = json.comunas.map(comuna => {
return {
text: comuna.descripcion,
name: comuna.descripcion,
value: comuna.id
}
})
this.components.$comuna.dropdown('change values', this.data.comunas[region_id])
if (this.data.current_user !== null && this.data.current_user?.direccion?.comuna !== null) {
this.components.$comuna.dropdown('set selected', this.data.current_user.direccion.comuna.id)
}
})
},
brokers: project_id => {
if (project_id in this.data.brokers) {
return new Promise((resolve, reject) => {
resolve(this.data.brokers[project_id])
})
}
const uri = `/api/proyecto/${project_id}/brokers`
return APIClient.fetch(uri).then(response => response.json()).then(json => {
if (json.contracts.length === 0) {
return
}
const formatter = new Intl.NumberFormat('es-CL', { style: 'percent', minimumFractionDigits: 2 })
this.data.brokers[project_id] = json.contracts.map(contract => {
return {
id: contract.id,
broker_rut: contract.broker_rut,
commission: formatter.format(contract.commission),
name: '',
text: '',
}
})
const promises = []
json.contracts.forEach(contract => {
promises.push(this.get.broker(contract.broker_rut))
})
return Promise.all(promises).then(data => {
data.forEach(broker => {
if (!('rut' in broker)) {
return
}
const idx = this.data.brokers[project_id].findIndex(contract => contract.broker_rut === broker.rut)
this.data.brokers[project_id][idx].name = this.data.brokers[project_id][idx].text = `${broker.name} - ${this.data.brokers[project_id][idx].commission}`
})
this.fill.brokers()
})
})
},
broker: (broker_rut) => {
const uri = `/api/proyectos/broker/${broker_rut}`
return APIClient.fetch(uri).then(response => response.json()).then(json => {
if (!('broker' in json)) {
return []
}
return json.broker
})
},
promotions: project_id => {
if (project_id in this.data.promotions) {
return new Promise((resolve, reject) => {
resolve(this.data.promotions[project_id])
})
}
const uri = `/api/proyecto/${project_id}/promotions`
return APIClient.fetch(uri).then(response => response.json()).then(json => {
if (json.promotions.length === 0) {
return this.data.promotions[project_id] = []
}
return this.data.promotions[project_id] = json.promotions.map(promotion => {
return {
text: promotion.name,
name: promotion.name,
value: promotion.id
}
})
})
},
units: project_id => {
if (project_id in this.data.units) {
return new Promise((resolve, reject) => {
resolve(this.data.units[project_id])
})
}
const uri = `/api/proyecto/${project_id}/unidades`
return APIClient.fetch(uri).then(response => response.json()).then(json => {
if (json.total === 0) {
this.data.units[project_id] = {}
return this.data.units[project_id]
}
if (!(project_id in this.data.units)) {
this.data.units[project_id] = {}
}
Object.entries(json.unidades).forEach(([type, units]) => {
if (!(type in this.data.units[project_id])) {
this.data.units[project_id][type] = []
}
units.forEach(unit => {
this.data.units[project_id][type].push({
text: unit.descripcion,
name: unit.descripcion,
value: unit.id
})
})
})
return this.data.units[project_id]
})
},
user: rut => {
if (this.data.current_user !== null && this.data.current_user?.rut === rut) {
return this.data.current_user
}
this.loader.show()
const uri = `/api/persona/${rut}`
return APIClient.fetch(uri).then(response => response.json()).then(json => {
this.loader.hide()
if (!json.success) {
return
}
this.data.current_user = json.persona
return json.persona
})
}
}
fill = {
user: user => {
const form = this.components.form
form.querySelector('input[name="name"]').value = user.nombres || ''
form.querySelector('input[name="last_name"]').value = user.apellidoPaterno || ''
form.querySelector('input[name="last_name2"]').value = user.apellidoMaterno || ''
form.querySelector('input[name="calle"]').value = user.datos?.direccion?.calle || ''
form.querySelector('input[name="numero"]').value = user.datos?.direccion?.numero || ''
form.querySelector('input[name="extra"]').value = user.datos?.direccion?.extra || ''
if (parseInt(this.components.$region.dropdown('get value')) !== user.datos?.direccion?.comuna?.provincia?.region?.id) {
this.components.$region.dropdown('set selected', user.datos?.direccion?.comuna?.provincia?.region?.id)
} else {
this.components.$comuna.dropdown('set selected', user.datos?.direccion?.comuna?.id)
}
form.querySelector('input[name="phone"]').value = user.datos?.telefono
const email_parts = user.datos?.email.split('@')
form.querySelector('input[name="email_name"]').value = email_parts[0]
form.querySelector('input[name="email_domain"]').value = email_parts[1]
if ('estadoCivil' in user.datos) {
form.querySelector('input[name="civil_status"]').value = user.datos?.estadoCivil.charAt(0).toUpperCase() + user.datos?.estadoCivil.slice(1)
} else {
form.querySelector('input[name="civil_status"]').value = ''
}
if ('ocupacion' in user.datos) {
form.querySelector('input[name="profession"]').value = user.datos?.ocupacion
} else {
form.querySelector('input[name="profession"]').value = ''
}
if ('fechaNacimiento' in user.datos) {
this.components.$birthdate.calendar('set date', user.datos?.fechaNacimiento)
}
},
brokers: () => {
this.components.$broker.dropdown('change values', this.data.brokers[this.data.current_project])
},
units: () => {
const buttons = []
Object.entries(this.maps.unit_types).forEach(([type, map]) => {
if (!(type in this.data.units[this.data.current_project])) {
return
}
buttons.push(`<div class="field"><div class="ui icon button" data-type="${type}" title="${type.charAt(0).toUpperCase() + type.slice(1)}"><i class="plus icon"></i><i class="${map} icon"></i></div></div>`)
})
this.components.unit_buttons.innerHTML = buttons.join('')
this.components.unit_buttons.querySelectorAll('.ui.icon.button').forEach(button => {
button.addEventListener('click', () => {
this.units.add(button.dataset.type)
})
})
}
}
watch = {
region: (value, text, $choice) => {
this.get.comunas(value)
},
}
loader = {
show: () => {
this.components.$loader.show()
},
hide: () => {
this.components.$loader.hide()
}
}
show() {
this.reset()
this.components.$modal.modal('show')
}
setup() {
this.components.$modal = $(`#${this.ids.modal}`)
this.components.form = document.getElementById(this.ids.form)
this.components.$date = $(`#${this.ids.date}`)
this.components.rut = document.getElementById(this.ids.rut)
this.components.digit = document.getElementById(this.ids.digit)
this.components.$birthdate = $(`#${this.ids.birthdate}`)
this.components.$comuna = $(`#${this.ids.comuna}`)
this.components.$region = $(`#${this.ids.region}`)
this.components.$broker = $(`#${this.ids.broker}`)
this.components.promotions = new AddModalPromotions()
this.components.units = new AddModalUnits()
this.components.$modal.modal({
onApprove: () => {
this.add()
}
})
this.components.form.addEventListener('submit', event => {
event.preventDefault()
this.add()
return false
})
const cdo = structuredClone(calendar_date_options)
cdo['startDate'] = new Date()
cdo['maxDate'] = new Date()
this.components.$date.calendar(cdo)
const rutInput = this.components.rut.querySelector('input')
rutInput.addEventListener('input', event => {
const value = event.currentTarget.value.replace(/\D/g, '')
if (value.length <= 3) {
return
}
this.components.digit.textContent = Rut.digitoVerificador(value)
})
rutInput.addEventListener('blur', event => {
const value = event.currentTarget.value.replace(/\D/g, '')
if (value.length <= 3) {
return
}
event.currentTarget.value = Rut.format(value)
this.get.user(value).then(user => {
this.fill.user(user)
})
})
const cdo2 = structuredClone(cdo)
cdo2['startDate'].setFullYear(cdo2['startDate'].getFullYear() - 18)
cdo2['maxDate'].setFullYear(cdo2['maxDate'].getFullYear() - 18)
this.components.$birthdate.calendar(cdo2)
this.components.$region.dropdown({
fireOnInit: true,
onChange: this.watch.region
})
this.components.$region.dropdown('set selected', 13)
this.components.$comuna.dropdown()
this.components.$broker.dropdown()
this.components.$loader = $(`#${this.ids.loader}`)
}
}
</script>
@endpush

View File

@ -0,0 +1,34 @@
<?php
namespace Incoviba\Controller\API;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Exception\ServiceAction;
use Incoviba\Repository;
use Incoviba\Service;
class Personas extends Ideal\Controller
{
use withJson;
public function get(ServerRequestInterface $request, ResponseInterface $response,
Service\Persona $personaService, int $rut): ResponseInterface
{
$output = [
'rut' => $rut,
'persona' => null,
'success' => false
];
try {
$persona = $personaService->getById($rut);
$output['persona'] = $persona;
$output['success'] = true;
} catch (ServiceAction\Read $exception) {
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
}
return $this->withJson($response, $output);
}
}

View File

@ -187,5 +187,18 @@ class Proyectos
}
return $this->withJson($response, $output);
}
public function promotions(ServerRequestInterface $request, ResponseInterface $response,
Service\Venta\Promotion $promotionService, int $proyecto_id): ResponseInterface
{
$output = [
'project_id' => $proyecto_id,
'promotions' => []
];
try {
$output['promotions'] = $promotionService->getByProject($proyecto_id);
} catch (Read $exception) {
return $this->withError($response, $exception);
}
return $this->withJson($response, $output);
}
}

View File

@ -11,7 +11,8 @@ class Reservations
{
use withJson;
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Reservation $reservationService): ResponseInterface
public function __invoke(ServerRequestInterface $request, ResponseInterface $response,
Service\Venta\Reservation $reservationService): ResponseInterface
{
$reservations = [];
try {
@ -22,6 +23,18 @@ class Reservations
return $this->withJson($response, compact('reservations'));
}
public function getByProject(ServerRequestInterface $request, ResponseInterface $response,
Service\Venta\Reservation $reservationService, int $project_id): ResponseInterface
{
$reservations = [];
try {
$reservations = $reservationService->getByProject($project_id);
} catch (ServiceAction\Read $exception) {
return $this->withError($response, $exception);
}
return $this->withJson($response, compact('reservations'));
}
public function get(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Reservation $reservationService, int $reservation_id): ResponseInterface
{
$output = [
@ -100,4 +113,47 @@ class Reservations
return $this->withJson($response, $output);
}
public function active(ServerRequestInterface $request, ResponseInterface $response,
Service\Venta\Reservation $reservationService, int $project_id): ResponseInterface
{
$output = [
'project_id' => $project_id,
'reservations' => [],
'success' => false,
];
try {
$output['reservations'] = $reservationService->getActive($project_id);
$output['success'] = true;
} catch (ServiceAction\Read) {}
return $this->withJson($response, $output);
}
public function pending(ServerRequestInterface $request, ResponseInterface $response,
Service\Venta\Reservation $reservationService, int $project_id): ResponseInterface
{
$output = [
'project_id' => $project_id,
'reservations' => [],
'success' => false,
];
try {
$output['reservations'] = $reservationService->getPending($project_id);
$output['success'] = true;
} catch (ServiceAction\Read) {}
return $this->withJson($response, $output);
}
public function rejected(ServerRequestInterface $request, ResponseInterface $response,
Service\Venta\Reservation $reservationService, int $project_id): ResponseInterface
{
$output = [
'project_id' => $project_id,
'reservations' => [],
'success' => false,
];
try {
$output['reservations'] = $reservationService->getRejected($project_id);
$output['success'] = true;
} catch (ServiceAction\Read) {}
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace Incoviba\Controller\Ventas;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Repository;
use Incoviba\Service;
class Reservations
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response,
Service\Proyecto $proyectoService, Repository\Region $regionRepository,
View $view): ResponseInterface
{
$projects = [];
try {
$projects = $proyectoService->getVendibles('descripcion');
} catch (Read) {}
$regions = [];
try {
$regions = $regionRepository->fetchAll();
} catch (EmptyResult) {}
return $view->render($response, 'ventas.reservations', compact('projects', 'regions'));
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace Incoviba\Exception\Model;
use Throwable;
use Exception;
class InvalidState extends Exception
{
public function __construct(string $message = "Invalid state", int $code = 505, ?Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}

View File

@ -1,6 +1,7 @@
<?php
namespace Incoviba\Model;
use Incoviba\Common\Implement\Exception\EmptyResult;
use InvalidArgumentException;
use Incoviba\Common\Ideal;
use Incoviba\Model\Persona\Datos;
@ -27,7 +28,11 @@ class Persona extends Ideal\Model
public function datos(): ?Datos
{
if (!isset($this->datos)) {
$this->datos = $this->runFactory('datos');
try {
$this->datos = $this->runFactory('datos');
} catch (EmptyResult) {
$this->datos = null;
}
}
return $this->datos;
}

View File

@ -1,7 +1,10 @@
<?php
namespace Incoviba\Model\Proyecto;
use DateTimeImmutable;
use DateTimeInterface;
use Incoviba\Common;
use Incoviba\Model\Proyecto;
class Broker extends Common\Ideal\Model
{
@ -26,6 +29,36 @@ class Broker extends Common\Ideal\Model
}
return $this->contracts;
}
public function getContract(Proyecto $proyecto, ?DateTimeInterface $date = null): ?Proyecto\Broker\Contract
{
if ($date === null) {
$date = new DateTimeImmutable();
}
$contracts = $this->contracts();
$valid = array_filter($contracts, fn(Proyecto\Broker\Contract $contract) => $contract->project->id === $proyecto->id);
$valid = array_filter($valid, fn(Proyecto\Broker\Contract $contract) => $contract->wasActive($date));
if (count($valid) === 0) {
return null;
}
return last($valid);
}
public function applyCommission(Proyecto $proyecto, float $price, ?DateTimeInterface $date = null): float
{
$contract = $this->getContract($proyecto, $date);
if ($contract === null) {
return $price;
}
return $contract->activate()->apply($proyecto, $price);
}
public function reverseCommission(Proyecto $proyecto, float $price, ?DateTimeInterface $date = null): float
{
$contract = $this->getContract($proyecto, $date);
if ($contract === null) {
return $price;
}
return $contract->activate()->reverse($proyecto, $price);
}
public function rutFull(): string
{

View File

@ -1,6 +1,7 @@
<?php
namespace Incoviba\Model\Proyecto\Broker;
use DateTimeInterface;
use Incoviba\Common;
use Incoviba\Model;
@ -41,6 +42,51 @@ class Contract extends Common\Ideal\Model
return $this->promotions;
}
public function isActive(): bool
{
$state = $this->current();
return $state !== null and $state->isActive();
}
public function activate(): self
{
$this->current()->activate();
return $this;
}
public function wasActive(DateTimeInterface $date): bool
{
$states = $this->states();
return array_any($states, fn($state) => $state->date <= $date);
}
public function value(float $price): float
{
if (!$this->isActive()) {
return $price;
}
return $price * (1 + $this->commission);
}
public function inverse(float $price): float
{
if (!$this->isActive()) {
return $price;
}
return $price / (1 + $this->commission);
}
public function apply(Model\Proyecto $project, float $price): float
{
if (!$this->isActive() or $this->project->id !== $project->id) {
return $price;
}
return $this->value($price);
}
public function reverse(Model\Proyecto $project, float $price): float
{
if (!$this->isActive() or $this->project->id !== $project->id) {
return $price;
}
return $this->inverse($price);
}
protected function jsonComplement(): array
{
return [

View File

@ -11,6 +11,16 @@ class State extends Common\Ideal\Model
public DateTimeInterface $date;
public State\Type $type;
public function isActive(): bool
{
return $this->type === State\Type::ACTIVE;
}
public function activate(): self
{
$this->type = State\Type::ACTIVE;
return $this;
}
protected function jsonComplement(): array
{
return [

View File

@ -3,6 +3,7 @@ namespace Incoviba\Model\Venta;
use DateTimeInterface;
use Incoviba\Common;
use Incoviba\Model\Proyecto;
use Incoviba\Model\Proyecto\Broker;
use Incoviba\Model\Venta\Promotion\State;
use Incoviba\Model\Venta\Promotion\Type;
@ -61,13 +62,95 @@ class Promotion extends Common\Ideal\Model
return $this->units;
}
public function isActive(): bool
{
return $this->state === State::ACTIVE;
}
public function activate(): self
{
$this->state = State::ACTIVE;
return $this;
}
public function value(float $price): float
{
if (!$this->isActive()) {
return $price;
}
if ($this->type === Type::FIXED) {
return $price + $this->amount;
}
return $price / (1 - $this->amount);
}
public function inverse(float $price): float
{
if (!$this->isActive()) {
return $price;
}
if ($this->type === Type::FIXED) {
return $price - $this->amount;
}
return $price * (1 - $this->amount);
}
public function apply(Unidad $unit, float $price, ?Broker $broker = null): float
{
if (!$this->isActive()) {
return $price;
}
$projectIds = array_map(fn(Proyecto $proyecto) => $proyecto->id, $this->projects());
if (in_array($unit->proyectoTipoUnidad->proyecto->id, $projectIds)) {
return $this->value($price);
}
if ($broker !== null) {
$brokerIds = array_map(fn(Broker $broker) => $broker->id, $this->brokers());
if (in_array($broker->id, $brokerIds)) {
return $this->value($price);
}
}
$typeIds = array_map(fn(Proyecto\TipoUnidad $type) => $type->id, $this->unitTypes());
if (in_array($unit->proyectoTipoUnidad->tipoUnidad->id, $typeIds)) {
return $this->value($price);
}
$lineIds = array_map(fn(Proyecto\ProyectoTipoUnidad $line) => $line->id, $this->unitLines());
if (in_array($unit->proyectoTipoUnidad->id, $lineIds)) {
return $this->value($price);
}
$unitIds = array_map(fn(Unidad $unit) => $unit->id, $this->units());
if (in_array($unit->id, $unitIds)) {
return $this->value($price);
}
return $price;
}
public function reverse(Unidad $unit, float $price, ?Broker $broker = null): float
{
if (!$this->isActive()) {
return $price;
}
$projectIds = array_map(fn(Proyecto $proyecto) => $proyecto->id, $this->projects());
if (in_array($unit->proyectoTipoUnidad->proyecto->id, $projectIds)) {
return $this->inverse($price);
}
if ($broker !== null) {
$brokerIds = array_map(fn(Broker $broker) => $broker->id, $this->brokers());
if (in_array($broker->id, $brokerIds)) {
return $this->inverse($price);
}
}
$typeIds = array_map(fn(Proyecto\TipoUnidad $type) => $type->id, $this->unitTypes());
if (in_array($unit->proyectoTipoUnidad->tipoUnidad->id, $typeIds)) {
return $this->inverse($price);
}
$lineIds = array_map(fn(Proyecto\ProyectoTipoUnidad $line) => $line->id, $this->unitLines());
if (in_array($unit->proyectoTipoUnidad->id, $lineIds)) {
return $this->inverse($price);
}
$unitIds = array_map(fn(Unidad $unit) => $unit->id, $this->units());
if (in_array($unit->id, $unitIds)) {
return $this->inverse($price);
}
return $price;
}
protected function jsonComplement(): array
{

View File

@ -7,11 +7,44 @@ use Incoviba\Model;
class Reservation extends Common\Ideal\Model
{
public Model\Proyecto $project;
public Model\Persona $buyer;
public DateTimeInterface $date;
public array $units = [];
public array $promotions = [];
public ?Model\Proyecto\Broker $broker = null;
public function offer(): float
{
return array_sum(array_column($this->units, 'value'));
}
public function withCommission(): float
{
$base = 0;
foreach ($this->units as $unit) {
foreach ($this->promotions as $promotion) {
$base += $promotion->activate()->reverse($unit['unit'], $unit['value'], $this->broker);
}
}
return $base;
}
public function base(): float
{
$base = $this->withCommission();
if ($this->broker !== null) {
$base = $this->broker->reverseCommission($this->project, $base, $this->date);
}
return $base;
}
public function price(): float
{
$price = 0;
foreach ($this->units as $unit) {
$price += $unit->unit->precio($this->date);
}
return $price;
}
protected array $states = [];
public function states(): array
@ -38,13 +71,12 @@ class Reservation extends Common\Ideal\Model
$this->units[$i]['value'] = $value;
return $this;
}
$this->units[] = [
$this->units[] = (object) [
'unit' => $unit,
'value' => $value,
];
return $this;
}
public function removeUnit(int $unit_id): self
{
if (($i = $this->findUnit($unit_id)) === null) {
@ -54,7 +86,6 @@ class Reservation extends Common\Ideal\Model
$this->units = array_values($this->units);
return $this;
}
public function findUnit(int $unit_id): ?int
{
foreach ($this->units as $idx => $unit) {
@ -64,20 +95,43 @@ class Reservation extends Common\Ideal\Model
}
return null;
}
public function hasUnit(int $unit_id): bool
{
return $this->findUnit($unit_id) !== null;
}
public function summary(): string
{
$unitSummary = array_map(function($unit) {
$type = $unit->unit->proyectoTipoUnidad->tipoUnidad->descripcion;
$cap = strtoupper(strstr($type, 0, 1));
return "{$cap}{$unit->unit->descripcion}";
}, $this->units);
return implode('', $unitSummary);
}
public function valid(): bool
{
$base = $this->base();
$price = $this->price();
return $base >= $price;
}
protected function jsonComplement(): array
{
return [
'buyer_rut' => $this->buyer->rut,
'project_id' => $this->project->id,
'buyer' => $this->buyer,
'date' => $this->date->format('Y-m-d'),
'units' => $this->units,
'promotions' => $this->promotions,
'broker_rut' => $this->broker?->rut,
'broker' => $this->broker,
'offer' => $this->offer(),
'with_commission' => $this->withCommission(),
'base' => $this->base(),
'price' => $this->price(),
'valid' => $this->valid(),
'summary' => $this->summary()
];
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace Incoviba\Model\Venta\Reservation\Detail;
enum Type: int
{
case Unit = 1;
case Promotion = 2;
case Broker = 3;
public function jsonSerialize(): array
{
return [
'id' => $this->value,
'description' => $this->name
];
}
}

View File

@ -9,17 +9,14 @@ class State extends Common\Ideal\Model
{
public Model\Venta\Reservation $reservation;
public DateTimeInterface $date;
public int $type;
public Model\Venta\Reservation\State\Type $type;
protected function jsonComplement(): array
{
return [
'reservation_id' => $this->reservation->id,
'date' => $this->date->format('Y-m-d'),
'type' => [
'id' => $this->type,
'description' => State\Type::name($this->type)
]
'type' => $this->type
];
}
}
}

View File

@ -7,13 +7,15 @@ enum Type: int
case INACTIVE = 0;
case REJECTED = -1;
public static function name(int $type): string
public function jsonSerialize(): array
{
return match ($type) {
self::ACTIVE => 'active',
self::INACTIVE => 'inactive',
self::REJECTED => 'rejected',
default => throw new \InvalidArgumentException('Unexpected match value')
};
return [
'id' => $this->value,
'description' => $this->name
];
}
}
public static function getTypes(): array
{
return [self::ACTIVE->value, self::INACTIVE->value, self::REJECTED->value];
}
}

View File

@ -29,6 +29,9 @@ class Datos extends Ideal\Repository
->register('direccion_id', (new Implement\Repository\Mapper())
->setProperty('direccion')
->setFunction(function($data) {
if ($data['direccion_id'] === null) {
return null;
}
return $this->direccionRepository->fetchById($data['direccion_id']);
})->setDefault(null))
->register('telefono', (new Implement\Repository\Mapper())->setFunction(function($data) {

View File

@ -3,14 +3,19 @@ namespace Incoviba\Repository\Venta;
use DateTimeInterface;
use DateInterval;
use Incoviba\Common\Define;
use Incoviba\Exception\Model\InvalidState;
use PDO;
use Incoviba\Common;
use Incoviba\Model;
use Incoviba\Repository;
use PDOException;
class Reservation extends Common\Ideal\Repository
{
public function __construct(Common\Define\Connection $connection, protected Repository\Persona $personaRepository,
public function __construct(Common\Define\Connection $connection,
protected Repository\Proyecto $proyectoRepository,
protected Repository\Persona $personaRepository,
protected Repository\Proyecto\Broker $brokerRepository,
protected Unidad $unitRepository, protected Promotion $promotionRepository)
{
@ -25,37 +30,33 @@ class Reservation extends Common\Ideal\Repository
public function create(?array $data = null): Model\Venta\Reservation
{
$map = (new Common\Implement\Repository\MapperParser())
->register('project_id', (new Common\Implement\Repository\Mapper())
->setProperty('project')
->setFunction(function($data) {
return $this->proyectoRepository->fetchById($data['project_id']);
}))
->register('buyer_rut', (new Common\Implement\Repository\Mapper())
->setProperty('buyer')
->setFunction(function($data) use ($data) {
->setFunction(function($data) {
return $this->personaRepository->fetchById($data['buyer_rut']);
}))
->register('date', new Common\Implement\Repository\Mapper\DateTime('date'))
->register('broker_rut', (new Common\Implement\Repository\Mapper())
->setProperty('broker')
->setDefault(null)
->setFunction(function($data) use ($data) {
try {
return $this->brokerRepository->fetchById($data['broker_rut']);
} catch (Common\Implement\Exception\EmptyResult) {
return null;
}
}));
->register('date', new Common\Implement\Repository\Mapper\DateTime('date'));
return $this->parseData(new Model\Venta\Reservation(), $data, $map);
}
public function save(Common\Define\Model $model): Model\Venta\Reservation
{
$model->id = $this->saveNew([
'project_id',
'buyer_rut',
'date',
'broker_rut'
'date'
], [
$model->project->id,
$model->buyer->rut,
$model->date->format('Y-m-d'),
$model->broker?->rut
$model->date->format('Y-m-d')
]);
$this->saveUnits($model);
$this->savePromotions($model);
$this->saveBroker($model);
return $model;
}
@ -67,15 +68,20 @@ class Reservation extends Common\Ideal\Repository
*/
public function edit(Common\Define\Model $model, array $new_data): Model\Venta\Reservation
{
return $this->update($model, ['buyer_rut', 'date', 'broker_rut'], $new_data);
$model = $this->update($model, ['project_id', 'buyer_rut', 'date'], $new_data);
$this->editUnits($model, $new_data);
$this->editPromotions($model, $new_data);
$this->editBroker($model, $new_data);
return $model;
}
public function load(array $data_row): Model\Venta\Reservation
{
$model = parent::load($data_row);
$this->fetchUnits($model);
$this->fetchPromotions($model);
$this->fetchUnits($model, $data_row);
$this->fetchBroker($model, $data_row);
$this->fetchPromotions($model, $data_row);
return $model;
}
@ -93,6 +99,86 @@ class Reservation extends Common\Ideal\Repository
->where('buyer_rut = :buyer_rut AND date >= :date');
return $this->fetchOne($query, ['buyer_rut' => $buyer_rut, 'date' => $date->sub(new DateInterval('P10D'))->format('Y-m-d')]);
}
public function fetchByProject(int $project_id): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from('reservations')
->where('project_id = :project_id');
return $this->fetchMany($query, ['project_id' => $project_id]);
}
/**
* @param int $project_id
* @param int $state
* @return array
* @throws Common\Implement\Exception\EmptyResult
* @throws InvalidState
*/
public function fetchState(int $project_id, int $state): array
{
if (!in_array($state, Model\Venta\Reservation\State\Type::getTypes())) {
throw new InvalidState();
}
$sub1 = $this->connection->getQueryBuilder()
->select('MAX(id) AS id, reservation_id')
->from('reservation_states')
->group('reservation_id');
$sub2 = $this->connection->getQueryBuilder()
->select('er1.*')
->from('reservation_states er1')
->joined("INNER JOIN ({$sub1}) er0 ON er0.id = er1.id");
$query = $this->connection->getQueryBuilder()
->select()
->from('reservations')
->joined("INNER JOIN ({$sub2}) er ON er.reservation_id = reservations.id")
->where('project_id = :project_id AND er.type = :state');
return $this->fetchMany($query, ['project_id' => $project_id,
'state' => $state]);
}
/**
* @param int $project_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchActive(int $project_id): array
{
try {
return $this->fetchState($project_id, Model\Venta\Reservation\State\Type::ACTIVE->value);
} catch (InvalidState $exception) {
throw new Common\Implement\Exception\EmptyResult('Select active reservations', $exception);
}
}
/**
* @param int $project_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchPending(int $project_id): array
{
try {
return $this->fetchState($project_id, Model\Venta\Reservation\State\Type::INACTIVE->value);
} catch (InvalidState $exception) {
throw new Common\Implement\Exception\EmptyResult('Select pending reservations', $exception);
}
}
/**
* @param int $project_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchRejected(int $project_id): array
{
try {
return $this->fetchState($project_id, Model\Venta\Reservation\State\Type::REJECTED->value);
} catch (InvalidState $exception) {
throw new Common\Implement\Exception\EmptyResult('Select rejected reservations', $exception);
}
}
protected function saveUnits(Model\Venta\Reservation $reservation): void
{
@ -101,22 +187,71 @@ class Reservation extends Common\Ideal\Repository
}
$queryCheck = $this->connection->getQueryBuilder()
->select('COUNT(id) AS cnt')
->from('reservation_data')
->where('reservation_id = :id AND type = "Unit" AND reference_id = :unit_id');
->from('reservation_details')
->where('reservation_id = :id AND type = :type AND reference_id = :unit_id');
$statementCheck = $this->connection->prepare($queryCheck);
$queryInsert = $this->connection->getQueryBuilder()
->insert()
->into('reservation_data')
->into('reservation_details')
->columns(['reservation_id', 'type', 'reference_id', 'value'])
->values([':reservation_id', ':type', ':reference_id', ':value']);
$statementInsert = $this->connection->prepare($queryInsert);
foreach ($reservation->units as $unit) {
$statementCheck->execute(['id' => $reservation->id, 'unit_id' => $unit['unit']->id]);
$statementCheck->execute([
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Unit->value,
'unit_id' => $unit->unit->id
]);
$result = $statementCheck->fetch(PDO::FETCH_ASSOC);
if ($result['cnt'] > 0) {
continue;
}
$statementInsert->execute(['reservation_id' => $reservation->id, 'type' => 'Unit', 'reference_id' => $unit['unit']->id, 'value' => $unit['value']]);
$statementInsert->execute([
'reservation_id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Unit->value,
'reference_id' => $unit->unit->id,
'value' => $unit->value
]);
}
$this->cleanUpUnits($reservation);
}
protected function cleanUpUnits(Model\Venta\Reservation $reservation): void
{
$this->cleanUpDetails($reservation,
Model\Venta\Reservation\Detail\Type::Unit->value,
array_map(fn($unit) => $unit->unit->id, $reservation->units));
}
protected function saveBroker(Model\Venta\Reservation &$reservation): void
{
if ($reservation->broker === null) {
$this->removeBroker($reservation);
return;
}
try {
$queryCheck = $this->connection->getQueryBuilder()
->select('id')
->from('reservation_details')
->where('reservation_id = :id AND type = :type');
$statementCheck = $this->connection->execute($queryCheck, [
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Broker->value
]);
$result = $statementCheck->fetch(PDO::FETCH_ASSOC);
$new_id = $reservation->broker->id;
$reservation->broker = $this->brokerRepository->fetchById($result['id']);
$this->editBroker($reservation, ['broker_id' => $new_id]);
} catch (PDOException) {
$queryInsert = $this->connection->getQueryBuilder()
->insert()
->into('reservation_details')
->columns(['reservation_id', 'type', 'reference_id'])
->values([':reservation_id', ':type', ':reference_id']);
$this->connection->execute($queryInsert, [
'reservation_id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Broker->value,
'reference_id' => $reservation->broker->id
]);
}
}
protected function savePromotions(Model\Venta\Reservation $reservation): void
@ -126,60 +261,152 @@ class Reservation extends Common\Ideal\Repository
}
$queryCheck = $this->connection->getQueryBuilder()
->select('COUNT(id) AS cnt')
->from('reservation_data')
->where('reservation_id = :id AND type = "Promotion" AND reference_id = :promotion_id');
->from('reservation_details')
->where('reservation_id = :id AND type = :type AND reference_id = :promotion_id');
$statementCheck = $this->connection->prepare($queryCheck);
$queryInsert = $this->connection->getQueryBuilder()
->insert()
->into('reservation_data')
->into('reservation_details')
->columns(['reservation_id', 'type', 'reference_id'])
->values([':reservation_id', ':type', ':reference_id']);
$statementInsert = $this->connection->prepare($queryInsert);
foreach ($reservation->promotions as $promotion) {
$statementCheck->execute(['id' => $reservation->id, 'promotion_id' => $promotion->id]);
$statementCheck->execute([
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Promotion->value,
'promotion_id' => $promotion->id
]);
$result = $statementCheck->fetch(PDO::FETCH_ASSOC);
if ($result['cnt'] > 0) {
continue;
}
$statementInsert->execute(['reservation_id' => $reservation->id, 'type' => 'Promotion', 'reference_id' => $promotion->id]);
$statementInsert->execute([
'reservation_id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Promotion->value,
'reference_id' => $promotion->id
]);
}
$this->cleanUpPromotions($reservation);
}
protected function editUnits(Model\Venta\Reservation $reservation, array $new_data): void
protected function cleanUpPromotions(Model\Venta\Reservation $reservation): void
{
$this->cleanUpDetails($reservation,
Model\Venta\Reservation\Detail\Type::Promotion->value,
array_map(fn($promotion) => $promotion->id, $reservation->promotions));
}
protected function cleanUpDetails(Model\Venta\Reservation $reservation, int $type_id, array $currentIds): void
{
$queryCheck = $this->connection->getQueryBuilder()
->select('COUNT(id) AS cnt')
->from('reservation_details')
->where('reservation_id = :id AND type = :type');
$statementCheck = $this->connection->prepare($queryCheck);
$deleteParam = implode(', ', array_map(fn($id) => ":id$id", $currentIds));
$queryDelete = $this->connection->getQueryBuilder()
->delete()
->from('reservation_details')
->where("reservation_id = :id AND type = :type AND reference_id NOT IN ({$deleteParam})");
$statementDelete = $this->connection->prepare($queryDelete);
try {
$statementCheck->execute([
'id' => $reservation->id,
'type' => $type_id
]);
$result = $statementCheck->fetch(PDO::FETCH_ASSOC);
if ($result['cnt'] <= count($currentIds)) {
return;
}
$deleteIdValues = array_combine(array_map(fn($id) => "id$id", $currentIds), $currentIds);
$statementDelete->execute(array_merge(
['id' => $reservation->id, 'type' => $type_id],
$deleteIdValues));
} catch (PDOException) {}
}
protected function editUnits(Model\Venta\Reservation &$reservation, array $new_data): void
{
$querySelect = $this->connection->getQueryBuilder()
->select()
->from('reservation_data')
->where('reservation_id = :id AND type = "Unit" AND reference_id = :unit_id');
->from('reservation_details')
->where('reservation_id = :id AND type = :type AND reference_id = :unit_id');
$statementSelect = $this->connection->prepare($querySelect);
$queryUpdate = $this->connection->getQueryBuilder()
->update('reservation_data')
->update('reservation_details')
->set('value = :value')
->where('reservation_id = :id AND type = "Unit" AND reference_id = :unit_id');
->where('reservation_id = :id AND type = :type AND reference_id = :unit_id');
$statementUpdate = $this->connection->prepare($queryUpdate);
foreach ($new_data as $unit_id => $value) {
$idx = $reservation->findUnit($unit_id);
$queryInsert = $this->connection->getQueryBuilder()
->insert()
->into('reservation_details')
->columns(['reservation_id', 'type', 'reference_id', 'value'])
->values([':reservation_id', ':type', ':reference_id', ':value']);
$statementInsert = $this->connection->prepare($queryInsert);
foreach ($new_data['units'] as $unit) {
$idx = $reservation->findUnit($unit['unit_id']);
if ($idx === null) {
$reservation->addUnit($this->unitRepository->fetchById($unit_id), $value);
$reservation->addUnit($this->unitRepository->fetchById($unit['unit_id']), $unit['value']);
$statementInsert->execute([
'reservation_id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Unit->value,
'reference_id' => $unit['unit_id'],
'value' => $unit['value']
]);
continue;
}
$statementSelect->execute(['id' => $reservation->id, 'unit_id' => $unit_id]);
$statementSelect->execute([
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Unit->value,
'unit_id' => $unit['unit_id']
]);
$result = $statementSelect->fetch(PDO::FETCH_ASSOC);
if (!$result) {
$reservation->addUnit($this->unitRepository->fetchById($unit['unit_id']), $unit['value']);
$statementInsert->execute([
'reservation_id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Unit->value,
'reference_id' => $unit['unit_id'],
'value' => $unit['value']
]);
continue;
}
$statementUpdate->execute(['id' => $reservation->id, 'unit_id' => $unit_id, 'value' => $value]);
$reservation->units[$idx]['value'] = $value;
$statementUpdate->execute([
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Unit->value,
'unit_id' => $unit['unit_id'],
'value' => $unit['value']
]);
$reservation->units[$idx]['value'] = $unit['value'];
}
}
protected function editPromotions(Model\Venta\Reservation $reservation, array $new_data): void
protected function editBroker(Model\Venta\Reservation &$reservation, array $new_data): void
{
if (!array_key_exists('broker_id', $new_data) or $new_data['broker_id'] === $reservation->broker->id) {
return;
}
try {
$query = $this->connection->getQueryBuilder()
->update('reservation_details')
->set('reference_id = :broker_id')
->where('reservation_id = :id AND type = :type');
$this->connection->execute($query, [
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Broker->value,
'broker_id' => $new_data['broker_id']
]);
$reservation->broker = $this->brokerRepository->fetchById($new_data['broker_id']);
} catch (PDOException) {}
}
protected function editPromotions(Model\Venta\Reservation &$reservation, array $new_data): void
{
$querySelect = $this->connection->getQueryBuilder()
->select()
->from('reservation_data')
->from('reservation_details')
->where('reservation_id = :id AND type = "Promotion" AND reference_id = :promotion_id');
$statementSelect = $this->connection->prepare($querySelect);
$queryUpdate = $this->connection->getQueryBuilder()
->update('reservation_data')
->update('reservation_details')
->set('value = :value')
->where('reservation_id = :id AND type = "Promotion" AND reference_id = :promotion_id');
$statementUpdate = $this->connection->prepare($queryUpdate);
@ -198,13 +425,26 @@ class Reservation extends Common\Ideal\Repository
$reservation->promotions[$idx] = $this->promotionRepository->fetchById($promotion_id);
}
}
protected function fetchUnits(Model\Venta\Reservation &$reservation): Model\Venta\Reservation
protected function fetchUnits(Model\Venta\Reservation &$reservation, array $new_data): Model\Venta\Reservation
{
$this->fetchSavedUnits($reservation);
if (array_key_exists('units', $new_data) and count($new_data['units']) > 0) {
$this->fetchUnsavedUnits($reservation, $new_data);
}
return $reservation;
}
protected function fetchSavedUnits(Model\Venta\Reservation &$reservation): Model\Venta\Reservation
{
$query = $this->connection->getQueryBuilder()
->select()
->from('reservation_data')
->where('reservation_id = :id AND type = "Unit"');
$statement = $this->connection->execute($query, ['id' => $reservation->id]);
->from('reservation_details')
->where('reservation_id = :id AND type = ?');
$statement = $this->connection->execute($query, [
'id' => $reservation->id,
Model\Venta\Reservation\Detail\Type::Unit->value
]);
while ($result = $statement->fetch(PDO::FETCH_ASSOC)) {
try {
@ -213,13 +453,69 @@ class Reservation extends Common\Ideal\Repository
}
return $reservation;
}
protected function fetchPromotions(Model\Venta\Reservation $reservation): Model\Venta\Reservation
protected function fetchUnsavedUnits(Model\Venta\Reservation &$reservation, array $new_data): Model\Venta\Reservation
{
if (!array_key_exists('units', $new_data) or count($new_data['units']) > 0) {
return $reservation;
}
$queryCheck = $this->connection->getQueryBuilder()
->select('COUNT(id) AS cnt')
->from('reservation_details')
->where('reservation_id = :id AND type = :type AND reference_id = :unit_id');
$statementCheck = $this->connection->prepare($queryCheck);
foreach ($new_data['units'] as $unit) {
$statementCheck->execute([
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Unit->value,
'unit_id' => $unit['unit_id']
]);
$result = $statementCheck->fetch(PDO::FETCH_ASSOC);
if ($result['cnt'] > 0) {
continue;
}
try {
$reservation->addUnit($this->unitRepository->fetchById($unit['unit_id']), $unit['value']);
} catch (Common\Implement\Exception\EmptyResult) {}
}
return $reservation;
}
protected function fetchBroker(Model\Venta\Reservation &$reservation, array $new_data): Model\Venta\Reservation
{
if (!array_key_exists('broker_id', $new_data)) {
$query = $this->connection->getQueryBuilder()
->select('reference_id')
->from('reservation_details')
->where('reservation_id = :id AND type = :type');
try {
$statement =$this->connection->execute($query, [
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Broker->value
]);
$result = $statement->fetch(PDO::FETCH_ASSOC);
$reservation->broker = $this->brokerRepository->fetchById($result['reference_id']);
} catch (PDOException) {}
return $reservation;
}
try {
$reservation->broker = $this->brokerRepository->fetchById($new_data['broker_id']);
} catch (Common\Implement\Exception\EmptyResult) {}
return $reservation;
}
protected function fetchPromotions(Model\Venta\Reservation &$reservation, array $new_data): Model\Venta\Reservation
{
$this->fetchSavedPromotions($reservation);
$this->fetchUnsavedPromotions($reservation, $new_data);
return $reservation;
}
protected function fetchSavedPromotions(Model\Venta\Reservation &$reservation): Model\Venta\Reservation
{
$query = $this->connection->getQueryBuilder()
->select()
->from('reservation_data')
->where('type = "Promotion" AND reservation_id = :id');
$statement = $this->connection->execute($query, ['id' => $reservation->id]);
->from('reservation_details')
->where('type = :type AND reservation_id = :id');
$statement = $this->connection->execute($query,
['id' => $reservation->id, 'type' => Model\Venta\Reservation\Detail\Type::Promotion->value]);
while ($result = $statement->fetch(PDO::FETCH_ASSOC)) {
try {
$reservation->promotions []= $this->promotionRepository->fetchById($result['reference_id']);
@ -227,4 +523,43 @@ class Reservation extends Common\Ideal\Repository
}
return $reservation;
}
protected function fetchUnsavedPromotions(Model\Venta\Reservation &$reservation, array $new_data): Model\Venta\Reservation
{
if (!array_key_exists('promotions', $new_data) or count($new_data['promotions']) > 0) {
return $reservation;
}
$queryCheck = $this->connection->getQueryBuilder()
->select('COUNT(id) AS cnt')
->from('reservation_details')
->where('type = :type AND reservation_id = :id AND reference_id = :promotion_id');
$statementCheck = $this->connection->prepare($queryCheck);
foreach ($new_data['promotions'] as $promotion) {
$statementCheck->execute([
'id' => $reservation->id,
'promotion_id' => $promotion
]);
$result = $statementCheck->fetch(PDO::FETCH_ASSOC);
if ($result['cnt'] > 0) {
continue;
}
try {
$reservation->promotions []= $this->promotionRepository->fetchById($promotion);
} catch (Common\Implement\Exception\EmptyResult) {}
}
return $reservation;
}
protected function removeBroker(Model\Venta\Reservation &$reservation): void
{
try {
$query = $this->connection->getQueryBuilder()
->delete()
->from('reservation_details')
->where('reservation_id = :id AND type = :type');
$this->connection->execute($query, [
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Broker->value
]);
$reservation->broker = null;
} catch (PDOException) {}
}
}

View File

@ -22,7 +22,7 @@ class State extends Common\Ideal\Repository
$map = (new Common\Implement\Repository\MapperParser(['type']))
->register('reservation_id', (new Common\Implement\Repository\Mapper())
->setProperty('reservation')
->setFunction(function($data) use ($data) {
->setFunction(function($data) {
return $this->reservationRepository->fetchById($data['reservation_id']);
}))
->register('date', new Common\Implement\Repository\Mapper\DateTime('date'));

View File

@ -35,7 +35,7 @@ class Persona extends Ideal\Service
/**
* @param int $rut
* @return Model\Persona
* @throws Read|Create
* @throws Read
*/
public function getById(int $rut): Model\Persona
{
@ -44,7 +44,11 @@ class Persona extends Ideal\Service
} catch (Implement\Exception\EmptyResult) {
try {
$this->propietarioRepository->fetchById($rut);
return $this->add(compact('rut'));
try {
return $this->add(compact('rut'));
} catch (Create $exception) {
throw new Read(__CLASS__, $exception);
}
} catch (Implement\Exception\EmptyResult $exception) {
throw new Read(__CLASS__, $exception);
}

View File

@ -48,6 +48,20 @@ class Promotion extends Ideal\Service
}
}
/**
* @param int $project_id
* @return array
* @throws Exception\ServiceAction\Read
*/
public function getByProject(int $project_id): array
{
try {
return array_map([$this, 'process'], $this->promotionRepository->fetchByProject($project_id));
} catch (Implement\Exception\EmptyResult $exception) {
throw new Exception\ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @param int $contract_id
* @return array

View File

@ -14,7 +14,9 @@ use Incoviba\Repository;
class Reservation extends Ideal\Service\API
{
public function __construct(LoggerInterface $logger, protected Repository\Venta\Reservation $reservationRepository)
public function __construct(LoggerInterface $logger,
protected Repository\Venta\Reservation $reservationRepository,
protected Repository\Venta\Reservation\State $stateRepository)
{
parent::__construct($logger);
}
@ -22,11 +24,19 @@ class Reservation extends Ideal\Service\API
public function getAll(null|string|array $order = null): array
{
try {
return $this->reservationRepository->fetchAll($order);
return array_map([$this, 'process'], $this->reservationRepository->fetchAll($order));
} catch (Implement\Exception\EmptyResult) {
return [];
}
}
public function getByProject(int $project_id): array
{
try {
return array_map([$this, 'process'], $this->reservationRepository->fetchByProject($project_id));
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
public function get(int $id): Model\Venta\Reservation
{
@ -37,6 +47,48 @@ class Reservation extends Ideal\Service\API
}
}
/**
* @param int $project_id
* @return array
* @throws ServiceAction\Read
*/
public function getActive(int $project_id): array
{
try {
return array_map([$this, 'process'], $this->reservationRepository->fetchActive($project_id));
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @param int $project_id
* @return array
* @throws ServiceAction\Read
*/
public function getPending(int $project_id): array
{
try {
return array_map([$this, 'process'], $this->reservationRepository->fetchPending($project_id));
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @param int $project_id
* @return array
* @throws ServiceAction\Read
*/
public function getRejected(int $project_id): array
{
try {
return array_map([$this, 'process'], $this->reservationRepository->fetchRejected($project_id));
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
public function add(array $data): Model\Venta\Reservation
{
try {
@ -76,6 +128,12 @@ class Reservation extends Ideal\Service\API
}
protected function process(Define\Model $model): Model\Venta\Reservation
{
$model->addFactory('states', new Implement\Repository\Factory()
->setArgs(['reservation_id' => $model->id])
->setCallable(function(int $reservation_id) {
return $this->stateRepository->fetchByReservation($reservation_id);
})
);
return $model;
}
}