Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create expenses overview at index #3

Merged
merged 3 commits into from
Dec 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ edition = "2021"
askama = { version = "0.12.1", features = ["with-axum"] }
askama_axum = "0.4.0"
axum = "0.7.2"
chrono = { version = "0.4.31", features = ["serde"] }
serde = { version = "1.0.193", features = ["derive"] }
shuttle-axum = { version = "0.35.1", default-features = false, features = ["axum-0-7"] }
shuttle-runtime = "0.35.1"
shuttle-shared-db = { version = "0.35.1", features = ["postgres"] }
sqlx = { version = "0.7.3", features = ["runtime-tokio-rustls", "postgres"] }
strum = { version = "0.25.0", features = ["strum_macros", "derive"] }
tokio = { version = "1.35.1", features = ["full"] }
tower-http = { version = "0.5.0", features = ["fs"] }
tracing = "0.1.40"
6 changes: 0 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
# Contributing

## Create and activate a virtual environment to use pre-commit
```shell
virtualenv .
source bin/activate
```

## Install pre-commit
```shell
curl -LO https://github.com/pre-commit/pre-commit/releases/download/v3.6.0/pre-commit-3.6.0.pyz
Expand Down
11 changes: 10 additions & 1 deletion migrations/1_schema.sql
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
DROP TABLE IF EXISTS expenses;

DO $$ BEGIN
CREATE TYPE expense_type AS ENUM ('food', 'transport', 'health', 'education', 'entertainment', 'other');
EXCEPTION
WHEN duplicate_object THEN null;
END $$;

CREATE TABLE IF NOT EXISTS expenses (
id serial PRIMARY KEY,
amount real NOT NULL
description varchar(255) NOT NULL,
price real NOT NULL,
expense_type expense_type NOT NULL,
is_essencial boolean NOT NULL
);
58 changes: 58 additions & 0 deletions src/data.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use std::fmt::Display;

use chrono::Month;
use strum::EnumIter;

#[derive(EnumIter, Debug, PartialEq, Clone)]
pub enum Months {
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December,
}

impl Display for Months {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Months::January => write!(f, "January"),
Months::February => write!(f, "February"),
Months::March => write!(f, "March"),
Months::April => write!(f, "April"),
Months::May => write!(f, "May"),
Months::June => write!(f, "June"),
Months::July => write!(f, "July"),
Months::August => write!(f, "August"),
Months::September => write!(f, "September"),
Months::October => write!(f, "October"),
Months::November => write!(f, "November"),
Months::December => write!(f, "December"),
}
}
}

impl Months {
pub fn from_chrono_month(month: Month) -> Self {
match month {
Month::January => Months::January,
Month::February => Months::February,
Month::March => Months::March,
Month::April => Months::April,
Month::May => Months::May,
Month::June => Months::June,
Month::July => Months::July,
Month::August => Months::August,
Month::September => Months::September,
Month::October => Months::October,
Month::November => Months::November,
Month::December => Months::December,
}
}
}
23 changes: 23 additions & 0 deletions src/data_router.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use axum::routing::get;
use std::sync::Arc;

use askama_axum::IntoResponse;
use axum::{extract::State, http::StatusCode, Json, Router};

use crate::{schema::Expense, AppState};

pub fn data_router() -> Router<Arc<AppState>> {
Router::new().route("/api/expenses", get(get_expenses))
}

pub async fn get_expenses(
State(shared_state): State<Arc<AppState>>,
) -> Result<impl IntoResponse, impl IntoResponse> {
match sqlx::query_as::<_, Expense>("SELECT * FROM expenses")
.fetch_all(&shared_state.pool)
.await
{
Ok(expenses) => Ok((StatusCode::CREATED, Json(expenses))),
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
108 changes: 108 additions & 0 deletions src/hypermedia_router.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
use std::sync::Arc;

use askama_axum::IntoResponse;
use axum::extract::Path;
use axum::routing::get;
use axum::Router;
use axum::{extract::State, response::Html};

use crate::{
schema::Expense,
util::{EDITABLE_TABLE_ROW, TABLE_ROW},
AppState, ExpensesTemplate,
};

pub fn hypermedia_router() -> Router<Arc<AppState>> {
Router::new()
.route("/", get(expenses_index))
.route("/expenses", get(get_expenses))
.route("/expenses/:id/edit", get(edit_expense))
.route("/expenses/:id", get(get_expense).put(update_expense))
}

pub async fn expenses_index() -> impl IntoResponse {
ExpensesTemplate {
..Default::default()
}
}

pub async fn get_expenses(State(shared_state): State<Arc<AppState>>) -> impl IntoResponse {
// let expenses: Vec<Expense> = sqlx::query_as!(Expense, "SELECT * FROM expenses")
// .fetch_all(&shared_state.pool)
// .await
// .unwrap();
let expenses: Vec<Expense> = sqlx::query_as("SELECT * FROM expenses")
.fetch_all(&shared_state.pool)
.await
.unwrap();

Html(
expenses
.iter()
.map(|expense| {
format!(
TABLE_ROW!(),
expense.description,
expense.price,
expense.expense_type,
expense.is_essencial,
expense.id
)
})
.collect::<Vec<String>>()
.join("\n"),
)
}

pub async fn edit_expense(
Path(id): Path<i32>,
State(shared_state): State<Arc<AppState>>,
) -> impl IntoResponse {
let expense: Expense = sqlx::query_as("SELECT * FROM expenses WHERE id = $1")
.bind(id)
.fetch_one(&shared_state.pool)
.await
.unwrap();

Html(format!(
EDITABLE_TABLE_ROW!(),
expense.id,
expense.description,
expense.price,
expense.is_essencial,
expense.id,
expense.id
))
}

pub async fn get_expense(
Path(id): Path<i32>,
State(shared_state): State<Arc<AppState>>,
) -> impl IntoResponse {
let expense: Expense = sqlx::query_as("SELECT * FROM expenses WHERE id = $1")
.bind(id)
.fetch_one(&shared_state.pool)
.await
.unwrap();

Html(format!(
TABLE_ROW!(),
expense.description, expense.price, expense.expense_type, expense.is_essencial, expense.id
))
}

pub async fn update_expense(
Path(id): Path<i32>,
State(shared_state): State<Arc<AppState>>,
) -> impl IntoResponse {
let expense: Expense = sqlx::query_as("SELECT * FROM expenses WHERE id = $1")
.bind(id)
.fetch_one(&shared_state.pool)
.await
.unwrap();

Html(format!(
TABLE_ROW!(),
expense.description, expense.price, expense.expense_type, expense.is_essencial, expense.id
))
}
102 changes: 27 additions & 75 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,24 @@
mod data;
mod data_router;
mod hypermedia_router;
mod schema;
mod util;

use crate::data::{Months, MonthsIter};
use std::sync::Arc;

use askama::Template;
use axum::{
extract::{Path, State},
// http::StatusCode,
response::{Html, IntoResponse},
routing::get,
Router,
//Json,
};
use serde::Serialize;
use axum::Router;
use chrono::{Datelike, Month, Utc};
use shuttle_runtime::CustomError;
use sqlx::{FromRow, PgPool};
use sqlx::PgPool;
use strum::IntoEnumIterator;
use tower_http::services::ServeDir;

struct AppState {
pool: PgPool,
}

#[derive(FromRow, Serialize)]
struct Expense {
id: i32,
amount: f32,
}

#[shuttle_runtime::main]
async fn axum(#[shuttle_shared_db::Postgres] pool: PgPool) -> shuttle_axum::ShuttleAxum {
sqlx::migrate!()
Expand All @@ -33,71 +28,28 @@ async fn axum(#[shuttle_shared_db::Postgres] pool: PgPool) -> shuttle_axum::Shut

let shared_state = Arc::new(AppState { pool });
let router = Router::new()
.route("/", get(expenses_index))
.route("/expenses", get(get_expenses))
.route("/hello", get(hello_world))
.route("/greet/:name", get(greet))
//.route("/whatever", get(whatever))
.merge(hypermedia_router::hypermedia_router())
.merge(data_router::data_router())
.nest_service("/static", ServeDir::new("./css"))
.with_state(shared_state);

Ok(router.into())
}

//async fn whatever(
// State(shared_state): State<Arc<AppState>>,
//) -> Result<impl IntoResponse, impl IntoResponse> {
// match sqlx::query_as!(Expense, "SELECT * FROM expenses")
// .fetch_all(&shared_state.pool)
// .await
// {
// Ok(expenses) => Ok((StatusCode::CREATED, Json(expenses))),
// Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
// }
//}

async fn hello_world() -> &'static str {
"Hello, world!"
}

#[derive(Template)]
#[template(path = "hello.html")]
struct HelloTemplate {
name: String,
}

async fn greet(Path(name): Path<String>) -> impl IntoResponse {
HelloTemplate { name }
}

#[derive(Template)]
#[template(path = "expenses.html")]
struct ExpensesTemplate {}

async fn expenses_index() -> impl IntoResponse {
ExpensesTemplate {}
}

async fn get_expenses(State(shared_state): State<Arc<AppState>>) -> impl IntoResponse {
// let expenses: Vec<Expense> = sqlx::query_as!(Expense, "SELECT * FROM expenses")
// .fetch_all(&shared_state.pool)
// .await
// .unwrap();
let expenses: Vec<Expense> = sqlx::query_as("SELECT * FROM expenses")
.fetch_all(&shared_state.pool)
.await
.unwrap();

Html(
expenses
.iter()
.map(|expense| {
format!(
"<tr><td>{}</td><td>{}</td></tr>",
expense.id, expense.amount
)
})
.collect::<Vec<String>>()
.join("\n"),
)
struct ExpensesTemplate {
months: MonthsIter,
current_month: Months,
}

impl Default for ExpensesTemplate {
fn default() -> Self {
Self {
months: Months::iter(),
current_month: Months::from_chrono_month(
Month::try_from(u8::try_from(Utc::now().month()).unwrap()).unwrap(),
),
}
}
}
Loading