Compare commits

..

2 commits

Author SHA1 Message Date
Alexander Ek
bf457f26d1 new database schema 2024-05-03 18:14:15 +02:00
Alexander Ek
e693a67b73 DATABASE SCHEMA 2024-05-03 18:10:32 +02:00
31 changed files with 248 additions and 495 deletions

3
.gitignore vendored
View file

@ -28,7 +28,4 @@ krusty.sqlite3
*.sqlite3
*.db
*.tar.gz
*.zip
*.minisig
*.jpg
*.pdf

146
README.md
View file

@ -1,146 +0,0 @@
# Krusty Cookies
> Krusty Kookies is a bakery which specializes in cookies, and they need a database to keep track of their production and deliveries.
## Building and testing
This project uses sqlite3 as a database. Migrations happens automatically on launch.
Migrations drop all tables and recreate them, so all data is lost on restart.
By default jdbc connects sqlite to an in-memory database, so all data is lost on restart anyway.
```bash
./gradlew build
./gradlew test
```
The gradle environment is bumped to a recent version, and it is configured with kotlin and junit5.
The syntax for junit4 was ported to junit5.
**Most** of the pre-configured deps in the handout contained CVEs of varying severity, so they were updated to newer versions.
No tests were changed, some helper classes were implemented.
## Base tables
**This description is no longer consistent with the current state of the project.**
Unsuprisingly, we will need a cookie table.
```sql
CREATE TABLE cookies (
cookie_id INT PRIMARY KEY,
cookie_name VARCHAR(50) NOT NULL UNIQUE,
);
```
Last i checked, a commercial bakery needs customers:
```sql
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(50) NOT NULL,
customer_address VARCHAR(50) NOT NULL,
);
```
We could also have a recipe table that relates ingredients to cookies. But instead, we just keep track of inventory (raw materials) and let the business logic handle orders/production by subtracting a certain set of ingredients from the inventory, and adding the corresponding pallets to the "freezer".
```sql
CREATE TABLE raw_materials (
ingredient_id INT PRIMARY KEY,
ingredient_name VARCHAR(50) NOT NULL UNIQUE,
ingredient_quantity INT NOT NULL,
unit VARCHAR(50) NOT NULL CHECK (unit IN ('g', 'ml'))
);
```
> When a pallet is produced, the raw materials storage must be updated, and the company must be able to check the amount in store of each ingredient, and to see when, and **how much of**, an ingredient was last delivered into storage.
Because of the 'how much of' part, we cannot simply record a last_delivery field in the raw_materials table.
We will use a separate table to keep track of increments in inventory (raw material deliveries).
```sql
CREATE TABLE raw_materials_deliveries (
delivery_id INT PRIMARY KEY,
ingredient_id INT NOT NULL,
delivery_date DATE NOT NULL,
delivery_quantity INT NOT NULL,
unit VARCHAR(50) NOT NULL CHECK (unit IN ('g', 'ml')),
FOREIGN KEY (ingredient_id) REFERENCES raw_materials(ingredient_id)
);
```
When recieving new inventory, we need to initiate a transaction that updates the inventory table, and adds a new row to the raw_mat_delivery table.
### Pallets and orders
> The cookies are baked in large quantities, and then quickly frozen and packaged in bags with 15 cookies in each bag. The bags are put into boxes, with 10 bags per box. Finally, the boxes are stacked on pallets, where each pallet contains 36 boxes.
15 x 10 x 36 = 5400 cookies per pallet. So, to produce a pallet: calculate the total material cost and subtract it from the inventory.
> The company only delivers to to wholesale Links to an external site. customers, and a typical order looks like “send 10 pallets of Tango cookies, and 6 pallets of Berliners to Kalaskakor AB” pallets are the unit of all orders (i.e., you cant break up a pallet in an order).
This is reiterating the fact that 'pallet' is the atomic unit of orders. Furthermore:
> A pallet is considered to be produced when the pallet label is read at the entrance to the deep-freeze storage. The pallet number, product name, and date and time of production are registered in the database. The pallet number is unique.
Conceptually, what happens before the cookies arrive in the freezer is not interesting to us. We only care about the final pallets. The number of cookies per pallet is also of intrest, to keep track of the inventory (recipes and subsequent raw_materials subtractions are handled by the business logic).
Either we have pallets in the freezer, or we make more pallets. If we do not have enough inventory to make a pallet, we can't make a pallet, and the order is rejected.
```sql
CREATE TABLE pallets (
pallet_id INT PRIMARY KEY,
cookie_id INT NOT NULL,
order_id INT NOT NULL,
status VARCHAR(50) NOT NULL CHECK (status IN ('freezer', 'delivered', 'blocked')),
production_date DATE NOT NULL,
FOREIGN KEY (cookie_id) REFERENCES cookie(cookie_id)
FOREIGN KEY (order_id) REFERENCES orders(order_id)
);
```
> When the truck is fully loaded, the driver receives a loading bill containing customer names, addresses, and the number of pallets of each product that is to be delivered to each customer. A transport may contain deliveries intended for different customers.
This suggests that we may need to relate pallets to customers via a truck entity, however, this truck entity is never referenced, so we can omit it entirely.
> On delivery, pallets are transported from the deep-freeze storeroom via a loading ramp to the freezer trucks each truck loads 60 pallets. The entry to the loading ramp contains a bar code reader which reads the pallet label. Pallets must be loaded in production date order.
Again, the truck as an entity is irrelevant and we only need a table to keep track of what pallet was delivered to what customer along with a date.
```sql
```
> Orders must be registered in the database, and, for production planning purposes, the company must be able to see all orders which are to be delivered during a specific time period.
Note that the individial pallets hold the delivery date.
```sql
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT NOT NULL,
cookie_id INT NOT NULL,
order_date DATE NOT NULL DEFAULT CURRENT_DATE CHECK (order_date >= CURRENT_DATE),
FOREIGN KEY (customer_id) REFERENCES customer(customer_id),
FOREIGN KEY (cookie_id) REFERENCES cookie(cookie_id)
);
```
> The company continuously take random samples among the products, and the samples are analyzed in their laboratory. If a sample doesnt meet their quality standards, all pallets containing that product which have been produced during a specific time interval are blocked. A blocked pallet may not be delivered to customers.
So, our pallet table needs a status column. This conveniently fits as an enum of 'freezer', 'delivered' and 'blocked'.
> All pallets must be traceable, for instance, the company needs to be able to see all information about a pallet with a given number (the contents of the pallet, the location of the pallet, if the pallet is delivered and in that case to whom, etc.). They must also be able to see which pallets contain a certain product and which pallets have been produced during a certain time interval.
This should all be possible with a simple join query.
> Blocked products are of special interest. The company needs to find out **which products are blocked**, and also which pallets contain a certain blocked product.
As well as:
> Finally, they must be able to check **which pallets have been delivered** to a given customer, and the date and time of delivery.
And:
> Orders must be registered in the database, and, for production planning purposes, the company must be able to see all orders which are to be **delivered during a specific time period**.
These are all trivial queries.

