arshtech commited on
Commit
85b8564
·
verified ·
1 Parent(s): 63201f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +312 -40
app.py CHANGED
@@ -10,26 +10,28 @@ import os
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/carwala?retryWrites=true&w=majority"
15
  client = MongoClient(MONGODB_URI)
16
- db = client.carwala
17
-
18
- # Collections
19
- users = db.users
20
- cars = db.cars
21
- appointments = db.appointments
22
-
23
- # Email configuration
24
- SMTP_EMAIL = "singharshbir76@gmail.com"
25
- SMTP_PASSWORD = "wpiy tuxp pgpf wljz"
26
 
27
  # Admin credentials
28
  ADMIN_EMAIL = "singharshbir76@gmail.com"
29
  ADMIN_PASSWORD = "arshbir"
30
 
31
- def create_admin_user():
32
- """Create admin user if not exists"""
 
 
 
 
 
 
 
 
 
 
 
33
  admin_user = users.find_one({"email": ADMIN_EMAIL})
34
  if not admin_user:
35
  hashed_password = bcrypt.hashpw(ADMIN_PASSWORD.encode('utf-8'), bcrypt.gensalt())
@@ -44,18 +46,55 @@ def create_admin_user():
44
  "created_at": datetime.now()
45
  }
46
  users.insert_one(admin_data)
47
- print("Admin user created successfully!")
48
- else:
49
- print("Admin user already exists")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
- # Create admin user when app starts
52
- create_admin_user()
53
 
54
  # Routes
55
  @app.route('/')
56
  def index():
57
  # Get all approved cars
58
- car_list = list(cars.find({"status": "approved"}))
59
  return render_template('index.html', cars=car_list)
60
 
61
  @app.route('/login', methods=['GET', 'POST'])
@@ -63,22 +102,22 @@ def login():
63
  if request.method == 'POST':
64
  email = request.form.get('email')
65
  password = request.form.get('password')
66
- print(f"Login attempt: {email}") # Debug log
67
-
68
- user = users.find_one({"email": email})
69
 
70
- if user:
71
- print(f"User found: {user['email']}, Role: {user.get('role')}") # Debug log
72
-
73
- # Check if user is admin using the special credentials
74
- if email == ADMIN_EMAIL and password == ADMIN_PASSWORD:
75
- session['user_id'] = str(user['_id'])
76
  session['role'] = 'admin'
77
- session['email'] = email
78
- print("Admin login successful") # Debug log
79
  return redirect(url_for('admin_dashboard'))
80
-
81
- # Check password for regular users
 
 
 
 
82
  if bcrypt.checkpw(password.encode('utf-8'), user['password']):
83
  # Check if seller is approved
84
  if user['role'] == 'seller' and not user.get('approved', False):
@@ -89,19 +128,66 @@ def login():
89
  session['role'] = user['role']
90
  session['email'] = email
91
 
 
 
92
  if user['role'] == 'buyer':
93
  return redirect(url_for('index'))
94
  elif user['role'] == 'seller':
95
  return redirect(url_for('seller_dashboard'))
96
  else:
97
  flash('Invalid email or password')
98
- print("Password check failed") # Debug log
99
  else:
100
- flash('User not found')
101
- print("User not found") # Debug log
102
 
103
  return render_template('login.html')
104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  @app.route('/admin')
106
  def admin_dashboard():
107
  if 'user_id' not in session or session.get('role') != 'admin':
@@ -109,16 +195,202 @@ def admin_dashboard():
109
  return redirect(url_for('login'))
110
 
111
  # Get pending seller approvals
112
- pending_sellers = list(users.find({"role": "seller", "approved": False}))
113
 
114
  # Get all cars for approval
115
- pending_cars = list(cars.find({"status": "pending"}))
 
 
 
 
 
116
 
117
  return render_template('admin.html',
118
  pending_sellers=pending_sellers,
119
- pending_cars=pending_cars)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
- # ... (rest of the routes remain the same)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
  if __name__ == '__main__':
124
  app.run(host='0.0.0.0', port=7860, debug=False)
 
10
  app = Flask(__name__)
11
  app.secret_key = 'carwala_secret_key_2024'
12
 
13
+ # MongoDB configuration - using carwala1 database
14
+ MONGODB_URI = "mongodb+srv://arshbir:arshbir123@arshbir.9pulohe.mongodb.net/carwala1?retryWrites=true&w=majority"
15
  client = MongoClient(MONGODB_URI)
16
+ db = client.carwala1
 
 
 
 
 
 
 
 
 
17
 
18
  # Admin credentials
