repo stringclasses 4 values | file_path stringlengths 6 193 | extension stringclasses 23 values | content stringlengths 0 1.73M | token_count int64 0 724k | __index_level_0__ int64 0 10.8k |
|---|---|---|---|---|---|
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RecoveryProcessors/RevenueRecoveryBillingProcessors/BillingProcessorsWebhooks.res | .res | @react.component
let make = (~initialValues, ~merchantId, ~onNextClick) => {
let connectorInfoDict = ConnectorInterface.mapDictToConnectorPayload(
ConnectorInterface.connectorInterfaceV2,
initialValues->LogicUtils.getDictFromJsonObject,
)
<RevenueRecoveryOnboardingUtils.PageWrapper
title="Setup Subscription Webhook"
subTitle="Configure this endpoint in the subscription management system dashboard under webhook settings for us to pick up failed payments for recovery.">
<div className="mb-10 flex flex-col gap-7">
<div className="mb-10 flex flex-col gap-7 w-540-px">
<ConnectorWebhookPreview
merchantId
connectorName=connectorInfoDict.id
textCss="border border-nd_gray-400 font-medium rounded-xl px-4 py-2 mb-6 mt-6 text-nd_gray-400 w-full !font-jetbrain-mono"
containerClass="flex flex-row items-center justify-between"
displayTextLength=38
hideLabel=true
showFullCopy=true
/>
<Button text="Next" buttonType=Primary onClick={onNextClick} customButtonStyle="w-full" />
</div>
</div>
</RevenueRecoveryOnboardingUtils.PageWrapper>
}
| 286 | 9,321 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RecoveryProcessors/RevenueRecoveryBillingProcessors/BillingProcessorsUtils.res | .res | module SubHeading = {
@react.component
let make = (~title, ~subTitle) => {
<div className="flex flex-col gap-1">
<p className="text-lg font-semibold text-grey-800"> {title->React.string} </p>
<p className="text-sm text-gray-500"> {subTitle->React.string} </p>
</div>
}
}
let getConnectorDetails = (connectorList: array<ConnectorTypes.connectorPayloadV2>) => {
let (mca, name) = switch connectorList->Array.get(0) {
| Some(connectorDetails) => (connectorDetails.id, connectorDetails.connector_name)
| _ => ("", "")
}
(mca, name)
}
let getConnectorConfig = connector => {
switch connector {
| "chargebee" =>
{
"connector_auth": {
"HeaderKey": {
"api_key": "Chargebee API Key",
},
},
"connector_webhook_details": {
"merchant_secret": "Username",
"additional_secret": "Password",
},
"metadata": {
"site": [
("name", "site"),
("label", "Site"),
("placeholder", "Enter chargebee site"),
("required", "true"),
("type", "Text"),
]->Map.fromArray,
},
}->Identity.genericTypeToJson
| _ => JSON.Encode.null
}
}
| 315 | 9,322 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RecoveryProcessors/RevenueRecoveryBillingProcessors/BillingProcessorsConfigureRetry.res | .res | @react.component
let make = (~handleAuthKeySubmit, ~initialValues, ~validateMandatoryField) => {
open RevenueRecoveryOnboardingUtils
<PageWrapper
title="Configure Recovery Plan"
subTitle="Set up how invoices should be selected and processed for recovery.">
<div className="mb-10 flex flex-col gap-8">
<Form onSubmit={handleAuthKeySubmit} initialValues validate=validateMandatoryField>
<div>
<div className="text-nd_gray-700 font-medium flex gap-2 w-fit align-center">
{"Start Retry After"->React.string}
<ToolTip
height="mt-0.5"
description="Sets the number of failed attempts that will be monitored before initiating retry scheduling"
toolTipFor={<div className="cursor-pointer">
<Icon name="info-vacent" size=13 />
</div>}
toolTipPosition=ToolTip.Top
newDesign=true
/>
</div>
<div className="-m-1 -mt-3">
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={FormRenderer.makeFieldInfo(
~label="",
~name="feature_metadata.revenue_recovery.billing_connector_retry_threshold",
~toolTipPosition=Right,
~customInput=InputFields.numericTextInput(~customStyle="border rounded-xl"),
~placeholder="ex 3",
)}
/>
</div>
</div>
<div className="mt-5">
<div className="text-nd_gray-700 font-medium flex gap-2 w-fit">
{"Max Retry Attempts"->React.string}
<ToolTip
height="mt-0.5"
description="Defines the maximum number of retry attempts before the system stops trying."
toolTipFor={<div className="cursor-pointer">
<Icon name="info-vacent" size=13 />
</div>}
toolTipPosition=ToolTip.Top
newDesign=true
/>
</div>
<div className="-m-1 -mt-3">
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={FormRenderer.makeFieldInfo(
~label="",
~name="feature_metadata.revenue_recovery.max_retry_count",
~toolTipPosition=Right,
~customInput=InputFields.numericTextInput(~customStyle="border rounded-xl"),
~placeholder="ex 15",
)}
/>
<FormRenderer.SubmitButton
text="Next"
buttonSize={Small}
customSumbitButtonStyle="!w-full mt-8"
tooltipForWidthClass="w-full"
/>
</div>
</div>
<FormValuesSpy />
</Form>
</div>
</PageWrapper>
}
| 612 | 9,323 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RecoveryProcessors/RevenueRecoveryOnboarding/RevenueRecoveryOnboardingUtils.res | .res | open VerticalStepIndicatorTypes
open RevenueRecoveryOnboardingTypes
let getMainStepName = step => {
switch step {
| #connectProcessor => "Connect Processor"
| #addAPlatform => "Add a Platform"
| #reviewDetails => "Review Details"
}
}
let getStepName = step => {
switch step {
| #selectProcessor => "Select a Processor"
| #activePaymentMethods => "Active Payment Methods"
| #setupWebhookProcessor => "Setup Webhook"
| #selectAPlatform => "Select a Platform"
| #configureRetries => "Configure Retries"
| #connectProcessor => "Connect Processor"
| #setupWebhookPlatform => "Setup Webhook"
}
}
let getIcon = step => {
switch step {
| #connectProcessor => "nd-inbox"
| #addAPlatform => "nd-plugin"
| #reviewDetails => "nd-flag"
}
}
let sections = [
{
id: (#connectProcessor: revenueRecoverySections :> string),
name: #connectProcessor->getMainStepName,
icon: #connectProcessor->getIcon,
subSections: Some([
{
id: (#selectProcessor: revenueRecoverySubsections :> string),
name: #selectProcessor->getStepName,
},
{
id: (#setupWebhookProcessor: revenueRecoverySubsections :> string),
name: #setupWebhookProcessor->getStepName,
},
]),
},
{
id: (#addAPlatform: revenueRecoverySections :> string),
name: #addAPlatform->getMainStepName,
icon: #addAPlatform->getIcon,
subSections: Some([
{
id: (#selectAPlatform: revenueRecoverySubsections :> string),
name: #selectAPlatform->getStepName,
},
{
id: (#configureRetries: revenueRecoverySubsections :> string),
name: #configureRetries->getStepName,
},
{
id: (#connectProcessor: revenueRecoverySubsections :> string),
name: #connectProcessor->getStepName,
},
{
id: (#setupWebhookPlatform: revenueRecoverySubsections :> string),
name: #setupWebhookPlatform->getStepName,
},
]),
},
{
id: (#reviewDetails: revenueRecoverySections :> string),
name: #reviewDetails->getMainStepName,
icon: #reviewDetails->getIcon,
subSections: None,
},
]
let defaultStep = {
sectionId: (#connectProcessor: revenueRecoverySections :> string),
subSectionId: Some((#selectProcessor: revenueRecoverySubsections :> string)),
}
let defaultStepBilling = {
sectionId: (#addAPlatform: revenueRecoverySections :> string),
subSectionId: Some((#selectAPlatform: revenueRecoverySubsections :> string)),
}
open VerticalStepIndicatorUtils
let getNextStep = (currentStep: step): option<step> => {
findNextStep(sections, currentStep)
}
let getPreviousStep = (currentStep: step): option<step> => {
findPreviousStep(sections, currentStep)
}
let onNextClick = (currentStep, setNextStep) => {
switch getNextStep(currentStep) {
| Some(nextStep) => setNextStep(_ => nextStep)
| None => ()
}
}
let onPreviousClick = (currentStep, setNextStep) => {
switch getPreviousStep(currentStep) {
| Some(previousStep) => setNextStep(_ => previousStep)
| None => ()
}
}
let getSectionVariant = ({sectionId, subSectionId}) => {
let mainSection = switch sectionId {
| "connectProcessor" => #connectProcessor
| "addAPlatform" => #addAPlatform
| "reviewDetails" | _ => #reviewDetails
}
let subSection = switch subSectionId {
| Some("selectProcessor") => #selectProcessor
| Some("activePaymentMethods") => #activePaymentMethods
| Some("setupWebhookProcessor") => #setupWebhookProcessor
| Some("selectAPlatform") => #selectAPlatform
| Some("configureRetries") => #configureRetries
| Some("connectProcessor") => #connectProcessor
| Some("setupWebhookPlatform") | _ => #setupWebhookPlatform
}
(mainSection, subSection)
}
let sampleDataBanner =
<div
className="absolute z-10 top-76-px left-0 w-full py-4 px-10 bg-orange-50 flex justify-between items-center">
<div className="flex gap-4 items-center">
<Icon name="nd-information-triangle" size=24 />
<p className="text-nd_gray-600 text-base leading-6 font-medium">
{"You are in demo environment and this is sample setup."->React.string}
</p>
</div>
</div>
module PageWrapper = {
@react.component
let make = (~title, ~subTitle, ~children) => {
<div className="flex flex-col gap-7">
<PageUtils.PageHeading
title subTitle customSubTitleStyle="font-500 font-normal text-nd_gray-700"
/>
{children}
</div>
}
}
open ConnectorTypes
let billingConnectorList: array<connectorTypes> = [BillingProcessor(CHARGEBEE)]
let getOptions: array<ConnectorTypes.connectorTypes> => array<
SelectBox.dropdownOption,
> = dropdownList => {
open ConnectorUtils
let options: array<SelectBox.dropdownOption> = dropdownList->Array.map((
connector
): SelectBox.dropdownOption => {
let connectorValue = connector->getConnectorNameString
let connectorName = switch connector {
| BillingProcessor(processor) => processor->getDisplayNameForBillingProcessor
| Processors(processor) => processor->getDisplayNameForProcessor
| _ => ""
}
{
label: connectorName,
customRowClass: "my-1",
value: connectorValue,
icon: Button.CustomIcon(
<GatewayIcon gateway={connectorValue->String.toUpperCase} className="mr-2 w-5 h-5" />,
),
}
})
options
}
let getMixpanelEventName = currentStep => {
switch currentStep->getSectionVariant {
| (#connectProcessor, #selectProcessor) => "recovery_payment_processor_step1"
| (#connectProcessor, #activePaymentMethods) => "recovery_payment_processor_step2"
| (#connectProcessor, #setupWebhookProcessor) => "recovery_payment_processor_step3"
| (#addAPlatform, #selectAPlatform) => "recovery_billing_processor_step1"
| (#addAPlatform, #configureRetries) => "recovery_billing_processor_step2"
| (#addAPlatform, #connectProcessor) => "recovery_billing_processor_step3"
| (#addAPlatform, #setupWebhookPlatform) => "recovery_billing_processor_step4"
| _ => ""
}
}
| 1,564 | 9,324 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RecoveryProcessors/RevenueRecoveryOnboarding/RevenueRecoveryData.res | .res | let connector_account_details = {
"auth_type": "HeaderKey",
"api_key": "sk_51HfYdZK8b3X9qLmW
",
}->Identity.genericTypeToJson
let payment_connector_webhook_details = {
"merchant_secret": "secret_9FvX2YtL7KqW4",
}->Identity.genericTypeToJson
let metadata = {
"site": "site_9FvX2YtL7KqW4",
}->Identity.genericTypeToJson
let connector_webhook_details = {
"merchant_secret": "secret_9FvX2YtL7KqW4",
"additional_secret": "secret_A7XgT5L2Yt9F",
}->Identity.genericTypeToJson
let feature_metadata = (~id) => {
let billing_account_reference =
[(id, "acct_12Xy9KqW4RmJ0P5vN6ZC3XgTLM8S2A7"->JSON.Encode.string)]->Dict.fromArray
{
"revenue_recovery": {
"billing_connector_retry_threshold": 3,
"max_retry_count": 15,
"billing_account_reference": billing_account_reference->Identity.genericTypeToJson,
},
}->Identity.genericTypeToJson
}
let orderData = {
"count": 20,
"total_count": 20,
"data": [
{
"id": "12345_pay_001",
"status": "processing",
"amount": {
"order_amount": 100,
"currency": "INR",
"net_amount": 100,
},
"connector": "stripe",
"client_secret": "12345_secret_001",
"created": "2025-03-19T10:01:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "bhim",
"attempts": [
{
"id": "12345_att_001_01",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_001_02",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_001_03",
"status": "failure",
"error": "Fraud suspicion",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_001_04",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_001_05",
"status": "failure",
"error": "Decline due to daily cutoff being in progress",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_001_06",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_001_07",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_001_08",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_001_09",
"status": "failure",
"error": "Decline due to daily cutoff being in progress",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_001_10",
"status": "upcoming_attempt",
"error": "",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_002",
"status": "processing",
"amount": {
"order_amount": 200,
"currency": "INR",
"net_amount": 200,
},
"connector": "stripe",
"client_secret": "12345_secret_002",
"created": "2025-03-18T10:02:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "credit",
"attempts": [
{
"id": "12345_att_002_01",
"status": "failure",
"error": "Card expired",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_002_02",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_002_03",
"status": "failure",
"error": "Transaction limit exceeded",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_002_04",
"status": "failure",
"error": "Card expired",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_002_05",
"status": "failure",
"error": "Fraud suspicion",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_002_06",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_002_07",
"status": "upcoming_attempt",
"error": "",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_003",
"status": "failed",
"amount": {
"order_amount": 300,
"currency": "INR",
"net_amount": 300,
},
"connector": "stripe",
"client_secret": "12345_secret_003",
"created": "2025-03-17T10:03:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "bhim",
"attempts": [
{
"id": "12345_att_003_01",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_003_02",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_003_03",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_003_04",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_003_05",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_003_06",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_003_07",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_003_08",
"status": "failure",
"error": "Decline due to daily cutoff being in progress",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_003_09",
"status": "failure",
"error": "Decline due to daily cutoff being in progress",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_003_10",
"status": "failure",
"error": "3D Secure authentication failed",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_003_11",
"status": "failure",
"error": "Decline due to daily cutoff being in progress",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_003_12",
"status": "failure",
"error": "3D Secure authentication failed",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_003_13",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_003_14",
"status": "failure",
"error": "Insufficient funds",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_003_15",
"status": "failure",
"error": "Decline due to daily cutoff being in progress",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_004",
"status": "succeeded",
"amount": {
"order_amount": 400,
"currency": "INR",
"net_amount": 400,
},
"connector": "stripe",
"client_secret": "12345_secret_004",
"created": "2025-03-16T10:04:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "credit",
"attempts": [
{
"id": "12345_att_004_01",
"status": "failure",
"error": "Transaction limit exceeded",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_004_02",
"status": "failure",
"error": "Transaction limit exceeded",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_004_03",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_004_04",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_004_05",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_004_06",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_004_07",
"status": "failure",
"error": "Fraud suspicion",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_004_08",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_004_09",
"status": "charged",
"error": "",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_005",
"status": "processing",
"amount": {
"order_amount": 500,
"currency": "INR",
"net_amount": 500,
},
"connector": "stripe",
"client_secret": "12345_secret_005",
"created": "2025-03-15T10:05:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "bhim",
"attempts": [
{
"id": "12345_att_005_01",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_005_02",
"status": "failure",
"error": "Decline due to daily cutoff being in progress",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_005_03",
"status": "failure",
"error": "Decline due to daily cutoff being in progress",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_005_04",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_005_05",
"status": "failure",
"error": "Card expired",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_005_06",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_005_07",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_005_08",
"status": "failure",
"error": "Fraud suspicion",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_005_09",
"status": "failure",
"error": "Insufficient funds",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_005_10",
"status": "upcoming_attempt",
"error": "",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_006",
"status": "failed",
"amount": {
"order_amount": 600,
"currency": "INR",
"net_amount": 600,
},
"connector": "stripe",
"client_secret": "12345_secret_006",
"created": "2025-03-14T10:06:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "credit",
"attempts": [
{
"id": "12345_att_006_01",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_006_02",
"status": "failure",
"error": "Transaction limit exceeded",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_006_03",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_006_04",
"status": "failure",
"error": "Transaction limit exceeded",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_006_05",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_006_06",
"status": "failure",
"error": "Fraud suspicion",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_006_07",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_006_08",
"status": "failure",
"error": "Insufficient funds",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_006_09",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_006_10",
"status": "failure",
"error": "Card expired",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_006_11",
"status": "failure",
"error": "Insufficient funds",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_006_12",
"status": "failure",
"error": "Insufficient funds",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_006_13",
"status": "failure",
"error": "3D Secure authentication failed",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_006_14",
"status": "failure",
"error": "Decline due to daily cutoff being in progress",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_006_15",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_007",
"status": "processing",
"amount": {
"order_amount": 700,
"currency": "INR",
"net_amount": 700,
},
"connector": "stripe",
"client_secret": "12345_secret_007",
"created": "2025-03-13T10:07:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "bhim",
"attempts": [
{
"id": "12345_att_007_01",
"status": "failure",
"error": "Decline due to daily cutoff being in progress",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_007_02",
"status": "failure",
"error": "Decline due to daily cutoff being in progress",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_007_03",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_007_04",
"status": "failure",
"error": "Fraud suspicion",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_007_05",
"status": "failure",
"error": "Transaction limit exceeded",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_007_06",
"status": "failure",
"error": "Fraud suspicion",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_007_07",
"status": "failure",
"error": "Decline due to daily cutoff being in progress",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_007_08",
"status": "failure",
"error": "Fraud suspicion",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_007_09",
"status": "upcoming_attempt",
"error": "",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_008",
"status": "succeeded",
"amount": {
"order_amount": 800,
"currency": "INR",
"net_amount": 800,
},
"connector": "stripe",
"client_secret": "12345_secret_008",
"created": "2025-03-12T10:08:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "credit",
"attempts": [
{
"id": "12345_att_008_01",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_008_02",
"status": "charged",
"error": "",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_009",
"status": "failed",
"amount": {
"order_amount": 900,
"currency": "INR",
"net_amount": 900,
},
"connector": "stripe",
"client_secret": "12345_secret_009",
"created": "2025-03-11T10:09:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "bhim",
"attempts": [
{
"id": "12345_att_009_01",
"status": "failure",
"error": "Transaction limit exceeded",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_009_02",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_009_03",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_009_04",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_009_05",
"status": "failure",
"error": "3D Secure authentication failed",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_009_06",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_009_07",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_009_08",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_009_09",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_009_10",
"status": "failure",
"error": "Fraud suspicion",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_009_11",
"status": "failure",
"error": "3D Secure authentication failed",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_009_12",
"status": "failure",
"error": "Insufficient funds",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_009_13",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_009_14",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_009_15",
"status": "failure",
"error": "Transaction limit exceeded",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_010",
"status": "processing",
"amount": {
"order_amount": 1000,
"currency": "INR",
"net_amount": 1000,
},
"connector": "stripe",
"client_secret": "12345_secret_010",
"created": "2025-03-10T10:10:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "credit",
"attempts": [
{
"id": "12345_att_010_01",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_010_02",
"status": "failure",
"error": "3D Secure authentication failed",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_010_03",
"status": "failure",
"error": "Card expired",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_010_04",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_010_05",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_010_06",
"status": "failure",
"error": "Card expired",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_010_07",
"status": "upcoming_attempt",
"error": "",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_011",
"status": "processing",
"amount": {
"order_amount": 1100,
"currency": "INR",
"net_amount": 1100,
},
"connector": "stripe",
"client_secret": "12345_secret_011",
"created": "2025-03-9T10:11:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "bhim",
"attempts": [
{
"id": "12345_att_011_01",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_011_02",
"status": "failure",
"error": "Transaction limit exceeded",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_011_03",
"status": "failure",
"error": "Decline due to daily cutoff being in progress",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_011_04",
"status": "failure",
"error": "Insufficient funds",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_011_05",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_011_06",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_011_07",
"status": "failure",
"error": "Fraud suspicion",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_011_08",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_011_09",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_011_10",
"status": "upcoming_attempt",
"error": "",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_012",
"status": "succeeded",
"amount": {
"order_amount": 1200,
"currency": "INR",
"net_amount": 1200,
},
"connector": "stripe",
"client_secret": "12345_secret_012",
"created": "2025-03-8T10:12:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "credit",
"attempts": [
{
"id": "12345_att_012_01",
"status": "charged",
"error": "",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_013",
"status": "processing",
"amount": {
"order_amount": 1300,
"currency": "INR",
"net_amount": 1300,
},
"connector": "stripe",
"client_secret": "12345_secret_013",
"created": "2025-03-7T10:13:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "bhim",
"attempts": [
{
"id": "12345_att_013_01",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_013_02",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_013_03",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_013_04",
"status": "failure",
"error": "Fraud suspicion",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_013_05",
"status": "failure",
"error": "Transaction limit exceeded",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_013_06",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_013_07",
"status": "failure",
"error": "Card expired",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_013_08",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_013_09",
"status": "upcoming_attempt",
"error": "",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_014",
"status": "processing",
"amount": {
"order_amount": 1400,
"currency": "INR",
"net_amount": 1400,
},
"connector": "stripe",
"client_secret": "12345_secret_014",
"created": "2025-03-6T10:14:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "credit",
"attempts": [
{
"id": "12345_att_014_01",
"status": "failure",
"error": "3D Secure authentication failed",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_014_02",
"status": "failure",
"error": "Fraud suspicion",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_014_03",
"status": "failure",
"error": "Card expired",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_014_04",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_014_05",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_014_06",
"status": "failure",
"error": "Card expired",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_014_07",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_014_08",
"status": "upcoming_attempt",
"error": "",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_015",
"status": "failed",
"amount": {
"order_amount": 1500,
"currency": "INR",
"net_amount": 1500,
},
"connector": "stripe",
"client_secret": "12345_secret_015",
"created": "2025-03-5T10:15:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "bhim",
"attempts": [
{
"id": "12345_att_015_01",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_015_02",
"status": "failure",
"error": "Card expired",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_015_03",
"status": "failure",
"error": "3D Secure authentication failed",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_015_04",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_015_05",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_015_06",
"status": "failure",
"error": "Fraud suspicion",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_015_07",
"status": "failure",
"error": "Transaction limit exceeded",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_015_08",
"status": "failure",
"error": "Fraud suspicion",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_015_09",
"status": "failure",
"error": "Transaction limit exceeded",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_015_10",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_015_11",
"status": "failure",
"error": "Insufficient funds",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_015_12",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_015_13",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_015_14",
"status": "failure",
"error": "Insufficient funds",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_015_15",
"status": "failure",
"error": "Decline due to daily cutoff being in progress",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_016",
"status": "succeeded",
"amount": {
"order_amount": 1600,
"currency": "INR",
"net_amount": 1600,
},
"connector": "stripe",
"client_secret": "12345_secret_016",
"created": "2025-03-4T10:16:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "credit",
"attempts": [
{
"id": "12345_att_016_01",
"status": "failure",
"error": "Insufficient funds",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_016_02",
"status": "failure",
"error": "Transaction limit exceeded",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_016_03",
"status": "failure",
"error": "Insufficient funds",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_016_04",
"status": "charged",
"error": "",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_017",
"status": "processing",
"amount": {
"order_amount": 1700,
"currency": "INR",
"net_amount": 1700,
},
"connector": "stripe",
"client_secret": "12345_secret_017",
"created": "2025-03-3T10:17:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "bhim",
"attempts": [
{
"id": "12345_att_017_01",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_017_02",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_017_03",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_017_04",
"status": "failure",
"error": "Transaction limit exceeded",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_017_05",
"status": "failure",
"error": "Card expired",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_017_06",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_017_07",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_017_08",
"status": "upcoming_attempt",
"error": "",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_018",
"status": "failed",
"amount": {
"order_amount": 1800,
"currency": "INR",
"net_amount": 1800,
},
"connector": "stripe",
"client_secret": "12345_secret_018",
"created": "2025-03-2T10:18:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "credit",
"attempts": [
{
"id": "12345_att_018_01",
"status": "failure",
"error": "3D Secure authentication failed",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_018_02",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_018_03",
"status": "failure",
"error": "Transaction limit exceeded",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_018_04",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_018_05",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_018_06",
"status": "failure",
"error": "Fraud suspicion",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_018_07",
"status": "failure",
"error": "Decline due to daily cutoff being in progress",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_018_08",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_018_09",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_018_10",
"status": "failure",
"error": "Card expired",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_018_11",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_018_12",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_018_13",
"status": "failure",
"error": "Fraud suspicion",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_018_14",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_018_15",
"status": "failure",
"error": "Insufficient funds",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_019",
"status": "processing",
"amount": {
"order_amount": 1900,
"currency": "INR",
"net_amount": 1900,
},
"connector": "stripe",
"client_secret": "12345_secret_019",
"created": "2025-03-1T10:19:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "bhim",
"attempts": [
{
"id": "12345_att_019_01",
"status": "failure",
"error": "3D Secure authentication failed",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_019_02",
"status": "failure",
"error": "Insufficient funds",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_019_03",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_019_04",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_019_05",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_019_06",
"status": "failure",
"error": "Decline due to daily cutoff being in progress",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_019_07",
"status": "failure",
"error": "3D Secure authentication failed",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_019_08",
"status": "failure",
"error": "Insufficient funds",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_019_09",
"status": "failure",
"error": "Transaction limit exceeded",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_019_10",
"status": "upcoming_attempt",
"error": "",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
{
"id": "12345_pay_020",
"status": "succeeded",
"amount": {
"order_amount": 2000,
"currency": "INR",
"net_amount": 2000,
},
"connector": "stripe",
"client_secret": "12345_secret_020",
"created": "2025-03-0T10:20:03.000Z",
"payment_method_type": "card",
"payment_method_subtype": "credit",
"attempts": [
{
"id": "12345_att_020_01",
"status": "failure",
"error": "Invalid payment method",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_020_02",
"status": "failure",
"error": "Invalid CVV",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_020_03",
"status": "failure",
"error": "Bank server unavailable",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_020_04",
"status": "failure",
"error": "Account restricted",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "external",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_020_05",
"status": "failure",
"error": "3D Secure authentication failed",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
{
"id": "12345_att_020_06",
"status": "charged",
"error": "",
"feature_metadata": {
"revenue_recovery": {
"attempt_triggered_by": "internal",
},
},
"created": "2025-03-17T13:20:12.000Z",
},
],
},
],
}->Identity.genericTypeToJson
| 20,811 | 9,325 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RecoveryProcessors/RevenueRecoveryOnboarding/RevenueRecoveryOnboardingLanding.res | .res | @react.component
let make = (~createMerchant) => {
open PageUtils
let mixpanelEvent = MixpanelHook.useSendEvent()
let {setCreateNewMerchant} = React.useContext(ProductSelectionProvider.defaultContext)
let userHasCreateMerchantAccess = OMPCreateAccessHook.useOMPCreateAccessHook([
#tenant_admin,
#org_admin,
])
<div className="flex flex-1 flex-col gap-14 items-center justify-center w-full h-screen">
<img className="h-56" alt="recoveryOnboarging" src="/assets/DefaultHomeRecoveryCard.svg" />
<div className="flex flex-col gap-7 items-center">
<div
className="border rounded-md text-nd_green-200 border-nd_green-200 font-semibold p-1.5 text-sm w-fit mb-5">
{"Recovery"->React.string}
</div>
<PageHeading
customHeadingStyle="flex flex-col items-center"
title="Never lose revenue to unwarranted churn"
customTitleStyle="text-2xl text-center font-bold"
customSubTitleStyle="text-fs-16 font-normal text-center max-w-700"
subTitle="Maximize retention and recover failed transactions with automated retry strategies."
/>
<ACLButton
authorization={userHasCreateMerchantAccess}
text={"Get Started"}
onClick={_ => {
if createMerchant {
mixpanelEvent(~eventName="recovery_get_started_new_merchant")
setCreateNewMerchant(ProductTypes.Recovery)
} else {
mixpanelEvent(~eventName="recovery_integrate_connectors_")
RescriptReactRouter.replace(
GlobalVars.appendDashboardPath(~url=`/v2/recovery/onboarding`),
)
}
}}
buttonType=Primary
buttonSize=Large
buttonState=Normal
/>
</div>
</div>
}
| 418 | 9,326 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RecoveryProcessors/RevenueRecoveryOnboarding/RevenueRecoveryOnboarding.res | .res | @react.component
let make = () => {
open RevenueRecoveryOnboardingUtils
let connectorList = ConnectorInterface.useConnectorArrayMapper(
~interface=ConnectorInterface.connectorInterfaceV2,
~retainInList=PaymentProcessor,
)
let hasConfiguredPaymentConnector = connectorList->Array.length > 0
let (connectorID, connectorName) = connectorList->BillingProcessorsUtils.getConnectorDetails
let (currentStep, setNextStep) = React.useState(() =>
hasConfiguredPaymentConnector ? defaultStepBilling : defaultStep
)
let {setShowSideBar} = React.useContext(GlobalProvider.defaultContext)
let {getUserInfoData} = React.useContext(UserInfoProvider.defaultContext)
let {profileId, merchantId} = getUserInfoData()
let (_, getNameForId) = OMPSwitchHooks.useOMPData()
let activeBusinessProfile = getNameForId(#Profile)
let (paymentConnectorName, setPaymentConnectorName) = React.useState(() => connectorName)
let (paymentConnectorID, setPaymentConnectorID) = React.useState(() => connectorID)
let (billingConnectorName, setBillingConnectorName) = React.useState(() => "")
React.useEffect(() => {
setShowSideBar(_ => false)
(
() => {
setShowSideBar(_ => true)
}
)->Some
}, [])
<div className="flex flex-row">
<VerticalStepIndicator
titleElement={"Setup Recovery"->React.string}
sections
currentStep
backClick={() => {
RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url="/v2/recovery/overview"))
}}
/>
<div className="flex flex-row ml-14 mt-16 w-540-px">
<RecoveryOnboardingPayments
currentStep
setConnectorID={setPaymentConnectorID}
connector={paymentConnectorName}
setConnectorName={setPaymentConnectorName}
setNextStep
profileId
merchantId
activeBusinessProfile
/>
<RecoveryOnboardingBilling
currentStep
connectorID={paymentConnectorID}
connector=billingConnectorName
paymentConnectorName={paymentConnectorName}
setConnectorName=setBillingConnectorName
setNextStep
profileId
merchantId
activeBusinessProfile
/>
</div>
</div>
}
| 515 | 9,327 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RecoveryProcessors/RevenueRecoveryOnboarding/RevenueRecoveryOnboardingTypes.res | .res | type revenueRecoverySections = [#connectProcessor | #addAPlatform | #reviewDetails]
type revenueRecoverySubsections = [
| #selectProcessor
| #activePaymentMethods
| #setupWebhookProcessor
| #selectAPlatform
| #configureRetries
| #connectProcessor
| #setupWebhookPlatform
]
| 77 | 9,328 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RecoveryProcessors/RecoveryProcessorsPaymentProcessors/RecoveryProcessorCards.res | .res | let p1MediumTextStyle = HSwitchUtils.getTextClass((P1, Medium))
module RequestConnector = {
@react.component
let make = (~connectorList, ~setShowModal) => {
<RenderIf condition={connectorList->Array.length === 0}>
<div
className="flex flex-col gap-6 items-center justify-center w-full bg-white rounded-lg border p-8">
<div className="mb-8 mt-4 max-w-full h-auto">
<img alt="notfound" src={`${LogicUtils.useUrlPrefix()}/notfound.svg`} />
</div>
<p className="jp-grey-700 opacity-50">
{"Uh-oh! Looks like we couldn't find the processor you were searching for."->React.string}
</p>
<Button
text={"Request a processor"} buttonType=Primary onClick={_ => setShowModal(_ => true)}
/>
</div>
</RenderIf>
}
}
module CantFindProcessor = {
@react.component
let make = (~showRequestConnectorBtn, ~setShowModal) => {
<RenderIf condition={showRequestConnectorBtn}>
<div
className="flex flex-row items-center gap-2 text-primary cursor-pointer"
onClick={_ => setShowModal(_ => true)}>
<ToolTip />
{"Request a processor"->React.string}
</div>
</RenderIf>
}
}
@react.component
let make = (
~connectorsAvailableForIntegration: array<ConnectorTypes.connectorTypes>,
~configuredConnectors: array<ConnectorTypes.connectorTypes>,
~showAllConnectors=true,
~connectorType=ConnectorTypes.Processor,
~setProcessorModal=_ => (),
~showTestProcessor=false,
) => {
open ConnectorUtils
let mixpanelEvent = MixpanelHook.useSendEvent()
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let {setShowSideBar} = React.useContext(GlobalProvider.defaultContext)
let unConfiguredConnectors =
connectorsAvailableForIntegration->Array.filter(total =>
configuredConnectors->Array.find(item => item === total)->Option.isNone
)
let (showModal, setShowModal) = React.useState(_ => false)
let (searchedConnector, setSearchedConnector) = React.useState(_ => "")
let searchRef = React.useRef(Nullable.null)
let leftIcon =
<div id="leftIcon" className="self-center py-3 pl-5 pr-4">
<Icon size=18 name="search" />
</div>
let handleClick = connectorName => {
mixpanelEvent(~eventName=`connect_processor_${connectorName}`)
setShowSideBar(_ => false)
RescriptReactRouter.push(
GlobalVars.appendDashboardPath(~url=`v2/recovery/connectors/new?name=${connectorName}`),
)
}
let unConfiguredConnectorsCount = unConfiguredConnectors->Array.length
let handleSearch = event => {
let val = ref(ReactEvent.Form.currentTarget(event)["value"])
setSearchedConnector(_ => val.contents)
}
let descriptedConnectors = (
connectorList: array<ConnectorTypes.connectorTypes>,
~heading: string,
~showRequestConnectorBtn,
~showSearch=true,
~showDummyConnectorButton=false,
(),
) => {
if connectorList->Array.length > 0 {
connectorList->Array.sort(sortByName)
}
<>
<AddDataAttributes
attributes=[("data-testid", heading->LogicUtils.titleToSnake->String.toLowerCase)]>
<h2
className="font-semibold text-xl text-nd_gray-600 dark:text-white dark:text-opacity-75">
{heading->React.string}
</h2>
</AddDataAttributes>
<div className="flex w-full justify-between gap-4 mt-4 mb-4">
<RenderIf condition={showSearch}>
<AddDataAttributes attributes=[("data-testid", "search-processor")]>
<div
className="flex flex-row border border-gray-300 rounded-2xl focus:outline-none w-1/3 font-500 ">
{leftIcon}
<input
ref={searchRef->ReactDOM.Ref.domRef}
type_="text"
value=searchedConnector
onChange=handleSearch
placeholder="Search a processor"
className={`outline-none`}
id="search-processor"
/>
</div>
</AddDataAttributes>
</RenderIf>
<RenderIf
condition={!featureFlagDetails.isLiveMode &&
configuredConnectors->Array.length > 0 &&
showDummyConnectorButton}>
<ACLButton
authorization={userHasAccess(~groupAccess=ConnectorsManage)}
leftIcon={CustomIcon(
<Icon
name="plus"
size=16
className="text-jp-gray-900 fill-opacity-50 dark:jp-gray-text_darktheme"
/>,
)}
text="Connect a Dummy Processor"
buttonType={Secondary}
buttonSize={Large}
textStyle="text-jp-gray-900"
onClick={_ => setProcessorModal(_ => true)}
/>
</RenderIf>
<CantFindProcessor showRequestConnectorBtn setShowModal />
</div>
<RenderIf condition={connectorList->Array.length > 0}>
<div
className={`grid gap-x-5 gap-y-6
2xl:grid-cols-3 lg:grid-cols-3 md:grid-cols-2 grid-cols-3 mb-5`}>
{connectorList
->Array.mapWithIndex((connector: ConnectorTypes.connectorTypes, i) => {
let connectorName = connector->getConnectorNameString
let connectorInfo = connector->getConnectorInfo
let size = "w-14 h-14 rounded-sm"
<ACLDiv
authorization={userHasAccess(~groupAccess=ConnectorsManage)}
onClick={_ => handleClick(connectorName)}
key={i->Int.toString}
className="border p-6 gap-4 bg-white rounded-lg flex flex-col justify-between h-12.5-rem hover:bg-gray-50 hover:cursor-pointer"
dataAttrStr=connectorName>
<div className="flex flex-row gap-3 items-center">
<GatewayIcon gateway={connectorName->String.toUpperCase} className=size />
<p className={`${p1MediumTextStyle} break-all`}>
{connectorName->getDisplayNameForConnector(~connectorType)->React.string}
</p>
</div>
<p className="overflow-hidden text-nd_gray-400 flex-1 line-clamp-3">
{connectorInfo.description->React.string}
</p>
</ACLDiv>
})
->React.array}
</div>
</RenderIf>
<RequestConnector connectorList setShowModal />
</>
}
let connectorListFiltered = {
if searchedConnector->LogicUtils.isNonEmptyString {
connectorsAvailableForIntegration->Array.filter(item =>
item->getConnectorNameString->String.includes(searchedConnector->String.toLowerCase)
)
} else {
connectorsAvailableForIntegration
}
}
<div className="mt-10">
<RenderIf condition={unConfiguredConnectorsCount > 0}>
<RenderIf condition={showAllConnectors}>
<div className="flex flex-col gap-4">
{connectorListFiltered->descriptedConnectors(
~heading="Connect a new processor",
~showRequestConnectorBtn=true,
~showDummyConnectorButton=false,
(),
)}
</div>
<RenderIf condition={showModal}>
<HSwitchFeedBackModal
modalHeading="Request a processor"
setShowModal
showModal
modalType={RequestConnectorModal}
/>
</RenderIf>
</RenderIf>
<RenderIf condition={showTestProcessor}>
{showTestProcessor
->dummyConnectorList
->descriptedConnectors(
~heading="",
~showRequestConnectorBtn=false,
~showSearch=false,
~showDummyConnectorButton=false,
(),
)}
</RenderIf>
</RenderIf>
</div>
}
| 1,807 | 9,329 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RecoveryProcessors/RecoveryProcessorsPaymentProcessors/RecoveryOnboardingPayments.res | .res | @react.component
let make = (
~currentStep,
~setConnectorID,
~connector,
~setConnectorName,
~setNextStep,
~profileId,
~merchantId,
~activeBusinessProfile,
) => {
open APIUtils
open LogicUtils
open ConnectorUtils
open PageLoaderWrapper
open RevenueRecoveryOnboardingUtils
open ConnectProcessorsHelper
let getURL = useGetURL()
let showToast = ToastState.useShowToast()
let fetchConnectorListResponse = ConnectorListHook.useFetchConnectorList(
~entityName=V2(V2_CONNECTOR),
~version=UserInfoTypes.V2,
)
let updateAPIHook = useUpdateMethod(~showErrorToast=false)
let (screenState, setScreenState) = React.useState(_ => Success)
let (arrow, setArrow) = React.useState(_ => false)
let toggleChevronState = () => {
setArrow(prev => !prev)
}
let (initialValues, setInitialValues) = React.useState(_ => Dict.make()->JSON.Encode.object)
let connectorInfoDict = ConnectorInterface.mapDictToConnectorPayload(
ConnectorInterface.connectorInterfaceV2,
initialValues->LogicUtils.getDictFromJsonObject,
)
let connectorTypeFromName = connector->getConnectorNameTypeFromString
let selectedConnector = React.useMemo(() => {
connectorTypeFromName->getConnectorInfo
}, [connector])
let connectorDetails = React.useMemo(() => {
try {
if connector->isNonEmptyString {
let dict = Window.getConnectorConfig(connector)
dict
} else {
Dict.make()->JSON.Encode.object
}
} catch {
| Exn.Error(e) => {
Js.log2("FAILED TO LOAD CONNECTOR CONFIG", e)
Dict.make()->JSON.Encode.object
}
}
}, [selectedConnector])
let updatedInitialVal = React.useMemo(() => {
let initialValuesToDict = initialValues->getDictFromJsonObject
// TODO: Refactor for generic case
initialValuesToDict->Dict.set("connector_name", `${connector}`->JSON.Encode.string)
initialValuesToDict->Dict.set(
"connector_label",
`${connector}_${activeBusinessProfile}`->JSON.Encode.string,
)
initialValuesToDict->Dict.set("connector_type", "payment_processor"->JSON.Encode.string)
initialValuesToDict->Dict.set("profile_id", profileId->JSON.Encode.string)
initialValuesToDict->Dict.set(
"connector_webhook_details",
RevenueRecoveryData.payment_connector_webhook_details,
)
initialValuesToDict->Dict.set(
"connector_account_details",
RevenueRecoveryData.connector_account_details,
)
let keys =
connectorDetails
->getDictFromJsonObject
->Dict.keysToArray
->Array.filter(val => Array.includes(["credit", "debit"], val))
let pmtype = keys->Array.flatMap(key => {
let paymentMethodType = connectorDetails->getDictFromJsonObject->getArrayFromDict(key, [])
let updatedData = paymentMethodType->Array.map(
val => {
let wasmDict = val->getDictFromJsonObject
let exisitngData =
wasmDict->ConnectorPaymentMethodV2Utils.getPaymentMethodDictV2(key, connector)
exisitngData
},
)
updatedData
})
let pmSubTypeDict =
[
("payment_method_type", "card"->JSON.Encode.string),
("payment_method_subtypes", pmtype->Identity.genericTypeToJson),
]->Dict.fromArray
let pmArr = Array.make(~length=1, pmSubTypeDict)
initialValuesToDict->Dict.set("payment_methods_enabled", pmArr->Identity.genericTypeToJson)
initialValuesToDict->JSON.Encode.object
}, [connector, profileId])
let onSubmit = async (values, _form: ReactFinalForm.formApi) => {
try {
setScreenState(_ => Loading)
let connectorUrl = getURL(~entityName=V2(V2_CONNECTOR), ~methodType=Put, ~id=None)
let response = await updateAPIHook(connectorUrl, values, Post, ~version=V2)
setInitialValues(_ => response)
let connectorInfoDict = ConnectorInterface.mapDictToConnectorPayload(
ConnectorInterface.connectorInterfaceV2,
response->getDictFromJsonObject,
)
setConnectorID(_ => connectorInfoDict.id)
fetchConnectorListResponse()->ignore
setScreenState(_ => Success)
onNextClick(currentStep, setNextStep)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong")
let errorCode = err->safeParse->getDictFromJsonObject->getString("code", "")
let errorMessage = err->safeParse->getDictFromJsonObject->getString("message", "")
if errorCode === "HE_01" {
showToast(~message="Connector label already exist!", ~toastType=ToastError)
setNextStep(_ => RevenueRecoveryOnboardingUtils.defaultStep)
setScreenState(_ => Success)
} else {
showToast(~message=errorMessage, ~toastType=ToastError)
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
}
Nullable.null
}
let (
_,
connectorAccountFields,
connectorMetaDataFields,
_,
connectorWebHookDetails,
connectorLabelDetailField,
_,
) = getConnectorFields(connectorDetails)
let validateMandatoryField = values => {
let errors = Dict.make()
let valuesFlattenJson = values->JsonFlattenUtils.flattenObject(true)
let profileId = valuesFlattenJson->getString("profile_id", "")
if profileId->String.length === 0 {
Dict.set(errors, "Profile Id", `Please select your business profile`->JSON.Encode.string)
}
validateConnectorRequiredFields(
connectorTypeFromName,
valuesFlattenJson,
connectorAccountFields,
connectorMetaDataFields,
connectorWebHookDetails,
connectorLabelDetailField,
errors->JSON.Encode.object,
)
}
let input: ReactFinalForm.fieldRenderPropsInput = {
name: "name",
onBlur: _ => (),
onChange: ev => {
let value = ev->Identity.formReactEventToString
setConnectorName(_ => value)
RescriptReactRouter.replace(
GlobalVars.appendDashboardPath(~url=`/v2/recovery/onboarding?name=${value}`),
)
},
onFocus: _ => (),
value: connector->JSON.Encode.string,
checked: true,
}
let options = RecoveryConnectorUtils.recoveryConnectorList->getOptions
let addItemBtnStyle = "border border-t-0 !w-full"
let customScrollStyle = "max-h-72 overflow-scroll px-1 pt-1 border border-b-0"
let dropdownContainerStyle = "rounded-md border border-1 !w-full"
<div>
{switch currentStep->RevenueRecoveryOnboardingUtils.getSectionVariant {
| (#connectProcessor, #selectProcessor) =>
<PageWrapper
title="Where do you process your payments"
subTitle="Link the payment processor you use for handling subscription transactions.">
<div className="-m-1 mb-10 flex flex-col gap-7 w-540-px">
<PageLoaderWrapper screenState>
<Form onSubmit initialValues validate=validateMandatoryField>
<SelectBox.BaseDropdown
allowMultiSelect=false
buttonText="Choose a processor"
input
deselectDisable=true
customButtonStyle="!rounded-xl h-[45px] pr-2"
options
baseComponent={<ListBaseComp
placeHolder="Choose a processor" heading="Profile" subHeading=connector arrow
/>}
bottomComponent={<AddNewOMPButton
filterConnector=None
prodConnectorList=RecoveryConnectorUtils.recoveryConnectorListProd
user=#Profile
addItemBtnStyle
/>}
hideMultiSelectButtons=true
addButton=false
searchable=true
customStyle="!w-full"
customScrollStyle
dropdownContainerStyle
toggleChevronState
customDropdownOuterClass="!border-none"
fullLength=true
shouldDisplaySelectedOnTop=true
searchInputPlaceHolder="Search Processor"
/>
<RenderIf condition={connector->isNonEmptyString}>
<div className="flex flex-col mb-5 mt-7 gap-3 w-full ">
<ConnectorAuthKeys
initialValues={updatedInitialVal} showVertically=true updateAccountDetails=false
/>
<ConnectorLabelV2 isInEditState=true connectorInfo={connectorInfoDict} />
<ConnectorMetadataV2 isInEditState=true connectorInfo={connectorInfoDict} />
<ConnectorWebhookDetails isInEditState=true connectorInfo={connectorInfoDict} />
<FormRenderer.SubmitButton
text="Next"
buttonSize={Small}
customSumbitButtonStyle="!w-full mt-8"
tooltipForWidthClass="w-full"
/>
</div>
</RenderIf>
<FormValuesSpy />
</Form>
</PageLoaderWrapper>
</div>
</PageWrapper>
| (#connectProcessor, #activePaymentMethods) =>
<PageWrapper title="Payment Methods" subTitle="Configure your PaymentMethods.">
<div className="mb-10 flex flex-col gap-7 w-540-px">
<PageLoaderWrapper screenState>
<Form onSubmit initialValues validate=validateMandatoryField>
<div className="flex flex-col mb-5 gap-3 ">
<ConnectorPaymentMethodV2 initialValues isInEditState=true />
<FormRenderer.SubmitButton
text="Next"
buttonSize={Small}
customSumbitButtonStyle="!w-full mt-8"
tooltipForWidthClass="w-full"
/>
</div>
<FormValuesSpy />
</Form>
</PageLoaderWrapper>
</div>
</PageWrapper>
| (#connectProcessor, #setupWebhookProcessor) =>
<PageWrapper
title="Setup Payments Webhook"
subTitle="Configure this endpoint in the payment processors dashboard under webhook settings for us to receive events from the processor.">
<div className="-m-1 mb-10 flex flex-col gap-7 w-540-px">
<ConnectorWebhookPreview
merchantId
connectorName=connectorInfoDict.id
textCss="border border-nd_gray-400 font-medium rounded-xl px-4 py-2 mb-6 mt-6 text-nd_gray-400 w-full !font-jetbrain-mono"
containerClass="flex flex-row items-center justify-between"
displayTextLength=38
hideLabel=true
showFullCopy=true
/>
<Button
text="Next"
buttonType=Primary
onClick={_ => onNextClick(currentStep, setNextStep)->ignore}
customButtonStyle="w-full mt-8"
/>
</div>
</PageWrapper>
| (_, _) => React.null
}}
</div>
}
| 2,400 | 9,330 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RecoveryProcessors/RecoveryProcessorsPaymentProcessors/RecoveryConnectorTypes.res | .res | type sectionType = [
| #AuthenticateProcessor
| #SetupPmts
| #SetupWebhook
| #ReviewAndConnect
]
| 33 | 9,331 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RecoveryProcessors/RecoveryProcessorsPaymentProcessors/RecoveryProceesorReview.res | .res | @react.component
let make = (~connectorInfo) => {
open CommonAuthHooks
open LogicUtils
let {setShowSideBar} = React.useContext(GlobalProvider.defaultContext)
let connectorInfo = connectorInfo->LogicUtils.getDictFromJsonObject
let connectorInfodict = ConnectorInterface.mapDictToConnectorPayload(
ConnectorInterface.connectorInterfaceV2,
connectorInfo,
)
let (processorType, _) =
connectorInfodict.connector_type
->ConnectorUtils.connectorTypeTypedValueToStringMapper
->ConnectorUtils.connectorTypeTuple
let {connector_name: connectorName} = connectorInfodict
let {merchantId} = useCommonAuthInfo()->Option.getOr(defaultAuthInfo)
let connectorAccountFields = React.useMemo(() => {
try {
if connectorName->LogicUtils.isNonEmptyString {
let dict = switch processorType {
| PaymentProcessor => Window.getConnectorConfig(connectorName)
| PayoutProcessor => Window.getPayoutConnectorConfig(connectorName)
| AuthenticationProcessor => Window.getAuthenticationConnectorConfig(connectorName)
| PMAuthProcessor => Window.getPMAuthenticationProcessorConfig(connectorName)
| TaxProcessor => Window.getTaxProcessorConfig(connectorName)
| BillingProcessor => BillingProcessorsUtils.getConnectorConfig(connectorName)
| PaymentVas => JSON.Encode.null
}
let connectorAccountDict = dict->getDictFromJsonObject->getDictfromDict("connector_auth")
let bodyType = connectorAccountDict->Dict.keysToArray->getValueFromArray(0, "")
let connectorAccountFields = connectorAccountDict->getDictfromDict(bodyType)
connectorAccountFields
} else {
Dict.make()
}
} catch {
| Exn.Error(e) => {
Js.log2("FAILED TO LOAD CONNECTOR CONFIG", e)
let _ = Exn.message(e)->Option.getOr("Something went wrong")
Dict.make()
}
}
}, [connectorInfodict.id])
<div className="flex flex-col px-10 gap-8">
<div className="flex flex-col ">
<PageUtils.PageHeading
title="Review and Connect"
subTitle="Review your configured processor details, enabled payment methods and associated settings."
customSubTitleStyle="font-500 font-normal text-nd_gray-400"
/>
<div className=" flex flex-col py-4 gap-6">
<div className="flex flex-col gap-0.5-rem ">
<h4 className="text-nd_gray-400 "> {"Profile"->React.string} </h4>
{connectorInfodict.profile_id->React.string}
</div>
<div className="flex flex-col ">
<ConnectorHelperV2.PreviewCreds connectorInfo=connectorInfodict connectorAccountFields />
</div>
<ConnectorWebhookPreview merchantId connectorName=connectorInfodict.id />
</div>
</div>
<ACLButton
text="Done"
onClick={_ => {
setShowSideBar(_ => true)
}}
buttonSize=Large
buttonType=Primary
customButtonStyle="w-full"
/>
</div>
}
| 688 | 9,332 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RecoveryProcessors/RecoveryProcessorsPaymentProcessors/RecoveryConnectorEntity.res | .res | open ConnectorTypes
let getPreviouslyConnectedList: JSON.t => array<connectorPayloadV2> = json => {
let data = ConnectorInterface.mapJsonArrayToConnectorPayloads(
ConnectorInterface.connectorInterfaceV2,
json,
PaymentProcessor,
)
data
}
type colType =
| Name
| Status
| Disabled
| Actions
| ProfileId
| ProfileName
| ConnectorLabel
| PaymentMethods
| MerchantConnectorId
let defaultColumns = [
Name,
MerchantConnectorId,
ProfileId,
ProfileName,
ConnectorLabel,
Status,
Disabled,
Actions,
PaymentMethods,
]
let getHeading = colType => {
switch colType {
| Name => Table.makeHeaderInfo(~key="connector_name", ~title="Processor")
| Status => Table.makeHeaderInfo(~key="status", ~title="Integration status")
| Disabled => Table.makeHeaderInfo(~key="disabled", ~title="Disabled")
| Actions => Table.makeHeaderInfo(~key="actions", ~title="")
| ProfileId => Table.makeHeaderInfo(~key="profile_id", ~title="Profile Id")
| MerchantConnectorId =>
Table.makeHeaderInfo(~key="merchant_connector_id", ~title="Merchant Connector Id")
| ProfileName => Table.makeHeaderInfo(~key="profile_name", ~title="Profile Name")
| ConnectorLabel => Table.makeHeaderInfo(~key="connector_label", ~title="Connector Label")
| PaymentMethods => Table.makeHeaderInfo(~key="payment_methods", ~title="Payment Methods")
}
}
let connectorStatusStyle = connectorStatus =>
switch connectorStatus->String.toLowerCase {
| "active" => "text-green-700"
| _ => "text-grey-800 opacity-50"
}
let getConnectorObjectFromListViaId = (
connectorList: array<ConnectorTypes.connectorPayloadV2>,
mca_id: string,
) => {
let default = ConnectorInterface.mapDictToConnectorPayload(
ConnectorInterface.connectorInterfaceV2,
Dict.make(),
)
connectorList
->Array.find(ele => {ele.id == mca_id})
->Option.getOr(default)
}
let getAllPaymentMethods = (paymentMethodsArray: array<paymentMethodEnabledTypeV2>) => {
let paymentMethods = paymentMethodsArray->Array.reduce([], (acc, item) => {
acc->Array.concat([item.payment_method_type->LogicUtils.capitalizeString])
})
paymentMethods
}
let getTableCell = (~connectorType: ConnectorTypes.connector=Processor) => {
let getCell = (connector: connectorPayloadV2, colType): Table.cell => {
switch colType {
| Name =>
CustomCell(
<HelperComponents.ConnectorCustomCell
connectorName=connector.connector_name connectorType
/>,
"",
)
| Disabled =>
Label({
title: connector.disabled ? "DISABLED" : "ENABLED",
color: connector.disabled ? LabelGray : LabelGreen,
})
| Status =>
Table.CustomCell(
<div className={`font-semibold ${connector.status->connectorStatusStyle}`}>
{connector.status->String.toUpperCase->React.string}
</div>,
"",
)
| ProfileId => DisplayCopyCell(connector.profile_id)
| ProfileName =>
Table.CustomCell(
<HelperComponents.BusinessProfileComponent profile_id={connector.profile_id} />,
"",
)
| ConnectorLabel => Text(connector.connector_label)
| Actions => Table.CustomCell(<div />, "")
| PaymentMethods =>
Table.CustomCell(
<div>
{connector.payment_methods_enabled
->getAllPaymentMethods
->Array.joinWith(", ")
->React.string}
</div>,
"",
)
| MerchantConnectorId => DisplayCopyCell(connector.id)
}
}
getCell
}
let connectorEntity = (path: string, ~authorization: CommonAuthTypes.authorization) => {
EntityType.makeEntity(
~uri=``,
~getObjects=getPreviouslyConnectedList,
~defaultColumns,
~getHeading,
~getCell=getTableCell(~connectorType=Processor),
~dataKey="",
~getShowLink={
connec =>
GroupAccessUtils.linkForGetShowLinkViaAccess(
~url=GlobalVars.appendDashboardPath(
~url=`/${path}/${connec.id}?name=${connec.connector_name}`,
),
~authorization,
)
},
)
}
| 951 | 9,333 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RecoveryProcessors/RecoveryProcessorsPaymentProcessors/RecoveryConnectorHome.res | .res | @react.component
let make = () => {
open APIUtils
open LogicUtils
open VerticalStepIndicatorTypes
open VerticalStepIndicatorUtils
open ConnectorUtils
open PageLoaderWrapper
open RecoveryConnectorTypes
open RecoveryConnectorUtils
let getURL = useGetURL()
let (_, getNameForId) = OMPSwitchHooks.useOMPData()
let updateAPIHook = useUpdateMethod(~showErrorToast=false)
let (initialValues, setInitialValues) = React.useState(_ => Dict.make()->JSON.Encode.object)
let {setShowSideBar} = React.useContext(GlobalProvider.defaultContext)
let {getUserInfoData} = React.useContext(UserInfoProvider.defaultContext)
let (screenState, setScreenState) = React.useState(_ => Success)
let {profileId, merchantId} = getUserInfoData()
let showToast = ToastState.useShowToast()
let connectorInfo = initialValues->LogicUtils.getDictFromJsonObject
let connectorInfoDict = ConnectorInterface.mapDictToConnectorPayload(
ConnectorInterface.connectorInterfaceV2,
connectorInfo,
)
let (currentStep, setNextStep) = React.useState(() => {
sectionId: (#AuthenticateProcessor: sectionType :> string),
subSectionId: None,
})
let fetchConnectorListResponse = ConnectorListHook.useFetchConnectorList()
let connector = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("name", "")
let connectorTypeFromName = connector->getConnectorNameTypeFromString
let selectedConnector = React.useMemo(() => {
connectorTypeFromName->getConnectorInfo
}, [connector])
let connectorName = connector->getDisplayNameForConnector
let getNextStep = (currentStep: step): option<step> => {
findNextStep(sections, currentStep)
}
let activeBusinessProfile = getNameForId(#Profile)
let updatedInitialVal = React.useMemo(() => {
let initialValuesToDict = initialValues->getDictFromJsonObject
// TODO: Refactor for generic case
initialValuesToDict->Dict.set("connector_name", `${connector}`->JSON.Encode.string)
initialValuesToDict->Dict.set(
"connector_label",
`${connector}_${activeBusinessProfile}`->JSON.Encode.string,
)
initialValuesToDict->Dict.set("connector_type", "payment_processor"->JSON.Encode.string)
initialValuesToDict->Dict.set("profile_id", profileId->JSON.Encode.string)
initialValuesToDict->JSON.Encode.object
}, [connector, profileId])
let onNextClick = () => {
switch getNextStep(currentStep) {
| Some(nextStep) => setNextStep(_ => nextStep)
| None => ()
}
}
let handleAuthKeySubmit = async (_, _) => {
onNextClick()
Nullable.null
}
let onSubmit = async (values, _form: ReactFinalForm.formApi) => {
try {
setScreenState(_ => Loading)
let connectorUrl = getURL(~entityName=V2(V2_CONNECTOR), ~methodType=Put, ~id=None)
let response = await updateAPIHook(connectorUrl, values, Post, ~version=V2)
setInitialValues(_ => response)
fetchConnectorListResponse()->ignore
setScreenState(_ => Success)
onNextClick()
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong")
let errorCode = err->safeParse->getDictFromJsonObject->getString("code", "")
let errorMessage = err->safeParse->getDictFromJsonObject->getString("message", "")
if errorCode === "HE_01" {
showToast(~message="Connector label already exist!", ~toastType=ToastError)
setNextStep(_ => {
sectionId: (#AuthenticateProcessor: sectionType :> string),
subSectionId: None,
})
setScreenState(_ => Success)
} else {
showToast(~message=errorMessage, ~toastType=ToastError)
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
}
Nullable.null
}
let backClick = () => {
RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url="/v2/recovery/connectors"))
setShowSideBar(_ => true)
}
let connectorDetails = React.useMemo(() => {
try {
if connector->isNonEmptyString {
let dict = Window.getConnectorConfig(connector)
dict
} else {
Dict.make()->JSON.Encode.object
}
} catch {
| Exn.Error(e) => {
Js.log2("FAILED TO LOAD CONNECTOR CONFIG", e)
Dict.make()->JSON.Encode.object
}
}
}, [selectedConnector])
let (
_,
connectorAccountFields,
connectorMetaDataFields,
_,
connectorWebHookDetails,
connectorLabelDetailField,
_,
) = getConnectorFields(connectorDetails)
let validateMandatoryField = values => {
let errors = Dict.make()
let valuesFlattenJson = values->JsonFlattenUtils.flattenObject(true)
let profileId = valuesFlattenJson->getString("profile_id", "")
if profileId->String.length === 0 {
Dict.set(errors, "Profile Id", `Please select your business profile`->JSON.Encode.string)
}
validateConnectorRequiredFields(
connectorTypeFromName,
valuesFlattenJson,
connectorAccountFields,
connectorMetaDataFields,
connectorWebHookDetails,
connectorLabelDetailField,
errors->JSON.Encode.object,
)
}
let recoveryTitleElement =
<>
<GatewayIcon gateway={`${connector}`->String.toUpperCase} />
<h1 className="text-medium font-semibold text-gray-600">
{`Setup ${connectorName}`->React.string}
</h1>
</>
<div className="flex flex-row gap-x-6">
<VerticalStepIndicator titleElement=recoveryTitleElement sections currentStep backClick />
{switch currentStep->getSectionVariant {
| #AuthenticateProcessor =>
<div className="flex flex-col w-1/2 px-10 ">
<PageUtils.PageHeading
title="Authenticate Processor"
subTitle="Configure your credentials from your processor dashboard. Hyperswitch encrypts and stores these credentials securely."
customSubTitleStyle="font-500 font-normal text-nd_gray-700"
/>
<PageLoaderWrapper screenState>
<Form onSubmit={handleAuthKeySubmit} initialValues validate=validateMandatoryField>
<div className="flex flex-col mb-5 gap-3 ">
<ConnectorAuthKeys initialValues={updatedInitialVal} showVertically=true />
<ConnectorLabelV2 isInEditState=true connectorInfo={connectorInfoDict} />
<ConnectorMetadataV2 isInEditState=true connectorInfo={connectorInfoDict} />
<ConnectorWebhookDetails isInEditState=true connectorInfo={connectorInfoDict} />
<FormRenderer.SubmitButton
text="Next"
buttonSize={Small}
customSumbitButtonStyle="!w-full mt-8"
tooltipForWidthClass="w-full"
/>
</div>
<FormValuesSpy />
</Form>
</PageLoaderWrapper>
</div>
| #SetupPmts =>
<div className="flex flex-col w-1/2 px-10 ">
<PageUtils.PageHeading
title="Payment Methods"
subTitle="Configure your PaymentMethods."
customSubTitleStyle="font-500 font-normal text-nd_gray-700"
/>
<PageLoaderWrapper screenState>
<Form onSubmit initialValues validate=validateMandatoryField>
<div className="flex flex-col mb-5 gap-3 ">
<ConnectorPaymentMethodV2 initialValues isInEditState=true />
<FormRenderer.SubmitButton
text="Next"
buttonSize={Small}
customSumbitButtonStyle="!w-full mt-8"
tooltipForWidthClass="w-full"
/>
</div>
<FormValuesSpy />
</Form>
</PageLoaderWrapper>
</div>
| #SetupWebhook =>
<div className="flex flex-col w-1/2 px-10">
<PageUtils.PageHeading
title="Setup Webhook"
subTitle="Configure this endpoint in the processors dashboard under webhook settings for us to receive events from the processor"
customSubTitleStyle="font-medium text-nd_gray-700"
/>
<ConnectorWebhookPreview
merchantId
connectorName=connectorInfoDict.id
textCss="border border-nd_gray-300 font-[700] rounded-xl px-4 py-2 mb-6 mt-6 text-nd_gray-400"
containerClass="flex flex-row items-center justify-between"
hideLabel=true
showFullCopy=true
/>
<Button
text="Next"
buttonType=Primary
onClick={_ => onNextClick()->ignore}
customButtonStyle="w-full mt-8"
/>
</div>
| #ReviewAndConnect => <RecoveryProceesorReview connectorInfo=initialValues />
}}
</div>
}
| 1,980 | 9,334 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RecoveryProcessors/RecoveryProcessorsPaymentProcessors/RecoveryConnectorUtils.res | .res | let getSectionName = section => {
switch section {
| #AuthenticateProcessor => "Authenticate your processor"
| #SetupPmts => "Setup Payment Methods"
| #SetupWebhook => "Setup Webhook"
| #ReviewAndConnect => "Review and Connect"
}
}
let getSectionIcon = section => {
switch section {
| #AuthenticateProcessor => "nd-shield"
| #SetupPmts => "nd-webhook"
| #SetupWebhook => "nd-webhook"
| #ReviewAndConnect => "nd-flag"
}
}
open VerticalStepIndicatorTypes
open RecoveryConnectorTypes
let sections = [
{
id: (#AuthenticateProcessor: sectionType :> string),
name: #AuthenticateProcessor->getSectionName,
icon: #AuthenticateProcessor->getSectionIcon,
subSections: None,
},
{
id: (#SetupPmts: sectionType :> string),
name: #SetupPmts->getSectionName,
icon: #SetupPmts->getSectionIcon,
subSections: None,
},
{
id: (#SetupWebhook: sectionType :> string),
name: #SetupWebhook->getSectionName,
icon: #SetupWebhook->getSectionIcon,
subSections: None,
},
{
id: (#ReviewAndConnect: sectionType :> string),
name: #ReviewAndConnect->getSectionName,
icon: #ReviewAndConnect->getSectionIcon,
subSections: None,
},
]
let getSectionVariant = ({sectionId}) => {
switch sectionId {
| "AuthenticateProcessor" => #AuthenticateProcessor
| "SetupPmts" => #SetupPmts
| "SetupWebhook" => #SetupWebhook
| "ReviewAndConnect" | _ => #ReviewAndConnect
}
}
let getOptions: array<ConnectorTypes.connectorTypes> => array<
SelectBox.dropdownOption,
> = dropdownList => {
open ConnectorUtils
open ConnectorTypes
let options: array<SelectBox.dropdownOption> = dropdownList->Array.map((
connector
): SelectBox.dropdownOption => {
let connectorValue = connector->getConnectorNameString
let connectorName = switch connector {
| Processors(connector) => connector->getDisplayNameForProcessor
| _ => ""
}
{
label: connectorName,
value: connectorValue,
}
})
options
}
open ConnectorTypes
let recoveryConnectorList: array<connectorTypes> = [Processors(STRIPE)]
let recoveryConnectorListProd: array<connectorTypes> = [
Processors(ADYEN),
Processors(CYBERSOURCE),
Processors(GLOBEPAY),
Processors(WORLDPAY),
Processors(NOON),
Processors(BANKOFAMERICA),
]
| 611 | 9,335 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RecoveryProcessors/RecoveryProcessorsPaymentProcessors/RecoveryConnectorList.res | .res | @react.component
let make = () => {
open ConnectorUtils
let (configuredConnectors, setConfiguredConnectors) = React.useState(_ => [])
let (previouslyConnectedData, setPreviouslyConnectedData) = React.useState(_ => [])
let (filteredConnectorData, setFilteredConnectorData) = React.useState(_ => [])
let connectorListFromRecoil = ConnectorInterface.useConnectorArrayMapper(
~interface=ConnectorInterface.connectorInterfaceV2,
~retainInList=PaymentProcessor,
)
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
let (searchText, setSearchText) = React.useState(_ => "")
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (offset, setOffset) = React.useState(_ => 0)
let getConnectorListAndUpdateState = async () => {
try {
setScreenState(_ => PageLoaderWrapper.Loading)
connectorListFromRecoil->Array.reverse
let list = ConnectorInterface.mapConnectorPayloadToConnectorType(
ConnectorInterface.connectorInterfaceV2,
ConnectorTypes.Processor,
connectorListFromRecoil,
)
setConfiguredConnectors(_ => list)
setFilteredConnectorData(_ => connectorListFromRecoil->Array.map(Nullable.make))
setPreviouslyConnectedData(_ => connectorListFromRecoil->Array.map(Nullable.make))
setScreenState(_ => Success)
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Error("Failed to fetch"))
}
}
React.useEffect(() => {
getConnectorListAndUpdateState()->ignore
None
}, [connectorList])
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let connectorsAvailableForIntegration = featureFlagDetails.isLiveMode
? connectorListForLive
: connectorList
let filterLogic = ReactDebounce.useDebounced(ob => {
open LogicUtils
let (searchText, arr) = ob
let filteredList = if searchText->isNonEmptyString {
arr->Array.filter((obj: Nullable.t<ConnectorTypes.connectorPayloadV2>) => {
switch Nullable.toOption(obj) {
| Some(obj) =>
isContainingStringLowercase(obj.connector_name, searchText) ||
isContainingStringLowercase(obj.id, searchText) ||
isContainingStringLowercase(obj.connector_label, searchText)
| None => false
}
})
} else {
arr
}
setFilteredConnectorData(_ => filteredList)
}, ~wait=200)
<PageLoaderWrapper screenState>
<div className="mt-12">
<RenderIf condition={configuredConnectors->Array.length > 0}>
<LoadedTable
title="Connected Processors"
actualData=filteredConnectorData
totalResults={filteredConnectorData->Array.length}
filters={<TableSearchFilter
data={previouslyConnectedData}
filterLogic
placeholder="Search Processor or Merchant Connector Id or Connector Label"
customSearchBarWrapperWidth="w-full lg:w-1/2"
customInputBoxWidth="w-full"
searchVal=searchText
setSearchVal=setSearchText
/>}
resultsPerPage=20
offset
setOffset
entity={RecoveryConnectorEntity.connectorEntity(
"v2/recovery/connectors",
~authorization=userHasAccess(~groupAccess=ConnectorsManage),
)}
currrentFetchCount={filteredConnectorData->Array.length}
collapseTableRow=false
/>
</RenderIf>
<RecoveryProcessorCards configuredConnectors connectorsAvailableForIntegration />
</div>
</PageLoaderWrapper>
}
| 791 | 9,336 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RevenueRecoveryOverview/RevenueRecoveryTypes.res | .res | type colType =
| InvoiceId
| PaymentId
| MerchantId
| Status
| Amount
| AmountCapturable
| AmountReceived
| ProfileId
| Connector
| ConnectorTransactionID
| Created
| Currency
| CustomerId
| Description
| SetupFutureUsage
| CaptureMethod
| PaymentMethod
| PaymentMethodType
| PaymentMethodData
| PaymentToken
| Shipping
| Email
| Name
| Phone
| ReturnUrl
| AuthenticationType
| StatementDescriptorName
| StatementDescriptorSuffix
| NextAction
| CancellationReason
| ErrorCode
| ErrorMessage
| Metadata
| MerchantOrderReferenceId
| AttemptCount
type refundMetaData = {
udf1: string,
new_customer: string,
login_date: string,
}
type refunds = {
refund_id: string,
payment_id: string,
amount: float,
currency: string,
reason: string,
status: string,
metadata: refundMetaData,
updated_at: string,
created_at: string,
error_message: string,
}
type attempts = {
id: string,
status: string,
amount: float,
currency: string,
connector: string,
error_message: string,
payment_method: string,
connector_reference_id: string,
capture_method: string,
authentication_type: string,
cancellation_reason: string,
mandate_id: string,
error_code: string,
payment_token: string,
connector_metadata: string,
payment_experience: string,
payment_method_type: string,
reference_id: string,
client_source: string,
client_version: string,
attempt_amount: float,
}
type frmMessage = {
frm_name: string,
frm_transaction_id: string,
frm_transaction_type: string,
frm_status: string,
frm_score: int,
frm_reason: string,
frm_error: string,
}
type order = {
invoice_id: string,
payment_id: string,
merchant_id: string,
net_amount: float,
order_amount: float,
status: string,
amount: float,
amount_capturable: float,
amount_received: float,
created: string,
last_updated: string,
currency: string,
customer_id: string,
description: string,
setup_future_usage: string,
capture_method: string,
payment_method: string,
payment_method_type: string,
payment_method_data: option<JSON.t>,
external_authentication_details: option<JSON.t>,
payment_token: string,
shipping: string,
shippingEmail: string,
shippingPhone: string,
metadata: Dict.t<JSON.t>,
email: string,
name: string,
phone: string,
return_url: string,
authentication_type: string,
statement_descriptor_name: string,
statement_descriptor_suffix: string,
next_action: string,
cancellation_reason: string,
error_code: string,
error_message: string,
connector: string,
order_quantity: string,
product_name: string,
card_brand: string,
payment_experience: string,
frm_message: frmMessage,
connector_transaction_id: string,
merchant_connector_id: string,
merchant_decision: string,
profile_id: string,
disputes: array<DisputeTypes.disputes>,
attempts: array<attempts>,
merchant_order_reference_id: string,
attempt_count: int,
connector_label: string,
attempt_amount: float,
}
type refundsColType =
| Amount
| Created
| Currency
| LastUpdated
| PaymentId
| RefundId
| RefundReason
| RefundStatus
| ErrorMessage
type frmColType =
| PaymentId
| PaymentMethodType
| Amount
| Currency
| PaymentProcessor
| FRMConnector
| FRMMessage
| MerchantDecision
type authenticationColType =
| AuthenticationFlow
| DsTransactionId
| ElectronicCommerceIndicator
| ErrorCode
| ErrorMessage
| Status
| Version
type attemptColType =
| AttemptId
| Status
| Amount
| Connector
| PaymentMethodType
| ErrorMessage
| ConnectorReferenceID
| CaptureMethod
| AuthenticationType
| CancellationReason
| MandateID
| ErrorCode
| PaymentToken
| ConnectorMetadata
| PaymentExperience
| ClientSource
| ClientVersion
type summaryColType =
| Created
| NetAmount
| OrderAmount
| LastUpdated
| PaymentId
| Currency
| AmountReceived
| OrderQuantity
| ProductName
| ErrorMessage
| ConnectorTransactionID
type aboutPaymentColType =
| Connector
| ProfileId
| ProfileName
| PaymentMethod
| PaymentMethodType
| CardBrand
| ConnectorLabel
| AuthenticationType
| CaptureMethod
| CardNetwork
| MandateId
| AmountCapturable
| AmountReceived
type otherDetailsColType =
| AmountCapturable
| ErrorCode
| ShippingAddress
| ShippingEmail
| ShippingPhone
| Email
| FirstName
| LastName
| Phone
| CustomerId
| Description
| MerchantId
| ReturnUrl
| CaptureMethod
| NextAction
| SetupFutureUsage
| CancellationReason
| StatementDescriptorName
| StatementDescriptorSuffix
| PaymentExperience
| FRMName
| FRMTransactionType
| FRMStatus
| MerchantOrderReferenceId
type optionObj = {
urlKey: string,
label: string,
}
type frmStatus = [#APPROVE | #REJECT]
type topic =
| String(string)
| ReactElement(React.element)
| 1,308 | 9,337 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RevenueRecoveryOverview/RecoveryOverviewHelper.res | .res | module DisplayKeyValueParams = {
@react.component
let make = (
~showTitle: bool=true,
~heading: Table.header,
~value: Table.cell,
~isInHeader=false,
~isHorizontal=false,
~customMoneyStyle="",
~labelMargin="",
~customDateStyle="",
~wordBreak=true,
~overiddingHeadingStyles="",
~textColor="!font-medium !text-nd_gray-600",
) => {
let marginClass = if labelMargin->LogicUtils.isEmptyString {
"mt-4 py-0"
} else {
labelMargin
}
let fontClass = if isInHeader {
"text-fs-20"
} else {
"text-fs-13"
}
let textColor =
textColor->LogicUtils.isEmptyString ? "text-jp-gray-900 dark:text-white" : textColor
let description = heading.description->Option.getOr("")
{
<AddDataAttributes attributes=[("data-label", heading.title)]>
<div
className={`flex ${isHorizontal ? "flex-row justify-between" : "flex-col gap-1"} py-4 `}>
<div
className={`flex flex-row text-fs-11 ${isHorizontal
? "flex justify-start"
: ""} text-jp-gray-900 text-opacity-50 dark:text-jp-gray-text_darktheme dark:text-opacity-50 `}>
<div className={overiddingHeadingStyles}>
{React.string(showTitle ? `${heading.title}:` : " x")}
</div>
<RenderIf condition={description->LogicUtils.isNonEmptyString}>
<div className="text-sm text-gray-500 mx-2 -mt-1 ">
<ToolTip description={description} toolTipPosition={ToolTip.Top} />
</div>
</RenderIf>
</div>
<div
className={`${isHorizontal
? "flex justify-end"
: ""} ${fontClass} font-semibold text-left ${textColor}`}>
<Table.TableCell
cell=value
textAlign=Table.Left
fontBold=true
customMoneyStyle
labelMargin=marginClass
customDateStyle
/>
</div>
</div>
</AddDataAttributes>
}
}
}
module Heading = {
@react.component
let make = (
~topic: RevenueRecoveryOrderTypes.topic,
~children=?,
~borderClass="border-b",
~headingCss="",
) => {
let widthClass = headingCss->LogicUtils.isEmptyString ? "" : "w-full"
<div
className={`${borderClass} border-jp-gray-940 border-opacity-75 dark:border-jp-gray-960 flex justify justify-between dark:bg-jp-gray-lightgray_background ${headingCss}`}>
<div className={`p-2 m-2 flex flex-row justify-start ${widthClass}`}>
{switch topic {
| String(string) =>
<AddDataAttributes attributes=[("data-heading", string)]>
<span className="text-gray-600 dark:text-gray-400 font-bold text-base text-fs-16">
{React.string({string})}
</span>
</AddDataAttributes>
| ReactElement(element) => element
}}
</div>
<div className="p-2 m-2 flex flex-row justify-end ">
<span>
{switch children {
| Some(element) => element
| None => React.null
}}
</span>
</div>
</div>
}
}
module Section = {
@react.component
let make = (
~children,
~customCssClass="border border-jp-gray-500 dark:border-jp-gray-960 bg-white dark:bg-jp-gray-950 rounded-md p-0 m-3",
) => {
<div className=customCssClass> children </div>
}
}
module Details = {
@react.component
let make = (
~heading,
~data,
~getHeading,
~getCell,
~excludeColKeys=[],
~detailsFields,
~justifyClassName="justify-start",
~widthClass="w-3/12",
~chargeBackField=None,
~bgColor="bg-white dark:bg-jp-gray-lightgray_background",
~children=?,
~headRightElement=React.null,
~borderRequired=true,
~isHeadingRequired=true,
~cardView=false,
~showDetails=true,
~headingCss="",
~showTitle=true,
~flexClass="flex flex-wrap",
) => {
let customBorderCss = `${borderRequired
? "border border-jp-gray-940 border-opacity-75 dark:border-jp-gray-960"
: ""}`
if !cardView {
<Section customCssClass={` ${customBorderCss} ${bgColor} rounded-md `}>
<RenderIf condition=isHeadingRequired>
<Heading topic=heading headingCss> {headRightElement} </Heading>
</RenderIf>
<RenderIf condition=showDetails>
<FormRenderer.DesktopRow>
<div
className={`${flexClass} ${justifyClassName} lg:flex-row flex-col dark:bg-jp-gray-lightgray_background dark:border-jp-gray-no_data_border`}>
{detailsFields
->Array.mapWithIndex((colType, i) => {
if !(excludeColKeys->Array.includes(colType)) {
<div className=widthClass key={Int.toString(i)}>
<DisplayKeyValueParams
heading={getHeading(colType)}
value={getCell(data, colType)}
customMoneyStyle="!text-fs-13"
labelMargin="!py-0 mt-2"
customDateStyle="!font-fira-code"
showTitle
/>
<div />
</div>
} else {
React.null
}
})
->React.array}
{switch chargeBackField {
| Some(field) =>
<div className="flex flex-col py-4">
<div
className="text-fs-11 leading-3 text-jp-gray-900 text-opacity-50 dark:text-jp-gray-text_darktheme dark:text-opacity-50">
{React.string("Chargeback Amount")}
</div>
<div
className="text-fs-13 font-semibold text-left dark:text-white text-jp-gray-900 break-all">
<Table.TableCell
cell=field
textAlign=Table.Left
fontBold=true
customDateStyle="!font-fira-code"
customMoneyStyle="!text-fs-13"
labelMargin="!py-0 mt-2 h-6"
/>
</div>
</div>
| None => React.null
}}
</div>
</FormRenderer.DesktopRow>
</RenderIf>
{switch children {
| Some(ele) => ele
| None => React.null
}}
</Section>
} else {
<div
className="flex flex-col w-full pt-4 gap-4 bg-white rounded-md dark:bg-jp-gray-lightgray_background">
{detailsFields
->Array.map(item => {
<div className="flex justify-between">
<div className="text-jp-gray-900 dark:text-white opacity-50 font-medium">
{getHeading(item).title->React.string}
</div>
<div className="font-semibold break-all">
<Table.TableCell cell={getCell(data, item)} />
</div>
</div>
})
->React.array}
</div>
}
}
}
| 1,683 | 9,338 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RevenueRecoveryOverview/ShowRevenueRecovery.res | .res | open RevenueRecoveryEntity
open LogicUtils
open RecoveryOverviewHelper
open RevenueRecoveryOrderTypes
module ShowOrderDetails = {
@react.component
let make = (
~data,
~getHeading,
~getCell,
~detailsFields,
~justifyClassName="justify-start",
~widthClass="w-1/3",
~bgColor="bg-white dark:bg-jp-gray-lightgray_background",
~isButtonEnabled=false,
~border="border border-jp-gray-940 border-opacity-75 dark:border-jp-gray-960",
~customFlex="flex-wrap",
~isHorizontal=false,
) => {
<FormRenderer.DesktopRow>
<div
className={`flex ${customFlex} ${justifyClassName} dark:bg-jp-gray-lightgray_background dark:border-jp-gray-no_data_border `}>
{detailsFields
->Array.mapWithIndex((colType, i) => {
<div className=widthClass key={i->Int.toString}>
<DisplayKeyValueParams
heading={getHeading(colType)}
value={getCell(data, colType)}
customMoneyStyle="!font-normal !text-sm"
labelMargin="!py-0 mt-2"
overiddingHeadingStyles="text-nd_gray-400 text-sm font-medium"
isHorizontal
/>
</div>
})
->React.array}
</div>
</FormRenderer.DesktopRow>
}
}
module OrderInfo = {
@react.component
let make = (~order) => {
<div className="flex flex-col mb-6 w-full">
<ShowOrderDetails
data=order
getHeading
getCell
detailsFields=[Id, Status, OrderAmount, Connector, Created, PaymentMethodType]
isButtonEnabled=true
/>
</div>
}
}
module Attempts = {
@react.component
let make = (~order) => {
let getStyle = status => {
let orderStatus = status->HSwitchOrderUtils.paymentAttemptStatusVariantMapper
switch orderStatus {
| #CHARGED => ("green-status", "nd-check")
| #FAILURE => ("red-status", "nd-alert-triangle-outline")
| _ => ("orange-status", "nd-calender")
}
}
<div className="border rounded-lg w-full h-fit p-5">
<div className="font-bold text-lg mb-5 px-4"> {"Attempts History"->React.string} </div>
<div className="p-5 flex flex-col gap-11 ">
{order.attempts
->Array.mapWithIndex((item, index) => {
let (border, icon) = item.status->getStyle
<div className="grid grid-cols-10 gap-5" key={index->Int.toString}>
<div className="flex flex-col gap-1">
<div className="w-full flex justify-end font-semibold">
{`#${(order.attempts->Array.length - index)->Int.toString}`->React.string}
</div>
<div className="w-full flex justify-end text-xs opacity-50">
{<Table.DateCell timestamp={item.created} isCard=true hideTime=true />}
</div>
</div>
<div className="relative ml-7">
<div
className={`absolute left-0 -ml-0.5 top-0 border-1.5 p-2 rounded-full h-fit w-fit border-${border} bg-white z-10`}>
<Icon name=icon className={`w-5 h-5 text-${border}`} />
</div>
<RenderIf condition={index != order.attempts->Array.length - 1}>
<div className="ml-4 mt-10 border-l-2 border-gray-200 h-full w-1 z-20" />
</RenderIf>
</div>
<div className="border col-span-8 rounded-lg px-2">
<ShowOrderDetails
data=item
getHeading=getAttemptHeading
getCell=getAttemptCell
detailsFields=[AttemptTriggeredBy, Status, Error]
/>
</div>
</div>
})
->React.array}
</div>
</div>
}
}
@react.component
let make = (~id) => {
open APIUtils
let getURL = useGetURL()
let fetchDetails = useGetMethod()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (revenueRecoveryData, setRevenueRecoveryData) = React.useState(_ =>
Dict.make()->RevenueRecoveryEntity.itemToObjMapper
)
let showToast = ToastState.useShowToast()
let {globalUIConfig: {primaryColor}} = React.useContext(ThemeProvider.themeContext)
let fetchOrderDetails = async _ => {
try {
setScreenState(_ => Loading)
let _ordersUrl = getURL(~entityName=V2(V2_ORDERS_LIST), ~methodType=Get, ~id=Some(id))
//let res = await fetchDetails(ordersUrl)
let res = RevenueRecoveryData.orderData
let data =
res
->getDictFromJsonObject
->getArrayFromDict("data", [])
let order =
data
->Array.map(item => {
item
->getDictFromJsonObject
->RevenueRecoveryEntity.itemToObjMapper
})
->Array.find(item => item.id == id)
switch order {
| Some(value) => setRevenueRecoveryData(_ => value)
| _ => ()
}
setScreenState(_ => Success)
} catch {
| Exn.Error(e) =>
switch Exn.message(e) {
| Some(message) =>
if message->String.includes("HE_02") {
setScreenState(_ => Custom)
} else {
showToast(~message="Failed to Fetch!", ~toastType=ToastState.ToastError)
setScreenState(_ => Error("Failed to Fetch!"))
}
| None => setScreenState(_ => Error("Failed to Fetch!"))
}
}
}
React.useEffect(() => {
fetchOrderDetails()->ignore
None
}, [])
<div className="flex flex-col gap-8">
<BreadCrumbNavigation
path=[{title: "Overview", link: "/v2/recovery/overview"}]
currentPageTitle=id
cursorStyle="cursor-pointer"
customTextClass="text-nd_gray-400"
titleTextClass="text-nd_gray-600 font-medium"
fontWeight="font-medium"
dividerVal=Slash
childGapClass="gap-2"
/>
<div className="flex flex-col gap-10">
<div className="flex flex-row justify-between items-center">
<div className="flex gap-2 items-center">
<PageUtils.PageHeading title="Invoice summary" />
</div>
</div>
<PageLoaderWrapper
screenState
customUI={<NoDataFound
message="Payment does not exists in out record" renderType=NotFound
/>}>
<div className="w-full">
<OrderInfo order=revenueRecoveryData />
</div>
</PageLoaderWrapper>
</div>
<div className="overflow-scroll">
<Attempts order={revenueRecoveryData} />
</div>
</div>
}
| 1,609 | 9,339 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RevenueRecoveryOverview/RevenueRecoveryEntity.res | .res | open LogicUtils
open RevenueRecoveryOrderTypes
module CurrencyCell = {
@react.component
let make = (~amount, ~currency) => {
<p className="whitespace-nowrap"> {`${amount} ${currency}`->React.string} </p>
}
}
let getAttemptCell = (attempt: attempts, attemptColType: attemptColType): Table.cell => {
switch attemptColType {
| Status =>
Label({
title: attempt.status->String.toUpperCase,
color: switch attempt.status->HSwitchOrderUtils.paymentAttemptStatusVariantMapper {
| #CHARGED => LabelGreen
| #AUTHENTICATION_FAILED
| #ROUTER_DECLINED
| #AUTHORIZATION_FAILED
| #VOIDED
| #CAPTURE_FAILED
| #VOID_FAILED
| #FAILURE =>
LabelRed
| _ => LabelLightGray
},
})
| Id => DisplayCopyCell(attempt.id)
| Error => Text(attempt.error)
| AttemptTriggeredBy => Text(attempt.attempt_triggered_by->LogicUtils.snakeToTitle)
| Created => Text(attempt.created)
}
}
let getAttemptHeading = (attemptColType: attemptColType) => {
switch attemptColType {
| Id => Table.makeHeaderInfo(~key="id", ~title="Attempt ID")
| Status => Table.makeHeaderInfo(~key="Status", ~title="Status")
| Error => Table.makeHeaderInfo(~key="Error", ~title="Error Reason")
| AttemptTriggeredBy => Table.makeHeaderInfo(~key="AttemptTriggeredBy", ~title="Attempted By")
| Created => Table.makeHeaderInfo(~key="Created", ~title="Created")
}
}
let attemptsItemToObjMapper = dict => {
id: dict->getString("id", ""),
status: dict->getString("status", ""),
error: dict->getString("error", ""),
attempt_triggered_by: dict
->getDictfromDict("feature_metadata")
->getDictfromDict("revenue_recovery")
->getString("attempt_triggered_by", ""),
created: dict->getString("created", ""),
}
let getAttempts: JSON.t => array<attempts> = json => {
LogicUtils.getArrayDataFromJson(json, attemptsItemToObjMapper)
}
let allColumns: array<colType> = [Id, Status, OrderAmount, Connector, Created, PaymentMethodType]
let getHeading = (colType: colType) => {
switch colType {
| Id => Table.makeHeaderInfo(~key="Invoice_ID", ~title="Invoice ID")
| Status => Table.makeHeaderInfo(~key="Status", ~title="Status")
| OrderAmount => Table.makeHeaderInfo(~key="OrderAmount", ~title="Order Amount")
| Connector => Table.makeHeaderInfo(~key="Connector", ~title="Connector")
| Created => Table.makeHeaderInfo(~key="Created", ~title="Created")
| PaymentMethodType => Table.makeHeaderInfo(~key="PaymentMethodType", ~title="Payment Method")
}
}
let getStatus = (order, primaryColor) => {
let orderStatusLabel = order.status->capitalizeString
let fixedStatusCss = "text-sm text-nd_green-400 font-medium px-2 py-1 rounded-md h-1/2"
switch order.status->HSwitchOrderUtils.statusVariantMapper {
| Succeeded
| PartiallyCaptured =>
<div className={`${fixedStatusCss} bg-green-50 dark:bg-opacity-50`}>
{orderStatusLabel->React.string}
</div>
| Failed
| Cancelled =>
<div className={`${fixedStatusCss} bg-red-960 dark:bg-opacity-50`}>
{orderStatusLabel->React.string}
</div>
| Processing
| RequiresCustomerAction
| RequiresConfirmation
| RequiresPaymentMethod =>
<div className={`${fixedStatusCss} ${primaryColor} bg-opacity-50`}>
{orderStatusLabel->React.string}
</div>
| _ =>
<div className={`${fixedStatusCss} ${primaryColor} bg-opacity-50`}>
{orderStatusLabel->React.string}
</div>
}
}
let getCell = (order, colType: colType): Table.cell => {
let orderStatus = order.status->HSwitchOrderUtils.statusVariantMapper
switch colType {
| Id =>
CustomCell(
<HelperComponents.CopyTextCustomComp
customTextCss="w-36 truncate whitespace-nowrap" displayValue=Some(order.id)
/>,
"",
)
| Status =>
Label({
title: order.status->String.toUpperCase,
color: switch orderStatus {
| Succeeded
| PartiallyCaptured =>
LabelGreen
| Failed
| Cancelled =>
LabelRed
| Processing
| RequiresCustomerAction
| RequiresConfirmation
| RequiresPaymentMethod =>
LabelBlue
| _ => LabelLightGray
},
})
| OrderAmount =>
CustomCell(
<CurrencyCell amount={(order.order_amount /. 100.0)->Float.toString} currency={"USD"} />,
"",
)
| Connector =>
CustomCell(
<HelperComponents.ConnectorCustomCell
connectorName=order.connector
connectorType={ConnectorUtils.connectorTypeFromConnectorName(order.connector)}
/>,
"",
)
| Created => Date(order.created)
| PaymentMethodType => Text(order.payment_method_type)
}
}
let concatValueOfGivenKeysOfDict = (dict, keys) => {
Array.reduceWithIndex(keys, "", (acc, key, i) => {
let val = dict->getString(key, "")
let delimiter = if val->isNonEmptyString {
if key !== "first_name" {
i + 1 == keys->Array.length ? "." : ", "
} else {
" "
}
} else {
""
}
String.concat(acc, `${val}${delimiter}`)
})
}
let defaultColumns: array<colType> = [
Id,
Status,
OrderAmount,
Connector,
Created,
PaymentMethodType,
]
let itemToObjMapper = dict => {
let attempts = dict->getArrayFromDict("attempts", [])->JSON.Encode.array->getAttempts
attempts->Array.reverse
{
id: dict->getString("id", ""),
status: dict->getString("status", ""),
order_amount: dict
->getDictfromDict("amount")
->getFloat("order_amount", 0.0) *. 100.0,
connector: dict->getString("connector", ""),
created: dict->getString("created", ""),
payment_method_type: dict->getString("payment_method_type", ""),
payment_method_subtype: dict->getString("payment_method_subtype", ""),
attempts,
}
}
let getOrders: JSON.t => array<order> = json => {
getArrayDataFromJson(json, itemToObjMapper)
}
let revenueRecoveryEntity = (merchantId, orgId, profile_id) =>
EntityType.makeEntity(
~uri=``,
~getObjects=getOrders,
~defaultColumns,
~allColumns,
~getHeading,
~getCell,
~dataKey="",
~getShowLink={
order =>
GlobalVars.appendDashboardPath(
~url=`v2/recovery/overview/${order.id}/${profile_id}/${merchantId}/${orgId}`,
)
},
)
| 1,606 | 9,340 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RevenueRecoveryOverview/RevenueRecoveryOrderUtils.res | .res | let getArrayDictFromRes = res => {
open LogicUtils
res->getDictFromJsonObject->getArrayFromDict("data", [])
}
let getSizeofRes = res => {
open LogicUtils
res->getDictFromJsonObject->getInt("size", 0)
}
let (startTimeFilterKey, endTimeFilterKey) = ("created.gte", "created.lte")
type filter = [
| #connector
| #payment_method
| #currency
| #authentication_type
| #status
| #payment_method_type
| #connector_label
| #card_network
| #card_discovery
| #customer_id
| #merchant_order_reference_id
| #unknown
]
let getFilterTypeFromString = filterType => {
switch filterType {
| "connector" => #connector
| "payment_method" => #payment_method
| "currency" => #currency
| "status" => #status
| "authentication_type" => #authentication_type
| "payment_method_type" => #payment_method_type
| "connector_label" => #connector_label
| "card_network" => #card_network
| "card_discovery" => #card_discovery
| "customer_id" => #customer_id
| "merchant_order_reference_id" => #merchant_order_reference_id
| _ => #unknown
}
}
let initialFilters = (json, filtervalues, removeKeys, filterKeys, setfilterKeys) => {
open LogicUtils
let filterDict = json->getDictFromJsonObject
let filterData = filterDict->OrderUIUtils.itemToObjMapper
let filtersArray = filterDict->Dict.keysToArray
let onDeleteClick = name => {
[name]->removeKeys
setfilterKeys(_ => filterKeys->Array.filter(item => item !== name))
}
let connectorFilter = filtervalues->getArrayFromDict("connector", [])->getStrArrayFromJsonArray
if connectorFilter->Array.length !== 0 {
filtersArray->Array.push(#connector_label->OrderUIUtils.getLabelFromFilterType)
}
let additionalFilters =
[#payment_method_type, #customer_id, #merchant_order_reference_id]->Array.map(
OrderUIUtils.getLabelFromFilterType,
)
let allFiltersArray = filtersArray->Array.concat(additionalFilters)
allFiltersArray->Array.map((key): EntityType.initialFilters<'t> => {
let values = switch key->getFilterTypeFromString {
| #connector => filterData.connector
| #payment_method => filterData.payment_method
| #currency => filterData.currency
| #authentication_type => filterData.authentication_type
| #status => filterData.status
| #payment_method_type =>
OrderUIUtils.getConditionalFilter(key, filterDict, filtervalues)->Array.length > 0
? OrderUIUtils.getConditionalFilter(key, filterDict, filtervalues)
: filterData.payment_method_type
| #connector_label => OrderUIUtils.getConditionalFilter(key, filterDict, filtervalues)
| #card_network => filterData.card_network
| #card_discovery => filterData.card_discovery
| _ => []
}
let title = `Select ${key->snakeToTitle}`
let makeOptions = (options: array<string>): array<FilterSelectBox.dropdownOption> => {
options->Array.map(str => {
let option: FilterSelectBox.dropdownOption = {label: str->snakeToTitle, value: str}
option
})
}
let options = switch key->getFilterTypeFromString {
| #connector_label => OrderUIUtils.getOptionsForOrderFilters(filterDict, filtervalues)
| _ => values->makeOptions
}
let customInput = switch key->getFilterTypeFromString {
| #customer_id
| #merchant_order_reference_id =>
(~input: ReactFinalForm.fieldRenderPropsInput, ~placeholder as _) =>
InputFields.textInput(
~rightIcon=<div
className="p-1 rounded-lg hover:bg-gray-200 cursor-pointer mr-6 "
onClick={_ => input.name->onDeleteClick}>
<Icon name="cross-outline" size=13 />
</div>,
~customWidth="w-48",
)(~input, ~placeholder=`Enter ${input.name->snakeToTitle}...`)
| _ =>
InputFields.filterMultiSelectInput(
~options,
~buttonText=title,
~showSelectionAsChips=false,
~searchable=true,
~showToolTip=true,
~allowMultiSelect=false,
~showNameAsToolTip=true,
~showAllSelectedOptions=false,
~customButtonStyle="bg-none",
(),
)
}
{
field: FormRenderer.makeFieldInfo(
~label=key,
~name=OrderUIUtils.getValueFromFilterType(key->getFilterTypeFromString),
~customInput,
),
localFilter: Some(OrderUIUtils.filterByData),
}
})
}
let initialFixedFilter = () => [
(
{
localFilter: None,
field: FormRenderer.makeMultiInputFieldInfo(
~label="",
~comboCustomInput=InputFields.filterDateRangeField(
~startKey=startTimeFilterKey,
~endKey=endTimeFilterKey,
~format="YYYY-MM-DDTHH:mm:ss[Z]",
~showTime=false,
~disablePastDates={false},
~disableFutureDates={true},
~predefinedDays=[
Hour(0.5),
Hour(1.0),
Hour(2.0),
Today,
Yesterday,
Day(2.0),
Day(7.0),
Day(30.0),
ThisMonth,
LastMonth,
],
~numMonths=2,
~disableApply=false,
~dateRangeLimit=180,
),
~inputFields=[],
~isRequired=false,
),
}: EntityType.initialFilters<'t>
),
]
| 1,299 | 9,341 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RevenueRecoveryOverview/RevenueRecoveryOverview.res | .res | @react.component
let make = () => {
open APIUtils
open LogicUtils
//open HSwitchRemoteFilter
let getURL = useGetURL()
let fetchDetails = useGetMethod()
let {userInfo: {merchantId, orgId, profileId}} = React.useContext(UserInfoProvider.defaultContext)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (totalCount, setTotalCount) = React.useState(_ => 0)
let defaultValue: LoadedTable.pageDetails = {offset: 0, resultsPerPage: 10}
let pageDetailDict = Recoil.useRecoilValueFromAtom(LoadedTable.table_pageDetails)
let pageDetail = pageDetailDict->Dict.get("recovery_orders")->Option.getOr(defaultValue)
let (offset, setOffset) = React.useState(_ => pageDetail.offset)
let (filters, setFilters) = React.useState(_ => None)
let (searchText, setSearchText) = React.useState(_ => "")
let {filterValueJson, updateExistingKeys} = React.useContext(FilterContext.filterContext)
let startTime = filterValueJson->getString("created.gte", "")
let (revenueRecoveryData, setRevenueRecoveryData) = React.useState(_ => [])
let mixpanelEvent = MixpanelHook.useSendEvent()
let setData = (total, data) => {
let arr = Array.make(~length=offset, Dict.make())
if total <= offset {
setOffset(_ => 0)
}
if total > 0 {
let orderDataDictArr = data->Belt.Array.keepMap(JSON.Decode.object)
let orderData = orderDataDictArr->Array.map(RevenueRecoveryEntity.itemToObjMapper)
let list = orderData->Array.map(Nullable.make)
setTotalCount(_ => total)
setRevenueRecoveryData(_ => list)
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Success)
}
}
let getPaymentsList = async (filterValueJson: RescriptCore.Dict.t<Core__JSON.t>) => {
setScreenState(_ => PageLoaderWrapper.Loading)
try {
let filter =
filterValueJson
->Dict.toArray
->Array.map(item => {
let (key, value) = item
let value = switch value->JSON.Classify.classify {
| String(str) => str
| Number(num) => num->Float.toString
| _ => ""
}
(key, value)
})
->Dict.fromArray
let ordersUrl = getURL(
~entityName=V2(V2_ORDERS_LIST),
~methodType=Get,
~queryParamerters=Some(filter->FilterUtils.parseFilterDict),
)
//let res = await fetchDetails(ordersUrl, ~version=V2)
let res = RevenueRecoveryData.orderData
let data = res->getDictFromJsonObject->getArrayFromDict("data", [])
let total = res->getDictFromJsonObject->getInt("total_count", 0)
if data->Array.length === 0 && filterValueJson->Dict.get("payment_id")->Option.isSome {
let payment_id =
filterValueJson
->Dict.get("payment_id")
->Option.getOr(""->JSON.Encode.string)
->JSON.Decode.string
->Option.getOr("")
if RegExp.test(%re(`/^[A-Za-z0-9]+_[A-Za-z0-9]+_[0-9]+/`), payment_id) {
let newID = payment_id->String.replaceRegExp(%re("/_[0-9]$/g"), "")
filterValueJson->Dict.set("payment_id", newID->JSON.Encode.string)
//let res = await fetchDetails(ordersUrl, ~version=V2)
let res = RevenueRecoveryData.orderData
let data = res->getDictFromJsonObject->getArrayFromDict("data", [])
let total = res->getDictFromJsonObject->getInt("total_count", 0)
setData(total, data)
} else {
setScreenState(_ => PageLoaderWrapper.Success)
}
} else {
setData(total, data)
}
} catch {
| Exn.Error(_) => setScreenState(_ => PageLoaderWrapper.Error("Something went wrong!"))
}
}
let fetchOrders = () => {
let query = switch filters {
| Some(dict) =>
let filters = Dict.make()
filters->Dict.set("offset", offset->Int.toFloat->JSON.Encode.float)
filters->Dict.set("limit", 50->Int.toFloat->JSON.Encode.float)
if !(searchText->isEmptyString) {
filters->Dict.set("payment_id", searchText->String.trim->JSON.Encode.string)
}
//to create amount_filter query
let newDict = AmountFilterUtils.createAmountQuery(~dict)
newDict
->Dict.toArray
->Array.forEach(item => {
let (key, value) = item
filters->Dict.set(key, value)
})
// TODO: enable amount filter later
filters->Dict.delete("amount_filter")
filters
| _ => Dict.make()
}
query
->getPaymentsList
->ignore
}
React.useEffect(() => {
// if filters->OrderUIUtils.isNonEmptyValue {
// fetchOrders()
// }
fetchOrders()
None
}, (offset, filters, searchText))
let customTitleStyle = "py-0 !pt-0"
// let customUI =
// <NoDataFound
// customCssClass="my-6" message="Recovery details will appear soon" renderType={ExtendDateUI}
// />
let (widthClass, heightClass) = ("w-full", "")
// let filtersUI = React.useMemo(() => {
// <RemoteTableFilters
// title="Orders"
// setFilters
// endTimeFilterKey
// startTimeFilterKey
// initialFilters
// initialFixedFilter
// setOffset
// submitInputOnEnter=true
// customLeftView={<SearchBarFilter
// placeholder="Search for payment ID" setSearchVal=setSearchText searchVal=searchText
// />}
// entityName=V2(V2_ORDER_FILTERS)
// version=V2
// />
// }, [searchText])
<ErrorBoundary>
<div className={`flex flex-col mx-auto h-full ${widthClass} ${heightClass} min-h-[50vh]`}>
<div className="flex justify-between items-center">
<PageUtils.PageHeading
title="Revenue Recovery Payments"
subTitle="List of failed Invoices picked up for retry"
customTitleStyle
/>
</div>
//<div className="flex"> {filtersUI} </div>
<PageLoaderWrapper screenState>
<LoadedTableWithCustomColumns
title="Recovery"
actualData=revenueRecoveryData
entity={RevenueRecoveryEntity.revenueRecoveryEntity(merchantId, orgId, profileId)}
resultsPerPage=10
showSerialNumber=true
totalResults={totalCount}
offset
setOffset
currrentFetchCount={revenueRecoveryData->Array.length}
customColumnMapper=TableAtoms.revenueRecoveryMapDefaultCols
defaultColumns={RevenueRecoveryEntity.defaultColumns}
showSerialNumberInCustomizeColumns=false
sortingBasedOnDisabled=false
hideTitle=true
remoteSortEnabled=true
showAutoScroll=true
hideCustomisableColumnButton=true
/>
</PageLoaderWrapper>
</div>
</ErrorBoundary>
}
| 1,682 | 9,342 |
hyperswitch-control-center | src/RevenueRecovery/RevenueRecoveryScreens/RevenueRecoveryOverview/RevenueRecoveryOrderTypes.res | .res | type colType =
| Id
| Status
| OrderAmount
| Connector
| Created
| PaymentMethodType
type attemptColType =
| Id
| Status
| Error
| AttemptTriggeredBy
| Created
type attempts = {
id: string,
status: string,
error: string,
attempt_triggered_by: string,
created: string,
}
type order = {
id: string,
status: string,
order_amount: float,
connector: string,
created: string,
payment_method_type: string,
payment_method_subtype: string,
attempts: array<attempts>,
}
type optionObj = {
urlKey: string,
label: string,
}
type topic =
| String(string)
| ReactElement(React.element)
| 176 | 9,343 |
hyperswitch-control-center | src/entryPoints/HyperSwitchEntry.res | .res | module HyperSwitchEntryComponent = {
open HyperswitchAtom
@react.component
let make = () => {
let fetchDetails = APIUtils.useGetMethod()
let url = RescriptReactRouter.useUrl()
let (_zone, setZone) = React.useContext(UserTimeZoneProvider.userTimeContext)
let setFeatureFlag = featureFlagAtom->Recoil.useSetRecoilState
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let {getThemesJson} = React.useContext(ThemeProvider.themeContext)
let configureFavIcon = (faviconUrl: option<string>) => {
try {
open DOMUtils
let a = createElement(DOMUtils.document, "link")
let _ = setAttribute(a, "href", `${faviconUrl->Option.getOr("/HyperswitchFavicon.png")}`)
let _ = setAttribute(a, "rel", "shortcut icon")
let _ = setAttribute(a, "type", "image/x-icon")
let _ = appendHead(a)
} catch {
| _ => Exn.raiseError("Error on configuring favicon")
}
}
let themesID =
url.search->LogicUtils.getDictFromUrlSearchParams->Dict.get("theme_id")->Option.getOr("")
let configEnv = (urlConfig: JSON.t) => {
open LogicUtils
open HyperSwitchConfigTypes
try {
let dict = urlConfig->getDictFromJsonObject->getDictfromDict("endpoints")
let value: urlConfig = {
apiBaseUrl: dict->getString("api_url", ""),
mixpanelToken: dict->getString("mixpanel_token", ""),
sdkBaseUrl: dict->getString("sdk_url", "")->getNonEmptyString,
agreementUrl: dict->getString("agreement_url", "")->getNonEmptyString,
dssCertificateUrl: dict->getString("dss_certificate_url", "")->getNonEmptyString,
applePayCertificateUrl: dict
->getString("apple_pay_certificate_url", "")
->getNonEmptyString,
agreementVersion: dict->getString("agreement_version", "")->getNonEmptyString,
reconIframeUrl: dict->getString("recon_iframe_url", "")->getNonEmptyString,
urlThemeConfig: {
faviconUrl: dict->getString("favicon_url", "")->getNonEmptyString,
logoUrl: dict->getString("logo_url", "")->getNonEmptyString,
},
hypersenseUrl: dict->getString("hypersense_url", ""),
}
DOMUtils.window._env_ = value
configureFavIcon(value.urlThemeConfig.faviconUrl)->ignore
} catch {
| _ => Exn.raiseError("Error on configuring endpoint")
}
}
let fetchConfig = async () => {
try {
let domain = HyperSwitchEntryUtils.getSessionData(~key="domain", ~defaultValue="")
let apiURL = `${GlobalVars.getHostUrlWithBasePath}/config/feature?domain=${domain}` // todo: domain shall be removed from query params later
let res = await fetchDetails(apiURL)
let featureFlags = res->FeatureFlagUtils.featureFlagType
setFeatureFlag(_ => featureFlags)
let devThemeFeature = featureFlags.devThemeFeature
let _ = configEnv(res) // to set initial env
let _ = await getThemesJson(themesID, res, devThemeFeature)
// Delay added on Expecting feature flag recoil gets updated
await HyperSwitchUtils.delay(1000)
setScreenState(_ => PageLoaderWrapper.Success)
} catch {
| _ => setScreenState(_ => Custom)
}
}
React.useEffect(() => {
let _ = HyperSwitchEntryUtils.setSessionData(~key="auth_id", ~searchParams=url.search)
let _ = HyperSwitchEntryUtils.setSessionData(~key="domain", ~searchParams=url.search) // todo: setting domain in session storage shall be removed later
let _ = fetchConfig()->ignore
None
}, [])
React.useEffect(() => {
TimeZoneUtils.getUserTimeZone()->setZone
None
}, [])
let setPageName = pageTitle => {
let page = pageTitle->LogicUtils.snakeToTitle
let title = `${page} - Dashboard`
DOMUtils.document.title = title
GoogleAnalytics.send({hitType: "pageview", page})
}
React.useEffect(() => {
switch url.path {
| list{"user", "verify_email"} => "verify_email"->setPageName
| list{"user", "set_password"} => "set_password"->setPageName
| list{"user", "login"} => "magic_link_verify"->setPageName
| _ =>
switch url.path->List.drop(1) {
| Some(val) =>
switch List.head(val) {
| Some(pageTitle) => pageTitle->setPageName
| _ => ()
}
| _ => ()
}
}
None
}, [url.path])
<PageLoaderWrapper
screenState
sectionHeight="h-screen"
customUI={<NoDataFound message="Oops! Missing config" renderType=NotFound />}>
<div className="text-black">
<AuthEntry />
</div>
</PageLoaderWrapper>
}
}
let uiConfig: UIConfig.t = HyperSwitchDefaultConfig.config
EntryPointUtils.renderDashboardApp(<HyperSwitchEntryComponent />)
| 1,168 | 9,344 |
hyperswitch-control-center | src/entryPoints/HyperSwitchEntryUtils.res | .res | open SessionStorage
open LogicUtils
let setSessionData = (~key, ~searchParams) => {
let result = searchParams->getDictFromUrlSearchParams->Dict.get(key)
switch result {
| Some(data) => sessionStorage.setItem(key, data)
| None => ()
}
}
let getSessionData = (~key, ~defaultValue="") => {
let result = sessionStorage.getItem(key)->Nullable.toOption->Option.getOr("")->getNonEmptyString
switch result {
| Some(data) => data
| None => defaultValue
}
}
| 119 | 9,345 |
hyperswitch-control-center | src/entryPoints/ProductTypes.res | .res | @unboxed
type productTypes =
| @as("orchestration") Orchestration
| @as("recon") Recon
| @as("recovery") Recovery
| @as("vault") Vault
| @as("cost_observability") CostObservability
| @as("dynamic_routing") DynamicRouting
| 75 | 9,346 |
hyperswitch-control-center | src/entryPoints/HyperSwitchApp.res | .res | @react.component
let make = () => {
open HSwitchUtils
open GlobalVars
open APIUtils
open HyperswitchAtom
let url = RescriptReactRouter.useUrl()
let {
showFeedbackModal,
setShowFeedbackModal,
dashboardPageState,
setDashboardPageState,
} = React.useContext(GlobalProvider.defaultContext)
let {activeProduct, setActiveProductValue} = React.useContext(
ProductSelectionProvider.defaultContext,
)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let merchantDetailsTypedValue = Recoil.useRecoilValueFromAtom(merchantDetailsValueAtom)
let featureFlagDetails = featureFlagAtom->Recoil.useRecoilValueFromAtom
let (userGroupACL, setuserGroupACL) = Recoil.useRecoilState(userGroupACLAtom)
let {getThemesJson} = React.useContext(ThemeProvider.themeContext)
let {devThemeFeature} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let {
fetchMerchantSpecificConfig,
useIsFeatureEnabledForMerchant,
merchantSpecificConfig,
} = MerchantSpecificConfigHook.useMerchantSpecificConfig()
let {fetchUserGroupACL, userHasAccess, hasAnyGroupAccess} = GroupACLHooks.useUserGroupACLHook()
let {setShowSideBar} = React.useContext(GlobalProvider.defaultContext)
let fetchMerchantAccountDetails = MerchantDetailsHook.useFetchMerchantDetails()
let {
userInfo: {orgId, merchantId, profileId, roleId, themeId, version},
checkUserEntity,
} = React.useContext(UserInfoProvider.defaultContext)
let isInternalUser = roleId->HyperSwitchUtils.checkIsInternalUser
let modeText = featureFlagDetails.isLiveMode ? "Live Mode" : "Test Mode"
let modebg = featureFlagDetails.isLiveMode ? "bg-hyperswitch_green" : "bg-orange-500 "
let isReconEnabled = React.useMemo(() => {
merchantDetailsTypedValue.recon_status === Active
}, [merchantDetailsTypedValue.merchant_id])
let maintainenceAlert = featureFlagDetails.maintainenceAlert
let hyperSwitchAppSidebars = SidebarValues.useGetSidebarValuesForCurrentActive(~isReconEnabled)
let productSidebars = ProductsSidebarValues.useGetProductSideBarValues(~activeProduct)
sessionExpired := false
let applyTheme = async () => {
try {
if devThemeFeature || themeId->LogicUtils.isNonEmptyString {
let _ = await getThemesJson(themeId, JSON.Encode.null, devThemeFeature)
}
} catch {
| _ => ()
}
}
// set the product url based on the product type
let setupProductUrl = (~productType: ProductTypes.productTypes) => {
let currentUrl = GlobalVars.extractModulePath(
~path=url.path,
~query=url.search,
~end=url.path->List.toArray->Array.length,
)
let productUrl = ProductUtils.getProductUrl(~productType, ~url=currentUrl)
RescriptReactRouter.replace(productUrl)
switch url.path->urlPath {
| list{"unauthorized"} => RescriptReactRouter.push(appendDashboardPath(~url="/home"))
| _ => ()
}
}
let setUpDashboard = async () => {
try {
// NOTE: Treat groupACL map similar to screenstate
setScreenState(_ => PageLoaderWrapper.Loading)
setuserGroupACL(_ => None)
Window.connectorWasmInit()->ignore
let merchantResponse = await fetchMerchantAccountDetails(~version)
let _ = await fetchMerchantSpecificConfig()
let _ = await fetchUserGroupACL()
setActiveProductValue(merchantResponse.product_type)
setShowSideBar(_ => true)
setupProductUrl(~productType=merchantResponse.product_type)
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Error("Failed to setup dashboard!"))
}
}
React.useEffect(() => {
setUpDashboard()->ignore
None
}, [orgId, merchantId, profileId, themeId])
React.useEffect(() => {
applyTheme()->ignore
None
}, (themeId, devThemeFeature))
React.useEffect(() => {
if userGroupACL->Option.isSome {
setDashboardPageState(_ => #HOME)
setScreenState(_ => PageLoaderWrapper.Success)
}
None
}, [userGroupACL])
let pageViewEvent = MixpanelHook.usePageView()
let path = url.path->List.toArray->Array.joinWith("/")
React.useEffect(() => {
if featureFlagDetails.mixpanel {
pageViewEvent(~path)->ignore
}
None
}, (featureFlagDetails.mixpanel, path))
<>
<div>
{switch dashboardPageState {
| #AUTO_CONNECTOR_INTEGRATION => <HSwitchSetupAccount />
// INTEGRATION_DOC Need to be removed
| #INTEGRATION_DOC => <UserOnboarding />
| #HOME =>
<div className="relative">
// TODO: Change the key to only profileId once the userInfo starts sending profileId
<div className={`h-screen flex flex-col`}>
<div className="flex relative overflow-auto h-screen ">
<RenderIf condition={screenState === Success}>
<Sidebar
path={url.path}
sidebars={hyperSwitchAppSidebars}
key={(screenState :> string)}
productSiebars=productSidebars
/>
</RenderIf>
<PageLoaderWrapper
screenState={screenState} sectionHeight="!h-screen w-full" showLogoutButton=true>
<div
className="flex relative flex-col flex-1 bg-hyperswitch_background dark:bg-black overflow-scroll md:overflow-x-hidden">
<div className="w-full max-w-fixedPageWidth md:px-12 px-5 pt-3">
<Navbar
headerActions={<div className="relative flex space-around gap-4 my-2 ">
<div className="flex gap-4 items-center">
<RenderIf
condition={merchantDetailsTypedValue.product_type == Orchestration}>
<GlobalSearchBar />
</RenderIf>
<RenderIf condition={isInternalUser}>
<SwitchMerchantForInternal />
</RenderIf>
</div>
</div>}
headerLeftActions={switch Window.env.urlThemeConfig.logoUrl {
| Some(url) =>
<div className="flex md:gap-4 gap-2 items-center">
<img className="h-8 w-auto object-contain" alt="image" src={`${url}`} />
<ProfileSwitch />
<div
className={`flex flex-row items-center px-2 py-3 gap-2 whitespace-nowrap cursor-default justify-between h-8 bg-white border rounded-lg text-sm text-nd_gray-500 border-nd_gray-300`}>
<span className="relative flex h-2 w-2">
<span
className={`animate-ping absolute inline-flex h-full w-full rounded-full ${modebg} opacity-75`}
/>
<span
className={`relative inline-flex rounded-full h-2 w-2 ${modebg}`}
/>
</span>
<span className="font-semibold"> {modeText->React.string} </span>
</div>
</div>
| None =>
<div className="flex md:gap-4 gap-2 items-center">
<ProfileSwitch />
<div
className={`flex flex-row items-center px-2 py-3 gap-2 whitespace-nowrap cursor-default justify-between h-8 bg-white border rounded-lg text-sm text-nd_gray-500 border-nd_gray-300`}>
<span className="relative flex h-2 w-2">
<span
className={`animate-ping absolute inline-flex h-full w-full rounded-full ${modebg} opacity-75`}
/>
<span
className={`relative inline-flex rounded-full h-2 w-2 ${modebg}`}
/>
</span>
<span className="font-semibold"> {modeText->React.string} </span>
</div>
</div>
}}
/>
</div>
<div
className="w-full h-screen overflow-x-scroll xl:overflow-x-hidden overflow-y-scroll">
<RenderIf condition={maintainenceAlert->LogicUtils.isNonEmptyString}>
<HSwitchUtils.AlertBanner bannerText={maintainenceAlert} bannerType={Info} />
</RenderIf>
<div
className="p-6 md:px-12 md:py-8 flex flex-col gap-10 max-w-fixedPageWidth min-h-full">
<ErrorBoundary>
{switch url.path->urlPath {
/* DEFAULT HOME */
| list{"v2", "home"} => <DefaultHome />
/* RECON PRODUCT */
| list{"v2", "recon", ..._} => <ReconApp />
/* RECOVERY PRODUCT */
| list{"v2", "recovery", ..._} => <RevenueRecoveryApp />
/* VAULT PRODUCT */
| list{"v2", "vault", ..._} => <VaultApp />
/* HYPERSENSE PRODUCT */
| list{"v2", "cost-observability", ..._} => <HypersenseApp />
/* INTELLIGENT ROUTING PRODUCT */
| list{"v2", "dynamic-routing", ..._} => <IntelligentRoutingApp />
/* ORCHESTRATOR PRODUCT */
| list{"home", ..._}
| list{"recon"}
| list{"upload-files"}
| list{"run-recon"}
| list{"recon-analytics"}
| list{"reports"}
| list{"config-settings"}
| list{"sdk"} =>
<MerchantAccountContainer setAppScreenState=setScreenState />
// Commented as not needed now
// list{"file-processor"}
| list{"connectors", ..._}
| list{"payoutconnectors", ..._}
| list{"3ds-authenticators", ..._}
| list{"pm-authentication-processor", ..._}
| list{"tax-processor", ..._}
| list{"fraud-risk-management", ..._}
| list{"configure-pmts", ..._}
| list{"routing", ..._}
| list{"payoutrouting", ..._}
| list{"payment-settings", ..._}
| list{"webhooks", ..._} =>
<ConnectorContainer />
| list{"apm"} => <APMContainer />
| list{"business-details", ..._}
| list{"business-profiles", ..._} =>
<BusinessProfileContainer />
| list{"payments", ..._}
| list{"refunds", ..._}
| list{"disputes", ..._}
| list{"payouts", ..._} =>
<TransactionContainer />
| list{"analytics-payments"}
| list{"performance-monitor"}
| list{"analytics-refunds"}
| list{"analytics-disputes"}
| list{"analytics-authentication"} =>
<AnalyticsContainer />
| list{"new-analytics-payment"}
| list{"new-analytics-refund"}
| list{"new-analytics-smart-retry"} =>
<AccessControl
isEnabled={featureFlagDetails.newAnalytics &&
useIsFeatureEnabledForMerchant(merchantSpecificConfig.newAnalytics)}
authorization={userHasAccess(~groupAccess=AnalyticsView)}>
<FilterContext key="NewAnalytics" index="NewAnalytics">
<NewAnalyticsContainer />
</FilterContext>
</AccessControl>
| list{"customers", ...remainingPath} =>
<AccessControl
authorization={userHasAccess(~groupAccess=OperationsView)}
isEnabled={[#Tenant, #Organization, #Merchant]->checkUserEntity}>
<EntityScaffold
entityName="Customers"
remainingPath
access=Access
renderList={() => <Customers />}
renderShow={(id, _) => <ShowCustomers id />}
/>
</AccessControl>
| list{"users", ..._} => <UserManagementContainer />
| list{"developer-api-keys"} =>
<AccessControl
// TODO: Remove `MerchantDetailsManage` permission in future
authorization={hasAnyGroupAccess(
userHasAccess(~groupAccess=MerchantDetailsView),
userHasAccess(~groupAccess=AccountManage),
)}
isEnabled={!checkUserEntity([#Profile])}>
<KeyManagement.KeysManagement />
</AccessControl>
| list{"compliance"} =>
<AccessControl
isEnabled=featureFlagDetails.complianceCertificate authorization=Access>
<Compliance />
</AccessControl>
| list{"3ds"} =>
<AccessControl authorization={userHasAccess(~groupAccess=WorkflowsView)}>
<HSwitchThreeDS />
</AccessControl>
| list{"surcharge"} =>
<AccessControl
isEnabled={featureFlagDetails.surcharge}
authorization={userHasAccess(~groupAccess=WorkflowsView)}>
<Surcharge />
</AccessControl>
| list{"account-settings"} =>
<AccessControl
isEnabled=featureFlagDetails.sampleData
// TODO: Remove `MerchantDetailsManage` permission in future
authorization={hasAnyGroupAccess(
userHasAccess(~groupAccess=MerchantDetailsManage),
userHasAccess(~groupAccess=AccountManage),
)}>
<HSwitchSettings />
</AccessControl>
| list{"account-settings", "profile", ...remainingPath} =>
<EntityScaffold
entityName="profile setting"
remainingPath
renderList={() => <HSwitchProfileSettings />}
renderShow={(_, _) => <ModifyTwoFaSettings />}
/>
| list{"search"} => <SearchResultsPage />
| list{"payment-attempts"} =>
<AccessControl
isEnabled={featureFlagDetails.globalSearch}
authorization={userHasAccess(~groupAccess=OperationsView)}>
<PaymentAttemptTable />
</AccessControl>
| list{"payment-intents"} =>
<AccessControl
isEnabled={featureFlagDetails.globalSearch}
authorization={userHasAccess(~groupAccess=OperationsView)}>
<PaymentIntentTable />
</AccessControl>
| list{"refunds-global"} =>
<AccessControl
isEnabled={featureFlagDetails.globalSearch}
authorization={userHasAccess(~groupAccess=OperationsView)}>
<RefundsTable />
</AccessControl>
| list{"dispute-global"} =>
<AccessControl
isEnabled={featureFlagDetails.globalSearch}
authorization={userHasAccess(~groupAccess=OperationsView)}>
<DisputeTable />
</AccessControl>
| list{"unauthorized"} => <UnauthorizedPage />
| _ =>
// SPECIAL CASE FOR ORCHESTRATOR
if activeProduct === Orchestration {
RescriptReactRouter.replace(appendDashboardPath(~url="/home"))
<MerchantAccountContainer setAppScreenState=setScreenState />
} else {
React.null
}
}}
</ErrorBoundary>
</div>
</div>
</div>
<RenderIf condition={showFeedbackModal && featureFlagDetails.feedback}>
<HSwitchFeedBackModal
modalHeading="We'd love to hear from you!"
showModal={showFeedbackModal}
setShowModal={setShowFeedbackModal}
/>
</RenderIf>
<RenderIf condition={!featureFlagDetails.isLiveMode}>
<ProdIntentForm productType={activeProduct} />
</RenderIf>
</PageLoaderWrapper>
</div>
</div>
</div>
| #DEFAULT =>
<div className="h-screen flex justify-center items-center">
<Loader />
</div>
}}
</div>
</>
}
| 3,411 | 9,347 |
hyperswitch-control-center | src/entryPoints/EntryPointUtils.res | .res | %%raw(`require("tailwindcss/tailwind.css")`)
module ContextWrapper = {
@react.component
let make = (~children) => {
let loader =
<div className={`h-screen w-screen flex justify-center items-center`}>
<Loader />
</div>
<React.Suspense fallback={loader}>
<ErrorBoundary renderFallback={_ => <div> {React.string("Error")} </div>}>
<Recoil.RecoilRoot>
<ErrorBoundary>
<ThemeProvider>
<PopUpContainer>
<SnackBarContainer>
<ToastContainer>
<TokenContextProvider>
<UserTimeZoneProvider>
<SidebarProvider>
<ModalContainer> children </ModalContainer>
</SidebarProvider>
</UserTimeZoneProvider>
</TokenContextProvider>
</ToastContainer>
</SnackBarContainer>
</PopUpContainer>
</ThemeProvider>
</ErrorBoundary>
</Recoil.RecoilRoot>
</ErrorBoundary>
</React.Suspense>
}
}
let renderDashboardApp = children => {
switch ReactDOM.querySelector("#app") {
| Some(container) =>
open ReactDOM.Client
open ReactDOM.Client.Root
let root = createRoot(container)
root->render(
<div className={`h-screen overflow-hidden flex flex-col font-inter-style`}>
<ContextWrapper> children </ContextWrapper>
</div>,
)
| None => ()
}
}
| 305 | 9,348 |
hyperswitch-control-center | src/entryPoints/SidebarValues.res | .res | open SidebarTypes
open UserManagementTypes
// * Custom Component
module GetProductionAccess = {
@react.component
let make = () => {
let mixpanelEvent = MixpanelHook.useSendEvent()
let textStyles = HSwitchUtils.getTextClass((P2, Medium))
let {isProdIntentCompleted, setShowProdIntentForm} = React.useContext(
GlobalProvider.defaultContext,
)
let {globalUIConfig: {sidebarColor: {borderColor}}} = React.useContext(
ThemeProvider.themeContext,
)
let isProdIntent = isProdIntentCompleted->Option.getOr(false)
let cursorStyles = isProdIntent ? "cursor-default" : "cursor-pointer"
let productionAccessString = isProdIntent
? "Production Access Requested"
: "Get Production Access"
switch isProdIntentCompleted {
| Some(_) =>
<div
className={`flex items-center gap-2 border ${borderColor} bg-white text-nd_gray-700 ${cursorStyles} px-3 py-10-px mb-4 whitespace-nowrap rounded-lg justify-between`}
onClick={_ => {
isProdIntent
? ()
: {
setShowProdIntentForm(_ => true)
mixpanelEvent(~eventName="get_production_access")
}
}}>
<div className={`text-nd_gray-600 ${textStyles} !font-semibold`}>
{productionAccessString->React.string}
</div>
<RenderIf condition={!isProdIntent}>
<Icon name="nd-arrow-right" size=22 className="pt-2" />
</RenderIf>
</div>
| None =>
<Shimmer
styleClass="h-10 px-4 py-3 m-2 ml-2 mb-3 dark:bg-black bg-white rounded" shimmerType={Small}
/>
}
}
}
module ProductHeaderComponent = {
@react.component
let make = () => {
let {activeProduct} = React.useContext(ProductSelectionProvider.defaultContext)
<div className={`text-xs font-semibold px-3 py-2 text-nd_gray-400 tracking-widest`}>
{React.string(activeProduct->ProductUtils.getProductDisplayName->String.toUpperCase)}
</div>
}
}
let emptyComponent = CustomComponent({
component: React.null,
})
let productionAccessComponent = (isProductionAccessEnabled, userHasAccess, hasAnyGroupAccess) =>
isProductionAccessEnabled &&
// TODO: Remove `MerchantDetailsManage` permission in future
hasAnyGroupAccess(
userHasAccess(~groupAccess=MerchantDetailsManage),
userHasAccess(~groupAccess=AccountManage),
) === CommonAuthTypes.Access
? CustomComponent({
component: <GetProductionAccess />,
})
: emptyComponent
// * Main Features
let home = isHomeEnabled =>
isHomeEnabled
? Link({
name: "Home",
icon: "nd-home",
link: "/home",
access: Access,
selectedIcon: "nd-fill-home",
})
: emptyComponent
let payments = userHasResourceAccess => {
SubLevelLink({
name: "Payments",
link: `/payments`,
access: userHasResourceAccess(~resourceAccess=Payment),
searchOptions: [("View payment operations", "")],
})
}
let refunds = userHasResourceAccess => {
SubLevelLink({
name: "Refunds",
link: `/refunds`,
access: userHasResourceAccess(~resourceAccess=Refund),
searchOptions: [("View refund operations", "")],
})
}
let disputes = userHasResourceAccess => {
SubLevelLink({
name: "Disputes",
link: `/disputes`,
access: userHasResourceAccess(~resourceAccess=Dispute),
searchOptions: [("View dispute operations", "")],
})
}
let customers = userHasResourceAccess => {
SubLevelLink({
name: "Customers",
link: `/customers`,
access: userHasResourceAccess(~resourceAccess=Customer),
searchOptions: [("View customers", "")],
})
}
let payouts = userHasResourceAccess => {
SubLevelLink({
name: "Payouts",
link: `/payouts`,
access: userHasResourceAccess(~resourceAccess=Payout),
searchOptions: [("View payouts operations", "")],
})
}
let alternatePaymentMethods = isApmEnabled =>
isApmEnabled
? Link({
name: "Alt Payment Methods",
icon: "nd-apm",
link: "/apm",
access: Access,
selectedIcon: "nd-fill-apm",
})
: emptyComponent
let operations = (isOperationsEnabled, ~userHasResourceAccess, ~isPayoutsEnabled, ~userEntity) => {
let payments = payments(userHasResourceAccess)
let refunds = refunds(userHasResourceAccess)
let disputes = disputes(userHasResourceAccess)
let customers = customers(userHasResourceAccess)
let payouts = payouts(userHasResourceAccess)
let links = [payments, refunds, disputes]
let isCustomersEnabled = userEntity !== #Profile
if isPayoutsEnabled {
links->Array.push(payouts)->ignore
}
if isCustomersEnabled {
links->Array.push(customers)->ignore
}
isOperationsEnabled
? Section({
name: "Operations",
icon: "nd-operations",
showSection: true,
links,
selectedIcon: "nd-operations-fill",
})
: emptyComponent
}
let paymentProcessor = (isLiveMode, userHasResourceAccess) => {
SubLevelLink({
name: "Payment Processors",
link: `/connectors`,
access: userHasResourceAccess(~resourceAccess=Connector),
searchOptions: HSwitchUtils.getSearchOptionsForProcessors(
~processorList=isLiveMode
? ConnectorUtils.connectorListForLive
: ConnectorUtils.connectorList,
~getNameFromString=ConnectorUtils.getConnectorNameString,
),
})
}
let payoutConnectors = (~userHasResourceAccess) => {
SubLevelLink({
name: "Payout Processors",
link: `/payoutconnectors`,
access: userHasResourceAccess(~resourceAccess=Connector),
searchOptions: HSwitchUtils.getSearchOptionsForProcessors(
~processorList=ConnectorUtils.payoutConnectorList,
~getNameFromString=ConnectorUtils.getConnectorNameString,
),
})
}
let fraudAndRisk = (~userHasResourceAccess) => {
SubLevelLink({
name: "Fraud & Risk",
link: `/fraud-risk-management`,
access: userHasResourceAccess(~resourceAccess=Connector),
searchOptions: [],
})
}
let threeDsConnector = (~userHasResourceAccess) => {
SubLevelLink({
name: "3DS Authenticators",
link: "/3ds-authenticators",
access: userHasResourceAccess(~resourceAccess=Connector),
searchOptions: [
("Connect 3dsecure.io", "/new?name=threedsecureio"),
("Connect threedsecureio", "/new?name=threedsecureio"),
],
})
}
let pmAuthenticationProcessor = (~userHasResourceAccess) => {
SubLevelLink({
name: "PM Authentication Processor",
link: `/pm-authentication-processor`,
access: userHasResourceAccess(~resourceAccess=Connector),
searchOptions: HSwitchUtils.getSearchOptionsForProcessors(
~processorList=ConnectorUtils.pmAuthenticationConnectorList,
~getNameFromString=ConnectorUtils.getConnectorNameString,
),
})
}
let taxProcessor = (~userHasResourceAccess) => {
SubLevelLink({
name: "Tax Processor",
link: `/tax-processor`,
access: userHasResourceAccess(~resourceAccess=Connector),
searchOptions: HSwitchUtils.getSearchOptionsForProcessors(
~processorList=ConnectorUtils.taxProcessorList,
~getNameFromString=ConnectorUtils.getConnectorNameString,
),
})
}
let connectors = (
isConnectorsEnabled,
~isLiveMode,
~isFrmEnabled,
~isPayoutsEnabled,
~isThreedsConnectorEnabled,
~isPMAuthenticationProcessor,
~isTaxProcessor,
~userHasResourceAccess,
) => {
let connectorLinkArray = [paymentProcessor(isLiveMode, userHasResourceAccess)]
if isPayoutsEnabled {
connectorLinkArray->Array.push(payoutConnectors(~userHasResourceAccess))->ignore
}
if isThreedsConnectorEnabled {
connectorLinkArray->Array.push(threeDsConnector(~userHasResourceAccess))->ignore
}
if isFrmEnabled {
connectorLinkArray->Array.push(fraudAndRisk(~userHasResourceAccess))->ignore
}
if isPMAuthenticationProcessor {
connectorLinkArray->Array.push(pmAuthenticationProcessor(~userHasResourceAccess))->ignore
}
if isTaxProcessor {
connectorLinkArray->Array.push(taxProcessor(~userHasResourceAccess))->ignore
}
isConnectorsEnabled
? Section({
name: "Connectors",
icon: "nd-connectors",
showSection: true,
links: connectorLinkArray,
selectedIcon: "nd-connectors-fill",
})
: emptyComponent
}
let paymentAnalytcis = SubLevelLink({
name: "Payments",
link: `/analytics-payments`,
access: Access,
searchOptions: [("View analytics", "")],
})
let performanceMonitor = SubLevelLink({
name: "Performance",
link: `/performance-monitor`,
access: Access,
searchOptions: [("View Performance", "")],
})
let newAnalytics = SubLevelLink({
name: "Insights",
link: `/new-analytics-payment`,
access: Access,
searchOptions: [("Insights", "")],
})
let disputeAnalytics = SubLevelLink({
name: "Disputes",
link: `/analytics-disputes`,
access: Access,
searchOptions: [("View Dispute analytics", "")],
})
let refundAnalytics = SubLevelLink({
name: "Refunds",
link: `/analytics-refunds`,
access: Access,
searchOptions: [("View analytics", "")],
})
let authenticationAnalytics = SubLevelLink({
name: "Authentication",
link: `/analytics-authentication`,
access: Access,
iconTag: "betaTag",
searchOptions: [("View analytics", "")],
})
let analytics = (
isAnalyticsEnabled,
disputeAnalyticsFlag,
performanceMonitorFlag,
newAnalyticsflag,
~authenticationAnalyticsFlag,
~userHasResourceAccess,
) => {
let links = [paymentAnalytcis, refundAnalytics]
if authenticationAnalyticsFlag {
links->Array.push(authenticationAnalytics)
}
if disputeAnalyticsFlag {
links->Array.push(disputeAnalytics)
}
if newAnalyticsflag {
links->Array.push(newAnalytics)
}
if performanceMonitorFlag {
links->Array.push(performanceMonitor)
}
isAnalyticsEnabled
? Section({
name: "Analytics",
icon: "nd-analytics",
showSection: userHasResourceAccess(~resourceAccess=Analytics) === CommonAuthTypes.Access,
links,
})
: emptyComponent
}
let routing = userHasResourceAccess => {
SubLevelLink({
name: "Routing",
link: `/routing`,
access: userHasResourceAccess(~resourceAccess=Routing),
searchOptions: [
("Manage default routing configuration", "/default"),
("Create new volume based routing", "/volume"),
("Create new rule based routing", "/rule"),
("Manage smart routing", ""),
],
})
}
let payoutRouting = userHasResourceAccess => {
SubLevelLink({
name: "Payout Routing",
link: `/payoutrouting`,
access: userHasResourceAccess(~resourceAccess=Routing),
searchOptions: [
("Manage default routing configuration", "/default"),
("Create new volume based routing", "/volume"),
("Create new rule based routing", "/rule"),
("Manage smart routing", ""),
],
})
}
let threeDs = userHasResourceAccess => {
SubLevelLink({
name: "3DS Decision Manager",
link: `/3ds`,
access: userHasResourceAccess(~resourceAccess=ThreeDsDecisionManager),
searchOptions: [("Configure 3ds", "")],
})
}
let surcharge = userHasResourceAccess => {
SubLevelLink({
name: "Surcharge",
link: `/surcharge`,
access: userHasResourceAccess(~resourceAccess=SurchargeDecisionManager),
searchOptions: [("Add Surcharge", "")],
})
}
let workflow = (
isWorkflowEnabled,
isSurchargeEnabled,
~userHasResourceAccess,
~isPayoutEnabled,
~userEntity,
) => {
let routing = routing(userHasResourceAccess)
let threeDs = threeDs(userHasResourceAccess)
let payoutRouting = payoutRouting(userHasResourceAccess)
let surcharge = surcharge(userHasResourceAccess)
let defaultWorkFlow = [routing]
let isNotProfileEntity = userEntity !== #Profile
if isSurchargeEnabled && isNotProfileEntity {
defaultWorkFlow->Array.push(surcharge)->ignore
}
if isNotProfileEntity {
defaultWorkFlow->Array.push(threeDs)->ignore
}
if isPayoutEnabled {
defaultWorkFlow->Array.push(payoutRouting)->ignore
}
isWorkflowEnabled
? Section({
name: "Workflow",
icon: "nd-workflow",
showSection: true,
links: defaultWorkFlow,
selectedIcon: "nd-workflow-fill",
})
: emptyComponent
}
let userManagement = userHasResourceAccess => {
SubLevelLink({
name: "Users",
link: `/users`,
access: userHasResourceAccess(~resourceAccess=User),
searchOptions: [("View user management", "")],
})
}
let businessDetails = userHasResourceAccess => {
SubLevelLink({
name: "Business Details",
link: `/business-details`,
access: userHasResourceAccess(~resourceAccess=Account),
searchOptions: [("Configure business details", "")],
})
}
let businessProfiles = userHasResourceAccess => {
SubLevelLink({
name: "Business Profiles",
link: `/business-profiles`,
access: userHasResourceAccess(~resourceAccess=Account),
searchOptions: [("Configure business profiles", "")],
})
}
let configurePMTs = userHasResourceAccess => {
SubLevelLink({
name: "Configure PMTs",
link: `/configure-pmts`,
access: userHasResourceAccess(~resourceAccess=Connector),
searchOptions: [("Configure payment methods", "Configure country currency")],
})
}
let complianceCertificateSection = {
SubLevelLink({
name: "Compliance ",
link: `/compliance`,
access: Access,
searchOptions: [("PCI certificate", "")],
})
}
let settings = (~isConfigurePmtsEnabled, ~userHasResourceAccess, ~complianceCertificate) => {
let settingsLinkArray = [
businessDetails(userHasResourceAccess),
businessProfiles(userHasResourceAccess),
]
if isConfigurePmtsEnabled {
settingsLinkArray->Array.push(configurePMTs(userHasResourceAccess))->ignore
}
if complianceCertificate {
settingsLinkArray->Array.push(complianceCertificateSection)->ignore
}
settingsLinkArray->Array.push(userManagement(userHasResourceAccess))->ignore
Section({
name: "Settings",
icon: "nd-settings",
showSection: true,
links: settingsLinkArray,
selectedIcon: "nd-settings-fill",
})
}
let apiKeys = userHasResourceAccess => {
SubLevelLink({
name: "API Keys",
link: `/developer-api-keys`,
access: userHasResourceAccess(~resourceAccess=ApiKey),
searchOptions: [("View API Keys", "")],
})
}
let paymentSettings = userHasResourceAccess => {
SubLevelLink({
name: "Payment Settings",
link: `/payment-settings`,
access: userHasResourceAccess(~resourceAccess=Account),
searchOptions: [("View payment settings", ""), ("View webhooks", ""), ("View return url", "")],
})
}
let webhooks = userHasResourceAccess => {
SubLevelLink({
name: "Webhooks",
link: `/webhooks`,
access: userHasResourceAccess(~resourceAccess=Account),
searchOptions: [("Webhooks", ""), ("Retry webhooks", "")],
})
}
let developers = (
isDevelopersEnabled,
~isWebhooksEnabled,
~userHasResourceAccess,
~checkUserEntity,
) => {
let isProfileUser = checkUserEntity([#Profile])
let apiKeys = apiKeys(userHasResourceAccess)
let paymentSettings = paymentSettings(userHasResourceAccess)
let webhooks = webhooks(userHasResourceAccess)
let defaultDevelopersOptions = [paymentSettings]
if isWebhooksEnabled {
defaultDevelopersOptions->Array.push(webhooks)
}
if !isProfileUser {
defaultDevelopersOptions->Array.push(apiKeys)
}
isDevelopersEnabled
? Section({
name: "Developers",
icon: "nd-developers",
showSection: true,
links: defaultDevelopersOptions,
})
: emptyComponent
}
let uploadReconFiles = {
SubLevelLink({
name: "Upload Recon Files",
link: `/upload-files`,
access: Access,
searchOptions: [("Upload recon files", "")],
})
}
let runRecon = {
SubLevelLink({
name: "Run Recon",
link: `/run-recon`,
access: Access,
searchOptions: [("Run recon", "")],
})
}
let reconAnalytics = {
SubLevelLink({
name: "Analytics",
link: `/recon-analytics`,
access: Access,
searchOptions: [("Recon analytics", "")],
})
}
let reconReports = {
SubLevelLink({
name: "Reports",
link: `/reports`,
access: Access,
searchOptions: [("Recon reports", "")],
})
}
let reconConfigurator = {
SubLevelLink({
name: "Configurator",
link: `/config-settings`,
access: Access,
searchOptions: [("Recon configurator", "")],
})
}
// Commented as not needed now
// let reconFileProcessor = {
// SubLevelLink({
// name: "File Processor",
// link: `/file-processor`,
// access: Access,
// searchOptions: [("Recon file processor", "")],
// })
// }
let reconAndSettlement = (recon, isReconEnabled, checkUserEntity, userHasResourceAccess) => {
switch (recon, isReconEnabled, checkUserEntity([#Merchant, #Organization, #Tenant])) {
| (true, true, true) => {
let links = []
if userHasResourceAccess(~resourceAccess=ReconFiles) == CommonAuthTypes.Access {
links->Array.push(uploadReconFiles)
}
if userHasResourceAccess(~resourceAccess=RunRecon) == CommonAuthTypes.Access {
links->Array.push(runRecon)
}
if (
userHasResourceAccess(~resourceAccess=ReconAndSettlementAnalytics) == CommonAuthTypes.Access
) {
links->Array.push(reconAnalytics)
}
if userHasResourceAccess(~resourceAccess=ReconReports) == CommonAuthTypes.Access {
links->Array.push(reconReports)
}
if userHasResourceAccess(~resourceAccess=ReconConfig) == CommonAuthTypes.Access {
links->Array.push(reconConfigurator)
}
// Commented as not needed now
// if userHasResourceAccess(~resourceAccess=ReconFiles) == CommonAuthTypes.Access {
// links->Array.push(reconFileProcessor)
// }
Section({
name: "Recon And Settlement",
icon: "recon",
showSection: true,
links,
})
}
| (true, false, true) =>
Link({
name: "Reconciliation",
icon: isReconEnabled ? "recon" : "recon-lock",
link: `/recon`,
access: userHasResourceAccess(~resourceAccess=ReconToken),
})
| _ => emptyComponent
}
}
let useGetHsSidebarValues = (~isReconEnabled: bool) => {
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let {userHasResourceAccess} = GroupACLHooks.useUserGroupACLHook()
let {userInfo: {userEntity}, checkUserEntity} = React.useContext(UserInfoProvider.defaultContext)
let {
frm,
payOut,
recon,
default,
surcharge: isSurchargeEnabled,
isLiveMode,
threedsAuthenticator,
disputeAnalytics,
configurePmts,
complianceCertificate,
performanceMonitor: performanceMonitorFlag,
pmAuthenticationProcessor,
taxProcessor,
newAnalytics,
authenticationAnalytics,
devAltPaymentMethods,
devWebhooks,
} = featureFlagDetails
let {
useIsFeatureEnabledForMerchant,
merchantSpecificConfig,
} = MerchantSpecificConfigHook.useMerchantSpecificConfig()
let isNewAnalyticsEnable =
newAnalytics && useIsFeatureEnabledForMerchant(merchantSpecificConfig.newAnalytics)
let sidebar = [
default->home,
default->operations(~userHasResourceAccess, ~isPayoutsEnabled=payOut, ~userEntity),
default->connectors(
~isLiveMode,
~isFrmEnabled=frm,
~isPayoutsEnabled=payOut,
~isThreedsConnectorEnabled=threedsAuthenticator,
~isPMAuthenticationProcessor=pmAuthenticationProcessor,
~isTaxProcessor=taxProcessor,
~userHasResourceAccess,
),
default->analytics(
disputeAnalytics,
performanceMonitorFlag,
isNewAnalyticsEnable,
~authenticationAnalyticsFlag=authenticationAnalytics,
~userHasResourceAccess,
),
default->workflow(
isSurchargeEnabled,
~userHasResourceAccess,
~isPayoutEnabled=payOut,
~userEntity,
),
devAltPaymentMethods->alternatePaymentMethods,
recon->reconAndSettlement(isReconEnabled, checkUserEntity, userHasResourceAccess),
default->developers(~isWebhooksEnabled=devWebhooks, ~userHasResourceAccess, ~checkUserEntity),
settings(~isConfigurePmtsEnabled=configurePmts, ~userHasResourceAccess, ~complianceCertificate),
]
sidebar
}
let useGetSidebarValuesForCurrentActive = (~isReconEnabled) => {
let {activeProduct} = React.useContext(ProductSelectionProvider.defaultContext)
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let {userHasAccess, hasAnyGroupAccess} = GroupACLHooks.useUserGroupACLHook()
let {isLiveMode, devModularityV2} = featureFlagDetails
let hsSidebars = useGetHsSidebarValues(~isReconEnabled)
let defaultSidebar = [productionAccessComponent(!isLiveMode, userHasAccess, hasAnyGroupAccess)]
if devModularityV2 {
defaultSidebar->Array.pushMany([
Link({
name: "Overview",
icon: "nd-home",
link: "/v2/home",
access: Access,
selectedIcon: "nd-fill-home",
}),
CustomComponent({
component: <ProductHeaderComponent />,
}),
])
}
let sidebarValuesForProduct = switch activeProduct {
| Orchestration => hsSidebars
| Recon => ReconSidebarValues.reconSidebars
| Recovery => RevenueRecoverySidebarValues.recoverySidebars
| Vault => VaultSidebarValues.vaultSidebars
| CostObservability => HypersenseSidebarValues.hypersenseSidebars
| DynamicRouting => IntelligentRoutingSidebarValues.intelligentRoutingSidebars
}
defaultSidebar->Array.concat(sidebarValuesForProduct)
}
| 5,224 | 9,349 |
hyperswitch-control-center | src/entryPoints/FeatureFlagUtils.res | .res | type config = {
orgId: option<string>,
merchantId: option<string>,
profileId: option<string>,
}
type merchantSpecificConfig = {newAnalytics: config}
type featureFlag = {
default: bool,
testLiveToggle: bool,
email: bool,
isLiveMode: bool,
auditTrail: bool,
sampleData: bool,
frm: bool,
payOut: bool,
recon: bool,
testProcessors: bool,
feedback: bool,
generateReport: bool,
mixpanel: bool,
mixpanelToken: string,
surcharge: bool,
disputeEvidenceUpload: bool,
paypalAutomaticFlow: bool,
threedsAuthenticator: bool,
globalSearch: bool,
globalSearchFilters: bool,
disputeAnalytics: bool,
configurePmts: bool,
branding: bool,
granularity: bool,
complianceCertificate: bool,
pmAuthenticationProcessor: bool,
performanceMonitor: bool,
newAnalytics: bool,
newAnalyticsSmartRetries: bool,
newAnalyticsRefunds: bool,
newAnalyticsFilters: bool,
downTime: bool,
taxProcessor: bool,
xFeatureRoute: bool,
tenantUser: bool,
clickToPay: bool,
debitRouting: bool,
devThemeFeature: bool,
devReconv2Product: bool,
devRecoveryV2Product: bool,
devVaultV2Product: bool,
devAltPaymentMethods: bool,
devHypersenseV2Product: bool,
devModularityV2: bool,
maintainenceAlert: string,
forceCookies: bool,
authenticationAnalytics: bool,
devIntelligentRoutingV2: bool,
googlePayDecryptionFlow: bool,
devWebhooks: bool,
}
let featureFlagType = (featureFlags: JSON.t) => {
open LogicUtils
let dict = featureFlags->getDictFromJsonObject->getDictfromDict("features")
{
default: dict->getBool("default", true),
testLiveToggle: dict->getBool("test_live_toggle", false),
email: dict->getBool("email", false),
isLiveMode: dict->getBool("is_live_mode", false),
auditTrail: dict->getBool("audit_trail", false),
sampleData: dict->getBool("sample_data", false),
frm: dict->getBool("frm", false),
payOut: dict->getBool("payout", false),
recon: dict->getBool("recon", false),
testProcessors: dict->getBool("test_processors", false),
clickToPay: dict->getBool("dev_click_to_pay", false),
debitRouting: dict->getBool("dev_debit_routing", false),
feedback: dict->getBool("feedback", false),
generateReport: dict->getBool("generate_report", false),
mixpanel: dict->getBool("mixpanel", false),
mixpanelToken: dict->getString("mixpanel_token", ""),
surcharge: dict->getBool("surcharge", false),
disputeEvidenceUpload: dict->getBool("dispute_evidence_upload", false),
paypalAutomaticFlow: dict->getBool("paypal_automatic_flow", false),
threedsAuthenticator: dict->getBool("threeds_authenticator", false),
globalSearch: dict->getBool("global_search", false),
globalSearchFilters: dict->getBool("global_search_filters", false),
disputeAnalytics: dict->getBool("dispute_analytics", false),
configurePmts: dict->getBool("configure_pmts", false),
branding: dict->getBool("branding", false),
granularity: dict->getBool("granularity", false),
complianceCertificate: dict->getBool("compliance_certificate", false),
pmAuthenticationProcessor: dict->getBool("pm_authentication_processor", false),
performanceMonitor: dict->getBool("performance_monitor", false),
newAnalytics: dict->getBool("new_analytics", false),
newAnalyticsSmartRetries: dict->getBool("new_analytics_smart_retries", false),
newAnalyticsRefunds: dict->getBool("new_analytics_refunds", false),
newAnalyticsFilters: dict->getBool("new_analytics_filters", false),
downTime: dict->getBool("down_time", false),
taxProcessor: dict->getBool("tax_processor", false),
xFeatureRoute: dict->getBool("x_feature_route", false),
tenantUser: dict->getBool("tenant_user", false),
devThemeFeature: dict->getBool("dev_theme_feature", false),
devReconv2Product: dict->getBool("dev_recon_v2_product", false),
devRecoveryV2Product: dict->getBool("dev_recovery_v2_product", false),
devVaultV2Product: dict->getBool("dev_vault_v2_product", false),
devHypersenseV2Product: dict->getBool("dev_hypersense_v2_product", false),
maintainenceAlert: dict->getString("maintainence_alert", ""),
forceCookies: dict->getBool("force_cookies", false),
authenticationAnalytics: dict->getBool("authentication_analytics", false),
devModularityV2: dict->getBool("dev_modularity_v2", false),
devAltPaymentMethods: dict->getBool("dev_alt_payment_methods", false),
devIntelligentRoutingV2: dict->getBool("dev_intelligent_routing_v2", false),
googlePayDecryptionFlow: dict->getBool("google_pay_decryption_flow", false),
devWebhooks: dict->getBool("dev_webhooks", false),
}
}
let configMapper = dict => {
open LogicUtils
{
orgId: dict->getOptionString("org_id"),
merchantId: dict->getOptionString("merchant_id"),
profileId: dict->getOptionString("profile_id"),
}
}
let merchantSpecificConfig = (config: JSON.t) => {
open LogicUtils
let dict = config->getDictFromJsonObject
{
newAnalytics: dict->getDictfromDict("new_analytics")->configMapper,
}
}
| 1,338 | 9,350 |
hyperswitch-control-center | src/entryPoints/ProductsSidebarValues.res | .res | open SidebarTypes
let emptyComponent = CustomComponent({
component: React.null,
})
let useGetSideBarValues = () => {
let {devReconv2Product, devRecoveryV2Product} =
HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let sideBarValues = []
if devReconv2Product {
sideBarValues->Array.pushMany(ReconSidebarValues.reconSidebars)
}
if devRecoveryV2Product {
sideBarValues->Array.pushMany(RevenueRecoverySidebarValues.recoverySidebars)
}
sideBarValues
}
let useGetProductSideBarValues = (~activeProduct: ProductTypes.productTypes) => {
open ProductUtils
let {
devReconv2Product,
devRecoveryV2Product,
devVaultV2Product,
devHypersenseV2Product,
devIntelligentRoutingV2,
} =
HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let sideBarValues = [
Link({
name: Orchestration->getProductDisplayName,
icon: "orchestrator-home",
link: "/v2/home",
access: Access,
}),
]
if devReconv2Product {
sideBarValues->Array.push(
Link({
name: Recon->getProductDisplayName,
icon: "recon-home",
link: "/v2/recon",
access: Access,
}),
)
}
if devRecoveryV2Product {
sideBarValues->Array.push(
Link({
name: Recovery->getProductDisplayName,
icon: "recovery-home",
link: "/v2/recovery",
access: Access,
}),
)
}
if devVaultV2Product {
sideBarValues->Array.push(
Link({
name: Vault->getProductDisplayName,
icon: "vault-home",
link: "/v2/vault",
access: Access,
}),
)
}
if devHypersenseV2Product {
sideBarValues->Array.push(
Link({
name: CostObservability->getProductDisplayName,
icon: "nd-piggy-bank",
link: "/v2/cost-observability",
access: Access,
}),
)
}
if devIntelligentRoutingV2 {
sideBarValues->Array.push(
Link({
name: DynamicRouting->getProductDisplayName,
icon: "intelligent-routing-home",
link: "/v2/dynamic-routing",
access: Access,
}),
)
}
// Need to be refactored
let productName = activeProduct->getProductDisplayName
sideBarValues->Array.filter(topLevelItem =>
switch topLevelItem {
| Link(optionType) => optionType.name != productName
| _ => true
}
)
}
| 624 | 9,351 |
hyperswitch-control-center | src/entryPoints/ProductUtils.res | .res | open ProductTypes
let getProductVariantFromString = product => {
switch product->String.toLowerCase {
| "recon" => Recon
| "recovery" => Recovery
| "vault" => Vault
| "cost_observability" => CostObservability
| "dynamic_routing" => DynamicRouting
| _ => Orchestration
}
}
let getProductDisplayName = product =>
switch product {
| Recon => "Recon"
| Recovery => "Revenue Recovery"
| Orchestration => "Orchestrator"
| Vault => "Vault"
| CostObservability => "Cost Observability"
| DynamicRouting => "Intelligent Routing"
}
let getProductVariantFromDisplayName = product => {
switch product {
| "Recon" => Recon
| "Revenue Recovery" => Recovery
| "Orchestrator" => Orchestration
| "Vault" => Vault
| "Cost Observability" => CostObservability
| "Intelligent Routing" => DynamicRouting
| _ => Orchestration
}
}
let getProductUrl = (~productType: ProductTypes.productTypes, ~url) => {
switch productType {
| Orchestration =>
if url->String.includes("v2") {
`/dashboard/home`
} else {
url
}
| Recon => `/dashboard/v2/recon/overview`
| Recovery => `/dashboard/v2/recovery/overview`
| _ => `/dashboard/v2/${(Obj.magic(productType) :> string)->LogicUtils.toKebabCase}/home`
}
}
| 345 | 9,352 |
hyperswitch-control-center | src/entryPoints/configs/HyperSwitchDefaultConfig.res | .res | let config: UIConfig.t = {
primaryColor: "primary",
secondaryColor: "secondary",
backgroundColor: "bg-primary",
button: {
height: {
medium: "h-fit",
xSmall: "h-fit",
small: "h-fit",
},
padding: {
xSmall: "py-3 px-4",
small: "py-3 px-4",
smallPagination: "py-3 px-4 mr-1",
smallDropdown: "py-3 px-4",
medium: "py-3 px-4",
mediumPagination: "py-3 px-4 mr-1",
large: "py-3 px-4",
xSmallText: "px-1",
smallText: "px-1",
mediumText: "px-1",
largeText: "px-1",
},
border: {
borderFirstWidthClass: "border focus:border-r",
borderLastWidthClass: "border focus:border-l",
borderPrimaryOutlineBorderStyleClass: "border-1",
borderSecondaryLoadingBorderStyleClass: "border-border_gray",
borderSecondaryBorderStyleClass: "border-border_gray border-opacity-20 dark:border-jp-gray-960 dark:border-opacity-100",
},
backgroundColor: {
primaryNormal: "bg-button-primary-bg hover:bg-button-primary-hoverbg focus:outline-none",
primaryDisabled: "bg-button-primary-bg opacity-60 dark:bg-jp-gray-950 dark:bg-opacity-50 border dark:border-jp-gray-disabled_border dark:border-opacity-50",
primaryNoHover: "bg-button-primary-bg hover:bg-button-primary-hoverbg focus:outline-none dark:text-opacity-50 text-opacity-50",
primaryLoading: "bg-button-primary-bg ",
primaryOutline: "mix-blend-normal",
paginationNormal: "border-left-1 opacity-80 border-right-1 font-normal border-left-1 text-jp-gray-900 text-opacity-50 hover:text-jp-gray-900 focus:outline-none",
paginationLoading: "border-left-1 border-right-1 font-normal border-left-1 bg-jp-gray-200 dark:bg-jp-gray-800 dark:bg-opacity-10",
paginationDisabled: "border-left-1 border-right-1 font-normal border-left-1 bg-jp-gray-300 dark:bg-jp-gray-950 dark:bg-opacity-50 border dark:border-jp-gray-disabled_border dark:border-opacity-50",
paginationNoHover: "bg-white border-left-1 border-right-1 font-normal text-jp-gray-900 text-opacity-75 hover:text-jp-gray-900 dark:text-jp-gray-text_darktheme dark:text-opacity-75",
dropdownDisabled: "bg-gray-200 dark:bg-jp-gray-950 dark:bg-opacity-50 border dark:border-jp-gray-disabled_border dark:border-opacity-50",
secondaryNormal: "bg-button-secondary-bg hover:bg-button-secondary-hoverbg dark:bg-jp-gray-darkgray_background dark:text-jp-gray-text_darktheme dark:text-opacity-50 focus:outline-none",
secondaryDisabled: "bg-button-secondary-bg secondary-gradient-button focus:outline-none",
secondaryNoBorder: "hover:bg-jp-gray-lightmode_steelgray hover:bg-opacity-40 dark:bg-jp-gray-darkgray_background dark:text-jp-gray-text_darktheme dark:text-opacity-50 dark:hover:bg-jp-gray-950 focus:outline-none",
secondaryLoading: "bg-button-secondary-bg dark:bg-jp-gray-darkgray_background",
secondaryNoHover: "bg-button-secondary-bg text-opacity-50 hover:bg-button-secondary-hoverbg dark:bg-jp-gray-darkgray_background dark:text-jp-gray-text_darktheme focus:outline-none dark:text-opacity-50 ",
},
borderRadius: {
default: "rounded",
defaultPagination: "rounded-md",
},
textColor: {
primaryNormal: "text-button-primary-text",
primaryOutline: "text-button-primary-text",
primaryDisabled: "text-jp-gray-600 dark:text-jp-gray-text_darktheme dark:text-opacity-25",
secondaryNormal: "text-button-secondary-text dark:text-jp-gray-text_darktheme dark:hover:text-jp-gray-text_darktheme dark:hover:text-opacity-75",
secondaryNoBorder: "text-jp-gray-900 ",
secondaryLoading: "text-button-secondary-text dark:text-jp-gray-text_darktheme dark:text-opacity-75",
secondaryDisabled: "text-jp-gray-600 dark:text-jp-gray-text_darktheme dark:text-opacity-25",
},
},
font: {
textColor: {
primaryNormal: "text-primary",
},
},
shadow: {
shadowColor: {
primaryNormal: "focus:shadow-primary",
primaryFocused: "focus:shadow-primary",
},
},
border: {
borderColor: {
primaryNormal: "border border-primary",
primaryFocused: "focus:border-primary",
},
},
sidebarColor: {
backgroundColor: {
sidebarNormal: "bg-sidebar-primary",
sidebarSecondary: "bg-sidebar-secondary",
},
primaryTextColor: "text-sidebar-primaryTextColor",
secondaryTextColor: "text-sidebar-secondaryTextColor",
hoverColor: "hover:bg-sidebar-hoverColor",
borderColor: "border border-sidebar-borderColor",
},
}
| 1,166 | 9,353 |
hyperswitch-control-center | src/entryPoints/configs/HyperSwitchConfigTypes.res | .res | type urlThemeConfig = {
faviconUrl: option<string>,
logoUrl: option<string>,
}
type urlConfig = {
apiBaseUrl: string,
mixpanelToken: string,
sdkBaseUrl: option<string>,
agreementUrl: option<string>,
agreementVersion: option<string>,
applePayCertificateUrl: option<string>,
reconIframeUrl: option<string>,
dssCertificateUrl: option<string>,
urlThemeConfig: urlThemeConfig,
hypersenseUrl: string,
}
// Type definition for themes
type colorPalette = {
primary: string,
secondary: string,
background: string,
}
type typographyConfig = {
fontFamily: string,
fontSize: string,
headingFontSize: string,
textColor: string,
linkColor: string,
linkHoverColor: string,
}
type buttonStyleConfig = {
backgroundColor: string,
textColor: string,
hoverBackgroundColor: string,
}
type borderConfig = {
defaultRadius: string,
borderColor: string,
}
type spacingConfig = {
padding: string,
margin: string,
}
type buttonConfig = {
primary: buttonStyleConfig,
secondary: buttonStyleConfig,
}
type sidebarConfig = {
primary: string,
secondary: string,
hoverColor: string,
primaryTextColor: string,
secondaryTextColor: string,
borderColor: string,
}
type themeSettings = {
colors: colorPalette,
sidebar: sidebarConfig,
typography: typographyConfig,
buttons: buttonConfig,
borders: borderConfig,
spacing: spacingConfig,
}
type customStylesTheme = {
settings: themeSettings,
urls: urlThemeConfig,
}
| 348 | 9,354 |
hyperswitch-control-center | src/entryPoints/AuthModule/AuthProviderTypes.res | .res | type preLoginType = {
token: option<string>,
token_type: string,
email_token: option<string>,
}
type authInfo = {token: option<string>}
type authType = Auth(authInfo)
type authStatus =
| LoggedOut
| PreLogin(preLoginType)
| LoggedIn(authType)
| CheckingAuthStatus
| 75 | 9,355 |
hyperswitch-control-center | src/entryPoints/AuthModule/AuthWrapper.res | .res | module AuthHeaderWrapper = {
@react.component
let make = (~children, ~childrenStyle="") => {
open FramerMotion.Motion
open CommonAuthTypes
let {branding} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let (logoVariant, iconUrl) = switch (Window.env.urlThemeConfig.logoUrl, branding) {
| (Some(url), true) => (IconWithURL, Some(url))
| (Some(url), false) => (IconWithURL, Some(url))
| _ => (IconWithText, None)
}
<HSwitchUtils.BackgroundImageWrapper
customPageCss="flex flex-col items-center justify-center overflow-scroll">
<div
className="h-full flex flex-col items-center justify-between overflow-scoll text-grey-0 w-full mobile:w-30-rem">
<div className="flex flex-col items-center gap-6 flex-1 mt-4 mobile:my-20">
<Div layoutId="form" className="bg-white w-full text-black mobile:border rounded-lg">
<div className="px-7 py-6">
<Div layoutId="logo">
<HyperSwitchLogo logoHeight="h-8" theme={Dark} logoVariant iconUrl />
</Div>
</div>
<Div layoutId="border" className="border-b w-full" />
<div className={`p-7 ${childrenStyle}`}> {children} </div>
</Div>
<RenderIf condition={!branding}>
<Div
layoutId="footer-links"
className="justify-center text-sm mobile:text-base flex flex-col mobile:flex-row mobile:gap-3 items-center w-full max-w-xl text-center">
<CommonAuth.TermsAndCondition />
</Div>
</RenderIf>
</div>
<RenderIf condition={!branding}>
<CommonAuth.PageFooterSection />
</RenderIf>
</div>
</HSwitchUtils.BackgroundImageWrapper>
}
}
@react.component
let make = (~children) => {
open APIUtils
let getURL = useGetURL()
let url = RescriptReactRouter.useUrl()
let updateDetails = useUpdateMethod()
let {fetchAuthMethods, checkAuthMethodExists} = AuthModuleHooks.useAuthMethods()
let {authStatus, setAuthStatus, authMethods, setAuthStateToLogout} = React.useContext(
AuthInfoProvider.authStatusContext,
)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Success)
let getAuthDetails = () => {
open AuthUtils
open LogicUtils
let preLoginInfo = getPreLoginDetailsFromLocalStorage()
let loggedInInfo = getUserInfoDetailsFromLocalStorage()
if preLoginInfo.token->Option.isSome && preLoginInfo.token_type->isNonEmptyString {
setAuthStatus(PreLogin(preLoginInfo))
} else if loggedInInfo.token->Option.isSome {
setAuthStatus(LoggedIn(Auth(loggedInInfo)))
} else {
setAuthStatus(LoggedOut)
}
}
let getDetailsFromEmail = async () => {
open CommonAuthUtils
open LogicUtils
try {
let tokenFromUrl = url.search->getDictFromUrlSearchParams->Dict.get("token")
let url = getURL(~entityName=V1(USERS), ~userType=#FROM_EMAIL, ~methodType=Post)
switch tokenFromUrl {
| Some(token) => {
let response = await updateDetails(url, token->generateBodyForEmailRedirection, Post)
setAuthStatus(PreLogin(AuthUtils.getPreLoginInfo(response, ~email_token=Some(token))))
}
| None => setAuthStatus(LoggedOut)
}
} catch {
| _ => {
setAuthStatus(LoggedOut)
setScreenState(_ => Success)
}
}
}
let handleRedirectFromSSO = () => {
open AuthUtils
let info = getPreLoginDetailsFromLocalStorage()->SSOUtils.ssoDefaultValue
setAuthStatus(PreLogin(info))
}
let handleLoginWithSso = id => {
switch id {
| Some(method_id) =>
Window.Location.replace(`${Window.env.apiBaseUrl}/user/auth/url?id=${method_id}`)
| _ => ()
}
}
React.useEffect(() => {
switch url.path {
| list{"user", "login"}
| list{"register"} =>
setAuthStateToLogout()
| list{"user", "verify_email"}
| list{"user", "set_password"}
| list{"user", "accept_invite_from_email"} =>
getDetailsFromEmail()->ignore
| list{"redirect", "oidc", ..._} => handleRedirectFromSSO()
| _ => getAuthDetails()
}
None
}, [])
let getAuthMethods = async () => {
try {
setScreenState(_ => Loading)
let _ = await fetchAuthMethods()
setScreenState(_ => Success)
} catch {
| _ => setScreenState(_ => Success)
}
}
React.useEffect(() => {
if authStatus === LoggedOut {
getAuthMethods()->ignore
AuthUtils.redirectToLogin()
}
None
}, [authStatus])
let renderComponentForAuthTypes = (method: SSOTypes.authMethodResponseType) => {
let authMethodType = method.auth_method.\"type"
let authMethodName = method.auth_method.name
switch (authMethodType, authMethodName) {
| (OPEN_ID_CONNECT, #Okta) | (OPEN_ID_CONNECT, #Google) | (OPEN_ID_CONNECT, #Github) =>
<Button
text={`Continue with ${(authMethodName :> string)}`}
buttonType={PrimaryOutline}
customButtonStyle="!w-full"
onClick={_ => handleLoginWithSso(method.id)}
/>
| (_, _) => React.null
}
}
<div className="font-inter-style">
{switch authStatus {
| LoggedOut =>
<PageLoaderWrapper screenState sectionHeight="h-screen">
<AuthHeaderWrapper childrenStyle="flex flex-col gap-4">
<RenderIf condition={checkAuthMethodExists([PASSWORD, MAGIC_LINK])}>
<TwoFaAuthScreen setAuthStatus />
</RenderIf>
<RenderIf condition={checkAuthMethodExists([OPEN_ID_CONNECT])}>
<RenderIf condition={checkAuthMethodExists([PASSWORD, MAGIC_LINK])}>
{PreLoginUtils.divider}
</RenderIf>
{authMethods
->Array.mapWithIndex((authMethod, index) =>
<React.Fragment key={index->Int.toString}>
{authMethod->renderComponentForAuthTypes}
</React.Fragment>
)
->React.array}
</RenderIf>
</AuthHeaderWrapper>
</PageLoaderWrapper>
| PreLogin(_) => <DecisionScreen />
| LoggedIn(_token) => children
| CheckingAuthStatus => <PageLoaderWrapper.ScreenLoader sectionHeight="h-screen" />
}}
</div>
}
| 1,526 | 9,356 |
hyperswitch-control-center | src/entryPoints/AuthModule/UnderMaintenance.res | .res | @react.component
let make = () => {
open HeadlessUI
<>
<Transition
\"as"="span"
enter={"transition ease-out duration-300"}
enterFrom="opacity-0 translate-y-1"
enterTo="opacity-100 translate-y-0"
leave={"transition ease-in duration-300"}
leaveFrom="opacity-100 translate-y-0"
leaveTo="opacity-0 translate-y-1"
show={true}>
<div
className={`flex flex-row px-4 py-2 md:gap-8 gap-4 rounded whitespace-nowrap text-fs-13 bg-yellow-200 border-yellow-200 font-semibold justify-center`}>
<div className="flex gap-2">
<div className="flex text-gray-500 items-center">
{`Hyperswitch Control Center is under maintenance`->React.string}
</div>
</div>
</div>
</Transition>
<NoDataFound
message="Hyperswitch Control Center is under maintenance will be back in an hour"
renderType=LoadError
/>
</>
}
| 257 | 9,357 |
hyperswitch-control-center | src/entryPoints/AuthModule/AuthModuleHooks.res | .res | type fetchAuthMethods = unit => promise<unit>
type checkAuthMethodExists = array<SSOTypes.authMethodTypes> => bool
type getAuthMethod = SSOTypes.authMethodTypes => option<array<SSOTypes.authMethodResponseType>>
type isMagicLinkEnabled = unit => bool
type isPasswordEnabled = unit => bool
type isSignUpAllowed = unit => (bool, SSOTypes.authMethodTypes)
type authMethodProps = {
checkAuthMethodExists: checkAuthMethodExists,
getAuthMethod: SSOTypes.authMethodTypes => option<array<SSOTypes.authMethodResponseType>>,
fetchAuthMethods: fetchAuthMethods,
isPasswordEnabled: isPasswordEnabled,
isMagicLinkEnabled: isMagicLinkEnabled,
isSignUpAllowed: isSignUpAllowed,
}
let useAuthMethods = (): authMethodProps => {
open APIUtils
open LogicUtils
let getURL = useGetURL()
let featureFlagValues = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let fetchDetails = useGetMethod(~showErrorToast=false)
let {authMethods, setAuthMethods} = React.useContext(AuthInfoProvider.authStatusContext)
let fetchAuthMethods = React.useCallback(async () => {
try {
let authId = HyperSwitchEntryUtils.getSessionData(~key="auth_id")
let authListUrl = getURL(
~entityName=V1(USERS),
~userType=#GET_AUTH_LIST,
~methodType=Get,
~queryParamerters=Some(`auth_id=${authId}`),
)
let json = await fetchDetails(`${authListUrl}`)
let arrayFromJson = json->getArrayFromJson([])
let methods = if arrayFromJson->Array.length === 0 {
AuthUtils.defaultListOfAuth
} else {
let typedvalue = arrayFromJson->SSOUtils.getAuthVariants
typedvalue->Array.sort((item1, item2) => {
if item1.auth_method.\"type" == PASSWORD {
-1.
} else if item2.auth_method.\"type" == PASSWORD {
1.
} else {
0.
}
})
typedvalue
}
setAuthMethods(_ => methods)
} catch {
| Exn.Error(_) => setAuthMethods(_ => AuthUtils.defaultListOfAuth)
}
}, [])
let checkAuthMethodExists = React.useCallback(methods => {
authMethods->Array.some(v => {
let authMethod = v.auth_method.\"type"
methods->Array.includes(authMethod)
})
}, [authMethods])
let getAuthMethod = React.useCallback(authMethod => {
let value = authMethods->Array.filter(v => {
let method = v.auth_method.\"type"
authMethod == method
})
value->getNonEmptyArray
}, [authMethods])
let isMagicLinkEnabled = React.useCallback(() => {
let method: SSOTypes.authMethodTypes = MAGIC_LINK
featureFlagValues.email && getAuthMethod(method)->Option.isSome
}, [authMethods])
let isPasswordEnabled = React.useCallback(() => {
let method: SSOTypes.authMethodTypes = PASSWORD
featureFlagValues.email && getAuthMethod(method)->Option.isSome
}, [authMethods])
let isSignUpAllowed = React.useCallback(() => {
open SSOTypes
let magicLinkmethod = getAuthMethod(MAGIC_LINK)
let passwordmethod = getAuthMethod(PASSWORD)
let isSingUpAllowedinMagicLink = switch magicLinkmethod {
| Some(magicLinkData) => magicLinkData->Array.some(v => v.allow_signup)
| None => false
}
let isSingUpAllowedinPassword = switch passwordmethod {
| Some(passwordData) => passwordData->Array.some(v => v.allow_signup)
| None => false
}
let emailFeatureFlagEnable = featureFlagValues.email
// let isTotpFeatureDisable = featureFlagValues.totp
let isLiveMode = featureFlagValues.isLiveMode
if isLiveMode {
// Singup not allowed in Prod
(false, INVALID)
} else if isSingUpAllowedinMagicLink && emailFeatureFlagEnable {
// Singup is allowed if email feature flag and allow_signup in the magicLink method is true
(true, MAGIC_LINK)
} else if isSingUpAllowedinPassword {
// Singup is allowed if email feature flag and allow_signup in the passowrd method is true
(true, PASSWORD)
} else if emailFeatureFlagEnable {
// Singup is allowed if totp feature is disable and email feature is enabled
(true, MAGIC_LINK)
} else if !isLiveMode {
// Singup is allowed if totp feature is disable
(true, PASSWORD)
} else {
(false, INVALID)
}
}, [authMethods])
{
fetchAuthMethods,
checkAuthMethodExists,
getAuthMethod,
isMagicLinkEnabled,
isPasswordEnabled,
isSignUpAllowed,
}
}
let useNote = (authType, setAuthType) => {
open CommonAuthTypes
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let authId = HyperSwitchEntryUtils.getSessionData(~key="auth_id")
let {isMagicLinkEnabled, isPasswordEnabled} = useAuthMethods()
let getFooterLinkComponent = (~btnText, ~authType, ~path) => {
<div
onClick={_ => {
setAuthType(_ => authType)
GlobalVars.appendDashboardPath(~url=path)->RescriptReactRouter.push
}}
className={`text-sm text-center ${textColor.primaryNormal} cursor-pointer hover:underline underline-offset-2`}>
{btnText->React.string}
</div>
}
<div className="w-96">
{switch authType {
| LoginWithEmail =>
<RenderIf condition={isPasswordEnabled() && isMagicLinkEnabled()}>
{getFooterLinkComponent(
~btnText="sign in using password",
~authType=LoginWithPassword,
~path=`/login?auth_id${authId}`,
)}
</RenderIf>
| LoginWithPassword =>
<RenderIf condition={isMagicLinkEnabled()}>
{getFooterLinkComponent(
~btnText="sign in with an email",
~authType=LoginWithEmail,
~path=`/login?auth_id${authId}`,
)}
</RenderIf>
| SignUP =>
<RenderIf condition={isMagicLinkEnabled()}>
<p className="text-center text-sm">
{"We'll be emailing you a magic link for a password-free experience, you can always choose to setup a password later."->React.string}
</p>
</RenderIf>
| ForgetPassword | MagicLinkEmailSent | ForgetPasswordEmailSent | ResendVerifyEmailSent =>
<div className="w-full flex justify-center">
<div
onClick={_ => {
let backState = switch authType {
| ForgetPasswordEmailSent => ForgetPassword
| ResendVerifyEmailSent => ResendVerifyEmail
| ForgetPassword | MagicLinkEmailSent | _ => LoginWithEmail
}
setAuthType(_ => backState)
}}
className={`text-sm text-center ${textColor.primaryNormal} hover:underline underline-offset-2 cursor-pointer w-fit`}>
{"Cancel"->React.string}
</div>
</div>
| _ => React.null
}}
</div>
}
| 1,642 | 9,358 |
hyperswitch-control-center | src/entryPoints/AuthModule/UserInfoScreen.res | .res | @react.component
let make = (~onClick) => {
let (errorMessage, setErrorMessage) = React.useState(_ => "")
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let {setAuthStatus, authStatus} = React.useContext(AuthInfoProvider.authStatusContext)
let token = switch authStatus {
| PreLogin(preLoginInfo) => preLoginInfo.token
| _ => None
}
let userInfo = async () => {
open HSLocalStorage
try {
let dict = [("token", token->Option.getOr("")->JSON.Encode.string)]->Dict.fromArray
let info = AuthUtils.getAuthInfo(dict->JSON.Encode.object)
setAuthStatus(LoggedIn(Auth(info)))
removeItemFromLocalStorage(~key="PRE_LOGIN_INFO")
removeItemFromLocalStorage(~key="email_token")
removeItemFromLocalStorage(~key="code")
setScreenState(_ => PageLoaderWrapper.Success)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Verification Failed")
setErrorMessage(_ => err)
setAuthStatus(LoggedOut)
}
}
}
React.useEffect(() => {
userInfo()->ignore
None
}, [])
<PageLoaderWrapper screenState>
<EmailVerifyScreen
errorMessage onClick trasitionMessage="You will be redirecting to the dashboard.."
/>
</PageLoaderWrapper>
}
| 311 | 9,359 |
hyperswitch-control-center | src/entryPoints/AuthModule/AuthEntry.res | .res | @react.component
let make = () => {
open HyperswitchAtom
let {downTime} = featureFlagAtom->Recoil.useRecoilValueFromAtom
<>
<RenderIf condition={downTime}>
<UnderMaintenance />
</RenderIf>
<RenderIf condition={!downTime}>
<AuthInfoProvider>
<AuthWrapper>
<GlobalProvider>
<UserInfoProvider>
<ProductSelectionProvider>
<HyperSwitchApp />
</ProductSelectionProvider>
</UserInfoProvider>
</GlobalProvider>
</AuthWrapper>
</AuthInfoProvider>
</RenderIf>
</>
}
| 135 | 9,360 |
hyperswitch-control-center | src/entryPoints/AuthModule/AuthUtils.res | .res | let getAuthInfo = json => {
open LogicUtils
open AuthProviderTypes
let dict = json->JsonFlattenUtils.flattenObject(false)
let totpInfo = {
token: getString(dict, "token", "")->getNonEmptyString,
}
totpInfo
}
let storeEmailTokenTmp = emailToken => {
LocalStorage.setItem("email_token", emailToken)
}
let getEmailTmpToken = () => {
LocalStorage.getItem("email_token")->Nullable.toOption
}
let getEmailTokenValue = email_token => {
switch email_token {
| Some(str) => {
str->storeEmailTokenTmp
email_token
}
| None => getEmailTmpToken()
}
}
let getPreLoginInfo = (~email_token=None, json) => {
open LogicUtils
let dict = json->JsonFlattenUtils.flattenObject(false)
let preLoginInfo: AuthProviderTypes.preLoginType = {
token: dict->getString("token", "")->getNonEmptyString,
token_type: dict->getString("token_type", ""),
email_token: getEmailTokenValue(email_token),
}
preLoginInfo
}
let setDetailsToLocalStorage = (json, key) => {
LocalStorage.setItem(key, json->JSON.stringifyAny->Option.getOr(""))
}
let getPreLoginDetailsFromLocalStorage = () => {
open LogicUtils
let json = LocalStorage.getItem("PRE_LOGIN_INFO")->getValFromNullableValue("")->safeParse
json->getPreLoginInfo
}
let getUserInfoDetailsFromLocalStorage = () => {
open LogicUtils
let json = LocalStorage.getItem("USER_INFO")->getValFromNullableValue("")->safeParse
json->getAuthInfo
}
let defaultListOfAuth: array<SSOTypes.authMethodResponseType> = [
{
id: None,
auth_id: "defaultpasswordAuthId",
auth_method: {
\"type": PASSWORD,
name: #Password,
},
allow_signup: true,
},
{
id: None,
auth_id: "defaultmagicLinkId",
auth_method: {
\"type": MAGIC_LINK,
name: #Magic_Link,
},
allow_signup: true,
},
]
let redirectToLogin = () => {
open HyperSwitchEntryUtils
open GlobalVars
open LogicUtils
let authId = getSessionData(~key="auth_id")
let domain = getSessionData(~key="domain") // todo: setting domain in session storage shall be removed later
let urlToRedirect = switch (authId->isNonEmptyString, domain->isNonEmptyString) {
| (true, true) => `/login?auth_id=${authId}&domain=${domain}`
| (true, false) => `/login?auth_id=${authId}`
| (false, true) => `/login?domain=${domain}`
| (_, _) => `/login`
}
RescriptReactRouter.push(appendDashboardPath(~url=urlToRedirect))
}
| 639 | 9,361 |
hyperswitch-control-center | src/entryPoints/AuthModule/SSOAuth/SSOUtils.res | .res | open SSOTypes
let authMethodsNameToVariantMapper = value => {
switch value->String.toLowerCase {
| "password" => #Password
| "magic_link" => #Magic_Link
| "okta" => #Okta
| "google" => #Google
| "github" => #Github
| _ => #Password
}
}
let authMethodsTypeToVariantMapper = value => {
switch value->String.toLowerCase {
| "password" => PASSWORD
| "magic_link" => MAGIC_LINK
| "open_id_connect" => OPEN_ID_CONNECT
| _ => PASSWORD
}
}
let getTypedValueFromResponse: Dict.t<JSON.t> => SSOTypes.authMethodResponseType = dict => {
open LogicUtils
let authMethodsDict = dict->getDictfromDict("auth_method")
{
id: dict->getOptionString("id"),
auth_id: dict->getString("auth_id", ""),
auth_method: {
\"type": authMethodsDict->getString("type", "")->authMethodsTypeToVariantMapper,
name: {
let name = authMethodsDict->getOptionString("name")
switch name {
| Some(value) => value->authMethodsNameToVariantMapper
| None => authMethodsDict->getString("type", "")->authMethodsNameToVariantMapper
}
},
},
allow_signup: dict->getBool("allow_signup", false),
}
}
let getAuthVariants = auth_methods => {
open LogicUtils
auth_methods->Array.map(item => {
let dictFromJson = item->getDictFromJsonObject
dictFromJson->getTypedValueFromResponse
})
}
let ssoDefaultValue = (values: AuthProviderTypes.preLoginType): AuthProviderTypes.preLoginType => {
{
token: values.token,
token_type: "sso",
email_token: values.email_token,
}
}
| 415 | 9,362 |
hyperswitch-control-center | src/entryPoints/AuthModule/SSOAuth/SSOTypes.res | .res | type authMethodTypes = PASSWORD | MAGIC_LINK | OPEN_ID_CONNECT | INVALID
type authNameTypes = [#Magic_Link | #Password | #Okta | #Google | #Github]
type okta = {
code: option<string>,
state: option<string>,
}
type redirectmethods = [#Okta(okta) | #Google | #Github]
type ssoflowType = SSO_FROM_REDIRECT(redirectmethods) | LOADING
type authMethodType = {
\"type": authMethodTypes,
name: authNameTypes,
}
type authMethodResponseType = {
id: option<string>,
auth_id: string,
auth_method: authMethodType,
allow_signup: bool,
}
| 146 | 9,363 |
hyperswitch-control-center | src/entryPoints/AuthModule/SSOAuth/SSODecisionScreen.res | .res | module SSOFromRedirect = {
@react.component
let make = (~localSSOState) => {
open SSOTypes
open APIUtils
let updateDetails = useUpdateMethod()
let getURL = useGetURL()
let {setAuthStatus} = React.useContext(AuthInfoProvider.authStatusContext)
let signInWithSSO = async () => {
open AuthUtils
try {
let body = switch localSSOState {
| SSO_FROM_REDIRECT(#Okta(data)) => data->Identity.genericTypeToJson
| _ => Dict.make()->JSON.Encode.object
}
let ssoUrl = getURL(~entityName=V1(USERS), ~userType=#SIGN_IN_WITH_SSO, ~methodType=Post)
let response = await updateDetails(ssoUrl, body, Post)
setAuthStatus(PreLogin(getPreLoginInfo(response)))
} catch {
| _ => setAuthStatus(LoggedOut)
}
}
React.useEffect(() => {
signInWithSSO()->ignore
None
}, [])
<HSwitchUtils.BackgroundImageWrapper customPageCss="font-semibold md:text-3xl p-16">
<div className="h-full w-full flex justify-center items-center text-white opacity-90">
{"You will be redirecting to the dashboard..."->React.string}
</div>
</HSwitchUtils.BackgroundImageWrapper>
}
}
@react.component
let make = (~auth_id: option<string>) => {
open SSOTypes
let url = RescriptReactRouter.useUrl()
let path = url.path->List.toArray->Array.joinWith("/")
let (localSSOState, setLocalSSOState) = React.useState(_ => LOADING)
let oktaMethod = () => {
open LogicUtils
let dict = url.search->getDictFromUrlSearchParams
let okta = {
code: dict->Dict.get("code"),
state: dict->Dict.get("state"),
}
setLocalSSOState(_ => SSO_FROM_REDIRECT(#Okta(okta)))
}
React.useEffect(() => {
switch (url.path, auth_id) {
| (list{"redirect", "oidc", "okta"}, _) => oktaMethod()
| (_, Some(str)) => Window.Location.replace(`${Window.env.apiBaseUrl}/user/auth/url?id=${str}`)
| _ => ()
}
None
}, [path])
switch localSSOState {
| SSO_FROM_REDIRECT(_) => <SSOFromRedirect localSSOState />
| LOADING => <PageLoaderWrapper.ScreenLoader sectionHeight="h-screen" />
}
}
| 574 | 9,364 |
hyperswitch-control-center | src/entryPoints/AuthModule/ProductSelection/ProductSelectionState.res | .res | open ProductTypes
type productSelectionState =
| CreateNewMerchant
| SwitchToMerchant(OMPSwitchTypes.ompListTypes)
| SelectMerchantToSwitch(array<OMPSwitchTypes.ompListTypes>)
type productSelectProviderTypes = {
activeProduct: productTypes,
setActiveProductValue: productTypes => unit,
setCreateNewMerchant: productTypes => unit,
setSwitchToMerchant: (OMPSwitchTypes.ompListTypes, productTypes) => unit,
setSelectMerchantToSwitch: array<OMPSwitchTypes.ompListTypes> => unit,
onProductSelectClick: string => unit,
}
let defaultValueOfProductProvider = (~currentProductValue) => {
activeProduct: currentProductValue->ProductUtils.getProductVariantFromString,
setActiveProductValue: _ => (),
setCreateNewMerchant: _ => (),
setSwitchToMerchant: (_, _) => (),
setSelectMerchantToSwitch: _ => (),
onProductSelectClick: _ => (),
}
| 211 | 9,365 |
hyperswitch-control-center | src/entryPoints/AuthModule/ProductSelection/ProductSelectionProvider.res | .res | open ProductSelectionState
open ProductTypes
module SwitchMerchantBody = {
@react.component
let make = (~merchantDetails: OMPSwitchTypes.ompListTypes, ~setShowModal, ~selectedProduct) => {
let internalSwitch = OMPSwitchHooks.useInternalSwitch()
let showToast = ToastState.useShowToast()
let switchMerch = async () => {
try {
let version = UserUtils.getVersion(selectedProduct)
let _ = await internalSwitch(~expectedMerchantId=Some(merchantDetails.id), ~version)
} catch {
| _ => showToast(~message="Failed to switch merchant", ~toastType=ToastError)
}
setShowModal(_ => false)
}
React.useEffect(() => {
switchMerch()->ignore
None
}, [])
<div className="flex flex-col items-center gap-2">
<Loader />
<div className="text-xl font-semibold mb-4"> {"Switching merchant...."->React.string} </div>
</div>
}
}
module SelectMerchantBody = {
@react.component
let make = (
~setShowModal,
~merchantList: array<OMPSwitchTypes.ompListTypes>,
~selectedProduct: ProductTypes.productTypes,
) => {
open LogicUtils
let url = RescriptReactRouter.useUrl()
let internalSwitch = OMPSwitchHooks.useInternalSwitch()
let showToast = ToastState.useShowToast()
let merchantDetailsTypedValue =
HyperswitchAtom.merchantDetailsValueAtom->Recoil.useRecoilValueFromAtom
let dropDownOptions =
merchantList
->Array.filter(item => {
switch item.productType {
| Some(prodType) => prodType == selectedProduct
| None => false
}
})
->Array.map((item: OMPSwitchTypes.ompListTypes): SelectBox.dropdownOption => {
{
label: `${item.name->String.length > 0 ? item.name : item.id} - ${item.id}`,
value: item.id,
}
})
let getFirstValueForDropdown = dropDownOptions->getValueFromArray(
0,
{
label: "",
value: "",
},
)
let initialValues =
[
("merchant_selected", getFirstValueForDropdown.value->JSON.Encode.string),
]->getJsonFromArrayOfJson
let merchantName = FormRenderer.makeFieldInfo(
~label="Merchant ID",
~name="merchant_selected",
~customInput=InputFields.selectInput(
~options=dropDownOptions,
~buttonText="Select Field",
~deselectDisable=true,
~customButtonStyle="!w-full pr-4 pl-2",
~fullLength=true,
),
~isRequired=true,
)
let onSubmit = async (values, _) => {
try {
let dict = values->getDictFromJsonObject
let merchantid = dict->getString("merchant_selected", "")->String.trim
let version = UserUtils.getVersion(selectedProduct)
let _ = await internalSwitch(~expectedMerchantId=Some(merchantid), ~version)
} catch {
| _ => showToast(~message="Failed to switch merchant", ~toastType=ToastError)
}
setShowModal(_ => false)
Nullable.null
}
let validateForm = (values: JSON.t) => {
let errors = Dict.make()
let merchant_selected =
values->getDictFromJsonObject->getString("merchant_selected", "")->String.trim
if merchant_selected->isEmptyString {
Dict.set(errors, "company_name", "Merchant cannot be emoty"->JSON.Encode.string)
}
errors->JSON.Encode.object
}
<div>
<div className="pt-2 mx-4 my-2 flex justify-between">
<CardUtils.CardHeader
heading={`Merchant Selection for ${selectedProduct->ProductUtils.getProductDisplayName}`}
subHeading=""
customHeadingStyle="!text-lg font-semibold"
customSubHeadingStyle="w-full !max-w-none "
/>
<div
className="h-fit"
onClick={_ => {
let currentUrl = GlobalVars.extractModulePath(
~path=url.path,
~end=url.path->List.toArray->Array.length,
)
setShowModal(_ => false)
let productUrl = ProductUtils.getProductUrl(
~productType=merchantDetailsTypedValue.product_type,
~url=currentUrl,
)
RescriptReactRouter.replace(productUrl)
}}>
<Icon name="modal-close-icon" className="cursor-pointer text-gray-500" size=30 />
</div>
</div>
<hr />
<Form key="new-merchant-creation" onSubmit initialValues validate={validateForm}>
<div className="flex flex-col h-full w-full">
<span className="text-sm text-gray-400 font-medium mx-4 mt-4">
{"Select the appropriate Merchant from the list of ID's created for this module."->React.string}
</span>
<div className="py-4">
<FormRenderer.DesktopRow>
<FormRenderer.FieldRenderer
fieldWrapperClass="w-full"
field={merchantName}
showErrorOnChange=true
errorClass={ProdVerifyModalUtils.errorClass}
labelClass="!text-black font-medium"
/>
</FormRenderer.DesktopRow>
</div>
<div className="flex justify-end w-full p-3">
<FormRenderer.SubmitButton
text="Select Merchant" buttonSize=Small customSumbitButtonStyle="w-full mb-2"
/>
</div>
</div>
</Form>
</div>
}
}
module CreateNewMerchantBody = {
@react.component
let make = (~setShowModal, ~selectedProduct: productTypes) => {
open APIUtils
open LogicUtils
let getURL = useGetURL()
let mixpanelEvent = MixpanelHook.useSendEvent()
let updateDetails = useUpdateMethod()
let showToast = ToastState.useShowToast()
let internalSwitch = OMPSwitchHooks.useInternalSwitch()
let initialValues = React.useMemo(() => {
let dict = Dict.make()
dict->Dict.set("product_type", (Obj.magic(selectedProduct) :> string)->JSON.Encode.string)
dict->JSON.Encode.object
}, [selectedProduct])
let switchMerch = async merchantid => {
try {
let version = UserUtils.getVersion(selectedProduct)
let _ = await internalSwitch(~expectedMerchantId=Some(merchantid), ~version)
} catch {
| _ => showToast(~message="Failed to switch merchant", ~toastType=ToastError)
}
}
let onSubmit = async (values, _) => {
try {
let dict = values->getDictFromJsonObject
let trimmedData = dict->getString("company_name", "")->String.trim
Dict.set(dict, "company_name", trimmedData->JSON.Encode.string)
let res = switch selectedProduct {
| Orchestration
| DynamicRouting
| CostObservability => {
let url = getURL(~entityName=V1(USERS), ~userType=#CREATE_MERCHANT, ~methodType=Post)
await updateDetails(url, values, Post)
}
| _ => {
let url = getURL(~entityName=V2(USERS), ~userType=#CREATE_MERCHANT, ~methodType=Post)
await updateDetails(url, values, Post, ~version=V2)
}
}
mixpanelEvent(~eventName="create_new_merchant", ~metadata=values)
let merchantID = res->getDictFromJsonObject->getString("merchant_id", "")
let _ = await switchMerch(merchantID)
showToast(
~toastType=ToastSuccess,
~message="Merchant Created Successfully!",
~autoClose=true,
)
} catch {
| _ => showToast(~toastType=ToastError, ~message="Merchant Creation Failed", ~autoClose=true)
}
setShowModal(_ => false)
Nullable.null
}
let merchantName = FormRenderer.makeFieldInfo(
~label="Merchant Name",
~name="company_name",
~customInput=(~input, ~placeholder as _) =>
InputFields.textInput()(
~input={
...input,
onChange: event =>
ReactEvent.Form.target(event)["value"]
->String.trimStart
->Identity.stringToFormReactEvent
->input.onChange,
},
~placeholder="Eg: My New Merchant",
),
~isRequired=true,
)
let validateForm = (values: JSON.t) => {
let errors = Dict.make()
let companyName = values->getDictFromJsonObject->getString("company_name", "")->String.trim
let regexForCompanyName = "^([a-z]|[A-Z]|[0-9]|_|\\s)+$"
let errorMessage = if companyName->isEmptyString {
"Merchant name cannot be empty"
} else if companyName->String.length > 64 {
"Merchant name cannot exceed 64 characters"
} else if !RegExp.test(RegExp.fromString(regexForCompanyName), companyName) {
"Merchant name should not contain special characters"
} else {
""
}
if errorMessage->isNonEmptyString {
Dict.set(errors, "company_name", errorMessage->JSON.Encode.string)
}
errors->JSON.Encode.object
}
<div className="">
<div className="pt-3 m-3 flex justify-between">
<CardUtils.CardHeader
heading="Add a new merchant"
subHeading=""
customSubHeadingStyle="w-full !max-w-none pr-10"
/>
<div className="h-fit" onClick={_ => setShowModal(_ => false)}>
<Icon name="modal-close-icon" className="cursor-pointer" size=30 />
</div>
</div>
<hr />
<Form key="new-merchant-creation" onSubmit initialValues validate={validateForm}>
<div className="flex flex-col h-full w-full">
<div className="py-10">
<FormRenderer.DesktopRow>
<FormRenderer.FieldRenderer
fieldWrapperClass="w-full"
field={merchantName}
showErrorOnChange=true
errorClass={ProdVerifyModalUtils.errorClass}
labelClass="!text-black font-medium !-ml-[0.5px]"
/>
</FormRenderer.DesktopRow>
</div>
<hr className="mt-4" />
<div className="flex justify-end w-full p-3">
<FormRenderer.SubmitButton text="Add Merchant" buttonSize=Small />
</div>
</div>
</Form>
</div>
}
}
module ModalBody = {
@react.component
let make = (~action, ~setShowModal, ~selectedProduct) => {
switch action {
| CreateNewMerchant => <CreateNewMerchantBody setShowModal selectedProduct />
| SwitchToMerchant(merchantDetails) =>
<SwitchMerchantBody merchantDetails setShowModal selectedProduct />
| SelectMerchantToSwitch(merchantDetails) =>
<SelectMerchantBody setShowModal merchantList={merchantDetails} selectedProduct />
}
}
}
module ProductExistModal = {
@react.component
let make = (~showModal, ~setShowModal, ~action, ~selectedProduct) => {
<Modal
showModal
closeOnOutsideClick=false
setShowModal
childClass="p-0"
borderBottom=true
modalClass="w-full !max-w-lg mx-auto my-auto dark:!bg-jp-gray-lightgray_background">
<ModalBody setShowModal action selectedProduct />
</Modal>
}
}
open SessionStorage
let currentProductValue =
sessionStorage.getItem("product")
->Nullable.toOption
->Option.getOr("orchestration")
let defaultContext = React.createContext(defaultValueOfProductProvider(~currentProductValue))
module Provider = {
let make = React.Context.provider(defaultContext)
}
@react.component
let make = (~children) => {
let merchantList: array<OMPSwitchTypes.ompListTypes> = Recoil.useRecoilValueFromAtom(
HyperswitchAtom.merchantListAtom,
)
let (activeProduct, setActiveProduct) = React.useState(_ =>
currentProductValue->ProductUtils.getProductVariantFromString
)
let (action, setAction) = React.useState(_ => None)
let (showModal, setShowModal) = React.useState(_ => false)
let (selectedProduct, setSelectedProduct) = React.useState(_ => None)
let setCreateNewMerchant = product => {
setShowModal(_ => true)
setAction(_ => Some(CreateNewMerchant))
setSelectedProduct(_ => Some(product))
}
let setSwitchToMerchant = (merchantDetails, product) => {
setShowModal(_ => true)
setAction(_ => Some(SwitchToMerchant(merchantDetails)))
setSelectedProduct(_ => Some(product))
}
let setSelectMerchantToSwitch = merchantList => {
setShowModal(_ => true)
setAction(_ => Some(SelectMerchantToSwitch(merchantList)))
}
let onProductSelectClick = product => {
let productVariant = product->ProductUtils.getProductVariantFromDisplayName
setSelectedProduct(_ => Some(product->ProductUtils.getProductVariantFromDisplayName))
let midsWithProductValue = merchantList->Array.filter(mid => {
mid.productType->Option.mapOr(false, productVaule => productVaule === productVariant)
})
if midsWithProductValue->Array.length == 0 {
setAction(_ => None)
} else if midsWithProductValue->Array.length == 1 {
let merchantIdToSwitch =
midsWithProductValue
->Array.get(0)
->Option.getOr({
name: "",
id: "",
productType: Orchestration,
})
setSwitchToMerchant(merchantIdToSwitch, productVariant)
} else if midsWithProductValue->Array.length > 1 {
setSelectMerchantToSwitch(midsWithProductValue)
} else {
setAction(_ => None)
}
}
let setActiveProductValue = product => {
setActiveProduct(_ => product)
}
let merchantHandle = React.useMemo(() => {
switch action {
| Some(actionVariant) =>
<ProductExistModal
showModal
setShowModal
action={actionVariant}
selectedProduct={selectedProduct->Option.getOr(Vault)}
/>
| None => React.null
}
}, (action, showModal))
<Provider
value={
setCreateNewMerchant,
setSwitchToMerchant,
setSelectMerchantToSwitch,
onProductSelectClick,
activeProduct,
setActiveProductValue,
}>
children
{merchantHandle}
</Provider>
}
| 3,180 | 9,366 |
hyperswitch-control-center | src/entryPoints/AuthModule/PreLoginModule/ListInvitationScreen.res | .res | @react.component
let make = () => {
open APIUtils
open LogicUtils
open PreLoginTypes
open HSwitchUtils
let getURL = useGetURL()
let fetchDetails = useGetMethod()
let updateDetails = useUpdateMethod()
let textHeadingClass = getTextClass((H2, Optional))
let textSubHeadingClass = getTextClass((P1, Regular))
let {setAuthStatus} = React.useContext(AuthInfoProvider.authStatusContext)
let (acceptedInvites, setAcceptedInvites) = React.useState(_ => [])
let (pendindInvites, setPendingInvites) = React.useState(_ => [])
let handleLogout = useHandleLogout()
let getListOfMerchantIds = async () => {
try {
let url = getURL(~entityName=V1(USERS), ~userType=#LIST_INVITATION, ~methodType=Get)
let listOfMerchants = await fetchDetails(url)
setPendingInvites(_ =>
listOfMerchants->getArrayDataFromJson(PreLoginUtils.itemToObjectMapper)
)
} catch {
| _ => setAuthStatus(LoggedOut)
}
}
React.useEffect(() => {
getListOfMerchantIds()->ignore
None
}, [])
let acceptInviteOnClick = ele => setAcceptedInvites(_ => [...acceptedInvites, ele])
let checkIfInvitationAccepted = (entityId, entityType: UserInfoTypes.entity) => {
acceptedInvites->Array.find(value =>
value.entityId === entityId && value.entityType === entityType
)
}
let onClickLoginToDashboard = async () => {
open AuthUtils
try {
let url = getURL(
~entityName=V1(USERS),
~userType=#ACCEPT_INVITATION_PRE_LOGIN,
~methodType=Post,
)
let body =
acceptedInvites
->Array.map(value => {
let acceptedinvite: acceptInviteRequest = {
entity_id: value.entityId,
entity_type: (value.entityType :> string)->String.toLowerCase,
}
acceptedinvite
})
->Identity.genericTypeToJson
let res = await updateDetails(url, body, Post)
setAuthStatus(PreLogin(getPreLoginInfo(res)))
} catch {
| _ => setAcceptedInvites(_ => [])
}
}
<BackgroundImageWrapper>
<div className="h-full w-full flex flex-col gap-4 items-center justify-center p-6">
<div className="bg-white h-35-rem w-200 rounded-2xl">
<div className="p-6 border-b-2">
<img alt="logo-with-text" src={`assets/Dark/hyperswitchLogoIconWithText.svg`} />
</div>
<div className="p-6 flex flex-col gap-2">
<p className={`${textHeadingClass} text-grey-900`}>
{"Hey there, welcome to Hyperswitch!"->React.string}
</p>
<p className=textSubHeadingClass>
{"Please accept the your pending invitations"->React.string}
</p>
</div>
<div className="h-[50%] overflow-auto show-scrollbar flex flex-col gap-10 p-8">
{pendindInvites
->Array.mapWithIndex((ele, index) => {
<div
key={index->string_of_int}
className="border-1 flex items-center justify-between rounded-xl">
<div className="flex items-center gap-5">
<Icon size=40 name="group-users" />
<div>
{`You've been invited to the Hyperswitch dashboard by `->React.string}
<span className="font-bold"> {{ele.entityId}->React.string} </span>
{` as `->React.string}
<span className="font-bold"> {{ele.roleId}->React.string} </span>
</div>
</div>
{switch checkIfInvitationAccepted(ele.entityId, ele.entityType) {
| Some(_) =>
<div className="flex items-center gap-1 text-green-accepted_green_800">
<Icon name="green-tick-without-background" />
{"Accepted"->React.string}
</div>
| None =>
<Button
text="Accept"
buttonType={PrimaryOutline}
customButtonStyle="!p-2"
onClick={_ => acceptInviteOnClick(ele)}
/>
}}
</div>
})
->React.array}
</div>
<div className="w-full flex items-center justify-center mt-4">
<Button
text="Login to Dashboard"
buttonType={Primary}
onClick={_ => onClickLoginToDashboard()->ignore}
buttonState={acceptedInvites->Array.length > 0 ? Normal : Disabled}
/>
</div>
</div>
<div className="text-grey-200 flex gap-2">
{"Log in with a different account?"->React.string}
<p
className="underline cursor-pointer underline-offset-2 hover:text-blue-700"
onClick={_ => handleLogout()->ignore}>
{"Click here to log out."->React.string}
</p>
</div>
</div>
</BackgroundImageWrapper>
}
| 1,151 | 9,367 |
hyperswitch-control-center | src/entryPoints/AuthModule/PreLoginModule/AcceptInviteScreen.res | .res | @react.component
let make = (~onClick) => {
open AuthProviderTypes
open APIUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let (errorMessage, setErrorMessage) = React.useState(_ => "")
let {authStatus, setAuthStatus} = React.useContext(AuthInfoProvider.authStatusContext)
let acceptInviteFromEmailWithSPT = async body => {
try {
open AuthUtils
let url = getURL(
~entityName=V1(USERS),
~methodType=Post,
~userType={#ACCEPT_INVITE_FROM_EMAIL},
)
let res = await updateDetails(url, body, Post)
setAuthStatus(PreLogin(getPreLoginInfo(res)))
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Verification Failed")
setErrorMessage(_ => err)
setAuthStatus(LoggedOut)
}
}
}
React.useEffect(() => {
open CommonAuthUtils
open TwoFaUtils
open GlobalVars
RescriptReactRouter.replace(appendDashboardPath(~url="/accept_invite_from_email"))
let emailToken = authStatus->getEmailToken
switch emailToken {
| Some(token) => token->generateBodyForEmailRedirection->acceptInviteFromEmailWithSPT->ignore
| None => setErrorMessage(_ => "Token not received")
}
None
}, [])
<EmailVerifyScreen
errorMessage
onClick
trasitionMessage="Accepting invite... You will be redirecting to the Dashboard.."
/>
}
| 351 | 9,368 |
hyperswitch-control-center | src/entryPoints/AuthModule/PreLoginModule/PreLoginTypes.res | .res | type preLoginTypes =
| AUTH_SELECT
| SSO
| MERCHANT_SELECT
| TOTP
| FORCE_SET_PASSWORD
| ACCEPT_INVITE
| VERIFY_EMAIL
| ACCEPT_INVITATION_FROM_EMAIL
| RESET_PASSWORD
| USER_INFO
| ERROR
type invitationResponseType = {
entityId: string,
entityType: UserInfoTypes.entity,
entityName: string,
roleId: string,
}
type acceptInviteRequest = {
entity_id: string,
entity_type: string,
}
| 114 | 9,369 |
hyperswitch-control-center | src/entryPoints/AuthModule/PreLoginModule/PreLoginUtils.res | .res | open PreLoginTypes
let flowTypeStrToVariantMapperForNewFlow = val => {
switch val {
// old types
| "merchant_select" => MERCHANT_SELECT
| "totp" => TOTP
// rotate password
| "force_set_password" => FORCE_SET_PASSWORD
// merchant select
| "accept_invite" => ACCEPT_INVITE
| "accept_invitation_from_email" => ACCEPT_INVITATION_FROM_EMAIL
| "verify_email" => VERIFY_EMAIL
| "reset_password" => RESET_PASSWORD
// home call
| "user_info" => USER_INFO
| "sso" => SSO
| "auth_select" => AUTH_SELECT
| _ => ERROR
}
}
let variantToStringFlowMapper = val => {
switch val {
| AUTH_SELECT => "auth_select"
| MERCHANT_SELECT => "merchant_select"
| TOTP => "totp"
| FORCE_SET_PASSWORD => "force_set_password"
| ACCEPT_INVITE => "accept_invite"
| VERIFY_EMAIL => "verify_email"
| ACCEPT_INVITATION_FROM_EMAIL => "accept_invitation_from_email"
| RESET_PASSWORD => "reset_password"
| USER_INFO => "user_info"
| SSO => "sso"
| ERROR => ""
}
}
let divider =
<div className="flex gap-2 items-center ">
<hr className="w-full" />
<p className=" text-gray-400"> {"OR"->React.string} </p>
<hr className="w-full" />
</div>
let itemToObjectMapper = dict => {
open LogicUtils
{
entityId: dict->getString("entity_id", ""),
entityType: dict->getString("entity_type", "")->UserInfoUtils.entityMapper,
entityName: dict->getString("entity_name", ""),
roleId: dict->getString("role_id", ""),
}
}
| 413 | 9,370 |
hyperswitch-control-center | src/entryPoints/AuthModule/PreLoginModule/VerifyUserFromEmail.res | .res | @react.component
let make = (~onClick) => {
open AuthProviderTypes
open APIUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let (errorMessage, setErrorMessage) = React.useState(_ => "")
let {authStatus, setAuthStatus} = React.useContext(AuthInfoProvider.authStatusContext)
let verifyEmailWithSPT = async token => {
try {
open CommonAuthUtils
open AuthUtils
let body = token->generateBodyForEmailRedirection
let url = getURL(~entityName=V1(USERS), ~methodType=Post, ~userType={#VERIFY_EMAILV2})
let res = await updateDetails(url, body, Post)
setAuthStatus(PreLogin(getPreLoginInfo(res)))
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Verification Failed")
setErrorMessage(_ => err)
setAuthStatus(LoggedOut)
}
}
}
React.useEffect(() => {
open TwoFaUtils
open GlobalVars
RescriptReactRouter.replace(appendDashboardPath(~url="/accept_invite_from_email"))
switch authStatus->getEmailToken {
| Some(token) => token->verifyEmailWithSPT->ignore
| None => setErrorMessage(_ => "Token not received")
}
None
}, [])
<EmailVerifyScreen
errorMessage onClick trasitionMessage="Verifying... You will be redirecting.."
/>
}
| 330 | 9,371 |
hyperswitch-control-center | src/entryPoints/AuthModule/PreLoginModule/AuthSelect.res | .res | @react.component
let make = (~setSelectedAuthId) => {
open FramerMotion.Motion
open CommonAuthTypes
open AuthProviderTypes
open APIUtils
let getURL = useGetURL()
let {setAuthStatus, authMethods} = React.useContext(AuthInfoProvider.authStatusContext)
let {fetchAuthMethods} = AuthModuleHooks.useAuthMethods()
let updateDetails = useUpdateMethod()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Success)
let (logoVariant, iconUrl) = switch Window.env.urlThemeConfig.logoUrl {
| Some(url) => (IconWithURL, Some(url))
| _ => (IconWithText, None)
}
let getAuthMethods = async () => {
try {
setScreenState(_ => Loading)
let _ = await fetchAuthMethods()
setScreenState(_ => Success)
} catch {
| _ => setScreenState(_ => Success)
}
}
let handleTerminateSSO = async method_id => {
open AuthUtils
open LogicUtils
try {
let body = Dict.make()
body->setOptionString("id", method_id)
let terminateURL = getURL(~entityName=V1(USERS), ~userType=#AUTH_SELECT, ~methodType=Post)
let response = await updateDetails(terminateURL, body->JSON.Encode.object, Post)
setSelectedAuthId(_ => method_id)
setAuthStatus(PreLogin(getPreLoginInfo(response)))
} catch {
| _ => setAuthStatus(LoggedOut)
}
}
React.useEffect(() => {
getAuthMethods()->ignore
None
}, [])
let renderComponentForAuthTypes = (method: SSOTypes.authMethodResponseType) => {
let authMethodType = method.auth_method.\"type"
let authMethodName = method.auth_method.name
switch (authMethodType, authMethodName) {
| (PASSWORD, #Password) =>
<Button
text="Continue with Password"
buttonType={Primary}
buttonSize={Large}
customButtonStyle="!w-full"
onClick={_ => handleTerminateSSO(method.id)->ignore}
/>
| (OPEN_ID_CONNECT, #Okta) | (OPEN_ID_CONNECT, #Google) | (OPEN_ID_CONNECT, #Github) =>
<Button
text={`Login with ${(authMethodName :> string)}`}
buttonType={PrimaryOutline}
buttonSize={Large}
customButtonStyle="!w-full"
onClick={_ => handleTerminateSSO(method.id)->ignore}
/>
| (_, _) => React.null
}
}
<PageLoaderWrapper screenState>
<HSwitchUtils.BackgroundImageWrapper
customPageCss="flex flex-col items-center overflow-scroll ">
<div
className="h-full flex flex-col items-center justify-between overflow-scoll text-grey-0 w-full mobile:w-30-rem">
<div className="flex flex-col items-center gap-6 flex-1 mt-32 w-30-rem">
<Div layoutId="form" className="bg-white w-full text-black mobile:border rounded-lg">
<div className="px-7 py-6">
<Div layoutId="logo">
<HyperSwitchLogo logoHeight="h-8" theme={Dark} logoVariant iconUrl />
</Div>
</div>
<Div layoutId="border" className="border-b w-full" />
<div className="flex flex-col gap-4 p-7">
{authMethods
->Array.mapWithIndex((authMethod, index) =>
<React.Fragment key={index->Int.toString}>
{authMethod->renderComponentForAuthTypes}
<RenderIf condition={index === 0 && authMethods->Array.length !== 2}>
{PreLoginUtils.divider}
</RenderIf>
</React.Fragment>
)
->React.array}
</div>
</Div>
</div>
</div>
</HSwitchUtils.BackgroundImageWrapper>
</PageLoaderWrapper>
}
| 880 | 9,372 |
hyperswitch-control-center | src/entryPoints/AuthModule/PreLoginModule/DecisionScreen.res | .res | @react.component
let make = () => {
let (selectedAuthId, setSelectedAuthId) = React.useState(_ => None)
let {authStatus, setAuthStatus} = React.useContext(AuthInfoProvider.authStatusContext)
let url = RescriptReactRouter.useUrl()
let pageViewEvent = MixpanelHook.usePageView()
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let flowType = switch authStatus {
| PreLogin(info) => info.token_type->PreLoginUtils.flowTypeStrToVariantMapperForNewFlow
| _ => ERROR
}
let onClickErrorPageButton = () => {
setAuthStatus(LoggedOut)
}
React.useEffect(() => {
let path = url.path->List.toArray->Array.joinWith("/")
if featureFlagDetails.mixpanel {
pageViewEvent(~path)->ignore
}
None
}, (featureFlagDetails.mixpanel, flowType))
switch flowType {
| AUTH_SELECT => <AuthSelect setSelectedAuthId />
| SSO => <SSODecisionScreen auth_id=selectedAuthId />
| MERCHANT_SELECT
| ACCEPT_INVITE =>
<ListInvitationScreen />
| TOTP => <TwoFaLanding />
| FORCE_SET_PASSWORD
| RESET_PASSWORD =>
<ResetPassword flowType />
| ACCEPT_INVITATION_FROM_EMAIL => <AcceptInviteScreen onClick=onClickErrorPageButton />
| VERIFY_EMAIL => <VerifyUserFromEmail onClick=onClickErrorPageButton />
| USER_INFO => <UserInfoScreen onClick=onClickErrorPageButton />
| ERROR => <CommonAuthError onClick=onClickErrorPageButton />
}
}
| 365 | 9,373 |
hyperswitch-control-center | src/entryPoints/AuthModule/PreLoginModule/ResetPassword.res | .res | @react.component
let make = (~flowType) => {
open APIUtils
open LogicUtils
open FramerMotion.Motion
open CommonAuthTypes
open CommonAuthUtils
open CommonAuthForm
let getURL = useGetURL()
let initialValues = Dict.make()->JSON.Encode.object
let showToast = ToastState.useShowToast()
let updateDetails = useUpdateMethod(~showErrorToast=false)
let {authStatus, setAuthStatus} = React.useContext(AuthInfoProvider.authStatusContext)
let setResetPassword = async body => {
try {
let url = getURL(~entityName=V1(USERS), ~userType=#RESET_PASSWORD, ~methodType=Post)
let _ = await updateDetails(url, body, Post)
showToast(~message=`Password Changed Successfully`, ~toastType=ToastSuccess)
setAuthStatus(LoggedOut)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to update!")
Exn.raiseError(err)
}
}
}
let rotatePassword = async password => {
try {
let url = getURL(~entityName=V1(USERS), ~userType=#ROTATE_PASSWORD, ~methodType=Post)
let body = [("password", password->JSON.Encode.string)]->getJsonFromArrayOfJson
let _ = await updateDetails(url, body, Post)
showToast(~message=`Password Changed Successfully`, ~toastType=ToastSuccess)
setAuthStatus(LoggedOut)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to update!")
Exn.raiseError(err)
}
}
}
let {branding} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let (logoVariant, iconUrl) = switch (Window.env.urlThemeConfig.logoUrl, branding) {
| (Some(url), true) => (IconWithURL, Some(url))
| (Some(url), false) => (IconWithURL, Some(url))
| _ => (IconWithText, None)
}
let confirmButtonAction = async password => {
open PreLoginTypes
open TwoFaUtils
try {
switch flowType {
| FORCE_SET_PASSWORD => await rotatePassword(password)
| _ => {
let emailToken = authStatus->getEmailToken
switch emailToken {
| Some(email_token) => {
let body = getResetpasswordBodyJson(password, email_token)
await setResetPassword(body)
}
| None => Exn.raiseError("Missing Token")
}
}
}
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to update!")
Exn.raiseError(err)
}
}
}
let onSubmit = async (values, _) => {
try {
let valuesDict = values->getDictFromJsonObject
let password = getString(valuesDict, "create_password", "")
let _ = await confirmButtonAction(password)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong")
let errorCode = err->safeParse->getDictFromJsonObject->getString("code", "")
let errorMessage = err->safeParse->getDictFromJsonObject->getString("message", "")
if errorCode->errorSubCodeMapper === UR_29 {
showToast(~message=errorMessage, ~toastType=ToastError)
} else {
showToast(~message="Password Reset Failed, Try again", ~toastType=ToastError)
setAuthStatus(LoggedOut)
}
}
}
Nullable.null
}
let headerText = switch flowType {
| FORCE_SET_PASSWORD => "Set password"
| _ => "Reset password"
}
React.useEffect(_ => {
open GlobalVars
RescriptReactRouter.replace(appendDashboardPath(~url="/reset_password"))
None
}, [])
<HSwitchUtils.BackgroundImageWrapper
customPageCss="flex flex-col items-center justify-center overflow-scroll ">
<div
className="h-full flex flex-col items-center justify-between overflow-scoll text-grey-0 w-full mobile:w-30-rem">
<div className="flex flex-col items-center justify-center gap-6 flex-1 mt-4 w-30-rem">
<Div layoutId="form" className="bg-white w-full text-black mobile:border rounded-lg">
<div className="px-7 py-6">
<Div layoutId="logo">
<HyperSwitchLogo logoHeight="h-8" theme={Dark} logoVariant iconUrl />
</Div>
</div>
<Div layoutId="border" className="border-b w-full" />
<div className="p-7">
<Form
key="auth"
initialValues
validate={values =>
TwoFaUtils.validateTotpForm(values, ["create_password", "comfirm_password"])}
onSubmit>
<div className="flex flex-col gap-6">
<h1 id="card-header" className="font-semibold text-xl md:text-2xl">
{headerText->React.string}
</h1>
<div
className="flex flex-col justify-evenly gap-5 h-full w-full !overflow-visible text-grey-600">
<ResetPasswordForm />
<div id="auth-submit-btn" className="flex flex-col gap-2">
<FormRenderer.SubmitButton
customSumbitButtonStyle="!w-full !rounded"
text="Confirm"
userInteractionRequired=true
showToolTip=false
loadingText="Loading..."
/>
</div>
</div>
</div>
</Form>
</div>
</Div>
</div>
</div>
</HSwitchUtils.BackgroundImageWrapper>
}
| 1,280 | 9,374 |
hyperswitch-control-center | src/entryPoints/AuthModule/Common/CommonAuthTypes.res | .res | type commonAuthInfo = {
token: option<string>,
merchantId: string,
name: string,
email: string,
userRole: string,
}
type authorization = NoAccess | Access
type logoVariant = Icon | Text | IconWithText | IconWithURL
type authFlow =
| LoginWithPassword
| LoginWithEmail
| SignUP
| EmailVerify
| MagicLinkVerify
| ForgetPassword
| ForgetPasswordEmailSent
| ResendVerifyEmailSent
| MagicLinkEmailSent
| ResetPassword
| ResendVerifyEmail
| LiveMode
| ActivateFromEmail
type data = {code: string, message: string, type_: string}
type subCode =
| HE_02
| UR_00
| UR_01
| UR_03
| UR_05
| UR_16
| UR_29
| UR_33
| UR_38
| UR_40
| UR_41
| UR_42
| UR_48
| UR_49
| UR_06
| UR_37
| UR_39
type modeType = TestButtonMode | LiveButtonMode
| 290 | 9,375 |
hyperswitch-control-center | src/entryPoints/AuthModule/Common/ResendBtn.res | .res | @react.component
let make = (~callBackFun) => {
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let (seconds, setSeconds) = React.useState(_ => 30)
let isDisabled = seconds > 0
let resendOTP = () => {
callBackFun()
setSeconds(_ => 30)
}
let disabledColor = isDisabled ? "text-jp-gray-700" : textColor.primaryNormal
React.useEffect(() => {
let intervalId = setInterval(() => setSeconds(p => p > 0 ? p - 1 : p), 1000)
let cleanup = () => {
clearInterval(intervalId)
}
Some(cleanup)
}, [])
<div className="flex w-full justify-center text-sm font-medium">
<div className="text-dark_black opacity-80 mr-1">
{"Didn't receive the mail?"->React.string}
</div>
<a
className={`${disabledColor} cursor-pointer text-md !hover:${disabledColor} mr-2 underline underline-offset-4`}
onClick={_ => {
if !isDisabled {
resendOTP()
}
}}>
{"Send again."->React.string}
</a>
<RenderIf condition={isDisabled}>
<div className={`${textColor.primaryNormal}`}>
{`(${mod(seconds, 60)->Int.toString}sec)`->React.string}
</div>
</RenderIf>
</div>
}
| 331 | 9,376 |
hyperswitch-control-center | src/entryPoints/AuthModule/Common/EmailVerifyScreen.res | .res | @react.component
let make = (~errorMessage, ~onClick, ~trasitionMessage) => {
if errorMessage->String.length !== 0 {
<CommonAuthError onClick />
} else {
<HSwitchUtils.BackgroundImageWrapper customPageCss="font-semibold md:text-3xl p-16">
<div className="h-full w-full flex justify-center items-center text-white opacity-90">
{trasitionMessage->React.string}
</div>
</HSwitchUtils.BackgroundImageWrapper>
}
}
| 109 | 9,377 |
hyperswitch-control-center | src/entryPoints/AuthModule/Common/CommonAuth.res | .res | module TermsAndCondition = {
@react.component
let make = () => {
<AddDataAttributes attributes=[("data-testid", "tc-text")]>
<div id="tc-text" className="text-center text-sm text-gray-300">
{"By continuing, you agree to our "->React.string}
<a
className="underline cursor-pointer"
href="https://hyperswitch.io/terms-of-services"
target="__blank">
{"Terms of Service"->React.string}
</a>
{" & "->React.string}
<a
className="underline cursor-pointer"
href="https://hyperswitch.io/privacy-policy"
target="__blank">
{"Privacy Policy"->React.string}
</a>
</div>
</AddDataAttributes>
}
}
module PageFooterSection = {
@react.component
let make = () => {
<div
className="justify-center text-base flex flex-col md:flex-row md:gap-3 items-center py-5 md:py-7">
<AddDataAttributes attributes=[("data-testid", "footer")]>
<div id="footer" className="flex items-center gap-2">
{"An open-source initiative by "->React.string}
<a href="https://juspay.in/" target="__blank">
<img alt="juspay-logo" src={`/icons/juspay-logo-dark.svg`} className="h-3" />
</a>
</div>
</AddDataAttributes>
</div>
}
}
module Header = {
@react.component
let make = (~authType, ~setAuthType, ~email) => {
open CommonAuthTypes
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let {isSignUpAllowed} = AuthModuleHooks.useAuthMethods()
let form = ReactFinalForm.useForm()
let {email: isMagicLinkEnabled} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let authId = HyperSwitchEntryUtils.getSessionData(~key="auth_id")
let headerStyle = switch authType {
| MagicLinkEmailSent
| ForgetPasswordEmailSent
| ForgetPassword
| ResendVerifyEmailSent => "flex flex-col justify-center items-center"
| _ => "flex flex-col"
}
let cardHeaderText = switch authType {
| LoginWithPassword | LoginWithEmail => "Hey there, Welcome back!"
| SignUP => "Welcome to Hyperswitch"
| MagicLinkEmailSent
| ForgetPasswordEmailSent
| ResendVerifyEmailSent => "Please check your inbox"
| ResetPassword => "Reset Password"
| ForgetPassword => "Forgot Password?"
| ResendVerifyEmail => "Resend Verify Email"
| _ => ""
}
let getNoteUI = info => {
<div className="flex-col items-center justify-center">
<div> {info->React.string} </div>
<div className="w-full flex justify-center text-center font-bold">
{email->React.string}
</div>
</div>
}
let getHeaderLink = (~prefix, ~authType, ~path, ~sufix) => {
<div className="flex text-sm items-center gap-2">
<div className="text-grey-650"> {prefix->React.string} </div>
<AddDataAttributes attributes=[("data-testid", "card-subtitle")]>
<div
onClick={_ => {
form.resetFieldState("email")
form.reset(JSON.Encode.object(Dict.make())->Nullable.make)
setAuthType(_ => authType)
GlobalVars.appendDashboardPath(~url=path)->RescriptReactRouter.push
}}
id="card-subtitle"
className={`font-semibold ${textColor.primaryNormal} cursor-pointer`}>
{sufix->React.string}
</div>
</AddDataAttributes>
</div>
}
let showInfoIcon = switch authType {
| MagicLinkEmailSent
| ForgetPassword
| ForgetPasswordEmailSent
| ResendVerifyEmailSent
| ResendVerifyEmail => true
| _ => false
}
let (signUpAllowed, _) = isSignUpAllowed()
<div className={`${headerStyle} gap-2 h-fit mb-7 w-96`}>
<RenderIf condition={showInfoIcon}>
<div className="flex justify-center my-5">
{switch authType {
| MagicLinkEmailSent | ForgetPasswordEmailSent | ResendVerifyEmailSent =>
<img alt="mail" className="w-48" src={`/assets/mail.svg`} />
| ForgetPassword =>
<img alt="password" className="w-24" src={`/assets/key-password.svg`} />
| _ => React.null
}}
</div>
</RenderIf>
<AddDataAttributes attributes=[("data-testid", "card-header")]>
<h1 id="card-header" className="font-semibold text-xl md:text-2xl">
{cardHeaderText->React.string}
</h1>
</AddDataAttributes>
{switch authType {
| LoginWithPassword | LoginWithEmail =>
<RenderIf condition={signUpAllowed}>
{getHeaderLink(
~prefix="New to Hyperswitch?",
~authType=SignUP,
~path="/register",
~sufix="Sign up",
)}
</RenderIf>
| SignUP =>
getHeaderLink(
~prefix="Already using Hyperswitch?",
~authType=isMagicLinkEnabled ? LoginWithEmail : LoginWithPassword,
~path=`/login?auth_id=${authId}`,
~sufix="Sign in",
)
| ForgetPassword =>
<div className="text-md text-center text-grey-650 w-full max-w-md">
{"Enter your email address associated with your account, and we'll send you a link to reset your password."->React.string}
</div>
| MagicLinkEmailSent => "A magic link has been sent to "->getNoteUI
| ForgetPasswordEmailSent => "A reset password link has been sent to "->getNoteUI
| ResendVerifyEmailSent => "A verify email link has been sent to "->getNoteUI
| _ => React.null
}}
</div>
}
}
| 1,385 | 9,378 |
hyperswitch-control-center | src/entryPoints/AuthModule/Common/CommonInviteScreen.res | .res | @react.component
let make = (~merchantData, ~acceptInviteOnClick, ~onClickLoginToDashboard) => {
open HSwitchUtils
open LogicUtils
let textHeadingClass = getTextClass((H2, Optional))
let textSubHeadingClass = getTextClass((P1, Regular))
let handleLogout = APIUtils.useHandleLogout()
let isAtleastOneAccept = React.useMemo(() => {
merchantData
->Array.find(ele => ele->getDictFromJsonObject->getBool("is_active", false))
->Option.getOr(JSON.Encode.null)
->getDictFromJsonObject
->getBool("is_active", false)
}, [merchantData])
<BackgroundImageWrapper>
<div className="h-full w-full flex flex-col gap-4 items-center justify-center p-6">
<div className="bg-white h-35-rem w-200 rounded-2xl">
<div className="p-6 border-b-2">
<img alt="logo-with-text" src={`assets/Dark/hyperswitchLogoIconWithText.svg`} />
</div>
<div className="p-6 flex flex-col gap-2">
<p className={`${textHeadingClass} text-grey-900`}>
{"Hey there, welcome to Hyperswitch!"->React.string}
</p>
<p className=textSubHeadingClass>
{"Please accept the your pending invitations"->React.string}
</p>
</div>
<div className="h-[50%] overflow-auto show-scrollbar">
{merchantData
->Array.mapWithIndex((ele, index) => {
let merchantId = ele->getDictFromJsonObject->getString("merchant_id", "")
let merchantName = ele->getDictFromJsonObject->getString("merchant_name", "")
let isActive = ele->getDictFromJsonObject->getBool("is_active", false)
<div
key={index->string_of_int}
className="border-1 m-6 p-5 flex items-center justify-between rounded-xl">
<div className="flex items-center gap-5">
<Icon size=40 name="group-users" />
<div>
{`You've been invited to the Hyperswitch dashboard by `->React.string}
<span className="font-bold">
{{merchantName->String.length > 0 ? merchantName : merchantId}->React.string}
</span>
</div>
</div>
<RenderIf condition={!isActive}>
<Button
text="Accept"
buttonType={PrimaryOutline}
customButtonStyle="!p-2"
onClick={_ => acceptInviteOnClick(index)}
/>
</RenderIf>
<RenderIf condition={isActive}>
<div className="flex items-center gap-1 text-green-accepted_green_800">
<Icon name="green-tick-without-background" />
{"Accepted"->React.string}
</div>
</RenderIf>
</div>
})
->React.array}
</div>
<div className="w-full flex items-center justify-center mt-4">
<Button
text="Login to Dashboard"
buttonType={Primary}
onClick={_ => onClickLoginToDashboard()->ignore}
buttonState={isAtleastOneAccept ? Normal : Disabled}
/>
</div>
</div>
<div className="text-grey-200 flex gap-2">
{"Log in with a different account?"->React.string}
<p
className="underline cursor-pointer underline-offset-2 hover:text-blue-700"
onClick={_ => handleLogout()->ignore}>
{"Click here to log out."->React.string}
</p>
</div>
</div>
</BackgroundImageWrapper>
}
| 817 | 9,379 |
hyperswitch-control-center | src/entryPoints/AuthModule/Common/CommonAuthUtils.res | .res | open CommonAuthTypes
let passwordKeyValidation = (value, key, keyVal, errors) => {
let mustHave: array<string> = []
if value->LogicUtils.isNonEmptyString && key === keyVal {
if value->String.length < 8 {
Dict.set(
errors,
key,
"Your password is not strong enough. Password size must be more than 8"->JSON.Encode.string,
)
} else {
if !RegExp.test(%re("/^(?=.*[A-Z])/"), value) {
mustHave->Array.push("uppercase")
}
if !RegExp.test(%re("/^(?=.*[a-z])/"), value) {
mustHave->Array.push("lowercase")
}
if !RegExp.test(%re("/^(?=.*[0-9])/"), value) {
mustHave->Array.push("numeric")
}
/*
Checks if the password contains one of the below special character:
['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '-', '=', '[', ']', '{', '}', ';', "'", ':', '"', '\\', '|', ',', '.', '<', '>', '/', '?', '', '~']
*/
if (
!RegExp.test(
RegExp.fromString("^(?=.*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>\\/?`~])"),
value,
)
) {
mustHave->Array.push("special")
}
if RegExp.test(%re("/\s/"), value) {
Dict.set(errors, key, `Password should not contain whitespaces.`->JSON.Encode.string)
}
if mustHave->Array.length > 0 {
Dict.set(
errors,
key,
`Your password is not strong enough. A good password must contain atleast ${mustHave->Array.joinWith(
",",
)} character`->JSON.Encode.string,
)
}
}
}
}
let confirmPasswordCheck = (value, key, confirmKey, passwordKey, valuesDict, errors) => {
if (
key === confirmKey &&
value->LogicUtils.isNonEmptyString &&
!Option.equal(Dict.get(valuesDict, passwordKey), Dict.get(valuesDict, key), (a, b) => a == b)
) {
Dict.set(errors, key, "The New password does not match!"->JSON.Encode.string)
}
}
let isValidEmail = value =>
!RegExp.test(
%re(`/^(([^<>()[\]\.,;:\s@"]+(\.[^<>()[\]\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/`),
value,
)
let getResetpasswordBodyJson = (password, token) =>
[("password", password->JSON.Encode.string), ("token", token->JSON.Encode.string)]
->Dict.fromArray
->JSON.Encode.object
let getEmailPasswordBody = (email, password, country) =>
[
("email", email->JSON.Encode.string),
("password", password->JSON.Encode.string),
("country", country->JSON.Encode.string),
]
->Dict.fromArray
->JSON.Encode.object
let getEmailBody = (email, ~country=?) => {
let fields = [("email", email->JSON.Encode.string)]
switch country {
| Some(value) => fields->Array.push(("country", value->JSON.Encode.string))->ignore
| _ => ()
}
fields->Dict.fromArray->JSON.Encode.object
}
let generateBodyForEmailRedirection = token => {
open LogicUtils
[("token", token->JSON.Encode.string)]->getJsonFromArrayOfJson
}
let errorMapper = dict => {
open LogicUtils
{
code: dict->getString("code", "UR_00"),
message: dict->getString("message", "something went wrong"),
type_: dict->getString("message", "something went wrong"),
}
}
let parseErrorMessage = errorMessage => {
let parsedValue = switch Exn.message(errorMessage) {
| Some(msg) => msg->LogicUtils.safeParse
| None => JSON.Encode.null
}
switch JSON.Classify.classify(parsedValue) {
| Object(obj) => obj->errorMapper
| String(_str) => Dict.make()->errorMapper
| _ => Dict.make()->errorMapper
}
}
let errorSubCodeMapper = (subCode: string) => {
switch subCode {
| "HE_02" => HE_02
| "UR_01" => UR_01
| "UR_03" => UR_03
| "UR_05" => UR_05
| "UR_16" => UR_16
| "UR_29" => UR_29
| "UR_33" => UR_33
| "UR_38" => UR_38
| "UR_40" => UR_40
| "UR_41" => UR_41
| "UR_42" => UR_42
| "UR_48" => UR_48
| "UR_49" => UR_49
| "UR_06" => UR_06
| "UR_37" => UR_37
| "UR_39" => UR_39
| _ => UR_00
}
}
let clearLocalStorage = () => {
LocalStorage.clear()
}
module ToggleLiveTestMode = {
open GlobalVars
open CommonAuthTypes
@react.component
let make = (~authType, ~mode, ~setMode, ~setAuthType, ~customClass="") => {
let liveButtonRedirectUrl = getHostUrlWithBasePath
let testButtonRedirectUrl = getHostUrlWithBasePath
<>
{switch authType {
| LoginWithPassword
| LoginWithEmail
| LiveMode => {
let borderStyle = "border-b-1 border-grey-600 border-opacity-50"
let selectedtStyle = "border-b-2 inline-block relative -bottom-px py-2"
let testModeStyles = mode === TestButtonMode ? selectedtStyle : ""
let liveModeStyles = mode === LiveButtonMode ? selectedtStyle : ""
<FramerMotion.Motion.Div
transition={{duration: 0.3}} layoutId="toggle" className="w-full">
<div className={`w-full p-2 ${customClass} `}>
<div className={`flex items-center ${borderStyle} gap-4`}>
<div
className={`!shadow-none text-white text-start text-fs-16 font-semibold cursor-pointer flex justify-center`}
onClick={_ => {
setMode(_ => TestButtonMode)
setAuthType(_ => LoginWithEmail)
Window.Location.replace(testButtonRedirectUrl)
}}>
<span className={`${testModeStyles}`}> {"Test Mode"->React.string} </span>
</div>
<div
className={`!shadow-none text-white text-start text-fs-16 font-semibold cursor-pointer flex justify-center`}
onClick={_ => {
setMode(_ => LiveButtonMode)
setAuthType(_ => LoginWithEmail)
Window.Location.replace(liveButtonRedirectUrl)
}}>
<span className={`${liveModeStyles}`}> {"Live Mode"->React.string} </span>
</div>
</div>
</div>
</FramerMotion.Motion.Div>
}
| _ => React.null
}}
</>
}
}
| 1,711 | 9,380 |
hyperswitch-control-center | src/entryPoints/AuthModule/Common/CommonInputFields.res | .res | let emailField = FormRenderer.makeFieldInfo(
~label="Email",
~name="email",
~placeholder="Enter your Email",
~isRequired=false,
~customInput=(~input, ~placeholder as _) =>
InputFields.textInput(~autoComplete="off")(
~input={
...input,
onChange: event =>
ReactEvent.Form.target(event)["value"]
->String.trim
->Identity.stringToFormReactEvent
->input.onChange,
},
~placeholder="Enter your Email",
),
)
let oldPasswordField = FormRenderer.makeFieldInfo(
~label="Old Password",
~name="old_password",
~placeholder="Enter your Old Password",
~type_="password",
~customInput=InputFields.passwordMatchField(
~leftIcon={
<Icon name="password-lock" size=13 />
},
),
~isRequired=false,
)
let newPasswordField = FormRenderer.makeFieldInfo(
~label="New Password",
~name="new_password",
~placeholder="Enter your New Password",
~type_="password",
~customInput=InputFields.passwordMatchField(
~leftIcon={
<Icon name="password-lock" size=13 />
},
),
~isRequired=false,
)
let confirmNewPasswordField = FormRenderer.makeFieldInfo(
~label="Confirm Password",
~name="confirm_password",
~placeholder="Re-enter your Password",
~type_="password",
~customInput=InputFields.textInput(
~type_="password",
~autoComplete="off",
~leftIcon={
<Icon name="password-lock" size=13 />
},
),
~isRequired=false,
)
let createPasswordField = FormRenderer.makeFieldInfo(
~label="Password",
~name="create_password",
~placeholder="Enter your Password",
~type_="password",
~customInput=InputFields.passwordMatchField(
~leftIcon={
<Icon name="password-lock" size=13 />
},
),
~isRequired=false,
)
let confirmPasswordField = FormRenderer.makeFieldInfo(
~label="Confirm Password",
~name="comfirm_password",
~placeholder="Re-enter your Password",
~type_="password",
~customInput=InputFields.textInput(
~type_="password",
~autoComplete="off",
~leftIcon={
<Icon name="password-lock" size=13 />
},
),
~isRequired=false,
)
let passwordField = FormRenderer.makeFieldInfo(
~label="Password",
~name="password",
~placeholder="Enter your Password",
~type_="password",
~customInput=InputFields.textInput(
~type_="password",
~autoComplete="off",
~leftIcon={
<Icon name="password-lock" size=13 />
},
),
~isRequired=false,
)
| 624 | 9,381 |
hyperswitch-control-center | src/entryPoints/AuthModule/Common/CommonAuthHooks.res | .res | let useNote = (authType, setAuthType, isMagicLinkEnabled) => {
open CommonAuthTypes
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let authId = HyperSwitchEntryUtils.getSessionData(~key="auth_id")
let getFooterLinkComponent = (~btnText, ~authType, ~path) => {
<div
onClick={_ => {
setAuthType(_ => authType)
GlobalVars.appendDashboardPath(~url=path)->RescriptReactRouter.push
}}
className={`text-sm text-center ${textColor.primaryNormal} cursor-pointer hover:underline underline-offset-2`}>
{btnText->React.string}
</div>
}
<div className="w-96">
{switch authType {
| LoginWithEmail =>
getFooterLinkComponent(
~btnText="or sign in using password",
~authType=LoginWithPassword,
~path=`/login?auth_id${authId}`,
)
| LoginWithPassword =>
<RenderIf condition={isMagicLinkEnabled}>
{getFooterLinkComponent(
~btnText="or sign in with magic link",
~authType=LoginWithEmail,
~path=`/login?auth_id${authId}`,
)}
</RenderIf>
| SignUP =>
<RenderIf condition={isMagicLinkEnabled}>
<p className="text-center text-sm">
{"We'll be emailing you a magic link for a password-free experience, you can always choose to setup a password later."->React.string}
</p>
</RenderIf>
| ForgetPassword | MagicLinkEmailSent | ForgetPasswordEmailSent | ResendVerifyEmailSent =>
<div className="w-full flex justify-center">
<div
onClick={_ => {
let backState = switch authType {
| MagicLinkEmailSent => SignUP
| ForgetPasswordEmailSent => ForgetPassword
| ResendVerifyEmailSent => ResendVerifyEmail
| ForgetPassword | _ => LoginWithPassword
}
setAuthType(_ => backState)
}}
className={`text-sm text-center ${textColor.primaryNormal} hover:underline underline-offset-2 cursor-pointer w-fit`}>
{"Cancel"->React.string}
</div>
</div>
| _ => React.null
}}
</div>
}
let defaultAuthInfo: CommonAuthTypes.commonAuthInfo = {
token: None,
merchantId: "",
name: "",
email: "",
userRole: "",
}
let useCommonAuthInfo = () => {
let {authStatus} = React.useContext(AuthInfoProvider.authStatusContext)
let {userInfo: {merchantId, roleId, name, email}} = React.useContext(
UserInfoProvider.defaultContext,
)
let authInfo: option<CommonAuthTypes.commonAuthInfo> = switch authStatus {
| LoggedIn(info) =>
switch info {
| Auth({token}) =>
Some({
token,
merchantId,
name,
email,
userRole: roleId,
})
}
| _ => None
}
authInfo
}
| 682 | 9,382 |
hyperswitch-control-center | src/entryPoints/AuthModule/Common/CommonAuthForm.res | .res | let fieldWrapperClass = "w-full flex flex-col"
let labelClass = "!text-black !font-medium"
module EmailPasswordForm = {
@react.component
let make = (~setAuthType) => {
open CommonInputFields
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let {email} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
<div className="flex flex-col gap-3">
<FormRenderer.FieldRenderer field=emailField labelClass fieldWrapperClass />
<div className="flex flex-col gap-3">
<FormRenderer.FieldRenderer field=passwordField labelClass fieldWrapperClass />
<RenderIf condition={email}>
<AddDataAttributes attributes=[("data-testid", "forgot-password")]>
<label
className={`not-italic text-[12px] font-semibold font-ibm-plex ${textColor.primaryNormal} cursor-pointer w-fit`}
onClick={_ => setAuthType(_ => CommonAuthTypes.ForgetPassword)}>
{"Forgot Password?"->React.string}
</label>
</AddDataAttributes>
</RenderIf>
</div>
</div>
}
}
module EmailForm = {
@react.component
let make = () => {
open CommonInputFields
<FormRenderer.FieldRenderer field=emailField labelClass fieldWrapperClass />
}
}
module ResetPasswordForm = {
@react.component
let make = () => {
open CommonInputFields
<>
<FormRenderer.FieldRenderer field=createPasswordField labelClass fieldWrapperClass />
<FormRenderer.FieldRenderer field=confirmPasswordField labelClass fieldWrapperClass />
</>
}
}
module ChangePasswordForm = {
@react.component
let make = () => {
open CommonInputFields
<>
<FormRenderer.FieldRenderer field=oldPasswordField labelClass fieldWrapperClass />
<FormRenderer.FieldRenderer field=newPasswordField labelClass fieldWrapperClass />
<FormRenderer.FieldRenderer field=confirmNewPasswordField labelClass fieldWrapperClass />
</>
}
}
| 444 | 9,383 |
hyperswitch-control-center | src/entryPoints/AuthModule/Common/CommonAuthError.res | .res | @react.component
let make = (~onClick) => {
<HSwitchUtils.BackgroundImageWrapper customPageCss="font-semibold md:text-3xl p-16">
<div className="flex flex-col justify-between gap-32 flex items-center justify-center h-2/3">
<Icon
name="hyperswitch-text-icon"
size=40
className="cursor-pointer w-60"
parentClass="flex flex-col justify-center items-center bg-white"
/>
<div className="flex flex-col justify-between items-center gap-12 ">
<img alt="work-in-progress" src={`/assets/WorkInProgress.svg`} />
<div
className={`leading-4 ml-1 mt-2 text-center flex items-center flex-col gap-6 w-full md:w-133 flex-wrap`}>
<div className="flex gap-2.5 items-center">
<Icon name="exclamation-circle" size=22 className="fill-red-500 mr-1.5" />
<p className="text-fs-20 font-bold text-white">
{React.string("Invalid Link or session expired")}
</p>
</div>
<p className="text-fs-14 text-white opacity-60 font-semibold ">
{"It appears that the link you were trying to access has expired or is no longer valid. Please try again ."->React.string}
</p>
</div>
<Button
text="Go back to login"
buttonType={Primary}
buttonSize={Small}
customButtonStyle="cursor-pointer cursor-pointer w-5 rounded-md"
onClick={_ => onClick()}
/>
</div>
</div>
</HSwitchUtils.BackgroundImageWrapper>
}
| 376 | 9,384 |
hyperswitch-control-center | src/entryPoints/AuthModule/UserInfo/UserInfoProvider.res | .res | let defaultContext = React.createContext(UserInfoUtils.defaultValueOfUserInfoProvider)
module Provider = {
let make = React.Context.provider(defaultContext)
}
type userInfoScreenState = Loading | Success | Error
@react.component
let make = (~children) => {
let (screenState, setScreenState) = React.useState(_ => Loading)
let (userInfo, setUserInfo) = React.useState(_ => UserInfoUtils.defaultValueOfUserInfo)
let fetchApi = AuthHooks.useApiFetcher()
let {xFeatureRoute, forceCookies} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let getUserInfo = async () => {
open LogicUtils
let url = `${Window.env.apiBaseUrl}/user`
try {
let res = await fetchApi(`${url}`, ~method_=Get, ~xFeatureRoute, ~forceCookies)
let response = await res->(res => res->Fetch.Response.json)
let userInfo = response->getDictFromJsonObject->UserInfoUtils.itemMapper
setUserInfo(_ => userInfo)
setScreenState(_ => Success)
} catch {
| _ => setScreenState(_ => Error)
}
}
let setUserInfoData = userData => {
setUserInfo(_ => userData)
}
let getUserInfoData = () => {
userInfo
}
let checkUserEntity = (entities: array<UserInfoTypes.entity>) => {
entities->Array.includes(userInfo.userEntity)
}
React.useEffect(() => {
getUserInfo()->ignore
None
}, [])
<Provider
value={
userInfo,
setUserInfoData,
getUserInfoData,
checkUserEntity,
}>
<RenderIf condition={screenState === Success}> children </RenderIf>
<RenderIf condition={screenState === Error}>
<NoDataFound message="Something went wrong" renderType=Painting />
</RenderIf>
</Provider>
}
| 403 | 9,385 |
hyperswitch-control-center | src/entryPoints/AuthModule/UserInfo/UserInfoTypes.res | .res | type entity = [#Tenant | #Organization | #Merchant | #Profile]
type version = V1 | V2
type userInfo = {
email: string,
isTwoFactorAuthSetup: bool,
merchantId: string,
name: string,
orgId: string,
recoveryCodesLeft: option<int>,
roleId: string,
verificationDaysLeft: option<int>,
profileId: string,
userEntity: entity,
themeId: string,
mutable transactionEntity: entity,
mutable analyticsEntity: entity,
version: version,
}
type userInfoProviderTypes = {
userInfo: userInfo,
setUserInfoData: userInfo => unit,
getUserInfoData: unit => userInfo,
checkUserEntity: array<entity> => bool,
}
| 160 | 9,386 |
hyperswitch-control-center | src/entryPoints/AuthModule/UserInfo/UserInfoUtils.res | .res | open UserInfoTypes
let defaultValueOfUserInfo = {
email: "",
isTwoFactorAuthSetup: false,
merchantId: "",
name: "",
orgId: "",
recoveryCodesLeft: None,
roleId: "",
verificationDaysLeft: None,
profileId: "",
userEntity: #Merchant,
transactionEntity: #Merchant,
analyticsEntity: #Merchant,
themeId: "",
version: V1,
}
let entityMapper = entity => {
switch entity->String.toLowerCase {
| "tenant" => #Tenant
| "organization" => #Organization
| "merchant" => #Merchant
| "profile" => #Profile
| _ => #Merchant
}
}
let transactionEntityMapper = entity => {
switch entity->String.toLowerCase {
| "merchant" => #Merchant
| "profile" => #Profile
| _ => #Merchant
}
}
let analyticsEntityMapper = entity => {
switch entity->String.toLowerCase {
| "tenant"
| "organization" =>
#Organization
| "merchant" => #Merchant
| "profile" => #Profile
| _ => #Merchant
}
}
let versionMapper = version =>
switch version->String.toLowerCase {
| "v2" => V2
| _ => V1
}
let defaultValueOfUserInfoProvider = {
userInfo: defaultValueOfUserInfo,
setUserInfoData: _ => (),
getUserInfoData: _ => defaultValueOfUserInfo,
checkUserEntity: _ => false,
}
open LogicUtils
let itemMapper = dict => {
email: dict->getString("email", defaultValueOfUserInfo.email),
isTwoFactorAuthSetup: dict->getBool(
"is_two_factor_auth_setup",
defaultValueOfUserInfo.isTwoFactorAuthSetup,
),
merchantId: dict->getString("merchant_id", defaultValueOfUserInfo.merchantId),
name: dict->getString("name", defaultValueOfUserInfo.name),
orgId: dict->getString("org_id", defaultValueOfUserInfo.orgId),
recoveryCodesLeft: dict->getOptionInt("recovery_codes_left"),
roleId: dict->getString("role_id", defaultValueOfUserInfo.roleId),
verificationDaysLeft: dict->getOptionInt("verification_days_left"),
profileId: dict->getString("profile_id", ""),
userEntity: dict->getString("entity_type", "")->entityMapper,
analyticsEntity: dict->getString("entity_type", "")->analyticsEntityMapper,
transactionEntity: dict->getString("entity_type", "")->transactionEntityMapper,
themeId: dict->getString("theme_id", ""),
version: dict->getString("version", "v1")->versionMapper,
}
| 571 | 9,387 |
hyperswitch-control-center | src/entryPoints/AuthModule/TwoFaAuth/OtpInput.res | .res | @send
external focus: (Dom.element, unit) => unit = "focus"
module InputFieldForOtp = {
@react.component
let make = (~inputRef, ~value, ~index, ~handleChange, ~handleFocus) => {
let inputClass = `text-center h-full w-full border border-jp-2-light-gray-600 rounded-lg outline-none focus:border-primary focus:shadow-focusBoxShadow text-2xl overflow-hidden`
let onChange = ev => {
let currValue = {ev->ReactEvent.Form.target}["value"]
if %re("/^[0-9]+$/")->RegExp.test(currValue) || currValue === "" {
let newValue =
value->String.slice(~start=0, ~end=index) ++
currValue ++
value->String.sliceToEnd(~start=index + 1)
handleChange(newValue)
}
}
let subVal = value->String.slice(~start=index, ~end=index + 1)
let handleKeyDown = ev => {
let key = ev->ReactEvent.Keyboard.keyCode
if key === 8 || key === 46 {
if value->String.length === index {
handleChange(value->String.slice(~start=0, ~end=index - 1))
}
}
}
<input
key={index->Int.toString}
ref={inputRef->ReactDOM.Ref.domRef}
value={subVal}
className=inputClass
onChange
onFocus={handleFocus}
onKeyDown={handleKeyDown}
autoComplete="off"
/>
}
}
@react.component
let make = (~value, ~setValue) => {
let input1Ref = React.useRef(Nullable.null)
let input2Ref = React.useRef(Nullable.null)
let input3Ref = React.useRef(Nullable.null)
let input4Ref = React.useRef(Nullable.null)
let input5Ref = React.useRef(Nullable.null)
let input6Ref = React.useRef(Nullable.null)
let inputRefArray = [input1Ref, input2Ref, input3Ref, input4Ref, input5Ref, input6Ref]
let handleChange = str => {
setValue(_ => str->String.slice(~start=0, ~end=6))
}
let handleFocus = _val => {
let indexToFocus = Math.Int.min(5, value->String.length)
let elementToFocus = (inputRefArray[indexToFocus]->Option.getOr(input1Ref)).current
switch elementToFocus->Nullable.toOption {
| Some(elem) => elem->focus()
| None => ()
}
}
React.useEffect(() => {
let indexToFocus = Math.Int.min(5, value->String.length)
let elementToFocus = (inputRefArray[indexToFocus]->Option.getOr(input1Ref)).current
switch elementToFocus->Nullable.toOption {
| Some(elem) => elem->focus()
| None => ()
}
None
}, [value->String.length])
<div className="flex justify-center relative ">
{inputRefArray
->Array.mapWithIndex((ref, index) =>
<div className="w-16 h-16" key={index->Int.toString}>
<InputFieldForOtp inputRef={ref} value handleChange index handleFocus />
</div>
)
->React.array}
</div>
}
| 729 | 9,388 |
hyperswitch-control-center | src/entryPoints/AuthModule/TwoFaAuth/TotpRecoveryCodes.res | .res | let h2TextStyle = HSwitchUtils.getTextClass((H2, Optional))
@react.component
let make = (~setTwoFaPageState, ~onClickDownload, ~setShowNewQR) => {
let showToast = ToastState.useShowToast()
let getURL = APIUtils.useGetURL()
let fetchDetails = APIUtils.useGetMethod()
let (recoveryCodes, setRecoveryCodes) = React.useState(_ => [])
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Success)
let generateRecoveryCodes = async () => {
open LogicUtils
try {
setScreenState(_ => PageLoaderWrapper.Loading)
let url = getURL(~entityName=V1(USERS), ~userType=#GENERATE_RECOVERY_CODES, ~methodType=Get)
let response = await fetchDetails(url)
let recoveryCodesValue = response->getDictFromJsonObject->getStrArray("recovery_codes")
setRecoveryCodes(_ => recoveryCodesValue)
setScreenState(_ => PageLoaderWrapper.Success)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong")
let errorCode = err->safeParse->getDictFromJsonObject->getString("code", "")
if errorCode->CommonAuthUtils.errorSubCodeMapper === UR_38 {
setTwoFaPageState(_ => TwoFaTypes.TOTP_SHOW_QR)
setShowNewQR(prev => !prev)
} else {
showToast(~message="Something went wrong", ~toastType=ToastError)
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
}
}
let copyRecoveryCodes = ev => {
open LogicUtils
ev->ReactEvent.Mouse.stopPropagation
Clipboard.writeText(JSON.stringifyWithIndent(recoveryCodes->getJsonFromArrayOfString, 3))
showToast(~message="Copied to Clipboard!", ~toastType=ToastSuccess)
}
React.useEffect(() => {
generateRecoveryCodes()->ignore
None
}, [])
<PageLoaderWrapper screenState>
<div className={`bg-white h-40-rem w-133 rounded-2xl flex flex-col`}>
<div className="p-6 border-b-2 flex justify-between items-center">
<p className={`${h2TextStyle} text-grey-900`}>
{"Two factor recovery codes"->React.string}
</p>
</div>
<div className="px-8 py-8 flex flex-col flex-1 justify-between">
<div className="flex flex-col gap-6">
<p className="text-jp-gray-700">
{"Recovery codes provide a way to access your account if you lose your device and can't receive two-factor authentication codes."->React.string}
</p>
<HSwitchUtils.AlertBanner
bannerText="These codes are the last resort for accessing your account in case you lose your password and second factors. If you cannot find these codes, you will lose access to your account."
bannerType=Warning
/>
<TwoFaElements.ShowRecoveryCodes recoveryCodes />
</div>
<div className="flex gap-4 justify-end">
<Button
leftIcon={CustomIcon(<Icon name="nd-copy" className="cursor-pointer" />)}
text={"Copy"}
buttonType={Secondary}
buttonSize={Small}
onClick={copyRecoveryCodes}
/>
<Button
leftIcon={FontAwesome("download-api-key")}
text={"Download"}
buttonType={Primary}
buttonSize={Small}
onClick={_ => {
TwoFaUtils.downloadRecoveryCodes(~recoveryCodes)
onClickDownload(~skip_2fa=false)->ignore
}}
/>
</div>
</div>
</div>
</PageLoaderWrapper>
}
| 827 | 9,389 |
hyperswitch-control-center | src/entryPoints/AuthModule/TwoFaAuth/TotpSetup.res | .res | let h2TextStyle = HSwitchUtils.getTextClass((H2, Optional))
let p2Regular = HSwitchUtils.getTextClass((P2, Regular))
let p3Regular = HSwitchUtils.getTextClass((P3, Regular))
module EnterAccessCode = {
@react.component
let make = (
~setTwoFaPageState,
~onClickVerifyAccessCode,
~errorHandling,
~isSkippable,
~showOnlyRc=false,
) => {
let showToast = ToastState.useShowToast()
let verifyRecoveryCodeLogic = TotpHooks.useVerifyRecoveryCode()
let (recoveryCode, setRecoveryCode) = React.useState(_ => "")
let (buttonState, setButtonState) = React.useState(_ => Button.Normal)
let verifyAccessCode = async _ => {
open LogicUtils
try {
setButtonState(_ => Button.Loading)
if recoveryCode->String.length > 0 {
let body = [("recovery_code", recoveryCode->JSON.Encode.string)]->getJsonFromArrayOfJson
let _ = await verifyRecoveryCodeLogic(body)
onClickVerifyAccessCode(~skip_2fa=false)->ignore
} else {
showToast(~message="Recovery code cannot be empty!", ~toastType=ToastError)
}
setButtonState(_ => Button.Normal)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong")
let errorCode = err->safeParse->getDictFromJsonObject->getString("code", "")
let errorMessage = err->safeParse->getDictFromJsonObject->getString("message", "")
if errorCode->CommonAuthUtils.errorSubCodeMapper == UR_49 {
errorHandling()
}
if errorCode->CommonAuthUtils.errorSubCodeMapper == UR_39 {
showToast(~message=errorMessage, ~toastType=ToastError)
}
setRecoveryCode(_ => "")
setButtonState(_ => Button.Normal)
}
}
}
let handleKeyUp = ev => {
open ReactEvent.Keyboard
let key = ev->key
let keyCode = ev->keyCode
if key === "Enter" || keyCode === 13 {
verifyAccessCode()->ignore
}
}
React.useEffect(() => {
if recoveryCode->String.length == 9 {
Window.addEventListener("keyup", handleKeyUp)
} else {
Window.removeEventListener("keyup", handleKeyUp)
}
Some(
() => {
Window.removeEventListener("keyup", handleKeyUp)
},
)
}, [recoveryCode])
<div className={`bg-white h-20-rem w-200 rounded-2xl flex flex-col`}>
<div className="p-6 border-b-2 flex justify-between items-center">
<p className={`${h2TextStyle} text-grey-900`}> {"Enter access code"->React.string} </p>
</div>
<div className="px-12 py-8 flex flex-col gap-12 justify-between flex-1">
<div className="flex flex-col justify-center items-center gap-4">
<TwoFaElements.RecoveryCodesInput recoveryCode setRecoveryCode />
<RenderIf condition={!showOnlyRc}>
<p className={`${p2Regular} text-jp-gray-700`}>
{"Didn't get a code? "->React.string}
<span
className="cursor-pointer underline underline-offset-2 text-blue-600"
onClick={_ => setTwoFaPageState(_ => TwoFaTypes.TOTP_SHOW_QR)}>
{"Use totp instead"->React.string}
</span>
</p>
</RenderIf>
</div>
<div className="flex justify-end gap-4">
<RenderIf condition={isSkippable}>
<Button
text="Skip now"
buttonType={Secondary}
buttonSize=Small
onClick={_ => onClickVerifyAccessCode(~skip_2fa=true)->ignore}
dataTestId="skip-now"
/>
</RenderIf>
<Button
text="Verify recovery code"
buttonType=Primary
buttonSize=Small
buttonState={recoveryCode->String.length < 9 ? Disabled : buttonState}
customButtonStyle="group"
rightIcon={CustomIcon(
<Icon
name="thin-right-arrow" size=20 className="group-hover:scale-125 cursor-pointer"
/>,
)}
onClick={_ => verifyAccessCode()->ignore}
/>
</div>
</div>
</div>
}
}
module ConfigureTotpScreen = {
@react.component
let make = (
~isQrVisible,
~totpUrl,
~twoFaStatus,
~setTwoFaPageState,
~terminateTwoFactorAuth,
~errorHandling,
~isSkippable,
~showOnlyTotp=false,
) => {
open TwoFaTypes
let verifyTotpLogic = TotpHooks.useVerifyTotp()
let showToast = ToastState.useShowToast()
let (otp, setOtp) = React.useState(_ => "")
let (buttonState, setButtonState) = React.useState(_ => Button.Normal)
let verifyTOTP = async () => {
open LogicUtils
try {
setButtonState(_ => Button.Loading)
if otp->String.length > 0 {
let body = [("totp", otp->JSON.Encode.string)]->getJsonFromArrayOfJson
let methodType: Fetch.requestMethod = twoFaStatus === TWO_FA_SET ? Post : Put
let _ = await verifyTotpLogic(body, methodType)
if twoFaStatus === TWO_FA_SET {
terminateTwoFactorAuth(~skip_2fa=false)->ignore
} else {
setTwoFaPageState(_ => TwoFaTypes.TOTP_SHOW_RC)
}
} else {
showToast(~message="OTP field cannot be empty!", ~toastType=ToastError)
}
setButtonState(_ => Button.Normal)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong")
let errorCode = err->safeParse->getDictFromJsonObject->getString("code", "")
let errorMessage = err->safeParse->getDictFromJsonObject->getString("message", "")
if errorCode->CommonAuthUtils.errorSubCodeMapper == UR_48 {
errorHandling()
}
if errorCode->CommonAuthUtils.errorSubCodeMapper == UR_37 {
showToast(~message=errorMessage, ~toastType=ToastError)
}
setOtp(_ => "")
setButtonState(_ => Button.Normal)
}
}
}
let skipTotpSetup = async () => {
terminateTwoFactorAuth(~skip_2fa=true)->ignore
}
let buttonText = twoFaStatus === TWO_FA_SET ? "Verify OTP" : "Enable 2FA"
let modalHeaderText =
twoFaStatus === TWO_FA_SET ? "Enter TOTP Code" : "Enable Two Factor Authentication"
let handleKeyUp = ev => {
open ReactEvent.Keyboard
let key = ev->key
let keyCode = ev->keyCode
if key === "Enter" || keyCode === 13 {
verifyTOTP()->ignore
}
}
React.useEffect(() => {
if otp->String.length == 6 {
Window.addEventListener("keyup", handleKeyUp)
} else {
Window.removeEventListener("keyup", handleKeyUp)
}
Some(
() => {
Window.removeEventListener("keyup", handleKeyUp)
},
)
}, [otp])
<div
className={`bg-white ${twoFaStatus === TWO_FA_SET
? "h-20-rem"
: "h-40-rem"} w-200 rounded-2xl flex flex-col`}>
<div className="p-6 border-b-2 flex justify-between items-center">
<p className={`${h2TextStyle} text-grey-900`}> {modalHeaderText->React.string} </p>
</div>
<div className="px-12 py-8 flex flex-col gap-12 justify-between flex-1">
<RenderIf condition={twoFaStatus === TWO_FA_NOT_SET}>
<TwoFaElements.TotpScanQR totpUrl isQrVisible />
</RenderIf>
<div className="flex flex-col justify-center items-center gap-4">
<TwoFaElements.TotpInput otp setOtp />
<RenderIf condition={twoFaStatus === TWO_FA_SET && !showOnlyTotp}>
<p className={`${p2Regular} text-jp-gray-700`}>
{"Didn't get a code? "->React.string}
<span
className="cursor-pointer underline underline-offset-2 text-blue-600"
onClick={_ => setTwoFaPageState(_ => TOTP_INPUT_RECOVERY_CODE)}>
{"Use recovery-code"->React.string}
</span>
</p>
</RenderIf>
</div>
<div className="flex justify-end gap-4">
<RenderIf condition={isSkippable}>
<Button
text="Skip now"
buttonType={Secondary}
buttonSize=Small
onClick={_ => skipTotpSetup()->ignore}
dataTestId="skip-now"
/>
</RenderIf>
<Button
text=buttonText
buttonType=Primary
buttonSize=Small
customButtonStyle="group"
buttonState={otp->String.length === 6 ? buttonState : Disabled}
onClick={_ => verifyTOTP()->ignore}
rightIcon={CustomIcon(
<Icon
name="thin-right-arrow" size=20 className="group-hover:scale-125 cursor-pointer"
/>,
)}
/>
</div>
</div>
</div>
}
}
@react.component
let make = (
~setTwoFaPageState,
~twoFaPageState,
~errorHandling,
~isSkippable,
~checkTwoFaResonse: TwoFaTypes.checkTwofaResponseType,
) => {
open HSwitchUtils
open TwoFaTypes
let getURL = APIUtils.useGetURL()
let showToast = ToastState.useShowToast()
let fetchDetails = APIUtils.useGetMethod()
let handleLogout = APIUtils.useHandleLogout()
let {setAuthStatus} = React.useContext(AuthInfoProvider.authStatusContext)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (isQrVisible, setIsQrVisible) = React.useState(_ => false)
let (totpUrl, setTotpUrl) = React.useState(_ => "")
let (twoFaStatus, setTwoFaStatus) = React.useState(_ => TWO_FA_NOT_SET)
let (showNewQR, setShowNewQR) = React.useState(_ => false)
let delayTimer = () => {
let timeoutId = {
setTimeout(_ => {
setIsQrVisible(_ => true)
}, 1000)
}
Some(
() => {
clearTimeout(timeoutId)
},
)
}
let terminateTwoFactorAuth = async (~skip_2fa) => {
open LogicUtils
try {
open AuthUtils
let url = getURL(
~entityName=V1(USERS),
~userType=#TERMINATE_TWO_FACTOR_AUTH,
~methodType=Get,
~queryParamerters=Some(`skip_two_factor_auth=${skip_2fa->getStringFromBool}`),
)
let response = await fetchDetails(url)
setAuthStatus(PreLogin(getPreLoginInfo(response)))
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong")
let errorCode = err->safeParse->getDictFromJsonObject->getString("code", "")
if (
errorCode->CommonAuthUtils.errorSubCodeMapper === UR_40 ||
errorCode->CommonAuthUtils.errorSubCodeMapper === UR_41
) {
setTwoFaPageState(_ => TOTP_SHOW_QR)
showToast(~message="Failed to complete 2fa!", ~toastType=ToastError)
setShowNewQR(prev => !prev)
} else {
showToast(~message="Something went wrong", ~toastType=ToastError)
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
}
}
let getTOTPString = async () => {
open LogicUtils
try {
setTotpUrl(_ => "")
let url = getURL(~entityName=V1(USERS), ~userType=#BEGIN_TOTP, ~methodType=Get)
let response = await fetchDetails(url)
let responseDict = response->getDictFromJsonObject->getJsonObjectFromDict("secret")
switch responseDict->JSON.Classify.classify {
| Object(objectValue) => {
let otpUrl = objectValue->getString("totp_url", "")
setTotpUrl(_ => otpUrl)
}
| _ => setTwoFaStatus(_ => TWO_FA_SET)
}
setScreenState(_ => PageLoaderWrapper.Success)
// NOTE : added delay to show the QR code after loading animation
delayTimer()->ignore
} catch {
| _ => {
setScreenState(_ => PageLoaderWrapper.Error("Failed to fetch!"))
setAuthStatus(LoggedOut)
}
}
}
React.useEffect(() => {
getTOTPString()->ignore
None
}, [showNewQR])
let (showOnlyTotp, showOnlyRc) = React.useMemo1(() => {
switch checkTwoFaResonse.status {
| Some(value) =>
if value.totp.attemptsRemaining === 0 && value.recoveryCode.attemptsRemaining > 0 {
(false, true)
} else if value.recoveryCode.attemptsRemaining === 0 && value.totp.attemptsRemaining > 0 {
(true, false)
} else {
(false, false)
}
| None => (true, true)
}
}, [checkTwoFaResonse.status])
<PageLoaderWrapper screenState sectionHeight="h-screen">
<BackgroundImageWrapper>
<div className="h-full w-full flex flex-col gap-4 items-center justify-center p-6">
{switch twoFaPageState {
| TOTP_SHOW_QR =>
<ConfigureTotpScreen
isQrVisible
totpUrl
twoFaStatus
setTwoFaPageState
terminateTwoFactorAuth
errorHandling
isSkippable
showOnlyTotp
/>
| TOTP_SHOW_RC =>
<TotpRecoveryCodes
setTwoFaPageState onClickDownload={terminateTwoFactorAuth} setShowNewQR
/>
| TOTP_INPUT_RECOVERY_CODE =>
<EnterAccessCode
setTwoFaPageState
onClickVerifyAccessCode={terminateTwoFactorAuth}
errorHandling
isSkippable
showOnlyRc
/>
}}
<div className="text-grey-200 flex gap-2">
{"Log in with a different account?"->React.string}
<p
className="underline cursor-pointer underline-offset-2 hover:text-blue-700"
onClick={_ => handleLogout()->ignore}>
{"Click here to log out."->React.string}
</p>
</div>
</div>
</BackgroundImageWrapper>
</PageLoaderWrapper>
}
| 3,383 | 9,390 |
hyperswitch-control-center | src/entryPoints/AuthModule/TwoFaAuth/TwoFaAuth.res | .res | @react.component
let make = (~setAuthStatus, ~authType, ~setAuthType) => {
open APIUtils
open CommonAuthForm
open GlobalVars
open LogicUtils
open TwoFaUtils
open AuthProviderTypes
let getURL = useGetURL()
let url = RescriptReactRouter.useUrl()
let mixpanelEvent = MixpanelHook.useSendEvent()
let setMixpanelIdentity = MixpanelHook.useSetIdentity()
let initialValues = Dict.make()->JSON.Encode.object
let clientCountry = HSwitchUtils.getBrowswerDetails().clientCountry
let country = clientCountry.isoAlpha2->CountryUtils.getCountryCodeStringFromVarient
let showToast = ToastState.useShowToast()
let updateDetails = useUpdateMethod(~showErrorToast=false)
let (email, setEmail) = React.useState(_ => "")
let featureFlagValues = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let authId = HyperSwitchEntryUtils.getSessionData(~key="auth_id")
let domain = HyperSwitchEntryUtils.getSessionData(~key="domain")
let {
isMagicLinkEnabled,
isSignUpAllowed,
checkAuthMethodExists,
} = AuthModuleHooks.useAuthMethods()
let (signUpAllowed, signupMethod) = isSignUpAllowed()
let handleAuthError = e => {
open CommonAuthUtils
let error = e->parseErrorMessage
switch error.code->errorSubCodeMapper {
| UR_03 => "An account already exists with this email"
| UR_05 => {
setAuthType(_ => CommonAuthTypes.ResendVerifyEmail)
"Kindly verify your account"
}
| UR_16 => "Please use a valid email"
| UR_01 => "Incorrect email or password"
| _ => "Register failed, Try again"
}
}
let getUserWithEmail = async body => {
try {
let url = getURL(
~entityName=V1(USERS),
~userType=#CONNECT_ACCOUNT,
~methodType=Post,
~queryParamerters=Some(`auth_id=${authId}&domain=${domain}`), // todo: domain shall be removed from query params later
)
let res = await updateDetails(url, body, Post)
let valuesDict = res->getDictFromJsonObject
let magicLinkSent = valuesDict->LogicUtils.getBool("is_email_sent", false)
if magicLinkSent {
setAuthType(_ => MagicLinkEmailSent)
} else {
showToast(~message="Failed to send an email, Try again", ~toastType=ToastError)
}
} catch {
| Exn.Error(e) => showToast(~message={e->handleAuthError}, ~toastType=ToastError)
}
Nullable.null
}
let getUserWithEmailPassword = async (body, userType) => {
try {
let url = getURL(~entityName=V1(USERS), ~userType, ~methodType=Post)
let res = await updateDetails(url, body, Post)
setAuthStatus(PreLogin(AuthUtils.getPreLoginInfo(res)))
} catch {
| Exn.Error(e) => showToast(~message={e->handleAuthError}, ~toastType=ToastError)
}
Nullable.null
}
let openPlayground = _ => {
open CommonAuthUtils
let body = getEmailPasswordBody(playgroundUserEmail, playgroundUserPassword, country)
getUserWithEmailPassword(body, #SIGNINV2)->ignore
HSLocalStorage.setIsPlaygroundInLocalStorage(true)
}
let setResetPassword = async body => {
try {
// Need to check this
let url = getURL(~entityName=V1(USERS), ~userType=#RESET_PASSWORD, ~methodType=Post)
let _ = await updateDetails(url, body, Post)
LocalStorage.clear()
showToast(~message=`Password Changed Successfully`, ~toastType=ToastSuccess)
setAuthType(_ => LoginWithEmail)
} catch {
| _ => showToast(~message="Password Reset Failed, Try again", ~toastType=ToastError)
}
Nullable.null
}
let setForgetPassword = async body => {
try {
// Need to check this
let url = getURL(
~entityName=V1(USERS),
~userType=#FORGOT_PASSWORD,
~methodType=Post,
~queryParamerters=Some(`auth_id=${authId}`),
)
let _ = await updateDetails(url, body, Post)
setAuthType(_ => ForgetPasswordEmailSent)
showToast(~message="Please check your registered e-mail", ~toastType=ToastSuccess)
} catch {
| _ => showToast(~message="Forgot Password Failed, Try again", ~toastType=ToastError)
}
Nullable.null
}
let resendVerifyEmail = async body => {
try {
// Need to check this
let url = getURL(
~entityName=V1(USERS),
~userType=#VERIFY_EMAIL_REQUEST,
~methodType=Post,
~queryParamerters=Some(`auth_id=${authId}`),
)
let _ = await updateDetails(url, body, Post)
setAuthType(_ => ResendVerifyEmailSent)
showToast(~message="Please check your registered e-mail", ~toastType=ToastSuccess)
} catch {
| _ => showToast(~message="Resend mail failed, Try again", ~toastType=ToastError)
}
Nullable.null
}
let logMixpanelEvents = email => {
open CommonAuthTypes
switch authType {
| LoginWithPassword => mixpanelEvent(~eventName=`signin_using_email&password`, ~email)
| LoginWithEmail => mixpanelEvent(~eventName=`signin_using_magic_link`, ~email)
| SignUP => mixpanelEvent(~eventName=`signup_using_magic_link`, ~email)
| _ => ()
}
}
let onSubmit = async (values, _) => {
try {
open CommonAuthUtils
let valuesDict = values->getDictFromJsonObject
let email = valuesDict->getString("email", "")->String.toLowerCase
setEmail(_ => email)
logMixpanelEvents(email)
setMixpanelIdentity(~distinctId=email)->ignore
let _ = await (
switch (signupMethod, signUpAllowed, isMagicLinkEnabled(), authType) {
| (MAGIC_LINK, true, true, SignUP) => {
let body = getEmailBody(email, ~country)
getUserWithEmail(body)
}
| (PASSWORD, true, _, SignUP) => {
let password = getString(valuesDict, "password", "")
let body = getEmailPasswordBody(email, password, country)
getUserWithEmailPassword(body, #SIGNUP)
}
| (_, _, true, LoginWithEmail) => {
let body = getEmailBody(email, ~country)
getUserWithEmail(body)
}
| (_, _, _, LoginWithPassword) => {
let password = getString(valuesDict, "password", "")
let body = getEmailPasswordBody(email, password, country)
getUserWithEmailPassword(body, #SIGNINV2)
}
| (_, _, _, ResendVerifyEmail) => {
let exists = checkAuthMethodExists([PASSWORD])
if exists {
let body = email->getEmailBody
resendVerifyEmail(body)
} else {
Promise.make((resolve, _) => resolve(Nullable.null))
}
}
| (_, _, _, ForgetPassword) => {
let exists = checkAuthMethodExists([PASSWORD])
if exists {
let body = email->getEmailBody
setForgetPassword(body)
} else {
Promise.make((resolve, _) => resolve(Nullable.null))
}
}
| (_, _, _, ResetPassword) => {
let queryDict = url.search->getDictFromUrlSearchParams
let password_reset_token = queryDict->Dict.get("token")->Option.getOr("")
let password = getString(valuesDict, "create_password", "")
let body = getResetpasswordBodyJson(password, password_reset_token)
setResetPassword(body)
}
| _ =>
switch (featureFlagValues.email, authType) {
| (true, ForgetPassword) =>
let body = email->getEmailBody
setForgetPassword(body)
| _ => Promise.make((resolve, _) => resolve(Nullable.null))
}
}
)
} catch {
| _ => showToast(~message="Something went wrong, Try again", ~toastType=ToastError)
}
Nullable.null
}
let resendEmail = () => {
open CommonAuthUtils
let body = email->getEmailBody
switch authType {
| MagicLinkEmailSent => getUserWithEmail(body)->ignore
| ForgetPasswordEmailSent => setForgetPassword(body)->ignore
| ResendVerifyEmailSent => resendVerifyEmail(body)->ignore
| _ => ()
}
}
let submitBtnText = switch authType {
| LoginWithPassword | LoginWithEmail => "Continue"
| ResetPassword => "Confirm"
| ForgetPassword => "Reset password"
| ResendVerifyEmail => "Send mail"
| _ => "Get started, for free!"
}
let validateKeys = switch authType {
| ForgetPassword
| ResendVerifyEmail
| LoginWithEmail => ["email"]
| SignUP => featureFlagValues.email ? ["email"] : ["email", "password"]
| LoginWithPassword => ["email"]
| ResetPassword => ["create_password", "comfirm_password"]
| _ => []
}
React.useEffect(() => {
if url.hash === "playground" {
openPlayground()
}
None
}, [])
let note = AuthModuleHooks.useNote(authType, setAuthType)
<ReactFinalForm.Form
key="auth"
initialValues
subscription=ReactFinalForm.subscribeToValues
validate={values => validateTotpForm(values, validateKeys)}
onSubmit
render={({handleSubmit}) => {
<>
<CommonAuth.Header authType setAuthType email />
<form
onSubmit={handleSubmit}
className={`flex flex-col justify-evenly gap-5 h-full w-full !overflow-visible text-grey-600`}>
{switch authType {
| LoginWithPassword => <EmailPasswordForm setAuthType />
| ForgetPassword =>
<RenderIf condition={featureFlagValues.email && checkAuthMethodExists([PASSWORD])}>
<EmailForm />
</RenderIf>
| ResendVerifyEmail
| SignUP =>
<>
<RenderIf condition={signUpAllowed && signupMethod === SSOTypes.MAGIC_LINK}>
<EmailForm />
</RenderIf>
<RenderIf condition={signUpAllowed && signupMethod == SSOTypes.PASSWORD}>
<EmailPasswordForm setAuthType />
</RenderIf>
</>
| LoginWithEmail =>
isMagicLinkEnabled() ? <EmailForm /> : <EmailPasswordForm setAuthType />
| ResetPassword => <ResetPasswordForm />
| MagicLinkEmailSent | ForgetPasswordEmailSent | ResendVerifyEmailSent =>
<ResendBtn callBackFun={resendEmail} />
| _ => React.null
}}
<AddDataAttributes attributes=[("data-testid", "auth-submit-btn")]>
<div id="auth-submit-btn" className="flex flex-col gap-2">
{switch authType {
| LoginWithPassword
| LoginWithEmail
| ResetPassword
| ForgetPassword
| ResendVerifyEmail
| SignUP =>
<FormRenderer.SubmitButton
customSumbitButtonStyle="!w-full"
text=submitBtnText
userInteractionRequired=true
showToolTip=false
loadingText="Loading..."
/>
| _ => React.null
}}
</div>
</AddDataAttributes>
<AddDataAttributes attributes=[("data-testid", "card-foot-text")]>
<div> {note} </div>
</AddDataAttributes>
</form>
</>
}}
/>
}
| 2,613 | 9,391 |
hyperswitch-control-center | src/entryPoints/AuthModule/TwoFaAuth/TwoFaAuthScreen.res | .res | @react.component
let make = (~setAuthStatus) => {
open CommonAuthTypes
let url = RescriptReactRouter.useUrl()
let (_mode, setMode) = React.useState(_ => TestButtonMode)
let {isMagicLinkEnabled, checkAuthMethodExists} = AuthModuleHooks.useAuthMethods()
let {isLiveMode} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let pageViewEvent = MixpanelHook.usePageView()
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let authInitState = LoginWithPassword
let (authType, setAuthType) = React.useState(_ => authInitState)
let (actualAuthType, setActualAuthType) = React.useState(_ => authInitState)
React.useEffect(() => {
if isLiveMode {
setMode(_ => LiveButtonMode)
} else {
setMode(_ => TestButtonMode)
}
switch url.path {
| list{"user", "verify_email"} => setActualAuthType(_ => EmailVerify)
| list{"login"} =>
setActualAuthType(_ => isMagicLinkEnabled() ? LoginWithEmail : LoginWithPassword)
| list{"user", "set_password"} =>
checkAuthMethodExists([PASSWORD]) ? setActualAuthType(_ => ResetPassword) : ()
| list{"user", "accept_invite_from_email"} => setActualAuthType(_ => ActivateFromEmail)
| list{"forget-password"} =>
checkAuthMethodExists([PASSWORD]) ? setActualAuthType(_ => ForgetPassword) : ()
| list{"register"} =>
// In Live mode users are not allowed to singup directly
!isLiveMode ? setActualAuthType(_ => SignUP) : AuthUtils.redirectToLogin()
| _ => ()
}
None
}, [url.path])
React.useEffect(() => {
if authType != actualAuthType {
setAuthType(_ => actualAuthType)
}
None
}, [actualAuthType])
React.useEffect(() => {
switch (authType, url.path) {
| (
LoginWithEmail | LoginWithPassword,
list{"user", "verify_email"}
| list{"user", "accept_invite_from_email"}
| list{"user", "login"}
| list{"user", "set_password"}
| list{"register", ..._},
) => () // to prevent duplicate push
| (LoginWithPassword | LoginWithEmail, _) => AuthUtils.redirectToLogin()
| (SignUP, list{"register", ..._}) => () // to prevent duplicate push
| (SignUP, _) => GlobalVars.appendDashboardPath(~url="/register")->RescriptReactRouter.push
| (ForgetPassword | ForgetPasswordEmailSent, list{"forget-password", ..._}) => () // to prevent duplicate push
| (ForgetPassword | ForgetPasswordEmailSent, _) =>
GlobalVars.appendDashboardPath(~url="/forget-password")->RescriptReactRouter.push
| (ResendVerifyEmail | ResendVerifyEmailSent, list{"resend-mail", ..._}) => () // to prevent duplicate push
| (ResendVerifyEmail | ResendVerifyEmailSent, _) =>
GlobalVars.appendDashboardPath(~url="/resend-mail")->RescriptReactRouter.push
| _ => ()
}
None
}, [authType])
React.useEffect(() => {
let path = url.path->List.toArray->Array.joinWith("/")
if featureFlagDetails.mixpanel {
pageViewEvent(~path)->ignore
}
None
}, (featureFlagDetails.mixpanel, authType))
<TwoFaAuth setAuthStatus authType setAuthType />
}
| 808 | 9,392 |
hyperswitch-control-center | src/entryPoints/AuthModule/TwoFaAuth/TwoFaElements.res | .res | let h2TextStyle = HSwitchUtils.getTextClass((H2, Optional))
let h3TextStyle = HSwitchUtils.getTextClass((H3, Leading_1))
let p2Regular = HSwitchUtils.getTextClass((P2, Regular))
let p3Regular = HSwitchUtils.getTextClass((P3, Regular))
module TotpScanQR = {
@react.component
let make = (~totpUrl, ~isQrVisible) => {
<>
<div className="grid grid-cols-4 gap-4 w-full">
<div className="flex flex-col gap-10 col-span-3">
<p> {"Use any authenticator app to complete the setup"->React.string} </p>
<div className="flex flex-col gap-4">
<p className=p2Regular>
{"Follow these steps to configure two factor authentication:"->React.string}
</p>
<div className="flex flex-col gap-4 ml-2">
<p className={`${p2Regular} opacity-60 flex gap-2 items-center`}>
<div className="text-white rounded-full bg-grey-900 opacity-50 px-2 py-0.5">
{"1"->React.string}
</div>
{"Scan the QR code shown on the screen with your authenticator application"->React.string}
</p>
<p className={`${p2Regular} opacity-60 flex gap-2 items-center`}>
<div className="text-white rounded-full bg-grey-900 opacity-50 px-2 py-0.5">
{"2"->React.string}
</div>
{"Enter the OTP code displayed on the authenticator app in below text field or textbox"->React.string}
</p>
</div>
</div>
</div>
<div
className={`flex flex-col gap-2 col-span-1 items-center justify-center ${totpUrl->String.length > 0
? "blur-none"
: "blur-sm"}`}>
<p className=p3Regular> {"Scan the QR Code into your app"->React.string} </p>
{if isQrVisible {
<ReactQRCode value=totpUrl size=150 />
} else {
<Icon
name="spinner"
size=20
className="animate-spin"
parentClass="w-full h-full flex justify-center items-center"
/>
}}
</div>
</div>
<div className="h-px w-11/12 bg-grey-200 opacity-50" />
</>
}
}
module TotpInput = {
@react.component
let make = (~otp, ~setOtp) => {
<div className="flex flex-col gap-4 items-center">
<p>
{"Enter a 6-digit authentication code generated by you authenticator app"->React.string}
</p>
<OtpInput value={otp} setValue={setOtp} />
</div>
}
}
module ShowRecoveryCodes = {
@react.component
let make = (~recoveryCodes) => {
<div
className="border border-gray-200 rounded-md bg-jp-gray-100 py-6 px-12 flex gap-8 justify-evenly">
<div className="grid grid-cols-2 gap-4">
{recoveryCodes
->Array.map(recoveryCode =>
<div className="flex items-center gap-2">
<div className="p-1 rounded-full bg-jp-gray-600" />
<p className="text-jp-gray-700 text-xl"> {recoveryCode->React.string} </p>
</div>
)
->React.array}
</div>
</div>
}
}
module RecoveryCodesInput = {
@react.component
let make = (~recoveryCode, ~setRecoveryCode) => {
let recoveryCodeInput: ReactFinalForm.fieldRenderPropsInput = {
name: "recovery_code_input",
onBlur: _ => (),
onChange: ev => {
let value = ReactEvent.Form.target(ev)["value"]
setRecoveryCode(_ => value)
},
onFocus: _ => (),
value: recoveryCode->JSON.Encode.string,
checked: true,
}
<div className="flex flex-col gap-4 items-center">
<p> {"Enter a 8-digit recovery code generated provided during signup."->React.string} </p>
<TextInput
input=recoveryCodeInput
placeholder="XXXX-XXXX"
customWidth="w-96"
customStyle="h-16 text-xl justify-center text-center"
maxLength=9
/>
</div>
}
}
| 1,033 | 9,393 |
hyperswitch-control-center | src/entryPoints/AuthModule/TwoFaAuth/TwoFaLanding.res | .res | let p2Regular = HSwitchUtils.getTextClass((P2, Regular))
module AttemptsExpiredComponent = {
@react.component
let make = (~expiredType, ~setTwoFaPageState, ~setTwoFaStatus) => {
open TwoFaTypes
open HSwitchUtils
let handleLogout = APIUtils.useHandleLogout()
let expiredComponent = switch expiredType {
| TOTP_ATTEMPTS_EXPIRED =>
<div
className="bg-white px-6 py-12 rounded-md border w-1/3 text-center font-semibold flex flex-col gap-4">
<p>
{"There have been multiple unsuccessful TOTP attempts for this account. Please wait a moment before trying again."->React.string}
</p>
<p className={`${p2Regular} text-jp-gray-700`}>
{"or "->React.string}
<span
className="cursor-pointer underline underline-offset-2 text-blue-600"
onClick={_ => {
setTwoFaStatus(_ => TwoFaNotExpired)
setTwoFaPageState(_ => TOTP_INPUT_RECOVERY_CODE)
}}>
{"Use recovery-code"->React.string}
</span>
</p>
</div>
| RC_ATTEMPTS_EXPIRED =>
<div
className="bg-white px-6 py-12 rounded-md border w-1/3 text-center font-semibold flex flex-col gap-4">
<p>
{"There have been multiple unsuccessful Recovery code attempts for this account. Please wait a moment before trying again."->React.string}
</p>
<p className={`${p2Regular} text-jp-gray-700`}>
{"or "->React.string}
<span
className="cursor-pointer underline underline-offset-2 text-blue-600"
onClick={_ => {
setTwoFaStatus(_ => TwoFaNotExpired)
setTwoFaPageState(_ => TOTP_SHOW_QR)
}}>
{"Use totp"->React.string}
</span>
</p>
</div>
| TWO_FA_EXPIRED =>
<div
className="bg-white px-6 py-12 rounded-md border w-1/3 text-center font-semibold flex flex-col gap-4">
<p>
{"There have been multiple unsuccessful two-factor attempts for this account. Please wait a moment before trying again."->React.string}
</p>
</div>
}
<BackgroundImageWrapper>
<div className="h-full w-full flex flex-col gap-4 items-center justify-center p-6 ">
{expiredComponent}
<div className="text-grey-200 flex gap-2">
{"Log in with a different account?"->React.string}
<p
className="underline cursor-pointer underline-offset-2 hover:text-blue-700"
onClick={_ => handleLogout()->ignore}>
{"Click here to log out."->React.string}
</p>
</div>
</div>
</BackgroundImageWrapper>
}
}
@react.component
let make = () => {
open TwoFaTypes
let getURL = APIUtils.useGetURL()
let fetchDetails = APIUtils.useGetMethod()
let {setAuthStatus} = React.useContext(AuthInfoProvider.authStatusContext)
let (twoFaStatus, setTwoFaStatus) = React.useState(_ => TwoFaNotExpired)
let (twoFaPageState, setTwoFaPageState) = React.useState(_ => TOTP_SHOW_QR)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (isSkippable, setIsSkippable) = React.useState(_ => true)
let (checkTwoFaResonse, setCheckTwoFaResponse) = React.useState(_ =>
JSON.Encode.null->TwoFaUtils.jsonTocheckTwofaResponseType
)
let handlePageBasedOnAttempts = responseDict => {
switch responseDict {
| Some(value) =>
if value.totp.attemptsRemaining > 0 && value.recoveryCode.attemptsRemaining > 0 {
setTwoFaStatus(_ => TwoFaNotExpired)
setTwoFaPageState(_ => TOTP_SHOW_QR)
} else if value.totp.attemptsRemaining == 0 && value.recoveryCode.attemptsRemaining == 0 {
setTwoFaStatus(_ => TwoFaExpired(TWO_FA_EXPIRED))
} else if value.totp.attemptsRemaining == 0 {
setTwoFaStatus(_ => TwoFaExpired(TOTP_ATTEMPTS_EXPIRED))
} else if value.recoveryCode.attemptsRemaining == 0 {
setTwoFaStatus(_ => TwoFaExpired(RC_ATTEMPTS_EXPIRED))
}
| None => setTwoFaStatus(_ => TwoFaNotExpired)
}
}
let checkTwofaStatus = async () => {
try {
let url = getURL(
~entityName=V1(USERS),
~userType=#CHECK_TWO_FACTOR_AUTH_STATUS_V2,
~methodType=Get,
)
let response = await fetchDetails(url)
let responseDict = response->TwoFaUtils.jsonTocheckTwofaResponseType
handlePageBasedOnAttempts(responseDict.status)
setCheckTwoFaResponse(_ => responseDict)
setIsSkippable(_ => responseDict.isSkippable)
setScreenState(_ => PageLoaderWrapper.Success)
} catch {
| _ => {
setScreenState(_ => PageLoaderWrapper.Error("Failed to fetch!"))
setAuthStatus(LoggedOut)
}
}
}
let errorHandling = () => {
checkTwofaStatus()->ignore
}
React.useEffect(() => {
checkTwofaStatus()->ignore
None
}, [])
<PageLoaderWrapper screenState sectionHeight="h-screen">
{switch twoFaStatus {
| TwoFaExpired(expiredType) =>
<AttemptsExpiredComponent expiredType setTwoFaPageState setTwoFaStatus />
| TwoFaNotExpired =>
<TotpSetup twoFaPageState setTwoFaPageState errorHandling isSkippable checkTwoFaResonse />
}}
</PageLoaderWrapper>
}
| 1,332 | 9,394 |
hyperswitch-control-center | src/entryPoints/AuthModule/TwoFaAuth/TwoFaUtils.res | .res | let getEmailToken = (authStatus: AuthProviderTypes.authStatus) => {
switch authStatus {
| PreLogin(preLoginValue) => preLoginValue.email_token
| _ => None
}
}
let validateTotpForm = (values: JSON.t, keys: array<string>) => {
let valuesDict = values->LogicUtils.getDictFromJsonObject
let errors = Dict.make()
keys->Array.forEach(key => {
let value = LogicUtils.getString(valuesDict, key, "")
// empty check
if value->LogicUtils.isEmptyString {
switch key {
| "email" => Dict.set(errors, key, "Please enter your Email ID"->JSON.Encode.string)
| "password" => Dict.set(errors, key, "Please enter your Password"->JSON.Encode.string)
| "create_password" => Dict.set(errors, key, "Please enter your Password"->JSON.Encode.string)
| "comfirm_password" =>
Dict.set(errors, key, "Please enter your Password Once Again"->JSON.Encode.string)
| _ =>
Dict.set(
errors,
key,
`${key
->LogicUtils.capitalizeString
->LogicUtils.snakeToTitle} cannot be empty`->JSON.Encode.string,
)
}
}
// email check
if (
value->LogicUtils.isNonEmptyString && key === "email" && value->CommonAuthUtils.isValidEmail
) {
Dict.set(errors, key, "Please enter valid Email ID"->JSON.Encode.string)
}
// password check
switch key {
| "password" => CommonAuthUtils.passwordKeyValidation(value, key, "password", errors)
| "new_password" => CommonAuthUtils.passwordKeyValidation(value, key, "new_password", errors)
| _ => CommonAuthUtils.passwordKeyValidation(value, key, "create_password", errors)
}
// confirm password check
CommonAuthUtils.confirmPasswordCheck(
value,
key,
"comfirm_password",
"create_password",
valuesDict,
errors,
)
//confirm password check for #change_password
CommonAuthUtils.confirmPasswordCheck(
value,
key,
"confirm_password",
"new_password",
valuesDict,
errors,
)
})
errors->JSON.Encode.object
}
let downloadRecoveryCodes = (~recoveryCodes) => {
open LogicUtils
DownloadUtils.downloadOld(
~fileName="recoveryCodes.txt",
~content=JSON.stringifyWithIndent(recoveryCodes->getJsonFromArrayOfString, 3),
)
}
let jsonToTwoFaValueType: Dict.t<'a> => TwoFaTypes.twoFaValueType = dict => {
open LogicUtils
{
isCompleted: dict->getBool("is_completed", false),
attemptsRemaining: dict->getInt("remaining_attempts", 4),
}
}
let jsonTocheckTwofaResponseType: JSON.t => TwoFaTypes.checkTwofaResponseType = json => {
open LogicUtils
let jsonToDict = json->getDictFromJsonObject
let statusValueDict = jsonToDict->Dict.get("status")
let isSkippable = jsonToDict->getBool("is_skippable", true)
let statusValue = switch statusValueDict {
| Some(json) => {
let dict = json->getDictFromJsonObject
let twoFaValue: TwoFaTypes.twoFatype = {
totp: dict->getDictfromDict("totp")->jsonToTwoFaValueType,
recoveryCode: dict->getDictfromDict("recovery_code")->jsonToTwoFaValueType,
}
Some(twoFaValue)
}
| None => None
}
{
status: statusValue,
isSkippable,
}
}
| 811 | 9,395 |
hyperswitch-control-center | src/entryPoints/AuthModule/TwoFaAuth/TwoFaTypes.res | .res | type twoFaPageState =
| TOTP_SHOW_QR
| TOTP_SHOW_RC
| TOTP_INPUT_RECOVERY_CODE
type twoFaStatus = TWO_FA_NOT_SET | TWO_FA_SET
type twoFaValueType = {
isCompleted: bool,
attemptsRemaining: int,
}
type twoFatype = {
totp: twoFaValueType,
recoveryCode: twoFaValueType,
}
type checkTwofaResponseType = {
status: option<twoFatype>,
isSkippable: bool,
}
type expiredTypes =
| TOTP_ATTEMPTS_EXPIRED
| RC_ATTEMPTS_EXPIRED
| TWO_FA_EXPIRED
type twoFaStatusType = TwoFaExpired(expiredTypes) | TwoFaNotExpired
| 161 | 9,396 |
hyperswitch-control-center | src/entryPoints/Provider/ProviderTypes.res | .res | type integration = {
mutable is_done: bool,
mutable metadata: JSON.t,
}
type dashboardPageStateTypes = [
| #AUTO_CONNECTOR_INTEGRATION
| #DEFAULT
| #INTEGRATION_DOC
| #HOME
]
type integrationDetailsType = {
pricing_plan: integration,
connector_integration: integration,
integration_checklist: integration,
account_activation: integration,
}
type contextType = {
showFeedbackModal: bool,
setShowFeedbackModal: (bool => bool) => unit,
showProdIntentForm: bool,
setShowProdIntentForm: (bool => bool) => unit,
dashboardPageState: dashboardPageStateTypes,
setDashboardPageState: (dashboardPageStateTypes => dashboardPageStateTypes) => unit,
integrationDetails: integrationDetailsType,
setIntegrationDetails: (integrationDetailsType => integrationDetailsType) => unit,
permissionInfo: array<UserManagementTypes.getInfoType>,
setPermissionInfo: (
array<UserManagementTypes.getInfoType> => array<UserManagementTypes.getInfoType>
) => unit,
isProdIntentCompleted: option<bool>,
setIsProdIntentCompleted: (option<bool> => option<bool>) => unit,
showSideBar: bool,
setShowSideBar: (bool => bool) => unit,
}
type sidebarContextType = {
isSidebarExpanded: bool,
setIsSidebarExpanded: (bool => bool) => unit,
}
| 301 | 9,397 |
hyperswitch-control-center | src/entryPoints/Provider/GlobalProvider.res | .res | open ProviderTypes
let defaultIntegrationValue = Dict.make()->JSON.Encode.object->ProviderHelper.getIntegrationDetails
let defaultValue = {
showFeedbackModal: false,
setShowFeedbackModal: _ => (),
showProdIntentForm: false,
setShowProdIntentForm: _ => (),
integrationDetails: defaultIntegrationValue,
setIntegrationDetails: _ => (),
dashboardPageState: #DEFAULT,
setDashboardPageState: _ => (),
// TODO: change this when custom role for user-management revamp is picked
permissionInfo: [],
setPermissionInfo: _ => (),
isProdIntentCompleted: None,
setIsProdIntentCompleted: _ => (),
showSideBar: true,
setShowSideBar: _ => (),
}
let defaultContext = React.createContext(defaultValue)
module Provider = {
let make = React.Context.provider(defaultContext)
}
@react.component
let make = (~children) => {
let (showFeedbackModal, setShowFeedbackModal) = React.useState(_ => false)
let (showProdIntentForm, setShowProdIntentForm) = React.useState(_ => false)
let (dashboardPageState, setDashboardPageState) = React.useState(_ => #DEFAULT)
let (permissionInfo, setPermissionInfo) = React.useState(_ => [])
let (isProdIntentCompleted, setIsProdIntentCompleted) = React.useState(_ => None)
let (showSideBar, setShowSideBar) = React.useState(_ => true)
let (integrationDetails, setIntegrationDetails) = React.useState(_ =>
Dict.make()->JSON.Encode.object->ProviderHelper.getIntegrationDetails
)
<Provider
value={
showFeedbackModal,
setShowFeedbackModal,
setIntegrationDetails,
integrationDetails,
showProdIntentForm,
setShowProdIntentForm,
dashboardPageState,
setDashboardPageState,
permissionInfo,
setPermissionInfo,
isProdIntentCompleted,
setIsProdIntentCompleted,
showSideBar,
setShowSideBar,
}>
children
</Provider>
}
| 424 | 9,398 |
hyperswitch-control-center | src/entryPoints/Provider/ProviderHelper.res | .res | open ProviderTypes
let itemIntegrationDetailsMapper = dict => {
open LogicUtils
{
is_done: dict->getBool("is_done", false),
metadata: dict->getDictfromDict("metadata")->JSON.Encode.object,
}
}
let itemToObjMapper = dict => {
open LogicUtils
{
pricing_plan: dict->getDictfromDict("pricing_plan")->itemIntegrationDetailsMapper,
connector_integration: dict
->getDictfromDict("connector_integration")
->itemIntegrationDetailsMapper,
integration_checklist: dict
->getDictfromDict("integration_checklist")
->itemIntegrationDetailsMapper,
account_activation: dict->getDictfromDict("account_activation")->itemIntegrationDetailsMapper,
}
}
let getIntegrationDetails: JSON.t => integrationDetailsType = json => {
open LogicUtils
json->getDictFromJsonObject->itemToObjMapper
}
let itemToObjMapperForGetInfo: Dict.t<JSON.t> => UserManagementTypes.getInfoType = dict => {
open LogicUtils
{
module_: getString(dict, "group", ""),
description: getString(dict, "description", ""),
}
}
| 247 | 9,399 |
hyperswitch-control-center | src/Recon/ReconHelper.res | .res | module GetProductionAccess = {
@react.component
let make = () => {
let mixpanelEvent = MixpanelHook.useSendEvent()
let {isProdIntentCompleted, setShowProdIntentForm} = React.useContext(
GlobalProvider.defaultContext,
)
let isProdIntent = isProdIntentCompleted->Option.getOr(false)
let productionAccessString = isProdIntent
? "Production Access Requested"
: "Get Production Access"
switch isProdIntentCompleted {
| Some(_) =>
<Button
text=productionAccessString
buttonType=Primary
buttonSize=Medium
buttonState=Normal
onClick={_ => {
if !isProdIntent {
setShowProdIntentForm(_ => true)
mixpanelEvent(~eventName="recon_get_production_access")
}
}}
/>
| None =>
<Shimmer
styleClass="h-10 px-4 py-3 m-2 ml-2 mb-3 dark:bg-black bg-white rounded" shimmerType={Small}
/>
}
}
}
| 231 | 9,400 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconConfiguration/ReconConfigurationHelper.res | .res | module SubHeading = {
@react.component
let make = (~title, ~subTitle) => {
<div className="flex flex-col gap-y-1">
<p className="text-2xl font-semibold text-nd_gray-700 leading-9"> {title->React.string} </p>
<p className="text-sm text-nd_gray-400 font-medium leading-5"> {subTitle->React.string} </p>
</div>
}
}
module StepCard = {
@react.component
let make = (
~stepName,
~description="",
~isSelected,
~onClick,
~iconName,
~isLoading=false,
~customSelectionComponent,
~customOuterClass="",
~customSelectionBorderClass=?,
~isDisabled=false,
) => {
let borderClass = switch (customSelectionBorderClass, isSelected) {
| (Some(val), true) => val
| (_, true) => "border-blue-500"
| _ => ""
}
let disabledClass = if isDisabled {
"opacity-60 filter blur-xs pointer-events-none cursor-not-allowed"
} else {
"cursor-pointer"
}
<div
key={stepName}
className={`flex items-center gap-x-2.5 border rounded-xl p-3 transition-shadow justify-between w-full ${borderClass} ${disabledClass} ${customOuterClass}`}
onClick={onClick}>
<div className="flex flex-row items-center gap-x-4">
<Icon name=iconName className="w-8 h-8" />
<div className="flex flex-col gap-1">
<h3 className="text-sm font-semibold text-nd_gray-600 leading-5">
{stepName->React.string}
</h3>
<RenderIf condition={description->String.length > 0}>
<p className="text-xs font-medium text-nd_gray-400"> {description->React.string} </p>
</RenderIf>
</div>
</div>
<RenderIf condition={isSelected}>
{<div className="flex flex-row items-center gap-2"> customSelectionComponent </div>}
</RenderIf>
<RenderIf condition={isDisabled}>
<div className="h-4 w-4 border border-nd_gray-300 rounded-full" />
</RenderIf>
</div>
}
}
| 529 | 9,401 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconConfiguration/ReconConfigurationUtils.res | .res | open VerticalStepIndicatorTypes
open ReconConfigurationTypes
open LogicUtils
let sections = [
{
id: (#orderDataConnection: sections :> string),
name: "Order Data Connection",
icon: "nd-inbox",
subSections: None,
},
{
id: (#connectProcessors: sections :> string),
name: "Connect Processors",
icon: "nd-plugin",
subSections: None,
},
{
id: (#finish: sections :> string),
name: "Finish",
icon: "nd-flag",
subSections: None,
},
]
let getSectionVariantFromString = (section: string): sections =>
switch section {
| "orderDataConnection" => #orderDataConnection
| "connectProcessors" => #connectProcessors
| "finish" => #finish
| _ => #orderDataConnection
}
let itemToObjMapperForReconStatusData: Dict.t<JSON.t> => reconDataType = dict => {
let reconStatusDict = dict->getDictfromDict("ReconStatus")
{
is_order_data_set: reconStatusDict->getBool("is_order_data_set", false),
is_processor_data_set: reconStatusDict->getBool("is_processor_data_set", false),
}
}
let defaultReconStatusData: reconDataType = {
{
is_order_data_set: false,
is_processor_data_set: false,
}
}
let getRequestBody = (~isOrderDataSet: bool, ~isProcessorDataSet: bool) => {
{
"ReconStatus": {
is_order_data_set: isOrderDataSet,
is_processor_data_set: isProcessorDataSet,
},
}
}
| 366 | 9,402 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconConfiguration/ReconConfiguration.res | .res | @react.component
let make = (~setShowOnBoarding, ~currentStep, ~setCurrentStep) => {
open OrderDataConnectionTypes
open VerticalStepIndicatorTypes
open ReconConfigurationUtils
let (selectedOrderSource, setSelectedOrderSource) = React.useState(_ => UploadFile)
let {setShowSideBar} = React.useContext(GlobalProvider.defaultContext)
let backClick = () => {
setShowSideBar(_ => true)
RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url="/v2/recon/overview"))
}
let removeSidebar = () => {
setShowSideBar(_ => false)
}
React.useEffect(() => {
removeSidebar()
None
}, [])
let reconTitleElement =
<>
<h1 className="text-medium font-semibold text-gray-600">
{"Setup Reconciliation"->React.string}
</h1>
</>
<div className="flex flex-col gap-10 h-774-px">
<div className="flex h-full mt-10">
<div className="flex flex-col">
<VerticalStepIndicator titleElement=reconTitleElement sections currentStep backClick />
</div>
<div className="mx-12 mt-16 overflow-y-auto">
<div
className="absolute z-10 top-76-px left-0 w-full py-4 px-10 bg-orange-50 flex justify-between items-center">
<div className="flex gap-4 items-center">
<Icon name="nd-information-triangle" size=24 />
<p className="text-nd_gray-600 text-base leading-6 font-medium">
{"You're viewing sample analytics to help you understand how the reports will look with real data"->React.string}
</p>
</div>
</div>
<div className="w-500-px">
{switch currentStep.sectionId->getSectionVariantFromString {
| #orderDataConnection =>
<OrderDataConnection
currentStep={currentStep}
setCurrentStep={setCurrentStep}
selectedOrderSource
setSelectedOrderSource
/>
| #connectProcessors =>
<ConnectProcessors currentStep={currentStep} setCurrentStep={setCurrentStep} />
| #finish =>
<Final currentStep={currentStep} setCurrentStep={setCurrentStep} setShowOnBoarding />
}}
</div>
</div>
</div>
</div>
}
| 536 | 9,403 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconConfiguration/ReconConfigurationTypes.res | .res | type sections = [#orderDataConnection | #connectProcessors | #finish]
type reconDataType = {is_order_data_set: bool, is_processor_data_set: bool}
| 35 | 9,404 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconConfiguration/ConnectProcessors/ConnectProcessors.res | .res | @react.component
let make = (~currentStep: VerticalStepIndicatorTypes.step, ~setCurrentStep) => {
open APIUtils
open ConnectProcessorsHelper
open ConnectProcessorsUtils
open ReconConfigurationUtils
open VerticalStepIndicatorUtils
let mixpanelEvent = MixpanelHook.useSendEvent()
let updateDetails = useUpdateMethod()
let getURL = useGetURL()
let showToast = ToastState.useShowToast()
let getNextStep = (currentStep: VerticalStepIndicatorTypes.step): option<
VerticalStepIndicatorTypes.step,
> => {
findNextStep(sections, currentStep)
}
let onNextClick = async () => {
try {
let url = getURL(~entityName=V1(USERS), ~userType=#USER_DATA, ~methodType=Post)
let body = getRequestBody(~isOrderDataSet=true, ~isProcessorDataSet=true)
let _ = await updateDetails(url, body->Identity.genericTypeToJson, Post)
switch getNextStep(currentStep) {
| Some(nextStep) => setCurrentStep(_ => nextStep)
| None => ()
}
} catch {
| Exn.Error(_err) =>
showToast(~message="Something went wrong. Please try again", ~toastType=ToastError)
}
}
let onSubmit = async (_values, _form: ReactFinalForm.formApi) => {
mixpanelEvent(~eventName="recon_onboarding_step2")
let _ = await onNextClick()
Nullable.null
}
<div className="flex flex-col h-full gap-y-10">
<div className="flex flex-col h-full gap-y-10">
<ReconConfigurationHelper.SubHeading
title="Where do you process your payments?"
subTitle="Choose one processor for now. You can connect more processors later"
/>
<div className="flex flex-col gap-y-4">
<p className="text-base text-gray-700 font-semibold">
{"Select a processor"->React.string}
</p>
<Form
initialValues={Dict.make()->JSON.Encode.object}
validate={validateProcessorFields}
onSubmit>
<ConnectProcessorsFields />
</Form>
</div>
</div>
</div>
}
| 486 | 9,405 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconConfiguration/ConnectProcessors/ConnectProcessorsTypes.res | .res | type processorFieldsConfig = {
processor_type: string,
secret_key: string,
client_verification_key: string,
}
| 26 | 9,406 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconConfiguration/ConnectProcessors/ConnectProcessorsHelper.res | .res | open HSwitchUtils
let p1MediumTextStyle = HSwitchUtils.getTextClass((P1, Medium))
let p1RegularText = getTextClass((P1, Regular))
let generateDropdownOptionsCustomComponent: array<OMPSwitchTypes.ompListTypes> => array<
SelectBox.dropdownOption,
> = dropdownList => {
let options: array<SelectBox.dropdownOption> = dropdownList->Array.map((
item
): SelectBox.dropdownOption => {
let option: SelectBox.dropdownOption = {
label: item.name,
value: item.id,
icon: Button.CustomIcon(
<GatewayIcon gateway={item.name->String.toUpperCase} className="mt-0.5 mr-2 w-4 h-4" />,
),
}
option
})
options
}
module ListBaseComp = {
@react.component
let make = (
~heading="",
~subHeading,
~arrow,
~showEditIcon=false,
~onEditClick=_ => (),
~isDarkBg=false,
~showDropdownArrow=true,
~placeHolder="Select Processor",
) => {
let {globalUIConfig: {sidebarColor: {secondaryTextColor}}} = React.useContext(
ThemeProvider.themeContext,
)
let arrowClassName = isDarkBg
? `${arrow
? "rotate-180"
: "-rotate-0"} transition duration-[250ms] opacity-70 ${secondaryTextColor}`
: `${arrow
? "rotate-0"
: "rotate-180"} transition duration-[250ms] opacity-70 ${secondaryTextColor}`
<div
className={`flex flex-row cursor-pointer items-center py-5 px-4 gap-2 min-w-44 justify-between h-8 bg-white border rounded-lg border-nd_gray-100 shadow-sm`}>
<div className="flex flex-row items-center gap-2">
<RenderIf condition={subHeading->String.length > 0}>
<GatewayIcon gateway={subHeading->String.toUpperCase} className="w-6 h-6" />
<p
className="overflow-scroll text-nowrap text-sm font-medium text-nd_gray-500 whitespace-pre ">
{subHeading->React.string}
</p>
</RenderIf>
<RenderIf condition={subHeading->String.length == 0}>
<p
className="overflow-scroll text-nowrap text-sm font-medium text-nd_gray-500 whitespace-pre ">
{placeHolder->React.string}
</p>
</RenderIf>
</div>
<RenderIf condition={showDropdownArrow}>
<Icon className={`${arrowClassName} ml-1`} name="nd-angle-down" size=12 />
</RenderIf>
</div>
}
}
module AddNewOMPButton = {
@react.component
let make = (
~user: UserInfoTypes.entity,
~customPadding="",
~customHRTagStyle="",
~addItemBtnStyle="",
~prodConnectorList=ConnectorUtils.connectorListForLive,
~filterConnector=ConnectorTypes.Processors(STRIPE)->Some,
) => {
open ConnectorUtils
let allowedRoles = switch user {
| #Organization => [#tenant_admin]
| #Merchant => [#tenant_admin, #org_admin]
| #Profile => [#tenant_admin, #org_admin, #merchant_admin]
| _ => []
}
let hasOMPCreateAccess = OMPCreateAccessHook.useOMPCreateAccessHook(allowedRoles)
let cursorStyles = GroupAccessUtils.cursorStyles(hasOMPCreateAccess)
let connectorsList = switch filterConnector {
| Some(connector) => prodConnectorList->Array.filter(item => item != connector)
| _ => prodConnectorList
}
<ACLDiv
authorization={hasOMPCreateAccess}
noAccessDescription="You do not have the required permissions for this action. Please contact your admin."
onClick={_ => ()}
isRelative=false
contentAlign=Default
tooltipForWidthClass="!h-full"
className={`${cursorStyles} ${customPadding} ${addItemBtnStyle}`}
showTooltip={hasOMPCreateAccess == Access}>
{<>
<hr className={customHRTagStyle} />
<div className="flex flex-col items-start gap-3.5 font-medium px-3.5 py-3">
<p
className="uppercase text-nd_gray-400 font-semibold leading-3 text-fs-10 tracking-wider bg-white">
{"Available for production"->React.string}
</p>
<div className="flex flex-col gap-2.5 h-40 overflow-scroll cursor-not-allowed w-full">
{connectorsList
->Array.mapWithIndex((connector: ConnectorTypes.connectorTypes, _) => {
let connectorName = connector->getConnectorNameString
let size = "w-4 h-4 rounded-sm"
<div className="flex flex-row gap-3 items-center">
<GatewayIcon gateway={connectorName->String.toUpperCase} className=size />
<p className="text-sm font-medium normal-case text-nd_gray-600/40">
{connectorName
->getDisplayNameForConnector(~connectorType=ConnectorTypes.Processor)
->React.string}
</p>
</div>
})
->React.array}
</div>
</div>
</>}
</ACLDiv>
}
}
module ConnectProcessorsFields = {
@react.component
let make = () => {
open OMPSwitchTypes
let form = ReactFinalForm.useForm()
let (selectedProcessor, setSelectedProcessor) = React.useState(_ => "")
let (processorList, _) = React.useState(_ => [{id: "Stripe", name: "Stripe"}])
let (arrow, setArrow) = React.useState(_ => false)
let toggleChevronState = () => {
setArrow(prev => !prev)
}
let input: ReactFinalForm.fieldRenderPropsInput = {
name: "name",
onBlur: _ => (),
onChange: ev => {
let value = ev->Identity.formReactEventToString
form.change("processor_type", value->JSON.Encode.string)
setSelectedProcessor(_ => value)
},
onFocus: _ => (),
value: selectedProcessor->JSON.Encode.string,
checked: true,
}
let addItemBtnStyle = "border border-t-0 !w-full"
let customScrollStyle = "max-h-72 overflow-scroll px-1 pt-1 border border-b-0"
let dropdownContainerStyle = "rounded-md border border-1 !w-full"
<>
<SelectBox.BaseDropdown
allowMultiSelect=false
buttonText=""
input
deselectDisable=true
customButtonStyle="!rounded-lg"
options={processorList->generateDropdownOptionsCustomComponent}
hideMultiSelectButtons=true
addButton=false
searchable=false
baseComponent={<ListBaseComp heading="Profile" subHeading=selectedProcessor arrow />}
bottomComponent={<AddNewOMPButton user=#Profile addItemBtnStyle />}
customDropdownOuterClass="!border-none !w-full"
fullLength=true
toggleChevronState
customScrollStyle
dropdownContainerStyle
shouldDisplaySelectedOnTop=true
customSelectionIcon={CustomIcon(<Icon name="nd-checkbox-base" />)}
/>
<RenderIf condition={selectedProcessor->String.length > 0}>
<div className="flex flex-col gap-y-3 mt-10">
<p className="font-semibold leading-5 text-nd_gray-700 text-sm">
{"Provide authentication details"->React.string}
</p>
<FormRenderer.FieldRenderer
labelClass="font-semibold"
field={FormRenderer.makeFieldInfo(
~label="Secret Key",
~name="secret_key",
~placeholder="sk_test_1234AbCDeFghijtT1zdp7dc",
~customInput=InputFields.textInput(
~customStyle="rounded-xl bg-nd_gray-50",
~isDisabled=true,
),
~isRequired=false,
)}
/>
<FormRenderer.FieldRenderer
labelClass="font-semibold"
field={FormRenderer.makeFieldInfo(
~label="Client Verification Key",
~name="client_verification_key",
~placeholder="hs_1234567890abcdef1234567890abcdef",
~customInput=InputFields.textInput(
~customStyle="rounded-xl bg-nd_gray-50",
~isDisabled=true,
),
~isRequired=false,
)}
/>
</div>
</RenderIf>
<div className="mt-10 w-full">
<FormRenderer.DesktopRow wrapperClass="!w-full" itemWrapperClass="!mx-0">
<FormRenderer.SubmitButton
text="Next"
customSumbitButtonStyle="rounded !w-full"
buttonType={Primary}
tooltipForWidthClass="w-full"
/>
</FormRenderer.DesktopRow>
</div>
<FormValuesSpy />
</>
}
}
| 1,987 | 9,407 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconConfiguration/ConnectProcessors/ConnectProcessorsUtils.res | .res | open LogicUtils
open ConnectProcessorsTypes
let processorFieldsConfig = dict => {
{
processor_type: dict->getString("processor_type", ""),
secret_key: dict->getString("secret_key", ""),
client_verification_key: dict->getString("client_verification_key", ""),
}
}
let validateProcessorFields = (values: JSON.t) => {
let data = values->getDictFromJsonObject->processorFieldsConfig
let errors = Dict.make()
let errorMessage = if data.processor_type->isEmptyString {
"Processor cannot be empty!"
} else {
""
}
if errorMessage->isNonEmptyString {
Dict.set(errors, "Error", errorMessage->JSON.Encode.string)
}
errors->JSON.Encode.object
}
| 156 | 9,408 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconConfiguration/Final/Final.res | .res | open VerticalStepIndicatorTypes
@react.component
let make = (~currentStep: step, ~setCurrentStep, ~setShowOnBoarding) => {
open ReconConfigurationUtils
open VerticalStepIndicatorUtils
let {setShowSideBar} = React.useContext(GlobalProvider.defaultContext)
let mixpanelEvent = MixpanelHook.useSendEvent()
let getNextStep = (currentStep: step): option<step> => {
findNextStep(sections, currentStep)
}
let onNextClick = () => {
switch getNextStep(currentStep) {
| Some(nextStep) => setCurrentStep(_ => nextStep)
| None => ()
}
setShowSideBar(_ => true)
RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url="/v2/recon/overview"))
setShowOnBoarding(_ => false)
}
let customSelectionComponent =
<>
<Icon name="nd-tick-circle" customHeight="16" />
<p className="font-semibold text-sm leading-5 text-nd_green-600">
{"Completed"->React.string}
</p>
</>
<div className="flex flex-col h-full gap-y-10">
<div className="flex flex-col h-full gap-y-10">
<ReconConfigurationHelper.SubHeading
title="Reconciliation Successful" subTitle="Explore all the Recon metrics in the dashboard"
/>
<div className="flex flex-col gap-6">
<ReconConfigurationHelper.StepCard
key="order_data_successful"
stepName="Order data connection successful"
description=""
isSelected=true
customSelectionComponent
iconName="nd-inbox-with-outline"
onClick={_ => ()}
customSelectionBorderClass="border-nd_br_gray-500"
/>
<ReconConfigurationHelper.StepCard
key="processor_data_sucessful"
stepName="Processor connection successful"
description=""
isSelected=true
customSelectionComponent
iconName="nd-plugin-with-outline"
onClick={_ => ()}
customSelectionBorderClass="border-nd_br_gray-500"
/>
</div>
</div>
<div className="flex justify-end items-center">
<Button
text="Start exploring"
customButtonStyle="rounded w-full"
buttonType={Primary}
buttonState={Normal}
onClick={_ => {
mixpanelEvent(~eventName="recon_onboarding_step3")
onNextClick()->ignore
}}
/>
</div>
</div>
}
| 546 | 9,409 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconConfiguration/OrderDataConnection/OrderDataConnection.res | .res | open VerticalStepIndicatorTypes
@react.component
let make = (~currentStep: step, ~setCurrentStep, ~selectedOrderSource, ~setSelectedOrderSource) => {
open APIUtils
open ReconConfigurationUtils
open OrderDataConnectionUtils
open VerticalStepIndicatorUtils
let mixpanelEvent = MixpanelHook.useSendEvent()
let updateDetails = useUpdateMethod()
let getURL = useGetURL()
let showToast = ToastState.useShowToast()
let getNextStep = (currentStep: step): option<step> => {
findNextStep(sections, currentStep)
}
let onNextClick = async () => {
try {
let url = getURL(~entityName=V1(USERS), ~userType=#USER_DATA, ~methodType=Post)
let body = getRequestBody(~isOrderDataSet=true, ~isProcessorDataSet=false)
let _ = await updateDetails(url, body->Identity.genericTypeToJson, Post)
switch getNextStep(currentStep) {
| Some(nextStep) => setCurrentStep(_ => nextStep)
| None => ()
}
} catch {
| Exn.Error(_err) =>
showToast(~message="Something went wrong. Please try again", ~toastType=ToastError)
}
}
let onSubmit = async () => {
mixpanelEvent(~eventName="recon_onboarding_step1")
let _ = await onNextClick()
}
<div className="flex flex-col h-full gap-y-10">
<ReconConfigurationHelper.SubHeading
title="Connect Order Data Source"
subTitle="Link your order data source to streamline the reconciliation process"
/>
<div className="flex flex-col h-full gap-y-10">
<div className="flex flex-col gap-y-4">
<p className="text-sm text-nd_gray-700 font-semibold">
{"Where do you want to fetch your data from?"->React.string}
</p>
<div className="flex flex-col gap-y-4">
{orderDataStepsArr
->Array.map(step => {
let stepName = step->getSelectedStepName
let description = step->getSelectedStepDescription
let isSelected = selectedOrderSource === step
<ReconConfigurationHelper.StepCard
key={stepName}
stepName={stepName}
description={description}
isSelected={isSelected}
iconName={step->getIconName}
onClick={_ => setSelectedOrderSource(_ => step)}
customSelectionComponent={<Icon name="nd-checkbox-base" customHeight="16" />}
isDisabled={step->isDisabled}
/>
})
->React.array}
</div>
</div>
<div className="flex justify-end items-center mx-0.5">
<Button
text="Next"
customButtonStyle="rounded w-full"
buttonType={Primary}
buttonState={Normal}
onClick={_ => onSubmit()->ignore}
/>
</div>
</div>
</div>
}
| 650 | 9,410 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconConfiguration/OrderDataConnection/OrderDataConnectionUtils.res | .res | open OrderDataConnectionTypes
let getSelectedStepName = step => {
switch step {
| ConnectYourOrderDataSource => "Connect your order data source"
| UploadFile => "Try with Sample Data"
}
}
let getSelectedStepDescription = step => {
switch step {
| ConnectYourOrderDataSource => "This feature is available in production only"
| UploadFile => "Explore with our pre-populated sample order data."
}
}
let isDisabled = step => {
switch step {
| ConnectYourOrderDataSource => true
| UploadFile => false
}
}
let orderDataStepsArr: array<orderDataSteps> = [UploadFile, ConnectYourOrderDataSource]
let getIconName = step => {
switch step {
| ConnectYourOrderDataSource => "nd-connect-your-order-data-source"
| UploadFile => "nd-upload-file"
}
}
| 187 | 9,411 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconConfiguration/OrderDataConnection/OrderDataConnectionTypes.res | .res | type orderDataSteps = ConnectYourOrderDataSource | UploadFile
| 13 | 9,412 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconOnboarding/ReconOnboardingHelper.res | .res | module ReconOnboardingLanding = {
@react.component
let make = () => {
open PageUtils
let {setCreateNewMerchant, activeProduct} = React.useContext(
ProductSelectionProvider.defaultContext,
)
let userHasCreateMerchantAccess = OMPCreateAccessHook.useOMPCreateAccessHook([
#tenant_admin,
#org_admin,
])
let mixpanelEvent = MixpanelHook.useSendEvent()
let onTryDemoClick = () => {
setCreateNewMerchant(ProductTypes.Recon)
}
let handleClick = () => {
if activeProduct == Recon {
RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="v2/recon/configuration"))
} else {
onTryDemoClick()
}
}
<div className="flex flex-1 flex-col gap-14 items-center justify-center w-full h-screen">
<img alt="reconOnboarding" src="/Recon/landing.svg" className="rounded-3xl" />
<div className="flex flex-col gap-8 items-center">
<div
className="border rounded-md text-nd_green-200 border-nd_green-200 font-semibold p-1.5 text-sm w-fit">
{"Reconciliation"->React.string}
</div>
<PageHeading
customHeadingStyle="gap-3 flex flex-col items-center"
title="Settlement reconciliation automation"
customTitleStyle="text-2xl text-center font-bold text-nd_gray-700 font-500"
customSubTitleStyle="text-fs-16 font-normal text-center max-w-700"
subTitle="Built for 10x financial & transactional accuracy"
/>
<ACLButton
authorization={userHasCreateMerchantAccess}
text="Try Demo"
onClick={_ => {
mixpanelEvent(~eventName="recon_try_demo")
handleClick()
}}
rightIcon={CustomIcon(<Icon name="nd-angle-right" size=15 />)}
customTextPaddingClass="pr-0"
buttonType=Primary
buttonSize=Large
buttonState=Normal
/>
</div>
</div>
}
}
module ListBaseComp = {
@react.component
let make = (
~heading="",
~subHeading,
~arrow,
~showEditIcon=false,
~onEditClick=_ => (),
~isDarkBg=false,
~showDropdownArrow=true,
~placeHolder="Select Processor",
) => {
let {globalUIConfig: {sidebarColor: {secondaryTextColor}}} = React.useContext(
ThemeProvider.themeContext,
)
let arrowClassName = isDarkBg
? `${arrow
? "rotate-180"
: "-rotate-0"} transition duration-[250ms] opacity-70 ${secondaryTextColor}`
: `${arrow
? "rotate-0"
: "rotate-180"} transition duration-[250ms] opacity-70 ${secondaryTextColor}`
let bgClass = subHeading->String.length > 0 ? "bg-white" : "bg-nd_gray-50"
<div
className={`flex flex-row cursor-pointer items-center py-5 px-4 gap-2 min-w-44 justify-between h-8 ${bgClass} border rounded-lg border-nd_gray-100 shadow-sm`}>
<div className="flex flex-row items-center gap-2">
<RenderIf condition={subHeading->String.length > 0}>
<p
className="overflow-scroll text-nowrap text-sm font-medium text-nd_gray-500 whitespace-pre ">
{subHeading->React.string}
</p>
</RenderIf>
<RenderIf condition={subHeading->String.length == 0}>
<p
className="overflow-scroll text-nowrap text-sm font-medium text-nd_gray-500 whitespace-pre ">
{placeHolder->React.string}
</p>
</RenderIf>
</div>
<RenderIf condition={showDropdownArrow}>
<Icon className={`${arrowClassName} ml-1`} name="nd-angle-down" size=12 />
</RenderIf>
</div>
}
}
module Card = {
@react.component
let make = (~title: string, ~value: string) => {
<div
className="flex flex-col gap-4 items-start border rounded-xl border-nd_gray-150 px-4 pt-3 pb-4">
<p className="text-nd_gray-400 text-xs leading-4 font-medium"> {title->React.string} </p>
<p className="text-nd_gray-800 font-semibold leading-8 text-2xl"> {value->React.string} </p>
</div>
}
}
module ReconCards = {
@react.component
let make = () => {
<div className="grid grid-cols-3 gap-6 mt-2">
<Card title="Automatic Reconciliation Rate" value="90%" />
<Card title="Total Reconciled Amount" value="$ 2,500,011" />
<Card title="Unreconciled Amount" value="$ 300,007" />
<Card title="Reconciled Orders" value="1800" />
<Card title="Unreconciled Orders" value="150" />
<Card title="Data Missing" value="50" />
</div>
}
}
module StackedBarGraphs = {
@react.component
let make = () => {
let isMiniLaptopView = MatchMedia.useMatchMedia("(max-width: 1600px)")
<div className="grid grid-cols-2 gap-6">
<div
className="flex flex-col space-y-2 items-start border rounded-xl border-nd_gray-150 px-4 pt-3 pb-4">
<p className="text-nd_gray-400 text-xs leading-5 font-medium">
{"Total Orders"->React.string}
</p>
<p className="text-nd_gray-800 font-semibold text-2xl leading-8">
{"2000"->React.string}
</p>
<div className="w-full">
<StackedBarGraph
options={StackedBarGraphUtils.getStackedBarGraphOptions(
{
categories: ["Total Orders"],
data: [
{
name: "Missing",
data: [50.0],
color: "#FEBBB2",
},
{
name: "Mismatch",
data: [150.0],
color: "#7F7F7F",
},
{
name: "Matched",
data: [1800.0],
color: "#1F77B4",
},
],
labelFormatter: StackedBarGraphUtils.stackedBarGraphLabelFormatter(
~statType=Default,
),
},
~yMax=2000,
~labelItemDistance={isMiniLaptopView ? 45 : 90},
)}
/>
</div>
</div>
<div
className="flex flex-col space-y-2 items-start border rounded-xl border-nd_gray-150 px-4 pt-3 pb-4">
<p className="text-nd_gray-400 text-xs leading-5 font-medium">
{"Total Amount"->React.string}
</p>
<p className="text-nd_gray-800 font-semibold text-2xl leading-8">
{"$ 2,879,147"->React.string}
</p>
<div className="w-full">
<StackedBarGraph
options={StackedBarGraphUtils.getStackedBarGraphOptions(
{
categories: ["Total Amount"],
data: [
{
name: "Missing",
data: [79129.0],
color: "#FEBBB2",
},
{
name: "Mismatch",
data: [300007.0],
color: "#A0872C",
},
{
name: "Matched",
data: [2500011.0],
color: "#17BECF",
},
],
labelFormatter: StackedBarGraphUtils.stackedBarGraphLabelFormatter(
~statType=FormattedAmount,
~currency="$",
),
},
~yMax=2879147,
~labelItemDistance={isMiniLaptopView ? 10 : 40},
)}
/>
</div>
</div>
</div>
}
}
module ExceptionCards = {
@react.component
let make = () => {
<div className="grid grid-cols-3 gap-6">
<Card title="Exceptions Transactions" value="150" />
<Card title="Average Aging Time" value="4.36" />
<Card title="Total Exception Value" value="$ 300,007" />
</div>
}
}
module ReconciliationOverview = {
@react.component
let make = () => {
open OMPSwitchTypes
open ReconOnboardingUtils
let (selectedReconId, setSelectedReconId) = React.useState(_ => "Recon_235")
let (reconList, _) = React.useState(_ => [{id: "Recon_235", name: "Recon_235"}])
let (arrow, setArrow) = React.useState(_ => false)
let input: ReactFinalForm.fieldRenderPropsInput = {
name: "name",
onBlur: _ => (),
onChange: ev => {
let value = ev->Identity.formReactEventToString
setSelectedReconId(_ => value)
},
onFocus: _ => (),
value: selectedReconId->JSON.Encode.string,
checked: true,
}
let toggleChevronState = () => {
setArrow(prev => !prev)
}
let navigateToExceptions = () => {
RescriptReactRouter.push(
GlobalVars.appendDashboardPath(~url="v2/recon/reports?tab=exceptions"),
)
}
let customScrollStyle = "max-h-72 overflow-scroll px-1 pt-1 border border-b-0"
let dropdownContainerStyle = "rounded-md border border-1 !w-full"
<div className="flex flex-col gap-6 w-full">
<div className="relative flex items-center justify-between w-full mt-12">
<PageUtils.PageHeading
title={"Reconciliation Overview"}
customTitleStyle="!text-2xl !leading-8 !font-semibold !text-nd_gray-700 !tracking-normal"
/>
<div className="flex flex-row gap-6 absolute bottom-0 right-0">
<Form>
<div className="flex flex-row gap-6">
<SelectBox.BaseDropdown
allowMultiSelect=false
buttonText=""
input
deselectDisable=true
customButtonStyle="!rounded-lg"
options={reconList->generateDropdownOptionsCustomComponent}
marginTop="mt-10"
hideMultiSelectButtons=true
addButton=false
baseComponent={<ListBaseComp heading="Recon" subHeading=selectedReconId arrow />}
customDropdownOuterClass="!border-none !w-full"
fullLength=true
toggleChevronState
customScrollStyle
dropdownContainerStyle
shouldDisplaySelectedOnTop=true
customSelectionIcon={CustomIcon(<Icon name="nd-check" />)}
/>
</div>
</Form>
</div>
</div>
<div
className="bg-nd_red-50 rounded-xl px-6 py-3 flex flex-row items-center justify-between self-stretch">
<div className="flex flex-row gap-4 items-center">
<div className="flex flex-row items-center gap-3">
<Icon name="nd-alert-triangle" size=24 />
<p className="text-nd_gray-700 font-semibold leading-5 text-center text-sm">
{"150 Exceptions Found"->React.string}
</p>
</div>
</div>
<div
className="flex items-center gap-1.5 cursor-pointer"
onClick={_ => navigateToExceptions()}>
<p className="text-nd_primary_blue-500 font-semibold leading-6 text-center text-sm">
{"View Details"->React.string}
</p>
<Icon name="nd-angle-right" size=16 className="text-nd_primary_blue-500" />
</div>
</div>
<ReconCards />
<StackedBarGraphs />
</div>
}
}
module Exceptions = {
@react.component
let make = () => {
let exceptionsAgingOptions: ColumnGraphTypes.columnGraphPayload = {
title: {
text: "",
},
data: [
{
showInLegend: false,
name: "Exceptions Aging",
colorByPoint: true,
data: [
{
name: "1 Day",
y: 13711.0,
color: "#DB88C1",
},
{
name: "2 Day",
y: 44579.0,
color: "#DB88C1",
},
{
name: "3 Day",
y: 40510.0,
color: "#DB88C1",
},
{
name: "4 Day",
y: 48035.0,
color: "#DB88C1",
},
{
name: "5 Day",
y: 51640.0,
color: "#DB88C1",
},
{
name: "6 Day",
y: 51483.0,
color: "#DB88C1",
},
{
name: "7 Day",
y: 50049.0,
color: "#DB88C1",
},
],
color: "",
},
],
tooltipFormatter: ColumnGraphUtils.columnGraphTooltipFormatter(
~title="Exceptions Aging",
~metricType=FormattedAmount,
),
yAxisFormatter: ColumnGraphUtils.columnGraphYAxisFormatter(
~statType=FormattedAmount,
~currency="$",
),
}
let unmatchedTransactionsOptions: ColumnGraphTypes.columnGraphPayload = {
title: {
text: "",
},
data: [
{
showInLegend: false,
name: "Unmatched Transactions",
colorByPoint: true,
data: [
{
name: "Status Mismatch",
y: 50.0,
color: "#BCBD22",
},
{
name: "Amount Mismatch",
y: 50.0,
color: "#72BEF4",
},
{
name: "Both",
y: 50.0,
color: "#4B6D8C",
},
],
color: "",
},
],
tooltipFormatter: ColumnGraphUtils.columnGraphTooltipFormatter(
~title="Unmatched Transactions",
~metricType=Default,
),
yAxisFormatter: ColumnGraphUtils.columnGraphYAxisFormatter(~statType=Default),
}
<div className="flex flex-col gap-6 w-full">
<div className="flex items-center justify-between w-full mt-12">
<PageUtils.PageHeading
title={"Exceptions"}
customTitleStyle=" !text-2xl !leading-8 !font-semibold !text-nd_gray-600 !tracking-normal"
/>
</div>
<ExceptionCards />
<div className="grid grid-cols-2 gap-6">
<div
className="flex flex-col gap-6 items-start border rounded-xl border-nd_gray-150 px-4 pt-3 pb-4">
<p className="text-nd_gray-600 text-sm leading-5 font-medium">
{"Exceptions Aging"->React.string}
</p>
<div className="w-full">
<ColumnGraph options={ColumnGraphUtils.getColumnGraphOptions(exceptionsAgingOptions)} />
</div>
</div>
<div
className="flex flex-col gap-6 items-start border rounded-xl border-nd_gray-150 px-4 pt-3 pb-4">
<p className="text-nd_gray-600 text-sm leading-5 font-medium">
{"Unmatched Transactions"->React.string}
</p>
<div className="w-full">
<ColumnGraph
options={ColumnGraphUtils.getColumnGraphOptions(unmatchedTransactionsOptions)}
/>
</div>
</div>
</div>
</div>
}
}
module ReconOverviewContent = {
@react.component
let make = () => {
let mixpanelEvent = MixpanelHook.useSendEvent()
let {setShowSideBar} = React.useContext(GlobalProvider.defaultContext)
React.useEffect(() => {
mixpanelEvent(~eventName="recon_analytics_overview")
setShowSideBar(_ => true)
None
}, [])
<div>
<div
className="absolute z-10 top-76-px left-0 w-full py-3 px-10 bg-orange-50 flex justify-between items-center">
<div className="flex gap-4 items-center">
<Icon name="nd-information-triangle" size=24 />
<p className="text-nd_gray-600 text-base leading-6 font-medium">
{"You're viewing sample analytics to help you understand how the reports will look with real data"->React.string}
</p>
</div>
<ReconHelper.GetProductionAccess />
</div>
<ReconciliationOverview />
<Exceptions />
</div>
}
}
| 3,963 | 9,413 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconOnboarding/ReconOnboardingUtils.res | .res | let generateDropdownOptionsCustomComponent: array<OMPSwitchTypes.ompListTypes> => array<
SelectBox.dropdownOption,
> = dropdownList => {
let options: array<SelectBox.dropdownOption> = dropdownList->Array.map((
item
): SelectBox.dropdownOption => {
let option: SelectBox.dropdownOption = {
label: item.name,
value: item.id,
}
option
})
options
}
| 94 | 9,414 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconReports/ShowReconExceptionReport.res | .res | module ShowOrderDetails = {
@react.component
let make = (
~data,
~getHeading,
~getCell,
~detailsFields,
~justifyClassName="justify-start",
~widthClass="w-1/3",
~bgColor="bg-white dark:bg-jp-gray-lightgray_background",
~isButtonEnabled=false,
~border="border border-jp-gray-940 border-opacity-75 dark:border-jp-gray-960",
~customFlex="flex-wrap",
~isHorizontal=false,
) => {
<FormRenderer.DesktopRow>
<div
className={`flex ${customFlex} ${justifyClassName} dark:bg-jp-gray-lightgray_background dark:border-jp-gray-no_data_border `}>
{detailsFields
->Array.mapWithIndex((colType, i) => {
<div className=widthClass key={i->Int.toString}>
<ReconReportsHelper.DisplayKeyValueParams
heading={getHeading(colType)}
value={getCell(data, colType)}
customMoneyStyle="!font-normal !text-sm"
labelMargin="!py-0 mt-2"
overiddingHeadingStyles="text-nd_gray-400 text-sm font-medium"
isHorizontal
/>
</div>
})
->React.array}
</div>
</FormRenderer.DesktopRow>
}
}
module OrderInfo = {
@react.component
let make = (~exceptionReportDetails) => {
open ReportsExceptionTableEntity
<div className="w-full pb-6 border-b border-nd_gray-150">
<ShowOrderDetails
data=exceptionReportDetails
getHeading
getCell
detailsFields=[
TransactionId,
OrderId,
TransactionDate,
PaymentGateway,
PaymentMethod,
TxnAmount,
SettlementAmount,
ExceptionType,
]
isButtonEnabled=true
/>
</div>
}
}
@react.component
let make = (~showOnBoarding, ~id) => {
open LogicUtils
open ReconExceptionsUtils
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let showToast = ToastState.useShowToast()
let (offset, setOffset) = React.useState(_ => 0)
let (reconExceptionReport, setReconExceptionReport) = React.useState(_ =>
Dict.make()->ReconExceptionsUtils.getExceptionReportPayloadType
)
let (attemptData, setAttemptData) = React.useState(_ => [])
let (showModal, setShowModal) = React.useState(_ => false)
let defaultObject = Dict.make()->ReconExceptionsUtils.getExceptionReportPayloadType
let fetchApi = AuthHooks.useApiFetcher()
let fetchOrderDetails = async _ => {
if showOnBoarding {
RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url="/v2/recon"))
} else {
try {
setScreenState(_ => Loading)
let url = `${GlobalVars.getHostUrl}/test-data/recon/reconExceptions.json`
let exceptionsResponse = await fetchApi(
url,
~method_=Get,
~xFeatureRoute=false,
~forceCookies=false,
)
let res = await exceptionsResponse->(res => res->Fetch.Response.json)
let data =
res
->getDictFromJsonObject
->getArrayFromDict("data", [])
->ReconExceptionsUtils.getArrayOfReportsListPayloadType
let selectedDataArray = data->Array.filter(item => {item.transaction_id == id})
let selectedDataObject = selectedDataArray->getValueFromArray(0, defaultObject)
let exceptionMatrixArray = selectedDataObject.exception_matrix
setAttemptData(_ => exceptionMatrixArray)
setReconExceptionReport(_ => selectedDataObject)
setScreenState(_ => Success)
} catch {
| Exn.Error(e) =>
switch Exn.message(e) {
| Some(message) =>
if message->String.includes("HE_02") {
setScreenState(_ => Custom)
} else {
showToast(~message="Failed to Fetch!", ~toastType=ToastState.ToastError)
setScreenState(_ => Error("Failed to Fetch!"))
}
| None => setScreenState(_ => Error("Failed to Fetch!"))
}
}
}
}
React.useEffect(() => {
fetchOrderDetails()->ignore
None
}, [])
let modalHeading = {
<div className="flex justify-between border-b">
<div className="flex gap-4 items-center my-5">
<p className="font-semibold text-nd_gray-700 px-6 leading-5 text-lg">
{"Resolve Issue"->React.string}
</p>
</div>
<Icon
name="modal-close-icon"
className="cursor-pointer mr-4"
size=30
onClick={_ => setShowModal(_ => false)}
/>
</div>
}
let onSubmit = async (_values, _form: ReactFinalForm.formApi) => {
showToast(~message="Resolved Successfully!", ~toastType=ToastState.ToastSuccess)
setReconExceptionReport(_ => {...reconExceptionReport, exception_type: "Resolved"})
setShowModal(_ => false)
Nullable.null
}
<div className="flex flex-col gap-8">
<BreadCrumbNavigation
path=[{title: "Recon", link: `/v2/recon/reports?tab=exceptions`}]
currentPageTitle="Exceptions Summary"
cursorStyle="cursor-pointer"
customTextClass="text-nd_gray-400"
titleTextClass="text-nd_gray-600 font-medium"
fontWeight="font-medium"
dividerVal=Slash
childGapClass="gap-2"
/>
<div className="flex flex-col gap-4">
<div className="flex flex-row justify-between items-center">
<div className="flex gap-6 items-center">
<PageUtils.PageHeading title={`Transaction ID: ${reconExceptionReport.transaction_id}`} />
{switch reconExceptionReport.exception_type->getExceptionsStatusTypeFromString {
| AmountMismatch
| StatusMismatch
| Both =>
<div
className="text-sm text-white font-semibold px-3 py-1 rounded-md bg-nd_red-50 dark:bg-opacity-50 flex gap-2">
<p className="text-nd_red-400">
{reconExceptionReport.exception_type
->getExceptionsStatusTypeFromString
->getExceptionStringFromStatus
->React.string}
</p>
</div>
| Resolved =>
<div
className="text-sm text-white font-semibold px-3 py-1 rounded-md bg-nd_green-50 dark:bg-opacity-50 flex gap-2">
<p className="text-nd_green-400"> {"Resolved"->React.string} </p>
</div>
}}
</div>
<RenderIf
condition={reconExceptionReport.exception_type->getExceptionsStatusTypeFromString !=
Resolved}>
<ACLButton
text="Resolve Issue"
customButtonStyle="!w-fit"
buttonType={Primary}
onClick={_ => setShowModal(_ => true)}
/>
</RenderIf>
</div>
<div className="w-full py-3 px-4 bg-orange-50 flex justify-between items-center rounded-lg">
<div className="flex gap-4 items-center">
<Icon name="nd-hour-glass" size=16 />
<p className="text-nd_gray-600 text-base leading-6 font-medium">
{"Payment Gateway processed the payment, but no matching record exists in the bank statement (Settlement Missing)."->React.string}
</p>
</div>
</div>
<PageLoaderWrapper
screenState
customUI={<NoDataFound
message="Payment does not exists in out record" renderType=NotFound
/>}>
<OrderInfo exceptionReportDetails=reconExceptionReport />
<LoadedTable
title="Exception Matrix"
actualData={attemptData->Array.map(Nullable.make)}
entity={ReportsExceptionTableEntity.exceptionAttemptsEntity()}
totalResults={attemptData->Array.length}
resultsPerPage=20
offset
setOffset
currrentFetchCount={attemptData->Array.length}
/>
</PageLoaderWrapper>
</div>
<Modal
setShowModal
showModal
closeOnOutsideClick=true
modalClass="w-full max-w-xl mx-auto my-auto dark:!bg-jp-gray-lightgray_background"
childClass="m-4 h-full"
customModalHeading=modalHeading>
<div className="flex flex-col gap-4">
<Form onSubmit validate={validateNoteField} initialValues={Dict.make()->JSON.Encode.object}>
<FormRenderer.FieldRenderer
labelClass="font-semibold"
field={FormRenderer.makeFieldInfo(
~label="Add a Note",
~name="note",
~placeholder="You can log comments",
~customInput=InputFields.multiLineTextInput(
~isDisabled=false,
~rows=Some(4),
~cols=Some(50),
~maxLength=500,
~customClass="!h-28 !rounded-xl",
),
~isRequired=true,
)}
/>
<FormRenderer.DesktopRow wrapperClass="!w-full" itemWrapperClass="!mx-0.5">
<FormRenderer.SubmitButton
tooltipForWidthClass="w-full"
text="Done"
buttonType={Primary}
customSumbitButtonStyle="!w-full mt-4"
/>
</FormRenderer.DesktopRow>
</Form>
</div>
</Modal>
</div>
}
| 2,123 | 9,415 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconReports/ReconReports.res | .res | @react.component
let make = (~showOnBoarding) => {
open LogicUtils
open OMPSwitchTypes
open ReconOnboardingUtils
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let showToast = ToastState.useShowToast()
let url = RescriptReactRouter.useUrl()
let (tabIndex, setTabIndex) = React.useState(_ => 0)
let setCurrentTabName = Recoil.useSetRecoilState(HyperswitchAtom.currentTabNameRecoilAtom)
let (selectedReconId, setSelectedReconId) = React.useState(_ => "Recon_235")
let mixpanelEvent = MixpanelHook.useSendEvent()
let fetchApi = AuthHooks.useApiFetcher()
let (reconList, _) = React.useState(_ => [{id: "Recon_235", name: "Recon_235"}])
let (reconArrow, setReconArrow) = React.useState(_ => false)
let getTabName = index => index == 0 ? "All" : "Exceptions"
React.useEffect(() => {
switch url.search->ReconReportUtils.getTabFromUrl {
| Exceptions => {
mixpanelEvent(~eventName="recon_exceptions_reports")
setTabIndex(_ => 1)
}
| All => {
mixpanelEvent(~eventName="recon_all_reports")
setTabIndex(_ => 0)
}
}
setScreenState(_ => PageLoaderWrapper.Success)
None
}, [url.search])
let convertArrayToCSV = arr => {
let headers = ReconReportUtils.getHeadersForCSV()
let csv =
arr
->Array.map(row => row->Array.joinWith(","))
->Array.joinWith("\n")
headers ++ "\n" ++ csv
}
let downloadReport = async () => {
try {
let url = `${GlobalVars.getHostUrl}/test-data/recon/reconAllReports.json`
let allReportsResponse = await fetchApi(
`${url}`,
~method_=Get,
~xFeatureRoute=false,
~forceCookies=false,
)
let response = await allReportsResponse->(res => res->Fetch.Response.json)
let reportsList =
response
->getDictFromJsonObject
->getArrayFromDict("data", [])
->ReconReportUtils.getArrayOfReportsListPayloadType
let arr = reportsList->Array.map((obj: ReportsTypes.allReportPayload) => {
let row = [
obj.order_id,
obj.transaction_id,
obj.payment_gateway,
obj.payment_method,
obj.txn_amount->Float.toString,
obj.settlement_amount->Float.toString,
obj.recon_status,
obj.transaction_date,
]
row
})
let csvContent = arr->convertArrayToCSV
DownloadUtils.download(
~fileName=`${selectedReconId}_Reconciliation_Report.csv`,
~content=csvContent,
~fileType="text/csv",
)
showToast(~message="Report downloaded successfully", ~toastType=ToastSuccess)
} catch {
| _ => showToast(~message="Failed to download report", ~toastType=ToastError)
}
}
let tabs: array<Tabs.tab> = React.useMemo(() => {
open Tabs
[
{
title: "All",
renderContent: () => <ReconReportsList />,
onTabSelection: () => {
RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url="/v2/recon/reports"))
},
},
{
title: "Exceptions",
renderContent: () => <ReconExceptionsList />,
onTabSelection: () => {
RescriptReactRouter.replace(
GlobalVars.appendDashboardPath(~url="/v2/recon/reports?tab=exceptions"),
)
},
},
]
}, [])
let reconInput: ReactFinalForm.fieldRenderPropsInput = {
name: "name",
onBlur: _ => (),
onChange: ev => {
let value = ev->Identity.formReactEventToString
setSelectedReconId(_ => value)
},
onFocus: _ => (),
value: selectedReconId->JSON.Encode.string,
checked: true,
}
let toggleReconChevronState = () => {
setReconArrow(prev => !prev)
}
let customScrollStyle = "max-h-72 overflow-scroll px-1 pt-1 border border-b-0"
let dropdownContainerStyle = "rounded-md border border-1 !w-full"
<div>
<RenderIf condition={showOnBoarding}>
<div className="my-4">
<NoDataFound
message={"Please complete the demo setup to view the sample reports."}
renderType={Painting}
/>
</div>
</RenderIf>
<RenderIf condition={!showOnBoarding}>
<div
className="absolute z-10 top-76-px left-0 w-full py-3 px-10 bg-orange-50 flex justify-between items-center">
<div className="flex gap-4 items-center">
<Icon name="nd-information-triangle" size=24 />
<p className="text-nd_gray-600 text-base leading-6 font-medium">
{"You're viewing sample analytics to help you understand how the reports will look with real data"->React.string}
</p>
</div>
<ReconHelper.GetProductionAccess />
</div>
<div className="flex flex-col space-y-2 justify-center relative gap-4 mt-12">
<div>
<div className="flex justify-between items-center">
<p className="text-2xl font-semibold text-nd_gray-700">
{"Reconciliation Reports"->React.string}
</p>
<div className="flex flex-row gap-4">
<div className="flex flex-row gap-6">
<SelectBox.BaseDropdown
allowMultiSelect=false
buttonText=""
input=reconInput
deselectDisable=true
customButtonStyle="!rounded-lg"
options={reconList->generateDropdownOptionsCustomComponent}
marginTop="mt-10"
hideMultiSelectButtons=true
addButton=false
baseComponent={<ReconReportsHelper.ListBaseComp
heading="Recon" subHeading=selectedReconId arrow=reconArrow
/>}
customDropdownOuterClass="!border-none !w-full"
fullLength=true
toggleChevronState=toggleReconChevronState
customScrollStyle
dropdownContainerStyle
shouldDisplaySelectedOnTop=true
customSelectionIcon={CustomIcon(<Icon name="nd-check" />)}
/>
</div>
<Button
text="Download Reports"
buttonType={Secondary}
leftIcon={Button.CustomIcon(<Icon name="nd-download-bar-down" size=14 />)}
onClick={_ => {
mixpanelEvent(~eventName="recon_generate_reports_download")
downloadReport()->ignore
}}
buttonSize={Medium}
/>
</div>
</div>
<PageLoaderWrapper screenState>
<div className="flex flex-col relative">
<Tabs
initialIndex={tabIndex >= 0 ? tabIndex : 0}
tabs
showBorder=true
includeMargin=false
defaultClasses="!w-max flex flex-auto flex-row items-center justify-center px-6 font-semibold text-body"
onTitleClick={indx => {
setTabIndex(_ => indx)
setCurrentTabName(_ => getTabName(indx))
}}
selectTabBottomBorderColor="bg-primary"
customBottomBorderColor="bg-nd_gray-150"
/>
</div>
</PageLoaderWrapper>
</div>
</div>
</RenderIf>
</div>
}
| 1,695 | 9,416 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconReports/ReportsExceptionTableEntity.res | .res | open ReportsTypes
open ReconExceptionsUtils
let defaultColumns: array<exceptionColtype> = [
OrderId,
TransactionId,
PaymentGateway,
PaymentMethod,
TxnAmount,
SettlementAmount,
ExceptionType,
TransactionDate,
]
let exceptionMatrixColumns: array<exceptionMatrixColType> = [
Source,
OrderId,
TxnAmount,
PaymentGateway,
SettlementDate,
FeeAmount,
]
let getHeading = (colType: exceptionColtype) => {
switch colType {
| TransactionId => Table.makeHeaderInfo(~key="transaction_id", ~title="Transaction ID")
| OrderId => Table.makeHeaderInfo(~key="order_id", ~title="Order ID")
| PaymentGateway => Table.makeHeaderInfo(~key="payment_gateway", ~title="Payment Gateway")
| PaymentMethod => Table.makeHeaderInfo(~key="payment_method", ~title="Payment Method")
| TxnAmount => Table.makeHeaderInfo(~key="txn_amount", ~title="Transaction Amount ($)")
| SettlementAmount =>
Table.makeHeaderInfo(~key="settlement_amount", ~title="Settlement Amount ($)")
| TransactionDate => Table.makeHeaderInfo(~key="transaction_date", ~title="Transaction Date")
| ExceptionType => Table.makeHeaderInfo(~key="exception_type", ~title="Exception Type")
}
}
let getCell = (report: reportExceptionsPayload, colType: exceptionColtype): Table.cell => {
switch colType {
| TransactionId => Text(report.transaction_id)
| OrderId => Text(report.order_id)
| PaymentGateway =>
CustomCell(
<HelperComponents.ConnectorCustomCell
connectorName=report.payment_gateway connectorType={Processor}
/>,
"",
)
| PaymentMethod => Text(report.payment_method)
| ExceptionType =>
CustomCell(
<HelperComponents.EllipsisText showCopy=false displayValue={report.exception_type} />,
"",
)
| TransactionDate => EllipsisText(report.transaction_date, "")
| TxnAmount => Text(Float.toString(report.txn_amount))
| SettlementAmount => Text(Float.toString(report.settlement_amount))
}
}
let getExceptionMatrixCell = (
report: exceptionMatrixPayload,
colType: exceptionMatrixColType,
): Table.cell => {
switch colType {
| Source => Text(report.source)
| OrderId => Text(report.order_id)
| TxnAmount => Text(Float.toString(report.txn_amount))
| PaymentGateway =>
CustomCell(
<HelperComponents.ConnectorCustomCell
connectorName=report.payment_gateway connectorType={Processor}
/>,
"",
)
| SettlementDate => Text(`Expected: ${report.settlement_date->String.slice(~start=0, ~end=5)}`)
| FeeAmount => Text(Float.toString(report.txn_amount))
}
}
let getExceptionMatrixHeading = (colType: exceptionMatrixColType) => {
switch colType {
| Source => Table.makeHeaderInfo(~key="transaction_id", ~title="Source")
| OrderId => Table.makeHeaderInfo(~key="order_id", ~title="Order ID")
| PaymentGateway => Table.makeHeaderInfo(~key="payment_gateway", ~title="Payment Gateway")
| TxnAmount => Table.makeHeaderInfo(~key="txn_amount", ~title="Transaction Amount ($)")
| SettlementDate => Table.makeHeaderInfo(~key="settlement_date", ~title="Settlement Date")
| FeeAmount => Table.makeHeaderInfo(~key="fee_amount", ~title="Fee Amount ($)")
}
}
let exceptionReportsEntity = (path: string, ~authorization: CommonAuthTypes.authorization) => {
EntityType.makeEntity(
~uri=``,
~getObjects=getExceptionReportsList,
~defaultColumns,
~getHeading,
~getCell,
~dataKey="reports",
~getShowLink={
connec =>
GroupAccessUtils.linkForGetShowLinkViaAccess(
~url=GlobalVars.appendDashboardPath(~url=`/${path}/${connec.transaction_id}`),
~authorization,
)
},
)
}
let exceptionAttemptsEntity = () => {
EntityType.makeEntity(
~uri=``,
~defaultColumns=exceptionMatrixColumns,
~getObjects=getExceptionMatrixList,
~getHeading=getExceptionMatrixHeading,
~getCell=getExceptionMatrixCell,
~dataKey="exception_matrix",
)
}
| 935 | 9,417 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconReports/ReportsTypes.res | .res | type url = All | Exceptions
type reconStatus = Reconciled | Unreconciled | Missing
type exceptionType = AmountMismatch | StatusMismatch | Both | Resolved
type reportCommonPayload = {
transaction_id: string,
order_id: string,
payment_gateway: string,
payment_method: string,
txn_amount: float,
recon_status: string,
transaction_date: string,
settlement_amount: float,
}
type allReportPayload = {
...reportCommonPayload,
}
type exceptionMatrixPayload = {
source: string,
order_id: string,
txn_amount: float,
payment_gateway: string,
settlement_date: string,
fee_amount: float,
}
type reportExceptionsPayload = {
...reportCommonPayload,
exception_type: string,
exception_matrix: array<exceptionMatrixPayload>,
}
type commonColType =
| TransactionId
| OrderId
| PaymentGateway
| PaymentMethod
| TxnAmount
| SettlementAmount
| TransactionDate
type allColtype = ReconStatus | ...commonColType
type exceptionColtype =
| ...commonColType
| ExceptionType
type exceptionMatrixColType =
| Source
| OrderId
| TxnAmount
| PaymentGateway
| SettlementDate
| FeeAmount
| 283 | 9,418 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconReports/ReconExceptionsList.res | .res | @react.component
let make = () => {
open LogicUtils
let (offset, setOffset) = React.useState(_ => 0)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (configuredReports, setConfiguredReports) = React.useState(_ => [])
let (filteredReportsData, setFilteredReports) = React.useState(_ => [])
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
let (searchText, setSearchText) = React.useState(_ => "")
let fetchApi = AuthHooks.useApiFetcher()
let getReportsList = async _ => {
try {
setScreenState(_ => PageLoaderWrapper.Loading)
let url = `${GlobalVars.getHostUrl}/test-data/recon/reconExceptions.json`
let exceptionsResponse = await fetchApi(
url,
~method_=Get,
~xFeatureRoute=false,
~forceCookies=false,
)
let response = await exceptionsResponse->(res => res->Fetch.Response.json)
let data = response->getDictFromJsonObject->getArrayFromDict("data", [])
let reportsList = data->ReconExceptionsUtils.getArrayOfReportsListPayloadType
setConfiguredReports(_ => reportsList)
setFilteredReports(_ => reportsList->Array.map(Nullable.make))
setScreenState(_ => Success)
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Error("Failed to fetch"))
}
}
let filterLogic = ReactDebounce.useDebounced(ob => {
let (searchText, arr) = ob
let filteredList = if searchText->isNonEmptyString {
arr->Array.filter((obj: Nullable.t<ReportsTypes.reportExceptionsPayload>) => {
switch Nullable.toOption(obj) {
| Some(obj) =>
isContainingStringLowercase(obj.transaction_id, searchText) ||
isContainingStringLowercase(obj.order_id, searchText) ||
isContainingStringLowercase(obj.exception_type, searchText)
| None => false
}
})
} else {
arr
}
setFilteredReports(_ => filteredList)
}, ~wait=200)
React.useEffect(() => {
getReportsList()->ignore
None
}, [])
<PageLoaderWrapper screenState>
<div className="mt-8">
<RenderIf condition={configuredReports->Array.length === 0}>
<div className="my-4">
<NoDataFound message={"No data available"} renderType={Painting} />
</div>
</RenderIf>
<div className="flex flex-col mx-auto w-full h-full mt-5 ">
<RenderIf condition={configuredReports->Array.length > 0}>
<LoadedTableWithCustomColumns
title="Exception Reports"
actualData={filteredReportsData}
entity={ReportsExceptionTableEntity.exceptionReportsEntity(
`v2/recon/reports`,
~authorization=userHasAccess(~groupAccess=UsersManage),
)}
resultsPerPage=10
filters={<TableSearchFilter
data={configuredReports->Array.map(Nullable.make)}
filterLogic
placeholder="Search Transaction Id or Order Id or Exception Type"
customSearchBarWrapperWidth="w-full lg:w-1/2"
searchVal=searchText
setSearchVal=setSearchText
/>}
showSerialNumber=false
totalResults={filteredReportsData->Array.length}
offset
setOffset
currrentFetchCount={configuredReports->Array.length}
customColumnMapper=TableAtoms.reconExceptionReportsDefaultCols
defaultColumns={ReportsExceptionTableEntity.defaultColumns}
showSerialNumberInCustomizeColumns=false
sortingBasedOnDisabled=false
hideTitle=true
remoteSortEnabled=true
customizeColumnButtonIcon="nd-filter-horizontal"
hideRightTitleElement=true
showAutoScroll=true
/>
</RenderIf>
</div>
</div>
</PageLoaderWrapper>
}
| 848 | 9,419 |
hyperswitch-control-center | src/Recon/ReconScreens/ReconReports/ReportStatus.res | .res | open ReconReportUtils
open ReportsTypes
let useGetAllReportStatus = (order: allReportPayload) => {
let orderStatusLabel = order.recon_status->LogicUtils.capitalizeString
let fixedStatusCss = "text-xs text-white font-semibold px-2 py-1 rounded flex items-center gap-2"
switch order.recon_status->getReconStatusTypeFromString {
| Reconciled =>
<div className={`${fixedStatusCss} bg-nd_green-50 dark:bg-opacity-50`}>
<p className="text-nd_green-400"> {orderStatusLabel->React.string} </p>
</div>
| Unreconciled =>
<div className={`${fixedStatusCss} bg-nd_red-50 dark:bg-opacity-50`}>
<p className="text-nd_red-400"> {orderStatusLabel->React.string} </p>
</div>
| Missing =>
<div className={`${fixedStatusCss} bg-orange-50 dark:bg-opacity-50`}>
<p className="text-orange-400"> {orderStatusLabel->React.string} </p>
</div>
}
}
| 254 | 9,420 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.