arshtech commited on
Commit
6888185
·
verified ·
1 Parent(s): 7909d88

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +204 -376
app.py CHANGED
@@ -5,25 +5,21 @@ import smtplib
5
  from email.mime.text import MIMEText
6
  from email.mime.multipart import MIMEMultipart
7
  from datetime import datetime
8
- import os
9
  from bson.objectid import ObjectId
10
- import traceback
11
 
12
  app = Flask(__name__)
13
  app.secret_key = 'carwala_secret_key_2024'
14
 
15
- # MongoDB configuration - using carwala1 database
16
  MONGODB_URI = "mongodb+srv://arshbir:arshbir123@arshbir.9pulohe.mongodb.net/carwala1?retryWrites=true&w=majority"
17
 
18
  try:
19
- client = MongoClient(MONGODB_URI)
20
- # Test the connection
21
  client.admin.command('ping')
22
  db = client.carwala1
23
- print("✅ MongoDB connection successful!")
24
  except Exception as e:
25
  print(f"❌ MongoDB connection failed: {e}")
26
- # Create a dummy client to prevent crashes
27
  db = None
28
 
29
  # Email configuration
@@ -35,498 +31,330 @@ ADMIN_EMAIL = "singharshbir76@gmail.com"
35
  ADMIN_PASSWORD = "arshbir"
36
 
37
  def initialize_database():
38
- """Initialize database and create collections if they don't exist"""
39
- if db is None:
40
- print("❌ Database not available")
41
  return
42
 
43
  try:
44
- # Get or create collections
45
  users = db.users
46
  cars = db.cars
47
  appointments = db.appointments
48
 
49
- # Create indexes
50
- users.create_index("email", unique=True)
51
- cars.create_index("seller_id")
52
- appointments.create_index("car_id")
 
 
 
 
53
 
54
- # Create admin user if not exists
55
- admin_user = users.find_one({"email": ADMIN_EMAIL})
56
- if not admin_user:
57
- hashed_password = bcrypt.hashpw(ADMIN_PASSWORD.encode('utf-8'), bcrypt.gensalt())
58
- admin_data = {
59
- "name": "Admin User",
60
- "email": ADMIN_EMAIL,
61
- "password": hashed_password,
62
- "role": "admin",
63
- "address": "Delhi, India",
64
- "phone": "9876543210",
65
- "approved": True,
66
- "created_at": datetime.now()
67
- }
68
- users.insert_one(admin_data)
69
- print("✅ Admin user created successfully!")
70
-
71
- # Add some sample cars with Indian prices if database is empty
72
  if cars.count_documents({}) == 0:
73
  sample_cars = [
74
- {
75
- "name": "Maruti Suzuki Swift",
76
- "year": 2022,
77
- "price": 650000,
78
- "description": "Excellent condition, low mileage, fuel efficient. Petrol engine, 5-speed manual.",
79
- "seller_id": "admin",
80
- "seller_email": ADMIN_EMAIL,
81
- "status": "approved",
82
- "created_at": datetime.now()
83
- },
84
- {
85
- "name": "Hyundai Creta",
86
- "year": 2021,
87
- "price": 1250000,
88
- "description": "Well maintained, single owner, all services done. Diesel automatic, sunroof.",
89
- "seller_id": "admin",
90
- "seller_email": ADMIN_EMAIL,
91
- "status": "approved",
92
- "created_at": datetime.now()
93
- },
94
- {
95
- "name": "Toyota Fortuner",
96
- "year": 2020,
97
- "price": 3200000,
98
- "description": "Powerful engine, premium SUV, 4x4 drive. Leather seats, well maintained.",
99
- "seller_id": "admin",
100
- "seller_email": ADMIN_EMAIL,
101
- "status": "approved",
102
- "created_at": datetime.now()
103
- }
104
  ]
105
  cars.insert_many(sample_cars)
106
- print("✅ Sample cars added successfully!")
107
-
108
- print("✅ Database initialized successfully!")
109
  except Exception as e:
110
- print(f"❌ Database initialization failed: {e}")
111
 
