Exemplo n.º 1
0
def adduser(name, email, group, profitgroup, birthday):
    user = User(name=name, email=email, usergroup_id=group, profitgroup_id=profitgroup, birthday=birthday)
    db.session.add(user)
    db.session.commit()

    statshandler.update_daily_stats('users', 1)

    return "Gebruiker {} succesvol geregistreerd".format(user.name), "success"
Exemplo n.º 2
0
def soft_del_user(user_id):
    user = User.query.get(user_id)

    if user.balance != 0:
        return "Verwijderen van gebruiker {} mislukt: gebruiker heeft nog saldo!".format(user.name), "danger"

    user.deleted = not user.deleted
    db.session.commit()

    if user.deleted:
        statshandler.update_daily_stats('users', -1)
        return "Verwijderen van gebruiker {} gelukt!"
    if not user.deleted:
        statshandler.update_daily_stats('users', 1)
        return "Verwijderen van gebruiker {} ongedaan gemaakt!"
Exemplo n.º 3
0
def editdrink_attr(product_id, name, price, category, order, purchaseable, recipe, inventory_warning, alcohol, volume,
                   unit):
    result_recipe = parse_recipe(recipe)
    if type(result_recipe) is tuple:
        return result_recipe

    product = Product.query.get(product_id)

    if product.recipe_input != result_recipe:
        for r in Recipe.query.filter(Recipe.product_id == product.id):
            db.session.delete(r)
        for key, val in result_recipe:
            db.session.add(Recipe(product_id=product.id, ingredient_id=key, quantity=val))

    purchaseable_old = product.purchaseable

    product.name = name
    product.price = price
    product.category = category
    if order > Product.query.count():
        order = Product.query.count()
    if order < product.order:
        p_ord = Product.query.filter(Product.order >= order, Product.order < product.order).all()
        for i in range(0, len(p_ord)):
            p_ord[i].order = p_ord[i].order + 1
    elif order > product.order:
        p_ord = Product.query.filter(Product.order <= order, Product.order > product.order).all()
        for i in range(0, len(p_ord)):
            p_ord[i].order = p_ord[i].order - 1
    product.order = order
    product.purchaseable = purchaseable
    product.recipe_input = result_recipe
    product.inventory_warning = inventory_warning
    if alcohol != "":
        product.alcohol = alcohol / 100
    else:
        product.alcohol = None
    product.volume = volume
    product.unit = unit
    db.session.commit()

    if purchaseable_old is True and purchaseable is False:
        statshandler.update_daily_stats('products', -1)
    elif purchaseable_old is False and purchaseable is True:
        statshandler.update_daily_stats('products', 1)

    return "Product {} (ID: {}) succesvol aangepast!".format(product.name, product.id), "success"
Exemplo n.º 4
0
def addbalance(user_id, description, amount, profit_id=None):
    # Create an upgrade entry and add it to the database
    upgrade = Upgrade(user_id=user_id, description=description, timestamp=datetime.now(), amount=amount)
    db.session.add(upgrade)
    db.session.commit()
    # Get the user object
    user = User.query.get(upgrade.user_id)
    # Upgrade its balance
    user.balance = user.balance + float(amount)
    # Create a transaction object with the new balance and the upgrade entry and add it to the database
    transaction = Transaction(user_id=user_id, timestamp=datetime.now(), upgrade_id=upgrade.id,
                              balchange=upgrade.amount, profit_id=profit_id, newbal=user.balance)
    db.session.add(transaction)
    db.session.commit()

    # Update the daily stats accordingly
    statshandler.update_daily_stats('euros', upgrade.amount)

    return upgrade
