Overview
The loans module manages the complete book circulation lifecycle: checkout, return, renewal, and loan tracking. All loans have a 14-day lending period.Checkout Books
Parameters
List of book objects to checkout. Each book dict must contain an
isbn key.Example:Database ID of the user checking out the books
Returns
This function does not return a value. All operations complete successfully or raise an exception.
Side Effects
- Updates Book Status: Sets each book’s status to “Checked Out”
- Creates Loan Records: Inserts one loan record per book with:
user_id: The borrowing userisbn: The book identifierchecked_out: Current timestamp (auto-set)due_date: Current date + 14 daysreturned: 0 (active loan)
Implementation Details
Return Book
Parameters
ISBN of the book to return
Returns
True: Book was successfully returnedFalse: No active loan found for this ISBN
Operation Details
-
Find Active Loan: Queries for the most recent loan where:
isbnmatches the parameterreturned = 0(loan is active)- Orders by
checked_out DESCto get the latest loan
-
Close Loan: If found, updates the loan record:
- Sets
returned = 1 - Sets
returned_dateto current timestamp
- Sets
- Update Book: Sets book status back to “Available”
Error Cases
ReturnsFalse when:
- No active loan exists for the ISBN
- Book was never checked out
- Book was already returned
Renew Book
Parameters
Database ID of the loan record to renew
Returns
True: Loan was successfully renewedFalse: Loan not found or already returned
Renewal Logic
- Verify Active Loan: Checks that loan exists and
returned = 0 - Calculate New Due Date:
new_due_date = today + 14 days - Update Record: Sets
due_dateto the new date
- Renewing early gives 14 days from today
- Overdue books would get 14 days from today (if allowed)
Business Logic Recommendations
Consider these rules in your UI:- Disable renewal for overdue books
- Limit number of renewals per loan
- Only allow renewals within certain timeframes
Get User Loans
Parameters
Database ID of the user whose loans to retrieve
Returns
List of all loan records for the user, ordered by checkout date (newest first)
SQL Query
The function executes a JOIN query:Date Parsing
Datetime fields are automatically parsed:- SQLite stores datetimes as ISO 8601 strings
- Function attempts to parse
due_dateandreturned_dateas datetime objects - Falls back to original string value if parsing fails
Use Cases
- My Books Page: Display current checkouts and history
- Overdue Tracking: Filter by due_date < now()
- Renewal Interface: Show active loans with renewal options
- Reading History: Filter by
returned = True