diff --git a/foods.db b/foods.db index 5ad494a..8574d18 100644 Binary files a/foods.db and b/foods.db differ diff --git a/src/main.rs b/src/main.rs index 3bae5b7..69cb3c6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,6 @@ use std::sync::{Arc, Mutex}; -use axum::{extract::State, response::Html, routing::get, Router}; +use axum::{extract::{Path, State}, response::{Html, Redirect}, routing::{get, post}, Router}; use rusqlite::Connection; use askama::Template; @@ -8,6 +8,7 @@ use askama::Template; #[template(path = "index.html")] struct IndexTemplate { foods: Vec, + sum: i32, } #[derive(Debug, Clone, PartialEq)] @@ -27,7 +28,10 @@ async fn main() { conn.execute(include_str!("create_tables.sql"), ()).unwrap(); let conn = Arc::new(Mutex::new(conn)); - let app = Router::new().route("/", get(root)).with_state(conn); + let app = Router::new().route("/", get(root)) + .route("/increase/{id}", post(increase)) + .route("/decrease/{id}", post(decrease)) + .with_state(conn); let listener = tokio::net::TcpListener::bind("0.0.0.0:3001").await.unwrap(); println!("listening on {}", listener.local_addr().unwrap()); @@ -49,8 +53,29 @@ async fn root( actual_servings: row.get(5).unwrap(), }) }).unwrap().collect::>().unwrap(); - let index = IndexTemplate {foods}; + let mut stmt = conn.prepare("SELECT SUM(kc_per_serving * actual_servings) as kc FROM food").unwrap(); + let sum = stmt.query_one((), |row| row.get(0)).unwrap(); + let index = IndexTemplate {foods, sum}; Html( index.render().unwrap() ) } + +async fn increase( + State(conn): State>>, + Path(id): Path +) -> Redirect{ + let conn = conn.lock().unwrap(); + let mut stmt = conn.prepare("UPDATE food SET actual_servings = (SELECT actual_servings FROM food WHERE id = ?1) + 1 WHERE id = ?1").unwrap(); + stmt.execute((id,)).unwrap(); + Redirect::to("/") +} +async fn decrease( + State(conn): State>>, + Path(id): Path +) -> Redirect{ + let conn = conn.lock().unwrap(); + let mut stmt = conn.prepare("UPDATE food SET actual_servings = (SELECT actual_servings FROM food WHERE id = ?1) - 1 WHERE id = ?1").unwrap(); + stmt.execute((id,)).unwrap(); + Redirect::to("/") +} diff --git a/templates/index.html b/templates/index.html index ee967bd..11c2627 100644 --- a/templates/index.html +++ b/templates/index.html @@ -10,7 +10,7 @@
- +
@@ -24,13 +24,22 @@ {% endfor %} + + + +
Portion Lebensmittel{{ food.kc_per_serving }} - food.target_servings %}style="accent-color: red;"{% endif %}> + food.target_servings %} + style="accent-color: red;" + {% endif %}> + {{ food.actual_servings }}/{{ food.target_servings }} - - +
+ + +
kc.:{{ sum }}