Py.Cafe

Letshadow/

dash-dynamic-data

Dynamic Data Manager

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194

import dash  
from dash import Dash, html, Input, Output, State, callback, ALL, MATCH  
import dash_mantine_components as dmc  
from dash_iconify import DashIconify  
  
app = Dash(__name__)  
  
# Datos iniciales para tarjetas dinámicas  
initial_cards = [  
    {"id": 1, "title": "Ventas", "value": 1250, "icon": "tabler:chart-line"},  
    {"id": 2, "title": "Usuarios", "value": 89, "icon": "tabler:users"},  
    {"id": 3, "title": "Pedidos", "value": 34, "icon": "tabler:shopping-cart"}  
]  
  
app.layout = dmc.MantineProvider([  
    dmc.Container([  
        dmc.Title("Dashboard Dinámico", order=1, mb="lg"),  
          
        # Botones de control  
        dmc.Group([  
            dmc.Button("Agregar Tarjeta", id="add-card-btn", leftSection=DashIconify(icon="tabler:plus")),  
            dmc.Button("Actualizar Datos", id="refresh-btn", leftSection=DashIconify(icon="tabler:refresh")),  
        ], mb="xl"),  
          
        # Contenedor de tarjetas dinámicas  
        dmc.SimpleGrid(  
            id="cards-container",  
            cols=3,  
            children=[  
                dmc.Card([  
                    dmc.Group([  
                        DashIconify(  
                            icon=card["icon"],   
                            width=30,   
                            id={"type": "card-icon", "index": card["id"]}  
                        ),  
                        dmc.Stack([  
                            dmc.Text(card["title"], size="sm", c="dimmed"),  
                            dmc.Text(str(card["value"]), size="xl", fw=700, id={"type": "card-value", "index": card["id"]})  
                        ], gap="xs")  
                    ], justify="space-between"),  
                      
                    dmc.Button(  
                        "Eliminar",   
                        variant="light",   
                        color="red",   
                        size="xs",  
                        id={"type": "delete-btn", "index": card["id"]},  
                        mt="sm"  
                    )  
                ],   
                withBorder=True,   
                shadow="sm",   
                radius="md",  
                id={"type": "card", "index": card["id"]},  
                key=f"card-{card['id']}"  
                ) for card in initial_cards  
            ]  
        ),  
          
        # Modal para agregar nueva tarjeta  
        dmc.Modal(  
            title="Nueva Tarjeta",  
            id="add-modal",  
            children=[  
                dmc.Stack([  
                    dmc.TextInput(label="Título", id="new-title", placeholder="Ej: Ingresos"),  
                    dmc.NumberInput(label="Valor inicial", id="new-value", value=0),  
                    dmc.Select(  
                        label="Icono",  
                        id="new-icon",  
                        data=[  
                            {"value": "tabler:chart-bar", "label": "Gráfico de barras"},  
                            {"value": "tabler:currency-dollar", "label": "Dinero"},  
                            {"value": "tabler:trending-up", "label": "Tendencia"},  
                            {"value": "tabler:star", "label": "Estrella"}  
                        ]  
                    ),  
                    dmc.Group([  
                        dmc.Button("Cancelar", variant="outline", id="cancel-btn"),  
                        dmc.Button("Crear", id="create-btn")  
                    ], justify="flex-end")  
                ])  
            ]  
        )  
    ], size="lg")  
])  
  
# Callback para abrir modal  
@callback(  
    Output("add-modal", "opened"),  
    Input("add-card-btn", "n_clicks"),  
    Input("cancel-btn", "n_clicks"),  
    Input("create-btn", "n_clicks"),  
    prevent_initial_call=True  
)  
def toggle_modal(add_clicks, cancel_clicks, create_clicks):  
    ctx = dash.callback_context  
    if ctx.triggered_id == "add-card-btn":  
        return True  
    return False  
  
# Callback principal para manejar tarjetas dinámicas  
@callback(  
    Output("cards-container", "children"),  
    Input("create-btn", "n_clicks"),  
    Input({"type": "delete-btn", "index": ALL}, "n_clicks"),  
    Input("refresh-btn", "n_clicks"),  
    State("new-title", "value"),  
    State("new-value", "value"),  
    State("new-icon", "value"),  
    State("cards-container", "children"),  
    prevent_initial_call=True  
)  
def manage_cards(create_clicks, delete_clicks, refresh_clicks, title, value, icon, current_cards):  
    ctx = dash.callback_context  
      
    if not ctx.triggered:  
        return current_cards  
      
    trigger_id = ctx.triggered[0]["prop_id"]  
      
    # Crear nueva tarjeta  
    if "create-btn" in trigger_id and title and icon:  
        new_id = max([card["props"]["id"]["index"] for card in current_cards]) + 1  
          
        new_card = dmc.Card([  
            dmc.Group([  
                DashIconify(  
                    icon=icon,   
                    width=30,   
                    id={"type": "card-icon", "index": new_id}  
                ),  
                dmc.Stack([  
                    dmc.Text(title, size="sm", c="dimmed"),  
                    dmc.Text(str(value or 0), size="xl", fw=700, id={"type": "card-value", "index": new_id})  
                ], gap="xs")  
            ], justify="space-between"),  
              
            dmc.Button(  
                "Eliminar",   
                variant="light",   
                color="red",   
                size="xs",  
                id={"type": "delete-btn", "index": new_id},  
                mt="sm"  
            )  
        ],   
        withBorder=True,   
        shadow="sm",   
        radius="md",  
        id={"type": "card", "index": new_id},  
        key=f"card-{new_id}"  
        )  
          
        return current_cards + [new_card]  
      
    # Eliminar tarjeta  
    elif "delete-btn" in trigger_id:  
        clicked_index = eval(trigger_id.split('.')[0])["index"]  
        return [card for card in current_cards if card["props"]["id"]["index"] != clicked_index]  
      
    # Actualizar valores (simulado)  
    elif "refresh-btn" in trigger_id:  
        import random  
        updated_cards = []  
        for card in current_cards:  
            # Crear una copia de la tarjeta con valor actualizado  
            card_copy = card.copy()  
            card_id = card["props"]["id"]["index"]  
              
            # Buscar y actualizar el componente de valor  
            for child in card_copy["props"]["children"]:  
                if hasattr(child, "props") and "children" in child["props"]:  
                    for subchild in child["props"]["children"]:  
                        if (hasattr(subchild, "props") and   
                            "children" in subchild["props"] and   
                            isinstance(subchild["props"]["children"], list)):  
                            for item in subchild["props"]["children"]:  
                                if (hasattr(item, "props") and   
                                    "id" in item["props"] and   
                                    item["props"]["id"]["type"] == "card-value"):  
                                    # Actualizar el valor con uno aleatorio  
                                    item["props"]["children"] = str(random.randint(50, 2000))  
              
            updated_cards.append(card_copy)  
          
        return updated_cards  
      
    return current_cards  
  
if __name__ == "__main__":  
    app.run_server(debug=True)