            Self::Reunion => CountryAlpha3::REU,
            Self::Romania => CountryAlpha3::ROU,
            Self::RussianFederation => CountryAlpha3::RUS,
            Self::Rwanda => CountryAlpha3::RWA,
            Self::SaintBarthelemy => CountryAlpha3::BLM,
            Self::SaintHelenaAscensionAndTristandaCunha => CountryAlpha3::SHN,
            Self::SaintKittsAndNevis => CountryAlpha3::KNA,
            Self::SaintLucia => CountryAlpha3::LCA,
            Self::SaintMartinFrenchpart => CountryAlpha3::MAF,
            Self::SaintPierreAndMiquelon => CountryAlpha3::SPM,
            Self::SaintVincentAndTheGrenadines => CountryAlpha3::VCT,
            Self::Samoa => CountryAlpha3::WSM,
            Self::SanMarino => CountryAlpha3::SMR,
            Self::SaoTomeAndPrincipe => CountryAlpha3::STP,
            Self::SaudiArabia => CountryAlpha3::SAU,
            Self::Senegal => CountryAlpha3::SEN,
            Self::Serbia => CountryAlpha3::SRB,
            Self::Seychelles => CountryAlpha3::SYC,
            Self::SierraLeone => CountryAlpha3::SLE,
            Self::Singapore => CountryAlpha3::SGP,
            Self::SintMaartenDutchpart => CountryAlpha3::SXM,
            Self::Slovakia => CountryAlpha3::SVK,
            Self::Slovenia => CountryAlpha3::SVN,
            Self::SolomonIslands => CountryAlpha3::SLB,
            Self::Somalia => CountryAlpha3::SOM,
            Self::SouthAfrica => CountryAlpha3::ZAF,
            Self::SouthGeorgiaAndTheSouthSandwichIslands => CountryAlpha3::SGS,
            Self::SouthSudan => CountryAlpha3::SSD,
            Self::Spain => CountryAlpha3::ESP,
            Self::SriLanka => CountryAlpha3::LKA,
            Self::Sudan => CountryAlpha3::SDN,
            Self::Suriname => CountryAlpha3::SUR,
            Self::SvalbardAndJanMayen => CountryAlpha3::SJM,
            Self::Swaziland => CountryAlpha3::SWZ,
            Self::Sweden => CountryAlpha3::SWE,
            Self::Switzerland => CountryAlpha3::CHE,
            Self::SyrianArabRepublic => CountryAlpha3::SYR,
            Self::TaiwanProvinceOfChina => CountryAlpha3::TWN,
            Self::Tajikistan => CountryAlpha3::TJK,
            Self::TanzaniaUnitedRepublic => CountryAlpha3::TZA,
            Self::Thailand => CountryAlpha3::THA,
            Self::TimorLeste => CountryAlpha3::TLS,
            Self::Togo => CountryAlpha3::TGO,
            Self::Tokelau => CountryAlpha3::TKL,
            Self::Tonga => CountryAlpha3::TON,
            Self::TrinidadAndTobago => CountryAlpha3::TTO,
            Self::Tunisia => CountryAlpha3::TUN,
            Self::Turkey => CountryAlpha3::TUR,
            Self::Turkmenistan => CountryAlpha3::TKM,
            Self::TurksAndCaicosIslands => CountryAlpha3::TCA,
            Self::Tuvalu => CountryAlpha3::TUV,
            Self::Uganda => CountryAlpha3::UGA,
            Self::Ukraine => CountryAlpha3::UKR,
            Self::UnitedArabEmirates => CountryAlpha3::ARE,
            Self::UnitedKingdomOfGreatBritainAndNorthernIreland => CountryAlpha3::GBR,
            Self::UnitedStatesOfAmerica => CountryAlpha3::USA,
            Self::UnitedStatesMinorOutlyingIslands => CountryAlpha3::UMI,
            Self::Uruguay => CountryAlpha3::URY,
            Self::Uzbekistan => CountryAlpha3::UZB,
            Self::Vanuatu => CountryAlpha3::VUT,
            Self::VenezuelaBolivarianRepublic => CountryAlpha3::VEN,
            Self::Vietnam => CountryAlpha3::VNM,
            Self::VirginIslandsBritish => CountryAlpha3::VGB,
            Self::VirginIslandsUS => CountryAlpha3::VIR,
            Self::WallisAndFutuna => CountryAlpha3::WLF,
            Self::WesternSahara => CountryAlpha3::ESH,
            Self::Yemen => CountryAlpha3::YEM,
            Self::Zambia => CountryAlpha3::ZMB,
            Self::Zimbabwe => CountryAlpha3::ZWE,
        }
    }
    pub const fn from_numeric(code: u32) -> Result<Self, NumericCountryCodeParseError> {
        match code {
            4 => Ok(Self::Afghanistan),
            248 => Ok(Self::AlandIslands),
            8 => Ok(Self::Albania),
            12 => Ok(Self::Algeria),
            16 => Ok(Self::AmericanSamoa),
            20 => Ok(Self::Andorra),
            24 => Ok(Self::Angola),
            660 => Ok(Self::Anguilla),
            10 => Ok(Self::Antarctica),
            28 => Ok(Self::AntiguaAndBarbuda),
            32 => Ok(Self::Argentina),
            51 => Ok(Self::Armenia),
            533 => Ok(Self::Aruba),
            36 => Ok(Self::Australia),
            40 => Ok(Self::Austria),
            31 => Ok(Self::Azerbaijan),
            44 => Ok(Self::Bahamas),
            48 => Ok(Self::Bahrain),
            50 => Ok(Self::Bangladesh),
            52 => Ok(Self::Barbados),
            112 => Ok(Self::Belarus),
            56 => Ok(Self::Belgium),
            84 => Ok(Self::Belize),
            204 => Ok(Self::Benin),
            60 => Ok(Self::Bermuda),
            64 => Ok(Self::Bhutan),
            68 => Ok(Self::BoliviaPlurinationalState),
            535 => Ok(Self::BonaireSintEustatiusAndSaba),
            70 => Ok(Self::BosniaAndHerzegovina),
            72 => Ok(Self::Botswana),
            74 => Ok(Self::BouvetIsland),
            76 => Ok(Self::Brazil),
            86 => Ok(Self::BritishIndianOceanTerritory),
            96 => Ok(Self::BruneiDarussalam),
            100 => Ok(Self::Bulgaria),
            854 => Ok(Self::BurkinaFaso),
            108 => Ok(Self::Burundi),
            132 => Ok(Self::CaboVerde),
            116 => Ok(Self::Cambodia),
            120 => Ok(Self::Cameroon),
            124 => Ok(Self::Canada),
            136 => Ok(Self::CaymanIslands),
            140 => Ok(Self::CentralAfricanRepublic),
            148 => Ok(Self::Chad),
            152 => Ok(Self::Chile),
            156 => Ok(Self::China),
            162 => Ok(Self::ChristmasIsland),
            166 => Ok(Self::CocosKeelingIslands),
            170 => Ok(Self::Colombia),
            174 => Ok(Self::Comoros),
            178 => Ok(Self::Congo),
            180 => Ok(Self::CongoDemocraticRepublic),
            184 => Ok(Self::CookIslands),
            188 => Ok(Self::CostaRica),
            384 => Ok(Self::CotedIvoire),
            191 => Ok(Self::Croatia),
            192 => Ok(Self::Cuba),
            531 => Ok(Self::Curacao),
            196 => Ok(Self::Cyprus),
            203 => Ok(Self::Czechia),
            208 => Ok(Self::Denmark),
            262 => Ok(Self::Djibouti),
            212 => Ok(Self::Dominica),
            214 => Ok(Self::DominicanRepublic),
            218 => Ok(Self::Ecuador),
            818 => Ok(Self::Egypt),
            222 => Ok(Self::ElSalvador),
            226 => Ok(Self::EquatorialGuinea),
            232 => Ok(Self::Eritrea),
            233 => Ok(Self::Estonia),
            231 => Ok(Self::Ethiopia),
            238 => Ok(Self::FalklandIslandsMalvinas),
            234 => Ok(Self::FaroeIslands),
            242 => Ok(Self::Fiji),
            246 => Ok(Self::Finland),
            250 => Ok(Self::France),
            254 => Ok(Self::FrenchGuiana),
            258 => Ok(Self::FrenchPolynesia),
            260 => Ok(Self::FrenchSouthernTerritories),
            266 => Ok(Self::Gabon),
            270 => Ok(Self::Gambia),
            268 => Ok(Self::Georgia),
            276 => Ok(Self::Germany),
            288 => Ok(Self::Ghana),
            292 => Ok(Self::Gibraltar),
            300 => Ok(Self::Greece),
            304 => Ok(Self::Greenland),
            308 => Ok(Self::Grenada),
            312 => Ok(Self::Guadeloupe),
            316 => Ok(Self::Guam),
            320 => Ok(Self::Guatemala),
            831 => Ok(Self::Guernsey),
            324 => Ok(Self::Guinea),
            624 => Ok(Self::GuineaBissau),
            328 => Ok(Self::Guyana),
            332 => Ok(Self::Haiti),
            334 => Ok(Self::HeardIslandAndMcDonaldIslands),
            336 => Ok(Self::HolySee),
            340 => Ok(Self::Honduras),
            344 => Ok(Self::HongKong),
            348 => Ok(Self::Hungary),
            352 => Ok(Self::Iceland),
            356 => Ok(Self::India),
            360 => Ok(Self::Indonesia),
            364 => Ok(Self::IranIslamicRepublic),
            368 => Ok(Self::Iraq),
            372 => Ok(Self::Ireland),
            833 => Ok(Self::IsleOfMan),
            376 => Ok(Self::Israel),
            380 => Ok(Self::Italy),
            388 => Ok(Self::Jamaica),
            392 => Ok(Self::Japan),
            832 => Ok(Self::Jersey),
            400 => Ok(Self::Jordan),
            398 => Ok(Self::Kazakhstan),
            404 => Ok(Self::Kenya),
            296 => Ok(Self::Kiribati),
            408 => Ok(Self::KoreaDemocraticPeoplesRepublic),
            410 => Ok(Self::KoreaRepublic),
            414 => Ok(Self::Kuwait),
            417 => Ok(Self::Kyrgyzstan),
            418 => Ok(Self::LaoPeoplesDemocraticRepublic),
            428 => Ok(Self::Latvia),
            422 => Ok(Self::Lebanon),
            426 => Ok(Self::Lesotho),
            430 => Ok(Self::Liberia),
            434 => Ok(Self::Libya),
            438 => Ok(Self::Liechtenstein),
            440 => Ok(Self::Lithuania),
            442 => Ok(Self::Luxembourg),
            446 => Ok(Self::Macao),
            807 => Ok(Self::MacedoniaTheFormerYugoslavRepublic),
            450 => Ok(Self::Madagascar),
            454 => Ok(Self::Malawi),
            458 => Ok(Self::Malaysia),
            462 => Ok(Self::Maldives),
            466 => Ok(Self::Mali),
            470 => Ok(Self::Malta),
            584 => Ok(Self::MarshallIslands),
            474 => Ok(Self::Martinique),
            478 => Ok(Self::Mauritania),
            480 => Ok(Self::Mauritius),
            175 => Ok(Self::Mayotte),
            484 => Ok(Self::Mexico),
            583 => Ok(Self::MicronesiaFederatedStates),
            498 => Ok(Self::MoldovaRepublic),
            492 => Ok(Self::Monaco),
            496 => Ok(Self::Mongolia),
            499 => Ok(Self::Montenegro),
            500 => Ok(Self::Montserrat),
            504 => Ok(Self::Morocco),
            508 => Ok(Self::Mozambique),
            104 => Ok(Self::Myanmar),
            516 => Ok(Self::Namibia),
            520 => Ok(Self::Nauru),
            524 => Ok(Self::Nepal),
            528 => Ok(Self::Netherlands),
            540 => Ok(Self::NewCaledonia),
            554 => Ok(Self::NewZealand),
            558 => Ok(Self::Nicaragua),
            562 => Ok(Self::Niger),
            566 => Ok(Self::Nigeria),
            570 => Ok(Self::Niue),
            574 => Ok(Self::NorfolkIsland),
            580 => Ok(Self::NorthernMarianaIslands),
            578 => Ok(Self::Norway),
            512 => Ok(Self::Oman),
            586 => Ok(Self::Pakistan),
            585 => Ok(Self::Palau),
            275 => Ok(Self::PalestineState),
            591 => Ok(Self::Panama),
            598 => Ok(Self::PapuaNewGuinea),
            600 => Ok(Self::Paraguay),
            604 => Ok(Self::Peru),
            608 => Ok(Self::Philippines),
            612 => Ok(Self::Pitcairn),
            616 => Ok(Self::Poland),
            620 => Ok(Self::Portugal),
            630 => Ok(Self::PuertoRico),
            634 => Ok(Self::Qatar),
            638 => Ok(Self::Reunion),
            642 => Ok(Self::Romania),
            643 => Ok(Self::RussianFederation),
            646 => Ok(Self::Rwanda),
            652 => Ok(Self::SaintBarthelemy),
            654 => Ok(Self::SaintHelenaAscensionAndTristandaCunha),
            659 => Ok(Self::SaintKittsAndNevis),
            662 => Ok(Self::SaintLucia),
            663 => Ok(Self::SaintMartinFrenchpart),
            666 => Ok(Self::SaintPierreAndMiquelon),
            670 => Ok(Self::SaintVincentAndTheGrenadines),
            882 => Ok(Self::Samoa),
            674 => Ok(Self::SanMarino),
            678 => Ok(Self::SaoTomeAndPrincipe),
            682 => Ok(Self::SaudiArabia),
            686 => Ok(Self::Senegal),
            688 => Ok(Self::Serbia),
            690 => Ok(Self::Seychelles),
            694 => Ok(Self::SierraLeone),
            702 => Ok(Self::Singapore),
            534 => Ok(Self::SintMaartenDutchpart),
            703 => Ok(Self::Slovakia),
            705 => Ok(Self::Slovenia),
            90 => Ok(Self::SolomonIslands),
            706 => Ok(Self::Somalia),
            710 => Ok(Self::SouthAfrica),
            239 => Ok(Self::SouthGeorgiaAndTheSouthSandwichIslands),
            728 => Ok(Self::SouthSudan),
            724 => Ok(Self::Spain),
            144 => Ok(Self::SriLanka),
            729 => Ok(Self::Sudan),
            740 => Ok(Self::Suriname),
            744 => Ok(Self::SvalbardAndJanMayen),
            748 => Ok(Self::Swaziland),
            752 => Ok(Self::Sweden),
            756 => Ok(Self::Switzerland),
            760 => Ok(Self::SyrianArabRepublic),
            158 => Ok(Self::TaiwanProvinceOfChina),
            762 => Ok(Self::Tajikistan),
            834 => Ok(Self::TanzaniaUnitedRepublic),
            764 => Ok(Self::Thailand),
            626 => Ok(Self::TimorLeste),
            768 => Ok(Self::Togo),
            772 => Ok(Self::Tokelau),
            776 => Ok(Self::Tonga),
            780 => Ok(Self::TrinidadAndTobago),
            788 => Ok(Self::Tunisia),
            792 => Ok(Self::Turkey),
            795 => Ok(Self::Turkmenistan),
            796 => Ok(Self::TurksAndCaicosIslands),
            798 => Ok(Self::Tuvalu),
            800 => Ok(Self::Uganda),
            804 => Ok(Self::Ukraine),
            784 => Ok(Self::UnitedArabEmirates),
            826 => Ok(Self::UnitedKingdomOfGreatBritainAndNorthernIreland),
            840 => Ok(Self::UnitedStatesOfAmerica),
            581 => Ok(Self::UnitedStatesMinorOutlyingIslands),
            858 => Ok(Self::Uruguay),
            860 => Ok(Self::Uzbekistan),
            548 => Ok(Self::Vanuatu),
            862 => Ok(Self::VenezuelaBolivarianRepublic),
            704 => Ok(Self::Vietnam),
            92 => Ok(Self::VirginIslandsBritish),
            850 => Ok(Self::VirginIslandsUS),
            876 => Ok(Self::WallisAndFutuna),
            732 => Ok(Self::WesternSahara),
            887 => Ok(Self::Yemen),
            894 => Ok(Self::Zambia),
            716 => Ok(Self::Zimbabwe),
            _ => Err(NumericCountryCodeParseError),
        }
    }
    pub const fn to_numeric(self) -> u32 {
        match self {
            Self::Afghanistan => 4,
            Self::AlandIslands => 248,
            Self::Albania => 8,
            Self::Algeria => 12,
            Self::AmericanSamoa => 16,
            Self::Andorra => 20,
            Self::Angola => 24,
            Self::Anguilla => 660,
            Self::Antarctica => 10,
            Self::AntiguaAndBarbuda => 28,
            Self::Argentina => 32,
            Self::Armenia => 51,
            Self::Aruba => 533,
            Self::Australia => 36,
            Self::Austria => 40,
            Self::Azerbaijan => 31,
            Self::Bahamas => 44,
            Self::Bahrain => 48,
            Self::Bangladesh => 50,
            Self::Barbados => 52,
            Self::Belarus => 112,
            Self::Belgium => 56,
            Self::Belize => 84,
            Self::Benin => 204,
            Self::Bermuda => 60,
            Self::Bhutan => 64,
            Self::BoliviaPlurinationalState => 68,
            Self::BonaireSintEustatiusAndSaba => 535,
            Self::BosniaAndHerzegovina => 70,
            Self::Botswana => 72,
            Self::BouvetIsland => 74,
            Self::Brazil => 76,
            Self::BritishIndianOceanTerritory => 86,
            Self::BruneiDarussalam => 96,
            Self::Bulgaria => 100,
            Self::BurkinaFaso => 854,
            Self::Burundi => 108,
            Self::CaboVerde => 132,
            Self::Cambodia => 116,
            Self::Cameroon => 120,
            Self::Canada => 124,
            Self::CaymanIslands => 136,
            Self::CentralAfricanRepublic => 140,
            Self::Chad => 148,
            Self::Chile => 152,
            Self::China => 156,
            Self::ChristmasIsland => 162,
            Self::CocosKeelingIslands => 166,
            Self::Colombia => 170,
            Self::Comoros => 174,
            Self::Congo => 178,
            Self::CongoDemocraticRepublic => 180,
            Self::CookIslands => 184,
            Self::CostaRica => 188,
            Self::CotedIvoire => 384,
            Self::Croatia => 191,
            Self::Cuba => 192,
            Self::Curacao => 531,
            Self::Cyprus => 196,
            Self::Czechia => 203,
            Self::Denmark => 208,
            Self::Djibouti => 262,
            Self::Dominica => 212,
            Self::DominicanRepublic => 214,
            Self::Ecuador => 218,
            Self::Egypt => 818,
            Self::ElSalvador => 222,
            Self::EquatorialGuinea => 226,
            Self::Eritrea => 232,
            Self::Estonia => 233,
            Self::Ethiopia => 231,
            Self::FalklandIslandsMalvinas => 238,
            Self::FaroeIslands => 234,
            Self::Fiji => 242,
            Self::Finland => 246,
            Self::France => 250,
            Self::FrenchGuiana => 254,
            Self::FrenchPolynesia => 258,
            Self::FrenchSouthernTerritories => 260,
            Self::Gabon => 266,
            Self::Gambia => 270,
            Self::Georgia => 268,
            Self::Germany => 276,
            Self::Ghana => 288,
            Self::Gibraltar => 292,
            Self::Greece => 300,
            Self::Greenland => 304,
            Self::Grenada => 308,
            Self::Guadeloupe => 312,
            Self::Guam => 316,
            Self::Guatemala => 320,
            Self::Guernsey => 831,
            Self::Guinea => 324,
            Self::GuineaBissau => 624,
            Self::Guyana => 328,
            Self::Haiti => 332,
            Self::HeardIslandAndMcDonaldIslands => 334,
            Self::HolySee => 336,
            Self::Honduras => 340,
            Self::HongKong => 344,
            Self::Hungary => 348,
            Self::Iceland => 352,
            Self::India => 356,
            Self::Indonesia => 360,
            Self::IranIslamicRepublic => 364,
            Self::Iraq => 368,
            Self::Ireland => 372,
            Self::IsleOfMan => 833,
            Self::Israel => 376,
            Self::Italy => 380,
            Self::Jamaica => 388,
            Self::Japan => 392,
            Self::Jersey => 832,
            Self::Jordan => 400,
            Self::Kazakhstan => 398,
            Self::Kenya => 404,
            Self::Kiribati => 296,
            Self::KoreaDemocraticPeoplesRepublic => 408,
            Self::KoreaRepublic => 410,
            Self::Kuwait => 414,
            Self::Kyrgyzstan => 417,
            Self::LaoPeoplesDemocraticRepublic => 418,
            Self::Latvia => 428,
            Self::Lebanon => 422,
            Self::Lesotho => 426,
            Self::Liberia => 430,
            Self::Libya => 434,
            Self::Liechtenstein => 438,
            Self::Lithuania => 440,
            Self::Luxembourg => 442,
            Self::Macao => 446,
            Self::MacedoniaTheFormerYugoslavRepublic => 807,
            Self::Madagascar => 450,
            Self::Malawi => 454,
            Self::Malaysia => 458,
            Self::Maldives => 462,
            Self::Mali => 466,
            Self::Malta => 470,
            Self::MarshallIslands => 584,
            Self::Martinique => 474,
            Self::Mauritania => 478,
            Self::Mauritius => 480,
            Self::Mayotte => 175,
            Self::Mexico => 484,
            Self::MicronesiaFederatedStates => 583,
            Self::MoldovaRepublic => 498,
            Self::Monaco => 492,
            Self::Mongolia => 496,
            Self::Montenegro => 499,
            Self::Montserrat => 500,
            Self::Morocco => 504,
            Self::Mozambique => 508,
            Self::Myanmar => 104,
            Self::Namibia => 516,
            Self::Nauru => 520,
            Self::Nepal => 524,
            Self::Netherlands => 528,
            Self::NewCaledonia => 540,
            Self::NewZealand => 554,
            Self::Nicaragua => 558,
            Self::Niger => 562,
            Self::Nigeria => 566,
            Self::Niue => 570,
            Self::NorfolkIsland => 574,
            Self::NorthernMarianaIslands => 580,
            Self::Norway => 578,
            Self::Oman => 512,
            Self::Pakistan => 586,
            Self::Palau => 585,
            Self::PalestineState => 275,
            Self::Panama => 591,
            Self::PapuaNewGuinea => 598,
            Self::Paraguay => 600,
            Self::Peru => 604,
            Self::Philippines => 608,
            Self::Pitcairn => 612,
            Self::Poland => 616,
            Self::Portugal => 620,
            Self::PuertoRico => 630,
            Self::Qatar => 634,
            Self::Reunion => 638,
            Self::Romania => 642,
            Self::RussianFederation => 643,
            Self::Rwanda => 646,
            Self::SaintBarthelemy => 652,
            Self::SaintHelenaAscensionAndTristandaCunha => 654,
            Self::SaintKittsAndNevis => 659,
            Self::SaintLucia => 662,
            Self::SaintMartinFrenchpart => 663,
            Self::SaintPierreAndMiquelon => 666,
            Self::SaintVincentAndTheGrenadines => 670,
            Self::Samoa => 882,
            Self::SanMarino => 674,
            Self::SaoTomeAndPrincipe => 678,
            Self::SaudiArabia => 682,
            Self::Senegal => 686,
            Self::Serbia => 688,
            Self::Seychelles => 690,
            Self::SierraLeone => 694,
            Self::Singapore => 702,
            Self::SintMaartenDutchpart => 534,
            Self::Slovakia => 703,
            Self::Slovenia => 705,
            Self::SolomonIslands => 90,
            Self::Somalia => 706,
            Self::SouthAfrica => 710,
            Self::SouthGeorgiaAndTheSouthSandwichIslands => 239,
            Self::SouthSudan => 728,
            Self::Spain => 724,
            Self::SriLanka => 144,
            Self::Sudan => 729,
            Self::Suriname => 740,
            Self::SvalbardAndJanMayen => 744,
            Self::Swaziland => 748,
            Self::Sweden => 752,
            Self::Switzerland => 756,
            Self::SyrianArabRepublic => 760,
            Self::TaiwanProvinceOfChina => 158,
            Self::Tajikistan => 762,
            Self::TanzaniaUnitedRepublic => 834,
            Self::Thailand => 764,
            Self::TimorLeste => 626,
            Self::Togo => 768,
            Self::Tokelau => 772,
            Self::Tonga => 776,
            Self::TrinidadAndTobago => 780,
            Self::Tunisia => 788,
            Self::Turkey => 792,
            Self::Turkmenistan => 795,
            Self::TurksAndCaicosIslands => 796,
            Self::Tuvalu => 798,
            Self::Uganda => 800,
            Self::Ukraine => 804,
            Self::UnitedArabEmirates => 784,
            Self::UnitedKingdomOfGreatBritainAndNorthernIreland => 826,
            Self::UnitedStatesOfAmerica => 840,
            Self::UnitedStatesMinorOutlyingIslands => 581,
            Self::Uruguay => 858,
            Self::Uzbekistan => 860,
            Self::Vanuatu => 548,
            Self::VenezuelaBolivarianRepublic => 862,
            Self::Vietnam => 704,
            Self::VirginIslandsBritish => 92,
            Self::VirginIslandsUS => 850,
            Self::WallisAndFutuna => 876,
            Self::WesternSahara => 732,
            Self::Yemen => 887,
            Self::Zambia => 894,
            Self::Zimbabwe => 716,
        }
    }
}

