Moved templates to be embedded in executable

This commit is contained in:
Manuel Forcén Muñoz 2024-06-03 18:39:17 +02:00
parent b676be8cb2
commit 1c1a9589b7
25 changed files with 957 additions and 256 deletions

View file

@ -5,6 +5,9 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
crate-type = ["lib"]
[dependencies]
serde = { workspace = true, features = ["derive"] }
chrono = { workspace = true, features = ["serde"] }

4
webserver/src/lib.rs Normal file
View file

@ -0,0 +1,4 @@
pub mod routes;
pub mod server;
pub mod static_values;
pub mod users;

View file

@ -1,110 +1,15 @@
use std::net::SocketAddr;
use std::sync::Arc;
use sqlx::SqlitePool;
use axum::{
extract::FromRef,
routing::{get, post},
Router,
};
use hyper::StatusCode;
use tera::Tera;
mod routes;
mod server;
mod static_values;
mod users;
const DB_URL: &str = "sqlite://sqlite.db";
#[tokio::main]
async fn main() {
let db = accounters::create_db(DB_URL).await.unwrap();
let server = server::start_server("127.0.0.1:3000", DB_URL);
let mut tmpls = Tera::new("templates/*").unwrap();
tmpls.autoescape_on(vec!["html"]);
let state = AppState {
db: Arc::new(db),
tmpls: Arc::new(tmpls),
};
let exec_id: u32 = rand::random();
let app = Router::new()
.nest(
"/",
Router::new()
.route("/", get(routes::ui::index))
.route("/accounts/id/:id", get(routes::ui::account::show))
.route(
"/accounts/id/:id/transactions/add",
get(routes::ui::account::add_transactions_view)
.post(routes::ui::account::add_transactions_action),
)
.route(
"/accounts/id/:id/transactions",
get(routes::ui::account::list_transactions),
)
.route(
"/transaction/:id",
get(routes::ui::transaction::view).post(routes::ui::transaction::update),
)
.route(
"/classifiers",
get(routes::ui::classifier::view_classifiers),
)
.route(
"/classifiers/new_rule",
get(routes::ui::classifier::rules_new_view)
.post(routes::ui::classifier::rules_new_action),
)
.route(
"/classifiers/new_category",
get(routes::ui::classifier::category_new_view)
.post(routes::ui::classifier::category_new_action),
)
.nest(
"/static",
Router::new()
.route("/styles.css", get(routes::static_routes::styles))
.route("/csv.js", get(routes::static_routes::csv)),
)
.route(
"/execution",
get(move || async move { format!("{exec_id}") }),
),
)
.nest(
"/api/v1",
Router::new()
.route("/user", post(routes::api::create_user))
.route("/login", post(routes::api::login))
.route("/accounts", post(routes::api::accounts::account_create))
.route("/accounts", get(routes::api::accounts::account_list))
.route("/accounts/id/:id", get(routes::api::accounts::account_get))
.route(
"/accounts/id/:id/transaction",
post(routes::api::transactions::create),
)
.route(
"/accounts/id/:id/transaction",
get(routes::api::transactions::list),
)
.route(
"/accounts/id/:id/recategorize",
post(routes::api::accounts::recategorize),
)
.route("/categories", post(routes::api::categories::create))
.route("/categories", get(routes::api::categories::list))
.route("/rules", post(routes::api::rules::create))
.route("/rules", get(routes::api::rules::list)),
)
.with_state(state);
let addr = SocketAddr::from(([0, 0, 0, 0], 3000));
let server = axum::Server::bind(&addr).serve(app.into_make_service());
let wv_task = tokio::task::spawn_blocking(|| {
/*let wv_task = tokio::task::spawn_blocking(|| {
web_view::builder()
.title("Test")
.content(web_view::Content::Url("http://localhost:3000"))
@ -122,27 +27,6 @@ async fn main() {
e = server => {
println!("Axum finished with result {e:?}");
}
}
}
#[derive(Clone)]
pub struct AppState {
db: Arc<SqlitePool>,
tmpls: Arc<Tera>,
}
impl FromRef<AppState> for Arc<SqlitePool> {
fn from_ref(state: &AppState) -> Arc<SqlitePool> {
state.db.clone()
}
}
impl FromRef<AppState> for Arc<Tera> {
fn from_ref(state: &AppState) -> Arc<Tera> {
state.tmpls.clone()
}
}
async fn index() -> (StatusCode, String) {
(StatusCode::OK, String::from("Hello, World!"))
}*/
server.await.unwrap()
}

View file

@ -3,11 +3,13 @@ use std::fs;
use axum::response::IntoResponse;
use hyper::{header::CONTENT_TYPE, StatusCode};
use crate::static_values;
pub async fn styles() -> impl IntoResponse {
(
StatusCode::OK,
[(CONTENT_TYPE, "text/css")],
fs::read_to_string("static/styles.css").unwrap(),
static_values::STYLES,
)
}
@ -15,6 +17,6 @@ pub async fn csv() -> impl IntoResponse {
(
StatusCode::OK,
[(CONTENT_TYPE, "application/javascript")],
fs::read_to_string("static/csv.js").unwrap(),
static_values::CSV,
)
}

202
webserver/src/server.rs Normal file
View file

@ -0,0 +1,202 @@
use std::net::{AddrParseError, SocketAddr};
use std::sync::Arc;
use axum::headers::ContentType;
use hyper::{header, StatusCode};
use sqlx::SqlitePool;
use axum::{
extract::FromRef,
routing::{get, post},
Router,
};
use tera::Tera;
use crate::{routes, static_values as templates};
#[derive(Debug)]
pub enum ServerError {
Db(sqlx::Error),
Tera(tera::Error),
Axum(axum::Error),
Hyper(hyper::Error),
AddrParse(AddrParseError),
}
impl From<sqlx::Error> for ServerError {
fn from(value: sqlx::Error) -> Self {
Self::Db(value)
}
}
impl From<tera::Error> for ServerError {
fn from(value: tera::Error) -> Self {
Self::Tera(value)
}
}
impl From<axum::Error> for ServerError {
fn from(value: axum::Error) -> Self {
Self::Axum(value)
}
}
impl From<hyper::Error> for ServerError {
fn from(value: hyper::Error) -> Self {
Self::Hyper(value)
}
}
impl From<AddrParseError> for ServerError {
fn from(value: AddrParseError) -> Self {
Self::AddrParse(value)
}
}
pub async fn start_server(bind: &str, db_url: &str) -> Result<(), ServerError> {
let mut tmpls = Tera::default();
tmpls
.add_raw_template("base.html", templates::BASE)
.unwrap();
tmpls
.add_raw_template("index.html", templates::INDEX)
.unwrap();
tmpls
.add_raw_template("account_summary.html", templates::ACCOUNT_SUMMARY)
.unwrap();
tmpls
.add_raw_template("account_txs.html", templates::ACCOUNT_TXS)
.unwrap();
tmpls
.add_raw_template("account_add_txs.html", templates::ACCOUNT_ADD_TXS)
.unwrap();
tmpls
.add_raw_template("categories_new.html", templates::CATEGORIES_NEW)
.unwrap();
tmpls
.add_raw_template("classifiers.html", templates::CLASSIFIERS)
.unwrap();
tmpls
.add_raw_template("rules_new.html", templates::RULES_NEW)
.unwrap();
tmpls
.add_raw_template("rules_new_success.html", templates::RULES_NEW_SUCCESS)
.unwrap();
tmpls
.add_raw_template("transaction.html", templates::TRANSACTION)
.unwrap();
let db = accounters::create_db(db_url).await?;
let state = AppState {
db: Arc::new(db),
tmpls: Arc::new(tmpls),
};
let exec_id: u32 = rand::random();
let app = Router::new()
.nest(
"/",
Router::new()
.route("/", get(routes::ui::index))
.route("/accounts/id/:id", get(routes::ui::account::show))
.route(
"/accounts/id/:id/transactions/add",
get(routes::ui::account::add_transactions_view)
.post(routes::ui::account::add_transactions_action),
)
.route(
"/accounts/id/:id/transactions",
get(routes::ui::account::list_transactions),
)
.route(
"/transaction/:id",
get(routes::ui::transaction::view).post(routes::ui::transaction::update),
)
.route(
"/classifiers",
get(routes::ui::classifier::view_classifiers),
)
.route(
"/classifiers/new_rule",
get(routes::ui::classifier::rules_new_view)
.post(routes::ui::classifier::rules_new_action),
)
.route(
"/classifiers/new_category",
get(routes::ui::classifier::category_new_view)
.post(routes::ui::classifier::category_new_action),
)
.nest(
"/static",
Router::new()
.route("/styles.css", get(routes::static_routes::styles))
.route("/csv.js", get(routes::static_routes::csv)),
)
.route(
"/execution",
get(move || async move { format!("{exec_id}") }),
),
)
.nest(
"/api/v1",
Router::new()
.route(
"/healthcheck",
get(|| async {
(
StatusCode::OK,
[(header::CONTENT_TYPE, "text/html")],
String::from("<html><body><div>Hello world from the healthcheck!</div></body></html>"),
)
}),
)
.route("/user", post(routes::api::create_user))
.route("/login", post(routes::api::login))
.route("/accounts", post(routes::api::accounts::account_create))
.route("/accounts", get(routes::api::accounts::account_list))
.route("/accounts/id/:id", get(routes::api::accounts::account_get))
.route(
"/accounts/id/:id/transaction",
post(routes::api::transactions::create),
)
.route(
"/accounts/id/:id/transaction",
get(routes::api::transactions::list),
)
.route(
"/accounts/id/:id/recategorize",
post(routes::api::accounts::recategorize),
)
.route("/categories", post(routes::api::categories::create))
.route("/categories", get(routes::api::categories::list))
.route("/rules", post(routes::api::rules::create))
.route("/rules", get(routes::api::rules::list)),
)
.with_state(state);
let addr: SocketAddr = bind.parse()?;
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await?;
Ok(())
}
#[derive(Clone)]
pub struct AppState {
pub db: Arc<SqlitePool>,
pub tmpls: Arc<Tera>,
}
impl FromRef<AppState> for Arc<SqlitePool> {
fn from_ref(state: &AppState) -> Arc<SqlitePool> {
state.db.clone()
}
}
impl FromRef<AppState> for Arc<Tera> {
fn from_ref(state: &AppState) -> Arc<Tera> {
state.tmpls.clone()
}
}

View file

@ -0,0 +1,105 @@
{% extends "base.html" %}
{% block title %}Account {{account.account_name}}{% endblock title %}
{% block body %}
<div class="flex">
<span class="text-lg grow">{{account.account_name}}</span>
<div>
<a href="/accounts/id/{{account.account_id}}/transactions/add">+</a>
</div>
</div>
<div class="mb-4">
<h2>Net amount</h2>
<div class="ars-input">
<label>
<span>Dates</span>
<button style="float: right;" class="ars-button" onclick="onDateChange(event)">Update</button>
<input id="amount-date-range" />
</label>
</div>
<div style="height: 400px; width: 800px; position: relative;">
<canvas id="amount-trend"></canvas>
</div>
</div>
<div class="mb-2">
<h2>Last transactions</h2>
<a class="ars-button" href="/accounts/id/{{account.account_id}}/transactions">More</a>
<table width="100%">
<thead>
<tr>
<th width="40%">Description</th>
<th width="20%">Date</th>
<th width="10%">Amount</th>
<th width="10%">Acc</th>
<th width="15%">Category</th>
<th width="5%">Link</th>
</tr>
</thead>
<tbody>
{% for tx in transactions %}
<tr>
<td>{{tx.description}}</td>
<td>{{tx.tx_date}}</td>
<td>{{tx.amount/100}}</td>
<td>{{tx.accumulated/100}}</td>
<td>{% if tx.category %}{{categories[tx.category]}}{% endif %}</td>
<td><a href="/transaction/{{ tx.transaction_id }}">Go to</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<style>
table {
border-spacing: 0.2rem;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/litepicker/dist/litepicker.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
function onDateChange(e) {
let date_val = document.getElementById('amount-date-range').value.split(' - ');
let params = new URLSearchParams(window.location.search);
params.set('from', date_val[0]);
params.set('to', date_val[1]);
window.location.search = params.toString();
}
function onSelect(e) {
let params = new URLSearchParams(window.location.search);
params.set("entries", e.target.value);
window.location.search = params.toString();
}
const dateEl = document.getElementById('amount-date-range');
const picker = new Litepicker({
element: dateEl,
singleMode: false,
maxDate: new Date(),
startDate: "{{date_from}}",
endDate: "{{date_to}}"
});
function formatDate(date) {
return date.substr(0, date.indexOf('T'));
}
const data = [
{% for txag in tx_agg -%}
{x: formatDate("{{txag.tx_date}}"), y: {{txag.accumulated/100}} },
{% endfor %}
];
const ctx = document.getElementById('amount-trend');
const chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{label: 'Account', data: data}],
},
});
</script>
{% endblock body %}

