Files
books/loan.py

115 lines
5.6 KiB
Python

from wtforms import SubmitField, StringField, HiddenField, validators, TextAreaField
from flask_wtf import FlaskForm
from flask import request, render_template, redirect
from flask_login import login_required, current_user
from wtforms import DateField
from main import db, app, ma
from datetime import date
from sqlalchemy import Sequence
from sqlalchemy.exc import SQLAlchemyError
from status import st, Status
################################################################################
# Class describing Loan in the database, and via sqlalchemy, connected to the DB as well
################################################################################
class Loan(db.Model):
id = db.Column(db.Integer, db.Sequence('loan_id_seq'), primary_key=True )
surname = db.Column(db.String(30), unique=False, nullable=False)
firstnames = db.Column(db.String(50), unique=False, nullable=False)
contact_details = db.Column(db.String(256), unique=False, nullable=False)
date_lent = db.Column(db.Date, nullable=False )
def __repr__(self):
return f"<id: {self.id}, firstnames: {self.firstnames}, surname: {self.surname}>"
################################################################################
# Helper class that inherits a .dump() method to turn class Loan into json / useful in jinja2
################################################################################
class LoanSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Loan
ordered = True
################################################################################
# Helper class that defines a form for loan, used to make html <form>, with field validation (via wtforms)
################################################################################
class LoanForm(FlaskForm):
id = HiddenField()
firstnames = StringField('FirstName(s):', [validators.DataRequired()])
surname = StringField('Surname:', [validators.DataRequired()])
contact_details = TextAreaField('Contact Details:', [validators.DataRequired()])
surname = StringField('Surname:', [validators.DataRequired()])
date_lent = DateField('Date Lent:', format='%Y-%m-%d', default=date.today(), validators=[validators.DataRequired()] )
submit = SubmitField('Save' )
delete = SubmitField('Delete' )
################################################################################
# Routes for loan data
#
# /loans -> GET only -> prints out list of all loans
################################################################################
@app.route("/loans", methods=["GET"])
@login_required
def loans():
loans = Loan.query.all()
return render_template("loans.html", loans=loans, alert=st.GetAlert(), message=st.GetMessage())
################################################################################
# /loan -> GET/POST -> creates a new loan type and when created, takes you back to /loans
################################################################################
@app.route("/loan", methods=["GET", "POST"])
@login_required
def new_loan():
form = LoanForm(request.form)
page_title='Create new Loan'
if 'firstnames' not in request.form:
return render_template("loan.html", form=form, page_title=page_title )
else:
loan = Loan( firstnames=request.form["firstnames"], surname=request.form["surname"], date_lent=request.form["date_lent"], contact_details=request.form["contact_details"] )
try:
db.session.add(loan)
db.session.commit()
st.SetMessage( f"Created new Loan (id={loan.id})" )
return redirect( '/loans' )
except SQLAlchemyError as e:
st.SetAlert( "danger" )
st.SetMessage( f"<b>Failed to add Loan:</b>&nbsp;{e.orig}" )
return render_template("edit_id_name.html", form=form, page_title=page_title, alert=st.GetAlert(), message=st.GetMessage() )
################################################################################
# /loan/<id> -> GET/POST(save or delete) -> shows/edits/delets a single loan
################################################################################
@app.route("/loan/<id>", methods=["GET", "POST"])
@login_required
def loan(id):
### DDP: should this be request.form or request.values?
form = LoanForm(request.form)
page_title='Edit Loan'
if request.method == 'POST' and form.validate():
loan = Loan.query.get(id)
try:
if 'delete' in request.form:
from main import Book_Loan_Link
st.SetMessage( f"Successfully deleted (id={loan.id}, who={loan.firstnames} {loan.surname})" )
Book_Loan_Link.query.filter(Loan.id==id).delete()
Loan.query.filter(Loan.id==id).delete()
if 'submit' in request.form:
st.SetMessage( f"Successfully Updated Loan (id={id})" )
loan.firstnames = request.form['firstnames']
loan.surname = request.form['surname']
loan.surname = request.form['surname']
loan.contact_details = request.form['contact_details']
loan.date_lent = request.form['date_lent']
db.session.commit()
return redirect( '/loans' )
except SQLAlchemyError as e:
st.SetAlert( "danger" )
st.SetMessage( f"<b>Failed to modify Loan:</b>&nbsp;{e.orig}" )
return render_template("edit_id_name.html", form=form, page_title=page_title, alert=st.GetAlert(), message=st.GetMessage() )
else:
loan = Loan.query.get(id)
form = LoanForm(request.values, obj=loan)
return render_template("loan.html", loan=loan, form=form, page_title=page_title)