impl<V> ConstraintGraphBuilder<V>
where
    V: ValueNode,
{
    pub fn new() -> Self {
        Self {
            domain: DenseMap::new(),
            nodes: DenseMap::new(),
            edges: DenseMap::new(),
            domain_identifier_map: FxHashMap::default(),
            value_map: FxHashMap::default(),
            edges_map: FxHashMap::default(),
            node_info: DenseMap::new(),
            node_metadata: DenseMap::new(),
        }
    }

    pub fn build(self) -> ConstraintGraph<V> {
        ConstraintGraph {
            domain: self.domain,
            domain_identifier_map: self.domain_identifier_map,
            nodes: self.nodes,
            edges: self.edges,
            value_map: self.value_map,
            node_info: self.node_info,
            node_metadata: self.node_metadata,
        }
    }

    fn retrieve_domain_from_identifier(
        &self,
        domain_ident: DomainIdentifier,
    ) -> Result<DomainId, GraphError<V>> {
        self.domain_identifier_map
            .get(&domain_ident)
            .copied()
            .ok_or(GraphError::DomainNotFound)
    }

    pub fn make_domain(
        &mut self,
        domain_identifier: String,
        domain_description: &str,
    ) -> Result<DomainId, GraphError<V>> {
        let domain_identifier = DomainIdentifier::new(domain_identifier);
        Ok(self
            .domain_identifier_map
            .clone()
            .get(&domain_identifier)
            .map_or_else(
                || {
                    let domain_id = self.domain.push(DomainInfo {
                        domain_identifier: domain_identifier.clone(),
                        domain_description: domain_description.to_string(),
                    });
                    self.domain_identifier_map
                        .insert(domain_identifier, domain_id);
                    domain_id
                },
                |domain_id| *domain_id,
            ))
    }

    pub fn make_value_node<M: Metadata>(
        &mut self,
        value: NodeValue<V>,
        info: Option<&'static str>,
        metadata: Option<M>,
    ) -> NodeId {
        self.value_map.get(&value).copied().unwrap_or_else(|| {
            let node_id = self.nodes.push(Node::new(NodeType::Value(value.clone())));
            let _node_info_id = self.node_info.push(info);

            let _node_metadata_id = self
                .node_metadata
                .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) }));

            self.value_map.insert(value, node_id);
            node_id
        })
    }

    pub fn make_edge<T: Into<DomainIdOrIdentifier>>(
        &mut self,
        pred_id: NodeId,
        succ_id: NodeId,
        strength: Strength,
        relation: Relation,
        domain: Option<T>,
    ) -> Result<EdgeId, GraphError<V>> {
        self.ensure_node_exists(pred_id)?;
        self.ensure_node_exists(succ_id)?;
        let domain_id = domain
            .map(|d| match d.into() {
                DomainIdOrIdentifier::DomainIdentifier(ident) => {
                    self.retrieve_domain_from_identifier(ident)
                }
                DomainIdOrIdentifier::DomainId(domain_id) => {
                    self.ensure_domain_exists(domain_id).map(|_| domain_id)
                }
            })
            .transpose()?;
        self.edges_map
            .get(&(pred_id, succ_id, domain_id))
            .copied()
            .and_then(|edge_id| self.edges.get(edge_id).cloned().map(|edge| (edge_id, edge)))
            .map_or_else(
                || {
                    let edge_id = self.edges.push(Edge {
                        strength,
                        relation,
                        pred: pred_id,
                        succ: succ_id,
                        domain: domain_id,
                    });
                    self.edges_map
                        .insert((pred_id, succ_id, domain_id), edge_id);

                    let pred = self
                        .nodes
                        .get_mut(pred_id)
                        .ok_or(GraphError::NodeNotFound)?;
                    pred.succs.push(edge_id);

                    let succ = self
                        .nodes
                        .get_mut(succ_id)
                        .ok_or(GraphError::NodeNotFound)?;
                    succ.preds.push(edge_id);

                    Ok(edge_id)
                },
                |(edge_id, edge)| {
                    if edge.strength == strength && edge.relation == relation {
                        Ok(edge_id)
                    } else {
                        Err(GraphError::ConflictingEdgeCreated)
                    }
                },
            )
    }

    pub fn make_all_aggregator<M: Metadata>(
        &mut self,
        nodes: &[(NodeId, Relation, Strength)],
        info: Option<&'static str>,
        metadata: Option<M>,
        domain_id: Option<DomainId>,
    ) -> Result<NodeId, GraphError<V>> {
        nodes
            .iter()
            .try_for_each(|(node_id, _, _)| self.ensure_node_exists(*node_id))?;

        let aggregator_id = self.nodes.push(Node::new(NodeType::AllAggregator));
        let _aggregator_info_id = self.node_info.push(info);

        let _node_metadata_id = self
            .node_metadata
            .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) }));

        for (node_id, relation, strength) in nodes {
            self.make_edge(*node_id, aggregator_id, *strength, *relation, domain_id)?;
        }

        Ok(aggregator_id)
    }

    pub fn make_any_aggregator<M: Metadata>(
        &mut self,
        nodes: &[(NodeId, Relation, Strength)],
        info: Option<&'static str>,
        metadata: Option<M>,
        domain_id: Option<DomainId>,
    ) -> Result<NodeId, GraphError<V>> {
        nodes
            .iter()
            .try_for_each(|(node_id, _, _)| self.ensure_node_exists(*node_id))?;

        let aggregator_id = self.nodes.push(Node::new(NodeType::AnyAggregator));
        let _aggregator_info_id = self.node_info.push(info);

        let _node_metadata_id = self
            .node_metadata
            .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) }));

        for (node_id, relation, strength) in nodes {
            self.make_edge(*node_id, aggregator_id, *strength, *relation, domain_id)?;
        }

        Ok(aggregator_id)
    }

    pub fn make_in_aggregator<M: Metadata>(
        &mut self,
        values: Vec<V>,
        info: Option<&'static str>,
        metadata: Option<M>,
    ) -> Result<NodeId, GraphError<V>> {
        let key = values
            .first()
            .ok_or(GraphError::NoInAggregatorValues)?
            .get_key();

        for val in &values {
            if val.get_key() != key {
                Err(GraphError::MalformedGraph {
                    reason: "Values for 'In' aggregator not of same key".to_string(),
                })?;
            }
        }
        let node_id = self
            .nodes
            .push(Node::new(NodeType::InAggregator(FxHashSet::from_iter(
                values,
            ))));
        let _aggregator_info_id = self.node_info.push(info);

        let _node_metadata_id = self
            .node_metadata
            .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) }));

        Ok(node_id)
    }

    fn ensure_node_exists(&self, id: NodeId) -> Result<(), GraphError<V>> {
        if self.nodes.contains_key(id) {
            Ok(())
        } else {
            Err(GraphError::NodeNotFound)
        }
    }

    fn ensure_domain_exists(&self, id: DomainId) -> Result<(), GraphError<V>> {
        if self.domain.contains_key(id) {
            Ok(())
        } else {
            Err(GraphError::DomainNotFound)
        }
    }
}


pub struct AutomationConfigs {
    pub hs_base_url: Option<String>,
    pub hs_api_key: Option<String>,
    pub hs_api_keys: Option<String>,
    pub hs_webhook_url: Option<String>,
    pub hs_test_env: Option<String>,
    pub hs_test_browser: Option<String>,
    pub chrome_profile_path: Option<String>,
    pub firefox_profile_path: Option<String>,
    pub pypl_email: Option<String>,
    pub pypl_pass: Option<String>,
    pub gmail_email: Option<String>,
    pub gmail_pass: Option<String>,
    pub clearpay_email: Option<String>,
    pub clearpay_pass: Option<String>,
    pub configs_url: Option<String>,
    pub stripe_pub_key: Option<String>,
    pub testcases_path: Option<String>,
    pub bluesnap_gateway_merchant_id: Option<String>,
    pub globalpay_gateway_merchant_id: Option<String>,
    pub authorizedotnet_gateway_merchant_id: Option<String>,
    pub run_minimum_steps: Option<bool>,
    pub airwallex_merchant_name: Option<String>,
    pub adyen_bancontact_username: Option<String>,
    pub adyen_bancontact_pass: Option<String>,
}


File: crates/diesel_models/src/role.rs
 Public structs: 3

use common_utils::id_type;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;

use crate::{enums, schema::roles};

#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]
#[diesel(table_name = roles, primary_key(role_id), check_for_backend(diesel::pg::Pg))]
pub struct Role {
    pub role_name: String,
    pub role_id: String,
    pub merchant_id: Option<id_type::MerchantId>,
    pub org_id: id_type::OrganizationId,
    #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)]
    pub groups: Vec<enums::PermissionGroup>,
    pub scope: enums::RoleScope,
    pub created_at: PrimitiveDateTime,
    pub created_by: String,
    pub last_modified_at: PrimitiveDateTime,
    pub last_modified_by: String,
    pub entity_type: enums::EntityType,
    pub profile_id: Option<id_type::ProfileId>,
    pub tenant_id: id_type::TenantId,
}

#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = roles)]
pub struct RoleNew {
    pub role_name: String,
    pub role_id: String,
    pub merchant_id: Option<id_type::MerchantId>,
    pub org_id: id_type::OrganizationId,
    #[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)]
    pub groups: Vec<enums::PermissionGroup>,
    pub scope: enums::RoleScope,
    pub created_at: PrimitiveDateTime,
    pub created_by: String,
    pub last_modified_at: PrimitiveDateTime,
    pub last_modified_by: String,
    pub entity_type: enums::EntityType,
    pub profile_id: Option<id_type::ProfileId>,
    pub tenant_id: id_type::TenantId,
}

#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = roles)]
pub struct RoleUpdateInternal {
    groups: Option<Vec<enums::PermissionGroup>>,
    role_name: Option<String>,
    last_modified_by: String,
    last_modified_at: PrimitiveDateTime,
}

