arshtech commited on
Commit
cadcd59
·
verified ·
1 Parent(s): 647538b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +236 -265
app.py CHANGED
@@ -1,342 +1,313 @@
1
- from flask import Flask, render_template, request, redirect, url_for, session, flash
 
2
  from pymongo import MongoClient
3
  import bcrypt
 
 
 
 
4
  from datetime import datetime
5
- from bson.objectid import ObjectId
6
 
7
  app = Flask(__name__)
8
  app.secret_key = 'carwala_secret_key_2024'
9
 
10
  # MongoDB configuration
11
- MONGODB_URI = "mongodb+srv://arshbir:arshbir123@arshbir.9pulohe.mongodb.net/carwala1?retryWrites=true&w=majority"
 
12
 
13
- try:
14
- client = MongoClient(MONGODB_URI)
15
- db = client.carwala1
16
- print("✅ MongoDB connected successfully!")
17
- except Exception as e:
18
- print(f"❌ MongoDB connection failed: {e}")
19
- db = None
 
20
 
21
  # Admin credentials
22
  ADMIN_EMAIL = "singharshbir76@gmail.com"
23
  ADMIN_PASSWORD = "arshbir"
24
 
25
- def initialize_database():
26
- """Initialize database with sample data"""
27
- if db is None:
28
- return
29
-
30
- try:
31
- # Create collections if they don't exist
32
- users = db.users
33
- cars = db.cars
34
- appointments = db.appointments
35
-
36
- # Create admin user if not exists
37
- if users.find_one({"email": ADMIN_EMAIL}) is None:
38
- hashed_password = bcrypt.hashpw(ADMIN_PASSWORD.encode('utf-8'), bcrypt.gensalt())
39
- admin_data = {
40
- "name": "Admin User",
41
- "email": ADMIN_EMAIL,
42
- "password": hashed_password,
43
- "role": "admin",
44
- "approved": True,
45
- "created_at": datetime.now()
46
- }
47
- users.insert_one(admin_data)
48
- print("✅ Admin user created")
49
-
50
- # Add sample cars if none exist
51
- if cars.count_documents({}) == 0:
52
- sample_cars = [
53
- {
54
- "name": "Maruti Suzuki Swift",
55
- "year": 2022,
56
- "price": 650000,
57
- "description": "Excellent condition with low mileage",
58
- "status": "approved",
59
- "created_at": datetime.now()
60
- },
61
- {
62
- "name": "Hyundai Creta",
63
- "year": 2021,
64
- "price": 1250000,
65
- "description": "Well maintained SUV",
66
- "status": "approved",
67
- "created_at": datetime.now()
68
- }
69
- ]
70
- cars.insert_many(sample_cars)
71
- print("✅ Sample cars added")
72
-
73
- except Exception as e:
74
- print(f"Database initialization error: {e}")
75
-
76
- # Initialize database
77
- initialize_database()
78
-
79
- # Price formatting filter
80
- def format_price(price):
81
- try:
82
- return f"₹{int(price):,}"
83
- except:
84
- return "₹0"
85
-
86
- app.jinja_env.filters['format_price'] = format_price
87
-
88
  @app.route('/')
89
  def index():
90
- try:
91
- if db is not None:
92
- cars = list(db.cars.find({"status": "approved"}))
93
- else:
94
- cars = []
95
- return render_template('index.html', cars=cars)
96
- except Exception as e:
97
- print(f"Error in index route: {e}")
98
- return render_template('index.html', cars=[])
99
 
100
  @app.route('/login', methods=['GET', 'POST'])
101
  def login():
102
  if request.method == 'POST':
103
- try:
104
- email = request.form.get('email')
105
- password = request.form.get('password')
106
-
107
- # Admin login
 
 
108
  if email == ADMIN_EMAIL and password == ADMIN_PASSWORD:
109
- session['user_id'] = 'admin'
110
  session['role'] = 'admin'
111
  session['email'] = email
112
- flash('Admin login successful!')
113
  return redirect(url_for('admin_dashboard'))
114
 
115
- # Regular user login
116
- if db is not None:
117
- user = db.users.find_one({"email": email})
118
- if user and bcrypt.checkpw(password.encode('utf-8'), user['password']):
119
- session['user_id'] = str(user['_id'])
120
- session['role'] = user['role']
121
- session['email'] = email
122
-
123
- if user['role'] == 'buyer':
124
- return redirect(url_for('index'))
125
- elif user['role'] == 'seller':
126
- if user.get('approved', False):
127
- return redirect(url_for('seller_dashboard'))
128
- else:
129
- flash('Seller account pending approval')
130
- return redirect(url_for('login'))
131
- else:
132
- flash('Invalid email or password')
133
- else:
134
- flash('Database connection issue')
135
 
136
- except Exception as e:
137
- print(f"Login error: {e}")
138
- flash('Login failed')
 
 
 
 
 
139
 
140
  return render_template('login.html')
141
 
142
  @app.route('/register', methods=['GET', 'POST'])
143
  def register():
144
  if request.method == 'POST':
145
- try:
146
- name = request.form.get('name')
147
- email = request.form.get('email')
148
- password = request.form.get('password')
149
- role = request.form.get('role')
150
- phone = request.form.get('phone')
151
- address = request.form.get('address')
152
-
153
- if db is not None:
154
- # Check if user exists
155
- if db.users.find_one({"email": email}):
156
- flash('Email already registered')
157
- return redirect(url_for('register'))
158
-
159
- # Create new user
160
- hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
161
- user_data = {
162
- "name": name,
163
- "email": email,
164
- "password": hashed_password,
165
- "role": role,
166
- "phone": phone,
167
- "address": address,
168
- "approved": role == 'buyer',
169
- "created_at": datetime.now()
170
- }
171
-
172
- db.users.insert_one(user_data)
173
-
174
- if role == 'buyer':
175
- flash('Registration successful! Please login.')
176
- else:
177
- flash('Registration submitted. Waiting for admin approval.')
178
-
179
- return redirect(url_for('login'))
180
- else:
181
- flash('Database connection issue')
182
-
183
- except Exception as e:
184
- print(f"Registration error: {e}")
185
- flash('Registration failed')
186
 
187
  return render_template('register.html')
188
 
189
  @app.route('/logout')
190
  def logout():
191
  session.clear()
192
- flash('Logged out successfully')
193
  return redirect(url_for('index'))
194
 
195
  @app.route('/admin')
196
  def admin_dashboard():
197
- if session.get('role') != 'admin':
198
- flash('Please login as admin')
199
  return redirect(url_for('login'))
200
 
201
- try:
202
- if db is not None:
203
- pending_sellers = list(db.users.find({"role": "seller", "approved": False}))
204
- pending_cars = list(db.cars.find({"status": "pending"}))
205
- else:
206
- pending_sellers = []
207
- pending_cars = []
208
-
209
- return render_template('admin.html',
210
- pending_sellers=pending_sellers,
211
- pending_cars=pending_cars)
212
- except Exception as e:
213
- print(f"Admin dashboard error: {e}")
214
- flash('Error loading admin dashboard')
215
- return render_template('admin.html', pending_sellers=[], pending_cars=[])
216
 
217
  @app.route('/approve_seller/<user_id>')
218
  def approve_seller(user_id):
219
- if session.get('role') != 'admin':
220
  return redirect(url_for('login'))
221
 
222
- try:
223
- if db is not None:
224
- db.users.update_one({"_id": ObjectId(user_id)}, {"$set": {"approved": True}})
225
- flash('Seller approved successfully')
226
- except Exception as e:
227
- print(f"Approve seller error: {e}")
228
- flash('Error approving seller')
229
-
230
  return redirect(url_for('admin_dashboard'))
231
 
232
  @app.route('/seller')