View file

@ -0,0 +1,82 @@
{% extends "base.html" %}
{% block title %}Account {{account.account_name}}{% endblock title %}
{% block body %}
<div class="flex">
<span class="text-lg grow">{{account.account_name}}</span>
<div>
<a href="/accounts/id/{{account.account_id}}/transactions/add">+</a>
</div>
</div>
<div class="mb-2">
<h2>Transactions</h2>
<button class="ars-button" onclick="onRecategorize()">Recategorize</button>
<table width="100%">
<thead>
<tr>
<th width="40%">Description</th>
<th width="20%">Date</th>
<th width="10%">Amount</th>
<th width="10%">Acc</th>
<th width="15%">Category</th>
<th width="5%">Link</th>
</tr>
</thead>
<tbody>
{% for tx in transactions %}
<tr>
<td>{{tx.description}}</td>
<td>{{tx.tx_date}}</td>
<td>{{tx.amount/100}}</td>
<td>{{tx.accumulated/100}}</td>
<td>{% if tx.category %}{{categories[tx.category]}}{% endif %}</td>
<td><a href="/transaction/{{ tx.transaction_id }}">Go to</a></td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="flex">
<div class="flex grow flex-row justify-evenly">
<div>
<a href="/accounts/id/{{account.account_id}}?entries={{n_entries}}&page={{prev_page}}">&lt;</a>
</div>
<div>{{curr_page + 1}}</div>
<div>
<a href="/accounts/id/{{account.account_id}}?entries={{n_entries}}&page={{next_page}}">&gt;</a>
</div>
</div>
<div>
<select onchange="onSelect(event)">
<option {% if n_entries == 10 %}selected="selected"{% endif %}>10</option>
<option {% if n_entries == 20 %}selected="selected"{% endif %}>20</option>
<option {% if n_entries == 50 %}selected="selected"{% endif %}>50</option>
<option {% if n_entries == 100 %}selected="selected"{% endif %}>100</option>
<option {% if n_entries == 200 %}selected="selected"{% endif %}>200</option>
</select>
</div>
</div>
</div>
<style>
table {
border-spacing: 0.2rem;
}
</style>
<script>
function onRecategorize() {
fetch(
'/api/v1/accounts/id/{{account.account_id}}/recategorize',
{method: 'POST'}
).then(e=>console.log(e));
}
function onSelect(e) {
let params = new URLSearchParams(window.location.search);
params.set("entries", e.target.value);
window.location.search = params.toString();
}
function formatDate(date) {
return date.substr(0, date.indexOf('T'));
}
</script>
{% endblock body %}