pub enum RoleUpdate {
    UpdateDetails {
        groups: Option<Vec<enums::PermissionGroup>>,
        role_name: Option<String>,
        last_modified_at: PrimitiveDateTime,
        last_modified_by: String,
    },
}

impl From<RoleUpdate> for RoleUpdateInternal {
    fn from(value: RoleUpdate) -> Self {
        match value {
            RoleUpdate::UpdateDetails {
                groups,
                role_name,
                last_modified_by,
                last_modified_at,
            } => Self {
                groups,
                role_name,
                last_modified_at,
                last_modified_by,
            },
        }
    }
}

#[derive(Clone, Debug)]
pub enum ListRolesByEntityPayload {
    Profile(id_type::MerchantId, id_type::ProfileId),
    Merchant(id_type::MerchantId),
    Organization,
}


impl ApiEvent {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        tenant_id: common_utils::id_type::TenantId,
        merchant_id: Option<common_utils::id_type::MerchantId>,
        api_flow: &impl FlowMetric,
        request_id: &RequestId,
        latency: u128,
        status_code: i64,
        request: serde_json::Value,
        response: Option<serde_json::Value>,
        hs_latency: Option<u128>,
        auth_type: AuthenticationType,
        error: Option<serde_json::Value>,
        event_type: ApiEventsType,
        http_req: &HttpRequest,
        http_method: &http::Method,
        infra_components: Option<serde_json::Value>,
    ) -> Self {
        Self {
            tenant_id,
            merchant_id,
            api_flow: api_flow.to_string(),
            created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,
            request_id: request_id.as_hyphenated().to_string(),
            latency,
            status_code,
            request: request.to_string(),
            response: response.map(|resp| resp.to_string()),
            auth_type,
            error,
            ip_addr: http_req
                .connection_info()
                .realip_remote_addr()
                .map(ToOwned::to_owned),
            user_agent: http_req
                .headers()
                .get("user-agent")
                .and_then(|user_agent_value| user_agent_value.to_str().ok().map(ToOwned::to_owned)),
            url_path: http_req.path().to_string(),
            event_type,
            hs_latency,
            http_method: http_method.to_string(),
            infra_components,
        }
    }
}


pub fn new() -> &'static Self {
        &Self {
            amount_converter: &StringMajorUnitForConnector,
            amount_converter_to_string_minor_unit: &StringMinorUnitForConnector,
            amount_converter_float_major_unit: &FloatMajorUnitForConnector,
        }
    }


impl RequiredFieldsForEnabledPaymentMethodTypes {
    fn perform_surcharge_calculation(
        self,
    ) -> RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes {
        // TODO: Perform surcharge calculation
        let details_with_surcharge = self
            .0
            .into_iter()
            .map(
                |payment_methods_enabled| RequiredFieldsAndSurchargeForEnabledPaymentMethodType {
                    payment_method_type: payment_methods_enabled.payment_method_type,
                    required_fields: payment_methods_enabled.required_fields,
                    payment_method_subtype: payment_methods_enabled.payment_method_subtype,
                    payment_experience: payment_methods_enabled.payment_experience,
                    surcharge: None,
                    connectors: payment_methods_enabled.connectors,
                },
            )
            .collect();

        RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes(details_with_surcharge)
    }
}


pub fn get_tax_on_surcharge(&self) -> Option<MinorUnit> {
        self.tax_on_surcharge
    }


pub fn new(
        payment_method: Option<String>,
        platform: Option<String>,
        browser_name: Option<String>,
        source: Option<String>,
        component: Option<String>,
        payment_experience: Option<String>,
        time_bucket: Option<String>,
    ) -> Self {
        Self {
            payment_method,
            platform,
            browser_name,
            source,
            component,
            payment_experience,
            time_bucket,
        }
    }


File: crates/router_env/src/cargo_workspace.rs
 Public functions: 2

/// Sets the `CARGO_WORKSPACE_MEMBERS` environment variable to include a comma-separated list of
/// names of all crates in the current cargo workspace.
///
/// This function should be typically called within build scripts, so that the environment variable
/// is available to the corresponding crate at compile time.
///
/// # Panics
///
/// Panics if running the `cargo metadata` command fails.
#[allow(clippy::expect_used)]
pub fn set_cargo_workspace_members_env() {
    use std::io::Write;

    let metadata = cargo_metadata::MetadataCommand::new()
        .exec()
        .expect("Failed to obtain cargo metadata");

    let workspace_members = metadata
        .workspace_packages()
        .iter()
        .map(|package| package.name.as_str())
        .collect::<Vec<_>>()
        .join(",");

    writeln!(
        &mut std::io::stdout(),
        "cargo:rustc-env=CARGO_WORKSPACE_MEMBERS={workspace_members}"
    )
    .expect("Failed to set `CARGO_WORKSPACE_MEMBERS` environment variable");
}

/// Verify that the cargo metadata workspace packages format matches that expected by
/// [`set_cargo_workspace_members_env`] to set the `CARGO_WORKSPACE_MEMBERS` environment variable.
///
/// This function should be typically called within build scripts, before the
/// [`set_cargo_workspace_members_env`] function is called.
///
/// # Panics
///
/// Panics if running the `cargo metadata` command fails, or if the workspace member package names
/// cannot be determined.
pub fn verify_cargo_metadata_format() {
    #[allow(clippy::expect_used)]
    let metadata = cargo_metadata::MetadataCommand::new()
        .exec()
        .expect("Failed to obtain cargo metadata");

    assert!(
        metadata
            .workspace_packages()
            .iter()
            .any(|package| package.name == env!("CARGO_PKG_NAME")),
        "Unable to determine workspace member package names from `cargo metadata`"
    );
}

/// Obtain the crates in the current cargo workspace as a `HashSet`.
///
/// This macro requires that [`set_cargo_workspace_members_env()`] function be called in the
/// build script of the crate where this macro is being called.
///
/// # Errors
///
/// Causes a compilation error if the `CARGO_WORKSPACE_MEMBERS` environment variable is unset.
#[macro_export]
macro_rules! cargo_workspace_members {
    () => {
        std::env!("CARGO_WORKSPACE_MEMBERS")
            .split(',')
            .collect::<std::collections::HashSet<&'static str>>()
    };
}


pub struct RedsysSyncRequest {
    #[serde(rename = "Ds_MerchantCode")]
    ds_merchant_code: Secret<String>,
    #[serde(rename = "Ds_Terminal")]
    ds_terminal: Secret<String>,
    #[serde(rename = "Ds_Order")]
    ds_order: String,
    #[serde(rename = "Ds_TransactionType")]
    ds_transaction_type: String,
}


impl common_utils::events::ApiEventMetric for EventRetrieveResponse {
    fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
        Some(common_utils::events::ApiEventsType::Events {
            merchant_id: self.event_information.merchant_id.clone(),
        })
    }
}

impl common_utils::events::ApiEventMetric for for EventRetrieveResponse