233
  def seller_dashboard():
234
- if session.get('role') != 'seller':
235
  return redirect(url_for('login'))
236
 
237
- try:
238
- if db is not None:
239
- # Verify seller is approved
240
- user = db.users.find_one({"_id": ObjectId(session['user_id'])})
241
- if not user or not user.get('approved', False):
242
- flash('Seller account not approved')
243
- return redirect(url_for('login'))
244
-
245
- cars = list(db.cars.find({"seller_id": session['user_id']}))
246
- else:
247
- cars = []
248
-
249
- return render_template('seller_dashboard.html', cars=cars)
250
- except Exception as e:
251
- print(f"Seller dashboard error: {e}")
252
- flash('Error loading seller dashboard')
253
- return render_template('seller_dashboard.html', cars=[])
254
 
255
  @app.route('/add_car', methods=['POST'])
256
  def add_car():
257
- if session.get('role') != 'seller':
258
  return redirect(url_for('login'))
259
 
260
- try:
261
- name = request.form.get('name')
262
- year = request.form.get('year')
263
- price = request.form.get('price')
264
- description = request.form.get('description')
265
-
266
- if db is not None:
267
- car_data = {
268
- "name": name,
269
- "year": int(year),
270
- "price": int(price),
271
- "description": description,
272
- "seller_id": session['user_id'],
273
- "seller_email": session.get('email', ''),
274
- "status": "pending",
275
- "created_at": datetime.now()
276
- }
277
- db.cars.insert_one(car_data)
278
- flash('Car added successfully. Waiting for admin approval.')
279
- else:
280
- flash('Database connection issue')
281
-
282
- except Exception as e:
283
- print(f"Add car error: {e}")
284
- flash('Error adding car')
285
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
  return redirect(url_for('seller_dashboard'))
287
 
288
  @app.route('/approve_car/<car_id>')
289
  def approve_car(car_id):
290
- if session.get('role') != 'admin':
291
  return redirect(url_for('login'))
292
 
293
- try:
294
- if db is not None:
295
- db.cars.update_one({"_id": ObjectId(car_id)}, {"$set": {"status": "approved"}})
296
- flash('Car approved successfully')
297
- except Exception as e:
298
- print(f"Approve car error: {e}")
299
- flash('Error approving car')
300
-
301
  return redirect(url_for('admin_dashboard'))
302
 
303
  @app.route('/book_appointment/<car_id>', methods=['GET', 'POST'])
304
  def book_appointment(car_id):
305
- if session.get('role') != 'buyer':
306
  return redirect(url_for('login'))
307
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308
  try:
309
- if db is not None:
310
- car = db.cars.find_one({"_id": ObjectId(car_id)})
311
- if not car:
312
- flash('Car not found')
313
- return redirect(url_for('index'))
314
-
315
- if request.method == 'POST':
316
- appointment_data = {
317
- "car_id": car_id,
318
- "car_name": car['name'],
319
- "buyer_id": session['user_id'],
320
- "buyer_name": request.form.get('name'),
321
- "buyer_email": request.form.get('email'),
322
- "buyer_phone": request.form.get('phone'),
323
- "buyer_address": request.form.get('address'),
324
- "status": "pending",
325
- "created_at": datetime.now()
326
- }
327
- db.appointments.insert_one(appointment_data)
328
- flash('Appointment booked successfully!')
329
- return redirect(url_for('index'))
330
-
331
- return render_template('appointment.html', car=car)
332
- else:
333
- flash('Database connection issue')
334
- return redirect(url_for('index'))
335
-
 
 
 
 
 
336
  except Exception as e:
337
- print(f"Book appointment error: {e}")
338
- flash('Error booking appointment')
339
- return redirect(url_for('index'))
340
 
341
  if __name__ == '__main__':
342
- app.run(host='0.0.0.0', port=7860, debug=False)
 
