iatoolkit 0.4.2__py3-none-any.whl → 0.66.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. iatoolkit/__init__.py +13 -35
  2. iatoolkit/base_company.py +74 -8
  3. iatoolkit/cli_commands.py +15 -23
  4. iatoolkit/common/__init__.py +0 -0
  5. iatoolkit/common/exceptions.py +46 -0
  6. iatoolkit/common/routes.py +141 -0
  7. iatoolkit/common/session_manager.py +24 -0
  8. iatoolkit/common/util.py +348 -0
  9. iatoolkit/company_registry.py +7 -8
  10. iatoolkit/iatoolkit.py +169 -96
  11. iatoolkit/infra/__init__.py +5 -0
  12. iatoolkit/infra/call_service.py +140 -0
  13. iatoolkit/infra/connectors/__init__.py +5 -0
  14. iatoolkit/infra/connectors/file_connector.py +17 -0
  15. iatoolkit/infra/connectors/file_connector_factory.py +57 -0
  16. iatoolkit/infra/connectors/google_cloud_storage_connector.py +53 -0
  17. iatoolkit/infra/connectors/google_drive_connector.py +68 -0
  18. iatoolkit/infra/connectors/local_file_connector.py +46 -0
  19. iatoolkit/infra/connectors/s3_connector.py +33 -0
  20. iatoolkit/infra/gemini_adapter.py +356 -0
  21. iatoolkit/infra/google_chat_app.py +57 -0
  22. iatoolkit/infra/llm_client.py +429 -0
  23. iatoolkit/infra/llm_proxy.py +139 -0
  24. iatoolkit/infra/llm_response.py +40 -0
  25. iatoolkit/infra/mail_app.py +145 -0
  26. iatoolkit/infra/openai_adapter.py +90 -0
  27. iatoolkit/infra/redis_session_manager.py +122 -0
  28. iatoolkit/locales/en.yaml +144 -0
  29. iatoolkit/locales/es.yaml +140 -0
  30. iatoolkit/repositories/__init__.py +5 -0
  31. iatoolkit/repositories/database_manager.py +110 -0
  32. iatoolkit/repositories/document_repo.py +33 -0
  33. iatoolkit/repositories/llm_query_repo.py +91 -0
  34. iatoolkit/repositories/models.py +336 -0
  35. iatoolkit/repositories/profile_repo.py +123 -0
  36. iatoolkit/repositories/tasks_repo.py +52 -0
  37. iatoolkit/repositories/vs_repo.py +139 -0
  38. iatoolkit/services/__init__.py +5 -0
  39. iatoolkit/services/auth_service.py +193 -0
  40. {services → iatoolkit/services}/benchmark_service.py +6 -6
  41. iatoolkit/services/branding_service.py +149 -0
  42. {services → iatoolkit/services}/dispatcher_service.py +39 -99
  43. {services → iatoolkit/services}/document_service.py +5 -5
  44. {services → iatoolkit/services}/excel_service.py +27 -21
  45. {services → iatoolkit/services}/file_processor_service.py +5 -5
  46. iatoolkit/services/help_content_service.py +30 -0
  47. {services → iatoolkit/services}/history_service.py +8 -16
  48. iatoolkit/services/i18n_service.py +104 -0
  49. {services → iatoolkit/services}/jwt_service.py +18 -27
  50. iatoolkit/services/language_service.py +77 -0
  51. {services → iatoolkit/services}/load_documents_service.py +19 -14
  52. {services → iatoolkit/services}/mail_service.py +5 -5
  53. iatoolkit/services/onboarding_service.py +43 -0
  54. {services → iatoolkit/services}/profile_service.py +155 -89
  55. {services → iatoolkit/services}/prompt_manager_service.py +26 -11
  56. {services → iatoolkit/services}/query_service.py +142 -104
  57. {services → iatoolkit/services}/search_service.py +21 -5
  58. {services → iatoolkit/services}/sql_service.py +24 -6
  59. {services → iatoolkit/services}/tasks_service.py +10 -10
  60. iatoolkit/services/user_feedback_service.py +103 -0
  61. iatoolkit/services/user_session_context_service.py +143 -0
  62. iatoolkit/static/images/fernando.jpeg +0 -0
  63. iatoolkit/static/js/chat_feedback_button.js +80 -0
  64. iatoolkit/static/js/chat_filepond.js +85 -0
  65. iatoolkit/static/js/chat_help_content.js +124 -0
  66. iatoolkit/static/js/chat_history_button.js +112 -0
  67. iatoolkit/static/js/chat_logout_button.js +36 -0
  68. iatoolkit/static/js/chat_main.js +364 -0
  69. iatoolkit/static/js/chat_onboarding_button.js +97 -0
  70. iatoolkit/static/js/chat_prompt_manager.js +94 -0
  71. iatoolkit/static/js/chat_reload_button.js +35 -0
  72. iatoolkit/static/styles/chat_iatoolkit.css +592 -0
  73. iatoolkit/static/styles/chat_modal.css +169 -0
  74. iatoolkit/static/styles/chat_public.css +107 -0
  75. iatoolkit/static/styles/landing_page.css +182 -0
  76. iatoolkit/static/styles/llm_output.css +115 -0
  77. iatoolkit/static/styles/onboarding.css +169 -0
  78. iatoolkit/system_prompts/query_main.prompt +5 -15
  79. iatoolkit/templates/_company_header.html +20 -0
  80. iatoolkit/templates/_login_widget.html +42 -0
  81. iatoolkit/templates/about.html +13 -0
  82. iatoolkit/templates/base.html +65 -0
  83. iatoolkit/templates/change_password.html +66 -0
  84. iatoolkit/templates/chat.html +287 -0
  85. iatoolkit/templates/chat_modals.html +181 -0
  86. iatoolkit/templates/error.html +51 -0
  87. iatoolkit/templates/forgot_password.html +50 -0
  88. iatoolkit/templates/index.html +145 -0
  89. iatoolkit/templates/login_simulation.html +34 -0
  90. iatoolkit/templates/onboarding_shell.html +104 -0
  91. iatoolkit/templates/signup.html +76 -0
  92. iatoolkit/views/__init__.py +5 -0
  93. iatoolkit/views/base_login_view.py +92 -0
  94. iatoolkit/views/change_password_view.py +117 -0
  95. iatoolkit/views/external_login_view.py +73 -0
  96. iatoolkit/views/file_store_api_view.py +65 -0
  97. iatoolkit/views/forgot_password_view.py +72 -0
  98. iatoolkit/views/help_content_api_view.py +54 -0
  99. iatoolkit/views/history_api_view.py +56 -0
  100. iatoolkit/views/home_view.py +61 -0
  101. iatoolkit/views/index_view.py +14 -0
  102. iatoolkit/views/init_context_api_view.py +73 -0
  103. iatoolkit/views/llmquery_api_view.py +57 -0
  104. iatoolkit/views/login_simulation_view.py +81 -0
  105. iatoolkit/views/login_view.py +153 -0
  106. iatoolkit/views/logout_api_view.py +49 -0
  107. iatoolkit/views/profile_api_view.py +46 -0
  108. iatoolkit/views/prompt_api_view.py +37 -0
  109. iatoolkit/views/signup_view.py +94 -0
  110. iatoolkit/views/tasks_api_view.py +72 -0
  111. iatoolkit/views/tasks_review_api_view.py +55 -0
  112. iatoolkit/views/user_feedback_api_view.py +60 -0
  113. iatoolkit/views/verify_user_view.py +62 -0
  114. {iatoolkit-0.4.2.dist-info → iatoolkit-0.66.2.dist-info}/METADATA +2 -2
  115. iatoolkit-0.66.2.dist-info/RECORD +119 -0
  116. {iatoolkit-0.4.2.dist-info → iatoolkit-0.66.2.dist-info}/top_level.txt +0 -1
  117. iatoolkit/system_prompts/arquitectura.prompt +0 -32
  118. iatoolkit-0.4.2.dist-info/RECORD +0 -32
  119. services/__init__.py +0 -5
  120. services/api_service.py +0 -75
  121. services/user_feedback_service.py +0 -67
  122. services/user_session_context_service.py +0 -85
  123. {iatoolkit-0.4.2.dist-info → iatoolkit-0.66.2.dist-info}/WHEEL +0 -0