View file

@ -0,0 +1,176 @@
{% extends "base.html" %}
{% block title %}Account {{account.account_name}}{% endblock title %}
{% block body %}
<div class="flex flex-col">
<div>
<span class="text-lg grow">Add transactions to {{account.account_name}}</span>
</div>
<div>
<form id="file-form">
<div><input id="file-input" type="file" name="file"></div>
<div><input id="file-submit" type="submit" value="Upload transactions" disabled></div>
</form>
</div>
<div id="file-content">
</div>
</div>
<script type="module" src="/static/csv.js"></script>
<script type="module">
import csv_parse from "/static/csv.js";
const form_elem = document.getElementById('file-form')
form_elem.onsubmit = (evt) => {
evt.preventDefault();
console.log('Unable to send');
}
const mappers = [
['None', null],
['Date dd/mm/yyyy', el => {
let split = el.split('/');
return new Date(Date.UTC(
parseInt(split[2], 10),
parseInt(split[1], 10)-1,
parseInt(split[0], 10),
));
}],
['Date yyyy/mm/dd', el => {
let split = el.split('/');
return new Date(Date.UTC(
parseInt(split[0], 10),
parseInt(split[1], 10)-1,
parseInt(split[2], 10),
));
}],
['Description', el => el],
['Amount', el => parseFloat(el)]
];
function appendOptions(el) {
el.replaceChildren(...mappers.map((e, idx)=>{
let option = document.createElement('option');
option.setAttribute('value', idx);
option.textContent = e[0];
return option;
}));
}
document.getElementById('file-input').onchange = (evt) => {
let files = evt.target.files;
if(files.length > 0) {
let file = files[0];
if(file.type != 'text/csv') {
window.alert("File not valid");
return;
}
file.text().then(content => {
let line_end = content.indexOf('\n');
if(line_end == -1) {
window.alert("File is not a valid CSV");
return;
}
let table_content = csv_parse(content);
let table_header = table_content.splice(0,1)[0];
let table = document.createElement('table');
let thead = document.createElement('thead');
let trhead = document.createElement('tr');
trhead.replaceChildren(...table_header.map(e =>{
let elem = document.createElement('th');
let text = document.createElement('div');
text.textContent = e;
elem.appendChild(text);
let container = document.createElement('div');
let sel_el = document.createElement('select');
sel_el.id = 'column_' + e;
appendOptions(sel_el);
container.appendChild(sel_el);
elem.appendChild(container);
return elem;
}));
thead.appendChild(trhead);
table.appendChild(thead);
form_elem.onsubmit = (evt) => {
evt.preventDefault();
console.log(table_header);
console.log(table_content);
let mapper = {
date: null,
amount: null,
description: null
};
table_header.forEach((e, idx)=>{
let option = document.getElementById('column_'+e).selectedIndex;
switch(option){
case 1:
case 2:
mapper.date = row => mappers[option][1](row[idx]);
break;
case 3:
mapper.description = row => mappers[option][1](row[idx]);
break;
case 4:
mapper.amount = row => mappers[option][1](row[idx]);
break;
}
});
if(mapper.date == null) {
alert('Missing date mapping');
return;
} else if(mapper.amount == null) {
alert('Missing amount mapping');
return;
} else if(mapper.description == null) {
alert('Missing description mapping');
return;
}
let out = table_content.map(e=>{
return {
date: mapper.date(e),
amount: mapper.amount(e),
description: mapper.description(e)
};
});
fetch('add', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(out)
}).then(e=>window.location.href='..');
};
document.getElementById('file-submit').removeAttribute('disabled');
let tbody = document.createElement('tbody');
tbody.replaceChildren(...table_content.map(row => {
let row_elem = document.createElement('tr');
row_elem.replaceChildren(...row.map(cell => {
let td = document.createElement('td');
td.textContent = cell;
return td;
}));
return row_elem;
}))
table.appendChild(tbody);
let content_div = document.getElementById('file-content');
content_div.replaceChildren(table);
});
}
}
</script>
<style>
th, td {
padding: 0.25rem 1rem;
}
</style>
{% endblock body %}

View file

@ -0,0 +1,59 @@
<!doctype html>
<html>
<head>
<title>{% block title %}{% endblock title %}</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="/static/styles.css">
<style>
html, body {
height: 100%;
margin: 0;
background:
}
.sidebar {
width: 12rem;
}
.sidebar a {
padding: 0.5rem;
border-radius: 3px;
}
</style>
</head>
<body>
<div class="flex h-full">
<aside class="sidebar bg-stone-300 p-4 flex flex-col">
<a class="hover:bg-stone-400" href="/">Summary</a>
<a class="hover:bg-stone-400" href="/accounts">Accounts</a>
<a class="hover:bg-stone-400" href="/classifiers">Classifiers</a>
</aside>
<div class="p-4 grow h-full overflow-auto">
{% block body %}
{% endblock body %}
</div>
</div>
<script>
let state = {execution: null};
const check_exec = () => {
return fetch('/execution')
.then(response => response.text())
.then(data => parseInt(data))
.catch(err => {});
}
/*window.onload = () => {
check_exec().then(exec => {
state.execution = exec;
setInterval(()=>{
check_exec().then(exec => {
if(exec && state.execution != exec) {
location.reload();
}
});
}, 1000);
})
}*/
</script>
</body>
</html>

View file

@ -0,0 +1,21 @@
{% extends "base.html" %}
{% block title %}Create category{% endblock title %}
{% block body %}
<form action="/classifiers/new_category" method="post">
<div class="mb-2">
<label class="ars-input">
Name
<input type="text" name="name" />
</label>
</div>
<div class="mb-2">
<label class="ars-input">
Description
<input type="text" name="description" />
</label>
</div>
<div class="mb-2" style="text-align: right;">
<button class="ars-button" type="submit">Submit</button>
</div>
</form>
{% endblock body %}