112
- # Initialize database when app starts
113
  initialize_database()
114
 
115
- # Format price in Indian Rupees
116
  def format_price(price):
117
- """Format price in Indian Rupees with comma separation"""
118
- return f"₹{price:,.0f}"
 
 
 
 
 
119
 
120
- # Add the format_price function to Jinja2 templates
121
  app.jinja_env.filters['format_price'] = format_price
122
 
123
- # Routes
124
  @app.route('/')
125
  def index():
126
- try:
127
- if db is None:
128
- flash('Database connection issue. Please try again later.')
129
- return render_template('index.html', cars=[])
130
-
131
- # Get all approved cars
132
- car_list = list(db.cars.find({"status": "approved"}))
133
- return render_template('index.html', cars=car_list)
134
- except Exception as e:
135
- print(f"Error in index route: {e}")
136
- flash('Error loading cars. Please try again.')
137
- return render_template('index.html', cars=[])
138
 
139
  @app.route('/login', methods=['GET', 'POST'])
140
  def login():
141
  if request.method == 'POST':
142
- try:
143
- if db is None:
144
- flash('Database connection issue. Please try again later.')
145
- return redirect(url_for('login'))
146
-
147
- email = request.form.get('email')
148
- password = request.form.get('password')
149
-
150
- # First check if it's the admin login
151
- if email == ADMIN_EMAIL and password == ADMIN_PASSWORD:
152
- admin_user = db.users.find_one({"email": ADMIN_EMAIL})
153
- if admin_user:
154
- session['user_id'] = str(admin_user['_id'])
155
- session['role'] = 'admin'
156
- session['email'] = ADMIN_EMAIL
157
- flash('Admin login successful!')
158
- return redirect(url_for('admin_dashboard'))
159
-
160
- # Regular user login
161
- user = db.users.find_one({"email": email})
162
-
163
- if user:
164
- # Check password
165
- if bcrypt.checkpw(password.encode('utf-8'), user['password']):
166
- # Check if seller is approved
167
  if user['role'] == 'seller' and not user.get('approved', False):
168
- flash('Your seller account is pending approval by admin.')
169
  return redirect(url_for('login'))
170
 
171
  session['user_id'] = str(user['_id'])
172
  session['role'] = user['role']
173
  session['email'] = email
174
 
175
- flash(f'Welcome back, {user["name"]}!')
176
-
177
  if user['role'] == 'buyer':
178
  return redirect(url_for('index'))
179
- elif user['role'] == 'seller':
180
  return redirect(url_for('seller_dashboard'))
181
  else:
182
- flash('Invalid email or password')
183
- else:
184
- flash('User not found. Please register first.')
185
- except Exception as e:
186
- print(f"Error in login: {e}")
187
- flash('Login failed. Please try again.')
188
 
189
  return render_template('login.html')
190
 
191
  @app.route('/register', methods=['GET', 'POST'])
192
  def register():
193
  if request.method == 'POST':
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  try:
195
- if db is None:
196
- flash('Database connection issue. Please try again later.')
197
- return redirect(url_for('register'))
198
-
199
- name = request.form.get('name')
200
- email = request.form.get('email')
201
- password = request.form.get('password')
202
- role = request.form.get('role')
203
- address = request.form.get('address')
204
- phone = request.form.get('phone')
205
-
206
- # Check if user already exists
207
  if db.users.find_one({"email": email}):
208
  flash('Email already registered')
209
- return redirect(url_for('register'))
210
-
211
- # Hash password
212
- hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
213
 
214
- # Create user document
215
  user_data = {
216
- "name": name,
217
- "email": email,
218
- "password": hashed_password,
219
- "role": role,
220
- "address": address,
221
- "phone": phone,
222
- "approved": True if role == 'buyer' else False,
223
  "created_at": datetime.now()
224
  }
225
 
226
  db.users.insert_one(user_data)
 
 
227
 
228
- if role == 'buyer':
229
- flash('Registration successful! Please login.')
230
- return redirect(url_for('login'))
231
- else:
232
- flash('Registration submitted. Waiting for admin approval.')
233
- return redirect(url_for('login'))
234
  except Exception as e:
235
- print(f"Error in register: {e}")
236
- flash('Registration failed. Please try again.')
237
 
238
  return render_template('register.html')
239
 
240
  @app.route('/logout')
241
  def logout():
242
  session.clear()
243
- flash('You have been logged out successfully.')
244
  return redirect(url_for('index'))
245
 
246
  @app.route('/admin')
247
  def admin_dashboard():
248
- if 'user_id' not in session or session.get('role') != 'admin':
249
- flash('Please login as admin to access this page.')
250
  return redirect(url_for('login'))
251
 
252
- try:
253
- if db is None:
254
- flash('Database connection issue. Please try again later.')
255
- return render_template('admin.html', pending_sellers=[], pending_cars=[], total_users=0, total_cars=0, total_appointments=0)
256
-
257
- # Get pending seller approvals
258
- pending_sellers = list(db.users.find({"role": "seller", "approved": False}))
259
-
260
- # Get all cars for approval
261
- pending_cars = list(db.cars.find({"status": "pending"}))
262
-
263
- # Get stats
264
- total_users = db.users.count_documents({})
265
- total_cars = db.cars.count_documents({})
266
- total_appointments = db.appointments.count_documents({})
267
-
268
- return render_template('admin.html',
269
- pending_sellers=pending_sellers,
270
- pending_cars=pending_cars,
271
- total_users=total_users,
272
- total_cars=total_cars,
273
- total_appointments=total_appointments)
274
- except Exception as e:
275
- print(f"Error in admin dashboard: {e}")
276
- flash('Error loading admin dashboard.')
277
- return render_template('admin.html', pending_sellers=[], pending_cars=[], total_users=0, total_cars=0, total_appointments=0)
278
 
279
  @app.route('/approve_seller/<user_id>')
280
  def approve_seller(user_id):
281
- if 'user_id' not in session or session.get('role') != 'admin':
282
  return redirect(url_for('login'))
283
 
284
- try:
285
- if db is None:
286
- flash('Database connection issue.')
287
- return redirect(url_for('admin_dashboard'))
288
-
289
- db.users.update_one({"_id": ObjectId(user_id)}, {"$set": {"approved": True}})
290
- flash('Seller approved successfully')
291
- except Exception as e:
292
- print(f"Error approving seller: {e}")
293
- flash('Error approving seller.')
294
 
295
  return redirect(url_for('admin_dashboard'))
296
 
297
  @app.route('/seller')
298
  def seller_dashboard():
299
- if 'user_id' not in session or session.get('role') != 'seller':
300
  return redirect(url_for('login'))
301
 
302
- try:
303
- if db is None:
304
- flash('Database connection issue. Please try again later.')
305
- return render_template('seller_dashboard.html', cars=[])
306
-
307
- # Check if seller is approved
308
- user = db.users.find_one({"_id": ObjectId(session['user_id'])})
309
- if not user.get('approved', False):
310
- flash('Your seller account is pending approval.')
311
- return redirect(url_for('login'))
312
-
313
- # Get seller's cars
314
- seller_cars = list(db.cars.find({"seller_id": session['user_id']}))
315
- return render_template('seller_dashboard.html', cars=seller_cars)
316
- except Exception as e:
317
- print(f"Error in seller dashboard: {e}")
318
- flash('Error loading seller dashboard.')
319
- return render_template('seller_dashboard.html', cars=[])
320
 
321
  @app.route('/add_car', methods=['POST'])
322
  def add_car():
323
- if 'user_id' not in session or session.get('role') != 'seller':
324
  return redirect(url_for('login'))
325
 
326
- try:
327
- if db is None:
328
- flash('Database connection issue.')
329
- return redirect(url_for('seller_dashboard'))
330
-
331
- name = request.form.get('name')
332
- year = request.form.get('year')
333
- price = request.form.get('price')
334
- description = request.form.get('description')
335
-
336
- car_data = {
337
- "name": name,
338
- "year": int(year),
339
- "price": int(price),
340
- "description": description,
341
- "seller_id": session['user_id'],
342
- "seller_email": session['email'],
343
- "status": "pending",
344
- "created_at": datetime.now()
345
- }
346
-
347
- db.cars.insert_one(car_data)
348
- flash('Car added successfully. Waiting for admin approval.')
349
- except Exception as e:
350
- print(f"Error adding car: {e}")
351
- flash('Error adding car. Please try again.')
352
 