@@ -0,0 +1,143 @@
1
+ # Copyright (c) 2024 Fernando Libedinsky
2
+ # Product: IAToolkit
3
+ #
4
+ # IAToolkit is open source software.
5
+
6
+ from iatoolkit.infra.redis_session_manager import RedisSessionManager
7
+ from typing import List, Dict, Optional
8
+ import json
9
+ import logging
10
+
11
+
12
+ class UserSessionContextService:
13
+ """
14
+ Gestiona el contexto de la sesión del usuario usando un único Hash de Redis por sesión.
15
+ Esto mejora la atomicidad y la eficiencia.
16
+ """
17
+
18
+ def _get_session_key(self, company_short_name: str, user_identifier: str) -> Optional[str]:
19
+ """Devuelve la clave única de Redis para el Hash de sesión del usuario."""
20
+ user_identifier = (user_identifier or "").strip()
21
+ if not company_short_name or not user_identifier:
22
+ return None
23
+ return f"session:{company_short_name}/{user_identifier}"
24
+
25
+ def clear_all_context(self, company_short_name: str, user_identifier: str):
26
+ """Limpia el contexto del LLM en la sesión para un usuario de forma atómica."""
27
+ session_key = self._get_session_key(company_short_name, user_identifier)
28
+ if session_key:
29
+ # RedisSessionManager.remove(session_key)
30
+ # 'profile_data' should not be deleted
31
+ RedisSessionManager.hdel(session_key, 'context_version')
32
+ RedisSessionManager.hdel(session_key, 'context_history')
33
+ RedisSessionManager.hdel(session_key, 'last_response_id')
34
+
35
+ def clear_llm_history(self, company_short_name: str, user_identifier: str):
36
+ """Limpia solo los campos relacionados con el historial del LLM (ID y chat)."""
37
+ session_key = self._get_session_key(company_short_name, user_identifier)
38
+ if session_key:
39
+ RedisSessionManager.hdel(session_key, 'last_response_id', 'context_history')
40
+
41
+ def get_last_response_id(self, company_short_name: str, user_identifier: str) -> Optional[str]:
42
+ session_key = self._get_session_key(company_short_name, user_identifier)
43
+ if not session_key:
44
+ return None
45
+ return RedisSessionManager.hget(session_key, 'last_response_id')
46
+
47
+ def save_last_response_id(self, company_short_name: str, user_identifier: str, response_id: str):
48
+ session_key = self._get_session_key(company_short_name, user_identifier)
49
+ if session_key:
50
+ RedisSessionManager.hset(session_key, 'last_response_id', response_id)
51
+
52
+ def save_context_history(self, company_short_name: str, user_identifier: str, context_history: List[Dict]):
53
+ session_key = self._get_session_key(company_short_name, user_identifier)
54
+ if session_key:
55
+ try:
56
+ history_json = json.dumps(context_history)
57
+ RedisSessionManager.hset(session_key, 'context_history', history_json)
58
+ except (TypeError, ValueError) as e:
59
+ logging.error(f"Error al serializar context_history para {session_key}: {e}")
60
+
61
+ def get_context_history(self, company_short_name: str, user_identifier: str) -> Optional[List[Dict]]:
62
+ session_key = self._get_session_key(company_short_name, user_identifier)
63
+ if not session_key:
64
+ return None
65
+
66
+ history_json = RedisSessionManager.hget(session_key, 'context_history')
67
+ if not history_json:
68
+ return []
69
+
70
+ try:
71
+ return json.loads(history_json)
72
+ except json.JSONDecodeError:
73
+ return []
74
+
75
+ def save_profile_data(self, company_short_name: str, user_identifier: str, data: dict):
76
+ session_key = self._get_session_key(company_short_name, user_identifier)
77
+ if session_key:
78
+ try:
79
+ data_json = json.dumps(data)
80
+ RedisSessionManager.hset(session_key, 'profile_data', data_json)
81
+ except (TypeError, ValueError) as e:
82
+ logging.error(f"Error al serializar profile_data para {session_key}: {e}")
83
+
84
+ def get_profile_data(self, company_short_name: str, user_identifier: str) -> dict:
85
+ session_key = self._get_session_key(company_short_name, user_identifier)
86
+ if not session_key:
87
+ return {}
88
+
89
+ data_json = RedisSessionManager.hget(session_key, 'profile_data')
90
+ if not data_json:
91
+ return {}
92
+
93
+ try:
94
+ return json.loads(data_json)
95
+ except json.JSONDecodeError:
96
+ return {}
97
+
98
+ def save_context_version(self, company_short_name: str, user_identifier: str, version: str):
99
+ session_key = self._get_session_key(company_short_name, user_identifier)
100
+ if session_key:
101
+ RedisSessionManager.hset(session_key, 'context_version', version)
102
+
103
+ def get_context_version(self, company_short_name: str, user_identifier: str) -> Optional[str]:
104
+ session_key = self._get_session_key(company_short_name, user_identifier)
105
+ if not session_key:
106
+ return None
107
+ return RedisSessionManager.hget(session_key, 'context_version')
108
+
109
+ def save_prepared_context(self, company_short_name: str, user_identifier: str, context: str, version: str):
110
+ """Guarda un contexto de sistema pre-renderizado y su versión, listos para ser enviados al LLM."""
111
+ session_key = self._get_session_key(company_short_name, user_identifier)
112
+ if session_key:
113
+ RedisSessionManager.hset(session_key, 'prepared_context', context)
114
+ RedisSessionManager.hset(session_key, 'prepared_context_version', version)
115
+
116
+ def get_and_clear_prepared_context(self, company_short_name: str, user_identifier: str) -> tuple:
117
+ """Obtiene el contexto preparado y su versión, y los elimina para asegurar que se usan una sola vez."""
118
+ session_key = self._get_session_key(company_short_name, user_identifier)
119
+ if not session_key:
120
+ return None, None
121
+
122
+ pipe = RedisSessionManager.pipeline()
123
+ pipe.hget(session_key, 'prepared_context')
124
+ pipe.hget(session_key, 'prepared_context_version')
125
+ pipe.hdel(session_key, 'prepared_context', 'prepared_context_version')
126
+ results = pipe.execute()
127
+
128
+ # results[0] es el contexto, results[1] es la versión
129
+ return (results[0], results[1]) if results else (None, None)
130
+
131
+ # --- Métodos de Bloqueo ---
132
+ def acquire_lock(self, lock_key: str, expire_seconds: int) -> bool:
133
+ """Intenta adquirir un lock. Devuelve True si se adquiere, False si no."""
134
+ # SET con NX (solo si no existe) y EX (expiración) es una operación atómica.
135
+ return RedisSessionManager.set(lock_key, "1", ex=expire_seconds, nx=True)
136
+
137
+ def release_lock(self, lock_key: str):
138
+ """Libera un lock."""
139
+ RedisSessionManager.remove(lock_key)
140
+
141
+ def is_locked(self, lock_key: str) -> bool:
142
+ """Verifica si un lock existe."""
143
+ return RedisSessionManager.exists(lock_key)
Binary file
@@ -0,0 +1,80 @@
1
+ $(document).ready(function () {
2
+ const feedbackModal = $('#feedbackModal');
3
+ $('#submit-feedback').on('click', function () {
4
+ sendFeedback(this);
5
+ });
6
+
7
+ // Evento para enviar el feedback
8
+ async function sendFeedback(submitButton) {
9
+ toastr.options = {"positionClass": "toast-bottom-right", "preventDuplicates": true};
10
+ const feedbackText = $('#feedback-text').val().trim();
11
+ const activeStars = $('.star.active').length;
12
+
13
+ if (!feedbackText) {
14
+ toastr.error(t_js('feedback_comment_error'));
15
+ return;
16
+ }
17
+
18
+ if (activeStars === 0) {
19
+ toastr.error(t_js('feedback_rating_error'));
20
+ return;
21
+ }
22
+
23
+ submitButton.disabled = true;
24
+
25
+ // call the IAToolkit API to send feedback
26
+ const data = {
27
+ "user_identifier": window.user_identifier,
28
+ "message": feedbackText,
29
+ "rating": activeStars,
30
+ };
31
+
32
+ const responseData = await callToolkit('/api/feedback', data, "POST");
33
+ if (responseData)
34
+ toastr.success(t_js('feedback_sent_success_body'), t_js('feedback_sent_success_title'));
35
+ else
36
+ toastr.error(t_js('feedback_sent_error'));
37
+
38
+ submitButton.disabled = false;
39
+ feedbackModal.modal('hide');
40
+ }
41
+
42
+ // Evento para abrir el modal de feedback
43
+ $('#send-feedback-button').on('click', function () {
44
+ $('#submit-feedback').prop('disabled', false);
45
+ $('.star').removeClass('active hover-active'); // Resetea estrellas
46
+ $('#feedback-text').val('');
47
+ feedbackModal.modal('show');
48
+ });
49
+
50
+ // Evento que se dispara DESPUÉS de que el modal se ha ocultado
51
+ $('#feedbackModal').on('hidden.bs.modal', function () {
52
+ $('#feedback-text').val('');
53
+ $('.star').removeClass('active');
54
+ });
55
+
56
+ // Function for the star rating system
57
+ window.gfg = function (rating) {
58
+ $('.star').removeClass('active');
59
+ $('.star').each(function (index) {
60
+ if (index < rating) {
61
+ $(this).addClass('active');
62
+ }
63
+ });
64
+ };
65
+
66
+ $('.star').hover(
67
+ function () {
68
+ const rating = $(this).data('rating');
69
+ $('.star').removeClass('hover-active');
70
+ $('.star').each(function (index) {
71
+ if ($(this).data('rating') <= rating) {
72
+ $(this).addClass('hover-active');
73
+ }
74
+ });
75
+ },
76
+ function () {
77
+ $('.star').removeClass('hover-active');
78
+ });
79
+
80
+ });
@@ -0,0 +1,85 @@
1
+ $(document).ready(function () {
2
+ const paperclipButton = $('#paperclip-button');
3
+ const viewFilesButtonContainer = $('#view-files-button-container');
4
+ const viewFilesButton = $('#view-files-button');
5
+ const uploadedFilesModalElement = $('#uploadedFilesModal');
6
+ const uploadedFilesModal = uploadedFilesModalElement; // En Bootstrap 3, el elemento jQuery es el modal
7
+ const uploadedFilesList = $('#uploaded-files-list');
8
+
9
+ // Initialize FilePond
10
+ window.filePond = FilePond.create(
11
+ document.querySelector('#file-upload'), {
12
+ allowMultiple: true,
13
+ labelIdle: '',
14
+ credits: false,
15
+ allowFileSizeValidation: true,
16
+ maxFileSize: '10MB',
17
+ stylePanelLayout: null,
18
+ itemInsertLocation: 'after',
19
+ instantUpload: false,
20
+ });
21
+
22
+ $('.filepond--root').hide(); // Ocultar la UI de FilePond
23
+
24
+ // Función para actualizar la visibilidad del icono "ver archivos"
25
+ function updateFileIconsVisibility() {
26
+ const files = filePond.getFiles();
27
+ if (files.length > 0) {
28
+ viewFilesButtonContainer.show();
29
+ } else {
30
+ viewFilesButtonContainer.hide();
31
+ if (uploadedFilesModalElement.hasClass('in')) { // Si el modal está abierto y no hay archivos, ciérralo
32
+ uploadedFilesModal.modal('hide');
33
+ }
34
+ }
35
+ }
36
+
37
+ // Función para poblar el modal con los archivos y botones de eliminar
38
+ function populateFilesModal() {
39
+ uploadedFilesList.empty(); // Limpiar lista anterior
40
+ const files = filePond.getFiles();
41
+
42
+ if (files.length === 0) {
43
+ uploadedFilesList.append('<li class="list-group-item">No hay archivos adjuntos.</li>');
44
+ return;
45
+ }
46
+
47
+ files.forEach(file => {
48
+ const listItem = $(`
49
+ <li class="list-group-item d-flex justify-content-between align-items-center">
50
+ <span class="file-name-modal">${file.filename}</span>
51
+ <button type="button" class="btn btn-sm btn-outline-danger remove-file-btn" data-file-id="${file.id}" title="Eliminar archivo">
52
+ <i class="bi bi-trash-fill"></i>
53
+ </button>
54
+ </li>
55
+ `);
56
+ uploadedFilesList.append(listItem);
57
+ });
58
+ }
59
+
60
+ // Event listeners de FilePond
61
+ window.filePond.on('addfile', () => updateFileIconsVisibility());
62
+ window.filePond.on('removefile', () => {
63
+ updateFileIconsVisibility();
64
+ if (uploadedFilesModalElement.hasClass('in')) {
65
+ populateFilesModal();
66
+ }
67
+ });
68
+
69
+ // Event listeners de los botones de la UI
70
+ paperclipButton.on('click', () => window.filePond.browse());
71
+ viewFilesButton.on('click', () => {
72
+ populateFilesModal();
73
+ uploadedFilesModal.modal('show');
74
+ });
75
+ uploadedFilesList.on('click', '.remove-file-btn', function () {
76
+ const fileIdToRemove = $(this).data('file-id');
77
+ if (fileIdToRemove) {
78
+ window.filePond.removeFile(fileIdToRemove);
79
+ }
80
+ });
81
+
82
+ // Inicializar visibilidad al cargar
83
+ updateFileIconsVisibility();
84
+ });
85
+
@@ -0,0 +1,124 @@
1
+ $(document).ready(function () {
2
+
3
+ let helpContent = null; // Variable para cachear el contenido de ayuda
4
+
5
+ // Evento de clic en el botón de ayuda
6
+ $('#open-help-button').on('click', async function () {
7
+ const helpModal = new bootstrap.Modal(document.getElementById('helpModal'));
8
+ const accordionContainer = $('#help-accordion-container');
9
+ const spinner = $('#help-spinner');
10
+
11
+ // Si el contenido no se ha cargado, hacer la llamada a la API
12
+ if (helpContent) {
13
+ // Si el contenido ya está cacheado, solo muestra el modal
14
+ helpModal.show();
15
+ return;
16
+ }
17
+
18
+ spinner.show();
19
+ accordionContainer.hide();
20
+ helpModal.show();
21
+
22
+ try {
23
+ const helpContent = await callToolkit('/api/help-content', {}, "POST");
24
+
25
+ if (!helpContent) {
26
+ toastr.error('No se pudo cargar la guía de uso. Por favor, intente más tarde.');
27
+ spinner.hide();
28
+ helpModal.hide();
29
+ return;
30
+ }
31
+
32
+ // Construir el HTML del acordeón y mostrarlo
33
+ buildHelpAccordion(helpContent);
34
+ spinner.hide();
35
+ accordionContainer.show();
36
+
37
+ } catch (error) {
38
+ console.error("Error al cargar el contenido de ayuda:", error);
39
+ toastr.error('Ocurrió un error de red al cargar la guía.');
40
+ spinner.hide();
41
+ helpModal.hide();
42
+ }
43
+ });
44
+
45
+ /**
46
+ * Construye dinámicamente el HTML para el acordeón de ayuda a partir de los datos.
47
+ * @param {object} data El objeto JSON con el contenido de ayuda.
48
+ */
49
+ function buildHelpAccordion(data) {
50
+ const container = $('#help-accordion-container');
51
+ container.empty(); // Limpiar cualquier contenido previo
52
+
53
+ let accordionHtml = '';
54
+
55
+ if (data.example_questions) {
56
+ let contentHtml = '';
57
+ data.example_questions.forEach(cat => {
58
+ contentHtml += `<h6 class="fw-bold">${cat.category}</h6><ul>`;
59
+ cat.questions.forEach(q => contentHtml += `<li>${q}</li>`);
60
+ contentHtml += `</ul>`;
61
+ });
62
+ accordionHtml += createAccordionItem('examples', 'Preguntas de Ejemplo', contentHtml, true);
63
+ }
64
+
65
+ if (data.data_sources) {
66
+ let contentHtml = '<dl>';
67
+ data.data_sources.forEach(p => {
68
+ contentHtml += `<dt>${p.source}</dt><dd>${p.description}</dd>`;
69
+ });
70
+ contentHtml += `</dl>`;
71
+ accordionHtml += createAccordionItem('sources', 'Datos disponibles', contentHtml );
72
+ }
73
+
74
+ if (data.best_practices) {
75
+ let contentHtml = '<dl>';
76
+ data.best_practices.forEach(p => {
77
+ contentHtml += `<dt>${p.title}</dt><dd>${p.description}`;
78
+ if (p.example) {
79
+ contentHtml += `<br><small class="text-muted"><em>Ej: "${p.example}"</em></small>`;
80
+ }
81
+ contentHtml += `</dd>`;
82
+ });
83
+ contentHtml += `</dl>`;
84
+ accordionHtml += createAccordionItem('practices', 'Mejores Prácticas', contentHtml);
85
+ }
86
+
87
+ if (data.capabilities) {
88
+ let contentHtml = `<div class="row">`;
89
+ contentHtml += `<div class="col-md-6"><h6 class="fw-bold">Puede hacer:</h6><ul>${data.capabilities.can_do.map(item => `<li>${item}</li>`).join('')}</ul></div>`;
90
+ contentHtml += `<div class="col-md-6"><h6 class="fw-bold">No puede hacer:</h6><ul>${data.capabilities.cannot_do.map(item => `<li>${item}</li>`).join('')}</ul></div>`;
91
+ contentHtml += `</div>`;
92
+ accordionHtml += createAccordionItem('capabilities', 'Capacidades y Límites', contentHtml);
93
+ }
94
+
95
+ container.html(accordionHtml);
96
+ }
97
+
98
+ /**
99
+ * Helper para crear un item del acordeón de Bootstrap.
100
+ * @param {string} id El ID base para los elementos.
101
+ * @param {string} title El título que se muestra en el botón del acordeón.
102
+ * @param {string} contentHtml El HTML que va dentro del cuerpo colapsable.
103
+ * @param {boolean} isOpen Si el item debe estar abierto por defecto.
104
+ * @returns {string} El string HTML del item del acordeón.
105
+ */
106
+ function createAccordionItem(id, title, contentHtml, isOpen = false) {
107
+ const showClass = isOpen ? 'show' : '';
108
+ const collapsedClass = isOpen ? '' : 'collapsed';
109
+
110
+ return `
111
+ <div class="accordion-item">
112
+ <h2 class="accordion-header" id="heading-${id}">
113
+ <button class="accordion-button ${collapsedClass}" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-${id}" aria-expanded="${isOpen}" aria-controls="collapse-${id}">
114
+ ${title}
115
+ </button>
116
+ </h2>
117
+ <div id="collapse-${id}" class="accordion-collapse collapse ${showClass}" aria-labelledby="heading-${id}" data-bs-parent="#help-accordion-container">
118
+ <div class="accordion-body">
119
+ ${contentHtml}
120
+ </div>
121
+ </div>
122
+ </div>`;
123
+ }
124
+ });
@@ -0,0 +1,112 @@
1
+ $(document).ready(function () {
2
+ // Evento para abrir el modal de historial
3
+ const historyModal = $('#historyModal');
4
+
5
+ $('#history-button').on('click', function() {
6
+ historyModal.modal('show');
7
+ loadHistory();
8
+ });
9
+
10
+
11
+ // Función para cargar el historial
12
+ async function loadHistory() {
13
+ const historyLoading = $('#history-loading');
14
+ const historyContent = $('#history-content');
15
+ const historyTable = historyContent.find('table');
16
+ const noHistoryMessage = $('#no-history-message');
17
+
18
+ // prepare UI for loading
19
+ historyLoading.show();
20
+ historyContent.hide();
21
+ historyTable.show();
22
+ noHistoryMessage.hide();
23
+
24
+ // cal the toolkit, handle the response and errors
25
+ const data = await callToolkit("/api/history", {}, "POST");
26
+
27
+ if (!data || !data.history) {
28
+ toastr.error(t_js('error_loading_history'));
29
+ historyModal.modal('hide');
30
+ return;
31
+ }
32
+
33
+ if (data.history.length === 0) {
34
+ historyTable.hide();
35
+ noHistoryMessage.show();
36
+ } else
37
+ displayAllHistory(data.history);
38
+
39
+ historyLoading.hide();
40
+ historyContent.show();
41
+ }
42
+
43
+ // Función para mostrar todo el historial
44
+ function displayAllHistory(historyData) {
45
+ const historyTableBody = $('#history-table-body');
46
+
47
+ historyTableBody.empty();
48
+
49
+ // Filtrar solo consultas que son strings simples
50
+ const filteredHistory = historyData.filter(item => {
51
+ try {
52
+ JSON.parse(item.query);
53
+ return false;
54
+ } catch (e) {
55
+ return true;
56
+ }
57
+ });
58
+
59
+ // Poblar la tabla
60
+ filteredHistory.forEach((item, index) => {
61
+ const icon = $('<i>').addClass('bi bi-pencil-fill');
62
+
63
+ const link = $('<a>')
64
+ .attr('href', 'javascript:void(0);')
65
+ .addClass('edit-pencil')
66
+ .attr('title', t_js('edit_query'))
67
+ .data('query', item.query)
68
+ .append(icon);
69
+
70
+ const row = $('<tr>').append(
71
+ $('<td>').addClass('text-nowrap').text(formatDate(item.created_at)),
72
+ $('<td>').text(item.query),
73
+ $('<td>').append(link),
74
+ );
75
+
76
+ historyTableBody.append(row);
77
+ });
78
+ }
79
+
80
+ function formatDate(dateString) {
81
+ const date = new Date(dateString);
82
+
83
+ const padTo2Digits = (num) => num.toString().padStart(2, '0');
84
+
85
+ const day = padTo2Digits(date.getDate());
86
+ const month = padTo2Digits(date.getMonth() + 1);
87
+ const year = date.getFullYear();
88
+ const hours = padTo2Digits(date.getHours());
89
+ const minutes = padTo2Digits(date.getMinutes());
90
+
91
+ return `${day}-${month} ${hours}:${minutes}`;
92
+ }
93
+
94
+ // event handler for the edit pencil icon
95
+ $('#history-table-body').on('click', '.edit-pencil', function() {
96
+ const queryText = $(this).data('query');
97
+
98
+ // copy the text to the chat input box
99
+ if (queryText) {
100
+ $('#question').val(queryText);
101
+ autoResizeTextarea($('#question')[0]);
102
+ $('#send-button').removeClass('disabled');
103
+
104
+ // Cerrar el modal
105
+ $('#historyModal').modal('hide');
106
+
107
+ // Hacer focus en el textarea
108
+ if (window.innerWidth > 768)
109
+ $('#question').focus();
110
+ }
111
+ });
112
+ });
@@ -0,0 +1,36 @@
1
+ document.addEventListener('DOMContentLoaded', function() {
2
+ const logoutButton = document.getElementById('logout-button');
3
+ if (!logoutButton) {
4
+ console.warn('El botón de logout con id "logout-button" no fue encontrado.');
5
+ return;
6
+ }
7
+
8
+ if (window.toastr) {
9
+ toastr.options = { "positionClass": "toast-bottom-right", "preventDuplicates": true };
10
+ }
11
+
12
+ logoutButton.addEventListener('click', async function(event) {
13
+ event.preventDefault();
14
+
15
+ try {
16
+ const apiPath = '/api/logout';
17
+ const data = await callToolkit(apiPath, null, 'GET');
18
+
19
+ // Procesar la respuesta
20
+ if (data && data.status === 'success' && data.url) {
21
+ window.top.location.href = data.url;
22
+ } else {
23
+ // Si algo falla, callToolkit usualmente muestra un error.
24
+ // Mostramos un toast como fallback.
25
+ if (window.toastr) {
26
+ toastr.error('No se pudo procesar el cierre de sesión. Por favor, intente de nuevo.');
27
+ }
28
+ }
29
+ } catch (error) {
30
+ console.error('Error durante el logout:', error);
31
+ if (window.toastr) {
32
+ toastr.error('Ocurrió un error de red al intentar cerrar sesión.');
33
+ }
34
+ }
35
+ });
36
+ });