pub struct ArchipelPaymentsResponse {
    order: ArchipelOrderResponse,
    transaction_id: String,
    transaction_date: String,
    transaction_result: ArchipelPaymentStatus,
    error: Option<ArchipelErrorMessage>,
    financial_network_code: Option<String>,
    issuer_transaction_id: Option<String>,
    response_code: Option<String>,
    authorization_code: Option<String>,
    payment_account_reference: Option<Secret<String>>,
}


                "Viseu District" => Ok(Self::ViseuDistrict),
                "Évora District" => Ok(Self::EvoraDistrict),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for SwitzerlandStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "SwitzerlandStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Aargau" => Ok(Self::Aargau),
                "Appenzell Ausserrhoden" => Ok(Self::AppenzellAusserrhoden),
                "Appenzell Innerrhoden" => Ok(Self::AppenzellInnerrhoden),
                "Basel-Landschaft" => Ok(Self::BaselLandschaft),
                "Canton of Fribourg" => Ok(Self::CantonOfFribourg),
                "Canton of Geneva" => Ok(Self::CantonOfGeneva),
                "Canton of Jura" => Ok(Self::CantonOfJura),
                "Canton of Lucerne" => Ok(Self::CantonOfLucerne),
                "Canton of Neuchâtel" => Ok(Self::CantonOfNeuchatel),
                "Canton of Schaffhausen" => Ok(Self::CantonOfSchaffhausen),
                "Canton of Solothurn" => Ok(Self::CantonOfSolothurn),
                "Canton of St. Gallen" => Ok(Self::CantonOfStGallen),
                "Canton of Valais" => Ok(Self::CantonOfValais),
                "Canton of Vaud" => Ok(Self::CantonOfVaud),
                "Canton of Zug" => Ok(Self::CantonOfZug),
                "Glarus" => Ok(Self::Glarus),
                "Graubünden" => Ok(Self::Graubunden),
                "Nidwalden" => Ok(Self::Nidwalden),
                "Obwalden" => Ok(Self::Obwalden),
                "Schwyz" => Ok(Self::Schwyz),
                "Thurgau" => Ok(Self::Thurgau),
                "Ticino" => Ok(Self::Ticino),
                "Uri" => Ok(Self::Uri),
                "canton of Bern" => Ok(Self::CantonOfBern),
                "canton of Zürich" => Ok(Self::CantonOfZurich),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for NorthMacedoniaStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "NorthMacedoniaStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Aerodrom Municipality" => Ok(Self::AerodromMunicipality),
                "Aračinovo Municipality" => Ok(Self::AracinovoMunicipality),
                "Berovo Municipality" => Ok(Self::BerovoMunicipality),
                "Bitola Municipality" => Ok(Self::BitolaMunicipality),
                "Bogdanci Municipality" => Ok(Self::BogdanciMunicipality),
                "Bogovinje Municipality" => Ok(Self::BogovinjeMunicipality),
                "Bosilovo Municipality" => Ok(Self::BosilovoMunicipality),
                "Brvenica Municipality" => Ok(Self::BrvenicaMunicipality),
                "Butel Municipality" => Ok(Self::ButelMunicipality),
                "Centar Municipality" => Ok(Self::CentarMunicipality),
                "Centar Župa Municipality" => Ok(Self::CentarZupaMunicipality),
                "Debarca Municipality" => Ok(Self::DebarcaMunicipality),
                "Delčevo Municipality" => Ok(Self::DelcevoMunicipality),
                "Demir Hisar Municipality" => Ok(Self::DemirHisarMunicipality),
                "Demir Kapija Municipality" => Ok(Self::DemirKapijaMunicipality),
                "Dojran Municipality" => Ok(Self::DojranMunicipality),
                "Dolneni Municipality" => Ok(Self::DolneniMunicipality),
                "Drugovo Municipality" => Ok(Self::DrugovoMunicipality),
                "Gazi Baba Municipality" => Ok(Self::GaziBabaMunicipality),
                "Gevgelija Municipality" => Ok(Self::GevgelijaMunicipality),
                "Gjorče Petrov Municipality" => Ok(Self::GjorcePetrovMunicipality),
                "Gostivar Municipality" => Ok(Self::GostivarMunicipality),
                "Gradsko Municipality" => Ok(Self::GradskoMunicipality),
                "Greater Skopje" => Ok(Self::GreaterSkopje),
                "Ilinden Municipality" => Ok(Self::IlindenMunicipality),
                "Jegunovce Municipality" => Ok(Self::JegunovceMunicipality),
                "Karbinci" => Ok(Self::Karbinci),
                "Karpoš Municipality" => Ok(Self::KarposMunicipality),
                "Kavadarci Municipality" => Ok(Self::KavadarciMunicipality),
                "Kisela Voda Municipality" => Ok(Self::KiselaVodaMunicipality),
                "Kičevo Municipality" => Ok(Self::KicevoMunicipality),
                "Konče Municipality" => Ok(Self::KonceMunicipality),
                "Kočani Municipality" => Ok(Self::KocaniMunicipality),
                "Kratovo Municipality" => Ok(Self::KratovoMunicipality),
                "Kriva Palanka Municipality" => Ok(Self::KrivaPalankaMunicipality),
                "Krivogaštani Municipality" => Ok(Self::KrivogastaniMunicipality),
                "Kruševo Municipality" => Ok(Self::KrusevoMunicipality),
                "Kumanovo Municipality" => Ok(Self::KumanovoMunicipality),
                "Lipkovo Municipality" => Ok(Self::LipkovoMunicipality),
                "Lozovo Municipality" => Ok(Self::LozovoMunicipality),
                "Makedonska Kamenica Municipality" => Ok(Self::MakedonskaKamenicaMunicipality),
                "Makedonski Brod Municipality" => Ok(Self::MakedonskiBrodMunicipality),
                "Mavrovo and Rostuša Municipality" => Ok(Self::MavrovoAndRostusaMunicipality),
                "Mogila Municipality" => Ok(Self::MogilaMunicipality),
                "Negotino Municipality" => Ok(Self::NegotinoMunicipality),
                "Novaci Municipality" => Ok(Self::NovaciMunicipality),
                "Novo Selo Municipality" => Ok(Self::NovoSeloMunicipality),
                "Ohrid Municipality" => Ok(Self::OhridMunicipality),
                "Oslomej Municipality" => Ok(Self::OslomejMunicipality),
                "Pehčevo Municipality" => Ok(Self::PehcevoMunicipality),
                "Petrovec Municipality" => Ok(Self::PetrovecMunicipality),
                "Plasnica Municipality" => Ok(Self::PlasnicaMunicipality),
                "Prilep Municipality" => Ok(Self::PrilepMunicipality),
                "Probištip Municipality" => Ok(Self::ProbishtipMunicipality),
                "Radoviš Municipality" => Ok(Self::RadovisMunicipality),
                "Rankovce Municipality" => Ok(Self::RankovceMunicipality),
                "Resen Municipality" => Ok(Self::ResenMunicipality),
                "Rosoman Municipality" => Ok(Self::RosomanMunicipality),
                "Saraj Municipality" => Ok(Self::SarajMunicipality),
                "Sopište Municipality" => Ok(Self::SopisteMunicipality),
                "Staro Nagoričane Municipality" => Ok(Self::StaroNagoricaneMunicipality),
                "Struga Municipality" => Ok(Self::StrugaMunicipality),
                "Strumica Municipality" => Ok(Self::StrumicaMunicipality),
                "Studeničani Municipality" => Ok(Self::StudenicaniMunicipality),
                "Sveti Nikole Municipality" => Ok(Self::SvetiNikoleMunicipality),
                "Tearce Municipality" => Ok(Self::TearceMunicipality),
                "Tetovo Municipality" => Ok(Self::TetovoMunicipality),
                "Valandovo Municipality" => Ok(Self::ValandovoMunicipality),
                "Vasilevo Municipality" => Ok(Self::VasilevoMunicipality),
                "Veles Municipality" => Ok(Self::VelesMunicipality),
                "Vevčani Municipality" => Ok(Self::VevcaniMunicipality),
                "Vinica Municipality" => Ok(Self::VinicaMunicipality),
                "Vraneštica Municipality" => Ok(Self::VranesticaMunicipality),
                "Vrapčište Municipality" => Ok(Self::VrapcisteMunicipality),
                "Zajas Municipality" => Ok(Self::ZajasMunicipality),
                "Zelenikovo Municipality" => Ok(Self::ZelenikovoMunicipality),
                "Zrnovci Municipality" => Ok(Self::ZrnovciMunicipality),
                "Čair Municipality" => Ok(Self::CairMunicipality),
                "Čaška Municipality" => Ok(Self::CaskaMunicipality),
                "Češinovo-Obleševo Municipality" => Ok(Self::CesinovoOblesevoMunicipality),
                "Čučer-Sandevo Municipality" => Ok(Self::CucerSandevoMunicipality),
                "Štip Municipality" => Ok(Self::StipMunicipality),
                "Šuto Orizari Municipality" => Ok(Self::ShutoOrizariMunicipality),
                "Želino Municipality" => Ok(Self::ZelinoMunicipality),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for MontenegroStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "MontenegroStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Andrijevica Municipality" => Ok(Self::AndrijevicaMunicipality),
                "Bar Municipality" => Ok(Self::BarMunicipality),
                "Berane Municipality" => Ok(Self::BeraneMunicipality),
                "Bijelo Polje Municipality" => Ok(Self::BijeloPoljeMunicipality),
                "Budva Municipality" => Ok(Self::BudvaMunicipality),
                "Danilovgrad Municipality" => Ok(Self::DanilovgradMunicipality),
                "Gusinje Municipality" => Ok(Self::GusinjeMunicipality),
                "Kolašin Municipality" => Ok(Self::KolasinMunicipality),
                "Kotor Municipality" => Ok(Self::KotorMunicipality),
                "Mojkovac Municipality" => Ok(Self::MojkovacMunicipality),
                "Nikšić Municipality" => Ok(Self::NiksicMunicipality),
                "Petnjica Municipality" => Ok(Self::PetnjicaMunicipality),
                "Plav Municipality" => Ok(Self::PlavMunicipality),
                "Pljevlja Municipality" => Ok(Self::PljevljaMunicipality),
                "Plužine Municipality" => Ok(Self::PlužineMunicipality),
                "Podgorica Municipality" => Ok(Self::PodgoricaMunicipality),
                "Rožaje Municipality" => Ok(Self::RožajeMunicipality),
                "Tivat Municipality" => Ok(Self::TivatMunicipality),
                "Ulcinj Municipality" => Ok(Self::UlcinjMunicipality),
                "Žabljak Municipality" => Ok(Self::ŽabljakMunicipality),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for MonacoStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "MonacoStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Monaco" => Ok(Self::Monaco),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for NetherlandsStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "NetherlandsStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Bonaire" => Ok(Self::Bonaire),
                "Drenthe" => Ok(Self::Drenthe),
                "Flevoland" => Ok(Self::Flevoland),
                "Friesland" => Ok(Self::Friesland),
                "Gelderland" => Ok(Self::Gelderland),
                "Groningen" => Ok(Self::Groningen),
                "Limburg" => Ok(Self::Limburg),
                "North Brabant" => Ok(Self::NorthBrabant),
                "North Holland" => Ok(Self::NorthHolland),
                "Overijssel" => Ok(Self::Overijssel),
                "Saba" => Ok(Self::Saba),
                "Sint Eustatius" => Ok(Self::SintEustatius),
                "South Holland" => Ok(Self::SouthHolland),
                "Utrecht" => Ok(Self::Utrecht),
                "Zeeland" => Ok(Self::Zeeland),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for MoldovaStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "MoldovaStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Anenii Noi District" => Ok(Self::AneniiNoiDistrict),
                "Basarabeasca District" => Ok(Self::BasarabeascaDistrict),
                "Bender Municipality" => Ok(Self::BenderMunicipality),
                "Briceni District" => Ok(Self::BriceniDistrict),
                "Bălți Municipality" => Ok(Self::BălțiMunicipality),
                "Cahul District" => Ok(Self::CahulDistrict),
                "Cantemir District" => Ok(Self::CantemirDistrict),
                "Chișinău Municipality" => Ok(Self::ChișinăuMunicipality),
                "Cimișlia District" => Ok(Self::CimișliaDistrict),
                "Criuleni District" => Ok(Self::CriuleniDistrict),
                "Călărași District" => Ok(Self::CălărașiDistrict),
                "Căușeni District" => Ok(Self::CăușeniDistrict),
                "Dondușeni District" => Ok(Self::DondușeniDistrict),
                "Drochia District" => Ok(Self::DrochiaDistrict),
                "Dubăsari District" => Ok(Self::DubăsariDistrict),
                "Edineț District" => Ok(Self::EdinețDistrict),
                "Florești District" => Ok(Self::FloreștiDistrict),
                "Fălești District" => Ok(Self::FăleștiDistrict),
                "Găgăuzia" => Ok(Self::Găgăuzia),
                "Glodeni District" => Ok(Self::GlodeniDistrict),
                "Hîncești District" => Ok(Self::HînceștiDistrict),
                "Ialoveni District" => Ok(Self::IaloveniDistrict),
                "Nisporeni District" => Ok(Self::NisporeniDistrict),
                "Ocnița District" => Ok(Self::OcnițaDistrict),
                "Orhei District" => Ok(Self::OrheiDistrict),
                "Rezina District" => Ok(Self::RezinaDistrict),
                "Rîșcani District" => Ok(Self::RîșcaniDistrict),
                "Soroca District" => Ok(Self::SorocaDistrict),
                "Strășeni District" => Ok(Self::StrășeniDistrict),
                "Sîngerei District" => Ok(Self::SîngereiDistrict),
                "Taraclia District" => Ok(Self::TaracliaDistrict),
                "Telenești District" => Ok(Self::TeleneștiDistrict),
                "Transnistria Autonomous Territorial Unit" => {
                    Ok(Self::TransnistriaAutonomousTerritorialUnit)
                }
                "Ungheni District" => Ok(Self::UngheniDistrict),
                "Șoldănești District" => Ok(Self::ȘoldăneștiDistrict),
                "Ștefan Vodă District" => Ok(Self::ȘtefanVodăDistrict),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for LithuaniaStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "LithuaniaStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Akmenė District Municipality" => Ok(Self::AkmeneDistrictMunicipality),
                "Alytus City Municipality" => Ok(Self::AlytusCityMunicipality),
                "Alytus County" => Ok(Self::AlytusCounty),
                "Alytus District Municipality" => Ok(Self::AlytusDistrictMunicipality),
                "Birštonas Municipality" => Ok(Self::BirstonasMunicipality),
                "Biržai District Municipality" => Ok(Self::BirzaiDistrictMunicipality),
                "Druskininkai municipality" => Ok(Self::DruskininkaiMunicipality),
                "Elektrėnai municipality" => Ok(Self::ElektrenaiMunicipality),
                "Ignalina District Municipality" => Ok(Self::IgnalinaDistrictMunicipality),
                "Jonava District Municipality" => Ok(Self::JonavaDistrictMunicipality),
                "Joniškis District Municipality" => Ok(Self::JoniskisDistrictMunicipality),
                "Jurbarkas District Municipality" => Ok(Self::JurbarkasDistrictMunicipality),
                "Kaišiadorys District Municipality" => Ok(Self::KaisiadorysDistrictMunicipality),
                "Kalvarija municipality" => Ok(Self::KalvarijaMunicipality),
                "Kaunas City Municipality" => Ok(Self::KaunasCityMunicipality),
                "Kaunas County" => Ok(Self::KaunasCounty),
                "Kaunas District Municipality" => Ok(Self::KaunasDistrictMunicipality),
                "Kazlų Rūda municipality" => Ok(Self::KazluRudaMunicipality),
                "Kelmė District Municipality" => Ok(Self::KelmeDistrictMunicipality),
                "Klaipeda City Municipality" => Ok(Self::KlaipedaCityMunicipality),
                "Klaipėda County" => Ok(Self::KlaipedaCounty),
                "Klaipėda District Municipality" => Ok(Self::KlaipedaDistrictMunicipality),
                "Kretinga District Municipality" => Ok(Self::KretingaDistrictMunicipality),
                "Kupiškis District Municipality" => Ok(Self::KupiskisDistrictMunicipality),
                "Kėdainiai District Municipality" => Ok(Self::KedainiaiDistrictMunicipality),
                "Lazdijai District Municipality" => Ok(Self::LazdijaiDistrictMunicipality),
                "Marijampolė County" => Ok(Self::MarijampoleCounty),
                "Marijampolė Municipality" => Ok(Self::MarijampoleMunicipality),
                "Mažeikiai District Municipality" => Ok(Self::MazeikiaiDistrictMunicipality),
                "Molėtai District Municipality" => Ok(Self::MoletaiDistrictMunicipality),
                "Neringa Municipality" => Ok(Self::NeringaMunicipality),
                "Pagėgiai municipality" => Ok(Self::PagegiaiMunicipality),
                "Pakruojis District Municipality" => Ok(Self::PakruojisDistrictMunicipality),
                "Palanga City Municipality" => Ok(Self::PalangaCityMunicipality),
                "Panevėžys City Municipality" => Ok(Self::PanevezysCityMunicipality),
                "Panevėžys County" => Ok(Self::PanevezysCounty),
                "Panevėžys District Municipality" => Ok(Self::PanevezysDistrictMunicipality),
                "Pasvalys District Municipality" => Ok(Self::PasvalysDistrictMunicipality),
                "Plungė District Municipality" => Ok(Self::PlungeDistrictMunicipality),
                "Prienai District Municipality" => Ok(Self::PrienaiDistrictMunicipality),
                "Radviliškis District Municipality" => Ok(Self::RadviliskisDistrictMunicipality),
                "Raseiniai District Municipality" => Ok(Self::RaseiniaiDistrictMunicipality),
                "Rietavas municipality" => Ok(Self::RietavasMunicipality),
                "Rokiškis District Municipality" => Ok(Self::RokiskisDistrictMunicipality),
                "Skuodas District Municipality" => Ok(Self::SkuodasDistrictMunicipality),
                "Tauragė County" => Ok(Self::TaurageCounty),
                "Tauragė District Municipality" => Ok(Self::TaurageDistrictMunicipality),
                "Telšiai County" => Ok(Self::TelsiaiCounty),
                "Telšiai District Municipality" => Ok(Self::TelsiaiDistrictMunicipality),
                "Trakai District Municipality" => Ok(Self::TrakaiDistrictMunicipality),
                "Ukmergė District Municipality" => Ok(Self::UkmergeDistrictMunicipality),
                "Utena County" => Ok(Self::UtenaCounty),
                "Utena District Municipality" => Ok(Self::UtenaDistrictMunicipality),
                "Varėna District Municipality" => Ok(Self::VarenaDistrictMunicipality),
                "Vilkaviškis District Municipality" => Ok(Self::VilkaviskisDistrictMunicipality),
                "Vilnius City Municipality" => Ok(Self::VilniusCityMunicipality),
                "Vilnius County" => Ok(Self::VilniusCounty),
                "Vilnius District Municipality" => Ok(Self::VilniusDistrictMunicipality),
                "Visaginas Municipality" => Ok(Self::VisaginasMunicipality),
                "Zarasai District Municipality" => Ok(Self::ZarasaiDistrictMunicipality),
                "Šakiai District Municipality" => Ok(Self::SakiaiDistrictMunicipality),
                "Šalčininkai District Municipality" => Ok(Self::SalcininkaiDistrictMunicipality),
                "Šiauliai City Municipality" => Ok(Self::SiauliaiCityMunicipality),
                "Šiauliai County" => Ok(Self::SiauliaiCounty),
                "Šiauliai District Municipality" => Ok(Self::SiauliaiDistrictMunicipality),
                "Šilalė District Municipality" => Ok(Self::SilaleDistrictMunicipality),
                "Šilutė District Municipality" => Ok(Self::SiluteDistrictMunicipality),
                "Širvintos District Municipality" => Ok(Self::SirvintosDistrictMunicipality),
                "Švenčionys District Municipality" => Ok(Self::SvencionysDistrictMunicipality),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for LiechtensteinStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "LiechtensteinStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Balzers" => Ok(Self::Balzers),
                "Eschen" => Ok(Self::Eschen),
                "Gamprin" => Ok(Self::Gamprin),
                "Mauren" => Ok(Self::Mauren),
                "Planken" => Ok(Self::Planken),
                "Ruggell" => Ok(Self::Ruggell),
                "Schaan" => Ok(Self::Schaan),
                "Schellenberg" => Ok(Self::Schellenberg),
                "Triesen" => Ok(Self::Triesen),
                "Triesenberg" => Ok(Self::Triesenberg),
                "Vaduz" => Ok(Self::Vaduz),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for LatviaStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "LatviaStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Aglona Municipality" => Ok(Self::AglonaMunicipality),
                "Aizkraukle Municipality" => Ok(Self::AizkraukleMunicipality),
                "Aizpute Municipality" => Ok(Self::AizputeMunicipality),
                "Aknīste Municipality" => Ok(Self::AknīsteMunicipality),
                "Aloja Municipality" => Ok(Self::AlojaMunicipality),
                "Alsunga Municipality" => Ok(Self::AlsungaMunicipality),
                "Alūksne Municipality" => Ok(Self::AlūksneMunicipality),
                "Amata Municipality" => Ok(Self::AmataMunicipality),
                "Ape Municipality" => Ok(Self::ApeMunicipality),
                "Auce Municipality" => Ok(Self::AuceMunicipality),
                "Babīte Municipality" => Ok(Self::BabīteMunicipality),
                "Baldone Municipality" => Ok(Self::BaldoneMunicipality),
                "Baltinava Municipality" => Ok(Self::BaltinavaMunicipality),
                "Balvi Municipality" => Ok(Self::BalviMunicipality),
                "Bauska Municipality" => Ok(Self::BauskaMunicipality),
                "Beverīna Municipality" => Ok(Self::BeverīnaMunicipality),
                "Brocēni Municipality" => Ok(Self::BrocēniMunicipality),
                "Burtnieki Municipality" => Ok(Self::BurtniekiMunicipality),
                "Carnikava Municipality" => Ok(Self::CarnikavaMunicipality),
                "Cesvaine Municipality" => Ok(Self::CesvaineMunicipality),
                "Cibla Municipality" => Ok(Self::CiblaMunicipality),
                "Cēsis Municipality" => Ok(Self::CēsisMunicipality),
                "Dagda Municipality" => Ok(Self::DagdaMunicipality),
                "Daugavpils" => Ok(Self::Daugavpils),
                "Daugavpils Municipality" => Ok(Self::DaugavpilsMunicipality),
                "Dobele Municipality" => Ok(Self::DobeleMunicipality),
                "Dundaga Municipality" => Ok(Self::DundagaMunicipality),
                "Durbe Municipality" => Ok(Self::DurbeMunicipality),
                "Engure Municipality" => Ok(Self::EngureMunicipality),
                "Garkalne Municipality" => Ok(Self::GarkalneMunicipality),
                "Grobiņa Municipality" => Ok(Self::GrobiņaMunicipality),
                "Gulbene Municipality" => Ok(Self::GulbeneMunicipality),
                "Iecava Municipality" => Ok(Self::IecavaMunicipality),
                "Ikšķile Municipality" => Ok(Self::IkšķileMunicipality),
                "Ilūkste Municipalityy" => Ok(Self::IlūksteMunicipality),
                "Inčukalns Municipality" => Ok(Self::InčukalnsMunicipality),
                "Jaunjelgava Municipality" => Ok(Self::JaunjelgavaMunicipality),
                "Jaunpiebalga Municipality" => Ok(Self::JaunpiebalgaMunicipality),
                "Jaunpils Municipality" => Ok(Self::JaunpilsMunicipality),
                "Jelgava" => Ok(Self::Jelgava),
                "Jelgava Municipality" => Ok(Self::JelgavaMunicipality),
                "Jēkabpils" => Ok(Self::Jēkabpils),
                "Jēkabpils Municipality" => Ok(Self::JēkabpilsMunicipality),
                "Jūrmala" => Ok(Self::Jūrmala),
                "Kandava Municipality" => Ok(Self::KandavaMunicipality),
                "Kocēni Municipality" => Ok(Self::KocēniMunicipality),
                "Koknese Municipality" => Ok(Self::KokneseMunicipality),
                "Krimulda Municipality" => Ok(Self::KrimuldaMunicipality),
                "Krustpils Municipality" => Ok(Self::KrustpilsMunicipality),
                "Krāslava Municipality" => Ok(Self::KrāslavaMunicipality),
                "Kuldīga Municipality" => Ok(Self::KuldīgaMunicipality),
                "Kārsava Municipality" => Ok(Self::KārsavaMunicipality),
                "Lielvārde Municipality" => Ok(Self::LielvārdeMunicipality),
                "Liepāja" => Ok(Self::Liepāja),
                "Limbaži Municipality" => Ok(Self::LimbažiMunicipality),
                "Lubāna Municipality" => Ok(Self::LubānaMunicipality),
                "Ludza Municipality" => Ok(Self::LudzaMunicipality),
                "Līgatne Municipality" => Ok(Self::LīgatneMunicipality),
                "Līvāni Municipality" => Ok(Self::LīvāniMunicipality),
                "Madona Municipality" => Ok(Self::MadonaMunicipality),
                "Mazsalaca Municipality" => Ok(Self::MazsalacaMunicipality),
                "Mālpils Municipality" => Ok(Self::MālpilsMunicipality),
                "Mārupe Municipality" => Ok(Self::MārupeMunicipality),
                "Mērsrags Municipality" => Ok(Self::MērsragsMunicipality),
                "Naukšēni Municipality" => Ok(Self::NaukšēniMunicipality),
                "Nereta Municipality" => Ok(Self::NeretaMunicipality),
                "Nīca Municipality" => Ok(Self::NīcaMunicipality),
                "Ogre Municipality" => Ok(Self::OgreMunicipality),
                "Olaine Municipality" => Ok(Self::OlaineMunicipality),
                "Ozolnieki Municipality" => Ok(Self::OzolniekiMunicipality),
                "Preiļi Municipality" => Ok(Self::PreiļiMunicipality),
                "Priekule Municipality" => Ok(Self::PriekuleMunicipality),
                "Priekuļi Municipality" => Ok(Self::PriekuļiMunicipality),
                "Pārgauja Municipality" => Ok(Self::PārgaujaMunicipality),
                "Pāvilosta Municipality" => Ok(Self::PāvilostaMunicipality),
                "Pļaviņas Municipality" => Ok(Self::PļaviņasMunicipality),
                "Rauna Municipality" => Ok(Self::RaunaMunicipality),
                "Riebiņi Municipality" => Ok(Self::RiebiņiMunicipality),
                "Riga" => Ok(Self::Riga),
                "Roja Municipality" => Ok(Self::RojaMunicipality),
                "Ropaži Municipality" => Ok(Self::RopažiMunicipality),
                "Rucava Municipality" => Ok(Self::RucavaMunicipality),
                "Rugāji Municipality" => Ok(Self::RugājiMunicipality),
                "Rundāle Municipality" => Ok(Self::RundāleMunicipality),
                "Rēzekne" => Ok(Self::Rēzekne),
                "Rēzekne Municipality" => Ok(Self::RēzekneMunicipality),
                "Rūjiena Municipality" => Ok(Self::RūjienaMunicipality),
                "Sala Municipality" => Ok(Self::SalaMunicipality),
                "Salacgrīva Municipality" => Ok(Self::SalacgrīvaMunicipality),
                "Salaspils Municipality" => Ok(Self::SalaspilsMunicipality),
                "Saldus Municipality" => Ok(Self::SaldusMunicipality),
                "Saulkrasti Municipality" => Ok(Self::SaulkrastiMunicipality),
                "Sigulda Municipality" => Ok(Self::SiguldaMunicipality),
                "Skrunda Municipality" => Ok(Self::SkrundaMunicipality),


pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserRole> {
        generics::generic_insert(conn, self).await
    }


pub struct JuspaythreedsserverPaymentsRequest {
    amount: StringMinorUnit,
    card: JuspaythreedsserverCard,
}


impl ConnectorCommon for Chargebee {
    fn id(&self) -> &'static str {
        "chargebee"
    }

    fn get_currency_unit(&self) -> api::CurrencyUnit {
        api::CurrencyUnit::Minor
    }

    fn common_get_content_type(&self) -> &'static str {
        "application/x-www-form-urlencoded"
    }

    fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
        connectors.chargebee.base_url.as_ref()
    }

    fn get_auth_header(
        &self,
        auth_type: &ConnectorAuthType,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        let auth = chargebee::ChargebeeAuthType::try_from(auth_type)
            .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
        let encoded_api_key = BASE64_ENGINE.encode(auth.full_access_key_v1.peek());
        Ok(vec![(
            headers::AUTHORIZATION.to_string(),
            format!("Basic {encoded_api_key}").into_masked(),
        )])
    }

    fn build_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        let response: chargebee::ChargebeeErrorResponse = res
            .response
            .parse_struct("ChargebeeErrorResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;

        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);

        Ok(ErrorResponse {
            status_code: res.status_code,
            code: response.api_error_code.clone(),
            message: response.api_error_code.clone(),
            reason: Some(response.message),
            attempt_status: None,
            connector_transaction_id: None,
            network_advice_code: None,
            network_decline_code: None,
            network_error_message: None,
            connector_metadata: None,
        })
    }
}


