Skip to content

Commit

Permalink
feat(user): generate and delete sample data (#2987)
Browse files Browse the repository at this point in the history
Co-authored-by: Rachit Naithani <[email protected]>
Co-authored-by: Mani Chandra Dulam <[email protected]>
  • Loading branch information
3 people authored Dec 1, 2023
1 parent c4bd47e commit 092ec73
Show file tree
Hide file tree
Showing 22 changed files with 1,151 additions and 18 deletions.
5 changes: 5 additions & 0 deletions crates/api_models/src/events/user.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
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,
Expand Down Expand Up @@ -29,3 +31,6 @@ common_utils::impl_misc_api_event_type!(
CreateInternalUserRequest,
UserMerchantCreate
);

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

#[derive(serde::Deserialize, Debug, Clone, serde::Serialize)]
pub struct ConnectAccountRequest {
Expand Down
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>,
}
1 change: 1 addition & 0 deletions crates/diesel_models/src/query/user.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use diesel::{associations::HasTable, ExpressionMethods};
use error_stack::report;
use router_env::tracing::{self, instrument};
pub mod sample_data;

use crate::{
errors::{self},
Expand Down
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
119 changes: 119 additions & 0 deletions crates/diesel_models/src/user/sample_data.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
use common_enums::{
AttemptStatus, AuthenticationType, CaptureMethod, Currency, PaymentExperience, PaymentMethod,
PaymentMethodType,
};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;

use crate::{enums::MandateDataType, schema::payment_attempt, PaymentAttemptNew};

#[derive(
Clone, Debug, Default, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize,
)]
#[diesel(table_name = payment_attempt)]
pub struct PaymentAttemptBatchNew {
pub payment_id: String,
pub merchant_id: String,
pub attempt_id: String,
pub status: AttemptStatus,
pub amount: i64,
pub currency: Option<Currency>,
pub save_to_locker: Option<bool>,
pub connector: Option<String>,
pub error_message: Option<String>,
pub offer_amount: Option<i64>,
pub surcharge_amount: Option<i64>,
pub tax_amount: Option<i64>,
pub payment_method_id: Option<String>,
pub payment_method: Option<PaymentMethod>,
pub capture_method: Option<CaptureMethod>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub capture_on: Option<PrimitiveDateTime>,
pub confirm: bool,
pub authentication_type: Option<AuthenticationType>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub created_at: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub modified_at: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub cancellation_reason: Option<String>,
pub amount_to_capture: Option<i64>,
pub mandate_id: Option<String>,
pub browser_info: Option<serde_json::Value>,
pub payment_token: Option<String>,
pub error_code: Option<String>,
pub connector_metadata: Option<serde_json::Value>,
pub payment_experience: Option<PaymentExperience>,
pub payment_method_type: Option<PaymentMethodType>,
pub payment_method_data: Option<serde_json::Value>,
pub business_sub_label: Option<String>,
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
pub mandate_details: Option<MandateDataType>,
pub error_reason: Option<String>,
pub connector_response_reference_id: Option<String>,
pub connector_transaction_id: Option<String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: i64,
pub updated_by: String,
pub merchant_connector_id: Option<String>,
pub authentication_data: Option<serde_json::Value>,
pub encoded_data: Option<String>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
}

#[allow(dead_code)]
impl PaymentAttemptBatchNew {
// Used to verify compatibility with PaymentAttemptTable
fn convert_into_normal_attempt_insert(self) -> PaymentAttemptNew {
PaymentAttemptNew {
payment_id: self.payment_id,
merchant_id: self.merchant_id,
attempt_id: self.attempt_id,
status: self.status,
amount: self.amount,
currency: self.currency,
save_to_locker: self.save_to_locker,
connector: self.connector,
error_message: self.error_message,
offer_amount: self.offer_amount,
surcharge_amount: self.surcharge_amount,
tax_amount: self.tax_amount,
payment_method_id: self.payment_method_id,
payment_method: self.payment_method,
capture_method: self.capture_method,
capture_on: self.capture_on,
confirm: self.confirm,
authentication_type: self.authentication_type,
created_at: self.created_at,
modified_at: self.modified_at,
last_synced: self.last_synced,
cancellation_reason: self.cancellation_reason,
amount_to_capture: self.amount_to_capture,
mandate_id: self.mandate_id,
browser_info: self.browser_info,
payment_token: self.payment_token,
error_code: self.error_code,
connector_metadata: self.connector_metadata,
payment_experience: self.payment_experience,
payment_method_type: self.payment_method_type,
payment_method_data: self.payment_method_data,
business_sub_label: self.business_sub_label,
straight_through_algorithm: self.straight_through_algorithm,
preprocessing_step_id: self.preprocessing_step_id,
mandate_details: self.mandate_details,
error_reason: self.error_reason,
multiple_capture_count: self.multiple_capture_count,
connector_response_reference_id: self.connector_response_reference_id,
amount_capturable: self.amount_capturable,
updated_by: self.updated_by,
merchant_connector_id: self.merchant_connector_id,
authentication_data: self.authentication_data,
encoded_data: self.encoded_data,
unified_code: self.unified_code,
unified_message: self.unified_message,
}
}
}
1 change: 1 addition & 0 deletions crates/router/src/core/errors/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::services::ApplicationResponse;

pub type UserResult<T> = CustomResult<T, UserErrors>;
pub type UserResponse<T> = CustomResult<ApplicationResponse<T>, UserErrors>;
pub mod sample_data;

#[derive(Debug, thiserror::Error)]
pub enum UserErrors {
Expand Down
Loading

0 comments on commit 092ec73

Please sign in to comment.