-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbook.py
More file actions
338 lines (272 loc) · 12.4 KB
/
book.py
File metadata and controls
338 lines (272 loc) · 12.4 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
import tkinter as tk
from tkinter import ttk, messagebox
import csv
from datetime import datetime, timedelta
class Book:
def __init__(self, book_id, title, author, total_copies, available_copies):
self.book_id = book_id
self.title = title
self.author = author
self.total_copies = int(total_copies)
self.available_copies = int(available_copies)
def to_csv_format(self):
return [self.book_id, self.title, self.author,
str(self.total_copies), str(self.available_copies)]
@staticmethod
def from_csv_row(row):
return Book(row[0], row[1], row[2], row[3], row[4])
class Student:
def __init__(self, student_id, name, email, borrowed_books=""):
self.student_id = student_id
self.name = name
self.email = email
self.borrowed_books = borrowed_books.split(';') if borrowed_books and borrowed_books.strip() else []
def add_borrowed_book(self, book_id):
if book_id not in self.borrowed_books:
self.borrowed_books.append(book_id)
def remove_borrowed_book(self, book_id):
if book_id in self.borrowed_books:
self.borrowed_books.remove(book_id)
def can_borrow(self):
return len(self.borrowed_books) < 3
def to_csv_format(self):
borrowed = ';'.join(self.borrowed_books) if self.borrowed_books else ""
return [self.student_id, self.name, self.email, borrowed]
@staticmethod
def from_csv_row(row):
return Student(row[0], row[1], row[2], row[3])
class Librarian:
def __init__(self):
self.books = {}
self.students = {}
self.load_data()
def load_data(self):
# Load books
with open('books.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
book = Book.from_csv_row(row)
self.books[book.book_id] = book
# Load students
with open('students.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
student = Student.from_csv_row(row)
self.students[student.student_id] = student
def save_data(self):
# Save books
with open('books.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['book_id', 'title', 'author', 'total_copies', 'available_copies'])
for book in self.books.values():
writer.writerow(book.to_csv_format())
# Save students
with open('students.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['student_id', 'name', 'email', 'borrowed_books'])
for student in self.students.values():
writer.writerow(student.to_csv_format())
def check_stock(self):
return [book for book in self.books.values() if book.available_copies > 0]
def search_book(self, query):
query = query.lower()
results = [book for book in self.books.values()
if query in book.title.lower() or
query in book.author.lower() or
query in book.book_id.lower()]
return results
def search_student(self, query):
query = query.lower()
return [student for student in self.students.values()
if query in student.name.lower() or
query in student.student_id.lower() or
query in student.email.lower()]
def issue_book(self, book_id, student_id):
if book_id not in self.books or student_id not in self.students:
return False, "Invalid book or student ID"
book = self.books[book_id]
student = self.students[student_id]
if not student.can_borrow():
return False, "Student has reached maximum borrowing limit"
if book.available_copies <= 0:
return False, "Book not available"
book.available_copies -= 1
student.add_borrowed_book(book_id)
self.save_data()
due_date = (datetime.now() + timedelta(days=14)).strftime('%Y-%m-%d')
self.update_logs('ISSUE', book_id, student_id, due_date)
return True, f"Book issued successfully. Due date: {due_date}"
def return_book(self, book_id, student_id):
if book_id not in self.books or student_id not in self.students:
return False, "Invalid book or student ID"
book = self.books[book_id]
student = self.students[student_id]
if book_id not in student.borrowed_books:
return False, "This book was not borrowed by this student"
book.available_copies += 1
student.remove_borrowed_book(book_id)
self.save_data()
penalty = self.calculate_penalty(book_id, student_id)
self.update_logs('RETURN', book_id, student_id)
return True, f"Book returned successfully. Penalty: ${penalty}"
def calculate_penalty(self, book_id, student_id):
latest_issue_date = None
with open('logs.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
# Find the most recent ISSUE record for this book and student
if (row[2] == 'ISSUE' and
row[3] == book_id and
row[4] == student_id):
issue_date = datetime.strptime(row[5], '%Y-%m-%d')
if latest_issue_date is None or issue_date > latest_issue_date:
latest_issue_date = issue_date
if latest_issue_date:
current_date = datetime.now()
days_late = (current_date - latest_issue_date).days - 14 # 14 days loan period
# Subtract grace period
days_late = days_late - 2 if days_late > 2 else 0
# Calculate penalty
if days_late > 0:
return min(days_late * 1, 50) # $1 per day, max $50
return 0
def update_logs(self, transaction_type, book_id, student_id, due_date=None):
with open('logs.csv', 'a', newline='') as file:
writer = csv.writer(file)
transaction_id = datetime.now().strftime('T%Y%m%d%H%M%S')
current_date = datetime.now().strftime('%Y-%m-%d')
writer.writerow([
transaction_id,
current_date,
transaction_type,
book_id,
student_id,
due_date if due_date else ''
])
def get_student_borrowed_books_info(self, student_id):
student = self.students.get(student_id)
if not student:
return "No books borrowed"
book_info = []
for book_id in student.borrowed_books:
if book_id in self.books:
book = self.books[book_id]
book_info.append(f"{book_id}:{book.title}")
return ';'.join(book_info) if book_info else "No books borrowed"
class LibraryGUI:
def __init__(self, root):
self.root = root
self.root.title("Library Management System")
self.librarian = Librarian()
self.setup_gui()
def setup_gui(self):
# Create notebook for tabs
notebook = ttk.Notebook(self.root)
notebook.pack(pady=10, expand=True)
books_frame = ttk.Frame(notebook)
notebook.add(books_frame, text="Books")
ttk.Label(books_frame, text="Search Books:").pack(pady=5)
self.book_search_var = tk.StringVar()
ttk.Entry(books_frame, textvariable=self.book_search_var).pack(pady=5)
ttk.Button(books_frame, text="Search",
command=self.search_books).pack(pady=5)
self.books_tree = ttk.Treeview(books_frame,
columns=('ID', 'Title', 'Author', 'Available'),
show='headings')
self.books_tree.heading('ID', text='ID')
self.books_tree.heading('Title', text='Title')
self.books_tree.heading('Author', text='Author')
self.books_tree.heading('Available', text='Available')
self.books_tree.pack(pady=10)
students_frame = ttk.Frame(notebook)
notebook.add(students_frame, text="Students")
ttk.Label(students_frame, text="Search Students:").pack(pady=5)
self.student_search_var = tk.StringVar()
ttk.Entry(students_frame,
textvariable=self.student_search_var).pack(pady=5)
ttk.Button(students_frame, text="Search",
command=self.search_students).pack(pady=5)
self.students_tree = ttk.Treeview(students_frame,
columns=('ID', 'Name', 'Email', 'Borrowed'),
show='headings')
self.students_tree.heading('ID', text='ID')
self.students_tree.heading('Name', text='Name')
self.students_tree.heading('Email', text='Email')
self.students_tree.heading('Borrowed', text='Borrowed Books')
self.students_tree.pack(pady=10)
transactions_frame = ttk.Frame(notebook)
notebook.add(transactions_frame, text="Transactions")
ttk.Label(transactions_frame, text="Issue Book").pack(pady=5)
ttk.Label(transactions_frame, text="Book ID:").pack()
self.issue_book_id = tk.StringVar()
ttk.Entry(transactions_frame,
textvariable=self.issue_book_id).pack(pady=5)
ttk.Label(transactions_frame, text="Student ID:").pack()
self.issue_student_id = tk.StringVar()
ttk.Entry(transactions_frame,
textvariable=self.issue_student_id).pack(pady=5)
ttk.Button(transactions_frame, text="Issue Book",
command=self.issue_book).pack(pady=10)
# Return book
ttk.Label(transactions_frame, text="Return Book").pack(pady=5)
ttk.Label(transactions_frame, text="Book ID:").pack()
self.return_book_id = tk.StringVar()
ttk.Entry(transactions_frame,
textvariable=self.return_book_id).pack(pady=5)
ttk.Label(transactions_frame, text="Student ID:").pack()
self.return_student_id = tk.StringVar()
ttk.Entry(transactions_frame,
textvariable=self.return_student_id).pack(pady=5)
ttk.Button(transactions_frame, text="Return Book",
command=self.return_book).pack(pady=10)
def search_books(self):
query = self.book_search_var.get()
books = self.librarian.search_book(query)
for item in self.books_tree.get_children():
self.books_tree.delete(item)
#books = self.librarian.search_book(query)
if not books:
messagebox.showinfo("Search Result", f"No books found matching '{query}' in the library database.")
return
for book in books:
self.books_tree.insert('', 'end', values=(
book.book_id,
book.title,
book.author,
book.available_copies
))
def search_students(self):
query = self.student_search_var.get()
students = self.librarian.search_student(query)
for item in self.students_tree.get_children():
self.students_tree.delete(item)
for student in students:
self.students_tree.insert('', 'end', values=(
student.student_id,
student.name,
student.email,
';'.join(student.borrowed_books)
))
def issue_book(self):
success, message = self.librarian.issue_book(
self.issue_book_id.get(),
self.issue_student_id.get()
)
messagebox.showinfo("Issue Book", message)
self.search_books()
self.search_students()
def return_book(self):
success, message = self.librarian.return_book(
self.return_book_id.get(),
self.return_student_id.get()
)
messagebox.showinfo("Return Book", message)
self.search_books()
self.search_students()
if __name__ == "__main__":
root = tk.Tk()
app = LibraryGUI(root)
root.mainloop()