[pricelist] Fixed warnings

This commit is contained in:
Ferdinand Thiessen 2021-03-28 23:14:03 +02:00
parent 3ad1cfa9be
commit 544ae6a3fe
3 changed files with 101 additions and 114 deletions

View File

@ -1,19 +1,21 @@
"""Pricelist plugin""" """Pricelist plugin"""
from flask import Blueprint, jsonify, request from flask import Blueprint, jsonify, request, current_app
from http.client import NO_CONTENT from werkzeug.local import LocalProxy
from werkzeug.exceptions import BadRequest, Forbidden
from flaschengeist.plugins import Plugin from flaschengeist.plugins import Plugin
from flaschengeist.utils.decorators import login_required from flaschengeist.utils.decorators import login_required
from werkzeug.exceptions import BadRequest, Forbidden from flaschengeist.utils.HTTP import no_content
from flaschengeist.models.session import Session
from flaschengeist.controller import userController
from . import models from . import models
from . import pricelist_controller, permissions from . import pricelist_controller, permissions
from ...controller import userController
from ...models.session import Session
from ...utils.HTTP import no_content
pricelist_bp = Blueprint("pricelist", __name__, url_prefix="/pricelist") plugin_name = "pricelist"
pricelist_bp = Blueprint(plugin_name, __name__, url_prefix="/pricelist")
plugin = LocalProxy(lambda: current_app.config["FG_PLUGINS"][plugin_name])
class PriceListPlugin(Plugin): class PriceListPlugin(Plugin):
@ -28,10 +30,10 @@ class PriceListPlugin(Plugin):
@pricelist_bp.route("/drink-types", methods=["GET"]) @pricelist_bp.route("/drink-types", methods=["GET"])
@pricelist_bp.route("/drink-types/<int:identifier>", methods=["GET"]) @pricelist_bp.route("/drink-types/<int:identifier>", methods=["GET"])
def get_drink_types(identifier=None): def get_drink_types(identifier=None):
if identifier: if identifier is None:
result = pricelist_controller.get_drink_type(identifier)
else:
result = pricelist_controller.get_drink_types() result = pricelist_controller.get_drink_types()
else:
result = pricelist_controller.get_drink_type(identifier)
return jsonify(result) return jsonify(result)
@ -51,7 +53,7 @@ def update_drink_type(identifier, current_session):
data = request.get_json() data = request.get_json()
if "name" not in data: if "name" not in data:
raise BadRequest raise BadRequest
drink_type = pricelist_controller.rename_drink_type(data["id"], data["name"]) drink_type = pricelist_controller.rename_drink_type(identifier, data["name"])
return jsonify(drink_type) return jsonify(drink_type)
@ -59,7 +61,7 @@ def update_drink_type(identifier, current_session):
@login_required(permission=permissions.DELETE_TYPE) @login_required(permission=permissions.DELETE_TYPE)
def delete_drink_type(identifier, current_session): def delete_drink_type(identifier, current_session):
pricelist_controller.delete_drink_type(identifier) pricelist_controller.delete_drink_type(identifier)
return "", NO_CONTENT return no_content()
@pricelist_bp.route("/tags", methods=["GET"]) @pricelist_bp.route("/tags", methods=["GET"])
@ -88,15 +90,15 @@ def update_tag(identifier, current_session):
data = request.get_json() data = request.get_json()
if "name" not in data: if "name" not in data:
raise BadRequest raise BadRequest
drink_type = pricelist_controller.rename_tag(data["name"]) tag = pricelist_controller.rename_tag(identifier, data["name"])
return jsonify(drink_type) return jsonify(tag)
@pricelist_bp.route("/tags/<int:identifier>", methods=["DELETE"]) @pricelist_bp.route("/tags/<int:identifier>", methods=["DELETE"])
@login_required(permission=permissions.DELETE_TAG) @login_required(permission=permissions.DELETE_TAG)
def delete_tag(identifier, current_session): def delete_tag(identifier, current_session):
pricelist_controller.delete_tag(identifier) pricelist_controller.delete_tag(identifier)
return "", NO_CONTENT return no_content()
@pricelist_bp.route("/drinks", methods=["GET"]) @pricelist_bp.route("/drinks", methods=["GET"])
@ -130,30 +132,30 @@ def update_drink(identifier):
@pricelist_bp.route("/drinks/<int:identifier>", methods=["DELETE"]) @pricelist_bp.route("/drinks/<int:identifier>", methods=["DELETE"])
def delete_drink(identifier): def delete_drink(identifier):
pricelist_controller.delete_drink(identifier) pricelist_controller.delete_drink(identifier)
return "", NO_CONTENT return no_content()
@pricelist_bp.route("/prices/<int:identifier>", methods=["DELETE"]) @pricelist_bp.route("/prices/<int:identifier>", methods=["DELETE"])
def delete_price(identifier): def delete_price(identifier):
pricelist_controller.delete_price(identifier) pricelist_controller.delete_price(identifier)
return "", NO_CONTENT return no_content()
@pricelist_bp.route("/volumes/<int:identifier>", methods=["DELETE"]) @pricelist_bp.route("/volumes/<int:identifier>", methods=["DELETE"])
def delete_volume(identifier): def delete_volume(identifier):
pricelist_controller.delete_volume(identifier) pricelist_controller.delete_volume(identifier)
return "", NO_CONTENT return no_content()
@pricelist_bp.route("/ingredients/extraIngredients", methods=["GET"]) @pricelist_bp.route("/ingredients/extraIngredients", methods=["GET"])
def get_extraIngredients(): def get_extra_ingredients():
return jsonify(pricelist_controller.get_extra_ingredients()) return jsonify(pricelist_controller.get_extra_ingredients())
@pricelist_bp.route("/ingredients/<int:identifier>", methods=["DELETE"]) @pricelist_bp.route("/ingredients/<int:identifier>", methods=["DELETE"])
def delete_ingredient(identifier): def delete_ingredient(identifier):
pricelist_controller.delete_ingredient(identifier) pricelist_controller.delete_ingredient(identifier)
return "", NO_CONTENT return no_content()
@pricelist_bp.route("/ingredients/extraIngredients", methods=["POST"]) @pricelist_bp.route("/ingredients/extraIngredients", methods=["POST"])
@ -171,19 +173,19 @@ def update_extra_ingredient(identifier):
@pricelist_bp.route("/ingredients/extraIngredients/<int:identifier>", methods=["DELETE"]) @pricelist_bp.route("/ingredients/extraIngredients/<int:identifier>", methods=["DELETE"])
def delete_extra_ingredient(identifier): def delete_extra_ingredient(identifier):
pricelist_controller.delete_extra_ingredient(identifier) pricelist_controller.delete_extra_ingredient(identifier)
return "", NO_CONTENT return no_content()
@pricelist_bp.route("/settings/min_prices", methods=["POST", "GET"]) @pricelist_bp.route("/settings/min_prices", methods=["POST", "GET"])
def pricelist_settings_min_prices(): def pricelist_settings_min_prices():
if request.method == "GET": if request.method == "GET":
return jsonify(PriceListPlugin.get_setting(PriceListPlugin, "min_prices")) return jsonify(plugin.get_setting("min_prices"))
else: else:
data = request.get_json() data = request.get_json()
if not isinstance(data, list) or not all(isinstance(n, int) for n in data): if not isinstance(data, list) or not all(isinstance(n, int) for n in data):
raise BadRequest raise BadRequest
data.sort() data.sort()
PriceListPlugin.set_setting(PriceListPlugin, "min_prices", data) plugin.set_setting("min_prices", data)
return no_content() return no_content()