impl From<PaymentMethodType> for PaymentMethod {
    fn from(value: PaymentMethodType) -> Self {
        match value {
            PaymentMethodType::Ach => Self::BankDebit,
            PaymentMethodType::Affirm => Self::PayLater,
            PaymentMethodType::AfterpayClearpay => Self::PayLater,
            PaymentMethodType::AliPay => Self::Wallet,
            PaymentMethodType::AliPayHk => Self::Wallet,
            PaymentMethodType::Alma => Self::PayLater,
            PaymentMethodType::AmazonPay => Self::Wallet,
            PaymentMethodType::Paysera => Self::Wallet,
            PaymentMethodType::Skrill => Self::Wallet,
            PaymentMethodType::ApplePay => Self::Wallet,
            PaymentMethodType::Bacs => Self::BankDebit,
            PaymentMethodType::BancontactCard => Self::BankRedirect,
            PaymentMethodType::BcaBankTransfer => Self::BankTransfer,
            PaymentMethodType::Becs => Self::BankDebit,
            PaymentMethodType::BniVa => Self::BankTransfer,
            PaymentMethodType::Breadpay => Self::PayLater,
            PaymentMethodType::BriVa => Self::BankTransfer,
            PaymentMethodType::Benefit => Self::CardRedirect,
            PaymentMethodType::Bizum => Self::BankRedirect,
            PaymentMethodType::Blik => Self::BankRedirect,
            PaymentMethodType::Bluecode => Self::Wallet,
            PaymentMethodType::Alfamart => Self::Voucher,
            PaymentMethodType::CardRedirect => Self::CardRedirect,
            PaymentMethodType::CimbVa => Self::BankTransfer,
            PaymentMethodType::ClassicReward => Self::Reward,
            PaymentMethodType::Credit => Self::Card,
            #[cfg(feature = "v2")]
            PaymentMethodType::Card => Self::Card,
            PaymentMethodType::CryptoCurrency => Self::Crypto,
            PaymentMethodType::Dana => Self::Wallet,
            PaymentMethodType::DanamonVa => Self::BankTransfer,
            PaymentMethodType::Debit => Self::Card,
            PaymentMethodType::Flexiti => Self::PayLater,
            PaymentMethodType::Fps => Self::RealTimePayment,
            PaymentMethodType::DuitNow => Self::RealTimePayment,
            PaymentMethodType::Eft => Self::BankRedirect,
            PaymentMethodType::Eps => Self::BankRedirect,
            PaymentMethodType::Evoucher => Self::Reward,
            PaymentMethodType::Giropay => Self::BankRedirect,
            PaymentMethodType::GooglePay => Self::Wallet,
            PaymentMethodType::GoPay => Self::Wallet,
            PaymentMethodType::Gcash => Self::Wallet,
            PaymentMethodType::Mifinity => Self::Wallet,
            PaymentMethodType::Ideal => Self::BankRedirect,
            PaymentMethodType::Klarna => Self::PayLater,
            PaymentMethodType::KakaoPay => Self::Wallet,
            PaymentMethodType::Knet => Self::CardRedirect,
            PaymentMethodType::LocalBankRedirect => Self::BankRedirect,
            PaymentMethodType::MbWay => Self::Wallet,
            PaymentMethodType::MobilePay => Self::Wallet,
            PaymentMethodType::Momo => Self::Wallet,
            PaymentMethodType::MomoAtm => Self::CardRedirect,
            PaymentMethodType::Multibanco => Self::BankTransfer,
            PaymentMethodType::MandiriVa => Self::BankTransfer,
            PaymentMethodType::Interac => Self::BankRedirect,
            PaymentMethodType::InstantBankTransfer => Self::BankTransfer,
            PaymentMethodType::InstantBankTransferFinland => Self::BankTransfer,
            PaymentMethodType::InstantBankTransferPoland => Self::BankTransfer,
            PaymentMethodType::Indomaret => Self::Voucher,
            PaymentMethodType::OnlineBankingCzechRepublic => Self::BankRedirect,


// Function: get_api_event_metrics
// File: crates/analytics/src/api_event/core.rs
// Module: analytics

pub fn get_api_event_metrics(
    pool: &AnalyticsProvider,
    merchant_id: &common_utils::id_type::MerchantId,
    req: GetApiEventMetricRequest,
) -> AnalyticsResult<MetricsResponse<ApiMetricsBucketResponse>>


// File: crates/router/src/services/kafka/refund_event.rs
// Module: router
// Public functions: 2
// Public structs: 2

#[cfg(feature = "v2")]
use common_utils::pii;
#[cfg(feature = "v2")]
use common_utils::types::{self, ChargeRefunds};
use common_utils::{
    id_type,
    types::{ConnectorTransactionIdTrait, MinorUnit},
};
use diesel_models::{enums as storage_enums, refund::Refund};
use time::OffsetDateTime;

use crate::events;

#[cfg(feature = "v1")]
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaRefundEvent<'a> {
    pub internal_reference_id: &'a String,
    pub refund_id: &'a String, //merchant_reference id
    pub payment_id: &'a id_type::PaymentId,
    pub merchant_id: &'a id_type::MerchantId,
    pub connector_transaction_id: &'a String,
    pub connector: &'a String,
    pub connector_refund_id: Option<&'a String>,
    pub external_reference_id: Option<&'a String>,
    pub refund_type: &'a storage_enums::RefundType,
    pub total_amount: &'a MinorUnit,
    pub currency: &'a storage_enums::Currency,
    pub refund_amount: &'a MinorUnit,
    pub refund_status: &'a storage_enums::RefundStatus,
    pub sent_to_gateway: &'a bool,
    pub refund_error_message: Option<&'a String>,
    pub refund_arn: Option<&'a String>,
    #[serde(with = "time::serde::timestamp::nanoseconds")]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::timestamp::nanoseconds")]
    pub modified_at: OffsetDateTime,
    pub description: Option<&'a String>,
    pub attempt_id: &'a String,
    pub refund_reason: Option<&'a String>,
    pub refund_error_code: Option<&'a String>,
    pub profile_id: Option<&'a id_type::ProfileId>,
    pub organization_id: &'a id_type::OrganizationId,
}

#[cfg(feature = "v1")]
impl<'a> KafkaRefundEvent<'a> {
    pub fn from_storage(refund: &'a Refund) -> Self {
        Self {
            internal_reference_id: &refund.internal_reference_id,
            refund_id: &refund.refund_id,
            payment_id: &refund.payment_id,
            merchant_id: &refund.merchant_id,
            connector_transaction_id: refund.get_connector_transaction_id(),
            connector: &refund.connector,
            connector_refund_id: refund.get_optional_connector_refund_id(),
            external_reference_id: refund.external_reference_id.as_ref(),
            refund_type: &refund.refund_type,
            total_amount: &refund.total_amount,
            currency: &refund.currency,
            refund_amount: &refund.refund_amount,
            refund_status: &refund.refund_status,
            sent_to_gateway: &refund.sent_to_gateway,
            refund_error_message: refund.refund_error_message.as_ref(),
            refund_arn: refund.refund_arn.as_ref(),
            created_at: refund.created_at.assume_utc(),
            modified_at: refund.modified_at.assume_utc(),
            description: refund.description.as_ref(),
            attempt_id: &refund.attempt_id,
            refund_reason: refund.refund_reason.as_ref(),
            refund_error_code: refund.refund_error_code.as_ref(),
            profile_id: refund.profile_id.as_ref(),
            organization_id: &refund.organization_id,
        }
    }
}

#[cfg(feature = "v2")]
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaRefundEvent<'a> {
    pub refund_id: &'a id_type::GlobalRefundId,
    pub merchant_reference_id: &'a id_type::RefundReferenceId,
    pub payment_id: &'a id_type::GlobalPaymentId,
    pub merchant_id: &'a id_type::MerchantId,
    pub connector_transaction_id: &'a types::ConnectorTransactionId,
    pub connector: &'a String,
    pub connector_refund_id: Option<&'a types::ConnectorTransactionId>,
    pub external_reference_id: Option<&'a String>,
    pub refund_type: &'a storage_enums::RefundType,
    pub total_amount: &'a MinorUnit,
    pub currency: &'a storage_enums::Currency,
    pub refund_amount: &'a MinorUnit,
    pub refund_status: &'a storage_enums::RefundStatus,
    pub sent_to_gateway: &'a bool,
    pub refund_error_message: Option<&'a String>,
    pub refund_arn: Option<&'a String>,
    #[serde(with = "time::serde::timestamp::nanoseconds")]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::timestamp::nanoseconds")]
    pub modified_at: OffsetDateTime,
    pub description: Option<&'a String>,
    pub attempt_id: &'a id_type::GlobalAttemptId,
    pub refund_reason: Option<&'a String>,
    pub refund_error_code: Option<&'a String>,
    pub profile_id: Option<&'a id_type::ProfileId>,
    pub organization_id: &'a id_type::OrganizationId,

    pub metadata: Option<&'a pii::SecretSerdeValue>,
    pub updated_by: &'a String,
    pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
    pub charges: Option<&'a ChargeRefunds>,
    pub connector_refund_data: Option<&'a String>,
    pub connector_transaction_data: Option<&'a String>,
    pub split_refunds: Option<&'a common_types::refunds::SplitRefund>,
    pub unified_code: Option<&'a String>,
    pub unified_message: Option<&'a String>,
    pub processor_refund_data: Option<&'a String>,
    pub processor_transaction_data: Option<&'a String>,
}

#[cfg(feature = "v2")]
impl<'a> KafkaRefundEvent<'a> {
    pub fn from_storage(refund: &'a Refund) -> Self {
        let Refund {
            payment_id,
            merchant_id,
            connector_transaction_id,
            connector,
            connector_refund_id,
            external_reference_id,
            refund_type,
            total_amount,
            currency,
            refund_amount,
            refund_status,
            sent_to_gateway,
            refund_error_message,
            metadata,
            refund_arn,
            created_at,
            modified_at,
            description,
            attempt_id,
            refund_reason,
            refund_error_code,
            profile_id,
            updated_by,
            charges,
            organization_id,
            split_refunds,
            unified_code,
            unified_message,
            processor_refund_data,
            processor_transaction_data,
            id,
            merchant_reference_id,
            connector_id,
        } = refund;

        Self {
            refund_id: id,
            merchant_reference_id,
            payment_id,
            merchant_id,
            connector_transaction_id,
            connector,
            connector_refund_id: connector_refund_id.as_ref(),
            external_reference_id: external_reference_id.as_ref(),
            refund_type,
            total_amount,
            currency,
            refund_amount,
            refund_status,
            sent_to_gateway,
            refund_error_message: refund_error_message.as_ref(),
            refund_arn: refund_arn.as_ref(),
            created_at: created_at.assume_utc(),
            modified_at: modified_at.assume_utc(),
            description: description.as_ref(),
            attempt_id,
            refund_reason: refund_reason.as_ref(),
            refund_error_code: refund_error_code.as_ref(),
            profile_id: profile_id.as_ref(),
            organization_id,
            metadata: metadata.as_ref(),
            updated_by,
            merchant_connector_id: connector_id.as_ref(),
            charges: charges.as_ref(),
            connector_refund_data: processor_refund_data.as_ref(),
            connector_transaction_data: processor_transaction_data.as_ref(),
            split_refunds: split_refunds.as_ref(),
            unified_code: unified_code.as_ref(),
            unified_message: unified_message.as_ref(),
            processor_refund_data: processor_refund_data.as_ref(),
            processor_transaction_data: processor_transaction_data.as_ref(),
        }
    }
}

#[cfg(feature = "v1")]
impl super::KafkaMessage for KafkaRefundEvent<'_> {
    fn key(&self) -> String {
        format!(
            "{}_{}_{}_{}",
            self.merchant_id.get_string_repr(),
            self.payment_id.get_string_repr(),
            self.attempt_id,
            self.refund_id
        )
    }
    fn event_type(&self) -> events::EventType {
        events::EventType::Refund
    }
}

