bkbh/src-tauri/src/lib.rs
2025-02-16 16:01:14 +01:00

126 lines
2.6 KiB
Rust

use chrono::offset::Utc;
use rand::prelude::*;
use rusqlite::{types::ToSqlOutput, Connection, ToSql};
use tauri::{Manager, State};
use tauri_plugin_fs::FsExt;
use tokio::sync::Mutex;
use std::collections::HashMap;
mod app_state;
mod data_door;
use app_state::AppState;
#[derive(Clone, Copy)]
enum Store {
Aldi,
Edeka,
Dm,
Lidl,
Rewe,
Tegut,
}
impl TryFrom<&str> for Store {
type Error = ();
fn try_from(s: &str) -> Result<Self, Self::Error> {
match s {
"aldi" => Ok(Store::Aldi),
"edeka" => Ok(Store::Edeka),
"dm" => Ok(Store::Dm),
"lidl" => Ok(Store::Lidl),
"rewe" => Ok(Store::Rewe),
"tegut" => Ok(Store::Tegut),
_ => Err(()),
}
}
}
impl ToSql for Store {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
match self {
Store::Aldi => 0.to_sql(),
Store::Edeka => 1.to_sql(),
Store::Dm => 2.to_sql(),
Store::Lidl => 3.to_sql(),
Store::Rewe => 4.to_sql(),
Store::Tegut => 5.to_sql(),
}
}
}
#[tauri::command]
async fn inventory(
data: HashMap<String, String>,
state: State<'_, Mutex<AppState>>,
) -> Result<(), ()> {
println!("{:?}", data);
Ok(())
}
#[tauri::command]
async fn swap(
store: &str,
acc: i64,
state: State<'_, Mutex<AppState>>,
) -> Result<(), ()> {
let state = state.lock().await;
let mut rng = rand::thread_rng();
let store: Store = store.try_into()?;
state.db.execute(
"INSERT INTO swap VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
(
rng.gen::<i64>(),
store,
acc,
i64::from_ne_bytes(state.id.to_ne_bytes()),
Utc::now().timestamp(),
false,
),
)
.map_err(|e| println!("{:?}", e))?;
Ok(())
}
#[tauri::command]
async fn count(state: State<'_, Mutex<AppState>>) -> Result<String, ()> {
let state = state.lock().await;
let mut stmt =
state.db.prepare("SELECT COUNT(*) FROM swap")
.map_err(|e| println!("{:?}", e))?;
let mut rows = stmt.query([]).map_err(|e| println!("{:?}", e))?;
let row = rows.next().map_err(|e| println!("{:?}", e))?;
let row = match row {
Some(r) => Ok(r),
None => {
println!("No rows");
Err(())
}
}?;
let cnt: u64 = row.get(0).map_err(|e| println!("{:?}", e))?;
Ok(cnt.to_string())
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let state = AppState::new();
tauri::Builder::default()
.plugin(tauri_plugin_fs::init())
.setup(|app| {
app.manage(Mutex::new(state));
let scope = app.fs_scope();
let path = app.path();
scope.allow_directory(path.temp_dir()?, false)?;
Ok(())
})
.invoke_handler(tauri::generate_handler![
swap,
count,
inventory,
data_door::pull_data,
data_door::push_data,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}