353
  return redirect(url_for('seller_dashboard'))
354
 
355
  @app.route('/approve_car/<car_id>')
356
  def approve_car(car_id):
357
- if 'user_id' not in session or session.get('role') != 'admin':
358
  return redirect(url_for('login'))
359
 
360
- try:
361
- if db is None:
362
- flash('Database connection issue.')
363
- return redirect(url_for('admin_dashboard'))
364
-
365
- db.cars.update_one({"_id": ObjectId(car_id)}, {"$set": {"status": "approved"}})
366
- flash('Car approved successfully')
367
- except Exception as e:
368
- print(f"Error approving car: {e}")
369
- flash('Error approving car.')
370
 
371
  return redirect(url_for('admin_dashboard'))
372
 
373
  @app.route('/book_appointment/<car_id>', methods=['GET', 'POST'])
374
  def book_appointment(car_id):
375
- if 'user_id' not in session or session.get('role') != 'buyer':
376
  return redirect(url_for('login'))
377
 
 
 
 
 
378
  try:
379
- if db is None:
380
- flash('Database connection issue. Please try again later.')
381
- return redirect(url_for('index'))
382
-
383
  car = db.cars.find_one({"_id": ObjectId(car_id)})
 
 
 
384
 
385
  if request.method == 'POST':
386
- name = request.form.get('name')
387
- email = request.form.get('email')
388
- address = request.form.get('address')
389
- phone = request.form.get('phone')
390
- preferred_date = request.form.get('preferred_date')
391
- preferred_time = request.form.get('preferred_time')
 
 
392
 
393
  appointment_data = {
394
- "car_id": car_id,
395
- "car_name": car['name'],
396
- "buyer_id": session['user_id'],
397
- "buyer_name": name,
398
- "buyer_email": email,
399
- "buyer_address": address,
400
- "buyer_phone": phone,
401
- "preferred_date": preferred_date,
402
- "preferred_time": preferred_time,
403
- "status": "pending",
404
- "created_at": datetime.now()
405
  }
406
 
407
  db.appointments.insert_one(appointment_data)
408
- flash('Appointment booked successfully. Seller will contact you soon.')
409
  return redirect(url_for('index'))
410
 
411
  return render_template('appointment.html', car=car)
 
412
  except Exception as e:
413
- print(f"Error booking appointment: {e}")
414
- flash('Error booking appointment. Please try again.')
415
  return redirect(url_for('index'))
416
 
417
  @app.route('/seller_appointments/<car_id>')
418
  def seller_appointments(car_id):
419
- if 'user_id' not in session or session.get('role') != 'seller':
420
  return redirect(url_for('login'))
421
 
422
- try:
423
- if db is None:
424
- flash('Database connection issue. Please try again later.')
425
- return render_template('seller.html', appointments=[], car={})
426
-
427
- car_appointments = list(db.appointments.find({"car_id": car_id}))
428
- car = db.cars.find_one({"_id": ObjectId(car_id)})
429
- return render_template('seller.html', appointments=car_appointments, car=car)
430
- except Exception as e:
431
- print(f"Error loading appointments: {e}")
432
- flash('Error loading appointments.')
433
- return render_template('seller.html', appointments=[], car={})
434
 
435
  @app.route('/approve_appointment/<appointment_id>', methods=['POST'])
436
  def approve_appointment(appointment_id):
437
- if 'user_id' not in session or session.get('role') != 'seller':
438
  return redirect(url_for('login'))
439
 