Exemplo n.º 5
0
def adddrink(name, price, category, order, image, hoverimage, recipe, inventory_warning, alcohol, volume, unit):
    # Get the recipe if it exists
    result_recipe = parse_recipe(recipe)
    # If the result_recipe is a tuple, it is a return message so we return it
    if type(result_recipe) is tuple:
        return result_recipe
    # If no inventory warning is set, we set it to zero by default
    if inventory_warning is None:
        inventory_warning = 0
    else:
        inventory_warning = int(inventory_warning)

    # Get the filename of both images and check that they have the correct extensions
    s_filename, s_file_extension = os.path.splitext(secure_filename(image.filename))
    if s_file_extension[1:] not in app.config["ALLOWED_EXTENSIONS"]:
        return "Statische afbeelding is niet van het correcte bestandstype (geen .png, .jpg, .bmp of .gif)", "danger"
    if hoverimage != "":
        h_filename, h_file_extension = os.path.splitext(secure_filename(hoverimage.filename))
        if h_file_extension[1:] not in app.config["ALLOWED_EXTENSIONS"]:
            return "Hover afbeelding is niet van het correcte bestandstype (geen .png, .jpg, .bmp of .gif)", "danger"

    # Calculate the product placement in the order list
    amount_of_prod = Product.query.count()
    # If the order number is smaller than the amount...
    if order < amount_of_prod:
        # We need to increase the order number of all successive products
        p_ord = Product.query.filter(Product.order >= order).all()
        for i in range(0, len(p_ord)):
            p_ord[i].order = p_ord[i].order + 1
    # If this is not the case, we set the position to the last product in the list
    elif order >= amount_of_prod:
        order = amount_of_prod + 1

    # If we have a recipe...
    if result_recipe is not None:
        # We create a product with the recipe
        product = Product(name=name, price=price, category=category, order=order, purchaseable=True, image="",
                          hoverimage="",
                          recipe_input=result_recipe)
    # If we do not have a recipe...
    else:
        # We set the default values of volume and alcohol if none is given
        if volume is "":
            volume = 0
        if alcohol is "":
            alcohol = 0
        # Then, we create a new product in the database
        product = Product(name=name, price=price, category=category, order=order, purchaseable=True, image="",
                          hoverimage="", inventory_warning=inventory_warning, volume=volume, unit=unit,
                          alcohol=alcohol / 100)
    db.session.add(product)
    db.session.commit()

    # If we have a recipe...
    if result_recipe is not None:
        # Then we need to add a recipe entry for all ingredients in the database
        for key, val in result_recipe.items():
            db.session.add(Recipe(product_id=product.id, ingredient_id=key, quantity=val))
        db.session.commit()

    # Create the upload folder if it does not exist
    if not os.path.exists(app.config["UPLOAD_FOLDER"]):
        os.makedirs(app.config["UPLOAD_FOLDER"])
    # Set the product images
    product.image = create_filename(product, str(product.id) + "s-0", image, "s")
    image.save(os.path.join(app.config["UPLOAD_FOLDER"], product.image))

    if hoverimage == "":
        product.hoverimage = product.image
    else:
        product.hoverimage = create_filename(product, str(product.id) + "h-0", hoverimage, "h")
        hoverimage.save(os.path.join(app.config["UPLOAD_FOLDER"], product.hoverimage))
    db.session.commit()

    # Update the daily stats because we added a product
    statshandler.update_daily_stats('products', 1)

    return "Product {} succesvol aangemaakt".format(product.name), "success"
