[pricelist][tags] change model of tags, fixed tags on updateDrink

This commit is contained in:
Tim Gröger 2021-04-01 22:45:28 +02:00
parent 15c7a56d56
commit 5c688df392
3 changed files with 44 additions and 15 deletions

View File

@ -4,6 +4,7 @@ from flask import Blueprint, jsonify, request, current_app
from werkzeug.local import LocalProxy
from werkzeug.exceptions import BadRequest, Forbidden, Unauthorized
from flaschengeist import logger
from flaschengeist.plugins import Plugin
from flaschengeist.utils.decorators import login_required, extract_session
from flaschengeist.utils.HTTP import no_content
@ -78,9 +79,7 @@ def get_tags(identifier=None):
@login_required(permission=permissions.CREATE_TAG)
def new_tag(current_session):
data = request.get_json()
if "name" not in data:
raise BadRequest
drink_type = pricelist_controller.create_tag(data["name"])
drink_type = pricelist_controller.create_tag(data)
return jsonify(drink_type)
@ -88,9 +87,7 @@ def new_tag(current_session):
@login_required(permission=permissions.EDIT_TAG)
def update_tag(identifier, current_session):
data = request.get_json()
if "name" not in data:
raise BadRequest
tag = pricelist_controller.rename_tag(identifier, data["name"])
tag = pricelist_controller.update_tag(identifier, data)
return jsonify(tag)
@ -115,6 +112,7 @@ def get_drinks(identifier=None):
result = pricelist_controller.get_drink(identifier, public=public)
else:
result = pricelist_controller.get_drinks(public=public)
logger.debug(f"GET drink {result}")
return jsonify(result)
@ -133,6 +131,7 @@ def create_drink(current_session):
@PriceListPlugin.blueprint.route("/drinks/<int:identifier>", methods=["PUT"])
def update_drink(identifier):
data = request.get_json()
logger.debug(f"update drink {data}")
return jsonify(pricelist_controller.update_drink(identifier, data))
@ -232,6 +231,7 @@ def get_columns(userid, current_session: Session):
userController.persist()
return no_content()
@PriceListPlugin.blueprint.route("/drinks/<int:identifier>/picture", methods=["POST", "GET", "DELETE"])
def set_picture(identifier):
@ -248,9 +248,10 @@ def set_picture(identifier):
else:
raise BadRequest
@PriceListPlugin.blueprint.route("/picture/<identifier>", methods=["GET"])
def _get_picture(identifier):
if request.method == "GET":
size = request.args.get("size")
response = pricelist_controller.get_drink_picture(identifier, size)
return response.make_conditional(request)
return response.make_conditional(request)

View File

@ -26,6 +26,7 @@ class Tag(db.Model, ModelSerializeMixin):
__tablename__ = "drink_tag"
id: int = db.Column("id", db.Integer, primary_key=True)
name: str = db.Column(db.String(30), nullable=False, unique=True)
color: str = db.Column(db.String(7), nullable=False)
class DrinkType(db.Model, ModelSerializeMixin):
@ -51,6 +52,9 @@ class DrinkPrice(db.Model, ModelSerializeMixin):
public: bool = db.Column(db.Boolean, default=True)
description: Optional[str] = db.Column(db.String(30))
def __repr__(self):
return f"DrinkPric({self.id},{self.price},{self.public},{self.description})"
class ExtraIngredient(db.Model, ModelSerializeMixin):
"""
@ -123,6 +127,9 @@ class DrinkPriceVolume(db.Model, ModelSerializeMixin):
prices: list[DrinkPrice] = db.relationship(DrinkPrice, back_populates="volume", cascade="all,delete,delete-orphan")
ingredients: list[Ingredient] = db.relationship("Ingredient", foreign_keys=Ingredient.volume_id)
def __repr__(self):
return f"DrinkPriceVolume({self.id},{self.drink_id},{self.prices})"
class Drink(db.Model, ModelSerializeMixin):
"""
@ -147,6 +154,9 @@ class Drink(db.Model, ModelSerializeMixin):
type: Optional[DrinkType] = db.relationship("DrinkType", foreign_keys=[_type_id])
volumes: list[DrinkPriceVolume] = db.relationship(DrinkPriceVolume)
def __repr__(self):
return f"Drink({self.id},{self.name},{self.volumes})"
class _Picture:
"""Wrapper class for pictures binaries"""

View File

@ -31,9 +31,13 @@ def get_tag(identifier):
return ret
def create_tag(name):
def create_tag(data):
try:
tag = Tag(name=name)
if "id" in data:
data.pop("id")
allowed_keys = Tag().serialize().keys()
values = {key: value for key, value in data.items() if key in allowed_keys}
tag = Tag(**values)
db.session.add(tag)
update()
return tag
@ -41,9 +45,12 @@ def create_tag(name):
raise BadRequest("Name already exists")
def rename_tag(identifier, new_name):
def update_tag(identifier, data):
tag = get_tag(identifier)
tag.name = new_name
allowed_keys = Tag().serialize().keys()
values = {key: value for key, value in data.items() if key in allowed_keys}
for key, value in values.items():
setattr(tag, key, value)
try:
update()
except IntegrityError:
@ -104,6 +111,7 @@ def delete_drink_type(identifier):
except IntegrityError:
raise BadRequest("DrinkType still in use")
def _create_public_drink(drink):
_volumes = []
for volume in drink.volumes:
@ -120,6 +128,7 @@ def _create_public_drink(drink):
return drink
return None
def get_drinks(name=None, public=False):
if name:
drinks = Drink.query.filter(Drink.name.contains(name)).all()
@ -153,8 +162,13 @@ def update_drink(identifier, data):
if "id" in data:
data.pop("id")
volumes = data.pop("volumes") if "volumes" in data else None
tags = []
if "tags" in data:
data.pop("tags")
_tags = data.pop("tags")
if isinstance(_tags, list):
for _tag in _tags:
if isinstance(_tag, dict) and "id" in _tag:
tags.append(get_tag(_tag["id"]))
drink_type = data.pop("type")
if isinstance(drink_type, dict) and "id" in drink_type:
drink_type = drink_type["id"]
@ -172,6 +186,8 @@ def update_drink(identifier, data):
drink.type = drink_type
if volumes is not None:
set_volumes(volumes, drink)
if len(tags) > 0:
drink.tags = tags
db.session.commit()
return drink
except (NotFound, KeyError):
@ -265,7 +281,9 @@ def get_prices(volume_id=None):
def set_price(data):
allowed_keys = DrinkPrice().serialize().keys()
allowed_keys = list(DrinkPrice().serialize().keys())
allowed_keys.append("description")
logger.debug(f"allowed_key {allowed_keys}")
values = {key: value for key, value in data.items() if key in allowed_keys}
price_id = values.pop("id", -1)
if price_id < 0:
@ -396,7 +414,7 @@ def get_drink_picture(identifier, size=None):
if isinstance(identifier, int):
drink = get_drink(identifier)
if isinstance(identifier, str):
drink = Drink.query.filter(Drink.uuid==identifier).one_or_none()
drink = Drink.query.filter(Drink.uuid == identifier).one_or_none()
try:
if drink:
return get_picture(f"{path}/{drink.uuid}", size)
@ -405,10 +423,10 @@ def get_drink_picture(identifier, size=None):
db.session.commit()
raise FileNotFoundError
def delete_drink_picture(identifier):
drink = get_drink(identifier)
if drink.uuid:
delete_picture(f"{config['pricelist']['path']}/{drink.uuid}")
drink.uuid = None
db.session.commit()