diff --git a/src/app.rs b/src/app.rs index fcd99b6..047c046 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,8 +1,10 @@ -use crate::pages::{AboutPage, HomePage, ProviderPortal, ComparisonTestPage, ScholarshipInfoPage, TestPage, ProviderContactPage, LoanerShell, LoanerFallback, LoanerBorrowForm, LoanerReturnForm}; +use crate::pages::{AboutPage, HomePage, ProviderPortal, ComparisonTestPage, ScholarshipInfoPage, TestPage, ProviderContactPage, LoanerShell, LoanerFallback, LoanerBorrowForm, LoanerReturnForm, AuthCallbackPage}; use leptos::prelude::*; use leptos_meta::{MetaTags, Stylesheet, Title, provide_meta_context}; -use leptos_oidc::{Auth, AuthParameters, AuthSignal, Challenge}; -use leptos_router::{components::{Route, Router, Routes, ParentRoute}, path}; +use leptos_oidc::AuthSignal; +use leptos_router::{components::{Route, Router, Routes, ParentRoute}, path, MatchNestedRoutes}; +use leptos_router::any_nested_route::IntoAnyNestedRoute; +use crate::components::login::ProviderLoginContext; use crate::components::ToastList; pub fn shell(options: LeptosOptions) -> impl IntoView { @@ -31,10 +33,10 @@ pub fn App() -> impl IntoView { view! { // injects a stylesheet into the document // id=leptos means cargo-leptos will hot-reload this stylesheet - - + + // sets the document title - + <Title text="R15 Scholarship App DEV" /> // content for this welcome page <Router> @@ -43,82 +45,64 @@ pub fn App() -> impl IntoView { } } -fn use_origin() -> String { - #[cfg(target_arch = "wasm32")] { - use leptos::web_sys; - // Just get the current URL origin. - web_sys::window() - .unwrap() - .location() - .origin() - .unwrap_or("http://localhost:3000/".to_string()) - } - - #[cfg(not(target_arch = "wasm32"))] { - // Read the expected origin out of an environment variable. - std::env::var("LP_SITE_ORIGIN").unwrap_or("http://localhost:3000/".to_string()) - } -} - #[component] pub fn AppWithRoutes() -> impl IntoView { provide_meta_context(); - - let current_origin = use_origin(); - - // Authentication setup - let parameters = AuthParameters { - issuer: "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_Lfjuy5zaM".into(), - client_id: "10jr2h3vtpu9n7gj46pvg5qo2q".into(), - redirect_uri: format!("{}/", use_origin()), - post_logout_redirect_uri: current_origin, - scope: Some("openid%20profile%20email".into()), - audience: None, - challenge: Challenge::None, - }; - - let auth = Auth::signal(); - provide_context(auth); // allows use of this signal in lower areas of the tree without - // explicitly passing it through the html tree - - let _ = Auth::init(parameters); view! { // injects a stylesheet into the document <head> // id=leptos means cargo-leptos will hot-reload this stylesheet <Stylesheet id="leptos" href="/pkg/scholarships-rs-wasm.css" /> - // <AuthLoading><p>"Authentication is loading"</p></AuthLoading> - // <AuthErrorContext><AuthErrorView/></AuthErrorContext> - // sets the document title <Title text="R15 Scholarship App DEV" /> - + <main> <ToastList> // TODO Create a 404 page <Routes fallback=|| "Page not found.".into_view()> - <Route path=path!("") view=HomePage/> - <Route path=path!("/about") view=AboutPage/> - <Route path=path!("/test_page") view=TestPage/> + <Route path=path!("") view=HomePage /> + <Route path=path!("/about") view=AboutPage /> + <Route path=path!("/test_page") view=TestPage /> <Route path=path!("/comparison") view=ComparisonTestPage /> - <Route path=path!("/providers") view=ProviderPortal/> - <Route path=path!("/providers/profile") view=ProviderContactPage /> - <ParentRoute path=path!("/providers/scholarships") view=ScholarshipInfoPage> - <Route path=path!(":id") view=ScholarshipInfoPage/> - <Route path=path!("") view=ScholarshipInfoPage/> - </ParentRoute> - <ParentRoute path=path!("loaners") view=LoanerShell> - <Route path=path!("") view=LoanerFallback /> - <Route path=path!("borrowing") view=LoanerBorrowForm /> - <Route path=path!("returning") view=LoanerReturnForm /> - </ParentRoute> + <ProviderRoutes /> + <LoanerRoutes /> </Routes> </ToastList> </main> } } +#[component(transparent)] +fn ProviderRoutes() -> impl MatchNestedRoutes + Clone { + view! { + <ParentRoute path=path!("/providers") view=ProviderLoginContext> + <Route path=path!("/callback") view=AuthCallbackPage /> + <Route path=path!("") view=ProviderPortal /> + <Route path=path!("/profile") view=ProviderContactPage /> + <ParentRoute path=path!("/scholarships") view=ScholarshipInfoPage> + <Route path=path!(":id") view=ScholarshipInfoPage /> + <Route path=path!("") view=ScholarshipInfoPage /> + </ParentRoute> + </ParentRoute> + } + .into_inner() + .into_any_nested_route() +} + +#[component(transparent)] +fn LoanerRoutes() -> impl MatchNestedRoutes + Clone { + view! { + <ParentRoute path=path!("loaners") view=LoanerShell> + <Route path=path!("") view=LoanerFallback /> + <Route path=path!("borrowing") view=LoanerBorrowForm /> + <Route path=path!("returning") view=LoanerReturnForm /> + </ParentRoute> + } + .into_inner() + .into_any_nested_route() +} + #[component] pub fn AuthErrorView() -> impl IntoView { let auth = use_context::<AuthSignal>().expect("AuthError: RwSignal<AuthStore> was not found"); diff --git a/src/common/date_info.rs b/src/common/date_info.rs new file mode 100644 index 0000000..269c300 --- /dev/null +++ b/src/common/date_info.rs @@ -0,0 +1,63 @@ +use chrono::{DateTime, FixedOffset, Local}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct DateInfo { + pub id: String, + pub title: String, + pub date: DateRange, + pub description: String, +} + +impl DateInfo { + pub fn get_start_date(&self) -> DateTime<FixedOffset> { + match self.date { + DateRange::Single(date) | DateRange::Range(date, _) => date, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum DateRange { + Single(DateTime<FixedOffset>), + Range(DateTime<FixedOffset>, DateTime<FixedOffset>), +} + +impl DateRange { + pub fn get_status(&self) -> DateStatus { + match self { + DateRange::Single(_) => DateStatus::Blank, + DateRange::Range(start_date, end_date) => { + let local = Local::now(); + // Check the amount of time from now to the start date. Values that are negative + // indicate that the start date has already passed. + if dbg!(start_date.signed_duration_since(local).num_days()) > 0 { + DateStatus::Upcoming + } else { + // Check the amount of time from now to the end date. The value will be positive if + // the end date is in the future. We will be specific to the minute. + let duration_until = dbg!(end_date).signed_duration_since(local); + let num_days = dbg!(duration_until.num_days()); + let num_mins = dbg!(duration_until.num_minutes()); + + if num_mins <= 0 { + DateStatus::Closed + } else if num_days <= 5 { + DateStatus::Deadline + } else { + DateStatus::Open + } + } + } + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, PartialOrd, Eq, Ord)] +pub enum DateStatus { + Closed, + Deadline, + Open, + Upcoming, + Blank, +} diff --git a/src/common/expandable_info.rs b/src/common/expandable_info.rs index 0ef8ff0..a209606 100644 --- a/src/common/expandable_info.rs +++ b/src/common/expandable_info.rs @@ -15,7 +15,7 @@ use std::collections::HashMap; /// now, the table will simply create a single massive `Map` field that contains all the stored /// information in the `HashMap`. We'd prefer to be able to get single values if possible, /// especially for interoperability with other applications, should they be created. -#[derive(Debug, Clone, Serialize, Deserialize, Reactive, )] +#[derive(Debug, Clone, Serialize, Deserialize, Reactive)] pub struct ExpandableInfo { /// The main key member. Required and used to get/put the information in a database. pub subject: String, diff --git a/src/common/mod.rs b/src/common/mod.rs index 5f68c9d..487f959 100644 --- a/src/common/mod.rs +++ b/src/common/mod.rs @@ -1,10 +1,14 @@ mod comparison; +mod date_info; mod expandable_info; mod form_params; mod form_schema; +mod submit_status; mod user; mod value_type; -mod submit_status; pub mod animations; -pub use self::{comparison::*, expandable_info::*, form_schema::*, user::*, value_type::*, form_params::*, submit_status::*}; +pub use self::{ + comparison::*, date_info::*, expandable_info::*, form_params::*, form_schema::*, + submit_status::*, user::*, value_type::*, +}; diff --git a/src/components/banner.rs b/src/components/banner.rs index 79b95ca..ac7dce2 100644 --- a/src/components/banner.rs +++ b/src/components/banner.rs @@ -32,17 +32,21 @@ pub fn Banner( view! { <div class="mx-auto"> - <div class="bg-red-900 shadow-lg shadow-[inset_0_2px_4px_0_rgba(0,0,0,0.3),0_4px_6px_-1px_rgba(127,29,29,0.3),0_2px_4px_-1px_rgba(127,29,29,0.2)]"> - <div class="flex items-center gap-4 p-6"> - <div class="flex-shrink-0"> - <img src={logo.clone()} class="h-10 w-10 cursor-pointer" alt="icon" on:click=on_click/> - </div> - <div class="flex-1"> - <h2 class="text-white text-lg font-bold">{title.clone()}</h2> - </div> + <div class="bg-red-900 shadow-lg shadow-[inset_0_2px_4px_0_rgba(0,0,0,0.3),0_4px_6px_-1px_rgba(127,29,29,0.3),0_2px_4px_-1px_rgba(127,29,29,0.2)]"> + <div class="flex items-center gap-4 p-6"> + <div class="flex-shrink-0"> + <img + src=logo.clone() + class="h-10 w-10 cursor-pointer" + alt="icon" + on:click=on_click + /> + </div> + <div class="flex-1"> + <h2 class="text-white text-2xl font-bold">{title.clone()}</h2> + </div> + </div> </div> - </div> </div> - } } diff --git a/src/components/dashboard_button.rs b/src/components/dashboard_button.rs index f471e33..9558824 100644 --- a/src/components/dashboard_button.rs +++ b/src/components/dashboard_button.rs @@ -57,5 +57,5 @@ pub fn DashboardButton( </div> </button> - } + }.into_any() } diff --git a/src/components/date.rs b/src/components/date.rs new file mode 100644 index 0000000..67c50d8 --- /dev/null +++ b/src/components/date.rs @@ -0,0 +1,124 @@ +use crate::common::{DateInfo, DateRange, DateStatus}; +use leptos::prelude::*; + +fn render_dates(dates: DateRange) -> impl IntoView { + let date_text = match dates { + DateRange::Single(date) => format!("{}", date.format("%A %B %d, %I:%M%p")), + DateRange::Range(start_date, end_date) => + format!("{} - {}", + start_date.format("%D %I:%M%p"), + end_date.format("%D %I:%M%p") + ), + }; + + view! { <span>{move || date_text.clone()}</span> } +} + +fn render_status(date: DateRange) -> impl IntoView { + let status = date.get_status(); + + let status_text = match dbg!(status.clone()) { + DateStatus::Blank => "", + DateStatus::Upcoming => "Upcoming", + DateStatus::Open => "Open", + DateStatus::Deadline => "Deadline", + DateStatus::Closed => "Closed", + }; + + let background_class = match status { + DateStatus::Blank => "hidden border-none", + DateStatus::Upcoming => "bg-yellow-100 text-yellow-800 border-yellow-100", + DateStatus::Open => "bg-green-100 text-green-800 border-green-100", + DateStatus::Deadline => "bg-red-100 text-red-800 border-red-100", + DateStatus::Closed => "bg-red-700 text-white border-red-700" + }; + + let classes = + format!("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs + font-medium w-fit whitespace-nowrap shrink-0 {}", + background_class + ); + + view! { <span class=classes>{move || status_text}</span> } +} + +/// # Date Component +/// A single date, for use in a [`DateList`] component. +/// +/// Example usage: +/// ``` +/// let date_info = DateInfo { +/// title: "Example Title".to_string(), +/// date: DateRange::Single("January 1st, 1990".to_string()), +/// description: "A description of the date.".to_string(), +/// status: DateStatus::Upcoming +/// } +/// +/// view! { +/// <Date +/// info=date_info +/// /> +/// } +/// ``` +#[component] +fn Date( + /// Struct of title, date, and description + #[prop(into)] info: Signal<DateInfo>, +) -> impl IntoView { + view! { + <div class="flex items-start gap-3 rounded-lg border-grey-300 p-3 + w-full text-left shadow-lg"> + // <div class="flex-shrink-0 mt-0.5"> + // <img src={icon} class="h-4 w-4" alt="icon"/> + // </div> + <div class="flex-1 min-w-0"> + <div class="flex items-start justify-between"> + <div class="flex-1"> + <h3 class="font-bold text-md text-base">{info.get().title}</h3> + <h3 class="text-md text-base mt-1"> + {move || render_dates(info.get().date)} + </h3> + <p class="text-sm text-gray-600">{info.get().description}</p> + </div> + <div class="flex-shrink-0 ml-2">{move || render_status(info.get().date)}</div> + </div> + </div> + </div> + } +} + +///# Dates List Component +/// Displays a list of important dates in a column, with badges that draw attention to dates that +/// are more important. +/// +/// Example usage: +/// ``` +/// let dates = vec![ +/// DateInfo { +/// title: "Example Title".to_string(), +/// date: DateRange::Single("January 1st, 1990".to_string()), +/// description: "A description of the date.".to_string(), +/// status: DateStatus::Upcoming +/// } +/// ] +/// +/// view! { +/// <DateList dates=dates /> +/// } +/// ``` +#[component] +pub fn DateList( + #[prop(into)] dates: Signal<Vec<DateInfo>>, +) -> impl IntoView { + view! { + {move || { + dates + .get() + .iter() + .map(|info| { + view! { <Date info=info.clone() /> } + }) + .collect_view() + }} + }.into_any() +} diff --git a/src/components/lists/multi/checkbox.rs b/src/components/lists/multi/checkbox.rs index 7515b78..252402d 100644 --- a/src/components/lists/multi/checkbox.rs +++ b/src/components/lists/multi/checkbox.rs @@ -134,25 +134,26 @@ pub fn CheckboxList( let cloned = item.clone(); move || cloned.clone() }); - let checked = Signal::derive(move || { controller.selected_list.get().contains(&item.get()) }); - let on_change = move || { - // Update the data list by checking if the value is present in it. If so, - // remove it. If not, add it. - controller.selected_list.update(|list| { - let item = item.get(); - if list.contains(&item) { - list.retain(|val| *val != item); - } else { - list.push(item); - } - }); + controller + .selected_list + .update(|list| { + let item = item.get(); + if list.contains(&item) { + list.retain(|val| *val != item); + } else { + list.push(item); + } + }); controller.dirty.set(true); }; + // Update the data list by checking if the value is present in it. If so, + // remove it. If not, add it. + view! { <Checkbox checked=checked @@ -171,7 +172,7 @@ pub fn CheckboxList( {move || { match controller.error.get() { ValidationState::Invalid(msg) => msg, - _ => "There is no error - should not see this message.".to_string() + _ => "There is no error - should not see this message.".to_string(), } }} </div> diff --git a/src/components/lists/multi/chips.rs b/src/components/lists/multi/chips.rs index d00cd8c..fdd4a22 100644 --- a/src/components/lists/multi/chips.rs +++ b/src/components/lists/multi/chips.rs @@ -45,16 +45,17 @@ pub fn Chip( id=id.clone() prop:checked=checked on:change=move |_| on_change.run(()) - disabled=disabled /> + disabled=disabled + /> <div class="rounded-full p-2.5 - cursor-pointer text-base - bg-transparent border-1 border-gray-300 - shadow-md/50 hover:shadow-md/70 - peer-checked:bg-red-700 peer-checked:border-red-700 peer-checked:text-white - peer-disabled:peer-checked:bg-gray-700 - peer-disabled:peer-checked:border-gray-700 - peer-disabled:cursor-default - transition-all duration-150"> + cursor-pointer text-base + bg-transparent border-1 border-gray-300 + shadow-md/50 hover:shadow-md/70 + peer-checked:bg-red-700 peer-checked:border-red-700 peer-checked:text-white + peer-disabled:peer-checked:bg-gray-700 + peer-disabled:peer-checked:border-gray-700 + peer-disabled:cursor-default + transition-all duration-150"> <span>{display_text.clone()}</span> </div> </label> @@ -98,47 +99,60 @@ pub fn ChipsList( <div class="m-1.5 mt-0 mb-0"> <span class="font-bold">{label}</span> <div class="flex flex-row flex-wrap gap-2 mb-1"> - {move || displayed_text.get().into_iter().zip(values.get()) - .into_iter() - .map(|(text, value)| { - let value = RwSignal::new(value); + {move || { + displayed_text + .get() + .into_iter() + .zip(values.get()) + .into_iter() + .map(|(text, value)| { + let value = RwSignal::new(value); + let checked = Signal::derive(move || { + controller.selected_list.get().contains(&value.get()) + }); + let on_change = move || { + let value = value.get(); + let list = controller.selected_list.get(); + if list.contains(&value) { + allows_multiple + .get() + .then(|| { + controller + .selected_list + .update(|list| list.retain(|v| v != &value)) + }) + .or_else(|| Some(controller.selected_list.set(Vec::new()))); + } else { + allows_multiple + .get() + .then(|| { + controller + .selected_list + .update(|list| list.push(value.clone())) + }) + .or_else(|| Some( + controller.selected_list.set(vec![value.clone()]), + )); + } + controller.dirty.set(true); + }; - let checked = Signal::derive(move || { - controller.selected_list.get().contains(&value.get()) - }); - - let on_change = move || { // Update the data list by checking if the value is present in it. If so, // remove it. If not, add it. - let value = value.get(); - let list = controller.selected_list.get(); - if list.contains(&value) { - allows_multiple.get() - .then(|| controller.selected_list.update(|list| list.retain(|v| v != &value))) - .or_else(|| Some(controller.selected_list.set(Vec::new()))); - } else { - allows_multiple.get() - .then(|| controller.selected_list.update(|list| list.push(value.clone()))) - .or_else(|| Some(controller.selected_list.set(vec![value.clone()]))); + view! { + <Chip + checked=checked + on_change=on_change + value=value + display_text=text + name=data_member + disabled=disabled + /> } - - controller.dirty.set(true); - }; - - view! { - <Chip - checked=checked - on_change=on_change - value=value - display_text=text - name=data_member - disabled=disabled - /> - } - }) - .collect_view() - } + }) + .collect_view() + }} </div> </div> <Show when=move || controller.show_errors.get()> @@ -146,7 +160,7 @@ pub fn ChipsList( {move || { match controller.error.get() { ValidationState::Invalid(msg) => msg, - _ => "There is no error - should not see this message.".to_string() + _ => "There is no error - should not see this message.".to_string(), } }} </div> diff --git a/src/components/lists/single/radio.rs b/src/components/lists/single/radio.rs index 1cdbc25..a554dd7 100644 --- a/src/components/lists/single/radio.rs +++ b/src/components/lists/single/radio.rs @@ -108,22 +108,21 @@ fn RadioOther( // This div displays the box for the checkbox, and applies some styling to the child // span element. <div class="relative inline-block min-h-5 min-w-5 h-5 w-5 m-1 mr-2 rounded-full border border-gray-300 bg-white - transition-bg duration-200 peer-checked:bg-red-700 peer-checked:border-red-700 - [&>span]:opacity-0 peer-checked:[&>span]:opacity-100 - peer-disabled:bg-gray-600/33 peer-disabled:border-gray-600 - peer-disabled:peer-checked:bg-gray-600"> + transition-bg duration-200 peer-checked:bg-red-700 peer-checked:border-red-700 + [&>span]:opacity-0 peer-checked:[&>span]:opacity-100 + peer-disabled:bg-gray-600/33 peer-disabled:border-gray-600 + peer-disabled:peer-checked:bg-gray-600"> // This span is the check icon. It is centered within the div and has a border on the bottom // and right sides, which is then rotated to appear like a checkmark. - <span - class="absolute left-1/2 top-1/2 block h-2.5 w-2.5 -translate-x-1/2 -translate-y-1/2 - rotate-45 transform border-3 border-3 rounded-full bg-white - border-white transition-opacity duration-150"></span> + <span class="absolute left-1/2 top-1/2 block h-2.5 w-2.5 -translate-x-1/2 -translate-y-1/2 + rotate-45 transform border-3 border-3 rounded-full bg-white + border-white transition-opacity duration-150"></span> </div> <input node_ref=input_ref class="border-b-2 mb-1.5 px-1.5 py-0.5 rounded-t-xs bg-transparent relative flex-1 transition-all duration-150 - border-red-700 disabled:border-gray-600 disabled:pointer-events-none disabled:bg-gray-600/33" + border-red-700 disabled:border-gray-600 disabled:pointer-events-none disabled:bg-gray-600/33" r#type="text" disabled=input_disabled placeholder=placeholder @@ -239,19 +238,23 @@ pub fn RadioList( .into_iter() .map(|item| { let item = RwSignal::new(item); - let checked_signal = Signal::derive(move || { selected_value.get() == item.get() && !other_checked.get() }); - let on_change = move || { - // on_change only runs when the radio button is checked, not when unchecked. - // Change the selected value to the new one. other_checked.set(false); selected_value.set(item.get()); - error.set(validate(selected_value.get_untracked(), required.get_untracked())); + error + .set( + validate( + selected_value.get_untracked(), + required.get_untracked(), + ), + ); dirty.set(true); }; + // on_change only runs when the radio button is checked, not when unchecked. + // Change the selected value to the new one. view! { <Radio @@ -266,24 +269,24 @@ pub fn RadioList( }) .collect::<Vec<_>>()} - <Show when=move || !other_prompt.get().is_empty()> - <RadioOther - checked=other_checked - name=data_member - disabled=disabled - value=other_value - on_change=move |_| other_checked.set(true) - placeholder=other_prompt - dirty=dirty - /> - </Show> + <Show when=move || !other_prompt.get().is_empty()> + <RadioOther + checked=other_checked + name=data_member + disabled=disabled + value=other_value + on_change=move |_| other_checked.set(true) + placeholder=other_prompt + dirty=dirty + /> + </Show> </div> <Show when=move || show_errors.get()> <div class="text-red-600 text-sm mr-1.5 ml-1.5"> {move || { match error.get() { ValidationState::Invalid(msg) => msg, - _ => "There is no error - should not see this message.".to_string() + _ => "There is no error - should not see this message.".to_string(), } }} </div> diff --git a/src/components/lists/single/select.rs b/src/components/lists/single/select.rs index 3fd6ab6..b20cddc 100644 --- a/src/components/lists/single/select.rs +++ b/src/components/lists/single/select.rs @@ -93,9 +93,9 @@ pub fn Select( <span class="ml-1.5 mb-0 font-bold">{label}</span> <select class="relative flex-1 border-2 m-1.5 mt-0 p-1.5 rounded-md - transition-border duration-150 - border-red-700 bg-transparent - disabled:border-gray-600 disabled:pointer-events-none disabled:bg-gray-600/33" + transition-border duration-150 + border-red-700 bg-transparent + disabled:border-gray-600 disabled:pointer-events-none disabled:bg-gray-600/33" on:change:target=on_change disabled=disabled > @@ -104,15 +104,18 @@ pub fn Select( value="" disabled hidden - selected={move || raw_value.get().is_empty()} - >"Select one..."</option> + selected=move || raw_value.get().is_empty() + > + "Select one..." + </option> {move || { - value_list.iter().map( - move |value| { + value_list + .iter() + .map(move |value| { let display = value.to_owned(); - view! { <option value={display}>{display.clone()}</option> } - } - ).collect::<Vec<_>>() + view! { <option value=display>{display.clone()}</option> } + }) + .collect::<Vec<_>>() }} </select> </label> @@ -122,7 +125,7 @@ pub fn Select( {move || { match error.get() { ValidationState::Invalid(msg) => msg, - _ => "There is no error - should not see this message.".to_string() + _ => "There is no error - should not see this message.".to_string(), } }} </div> diff --git a/src/components/login/mod.rs b/src/components/login/mod.rs new file mode 100644 index 0000000..fae50eb --- /dev/null +++ b/src/components/login/mod.rs @@ -0,0 +1,5 @@ +mod provider; +pub use provider::*; +mod student; +pub use student::*; +pub(crate) mod setup; \ No newline at end of file diff --git a/src/components/login/provider.rs b/src/components/login/provider.rs new file mode 100644 index 0000000..ce1fb6d --- /dev/null +++ b/src/components/login/provider.rs @@ -0,0 +1,30 @@ +use leptos::prelude::*; +use leptos_router::components::Outlet; +use super::setup::provide_auth_context; + +///# Provider Login Context Component +/// +/// This component handles providing context to the provider login information. +/// It creates the corresponding [`AuthSignal`], specific to the student login page and redirects. +/// +/// Example usage: +/// ``` +/// view! { +/// <ProviderLoginContext> +/// // The rest of the student application. Don't forget AuthLoaded and +/// // Authenticated components! +/// </ProviderLoginContext> +/// } +#[component] +pub fn ProviderLoginContext() -> impl IntoView { + provide_auth_context( + crate::utils::use_origin(), + "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_Lfjuy5zaM", + "56c2bqvl021rv8d5mq36blt7jv", + "/providers/callback" + ); + + view! { + <Outlet /> + } +} diff --git a/src/components/login/setup.rs b/src/components/login/setup.rs new file mode 100644 index 0000000..a5ebae6 --- /dev/null +++ b/src/components/login/setup.rs @@ -0,0 +1,24 @@ +use leptos::prelude::*; +use leptos_oidc::{Auth, AuthParameters, Challenge}; + +pub fn provide_auth_context( + origin: String, + issuer: impl Into<String>, + client_id: impl Into<String>, + redirect_path: impl Into<String>, +) { + let params = AuthParameters { + issuer: issuer.into(), + client_id: client_id.into(), + redirect_uri: format!("{}{}", origin, redirect_path.into()), + post_logout_redirect_uri: origin, + scope: Some("openid%20profile%20email".into()), + audience: None, + challenge: Challenge::None, + }; + + let auth = Auth::signal(); + provide_context(auth); + + let _ = Auth::init(params); +} diff --git a/src/components/login/student.rs b/src/components/login/student.rs new file mode 100644 index 0000000..f3b89df --- /dev/null +++ b/src/components/login/student.rs @@ -0,0 +1,30 @@ +use leptos::prelude::*; +use leptos_router::components::Outlet; +use super::setup::provide_auth_context; + +///# Student Login Context Component +/// +/// This component handles providing context to the student login information. +/// It creates the corresponding [`AuthSignal`], specific to the student login page and redirects. +/// +/// Example usage: +/// ``` +/// view! { +/// <StudentLoginContext> +/// // The rest of the student application. Don't forget AuthLoaded and +/// // Authenticated components! +/// </StudentLoginContext> +/// } +#[component] +pub fn StudentLoginContext() -> impl IntoView { + provide_auth_context( + crate::utils::use_origin(), + "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_Lfjuy5zaM", + "10jr2h3vtpu9n7gj46pvg5qo2q", + "/students/callback" + ); + + view! { + <Outlet /> + } +} diff --git a/src/components/mod.rs b/src/components/mod.rs index a5f210f..27d6b69 100644 --- a/src/components/mod.rs +++ b/src/components/mod.rs @@ -1,6 +1,7 @@ mod action_button; mod banner; mod dashboard_button; +mod date; mod loading; mod multi_entry; mod panel; @@ -11,9 +12,10 @@ mod validated_form; mod lists; mod toasts; mod header; +pub mod login; pub use self::{ action_button::*, banner::*, dashboard_button::*, lists::*, loading::*, multi_entry::*, panel::*, row::*, text_field::*, - validated_form::*, toasts::*, header::* + validated_form::*, toasts::*, header::*, date::* }; diff --git a/src/components/text_field.rs b/src/components/text_field.rs index dee1854..40e9052 100644 --- a/src/components/text_field.rs +++ b/src/components/text_field.rs @@ -144,12 +144,12 @@ pub fn OutlinedTextField( <input node_ref=input_ref class="border-2 m-1.5 p-1.5 mt-0 rounded-md bg-transparent relative flex-1 - transition-all duration-150 - border-red-700 bg-transparent - disabled:border-gray-600 disabled:pointer-events-none disabled:bg-gray-600/33" - r#type={str_type} - disabled={disabled} - placeholder={placeholder} + transition-all duration-150 + border-red-700 bg-transparent + disabled:border-gray-600 disabled:pointer-events-none disabled:bg-gray-600/33" + r#type=str_type + disabled=disabled + placeholder=placeholder prop:name=name prop:value=raw_value on:input=on_input @@ -160,7 +160,7 @@ pub fn OutlinedTextField( {move || { match error.get() { ValidationState::Invalid(msg) => msg, - _ => "There is no error - should not see this message.".to_string() + _ => "There is no error - should not see this message.".to_string(), } }} </div> diff --git a/src/lib.rs b/src/lib.rs index 9958e9f..b512299 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,7 @@ pub mod app; mod common; mod components; mod pages; +pub mod utils; #[cfg(feature = "hydrate")] #[wasm_bindgen::prelude::wasm_bindgen] diff --git a/src/main.rs b/src/main.rs index 1d9b6f6..2900ec5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,7 +6,12 @@ async fn main() { use leptos::prelude::*; use leptos_axum::{LeptosRoutes, generate_route_list}; use scholarships_rs::app::*; + use scholarships_rs::utils::server::create_dynamo_client; + use std::sync::Arc; + let dynamo_client = create_dynamo_client().await; + let shared_client = Arc::new(dynamo_client); + let conf = get_configuration(None).unwrap(); let addr = conf.leptos_options.site_addr; let leptos_options = conf.leptos_options; @@ -14,10 +19,20 @@ async fn main() { let routes = generate_route_list(App); let app = Router::new() - .leptos_routes(&leptos_options, routes, { - let leptos_options = leptos_options.clone(); - move || shell(leptos_options.clone()) - }) + .leptos_routes_with_context( + &leptos_options, + routes, + { + let shared_client = Arc::clone(&shared_client); + move || { + provide_context(Arc::clone(&shared_client)); + } + }, + { + let leptos_options = leptos_options.clone(); + move || shell(leptos_options.clone()) + } + ) .fallback(leptos_axum::file_and_error_handler(shell)) .with_state(leptos_options); diff --git a/src/pages/api/comparisons.rs b/src/pages/api/comparisons.rs index daf1339..9177955 100644 --- a/src/pages/api/comparisons.rs +++ b/src/pages/api/comparisons.rs @@ -1,6 +1,5 @@ -use std::collections::HashMap; #[cfg(feature = "ssr")] -use crate::pages::utils::server_utils::create_dynamo_client; +use crate::utils::server::create_dynamo_client; #[cfg(feature = "ssr")] use aws_sdk_dynamodb::error::ProvideErrorMetadata; @@ -12,6 +11,7 @@ use crate::common::{ ComparisonData, ComparisonType, MapListComparison, NumberComparison, NumberListComparison, TextComparison, TextListComparison, ValueType, }; +use std::collections::HashMap; use leptos::prelude::ServerFnError; use leptos::server; diff --git a/src/pages/api/dates.rs b/src/pages/api/dates.rs new file mode 100644 index 0000000..12d5cdf --- /dev/null +++ b/src/pages/api/dates.rs @@ -0,0 +1,75 @@ +use std::collections::HashMap; +use leptos::logging::log; +use leptos::prelude::*; +use crate::common::DateInfo; + +#[cfg(feature = "ssr")] +static DATES_TABLE: &str = "leptos-dates"; + +#[cfg(feature = "ssr")] +use aws_sdk_dynamodb::{ + types::{WriteRequest, PutRequest}, + Client as DynamoClient +}; + +#[cfg(feature = "ssr")] +use std::sync::Arc; + +#[server] +pub async fn create_dates(dates: Vec<DateInfo>) -> Result<(), ServerFnError> { + // Serialize and put dates into the database. + let client = expect_context::<Arc<DynamoClient>>(); + + log!("Creating dates: {:?}", dates); + + let requests = dates + .into_iter() + .map(|date| { + let item = serde_dynamo::to_item(&date) + .unwrap_or_default(); + + let put_request = PutRequest::builder() + .set_item(Some(item)) + .build() + .expect("Couldn't build request, item is not present"); + + WriteRequest::builder().put_request(put_request).build() + }) + .collect::<Vec<WriteRequest>>(); + + let mut request_map = HashMap::new(); + request_map.insert(DATES_TABLE.to_string(), requests); + + client + .batch_write_item() + .set_request_items(Some(request_map)) + .send() + .await + .map(|_| ()) + .map_err(ServerFnError::from) +} + +#[server] +pub async fn get_important_dates() -> Result<Vec<DateInfo>, ServerFnError> { + let client = expect_context::<Arc<DynamoClient>>(); + + client + .scan() + .table_name(DATES_TABLE) + .send() + .await + .map(|output| { + if let Some(items) = output.items { + items + .into_iter() + .filter_map(|item| { + serde_dynamo::from_item::<_, DateInfo>(item) + .ok() + }) + .collect::<Vec<DateInfo>>() + } else { + Vec::new() + } + }) + .map_err(ServerFnError::from) +} diff --git a/src/pages/api/mod.rs b/src/pages/api/mod.rs index e13ff2b..f7aa9bf 100644 --- a/src/pages/api/mod.rs +++ b/src/pages/api/mod.rs @@ -1,4 +1,7 @@ mod comparisons; +pub use comparisons::*; mod scholarships; +pub use scholarships::*; +mod dates; +pub use dates::*; -pub use self::{comparisons::*, scholarships::*}; diff --git a/src/pages/api/scholarships.rs b/src/pages/api/scholarships.rs index d467a2e..6a8b345 100644 --- a/src/pages/api/scholarships.rs +++ b/src/pages/api/scholarships.rs @@ -8,7 +8,7 @@ use leptos::leptos_dom::log; #[cfg(feature = "ssr")] use uuid::Uuid; #[cfg(feature = "ssr")] -use crate::pages::utils::server_utils::create_dynamo_client; +use crate::utils::server::{create_dynamo_client, into_attr_map}; #[cfg(feature = "ssr")] use crate::common::ValueType; @@ -52,7 +52,6 @@ pub async fn get_scholarship_info(id: String) -> Result<ExpandableInfo, ServerFn #[server(CreateScholarshipInfo, endpoint = "/scholarship/info/create")] pub async fn create_scholarship_info(info: ExpandableInfo) -> Result<(), ServerFnError> { - use crate::pages::utils::server_utils::create_dynamo_client; use aws_sdk_dynamodb::error::ProvideErrorMetadata; let client = create_dynamo_client().await; diff --git a/src/pages/auth_callback.rs b/src/pages/auth_callback.rs new file mode 100644 index 0000000..4b2dbe3 --- /dev/null +++ b/src/pages/auth_callback.rs @@ -0,0 +1,37 @@ +use leptos::prelude::*; +use leptos_oidc::AuthSignal; +use leptos_router::hooks::use_navigate; + +#[component] +pub fn AuthCallbackPage() -> impl IntoView { + // This should wait for authentication, read the values in session storage, and then redirect + // to the correct page. The session storage should contain a path, which we'll need to check. + + let auth = expect_context::<AuthSignal>(); + let navigate = use_navigate(); + + Effect::new(move || { + // Wait for auth to load, then read information. + if let Some(_) = auth.get().authenticated() { + // Read the sessionStorage to get the last navigated path. + let storage_opt = window().session_storage().ok().flatten(); + let path = storage_opt + .and_then(|storage| storage.get_item("post_login_path").ok().flatten()) + .unwrap_or_else(|| "/".to_string()); + + // Clear storage in case we need to reauth again + if let Some(storage) = window().session_storage().ok().flatten() { + let _ = storage.remove_item("post_login_path"); + } + + // Redirect to the stored path + navigate(&path, Default::default()); + } + }); + + view! { + <div class="flex flex-col w-full mx-auto items-center justify-center"> + <p>"Completing the login process..."</p> + </div> + } +} diff --git a/src/pages/comparison_test.rs b/src/pages/comparison_test.rs index 8bb9ab8..50dd46f 100644 --- a/src/pages/comparison_test.rs +++ b/src/pages/comparison_test.rs @@ -1,16 +1,14 @@ use super::UnauthenticatedPage; +use super::api::{get_all_scholarship_info, get_comparison_info}; use super::home_page::get_submission; -use crate::common::{ - ComparisonData, ExpandableInfo, ValueType, -}; +use crate::common::{ComparisonData, ExpandableInfo, ValueType}; use crate::components::{ActionButton, Loading, Panel, Row}; use leptos::either::Either; use leptos::leptos_dom::logging::console_log; use leptos::logging::log; use leptos::prelude::*; use leptos_oidc::{AuthLoaded, Authenticated}; -use crate::pages::utils::get_user_claims; -use super::api::{get_comparison_info, get_all_scholarship_info}; +use crate::utils::get_user_claims; #[component] pub fn ComparisonTestPage() -> impl IntoView { @@ -59,93 +57,84 @@ pub fn ComparisonTestPage() -> impl IntoView { let student_info = student_resource.get(); let comparison_info = comparison_resource.get(); let scholarship_info = scholarship_resource.get(); - match (student_info, comparison_info, scholarship_info) { - (Some(student), Some(comparisons), Some(scholarships)) => Either::Right(view! { - <Panel> - <Row> - <p>{result_msg}</p> - </Row> - <Row> - <ActionButton on:click=move |_| { - // Iterate over all scholarships, get the comparison IDs, - // get ComparisonData from the IDs, then perform the - // comparisons and return a boolean. Alternatively, return - // a list of comparisons that complete and a list that don't. - let comp_member = "requirements".to_string(); - let comparison_results = scholarships.iter().map(|scholarship| { - let list = match scholarship.data.get(&comp_member) { - Some(ValueType::List(Some(list))) => list, - _ => { - log!("Cannot find requirements, assuming none."); - return Ok(Some(scholarship)) // students will always qualify when there are no requirements - } - }; + (Some(student), Some(comparisons), Some(scholarships)) => { + Either::Right( - let mut final_result = Ok(true); - - // The list should exist, and it should contain a series of strings. - for val in list { - let comp_opt = match val { - ValueType::String(Some(comp_id)) => { - // Find the comparison - comparisons.iter().find(|comp| comp.id == *comp_id) - } - _ => None - }; - - let comparison_outcome = match comp_opt { - Some(comp) => { - // Perform the comparison - comp.compare(&student) - } - _ => Err("".to_string()) - }; - - match comparison_outcome { - Ok(true) => {}, - Ok(false) => final_result = Ok(false), - Err(e) => { - final_result = Err(e); - break; + view! { + <Panel> + <Row> + <p>{result_msg}</p> + </Row> + <Row> + <ActionButton on:click=move |_| { + let comp_member = "requirements".to_string(); + let comparison_results = scholarships + .iter() + .map(|scholarship| { + let list = match scholarship.data.get(&comp_member) { + Some(ValueType::List(Some(list))) => list, + _ => { + log!("Cannot find requirements, assuming none."); + return Ok(Some(scholarship)); + } + }; + let mut final_result = Ok(true); + for val in list { + let comp_opt = match val { + ValueType::String(Some(comp_id)) => { + comparisons.iter().find(|comp| comp.id == *comp_id) + } + _ => None, + }; + let comparison_outcome = match comp_opt { + Some(comp) => comp.compare(&student), + _ => Err("".to_string()), + }; + match comparison_outcome { + Ok(true) => {} + Ok(false) => final_result = Ok(false), + Err(e) => { + final_result = Err(e); + break; + } + } + } + match final_result { + Ok(true) => Ok(Some(scholarship)), + Ok(false) => Ok(None), + Err(e) => Err(e), + } + }) + .collect::<Vec<Result<Option<&ExpandableInfo>, String>>>(); + let mut strings = Vec::new(); + strings.push("Scholarship results: \n".to_string()); + for result in comparison_results { + match result { + Ok(Some(scholarship_info)) => { + let name_member = "name".to_string(); + let scl_name = scholarship_info + .data + .get(&name_member) + .unwrap() + .as_string() + .unwrap() + .unwrap(); + strings.push(scl_name); + } + Ok(None) => {} + Err(msg) => strings.push(msg), } } - } - - match final_result { - Ok(true) => Ok(Some(scholarship)), - Ok(false) => Ok(None), - Err(e) => Err(e) - } - }).collect::<Vec<Result<Option<&ExpandableInfo>, String>>>(); - - // Build a display string - let mut strings = Vec::new(); - strings.push("Scholarship results: \n".to_string()); - for result in comparison_results { - match result { - Ok(Some(scholarship_info)) => { - // Get the scholarship name. - let name_member = "name".to_string(); - let scl_name = scholarship_info.data.get(&name_member).unwrap() - .as_string().unwrap().unwrap(); - strings.push(scl_name); - }, - Ok(None) => {}, - Err(msg) => strings.push(msg) - } - } - - let display_text = strings.join("\n").to_string(); - - result_msg.set(display_text); - }>"Test Comparison"</ActionButton> - </Row> - </Panel> - }), - _ => Either::Left(view! { - <p>"Failed API requests."</p> - }) + let display_text = strings.join("\n").to_string(); + result_msg.set(display_text); + }>"Test Comparison"</ActionButton> + </Row> + </Panel> + }, + ) + } + _ => Either::Left(view! { <p>"Failed API requests."</p> }), } }} </Suspense> diff --git a/src/pages/home_page.rs b/src/pages/home_page.rs index 3481a5b..194c44f 100644 --- a/src/pages/home_page.rs +++ b/src/pages/home_page.rs @@ -10,8 +10,10 @@ use std::io::Write; use crate::common::ExpandableInfo; use crate::pages::UnauthenticatedPage; -use crate::pages::utils::get_user_claims; -use crate::components::{ActionButton, CheckboxList, Loading, MultiEntry, OutlinedTextField, Panel, RadioList, Row, Select, TextFieldType, ValidatedForm}; +use crate::components::{ + ActionButton, CheckboxList, Loading, MultiEntry, OutlinedTextField, Panel, RadioList, Row, + Select, TextFieldType, ValidatedForm +}; use crate::input; use leptos::leptos_dom::logging::console_log; use leptos::prelude::*; @@ -22,6 +24,7 @@ use leptos::task::spawn_local; use leptos::web_sys::HtmlAnchorElement; use leptos::wasm_bindgen::JsCast; use std::collections::HashMap; +use crate::utils::get_user_claims; /// # Get Student Info /// Gets a student's information given their `subject`. @@ -155,7 +158,7 @@ pub fn HomePage() -> impl IntoView { async move |subject| get_submission(subject.unwrap_or_default()).await ); let submit_action = ServerAction::<CreateSampleSubmission>::new(); - + Effect::new(move || { match server_resource.get() { Some(Ok(submission)) => { @@ -222,7 +225,7 @@ pub fn HomePage() -> impl IntoView { <Row> <div class="flex flex-col flex-1" /> <Panel> - <ValidatedForm + <ValidatedForm on_submit=Callback::new(on_submit) title="Home Page Test Form" description="This really is just a test." @@ -263,7 +266,7 @@ pub fn HomePage() -> impl IntoView { data_member="contact_email" data_map=form_data input_type=TextFieldType::Email( - vec!["fakeemail.org".to_string(), "gmail.com".to_string()] + vec!["fakeemail.org".to_string(), "gmail.com".to_string()], ) required=true /> @@ -344,8 +347,12 @@ pub fn HomePage() -> impl IntoView { data_map=form_data data_member="community_involvement" schema=vec![ - input!(Text, "service_name", "Activity Name:", true, "Some service activity..."), - input!(Number, "service_hours", "Total Service Hours", true, "20") + input!( + Text, "service_name", "Activity Name:", true, "Some service activity..." + ), + input!( + Number, "service_hours", "Total Service Hours", true, "20" + ), ] /> </Row> @@ -355,8 +362,7 @@ pub fn HomePage() -> impl IntoView { </Row> } }) - }} - <Row> + }} <Row> <ActionButton on:click=pdf_button_click>"Get PDF"</ActionButton> </Row> </Suspense> diff --git a/src/pages/loaner_page.rs b/src/pages/loaner_page.rs index 07b2464..14cd5b0 100644 --- a/src/pages/loaner_page.rs +++ b/src/pages/loaner_page.rs @@ -213,11 +213,7 @@ pub fn LoanerShell() -> impl IntoView { // We'll create the page here - the sidebar contains all the buttons, while the form // container either shows forms or shows placeholder text. view! { - <Banner - title="Chromebook Loaners" - logo="/PHS_Stacked_Acronym.png" - path="/loaners" - /> + <Banner title="Chromebook Loaners" logo="/PHS_Stacked_Acronym.png" path="/loaners" /> <div class="flex m-5"> <div class="flex flex-1 flex-row gap-3"> <div id="sidebar" class="flex flex-1 flex-col gap-2"> @@ -247,16 +243,9 @@ pub fn LoanerShell() -> impl IntoView { #[component] pub fn LoanerFallback() -> impl IntoView { view! { - <div - class="flex flex-col items-center justify-center" - use:animate=pop_in_out() - > - <div class="text-3xl font-bold mb-2"> - "Chromebook Loaner Form" - </div> - <div class="text-lg"> - "Select an option from the left to begin." - </div> + <div class="flex flex-col items-center justify-center" use:animate=pop_in_out()> + <div class="text-3xl font-bold mb-2">"Chromebook Loaner Form"</div> + <div class="text-lg">"Select an option from the left to begin."</div> </div> } } @@ -431,69 +420,85 @@ pub fn LoanerReturnForm() -> impl IntoView { <dialog use:animate=pop_in_out() class="p-3 m-auto rounded-md shadow-lg/33 backdrop:backdrop-blur-xs backdrop:transition-backdrop-filter" - node_ref=dialog_ref> + node_ref=dialog_ref + > <h2 class="text-2xl font-bold">"Confirmation"</h2> <h4 class="text-xl mb-3"> - {move || chosen_student.with(|opt_student| { - if let Some(student) = opt_student.as_ref() { - format!("Are you sure want to check in {} {}?", student.first_name, student.last_name) - } else { - "There is no student selected.".to_string() - } - })} + {move || { + chosen_student + .with(|opt_student| { + if let Some(student) = opt_student.as_ref() { + format!( + "Are you sure want to check in {} {}?", + student.first_name, + student.last_name, + ) + } else { + "There is no student selected.".to_string() + } + }) + }} </h4> - <ActionButton on:click=close_dialog disabled=dialog_disabled>"Close"</ActionButton> - <ActionButton on:click=dialog_check_in disabled=dialog_disabled>"Check In"</ActionButton> + <ActionButton on:click=close_dialog disabled=dialog_disabled> + "Close" + </ActionButton> + <ActionButton on:click=dialog_check_in disabled=dialog_disabled> + "Check In" + </ActionButton> </dialog> - <div - class="flex flex-col gap-2 m-2" - use:animate=pop_in_out() - > + <div class="flex flex-col gap-2 m-2" use:animate=pop_in_out()> <div class="flex flex-col justify-center gap-2 mb-3 py-3 px-2"> <h2 class="text-2xl font-bold">"Student List"</h2> <p class="text-lg">"Please select your name from the list."</p> </div> - <Suspense fallback=move || "Loading...".into_view()> + <Suspense fallback=move || { + "Loading...".into_view() + }> {move || { match return_list_resource.get() { Some(loaner_list) => { - let list_view = loaner_list.iter().map(|student| { - let on_click = { - let student_click = student.clone(); - move |_| { - log!("Running on_click using student {:?}", student_click); - if let Some(dialog) = dialog_ref.get() { - chosen_student.set(Some(student_click.clone())); - dialog.show_modal().expect("Couldn't show modal dialog."); + let list_view = loaner_list + .iter() + .map(|student| { + let on_click = { + let student_click = student.clone(); + move |_| { + log!("Running on_click using student {:?}", student_click); + if let Some(dialog) = dialog_ref.get() { + chosen_student.set(Some(student_click.clone())); + dialog.show_modal().expect("Couldn't show modal dialog."); + } } + }; + let naive_time = chrono::NaiveDateTime::parse_from_str( + &student.date, + "%H:%M, %m/%d/%Y", + ) + .unwrap(); + let time_zone = FixedOffset::west_opt(5 * 3600).unwrap(); + let student_date = time_zone + .from_utc_datetime(&naive_time) + .format("%l:%M %p, %m/%d/%Y") + .to_string(); + log!("Found current date {:?}", student_date); + + view! { + <div + class="flex flex-row p-3 rounded-md cursor-pointer transition-shadow shadow-sm hover:shadow-lg/33" + on:click=on_click + > + <div class="flex-1"> + {student.first_name.clone()}" "{student.last_name.clone()} + </div> + <div class="flex-none">{student_date.clone()}</div> + </div> } - }; - - let naive_time = chrono::NaiveDateTime::parse_from_str(&student.date, "%H:%M, %m/%d/%Y") - .unwrap(); - let time_zone = FixedOffset::west_opt(5 * 3600).unwrap(); - let student_date = time_zone.from_utc_datetime(&naive_time) - .format("%l:%M %p, %m/%d/%Y") - .to_string(); - - log!("Found current date {:?}", student_date); - - view! { - <div class="flex flex-row p-3 rounded-md cursor-pointer transition-shadow shadow-sm hover:shadow-lg/33" on:click=on_click> - <div class="flex-1"> - {student.first_name.clone()}" "{student.last_name.clone()} - </div> - <div class="flex-none"> - {student_date.clone()} - </div> - </div> - } - }).collect_view(); - + }) + .collect_view(); Either::Left(list_view) - }, - None => Either::Right("No loaners found.".into_view()) + } + None => Either::Right("No loaners found.".into_view()), } }} </Suspense> diff --git a/src/pages/mod.rs b/src/pages/mod.rs index 4da8c68..6b76373 100644 --- a/src/pages/mod.rs +++ b/src/pages/mod.rs @@ -7,10 +7,11 @@ mod provider_portal; mod scholarship_info; mod test_page; mod unauthenticated_page; -mod utils; mod provider_contact; +mod auth_callback; pub use self::{ about_page::*, comparison_test::*, home_page::*, loaner_page::*, provider_portal::*, - test_page::*, unauthenticated_page::*, scholarship_info::*, provider_contact::* + test_page::*, unauthenticated_page::*, scholarship_info::*, provider_contact::*, + auth_callback::*, }; diff --git a/src/pages/provider_contact.rs b/src/pages/provider_contact.rs index 355dc69..f04271c 100644 --- a/src/pages/provider_contact.rs +++ b/src/pages/provider_contact.rs @@ -1,14 +1,14 @@ -use std::collections::HashMap; +#[cfg(feature = "ssr")] +use crate::utils::server::{create_dynamo_client, into_attr_map}; + +use std::collections::HashMap; use leptos::logging::log; use leptos::prelude::*; use leptos_oidc::{AuthLoaded, Authenticated}; use crate::common::ValueType; use crate::components::{Banner, Loading, OutlinedTextField, Panel, Row, TextFieldType, Toast, ToastContext, ToastList, ValidatedForm}; use crate::pages::UnauthenticatedPage; -use crate::pages::utils::get_user_claims; - -#[cfg(feature = "ssr")] -use crate::pages::utils::server_utils::create_dynamo_client; +use crate::utils::get_user_claims; #[cfg(feature = "ssr")] static PROVIDER_CONTACT_TABLE: &str = "leptos-provider-contacts"; @@ -52,7 +52,6 @@ async fn get_provider_contact(id: String) -> Result<HashMap<String, ValueType>, #[server] async fn put_provider_contact(id: String, contact_info: HashMap<String, ValueType>) -> Result<(), ServerFnError> { use aws_sdk_dynamodb::error::ProvideErrorMetadata; - use crate::pages::utils::server_utils::into_attr_map; let client = create_dynamo_client().await; @@ -149,7 +148,7 @@ pub fn ProviderContactPage() -> impl IntoView { <div class="flex flex-row"> <div class="flex flex-col flex-1" /> <Panel> - <ValidatedForm + <ValidatedForm on_submit=on_submit title="Contact Form" description="Enter your contact information and click submit." diff --git a/src/pages/provider_portal.rs b/src/pages/provider_portal.rs index 145901b..8dc2018 100644 --- a/src/pages/provider_portal.rs +++ b/src/pages/provider_portal.rs @@ -1,42 +1,71 @@ -use crate::components::{Banner, DashboardButton}; +use crate::components::{Banner, DashboardButton, DateList, Loading}; use leptos::prelude::*; +use leptos_oidc::{AuthLoaded, Authenticated}; +use crate::pages::api::get_important_dates; +use crate::pages::UnauthenticatedPage; #[component] pub fn ProviderPortal() -> impl IntoView { + let dates_resource = OnceResource::new(async move { + get_important_dates().await + }); + + let dates_list = RwSignal::new(Vec::new()); + + Effect::new(move || { + if let Some(Ok(mut dates)) = dates_resource.get() { + dates.sort_by_key(|info| info.date.get_status()); + dates_list.set(dates); + } + }); + view! { <Banner title="Provider Dashboard" logo="PHS_Stacked_Acronym.png" path="/" /> - <div class="mx-auto px-6"> - <div class="container mx-auto px-6 py-8 space-y-8"> - <div class="grid grid-cols-1 lg:grid-cols-2 gap-8"> - <section class="space-y-4"> - <DashboardButton - title="Profile" - description="Edit user profile" - icon="/Person_Black.png" - path="/providers/profile" - /> - <DashboardButton - title="Create Scholarship" - description="Navigate to Scholarship Creation Page" - icon="/Create_Black.png" - path="/providers/scholarships" - /> - <DashboardButton - title="Applicants" - description="View Scholarship Applicants" - icon="/Form_Black.png" - path="/" - /> - </section> - <section class="space-y-4"> - - </section> + <AuthLoaded fallback=Loading> + <Authenticated unauthenticated=UnauthenticatedPage> + <div class="mx-auto px-6"> + <div class="container mx-auto px-6 py-8 space-y-8"> + <div class="grid grid-cols-1 lg:grid-cols-2 gap-8"> + <section class="space-y-4"> + <DashboardButton + title="Profile" + description="Edit user profile" + icon="/Person_Black.png" + path="/providers/profile" + /> + <DashboardButton + title="Create Scholarship" + description="Navigate to Scholarship Creation Page" + icon="/Create_Black.png" + path="/providers/scholarships" + /> + <DashboardButton + title="Applicants" + description="View Scholarship Applicants" + icon="/Form_Black.png" + path="/" + /> + </section> + <section class="space-y-4"> + <div class="rounded-lg shadow-lg/25 overflow-hidden"> + <div class="bg-red-900 text-white px-4 py-3 shadow-lg"> + <h3 class="text-white font-bold">Important Dates</h3> + </div> + <div class="p-2"> + <div class="flex flex-col p-3 gap-3"> + <DateList dates=dates_list /> + </div> + </div> + </div> + </section> + </div> + </div> </div> - </div> - </div> + </Authenticated> + </AuthLoaded> } } diff --git a/src/pages/scholarship_info.rs b/src/pages/scholarship_info.rs index b27953a..7a0628d 100644 --- a/src/pages/scholarship_info.rs +++ b/src/pages/scholarship_info.rs @@ -8,7 +8,7 @@ use leptos_router::hooks::{use_navigate, use_params}; use crate::common::{ExpandableInfo, ScholarshipFormParams, SubmitStatus, ValueType}; use crate::components::{ActionButton, Banner, ChipsList, Loading, OutlinedTextField, Panel, RadioList, Row, TextFieldType, Toast, ToastContext, ToastList, ValidatedForm}; use super::UnauthenticatedPage; -use crate::pages::utils::get_user_claims; +use crate::utils::get_user_claims; use super::api::{get_provider_scholarships, get_scholarship_info, CreateScholarshipInfo, RegisterScholarship, DeleteProviderScholarship, get_comparisons_categorized, CreateTestComparisons}; @@ -609,7 +609,7 @@ fn ScholarshipForm( items=vec![ "Write an essay describing your major/career direction. Include any abilities, interests, experiences, employment or clubs you have had that have affected your direction. If you are undecided, indicate why.", "Why is community service important? How has it personally affected you and your goals and what role do you hope to play in it in the future?", - "How has participation in sports been beneficial to your personal, academic, and emotional growth?" + "How has participation in sports been beneficial to your personal, academic, and emotional growth?", ] .iter() .map(|prompt| prompt.to_string()) diff --git a/src/pages/test_page.rs b/src/pages/test_page.rs index f3e1f28..008676f 100644 --- a/src/pages/test_page.rs +++ b/src/pages/test_page.rs @@ -2,27 +2,44 @@ use crate::components::DashboardButton; use leptos::prelude::*; #[component] -pub fn TestPage() -> impl IntoView { +pub fn TestPage() -> impl IntoView { view! { - <div class="p-6 space-y-4 max-w-1/3"> - <DashboardButton - title="Home Page" - description="Navigate to Home Page" - icon="Book.png" - path="/" - /> - <DashboardButton - title="Home Page" - description="Navigate to Home Page" - icon="Calendar.png" - path="/" - /> - <DashboardButton - title="Home Page" - description="Navigate to Home Page" - icon="Edit.png" - path="/" - /> + <div class="mx-auto px-6"> + <div class="container mx-auto px-6 py-8 space-y-8"> + <div class="grid grid-cols-1 lg:grid-cols-2 gap-8"> + <section class="space-y-4"> + <DashboardButton + title="Profile" + description="Edit user profile" + icon="/Person_Black.png" + path="/" + /> + <DashboardButton + title="Create Scholarship" + description="Navigate to Scholarship Creation Page" + icon="/Create_Black.png" + path="/" + /> + <DashboardButton + title="Applicants" + description="View Scholarship Applicants" + icon="/Form_Black.png" + path="/" + /> + </section> + <section class="space-y-2"> + <div class="rounded-lg shadow-lg/25 overflow-hidden"> + <div class="bg-red-900 text-white px-4 py-3 shadow-lg"> + <h3 class="text-white font-bold">Important Dates</h3> + </div> + <div class="p-2"> + <div class="flex flex-col p-3 gap-3"> + </div> + </div> + </div> + </section> + </div> + </div> </div> - } + }.into_any() } diff --git a/src/pages/unauthenticated_page.rs b/src/pages/unauthenticated_page.rs index 7de72e3..e2d6857 100644 --- a/src/pages/unauthenticated_page.rs +++ b/src/pages/unauthenticated_page.rs @@ -2,35 +2,43 @@ use crate::components::ActionButton; use leptos::logging::log; use leptos::prelude::*; use leptos_oidc::AuthSignal; +use leptos_router::hooks::{use_navigate, use_location}; #[component] pub fn UnauthenticatedPage() -> impl IntoView { let auth = use_context::<AuthSignal>().expect("AuthSignal not present in LoginLink"); - let login_url = move || { + let login_url = Memo::new(move |_| { auth.with(|auth| { auth.unauthenticated() .map(|unauthenticated| unauthenticated.login_url()) }) + }); + + Effect::new(move || log!("Generated login url: {:?}", login_url.get())); + + let navigate = use_navigate(); + let location = use_location(); + + let on_click = move |_| { + let current_path = location.pathname.get(); + + let storage_opt = window().session_storage().ok().flatten(); + if let Some(session_storage) = storage_opt { + let _ = session_storage.set_item("post_login_path", ¤t_path); + } + if let Some(url) = login_url.get() { + navigate(&url, Default::default()) + } }; - Effect::new(move || log!("Generated login url: {:?}", login_url())); - - let navigate = leptos_router::hooks::use_navigate(); - - view! ( + view! { <div class="flex h-screen justify-center items-center pb-50"> <div class="bg-white p-8 border rounded-lg shadow-lg"> - <h3> "You're not signed in. Please sign in with your Region 15 email." </h3> + <h3>"You're not signed in. Please sign in with your Region 15 email."</h3> <div class="flex pt-4 justify-center items-center"> - <ActionButton on:click=move |_| { - if let Some(url) = login_url() { - navigate(&url, Default::default()) - } - }> - "Sign in" - </ActionButton> + <ActionButton on:click=on_click>"Sign in"</ActionButton> </div> </div> </div> - ) + } } diff --git a/src/pages/utils.rs b/src/pages/utils.rs deleted file mode 100644 index 898ed2f..0000000 --- a/src/pages/utils.rs +++ /dev/null @@ -1,42 +0,0 @@ -use leptos::prelude::{use_context, Signal, With}; -use leptos_oidc::{Algorithm, AuthSignal, TokenData}; -use crate::common::UserClaims; - -/// # Server Utilities -/// -/// These utility functions can only be used from the server. They are created to use server-side -/// dependencies like the AWS SDK. Use of these functions will crash the front end, as these -/// dependencies cannot be compiled for WASM (nor should they be). -#[cfg(feature = "ssr")] -pub mod server_utils { - use std::collections::HashMap; - use aws_config::SdkConfig; - use crate::common::ValueType; - - /// Creates an [`SdkConfig`] struct for use with AWS SDK structs. - pub async fn create_aws_config() -> SdkConfig { - aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await - } - - /// Creates a DynamoDB client. - pub async fn create_dynamo_client() -> aws_sdk_dynamodb::Client { - aws_sdk_dynamodb::Client::new(&create_aws_config().await) - } - - pub fn into_attr_map(map: HashMap<String, ValueType>) -> HashMap<String, aws_sdk_dynamodb::types::AttributeValue> { - map.into_iter().map(|(k, v)| (k, v.into())).collect() - } -} - -/// Gets the current user claims. This function should only be used in an area that has -/// access to an AuthSignal, or it will result in a total failure. -pub fn get_user_claims() -> Signal<Option<TokenData<UserClaims>>> { - let auth = use_context::<AuthSignal>().expect("Couldn't find AuthSignal."); - Signal::derive(move || { - auth.with(|auth| { - auth.authenticated().and_then(|data| { - data.decoded_access_token::<UserClaims>(Algorithm::RS256, &["account"]) - }) - }) - }) -} diff --git a/src/utils/common.rs b/src/utils/common.rs new file mode 100644 index 0000000..a80584d --- /dev/null +++ b/src/utils/common.rs @@ -0,0 +1,33 @@ +use leptos::prelude::*; +use leptos_oidc::{Algorithm, AuthSignal, TokenData}; +use crate::common::UserClaims; + +pub fn use_origin() -> String { + #[cfg(target_arch = "wasm32")] { + use leptos::web_sys; + // Just get the current URL origin. + web_sys::window() + .unwrap() + .location() + .origin() + .unwrap_or("http://localhost:3000/".to_string()) + } + + #[cfg(not(target_arch = "wasm32"))] { + // Read the expected origin out of an environment variable. + std::env::var("LP_SITE_ORIGIN").unwrap_or("http://localhost:3000/".to_string()) + } +} + +/// Gets the current user claims. This function should only be used in an area that has +/// access to an AuthSignal, or it will result in a total failure. +pub fn get_user_claims() -> Signal<Option<TokenData<UserClaims>>> { + let auth = use_context::<AuthSignal>().expect("Couldn't find AuthSignal."); + Signal::derive(move || { + auth.with(|auth| { + auth.authenticated().and_then(|data| { + data.decoded_access_token::<UserClaims>(Algorithm::RS256, &["account"]) + }) + }) + }) +} diff --git a/src/utils/mod.rs b/src/utils/mod.rs new file mode 100644 index 0000000..93fe774 --- /dev/null +++ b/src/utils/mod.rs @@ -0,0 +1,5 @@ +#[cfg(feature = "ssr")] +pub mod server; + +mod common; +pub use common::*; \ No newline at end of file diff --git a/src/utils/server.rs b/src/utils/server.rs new file mode 100644 index 0000000..e6c5c9b --- /dev/null +++ b/src/utils/server.rs @@ -0,0 +1,17 @@ +use std::collections::HashMap; +use aws_config::SdkConfig; +use crate::common::ValueType; + +/// Creates an [`SdkConfig`] struct for use with AWS SDK structs. +pub async fn create_aws_config() -> SdkConfig { + aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await +} + +/// Creates a DynamoDB client. +pub async fn create_dynamo_client() -> aws_sdk_dynamodb::Client { + aws_sdk_dynamodb::Client::new(&create_aws_config().await) +} + +pub fn into_attr_map(map: HashMap<String, ValueType>) -> HashMap<String, aws_sdk_dynamodb::types::AttributeValue> { + map.into_iter().map(|(k, v)| (k, v.into())).collect() +} \ No newline at end of file