#[cfg(feature = "v2")]
impl super::KafkaMessage for KafkaRefundEvent<'_> {
    fn key(&self) -> String {
        format!(
            "{}_{}_{}_{}",
            self.merchant_id.get_string_repr(),
            self.payment_id.get_string_repr(),
            self.attempt_id.get_string_repr(),
            self.merchant_reference_id.get_string_repr()
        )
    }
    fn event_type(&self) -> events::EventType {
        events::EventType::Refund
    }
}


// Implementation: impl ConnectorValidation for for Riskified
// File: crates/hyperswitch_connectors/src/connectors/riskified.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl ConnectorValidation for for Riskified


// Struct: OnboardSubAccountResponse
// File: crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct OnboardSubAccountResponse


// Struct: CreditCardMethodData
// File: crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct CreditCardMethodData


// Implementation: impl webhooks::IncomingWebhook for for Worldpayvantiv
// File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)

impl webhooks::IncomingWebhook for for Worldpayvantiv


// Struct: PlainCardDetails
// File: crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct PlainCardDetails


// Implementation: impl api::RefundExecute for for Multisafepay
// File: crates/hyperswitch_connectors/src/connectors/multisafepay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::RefundExecute for for Multisafepay


// Function: payouts_fulfill
// File: crates/router/src/routes/payouts.rs
// Module: router

