Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add typing to Haldis #141

Merged
merged 6 commits into from Sep 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 4 additions & 2 deletions app/admin.py
@@ -1,12 +1,14 @@
import flask_login as login
from flask import Flask
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_sqlalchemy import SQLAlchemy

from models import Location, Order, OrderItem, Product, User


class ModelBaseView(ModelView):
def is_accessible(self):
def is_accessible(self) -> bool:
if login.current_user.is_anonymous():
return False

Expand All @@ -29,7 +31,7 @@ class LocationAdminModel(ModelBaseView):
form_columns = ("name", "address", "website", "telephone")


def init_admin(app, db):
def init_admin(app: Flask, db: SQLAlchemy) -> None:
admin = Admin(app, name="Haldis", url="/admin", template_mode="bootstrap3")

admin.add_view(UserAdminModel(User, db.session))
Expand Down
21 changes: 11 additions & 10 deletions app/app.py
@@ -1,4 +1,5 @@
import logging
import typing
from datetime import datetime
from logging.handlers import TimedRotatingFileHandler

Expand All @@ -19,7 +20,7 @@
from zeus import init_oauth


def create_app():
def create_app() -> Manager:
app = Flask(__name__)

# Load the config file
Expand All @@ -34,7 +35,7 @@ def create_app():
return manager


def register_plugins(app, debug: bool):
def register_plugins(app: Flask, debug: bool) -> Manager:
# Register Airbrake and enable the logrotation
if not app.debug:
timedFileHandler = TimedRotatingFileHandler(
Expand Down Expand Up @@ -96,17 +97,17 @@ def register_plugins(app, debug: bool):
return manager


def add_handlers(app):
def add_handlers(app: Flask) -> None:
@app.errorhandler(404)
def handle404(e):
def handle404(e) -> typing.Tuple[str, int]:
return render_template("errors/404.html"), 404

@app.errorhandler(401)
def handle401(e):
def handle401(e) -> typing.Tuple[str, int]:
return render_template("errors/401.html"), 401


def add_routes(application):
def add_routes(application: Flask) -> None:
# import views # TODO convert to blueprint
# import views.stats # TODO convert to blueprint

Expand All @@ -127,9 +128,9 @@ def add_routes(application):
application.register_blueprint(debug_bp, url_prefix="/debug")


def add_template_filters(app):
def add_template_filters(app: Flask) -> None:
@app.template_filter("countdown")
def countdown(value, only_positive=True, show_text=True):
def countdown(value, only_positive: bool = True, show_text: bool = True) -> str:
delta = value - datetime.now()
if delta.total_seconds() < 0 and only_positive:
return "closed"
Expand All @@ -141,11 +142,11 @@ def countdown(value, only_positive=True, show_text=True):
return time

@app.template_filter("year")
def current_year(value):
def current_year(value: typing.Any) -> str:
return str(datetime.now().year)

@app.template_filter("euro")
def euro(value):
def euro(value: int) -> None:
euro_string(value)


Expand Down
2 changes: 1 addition & 1 deletion app/database/add_admins.py
Expand Up @@ -2,7 +2,7 @@
from models import User


def add():
def add() -> None:
feli = User()
feli.configure("feliciaan", True, 0)
db.session.add(feli)
Expand Down
5 changes: 2 additions & 3 deletions app/database/add_fitchen.py
@@ -1,6 +1,5 @@
from models import Location, Product
from app import db

from models import Location, Product

menuitems = [
"Spicy Chicken",
Expand All @@ -23,7 +22,7 @@
pricedict = {"Small": 799, "Medium": 999, "Large": 1199}


def add():
def add() -> None:
simpizza = Location()
simpizza.configure("Fitchen", "?", "?", "https://www.fitchen.be/")
db.session.add(simpizza)
Expand Down
10 changes: 5 additions & 5 deletions app/database/add_oceans_garden.py
@@ -1,7 +1,7 @@
from models import Location, Product
from app import db
from itertools import product

from app import db
from models import Location, Product

zetmelen = ["Nasi", "Bami"]
vlezen = ["Rundsvlees", "Varkensvlees", "Kippenstukkjes"]
Expand Down Expand Up @@ -29,7 +29,7 @@
]


def add():
def add() -> None:
chinees = Location()
chinees.configure(
"Oceans's Garden",
Expand All @@ -39,12 +39,12 @@ def add():
)
db.session.add(chinees)

def chinees_create_entry(name):
def chinees_create_entry(name) -> None:
entry = Product()
entry.configure(chinees, name, 550)
db.session.add(entry)

def chinees_create_regulat(zetmeel, vlees="", saus=""):
def chinees_create_regulat(zetmeel, vlees="", saus="") -> None:
chinees_create_entry("{} {} {}".format(zetmeel, vlees, saus).rstrip())

for z, v, s in product(zetmelen, vlezen, sauzen):
Expand Down
6 changes: 3 additions & 3 deletions app/database/add_primadonna.py
@@ -1,5 +1,5 @@
from models import Location, Product
from app import db
from models import Location, Product


def add():
Expand Down Expand Up @@ -46,7 +46,7 @@ def add():
}


def addTA():
def addTA() -> None:
primadonna_takeaway = Location()
primadonna_takeaway.configure(
"Primadonna (takeaway laten bezorgen)",
Expand Down Expand Up @@ -101,7 +101,7 @@ def addTA():
}


