Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,41 +1,20 @@
|
|
| 1 |
-
|
| 2 |
-
from
|
| 3 |
-
from fastapi.templating import Jinja2Templates
|
| 4 |
-
from fastapi.staticfiles import StaticFiles
|
| 5 |
-
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
| 6 |
import sqlite3
|
| 7 |
import os
|
| 8 |
from datetime import datetime
|
| 9 |
-
import
|
| 10 |
-
from
|
| 11 |
-
from
|
| 12 |
-
from starlette.middleware.sessions import SessionMiddleware
|
| 13 |
-
from passlib.context import CryptContext
|
| 14 |
-
import uuid
|
| 15 |
|
| 16 |
-
|
| 17 |
-
app =
|
| 18 |
-
app.add_middleware(SessionMiddleware, secret_key="fruit_veg_secret_key")
|
| 19 |
-
|
| 20 |
-
# Configure templates and static files
|
| 21 |
-
templates = Jinja2Templates(directory="templates")
|
| 22 |
-
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 23 |
-
|
| 24 |
-
# Password hashing context
|
| 25 |
-
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 26 |
-
|
| 27 |
-
# Security
|
| 28 |
-
security = HTTPBasic()
|
| 29 |
-
|
| 30 |
-
# Ensure upload directories exist
|
| 31 |
-
os.makedirs("static/images", exist_ok=True)
|
| 32 |
|
| 33 |
# Database initialization
|
| 34 |
def init_db():
|
| 35 |
conn = sqlite3.connect('fruitsveggies.db')
|
| 36 |
cursor = conn.cursor()
|
| 37 |
-
|
| 38 |
-
# Create admin users table
|
| 39 |
cursor.execute('''
|
| 40 |
CREATE TABLE IF NOT EXISTS admin_users (
|
| 41 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -43,19 +22,33 @@ def init_db():
|
|
| 43 |
password TEXT NOT NULL
|
| 44 |
)
|
| 45 |
''')
|
| 46 |
-
|
| 47 |
-
# Create users table
|
| 48 |
cursor.execute('''
|
| 49 |
CREATE TABLE IF NOT EXISTS users (
|
| 50 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 51 |
name TEXT NOT NULL,
|
| 52 |
email TEXT NOT NULL UNIQUE,
|
| 53 |
phone TEXT NOT NULL UNIQUE,
|
| 54 |
-
password TEXT NOT NULL
|
| 55 |
-
address TEXT
|
| 56 |
)
|
| 57 |
''')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
# Create products table
|
| 60 |
cursor.execute('''
|
| 61 |
CREATE TABLE IF NOT EXISTS products (
|
|
@@ -83,16 +76,6 @@ def init_db():
|
|
| 83 |
)
|
| 84 |
''')
|
| 85 |
|
| 86 |
-
# Check if admin user exists, if not create a default one
|
| 87 |
-
cursor.execute("SELECT COUNT(*) FROM admin_users")
|
| 88 |
-
count = cursor.fetchone()[0]
|
| 89 |
-
|
| 90 |
-
if count == 0:
|
| 91 |
-
# Create default admin user: username 'admin', password 'admin123'
|
| 92 |
-
hashed_password = pwd_context.hash('admin123')
|
| 93 |
-
cursor.execute("INSERT INTO admin_users (username, password) VALUES (?, ?)",
|
| 94 |
-
('admin', hashed_password))
|
| 95 |
-
|
| 96 |
# Check if products already exist to avoid duplicates
|
| 97 |
cursor.execute("SELECT COUNT(*) FROM products")
|
| 98 |
count = cursor.fetchone()[0]
|
|
@@ -135,34 +118,11 @@ def init_db():
|
|
| 135 |
# Initialize database on startup
|
| 136 |
init_db()
|
| 137 |
|
| 138 |
-
#
|
| 139 |
-
|
|
|
|
| 140 |
conn = sqlite3.connect('fruitsveggies.db')
|
| 141 |
conn.row_factory = sqlite3.Row
|
| 142 |
-
return conn
|
| 143 |
-
|
| 144 |
-
def verify_admin(credentials: HTTPBasicCredentials = Depends(security)):
|
| 145 |
-
conn = get_db()
|
| 146 |
-
cursor = conn.cursor()
|
| 147 |
-
cursor.execute("SELECT * FROM admin_users WHERE username = ?", (credentials.username,))
|
| 148 |
-
user = cursor.fetchone()
|
| 149 |
-
conn.close()
|
| 150 |
-
|
| 151 |
-
if not user or not pwd_context.verify(credentials.password, user['password']):
|
| 152 |
-
raise HTTPException(
|
| 153 |
-
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 154 |
-
detail="Invalid credentials",
|
| 155 |
-
headers={"WWW-Authenticate": "Basic"},
|
| 156 |
-
)
|
| 157 |
-
return credentials.username
|
| 158 |
-
|
| 159 |
-
def get_session(request: Request):
|
| 160 |
-
return request.session
|
| 161 |
-
|
| 162 |
-
# Routes
|
| 163 |
-
@app.get("/", response_class=HTMLResponse)
|
| 164 |
-
async def home(request: Request, category: Optional[str] = None):
|
| 165 |
-
conn = get_db()
|
| 166 |
cursor = conn.cursor()
|
| 167 |
|
| 168 |
# Get categories for filter
|
|
@@ -170,6 +130,7 @@ async def home(request: Request, category: Optional[str] = None):
|
|
| 170 |
categories = [dict(row) for row in cursor.fetchall()]
|
| 171 |
|
| 172 |
# Get all products (or filtered by category if provided)
|
|
|
|
| 173 |
if category:
|
| 174 |
cursor.execute("SELECT * FROM products WHERE category = ?", (category,))
|
| 175 |
else:
|
|
@@ -178,422 +139,189 @@ async def home(request: Request, category: Optional[str] = None):
|
|
| 178 |
products = [dict(row) for row in cursor.fetchall()]
|
| 179 |
conn.close()
|
| 180 |
|
| 181 |
-
return
|
| 182 |
-
"index.html",
|
| 183 |
-
{"request": request, "products": products, "categories": categories, "selected_category": category}
|
| 184 |
-
)
|
| 185 |
|
| 186 |
-
@app.
|
| 187 |
-
|
| 188 |
-
conn =
|
|
|
|
| 189 |
cursor = conn.cursor()
|
| 190 |
|
| 191 |
cursor.execute("SELECT * FROM products WHERE id = ?", (product_id,))
|
| 192 |
product = dict(cursor.fetchone())
|
| 193 |
conn.close()
|
| 194 |
|
| 195 |
-
return
|
| 196 |
|
| 197 |
-
@app.
|
| 198 |
-
|
| 199 |
-
request
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
(name, mobile, address, payment_method, datetime.now(), product_id, quantity)
|
| 215 |
-
)
|
| 216 |
|
| 217 |
-
|
|
|
|
| 218 |
conn.close()
|
| 219 |
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
@app.
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
)
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
cursor = conn.cursor()
|
| 242 |
|
| 243 |
-
cursor.execute("SELECT * FROM
|
| 244 |
-
|
| 245 |
conn.close()
|
| 246 |
|
| 247 |
-
|
| 248 |
-
session["user_logged_in"] = True
|
| 249 |
-
session["user_id"] = user['id']
|
| 250 |
-
session["user_name"] = user['name']
|
| 251 |
-
return RedirectResponse(url="/", status_code=status.HTTP_303_SEE_OTHER)
|
| 252 |
-
else:
|
| 253 |
-
return templates.TemplateResponse(
|
| 254 |
-
"login.html",
|
| 255 |
-
{"request": request, "error": "Invalid phone number or password"}
|
| 256 |
-
)
|
| 257 |
|
| 258 |
-
@app.
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
)
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
)
|
| 277 |
-
|
| 278 |
-
# Hash the password
|
| 279 |
-
hashed_password = pwd_context.hash(password)
|
| 280 |
-
|
| 281 |
-
conn = get_db()
|
| 282 |
-
cursor = conn.cursor()
|
| 283 |
-
|
| 284 |
-
try:
|
| 285 |
cursor.execute(
|
| 286 |
-
"INSERT INTO
|
| 287 |
-
(name,
|
| 288 |
)
|
|
|
|
| 289 |
conn.commit()
|
| 290 |
-
return RedirectResponse(url="/login?message=Account created successfully! Please login.", status_code=status.HTTP_303_SEE_OTHER)
|
| 291 |
-
except sqlite3.IntegrityError:
|
| 292 |
-
return templates.TemplateResponse(
|
| 293 |
-
"signup.html",
|
| 294 |
-
{"request": request, "error": "Email or phone number already exists"}
|
| 295 |
-
)
|
| 296 |
-
finally:
|
| 297 |
conn.close()
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
session.clear()
|
| 302 |
-
return RedirectResponse(url="/", status_code=status.HTTP_303_SEE_OTHER)
|
| 303 |
-
|
| 304 |
-
# User profile routes
|
| 305 |
-
@app.get("/profile", response_class=HTMLResponse)
|
| 306 |
-
async def profile(request: Request, session: dict = Depends(get_session)):
|
| 307 |
-
if not session.get("user_logged_in"):
|
| 308 |
-
return RedirectResponse(url="/login?message=Please login to view your profile", status_code=status.HTTP_303_SEE_OTHER)
|
| 309 |
-
|
| 310 |
-
user_id = session.get("user_id")
|
| 311 |
-
|
| 312 |
-
conn = get_db()
|
| 313 |
-
cursor = conn.cursor()
|
| 314 |
-
|
| 315 |
-
# Get user info
|
| 316 |
-
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
|
| 317 |
-
user = dict(cursor.fetchone())
|
| 318 |
-
|
| 319 |
-
# Get user orders
|
| 320 |
-
cursor.execute('''
|
| 321 |
-
SELECT
|
| 322 |
-
o.id,
|
| 323 |
-
o.order_date,
|
| 324 |
-
o.quantity,
|
| 325 |
-
p.name AS product_name,
|
| 326 |
-
p.price
|
| 327 |
-
FROM orders o
|
| 328 |
-
JOIN products p ON o.product_id = p.id
|
| 329 |
-
WHERE o.customer_name = ?
|
| 330 |
-
ORDER BY o.order_date DESC
|
| 331 |
-
''', (user['name'],))
|
| 332 |
-
|
| 333 |
-
orders = []
|
| 334 |
-
for row in cursor.fetchall():
|
| 335 |
-
order = dict(row)
|
| 336 |
-
# Parse the order_date string into a datetime object
|
| 337 |
-
order_date_str = order['order_date']
|
| 338 |
-
try:
|
| 339 |
-
# Attempt to parse with microseconds
|
| 340 |
-
order_date = datetime.strptime(order_date_str, '%Y-%m-%d %H:%M:%S.%f')
|
| 341 |
-
except ValueError:
|
| 342 |
-
# Fallback to parsing without microseconds
|
| 343 |
-
order_date = datetime.strptime(order_date_str, '%Y-%m-%d %H:%M:%S')
|
| 344 |
-
order['order_date'] = order_date
|
| 345 |
-
orders.append(order)
|
| 346 |
-
|
| 347 |
-
conn.close()
|
| 348 |
-
|
| 349 |
-
return templates.TemplateResponse("profile.html", {"request": request, "user": user, "orders": orders})
|
| 350 |
-
|
| 351 |
-
@app.get("/edit_profile", response_class=HTMLResponse)
|
| 352 |
-
async def edit_profile_page(request: Request, session: dict = Depends(get_session)):
|
| 353 |
-
if not session.get("user_logged_in"):
|
| 354 |
-
return RedirectResponse(url="/login?message=Please login to edit your profile", status_code=status.HTTP_303_SEE_OTHER)
|
| 355 |
-
|
| 356 |
-
user_id = session.get("user_id")
|
| 357 |
-
|
| 358 |
-
conn = get_db()
|
| 359 |
-
cursor = conn.cursor()
|
| 360 |
-
|
| 361 |
-
# Get user info
|
| 362 |
-
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
|
| 363 |
-
user = dict(cursor.fetchone())
|
| 364 |
-
conn.close()
|
| 365 |
|
| 366 |
-
return
|
| 367 |
|
| 368 |
-
@app.
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
phone: str = Form(...),
|
| 374 |
-
address: str = Form(...),
|
| 375 |
-
current_password: str = Form(...),
|
| 376 |
-
new_password: str = Form(None),
|
| 377 |
-
confirm_password: str = Form(None),
|
| 378 |
-
session: dict = Depends(get_session)
|
| 379 |
-
):
|
| 380 |
-
if not session.get("user_logged_in"):
|
| 381 |
-
return RedirectResponse(url="/login?message=Please login to edit your profile", status_code=status.HTTP_303_SEE_OTHER)
|
| 382 |
-
|
| 383 |
-
user_id = session.get("user_id")
|
| 384 |
-
|
| 385 |
-
conn = get_db()
|
| 386 |
cursor = conn.cursor()
|
| 387 |
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
try:
|
| 401 |
-
# If new password is provided, update it
|
| 402 |
-
if new_password:
|
| 403 |
-
if new_password != confirm_password:
|
| 404 |
-
conn.close()
|
| 405 |
-
return templates.TemplateResponse(
|
| 406 |
-
"edit_profile.html",
|
| 407 |
-
{"request": request, "user": user, "error": "New passwords do not match"}
|
| 408 |
-
)
|
| 409 |
|
| 410 |
-
|
| 411 |
cursor.execute(
|
| 412 |
-
"UPDATE
|
| 413 |
-
(name,
|
| 414 |
)
|
| 415 |
else:
|
| 416 |
-
#
|
| 417 |
cursor.execute(
|
| 418 |
-
"UPDATE
|
| 419 |
-
(name,
|
| 420 |
)
|
| 421 |
|
| 422 |
conn.commit()
|
| 423 |
-
|
| 424 |
-
return
|
| 425 |
-
|
| 426 |
-
except sqlite3.IntegrityError:
|
| 427 |
-
return templates.TemplateResponse(
|
| 428 |
-
"edit_profile.html",
|
| 429 |
-
{"request": request, "user": user, "error": "Email or phone number already in use"}
|
| 430 |
-
)
|
| 431 |
-
finally:
|
| 432 |
-
conn.close()
|
| 433 |
-
|
| 434 |
-
# Admin routes
|
| 435 |
-
@app.get("/admin", response_class=HTMLResponse)
|
| 436 |
-
async def admin_login_page(request: Request):
|
| 437 |
-
return templates.TemplateResponse("admin/login.html", {"request": request})
|
| 438 |
-
|
| 439 |
-
@app.post("/admin/login")
|
| 440 |
-
async def admin_login(
|
| 441 |
-
request: Request,
|
| 442 |
-
username: str = Form(...),
|
| 443 |
-
password: str = Form(...),
|
| 444 |
-
session: dict = Depends(get_session)
|
| 445 |
-
):
|
| 446 |
-
conn = get_db()
|
| 447 |
-
cursor = conn.cursor()
|
| 448 |
-
|
| 449 |
-
cursor.execute("SELECT * FROM admin_users WHERE username = ?", (username,))
|
| 450 |
-
user = cursor.fetchone()
|
| 451 |
-
conn.close()
|
| 452 |
-
|
| 453 |
-
if user and pwd_context.verify(password, user['password']):
|
| 454 |
-
session["admin_logged_in"] = True
|
| 455 |
-
session["admin_username"] = username
|
| 456 |
-
return RedirectResponse(url="/admin/dashboard", status_code=status.HTTP_303_SEE_OTHER)
|
| 457 |
-
else:
|
| 458 |
-
return templates.TemplateResponse(
|
| 459 |
-
"admin/login.html",
|
| 460 |
-
{"request": request, "error": "Invalid credentials"}
|
| 461 |
-
)
|
| 462 |
-
|
| 463 |
-
@app.get("/admin/logout")
|
| 464 |
-
async def admin_logout(request: Request, session: dict = Depends(get_session)):
|
| 465 |
-
session.pop("admin_logged_in", None)
|
| 466 |
-
session.pop("admin_username", None)
|
| 467 |
-
return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER)
|
| 468 |
-
|
| 469 |
-
@app.get("/admin/dashboard", response_class=HTMLResponse)
|
| 470 |
-
async def admin_dashboard(request: Request, session: dict = Depends(get_session)):
|
| 471 |
-
if not session.get("admin_logged_in"):
|
| 472 |
-
return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER)
|
| 473 |
-
|
| 474 |
-
return templates.TemplateResponse("admin/dashboard.html", {"request": request})
|
| 475 |
-
|
| 476 |
-
@app.get("/admin/products", response_class=HTMLResponse)
|
| 477 |
-
async def admin_products(request: Request, session: dict = Depends(get_session)):
|
| 478 |
-
if not session.get("admin_logged_in"):
|
| 479 |
-
return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER)
|
| 480 |
-
|
| 481 |
-
conn = get_db()
|
| 482 |
-
cursor = conn.cursor()
|
| 483 |
-
|
| 484 |
-
cursor.execute("SELECT * FROM products ORDER BY category, name")
|
| 485 |
-
products = [dict(row) for row in cursor.fetchall()]
|
| 486 |
-
conn.close()
|
| 487 |
-
|
| 488 |
-
return templates.TemplateResponse("admin/products.html", {"request": request, "products": products})
|
| 489 |
-
|
| 490 |
-
@app.get("/admin/add_product", response_class=HTMLResponse)
|
| 491 |
-
async def add_product_page(request: Request, session: dict = Depends(get_session)):
|
| 492 |
-
if not session.get("admin_logged_in"):
|
| 493 |
-
return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER)
|
| 494 |
-
|
| 495 |
-
return templates.TemplateResponse("admin/add_product.html", {"request": request})
|
| 496 |
-
|
| 497 |
-
@app.post("/admin/add_product")
|
| 498 |
-
async def add_product(
|
| 499 |
-
request: Request,
|
| 500 |
-
name: str = Form(...),
|
| 501 |
-
description: str = Form(...),
|
| 502 |
-
price: float = Form(...),
|
| 503 |
-
category: str = Form(...),
|
| 504 |
-
image: UploadFile = File(...),
|
| 505 |
-
session: dict = Depends(get_session)
|
| 506 |
-
):
|
| 507 |
-
if not session.get("admin_logged_in"):
|
| 508 |
-
return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER)
|
| 509 |
-
|
| 510 |
-
# Handle image upload
|
| 511 |
-
filename = ""
|
| 512 |
-
if image.filename:
|
| 513 |
-
filename = f"{uuid.uuid4().hex}_{image.filename}"
|
| 514 |
-
file_path = os.path.join("static/images", filename)
|
| 515 |
-
|
| 516 |
-
with open(file_path, "wb") as buffer:
|
| 517 |
-
shutil.copyfileobj(image.file, buffer)
|
| 518 |
-
else:
|
| 519 |
-
filename = "default.jpg" # Default image if none provided
|
| 520 |
-
|
| 521 |
-
conn = get_db()
|
| 522 |
-
cursor = conn.cursor()
|
| 523 |
-
|
| 524 |
-
cursor.execute(
|
| 525 |
-
"INSERT INTO products (name, description, price, image, category) VALUES (?, ?, ?, ?, ?)",
|
| 526 |
-
(name, description, price, filename, category)
|
| 527 |
-
)
|
| 528 |
-
|
| 529 |
-
conn.commit()
|
| 530 |
-
conn.close()
|
| 531 |
-
|
| 532 |
-
return RedirectResponse(url="/admin/products?message=Product added successfully", status_code=status.HTTP_303_SEE_OTHER)
|
| 533 |
-
|
| 534 |
-
@app.get("/admin/edit_product/{product_id}", response_class=HTMLResponse)
|
| 535 |
-
async def edit_product_page(request: Request, product_id: int, session: dict = Depends(get_session)):
|
| 536 |
-
if not session.get("admin_logged_in"):
|
| 537 |
-
return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER)
|
| 538 |
-
|
| 539 |
-
conn = get_db()
|
| 540 |
-
cursor = conn.cursor()
|
| 541 |
|
| 542 |
# Get product for editing
|
| 543 |
cursor.execute("SELECT * FROM products WHERE id = ?", (product_id,))
|
| 544 |
product = dict(cursor.fetchone())
|
| 545 |
conn.close()
|
| 546 |
|
| 547 |
-
return
|
| 548 |
|
| 549 |
-
@app.
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
name: str = Form(...),
|
| 554 |
-
description: str = Form(...),
|
| 555 |
-
price: float = Form(...),
|
| 556 |
-
category: str = Form(...),
|
| 557 |
-
image: UploadFile = File(None),
|
| 558 |
-
session: dict = Depends(get_session)
|
| 559 |
-
):
|
| 560 |
-
if not session.get("admin_logged_in"):
|
| 561 |
-
return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER)
|
| 562 |
-
|
| 563 |
-
conn = get_db()
|
| 564 |
-
cursor = conn.cursor()
|
| 565 |
-
|
| 566 |
-
# Handle image upload
|
| 567 |
-
if image and image.filename:
|
| 568 |
-
filename = f"{uuid.uuid4().hex}_{image.filename}"
|
| 569 |
-
file_path = os.path.join("static/images", filename)
|
| 570 |
-
|
| 571 |
-
with open(file_path, "wb") as buffer:
|
| 572 |
-
shutil.copyfileobj(image.file, buffer)
|
| 573 |
-
|
| 574 |
-
# Update product with new image
|
| 575 |
-
cursor.execute(
|
| 576 |
-
"UPDATE products SET name = ?, description = ?, price = ?, image = ?, category = ? WHERE id = ?",
|
| 577 |
-
(name, description, price, filename, category, product_id)
|
| 578 |
-
)
|
| 579 |
-
else:
|
| 580 |
-
# Update product without changing image
|
| 581 |
-
cursor.execute(
|
| 582 |
-
"UPDATE products SET name = ?, description = ?, price = ?, category = ? WHERE id = ?",
|
| 583 |
-
(name, description, price, category, product_id)
|
| 584 |
-
)
|
| 585 |
-
|
| 586 |
-
conn.commit()
|
| 587 |
-
conn.close()
|
| 588 |
-
|
| 589 |
-
return RedirectResponse(url="/admin/products?message=Product updated successfully", status_code=status.HTTP_303_SEE_OTHER)
|
| 590 |
-
|
| 591 |
-
@app.post("/admin/delete_product/{product_id}")
|
| 592 |
-
async def delete_product(request: Request, product_id: int, session: dict = Depends(get_session)):
|
| 593 |
-
if not session.get("admin_logged_in"):
|
| 594 |
-
return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER)
|
| 595 |
-
|
| 596 |
-
conn = get_db()
|
| 597 |
cursor = conn.cursor()
|
| 598 |
|
| 599 |
# First get the image filename to delete it from the filesystem
|
|
@@ -607,18 +335,17 @@ async def delete_product(request: Request, product_id: int, session: dict = Depe
|
|
| 607 |
|
| 608 |
# Delete the image file if it exists and is not a default
|
| 609 |
if image != 'default.jpg':
|
| 610 |
-
image_path = os.path.join(
|
| 611 |
if os.path.exists(image_path):
|
| 612 |
os.remove(image_path)
|
| 613 |
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
@app.
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
conn = get_db()
|
| 622 |
cursor = conn.cursor()
|
| 623 |
|
| 624 |
cursor.execute('''
|
|
@@ -654,17 +381,199 @@ async def admin_orders(request: Request, session: dict = Depends(get_session)):
|
|
| 654 |
|
| 655 |
conn.close()
|
| 656 |
|
| 657 |
-
return
|
|
|
|
|
|
|
|
|
|
| 658 |
|
| 659 |
-
@app.get("/about", response_class=HTMLResponse)
|
| 660 |
-
async def about(request: Request):
|
| 661 |
-
return templates.TemplateResponse("about.html", {"request": request})
|
| 662 |
|
| 663 |
-
@app.
|
| 664 |
-
|
| 665 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 666 |
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
|
|
|
|
|
|
|
|
|
|
| 3 |
import sqlite3
|
| 4 |
import os
|
| 5 |
from datetime import datetime
|
| 6 |
+
from flask import session
|
| 7 |
+
from werkzeug.security import check_password_hash, generate_password_hash
|
| 8 |
+
from werkzeug.utils import secure_filename
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
+
app = Flask(__name__)
|
| 11 |
+
app.secret_key = "fruit_veg_secret_key"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
# Database initialization
|
| 14 |
def init_db():
|
| 15 |
conn = sqlite3.connect('fruitsveggies.db')
|
| 16 |
cursor = conn.cursor()
|
| 17 |
+
# Create admin users table
|
|
|
|
| 18 |
cursor.execute('''
|
| 19 |
CREATE TABLE IF NOT EXISTS admin_users (
|
| 20 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
|
|
| 22 |
password TEXT NOT NULL
|
| 23 |
)
|
| 24 |
''')
|
|
|
|
|
|
|
| 25 |
cursor.execute('''
|
| 26 |
CREATE TABLE IF NOT EXISTS users (
|
| 27 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 28 |
name TEXT NOT NULL,
|
| 29 |
email TEXT NOT NULL UNIQUE,
|
| 30 |
phone TEXT NOT NULL UNIQUE,
|
| 31 |
+
password TEXT NOT NULL
|
|
|
|
| 32 |
)
|
| 33 |
''')
|
| 34 |
+
cursor.execute('''
|
| 35 |
+
PRAGMA table_info(users)
|
| 36 |
+
''')
|
| 37 |
+
columns = [column[1] for column in cursor.fetchall()]
|
| 38 |
|
| 39 |
+
if 'address' not in columns:
|
| 40 |
+
cursor.execute('''
|
| 41 |
+
ALTER TABLE users ADD COLUMN address TEXT
|
| 42 |
+
''')
|
| 43 |
+
# Check if admin user exists, if not create a default one
|
| 44 |
+
cursor.execute("SELECT COUNT(*) FROM admin_users")
|
| 45 |
+
count = cursor.fetchone()[0]
|
| 46 |
+
|
| 47 |
+
if count == 0:
|
| 48 |
+
# Create default admin user: username 'admin', password 'admin123'
|
| 49 |
+
hashed_password = generate_password_hash('admin123')
|
| 50 |
+
cursor.execute("INSERT INTO admin_users (username, password) VALUES (?, ?)",
|
| 51 |
+
('admin', hashed_password))
|
| 52 |
# Create products table
|
| 53 |
cursor.execute('''
|
| 54 |
CREATE TABLE IF NOT EXISTS products (
|
|
|
|
| 76 |
)
|
| 77 |
''')
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
# Check if products already exist to avoid duplicates
|
| 80 |
cursor.execute("SELECT COUNT(*) FROM products")
|
| 81 |
count = cursor.fetchone()[0]
|
|
|
|
| 118 |
# Initialize database on startup
|
| 119 |
init_db()
|
| 120 |
|
| 121 |
+
# Routes
|
| 122 |
+
@app.route('/')
|
| 123 |
+
def home():
|
| 124 |
conn = sqlite3.connect('fruitsveggies.db')
|
| 125 |
conn.row_factory = sqlite3.Row
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
cursor = conn.cursor()
|
| 127 |
|
| 128 |
# Get categories for filter
|
|
|
|
| 130 |
categories = [dict(row) for row in cursor.fetchall()]
|
| 131 |
|
| 132 |
# Get all products (or filtered by category if provided)
|
| 133 |
+
category = request.args.get('category', None)
|
| 134 |
if category:
|
| 135 |
cursor.execute("SELECT * FROM products WHERE category = ?", (category,))
|
| 136 |
else:
|
|
|
|
| 139 |
products = [dict(row) for row in cursor.fetchall()]
|
| 140 |
conn.close()
|
| 141 |
|
| 142 |
+
return render_template('index.html', products=products, categories=categories, selected_category=category)
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
+
@app.route('/product/<int:product_id>')
|
| 145 |
+
def product_detail(product_id):
|
| 146 |
+
conn = sqlite3.connect('fruitsveggies.db')
|
| 147 |
+
conn.row_factory = sqlite3.Row
|
| 148 |
cursor = conn.cursor()
|
| 149 |
|
| 150 |
cursor.execute("SELECT * FROM products WHERE id = ?", (product_id,))
|
| 151 |
product = dict(cursor.fetchone())
|
| 152 |
conn.close()
|
| 153 |
|
| 154 |
+
return render_template('product_detail.html', product=product)
|
| 155 |
|
| 156 |
+
@app.route('/place_order', methods=['POST'])
|
| 157 |
+
def place_order():
|
| 158 |
+
if request.method == 'POST':
|
| 159 |
+
try:
|
| 160 |
+
name = request.form['name']
|
| 161 |
+
mobile = request.form['mobile']
|
| 162 |
+
address = request.form['address']
|
| 163 |
+
payment_method = request.form['payment_method']
|
| 164 |
+
product_id = request.form['product_id']
|
| 165 |
+
quantity = request.form['quantity']
|
| 166 |
+
|
| 167 |
+
conn = sqlite3.connect('fruitsveggies.db')
|
| 168 |
+
cursor = conn.cursor()
|
| 169 |
+
|
| 170 |
+
# Insert the order
|
| 171 |
+
cursor.execute(
|
| 172 |
+
"INSERT INTO orders (customer_name, mobile, address, payment_method, order_date, product_id, quantity) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
| 173 |
+
(name, mobile, address, payment_method, datetime.now(), product_id, quantity)
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
conn.commit()
|
| 177 |
+
conn.close()
|
| 178 |
+
|
| 179 |
+
return redirect(url_for('order_success'))
|
| 180 |
+
except Exception as e:
|
| 181 |
+
flash(f"Error placing order: {str(e)}")
|
| 182 |
+
return redirect(url_for('product_detail', product_id=product_id))
|
| 183 |
+
|
| 184 |
+
# Make sure the upload directory exists
|
| 185 |
+
#@app._got_first_request
|
| 186 |
+
#def create_upload_directory():
|
| 187 |
+
# if not os.path.exists('static/images'):
|
| 188 |
+
# os.makedirs('static/images')
|
| 189 |
+
|
| 190 |
+
# Admin routes
|
| 191 |
+
@app.route('/admin', methods=['GET', 'POST'])
|
| 192 |
+
def admin_login():
|
| 193 |
+
if request.method == 'POST':
|
| 194 |
+
username = request.form['username']
|
| 195 |
+
password = request.form['password']
|
| 196 |
|
| 197 |
+
conn = sqlite3.connect('fruitsveggies.db')
|
| 198 |
+
conn.row_factory = sqlite3.Row
|
| 199 |
+
cursor = conn.cursor()
|
|
|
|
|
|
|
| 200 |
|
| 201 |
+
cursor.execute("SELECT * FROM admin_users WHERE username = ?", (username,))
|
| 202 |
+
user = cursor.fetchone()
|
| 203 |
conn.close()
|
| 204 |
|
| 205 |
+
if user and check_password_hash(user['password'], password):
|
| 206 |
+
session['admin_logged_in'] = True
|
| 207 |
+
session['admin_username'] = username
|
| 208 |
+
return redirect(url_for('admin_dashboard'))
|
| 209 |
+
else:
|
| 210 |
+
flash('Invalid credentials')
|
| 211 |
+
|
| 212 |
+
return render_template('admin/login.html')
|
| 213 |
+
|
| 214 |
+
@app.route('/admin/logout')
|
| 215 |
+
def admin_logout():
|
| 216 |
+
session.pop('admin_logged_in', None)
|
| 217 |
+
session.pop('admin_username', None)
|
| 218 |
+
return redirect(url_for('admin_login'))
|
| 219 |
+
|
| 220 |
+
def admin_required(f):
|
| 221 |
+
def decorated_function(*args, **kwargs):
|
| 222 |
+
if not session.get('admin_logged_in'):
|
| 223 |
+
return redirect(url_for('admin_login'))
|
| 224 |
+
return f(*args, **kwargs)
|
| 225 |
+
decorated_function.__name__ = f.__name__
|
| 226 |
+
return decorated_function
|
| 227 |
+
|
| 228 |
+
@app.route('/admin/dashboard')
|
| 229 |
+
@admin_required
|
| 230 |
+
def admin_dashboard():
|
| 231 |
+
return render_template('admin/dashboard.html')
|
| 232 |
+
|
| 233 |
+
@app.route('/admin/products')
|
| 234 |
+
@admin_required
|
| 235 |
+
def admin_products():
|
| 236 |
+
conn = sqlite3.connect('fruitsveggies.db')
|
| 237 |
+
conn.row_factory = sqlite3.Row
|
| 238 |
cursor = conn.cursor()
|
| 239 |
|
| 240 |
+
cursor.execute("SELECT * FROM products ORDER BY category, name")
|
| 241 |
+
products = [dict(row) for row in cursor.fetchall()]
|
| 242 |
conn.close()
|
| 243 |
|
| 244 |
+
return render_template('admin/products.html', products=products)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
|
| 246 |
+
@app.route('/admin/add_product', methods=['GET', 'POST'])
|
| 247 |
+
@admin_required
|
| 248 |
+
def add_product():
|
| 249 |
+
if request.method == 'POST':
|
| 250 |
+
name = request.form['name']
|
| 251 |
+
description = request.form['description']
|
| 252 |
+
price = float(request.form['price'])
|
| 253 |
+
category = request.form['category']
|
| 254 |
+
|
| 255 |
+
# Handle image upload
|
| 256 |
+
image = request.files['image']
|
| 257 |
+
if image and image.filename:
|
| 258 |
+
filename = secure_filename(image.filename)
|
| 259 |
+
image.save(os.path.join('static/images', filename))
|
| 260 |
+
else:
|
| 261 |
+
filename = 'default.jpg' # Default image if none provided
|
| 262 |
+
|
| 263 |
+
conn = sqlite3.connect('fruitsveggies.db')
|
| 264 |
+
cursor = conn.cursor()
|
| 265 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
cursor.execute(
|
| 267 |
+
"INSERT INTO products (name, description, price, image, category) VALUES (?, ?, ?, ?, ?)",
|
| 268 |
+
(name, description, price, filename, category)
|
| 269 |
)
|
| 270 |
+
|
| 271 |
conn.commit()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
conn.close()
|
| 273 |
+
|
| 274 |
+
flash('Product added successfully')
|
| 275 |
+
return redirect(url_for('admin_products'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
|
| 277 |
+
return render_template('admin/add_product.html')
|
| 278 |
|
| 279 |
+
@app.route('/admin/edit_product/<int:product_id>', methods=['GET', 'POST'])
|
| 280 |
+
@admin_required
|
| 281 |
+
def edit_product(product_id):
|
| 282 |
+
conn = sqlite3.connect('fruitsveggies.db')
|
| 283 |
+
conn.row_factory = sqlite3.Row
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
cursor = conn.cursor()
|
| 285 |
|
| 286 |
+
if request.method == 'POST':
|
| 287 |
+
name = request.form['name']
|
| 288 |
+
description = request.form['description']
|
| 289 |
+
price = float(request.form['price'])
|
| 290 |
+
category = request.form['category']
|
| 291 |
+
|
| 292 |
+
# Handle image upload
|
| 293 |
+
image = request.files['image']
|
| 294 |
+
if image and image.filename:
|
| 295 |
+
filename = secure_filename(image.filename)
|
| 296 |
+
image.save(os.path.join('static/images', filename))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
|
| 298 |
+
# Update product with new image
|
| 299 |
cursor.execute(
|
| 300 |
+
"UPDATE products SET name = ?, description = ?, price = ?, image = ?, category = ? WHERE id = ?",
|
| 301 |
+
(name, description, price, filename, category, product_id)
|
| 302 |
)
|
| 303 |
else:
|
| 304 |
+
# Update product without changing image
|
| 305 |
cursor.execute(
|
| 306 |
+
"UPDATE products SET name = ?, description = ?, price = ?, category = ? WHERE id = ?",
|
| 307 |
+
(name, description, price, category, product_id)
|
| 308 |
)
|
| 309 |
|
| 310 |
conn.commit()
|
| 311 |
+
flash('Product updated successfully')
|
| 312 |
+
return redirect(url_for('admin_products'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
# Get product for editing
|
| 315 |
cursor.execute("SELECT * FROM products WHERE id = ?", (product_id,))
|
| 316 |
product = dict(cursor.fetchone())
|
| 317 |
conn.close()
|
| 318 |
|
| 319 |
+
return render_template('admin/edit_product.html', product=product)
|
| 320 |
|
| 321 |
+
@app.route('/admin/delete_product/<int:product_id>', methods=['POST'])
|
| 322 |
+
@admin_required
|
| 323 |
+
def delete_product(product_id):
|
| 324 |
+
conn = sqlite3.connect('fruitsveggies.db')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
cursor = conn.cursor()
|
| 326 |
|
| 327 |
# First get the image filename to delete it from the filesystem
|
|
|
|
| 335 |
|
| 336 |
# Delete the image file if it exists and is not a default
|
| 337 |
if image != 'default.jpg':
|
| 338 |
+
image_path = os.path.join('static/images', image)
|
| 339 |
if os.path.exists(image_path):
|
| 340 |
os.remove(image_path)
|
| 341 |
|
| 342 |
+
flash('Product deleted successfully')
|
| 343 |
+
return redirect(url_for('admin_products'))
|
| 344 |
+
@app.route('/admin/orders')
|
| 345 |
+
@admin_required
|
| 346 |
+
def admin_orders():
|
| 347 |
+
conn = sqlite3.connect('fruitsveggies.db')
|
| 348 |
+
conn.row_factory = sqlite3.Row
|
|
|
|
| 349 |
cursor = conn.cursor()
|
| 350 |
|
| 351 |
cursor.execute('''
|
|
|
|
| 381 |
|
| 382 |
conn.close()
|
| 383 |
|
| 384 |
+
return render_template('admin/orders.html', orders=orders)
|
| 385 |
+
@app.route('/order_success')
|
| 386 |
+
def order_success():
|
| 387 |
+
return render_template('order_success.html')
|
| 388 |
|
|
|
|
|
|
|
|
|
|
| 389 |
|
| 390 |
+
@app.route('/login', methods=['GET', 'POST'])
|
| 391 |
+
def login():
|
| 392 |
+
if request.method == 'POST':
|
| 393 |
+
phone = request.form['phone']
|
| 394 |
+
password = request.form['password']
|
| 395 |
+
|
| 396 |
+
conn = sqlite3.connect('fruitsveggies.db')
|
| 397 |
+
conn.row_factory = sqlite3.Row
|
| 398 |
+
cursor = conn.cursor()
|
| 399 |
+
|
| 400 |
+
cursor.execute("SELECT * FROM users WHERE phone = ?", (phone,))
|
| 401 |
+
user = cursor.fetchone()
|
| 402 |
+
conn.close()
|
| 403 |
+
|
| 404 |
+
if user and check_password_hash(user['password'], password):
|
| 405 |
+
session['user_logged_in'] = True
|
| 406 |
+
session['user_id'] = user['id']
|
| 407 |
+
session['user_name'] = user['name']
|
| 408 |
+
flash('Login successful!')
|
| 409 |
+
return redirect(url_for('home'))
|
| 410 |
+
else:
|
| 411 |
+
flash('Invalid phone number or password')
|
| 412 |
+
|
| 413 |
+
return render_template('login.html')
|
| 414 |
+
|
| 415 |
+
@app.route('/signup', methods=['GET', 'POST'])
|
| 416 |
+
def signup():
|
| 417 |
+
if request.method == 'POST':
|
| 418 |
+
name = request.form['name']
|
| 419 |
+
email = request.form['email']
|
| 420 |
+
phone = request.form['phone']
|
| 421 |
+
password = request.form['password']
|
| 422 |
+
confirm_password = request.form['confirm_password']
|
| 423 |
+
|
| 424 |
+
# Validate passwords match
|
| 425 |
+
if password != confirm_password:
|
| 426 |
+
flash('Passwords do not match')
|
| 427 |
+
return render_template('signup.html')
|
| 428 |
+
|
| 429 |
+
# Hash the password
|
| 430 |
+
hashed_password = generate_password_hash(password)
|
| 431 |
+
|
| 432 |
+
conn = sqlite3.connect('fruitsveggies.db')
|
| 433 |
+
cursor = conn.cursor()
|
| 434 |
+
|
| 435 |
+
try:
|
| 436 |
+
cursor.execute(
|
| 437 |
+
"INSERT INTO users (name, email, phone, password) VALUES (?, ?, ?, ?)",
|
| 438 |
+
(name, email, phone, hashed_password)
|
| 439 |
+
)
|
| 440 |
+
conn.commit()
|
| 441 |
+
flash('Account created successfully! Please login.')
|
| 442 |
+
return redirect(url_for('login'))
|
| 443 |
+
except sqlite3.IntegrityError:
|
| 444 |
+
flash('Email or phone number already exists')
|
| 445 |
+
finally:
|
| 446 |
+
conn.close()
|
| 447 |
+
|
| 448 |
+
return render_template('signup.html')
|
| 449 |
+
|
| 450 |
+
@app.route('/logout')
|
| 451 |
+
def logout():
|
| 452 |
+
session.pop('user_logged_in', None)
|
| 453 |
+
session.pop('user_id', None)
|
| 454 |
+
session.pop('user_name', None)
|
| 455 |
+
flash('You have been logged out')
|
| 456 |
+
return redirect(url_for('home'))
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
# Add these new routes
|
| 460 |
+
@app.route('/profile')
|
| 461 |
+
def profile():
|
| 462 |
+
# Check if user is logged in
|
| 463 |
+
if not session.get('user_logged_in'):
|
| 464 |
+
flash('Please login to view your profile')
|
| 465 |
+
return redirect(url_for('login'))
|
| 466 |
+
|
| 467 |
+
user_id = session.get('user_id')
|
| 468 |
+
|
| 469 |
+
conn = sqlite3.connect('fruitsveggies.db')
|
| 470 |
+
conn.row_factory = sqlite3.Row
|
| 471 |
+
cursor = conn.cursor()
|
| 472 |
+
|
| 473 |
+
# Get user info
|
| 474 |
+
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
|
| 475 |
+
user = dict(cursor.fetchone())
|
| 476 |
+
|
| 477 |
+
# Get user orders
|
| 478 |
+
cursor.execute('''
|
| 479 |
+
SELECT
|
| 480 |
+
o.id,
|
| 481 |
+
o.order_date,
|
| 482 |
+
o.quantity,
|
| 483 |
+
p.name AS product_name,
|
| 484 |
+
p.price
|
| 485 |
+
FROM orders o
|
| 486 |
+
JOIN products p ON o.product_id = p.id
|
| 487 |
+
WHERE o.customer_name = ?
|
| 488 |
+
ORDER BY o.order_date DESC
|
| 489 |
+
''', (user['name'],))
|
| 490 |
+
|
| 491 |
+
orders = []
|
| 492 |
+
for row in cursor.fetchall():
|
| 493 |
+
order = dict(row)
|
| 494 |
+
# Parse the order_date string into a datetime object
|
| 495 |
+
order_date_str = order['order_date']
|
| 496 |
+
try:
|
| 497 |
+
# Attempt to parse with microseconds
|
| 498 |
+
order_date = datetime.strptime(order_date_str, '%Y-%m-%d %H:%M:%S.%f')
|
| 499 |
+
except ValueError:
|
| 500 |
+
# Fallback to parsing without microseconds
|
| 501 |
+
order_date = datetime.strptime(order_date_str, '%Y-%m-%d %H:%M:%S')
|
| 502 |
+
order['order_date'] = order_date
|
| 503 |
+
orders.append(order)
|
| 504 |
+
|
| 505 |
+
conn.close()
|
| 506 |
+
|
| 507 |
+
return render_template('profile.html', user=user, orders=orders)
|
| 508 |
|
| 509 |
+
@app.route('/edit_profile', methods=['GET', 'POST'])
|
| 510 |
+
def edit_profile():
|
| 511 |
+
# Check if user is logged in
|
| 512 |
+
if not session.get('user_logged_in'):
|
| 513 |
+
flash('Please login to edit your profile')
|
| 514 |
+
return redirect(url_for('login'))
|
| 515 |
+
|
| 516 |
+
user_id = session.get('user_id')
|
| 517 |
+
|
| 518 |
+
conn = sqlite3.connect('fruitsveggies.db')
|
| 519 |
+
conn.row_factory = sqlite3.Row
|
| 520 |
+
cursor = conn.cursor()
|
| 521 |
+
|
| 522 |
+
# Get user info
|
| 523 |
+
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
|
| 524 |
+
user = dict(cursor.fetchone())
|
| 525 |
+
|
| 526 |
+
if request.method == 'POST':
|
| 527 |
+
name = request.form['name']
|
| 528 |
+
email = request.form['email']
|
| 529 |
+
phone = request.form['phone']
|
| 530 |
+
address = request.form['address']
|
| 531 |
+
current_password = request.form['current_password']
|
| 532 |
+
new_password = request.form['new_password']
|
| 533 |
+
confirm_password = request.form['confirm_password']
|
| 534 |
+
|
| 535 |
+
# Verify current password
|
| 536 |
+
if not check_password_hash(user['password'], current_password):
|
| 537 |
+
flash('Current password is incorrect')
|
| 538 |
+
return render_template('edit_profile.html', user=user)
|
| 539 |
+
|
| 540 |
+
try:
|
| 541 |
+
# If new password is provided, update it
|
| 542 |
+
if new_password:
|
| 543 |
+
if new_password != confirm_password:
|
| 544 |
+
flash('New passwords do not match')
|
| 545 |
+
return render_template('edit_profile.html', user=user)
|
| 546 |
+
|
| 547 |
+
hashed_password = generate_password_hash(new_password)
|
| 548 |
+
cursor.execute(
|
| 549 |
+
"UPDATE users SET name = ?, email = ?, phone = ?, address = ?, password = ? WHERE id = ?",
|
| 550 |
+
(name, email, phone, address, hashed_password, user_id)
|
| 551 |
+
)
|
| 552 |
+
else:
|
| 553 |
+
# Otherwise just update other fields
|
| 554 |
+
cursor.execute(
|
| 555 |
+
"UPDATE users SET name = ?, email = ?, phone = ?, address = ? WHERE id = ?",
|
| 556 |
+
(name, email, phone, address, user_id)
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
conn.commit()
|
| 560 |
+
session['user_name'] = name # Update session user name
|
| 561 |
+
flash('Profile updated successfully')
|
| 562 |
+
return redirect(url_for('profile'))
|
| 563 |
+
|
| 564 |
+
except sqlite3.IntegrityError:
|
| 565 |
+
flash('Email or phone number already in use')
|
| 566 |
+
finally:
|
| 567 |
+
conn.close()
|
| 568 |
+
|
| 569 |
+
conn.close()
|
| 570 |
+
return render_template('edit_profile.html', user=user)
|
| 571 |
+
@app.route('/about')
|
| 572 |
+
def about():
|
| 573 |
+
return render_template('about.html')
|
| 574 |
+
@app.route('/contact')
|
| 575 |
+
def contact():
|
| 576 |
+
return render_template('contact.html')
|
| 577 |
+
|
| 578 |
+
if __name__ == '__main__':
|
| 579 |
+
app.run(debug=True)
|