440
- try:
441
- if db is None:
442
- flash('Database connection issue.')
443
- return redirect(url_for('seller_dashboard'))
444
-
445
- meeting_date = request.form.get('meeting_date')
446
- meeting_time = request.form.get('meeting_time')
447
- meeting_place = request.form.get('meeting_place')
448
-
449
- appointment = db.appointments.find_one({"_id": ObjectId(appointment_id)})
450
-
451
- # Update appointment status
452
- db.appointments.update_one(
453
- {"_id": ObjectId(appointment_id)},
454
- {"$set": {
455
  "status": "approved",
456
- "meeting_date": meeting_date,
457
- "meeting_time": meeting_time,
458
- "meeting_place": meeting_place
459
- }}
460
- )
461
-
462
- # Send email to buyer
463
- send_meeting_email(
464
- appointment['buyer_email'],
465
- appointment['car_name'],
466
- meeting_date,
467
- meeting_time,
468
- meeting_place
469
- )
470
-
471
- flash('Appointment approved and email sent to buyer')
472
- except Exception as e:
473
- print(f"Error approving appointment: {e}")
474
- flash('Error approving appointment.')
475
 
476
- return redirect(url_for('seller_appointments', car_id=appointment['car_id']))
477
-
478
- def send_meeting_email(buyer_email, car_name, date, time, place):
479
- try:
480
- subject = f"Carwala - Appointment Confirmation for {car_name}"
481
- body = f"""
482
- Dear Valued Customer,
483
-
484
- Your appointment for {car_name} has been approved by the seller.
485
-
486
- Meeting Details:
487
- - Car: {car_name}
488
- - Date: {date}
489
- - Time: {time}
490
- - Location: {place}
491
-
492
- Please arrive on time for the test drive. Don't forget to bring your driving license.
493
-
494
- If you have any questions, please contact the seller directly.
495
-
496
- Thank you for choosing Carwala!
497
-
498
- Best regards,
499
- Carwala Team
500
- Car Buying & Selling Platform
501
- """
502
-
503
- msg = MIMEMultipart()
504
- msg['From'] = SMTP_EMAIL
505
- msg['To'] = buyer_email
506
- msg['Subject'] = subject
507
-
508
- msg.attach(MIMEText(body, 'plain'))
509
-
510
- server = smtplib.SMTP('smtp.gmail.com', 587)
511
- server.starttls()
512
- server.login(SMTP_EMAIL, SMTP_PASSWORD)
513
- text = msg.as_string()
514
- server.sendmail(SMTP_EMAIL, buyer_email, text)
515
- server.quit()
516
-
517
- return True
518
- except Exception as e:
519
- print(f"Email error: {e}")
520
- return False
521
-
522
- # Error handler
523
- @app.errorhandler(500)
524
- def internal_error(error):
525
- return render_template('error.html'), 500
526
-
527
- @app.errorhandler(404)
528
- def not_found_error(error):
529
- return render_template('error.html'), 404
530
 
531
  if __name__ == '__main__':
532
  app.run(host='0.0.0.0', port=7860, debug=False)
 
5
  from email.mime.text import MIMEText
6
  from email.mime.multipart import MIMEMultipart
7
  from datetime import datetime
 
8
  from bson.objectid import ObjectId
 
9
 
10
  app = Flask(__name__)
11
  app.secret_key = 'carwala_secret_key_2024'
12
 
13
+ # MongoDB configuration
14
  MONGODB_URI = "mongodb+srv://arshbir:arshbir123@arshbir.9pulohe.mongodb.net/carwala1?retryWrites=true&w=majority"
15
 
16
  try:
17
+ client = MongoClient(MONGODB_URI, serverSelectionTimeoutMS=5000)
 
18
  client.admin.command('ping')
19
  db = client.carwala1
20
+ print("✅ MongoDB connected successfully!")
21
  except Exception as e:
22
  print(f"❌ MongoDB connection failed: {e}")
 
23
  db = None
24
 
25
  # Email configuration
 
31
  ADMIN_PASSWORD = "arshbir"
32
 
33
  def initialize_database():
34
+ """Initialize database and create collections"""
35
+ if not db:
 
36
  return
37
 
38
  try:
 
39
  users = db.users
40
  cars = db.cars
41
  appointments = db.appointments
42
 
