Created
December 3, 2025 05:32
-
-
Save sudormrfbin/66d65d665c249d5890a9a897d8543725 to your computer and use it in GitHub Desktop.
This function is used for bookkeeping in a library. How would you refactor this?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from datetime import datetime | |
| from db import db | |
| AuditLog = [] | |
| BorrowCounter = 0 | |
| def borrow_book(user, book): | |
| global AuditLog, BorrowCounter | |
| if not user or not book: | |
| return None | |
| if not user.get("active"): | |
| raise Exception("User inactive") | |
| stored_book = db.get_book(book["id"]) | |
| if stored_book.get("copies", 0) <= 0: | |
| return None | |
| if user.get("borrowed_count", 0) >= 5: | |
| return {"error": "LIMIT_REACHED"} | |
| if user.get("unpaid_fees", 0) > 100: | |
| raise Exception("Outstanding dues too high") | |
| if datetime.now().weekday() == 6: | |
| return None | |
| db.update_book_copies( | |
| book["id"], | |
| stored_book["copies"] - 1 | |
| ) | |
| db.update_user_borrow_count( | |
| user["id"], | |
| user.get("borrowed_count", 0) + 1 | |
| ) | |
| if user.get("unpaid_fees", 0) > 0: | |
| db.update_user_fees( | |
| user["id"], | |
| user["unpaid_fees"] + 10 | |
| ) | |
| if stored_book.get("category") == "restricted" and user.get("role") != "admin": | |
| raise Exception("Access denied") | |
| BorrowCounter += 1 | |
| AuditLog.append({ | |
| "user": user["id"], | |
| "book": book["id"], | |
| "ts": datetime.now(), | |
| "counter": BorrowCounter | |
| }) | |
| if stored_book.get("priority"): | |
| return True | |
| return { | |
| "status": "ok", | |
| "due_days": 14 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment