Amount is calculated by DB

This commit is contained in:
Manuel Forcén Muñoz 2024-04-24 23:19:21 +02:00
parent 79ef859fbe
commit bbc61cfe45
3 changed files with 71 additions and 109 deletions

View file

@ -38,7 +38,6 @@ CREATE TABLE IF NOT EXISTS transactions (
amount INTEGER, amount INTEGER,
accumulated INTEGER DEFAULT 0, accumulated INTEGER DEFAULT 0,
tx_order INTEGER DEFAULT 0, tx_order INTEGER DEFAULT 0,
hash TEXT,
FOREIGN KEY (account) REFERENCES accounts(account_id), FOREIGN KEY (account) REFERENCES accounts(account_id),
FOREIGN KEY (category) REFERENCES categories(category_id) FOREIGN KEY (category) REFERENCES categories(category_id)
); );
@ -48,34 +47,39 @@ BEGIN
UPDATE transactions UPDATE transactions
SET accumulated=old.acc+NEW.amount SET accumulated=old.acc+NEW.amount
FROM ( FROM (
SELECT COALESCE(max(accumulated), 0) AS acc SELECT COALESCE(accumulated, 0) AS acc
FROM transactions FROM transactions
WHERE date <= NEW.date WHERE tx_date <= NEW.tx_date
ORDER BY tx_order DESC AND transaction_id <> NEW.transaction_id
AND account=NEW.account
ORDER BY tx_date DESC, tx_order DESC
LIMIT 1 LIMIT 1
) AS old ) AS old
WHERE id=NEW.id; WHERE transaction_id=NEW.transaction_id;
UPDATE transactions UPDATE transactions
SET tx_order=old.tx_order+1 FROM ( SET tx_order=old.tx_order+1 FROM (
SELECT COALESCE(max(tx_order), 0) as tx_order SELECT COALESCE(max(tx_order), 0) as tx_order
FROM tx WHERE date=NEW.date FROM transactions WHERE tx_date=NEW.tx_date
) AS old ) AS old
WHERE id=NEW.id; WHERE transaction_id=NEW.transaction_id;
UPDATE transactions SET accumulated=calc.acc+NEW.accumulated FROM ( UPDATE transactions SET accumulated=calc.acc+cte_tx.accumulated FROM (
SELECT tx.id, ( SELECT tx.transaction_id, (
SUM(amount) OVER ( SUM(amount) OVER (
ORDER BY date, tx_order ORDER BY tx_date, tx_order
ROWS BETWEEN ROWS BETWEEN
UNBOUNDED PRECEDING UNBOUNDED PRECEDING
AND CURRENT ROW AND CURRENT ROW
) )
) acc ) acc
FROM transactions tx FROM transactions tx
WHERE date > NEW.date OR id=NEW.id; WHERE tx_date > NEW.tx_date AND account=NEW.account
) ) AS calc, (
WHERE transactions.id=calc.id; SELECT accumulated
FROM transactions tx
WHERE tx.transaction_id=NEW.transaction_id
) AS cte_tx
WHERE transactions.transaction_id=calc.transaction_id;
END; END;
CREATE INDEX idx_transactions_ts ON transactions(account, tx_date); CREATE INDEX idx_transactions_ts ON transactions(account, tx_date);
CREATE INDEX idx_transactions_hash ON transactions(hash);

View file