43
+ # Create admin user
44
+ if not users.find_one({"email": ADMIN_EMAIL}):
45
+ hashed = bcrypt.hashpw(ADMIN_PASSWORD.encode('utf-8'), bcrypt.gensalt())
46
+ users.insert_one({
47
+ "name": "Admin", "email": ADMIN_EMAIL, "password": hashed,
48
+ "role": "admin", "approved": True, "created_at": datetime.now()
49
+ })
50
+ print("✅ Admin user created")
51
 
52
+ # Add sample cars
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  if cars.count_documents({}) == 0:
54
  sample_cars = [
55
+ {"name": "Maruti Swift", "year": 2022, "price": 650000, "status": "approved"},
56
+ {"name": "Hyundai Creta", "year": 2021, "price": 1250000, "status": "approved"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  ]
58
  cars.insert_many(sample_cars)
59
+ print("✅ Sample cars added")
60
+
 
61
  except Exception as e:
62
+ print(f"❌ Database init error: {e}")
63
 
 
64
  initialize_database()
65
 
66
+ # Safe price formatting function
67
  def format_price(price):
68
+ """Format price safely - handle None and other types"""
69
+ try:
70
+ if price is None:
71
+ return "₹0"
72
+ return f"₹{int(price):,}"
73
+ except (ValueError, TypeError):
74
+ return "₹0"
75
 
 
76
  app.jinja_env.filters['format_price'] = format_price
77
 
 
78
  @app.route('/')
79
  def index():
80
+ cars = []
81
+ if db:
82
+ try:
83
+ cars = list(db.cars.find({"status": "approved"}))
84
+ except Exception as e:
85
+ print(f"Error fetching cars: {e}")
86
+ flash("Error loading cars")
87
+
88
+ return render_template('index.html', cars=cars)
 
 
 
89
 
90
  @app.route('/login', methods=['GET', 'POST'])
91
  def login():
92
  if request.method == 'POST':
93
+ email = request.form.get('email', '').strip()
94
+ password = request.form.get('password', '')
95
+
96
+ if not email or not password:
97
+ flash('Please fill all fields')
98
+ return render_template('login.html')
99
+
100
+ # Admin login
101
+ if email == ADMIN_EMAIL and password == ADMIN_PASSWORD:
102
+ session['user_id'] = 'admin'
103
+ session['role'] = 'admin'
104
+ session['email'] = email
105
+ flash('Admin login successful!')
106
+ return redirect(url_for('admin_dashboard'))
107
+
108
+ # Regular user login
109
+ if db:
110
+ try:
111
+ user = db.users.find_one({"email": email})
112
+ if user and bcrypt.checkpw(password.encode('utf-8'), user['password']):
 
 
 
 
 
113
  if user['role'] == 'seller' and not user.get('approved', False):
114
+ flash('Seller account pending approval')
115
  return redirect(url_for('login'))
116
 
117
  session['user_id'] = str(user['_id'])
118
  session['role'] = user['role']
119
  session['email'] = email
120
 
 
 
121
  if user['role'] == 'buyer':
122
  return redirect(url_for('index'))
123
+ else:
124
  return redirect(url_for('seller_dashboard'))
125
  else:
126
+ flash('Invalid credentials')
127
+ except Exception as e:
128
+ print(f"Login error: {e}")
129
+ flash('Login error occurred')
130
+ else:
131
+ flash('Database unavailable')
132
 
133
  return render_template('login.html')
134
 
135
  @app.route('/register', methods=['GET', 'POST'])
136
  def register():
137
  if request.method == 'POST':
138
+ name = request.form.get('name', '').strip()
139
+ email = request.form.get('email', '').strip()
140
+ password = request.form.get('password', '')
141
+ role = request.form.get('role', 'buyer')
142
+ phone = request.form.get('phone', '').strip()
143
+ address = request.form.get('address', '').strip()
144
+
145
+ if not all([name, email, password, phone, address]):
146
+ flash('Please fill all fields')
147
+ return render_template('register.html')
148
+
149
+ if not db:
150
+ flash('Database unavailable')
151
+ return render_template('register.html')
152
+
153
  try:
 
 
 
 
 
 
 
 
 
 
 
 
154
  if db.users.find_one({"email": email}):
155
  flash('Email already registered')
156
+ return render_template('register.html')
 
 
 
157
 
158
+ hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
159
  user_data = {
160
+ "name": name, "email": email, "password": hashed, "role": role,
161
+ "phone": phone, "address": address, "approved": role == 'buyer',
 
 
 
 
 
162
  "created_at": datetime.now()
163
  }
164
 
165
  db.users.insert_one(user_data)
166
+ flash('Registration successful! Please login.' if role == 'buyer' else 'Registration pending approval')
167
+ return redirect(url_for('login'))
168
 
 
 
 
 
 
 
169
  except Exception as e:
170
+ print(f"Registration error: {e}")
171
+ flash('Registration failed')
172
 
173
  return render_template('register.html')
174
 
175
  @app.route('/logout')
176
  def logout():
177
  session.clear()
178
+ flash('Logged out successfully')
179
  return redirect(url_for('index'))
180
 
181
  @app.route('/admin')
182
  def admin_dashboard():
183
+ if session.get('role') != 'admin':
184
+ flash('Admin access required')
185
  return redirect(url_for('login'))
186
 
187
+ pending_sellers = []
188
+ pending_cars = []
189
+
190
+ if db:
191
+ try:
192
+ pending_sellers = list(db.users.find({"role": "seller", "approved": False}))
193
+ pending_cars = list(db.cars.find({"status": "pending"}))
194
+ except Exception as e:
195
+ print(f"Admin dashboard error: {e}")
196
+
197
+ return render_template('admin.html',
198
+ pending_sellers=pending_sellers,
199
+ pending_cars=pending_cars)
 
 
 
 
 
 
 
 
 
 
 
 
 
200
 
201
  @app.route('/approve_seller/<user_id>')
202
  def approve_seller(user_id):
203
+ if session.get('role') != 'admin':
204
  return redirect(url_for('login'))
205
 
206
+ if db:
207
+ try:
208
+ db.users.update_one({"_id": ObjectId(user_id)}, {"$set": {"approved": True}})
209
+ flash('Seller approved')
210
+ except Exception as e:
211
+ print(f"Approve seller error: {e}")
212
+ flash('Approval failed')
 
 
 
213
 
214
  return redirect(url_for('admin_dashboard'))
215
 
216
  @app.route('/seller')
217
  def seller_dashboard():
218
+ if session.get('role') != 'seller':
219
  return redirect(url_for('login'))
220
 
221
+ cars = []
222
+ if db:
223
+ try:
224
+ user = db.users.find_one({"_id": ObjectId(session['user_id'])})
225
+ if not user.get('approved', False):
226
+ flash('Account pending approval')
227
+ return redirect(url_for('login'))
228
+
229
+ cars = list(db.cars.find({"seller_id": session['user_id']}))
230
+ except Exception as e:
231
+ print(f"Seller dashboard error: {e}")
232
+
233
+ return render_template('seller_dashboard.html', cars=cars)
 
 
 
 
 
234
 
235
  @app.route('/add_car', methods=['POST'])
236
  def add_car():
237
+ if session.get('role') != 'seller':
238
  return redirect(url_for('login'))
239
 
240
+ name = request.form.get('name', '').strip()
241
+ year = request.form.get('year', '0')
242
+ price = request.form.get('price', '0')
243
+ description = request.form.get('description', '').strip()
244
+
245
+ if not name:
246
+ flash('Car name required')
247
+ return redirect(url_for('seller_dashboard'))
248
+
249
+ if db:
250
+ try:
251
+ car_data = {
252
+ "name": name, "year": int(year), "price": int(price),
253
+ "description": description, "seller_id": session['user_id'],
254
+ "seller_email": session['email'], "status": "pending",
255
+ "created_at": datetime.now()
256
+ }
257
+ db.cars.insert_one(car_data)
258
+ flash('Car added - pending approval')
259
+ except Exception as e:
260
+ print(f"Add car error: {e}")
261
+ flash('Error adding car')
 
 
 
 
262
 
263
  return redirect(url_for('seller_dashboard'))
264
 
265
  @app.route('/approve_car/<car_id>')
266
  def approve_car(car_id):
267
+ if session.get('role') != 'admin':
268
  return redirect(url_for('login'))
269
 
270
+ if db:
271
+ try:
272
+ db.cars.update_one({"_id": ObjectId(car_id)}, {"$set": {"status": "approved"}})
273
+ flash('Car approved')
274
+ except Exception as e:
275
+ print(f"Approve car error: {e}")
 
 
 
 
276
 
277
  return redirect(url_for('admin_dashboard'))
278
 
279
  @app.route('/book_appointment/<car_id>', methods=['GET', 'POST'])
280
  def book_appointment(car_id):
281
+ if session.get('role') != 'buyer':
282
  return redirect(url_for('login'))
283
 
284
+ if not db:
285
+ flash('Database unavailable')
286
+ return redirect(url_for('index'))
287
+
288
  try:
 
 
 
 
289
  car = db.cars.find_one({"_id": ObjectId(car_id)})
290
+ if not car:
291
+ flash('Car not found')
292
+ return redirect(url_for('index'))
293
 
294
  if request.method == 'POST':
295
+ name = request.form.get('name', '').strip()
296
+ email = request.form.get('email', '').strip()
297
+ address = request.form.get('address', '').strip()
298
+ phone = request.form.get('phone', '').strip()
299
+
300
+ if not all([name, email, address, phone]):
301
+ flash('Please fill all fields')
302
+ return render_template('appointment.html', car=car)
303
 
304
  appointment_data = {
305
+ "car_id": car_id, "car_name": car['name'], "buyer_id": session['user_id'],
306
+ "buyer_name": name, "buyer_email": email, "buyer_address": address,
307
+ "buyer_phone": phone, "status": "pending", "created_at": datetime.now()
 
 
 
 
 
 
 
 
308
  }
309
 
310
  db.appointments.insert_one(appointment_data)
311
+ flash('Appointment booked successfully!')
312
  return redirect(url_for('index'))
313
 
314
  return render_template('appointment.html', car=car)
315
+
316
  except Exception as e:
317
+ print(f"Appointment error: {e}")
318
+ flash('Error processing appointment')
319
  return redirect(url_for('index'))
320
 
321
  @app.route('/seller_appointments/<car_id>')
322
  def seller_appointments(car_id):
323
+ if session.get('role') != 'seller':
324
  return redirect(url_for('login'))
325
 
326
+ appointments = []
327
+ car = {}
328
+
329
+ if db:
330
+ try:
331
+ appointments = list(db.appointments.find({"car_id": car_id}))
332
+ car = db.cars.find_one({"_id": ObjectId(car_id)}) or {}
333
+ except Exception as e:
334
+ print(f"Appointments error: {e}")
335
+
336
+ return render_template('seller.html', appointments=appointments, car=car)
 
337
 
338
  @app.route('/approve_appointment/<appointment_id>', methods=['POST'])
339
  def approve_appointment(appointment_id):
340
+ if session.get('role') != 'seller':
341
  return redirect(url_for('login'))
342
 
343
+ if db:
344
+ try:
345
+ meeting_data = {
 
 
 
 
 
 
 
 
 
 
 
 
346
  "status": "approved",
347
+ "meeting_date": request.form.get('meeting_date', ''),
348
+ "meeting_time": request.form.get('meeting_time', ''),
349
+ "meeting_place": request.form.get('meeting_place', '')
350
+ }
351
+ db.appointments.update_one({"_id": ObjectId(appointment_id)}, {"$set": meeting_data})
352
+ flash('Appointment approved')
353
+ except Exception as e:
354
+ print(f"Approve appointment error: {e}")
355
+ flash('Approval failed')
 
 
 
 
 
 
 
 
 
 
356
 
357
+ return redirect(url_for('seller_dashboard'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358
 
359
  if __name__ == '__main__':
360
  app.run(host='0.0.0.0', port=7860, debug=False)