Skip to content

Commit

Permalink
fix: dimensions form on new page
Browse files Browse the repository at this point in the history
  • Loading branch information
ShubhranshuSanjeev committed Nov 20, 2024
1 parent 72209bb commit 5985e35
Show file tree
Hide file tree
Showing 10 changed files with 185 additions and 104 deletions.
26 changes: 24 additions & 2 deletions crates/context_aware_config/src/api/dimension/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@ use superposition_types::{result as superposition, TenantConfig, User};
use crate::{
api::dimension::{types::CreateReq, utils::get_dimension_usage_context_ids},
db::{
models::Dimension,
schema::{dimensions, dimensions::dsl::*},
self,
models::{self, Dimension},
schema::{
dimensions,
dimensions::dsl::{self, *},
},
},
helpers::validate_jsonschema,
};
Expand All @@ -28,6 +32,7 @@ pub fn endpoints() -> Scope {
Scope::new("")
.service(create)
.service(get)
.service(get_by_name)
.service(delete_dimension)
}

Expand Down Expand Up @@ -136,6 +141,23 @@ async fn get(
Ok(HttpResponse::Ok().json(dimensions_with_mandatory))
}

#[get("/{name}")]
async fn get_by_name(
db_conn: DbConnection,
path: Path<String>,
tenant_config: TenantConfig,
) -> superposition::Result<HttpResponse> {
let DbConnection(mut conn) = db_conn;
let name: String = path.into_inner().into();
let res = dsl::dimensions
.filter(db::schema::dimensions::dimension.eq(name))
.select(models::Dimension::as_select())
.get_result(&mut conn)?;
let is_mandatory = tenant_config.mandatory_dimensions.contains(&res.dimension);

Ok(HttpResponse::Ok().json(DimensionWithMandatory::new(res, is_mandatory)))
}

