Spaces:
Sleeping
Sleeping
Upload main.py
Browse files
main.py
CHANGED
|
@@ -9,9 +9,9 @@ import threading
|
|
| 9 |
|
| 10 |
from datetime import datetime
|
| 11 |
from zoneinfo import ZoneInfo
|
| 12 |
-
from typing import Optional, List
|
| 13 |
|
| 14 |
-
from fastapi import FastAPI, HTTPException
|
| 15 |
from pydantic import BaseModel
|
| 16 |
|
| 17 |
app = FastAPI(
|
|
@@ -41,9 +41,16 @@ site_settings = {
|
|
| 41 |
"photo_required_end": True,
|
| 42 |
"force_camera_only": True,
|
| 43 |
"allow_gallery_upload": True,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
"img_host": "https://whynotasif-telecloud-cdn.hf.space/upload",
|
| 45 |
-
"img_viewer": "https://whynotasif-telecloud-cdn.hf.space/view/"
|
| 46 |
-
"imgbb_apikeys": [] # No longer needed
|
| 47 |
}
|
| 48 |
|
| 49 |
# -------------------------
|
|
@@ -149,6 +156,149 @@ def user_has_active_session(username):
|
|
| 149 |
return None
|
| 150 |
|
| 151 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
# -------------------------
|
| 153 |
# MODELS
|
| 154 |
# -------------------------
|
|
@@ -162,6 +312,7 @@ class UserCreate(BaseModel):
|
|
| 162 |
ip_address: str
|
| 163 |
cnic_no: str
|
| 164 |
gender: str
|
|
|
|
| 165 |
full_name: str
|
| 166 |
email_address: str
|
| 167 |
contact_number: str
|
|
@@ -226,6 +377,9 @@ def add_user(data: UserCreate):
|
|
| 226 |
|
| 227 |
if data.username in users:
|
| 228 |
raise HTTPException(400, "User exists")
|
|
|
|
|
|
|
|
|
|
| 229 |
|
| 230 |
img_url = None
|
| 231 |
|
|
@@ -252,6 +406,7 @@ def add_user(data: UserCreate):
|
|
| 252 |
"union_council": data.union_council,
|
| 253 |
"full_address": data.full_address,
|
| 254 |
"is_admin": False,
|
|
|
|
| 255 |
"joining_time": date_time_now()
|
| 256 |
}
|
| 257 |
|
|
@@ -259,10 +414,14 @@ def add_user(data: UserCreate):
|
|
| 259 |
|
| 260 |
|
| 261 |
@app.delete("/users/delete")
|
| 262 |
-
def delete_user(username: str, backup: bool = True):
|
| 263 |
|
| 264 |
if username not in users:
|
| 265 |
raise HTTPException(404, "User not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
|
| 267 |
# If backup is True, prepare data for download before deleting
|
| 268 |
if backup:
|
|
@@ -280,6 +439,11 @@ def delete_user(username: str, backup: bool = True):
|
|
| 280 |
del sessions[username]
|
| 281 |
if username in fuel_record:
|
| 282 |
del fuel_record[username]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
# Return the data for download
|
| 284 |
return {
|
| 285 |
"msg": "deleted with backup",
|
|
@@ -292,6 +456,11 @@ def delete_user(username: str, backup: bool = True):
|
|
| 292 |
del sessions[username]
|
| 293 |
if username in fuel_record:
|
| 294 |
del fuel_record[username]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
return {"msg": "deleted"}
|
| 296 |
|
| 297 |
@app.get("/users/download")
|
|
@@ -372,19 +541,39 @@ def get_all_users():
|
|
| 372 |
|
| 373 |
|
| 374 |
@app.post("/users/set_admin")
|
| 375 |
-
def set_admin(username: str, value: bool):
|
| 376 |
-
|
|
|
|
|
|
|
|
|
|
| 377 |
users[username]["is_admin"] = value
|
| 378 |
-
|
|
|
|
|
|
|
| 379 |
return {"msg": "admin updated"}
|
| 380 |
|
| 381 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 382 |
@app.post("/users/update")
|
| 383 |
-
def update_user(username: str, field: str, value):
|
| 384 |
-
"""Generic admin update for arbitrary user fields
|
| 385 |
if username not in users:
|
| 386 |
raise HTTPException(404, "User not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
users[username][field] = value
|
|
|
|
|
|
|
|
|
|
| 388 |
return {"msg": "updated"}
|
| 389 |
|
| 390 |
# -------------------------
|
|
@@ -441,6 +630,9 @@ def new_session(data: SessionCreate):
|
|
| 441 |
"remarks": data.remarks
|
| 442 |
}
|
| 443 |
|
|
|
|
|
|
|
|
|
|
| 444 |
return {"session_id": sid}
|
| 445 |
|
| 446 |
|
|
@@ -479,16 +671,10 @@ def add_point(data: PointCreate):
|
|
| 479 |
|
| 480 |
s["points"].append(point)
|
| 481 |
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
#admin-panel
|
| 485 |
-
@app.post("/session/update")
|
| 486 |
-
def update_session(session_id: str, field: str, value):
|
| 487 |
-
|
| 488 |
-
sessions[session_id][field] = value
|
| 489 |
-
|
| 490 |
-
return {"msg": "updated"}
|
| 491 |
|
|
|
|
| 492 |
|
| 493 |
@app.post("/session/end")
|
| 494 |
def end_session(data: EndSession):
|
|
@@ -528,37 +714,83 @@ def end_session(data: EndSession):
|
|
| 528 |
s["total_km"] = total
|
| 529 |
s["ongoing"] = False
|
| 530 |
|
|
|
|
|
|
|
|
|
|
| 531 |
return {"total_km": total}
|
| 532 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 533 |
|
| 534 |
-
# administrative helpers for sessions/points
|
| 535 |
@app.delete("/session/delete")
|
| 536 |
-
def delete_session(session_id: str):
|
| 537 |
if session_id not in sessions:
|
| 538 |
raise HTTPException(404, "Session not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 539 |
del sessions[session_id]
|
|
|
|
|
|
|
|
|
|
| 540 |
return {"msg": "deleted"}
|
| 541 |
|
| 542 |
|
| 543 |
@app.post("/session/point/update")
|
| 544 |
-
def update_point(session_id: str, index: int, field: str, value):
|
| 545 |
if session_id not in sessions:
|
| 546 |
raise HTTPException(404, "Session not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 547 |
pts = sessions[session_id].get("points", [])
|
| 548 |
if index < 0 or index >= len(pts):
|
| 549 |
raise HTTPException(404, "Point not found")
|
| 550 |
pts[index][field] = value
|
|
|
|
|
|
|
|
|
|
| 551 |
return {"msg": "updated"}
|
| 552 |
|
| 553 |
|
| 554 |
@app.delete("/session/point/delete")
|
| 555 |
-
def delete_point(session_id: str, index: int):
|
| 556 |
if session_id not in sessions:
|
| 557 |
raise HTTPException(404, "Session not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 558 |
pts = sessions[session_id].get("points", [])
|
| 559 |
if index < 0 or index >= len(pts):
|
| 560 |
raise HTTPException(404, "Point not found")
|
| 561 |
pts.pop(index)
|
|
|
|
|
|
|
|
|
|
| 562 |
return {"msg": "deleted"}
|
| 563 |
|
| 564 |
|
|
@@ -598,6 +830,10 @@ def add_fuel(username: str, record: EnergyRecord, timestamp: Optional[str] = Non
|
|
| 598 |
if rec.get("liters") is not None and rec.get("price_per_liter") is not None and rec.get("total_cost") is None:
|
| 599 |
rec["total_cost"] = rec["liters"] * rec["price_per_liter"]
|
| 600 |
fuel_record[username][timestamp] = rec
|
|
|
|
|
|
|
|
|
|
|
|
|
| 601 |
return {"timestamp": timestamp}
|
| 602 |
|
| 603 |
|
|
@@ -630,17 +866,34 @@ def get_fuel_of_user(username: str):
|
|
| 630 |
return fuel_record.get(username, {})
|
| 631 |
|
| 632 |
@app.post("/fuel/update")
|
| 633 |
-
def update_fuel(username: str, timestamp: str, field: str, value):
|
| 634 |
if username not in fuel_record or timestamp not in fuel_record[username]:
|
| 635 |
raise HTTPException(404, "Record not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 636 |
fuel_record[username][timestamp][field] = value
|
|
|
|
|
|
|
|
|
|
| 637 |
return {"msg": "updated"}
|
| 638 |
|
|
|
|
| 639 |
@app.delete("/fuel/delete")
|
| 640 |
-
def delete_fuel(username: str, timestamp: str):
|
| 641 |
if username not in fuel_record or timestamp not in fuel_record[username]:
|
| 642 |
raise HTTPException(404, "Record not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 643 |
del fuel_record[username][timestamp]
|
|
|
|
|
|
|
|
|
|
| 644 |
return {"msg": "deleted"}
|
| 645 |
|
| 646 |
# -------------------------
|
|
@@ -654,13 +907,116 @@ def get_settings():
|
|
| 654 |
|
| 655 |
|
| 656 |
@app.post("/settings/update")
|
| 657 |
-
def update_setting(key: str, value):
|
| 658 |
-
|
|
|
|
|
|
|
|
|
|
| 659 |
site_settings[key] = value
|
| 660 |
|
|
|
|
|
|
|
|
|
|
| 661 |
return {"msg": "updated"}
|
| 662 |
|
| 663 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 664 |
# -------------------------
|
| 665 |
# REMOTE SYNC HELPERS
|
| 666 |
# -------------------------
|
|
|
|
| 9 |
|
| 10 |
from datetime import datetime
|
| 11 |
from zoneinfo import ZoneInfo
|
| 12 |
+
from typing import Optional, List, Dict
|
| 13 |
|
| 14 |
+
from fastapi import FastAPI, HTTPException, Request
|
| 15 |
from pydantic import BaseModel
|
| 16 |
|
| 17 |
app = FastAPI(
|
|
|
|
| 41 |
"photo_required_end": True,
|
| 42 |
"force_camera_only": True,
|
| 43 |
"allow_gallery_upload": True,
|
| 44 |
+
"allow_delete_session": True,
|
| 45 |
+
"allow_delete_fuel": True,
|
| 46 |
+
"allow_delete_user": True,
|
| 47 |
+
"allow_ai": True,
|
| 48 |
+
"logs": [],
|
| 49 |
+
"available_companies": [
|
| 50 |
+
"snip"
|
| 51 |
+
],
|
| 52 |
"img_host": "https://whynotasif-telecloud-cdn.hf.space/upload",
|
| 53 |
+
"img_viewer": "https://whynotasif-telecloud-cdn.hf.space/view/"
|
|
|
|
| 54 |
}
|
| 55 |
|
| 56 |
# -------------------------
|
|
|
|
| 156 |
return None
|
| 157 |
|
| 158 |
|
| 159 |
+
def get_user_company(username: str) -> Optional[str]:
|
| 160 |
+
"""Get company of a user"""
|
| 161 |
+
if username in users:
|
| 162 |
+
return users[username].get("company")
|
| 163 |
+
return None
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def filter_sessions_by_company(request_by: str, target_company: str = None) -> Dict:
|
| 167 |
+
"""Filter sessions by company for admin/owner view"""
|
| 168 |
+
result = {}
|
| 169 |
+
requester_company = get_user_company(request_by)
|
| 170 |
+
|
| 171 |
+
# Only allow if requester is admin/owner
|
| 172 |
+
if request_by not in users or not (users[request_by].get("is_admin") or users[request_by].get("is_owner")):
|
| 173 |
+
raise HTTPException(403, "Not authorized")
|
| 174 |
+
|
| 175 |
+
for sid, session in sessions.items():
|
| 176 |
+
session_company = get_user_company(session["username"])
|
| 177 |
+
|
| 178 |
+
# If requester is owner of a company, show only their company sessions
|
| 179 |
+
if users[request_by].get("is_owner") and requester_company:
|
| 180 |
+
if session_company == requester_company:
|
| 181 |
+
result[sid] = session
|
| 182 |
+
# If target_company is specified, filter by that
|
| 183 |
+
elif target_company and session_company == target_company:
|
| 184 |
+
result[sid] = session
|
| 185 |
+
# Otherwise show all (but only for super admin)
|
| 186 |
+
elif not target_company:
|
| 187 |
+
result[sid] = session
|
| 188 |
+
|
| 189 |
+
return result
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def filter_users_by_company(request_by: str, target_company: str = None) -> Dict:
|
| 193 |
+
"""Filter users by company for admin/owner view"""
|
| 194 |
+
result = {}
|
| 195 |
+
|
| 196 |
+
# Only allow if requester is admin/owner
|
| 197 |
+
if request_by not in users or not (users[request_by].get("is_admin") or users[request_by].get("is_owner")):
|
| 198 |
+
raise HTTPException(403, "Not authorized")
|
| 199 |
+
|
| 200 |
+
requester_company = get_user_company(request_by)
|
| 201 |
+
|
| 202 |
+
for username, user in users.items():
|
| 203 |
+
user_company = user.get("company")
|
| 204 |
+
|
| 205 |
+
# If requester is owner of a company, show only their company users
|
| 206 |
+
if users[request_by].get("is_owner") and requester_company:
|
| 207 |
+
if user_company == requester_company:
|
| 208 |
+
result[username] = user
|
| 209 |
+
# If target_company is specified, filter by that
|
| 210 |
+
elif target_company and user_company == target_company:
|
| 211 |
+
result[username] = user
|
| 212 |
+
# Otherwise show all (but only for super admin)
|
| 213 |
+
elif not target_company:
|
| 214 |
+
result[username] = user
|
| 215 |
+
|
| 216 |
+
return result
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def filter_fuel_by_company(request_by: str, target_company: str = None) -> Dict:
|
| 220 |
+
"""Filter fuel records by company for admin/owner view"""
|
| 221 |
+
result = {}
|
| 222 |
+
|
| 223 |
+
# Only allow if requester is admin/owner
|
| 224 |
+
if request_by not in users or not (users[request_by].get("is_admin") or users[request_by].get("is_owner")):
|
| 225 |
+
raise HTTPException(403, "Not authorized")
|
| 226 |
+
|
| 227 |
+
requester_company = get_user_company(request_by)
|
| 228 |
+
|
| 229 |
+
for username, fuel_records in fuel_record.items():
|
| 230 |
+
user_company = get_user_company(username)
|
| 231 |
+
|
| 232 |
+
# If requester is owner of a company, show only their company fuel records
|
| 233 |
+
if users[request_by].get("is_owner") and requester_company:
|
| 234 |
+
if user_company == requester_company:
|
| 235 |
+
result[username] = fuel_records
|
| 236 |
+
# If target_company is specified, filter by that
|
| 237 |
+
elif target_company and user_company == target_company:
|
| 238 |
+
result[username] = fuel_records
|
| 239 |
+
# Otherwise show all (but only for super admin)
|
| 240 |
+
elif not target_company:
|
| 241 |
+
result[username] = fuel_records
|
| 242 |
+
|
| 243 |
+
return result
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def is_owner(request_by: str) -> bool:
|
| 247 |
+
"""Check if user is owner"""
|
| 248 |
+
if request_by in users:
|
| 249 |
+
return users[request_by].get("is_owner", False)
|
| 250 |
+
return False
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def can_delete_sessions(request_by: str) -> bool:
|
| 254 |
+
"""Check if user can delete sessions based on settings"""
|
| 255 |
+
if is_owner(request_by):
|
| 256 |
+
return True
|
| 257 |
+
return site_settings.get("allow_delete_session", False)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def can_delete_fuel(request_by: str) -> bool:
|
| 261 |
+
"""Check if user can delete fuel based on settings"""
|
| 262 |
+
if is_owner(request_by):
|
| 263 |
+
return True
|
| 264 |
+
return site_settings.get("allow_delete_fuel", False)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def can_delete_user(request_by: str) -> bool:
|
| 268 |
+
"""Check if user can delete users based on settings"""
|
| 269 |
+
if is_owner(request_by):
|
| 270 |
+
return True
|
| 271 |
+
return site_settings.get("allow_delete_user", False)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def add_log(request_by: str, action: str, details: str = ""):
|
| 275 |
+
"""Add an action log entry"""
|
| 276 |
+
log_entry = {
|
| 277 |
+
"time": date_time_now(),
|
| 278 |
+
"by": request_by,
|
| 279 |
+
"action": action,
|
| 280 |
+
"details": details
|
| 281 |
+
}
|
| 282 |
+
site_settings["logs"].append(log_entry)
|
| 283 |
+
# Keep only last 1000 logs
|
| 284 |
+
if len(site_settings["logs"]) > 1000:
|
| 285 |
+
site_settings["logs"] = site_settings["logs"][-1000:]
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def can_delete_fuel(request_by: str) -> bool:
|
| 289 |
+
"""Check if user can delete fuel based on settings"""
|
| 290 |
+
if is_owner(request_by):
|
| 291 |
+
return True
|
| 292 |
+
return site_settings.get("allow_delete_fuel", False)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def can_delete_user(request_by: str) -> bool:
|
| 296 |
+
"""Check if user can delete users based on settings"""
|
| 297 |
+
if is_owner(request_by):
|
| 298 |
+
return True
|
| 299 |
+
return site_settings.get("allow_delete_user", False)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
# -------------------------
|
| 303 |
# MODELS
|
| 304 |
# -------------------------
|
|
|
|
| 312 |
ip_address: str
|
| 313 |
cnic_no: str
|
| 314 |
gender: str
|
| 315 |
+
company: str
|
| 316 |
full_name: str
|
| 317 |
email_address: str
|
| 318 |
contact_number: str
|
|
|
|
| 377 |
|
| 378 |
if data.username in users:
|
| 379 |
raise HTTPException(400, "User exists")
|
| 380 |
+
|
| 381 |
+
if data.company not in site_settings["available_companies"]:
|
| 382 |
+
raise HTTPException(400, "Company Not exists")
|
| 383 |
|
| 384 |
img_url = None
|
| 385 |
|
|
|
|
| 406 |
"union_council": data.union_council,
|
| 407 |
"full_address": data.full_address,
|
| 408 |
"is_admin": False,
|
| 409 |
+
"is_owner": False,
|
| 410 |
"joining_time": date_time_now()
|
| 411 |
}
|
| 412 |
|
|
|
|
| 414 |
|
| 415 |
|
| 416 |
@app.delete("/users/delete")
|
| 417 |
+
def delete_user(username: str, backup: bool = True, request_by: str = ""):
|
| 418 |
|
| 419 |
if username not in users:
|
| 420 |
raise HTTPException(404, "User not found")
|
| 421 |
+
|
| 422 |
+
# Check permission - only owner can delete users
|
| 423 |
+
if request_by and not can_delete_user(request_by):
|
| 424 |
+
raise HTTPException(403, "Not authorized to delete users")
|
| 425 |
|
| 426 |
# If backup is True, prepare data for download before deleting
|
| 427 |
if backup:
|
|
|
|
| 439 |
del sessions[username]
|
| 440 |
if username in fuel_record:
|
| 441 |
del fuel_record[username]
|
| 442 |
+
|
| 443 |
+
# Log the action
|
| 444 |
+
if request_by:
|
| 445 |
+
add_log(request_by, "delete_user", f"Deleted user {username} with backup")
|
| 446 |
+
|
| 447 |
# Return the data for download
|
| 448 |
return {
|
| 449 |
"msg": "deleted with backup",
|
|
|
|
| 456 |
del sessions[username]
|
| 457 |
if username in fuel_record:
|
| 458 |
del fuel_record[username]
|
| 459 |
+
|
| 460 |
+
# Log the action
|
| 461 |
+
if request_by:
|
| 462 |
+
add_log(request_by, "delete_user", f"Deleted user {username} permanently (no backup)")
|
| 463 |
+
|
| 464 |
return {"msg": "deleted"}
|
| 465 |
|
| 466 |
@app.get("/users/download")
|
|
|
|
| 541 |
|
| 542 |
|
| 543 |
@app.post("/users/set_admin")
|
| 544 |
+
def set_admin(username: str, value: bool, request_by: str):
|
| 545 |
+
"""Set user as admin - only owner can do this"""
|
| 546 |
+
if not is_owner(request_by):
|
| 547 |
+
raise HTTPException(403, "Only owners can set admins")
|
| 548 |
+
|
| 549 |
users[username]["is_admin"] = value
|
| 550 |
+
|
| 551 |
+
# Log the action
|
| 552 |
+
add_log(request_by, "set_admin", f"Set {username} as admin: {value}")
|
| 553 |
return {"msg": "admin updated"}
|
| 554 |
|
| 555 |
|
| 556 |
+
@app.post("/users/set_owner")
|
| 557 |
+
def set_owner(username: str, value: bool):
|
| 558 |
+
"""Set user as owner - can only be done directly"""
|
| 559 |
+
users[username]["is_owner"] = value
|
| 560 |
+
return {"msg": "owner updated"}
|
| 561 |
+
|
| 562 |
+
|
| 563 |
@app.post("/users/update")
|
| 564 |
+
def update_user(username: str, field: str, value, request_by: str):
|
| 565 |
+
"""Generic admin update for arbitrary user fields - only owner can update other users"""
|
| 566 |
if username not in users:
|
| 567 |
raise HTTPException(404, "User not found")
|
| 568 |
+
|
| 569 |
+
# Only owner can update other users
|
| 570 |
+
if not is_owner(request_by):
|
| 571 |
+
raise HTTPException(403, "Only owners can update users")
|
| 572 |
+
|
| 573 |
users[username][field] = value
|
| 574 |
+
|
| 575 |
+
# Log the action
|
| 576 |
+
add_log(request_by, "update_user", f"Updated {field} to '{value}' for user {username}")
|
| 577 |
return {"msg": "updated"}
|
| 578 |
|
| 579 |
# -------------------------
|
|
|
|
| 630 |
"remarks": data.remarks
|
| 631 |
}
|
| 632 |
|
| 633 |
+
# Log the action
|
| 634 |
+
add_log(data.username, "session_start", f"Started new session {sid} with {data.start_km}km")
|
| 635 |
+
|
| 636 |
return {"session_id": sid}
|
| 637 |
|
| 638 |
|
|
|
|
| 671 |
|
| 672 |
s["points"].append(point)
|
| 673 |
|
| 674 |
+
# Log the action
|
| 675 |
+
add_log(s["username"], "session_add_point", f"Added checkpoint at {data.village} ({data.km}km) to session {data.session_id}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 676 |
|
| 677 |
+
return {"msg": "point added"}
|
| 678 |
|
| 679 |
@app.post("/session/end")
|
| 680 |
def end_session(data: EndSession):
|
|
|
|
| 714 |
s["total_km"] = total
|
| 715 |
s["ongoing"] = False
|
| 716 |
|
| 717 |
+
# Log the action
|
| 718 |
+
add_log(s["username"], "session_end", f"Ended session {data.session_id} at {data.end_km}km ({total}km total)")
|
| 719 |
+
|
| 720 |
return {"total_km": total}
|
| 721 |
|
| 722 |
+
#admin-panel from owner - only owner can update sessions
|
| 723 |
+
@app.post("/session/update")
|
| 724 |
+
def update_session(session_id: str, field: str, value, request_by: str):
|
| 725 |
+
if session_id not in sessions:
|
| 726 |
+
raise HTTPException(404, "Session not found")
|
| 727 |
+
|
| 728 |
+
# Only owner can update sessions
|
| 729 |
+
if not is_owner(request_by):
|
| 730 |
+
raise HTTPException(403, "Only owners can update sessions")
|
| 731 |
+
|
| 732 |
+
sessions[session_id][field] = value
|
| 733 |
+
|
| 734 |
+
# Log the action
|
| 735 |
+
add_log(request_by, "update_session", f"Updated {field} for session {session_id}")
|
| 736 |
+
|
| 737 |
+
return {"msg": "updated"}
|
| 738 |
+
|
| 739 |
|
| 740 |
+
# administrative helpers for sessions/points - owner only
|
| 741 |
@app.delete("/session/delete")
|
| 742 |
+
def delete_session(session_id: str, request_by: str):
|
| 743 |
if session_id not in sessions:
|
| 744 |
raise HTTPException(404, "Session not found")
|
| 745 |
+
|
| 746 |
+
# Only owner can delete sessions
|
| 747 |
+
if not can_delete_sessions(request_by):
|
| 748 |
+
raise HTTPException(403, "Not authorized to delete sessions")
|
| 749 |
+
|
| 750 |
+
# Get session info for logging
|
| 751 |
+
session_username = sessions[session_id].get("username", "unknown")
|
| 752 |
del sessions[session_id]
|
| 753 |
+
|
| 754 |
+
# Log the action
|
| 755 |
+
add_log(request_by, "delete_session", f"Deleted session {session_id} for user {session_username}")
|
| 756 |
return {"msg": "deleted"}
|
| 757 |
|
| 758 |
|
| 759 |
@app.post("/session/point/update")
|
| 760 |
+
def update_point(session_id: str, index: int, field: str, value, request_by: str):
|
| 761 |
if session_id not in sessions:
|
| 762 |
raise HTTPException(404, "Session not found")
|
| 763 |
+
|
| 764 |
+
# Only owner can update points
|
| 765 |
+
if not is_owner(request_by):
|
| 766 |
+
raise HTTPException(403, "Only owners can update points")
|
| 767 |
+
|
| 768 |
pts = sessions[session_id].get("points", [])
|
| 769 |
if index < 0 or index >= len(pts):
|
| 770 |
raise HTTPException(404, "Point not found")
|
| 771 |
pts[index][field] = value
|
| 772 |
+
|
| 773 |
+
# Log the action
|
| 774 |
+
add_log(request_by, "update_point", f"Updated point {index} field '{field}' in session {session_id}")
|
| 775 |
return {"msg": "updated"}
|
| 776 |
|
| 777 |
|
| 778 |
@app.delete("/session/point/delete")
|
| 779 |
+
def delete_point(session_id: str, index: int, request_by: str):
|
| 780 |
if session_id not in sessions:
|
| 781 |
raise HTTPException(404, "Session not found")
|
| 782 |
+
|
| 783 |
+
# Only owner can delete points
|
| 784 |
+
if not is_owner(request_by):
|
| 785 |
+
raise HTTPException(403, "Only owners can delete points")
|
| 786 |
+
|
| 787 |
pts = sessions[session_id].get("points", [])
|
| 788 |
if index < 0 or index >= len(pts):
|
| 789 |
raise HTTPException(404, "Point not found")
|
| 790 |
pts.pop(index)
|
| 791 |
+
|
| 792 |
+
# Log the action
|
| 793 |
+
add_log(request_by, "delete_point", f"Deleted point {index} from session {session_id}")
|
| 794 |
return {"msg": "deleted"}
|
| 795 |
|
| 796 |
|
|
|
|
| 830 |
if rec.get("liters") is not None and rec.get("price_per_liter") is not None and rec.get("total_cost") is None:
|
| 831 |
rec["total_cost"] = rec["liters"] * rec["price_per_liter"]
|
| 832 |
fuel_record[username][timestamp] = rec
|
| 833 |
+
|
| 834 |
+
# Log the action
|
| 835 |
+
add_log(username, "fuel_add", f"Added fuel record: {rec.get('liters', 0)}L at {rec.get('station', 'Unknown')} (${rec.get('total_cost', 0)})")
|
| 836 |
+
|
| 837 |
return {"timestamp": timestamp}
|
| 838 |
|
| 839 |
|
|
|
|
| 866 |
return fuel_record.get(username, {})
|
| 867 |
|
| 868 |
@app.post("/fuel/update")
|
| 869 |
+
def update_fuel(username: str, timestamp: str, field: str, value, request_by: str):
|
| 870 |
if username not in fuel_record or timestamp not in fuel_record[username]:
|
| 871 |
raise HTTPException(404, "Record not found")
|
| 872 |
+
|
| 873 |
+
# Only owner can update fuel
|
| 874 |
+
if not is_owner(request_by):
|
| 875 |
+
raise HTTPException(403, "Only owners can update fuel records")
|
| 876 |
+
|
| 877 |
fuel_record[username][timestamp][field] = value
|
| 878 |
+
|
| 879 |
+
# Log the action
|
| 880 |
+
add_log(request_by, "update_fuel", f"Updated {field} for {username}'s fuel record at {timestamp}")
|
| 881 |
return {"msg": "updated"}
|
| 882 |
|
| 883 |
+
|
| 884 |
@app.delete("/fuel/delete")
|
| 885 |
+
def delete_fuel(username: str, timestamp: str, request_by: str):
|
| 886 |
if username not in fuel_record or timestamp not in fuel_record[username]:
|
| 887 |
raise HTTPException(404, "Record not found")
|
| 888 |
+
|
| 889 |
+
# Only owner can delete fuel based on settings
|
| 890 |
+
if not can_delete_fuel(request_by):
|
| 891 |
+
raise HTTPException(403, "Not authorized to delete fuel records")
|
| 892 |
+
|
| 893 |
del fuel_record[username][timestamp]
|
| 894 |
+
|
| 895 |
+
# Log the action
|
| 896 |
+
add_log(request_by, "delete_fuel", f"Deleted fuel record for {username} at {timestamp}")
|
| 897 |
return {"msg": "deleted"}
|
| 898 |
|
| 899 |
# -------------------------
|
|
|
|
| 907 |
|
| 908 |
|
| 909 |
@app.post("/settings/update")
|
| 910 |
+
def update_setting(key: str, value, request_by: str):
|
| 911 |
+
"""Update site settings - only owner can do this"""
|
| 912 |
+
if not is_owner(request_by):
|
| 913 |
+
raise HTTPException(403, "Only owners can update settings")
|
| 914 |
+
|
| 915 |
site_settings[key] = value
|
| 916 |
|
| 917 |
+
# Log the action
|
| 918 |
+
add_log(request_by, "settings_update", f"Updated setting '{key}' to '{value}'")
|
| 919 |
+
|
| 920 |
return {"msg": "updated"}
|
| 921 |
|
| 922 |
|
| 923 |
+
# -------------------------
|
| 924 |
+
# COMPANY FILTERED ENDPOINTS (for admin panel)
|
| 925 |
+
# -------------------------
|
| 926 |
+
|
| 927 |
+
@app.get("/admin/sessions")
|
| 928 |
+
def get_admin_sessions(request_by: str):
|
| 929 |
+
"""Get all sessions filtered by requester's company - for admin panel"""
|
| 930 |
+
return filter_sessions_by_company(request_by)
|
| 931 |
+
|
| 932 |
+
|
| 933 |
+
@app.get("/admin/users")
|
| 934 |
+
def get_admin_users(request_by: str):
|
| 935 |
+
"""Get all users filtered by requester's company - for admin panel"""
|
| 936 |
+
return filter_users_by_company(request_by)
|
| 937 |
+
|
| 938 |
+
|
| 939 |
+
@app.get("/admin/fuel")
|
| 940 |
+
def get_admin_fuel(request_by: str):
|
| 941 |
+
"""Get all fuel records filtered by requester's company - for admin panel"""
|
| 942 |
+
return filter_fuel_by_company(request_by)
|
| 943 |
+
|
| 944 |
+
|
| 945 |
+
# -------------------------
|
| 946 |
+
# AI CHAT ENDPOINT (for visitors)
|
| 947 |
+
# -------------------------
|
| 948 |
+
|
| 949 |
+
@app.post("/ai/chat")
|
| 950 |
+
def chat_with_ai(message: str):
|
| 951 |
+
"""Chat with AI - limit is handled on frontend via localStorage"""
|
| 952 |
+
|
| 953 |
+
# Check if AI is allowed
|
| 954 |
+
if not site_settings.get("allow_ai", False):
|
| 955 |
+
raise HTTPException(403, "AI chat is not available")
|
| 956 |
+
|
| 957 |
+
# Simple AI response - in production, you would integrate with an actual AI API
|
| 958 |
+
# For now, return a helpful response based on the message
|
| 959 |
+
response = generate_ai_response(message)
|
| 960 |
+
|
| 961 |
+
return {
|
| 962 |
+
"response": response
|
| 963 |
+
}
|
| 964 |
+
|
| 965 |
+
|
| 966 |
+
def generate_ai_response(message: str) -> str:
|
| 967 |
+
"""Generate a simple AI response based on the message"""
|
| 968 |
+
message_lower = message.lower()
|
| 969 |
+
|
| 970 |
+
# Greetings
|
| 971 |
+
if any(word in message_lower for word in ["hello", "hi", "hey", "greetings"]):
|
| 972 |
+
return "Hello! I'm here to help you with DriveLedger. You can ask me about starting a session, recording fuel, or using the features. How can I assist you today?"
|
| 973 |
+
|
| 974 |
+
# Help with sessions
|
| 975 |
+
if "session" in message_lower or "start" in message_lower or "drive" in message_lower:
|
| 976 |
+
return "To start a driving session: 1) Login to your account 2) Go to 'Start Session' 3) Take a photo of your odometer 4) Enter the starting KM 5) Click Start. The system will track your trip with GPS and photos."
|
| 977 |
+
|
| 978 |
+
# Help with fuel
|
| 979 |
+
if "fuel" in message_lower or "petrol" in message_lower or "diesel" in message_lower:
|
| 980 |
+
return "To record fuel: Go to 'Fuel Records' in your dashboard. Enter the fuel type, liters, price per liter, and optionally upload a receipt photo. The system will calculate the total cost automatically."
|
| 981 |
+
|
| 982 |
+
# Help with login/signup
|
| 983 |
+
if "login" in message_lower or "sign up" in message_lower or "register" in message_lower:
|
| 984 |
+
return "To get started: Click 'Sign Up' on the home page. Fill in your details including your company name, vehicle number, and location. You'll need a profile picture and your CNIC number."
|
| 985 |
+
|
| 986 |
+
# Help with admin
|
| 987 |
+
if "admin" in message_lower or "manage" in message_lower:
|
| 988 |
+
return "Admin features include: viewing all users and sessions, fuel records management, and data export. Contact your administrator for access."
|
| 989 |
+
|
| 990 |
+
# Help with export
|
| 991 |
+
if "export" in message_lower or "download" in message_lower:
|
| 992 |
+
return "To export your data: Go to 'Export Data' in your dashboard. You can download your session history and fuel records in various formats."
|
| 993 |
+
|
| 994 |
+
# Default response
|
| 995 |
+
return "I'm here to help with DriveLedger! Ask me about:\n- Starting a driving session\n- Recording fuel entries\n- Login and registration\n- Admin features\n- Data export\n\nWhat would you like to know?"
|
| 996 |
+
|
| 997 |
+
|
| 998 |
+
# -------------------------
|
| 999 |
+
# LOGS ENDPOINTS
|
| 1000 |
+
# -------------------------
|
| 1001 |
+
|
| 1002 |
+
@app.get("/logs")
|
| 1003 |
+
def get_logs(request_by: str):
|
| 1004 |
+
"""Get all logs - only owner can view"""
|
| 1005 |
+
if not is_owner(request_by):
|
| 1006 |
+
raise HTTPException(403, "Only owners can view logs")
|
| 1007 |
+
return site_settings.get("logs", [])
|
| 1008 |
+
|
| 1009 |
+
|
| 1010 |
+
@app.delete("/logs/clear")
|
| 1011 |
+
def clear_logs(request_by: str):
|
| 1012 |
+
"""Clear all logs - only owner can do this"""
|
| 1013 |
+
if not is_owner(request_by):
|
| 1014 |
+
raise HTTPException(403, "Only owners can clear logs")
|
| 1015 |
+
site_settings["logs"] = []
|
| 1016 |
+
add_log(request_by, "clear_logs", "All logs cleared")
|
| 1017 |
+
return {"msg": "logs cleared"}
|
| 1018 |
+
|
| 1019 |
+
|
| 1020 |
# -------------------------
|
| 1021 |
# REMOTE SYNC HELPERS
|
| 1022 |
# -------------------------
|