pub fn payouts_fulfill(
    state: web::Data<AppState>,
    req: HttpRequest,
    path: web::Path<id_type::PayoutId>,
) -> HttpResponse


// Function: perform_payment_ops
// File: crates/router/src/core/payment_methods.rs
// Module: router

pub fn perform_payment_ops(
        &self,
        state: &SessionState,
        parent_payment_method_token: Option<String>,
        pma: &api::CustomerPaymentMethodResponseItem,
        pm_list_context: PaymentMethodListContext,
    ) -> RouterResult<()>


// Implementation: impl Routing
// File: crates/router/src/routes/app.rs
// Module: router
// Methods: 1 total (1 public)

impl Routing


// Implementation: impl super::behaviour::Conversion for for Event
// File: crates/router/src/types/domain/event.rs
// Module: router
// Methods: 3 total (0 public)

impl super::behaviour::Conversion for for Event


// Function: get_transformed_response_payload
// File: crates/connector_configs/src/response_modifier.rs
// Module: connector_configs

pub fn get_transformed_response_payload(response: Self) -> DashboardRequestPayload


// Struct: PaymentIntentMetricsAccumulator
// File: crates/analytics/src/payment_intents/accumulator.rs
// Module: analytics
// Implementations: 1

pub struct PaymentIntentMetricsAccumulator


// Struct: CallbackURLs
// File: crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct CallbackURLs


// Struct: NmiRedirectResponseData
// File: crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct NmiRedirectResponseData


// Struct: SubscriptionCreateData
// File: crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct SubscriptionCreateData


// File: crates/router/src/core/verification/utils.rs
// Module: router
// Public functions: 4

use common_utils::{errors::CustomResult, id_type::PaymentId};
use error_stack::{Report, ResultExt};

use crate::{
    core::{
        errors::{self, utils::StorageErrorExt},
        utils,
    },
    logger,
    routes::SessionState,
    services::authentication::AuthenticationData,
    types::{self, storage},
};

pub async fn check_existence_and_add_domain_to_db(
    state: &SessionState,
    merchant_id: common_utils::id_type::MerchantId,
    profile_id_from_auth_layer: Option<common_utils::id_type::ProfileId>,
    merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
    domain_from_req: Vec<String>,
) -> CustomResult<Vec<String>, errors::ApiErrorResponse> {
    let key_manager_state = &state.into();
    let key_store = state
        .store
        .get_merchant_key_store_by_merchant_id(
            key_manager_state,
            &merchant_id,
            &state.store.get_master_key().to_vec().into(),
        )
        .await
        .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;

    #[cfg(feature = "v1")]
    let merchant_connector_account = state
        .store
        .find_by_merchant_connector_account_merchant_id_merchant_connector_id(
            key_manager_state,
            &merchant_id,
            &merchant_connector_id,
            &key_store,
        )
        .await
        .change_context(errors::ApiErrorResponse::InternalServerError)?;

    #[cfg(feature = "v2")]
    let merchant_connector_account = state
        .store
        .find_merchant_connector_account_by_id(
            key_manager_state,
            &merchant_connector_id,
            &key_store,
        )
        .await
        .change_context(errors::ApiErrorResponse::InternalServerError)?;
    utils::validate_profile_id_from_auth_layer(
        profile_id_from_auth_layer,
        &merchant_connector_account,
    )?;
    let mut already_verified_domains = merchant_connector_account
        .applepay_verified_domains
        .clone()
        .unwrap_or_default();

    let mut new_verified_domains: Vec<String> = domain_from_req
        .into_iter()
        .filter(|req_domain| !already_verified_domains.contains(req_domain))
        .collect();

    already_verified_domains.append(&mut new_verified_domains);
    #[cfg(feature = "v1")]
    let updated_mca = storage::MerchantConnectorAccountUpdate::Update {
        connector_type: None,
        connector_name: None,
        connector_account_details: Box::new(None),
        test_mode: None,
        disabled: None,
        merchant_connector_id: None,
        payment_methods_enabled: None,
        metadata: None,
        frm_configs: None,
        connector_webhook_details: Box::new(None),
        applepay_verified_domains: Some(already_verified_domains.clone()),
        pm_auth_config: Box::new(None),
        connector_label: None,
        status: None,
        connector_wallets_details: Box::new(None),
        additional_merchant_data: Box::new(None),
    };
    #[cfg(feature = "v2")]
    let updated_mca = storage::MerchantConnectorAccountUpdate::Update {
        connector_type: None,
        connector_account_details: Box::new(None),
        disabled: None,
        payment_methods_enabled: None,
        metadata: None,
        frm_configs: None,
        connector_webhook_details: Box::new(None),
        applepay_verified_domains: Some(already_verified_domains.clone()),
        pm_auth_config: Box::new(None),
        connector_label: None,
        status: None,
        connector_wallets_details: Box::new(None),
        additional_merchant_data: Box::new(None),
        feature_metadata: Box::new(None),
    };
    state
        .store
        .update_merchant_connector_account(
            key_manager_state,
            merchant_connector_account,
            updated_mca.into(),
            &key_store,
        )
        .await
        .change_context(errors::ApiErrorResponse::InternalServerError)
        .attach_printable_lazy(|| {
            format!(
                "Failed while updating MerchantConnectorAccount: id: {merchant_connector_id:?}",

            )
        })?;

    Ok(already_verified_domains.clone())
}

