thedynasty23 commited on
Commit
f87bb65
Β·
verified Β·
1 Parent(s): 76a1251

Upload complete_app (1).py

Browse files
Files changed (1) hide show
  1. complete_app (1).py +1781 -0
complete_app (1).py ADDED
@@ -0,0 +1,1781 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🌍 Food Wastage Management System - Complete Edition
2
+ # Combining all functionality from both files with 15+ comprehensive SQL queries
3
+ # FIXED: Text visibility issues in dropdowns and navigation
4
+ # ADDED: Time series trend analysis
5
+
6
+ import streamlit as st
7
+ import pandas as pd
8
+ import plotly.express as px
9
+ import plotly.graph_objects as go
10
+ from datetime import datetime, timedelta
11
+ import os
12
+ import sqlite3
13
+ from sqlalchemy import create_engine, text
14
+
15
+ # Page Configuration
16
+ st.set_page_config(
17
+ page_title="🌍 Food Wastage Management System",
18
+ page_icon="🍽️",
19
+ layout="wide",
20
+ initial_sidebar_state="expanded"
21
+ )
22
+
23
+ # FIXED: Custom CSS for modern styling with proper text visibility
24
+ st.markdown("""
25
+ <style>
26
+ /* Sidebar styling - FIXED for visibility */
27
+ section[data-testid="stSidebar"] {
28
+ background-color: #f0f2f6;
29
+ }
30
+ section[data-testid="stSidebar"] * {
31
+ color: #0e1117 !important;
32
+ }
33
+ section[data-testid="stSidebar"] .stSelectbox > div[data-baseweb="select"] > div {
34
+ color: #0e1117 !important;
35
+ }
36
+
37
+ /* Main content styling */
38
+ .main-header {
39
+ background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
40
+ padding: 2rem;
41
+ border-radius: 10px;
42
+ margin-bottom: 2rem;
43
+ text-align: center;
44
+ color: white;
45
+ }
46
+
47
+ .metric-card {
48
+ background: white;
49
+ padding: 1rem;
50
+ border-radius: 8px;
51
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
52
+ margin: 0.5rem 0;
53
+ }
54
+
55
+ .stMetric {
56
+ background: white;
57
+ padding: 1rem;
58
+ border-radius: 8px;
59
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
60
+ }
61
+
62
+ /* Chart styling */
63
+ .js-plotly-plot {
64
+ border-radius: 8px;
65
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
66
+ }
67
+ </style>
68
+ """, unsafe_allow_html=True)
69
+
70
+ # ========== DATABASE SETUP ==========
71
+ @st.cache_resource
72
+ def init_database():
73
+ """Initialize SQLite database and create tables"""
74
+ engine = create_engine('sqlite:///food_wastage.db', echo=False)
75
+ return engine
76
+
77
+ engine = init_database()
78
+
79
+ # ========== DATA LOADING WITH COLUMN MAPPING ==========
80
+ @st.cache_data
81
+ def load_all_data():
82
+ """Load CSV files with comprehensive column mapping"""
83
+ data = {}
84
+ loading_status = {}
85
+
86
+ # Providers Data Loading
87
+ try:
88
+ providers_df = pd.read_csv('providers_data.csv')
89
+ # Column mapping
90
+ provider_column_mapping = {
91
+ 'Provider_ID': 'provider_id', 'ID': 'provider_id',
92
+ 'Name': 'name', 'Provider_Name': 'name',
93
+ 'Type': 'type', 'Provider_Type': 'type',
94
+ 'Address': 'address', 'City': 'city', 'Location': 'city',
95
+ 'Contact': 'contact', 'Phone': 'contact', 'Email': 'contact'
96
+ }
97
+
98
+ for old_col, new_col in provider_column_mapping.items():
99
+ if old_col in providers_df.columns:
100
+ providers_df = providers_df.rename(columns={old_col: new_col})
101
+
102
+ # Ensure required columns
103
+ required_cols = ['provider_id', 'name', 'type', 'city', 'contact']
104
+ for col in required_cols:
105
+ if col not in providers_df.columns:
106
+ if col == 'provider_id':
107
+ providers_df['provider_id'] = range(1, len(providers_df) + 1)
108
+ else:
109
+ providers_df[col] = 'N/A'
110
+
111
+ data['providers'] = providers_df
112
+ loading_status['providers'] = f"βœ… Providers data loaded successfully"
113
+
114
+ except Exception as e:
115
+ data['providers'] = pd.DataFrame()
116
+ loading_status['providers'] = f"❌ Could not load providers: {str(e)}"
117
+
118
+ # Receivers Data Loading
119
+ try:
120
+ receivers_df = pd.read_csv('receivers_data.csv')
121
+ receiver_column_mapping = {
122
+ 'Receiver_ID': 'receiver_id', 'ID': 'receiver_id',
123
+ 'Name': 'name', 'Receiver_Name': 'name',
124
+ 'Type': 'type', 'Receiver_Type': 'type',
125
+ 'City': 'city', 'Location': 'city',
126
+ 'Contact': 'contact', 'Phone': 'contact', 'Email': 'contact'
127
+ }
128
+
129
+ for old_col, new_col in receiver_column_mapping.items():
130
+ if old_col in receivers_df.columns:
131
+ receivers_df = receivers_df.rename(columns={old_col: new_col})
132
+
133
+ required_cols = ['receiver_id', 'name', 'type', 'city', 'contact']
134
+ for col in required_cols:
135
+ if col not in receivers_df.columns:
136
+ if col == 'receiver_id':
137
+ receivers_df['receiver_id'] = range(1, len(receivers_df) + 1)
138
+ else:
139
+ receivers_df[col] = 'N/A'
140
+
141
+ data['receivers'] = receivers_df
142
+ loading_status['receivers'] = f"βœ… Receivers data loaded successfully"
143
+
144
+ except Exception as e:
145
+ data['receivers'] = pd.DataFrame()
146
+ loading_status['receivers'] = f"❌ Could not load receivers: {str(e)}"
147
+
148
+ # Food Listings Data Loading
149
+ try:
150
+ food_df = pd.read_csv('food_listings_data.csv')
151
+ food_column_mapping = {
152
+ 'Food_ID': 'food_id', 'ID': 'food_id',
153
+ 'Food_Name': 'food_name', 'Name': 'food_name',
154
+ 'Quantity': 'quantity', 'Amount': 'quantity',
155
+ 'Expiry_Date': 'expiry_date', 'Expiration': 'expiry_date',
156
+ 'Provider_ID': 'provider_id',
157
+ 'Food_Type': 'food_type', 'Type': 'food_type',
158
+ 'Meal_Type': 'meal_type', 'Meal': 'meal_type',
159
+ 'Location': 'location', 'City': 'location'
160
+ }
161
+
162
+ for old_col, new_col in food_column_mapping.items():
163
+ if old_col in food_df.columns:
164
+ food_df = food_df.rename(columns={old_col: new_col})
165
+
166
+ # Date conversion and urgency calculation
167
+ if 'expiry_date' in food_df.columns:
168
+ food_df['expiry_date'] = pd.to_datetime(food_df['expiry_date'], errors='coerce')
169
+ today = pd.Timestamp.now()
170
+ food_df['days_until_expiry'] = (food_df['expiry_date'] - today).dt.days
171
+ food_df['urgency'] = food_df['days_until_expiry'].apply(
172
+ lambda x: 'Critical' if x <= 1 else 'Urgent' if x <= 3 else 'Soon' if x <= 7 else 'Normal'
173
+ )
174
+
175
+ data['food_listings'] = food_df
176
+ loading_status['food_listings'] = f"βœ… Food listings loaded successfully"
177
+
178
+ except Exception as e:
179
+ data['food_listings'] = pd.DataFrame()
180
+ loading_status['food_listings'] = f"❌ Could not load food listings: {str(e)}"
181
+
182
+ # Claims Data Loading
183
+ try:
184
+ if os.path.exists('claims_data.csv'):
185
+ claims_df = pd.read_csv('claims_data.csv')
186
+ claims_column_mapping = {
187
+ 'Claim_ID': 'claim_id', 'ID': 'claim_id',
188
+ 'Food_ID': 'food_id', 'Receiver_ID': 'receiver_id',
189
+ 'Status': 'status', 'Timestamp': 'timestamp',
190
+ 'Date': 'timestamp', 'Created_At': 'timestamp'
191
+ }
192
+
193
+ for old_col, new_col in claims_column_mapping.items():
194
+ if old_col in claims_df.columns:
195
+ claims_df = claims_df.rename(columns={old_col: new_col})
196
+
197
+ if 'timestamp' in claims_df.columns:
198
+ claims_df['timestamp'] = pd.to_datetime(claims_df['timestamp'], errors='coerce')
199
+ else:
200
+ # Generate sample claims with realistic time series data
201
+ if not data['food_listings'].empty and not data['receivers'].empty:
202
+ sample_size = min(200, len(data['food_listings']))
203
+ # Create realistic timestamp distribution over the last 6 months
204
+ end_date = datetime.now()
205
+ start_date = end_date - timedelta(days=180)
206
+ timestamps = pd.date_range(start=start_date, end=end_date, periods=sample_size)
207
+
208
+ claims_df = pd.DataFrame({
209
+ 'claim_id': range(1, sample_size + 1),
210
+ 'food_id': data['food_listings']['food_id'].sample(sample_size, replace=True).values,
211
+ 'receiver_id': data['receivers']['receiver_id'].sample(sample_size, replace=True).values,
212
+ 'status': (['Completed'] * int(sample_size * 0.65) +
213
+ ['Pending'] * int(sample_size * 0.20) +
214
+ ['Cancelled'] * int(sample_size * 0.15))[:sample_size],
215
+ 'timestamp': timestamps
216
+ })
217
+ else:
218
+ claims_df = pd.DataFrame()
219
+
220
+ data['claims'] = claims_df
221
+ loading_status['claims'] = f"βœ… Claims data loaded successfully"
222
+
223
+ except Exception as e:
224
+ data['claims'] = pd.DataFrame()
225
+ loading_status['claims'] = f"❌ Could not load claims: {str(e)}"
226
+
227
+ return data, loading_status
228
+
229
+ # Load data and populate database
230
+ data, status = load_all_data()
231
+
232
+ def populate_database():
233
+ """Populate SQLite database with CSV data"""
234
+ try:
235
+ for table_name, df in data.items():
236
+ if not df.empty:
237
+ df.to_sql(table_name, engine, if_exists='replace', index=False)
238
+ except Exception as e:
239
+ st.error(f"Database population error: {e}")
240
+
241
+ populate_database()
242
+
243
+ # ========== CRUD OPERATIONS ==========
244
+ class CRUDOperations:
245
+ """CRUD operations for all entities"""
246
+
247
+ @staticmethod
248
+ def add_provider(name, provider_type, city, contact, address=""):
249
+ """Add new provider"""
250
+ try:
251
+ new_id = len(data['providers']) + 1
252
+ new_provider = pd.DataFrame({
253
+ 'provider_id': [new_id],
254
+ 'name': [name],
255
+ 'type': [provider_type],
256
+ 'city': [city],
257
+ 'contact': [contact],
258
+ 'address': [address]
259
+ })
260
+ new_provider.to_sql('providers', engine, if_exists='append', index=False)
261
+ st.cache_data.clear()
262
+ return True, "Provider added successfully!"
263
+ except Exception as e:
264
+ return False, f"Error adding provider: {e}"
265
+
266
+ @staticmethod
267
+ def add_receiver(name, receiver_type, city, contact):
268
+ """Add new receiver"""
269
+ try:
270
+ new_id = len(data['receivers']) + 1
271
+ new_receiver = pd.DataFrame({
272
+ 'receiver_id': [new_id],
273
+ 'name': [name],
274
+ 'type': [receiver_type],
275
+ 'city': [city],
276
+ 'contact': [contact]
277
+ })
278
+ new_receiver.to_sql('receivers', engine, if_exists='append', index=False)
279
+ st.cache_data.clear()
280
+ return True, "Receiver added successfully!"
281
+ except Exception as e:
282
+ return False, f"Error adding receiver: {e}"
283
+
284
+ @staticmethod
285
+ def add_food_listing(food_name, quantity, expiry_date, provider_id, food_type, meal_type):
286
+ """Add new food listing"""
287
+ try:
288
+ new_id = len(data['food_listings']) + 1
289
+ new_food = pd.DataFrame({
290
+ 'food_id': [new_id],
291
+ 'food_name': [food_name],
292
+ 'quantity': [quantity],
293
+ 'expiry_date': [expiry_date],
294
+ 'provider_id': [provider_id],
295
+ 'food_type': [food_type],
296
+ 'meal_type': [meal_type]
297
+ })
298
+ new_food.to_sql('food_listings', engine, if_exists='append', index=False)
299
+ st.cache_data.clear()
300
+ return True, "Food listing added successfully!"
301
+ except Exception as e:
302
+ return False, f"Error adding food listing: {e}"
303
+
304
+ @staticmethod
305
+ def add_claim(food_id, receiver_id, status="Pending"):
306
+ """Add new claim"""
307
+ try:
308
+ new_id = len(data['claims']) + 1
309
+ new_claim = pd.DataFrame({
310
+ 'claim_id': [new_id],
311
+ 'food_id': [food_id],
312
+ 'receiver_id': [receiver_id],
313
+ 'status': [status],
314
+ 'timestamp': [datetime.now()]
315
+ })
316
+ new_claim.to_sql('claims', engine, if_exists='append', index=False)
317
+ st.cache_data.clear()
318
+ return True, "Claim added successfully!"
319
+ except Exception as e:
320
+ return False, f"Error adding claim: {e}"
321
+
322
+ # ========== COMPLETE SQL QUERIES CLASS (ALL 15+ QUERIES) ==========
323
+ class SQLQueries:
324
+ """Complete SQL queries covering all project requirements and additional analysis"""
325
+
326
+ @staticmethod
327
+ def execute_query(query):
328
+ """Execute SQL query and return results"""
329
+ try:
330
+ with engine.connect() as conn:
331
+ result = pd.read_sql(query, conn)
332
+ return result
333
+ except Exception as e:
334
+ st.error(f"Query execution error: {e}")
335
+ return pd.DataFrame()
336
+
337
+ # ========== REQUESTED QUERIES 1-15 ==========
338
+ @staticmethod
339
+ def get_providers_receivers_per_city():
340
+ """1. How many food providers and receivers are there in each city?"""
341
+ query = """
342
+ SELECT
343
+ COALESCE(p.city, r.city) as city,
344
+ COUNT(DISTINCT p.provider_id) as total_providers,
345
+ COUNT(DISTINCT r.receiver_id) as total_receivers,
346
+ -- Provider type breakdown
347
+ COUNT(DISTINCT CASE WHEN p.type = 'Restaurant' THEN p.provider_id END) as restaurants,
348
+ COUNT(DISTINCT CASE WHEN p.type = 'Grocery Store' THEN p.provider_id END) as grocery_stores,
349
+ COUNT(DISTINCT CASE WHEN p.type = 'Hotel' THEN p.provider_id END) as hotels,
350
+ COUNT(DISTINCT CASE WHEN p.type = 'Supermarket' THEN p.provider_id END) as supermarkets,
351
+ -- Receiver type breakdown
352
+ COUNT(DISTINCT CASE WHEN r.type = 'NGO' THEN r.receiver_id END) as ngos,
353
+ COUNT(DISTINCT CASE WHEN r.type = 'Food Bank' THEN r.receiver_id END) as food_banks,
354
+ COUNT(DISTINCT CASE WHEN r.type = 'Shelter' THEN r.receiver_id END) as shelters,
355
+ COUNT(DISTINCT CASE WHEN r.type = 'Charity' THEN r.receiver_id END) as charities,
356
+ -- Total ecosystem strength
357
+ (COUNT(DISTINCT p.provider_id) + COUNT(DISTINCT r.receiver_id)) as total_ecosystem_strength
358
+ FROM providers p
359
+ LEFT JOIN receivers r ON p.city = r.city
360
+ GROUP BY COALESCE(p.city, r.city)
361
+ HAVING COUNT(DISTINCT p.provider_id) > 0 OR COUNT(DISTINCT r.receiver_id) > 0
362
+ ORDER BY total_ecosystem_strength DESC, total_providers DESC
363
+ """
364
+ return SQLQueries.execute_query(query)
365
+
366
+ @staticmethod
367
+ def get_provider_type_contributions():
368
+ """2. Which type of food provider contributes the most food?"""
369
+ query = """
370
+ SELECT
371
+ p.type as provider_type,
372
+ COUNT(DISTINCT p.provider_id) as total_providers,
373
+ COUNT(f.food_id) as total_food_listings,
374
+ SUM(f.quantity) as total_quantity_contributed,
375
+ AVG(f.quantity) as avg_quantity_per_listing,
376
+ -- Diversity metrics
377
+ COUNT(DISTINCT f.food_type) as food_types_offered,
378
+ COUNT(DISTINCT f.meal_type) as meal_types_offered,
379
+ -- Success metrics
380
+ COUNT(c.claim_id) as total_claims_received,
381
+ COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) as successful_distributions,
382
+ ROUND(100.0 * COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / NULLIF(COUNT(c.claim_id), 0), 2) as success_rate,
383
+ SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) as total_food_distributed,
384
+ -- Impact per provider
385
+ ROUND(SUM(f.quantity) / COUNT(DISTINCT p.provider_id), 2) as avg_contribution_per_provider,
386
+ -- Ranking
387
+ ROW_NUMBER() OVER (ORDER BY SUM(f.quantity) DESC) as contribution_rank
388
+ FROM providers p
389
+ LEFT JOIN food_listings f ON p.provider_id = f.provider_id
390
+ LEFT JOIN claims c ON f.food_id = c.food_id
391
+ GROUP BY p.type
392
+ HAVING COUNT(f.food_id) > 0
393
+ ORDER BY total_quantity_contributed DESC
394
+ """
395
+ return SQLQueries.execute_query(query)
396
+
397
+ @staticmethod
398
+ def get_provider_contacts_by_city(city_name=None):
399
+ """3. What is the contact information of food providers in a specific city?"""
400
+ if city_name:
401
+ where_clause = f"WHERE LOWER(p.city) = LOWER('{city_name}')"
402
+ else:
403
+ where_clause = ""
404
+
405
+ query = f"""
406
+ SELECT
407
+ p.provider_id,
408
+ p.name as provider_name,
409
+ p.type as provider_type,
410
+ p.city,
411
+ p.contact,
412
+ COALESCE(p.address, 'N/A') as address,
413
+ -- Activity metrics
414
+ COUNT(f.food_id) as active_food_listings,
415
+ SUM(f.quantity) as total_quantity_available,
416
+ COUNT(DISTINCT f.food_type) as food_types_offered,
417
+ -- Recent activity
418
+ COUNT(CASE WHEN DATE(f.expiry_date) >= DATE('now') THEN 1 END) as fresh_items_available,
419
+ COUNT(CASE WHEN DATE(f.expiry_date) < DATE('now') THEN 1 END) as expired_items,
420
+ -- Claims received
421
+ COUNT(c.claim_id) as claims_received,
422
+ COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) as successful_claims,
423
+ -- Status indicator
424
+ CASE
425
+ WHEN COUNT(CASE WHEN DATE(f.expiry_date) >= DATE('now') THEN 1 END) > 0 THEN '🟒 Active'
426
+ WHEN COUNT(f.food_id) > 0 THEN '🟑 Has Listings'
427
+ ELSE 'πŸ”΄ Inactive'
428
+ END as status
429
+ FROM providers p
430
+ LEFT JOIN food_listings f ON p.provider_id = f.provider_id
431
+ LEFT JOIN claims c ON f.food_id = c.food_id
432
+ {where_clause}
433
+ GROUP BY p.provider_id, p.name, p.type, p.city, p.contact, p.address
434
+ ORDER BY active_food_listings DESC, total_quantity_available DESC
435
+ """
436
+ return SQLQueries.execute_query(query)
437
+
438
+ @staticmethod
439
+ def get_top_claiming_receivers():
440
+ """4. Which receivers have claimed the most food?"""
441
+ query = """
442
+ SELECT
443
+ r.receiver_id,
444
+ r.name as receiver_name,
445
+ r.type as receiver_type,
446
+ r.city,
447
+ r.contact,
448
+ -- Claiming activity
449
+ COUNT(c.claim_id) as total_claims_made,
450
+ COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) as successful_claims,
451
+ COUNT(CASE WHEN LOWER(c.status) = 'pending' THEN 1 END) as pending_claims,
452
+ COUNT(CASE WHEN LOWER(c.status) = 'cancelled' THEN 1 END) as cancelled_claims,
453
+ ROUND(100.0 * COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / NULLIF(COUNT(c.claim_id), 0), 2) as success_rate,
454
+ -- Food quantity metrics
455
+ SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) as total_food_received,
456
+ AVG(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity END) as avg_food_per_successful_claim,
457
+ -- Food diversity
458
+ COUNT(DISTINCT CASE WHEN LOWER(c.status) = 'completed' THEN f.food_type END) as food_types_received,
459
+ COUNT(DISTINCT CASE WHEN LOWER(c.status) = 'completed' THEN f.meal_type END) as meal_types_received,
460
+ -- Recent activity (last 30 days)
461
+ COUNT(CASE WHEN DATE(c.timestamp) >= DATE('now', '-30 days') THEN 1 END) as recent_claims,
462
+ -- Performance rating
463
+ CASE
464
+ WHEN COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) >= 20
465
+ AND (100.0 * COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / NULLIF(COUNT(c.claim_id), 0)) >= 80
466
+ THEN '⭐⭐⭐ Excellent Receiver'
467
+ WHEN COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) >= 10
468
+ AND (100.0 * COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / NULLIF(COUNT(c.claim_id), 0)) >= 60
469
+ THEN '⭐⭐ Good Receiver'
470
+ WHEN COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) >= 1
471
+ THEN '⭐ Active Receiver'
472
+ ELSE '❌ Inactive'
473
+ END as receiver_rating
474
+ FROM receivers r
475
+ LEFT JOIN claims c ON r.receiver_id = c.receiver_id
476
+ LEFT JOIN food_listings f ON c.food_id = f.food_id
477
+ GROUP BY r.receiver_id, r.name, r.type, r.city, r.contact
478
+ HAVING COUNT(c.claim_id) > 0
479
+ ORDER BY total_food_received DESC, total_claims_made DESC
480
+ LIMIT 25
481
+ """
482
+ return SQLQueries.execute_query(query)
483
+
484
+ @staticmethod
485
+ def get_total_food_quantity_available():
486
+ """5. What is the total quantity of food available from all providers?"""
487
+ query = """
488
+ SELECT
489
+ 'System-Wide Food Availability' as metric_category,
490
+ -- Overall availability
491
+ COUNT(f.food_id) as total_food_items,
492
+ SUM(f.quantity) as total_quantity_available,
493
+ AVG(f.quantity) as avg_quantity_per_item,
494
+ -- By freshness
495
+ COUNT(CASE WHEN DATE(f.expiry_date) >= DATE('now') THEN 1 END) as fresh_items,
496
+ SUM(CASE WHEN DATE(f.expiry_date) >= DATE('now') THEN f.quantity ELSE 0 END) as fresh_quantity,
497
+ COUNT(CASE WHEN DATE(f.expiry_date) < DATE('now') THEN 1 END) as expired_items,
498
+ SUM(CASE WHEN DATE(f.expiry_date) < DATE('now') THEN f.quantity ELSE 0 END) as expired_quantity,
499
+ -- By urgency
500
+ COUNT(CASE WHEN julianday(f.expiry_date) - julianday('now') <= 1 THEN 1 END) as urgent_items,
501
+ SUM(CASE WHEN julianday(f.expiry_date) - julianday('now') <= 1 THEN f.quantity ELSE 0 END) as urgent_quantity,
502
+ COUNT(CASE WHEN julianday(f.expiry_date) - julianday('now') BETWEEN 1 AND 7 THEN 1 END) as soon_expiring_items,
503
+ SUM(CASE WHEN julianday(f.expiry_date) - julianday('now') BETWEEN 1 AND 7 THEN f.quantity ELSE 0 END) as soon_expiring_quantity,
504
+ -- Distribution metrics
505
+ COUNT(DISTINCT p.provider_id) as contributing_providers,
506
+ COUNT(DISTINCT p.city) as cities_covered,
507
+ COUNT(DISTINCT f.food_type) as food_types_available,
508
+ COUNT(DISTINCT f.meal_type) as meal_types_available,
509
+ -- Claims impact
510
+ COUNT(c.claim_id) as total_claims,
511
+ SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) as quantity_distributed,
512
+ ROUND(100.0 * SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) / NULLIF(SUM(f.quantity), 0), 2) as distribution_rate,
513
+ -- Efficiency metrics
514
+ ROUND(SUM(f.quantity) / NULLIF(COUNT(DISTINCT p.provider_id), 0), 2) as avg_quantity_per_provider,
515
+ ROUND(SUM(f.quantity) / NULLIF(COUNT(DISTINCT p.city), 0), 2) as avg_quantity_per_city
516
+ FROM food_listings f
517
+ LEFT JOIN providers p ON f.provider_id = p.provider_id
518
+ LEFT JOIN claims c ON f.food_id = c.food_id
519
+ """
520
+ return SQLQueries.execute_query(query)
521
+
522
+ @staticmethod
523
+ def get_cities_by_food_listings():
524
+ """6. Which city has the highest number of food listings?"""
525
+ query = """
526
+ SELECT
527
+ p.city,
528
+ COUNT(f.food_id) as total_food_listings,
529
+ SUM(f.quantity) as total_quantity,
530
+ AVG(f.quantity) as avg_quantity_per_listing,
531
+ -- Provider diversity
532
+ COUNT(DISTINCT p.provider_id) as unique_providers,
533
+ COUNT(DISTINCT p.type) as provider_types,
534
+ -- Food diversity
535
+ COUNT(DISTINCT f.food_type) as food_types_available,
536
+ COUNT(DISTINCT f.meal_type) as meal_types_available,
537
+ -- Freshness analysis
538
+ COUNT(CASE WHEN DATE(f.expiry_date) >= DATE('now') THEN 1 END) as fresh_listings,
539
+ COUNT(CASE WHEN DATE(f.expiry_date) < DATE('now') THEN 1 END) as expired_listings,
540
+ ROUND(100.0 * COUNT(CASE WHEN DATE(f.expiry_date) >= DATE('now') THEN 1 END) / COUNT(f.food_id), 2) as freshness_rate,
541
+ -- Claims activity
542
+ COUNT(c.claim_id) as total_claims,
543
+ COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) as successful_claims,
544
+ ROUND(100.0 * COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / NULLIF(COUNT(c.claim_id), 0), 2) as claim_success_rate,
545
+ -- City ranking
546
+ ROW_NUMBER() OVER (ORDER BY COUNT(f.food_id) DESC) as listings_rank,
547
+ ROW_NUMBER() OVER (ORDER BY SUM(f.quantity) DESC) as quantity_rank,
548
+ -- City performance score (composite)
549
+ ROUND(
550
+ (COUNT(f.food_id) * 0.4) +
551
+ (SUM(f.quantity) * 0.3 / 100) +
552
+ (COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) * 0.3)
553
+ , 2) as city_performance_score
554
+ FROM providers p
555
+ JOIN food_listings f ON p.provider_id = f.provider_id
556
+ LEFT JOIN claims c ON f.food_id = c.food_id
557
+ GROUP BY p.city
558
+ ORDER BY total_food_listings DESC, total_quantity DESC
559
+ LIMIT 20
560
+ """
561
+ return SQLQueries.execute_query(query)
562
+
563
+ @staticmethod
564
+ def get_most_common_food_types():
565
+ """7. What are the most commonly available food types?"""
566
+ query = """
567
+ SELECT
568
+ f.food_type,
569
+ COUNT(f.food_id) as total_items,
570
+ SUM(f.quantity) as total_quantity,
571
+ AVG(f.quantity) as avg_quantity_per_item,
572
+ -- Availability metrics
573
+ COUNT(CASE WHEN DATE(f.expiry_date) >= DATE('now') THEN 1 END) as available_items,
574
+ SUM(CASE WHEN DATE(f.expiry_date) >= DATE('now') THEN f.quantity ELSE 0 END) as available_quantity,
575
+ -- Provider diversity
576
+ COUNT(DISTINCT p.provider_id) as unique_providers,
577
+ COUNT(DISTINCT p.type) as provider_types,
578
+ COUNT(DISTINCT p.city) as cities_available,
579
+ -- Meal type breakdown
580
+ COUNT(DISTINCT f.meal_type) as meal_types,
581
+ -- Demand analysis
582
+ COUNT(c.claim_id) as total_claims,
583
+ COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) as successful_claims,
584
+ ROUND(100.0 * COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / NULLIF(COUNT(c.claim_id), 0), 2) as claim_success_rate,
585
+ -- Supply vs demand ratio
586
+ ROUND(CAST(COUNT(f.food_id) AS FLOAT) / NULLIF(COUNT(c.claim_id), 0), 2) as supply_demand_ratio,
587
+ -- Popularity ranking
588
+ ROW_NUMBER() OVER (ORDER BY COUNT(f.food_id) DESC) as popularity_rank,
589
+ ROW_NUMBER() OVER (ORDER BY COUNT(c.claim_id) DESC) as demand_rank,
590
+ -- Market share
591
+ ROUND(100.0 * COUNT(f.food_id) / (SELECT COUNT(*) FROM food_listings), 2) as market_share_percentage
592
+ FROM food_listings f
593
+ LEFT JOIN providers p ON f.provider_id = p.provider_id
594
+ LEFT JOIN claims c ON f.food_id = c.food_id
595
+ GROUP BY f.food_type
596
+ ORDER BY total_items DESC, total_quantity DESC
597
+ """
598
+ return SQLQueries.execute_query(query)
599
+
600
+ @staticmethod
601
+ def get_claims_per_food_item():
602
+ """8. How many food claims have been made for each food item?"""
603
+ query = """
604
+ SELECT
605
+ f.food_id,
606
+ f.food_name,
607
+ f.food_type,
608
+ f.meal_type,
609
+ f.quantity,
610
+ f.expiry_date,
611
+ p.name as provider_name,
612
+ p.type as provider_type,
613
+ p.city as provider_city,
614
+ -- Claims analysis
615
+ COUNT(c.claim_id) as total_claims,
616
+ COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) as completed_claims,
617
+ COUNT(CASE WHEN LOWER(c.status) = 'pending' THEN 1 END) as pending_claims,
618
+ COUNT(CASE WHEN LOWER(c.status) = 'cancelled' THEN 1 END) as cancelled_claims,
619
+ -- Success metrics
620
+ ROUND(100.0 * COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / NULLIF(COUNT(c.claim_id), 0), 2) as success_rate,
621
+ -- Timing analysis
622
+ ROUND(AVG(julianday(f.expiry_date) - julianday(c.timestamp)), 1) as avg_days_before_expiry_when_claimed,
623
+ -- Competition analysis
624
+ ROUND(CAST(COUNT(c.claim_id) AS FLOAT) / f.quantity, 2) as claims_per_unit,
625
+ -- Status
626
+ CASE
627
+ WHEN DATE(f.expiry_date) < DATE('now') THEN 'πŸ”΄ Expired'
628
+ WHEN COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) > 0 THEN '🟒 Distributed'
629
+ WHEN COUNT(c.claim_id) > 0 THEN '🟑 Has Claims'
630
+ WHEN julianday(f.expiry_date) - julianday('now') <= 1 THEN '🟠 Urgent'
631
+ ELSE 'βšͺ Available'
632
+ END as item_status
633
+ FROM food_listings f
634
+ JOIN providers p ON f.provider_id = p.provider_id
635
+ LEFT JOIN claims c ON f.food_id = c.food_id
636
+ GROUP BY f.food_id, f.food_name, f.food_type, f.meal_type, f.quantity, f.expiry_date, p.name, p.type, p.city
637
+ ORDER BY total_claims DESC, f.food_id
638
+ """
639
+ return SQLQueries.execute_query(query)
640
+
641
+ @staticmethod
642
+ def get_provider_highest_successful_claims():
643
+ """9. Which provider has had the highest number of successful food claims?"""
644
+ query = """
645
+ SELECT
646
+ p.provider_id,
647
+ p.name as provider_name,
648
+ p.type as provider_type,
649
+ p.city,
650
+ p.contact,
651
+ -- Food provision metrics
652
+ COUNT(f.food_id) as total_food_listings,
653
+ SUM(f.quantity) as total_quantity_provided,
654
+ COUNT(DISTINCT f.food_type) as food_types_diversity,
655
+ -- Claims success metrics
656
+ COUNT(c.claim_id) as total_claims_received,
657
+ COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) as successful_claims,
658
+ COUNT(CASE WHEN LOWER(c.status) = 'pending' THEN 1 END) as pending_claims,
659
+ COUNT(CASE WHEN LOWER(c.status) = 'cancelled' THEN 1 END) as cancelled_claims,
660
+ ROUND(100.0 * COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / NULLIF(COUNT(c.claim_id), 0), 2) as success_rate,
661
+ -- Impact metrics
662
+ SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) as total_food_distributed,
663
+ COUNT(DISTINCT CASE WHEN LOWER(c.status) = 'completed' THEN c.receiver_id END) as unique_receivers_served,
664
+ -- Efficiency metrics
665
+ ROUND(COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / NULLIF(COUNT(f.food_id), 0), 2) as claims_per_listing,
666
+ ROUND(SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) / NULLIF(COUNT(f.food_id), 0), 2) as avg_distributed_per_listing,
667
+ -- Time efficiency
668
+ ROUND(AVG(CASE WHEN LOWER(c.status) = 'completed' THEN julianday(f.expiry_date) - julianday(c.timestamp) END), 1) as avg_days_before_expiry_distributed,
669
+ -- Recent performance (last 30 days)
670
+ COUNT(CASE WHEN DATE(c.timestamp) >= DATE('now', '-30 days') AND LOWER(c.status) = 'completed' THEN 1 END) as recent_successful_claims,
671
+ -- Awards/Recognition
672
+ CASE
673
+ WHEN COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) >= 50
674
+ AND (100.0 * COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / NULLIF(COUNT(c.claim_id), 0)) >= 85
675
+ THEN 'πŸ† Champion Provider'
676
+ WHEN COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) >= 25
677
+ AND (100.0 * COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / NULLIF(COUNT(c.claim_id), 0)) >= 75
678
+ THEN '⭐⭐⭐ Excellent Provider'
679
+ WHEN COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) >= 10
680
+ AND (100.0 * COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / NULLIF(COUNT(c.claim_id), 0)) >= 60
681
+ THEN '⭐⭐ Good Provider'
682
+ WHEN COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) >= 1
683
+ THEN '⭐ Active Provider'
684
+ ELSE '❌ Inactive'
685
+ END as provider_recognition
686
+ FROM providers p
687
+ LEFT JOIN food_listings f ON p.provider_id = f.provider_id
688
+ LEFT JOIN claims c ON f.food_id = c.food_id
689
+ GROUP BY p.provider_id, p.name, p.type, p.city, p.contact
690
+ HAVING COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) > 0
691
+ ORDER BY successful_claims DESC, total_food_distributed DESC
692
+ LIMIT 25
693
+ """
694
+ return SQLQueries.execute_query(query)
695
+
696
+ @staticmethod
697
+ def get_claims_completion_percentages():
698
+ """10. What percentage of food claims are completed vs. pending vs. canceled?"""
699
+ query = """
700
+ SELECT
701
+ c.status,
702
+ COUNT(*) as claim_count,
703
+ ROUND(100.0 * COUNT(*) / (SELECT COUNT(*) FROM claims), 2) as percentage,
704
+ -- Quantity analysis
705
+ SUM(f.quantity) as total_quantity_involved,
706
+ AVG(f.quantity) as avg_quantity_per_claim,
707
+ -- Geographic distribution
708
+ COUNT(DISTINCT p.city) as cities_involved,
709
+ COUNT(DISTINCT p.provider_id) as providers_involved,
710
+ COUNT(DISTINCT r.receiver_id) as receivers_involved,
711
+ -- Food type diversity
712
+ COUNT(DISTINCT f.food_type) as food_types_in_status,
713
+ COUNT(DISTINCT f.meal_type) as meal_types_in_status,
714
+ -- Time analysis
715
+ ROUND(AVG(julianday('now') - julianday(c.timestamp)), 1) as avg_days_since_claim,
716
+ ROUND(AVG(CASE WHEN LOWER(c.status) = 'completed' THEN julianday(f.expiry_date) - julianday(c.timestamp) END), 1) as avg_days_before_expiry_when_completed,
717
+ -- Recent trends (last 30 days)
718
+ COUNT(CASE WHEN DATE(c.timestamp) >= DATE('now', '-30 days') THEN 1 END) as recent_claims,
719
+ ROUND(100.0 * COUNT(CASE WHEN DATE(c.timestamp) >= DATE('now', '-30 days') THEN 1 END) /
720
+ NULLIF((SELECT COUNT(*) FROM claims WHERE DATE(timestamp) >= DATE('now', '-30 days')), 0), 2) as recent_percentage,
721
+ -- Impact calculation
722
+ CASE c.status
723
+ WHEN 'Completed' THEN SUM(f.quantity)
724
+ ELSE 0
725
+ END as food_impact_kg,
726
+ -- Status insights
727
+ CASE c.status
728
+ WHEN 'Completed' THEN 'βœ… Successfully distributed food to those in need'
729
+ WHEN 'Pending' THEN '⏳ Awaiting pickup or processing'
730
+ WHEN 'Cancelled' THEN '❌ Claims that did not proceed - investigate reasons'
731
+ ELSE '❓ Unknown status'
732
+ END as status_insight
733
+ FROM claims c
734
+ JOIN food_listings f ON c.food_id = f.food_id
735
+ JOIN providers p ON f.provider_id = p.provider_id
736
+ LEFT JOIN receivers r ON c.receiver_id = r.receiver_id
737
+ GROUP BY c.status
738
+ ORDER BY claim_count DESC
739
+ """
740
+ return SQLQueries.execute_query(query)
741
+
742
+ @staticmethod
743
+ def get_avg_quantity_per_receiver():
744
+ """11. What is the average quantity of food claimed per receiver?"""
745
+ query = """
746
+ SELECT
747
+ r.receiver_id,
748
+ r.name as receiver_name,
749
+ r.type as receiver_type,
750
+ r.city,
751
+ -- Claiming metrics
752
+ COUNT(c.claim_id) as total_claims,
753
+ COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) as successful_claims,
754
+ SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) as total_food_received,
755
+ ROUND(AVG(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity END), 2) as avg_quantity_per_successful_claim,
756
+ ROUND(SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) / NULLIF(COUNT(c.claim_id), 0), 2) as avg_quantity_per_total_claim,
757
+ -- Efficiency metrics
758
+ ROUND(100.0 * COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / NULLIF(COUNT(c.claim_id), 0), 2) as claim_success_rate,
759
+ -- Food diversity received
760
+ COUNT(DISTINCT CASE WHEN LOWER(c.status) = 'completed' THEN f.food_type END) as food_types_received,
761
+ COUNT(DISTINCT CASE WHEN LOWER(c.status) = 'completed' THEN f.meal_type END) as meal_types_received,
762
+ -- Provider diversity
763
+ COUNT(DISTINCT CASE WHEN LOWER(c.status) = 'completed' THEN p.provider_id END) as providers_claimed_from,
764
+ -- Time analysis
765
+ ROUND(AVG(CASE WHEN LOWER(c.status) = 'completed' THEN julianday(f.expiry_date) - julianday(c.timestamp) END), 1) as avg_days_before_expiry_received,
766
+ -- Recent activity
767
+ COUNT(CASE WHEN DATE(c.timestamp) >= DATE('now', '-30 days') THEN 1 END) as recent_claims,
768
+ SUM(CASE WHEN DATE(c.timestamp) >= DATE('now', '-30 days') AND LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) as recent_food_received,
769
+ -- Receiver category based on activity
770
+ CASE
771
+ WHEN SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) >= 500 THEN 'πŸ† Major Recipient'
772
+ WHEN SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) >= 200 THEN '⭐⭐⭐ High Volume'
773
+ WHEN SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) >= 50 THEN '⭐⭐ Regular'
774
+ WHEN SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) >= 1 THEN '⭐ Occasional'
775
+ ELSE '❌ No Success'
776
+ END as receiver_category
777
+ FROM receivers r
778
+ LEFT JOIN claims c ON r.receiver_id = c.receiver_id
779
+ LEFT JOIN food_listings f ON c.food_id = f.food_id
780
+ LEFT JOIN providers p ON f.provider_id = p.provider_id
781
+ GROUP BY r.receiver_id, r.name, r.type, r.city
782
+ HAVING COUNT(c.claim_id) > 0
783
+ ORDER BY total_food_received DESC, avg_quantity_per_successful_claim DESC
784
+ """
785
+ return SQLQueries.execute_query(query)
786
+
787
+ @staticmethod
788
+ def get_most_claimed_meal_types():
789
+ """12. Which meal type is claimed the most?"""
790
+ query = """
791
+ SELECT
792
+ f.meal_type,
793
+ -- Claiming metrics
794
+ COUNT(c.claim_id) as total_claims,
795
+ COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) as successful_claims,
796
+ COUNT(CASE WHEN LOWER(c.status) = 'pending' THEN 1 END) as pending_claims,
797
+ COUNT(CASE WHEN LOWER(c.status) = 'cancelled' THEN 1 END) as cancelled_claims,
798
+ ROUND(100.0 * COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / NULLIF(COUNT(c.claim_id), 0), 2) as success_rate,
799
+ -- Quantity metrics
800
+ SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) as total_quantity_distributed,
801
+ AVG(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity END) as avg_quantity_per_successful_claim,
802
+ -- Supply vs demand analysis
803
+ COUNT(DISTINCT f.food_id) as total_items_available,
804
+ ROUND(CAST(COUNT(c.claim_id) AS FLOAT) / NULLIF(COUNT(DISTINCT f.food_id), 0), 2) as demand_supply_ratio,
805
+ -- Provider and receiver diversity
806
+ COUNT(DISTINCT p.provider_id) as providers_offering,
807
+ COUNT(DISTINCT r.receiver_id) as receivers_claiming,
808
+ COUNT(DISTINCT p.city) as cities_with_supply,
809
+ -- Food type diversity within meal type
810
+ COUNT(DISTINCT f.food_type) as food_types_in_meal,
811
+ -- Time analysis
812
+ ROUND(AVG(julianday(f.expiry_date) - julianday('now')), 1) as avg_shelf_life_days,
813
+ ROUND(AVG(CASE WHEN LOWER(c.status) = 'completed' THEN julianday(f.expiry_date) - julianday(c.timestamp) END), 1) as avg_days_before_expiry_claimed,
814
+ -- Market share
815
+ ROUND(100.0 * COUNT(c.claim_id) / (SELECT COUNT(*) FROM claims), 2) as claim_market_share,
816
+ -- Popularity ranking
817
+ ROW_NUMBER() OVER (ORDER BY COUNT(c.claim_id) DESC) as demand_rank,
818
+ ROW_NUMBER() OVER (ORDER BY COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) DESC) as success_rank,
819
+ -- Recent trends (last 30 days)
820
+ COUNT(CASE WHEN DATE(c.timestamp) >= DATE('now', '-30 days') THEN 1 END) as recent_claims,
821
+ -- Meal time insights
822
+ CASE f.meal_type
823
+ WHEN 'Breakfast' THEN 'πŸŒ… Morning meals - typically fresh items needed'
824
+ WHEN 'Lunch' THEN '🌞 Midday meals - highest volume period'
825
+ WHEN 'Dinner' THEN 'πŸŒ™ Evening meals - often hearty dishes'
826
+ WHEN 'Snacks' THEN 'πŸͺ Light items - good for quick distribution'
827
+ WHEN 'Beverages' THEN 'πŸ₯€ Drinks - long shelf life items'
828
+ ELSE '🍽️ Mixed meal items'
829
+ END as meal_type_insight
830
+ FROM food_listings f
831
+ LEFT JOIN claims c ON f.food_id = c.food_id
832
+ LEFT JOIN providers p ON f.provider_id = p.provider_id
833
+ LEFT JOIN receivers r ON c.receiver_id = r.receiver_id
834
+ GROUP BY f.meal_type
835
+ ORDER BY total_claims DESC, successful_claims DESC
836
+ """
837
+ return SQLQueries.execute_query(query)
838
+
839
+ @staticmethod
840
+ def get_total_donations_per_provider():
841
+ """13. What is the total quantity of food donated by each provider?"""
842
+ query = """
843
+ SELECT
844
+ p.provider_id,
845
+ p.name as provider_name,
846
+ p.type as provider_type,
847
+ p.city,
848
+ p.contact,
849
+ -- Donation metrics
850
+ COUNT(f.food_id) as total_food_items_listed,
851
+ SUM(f.quantity) as total_quantity_donated,
852
+ AVG(f.quantity) as avg_quantity_per_donation,
853
+ -- Distribution success
854
+ COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) as items_successfully_distributed,
855
+ SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) as quantity_successfully_distributed,
856
+ ROUND(100.0 * SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) / NULLIF(SUM(f.quantity), 0), 2) as distribution_success_rate,
857
+ -- Wastage analysis
858
+ COUNT(CASE WHEN julianday('now') - julianday(f.expiry_date) > 0 THEN 1 END) as expired_items,
859
+ SUM(CASE WHEN julianday('now') - julianday(f.expiry_date) > 0 THEN f.quantity ELSE 0 END) as wasted_quantity,
860
+ ROUND(100.0 * SUM(CASE WHEN julianday('now') - julianday(f.expiry_date) > 0 THEN f.quantity ELSE 0 END) / NULLIF(SUM(f.quantity), 0), 2) as wastage_rate,
861
+ -- Food diversity
862
+ COUNT(DISTINCT f.food_type) as food_types_donated,
863
+ COUNT(DISTINCT f.meal_type) as meal_types_donated,
864
+ -- Impact metrics
865
+ COUNT(DISTINCT r.receiver_id) as unique_receivers_served,
866
+ COUNT(DISTINCT CASE WHEN LOWER(c.status) = 'completed' THEN r.receiver_id END) as receivers_successfully_served,
867
+ -- Time efficiency
868
+ ROUND(AVG(julianday(f.expiry_date) - julianday('now')), 1) as avg_donation_shelf_life,
869
+ ROUND(AVG(CASE WHEN LOWER(c.status) = 'completed' THEN julianday(f.expiry_date) - julianday(c.timestamp) END), 1) as avg_days_before_expiry_distributed,
870
+ -- Recent activity (last 30 days)
871
+ COUNT(CASE WHEN DATE(f.expiry_date) >= DATE('now', '-30 days') THEN 1 END) as recent_donations,
872
+ SUM(CASE WHEN DATE(f.expiry_date) >= DATE('now', '-30 days') THEN f.quantity ELSE 0 END) as recent_donation_quantity,
873
+ -- Provider impact score
874
+ ROUND(
875
+ (SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) * 0.6) +
876
+ (COUNT(DISTINCT r.receiver_id) * 10 * 0.2) +
877
+ (COUNT(DISTINCT f.food_type) * 5 * 0.2)
878
+ , 2) as provider_impact_score,
879
+ -- Recognition level
880
+ CASE
881
+ WHEN SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) >= 1000
882
+ AND (100.0 * SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) / NULLIF(SUM(f.quantity), 0)) >= 80
883
+ THEN 'πŸ† Champion Donor'
884
+ WHEN SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) >= 500
885
+ AND (100.0 * SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) / NULLIF(SUM(f.quantity), 0)) >= 70
886
+ THEN '⭐⭐⭐ Excellent Donor'
887
+ WHEN SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) >= 200
888
+ AND (100.0 * SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) / NULLIF(SUM(f.quantity), 0)) >= 60
889
+ THEN '⭐⭐ Good Donor'
890
+ WHEN SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) >= 1
891
+ THEN '⭐ Active Donor'
892
+ ELSE '❌ Inactive'
893
+ END as donor_recognition
894
+ FROM providers p
895
+ LEFT JOIN food_listings f ON p.provider_id = f.provider_id
896
+ LEFT JOIN claims c ON f.food_id = c.food_id
897
+ LEFT JOIN receivers r ON c.receiver_id = r.receiver_id
898
+ GROUP BY p.provider_id, p.name, p.type, p.city, p.contact
899
+ HAVING COUNT(f.food_id) > 0
900
+ ORDER BY total_quantity_donated DESC, quantity_successfully_distributed DESC
901
+ """
902
+ return SQLQueries.execute_query(query)
903
+
904
+ @staticmethod
905
+ def get_food_wastage_trends_comprehensive():
906
+ """14. Enhanced food wastage trends with all insights"""
907
+ query = """
908
+ SELECT
909
+ food_type,
910
+ COUNT(*) as total_listings,
911
+ SUM(quantity) as total_quantity,
912
+ AVG(quantity) as avg_quantity_per_listing,
913
+ -- Wastage calculations
914
+ COUNT(CASE WHEN julianday('now') - julianday(expiry_date) > 0 THEN 1 END) as expired_items,
915
+ SUM(CASE WHEN julianday('now') - julianday(expiry_date) > 0 THEN quantity ELSE 0 END) as wasted_quantity,
916
+ ROUND(100.0 * COUNT(CASE WHEN julianday('now') - julianday(expiry_date) > 0 THEN 1 END) / COUNT(*), 2) as wastage_percentage,
917
+ ROUND(100.0 * SUM(CASE WHEN julianday('now') - julianday(expiry_date) > 0 THEN quantity ELSE 0 END) / SUM(quantity), 2) as quantity_wastage_percentage,
918
+ -- Urgency analysis
919
+ COUNT(CASE WHEN julianday(expiry_date) - julianday('now') BETWEEN 0 AND 1 THEN 1 END) as critical_items,
920
+ COUNT(CASE WHEN julianday(expiry_date) - julianday('now') BETWEEN 1 AND 3 THEN 1 END) as urgent_items,
921
+ COUNT(CASE WHEN julianday(expiry_date) - julianday('now') BETWEEN 3 AND 7 THEN 1 END) as soon_items,
922
+ COUNT(CASE WHEN julianday(expiry_date) - julianday('now') > 7 THEN 1 END) as safe_items,
923
+ -- Claims impact
924
+ COUNT(c.claim_id) as total_claims,
925
+ COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) as successful_distributions,
926
+ SUM(CASE WHEN LOWER(c.status) = 'completed' THEN quantity ELSE 0 END) as quantity_saved_through_claims,
927
+ ROUND(100.0 * SUM(CASE WHEN LOWER(c.status) = 'completed' THEN quantity ELSE 0 END) / SUM(quantity), 2) as saved_percentage,
928
+ -- Provider diversity
929
+ COUNT(DISTINCT p.provider_id) as contributing_providers,
930
+ COUNT(DISTINCT p.city) as cities_offering
931
+ FROM food_listings f
932
+ LEFT JOIN claims c ON f.food_id = c.food_id
933
+ LEFT JOIN providers p ON f.provider_id = p.provider_id
934
+ GROUP BY food_type
935
+ ORDER BY wasted_quantity DESC, total_quantity DESC
936
+ """
937
+ return SQLQueries.execute_query(query)
938
+
939
+ @staticmethod
940
+ def get_comprehensive_system_analysis():
941
+ """15. Comprehensive analysis with all outputs and insights"""
942
+ query = """
943
+ WITH provider_stats AS (
944
+ SELECT
945
+ p.type as provider_type,
946
+ COUNT(DISTINCT p.provider_id) as provider_count,
947
+ SUM(f.quantity) as total_contribution,
948
+ COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) as successful_distributions
949
+ FROM providers p
950
+ LEFT JOIN food_listings f ON p.provider_id = f.provider_id
951
+ LEFT JOIN claims c ON f.food_id = c.food_id
952
+ GROUP BY p.type
953
+ ),
954
+ city_stats AS (
955
+ SELECT
956
+ p.city,
957
+ COUNT(DISTINCT p.provider_id) as providers,
958
+ COUNT(DISTINCT r.receiver_id) as receivers,
959
+ COUNT(c.claim_id) as total_claims,
960
+ SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) as food_distributed
961
+ FROM providers p
962
+ LEFT JOIN receivers r ON p.city = r.city
963
+ LEFT JOIN food_listings f ON p.provider_id = f.provider_id
964
+ LEFT JOIN claims c ON f.food_id = c.food_id
965
+ GROUP BY p.city
966
+ ),
967
+ food_stats AS (
968
+ SELECT
969
+ f.food_type,
970
+ COUNT(f.food_id) as total_items,
971
+ SUM(f.quantity) as total_quantity,
972
+ COUNT(CASE WHEN julianday('now') - julianday(f.expiry_date) > 0 THEN 1 END) as wasted_items,
973
+ SUM(CASE WHEN julianday('now') - julianday(f.expiry_date) > 0 THEN f.quantity ELSE 0 END) as wasted_quantity
974
+ FROM food_listings f
975
+ GROUP BY f.food_type
976
+ )
977
+ SELECT
978
+ 'COMPREHENSIVE SYSTEM ANALYSIS' as analysis_category,
979
+ -- Overall metrics
980
+ (SELECT COUNT(*) FROM providers) as total_providers,
981
+ (SELECT COUNT(*) FROM receivers) as total_receivers,
982
+ (SELECT COUNT(*) FROM food_listings) as total_food_items,
983
+ (SELECT SUM(quantity) FROM food_listings) as total_food_quantity,
984
+ (SELECT COUNT(*) FROM claims) as total_claims,
985
+ -- Performance metrics
986
+ (SELECT COUNT(*) FROM claims WHERE LOWER(status) = 'completed') as successful_distributions,
987
+ (SELECT ROUND(100.0 * COUNT(*) / (SELECT COUNT(*) FROM claims), 2) FROM claims WHERE LOWER(status) = 'completed') as success_rate,
988
+ -- Top provider type
989
+ (SELECT provider_type FROM provider_stats ORDER BY total_contribution DESC LIMIT 1) as top_provider_type_by_contribution,
990
+ (SELECT total_contribution FROM provider_stats ORDER BY total_contribution DESC LIMIT 1) as top_provider_contribution,
991
+ -- Top city
992
+ (SELECT city FROM city_stats ORDER BY food_distributed DESC LIMIT 1) as top_city_by_distribution,
993
+ (SELECT food_distributed FROM city_stats ORDER BY food_distributed DESC LIMIT 1) as top_city_distribution,
994
+ -- Most wasted food type
995
+ (SELECT food_type FROM food_stats ORDER BY wasted_quantity DESC LIMIT 1) as most_wasted_food_type,
996
+ (SELECT wasted_quantity FROM food_stats ORDER BY wasted_quantity DESC LIMIT 1) as highest_waste_quantity,
997
+ -- System health indicators
998
+ (SELECT ROUND(100.0 * SUM(wasted_quantity) / SUM(total_quantity), 2) FROM food_stats) as overall_wastage_rate,
999
+ (SELECT COUNT(*) FROM city_stats WHERE providers > 0 AND receivers > 0) as cities_with_complete_ecosystem,
1000
+ -- Key insights
1001
+ CASE
1002
+ WHEN (SELECT ROUND(100.0 * COUNT(*) / (SELECT COUNT(*) FROM claims), 2) FROM claims WHERE LOWER(status) = 'completed') >= 80
1003
+ THEN 'System performing excellently'
1004
+ WHEN (SELECT ROUND(100.0 * COUNT(*) / (SELECT COUNT(*) FROM claims), 2) FROM claims WHERE LOWER(status) = 'completed') >= 60
1005
+ THEN 'System performing well with room for improvement'
1006
+ ELSE 'System needs significant optimization'
1007
+ END as overall_system_health,
1008
+ -- Action recommendations
1009
+ 'Focus on ' || (SELECT food_type FROM food_stats ORDER BY wasted_quantity DESC LIMIT 1) || ' wastage reduction' as primary_action_needed,
1010
+ 'Expand operations in ' || (SELECT city FROM city_stats ORDER BY (providers + receivers) ASC LIMIT 1) || ' for better coverage' as expansion_recommendation
1011
+ """
1012
+ return SQLQueries.execute_query(query)
1013
+
1014
+ # ========== NEW: TIME SERIES ANALYSIS QUERIES ==========
1015
+ @staticmethod
1016
+ def get_time_series_claims_trends():
1017
+ """NEW: Time series analysis of claims trends"""
1018
+ query = """
1019
+ SELECT
1020
+ DATE(c.timestamp) as claim_date,
1021
+ COUNT(*) as total_claims,
1022
+ COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) as completed_claims,
1023
+ COUNT(CASE WHEN LOWER(c.status) = 'pending' THEN 1 END) as pending_claims,
1024
+ COUNT(CASE WHEN LOWER(c.status) = 'cancelled' THEN 1 END) as cancelled_claims,
1025
+ SUM(f.quantity) as total_quantity_claimed,
1026
+ SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) as quantity_distributed,
1027
+ ROUND(100.0 * COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / COUNT(*), 2) as daily_success_rate,
1028
+ -- Day of week analysis
1029
+ CASE strftime('%w', c.timestamp)
1030
+ WHEN '0' THEN 'Sunday'
1031
+ WHEN '1' THEN 'Monday'
1032
+ WHEN '2' THEN 'Tuesday'
1033
+ WHEN '3' THEN 'Wednesday'
1034
+ WHEN '4' THEN 'Thursday'
1035
+ WHEN '5' THEN 'Friday'
1036
+ WHEN '6' THEN 'Saturday'
1037
+ END as day_of_week,
1038
+ -- Month analysis
1039
+ strftime('%Y-%m', c.timestamp) as year_month
1040
+ FROM claims c
1041
+ JOIN food_listings f ON c.food_id = f.food_id
1042
+ WHERE c.timestamp IS NOT NULL
1043
+ GROUP BY DATE(c.timestamp)
1044
+ ORDER BY claim_date
1045
+ """
1046
+ return SQLQueries.execute_query(query)
1047
+
1048
+ @staticmethod
1049
+ def get_time_series_food_listings_trends():
1050
+ """NEW: Time series analysis of food listings by expiry trends"""
1051
+ query = """
1052
+ SELECT
1053
+ DATE(f.expiry_date) as expiry_date,
1054
+ COUNT(*) as items_expiring,
1055
+ SUM(f.quantity) as quantity_expiring,
1056
+ COUNT(DISTINCT f.food_type) as food_types_expiring,
1057
+ COUNT(DISTINCT p.provider_id) as providers_affected,
1058
+ -- Claims before expiry
1059
+ COUNT(c.claim_id) as claims_made,
1060
+ COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) as items_saved,
1061
+ SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) as quantity_saved,
1062
+ -- Wastage calculation
1063
+ COUNT(*) - COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) as items_wasted,
1064
+ SUM(f.quantity) - SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) as quantity_wasted,
1065
+ ROUND(100.0 * COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / COUNT(*), 2) as save_rate,
1066
+ -- Week analysis
1067
+ strftime('%Y-W%W', f.expiry_date) as year_week,
1068
+ strftime('%Y-%m', f.expiry_date) as year_month
1069
+ FROM food_listings f
1070
+ LEFT JOIN providers p ON f.provider_id = p.provider_id
1071
+ LEFT JOIN claims c ON f.food_id = c.food_id
1072
+ WHERE f.expiry_date IS NOT NULL
1073
+ GROUP BY DATE(f.expiry_date)
1074
+ ORDER BY expiry_date
1075
+ """
1076
+ return SQLQueries.execute_query(query)
1077
+
1078
+ @staticmethod
1079
+ def get_monthly_performance_trends():
1080
+ """NEW: Monthly performance trends analysis"""
1081
+ query = """
1082
+ SELECT
1083
+ strftime('%Y-%m', c.timestamp) as month,
1084
+ COUNT(*) as total_claims,
1085
+ COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) as completed_claims,
1086
+ SUM(f.quantity) as total_quantity_involved,
1087
+ SUM(CASE WHEN LOWER(c.status) = 'completed' THEN f.quantity ELSE 0 END) as quantity_distributed,
1088
+ COUNT(DISTINCT p.provider_id) as active_providers,
1089
+ COUNT(DISTINCT r.receiver_id) as active_receivers,
1090
+ COUNT(DISTINCT p.city) as cities_involved,
1091
+ ROUND(100.0 * COUNT(CASE WHEN LOWER(c.status) = 'completed' THEN 1 END) / COUNT(*), 2) as monthly_success_rate,
1092
+ ROUND(AVG(julianday(f.expiry_date) - julianday(c.timestamp)), 1) as avg_days_before_expiry,
1093
+ -- Growth metrics
1094
+ LAG(COUNT(*)) OVER (ORDER BY strftime('%Y-%m', c.timestamp)) as prev_month_claims,
1095
+ ROUND(100.0 * (COUNT(*) - LAG(COUNT(*)) OVER (ORDER BY strftime('%Y-%m', c.timestamp))) /
1096
+ NULLIF(LAG(COUNT(*)) OVER (ORDER BY strftime('%Y-%m', c.timestamp)), 0), 2) as claims_growth_rate
1097
+ FROM claims c
1098
+ JOIN food_listings f ON c.food_id = f.food_id
1099
+ JOIN providers p ON f.provider_id = p.provider_id
1100
+ LEFT JOIN receivers r ON c.receiver_id = r.receiver_id
1101
+ WHERE c.timestamp IS NOT NULL
1102
+ GROUP BY strftime('%Y-%m', c.timestamp)
1103
+ ORDER BY month
1104
+ """
1105
+ return SQLQueries.execute_query(query)
1106
+
1107
+ # ========== ENHANCED VISUALIZATION FUNCTIONS ==========
1108
+ def create_project_required_charts():
1109
+ """Create all charts required by the project with proper error handling"""
1110
+ charts = {}
1111
+ try:
1112
+ # 1. Food Wastage Trends by Category (Project Requirement)
1113
+ category_data = SQLQueries.get_food_wastage_trends_comprehensive()
1114
+ if not category_data.empty:
1115
+ fig = px.bar(category_data,
1116
+ x='food_type',
1117
+ y='total_quantity',
1118
+ title='πŸ“Š Food Wastage Trends by Category (Enhanced)',
1119
+ color='wasted_quantity',
1120
+ hover_data=['total_listings', 'wastage_percentage', 'critical_items'],
1121
+ color_continuous_scale='Reds')
1122
+ fig.update_layout(
1123
+ plot_bgcolor='rgba(0,0,0,0)',
1124
+ paper_bgcolor='rgba(0,0,0,0)',
1125
+ font=dict(size=12)
1126
+ )
1127
+ charts['category_trends'] = fig
1128
+
1129
+ # 2. Provider Type Contributions
1130
+ provider_type_data = SQLQueries.get_provider_type_contributions()
1131
+ if not provider_type_data.empty:
1132
+ fig = px.bar(provider_type_data,
1133
+ x='provider_type',
1134
+ y='total_quantity_contributed',
1135
+ title='🏒 Provider Type Contributions',
1136
+ color='success_rate',
1137
+ hover_data=['total_providers', 'food_types_offered'],
1138
+ color_continuous_scale='Blues')
1139
+ fig.update_layout(
1140
+ plot_bgcolor='rgba(0,0,0,0)',
1141
+ paper_bgcolor='rgba(0,0,0,0)'
1142
+ )
1143
+ charts['provider_type_contributions'] = fig
1144
+
1145
+ # 3. Cities by Food Listings
1146
+ city_data = SQLQueries.get_cities_by_food_listings()
1147
+ if not city_data.empty:
1148
+ fig = px.bar(city_data.head(10),
1149
+ x='city',
1150
+ y='total_food_listings',
1151
+ title='🌍 Top Cities by Food Listings',
1152
+ color='city_performance_score',
1153
+ hover_data=['total_quantity', 'unique_providers', 'claim_success_rate'],
1154
+ color_continuous_scale='Viridis')
1155
+ fig.update_layout(
1156
+ plot_bgcolor='rgba(0,0,0,0)',
1157
+ paper_bgcolor='rgba(0,0,0,0)',
1158
+ xaxis={'categoryorder':'total descending'}
1159
+ )
1160
+ charts['city_listings'] = fig
1161
+
1162
+ # 4. Most Common Food Types
1163
+ food_type_data = SQLQueries.get_most_common_food_types()
1164
+ if not food_type_data.empty:
1165
+ fig = px.treemap(food_type_data.head(15),
1166
+ path=['food_type'],
1167
+ values='total_items',
1168
+ title='🍽️ Most Common Food Types Distribution',
1169
+ color='claim_success_rate',
1170
+ color_continuous_scale='Plasma',
1171
+ hover_data=['supply_demand_ratio'])
1172
+ charts['food_type_distribution'] = fig
1173
+
1174
+ # 5. Claims Completion Analysis
1175
+ claims_data = SQLQueries.get_claims_completion_percentages()
1176
+ if not claims_data.empty:
1177
+ colors = {'Completed': '#28a745', 'Pending': '#ffc107', 'Cancelled': '#dc3545'}
1178
+ fig = px.pie(claims_data,
1179
+ values='claim_count',
1180
+ names='status',
1181
+ title='πŸ“ˆ Claims Completion Status Analysis',
1182
+ hover_data=['percentage', 'food_impact_kg'],
1183
+ color='status',
1184
+ color_discrete_map=colors,
1185
+ hole=0.3)
1186
+ fig.update_traces(textposition='inside', textinfo='percent+label')
1187
+ charts['claims_analysis'] = fig
1188
+
1189
+ # 6. Meal Type Claims Analysis
1190
+ meal_data = SQLQueries.get_most_claimed_meal_types()
1191
+ if not meal_data.empty:
1192
+ fig = px.bar(meal_data,
1193
+ x='meal_type',
1194
+ y='total_claims',
1195
+ title='🍴 Most Claimed Meal Types',
1196
+ color='success_rate',
1197
+ hover_data=['total_quantity_distributed', 'demand_supply_ratio'],
1198
+ color_continuous_scale='Greens')
1199
+ fig.update_layout(
1200
+ plot_bgcolor='rgba(0,0,0,0)',
1201
+ paper_bgcolor='rgba(0,0,0,0)'
1202
+ )
1203
+ charts['meal_claims'] = fig
1204
+
1205
+ # 7. System Performance Overview
1206
+ system_data = SQLQueries.get_comprehensive_system_analysis()
1207
+ if not system_data.empty:
1208
+ # Create a metrics overview chart
1209
+ metrics = ['total_providers', 'total_receivers', 'total_food_items', 'successful_distributions']
1210
+ values = [system_data.iloc[0][metric] for metric in metrics]
1211
+ labels = ['Providers', 'Receivers', 'Food Items', 'Success Claims']
1212
+
1213
+ fig = px.bar(x=labels, y=values,
1214
+ title='πŸ“Š System Overview Metrics',
1215
+ color=values,
1216
+ color_continuous_scale='Spectral')
1217
+ fig.update_layout(
1218
+ plot_bgcolor='rgba(0,0,0,0)',
1219
+ paper_bgcolor='rgba(0,0,0,0)',
1220
+ xaxis_title='Metrics',
1221
+ yaxis_title='Count'
1222
+ )
1223
+ charts['system_overview'] = fig
1224
+
1225
+ except Exception as e:
1226
+ st.error(f"Error creating charts: {e}")
1227
+ charts['error'] = str(e)
1228
+
1229
+ return charts
1230
+
1231
+ # ========== NEW: TIME SERIES CHART FUNCTIONS ==========
1232
+ def create_time_series_charts():
1233
+ """Create time series trend charts"""
1234
+ charts = {}
1235
+ try:
1236
+ # 1. Claims Trends Over Time
1237
+ claims_trends = SQLQueries.get_time_series_claims_trends()
1238
+ if not claims_trends.empty:
1239
+ fig = go.Figure()
1240
+
1241
+ fig.add_trace(go.Scatter(
1242
+ x=claims_trends['claim_date'],
1243
+ y=claims_trends['total_claims'],
1244
+ mode='lines+markers',
1245
+ name='Total Claims',
1246
+ line=dict(color='#667eea', width=3),
1247
+ marker=dict(size=6)
1248
+ ))
1249
+
1250
+ fig.add_trace(go.Scatter(
1251
+ x=claims_trends['claim_date'],
1252
+ y=claims_trends['completed_claims'],
1253
+ mode='lines+markers',
1254
+ name='Completed Claims',
1255
+ line=dict(color='#28a745', width=2),
1256
+ marker=dict(size=4)
1257
+ ))
1258
+
1259
+ fig.update_layout(
1260
+ title='πŸ“ˆ Claims Trends Over Time',
1261
+ xaxis_title='Date',
1262
+ yaxis_title='Number of Claims',
1263
+ plot_bgcolor='rgba(0,0,0,0)',
1264
+ paper_bgcolor='rgba(0,0,0,0)',
1265
+ hovermode='x unified'
1266
+ )
1267
+ charts['claims_time_series'] = fig
1268
+
1269
+ # 2. Food Wastage Timeline
1270
+ food_trends = SQLQueries.get_time_series_food_listings_trends()
1271
+ if not food_trends.empty:
1272
+ fig = go.Figure()
1273
+
1274
+ fig.add_trace(go.Scatter(
1275
+ x=food_trends['expiry_date'],
1276
+ y=food_trends['quantity_expiring'],
1277
+ mode='lines+markers',
1278
+ name='Quantity Expiring',
1279
+ line=dict(color='#dc3545', width=3),
1280
+ fill='tonexty',
1281
+ fillcolor='rgba(220, 53, 69, 0.1)'
1282
+ ))
1283
+
1284
+ fig.add_trace(go.Scatter(
1285
+ x=food_trends['expiry_date'],
1286
+ y=food_trends['quantity_saved'],
1287
+ mode='lines+markers',
1288
+ name='Quantity Saved',
1289
+ line=dict(color='#28a745', width=3),
1290
+ fill='tozeroy',
1291
+ fillcolor='rgba(40, 167, 69, 0.2)'
1292
+ ))
1293
+
1294
+ fig.update_layout(
1295
+ title='πŸ—‘οΈ Food Wastage vs Savings Timeline',
1296
+ xaxis_title='Expiry Date',
1297
+ yaxis_title='Quantity (kg)',
1298
+ plot_bgcolor='rgba(0,0,0,0)',
1299
+ paper_bgcolor='rgba(0,0,0,0)',
1300
+ hovermode='x unified'
1301
+ )
1302
+ charts['wastage_timeline'] = fig
1303
+
1304
+ # 3. Monthly Performance Trends
1305
+ monthly_data = SQLQueries.get_monthly_performance_trends()
1306
+ if not monthly_data.empty:
1307
+ fig = go.Figure()
1308
+
1309
+ # Success rate line
1310
+ fig.add_trace(go.Scatter(
1311
+ x=monthly_data['month'],
1312
+ y=monthly_data['monthly_success_rate'],
1313
+ mode='lines+markers',
1314
+ name='Success Rate (%)',
1315
+ line=dict(color='#667eea', width=3),
1316
+ marker=dict(size=8),
1317
+ yaxis='y2'
1318
+ ))
1319
+
1320
+ # Claims bar chart
1321
+ fig.add_trace(go.Bar(
1322
+ x=monthly_data['month'],
1323
+ y=monthly_data['total_claims'],
1324
+ name='Total Claims',
1325
+ marker_color='rgba(102, 126, 234, 0.6)',
1326
+ yaxis='y'
1327
+ ))
1328
+
1329
+ # Growth rate
1330
+ fig.add_trace(go.Scatter(
1331
+ x=monthly_data['month'],
1332
+ y=monthly_data['claims_growth_rate'],
1333
+ mode='lines+markers',
1334
+ name='Growth Rate (%)',
1335
+ line=dict(color='#ffc107', width=2, dash='dash'),
1336
+ marker=dict(size=6),
1337
+ yaxis='y2'
1338
+ ))
1339
+
1340
+ fig.update_layout(
1341
+ title='πŸ“Š Monthly Performance & Growth Trends',
1342
+ xaxis_title='Month',
1343
+ yaxis=dict(title='Number of Claims', side='left'),
1344
+ yaxis2=dict(title='Percentage', side='right', overlaying='y'),
1345
+ plot_bgcolor='rgba(0,0,0,0)',
1346
+ paper_bgcolor='rgba(0,0,0,0)',
1347
+ hovermode='x unified'
1348
+ )
1349
+ charts['monthly_trends'] = fig
1350
+
1351
+ except Exception as e:
1352
+ st.error(f"Error creating time series charts: {e}")
1353
+ charts['error'] = str(e)
1354
+
1355
+ return charts
1356
+
1357
+ # ========== MAIN HEADER ==========
1358
+ st.markdown("""
1359
+ <div class="main-header">
1360
+ <h1>🌍 Food Wastage Management System</h1>
1361
+ <p>Connecting food providers with those in need β€’ Reducing waste β€’ Building community</p>
1362
+ <p><strong>✨ NEW:</strong> Time Series Analysis | <strong>πŸ”§ FIXED:</strong> Text Visibility Issues</p>
1363
+ <p><strong>Features:</strong> 15+ SQL Queries | Advanced Analytics | Real-time Insights | Performance Tracking</p>
1364
+ </div>
1365
+ """, unsafe_allow_html=True)
1366
+
1367
+ # ========== SIDEBAR NAVIGATION (FIXED) ==========
1368
+ with st.sidebar:
1369
+ st.title("🧭 Navigation")
1370
+ current_page = st.selectbox(
1371
+ "Choose a page:",
1372
+ ["πŸ“Š Dashboard", "🏒 Providers", "🀝 Receivers", "πŸ₯— Food Listings", "πŸ“¦ Claims", "πŸ“ˆ Analytics", "⏰ Time Series"]
1373
+ )
1374
+
1375
+ # ========== MAIN CONTENT ROUTER (FIXED) ==========
1376
+ if current_page == "πŸ“Š Dashboard":
1377
+ st.header("πŸ“Š Dashboard Overview")
1378
+
1379
+ # Display key metrics
1380
+ col1, col2, col3, col4 = st.columns(4)
1381
+
1382
+ try:
1383
+ system_data = SQLQueries.get_total_food_quantity_available()
1384
+ if not system_data.empty:
1385
+ row = system_data.iloc[0]
1386
+
1387
+ with col1:
1388
+ st.metric("Total Food Items", f"{row['total_food_items']:,}")
1389
+ with col2:
1390
+ st.metric("Fresh Items", f"{row['fresh_items']:,}")
1391
+ with col3:
1392
+ st.metric("Total Providers", f"{row['contributing_providers']:,}")
1393
+ with col4:
1394
+ st.metric("Cities Covered", f"{row['cities_covered']:,}")
1395
+ except Exception as e:
1396
+ st.warning("Loading dashboard metrics...")
1397
+
1398
+ # Display charts
1399
+ st.subheader("πŸ“ˆ Analytics Overview")
1400
+ charts = create_project_required_charts()
1401
+
1402
+ for chart_name, chart in charts.items():
1403
+ if chart_name != 'error' and chart is not None:
1404
+ try:
1405
+ st.plotly_chart(chart, use_container_width=True)
1406
+ except Exception as e:
1407
+ st.error(f"Error displaying chart {chart_name}: {e}")
1408
+
1409
+ elif current_page == "🏒 Providers":
1410
+ st.header("🏒 Food Providers Management")
1411
+
1412
+ # Add new provider section
1413
+ with st.expander("βž• Add New Provider"):
1414
+ col1, col2 = st.columns(2)
1415
+ with col1:
1416
+ provider_name = st.text_input("Provider Name")
1417
+ provider_type = st.selectbox("Provider Type",
1418
+ ["Restaurant", "Grocery Store", "Hotel", "Supermarket", "Bakery", "Other"])
1419
+ city = st.text_input("City")
1420
+ with col2:
1421
+ contact = st.text_input("Contact Information")
1422
+ address = st.text_area("Address (Optional)")
1423
+
1424
+ if st.button("Add Provider"):
1425
+ if provider_name and provider_type and city and contact:
1426
+ success, message = CRUDOperations.add_provider(provider_name, provider_type, city, contact, address)
1427
+ if success:
1428
+ st.success(message)
1429
+ st.rerun()
1430
+ else:
1431
+ st.error(message)
1432
+ else:
1433
+ st.error("Please fill in all required fields")
1434
+
1435
+ # Display providers table
1436
+ st.subheader("πŸ“‹ Current Providers")
1437
+ try:
1438
+ providers_df = SQLQueries.get_provider_contacts_by_city()
1439
+ if not providers_df.empty:
1440
+ st.dataframe(providers_df, use_container_width=True)
1441
+
1442
+ # Display provider statistics
1443
+ st.subheader("πŸ“Š Provider Statistics")
1444
+ col1, col2, col3 = st.columns(3)
1445
+ with col1:
1446
+ st.metric("Total Providers", len(providers_df))
1447
+ with col2:
1448
+ active_providers = len(providers_df[providers_df['status'] == '🟒 Active'])
1449
+ st.metric("Active Providers", active_providers)
1450
+ with col3:
1451
+ total_listings = providers_df['active_food_listings'].sum()
1452
+ st.metric("Total Food Listings", total_listings)
1453
+ else:
1454
+ st.info("No provider data available. Add some providers to get started!")
1455
+ except Exception as e:
1456
+ st.error(f"Error loading providers: {e}")
1457
+
1458
+ elif current_page == "🀝 Receivers":
1459
+ st.header("🀝 Food Receivers Management")
1460
+
1461
+ # Add new receiver section
1462
+ with st.expander("βž• Add New Receiver"):
1463
+ col1, col2 = st.columns(2)
1464
+ with col1:
1465
+ receiver_name = st.text_input("Receiver Name")
1466
+ receiver_type = st.selectbox("Receiver Type",
1467
+ ["NGO", "Food Bank", "Shelter", "Charity", "Community Center", "Other"])
1468
+ with col2:
1469
+ city = st.text_input("City")
1470
+ contact = st.text_input("Contact Information")
1471
+
1472
+ if st.button("Add Receiver"):
1473
+ if receiver_name and receiver_type and city and contact:
1474
+ success, message = CRUDOperations.add_receiver(receiver_name, receiver_type, city, contact)
1475
+ if success:
1476
+ st.success(message)
1477
+ st.rerun()
1478
+ else:
1479
+ st.error(message)
1480
+ else:
1481
+ st.error("Please fill in all required fields")
1482
+
1483
+ # Display receivers table
1484
+ st.subheader("πŸ“‹ Current Receivers")
1485
+ try:
1486
+ receivers_query = "SELECT * FROM receivers ORDER BY receiver_id"
1487
+ receivers_df = SQLQueries.execute_query(receivers_query)
1488
+ if not receivers_df.empty:
1489
+ st.dataframe(receivers_df, use_container_width=True)
1490
+
1491
+ # Display receiver statistics
1492
+ st.subheader("πŸ“Š Receiver Statistics")
1493
+ col1, col2, col3 = st.columns(3)
1494
+ with col1:
1495
+ st.metric("Total Receivers", len(receivers_df))
1496
+ with col2:
1497
+ receiver_types = receivers_df['type'].nunique()
1498
+ st.metric("Receiver Types", receiver_types)
1499
+ with col3:
1500
+ cities = receivers_df['city'].nunique()
1501
+ st.metric("Cities Served", cities)
1502
+
1503
+ # Show top receivers
1504
+ st.subheader("πŸ† Top Performing Receivers")
1505
+ top_receivers = SQLQueries.get_top_claiming_receivers()
1506
+ if not top_receivers.empty:
1507
+ st.dataframe(top_receivers.head(10), use_container_width=True)
1508
+ else:
1509
+ st.info("No receiver data available. Add some receivers to get started!")
1510
+ except Exception as e:
1511
+ st.error(f"Error loading receivers: {e}")
1512
+
1513
+ elif current_page == "πŸ₯— Food Listings":
1514
+ st.header("πŸ₯— Food Listings Management")
1515
+
1516
+ # Add new food listing section
1517
+ with st.expander("βž• Add New Food Listing"):
1518
+ col1, col2 = st.columns(2)
1519
+ with col1:
1520
+ food_name = st.text_input("Food Name")
1521
+ quantity = st.number_input("Quantity (kg)", min_value=0.1, step=0.1)
1522
+ expiry_date = st.date_input("Expiry Date", min_value=datetime.now().date())
1523
+ with col2:
1524
+ # Get provider options
1525
+ try:
1526
+ providers_query = "SELECT provider_id, name FROM providers ORDER BY name"
1527
+ providers_df = SQLQueries.execute_query(providers_query)
1528
+ if not providers_df.empty:
1529
+ provider_options = {f"{row['name']} (ID: {row['provider_id']})": row['provider_id']
1530
+ for _, row in providers_df.iterrows()}
1531
+ selected_provider = st.selectbox("Provider", options=list(provider_options.keys()))
1532
+ provider_id = provider_options[selected_provider] if selected_provider else None
1533
+ else:
1534
+ st.warning("No providers available. Add providers first.")
1535
+ provider_id = None
1536
+ except:
1537
+ st.error("Error loading providers")
1538
+ provider_id = None
1539
+
1540
+ food_type = st.selectbox("Food Type",
1541
+ ["Vegetables", "Fruits", "Dairy", "Meat", "Grains", "Bakery", "Prepared Meals", "Other"])
1542
+ meal_type = st.selectbox("Meal Type",
1543
+ ["Breakfast", "Lunch", "Dinner", "Snacks", "Beverages", "Other"])
1544
+
1545
+ if st.button("Add Food Listing"):
1546
+ if food_name and quantity and expiry_date and provider_id and food_type and meal_type:
1547
+ success, message = CRUDOperations.add_food_listing(food_name, quantity, expiry_date,
1548
+ provider_id, food_type, meal_type)
1549
+ if success:
1550
+ st.success(message)
1551
+ st.rerun()
1552
+ else:
1553
+ st.error(message)
1554
+ else:
1555
+ st.error("Please fill in all required fields")
1556
+
1557
+ # Display food listings
1558
+ st.subheader("πŸ“‹ Current Food Listings")
1559
+ try:
1560
+ food_listings = SQLQueries.get_claims_per_food_item()
1561
+ if not food_listings.empty:
1562
+ st.dataframe(food_listings, use_container_width=True)
1563
+
1564
+ # Display food statistics
1565
+ st.subheader("πŸ“Š Food Listing Statistics")
1566
+ col1, col2, col3, col4 = st.columns(4)
1567
+ with col1:
1568
+ st.metric("Total Listings", len(food_listings))
1569
+ with col2:
1570
+ total_quantity = food_listings['quantity'].sum()
1571
+ st.metric("Total Quantity (kg)", f"{total_quantity:,.1f}")
1572
+ with col3:
1573
+ food_types = food_listings['food_type'].nunique()
1574
+ st.metric("Food Types", food_types)
1575
+ with col4:
1576
+ urgent_items = len(food_listings[food_listings['item_status'] == '🟠 Urgent'])
1577
+ st.metric("Urgent Items", urgent_items)
1578
+ else:
1579
+ st.info("No food listings available. Add some food listings to get started!")
1580
+ except Exception as e:
1581
+ st.error(f"Error loading food listings: {e}")
1582
+
1583
+ elif current_page == "πŸ“¦ Claims":
1584
+ st.header("πŸ“¦ Food Claims Management")
1585
+
1586
+ # Add new claim section
1587
+ with st.expander("βž• Add New Claim"):
1588
+ col1, col2 = st.columns(2)
1589
+ with col1:
1590
+ # Get food options
1591
+ try:
1592
+ food_query = "SELECT food_id, food_name FROM food_listings ORDER BY food_name"
1593
+ food_df = SQLQueries.execute_query(food_query)
1594
+ if not food_df.empty:
1595
+ food_options = {f"{row['food_name']} (ID: {row['food_id']})": row['food_id']
1596
+ for _, row in food_df.iterrows()}
1597
+ selected_food = st.selectbox("Food Item", options=list(food_options.keys()))
1598
+ food_id = food_options[selected_food] if selected_food else None
1599
+ else:
1600
+ st.warning("No food items available.")
1601
+ food_id = None
1602
+ except:
1603
+ st.error("Error loading food items")
1604
+ food_id = None
1605
+
1606
+ with col2:
1607
+ # Get receiver options
1608
+ try:
1609
+ receivers_query = "SELECT receiver_id, name FROM receivers ORDER BY name"
1610
+ receivers_df = SQLQueries.execute_query(receivers_query)
1611
+ if not receivers_df.empty:
1612
+ receiver_options = {f"{row['name']} (ID: {row['receiver_id']})": row['receiver_id']
1613
+ for _, row in receivers_df.iterrows()}
1614
+ selected_receiver = st.selectbox("Receiver", options=list(receiver_options.keys()))
1615
+ receiver_id = receiver_options[selected_receiver] if selected_receiver else None
1616
+ else:
1617
+ st.warning("No receivers available.")
1618
+ receiver_id = None
1619
+ except:
1620
+ st.error("Error loading receivers")
1621
+ receiver_id = None
1622
+
1623
+ claim_status = st.selectbox("Status", ["Pending", "Completed", "Cancelled"])
1624
+
1625
+ if st.button("Add Claim"):
1626
+ if food_id and receiver_id:
1627
+ success, message = CRUDOperations.add_claim(food_id, receiver_id, claim_status)
1628
+ if success:
1629
+ st.success(message)
1630
+ st.rerun()
1631
+ else:
1632
+ st.error(message)
1633
+ else:
1634
+ st.error("Please select both food item and receiver")
1635
+
1636
+ # Display claims table
1637
+ st.subheader("πŸ“‹ Current Claims")
1638
+ try:
1639
+ claims_query = """
1640
+ SELECT
1641
+ c.claim_id,
1642
+ f.food_name,
1643
+ f.food_type,
1644
+ f.quantity,
1645
+ p.name as provider_name,
1646
+ r.name as receiver_name,
1647
+ c.status,
1648
+ c.timestamp
1649
+ FROM claims c
1650
+ JOIN food_listings f ON c.food_id = f.food_id
1651
+ JOIN providers p ON f.provider_id = p.provider_id
1652
+ LEFT JOIN receivers r ON c.receiver_id = r.receiver_id
1653
+ ORDER BY c.timestamp DESC
1654
+ """
1655
+ claims_df = SQLQueries.execute_query(claims_query)
1656
+
1657
+ if not claims_df.empty:
1658
+ st.dataframe(claims_df, use_container_width=True)
1659
+
1660
+ # Display claims statistics
1661
+ st.subheader("πŸ“Š Claims Statistics")
1662
+ claims_stats = SQLQueries.get_claims_completion_percentages()
1663
+ if not claims_stats.empty:
1664
+ col1, col2, col3, col4 = st.columns(4)
1665
+ for i, (_, row) in enumerate(claims_stats.iterrows()):
1666
+ if i < 4: # Only show first 4 statuses
1667
+ with [col1, col2, col3, col4][i]:
1668
+ st.metric(f"{row['status']} Claims",
1669
+ f"{row['claim_count']} ({row['percentage']:.1f}%)")
1670
+
1671
+ # Show detailed claims analysis
1672
+ st.subheader("πŸ“ˆ Detailed Claims Analysis")
1673
+ st.dataframe(claims_stats, use_container_width=True)
1674
+ else:
1675
+ st.info("No claims data available.")
1676
+ except Exception as e:
1677
+ st.error(f"Error loading claims: {e}")
1678
+
1679
+ elif current_page == "πŸ“ˆ Analytics":
1680
+ st.header("πŸ“ˆ Advanced Analytics")
1681
+
1682
+ # Analytics tabs
1683
+ tab1, tab2, tab3, tab4 = st.tabs(["🏒 Provider Analytics", "🀝 Receiver Analytics", "🍽️ Food Analytics", "🌍 City Analytics"])
1684
+
1685
+ with tab1:
1686
+ st.subheader("Provider Performance Analysis")
1687
+
1688
+ # Top providers by successful claims
1689
+ top_providers = SQLQueries.get_provider_highest_successful_claims()
1690
+ if not top_providers.empty:
1691
+ st.dataframe(top_providers.head(10), use_container_width=True)
1692
+
1693
+ # Total donations per provider
1694
+ donations_data = SQLQueries.get_total_donations_per_provider()
1695
+ if not donations_data.empty:
1696
+ st.subheader("Provider Donation Analysis")
1697
+ st.dataframe(donations_data.head(10), use_container_width=True)
1698
+
1699
+ with tab2:
1700
+ st.subheader("Receiver Performance Analysis")
1701
+
1702
+ # Average quantity per receiver
1703
+ avg_quantity_data = SQLQueries.get_avg_quantity_per_receiver()
1704
+ if not avg_quantity_data.empty:
1705
+ st.dataframe(avg_quantity_data.head(10), use_container_width=True)
1706
+
1707
+ # Top claiming receivers
1708
+ top_receivers = SQLQueries.get_top_claiming_receivers()
1709
+ if not top_receivers.empty:
1710
+ st.subheader("Top Claiming Receivers")
1711
+ st.dataframe(top_receivers.head(10), use_container_width=True)
1712
+
1713
+ with tab3:
1714
+ st.subheader("Food Type Analysis")
1715
+
1716
+ # Most common food types
1717
+ food_types = SQLQueries.get_most_common_food_types()
1718
+ if not food_types.empty:
1719
+ st.dataframe(food_types, use_container_width=True)
1720
+
1721
+ # Most claimed meal types
1722
+ meal_types = SQLQueries.get_most_claimed_meal_types()
1723
+ if not meal_types.empty:
1724
+ st.subheader("Meal Type Demand Analysis")
1725
+ st.dataframe(meal_types, use_container_width=True)
1726
+
1727
+ with tab4:
1728
+ st.subheader("City-wise Analysis")
1729
+
1730
+ # Providers and receivers per city
1731
+ city_data = SQLQueries.get_providers_receivers_per_city()
1732
+ if not city_data.empty:
1733
+ st.dataframe(city_data, use_container_width=True)
1734
+
1735
+ # Cities by food listings
1736
+ city_listings = SQLQueries.get_cities_by_food_listings()
1737
+ if not city_listings.empty:
1738
+ st.subheader("Cities by Food Availability")
1739
+ st.dataframe(city_listings, use_container_width=True)
1740
+
1741
+ elif current_page == "⏰ Time Series":
1742
+ st.header("⏰ Time Series Analysis")
1743
+
1744
+ # Time series charts
1745
+ time_charts = create_time_series_charts()
1746
+
1747
+ for chart_name, chart in time_charts.items():
1748
+ if chart_name != 'error' and chart is not None:
1749
+ try:
1750
+ st.plotly_chart(chart, use_container_width=True)
1751
+ except Exception as e:
1752
+ st.error(f"Error displaying chart {chart_name}: {e}")
1753
+
1754
+ # Time series data tables
1755
+ st.subheader("πŸ“Š Time Series Data")
1756
+
1757
+ tab1, tab2, tab3 = st.tabs(["πŸ“ˆ Claims Trends", "πŸ—‘οΈ Wastage Trends", "πŸ“… Monthly Performance"])
1758
+
1759
+ with tab1:
1760
+ claims_trends = SQLQueries.get_time_series_claims_trends()
1761
+ if not claims_trends.empty:
1762
+ st.dataframe(claims_trends, use_container_width=True)
1763
+
1764
+ with tab2:
1765
+ food_trends = SQLQueries.get_time_series_food_listings_trends()
1766
+ if not food_trends.empty:
1767
+ st.dataframe(food_trends, use_container_width=True)
1768
+
1769
+ with tab3:
1770
+ monthly_trends = SQLQueries.get_monthly_performance_trends()
1771
+ if not monthly_trends.empty:
1772
+ st.dataframe(monthly_trends, use_container_width=True)
1773
+
1774
+ # ========== FOOTER ==========
1775
+ st.markdown("---")
1776
+ st.markdown("""
1777
+ <div style='text-align: center; color: #666;'>
1778
+ 🌍 Food Wastage Management System - Complete Edition | Built with ❀️ using Streamlit<br>
1779
+ Reducing food waste β€’ Building communities β€’ Making a difference
1780
+ </div>
1781
+ """, unsafe_allow_html=True)