def addAfhalen():
def addAfhalen() -> None:
primadonna_afhalen = Location()
primadonna_afhalen.configure(
"Primadonna (bellen en afhalen)",
Expand Down
5 changes: 2 additions & 3 deletions app/database/add_simpizza.py
@@ -1,6 +1,5 @@
from models import Location, Product
from app import db

from models import Location, Product

pizzas = [
"Bolognese de luxe",
Expand Down Expand Up @@ -33,7 +32,7 @@
]


def add():
def add() -> None:
simpizza = Location()
simpizza.configure(
"Sim-pizza",
Expand Down
8 changes: 4 additions & 4 deletions app/database/add_stefanos.py
@@ -1,5 +1,5 @@
from models import Location, Product
from app import db
from models import Location, Product

bickies = {
"Bicky Burger Original": 330,
Expand All @@ -11,7 +11,7 @@
"Bicky Veggie": 350,
}

saus = {
sauskes = {
"american": 70,
"andalouse": 70,
"bicky saus": 70,
Expand Down Expand Up @@ -100,7 +100,7 @@
data = [special_bickies, specials, vlezekes, friet]


def add():
def add() -> None:
stefanos = Location()
stefanos.configure(
"Stefano's Place",
Expand All @@ -127,7 +127,7 @@ def add():
db.session.add(item)

# saus in een potteke bestellen is 10 cent extra
for name, price in saus.items():
for name, price in sauskes.items():
saus = Product()
saus.configure(stefanos, name, price)
db.session.add(saus)
Expand Down
31 changes: 17 additions & 14 deletions app/database/create_database.py
@@ -1,6 +1,9 @@
import add_admins
import add_fitchen
import add_oceans_garden
import add_primadonna
import add_simpizza
from app import db
import add_oceans_garden, add_admins, add_simpizza, add_primadonna, add_fitchen


entry_sets = {
"Admins": add_admins.add,
Expand All @@ -15,23 +18,23 @@


# Commit all the things
def commit():
def commit() -> None:
db.session.commit()
print("Committing successful")


def check_if_overwrite():
def check_if_overwrite() -> bool:
answer = input("Do you want to overwrite the previous database? (y/N) ")
return answer in yes


def add_all():
def add_all() -> None:
for entry_set in entry_sets.keys():
print("Adding {}.".format(entry_set))
entry_sets[entry_set]()


def recreate_from_scratch():
def recreate_from_scratch() -> None:
confirmation = "Are you very very sure? (Will delete previous entries!) (y/N) "
check = "I acknowledge any repercussions!"
if input(confirmation) in yes and input("Type: '{}' ".format(check)) == check:
Expand All @@ -41,10 +44,10 @@ def recreate_from_scratch():
add_to_current()


def add_to_current():
def add_to_current() -> None:
available = [entry_set for entry_set in entry_sets]

def add_numbers():
def add_numbers() -> str:
return " ".join(
["{}({}), ".format(loc, i) for i, loc in enumerate(available)]
).rstrip(", ")
Expand All @@ -59,17 +62,17 @@ def add_numbers():
available = []
elif answer == "C":
pass
elif answer in [str(x) for x in range(len(available))]:
answer = int(answer)
print("Adding {}.".format(available[answer]))
entry_sets[str(available[answer])]()
del available[answer]
elif answer.isnumeric() and answer in [str(x) for x in range(len(available))]:
answer_index = int(answer)
print("Adding {}.".format(available[answer_index]))
entry_sets[str(available[answer_index])]()
del available[answer_index]
else:
print("Not a valid answer.")
print("Thank you for adding, come again!")


def init():
def init() -> None:
print("Database modification script!")
print("=============================\n\n")
if check_if_overwrite():
Expand Down
4 changes: 3 additions & 1 deletion app/fatmodels.py
@@ -1,3 +1,5 @@
import typing

from sqlalchemy.sql import desc, func

from models import Location, Order, OrderItem, Product, User
Expand Down Expand Up @@ -42,7 +44,7 @@ class FatOrderItem(OrderItem, FatModel):

class FatProduct(Product, FatModel):
@classmethod
def top4(cls):
def top4(cls) -> None:
top4 = (
OrderItem.query.join(Product)
.join(Location)
Expand Down
11 changes: 6 additions & 5 deletions app/forms.py
Expand Up @@ -3,7 +3,8 @@
from flask import session
from flask_login import current_user
from flask_wtf import FlaskForm as Form
from wtforms import DateTimeField, SelectField, StringField, SubmitField, validators
from wtforms import (DateTimeField, SelectField, StringField, SubmitField,
validators)

from models import Location, User
from utils import euro_string
Expand All @@ -20,7 +21,7 @@ class OrderForm(Form):
stoptime = DateTimeField("Stoptime", format="%d-%m-%Y %H:%M")
submit_button = SubmitField("Submit")

def populate(self):
def populate(self) -> None:
if current_user.is_admin():
self.courrier_id.choices = [(0, None)] + [
(u.id, u.username) for u in User.query.order_by("username")
Expand All @@ -42,7 +43,7 @@ class OrderItemForm(Form):
extra = StringField("Extra")
submit_button = SubmitField("Submit")

def populate(self, location):
def populate(self, location: Location) -> None:
self.product_id.choices = [
(i.id, (i.name + ": " + euro_string(i.price))) for i in location.products
]
Expand All @@ -51,12 +52,12 @@ def populate(self, location):
class AnonOrderItemForm(OrderItemForm):
name = StringField("Name", validators=[validators.required()])

def populate(self, location):
def populate(self, location: Location) -> None:
OrderItemForm.populate(self, location)
if self.name.data is None:
self.name.data = session.get("anon_name", None)

def validate(self):
def validate(self) -> bool:
rv = OrderForm.validate(self)
if not rv:
return False
Expand Down