19
  ADMIN_EMAIL = "singharshbir76@gmail.com"
20
  ADMIN_PASSWORD = "arshbir"
21
 
22
+ def initialize_database():
23
+ """Initialize database and create collections if they don't exist"""
24
+ # Get or create collections
25
+ users = db.users
26
+ cars = db.cars
27
+ appointments = db.appointments
28
+
29
+ # Create indexes
30
+ users.create_index("email", unique=True)
31
+ cars.create_index("seller_id")
32
+ appointments.create_index("car_id")
33
+
34
+ # Create admin user if not exists
35
  admin_user = users.find_one({"email": ADMIN_EMAIL})
36
  if not admin_user:
37
  hashed_password = bcrypt.hashpw(ADMIN_PASSWORD.encode('utf-8'), bcrypt.gensalt())
 
46
  "created_at": datetime.now()
47
  }
48
  users.insert_one(admin_data)
49
+ print("Admin user created successfully!")
50
+
51
+ # Add some sample cars if database is empty
52
+ if cars.count_documents({}) == 0:
53
+ sample_cars = [
54
+ {
55
+ "name": "Toyota Camry",
56
+ "year": 2020,
57
+ "price": 25000,
58
+ "description": "Excellent condition, low mileage, fuel efficient",
59
+ "seller_id": "admin",
60
+ "seller_email": ADMIN_EMAIL,
61
+ "status": "approved",
62
+ "created_at": datetime.now()
63
+ },
64
+ {
65
+ "name": "Honda Civic",
66
+ "year": 2019,
67
+ "price": 22000,
68
+ "description": "Well maintained, single owner, all services done",
69
+ "seller_id": "admin",
70
+ "seller_email": ADMIN_EMAIL,
71
+ "status": "approved",
72
+ "created_at": datetime.now()
73
+ },
74
+ {
75
+ "name": "Ford Mustang",
76
+ "year": 2021,
77
+ "price": 35000,
78
+ "description": "Powerful engine, sporty look, premium features",
79
+ "seller_id": "admin",
80
+ "seller_email": ADMIN_EMAIL,
81
+ "status": "approved",
82
+ "created_at": datetime.now()
83
+ }
84
+ ]
85
+ cars.insert_many(sample_cars)
86
+ print("✅ Sample cars added successfully!")
87
+
88
+ print("✅ Database initialized successfully!")
89
 
90
+ # Initialize database when app starts
91
+ initialize_database()
92
 
93
  # Routes
94
  @app.route('/')
95
  def index():
96
  # Get all approved cars
97
+ car_list = list(db.cars.find({"status": "approved"}))
98
  return render_template('index.html', cars=car_list)
99
 
100
  @app.route('/login', methods=['GET', 'POST'])
 
102
  if request.method == 'POST':
103
  email = request.form.get('email')
104
  password = request.form.get('password')
 
 
 
105
 
106
+ # First check if it's the admin login
107
+ if email == ADMIN_EMAIL and password == ADMIN_PASSWORD:
108
+ admin_user = db.users.find_one({"email": ADMIN_EMAIL})
109
+ if admin_user:
110
+ session['user_id'] = str(admin_user['_id'])
 
111
  session['role'] = 'admin'
112
+ session['email'] = ADMIN_EMAIL
113
+ flash('Admin login successful!')
114
  return redirect(url_for('admin_dashboard'))
115
+
116
+ # Regular user login
117
+ user = db.users.find_one({"email": email})
118
+
119
+ if user:
120
+ # Check password
121
  if bcrypt.checkpw(password.encode('utf-8'), user['password']):
122
  # Check if seller is approved
123
  if user['role'] == 'seller' and not user.get('approved', False):
 
128
  session['role'] = user['role']
129
  session['email'] = email
130
 
131
+ flash(f'Welcome back, {user["name"]}!')
132
+
133
  if user['role'] == 'buyer':
134
  return redirect(url_for('index'))
135
  elif user['role'] == 'seller':
136
  return redirect(url_for('seller_dashboard'))
137
  else:
138
  flash('Invalid email or password')
 
139
  else:
140
+ flash('User not found. Please register first.')
 
141
 
142
  return render_template('login.html')
143
 