pub struct PaymentMethodsCallCount;


impl api::PaymentAuthorize for Powertranz {}

impl api::PaymentAuthorize for for Powertranz


pub struct UserDeprecated;


pub struct FacilitapayPerson {
    pub document_number: Secret<String>,
    pub document_type: DocumentType,
    pub social_name: Secret<String>,
    pub fiscal_country: CountryAlpha2,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<pii::Email>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub birth_date: Option<time::Date>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phone_country_code: Option<Secret<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phone_area_code: Option<Secret<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phone_number: Option<Secret<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address_city: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address_state: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address_complement: Option<Secret<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address_country: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address_number: Option<Secret<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address_postal_code: Option<Secret<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address_street: Option<Secret<String>>,
    pub net_monthly_average_income: Option<StringMajorUnit>,
}


pub struct ConsumerSettings {
    pub disabled: bool,
    pub consumer_group: String,
}


pub struct PhoneNumber {
    /// Country Code of the phone, limited to 1-3 characters
    #[serde(rename = "cc")]
    country_code: Option<String>,
    subscriber: Option<masking::Secret<String>>,
}


impl RelayRequestInner<RelayRefund> {
    pub fn from_relay_request(relay_request: relay_api_models::RelayRequest) -> RouterResult<Self> {
        match relay_request.data {
            Some(relay_api_models::RelayData::Refund(ref_data)) => Ok(Self {
                connector_resource_id: relay_request.connector_resource_id,
                connector_id: relay_request.connector_id,
                relay_type: PhantomData,
                data: ref_data,
            }),
            None => Err(errors::ApiErrorResponse::InvalidRequestData {
                message: "Relay data is required for relay type refund".to_string(),
            })?,
        }
    }
}


File: crates/router/src/types/api/verify_connector/paypal.rs

use error_stack::ResultExt;

use super::{VerifyConnector, VerifyConnectorData};
use crate::{
    connector,
    core::errors,
    routes::SessionState,
    services,
    types::{self, api},
};