1
+ from flask import Flask, render_template, request, redirect, url_for, session, flash, jsonify
2
+ from flask_pymongo import PyMongo
3
  from pymongo import MongoClient
4
  import bcrypt
5
+ import smtplib
6
+ from email.mime.text import MimeText
7
+ from email.mime.multipart import MimeMultipart
8
+ import os
9
  from datetime import datetime
10
+ import uuid
11
 
12
  app = Flask(__name__)
13
  app.secret_key = 'carwala_secret_key_2024'
14
 
15
  # MongoDB configuration
16
+ app.config["MONGO_URI"] = "mongodb+srv://arshbir:arshbir123@arshbir.9pulohe.mongodb.net/carwala?retryWrites=true&w=majority"
17
+ mongo = PyMongo(app)
18
 
19
+ # Email configuration
20
+ SMTP_EMAIL = "singharshbir76@gmail.com"
21
+ SMTP_PASSWORD = "wpiy tuxp pgpf wljz"
22
+
23
+ # Initialize collections
24
+ users = mongo.db.users
25
+ cars = mongo.db.cars
26
+ appointments = mongo.db.appointments
27
 
28
  # Admin credentials
29
  ADMIN_EMAIL = "singharshbir76@gmail.com"
30
  ADMIN_PASSWORD = "arshbir"
31
 
32
+ # Routes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  @app.route('/')
34
  def index():
35
+ # Get all approved cars
36
+ car_list = list(cars.find({"status": "approved"}))
37
+ return render_template('index.html', cars=car_list)
 
 
 
 
 
 
38
 
39
  @app.route('/login', methods=['GET', 'POST'])
40
  def login():
41
  if request.method == 'POST':
42
+ email = request.form.get('email')
43
+ password = request.form.get('password')
44
+
45
+ user = users.find_one({"email": email})
46
+
47
+ if user:
48
+ # Check if user is admin
49
  if email == ADMIN_EMAIL and password == ADMIN_PASSWORD:
50
+ session['user_id'] = str(user['_id'])
51
  session['role'] = 'admin'
52
  session['email'] = email
 
53
  return redirect(url_for('admin_dashboard'))
54
 
55
+ # Check password for regular users
56
+ if bcrypt.checkpw(password.encode('utf-8'), user['password']):
57
+ # Check if seller is approved
58
+ if user['role'] == 'seller' and not user.get('approved', False):
59
+ flash('Your seller account is pending approval by admin.')
60
+ return redirect(url_for('login'))
61
+
62
+ session['user_id'] = str(user['_id'])
63
+ session['role'] = user['role']
64
+ session['email'] = email
 
 
 
 
 
 
 
 
 
 
65
 
66
+ if user['role'] == 'buyer':
67
+ return redirect(url_for('index'))
68
+ elif user['role'] == 'seller':
69
+ return redirect(url_for('seller_dashboard'))
70
+ else:
71
+ flash('Invalid email or password')
72
+ else:
73
+ flash('User not found')
74
 
75
  return render_template('login.html')
76
 
77
  @app.route('/register', methods=['GET', 'POST'])
78
  def register():
79
  if request.method == 'POST':
80
+ name = request.form.get('name')
81
+ email = request.form.get('email')
82
+ password = request.form.get('password')
83
+ role = request.form.get('role')
84
+ address = request.form.get('address')
85
+ phone = request.form.get('phone')
86
+
87
+ # Check if user already exists
88
+ if users.find_one({"email": email}):
89
+ flash('Email already registered')
90
+ return redirect(url_for('register'))
91
+
92
+ # Hash password
93
+ hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
94
+
95
+ # Create user document
96
+ user_data = {
97
+ "name": name,
98
+ "email": email,
99
+ "password": hashed_password,
100
+ "role": role,
101
+ "address": address,
102
+ "phone": phone,
103
+ "approved": True if role == 'buyer' else False,
104
+ "created_at": datetime.now()
105
+ }
106
+
107
+ users.insert_one(user_data)
108
+
109
+ if role == 'buyer':
110
+ flash('Registration successful! Please login.')
111
+ return redirect(url_for('login'))
112
+ else:
113
+ flash('Registration submitted. Waiting for admin approval.')
114
+ return redirect(url_for('login'))
 
 
 
 
 
 
115
 
