-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibraryManagementSystem.py
More file actions
282 lines (220 loc) · 8.18 KB
/
LibraryManagementSystem.py
File metadata and controls
282 lines (220 loc) · 8.18 KB
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
import getpass
from datetime import date
# -----------------------------------
# DATA STORAGE
# -----------------------------------
books = []
borrowing_records = []
USERS_FILE = "passwords.txt"
def load_users():
"""Load users from passwords.txt"""
users = {}
try:
with open(USERS_FILE) as f:
for line in f:
username, password, role = line.strip().split(",")
users[username] = {"password": password, "role": role}
except FileNotFoundError:
pass
return users
def authenticate(username, password):
users = load_users()
if username not in users:
return None, "User does not exist"
if password != users[username]["password"]:
return None, "Incorrect password"
return users[username]["role"], "Login successful!"
# -----------------------------------
# VALIDATION & UTILITY
# -----------------------------------
def validate_isbn(isbn):
"""ISBN must be numeric and 10 or 13 digits. """
return isbn.isdigit() and len(isbn) in (10, 13)
def calculate_late_fee(days_overdue):
"""Calculate late fee based on given fee structure"""
if days_overdue <= 0:
return 0.0
if days_overdue <= 7:
returnmin(days_overdue * 0.5, 3.5)
elif days_overdue <= 14:
return min(3.5 + (days_overdue - 7) * 1.0, 10.5)
elif days_overdue <= 30:
return min(10.5 + (days_overdue - 14) * 2.0, 42.5)
else:
return round(42.5 + (days_overdue - 30) * 3.0, 2)
# -----------------------------------
# BOOK MANAGEMENT (ADMIN)
# -----------------------------------
def add_book(title, isbn, author, category):
if not title.strip() or not author.strip():
return "Error: Title and author cannot be empty"
if not validate_isbn(isbn):
return "Error: ISBN is not a valid ISBN"
for book in books:
if book["isbn"] == isbn:
return "Error: ISBN already exists"
books.append({"title": title, "isbn": isbn, "author": author, "category": category, "available": True, "borrow_count": 0})
return "Book added successfully!"
def search_book(search_term, search_type):
results = []
for book in books:
if search_type == "title" and search_term.lower() in book["title"].lower():
results.append(book)
elif search_type == "author" and search_term.lower() in book["author"].lower():
results.append(book)
elif search_type == "isbn" and search_term == book["isbn"]:
results.append(book)
return results
# -----------------------------------
# BORROWING MANAGEMENT (USER)
# -----------------------------------
def borrow_book(member_id, isbn):
for book in books:
if book["isbn"] == isbn:
if not book["available"]:
return "Error: Book is not available"
book["available"] = False
book["borrow_count"] += 1
borrowing_records.append({
"member_id": member_id,
"isbn": isbn,
"borrow_date": date.today(),
"return_date": None,
"late_fee": 0.0
})
return "Book borrowed successfully!"
return "Error: Book not found"
def return_book(member_id, isbn):
for record in borrowing_records:
if record["member_id"] == member_id and record["isbn"] == isbn and record["return_date"] is None:
record["return_date"] = date.today()
days_borrowed = (record["return_date"] - record["borrow_date"]).days
overdue_days = max(0, days_borrowed - 14)
fee = calculate_late_fee(overdue_days)
record["late_fee"] = fee
for book in books:
if book["isbn"] == isbn:
book["available"] = True
title = book["title"]
return f"Returned '{title}'. Days borrowed: {days_borrowed}, Late fee: RM {fee}"
return "Error: Active borrowing records not found"
def get_member_borrowing_history(member_id):
history = []
for record in borrowing_records:
if record["member_id"] == member_id:
history.append(record)
return history
# -----------------------------------
# REPORTS (ADMIN)
# -----------------------------------
def generate_available_books_report(category=None):
report = {}
for book in books:
if book["available"] and (category is None or book["category"] == category):
report.setdefault(book["category"], []).append(book)
return report
def generate_library_summary():
total_books = len(books)
available = sum(1 for b in books if b["available"])
borrowed = total_books - available
most_borrowed = max(books, key=lambda book: book["borrow_count"], default=None)
total_fees = sum(r["late_fee"] for r in borrowing_records)
overdue = [
r for r in borrowing_records
if r["return_date"] is None and (date.today() - r["borrow_date"]).days > 14
]
category_dist = {}
for b in books:
category_dist[b["category"]] = category_dist.get(b["category"], 0) + 1
return {
"total_books": total_books,
"available": available,
"borrowed": borrowed,
"most_borrowed": most_borrowed,
"total_fees": total_fees,
"overdue_books": overdue,
"category_distribution": category_dist,
}
# -----------------------------------
# MENUS
# -----------------------------------
def userMenu(username):
while True:
print (f"\n=== Welcome to the library system, {username}! ===")
print ("1. Search book")
print ("2. Borrow book")
print ("3. Return book")
print ("4. View borrowing history")
print ("5. Logout")
choice = input("Enter your choice: ")
if choice == "1":
st = input("Search by (title/author/ISBN): )")
term = input("Enter search term: ")
print(search_book(term, st))
elif choice == "2":
print(borrow_book(username, input("Enter book ISBN: ")))
elif choice == "3":
print(return_book(username, input("Enter book ISBN: ")))
elif choice == "4":
print(get_member_borrowing_history(username))
elif choice == "5":
break
else:
print ("Invalid choice")
def adminMenu(username):
while True:
print ("\n=== Admin Interface ===")
print("1. Add book")
print("2. View available books")
print("3. Library Summary")
print("4. Logout")
choice = input("Enter your choice: ")
if choice == "1":
print(add_book(
input("Title:"),
input("ISBN:"),
input("Author:"),
input("Category"),
))
elif choice == "2":
print(generate_available_books_report())
elif choice == "3":
print(generate_library_summary())
elif choice == "4":
break
else:
print ("Invalid choice")
# -----------------------------------
# HOME
# -----------------------------------
def libraryHome():
# Sample data
add_book("1984", "1234567890", "George Orwell", "Fiction")
add_book("Python Programming", "1234567890123", "John Smith", "Reference")
add_book("Children Tales", "0987654321", "Jane Doe", "Children")
add_book("Data Science", "9998887776661", "Alice Brown", "Non-Fiction")
while True:
print ("\n=== LIBRARY HOME ===")
print ("1. Login")
print ("2. Request user creation - Library Admin")
print ("3. Exit")
choice = input("Enter your choice: ")
if choice == "1":
username = input("Username: ")
password = input("Password: ")
role, msg = authenticate(username, password)
print(msg)
if role == "admin":
adminMenu(username)
elif role == "libuser":
userMenu(username)
elif choice == "2":
print ("Email admin at library_admin@library.com.my")
elif choice == "3":
break
else:
print ("Invalid choice")
# -----------------------------------
# PROGRAM ENTRY
# -----------------------------------
libraryHome()