Author SHA1 Message Date
ide 4315ed07cc made number of days until button an environment variable 2026-08-17 23:00:19 +02:00
ide 495b0de7a7 finished implementing setting category 2026-08-17 22:47:02 +02:00
ide b3dd373403 idk what I did last 2026-06-12 19:24:39 +02:00
10 changed files with 1854 additions and 1180 deletions
+2
View File
@@ -3,3 +3,5 @@ target/
**/*.rs.bk
*.sqlite
dabase
Generated
+1650 -1161
View File
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -18,6 +18,8 @@ pub use fs::*;
#[cfg(target_os = "linux")]
mod fs {
use crate::runtime::spawn;
use super::Config;
use anyhow::{Context, Ok};
use serde_json;
@@ -34,7 +36,7 @@ mod fs {
.place_config_file(CONFIG_FILE_NAME)
.context("unable to create config directory")?;
tokio::spawn(async {
spawn(async {
let res = tokio::fs::write(path, conf)
.await
.context("unable to write config file");
+67 -1
View File
@@ -15,7 +15,7 @@ use std::{
sync::{Arc, Mutex},
};
use inkopslista_lib::{Item, ItemData};
use inkopslista_lib::{ButtonItem, Item, ItemData};
use reqwest::Url;
use slint::{Model, ModelRc, ToSharedString, VecModel};
@@ -31,6 +31,13 @@ async fn get_list(conf: &Mutex<Config>) -> Result<Vec<Item>, anyhow::Error> {
Ok(list)
}
async fn get_favorites(conf: &Mutex<Config>) -> Result<Vec<ButtonItem>, anyhow::Error> {
let base = Url::parse(&conf.lock().unwrap().address)?;
let url = base.join("/api/favorites")?;
let favs = reqwest::get(url).await?.json::<Vec<ButtonItem>>().await?;
Ok(favs)
}
/// Add or update an item in the list
async fn put_list(item: &str, data: &ItemData, conf: &Mutex<Config>) -> Result<(), anyhow::Error> {
let client = reqwest::Client::new();
@@ -53,6 +60,26 @@ async fn delete_item(item: &str, conf: &Mutex<Config>) -> Result<(), anyhow::Err
Ok(())
}
async fn put_category(
itemname: &str,
category: &str,
conf: &Mutex<Config>,
) -> Result<(), anyhow::Error> {
let client = reqwest::Client::new();
let url: Url = format!(
"{address}/api/favourites/{itemname}/category",
address = conf.lock().unwrap().address
)
.parse()?;
let _response = client
.put(url)
.body(category.to_string())
.send()
.await?
.error_for_status()?;
Ok(())
}
/// Convert shopping list to slint types
fn update_slint_list(new_list: Vec<Item>, list: &VecModel<SItem>) {
list.clear();
@@ -66,6 +93,17 @@ fn update_slint_list(new_list: Vec<Item>, list: &VecModel<SItem>) {
.for_each(|item| list.push(item));
}
fn update_slint_favs(new_favs: Vec<ButtonItem>, favs: &VecModel<SButtonItem>) {
favs.clear();
new_favs
.into_iter()
.map(|item| SButtonItem {
name: item.name.into(),
category: item.category.unwrap_or_default().to_shared_string(),
})
.for_each(|item| favs.push(item));
}
fn refresh_list(conf: &Arc<Mutex<Config>>, app_weak: &slint::Weak<App>) {
let conf = conf.clone();
let app_weak = app_weak.clone();
@@ -82,6 +120,19 @@ fn refresh_list(conf: &Arc<Mutex<Config>>, app_weak: &slint::Weak<App>) {
let list: &VecModel<SItem> = list.as_any().downcast_ref().expect("list is a VecModel");
update_slint_list(new_list, &list);
});
let new_favs = match get_favorites(&conf).await {
Ok(new_favs) => new_favs,
Err(e) => {
eprintln!("{e:?}");
return;
}
};
let _ = app_weak.upgrade_in_event_loop(|app| {
let favs: ModelRc<SButtonItem> = app.global::<State>().get_favorites();
let favs: &VecModel<SButtonItem> =
favs.as_any().downcast_ref().expect("favs is a vec model");
update_slint_favs(new_favs, favs);
});
});
}
@@ -89,7 +140,9 @@ pub fn run() -> Result<(), anyhow::Error> {
let app = App::new()?;
let state = app.global::<State>();
let list_shared = Rc::new(VecModel::default());
let fav_shared = Rc::new(VecModel::default());
state.set_list(ModelRc::new(list_shared.clone()));
state.set_favorites(ModelRc::new(fav_shared.clone()));
#[cfg(target_os = "linux")]
let conf = runtime::RT
@@ -289,6 +342,19 @@ pub fn run() -> Result<(), anyhow::Error> {
}
});
let conf = conf_shared.clone();
state.on_set_cat(move |itemname, cat| {
let conf = conf.clone();
spawn(async move {
let res = put_category(&itemname, &cat, &conf).await;
if let Err(err) = res {
eprintln!("{err:?}");
}
});
return;
});
state.on_set_server_address(move |address| {
conf_shared.lock().unwrap().address = address.to_string();
#[cfg(target_os = "linux")]
+40 -8
View File
@@ -7,12 +7,12 @@ import {
CheckBox,
ScrollView,
GridBox,
HorizontalBox,
ComboBox,
} from "std-widgets.slint";
import { SettingsView } from "settings.slint";
import { State, SItem } from "state.slint";
import { State, SItem, SButtonItem } from "state.slint";
export { State, SItem }
component GoodListItem inherits Rectangle {
in-out property <SItem> item;
background: #ffffff10;
@@ -177,25 +177,24 @@ component GoodsListAdd {
}
component GoodButtons inherits ScrollView {
in property <[string]> favorites: ["Mjölk", "Ost", "Ägg", "Bullens", "Oboy", "Mjöl", "Havregryn", "KrosTom"];
in property <int> button-width: 100;
in property <int> button-height: 60;
in property <int> button-spacing: 10;
property <int> count-x: floor(root.width / 1pt / (button-width + button-spacing));
property <int> count-y: ceil(favorites.length / count-x);
property <int> count-y: ceil(State.favorites.length / count-x);
viewport-height: (count-y * (button-height + button-spacing)) * 1pt;
mouse-drag-pan-enabled: true;
for item[idx] in favorites: Button {
for item[idx] in State.favorites: Button {
x: floor(mod(idx, count-x)) * (root.button-width + root.button-spacing) * 1pt;
y: floor(idx / count-x) * (root.button-height + root.button-spacing) * 1pt;
width: root.button-width * 1pt;
height: root.button-height * 1pt;
text: item;
text: item.name;
clicked => {
State.add-to-list(item);
State.add-to-list(item.name);
}
}
}
@@ -278,6 +277,32 @@ component ShopView inherits VerticalLayout {
}
}
component CatItem inherits HorizontalBox {
in-out property <SButtonItem> item;
Text {
text: item.name;
vertical-alignment: center;
font-size: 16px;
}
ComboBox {
model: ["kyl", "skafferi", "frys", "övrigt"];
current-value: item.category;
width: 60%;
selected(category) => { State.set-cat(item.name, category) }
}
}
component CatView inherits VerticalLayout {
in-out property <[SButtonItem]> cats;
for item in cats: CatItem {
item: item;
}
}
export component App inherits Window {
preferred-height: 700px;
@@ -297,6 +322,13 @@ export component App inherits Window {
}
}
Tab {
title: "Categories";
CatView {
cats <=> State.favorites;
}
}
Tab {
title: "Settings";
SettingsView { }
+8
View File
@@ -4,6 +4,8 @@ export struct SItem {
amount: int,
}
export struct SButtonItem { name: string, category: string }
export global State {
in-out property <[SItem]> list: [
{ name: "Test 1", checked: true },
@@ -16,7 +18,13 @@ export global State {
callback delete-checked();
callback inc-amount(string);
callback dec-amount(string);
callback set-cat(string, string);
in-out property <string> server-address;
in property <[SButtonItem]> favorites: [
{ name: "mjölk", category: "kyl" },
{ name: "ost", category: "kyl" },
];
callback set-server-address(string);
set-server-address(address) => {
server-address = address;
+6 -2
View File
@@ -7,9 +7,13 @@ pub struct Item {
}
#[derive(Serialize, Deserialize, Default, Debug, Clone)]
pub struct ItemData {
pub checked: bool,
pub amount: i64,
// TODO: add number
}
#[derive(Serialize, Deserialize, Default, Debug, Clone)]
pub struct ButtonItem {
pub name: String,
pub category: Option<String>,
}
+1
View File
@@ -9,3 +9,4 @@ serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.145"
inkopslista-lib = { path = "../lib" }
sqlite = "0.37.0"
clap = { version = "4.6.6", features = ["derive", "env"] }
+11 -1
View File
@@ -3,4 +3,14 @@ CREATE TABLE
itemname TEXT NOT NULL PRIMARY KEY,
checked INT NOT NULL, -- actually a boolean
amount INT NOT NULL
) STRICT;
) STRICT;
CREATE TABLE
IF NOT EXISTS adds (
itemname TEXT NOT NULL,
date_added INT NOT NULL,
PRIMARY KEY (itemname, date_added)
) STRICT;
CREATE TABLE
IF NOT EXISTS categories (itemname TEXT NOT NULL PRIMARY KEY, category TEXT) STRICT;
+66 -6
View File
@@ -1,9 +1,8 @@
#[macro_use]
extern crate rocket;
use std::{env, path::Path};
use inkopslista_lib::{Item, ItemData};
use clap::Parser;
use inkopslista_lib::{ButtonItem, Item, ItemData};
use rocket::{
fs::{FileServer, NamedFile},
serde::json::Json,
@@ -11,6 +10,7 @@ use rocket::{
State,
};
use sqlite::ConnectionThreadSafe;
use std::path::{Path, PathBuf};
/// The directory where the web files for the gui is stored.
fn www_path() -> &'static Path {
@@ -47,6 +47,44 @@ fn get_list(db: &State<ConnectionThreadSafe>) -> Json<Vec<Item>> {
Json(list)
}
#[get("/api/favorites")]
fn get_favorites(db: &State<ConnectionThreadSafe>) -> Json<Vec<ButtonItem>> {
let opt = Opt::parse();
let query = format!("WITH favorites as (SELECT itemname, COUNT(date_added) day_count
FROM adds
WHERE (date(julianday('now')) - date(date_added, 'unixepoch')) < 184
GROUP BY itemname
HAVING day_count > {num_days})
SELECT favorites.itemname, category FROM favorites LEFT OUTER JOIN categories ON favorites.itemname = categories.itemname", num_days = opt.num_days);
let list: Vec<ButtonItem> = db
.prepare(query)
.unwrap()
.into_iter()
.map(|row| {
let row = row.unwrap();
ButtonItem {
name: row.read::<&str, _>("itemname").to_string(),
category: row
.try_read::<&str, _>("category")
.ok()
.map(ToString::to_string),
}
})
.collect();
Json(list)
}
#[put("/api/favourites/<itemname>/category", data = "<category>")]
fn put_category(db: &State<ConnectionThreadSafe>, itemname: &str, category: &str) {
let query = "INSERT INTO categories VALUES (?, ?) ON CONFLICT DO UPDATE SET category = ?";
let mut statement = db.prepare(query).unwrap();
statement.bind((1, itemname)).unwrap();
statement.bind((2, category)).unwrap();
statement.bind((3, category)).unwrap();
while let Ok(sqlite::State::Row) = statement.next() {}
}
#[put("/api/list/<item>", data = "<data>")]
fn put_list(item: &str, data: Json<ItemData>, db: &State<ConnectionThreadSafe>) {
// TODO: errorhandling
@@ -60,6 +98,10 @@ fn put_list(item: &str, data: Json<ItemData>, db: &State<ConnectionThreadSafe>)
statement.bind((4, data.checked as i64)).unwrap();
statement.bind((5, data.amount)).unwrap();
while let Ok(sqlite::State::Row) = statement.next() {}
let query = "INSERT INTO adds VALUES(?, strftime('%s','now')) ON CONFLICT DO NOTHING";
let mut statement = db.prepare(query).unwrap();
statement.bind((1, item)).unwrap();
while let Ok(sqlite::State::Row) = statement.next() {}
}
#[delete("/api/list/<item>")]
@@ -71,10 +113,18 @@ fn delete_item(item: &str, db: &State<ConnectionThreadSafe>) {
while let Ok(sqlite::State::Row) = statement.next() {}
}
#[derive(Parser)]
struct Opt {
#[clap(long, env = "DB_PATH")]
db_path: PathBuf,
#[clap(long, env = "NUM_DAYS", default_value = "5")]
num_days: u32,
}
#[launch]
fn rocket() -> _ {
let db_path = env::var("DB_PATH").unwrap();
let db = sqlite::Connection::open_thread_safe(db_path).unwrap();
let opt = Opt::parse();
let db = sqlite::Connection::open_thread_safe(opt.db_path).unwrap();
db.execute(include_str!("db/init.sql"))
.expect("unable to initialize database");
rocket::build()
@@ -84,6 +134,16 @@ fn rocket() -> _ {
.disable::<rocket::shield::Frame>(),
)
.manage(db)
.mount("/", routes![index, get_list, put_list, delete_item])
.mount(
"/",
routes![
index,
get_list,
put_list,
delete_item,
get_favorites,
put_category
],
)
.mount("/", FileServer::from(www_path()))
}