Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
Piglet v1.1.0:
- added complete new "future spends" feature
- Bugfixes
- Removed old code
  • Loading branch information
k3nd0x committed Jun 28, 2023
1 parent fd93ec7 commit f5b1825
Show file tree
Hide file tree
Showing 17 changed files with 484 additions and 224 deletions.
2 changes: 2 additions & 0 deletions webapp/api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
from .routes.admin import admin
from .routes.notifications import notifications
from .routes.system import system
from .routes.futurespends import futurespends

app.include_router(user,prefix="/user",tags=["User"])
app.include_router(order,prefix="/order",tags=["Order"])
Expand All @@ -49,3 +50,4 @@
app.include_router(admin,prefix="/admin",tags=["Admin Part"])
app.include_router(notifications,prefix="/notifications",tags=["Notification generation and supplying"])
app.include_router(system,prefix="/system",tags=["Monitoring and Testing"])
app.include_router(futurespends,prefix="/futurespends",tags=["Future Spends orders"])
136 changes: 136 additions & 0 deletions webapp/api/routes/futurespends.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim: showmatch ts=4 sts=4 sw=4 autoindent smartindent smarttab expandtab

from fastapi import APIRouter, Path, Depends,HTTPException
from enum import Enum
import json
from pydantic import BaseModel
from typing import Optional
from datetime import datetime

from .mysql import sql
from .functs import get_budgetid,check,_get_uids,get_notisettings
from .sendmail import mail

from .admin import oauth2_scheme,get_current_user

futurespends = APIRouter()

@futurespends.get("/", summary="Get all future spends by userid or budget_id")
async def spends(budget_id: int, max_entries: Optional[int]=30, current_user = Depends(get_current_user)):
mysql = sql()
check(mysql,current_user["bid_mapping"], budget_id)

query = '''select (select name from registered_user where id=user_id) as user, (select name from pig_category where id=category_id) as category, CONCAT(value,' ',currency) AS value, id, DATE_FORMAT(timestamp, '%Y-%m-%d') as timestamp,description FROM pig_futurespends where budget_id={} order by timestamp DESC'''.format(budget_id)
print(query,flush=True)
response = mysql.get(query)

max_count = 1
return_list = []

for i in response:
if max_count <= max_entries:
return_list.append(i)
max_count += 1

graphquery = f'''select MONTH(TIMESTAMP) as monthnumber, MONTHNAME(TIMESTAMP) as month, sum(value) as value, currency from pig_futurespends where budget_id={budget_id} group by month;'''
response = mysql.get(graphquery)

currentMonth = int(datetime.now().month)

return_dict = { "orders": return_list, "monthlist": [], "valuelist": [], "colorlist": [] }

months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
updated_data = []

if len(response) == 0:
for month_number, month_name in enumerate(months, start=1):
updated_data.append({'monthnumber': month_number, 'month': month_name,'value': 0.0, 'currency': 'EUR'})
else:
existing_data = {entry['monthnumber']: entry for entry in response}

for month_number, month_name in enumerate(months, start=1):
if month_number in existing_data:
updated_data.append(existing_data[month_number])
else:
updated_data.append({'monthnumber': month_number, 'month': month_name,
'value': 0.0, 'currency': response[0]["currency"]})

print(updated_data,flush=True)

for i in updated_data:
if i["monthnumber"] >= currentMonth:
value = float(i['value'])

return_dict["monthlist"].append(i["month"])
return_dict["colorlist"].append('#2739ff')
return_dict["valuelist"].append(value)


mysql.close()
return return_dict

class newSpend(BaseModel):
value: str
userid: str
category: str
description: Optional[str] = None
budget_id: str
timestamp: str
class Config:
schema_extra = {
"example": {
"userid": "1",
"category": "2",
"value": "123.02",
"budget_id": "151",
"description": "Einkaufen Kupsch (ptional)",
"timestamp": "2023-06-28 10:00:00"
}
}

@futurespends.post("/new", summary="Place new order with payload")
async def spends(newSpend: newSpend,current_user = Depends(get_current_user)):
try:
value = float(newSpend.value)
category = int(newSpend.category)
userid = int(newSpend.userid)
budget_id = int(newSpend.budget_id)
description = newSpend.description
timestamp = newSpend.timestamp
except:
return "Variables not valid"
mysql = sql()

if userid != current_user["id"]:
raise HTTPException(status_code=403, detail="Forbidden")

check(mysql,current_user["bid_mapping"], budget_id)

currency_query = f"select currency from pig_budgets where id={budget_id}"
curr = mysql.get(currency_query)[0]["currency"]

query = '''insert into pig_futurespends(value,currency,user_id,category_id,budget_id,description,timestamp) VALUES ({},"{}",{},{},{},"{}","{}")'''.format(value,curr,userid,category,budget_id,description,timestamp)
print(query)
insert = mysql.post(query)
if insert == True:
output = "Order added".format(userid,value, curr, category,description)


mysql.close()
return output
@futurespends.delete("/{id}", summary="Delete order by timestamp")
async def spends(id: str, budget_id: str,current_user = Depends(get_current_user)):
mysql = sql()

userid = current_user["id"]
check(mysql,current_user["bid_mapping"], budget_id)

query = '''delete from pig_futurespends where id="{}" and budget_id={}'''.format(id,budget_id)

response = mysql.delete(query)

mysql.close()

return response
2 changes: 1 addition & 1 deletion webapp/api/routes/order.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ class Config:

@order.post("/new", summary="Place new order with payload")
async def orders(newOrder: newOrder,current_user = Depends(get_current_user)):
mysql = sql()
try:
value = float(newOrder.value)
category = int(newOrder.category)
Expand All @@ -69,6 +68,7 @@ async def orders(newOrder: newOrder,current_user = Depends(get_current_user)):
description = newOrder.description
except:
return "Variables not valid"
mysql = sql()