116
  return render_template('register.html')
117
 
118
  @app.route('/logout')
119
  def logout():
120
  session.clear()
 
121
  return redirect(url_for('index'))
122
 
123
  @app.route('/admin')
124
  def admin_dashboard():
125
+ if 'user_id' not in session or session.get('role') != 'admin':
 
126
  return redirect(url_for('login'))
127
 
128
+ # Get pending seller approvals
129
+ pending_sellers = list(users.find({"role": "seller", "approved": False}))
130
+
131
+ # Get all cars for approval
132
+ pending_cars = list(cars.find({"status": "pending"}))
133
+
134
+ return render_template('admin.html',
135
+ pending_sellers=pending_sellers,
136
+ pending_cars=pending_cars)
 
 
 
 
 
 
137
 
138
  @app.route('/approve_seller/<user_id>')
139
  def approve_seller(user_id):
140
+ if 'user_id' not in session or session.get('role') != 'admin':
141
  return redirect(url_for('login'))
142
 
143
+ users.update_one({"_id": user_id}, {"$set": {"approved": True}})
144
+ flash('Seller approved successfully')
 
 
 
 
 
 
145
  return redirect(url_for('admin_dashboard'))
146
 
147
  @app.route('/seller')
148
  def seller_dashboard():
149
+ if 'user_id' not in session or session.get('role') != 'seller':
150
  return redirect(url_for('login'))
151
 
152
+ # Check if seller is approved
153
+ user = users.find_one({"_id": session['user_id']})
154
+ if not user.get('approved', False):
155
+ flash('Your seller account is pending approval.')
156
+ return redirect(url_for('login'))
157
+
158
+ # Get seller's cars
159
+ seller_cars = list(cars.find({"seller_id": session['user_id']}))
160
+ return render_template('seller_dashboard.html', cars=seller_cars)
 
 
 
 
 
 
 
 
161
 
162
  @app.route('/add_car', methods=['POST'])
163
  def add_car():
164
+ if 'user_id' not in session or session.get('role') != 'seller':
165
  return redirect(url_for('login'))
166
 
167
+ name = request.form.get('name')
168
+ year = request.form.get('year')
169
+ price = request.form.get('price')
170
+ description = request.form.get('description')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
+ car_data = {
173
+ "name": name,
174
+ "year": year,
175
+ "price": price,
176
+ "description": description,
177
+ "seller_id": session['user_id'],
178
+ "seller_email": session['email'],
179
+ "status": "pending",
180
+ "created_at": datetime.now()
181
+ }
182
+
183
+ cars.insert_one(car_data)
184
+ flash('Car added successfully. Waiting for admin approval.')
185
  return redirect(url_for('seller_dashboard'))
186
 
187
  @app.route('/approve_car/<car_id>')
188
  def approve_car(car_id):
189
+ if 'user_id' not in session or session.get('role') != 'admin':
190
  return redirect(url_for('login'))
191
 
192
+ cars.update_one({"_id": car_id}, {"$set": {"status": "approved"}})
193
+ flash('Car approved successfully')
 
 
 
 
 
 
194
  return redirect(url_for('admin_dashboard'))
195
 
196
  @app.route('/book_appointment/<car_id>', methods=['GET', 'POST'])
197
  def book_appointment(car_id):
198
+ if 'user_id' not in session or session.get('role') != 'buyer':
199
  return redirect(url_for('login'))
200
 
