382 Commits

Author SHA1 Message Date
2e80fddfb6 añadidos más formatos a tarifas encuadernacion lineas (dimensiones) 2024-11-07 14:15:14 +01:00
1e2d550301 archivos resumen 2024-11-06 22:10:09 +01:00
0a3618cd00 Merge branch 'fix/message-notification' into 'dev/presu_cliente_v2'
Fix/message notification

See merge request jjimenez/safekat!359
2024-11-06 21:09:05 +00:00
33fbfc1a5d Merge branch 'dev/presu_cliente_v2' into fix/message-notification 2024-11-06 22:06:02 +01:00
a8612f64a4 fix : notification clientes add where chat_department_id is not NULL 2024-11-06 19:56:20 +01:00
0b614d4d58 bug para presupuesto cliente (en direcciones) 2024-11-06 17:15:41 +01:00
55b225ab49 errata de 109 en encuadernaciones model 2024-11-05 17:47:30 +01:00
315d2a3acd arreglado carga de cliente 2024-11-04 23:58:18 +01:00
83c8628645 presupuesto cliente para perfil cliente 2024-10-31 08:42:41 +01:00
d0ee0b27bc precio minimo en tarifa encuadernacion a nivel de lineas 2024-10-30 18:36:35 +01:00
8556887567 vuelta a importe minimo en tiradas 2024-10-30 17:46:35 +01:00
f50987dc2b arreglado bug con tamaño personalizado en presupuesto admin 2024-10-28 18:52:06 +01:00
4180cea16a Merge branch 'fix/message-notification' into 'dev/presu_cliente_v2'
refactor : in message notification send client to presupuestocliente and admin...

See merge request jjimenez/safekat!357
2024-10-26 11:15:09 +00:00
0b3bf0ed85 refactor : in message notification send client to presupuestocliente and admin or beta to presupuesto admin 2024-10-26 08:56:18 +02:00
14fe3b1461 refactor : in message notification send client to presupuestocliente and admin or beta to presupuesto admin 2024-10-26 08:56:06 +02:00
58ab81d8e8 arreglado el poder guardar sin direcciones 2024-10-25 13:59:23 +02:00
cdb9afc290 arreglando el lomo de cubierta cuando cambias de fresado a cosido 2024-10-25 13:56:37 +02:00
adcf2fbec3 arreglado grapado 2024-10-25 13:42:09 +02:00
eb806621c6 preview
terminada
2024-10-25 12:30:38 +02:00
0963fae240 preview 2024-10-25 12:12:16 +02:00
daa10420c7 Merge branch 'fix/datatable-error-presupuesto' into 'dev/presu_cliente_v2'
default sort error presupuestos datatable,set pagination to 50 and add page selector

See merge request jjimenez/safekat!356
2024-10-25 09:29:30 +00:00
716019bf81 default sort error presupuestos datatable,set pagination to 50 and add page selector 2024-10-25 11:27:27 +02:00
2ac99d14c0 click para moverse del menu 2024-10-24 21:05:59 +02:00
0f00649f99 corregidos errores 2024-10-24 08:50:13 +02:00
3dd9f8f7e3 fix notification chat error cuando cliente no tiene facturas asociadas 2024-10-23 05:48:06 +00:00
c79bc4343f Merge branch 'feat/add-chat-presupuesto-cliente' into 'dev/presu_cliente_v2'
Feat/add chat presupuesto cliente

See merge request jjimenez/safekat!354
2024-10-23 05:19:36 +00:00
8f2f19df1b fix mensajes internos 2024-10-23 05:14:31 +00:00
a3561d7623 add mensajeria module to presupuesto cliente edit 2024-10-23 05:14:04 +00:00
5e2d37ed26 add xdeubg 2024-10-23 05:10:33 +00:00
72b6845625 fix app.come_back button 2024-10-23 05:01:58 +00:00
9919496397 finalizado nuevo presupuesto cliente a falta de confirmar 2024-10-22 23:34:21 +02:00
33496d81ee Merge branch 'feat/tarifa-code' into 'dev/presu_cliente_v2'
Feat/tarifa code

See merge request jjimenez/safekat!351
2024-10-22 12:29:26 +00:00
a1f1151c1b error-presupuesto 2024-10-22 14:28:22 +02:00
b28b383136 Merge branch 'dev/presu_cliente_v2' into feat/tarifa-code 2024-10-22 14:22:07 +02:00
0a5f8dee68 espiral y wireo 2024-10-22 14:14:52 +02:00
7a3c11c343 Merge branch 'fix/visto-datatable-errores-presupuesto' into 'dev/presu_cliente_v2'
Fix/visto datatable errores presupuesto

See merge request jjimenez/safekat!350
2024-10-22 08:33:34 +00:00
4afb977577 Merge branch 'dev/presu_cliente_v2' of https://git.imnavajas.es/jjimenez/safekat into dev/presu_cliente_v2 2024-10-22 10:31:43 +02:00
262aa4a88f fix visto datatable errores-presupuesto 2024-10-22 10:30:47 +02:00
9f61faf67a preview casi 2024-10-22 10:29:34 +02:00
2f83526d7e comprobando presupuestos 2024-10-22 08:43:21 +02:00
e64788ddb5 remove * from label comment input form 2024-10-21 18:08:56 +00:00
1ed5c868b5 add comment and code to tarifas extra 2024-10-21 18:07:22 +00:00
ecb5abaa6d remove required from code field 2024-10-21 18:07:12 +00:00
b74495117f add code and comment to tarifas envios 2024-10-21 18:00:33 +00:00
db67b1946f add code and comment to tarifas encuadernacion 2024-10-21 17:56:39 +00:00
66a5651a30 add code and comment to tarifaacabado 2024-10-21 17:52:09 +00:00
2ff86a7743 add comment field 2024-10-21 17:46:46 +00:00
c7c9b54556 add code and comment tarifapreimpresion 2024-10-21 17:20:02 +00:00
9b964a89f6 add comment field 2024-10-21 17:06:03 +00:00
c6b1bd9292 add comment field 2024-10-21 17:05:50 +00:00
73a60466d3 add code field to models and entities 2024-10-21 16:51:19 +00:00
49e03fb7e9 fix : add breadcumbs and fix button save 2024-10-20 17:50:49 +00:00
62a3706049 cargando presu 2024-10-19 20:26:52 +02:00
1914cb01fe a punto de guardar 2024-10-19 14:32:49 +02:00
09e5149090 Mergeado
Merge branch 'dev/presu_cliente_v2' of https://git.imnavajas.es/jjimenez/safekat into dev/presu_cliente_v2
2024-10-19 13:04:05 +02:00
ac3a93370c fix : update visto errorPresupuestoForm 2024-10-19 10:00:31 +00:00
859f2a99be merge errores_presupuestos 2024-10-19 08:56:31 +00:00
4d20b4ac1c fix : contemplat que presupuesto_id es null 2024-10-19 08:54:53 +00:00
8135e635ab errores presupuesto 2024-10-19 10:38:13 +02:00
643e325e59 Merge branch 'dev/presu_cliente_v2' of https://git.imnavajas.es/jjimenez/safekat into dev/presu_cliente_v2 2024-10-19 09:42:06 +02:00
3c48d88357 cargando presu 2024-10-19 09:36:48 +02:00
15642d6e47 Merge branch 'feat/errores_presupuestos' into 'dev/presu_cliente_v2'
Feat/errores presupuestos

See merge request jjimenez/safekat!348
2024-10-19 07:34:00 +00:00
035d695780 merge changes from dev/presu_cliente_v2 2024-10-19 07:33:41 +00:00
f9b12cbcdd feat:errores presupuesto 2024-10-19 07:29:47 +00:00
f1df4559f7 error presupuestos 2024-10-18 16:00:10 +02:00
464e136025 cargando presupuesto datos generales 2024-10-18 14:33:27 +02:00
23491b2e1a add errores presupuesto 2024-10-17 23:48:16 +00:00
8a044d41fe cargando datos 2024-10-18 01:43:41 +02:00
7c9b8a0b6d guardar terminado 2024-10-17 22:22:43 +02:00
a0128d8f1e arreglado la comprobación del papelformato 2024-10-17 11:43:16 +02:00
fdf838c909 quitado rellenar presupuesto 2024-10-16 03:46:35 +02:00
b5924dceb5 falta preview resumen 2024-10-16 03:45:10 +02:00
2c5ea4d7ba Merge branch 'dev/presu_cliente_v2' of https://git.imnavajas.es/jjimenez/safekat into dev/presu_cliente_v2 2024-10-15 15:42:19 +02:00
19be8591f3 trabajando en el backend para papeles diferentes 2024-10-15 15:41:38 +02:00
a8a741f0bf trabajando en añadir las tiradas a las direcciones 2024-10-15 11:43:44 +02:00
6865d810da change title message notification dropdown 2024-10-15 05:20:35 +00:00
de9cf30aac solucionados todos los select2 en conflicto 2024-10-14 18:29:50 +02:00
29eeecb905 fix : mensaje-internos only users in group admin and beta 2024-10-14 16:20:59 +00:00
668d0d79e6 problema ruta papelformato 2024-10-14 18:19:41 +02:00
52303e9185 trabajando en el selector de cliente 2024-10-14 14:45:40 +02:00
7857e5992a test 2024-10-14 14:33:49 +02:00
f9b7de63fd Merge branch 'dev/presu_cliente_v2' of https://git.imnavajas.es/jjimenez/safekat into dev/presu_cliente_v2 2024-10-14 14:33:06 +02:00
9c3a7848f3 arreglado los select2 para que funcionen con el select2 de alvaro 2024-10-14 14:29:43 +02:00
6b49984c28 Merge branch 'main' into 'dev/presu_cliente_v2'
Main

See merge request jjimenez/safekat!347
2024-10-14 12:04:48 +00:00
44fc60372b Cogido el select2 de alvaro para problema del merge. 2024-10-14 14:03:24 +02:00
287335dc6b cogido select2 de alvaro 2024-10-14 13:58:50 +02:00
cb1d280b35 Merge branch 'bug/save_tarifas_extra' into 'main'
arreglado bug de tarifas extra importe fijo

See merge request jjimenez/safekat!345
2024-10-14 11:55:14 +00:00
c5c4a31521 arreglado bug de tarifas extra importe fijo 2024-10-14 13:54:08 +02:00
612b67883c Merge branch 'feat/mensajes-internos' into 'main'
feat : mensajes internos module

See merge request jjimenez/safekat!344
2024-10-13 23:13:14 +00:00
2012ada27f feat : mensajes internos module 2024-10-13 23:10:17 +00:00
7ad3133a15 acabando el tema de las direcciones 2024-10-14 00:50:15 +02:00
0eaac5af28 trabajando en el backend 2024-10-13 21:10:02 +02:00
e64022a7b7 falta boton add direcciones 2024-10-09 20:04:58 +02:00
a069b4109c trabajando en el componente direccion 2024-10-09 13:02:49 +02:00
92389bb5f5 Merge branch 'dev/presu_cliente_v2' of https://git.imnavajas.es/jjimenez/safekat into dev/presu_cliente_v2
mergeo de main
2024-10-08 15:15:25 +02:00
032b09f0a3 añadido direcciones 2024-10-08 15:14:12 +02:00
91f26520cb Merge branch 'main' into 'dev/presu_cliente_v2'
Main

See merge request jjimenez/safekat!343
2024-10-08 13:13:52 +00:00
dfd915e47f corregidos errores en logica 2024-10-08 14:07:29 +02:00
4045771c2d paginas para cosido multiplo de 4 2024-10-08 13:49:53 +02:00
1d3f817709 terminada la vista cubierta 2024-10-08 13:20:22 +02:00
2e2888ec26 solucionado el click de los gramajes 2024-10-07 11:31:01 +02:00
78b255fa0d problema con los custom radiobutons 2024-10-06 19:52:24 +02:00
cece606bb1 trbajando en los custom checks 2024-10-05 19:17:52 +02:00
ba3ec185ef Merge branch 'feat/config-variables-app' into 'main'
feat: add config variable menu

See merge request jjimenez/safekat!342
2024-10-02 18:37:49 +00:00
8b10aa655a feat: add config variable menu 2024-10-02 18:32:52 +00:00
13e3a69cd6 añadido coger el idioma 2024-09-30 11:06:00 +02:00
f09d5aeceb modificado calssselect.js 2024-09-30 08:53:37 +02:00
daca044cf3 modificado datosgenerales.js 2024-09-30 08:52:14 +02:00
cb982bd38a añadidos los ficheros 2024-09-30 08:38:22 +02:00
69b27f0cd8 cambiando presupuesto cliente 2024-09-29 18:07:54 +02:00
8617553dea Merge branch 'dev/chat' into 'main'
Dev/chat

See merge request jjimenez/safekat!341
2024-09-26 13:14:14 +00:00
2049cb1e02 fix:conflicts 2024-09-26 13:13:58 +00:00
bdc5b0c442 feat:chat 2024-09-26 13:11:01 +00:00
c5a5f01fa0 fix : chat modules, notifications 2024-09-26 13:10:12 +00:00
c0e90a723b Merge branch 'dev/tokens' into 'main'
Configuracion inicial para usar atentificacion via JWT (requerido tocar el...

See merge request jjimenez/safekat!340
2024-09-26 12:03:47 +00:00
130c5dad88 Configuracion inicial para usar atentificacion via JWT (requerido tocar el composer para firebase/jwt 2024-09-26 14:01:58 +02:00
bd22e89a28 Merge branch 'dev/chat' into 'main'
Dev/chat

See merge request jjimenez/safekat!339
2024-09-26 07:53:15 +00:00
d3722440c3 fix chat 2024-09-26 07:51:53 +00:00
21c1bd9bd2 fix : add chat presupuesto cliente 2024-09-26 07:50:53 +00:00
a6dbe6de07 fix : cliente show departments chats 2024-09-26 07:33:34 +00:00
68d5a7157e Merge branch 'fix/porcentaje_total_presupuesto' into 'main'
corregida division por cero

See merge request jjimenez/safekat!338
2024-09-26 07:07:14 +00:00
bf568fec92 corregida division por cero 2024-09-26 09:06:34 +02:00
5aa1aa6222 Merge branch 'dev/chat' into 'main'
feat:chat modules

See merge request jjimenez/safekat!337
2024-09-25 17:44:02 +00:00
c651db61ff feat:chat modules 2024-09-25 17:42:55 +00:00
a2f91866f7 Merge branch 'dev/chat' into 'main'
Dev/chat

See merge request jjimenez/safekat!336
2024-09-23 08:10:57 +00:00
2fc9af9db4 Merge branch 'main' into dev/chat 2024-09-23 10:04:55 +02:00
d6a95f78ee feat : add chat in facturas,presupuestos y pedidos 2024-09-23 10:00:47 +02:00
766347ad81 feat: chat module 2024-09-23 09:19:45 +02:00
70fa74333d Merge branch 'fix/porcentaje_margen_total' into 'main'
añadido porcentaje al margen total

See merge request jjimenez/safekat!334
2024-09-22 10:13:04 +00:00
0b0b928619 añadido porcentaje al margen total 2024-09-22 12:12:40 +02:00
b1eeddc5bc Merge branch 'dev/add_precio_coste_servicios' into 'main'
añadido el coste en las tablas de los servicios

See merge request jjimenez/safekat!333
2024-09-22 09:56:47 +00:00
74041042c5 añadido el coste en las tablas de los servicios 2024-09-22 11:55:52 +02:00
bfea4aa67c feat : migration and chat models 2024-09-20 11:25:34 +02:00
b25abc19d9 feat : chat migrations 2024-09-20 08:54:43 +02:00
b7cfdf87b9 Merge branch 'fix/resumen_presupuesto2' into 'main'
cogerrido error margen

See merge request jjimenez/safekat!332
2024-09-19 07:18:56 +00:00
7d26975ac3 cogerrido error margen 2024-09-19 09:18:39 +02:00
0177ca0f73 Merge branch 'fix/resumen_presupuesto' into 'main'
cambiado el margen de servicios para que coincida con las tarifas. Las horas...

See merge request jjimenez/safekat!331
2024-09-19 07:13:47 +00:00
19e3e6ce0e cambiado el margen de servicios para que coincida con las tarifas. Las horas se meten como margen impresion 2024-09-19 09:13:25 +02:00
2f93a8a02c Merge branch 'fix/importe_minimo_presu' into 'main'
modificadas tarifas en las que import minimo y precio minimo no tenian...

See merge request jjimenez/safekat!330
2024-09-19 06:58:35 +00:00
1862d4ccf9 modificadas tarifas en las que import minimo y precio minimo no tenian sentido. Revision de Presupuestos* para calcular la tarifa 2024-09-19 08:58:15 +02:00
5c72771fbe trabajando en los errores de calculo de tarifas 2024-09-18 21:01:13 +02:00
8777ce19c1 Merge branch 'fix/importe_minimo_tarifas_presu' into 'main'
solucionado el problema del precio mínimo en los presupuestosencuadernacion....

See merge request jjimenez/safekat!329
2024-09-18 12:59:48 +00:00
64288baf54 solucionado el problema del precio mínimo en los presupuestosencuadernacion. Falta el resto de presupuestos 2024-09-18 14:59:06 +02:00
f8dd56b74c feat: add chat related models 2024-09-17 23:36:31 +02:00
db3f79da29 feat: add timestamp fields 2024-09-17 23:36:10 +02:00
51dc0ca676 feat: add chat migrations 2024-09-17 23:11:35 +02:00
639230f780 Merge branch 'mod/textos_color_impresion' into 'main'
Arreglo estetico de las opciones de impresion en presupuestos de clientes

See merge request jjimenez/safekat!328
2024-09-16 20:03:21 +00:00
d3ae73a82d Arreglo estetico de las opciones de impresion en presupuestos de clientes 2024-09-16 22:02:54 +02:00
cf3cebfcfb Merge branch 'main' into dev/chat 2024-09-16 20:45:58 +02:00
9ad062ed27 Merge branch 'fix/resumen_presupuesto_admin_servicios_margen' into 'main'
cambio en como se calcula el margen de servicios en presupuestos

See merge request jjimenez/safekat!327
2024-09-16 15:50:57 +00:00
2469101541 cambio en como se calcula el margen de servicios en presupuestos 2024-09-16 17:50:20 +02:00
4a3d594347 Merge branch 'fix/id_cliente_pedidos-facturas' into 'main'
customizada vista de peiddos y facturas cliente

See merge request jjimenez/safekat!326
2024-09-16 11:59:14 +00:00
4ce8b22c5a customizada vista de peiddos y facturas cliente 2024-09-16 13:58:53 +02:00
d860d6426c Merge branch 'fix/acabados_cubierta_p_cliente' into 'main'
corregido error en pasar acabados cubierta en presupuesto cliente

See merge request jjimenez/safekat!325
2024-09-16 10:09:46 +00:00
4b2b4dfade corregido error en pasar acabados cubierta en presupuesto cliente 2024-09-16 12:09:27 +02:00
dd9b49026b Merge branch 'feat/direcciones_cliente' into 'main'
añadida la vista para modificar las direcciones de cliente

See merge request jjimenez/safekat!324
2024-09-16 08:58:02 +00:00
07cd952532 añadida la vista para modificar las direcciones de cliente 2024-09-16 10:57:38 +02:00
ca5d70b37c Merge branch 'bug/ancho_libro_solapas' into 'main'
Modificado calculo del ancho de esquema de cubierta en admin y cliente para...

See merge request jjimenez/safekat!323
2024-09-14 19:57:57 +00:00
f8497e4388 Modificado calculo del ancho de esquema de cubierta en admin y cliente para tener en cuenta los 3mm de offset de solapas 2024-09-14 21:57:33 +02:00
150a7aa158 Merge branch 'bug/boton_imprimir_presu_cliente' into 'main'
Añadido boton imprimir en presupuesto cliente, tanto en presupuestos confirmados como no

See merge request jjimenez/safekat!322
2024-09-14 07:27:11 +00:00
19e81a6c25 Añadido boton imprimir en presupuesto cliente, tanto en presupuestos confirmados como no 2024-09-14 09:26:46 +02:00
6e0c22d981 Merge branch 'bugs/varios' into 'main'
Bugs/varios

See merge request jjimenez/safekat!321
2024-09-13 19:09:29 +00:00
2239d39919 Quitado menu vistas de impresion, maquetacion etc a clientes, solo ADMIN 2024-09-13 21:09:08 +02:00
d01fbbfe4b Añadida visualizacion de menus en roles cliente (admin/editor 2024-09-13 20:55:25 +02:00
9e57aef8bc Merge branch 'fix/servicios_defecto' into 'main'
solucionado el problema de calcular serv defecto en presupuestador admin....

See merge request jjimenez/safekat!320
2024-09-13 17:53:29 +00:00
6a307e9fe3 solucionado el problema de calcular serv defecto en presupuestador admin. Quitada merma para calcular precio servicios en presupuestador admin 2024-09-13 19:52:36 +02:00
26056082fa Merge branch 'bug/arreglar_vistas' into 'main'
Arreglado bug del direccionamiento en vista de clientes al listados de...

See merge request jjimenez/safekat!319
2024-09-13 13:11:15 +00:00
9cc8c40434 Añadido menu --Direcciones-- dentro de perfil clientes (admin y editor 2024-09-13 15:10:10 +02:00
99bdaf7a24 Arreglado bug del direccionamiento en vista de clientes al listados de clientes en lugar de al perfil 2024-09-13 14:54:55 +02:00
4614db53cf Merge branch 'main' into dev/chat 2024-09-07 20:30:51 +02:00
36a627b737 Merge branch 'fix/xml-upload' into 'main'
fix:pedido xml folder

See merge request jjimenez/safekat!318
2024-09-05 12:23:34 +00:00
6bddf1b997 fix:pedido xml folder 2024-09-05 12:38:25 +02:00
54731f65b2 Merge branch 'fix/error-pedido-xml' into 'main'
fix : remote dir for pedido files

See merge request jjimenez/safekat!317
2024-09-04 13:31:40 +00:00
333d9a8c09 fix : remote dir for pedido files 2024-09-04 15:30:08 +02:00
69917caed3 Merge branch 'fix/error-pedido-xml' into 'main'
fix : error naming HIDRIVE PORT

See merge request jjimenez/safekat!316
2024-09-03 10:50:13 +00:00
adb1335c17 fix : error naming HIDRIVE PORT 2024-09-03 12:48:58 +02:00
357966cf69 Merge branch 'feat/xml-pedido' into 'main'
Feat/xml pedido

See merge request jjimenez/safekat!315
2024-09-03 10:16:53 +00:00
7097ef72cc Merge branch 'main' into feat/xml-pedido 2024-09-02 23:36:42 +02:00
93714ac955 feat : add generate XML functionality in crearPedido 2024-09-02 23:33:48 +02:00
fe4fdb8607 feat: generateXML finished 2024-09-02 23:33:05 +02:00
6e41e73997 feat : add method getPedidoPresupuestoTipoImpresion 2024-09-02 23:32:11 +02:00
ebe649c7d8 feat : add method findByPresupuesto 2024-09-02 23:31:50 +02:00
68f2ccb1c5 feat : add class library for sftp 2024-09-02 23:31:20 +02:00
1d7f06b018 feat : after upload presupuesto file send to sftp server 2024-09-02 23:30:59 +02:00
295fd88201 feat: add class config for SFTP xml export 2024-09-02 23:29:14 +02:00
173b6d5a5d feat: add config class for XML export to sftp 2024-09-02 23:28:54 +02:00
23a34d10b0 delete 2024-09-02 23:28:03 +02:00
121708b71c add package phpseclib/phpseclib for stfp 2024-09-02 23:27:54 +02:00
403c742bf3 Merge branch 'mod/albaranes_del_confirmacion' into 'main'
añadida confirmación para borrar albaranes

See merge request jjimenez/safekat!313
2024-08-29 12:06:42 +00:00
8653971dd2 añadida confirmación para borrar albaranes 2024-08-29 14:05:17 +02:00
4e40d2e8f4 Merge branch 'mod/quitar_pais_req_presupuestos' into 'main'
quitado pais como campo obligatorio para nuevo presupuesto administrador

See merge request jjimenez/safekat!312
2024-08-29 09:56:18 +00:00
1f09a1c603 quitado pais como campo obligatorio para nuevo presupuesto administrador 2024-08-29 11:55:58 +02:00
1afa6bc520 Merge branch 'feat/proveedor_tarifas_manipulado' into 'main'
Feat/proveedor tarifas manipulado

See merge request jjimenez/safekat!311
2024-08-29 07:33:28 +00:00
e1a72e7874 modificado lo necesario para presupuesto cliente 2024-08-29 09:32:58 +02:00
b908c5b5bf modificado presupuesto comercial 2024-08-29 09:27:05 +02:00
43fdafc099 upload xml to server by ftp 2024-08-29 01:04:44 +02:00
3a0011b49a delete FTPService, moved to Libraries 2024-08-29 01:04:10 +02:00
c8335b5740 add SafekatFtpClient Library 2024-08-29 01:03:50 +02:00
8e5d208bbf add general_helper, deleted by error 2024-08-29 01:03:29 +02:00
01cc74ed60 delete ftp method 2024-08-29 01:03:00 +02:00
c3248cd3ec add FTP Config file 2024-08-29 01:02:33 +02:00
251268fb24 add Libraries path 2024-08-29 01:02:15 +02:00
eb4ea31cef add php ftp lib 2024-08-28 22:28:49 +02:00
da379a7af9 ftp service 2024-08-28 22:28:34 +02:00
f278f821b6 trabajando en presupuesto comercial 2024-08-28 18:47:53 +02:00
c8106eafa1 Merge branch 'main' into feat/xml-pedido 2024-08-28 07:56:12 +02:00
e2289030db arraglado fallo en buscador cuando se limpia, orden precios y replace de , a . 2024-08-27 19:04:18 +02:00
49314e166d terminadas modificaciones en tarifas acabado 2024-08-27 14:31:00 +02:00
1e347cc7d6 Merge branch 'mod/tarifas_cosido' into 'main'
Mod/tarifas cosido

See merge request jjimenez/safekat!310
2024-08-24 09:38:56 +00:00
597330adb7 insertado lo de los cuadernillos en presupuesto cliente 2024-08-24 11:38:22 +02:00
8c91be99c3 Merge branch 'main' into 'mod/tarifas_cosido'
Main

See merge request jjimenez/safekat!309
2024-08-23 11:45:11 +00:00
b9f28c5ee8 paginas por cuadernillo añadido a presupuesto comercial 2024-08-23 13:44:24 +02:00
d702b5aa92 Merge branch 'mod/titulos_tarifas' into 'main'
Cambiados textos de encabezados de tabla

See merge request jjimenez/safekat!308
2024-08-22 19:26:18 +00:00
21a955d4d2 Cambiados textos de encabezados de tabla 2024-08-22 21:22:06 +02:00
50334186f2 Merge branch 'bug/tiempo_t_enc_presupuestos' into 'main'
arreglado que no se mostraba el tiempo cuando se añadian los servicios por defecto

See merge request jjimenez/safekat!307
2024-08-20 11:23:38 +00:00
996cafeb65 arreglado que no se mostraba el tiempo cuando se añadian los servicios por defecto 2024-08-20 13:23:06 +02:00
ee45baec3b xml file generation 2024-08-19 08:23:39 +02:00
2734a94983 Merge branch 'pdf_factura' into 'main'
Pdf factura

See merge request jjimenez/safekat!306
2024-08-17 17:17:36 +00:00
242feffe7f Generados botones de exportar a excel en listado facturas (no logica 2024-08-17 19:15:09 +02:00
d8eefcf1b7 Implementados botones de imprimir factura y exportar lineas pedido 2024-08-17 18:37:13 +02:00
1170852209 Fix bug del id de factura 2024-08-16 16:01:43 +02:00
ec8288e6e4 Preparada factura en PDF 2024-08-16 15:44:45 +02:00
144faa9363 Merge branch 'main' into 'dev/chat'
Main

See merge request jjimenez/safekat!305
2024-08-16 08:51:39 +00:00
5169174e57 git push 2024-08-12 12:16:04 +02:00
070ffb934d xml envios 2024-08-12 10:59:53 +02:00
5648f43413 xml service 2024-08-12 08:02:14 +02:00
a91685747c Merge branch 'main' into feat/pedidos-export 2024-08-10 21:11:10 +02:00
665dc2d86d xml service 2024-08-10 21:09:56 +02:00
a8f8c4851a Merge branch 'dev/excel_pdf_facturas' into 'main'
Dev/excel pdf facturas

See merge request jjimenez/safekat!304
2024-08-08 12:50:44 +00:00
1ad6fe93b7 terminado tirada flexible 2024-08-08 14:49:37 +02:00
b95930dcc2 falta boton excedentes 2024-08-07 22:01:00 +02:00
d39a8a4e0b Merge branch 'main' into 'dev/excel_pdf_facturas'
Main

See merge request jjimenez/safekat!303
2024-08-06 07:18:46 +00:00
42d21c9ca1 Merge branch 'feat/facturas_tiradas_flex' into 'main'
Feat/facturas tiradas flex

See merge request jjimenez/safekat!302
2024-08-06 07:18:12 +00:00
74b722903f Merge branch 'main' into 'feat/facturas_tiradas_flex'
Main

See merge request jjimenez/safekat!301
2024-08-06 07:17:43 +00:00
c5867d25b5 Merge branch 'dev/totalizadores_pedidos' into 'main'
Dev/totalizadores pedidos

See merge request jjimenez/safekat!300
2024-08-05 19:25:40 +00:00
8ea0ab13c0 totalizadores implementados 2024-08-05 21:25:16 +02:00
4255b74f33 filtros columna en pedidos hecho 2024-08-05 17:59:00 +02:00
3d6aa77993 Merge branch 'main' into 'feat/facturas_tiradas_flex'
Main

See merge request jjimenez/safekat!298
2024-08-05 11:38:18 +00:00
d4373a401f Arreglando filtrado 2024-08-05 13:36:26 +02:00
7318e4bd7c Actualizacion automatica: 2024-07-31 22:54:20 2024-07-31 22:54:20 +02:00
d193ba0b5f Merge branch 'mod/formas_pago' into 'main'
Añadido CRUD para formas de pago

See merge request jjimenez/safekat!297
2024-07-31 20:19:20 +00:00
3f1165f323 Añadido CRUD para formas de pago 2024-07-31 22:18:53 +02:00
f3ad5d8b06 Merge branch 'main' into 'dev/chat'
Main

See merge request jjimenez/safekat!296
2024-07-31 18:41:45 +00:00
c5e4a70ec0 Actualizacion automatica: 2024-07-31 20:40:31 2024-07-31 20:40:33 +02:00
17aa1cf51e Merge branch 'feat/seccion_facturas_en_pedidos' into 'main'
finalizado el ver facturas en pedidos

See merge request jjimenez/safekat!295
2024-07-30 17:07:57 +00:00
6dd6622b35 finalizado el ver facturas en pedidos 2024-07-30 19:07:03 +02:00
8f2e99863d Merge branch 'feat/edit_factura' into 'main'
Feat/edit factura

See merge request jjimenez/safekat!293
2024-07-30 11:32:55 +00:00
38d3592461 edicion de facturas terminada a falta de tirada flexible 2024-07-30 13:30:33 +02:00
7813cf744b Arreglado bug para que salga en el menu configuracion papel generico y de impresion 2024-07-24 13:16:09 +02:00
1c0be4f96f aaa 2024-07-18 14:29:18 +02:00
4c33167764 casi terminado 2024-07-17 14:51:47 +02:00
99e9bf51a6 Merge branch 'main' into 'feat/edit_factura'
Main

See merge request jjimenez/safekat!292
2024-07-17 07:55:06 +00:00
5f03a3dfda Merge branch 'mod/user_pwd' into 'main'
Añadido campo de verficacion de contraseña y campo de notas

See merge request jjimenez/safekat!291
2024-07-16 20:52:42 +00:00
0b6ce06c96 Añadido campo de verficacion de contraseña y campo de notas 2024-07-16 22:52:05 +02:00
67fbc2589f trabajando en pagos (datepicker) 2024-07-16 22:11:21 +02:00
57688a5310 Merge branch 'feat/user_pwd' into 'main'
Feat/user pwd

See merge request jjimenez/safekat!290
2024-07-16 07:27:23 +00:00
944f92f3b0 Terminada gestion de contraseñas de usuarios en perfil y zona admin 2024-07-16 09:26:03 +02:00
ad266dd14f Merge branch 'main' into 'feat/user_pwd'
Main

See merge request jjimenez/safekat!289
2024-07-16 06:34:42 +00:00
722748aba4 Merge branch 'mod/profile_pwd' into 'main'
Añadido cambio de contraseña en perfil de usuario (mejorar UI

See merge request jjimenez/safekat!288
2024-07-15 21:20:37 +00:00
ad26a70aed Añadido cambio de contraseña en perfil de usuario (mejorar UI 2024-07-15 23:20:00 +02:00
159c4a6ce1 añadido opcion de crear contraseña en interfaz de administrador 2024-07-15 15:26:53 +02:00
ce7ba82bda Merge branch 'feat/add_edit_factura' into 'main'
Feat/add edit factura

See merge request jjimenez/safekat!286
2024-07-15 09:24:15 +00:00
955fa05666 commit para mergear antes de ramas nuevas 2024-07-15 11:23:13 +02:00
e18368e647 working 2024-07-10 12:28:48 +02:00
b6420b7b8a trabajando boton ver pedido 2024-07-10 00:25:26 +02:00
078205b552 añadiendo lineas 2024-07-09 20:25:32 +02:00
2b7b12fde7 añadiendo linea factura 2024-07-09 15:21:20 +02:00
5605a88846 editar factura 2024-07-07 19:25:39 +02:00
f46a03e66d avances de hoy 2024-07-06 22:44:29 +02:00
26f3057bbe Merge branch 'main' into 'dev/chat'
Main

See merge request jjimenez/safekat!284
2024-07-06 15:54:04 +00:00
c7d8d0c5cc Merge branch 'feat/entidades_modelos_facturas' into 'main'
Feat/entidades modelos facturas

See merge request jjimenez/safekat!283
2024-07-06 15:20:35 +00:00
a06efc5736 Merge branch 'main' into 'feat/entidades_modelos_facturas'
Instalada libreria de PHP para Excel y hecho primer ejemplo de creacion de...

See merge request jjimenez/safekat!282
2024-07-06 15:12:47 +00:00
35e4e8ef95 Configuraciones iniciales del sistema de mensajeria 2024-07-02 21:45:32 +02:00
95ca383215 Merge branch 'dev/excel' into 'main'
Instalada libreria de PHP para Excel y hecho primer ejemplo de creacion de...

See merge request jjimenez/safekat!281
2024-07-02 15:43:46 +00:00
d1495534e0 Instalada libreria de PHP para Excel y hecho primer ejemplo de creacion de excel. Esta hecho el excel de giros de SK (encabezados + dummy data 2024-07-02 14:07:01 +02:00
514711c5c2 Merge branch 'bud/tarifas_extras' into 'main'
Bud/tarifas extras

See merge request jjimenez/safekat!280
2024-07-02 11:34:05 +00:00
c8e3dfd873 Añadidos permisos a tarifas, salvo metodo delete 2024-07-02 10:40:17 +02:00
108899c796 Actualizacion automatica: 2024-07-02 01:01:40 2024-07-02 01:01:42 +02:00
1fb9977094 a 2024-06-28 20:45:41 +02:00
ca901b14f3 listado de facturas terminado. trabajando en añadir 2024-06-27 20:16:30 +02:00
fcaacfbb5d hechos modelos y entidades para facturas 2024-06-25 20:08:17 +02:00
2d0732c218 Añadidas tarifas extras, trabajando en permisos de tarifas 2024-06-18 22:33:07 +02:00
20702a47f8 Merge branch 'feat/presu_cliente_pass_id' into 'main'
Feat/presu cliente pass

See merge request jjimenez/safekat!279
2024-06-18 15:47:57 +00:00
5e876f07fb terminado y arreglado otros bugs 2024-06-18 17:47:21 +02:00
e235165499 falta comprobar que se puede cambiar el tipo de presupuesto 2024-06-18 15:26:15 +02:00
c476c9a938 Merge branch 'dev/usuarios_clientes' into 'main'
añadido cliente id a users

See merge request jjimenez/safekat!278
2024-06-18 11:19:24 +00:00
1fa4e1cd9c añadido cliente id a users 2024-06-18 13:18:25 +02:00
52633ef695 Merge branch 'dev/albaranes_pdf_2' into 'main'
Implementada la logica para la creacion de albaranes en PDF

See merge request jjimenez/safekat!277
2024-06-16 20:54:18 +00:00
2147452125 Implementada la logica para la creacion de albaranes en PDF 2024-06-16 22:53:52 +02:00
57194b5dd3 Merge branch 'feat/confirmar_presupuesto_admin' into 'main'
ya se puede confirmar

See merge request jjimenez/safekat!276
2024-06-16 16:04:33 +00:00
8335c458ed ya se puede confirmar 2024-06-16 18:02:50 +02:00
aed64581c9 Merge branch 'dev/pdf_albaranes' into 'main'
Dev/pdf albaranes

See merge request jjimenez/safekat!275
2024-06-16 07:19:00 +00:00
e6e46c84e7 Añadida impresion dummy pdf 2024-06-16 09:18:33 +02:00
4686e5040e Arreglado archivo de rutas 2024-06-16 08:35:30 +02:00
953b07497d Merge branch 'main' into 'dev/pdf_albaranes'
Main

See merge request jjimenez/safekat!274
2024-06-16 06:30:06 +00:00
17e9f8e52f Arreglar conflictos locales del Routes.php 2024-06-16 08:29:13 +02:00
31565ff6dd Merge branch 'dev/pedidos_v1' into 'main'
Dev/pedidos v1

See merge request jjimenez/safekat!273
2024-06-16 00:10:32 +00:00
2f1f6f9631 terminado 2024-06-16 02:10:01 +02:00
3171c32283 faltan las fechas 2024-06-16 01:47:34 +02:00
4076fff844 haciendo los eventos 2024-06-15 19:42:36 +02:00
87e6b029e2 falta mostrar precios albaran 2024-06-15 11:14:02 +02:00
3e0443927c trabajando 2024-06-14 15:04:41 +02:00
ef7cbf853b Merge branch 'main' into 'dev/pedidos_v1'
Main

See merge request jjimenez/safekat!272
2024-06-14 07:11:10 +00:00
c9d8875392 trabajando en pedidos 3 2024-06-13 23:53:20 +02:00
d7de7b0778 Primera version del pdf de albaran 2024-06-13 22:45:49 +02:00
40279095a3 Merge branch 'dev/exponer_tablas' into 'main'
Dev/exponer tablas

See merge request jjimenez/safekat!271
2024-06-13 19:05:48 +00:00
324d4774f3 Arreglado bug de validaciones 2024-06-13 21:05:15 +02:00
405afd0cf1 Terminada exposicion de tablas ubicacion y series 2024-06-13 21:00:33 +02:00
b1734e169b trabajando en el form 2024-06-13 19:23:50 +02:00
02ba5d75d1 Añadidos ubicaciones y series de facturas 2024-06-13 18:58:54 +02:00
e491172b28 cambiado el obtener la lista a pedidos_linea 2024-06-11 11:11:02 +02:00
3f876a0b81 Merge branch 'dev/pedidos_v1' of https://git.imnavajas.es/jjimenez/safekat into dev/pedidos_v1 2024-06-11 11:04:33 +02:00
8aa7751060 trabajando en el form de cliente 2024-06-11 11:02:36 +02:00
22deda2aea Merge branch 'main' into 'dev/pedidos_v1'
Main

See merge request jjimenez/safekat!270
2024-06-11 06:54:06 +00:00
2143660cf6 añadidos entidades y modelos. Hecha lista de todos 2024-06-11 08:53:20 +02:00
e5004e762a Merge branch 'dev/vista_cliente' into 'main'
Configurada vista de clientes

See merge request jjimenez/safekat!269
2024-06-07 15:22:57 +00:00
720346e8e3 Configurada vista de clientes 2024-06-07 17:22:25 +02:00
bc85572610 Merge branch 'main' into 'dev/pedidos_v1'
Main

See merge request jjimenez/safekat!268
2024-06-07 14:49:05 +00:00
8815319577 Merge branch 'bug/filtros_cabecera_presu' into 'main'
ya se filtra bien

See merge request jjimenez/safekat!267
2024-06-07 14:47:54 +00:00
38abbe22a7 ya se filtra bien 2024-06-07 16:47:11 +02:00
aac17468c3 Merge branch 'mod/presu_cliente' into 'main'
Mod/presu cliente

See merge request jjimenez/safekat!266
2024-06-07 13:36:18 +00:00
94cf67a47f Arreglado bug del lomo cubierta 2024-06-07 13:10:32 +02:00
120e46f994 Falta lomo 2024-06-06 19:55:51 +02:00
af6780b36c Merge branch 'bug/siguiente_presu_cliente' into 'main'
Bug/siguiente presu cliente

See merge request jjimenez/safekat!265
2024-06-06 10:22:56 +00:00
d2f5b77f16 Corregido bug 2024-06-06 12:22:32 +02:00
db3ada3830 modificando las cosas 2024-06-06 12:00:44 +02:00
552ef89cd7 Merge branch 'main' into 'dev/pedidos_v1'
Main

See merge request jjimenez/safekat!264
2024-06-05 14:13:23 +00:00
5ee6a2c97e Merge branch 'dev/anadir_ficheros_presu' into 'main'
Dev/anadir ficheros presu

See merge request jjimenez/safekat!263
2024-06-05 09:47:51 +00:00
dd65b1fd88 Merge branch 'main' into 'dev/anadir_ficheros_presu'
Main

See merge request jjimenez/safekat!262
2024-06-05 09:47:04 +00:00
96a1faf97a Delete xdebug.log 2024-06-05 09:46:39 +00:00
673a903c75 Delete xdebug.log 2024-06-05 09:43:43 +00:00
c588936f00 modificado gitignore 2024-06-05 11:38:55 +02:00
1453140005 terminado dropzone 2024-06-05 11:35:29 +02:00
7e68ec5948 Añadido clase intranet para exponer archivos detras del root_path 2024-06-04 23:10:10 +02:00
7e878c00b2 falta cargar thumbail y preview 2024-06-04 20:05:12 +02:00
51d4f988cc queda preview y cargar ficheros del server 2024-06-04 15:16:32 +02:00
78126f6549 falta backend meter en bbdd y borrar antiguos 2024-06-03 17:34:38 +02:00
8833999e8d trabajando en el dropzone 2 2024-06-03 15:33:51 +02:00
b4bddaea6a Actualizacion automatica: 2024-06-03 13:40:32 2024-06-03 13:40:34 +02:00
9ee559fd2f Merge branch 'dev/clientes_lista_soporte' into 'main'
añadida busqueda correcta de persona de soporte en clientes

See merge request jjimenez/safekat!260
2024-06-03 10:15:32 +00:00
3151d95ec2 añadida busqueda correcta de persona de soporte en clientes 2024-06-03 12:14:52 +02:00
234006783c trabajando en dropzone 2024-06-03 12:01:40 +02:00
1146929beb Merge branch 'bug/cliente_error' into 'main'
resuelto problema de la tabla de precios y añadida lista a los comerciales

See merge request jjimenez/safekat!259
2024-06-02 17:56:21 +00:00
1d969e5c9f resuelto problema de la tabla de precios y añadida lista a los comerciales 2024-06-02 19:55:38 +02:00
ce753ef926 Merge branch 'bug/new_user' into 'main'
ya se pueden añadir usuarios

See merge request jjimenez/safekat!258
2024-06-02 17:12:16 +00:00
42b213922c ya se pueden añadir usuarios 2024-06-02 19:11:30 +02:00
3119005688 Merge branch 'bug/tamanio_personalizado' into 'main'
arreglado bug de tamanio personalizado y presupuesto solo a color

See merge request jjimenez/safekat!257
2024-05-23 14:33:25 +00:00
84e1bc8d27 arreglado bug de tamanio personalizado y presupuesto solo a color 2024-05-23 16:32:25 +02:00
0b5741de7c Merge branch 'func/copiar_tarifas_encuadernacion' into 'main'
creada funcion en controlador de Test para clonar tarifas de encuadernacion existentes

See merge request jjimenez/safekat!256
2024-05-23 13:42:25 +00:00
56c828f387 creada funcion en controlador de Test para clonar tarifas de encuadernacion existentes 2024-05-23 15:41:10 +02:00
ef2649c3fd Merge branch 'bug/guardas_cliente' into 'main'
arraglados algunos bugs

See merge request jjimenez/safekat!255
2024-05-22 15:15:47 +00:00
9e0ff7501e arraglados algunos bugs 2024-05-22 17:14:49 +02:00
9a98ffd6e6 Merge branch 'bug/add-presu-cliente' into 'main'
Bug/add presu cliente

See merge request jjimenez/safekat!254
2024-05-22 14:30:59 +00:00
667a2ab679 reparados bugs 2024-05-22 16:30:05 +02:00
e4f6295597 reparando bugs 2024-05-22 16:22:55 +02:00
1063c95fc0 Merge branch 'dev/editar_presu_cliente' into 'main'
Dev/editar presu cliente

See merge request jjimenez/safekat!253
2024-05-22 13:07:15 +00:00
b036e2ce32 adaptado el preview a presupuestos confirmados 2024-05-22 15:06:19 +02:00
a3962da518 Merge branch 'main' into 'dev/editar_presu_cliente'
Main

See merge request jjimenez/safekat!252
2024-05-22 11:26:57 +00:00
e2c8cb0f7c arreglando resumen 2024-05-22 13:26:36 +02:00
3d80216780 terminado editar cliente 2024-05-22 13:22:14 +02:00
d205fb7c6b Merge branch 'dev/preview' into 'main'
Dev/preview

See merge request jjimenez/safekat!251
2024-05-22 09:39:12 +00:00
7ad551238d Terminado previews listos para verificar por cliente 2024-05-22 11:28:56 +02:00
889ad57adc Actualizacion automatica: 2024-05-22 09:24:56 2024-05-22 09:24:57 +02:00
44c5595173 terminado a falta del resumen 2024-05-21 20:43:47 +02:00
77c284c9b4 finalizando el edit 2024-05-21 17:33:10 +02:00
2364edb684 Actualizacion automatica: 2024-05-21 15:49:10 2024-05-21 15:49:11 +02:00
3cb756a42f Añadiendo preview thumbnail y detalles 2024-05-20 22:45:11 +02:00
8b1114dc7f hay que corregir el checkeo de lineas con las paginas 2024-05-20 21:20:09 +02:00
75df199c5d trabajando en edit 2024-05-20 16:18:54 +02:00
5d80eacb3f Merge branch 'dev/default_permisos' into 'main'
Merge branch 'main' into 'dev/default_permisos'

See merge request jjimenez/safekat!249
2024-05-19 18:37:40 +00:00
6d31cbe33e Merge branch 'main' into 'dev/default_permisos'
Main

See merge request jjimenez/safekat!248
2024-05-19 18:36:18 +00:00
0ac3414a95 Merge branch 'dev/añadir_palets_cajas' into 'main'
Dev/añadir palets cajas

See merge request jjimenez/safekat!247
2024-05-19 18:34:52 +00:00
e3e21d2b1e trabajando en editar y rellenar el presupuesto 2024-05-19 20:33:20 +02:00
79d89b9718 trabajando en el editar 2024-05-18 21:13:58 +02:00
1741d6cd60 terminado añadir presupuesto a falta de volver en el botón 2024-05-18 12:07:30 +02:00
6c748a8a2d haciendo pruebas 2024-05-18 10:19:25 +02:00
efa327fb48 Merge branch 'bug/presupuesto_cliente' into 'dev/añadir_palets_cajas'
Bug/presupuesto cliente

See merge request jjimenez/safekat!246
2024-05-17 09:27:48 +00:00
b110fd063c falta guardar tiradas 2024-05-16 14:52:18 +02:00
fdb1fe77db trabajando en guardar presupuesto 2024-05-14 17:39:28 +02:00
0c78f0af7a añadida entrega a pie de calle y lomo_cubierta 2024-05-13 14:00:43 +02:00
4a12aad3dc Merge branch 'bug/presupuesto_cliente' into 'dev/añadir_palets_cajas'
Integrando preview de cliente

See merge request jjimenez/safekat!243
2024-05-13 08:22:28 +00:00
745474a37f cambio en dim máximo cubierta y expuesto lomo 2024-05-13 10:22:03 +02:00
438 changed files with 31677 additions and 526199 deletions

3
.gitignore vendored
View File

@ -1,4 +1,5 @@
ci4/.env ci4/.env
.vscode/ .vscode/
./xdebug.log xdebug.log
xdebug.*

View File

@ -1,92 +0,0 @@
# safekat
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://git.imnavajas.es/jjimenez/safekat.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://git.imnavajas.es/jjimenez/safekat/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

View File

@ -1,133 +0,0 @@
Quitar Oauth
---------------------------------------------
Quitar packete con composer que se usa en la Oauth
composer remove hybridauth/hybridauth
Tablas en la BBDD.
wg_user_oauth
wg_settings_oauth
Se hace migración (hay que añadir el controlador Migrate a whiteListController)
Modelos
UserOauthModel.php
SettingsOauthModel.php
Controllers
Oauth.php
Realizar busqueda de UserOauthModel que está en varios Controllers
Buscar la variable que crea en cada controlador y ver para que la usa
Igual que la acción anterior pero con SettingsOauthModel
Está en el controlador Settings.php. Buscar la variable que crea y borrarla
Eliminar Views\themes\backend\focus2\form\settings\oauth.php
En Views\themes\backend\focus2\main\menu.
Quitar la línea php que invoca a la configuración de Oauth (site_url("settings/oauth"))
En Views\themes\frontend\tivo\main\menu.php
Quitar la línea php que invoca a la configuración de Oauth (site_url("settings/oauth"))
En en controlador Settings.php
Quitar las funciones oauth() y oauth_store()
En los idiomas quitar la key dashboard_chart_auth
En la vista quitar la carta de Solcial autenthification
<div class="col-lg-4">
<div class="card">
<div class="card-header">
<h4 class="card-title"><?=lang("App.dashboard_chart_auth")?></h4>
</div>
<div class="card-body">
<div class="row">
<div class="col-lg-12" id="ct-icon-chart"></div>
</div>
<div class="row">
<div class="col-lg-12"><div class="ct-pie-chart"></div></div>
</div>
</div>
</div>
</div>
Quitar los SMS
--------------------------------------------
Quitar packete con composer que se usa en la Oauth
twilio/sdk
Dentro de Controllers\Integration.php
Eliminar sendSMS (public y private)
Se hace migración de la BBDD
Del controlador Cron.php se elimina
la accion // Cron Notification SMS
la función test()
Del controlador Ajax.php
linea 368, quitar is_send_sms de la lista
linea 399, eliminar "is_send_sms"=>$record['is_send_sms'],
Del controlador Login.php eliminar
//Notification SMS User Welcome
//SMS Account Confirmation
Dentro de //Notification New Register, las dos líneas is_send_sms y send_sms_notification
linea 455 if($settings['send_sms_register']??false){ quitar if completo
Del controlador Notification.php
linea 117 , 148, 150
Del controlador Settings.php
linea 106, 109
De los idiomas, quitar los registros
settings_field_send_sms_register
notification_field_send_sms
Del modelo NotificationModel.php
Quitar los fields is_send_sms y send_sms_notification
Del modelo SettingsModel.php
Quitar los fields send_sms_register y send_sms_welcome
sms_gateway, sms_account_id, ,sms_auth_token, sms_info_add, sms_confirmation
De la vista Views\themes\backend\focus2\form\notification\form quitar
<div class="col-md-3">
<div class="form-group">
<label class="text-dark"><?=lang("App.notification_field_send_sms")?></label>
<div class="custom-control custom-switch">
<input type="checkbox" id="send_sms_notification" name="send_sms_notification" class="custom-control-input" <?= $obj['send_sms_notification']??false ? 'checked' : ''?>>
<label for="send_sms_notification" class="custom-control-label"><?=lang("App.notification_field_send_label")?></label>
</div>
</div>
</div>
De la vista Views\themes\backend\focus2\form\notification\index.php quitar de la linea 129 { data: 'is_send_sms' },
De la vista Views\themes\backend\focus2\form\settings\index.php quitar los siguientes bloques
<div class="col-lg-3">
<div class="form-group">
<label class="text-dark"><?=lang("App.settings_field_send_welcome_message_sms")?></label>
<div class="custom-control custom-switch">
<input type="checkbox" id="send_sms_welcome" name="send_sms_welcome" class="custom-control-input" <?= $obj['send_sms_welcome']??false ? 'checked' : ''?>>
<label for="send_sms_welcome" class="custom-control-label"><?=lang("App.global_activate")?></label>
</div>
</div>
</div>
y
<div class="col-lg-3">
<div class="form-group">
<label class="text-dark"><?=lang("App.settings_field_send_sms_register")?></label>
<div class="custom-control custom-switch">
<input type="checkbox" id="send_sms_register" name="send_sms_register" class="custom-control-input" <?= $obj['send_sms_register']??false ? 'checked' : ''?>>
<label for="send_sms_register" class="custom-control-label"><?=lang("App.global_activate")?></label>
</div>
</div>
</div>
En el controlador Ajax.php quitar if($records[$key]['sms_confirmed'] == 1)
En el controlador Login.php quitar
bloque // Check sms confirmed
if($confirmation['type'] == 'sms')
En el controlador Settings.php quitar
linea 104
case 'sms;
En el controlador User.php quitar linea 217 y 236
Del modelo UserModel.php quitar el campo sms_confirmed
En los idiomas buscar la key sms
En la vista Views\themes\backend\focus2\form\notification\index.php quitar linea 49
En la vista Views\themes\backend\focus2\form\settings\index.php quitar
linea 37
bloque en linea 298
linea 355
bloque en linea 679
linea 1033
En la vista Views\themes\backend\focus2\form\settings\template.php
bloque linea 87 hasta 131
En la vista Views\themes\backend\focus2\form\user\form.php
bloque linea 104 hasta 113
linea 210
Renombrar tablas a auth_ en lugar de wg_
-------------------------------------------------
La tabla wg_migrations hay que modificarla a mano.
En .env quitar el prefijo: database.default.DBPrefix =
En todos los modelos añadir auth_ al principio del nombre de la tabla

View File

@ -13,7 +13,9 @@ declare(strict_types=1);
namespace Config; namespace Config;
use App\Entities\Usuarios\UsersEntity;
use App\Models\UserModel; use App\Models\UserModel;
use CodeIgniter\Shield\Authentication\Authenticators\JWT;
use CodeIgniter\Shield\Authentication\Passwords\ValidationRules; use CodeIgniter\Shield\Authentication\Passwords\ValidationRules;
use CodeIgniter\Shield\Config\Auth as ShieldAuth; use CodeIgniter\Shield\Config\Auth as ShieldAuth;
use CodeIgniter\Shield\Authentication\Actions\ActionInterface; use CodeIgniter\Shield\Authentication\Actions\ActionInterface;
@ -117,7 +119,7 @@ class Auth extends ShieldAuth
'tokens' => AccessTokens::class, 'tokens' => AccessTokens::class,
'session' => Session::class, 'session' => Session::class,
'hmac' => HmacSha256::class, 'hmac' => HmacSha256::class,
// 'jwt' => JWT::class, 'jwt' => JWT::class,
]; ];
/** /**
@ -144,7 +146,7 @@ class Auth extends ShieldAuth
'session', 'session',
'tokens', 'tokens',
'hmac', 'hmac',
// 'jwt', 'jwt',
]; ];
/** /**

View File

@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter Shield.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Config;
use CodeIgniter\Shield\Config\AuthJWT as ShieldAuthJWT;
/**
* JWT Authenticator Configuration
*/
class AuthJWT extends ShieldAuthJWT
{
/**
* --------------------------------------------------------------------
* Name of Authenticator Header
* --------------------------------------------------------------------
* The name of Header that the Authorization token should be found.
* According to the specs, this should be `Authorization`, but rare
* circumstances might need a different header.
*/
public string $authenticatorHeader = 'Authorization';
/**
* --------------------------------------------------------------------
* The Default Payload Items
* --------------------------------------------------------------------
* All JWTs will have these claims in the payload.
*
* @var array<string, string>
*/
public array $defaultClaims = [
'iss' => 'https://safekat.com',
];
/**
* --------------------------------------------------------------------
* The Keys
* --------------------------------------------------------------------
* The key of the array is the key group name.
* The first key of the group is used for signing.
*
* @var array<string, array<int, array<string, string>>>
* @phpstan-var array<string, list<array<string, string>>>
*/
public array $keys = [
'default' => [
// Symmetric Key
[
'kid' => '', // Key ID. Optional if you have only one key.
'alg' => 'HS256', // algorithm.
// Set secret random string. Needs at least 256 bits for HS256 algorithm.
// E.g., $ php -r 'echo base64_encode(random_bytes(32));'
'secret' => 'ZAfosrIVWDaKEhBhicTKCpW8T5ZxC3GYAxFgCkUQjlU=',
],
// Asymmetric Key
// [
// 'kid' => '', // Key ID. Optional if you have only one key.
// 'alg' => 'RS256', // algorithm.
// 'public' => '', // Public Key
// 'private' => '', // Private Key
// 'passphrase' => '' // Passphrase
// ],
],
];
/**
* --------------------------------------------------------------------
* Time To Live (in seconds)
* --------------------------------------------------------------------
* Specifies the amount of time, in seconds, that a token is valid.
*/
public int $timeToLive = HOUR;
/**
* --------------------------------------------------------------------
* Record Login Attempts
* --------------------------------------------------------------------
* Whether login attempts are recorded in the database.
*
* Valid values are:
* - Auth::RECORD_LOGIN_ATTEMPT_NONE
* - Auth::RECORD_LOGIN_ATTEMPT_FAILURE
* - Auth::RECORD_LOGIN_ATTEMPT_ALL
*/
public int $recordLoginAttempt = Auth::RECORD_LOGIN_ATTEMPT_FAILURE;
}

View File

@ -46,6 +46,7 @@ class Autoload extends AutoloadConfig
public $psr4 = [ public $psr4 = [
APP_NAMESPACE => APPPATH, // For custom app namespace APP_NAMESPACE => APPPATH, // For custom app namespace
'Config' => APPPATH . 'Config', 'Config' => APPPATH . 'Config',
'Libraries' => APPPATH . 'Libraries',
'Dompdf' => APPPATH . 'ThirdParty/dompdf/src', 'Dompdf' => APPPATH . 'ThirdParty/dompdf/src',
]; ];

View File

@ -8,6 +8,7 @@ use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\Honeypot; use CodeIgniter\Filters\Honeypot;
use CodeIgniter\Filters\InvalidChars; use CodeIgniter\Filters\InvalidChars;
use CodeIgniter\Filters\SecureHeaders; use CodeIgniter\Filters\SecureHeaders;
use CodeIgniter\Shield\Authentication\Authenticators\JWT;
class Filters extends BaseConfig class Filters extends BaseConfig
@ -43,6 +44,8 @@ class Filters extends BaseConfig
'login*', 'login*',
'register', 'register',
'auth/a/*', 'auth/a/*',
'auth/jwt',
'api/*',
'logout'] 'logout']
], ],
], ],
@ -73,5 +76,9 @@ class Filters extends BaseConfig
* Example: * Example:
* 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']] * 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
*/ */
public array $filters = []; public array $filters = [
/*'jwt' => [
'before' => ['api', 'api/*']
],*/
];
} }

View File

@ -0,0 +1,27 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class PedidoXML extends BaseConfig
{
public string $host;
public int $port;
public string $username;
public string $password;
public string $base_dir; # FTP server directory
public bool $xml_enabled;
public function __construct() {
parent::__construct();
$this->host = env("HIDRIVE_HOST","10.5.0.6");
$this->port = env("HIDRIVE_PORT",21);
$this->username = env("HIDRIVE_USER","admin");
$this->password = env("HIDRIVE_PASS","A77h3b0X4OA2rOYAf4w2");
$this->base_dir = env("HIDRIVE_PATH_ROOT","/home/admin/safekat"); # FTP server directory
$this->xml_enabled = env("FTP_XML_ENABLED",false);
}
}

View File

@ -9,10 +9,18 @@ const SK_PERMISSION_MATRIX = [
"plantilla-tarifa.edit", "plantilla-tarifa.edit",
"plantilla-tarifa.delete", "plantilla-tarifa.delete",
"plantilla-tarifa.menu", "plantilla-tarifa.menu",
"perfil.create",
"perfil.edit",
"perfil.delete",
"perfil.menu",
"presupuesto.create", "presupuesto.create",
"presupuesto.edit", "presupuesto.edit",
"presupuesto.delete", "presupuesto.delete",
"presupuesto.menu", "presupuesto.menu",
"presupuesto-cliente.create",
"presupuesto-cliente.edit",
"presupuesto-cliente.delete",
"presupuesto-cliente.menu",
"tarifa-preimpresion.create", "tarifa-preimpresion.create",
"tarifa-preimpresion.edit", "tarifa-preimpresion.edit",
"tarifa-preimpresion.delete", "tarifa-preimpresion.delete",
@ -33,6 +41,10 @@ const SK_PERMISSION_MATRIX = [
"tarifa-envio.edit", "tarifa-envio.edit",
"tarifa-envio.delete", "tarifa-envio.delete",
"tarifa-envio.menu", "tarifa-envio.menu",
"tarifa-extra.create",
"tarifa-extra.edit",
"tarifa-extra.delete",
"tarifa-extra.menu",
"proveedores.create", "proveedores.create",
"proveedores.edit", "proveedores.edit",
"proveedores.delete", "proveedores.delete",
@ -49,6 +61,10 @@ const SK_PERMISSION_MATRIX = [
"paises.edit", "paises.edit",
"paises.delete", "paises.delete",
"paises.menu", "paises.menu",
"formas-pago.create",
"formas-pago.edit",
"formas-pago.delete",
"formas-pago.menu",
"maquinas.create", "maquinas.create",
"maquinas.edit", "maquinas.edit",
"maquinas.delete", "maquinas.delete",
@ -73,62 +89,40 @@ const SK_PERMISSION_MATRIX = [
"roles-permisos.edit", "roles-permisos.edit",
"roles-permisos.delete", "roles-permisos.delete",
"roles-permisos.menu", "roles-permisos.menu",
"ubicaciones.create",
"ubicaciones.edit",
"ubicaciones.delete",
"ubicaciones.menu",
"series-facturas.create",
"series-facturas.edit",
"series-facturas.delete",
"series-facturas.menu",
], ],
"cliente-admin" => [ "cliente-admin" => [
"clientes.create", "perfil.edit",
"clientes.edit", "perfil.menu",
"clientes.delete", "direcciones.create",
"clientes.menu", "direcciones.edit",
"presupuesto.create", "direcciones.delete",
"presupuesto.edit", "direcciones.menu",
"presupuesto.delete", "presupuesto-cliente.create",
"presupuesto.menu", "presupuesto-cliente.edit",
"presupuesto-cliente.delete",
"presupuesto-cliente.menu",
], ],
"cliente-editor" => [ "cliente-editor" => [
"clientes.create", "perfil.create",
"clientes.edit", "perfil.edit",
"clientes.delete", "perfil.delete",
"clientes.menu", "perfil.menu",
"plantilla-tarifa.create", "direcciones.create",
"plantilla-tarifa.edit", "direcciones.edit",
"plantilla-tarifa.delete", "direcciones.delete",
"plantilla-tarifa.menu", "direcciones.menu",
"presupuesto.create", "presupuesto-cliente.create",
"presupuesto.edit", "presupuesto-cliente.edit",
"presupuesto.delete", "presupuesto-cliente.delete",
"presupuesto.menu", "presupuesto-cliente.menu",
"tarifa-preimpresion.create",
"tarifa-preimpresion.edit",
"tarifa-preimpresion.delete",
"tarifa-preimpresion.menu",
"tarifa-manipulado.create",
"tarifa-manipulado.edit",
"tarifa-manipulado.delete",
"tarifa-manipulado.menu",
"tarifa-acabado.create",
"tarifa-acabado.edit",
"tarifa-acabado.delete",
"tarifa-acabado.menu",
"tarifa-encuadernacion.create",
"tarifa-encuadernacion.edit",
"tarifa-encuadernacion.delete",
"tarifa-encuadernacion.menu",
"tarifa-envio.create",
"tarifa-envio.edit",
"tarifa-envio.delete",
"tarifa-envio.menu",
"proveedores.create",
"proveedores.edit",
"proveedores.delete",
"proveedores.menu",
"ajustes.create",
"ajustes.edit",
"ajustes.delete",
"ajustes.menu",
"actividad.create",
"actividad.edit",
"actividad.delete",
"actividad.menu",
], ],
"comercial" => [ "comercial" => [
"token.token", "token.token",
@ -169,10 +163,18 @@ const SK_PERMISSION_MATRIX = [
"plantilla-tarifa.edit", "plantilla-tarifa.edit",
"plantilla-tarifa.delete", "plantilla-tarifa.delete",
"plantilla-tarifa.menu", "plantilla-tarifa.menu",
"perfil.create",
"perfil.edit",
"perfil.delete",
"perfil.menu",
"presupuesto.create", "presupuesto.create",
"presupuesto.edit", "presupuesto.edit",
"presupuesto.delete", "presupuesto.delete",
"presupuesto.menu", "presupuesto.menu",
"presupuesto-cliente.create",
"presupuesto-cliente.edit",
"presupuesto-cliente.delete",
"presupuesto-cliente.menu",
"tarifa-preimpresion.create", "tarifa-preimpresion.create",
"tarifa-preimpresion.edit", "tarifa-preimpresion.edit",
"tarifa-preimpresion.delete", "tarifa-preimpresion.delete",
@ -193,6 +195,10 @@ const SK_PERMISSION_MATRIX = [
"tarifa-envio.edit", "tarifa-envio.edit",
"tarifa-envio.delete", "tarifa-envio.delete",
"tarifa-envio.menu", "tarifa-envio.menu",
"tarifa-extra.create",
"tarifa-extra.edit",
"tarifa-extra.delete",
"tarifa-extra.menu",
"proveedores.create", "proveedores.create",
"proveedores.edit", "proveedores.edit",
"proveedores.delete", "proveedores.delete",
@ -205,5 +211,41 @@ const SK_PERMISSION_MATRIX = [
"actividad.edit", "actividad.edit",
"actividad.delete", "actividad.delete",
"actividad.menu", "actividad.menu",
"paises.create",
"paises.edit",
"paises.delete",
"paises.menu",
"maquinas.create",
"maquinas.edit",
"maquinas.delete",
"maquinas.menu",
"maquinas-defecto.create",
"maquinas-defecto.edit",
"maquinas-defecto.delete",
"maquinas-defecto.menu",
"papel-generico.create",
"papel-generico.edit",
"papel-generico.delete",
"papel-generico.menu",
"papel-impresion.create",
"papel-impresion.edit",
"papel-impresion.delete",
"papel-impresion.menu",
"usuarios.create",
"usuarios.edit",
"usuarios.delete",
"usuarios.menu",
"roles-permisos.create",
"roles-permisos.edit",
"roles-permisos.delete",
"roles-permisos.menu",
"ubicaciones.create",
"ubicaciones.edit",
"ubicaciones.delete",
"ubicaciones.menu",
"series-facturas.create",
"series-facturas.edit",
"series-facturas.delete",
"series-facturas.menu",
], ],
]; ];

View File

@ -1,28 +0,0 @@
<?php
const SK_PERMISSION_MATRIX = [
"superadmin"=> [
"admin.*",
"users.*",
"beta.*"
],
"admin"=> [
"admin.access",
"users.create",
"users.edit",
"users.delete",
"beta.access"
],
"developer"=> [
"admin.access",
"admin.settings",
"users.create",
"users.edit",
"beta.access"
],
"user"=> [
"users.list"
],
"beta"=> [
"beta.access"
]
];

View File

@ -9,10 +9,22 @@ const SK_PERMISSIONS = [
'plantilla-tarifa.edit' => 'Can edit', 'plantilla-tarifa.edit' => 'Can edit',
'plantilla-tarifa.delete' => 'Can delete', 'plantilla-tarifa.delete' => 'Can delete',
'plantilla-tarifa.menu' => 'Menu shall be visualize', 'plantilla-tarifa.menu' => 'Menu shall be visualize',
'perfil.create' => 'Can create',
'perfil.edit' => 'Can edit',
'perfil.delete' => 'Can delete',
'perfil.menu' => 'Menu shall be visualize',
'direcciones.create' => 'Can create',
'direcciones.edit' => 'Can edit',
'direcciones.delete' => 'Can delete',
'direcciones.menu' => 'Menu shall be visualize',
'presupuesto.create' => 'Can create', 'presupuesto.create' => 'Can create',
'presupuesto.edit' => 'Can edit', 'presupuesto.edit' => 'Can edit',
'presupuesto.delete' => 'Can delete', 'presupuesto.delete' => 'Can delete',
'presupuesto.menu' => 'Menu shall be visualize', 'presupuesto.menu' => 'Menu shall be visualize',
'presupuesto-cliente.create' => 'Can create',
'presupuesto-cliente.edit' => 'Can edit',
'presupuesto-cliente.delete' => 'Can delete',
'presupuesto-cliente.menu' => 'Menu shall be visualize',
'tarifa-preimpresion.create' => 'Can create', 'tarifa-preimpresion.create' => 'Can create',
'tarifa-preimpresion.edit' => 'Can edit', 'tarifa-preimpresion.edit' => 'Can edit',
'tarifa-preimpresion.delete' => 'Can delete', 'tarifa-preimpresion.delete' => 'Can delete',
@ -33,6 +45,10 @@ const SK_PERMISSIONS = [
'tarifa-envio.edit' => 'Can edit', 'tarifa-envio.edit' => 'Can edit',
'tarifa-envio.delete' => 'Can delete', 'tarifa-envio.delete' => 'Can delete',
'tarifa-envio.menu' => 'Menu shall be visualize', 'tarifa-envio.menu' => 'Menu shall be visualize',
'tarifa-extra.create' => 'Can create',
'tarifa-extra.edit' => 'Can edit',
'tarifa-extra.delete' => 'Can delete',
'tarifa-extra.menu' => 'Menu shall be visualize',
'proveedores.create' => 'Can create', 'proveedores.create' => 'Can create',
'proveedores.edit' => 'Can edit', 'proveedores.edit' => 'Can edit',
'proveedores.delete' => 'Can delete', 'proveedores.delete' => 'Can delete',
@ -49,6 +65,10 @@ const SK_PERMISSIONS = [
'paises.edit' => 'Can edit', 'paises.edit' => 'Can edit',
'paises.delete' => 'Can delete', 'paises.delete' => 'Can delete',
'paises.menu' => 'Menu shall be visualize', 'paises.menu' => 'Menu shall be visualize',
'formas-pago.create' => 'Can create',
'formas-pago.edit' => 'Can edit',
'formas-pago.delete' => 'Can delete',
'formas-pago.menu' => 'Menu shall be visualize',
'maquinas.create' => 'Can create', 'maquinas.create' => 'Can create',
'maquinas.edit' => 'Can edit', 'maquinas.edit' => 'Can edit',
'maquinas.delete' => 'Can delete', 'maquinas.delete' => 'Can delete',
@ -73,4 +93,12 @@ const SK_PERMISSIONS = [
'roles-permisos.edit' => 'Can edit', 'roles-permisos.edit' => 'Can edit',
'roles-permisos.delete' => 'Can delete', 'roles-permisos.delete' => 'Can delete',
'roles-permisos.menu' => 'Menu shall be visualize', 'roles-permisos.menu' => 'Menu shall be visualize',
'ubicaciones.create' => 'Can create',
'ubicaciones.edit' => 'Can edit',
'ubicaciones.delete' => 'Can delete',
'ubicaciones.menu' => 'Menu shall be visualize',
'series-facturas.create' => 'Can create',
'series-facturas.edit' => 'Can edit',
'series-facturas.delete' => 'Can delete',
'series-facturas.menu' => 'Menu shall be visualize',
]; ];

View File

@ -1,11 +0,0 @@
<?php
const SK_PERMISSIONS = [
'admin.access' => 'Can access the sites admin area',
'admin.settings' => 'Can access the main site settings',
'users.manage-admins' => 'Can manage other admins',
'users.list' => 'Can list user stuff',
'users.create' => 'Can create new non-admin users',
'users.edit' => 'Can edit existing non-admin users',
'users.delete' => 'Can delete existing non-admin users',
'beta.access' => 'Can access beta-level features',
];

View File

@ -3,7 +3,7 @@
const SK_ROLES = [ const SK_ROLES = [
'admin' => [ 'admin' => [
'title' => 'Administrador', 'title' => 'Administrador',
'description' => '', 'description' => 'Administrador del ERP',
], ],
'cliente-admin' => [ 'cliente-admin' => [
'title' => 'Cliente administrador', 'title' => 'Cliente administrador',

View File

@ -1,23 +0,0 @@
<?php
const SK_ROLES = [
'superadmin' => [
'title' => 'Super Admin',
'description' => 'Complete control of the site.',
],
'admin' => [
'title' => 'Admin',
'description' => 'Day to day administrators of the site.',
],
'developer' => [
'title' => 'Developer',
'description' => 'Site programmers.',
],
'user' => [
'title' => 'User',
'description' => 'General users of the site. Often customers.',
],
'beta' => [
'title' => 'Beta User',
'description' => 'Has access to beta-level features.',
],
];

267
ci4/app/Config/Routes.php Executable file → Normal file
View File

@ -9,6 +9,7 @@ use CodeIgniter\Router\RouteCollection;
//service('auth')->routes($routes, ['except' => ['login', 'register']]); //service('auth')->routes($routes, ['except' => ['login', 'register']]);
service('auth')->routes($routes); service('auth')->routes($routes);
//WEB ROUTER ------------------------------------------------------ //WEB ROUTER ------------------------------------------------------
//------------------------------------------------------------------ //------------------------------------------------------------------
$routes->get('/', 'Home::index', ['as' => 'home']); $routes->get('/', 'Home::index', ['as' => 'home']);
@ -33,7 +34,7 @@ $routes->group('settings', ['namespace' => 'App\Controllers\Sistema'], function
* -------------------------------------------------------------------- * --------------------------------------------------------------------
*/ */
/* Rutas para configuraciones */ /* Rutas para tarifas */
$routes->group('tarifas', ['namespace' => 'App\Controllers\Tarifas'], function ($routes) { $routes->group('tarifas', ['namespace' => 'App\Controllers\Tarifas'], function ($routes) {
/* Cliente */ /* Cliente */
@ -51,7 +52,53 @@ $routes->group('tarifas', ['namespace' => 'App\Controllers\Tarifas'], function (
$routes->get('delete/(:num)', 'TarifaAcabadosLineas::delete/$1', ['as' => 'tarifaAcabadoLineasDelete']); $routes->get('delete/(:num)', 'TarifaAcabadosLineas::delete/$1', ['as' => 'tarifaAcabadoLineasDelete']);
}); });
}); });
});
/* Rutas para configuraciones */
$routes->group('configuracion', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
/* Ubicaciones */
$routes->group('ubicaciones', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Ubicaciones::index', ['as' => 'ubicacionesList']);
$routes->match(['get', 'post'], 'add', 'Ubicaciones::add', ['as' => 'ubicacionesAdd']);
$routes->match(['get', 'post'], 'edit/(:num)', 'Ubicaciones::edit/$1', ['as' => 'ubicacionesEdit']);
$routes->get('delete/(:num)', 'Ubicaciones::delete/$1', ['as' => 'ubicacionesDelete']);
$routes->post('datatable', 'Ubicaciones::datatable', ['as' => 'ubicacionesDT']);
});
/* Series Factura */
$routes->group('series-facturas', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'SeriesFacturas::index', ['as' => 'seriesFacturasList']);
$routes->match(['get', 'post'], 'add', 'SeriesFacturas::add', ['as' => 'seriesFacturasAdd']);
$routes->match(['get', 'post'], 'edit/(:num)', 'SeriesFacturas::edit/$1', ['as' => 'seriesFacturasEdit']);
$routes->get('delete/(:num)', 'SeriesFacturas::delete/$1', ['as' => 'seriesFacturasDelete']);
$routes->post('datatable', 'SeriesFacturas::datatable', ['as' => 'seriesFacturasDT']);
$routes->post('menuitemsFacturas', 'SeriesFacturas::menuItemsFacturas', ['as' => 'menuItemsOfSeriesFacturas']);
});
/* Formas de Pago */
$routes->group('formas-pago', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'FormasPago::index', ['as' => 'formasPagoList']);
$routes->match(['get', 'post'], 'add', 'FormasPago::add', ['as' => 'formasPagoAdd']);
$routes->match(['get', 'post'], 'edit/(:num)', 'FormasPago::edit/$1', ['as' => 'formasPagoEdit']);
$routes->get('delete/(:num)', 'FormasPago::delete/$1', ['as' => 'formasPagoDelete']);
$routes->post('datatable', 'FormasPago::datatable', ['as' => 'formasPagoDT']);
});
$routes->group("variables", ["namespace" => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'ConfigVariables::index', ['as' => 'variablesIndex']);
$routes->get('find/(:num)', 'ConfigVariables::get/$1', ['as' => 'variablesFind']);
$routes->post('edit/(:num)', 'ConfigVariables::updateVariable/$1', ['as' => 'updateVariable']);
$routes->delete('delete/(:num)', 'ConfigVariables::delete/$1', ['as' => 'deleteVariable']);
$routes->get('datatable', 'ConfigVariables::datatable', ['as' => 'datatableVariables']);
});
$routes->group("errores-presupuesto", ["namespace" => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'ConfigErrores::index', ['as' => 'erroresPresupuestoIndex']);
$routes->get('edit/(:num)', 'ConfigErrores::viewForm/$1', ['as' => 'erroresPresupuestoViewForm']);
$routes->get('get/(:num)', 'ConfigErrores::get_error_presupuesto/$1', ['as' => 'erroresPresupuestoGetErrorPresupuesto']);
$routes->get('datatable', 'ConfigErrores::datatable', ['as' => 'erroresPresupuestoDatatable']);
$routes->post('edit/(:num)', 'ConfigErrores::update_error_presupuesto/$1', ['as' => 'erroresPresupuestoUpdate']);
});
}); });
@ -66,6 +113,7 @@ $routes->group('users', ['namespace' => 'App\Controllers\Configuracion'], functi
$routes->get('delete/(:num)', 'Users::delete/$1', ['as' => 'deleteUser']); $routes->get('delete/(:num)', 'Users::delete/$1', ['as' => 'deleteUser']);
$routes->post('allmenuitems', 'Users::allItemsSelect', ['as' => 'select2ItemsOfUsers']); $routes->post('allmenuitems', 'Users::allItemsSelect', ['as' => 'select2ItemsOfUsers']);
$routes->post('menuitems', 'Users::menuItems', ['as' => 'menuItemsOfUsers']); $routes->post('menuitems', 'Users::menuItems', ['as' => 'menuItemsOfUsers']);
$routes->post('getMenuComerciales', 'Users::getMenuComerciales', ['as' => 'menuItemsComerciales']);
}); });
$routes->group('group', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) { $routes->group('group', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
@ -322,42 +370,22 @@ $routes->group('clientes', ['namespace' => 'App\Controllers\Clientes'], function
/* Cliente */ /* Cliente */
$routes->group('cliente', ['namespace' => 'App\Controllers\Clientes'], function ($routes) { $routes->group('cliente', ['namespace' => 'App\Controllers\Clientes'], function ($routes) {
$routes->get('', 'Cliente::index', ['as' => 'clienteList']); $routes->get('', 'Cliente::index', ['as' => 'clienteList']);
$routes->get('edit/(:num)', 'Cliente::edit/$1', ['as' => 'editarCliente']);
$routes->match(['get', 'post'], 'add', 'Cliente::add', ['as' => 'clienteAdd']); $routes->match(['get', 'post'], 'add', 'Cliente::add', ['as' => 'clienteAdd']);
$routes->match(['get', 'post'], 'edit/(:num)', 'Cliente::edit/$1', ['as' => 'clienteEdit']); $routes->match(['get', 'post'], 'edit/(:num)', 'Cliente::edit/$1', ['as' => 'clienteEdit']);
$routes->get('delete/(:num)', 'Cliente::delete/$1', ['as' => 'clienteDelete']); $routes->get('delete/(:num)', 'Cliente::delete/$1', ['as' => 'clienteDelete']);
$routes->post('datatable', 'Cliente::datatable', ['as' => 'clienteDT']); $routes->post('datatable', 'Cliente::datatable', ['as' => 'clienteDT']);
$routes->post('menuitems', 'Cliente::menuItems', ['as' => 'menuItemsOfClientes']); $routes->post('menuitems', 'Cliente::menuItems', ['as' => 'menuItemsOfClientes']);
$routes->get('getSelect2', 'Cliente::getSelect2', ['as' => 'getListaSelect2']);
}); });
/* Precios */
/*$routes->group('precios', ['namespace' => 'App\Controllers\Clientes'], function ($routes) {
$routes->post('datatable', 'ClientePrecios::datatable', ['as' => 'clientePreciosDT']);
$routes->post('datatable_editor', 'ClientePrecios::datatable_editor', ['as' => 'clientePreciosDTE']);
});*/
}); });
/*$routes->group('cliente', ['namespace' => 'App\Controllers\Clientes'], function ($routes) {
$routes->get('', 'Cliente::index', ['as' => 'clienteList']);
$routes->get('add', 'Cliente::add', ['as' => 'newCliente']);
$routes->post('add', 'Cliente::add', ['as' => 'createCliente']);
$routes->post('create', 'Cliente::create', ['as' => 'ajaxCreateCliente']);
$routes->put('(:num)/update', 'Cliente::update/$1', ['as' => 'ajaxUpdateCliente']);
$routes->post('edit/(:num)', 'Cliente::edit/$1', ['as' => 'updateCliente']);
$routes->get('delete/(:num)', 'Cliente::delete/$1', ['as' => 'deleteCliente']);
$routes->post('datatable', 'Cliente::datatable', ['as' => 'dataTableOfClientes']);
$routes->post('allmenuitems', 'Cliente::allItemsSelect', ['as' => 'select2ItemsOfClientes']);
});
$routes->resource('cliente', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'Cliente', 'except' => 'show,new,create,update']);*/
$routes->group('clienteprecios', ['namespace' => 'App\Controllers\Clientes'], function ($routes) { $routes->group('clienteprecios', ['namespace' => 'App\Controllers\Clientes'], function ($routes) {
$routes->post('datatable', 'Clienteprecios::datatable', ['as' => 'dataTableOfClienteprecios']); $routes->post('datatable', 'ClientePrecios::datatable', ['as' => 'dataTableOfClienteprecios']);
$routes->post('datatable_editor', 'Clienteprecios::datatable_editor', ['as' => 'editorOfClienteprecios']); $routes->post('datatable_editor', 'ClientePrecios::datatable_editor', ['as' => 'editorOfClienteprecios']);
}); });
$routes->resource('clienteprecios', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'Clienteprecios', 'except' => 'show,new,create,update']); $routes->resource('clienteprecios', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'ClientePrecios', 'except' => 'show,new,create,update']);
$routes->group('clienteplantillaprecios', ['namespace' => 'App\Controllers\Clientes'], function ($routes) { $routes->group('clienteplantillaprecios', ['namespace' => 'App\Controllers\Clientes'], function ($routes) {
@ -383,6 +411,15 @@ $routes->group('clienteusuarios', ['namespace' => 'App\Controllers\Clientes'], f
}); });
$routes->group('misdirecciones', ['namespace' => 'App\Controllers\Clientes'], function ($routes) {
$routes->get('', 'Clientedirecciones::index', ['as' => 'clientedireccionesIndex']);
$routes->get('get/(:num)', 'Clientedirecciones::get/$1', ['as' => 'get']);
$routes->get('getDireccionPresupuesto/(:num)', 'Clientedirecciones::getDireccionPresupuesto/$1', ['as' => 'getDireccionPresupuesto']);
$routes->post('add', 'Clientedirecciones::add', ['as' => 'newClientedirecciones']);
$routes->get('getSelect2', 'Clientedirecciones::getSelect2', ['as' => 'listaClientedirecciones']);
});
$routes->group('formas-pagos', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) { $routes->group('formas-pagos', ['namespace' => 'App\Controllers\Configuracion'], function ($routes) {
$routes->get('', 'Formaspagos::index', ['as' => 'formaDePagoList']); $routes->get('', 'Formaspagos::index', ['as' => 'formaDePagoList']);
$routes->get('add', 'Formaspagos::add', ['as' => 'newFormaDePago']); $routes->get('add', 'Formaspagos::add', ['as' => 'newFormaDePago']);
@ -522,6 +559,7 @@ $routes->resource('clientedirecciones', ['namespace' => 'App\Controllers\Cliente
$routes->group('cosidotapablanda', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) { $routes->group('cosidotapablanda', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->get('list/(:num)', 'Cosidotapablanda::list/$1', ['as' => 'cosidotapablandaList']); // HOMOGENIZAR CON ARGS DINAMICOS!!! $routes->get('list/(:num)', 'Cosidotapablanda::list/$1', ['as' => 'cosidotapablandaList']); // HOMOGENIZAR CON ARGS DINAMICOS!!!
$routes->get('add/(:num)', 'Cosidotapablanda::add/$1', ['as' => 'newCosidotapablanda']); $routes->get('add/(:num)', 'Cosidotapablanda::add/$1', ['as' => 'newCosidotapablanda']);
$routes->get('edit/(:any)', 'Cosidotapablanda::edit/$1', ['as' => 'editarPresupuesto']);
$routes->post('add/(:num)', 'Cosidotapablanda::add/$1', ['as' => 'createCosidotapablanda']); $routes->post('add/(:num)', 'Cosidotapablanda::add/$1', ['as' => 'createCosidotapablanda']);
$routes->post('create', 'Cosidotapablanda::create', ['as' => 'ajaxCreateCosidotapablanda']); $routes->post('create', 'Cosidotapablanda::create', ['as' => 'ajaxCreateCosidotapablanda']);
$routes->put('(:num)/update', 'Cosidotapablanda::update/$1', ['as' => 'ajaxUpdateCosidotapablanda']); $routes->put('(:num)/update', 'Cosidotapablanda::update/$1', ['as' => 'ajaxUpdateCosidotapablanda']);
@ -534,21 +572,26 @@ $routes->group('cosidotapablanda', ['namespace' => 'App\Controllers\Presupuestos
$routes->resource('cosidotapablanda', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Cosidotapablanda', 'except' => 'show,new,create,update']); $routes->resource('cosidotapablanda', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Cosidotapablanda', 'except' => 'show,new,create,update']);
$routes->group('presupuestocliente', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) { $routes->group('presupuestocliente', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->get('list/(:num)', 'Presupuestocliente::list/$1', ['as' => 'listarPresupuestoCliente']); // HOMOGENIZAR CON ARGS DINAMICOS!!! $routes->get('list', 'Presupuestocliente::list', ['as' => 'listaPresupuestos']);
$routes->post('datatable', 'Presupuestocliente::datatable', ['as' => 'datatableOfPresupuestos']);
$routes->get('add', 'Presupuestocliente::add', ['as' => 'nuevoPresupuestoCliente']); $routes->get('add', 'Presupuestocliente::add', ['as' => 'nuevoPresupuestoCliente']);
$routes->post('add', 'Presupuestocliente::add', ['as' => 'crearPresupuestoCliente']); $routes->post('add', 'Presupuestocliente::add', ['as' => 'crearPresupuestoCliente']);
$routes->post('edit/(:num)', 'Presupuestocliente::edit/$1', ['as' => 'editarPresupuestoCliente']); $routes->post('edit/(:num)', 'Presupuestocliente::edit/$1', ['as' => 'editarPresupuestoCliente']);
$routes->post('datatable', 'Cosidotapablanda::datatable', ['as' => 'tablaPresupuestosCliente']); $routes->get('edit/(:any)', 'Presupuestocliente::edit/$1', ['as' => 'editarPresupuestoCliente2']);
$routes->post('getgramaje', 'Presupuestocliente::getGramaje', ['as' => 'obtenerGramaje']); $routes->post('getgramaje', 'Presupuestocliente::getGramaje', ['as' => 'obtenerGramaje']);
$routes->post('presupuesto', 'Presupuestocliente::presupuesto', ['as' => 'presupuestoCliente']); $routes->post('presupuesto', 'Presupuestocliente::presupuesto', ['as' => 'presupuestoCliente']);
$routes->post('getDireccionesCliente', 'Presupuestocliente::getDireccionesCliente', ['as' => 'getDirecciones']); $routes->post('getDireccionesCliente', 'Presupuestocliente::getDireccionesCliente', ['as' => 'getDirecciones']);
$routes->post('getDatosDireccion', 'Presupuestocliente::getDatosDireccion', ['as' => 'getDatosDireccion']);
$routes->post('getNuevaDireccion', 'Presupuestocliente::getNuevaDireccion', ['as' => 'nuevaDireccion']); $routes->post('getNuevaDireccion', 'Presupuestocliente::getNuevaDireccion', ['as' => 'nuevaDireccion']);
$routes->post('guardar', 'Presupuestocliente::guardar', ['as' => 'guardar']);
$routes->get('cargar/(:num)', 'Presupuestocliente::cargar/$1', ['as' => 'cargarPresupuesto']);
$routes->post('duplicarPresupuesto', 'Presupuestocliente::duplicarPresupuesto', ['as' => 'duplicarPresupuesto']);
$routes->post('calcular', 'Presupuestocliente::calcular', ['as' => 'calcularPresupuesto']);
}); });
$routes->resource('presupuestocliente', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Presupuestocliente', 'except' => 'show,new,create,update']); $routes->resource('presupuestocliente', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Presupuestocliente', 'except' => 'show,new,create,update']);
$routes->group('serviciosacabados', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) { $routes->group('serviciosacabados', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->post('datatable', 'Presupuestoacabados::datatable', ['as' => 'dataTableOfPresupuestoAcabados']); $routes->post('datatable', 'Presupuestoacabados::datatable', ['as' => 'dataTableOfPresupuestoAcabados']);
$routes->post('menuitems', 'Presupuestoacabados::menuItems', ['as' => 'menuItemsOfPresupuestoAcabados']);
$routes->post('edit/(:num)', 'Presupuestoacabados::edit/$1', ['as' => 'updatePresupuestoacabados']); $routes->post('edit/(:num)', 'Presupuestoacabados::edit/$1', ['as' => 'updatePresupuestoacabados']);
}); });
@ -557,7 +600,6 @@ $routes->group('serviciosencuadernaciones', ['namespace' => 'App\Controllers\Pre
$routes->post('menuitems', 'Presupuestoencuadernaciones::menuItems', ['as' => 'menuItemsOfPresupuestoEncuadernaciones']); $routes->post('menuitems', 'Presupuestoencuadernaciones::menuItems', ['as' => 'menuItemsOfPresupuestoEncuadernaciones']);
$routes->get('delete/(:num)', 'Presupuestoencuadernaciones::delete/$1', ['as' => 'deletePresupuestoencuadernaciones']); $routes->get('delete/(:num)', 'Presupuestoencuadernaciones::delete/$1', ['as' => 'deletePresupuestoencuadernaciones']);
$routes->post('edit/(:num)', 'Presupuestoencuadernaciones::edit/$1', ['as' => 'updatePresupuestoencuadernaciones']); $routes->post('edit/(:num)', 'Presupuestoencuadernaciones::edit/$1', ['as' => 'updatePresupuestoencuadernaciones']);
}); });
$routes->group('serviciosmanipulados', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) { $routes->group('serviciosmanipulados', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
@ -585,6 +627,60 @@ $routes->group('presupuestotiradasalternativas', ['namespace' => 'App\Controller
$routes->post('datatable_2', 'Presupuestotiradasalternativas::datatable_2', ['as' => 'getTiradaData']); $routes->post('datatable_2', 'Presupuestotiradasalternativas::datatable_2', ['as' => 'getTiradaData']);
}); });
$routes->group('pedidos', ['namespace' => 'App\Controllers\Pedidos'], function ($routes) {
$routes->get('list', 'Pedido::todos', ['as' => 'listaPresupuestos']);
$routes->get('listActivos', 'Pedido::activos', ['as' => 'listaPresupuestosActivos']);
$routes->get('listFinalizados', 'Pedido::finalizados', ['as' => 'listaFinalizados']);
$routes->get('listCancelados', 'Pedido::cancelados', ['as' => 'listaCancelados']);
$routes->post('datatable', 'Pedido::datatable', ['as' => 'dataTableOfPedidos']);
$routes->get('add', 'Pedido::add', ['as' => 'nuevoPedido']);
$routes->post('add', 'Pedido::add', ['as' => 'crearPedido']);
$routes->get('edit/(:any)', 'Pedido::edit/$1', ['as' => 'editarPedido']);
$routes->post('getlineas', 'Pedido::getLineas', ['as' => 'tablaLineasPedido']);
$routes->post('cambiarestado', 'Pedido::cambiarEstado', ['as' => 'cambiarEstadoPedido']);
$routes->post('update/(:any)', 'Pedido::update/$1', ['as' => 'actualizarPedido']);
$routes->get('xml/(:num)', 'Pedido::get_xml_pedido/$1', ['as' => 'getXMLPedido']);
});
$routes->resource('pedidos', ['namespace' => 'App\Controllers\Pedidos', 'controller' => 'Pedido', 'except' => 'show,new,create,update']);
$routes->group('albaranes', ['namespace' => 'App\Controllers\Pedidos'], function ($routes) {
$routes->post('add', 'Albaran::add', ['as' => 'crearAlbaranesPedido']);
$routes->post('update/(:any)', 'Albaran::update/$1', ['as' => 'actualizarAlbaran']);
$routes->post('updateLinea/(:any)', 'Albaran::updateLinea/$1', ['as' => 'actualizarLineaAlbaran']);
$routes->post('deletelinea', 'Albaran::borrarlinea', ['as' => 'borrarAlbaranLinea']);
$routes->get('delete/(:any)', 'Albaran::delete/$1', ['as' => 'borrarAlbaran']);
$routes->get('getalbaranes/(:any)', 'Albaran::getAlbaranes/$1', ['as' => 'getAlbaranes']);
$routes->get('nuevalinea/(:any)', 'Albaran::addLinea/$1', ['as' => 'addAlbaranLinea']);
$routes->post('nuevalinea/(:any)', 'Albaran::addLinea/$1', ['as' => 'addIVA']);
});
$routes->resource('albaranes', ['namespace' => 'App\Controllers\Pedidos', 'controller' => 'Albaran', 'except' => 'show,new,create,update']);
$routes->group('facturas', ['namespace' => 'App\Controllers\Facturacion'], function ($routes) {
$routes->get('list', 'Facturas::list', ['as' => 'facturasList']);
$routes->post('datatable', 'Facturas::datatable', ['as' => 'dataTableOfFacturas']);
$routes->get('add', 'Facturas::add', ['as' => 'newFactura']);
$routes->post('add', 'Facturas::add', ['as' => 'createFactura']);
$routes->get('edit/(:any)', 'Facturas::edit/$1', ['as' => 'editarFactura']);
$routes->get('validar/(:any)', 'Facturas::validar/$1', ['as' => 'validarFactura']);
$routes->post('update/(:any)', 'Facturas::update/$1', ['as' => 'actualizarFactura']);
$routes->post('duplicate/(:any)', 'Facturas::duplicate/$1', ['as' => 'duplicarFactura']);
$routes->post('datatable/(:any)', 'FacturasLineas::datatable/$1', ['as' => 'dataTableOfLineasFacturas']);
$routes->post('menuPedidosPendientes/(:num)', 'Facturas::menuPedidosPendientes/$1', ['as' => 'menuPedidosPendientesImpresion']);
$routes->post('addLineaPedidoImpresion/(:num)', 'Facturas::addLineaPedidoImpresion/$1', ['as' => 'addLineaPedidoImpresion2Factura']);
$routes->post('addExcedentes/(:any)', 'Facturas::addExcedentes/$1', ['as' => 'addLineaExcedentes']);
$routes->get('deleteLinea/(:any)', 'FacturasLineas::deleteLinea/$1', ['as' => 'deleteLineaFactura']);
$routes->get('delete/(:any)', 'Facturas::delete/$1', ['as' => 'borrarFactura']);
$routes->post('deleteFacturaLineaPedido', 'Facturas::deleteLineaPedidoImpresion', ['as' => 'deleteLineaPedidoImpresion']);
$routes->post('editorLineas', 'FacturasLineas::datatable_editor', ['as' => 'editorOfLineasFacturas']);
$routes->post('updateTotales/(:any)', 'Facturas::updateTotales/$1', ['as' => 'updateFacturaTotales']);
$routes->post('updateCabecera/(:any)', 'Facturas::updateCabecera/$1', ['as' => 'updateCabecera']);
$routes->post('datatablePagos/(:any)', 'FacturasPagos::datatable/$1', ['as' => 'dataTableOfPagosFacturas']);
$routes->post('editorPagos', 'FacturasPagos::datatable_editor', ['as' => 'editorOfPagosFacturas']);
$routes->post('datatablePedidos', 'Facturas::datatablePedidos', ['as' => 'dataTableOfFacturasPedido']);
});
$routes->group( $routes->group(
@ -596,6 +692,40 @@ $routes->group(
} }
); );
$routes->group(
'print-albaran',
['namespace' => 'App\Controllers\Pdf'],
function ($routes) {
$routes->get('index/(:num)', 'PrintAlbaranes::index/$1', ['as' => 'viewAlbaranPDF']);
$routes->get('generar/(:num)', 'PrintAlbaranes::generar/$1', ['as' => 'albaranToPdf']);
}
);
$routes->group(
'print-factura',
['namespace' => 'App\Controllers\Pdf'],
function ($routes) {
$routes->get('index/(:num)', 'PrintFacturas::index/$1', ['as' => 'viewFacturaPDF']);
$routes->get('generar/(:num)', 'PrintFacturas::generar/$1', ['as' => 'facturaToPdf']);
}
);
$routes->group(
'export-giros',
['namespace' => 'App\Controllers\Excel'],
function ($routes) {
$routes->get('generar/(:num)', 'PrintGiros::generateExcel/$1', ['as' => 'girosToExcel']);
}
);
$routes->group(
'export-lineas',
['namespace' => 'App\Controllers\Excel'],
function ($routes) {
$routes->get('generar/(:num)', 'PrintLineas::generateExcel/$1', ['as' => 'lineasToExcel']);
}
);
$routes->group( $routes->group(
'buscadorpresupuestos', 'buscadorpresupuestos',
['namespace' => 'App\Controllers\Presupuestos'], ['namespace' => 'App\Controllers\Presupuestos'],
@ -607,6 +737,83 @@ $routes->group(
$routes->resource('buscadorpresupuestos', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Buscador', 'except' => 'show,new,create,update']); $routes->resource('buscadorpresupuestos', ['namespace' => 'App\Controllers\Presupuestos', 'controller' => 'Buscador', 'except' => 'show,new,create,update']);
$routes->group(
'papel-formato',
['namespace' => 'App\Controllers\Configuracion'],
function ($routes) {
$routes->post('menuitems', 'Papelformato::menuitems', ['as' => 'menuitems']);
$routes->get('getSelect2', 'Papelformato::getSelect2', ['as' => 'getSelect2']);
}
);
$routes->resource('papel-formato', ['namespace' => 'App\Controllers\Configuracion', 'controller' => 'Papelformato', 'except' => 'show,new,create,update']);
/* Rutas para mensajeria */
$routes->group('mensajes', ['namespace' => 'App\Controllers\Mensajeria'], function ($routes) {
/* Interna */
$routes->group('internos', ['namespace' => 'App\Controllers\Mensajeria'], function ($routes) {
$routes->get('', 'MensajesDirectos::index', ['as' => 'mensajeriaView']);
$routes->get('chat/(:num)', 'MensajesDirectos::getChatInfo/$1', ['as' => 'getChatInfo']);
/*$routes->match(['get', 'post'], 'add', 'TarifaAcabados::add', ['as' => 'tarifaAcabadoAdd']);
$routes->match(['get', 'post'], 'edit/(:num)', 'TarifaAcabados::edit/$1', ['as' => 'tarifaAcabadoEdit']);
$routes->get('delete/(:num)', 'TarifaAcabados::delete/$1', ['as' => 'tarifaAcabadoDelete']);
$routes->post('datatable', 'TarifaAcabados::datatable', ['as' => 'tarifaAcabadoDT']);*/
});
});
$routes->group('chat', ['namespace' => 'App\Controllers\Chat'], function ($routes) {
$routes->get('departments', 'ChatController::get_chat_departments', ['as' => 'getChatDepartments']);
$routes->get('department/presupuesto/(:num)/(:num)', 'ChatController::get_chat_presupuesto/$1/$2', ['as' => 'getChatPresupuesto']);
$routes->get('department/pedido/(:num)/(:num)', 'ChatController::get_chat_pedido/$1/$2', ['as' => 'getChatPedido']);
$routes->get('department/factura/(:num)/(:num)', 'ChatController::get_chat_factura/$1/$2', ['as' => 'getChatFactura']);
$routes->get('department/(:num)/users', 'ChatController::get_chat_department_users/$1', ['as' => 'getChatDepartmentUsers']);
$routes->get('(:num)', 'ChatController::get_chat/$1', ['as' => 'getChat']);
$routes->post('message/presupuesto', 'ChatController::store_chat_message_presupuesto', ['as' => 'storeChatMessagePresupuesto']);
$routes->post('message/pedido', 'ChatController::store_chat_message_pedido', ['as' => 'storeChatMessagePedido']);
$routes->post('message/factura', 'ChatController::store_chat_message_factura', ['as' => 'storeChatMessageFactura']);
$routes->post('message/internal', 'ChatController::store_chat_message_single', ['as' => 'storeChatMessageSingle']);
$routes->get('contacts', 'ChatController::get_chat_internal_contacts', ['as' => 'getChatInternalContacts']);
$routes->get('contacts/(:num)', 'ChatController::get_chat_internal_contact/$1', ['as' => 'getChatInternalContact']);
$routes->get('contact/(:num)/messages', 'ChatController::get_chat_internal_messages/$1', ['as' => 'getChatInternalMessages']);
$routes->get('notifications', 'ChatController::get_chat_cliente/$1', ['as' => 'getChatCliente']);
$routes->get('users/internal', 'ChatController::get_chat_users_internal', ['as' => 'getChatUsersInternal']);
$routes->post('hebra/presupuesto', 'ChatController::store_hebra_presupuesto', ['as' => 'storeHebraPresupuesto']);
$routes->post('hebra/pedido', 'ChatController::store_hebra_pedido', ['as' => 'storeHebraPedido']);
$routes->post('hebra/factura', 'ChatController::store_hebra_factura', ['as' => 'storeHebraFactura']);
$routes->post('hebra/(:num)', 'ChatController::update_hebra/$1', ['as' => 'updateHebra']);
$routes->get('hebra/presupuesto/(:num)', "ChatController::get_hebra_presupuesto/$1", ["as" => "getHebraPresupuesto"]);
$routes->get('hebra/pedido/(:num)', "ChatController::get_hebra_pedido/$1", ["as" => "getHebraPedido"]);
$routes->get('hebra/factura/(:num)', "ChatController::get_hebra_factura/$1", ["as" => "getHebraFactura"]);
});
/*
* --------------------------------------------------------------------
* APIs Route Definitions
* --------------------------------------------------------------------
*/
$routes->post('auth/jwt', '\App\Controllers\Sistema\AuthAPIController::jwtLogin');
$routes->group('api', ['filter' => 'jwt'], static function ($routes) {
$routes->get('test', 'Test::echo');
// ...
});
/*
* --------------------------------------------------------------------
* Translation
* --------------------------------------------------------------------
*/
$routes->group('translate', ['namespace' => 'App\Controllers'], function ($routes) {
$routes->post('getTranslation', 'Language::getTranslation', ['as' => 'getKeys']);
});
$routes->resource('translate', ['namespace' => 'App\Controllers', 'controller' => 'Language', 'except' => '']);
/* /*
* -------------------------------------------------------------------- * --------------------------------------------------------------------
* Additional Routing * Additional Routing

View File

@ -2,6 +2,7 @@
namespace Config; namespace Config;
use App\Services\FTPService;
use CodeIgniter\Config\BaseService; use CodeIgniter\Config\BaseService;
/** /**

View File

@ -37,7 +37,7 @@ class BaseController extends Controller
* *
* @var array * @var array
*/ */
protected $helpers = ['general', 'go_common']; protected $helpers = ['general', 'go_common', 'rbac'];
/** /**
* Constructor. * Constructor.

View File

@ -43,7 +43,7 @@ abstract class BaseResourceController extends \CodeIgniter\RESTful\ResourceContr
*/ */
protected static $pluralObjectName; protected static $pluralObjectName;
/** /**
* Path for the views directory for the extending view controller * Path for the views directory for the extending view controller
* *
* @var string * @var string
@ -85,7 +85,7 @@ abstract class BaseResourceController extends \CodeIgniter\RESTful\ResourceContr
* *
* @var array * @var array
*/ */
protected $helpers = ['session', 'go_common', 'form', 'text', 'general']; //JJO protected $helpers = ['session', 'go_common', 'form', 'text', 'general', 'rbac']; //JJO
/** /**
* Initializer method. * Initializer method.
@ -159,7 +159,7 @@ abstract class BaseResourceController extends \CodeIgniter\RESTful\ResourceContr
} }
if (!isset($this->viewData['formAction'])) { if (!isset($this->viewData['formAction'])) {
$this->viewData['formAction'] = base_url(strtolower($this->viewData['currentModule']) . '/' . $formActionSuffix . '/' . $action ); $this->viewData['formAction'] = base_url(strtolower($this->viewData['currentModule']) . '/' . $formActionSuffix . '/' . $action);
} }
if ((!isset($this->viewData['boxTitle']) || empty($this->viewData['boxTitle'])) && isset(static::$singularObjectName) && !empty(static::$singularObjectName)) { if ((!isset($this->viewData['boxTitle']) || empty($this->viewData['boxTitle'])) && isset(static::$singularObjectName) && !empty(static::$singularObjectName)) {
@ -223,22 +223,21 @@ abstract class BaseResourceController extends \CodeIgniter\RESTful\ResourceContr
public function delete($id = null) public function delete($id = null)
{ {
if (!empty(static::$pluralObjectNameCc) && !empty(static::$singularObjectNameCc)) { if (!empty(static::$pluralObjectNameCc) && !empty(static::$singularObjectNameCc)) {
$objName = mb_strtolower(lang(ucfirst(static::$pluralObjectNameCc).'.'.static::$singularObjectNameCc)); $objName = mb_strtolower(lang(ucfirst(static::$pluralObjectNameCc) . '.' . static::$singularObjectNameCc));
} else { } else {
$objName = lang('Basic.global.record'); $objName = lang('Basic.global.record');
} }
if (!$this->soft_delete){ if (!$this->soft_delete) {
if (!$this->model->delete($id)) { if (!$this->model->delete($id)) {
return $this->failNotFound(lang('Basic.global.deleteError', [$objName])); return $this->failNotFound(lang('Basic.global.deleteError', [$objName]));
} }
} } else {
else{
$datetime = (new \CodeIgniter\I18n\Time("now")); $datetime = (new \CodeIgniter\I18n\Time("now"));
$rawResult = $this->model->where('id',$id) $rawResult = $this->model->where('id', $id)
->set(['deleted_at' => $datetime->format('Y-m-d H:i:s'), ->set(['deleted_at' => $datetime->format('Y-m-d H:i:s'),
'is_deleted' => $this->delete_flag]) 'is_deleted' => $this->delete_flag])
->update(); ->update();
if (!$rawResult) { if (!$rawResult) {
return $this->failNotFound(lang('Basic.global.deleteError', [$objName])); return $this->failNotFound(lang('Basic.global.deleteError', [$objName]));
@ -261,20 +260,18 @@ abstract class BaseResourceController extends \CodeIgniter\RESTful\ResourceContr
protected function canValidate($customValidationRules = null, $customValidationMessages = null) protected function canValidate($customValidationRules = null, $customValidationMessages = null)
{ {
if($customValidationRules == null){ if ($customValidationRules == null) {
$validationRules = $this->model->validationRules ?? $this->formValidationRules ?? null; $validationRules = $this->model->validationRules ?? $this->formValidationRules ?? null;
} } else {
else{
$validationRules = $customValidationRules; $validationRules = $customValidationRules;
} }
if ($validationRules == null) { if ($validationRules == null) {
return true; return true;
} }
if($customValidationMessages == null){ if ($customValidationMessages == null) {
$validationErrorMessages = $this->model->validationMessages ?? $this->formValidationErrorMessagess ?? null;; $validationErrorMessages = $this->model->validationMessages ?? $this->formValidationErrorMessagess ?? null;;
} } else {
else{
$validationErrorMessages = $customValidationMessages; $validationErrorMessages = $customValidationMessages;
} }
@ -303,7 +300,8 @@ abstract class BaseResourceController extends \CodeIgniter\RESTful\ResourceContr
* @param array|null $postData * @param array|null $postData
* @return array * @return array
*/ */
protected function sanitized(array $postData = null, bool $nullIfEmpty = false) { protected function sanitized(array $postData = null, bool $nullIfEmpty = false)
{
if ($postData == null) { if ($postData == null) {
$postData = $this->request->getPost(); $postData = $this->request->getPost();
} }
@ -326,15 +324,15 @@ abstract class BaseResourceController extends \CodeIgniter\RESTful\ResourceContr
* @param string $customMessage * @param string $customMessage
* @return mixed * @return mixed
*/ */
protected function failWithNewToken($messages, int $status = 400, string $code = null, string $customMessage = '') { protected function failWithNewToken($messages, int $status = 400, string $code = null, string $customMessage = '')
{
if (! is_array($messages)) if (!is_array($messages)) {
{
$messages = ['error' => $messages]; $messages = ['error' => $messages];
} }
$response = [ $response = [
'status' => $status, 'status' => $status,
'error' => $status, 'error' => $status,
'messages' => $messages, 'messages' => $messages,
csrf_token() => csrf_hash() csrf_token() => csrf_hash()
]; ];
@ -360,7 +358,8 @@ abstract class BaseResourceController extends \CodeIgniter\RESTful\ResourceContr
* Convenience method for common exception handling * Convenience method for common exception handling
* @param \Exception $e * @param \Exception $e
*/ */
protected function dealWithException(\Exception $e) { protected function dealWithException(\Exception $e)
{
// using another try / catch block to prevent to avoid CodeIgniter bug throwing trivial exceptions for querying DB errors // using another try / catch block to prevent to avoid CodeIgniter bug throwing trivial exceptions for querying DB errors
try { try {
$query = $this->model->db->getLastQuery(); $query = $this->model->db->getLastQuery();
@ -368,16 +367,16 @@ abstract class BaseResourceController extends \CodeIgniter\RESTful\ResourceContr
$dbError = $this->model->db->error(); $dbError = $this->model->db->error();
$userFriendlyErrMsg = lang('Basic.global.persistErr1', [static::$singularObjectNameCc]); $userFriendlyErrMsg = lang('Basic.global.persistErr1', [static::$singularObjectNameCc]);
if (isset($dbError['code']) && $dbError['code'] == 1062) : if (isset($dbError['code']) && $dbError['code'] == 1062) :
$userFriendlyErrMsg .= PHP_EOL.lang('Basic.global.persistDuplErr', [static::$singularObjectNameCc]); $userFriendlyErrMsg .= PHP_EOL . lang('Basic.global.persistDuplErr', [static::$singularObjectNameCc]);
endif; endif;
// $userFriendlyErrMsg = str_replace("'", "\'", $userFriendlyErrMsg); // Uncomment if experiencing unescaped single quote errors // $userFriendlyErrMsg = str_replace("'", "\'", $userFriendlyErrMsg); // Uncomment if experiencing unescaped single quote errors
log_message('error', $userFriendlyErrMsg.PHP_EOL.$e->getMessage().PHP_EOL.$queryStr); log_message('error', $userFriendlyErrMsg . PHP_EOL . $e->getMessage() . PHP_EOL . $queryStr);
if (isset($dbError['message']) && !empty($dbError['message'])) : if (isset($dbError['message']) && !empty($dbError['message'])) :
log_message('error', $dbError['code'].' : '.$dbError['message']); log_message('error', $dbError['code'] . ' : ' . $dbError['message']);
endif; endif;
$this->viewData['errorMessage'] = $userFriendlyErrMsg; $this->viewData['errorMessage'] = $userFriendlyErrMsg;
} catch (\Exception $e2) { } catch (\Exception $e2) {
log_message('debug', 'You can probably safely ignore this: In attempt to check DB errors, CodeIgniter threw: '.PHP_EOL.$e2->getMessage()); log_message('debug', 'You can probably safely ignore this: In attempt to check DB errors, CodeIgniter threw: ' . PHP_EOL . $e2->getMessage());
} }
} }
} }

View File

@ -0,0 +1,420 @@
<?php
namespace App\Controllers\Chat;
use App\Controllers\BaseController;
use App\Models\Chat\ChatDeparmentModel;
use App\Models\Chat\ChatDeparmentUserModel;
use App\Models\Chat\ChatMessageModel;
use App\Models\Chat\ChatModel;
use App\Models\ChatNotification;
use App\Models\ChatUser;
use App\Models\Clientes\ClienteModel;
use App\Models\Usuarios\UserModel;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\Log\Logger;
use Psr\Log\LoggerInterface;
class ChatController extends BaseController
{
protected ChatDeparmentModel $chatDeparmentModel;
protected ChatDeparmentUserModel $chatDeparmentUserModel;
protected ChatModel $chatModel;
protected ChatMessageModel $chatMessageModel;
protected UserModel $userModel;
protected ClienteModel $clienteModel;
protected ChatUser $chatUserModel;
protected ChatNotification $chatNotificationModel;
public function initController(
RequestInterface $request,
ResponseInterface $response,
LoggerInterface $logger
) {
parent::initController($request, $response, $logger);
// Add your code here.
$this->chatDeparmentModel = model(ChatDeparmentModel::class);
$this->chatDeparmentUserModel = model(ChatDeparmentUserModel::class);
$this->chatModel = model(ChatModel::class);
$this->chatMessageModel = model(ChatMessageModel::class);
$this->userModel = model(UserModel::class);
$this->clienteModel = model(ClienteModel::class);
$this->chatUserModel = model(ChatUser::class);
$this->chatNotificationModel = model(ChatNotification::class);
}
public function index() {}
public function get_chat_departments()
{
$data = $this->chatDeparmentModel->getChatDepartments();
return $this->response->setJSON($data);
}
public function get_chat_presupuesto(int $chat_department_id, int $presupuesto_id)
{
$data = [
"chat" => null,
"messages" => null,
"count" => 0,
];
$chat = $this->chatModel->getChatPresupuesto($chat_department_id, $presupuesto_id);
if ($chat) {
$data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id);
$this->chatMessageModel->set_chat_department_messages_as_read($chat->id);
$data["count"] = count($data["messages"]);
}
$data["chat"] = $chat;
return $this->response->setJSON($data);
}
public function get_chat_pedido(int $chat_department_id, int $pedido_id)
{
$data = [
"chat" => null,
"messages" => null,
"count" => 0,
];
$chat = $this->chatModel->getChatPedido($chat_department_id, $pedido_id);
if ($chat) {
$data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id);
$this->chatMessageModel->set_chat_department_messages_as_read($chat->id);
$data["count"] = count($data["messages"]);
}
$data["chat"] = $chat;
return $this->response->setJSON($data);
}
public function get_chat_factura(int $chat_department_id, int $factura_id)
{
$data = [
"chat" => null,
"messages" => null,
"count" => 0,
];
$chat = $this->chatModel->getChatFactura($chat_department_id, $factura_id);
if ($chat) {
$data["messages"] = $this->chatMessageModel->get_chat_messages($chat->id);
$this->chatMessageModel->set_chat_department_messages_as_read($chat->id);
$data["count"] = count($data["messages"]);
}
$data["chat"] = $chat;
return $this->response->setJSON($data);
}
public function get_chat(int $chat_id)
{
$data = $this->chatModel->getChat($chat_id);
return $this->response->setJSON($data);
}
public function store_chat_message_presupuesto()
{
$data = $this->request->getPost();
// $data = $this->chatModel->createChatPresupuesto();
$existChat = $this->chatModel->existChatPresupuesto($data["chat_department_id"], $data["model_id"]);
if ($existChat == false) {
$chatId = $this->chatModel->createChatPresupuesto($data["chat_department_id"], $data["model_id"]);
} else {
$chat = $this->chatModel->getChatPresupuesto($data["chat_department_id"], $data["model_id"]);
$chatId = $chat->id;
}
$chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id);
return $this->response->setJSON($dataResponse);
}
public function store_chat_message_pedido()
{
$data = $this->request->getPost();
$existChat = $this->chatModel->existChatPedido($data["chat_department_id"], $data["model_id"]);
if ($existChat == false) {
$chatId = $this->chatModel->createChatPedido($data["chat_department_id"], $data["model_id"]);
} else {
$chat = $this->chatModel->getChatPedido($data["chat_department_id"], $data["model_id"]);
$chatId = $chat->id;
}
$chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id);
return $this->response->setJSON($dataResponse);
}
public function store_chat_message_factura()
{
$data = $this->request->getPost();
$existChat = $this->chatModel->existChatFactura($data["chat_department_id"], $data["model_id"]);
if ($existChat == false) {
$chatId = $this->chatModel->createChatFactura($data["chat_department_id"], $data["model_id"]);
} else {
$chat = $this->chatModel->getChatFactura($data["chat_department_id"], $data["model_id"]);
$chatId = $chat->id;
}
$chat_message_id = $this->chatMessageModel->insert(["chat_id" => $chatId, "sender_id" => auth()->user()->id, "message" => $data["message"]]);
$dataResponse = $this->chatMessageModel->find($chat_message_id);
return $this->response->setJSON($dataResponse);
}
public function store_chat_message_single()
{
$data = $this->request->getPost();
$existChat = $this->chatMessageModel->get_chat_contact_messages($data["receiver_id"]);
if (count($existChat) > 0) {
$chatId = $existChat[0]->chat_id;
} else {
$chatId = $this->chatModel->createChatSingle();
}
$chat_message_id = $this->chatMessageModel->insert(
[
"chat_id" => $chatId,
"sender_id" => auth()->user()->id,
"message" => $data["message"],
"receiver_id" => $data["receiver_id"]
]
);
$dataResponse = $this->chatMessageModel->find($chat_message_id);
return $this->response->setJSON($dataResponse);
}
public function get_chat_internal_contacts()
{
if (auth()->user()->cliente_id) {
return $this->response->setJSON([]);
}
$users = $this->userModel->builder()
->where("cliente_id", null)
->whereNotIn("id", [auth()->user()->id])
->where("deleted_at", null)
->get()->getResultObject();
foreach ($users as $user) {
$user->unreadMessages = $this->chatMessageModel->get_chat_unread_messages_count($user->id);
}
usort($users, fn($a, $b) => $a->unreadMessages < $b->unreadMessages);
return $this->response->setJSON($users);
}
public function get_chat_internal_contact(int $user_id)
{
if (auth()->user()->cliente_id) {
return $this->response->setJSON([]);
}
$users = $this->userModel->builder()
->where("cliente_id", null)
->where("deleted_at", null)
->where("id", $user_id)
->get()->getFirstRow();
$this->chatMessageModel->set_chat_messages_as_read($user_id);
return $this->response->setJSON($users);
}
public function get_chat_internal_messages(int $user_id)
{
$conversation = $this->chatMessageModel->get_chat_contact_messages($user_id);
return $this->response->setJSON($conversation);
}
public function get_chat_cliente()
{
$cliente_id = auth()->user()->cliente_id;
$response = [];
if ($cliente_id) {
$data = $this->clienteModel->getClienteDataPresupuestoPedidoFactura($cliente_id);
$response["totalMessages"] = 0;
$response["chatFacturas"] = $this->chatModel->getClienteChatFacturas($data["facturas"]);
foreach ($response["chatFacturas"] as $key => $value) {
$response["totalMessages"] += $value->unreadMessages;
}
$response["chatPresupuestos"] = $this->chatModel->getClienteChatPresupuestos($data["presupuestos"]);
foreach ($response["chatPresupuestos"] as $key => $value) {
$response["totalMessages"] += $value->unreadMessages;
}
$response["chatPedidos"] = $this->chatModel->getClienteChatPedidos($data["pedidos"]);
foreach ($response["chatPedidos"] as $key => $value) {
$response["totalMessages"] += $value->unreadMessages;
}
$response["data"] = $data;
} else {
$response["internals"] = $this->chatModel->getChatDepartmentNotifications();
$internal_notifications = $this->chatModel->getChatInternalNotifications();
foreach ($internal_notifications as $value) {
$response["internals"][] = $value;
}
$response["totalMessages"] = 0;
foreach ($response["internals"] as $key => $value) {
$response["totalMessages"] += $value->unreadMessages;
}
}
return $this->response->setJSON($response);
}
public function get_chat_department_users(int $chat_department_id)
{
$data = $this->chatDeparmentModel->getChatDepartmentUsers($chat_department_id);
return $this->response->setJSON($data);
}
public function get_chat_users_internal()
{
$query = $this->userModel->builder()->select(
[
"id",
"CONCAT(first_name,' ',last_name,'(',username,')') as name"
]
)->where("cliente_id", null)
->where("deleted_at", null)
->whereNotIn("id",[auth()->user()->id]);
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("users.username", $this->request->getGet("q"))
->orLike("CONCAT(first_name,' ',last_name)", $this->request->getGet("q"))
->groupEnd();
}
return $this->response->setJSON($query->get()->getResultObject());
}
public function store_hebra_presupuesto()
{
$bodyData = $this->request->getPost();
$chat_id = $this->chatModel->insert([
"presupuesto_id" => $bodyData["modelId"],
"title" => $bodyData["title"]
]);
$chatMessageId = $this->chatMessageModel->insert([
"chat_id" => $chat_id,
"message" => $bodyData["message"],
"sender_id" => auth()->user()->id
]);
if(isset($bodyData["users"])){
$chatUserData = array_map(fn($x) => ["user_id" => $x,"chat_id" => $chat_id],$bodyData["users"]);
$this->chatUserModel->insertBatch($chatUserData);
foreach ($bodyData["users"] as $userId) {
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId,"user_id" => $userId]);
}
}
return $this->response->setJSON(["message" => "Hebra creada correctamente","status" => true]);
}
public function store_hebra_pedido()
{
$bodyData = $this->request->getPost();
$chat_id = $this->chatModel->insert([
"pedido_id" => $bodyData["modelId"],
"title" => $bodyData["title"]
]);
$chatMessageId = $this->chatMessageModel->insert([
"chat_id" => $chat_id,
"message" => $bodyData["message"],
"sender_id" => auth()->user()->id
]);
if(isset($bodyData["users"])){
$chatUserData = array_map(fn($x) => ["user_id" => $x,"chat_id" => $chat_id],$bodyData["users"]);
$this->chatUserModel->insertBatch($chatUserData);
foreach ($bodyData["users"] as $userId) {
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId,"user_id" => $userId]);
}
}
return $this->response->setJSON(["message" => "Hebra creada correctamente","status" => true]);
}
public function store_hebra_factura()
{
$bodyData = $this->request->getPost();
$chat_id = $this->chatModel->insert([
"factura_id" => $bodyData["modelId"],
"title" => $bodyData["title"]
]);
$chatMessageId = $this->chatMessageModel->insert([
"chat_id" => $chat_id,
"message" => $bodyData["message"],
"sender_id" => auth()->user()->id
]);
if(isset($bodyData["users"])){
$chatUserData = array_map(fn($x) => ["user_id" => $x,"chat_id" => $chat_id],$bodyData["users"]);
$this->chatUserModel->insertBatch($chatUserData);
foreach ($bodyData["users"] as $userId) {
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId,"user_id" => $userId]);
}
}
return $this->response->setJSON(["message" => "Hebra creada correctamente","status" => true]);
}
public function update_hebra($chat_id)
{
$bodyData = $this->request->getPost();
$chatMessageId = $this->chatMessageModel->insert([
"chat_id" => $chat_id,
"message" => $bodyData["message"],
"sender_id" => auth()->user()->id
]);
$actualUsers = $this->chatUserModel->builder()->select("user_id")->where("chat_id",$chat_id)->get()->getResultArray();
$actualUsersArray = array_map(fn($x) => $x["user_id"],$actualUsers);
foreach ($actualUsersArray as $key => $user_id) {
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId,"user_id" => $user_id]);
}
if(isset($bodyData["users"])){
foreach ($bodyData["users"] as $userId) {
if(in_array($userId,$actualUsersArray) == false){
$chatUserData = ["user_id" => $userId,"chat_id" => $chat_id];
$this->chatUserModel->insert($chatUserData);
}
$this->chatNotificationModel->insert(
["chat_message_id" => $chatMessageId,"user_id" => $userId]);
}
}
return $this->response->setJSON(["message" => "Hebra actualizada correctamente","status" => true]);
}
public function get_hebra_presupuesto($presupuesto_id){
$data = $this->chatModel->getPresupuestoHebras($presupuesto_id);
$notifications = $this->chatModel->builder()->select([
"chat_notifications.id"
])
->join("chat_messages","chat_messages.chat_id = chats.id","left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left")
->where("chats.presupuesto_id",$presupuesto_id)
->where("chat_notifications.user_id",auth()->user()->id)
->get()->getResultArray();
foreach ($notifications as $notification) {
$this->chatNotificationModel->update($notification["id"],["viewed" => true]);
}
return $this->response->setJSON($data);
}
public function get_hebra_pedido($pedido_id){
$data = $this->chatModel->getPedidoHebras($pedido_id);
$notifications = $this->chatModel->builder()->select([
"chat_notifications.id"
])
->join("chat_messages","chat_messages.chat_id = chats.id","left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left")
->where("chats.pedido_id",$pedido_id)
->where("chat_notifications.user_id",auth()->user()->id)
->get()->getResultArray();
foreach ($notifications as $notification) {
$this->chatNotificationModel->update($notification["id"],["viewed" => true]);
}
return $this->response->setJSON($data);
}
public function get_hebra_factura($factura_id){
$data = $this->chatModel->getFacturaHebras($factura_id);
$notifications = $this->chatModel->builder()->select([
"chat_notifications.id"
])
->join("chat_messages","chat_messages.chat_id = chats.id","left")
->join("chat_notifications","chat_notifications.chat_message_id = chat_messages.id","left")
->where("chats.factura_id",$factura_id)
->where("chat_notifications.user_id",auth()->user()->id)
->get()->getResultArray();
foreach ($notifications as $notification) {
$this->chatNotificationModel->update($notification["id"],["viewed" => true]);
}
return $this->response->setJSON($data);
}
}

View File

@ -1,4 +1,6 @@
<?php namespace App\Controllers\Clientes; <?php
namespace App\Controllers\Clientes;
@ -310,14 +312,9 @@ class Cliente extends \App\Controllers\BaseResourceController
$onlyActiveOnes = false; $onlyActiveOnes = false;
$columns2select = [$reqId ?? 'id', $reqText ?? 'nombre']; $columns2select = [$reqId ?? 'id', $reqText ?? 'nombre'];
$onlyActiveOnes = false; $onlyActiveOnes = false;
try{ try {
$menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr); $menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr);
$nonItem = new \stdClass; } catch (Exception $e) {
$nonItem->id = '';
$nonItem->text = '- ' . lang('Basic.global.None') . ' -';
array_unshift($menu, $nonItem);
}
catch(Exception $e){
$menu = []; $menu = [];
} }
@ -334,6 +331,28 @@ class Cliente extends \App\Controllers\BaseResourceController
} }
public function getSelect2()
{
if ($this->request->isAJAX()) {
$query = $this->model->builder()->select(
[
"id",
"nombre as name"
]
)->where("deleted_at", null);
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("clientes.nombre", $this->request->getGet("q"))
->groupEnd();
}
return $this->response->setJSON($query->get()->getResultObject());
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
protected function getPaisListItems($selId = null) protected function getPaisListItems($selId = null)
{ {
$paisModel = model('App\Models\Configuracion\PaisModel'); $paisModel = model('App\Models\Configuracion\PaisModel');
@ -399,7 +418,7 @@ class Cliente extends \App\Controllers\BaseResourceController
protected function getFormaDePagoListItems($selId = null) protected function getFormaDePagoListItems($selId = null)
{ {
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('FormasPagoes.formaDePago'))])]; $data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('FormasPago.formaDePago'))])];
if (!empty($selId)) : if (!empty($selId)) :
$formaPagoModel = model('App\Models\Configuracion\FormaPagoModel'); $formaPagoModel = model('App\Models\Configuracion\FormaPagoModel');
@ -427,24 +446,23 @@ class Cliente extends \App\Controllers\BaseResourceController
} }
protected function getPrecioTemplate($cliente_id){ protected function getPrecioTemplate($cliente_id)
{
$modelPreciosCliente = model('App\Models\Clientes\ClientePreciosModel'); $modelPreciosCliente = model('App\Models\Clientes\ClientePreciosModel');
$plantilla_id = $modelPreciosCliente->get_plantilla_precios($cliente_id); $plantilla_id = $modelPreciosCliente->get_plantilla_precios($cliente_id);
if (is_null($plantilla_id)){ if (is_null($plantilla_id)) {
return null; return null;
} }
$modelPlantillaPreciosCliente = model('App\Models\Clientes\ClientePlantillaPreciosModel'); $modelPlantillaPreciosCliente = model('App\Models\Clientes\ClientePlantillaPreciosModel');
$plantilla = $modelPlantillaPreciosCliente->where("id", $plantilla_id)->where("is_deleted", 0)->first(); $plantilla = $modelPlantillaPreciosCliente->where("id", $plantilla_id)->where("is_deleted", 0)->first();
if ($plantilla == false){ if ($plantilla == false) {
return null; return null;
} } else {
else{
return (object)array( return (object)array(
"value" => $plantilla_id, "value" => $plantilla_id,
"label" => $plantilla->nombre "label" => $plantilla->nombre
); );
} }
} }
} }

View File

@ -1,4 +1,6 @@
<?php namespace App\Controllers\Clientes; <?php
namespace App\Controllers\Clientes;
use App\Models\Collection; use App\Models\Collection;
@ -6,6 +8,8 @@ use App\Entities\Clientes\ClienteDireccionesEntity;
use App\Models\Clientes\ClienteDireccionesModel; use App\Models\Clientes\ClienteDireccionesModel;
use App\Models\Usuarios\UserModel;
use DataTables\Editor; use DataTables\Editor;
use DataTables\Editor\Field; use DataTables\Editor\Field;
use DataTables\Editor\Validate; use DataTables\Editor\Validate;
@ -22,7 +26,55 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
protected static $controllerSlug = 'clientedirecciones'; protected static $controllerSlug = 'clientedirecciones';
public function add(){ protected static $viewPath = 'themes/vuexy/form/clientes/direcciones/';
protected $indexRoute = 'clienteDireccionesList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = lang('Clientes.direccionesEnvio');
$this->viewData['usingSweetAlert'] = true;
$this->viewData = ['usingServerSideDataTable' => true]; // JJO
// Breadcrumbs (IMN)
$this->viewData['breadcrumb'] = [
['title' => lang("Clientes.direccionesEnvio"), 'route' => "javascript:void(0);", 'active' => false],
];
$this->viewData['comunidadAutonomaList'] = $this->getComunidadAutonomaListItems($clienteEntity->comunidad_autonoma_id ?? null);
$this->viewData['provinciaList'] = $this->getProvinciaListItems($clienteEntity->provincia_id ?? null);
$this->viewData['paisList'] = $this->getPaisListItems($clienteEntity->pais_id ?? null);
parent::initController($request, $response, $logger);
}
public function index()
{
$id = auth()->user()->id;
$user_model = new UserModel();
$user = $user_model->find($id);
$cliente_id = $user->cliente_id;
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Clientes.cliente')]),
'cliente_id' => $cliente_id,
"user_id" => $id,
'usingServerSideDataTable' => true,
];
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
return view(static::$viewPath . 'viewClienteDireccionesList', $viewData);
}
public function add()
{
if ($this->request->isAJAX()) { if ($this->request->isAJAX()) {
$reqData = $this->request->getPost(); $reqData = $this->request->getPost();
@ -30,7 +82,7 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
$att = $reqData['att'] ?? ""; $att = $reqData['att'] ?? "";
$email = $reqData['email'] ?? ""; $email = $reqData['email'] ?? "";
$direccion = $reqData['direccion'] ?? ""; $direccion = $reqData['direccion'] ?? "";
$pais_id = $reqData['paisId'] ?? -1; $pais_id = $reqData['pais_id'] ?? -1;
$provincia = $reqData['provincia'] ?? ""; $provincia = $reqData['provincia'] ?? "";
$municipio = $reqData['municipio'] ?? ""; $municipio = $reqData['municipio'] ?? "";
$cp = $reqData['cp'] ?? ""; $cp = $reqData['cp'] ?? "";
@ -51,14 +103,10 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
]; ];
$response = $this->model->insert($data); $response = $this->model->insert($data);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data_ret = [ $data_ret = [
'data' => $response, 'data' => $response,
$csrfTokenName => $newTokenHash
]; ];
return $this->respond($data_ret); return $this->respond($data_ret);
} else { } else {
return $this->failUnauthorized('Invalid request', 403); return $this->failUnauthorized('Invalid request', 403);
} }
@ -89,6 +137,34 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
} }
public function getSelect2()
{
if ($this->request->isAJAX()) {
$cliente_id = $this->request->getGet('cliente_id');
$query = $this->model->builder()->select(
[
"id",
"alias as name"
]
)
->where("cliente_id", $cliente_id)
->orderBy("alias", "asc");
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("clientes.nombre", $this->request->getGet("q"))
->groupEnd();
}
return $this->response->setJSON($query->get()->getResultObject());
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function datatable() public function datatable()
{ {
if ($this->request->isAJAX()) { if ($this->request->isAJAX()) {
@ -96,7 +172,7 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
$tipo = $reqData['tipo'] ?? null; $tipo = $reqData['tipo'] ?? null;
if(is_null($tipo)){ if (is_null($tipo)) {
if (!isset($reqData['draw']) || !isset($reqData['columns'])) { if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
$errstr = 'No data available in response to this specific request.'; $errstr = 'No data available in response to this specific request.';
$response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr); $response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr);
@ -120,8 +196,7 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
$this->model->getResource()->countAllResults(), $this->model->getResource()->countAllResults(),
$this->model->getResource("", $id_C)->countAllResults() $this->model->getResource("", $id_C)->countAllResults()
)); ));
} } else {
else{
$id = $reqData['id'] ?? -1; $id = $reqData['id'] ?? -1;
@ -135,6 +210,44 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
} }
} }
public function get($id)
{
try {
$resourceData = $this->model->getDireccion($id);
$response = (object)[
'error' => false,
'data' => $resourceData
];
return $this->respond($response);
} catch (\Exception $e) {
$response = (object)[
'error' => true,
'message' => $e->getMessage()
];
return $this->fail($response);
}
}
public function getDireccionPresupuesto($id)
{
try {
$model = model('App\Models\Presupuestos\PresupuestoDireccionesModel');
$resourceData = $model->getDireccion($id);
$response = (object)[
'error' => false,
'data' => $resourceData
];
return $this->respond($response);
} catch (\Exception $e) {
$response = (object)[
'error' => true,
'message' => $e->getMessage()
];
return $this->fail($response);
}
}
public function datatable_editor() public function datatable_editor()
{ {
if ($this->request->isAJAX()) { if ($this->request->isAJAX()) {
@ -145,69 +258,113 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
$response = Editor::inst($db, 'cliente_direcciones') $response = Editor::inst($db, 'cliente_direcciones')
->fields( ->fields(
Field::inst('att') Field::inst('att')
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('ClienteDirecciones.validation.required')) 'Validate::notEmpty',
array(
'message' => lang('ClienteDirecciones.validation.required')
)
) )
->validator( Validate::maxLen( 100 ) , array( ->validator(
'message' => lang('ClienteDirecciones.validation.max_length')) Validate::maxLen(100),
), array(
'message' => lang('ClienteDirecciones.validation.max_length')
)
),
Field::inst('alias') Field::inst('alias')
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('ClienteDirecciones.validation.required')) 'Validate::notEmpty',
array(
'message' => lang('ClienteDirecciones.validation.required')
)
) )
->validator( Validate::maxLen( 100 ) , array( ->validator(
'message' => lang('ClienteDirecciones.validation.max_length')) Validate::maxLen(100),
), array(
'message' => lang('ClienteDirecciones.validation.max_length')
)
),
Field::inst('email') Field::inst('email')
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('ClienteDirecciones.validation.required')) 'Validate::notEmpty',
array(
'message' => lang('ClienteDirecciones.validation.required')
)
) )
->validator( Validate::maxLen( 100 ) , array( ->validator(
'message' => lang('ClienteDirecciones.validation.max_length')) Validate::maxLen(100),
), array(
'message' => lang('ClienteDirecciones.validation.max_length')
)
),
Field::inst('direccion') Field::inst('direccion')
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('ClienteDirecciones.validation.required')) 'Validate::notEmpty',
array(
'message' => lang('ClienteDirecciones.validation.required')
)
) )
->validator( Validate::maxLen( 255 ) , array( ->validator(
'message' => lang('ClienteDirecciones.validation.max_length')) Validate::maxLen(255),
), array(
'message' => lang('ClienteDirecciones.validation.max_length')
)
),
Field::inst('municipio') Field::inst('municipio')
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('ClienteDirecciones.validation.required')) 'Validate::notEmpty',
array(
'message' => lang('ClienteDirecciones.validation.required')
)
) )
->validator( Validate::maxLen( 100 ) , array( ->validator(
'message' => lang('ClienteDirecciones.validation.max_length')) Validate::maxLen(100),
), array(
'message' => lang('ClienteDirecciones.validation.max_length')
)
),
Field::inst('cp') Field::inst('cp')
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('ClienteDirecciones.validation.required')) 'Validate::notEmpty',
array(
'message' => lang('ClienteDirecciones.validation.required')
)
) )
->validator( Validate::maxLen( 20 ) , array( ->validator(
'message' => lang('ClienteDirecciones.validation.max_length')) Validate::maxLen(20),
), array(
'message' => lang('ClienteDirecciones.validation.max_length')
)
),
Field::inst('telefono') Field::inst('telefono')
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('ClienteDirecciones.validation.required')) 'Validate::notEmpty',
array(
'message' => lang('ClienteDirecciones.validation.required')
)
) )
->validator( Validate::maxLen( 40 ) , array( ->validator(
'message' => lang('ClienteDirecciones.validation.max_length')) Validate::maxLen(40),
), array(
'message' => lang('ClienteDirecciones.validation.max_length')
)
),
Field::inst('provincia') Field::inst('provincia')
->validator( function ( $val, $data, $field, $host ) { ->validator(
if ($data['pais_id'] == 1) { // Si es españa provincia y CCAA es obligatorio function ($val, $data, $field, $host) {
if (strlen( $val ) > 100) if ($data['pais_id'] == 1) { // Si es españa provincia y CCAA es obligatorio
return lang('ClienteDirecciones.validation.max_length'); if (strlen($val) > 100)
else if (strlen( $val ) == 0) return lang('ClienteDirecciones.validation.max_length');
lang('ClienteDirecciones.validation.required'); else if (strlen($val) == 0)
else lang('ClienteDirecciones.validation.required');
return true; else
return true;
}
return true;
} }
return true; ),
}
),
Field::inst('pais_id')->validator('Validate::notEmpty', array( Field::inst('pais_id')->validator('Validate::notEmpty', array(
'message' => lang('ClienteDirecciones.validation.required'))), 'message' => lang('ClienteDirecciones.validation.required')
)),
Field::inst('cliente_id'), Field::inst('cliente_id'),
) )
@ -221,9 +378,46 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
$response[$csrfTokenName] = $newTokenHash; $response[$csrfTokenName] = $newTokenHash;
echo json_encode($response); echo json_encode($response);
} else { } else {
return $this->failUnauthorized('Invalid request', 403); return $this->failUnauthorized('Invalid request', 403);
} }
} }
protected function getPaisListItems($selId = null)
{
$paisModel = model('App\Models\Configuracion\PaisModel');
$onlyActiveOnes = true;
$data = $paisModel->getAllForMenu('id, nombre', 'nombre', $onlyActiveOnes);
return $data;
}
protected function getComunidadAutonomaListItems($selId = null)
{
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('ComunidadesAutonomas.comunidadAutonoma'))])];
if (!is_null($selId)) :
$comunidadAutonomaModel = model('App\Models\Configuracion\ComunidadAutonomaModel');
$selOption = $comunidadAutonomaModel->where('id', $selId)->findColumn('nombre');
if (!empty($selOption)) :
$data[$selId] = $selOption[0];
endif;
endif;
return $data;
}
protected function getProvinciaListItems($selId = null)
{
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Provincias.provincia'))])];
if (!empty($selId)) :
$provinciaModel = model('App\Models\Configuracion\ProvinciaModel');
$selOption = $provinciaModel->where('id', $selId)->findColumn('nombre');
if (!empty($selOption)) :
$data[$selId] = $selOption[0];
endif;
endif;
return $data;
}
} }

View File

@ -0,0 +1,81 @@
<?php
namespace App\Controllers\Configuracion;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
use App\Models\Presupuestos\ErrorPresupuesto as ErrorPresupuestoModel;
use CodeIgniter\HTTP\Response;
use Hermawan\DataTables\DataTable;
class ConfigErrores extends BaseResourceController
{
protected ErrorPresupuestoModel $errorPresupuestoModel;
protected $format = 'json';
protected array $viewData = [];
protected static $viewPath = 'themes/vuexy/form/configuracion/error_presupuesto/';
protected static $controllerSlug = "errores-presupuesto";
protected $indexRoute = 'viewErrorPresupuestoList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->errorPresupuestoModel = model(ErrorPresupuestoModel::class);
}
public function index()
{
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_error_presupuesto"), 'route' => site_url('configuracion/errores-presupuesto'), 'active' => true]
];
return view(static::$viewPath . $this->indexRoute, $this->viewData);
}
public function viewForm(int $error_presupuesto_id)
{
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_error_presupuesto"), 'route' => site_url('configuracion/errores-presupuesto'), 'active' => true]
];
$this->viewData["error_presupuesto_id"] = $error_presupuesto_id;
$this->errorPresupuestoModel->update($error_presupuesto_id, [
"last_user_id" => auth()->user()->id,
"visto" => true,
]);
return view(static::$viewPath . 'viewErrorPresupuestoForm', $this->viewData);
}
public function store()
{
$data = [];
$variableCreated = $this->errorPresupuestoModel->store($data);
return $this->response->setJSON($variableCreated);
}
public function get_error_presupuesto(int $error_presupuesto_id)
{
$data = $this->errorPresupuestoModel->getErrorPresupuestoForm($error_presupuesto_id);
if (isset($data[0])) {
return $this->response->setJSON(["data" => $data[0]]);
} else {
return $this->response->setJSON(["data" => []]);
}
}
public function update_error_presupuesto(int $error_presupuesto_id)
{
$bodyData = $this->request->getPost();
$this->errorPresupuestoModel->updateComment($error_presupuesto_id, $bodyData["comments"]);
return $this->response->setJSON(["message" => "Comentario actualizado", "status" => true]);
}
public function datatable()
{
$query = $this->errorPresupuestoModel->getQueryDatatable()->orderBy("created_at", "DESC");
return DataTable::of($query)
->add("action", fn($q) => $q->id)
->toJson(true);
}
}

View File

@ -0,0 +1,92 @@
<?php
namespace App\Controllers\Configuracion;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
use App\Models\Configuracion\ConfigVariableModel;
use CodeIgniter\HTTP\Response;
use Hermawan\DataTables\DataTable;
class ConfigVariables extends BaseResourceController
{
protected $modelName = ConfigVariableModel::class;
protected ConfigVariableModel $configVariableModel;
protected $format = 'json';
protected static $singularObjectName = 'Variables';
protected static $singularObjectNameCc = 'variables';
protected static $pluralObjectName = 'Variables';
protected static $pluralObjectNameCc = 'variables';
protected static $controllerSlug = 'variables';
protected static $viewPath = 'themes/vuexy/form/configuracion/variables/';
protected $indexRoute = 'viewVariablesList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->configVariableModel = model(ConfigVariableModel::class);
}
public function index()
{
$viewData = [
'currentModule' => static::$controllerSlug,
];
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
return view(static::$viewPath . $this->indexRoute, $viewData);
}
public function store()
{
$data = [];
$variableCreated = $this->configVariableModel->store($data);
return $this->response->setJSON($variableCreated);
}
public function get(int $config_variable_id)
{
$data = $this->configVariableModel->find($config_variable_id);
return $this->response->setJSON($data);
}
public function updateVariable(int $config_variable_id)
{
$reqData = [];
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
$status = $this->configVariableModel->update($config_variable_id, $reqData);
return $this->response->setJSON([
"message" => "Variable actualizada correctamente",
"status" => $status
]);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function deleteVariable(int $config_variable_id): Response
{
return $this->response->setJSON([]);
}
public function datatable()
{
$query = $this->configVariableModel->builder()->select([
"id",
"name",
"value",
"description"
])->orderBy("name", "asc");
return DataTable::of($query)
->add("action", fn($q) => $q->id)
->toJson(true);
}
}

View File

@ -9,7 +9,7 @@ use App\Entities\Configuracion\FormaPagoEntity;
use App\Models\Configuracion\FormaPagoModel; use App\Models\Configuracion\FormaPagoModel;
class Formaspagos extends \App\Controllers\BaseResourceController class FormasPago extends \App\Controllers\BaseResourceController
{ {
protected $modelName = FormaPagoModel::class; protected $modelName = FormaPagoModel::class;
@ -22,15 +22,22 @@ class Formaspagos extends \App\Controllers\BaseResourceController
protected static $controllerSlug = 'formas-pagos'; protected static $controllerSlug = 'formas-pagos';
protected static $viewPath = 'themes/vuexy/form/configuracion/formasPagoViews/'; protected static $viewPath = 'themes/vuexy/form/configuracion/formas-pago/';
protected $indexRoute = 'formaDePagoList'; protected $indexRoute = 'formaDePagoList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{ {
$this->viewData['pageTitle'] = lang('FormasPagoes.moduleTitle'); $this->viewData['pageTitle'] = lang('FormasPago.moduleTitle');
$this->viewData['usingSweetAlert'] = true; $this->viewData['usingSweetAlert'] = true;
// Breadcrumbs (IMN)
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_formas_pago"), 'route' => route_to('formasPagoList'), 'active' => true]
];
parent::initController($request, $response, $logger); parent::initController($request, $response, $logger);
} }
@ -40,7 +47,7 @@ class Formaspagos extends \App\Controllers\BaseResourceController
$viewData = [ $viewData = [
'currentModule' => static::$controllerSlug, 'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('FormasPagoes.formaDePago')]), 'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('FormasPago.formaDePago')]),
'formaPagoEntity' => new FormaPagoEntity(), 'formaPagoEntity' => new FormaPagoEntity(),
'usingServerSideDataTable' => true, 'usingServerSideDataTable' => true,
@ -55,22 +62,15 @@ class Formaspagos extends \App\Controllers\BaseResourceController
public function add() public function add()
{ {
if ($this->request->getPost()) : if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost(); $postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, $nullIfEmpty); $sanitizedData = $this->sanitized($postData, true);
$noException = true; $noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) : if ($this->canValidate()) :
try { try {
$successfulResult = $this->model->skipValidation(true)->save($sanitizedData); $successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
@ -93,7 +93,8 @@ class Formaspagos extends \App\Controllers\BaseResourceController
if ($thenRedirect) : if ($thenRedirect) :
if (!empty($this->indexRoute)) : if (!empty($this->indexRoute)) :
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message); return redirect()->to(site_url('/configuracion/formas-pago/edit/' . $id))->with('sweet-success', $message);
//return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else: else:
return $this->redirect2listView('sweet-success', $message); return $this->redirect2listView('sweet-success', $message);
endif; endif;
@ -106,11 +107,8 @@ class Formaspagos extends \App\Controllers\BaseResourceController
endif; // ($requestMethod === 'post') endif; // ($requestMethod === 'post')
$this->viewData['formaPagoEntity'] = isset($sanitizedData) ? new FormaPagoEntity($sanitizedData) : new FormaPagoEntity(); $this->viewData['formaPagoEntity'] = isset($sanitizedData) ? new FormaPagoEntity($sanitizedData) : new FormaPagoEntity();
$this->viewData['formAction'] = route_to('formasPagoAdd');
$this->viewData['formAction'] = route_to('createFormaDePago'); $this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('FormasPago.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix');
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('FormasPagoes.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix');
return $this->displayForm(__METHOD__); return $this->displayForm(__METHOD__);
} // end function add() } // end function add()
@ -125,25 +123,18 @@ class Formaspagos extends \App\Controllers\BaseResourceController
$formaPagoEntity = $this->model->find($id); $formaPagoEntity = $this->model->find($id);
if ($formaPagoEntity == false) : if ($formaPagoEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('FormasPagoes.formaDePago')), $id]); $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('FormasPago.formaDePago')), $id]);
return $this->redirect2listView('sweet-error', $message); return $this->redirect2listView('sweet-error', $message);
endif; endif;
if ($this->request->getPost()) : if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost(); $postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, true);
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
$noException = true; $noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) : if ($this->canValidate()) :
try { try {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData); $successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
@ -152,13 +143,12 @@ class Formaspagos extends \App\Controllers\BaseResourceController
$this->dealWithException($e); $this->dealWithException($e);
} }
else: else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('FormasPagoes.formaDePago'))]); $this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('FormasPago.formaDePago'))]);
$this->session->setFlashdata('formErrors', $this->model->errors()); $this->session->setFlashdata('formErrors', $this->model->errors());
endif; endif;
$formaPagoEntity->fill($sanitizedData); $formaPagoEntity->fill($sanitizedData);
$thenRedirect = false; $thenRedirect = false;
endif; endif;
if ($noException && $successfulResult) : if ($noException && $successfulResult) :
@ -179,11 +169,8 @@ class Formaspagos extends \App\Controllers\BaseResourceController
endif; // ($requestMethod === 'post') endif; // ($requestMethod === 'post')
$this->viewData['formaPagoEntity'] = $formaPagoEntity; $this->viewData['formaPagoEntity'] = $formaPagoEntity;
$this->viewData['formAction'] = route_to('formasPagoEdit', $id);
$this->viewData['formAction'] = route_to('updateFormaDePago', $id); $this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('FormasPago.moduleTitle') . ' ' . lang('Basic.global.edit3');
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('FormasPagoes.moduleTitle') . ' ' . lang('Basic.global.edit3');
return $this->displayForm(__METHOD__, $id); return $this->displayForm(__METHOD__, $id);
} // end function edit(...) } // end function edit(...)

View File

@ -1,4 +1,5 @@
<?php namespace App\Controllers\Configuracion; <?php
namespace App\Controllers\Configuracion;
use App\Controllers\BaseResourceController; use App\Controllers\BaseResourceController;
@ -12,8 +13,8 @@ use App\Models\Configuracion\MaquinasTarifasImpresionModel;
use App\Models\Configuracion\MaquinaModel; use App\Models\Configuracion\MaquinaModel;
use use
DataTables\Editor, DataTables\Editor,
DataTables\Editor\Field; DataTables\Editor\Field;
class Maquinastarifasimpresion extends \App\Controllers\BaseResourceController class Maquinastarifasimpresion extends \App\Controllers\BaseResourceController
{ {
@ -71,7 +72,7 @@ class Maquinastarifasimpresion extends \App\Controllers\BaseResourceController
if ($this->request->getPost()) : if ($this->request->getPost()):
$nullIfEmpty = true; // !(phpversion() >= '8.1'); $nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -81,10 +82,10 @@ class Maquinastarifasimpresion extends \App\Controllers\BaseResourceController
$noException = true; $noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) : if ($this->canValidate()):
try { try {
$successfulResult = $this->model->skipValidation(true)->save($sanitizedData); $successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
} catch (\Exception $e) { } catch (\Exception $e) {
@ -98,14 +99,14 @@ class Maquinastarifasimpresion extends \App\Controllers\BaseResourceController
$thenRedirect = true; // Change this to false if you want your user to stay on the form after submission $thenRedirect = true; // Change this to false if you want your user to stay on the form after submission
endif; endif;
if ($noException && $successfulResult) : if ($noException && $successfulResult):
$id = $this->model->db->insertID(); $id = $this->model->db->insertID();
$message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.'; $message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect) : if ($thenRedirect):
if (!empty($this->indexRoute)) : if (!empty($this->indexRoute)):
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message); return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else: else:
return $this->redirect2listView('sweet-success', $message); return $this->redirect2listView('sweet-success', $message);
@ -134,20 +135,20 @@ class Maquinastarifasimpresion extends \App\Controllers\BaseResourceController
public function edit($requestedId = null) public function edit($requestedId = null)
{ {
if ($requestedId == null) : if ($requestedId == null):
return $this->redirect2listView(); return $this->redirect2listView();
endif; endif;
$id = filter_var($requestedId, FILTER_SANITIZE_URL); $id = filter_var($requestedId, FILTER_SANITIZE_URL);
$maquinasTarifasImpresion = $this->model->find($id); $maquinasTarifasImpresion = $this->model->find($id);
if ($maquinasTarifasImpresion == false) : if ($maquinasTarifasImpresion == false):
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('MaquinasTarifasImpresions.maquinasTarifaImpresion')), $id]); $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('MaquinasTarifasImpresions.maquinasTarifaImpresion')), $id]);
return $this->redirect2listView('sweet-error', $message); return $this->redirect2listView('sweet-error', $message);
endif; endif;
if ($this->request->getPost()) : if ($this->request->getPost()):
$nullIfEmpty = true; // !(phpversion() >= '8.1'); $nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -160,10 +161,10 @@ class Maquinastarifasimpresion extends \App\Controllers\BaseResourceController
$noException = true; $noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) : if ($this->canValidate()):
try { try {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData); $successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) { } catch (\Exception $e) {
@ -180,12 +181,12 @@ class Maquinastarifasimpresion extends \App\Controllers\BaseResourceController
$thenRedirect = false; $thenRedirect = false;
endif; endif;
if ($noException && $successfulResult) : if ($noException && $successfulResult):
$id = $maquinasTarifasImpresion->id ?? $id; $id = $maquinasTarifasImpresion->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.'; $message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect) : if ($thenRedirect):
if (!empty($this->indexRoute)) : if (!empty($this->indexRoute)):
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message); return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else: else:
return $this->redirect2listView('sweet-success', $message); return $this->redirect2listView('sweet-success', $message);
@ -220,30 +221,48 @@ class Maquinastarifasimpresion extends \App\Controllers\BaseResourceController
$response = Editor::inst($db, 'lg_maquinas_tarifas_impresion') $response = Editor::inst($db, 'lg_maquinas_tarifas_impresion')
->fields( ->fields(
Field::inst('uso') Field::inst('uso')
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('MaquinasTarifasImpresions.validation.uso.required')) 'Validate::notEmpty',
array(
'message' => lang('MaquinasTarifasImpresions.validation.uso.required')
)
), ),
Field::inst('tipo') Field::inst('tipo')
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('MaquinasTarifasImpresions.validation.tipo.required')) 'Validate::notEmpty',
array(
'message' => lang('MaquinasTarifasImpresions.validation.tipo.required')
)
), ),
Field::inst('precio') Field::inst('precio')
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar') ->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator('Validate::numeric', array( ->validator(
'Validate::numeric',
array(
"decimal" => ',', "decimal" => ',',
'message' => lang('MaquinasTarifasImpresions.validation.precio.decimal')) 'message' => lang('MaquinasTarifasImpresions.validation.precio.decimal')
)
) )
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('MaquinasTarifasImpresions.validation.tipo.required')) 'Validate::notEmpty',
array(
'message' => lang('MaquinasTarifasImpresions.validation.tipo.required')
)
), ),
Field::inst('margen') Field::inst('margen')
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar') ->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator('Validate::numeric', array( ->validator(
'Validate::numeric',
array(
"decimal" => ',', "decimal" => ',',
'message' => lang('MaquinasTarifasImpresions.validation.precio.decimal')) 'message' => lang('MaquinasTarifasImpresions.validation.precio.decimal')
)
) )
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('MaquinasTarifasImpresions.validation.tipo.required')) 'Validate::notEmpty',
array(
'message' => lang('MaquinasTarifasImpresions.validation.tipo.required')
)
), ),
Field::inst('maquina_id'), Field::inst('maquina_id'),
Field::inst('user_created_id'), Field::inst('user_created_id'),
@ -269,16 +288,21 @@ class Maquinastarifasimpresion extends \App\Controllers\BaseResourceController
'maquina_id' => $values['maquina_id'], 'maquina_id' => $values['maquina_id'],
'tipo' => $values['tipo'], 'tipo' => $values['tipo'],
'uso' => $values['uso'], 'uso' => $values['uso'],
'is_deleted' => 0)); 'is_deleted' => 0
));
$id = $builder->get()->getFirstRow()->id; $id = $builder->get()->getFirstRow();
if ($id) {
$id = $id->id;
// No se pueden duplicar valores al crear o al editar
if ($builder->countAllResults() >= 1) {
if (
($action === Editor::ACTION_EDIT && $id != $pkey)
|| $action === Editor::ACTION_CREATE
) {
// No se pueden duplicar valores al crear o al editar return lang('MaquinasTarifasImpresions.validation.duplicated_uso_tipo');
if ($builder->countAllResults() >= 1) { }
if (($action === Editor::ACTION_EDIT && $id != $pkey)
|| $action === Editor::ACTION_CREATE) {
return lang('MaquinasTarifasImpresions.validation.duplicated_uso_tipo');
} }
} }
} }
@ -413,11 +437,11 @@ class Maquinastarifasimpresion extends \App\Controllers\BaseResourceController
protected function getMaquinaListItems($selId = null) protected function getMaquinaListItems($selId = null)
{ {
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Maquinas.maquina'))])]; $data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Maquinas.maquina'))])];
if (!empty($selId)) : if (!empty($selId)):
$maquinaModel = model('App\Models\Configuracion\MaquinaModel'); $maquinaModel = model('App\Models\Configuracion\MaquinaModel');
$selOption = $maquinaModel->where('id', $selId)->findColumn('nombre'); $selOption = $maquinaModel->where('id', $selId)->findColumn('nombre');
if (!empty($selOption)) : if (!empty($selOption)):
$data[$selId] = $selOption[0]; $data[$selId] = $selOption[0];
endif; endif;
endif; endif;

View File

@ -244,23 +244,15 @@ class Papelformato extends \App\Controllers\BaseResourceController {
public function menuItems() { public function menuItems() {
if ($this->request->isAJAX()) { if ($this->request->isAJAX()) {
$searchStr = goSanitize($this->request->getPost('searchTerm'))[0]; $papelFormatoModel = model('App\Models\Configuracion\PapelFormatoModel');
$reqId = goSanitize($this->request->getPost('id'))[0]; $searchStr = goSanitize($this->request->getPfgost('searchTerm'))[0];
$reqText = goSanitize($this->request->getPost('text'))[0]; $menu = $papelFormatoModel->getElementsForMenu2($searchStr);
$onlyActiveOnes = false; if(empty(($searchStr)))
$columns2select = [$reqId ?? 'id', $reqText ?? 'ancho']; array_shift($menu);
$onlyActiveOnes = false;
$menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr);
$nonItem = new \stdClass;
$nonItem->id = '';
$nonItem->text = '- '.lang('Basic.global.None').' -';
array_unshift($menu , $nonItem);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [ $data = [
'menu' => $menu, 'menu' => $menu,
$csrfTokenName => $newTokenHash
]; ];
return $this->respond($data); return $this->respond($data);
} else { } else {
@ -268,4 +260,15 @@ class Papelformato extends \App\Controllers\BaseResourceController {
} }
} }
public function getSelect2()
{
if ($this->request->isAJAX()) {
$data = $this->model->getElementsForMenu2($this->request->getGet("q"));
return $this->response->setJSON($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
} }

View File

@ -0,0 +1,268 @@
<?php namespace App\Controllers\Configuracion;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
use App\Entities\Configuracion\SeriesFacturasEntity;
use App\Models\Configuracion\SeriesFacturasModel;
class SeriesFacturas extends BaseResourceController
{
protected $modelName = SeriesFacturasModel::class;
protected $format = 'json';
protected static $singularObjectName = 'Series Facturas';
protected static $singularObjectNameCc = 'seriesFacturas';
protected static $pluralObjectName = 'Series Facturas';
protected static $pluralObjectNameCc = 'seriesFacturas';
protected static $controllerSlug = 'ubicaciones';
protected static $viewPath = 'themes/vuexy/form/configuracion/series-facturas/';
protected $indexRoute = 'seriesFacturasList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = lang('SeriesFacturas.moduleTitle');
$this->viewData['usingSweetAlert'] = true;
// Breadcrumbs (IMN)
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_series_facturas"), 'route' => route_to('seriesFacturasList'), 'active' => true]
];
parent::initController($request, $response, $logger);
}
public function index()
{
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('SeriesFacturas.moduleTitle')]),
'seriesFacturasEntity' => new SeriesFacturasEntity(),
'usingServerSideDataTable' => true,
];
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
return view(static::$viewPath . 'viewSeriesFacturasList', $viewData);
}
public function add()
{
if ($this->request->getPost()) :
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, true);
$noException = true;
if ($successfulResult = $this->canValidate()) :
if ($this->canValidate()) :
try {
$successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['errorMessage'] = lang('Basic.global.formErr1', [lang('Basic.global.record')]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$thenRedirect = true; // Change this to false if you want your user to stay on the form after submission
endif;
if ($noException && $successfulResult) :
$id = $this->model->db->insertID();
$message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else:
return $this->redirect2listView('sweet-success', $message);
endif;
else:
$this->session->setFlashData('sweet-success', $message);
endif;
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$this->viewData['seriesFacturasEntity'] = isset($sanitizedData) ? new SeriesFacturasEntity($sanitizedData) : new SeriesFacturasEntity();
$this->viewData['formAction'] = route_to('seriesFacturasAdd');
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('SeriesFacturas.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix');
return $this->displayForm(__METHOD__);
} // end function add()
public function edit($requestedId = null)
{
if ($requestedId == null) :
return $this->redirect2listView();
endif;
$id = filter_var($requestedId, FILTER_SANITIZE_URL);
$seriesFacturasEntity = $this->model->find($id);
if ($seriesFacturasEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('SeriesFacturas.moduleTitle')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
if ($this->request->getPost()) :
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, true);
if ($this->request->getPost('show_erp') == null) {
$sanitizedData['show_erp'] = false;
}
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) :
try {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('SeriesFacturas.moduleTitle'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$seriesFacturasEntity->fill($sanitizedData);
$thenRedirect = false;
endif;
if ($noException && $successfulResult) :
$id = $seriesFacturasEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else:
return $this->redirect2listView('sweet-success', $message);
endif;
else:
$this->session->setFlashData('sweet-success', $message);
endif;
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$this->viewData['seriesFacturasEntity'] = $seriesFacturasEntity;
$this->viewData['formAction'] = route_to('seriesFacturasEdit', $id);
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('SeriesFacturas.moduleTitle') . ' ' . lang('Basic.global.edit3');
return $this->displayForm(__METHOD__, $id);
} // end function edit(...)
public function datatable()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
$errstr = 'No data available in response to this specific request.';
$response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr);
return $response;
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 1;
$order = SeriesFacturasModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 1];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource()->countAllResults(),
$this->model->getResource($search)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function allItemsSelect()
{
if ($this->request->isAJAX()) {
$onlyActiveOnes = true;
$reqVal = $this->request->getPost('val') ?? 'id';
$menu = $this->model->getAllForMenu($reqVal . ', nombre', 'nombre', $onlyActiveOnes, false);
$nonItem = new \stdClass;
$nonItem->id = '';
$nonItem->nombre = '- ' . lang('Basic.global.None') . ' -';
array_unshift($menu, $nonItem);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'menu' => $menu,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function menuItems()
{
if ($this->request->isAJAX()) {
$searchStr = goSanitize($this->request->getPost('searchTerm'))[0];
$reqId = goSanitize($this->request->getPost('id'))[0];
$reqText = goSanitize($this->request->getPost('text'))[0];
$onlyActiveOnes = false;
$columns2select = [$reqId ?? 'id', $reqText ?? 'nombre'];
$onlyActiveOnes = false;
$menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr);
$nonItem = new \stdClass;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'menu' => $menu,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function menuItemsFacturas()
{
if ($this->request->isAJAX()) {
$menu = $this->model->getMenuItemsFacturas();
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'menu' => $menu,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -0,0 +1,257 @@
<?php namespace App\Controllers\Configuracion;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
use App\Entities\Configuracion\UbicacionesEntity;
use App\Models\Configuracion\UbicacionesModel;
class Ubicaciones extends BaseResourceController
{
protected $modelName = UbicacionesModel::class;
protected $format = 'json';
protected static $singularObjectName = 'Ubicaciones';
protected static $singularObjectNameCc = 'ubicaciones';
protected static $pluralObjectName = 'Ubicaciones';
protected static $pluralObjectNameCc = 'ubicaciones';
protected static $controllerSlug = 'ubicaciones';
protected static $viewPath = 'themes/vuexy/form/configuracion/ubicaciones/';
protected $indexRoute = 'ubicacionesList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = lang('Ubicaciones.moduleTitle');
$this->viewData['usingSweetAlert'] = true;
// Breadcrumbs (IMN)
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_ubicaciones"), 'route' => route_to('ubicacionesList'), 'active' => true]
];
parent::initController($request, $response, $logger);
}
public function index()
{
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Ubicaciones.pais')]),
'ubicacionesEntity' => new UbicacionesEntity(),
'usingServerSideDataTable' => true,
];
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
return view(static::$viewPath . 'viewUbicacionesList', $viewData);
}
public function add()
{
if ($this->request->getPost()) :
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, true);
$noException = true;
if ($successfulResult = $this->canValidate()) :
if ($this->canValidate()) :
try {
$successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['errorMessage'] = lang('Basic.global.formErr1', [lang('Basic.global.record')]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$thenRedirect = true; // Change this to false if you want your user to stay on the form after submission
endif;
if ($noException && $successfulResult) :
$id = $this->model->db->insertID();
$message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else:
return $this->redirect2listView('sweet-success', $message);
endif;
else:
$this->session->setFlashData('sweet-success', $message);
endif;
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$this->viewData['ubicacionesEntity'] = isset($sanitizedData) ? new UbicacionesEntity($sanitizedData) : new UbicacionesEntity();
$this->viewData['formAction'] = route_to('ubicacionesAdd');
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Ubicaciones.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix');
return $this->displayForm(__METHOD__);
} // end function add()
public function edit($requestedId = null)
{
if ($requestedId == null) :
return $this->redirect2listView();
endif;
$id = filter_var($requestedId, FILTER_SANITIZE_URL);
$ubicacionesEntity = $this->model->find($id);
if ($ubicacionesEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Ubicaciones.moduleTitle')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
if ($this->request->getPost()) :
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, true);
if ($this->request->getPost('show_erp') == null) {
$sanitizedData['show_erp'] = false;
}
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) :
try {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Ubicaciones.moduleTitle'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$ubicacionesEntity->fill($sanitizedData);
$thenRedirect = false;
endif;
if ($noException && $successfulResult) :
$id = $ubicacionesEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else:
return $this->redirect2listView('sweet-success', $message);
endif;
else:
$this->session->setFlashData('sweet-success', $message);
endif;
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$this->viewData['ubicacionesEntity'] = $ubicacionesEntity;
$this->viewData['formAction'] = route_to('ubicacionesEdit', $id);
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Ubicaciones.moduleTitle') . ' ' . lang('Basic.global.edit3');
return $this->displayForm(__METHOD__, $id);
} // end function edit(...)
public function datatable()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
$errstr = 'No data available in response to this specific request.';
$response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr);
return $response;
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 1;
$order = UbicacionesModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 1];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource()->countAllResults(),
$this->model->getResource($search)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function allItemsSelect()
{
if ($this->request->isAJAX()) {
$onlyActiveOnes = true;
$reqVal = $this->request->getPost('val') ?? 'id';
$menu = $this->model->getAllForMenu($reqVal . ', nombre', 'nombre', $onlyActiveOnes, false);
$nonItem = new \stdClass;
$nonItem->id = '';
$nonItem->nombre = '- ' . lang('Basic.global.None') . ' -';
array_unshift($menu, $nonItem);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'menu' => $menu,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function menuItems()
{
if ($this->request->isAJAX()) {
$searchStr = goSanitize($this->request->getPost('searchTerm'))[0];
$reqId = goSanitize($this->request->getPost('id'))[0];
$reqText = goSanitize($this->request->getPost('text'))[0];
$onlyActiveOnes = false;
$columns2select = [$reqId ?? 'id', $reqText ?? 'nombre'];
$onlyActiveOnes = false;
$menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr);
$nonItem = new \stdClass;
$nonItem->id = '';
$nonItem->text = '- ' . lang('Basic.global.None') . ' -';
array_unshift($menu, $nonItem);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'menu' => $menu,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -1,22 +1,27 @@
<?php namespace App\Controllers\Configuracion; <?php namespace App\Controllers\Configuracion;
use App\Entities\Usuarios\UserEntity; use App\Entities\Usuarios\UserEntity;
use App\Models\Chat\ChatDeparmentModel;
use App\Models\Chat\ChatDeparmentUserModel;
use App\Models\Usuarios\GroupModel; use App\Models\Usuarios\GroupModel;
use App\Models\UserModel; use App\Models\UserModel;
use App\Models\Usuarios\GroupsUsersModel; use App\Models\Usuarios\GroupsUsersModel;
use CodeIgniter\Shield\Entities\User; use CodeIgniter\Shield\Entities\User;
use function PHPUnit\Framework\isNull;
class Users extends \App\Controllers\GoBaseController { class Users extends \App\Controllers\GoBaseController
{
private $group_model; private $group_model;
private $group_user_model; private $group_user_model;
private $user_model; private $user_model;
private ChatDeparmentModel $chat_department_model;
private ChatDeparmentUserModel $chat_department_user_model;
use \CodeIgniter\API\ResponseTrait;
use \CodeIgniter\API\ResponseTrait;
protected static $primaryModelName = 'App\Models\UserModel'; protected static $primaryModelName = 'App\Models\UserModel';
@ -30,12 +35,15 @@ class Users extends \App\Controllers\GoBaseController {
protected $indexRoute = 'userList'; protected $indexRoute = 'userList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) { {
$this->group_model = new GroupModel(); $this->group_model = new GroupModel();
$this->group_user_model = new GroupsUsersModel(); $this->group_user_model = new GroupsUsersModel();
$this->user_model = new UserModel(); $this->user_model = new UserModel();
$this->chat_department_model = model(ChatDeparmentModel::class);
$this->chat_department_user_model = model(ChatDeparmentUserModel::class);
$this->viewData['pageTitle'] = lang('Users.moduleTitle'); $this->viewData['pageTitle'] = lang('Users.moduleTitle');
@ -49,68 +57,96 @@ class Users extends \App\Controllers\GoBaseController {
} }
public function index() { public function index()
{
$this->viewData['usingClientSideDataTable'] = true; $this->viewData['usingClientSideDataTable'] = true;
$this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Users.user')]); $this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Users.user')]);
$this->viewData['user_model'] = $this->user_model; $this->viewData['user_model'] = $this->user_model;
$this->viewData['userList2'] = auth()->getProvider()->findAll();
parent::index(); parent::index();
} }
public function add() { public function add()
{
if ($this->request->getPost()) : if ($this->request->getPost()) :
$postData = $this->request->getPost(); $postData = $this->request->getPost();
$currentGroups = $postData['group']??[]; // Obtener contraseña nueva si se ha introducido en texto plano
if (empty($postData['new_pwd'])) {
$postData['password'] = 'Safekat2024'; // Contraseña por defecto
}else{
$postData['password'] = $postData['new_pwd'];
}
// Obtener los grupos a los que pertenece
$currentGroups = $postData['group'] ?? [];
$chatDepartments = $postData['chatDepartments'] ?? [];
unset($postData['group']); unset($postData['group']);
unset($postData['chatDepartments']);
$sanitizedData = $this->sanitized($postData, true); // Generar el nombre de usuario
$postData['username'] = strstr($postData['email'], '@', true);
$sanitizedData = $this->sanitized($postData, true);
$noException = true; $noException = true;
// Obtener proveedor de usuarios
$users = auth()->getProvider(); $users = auth()->getProvider();
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : if ($successfulResult = $this->canValidate()) :
if ($this->canValidate()) :
if ($this->canValidate()) : try {
try {
$user = new User([ $user = new User([
'username' => strstr($sanitizedData['email'], '@', true), 'username' => $sanitizedData['username'],
'email' => $sanitizedData['email'], 'first_name' => $sanitizedData['first_name'],
'password' => 'Safekat2024', 'last_name' => $sanitizedData['last_name'],
'email' => $sanitizedData['email'],
'password' => $sanitizedData['password'],
'status' => $sanitizedData['status'] ?? 0,
'active' => $sanitizedData['active'] ?? 0,
]); ]);
$users->save($user); $users->save($user);
$successfulResult = true; // Hacked $successfulResult = true; // Hacked
} catch (\Exception $e) { } catch (\Exception $e) {
$noException = false; $noException = false;
$this->dealWithException($e); //$this->dealWithException($e);
} if (strpos($e->getMessage(), 'correo duplicado') !== false) {
else: $this->viewData['errorMessage'] = "El correo electrónico ya está registrado en el sistema";
$this->viewData['errorMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Users.user'))]); $this->session->setFlashdata('formErrors', $this->model->errors());
$this->session->setFlashdata('formErrors', $this->model->errors()); }
endif;
$thenRedirect = true; // Change this to false if you want your user to stay on the form after submission }
else:
$this->viewData['errorMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Users.user'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$thenRedirect = true; // Change this to false if you want your user to stay on the form after submission
endif; endif;
if ($noException && $successfulResult) : if ($noException && $successfulResult) :
$id = $users->getInsertID(); $id = $users->getInsertID();
$this->group_user_model->where('user_id', $user->id)->delete(); $this->group_user_model->where('user_id', $id)->delete();
foreach($currentGroups as $group){ foreach ($currentGroups as $group) {
$group_user_data = [ $group_user_data = [
'user_id' => $user->id, 'user_id' => $id,
'group' => $group 'group' => $group
]; ];
$this->group_user_model->insert($group_user_data); $this->group_user_model->insert($group_user_data);
} }
$this->chat_department_user_model->where("user_id",$id)->delete();
foreach($chatDepartments as $chatDepartment)
{
$this->chat_department_user_model->insert([
"user_id" => $id,
"chat_department_id" => $this->chat_department_model->where("name",$chatDepartment)->first()["id"]
]);
}
$message = lang('Basic.global.saveSuccess', [mb_strtolower(lang('Users.user'))]) . 'Downloads'; $message = lang('Basic.global.saveSuccess', [mb_strtolower(lang('Users.user'))]) . '.';
$message .= anchor(route_to('editUser', $id), lang('Basic.global.continueEditing').'?');
$message = ucfirst(str_replace("'", "\'", $message)); $message = ucfirst(str_replace("'", "\'", $message));
if ($thenRedirect) : if ($thenRedirect) :
@ -128,75 +164,106 @@ class Users extends \App\Controllers\GoBaseController {
endif; // ($requestMethod === 'post') endif; // ($requestMethod === 'post')
$this->viewData['user'] = isset($sanitizedData) ? new UserEntity($sanitizedData) : new UserEntity(); $this->viewData['user'] = isset($sanitizedData) ? new UserEntity($sanitizedData) : new UserEntity();
$this->viewData['clienteList'] = $this->getClienteListItems();
$this->viewData['formAction'] = route_to('createUser'); $this->viewData['formAction'] = route_to('createUser');
$this->viewData['groups'] = $this->group_model->select('keyword, title')->findAll(); $this->viewData['groups'] = $this->group_model->select('keyword, title')->findAll();
$this->viewData['boxTitle'] = lang('Basic.global.addNew') .lang('Users.user').' '.lang('Basic.global.addNewSuffix'); $this->viewData['chatDepartments'] = $this->chat_department_model->findAll();
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Users.user') . ' ' . lang('Basic.global.addNewSuffix');
return $this->displayForm(__METHOD__); return $this->displayForm(__METHOD__);
} // end function add() } // end function add()
public function edit($requestedId = null) { public function edit($requestedId = null)
{
if ($requestedId == null) : if ($requestedId == null) {
return $this->redirect2listView(); return $this->redirect2listView();
endif; }
$id = filter_var($requestedId, FILTER_SANITIZE_URL); $id = filter_var($requestedId, FILTER_SANITIZE_URL);
$user = $this->model->find($id); $users = auth()->getProvider();
$user = $users->findById($id);
if ($user == false) : if ($user == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Users.user')), $id]); $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Users.user')), $id]);
return $this->redirect2listView('errorMessage', $message); return $this->redirect2listView('errorMessage', $message);
endif; endif;
if ($this->request->getPost()) : if ($this->request->getPost()) :
$postData = $this->request->getPost(); $postData = $this->request->getPost();
$currentGroups = $postData['group']; $currentGroups = $postData['group'] ?? [];
$chatDepartments = $postData['chatDepartments'] ?? [];
unset($postData['group']); unset($postData['group']);
unset($postData['chatDepartments']);
// Obtener contraseña nueva si se ha introducido en texto plano
// Obtener contraseña nueva si se ha introducido en texto plano
if (!empty($postData['new_pwd'])) {
$postData['password'] = $postData['new_pwd'];
}
$sanitizedData = $this->sanitized($postData, true); $sanitizedData = $this->sanitized($postData, true);
if ($this->request->getPost('status') == 0 ) { if ($this->request->getPost('status') == 0) {
$sanitizedData['status'] = null; $sanitizedData['status'] = null;
} }
$noException = true; $noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : if ($successfulResult = $this->canValidate()) :
if ($this->canValidate()) : if ($this->canValidate()) :
try { try {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Users.user'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif; if (in_array('cliente-editor', $currentGroups) || in_array('cliente-administrador', $currentGroups)) {
if (!array_key_exists('cliente_id', $sanitizedData) || is_null($sanitizedData['cliente_id'])) {
$this->viewData['errorMessage'] = lang('Users.errors.cliente_sin_clienteID');
$this->session->setFlashdata('formErrors', $this->model->errors());
$successfulResult = false;
} else {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
}
} else {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
}
$user->fill($sanitizedData); } catch (\Exception $e) {
$thenRedirect = false; $noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Users.user'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$user->fill($sanitizedData);
$users->save($user);
$thenRedirect = false;
endif; endif;
if ($noException && $successfulResult) : if ($noException && $successfulResult) :
$this->group_user_model->where('user_id', $user->id)->delete(); $this->group_user_model->where('user_id', $user->id)->delete();
foreach($currentGroups as $group){ foreach ($currentGroups as $group) {
$group_user_data = [ $group_user_data = [
'user_id' => $user->id, 'user_id' => $user->id,
'group' => $group 'group' => $group
]; ];
$this->group_user_model->insert($group_user_data); $this->group_user_model->insert($group_user_data);
} }
$this->chat_department_user_model->where("user_id",$id)->delete();
foreach($chatDepartments as $chatDepartment)
{
$this->chat_department_user_model->insert([
"user_id" => $id,
"chat_department_id" => $this->chat_department_model->where("name",$chatDepartment)->first()["id"]
]);
}
$id = $user->id ?? $id; $id = $user->id ?? $id;
$message = lang('Basic.global.updateSuccess', [mb_strtolower(lang('Users.user'))]) . 'Downloads'; $message = lang('Basic.global.updateSuccess', [mb_strtolower(lang('Users.user'))]) . '.';
$message .= anchor(route_to('editUser', $id), lang('Basic.global.continueEditing').'?');
$message = ucfirst(str_replace("'", "\'", $message)); $message = ucfirst(str_replace("'", "\'", $message));
if ($thenRedirect) : if ($thenRedirect) :
@ -213,16 +280,20 @@ class Users extends \App\Controllers\GoBaseController {
endif; // ($requestMethod === 'post') endif; // ($requestMethod === 'post')
$this->viewData['user'] = $user; $this->viewData['user'] = $user;
$this->viewData['clienteList'] = $this->getClienteListItems($user->cliente_id);
$this->viewData['formAction'] = route_to('updateUser', $id); $this->viewData['formAction'] = route_to('updateUser', $id);
$this->viewData['selectedGroups'] = $this->group_model->getUsersRoles($requestedId); $this->viewData['selectedGroups'] = $this->group_model->getUsersRoles($requestedId);
$this->viewData['groups'] = $this->group_model->select('keyword, title')->findAll(); $this->viewData['groups'] = $this->group_model->select('keyword, title')->findAll();
$this->viewData['boxTitle'] = lang('Basic.global.edit2') .lang('Users.user').' '.lang('Basic.global.edit3'); $this->viewData['chatDepartments'] = $this->chat_department_model->select(["display","name","id as chatDepartmentId"])->findAll();
$this->viewData['chatDepartmentUser'] = $this->chat_department_user_model->getChatDepartmentUser($user->id);
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Users.user') . ' ' . lang('Basic.global.edit3');
return $this->displayForm(__METHOD__, $id); return $this->displayForm(__METHOD__, $id);
} // end function edit(...) } // end function edit(...)
public function delete($requestedId = null, bool $deletePermanently = true) { public function delete($requestedId = null, bool $deletePermanently = true)
{
if ($requestedId == null) : if ($requestedId == null) :
return $this->redirect2listView(); return $this->redirect2listView();
@ -237,26 +308,25 @@ class Users extends \App\Controllers\GoBaseController {
endif; endif;
$users = auth()->getProvider(); $users = auth()->getProvider();
$users->delete($user->id, $deletePermanently); $users->delete($user->id);
$message = "Usuario eliminado correctamente"; $message = "Usuario eliminado correctamente";
return $this->redirect2listView('successMessage', $message); return $this->redirect2listView('successMessage', $message);
} // end function delete(...) } // end function delete(...)
public function allItemsSelect()
public function allItemsSelect() { {
if ($this->request->isAJAX()) { if ($this->request->isAJAX()) {
$onlyActiveOnes = true; $onlyActiveOnes = true;
$reqVal = $this->request->getPost('val') ?? 'id_user'; $reqVal = $this->request->getPost('val') ?? 'id_user';
$menu = $this->model->getAllForMenu($reqVal.', first_name', 'first_name', $onlyActiveOnes, false); $menu = $this->model->getAllForMenu($reqVal . ', first_name', 'first_name', $onlyActiveOnes, false);
$nonItem = new \stdClass; $nonItem = new \stdClass;
$nonItem->id_user = ''; $nonItem->id_user = '';
$nonItem->first_name = '- '.lang('Basic.global.None').' -'; $nonItem->first_name = '- ' . lang('Basic.global.None') . ' -';
array_unshift($menu , $nonItem); array_unshift($menu, $nonItem);
$newTokenHash = csrf_hash(); $newTokenHash = csrf_hash();
$csrfTokenName = csrf_token(); $csrfTokenName = csrf_token();
@ -270,7 +340,8 @@ class Users extends \App\Controllers\GoBaseController {
} }
} }
public function menuItems() { public function menuItems()
{
if ($this->request->isAJAX()) { if ($this->request->isAJAX()) {
$searchStr = goSanitize($this->request->getPost('searchTerm'))[0]; $searchStr = goSanitize($this->request->getPost('searchTerm'))[0];
$reqId = goSanitize($this->request->getPost('id'))[0]; $reqId = goSanitize($this->request->getPost('id'))[0];
@ -281,8 +352,8 @@ class Users extends \App\Controllers\GoBaseController {
$menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr); $menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr);
$nonItem = new \stdClass; $nonItem = new \stdClass;
$nonItem->id = ''; $nonItem->id = '';
$nonItem->text = '- '.lang('Basic.global.None').' -'; $nonItem->text = '- ' . lang('Basic.global.None') . ' -';
array_unshift($menu , $nonItem); array_unshift($menu, $nonItem);
$newTokenHash = csrf_hash(); $newTokenHash = csrf_hash();
$csrfTokenName = csrf_token(); $csrfTokenName = csrf_token();
@ -296,14 +367,46 @@ class Users extends \App\Controllers\GoBaseController {
} }
} }
public function getMenuComerciales()
{
if ($this->request->isAJAX()) {
$comerciales = $this->model->getComerciales();
protected function getPaisListItems() { $newTokenHash = csrf_hash();
$data = [''=>lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Pais.pais'))])]; $csrfTokenName = csrf_token();
$data = [
'menu' => $comerciales,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
protected function getPaisListItems()
{
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Pais.pais'))])];
$paisModel = model('App\Models\Configuracion\PaisModel'); $paisModel = model('App\Models\Configuracion\PaisModel');
$registers = $paisModel->findAll(); $registers = $paisModel->findAll();
return $registers; return $registers;
} }
protected function getClienteListItems($selId = null)
{
$data = ['' => ""];
if (!empty($selId)) :
$clienteModel = model('App\Models\Clientes\ClienteModel');
$selOption = $clienteModel->where('id', $selId)->findColumn('nombre');
if (!empty($selOption)) :
$data[$selId] = $selOption[0];
endif;
endif;
return $data;
}
} }

View File

@ -0,0 +1,82 @@
<?php
namespace App\Controllers\Excel;
use App\Controllers\BaseController;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class PrintGiros extends BaseController
{
public function generateExcel($factura_id = null)
{
// AQUI CREAR LAS CONSULTAS A LA BBDD, QUIZAS HAYA QUE CREARLO O COMO POST O COMO QUERY AJAX
// Crear un nuevo Spreadsheet
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// Especificar encabezados
$headers = [
'BIC (SWIFT)*',
'FECHA FIRMA MANDATO*',
'IBAN*',
'IMPORTE*',
'NOMBRE*',
'PAIS*',
'REFERENCIA DEL ADEUDO (REFADEUDO)*',
'REFERENCIA*',
'REFERENCIA DEL MANDATO (REMANDATO)*',
'RESIDENTE*',
'TIPO DE ADEUDO*',
'FECHA DE COBRO*',
'DIAS*'
];
// Establecer los encabezados en la primera fila
$column = 'A';
foreach ($headers as $header) {
$sheet->setCellValue($column . '1', $header);
$column++;
}
// Generar datos dummy
$dummyData = [
['ABCDEF12', '2024-01-01', 'ES1234567890123456789012', 100.50, 'John Doe', 'Spain', 'REF001', '12345', 'MAND001', 'Yes', 'Type1', '2024-02-01', 30],
['GHIJKL34', '2024-02-01', 'ES9876543210987654321098', 200.75, 'Jane Smith', 'France', 'REF002', '67890', 'MAND002', 'No', 'Type2', '2024-03-01', 60],
// Añade más datos dummy según sea necesario
];
// Rellenar las filas con datos dummy
$rowNumber = 2; // Empezar en la segunda fila
foreach ($dummyData as $row) {
$column = 'A';
foreach ($row as $cell) {
$sheet->setCellValue($column . $rowNumber, $cell);
$column++;
}
$rowNumber++;
}
// Ajustar automáticamente el tamaño de las columnas
foreach (range('A', $column) as $col) {
$sheet->getColumnDimension($col)->setAutoSize(true);
}
// Crear un escritor para guardar el archivo
$writer = new Xlsx($spreadsheet);
// Configurar la respuesta para descarga
$fileName = 'giros_reporte.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $fileName . '"');
header('Cache-Control: max-age=0');
// Escribir el archivo a la salida
$writer->save('php://output');
exit;
}
}

View File

@ -0,0 +1,70 @@
<?php
namespace App\Controllers\Excel;
use App\Controllers\BaseController;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class PrintLineas extends BaseController
{
public function generateExcel($factura_id = null)
{
// Modelos
$lineasFacturaModel = model('App\Models\Facturas\FacturaLineaModel');
$infoLineasFactura = $lineasFacturaModel->getResourceForExcel($factura_id)->get()->getResultObject();
// Crear un nuevo Spreadsheet
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// Especificar encabezados
$headers = [
'Factura',
'ID Pedido',
'Ref. Cliente',
'Base'
];
// Establecer los encabezados en la primera fila
$column = 'A';
foreach ($headers as $header) {
$sheet->setCellValue($column . '1', $header);
$column++;
}
// Rellenar las filas con datos
$rowNumber = 2; // Empezar en la segunda fila
foreach ($infoLineasFactura as $infoLineaFactura) {
$column = 'A';
foreach ($infoLineaFactura as $cell) {
$sheet->setCellValue($column . $rowNumber, $cell);
$column++;
}
$rowNumber++;
}
// Ajustar automáticamente el tamaño de las columnas
foreach (range('A', $column) as $col) {
$sheet->getColumnDimension($col)->setAutoSize(true);
}
// Crear un escritor para guardar el archivo
$writer = new Xlsx($spreadsheet);
// Configurar la respuesta para descarga
$fileName = 'lineas-pedido.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $fileName . '"');
header('Cache-Control: max-age=0');
// Escribir el archivo a la salida
$writer->save('php://output');
exit;
}
}

View File

@ -1,30 +0,0 @@
<?php
namespace App\Controllers\Facturacion;
use App\Controllers\BaseController;
class Albaran extends BaseController
{
function __construct()
{
}
public function index()
{
echo 'Albaran';
}
public function delete()
{
}
public function export()
{
}
}

View File

@ -1,41 +0,0 @@
<?php
namespace App\Controllers\Facturacion;
use App\Controllers\BaseController;
class Factura extends BaseController
{
function __construct()
{
}
public function index()
{
echo 'Facturas';
}
public function nueva()
{
echo 'Nueva Factura';
}
public function vencimiento()
{
echo 'Vencimiento Factura';
}
public function delete()
{
}
public function export()
{
}
}

View File

@ -0,0 +1,719 @@
<?php
namespace App\Controllers\Facturacion;
use App\Models\Facturas\FacturaModel;
use App\Entities\Facturas\FacturaEntity;
use App\Models\Clientes\ClienteModel;
use App\Models\Collection;
class Facturas extends \App\Controllers\BaseResourceController
{
protected $modelName = FacturaModel::class;
protected $format = 'json';
protected static $singularObjectNameCc = 'factura';
protected static $singularObjectName = 'Factura';
protected static $pluralObjectName = 'Facturas';
protected static $controllerSlug = 'factura';
protected static $viewPath = 'themes/vuexy/form/facturas/';
protected $indexRoute = 'facturaList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = lang('Facturas.facturas');
// Se indica que este controlador trabaja con soft_delete
$this->viewData = ['usingServerSideDataTable' => true];
// Breadcrumbs
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_facturas"), 'route' => "javascript:void(0);", 'active' => false],
];
parent::initController($request, $response, $logger);
}
public function index()
{
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
// Se obtiene el cliente ID a partir del usuario de la sesion
$model_user = model('App\Models\Usuarios\UserModel');
$user = $model_user->find(auth()->user()->id);
$clienteId = $user->cliente_id;
} else {
$clienteId = 0;
}
$this->viewData['cliente_id'] = $clienteId;
$this->viewData['usingClientSideDataTable'] = true;
$this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Tarifaextra.tarifaextra')]);
parent::index();
}
public function list()
{
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Facturas.facturas')]),
'usingServerSideDataTable' => true,
'pageTitle' => lang('Facturas.facturas'),
['title' => lang("App.menu_facturas"), 'route' => site_url('facturas/list'), 'active' => true]
];
$viewData['breadcrumb'] = [
['title' => lang("App.menu_facturas"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("Facturas.facturaList"), 'route' => "javascript:void(0);", 'active' => true]
];
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
// Se obtiene el cliente ID a partir del usuario de la sesion
$model_user = model('App\Models\Usuarios\UserModel');
$user = $model_user->find(auth()->user()->id);
$clienteId = $user->cliente_id;
} else {
$clienteId = 0;
}
$viewData['cliente_id'] = $clienteId;
return view(static::$viewPath . 'viewFacturasList', $viewData);
}
public function add()
{
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
$noException = true;
$allData = true;
if( !isset($postData['cliente_id']) || !isset($postData['serie_id']) ) {
$this->viewData['errorMessage'] = lang('Facturas.errors.requiredFields');
$this->session->setFlashdata('formErrors', $this->model->errors());
$allData = false;
$noException = false;
}
try {
$clienteModel = model('App\Models\Clientes\ClienteModel');
$datosCliente = $clienteModel->getClienteDataFacturas($postData['cliente_id']);
if(count($datosCliente)>0){
// add array data datosCliente to postData
$postData = array_merge($postData, $datosCliente[0]);
}
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
$sanitizedData['user_updated_id'] = auth()->user()->id;
$sanitizedData['user_created_id'] = auth()->user()->id;
if(!$sanitizedData['creditoAsegurado']){
$sanitizedData['creditoAsegurado'] = 0;
}
if ($allData && $successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) :
try {
$successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['errorMessage'] = lang('Basic.global.formErr1', [lang('Basic.global.record')]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
endif;
if ($noException && $successfulResult) :
$id = $this->model->db->insertID();
$message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';
return redirect()->to(route_to('editarFactura', $id))->with('sweet-success', $message);
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$this->viewData['factura'] = isset($sanitizedData) ? new FacturaEntity($sanitizedData) : new FacturaEntity();
$this->viewData['formAction'] = route_to('createFactura');
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Facturas.facturas') . ' ' . lang('Basic.global.addNewSuffix');
helper('form');
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_facturas"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("Facturas.facturaList"), 'route' => route_to('facturasList'), 'active' => true]
];
$this->viewData['usingSelect2'] = true;
$validation = \Config\Services::validation();
$this->viewData['validation'] = $validation;
$viewFilePath = static::$viewPath . 'viewAddFactura';
return view($viewFilePath, $this->viewData);
} // end function add()
public function edit($id=null){
if ($id == null) :
return $this->redirect2listView();
endif;
$id = filter_var($id, FILTER_SANITIZE_URL);
$factura = $this->model->find($id);
if ($factura == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Facturas.factura')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
$this->obtenerDatosFormulario($factura);
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_facturas"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("Facturas.facturaList"), 'route' => route_to('facturasList'), 'active' => true]
];
$this->viewData['facturaEntity'] = $factura;
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Facturas.factura') . ' ' . lang('Basic.global.edit3');
return $this->displayForm(__METHOD__, $id);
}
public function datatable(){
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
if (!isset($reqData['draw']) || !isset($reqData['columns']) ) {
$errstr = 'No data available in response to this specific request.';
$response = $this->respond(Collection::datatable( [], 0, 0, $errstr ), 400, $errstr);
return $response;
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 0;
$order = FacturaModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 0];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$cliente_id = $reqData['cliente_id'] ?? -1;
$resourceData = $this->model->getResource($search, $cliente_id)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource("", $cliente_id)->countAllResults(),
$this->model->getResource($search, $cliente_id)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function datatablePedidos(){
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
if (!isset($reqData['draw']) || !isset($reqData['columns']) ) {
$errstr = 'No data available in response to this specific request.';
$response = $this->respond(Collection::datatable( [], 0, 0, $errstr ), 400, $errstr);
return $response;
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 0;
$order = FacturaModel::SORTABLE_PEDIDOS[$requestedOrder >= 0 ? $requestedOrder : 0];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$pedido_id = $reqData['pedido_id'] ?? 0;
$resourceData = $this->model->getResourcePedidos($pedido_id)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResourcePedidos($pedido_id)->countAllResults(),
$this->model->getResourcePedidos($pedido_id)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function update($id = null){
if ($this->request->isAJAX()) {
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
if ($id == null) :
$data = [
'error' => 2,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif;
$id = filter_var($id, FILTER_SANITIZE_URL);
$facturaEntity = $this->model->find($id);
if ($facturaEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Factura.factura')), $id]);
$data = [
'error' => $message,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif;
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_updated_id'] = auth()->user()->id;
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) :
try {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Facturas.factura'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$facturaEntity->fill($sanitizedData);
endif;
if ($noException && $successfulResult) :
$id = $facturaEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
$data = [
'error' => 0,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$data = [
'error' => 1,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function menuPedidosPendientes($cliente_id){
if ($this->request->isAJAX()) {
$model = model('\App\Models\Pedidos\PedidoLineaModel');
$pedidos = [];
try{
$pedidos = $model->obtenerLineasPedidoSinFacturar($cliente_id);
}
catch(Exception $e){
}
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'menu' => $pedidos,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function duplicate($factura_id = 0){
if($this->request->isAJAX()){
$factura_origen = $this->model->find($factura_id);
// se quita la key "id" del objeto
unset($factura_origen->id);
$factura_origen->estado = 'borrador';
$factura_origen->estado_pago = 'pendiente';
$factura_origen->base = 0;
$factura_origen->total = 0;
$factura_origen->pendiente = 0;
$factura_origen->total_pagos = 0;
$factura_origen->user_created_id = auth()->user()->id;
$factura_origen->user_updated_id = null;
$this->model->insert($factura_origen);
$id = $this->model->getInsertID();
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'id' => $id,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}else{
return $this->failUnauthorized('Invalid request', 403);
}
}
public function updateTotales($factura_id = 0){
if($this->request->isAJAX()){
$postData = $this->request->getPost();
$pendiente = $postData['pendiente'] ?? 0;
$total = $postData['total'] ?? 0;
$data = [
'base' => $postData['base'] ?? 0,
'total' => $total,
'pendiente' => $pendiente,
'total_pagos' => $postData['total_pagos'] ?? 0,
'user_updated_id' => auth()->user()->id,
'estado_pago' => (intval($pendiente)==0 && intval($total)!=0) ? 'pagada' : 'pendiente',
];
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data_ret = [
$csrfTokenName => $newTokenHash
];
if($factura_id == 0){
return $this->respond($data_ret);
}
$data_ret['estado_pago'] = $data['estado_pago'];
$model = model('\App\Models\Facturas\FacturaModel');
$model->update($factura_id, $data);
return $this->respond($data_ret);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function addExcedentes($factura_id){
if ($this->request->isAJAX()) {
$model_factura_linea = model('\App\Models\Facturas\FacturaLineaModel');
$postData = $this->request->getPost();
$cantidad = $postData['cantidad'] ?? 0;
$precio_unidad = $postData['precio_unidad'] ?? 0;
$iva = $postData['iva'] ?? 0;
$descripcion = $postData['descripcion'] ?? '';
$descuento = $postData['descuento'] ?? 0;
$pedido_linea_impresion_id = $postData['pedido_linea_impresion_id'] ?? null;
$pedido_linea_maquetacion_id = $postData['pedido_linea_maquetacion_id'] ?? null;
$pedido_id = $postData['pedido_id'] ?? 0;
$nuevo_precio_unidad = round($precio_unidad*(100-floatval($descuento))/100, 4);
$base = round($cantidad * $nuevo_precio_unidad, 2);
$total_iva = round($base * $iva / 100, 2);
$data = (object)[
'factura_id'=>$factura_id,
'pedido_linea_impresion_id'=>$pedido_linea_impresion_id,
'pedido_linea_maquetacion_id'=>$pedido_linea_maquetacion_id,
'descripcion'=>$newString = preg_replace_callback('/Impresión de (\d+) ejemplares/', function ($matches) use ($cantidad) {
return 'Impresión de ' . $cantidad . ' ejemplares';
}, $descripcion),
'cantidad'=>$cantidad,
'precio_unidad'=> $nuevo_precio_unidad,
'iva' => $iva,
'base' => $base,
'total_iva' => $total_iva,
'total' => round($base + $total_iva, 2),
'user_updated_id' => auth()->user()->id,
];
$model_factura_linea->insert($data);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data_ret = [
$csrfTokenName => $newTokenHash
];
return $this->respond($data_ret);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function addLineaPedidoImpresion($factura_id){
if ($this->request->isAJAX()) {
$model_pedido_linea = model('\App\Models\Pedidos\PedidoLineaModel');
$model_presupuesto = model('\App\Models\Presupuestos\PresupuestoModel');
$model_factura_linea = model('\App\Models\Facturas\FacturaLineaModel');
try{
$pedido_linea_id = $this->request->getPost('lineaPedido') ?? 0;
$linea = $model_pedido_linea->find($pedido_linea_id);
$factura = $this->model->find($factura_id);
if($factura){
if($linea){
$presupuesto = $model_presupuesto->find($linea->presupuesto_id);
if($presupuesto){
// Se añade la linea de factura
$descripcion = $model_presupuesto->generarLineaPedido($presupuesto->id, true, $linea->pedido_id);
$cantidad = intval($presupuesto->tirada) - intval($this->model->getCantidadLineaPedidoFacturada($linea->id));
$base = $cantidad * floatval($presupuesto->total_precio_unidad);
$base = round($base, 2);
$total_iva = $base * ($presupuesto->iva_reducido==1 ? 0.04 : 0.21);
// se redondea a dos decimales
$total_iva = round($total_iva, 2);
$total = $base + $total_iva;
$data = (object)[
'factura_id'=>$factura_id,
'pedido_linea_impresion_id'=>$linea->pedido_id,
'descripcion'=>$descripcion[0]->concepto,
'cantidad'=>$cantidad,
'precio_unidad'=>$presupuesto->total_precio_unidad,
'iva' => $presupuesto->iva_reducido==1 ? 4 : 21,
'base' => $base,
'total_iva' => $total_iva,
'total' => $total,
'user_updated_id' => auth()->user()->id,
];
$model_factura_linea->insert($data);
$id = $model_factura_linea->getInsertID();
if($id){
$model_factura_linea->addFacturaPedidoLinea($factura_id, $linea->id, $cantidad);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'error' => 0,
'id' => $id,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
}
}
}
}
catch(Exception $e){
}
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function deleteLineaPedidoImpresion(){
if ($this->request->isAJAX()) {
$postData = $this->request->getPost();
$factura_id = $postData['factura_id'] ?? 0;
$linea_id = $postData['linea_id'] ?? 0;
$cantidad = $postData['cantidad'] ?? 0;
$model_factura_linea = model('\App\Models\Facturas\FacturaLineaModel');
$model_factura_linea->deleteFacturasLineasPedido($factura_id, $linea_id, $cantidad);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function validar($factura_id){
if($this->request->isAJAX()){
$factura = $this->model->find($factura_id);
if($factura){
$model_series = model('\App\Models\Configuracion\SeriesFacturasModel');
$numero = $model_series->getSerieNumerada($factura->serie_id);
$data = [
'estado' => 'validada',
'numero' => $numero,
'user_updated_id' => auth()->user()->id,
];
if((strpos($numero, "REC ") === 0)){
$data['estado_pago'] = 'pagada';
}
$this->model->update($factura_id, $data);
}
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function updateCabecera($factura_id){
if($this->request->isAJAX()){
if($factura_id == 0){
return;
}
$factura = $this->model->find($factura_id);
if($factura){
$postData = $this->request->getPost();
$dataName = $postData['name'] ?? '';
$dataValue = $postData['value'] ?? '';
if($dataName == 'factura_rectificativa_id'){
// se actualiza la factura donde el campo 'numero' sea igual al valor de $dataValue. El campo a actualizar es 'factura_rectificada_id'
$factura_rectificada = $this->model->where('numero', $dataValue)->first();
if($factura_rectificada){
$data2 = [
'factura_rectificada_id' => $factura->numero,
'user_updated_id' => auth()->user()->id,
];
$this->model->update($factura_rectificada->id, $data2);
}
}
$data = [
$dataName => $dataValue,
'user_updated_id' => auth()->user()->id,
];
$this->model->update($factura_id, $data);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
/*************************************
* FUNCIONES AUXILIARES
************************************/
private function obtenerDatosFormulario(&$factura){
if($factura->estado == 'borrador'){
$serieModel = model('App\Models\Configuracion\SeriesFacturasModel');
$serie = $serieModel->find($factura->serie_id);
if($serie){
$factura->numero = str_replace("{numero}", $serie->next, $serie->formato);
}
}
$clienteModel = model('App\Models\Clientes\ClienteModel');
$cliente = $clienteModel->find($factura->cliente_id);
$factura->cliente_alias = $cliente->alias;
$serieModel = model('App\Models\Configuracion\SeriesFacturasModel');
$serie = $serieModel->find($factura->serie_id);
$factura->serie_nombre = $serie->nombre;
$formaPagoModel = model('App\Models\Configuracion\FormaPagoModel');
$factura->formas_pago = $formaPagoModel->getMenuItems();
$factura->fecha_factura_at_text = $factura->fecha_factura_at ? date('d/m/Y', strtotime($factura->fecha_factura_at)) : '';
}
}

View File

@ -0,0 +1,228 @@
<?php
namespace App\Controllers\Facturacion;
use App\Models\Facturas\FacturaLineaModel;
use App\Models\Collection;
use DataTables\Editor;
use DataTables\Editor\Field;
use DataTables\Editor\Validate;
class FacturasLineas extends \App\Controllers\BaseResourceController
{
protected $modelName = FacturaLineaModel::class;
protected $format = 'json';
protected static $controllerSlug = 'factura-lineas';
public function datatable($factura_id = null){
if ($this->request->isAJAX() && $factura_id != null) {
$reqData = $this->request->getPost();
if (!isset($reqData['draw']) || !isset($reqData['columns']) ) {
$errstr = 'No data available in response to this specific request.';
$response = $this->respond(Collection::datatable( [], 0, 0, $errstr ), 400, $errstr);
return $response;
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 0;
//$order = FacturaModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 0];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$resourceData = $this->model->getResource($factura_id)->orderBy(1, $dir)->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource($factura_id)->countAllResults(),
$this->model->getResource($factura_id)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function deleteLinea($factura_linea_id = 0){
if (!empty(static::$pluralObjectNameCc) && !empty(static::$singularObjectNameCc)) {
$objName = mb_strtolower(lang(ucfirst(static::$pluralObjectNameCc).'.'.static::$singularObjectNameCc));
} else {
$objName = lang('Basic.global.record');
}
if($factura_linea_id == 0){
return $this->failNotFound(lang('Basic.global.deleteError', [$objName]));
}
$facturaLinea = $this->model->find($factura_linea_id);
if($facturaLinea == null){
return $this->failNotFound(lang('Basic.global.deleteError', [$objName]));
}
if($facturaLinea->pedido_linea_impresion_id != null){
$this->model->deleteFacturasLineasPedido($facturaLinea->factura_id, $facturaLinea->pedido_linea_impresion_id, $facturaLinea->cantidad);
}
if($facturaLinea->pedido_maquetacion_id != null){
//$this->model->deleteFacturasLineasPedido($facturaLinea->factura_id, $facturaLinea->pedido_maquetacion_id, $facturaLinea->cantidad);
}
$facturaLinea = $this->model->delete($factura_linea_id);
$message = lang('Basic.global.deleteSuccess', [lang('Basic.global.record')]);
$response = $this->respondDeleted(['id' => $factura_linea_id, 'msg' => $message]);
return $response;
}
public function datatable_editor() {
if ($this->request->isAJAX()) {
include(APPPATH . "ThirdParty/DatatablesEditor/DataTables.php");
// Build our Editor instance and process the data coming from _POST
$response = Editor::inst( $db, 'facturas_lineas' )
->fields(
Field::inst( 'id' ),
Field::inst( 'base' ),
Field::inst( 'total_iva' ),
Field::inst( 'total' ),
Field::inst( 'cantidad' )
->validator('Validate::numeric', array(
'message' => lang('Facturas.validation.numerico'))
)
->validator('Validate::notEmpty', array(
'message' => lang('Facturas.validation.requerido'))
),
Field::inst( 'descripcion' )
->validator('Validate::notEmpty', array(
'message' => lang('Facturas.validation.requerido'))
),
Field::inst( 'precio_unidad' )
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
->validator('Validate::numeric', array(
"decimal" => ',',
'message' => lang('Facturas.validation.decimal'))
)
->validator('Validate::notEmpty', array(
'message' => lang('Facturas.validation.requerido'))
),
Field::inst( 'iva' )
->validator('Validate::numeric', array(
'message' => lang('Facturas.validation.numerico'))
)
->validator('Validate::notEmpty', array(
'message' => lang('Facturas.validation.requerido'))
),
Field::inst( 'pedido_linea_impresion_id' )
->setFormatter(function($val, $data, $opts) {
return $val === '' ? null : $val;
}),
Field::inst( 'factura_id' ),
Field::inst( 'user_updated_id' ),
)
->on('preCreate', function ($editor, &$values) {
$totales = $this->generate_totales(
$values['factura_id'],
$values['pedido_linea_impresion_id'],
$values['precio_unidad'],
$values['iva'],
$values['cantidad'],
$values['old_cantidad']);
$editor
->field('user_updated_id')
->setValue(auth()->user()->id);
$editor
->field('base')
->setValue($totales['base']);
$editor
->field('total_iva')
->setValue($totales['total_iva']);
$editor
->field('total')
->setValue($totales['total']);
$editor
->field('user_updated_id')
->setValue(auth()->user()->id);
})
->on('preEdit', function ($editor, $id, &$values) {
$totales = $this->generate_totales(
$values['factura_id'],
$values['pedido_linea_impresion_id'],
$values['precio_unidad'],
$values['iva'],
$values['cantidad'],
$values['old_cantidad']);
$editor
->field('factura_id')
->setValue($values['factura_id']);
$editor
->field('pedido_linea_impresion_id')
->setValue(null);
$editor
->field('pedido_maquetacion_id')
->setValue(null);
$editor
->field('user_updated_id')
->setValue(auth()->user()->id);
$editor
->field('base')
->setValue($totales['base']);
$editor
->field('total_iva')
->setValue($totales['total_iva']);
$editor
->field('total')
->setValue($totales['total']);
})
->debug(true)
->process($_POST)
->data();
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$response[$csrfTokenName] = $newTokenHash;
echo json_encode($response);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function updateTotalesFactura($factura_id = 0){
if($factura_id == 0){
return;
}
$model = model('\App\Models\Facturas\FacturaModel');
$model->updateTotales($factura_id);
}
private function generate_totales($factura_id, $pedido_linea_id, $precio_unidad, $iva, $cantidad, $old_cantidad)
{
// si es una linea que se refiere a pedido
if ($pedido_linea_id != null && $factura_id != null) {
// se actualiza la cantidad de la linea de pedido en la tabla pivote facturas_pedidos_lineas
$this->model->updateFacturaPedidoLinea($factura_id, $pedido_linea_id, $old_cantidad, $cantidad);
}
// se calcula y se actualiza el subtotal, total_iva y total
// redondeando a 4 decimales el precio_unidad y a dos el resto
$base = round($precio_unidad * $cantidad, 2);
$total_iva = round($base * $iva / 100, 2);
$total = round($base + $total_iva, 2);
$values = [];
$values['base'] = $base;
$values['total_iva'] = $total_iva;
$values['total'] = $total;
return $values;
}
}

View File

@ -0,0 +1,142 @@
<?php
namespace App\Controllers\Facturacion;
use App\Models\Facturas\FacturaPagoModel;
use App\Models\Collection;
use DataTables\Editor;
use DataTables\Editor\Field;
use DataTables\Editor\Validate;
use DataTables\Editor\Format;
class FacturasPagos extends \App\Controllers\BaseResourceController
{
protected $modelName = FacturaPagoModel::class;
protected $format = 'json';
protected static $controllerSlug = 'factura-pagos';
public function datatable($factura_id = null){
if ($this->request->isAJAX() && $factura_id != null) {
$reqData = $this->request->getPost();
if (!isset($reqData['draw']) || !isset($reqData['columns']) ) {
$errstr = 'No data available in response to this specific request.';
$response = $this->respond(Collection::datatable( [], 0, 0, $errstr ), 400, $errstr);
return $response;
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 0;
//$order = FacturaModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 0];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$resourceData = $this->model->getResource($factura_id)->orderBy(1, $dir)->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource($factura_id)->countAllResults(),
$this->model->getResource($factura_id)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function datatable_editor() {
if ($this->request->isAJAX()) {
include(APPPATH . "ThirdParty/DatatablesEditor/DataTables.php");
// Build our Editor instance and process the data coming from _POST
$response = Editor::inst( $db, 'facturas_pagos' )
->fields(
Field::inst( 'id' ),
Field::inst( 'forma_pago_id' ),
Field::inst( 'notes' )
->validator('Validate::notEmpty', array(
'message' => lang('Facturas.validation.requerido'))
),
Field::inst( 'fecha_pago_at' )
->validator( Validate::dateFormat( 'Y-m-d H:i:s' ) )
->getFormatter( Format::dateSqlToFormat( 'Y-m-d H:i:s' ) )
->setFormatter( Format::dateFormatToSql( 'Y-m-d H:i:s' ) ),
Field::inst( 'fecha_vencimiento_at' )
->validator( Validate::dateFormat( 'Y-m-d H:i:s' ) )
->getFormatter( Format::dateSqlToFormat( 'Y-m-d H:i:s' ) )
->setFormatter( Format::dateFormatToSql( 'Y-m-d H:i:s' ) ),
Field::inst( 'total' )
->validator('Validate::numeric', array(
'message' => lang('Facturas.validation.numerico'))
)
->validator('Validate::notEmpty', array(
'message' => lang('Facturas.validation.requerido'))
),
Field::inst( 'factura_id' ),
Field::inst( 'user_updated_id' ),
)
->on('preCreate', function ($editor, &$values) {
/*
$editor
->field('user_updated_id')
->setValue(auth()->user()->id);
$editor
->field('base')
->setValue($totales['base']);
$editor
->field('total_iva')
->setValue($totales['total_iva']);
$editor
->field('total')
->setValue($totales['total']);
$editor
->field('user_updated_id')
->setValue(auth()->user()->id);
*/
})
->on('preEdit', function ($editor, $id, &$values) {
/*
$editor
->field('factura_id')
->setValue($values['factura_id']);
$editor
->field('pedido_linea_impresion_id')
->setValue(null);
$editor
->field('pedido_maquetacion_id')
->setValue(null);
$editor
->field('user_updated_id')
->setValue(auth()->user()->id);
$editor
->field('base')
->setValue($totales['base']);
$editor
->field('total_iva')
->setValue($totales['total_iva']);
$editor
->field('total')
->setValue($totales['total']);
*/
})
->debug(true)
->process($_POST)
->data();
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$response[$csrfTokenName] = $newTokenHash;
echo json_encode($response);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -139,7 +139,7 @@ abstract class GoBaseController extends Controller {
* *
* @var array * @var array
*/ */
protected $helpers = ['session', 'go_common', 'text', 'general','jwt']; //JJO protected $helpers = ['session', 'go_common', 'text', 'general','jwt', 'rbac']; //JJO
public static $queries = []; public static $queries = [];

View File

@ -17,7 +17,7 @@ class Home extends BaseController
public function index() public function index()
{ {
echo view(getenv('theme.path') . 'main/defaultlayout'); echo view(getenv('theme.path') . 'form/home/viewHome');
} }

View File

@ -117,5 +117,13 @@ class Js_loader extends BaseController
$this->response->setHeader('Content-Type', 'text/javascript'); $this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/presupuestos/cliente/previews.js'); return view('themes/vuexy/form/presupuestos/cliente/previews.js');
} }
function chat_js()
{
$this->response->setHeader('Content-Type', 'text/javascript');
return view('themes/vuexy/form/mensajes/mensajeria.js');
}
} }

View File

@ -15,4 +15,15 @@ class Language extends BaseController
$url = previous_url(); $url = previous_url();
return redirect()->to($url); return redirect()->to($url);
} }
// Function to get the translation of the language file from a AJAX request
public function getTranslation()
{
$translationFile = $this->request->getPost('translationFile');
$locale = $this->request->getPost('locale');
$path = "Language/{$locale}/$translationFile.php";
$lang = require APPPATH.$path;
return json_encode($lang);
}
} }

View File

@ -0,0 +1,64 @@
<?php namespace App\Controllers\Mensajeria;
use App\Controllers\BaseResourceController;
use App\Entities\Mensajeria\ConversacionEntity;
use App\Entities\Sistema\ActivityEntity;
use App\Models\CollectionModel;
use App\Models\Mensajeria\ConversacionModel;
use App\Models\Sistema\ActivityModel;
class MensajesDirectos extends BaseResourceController
{
protected $modelName = ConversacionModel::class;
protected $format = 'json';
protected static $controllerSlug = 'mensajes-internos';
protected static $viewPath = 'themes/vuexy/form/mensajes/';
protected static $indexRoute = 'mensajesView';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = "Mensajeria interna";
// Breadcrumbs
$this->viewData['breadcrumb'] = [
['title' => "Home", 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_mensajes"), 'route' => route_to('mensajeriaView'), 'active' => true]
];
parent::initController($request, $response, $logger);
}
public function index()
{
return view(static::$viewPath . static::$indexRoute);
}
public function getChatInfo($conversacionId)
{
// Modelos
$conversacionModel = model('App\Models\Mensajeria\ConversacionModel');
// Verificar si es una solicitud AJAX
if ($this->request->isAJAX()) {
// Obtener los datos
$data = [
'people' => $conversacionModel->getChatParticipants($conversacionId),
'messages' => $conversacionModel->getChatMessages($conversacionId)
];
// Devolver respuesta JSON
return $this->respond($data, 200, 'Chat information retrieved successfully');
} else {
return $this->failForbidden('Only AJAX requests are allowed');
}
}
}

View File

@ -0,0 +1,66 @@
<?php
namespace App\Controllers\Pdf;
use App\Controllers\BaseController;
class PrintAlbaranes extends BaseController
{
public function index($albaran_id)
{
$albaranModel = model('App\Models\Pedidos\AlbaranModel');
$lineasAlbaranModel = model('App\Models\Pedidos\AlbaranLineaModel');
$data['albaran'] = $albaranModel->getResourceForPdf($albaran_id)->get()->getRow();
$data['albaranLineas'] = $lineasAlbaranModel->getResourceForPdf($albaran_id)->get()->getResultObject();
return view(getenv('theme.path') . 'pdfs/albaran', $data);
}
public function generar($albaran_id)
{
// Cargar modelos
$albaranModel = model('App\Models\Pedidos\AlbaranModel');
$lineasAlbaranModel = model('App\Models\Pedidos\AlbaranLineaModel');
// Informacion del presupuesto
$data['albaran'] = $albaranModel->getResourceForPdf($albaran_id)->get()->getRow();
$data['albaranLineas'] = $lineasAlbaranModel->getResourceForPdf($albaran_id)->get()->getResultObject();
// Crear una instancia de Dompdf
$options = new \Dompdf\Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isPhpEnabled', true);
$options->set('isRemoteEnabled', true);
$dompdf = new \Dompdf\Dompdf($options);
// Contenido HTML del documento
$dompdf->loadHtml(view(getenv('theme.path').'pdfs/albaran', $data));
// Establecer el tamaño del papel
$dompdf->setPaper('A4', 'portrait');
// Renderizar el PDF
$dompdf->render();
// Obtener el contenido generado
$output = $dompdf->output();
// Establecer las cabeceras para visualizar en lugar de descargar
$file_name = "presupuesto-$albaran_id.pdf";
return $this->response
->setStatusCode(200)
->setHeader('Content-Type', 'application/pdf')
->setHeader('Content-Disposition', 'inline; filename="' . $file_name . '"')
->setHeader('Cache-Control', 'private, max-age=0, must-revalidate')
->setHeader('Pragma', 'public')
->setHeader('Content-Length', strlen($output))
->setBody($output);
}
}

View File

@ -0,0 +1,65 @@
<?php
namespace App\Controllers\Pdf;
use App\Controllers\BaseController;
class PrintFacturas extends BaseController
{
public function index($id_factura)
{
$facturaModel = model('App\Models\Facturas\FacturaModel');
$lineasFacturaModel = model('App\Models\Facturas\FacturaLineaModel');
$data['factura'] = $facturaModel->getResourceForPdf($id_factura)->get()->getRow();
$data['lineas_factura'] = $lineasFacturaModel->getResourceForPdf($id_factura)->get()->getResultObject();
$data['resumen_por_iva'] = $lineasFacturaModel->getResourceResumenIVAsForPdf($id_factura)->get()->getResultObject();
return view(getenv('theme.path') . 'pdfs/factura', $data);
}
public function generar($id_factura)
{
// Cargar modelos
$facturaModel = model('App\Models\Facturas\FacturaModel');
$lineasFacturaModel = model('App\Models\Facturas\FacturaLineaModel');
// Informacion del presupuesto
$data['factura'] = $facturaModel->getResourceForPdf($id_factura)->get()->getRow();
$data['lineas_factura'] = $lineasFacturaModel->getResourceForPdf($id_factura)->get()->getResultObject();
$data['resumen_por_iva'] = $lineasFacturaModel->getResourceResumenIVAsForPdf($id_factura)->get()->getResultObject();
// Crear una instancia de Dompdf
$options = new \Dompdf\Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isPhpEnabled', true);
$options->set('isRemoteEnabled', true);
$dompdf = new \Dompdf\Dompdf($options);
// Contenido HTML del documento
$dompdf->loadHtml(view(getenv('theme.path').'pdfs/factura', $data));
// Establecer el tamaño del papel
$dompdf->setPaper('A4', 'portrait');
// Renderizar el PDF
$dompdf->render();
// Obtener el contenido generado
$output = $dompdf->output();
// Establecer las cabeceras para visualizar en lugar de descargar
$file_name = $data['factura']->numero . ".pdf";
return $this->response
->setStatusCode(200)
->setHeader('Content-Type', 'application/pdf')
->setHeader('Content-Disposition', 'inline; filename="' . $file_name . '"')
->setHeader('Cache-Control', 'private, max-age=0, must-revalidate')
->setHeader('Pragma', 'public')
->setHeader('Content-Length', strlen($output))
->setBody($output);
}
}

View File

@ -0,0 +1,388 @@
<?php
namespace App\Controllers\Pedidos;
use App\Entities\Pedidos\AlbaranEntity;
use App\Models\Pedidos\AlbaranModel;
class Albaran extends \App\Controllers\BaseResourceController
{
protected $modelName = AlbaranModel::class;
protected $format = 'json';
protected static $singularObjectNameCc = 'albaran';
protected static $singularObjectName = 'Albaran';
protected static $pluralObjectName = 'Albaranes';
protected static $controllerSlug = 'albaran';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
}
public function index()
{
}
public function delete($id = null)
{
if ($this->request->isAJAX()) {
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
$model_linea->where('albaran_id', $id)->delete();
$this->model->where('id', $id)->delete();
$data = [
'error' => 0,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function addLinea($albaran_id){
if ($this->request->isAJAX()) {
$model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
// si es un post, es el iva
if($this->request->getPost()){
$reqData = $this->request->getPost();
$albaran_id = $reqData['albaran_id'] ?? 0;
$albaran = $this->model->find($albaran_id);
if($albaran == false){
$data = [
'error' => 'Albaran no encontrado',
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
$presupuesto_model = model('App\Models\Presupuestos\PresupuestoModel');
$presupuesto = $presupuesto_model->find($albaran->presupuesto_id);
if($presupuesto == false){
$data = [
'error' => 'Presupuesto no encontrado',
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
$iva_reducido = $presupuesto->iva_reducido;
$lineas = $model_linea->where('albaran_id', $albaran_id)->findAll();
$total = 0;
foreach($lineas as $linea){
$total += $linea->total;
}
$iva = $iva_reducido? $total * 4.0 / 100: $total * 21.0 / 100;
$data_linea= [
'albaran_id' => $albaran_id,
'titulo' => $iva_reducido?lang('Pedidos.iva4'):lang('Pedidos.iva21'),
'cantidad' => 1,
'precio_unidad' => round($iva,2),
'total' => round($iva,2),
'user_created_id' => auth()->user()->id,
'user_updated_id' => auth()->user()->id
];
$id_linea = $model_linea->insert($data_linea);
$linea = $model_linea->find($id_linea);
$data = [
'error' => 0,
'data' => $linea,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else{
$linea = [
'albaran_id' => $albaran_id,
'user_created_id' => auth()->user()->id,
'user_updated_id' => auth()->user()->id
];
$id_linea = $model_linea->insert($linea);
$data = $model_linea->find($id_linea);
$data = [
'error' => 0,
'data' => $data,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function add()
{
if ($this->request->isAJAX()) {
$user = auth()->user()->id;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$reqData = $this->request->getPost();
$pedido_id = $reqData['pedido_id'] ?? 0;
$presupuestos_id = $reqData['presupuestos_id'] ?? 0;
$return_data = $this->model->generarAlbaranes($pedido_id, $presupuestos_id, $user);
$data = [
'data' => $return_data,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function update($id = null){
if ($this->request->isAJAX()) {
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
if ($id == null) :
$data = [
'error' => 2,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif;
$id = filter_var($id, FILTER_SANITIZE_URL);
$albaranEntity = $this->model->find($id);
if ($albaranEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
$data = [
'error' => $message,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif;
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_updated_id'] = auth()->user()->id;
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) :
try {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Pedidos.albaran'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$albaranEntity->fill($sanitizedData);
endif;
if ($noException && $successfulResult) :
$id = $albaranEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
$data = [
'error' => 0,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$data = [
'error' => 1,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function updateLinea($id = null){
if ($this->request->isAJAX()) {
$model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
if ($id == null) :
$data = [
'error' => 2,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif;
$id = filter_var($id, FILTER_SANITIZE_URL);
$albaranEntity = $model_linea->find($id);
if ($albaranEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
$data = [
'error' => $message,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif;
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_updated_id'] = auth()->user()->id;
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) :
try {
$successfulResult = $model_linea->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Pedidos.albaran'))]);
$this->session->setFlashdata('formErrors', $model_linea->errors());
endif;
$albaranEntity->fill($sanitizedData);
endif;
if ($noException && $successfulResult) :
$id = $albaranEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
$data = [
'error' => 0,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$data = [
'error' => 1,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function borrarLinea(){
if ($this->request->isAJAX()) {
$model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$reqData = $this->request->getPost();
$id = $reqData['id'] ?? 0;
$id = filter_var($id, FILTER_SANITIZE_URL);
$albaranLineaEntity = $model_linea->find($id);
if ($albaranLineaEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
$data = [
'error' => $message,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif;
$successfulResult = $model_linea->skipValidation(true)->update($id, ['deleted_at' => date('Y-m-d H:i:s')]);
if ($successfulResult) :
$data = [
'error' => 0,
$csrfTokenName => $newTokenHash
];
else:
$data = [
'error' => 1,
$csrfTokenName => $newTokenHash
];
endif;
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function getAlbaranes($pedido_id = null){
if ($this->request->isAJAX()) {
$model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$returnData = [];
$albaranes = $this->model->asArray()->where('pedido_id', $pedido_id)->findAll();
foreach($albaranes as $albaran){
$albaran['fecha_albaran'] = $albaran['updated_at'];
array_push($returnData,
[
'albaran' => $albaran,
'lineas' => $model_linea->asArray()->where('albaran_id', $albaran['id'])->findAll()]
);
}
$data = [
'data' => $returnData,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -2,54 +2,391 @@
namespace App\Controllers\Pedidos; namespace App\Controllers\Pedidos;
use App\Controllers\BaseController; use App\Controllers\BaseController;
use App\Entities\Pedidos\PedidoEntity;
use App\Models\Collection;
use App\Models\Pedidos\PedidoModel;
use App\Services\PedidoXMLService;
class Pedido extends \App\Controllers\BaseResourceController
class Pedido extends BaseController
{ {
function __construct() protected $modelName = PedidoModel::class;
protected $format = 'json';
protected static $singularObjectNameCc = 'pedido';
protected static $singularObjectName = 'Pedido';
protected static $pluralObjectName = 'Pedidos';
protected static $controllerSlug = 'pedido';
protected static $viewPath = 'themes/vuexy/form/pedidos/';
protected $indexRoute = 'pedidoList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{ {
$this->viewData['pageTitle'] = lang('Pedidos.moduleTitle');
// Se indica que este controlador trabaja con soft_delete
$this->viewData = ['usingServerSideDataTable' => true];
// Breadcrumbs
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_pedidos"), 'route' => "javascript:void(0);", 'active' => false],
];
parent::initController($request, $response, $logger);
} }
public function index() public function index()
{ {
echo 'Pedidos';
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
// Se obtiene el cliente ID a partir del usuario de la sesion
$model_user = model('App\Models\Usuarios\UserModel');
$user = $model_user->find(auth()->user()->id);
$clienteId = $user->cliente_id;
} else {
$clienteId = -1;
}
$this->viewData['cliente_id'] = $clienteId;
$this->viewData['usingClientSideDataTable'] = true;
$this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Tarifaextra.tarifaextra')]);
parent::index();
} }
public function activos() public function activos()
{ {
echo 'Pedidos Activos'; $viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Pedidos.pedido')]),
'pedidoEntity' => new PedidoEntity(),
'usingServerSideDataTable' => true,
'pageTitle' => lang('Pedidos.Pedidos'),
'estadoPedidos' => 'activo',
['title' => lang("App.menu_pedidos"), 'route' => site_url('pedidos/todos'), 'active' => true]
];
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
// Se obtiene el cliente ID a partir del usuario de la sesion
$model_user = model('App\Models\Usuarios\UserModel');
$user = $model_user->find(auth()->user()->id);
$clienteId = $user->cliente_id;
} else {
$clienteId = -1;
}
$viewData['cliente_id'] = $clienteId;
return view(static::$viewPath . 'viewPedidosList', $viewData);
} }
public function finalizados() public function finalizados()
{ {
echo 'Pedidos Finalizados'; $viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Pedidos.pedido')]),
'pedidoEntity' => new PedidoEntity(),
'usingServerSideDataTable' => true,
'pageTitle' => lang('Pedidos.Pedidos'),
'estadoPedidos' => 'finalizado',
['title' => lang("App.menu_pedidos"), 'route' => site_url('pedidos/todos'), 'active' => true]
];
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
// Se obtiene el cliente ID a partir del usuario de la sesion
$model_user = model('App\Models\Usuarios\UserModel');
$user = $model_user->find(auth()->user()->id);
$clienteId = $user->cliente_id;
} else {
$clienteId = -1;
}
$viewData['cliente_id'] = $clienteId;
return view(static::$viewPath . 'viewPedidosList', $viewData);
} }
public function cancelados() public function cancelados()
{ {
echo 'Pedidos Cancelados'; $viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Pedidos.pedido')]),
'pedidoEntity' => new PedidoEntity(),
'usingServerSideDataTable' => true,
'pageTitle' => lang('Pedidos.Pedidos'),
'estadoPedidos' => 'cancelado',
['title' => lang("App.menu_pedidos"), 'route' => site_url('pedidos/todos'), 'active' => true]
];
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
// Se obtiene el cliente ID a partir del usuario de la sesion
$model_user = model('App\Models\Usuarios\UserModel');
$user = $model_user->find(auth()->user()->id);
$clienteId = $user->cliente_id;
} else {
$clienteId = -1;
}
$viewData['cliente_id'] = $clienteId;
return view(static::$viewPath . 'viewPedidosList', $viewData);
} }
public function manuales() public function todos()
{ {
echo 'Pedidos Manuales';
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Pedidos.pedido')]),
'pedidoEntity' => new PedidoEntity(),
'usingServerSideDataTable' => true,
'pageTitle' => lang('Pedidos.Pedidos'),
'estadoPedidos' => 'todos',
['title' => lang("App.menu_pedidos"), 'route' => site_url('pedidos/todos'), 'active' => true]
];
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
// Se obtiene el cliente ID a partir del usuario de la sesion
$model_user = model('App\Models\Usuarios\UserModel');
$user = $model_user->find(auth()->user()->id);
$clienteId = $user->cliente_id;
} else {
$clienteId = -1;
}
$viewData['cliente_id'] = $clienteId;
return view(static::$viewPath . 'viewPedidosList', $viewData);
} }
// public function delete_files() public function cambiarEstado(){
// { if($this->request->isAJAX()){
//
// }
//
// public function pedidos_maquetacion()
// {
//
// }
//
// public function pedidos_prestashop()
// {
//
// }
$id = $this->request->getPost('id');
$estado = $this->request->getPost('estado');
$this->model->where('id', $id)->set(['estado' => $estado])->update();
return $this->respond(['status' => 'success', 'message' => lang('Basic.global.success')]);
}else{
return $this->failUnauthorized('Invalid request', 403);
}
}
public function update($id = null){
if ($this->request->isAJAX()) {
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
if ($id == null) :
$data = [
'error' => 2,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif;
$id = filter_var($id, FILTER_SANITIZE_URL);
$pedidoEntity = $this->model->find($id);
if ($pedidoEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.pedido')), $id]);
$data = [
'error' => $message,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif;
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_updated_id'] = auth()->user()->id;
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) :
try {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Pedidos.albaran'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$pedidoEntity->fill($sanitizedData);
endif;
if ($noException && $successfulResult) :
$id = $pedidoEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
$data = [
'error' => 0,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$data = [
'error' => 1,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function edit($id=null){
if ($id == null) :
return $this->redirect2listView();
endif;
$id = filter_var($id, FILTER_SANITIZE_URL);
$pedidoEntity = $this->model->find($id);
if ($pedidoEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.pedido')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
$this->obtenerDatosFormulario($pedidoEntity);
$this->viewData['pedidoEntity'] = $pedidoEntity;
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Pedidos.moduleTitle') . ' ' . lang('Basic.global.edit3');
return $this->displayForm(__METHOD__, $id);
}
public function datatable(){
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
if (!isset($reqData['draw']) || !isset($reqData['columns']) ) {
$errstr = 'No data available in response to this specific request.';
$response = $this->respond(Collection::datatable( [], 0, 0, $errstr ), 400, $errstr);
return $response;
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 0;
$order = PedidoModel::SORTABLE_TODOS[$requestedOrder >= 0 ? $requestedOrder : 0];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$estado = $reqData['estado'] ?? 'todos';
$cliente_id = $reqData['cliente_id'] ?? -1;
if($estado == 'todos') $estado = '';
$showTotal = $reqData['showTotal'] ?? false;
$searchValues = get_filter_datatables_columns($reqData);
$model_linea = model('\App\Models\Pedidos\PedidoLineaModel');
$resourceData = $model_linea->getResource($searchValues, $estado, $cliente_id)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
$totalTirada = $model_linea->getSumOfTirada($searchValues, $estado, $cliente_id, $start, $length);
$total = $model_linea->getSumOfTotalAceptado($searchValues, $estado, $cliente_id, $start, $length);
$total2 = 0;
if($showTotal){
$total2 = $model_linea->getTotalOfTotalAceptado();
}
if($total2 != 0){
$total = "" . $total . " \n(" . $total2 . ")";
}
return $this->respond(Collection::datatable(
$resourceData,
$model_linea->getResource("", $estado)->countAllResults(),
$model_linea->getResource($searchValues, $estado)->countAllResults(),
"",
[
'total_tirada' => $totalTirada,
'total' => $total
]
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function obtenerPedidosForFacturas(){
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
$start = $reqData['start'] ?? 0;
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function getlineas(){
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
if (!isset($reqData['draw']) || !isset($reqData['columns']) ) {
$errstr = 'No data available in response to this specific request.';
$response = $this->respond(Collection::datatable( [], 0, 0, $errstr ), 400, $errstr);
return $response;
}
$id = $reqData['pedido_id'] ?? 0;
$resourceData = $this->model->obtenerLineasPedido($id);
return $this->respond(Collection::datatable(
$resourceData,
count($resourceData),
count($resourceData)
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
private function obtenerDatosFormulario(&$pedidoEntity){
$datos = $this->model->obtenerDatosForm($pedidoEntity->id);
$pedidoEntity->estadoText = lang('Pedidos.' . $pedidoEntity->estado);
if(count($datos) > 0){
$pedidoEntity->cliente = $datos[0]->cliente;
$pedidoEntity->cliente_id = $datos[0]->cliente_id;
$pedidoEntity->comercial = $datos[0]->comercial;
}
$pedidoEntity->fecha_entrega_real_text = $pedidoEntity->fecha_entrega_real ? date('d/m/Y', strtotime($pedidoEntity->fecha_entrega_real)) : '';
$pedidoEntity->fecha_impresion_text = $pedidoEntity->fecha_impresion ? date('d/m/Y', strtotime($pedidoEntity->fecha_impresion)) : '';
$pedidoEntity->fecha_encuadernado_text = $pedidoEntity->fecha_encuadernado ? date('d/m/Y', strtotime($pedidoEntity->fecha_encuadernado)) : '';
$pedidoEntity->fecha_entrega_externo_text = $pedidoEntity->fecha_entrega_externo ? date('d/m/Y', strtotime($pedidoEntity->fecha_entrega_externo)) : '';
}
public function get_xml_pedido($pedido_id)
{
$data = PedidoXMLService::generate_xml($pedido_id);
// $xml_service = new PedidoXMLService($this->model);
return $this->respond($data);
}
} }

View File

@ -97,11 +97,11 @@ class Buscador extends \App\Controllers\BaseResourceController
$order1 = PresupuestoModel::SORTABLE[$requestedOrder1 >= 0 ? $requestedOrder1 : 0]; $order1 = PresupuestoModel::SORTABLE[$requestedOrder1 >= 0 ? $requestedOrder1 : 0];
$dir1 = $reqData['order']['0']['dir'] ?? 'asc'; $dir1 = $reqData['order']['0']['dir'] ?? 'asc';
$requestedOrder2 = $reqData['order']['1']['column'] ?? 0; $requestedOrder2 = $reqData['order']['1']['column'] ?? 0;
$order2 = PresupuestoModel::SORTABLE[$requestedOrder2 >= 0 ? $requestedOrder1 : 0]; $order2 = PresupuestoModel::SORTABLE[$requestedOrder2 >= 0 ? $requestedOrder2 : 0];
$dir2 = $reqData['order']['0']['dir'] ?? 'asc'; $dir2 = $reqData['order']['1']['dir'] ?? 'asc';
$requestedOrder3 = $reqData['order']['2']['column'] ?? 0; $requestedOrder3 = $reqData['order']['2']['column'] ?? 0;
$order3 = PresupuestoModel::SORTABLE[$requestedOrder3 >= 0 ? $requestedOrder1 : 0]; $order3 = PresupuestoModel::SORTABLE[$requestedOrder3 >= 0 ? $requestedOrder3 : 0];
$dir3 = $reqData['order']['0']['dir'] ?? 'asc'; $dir3 = $reqData['order']['2']['dir'] ?? 'asc';
$searchValues = get_filter_datatables_columns($reqData); $searchValues = get_filter_datatables_columns($reqData);
@ -111,7 +111,7 @@ class Buscador extends \App\Controllers\BaseResourceController
return $this->respond(Collection::datatable( return $this->respond(Collection::datatable(
$resourceData, $resourceData,
$this->model->getResource("")->countAllResults(), $this->model->getResource("")->countAllResults(),
$this->model->getResource($search)->countAllResults() $this->model->getResource($searchValues)->countAllResults()
)); ));
} else { } else {
return $this->failUnauthorized('Invalid request', 403); return $this->failUnauthorized('Invalid request', 403);

View File

@ -295,6 +295,12 @@ class Cosidotapablanda extends \App\Controllers\BaseResourceController
endif; endif;
else : else :
if ($this->request->isAJAX()) { if ($this->request->isAJAX()) {
if($presupuestoEntity->estado_id==1 && $presupuestoEntity->confirmar==1){
$this->model->confirmarPresupuesto($id);
PresupuestoService::crearPedido($id);
}
$newTokenHash = csrf_hash(); $newTokenHash = csrf_hash();
$csrfTokenName = csrf_token(); $csrfTokenName = csrf_token();
$data = [ $data = [
@ -861,6 +867,7 @@ class Cosidotapablanda extends \App\Controllers\BaseResourceController
$presupuesto = $this->model->find($id); $presupuesto = $this->model->find($id);
$presupuesto->titulo = $presupuesto->titulo .' - ' . lang('Presupuestos.duplicado'); $presupuesto->titulo = $presupuesto->titulo .' - ' . lang('Presupuestos.duplicado');
$presupuesto->is_duplicado = 1; $presupuesto->is_duplicado = 1;
$presupuesto->estado_id = 1;
$new_id = $this->model->insert($presupuesto); $new_id = $this->model->insert($presupuesto);
$presupuestoAcabadosModel = model('App\Models\Presupuestos\PresupuestoAcabadosModel'); $presupuestoAcabadosModel = model('App\Models\Presupuestos\PresupuestoAcabadosModel');
@ -1271,8 +1278,8 @@ class Cosidotapablanda extends \App\Controllers\BaseResourceController
$input_data['is_duplicado'] = $presupuestoEntity->is_duplicado; $input_data['is_duplicado'] = $presupuestoEntity->is_duplicado;
if($presupuestoEntity->papel_formato_personalizado){ if($presupuestoEntity->papel_formato_personalizado){
$input_data['ancho'] = $presupuestoEntity->ancho; $input_data['ancho'] = $presupuestoEntity->papel_formato_ancho ;
$input_data['alto'] = $presupuestoEntity->alto; $input_data['alto'] = $presupuestoEntity->papel_formato_alto ;
} }
else{ else{
$model = model("App\Models\Configuracion\PapelFormatoModel"); $model = model("App\Models\Configuracion\PapelFormatoModel");

View File

@ -99,12 +99,13 @@ class Presupuestoacabados extends \App\Controllers\BaseResourceController
$tarifa_acabado_id = $reqData['tarifa_acabado_id'] ?? 0; $tarifa_acabado_id = $reqData['tarifa_acabado_id'] ?? 0;
$tirada = $reqData['tirada'] ?? 0; $tirada = $reqData['tirada'] ?? 0;
$proveedor_id = $reqData['proveedor_id'] ?? -1;
$POD = $reqData['POD'] ?? 0; $POD = $reqData['POD'] ?? 0;
$newTokenHash = csrf_hash(); $newTokenHash = csrf_hash();
$csrfTokenName = csrf_token(); $csrfTokenName = csrf_token();
$values = $this->model->getPrecioTarifa($tarifa_acabado_id, $tirada, $POD); $values = $this->model->getPrecioTarifa($tarifa_acabado_id, $tirada, $proveedor_id, $POD);
$data = [ $data = [
'values' => $values, 'values' => $values,
@ -119,4 +120,39 @@ class Presupuestoacabados extends \App\Controllers\BaseResourceController
} }
public function menuItems()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
try{
$tarifa_id = $reqData['tarifa_id'] ?? -1;
$tirada = $reqData['tirada'] ?? 0;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$menu = $this->model->getProveedoresForSelector($tarifa_id, $tirada);
$data = [
'menu' => $menu,
$csrfTokenName => $newTokenHash
];
}
catch(Exception $e){
$data = [
'error' => $e,
$csrfTokenName => $newTokenHash
];
}
finally{
return $this->respond($data);
}
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -110,7 +110,7 @@ class Presupuestoencuadernaciones extends \App\Controllers\BaseResourceControlle
$proveedor_id = $reqData['proveedor_id'] ?? 0; $proveedor_id = $reqData['proveedor_id'] ?? 0;
} }
else{ else{
$solapas = $reqData['solapas'] ?? -1; $solapas = $reqData['solapas'] ?? 0;
} }
$paginas = $reqData['paginas'] ?? 0; $paginas = $reqData['paginas'] ?? 0;
$tirada = $reqData['tirada'] ?? 0; $tirada = $reqData['tirada'] ?? 0;
@ -118,6 +118,7 @@ class Presupuestoencuadernaciones extends \App\Controllers\BaseResourceControlle
$alto = $reqData['alto'] ?? 0; $alto = $reqData['alto'] ?? 0;
$POD = $reqData['POD'] ?? 0; $POD = $reqData['POD'] ?? 0;
$paginas_cuadernillo = $reqData['paginas_por_cuadernillo'] ?? null;
$newTokenHash = csrf_hash(); $newTokenHash = csrf_hash();
$csrfTokenName = csrf_token(); $csrfTokenName = csrf_token();
@ -125,7 +126,7 @@ class Presupuestoencuadernaciones extends \App\Controllers\BaseResourceControlle
$tarifaModel = model('App\Models\Tarifas\TarifaEncuadernacionModel'); $tarifaModel = model('App\Models\Tarifas\TarifaEncuadernacionModel');
if(is_null($tipo)){ if(is_null($tipo)){
if($tarifaModel->isTarifaPorHoras($tarifa_encuadernacion_id)){ if($tarifaModel->isTarifaPorHoras($tarifa_encuadernacion_id)){
$values = $this->model->getPrecioTarifaHoras($tarifa_encuadernacion_id, $paginas, $tirada, $proveedor_id, $POD); $values = $this->model->getPrecioTarifaHoras($tarifa_encuadernacion_id, $paginas, $tirada, $proveedor_id, $POD, $paginas_cuadernillo);
}else{ }else{
$values = $this->model->getPrecioTarifa($tarifa_encuadernacion_id, $paginas, $tirada, $ancho, $alto, $proveedor_id, $POD); $values = $this->model->getPrecioTarifa($tarifa_encuadernacion_id, $paginas, $tirada, $ancho, $alto, $proveedor_id, $POD);
} }

View File

@ -7,91 +7,81 @@ use App\Models\UserModel;
class Profile extends BaseController class Profile extends BaseController
{ {
private $user_model;
private $id_user;
function __construct() function __construct()
{ {
$this->user_model = new UserModel();
$this->id_user = auth()->user()->id;
} }
public function index() public function index()
{ {
helper('file');
helper('form');
helper('text');
$data['title'] = [
'module' => lang("App.profile_title"),
'page' => lang("App.profile_subtitle"),
'icon' => 'fas fa-user'
];
$data['breadcrumb'] = [ $data['breadcrumb'] = [
['title' => lang("App.menu_dashboard"), 'route' => "/home", 'active' => false], ['title' => lang("App.menu_dashboard"), 'route' => "/home", 'active' => false],
['title' => lang("App.profile_title"), 'route' => "", 'active' => true] ['title' => lang("App.profile_title"), 'route' => "", 'active' => true]
]; ];
$data['btn_return'] = [ // Get the User Provider (UserModel by default)
'title' => lang("App.global_come_back"), $users = auth()->getProvider();
'route' => '/',
'class' => 'btn btn-dark mr-1',
'icon' => 'fas fa-angle-left'
];
$data['btn_submit'] = [ // Find by the user_id
'title' => lang("App.global_save"), $data['obj'] = $users->findById(auth()->id());
'route' => '',
'class' => 'btn btn-primary mr-1',
'icon' => 'fas fa-save'
];
$session = session(); echo view(getenv('theme.path') . 'form/profile/profileDetails', $data);
$data['obj'] = $this->user_model->where('id', $this->id_user)->first();
echo view(getenv('theme.path') . 'form/profile/index', $data);
} }
public function store() public function store()
{ {
$session = session(); $session = session();
helper('form'); helper('form');
$rules = [ $rules = [
'first_name' => 'required', 'first_name' => 'required',
'last_name' => 'required', 'last_name' => 'required',
'new_pwd' => 'permit_empty|min_length[8]',
'new_pwd_confirm' => 'required_with[new_pwd]|matches[new_pwd]'
]; ];
// Definir los mensajes de error personalizados
$rules_error = [ $rules_error = [
'first_name' => ['required' => lang("App.profile_rules_first_name_r")], 'first_name' => ['required' => lang("App.profile_rules_first_name_r")],
'last_name' => ['required' => lang("App.profile_rules_last_name_r")], 'last_name' => ['required' => lang("App.profile_rules_last_name_r")],
'new_pwd' => ['min_length' => lang("App.profile_rules_password_m")],
'new_pwd_confirm' => [
'matches' => lang("App.profile_rules_password_confirm_m")
]
]; ];
// Validar la entrada
if ($this->validate($rules ?? [], $rules_error ?? [])) { if (!$this->validate($rules, $rules_error)) {
if (!empty($this->id_user)) { // Si la validación falla, redirigir de vuelta con errores
$this->user_model->save([ return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
'id' => $this->id_user,
'first_name' => $this->request->getPost('first_name'),
'last_name' => $this->request->getPost('last_name')
]);
$session->setFlashdata('sweet', ['success', lang("App.global_alert_save_success")]);
} else {
$session->setFlashdata('sweet', ['error', lang("App.global_alert_save_error")]);
}
} else {
$session->setFlashdata('error', 'error');
return $this->index();
} }
return redirect()->to('/profile'); // Obtener los valores de los campos
$firstName = $this->request->getPost('first_name');
$lastName = $this->request->getPost('last_name');
$newPwd = $this->request->getPost('new_pwd');
$update_data = [
'first_name' => $firstName,
'last_name' => $lastName,
'password' => $newPwd,
];
if(empty($newPwd)){
unset($update_data['password']);
}
// Aquí debes obtener el usuario actual, por ejemplo, desde la sesión
$users = auth()->getProvider();
$user = $users->findById(auth()->id());
$user->fill($update_data);
$users->save($user);
// Redirigir con un mensaje de éxito
return redirect()->back()->with('success', lang('App.profile_updated_successfully'));
} }
} }

View File

@ -0,0 +1,78 @@
<?php
namespace App\Controllers\Sistema;
use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Shield\Authentication\Authenticators\Session;
use CodeIgniter\Shield\Authentication\JWTManager;
use CodeIgniter\Shield\Validation\ValidationRules;
class AuthAPIController extends BaseController
{
use ResponseTrait;
/**
* Authenticate Existing User and Issue JWT.
*/
public function jwtLogin(): ResponseInterface
{
// Get the validation rules
$rules = $this->getValidationRules();
// Validate credentials
if (! $this->validateData($this->request->getJSON(true), $rules, [], config('Auth')->DBGroup)) {
return $this->fail(
['errors' => $this->validator->getErrors()],
$this->codes['unauthorized']
);
}
// Get the credentials for login
$credentials = $this->request->getJsonVar(setting('Auth.validFields'));
$credentials = array_filter($credentials);
$credentials['password'] = $this->request->getJsonVar('password');
/** @var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
// Check the credentials
$result = $authenticator->check($credentials);
// Credentials mismatch.
if (! $result->isOK()) {
// @TODO Record a failed login attempt
return $this->failUnauthorized($result->reason());
}
// Credentials match.
// @TODO Record a successful login attempt
$user = $result->extraInfo();
/** @var JWTManager $manager */
$manager = service('jwtmanager');
// Generate JWT and return to client
$jwt = $manager->generateToken($user);
return $this->respond([
'access_token' => $jwt,
]);
}
/**
* Returns the rules that should be used for validation.
*
* @return array<string, array<string, array<string>|string>>
* @phpstan-return array<string, array<string, string|list<string>>>
*/
protected function getValidationRules(): array
{
$rules = new ValidationRules();
return $rules->getLoginRules();
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace App\Controllers\Sistema;
use CodeIgniter\Controller;
class Intranet extends Controller
{
function presupuestos($resource_name)
{
helper('file');
$resource_path = WRITEPATH . 'uploads/presupuestos/' . $resource_name;
if (file_exists($resource_path)) {
// Get the mime type of the file
$mime_type = mime_content_type($resource_path);
// Get an instance of the Response class
$response = service('response');
// Set the content type
$response->setContentType($mime_type);
// Set the output
$response->setBody(file_get_contents($resource_path));
// Send the response to the browser
$response->send();
}
}
}

View File

@ -5,6 +5,10 @@ use App\Entities\Tarifas\Acabados\TarifaAcabadoEntity;
use App\Models\Collection; use App\Models\Collection;
use App\Models\Tarifas\Acabados\TarifaAcabadoModel; use App\Models\Tarifas\Acabados\TarifaAcabadoModel;
use App\Models\Compras\ProveedorModel;
use App\Models\Compras\ProveedorTipoModel;
class TarifaAcabados extends BaseResourceController class TarifaAcabados extends BaseResourceController
{ {
@ -38,7 +42,7 @@ class TarifaAcabados extends BaseResourceController
// Breadcrumbs // Breadcrumbs
$this->viewData['breadcrumb'] = [ $this->viewData['breadcrumb'] = [
['title' => lang("App.menu_tarifas"), 'route' => "javascript:void(0);", 'active' => false], ['title' => lang("App.menu_tarifas"), 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_tarifaacabado"), 'route' => site_url('tarifas/tarifaacabado'), 'active' => true] ['title' => lang("App.menu_tarifaacabado"), 'route' => site_url('tarifas/acabados'), 'active' => true]
]; ];
parent::initController($request, $response, $logger); parent::initController($request, $response, $logger);
@ -48,6 +52,8 @@ class TarifaAcabados extends BaseResourceController
public function index() public function index()
{ {
checkPermission('tarifa-acabado.menu');
$viewData = [ $viewData = [
'currentModule' => static::$controllerSlug, 'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Tarifaacabado.tarifaacabado')]), 'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Tarifaacabado.tarifaacabado')]),
@ -64,6 +70,8 @@ class TarifaAcabados extends BaseResourceController
public function add() public function add()
{ {
checkPermission('tarifa-acabado.create', $this->indexRoute);
if ($this->request->getPost()) : if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1'); $nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -125,6 +133,8 @@ class TarifaAcabados extends BaseResourceController
endif; // ($requestMethod === 'post') endif; // ($requestMethod === 'post')
$this->viewData['proveedores'] = $this->getProveedores();
$this->viewData['tarifaacabadoEntity'] = isset($sanitizedData) ? new TarifaAcabadoEntity($sanitizedData) : new TarifaAcabadoEntity(); $this->viewData['tarifaacabadoEntity'] = isset($sanitizedData) ? new TarifaAcabadoEntity($sanitizedData) : new TarifaAcabadoEntity();
$this->viewData['formAction'] = route_to('tarifaAcabadoAdd'); $this->viewData['formAction'] = route_to('tarifaAcabadoAdd');
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Tarifaacabado.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix'); $this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Tarifaacabado.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix');
@ -133,8 +143,10 @@ class TarifaAcabados extends BaseResourceController
return $this->displayForm(__METHOD__); return $this->displayForm(__METHOD__);
} // end function add() } // end function add()
public function edit($requestedId = null) { public function edit($requestedId = null)
{
checkPermission('tarifa-acabado.edit', $this->indexRoute);
if ($requestedId == null) : if ($requestedId == null) :
return $this->redirect2listView(); return $this->redirect2listView();
@ -211,6 +223,7 @@ class TarifaAcabados extends BaseResourceController
endif; // ($requestMethod === 'post') endif; // ($requestMethod === 'post')
$this->viewData['tarifaacabadoEntity'] = $tarifaacabadoEntity; $this->viewData['tarifaacabadoEntity'] = $tarifaacabadoEntity;
$this->viewData['proveedores'] = $this->getProveedores();
$this->viewData['formAction'] = route_to('updateTarifaAcabado', $id); $this->viewData['formAction'] = route_to('updateTarifaAcabado', $id);
@ -299,4 +312,12 @@ class TarifaAcabados extends BaseResourceController
} }
} }
private function getProveedores(){
$provTipoModel = new ProveedorTipoModel();
$provModel = new ProveedorModel();
$tipoId = $provTipoModel->getTipoId("Acabados");
return $provModel->getProvList($tipoId);
}
} }

View File

@ -213,13 +213,14 @@ class TarifaAcabadosLineas extends \App\Controllers\BaseResourceController
$id_TA = $reqData['id_tarifaacabado'] ?? -1; $id_TA = $reqData['id_tarifaacabado'] ?? -1;
$searchValues = get_filter_datatables_columns($reqData);
$resourceData = $this->model->getResource("", $id_TA)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject(); $resourceData = $this->model->getResource($searchValues, $id_TA)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable( return $this->respond(Collection::datatable(
$resourceData, $resourceData,
$this->model->getResource()->countAllResults(), $this->model->getResource()->countAllResults(),
$this->model->getResource($search, $id_TA)->countAllResults() $this->model->getResource($searchValues, $id_TA)->countAllResults()
)); ));
} else { } else {
return $this->failUnauthorized('Invalid request', 403); return $this->failUnauthorized('Invalid request', 403);
@ -280,6 +281,7 @@ class TarifaAcabadosLineas extends \App\Controllers\BaseResourceController
->validator('Validate::notEmpty', array( ->validator('Validate::notEmpty', array(
'message' => lang('TarifaAcabadoLineas.validation.margen.required')) 'message' => lang('TarifaAcabadoLineas.validation.margen.required'))
), ),
Field::inst('proveedor_id'),
Field::inst('tarifa_acabado_id'), Field::inst('tarifa_acabado_id'),
Field::inst('user_created_id'), Field::inst('user_created_id'),
Field::inst('created_at'), Field::inst('created_at'),
@ -297,6 +299,7 @@ class TarifaAcabadosLineas extends \App\Controllers\BaseResourceController
$process_data['tirada_min'] = $data['data'][$pkey]['tirada_min']; $process_data['tirada_min'] = $data['data'][$pkey]['tirada_min'];
$process_data['tirada_max'] = $data['data'][$pkey]['tirada_max']; $process_data['tirada_max'] = $data['data'][$pkey]['tirada_max'];
$process_data['proveedor_id'] = $data['data'][$pkey]['proveedor_id'];
$response = $this->model->checkIntervals($process_data, $pkey, $data['data'][$pkey]['tarifa_acabado_id']); $response = $this->model->checkIntervals($process_data, $pkey, $data['data'][$pkey]['tarifa_acabado_id']);
// No se pueden duplicar valores al crear o al editar // No se pueden duplicar valores al crear o al editar
if (!empty($response)) { if (!empty($response)) {

View File

@ -1,4 +1,5 @@
<?php namespace App\Controllers\Tarifas; <?php
namespace App\Controllers\Tarifas;
use App\Controllers\BaseResourceController; use App\Controllers\BaseResourceController;
@ -10,15 +11,15 @@ use App\Entities\Tarifas\TarifaEncuadernacionLinea;
use App\Models\Tarifas\TarifaEncuadernacionLineaModel; use App\Models\Tarifas\TarifaEncuadernacionLineaModel;
use use
DataTables\Editor, DataTables\Editor,
DataTables\Database, DataTables\Database,
DataTables\Editor\Field, DataTables\Editor\Field,
DataTables\Editor\Format, DataTables\Editor\Format,
DataTables\Editor\Mjoin, DataTables\Editor\Mjoin,
DataTables\Editor\Options, DataTables\Editor\Options,
DataTables\Editor\Upload, DataTables\Editor\Upload,
DataTables\Editor\Validate, DataTables\Editor\Validate,
DataTables\Editor\ValidateOptions; DataTables\Editor\ValidateOptions;
class Tarifaencuadernacionlineas extends \App\Controllers\BaseResourceController class Tarifaencuadernacionlineas extends \App\Controllers\BaseResourceController
@ -75,7 +76,7 @@ class Tarifaencuadernacionlineas extends \App\Controllers\BaseResourceController
if ($this->request->getPost()) : if ($this->request->getPost()):
$nullIfEmpty = true; // !(phpversion() >= '8.1'); $nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -84,10 +85,10 @@ class Tarifaencuadernacionlineas extends \App\Controllers\BaseResourceController
$sanitizedData = $this->sanitized($postData, $nullIfEmpty); $sanitizedData = $this->sanitized($postData, $nullIfEmpty);
$noException = true; $noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) : if ($this->canValidate()):
try { try {
$successfulResult = $this->model->skipValidation(true)->save($sanitizedData); $successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
} catch (\Exception $e) { } catch (\Exception $e) {
@ -101,14 +102,14 @@ class Tarifaencuadernacionlineas extends \App\Controllers\BaseResourceController
$thenRedirect = true; // Change this to false if you want your user to stay on the form after submission $thenRedirect = true; // Change this to false if you want your user to stay on the form after submission
endif; endif;
if ($noException && $successfulResult) : if ($noException && $successfulResult):
$id = $this->model->db->insertID(); $id = $this->model->db->insertID();
$message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.'; $message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect) : if ($thenRedirect):
if (!empty($this->indexRoute)) : if (!empty($this->indexRoute)):
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message); return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else: else:
return $this->redirect2listView('sweet-success', $message); return $this->redirect2listView('sweet-success', $message);
@ -134,20 +135,20 @@ class Tarifaencuadernacionlineas extends \App\Controllers\BaseResourceController
public function edit($requestedId = null) public function edit($requestedId = null)
{ {
if ($requestedId == null) : if ($requestedId == null):
return $this->redirect2listView(); return $this->redirect2listView();
endif; endif;
$id = filter_var($requestedId, FILTER_SANITIZE_URL); $id = filter_var($requestedId, FILTER_SANITIZE_URL);
$tarifaEncuadernacionLinea = $this->model->find($id); $tarifaEncuadernacionLinea = $this->model->find($id);
if ($tarifaEncuadernacionLinea == false) : if ($tarifaEncuadernacionLinea == false):
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('TarifaEncuadernacionLineas.tarifaencuadernacionLinea')), $id]); $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('TarifaEncuadernacionLineas.tarifaencuadernacionLinea')), $id]);
return $this->redirect2listView('sweet-error', $message); return $this->redirect2listView('sweet-error', $message);
endif; endif;
if ($this->request->getPost()) : if ($this->request->getPost()):
$nullIfEmpty = true; // !(phpversion() >= '8.1'); $nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -156,10 +157,10 @@ class Tarifaencuadernacionlineas extends \App\Controllers\BaseResourceController
$sanitizedData = $this->sanitized($postData, $nullIfEmpty); $sanitizedData = $this->sanitized($postData, $nullIfEmpty);
$noException = true; $noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) : if ($this->canValidate()):
try { try {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData); $successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) { } catch (\Exception $e) {
@ -176,12 +177,12 @@ class Tarifaencuadernacionlineas extends \App\Controllers\BaseResourceController
$thenRedirect = false; $thenRedirect = false;
endif; endif;
if ($noException && $successfulResult) : if ($noException && $successfulResult):
$id = $tarifaEncuadernacionLinea->id ?? $id; $id = $tarifaEncuadernacionLinea->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.'; $message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect) : if ($thenRedirect):
if (!empty($this->indexRoute)) : if (!empty($this->indexRoute)):
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message); return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else: else:
return $this->redirect2listView('sweet-success', $message); return $this->redirect2listView('sweet-success', $message);
@ -214,45 +215,90 @@ class Tarifaencuadernacionlineas extends \App\Controllers\BaseResourceController
$response = Editor::inst($db, 'tarifa_encuadernacion_lineas') $response = Editor::inst($db, 'tarifa_encuadernacion_lineas')
->fields( ->fields(
Field::inst('paginas_libro_min') Field::inst('paginas_libro_min')
->validator('Validate::numeric', array( ->validator(
'message' => lang('TarifaAcabadoLineas.validation.paginas_libro_min.decimal')) 'Validate::numeric',
array(
'message' => lang('TarifaAcabadoLineas.validation.paginas_libro_min.decimal')
)
) )
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('TarifaAcabadoLineas.validation.paginas_libro_min.required')) 'Validate::notEmpty',
array(
'message' => lang('TarifaAcabadoLineas.validation.paginas_libro_min.required')
)
), ),
Field::inst('paginas_libro_max') Field::inst('paginas_libro_max')
->validator('Validate::numeric', array( ->validator(
'message' => lang('TarifaAcabadoLineas.validation.paginas_libro_max.decimal')) 'Validate::numeric',
array(
'message' => lang('TarifaAcabadoLineas.validation.paginas_libro_max.decimal')
)
) )
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('TarifaAcabadoLineas.validation.paginas_libro_max.required')) 'Validate::notEmpty',
array(
'message' => lang('TarifaAcabadoLineas.validation.paginas_libro_max.required')
)
), ),
Field::inst('precio_min') Field::inst('precio_min')
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar') ->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator('Validate::numeric', array( ->validator(
'Validate::numeric',
array(
"decimal" => ',', "decimal" => ',',
'message' => lang('TarifaAcabadoLineas.validation.precio_min.decimal')) 'message' => lang('TarifaAcabadoLineas.validation.precio_min.decimal')
)
) )
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('TarifaAcabadoLineas.validation.precio_min.required')) 'Validate::notEmpty',
array(
'message' => lang('TarifaAcabadoLineas.validation.precio_min.required')
)
), ),
Field::inst('precio_max') Field::inst('precio_max')
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar') ->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator('Validate::numeric', array( ->validator(
'Validate::numeric',
array(
"decimal" => ',', "decimal" => ',',
'message' => lang('TarifaAcabadoLineas.validation.precio_max.decimal')) 'message' => lang('TarifaAcabadoLineas.validation.precio_max.decimal')
)
) )
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('TarifaAcabadoLineas.validation.precio_max.required')) 'Validate::notEmpty',
array(
'message' => lang('TarifaAcabadoLineas.validation.precio_max.required')
)
),
Field::inst('total_min')
->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator(
'Validate::numeric',
array(
"decimal" => ',',
'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_min.decimal')
)
)
->validator(
'Validate::notEmpty',
array(
'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_min.required')
)
), ),
Field::inst('margen') Field::inst('margen')
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar') ->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator('Validate::numeric', array( ->validator(
'Validate::numeric',
array(
"decimal" => ',', "decimal" => ',',
'message' => lang('TarifaAcabadoLineas.validation.margen.decimal')) 'message' => lang('TarifaAcabadoLineas.validation.margen.decimal')
)
) )
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('TarifaAcabadoLineas.validation.margen.required')) 'Validate::notEmpty',
array(
'message' => lang('TarifaAcabadoLineas.validation.margen.required')
)
), ),
Field::inst('tirada_encuadernacion_id'), Field::inst('tirada_encuadernacion_id'),
Field::inst('user_created_id'), Field::inst('user_created_id'),
@ -325,7 +371,7 @@ class Tarifaencuadernacionlineas extends \App\Controllers\BaseResourceController
$cleandatatable = $reqData['cleandatatable'] ?? 0; $cleandatatable = $reqData['cleandatatable'] ?? 0;
if($cleandatatable){ if ($cleandatatable) {
$tarifa_encuadernacion_id = $reqData['tarifa_encuadernacion_id'] ?? -1; $tarifa_encuadernacion_id = $reqData['tarifa_encuadernacion_id'] ?? -1;
@ -339,9 +385,7 @@ class Tarifaencuadernacionlineas extends \App\Controllers\BaseResourceController
]; ];
return $this->respond($data); return $this->respond($data);
} } else {
else{
if (!isset($reqData['draw']) || !isset($reqData['columns'])) { if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
$errstr = 'No data available in response to this specific request.'; $errstr = 'No data available in response to this specific request.';

View File

@ -1,4 +1,5 @@
<?php namespace App\Controllers\Tarifas; <?php
namespace App\Controllers\Tarifas;
use App\Controllers\BaseResourceController; use App\Controllers\BaseResourceController;
@ -10,15 +11,15 @@ use App\Entities\Tarifas\TarifaEncuadernacionLinea;
use App\Models\Tarifas\TarifaEncuadernacionLineaHorasModel; use App\Models\Tarifas\TarifaEncuadernacionLineaHorasModel;
use use
DataTables\Editor, DataTables\Editor,
DataTables\Database, DataTables\Database,
DataTables\Editor\Field, DataTables\Editor\Field,
DataTables\Editor\Format, DataTables\Editor\Format,
DataTables\Editor\Mjoin, DataTables\Editor\Mjoin,
DataTables\Editor\Options, DataTables\Editor\Options,
DataTables\Editor\Upload, DataTables\Editor\Upload,
DataTables\Editor\Validate, DataTables\Editor\Validate,
DataTables\Editor\ValidateOptions; DataTables\Editor\ValidateOptions;
class Tarifaencuadernacionlineashoras extends \App\Controllers\BaseResourceController class Tarifaencuadernacionlineashoras extends \App\Controllers\BaseResourceController
@ -73,7 +74,7 @@ class Tarifaencuadernacionlineashoras extends \App\Controllers\BaseResourceContr
{ {
if ($this->request->getPost()) : if ($this->request->getPost()):
$nullIfEmpty = true; // !(phpversion() >= '8.1'); $nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -82,10 +83,10 @@ class Tarifaencuadernacionlineashoras extends \App\Controllers\BaseResourceContr
$sanitizedData = $this->sanitized($postData, $nullIfEmpty); $sanitizedData = $this->sanitized($postData, $nullIfEmpty);
$noException = true; $noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) : if ($this->canValidate()):
try { try {
$successfulResult = $this->model->skipValidation(true)->save($sanitizedData); $successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
} catch (\Exception $e) { } catch (\Exception $e) {
@ -99,14 +100,14 @@ class Tarifaencuadernacionlineashoras extends \App\Controllers\BaseResourceContr
$thenRedirect = true; // Change this to false if you want your user to stay on the form after submission $thenRedirect = true; // Change this to false if you want your user to stay on the form after submission
endif; endif;
if ($noException && $successfulResult) : if ($noException && $successfulResult):
$id = $this->model->db->insertID(); $id = $this->model->db->insertID();
$message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.'; $message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect) : if ($thenRedirect):
if (!empty($this->indexRoute)) : if (!empty($this->indexRoute)):
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message); return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else: else:
return $this->redirect2listView('sweet-success', $message); return $this->redirect2listView('sweet-success', $message);
@ -134,20 +135,20 @@ class Tarifaencuadernacionlineashoras extends \App\Controllers\BaseResourceContr
public function edit($requestedId = null) public function edit($requestedId = null)
{ {
if ($requestedId == null) : if ($requestedId == null):
return $this->redirect2listView(); return $this->redirect2listView();
endif; endif;
$id = filter_var($requestedId, FILTER_SANITIZE_URL); $id = filter_var($requestedId, FILTER_SANITIZE_URL);
$tarifaEncuadernacionLinea = $this->model->find($id); $tarifaEncuadernacionLinea = $this->model->find($id);
if ($tarifaEncuadernacionLinea == false) : if ($tarifaEncuadernacionLinea == false):
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('TarifaEncuadernacionLineas.tarifaencuadernacionLinea')), $id]); $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('TarifaEncuadernacionLineas.tarifaencuadernacionLinea')), $id]);
return $this->redirect2listView('sweet-error', $message); return $this->redirect2listView('sweet-error', $message);
endif; endif;
if ($this->request->getPost()) : if ($this->request->getPost()):
$nullIfEmpty = true; // !(phpversion() >= '8.1'); $nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -156,10 +157,10 @@ class Tarifaencuadernacionlineashoras extends \App\Controllers\BaseResourceContr
$sanitizedData = $this->sanitized($postData, $nullIfEmpty); $sanitizedData = $this->sanitized($postData, $nullIfEmpty);
$noException = true; $noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) : if ($this->canValidate()):
try { try {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData); $successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) { } catch (\Exception $e) {
@ -176,12 +177,12 @@ class Tarifaencuadernacionlineashoras extends \App\Controllers\BaseResourceContr
$thenRedirect = false; $thenRedirect = false;
endif; endif;
if ($noException && $successfulResult) : if ($noException && $successfulResult):
$id = $tarifaEncuadernacionLinea->id ?? $id; $id = $tarifaEncuadernacionLinea->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.'; $message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect) : if ($thenRedirect):
if (!empty($this->indexRoute)) : if (!empty($this->indexRoute)):
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message); return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else: else:
return $this->redirect2listView('sweet-success', $message); return $this->redirect2listView('sweet-success', $message);
@ -214,40 +215,79 @@ class Tarifaencuadernacionlineashoras extends \App\Controllers\BaseResourceContr
$response = Editor::inst($db, 'tarifa_encuadernacion_lineas_horas') $response = Editor::inst($db, 'tarifa_encuadernacion_lineas_horas')
->fields( ->fields(
Field::inst('tiempo_min') Field::inst('tiempo_min')
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar') ->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator('Validate::numeric', array( ->validator(
'Validate::numeric',
array(
"decimal" => ',', "decimal" => ',',
'message' => lang('TarifaAcabadoLineas.validation.paginas_libro_min.decimal')) 'message' => lang('TarifaAcabadoLineas.validation.paginas_libro_min.decimal')
)
) )
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('TarifaAcabadoLineas.validation.paginas_libro_min.required')) 'Validate::notEmpty',
array(
'message' => lang('TarifaAcabadoLineas.validation.paginas_libro_min.required')
)
), ),
Field::inst('tiempo_max') Field::inst('tiempo_max')
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar') ->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator('Validate::numeric', array( ->validator(
'Validate::numeric',
array(
"decimal" => ',', "decimal" => ',',
'message' => lang('TarifaAcabadoLineas.validation.paginas_libro_max.decimal')) 'message' => lang('TarifaAcabadoLineas.validation.paginas_libro_max.decimal')
)
) )
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('TarifaAcabadoLineas.validation.paginas_libro_max.required')) 'Validate::notEmpty',
array(
'message' => lang('TarifaAcabadoLineas.validation.paginas_libro_max.required')
)
), ),
Field::inst('precio_hora') Field::inst('precio_hora')
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar') ->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator('Validate::numeric', array( ->validator(
'Validate::numeric',
array(
"decimal" => ',', "decimal" => ',',
'message' => lang('TarifaAcabadoLineas.validation.precio_min.decimal')) 'message' => lang('TarifaAcabadoLineas.validation.precio_min.decimal')
)
) )
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('TarifaAcabadoLineas.validation.precio_min.required')) 'Validate::notEmpty',
array(
'message' => lang('TarifaAcabadoLineas.validation.precio_min.required')
)
),
Field::inst('total_min')
->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator(
'Validate::numeric',
array(
"decimal" => ',',
'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_min.decimal')
)
)
->validator(
'Validate::notEmpty',
array(
'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_min.required')
)
), ),
Field::inst('margen') Field::inst('margen')
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar') ->getFormatter('Format::toDecimalChar')->setFormatter('Format::fromDecimalChar')
->validator('Validate::numeric', array( ->validator(
'Validate::numeric',
array(
"decimal" => ',', "decimal" => ',',
'message' => lang('TarifaAcabadoLineas.validation.margen.decimal')) 'message' => lang('TarifaAcabadoLineas.validation.margen.decimal')
)
) )
->validator('Validate::notEmpty', array( ->validator(
'message' => lang('TarifaAcabadoLineas.validation.margen.required')) 'Validate::notEmpty',
array(
'message' => lang('TarifaAcabadoLineas.validation.margen.required')
)
), ),
Field::inst('tirada_encuadernacion_id'), Field::inst('tirada_encuadernacion_id'),
Field::inst('user_created_id'), Field::inst('user_created_id'),
@ -317,7 +357,7 @@ class Tarifaencuadernacionlineashoras extends \App\Controllers\BaseResourceContr
$cleandatatable = $reqData['cleandatatable'] ?? 0; $cleandatatable = $reqData['cleandatatable'] ?? 0;
if($cleandatatable){ if ($cleandatatable) {
$tarifa_encuadernacion_id = $reqData['tarifa_encuadernacion_id'] ?? -1; $tarifa_encuadernacion_id = $reqData['tarifa_encuadernacion_id'] ?? -1;
@ -331,8 +371,7 @@ class Tarifaencuadernacionlineashoras extends \App\Controllers\BaseResourceContr
]; ];
return $this->respond($data); return $this->respond($data);
} } else {
else{
if (!isset($reqData['draw']) || !isset($reqData['columns'])) { if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
$errstr = 'No data available in response to this specific request.'; $errstr = 'No data available in response to this specific request.';
$response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr); $response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr);

View File

@ -126,15 +126,6 @@ class Tarifaencuadernaciontiradas extends \App\Controllers\BaseResourceControlle
->validator('Validate::notEmpty', array( ->validator('Validate::notEmpty', array(
'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_min.required')) 'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_min.required'))
), ),
Field::inst('precio_min')
->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
->validator('Validate::numeric', array(
"decimal" => ',',
'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_min.decimal'))
)
->validator('Validate::notEmpty', array(
'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_min.required'))
),
Field::inst('proveedor_id') Field::inst('proveedor_id')
->validator('Validate::notEmpty', array( ->validator('Validate::notEmpty', array(
'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_max.required')) 'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_max.required'))

View File

@ -40,6 +40,7 @@ class Tarifaextra extends \App\Controllers\GoBaseController
public function index() public function index()
{ {
checkPermission('tarifa-extra.menu');
$this->viewData['usingClientSideDataTable'] = true; $this->viewData['usingClientSideDataTable'] = true;
@ -51,8 +52,7 @@ class Tarifaextra extends \App\Controllers\GoBaseController
public function add() public function add()
{ {
checkPermission('tarifa-extra.create', $this->indexRoute);
if ($this->request->getPost()) : if ($this->request->getPost()) :
@ -117,6 +117,7 @@ class Tarifaextra extends \App\Controllers\GoBaseController
public function edit($requestedId = null) public function edit($requestedId = null)
{ {
checkPermission('tarifa-extra.edit', $this->indexRoute);
if ($requestedId == null) : if ($requestedId == null) :
return $this->redirect2listView(); return $this->redirect2listView();
@ -129,14 +130,10 @@ class Tarifaextra extends \App\Controllers\GoBaseController
return $this->redirect2listView('errorMessage', $message); return $this->redirect2listView('errorMessage', $message);
endif; endif;
if ($this->request->getPost()) : if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost(); $postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, $nullIfEmpty); $sanitizedData = $this->sanitized($postData, true);
// JJO // JJO
if (isset($this->model->user_updated_id)) { if (isset($this->model->user_updated_id)) {
@ -192,7 +189,6 @@ class Tarifaextra extends \App\Controllers\GoBaseController
return $this->displayForm(__METHOD__, $id); return $this->displayForm(__METHOD__, $id);
} // end function edit(...) } // end function edit(...)
public function allItemsSelect() public function allItemsSelect()
{ {
if ($this->request->isAJAX()) { if ($this->request->isAJAX()) {

View File

@ -1,35 +0,0 @@
<?php
namespace App\Controllers\Tarifas;
use App\Controllers\BaseController;
class Tarifaimpresion extends BaseController
{
function __construct()
{
}
public function index()
{
echo 'Tarifa impresion';
}
public function delete()
{
}
public function add()
{
}
public function edit()
{
}
}

View File

@ -1,35 +0,0 @@
<?php
namespace App\Controllers\Tarifas;
use App\Controllers\BaseController;
class Tarifapapelcompra extends BaseController
{
function __construct()
{
}
public function index()
{
echo 'Tarifa papel compra';
}
public function delete()
{
}
public function add()
{
}
public function edit()
{
}
}

View File

@ -1,35 +0,0 @@
<?php
namespace App\Controllers\Tarifas;
use App\Controllers\BaseController;
class Tarifapapeldefecto extends BaseController
{
function __construct()
{
}
public function index()
{
echo 'Tarifa papel defecto';
}
public function delete()
{
}
public function add()
{
}
public function edit()
{
}
}

View File

@ -40,19 +40,17 @@ class Tarifapreimpresion extends \App\Controllers\GoBaseController
public function index() public function index()
{ {
checkPermission('tarifa-preimpresion.menu');
$this->viewData['usingClientSideDataTable'] = true; $this->viewData['usingClientSideDataTable'] = true;
$this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Tarifapreimpresion.tarifapreimpresion')]); $this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Tarifapreimpresion.tarifapreimpresion')]);
parent::index(); parent::index();
} }
public function add() public function add()
{ {
checkPermission('tarifa-preimpresion.create', $this->indexRoute);
if ($this->request->getPost()) : if ($this->request->getPost()) :
@ -117,6 +115,7 @@ class Tarifapreimpresion extends \App\Controllers\GoBaseController
public function edit($requestedId = null) public function edit($requestedId = null)
{ {
checkPermission('tarifa-preimpresion.edit', $this->indexRoute);
if ($requestedId == null) : if ($requestedId == null) :
return $this->redirect2listView(); return $this->redirect2listView();

View File

@ -1,4 +1,6 @@
<?php namespace App\Controllers\Tarifas; <?php
namespace App\Controllers\Tarifas;
use App\Controllers\BaseResourceController; use App\Controllers\BaseResourceController;
@ -55,6 +57,8 @@ class Tarifasencuadernacion extends \App\Controllers\BaseResourceController
public function index() public function index()
{ {
// Check if the user is allowed to list items
checkPermission('tarifa-encuadernacion.menu');
$viewData = [ $viewData = [
'currentModule' => static::$controllerSlug, 'currentModule' => static::$controllerSlug,
@ -73,8 +77,7 @@ class Tarifasencuadernacion extends \App\Controllers\BaseResourceController
public function add() public function add()
{ {
checkPermission('tarifa-encuadernacion.create', $this->indexRoute);
if ($this->request->getPost()) : if ($this->request->getPost()) :
@ -145,7 +148,7 @@ class Tarifasencuadernacion extends \App\Controllers\BaseResourceController
$this->viewData['tarifaEncuadernacionEntity'] = isset($sanitizedData) ? new TarifaEncuadernacionEntity($sanitizedData) : new TarifaEncuadernacionEntity(); $this->viewData['tarifaEncuadernacionEntity'] = isset($sanitizedData) ? new TarifaEncuadernacionEntity($sanitizedData) : new TarifaEncuadernacionEntity();
$this->viewData['formAction'] = site_url('tarifas/tarifasencuadernacion/add');//route_to('createTarifaEncuadernacion'); $this->viewData['formAction'] = site_url('tarifas/tarifasencuadernacion/add'); //route_to('createTarifaEncuadernacion');
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Tarifaencuadernacion.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix'); $this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Tarifaencuadernacion.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix');
@ -157,6 +160,7 @@ class Tarifasencuadernacion extends \App\Controllers\BaseResourceController
public function edit($requestedId = null) public function edit($requestedId = null)
{ {
checkPermission('tarifa-encuadernacion.edit', $this->indexRoute);
if ($requestedId == null) : if ($requestedId == null) :
return $this->redirect2listView(); return $this->redirect2listView();
@ -248,6 +252,12 @@ class Tarifasencuadernacion extends \App\Controllers\BaseResourceController
return $this->displayForm(__METHOD__, $id); return $this->displayForm(__METHOD__, $id);
} // end function edit(...) } // end function edit(...)
/*public function delete($id =null){
if (!auth()->user()->can('tarifa-encuadernacion.delete')) {
return $this->fail('No tiene permisos');
}
parent::delete($id);
}*/
public function datatable() public function datatable()
{ {
@ -327,7 +337,8 @@ class Tarifasencuadernacion extends \App\Controllers\BaseResourceController
} }
} }
private function getProveedores(){ private function getProveedores()
{
$provTipoModel = new ProveedorTipoModel(); $provTipoModel = new ProveedorTipoModel();
$provModel = new ProveedorModel(); $provModel = new ProveedorModel();
@ -335,12 +346,13 @@ class Tarifasencuadernacion extends \App\Controllers\BaseResourceController
return $provModel->getProvList($tipoId); return $provModel->getProvList($tipoId);
} }
private function getDimensiones(){ private function getDimensiones()
{
$dimensionModel = new TarifaEncuadernacionDimensionesModel(); $dimensionModel = new TarifaEncuadernacionDimensionesModel();
$dimensiones = $dimensionModel->getDimensiones(); $dimensiones = $dimensionModel->getDimensiones();
foreach($dimensiones as $dim){ foreach ($dimensiones as $dim) {
$dim->label= lang("TarifaEncuadernacionLineas." . $dim->label); $dim->label = lang("TarifaEncuadernacionLineas." . $dim->label);
} }
return $dimensiones; return $dimensiones;
} }

View File

@ -56,6 +56,9 @@ class Tarifasenvios extends \App\Controllers\BaseResourceController {
public function index() { public function index() {
// Check if the user is allowed to list items
checkPermission('tarifa-envio.menu');
$viewData = [ $viewData = [
'currentModule' => static::$controllerSlug, 'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('TarifasEnvios.tarifaEnvio')]), 'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('TarifasEnvios.tarifaEnvio')]),
@ -72,8 +75,7 @@ class Tarifasenvios extends \App\Controllers\BaseResourceController {
public function add() { public function add() {
checkPermission('tarifa-envio.create', $this->indexRoute);
if ($this->request->getPost()) : if ($this->request->getPost()) :
@ -142,6 +144,8 @@ class Tarifasenvios extends \App\Controllers\BaseResourceController {
public function edit($requestedId = null) { public function edit($requestedId = null) {
checkPermission('tarifa-envio.edit', $this->indexRoute);
if ($requestedId == null) : if ($requestedId == null) :
return $this->redirect2listView(); return $this->redirect2listView();
@ -227,6 +231,10 @@ class Tarifasenvios extends \App\Controllers\BaseResourceController {
// JJO // JJO
public function delete($id = null) public function delete($id = null)
{ {
/*if (!auth()->user()->can('tarifa-envio.delete')) {
return $this->fail('Error');
}*/
if (!empty(static::$pluralObjectNameCc) && !empty(static::$singularObjectNameCc)) { if (!empty(static::$pluralObjectNameCc) && !empty(static::$singularObjectNameCc)) {
$objName = mb_strtolower(lang(ucfirst(static::$pluralObjectNameCc).'.'.static::$singularObjectNameCc)); $objName = mb_strtolower(lang(ucfirst(static::$pluralObjectNameCc).'.'.static::$singularObjectNameCc));
} else { } else {
@ -242,7 +250,6 @@ class Tarifasenvios extends \App\Controllers\BaseResourceController {
else{ else{
$datetime = (new \CodeIgniter\I18n\Time("now")); $datetime = (new \CodeIgniter\I18n\Time("now"));
$zonaModel = new TarifaEnvioZonaModel(); $zonaModel = new TarifaEnvioZonaModel();
$zonaResult = $zonaModel->removeAllZonasLineas($id, $datetime, $this->delete_flag); $zonaResult = $zonaModel->removeAllZonasLineas($id, $datetime, $this->delete_flag);

View File

@ -51,6 +51,8 @@ class Tarifasmanipulado extends \App\Controllers\BaseResourceController
public function index() public function index()
{ {
// Check if the user is allowed to list items
checkPermission('tarifa-manipulado.menu');
$viewData = [ $viewData = [
'currentModule' => static::$controllerSlug, 'currentModule' => static::$controllerSlug,
@ -69,8 +71,7 @@ class Tarifasmanipulado extends \App\Controllers\BaseResourceController
public function add() public function add()
{ {
checkPermission('tarifa-manipulado.create', $this->indexRoute);
if ($this->request->getPost()) : if ($this->request->getPost()) :
@ -140,6 +141,7 @@ class Tarifasmanipulado extends \App\Controllers\BaseResourceController
public function edit($requestedId = null) public function edit($requestedId = null)
{ {
checkPermission('tarifa-manipulado.edit', $this->indexRoute);
if ($requestedId == null) : if ($requestedId == null) :
return $this->redirect2listView(); return $this->redirect2listView();
@ -153,14 +155,11 @@ class Tarifasmanipulado extends \App\Controllers\BaseResourceController
endif; endif;
if ($this->request->getPost()) : if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost(); $postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, $nullIfEmpty); $sanitizedData = $this->sanitized($postData, true);
// JJO // JJO
if (isset($this->model->user_updated_id)) { if (isset($this->model->user_updated_id)) {

View File

@ -18,30 +18,73 @@ class Test extends BaseController
{ {
} }
public function echo(){
echo "echo";
}
public function index() public function index()
{ {
helper('rbac'); /*
$model = model("\App\Models\Pedidos\PedidoLineaModel");
$data = $model->obtenerLineasPedidoSinFacturar(999);
*/
var_dump(auth()->user()->can('plantilla-tarifa.menu')); xdebug_info();
//$user = auth()->user();
generate_php_permissions_constant();
//echo generate_php_permissions_matrix_constant();
//$user->syncGroups('admin');
//var_dump($user->can('token.menu'));
} }
private function clonar_tarifa_encuadernacion($teOrigen, $teDestino){
$tet_model = model('App\Models\Tarifas\TarifaEncuadernacionTiradaModel');
$tel_model = model('App\Models\Tarifas\TarifaEncuadernacionLineaModel');
$tarifasTiradas = $tet_model->asObject()->where('tarifa_encuadernacion_id',$teOrigen)->findAll();
foreach ($tarifasTiradas as $tarifasTirada){
echo "--->" . $tarifasTirada->id . "<br>";
$tarifasLineas = $tel_model->asObject()->where('tirada_encuadernacion_id',$tarifasTirada->id)->findAll();
// Prepare the data
unset($tarifasTirada->id);
$tarifasTirada->tarifa_encuadernacion_id = $teDestino;
$tarifasTirada->created_at = date('Y-m-d H:i:s');
$tarifasTirada->updated_at = date('Y-m-d H:i:s');
//var_dump($tarifasTirada);
// Insert it
$tet_model->insert($tarifasTirada);
$inserted_id = $tet_model->insertID();
foreach ($tarifasLineas as $tarifasLinea){
echo "------>" . $tarifasLinea->id . "<br>";
// Prepare the data
unset($tarifasLinea->id);
$tarifasLinea->tirada_encuadernacion_id = $inserted_id;
$tarifasLinea->created_at = date('Y-m-d H:i:s');
$tarifasLinea->updated_at = date('Y-m-d H:i:s');
//var_dump($tarifasLinea);
// Insert it
$tel_model->insert($tarifasLinea);
}
}
}
private function test_get_tirada_alt($tirada, $merma, $tipo_impresion_id, private function test_get_tirada_alt($tirada, $merma, $tipo_impresion_id,
$json_data, $cliente_id, $ancho, $alto, $json_data, $cliente_id, $ancho, $alto,
$solapas_cubierta, $solapas_ancho_cubierta, $solapas_sobrecubierta, $solapas_ancho_sobrecubierta, $lomo) $solapas_cubierta, $solapas_ancho_cubierta, $solapas_sobrecubierta, $solapas_ancho_sobrecubierta, $lomo)
{ {
$values = []; $values = [];

View File

@ -0,0 +1,66 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;
class ChatDepartments extends Migration
{
protected array $COLUMNS = [
"id" => [
"type" => "INT",
"unsigned" => true,
"auto_increment" => true
],
"name" => [
"type" => "VARCHAR",
"constraint" => '45',
"unique" => true,
],
"display" => [
"type" => "VARCHAR",
"constraint" => '255',
],
"description" => [
"type" => "TEXT",
"null" => true,
],
"type" => [
"type" => "ENUM",
'constraint' => ['general', 'presupuesto', 'pedido'],
'default' => 'general',
],
];
public function up()
{
$this->forge->addField($this->COLUMNS);
$currenttime = new RawSql("CURRENT_TIMESTAMP");
$this->forge->addField([
"created_at" => [
"type" => "TIMESTAMP",
"default" => $currenttime,
],
"updated_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
"deleted_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
]);
$this->forge->addPrimaryKey('id');
$this->forge->createTable("chat_departments", true);
}
public function down()
{
//
$this->forge->dropTable("chat_departments");
}
}

View File

@ -0,0 +1,81 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\RawSql;
use CodeIgniter\Database\Migration;
class ChatsTable extends Migration
{
protected array $COLUMNS = [
"id" => [
"type" => "INT",
"unsigned" => true,
"auto_increment" => true
],
"chat_department_id" => [
"type" => "INT",
"unsigned" => true,
"null" => true
],
"pedido_id" => [
"type" => "INT",
"constraint" => 16,
"unsigned" => true,
"null" => true
],
"presupuesto_id" => [
"type" => "INT",
"constraint" => 10,
"unsigned" => true,
"null" => true
],
"factura_id" => [
"type" => "INT",
"constraint" => 10,
"unsigned" => true,
"null" => true
],
];
public function up()
{
$this->forge->dropTable("chat_conversaciones", true);
$this->forge->dropTable("chat_mensajes", true);
$this->forge->dropTable("chat_participantes", true);
$this->forge->addField($this->COLUMNS);
$currenttime = new RawSql("CURRENT_TIMESTAMP");
$this->forge->addField([
"created_at" => [
"type" => "TIMESTAMP",
"default" => $currenttime,
],
"updated_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
"deleted_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
]);
$this->forge->addPrimaryKey('id');
$this->forge->addForeignKey('pedido_id', 'pedidos', 'id');
$this->forge->addForeignKey('chat_department_id', 'chat_departments', 'id');
$this->forge->addForeignKey('factura_id', 'facturas', 'id');
$this->forge->addForeignKey('presupuesto_id', 'presupuestos', 'id');
$this->forge->createTable("chats", true);
}
public function down()
{
//
$this->forge->dropTable("chats", true);
}
}

View File

@ -0,0 +1,75 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;
class ChatMessages extends Migration
{
protected array $COLUMNS = [
"id" => [
"type" => "INT",
"auto_increment" => true,
],
"chat_id" => [
"type" => "INT",
"unsigned" => true
],
"sender_id" => [
"type" => "INT",
"unsigned" => true,
"null" => true,
],
"receiver_id" => [
"type" => "INT",
"unsigned" => true,
"null" => true,
],
"message" => [
"type" => "TEXT",
],
"viewed" => [
"type" => "TEXT",
"type" => "boolean",
"default" => false,
],
];
public function up()
{
$this->forge->addField($this->COLUMNS);
$currenttime = new RawSql("CURRENT_TIMESTAMP");
$this->forge->addField([
"created_at" => [
"type" => "TIMESTAMP",
"default" => $currenttime,
],
"updated_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
"deleted_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
]);
$this->forge->addPrimaryKey('id');
$this->forge->addForeignKey(['receiver_id'], 'users', ['id']);
$this->forge->addForeignKey(['sender_id'], 'users', ['id']);
$this->forge->addForeignKey(['chat_id'], 'chats', ['id']);
$this->forge->createTable("chat_messages", true);
}
public function down()
{
$this->forge->dropTable("chat_messages", true);
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;
class ChatDepartmentUsers extends Migration
{
protected array $COLUMNS = [
"chat_department_id" => [
"type" => "INT",
"unsigned" => true,
],
"user_id" => [
"type" => "INT",
"unsigned" => true,
],
];
public function up()
{
$this->forge->addField($this->COLUMNS);
$currenttime = new RawSql("CURRENT_TIMESTAMP");
$this->forge->addField([
"created_at" => [
"type" => "TIMESTAMP",
"default" => $currenttime,
],
"updated_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
"deleted_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
]);
$this->forge->addForeignKey(["user_id"], "users", ["id"]);
$this->forge->addForeignKey(["chat_department_id"], "chat_departments", ["id"]);
$this->forge->createTable("chat_department_users", true);
}
public function down()
{
$this->forge->dropTable("chat_department_users");
}
}

View File

@ -0,0 +1,61 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;
class ConfigVariablesApp extends Migration
{
protected array $COLUMNS = [
"id" => [
"type" => "INT",
"unsigned" => true,
"auto_increment" => true
],
"name" => [
"type" => "VARCHAR",
"constraint" => '45',
"unique" => true,
],
"value" => [
"type" => "VARCHAR",
"constraint" => '255',
"null" => true
],
"description" => [
"type" => "TEXT",
"null" => true
],
];
public function up()
{
$this->forge->addField($this->COLUMNS);
$currenttime = new RawSql("CURRENT_TIMESTAMP");
$this->forge->addField([
"created_at" => [
"type" => "TIMESTAMP",
"default" => $currenttime,
],
"updated_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
"deleted_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
]);
$this->forge->addPrimaryKey('id');
$this->forge->createTable("config_variables_app", true);
}
public function down()
{
$this->forge->dropTable("config_variables_app");
}
}

View File

@ -0,0 +1,55 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;
class ChatUsers extends Migration
{
protected array $COLUMNS = [
"id" => [
"type" => "INT",
"unsigned" => true,
"auto_increment" => true
],
"chat_id" => [
"type" => "INT",
"unsigned" => true,
],
"user_id" => [
"type" => "INT",
"unsigned" => true,
],
];
public function up()
{
$this->forge->addField($this->COLUMNS);
$currenttime = new RawSql("CURRENT_TIMESTAMP");
$this->forge->addField([
"created_at" => [
"type" => "TIMESTAMP",
"default" => $currenttime,
],
"updated_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
"deleted_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
]);
$this->forge->addPrimaryKey('id');
$this->forge->addForeignKey(["user_id"], "users", ["id"]);
$this->forge->addForeignKey(["chat_id"], "chats", ["id"]);
$this->forge->createTable("chat_users", true);
}
public function down()
{
$this->forge->dropTable("chat_users");
}
}

View File

@ -0,0 +1,33 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\RawSql;
use CodeIgniter\Database\Migration;
class AlterChatTableAddTitleColumn extends Migration
{
protected array $COLUMNS = [
"title" => [
"type" => "VARCHAR",
"constraint" => 255,
"null" => true
],
];
public function up()
{
$this->forge->addColumn("chats",$this->COLUMNS);
}
public function down()
{
//
$this->forge->dropColumn("chats","title");
}
}

View File

@ -0,0 +1,58 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;
class ChatNotifications extends Migration
{
protected array $COLUMNS = [
"id" => [
"type" => "INT",
"unsigned" => true,
"auto_increment" => true
],
"chat_message_id" => [
"type" => "INT",
],
"user_id" => [
"type" => "INT",
"unsigned" => true,
],
"viewed" => [
"type" => "BOOLEAN",
"default" => false
],
];
public function up()
{
$this->forge->addField($this->COLUMNS);
$currenttime = new RawSql("CURRENT_TIMESTAMP");
$this->forge->addField([
"created_at" => [
"type" => "TIMESTAMP",
"default" => $currenttime,
],
"updated_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
"deleted_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
]);
$this->forge->addPrimaryKey('id');
$this->forge->addForeignKey(["chat_message_id"], "chat_messages", ["id"]);
$this->forge->addForeignKey(["user_id"], "users", ["id"]);
$this->forge->createTable("chat_notifications", true);
}
public function down()
{
$this->forge->dropTable("chat_notifications");
}
}

View File

@ -0,0 +1,89 @@
<?php
namespace App\Database\Seeds;
use App\Models\Chat\ChatDeparmentModel;
use App\Models\Chat\ChatDeparmentUserModel;
use CodeIgniter\Database\Seeder;
use App\Models\Usuarios\UserModel;
class ChatSeeder extends Seeder
{
public function run()
{
$data = [
[
"name" => "_produccion",
"display" => "Producción",
"users" => [
"mbalbaci@safekat.com",
"mari.cano@safekat.com",
"beatriz@safekat.com",
"imnavajas@coit.es",
],
],
[
"name" => "_pod",
"display" => "POD",
"users" => [
"pod@safekat.com",
"imnavajas@coit.es",
],
],
[
"name" => "_maquetacion",
"display" => "Maquetación",
"users" => [
"maquetacion@safekat.com",
"imnavajas@coit.es",
],
],
// [
// "name" => "_comercial",
// "display" => "Comercial",
// "users" => [
// "incidencias@safekat.com",
// ],
// ],
[
"name" => "_incidencias",
"display" => "Incidencias",
"users" => [
"incidencias@safekat.com",
],
],
[
"name" => "_logistica",
"display" => "Logística",
"users" => [
"logistica@safekat.com",
"imnavajas@coit.es",
],
],
[
"name" => "_admin",
"display" => "Administración",
"users" => [
"contabilidad@safekat.com",
"imnavajas@coit.es",
],
],
];
$chatDeparmentModel = model(ChatDeparmentModel::class);
$chatDeparmentUsersModel = model(ChatDeparmentUserModel::class);
$userModel = model(UserModel::class);
foreach ($data as $row) {
$chatDeparmentId = $chatDeparmentModel->insert(["name" => $row["name"], "display" => $row["display"]]);
if (count($row["users"]) > 0) {
foreach ($row["users"] as $mail) {
$user = $userModel->like("username", explode("@",$mail)[0])->first();
if ($user) {
echo $user->id."\r\n";
$chatDeparmentUsersModel->insert(['user_id' => $user->id, "chat_department_id" => $chatDeparmentId]);
}
}
}
};
}
}

View File

@ -0,0 +1,37 @@
<?php
namespace App\Database\Seeds;
use App\Models\Configuracion\ConfigVariableModel;
use CodeIgniter\Database\Seeder;
class DefaultConfigVariablesSeeder extends Seeder
{
protected array $data = [
[
"name" => "tamanio_solapas_min",
"value" => 50,
"description" => "Mínimo tamaño solapas"
],
[
"name" => "tamanio_solapas_max",
"value" => 150,
"description" => "Máximo tamaño solapas"
],
[
"name" => "limite_produccion_diaria",
"value" => 6000,
"description" => "Número de libros máximos que se puede producir al día"
],
];
public function run()
{
$variableModel = model(ConfigVariableModel::class);
foreach ($this->data as $row) {
if($variableModel->where("name",$row["name"])->first() == null){
$variableModel->insert($row);
}
}
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Entities\Configuracion;
use CodeIgniter\Entity;
class SeriesFacturasEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
'id' => null,
'nombre' => null,
'tipo' => 'facturacion', // default value
'formato' => null,
'next' => 1, // default value
'grupo' => 0, // default value
'created_at' => null, // default value
'updated_at' => null, // default value
];
protected $casts = [
];
}

View File

@ -0,0 +1,16 @@
<?php
namespace App\Entities\Configuracion;
use CodeIgniter\Entity;
class UbicacionesEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
'id' => null,
'nombre' => null,
'deleted_at' => null, // default value
];
protected $casts = [
];
}

View File

@ -0,0 +1,51 @@
<?php
namespace App\Entities\Facturas;
class FacturaEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
'id' => null,
'pedido_id' => null,
'factura_rectificada_id' => null,
'factura_rectificativa_id' => null,
'cliente_id' => null,
'serie_id' => null,
'numero' => null,
'estado' => null,
'estado_pago' => null,
'fecha_factura_at' => null,
'notas' => null,
'base' => null,
'total' => null,
'pendiente' => null,
'total_pagos' => null,
'creditoAsegurado' => null,
'cliente_nombre' => null,
'cliente_address' => null,
'cliente_cif' => null,
'cliente_pais' => null,
'cliente_cp' => null,
'cliente_ciudad' => null,
'cliente_provincia' => null,
'created_at' => null,
'updated_at' => null,
'deleted_at' => null,
'user_created_id' => null,
'user_updated_id' => null,
];
protected $casts = [
'id' => 'int',
'pedido_id' => 'int',
'cliente_id' => 'int',
'serie_id' => 'int',
'base' => 'float',
'total' => 'float',
'pendiente' => 'float',
'total_pagos' => 'float',
'creditoAsegurado' => 'float',
];
}

View File

@ -0,0 +1,39 @@
<?php
namespace App\Entities\Facturas;
class FacturaLineaEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
'id' => null,
'factura_id' => null,
'pedido_linea_impresion_id' => null,
'pedido_maquetacion_id' => null,
'descripcion' => null,
'cantidad' => null,
'precio_unidad' => null,
'iva' => null,
'base' => null,
'total_iva' => null,
'total' => null,
'data' => null,
'deleted_at' => null,
'user_updated_id' => null,
];
protected $casts = [
'id' => 'int',
'factura_id' => 'int',
'pedido_linea_impresion_id' => 'int',
'pedido_maquetacion_id' => 'int',
'cantidad' => 'float',
'precio_unidad' => 'float',
'iva' => 'float',
'base' => 'float',
'total_iva' => 'float',
'total' => 'float',
];
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Entities\Facturas;
class FacturaPagoEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
'id' => null,
'factura_id' => null,
'notes' => null,
'fecha_pago_at' => null,
'fecha_vencimiento_at' => null,
'forma_pago_id' => null,
'total' => null,
'deleted_at' => null,
'user_updated_id' => null,
];
protected $casts = [
'id' => 'int',
'factura_id' => 'int',
'forma_pago_id' => 'int',
'total' => 'float',
];
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Entities\Mensajeria;
use CodeIgniter\Entity\Entity;
class ConversacionEntity extends Entity
{
protected $attributes = [
'id' => null,
'pedido_libro_id' => null,
'pedido_maquetacion_id' => null,
'factura_id' => null,
'departamento' => null,
'asunto' => null,
'created_at' => null,
'updated_at' => null,
'deleted_at' => null,
];
protected $casts = [
"pedido_libro_id" => "?int",
"pedido_maquetacion_id" => "?int",
"factura_id" => "?int"
];
}

View File

@ -0,0 +1,26 @@
<?php
namespace App\Entities\Mensajeria;
use CodeIgniter\Entity\Entity;
class ParticipanteEntity extends Entity
{
protected $attributes = [
'id' => null,
'conversacion_id' => null,
'usuario_id' => null,
'cliente_id' => null,
'email' => null,
'last_read' => null,
'created_at' => null,
'updated_at' => null,
'deleted_at' => null,
];
protected $casts = [
"conversacion_id" => "?int",
"usuario_id" => "?int",
"cliente_id" => "?int"
];
}

View File

@ -0,0 +1,46 @@
<?php
namespace App\Entities\Pedidos;
use CodeIgniter\Entity;
class AlbaranEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
'id' => null,
'pedido_id' => null,
'presupuesto_id' => null,
'presupuesto_direccion_id' => null,
'cliente_id' => null,
'serie_id' => null,
'numero_albaran' => null,
'mostrar_precios' => null,
'total' => null,
'direccion_albaran' => null,
'att_albaran' => null,
'user_created_id' => null,
'user_updated_id' => null,
'created_at' => null,
'updated_at' => null,
'deleted_at' => null,
];
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $casts = [
'id' => 'integer',
'pedido_id' => '?integer',
'presupuesto_id' => '?integer',
'presupuesto_direccion_id' => '?integer',
'cliente_id' => '?integer',
'serie_id' => '?integer',
'numero_albaran' => '?string',
'mostrar_precios' => '?boolean',
'total' => 'float',
'direccion_albaran' => '?string',
'att_albaran' => '?string',
'user_created_id' => 'integer',
'user_updated_id' => 'integer',
];
// Agrega tus métodos personalizados aquí
}

View File

@ -0,0 +1,40 @@
<?php
namespace App\Entities\Pedidos;
use CodeIgniter\Entity;
class AlbaranLineaEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
'id' => null,
'albaran_id' => null,
'titulo' => null,
'isbn' => null,
'ref_cliente' => null,
'cantidad' => null,
'cajas' => null,
'ejemplares_por_caja' => null,
'precio_unidad' => null,
'total' => null,
'user_created_id' => null,
'user_updated_id' => null,
'created_at' => null,
'updated_at' => null,
'deleted_at' => null,
];
protected $casts = [
'id' => 'integer',
'albaran_id' => '?integer',
'titulo' => 'string',
'isbn' => '?string',
'ref_cliente' => '?string',
'cantidad' => '?integer',
'cajas' => '?integer',
'ejemplares_por_caja' => '?integer',
'precio_unidad' => 'float',
'total' => 'float',
'user_created_id' => 'integer',
'user_updated_id' => 'integer',
];
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Entities\Pedidos;
use CodeIgniter\Entity;
class PedidoEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
"id" => null,
"total_precio" => null,
"total_tirada" => null,
"estado" => null,
"user_created_id" => null,
"user_updated_id" => null,
"user_validated_id" => null,
"fecha_entrega_real" => null,
"fecha_impresion" => null,
"fecha_encuadernado" => null,
"fecha_entrega_externo" => null,
"created_at" => null,
"updated_at" => null,
"validated_at" => null,
];
protected $casts = [
"total_precio" => "float",
"total_tirada" => "float",
];
}

View File

@ -0,0 +1,25 @@
<?php
namespace App\Entities\Pedidos;
use CodeIgniter\Entity;
class PedidoLineaEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
"id" => null,
"pedido_id" => null,
"presupuesto_id" => null,
"ubicacion_id" => null,
"user_created_id" => null,
"user_updated_id" => null,
"created_at" => null,
"updated_at" => null,
];
protected $casts = [
"pedido_id" => "int",
"presupuesto_id" => "int",
"ubicacion_id" => "int",
];
}

View File

@ -9,6 +9,7 @@ class PresupuestoAcabadosEntity extends \CodeIgniter\Entity\Entity
"id" => null, "id" => null,
"presupuesto_id" => null, "presupuesto_id" => null,
"tarifa_acabado_id" => null, "tarifa_acabado_id" => null,
"proveedor_id" => null,
"precio_unidad" => null, "precio_unidad" => null,
"precio_total" => null, "precio_total" => null,
"margen" => null, "margen" => null,
@ -20,6 +21,7 @@ class PresupuestoAcabadosEntity extends \CodeIgniter\Entity\Entity
protected $casts = [ protected $casts = [
"presupuesto_id" => "int", "presupuesto_id" => "int",
"tarifa_acabado_id" => "int", "tarifa_acabado_id" => "int",
"proveedor_id" => "int",
"precio_unidad" => "float", "precio_unidad" => "float",
"precio_total" => "float", "precio_total" => "float",
"margen" => "float", "margen" => "float",

View File

@ -9,7 +9,9 @@ class PresupuestoEncuadernacionesEntity extends \CodeIgniter\Entity\Entity
"id" => null, "id" => null,
"presupuesto_id" => null, "presupuesto_id" => null,
"tarifa_encuadernado_id" => null, "tarifa_encuadernado_id" => null,
"proveedor_id" => null,
"precio_unidad" => null, "precio_unidad" => null,
"paginas_por_cuadernillo" => null,
"tiempo" => null, "tiempo" => null,
"precio_total" => null, "precio_total" => null,
"margen" => null, "margen" => null,
@ -19,7 +21,9 @@ class PresupuestoEncuadernacionesEntity extends \CodeIgniter\Entity\Entity
protected $casts = [ protected $casts = [
"presupuesto_id" => "int", "presupuesto_id" => "int",
"tarifa_encuadernado_id" => "int", "tarifa_encuadernado_id" => "int",
"proveedor_id" => "int",
"precio_unidad" => "float", "precio_unidad" => "float",
"paginas_por_cuadernillo" => "int",
"tiempo" => "float", "tiempo" => "float",
"precio_total" => "float", "precio_total" => "float",
"margen" => "float", "margen" => "float",

View File

@ -64,7 +64,7 @@ class PresupuestoEntity extends \CodeIgniter\Entity\Entity
"created_at" => null, "created_at" => null,
"updated_at" => null, "updated_at" => null,
"comp_tipo_impresion" => null, "comp_tipo_impresion" => null,
"comp_pos_paginas_color" => null, "pos_paginas_color" => null,
"total_coste_papel" => null, "total_coste_papel" => null,
"total_margen_papel" => null, "total_margen_papel" => null,
"total_margenPercent_papel" => null, "total_margenPercent_papel" => null,
@ -81,13 +81,20 @@ class PresupuestoEntity extends \CodeIgniter\Entity\Entity
"total_antes_descuento" => null, "total_antes_descuento" => null,
"total_descuento" => null, "total_descuento" => null,
"total_descuentoPercent" => null, "total_descuentoPercent" => null,
"total_presupuesto" => null,
"total_precio_unidad" => null, "total_precio_unidad" => null,
"total_factor" => null, "total_factor" => null,
"total_factor_ponderado" => null, "total_factor_ponderado" => null,
'total_aceptado' => null,
'iva_reducido' => null,
'excluir_rotativa' => null,
"acabado_cubierta_id" => null, "acabado_cubierta_id" => null,
"acabado_sobrecubierta_id" => null, "acabado_sobrecubierta_id" => null,
"is_duplicado" => false, "is_duplicado" => false,
'paginas_color_consecutivas' => null,
'papel_interior_diferente' => null,
'paginasCuadernillo' => null,
'lomo_redondo' => null,
'cabezada' => null,
]; ];
protected $casts = [ protected $casts = [
"cliente_id" => "int", "cliente_id" => "int",
@ -124,7 +131,6 @@ class PresupuestoEntity extends \CodeIgniter\Entity\Entity
"merma_cubierta" => "float", "merma_cubierta" => "float",
"lomo_cubierta" => "?float", "lomo_cubierta" => "?float",
"lomo_sobrecubierta" => "?float", "lomo_sobrecubierta" => "?float",
"total_presupuesto" => "?float",
"envios_recoge_cliente" => "boolean", "envios_recoge_cliente" => "boolean",
"aprobado_user_id" => "?int", "aprobado_user_id" => "?int",
"is_deleted" => "int", "is_deleted" => "int",
@ -148,8 +154,15 @@ class PresupuestoEntity extends \CodeIgniter\Entity\Entity
"total_precio_unidad" => "?float", "total_precio_unidad" => "?float",
"total_factor" => "?float", "total_factor" => "?float",
"total_factor_ponderado" => "?float", "total_factor_ponderado" => "?float",
'total_aceptado' => "?float",
'iva_reducido' => "?boolean",
'excluir_rotativa' => "?boolean",
"acabado_cubierta_id" => "int", "acabado_cubierta_id" => "int",
"acabado_sobrecubierta_id" => "int", "acabado_sobrecubierta_id" => "int",
"is_duplicado" => "boolean", "is_duplicado" => "boolean",
'paginas_color_consecutivas' => "boolean",
'papel_interior_diferente' => "boolean",
'paginasCuadernillo' => "int",
'lomo_redondo' => "boolean",
]; ];
} }

View File

@ -0,0 +1,19 @@
<?php
namespace App\Entities\Presupuestos;
use CodeIgniter\Entity;
class PresupuestoFicheroEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
"id" => null,
"presupuesto_id" => null,
"nombre" => null,
"file_path" => null,
"upload_by" => null,
"upload_at" => null,
];
protected $casts = [
"presupuesto_id" => "int",
];
}

View File

@ -8,6 +8,8 @@ class TarifaAcabadoEntity extends \CodeIgniter\Entity\Entity
protected $attributes = [ protected $attributes = [
"id" => null, "id" => null,
"nombre" => null, "nombre" => null,
"code" => null,
"comment" => null,
"precio_min" => 0, "precio_min" => 0,
"importe_fijo" => 0, "importe_fijo" => 0,
"mostrar_en_presupuesto" => 1, "mostrar_en_presupuesto" => 1,
@ -22,6 +24,8 @@ class TarifaAcabadoEntity extends \CodeIgniter\Entity\Entity
]; ];
protected $casts = [ protected $casts = [
"precio_min" => "float", "precio_min" => "float",
"comment" => "string",
"code" => "string",
"importe_fijo" => "float", "importe_fijo" => "float",
"user_created_id" => "int", "user_created_id" => "int",
"user_updated_id" => "int", "user_updated_id" => "int",

View File

@ -8,6 +8,7 @@ class TarifaAcabadoLineaEntity extends \CodeIgniter\Entity\Entity
protected $attributes = [ protected $attributes = [
"id" => null, "id" => null,
"tarifa_acabado_id" => 0, "tarifa_acabado_id" => 0,
"proveedor_id" => 0,
"tirada_min" => 0, "tirada_min" => 0,
"tirada_max" => 0, "tirada_max" => 0,
"precio_min" => 0, "precio_min" => 0,
@ -21,6 +22,7 @@ class TarifaAcabadoLineaEntity extends \CodeIgniter\Entity\Entity
]; ];
protected $casts = [ protected $casts = [
"tarifa_acabado_id" => "int", "tarifa_acabado_id" => "int",
"proveedor_id" => "int",
"tirada_min" => "int", "tirada_min" => "int",
"tirada_max" => "int", "tirada_max" => "int",
"precio_min" => "float", "precio_min" => "float",

View File

@ -9,6 +9,7 @@ class TarifaEncuadernacionEntity extends \CodeIgniter\Entity\Entity
protected $attributes = [ protected $attributes = [
"id" => null, "id" => null,
"nombre" => null, "nombre" => null,
"code" => null,
"mostrar_en_presupuesto" => 1, "mostrar_en_presupuesto" => 1,
"tipo_encuadernacion" => 0, "tipo_encuadernacion" => 0,
"servicio_encuadernacion" => 0, "servicio_encuadernacion" => 0,
@ -22,6 +23,7 @@ class TarifaEncuadernacionEntity extends \CodeIgniter\Entity\Entity
]; ];
protected $casts = [ protected $casts = [
"mostrar_en_presupuesto" => "int", "mostrar_en_presupuesto" => "int",
"code" => "string",
"tipo_encuadernacion" => "int", "tipo_encuadernacion" => "int",
"servicio_encuadernacion" => "int", "servicio_encuadernacion" => "int",
"por_horas" => "int", "por_horas" => "int",

View File

@ -15,6 +15,7 @@ class TarifaEncuadernacionLinea extends \CodeIgniter\Entity\Entity
"precio_max" => 0, "precio_max" => 0,
"tirada_min" => 0, "tirada_min" => 0,
"tirada_max" => 0, "tirada_max" => 0,
"total_min" => 0,
"margen" => 0, "margen" => 0,
"user_created_id" => 0, "user_created_id" => 0,
"user_updated_id" => 0, "user_updated_id" => 0,
@ -31,6 +32,7 @@ class TarifaEncuadernacionLinea extends \CodeIgniter\Entity\Entity
"precio_max" => "float", "precio_max" => "float",
"tirada_min" => "float", "tirada_min" => "float",
"tirada_max" => "float", "tirada_max" => "float",
"total_min" => "float",
"margen" => "float", "margen" => "float",
"user_created_id" => "int", "user_created_id" => "int",
"user_updated_id" => "int", "user_updated_id" => "int",

View File

@ -11,6 +11,7 @@ class TarifaEncuadernacionLineaHoras extends \CodeIgniter\Entity\Entity
"tiempo_min" => 0, "tiempo_min" => 0,
"tiempo_max" => 0, "tiempo_max" => 0,
"precio_hora" => 0, "precio_hora" => 0,
"total_min" => 0,
"margen" => 0, "margen" => 0,
"user_created_id" => 0, "user_created_id" => 0,
"user_updated_id" => 0, "user_updated_id" => 0,
@ -22,6 +23,7 @@ class TarifaEncuadernacionLineaHoras extends \CodeIgniter\Entity\Entity
"tirada_encuadernacion_id" => "int", "tirada_encuadernacion_id" => "int",
"tiempo_min" => "float", "tiempo_min" => "float",
"tiempo_max" => "float", "tiempo_max" => "float",
"total_min" => "float",
"precio_hora" => "float", "precio_hora" => "float",
"margen" => "float", "margen" => "float",
"user_created_id" => "int", "user_created_id" => "int",

View File

@ -11,7 +11,6 @@ class TarifaEncuadernacionTirada extends \CodeIgniter\Entity\Entity
"tirada_min" => 0, "tirada_min" => 0,
"tirada_max" => 0, "tirada_max" => 0,
"proveedor_id" => 0, "proveedor_id" => 0,
"precio_min" => 0,
"importe_fijo" => 0, "importe_fijo" => 0,
"user_created_id" => 0, "user_created_id" => 0,
"user_updated_id" => 0, "user_updated_id" => 0,
@ -24,7 +23,6 @@ class TarifaEncuadernacionTirada extends \CodeIgniter\Entity\Entity
"tirada_min" => "float", "tirada_min" => "float",
"tirada_max" => "float", "tirada_max" => "float",
"proveedor_id" => "int", "proveedor_id" => "int",
"precio_min" => "float",
"importe_fijo" => "float", "importe_fijo" => "float",
"user_created_id" => "int", "user_created_id" => "int",
"user_updated_id" => "int", "user_updated_id" => "int",

View File

@ -9,6 +9,8 @@ class TarifaEnvioEntity extends \CodeIgniter\Entity\Entity
"id" => null, "id" => null,
"pais_id" => null, "pais_id" => null,
"nombre" => null, "nombre" => null,
"code" => null,
"comment" => null,
"user_created_id" => 0, "user_created_id" => 0,
"user_updated_id" => 0, "user_updated_id" => 0,
"is_deleted" => 0, "is_deleted" => 0,
@ -17,6 +19,8 @@ class TarifaEnvioEntity extends \CodeIgniter\Entity\Entity
]; ];
protected $casts = [ protected $casts = [
"pais_id" => "?int", "pais_id" => "?int",
"code" => "string",
"comment" => "string",
"user_created_id" => "int", "user_created_id" => "int",
"user_updated_id" => "int", "user_updated_id" => "int",
"is_deleted" => "int", "is_deleted" => "int",

View File

@ -9,6 +9,8 @@ class TarifaManipuladoEntity extends \CodeIgniter\Entity\Entity
protected $attributes = [ protected $attributes = [
"id" => null, "id" => null,
"nombre" => null, "nombre" => null,
"code" => null,
"comment" => null,
"precio_min" => 0, "precio_min" => 0,
"importe_fijo" => 0, "importe_fijo" => 0,
"mostrar_en_presupuesto" => 1, "mostrar_en_presupuesto" => 1,
@ -22,6 +24,8 @@ class TarifaManipuladoEntity extends \CodeIgniter\Entity\Entity
protected $casts = [ protected $casts = [
"precio_min" => "float", "precio_min" => "float",
"importe_fijo" => "float", "importe_fijo" => "float",
"code" => "string",
"comment" => "string",
"mostrar_en_presupuesto" => "int", "mostrar_en_presupuesto" => "int",
"user_created_id" => "int", "user_created_id" => "int",
"user_updated_id" => "int", "user_updated_id" => "int",

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