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

Back-end development #3

Open
wants to merge 17 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 2 additions & 21 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,21 +1,2 @@
# Generated by Cargo
# will have compiled files and executables
debug/
target/

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock

# These are backup files generated by rustfmt
**/*.rs.bk

# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb

# RustRover
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
.idea
**/__pycache__/
3 changes: 3 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
flask==3.0.3
werkzeug==3.1.3
psycopg2-binary==2.9.10
21 changes: 0 additions & 21 deletions server/server/.gitignore

This file was deleted.

8 changes: 0 additions & 8 deletions server/server/Cargo.toml

This file was deleted.

3 changes: 0 additions & 3 deletions server/server/src/main.rs

This file was deleted.

47 changes: 47 additions & 0 deletions server/src/database/setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import psycopg2

# TODO Add these into a .env file, this is suboptimally secure :)
conn = psycopg2.connect(
database="stocky",
host="192.168.1.136",
user="dev",
password="dev",
port="5432"
)

db = conn.cursor()

def setup_table():
try:
db.execute("""
CREATE TABLE Producten (
Product_ID SERIAL PRIMARY KEY,
Product_Naam VARCHAR(255) NOT NULL,
Product_Aantal INT NOT NULL,
Product_Barcode VARCHAR(255)
);

CREATE TABLE Transacties (
Transactie_ID SERIAL PRIMARY KEY,
Product_ID INT NOT NULL,
Date_Time TIMESTAMP NOT NULL,
Transactie_Aantal INT NOT NULL,
FOREIGN KEY (Product_ID) REFERENCES Producten(Product_ID)
);

CREATE TABLE Derving (
Transactie_ID INT NOT NULL,
User_ID INT NOT NULL,
Derving_Type VARCHAR(255),
PRIMARY KEY (Transactie_ID, User_ID),
FOREIGN KEY (Transactie_ID) REFERENCES Transacties(Transactie_ID)
);

CREATE TABLE Succesvolle_Transacties (
Transactie_ID INT PRIMARY KEY,
FOREIGN KEY (Transactie_ID) REFERENCES Transacties(Transactie_ID)
);
""")
except psycopg2.errors.DuplicateTable:
print("Table already exists.")
conn.commit()
14 changes: 14 additions & 0 deletions server/src/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from flask import Flask

from server.src.web.routing import import_routes
from server.src.web.exception_handlers import import_handlers
from server.src.database.setup import setup_table

if __name__ == "__main__":
app = Flask(__name__)

import_routes(app)
import_handlers(app)
setup_table()

app.run(debug=True)
14 changes: 14 additions & 0 deletions server/src/web/exception_handlers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import werkzeug

from werkzeug.exceptions import BadRequest, Forbidden, NotFound, MethodNotAllowed, ImATeapot


def import_handlers(app):
handlers = [BadRequest, Forbidden, NotFound, MethodNotAllowed, ImATeapot]

for handler in handlers:
app.register_error_handler(handler, handle_error)


def handle_error(e: werkzeug.exceptions.HTTPException):
return f"{e.code} {str(e.description)}\n", e.code
28 changes: 28 additions & 0 deletions server/src/web/routes/product/add.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from flask import request
from werkzeug.exceptions import BadRequest

from server.src.database.setup import db, conn
from server.src.web.utils import filter_name


# {
# "name": "waffles",
# }
def add():
data = request.json

if "name" not in data:
raise BadRequest("Bad JSON structure")

# To prevent injections, only accept product names with no spaces
filtered_name = filter_name(data["name"])

db.execute(f"SELECT * FROM current_stock WHERE name LIKE '{filtered_name}' ")

if len(db.fetchall()) != 0:
raise BadRequest(f"Product {filtered_name} already exists")

db.execute(f"INSERT INTO current_stock (name, quantity) VALUES ('{filtered_name}', 0)")
conn.commit()