144
+ @app.route('/register', methods=['GET', 'POST'])
145
+ def register():
146
+ if request.method == 'POST':
147
+ name = request.form.get('name')
148
+ email = request.form.get('email')
149
+ password = request.form.get('password')
150
+ role = request.form.get('role')
151
+ address = request.form.get('address')
152
+ phone = request.form.get('phone')
153
+
154
+ # Check if user already exists
155
+ if db.users.find_one({"email": email}):
156
+ flash('Email already registered')
157
+ return redirect(url_for('register'))
158
+
159
+ # Hash password
160
+ hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
161
+
162
+ # Create user document
163
+ user_data = {
164
+ "name": name,
165
+ "email": email,
166
+ "password": hashed_password,
167
+ "role": role,
168
+ "address": address,
169
+ "phone": phone,
170
+ "approved": True if role == 'buyer' else False,
171
+ "created_at": datetime.now()
172
+ }
173
+
174
+ db.users.insert_one(user_data)
175
+
176
+ if role == 'buyer':
177
+ flash('Registration successful! Please login.')
178
+ return redirect(url_for('login'))
179
+ else:
180
+ flash('Registration submitted. Waiting for admin approval.')
181
+ return redirect(url_for('login'))
182
+
183
+ return render_template('register.html')
184
+
185
+ @app.route('/logout')
186
+ def logout():
187
+ session.clear()
188
+ flash('You have been logged out successfully.')
189
+ return redirect(url_for('index'))
190
+
191
  @app.route('/admin')
192
  def admin_dashboard():
193
  if 'user_id' not in session or session.get('role') != 'admin':
 
195
  return redirect(url_for('login'))
196
 
197
  # Get pending seller approvals
198
+ pending_sellers = list(db.users.find({"role": "seller", "approved": False}))
199
 
200
  # Get all cars for approval
201
+ pending_cars = list(db.cars.find({"status": "pending"}))
202
+
203
+ # Get stats
204
+ total_users = db.users.count_documents({})
205
+ total_cars = db.cars.count_documents({})
206
+ total_appointments = db.appointments.count_documents({})
207
 
208
  return render_template('admin.html',
209
  pending_sellers=pending_sellers,
210
+ pending_cars=pending_cars,
211
+ total_users=total_users,
212
+ total_cars=total_cars,
213
+ total_appointments=total_appointments)
214
+
215
+ @app.route('/approve_seller/<user_id>')
216
+ def approve_seller(user_id):
217
+ if 'user_id' not in session or session.get('role') != 'admin':
218
+ return redirect(url_for('login'))
219
+
220
+ from bson.objectid import ObjectId
221
+ db.users.update_one({"_id": ObjectId(user_id)}, {"$set": {"approved": True}})
222
+ flash('Seller approved successfully')
223
+ return redirect(url_for('admin_dashboard'))
224
+
225
+ @app.route('/seller')
226
+ def seller_dashboard():
227
+ if 'user_id' not in session or session.get('role') != 'seller':
228
+ return redirect(url_for('login'))
229
+
230
+ # Check if seller is approved
231
+ from bson.objectid import ObjectId
232
+ user = db.users.find_one({"_id": ObjectId(session['user_id'])})
233
+ if not user.get('approved', False):
234
+ flash('Your seller account is pending approval.')
235
+ return redirect(url_for('login'))
236
+
237
+ # Get seller's cars
238
+ seller_cars = list(db.cars.find({"seller_id": session['user_id']}))
239
+ return render_template('seller_dashboard.html', cars=seller_cars)
240
 