pub fn log_applepay_verification_response_if_error(
    response: &Result<Result<types::Response, types::Response>, Report<errors::ApiClientError>>,
) {
    if let Err(error) = response.as_ref() {
        logger::error!(applepay_domain_verification_error= ?error);
    };
    response.as_ref().ok().map(|res| {
        res.as_ref()
            .map_err(|error| logger::error!(applepay_domain_verification_error= ?error))
    });
}

#[cfg(feature = "v2")]
pub async fn check_if_profile_id_is_present_in_payment_intent(
    payment_id: PaymentId,
    state: &SessionState,
    auth_data: &AuthenticationData,
) -> CustomResult<(), errors::ApiErrorResponse> {
    todo!()
}

#[cfg(feature = "v1")]
pub async fn check_if_profile_id_is_present_in_payment_intent(
    payment_id: PaymentId,
    state: &SessionState,
    auth_data: &AuthenticationData,
) -> CustomResult<(), errors::ApiErrorResponse> {
    let db = &*state.store;
    let payment_intent = db
        .find_payment_intent_by_payment_id_merchant_id(
            &state.into(),
            &payment_id,
            auth_data.merchant_account.get_id(),
            &auth_data.key_store,
            auth_data.merchant_account.storage_scheme,
        )
        .await
        .change_context(errors::ApiErrorResponse::Unauthorized)?;

    utils::validate_profile_id_from_auth_layer(auth_data.profile_id.clone(), &payment_intent)
}


// Function: files_retrieve_core
// File: crates/router/src/core/files.rs
// Module: router

pub fn files_retrieve_core(
    state: SessionState,
    merchant_context: domain::MerchantContext,
    req: api::FileRetrieveRequest,
) -> RouterResponse<serde_json::Value>


// Implementation: impl common_utils::events::ApiEventMetric for for ThreeDsDecisionRuleExecuteRequest
// File: crates/api_models/src/three_ds_decision_rule.rs
// Module: api_models
// Methods: 1 total (0 public)

impl common_utils::events::ApiEventMetric for for ThreeDsDecisionRuleExecuteRequest


// Implementation: impl ConnectorSpecifications for for Mollie
// File: crates/hyperswitch_connectors/src/connectors/mollie.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl ConnectorSpecifications for for Mollie


// Implementation: impl HealthCheckDbInterface for for KafkaStore
// File: crates/router/src/db/kafka_store.rs
// Module: router
// Methods: 1 total (0 public)

impl HealthCheckDbInterface for for KafkaStore


// Implementation: impl api::MandateSetup for for Breadpay
// File: crates/hyperswitch_connectors/src/connectors/breadpay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::MandateSetup for for Breadpay


// Struct: AuthEventFilters
// File: crates/api_models/src/analytics/auth_events.rs
// Module: api_models
// Implementations: 0

pub struct AuthEventFilters


// Struct: WalletPMData
// File: crates/hyperswitch_connectors/src/connectors/aci/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct WalletPMData


// Function: route_connector_v2_for_payments
// File: crates/router/src/core/payments.rs
// Module: router

pub fn route_connector_v2_for_payments(
    state: &SessionState,
    merchant_context: &domain::MerchantContext,
    business_profile: &domain::Profile,
    transaction_data: core_routing::PaymentsDslInput<'_>,
    routing_data: &mut storage::RoutingData,
    _mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType>


// Implementation: impl ConnectorCommon for for Jpmorgan
// File: crates/hyperswitch_connectors/src/connectors/jpmorgan.rs
// Module: hyperswitch_connectors
// Methods: 5 total (0 public)

impl ConnectorCommon for for Jpmorgan


// Struct: NoonRouterData
// File: crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct NoonRouterData<T>


// Implementation: impl api::RefundSync for for Stripe
// File: crates/hyperswitch_connectors/src/connectors/stripe.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::RefundSync for for Stripe


// Struct: PaymentLinkBackgroundImageConfig
// File: crates/diesel_models/src/business_profile.rs
// Module: diesel_models
// Implementations: 0

pub struct PaymentLinkBackgroundImageConfig


// Struct: ServiceSessionIds
// File: crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct ServiceSessionIds


// Function: update_cards_info
// File: crates/router/src/routes/cards_info.rs
// Module: router

pub fn update_cards_info(
    state: web::Data<AppState>,
    req: HttpRequest,
    json_payload: web::Json<cards_info_api_types::CardInfoUpdateRequest>,
) -> impl Responder


// Function: api_key_create
// File: crates/openapi/src/routes/api_keys.rs
// Module: openapi

pub fn api_key_create()


// File: crates/external_services/src/crm.rs
// Module: external_services
// Public functions: 2
// Public structs: 3

use std::sync::Arc;

use common_utils::{
    errors::CustomResult,
    ext_traits::ConfigExt,
    request::{Method, Request, RequestBuilder, RequestContent},
};
use error_stack::ResultExt;
use http::header;
use hyperswitch_interfaces::{
    crm::{CrmInterface, CrmPayload},
    errors::HttpClientError,
    types::Proxy,
};
use reqwest;
use router_env::logger;

use crate::{http_client, hubspot_proxy::HubspotRequest};

/// Hubspot Crm configuration
#[derive(Debug, Clone, serde::Deserialize)]
pub struct HubspotProxyConfig {
    /// The ID of the Hubspot form to be submitted.
    pub form_id: String,

    /// The URL to which the Hubspot form data will be sent.
    pub request_url: String,
}

impl HubspotProxyConfig {
    /// Validates Hubspot configuration
    pub(super) fn validate(&self) -> Result<(), InvalidCrmConfig> {
        use common_utils::fp_utils::when;

        when(self.request_url.is_default_or_empty(), || {
            Err(InvalidCrmConfig("request url must not be empty"))
        })?;

        when(self.form_id.is_default_or_empty(), || {
            Err(InvalidCrmConfig("form_id must not be empty"))
        })
    }
}

/// Error thrown when the crm config is invalid
#[derive(Debug, Clone)]
pub struct InvalidCrmConfig(pub &'static str);

impl std::error::Error for InvalidCrmConfig {}

impl std::fmt::Display for InvalidCrmConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "crm: {}", self.0)
    }
}

#[derive(Debug, Clone, Copy)]
/// NoCrm struct
pub struct NoCrm;

/// Enum representing different Crm configurations
#[derive(Debug, Clone, Default, serde::Deserialize)]
#[serde(tag = "crm_manager")]
#[serde(rename_all = "snake_case")]
pub enum CrmManagerConfig {
    /// Hubspot Crm configuration
    HubspotProxy {
        /// Hubspot Crm configuration
        hubspot_proxy: HubspotProxyConfig,
    },

    /// No Crm configuration
    #[default]
    NoCrm,
}

impl CrmManagerConfig {
    /// Verifies that the client configuration is usable
    pub fn validate(&self) -> Result<(), InvalidCrmConfig> {
        match self {
            Self::HubspotProxy { hubspot_proxy } => hubspot_proxy.validate(),
            Self::NoCrm => Ok(()),
        }
    }

    /// Retrieves the appropriate Crm client based on the configuration.
    pub async fn get_crm_client(&self) -> Arc<dyn CrmInterface> {
        match self {
            Self::HubspotProxy { hubspot_proxy } => Arc::new(hubspot_proxy.clone()),
            Self::NoCrm => Arc::new(NoCrm),
        }
    }
}

#[async_trait::async_trait]
impl CrmInterface for NoCrm {
    async fn make_body(&self, _details: CrmPayload) -> RequestContent {
        RequestContent::Json(Box::new(()))
    }

    async fn make_request(&self, _body: RequestContent, _origin_base_url: String) -> Request {
        RequestBuilder::default().build()
    }

    async fn send_request(
        &self,
        _proxy: &Proxy,
        _request: Request,
    ) -> CustomResult<reqwest::Response, HttpClientError> {
        logger::info!("No CRM configured!");
        Err(HttpClientError::UnexpectedState).attach_printable("No CRM configured!")
    }
}

#[async_trait::async_trait]
impl CrmInterface for HubspotProxyConfig {
    async fn make_body(&self, details: CrmPayload) -> RequestContent {
        RequestContent::FormUrlEncoded(Box::new(HubspotRequest::new(
            details.business_country_name.unwrap_or_default(),
            self.form_id.clone(),
            details.poc_name.unwrap_or_default(),
            details.poc_email.clone().unwrap_or_default(),
            details.legal_business_name.unwrap_or_default(),
            details.business_website.unwrap_or_default(),
        )))
    }

    async fn make_request(&self, body: RequestContent, origin_base_url: String) -> Request {
        RequestBuilder::new()
            .method(Method::Post)
            .url(self.request_url.as_str())
            .set_body(body)
            .attach_default_headers()
            .headers(vec![(
                header::ORIGIN.to_string(),
                format!("{origin_base_url}/dashboard").into(),
            )])
            .build()
    }

    async fn send_request(
        &self,
        proxy: &Proxy,
        request: Request,
    ) -> CustomResult<reqwest::Response, HttpClientError> {
        http_client::send_request(proxy, request, None).await
    }
}


// Function: update_resource
// File: crates/storage_impl/src/mock_db.rs
// Module: storage_impl

pub fn update_resource<D, R>(
        &self,
        state: &KeyManagerState,
        key_store: &MerchantKeyStore,
        mut resources: MutexGuard<'_, Vec<D>>,
        resource_updated: D,
        filter_fn: impl Fn(&&mut D) -> bool,
        error_message: String,
    ) -> CustomResult<R, StorageError>
    where
        D: Sync + ReverseConversion<R> + Clone,
        R: Conversion,


// Struct: OpennodeErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/opennode/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct OpennodeErrorResponse


// Implementation: impl api::Payment for for Hipay
// File: crates/hyperswitch_connectors/src/connectors/hipay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::Payment for for Hipay


// Implementation: impl RecurringDetails
// File: crates/api_models/src/mandates.rs
// Module: api_models
// Methods: 1 total (1 public)

impl RecurringDetails


// Struct: NoonApplePayHeader
// File: crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct NoonApplePayHeader


// Implementation: impl api::PaymentToken for for Tesouro
// File: crates/hyperswitch_connectors/src/connectors/tesouro.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::PaymentToken for for Tesouro


// Implementation: impl SubmitEvidence for for Checkout
// File: crates/hyperswitch_connectors/src/connectors/checkout.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl SubmitEvidence for for Checkout