#[async_trait::async_trait]
impl VerifyConnector for connector::Paypal {
    async fn get_access_token(
        state: &SessionState,
        connector_data: VerifyConnectorData,
    ) -> errors::CustomResult<Option<types::AccessToken>, errors::ApiErrorResponse> {
        let token_data: types::AccessTokenRequestData =
            connector_data.connector_auth.clone().try_into()?;
        let router_data = connector_data.get_router_data(state, token_data, None);

        let request = connector_data
            .connector
            .get_connector_integration()
            .build_request(&router_data, &state.conf.connectors)
            .change_context(errors::ApiErrorResponse::InvalidRequestData {
                message: "Payment request cannot be built".to_string(),
            })?
            .ok_or(errors::ApiErrorResponse::InternalServerError)?;

        let response = services::call_connector_api(&state.to_owned(), request, "get_access_token")
            .await
            .change_context(errors::ApiErrorResponse::InternalServerError)?;

        match response {
            Ok(res) => Some(
                connector_data
                    .connector
                    .get_connector_integration()
                    .handle_response(&router_data, None, res)
                    .change_context(errors::ApiErrorResponse::InternalServerError)?
                    .response
                    .map_err(|_| errors::ApiErrorResponse::InternalServerError.into()),
            )
            .transpose(),
            Err(response_data) => {
                Self::handle_access_token_error_response::<
                    api::AccessTokenAuth,
                    types::AccessTokenFlowData,
                    types::AccessTokenRequestData,
                    types::AccessToken,
                >(
                    connector_data.connector.get_connector_integration(),
                    response_data,
                )
                .await
            }
        }
    }
}


File: crates/router/src/types/api/admin.rs
 Public functions: 1
 Public structs: 1

use std::collections::HashMap;

#[cfg(feature = "v2")]
pub use api_models::admin;
pub use api_models::{
    admin::{
        MaskedHeaders, MerchantAccountCreate, MerchantAccountDeleteResponse,
        MerchantAccountResponse, MerchantAccountUpdate, MerchantConnectorCreate,
        MerchantConnectorDeleteResponse, MerchantConnectorDetails, MerchantConnectorDetailsWrap,
        MerchantConnectorId, MerchantConnectorResponse, MerchantDetails, MerchantId,
        PaymentMethodsEnabled, ProfileCreate, ProfileResponse, ProfileUpdate, ToggleAllKVRequest,
        ToggleAllKVResponse, ToggleKVRequest, ToggleKVResponse, WebhookDetails,
    },
    organization::{
        OrganizationCreateRequest, OrganizationId, OrganizationResponse, OrganizationUpdateRequest,
    },
};
use common_utils::{ext_traits::ValueExt, types::keymanager as km_types};
use diesel_models::{business_profile::CardTestingGuardConfig, organization::OrganizationBridge};
use error_stack::ResultExt;
use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;
use masking::{ExposeInterface, PeekInterface, Secret};

use crate::{
    consts,
    core::errors,
    routes::SessionState,
    types::{
        domain::{
            self,
            types::{self as domain_types, AsyncLift},
        },
        transformers::{ForeignInto, ForeignTryFrom},
        ForeignFrom,
    },
    utils,
};

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ProfileAcquirerConfigs {
    pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>,
    pub profile_id: common_utils::id_type::ProfileId,
}

impl From<ProfileAcquirerConfigs>
    for Option<Vec<api_models::profile_acquirer::ProfileAcquirerResponse>>
{
    fn from(item: ProfileAcquirerConfigs) -> Self {
        item.acquirer_config_map.map(|config_map_val| {
            let mut vec: Vec<_> = config_map_val.0.into_iter().collect();
            vec.sort_by_key(|k| k.0.clone());
            vec.into_iter()
                .map(|(profile_acquirer_id, acquirer_config)| {
                    api_models::profile_acquirer::ProfileAcquirerResponse::from((
                        profile_acquirer_id,
                        &item.profile_id,
                        &acquirer_config,
                    ))
                })
                .collect::<Vec<api_models::profile_acquirer::ProfileAcquirerResponse>>()
        })
    }
}

impl ForeignFrom<diesel_models::organization::Organization> for OrganizationResponse {
    fn foreign_from(org: diesel_models::organization::Organization) -> Self {
        Self {
            #[cfg(feature = "v2")]
            id: org.get_organization_id(),

            #[cfg(feature = "v1")]
            organization_id: org.get_organization_id(),
            organization_name: org.get_organization_name(),
            organization_details: org.organization_details,
            metadata: org.metadata,
            modified_at: org.modified_at,
            created_at: org.created_at,
            organization_type: org.organization_type,
        }
    }
}

#[cfg(feature = "v1")]
impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse {
    type Error = error_stack::Report<errors::ParsingError>;
    fn foreign_try_from(item: domain::MerchantAccount) -> Result<Self, Self::Error> {
        let merchant_id = item.get_id().to_owned();
        let primary_business_details: Vec<api_models::admin::PrimaryBusinessDetails> = item
            .primary_business_details
            .parse_value("primary_business_details")?;

        let pm_collect_link_config: Option<api_models::admin::BusinessCollectLinkConfig> = item
            .pm_collect_link_config
            .map(|config| config.parse_value("pm_collect_link_config"))
            .transpose()?;

        Ok(Self {
            merchant_id,
            merchant_name: item.merchant_name,
            return_url: item.return_url,
            enable_payment_response_hash: item.enable_payment_response_hash,
            payment_response_hash_key: item.payment_response_hash_key,
            redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
            merchant_details: item.merchant_details,
            webhook_details: item.webhook_details.clone().map(ForeignInto::foreign_into),
            routing_algorithm: item.routing_algorithm,
            sub_merchants_enabled: item.sub_merchants_enabled,
            parent_merchant_id: item.parent_merchant_id,
            publishable_key: Some(item.publishable_key),
            metadata: item.metadata,
            locker_id: item.locker_id,
            primary_business_details,
            frm_routing_algorithm: item.frm_routing_algorithm,
            #[cfg(feature = "payouts")]
            payout_routing_algorithm: item.payout_routing_algorithm,
            organization_id: item.organization_id,
            is_recon_enabled: item.is_recon_enabled,
            default_profile: item.default_profile,
            recon_status: item.recon_status,
            pm_collect_link_config,
            product_type: item.product_type,
            merchant_account_type: item.merchant_account_type,
        })
    }
}

#[cfg(feature = "v2")]
impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse {
    type Error = error_stack::Report<errors::ValidationError>;
    fn foreign_try_from(item: domain::MerchantAccount) -> Result<Self, Self::Error> {
        use common_utils::ext_traits::OptionExt;

        let id = item.get_id().to_owned();

        let merchant_name = item
            .merchant_name
            .get_required_value("merchant_name")?
            .into_inner();

        Ok(Self {
            id,
            merchant_name,
            merchant_details: item.merchant_details,
            publishable_key: item.publishable_key,
            metadata: item.metadata,
            organization_id: item.organization_id,
            recon_status: item.recon_status,
            product_type: item.product_type,
        })
    }
}
#[cfg(feature = "v1")]
impl ForeignTryFrom<domain::Profile> for ProfileResponse {
    type Error = error_stack::Report<errors::ParsingError>;

    fn foreign_try_from(item: domain::Profile) -> Result<Self, Self::Error> {
        let profile_id = item.get_id().to_owned();
        let outgoing_webhook_custom_http_headers = item
            .outgoing_webhook_custom_http_headers
            .map(|headers| {
                headers
                    .into_inner()
                    .expose()
                    .parse_value::<HashMap<String, Secret<String>>>(
                        "HashMap<String, Secret<String>>",
                    )
            })
            .transpose()?;
        let masked_outgoing_webhook_custom_http_headers =
            outgoing_webhook_custom_http_headers.map(MaskedHeaders::from_headers);

        let card_testing_guard_config = item
            .card_testing_guard_config
            .or(Some(CardTestingGuardConfig::default()));

        Ok(Self {
            merchant_id: item.merchant_id,
            profile_id: profile_id.clone(),
            profile_name: item.profile_name,
            return_url: item.return_url,
            enable_payment_response_hash: item.enable_payment_response_hash,
            payment_response_hash_key: item.payment_response_hash_key,
            redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
            webhook_details: item.webhook_details.map(ForeignInto::foreign_into),
            metadata: item.metadata,
            routing_algorithm: item.routing_algorithm,
            intent_fulfillment_time: item.intent_fulfillment_time,
            frm_routing_algorithm: item.frm_routing_algorithm,
            #[cfg(feature = "payouts")]
            payout_routing_algorithm: item.payout_routing_algorithm,
            applepay_verified_domains: item.applepay_verified_domains,
            payment_link_config: item.payment_link_config.map(ForeignInto::foreign_into),
            session_expiry: item.session_expiry,
            authentication_connector_details: item
                .authentication_connector_details
                .map(ForeignInto::foreign_into),
            payout_link_config: item.payout_link_config.map(ForeignInto::foreign_into),
            use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing,
            extended_card_info_config: item
                .extended_card_info_config
                .map(|config| config.expose().parse_value("ExtendedCardInfoConfig"))
                .transpose()?,
            collect_shipping_details_from_wallet_connector: item
                .collect_shipping_details_from_wallet_connector,
            collect_billing_details_from_wallet_connector: item
                .collect_billing_details_from_wallet_connector,
            always_collect_billing_details_from_wallet_connector: item
                .always_collect_billing_details_from_wallet_connector,
            always_collect_shipping_details_from_wallet_connector: item
                .always_collect_shipping_details_from_wallet_connector,
            is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled,
            outgoing_webhook_custom_http_headers: masked_outgoing_webhook_custom_http_headers,
            tax_connector_id: item.tax_connector_id,
            is_tax_connector_enabled: item.is_tax_connector_enabled,
            is_network_tokenization_enabled: item.is_network_tokenization_enabled,
            is_auto_retries_enabled: item.is_auto_retries_enabled,
            max_auto_retries_enabled: item.max_auto_retries_enabled,
            always_request_extended_authorization: item.always_request_extended_authorization,
            is_click_to_pay_enabled: item.is_click_to_pay_enabled,
            authentication_product_ids: item.authentication_product_ids,
            card_testing_guard_config: card_testing_guard_config.map(ForeignInto::foreign_into),
            is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled,
            force_3ds_challenge: item.force_3ds_challenge,
            is_debit_routing_enabled: Some(item.is_debit_routing_enabled),
            merchant_business_country: item.merchant_business_country,
            is_pre_network_tokenization_enabled: item.is_pre_network_tokenization_enabled,
            acquirer_configs: ProfileAcquirerConfigs {
                acquirer_config_map: item.acquirer_config_map.clone(),
                profile_id: profile_id.clone(),
            }
            .into(),
            is_iframe_redirection_enabled: item.is_iframe_redirection_enabled,
            merchant_category_code: item.merchant_category_code,
            merchant_country_code: item.merchant_country_code,
            dispute_polling_interval: item.dispute_polling_interval,
            is_manual_retry_enabled: item.is_manual_retry_enabled,
        })
    }
}

