Skip to content

Commit

Permalink
mod: updating customers
Browse files Browse the repository at this point in the history
  • Loading branch information
bennjii committed Jan 14, 2024
1 parent 45fc363 commit 53ac67e
Show file tree
Hide file tree
Showing 5 changed files with 111 additions and 10 deletions.
21 changes: 21 additions & 0 deletions src/methods/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,27 @@ pub struct ContactInformation {
pub address: Address,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, Validate)]
pub struct ContactInformationInput {
pub name: String,
pub mobile: String,
pub email: String,
pub landline: String,
pub address: Address,
}

impl ContactInformationInput {
pub fn into_major(self) -> ContactInformation {
ContactInformation {
name: self.name,
email: Email::from(self.email),
mobile: MobileNumber::from(self.mobile),
landline: self.landline,
address: self.address
}
}
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, Validate)]
pub struct MobileNumber {
pub number: String,
Expand Down
18 changes: 17 additions & 1 deletion src/methods/customer/conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ impl CustomerInput {
id: Set(id),
name: Set(self.name),

contact: Set(json!(self.contact)),
contact: Set(json!(self.contact.into_major())),
customer_notes: Set(json!(self.customer_notes)),

balance: Set(self.balance),
Expand All @@ -28,6 +28,22 @@ impl CustomerInput {
updated_at: Set(Utc::now().naive_utc()),
}
}

pub(crate) fn from_existing(self, customer: Customer, tenant_id: String) -> ActiveModel {
ActiveModel {
id: Set(customer.id),
name: Set(self.name),

contact: Set(json!(self.contact.into_major())),
customer_notes: Set(json!(self.customer_notes)),
accepts_marketing: Set(self.accepts_marketing),
tenant_id: Set(tenant_id),

updated_at: Set(Utc::now().naive_utc()),

..Default::default()
}
}
}