if userid != current_user["id"]:
raise HTTPException(status_code=403, detail="Forbidden")
Expand Down
13 changes: 13 additions & 0 deletions webapp/config/scripts/piglet-schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,19 @@ CREATE TABLE `registered_user` (
UNIQUE KEY `id` (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE `pig_futurespends` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`value` float(255,2) DEFAULT NULL,
`currency` varchar(100) DEFAULT NULL,
`user_id` int(255) DEFAULT NULL,
`category_id` int(255) DEFAULT NULL,
`budget_id` int(255) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
);

/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

Expand Down
1 change: 1 addition & 0 deletions webapp/source/app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from source.app import register
from source.app import budget_sharing
from source.app import reports
from source.app import future_spends
app.config['UPLOAD_FOLDER'] = PROFILE_PICTURES


Expand Down
28 changes: 28 additions & 0 deletions webapp/source/app/api_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,18 @@ def get(url, data=None,debug=False,auth=None):
response = get(url)

return response
elif mode == "futurespends":
headers["Authorization"] = "Bearer {}".format(auth)

url = baseurl + "futurespends/"
budget_id = data["budget_id"]

url = url + "?budget_id=" + str(budget_id)

response = get(url)

return response


def post_data_api(mode, data,debug=False,auth=None):
baseurl = "http://127.0.0.1:8080/"
Expand Down Expand Up @@ -338,6 +350,11 @@ def put(url,auth=None):

response = post(url)

if mode == "futurespends":
headers["Authorization"] = "Bearer {}".format(auth)
url = baseurl + "futurespends/new"
response = post(url)



return response
Expand Down Expand Up @@ -394,6 +411,17 @@ def delete(url,auth=None):
response = delete(dataurl)

return response
elif mode == "futurespends":
headers["Authorization"] = "Bearer {}".format(auth)

url = baseurl + "futurespends/"

dataurl = "{}{}?budget_id={}".format(url,data["id"],data["budget_id"])

response = delete(dataurl)

return response


def get_token(data):
baseurl = "http://127.0.0.1:8080/"
Expand Down
21 changes: 21 additions & 0 deletions webapp/source/app/funcs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from flask import Flask, render_template, url_for, flash, redirect, request, session, send_from_directory
from source.app import app

from .api_func import get_data_api, post_data_api, del_data_api
def allowed_exts(ext):
allowed = [ 'jpeg', 'jpg', 'png']
ext = ext.lower()
if ext in allowed:
return True
else:
return False
def auth():
auth = session["authorization"]

return auth

def get_notis():
userid = session["userid"]
noticount, notilist, notifications = get_data_api("notis", data={ "uid": userid, "show_all": False},auth=auth())

return noticount, notilist, notifications
69 changes: 69 additions & 0 deletions webapp/source/app/future_spends.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
from flask import Flask, render_template, url_for, flash, redirect, request, session, send_from_directory
from source.app import app
from werkzeug.utils import secure_filename
from hashlib import sha256
import os
import json

from .api_func import get_data_api, post_data_api, del_data_api
from .funcs import get_notis, auth

@app.route('/futurespends', methods=["GET"])
def futurespends():
if session:
session["title"] = "futurespends"
budget_id = session["budget_id"]
data = { "budget_id": budget_id}
if request.method == "GET":
noticount, notilist, notifications = get_notis()
session["title"] = "futurespends"
apidata = get_data_api("futurespends", data=data,auth=auth())
orderlist = apidata["orders"]

monthlist = apidata["monthlist"]
valuelist = apidata["valuelist"]
colorlist = apidata["colorlist"]

categorylist = get_data_api("categorylist",data=budget_id,auth=auth())

return render_template("futurespends.html",orderlist=orderlist,notifications=notifications, notilist=notilist, noticount=noticount, monthlist=monthlist, valuelist=valuelist, colorlist=colorlist, categorylist=categorylist )
else:
return redirect(url_for('login'))
else:
return redirect(url_for('login'))

@app.route('/fdelete', methods=["GET","POST"])
def fdelete():
if session:
if request.args['name'] == "futurespends":
id = request.args['id']
data = { "id": id, "budget_id": session["budget_id"] }
return_value = del_data_api("futurespends",data,auth=auth())
if return_value =="Entity deleted":
flash_message = {"Entity deleted": "success"}
else:
flash_message = {"Error at delete": "danger"}

flash(flash_message)
return futurespends()

@app.route('/new-futurespend', methods=["GET", "POST"])
def new_futurespend():
if session:
budget_id = session["budget_id"]
userid = session["userid"]
if request.method == "POST":
data = request.form.to_dict()
data["userid"] = userid
data["budget_id"] = budget_id

response = post_data_api("futurespends", data,auth=auth())

if response == "Future spend added!":
flash_message = {response: "danger"}
else:
flash_message = {response: "success"}

flash(flash_message)

return redirect(url_for('futurespends'))
2 changes: 1 addition & 1 deletion webapp/source/app/templates/footer.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<link rel="icon" type="image/x-icon" href="static/favicon_v2.ico">

<div class="footer navbar-fixed-bottom d-flex justify-content-center">
<p class="text-piglet fw-bold" style="margin-top: 20px">Copyright Piglet <span id="year"></span> - Version 1.0.3 </p>
<p class="text-piglet fw-bold" style="margin-top: 20px">Copyright Piglet <span id="year"></span> - Version 1.1.0 </p>
</div>
<script>
document.getElementById("year").innerHTML = new Date().getFullYear();
Expand Down
Loading

0 comments on commit f5b1825

Please sign in to comment.