View File

@ -3,7 +3,7 @@ from __future__ import annotations # TODO: Remove if python requirement is >= 3
from flaschengeist.database import db from flaschengeist.database import db
from flaschengeist.models import ModelSerializeMixin from flaschengeist.models import ModelSerializeMixin
from typing import Optional, Union from typing import Optional
drink_tag_association = db.Table( drink_tag_association = db.Table(
"drink_x_tag", "drink_x_tag",
@ -71,7 +71,7 @@ class DrinkIngredient(db.Model, ModelSerializeMixin):
__tablename__ = "drink_ingredient" __tablename__ = "drink_ingredient"
id: int = db.Column("id", db.Integer, primary_key=True) id: int = db.Column("id", db.Integer, primary_key=True)
volume: float = db.Column(db.Numeric(precision=5, scale=2, asdecimal=False), nullable=False) volume: float = db.Column(db.Numeric(precision=5, scale=2, asdecimal=False), nullable=False)
drink_ingredient_id: int = db.Column("drink_ingredient_id", db.Integer, db.ForeignKey("drink.id")) ingredient_id: int = db.Column(db.Integer, db.ForeignKey("drink.id"))
# drink_ingredient: Drink = db.relationship("Drink") # drink_ingredient: Drink = db.relationship("Drink")
# price: float = 0 # price: float = 0
@ -92,11 +92,12 @@ class Ingredient(db.Model, ModelSerializeMixin):
__tablename__ = "ingredient_association" __tablename__ = "ingredient_association"
id: int = db.Column("id", db.Integer, primary_key=True) id: int = db.Column("id", db.Integer, primary_key=True)
volume_id = db.Column(db.Integer, db.ForeignKey("drink_price_volume.id")) volume_id = db.Column(db.Integer, db.ForeignKey("drink_price_volume.id"))
drink_ingredient_id = db.Column(db.Integer, db.ForeignKey("drink_ingredient.id"))
drink_ingredient: Optional[DrinkIngredient] = db.relationship(DrinkIngredient) drink_ingredient: Optional[DrinkIngredient] = db.relationship(DrinkIngredient)
extra_ingredient_id = db.Column(db.Integer, db.ForeignKey("extra_ingredient.id"))
extra_ingredient: Optional[ExtraIngredient] = db.relationship(ExtraIngredient) extra_ingredient: Optional[ExtraIngredient] = db.relationship(ExtraIngredient)
_drink_ingredient_id = db.Column(db.Integer, db.ForeignKey("drink_ingredient.id"))
_extra_ingredient_id = db.Column(db.Integer, db.ForeignKey("extra_ingredient.id"))
class MinPrices(ModelSerializeMixin): class MinPrices(ModelSerializeMixin):
""" """
@ -134,8 +135,8 @@ class Drink(db.Model, ModelSerializeMixin):
package_size: Optional[int] = db.Column(db.Integer) package_size: Optional[int] = db.Column(db.Integer)
name: str = db.Column(db.String(60), nullable=False) name: str = db.Column(db.String(60), nullable=False)
volume: Optional[float] = db.Column(db.Numeric(precision=5, scale=2, asdecimal=False)) volume: Optional[float] = db.Column(db.Numeric(precision=5, scale=2, asdecimal=False))
cost_price_pro_volume: Optional[float] = db.Column(db.Numeric(precision=5, scale=3, asdecimal=False)) cost_per_volume: Optional[float] = db.Column(db.Numeric(precision=5, scale=3, asdecimal=False))
cost_price_package_netto: Optional[float] = db.Column(db.Numeric(precision=5, scale=3, asdecimal=False)) cost_per_package: Optional[float] = db.Column(db.Numeric(precision=5, scale=3, asdecimal=False))
uuid = db.Column(db.String(36)) uuid = db.Column(db.String(36))

View File

@ -1,14 +1,13 @@
from werkzeug.exceptions import BadRequest, NotFound from werkzeug.exceptions import BadRequest, NotFound
from sqlalchemy.exc import IntegrityError from sqlalchemy.exc import IntegrityError
from uuid import uuid4
from flaschengeist import logger from flaschengeist import logger
from flaschengeist.config import config from flaschengeist.config import config
from flaschengeist.database import db from flaschengeist.database import db
from .models import Drink, DrinkPrice, Ingredient, Tag, DrinkType, DrinkPriceVolume, DrinkIngredient, ExtraIngredient
from flaschengeist.utils.picture import save_picture, get_picture from flaschengeist.utils.picture import save_picture, get_picture
from uuid import uuid4 from .models import Drink, DrinkPrice, Ingredient, Tag, DrinkType, DrinkPriceVolume, DrinkIngredient, ExtraIngredient
def update(): def update():
@ -21,15 +20,15 @@ def get_tags():
def get_tag(identifier): def get_tag(identifier):
if isinstance(identifier, int): if isinstance(identifier, int):
retVal = Tag.query.get(identifier) ret = Tag.query.get(identifier)
elif isinstance(identifier, str): elif isinstance(identifier, str):
retVal = Tag.query.filter(Tag.name == identifier).one_or_none() ret = Tag.query.filter(Tag.name == identifier).one_or_none()
else: else:
logger.debug("Invalid identifier type for Tag") logger.debug("Invalid identifier type for Tag")
raise BadRequest raise BadRequest
if not retVal: if ret is None:
raise NotFound raise NotFound
return retVal return ret
def create_tag(name): def create_tag(name):
@ -66,23 +65,23 @@ def get_drink_types():
def get_drink_type(identifier): def get_drink_type(identifier):
if isinstance(identifier, int): if isinstance(identifier, int):
retVal = DrinkType.query.get(identifier) ret = DrinkType.query.get(identifier)
elif isinstance(identifier, str): elif isinstance(identifier, str):
retVal = DrinkType.query.filter(Tag.name == identifier).one_or_none() ret = DrinkType.query.filter(Tag.name == identifier).one_or_none()
else: else:
logger.debug("Invalid identifier type for DrinkType") logger.debug("Invalid identifier type for DrinkType")
raise BadRequest raise BadRequest
if not retVal: if ret is None:
raise NotFound raise NotFound
return retVal return ret
def create_drink_type(name): def create_drink_type(name):
try: try:
drinkType = DrinkType(name=name) drink_type = DrinkType(name=name)
db.session.add(drinkType) db.session.add(drink_type)
update() update()
return drinkType return drink_type
except IntegrityError: except IntegrityError:
raise BadRequest("Name already exists") raise BadRequest("Name already exists")
@ -98,8 +97,8 @@ def rename_drink_type(identifier, new_name):
def delete_drink_type(identifier): def delete_drink_type(identifier):
drinkType = get_drink_type(identifier) drink_type = get_drink_type(identifier)
db.session.delete(drinkType) db.session.delete(drink_type)
try: try:
update() update()
except IntegrityError: except IntegrityError:
@ -114,13 +113,14 @@ def get_drinks(name=None):
def get_drink(identifier): def get_drink(identifier):
if isinstance(identifier, int): if isinstance(identifier, int):
return Drink.query.get(identifier) drink = Drink.query.get(identifier)
elif isinstance(identifier, str): elif isinstance(identifier, str):
return Drink.query.filter(Tag.name == identifier).one_or_none() drink = Drink.query.filter(Tag.name == identifier).one_or_none()
else: else:
logger.debug("Invalid identifier type for Drink") raise BadRequest("Invalid identifier type for Drink")
raise BadRequest if drink is None:
raise NotFound raise NotFound
return drink
def set_drink(data): def set_drink(data):
@ -128,44 +128,40 @@ def set_drink(data):
def update_drink(identifier, data): def update_drink(identifier, data):
allowedKeys = Drink().serialize().keys() try:
if "id" in data: if "id" in data:
data.pop("id") data.pop("id")
if "volumes" in data: volumes = data.pop("volumes") if "volumes" in data else None
volumes = data.pop("volumes") if "tags" in data:
if "tags" in data: data.pop("tags")
data.pop("tags") drink_type = data.pop("type")
type = None if isinstance(drink_type, dict) and "id" in drink_type:
if "type" in data: drink_type = drink_type["id"]
_type = data.pop("type") drink_type = get_drink_type(drink_type)
if isinstance(_type, dict) and "id" in _type: if identifier == -1:
type = get_drink_type(_type.get("id")) drink = Drink()
if identifier == -1: db.session.add(drink)
drink = Drink() else:
db.session.add(drink) drink = get_drink(identifier)
else: for key, value in data.items():
drink = get_drink(identifier) if hasattr(drink, key):
if not drink: setattr(drink, key, value if value != "" else None)
raise NotFound
for key, value in data.items():
if hasattr(drink, key):
setattr(drink, key, value if value != "" else None)
if type: if drink_type:
drink.type = type drink.type = drink_type
if volumes: if volumes is not None:
set_volumes(volumes, drink) set_volumes(volumes, drink)
db.session.commit() db.session.commit()
return drink return drink
except (NotFound, KeyError):
raise BadRequest
def set_volumes(volumes, drink): def set_volumes(volumes, drink):
if isinstance(volumes, list): if not isinstance(volumes, list):
_volumes = [] raise BadRequest
for _volume in volumes: for volume in volumes:
volume = set_volume(_volume) drink.volumes.append(set_volume(volume))
_volumes.append(volume)
drink.volumes = _volumes
def delete_drink(identifier): def delete_drink(identifier):
@ -193,15 +189,12 @@ def set_volume(data):
prices = values.pop("prices") prices = values.pop("prices")
if "ingredients" in values: if "ingredients" in values:
ingredients = values.pop("ingredients") ingredients = values.pop("ingredients")
id = None vol_id = values.pop("id", None)
if "id" in values: if vol_id < 0:
id = values.pop("id")
volume = None
if id < 0:
volume = DrinkPriceVolume(**values) volume = DrinkPriceVolume(**values)
db.session.add(volume) db.session.add(volume)
else: else:
volume = get_volume(id) volume = get_volume(vol_id)
if not volume: if not volume:
raise NotFound raise NotFound
for key, value in values.items(): for key, value in values.items():
@ -253,15 +246,12 @@ def get_prices(volume_id=None):
def set_price(data): def set_price(data):
allowed_keys = DrinkPrice().serialize().keys() allowed_keys = DrinkPrice().serialize().keys()
values = {key: value for key, value in data.items() if key in allowed_keys} values = {key: value for key, value in data.items() if key in allowed_keys}
id = None price_id = values.pop("id", -1)
if "id" in values: if price_id < 0:
id = values.pop("id")
price = None
if id < 0:
price = DrinkPrice(**values) price = DrinkPrice(**values)
db.session.add(price) db.session.add(price)
else: else:
price = get_price(id) price = get_price(price_id)
if not price: if not price:
raise NotFound raise NotFound
for key, value in values.items(): for key, value in values.items():
@ -277,17 +267,14 @@ def delete_price(identifier):
def set_drink_ingredient(data): def set_drink_ingredient(data):
allowedKeys = DrinkIngredient().serialize().keys() allowed_keys = DrinkIngredient().serialize().keys()
drink = None values = {key: value for key, value in data.items() if key in allowed_keys}
values = {key: value for key, value in data.items() if key in allowedKeys} ingredient_id = values.pop("id", -1)
id = None if ingredient_id < 0:
if "id" in values:
id = values.pop("id")
if id < 0:
drink_ingredient = DrinkIngredient(**values) drink_ingredient = DrinkIngredient(**values)
db.session.add(drink_ingredient) db.session.add(drink_ingredient)
else: else:
drink_ingredient = DrinkIngredient.query.get(id) drink_ingredient = DrinkIngredient.query.get(ingredient_id)
if not drink_ingredient: if not drink_ingredient:
raise NotFound raise NotFound
for key, value in values.items(): for key, value in values.items():
@ -306,15 +293,12 @@ def set_ingredient(data):
drink_ingredient_value = data.pop("drink_ingredient") drink_ingredient_value = data.pop("drink_ingredient")
if "extra_ingredient" in data: if "extra_ingredient" in data:
extra_ingredient_value = data.pop("extra_ingredient") extra_ingredient_value = data.pop("extra_ingredient")
id = None ingredient_id = data.pop("id", -1)
if "id" in data: if ingredient_id < 0:
id = data.pop("id")
ingredient = None
if id < 0:
ingredient = Ingredient(**data) ingredient = Ingredient(**data)
db.session.add(ingredient) db.session.add(ingredient)
else: else:
ingredient = get_ingredient(id) ingredient = get_ingredient(ingredient_id)
if not ingredient: if not ingredient:
raise NotFound raise NotFound
if drink_ingredient_value: if drink_ingredient_value:
@ -342,10 +326,10 @@ def get_extra_ingredient(identifier):
def set_extra_ingredient(data): def set_extra_ingredient(data):
allowedKeys = ExtraIngredient().serialize().keys() allowed_keys = ExtraIngredient().serialize().keys()
if "id" in data: if "id" in data:
data.pop("id") data.pop("id")
values = {key: value for key, value in data.items() if key in allowedKeys} values = {key: value for key, value in data.items() if key in allowed_keys}
extra_ingredient = ExtraIngredient(**values) extra_ingredient = ExtraIngredient(**values)
db.session.add(extra_ingredient) db.session.add(extra_ingredient)
db.session.commit() db.session.commit()
@ -353,10 +337,10 @@ def set_extra_ingredient(data):
def update_extra_ingredient(identifier, data): def update_extra_ingredient(identifier, data):
allowedKeys = ExtraIngredient().serialize().keys() allowed_keys = ExtraIngredient().serialize().keys()
if "id" in data: if "id" in data:
data.pop("id") data.pop("id")
values = {key: value for key, value in data.items() if key in allowedKeys} values = {key: value for key, value in data.items() if key in allowed_keys}
extra_ingredient = get_extra_ingredient(identifier) extra_ingredient = get_extra_ingredient(identifier)
if extra_ingredient: if extra_ingredient:
for key, value in values.items(): for key, value in values.items():