201
+ car = cars.find_one({"_id": car_id})
202
+
203
+ if request.method == 'POST':
204
+ name = request.form.get('name')
205
+ email = request.form.get('email')
206
+ address = request.form.get('address')
207
+ phone = request.form.get('phone')
208
+ preferred_date = request.form.get('preferred_date')
209
+ preferred_time = request.form.get('preferred_time')
210
+
211
+ appointment_data = {
212
+ "car_id": car_id,
213
+ "car_name": car['name'],
214
+ "buyer_id": session['user_id'],
215
+ "buyer_name": name,
216
+ "buyer_email": email,
217
+ "buyer_address": address,
218
+ "buyer_phone": phone,
219
+ "preferred_date": preferred_date,
220
+ "preferred_time": preferred_time,
221
+ "status": "pending",
222
+ "created_at": datetime.now()
223
+ }
224
+
225
+ appointments.insert_one(appointment_data)
226
+ flash('Appointment booked successfully. Seller will contact you soon.')
227
+ return redirect(url_for('index'))
228
+
229
+ return render_template('appointment.html', car=car)
230
+
231
+ @app.route('/seller_appointments/<car_id>')
232
+ def seller_appointments(car_id):
233
+ if 'user_id' not in session or session.get('role') != 'seller':
234
+ return redirect(url_for('login'))
235
+
236
+ car_appointments = list(appointments.find({"car_id": car_id}))
237
+ car = cars.find_one({"_id": car_id})
238
+ return render_template('seller.html', appointments=car_appointments, car=car)
239
+
240
+ @app.route('/approve_appointment/<appointment_id>', methods=['POST'])
241
+ def approve_appointment(appointment_id):
242
+ if 'user_id' not in session or session.get('role') != 'seller':
243
+ return redirect(url_for('login'))
244
+
245
+ meeting_date = request.form.get('meeting_date')
246
+ meeting_time = request.form.get('meeting_time')
247
+ meeting_place = request.form.get('meeting_place')
248
+
249
+ appointment = appointments.find_one({"_id": appointment_id})
250
+
251
+ # Update appointment status
252
+ appointments.update_one(
253
+ {"_id": appointment_id},
254
+ {"$set": {
255
+ "status": "approved",
256
+ "meeting_date": meeting_date,
257
+ "meeting_time": meeting_time,
258
+ "meeting_place": meeting_place
259
+ }}
260
+ )
261
+
262
+ # Send email to buyer
263
+ send_meeting_email(
264
+ appointment['buyer_email'],
265
+ appointment['car_name'],
266
+ meeting_date,
267
+ meeting_time,
268
+ meeting_place
269
+ )
270
+
271
+ flash('Appointment approved and email sent to buyer')
272
+ return redirect(url_for('seller_appointments', car_id=appointment['car_id']))
273
+
274
+ def send_meeting_email(buyer_email, car_name, date, time, place):
275
  try:
276
+ subject = f"Appointment Confirmation for {car_name}"
277
+ body = f"""
278
+ Dear Buyer,
279
+
280
+ Your appointment for {car_name} has been approved.
281
+
282
+ Meeting Details:
283
+ Date: {date}
284
+ Time: {time}
285
+ Place: {place}
286
+
287
+ Please arrive on time for the test drive.
288
+
289
+ Best regards,
290
+ Carwala Team
291
+ """
292
+
293
+ msg = MimeMultipart()
294
+ msg['From'] = SMTP_EMAIL
295
+ msg['To'] = buyer_email
296
+ msg['Subject'] = subject
297
+
298
+ msg.attach(MimeText(body, 'plain'))
299
+
300
+ server = smtplib.SMTP('smtp.gmail.com', 587)
301
+ server.starttls()
302
+ server.login(SMTP_EMAIL, SMTP_PASSWORD)
303
+ text = msg.as_string()
304
+ server.sendmail(SMTP_EMAIL, buyer_email, text)
305
+ server.quit()
306
+
307
+ return True
308
  except Exception as e:
309
+ print(f"Email error: {e}")
310
+ return False
 
311
 
312
  if __name__ == '__main__':
313
+ app.run(host='0.0.0.0', port=5000, debug=True)