View file

@ -0,0 +1,49 @@
{% extends "base.html" %}
{% block title %}Rules{% endblock title %}
{% block body %}
<div class="mb-8">
<div>
<a class="ars-button" href="/classifiers/new_category">New</a>
</div>
<table width="100%">
<thead>
<tr>
<th width="10%" span="col">Id</th>
<th width="30%" span="col">Name</th>
<th span="col">Description</th>
<tr>
</thead>
<tbody>
{% for category in categories %}
<tr>
<td>{{category.category_id}}</td>
<td>{{category.name}}</td>
<td>{{category.description}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div
<div>
<div>
<a class="ars-button" href="/classifiers/new_rule">New</a>
</div>
<table width="100%">
<thead>
<tr>
<th width="30%">Category</th>
<th>Rule</th>
</tr>
</thead>
<tbody>
{% for rule in rules %}
<tr>
<td>{{rule.category}}</td>
<td>{{rule.regex}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock body %}

View file

@ -0,0 +1,47 @@
function parse(text) {
let state = 0;
let idx = 0;
let current = '';
let curr_row = [];
let rows = [];
while(idx < text.length) {
switch (text[idx]) {
case '\\':
current += text[idx++];
break;
case '"':
if(current.length == 0) {
while(text.length > idx && text[++idx] != '"')
current += text[idx];
}
break;
case ',':
if (/^\d+(\.\d+)?$/.test(current)) {
let asnum = parseFloat(current);
curr_row.push(asnum);
} else {
curr_row.push(current);
}
current = '';
break;
case '\n':
curr_row.push(current);
current = '';
rows.push(curr_row);
curr_row = [];
break;
default:
current += text[idx];
break;
}
idx++;
}
return rows;
}
export default parse;

View file

@ -0,0 +1,91 @@
{% extends "base.html" %}
{% block title %}Index{% endblock title %}
{% block body %}
<div class="mb-4">
<h2 class="text-lg">Accounts</h2>
<table width="100%">
<thead>
<tr>
<th width="10%">ID</th>
<th>Description</th>
<th width="30%">Accumulated</th>
<th width="20%">Go to</th>
</tr>
</thead>
<tbody>
{% for account in accounts %}
<tr>
<td style="text-align: center;">{{ account.id }}</td>
<td style="text-align: center;">{{ account.description }}</td>
<td style="text-align: center;">{{ account.accumulated | round(precision=2) }}</td>
<td style="text-align: center;">
<a class="p-2 hover:bg-stone-200" href="/accounts/id/{{ account.id }}">{{ account.description }}</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="mb-4">
<h2 class="text-lg">Last month summary</h2>
<div style="width: 200px; height: 200px;">
<canvas id="chart" style="width: 200px; height: 200px;"></canvas>
</div>
</div>
<div>
<h2 class="text-lg">Last transactions</h2>
<table width="100%">
<thead>
<tr>
<th width="40%">Description</th>
<th width="20%">Date</th>
<th width="20%">Amount</th>
<th width="20%">Category</th>
</tr>
</thead>
<tbody>
{% for tx in transactions %}
<tr onclick="document.href='transactions/{{tx.transaction_id}}'">
<td>{{tx.description}}</td>
<td>{{tx.tx_date}}</td>
<td>{{tx.amount/100}}</td>
<td>{% if tx.category %}{{categories[tx.category]}}{% endif %}</td>
</tr>
{% endfor %}
</tbody>
</table>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('chart');
new Chart(ctx, {
type: 'doughnut',
data: {
labels: [
{% for i in income -%}
'Income: {{ categories[i.0] }}',
{% endfor -%}
{% for e in expenses -%}
'Expenses: {{ categories[e.0] }}',
{% endfor -%}
],
datasets: [{
label: 'Amount',
data: [
{% for i in income -%}
{{ i.1/100 }},
{% endfor -%}
{% for e in expenses -%}
{{ e.1/100 }},
{% endfor -%}
],
backgroundColor: [
{% for c in colors -%}
'#{{c}}',
{% endfor -%}
]
}]
}
})
</script>
</div>
{% endblock body %}

View file

@ -0,0 +1,36 @@
{% extends "base.html" %}
{% block title %}Create rule{% endblock title %}
{% block body %}
<form action="/classifiers/new_rule" method="post" class="flex flex-col">
<label class="grow">
Description
<input type="text" name="description" />
</label>
<label class="grow">
Regex
<input type="text" name="regex" />
</label>
<label class="grow">
Category
<select name="category">
<option></option>
{% for cat in categories %}
<option value={{cat.category_id}}>{{cat.name}}</option>
{% endfor %}
</select>
</label>
<button type="submit">Submit</button>
</form>
<style>
label {
width: 100%;
}
input {
width: 100%;
border: 1px solid black;
border-radius: 3px;
padding: 0.25rem;
margin: 0.25rem;
}
{% endblock body %}

View file

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Rule created</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="3;url=.." />
</head>
<body>
Rule created successfully
</body>
</html>

View file

@ -0,0 +1,704 @@
/*
! tailwindcss v3.4.3 | MIT License | https://tailwindcss.com
*/
/*
1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4)
2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116)
*/
*,
::before,
::after {
box-sizing: border-box;
/* 1 */
border-width: 0;
/* 2 */
border-style: solid;
/* 2 */
border-color: #e5e7eb;
/* 2 */
}
::before,
::after {
--tw-content: '';
}
/*
1. Use a consistent sensible line-height in all browsers.
2. Prevent adjustments of font size after orientation changes in iOS.
3. Use a more readable tab size.
4. Use the user's configured `sans` font-family by default.
5. Use the user's configured `sans` font-feature-settings by default.
6. Use the user's configured `sans` font-variation-settings by default.
7. Disable tap highlights on iOS
*/
html,
:host {
line-height: 1.5;
/* 1 */
-webkit-text-size-adjust: 100%;
/* 2 */
-moz-tab-size: 4;
/* 3 */
-o-tab-size: 4;
tab-size: 4;
/* 3 */
font-family: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
/* 4 */
font-feature-settings: normal;
/* 5 */
font-variation-settings: normal;
/* 6 */
-webkit-tap-highlight-color: transparent;
/* 7 */
}
/*
1. Remove the margin in all browsers.
2. Inherit line-height from `html` so users can set them as a class directly on the `html` element.
*/
body {
margin: 0;
/* 1 */
line-height: inherit;
/* 2 */
}
/*
1. Add the correct height in Firefox.
2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655)
3. Ensure horizontal rules are visible by default.
*/
hr {
height: 0;
/* 1 */
color: inherit;
/* 2 */
border-top-width: 1px;
/* 3 */
}
/*
Add the correct text decoration in Chrome, Edge, and Safari.
*/
abbr:where([title]) {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
}
/*
Remove the default font size and weight for headings.
*/
h1,
h2,
h3,
h4,
h5,
h6 {
font-size: inherit;
font-weight: inherit;
}
/*
Reset links to optimize for opt-in styling instead of opt-out.
*/
a {
color: inherit;
text-decoration: inherit;
}
/*
Add the correct font weight in Edge and Safari.
*/
b,
strong {
font-weight: bolder;
}
/*
1. Use the user's configured `mono` font-family by default.
2. Use the user's configured `mono` font-feature-settings by default.
3. Use the user's configured `mono` font-variation-settings by default.
4. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp,
pre {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
/* 1 */
font-feature-settings: normal;
/* 2 */
font-variation-settings: normal;
/* 3 */
font-size: 1em;
/* 4 */
}
/*
Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/*
Prevent `sub` and `sup` elements from affecting the line height in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/*
1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297)
2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016)
3. Remove gaps between table borders by default.
*/
table {
text-indent: 0;
/* 1 */
border-color: inherit;
/* 2 */
border-collapse: collapse;
/* 3 */
}
/*
1. Change the font styles in all browsers.
2. Remove the margin in Firefox and Safari.
3. Remove default padding in all browsers.
*/
button,
input,
optgroup,
select,
textarea {
font-family: inherit;
/* 1 */
font-feature-settings: inherit;
/* 1 */
font-variation-settings: inherit;
/* 1 */
font-size: 100%;
/* 1 */
font-weight: inherit;
/* 1 */
line-height: inherit;
/* 1 */
letter-spacing: inherit;
/* 1 */
color: inherit;
/* 1 */
margin: 0;
/* 2 */
padding: 0;
/* 3 */
}
/*
Remove the inheritance of text transform in Edge and Firefox.
*/
button,
select {
text-transform: none;
}
/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Remove default button styles.
*/
button,
input:where([type='button']),
input:where([type='reset']),
input:where([type='submit']) {
-webkit-appearance: button;
/* 1 */
background-color: transparent;
/* 2 */
background-image: none;
/* 2 */
}
/*
Use the modern Firefox focus style for all focusable elements.
*/
:-moz-focusring {
outline: auto;
}
/*
Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737)
*/
:-moz-ui-invalid {
box-shadow: none;
}
/*
Add the correct vertical alignment in Chrome and Firefox.
*/
progress {
vertical-align: baseline;
}
/*
Correct the cursor style of increment and decrement buttons in Safari.
*/
::-webkit-inner-spin-button,
::-webkit-outer-spin-button {
height: auto;
}
/*
1. Correct the odd appearance in Chrome and Safari.
2. Correct the outline style in Safari.
*/
[type='search'] {
-webkit-appearance: textfield;
/* 1 */
outline-offset: -2px;
/* 2 */
}
/*
Remove the inner padding in Chrome and Safari on macOS.
*/
::-webkit-search-decoration {
-webkit-appearance: none;
}
/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button;
/* 1 */
font: inherit;
/* 2 */
}
/*
Add the correct display in Chrome and Safari.
*/
summary {
display: list-item;
}
/*
Removes the default spacing and border for appropriate elements.
*/
blockquote,
dl,
dd,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
figure,
p,
pre {
margin: 0;
}
fieldset {
margin: 0;
padding: 0;
}
legend {
padding: 0;
}
ol,
ul,
menu {
list-style: none;
margin: 0;
padding: 0;
}
/*
Reset default styling for dialogs.
*/
dialog {
padding: 0;
}
/*
Prevent resizing textareas horizontally by default.
*/
textarea {
resize: vertical;
}
/*
1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300)
2. Set the default placeholder color to the user's configured gray 400 color.
*/
input::-moz-placeholder, textarea::-moz-placeholder {
opacity: 1;
/* 1 */
color: #9ca3af;
/* 2 */
}
input::placeholder,
textarea::placeholder {
opacity: 1;
/* 1 */
color: #9ca3af;
/* 2 */
}
/*
Set the default cursor for buttons.
*/
button,
[role="button"] {
cursor: pointer;
}
/*
Make sure disabled buttons don't get the pointer cursor.
*/
:disabled {
cursor: default;
}
/*
1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14)
2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210)
This can trigger a poorly considered lint error in some tools but is included by design.
*/
img,
svg,
video,
canvas,
audio,
iframe,
embed,
object {
display: block;
/* 1 */
vertical-align: middle;
/* 2 */
}
/*
Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14)
*/
img,
video {
max-width: 100%;
height: auto;
}
/* Make elements with the HTML hidden attribute stay hidden by default */
[hidden] {
display: none;
}
*, ::before, ::after {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
--tw-contain-size: ;
--tw-contain-layout: ;
--tw-contain-paint: ;
--tw-contain-style: ;
}
::backdrop {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
--tw-contain-size: ;
--tw-contain-layout: ;
--tw-contain-paint: ;
--tw-contain-style: ;
}
.container {
width: 100%;
}
@media (min-width: 640px) {
.container {
max-width: 640px;
}
}
@media (min-width: 768px) {
.container {
max-width: 768px;
}
}
@media (min-width: 1024px) {
.container {
max-width: 1024px;
}
}
@media (min-width: 1280px) {
.container {
max-width: 1280px;
}
}
@media (min-width: 1536px) {
.container {
max-width: 1536px;
}
}
.relative {
position: relative;
}
.mb-2 {
margin-bottom: 0.5rem;
}
.mb-4 {
margin-bottom: 1rem;
}
.mb-8 {
margin-bottom: 2rem;
}
.block {
display: block;
}
.flex {
display: flex;
}
.table {
display: table;
}
.h-full {
height: 100%;
}
.grow {
flex-grow: 1;
}
.flex-row {
flex-direction: row;
}
.flex-col {
flex-direction: column;
}
.justify-evenly {
justify-content: space-evenly;
}
.overflow-auto {
overflow: auto;
}
.border {
border-width: 1px;
}
.bg-stone-300 {
--tw-bg-opacity: 1;
background-color: rgb(214 211 209 / var(--tw-bg-opacity));
}
.p-2 {
padding: 0.5rem;
}
.p-4 {
padding: 1rem;
}
.text-lg {
font-size: 1.125rem;
line-height: 1.75rem;
}
.ars-input {
margin: 0.25rem;
margin-bottom: 0.75rem;
}
.ars-input input {
width: 100%;
padding: 0.25rem 0.75rem;
border: solid 1px #57534e;
border-radius: 0.5rem;
}
.ars-input select {
width: 100%;
padding: 0.25rem 0.75rem;
border: solid 1px #57534e;
border-radius: 0.5rem;
background-color: transparent;
}
.ars-button {
padding: 0.25rem 0.75rem;
border: solid 1px #57534e;
border-radius: 0.5rem;
}
.ars-button:hover {
background: #57534e77;
cursor: pointer;
}
.hover\:bg-stone-200:hover {
--tw-bg-opacity: 1;
background-color: rgb(231 229 228 / var(--tw-bg-opacity));
}
.hover\:bg-stone-400:hover {
--tw-bg-opacity: 1;
background-color: rgb(168 162 158 / var(--tw-bg-opacity));
}