241
+ @app.route('/add_car', methods=['POST'])
242
+ def add_car():
243
+ if 'user_id' not in session or session.get('role') != 'seller':
244
+ return redirect(url_for('login'))
245
+
246
+ name = request.form.get('name')
247
+ year = request.form.get('year')
248
+ price = request.form.get('price')
249
+ description = request.form.get('description')
250
+
251
+ car_data = {
252
+ "name": name,
253
+ "year": year,
254
+ "price": price,
255
+ "description": description,
256
+ "seller_id": session['user_id'],
257
+ "seller_email": session['email'],
258
+ "status": "pending",
259
+ "created_at": datetime.now()
260
+ }
261
+
262
+ db.cars.insert_one(car_data)
263
+ flash('Car added successfully. Waiting for admin approval.')
264
+ return redirect(url_for('seller_dashboard'))
265
+
266
+ @app.route('/approve_car/<car_id>')
267
+ def approve_car(car_id):
268
+ if 'user_id' not in session or session.get('role') != 'admin':
269
+ return redirect(url_for('login'))
270
+
271
+ from bson.objectid import ObjectId
272
+ db.cars.update_one({"_id": ObjectId(car_id)}, {"$set": {"status": "approved"}})
273
+ flash('Car approved successfully')
274
+ return redirect(url_for('admin_dashboard'))
275
+
276
+ @app.route('/book_appointment/<car_id>', methods=['GET', 'POST'])
277
+ def book_appointment(car_id):
278
+ if 'user_id' not in session or session.get('role') != 'buyer':
279
+ return redirect(url_for('login'))
280
+
281
+ from bson.objectid import ObjectId
282
+ car = db.cars.find_one({"_id": ObjectId(car_id)})
283
+
284
+ if request.method == 'POST':
285
+ name = request.form.get('name')
286
+ email = request.form.get('email')
287
+ address = request.form.get('address')
288
+ phone = request.form.get('phone')
289
+ preferred_date = request.form.get('preferred_date')
290
+ preferred_time = request.form.get('preferred_time')
291
+
292
+ appointment_data = {
293
+ "car_id": car_id,
294
+ "car_name": car['name'],
295
+ "buyer_id": session['user_id'],
296
+ "buyer_name": name,
297
+ "buyer_email": email,
298
+ "buyer_address": address,
299
+ "buyer_phone": phone,
300
+ "preferred_date": preferred_date,
301
+ "preferred_time": preferred_time,
302
+ "status": "pending",
303
+ "created_at": datetime.now()
304
+ }
305
+
306
+ db.appointments.insert_one(appointment_data)
307
+ flash('Appointment booked successfully. Seller will contact you soon.')
308
+ return redirect(url_for('index'))
309
+
310
+ return render_template('appointment.html', car=car)
311
+
312
+ @app.route('/seller_appointments/<car_id>')
313
+ def seller_appointments(car_id):
314
+ if 'user_id' not in session or session.get('role') != 'seller':
315
+ return redirect(url_for('login'))
316
+
317
+ car_appointments = list(db.appointments.find({"car_id": car_id}))
318
+ from bson.objectid import ObjectId
319
+ car = db.cars.find_one({"_id": ObjectId(car_id)})
320
+ return render_template('seller.html', appointments=car_appointments, car=car)
321
+
322
+ @app.route('/approve_appointment/<appointment_id>', methods=['POST'])
323
+ def approve_appointment(appointment_id):
324
+ if 'user_id' not in session or session.get('role') != 'seller':
325
+ return redirect(url_for('login'))
326
+
327
+ meeting_date = request.form.get('meeting_date')
328
+ meeting_time = request.form.get('meeting_time')
329
+ meeting_place = request.form.get('meeting_place')
330
+
331
+ from bson.objectid import ObjectId
332
+ appointment = db.appointments.find_one({"_id": ObjectId(appointment_id)})
333
+
334
+ # Update appointment status
335
+ db.appointments.update_one(
336
+ {"_id": ObjectId(appointment_id)},
337
+ {"$set": {
338
+ "status": "approved",
339
+ "meeting_date": meeting_date,
340
+ "meeting_time": meeting_time,
341
+ "meeting_place": meeting_place
342
+ }}
343
+ )
344
+
345
+ # Send email to buyer
346
+ send_meeting_email(
347
+ appointment['buyer_email'],
348
+ appointment['car_name'],
349
+ meeting_date,
350
+ meeting_time,
351
+ meeting_place
352
+ )
353
+
354
+ flash('Appointment approved and email sent to buyer')
355
+ return redirect(url_for('seller_appointments', car_id=appointment['car_id']))
356
+
357
+ def send_meeting_email(buyer_email, car_name, date, time, place):
358
+ try:
359
+ subject = f"Appointment Confirmation for {car_name}"
360
+ body = f"""
361
+ Dear Buyer,
362
+
363
+ Your appointment for {car_name} has been approved.
364
+
365
+ Meeting Details:
366
+ Date: {date}
367
+ Time: {time}
368
+ Place: {place}
369
+
370
+ Please arrive on time for the test drive.
371
+
372
+ Best regards,
373
+ Carwala Team
374
+ """
375
+
376
+ msg = MIMEMultipart()
377
+ msg['From'] = SMTP_EMAIL
378
+ msg['To'] = buyer_email
379
+ msg['Subject'] = subject
380
+
381
+ msg.attach(MIMEText(body, 'plain'))
382
+
383
+ server = smtplib.SMTP('smtp.gmail.com', 587)
384
+ server.starttls()
385
+ server.login(SMTP_EMAIL, SMTP_PASSWORD)
386
+ text = msg.as_string()
387
+ server.sendmail(SMTP_EMAIL, buyer_email, text)
388
+ server.quit()
389
+
390
+ return True
391
+ except Exception as e:
392
+ print(f"Email error: {e}")
393
+ return False
394
 
395
  if __name__ == '__main__':
396
  app.run(host='0.0.0.0', port=7860, debug=False)