// Struct: CardsInfoRequestParams
// File: crates/api_models/src/cards_info.rs
// Module: api_models
// Implementations: 0

pub struct CardsInfoRequestParams


// Function: schedule_refund_execution
// File: crates/router/src/core/refunds.rs
// Module: router

pub fn schedule_refund_execution(
    state: &SessionState,
    refund: diesel_refund::Refund,
    refund_type: api_models::refunds::RefundType,
    merchant_context: &domain::MerchantContext,
    payment_attempt: &storage::PaymentAttempt,
    payment_intent: &storage::PaymentIntent,
    creds_identifier: Option<String>,
    split_refunds: Option<SplitRefundsRequest>,
) -> RouterResult<diesel_refund::Refund>


// Implementation: impl PaymentLink
// File: crates/diesel_models/src/query/payment_link.rs
// Module: diesel_models
// Methods: 1 total (0 public)

impl PaymentLink


// Function: set_sso_id_in_redis
// File: crates/router/src/utils/user.rs
// Module: router

pub fn set_sso_id_in_redis(
    state: &SessionState,
    oidc_state: Secret<String>,
    sso_id: String,
) -> UserResult<()>


// Struct: NexixpayTransactionResponse
// File: crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct NexixpayTransactionResponse


// Struct: VoltPaymentsRequest
// File: crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct VoltPaymentsRequest


// Struct: Amount
// File: crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct Amount


// Trait: ConstructFlowSpecificData
// File: crates/router/src/core/payments/flows.rs
// Module: router

pub trait ConstructFlowSpecificData<F, Req, Res>


// File: crates/analytics/src/sdk_events/metrics/load_time.rs
// Module: analytics

use std::collections::HashSet;

use api_models::analytics::{
    sdk_events::{
        SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames,
    },
    Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;

use super::SdkEventMetricRow;
use crate::{
    query::{Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window},
    types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};

#[derive(Default)]
pub(super) struct LoadTime;

#[async_trait::async_trait]
impl<T> super::SdkEventMetric<T> for LoadTime
where
    T: AnalyticsDataSource + super::SdkEventMetricAnalytics,
    PrimitiveDateTime: ToSql<T>,
    AnalyticsCollection: ToSql<T>,
    Granularity: GroupByClause<T>,
    Aggregate<&'static str>: ToSql<T>,
    Window<&'static str>: ToSql<T>,
{
    async fn load_metrics(
        &self,
        dimensions: &[SdkEventDimensions],
        publishable_key: &str,
        filters: &SdkEventFilters,
        granularity: Option<Granularity>,
        time_range: &TimeRange,
        pool: &T,
    ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> {
        let mut query_builder: QueryBuilder<T> =
            QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics);
        let dimensions = dimensions.to_vec();

        for dim in dimensions.iter() {
            query_builder.add_select_column(dim).switch()?;
        }

        query_builder
            .add_select_column(Aggregate::Percentile {
                field: "latency",
                alias: Some("count"),
                percentile: Some(&50),
            })
            .switch()?;

        if let Some(granularity) = granularity {
            query_builder
                .add_granularity_in_mins(granularity)
                .switch()?;
        }

        filters.set_filter_clause(&mut query_builder).switch()?;

        query_builder
            .add_filter_clause("merchant_id", publishable_key)
            .switch()?;

        query_builder
            .add_bool_filter_clause("first_event", 1)
            .switch()?;

        query_builder
            .add_filter_clause("event_name", SdkEventNames::AppRendered)
            .switch()?;

        query_builder
            .add_custom_filter_clause("latency", 0, FilterTypes::Gt)
            .switch()?;

        time_range
            .set_filter_clause(&mut query_builder)
            .attach_printable("Error filtering time range")
            .switch()?;

        for dim in dimensions.iter() {
            query_builder
                .add_group_by_clause(dim)
                .attach_printable("Error grouping by dimensions")
                .switch()?;
        }

        if let Some(_granularity) = granularity.as_ref() {
            query_builder
                .add_group_by_clause("time_bucket")
                .attach_printable("Error adding granularity")
                .switch()?;
        }

        query_builder
            .execute_query::<SdkEventMetricRow, _>(pool)
            .await
            .change_context(MetricsError::QueryBuildingError)?
            .change_context(MetricsError::QueryExecutionFailure)?
            .into_iter()
            .map(|i| {
                Ok((
                    SdkEventMetricsBucketIdentifier::new(
                        i.payment_method.clone(),
                        i.platform.clone(),
                        i.browser_name.clone(),
                        i.source.clone(),
                        i.component.clone(),
                        i.payment_experience.clone(),
                        i.time_bucket.clone(),
                    ),
                    i,
                ))
            })
            .collect::<error_stack::Result<
                HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>,
                crate::query::PostProcessingError,
            >>()
            .change_context(MetricsError::PostProcessingFailure)
    }
}


// File: crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
// Module: hyperswitch_connectors
// Public structs: 21

use api_models::webhooks::IncomingWebhookEvent;
use common_enums::{AttemptStatus, Currency, FraudCheckStatus, PaymentMethod};
use common_utils::{ext_traits::ValueExt, pii::Email};
use error_stack::{self, ResultExt};
pub use hyperswitch_domain_models::router_request_types::fraud_check::RefundMethod;
use hyperswitch_domain_models::{
    router_data::RouterData,
    router_flow_types::Fulfillment,
    router_request_types::{
        fraud_check::{self, FraudCheckFulfillmentData, FrmFulfillmentRequest},
        ResponseId,
    },
    router_response_types::fraud_check::FraudCheckResponseData,
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
use num_traits::ToPrimitive;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;

use crate::{
    types::{
        FrmCheckoutRouterData, FrmFulfillmentRouterData, FrmRecordReturnRouterData,
        FrmSaleRouterData, FrmTransactionRouterData, ResponseRouterData,
    },
    utils::{
        AddressDetailsData as _, FraudCheckCheckoutRequest, FraudCheckRecordReturnRequest as _,
        FraudCheckSaleRequest as _, FraudCheckTransactionRequest as _, RouterData as _,
    },
};
#[allow(dead_code)]
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DecisionDelivery {
    Sync,
    AsyncOnly,
}

#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Purchase {
    #[serde(with = "common_utils::custom_serde::iso8601")]
    created_at: PrimitiveDateTime,
    order_channel: OrderChannel,
    total_price: i64,
    products: Vec<Products>,
    shipments: Shipments,
    currency: Option<Currency>,
    total_shipping_cost: Option<i64>,
    confirmation_email: Option<Email>,
    confirmation_phone: Option<Secret<String>>,
}

#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde(rename_all(serialize = "SCREAMING_SNAKE_CASE", deserialize = "snake_case"))]
pub enum OrderChannel {
    Web,
    Phone,
    MobileApp,
    Social,
    Marketplace,
    InStoreKiosk,
    ScanAndGo,
    SmartTv,
    Mit,
}

#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde(rename_all(serialize = "SCREAMING_SNAKE_CASE", deserialize = "snake_case"))]
pub enum FulfillmentMethod {
    Delivery,
    CounterPickup,
    CubsidePickup,
    LockerPickup,
    StandardShipping,
    ExpeditedShipping,
    GasPickup,
    ScheduledDelivery,
}

#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Products {
    item_name: String,
    item_price: i64,
    item_quantity: i32,
    item_id: Option<String>,
    item_category: Option<String>,
    item_sub_category: Option<String>,
    item_is_digital: Option<bool>,
}

#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Shipments {
    destination: Destination,
    fulfillment_method: Option<FulfillmentMethod>,
}

#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Destination {
    full_name: Secret<String>,
    organization: Option<String>,
    email: Option<Email>,
    address: Address,
}

#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Address {
    street_address: Secret<String>,
    unit: Option<Secret<String>>,
    postal_code: Secret<String>,
    city: String,
    province_code: Secret<String>,
    country_code: common_enums::CountryAlpha2,
}

#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde(rename_all(serialize = "SCREAMING_SNAKE_CASE", deserialize = "snake_case"))]
pub enum CoverageRequests {
    Fraud, // use when you need a financial guarantee for Payment Fraud.
    Inr,   // use when you need a financial guarantee for Item Not Received.
    Snad, // use when you need a financial guarantee for fraud alleging items are Significantly Not As Described.
    All,  // use when you need a financial guarantee on all chargebacks.
    None, // use when you do not need a financial guarantee. Suggested actions in decision.checkpointAction are recommendations.
}

#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsSaleRequest {
    order_id: String,
    purchase: Purchase,
    decision_delivery: DecisionDelivery,
    coverage_requests: Option<CoverageRequests>,
}

#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde(rename_all(serialize = "camelCase", deserialize = "snake_case"))]
pub struct SignifydFrmMetadata {
    pub total_shipping_cost: Option<i64>,
    pub fulfillment_method: Option<FulfillmentMethod>,
    pub coverage_request: Option<CoverageRequests>,
    pub order_channel: OrderChannel,
}

