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
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
import os
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.utils import PlotlyJSONEncoder
import json
from flask import Flask, render_template, request, redirect, url_for, session, flash, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
from functools import wraps
from datetime import datetime
from typing import Dict, List, Any, Optional, Callable

class DashboardConfig:
    """Configuration class for the dashboard"""
    def __init__(self):
        self.SECRET_KEY = os.environ.get('SECRET_KEY', 'your-secret-key-change-this')
        self.USERNAME = os.environ.get('DASHBOARD_USER', 'admin')
        self.PASSWORD = os.environ.get('DASHBOARD_PASS', 'admin123')
        self.DEBUG = os.environ.get('FLASK_DEBUG', 'True').lower() == 'true'

class DataProcessor:
    """Handle data processing and filtering operations"""
    
    def __init__(self):
        self.dataframes = {}
        self.filters = {}
        
    def register_dataframe(self, name: str, df: pd.DataFrame):
        """Register a dataframe for use in the dashboard"""
        self.dataframes[name] = df.copy()
        
    def get_dataframe(self, name: str, filters: Dict = None) -> pd.DataFrame:
        """Get a filtered dataframe"""
        if name not in self.dataframes:
            raise ValueError(f"Dataframe '{name}' not found")
            
        df = self.dataframes[name].copy()
        
        if filters:
            for column, filter_value in filters.items():
                if column in df.columns:
                    if isinstance(filter_value, list):
                        df = df[df[column].isin(filter_value)]
                    elif isinstance(filter_value, dict):
                        if 'min' in filter_value and 'max' in filter_value:
                            df = df[(df[column] >= filter_value['min']) & 
                                   (df[column] <= filter_value['max'])]
                    else:
                        df = df[df[column] == filter_value]
        
        return df
    
    def get_column_values(self, df_name: str, column: str) -> List:
        """Get unique values for a column"""
        if df_name in self.dataframes:
            return sorted(self.dataframes[df_name][column].dropna().unique().tolist())
        return []

class ChartBuilder:
    """Build different types of charts using Plotly"""
    
    @staticmethod
    def line_chart(df: pd.DataFrame, x: str, y: str, title: str = "", **kwargs):
        """Create a line chart"""
        fig = px.line(df, x=x, y=y, title=title, **kwargs)
        fig.update_layout(template='plotly_white')
        return json.dumps(fig, cls=PlotlyJSONEncoder)
    
    @staticmethod
    def bar_chart(df: pd.DataFrame, x: str, y: str, title: str = "", **kwargs):
        """Create a bar chart"""
        fig = px.bar(df, x=x, y=y, title=title, **kwargs)
        fig.update_layout(template='plotly_white')
        return json.dumps(fig, cls=PlotlyJSONEncoder)
    
    @staticmethod
    def scatter_plot(df: pd.DataFrame, x: str, y: str, title: str = "", **kwargs):
        """Create a scatter plot"""
        fig = px.scatter(df, x=x, y=y, title=title, **kwargs)
        fig.update_layout(template='plotly_white')
        return json.dumps(fig, cls=PlotlyJSONEncoder)
    
    @staticmethod
    def histogram(df: pd.DataFrame, x: str, title: str = "", **kwargs):
        """Create a histogram"""
        fig = px.histogram(df, x=x, title=title, **kwargs)
        fig.update_layout(template='plotly_white')
        return json.dumps(fig, cls=PlotlyJSONEncoder)
    
    @staticmethod
    def pie_chart(df: pd.DataFrame, names: str, values: str, title: str = "", **kwargs):
        """Create a pie chart"""
        fig = px.pie(df, names=names, values=values, title=title, **kwargs)
        fig.update_layout(template='plotly_white')
        return json.dumps(fig, cls=PlotlyJSONEncoder)
    
    @staticmethod
    def box_plot(df: pd.DataFrame, x: str, y: str, title: str = "", **kwargs):
        """Create a box plot"""
        fig = px.box(df, x=x, y=y, title=title, **kwargs)
        fig.update_layout(template='plotly_white')
        return json.dumps(fig, cls=PlotlyJSONEncoder)

