File size: 11,024 Bytes
3a1c84c 86369aa 3a1c84c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 | """Mock data & business logic for Streamlit Hostel MS."""
import copy
import math
import random
from datetime import date, datetime
DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
STATUS_MAP = {0: "Pending", 1: "In Progress", 2: "Resolved"}
def seed_data():
random.seed(42)
rooms = []
for i in range(15):
ac = i % 3 == 0
cap = 2 if i % 2 == 0 else 4
rooms.append({
"id": i + 1, "number": f"R-{101 + i:03d}", "floor": i // 5 + 1,
"type": "2-seater" if i % 2 == 0 else "4-seater", "ac": ac,
"capacity": cap, "occupied": 0, "rent": 18000 if ac else 12000,
"active": True,
})
names = [
"Ali Hassan", "Fatima Malik", "Usman Ahmed", "Ayesha Khan", "Bilal Raza",
"Hamza Younas", "Abdullah Khan", "Sana Iqbal", "Zain Butt", "Hira Nawaz",
]
students = []
for i, name in enumerate(names):
students.append({
"id": i + 1, "name": name, "roll": f"UCP-BSAI-{1001 + i}",
"phone": f"0300-{1000000 + i:07d}", "emergency": f"Parent {i + 1}",
"password": "student123", "room_id": i + 1, "active": True,
"rent_due": rooms[i]["rent"], "mess_due": 8500, "utility_due": 1500,
"rent_paid": i % 3 != 0, "mess_paid": i % 4 != 0,
"last_pay_date": "2026-05-15", "mess_off_days": 0,
})
rooms[i]["occupied"] = 1
mess = []
for d in range(7):
mess.append({
"day": DAYS[d],
"breakfast": "Paratha + Omelette + Tea",
"lunch": "Biryani + Raita",
"dinner": "Karahi + Naan",
})
complaints = [
{"id": 1, "student_idx": 0, "text": "Wi-Fi not working in Room R-101", "status": 0,
"created": "2026-06-10"},
{"id": 2, "student_idx": 3, "text": "Ceiling fan making noise", "status": 1,
"created": "2026-06-12"},
{"id": 3, "student_idx": 5, "text": "Water heater not heating properly", "status": 0,
"created": "2026-06-14"},
]
gate_logs = [
{"id": 1, "student_idx": 0, "type": "OUT", "time": "2026-06-15 08:30"},
{"id": 2, "student_idx": 0, "type": "IN", "time": "2026-06-15 18:45"},
{"id": 3, "student_idx": 5, "type": "OUT", "time": "2026-06-15 09:15"},
]
attendance = [
{"student_idx": i, "date": str(date.today()), "present": i % 5 != 0}
for i in range(10)
]
announcements = [
{"id": 1, "title": "Mess Timings Updated",
"body": "Dinner will be served 7:00β9:00 PM during exam week.",
"date": "2026-06-14", "priority": "high"},
{"id": 2, "title": "Fee Deadline Reminder",
"body": "Please clear pending dues before June 30 to avoid fine.",
"date": "2026-06-13", "priority": "medium"},
{"id": 3, "title": "Guest Policy",
"body": "Visitors allowed only in common room until 6 PM.",
"date": "2026-06-10", "priority": "low"},
]
payment_history = [
{"student_idx": 1, "type": "Rent", "amount": 18000, "date": "2026-05-01"},
{"student_idx": 1, "type": "Mess", "amount": 8500, "date": "2026-05-01"},
{"student_idx": 4, "type": "Rent", "amount": 12000, "date": "2026-05-03"},
]
return {
"rooms": rooms,
"students": students,
"mess": mess,
"complaints": complaints,
"gate_logs": gate_logs,
"attendance": attendance,
"announcements": announcements,
"payment_history": payment_history,
}
def fresh_state():
return copy.deepcopy(seed_data())
def find_student(students, roll):
for i, s in enumerate(students):
if s["active"] and s["roll"] == roll:
return i
return -1
def find_room(rooms, number):
for i, r in enumerate(rooms):
if r["active"] and r["number"].upper() == number.upper():
return i
return -1
def room_status(r):
if r["occupied"] == 0:
return "Vacant"
if r["occupied"] < r["capacity"]:
return "Partial"
return "Full"
def pay_label(paid):
return "Paid" if paid else "Due"
def calc_score(student, work=80000):
total = 0.0
for w in range(work):
total += math.sin(student["rent_due"] * w * 0.0001)
total += math.cos(student["mess_due"] + w * 0.001)
if not student["rent_paid"]:
total += 5000
if not student["mess_paid"]:
total += 3000
return total
def match_student(student, key):
if not student["active"]:
return False
k = key.lower()
return k in student["name"].lower() or k in student["roll"].lower()
def record_payment(db, idx, pay_rent, pay_mess):
s = db["students"][idx]
today = str(date.today())
if pay_rent and not s["rent_paid"]:
s["rent_paid"] = True
db["payment_history"].append({
"student_idx": idx, "type": "Rent", "amount": s["rent_due"], "date": today,
})
if pay_mess and not s["mess_paid"]:
s["mess_paid"] = True
db["payment_history"].append({
"student_idx": idx, "type": "Mess", "amount": s["mess_due"], "date": today,
})
s["last_pay_date"] = today
def add_student(db, name, roll, phone, room_number, password="student123"):
if find_student(db["students"], roll) >= 0:
return False, "Roll number already exists"
ri = find_room(db["rooms"], room_number)
if ri < 0:
return False, "Room not found"
room = db["rooms"][ri]
if room["occupied"] >= room["capacity"]:
return False, "Room is full"
idx = len(db["students"])
db["students"].append({
"id": idx + 1, "name": name, "roll": roll, "phone": phone,
"emergency": "Not set", "password": password, "room_id": room["id"],
"active": True, "rent_due": room["rent"], "mess_due": 8500,
"utility_due": 1500, "rent_paid": False, "mess_paid": False,
"last_pay_date": "-", "mess_off_days": 0,
})
room["occupied"] += 1
return True, f"Student {name} enrolled in {room['number']}"
def assign_room(db, roll, room_number):
si = find_student(db["students"], roll)
if si < 0:
return False, "Student not found"
ri = find_room(db["rooms"], room_number)
if ri < 0:
return False, "Room not found"
student = db["students"][si]
new_room = db["rooms"][ri]
if new_room["occupied"] >= new_room["capacity"]:
return False, "Target room is full"
if student["room_id"] > 0:
for r in db["rooms"]:
if r["id"] == student["room_id"] and r["occupied"] > 0:
r["occupied"] -= 1
student["room_id"] = new_room["id"]
student["rent_due"] = new_room["rent"]
new_room["occupied"] += 1
return True, f"Assigned {student['name']} to {new_room['number']}"
def add_gate_log(db, student_idx, log_type):
db["gate_logs"].append({
"id": len(db["gate_logs"]) + 1,
"student_idx": student_idx,
"type": log_type,
"time": datetime.now().strftime("%Y-%m-%d %H:%M"),
})
def mark_attendance(db, student_idx, present):
today = str(date.today())
for rec in db["attendance"]:
if rec["student_idx"] == student_idx and rec["date"] == today:
rec["present"] = present
return
db["attendance"].append({"student_idx": student_idx, "date": today, "present": present})
def add_announcement(db, title, body, priority="medium"):
db["announcements"].insert(0, {
"id": len(db["announcements"]) + 1,
"title": title,
"body": body,
"date": str(date.today()),
"priority": priority,
})
def bulk_mark_attendance(db, present=True):
today = str(date.today())
for i, s in enumerate(db["students"]):
if not s["active"]:
continue
mark_attendance(db, i, present)
def get_student_gate_logs(db, student_idx, limit=20):
return [g for g in db["gate_logs"] if g["student_idx"] == student_idx][-limit:]
def get_student_attendance_history(db, student_idx, limit=14):
return [a for a in db["attendance"] if a["student_idx"] == student_idx][-limit:]
def get_activity_feed(db, limit=8):
"""Recent events for dashboard activity stream."""
events = []
for g in reversed(db["gate_logs"][-5:]):
name = db["students"][g["student_idx"]]["name"]
events.append((g["time"], "πͺ", f"{name} β Gate {g['type']}", g["time"]))
for p in reversed(db["payment_history"][-3:]):
name = db["students"][p["student_idx"]]["name"]
events.append((p["date"], "π°", f"{name} paid {p['type']}", f"PKR {p['amount']:,}"))
for c in reversed(db["complaints"][-3:]):
name = db["students"][c["student_idx"]]["name"]
events.append((c.get("created", ""), "π", f"Ticket #{c['id']} β {name}", c["text"][:50]))
for a in db["announcements"][:2]:
events.append((a["date"], "π’", a["title"], a["body"][:60]))
events.sort(key=lambda x: x[0], reverse=True)
return [(icon, title, meta) for _, icon, title, meta in events[:limit]]
def export_summary(db):
stats = get_analytics(db)
return {
"generated": str(datetime.now()),
"analytics": stats,
"students": len([s for s in db["students"] if s["active"]]),
"rooms": len([r for r in db["rooms"] if r["active"]]),
"complaints_open": stats["complaint_counts"].get("Pending", 0),
"gate_logs": len(db["gate_logs"]),
}
def get_analytics(db):
rooms = [r for r in db["rooms"] if r["active"]]
students = [s for s in db["students"] if s["active"]]
vacant = sum(1 for r in rooms if r["occupied"] == 0)
partial = sum(1 for r in rooms if 0 < r["occupied"] < r["capacity"])
full = sum(1 for r in rooms if r["occupied"] >= r["capacity"])
rent_clear = sum(1 for s in students if s["rent_paid"])
mess_clear = sum(1 for s in students if s["mess_paid"])
defaulters = sum(1 for s in students if not s["rent_paid"] or not s["mess_paid"])
total_dues = sum(
s["rent_due"] + s["mess_due"] + s["utility_due"]
for s in students if not s["rent_paid"] or not s["mess_paid"]
)
complaint_counts = {STATUS_MAP[k]: 0 for k in STATUS_MAP}
for c in db["complaints"]:
complaint_counts[STATUS_MAP[c["status"]]] += 1
present_today = sum(
1 for a in db["attendance"]
if a["date"] == str(date.today()) and a["present"]
)
return {
"rooms_total": len(rooms),
"students_total": len(students),
"vacant": vacant,
"partial": partial,
"full": full,
"rent_clear": rent_clear,
"mess_clear": mess_clear,
"defaulters": defaulters,
"total_dues": total_dues,
"complaint_counts": complaint_counts,
"present_today": present_today,
"occupancy_pct": round(
sum(r["occupied"] for r in rooms) / max(sum(r["capacity"] for r in rooms), 1) * 100, 1
),
}
|