impl TryFrom<&FrmSaleRouterData> for SignifydPaymentsSaleRequest {
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(item: &FrmSaleRouterData) -> Result<Self, Self::Error> {
        let products = item
            .request
            .get_order_details()?
            .iter()
            .map(|order_detail| Products {
                item_name: order_detail.product_name.clone(),
                item_price: order_detail.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future.
                item_quantity: i32::from(order_detail.quantity),
                item_id: order_detail.product_id.clone(),
                item_category: order_detail.category.clone(),
                item_sub_category: order_detail.sub_category.clone(),
                item_is_digital: order_detail
                    .product_type
                    .as_ref()
                    .map(|product| product == &common_enums::ProductType::Digital),
            })
            .collect::<Vec<_>>();
        let metadata: SignifydFrmMetadata = item
            .frm_metadata
            .clone()
            .ok_or(ConnectorError::MissingRequiredField {
                field_name: "frm_metadata",
            })?
            .parse_value("Signifyd Frm Metadata")
            .change_context(ConnectorError::InvalidDataFormat {
                field_name: "frm_metadata",
            })?;
        let ship_address = item.get_shipping_address()?;
        let billing_address = item.get_billing()?;
        let street_addr = ship_address.get_line1()?;
        let city_addr = ship_address.get_city()?;
        let zip_code_addr = ship_address.get_zip()?;
        let country_code_addr = ship_address.get_country()?;
        let _first_name_addr = ship_address.get_first_name()?;
        let _last_name_addr = ship_address.get_last_name()?;
        let address: Address = Address {
            street_address: street_addr.clone(),
            unit: None,
            postal_code: zip_code_addr.clone(),
            city: city_addr.clone(),
            province_code: zip_code_addr.clone(),
            country_code: country_code_addr.to_owned(),
        };
        let destination: Destination = Destination {
            full_name: ship_address.get_full_name().unwrap_or_default(),
            organization: None,
            email: None,
            address,
        };

        let created_at = common_utils::date_time::now();
        let order_channel = metadata.order_channel;
        let shipments = Shipments {
            destination,
            fulfillment_method: metadata.fulfillment_method,
        };
        let purchase = Purchase {
            created_at,
            order_channel,
            total_price: item.request.amount,
            products,
            shipments,
            currency: item.request.currency,
            total_shipping_cost: metadata.total_shipping_cost,
            confirmation_email: item.request.email.clone(),
            confirmation_phone: billing_address
                .clone()
                .phone
                .and_then(|phone_data| phone_data.number),
        };
        Ok(Self {
            order_id: item.attempt_id.clone(),
            purchase,
            decision_delivery: DecisionDelivery::Sync, // Specify SYNC if you require the Response to contain a decision field. If you have registered for a webhook associated with this checkpoint, then the webhook will also be sent when SYNC is specified. If ASYNC_ONLY is specified, then the decision field in the response will be null, and you will require a Webhook integration to receive Signifyd's final decision
            coverage_requests: metadata.coverage_request,
        })
    }
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Decision {
    #[serde(with = "common_utils::custom_serde::iso8601")]
    created_at: PrimitiveDateTime,
    checkpoint_action: SignifydPaymentStatus,
    checkpoint_action_reason: Option<String>,
    checkpoint_action_policy: Option<String>,
    score: Option<f64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SignifydPaymentStatus {
    Accept,
    Challenge,
    Credit,
    Hold,
    Reject,
}

impl From<SignifydPaymentStatus> for FraudCheckStatus {
    fn from(item: SignifydPaymentStatus) -> Self {
        match item {
            SignifydPaymentStatus::Accept => Self::Legit,
            SignifydPaymentStatus::Reject => Self::Fraud,
            SignifydPaymentStatus::Hold => Self::ManualReview,
            SignifydPaymentStatus::Challenge | SignifydPaymentStatus::Credit => Self::Pending,
        }
    }
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsResponse {
    signifyd_id: i64,
    order_id: String,
    decision: Decision,
}

impl<F, T> TryFrom<ResponseRouterData<F, SignifydPaymentsResponse, T, FraudCheckResponseData>>
    for RouterData<F, T, FraudCheckResponseData>
{
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(
        item: ResponseRouterData<F, SignifydPaymentsResponse, T, FraudCheckResponseData>,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            response: Ok(FraudCheckResponseData::TransactionResponse {
                resource_id: ResponseId::ConnectorTransactionId(item.response.order_id),
                status: FraudCheckStatus::from(item.response.decision.checkpoint_action),
                connector_metadata: None,
                score: item.response.decision.score.and_then(|data| data.to_i32()),
                reason: item
                    .response
                    .decision
                    .checkpoint_action_reason
                    .map(serde_json::Value::from),
            }),
            ..item.data
        })
    }
}

#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct SignifydErrorResponse {
    pub messages: Vec<String>,
    pub errors: serde_json::Value,
}

#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Transactions {
    transaction_id: String,
    gateway_status_code: String,
    payment_method: PaymentMethod,
    amount: i64,
    currency: Currency,
    gateway: Option<String>,
}

#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsTransactionRequest {
    order_id: String,
    checkout_id: String,
    transactions: Transactions,
}

impl From<AttemptStatus> for GatewayStatusCode {
    fn from(item: AttemptStatus) -> Self {
        match item {
            AttemptStatus::Pending => Self::Pending,
            AttemptStatus::Failure => Self::Failure,
            AttemptStatus::Charged => Self::Success,
            _ => Self::Pending,
        }
    }
}

impl TryFrom<&FrmTransactionRouterData> for SignifydPaymentsTransactionRequest {
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(item: &FrmTransactionRouterData) -> Result<Self, Self::Error> {
        let currency = item.request.get_currency()?;
        let transactions = Transactions {
            amount: item.request.amount,
            transaction_id: item.clone().payment_id,
            gateway_status_code: GatewayStatusCode::from(item.status).to_string(),
            payment_method: item.payment_method,
            currency,
            gateway: item.request.connector.clone(),
        };
        Ok(Self {
            order_id: item.attempt_id.clone(),
            checkout_id: item.payment_id.clone(),
            transactions,
        })
    }
}

#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    Eq,
    PartialEq,
    serde::Serialize,
    serde::Deserialize,
    strum::Display,
    strum::EnumString,
)]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
pub enum GatewayStatusCode {
    Success,
    Failure,
    #[default]
    Pending,
    Error,
    Cancelled,
    Expired,
    SoftDecline,
}

#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsCheckoutRequest {
    checkout_id: String,
    order_id: String,
    purchase: Purchase,
    coverage_requests: Option<CoverageRequests>,
}

impl TryFrom<&FrmCheckoutRouterData> for SignifydPaymentsCheckoutRequest {
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(item: &FrmCheckoutRouterData) -> Result<Self, Self::Error> {
        let products = item
            .request
            .get_order_details()?
            .iter()
            .map(|order_detail| Products {
                item_name: order_detail.product_name.clone(),
                item_price: order_detail.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future.
                item_quantity: i32::from(order_detail.quantity),
                item_id: order_detail.product_id.clone(),
                item_category: order_detail.category.clone(),
                item_sub_category: order_detail.sub_category.clone(),
                item_is_digital: order_detail
                    .product_type
                    .as_ref()
                    .map(|product| product == &common_enums::ProductType::Digital),
            })
            .collect::<Vec<_>>();
        let metadata: SignifydFrmMetadata = item
            .frm_metadata
            .clone()
            .ok_or(ConnectorError::MissingRequiredField {
                field_name: "frm_metadata",
            })?
            .parse_value("Signifyd Frm Metadata")
            .change_context(ConnectorError::InvalidDataFormat {
                field_name: "frm_metadata",
            })?;
        let ship_address = item.get_shipping_address()?;
        let street_addr = ship_address.get_line1()?;
        let city_addr = ship_address.get_city()?;
        let zip_code_addr = ship_address.get_zip()?;
        let country_code_addr = ship_address.get_country()?;
        let _first_name_addr = ship_address.get_first_name()?;
        let _last_name_addr = ship_address.get_last_name()?;
        let billing_address = item.get_billing()?;
        let address: Address = Address {
            street_address: street_addr.clone(),
            unit: None,
            postal_code: zip_code_addr.clone(),
            city: city_addr.clone(),
            province_code: zip_code_addr.clone(),
            country_code: country_code_addr.to_owned(),
        };
        let destination: Destination = Destination {
            full_name: ship_address.get_full_name().unwrap_or_default(),
            organization: None,
            email: None,
            address,
        };
        let created_at = common_utils::date_time::now();
        let order_channel = metadata.order_channel;
        let shipments: Shipments = Shipments {
            destination,
            fulfillment_method: metadata.fulfillment_method,
        };
        let purchase = Purchase {
            created_at,
            order_channel,
            total_price: item.request.amount,
            products,
            shipments,
            currency: item.request.currency,
            total_shipping_cost: metadata.total_shipping_cost,
            confirmation_email: item.request.email.clone(),
            confirmation_phone: billing_address
                .clone()
                .phone
                .and_then(|phone_data| phone_data.number),
        };
        Ok(Self {
            checkout_id: item.payment_id.clone(),
            order_id: item.attempt_id.clone(),
            purchase,
            coverage_requests: metadata.coverage_request,
        })
    }
}

#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct FrmFulfillmentSignifydRequest {
    pub order_id: String,
    pub fulfillment_status: Option<FulfillmentStatus>,
    pub fulfillments: Vec<Fulfillments>,
}

#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde(untagged)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub enum FulfillmentStatus {
    PARTIAL,
    COMPLETE,
    REPLACEMENT,
    CANCELED,
}

#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct Fulfillments {
    pub shipment_id: String,
    pub products: Option<Vec<Product>>,
    pub destination: Destination,
    pub fulfillment_method: Option<String>,
    pub carrier: Option<String>,
    pub shipment_status: Option<String>,
    pub tracking_urls: Option<Vec<String>>,
    pub tracking_numbers: Option<Vec<String>>,
    pub shipped_at: Option<String>,
}

#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct Product {
    pub item_name: String,
    pub item_quantity: i64,
    pub item_id: String,
}

impl TryFrom<&FrmFulfillmentRouterData> for FrmFulfillmentSignifydRequest {
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(item: &FrmFulfillmentRouterData) -> Result<Self, Self::Error> {
        Ok(Self {
            order_id: item.request.fulfillment_req.order_id.clone(),
            fulfillment_status: item
                .request
                .fulfillment_req
                .fulfillment_status
                .as_ref()
                .map(|fulfillment_status| FulfillmentStatus::from(&fulfillment_status.clone())),
            fulfillments: get_signifyd_fulfillments_from_frm_fulfillment_request(
                &item.request.fulfillment_req,
            ),
        })
    }
}

impl From<&fraud_check::FulfillmentStatus> for FulfillmentStatus {
    fn from(status: &fraud_check::FulfillmentStatus) -> Self {
        match status {
            fraud_check::FulfillmentStatus::PARTIAL => Self::PARTIAL,
            fraud_check::FulfillmentStatus::COMPLETE => Self::COMPLETE,
            fraud_check::FulfillmentStatus::REPLACEMENT => Self::REPLACEMENT,
            fraud_check::FulfillmentStatus::CANCELED => Self::CANCELED,
        }
    }
}
pub(crate) fn get_signifyd_fulfillments_from_frm_fulfillment_request(
    fulfillment_req: &FrmFulfillmentRequest,
) -> Vec<Fulfillments> {
    fulfillment_req
        .fulfillments
        .iter()
        .map(|fulfillment| Fulfillments {
            shipment_id: fulfillment.shipment_id.clone(),
            products: fulfillment
                .products
                .as_ref()
                .map(|products| products.iter().map(|p| Product::from(p.clone())).collect()),
            destination: Destination::from(fulfillment.destination.clone()),
            tracking_urls: fulfillment_req.tracking_urls.clone(),
            tracking_numbers: fulfillment_req.tracking_numbers.clone(),
            fulfillment_method: fulfillment_req.fulfillment_method.clone(),
            carrier: fulfillment_req.carrier.clone(),
            shipment_status: fulfillment_req.shipment_status.clone(),
            shipped_at: fulfillment_req.shipped_at.clone(),
        })
        .collect()
}

impl From<fraud_check::Product> for Product {
    fn from(product: fraud_check::Product) -> Self {
        Self {
            item_name: product.item_name,
            item_quantity: product.item_quantity,
            item_id: product.item_id,
        }
    }
}

impl From<fraud_check::Destination> for Destination {
    fn from(destination: fraud_check::Destination) -> Self {
        Self {
            full_name: destination.full_name,
            organization: destination.organization,
            email: destination.email,
            address: Address::from(destination.address),
        }
    }
}

impl From<fraud_check::Address> for Address {
    fn from(address: fraud_check::Address) -> Self {
        Self {
            street_address: address.street_address,
            unit: address.unit,
            postal_code: address.postal_code,
            city: address.city,
            province_code: address.province_code,
            country_code: address.country_code,
        }
    }
}