#[cfg(feature = "v2")]
impl ForeignTryFrom<domain::Profile> for ProfileResponse {
    type Error = error_stack::Report<errors::ParsingError>;

    fn foreign_try_from(item: domain::Profile) -> Result<Self, Self::Error> {
        let id = item.get_id().to_owned();

        let outgoing_webhook_custom_http_headers = item
            .outgoing_webhook_custom_http_headers
            .map(|headers| {
                headers
                    .into_inner()
                    .expose()
                    .parse_value::<HashMap<String, Secret<String>>>(
                        "HashMap<String, Secret<String>>",
                    )
            })
            .transpose()?;

        let order_fulfillment_time = item
            .order_fulfillment_time
            .map(admin::OrderFulfillmentTime::try_new)
            .transpose()
            .change_context(errors::ParsingError::IntegerOverflow)?;
        let masked_outgoing_webhook_custom_http_headers =
            outgoing_webhook_custom_http_headers.map(MaskedHeaders::from_headers);

        let card_testing_guard_config = item
            .card_testing_guard_config
            .or(Some(CardTestingGuardConfig::default()));

        Ok(Self {
            merchant_id: item.merchant_id,
            id,
            profile_name: item.profile_name,
            return_url: item.return_url,
            enable_payment_response_hash: item.enable_payment_response_hash,
            payment_response_hash_key: item.payment_response_hash_key,
            redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
            webhook_details: item.webhook_details.map(ForeignInto::foreign_into),
            metadata: item.metadata,
            applepay_verified_domains: item.applepay_verified_domains,
            payment_link_config: item.payment_link_config.map(ForeignInto::foreign_into),
            session_expiry: item.session_expiry,
            authentication_connector_details: item
                .authentication_connector_details
                .map(ForeignInto::foreign_into),
            payout_link_config: item.payout_link_config.map(ForeignInto::foreign_into),
            use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing,
            extended_card_info_config: item
                .extended_card_info_config
                .map(|config| config.expose().parse_value("ExtendedCardInfoConfig"))
                .transpose()?,
            collect_shipping_details_from_wallet_connector_if_required: item
                .collect_shipping_details_from_wallet_connector,
            collect_billing_details_from_wallet_connector_if_required: item
                .collect_billing_details_from_wallet_connector,
            always_collect_shipping_details_from_wallet_connector: item
                .always_collect_shipping_details_from_wallet_connector,
            always_collect_billing_details_from_wallet_connector: item
                .always_collect_billing_details_from_wallet_connector,
            is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled,
            outgoing_webhook_custom_http_headers: masked_outgoing_webhook_custom_http_headers,
            order_fulfillment_time,
            order_fulfillment_time_origin: item.order_fulfillment_time_origin,
            should_collect_cvv_during_payment: item.should_collect_cvv_during_payment,
            tax_connector_id: item.tax_connector_id,
            is_tax_connector_enabled: item.is_tax_connector_enabled,
            is_network_tokenization_enabled: item.is_network_tokenization_enabled,
            is_click_to_pay_enabled: item.is_click_to_pay_enabled,
            authentication_product_ids: item.authentication_product_ids,
            card_testing_guard_config: card_testing_guard_config.map(ForeignInto::foreign_into),
            is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled,
            is_debit_routing_enabled: Some(item.is_debit_routing_enabled),
            merchant_business_country: item.merchant_business_country,
            is_iframe_redirection_enabled: item.is_iframe_redirection_enabled,
            is_external_vault_enabled: item.is_external_vault_enabled,
            external_vault_connector_details: item
                .external_vault_connector_details
                .map(ForeignInto::foreign_into),
            merchant_category_code: item.merchant_category_code,
            merchant_country_code: item.merchant_country_code,
            split_txns_enabled: item.split_txns_enabled,
        })
    }
}

#[cfg(feature = "v1")]
pub async fn create_profile_from_merchant_account(
    state: &SessionState,
    merchant_account: domain::MerchantAccount,
    request: ProfileCreate,
    key_store: &MerchantKeyStore,
) -> Result<domain::Profile, error_stack::Report<errors::ApiErrorResponse>> {
    use common_utils::ext_traits::AsyncExt;
    use diesel_models::business_profile::CardTestingGuardConfig;

    use crate::core;

    // Generate a unique profile id
    let profile_id = common_utils::generate_profile_id_of_default_length();
    let merchant_id = merchant_account.get_id().to_owned();

    let current_time = common_utils::date_time::now();

    let webhook_details = request.webhook_details.map(ForeignInto::foreign_into);

    let payment_response_hash_key = request
        .payment_response_hash_key
        .or(merchant_account.payment_response_hash_key)
        .unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64));

    let payment_link_config = request.payment_link_config.map(ForeignInto::foreign_into);
    let key_manager_state = state.into();
    let outgoing_webhook_custom_http_headers = request
        .outgoing_webhook_custom_http_headers
        .async_map(|headers| {
            core::payment_methods::cards::create_encrypted_data(
                &key_manager_state,
                key_store,
                headers,
            )
        })
        .await
        .transpose()
        .change_context(errors::ApiErrorResponse::InternalServerError)
        .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?;

    let payout_link_config = request
        .payout_link_config
        .map(|payout_conf| match payout_conf.config.validate() {
            Ok(_) => Ok(payout_conf.foreign_into()),
            Err(e) => Err(error_stack::report!(
                errors::ApiErrorResponse::InvalidRequestData {
                    message: e.to_string()
                }
            )),
        })
        .transpose()?;

    let key = key_store.key.clone().into_inner();
    let key_manager_state = state.into();

    let card_testing_secret_key = Some(Secret::new(utils::generate_id(
        consts::FINGERPRINT_SECRET_LENGTH,
        "fs",
    )));

    let card_testing_guard_config = request
        .card_testing_guard_config
        .map(CardTestingGuardConfig::foreign_from)
        .or(Some(CardTestingGuardConfig::default()));

    Ok(domain::Profile::from(domain::ProfileSetter {
        profile_id,
        merchant_id,
        profile_name: request.profile_name.unwrap_or("default".to_string()),
        created_at: current_time,
        modified_at: current_time,
        return_url: request
            .return_url
            .map(|return_url| return_url.to_string())
            .or(merchant_account.return_url),
        enable_payment_response_hash: request
            .enable_payment_response_hash
            .unwrap_or(merchant_account.enable_payment_response_hash),
        payment_response_hash_key: Some(payment_response_hash_key),
        redirect_to_merchant_with_http_post: request
            .redirect_to_merchant_with_http_post
            .unwrap_or(merchant_account.redirect_to_merchant_with_http_post),
        webhook_details: webhook_details.or(merchant_account.webhook_details),
        metadata: request.metadata,
        routing_algorithm: None,
        intent_fulfillment_time: request
            .intent_fulfillment_time
            .map(i64::from)
            .or(merchant_account.intent_fulfillment_time)
            .or(Some(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME)),
        frm_routing_algorithm: request
            .frm_routing_algorithm
            .or(merchant_account.frm_routing_algorithm),
        #[cfg(feature = "payouts")]
        payout_routing_algorithm: request
            .payout_routing_algorithm
            .or(merchant_account.payout_routing_algorithm),
        #[cfg(not(feature = "payouts"))]
        payout_routing_algorithm: None,
        is_recon_enabled: merchant_account.is_recon_enabled,
        applepay_verified_domains: request.applepay_verified_domains,
        payment_link_config,
        session_expiry: request
            .session_expiry
            .map(i64::from)
            .or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)),
        authentication_connector_details: request
            .authentication_connector_details
            .map(ForeignInto::foreign_into),
        payout_link_config,
        is_connector_agnostic_mit_enabled: request.is_connector_agnostic_mit_enabled,
        is_extended_card_info_enabled: None,
        extended_card_info_config: None,
        use_billing_as_payment_method_billing: request
            .use_billing_as_payment_method_billing
            .or(Some(true)),
        collect_shipping_details_from_wallet_connector: request
            .collect_shipping_details_from_wallet_connector
            .or(Some(false)),
        collect_billing_details_from_wallet_connector: request
            .collect_billing_details_from_wallet_connector
            .or(Some(false)),
        always_collect_billing_details_from_wallet_connector: request
            .always_collect_billing_details_from_wallet_connector
            .or(Some(false)),
        always_collect_shipping_details_from_wallet_connector: request
            .always_collect_shipping_details_from_wallet_connector
            .or(Some(false)),
        outgoing_webhook_custom_http_headers,
        tax_connector_id: request.tax_connector_id,
        is_tax_connector_enabled: request.is_tax_connector_enabled,
        dynamic_routing_algorithm: None,
        is_network_tokenization_enabled: request.is_network_tokenization_enabled,
        is_auto_retries_enabled: request.is_auto_retries_enabled.unwrap_or_default(),
        max_auto_retries_enabled: request.max_auto_retries_enabled.map(i16::from),
        always_request_extended_authorization: request.always_request_extended_authorization,
        is_click_to_pay_enabled: request.is_click_to_pay_enabled,
        authentication_product_ids: request.authentication_product_ids,
        card_testing_guard_config,
        card_testing_secret_key: card_testing_secret_key
            .async_lift(|inner| async {
                domain_types::crypto_operation(
                    &key_manager_state,
                    common_utils::type_name!(domain::Profile),
                    domain_types::CryptoOperation::EncryptOptional(inner),
                    km_types::Identifier::Merchant(key_store.merchant_id.clone()),
                    key.peek(),
                )
                .await
                .and_then(|val| val.try_into_optionaloperation())
            })
            .await
            .change_context(errors::ApiErrorResponse::InternalServerError)
            .attach_printable("error while generating card testing secret key")?,
        is_clear_pan_retries_enabled: request.is_clear_pan_retries_enabled.unwrap_or_default(),
        force_3ds_challenge: request.force_3ds_challenge.unwrap_or_default(),
        is_debit_routing_enabled: request.is_debit_routing_enabled.unwrap_or_default(),
        merchant_business_country: request.merchant_business_country,
        is_iframe_redirection_enabled: request.is_iframe_redirection_enabled,
        is_pre_network_tokenization_enabled: request
            .is_pre_network_tokenization_enabled
            .unwrap_or_default(),
        merchant_category_code: request.merchant_category_code,
        merchant_country_code: request.merchant_country_code,
        dispute_polling_interval: request.dispute_polling_interval,
        is_manual_retry_enabled: request.is_manual_retry_enabled,
    }))
}


