Application able to CRUD

This commit is contained in:
Manuel Forcén Muñoz 2024-02-12 14:04:03 +01:00
commit d2cb5b3031
19 changed files with 3268 additions and 0 deletions

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
/target
/test
/*.db*

2058
Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

28
Cargo.toml Normal file
View file

@ -0,0 +1,28 @@
[package]
name = "accounters"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
[dependencies]
serde = { version = "1", features = ["derive"] }
chrono = { version = "0.4", features = ["serde"] }
sqlx = { version = "0.7", features = ["runtime-tokio", "sqlite", "chrono"] }
futures = "0.3"
regex = "1"
[dev-dependencies]
tokio = { version = "1", features = ["full"] }
[workspace]
members = [
"webserver"
]
[workspace.dependencies]
serde = { version = "1", features = ["derive"] }
chrono = { version = "0.4", features = ["serde"]}
sqlx = { version = "0.7", features = ["runtime-tokio", "sqlite", "chrono"] }

View file

@ -0,0 +1,51 @@
-- Add migration script here
CREATE TABLE IF NOT EXISTS users(
user_id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT,
pass TEXT,
UNIQUE(username)
);
CREATE TABLE IF NOT EXISTS accounts(
account_id INTEGER PRIMARY KEY AUTOINCREMENT,
user INTEGER,
account_name TEXT,
FOREIGN KEY (user) REFERENCES users(user_id)
);
CREATE TABLE IF NOT EXISTS account_snapshot(
account INTEGER,
datestamp DATE,
amount INT,
FOREIGN KEY (account) REFERENCES accounts(account_id),
PRIMARY KEY (account, datestamp)
);
CREATE TABLE IF NOT EXISTS categories (
category_id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
description TEXT
);
CREATE TABLE IF NOT EXISTS rules(
rule_id INTEGER PRIMARY KEY AUTOINCREMENT,
user INTEGER,
regex TEXT,
category INTEGER,
FOREIGN KEY (user) REFERENCES users(user_id)
FOREIGN KEY (category) REFERENCES categories(category_id)
);
CREATE TABLE IF NOT EXISTS transactions (
transaction_id INTEGER PRIMARY KEY AUTOINCREMENT,
account INTEGER,
description TEXT,
transaction_timestamp DATETIME,
category INTEGER,
amount INTEGER,
FOREIGN KEY (account) REFERENCES accounts(account_id),
FOREIGN KEY (category) REFERENCES categories(category_id)
);
CREATE INDEX idx_transactions_ts ON transactions(account, transaction_timestamp);

20
src/lib.rs Normal file
View file

@ -0,0 +1,20 @@
use sqlx::{migrate::MigrateDatabase, Sqlite, SqlitePool};
pub mod models;
pub async fn create_db(db_url: &str) -> sqlx::Result<SqlitePool> {
if !Sqlite::database_exists(db_url).await.unwrap_or(false) {
println!("Creating database {}", db_url);
match Sqlite::create_database(db_url).await {
Ok(_) => println!("create db success"),
Err(e) => panic!("Cannot create db: {e:?}"),
};
} else {
println!("Database already exists")
}
let db = SqlitePool::connect(db_url).await?;
sqlx::migrate!().run(&db).await?;
Ok(db)
}

8
src/models.rs Normal file
View file

@ -0,0 +1,8 @@
mod account;
pub mod categories;
pub mod rules;
pub mod transaction;
pub mod users;
pub use account::{Account, AccountSnapshot};
pub use transaction::Transaction;

360
src/models/account.rs Normal file
View file

@ -0,0 +1,360 @@
use chrono::{prelude::*, Duration, DurationRound};
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, Result, SqlitePool};
use super::{rules::Rule, Transaction};
#[derive(FromRow, Serialize, Deserialize, Clone, Debug)]
pub struct AccountSnapshot {
account: i32,
datestamp: DateTime<Utc>,
amount: i32,
}
impl AccountSnapshot {
pub async fn get(
pool: &SqlitePool,
account: i32,
date: DateTime<Utc>,
) -> Result<AccountSnapshot> {
sqlx::query("SELECT * FROM account_snapshot WHERE account=? AND datestamp=?")
.bind(account)
.bind(date)
.fetch_one(pool)
.await
.and_then(|r| AccountSnapshot::from_row(&r))
}
pub async fn get_last(
pool: &SqlitePool,
account: i32,
date: DateTime<Utc>,
) -> Result<AccountSnapshot> {
sqlx::query("SELECT * FROM account_snapshot WHERE account=? AND datestamp<=? LIMIT 1")
.bind(account)
.bind(date)
.fetch_one(pool)
.await
.and_then(|r| AccountSnapshot::from_row(&r))
}
pub async fn list(
pool: &SqlitePool,
account: i32,
limit: Option<i32>,
offset: Option<i32>,
asc: bool,
) -> sqlx::Result<Vec<AccountSnapshot>> {
let mut query = sqlx::QueryBuilder::new("SELECT * FROM account_snapshot WHERE account=");
query.push_bind(account);
if let Some(limit) = limit {
query.push(" LIMIT ");
query.push_bind(limit);
}
if let Some(offset) = offset {
query.push(" OFFSET ");
query.push_bind(offset);
}
if asc {
query.push(" ORDER BY datestamp ASC");
} else {
query.push(" ORDER BY datestamp DESC");
}
let rows = query.build().fetch_all(pool).await?;
let mut res = Vec::new();
for r in rows.iter() {
res.push(AccountSnapshot::from_row(r)?);
}
Ok(res)
}
pub async fn list_by_date(
pool: &SqlitePool,
account: i32,
after: Option<DateTime<Utc>>,
before: Option<DateTime<Utc>>,
limit: Option<i32>,
asc: bool,
) -> sqlx::Result<Vec<AccountSnapshot>> {
let mut query = sqlx::QueryBuilder::new("SELECT * FROM account_snapshot WHERE account=");
query.push_bind(account);
if let Some(after) = after {
query.push(" AND datestamp >= ");
query.push_bind(after);
}
if let Some(before) = before {
query.push(" AND datestamp < ");
query.push_bind(before);
}
if let Some(limit) = limit {
query.push(" LIMIT ");
query.push_bind(limit);
}
if asc {
query.push(" ORDER BY datestamp ASC");
} else {
query.push(" ORDER BY datestamp DESC");
}
let rows = query.build().fetch_all(pool).await?;
let mut res = Vec::new();
for r in rows.iter() {
res.push(AccountSnapshot::from_row(r)?);
}
Ok(res)
}
pub async fn delete_by_dates(
pool: &SqlitePool,
account: i32,
after: Option<DateTime<Utc>>,
before: Option<DateTime<Utc>>,
) -> sqlx::Result<()> {
if after.is_none() && before.is_none() {
return Err(sqlx::Error::RowNotFound);
}
let mut query = sqlx::QueryBuilder::new("DELETE FROM account_snapshot WHERE account=");
query.push_bind(account);
if let Some(after) = after {
query.push(" AND datestamp >= ");
query.push_bind(after);
}
if let Some(before) = before {
query.push(" AND datestamp < ");
query.push_bind(before);
}
query.build().execute(pool).await?;
Ok(())
}
pub async fn insert(&self, pool: &SqlitePool) -> sqlx::Result<()> {
sqlx::query("INSERT INTO account_snapshot(account, datestamp, amount) VALUES(?,?,?)")
.bind(self.account)
.bind(self.datestamp)
.bind(self.amount)
.execute(pool)
.await
.map(|_| ())
}
pub async fn get_next(&self, pool: &SqlitePool) -> sqlx::Result<Option<AccountSnapshot>> {
let date_next = match Transaction::list_by_date(
pool,
self.account,
Some(self.datestamp + Duration::days(1)),
None,
Some(1),
true,
)
.await?
.first()
{
Some(tx) => tx.get_timestamp(),
None => {
return Ok(None);
}
}
.duration_trunc(chrono::Duration::days(1))
.unwrap();
println!(
"Starting date: {:?}, ending date: {:?}",
self.datestamp, date_next
);
let tx_list = Transaction::list_by_date(
pool,
self.account,
Some(self.datestamp),
Some(date_next),
None,
true,
)
.await?;
Ok(Some(AccountSnapshot {
datestamp: date_next,
account: self.account,
amount: self.amount + tx_list.iter().fold(0, |acc, tx| acc + tx.get_amount()),
}))
}
}
#[derive(FromRow, Serialize, Deserialize)]
pub struct Account {
account_id: i32,
user: i32,
account_name: String,
}
impl Account {
pub fn get_id(&self) -> i32 {
self.account_id
}
pub fn get_user(&self) -> i32 {
self.user
}
pub fn get_account_name(&self) -> &str {
self.account_name.as_str()
}
pub async fn set_account_name(&mut self, pool: &SqlitePool, name: &str) -> Result<()> {
sqlx::query("UPDATE accounts SET account_name=? WHERE account_id=?")
.bind(name)
.bind(self.account_id)
.execute(pool)
.await?;
self.account_name = name.to_string();
Ok(())
}
pub async fn get_by_id(pool: &SqlitePool, id: i32) -> Result<Self> {
sqlx::query("SELECT * FROM accounts WHERE account_id=?")
.bind(id)
.fetch_one(pool)
.await
.and_then(|r| Account::from_row(&r))
}
pub async fn new(pool: &SqlitePool, user: i32, name: &str) -> Result<Self> {
let row = sqlx::query("INSERT INTO accounts(user, account_name) VALUES (?,?) RETURNING *")
.bind(user)
.bind(name)
.fetch_one(pool)
.await?;
Self::from_row(&row)
}
pub async fn list(pool: &SqlitePool, user: i32) -> Result<Vec<Self>> {
let rows = sqlx::query("SELECT * FROM accounts WHERE user=?")
.bind(user)
.fetch_all(pool)
.await?;
let mut res = Vec::new();
for r in &rows {
res.push(Account::from_row(r)?)
}
Ok(res)
}
pub async fn recalculate_snapshots(
&self,
pool: &SqlitePool,
from: Option<DateTime<Utc>>,
) -> Result<()> {
let mut snap = match from {
Some(f) => {
let snapshot = AccountSnapshot::list_by_date(
pool,
self.get_id(),
None,
Some(f),
Some(1),
true,
)
.await?;
if snapshot.is_empty() {
AccountSnapshot {
account: self.account_id,
datestamp: Utc.timestamp_opt(0, 0).unwrap(),
amount: 0,
}
} else {
snapshot.first().unwrap().clone()
}
}
None => AccountSnapshot {
account: self.account_id,
datestamp: Utc.timestamp_opt(0, 0).unwrap(),
amount: 0,
},
};
AccountSnapshot::delete_by_dates(
pool,
self.get_id(),
Some(snap.datestamp + Duration::hours(12)),
None,
)
.await?;
while let Some(next) = snap.get_next(pool).await? {
next.insert(pool).await?;
snap = next;
}
Ok(())
}
pub async fn recategorize_transactions(
&self,
pool: &SqlitePool,
from: Option<DateTime<Utc>>,
to: Option<DateTime<Utc>>,
) -> Result<()> {
let rules = Rule::list_by_user(pool, self.user).await?;
let mut tx_list =
Transaction::list_by_date(pool, self.account_id, from, to, None, true).await?;
for tx in tx_list.iter_mut() {
println!("Checking {}", tx.get_description());
if tx.recategorize(pool, &rules).await? {
println!(
"Tx {} updated with category {}",
tx.get_id(),
tx.get_category().unwrap_or(0)
);
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::Account;
use crate::models::users::User;
use sqlx::SqlitePool;
async fn get_db() -> SqlitePool {
crate::create_db("sqlite://account_test.db").await.unwrap()
}
async fn remove_db(pool: SqlitePool) {
pool.close().await;
std::fs::remove_file("account_test.db").unwrap();
}
async fn new_user(pool: &SqlitePool) -> User {
User::create_user(pool, "account_test", "pass")
.await
.unwrap()
}
#[tokio::test]
async fn create_test() {
let pool = get_db().await;
let user = new_user(&pool).await;
Account::new(&pool, user.get_id(), "account_test")
.await
.unwrap();
remove_db(pool).await;
}
}

41
src/models/categories.rs Normal file
View file

@ -0,0 +1,41 @@
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, SqlitePool};
#[derive(FromRow, Serialize, Deserialize)]
pub struct Category {
pub category_id: i32,
pub name: String,
pub description: String,
}
impl Category {
pub async fn get_by_id(pool: &SqlitePool, id: i32) -> sqlx::Result<Self> {
sqlx::query("SELECT * FROM categories WHERE category_id=?")
.bind(id)
.fetch_one(pool)
.await
.and_then(|r| Category::from_row(&r))
}
pub async fn list(pool: &SqlitePool) -> sqlx::Result<Vec<Category>> {
let mut res = Vec::new();
for r in sqlx::query("SELECT * FROM categories")
.fetch_all(pool)
.await?
.iter()
{
res.push(Category::from_row(r)?)
}
Ok(res)
}
pub async fn new(pool: &SqlitePool, name: &str, description: &str) -> sqlx::Result<Category> {
sqlx::query("INSERT INTO categories(name, description) VALUES (?,?) RETURNING *")
.bind(name)
.bind(description)
.fetch_one(pool)
.await
.and_then(|r| Category::from_row(&r))
}
}

54
src/models/rules.rs Normal file
View file

@ -0,0 +1,54 @@
use regex::Regex;
use serde::Serialize;
use sqlx::{FromRow, SqlitePool};
#[derive(FromRow, Serialize)]
pub struct Rule {
pub rule_id: i32,
pub user: i32,
pub regex: String,
pub category: i32,
}
impl Rule {
pub async fn get_by_id(pool: &SqlitePool, rule_id: i32) -> sqlx::Result<Self> {
sqlx::query("SELECT * FROM rules WHERE rule_id=?")
.bind(rule_id)
.fetch_one(pool)
.await
.and_then(|r| Rule::from_row(&r))
}
pub async fn list_by_user(pool: &SqlitePool, user: i32) -> sqlx::Result<Vec<Self>> {
let mut res = Vec::new();
for r in sqlx::query("SELECT * FROM rules WHERE user=?")
.bind(user)
.fetch_all(pool)
.await?
.iter()
{
res.push(Rule::from_row(r)?);
}
Ok(res)
}
pub async fn new(
pool: &SqlitePool,
user: i32,
regex: String,
category: i32,
) -> sqlx::Result<Self> {
sqlx::query("INSERT INTO rules(user, regex, category) VALUES (?,?,?) RETURNING *")
.bind(user)
.bind(regex)
.bind(category)
.fetch_one(pool)
.await
.and_then(|r| Rule::from_row(&r))
}
pub fn matches(&self, description: &str) -> Result<bool, regex::Error> {
let re = Regex::new(&self.regex)?;
Ok(re.is_match(description))
}
}

217
src/models/transaction.rs Normal file
View file

@ -0,0 +1,217 @@
use chrono::prelude::*;
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, Result, Sqlite, SqlitePool};
use crate::models::rules::Rule;
#[derive(FromRow, Serialize, Deserialize, Debug)]
pub struct Transaction {
transaction_id: i32,
account: i32,
description: String,
transaction_timestamp: DateTime<Utc>,
category: Option<i32>,
amount: i32,
}
impl Transaction {
pub async fn new(
pool: &SqlitePool,
account: i32,
desc: &str,
ts: &DateTime<Utc>,
category: Option<i32>,
amount: i32,
) -> Result<Self> {
let res = sqlx::query(concat!(
"INSERT INTO transactions(",
"account, description, transaction_timestamp, category, amount",
") VALUES (?,?,?,?,?) RETURNING *"
))
.bind(account)
.bind(desc)
.bind(ts)
.bind(category)
.bind(amount)
.fetch_one(pool)
.await?;
Transaction::from_row(&res)
}
pub async fn list(
pool: &SqlitePool,
account: i32,
limit: i32,
offset: i32,
asc: bool,
) -> Result<Vec<Self>> {
let rows = sqlx::query(
if asc {
"SELECT * FROM transactions WHERE account=? ORDER BY transaction_timestamp ASC LIMIT ? OFFSET ?"
} else {
"SELECT * FROM transactions WHERE account=? ORDER BY transaction_timestamp DESC LIMIT ? OFFSET ?"
}
).bind(account)
.bind(limit)
.bind(offset)
.fetch_all(pool)
.await?;
let mut res = Vec::new();
for r in &rows {
res.push(Transaction::from_row(r)?);
}
Ok(res)
}
pub fn query_by_date<'a>(
account: i32,
after: Option<DateTime<Utc>>,
before: Option<DateTime<Utc>>,
limit: Option<i32>,
asc: bool,
) -> sqlx::QueryBuilder<'a, Sqlite> {
let mut query = sqlx::QueryBuilder::new("SELECT * FROM TRANSACTIONS WHERE account=");
query.push_bind(account);
if let Some(after) = after {
query.push(" AND transaction_timestamp >= ");
query.push_bind(after);
}
if let Some(before) = before {
query.push(" AND transaction_timestamp < ");
query.push_bind(before);
}
if asc {
query.push(" ORDER BY transaction_timestamp ASC");
} else {
query.push(" ORDER BY transaction_timestamp DESC");
}
if let Some(lim) = limit {
query.push(" LIMIT ");
query.push_bind(lim);
}
query
}
pub async fn list_by_date(
pool: &SqlitePool,
account: i32,
after: Option<DateTime<Utc>>,
before: Option<DateTime<Utc>>,
limit: Option<i32>,
asc: bool,
) -> Result<Vec<Self>> {
let mut query = Self::query_by_date(account, after, before, limit, asc);
let rows = query.build().fetch_all(pool).await?;
let mut res = Vec::new();
for r in &rows {
res.push(Transaction::from_row(r)?);
}
Ok(res)
}
pub fn get_id(&self) -> i32 {
self.transaction_id
}
pub fn get_account(&self) -> i32 {
self.account
}
pub fn get_description(&self) -> &str {
&self.description
}
pub fn get_timestamp(&self) -> &DateTime<Utc> {
&self.transaction_timestamp
}
pub fn get_category(&self) -> Option<i32> {
self.category
}
pub async fn set_category(&mut self, pool: &SqlitePool, new_category: i32) -> Result<()> {
sqlx::query("UPDATE transactions SET category=? WHERE transaction_id=?")
.bind(new_category)
.bind(self.transaction_id)
.execute(pool)
.await?;
self.category = Some(new_category);
Ok(())
}
pub async fn recategorize(&mut self, pool: &SqlitePool, rules: &Vec<Rule>) -> Result<bool> {
for r in rules.iter() {
if r.matches(&self.description)
.map_err(|_| sqlx::Error::Protocol("RegexError".to_string()))?
{
self.set_category(pool, r.category).await?;
return Ok(true);
}
}
Ok(false)
}
pub fn get_amount(&self) -> i32 {
self.amount
}
pub async fn set_description(&mut self, pool: &SqlitePool, desc: &str) -> Result<()> {
sqlx::query("UPDATE transactions SET description=? WHERE transaction_id=?")
.bind(desc)
.bind(self.transaction_id)
.execute(pool)
.await?;
self.description = desc.to_string();
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::Transaction;
use crate::models::{account::Account, users::User};
use sqlx::SqlitePool;
async fn get_db() -> SqlitePool {
crate::create_db("sqlite://tx_test.db").await.unwrap()
}
async fn remove_db(pool: SqlitePool) {
pool.close().await;
std::fs::remove_file("tx_test.db").unwrap();
}
async fn new_user(pool: &SqlitePool) -> User {
User::create_user(pool, "testuser", "pass").await.unwrap()
}
#[tokio::test]
async fn create_test() {
let pool = get_db().await;
let user = new_user(&pool).await;
let acc = Account::new(&pool, user.get_id(), "tx_test").await.unwrap();
let tx = Transaction::new(
&pool,
acc.get_id(),
"Test transaction",
&chrono::Utc::now(),
None,
100,
)
.await
.unwrap();
println!("{tx:?}");
remove_db(pool).await;
}
}

35
src/models/users.rs Normal file
View file

@ -0,0 +1,35 @@
use sqlx::{FromRow, SqlitePool};
#[derive(Debug, FromRow)]
pub struct User {
user_id: i32,
username: String,
pass: String,
}
impl User {
pub fn get_id(&self) -> i32 {
self.user_id
}
pub fn check_pass(&self, pass: &str) -> bool {
&self.pass == pass
}
pub async fn create_user(pool: &SqlitePool, user: &str, pass: &str) -> sqlx::Result<Self> {
sqlx::query("INSERT INTO users(username, pass) VALUES (?, ?) RETURNING *")
.bind(user)
.bind(pass)
.fetch_one(pool)
.await
.and_then(|r| User::from_row(&r))
}
pub async fn get_user(pool: &SqlitePool, user: &str) -> sqlx::Result<Self> {
sqlx::query("SELECT * FROM users WHERE username = ?")
.bind(user)
.fetch_one(pool)
.await
.and_then(|r| User::from_row(&r))
}
}

16
webserver/Cargo.toml Normal file
View file

@ -0,0 +1,16 @@
[package]
name = "webserver"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serde = { workspace = true, features = ["derive"] }
chrono = { workspace = true, features = ["serde"] }
sqlx = { workspace = true, features = ["runtime-tokio", "sqlite", "chrono"]}
tokio = { version = "1", features = ["full"] }
axum = { version = "0.6.20", features = ["macros", "headers"] }
hyper = "0.14.27"
serde_json = "1"
accounters = { path = ".." }

77
webserver/src/main.rs Normal file
View file

@ -0,0 +1,77 @@
use std::net::SocketAddr;
use std::sync::Arc;
use sqlx::SqlitePool;
use axum::{
extract::FromRef,
routing::{get, post},
Router,
};
use hyper::StatusCode;
mod routes;
mod users;
const DB_URL: &str = "sqlite://sqlite.db";
#[tokio::main]
async fn main() {
let db = accounters::create_db(DB_URL).await.unwrap();
let state = AppState { db: Arc::new(db) };
let app = Router::new()
.route("/", get(index))
.nest(
"/api/v1",
Router::new()
.route("/user", post(routes::create_user))
.route("/login", post(routes::login))
.route("/accounts", post(routes::accounts::account_create))
.route("/accounts", get(routes::accounts::account_list))
.route("/accounts/id/:id", get(routes::accounts::account_get))
.route(
"/accounts/id/:id/transaction",
post(routes::transactions::create),
)
.route(
"/accounts/id/:id/transaction",
get(routes::transactions::list),
)
.route(
"/accounts/id/:id/update",
post(routes::accounts::snapshot_update),
)
.route(
"/accounts/id/:id/recategorize",
post(routes::accounts::recategorize),
)
.route("/categories", post(routes::categories::create))
.route("/categories", get(routes::categories::list))
.route("/rules", post(routes::rules::create))
.route("/rules", get(routes::rules::list)),
)
.with_state(state);
let addr = SocketAddr::from(([0, 0, 0, 0], 3000));
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
#[derive(Clone)]
pub struct AppState {
db: Arc<SqlitePool>,
}
impl FromRef<AppState> for Arc<SqlitePool> {
fn from_ref(state: &AppState) -> Arc<SqlitePool> {
state.db.clone()
}
}
async fn index() -> (StatusCode, String) {
(StatusCode::OK, String::from("Hello, World!"))
}

43
webserver/src/routes.rs Normal file
View file

@ -0,0 +1,43 @@
use std::sync::Arc;
use axum::extract::{Json, State};
use hyper::StatusCode;
use serde::Deserialize;
use sqlx::SqlitePool;
use accounters::models::users::User;
pub mod accounts;
pub mod categories;
pub mod rules;
pub mod transactions;
#[derive(Deserialize)]
pub struct CreateUserRequest {
user: String,
pass: String,
}
pub async fn create_user(
State(db): State<Arc<SqlitePool>>,
Json(user_info): Json<CreateUserRequest>,
) -> (StatusCode, String) {
let exec = User::create_user(db.as_ref(), &user_info.user, &user_info.pass).await;
match exec {
Ok(e) => (StatusCode::OK, format!("{}", e.get_id())),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:?}")),
}
}
pub async fn login(
State(db): State<Arc<SqlitePool>>,
Json(user_info): Json<CreateUserRequest>,
) -> (StatusCode, String) {
let user = User::get_user(db.as_ref(), &user_info.user).await.unwrap();
if user.check_pass(&user_info.pass) {
(StatusCode::OK, format!("{}", user.get_id()))
} else {
(StatusCode::UNAUTHORIZED, String::new())
}
}

View file

@ -0,0 +1,87 @@
use std::sync::Arc;
use axum::extract::{Json, Path, State};
use hyper::StatusCode;
use serde::Deserialize;
use sqlx::SqlitePool;
use crate::users::UserToken;
use accounters::models::Account;
pub async fn account_get(
State(db): State<Arc<SqlitePool>>,
uid: UserToken,
Path(id): Path<i32>,
) -> (StatusCode, String) {
match Account::get_by_id(db.as_ref(), id).await {
Ok(a) => {
if a.get_user() == uid.user_id {
(StatusCode::OK, serde_json::to_string(&a).unwrap())
} else {
(StatusCode::UNAUTHORIZED, String::new())
}
}
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")),
}
}
#[derive(Deserialize)]
pub struct AccountRequestCreate {
pub name: String,
}
pub async fn account_create(
State(db): State<Arc<SqlitePool>>,
uid: UserToken,
Json(account): Json<AccountRequestCreate>,
) -> (StatusCode, String) {
match Account::new(db.as_ref(), uid.user_id, &account.name).await {
Ok(a) => (StatusCode::OK, serde_json::to_string(&a).unwrap()),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")),
}
}
pub async fn account_list(
State(db): State<Arc<SqlitePool>>,
uid: UserToken,
) -> (StatusCode, String) {
match Account::list(db.as_ref(), uid.user_id).await {
Ok(a) => (StatusCode::OK, serde_json::to_string(&a).unwrap()),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")),
}
}
pub async fn snapshot_update(
State(db): State<Arc<SqlitePool>>,
uid: UserToken,
Path(account): Path<i32>,
) -> (StatusCode, String) {
let account = Account::get_by_id(db.as_ref(), account).await.unwrap();
if account.get_user() != uid.user_id {
return (StatusCode::UNAUTHORIZED, String::new());
}
match account.recalculate_snapshots(db.as_ref(), None).await {
Ok(_) => (StatusCode::OK, String::new()),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")),
}
}
pub async fn recategorize(
State(db): State<Arc<SqlitePool>>,
uid: UserToken,
Path(account): Path<i32>,
) -> (StatusCode, String) {
let account = Account::get_by_id(db.as_ref(), account).await.unwrap();
if account.get_user() != uid.user_id {
return (StatusCode::UNAUTHORIZED, String::new());
}
match account
.recategorize_transactions(db.as_ref(), None, None)
.await
{
Ok(_) => (StatusCode::OK, String::new()),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")),
}
}

View file

@ -0,0 +1,33 @@
use std::sync::Arc;
use axum::{extract::State, Json};
use hyper::StatusCode;
use serde::Deserialize;
use sqlx::SqlitePool;
use crate::users::UserToken;
use accounters::models::categories::Category;
#[derive(Deserialize)]
pub struct CategoryCreateRequest {
name: String,
description: String,
}
pub async fn create(
State(db): State<Arc<SqlitePool>>,
uid: UserToken,
Json(new_category): Json<CategoryCreateRequest>,
) -> (StatusCode, String) {
match Category::new(db.as_ref(), &new_category.name, &new_category.description).await {
Ok(_) => (StatusCode::OK, String::new()),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:?}")),
}
}
pub async fn list(State(db): State<Arc<SqlitePool>>, uid: UserToken) -> (StatusCode, String) {
match Category::list(db.as_ref()).await {
Ok(c) => (StatusCode::OK, serde_json::to_string(&c).unwrap()),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:?}")),
}
}

View file

@ -0,0 +1,33 @@
use std::sync::Arc;
use axum::extract::{Json, State};
use hyper::StatusCode;
use serde::Deserialize;
use sqlx::SqlitePool;
use crate::users::UserToken;
use accounters::models::rules::Rule;
#[derive(Deserialize)]
pub struct RuleCreateRequest {
regex: String,
category: i32,
}
pub async fn create(
State(db): State<Arc<SqlitePool>>,
uid: UserToken,
Json(rule): Json<RuleCreateRequest>,
) -> (StatusCode, String) {
match Rule::new(db.as_ref(), uid.user_id, rule.regex, rule.category).await {
Ok(r) => (StatusCode::OK, serde_json::to_string(&r).unwrap()),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:?}")),
}
}
pub async fn list(State(db): State<Arc<SqlitePool>>, uid: UserToken) -> (StatusCode, String) {
match Rule::list_by_user(db.as_ref(), uid.user_id).await {
Ok(rule_list) => (StatusCode::OK, serde_json::to_string(&rule_list).unwrap()),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:?}")),
}
}

View file

@ -0,0 +1,62 @@
use std::sync::Arc;
use axum::extract::{Json, Path, Query, State};
use chrono::{offset::Utc, DateTime};
use hyper::StatusCode;
use serde::Deserialize;
use sqlx::SqlitePool;
use accounters::models::Transaction;
#[derive(Deserialize)]
pub struct TransactionContent {
description: String,
timestamp: DateTime<Utc>,
category: Option<String>,
amount: i32,
}
pub async fn create(
State(db): State<Arc<SqlitePool>>,
Path(account): Path<i32>,
Json(txcnt): Json<TransactionContent>,
) -> (StatusCode, String) {
match Transaction::new(
db.as_ref(),
account,
&txcnt.description,
&txcnt.timestamp,
None,
txcnt.amount,
)
.await
{
Ok(tx) => (StatusCode::OK, serde_json::to_string(&tx).unwrap()),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")),
}
}
#[derive(Deserialize)]
pub struct PaginationOptions {
pub limit: Option<i32>,
pub offset: Option<i32>,
}
pub async fn list(
State(db): State<Arc<SqlitePool>>,
Path(account): Path<i32>,
Query(pagination): Query<PaginationOptions>,
) -> (StatusCode, String) {
match Transaction::list(
db.as_ref(),
account,
pagination.limit.unwrap_or(100),
pagination.offset.unwrap_or(0),
true,
)
.await
{
Ok(txs) => (StatusCode::OK, serde_json::to_string(&txs).unwrap()),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")),
}
}

42
webserver/src/users.rs Normal file
View file

@ -0,0 +1,42 @@
use axum::{
async_trait,
extract::FromRequestParts,
headers::authorization::Bearer,
headers::Authorization,
http::request::Parts,
response::{IntoResponse, Redirect},
RequestPartsExt, TypedHeader,
};
pub struct AuthRedirect;
impl IntoResponse for AuthRedirect {
fn into_response(self) -> axum::response::Response {
Redirect::temporary("/login").into_response()
}
}
pub struct UserToken {
pub user_id: i32,
}
#[async_trait]
impl<S> FromRequestParts<S> for UserToken
where
S: Send + Sync,
{
type Rejection = AuthRedirect;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let auth = parts
.extract::<TypedHeader<Authorization<Bearer>>>()
.await
.map_err(|e| panic!("Could not get cookies: {e}"))
.unwrap();
let ut = UserToken {
user_id: auth.0 .0.token().parse().unwrap(),
};
Ok(ut)
}
}