import logging
from dash.dependencies import Input, Output, State
import dash_mantine_components as dmc
from dash import html
from flask_login import current_user
# Assuming 'app' is initialized elsewhere in your project
from server import app
# Assuming these are helper functions and constants
from utils import (
aux_replace_data_when_obfuscated,
create_group,
create_html_image,
get_df_from_db,
get_current_user_and_hospital,
layout_edit_form,
OBFUSCATION_BEHAVIOUR
)
# Initialize logger for this module
logger = logging.getLogger(__name__)
# --- Constants for better readability and maintainability ---
UNVALIDATED_VERSION_TEXT = 'Sin validar'
PRESENTACION_USERNAME_PART = 'presentacion'
# Columns to exclude from editing forms
EXCLUDED_EDIT_COLUMNS_COMMON = ['EDITAR', 'TEMPORALES', 'N_ORDEN', 'VERSION', 'ACTUALIZADO']
EXCLUDED_EDIT_COLUMNS_SENSITIVE = ['NHC', 'ID_ENF_PACIENTE', 'ID_ANA_PACIENTE']
ERROR_DIV_ID = 'edit-errors-div'
MODAL_TITLE_VALIDATION = "Se requiere validación del paciente con NHC = "
MODAL_TITLE_EDITING = "Modificando la entrada del paciente con NHC = "
TOOLTIP_VALIDATION_LABEL = 'Marcadas en rojo aquellas variables que requieren validación'
@app.callback(
Output('box-edit', 'children'),
Output('button-edit-save', 'disabled'),
Input('modal-edit', 'opened'),
Input({'type': 'agGrid-table', 'index': 'visualize'}, 'cellRendererData'),
State({'type': 'agGrid-table', 'index': 'visualize'}, 'rowData'),
State('switch-obfuscation', 'checked'),
State('dict-stored', 'data'),
State('screen-size-container', 'data'),
)
def create_modal_edit(
modal_edit_opened: bool,
cell_renderer_data: dict,
grid_row_data: list,
obfuscation_switch_checked: bool,
app_config_data: dict,
screen_size_data: dict
) -> tuple[dmc.Box | str, bool]:
"""
Creates and populates the edit/validation modal for a selected patient entry.
This callback is triggered when the 'modal-edit' is opened or when a cell
in the 'visualize' AgGrid table is rendered (indicating a row selection).
It determines whether the selected entry requires validation or is
available for direct editing, applies data obfuscation if needed,
and dynamically generates the appropriate form using `layout_edit_form`.
Args:
modal_edit_opened (bool): True if the edit modal is currently open.
cell_renderer_data (dict): Data from the clicked cell in the AgGrid table,
expected to contain 'rowId'.
grid_row_data (list): The complete list of row data currently displayed
in the AgGrid table.
obfuscation_switch_checked (bool): State of the obfuscation toggle switch.
app_config_data (dict): Application-wide configuration data, including
column definitions and created columns.
screen_size_data (dict): Data related to the screen size, used for UI layout.
Returns:
tuple[dmc.Box | str, bool]:
- A dmc.Box component containing the edit/validation form if a row
is selected and the modal is open. An empty string otherwise.
- A boolean indicating whether the 'button-edit-save' should be disabled.
(False if a form is displayed, True otherwise).
"""
logger.info(f"create_modal_edit callback triggered. Modal opened: {modal_edit_opened}")
if not modal_edit_opened:
logger.debug("Modal not open, returning empty children and disabling save button.")
return '', True # Return nothing and disable save button
# If the modal is open but no row is selected yet (or data is invalid)
if not cell_renderer_data:
logger.warning("Modal opened but no cell renderer data provided. Returning empty children.")
return '', True
try:
# Retrieve current user and hospital identifiers
current_username, current_hospital = get_current_user_and_hospital(current_user)
logger.debug(f"Current user: {current_username}, hospital: {current_hospital}")
# Get selected row based on rowId from cellRendererData
row_index = int(cell_renderer_data['rowId'])
selected_row_data = grid_row_data[row_index]
logger.info(f"Processing row with NHC: {selected_row_data.get('NHC', 'N/A')} at index {row_index}")
# Check for obfuscation status
obfuscation_active = (
OBFUSCATION_BEHAVIOUR or
PRESENTACION_USERNAME_PART in current_user.username or
obfuscation_switch_checked
)
if obfuscation_active:
logger.debug("Obfuscation is active. Replacing data for selected row.")
selected_row_data = aux_replace_data_when_obfuscated(
selected_row_data, app_config_data, current_hospital, current_username
)
# Determine columns to be copied/displayed in the form
all_app_columns = set(app_config_data.get('columns', []))
created_columns = set(app_config_data.get('created_columns', []))
excluded_cols = (
set(EXCLUDED_EDIT_COLUMNS_COMMON)
.union(EXCLUDED_EDIT_COLUMNS_SENSITIVE)
.union(created_columns)
)
display_columns = [col for col in all_app_columns if col not in excluded_cols]
logger.debug(f"Columns to display: {len(display_columns)} after excluding {len(excluded_cols)}.")
is_validation_required = selected_row_data.get('VERSION') == UNVALIDATED_VERSION_TEXT
# Initialize variables for dynamic content
form_clinical_data = selected_row_data
validation_arg = False
center_content = None
modal_title_nhc_text = str(selected_row_data.get('NHC', ''))
if is_validation_required:
logger.info(f"Patient NHC {modal_title_nhc_text} requires validation.")
# Attempt to fetch the real data using the de-obfuscated NHC value
# Note: This fetches a DataFrame, whereas 'selected_row_data' is a dict.
# `layout_edit_form` must handle both.
real_data = get_df_from_db(
current_hospital,
current_username,
app_config_data,
filter=True,
values={'NHC': selected_row_data.get('NHC')}, # Use get for safety
select_all=True
)
form_clinical_data = real_data
validation_arg = True
center_content = create_group(
component=[
html.A(
children=[
html.Span('Se requiere validación ', style={'color': 'red'}),
'del paciente con ',
html.B(f'NHC = {modal_title_nhc_text}'),
]
),
dmc.Tooltip(
create_html_image('ph--question.svg'),
label=TOOLTIP_VALIDATION_LABEL,
withArrow=True,
position='right',
transitionProps={
'transition': 'fade',
'duration': 200,
'timingFunction': 'ease'
},
)
]
)
else:
logger.info(f"Patient NHC {modal_title_nhc_text} is available for editing.")
center_content = html.A(
children=[
'Modificando la entrada del paciente con ',
html.B(f'NHC = {modal_title_nhc_text}')
]
)
# Generate the edit/validation table form
edit_form_table = layout_edit_form(
clinical_data=form_clinical_data,
dict_types=app_config_data,
columns_df=display_columns,
current_hospital=current_hospital,
current_username=current_username,
screen_size_data=screen_size_data,
validation=validation_arg, # Pass validation state
)
# Construct the common modal structure
return dmc.Box(
children=[
dmc.Divider(variant='solid'),
dmc.Space(h=20),
dmc.Center(center_content),
dmc.Space(h=20),
edit_form_table,
dmc.Box(
id=ERROR_DIV_ID,
children='',
style={'text-align': 'center', 'color': 'red'}
),
dmc.Space(h=20),
dmc.Divider(variant='solid'),
dmc.Space(h=20)
]
), False # Enable the save button
except IndexError:
logger.error(f"Invalid rowId '{cell_renderer_data.get('rowId')}' for grid_row_data of length {len(grid_row_data)}.", exc_info=True)
return dmc.Box(children=[html.Div("Error: Selected row not found.", style={'color': 'red'})]), True
except KeyError as e:
logger.error(f"Missing expected key in data: {e}", exc_info=True)
return dmc.Box(children=[html.Div(f"Error: Required data missing ({e}).", style={'color': 'red'})]), True
except Exception as e:
logger.critical(f"An unexpected error occurred in create_modal_edit: {e}", exc_info=True)
return dmc.Box(children=[html.Div("An unexpected error occurred. Please try again or contact support.", style={'color': 'red'})]), True