Skip to content

Commit

Permalink
Merge branch 'main' into use-card-bin
Browse files Browse the repository at this point in the history
  • Loading branch information
hrithikesh026 authored Dec 3, 2023
2 parents ccca67d + ec15ddd commit 671db52
Show file tree
Hide file tree
Showing 32 changed files with 1,663 additions and 107 deletions.
10 changes: 8 additions & 2 deletions crates/api_models/src/events/user.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use common_utils::events::{ApiEventMetric, ApiEventsType};

#[cfg(feature = "dummy_connector")]
use crate::user::sample_data::SampleDataRequest;
use crate::user::{
dashboard_metadata::{
GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest,
},
ChangePasswordRequest, ConnectAccountRequest, ConnectAccountResponse,
CreateInternalUserRequest, SwitchMerchantIdRequest, UserMerchantCreate,
CreateInternalUserRequest, GetUsersResponse, SwitchMerchantIdRequest, UserMerchantCreate,
};

impl ApiEventMetric for ConnectAccountResponse {
Expand All @@ -27,5 +29,9 @@ common_utils::impl_misc_api_event_type!(
SetMetaDataRequest,
SwitchMerchantIdRequest,
CreateInternalUserRequest,
UserMerchantCreate
UserMerchantCreate,
GetUsersResponse
);

#[cfg(feature = "dummy_connector")]
common_utils::impl_misc_api_event_type!(SampleDataRequest);
19 changes: 19 additions & 0 deletions crates/api_models/src/user.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use common_utils::pii;
use masking::Secret;

use crate::user_role::UserStatus;
pub mod dashboard_metadata;
#[cfg(feature = "dummy_connector")]
pub mod sample_data;

#[derive(serde::Deserialize, Debug, Clone, serde::Serialize)]
pub struct ConnectAccountRequest {
Expand Down Expand Up @@ -43,3 +47,18 @@ pub struct CreateInternalUserRequest {
pub struct UserMerchantCreate {
pub company_name: String,
}

#[derive(Debug, serde::Serialize)]
pub struct GetUsersResponse(pub Vec<UserDetails>);

#[derive(Debug, serde::Serialize)]
pub struct UserDetails {
pub user_id: String,
pub email: pii::Email,
pub name: Secret<String>,
pub role_id: String,
pub role_name: String,
pub status: UserStatus,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub last_modified_at: time::PrimitiveDateTime,
}
23 changes: 23 additions & 0 deletions crates/api_models/src/user/sample_data.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use common_enums::{AuthenticationType, CountryAlpha2};
use common_utils::{self};
use time::PrimitiveDateTime;

use crate::enums::Connector;

#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct SampleDataRequest {
pub record: Option<usize>,
pub connector: Option<Vec<Connector>>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub start_time: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub end_time: Option<PrimitiveDateTime>,
// The amount for each sample will be between min_amount and max_amount (in dollars)
pub min_amount: Option<i64>,
pub max_amount: Option<i64>,
pub currency: Option<Vec<common_enums::Currency>>,
pub auth_type: Option<Vec<AuthenticationType>>,
pub business_country: Option<CountryAlpha2>,
pub business_label: Option<String>,
pub profile_id: Option<String>,
}
6 changes: 6 additions & 0 deletions crates/api_models/src/user_role.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,9 @@ pub struct UpdateUserRoleRequest {
pub user_id: String,
pub role_id: String,
}

#[derive(Debug, serde::Serialize)]
pub enum UserStatus {
Active,
InvitationSent,
}
30 changes: 29 additions & 1 deletion crates/diesel_models/src/query/dashboard_metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ use crate::{
enums,
query::generics,
schema::dashboard_metadata::dsl,
user::dashboard_metadata::{DashboardMetadata, DashboardMetadataNew},
user::dashboard_metadata::{
DashboardMetadata, DashboardMetadataNew, DashboardMetadataUpdate,
DashboardMetadataUpdateInternal,
},
PgPooledConn, StorageResult,
};

Expand All @@ -17,6 +20,31 @@ impl DashboardMetadataNew {
}

impl DashboardMetadata {
pub async fn update(
conn: &PgPooledConn,
user_id: Option<String>,
merchant_id: String,
org_id: String,
data_key: enums::DashboardMetadata,
dashboard_metadata_update: DashboardMetadataUpdate,
) -> StorageResult<Self> {
generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::user_id
.eq(user_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned()))
.and(dsl::org_id.eq(org_id.to_owned()))
.and(dsl::data_key.eq(data_key.to_owned())),
DashboardMetadataUpdateInternal::from(dashboard_metadata_update),
)
.await
}

pub async fn find_user_scoped_dashboard_metadata(
conn: &PgPooledConn,
user_id: String,
Expand Down
48 changes: 40 additions & 8 deletions crates/diesel_models/src/query/user.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
use diesel::{associations::HasTable, ExpressionMethods};
use error_stack::report;
use router_env::tracing::{self, instrument};
use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{
associations::HasTable, debug_query, result::Error as DieselError, ExpressionMethods,
JoinOnDsl, QueryDsl,
};
use error_stack::{report, IntoReport};
use router_env::{
logger,
tracing::{self, instrument},
};
pub mod sample_data;

use crate::{
errors::{self},
query::generics,
schema::users::dsl,
schema::{
user_roles::{self, dsl as user_roles_dsl},
users::dsl as users_dsl,
},
user::*,
user_role::UserRole,
PgPooledConn, StorageResult,
};

Expand All @@ -21,15 +33,15 @@ impl User {
pub async fn find_by_user_email(conn: &PgPooledConn, user_email: &str) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::email.eq(user_email.to_owned()),
users_dsl::email.eq(user_email.to_owned()),
)
.await
}

pub async fn find_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::user_id.eq(user_id.to_owned()),
users_dsl::user_id.eq(user_id.to_owned()),
)
.await
}
Expand All @@ -41,7 +53,7 @@ impl User {
) -> StorageResult<Self> {
generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::user_id.eq(user_id.to_owned()),
users_dsl::user_id.eq(user_id.to_owned()),
UserUpdateInternal::from(user),
)
.await?
Expand All @@ -55,8 +67,28 @@ impl User {
pub async fn delete_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
dsl::user_id.eq(user_id.to_owned()),
users_dsl::user_id.eq(user_id.to_owned()),
)
.await
}