View file

@ -1,124 +1,112 @@
PRAGMA foreign_keys = OFF;
-- Drop everything...
DROP TABLE IF EXISTS pallets;
DROP TABLE IF EXISTS raw_materials_deliveries;
DROP TABLE IF EXISTS raw_materials;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS customers;
DROP TABLE IF EXISTS cookies;
--------------------------------------------
-- Orders, deliveries and customers
-- Logistics/orders related tables
--------------------------------------------
-- Our known customers, may need more fields
CREATE TABLE IF NOT EXISTS customers (
customer_id INTEGER PRIMARY KEY,
customer_name VARCHAR(50) NOT NULL,
customer_address VARCHAR(50) NOT NULL
customer_id int PRIMARY KEY,
customer_name varchar(100),
customer_address varchar(255)
);
-- Orders from customers.
-- Keep in mind that the delivery_date may be NULL
CREATE TABLE IF NOT EXISTS orders (
order_id INTEGER PRIMARY KEY,
customer_id INT NOT NULL,
order_date DATE NOT NULL DEFAULT CURRENT_DATE CHECK (order_date >= CURRENT_DATE),
expected_delivery_date DATE NOT NULL,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
order_id int PRIMARY KEY,
customer_id int,
order_datetime datetime DEFAULT NOW,
preferred_delivery_date DATE, --the table Delivery tells when the delivery is arrived
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
CREATE TABLE IF NOT EXISTS order_spec (
nbr_pallets INTEGER NOT NULL,
order_id INTEGER NOT NULL,
cookie_id INTEGER NOT NULL,
FOREIGN KEY (order_id) REFERENCES orders(order_id),
FOREIGN KEY (cookie_id) REFERENCES cookies(cookie_id),
PRIMARY KEY (order_id, cookie_id)
CREATE TABLE IF NOT EXISTS delivery (
order_id INT,
truck_id INT,
delivery_datetime DATETIME,
PRIMARY KEY (order_id, truck_id),
FOREIGN KEY (order_id) REFERENCES orders(order_id)
);
--------------------------------------------
-- Cookies, raw_materials and recipes
--------------------------------------------
-- Notes: the unit type can be defined in terms
-- of volume or weight instead. Here we choose
-- to use static si-prefixes in relevant tables.
-- Holds the different types of cookies we can make.
CREATE TABLE IF NOT EXISTS cookies (
cookie_id INTEGER PRIMARY KEY,
cookie_name VARCHAR(50) NOT NULL UNIQUE
CREATE TABLE IF NOT EXISTS OrderSpec (
order_id INT,
cookie_id INT,
quantity INT,
PRIMARY KEY (orderID, cookieID),
FOREIGN KEY (order_id) REFERENCES Orders(order_id),
FOREIGN KEY (cookie_id) REFERENCES Cookies(cookie_id)
);
-- What types of raw_materials do we handle.
-- raw_materials quantity tells us amount in stock
CREATE TABLE IF NOT EXISTS raw_materials (
ingredient_id INTEGER PRIMARY KEY,
ingredient_name VARCHAR(50) NOT NULL UNIQUE,
ingredient_quantity INT NOT NULL,
unit VARCHAR(50) NOT NULL CHECK (unit IN ('g', 'ml'))
);
-- What raw_materials are in what cookies?
-- Glues together the cookies and raw_materials, a 'recipe'.
CREATE TABLE IF NOT EXISTS recipe_contents (
cookie_id INT NOT NULL,
ingredient_id INT NOT NULL,
quantity INT NOT NULL,
unit VARCHAR(50) NOT NULL CHECK (unit IN ('g', 'ml')),
PRIMARY KEY (cookie_id, ingredient_id),
FOREIGN KEY (cookie_id) REFERENCES cookies(cookie_id),
FOREIGN KEY (ingredient_id) REFERENCES raw_materials(ingredient_id)
);
-- When did we get the raw_materials?
CREATE TABLE IF NOT EXISTS raw_materials_deliveries (
delivery_id INTEGER PRIMARY KEY,
ingredient_id INT NOT NULL,
delivery_date DATE NOT NULL,
delivery_quantity INT NOT NULL,
unit VARCHAR(50) NOT NULL CHECK (unit IN ('g', 'ml')),
FOREIGN KEY (ingredient_id) REFERENCES raw_materials(ingredient_id)
);
--------------------------------------------
-- Pallet related tables
--------------------------------------------
-- Pallets are used to store cookies for delivery
-- Order related columns are unused for now.
CREATE TABLE IF NOT EXISTS pallets (
pallet_id INTEGER PRIMARY KEY,
cookie_id INT NOT NULL,
status VARCHAR(50) NOT NULL CHECK (status IN ('freezer', 'delivered', 'blocked')),
production_date DATE NOT NULL DEFAULT NOW,
CREATE TABLE IF NOT EXISTS pallet (
pallet_id INT PRIMARY KEY,
order_id INT,
cookie_id INT,
production_datetime DATETIME,
is_blocked BOOLEAN,
pallet_location VARCHAR(255),
FOREIGN KEY (order_id) REFERENCES Orders(order_id),
FOREIGN KEY (cookie_id) REFERENCES cookies(cookie_id)
);
-- Connects pallets to orders
CREATE TABLE IF NOT EXISTS deliveries (
delivery_date DATE DEFAULT NOW,
order_id INT NOT NULL,
pallet_id INT NOT NULL,
FOREIGN KEY (order_id) REFERENCES orders(order_id),
FOREIGN KEY (pallet_id) REFERENCES pallets(pallet_id),
PRIMARY KEY (order_id, pallet_id)
--------------------------------------------
-- Recipe/Cookie related tables
--------------------------------------------
CREATE TABLE IF NOT EXISTS cookies (
cookie_id INT PRIMARY KEY,
recipe_id INT,
cookie_name VARCHAR(255),
price INT,
FOREIGN KEY (recipeID) REFERENCES Recipe(recipeID)
);
--------------------------------------------
-- Views
--------------------------------------------
-- Pallet
CREATE VIEW IF NOT EXISTS pallets_view AS
SELECT
pallets.pallet_id,
cookie_name,
status,
production_date,
delivery_date
FROM pallets
LEFT JOIN cookies ON pallets.cookie_id = cookies.cookie_id
LEFT JOIN deliveries ON pallets.pallet_id = deliveries.pallet_id;
-- Recipes for all the cookies (essentially a list of cookies)
CREATE TABLE IF NOT EXISTS recipes (
recipe_id int PRIMARY KEY,
cookie_id int,
recipe_name varchar(100) UNIQUE, -- Cookie name
FOREIGN KEY (cookie_id) REFERENCES cookies(cookie_id)
);
--weak table which descirbies the amout of the ingredient
--needed for a recipe
CREATE TABLE RecipeIngredients (
ingredient_id INT,
recipe_id INT,
quantity FLOAT,
PRIMARY KEY (ingredientID, recipeID),
FOREIGN KEY (ingredient_id) REFERENCES ingredients(ingredient_id),
FOREIGN KEY (recipe_id) REFERENCES recipes(recipe_id)
);
-- "The company has a raw materials warehouse in which
-- all ingredients used in their production are stored."
-- Describes ingredients and stock.
-- Each ingredient has 'amount' of 'unit' in stock
CREATE TABLE IF NOT EXISTS ingredients (
ingredient_id int PRIMARY KEY,
ingredient_name varchar(100),
in_stock float,
unit varchar(50),
amout_purchase float,
last_delivery DATETIME
);
-- use this table instead of amount_purchase and last_delivery attributes
-- in ingrdients table if the assigment want us to have a purchase history
-- for every ingredient order.
/*
CREATE TABLE IF NOT EXISTS ingredient_purchase(
ingredientOrder_id
ingredient_id int,
amout_purchase float,
delivery_datetime DATETIME,
FOREIGN KEY(ingreident_id) REFERENCES ingridients(ingridient_id)
);
*/
PRAGMA foreign_keys = ON;

View file

@ -12,7 +12,7 @@ VALUES
(8, 'Småbröd AB', 'Malmö');
INSERT
OR IGNORE INTO cookies (cookie_name)
OR IGNORE INTO recipes (recipe_name)
VALUES
('Nut ring'),
('Nut cookie'),
@ -22,7 +22,7 @@ VALUES
('Berliner');
INSERT
OR IGNORE INTO raw_materials(ingredient_name, ingredient_quantity, unit)
OR IGNORE INTO ingredients (ingredient_name, amount, unit)
VALUES
('Bread crumbs', 500000, 'g'),
('Butter', 500000, 'g'),

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"/><meta name="theme-color" content="#000000"/><meta name="description" content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="/logo192.png"/><link rel="manifest" href="/manifest.json"/><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500"><title>Krusty</title><link href="/static/css/main.59f83d58.chunk.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script>!function(e){function r(r){for(var n,f,l=r[0],i=r[1],a=r[2],c=0,s=[];c<l.length;c++)f=l[c],Object.prototype.hasOwnProperty.call(o,f)&&o[f]&&s.push(o[f][0]),o[f]=0;for(n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n]);for(p&&p(r);s.length;)s.shift()();return u.push.apply(u,a||[]),t()}function t(){for(var e,r=0;r<u.length;r++){for(var t=u[r],n=!0,l=1;l<t.length;l++){var i=t[l];0!==o[i]&&(n=!1)}n&&(u.splice(r--,1),e=f(f.s=t[0]))}return e}var n={},o={1:0},u=[];function f(r){if(n[r])return n[r].exports;var t=n[r]={i:r,l:!1,exports:{}};return e[r].call(t.exports,t,t.exports,f),t.l=!0,t.exports}f.m=e,f.c=n,f.d=function(e,r,t){f.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:t})},f.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},f.t=function(e,r){if(1&r&&(e=f(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var t=Object.create(null);if(f.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var n in e)f.d(t,n,function(r){return e[r]}.bind(null,n));return t},f.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(r,"a",r),r},f.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},f.p="/";var l=this.webpackJsonpfrontend=this.webpackJsonpfrontend||[],i=l.push.bind(l);l.push=r,l=l.slice();for(var a=0;a<l.length;a++)r(l[a]);var p=i;t()}([])</script><script src="/static/js/2.0a7bcc05.chunk.js"></script><script src="/static/js/main.4ee489f9.chunk.js"></script></body></html>

View file

@ -0,0 +1,2 @@
div.App{width:800px;margin:0 auto}@media screen and (max-width:800px){div.App{width:100%}}body{margin:10px;padding:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Roboto","Oxygen","Ubuntu","Cantarell","Fira Sans","Droid Sans","Helvetica Neue",sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}code{font-family:source-code-pro,Menlo,Monaco,Consolas,"Courier New",monospace}
/*# sourceMappingURL=main.59f83d58.chunk.css.map */

View file

@ -0,0 +1 @@
{"version":3,"sources":["index.css"],"names":[],"mappings":"AAAA,QACC,WAAY,CACZ,aACD,CAEA,oCACE,QACE,UACF,CACF,CAEA,KACE,WAAY,CACZ,SAAU,CACV,mJAEY,CACZ,kCAAmC,CACnC,iCACF,CAEA,KACE,yEAEF","file":"main.59f83d58.chunk.css","sourcesContent":["div.App {\n\twidth: 800px;\n\tmargin: 0 auto;\n}\n\n@media screen and (max-width: 800px) {\n div.App {\n width: 100%;\n }\n}\n\nbody {\n margin: 10px;\n padding: 0;\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", \"Roboto\", \"Oxygen\",\n \"Ubuntu\", \"Cantarell\", \"Fira Sans\", \"Droid Sans\", \"Helvetica Neue\",\n sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n font-family: source-code-pro, Menlo, Monaco, Consolas, \"Courier New\",\n monospace;\n}\n"]}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,49 @@
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/**
* A better abstraction over CSS.
*
* @copyright Oleg Isonen (Slobodskoi) / Isonen 2014-present
* @website https://github.com/cssinjs/jss
* @license MIT
*/
/** @license React v0.18.0
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/** @license React v16.12.0
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/** @license React v16.12.0
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/** @license React v16.12.0
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,2 @@
!function(e){function r(r){for(var n,f,l=r[0],i=r[1],a=r[2],c=0,s=[];c<l.length;c++)f=l[c],Object.prototype.hasOwnProperty.call(o,f)&&o[f]&&s.push(o[f][0]),o[f]=0;for(n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n]);for(p&&p(r);s.length;)s.shift()();return u.push.apply(u,a||[]),t()}function t(){for(var e,r=0;r<u.length;r++){for(var t=u[r],n=!0,l=1;l<t.length;l++){var i=t[l];0!==o[i]&&(n=!1)}n&&(u.splice(r--,1),e=f(f.s=t[0]))}return e}var n={},o={1:0},u=[];function f(r){if(n[r])return n[r].exports;var t=n[r]={i:r,l:!1,exports:{}};return e[r].call(t.exports,t,t.exports,f),t.l=!0,t.exports}f.m=e,f.c=n,f.d=function(e,r,t){f.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:t})},f.r=function(e){"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},f.t=function(e,r){if(1&r&&(e=f(e)),8&r)return e;if(4&r&&"object"===typeof e&&e&&e.__esModule)return e;var t=Object.create(null);if(f.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var n in e)f.d(t,n,function(r){return e[r]}.bind(null,n));return t},f.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(r,"a",r),r},f.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},f.p="/";var l=this.webpackJsonpfrontend=this.webpackJsonpfrontend||[],i=l.push.bind(l);l.push=r,l=l.slice();for(var a=0;a<l.length;a++)r(l[a]);var p=i;t()}([]);
//# sourceMappingURL=runtime-main.1c2d59f4.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,10 @@
{
"cookies": [
{"name": "Amneris"},
{"name": "Berliner"},
{"name": "Nut cookie"},
{"name": "Nut ring"},
{"name": "Tango"},
{"name": "Almond delight"}
]
}

View file

@ -0,0 +1,12 @@
{
"customers": [
{"name": "Bjudkakor AB", "address": "Ystad"},
{"name": "Finkakor AB", "address": "Helsingborg"},
{"name": "Gästkakor AB", "address": "Hässleholm"},
{"name": "Kaffebröd AB", "address": "Landskrona"},
{"name": "Kalaskakor AB", "address": "Trelleborg"},
{"name": "Partykakor AB", "address": "Kristianstad"},
{"name": "Skånekakor AB", "address": "Perstorp"},
{"name": "Småbröd AB", "address": "Malmö"}
]
}

View file

@ -0,0 +1,11 @@
{
"pallets": [
{"cookie": "Amneris", "blocked": "no"},
{"cookie": "Amneris", "blocked": "no"},
{"cookie": "Amneris", "blocked": "no"},
{"cookie": "Berliner", "blocked": "no"},
{"cookie": "Nut ring", "blocked": "no"},
{"cookie": "Nut ring", "blocked": "no"},
{"cookie": "Tango", "blocked": "no"}
]
}

View file

@ -0,0 +1,6 @@
{
"pallets": [
{"cookie": "Nut ring", "blocked": "no"},
{"cookie": "Nut ring", "blocked": "no"}
]
}

View file

@ -0,0 +1,4 @@
{
"pallets": [
]
}

View file

@ -0,0 +1,23 @@
{
"raw-materials": [
{"name": "Bread crumbs", "amount": 500000, "unit": "g"},
{"name": "Butter", "amount": 386600, "unit": "g"},
{"name": "Chocolate", "amount": 497300, "unit": "g"},
{"name": "Chopped almonds", "amount": 500000, "unit": "g"},
{"name": "Cinnamon", "amount": 500000, "unit": "g"},
{"name": "Egg whites", "amount": 500000, "unit": "ml"},
{"name": "Eggs", "amount": 456800, "unit": "g"},
{"name": "Fine-ground nuts", "amount": 500000, "unit": "g"},
{"name": "Flour", "amount": 416300, "unit": "g"},
{"name": "Ground, roasted nuts", "amount": 500000, "unit": "g"},
{"name": "Icing sugar", "amount": 474080, "unit": "g"},
{"name": "Marzipan", "amount": 378500, "unit": "g"},
{"name": "Potato starch", "amount": 495950, "unit": "g"},
{"name": "Roasted, chopped nuts", "amount": 475700, "unit": "g"},
{"name": "Sodium bicarbonate", "amount": 499784, "unit": "g"},
{"name": "Sugar", "amount": 486500, "unit": "g"},
{"name": "Vanilla", "amount": 499892, "unit": "g"},
{"name": "Vanilla sugar", "amount": 499730, "unit": "g"},
{"name": "Wheat flour", "amount": 495950, "unit": "g"}
]
}

View file

@ -0,0 +1,23 @@
{
"raw-materials": [
{"name": "Bread crumbs", "amount": 500000, "unit": "g"},
{"name": "Butter", "amount": 500000, "unit": "g"},
{"name": "Chocolate", "amount": 500000, "unit": "g"},
{"name": "Chopped almonds", "amount": 500000, "unit": "g"},
{"name": "Cinnamon", "amount": 500000, "unit": "g"},
{"name": "Egg whites", "amount": 500000, "unit": "ml"},
{"name": "Eggs", "amount": 500000, "unit": "g"},
{"name": "Fine-ground nuts", "amount": 500000, "unit": "g"},
{"name": "Flour", "amount": 500000, "unit": "g"},
{"name": "Ground, roasted nuts", "amount": 500000, "unit": "g"},
{"name": "Icing sugar", "amount": 500000, "unit": "g"},
{"name": "Marzipan", "amount": 500000, "unit": "g"},
{"name": "Potato starch", "amount": 500000, "unit": "g"},
{"name": "Roasted, chopped nuts", "amount": 500000, "unit": "g"},
{"name": "Sodium bicarbonate", "amount": 500000, "unit": "g"},
{"name": "Sugar", "amount": 500000, "unit": "g"},
{"name": "Vanilla", "amount": 500000, "unit": "g"},
{"name": "Vanilla sugar", "amount": 500000, "unit": "g"},
{"name": "Wheat flour", "amount": 500000, "unit": "g"}
]
}

Binary file not shown.

View file

@ -6,15 +6,11 @@ import spark.Response;
// Likely dependencies for db operations
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
// Likely dependencies for general operations
import java.io.IOException;
import java.sql.ResultSet;
import java.util.Date;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import java.nio.file.Files;
@ -22,16 +18,12 @@ import java.nio.file.Paths;
import java.util.stream.Stream;
public class Database {
// Here, we use an in-memory database. This string could be changed to
// "jdbc:sqlite:<filename>.sqlite3" to use a file-based database instead.
// Nore that ":memory:" is an **SQLite specific** magic string that tells the
// underlying SQLite engine to store the database in memory.
private static final String jdbcString = "jdbc:sqlite::memory:";
// private static final String jdbcString = "jdbc:sqlite:krusty.db";
// Hold a single connection to the database. Note that this is
// not a pool, so this is not thread-safe nor efficient.
private Connection conn = null;
public String getCustomers(Request req, Response res) {
@ -42,242 +34,30 @@ public class Database {
}
public String getRawMaterials(Request req, Response res) {
String result = selectQuery("raw_materials", "raw-materials", "ingredient_name", "ingredient_quantity", "unit");
String result = selectQuery("ingredients", "raw-materials", "ingredient_name", "amount", "unit");
result = result.replaceAll("ingredient_name", "name");
result = result.replaceAll("ingredient_quantity", "amount");
return result;
}
public String getCookies(Request req, Response res) {
String result = selectQuery("cookies", "cookies", "cookie_name");
result = result.replaceAll("cookie_name", "name");
String result = selectQuery("recipes", "cookies", "recipe_name");
result = result.replaceAll("recipe_name", "name");
return result;
}
public String getRecipes(Request req, Response res) {
// Essentially serialize DefaultRecipes to json
return "{}";
}
public String getPallets(Request req, Response res) {
// These queries look like:
// http://localhost:8888/api/v1/pallets?cookie=Nut+cookie&from=2024-05-23&to=2024-05-30&blocked=yes
// They may contain any combination of the parameters, or none at all.
Optional<Recipe> r = Optional.empty(); // Holds the ecipe if we have a cookie
Optional<Boolean> blocked = Optional.empty(); // Holds the blocked status
Optional<Date> from = Optional.empty(); // Holds the from date
Optional<Date> to = Optional.empty(); // Holds the to date
// Parameter validation block
{
// First we need the cookie parameter
String cookie = req.queryParams("cookie");
// And the blocked parameter
String blocked_str = req.queryParams("blocked");
// Then we need the date parameters
String from_str = req.queryParams("from");
String to_str = req.queryParams("to");
// Fancy functional one-liner to get the recipe if the cookie is present
if (cookie != null) {
r = Optional.ofNullable(DefaultRecipes.recipes.stream()
.filter(recipe -> recipe.name.equals(cookie))
.findFirst().orElse(null));
}
if (blocked_str != null) {
blocked = switch (blocked_str) {
case "yes" -> Optional.of(true);
case "no" -> Optional.of(false);
default -> Optional.empty();
};
}
if (from_str != null) {
try {
from = Optional.of(new SimpleDateFormat("yyyy-MM-dd").parse(from_str));
} catch (Exception e) {
from = Optional.empty();
}
}
if (to_str != null) {
try {
to = Optional.of(new SimpleDateFormat("yyyy-MM-dd").parse(to_str));
} catch (Exception e) {
to = Optional.empty();
}
}
// If the interval is negative, reset the dates
if (from.isPresent() && to.isPresent() && from.get().after(to.get())) {
from = Optional.empty();
to = Optional.empty();
}
}
// This type of code is unreadable, error prone and hard to maintain.
// The fact that im responsible for this code makes my soul hurt.
// This part almost made me write a simple query factory to handle this.
//
// SqlBuilder exists to 'take the pain out of generating SQL queries',
// but it's not in the standard library.
//
// Helmets, seatbelts and safety goggles on; we need to execute a query.
try {
Statement stmt = conn.createStatement();
StringBuilder query = new StringBuilder(
"SELECT cookie_name, status FROM pallets_view");
// r is validated here
if (r.isPresent()) {
query.append(" WHERE cookie_name = '" + r.get().name + "'");
}
if (from.isPresent()) {
String query_from = new SimpleDateFormat("yyyy-MM-dd").format(from.get());
// Super hacky, low quality code
String clause = query.toString().contains("WHERE") ? " AND " : " WHERE ";
query.append(clause + "production_date >= '" + query_from + "'");
}
if (to.isPresent()) {
String query_to = new SimpleDateFormat("yyyy-MM-dd").format(to.get());
// Super hacky, low quality code
String clause = query.toString().contains("WHERE") ? " AND " : " WHERE ";
query.append(clause + "production_date <= '" + query_to + "'");
}
if (blocked.isPresent()) {
// This again
String clause = query.toString().contains("WHERE") ? " AND " : " WHERE ";
query.append(clause);
// TODO: WARNING This logic is flawed. WARNING
// Remember, status can be 'freezer', 'delivered' or 'blocked'
query.append("status = " + (blocked.get() ? "'blocked'" : "'freezer'"));
}
System.out.println(query.toString());
ResultSet result = stmt.executeQuery(query.toString());
// Rename the columns
String jsonResult = Jsonizer.toJson(result, "pallets");
// Some carmack level code, as usual
jsonResult = jsonResult.replaceAll("cookie_name", "cookie");
jsonResult = jsonResult.replaceAll("freezer", "no");
jsonResult = jsonResult.replaceAll("delivered", "no");
jsonResult = jsonResult.replaceAll("blocked", "yes");
jsonResult = jsonResult.replaceAll("status", "blocked");
return jsonResult;
} catch (SQLException e) {
System.out.printf("Error executing query: \n%s", e);
}
// Statue 500, to give the client a
// chance to figure out that something went wrong
res.status(500);
return "{\"pallets\":[]}";
}
public String reset(Request req, Response res) {
try {
this.migrateScript("Migrations/create-schema.sql");
this.migrateScript("Migrations/initial-data.sql");
} catch (Exception e) {
System.out.printf("Error resetting database: \n%s", e);
res.status(500);
return "{}";
}
return "{}";
}
public String createPallet(Request req, Response res) {
// This on only has one query param and looks like:
// http://localhost:8888/api/v1/pallets?cookie=Amneris
Optional<Recipe> r = Optional.empty();
String cookie = req.queryParams("cookie");
if (cookie != null) {
r = Optional.ofNullable(DefaultRecipes.recipes.stream()
.filter(recipe -> recipe.name.equals(cookie))
.findFirst().orElse(null));
}
if (r.isEmpty()) {
res.status(404);
return "{}";
}
try (PreparedStatement getRawMaterials = conn
.prepareStatement("SELECT * FROM raw_materials WHERE ingredient_name = ?");
PreparedStatement decrementRawMaterials = conn.prepareStatement(
"UPDATE raw_materials SET ingredient_quantity = ingredient_quantity - ? WHERE ingredient_name = ?");
PreparedStatement insertPallet = conn.prepareStatement(
"INSERT INTO pallets (cookie_id, production_date, status) VALUES (?, ?, ?)");
PreparedStatement getCookieId = conn
.prepareStatement("SELECT cookie_id FROM cookies WHERE cookie_name = ?")) {
// Start transaction
conn.setAutoCommit(false);
for (Ingredient i : r.get().ingredients) {
getRawMaterials.setString(1, i.name);
ResultSet result = getRawMaterials.executeQuery();
if (!result.next()) {
conn.rollback();
res.status(500);
return "{}";
}
int amount_per_pallet = i.amount * 54; // 54 * 100
// Check if we have enough raw materials
if (result.getInt("ingredient_quantity") < amount_per_pallet) {
conn.rollback();
res.status(500);
return "{}";
}
decrementRawMaterials.setInt(1, amount_per_pallet);
decrementRawMaterials.setString(2, i.name);
decrementRawMaterials.executeUpdate();
}
// Fish out the cookie id
getCookieId.setString(1, cookie);
ResultSet cookie_rs = getCookieId.executeQuery();
if (!cookie_rs.next()) {
conn.rollback();
res.status(500);
return "{}";
}
int cookie_id = cookie_rs.getInt("cookie_id");
insertPallet.setInt(1, cookie_id);
insertPallet.setString(2, new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
insertPallet.setString(3, "freezer");
System.out.println(insertPallet.toString());
insertPallet.executeUpdate();
conn.commit();
} catch (SQLException e) {
System.out.printf("Error starting transaction: \n%s", e);
}
res.status(201);
return "{}";
}
@ -324,7 +104,6 @@ public class Database {
// The script location is relative to the gradle
// build script ("build.gradle.kts", in this case).
// Assumes every statement ends with a semicolon. (notably broken for triggers)
/** Reads an sql script into the database */
public void migrateScript(String filename) throws IOException, SQLException {
try (Stream<String> lines = Files.lines(Paths.get(filename))) {

View file

@ -10,12 +10,6 @@ public class Recipe {
}
public String toString() {
StringBuilder sb = new StringBuilder(name + ": ");
for (Ingredient i : ingredients) {
sb.append(i.toString());
sb.append(" ");
}
return sb.toString();
return name;
}
}

View file

@ -8,8 +8,6 @@ run:
clean:
./gradlew clean
rm -f *.tar.gz *.tar.gz.minisig *.zip *.jpg
rm -f app/krusty.db
test:
./gradlew test
@ -18,7 +16,6 @@ dbdump:
sqlite3 app/krusty.db .dump
migrate:
rm -f app/krusty.db
sqlite3 app/krusty.db < app/Migrations/create-schema.sql
sqlite3 app/krusty.db < app/Migrations/initial-data.sql
@ -28,12 +25,4 @@ release:
scp krusty-imbus_$(GITHASH).tar.gz server:/public/krusty/krusty-imbus_$(GITHASH).tar.gz
scp krusty-imbus_$(GITHASH).tar.gz.minisig server:/public/krusty/krusty-imbus_$(GITHASH).tar.gz.minisig
zip:
git archive --format=zip --prefix Rest11/ --output=Rest11.zip HEAD
7za a -tzip CourseProject11.zip ./app/Migrations/*.sql
# Generate ERD. Requires eralchemy2 (pip install eralchemy2)
erd: migrate
eralchemy2 -i sqlite:///app/krusty.db -o erd.jpg
.PHONY: run clean test build dbdump migrate release erd
.PHONY: run clean test build dbdump migrate release