-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
1563 lines (1304 loc) · 60.3 KB
/
app.py
File metadata and controls
1563 lines (1304 loc) · 60.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, render_template, request, redirect, url_for, session, jsonify, flash
import json
import os
from datetime import datetime, timedelta
import random
import hashlib
from functools import wraps
# app declaration
app = Flask(__name__)
app.secret_key = 'your_secret_key' # Change this to a secure random key in production
# Load data
def load_data(filename):
with open(filename, 'r') as f:
return json.load(f)
def save_data(data, filename):
# Determine the correct path based on the filename
if filename in ['products.json', 'locations.json']:
filepath = f'../{filename}'
else:
filepath = filename
with open(filepath, 'w') as f:
json.dump(data, f, indent=2)
# Load initial data
products_data = load_data('../products.json')
locations_data = load_data('../locations.json')
users_data = load_data('users.json')
order_history = load_data('order_history.json')
# Authentication decorators
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
return redirect(url_for('login', next=request.url))
return f(*args, **kwargs)
return decorated_function
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
return redirect(url_for('admin_login'))
# Check if user is admin
user = next((u for u in users_data['users'] if u['id'] == session['user_id']), None)
if not user or not user.get('is_admin', False):
return redirect(url_for('admin_login'))
return f(*args, **kwargs)
return decorated_function
# Helper functions
def get_user_by_id(user_id):
return next((u for u in users_data['users'] if u['id'] == user_id), None)
def get_user_by_email(email):
return next((u for u in users_data['users'] if u['email'] == email), None)
def get_product_by_id(product_id):
for category in products_data['categories']:
for product in category['products']:
if product['id'] == product_id:
return product
return None
def get_category_by_id(category_id):
return next((c for c in products_data['categories'] if c['id'] == category_id), None)
def get_city_by_id(city_id):
return next((c for c in locations_data['cities'] if c['id'] == city_id), None)
def get_district_by_id(city_id, district_id):
city = get_city_by_id(city_id)
if city:
return next((d for d in city['districts'] if d['id'] == district_id), None)
return None
def get_location_info():
if 'city_id' in session and 'district_id' in session:
city = get_city_by_id(session['city_id'])
district = get_district_by_id(session['city_id'], session['district_id'])
if city and district:
return {'city': city, 'district': district}
return None
def calculate_price_with_location(base_price, location):
if location:
return round(base_price * location['district']['price_factor'])
return base_price
def predict_price(product_id, location):
"""
Predict price based on previous 10 days of orders for a specific product and location
"""
if not location:
return None
# Load price history data
try:
with open('data/price_history.json', 'r') as f:
price_history = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
# If file doesn't exist or is invalid, initialize with empty data
price_history = {'history': []}
# Create a unique key for product and location combination
location_key = f"{location['city']['id']}_{location['district']['id']}"
product_location_key = f"{product_id}_{location_key}"
# Get product base price
product = get_product_by_id(product_id)
if not product:
return None
base_price = product['price']
current_price = round(base_price * location['district']['price_factor'])
# Filter price history for this product and location
product_history = [
entry for entry in price_history['history']
if entry['product_id'] == product_id and entry['location_key'] == location_key
]
# Sort by date (newest first)
product_history.sort(key=lambda x: x['date'], reverse=True)
# If we have less than 3 data points, return current price with location factor
if len(product_history) < 3:
return {
'current_price': current_price,
'predicted_price': current_price,
'confidence': 80, # Default confidence
'history': []
}
# Use up to last 10 days of data for prediction
recent_history = product_history[:10]
# Calculate average price and trend
prices = [entry['price'] for entry in recent_history]
avg_price = sum(prices) / len(prices)
# Simple trend analysis: positive if prices are generally increasing
trend = sum(prices[:3]) / 3 - sum(prices[-3:]) / 3
# Calculate predicted price with a small adjustment based on trend
trend_factor = 0.02 # How much to adjust for trend
predicted_price = avg_price * (1 + trend_factor * trend)
# Make sure prediction is reasonable (within ±15% of current price)
predicted_price = max(current_price * 0.85, min(current_price * 1.15, predicted_price))
predicted_price = round(predicted_price)
# Calculate confidence based on amount of data and volatility
data_points = len(recent_history)
volatility = sum([abs(prices[i] - prices[i-1]) for i in range(1, len(prices))]) / (len(prices) - 1)
volatility_factor = volatility / avg_price
confidence = round(min(95, max(50, 90 - volatility_factor * 100 + (data_points - 3) * 2)))
# Format recent history for display
formatted_history = []
for entry in recent_history:
date_obj = datetime.strptime(entry['date'], '%Y-%m-%d')
formatted_history.append({
'date': date_obj.strftime('%b %d'),
'price': entry['price']
})
return {
'current_price': current_price,
'predicted_price': predicted_price,
'confidence': confidence,
'history': formatted_history
}
def initialize_price_history():
"""
Create initial price history data for the past 10 days (if it doesn't exist)
"""
# Check if price history file already exists
if os.path.exists('data/price_history.json'):
return
today = datetime.now()
history_entries = []
# For each product in each location, create 10 days of price history
for category in products_data['categories']:
for product in category['products']:
product_id = product['id']
base_price = product['price']
for city in locations_data['cities']:
for district in city['districts']:
location_key = f"{city['id']}_{district['id']}"
# Calculate base price with location factor
location_price = round(base_price * district['price_factor'])
# Create 10 days of slightly varying prices
for day_offset in range(10, 0, -1):
date = (today - timedelta(days=day_offset)).strftime('%Y-%m-%d')
# Random variation between -5% and +5%
variation = 0.95 + (random.random() * 0.1)
price = round(location_price * variation)
history_entries.append({
'product_id': product_id,
'location_key': location_key,
'date': date,
'price': price
})
# Save the price history
price_history = {'history': history_entries}
with open('data/price_history.json', 'w') as f:
json.dump(price_history, f, indent=2)
print(f"Created initial price history with {len(history_entries)} entries")
def update_daily_price_history():
"""
Update price history with today's prices for all products in all locations
"""
today = datetime.now().strftime('%Y-%m-%d')
# Load existing price history
try:
with open('data/price_history.json', 'r') as f:
price_history = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
price_history = {'history': []}
# Check if we already have entries for today
today_entries = [
entry for entry in price_history['history']
if entry['date'] == today
]
if today_entries:
print(f"Price history for {today} already exists ({len(today_entries)} entries)")
return
# Add today's prices for all products in all locations
new_entries = []
for category in products_data['categories']:
for product in category['products']:
product_id = product['id']
base_price = product['price']
for city in locations_data['cities']:
for district in city['districts']:
location_key = f"{city['id']}_{district['id']}"
# Calculate price with location factor
price = round(base_price * district['price_factor'])
# Add a small random variation (-2% to +2%)
variation = 0.98 + (random.random() * 0.04)
price = round(price * variation)
new_entries.append({
'product_id': product_id,
'location_key': location_key,
'date': today,
'price': price
})
# Add new entries to history
price_history['history'].extend(new_entries)
# Optionally, limit history size to keep only recent data (e.g., last 30 days)
if len(price_history['history']) > 100000: # Arbitrary limit
# Sort by date (oldest first)
price_history['history'].sort(key=lambda x: x['date'])
# Keep only the most recent entries
price_history['history'] = price_history['history'][-100000:]
# Save updated price history
with open('data/price_history.json', 'w') as f:
json.dump(price_history, f, indent=2)
print(f"Added {len(new_entries)} price history entries for {today}")
# Initialize app data
def init_app_data():
# Create data directory if it doesn't exist
os.makedirs('data', exist_ok=True)
# Initialize price history data if needed
initialize_price_history()
# Update today's price history
update_daily_price_history()
# Call initialization when app starts
init_app_data()
# Routes
@app.route('/')
def index():
location = get_location_info()
# Apply location-based pricing to products
categories = []
for category in products_data['categories']:
category_copy = category.copy()
products_copy = []
for product in category['products']:
product_copy = product.copy()
product_copy['original_price'] = product['price']
product_copy['price'] = calculate_price_with_location(product['price'], location)
products_copy.append(product_copy)
category_copy['products'] = products_copy
categories.append(category_copy)
return render_template('index.html',
categories=categories,
location=location,
user_logged_in='user_id' in session,
user=get_user_by_id(session.get('user_id')))
@app.route('/category/<int:category_id>')
def category(category_id):
category = get_category_by_id(category_id)
location = get_location_info()
if not category:
return redirect(url_for('index'))
# Apply location-based pricing to products
category_copy = category.copy()
products_copy = []
for product in category['products']:
product_copy = product.copy()
product_copy['original_price'] = product['price']
product_copy['price'] = calculate_price_with_location(product['price'], location)
products_copy.append(product_copy)
category_copy['products'] = products_copy
return render_template('category.html',
category=category_copy,
location=location,
user_logged_in='user_id' in session,
user=get_user_by_id(session.get('user_id')))
@app.route('/product/<int:product_id>')
def product_detail(product_id):
product = get_product_by_id(product_id)
location = get_location_info()
if not product:
return redirect(url_for('index'))
# Apply location-based pricing
product_copy = product.copy()
product_copy['original_price'] = product['price']
product_copy['price'] = calculate_price_with_location(product['price'], location)
# Get price prediction
predicted_price = predict_price(product_id, location)
return render_template('product.html',
product=product_copy,
location=location,
predicted_price=predicted_price,
user_logged_in='user_id' in session,
user=get_user_by_id(session.get('user_id')))
@app.route('/location')
def location_selection():
current_city_id = session.get('city_id', 1)
current_district_id = session.get('district_id', 101)
return render_template('location.html',
locations=locations_data,
current_city_id=current_city_id,
current_district_id=current_district_id,
location=get_location_info(),
user_logged_in='user_id' in session,
user=get_user_by_id(session.get('user_id')))
@app.route('/update-location', methods=['POST'])
def update_location():
city_id = int(request.form.get('city_id', 1))
district_id = int(request.form.get('district_id', 101))
redirect_url = request.form.get('redirect_url', url_for('index'))
session['city_id'] = city_id
session['district_id'] = district_id
return redirect(redirect_url)
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
email = request.form.get('email')
password = request.form.get('password')
# Simple password hashing (use a proper hashing library in production)
password_hash = hashlib.md5(password.encode()).hexdigest()
user = get_user_by_email(email)
if user and user['password_hash'] == password_hash:
session['user_id'] = user['id']
return redirect(url_for('index'))
return render_template('login.html',
error='Invalid email or password',
email=email,
location=get_location_info(),
user_logged_in='user_id' in session,
user=get_user_by_id(session.get('user_id')))
return render_template('login.html',
location=get_location_info(),
user_logged_in='user_id' in session,
user=get_user_by_id(session.get('user_id')))
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
first_name = request.form.get('first_name')
last_name = request.form.get('last_name')
email = request.form.get('email')
phone = request.form.get('phone')
password = request.form.get('password')
confirm_password = request.form.get('confirm_password')
# Create form data to pass back in case of error
form_data = {
'first_name': first_name,
'last_name': last_name,
'email': email,
'phone': phone
}
# Validation
if password != confirm_password:
return render_template('register.html',
error='Passwords do not match',
form_data=form_data,
location=get_location_info(),
user_logged_in='user_id' in session,
user=get_user_by_id(session.get('user_id')))
if get_user_by_email(email):
return render_template('register.html',
error='Email already registered',
form_data=form_data,
location=get_location_info(),
user_logged_in='user_id' in session,
user=get_user_by_id(session.get('user_id')))
# Create new user
new_user = {
'id': max(u['id'] for u in users_data['users']) + 1,
'first_name': first_name,
'last_name': last_name,
'email': email,
'phone': phone,
'password_hash': hashlib.md5(password.encode()).hexdigest(),
'address': '',
'city_id': session.get('city_id', 1),
'district_id': session.get('district_id', 101),
'pincode': '',
'joined_date': datetime.now().strftime('%Y-%m-%d'),
'is_admin': False
}
users_data['users'].append(new_user)
save_data(users_data, 'users.json')
# Log in the new user
session['user_id'] = new_user['id']
return redirect(url_for('index'))
return render_template('register.html',
form_data={},
location=get_location_info(),
user_logged_in='user_id' in session,
user=get_user_by_id(session.get('user_id')))
@app.route('/logout')
def logout():
session.pop('user_id', None)
return redirect(url_for('index'))
@app.route('/add-to-cart', methods=['POST'])
@login_required
def add_to_cart():
product_id = int(request.form.get('product_id'))
quantity = int(request.form.get('quantity', 1))
if 'cart' not in session:
session['cart'] = []
cart = session['cart']
# Check if product already in cart
for item in cart:
if item['product_id'] == product_id:
item['quantity'] += quantity
session['cart'] = cart
return redirect(request.referrer or url_for('index'))
# Add new item to cart
cart.append({
'product_id': product_id,
'quantity': quantity
})
session['cart'] = cart
return redirect(request.referrer or url_for('index'))
@app.route('/update-cart', methods=['POST'])
@login_required
def update_cart():
try:
product_id = int(request.form.get('product_id'))
quantity = int(request.form.get('quantity', 0))
except ValueError:
# Handle invalid input
return redirect(url_for('cart'))
if quantity < 0:
quantity = 0 # Ensure quantity is not negative
if 'cart' not in session:
return redirect(url_for('cart'))
cart = session['cart']
if quantity == 0:
# Remove item from cart
cart = [item for item in cart if item['product_id'] != product_id]
else:
# Update quantity
item_found = False
for item in cart:
if item['product_id'] == product_id:
item['quantity'] = quantity
item_found = True
break
# If item not found but quantity > 0, add it
if not item_found and quantity > 0:
cart.append({
'product_id': product_id,
'quantity': quantity
})
session['cart'] = cart
return redirect(url_for('cart'))
@app.route('/cart')
def cart():
location = get_location_info()
cart_items = []
total = 0
original_total = 0
if 'cart' in session:
for item in session['cart']:
product = get_product_by_id(item['product_id'])
if product:
price = calculate_price_with_location(product['price'], location)
subtotal = price * item['quantity']
original = product['price'] * item['quantity']
cart_items.append({
'id': product['id'],
'name': product['name'],
'image': product['image'],
'unit': product['unit'],
'price': price,
'quantity': item['quantity'],
'subtotal': subtotal,
'original': original
})
total += subtotal
original_total += original
return render_template('cart.html',
cart_items=cart_items,
total=total,
original_total=original_total,
location=location,
user_logged_in='user_id' in session,
user=get_user_by_id(session.get('user_id')))
@app.route('/clear-cart')
def clear_cart():
session.pop('cart', None)
return redirect(url_for('cart'))
@app.route('/checkout', methods=['GET', 'POST'])
@login_required
def checkout():
user = get_user_by_id(session['user_id'])
location = get_location_info()
if not location:
flash('Please select a delivery location', 'error')
return redirect(url_for('location_selection', redirect_url=url_for('checkout')))
if 'cart' not in session or not session['cart']:
flash('Your cart is empty', 'error')
return redirect(url_for('cart'))
# Calculate total and prepare cart items
cart_items = []
total = 0
for item in session['cart']:
product = get_product_by_id(item['product_id'])
if product:
price = calculate_price_with_location(product['price'], location)
subtotal = price * item['quantity']
cart_items.append({
'id': product['id'],
'name': product['name'],
'image': product['image'],
'unit': product['unit'],
'price': price,
'quantity': item['quantity'],
'subtotal': subtotal
})
total += subtotal
if request.method == 'POST':
# Create a new order
order_id = max(order['id'] for order in order_history['orders']) + 1 if order_history['orders'] else 1
new_order = {
'id': order_id,
'user_id': user['id'],
'date': datetime.now().strftime('%Y-%m-%d'),
'location': {
'city_id': location['city']['id'],
'district_id': location['district']['id']
},
'items': [],
'total': total,
'status': 'pending',
'payment_method': request.form.get('payment_method', 'cod')
}
# Add items to order
for item in cart_items:
new_order['items'].append({
'product_id': item['id'],
'name': item['name'],
'price': item['price'],
'quantity': item['quantity'],
'subtotal': item['subtotal']
})
# Update inventory (if implemented)
# update_inventory(item['id'], location['city']['id'], location['district']['id'], -item['quantity'])
# Add order to history
order_history['orders'].append(new_order)
save_data(order_history, 'order_history.json')
# Clear cart
session.pop('cart', None)
# Redirect to order confirmation
flash('Order placed successfully!', 'success')
return redirect(url_for('index'))
return render_template('checkout.html',
total=total,
cart_items=cart_items,
user=user,
location=location,
user_logged_in=True)
@app.route('/api/cart_count')
def cart_count():
count = 0
if 'cart' in session:
for item in session['cart']:
count += item['quantity']
return jsonify({'count': count})
# Admin routes
@app.route('/admin/login', methods=['GET', 'POST'])
def admin_login():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
# Simple password hashing (use a proper hashing library in production)
password_hash = hashlib.md5(password.encode()).hexdigest()
# Find admin user
admin_user = next((u for u in users_data['users'] if u['email'] == username and u['is_admin']), None)
if admin_user and admin_user['password_hash'] == password_hash:
session['user_id'] = admin_user['id']
return redirect(url_for('admin_dashboard'))
return render_template('admin_login.html',
error='Invalid credentials',
username=username)
return render_template('admin_login.html')
@app.route('/admin/logout')
def admin_logout():
session.pop('user_id', None)
return redirect(url_for('admin_login'))
@app.route('/admin/dashboard')
@admin_required
def admin_dashboard():
admin_user = get_user_by_id(session['user_id'])
# Mock statistics for dashboard
stats = {
'total_orders': len(order_history['orders']),
'orders_today': random.randint(5, 20),
'total_revenue': sum(order['total'] for order in order_history['orders']),
'revenue_today': random.randint(1000, 5000),
'total_users': len(users_data['users']),
'new_users_today': random.randint(1, 10)
}
# Recent orders
recent_orders = []
for order in sorted(order_history['orders'], key=lambda x: x['date'], reverse=True)[:5]:
user = get_user_by_id(order['user_id'])
recent_orders.append({
'id': order['id'],
'user_name': f"{user['first_name']} {user['last_name']}",
'date': order['date'],
'amount': order['total']
})
# Price predictions
price_predictions = []
for i in range(5):
product = get_product_by_id(random.choice([101, 102, 201, 301]))
city = get_city_by_id(random.choice([1, 2, 3]))
district = random.choice(city['districts'])
location = {'city': city, 'district': district}
predicted_price = predict_price(product['id'], location)
current_price = calculate_price_with_location(product['price'], location)
price_predictions.append({
'name': product['name'],
'location': f"{city['name']}, {district['name']}",
'predicted_price': predicted_price or current_price,
'current_price': current_price
})
return render_template('admin_dashboard.html',
admin_user=admin_user,
stats=stats,
recent_orders=recent_orders,
price_predictions=price_predictions)
@app.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
user = get_user_by_id(session['user_id'])
if request.method == 'POST':
action = request.form.get('action')
if action == 'update_profile':
# Update user info
user['first_name'] = request.form.get('first_name')
user['last_name'] = request.form.get('last_name')
user['phone'] = request.form.get('phone')
user['address'] = request.form.get('address')
user['pincode'] = request.form.get('pincode')
# Update location if provided
if request.form.get('city_id') and request.form.get('district_id'):
user['city_id'] = int(request.form.get('city_id'))
user['district_id'] = int(request.form.get('district_id'))
# Save changes
save_data(users_data, 'users.json')
flash('Profile updated successfully', 'success')
elif action == 'change_password':
current_password = request.form.get('current_password')
new_password = request.form.get('new_password')
confirm_password = request.form.get('confirm_password')
# Verify current password
current_hash = hashlib.md5(current_password.encode()).hexdigest()
if user['password_hash'] != current_hash:
flash('Current password is incorrect', 'error')
elif new_password != confirm_password:
flash('New passwords do not match', 'error')
else:
# Update password
user['password_hash'] = hashlib.md5(new_password.encode()).hexdigest()
save_data(users_data, 'users.json')
flash('Password changed successfully', 'success')
return redirect(url_for('profile'))
return render_template('profile.html',
user=user,
location=get_location_info(),
locations=locations_data,
user_logged_in=True)
# Add this function to manage inventory
def update_inventory(product_id, city_id, district_id, quantity):
for category in products_data['categories']:
for product in category['products']:
if product['id'] == product_id:
if 'inventory' not in product:
product['inventory'] = {}
key = f"{city_id}_{district_id}"
product['inventory'][key] = quantity
save_data(products_data, 'products.json')
return True
return False
# Modify the admin_products route to include inventory management
@app.route('/admin/products', methods=['GET', 'POST'])
@admin_required
def admin_products():
admin_user = get_user_by_id(session['user_id'])
message = None
message_type = None
if request.method == 'POST':
action = request.form.get('action')
if action == 'add_product':
try:
# Get the highest existing product ID and add 1
max_id = 0
for category in products_data['categories']:
for product in category['products']:
if product['id'] > max_id:
max_id = product['id']
new_product = {
'id': max_id + 1,
'name': request.form.get('name'),
'price': float(request.form.get('price')),
'unit': request.form.get('unit'),
'image': request.form.get('image', '/placeholder.svg?height=200&width=200'),
'description': request.form.get('description', ''),
'inventory': {} # Initialize empty inventory
}
category_id = int(request.form.get('category_id'))
category_found = False
for category in products_data['categories']:
if category['id'] == category_id:
category['products'].append(new_product)
category_found = True
break
if not category_found:
message = f"Category ID {category_id} not found"
message_type = "error"
else:
save_data(products_data, 'products.json')
message = 'Product added successfully'
message_type = 'success'
except Exception as e:
message = f"Error adding product: {str(e)}"
message_type = "error"
elif action == 'edit_product':
try:
product_id = int(request.form.get('product_id'))
product_name = request.form.get('name')
product_price = float(request.form.get('price'))
product_unit = request.form.get('unit')
product_image = request.form.get('image')
product_description = request.form.get('description', '')
category_id = int(request.form.get('category_id'))
# Find the product to update
product_found = False
old_category_id = None
# First find the product and its current category
for category in products_data['categories']:
for i, product in enumerate(category['products']):
if product['id'] == product_id:
old_category_id = category['id']
if old_category_id == category_id:
# Update in the same category
product['name'] = product_name
product['price'] = product_price
product['unit'] = product_unit
product['image'] = product_image
product['description'] = product_description
product_found = True
else:
# Remove from current category to move to the new one
removed_product = category['products'].pop(i)
# Preserve inventory data
if 'inventory' in removed_product:
removed_product['inventory'] = removed_product['inventory']
break
if old_category_id:
break
# If product is being moved to a different category, add it to the new one
if old_category_id != category_id and old_category_id is not None:
for category in products_data['categories']:
if category['id'] == category_id:
# Create updated product with the same ID
updated_product = {
'id': product_id,
'name': product_name,
'price': product_price,
'unit': product_unit,
'image': product_image,
'description': product_description,
'inventory': removed_product.get('inventory', {})
}
category['products'].append(updated_product)
product_found = True
break
if product_found:
save_data(products_data, 'products.json')
message = 'Product updated successfully'
message_type = 'success'
else:
message = f"Product ID {product_id} not found"
message_type = "error"
except Exception as e:
message = f"Error updating product: {str(e)}"
message_type = "error"
elif action == 'update_inventory':
try:
product_id = int(request.form.get('product_id'))
city_id = int(request.form.get('city_id'))
district_id = int(request.form.get('district_id'))
quantity = int(request.form.get('quantity', 0))
if update_inventory(product_id, city_id, district_id, quantity):
message = 'Inventory updated successfully'
message_type = 'success'
else:
message = 'Failed to update inventory'
message_type = 'error'
except Exception as e:
message = f"Error updating inventory: {str(e)}"
message_type = "error"
elif action == 'add_category':
try:
# Get the highest existing category ID and add 1
max_id = max(category['id'] for category in products_data['categories'])
new_category = {
'id': max_id + 1,
'name': request.form.get('name'),
'image': request.form.get('image', '/placeholder.svg?height=80&width=80'),
'products': []
}
products_data['categories'].append(new_category)
save_data(products_data, 'products.json')
message = 'Category added successfully'
message_type = 'success'
except Exception as e:
message = f"Error adding category: {str(e)}"
message_type = "error"
# Prepare products list with categories and inventory
products = []
for category in products_data['categories']: