feat: Introduce event management with new database entities, server functions, and UI components.
This commit is contained in:
parent
572827e10b
commit
83db04a187
5
.vscode/settings.json
vendored
Normal file
5
.vscode/settings.json
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"rust-analyzer.cargo.features": [
|
||||
"server"
|
||||
]
|
||||
}
|
||||
1
Cargo.lock
generated
1
Cargo.lock
generated
@ -6751,6 +6751,7 @@ dependencies = [
|
||||
"axum",
|
||||
"dioxus",
|
||||
"dotenvy",
|
||||
"rand 0.8.5",
|
||||
"sea-orm",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@ -20,6 +20,7 @@ dotenvy = { version = "0.15.7", optional = true }
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = "1.0.145"
|
||||
tower-sessions = { version = "0.14.0", features = ["signed"], optional = true }
|
||||
rand = { version = "0.8", optional = true }
|
||||
|
||||
[features]
|
||||
default = ["web"]
|
||||
@ -34,4 +35,5 @@ server = [
|
||||
"dep:sea-orm",
|
||||
"dep:dotenvy",
|
||||
"dep:tower-sessions",
|
||||
"dep:rand",
|
||||
]
|
||||
|
||||
@ -12,10 +12,16 @@
|
||||
--color-green-600: oklch(62.7% 0.194 149.214);
|
||||
--color-blue-500: oklch(62.3% 0.214 259.815);
|
||||
--color-blue-600: oklch(54.6% 0.245 262.881);
|
||||
--color-purple-500: oklch(62.7% 0.265 303.9);
|
||||
--color-purple-600: oklch(55.8% 0.288 302.321);
|
||||
--color-gray-100: oklch(96.7% 0.003 264.542);
|
||||
--color-gray-300: oklch(87.2% 0.01 258.338);
|
||||
--color-gray-500: oklch(55.1% 0.027 264.364);
|
||||
--color-gray-800: oklch(27.8% 0.033 256.848);
|
||||
--color-white: #fff;
|
||||
--spacing: 0.25rem;
|
||||
--text-xl: 1.25rem;
|
||||
--text-xl--line-height: calc(1.75 / 1.25);
|
||||
--text-2xl: 1.5rem;
|
||||
--text-2xl--line-height: calc(2 / 1.5);
|
||||
--font-weight-bold: 700;
|
||||
@ -193,6 +199,9 @@
|
||||
max-width: 96rem;
|
||||
}
|
||||
}
|
||||
.mb-2 {
|
||||
margin-bottom: calc(var(--spacing) * 2);
|
||||
}
|
||||
.mb-4 {
|
||||
margin-bottom: calc(var(--spacing) * 4);
|
||||
}
|
||||
@ -208,18 +217,33 @@
|
||||
.w-64 {
|
||||
width: calc(var(--spacing) * 64);
|
||||
}
|
||||
.w-96 {
|
||||
width: calc(var(--spacing) * 96);
|
||||
}
|
||||
.border-collapse {
|
||||
border-collapse: collapse;
|
||||
}
|
||||
.transform {
|
||||
transform: var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,);
|
||||
}
|
||||
.resize {
|
||||
resize: both;
|
||||
}
|
||||
.flex-col {
|
||||
flex-direction: column;
|
||||
}
|
||||
.items-center {
|
||||
align-items: center;
|
||||
}
|
||||
.justify-between {
|
||||
justify-content: space-between;
|
||||
}
|
||||
.justify-center {
|
||||
justify-content: center;
|
||||
}
|
||||
.gap-2 {
|
||||
gap: calc(var(--spacing) * 2);
|
||||
}
|
||||
.gap-4 {
|
||||
gap: calc(var(--spacing) * 4);
|
||||
}
|
||||
@ -230,6 +254,10 @@
|
||||
border-style: var(--tw-border-style);
|
||||
border-width: 1px;
|
||||
}
|
||||
.border-b {
|
||||
border-bottom-style: var(--tw-border-style);
|
||||
border-bottom-width: 1px;
|
||||
}
|
||||
.bg-blue-500 {
|
||||
background-color: var(--color-blue-500);
|
||||
}
|
||||
@ -239,6 +267,9 @@
|
||||
.bg-green-500 {
|
||||
background-color: var(--color-green-500);
|
||||
}
|
||||
.bg-purple-500 {
|
||||
background-color: var(--color-purple-500);
|
||||
}
|
||||
.p-2 {
|
||||
padding: calc(var(--spacing) * 2);
|
||||
}
|
||||
@ -252,10 +283,17 @@
|
||||
font-size: var(--text-2xl);
|
||||
line-height: var(--tw-leading, var(--text-2xl--line-height));
|
||||
}
|
||||
.text-xl {
|
||||
font-size: var(--text-xl);
|
||||
line-height: var(--tw-leading, var(--text-xl--line-height));
|
||||
}
|
||||
.font-bold {
|
||||
--tw-font-weight: var(--font-weight-bold);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
.text-gray-500 {
|
||||
color: var(--color-gray-500);
|
||||
}
|
||||
.text-green-500 {
|
||||
color: var(--color-green-500);
|
||||
}
|
||||
@ -265,6 +303,13 @@
|
||||
.text-white {
|
||||
color: var(--color-white);
|
||||
}
|
||||
.underline {
|
||||
text-decoration-line: underline;
|
||||
}
|
||||
.outline {
|
||||
outline-style: var(--tw-outline-style);
|
||||
outline-width: 1px;
|
||||
}
|
||||
.hover\:bg-blue-600 {
|
||||
&:hover {
|
||||
@media (hover: hover) {
|
||||
@ -272,6 +317,13 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
.hover\:bg-gray-100 {
|
||||
&:hover {
|
||||
@media (hover: hover) {
|
||||
background-color: var(--color-gray-100);
|
||||
}
|
||||
}
|
||||
}
|
||||
.hover\:bg-green-600 {
|
||||
&:hover {
|
||||
@media (hover: hover) {
|
||||
@ -279,6 +331,13 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
.hover\:bg-purple-600 {
|
||||
&:hover {
|
||||
@media (hover: hover) {
|
||||
background-color: var(--color-purple-600);
|
||||
}
|
||||
}
|
||||
}
|
||||
.hover\:text-gray-300 {
|
||||
&:hover {
|
||||
@media (hover: hover) {
|
||||
@ -316,6 +375,11 @@
|
||||
syntax: "*";
|
||||
inherits: false;
|
||||
}
|
||||
@property --tw-outline-style {
|
||||
syntax: "*";
|
||||
inherits: false;
|
||||
initial-value: solid;
|
||||
}
|
||||
@layer properties {
|
||||
@supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b)))) {
|
||||
*, ::before, ::after, ::backdrop {
|
||||
@ -326,6 +390,7 @@
|
||||
--tw-skew-y: initial;
|
||||
--tw-border-style: solid;
|
||||
--tw-font-weight: initial;
|
||||
--tw-outline-style: solid;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
#[cfg(feature = "server")]
|
||||
use crate::db::{self, Entity as User};
|
||||
use crate::db::{self, users::Entity as User};
|
||||
#[cfg(feature = "server")]
|
||||
use argon2::{
|
||||
password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
|
||||
@ -36,7 +36,7 @@ pub async fn register(username: String, password: String) -> Result<String, Serv
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?
|
||||
.to_string();
|
||||
|
||||
let new_user = db::ActiveModel {
|
||||
let new_user = db::users::ActiveModel {
|
||||
username: Set(username),
|
||||
password: Set(password_hash),
|
||||
..Default::default()
|
||||
@ -57,7 +57,7 @@ pub async fn login(username: String, password: String) -> Result<String, ServerF
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
|
||||
let user = User::find()
|
||||
.filter(db::Column::Username.eq(username))
|
||||
.filter(db::users::Column::Username.eq(username))
|
||||
.one(&db)
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?
|
||||
|
||||
34
src/db.rs
34
src/db.rs
@ -1,34 +0,0 @@
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "users")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
#[sea_orm(unique)]
|
||||
pub username: String,
|
||||
pub password: String, // Argon2 hashed
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
use sea_orm::{Database, DatabaseConnection, DbErr, Schema};
|
||||
|
||||
pub async fn establish_connection() -> Result<DatabaseConnection, DbErr> {
|
||||
let database_url =
|
||||
std::env::var("DATABASE_URL").unwrap_or("sqlite://wichtl.db?mode=rwc".to_owned());
|
||||
let db = Database::connect(&database_url).await?;
|
||||
|
||||
// Create table if not exists
|
||||
let builder = db.get_database_backend();
|
||||
let schema = Schema::new(builder);
|
||||
let create_table_op = schema.create_table_from_entity(Entity);
|
||||
|
||||
let _ = db.execute(builder.build(&create_table_op)).await;
|
||||
|
||||
Ok(db)
|
||||
}
|
||||
48
src/db/assignments.rs
Normal file
48
src/db/assignments.rs
Normal file
@ -0,0 +1,48 @@
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "assignments")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
pub event_id: i32,
|
||||
pub giver_id: i32,
|
||||
pub receiver_id: i32,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(
|
||||
belongs_to = "super::events::Entity",
|
||||
from = "Column::EventId",
|
||||
to = "super::events::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Event,
|
||||
#[sea_orm(
|
||||
belongs_to = "super::participants::Entity",
|
||||
from = "Column::GiverId",
|
||||
to = "super::participants::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Giver,
|
||||
#[sea_orm(
|
||||
belongs_to = "super::participants::Entity",
|
||||
from = "Column::ReceiverId",
|
||||
to = "super::participants::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Receiver,
|
||||
}
|
||||
|
||||
impl Related<super::events::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Event.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
49
src/db/events.rs
Normal file
49
src/db/events.rs
Normal file
@ -0,0 +1,49 @@
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "events")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
pub name: String,
|
||||
pub date: String,
|
||||
pub budget: String,
|
||||
pub creator_id: i32,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(
|
||||
belongs_to = "super::users::Entity",
|
||||
from = "Column::CreatorId",
|
||||
to = "super::users::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
User,
|
||||
#[sea_orm(has_many = "super::participants::Entity")]
|
||||
Participants,
|
||||
#[sea_orm(has_many = "super::assignments::Entity")]
|
||||
Assignments,
|
||||
}
|
||||
|
||||
impl Related<super::users::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::User.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::participants::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Participants.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::assignments::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Assignments.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
33
src/db/exclusions.rs
Normal file
33
src/db/exclusions.rs
Normal file
@ -0,0 +1,33 @@
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "exclusions")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub participant_id: i32,
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub excluded_participant_id: i32,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(
|
||||
belongs_to = "super::participants::Entity",
|
||||
from = "Column::ParticipantId",
|
||||
to = "super::participants::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Participant,
|
||||
#[sea_orm(
|
||||
belongs_to = "super::participants::Entity",
|
||||
from = "Column::ExcludedParticipantId",
|
||||
to = "super::participants::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
ExcludedParticipant,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
35
src/db/mod.rs
Normal file
35
src/db/mod.rs
Normal file
@ -0,0 +1,35 @@
|
||||
pub mod assignments;
|
||||
pub mod events;
|
||||
pub mod exclusions;
|
||||
pub mod participants;
|
||||
pub mod users;
|
||||
|
||||
use sea_orm::{ConnectionTrait, Database, DatabaseConnection, DbErr, Schema};
|
||||
|
||||
pub async fn establish_connection() -> Result<DatabaseConnection, DbErr> {
|
||||
let database_url =
|
||||
std::env::var("DATABASE_URL").unwrap_or("sqlite://wichtl.db?mode=rwc".to_owned());
|
||||
let db = Database::connect(&database_url).await?;
|
||||
|
||||
// Create tables if not exist
|
||||
let builder = db.get_database_backend();
|
||||
let schema = Schema::new(builder);
|
||||
|
||||
let _ = db
|
||||
.execute(builder.build(&schema.create_table_from_entity(users::Entity)))
|
||||
.await;
|
||||
let _ = db
|
||||
.execute(builder.build(&schema.create_table_from_entity(events::Entity)))
|
||||
.await;
|
||||
let _ = db
|
||||
.execute(builder.build(&schema.create_table_from_entity(participants::Entity)))
|
||||
.await;
|
||||
let _ = db
|
||||
.execute(builder.build(&schema.create_table_from_entity(exclusions::Entity)))
|
||||
.await;
|
||||
let _ = db
|
||||
.execute(builder.build(&schema.create_table_from_entity(assignments::Entity)))
|
||||
.await;
|
||||
|
||||
Ok(db)
|
||||
}
|
||||
47
src/db/participants.rs
Normal file
47
src/db/participants.rs
Normal file
@ -0,0 +1,47 @@
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "participants")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
pub event_id: i32,
|
||||
pub name: String,
|
||||
pub email: Option<String>,
|
||||
pub user_id: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(
|
||||
belongs_to = "super::events::Entity",
|
||||
from = "Column::EventId",
|
||||
to = "super::events::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Event,
|
||||
#[sea_orm(
|
||||
belongs_to = "super::users::Entity",
|
||||
from = "Column::UserId",
|
||||
to = "super::users::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "SetNull"
|
||||
)]
|
||||
User,
|
||||
}
|
||||
|
||||
impl Related<super::events::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Event.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::users::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::User.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
26
src/db/users.rs
Normal file
26
src/db/users.rs
Normal file
@ -0,0 +1,26 @@
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "users")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
#[sea_orm(unique)]
|
||||
pub username: String,
|
||||
pub password: String, // Argon2 hashed
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(has_many = "super::events::Entity")]
|
||||
Events,
|
||||
}
|
||||
|
||||
impl Related<super::events::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Events.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
166
src/main.rs
166
src/main.rs
@ -2,6 +2,7 @@ use dioxus::prelude::*;
|
||||
mod auth;
|
||||
#[cfg(feature = "server")]
|
||||
mod db;
|
||||
mod server_fns;
|
||||
|
||||
#[derive(Debug, Clone, Routable, PartialEq)]
|
||||
#[rustfmt::skip]
|
||||
@ -13,6 +14,12 @@ enum Route {
|
||||
Login {},
|
||||
#[route("/register")]
|
||||
Register {},
|
||||
#[route("/dashboard")]
|
||||
Dashboard {},
|
||||
#[route("/create-event")]
|
||||
CreateEvent {},
|
||||
#[route("/event/:id")]
|
||||
EventPage { id: i32 },
|
||||
}
|
||||
|
||||
const MAIN_CSS: Asset = asset!("/assets/main.css");
|
||||
@ -94,6 +101,10 @@ fn Navbar() -> Element {
|
||||
"Home"
|
||||
}
|
||||
if let Some(user) = user_state() {
|
||||
Link {
|
||||
to: Route::Dashboard {},
|
||||
"Dashboard"
|
||||
}
|
||||
span { "Welcome, {user.username}!" }
|
||||
button {
|
||||
class: "hover:text-gray-300",
|
||||
@ -226,3 +237,158 @@ fn Register() -> Element {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn Dashboard() -> Element {
|
||||
let events = use_resource(move || async move { server_fns::get_my_events().await });
|
||||
|
||||
rsx! {
|
||||
div {
|
||||
class: "flex flex-col items-center min-h-screen py-2",
|
||||
h1 { class: "text-2xl font-bold mb-4", "My Events" }
|
||||
Link {
|
||||
to: Route::CreateEvent {},
|
||||
class: "bg-blue-500 text-white p-2 rounded hover:bg-blue-600 mb-4",
|
||||
"Create New Event"
|
||||
}
|
||||
match &*events.read_unchecked() {
|
||||
Some(Ok(list)) => rsx! {
|
||||
div {
|
||||
class: "flex flex-col gap-4 w-96",
|
||||
for event in list {
|
||||
Link {
|
||||
to: Route::EventPage { id: event.id },
|
||||
class: "border p-4 rounded hover:bg-gray-100 flex justify-between items-center",
|
||||
span { class: "font-bold", "{event.name}" }
|
||||
span { class: "text-gray-500", "{event.date}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
Some(Err(e)) => rsx! { p { class: "text-red-500", "Error: {e}" } },
|
||||
None => rsx! { p { "Loading..." } },
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn CreateEvent() -> Element {
|
||||
let mut name = use_signal(|| String::new());
|
||||
let mut date = use_signal(|| String::new());
|
||||
let mut budget = use_signal(|| String::new());
|
||||
let mut error = use_signal(|| String::new());
|
||||
let navigator = use_navigator();
|
||||
|
||||
rsx! {
|
||||
div {
|
||||
class: "flex flex-col items-center justify-center min-h-screen py-2",
|
||||
h1 { class: "text-2xl font-bold mb-4", "Create Event" }
|
||||
div {
|
||||
class: "flex flex-col gap-4 w-64",
|
||||
input {
|
||||
class: "border p-2 rounded",
|
||||
placeholder: "Event Name",
|
||||
value: "{name}",
|
||||
oninput: move |e| name.set(e.value())
|
||||
}
|
||||
input {
|
||||
class: "border p-2 rounded",
|
||||
type: "date",
|
||||
value: "{date}",
|
||||
oninput: move |e| date.set(e.value())
|
||||
}
|
||||
input {
|
||||
class: "border p-2 rounded",
|
||||
placeholder: "Budget (e.g. 20 EUR)",
|
||||
value: "{budget}",
|
||||
oninput: move |e| budget.set(e.value())
|
||||
}
|
||||
button {
|
||||
class: "bg-green-500 text-white p-2 rounded hover:bg-green-600",
|
||||
onclick: move |_| async move {
|
||||
match server_fns::create_event(name(), date(), budget()).await {
|
||||
Ok(_) => { navigator.push(Route::Dashboard {}); },
|
||||
Err(e) => error.set(e.to_string()),
|
||||
}
|
||||
},
|
||||
"Create"
|
||||
}
|
||||
if !error().is_empty() {
|
||||
p { class: "text-red-500", "{error}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn EventPage(id: i32) -> Element {
|
||||
let mut participants =
|
||||
use_resource(move || async move { server_fns::get_participants(id).await });
|
||||
let mut new_participant_name = use_signal(|| String::new());
|
||||
let mut new_participant_email = use_signal(|| String::new());
|
||||
|
||||
rsx! {
|
||||
div {
|
||||
class: "flex flex-col items-center min-h-screen py-2",
|
||||
h1 { class: "text-2xl font-bold mb-4", "Event Details" }
|
||||
|
||||
// Add Participant Form
|
||||
div {
|
||||
class: "flex gap-2 mb-4",
|
||||
input {
|
||||
class: "border p-2 rounded",
|
||||
placeholder: "Name",
|
||||
value: "{new_participant_name}",
|
||||
oninput: move |e| new_participant_name.set(e.value())
|
||||
}
|
||||
input {
|
||||
class: "border p-2 rounded",
|
||||
placeholder: "Email (Optional)",
|
||||
value: "{new_participant_email}",
|
||||
oninput: move |e| new_participant_email.set(e.value())
|
||||
}
|
||||
button {
|
||||
class: "bg-blue-500 text-white p-2 rounded",
|
||||
onclick: move |_| async move {
|
||||
let email = if new_participant_email().is_empty() { None } else { Some(new_participant_email()) };
|
||||
if server_fns::add_participant(id, new_participant_name(), email).await.is_ok() {
|
||||
participants.restart();
|
||||
new_participant_name.set("".to_string());
|
||||
new_participant_email.set("".to_string());
|
||||
}
|
||||
},
|
||||
"Add"
|
||||
}
|
||||
}
|
||||
|
||||
// Participants List
|
||||
h2 { class: "text-xl font-bold mb-2", "Participants" }
|
||||
match &*participants.read_unchecked() {
|
||||
Some(Ok(list)) => rsx! {
|
||||
ul {
|
||||
class: "w-96 mb-4",
|
||||
for p in list {
|
||||
li { class: "border-b p-2", "{p.name} ({p.email.clone().unwrap_or_default()})" }
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => rsx! { "Loading..." }
|
||||
}
|
||||
|
||||
// Draw Button
|
||||
button {
|
||||
class: "bg-purple-500 text-white p-2 rounded hover:bg-purple-600",
|
||||
onclick: move |_| async move {
|
||||
if let Err(e) = server_fns::draw_names(id).await {
|
||||
println!("Error drawing names: {}", e);
|
||||
} else {
|
||||
println!("Names drawn!");
|
||||
}
|
||||
},
|
||||
"Draw Names"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
297
src/server_fns.rs
Normal file
297
src/server_fns.rs
Normal file
@ -0,0 +1,297 @@
|
||||
#[cfg(feature = "server")]
|
||||
use crate::db::{self, assignments, events, exclusions, participants};
|
||||
use dioxus::prelude::dioxus_fullstack;
|
||||
use dioxus::prelude::server;
|
||||
use dioxus::prelude::ServerFnError;
|
||||
use dioxus::prelude::*;
|
||||
#[cfg(feature = "server")]
|
||||
use dioxus::prelude::*;
|
||||
#[cfg(feature = "server")]
|
||||
use sea_orm::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct EventSafe {
|
||||
pub id: i32,
|
||||
pub name: String,
|
||||
pub date: String,
|
||||
pub budget: String,
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub async fn create_event(
|
||||
name: String,
|
||||
date: String,
|
||||
budget: String,
|
||||
) -> Result<EventSafe, ServerFnError> {
|
||||
let session: tower_sessions::Session = FullstackContext::extract().await?;
|
||||
let user_id: i32 = session
|
||||
.get("user_id")
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?
|
||||
.ok_or(ServerFnError::new("Not logged in"))?;
|
||||
|
||||
let db = db::establish_connection()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
|
||||
let new_event = events::ActiveModel {
|
||||
name: Set(name),
|
||||
date: Set(date),
|
||||
budget: Set(budget),
|
||||
creator_id: Set(user_id),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let event = new_event
|
||||
.insert(&db)
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
|
||||
Ok(EventSafe {
|
||||
id: event.id,
|
||||
name: event.name,
|
||||
date: event.date,
|
||||
budget: event.budget,
|
||||
})
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub async fn get_my_events() -> Result<Vec<EventSafe>, ServerFnError> {
|
||||
let session: tower_sessions::Session = FullstackContext::extract().await?;
|
||||
let user_id: i32 = session
|
||||
.get("user_id")
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?
|
||||
.ok_or(ServerFnError::new("Not logged in"))?;
|
||||
|
||||
let db = db::establish_connection()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
|
||||
let events = events::Entity::find()
|
||||
.filter(events::Column::CreatorId.eq(user_id))
|
||||
.all(&db)
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
|
||||
Ok(events
|
||||
.into_iter()
|
||||
.map(|e| EventSafe {
|
||||
id: e.id,
|
||||
name: e.name,
|
||||
date: e.date,
|
||||
budget: e.budget,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ParticipantSafe {
|
||||
pub id: i32,
|
||||
pub name: String,
|
||||
pub email: Option<String>,
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub async fn add_participant(
|
||||
event_id: i32,
|
||||
name: String,
|
||||
email: Option<String>,
|
||||
) -> Result<ParticipantSafe, ServerFnError> {
|
||||
// Verify ownership
|
||||
let session: tower_sessions::Session = FullstackContext::extract().await?;
|
||||
let user_id: i32 = session
|
||||
.get("user_id")
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?
|
||||
.ok_or(ServerFnError::new("Not logged in"))?;
|
||||
|
||||
let db = db::establish_connection()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
|
||||
let event = events::Entity::find_by_id(event_id)
|
||||
.one(&db)
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?
|
||||
.ok_or(ServerFnError::new("Event not found"))?;
|
||||
|
||||
if event.creator_id != user_id {
|
||||
return Err(ServerFnError::new("Not authorized"));
|
||||
}
|
||||
|
||||
let new_participant = participants::ActiveModel {
|
||||
event_id: Set(event_id),
|
||||
name: Set(name),
|
||||
email: Set(email),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let participant = new_participant
|
||||
.insert(&db)
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
|
||||
Ok(ParticipantSafe {
|
||||
id: participant.id,
|
||||
name: participant.name,
|
||||
email: participant.email,
|
||||
})
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub async fn get_participants(event_id: i32) -> Result<Vec<ParticipantSafe>, ServerFnError> {
|
||||
let db = db::establish_connection()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
|
||||
let participants = participants::Entity::find()
|
||||
.filter(participants::Column::EventId.eq(event_id))
|
||||
.all(&db)
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
|
||||
Ok(participants
|
||||
.into_iter()
|
||||
.map(|p| ParticipantSafe {
|
||||
id: p.id,
|
||||
name: p.name,
|
||||
email: p.email,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub async fn add_exclusion(participant_id: i32, excluded_id: i32) -> Result<(), ServerFnError> {
|
||||
let db = db::establish_connection()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
|
||||
let exclusion = exclusions::ActiveModel {
|
||||
participant_id: Set(participant_id),
|
||||
excluded_participant_id: Set(excluded_id),
|
||||
};
|
||||
|
||||
exclusion
|
||||
.insert(&db)
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub async fn draw_names(event_id: i32) -> Result<(), ServerFnError> {
|
||||
use rand::seq::SliceRandom;
|
||||
use rand::thread_rng;
|
||||
|
||||
let session: tower_sessions::Session = FullstackContext::extract().await?;
|
||||
let user_id: i32 = session
|
||||
.get("user_id")
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?
|
||||
.ok_or(ServerFnError::new("Not logged in"))?;
|
||||
|
||||
let db = db::establish_connection()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
|
||||
let event = events::Entity::find_by_id(event_id)
|
||||
.one(&db)
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?
|
||||
.ok_or(ServerFnError::new("Event not found"))?;
|
||||
|
||||
if event.creator_id != user_id {
|
||||
return Err(ServerFnError::new("Not authorized"));
|
||||
}
|
||||
|
||||
let participants = participants::Entity::find()
|
||||
.filter(participants::Column::EventId.eq(event_id))
|
||||
.all(&db)
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
|
||||
if participants.len() < 2 {
|
||||
return Err(ServerFnError::new("Not enough participants"));
|
||||
}
|
||||
|
||||
let exclusions = exclusions::Entity::find()
|
||||
.all(&db)
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
|
||||
// Simple logic: exclusions map
|
||||
let mut exclusion_map: std::collections::HashMap<i32, std::collections::HashSet<i32>> =
|
||||
std::collections::HashMap::new();
|
||||
for exc in exclusions {
|
||||
exclusion_map
|
||||
.entry(exc.participant_id)
|
||||
.or_default()
|
||||
.insert(exc.excluded_participant_id);
|
||||
}
|
||||
|
||||
let mut rng = thread_rng();
|
||||
let mut success = false;
|
||||
let mut assignments_vec = Vec::new();
|
||||
|
||||
for _ in 0..1000 {
|
||||
// Retry limit
|
||||
let mut receivers = participants.clone();
|
||||
receivers.shuffle(&mut rng);
|
||||
|
||||
let mut valid = true;
|
||||
assignments_vec.clear();
|
||||
|
||||
for (i, giver) in participants.iter().enumerate() {
|
||||
let receiver = &receivers[i];
|
||||
|
||||
// Rule 1: Cannot give to self
|
||||
if giver.id == receiver.id {
|
||||
valid = false;
|
||||
break;
|
||||
}
|
||||
|
||||
// Rule 2: Exclusions
|
||||
if let Some(excluded) = exclusion_map.get(&giver.id) {
|
||||
if excluded.contains(&receiver.id) {
|
||||
valid = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
assignments_vec.push(assignments::ActiveModel {
|
||||
event_id: Set(event_id),
|
||||
giver_id: Set(giver.id),
|
||||
receiver_id: Set(receiver.id),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
|
||||
if valid {
|
||||
success = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if !success {
|
||||
return Err(ServerFnError::new(
|
||||
"Could not find a valid assignment configuration. Try removing some exclusions.",
|
||||
));
|
||||
}
|
||||
|
||||
// Clear old assignments
|
||||
assignments::Entity::delete_many()
|
||||
.filter(assignments::Column::EventId.eq(event_id))
|
||||
.exec(&db)
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
|
||||
// Save new assignments
|
||||
assignments::Entity::insert_many(assignments_vec)
|
||||
.exec(&db)
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user