Exemplo n.º 6
0
def addpurchase(drink_id, user_id, quantity, rondje, price_per_one):
    # Round quantity to at most two decimals
    quantity = round_up(quantity)
    # Get drink and user objects from database
    drink = Product.query.get(drink_id)
    user = User.query.get(user_id)

    # If the price is zero, we do not have to take any inventory
    if price_per_one > 0:
        # If we product is not a mix, we can simply take it from inventory
        if drink.recipe_input is None:
            inventory = take_from_inventory(user, drink_id, quantity)
        # However, if the product is a mix...
        else:
            inventory = {'costs': 0, 'inventory_usage': []}
            # For every ingredient of the mix...
            for r in Recipe.query.filter(Recipe.product_id == drink.id).all():
                # Take the respective quantity from inventory
                result = take_from_inventory(user, r.ingredient_id, round_up(r.quantity * quantity))
                # Add the costs of the ingredient to the total costs
                inventory['costs'] = inventory['costs'] + result['costs']
                # Add the inventory usage
                inventory['inventory_usage'] = inventory['inventory_usage'] + result['inventory_usage']
    else:
        # We take no inventory if the price is zero, so the costs are zero
        inventory = {'costs': 0, 'inventory_usage': []}

    # Get the profitgroup of the user
    profitgroup = Usergroup.query.get(user.profitgroup_id)
    # Calculate the profit
    prof = round_down((price_per_one * quantity - inventory['costs']) * app.config['PROFIT_PERCENTAGE'])
    # Add the profit to the group
    profitgroup.profit = profitgroup.profit + prof
    # Create a row object for the profit table
    profit_obj = Profit(profitgroup_id=profitgroup.id, timestamp=datetime.now(),
                        percentage=app.config['PROFIT_PERCENTAGE'], change=prof, new=profitgroup.profit)
    db.session.add(profit_obj)
    # Save to database
    db.session.commit()

    # Calculate the new user balance
    user.balance = user.balance - round_up(float(price_per_one) * quantity)
    # Create a purchase entry in the table, so we can use its purchase ID to create the transaction
    purchase = Purchase(user_id=user.id, timestamp=datetime.now(), product_id=drink.id, price=price_per_one,
                        amount=quantity, round=rondje)
    db.session.add(purchase)
    db.session.commit()

    # Create all inventory usage entries
    for x in inventory['inventory_usage']:
        i_u = Inventory_usage(purchase_id=purchase.id, inventory_id=x['id'], quantity=x['quantity'])
        db.session.add(i_u)
        db.session.commit()
        # Set the object to None to clean up after creation
        i_u = None

    # Calculate the change in balance
    balchange = round_down(-price_per_one * quantity)
    # Create a transaction entry and add it to the database
    transaction = Transaction(user_id=user.id, timestamp=datetime.now(), purchase_id=purchase.id,
                              profit_id=profit_obj.id, balchange=balchange, newbal=user.balance)
    db.session.add(transaction)
    db.session.commit()

    # Update the daily stats with the new purchase
    statshandler.update_daily_stats('euros', balchange)
    statshandler.update_daily_stats_purchase(user_id, drink_id, quantity, rondje, price_per_one)

    return quantity, drink.name, user.name, "success"
Exemplo n.º 7
0
def recalc_max():
    print(
        'Recalculating all maximum daily stats values will overwrite the old values. This action is irreversible!'
    )
    print('Are you sure you want to continue (y/n)?')
    answer = input()
    if answer != 'y':
        print('Aborted')
        return

    # First, reset the daily and the max stats
    statshandler.reset_max_stats()
    statshandler.reset_daily_stats(True)

    # Calculate the amount of days between the release of Tikker and today
    begin = datetime(year=2019, month=9, day=1, hour=12)
    now = datetime.now()
    days = (now - begin).days

    print("Recalculating... 0%", end="\r")

    # For every day...
    for i in range(0, days):
        # Get the purchase transactions of that day
        transactions = Transaction.query.filter(
            Transaction.timestamp > begin + timedelta(days=i),
            Transaction.timestamp < begin + timedelta(days=i + 1),
            Transaction.upgrade_id == None).all()
        # For each transaction...
        for t in transactions:
            # Get the purchase
            purchase = t.purchase
            # Update the daily stats with this purchase
            statshandler.update_daily_stats_purchase(purchase.user_id,
                                                     purchase.product_id,
                                                     purchase.amount,
                                                     purchase.round,
                                                     purchase.price)
        # Reset the daily stats when this day is over, so we can continue with the next
        statshandler.reset_daily_stats(True)

        print("Recalculating... {}%".format(int(i / days * 45)), end="\r")

    # Loop again over all transactions, but now include every single one
    transactions = Transaction.query.all()
    for i in range(0, len(transactions)):
        # Apply the balance change, so we can find the maximum sum of all balances
        statshandler.update_daily_stats("euros", transactions[i].balchange)

        print("Recalculating... {}%".format(
            int(i / len(transactions) * 45) + 45),
              end="\r")

    # Finally, find the two maximum values of the amount of products and the amount of users
    # These two models however are not being tracked over time. Thus, the best thing we can do is to simply save their
    # current nummer at this point in time. The 'products' daily statistic can be tricked though: temporarily set some
    # old products to purchaseable and they will count.
    statshandler.update_daily_stats(
        'products',
        Product.query.filter(
            Product.purchaseable == True,
            Product.id != settings['dinner_product_id']).count())
    print("Recalculating... 95%", end="\r")
    statshandler.update_daily_stats('users', User.query.count())
    print("Recalculating... 100%")

    # We are done!
    return