Basic giftexchange view funtionality

This commit is contained in:
Chris Jean-Marie 2024-11-05 21:35:40 +00:00
parent a590bf114a
commit f362fa8c93
5 changed files with 264 additions and 14 deletions

View File

@ -3,11 +3,12 @@ CREATE TABLE
`gift_exchange` ( `gift_exchange` (
`id` integer not null primary key autoincrement, `id` integer not null primary key autoincrement,
`created_at` INTEGER not null default CURRENT_TIMESTAMP, `created_at` INTEGER not null default CURRENT_TIMESTAMP,
`created_by` ineger null, `created_by` integer not null default 0,
`updated_at` INTEGER null default CURRENT_TIMESTAMP, `updated_at` INTEGER not null default CURRENT_TIMESTAMP,
`updated_by` integer null, `updated_by` integer not null default 0,
`name` varchar(255) null, `name` varchar(255) not null,
`exchange_date` INTEGER null, `exchange_date` INTEGER not null,
`status` INTEGER not null default 0,
unique (`id`) unique (`id`)
); );
@ -15,12 +16,12 @@ CREATE TABLE
`gift_exchange_participants` ( `gift_exchange_participants` (
`id` integer not null primary key autoincrement, `id` integer not null primary key autoincrement,
`created_at` INTEGER not null default CURRENT_TIMESTAMP, `created_at` INTEGER not null default CURRENT_TIMESTAMP,
`created_by` ineger null, `created_by` integer not null default 0,
`updated_at` INTEGER null default CURRENT_TIMESTAMP, `updated_at` INTEGER not null default CURRENT_TIMESTAMP,
`updated_by` integer null, `updated_by` integer not null default 0,
`exchange_id` INTEGER not null, `exchange_id` INTEGER not null,
`participant_id` INTEGER not null, `participant_id` INTEGER not null,
`gifter_id` INTEGER null, `gifter_id` INTEGER not null,
unique (`id`) unique (`id`)
); );

View File

@ -2,6 +2,7 @@ use std::net::SocketAddr;
use axum::{ use axum::{
middleware, routing::{get, get_service}, Extension, Router middleware, routing::{get, get_service}, Extension, Router
}; };
use secret_gift_exchange::{giftexchange, giftexchanges};
use sqlx::{sqlite::SqlitePoolOptions, SqlitePool}; use sqlx::{sqlite::SqlitePoolOptions, SqlitePool};
use sqlx::migrate::Migrator; use sqlx::migrate::Migrator;
use tower_http::services::ServeDir; use tower_http::services::ServeDir;
@ -13,6 +14,7 @@ mod routes;
mod user; mod user;
mod wishlist; mod wishlist;
mod email; mod email;
mod secret_gift_exchange;
use error_handling::AppError; use error_handling::AppError;
use middlewares::inject_user_data; use middlewares::inject_user_data;
@ -62,6 +64,8 @@ async fn main() {
.route("/userwishlist/add/:user_id", get(user_wishlist_add).post(user_wishlist_add_item)) .route("/userwishlist/add/:user_id", get(user_wishlist_add).post(user_wishlist_add_item))
.route("/userwishlist/bought/:user_id", get(user_wishlist_bought_item)) .route("/userwishlist/bought/:user_id", get(user_wishlist_bought_item))
.route("/userwishlist/received/:user_id", get(user_wishlist_received_item)) .route("/userwishlist/received/:user_id", get(user_wishlist_received_item))
.route("/giftexchanges", get(giftexchanges))
.route("/giftexchange/:giftexchange_id", get(giftexchange))
.nest_service("/assets", ServeDir::new("templates/assets") .nest_service("/assets", ServeDir::new("templates/assets")
.fallback(get_service(ServeDir::new("templates/assets")))) .fallback(get_service(ServeDir::new("templates/assets"))))
.route("/", get(index)) .route("/", get(index))

View File

@ -1,3 +1,20 @@
use askama::Template;
use askama_axum::{IntoResponse, Response};
use axum::{
extract::{Path, State},
response::Redirect,
Extension,
};
use axum_extra::response::Html;
use http::StatusCode;
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, SqlitePool};
use crate::{
middlewares::is_authorized,
user::{get_user_roles_display, UserData},
};
/// Select participants from user list /// Select participants from user list
/// create group id for exchange /// create group id for exchange
/// allow user to only see their recipient but whole list of participants /// allow user to only see their recipient but whole list of participants
@ -37,6 +54,153 @@
/// ///
/// API - select gifters /// API - select gifters
pub fn select_gifters() { struct HtmlTemplate<T>(T);
impl<T> IntoResponse for HtmlTemplate<T>
where
T: Template,
{
fn into_response(self) -> Response {
match self.0.render() {
Ok(html) => Html(html).into_response(),
Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to render template. Error: {}", err),
)
.into_response(),
}
}
} }
#[derive(Default, Clone, Debug, Serialize, Deserialize, FromRow)]
struct GiftExchange {
id: i64,
created_at: i64,
created_by: i64,
updated_at: i64,
updated_by: i64,
name: String,
exchange_date: i64,
status: i64,
}
#[derive(Template)]
#[template(path = "giftexchanges.html")]
struct GiftExchangesTemplate {
logged_in: bool,
name: String,
user_roles: Vec<crate::user::UserRolesDisplay>,
giftexchanges: Vec<GiftExchange>,
}
pub async fn giftexchanges(
Extension(user_data): Extension<Option<UserData>>,
State(db_pool): State<SqlitePool>,
) -> impl IntoResponse {
let user_name = user_data.as_ref().map(|s| s.name.clone());
let logged_in = user_name.is_some();
let name = user_name.unwrap_or_default();
let giftexchanges = sqlx::query_as::<_, GiftExchange>("SELECT * FROM gift_exchange")
.fetch_all(&db_pool)
.await
.unwrap();
let userid = user_data.as_ref().map(|s| s.id.clone()).unwrap_or_default();
if is_authorized("/giftexchange", user_data, db_pool.clone()).await {
// Get user roles
let user_roles = get_user_roles_display(userid, &db_pool.clone()).await;
let template = GiftExchangesTemplate {
logged_in,
name,
user_roles,
giftexchanges,
};
HtmlTemplate(template).into_response()
} else {
Redirect::to("/").into_response()
}
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, FromRow)]
struct GiftExchangeParticipant {
id: i64,
created_at: i64,
created_by: i64,
updated_at: i64,
updated_by: i64,
exchange_id: i64,
participant_id: i64,
gifter_id: i64,
}
#[derive(Template)]
#[template(path = "giftexchange.html")]
struct GiftExchangeTemplate {
logged_in: bool,
name: String,
user_roles: Vec<crate::user::UserRolesDisplay>,
giftexchange: GiftExchange,
participants: Vec<GiftExchangeParticipant>,
non_participants: Vec<UserData>,
}
pub async fn giftexchange(
Path(exchange_id): Path<i64>,
Extension(user_data): Extension<Option<UserData>>,
State(db_pool): State<SqlitePool>,
) -> impl IntoResponse {
let user_name = user_data.as_ref().map(|s| s.name.clone());
let logged_in = user_name.is_some();
let name = user_name.unwrap_or_default();
let userid = user_data.as_ref().map(|s| s.id.clone()).unwrap_or_default();
if is_authorized("/giftexchange", user_data, db_pool.clone()).await {
// Get user roles
let user_roles = get_user_roles_display(userid, &db_pool.clone()).await;
// Get gift exchange
let giftexchange = match sqlx::query_as!(GiftExchange, "SELECT * FROM gift_exchange WHERE id = ?", exchange_id)
.fetch_one(&db_pool)
.await {
Ok(giftexchange) => giftexchange,
Err(_) => {
GiftExchange::default()
}};
// Get participants
let participants = sqlx::query_as::<_, GiftExchangeParticipant>(
"SELECT * FROM gift_exchange_participants WHERE exchange_id = ?",
)
.bind(exchange_id)
.fetch_all(&db_pool)
.await
.unwrap();
// Get non participants
let non_participants = sqlx::query_as::<_, UserData>(
"select * from users where users.id not in (select participant_id from gift_exchange_participants where exchange_id = ?)",
)
.bind(exchange_id)
.fetch_all(&db_pool)
.await
.unwrap();
let template = GiftExchangeTemplate {
logged_in,
name,
user_roles,
giftexchange,
participants,
non_participants,
};
HtmlTemplate(template).into_response()
} else {
Redirect::to("/").into_response()
}
}
pub fn select_gifters() {}

View File

@ -0,0 +1,52 @@
{% extends "authorized.html" %}
{% block title %}Gift Exchange{% endblock %}
{% block center %}
<div class="row">
<div class="btn-toolbar" role="toolbar">
<a role="button" class="btn btn-primary" href="/giftexchange/{{ giftexchange.id }}">Save</a>
</div>
</div>
<div class="row">
Exchange Name: <input id="name" name="name" type="text" value="{{ giftexchange.name }}" required>
</div>
<div class="row">
<div class="col">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th data-sortable="true" data-field="name"scope="col">Name</th>
</tr>
</thead>
<tbody>
{% for participant in non_participants %}
<tr>
<td>{{ participant.name }}</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="col">
<div class="btn-group-vertical" role="group">
<button type="button" class="btn btn-primary">Add</button>
<button type="button" class="btn btn-primary">Remove</button>
</div>
</div>
<div class="col">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th data-sortable="true" data-field="name" scope="col">Name</th>
</tr>
</thead>
<tbody>
{% for participant in participants %}
<tr>
<td>{{ participant.participant_id }}</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock center %}

View File

@ -0,0 +1,29 @@
{% extends "authorized.html" %}
{% block title %}Gift Exchanges{% endblock %}
{% block center %}
<div class="row">
<div class="btn-toolbar" role="toolbar">
<a role="button" class="btn btn-primary" href="/giftexchange/0">Add</a>
</div>
</div>
<div class="row">
<table data-toggle="table" class="table table-striped table-bordered">
<thead>
<tr>
<th data-sortable="true" data-field="name" scope="col">Name</th>
<th data-sortable="true" data-field="exchange_date" scope="col">Date</th>
<th data-field="status" scope="col">Status</th>
</tr>
</thead>
<tbody>
{% for giftexchange in giftexchanges %}
<tr>
<td><a href="/giftexchange/{{ giftexchange.id }}">{{ giftexchange.name }}</a></td>
<td>{{ giftexchange.exchange_date }}</td>
<td>{{ giftexchange.status }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock center %}