pub struct CardPaymentInformation {
    card: Card,
}


pub struct RevenueRecoveryRecordBackRequest {
    pub merchant_reference_id: common_utils::id_type::PaymentReferenceId,
    pub amount: common_utils::types::MinorUnit,
    pub currency: enums::Currency,
    pub payment_method_type: Option<common_enums::PaymentMethodType>,
    pub attempt_status: common_enums::AttemptStatus,
    pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>,
    pub connector_params: connector_endpoints::ConnectorParams,
}


/// Converts a `prost_types::Timestamp` to an `time::PrimitiveDateTime`.
    pub fn convert_from_prost_timestamp(
        ts: &prost_types::Timestamp,
    ) -> error_stack::Result<time::PrimitiveDateTime, DateTimeConversionError> {
        let timestamp_nanos = i128::from(ts.seconds) * 1_000_000_000 + i128::from(ts.nanos);

        time::OffsetDateTime::from_unix_timestamp_nanos(timestamp_nanos)
            .map(|offset_dt| time::PrimitiveDateTime::new(offset_dt.date(), offset_dt.time()))
            .change_context(DateTimeConversionError::TimestampOutOfRange)
    }


impl FrmMetricsAccumulator {
    pub fn collect(self) -> FrmMetricsBucketValue {
        FrmMetricsBucketValue {
            frm_blocked_rate: self.frm_blocked_rate.collect(),
            frm_triggered_attempts: self.frm_triggered_attempts.collect(),
        }
    }
}


impl UserAuthenticationMethodInterface for KafkaStore {
    async fn insert_user_authentication_method(
        &self,
        user_authentication_method: storage::UserAuthenticationMethodNew,
    ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> {
        self.diesel_store
            .insert_user_authentication_method(user_authentication_method)
            .await
    }

    async fn get_user_authentication_method_by_id(
        &self,
        id: &str,
    ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> {
        self.diesel_store
            .get_user_authentication_method_by_id(id)
            .await
    }

    async fn list_user_authentication_methods_for_auth_id(
        &self,
        auth_id: &str,
    ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> {
        self.diesel_store
            .list_user_authentication_methods_for_auth_id(auth_id)
            .await
    }

    async fn list_user_authentication_methods_for_owner_id(
        &self,
        owner_id: &str,
    ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> {
        self.diesel_store
            .list_user_authentication_methods_for_owner_id(owner_id)
            .await
    }

    async fn update_user_authentication_method(
        &self,
        id: &str,
        user_authentication_method_update: storage::UserAuthenticationMethodUpdate,
    ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> {
        self.diesel_store
            .update_user_authentication_method(id, user_authentication_method_update)
            .await
    }

    async fn list_user_authentication_methods_for_email_domain(
        &self,
        email_domain: &str,
    ) -> CustomResult<
        Vec<diesel_models::user_authentication_method::UserAuthenticationMethod>,
        errors::StorageError,
    > {
        self.diesel_store
            .list_user_authentication_methods_for_email_domain(email_domain)
            .await
    }
}

impl UserAuthenticationMethodInterface for for KafkaStore


impl<Secret, MaskingStrategy> Eq for StrongSecret<Secret, MaskingStrategy>
where
    Self: PeekInterface<Secret>,
    Secret: ZeroizableSecret + StrongEq,
{
}


pub struct Trustpayments {
    amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}


impl Tokenio {
    pub fn new() -> &'static Self {
        &Self {
            amount_converter: &StringMajorUnitForConnector,
        }
    }
    fn create_jwt_token(
        &self,
        auth: &tokenio::TokenioAuthType,
        method: &str,
        path: &str,
        body: &RequestContent,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        // Create JWT header
        let exp_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .change_context(errors::ConnectorError::RequestEncodingFailed)?
            .as_millis()
            + 600_000; // 10 minutes

        let header = serde_json::json!({
            "alg": match auth.key_algorithm {
                tokenio::CryptoAlgorithm::RS256 => "RS256",
                tokenio::CryptoAlgorithm::ES256 => "ES256",
                tokenio::CryptoAlgorithm::EDDSA => "EdDSA",
            },
            "exp": exp_time.to_string(), // Convert to string as Token.io expects
            "mid": auth.merchant_id.clone().expose(),
            "kid": auth.key_id.clone().expose(),
            "method": method.to_uppercase(),
            "host": connectors.tokenio.base_url.trim_start_matches("https://").trim_end_matches("/"),
            "path": path,
            "typ": "JWT",
        });

        // For GET requests, use detached JWT (no payload)
        // For POST/PUT requests, include the request body as payload
        let is_get_request = method.to_uppercase() == "GET";
        let payload = if is_get_request {
            None // No payload for GET requests (detached JWT)
        } else {
            // For non-GET requests, include the request body
            match body {
                RequestContent::Json(json_body) => Some(
                    serde_json::to_value(json_body)
                        .change_context(errors::ConnectorError::RequestEncodingFailed)?,
                ),
                _ => Some(serde_json::json!({})),
            }
        };

        // Use compact JSON serialization (no extra whitespace)
        let encoded_header = self.base64url_encode(
            serde_json::to_string(&header)
                .change_context(errors::ConnectorError::RequestEncodingFailed)?
                .as_bytes(),
        )?;

        let (encoded_payload, signing_input) = match payload {
            Some(p) => {
                // Standard JWT with payload
                let encoded_payload = self.base64url_encode(
                    serde_json::to_string(&p)
                        .change_context(errors::ConnectorError::RequestEncodingFailed)?
                        .as_bytes(),
                )?;
                let signing_input = format!("{encoded_header}.{encoded_payload}");
                (encoded_payload, signing_input)
            }
            None => {
                // Detached JWT (GET requests) - sign only the header with a dot
                let signing_input = format!("{encoded_header}.");
                (String::new(), signing_input) // Empty payload for detached JWT
            }
        };

        // Sign the JWT based on algorithm
        let signature = match auth.key_algorithm {
            tokenio::CryptoAlgorithm::RS256 => {
                self.sign_rsa(&auth.private_key.clone().expose(), &signing_input)?
            }
            tokenio::CryptoAlgorithm::ES256 => {
                self.sign_ecdsa(&auth.private_key.clone().expose(), &signing_input)?
            }
            tokenio::CryptoAlgorithm::EDDSA => {
                self.sign_eddsa(&auth.private_key.clone().expose(), &signing_input)?
            }
        };

        let encoded_signature = self.base64url_encode(&signature)?;

        // Assemble JWT - for detached JWT, middle part is empty
        Ok(format!(
            "{encoded_header}.{encoded_payload}.{encoded_signature}",
        ))
    }

    fn base64url_encode(&self, data: &[u8]) -> CustomResult<String, errors::ConnectorError> {
        Ok(URL_SAFE_NO_PAD.encode(data))
    }

    fn sign_rsa(
        &self,
        private_key_pem: &str,
        data: &str,
    ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
        let rsa = Rsa::private_key_from_pem(private_key_pem.as_bytes())
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;

        let pkey =
            PKey::from_rsa(rsa).change_context(errors::ConnectorError::RequestEncodingFailed)?;

        let mut signer = Signer::new(MessageDigest::sha256(), &pkey)
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;

        signer
            .update(data.as_bytes())
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;

        let signature = signer
            .sign_to_vec()
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;

        Ok(signature)
    }

    fn sign_ecdsa(
        &self,
        private_key_pem: &str,
        data: &str,
    ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
        let ec_key = EcKey::private_key_from_pem(private_key_pem.as_bytes())
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;

        let pkey = PKey::from_ec_key(ec_key)
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;

        let mut signer = Signer::new(MessageDigest::sha256(), &pkey)
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;

        signer
            .update(data.as_bytes())
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;

        let signature = signer
            .sign_to_vec()
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;

        Ok(signature)
    }

    fn sign_eddsa(
        &self,
        private_key_pem: &str,
        data: &str,
    ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
        let pkey = PKey::private_key_from_pem(private_key_pem.as_bytes())
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;

        let mut signer = Signer::new_without_digest(&pkey)
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;

        signer
            .update(data.as_bytes())
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;

        let signature = signer
            .sign_to_vec()
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;

        Ok(signature)
    }
}


pub async fn get_theme_using_lineage(
    state: web::Data<AppState>,
    req: HttpRequest,
    query: web::Query<ThemeLineage>,
) -> HttpResponse {
    let flow = Flow::GetThemeUsingLineage;
    let lineage = query.into_inner();

    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        lineage,
        |state, _, lineage, _| theme_core::get_theme_using_lineage(state, lineage),
        &auth::AdminApiAuth,
        api_locking::LockAction::NotApplicable,
    ))
    .await
}