impl Customer {
Expand Down
41 changes: 40 additions & 1 deletion src/methods/customer/handlers.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use okapi::openapi3::OpenApi;
use crate::check_permissions;
use crate::{check_permissions};
use crate::methods::{
cookie_status_wrapper, Action, ContactInformation, CustomerWithTransactionsOut, Error,
ErrorResponse, Transaction,
Expand All @@ -22,6 +22,7 @@ pub fn documented_routes(settings: &OpenApiSettings) -> (Vec<rocket::Route>, Ope
openapi_get_routes_spec![
settings:
get,
delete,
get_by_name,
get_by_phone,
get_by_addr,
Expand All @@ -31,6 +32,7 @@ pub fn documented_routes(settings: &OpenApiSettings) -> (Vec<rocket::Route>, Ope
generate,
search_query,
update_contact_info,
update_by_input,
find_related_transactions
]
}
Expand All @@ -53,6 +55,24 @@ pub async fn get(
}
}

#[openapi(tag = "Customer")]
#[post("/delete/<id>")]
pub async fn delete(
conn: Connection<Db>,
id: &str,
cookies: &CookieJar<'_>,
) -> Result<(), Error> {
let db = conn.into_inner();

let session = cookie_status_wrapper(&db, cookies).await?;
check_permissions!(session.clone(), Action::AccessAdminPanel);

match Customer::delete(id, session, &db).await {
Ok(_res) => Ok(()),
Err(err) => Err(ErrorResponse::db_err(err)),
}
}

#[openapi(tag = "Customer")]
#[get("/recent")]
pub async fn get_recent(
Expand Down Expand Up @@ -192,6 +212,25 @@ async fn update(
))
}

#[openapi(tag = "Customer")]
#[post("/input/<id>", data = "<input_data>")]
async fn update_by_input(
conn: Connection<Db>,
id: &str,
cookies: &CookieJar<'_>,
input_data: Validated<Json<CustomerInput>>,
) -> Result<Json<Customer>, Error> {
let input_data = input_data.clone().0.into_inner();
let db = conn.into_inner();

let session = cookie_status_wrapper(&db, cookies).await?;
check_permissions!(session.clone(), Action::ModifyCustomer);

Ok(Json(
Customer::update_by_input(input_data, session, id, &db).await?
))
}

#[openapi(tag = "Customer")]
#[post("/contact/<id>", data = "<input_data>")]
async fn update_contact_info(
Expand Down
39 changes: 32 additions & 7 deletions src/methods/customer/structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::entities::customer;
use crate::entities::prelude::Customer as Cust;
#[cfg(feature = "process")]
use crate::methods::convert_addr_to_geo;
use crate::methods::{Address, ContactInformation, Email, Id, MobileNumber, NoteList};
use crate::methods::{Address, ContactInformation, Id, NoteList};
#[cfg(feature = "process")]
use sea_orm::QueryFilter;
#[cfg(feature = "process")]
Expand All @@ -17,12 +17,12 @@ use sea_orm::{
ActiveModelTrait, ColumnTrait, DbBackend, DbConn, DbErr, EntityTrait, FromQueryResult,
InsertResult, JsonValue, QuerySelect, RuntimeErr, Set, Statement,
};
use sea_orm::QueryOrder;
use sea_orm::{DeleteResult, QueryOrder};
use serde::{Deserialize, Serialize};
use serde_json::json;
use validator::Validate;
use crate::entities::customer::ActiveModel;
use crate::Session;
use crate::{ContactInformationInput, Session};

#[cfg(feature = "types")]
#[derive(Serialize, Deserialize, Clone, JsonSchema, Validate)]
Expand Down Expand Up @@ -84,7 +84,7 @@ pub struct CustomerWithTransactionsOut {
pub struct CustomerInput {
pub name: String,

pub contact: ContactInformation,
pub contact: ContactInformationInput,
pub customer_notes: NoteList,

pub special_pricing: String,
Expand Down Expand Up @@ -192,6 +192,17 @@ impl Customer {
Ok(mapped)
}

pub async fn delete(id: &str, session: Session, db: &DbConn) -> Result<DeleteResult, DbErr> {
match crate::entities::customer::Entity::delete_by_id(id)
.filter(customer::Column::TenantId.eq(session.tenant_id))
.exec(db)
.await
{
Ok(res) => Ok(res),
Err(err) => Err(err),
}
}

pub async fn fetch_containing_contact(
value: &str,
session: Session,
Expand Down Expand Up @@ -255,6 +266,20 @@ impl Customer {
Customer::fetch_by_id(&r.last_insert_id, session, db).await
}

pub async fn update_by_input(
cust: CustomerInput,
session: Session,
id: &str,
db: &DbConn,
) -> Result<Customer, DbErr> {
let old_customer = Self::fetch_by_id(id, session.clone(), db).await?;
let customer = cust.from_existing(old_customer, session.tenant_id.clone());

Cust::update(customer).exec(db).await?;

Self::fetch_by_id(id, session, db).await
}

pub async fn update(
cust: Customer,
session: Session,
Expand Down Expand Up @@ -362,10 +387,10 @@ impl Display for Customer {
}

pub fn example_customer() -> CustomerInput {
let customer = ContactInformation {
let customer = ContactInformationInput {
name: "Carl Kennith".into(),
mobile: MobileNumber::from("0212121204".to_string()),
email: Email::from("[email protected]".to_string()),
mobile: "0212121204".to_string(),
email: "[email protected]".to_string(),
landline: "".into(),
address: Address {
street: "54 Arney Crescent".into(),
Expand Down
2 changes: 1 addition & 1 deletion src/methods/employee/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ pub async fn auth(
}
Err(reason) => {
println!("[dberr]: {}", reason);
Err(ErrorResponse::input_error())
Err(ErrorResponse::db_err(reason))
}
}
}
Expand Down

0 comments on commit 53ac67e

Please sign in to comment.