#[delete("/{name}")]
async fn delete_dimension(
path: Path<DeleteReq>,
Expand Down
35 changes: 25 additions & 10 deletions crates/frontend/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ use superposition_types::Config;

use crate::{
types::{
ConfigVersionListResponse, DefaultConfig, Dimension, ExperimentResponse,
ExperimentsResponse, FetchTypeTemplateResponse, FunctionResponse, ListFilters, TypeTemplate, Context,
ConfigVersionListResponse, Context, DefaultConfig, Dimension, ExperimentResponse,
ExperimentsResponse, FetchTypeTemplateResponse, FunctionResponse, ListFilters,
TypeTemplate,
},
utils::{
construct_request_headers, get_host, parse_json_response, request,
Expand Down Expand Up @@ -278,10 +279,7 @@ pub async fn fetch_types(
.map_err(err_handler)
}

pub async fn fetch_type(
tenant: &str,
name: &str,
) -> Result<TypeTemplate, ServerFnError> {
pub async fn fetch_type(tenant: &str, name: &str) -> Result<TypeTemplate, ServerFnError> {
let host = use_host_server();
let url = format!("{host}/types/{name}");
let err_handler = |e: String| ServerFnError::new(e.to_string());
Expand All @@ -298,10 +296,7 @@ pub async fn fetch_type(
.map_err(err_handler)
}

pub async fn fetch_context(
tenant: &str,
id: &str,
) -> Result<Context, ServerFnError> {
pub async fn fetch_context(tenant: &str, id: &str) -> Result<Context, ServerFnError> {
let host = use_host_server();
let url = format!("{host}/context/{id}");
let err_handler = |e: String| ServerFnError::new(e.to_string());
Expand Down Expand Up @@ -337,3 +332,23 @@ pub async fn fetch_default_config_key(
.await
.map_err(err_handler)
}

pub async fn fetch_dimension(
tenant: &str,
name: &str,
) -> Result<Dimension, ServerFnError> {
let host = use_host_server();
let url = format!("{host}/dimension/{name}");
let err_handler = |e: String| ServerFnError::new(e.to_string());
let response = request::<()>(
url,
reqwest::Method::GET,
None,
construct_request_headers(&[("x-tenant", &tenant)]).map_err(err_handler)?,
)
.await
.map_err(err_handler)?;
parse_json_response::<Dimension>(response)
.await
.map_err(err_handler)
}
22 changes: 11 additions & 11 deletions crates/frontend/src/components/dimension_form.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pub fn dimension_form<NF>(
#[prop(default = String::new())] dimension_type: String,
#[prop(default = Value::Null)] dimension_schema: Value,
#[prop(default = None)] function_name: Option<Value>,
#[prop(into, default = String::new())] class: String,
handle_submit: NF,
) -> impl IntoView
where
Expand Down Expand Up @@ -110,7 +111,7 @@ where
});
};
view! {
<form class="form-control w-full space-y-4 bg-white text-gray-700 font-mono">
<form class=format!("relative form-control space-y-4 text-gray-700 font-mono {}", class)>
<div class="form-control">
<label class="label">
<span class="label-text">Dimension</span>
Expand Down Expand Up @@ -141,14 +142,16 @@ where
} else {
dimension_type_rs.get()
};
let dimension_type_schema = SchemaType::Single(JsonSchemaType::from(&dimension_schema_rs.get()));
let dimension_type_schema = SchemaType::Single(
JsonSchemaType::from(&dimension_schema_rs.get()),
);
view! {
<div class="form-control">
<label class="label">
<span class="label-text">Set Schema</span>
</label>
<Dropdown
dropdown_width="w-100"
dropdown_width="w-full max-w-md"
dropdown_icon="".to_string()
dropdown_text=dimension_t
dropdown_direction=DropdownDirection::Down
Expand All @@ -166,7 +169,9 @@ where
class="mt-5 rounded-md resize-y w-full max-w-md pt-3"
schema_type=dimension_type_schema
value=dimension_schema_rs.get()
on_change=Callback::new(move |new_type_schema| dimension_schema_ws.set(new_type_schema))
on_change=Callback::new(move |new_type_schema| {
dimension_schema_ws.set(new_type_schema)
})
r#type=InputType::Monaco
/>
</EditorProvider>
Expand Down Expand Up @@ -258,16 +263,11 @@ where

</Suspense>

<div class="form-control grid w-full justify-start">
<div class="absolute bottom-0 right-0 p-4 flex justify-end items-end w-full bg-white">
{move || {
let loading = req_inprogess_rs.get();
view! {
<Button
class="pl-[70px] pr-[70px] w-48 h-12".to_string()
text="Submit".to_string()
on_click=on_submit.clone()
loading
/>
<Button text="Submit".to_string() on_click=on_submit.clone() loading />
}
}}

Expand Down
24 changes: 24 additions & 0 deletions crates/frontend/src/hoc/nav_breadcrums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,30 @@ static BREADCRUMB_STORE: Lazy<HashMap<String, RouteMetadata>> = Lazy::new(|| {
},
);

routes.insert(
"/dimensions/new".to_string(),
RouteMetadata {
default_label: "New".to_string(),
parent: Some("/dimensions".to_string()),
icon: None,
dynamic_label: None,
},
);

routes.insert(
"/dimensions/:name/update".to_string(),
RouteMetadata {
default_label: "Update Dimension".to_string(),
parent: Some("/dimensions".to_string()),
icon: None,
dynamic_label: Some(Box::new(Arc::new(|params| {
params
.get("name")
.map(|name| format!("Update {}", name))
}))),
},
);

// Functions
routes.insert(
"/function".to_string(),
Expand Down
2 changes: 2 additions & 0 deletions crates/frontend/src/pages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,5 @@ pub mod new_contextual_override;
pub mod update_contextual_override;
pub mod new_default_config;
pub mod update_default_config;
pub mod new_dimension;
pub mod update_dimension;
88 changes: 9 additions & 79 deletions crates/frontend/src/pages/dimensions.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use crate::components::dimension_form::DimensionForm;
use crate::components::drawer::{close_drawer, open_drawer, Drawer, DrawerBtn};
use crate::components::button::Button;
use crate::components::skeleton::Skeleton;
use crate::components::{
delete_modal::DeleteModal,
stat::Stat,
table::{types::Column, Table},
};
use leptos::*;
use leptos_router::A;
use serde_json::{json, Map, Value};

use crate::api::{delete_dimension, fetch_dimensions};
Expand Down Expand Up @@ -55,45 +55,18 @@ pub fn dimensions() -> impl IntoView {
delete_modal_visible_ws.set(false);
});

let selected_dimension = create_rw_signal::<Option<RowData>>(None);

let table_columns = create_memo(move |_| {
let action_col_formatter = move |_: &str, row: &Map<String, Value>| {
logging::log!("Dimension row: {:?}", row);
let row_dimension = row["dimension"].to_string().replace('"', "");
let row_priority_str = row["priority"].to_string().replace('"', "");
let row_priority = row_priority_str.parse::<u32>().unwrap_or(0_u32);

let schema = row["schema"].clone().to_string();
let schema = serde_json::from_str::<Value>(&schema).unwrap_or(Value::Null);

let function_name = row["function_name"].to_string();
let fun_name = match function_name.as_str() {
"null" => None,
_ => Some(json!(function_name.replace('"', ""))),
};
let mandatory = row["mandatory"].as_bool().unwrap_or(false);
let dimension_name = row_dimension.clone();

let edit_click_handler = move |_| {
let row_data = RowData {
dimension: row_dimension.clone(),
priority: row_priority.clone(),
schema: schema.clone(),
function_name: fun_name.clone(),
mandatory: mandatory.clone(),
};
logging::log!("{:?}", row_data);
selected_dimension.set(Some(row_data));
open_drawer("dimension_drawer");
};

if dimension_name.clone() == String::from("variantIds") {
view! {
<div class="join">
<span class="cursor-pointer" on:click=edit_click_handler>
<A href=format!("{row_dimension}/update")>
<i class="ri-pencil-line ri-xl text-blue-500"></i>
</span>
</A>
</div>
}
.into_view()
Expand All @@ -104,9 +77,9 @@ pub fn dimensions() -> impl IntoView {
};
view! {
<div class="join">
<span class="cursor-pointer" on:click=edit_click_handler>
<A href=format!("{row_dimension}/update")>
<i class="ri-pencil-line ri-xl text-blue-500"></i>
</span>
</A>
<span class="cursor-pointer text-red-500" on:click=handle_dimension_delete>
<i class="ri-delete-bin-5-line ri-xl text-red-500"></i>
</span>
Expand All @@ -128,48 +101,6 @@ pub fn dimensions() -> impl IntoView {
});

view! {
{move || {
let handle_close = move || {
close_drawer("dimension_drawer");
selected_dimension.set(None);
};
if let Some(selected_dimension_data) = selected_dimension.get() {
view! {
<Drawer
id="dimension_drawer".to_string()
header="Edit Dimension"
handle_close=handle_close
>
<DimensionForm
edit=true
priority=selected_dimension_data.priority
dimension_name=selected_dimension_data.dimension
dimension_schema=selected_dimension_data.schema
function_name=selected_dimension_data.function_name
handle_submit=move || {
dimensions_resource.refetch();
selected_dimension.set(None);
close_drawer("dimension_drawer");
}
/>

</Drawer>
}
} else {
view! {
<Drawer
id="dimension_drawer".to_string()
header="Create New Dimension"
handle_close=handle_close
>
<DimensionForm handle_submit=move || {
dimensions_resource.refetch();
close_drawer("dimension_drawer");
} />
</Drawer>
}
}
}}
<Suspense fallback=move || {
view! { <Skeleton /> }
}>
Expand Down Expand Up @@ -198,10 +129,9 @@ pub fn dimensions() -> impl IntoView {
<h2 class="card-title chat-bubble text-gray-800 dark:text-white bg-white font-mono">
"Dimensions"
</h2>
<DrawerBtn drawer_id="dimension_drawer"
.to_string()>
Create Dimension <i class="ri-edit-2-line ml-2"></i>
</DrawerBtn>
<A href="new">
<Button text="Create Key" on_click=move |_| {} />
</A>
</div>
<Table
cell_class="min-w-48 font-mono".to_string()
Expand Down
13 changes: 13 additions & 0 deletions crates/frontend/src/pages/new_dimension.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use leptos::*;

use crate::components::dimension_form::DimensionForm;

#[component]
pub fn new_dimension() -> impl IntoView {
view! {
<DimensionForm
handle_submit=move || {}
class="w-1/2 h-main-content p-8 rounded-2xl border bg-white overflow-y-auto mx-auto"
/>
}
}
Loading

0 comments on commit 5985e35

Please sign in to comment.