View file

@ -0,0 +1,41 @@
{% extends "base.html" %}
{% block title %}Transaction {{tx_id}}{% endblock title %}
{% block body %}
<div class="mb-4">
<form method="post">
<div class="mb-2">
<label class="ars-input">
Name
<input type="text" name="description" value="{{tx.description}}" />
</label>
</div>
<div class="mb-2">
<label class="ars-input">
Date
<input type="text" name="date" value="{{tx.tx_date}}" />
</label>
</div>
<div class="mb-2">
<label class="ars-input">
Amount
<input type="text" name="amount" value="{{ tx.amount/100 }}" />
</label>
</div>
<div class="mb-2">
<label class="ars-input">
Category
<select style="width: 100%;" name="category">
<option></option>
{% for c in categories %}
<option {% if tx.category and c.category_id==tx.category %}selected{% endif %} value="{{ c.category_id }}">
{{ c.name }}
</option>
{% endfor %}
</select>
</label>
</div>
<div style="text-align: right;">
<input class="ars-button" type="submit" value="Update" />
</form>
</div>
{% endblock body %}

View file

@ -0,0 +1,13 @@
pub const INDEX: &str = include_str!("static/index.html");
pub const BASE: &str = include_str!("static/base.html");
pub const ACCOUNT_SUMMARY: &str = include_str!("static/account_summary.html");
pub const ACCOUNT_TXS: &str = include_str!("static/account_txs.html");
pub const ACCOUNT_ADD_TXS: &str = include_str!("static/accounts_add_txs.html");
pub const CATEGORIES_NEW: &str = include_str!("static/categories_new.html");
pub const CLASSIFIERS: &str = include_str!("static/classifiers.html");
pub const RULES_NEW: &str = include_str!("static/rules_new.html");
pub const RULES_NEW_SUCCESS: &str = include_str!("static/rules_new_success.html");
pub const TRANSACTION: &str = include_str!("static/transaction.html");
pub const STYLES: &str = include_str!("static/styles.css");
pub const CSV: &str = include_str!("static/csv.js");

View file

@ -1,5 +1,3 @@
use std::sync::Arc;
use accounters::models::users::User;
use axum::{
async_trait,
@ -12,7 +10,7 @@ use axum::{
};
use hyper::StatusCode;
use crate::AppState;
use crate::server::AppState;
pub struct AuthRedirect;