#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct FrmFulfillmentSignifydApiResponse {
    pub order_id: String,
    pub shipment_ids: Vec<String>,
}

impl
    TryFrom<
        ResponseRouterData<
            Fulfillment,
            FrmFulfillmentSignifydApiResponse,
            FraudCheckFulfillmentData,
            FraudCheckResponseData,
        >,
    > for RouterData<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>
{
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(
        item: ResponseRouterData<
            Fulfillment,
            FrmFulfillmentSignifydApiResponse,
            FraudCheckFulfillmentData,
            FraudCheckResponseData,
        >,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            response: Ok(FraudCheckResponseData::FulfillmentResponse {
                order_id: item.response.order_id,
                shipment_ids: item.response.shipment_ids,
            }),
            ..item.data
        })
    }
}

#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct SignifydRefund {
    method: RefundMethod,
    amount: String,
    currency: Currency,
}

#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsRecordReturnRequest {
    order_id: String,
    return_id: String,
    refund_transaction_id: Option<String>,
    refund: SignifydRefund,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct SignifydPaymentsRecordReturnResponse {
    return_id: String,
    order_id: String,
}

impl<F, T>
    TryFrom<ResponseRouterData<F, SignifydPaymentsRecordReturnResponse, T, FraudCheckResponseData>>
    for RouterData<F, T, FraudCheckResponseData>
{
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(
        item: ResponseRouterData<
            F,
            SignifydPaymentsRecordReturnResponse,
            T,
            FraudCheckResponseData,
        >,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            response: Ok(FraudCheckResponseData::RecordReturnResponse {
                resource_id: ResponseId::ConnectorTransactionId(item.response.order_id),
                return_id: Some(item.response.return_id.to_string()),
                connector_metadata: None,
            }),
            ..item.data
        })
    }
}

impl TryFrom<&FrmRecordReturnRouterData> for SignifydPaymentsRecordReturnRequest {
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(item: &FrmRecordReturnRouterData) -> Result<Self, Self::Error> {
        let currency = item.request.get_currency()?;
        let refund = SignifydRefund {
            method: item.request.refund_method.clone(),
            amount: item.request.amount.to_string(),
            currency,
        };
        Ok(Self {
            return_id: uuid::Uuid::new_v4().to_string(),
            refund_transaction_id: item.request.refund_transaction_id.clone(),
            refund,
            order_id: item.attempt_id.clone(),
        })
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SignifydWebhookBody {
    pub order_id: String,
    pub review_disposition: ReviewDisposition,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ReviewDisposition {
    Fraudulent,
    Good,
}

impl From<ReviewDisposition> for IncomingWebhookEvent {
    fn from(value: ReviewDisposition) -> Self {
        match value {
            ReviewDisposition::Fraudulent => Self::FrmRejected,
            ReviewDisposition::Good => Self::FrmApproved,
        }
    }
}


// Function: get_connector_wallets_details
// File: crates/hyperswitch_domain_models/src/merchant_connector_account.rs
// Module: hyperswitch_domain_models

pub fn get_connector_wallets_details(&self) -> Option<Secret<Value>>


// Function: server
// File: crates/router/src/routes/app.rs
// Module: router

pub fn server(state: AppState) -> Scope


// Function: initiate_pm_collect_link
// File: crates/router/src/core/payment_methods.rs
// Module: router

pub fn initiate_pm_collect_link(
    state: SessionState,
    merchant_context: domain::MerchantContext,
    req: payment_methods::PaymentMethodCollectLinkRequest,
) -> RouterResponse<payment_methods::PaymentMethodCollectLinkResponse>


// Function: find_by_global_id
// File: crates/diesel_models/src/query/customers.rs
// Module: diesel_models

pub fn find_by_global_id(
        conn: &PgPooledConn,
        id: &id_type::GlobalCustomerId,
    ) -> StorageResult<Self>


// Function: generate
// File: crates/common_utils/src/id_type/global_id/payment.rs
// Module: common_utils

// Documentation: Generate a new GlobalAttemptId from a cell id

pub fn generate(cell_id: &super::CellId) -> Self


// Struct: MpgsPaymentsRequest
// File: crates/hyperswitch_connectors/src/connectors/mpgs/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct MpgsPaymentsRequest


// Implementation: impl api::PaymentVoid for for Prophetpay
// File: crates/hyperswitch_connectors/src/connectors/prophetpay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::PaymentVoid for for Prophetpay


// Implementation: impl AuthorizationUpdateInternal
// File: crates/diesel_models/src/authorization.rs
// Module: diesel_models
// Methods: 1 total (1 public)

impl AuthorizationUpdateInternal


// Trait: AuthEventFilterAnalytics
// File: crates/analytics/src/auth_events/filters.rs
// Module: analytics

pub trait AuthEventFilterAnalytics: LoadRow<AuthEventFilterRow>


// Function: new
// File: crates/api_models/src/routing.rs
// Module: api_models

pub fn new(
        algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
            common_utils::id_type::RoutingId,
        >,
    ) -> Self


// Implementation: impl MerchantConnectorAccount
// File: crates/diesel_models/src/merchant_connector_account.rs
// Module: diesel_models
// Methods: 1 total (1 public)

impl MerchantConnectorAccount


// Struct: CreateCustomerRequest
// File: crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct CreateCustomerRequest


// Implementation: impl api::RefundExecute for for Blackhawknetwork
// File: crates/hyperswitch_connectors/src/connectors/blackhawknetwork.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::RefundExecute for for Blackhawknetwork


// Struct: DisputesFlowData
// File: crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct DisputesFlowData


// Function: get_refund_webhook_statuses
// File: crates/hyperswitch_domain_models/src/business_profile.rs
// Module: hyperswitch_domain_models

pub fn get_refund_webhook_statuses(&self) -> Cow<'_, [common_enums::RefundStatus]>


// Implementation: impl ConnectorCommon for for UnifiedAuthenticationService
// File: crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs
// Module: hyperswitch_connectors
// Methods: 5 total (0 public)

impl ConnectorCommon for for UnifiedAuthenticationService


// Struct: IntermediateString
// File: crates/external_services/src/email.rs
// Module: external_services
// Implementations: 1

pub struct IntermediateString


// File: crates/analytics/src/payments/metrics/success_rate.rs
// Module: analytics

use std::collections::HashSet;

use api_models::analytics::{
    payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier},
    Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;

use super::PaymentMetricRow;
use crate::{
    enums::AuthInfo,
    query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
    types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};

#[derive(Default)]
pub(super) struct PaymentSuccessRate;

#[async_trait::async_trait]
impl<T> super::PaymentMetric<T> for PaymentSuccessRate
where
    T: AnalyticsDataSource + super::PaymentMetricAnalytics,
    PrimitiveDateTime: ToSql<T>,
    AnalyticsCollection: ToSql<T>,
    Granularity: GroupByClause<T>,
    Aggregate<&'static str>: ToSql<T>,
    Window<&'static str>: ToSql<T>,
{
    async fn load_metrics(
        &self,
        dimensions: &[PaymentDimensions],
        auth: &AuthInfo,
        filters: &PaymentFilters,
        granularity: Option<Granularity>,
        time_range: &TimeRange,
        pool: &T,
    ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> {
        let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Payment);
        let mut dimensions = dimensions.to_vec();

        dimensions.push(PaymentDimensions::PaymentStatus);

        for dim in dimensions.iter() {
            query_builder.add_select_column(dim).switch()?;
        }

        query_builder
            .add_select_column(Aggregate::Count {
                field: None,
                alias: Some("count"),
            })
            .switch()?;
        query_builder
            .add_select_column(Aggregate::Min {
                field: "created_at",
                alias: Some("start_bucket"),
            })
            .switch()?;
        query_builder
            .add_select_column(Aggregate::Max {
                field: "created_at",
                alias: Some("end_bucket"),
            })
            .switch()?;

        filters.set_filter_clause(&mut query_builder).switch()?;

        auth.set_filter_clause(&mut query_builder).switch()?;

        time_range
            .set_filter_clause(&mut query_builder)
            .attach_printable("Error filtering time range")
            .switch()?;

        for dim in dimensions.iter() {
            query_builder
                .add_group_by_clause(dim)
                .attach_printable("Error grouping by dimensions")
                .switch()?;
        }

        if let Some(granularity) = granularity {
            granularity
                .set_group_by_clause(&mut query_builder)
                .attach_printable("Error adding granularity")
                .switch()?;
        }

        query_builder
            .execute_query::<PaymentMetricRow, _>(pool)
            .await
            .change_context(MetricsError::QueryBuildingError)?
            .change_context(MetricsError::QueryExecutionFailure)?
            .into_iter()
            .map(|i| {
                Ok((
                    PaymentMetricsBucketIdentifier::new(
                        i.currency.as_ref().map(|i| i.0),
                        None,
                        i.connector.clone(),
                        i.authentication_type.as_ref().map(|i| i.0),
                        i.payment_method.clone(),
                        i.payment_method_type.clone(),
                        i.client_source.clone(),
                        i.client_version.clone(),
                        i.profile_id.clone(),
                        i.card_network.clone(),
                        i.merchant_id.clone(),
                        i.card_last_4.clone(),
                        i.card_issuer.clone(),
                        i.error_reason.clone(),
                        i.routing_approach.as_ref().map(|i| i.0.clone()),
                        i.signature_network.clone(),
                        i.is_issuer_regulated,
                        i.is_debit_routed,
                        TimeRange {
                            start_time: match (granularity, i.start_bucket) {
                                (Some(g), Some(st)) => g.clip_to_start(st)?,
                                _ => time_range.start_time,
                            },
                            end_time: granularity.as_ref().map_or_else(
                                || Ok(time_range.end_time),
                                |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
                            )?,
                        },
                    ),
                    i,
                ))
            })
            .collect::<error_stack::Result<
                HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>,
                crate::query::PostProcessingError,
            >>()
            .change_context(MetricsError::PostProcessingFailure)
    }
}


// Function: routing_unlink_config
// File: crates/openapi/src/routes/routing.rs
// Module: openapi

pub fn routing_unlink_config()


// Implementation: impl std::ops::Deref for for PaymentsTokenReference
// File: crates/diesel_models/src/payment_method.rs
// Module: diesel_models
// Methods: 1 total (0 public)

impl std::ops::Deref for for PaymentsTokenReference


// Function: validate_create_request
// File: crates/router/src/core/payouts/validator.rs
// Module: router

pub fn validate_create_request(
    state: &SessionState,
    merchant_context: &domain::MerchantContext,
    req: &payouts::PayoutCreateRequest,
) -> RouterResult<(
    id_type::PayoutId,
    Option<payouts::PayoutMethodData>,
    id_type::ProfileId,
    Option<domain::Customer>,
    Option<PaymentMethod>,
)>


// Implementation: impl FraudCheck
// File: crates/diesel_models/src/query/fraud_check.rs
// Module: diesel_models
// Methods: 3 total (0 public)

impl FraudCheck