pub async fn find_joined_users_and_roles_by_merchant_id(
conn: &PgPooledConn,
mid: &str,
) -> StorageResult<Vec<(Self, UserRole)>> {
let query = Self::table()
.inner_join(user_roles::table.on(user_roles_dsl::user_id.eq(users_dsl::user_id)))
.filter(user_roles_dsl::merchant_id.eq(mid.to_owned()));

logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());

query
.get_results_async::<(Self, UserRole)>(conn)
.await
.into_report()
.map_err(|err| match err.current_context() {
DieselError::NotFound => err.change_context(errors::DatabaseError::NotFound),
_ => err.change_context(errors::DatabaseError::Others),
})
}
}
139 changes: 139 additions & 0 deletions crates/diesel_models/src/query/user/sample_data.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{associations::HasTable, debug_query, ExpressionMethods, TextExpressionMethods};
use error_stack::{IntoReport, ResultExt};
use router_env::logger;

use crate::{
errors,
schema::{
payment_attempt::dsl as payment_attempt_dsl, payment_intent::dsl as payment_intent_dsl,
refund::dsl as refund_dsl,
},
user::sample_data::PaymentAttemptBatchNew,
PaymentAttempt, PaymentIntent, PaymentIntentNew, PgPooledConn, Refund, RefundNew,
StorageResult,
};

pub async fn insert_payment_intents(
conn: &PgPooledConn,
batch: Vec<PaymentIntentNew>,
) -> StorageResult<Vec<PaymentIntent>> {
let query = diesel::insert_into(<PaymentIntent>::table()).values(batch);

logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());

query
.get_results_async(conn)
.await
.into_report()
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while inserting payment intents")
}
pub async fn insert_payment_attempts(
conn: &PgPooledConn,
batch: Vec<PaymentAttemptBatchNew>,
) -> StorageResult<Vec<PaymentAttempt>> {
let query = diesel::insert_into(<PaymentAttempt>::table()).values(batch);

logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());

query
.get_results_async(conn)
.await
.into_report()
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while inserting payment attempts")
}

pub async fn insert_refunds(
conn: &PgPooledConn,
batch: Vec<RefundNew>,
) -> StorageResult<Vec<Refund>> {
let query = diesel::insert_into(<Refund>::table()).values(batch);

logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());

query
.get_results_async(conn)
.await
.into_report()
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while inserting refunds")
}

pub async fn delete_payment_intents(
conn: &PgPooledConn,
merchant_id: &str,
) -> StorageResult<Vec<PaymentIntent>> {
let query = diesel::delete(<PaymentIntent>::table())
.filter(payment_intent_dsl::merchant_id.eq(merchant_id.to_owned()))
.filter(payment_intent_dsl::payment_id.like("test_%"));

logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());

query
.get_results_async(conn)
.await
.into_report()
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting payment intents")
.and_then(|result| match result.len() {
n if n > 0 => {
logger::debug!("{n} records deleted");
Ok(result)
}
0 => Err(error_stack::report!(errors::DatabaseError::NotFound)
.attach_printable("No records deleted")),
_ => Ok(result),
})
}
pub async fn delete_payment_attempts(
conn: &PgPooledConn,
merchant_id: &str,
) -> StorageResult<Vec<PaymentAttempt>> {
let query = diesel::delete(<PaymentAttempt>::table())
.filter(payment_attempt_dsl::merchant_id.eq(merchant_id.to_owned()))
.filter(payment_attempt_dsl::payment_id.like("test_%"));

logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());

query
.get_results_async(conn)
.await
.into_report()
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting payment attempts")
.and_then(|result| match result.len() {
n if n > 0 => {
logger::debug!("{n} records deleted");
Ok(result)
}
0 => Err(error_stack::report!(errors::DatabaseError::NotFound)
.attach_printable("No records deleted")),
_ => Ok(result),
})
}

pub async fn delete_refunds(conn: &PgPooledConn, merchant_id: &str) -> StorageResult<Vec<Refund>> {
let query = diesel::delete(<Refund>::table())
.filter(refund_dsl::merchant_id.eq(merchant_id.to_owned()))
.filter(refund_dsl::payment_id.like("test_%"));

logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());

query
.get_results_async(conn)
.await
.into_report()
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting refunds")
.and_then(|result| match result.len() {
n if n > 0 => {
logger::debug!("{n} records deleted");
Ok(result)
}
0 => Err(error_stack::report!(errors::DatabaseError::NotFound)
.attach_printable("No records deleted")),
_ => Ok(result),
})
}
1 change: 1 addition & 0 deletions crates/diesel_models/src/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::schema::users;

pub mod dashboard_metadata;

pub mod sample_data;
#[derive(Clone, Debug, Identifiable, Queryable)]
#[diesel(table_name = users)]
pub struct User {
Expand Down
Loading

0 comments on commit 671db52

Please sign in to comment.