@ -2,27 +2,17 @@ use chrono::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sqlx::{FromRow, Result, Sqlite, SqlitePool}; use sqlx::{FromRow, Result, Sqlite, SqlitePool};
use md5::{Digest, Md5};
use crate::models::rules::Rule; use crate::models::rules::Rule;
pub enum TxConflictResolutionMode {
Nothing,
Error,
Duplicate,
}
#[derive(FromRow, Serialize, Deserialize, Debug)] #[derive(FromRow, Serialize, Deserialize, Debug)]
pub struct Transaction { pub struct Transaction {
transaction_id: i32, transaction_id: i32,
account: i32, account: i32,
description: String, description: String,
transaction_timestamp: DateTime<Utc>, tx_date: DateTime<Utc>,
category: Option<i32>, category: Option<i32>,
amount: i32, amount: i32,
accumulated: i32, accumulated: i32,
#[serde(default, skip_serializing)]
hash: Option<String>,
} }
impl Transaction { impl Transaction {
@ -33,47 +23,28 @@ impl Transaction {
ts: &DateTime<Utc>, ts: &DateTime<Utc>,
category: Option<i32>, category: Option<i32>,
amount: i32, amount: i32,
on_conflict: TxConflictResolutionMode,
) -> Result<Self> { ) -> Result<Self> {
let hash = Transaction::get_tx_hash(account, &desc, &ts, amount);
let tx_db = match sqlx::query("SELECT * FROM transactions WHERE hash=? LIMIT 1")
.bind(&hash)
.fetch_one(pool)
.await
{
Ok(row) => Some(Transaction::from_row(&row)?),
Err(sqlx::Error::RowNotFound) => None,
Err(e) => {
return Err(e);
}
};
if let Some(tx) = tx_db {
match on_conflict {
TxConflictResolutionMode::Nothing => {
return Ok(tx);
}
TxConflictResolutionMode::Error => {
return Err(sqlx::Error::RowNotFound);
}
_ => {}
}
}
sqlx::query(concat!( sqlx::query(concat!(
"INSERT INTO transactions(", "INSERT INTO transactions(",
"account, description, transaction_timestamp, category, amount, hash", "account, description, tx_date, category, amount",
") VALUES (?,?,?,?,?,?) RETURNING *" ") VALUES (?,?,?,?,?) RETURNING *"
)) ))
.bind(account) .bind(account)
.bind(desc) .bind(desc)
.bind(ts) .bind(ts)
.bind(category) .bind(category)
.bind(amount) .bind(amount)
.bind(hash)
.fetch_one(pool) .fetch_one(pool)
.await .await
.map(|x| Transaction::from_row(&x).unwrap()) .and_then(|x| Transaction::from_row(&x))
}
pub async fn get_by_id(pool: &SqlitePool, tx_id: i32) -> Result<Self> {
sqlx::query("SELECT * FROM transactions WHERE transaction_id=?")
.bind(tx_id)
.fetch_one(pool)
.await
.and_then(|x| Transaction::from_row(&x))
} }
pub async fn list( pub async fn list(
@ -83,13 +54,12 @@ impl Transaction {
offset: i32, offset: i32,
asc: bool, asc: bool,
) -> Result<Vec<Self>> { ) -> Result<Vec<Self>> {
let rows = sqlx::query( let rows = sqlx::query(if asc {
if asc { "SELECT * FROM transactions WHERE account=? ORDER BY tx_date ASC LIMIT ? OFFSET ?"
"SELECT * FROM transactions WHERE account=? ORDER BY transaction_timestamp ASC LIMIT ? OFFSET ?"
} else { } else {
"SELECT * FROM transactions WHERE account=? ORDER BY transaction_timestamp DESC LIMIT ? OFFSET ?" "SELECT * FROM transactions WHERE account=? ORDER BY tx_date DESC LIMIT ? OFFSET ?"
} })
).bind(account) .bind(account)
.bind(limit) .bind(limit)
.bind(offset) .bind(offset)
.fetch_all(pool) .fetch_all(pool)
@ -111,9 +81,9 @@ impl Transaction {
) -> Result<Vec<Self>> { ) -> Result<Vec<Self>> {
let rows = sqlx::query( let rows = sqlx::query(
if asc { if asc {
"SELECT t.* FROM transactions t JOIN accounts a ON a.account_id=t.account WHERE a.user=? ORDER BY transaction_timestamp ASC LIMIT ? OFFSET ?" "SELECT t.* FROM transactions t JOIN accounts a ON a.account_id=t.account WHERE a.user=? ORDER BY tx_date ASC LIMIT ? OFFSET ?"
} else { } else {
"SELECT t.* FROM transactions t JOIN accounts a ON a.account_id=t.account WHERE a.user=? ORDER BY transaction_timestamp DESC LIMIT ? OFFSET ?" "SELECT t.* FROM transactions t JOIN accounts a ON a.account_id=t.account WHERE a.user=? ORDER BY tx_date DESC LIMIT ? OFFSET ?"
} }
).bind(user) ).bind(user)
.bind(limit) .bind(limit)
@ -139,19 +109,19 @@ impl Transaction {
query.push_bind(account); query.push_bind(account);
if let Some(after) = after { if let Some(after) = after {
query.push(" AND transaction_timestamp >= "); query.push(" AND tx_date >= ");
query.push_bind(after); query.push_bind(after);
} }
if let Some(before) = before { if let Some(before) = before {
query.push(" AND transaction_timestamp < "); query.push(" AND tx_date < ");
query.push_bind(before); query.push_bind(before);
} }
if asc { if asc {
query.push(" ORDER BY transaction_timestamp ASC"); query.push(" ORDER BY tx_date ASC");
} else { } else {
query.push(" ORDER BY transaction_timestamp DESC"); query.push(" ORDER BY tx_date DESC");
} }
if let Some(lim) = limit { if let Some(lim) = limit {
@ -194,20 +164,24 @@ impl Transaction {
} }
pub fn get_timestamp(&self) -> &DateTime<Utc> { pub fn get_timestamp(&self) -> &DateTime<Utc> {
&self.transaction_timestamp &self.tx_date
} }
pub fn get_category(&self) -> Option<i32> { pub fn get_category(&self) -> Option<i32> {
self.category self.category
} }
pub async fn set_category(&mut self, pool: &SqlitePool, new_category: i32) -> Result<()> { pub async fn set_category(
&mut self,
pool: &SqlitePool,
new_category: Option<i32>,
) -> Result<()> {
sqlx::query("UPDATE transactions SET category=? WHERE transaction_id=?") sqlx::query("UPDATE transactions SET category=? WHERE transaction_id=?")
.bind(new_category) .bind(new_category)
.bind(self.transaction_id) .bind(self.transaction_id)
.execute(pool) .execute(pool)
.await?; .await?;
self.category = Some(new_category); self.category = new_category;
Ok(()) Ok(())
} }
@ -216,7 +190,7 @@ impl Transaction {
if r.matches(&self.description) if r.matches(&self.description)
.map_err(|_| sqlx::Error::Protocol("RegexError".to_string()))? .map_err(|_| sqlx::Error::Protocol("RegexError".to_string()))?
{ {
self.set_category(pool, r.category).await?; self.set_category(pool, Some(r.category)).await?;
return Ok(true); return Ok(true);
} }
} }
@ -227,15 +201,13 @@ impl Transaction {
self.amount self.amount
} }
pub fn get_accumulated(&self) -> i32 {
self.accumulated
}
pub async fn set_description(&mut self, pool: &SqlitePool, desc: &str) -> Result<()> { pub async fn set_description(&mut self, pool: &SqlitePool, desc: &str) -> Result<()> {
sqlx::query("UPDATE transactions SET description=?, hash=? WHERE transaction_id=?") sqlx::query("UPDATE transactions SET description=? WHERE transaction_id=?")
.bind(desc) .bind(desc)
.bind(Transaction::get_tx_hash(
self.account,
desc,
&self.transaction_timestamp,
self.amount,
))
.bind(self.transaction_id) .bind(self.transaction_id)
.execute(pool) .execute(pool)
.await?; .await?;
@ -243,27 +215,22 @@ impl Transaction {
Ok(()) Ok(())
} }
pub fn get_tx_hash(account: i32, description: &str, ts: &DateTime<Utc>, amount: i32) -> String { pub async fn set_amount(&mut self, pool: &SqlitePool, amount: i32) -> Result<()> {
let mut hasher = Md5::new(); sqlx::query("UPDATE transactions SET amount=? WHERE transaction_id=?")
hasher.update(format!( .bind(amount)
"{}/{}/{}/{}", .bind(self.transaction_id)
account, .execute(pool)
description, .await?;
ts.to_rfc3339(), self.accumulated -= self.amount;
amount self.amount = amount;
)); self.accumulated += self.amount;
let mut out = String::new(); Ok(())
out.reserve(32);
for byte in hasher.finalize().iter() {
out.push_str(&format!("{:02x?}", byte));
}
out
} }
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{Transaction, TxConflictResolutionMode}; use super::Transaction;
use crate::models::{account::Account, users::User}; use crate::models::{account::Account, users::User};
use sqlx::SqlitePool; use sqlx::SqlitePool;
@ -292,7 +259,6 @@ mod tests {
&chrono::Utc::now(), &chrono::Utc::now(),
None, None,
100, 100,
TxConflictResolutionMode::Nothing,
) )
.await .await
.unwrap(); .unwrap();

View file

@ -6,7 +6,7 @@ use hyper::StatusCode;
use serde::Deserialize; use serde::Deserialize;
use sqlx::SqlitePool; use sqlx::SqlitePool;
use accounters::models::transaction::{Transaction, TxConflictResolutionMode}; use accounters::models::transaction::Transaction;
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct TransactionContent { pub struct TransactionContent {
@ -14,8 +14,6 @@ pub struct TransactionContent {
timestamp: DateTime<Utc>, timestamp: DateTime<Utc>,
category: Option<String>, category: Option<String>,
amount: i32, amount: i32,
#[serde(default)]
error_on_conflict: Option<bool>,
} }
pub async fn create( pub async fn create(
@ -23,11 +21,6 @@ pub async fn create(
Path(account): Path<i32>, Path(account): Path<i32>,
Json(txcnt): Json<TransactionContent>, Json(txcnt): Json<TransactionContent>,
) -> (StatusCode, String) { ) -> (StatusCode, String) {
let error_on_conflict = if txcnt.error_on_conflict.is_some_and(|x| x) {
TxConflictResolutionMode::Error
} else {
TxConflictResolutionMode::Nothing
};
match Transaction::new( match Transaction::new(
db.as_ref(), db.as_ref(),
account, account,
@ -35,7 +28,6 @@ pub async fn create(
&txcnt.timestamp, &txcnt.timestamp,
None, None,
txcnt.amount, txcnt.amount,
error_on_conflict,
) )
.await .await
{ {