return "200 OK\n"
28 changes: 28 additions & 0 deletions server/src/web/routes/product/remove.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from flask import request
from werkzeug.exceptions import BadRequest

from server.src.database.setup import db, conn
from server.src.web.utils import filter_name


# {
# "name": "waffles",
# }
def remove():
data = request.json

if "name" not in data:
raise BadRequest("Bad JSON structure")

# To prevent injections, only accept product names with no spaces
filtered_name = filter_name(data["name"])

db.execute(f"SELECT * FROM current_stock WHERE name LIKE '{filtered_name}' ")

if len(db.fetchall()) == 0:
raise BadRequest(f"Product {filtered_name} doesn't exist")

db.execute(f"DELETE FROM current_stock WHERE name LIKE '{filtered_name}' ")
conn.commit()

return "200 OK\n"
37 changes: 37 additions & 0 deletions server/src/web/routes/product/status.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from flask import request
from werkzeug.exceptions import BadRequest

from server.src.database.setup import db, conn
from server.src.web.utils import filter_name


def status_get():
data = request.json

if "name" not in data:
raise BadRequest("Bad JSON structure")

filtered_name = filter_name(data["name"])

db.execute(f"SELECT * FROM current_stock WHERE name LIKE '{filtered_name}' ")

query = db.fetchall()

if len(query) == 0:
raise BadRequest(f"Product {filtered_name} doesn't exist")

return {"quantity": query[0][2]}, 200


def status_post():
data = request.json
filtered_name = filter_name(data["name"])

# Enforce that the quantity is a positive integer
if not isinstance(data["quantity"], int) or data["quantity"] < 0:
raise BadRequest("Invalid quantity")

db.execute(f"UPDATE current_stock SET quantity = {data["quantity"]} WHERE name LIKE '{filtered_name}';")
conn.commit()

return "200 OK\n"
47 changes: 47 additions & 0 deletions server/src/web/routes/transaction.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from flask import request
from werkzeug.exceptions import BadRequest

from server.src.database.setup import db, conn
from server.src.web.utils import filter_name


# {
# "items": [
# {
# "name": "waffles",
# "quantity": 21
# }
# ]
# }
def transaction():
data: dict = request.json

if "items" not in data:
raise BadRequest("Bad JSON structure")

# Check if all items exist in the database and if there's enough in stock
for product in data["items"]:
if "name" not in product or "quantity" not in product:
raise BadRequest("Bad JSON structure")


# Enforce that the quantity is a positive integer
if not isinstance(product["quantity"], int) or product["quantity"] < 0:
raise BadRequest("Invalid quantity")

filtered_name = filter_name(product["name"])

db.execute(f"SELECT * FROM current_stock WHERE name LIKE '{filtered_name}'")
query = db.fetchall()
if len(query) == 0:
raise BadRequest(f"Product {filtered_name} not found")
if query[0][2] < product["quantity"]:
raise BadRequest(f"Not enough stock for {filtered_name}")

# Deduct stock
for product in data["items"]:
filtered_name = product["name"].split(" ")[0]
db.execute(f"UPDATE current_stock SET quantity = quantity - {product["quantity"]} WHERE name LIKE '{filtered_name}';")
conn.commit()

return "200 OK\n"
13 changes: 13 additions & 0 deletions server/src/web/routing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from server.src.web.routes.product.add import *
from server.src.web.routes.product.remove import *
from server.src.web.routes.product.status import *
from server.src.web.routes.transaction import *


def import_routes(app):
app.post("/product/add")(add)
app.delete("/product/remove")(remove)
app.post("/transaction")(transaction)

app.get("/product/status")(status_get)
app.post("/product/status")(status_post)
10 changes: 10 additions & 0 deletions server/src/web/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from werkzeug.exceptions import BadRequest


def filter_name(name):
# Enforce that the quantity is a string
if not isinstance(name, str):
raise BadRequest(f"Invalid product name")

# To prevent injections, only accept product names with no spaces
return name.split(" ")[0]