-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibrary.py
More file actions
524 lines (435 loc) · 21.5 KB
/
Library.py
File metadata and controls
524 lines (435 loc) · 21.5 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
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
import pandas as pd
import bcrypt
from Book import BookFactory
from Member import Member, MemberIterator
from FilterStrategy import TitleFilter, YearFilter, AuthorFilter, GenreFilter
from Logger import log_decorator
class Library:
"""
Singleton class that represents a library management system.
It manages books, members, and user accounts. Provides functionalities
for initializing files, creating members, and handling books.
"""
_instance = None
def __new__(cls):
# Ensures that only one instance of the Library class exists (Singleton).
if cls._instance is None:
cls._instance = super(Library, cls).__new__(cls)
return cls._instance
def __init__(self):
# Initializes library attributes and ensures required files are set up.
self.members = []
self.logged_in_user = None
self.check_and_create_users_file()
self.check_and_create_books_file()
self.check_and_create_members_file()
self.BookFactory = BookFactory()
self.filters = {
"title": TitleFilter(),
"year": YearFilter(),
"author": AuthorFilter(),
"genre": GenreFilter(),
}
def check_and_create_users_file(self):
"""Ensures the users file exists and creates it if not."""
try:
users = pd.read_csv('users.csv')
if users.empty:
self.create_empty_users_file()
except FileNotFoundError:
self.create_empty_users_file()
def create_empty_users_file(self):
"""Creates an empty users file with default columns."""
users = pd.DataFrame(columns=['username', 'password'])
users.to_csv('users.csv', index=False)
def check_and_create_members_file(self):
"""Ensures the members file exists and creates it if not."""
try:
members = pd.read_csv('members.csv')
self.create_members_from_file()
if members.empty:
self.create_empty_members_file()
except FileNotFoundError:
self.create_empty_members_file()
def create_empty_members_file(self):
"""Creates an empty members file with default columns."""
members = pd.DataFrame(columns=['name', 'phone', 'email', 'notifications'])
members['notifications'] = ""
members.to_csv('members.csv', index=False)
def create_members_from_file(self):
"""Loads members from the file into the members list."""
try:
members_df = pd.read_csv('members.csv')
if not members_df.empty:
# Creates Member objects for valid rows and adds them to the list.
for _, row in members_df.iterrows():
name = row['name'].strip() if pd.notna(row['name']) else ''
phone = str(row['phone']).strip() if pd.notna(row['phone']) else ''
email = row['email'].strip() if pd.notna(row['email']) else ''
if name and phone and email:
try:
member = Member(name, phone, email)
self.members.append(member)
except ValueError as e:
print(f"Skipping invalid member: {e}")
else:
print(f"Skipping member with invalid data: {name}, {phone}, {email}")
else:
print("No members found in the file.")
except FileNotFoundError:
print("members.csv file not found.")
except pd.errors.EmptyDataError:
print("members.csv is empty.")
def check_and_create_books_file(self):
"""Ensures the books file exists and updates its structure if needed."""
try:
books = pd.read_csv('books.csv')
except FileNotFoundError:
self.create_books_file()
self.update_books_file()
def create_books_file(self):
"""Creates an empty books file with default columns."""
columns = ['title', 'author', 'is_loaned', 'copies', 'genre', 'year', 'borrowed', 'popularity', 'wait_list']
books = pd.DataFrame(columns=columns)
books.to_csv('books.csv', index=False)
def update_books_file(self):
"""Adds or updates required columns in the books file."""
books = pd.read_csv('books.csv')
if 'borrowed' not in books.columns:
books['borrowed'] = books.apply(
lambda row: int(row['copies']) if row['is_loaned'] == "Yes" else 0,
axis=1
)
if 'popularity' not in books.columns:
books['popularity'] = books['borrowed'].astype(int)
if 'wait_list' not in books.columns:
books['wait_list'] = ""
books.to_csv('books.csv', index=False)
@log_decorator
def register_user(self, username, password):
"""Registers a new user by storing their username and hashed password."""
username = username.strip() if username else ""
password = password.strip() if password else ""
if not username or not password:
raise ValueError("One of the inputs is None, empty, or contains only spaces!")
username = str(username)
password = str(password)
try:
users = pd.read_csv('users.csv')
except FileNotFoundError:
users = pd.DataFrame(columns=['username', 'password'])
if username in users['username'].values:
raise ValueError("Username already exists!")
else:
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
new_user = pd.DataFrame({
'username': [username],
'password': [hashed_password.decode('utf-8')],
})
users = pd.concat([users, new_user], ignore_index=True)
users.to_csv('users.csv', index=False)
return f"Registration successful!"
@log_decorator
def login(self, username, password):
"""Logs in a user by verifying their username and password."""
username = str(username)
password = str(password)
try:
users = pd.read_csv('users.csv')
user_data = users[users['username'] == username]
if not user_data.empty:
hashed_password = user_data['password'].values[0]
if bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8')):
self.logged_in_user = "librarian"
return "librarian" # All logged-in users are librarians
else:
raise ValueError("Invalid password.")
else:
raise ValueError("Username not found.")
except FileNotFoundError:
self.create_empty_users_file()
raise ValueError("No users found, creating an empty user file.")
except pd.errors.EmptyDataError:
self.create_empty_users_file()
raise ValueError("No users found, creating an empty user file.")
@log_decorator
def add_book(self, title, author, genre, year, copies):
"""Adds a book to the library. Creates a new entry or updates existing copies."""
try:
b = self.BookFactory.create_book(title, author, genre, year)
except ValueError as e:
raise e
return self.add_book_help(b, copies)
def add_book_help(self, book, copies):
"""Helper function to add a book with the specified number of copies."""
if not self.is_librarian():
raise ValueError("You must be logged in as a librarian to perform this action.")
try:
copies = int(copies)
except ValueError:
raise ValueError(f"Copies {copies} is not an integer.")
if copies <= 0:
raise ValueError("Copies must be greater than zero.")
books = pd.read_csv('books.csv')
search_results = self.search_books(title=book.title, author=book.author, genre=book.genre, year=book.year)
if not search_results.empty:
# If the book exists, add more copies
books.loc[search_results.index, 'copies'] += copies
books.to_csv('books.csv', index=False)
return f"Book: {book.title} added successfully."
else:
# If the book does not exist, create a new entry
new_book = pd.DataFrame({
'title': [book.title],
'author': [book.author],
'is_loaned': ['No'],
'copies': [copies],
'genre': [book.genre],
'year': [book.year],
'borrowed': [0],
'popularity': [0],
})
books = pd.concat([books, new_book], ignore_index=True)
books.to_csv('books.csv', index=False)
return f"Book: {book.title} added successfully."
@log_decorator
def remove_book(self, book):
"""Removes a book from the library if it has no borrowed copies."""
if not self.is_librarian():
raise ValueError("You must be logged in as a librarian to perform this action.")
books = pd.read_csv('books.csv')
search_results = self.search_books(title=book.title, author=book.author, genre=book.genre, year=book.year)
if not search_results.empty:
if search_results['borrowed'].iloc[0] == 0:
books = books.drop(search_results.index)
books.to_csv('books.csv', index=False)
return f"Book: {book} removed successfully."
else:
raise ValueError(f"Book '{book.title}' has borrowed copies, can't be deleted.")
else:
raise ValueError(f"Book {book} not found in the list of books.")
@log_decorator
def lend_book(self, book):
"""Lends a book to a member if copies are available."""
if not self.is_librarian():
raise ValueError("You must be logged in as a librarian to perform this action.")
books = pd.read_csv('books.csv')
search_results = self.search_books(title=book.title, author=book.author, genre=book.genre, year=book.year)
if not search_results.empty:
book_index = search_results.index[0]
book_row = books.loc[book_index]
if book_row['is_loaned'] == 'No':
books.loc[book_index, 'borrowed'] += 1
if books.loc[book_index, 'borrowed'] == book_row['copies']:
books.loc[book_index, 'is_loaned'] = 'Yes'
books.loc[book_index, 'popularity'] += 1
books.to_csv('books.csv', index=False)
return "The book was loaned successfully."
else:
raise ValueError("All copies of this book are currently loaned. Please enter the waiting list.")
else:
raise ValueError(f"Book {book} not found in the list of books.")
@log_decorator
def return_book(self, book):
"""Handles returning a book and managing the waiting list if necessary."""
if not self.is_librarian():
raise ValueError("You must be logged in as a librarian to perform this action.")
books = pd.read_csv('books.csv')
books['wait_list'] = books['wait_list'].fillna('').astype(str)
search_results = self.search_books(title=book.title, author=book.author, genre=book.genre, year=book.year)
if not search_results.empty:
book_index = search_results.index[0]
book_row = books.loc[book_index]
if book_row['borrowed'] == 0:
raise ValueError(f"Book {book.title} is not loaned.")
current_wait_list = book_row['wait_list']
if not pd.isna(current_wait_list) and current_wait_list.strip():
wait_list = current_wait_list.split('|')
if wait_list:
member_str = wait_list.pop(0)
member_str = member_str.strip('[]')
parameters = member_str.split(',')
member = self.bring_member(parameters[0], parameters[1], parameters[2])
self.update_member_observer(member, f"Someone returned {book.title}, now you can borrow it.")
books.loc[book_index, 'wait_list'] = '|'.join(wait_list)
else:
books.loc[book_index, 'borrowed'] -= 1
if books.loc[book_index, 'borrowed'] < book_row['copies']:
books.loc[book_index, 'is_loaned'] = 'No'
books.loc[book_index, 'popularity'] -= 1
books.to_csv('books.csv', index=False)
return f"Book {book.title} returned successfully."
else:
raise ValueError(f"Book {book.title} not found in the list of books.")
@log_decorator
def enter_waiting_list(self, name, phone, email, book):
"""Adds a member to the waiting list for a book if it's not currently available."""
if not self.is_librarian():
raise ValueError("You must be logged in as a librarian to perform this action.")
books = pd.read_csv('books.csv')
books['wait_list'] = books['wait_list'].fillna('').astype(str)
search_results = self.search_books(title=book.title, author=book.author, genre=book.genre, year=book.year)
if not search_results.empty:
if books.loc[search_results.index, 'is_loaned'].iloc[0] == 'No':
raise ValueError(f"Book {book} has copies available, you can't enter the waiting list for this book.")
else:
member = self.bring_member(name, phone, email)
if member is None:
try:
member = Member(name, phone, email)
except ValueError as e:
raise ValueError(e)
self.members.append(member)
members = pd.read_csv('members.csv')
new_member = pd.DataFrame({
'name': [name],
'phone': [phone],
'email': [email],
'notifications': "",
})
members = pd.concat([members, new_member], ignore_index=True)
members.to_csv('members.csv', index=False)
# Get the current waiting list or create a new one if it doesn't exist
current_wait_list = books.loc[search_results.index, 'wait_list'].iloc[0]
if current_wait_list == "": # If no waiting list exists, create one
wait_list = []
else:
wait_list = current_wait_list.split('|') # Split the current list into members
# Add the new member to the waiting list
wait_list.append(f"[{name},{phone},{email}]")
if wait_list != "":
books.loc[search_results.index, 'wait_list'] = '|'.join(wait_list)
else:
books.loc[search_results.index, 'wait_list'] = wait_list
# Convert the 'wait_list' column to the correct data type
books['wait_list'] = books['wait_list'].astype(str)
# Update the popularity
books.loc[search_results.index, 'popularity'] += 1
# Save the updated data to the file
books.to_csv('books.csv', index=False)
self.update_member_observer(member, f"You entered the waiting list for '{book.title}' successfully")
return f"{name} entered the waiting list for {book} successfully"
else:
raise ValueError(f"Book {book} not found in the list of books.")
def bring_member(self, name, phone, email):
"""Searches for an existing member by name, phone, and email."""
if not self.is_librarian():
raise ValueError("You must be logged in as a librarian to perform this action.")
if self.members is None:
return None
for member in self:
if member.name == name and member.phone == phone and member.email == email:
return member
return None
def __iter__(self):
"""Returns an iterator for the members."""
return MemberIterator(self.members)
@log_decorator
def update_member_observer(self, member, message):
"""Updates the notifications for a member."""
member.update(message)
members = pd.read_csv('members.csv')
members['notifications'] = members['notifications'].fillna('').astype(str)
# Search for the member in the file
member_search = self.search_member_in_file(member.name, member.phone, member.email)
# Get the current notifications for the member
current_notifications = members.at[member_search.index[0], 'notifications']
# If there are no notifications, initialize the string as empty
if pd.isna(current_notifications):
current_notifications = ""
# If there are existing notifications, append the new one with '|', otherwise just add it
updated_notifications = f"{current_notifications} | {message}" if current_notifications else message
# Update the 'notifications' column
members.at[member_search.index[0], 'notifications'] = updated_notifications
# Save the updated data to the file
members.to_csv('members.csv', index=False)
@log_decorator
def only_search(self, title=None, author=None, genre=None, year=None):
"""Performs a book search and returns the results or raises an error if not found."""
try:
books = self.search_books(title=title, author=author, genre=genre, year=year)
if not books.empty:
return books
else:
raise ValueError(f"Book {title} not found in the list of books.")
except ValueError as e:
raise e
def search_books(self, title=None, author=None, genre=None, year=None):
"""Searches the books based on the given filters."""
if not self.is_librarian():
raise ValueError("You must be logged in as a librarian to perform this action.")
books = pd.read_csv('books.csv') # Load the book database
# List of parameters to apply to the filter
filters_to_apply = {
'title': title,
'author': author,
'genre': genre,
'year': year,
}
# Apply filters based on the provided parameters
for key, value in filters_to_apply.items():
if value: # If the parameter exists
books = self.filters[key].filter(books, value)
return books
def search_member_in_file(self, name, phone, email):
"""Searches for a member in the members database based on their details."""
if not self.is_librarian():
raise ValueError("You must be logged in as a librarian to perform this action.")
members = pd.read_csv('members.csv') # Load the members database
# Filter by name, phone, and email
members = members[members['name'].str.contains(name, case=False, na=False)]
members = members[members['phone'].astype(str).str.contains(str(phone), case=False, na=False)]
members = members[members['email'].str.contains(email, case=False, na=False)]
return members
@log_decorator
def display_books_by_category(self, category):
"""Displays all books in a given category."""
if not self.is_librarian():
raise ValueError("You must be logged in as a librarian to perform this action.")
books = pd.read_csv('books.csv')
return books[books['genre'].str.contains(category, case=False, na=False)]
@log_decorator
def display_all_books(self):
"""Displays all books in the library."""
if not self.is_librarian():
raise ValueError("You must be logged in as a librarian to perform this action.")
books = pd.read_csv('books.csv')
return books
@log_decorator
def display_available_books(self):
"""Displays only the available books that are not loaned out."""
if not self.is_librarian():
raise ValueError("You must be logged in as a librarian to perform this action.")
books = pd.read_csv('books.csv')
return books[books['is_loaned'].str.contains('No', case=False, na=False)]
@log_decorator
def display_loaned_books(self):
"""Displays books that are currently loaned out."""
if not self.is_librarian():
raise ValueError("You must be logged in as a librarian to perform this action.")
books = pd.read_csv('books.csv')
loaned_books = books[books['borrowed'] > 0]
return loaned_books
@log_decorator
def display_10_popularity_books(self):
"""Displays the top 10 most popular books based on the 'popularity' column."""
if not self.is_librarian():
raise ValueError("You must be logged in as a librarian to perform this action.")
books = pd.read_csv('books.csv')
top_10_popular_books = books.nlargest(10, 'popularity')
return top_10_popular_books
def is_librarian(self):
"""Checks if the current logged-in user is a librarian."""
return self.logged_in_user == "librarian"
@log_decorator
def logout(self):
"""Logs out the current user."""
if self.logged_in_user is None:
raise ValueError("You must be logged in to logout.")
else:
self.logged_in_user = None
return "Logged out successfully."
if __name__ == '__main__':
library = Library()
library.login('q','1')
print(library.members)