class FilterWidget:
    """Create filter widgets for the dashboard"""
    
    def __init__(self, name: str, widget_type: str, **kwargs):
        self.name = name
        self.widget_type = widget_type
        self.kwargs = kwargs

class DashboardApp:
    """Main dashboard application class"""
    
    def __init__(self, config: DashboardConfig = None):
        self.app = Flask(__name__)
        self.config = config or DashboardConfig()
        self.data_processor = DataProcessor()
        self.chart_builder = ChartBuilder()
        
        # Configure Flask app
        self.app.config['SECRET_KEY'] = self.config.SECRET_KEY
        
        # Store dashboard configuration
        self.dashboard_title = "Dashboard"
        self.dashboard_description = ""
        self.widgets = []
        self.charts = []
        self.filters = []
        
        # Setup routes
        self._setup_routes()
        
    def _setup_routes(self):
        """Setup Flask routes"""
        
        @self.app.route('/login', methods=['GET', 'POST'])
        def login():
            if request.method == 'POST':
                username = request.form['username']
                password = request.form['password']
                
                if (username == self.config.USERNAME and 
                    password == self.config.PASSWORD):
                    session['logged_in'] = True
                    return redirect(url_for('dashboard'))
                else:
                    flash('Invalid credentials')
            
            return render_template('login.html')
        
        @self.app.route('/logout')
        def logout():
            session.pop('logged_in', None)
            return redirect(url_for('login'))
        
        @self.app.route('/')
        @self._login_required
        def dashboard():
            return render_template('dashboard.html',
                                 title=self.dashboard_title,
                                 description=self.dashboard_description,
                                 filters=self.filters,
                                 charts=self._generate_charts())
        
        @self.app.route('/api/update_charts', methods=['POST'])
        @self._login_required
        def update_charts():
            filters = request.json.get('filters', {})
            charts = self._generate_charts(filters)
            return jsonify({'charts': charts})
        
        @self.app.route('/api/filter_options/<df_name>/<column>')
        @self._login_required
        def get_filter_options(df_name, column):
            options = self.data_processor.get_column_values(df_name, column)
            return jsonify(options)
    
    def _login_required(self, f):
        """Decorator for login required routes"""
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if not session.get('logged_in'):
                return redirect(url_for('login'))
            return f(*args, **kwargs)
        return decorated_function
    
    def configure(self, title: str = "Dashboard", description: str = ""):
        """Configure dashboard settings"""
        self.dashboard_title = title
        self.dashboard_description = description
    
    def add_dataframe(self, name: str, df: pd.DataFrame):
        """Add a dataframe to the dashboard"""
        self.data_processor.register_dataframe(name, df)
    
    def add_filter(self, name: str, df_name: str, column: str, filter_type: str = "multiselect", **kwargs):
        """Add a filter widget"""
        filter_widget = {
            'name': name,
            'df_name': df_name,
            'column': column,
            'type': filter_type,
            'options': self.data_processor.get_column_values(df_name, column),
            **kwargs
        }
        self.filters.append(filter_widget)
    
    def add_chart(self, chart_type: str, df_name: str, title: str = "", **chart_params):
        """Add a chart to the dashboard"""
        chart_config = {
            'type': chart_type,
            'df_name': df_name,
            'title': title,
            'params': chart_params
        }
        self.charts.append(chart_config)
    
    def _generate_charts(self, filters: Dict = None):
        """Generate all charts with applied filters"""
        generated_charts = []
        
        for chart_config in self.charts:
            try:
                df = self.data_processor.get_dataframe(chart_config['df_name'], filters)
                
                chart_method = getattr(self.chart_builder, chart_config['type'])
                chart_json = chart_method(df, title=chart_config['title'], **chart_config['params'])
                
                generated_charts.append({
                    'id': f"chart_{len(generated_charts)}",
                    'title': chart_config['title'],
                    'json': chart_json
                })
            except Exception as e:
                print(f"Error generating chart: {e}")
                continue
                
        return generated_charts
    
    def run(self, host: str = '0.0.0.0', port: int = 5000, debug: bool = None):
        """Run the dashboard application"""
        debug = debug if debug is not None else self.config.DEBUG
        
        # Create templates if they don't exist
        self._create_templates()
        
        self.app.run(host=host, port=port, debug=debug)
    
    def _create_templates(self):
        """Create HTML templates"""
        os.makedirs('templates', exist_ok=True)
        
        # Login template
        login_template = '''<!DOCTYPE html>
<html>
<head>
    <title>Dashboard Login</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background: #f5f5f5; }
        .login-container { max-width: 400px; margin: 100px auto; background: white; padding: 40px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        h2 { text-align: center; margin-bottom: 30px; color: #333; }
        .form-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 5px; color: #666; }
        input[type="text"], input[type="password"] { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
        button { width: 100%; padding: 12px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; }
        button:hover { background: #0056b3; }
        .flash-message { color: red; text-align: center; margin-bottom: 20px; }
    </style>
</head>
<body>
    <div class="login-container">
        <h2>Dashboard Login</h2>
        {% with messages = get_flashed_messages() %}
            {% if messages %}
                {% for message in messages %}
                    <div class="flash-message">{{ message }}</div>
                {% endfor %}
            {% endif %}
        {% endwith %}
        <form method="post">
            <div class="form-group">
                <label for="username">Username:</label>
                <input type="text" id="username" name="username" required>
            </div>
            <div class="form-group">
                <label for="password">Password:</label>
                <input type="password" id="password" name="password" required>
            </div>
            <button type="submit">Login</button>
        </form>
    </div>
</body>
</html>'''
        
        # Dashboard template
        dashboard_template = '''<!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <style>
        body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background: #f5f5f5; }
        .header { background: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .header h1 { margin: 0; color: #333; }
        .header p { margin: 10px 0 0 0; color: #666; }
        .logout { float: right; }
        .logout a { color: #dc3545; text-decoration: none; }
        .filters { background: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .filter-row { display: flex; gap: 20px; flex-wrap: wrap; align-items: end; }
        .filter-group { flex: 1; min-width: 200px; }
        .filter-group label { display: block; margin-bottom: 5px; color: #666; font-weight: bold; }
        .filter-group select { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
        .charts { display: grid; grid-template-columns: repeat(auto-fit, minmax(500px, 1fr)); gap: 20px; }
        .chart-container { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .chart-title { margin-bottom: 15px; color: #333; font-size: 18px; font-weight: bold; }
        button { padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background: #0056b3; }
    </style>
</head>
<body>
    <div class="header">
        <div class="logout">
            <a href="{{ url_for('logout') }}">Logout</a>
        </div>
        <h1>{{ title }}</h1>
        {% if description %}
            <p>{{ description }}</p>
        {% endif %}
    </div>

    {% if filters %}
    <div class="filters">
        <div class="filter-row">
            {% for filter in filters %}
            <div class="filter-group">
                <label for="filter_{{ loop.index0 }}">{{ filter.name }}:</label>
                <select id="filter_{{ loop.index0 }}" data-df="{{ filter.df_name }}" data-column="{{ filter.column }}" multiple>
                    {% for option in filter.options %}
                    <option value="{{ option }}">{{ option }}</option>
                    {% endfor %}
                </select>
            </div>
            {% endfor %}
            <div class="filter-group">
                <button onclick="updateCharts()">Update Charts</button>
            </div>
        </div>
    </div>
    {% endif %}

    <div id="charts-container" class="charts">
        {% for chart in charts %}
        <div class="chart-container">
            {% if chart.title %}
            <div class="chart-title">{{ chart.title }}</div>
            {% endif %}
            <div id="{{ chart.id }}"></div>
        </div>
        {% endfor %}
    </div>

    <script>
        // Render initial charts
        {% for chart in charts %}
        Plotly.newPlot('{{ chart.id }}', {{ chart.json|safe }}.data, {{ chart.json|safe }}.layout);
        {% endfor %}

        function updateCharts() {
            const filters = {};
            
            // Collect filter values
            {% for filter in filters %}
            const filter{{ loop.index0 }} = document.getElementById('filter_{{ loop.index0 }}');
            const selectedValues{{ loop.index0 }} = Array.from(filter{{ loop.index0 }}.selectedOptions).map(option => option.value);
            if (selectedValues{{ loop.index0 }}.length > 0) {
                if (!filters['{{ filter.df_name }}']) filters['{{ filter.df_name }}'] = {};
                filters['{{ filter.df_name }}']['{{ filter.column }}'] = selectedValues{{ loop.index0 }};
            }
            {% endfor %}

            // Send AJAX request to update charts
            fetch('/api/update_charts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({filters: filters})
            })
            .then(response => response.json())
            .then(data => {
                // Update each chart
                data.charts.forEach((chart, index) => {
                    const chartData = JSON.parse(chart.json);
                    Plotly.newPlot(chart.id, chartData.data, chartData.layout);
                });
            })
            .catch(error => console.error('Error updating charts:', error));
        }
    </script>
</body>
</html>'''
        
        with open('templates/login.html', 'w') as f:
            f.write(login_template)
            
        with open('templates/dashboard.html', 'w') as f:
            f.write(dashboard_template)

# Example usage
if __name__ == "__main__":
    # Create sample data
    import numpy as np
    
    # Sample sales data
    dates = pd.date_range('2023-01-01', periods=365, freq='D')
    sales_data = pd.DataFrame({
        'date': dates,
        'sales': np.random.normal(1000, 200, 365) + np.sin(np.arange(365) * 2 * np.pi / 365) * 300,
        'region': np.random.choice(['North', 'South', 'East', 'West'], 365),
        'product': np.random.choice(['Product A', 'Product B', 'Product C'], 365),
        'profit': np.random.normal(150, 50, 365)
    })
    
    # Sample customer data
    customer_data = pd.DataFrame({
        'customer_id': range(1, 1001),
        'age': np.random.normal(35, 12, 1000),
        'segment': np.random.choice(['Premium', 'Standard', 'Basic'], 1000),
        'lifetime_value': np.random.exponential(500, 1000)
    })
    
    # Create dashboard
    dashboard = DashboardApp()
    
    # Configure dashboard
    dashboard.configure(
        title="Sales Analytics Dashboard",
        description="Monitor sales performance and customer metrics"
    )
    
    # Add dataframes
    dashboard.add_dataframe('sales', sales_data)
    dashboard.add_dataframe('customers', customer_data)
    
    # Add filters
    dashboard.add_filter('Region', 'sales', 'region', 'multiselect')
    dashboard.add_filter('Product', 'sales', 'product', 'multiselect')
    dashboard.add_filter('Customer Segment', 'customers', 'segment', 'multiselect')
    
    # Add charts
    dashboard.add_chart('line_chart', 'sales', 'Daily Sales Trend', x='date', y='sales')
    dashboard.add_chart('bar_chart', 'sales', 'Sales by Region', 
                       x='region', y='sales', color='region')
    dashboard.add_chart('scatter_plot', 'sales', 'Sales vs Profit', 
                       x='sales', y='profit', color='product')
    dashboard.add_chart('histogram', 'customers', 'Customer Age Distribution', x='age')
    dashboard.add_chart('pie_chart', 'customers', 'Customer Segments', 
                       names='segment', values='lifetime_value')
    dashboard.add_chart('box_plot', 'customers', 'Lifetime Value by Segment', 
                       x='segment', y='lifetime_value')
    
    # Run the dashboard
    print("Dashboard starting...")
    print("Default credentials - Username: admin, Password: admin123")
    print("Access the dashboard at: http://localhost:5000")
    dashboard.run(debug=True)