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/screens/NewAnalytics/NewRefundsAnalytics/RefundsProcessed/RefundsProcessedTypes.res | .res | type refundsProcessedCols =
| Refund_Processed_Amount
| Refund_Processed_Count
| Total_Refund_Processed_Amount
| Total_Refund_Processed_Count
| Time_Bucket
type responseKeys = [
| #refund_processed_amount
| #refund_processed_amount_in_usd
| #refund_processed_count
| #total_refund_processed_amount
| #total_refund_processed_amount_in_usd
| #total_refund_processed_count
| #time_bucket
]
type refundsProcessedObject = {
refund_processed_amount: float,
refund_processed_count: int,
total_refund_processed_amount: float,
total_refund_processed_count: int,
time_bucket: string,
}
| 158 | 9,621 |
hyperswitch-control-center | src/screens/NewAnalytics/NewRefundsAnalytics/RefundsSuccessRate/RefundsSuccessRateTypes.res | .res | type successRateCols =
| Refund_Success_Rate
| Total_Refund_Success_Rate
| Time_Bucket
type payments_success_rate = {
refund_success_rate: float,
total_refund_success_rate: float,
time_bucket: string,
}
| 57 | 9,622 |
hyperswitch-control-center | src/screens/NewAnalytics/NewRefundsAnalytics/RefundsSuccessRate/RefundsSuccessRate.res | .res | open NewAnalyticsTypes
open NewAnalyticsHelper
open LineGraphTypes
open RefundsSuccessRateUtils
module PaymentsSuccessRateHeader = {
open NewAnalyticsUtils
open LogicUtils
@react.component
let make = (~data, ~keyValue, ~granularity, ~setGranularity, ~granularityOptions) => {
let setGranularity = value => {
setGranularity(_ => value)
}
let {filterValueJson} = React.useContext(FilterContext.filterContext)
let comparison = filterValueJson->getString("comparison", "")->DateRangeUtils.comparisonMapprer
let featureFlag = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let primaryValue = getMetaDataValue(~data, ~index=0, ~key=keyValue)
let secondaryValue = getMetaDataValue(~data, ~index=1, ~key=keyValue)
let (value, direction) = calculatePercentageChange(~primaryValue, ~secondaryValue)
<div className="w-full px-7 py-8 grid grid-cols-3">
<div className="flex gap-2 items-center">
<div className="text-fs-28 font-semibold">
{primaryValue->valueFormatter(Rate)->React.string}
</div>
<RenderIf condition={comparison == EnableComparison}>
<StatisticsCard value direction tooltipValue={secondaryValue->valueFormatter(Rate)} />
</RenderIf>
</div>
<div className="flex justify-center">
<RenderIf condition={featureFlag.granularity}>
<Tabs
option={granularity}
setOption={setGranularity}
options={granularityOptions}
showSingleTab=false
/>
</RenderIf>
</div>
<div />
</div>
}
}
@react.component
let make = (
~entity: moduleEntity,
~chartEntity: chartEntity<lineGraphPayload, lineGraphOptions, JSON.t>,
) => {
open LogicUtils
open APIUtils
open NewAnalyticsUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let isoStringToCustomTimeZone = TimeZoneHook.useIsoStringToCustomTimeZone()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (paymentsSuccessRateData, setPaymentsSuccessRateData) = React.useState(_ =>
JSON.Encode.array([])
)
let (paymentsSuccessRateMetaData, setpaymentsProcessedMetaData) = React.useState(_ =>
JSON.Encode.array([])
)
let {filterValueJson} = React.useContext(FilterContext.filterContext)
let startTimeVal = filterValueJson->getString("startTime", "")
let endTimeVal = filterValueJson->getString("endTime", "")
let compareToStartTime = filterValueJson->getString("compareToStartTime", "")
let compareToEndTime = filterValueJson->getString("compareToEndTime", "")
let comparison = filterValueJson->getString("comparison", "")->DateRangeUtils.comparisonMapprer
let currency = filterValueJson->getString((#currency: filters :> string), "")
let featureFlag = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let granularityOptions = getGranularityOptions(~startTime=startTimeVal, ~endTime=endTimeVal)
let defaulGranularity = getDefaultGranularity(
~startTime=startTimeVal,
~endTime=endTimeVal,
~granularity=featureFlag.granularity,
)
let (granularity, setGranularity) = React.useState(_ => defaulGranularity)
React.useEffect(() => {
if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString {
setGranularity(_ => defaulGranularity)
}
None
}, (startTimeVal, endTimeVal))
let getPaymentsSuccessRate = async () => {
setScreenState(_ => PageLoaderWrapper.Loading)
try {
let url = getURL(
~entityName=V1(ANALYTICS_REFUNDS),
~methodType=Post,
~id=Some((entity.domain: domain :> string)),
)
let primaryBody = requestBody(
~startTime=startTimeVal,
~endTime=endTimeVal,
~delta=entity.requestBodyConfig.delta,
~metrics=entity.requestBodyConfig.metrics,
~granularity=granularity.value->Some,
~filter=generateFilterObject(~globalFilters=filterValueJson)->Some,
)
let secondaryBody = requestBody(
~startTime=compareToStartTime,
~endTime=compareToEndTime,
~delta=entity.requestBodyConfig.delta,
~metrics=entity.requestBodyConfig.metrics,
~granularity=granularity.value->Some,
~filter=generateFilterObject(~globalFilters=filterValueJson)->Some,
)
let primaryResponse = await updateDetails(url, primaryBody, Post)
let primaryData = primaryResponse->getDictFromJsonObject->getArrayFromDict("queryData", [])
let primaryMetaData = primaryResponse->getDictFromJsonObject->getArrayFromDict("metaData", [])
let (secondaryMetaData, secondaryModifiedData) = switch comparison {
| EnableComparison => {
let secondaryResponse = await updateDetails(url, secondaryBody, Post)
let secondaryData =
secondaryResponse->getDictFromJsonObject->getArrayFromDict("queryData", [])
let secondaryMetaData =
secondaryResponse->getDictFromJsonObject->getArrayFromDict("metaData", [])
let secondaryModifiedData = [secondaryData]->Array.map(data => {
fillMissingDataPoints(
~data,
~startDate=compareToStartTime,
~endDate=compareToEndTime,
~timeKey="time_bucket",
~defaultValue={
"payment_count": 0,
"payment_processed_amount": 0,
"time_bucket": startTimeVal,
}->Identity.genericTypeToJson,
~isoStringToCustomTimeZone,
~granularity=granularity.value,
~granularityEnabled=featureFlag.granularity,
)
})
(secondaryMetaData, secondaryModifiedData)
}
| DisableComparison => ([], [])
}
if primaryData->Array.length > 0 {
let primaryModifiedData = [primaryData]->Array.map(data => {
fillMissingDataPoints(
~data,
~startDate=startTimeVal,
~endDate=endTimeVal,
~timeKey=Time_Bucket->getStringFromVariant,
~defaultValue={
"payment_count": 0,
"payment_success_rate": 0,
"time_bucket": startTimeVal,
}->Identity.genericTypeToJson,
~isoStringToCustomTimeZone,
~granularity=granularity.value,
~granularityEnabled=featureFlag.granularity,
)
})
setPaymentsSuccessRateData(_ =>
primaryModifiedData->Array.concat(secondaryModifiedData)->Identity.genericTypeToJson
)
setpaymentsProcessedMetaData(_ =>
primaryMetaData->Array.concat(secondaryMetaData)->Identity.genericTypeToJson
)
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Custom)
}
}
React.useEffect(() => {
if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString {
getPaymentsSuccessRate()->ignore
}
None
}, (
startTimeVal,
endTimeVal,
compareToStartTime,
compareToEndTime,
comparison,
currency,
granularity.value,
))
let params = {
data: paymentsSuccessRateData,
xKey: Refund_Success_Rate->getStringFromVariant,
yKey: Time_Bucket->getStringFromVariant,
comparison,
}
let options = chartEntity.getObjects(~params)->chartEntity.getChatOptions
<div>
<ModuleHeader title={entity.title} />
<Card>
<PageLoaderWrapper
screenState customLoader={<Shimmer layoutId=entity.title />} customUI={<NoData />}>
<PaymentsSuccessRateHeader
data={paymentsSuccessRateMetaData}
keyValue={Total_Refund_Success_Rate->getStringFromVariant}
granularity
setGranularity
granularityOptions
/>
<div className="mb-5">
<LineGraph options className="mr-3" />
</div>
</PageLoaderWrapper>
</Card>
</div>
}
| 1,793 | 9,623 |
hyperswitch-control-center | src/screens/NewAnalytics/NewRefundsAnalytics/RefundsSuccessRate/RefundsSuccessRateUtils.res | .res | open NewAnalyticsUtils
open RefundsSuccessRateTypes
let getStringFromVariant = value => {
switch value {
| Refund_Success_Rate => "refund_success_rate"
| Total_Refund_Success_Rate => "total_refund_success_rate"
| Time_Bucket => "time_bucket"
}
}
let getVariantValueFromString = value => {
switch value {
| "refund_success_rate" => Refund_Success_Rate
| "total_refund_success_rate" => Total_Refund_Success_Rate
| "time_bucket" | _ => Time_Bucket
}
}
let refundsSuccessRateMapper = (
~params: NewAnalyticsTypes.getObjects<JSON.t>,
): LineGraphTypes.lineGraphPayload => {
open LineGraphTypes
let {data, xKey, yKey} = params
let comparison = switch params.comparison {
| Some(val) => Some(val)
| None => None
}
let primaryCategories = data->getCategories(0, yKey)
let secondaryCategories = data->getCategories(1, yKey)
let lineGraphData = data->getLineGraphData(~xKey, ~yKey)
{
chartHeight: DefaultHeight,
chartLeftSpacing: DefaultLeftSpacing,
categories: primaryCategories,
data: lineGraphData,
title: {
text: "",
},
yAxisMaxValue: 100->Some,
yAxisMinValue: Some(0),
tooltipFormatter: tooltipFormatter(
~secondaryCategories,
~title="Refunds Success Rate",
~metricType=Rate,
~comparison,
),
yAxisFormatter: LineGraphUtils.lineGraphYAxisFormatter(
~statType=Default,
~currency="",
~suffix="",
),
legend: {
useHTML: true,
labelFormatter: LineGraphUtils.valueFormatter,
},
}
}
open NewAnalyticsTypes
let tabs = [{label: "Daily", value: (#G_ONEDAY: granularity :> string)}]
let defaulGranularity = {
label: "Hourly",
value: (#G_ONEDAY: granularity :> string),
}
| 461 | 9,624 |
hyperswitch-control-center | src/screens/NewAnalytics/NewRefundsAnalytics/FailedRefundsDistribution/FailedRefundsDistributionTypes.res | .res | type failedRefundsDistributionTypes =
| Refunds_Failure_Rate
| Refund_Count
| Connector
type failedRefundsDistributionObject = {
refund_count: int,
refunds_failure_rate: float,
connector: string,
}
| 53 | 9,625 |
hyperswitch-control-center | src/screens/NewAnalytics/NewRefundsAnalytics/FailedRefundsDistribution/FailedRefundsDistribution.res | .res | open NewAnalyticsTypes
open NewAnalyticsHelper
open NewRefundsAnalyticsEntity
open BarGraphTypes
open FailedRefundsDistributionUtils
open FailedRefundsDistributionTypes
module TableModule = {
@react.component
let make = (~data, ~className="") => {
let (offset, setOffset) = React.useState(_ => 0)
let defaultSort: Table.sortedObject = {
key: "",
order: Table.INC,
}
let visibleColumns = [Connector, Refunds_Failure_Rate]
let tableData = getTableData(data)
<div className>
<LoadedTable
visibleColumns
title="Failed Refunds Distribution"
hideTitle=true
actualData={tableData}
entity=failedRefundsDistributionTableEntity
resultsPerPage=10
totalResults={tableData->Array.length}
offset
setOffset
defaultSort
currrentFetchCount={tableData->Array.length}
tableLocalFilter=false
tableheadingClass=tableBorderClass
tableBorderClass
ignoreHeaderBg=true
tableDataBorderClass=tableBorderClass
isAnalyticsModule=true
/>
</div>
}
}
module FailedRefundsDistributionHeader = {
@react.component
let make = (~viewType, ~setViewType) => {
let setViewType = value => {
setViewType(_ => value)
}
<div className="w-full px-8 pt-3 pb-3 flex justify-end">
<div className="flex gap-2">
<TabSwitch viewType setViewType />
</div>
</div>
}
}
@react.component
let make = (
~entity: moduleEntity,
~chartEntity: chartEntity<barGraphPayload, barGraphOptions, JSON.t>,
) => {
open LogicUtils
open APIUtils
open NewAnalyticsUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let {filterValueJson} = React.useContext(FilterContext.filterContext)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (refundsDistribution, setrefundsDistribution) = React.useState(_ => JSON.Encode.array([]))
let (viewType, setViewType) = React.useState(_ => Graph)
let startTimeVal = filterValueJson->getString("startTime", "")
let endTimeVal = filterValueJson->getString("endTime", "")
let currency = filterValueJson->getString((#currency: filters :> string), "")
let getRefundsDistribution = async () => {
setScreenState(_ => PageLoaderWrapper.Loading)
try {
let url = getURL(
~entityName=V1(ANALYTICS_REFUNDS),
~methodType=Post,
~id=Some((entity.domain: domain :> string)),
)
let body = requestBody(
~startTime=startTimeVal,
~endTime=endTimeVal,
~delta=entity.requestBodyConfig.delta,
~metrics=entity.requestBodyConfig.metrics,
~groupByNames=[Connector->getStringFromVariant]->Some,
~filter=generateFilterObject(~globalFilters=filterValueJson)->Some,
)
let response = await updateDetails(url, body, Post)
let responseTotalNumberData =
response->getDictFromJsonObject->getArrayFromDict("queryData", [])
if responseTotalNumberData->Array.length > 0 {
let filters = Dict.make()
filters->Dict.set("refund_status", ["failure"->JSON.Encode.string]->JSON.Encode.array)
let body = requestBody(
~startTime=startTimeVal,
~endTime=endTimeVal,
~filter=generateFilterObject(
~globalFilters=filterValueJson,
~localFilters=filters->Some,
)->Some,
~delta=entity.requestBodyConfig.delta,
~metrics=entity.requestBodyConfig.metrics,
~groupByNames=[Connector->getStringFromVariant]->Some,
)
let response = await updateDetails(url, body, Post)
let responseFailedNumberData =
response->getDictFromJsonObject->getArrayFromDict("queryData", [])
setrefundsDistribution(_ =>
modifyQuery(responseTotalNumberData, responseFailedNumberData)->JSON.Encode.array
)
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Custom)
}
}
React.useEffect(() => {
if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString {
getRefundsDistribution()->ignore
}
None
}, [startTimeVal, endTimeVal, currency])
let params = {
data: refundsDistribution,
xKey: Refunds_Failure_Rate->getStringFromVariant,
yKey: Connector->getStringFromVariant,
}
let options = chartEntity.getChatOptions(chartEntity.getObjects(~params))
<div>
<ModuleHeader title={entity.title} />
<Card>
<PageLoaderWrapper
screenState customLoader={<Shimmer layoutId=entity.title />} customUI={<NoData />}>
<FailedRefundsDistributionHeader viewType setViewType />
<div className="mb-5">
{switch viewType {
| Graph => <BarGraph options className="mr-3" />
| Table => <TableModule data={refundsDistribution} className="mx-7" />
}}
</div>
</PageLoaderWrapper>
</Card>
</div>
}
| 1,195 | 9,626 |
hyperswitch-control-center | src/screens/NewAnalytics/NewRefundsAnalytics/FailedRefundsDistribution/FailedRefundsDistributionUtils.res | .res | open NewAnalyticsUtils
open LogicUtils
open FailedRefundsDistributionTypes
let getStringFromVariant = value => {
switch value {
| Refunds_Failure_Rate => "refunds_failure_rate"
| Refund_Count => "refund_count"
| Connector => "connector"
}
}
let failedRefundsDistributionMapper = (
~params: NewAnalyticsTypes.getObjects<JSON.t>,
): BarGraphTypes.barGraphPayload => {
open BarGraphTypes
let {data, xKey, yKey} = params
let categories = [data]->JSON.Encode.array->getCategories(0, yKey)
let barGraphData = getBarGraphObj(
~array=data->getArrayFromJson([]),
~key=xKey,
~name=xKey->snakeToTitle,
~color=redColor,
)
let title = {
text: "",
}
{
categories,
data: [barGraphData],
title,
tooltipFormatter: bargraphTooltipFormatter(
~title="Failed Refunds Distribution",
~metricType=Rate,
),
}
}
let tableItemToObjMapper: Dict.t<JSON.t> => failedRefundsDistributionObject = dict => {
{
refund_count: dict->getInt(Refund_Count->getStringFromVariant, 0),
refunds_failure_rate: dict->getFloat(Refunds_Failure_Rate->getStringFromVariant, 0.0),
connector: dict->getString(Connector->getStringFromVariant, ""),
}
}
let getObjects: JSON.t => array<failedRefundsDistributionObject> = json => {
json
->LogicUtils.getArrayFromJson([])
->Array.map(item => {
tableItemToObjMapper(item->getDictFromJsonObject)
})
}
let getHeading = colType => {
switch colType {
| Refunds_Failure_Rate =>
Table.makeHeaderInfo(
~key=Refunds_Failure_Rate->getStringFromVariant,
~title="Refunds Failure Rate",
~dataType=TextType,
)
| Connector =>
Table.makeHeaderInfo(
~key=Connector->getStringFromVariant,
~title="Connector",
~dataType=TextType,
)
| _ => Table.makeHeaderInfo(~key="", ~title="", ~dataType=TextType)
}
}
let getCell = (obj, colType): Table.cell => {
switch colType {
| Refunds_Failure_Rate => Text(obj.refunds_failure_rate->valueFormatter(Rate))
| Connector => Text(obj.connector)
| _ => Text("")
}
}
let getTableData = json => {
json->getArrayDataFromJson(tableItemToObjMapper)->Array.map(Nullable.make)
}
let modifyQuery = (totalCountArr, failureCountArr) => {
let mapper = Dict.make()
totalCountArr->Array.forEach(item => {
let valueDict = item->getDictFromJsonObject
let key = valueDict->getString(Connector->getStringFromVariant, "")
if key->isNonEmptyString {
mapper->Dict.set(key, item)
}
})
failureCountArr->Array.forEach(item => {
let itemDict = item->getDictFromJsonObject
let key = itemDict->getString(Connector->getStringFromVariant, "")
switch mapper->Dict.get(key) {
| Some(value) => {
let valueDict = value->getDictFromJsonObject
let failureCount = itemDict->getInt(Refund_Count->getStringFromVariant, 0)->Int.toFloat
let totalCount = valueDict->getInt(Refund_Count->getStringFromVariant, 0)->Int.toFloat
let failureRate = totalCount > 0.0 ? failureCount /. totalCount *. 100.0 : 0.0
valueDict->Dict.set(
Refunds_Failure_Rate->getStringFromVariant,
failureRate->JSON.Encode.float,
)
mapper->Dict.set(key, valueDict->JSON.Encode.object)
}
| _ => ()
}
})
mapper->Dict.valuesToArray
}
| 866 | 9,627 |
hyperswitch-control-center | src/screens/NewAnalytics/NewRefundsAnalytics/FailureReasonsRefunds/FailureReasonsRefundsTypes.res | .res | type failreResonsColsTypes =
| Refund_Error_Message
| Refund_Error_Message_Count
| Total_Refund_Error_Message_Count
| Refund_Error_Message_Count_Ratio
| Connector
type failreResonsObjectType = {
connector: string,
refund_error_message: string,
refund_error_message_count: int,
total_refund_error_message_count: int,
refund_error_message_count_ratio: float,
}
| 94 | 9,628 |
hyperswitch-control-center | src/screens/NewAnalytics/NewRefundsAnalytics/FailureReasonsRefunds/FailureReasonsRefunds.res | .res | open NewAnalyticsTypes
open FailureReasonsRefundsTypes
open NewRefundsAnalyticsEntity
open FailureReasonsRefundsUtils
open NewAnalyticsHelper
module TableModule = {
@react.component
let make = (~data, ~className="") => {
let (offset, setOffset) = React.useState(_ => 0)
let defaultSort: Table.sortedObject = {
key: "",
order: Table.INC,
}
let visibleColumns = [
Refund_Error_Message,
Refund_Error_Message_Count,
Refund_Error_Message_Count_Ratio,
Connector,
]
let tableData = getTableData(data)
<div className>
<LoadedTable
visibleColumns
title="Failure Reasons Refunds"
hideTitle=true
actualData={tableData}
entity=failureReasonsTableEntity
resultsPerPage=10
totalResults={tableData->Array.length}
offset
setOffset
defaultSort
currrentFetchCount={tableData->Array.length}
tableLocalFilter=false
tableheadingClass=tableBorderClass
tableBorderClass
ignoreHeaderBg=true
tableDataBorderClass=tableBorderClass
isAnalyticsModule=true
/>
</div>
}
}
@react.component
let make = (~entity: moduleEntity) => {
open LogicUtils
open APIUtils
open NewAnalyticsUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let {filterValueJson} = React.useContext(FilterContext.filterContext)
let (tableData, setTableData) = React.useState(_ => JSON.Encode.array([]))
let startTimeVal = filterValueJson->getString("startTime", "")
let endTimeVal = filterValueJson->getString("endTime", "")
let currency = filterValueJson->getString((#currency: filters :> string), "")
let getRefundsProcessed = async () => {
setScreenState(_ => PageLoaderWrapper.Loading)
try {
let url = getURL(
~entityName=V1(ANALYTICS_REFUNDS),
~methodType=Post,
~id=Some((entity.domain: domain :> string)),
)
let groupByNames = switch entity.requestBodyConfig.groupBy {
| Some(dimentions) =>
dimentions
->Array.map(item => (item: dimension :> string))
->Some
| _ => None
}
let body = requestBody(
~startTime=startTimeVal,
~endTime=endTimeVal,
~delta=entity.requestBodyConfig.delta,
~metrics=entity.requestBodyConfig.metrics,
~groupByNames,
~filter=generateFilterObject(~globalFilters=filterValueJson)->Some,
)
let response = await updateDetails(url, body, Post)
let metaData = response->getDictFromJsonObject->getArrayFromDict("metaData", [])
let data =
response
->getDictFromJsonObject
->getArrayFromDict("queryData", [])
->modifyQuery(metaData)
if data->Array.length > 0 {
setTableData(_ => data->JSON.Encode.array)
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Custom)
}
}
React.useEffect(() => {
if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString {
getRefundsProcessed()->ignore
}
None
}, [startTimeVal, endTimeVal, currency])
<div>
<ModuleHeader title={entity.title} />
<Card>
<PageLoaderWrapper
screenState customLoader={<Shimmer layoutId=entity.title />} customUI={<NoData />}>
<TableModule data={tableData} className="ml-6 mr-5 mt-6 mb-5" />
</PageLoaderWrapper>
</Card>
</div>
}
| 880 | 9,629 |
hyperswitch-control-center | src/screens/NewAnalytics/NewRefundsAnalytics/FailureReasonsRefunds/FailureReasonsRefundsUtils.res | .res | open FailureReasonsRefundsTypes
open LogicUtils
let getStringFromVariant = value => {
switch value {
| Refund_Error_Message => "refund_error_message"
| Refund_Error_Message_Count => "refund_error_message_count"
| Total_Refund_Error_Message_Count => "total_refund_error_message_count"
| Refund_Error_Message_Count_Ratio => "refund_error_message_count_ratio"
| Connector => "connector"
}
}
let tableItemToObjMapper: Dict.t<JSON.t> => failreResonsObjectType = dict => {
{
refund_error_message: dict->getString(Refund_Error_Message->getStringFromVariant, ""),
refund_error_message_count: dict->getInt(Refund_Error_Message_Count->getStringFromVariant, 0),
total_refund_error_message_count: dict->getInt(
Total_Refund_Error_Message_Count->getStringFromVariant,
0,
),
refund_error_message_count_ratio: dict->getFloat(
Refund_Error_Message_Count_Ratio->getStringFromVariant,
0.0,
),
connector: dict->getString(Connector->getStringFromVariant, ""),
}
}
let getObjects: JSON.t => array<failreResonsObjectType> = json => {
json
->LogicUtils.getArrayFromJson([])
->Array.map(item => {
tableItemToObjMapper(item->getDictFromJsonObject)
})
}
let getHeading = colType => {
switch colType {
| Refund_Error_Message =>
Table.makeHeaderInfo(
~key=Refund_Error_Message->getStringFromVariant,
~title="Error Reason",
~dataType=TextType,
)
| Refund_Error_Message_Count =>
Table.makeHeaderInfo(
~key=Refund_Error_Message_Count->getStringFromVariant,
~title="Count",
~dataType=TextType,
)
| Total_Refund_Error_Message_Count =>
Table.makeHeaderInfo(
~key=Total_Refund_Error_Message_Count->getStringFromVariant,
~title="",
~dataType=TextType,
)
| Refund_Error_Message_Count_Ratio =>
Table.makeHeaderInfo(
~key=Refund_Error_Message_Count_Ratio->getStringFromVariant,
~title="Ratio",
~dataType=TextType,
)
| Connector =>
Table.makeHeaderInfo(
~key=Connector->getStringFromVariant,
~title="Connector",
~dataType=TextType,
)
}
}
let getCell = (obj, colType): Table.cell => {
switch colType {
| Refund_Error_Message => Text(obj.refund_error_message)
| Refund_Error_Message_Count => Text(obj.refund_error_message_count->Int.toString)
| Total_Refund_Error_Message_Count => Text(obj.total_refund_error_message_count->Int.toString)
| Refund_Error_Message_Count_Ratio =>
Text(obj.refund_error_message_count_ratio->valueFormatter(Rate))
| Connector => Text(obj.connector)
}
}
let getTableData = json => {
json->getArrayDataFromJson(tableItemToObjMapper)->Array.map(Nullable.make)
}
let modifyQuery = (queryData, metaData) => {
let totalCount = switch metaData->Array.get(0) {
| Some(val) => {
let valueDict = val->getDictFromJsonObject
let failure_reason_count =
valueDict->getInt(Total_Refund_Error_Message_Count->getStringFromVariant, 0)
failure_reason_count
}
| _ => 0
}
let modifiedQuery = if totalCount > 0 {
queryData->Array.map(query => {
let valueDict = query->getDictFromJsonObject
let failure_reason_count =
valueDict->getInt(Refund_Error_Message_Count->getStringFromVariant, 0)
let ratio = failure_reason_count->Int.toFloat /. totalCount->Int.toFloat *. 100.0
valueDict->Dict.set(
Refund_Error_Message_Count_Ratio->getStringFromVariant,
ratio->JSON.Encode.float,
)
valueDict->JSON.Encode.object
})
} else {
queryData
}
modifiedQuery->Array.sort((queryA, queryB) => {
let valueDictA = queryA->getDictFromJsonObject
let valueDictB = queryB->getDictFromJsonObject
let failure_reason_countA =
valueDictA->getInt(Refund_Error_Message_Count->getStringFromVariant, 0)
let failure_reason_countB =
valueDictB->getInt(Refund_Error_Message_Count->getStringFromVariant, 0)
compareLogic(failure_reason_countA, failure_reason_countB)
})
modifiedQuery
}
| 993 | 9,630 |
hyperswitch-control-center | src/screens/NewAnalytics/SmartRetryAnalytics/NewSmartRetryAnalyticsEntity.res | .res | open NewAnalyticsTypes
// Smart Retry Payments Processed
let smartRetryPaymentsProcessedEntity: moduleEntity = {
requestBodyConfig: {
delta: false,
metrics: [#sessionized_payment_processed_amount],
},
title: "Smart Retry Payments Processed",
domain: #payments,
}
let smartRetryPaymentsProcessedChartEntity: chartEntity<
LineGraphTypes.lineGraphPayload,
LineGraphTypes.lineGraphOptions,
JSON.t,
> = {
getObjects: SmartRetryPaymentsProcessedUtils.smartRetryPaymentsProcessedMapper,
getChatOptions: LineGraphUtils.getLineGraphOptions,
}
let smartRetryPaymentsProcessedTableEntity = {
open SmartRetryPaymentsProcessedUtils
EntityType.makeEntity(
~uri=``,
~getObjects,
~dataKey="queryData",
~defaultColumns=visibleColumns,
~requiredSearchFieldsList=[],
~allColumns=visibleColumns,
~getCell,
~getHeading,
)
}
// Successful SmartRetry Distribution
let successfulSmartRetryDistributionEntity: moduleEntity = {
requestBodyConfig: {
delta: false,
metrics: [#payments_distribution],
},
title: "Successful Distribution of Smart Retry Payments",
domain: #payments,
}
let successfulSmartRetryDistributionChartEntity: chartEntity<
BarGraphTypes.barGraphPayload,
BarGraphTypes.barGraphOptions,
JSON.t,
> = {
getObjects: SuccessfulSmartRetryDistributionUtils.successfulSmartRetryDistributionMapper,
getChatOptions: BarGraphUtils.getBarGraphOptions,
}
let successfulSmartRetryDistributionTableEntity = {
open SuccessfulSmartRetryDistributionUtils
EntityType.makeEntity(
~uri=``,
~getObjects,
~dataKey="queryData",
~defaultColumns=[],
~requiredSearchFieldsList=[],
~allColumns=[],
~getCell,
~getHeading,
)
}
// Failed SmartRetry Distribution
let failedSmartRetryDistributionEntity: moduleEntity = {
requestBodyConfig: {
delta: false,
metrics: [#payments_distribution],
},
title: "Failed Distribution of Smart Retry Payments",
domain: #payments,
}
let failedSmartRetryDistributionChartEntity: chartEntity<
BarGraphTypes.barGraphPayload,
BarGraphTypes.barGraphOptions,
JSON.t,
> = {
getObjects: FailureSmartRetryDistributionUtils.failedSmartRetryDistributionMapper,
getChatOptions: BarGraphUtils.getBarGraphOptions,
}
let failedSmartRetryDistributionTableEntity = {
open FailureSmartRetryDistributionUtils
EntityType.makeEntity(
~uri=``,
~getObjects,
~dataKey="queryData",
~defaultColumns=[],
~requiredSearchFieldsList=[],
~allColumns=[],
~getCell,
~getHeading,
)
}
| 579 | 9,631 |
hyperswitch-control-center | src/screens/NewAnalytics/SmartRetryAnalytics/NewSmartRetryAnalytics.res | .res | @react.component
let make = () => {
open NewSmartRetryAnalyticsEntity
let {newAnalyticsFilters} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
<div className="flex flex-col gap-14 mt-5 pt-7">
<RenderIf condition={newAnalyticsFilters}>
<div className="flex gap-2">
<NewAnalyticsFilters domain={#payments} entityName={V1(ANALYTICS_PAYMENTS)} />
</div>
</RenderIf>
<SmartRetryPaymentsProcessed
entity={smartRetryPaymentsProcessedEntity}
chartEntity={smartRetryPaymentsProcessedChartEntity}
/>
<SuccessfulSmartRetryDistribution
entity={successfulSmartRetryDistributionEntity}
chartEntity={successfulSmartRetryDistributionChartEntity}
/>
<FailureSmartRetryDistribution
entity={failedSmartRetryDistributionEntity}
chartEntity={failedSmartRetryDistributionChartEntity}
/>
</div>
}
| 207 | 9,632 |
hyperswitch-control-center | src/screens/NewAnalytics/SmartRetryAnalytics/SmartRetryPaymentsProcessed/SmartRetryPaymentsProcessed.res | .res | open NewAnalyticsTypes
open NewAnalyticsHelper
open SmartRetryPaymentsProcessedUtils
open NewSmartRetryAnalyticsEntity
open PaymentsProcessedTypes
module TableModule = {
open LogicUtils
@react.component
let make = (~data, ~className="") => {
let (offset, setOffset) = React.useState(_ => 0)
let defaultSort: Table.sortedObject = {
key: "",
order: Table.INC,
}
let tableBorderClass = "border-collapse border border-jp-gray-940 border-solid border-2 border-opacity-30 dark:border-jp-gray-dark_table_border_color dark:border-opacity-30"
let smartRetryPaymentsProcessed =
data
->Array.map(item => {
item->getDictFromJsonObject->tableItemToObjMapper
})
->Array.map(Nullable.make)
let defaultCols = [Payment_Processed_Amount, Payment_Processed_Count]
let visibleColumns = defaultCols->Array.concat(visibleColumns)
<div className>
<LoadedTable
visibleColumns
title="Smart Retry Payments Processed"
hideTitle=true
actualData={smartRetryPaymentsProcessed}
entity=smartRetryPaymentsProcessedTableEntity
resultsPerPage=10
totalResults={smartRetryPaymentsProcessed->Array.length}
offset
setOffset
defaultSort
currrentFetchCount={smartRetryPaymentsProcessed->Array.length}
tableLocalFilter=false
tableheadingClass=tableBorderClass
tableBorderClass
ignoreHeaderBg=true
showSerialNumber=true
tableDataBorderClass=tableBorderClass
isAnalyticsModule=true
/>
</div>
}
}
module SmartRetryPaymentsProcessedHeader = {
open NewAnalyticsUtils
open LogicUtils
open LogicUtilsTypes
@react.component
let make = (
~data: JSON.t,
~viewType,
~setViewType,
~selectedMetric,
~setSelectedMetric,
~granularity,
~setGranularity,
~granularityOptions,
) => {
let {filterValueJson} = React.useContext(FilterContext.filterContext)
let comparison = filterValueJson->getString("comparison", "")->DateRangeUtils.comparisonMapprer
let currency = filterValueJson->getString((#currency: filters :> string), "")
let featureFlag = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let primaryValue = getMetaDataValue(
~data,
~index=0,
~key=selectedMetric.value->getMetaDataMapper,
)
let secondaryValue = getMetaDataValue(
~data,
~index=1,
~key=selectedMetric.value->getMetaDataMapper,
)
let (primaryValue, secondaryValue) = if selectedMetric.value->isAmountMetric {
(primaryValue /. 100.0, secondaryValue /. 100.0)
} else {
(primaryValue, secondaryValue)
}
let (value, direction) = calculatePercentageChange(~primaryValue, ~secondaryValue)
let setViewType = value => {
setViewType(_ => value)
}
let setSelectedMetric = value => {
setSelectedMetric(_ => value)
}
let setGranularity = value => {
setGranularity(_ => value)
}
let metricType = switch selectedMetric.value->getVariantValueFromString {
| Payment_Processed_Amount => Amount
| _ => Volume
}
<div className="w-full px-7 py-8 grid grid-cols-3">
<div className="flex gap-2 items-center">
<div className="text-fs-28 font-semibold">
{primaryValue->valueFormatter(metricType, ~currency)->React.string}
</div>
<RenderIf condition={comparison == EnableComparison}>
<StatisticsCard
value direction tooltipValue={secondaryValue->valueFormatter(metricType, ~currency)}
/>
</RenderIf>
</div>
<div className="flex justify-center">
<RenderIf condition={featureFlag.granularity}>
<Tabs
option={granularity}
setOption={setGranularity}
options={granularityOptions}
showSingleTab=false
/>
</RenderIf>
</div>
<div className="flex gap-2 justify-end">
<CustomDropDown
buttonText={selectedMetric} options={dropDownOptions} setOption={setSelectedMetric}
/>
<TabSwitch viewType setViewType />
</div>
</div>
}
}
@react.component
let make = (
~entity: moduleEntity,
~chartEntity: chartEntity<
LineGraphTypes.lineGraphPayload,
LineGraphTypes.lineGraphOptions,
JSON.t,
>,
) => {
open LogicUtils
open APIUtils
open NewAnalyticsUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let isoStringToCustomTimeZone = TimeZoneHook.useIsoStringToCustomTimeZone()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let {filterValueJson} = React.useContext(FilterContext.filterContext)
let (smartRetryPaymentsProcessedData, setSmartRetryPaymentsProcessedData) = React.useState(_ =>
JSON.Encode.array([])
)
let (
smartRetryPaymentsProcessedTableData,
setSmartRetryPaymentsProcessedTableData,
) = React.useState(_ => [])
let (
smartRetryPaymentsProcessedMetaData,
setSmartRetryPaymentsProcessedMetaData,
) = React.useState(_ => JSON.Encode.array([]))
let (selectedMetric, setSelectedMetric) = React.useState(_ => defaultMetric)
let (viewType, setViewType) = React.useState(_ => Graph)
let startTimeVal = filterValueJson->getString("startTime", "")
let endTimeVal = filterValueJson->getString("endTime", "")
let compareToStartTime = filterValueJson->getString("compareToStartTime", "")
let compareToEndTime = filterValueJson->getString("compareToEndTime", "")
let comparison = filterValueJson->getString("comparison", "")->DateRangeUtils.comparisonMapprer
let currency = filterValueJson->getString((#currency: filters :> string), "")
let featureFlag = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let granularityOptions = getGranularityOptions(~startTime=startTimeVal, ~endTime=endTimeVal)
let defaulGranularity = getDefaultGranularity(
~startTime=startTimeVal,
~endTime=endTimeVal,
~granularity=featureFlag.granularity,
)
let (granularity, setGranularity) = React.useState(_ => defaulGranularity)
React.useEffect(() => {
if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString {
setGranularity(_ => defaulGranularity)
}
None
}, (startTimeVal, endTimeVal))
let getSmartRetryPaymentsProcessed = async () => {
setScreenState(_ => PageLoaderWrapper.Loading)
try {
let url = getURL(
~entityName=V1(ANALYTICS_PAYMENTS_V2),
~methodType=Post,
~id=Some((entity.domain: domain :> string)),
)
let primaryBody = requestBody(
~startTime=startTimeVal,
~endTime=endTimeVal,
~delta=entity.requestBodyConfig.delta,
~metrics=entity.requestBodyConfig.metrics,
~granularity=granularity.value->Some,
~filter=generateFilterObject(~globalFilters=filterValueJson)->Some,
)
let secondaryBody = requestBody(
~startTime=compareToStartTime,
~endTime=compareToEndTime,
~delta=entity.requestBodyConfig.delta,
~metrics=entity.requestBodyConfig.metrics,
~granularity=granularity.value->Some,
~filter=generateFilterObject(~globalFilters=filterValueJson)->Some,
)
let primaryResponse = await updateDetails(url, primaryBody, Post)
let primaryData =
primaryResponse
->getDictFromJsonObject
->getArrayFromDict("queryData", [])
->modifySmartRetryQueryData(~currency)
->sortQueryDataByDate
let primaryMetaData =
primaryResponse
->getDictFromJsonObject
->getArrayFromDict("metaData", [])
->modifySmartRetryMetaData(~currency)
setSmartRetryPaymentsProcessedTableData(_ => primaryData)
let (secondaryMetaData, secondaryModifiedData) = switch comparison {
| EnableComparison => {
let secondaryResponse = await updateDetails(url, secondaryBody, Post)
let secondaryData =
secondaryResponse
->getDictFromJsonObject
->getArrayFromDict("queryData", [])
->modifySmartRetryQueryData(~currency)
let secondaryMetaData =
secondaryResponse
->getDictFromJsonObject
->getArrayFromDict("metaData", [])
->modifySmartRetryMetaData(~currency)
let secondaryModifiedData = [secondaryData]->Array.map(data => {
fillMissingDataPoints(
~data,
~startDate=compareToStartTime,
~endDate=compareToEndTime,
~timeKey="time_bucket",
~defaultValue={
"payment_count": 0,
"payment_processed_amount": 0,
"time_bucket": startTimeVal,
}->Identity.genericTypeToJson,
~isoStringToCustomTimeZone,
~granularity=granularity.value,
~granularityEnabled=featureFlag.granularity,
)
})
(secondaryMetaData, secondaryModifiedData)
}
| DisableComparison => ([], [])
}
if primaryData->Array.length > 0 {
let primaryModifiedData = [primaryData]->Array.map(data => {
fillMissingDataPoints(
~data,
~startDate=startTimeVal,
~endDate=endTimeVal,
~timeKey="time_bucket",
~defaultValue={
"payment_count": 0,
"payment_processed_amount": 0,
"time_bucket": startTimeVal,
}->Identity.genericTypeToJson,
~isoStringToCustomTimeZone,
~granularity=granularity.value,
~granularityEnabled=featureFlag.granularity,
)
})
setSmartRetryPaymentsProcessedData(_ =>
primaryModifiedData->Array.concat(secondaryModifiedData)->Identity.genericTypeToJson
)
setSmartRetryPaymentsProcessedMetaData(_ =>
primaryMetaData->Array.concat(secondaryMetaData)->Identity.genericTypeToJson
)
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Custom)
}
}
React.useEffect(() => {
if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString {
getSmartRetryPaymentsProcessed()->ignore
}
None
}, (
startTimeVal,
endTimeVal,
compareToStartTime,
compareToEndTime,
comparison,
currency,
granularity.value,
))
let params = {
data: smartRetryPaymentsProcessedData,
xKey: selectedMetric.value,
yKey: Time_Bucket->getStringFromVariant,
comparison,
currency,
}
let options = chartEntity.getObjects(~params)->chartEntity.getChatOptions
<div>
<ModuleHeader title={entity.title} />
<Card>
<PageLoaderWrapper
screenState customLoader={<Shimmer layoutId=entity.title />} customUI={<NoData />}>
<SmartRetryPaymentsProcessedHeader
data=smartRetryPaymentsProcessedMetaData
viewType
setViewType
selectedMetric
setSelectedMetric
granularity
setGranularity
granularityOptions
/>
<div className="mb-5">
{switch viewType {
| Graph => <LineGraph options className="mr-3" />
| Table => <TableModule data={smartRetryPaymentsProcessedTableData} className="mx-7" />
}}
</div>
</PageLoaderWrapper>
</Card>
</div>
}
| 2,582 | 9,633 |
hyperswitch-control-center | src/screens/NewAnalytics/SmartRetryAnalytics/SmartRetryPaymentsProcessed/SmartRetryPaymentsProcessedUtils.res | .res | open SmartRetryPaymentsProcessedTypes
open NewAnalyticsUtils
open LogicUtils
open PaymentsProcessedTypes
let getStringFromVariant = value => {
switch value {
| Payment_Processed_Amount => "payment_processed_amount"
| Payment_Processed_Count => "payment_processed_count"
| Total_Payment_Processed_Amount => "total_payment_processed_amount"
| Total_Payment_Processed_Count => "total_payment_processed_count"
| Time_Bucket => "time_bucket"
}
}
let getVariantValueFromString = value => {
switch value {
| "payment_processed_amount" | "payment_processed_amount_in_usd" => Payment_Processed_Amount
| "payment_processed_count" => Payment_Processed_Count
| "total_payment_processed_amount" | "total_payment_processed_amount_in_usd" =>
Total_Payment_Processed_Amount
| "total_payment_processed_count" => Total_Payment_Processed_Count
| "time_bucket" | _ => Time_Bucket
}
}
let isAmountMetric = key => {
switch key->getVariantValueFromString {
| Payment_Processed_Amount
| Total_Payment_Processed_Amount => true
| _ => false
}
}
let smartRetryPaymentsProcessedMapper = (
~params: NewAnalyticsTypes.getObjects<JSON.t>,
): LineGraphTypes.lineGraphPayload => {
open LineGraphTypes
let {data, xKey, yKey} = params
let comparison = switch params.comparison {
| Some(val) => Some(val)
| None => None
}
let currency = params.currency->Option.getOr("")
let primaryCategories = data->getCategories(0, yKey)
let secondaryCategories = data->getCategories(1, yKey)
let lineGraphData = data->getLineGraphData(~xKey, ~yKey, ~isAmount=xKey->isAmountMetric)
open LogicUtilsTypes
let metricType = switch xKey->getVariantValueFromString {
| Payment_Processed_Amount => Amount
| _ => Volume
}
{
chartHeight: DefaultHeight,
chartLeftSpacing: DefaultLeftSpacing,
categories: primaryCategories,
data: lineGraphData,
title: {
text: "",
},
yAxisMaxValue: data->isEmptyGraph(xKey) ? Some(1) : None,
yAxisMinValue: Some(0),
tooltipFormatter: tooltipFormatter(
~secondaryCategories,
~title="Smart Retry Payments Processed",
~metricType,
~comparison,
~currency,
),
yAxisFormatter: LineGraphUtils.lineGraphYAxisFormatter(
~statType=Default,
~currency="",
~suffix="",
),
legend: {
useHTML: true,
labelFormatter: LineGraphUtils.valueFormatter,
},
}
}
let visibleColumns = [Time_Bucket]
let tableItemToObjMapper: Dict.t<JSON.t> => smartRetryPaymentsProcessedObject = dict => {
{
smart_retry_payment_processed_amount: dict->getAmountValue(
~id=Payment_Processed_Amount->getStringFromVariant,
),
smart_retry_payment_processed_count: dict->getInt(
Payment_Processed_Count->getStringFromVariant,
0,
),
total_payment_smart_retry_processed_amount: dict->getAmountValue(
~id=Total_Payment_Processed_Amount->getStringFromVariant,
),
total_payment_smart_retry_processed_count: dict->getInt(
Total_Payment_Processed_Count->getStringFromVariant,
0,
),
time_bucket: dict->getString(Time_Bucket->getStringFromVariant, "NA"),
}
}
let getObjects: JSON.t => array<smartRetryPaymentsProcessedObject> = json => {
json
->LogicUtils.getArrayFromJson([])
->Array.map(item => {
tableItemToObjMapper(item->getDictFromJsonObject)
})
}
let getHeading = colType => {
switch colType {
| Payment_Processed_Amount =>
Table.makeHeaderInfo(
~key=Payment_Processed_Amount->getStringFromVariant,
~title="Amount",
~dataType=TextType,
)
| Payment_Processed_Count =>
Table.makeHeaderInfo(
~key=Payment_Processed_Count->getStringFromVariant,
~title="Count",
~dataType=TextType,
)
| Time_Bucket =>
Table.makeHeaderInfo(~key=Time_Bucket->getStringFromVariant, ~title="Date", ~dataType=TextType)
| Total_Payment_Processed_Amount
| Total_Payment_Processed_Count =>
Table.makeHeaderInfo(~key="", ~title="", ~dataType=TextType)
}
}
let getCell = (obj, colType): Table.cell => {
switch colType {
| Payment_Processed_Amount =>
Text(obj.smart_retry_payment_processed_amount->valueFormatter(Amount))
| Payment_Processed_Count => Text(obj.smart_retry_payment_processed_count->Int.toString)
| Time_Bucket => Text(obj.time_bucket->formatDateValue(~includeYear=true))
| Total_Payment_Processed_Amount
| Total_Payment_Processed_Count =>
Text("")
}
}
open NewAnalyticsTypes
let dropDownOptions = [
{label: "By Amount", value: Payment_Processed_Amount->getStringFromVariant},
{label: "By Count", value: Payment_Processed_Count->getStringFromVariant},
]
let tabs = [{label: "Daily", value: (#G_ONEDAY: granularity :> string)}]
let defaultMetric = {
label: "By Amount",
value: Payment_Processed_Amount->getStringFromVariant,
}
let defaulGranularity = {
label: "Daily",
value: (#G_ONEDAY: granularity :> string),
}
let getKey = (id, ~isSmartRetryEnabled=Smart_Retry, ~currency="") => {
let key = switch id {
| Time_Bucket => #time_bucket
| Payment_Processed_Count =>
switch isSmartRetryEnabled {
| Smart_Retry => #payment_processed_count
| Default => #payment_processed_count_without_smart_retries
}
| Total_Payment_Processed_Count =>
switch isSmartRetryEnabled {
| Smart_Retry => #total_payment_processed_count
| Default => #total_payment_processed_count_without_smart_retries
}
| Payment_Processed_Amount =>
switch (isSmartRetryEnabled, currency->getTypeValue) {
| (Smart_Retry, #all_currencies) => #payment_processed_amount_in_usd
| (Smart_Retry, _) => #payment_processed_amount
| (Default, #all_currencies) => #payment_processed_amount_without_smart_retries_in_usd
| (Default, _) => #payment_processed_amount_without_smart_retrie
}
| Total_Payment_Processed_Amount =>
switch (isSmartRetryEnabled, currency->getTypeValue) {
| (Smart_Retry, #all_currencies) => #total_payment_processed_amount_in_usd
| (Smart_Retry, _) => #total_payment_processed_amount
| (Default, #all_currencies) => #total_payment_processed_amount_without_smart_retries_in_usd
| (Default, _) => #total_payment_processed_amount_without_smart_retries
}
}
(key: responseKeys :> string)
}
let modifyQueryData = (data, ~currency) => {
let dataDict = Dict.make()
let isSmartRetryEnabled = Default
data->Array.forEach(item => {
let valueDict = item->getDictFromJsonObject
let time = valueDict->getString(Time_Bucket->getStringFromVariant, "")
// with smart retry
let key = Payment_Processed_Count->getStringFromVariant
let paymentProcessedCount = valueDict->getInt(key, 0)
// without smart retry
let key = Payment_Processed_Count->getKey(~isSmartRetryEnabled)
let paymentProcessedCountWithoutSmartRetries = valueDict->getInt(key, 0)
// with smart retry
let key = Payment_Processed_Amount->getKey(~currency)
let paymentProcessedAmount = valueDict->getFloat(key, 0.0)
// without smart retry
let key = Payment_Processed_Amount->getKey(~isSmartRetryEnabled, ~currency)
let paymentProcessedAmountWithoutSmartRetries = valueDict->getFloat(key, 0.0)
switch dataDict->Dict.get(time) {
| Some(prevVal) => {
// with smart retry
let key = Payment_Processed_Count->getStringFromVariant
let paymentProcessedCount = valueDict->getInt(key, 0)
let prevProcessedCount = prevVal->getInt(key, 0)
// without smart retry
let key = Payment_Processed_Count->getKey(~isSmartRetryEnabled)
let paymentProcessedCountWithoutSmartRetries = valueDict->getInt(key, 0)
let prevProcessedCountWithoutSmartRetries = prevVal->getInt(key, 0)
// with smart retry
let key = Payment_Processed_Amount->getKey(~currency)
let paymentProcessedAmount = valueDict->getFloat(key, 0.0)
let prevProcessedAmount = prevVal->getFloat(key, 0.0)
// without smart retry
let key = Payment_Processed_Amount->getKey(~isSmartRetryEnabled, ~currency)
let paymentProcessedAmountWithoutSmartRetries = valueDict->getFloat(key, 0.0)
let prevProcessedAmountWithoutSmartRetries = prevVal->getFloat(key, 0.0)
let totalPaymentProcessedCount = paymentProcessedCount + prevProcessedCount
let totalPaymentProcessedAmount = paymentProcessedAmount +. prevProcessedAmount
let totalPaymentProcessedAmountWithoutSmartRetries =
paymentProcessedAmountWithoutSmartRetries +. prevProcessedAmountWithoutSmartRetries
let totalPaymentProcessedCountWithoutSmartRetries =
paymentProcessedCountWithoutSmartRetries + prevProcessedCountWithoutSmartRetries
// with smart retry
prevVal->Dict.set(
Payment_Processed_Count->getStringFromVariant,
totalPaymentProcessedCount->JSON.Encode.int,
)
prevVal->Dict.set(
Payment_Processed_Amount->getKey(~currency),
totalPaymentProcessedAmount->JSON.Encode.float,
)
// without smart retry
prevVal->Dict.set(
Payment_Processed_Count->getKey(~isSmartRetryEnabled),
totalPaymentProcessedCountWithoutSmartRetries->JSON.Encode.int,
)
prevVal->Dict.set(
Payment_Processed_Amount->getKey(~isSmartRetryEnabled, ~currency),
totalPaymentProcessedAmountWithoutSmartRetries->JSON.Encode.float,
)
dataDict->Dict.set(time, prevVal)
}
| None => {
// with smart retry
valueDict->Dict.set(
Payment_Processed_Count->getStringFromVariant,
paymentProcessedCount->JSON.Encode.int,
)
valueDict->Dict.set(
Payment_Processed_Amount->getKey(~currency),
paymentProcessedAmount->JSON.Encode.float,
)
// without smart retry
valueDict->Dict.set(
Payment_Processed_Count->getKey(~isSmartRetryEnabled),
paymentProcessedCountWithoutSmartRetries->JSON.Encode.int,
)
valueDict->Dict.set(
Payment_Processed_Amount->getKey(~isSmartRetryEnabled, ~currency),
paymentProcessedAmountWithoutSmartRetries->JSON.Encode.float,
)
dataDict->Dict.set(time, valueDict)
}
}
})
dataDict->Dict.valuesToArray->Array.map(JSON.Encode.object)
}
let modifySmartRetryQueryData = (data, ~currency) => {
let data = data->modifyQueryData(~currency)
let isSmartRetryEnabled = Default
data->Array.map(item => {
let valueDict = item->getDictFromJsonObject
// with smart retry
let key = Payment_Processed_Count->getStringFromVariant
let paymentProcessedCount = valueDict->getInt(key, 0)
// without smart retry
let paymentProcessedCountWithoutSmartRetries =
valueDict->getInt(Payment_Processed_Count->getKey(~isSmartRetryEnabled), 0)
// with smart retry
let paymentProcessedAmount =
valueDict->getFloat(Payment_Processed_Amount->getKey(~currency), 0.0)
// without smart retry
let paymentProcessedAmountWithoutSmartRetries =
valueDict->getFloat(Payment_Processed_Amount->getKey(~isSmartRetryEnabled, ~currency), 0.0)
let totalPaymentProcessedCount =
paymentProcessedCount - paymentProcessedCountWithoutSmartRetries
let totalPaymentProcessedAmount =
paymentProcessedAmount -. paymentProcessedAmountWithoutSmartRetries
valueDict->Dict.set(
Payment_Processed_Count->getStringFromVariant,
totalPaymentProcessedCount->JSON.Encode.int,
)
valueDict->Dict.set(
Payment_Processed_Amount->getStringFromVariant,
totalPaymentProcessedAmount->JSON.Encode.float,
)
valueDict->JSON.Encode.object
})
}
let modifySmartRetryMetaData = (data, ~currency) => {
let isSmartRetryEnabled = Default
data->Array.map(item => {
let valueDict = item->getDictFromJsonObject
// with smart retry
let key = Total_Payment_Processed_Count->getStringFromVariant
let paymentProcessedCount = valueDict->getInt(key, 0)
// without smart retry
let paymentProcessedCountWithoutSmartRetries =
valueDict->getInt(Total_Payment_Processed_Count->getKey(~isSmartRetryEnabled), 0)
// with smart retry
let paymentProcessedAmount =
valueDict->getFloat(Total_Payment_Processed_Amount->getKey(~currency), 0.0)
// without smart retry
let paymentProcessedAmountWithoutSmartRetries =
valueDict->getFloat(
Total_Payment_Processed_Amount->getKey(~isSmartRetryEnabled, ~currency),
0.0,
)
let totalPaymentProcessedCount =
paymentProcessedCount - paymentProcessedCountWithoutSmartRetries
let totalPaymentProcessedAmount =
paymentProcessedAmount -. paymentProcessedAmountWithoutSmartRetries
valueDict->Dict.set(
Total_Payment_Processed_Count->getStringFromVariant,
totalPaymentProcessedCount->JSON.Encode.int,
)
valueDict->Dict.set(
Total_Payment_Processed_Amount->getStringFromVariant,
totalPaymentProcessedAmount->JSON.Encode.float,
)
valueDict->JSON.Encode.object
})
}
let getMetaDataMapper = key => {
let field = key->getVariantValueFromString
switch field {
| Payment_Processed_Amount => Total_Payment_Processed_Amount
| Payment_Processed_Count | _ => Total_Payment_Processed_Count
}->getStringFromVariant
}
| 3,176 | 9,634 |
hyperswitch-control-center | src/screens/NewAnalytics/SmartRetryAnalytics/SmartRetryPaymentsProcessed/SmartRetryPaymentsProcessedTypes.res | .res | type smartRetryPaymentsProcessedObject = {
smart_retry_payment_processed_amount: float,
smart_retry_payment_processed_count: int,
total_payment_smart_retry_processed_amount: float,
total_payment_smart_retry_processed_count: int,
time_bucket: string,
}
| 53 | 9,635 |
hyperswitch-control-center | src/screens/NewAnalytics/SmartRetryAnalytics/FailureSmartRetryDistribution/FailureSmartRetryDistribution.res | .res | open NewAnalyticsTypes
open NewAnalyticsHelper
open BarGraphTypes
open NewSmartRetryAnalyticsEntity
open FailureSmartRetryDistributionUtils
open FailureSmartRetryDistributionTypes
module TableModule = {
@react.component
let make = (~data, ~className="", ~selectedTab: string) => {
let (offset, setOffset) = React.useState(_ => 0)
let defaultSort: Table.sortedObject = {
key: "",
order: Table.INC,
}
let visibleColumns =
[selectedTab->getColumn]->Array.concat([Payments_Failure_Rate_Distribution_With_Only_Retries])
let tableData = getTableData(data)
<div className>
<LoadedTable
visibleColumns
title="Failed Payments Distribution"
hideTitle=true
actualData={tableData}
entity=failedSmartRetryDistributionTableEntity
resultsPerPage=10
totalResults={tableData->Array.length}
offset
setOffset
defaultSort
currrentFetchCount={tableData->Array.length}
tableLocalFilter=false
tableheadingClass=tableBorderClass
tableBorderClass
ignoreHeaderBg=true
tableDataBorderClass=tableBorderClass
isAnalyticsModule=true
/>
</div>
}
}
module FailureSmartRetryDistributionHeader = {
@react.component
let make = (~viewType, ~setViewType, ~groupBy, ~setGroupBy) => {
let setViewType = value => {
setViewType(_ => value)
}
let setGroupBy = value => {
setGroupBy(_ => value)
}
<div className="w-full px-7 py-8 flex justify-between">
<Tabs option={groupBy} setOption={setGroupBy} options={tabs} />
<div className="flex gap-2">
<TabSwitch viewType setViewType />
</div>
</div>
}
}
@react.component
let make = (
~entity: moduleEntity,
~chartEntity: chartEntity<barGraphPayload, barGraphOptions, JSON.t>,
) => {
open LogicUtils
open APIUtils
open NewAnalyticsUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let {filterValueJson} = React.useContext(FilterContext.filterContext)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (paymentsDistribution, setpaymentsDistribution) = React.useState(_ => JSON.Encode.array([]))
let (viewType, setViewType) = React.useState(_ => Graph)
let (groupBy, setGroupBy) = React.useState(_ => defaulGroupBy)
let startTimeVal = filterValueJson->getString("startTime", "")
let endTimeVal = filterValueJson->getString("endTime", "")
let currency = filterValueJson->getString((#currency: filters :> string), "")
let getPaymentsDistribution = async () => {
setScreenState(_ => PageLoaderWrapper.Loading)
try {
let url = getURL(
~entityName=V1(ANALYTICS_PAYMENTS),
~methodType=Post,
~id=Some((entity.domain: domain :> string)),
)
let filters = Dict.make()
filters->Dict.set("first_attempt", [false->JSON.Encode.bool]->JSON.Encode.array)
let body = requestBody(
~startTime=startTimeVal,
~endTime=endTimeVal,
~delta=entity.requestBodyConfig.delta,
~metrics=entity.requestBodyConfig.metrics,
~groupByNames=[groupBy.value]->Some,
~filter=generateFilterObject(
~globalFilters=filterValueJson,
~localFilters=filters->Some,
)->Some,
)
let response = await updateDetails(url, body, Post)
let responseData = response->getDictFromJsonObject->getArrayFromDict("queryData", [])
if responseData->Array.length > 0 {
setpaymentsDistribution(_ => responseData->JSON.Encode.array)
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Custom)
}
}
React.useEffect(() => {
if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString {
getPaymentsDistribution()->ignore
}
None
}, [startTimeVal, endTimeVal, groupBy.value, currency])
let params = {
data: paymentsDistribution,
xKey: Payments_Failure_Rate_Distribution_With_Only_Retries->getStringFromVariant,
yKey: groupBy.value,
}
let options = chartEntity.getChatOptions(chartEntity.getObjects(~params))
<div>
<ModuleHeader title={entity.title} />
<Card>
<PageLoaderWrapper
screenState customLoader={<Shimmer layoutId=entity.title />} customUI={<NoData />}>
<FailureSmartRetryDistributionHeader viewType setViewType groupBy setGroupBy />
<div className="mb-5">
{switch viewType {
| Graph => <BarGraph options className="mr-3" />
| Table =>
<TableModule data={paymentsDistribution} className="mx-7" selectedTab={groupBy.value} />
}}
</div>
</PageLoaderWrapper>
</Card>
</div>
}
| 1,157 | 9,636 |
hyperswitch-control-center | src/screens/NewAnalytics/SmartRetryAnalytics/FailureSmartRetryDistribution/FailureSmartRetryDistributionUtils.res | .res | open LogicUtils
open NewAnalyticsUtils
open FailureSmartRetryDistributionTypes
let getStringFromVariant = value => {
switch value {
| Payments_Failure_Rate_Distribution_With_Only_Retries => "payments_failure_rate_distribution_with_only_retries"
| Connector => "connector"
| Payment_Method => "payment_method"
| Payment_Method_Type => "payment_method_type"
| Authentication_Type => "authentication_type"
}
}
let getColumn = string => {
switch string {
| "connector" => Connector
| "payment_method" => Payment_Method
| "payment_method_type" => Payment_Method_Type
| "authentication_type" => Authentication_Type
| _ => Connector
}
}
let failedSmartRetryDistributionMapper = (
~params: NewAnalyticsTypes.getObjects<JSON.t>,
): BarGraphTypes.barGraphPayload => {
open BarGraphTypes
let {data, xKey, yKey} = params
let categories = [data]->JSON.Encode.array->getCategories(0, yKey)
let barGraphData = getBarGraphObj(
~array=data->getArrayFromJson([]),
~key=xKey,
~name=xKey->snakeToTitle,
~color="#BA3535",
)
let title = {
text: "",
}
{
categories,
data: [barGraphData],
title,
tooltipFormatter: bargraphTooltipFormatter(
~title="Failed Smart Retry Distribution",
~metricType=Rate,
),
}
}
open NewAnalyticsTypes
let tableItemToObjMapper: Dict.t<JSON.t> => failureSmartRetryDistributionObject = dict => {
{
payments_failure_rate_distribution_with_only_retries: dict->getFloat(
Payments_Failure_Rate_Distribution_With_Only_Retries->getStringFromVariant,
0.0,
),
connector: dict->getString(Connector->getStringFromVariant, ""),
payment_method: dict->getString(Payment_Method->getStringFromVariant, ""),
payment_method_type: dict->getString(Payment_Method_Type->getStringFromVariant, ""),
authentication_type: dict->getString(Authentication_Type->getStringFromVariant, ""),
}
}
let getObjects: JSON.t => array<failureSmartRetryDistributionObject> = json => {
json
->LogicUtils.getArrayFromJson([])
->Array.map(item => {
tableItemToObjMapper(item->getDictFromJsonObject)
})
}
let getHeading = colType => {
switch colType {
| Payments_Failure_Rate_Distribution_With_Only_Retries =>
Table.makeHeaderInfo(
~key=Payments_Failure_Rate_Distribution_With_Only_Retries->getStringFromVariant,
~title="Smart Retry Payments Failure Rate",
~dataType=TextType,
)
| Connector =>
Table.makeHeaderInfo(
~key=Connector->getStringFromVariant,
~title="Connector",
~dataType=TextType,
)
| Payment_Method =>
Table.makeHeaderInfo(
~key=Payment_Method->getStringFromVariant,
~title="Payment Method",
~dataType=TextType,
)
| Payment_Method_Type =>
Table.makeHeaderInfo(
~key=Payment_Method_Type->getStringFromVariant,
~title="Payment Method Type",
~dataType=TextType,
)
| Authentication_Type =>
Table.makeHeaderInfo(
~key=Authentication_Type->getStringFromVariant,
~title="Authentication Type",
~dataType=TextType,
)
}
}
let getCell = (obj, colType): Table.cell => {
switch colType {
| Payments_Failure_Rate_Distribution_With_Only_Retries =>
Text(obj.payments_failure_rate_distribution_with_only_retries->valueFormatter(Rate))
| Connector => Text(obj.connector)
| Payment_Method => Text(obj.payment_method)
| Payment_Method_Type => Text(obj.payment_method_type)
| Authentication_Type => Text(obj.authentication_type)
}
}
let getTableData = json => {
json->getArrayDataFromJson(tableItemToObjMapper)->Array.map(Nullable.make)
}
let tabs = [
{
label: "Connector",
value: Connector->getStringFromVariant,
},
{
label: "Payment Method",
value: Payment_Method->getStringFromVariant,
},
{
label: "Payment Method Type",
value: Payment_Method_Type->getStringFromVariant,
},
{
label: "Authentication Type",
value: Authentication_Type->getStringFromVariant,
},
]
let defaulGroupBy = {
label: "Connector",
value: Connector->getStringFromVariant,
}
| 994 | 9,637 |
hyperswitch-control-center | src/screens/NewAnalytics/SmartRetryAnalytics/FailureSmartRetryDistribution/FailureSmartRetryDistributionTypes.res | .res | type failureSmartRetryDistributionCols =
| Payments_Failure_Rate_Distribution_With_Only_Retries
| Connector
| Payment_Method
| Payment_Method_Type
| Authentication_Type
type failureSmartRetryDistributionObject = {
payments_failure_rate_distribution_with_only_retries: float,
connector: string,
payment_method: string,
payment_method_type: string,
authentication_type: string,
}
| 89 | 9,638 |
hyperswitch-control-center | src/screens/NewAnalytics/SmartRetryAnalytics/SuccessfulSmartRetryDistribution/SuccessfulSmartRetryDistributionTypes.res | .res | type successfulSmartRetryDistributionCols =
| Payments_Success_Rate_Distribution_With_Only_Retries
| Connector
| Payment_Method
| Payment_Method_Type
| Authentication_Type
type successfulSmartRetryDistributionObject = {
payments_success_rate_distribution_with_only_retries: float,
connector: string,
payment_method: string,
payment_method_type: string,
authentication_type: string,
}
| 88 | 9,639 |
hyperswitch-control-center | src/screens/NewAnalytics/SmartRetryAnalytics/SuccessfulSmartRetryDistribution/SuccessfulSmartRetryDistributionUtils.res | .res | open LogicUtils
open NewAnalyticsUtils
open SuccessfulSmartRetryDistributionTypes
let getStringFromVariant = value => {
switch value {
| Payments_Success_Rate_Distribution_With_Only_Retries => "payments_success_rate_distribution_with_only_retries"
| Connector => "connector"
| Payment_Method => "payment_method"
| Payment_Method_Type => "payment_method_type"
| Authentication_Type => "authentication_type"
}
}
let getColumn = string => {
switch string {
| "connector" => Connector
| "payment_method" => Payment_Method
| "payment_method_type" => Payment_Method_Type
| "authentication_type" => Authentication_Type
| _ => Connector
}
}
let successfulSmartRetryDistributionMapper = (
~params: NewAnalyticsTypes.getObjects<JSON.t>,
): BarGraphTypes.barGraphPayload => {
open BarGraphTypes
let {data, xKey, yKey} = params
let categories = [data]->JSON.Encode.array->getCategories(0, yKey)
let barGraphData = getBarGraphObj(
~array=data->getArrayFromJson([]),
~key=xKey,
~name=xKey->snakeToTitle,
~color="#7CC88F",
)
let title = {
text: "",
}
{
categories,
data: [barGraphData],
title,
tooltipFormatter: bargraphTooltipFormatter(
~title="Successful Smart Retry Distribution",
~metricType=Rate,
),
}
}
open NewAnalyticsTypes
let tableItemToObjMapper: Dict.t<JSON.t> => successfulSmartRetryDistributionObject = dict => {
{
payments_success_rate_distribution_with_only_retries: dict->getFloat(
Payments_Success_Rate_Distribution_With_Only_Retries->getStringFromVariant,
0.0,
),
connector: dict->getString(Connector->getStringFromVariant, ""),
payment_method: dict->getString(Payment_Method->getStringFromVariant, ""),
payment_method_type: dict->getString(Payment_Method_Type->getStringFromVariant, ""),
authentication_type: dict->getString(Authentication_Type->getStringFromVariant, ""),
}
}
let getObjects: JSON.t => array<successfulSmartRetryDistributionObject> = json => {
json
->LogicUtils.getArrayFromJson([])
->Array.map(item => {
tableItemToObjMapper(item->getDictFromJsonObject)
})
}
let getHeading = colType => {
switch colType {
| Payments_Success_Rate_Distribution_With_Only_Retries =>
Table.makeHeaderInfo(
~key=Payments_Success_Rate_Distribution_With_Only_Retries->getStringFromVariant,
~title="Smart Retry Payments Success Rate",
~dataType=TextType,
)
| Connector =>
Table.makeHeaderInfo(
~key=Connector->getStringFromVariant,
~title="Connector",
~dataType=TextType,
)
| Payment_Method =>
Table.makeHeaderInfo(
~key=Payment_Method->getStringFromVariant,
~title="Payment Method",
~dataType=TextType,
)
| Payment_Method_Type =>
Table.makeHeaderInfo(
~key=Payment_Method_Type->getStringFromVariant,
~title="Payment Method Type",
~dataType=TextType,
)
| Authentication_Type =>
Table.makeHeaderInfo(
~key=Authentication_Type->getStringFromVariant,
~title="Authentication Type",
~dataType=TextType,
)
}
}
let getCell = (obj, colType): Table.cell => {
switch colType {
| Payments_Success_Rate_Distribution_With_Only_Retries =>
Text(obj.payments_success_rate_distribution_with_only_retries->valueFormatter(Rate))
| Connector => Text(obj.connector)
| Payment_Method => Text(obj.payment_method)
| Payment_Method_Type => Text(obj.payment_method_type)
| Authentication_Type => Text(obj.authentication_type)
}
}
let getTableData = json => {
json->getArrayDataFromJson(tableItemToObjMapper)->Array.map(Nullable.make)
}
let tabs = [
{
label: "Connector",
value: Connector->getStringFromVariant,
},
{
label: "Payment Method",
value: Payment_Method->getStringFromVariant,
},
{
label: "Payment Method Type",
value: Payment_Method_Type->getStringFromVariant,
},
{
label: "Authentication Type",
value: Authentication_Type->getStringFromVariant,
},
]
let defaulGroupBy = {
label: "Connector",
value: Connector->getStringFromVariant,
}
| 989 | 9,640 |
hyperswitch-control-center | src/screens/NewAnalytics/SmartRetryAnalytics/SuccessfulSmartRetryDistribution/SuccessfulSmartRetryDistribution.res | .res | open NewAnalyticsTypes
open NewAnalyticsHelper
open BarGraphTypes
open NewSmartRetryAnalyticsEntity
open SuccessfulSmartRetryDistributionUtils
open SuccessfulSmartRetryDistributionTypes
module TableModule = {
@react.component
let make = (~data, ~className="", ~selectedTab: string) => {
let (offset, setOffset) = React.useState(_ => 0)
let defaultSort: Table.sortedObject = {
key: "",
order: Table.INC,
}
let visibleColumns =
[selectedTab->getColumn]->Array.concat([Payments_Success_Rate_Distribution_With_Only_Retries])
let tableData = getTableData(data)
<div className>
<LoadedTable
visibleColumns
title="Successful Payments Distribution"
hideTitle=true
actualData={tableData}
entity=successfulSmartRetryDistributionTableEntity
resultsPerPage=10
totalResults={tableData->Array.length}
offset
setOffset
defaultSort
currrentFetchCount={tableData->Array.length}
tableLocalFilter=false
tableheadingClass=tableBorderClass
tableBorderClass
ignoreHeaderBg=true
tableDataBorderClass=tableBorderClass
isAnalyticsModule=true
/>
</div>
}
}
module SuccessfulSmartRetryDistributionHeader = {
@react.component
let make = (~viewType, ~setViewType, ~groupBy, ~setGroupBy) => {
let setViewType = value => {
setViewType(_ => value)
}
let setGroupBy = value => {
setGroupBy(_ => value)
}
<div className="w-full px-7 py-8 flex justify-between">
<Tabs option={groupBy} setOption={setGroupBy} options={tabs} />
<div className="flex gap-2">
<TabSwitch viewType setViewType />
</div>
</div>
}
}
@react.component
let make = (
~entity: moduleEntity,
~chartEntity: chartEntity<barGraphPayload, barGraphOptions, JSON.t>,
) => {
open LogicUtils
open APIUtils
open NewAnalyticsUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let {filterValueJson} = React.useContext(FilterContext.filterContext)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (paymentsDistribution, setpaymentsDistribution) = React.useState(_ => JSON.Encode.array([]))
let (viewType, setViewType) = React.useState(_ => Graph)
let (groupBy, setGroupBy) = React.useState(_ => defaulGroupBy)
let startTimeVal = filterValueJson->getString("startTime", "")
let endTimeVal = filterValueJson->getString("endTime", "")
let currency = filterValueJson->getString((#currency: filters :> string), "")
let getPaymentsDistribution = async () => {
setScreenState(_ => PageLoaderWrapper.Loading)
try {
let url = getURL(
~entityName=V1(ANALYTICS_PAYMENTS),
~methodType=Post,
~id=Some((entity.domain: domain :> string)),
)
let filters = Dict.make()
filters->Dict.set("first_attempt", [false->JSON.Encode.bool]->JSON.Encode.array)
let body = requestBody(
~startTime=startTimeVal,
~endTime=endTimeVal,
~delta=entity.requestBodyConfig.delta,
~metrics=entity.requestBodyConfig.metrics,
~groupByNames=[groupBy.value]->Some,
~filter=generateFilterObject(
~globalFilters=filterValueJson,
~localFilters=filters->Some,
)->Some,
)
let response = await updateDetails(url, body, Post)
let responseData = response->getDictFromJsonObject->getArrayFromDict("queryData", [])
if responseData->Array.length > 0 {
setpaymentsDistribution(_ => responseData->JSON.Encode.array)
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Custom)
}
}
React.useEffect(() => {
if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString {
getPaymentsDistribution()->ignore
}
None
}, [startTimeVal, endTimeVal, groupBy.value, currency])
let params = {
data: paymentsDistribution,
xKey: Payments_Success_Rate_Distribution_With_Only_Retries->getStringFromVariant,
yKey: groupBy.value,
}
let options = chartEntity.getChatOptions(chartEntity.getObjects(~params))
<div>
<ModuleHeader title={entity.title} />
<Card>
<PageLoaderWrapper
screenState customLoader={<Shimmer layoutId=entity.title />} customUI={<NoData />}>
<SuccessfulSmartRetryDistributionHeader viewType setViewType groupBy setGroupBy />
<div className="mb-5">
{switch viewType {
| Graph => <BarGraph options className="mr-3" />
| Table =>
<TableModule data={paymentsDistribution} className="mx-7" selectedTab={groupBy.value} />
}}
</div>
</PageLoaderWrapper>
</Card>
</div>
}
| 1,155 | 9,641 |
hyperswitch-control-center | src/screens/Connectors/ConnectorTypes.res | .res | type steps = IntegFields | PaymentMethods | SummaryAndTest | Preview | AutomaticFlow
type connectorIntegrationField = {
placeholder?: string,
label?: string,
name: string,
isRequired?: bool,
encodeToBase64?: bool,
liveValidationRegex?: string,
testValidationRegex?: string,
liveExpectedFormat?: string,
testExpectedFormat?: string,
description?: string,
}
type metadataFields = {
google_pay?: array<connectorIntegrationField>,
apple_pay?: array<connectorIntegrationField>,
}
type integrationFields = {
description: string,
validate?: array<connectorIntegrationField>,
inputFieldDescription?: string,
}
type verifyResponse = Success | Failure | NoAttempt | Loading
type authType = [#HeaderKey | #BodyKey | #SignatureKey | #MultiAuthKey | #CurrencyAuthKey | #Nokey]
type cashToCodeMthd = [#Classic | #Evoucher]
type processorTypes =
| ADYEN
| CHECKOUT
| BRAINTREE
| BANKOFAMERICA
| BILLWERK
| AUTHORIZEDOTNET
| STRIPE
| KLARNA
| GLOBALPAY
| BLUESNAP
| AIRWALLEX
| WORLDPAY
| CYBERSOURCE
| COINGATE
| ELAVON
| ACI
| WORLDLINE
| FISERV
| FISERVIPG
| SHIFT4
| RAPYD
| PAYU
| NUVEI
| DLOCAL
| MULTISAFEPAY
| BAMBORA
| MOLLIE
| TRUSTPAY
| ZEN
| PAYPAL
| COINBASE
| OPENNODE
| PHONYPAY
| FAUXPAY
| PRETENDPAY
| NMI
| FORTE
| NEXINETS
| IATAPAY
| BITPAY
| CRYPTOPAY
| CASHTOCODE
| PAYME
| GLOBEPAY
| POWERTRANZ
| TSYS
| NOON
| STRIPE_TEST
| PAYPAL_TEST
| STAX
| GOCARDLESS
| VOLT
| PROPHETPAY
| HELCIM
| PLACETOPAY
| ZSL
| MIFINITY
| RAZORPAY
| BAMBORA_APAC
| ITAUBANK
| DATATRANS
| PLAID
| SQUARE
| PAYBOX
| WELLSFARGO
| FIUU
| NOVALNET
| DEUTSCHEBANK
| NEXIXPAY
| XENDIT
| JPMORGAN
| INESPAY
| MONERIS
| REDSYS
| HIPAY
| PAYSTACK
type payoutProcessorTypes =
| ADYEN
| ADYENPLATFORM
| CYBERSOURCE
| EBANX
| PAYPAL
| STRIPE
| WISE
| NOMUPAY
type threeDsAuthenticatorTypes =
THREEDSECUREIO | NETCETERA | CLICK_TO_PAY_MASTERCARD | JUSPAYTHREEDSSERVER | CLICK_TO_PAY_VISA
type frmTypes =
| Signifyd
| Riskifyed
type pmAuthenticationProcessorTypes = PLAID
type taxProcessorTypes = TAXJAR
type billingProcessorTypes = CHARGEBEE
type connectorTypeVariants =
| PaymentProcessor
| PaymentVas
| PayoutProcessor
| AuthenticationProcessor
| PMAuthProcessor
| TaxProcessor
| BillingProcessor
type connectorTypes =
| Processors(processorTypes)
| PayoutProcessor(payoutProcessorTypes)
| ThreeDsAuthenticator(threeDsAuthenticatorTypes)
| FRM(frmTypes)
| PMAuthenticationProcessor(pmAuthenticationProcessorTypes)
| TaxProcessor(taxProcessorTypes)
| BillingProcessor(billingProcessorTypes)
| UnknownConnector(string)
type paymentMethod =
| Card
| PayLater
| Wallet
| BankRedirect
| BankTransfer
| Crypto
| BankDebit
| UnknownPaymentMethod(string)
type paymentMethodTypes =
| Credit
| Debit
| GooglePay
| ApplePay
| SamsungPay
| PayPal
| Klarna
| BankDebit
| OpenBankingPIS
| Paze
| AliPay
| WeChatPay
| DirectCarrierBilling
| UnknownPaymentMethodType(string)
type advancedConfigurationList = {
@as("type") type_: string,
list: array<string>,
}
type advancedConfiguration = {options: advancedConfigurationList}
type paymentMethodConfigCommonType = {
card_networks: array<string>,
accepted_currencies: option<advancedConfigurationList>,
accepted_countries: option<advancedConfigurationList>,
minimum_amount: option<int>,
maximum_amount: option<int>,
recurring_enabled: option<bool>,
installment_payment_enabled: option<bool>,
payment_experience: option<string>,
}
type paymentMethodConfigType = {
payment_method_type: string,
...paymentMethodConfigCommonType,
}
type paymentMethodConfigTypeV2 = {
payment_method_subtype: string,
...paymentMethodConfigCommonType,
}
type paymentMethodEnabled = {
payment_method: string,
payment_method_type: string,
provider?: array<paymentMethodConfigType>,
card_provider?: array<paymentMethodConfigType>,
}
type applePay = {
merchant_identifier: string,
certificate: string,
display_name: string,
initiative_context: string,
certificate_keys: string,
}
type googlePay = {
merchant_name: string,
publishable_key?: string,
merchant_id: string,
}
type metaData = {
apple_pay?: applePay,
goole_pay?: googlePay,
}
type pmAuthPaymentMethods = {
payment_method: string,
payment_method_type: string,
connector_name: string,
mca_id: string,
}
type wasmRequest = {
payment_methods_enabled: array<paymentMethodEnabled>,
connector: string,
}
type wasmExtraPayload = {
profile_id: string,
connector_type: string,
connector_name: string,
connector_account_details: JSON.t,
disabled: bool,
test_mode: bool,
connector_webhook_details: option<JSON.t>,
}
// This type are used for FRM configuration which need to moved to wasm
type headerKey = {auth_type: string, api_key: string}
type bodyKey = {
auth_type: string,
api_key: string,
key1: string,
}
type signatureKey = {
auth_type: string,
api_key: string,
key1: string,
api_secret: string,
}
type multiAuthKey = {
auth_type: string,
api_key: string,
key1: string,
api_secret: string,
key2: string,
}
type currencyKey = {
auth_type: string,
merchant_id_classic: string,
password_classic: string,
username_classic: string,
}
type currencyAuthKey = {auth_key_map: Js.Dict.t<JSON.t>, auth_type: string}
type certificateAuth = {
auth_type: string,
certificate: string,
private_key: string,
}
type connectorAuthType =
| HeaderKey
| BodyKey
| SignatureKey
| MultiAuthKey
| CurrencyAuthKey
| CertificateAuth
| UnKnownAuthType
type connectorAuthTypeObj =
| HeaderKey(headerKey)
| BodyKey(bodyKey)
| SignatureKey(signatureKey)
| MultiAuthKey(multiAuthKey)
| CurrencyAuthKey(currencyAuthKey)
| CertificateAuth(certificateAuth)
| UnKnownAuthType(JSON.t)
type paymentMethodEnabledType = {
payment_method: string,
mutable payment_method_types: array<paymentMethodConfigType>,
}
type paymentMethodEnabledTypeV2 = {
payment_method_type: string,
payment_method_subtypes: array<paymentMethodConfigTypeV2>,
}
type payment_methods_enabled = array<paymentMethodEnabledType>
type payment_methods_enabledV2 = array<paymentMethodEnabledTypeV2>
type frm_payment_method_type = {
payment_method_type: string,
flow: string,
action: string,
}
type frm_payment_method = {
payment_method: string,
payment_method_types?: array<frm_payment_method_type>,
flow: string,
}
type frm_config = {
gateway: string,
mutable payment_methods: array<frm_payment_method>,
}
type connectorPayload = {
connector_type: connectorTypeVariants,
connector_name: string,
connector_label: string,
connector_account_details: connectorAuthTypeObj,
test_mode: bool,
disabled: bool,
payment_methods_enabled: payment_methods_enabled,
profile_id: string,
metadata: JSON.t,
merchant_connector_id: string,
frm_configs?: array<frm_config>,
status: string,
connector_webhook_details: JSON.t,
additional_merchant_data: JSON.t,
}
type connectorPayloadV2 = {
connector_type: connectorTypeVariants,
connector_name: string,
connector_label: string,
connector_account_details: connectorAuthTypeObj,
disabled: bool,
payment_methods_enabled: payment_methods_enabledV2,
profile_id: string,
metadata: JSON.t,
id: string,
frm_configs: array<frm_config>,
status: string,
connector_webhook_details: JSON.t,
additional_merchant_data: JSON.t,
feature_metadata: JSON.t,
}
type connector =
| FRMPlayer
| Processor
| PayoutProcessor
| ThreeDsAuthenticator
| PMAuthenticationProcessor
| TaxProcessor
| BillingProcessor
| 2,182 | 9,642 |
hyperswitch-control-center | src/screens/Connectors/ConnectorUtils.res | .res | open ConnectorTypes
type data = {code?: string, message?: string, type_?: string}
@scope("JSON") @val
external parseIntoMyData: string => data = "parse"
let stepsArr = [IntegFields, PaymentMethods, SummaryAndTest]
let payoutStepsArr = [IntegFields, PaymentMethods, SummaryAndTest]
let getStepName = step => {
switch step {
| IntegFields => "Credentials"
| PaymentMethods => "Payment Methods"
| SummaryAndTest => "Summary"
| Preview => "Preview"
| AutomaticFlow => "AutomaticFlow"
}
}
let payoutConnectorList: array<connectorTypes> = [
PayoutProcessor(ADYEN),
PayoutProcessor(ADYENPLATFORM),
PayoutProcessor(CYBERSOURCE),
PayoutProcessor(EBANX),
PayoutProcessor(PAYPAL),
PayoutProcessor(STRIPE),
PayoutProcessor(WISE),
PayoutProcessor(NOMUPAY),
]
let threedsAuthenticatorList: array<connectorTypes> = [
ThreeDsAuthenticator(THREEDSECUREIO),
ThreeDsAuthenticator(NETCETERA),
ThreeDsAuthenticator(CLICK_TO_PAY_MASTERCARD),
ThreeDsAuthenticator(JUSPAYTHREEDSSERVER),
ThreeDsAuthenticator(CLICK_TO_PAY_VISA),
]
let threedsAuthenticatorListForLive: array<connectorTypes> = [ThreeDsAuthenticator(NETCETERA)]
let pmAuthenticationConnectorList: array<connectorTypes> = [PMAuthenticationProcessor(PLAID)]
let taxProcessorList: array<connectorTypes> = [TaxProcessor(TAXJAR)]
let connectorList: array<connectorTypes> = [
Processors(STRIPE),
Processors(PAYPAL),
Processors(ACI),
Processors(ADYEN),
Processors(AIRWALLEX),
Processors(AUTHORIZEDOTNET),
Processors(BANKOFAMERICA),
Processors(BAMBORA),
Processors(BILLWERK),
Processors(BITPAY),
Processors(BLUESNAP),
Processors(BRAINTREE),
Processors(CASHTOCODE),
Processors(CHECKOUT),
Processors(COINBASE),
Processors(COINGATE),
Processors(CRYPTOPAY),
Processors(CYBERSOURCE),
Processors(DATATRANS),
Processors(DLOCAL),
Processors(ELAVON),
Processors(FISERV),
Processors(FISERVIPG),
Processors(FORTE),
Processors(GLOBALPAY),
Processors(GLOBEPAY),
Processors(GOCARDLESS),
Processors(HELCIM),
Processors(IATAPAY),
Processors(KLARNA),
Processors(MIFINITY),
Processors(MOLLIE),
Processors(MULTISAFEPAY),
Processors(NEXINETS),
Processors(NMI),
Processors(NOON),
Processors(NUVEI),
Processors(OPENNODE),
Processors(PAYME),
Processors(PAYU),
Processors(POWERTRANZ),
Processors(PROPHETPAY),
Processors(RAPYD),
Processors(SHIFT4),
Processors(STAX),
Processors(TRUSTPAY),
Processors(TSYS),
Processors(VOLT),
Processors(WORLDLINE),
Processors(WORLDPAY),
Processors(ZEN),
Processors(ZSL),
Processors(PLACETOPAY),
Processors(RAZORPAY),
Processors(BAMBORA_APAC),
Processors(ITAUBANK),
Processors(PLAID),
Processors(SQUARE),
Processors(PAYBOX),
Processors(FIUU),
Processors(WELLSFARGO),
Processors(NOVALNET),
Processors(DEUTSCHEBANK),
Processors(NEXIXPAY),
Processors(JPMORGAN),
Processors(XENDIT),
Processors(INESPAY),
Processors(MONERIS),
Processors(REDSYS),
Processors(HIPAY),
Processors(PAYSTACK),
]
let connectorListForLive: array<connectorTypes> = [
Processors(ADYEN),
Processors(AUTHORIZEDOTNET),
Processors(BANKOFAMERICA),
Processors(BLUESNAP),
Processors(BAMBORA),
Processors(BRAINTREE),
Processors(CHECKOUT),
Processors(CRYPTOPAY),
Processors(CASHTOCODE),
Processors(CYBERSOURCE),
Processors(COINGATE),
Processors(DATATRANS),
Processors(FIUU),
Processors(IATAPAY),
Processors(KLARNA),
Processors(MIFINITY),
Processors(NMI),
Processors(NOVALNET),
Processors(PAYPAL),
Processors(PAYBOX),
Processors(PAYME),
Processors(STRIPE),
Processors(TRUSTPAY),
Processors(VOLT),
Processors(WORLDPAY),
Processors(ZSL),
Processors(ZEN),
]
let connectorListWithAutomaticFlow = [PAYPAL]
let getPaymentMethodFromString = paymentMethod => {
switch paymentMethod->String.toLowerCase {
| "card" => Card
| "debit" | "credit" => Card
| "pay_later" => PayLater
| "wallet" => Wallet
| "bank_redirect" => BankRedirect
| "bank_transfer" => BankTransfer
| "crypto" => Crypto
| "bank_debit" => BankDebit
| _ => UnknownPaymentMethod(paymentMethod)
}
}
let getPaymentMethodTypeFromString = paymentMethodType => {
switch paymentMethodType->String.toLowerCase {
| "credit" => Credit
| "debit" => Debit
| "google_pay" => GooglePay
| "apple_pay" => ApplePay
| "paypal" => PayPal
| "klarna" => Klarna
| "open_banking_pis" => OpenBankingPIS
| "samsung_pay" => SamsungPay
| "paze" => Paze
| "alipay" => AliPay
| "wechatpay" => WeChatPay
| "directcarrierbilling" => DirectCarrierBilling
| _ => UnknownPaymentMethodType(paymentMethodType)
}
}
let dummyConnectorList = isTestProcessorsEnabled =>
isTestProcessorsEnabled
? [
Processors(STRIPE_TEST),
Processors(PAYPAL_TEST),
Processors(FAUXPAY),
Processors(PRETENDPAY),
]
: []
let checkIsDummyConnector = (connectorName, isTestProcessorsEnabled) =>
if isTestProcessorsEnabled {
switch connectorName {
| Processors(STRIPE_TEST)
| Processors(PAYPAL_TEST)
| Processors(FAUXPAY)
| Processors(PRETENDPAY) => true
| _ => false
}
} else {
false
}
let stripeInfo = {
description: "Versatile processor supporting credit cards, digital wallets, and bank transfers.",
validate: [
{
name: "connector_account_details.api_key",
liveValidationRegex: "^sk_live_(.+)$",
testValidationRegex: "^sk_test_(.+)$",
liveExpectedFormat: "Secret key should have the prefix sk_live_",
testExpectedFormat: "Secret key should have the prefix sk_test_",
},
],
}
let goCardLessInfo = {
description: "Simplify payment collection with a single, hassle-free integration across 30+ countries for Direct Debit payments.",
}
let adyenInfo = {
description: "Global processor accepting major credit cards, e-wallets, and local payment methods.",
}
let adyenPlatformInfo = {
description: "Send payout to third parties with Adyen's Balance Platform!",
}
let checkoutInfo = {
description: "Streamlined processor offering multiple payment options for a seamless checkout experience.",
validate: [
{
name: "connector_account_details.api_key",
liveValidationRegex: "^pk(?!_sbox).*",
testValidationRegex: "^pk(_sbox)?_(.+)$",
liveExpectedFormat: "API public key should begin with pk_ and not begin with pk_sbox_",
testExpectedFormat: "API public key should begin with pk_",
},
{
name: "connector_account_details.api_secret",
liveValidationRegex: "^sk(?!_sbox).*",
testValidationRegex: "^sk(_sbox)?_(.+)$",
liveExpectedFormat: "API secret key should begin with sk_ and not begin with sk_sbox_",
testExpectedFormat: "API secret key should begin with sk_",
},
],
}
let braintreeInfo = {
description: "Trusted processor supporting credit cards, e-checks, and mobile payments for secure online transactions.",
}
let klarnaInfo = {
description: "Flexible processor offering buy now, pay later options, and seamless checkout experiences for shoppers.",
inputFieldDescription: `Please enter API Key in this format: Basic {API Key}\n
Ex: If your API key is UE4wO please enter Basic UE4wO`,
}
let authorizedotnetInfo = {
description: "Trusted processor supporting credit cards, e-checks, and mobile payments for secure online transactions.",
}
let globalpayInfo = {
description: "Comprehensive processor providing global payment solutions for businesses of all sizes.",
}
let bluesnapInfo = {
description: "All-in-one processor supporting global payment methods, subscription billing, and built-in fraud prevention.",
}
let airwallexInfo = {
description: "Innovative processor enabling businesses to manage cross-border payments and foreign exchange seamlessly.",
}
let worldpayInfo = {
description: "Leading processor facilitating secure online and in-person payments with global coverage and a range of payment options.",
}
let cybersourceInfo = {
description: "Reliable processor providing fraud management tools, secure payment processing, and a variety of payment methods.",
}
let coingateInfo = {
description: "CoinGate is a cryptocurrency payment gateway that enables businesses to accept Bitcoin, Ethereum, and other cryptocurrencies as payment. It provides APIs, plugins, and point-of-sale solutions for merchants, supporting features like automatic conversion to fiat, payouts, and payment processing for various blockchain networks.",
}
let ebanxInfo = {
description: "Ebanx enables global organizations to grow exponentially in Rising Markets by leveraging a platform of end-to-end localized payment and financial solutions.",
}
let elavonInfo = {
description: "Elavon is a global payment processing company that provides businesses with secure and reliable payment solutions. As a subsidiary of U.S. Bank, Elavon serves merchants in various industries, offering services such as credit card processing, mobile payments, e-commerce solutions, and fraud prevention tools.",
}
let aciInfo = {
description: "Trusted processor offering a wide range of payment solutions, including cards, digital wallets, and real-time bank transfers.",
}
let worldlineInfo = {
description: "Comprehensive processor supporting secure payment acceptance across various channels and devices with advanced security features.",
}
let fiservInfo = {
description: "Full-service processor offering secure payment solutions and innovative banking technologies for businesses of all sizes.",
}
let fiservIPGInfo = {
description: "Internet Payment Gateway(IPG) is an application from Fiserv which offers Internet payment services in Europe, Middle East and Africa.",
}
let shift4Info = {
description: "Integrated processor providing secure payment processing, advanced fraud prevention, and comprehensive reporting and analytics.",
}
let rapydInfo = {
description: "Flexible processor enabling businesses to accept and disburse payments globally with a wide range of payment methods.",
}
let payuInfo = {
description: "Reliable processor offering easy integration, multiple payment methods, and localized solutions for global businesses.",
}
let nuveiInfo = {
description: "Payment technology company providing flexible, scalable, and secure payment solutions for businesses across various industries.",
}
let dlocalInfo = {
description: "Cross-border payment processor enabling businesses to accept and send payments in emerging markets worldwide.",
}
let multisafepayInfo = {
description: "Versatile processor supporting a wide range of payment methods, including credit cards, e-wallets, and online banking.",
}
let bamboraInfo = {
description: "Comprehensive processor offering secure payment solutions and advanced features for businesses in various industries.",
}
let zenInfo = {
description: "Modern processor providing seamless payment solutions with a focus on simplicity, security, and user experience.",
}
let mollieInfo = {
description: "Developer-friendly processor providing simple and customizable payment solutions for businesses of all sizes.",
}
let trustpayInfo = {
description: "Reliable processor offering secure online payment solutions, including credit cards, bank transfers, and e-wallets.",
}
let paypalInfo = {
description: "Well-known processor enabling individuals and businesses to send, receive, and manage online payments securely.",
}
let coinbaseInfo = {
description: "Cryptocurrency processor allowing businesses to accept digital currencies like Bitcoin, Ethereum, and more.",
}
let openNodeInfo = {
description: "Bitcoin payment processor enabling businesses to accept Bitcoin payments and settle in their local currency.",
}
let nmiInfo = {
description: "Versatile payment processor supporting various payment methods and offering advanced customization and integration capabilities.",
}
let iataPayInfo = {
description: "IATA Pay is an alternative method for travelers to pay for air tickets purchased online by directly debiting their bank account. It improves speed and security of payments, while reducing payment costs.",
}
let bitPayInfo = {
description: "BitPay is a payment service provider that allows businesses and individuals to accept and process payments in Bitcoin and other cryptocurrencies securely and conveniently.",
}
let nexinetsInfo = {
description: "Leading Italian payment processor providing a wide range of payment solutions for businesses of all sizes.",
}
let forteInfo = {
description: "Payment processor specializing in secure and reliable payment solutions for variuos industries like healthcare.",
}
let cryptopayInfo = {
description: "Secure cryptocurrency payment solution. Simplify transactions with digital currencies. Convenient and reliable.",
}
let cashToCodeInfo = {
description: "Secure cash-based payment solution. Generate barcode, pay with cash at retail. Convenient alternative for cash transactions online.",
}
let powertranzInfo = {
description: "Versatile processor empowering businesses with flexible payment solutions for online and mobile transactions.",
}
let paymeInfo = {
description: "Convenient and secure mobile payment solution for quick transactions anytime, anywhere.",
}
let globepayInfo = {
description: "Global gateway for seamless cross-border payments, ensuring efficient transactions worldwide.",
}
let tsysInfo = {
description: "Trusted provider offering reliable payment processing services to businesses of all sizes across the globe.",
}
let noonInfo = {
description: "A leading fintech company revolutionizing payments with innovative, secure, and convenient solutions for seamless financial transactions.",
}
let jpmorganInfo = {
description: "JPMorgan Connector is a payment integration module that supports businesses in regions like the United States (US), United Kingdom (UK), European Union (EU), and Canada (CA). It streamlines payment operations by enabling seamless processing of authorizations, captures, and refunds through JPMorgan’s payment gateway. This robust solution helps businesses manage transactions efficiently, ensuring secure and compliant payment processing across these regions.",
}
let xenditInfo = {
description: "Xendit is a financial technology company that provides payment infrastructure across Southeast Asia. Its platform enables businesses to accept payments, disburse funds, manage accounts, and streamline financial operations",
}
let inespayInfo = {
description: "Inespay is an online bank transfer payment gateway that operates in three simple steps without the need for prior registration. It is registered as a payment institution authorized by the Bank of Spain with number 6902. Specializing in integrating bank transfer as an online payment method on all kinds of web platforms, especially in B2B environments. It collaborates with leaders in various economic sectors, offering a real-time bank transfer income service and automatic reconciliation.",
}
let monerisInfo = {
description: "Unify your retail operations with the combined power of Moneris and Wix, in an all-in-one omnichannel POS solution.",
}
let redsysInfo = {
description: "Redsys is a Spanish payment gateway offering secure and innovative payment solutions for merchants and banks.",
}
let hipayInfo = {
description: "HiPay is a global payment service provider offering a range of solutions for online, mobile, and in-store payments. It supports multiple payment methods, including credit cards, e-wallets, and local payment options, with a focus on fraud prevention and data-driven insights.",
}
let paystackInfo = {
description: "Paystack is a technology company solving payments problems for ambitious businesses. Paystack builds technology to help Africa's best businesses grow - from new startups, to market leaders launching new business models.",
}
// Dummy Connector Info
let pretendpayInfo = {
description: "Don't be fooled by the name - PretendPay is the real deal when it comes to testing your payments.",
}
let fauxpayInfo = {
description: "Don't worry, it's not really fake - it's just FauxPay! Use it to simulate payments and refunds.",
}
let phonypayInfo = {
description: "Don't want to use real money to test your payment flow? - PhonyPay lets you simulate payments and refunds",
}
let stripeTestInfo = {
description: "A stripe test processor to test payments and refunds without real world consequences.",
}
let paypalTestInfo = {
description: "A paypal test processor to simulate payment flows and experience hyperswitch checkout.",
}
let wiseInfo = {
description: "Get your money moving internationally. Save up to 3.9x when you send with Wise.",
}
let staxInfo = {
description: "Empowering businesses with effortless payment solutions for truly seamless transactions",
}
let voltInfo = {
description: "A secure and versatile payment processor that facilitates seamless electronic transactions for businesses and individuals, offering a wide range of payment options and robust fraud protection.",
}
let prophetpayInfo = {
description: "A secure, affordable, and easy-to-use credit card processing platform for any business.",
}
let helcimInfo = {
description: "Helcim is the easy and affordable solution for small businesses accepting credit card payments.",
}
let threedsecuredotioInfo = {
description: "A secure, affordable and easy to connect 3DS authentication platform. Improve the user experience during checkout, enhance the conversion rates and stay compliant with the regulations with 3dsecure.io",
}
let netceteraInfo = {
description: "Cost-effective 3DS authentication platform ensuring security. Elevate checkout experience, boost conversion rates, and maintain regulatory compliance with Netcetera",
}
let clickToPayInfo = {
description: "Secure online payment method that allows customers to make purchases without manually entering their card details or reaching for their card",
}
let clickToPayVisaInfo = {
description: "Secure online payment method that allows customers to make purchases without manually entering their card details or reaching for their card",
}
let juspayThreeDsServerInfo = {
description: "Juspay's cost-effective 3DS platform, ensures security, compliance, and seamless checkout—reducing fraud, boosting conversions, and enhancing customer trust with frictionless authentication.",
}
let unknownConnectorInfo = {
description: "unkown connector",
}
let bankOfAmericaInfo = {
description: "A top financial firm offering banking, investing, and risk solutions to individuals and businesses.",
}
let placetopayInfo = {
description: "Reliable payment processor facilitating secure transactions online for businesses, ensuring seamless transactions.",
}
let billwerkInfo = {
description: "Billwerk+ Pay is an acquirer independent payment gateway that helps you get the best acquirer rates, select a wide variety of payment methods.",
}
let mifinityInfo = {
description: "Empowering you to pay online, receive funds, and send money globally, the MiFinity eWallet supports super-low fees, offering infinite possibilities to do more of the things you love.",
}
let zslInfo = {
description: "It is a payment processor that enables businesses to accept payments securely through local bank transfers.",
}
let razorpayInfo = {
description: "Razorpay helps you accept online payments from customers across Desktop, Mobile web, Android & iOS. Additionally by using Razorpay Payment Links, you can collect payments across multiple channels like SMS, Email, Whatsapp, Chatbots & Messenger.",
}
let bamboraApacInfo = {
description: "Bambora offers the ability to securely and efficiently process online, real-time transactions via an API, our user-friendly interface. The API web service accepts and processes SOAP requests from a remote location over TCP/IP. Transaction results are returned in real-time via the API.",
}
let itauBankInfo = {
description: "The Banking as a Service (BaaS) solution allows non-financial companies to offer services with the ecosystem that banking institutions have. Itaú as a Service (IaaS) is the ideal tool for your company to improve your customers' experience, offering a whole new portfolio of products, with Itaú's technology and security.",
}
let dataTransInfo = {
description: "Datatrans is a Swiss payment service provider offering secure online, mobile, and in-store payment processing. Key features include support for multiple payment methods, fraud prevention, multi-currency transactions, and integration options for websites and apps.",
}
let plaidInfo = {
description: "Plaid Link makes it easy for users to connect their financial accounts securely and quickly, giving you the best growth for your business.",
}
let squareInfo = {
description: "Powering all the ways you do business. Work smarter, automate for efficiency, and open up new revenue streams on the software and hardware platform millions of businesses trust.",
}
let payboxInfo = {
description: "Paybox, operated by Verifone, offers secure online payment solutions for e-commerce businesses. It supports a wide range of payment methods and provides features like one-click payments, recurring payments, and omnichannel payment processing. Their services cater to merchants, web agencies, integrators, and financial institutions, helping them accept various forms of payment",
}
let wellsfargoInfo = {
description: "WellsFargo is a leading American financial services company providing a comprehensive range of banking, investment, and mortgage products. With a focus on personal, small business, and commercial banking, Wells Fargo offers services such as checking and savings accounts, loans, credit cards, wealth management, and payment processing solutions.",
}
let fiuuInfo = {
description: "Fiuu has been the premier merchant service provider in Southeast Asia since 2005, connecting international brands to consumers across the region. The company helps its clients establish a foothold in Southeast Asia's market by offering a full range of alternative payment methods, such as online banking, cash at 7-Eleven (Fiuu Cash), e-wallets, and more. Fiuu provides comprehensive payment solutions to facilitate market entry and expansion for businesses looking to reach Southeast Asian consumers.",
}
let novalnetInfo = {
description: "Novalnet is a global payment service provider and financial technology company based in Germany. It offers a wide range of payment processing solutions and services to merchants and businesses, enabling them to accept various forms of payments online, in-store, or through mobile platforms.",
}
let deutscheBankInfo = {
description: "Deutsche Bank is a German multinational investment bank and financial services company.",
}
let taxJarInfo = {
description: "TaxJar is reimagining how businesses manage sales tax compliance. Its cloud-based platform automates the entire sales tax life cycle across all sales channels — from calculations and nexus tracking to reporting and filing.",
}
let chargebeeInfo = {
description: "Chargebee is a subscription management and billing platform that integrates with multiple payment gateways, allowing businesses to accept payments across various geographies and currencies.",
}
let nexixpayInfo = {
description: "Nexi's latest generation virtual POS is designed for those who, through a website, want to sell goods or services by managing payments online.",
}
let nomupayInfo = {
description: "A payment processing and software provider, that offers solutions such as e-commerce solutions, subscription billing services, payment gateways, and merchant accounts, to businesses of all sizes.",
}
let signifydInfo = {
description: "One platform to protect the entire shopper journey end-to-end",
validate: [
{
placeholder: "Enter API Key",
label: "API Key",
name: "connector_account_details.api_key",
isRequired: true,
encodeToBase64: false,
},
],
}
let riskifyedInfo = {
description: "Frictionless fraud management for eCommerce",
validate: [
{
placeholder: "Enter Secret token",
label: "Secret token",
name: "connector_account_details.api_key",
isRequired: true,
encodeToBase64: false,
},
{
placeholder: "Enter Domain name",
label: "Domain name",
name: "connector_account_details.key1",
isRequired: true,
encodeToBase64: false,
},
],
}
let getConnectorNameString = (connector: processorTypes) =>
switch connector {
| ADYEN => "adyen"
| CHECKOUT => "checkout"
| BRAINTREE => "braintree"
| AUTHORIZEDOTNET => "authorizedotnet"
| STRIPE => "stripe"
| KLARNA => "klarna"
| GLOBALPAY => "globalpay"
| BLUESNAP => "bluesnap"
| AIRWALLEX => "airwallex"
| WORLDPAY => "worldpay"
| CYBERSOURCE => "cybersource"
| COINGATE => "coingate"
| ELAVON => "elavon"
| ACI => "aci"
| WORLDLINE => "worldline"
| FISERV => "fiserv"
| SHIFT4 => "shift4"
| RAPYD => "rapyd"
| PAYU => "payu"
| NUVEI => "nuvei"
| MULTISAFEPAY => "multisafepay"
| DLOCAL => "dlocal"
| BAMBORA => "bambora"
| MOLLIE => "mollie"
| TRUSTPAY => "trustpay"
| ZEN => "zen"
| PAYPAL => "paypal"
| COINBASE => "coinbase"
| OPENNODE => "opennode"
| NMI => "nmi"
| FORTE => "forte"
| NEXINETS => "nexinets"
| IATAPAY => "iatapay"
| BITPAY => "bitpay"
| PHONYPAY => "phonypay"
| FAUXPAY => "fauxpay"
| PRETENDPAY => "pretendpay"
| CRYPTOPAY => "cryptopay"
| CASHTOCODE => "cashtocode"
| PAYME => "payme"
| GLOBEPAY => "globepay"
| POWERTRANZ => "powertranz"
| TSYS => "tsys"
| NOON => "noon"
| STRIPE_TEST => "stripe_test"
| PAYPAL_TEST => "paypal_test"
| STAX => "stax"
| GOCARDLESS => "gocardless"
| VOLT => "volt"
| PROPHETPAY => "prophetpay"
| BANKOFAMERICA => "bankofamerica"
| HELCIM => "helcim"
| PLACETOPAY => "placetopay"
| BILLWERK => "billwerk"
| MIFINITY => "mifinity"
| ZSL => "zsl"
| RAZORPAY => "razorpay"
| BAMBORA_APAC => "bamboraapac"
| ITAUBANK => "itaubank"
| DATATRANS => "datatrans"
| PLAID => "plaid"
| SQUARE => "square"
| PAYBOX => "paybox"
| WELLSFARGO => "wellsfargo"
| FISERVIPG => "fiservemea"
| FIUU => "fiuu"
| NOVALNET => "novalnet"
| DEUTSCHEBANK => "deutschebank"
| NEXIXPAY => "nexixpay"
| JPMORGAN => "jpmorgan"
| XENDIT => "xendit"
| INESPAY => "inespay"
| MONERIS => "moneris"
| REDSYS => "redsys"
| HIPAY => "hipay"
| PAYSTACK => "paystack"
}
let getPayoutProcessorNameString = (payoutProcessor: payoutProcessorTypes) =>
switch payoutProcessor {
| ADYEN => "adyen"
| ADYENPLATFORM => "adyenplatform"
| CYBERSOURCE => "cybersource"
| EBANX => "ebanx"
| PAYPAL => "paypal"
| STRIPE => "stripe"
| WISE => "wise"
| NOMUPAY => "nomupay"
}
let getThreeDsAuthenticatorNameString = (threeDsAuthenticator: threeDsAuthenticatorTypes) =>
switch threeDsAuthenticator {
| THREEDSECUREIO => "threedsecureio"
| NETCETERA => "netcetera"
| CLICK_TO_PAY_MASTERCARD => "ctp_mastercard"
| JUSPAYTHREEDSSERVER => "juspaythreedsserver"
| CLICK_TO_PAY_VISA => "ctp_visa"
}
let getFRMNameString = (frm: frmTypes) => {
switch frm {
| Signifyd => "signifyd"
| Riskifyed => "riskified"
}
}
let getPMAuthenticationConnectorNameString = (
pmAuthenticationConnector: pmAuthenticationProcessorTypes,
) => {
switch pmAuthenticationConnector {
| PLAID => "plaid"
}
}
let getTaxProcessorNameString = (taxProcessor: taxProcessorTypes) => {
switch taxProcessor {
| TAXJAR => "taxjar"
}
}
let getBillingProcessorNameString = (billingProcessor: billingProcessorTypes) => {
switch billingProcessor {
| CHARGEBEE => "chargebee"
}
}
let getConnectorNameString = (connector: connectorTypes) => {
switch connector {
| Processors(connector) => connector->getConnectorNameString
| PayoutProcessor(connector) => connector->getPayoutProcessorNameString
| ThreeDsAuthenticator(threeDsAuthenticator) =>
threeDsAuthenticator->getThreeDsAuthenticatorNameString
| FRM(frmConnector) => frmConnector->getFRMNameString
| PMAuthenticationProcessor(pmAuthenticationConnector) =>
pmAuthenticationConnector->getPMAuthenticationConnectorNameString
| TaxProcessor(taxProcessor) => taxProcessor->getTaxProcessorNameString
| BillingProcessor(billingProcessor) => billingProcessor->getBillingProcessorNameString
| UnknownConnector(str) => str
}
}
let getConnectorNameTypeFromString = (connector, ~connectorType=ConnectorTypes.Processor) => {
switch connectorType {
| Processor =>
switch connector {
| "adyen" => Processors(ADYEN)
| "checkout" => Processors(CHECKOUT)
| "braintree" => Processors(BRAINTREE)
| "authorizedotnet" => Processors(AUTHORIZEDOTNET)
| "stripe" => Processors(STRIPE)
| "klarna" => Processors(KLARNA)
| "globalpay" => Processors(GLOBALPAY)
| "bluesnap" => Processors(BLUESNAP)
| "airwallex" => Processors(AIRWALLEX)
| "worldpay" => Processors(WORLDPAY)
| "cybersource" => Processors(CYBERSOURCE)
| "elavon" => Processors(ELAVON)
| "coingate" => Processors(COINGATE)
| "aci" => Processors(ACI)
| "worldline" => Processors(WORLDLINE)
| "fiserv" => Processors(FISERV)
| "fiservemea" => Processors(FISERVIPG)
| "shift4" => Processors(SHIFT4)
| "rapyd" => Processors(RAPYD)
| "payu" => Processors(PAYU)
| "nuvei" => Processors(NUVEI)
| "multisafepay" => Processors(MULTISAFEPAY)
| "dlocal" => Processors(DLOCAL)
| "bambora" => Processors(BAMBORA)
| "mollie" => Processors(MOLLIE)
| "trustpay" => Processors(TRUSTPAY)
| "zen" => Processors(ZEN)
| "paypal" => Processors(PAYPAL)
| "coinbase" => Processors(COINBASE)
| "opennode" => Processors(OPENNODE)
| "nmi" => Processors(NMI)
| "forte" => Processors(FORTE)
| "nexinets" => Processors(NEXINETS)
| "iatapay" => Processors(IATAPAY)
| "bitpay" => Processors(BITPAY)
| "phonypay" => Processors(PHONYPAY)
| "fauxpay" => Processors(FAUXPAY)
| "pretendpay" => Processors(PRETENDPAY)
| "stripe_test" => Processors(STRIPE_TEST)
| "paypal_test" => Processors(PAYPAL_TEST)
| "cashtocode" => Processors(CASHTOCODE)
| "payme" => Processors(PAYME)
| "globepay" => Processors(GLOBEPAY)
| "powertranz" => Processors(POWERTRANZ)
| "tsys" => Processors(TSYS)
| "noon" => Processors(NOON)
| "stax" => Processors(STAX)
| "cryptopay" => Processors(CRYPTOPAY)
| "gocardless" => Processors(GOCARDLESS)
| "volt" => Processors(VOLT)
| "bankofamerica" => Processors(BANKOFAMERICA)
| "prophetpay" => Processors(PROPHETPAY)
| "helcim" => Processors(HELCIM)
| "placetopay" => Processors(PLACETOPAY)
| "billwerk" => Processors(BILLWERK)
| "mifinity" => Processors(MIFINITY)
| "zsl" => Processors(ZSL)
| "razorpay" => Processors(RAZORPAY)
| "bamboraapac" => Processors(BAMBORA_APAC)
| "itaubank" => Processors(ITAUBANK)
| "datatrans" => Processors(DATATRANS)
| "plaid" => Processors(PLAID)
| "square" => Processors(SQUARE)
| "paybox" => Processors(PAYBOX)
| "wellsfargo" => Processors(WELLSFARGO)
| "fiuu" => Processors(FIUU)
| "novalnet" => Processors(NOVALNET)
| "deutschebank" => Processors(DEUTSCHEBANK)
| "nexixpay" => Processors(NEXIXPAY)
| "jpmorgan" => Processors(JPMORGAN)
| "xendit" => Processors(XENDIT)
| "inespay" => Processors(INESPAY)
| "moneris" => Processors(MONERIS)
| "redsys" => Processors(REDSYS)
| "hipay" => Processors(HIPAY)
| "paystack" => Processors(PAYSTACK)
| _ => UnknownConnector("Not known")
}
| PayoutProcessor =>
switch connector {
| "adyen" => PayoutProcessor(ADYEN)
| "adyenplatform" => PayoutProcessor(ADYENPLATFORM)
| "cybersource" => PayoutProcessor(CYBERSOURCE)
| "ebanx" => PayoutProcessor(EBANX)
| "paypal" => PayoutProcessor(PAYPAL)
| "stripe" => PayoutProcessor(STRIPE)
| "wise" => PayoutProcessor(WISE)
| "nomupay" => PayoutProcessor(NOMUPAY)
| _ => UnknownConnector("Not known")
}
| ThreeDsAuthenticator =>
switch connector {
| "threedsecureio" => ThreeDsAuthenticator(THREEDSECUREIO)
| "netcetera" => ThreeDsAuthenticator(NETCETERA)
| "ctp_mastercard" => ThreeDsAuthenticator(CLICK_TO_PAY_MASTERCARD)
| "juspaythreedsserver" => ThreeDsAuthenticator(JUSPAYTHREEDSSERVER)
| "ctp_visa" => ThreeDsAuthenticator(CLICK_TO_PAY_VISA)
| _ => UnknownConnector("Not known")
}
| FRMPlayer =>
switch connector {
| "riskified" => FRM(Riskifyed)
| "signifyd" => FRM(Signifyd)
| _ => UnknownConnector("Not known")
}
| PMAuthenticationProcessor =>
switch connector {
| "plaid" => PMAuthenticationProcessor(PLAID)
| _ => UnknownConnector("Not known")
}
| TaxProcessor =>
switch connector {
| "taxjar" => TaxProcessor(TAXJAR)
| _ => UnknownConnector("Not known")
}
| BillingProcessor =>
switch connector {
| "chargebee" => BillingProcessor(CHARGEBEE)
| _ => UnknownConnector("Not known")
}
}
}
let getProcessorInfo = (connector: ConnectorTypes.processorTypes) => {
switch connector {
| STRIPE => stripeInfo
| ADYEN => adyenInfo
| GOCARDLESS => goCardLessInfo
| CHECKOUT => checkoutInfo
| BRAINTREE => braintreeInfo
| AUTHORIZEDOTNET => authorizedotnetInfo
| KLARNA => klarnaInfo
| GLOBALPAY => globalpayInfo
| BLUESNAP => bluesnapInfo
| AIRWALLEX => airwallexInfo
| WORLDPAY => worldpayInfo
| CYBERSOURCE => cybersourceInfo
| COINGATE => coingateInfo
| ELAVON => elavonInfo
| ACI => aciInfo
| WORLDLINE => worldlineInfo
| FISERV => fiservInfo
| FISERVIPG => fiservInfo
| SHIFT4 => shift4Info
| RAPYD => rapydInfo
| PAYU => payuInfo
| NUVEI => nuveiInfo
| DLOCAL => dlocalInfo
| MULTISAFEPAY => multisafepayInfo
| BAMBORA => bamboraInfo
| MOLLIE => mollieInfo
| TRUSTPAY => trustpayInfo
| ZEN => zenInfo
| PAYPAL => paypalInfo
| COINBASE => coinbaseInfo
| OPENNODE => openNodeInfo
| NEXINETS => nexinetsInfo
| FORTE => forteInfo
| NMI => nmiInfo
| IATAPAY => iataPayInfo
| BITPAY => bitPayInfo
| CRYPTOPAY => cryptopayInfo
| CASHTOCODE => cashToCodeInfo
| PHONYPAY => phonypayInfo
| FAUXPAY => fauxpayInfo
| PRETENDPAY => pretendpayInfo
| PAYME => paymeInfo
| GLOBEPAY => globepayInfo
| POWERTRANZ => powertranzInfo
| TSYS => tsysInfo
| NOON => noonInfo
| STRIPE_TEST => stripeTestInfo
| PAYPAL_TEST => paypalTestInfo
| STAX => staxInfo
| VOLT => voltInfo
| PROPHETPAY => prophetpayInfo
| BANKOFAMERICA => bankOfAmericaInfo
| HELCIM => helcimInfo
| PLACETOPAY => placetopayInfo
| BILLWERK => billwerkInfo
| MIFINITY => mifinityInfo
| ZSL => zslInfo
| RAZORPAY => razorpayInfo
| BAMBORA_APAC => bamboraApacInfo
| ITAUBANK => itauBankInfo
| DATATRANS => dataTransInfo
| PLAID => plaidInfo
| SQUARE => squareInfo
| PAYBOX => payboxInfo
| WELLSFARGO => wellsfargoInfo
| FIUU => fiuuInfo
| NOVALNET => novalnetInfo
| DEUTSCHEBANK => deutscheBankInfo
| NEXIXPAY => nexixpayInfo
| JPMORGAN => jpmorganInfo
| XENDIT => xenditInfo
| INESPAY => inespayInfo
| MONERIS => monerisInfo
| REDSYS => redsysInfo
| HIPAY => hipayInfo
| PAYSTACK => paystackInfo
}
}
let getPayoutProcessorInfo = (payoutconnector: ConnectorTypes.payoutProcessorTypes) => {
switch payoutconnector {
| ADYEN => adyenInfo
| ADYENPLATFORM => adyenPlatformInfo
| CYBERSOURCE => cybersourceInfo
| EBANX => ebanxInfo
| PAYPAL => paypalInfo
| STRIPE => stripeInfo
| WISE => wiseInfo
| NOMUPAY => nomupayInfo
}
}
let getThreedsAuthenticatorInfo = threeDsAuthenticator =>
switch threeDsAuthenticator {
| THREEDSECUREIO => threedsecuredotioInfo
| NETCETERA => netceteraInfo
| CLICK_TO_PAY_MASTERCARD => clickToPayInfo
| JUSPAYTHREEDSSERVER => juspayThreeDsServerInfo
| CLICK_TO_PAY_VISA => clickToPayVisaInfo
}
let getFrmInfo = frm =>
switch frm {
| Signifyd => signifydInfo
| Riskifyed => riskifyedInfo
}
let getOpenBankingProcessorInfo = (
pmAuthenticationConnector: ConnectorTypes.pmAuthenticationProcessorTypes,
) => {
switch pmAuthenticationConnector {
| PLAID => plaidInfo
}
}
let getTaxProcessorInfo = (taxProcessor: ConnectorTypes.taxProcessorTypes) => {
switch taxProcessor {
| TAXJAR => taxJarInfo
}
}
let getBillingProcessorInfo = (billingProcessor: ConnectorTypes.billingProcessorTypes) => {
switch billingProcessor {
| CHARGEBEE => chargebeeInfo
}
}
let getConnectorInfo = connector => {
switch connector {
| Processors(connector) => connector->getProcessorInfo
| PayoutProcessor(connector) => connector->getPayoutProcessorInfo
| ThreeDsAuthenticator(threeDsAuthenticator) => threeDsAuthenticator->getThreedsAuthenticatorInfo
| FRM(frm) => frm->getFrmInfo
| PMAuthenticationProcessor(pmAuthenticationConnector) =>
pmAuthenticationConnector->getOpenBankingProcessorInfo
| TaxProcessor(taxProcessor) => taxProcessor->getTaxProcessorInfo
| BillingProcessor(billingProcessor) => billingProcessor->getBillingProcessorInfo
| UnknownConnector(_) => unknownConnectorInfo
}
}
let acceptedValues = dict => {
open LogicUtils
let values = {
type_: dict->getString("type", "enable_only"),
list: dict->getStrArray("list"),
}
values.list->Array.length > 0 ? Some(values) : None
}
let itemProviderMapper = dict => {
open LogicUtils
{
payment_method_type: dict->getString("payment_method_type", ""),
accepted_countries: dict->getDictfromDict("accepted_countries")->acceptedValues,
accepted_currencies: dict->getDictfromDict("accepted_currencies")->acceptedValues,
minimum_amount: dict->getOptionInt("minimum_amount"),
maximum_amount: dict->getOptionInt("maximum_amount"),
recurring_enabled: dict->getOptionBool("recurring_enabled"),
installment_payment_enabled: dict->getOptionBool("installment_payment_enabled"),
payment_experience: dict->getOptionString("payment_experience"),
card_networks: dict->getStrArrayFromDict("card_networks", []),
}
}
let getPaymentMethodMapper: JSON.t => array<paymentMethodConfigType> = json => {
open LogicUtils
getArrayDataFromJson(json, itemProviderMapper)
}
let itemToObjMapper = dict => {
open LogicUtils
{
payment_method: dict->getString("payment_method", ""),
payment_method_type: dict->getString("payment_method_type", ""),
provider: dict->getArrayFromDict("provider", [])->JSON.Encode.array->getPaymentMethodMapper,
card_provider: dict
->getArrayFromDict("card_provider", [])
->JSON.Encode.array
->getPaymentMethodMapper,
}
}
let getPaymentMethodEnabled: JSON.t => array<paymentMethodEnabled> = json => {
open LogicUtils
getArrayDataFromJson(json, itemToObjMapper)
}
let connectorIgnoredField = [
"business_country",
"business_label",
"business_sub_label",
"merchant_connector_id",
"connector_name",
"profile_id",
"applepay_verified_domains",
"connector_account_details",
]
let configKeysToIgnore = [
"connector_auth",
"is_verifiable",
"metadata",
"connector_webhook_details",
"additional_merchant_data",
"connector_wallets_details",
]
let verifyConnectorIgnoreField = [
"business_country",
"business_label",
"business_sub_label",
"merchant_connector_id",
"applepay_verified_domains",
]
let ignoreFields = (json, id, fields) => {
if id->String.length <= 0 || id === "new" {
json
} else {
json
->LogicUtils.getDictFromJsonObject
->Dict.toArray
->Array.filter(entry => {
let (key, _val) = entry
!(fields->Array.includes(key))
})
->LogicUtils.getJsonFromArrayOfJson
}
}
let mapAuthType = (authType: string) => {
switch authType->String.toLowerCase {
| "bodykey" => #BodyKey
| "headerkey" => #HeaderKey
| "signaturekey" => #SignatureKey
| "multiauthkey" => #MultiAuthKey
| "currencyauthkey" => #CurrencyAuthKey
| "temporaryauth" => #TemporaryAuth
| _ => #Nokey
}
}
let getConnectorType = (connector: ConnectorTypes.connectorTypes) => {
switch connector {
| Processors(_) => "payment_processor"
| PayoutProcessor(_) => "payout_processor"
| ThreeDsAuthenticator(_) => "authentication_processor"
| PMAuthenticationProcessor(_) => "payment_method_auth"
| TaxProcessor(_) => "tax_processor"
| FRM(_) => "payment_vas"
| BillingProcessor(_) => "billing_processor"
| UnknownConnector(str) => str
}
}
let getSelectedPaymentObj = (paymentMethodsEnabled: array<paymentMethodEnabled>, paymentMethod) => {
paymentMethodsEnabled
->Array.find(item =>
item.payment_method_type->String.toLowerCase == paymentMethod->String.toLowerCase
)
->Option.getOr({
payment_method: "unknown",
payment_method_type: "unkonwn",
})
}
let addMethod = (paymentMethodsEnabled, paymentMethod, method) => {
let pmts = paymentMethodsEnabled->Array.copy
switch paymentMethod->getPaymentMethodFromString {
| Card =>
pmts->Array.forEach((val: paymentMethodEnabled) => {
if val.payment_method_type->String.toLowerCase === paymentMethod->String.toLowerCase {
val.card_provider
->Option.getOr([]->JSON.Encode.array->getPaymentMethodMapper)
->Array.push(method)
}
})
| _ =>
pmts->Array.forEach((val: paymentMethodEnabled) => {
if val.payment_method_type->String.toLowerCase === paymentMethod->String.toLowerCase {
val.provider
->Option.getOr([]->JSON.Encode.array->getPaymentMethodMapper)
->Array.push(method)
}
})
}
pmts
}
let removeMethod = (
paymentMethodsEnabled,
paymentMethod,
method: paymentMethodConfigType,
connector,
) => {
let pmts = paymentMethodsEnabled->Array.copy
switch (
method.payment_method_type->getPaymentMethodTypeFromString,
paymentMethod->getPaymentMethodFromString,
connector->getConnectorNameTypeFromString,
) {
| (PayPal, Wallet, Processors(PAYPAL)) =>
pmts->Array.forEach((val: paymentMethodEnabled) => {
if val.payment_method_type->String.toLowerCase === paymentMethod->String.toLowerCase {
let indexOfRemovalItem =
val.provider
->Option.getOr([]->JSON.Encode.array->getPaymentMethodMapper)
->Array.map(ele => ele.payment_experience)
->Array.indexOf(method.payment_experience)
val.provider
->Option.getOr([]->JSON.Encode.array->getPaymentMethodMapper)
->Array.splice(
~start=indexOfRemovalItem,
~remove=1,
~insert=[]->JSON.Encode.array->getPaymentMethodMapper,
)
}
})
| (_, Card, _) =>
pmts->Array.forEach((val: paymentMethodEnabled) => {
if val.payment_method_type->String.toLowerCase === paymentMethod->String.toLowerCase {
let indexOfRemovalItem =
val.card_provider
->Option.getOr([]->JSON.Encode.array->getPaymentMethodMapper)
->Array.map(ele => ele.payment_method_type)
->Array.indexOf(method.payment_method_type)
val.card_provider
->Option.getOr([]->JSON.Encode.array->getPaymentMethodMapper)
->Array.splice(
~start=indexOfRemovalItem,
~remove=1,
~insert=[]->JSON.Encode.array->getPaymentMethodMapper,
)
}
})
| _ =>
pmts->Array.forEach((val: paymentMethodEnabled) => {
if val.payment_method_type->String.toLowerCase === paymentMethod->String.toLowerCase {
let indexOfRemovalItem =
val.provider
->Option.getOr([]->JSON.Encode.array->getPaymentMethodMapper)
->Array.map(ele => ele.payment_method_type)
->Array.indexOf(method.payment_method_type)
val.provider
->Option.getOr([]->JSON.Encode.array->getPaymentMethodMapper)
->Array.splice(
~start=indexOfRemovalItem,
~remove=1,
~insert=[]->JSON.Encode.array->getPaymentMethodMapper,
)
}
})
}
pmts
}
let generateInitialValuesDict = (
~values,
~connector: string,
~bodyType,
~isLiveMode=false,
~connectorType: ConnectorTypes.connector=ConnectorTypes.Processor,
) => {
open LogicUtils
let dict = values->getDictFromJsonObject
let connectorAccountDetails =
dict->getJsonObjectFromDict("connector_account_details")->getDictFromJsonObject
connectorAccountDetails->Dict.set("auth_type", bodyType->JSON.Encode.string)
dict->Dict.set("connector_account_details", connectorAccountDetails->JSON.Encode.object)
dict->Dict.set("connector_name", connector->JSON.Encode.string)
dict->Dict.set(
"connector_type",
getConnectorType(connector->getConnectorNameTypeFromString(~connectorType))->JSON.Encode.string,
)
dict->Dict.set("disabled", dict->getBool("disabled", false)->JSON.Encode.bool)
dict->Dict.set("test_mode", (isLiveMode ? false : true)->JSON.Encode.bool)
dict->Dict.set("connector_label", dict->getString("connector_label", "")->JSON.Encode.string)
let connectorWebHookDetails =
dict->getJsonObjectFromDict("connector_webhook_details")->getDictFromJsonObject
dict->Dict.set(
"connector_webhook_details",
connectorWebHookDetails->getOptionString("merchant_secret")->Option.isSome
? connectorWebHookDetails->JSON.Encode.object
: JSON.Encode.null,
)
dict->JSON.Encode.object
}
let getDisableConnectorPayload = (connectorType, previousConnectorState) => {
[
("connector_type", connectorType->JSON.Encode.string),
("disabled", !previousConnectorState->JSON.Encode.bool),
]->Dict.fromArray
}
let getWebHookRequiredFields = (connector: connectorTypes, fieldName: string) => {
switch (connector, fieldName) {
| (Processors(ADYEN), "merchant_secret") => true
| (BillingProcessor(CHARGEBEE), "merchant_secret") => true
| (BillingProcessor(CHARGEBEE), "additional_secret") => true
| _ => false
}
}
let getAuthKeyMapFromConnectorAccountFields = connectorAccountFields => {
open LogicUtils
let authKeyMap =
connectorAccountFields
->getDictfromDict("auth_key_map")
->JSON.Encode.object
->Identity.jsonToAnyType
convertMapObjectToDict(authKeyMap)
}
let checkCashtoCodeFields = (keys, country, valuesFlattenJson) => {
open LogicUtils
keys->Array.map(field => {
let key = `connector_account_details.auth_key_map.${country}.${field}`
let value = valuesFlattenJson->getString(`${key}`, "")
value->String.length === 0 ? false : true
})
}
let checkCashtoCodeInnerField = (valuesFlattenJson, dict, country: string): bool => {
open LogicUtils
let value = dict->getDictfromDict(country)->Dict.keysToArray
let result = value->Array.map(method => {
let keys = dict->getDictfromDict(country)->getDictfromDict(method)->Dict.keysToArray
keys->checkCashtoCodeFields(country, valuesFlattenJson)->Array.includes(false) ? false : true
})
result->Array.includes(true)
}
let validateConnectorRequiredFields = (
connector: connectorTypes,
valuesFlattenJson,
connectorAccountFields,
connectorMetaDataFields,
connectorWebHookDetails,
connectorLabelDetailField,
errors,
) => {
open LogicUtils
let newDict = getDictFromJsonObject(errors)
switch connector {
| Processors(CASHTOCODE) => {
let dict = connectorAccountFields->getAuthKeyMapFromConnectorAccountFields
let indexLength = dict->Dict.keysToArray->Array.length
let vector = Js.Vector.make(indexLength, false)
dict
->Dict.keysToArray
->Array.forEachWithIndex((country, index) => {
let res = checkCashtoCodeInnerField(valuesFlattenJson, dict, country)
vector->Js.Vector.set(index, res)
})
Js.Vector.filterInPlace(val => val, vector)
if vector->Js.Vector.length === 0 {
Dict.set(newDict, "Currency", `Please enter currency`->JSON.Encode.string)
}
}
| _ =>
connectorAccountFields
->Dict.keysToArray
->Array.forEach(value => {
let key = `connector_account_details.${value}`
let errorKey = connectorAccountFields->getString(value, "")
let value = valuesFlattenJson->getString(`connector_account_details.${value}`, "")
if value->String.length === 0 {
Dict.set(newDict, key, `Please enter ${errorKey}`->JSON.Encode.string)
}
})
}
let keys =
connectorMetaDataFields
->Dict.keysToArray
->Array.filter(ele => !Array.includes(ConnectorMetaDataUtils.metaDataInputKeysToIgnore, ele))
{
keys->Array.forEach(field => {
let {\"type", name, required, label} =
connectorMetaDataFields
->getDictfromDict(field)
->JSON.Encode.object
->convertMapObjectToDict
->CommonConnectorUtils.inputFieldMapper
let key = `metadata.${name}`
let value = switch \"type" {
| Text | Select => valuesFlattenJson->getString(`${key}`, "")
| Toggle => valuesFlattenJson->getBool(`${key}`, false)->getStringFromBool
| _ => ""
}
let multiSelectValue = switch \"type" {
| MultiSelect => valuesFlattenJson->getArrayFromDict(key, [])
| _ => []
}
switch \"type" {
| Text | Select | Toggle =>
if value->isEmptyString && required {
Dict.set(newDict, key, `Please enter ${label}`->JSON.Encode.string)
}
| MultiSelect =>
if multiSelectValue->Array.length === 0 && required {
Dict.set(newDict, key, `Please enter ${label}`->JSON.Encode.string)
}
| _ => ()
}
})
}
connectorWebHookDetails
->Dict.keysToArray
->Array.forEach(fieldName => {
let key = `connector_webhook_details.${fieldName}`
let errorKey = connectorWebHookDetails->getString(fieldName, "")
let value = valuesFlattenJson->getString(key, "")
if value->String.length === 0 && connector->getWebHookRequiredFields(fieldName) {
Dict.set(newDict, key, `Please enter ${errorKey}`->JSON.Encode.string)
}
})
connectorLabelDetailField
->Dict.keysToArray
->Array.forEach(fieldName => {
let errorKey = connectorLabelDetailField->getString(fieldName, "")
let value = valuesFlattenJson->getString(fieldName, "")
if value->String.length === 0 {
Dict.set(newDict, fieldName, `Please enter ${errorKey}`->JSON.Encode.string)
}
})
newDict->JSON.Encode.object
}
let getPlaceHolder = label => {
`Enter ${label->LogicUtils.snakeToTitle}`
}
let connectorLabelDetailField = Dict.fromArray([
("connector_label", "Connector label"->JSON.Encode.string),
])
let getConnectorFields = connectorDetails => {
open LogicUtils
let connectorAccountDict =
connectorDetails->getDictFromJsonObject->getJsonObjectFromDict("connector_auth")
let bodyType = switch connectorAccountDict->JSON.Classify.classify {
| Object(dict) => dict->Dict.keysToArray->getValueFromArray(0, "")
| String(_) => "NoKey"
| _ => ""
}
let connectorAccountFields = switch bodyType {
| "NoKey" => Dict.make()
| _ => connectorAccountDict->getDictFromJsonObject->getDictfromDict(bodyType)
}
let connectorMetaDataFields = connectorDetails->getDictFromJsonObject->getDictfromDict("metadata")
let isVerifyConnector = connectorDetails->getDictFromJsonObject->getBool("is_verifiable", false)
let connectorWebHookDetails =
connectorDetails->getDictFromJsonObject->getDictfromDict("connector_webhook_details")
let connectorAdditionalMerchantData =
connectorDetails
->getDictFromJsonObject
->getDictfromDict("additional_merchant_data")
(
bodyType,
connectorAccountFields,
connectorMetaDataFields,
isVerifyConnector,
connectorWebHookDetails,
connectorLabelDetailField,
connectorAdditionalMerchantData,
)
}
let validateRequiredFiled = (valuesFlattenJson, dict, fieldName, errors) => {
open LogicUtils
let newDict = getDictFromJsonObject(errors)
dict
->Dict.keysToArray
->Array.forEach(_value => {
let lastItem = fieldName->String.split(".")->Array.pop->Option.getOr("")
let errorKey = dict->getString(lastItem, "")
let value = valuesFlattenJson->getString(`${fieldName}`, "")
if value->String.length === 0 {
Dict.set(newDict, fieldName, `Please enter ${errorKey}`->JSON.Encode.string)
}
})
newDict->JSON.Encode.object
}
let validate = (~selectedConnector, ~dict, ~fieldName, ~isLiveMode) => values => {
let errors = Dict.make()
let valuesFlattenJson = values->JsonFlattenUtils.flattenObject(true)
let labelArr = dict->Dict.valuesToArray
selectedConnector.validate
->Option.getOr([])
->Array.forEachWithIndex((field, index) => {
let key = field.name
let value =
valuesFlattenJson
->Dict.get(key)
->Option.getOr(""->JSON.Encode.string)
->LogicUtils.getStringFromJson("")
let regexToUse = isLiveMode ? field.liveValidationRegex : field.testValidationRegex
let validationResult = switch regexToUse {
| Some(regex) => regex->RegExp.fromString->RegExp.test(value)
| None => true
}
if field.isRequired->Option.getOr(true) && value->String.length === 0 {
let errorLabel =
labelArr
->Array.get(index)
->Option.getOr(""->JSON.Encode.string)
->LogicUtils.getStringFromJson("")
Dict.set(errors, key, `Please enter ${errorLabel}`->JSON.Encode.string)
} else if !validationResult && value->String.length !== 0 {
let expectedFormat = isLiveMode ? field.liveExpectedFormat : field.testExpectedFormat
let warningMessage = expectedFormat->Option.getOr("")
Dict.set(errors, key, warningMessage->JSON.Encode.string)
}
})
let profileId = valuesFlattenJson->LogicUtils.getString("profile_id", "")
if profileId->String.length === 0 {
Dict.set(errors, "Profile Id", `Please select your business profile`->JSON.Encode.string)
}
validateRequiredFiled(valuesFlattenJson, dict, fieldName, errors->JSON.Encode.object)
}
let getSuggestedAction = (~verifyErrorMessage, ~connector) => {
let (suggestedAction, suggestedActionExists) = {
open SuggestedActionHelper
let msg = verifyErrorMessage->Option.getOr("")
switch connector->getConnectorNameTypeFromString {
| Processors(STRIPE) => (
{
if msg->String.includes("Sending credit card numbers directly") {
<StripSendingCreditCard />
} else if msg->String.includes("Invalid API Key") {
<StripeInvalidAPIKey />
} else {
React.null
}
},
true,
)
| Processors(PAYPAL) => (
{
if msg->String.includes("Client Authentication failed") {
<PaypalClientAuthenticationFalied />
} else {
React.null
}
},
true,
)
| _ => (React.null, false)
}
}
(suggestedAction, suggestedActionExists)
}
let onSubmit = async (
~values,
~onSubmitVerify,
~onSubmitMain,
~setVerifyDone,
~verifyDone,
~isVerifyConnector,
) => {
setVerifyDone(_ => Loading)
if verifyDone === NoAttempt && isVerifyConnector {
onSubmitVerify(values)->ignore
} else {
onSubmitMain(values)->ignore
}
Nullable.null
}
let getWebhooksUrl = (~connectorName, ~merchantId) => {
`${Window.env.apiBaseUrl}/webhooks/${merchantId}/${connectorName}`
}
let itemToPMAuthMapper = dict => {
open LogicUtils
{
payment_method: dict->getString("payment_method", ""),
payment_method_type: dict->getString("payment_method_type", ""),
connector_name: dict->getString("connector_name", ""),
mca_id: dict->getString("mca_id", ""),
}
}
let constructConnectorRequestBody = (wasmRequest: wasmRequest, payload: JSON.t) => {
open LogicUtils
let dict = payload->getDictFromJsonObject
let connectorAccountDetails =
dict->getDictfromDict("connector_account_details")->JSON.Encode.object
let connectorAdditionalMerchantData = dict->getDictfromDict("additional_merchant_data")
let payLoadDetails: wasmExtraPayload = {
connector_account_details: connectorAccountDetails,
connector_webhook_details: dict->getDictfromDict("connector_webhook_details")->isEmptyDict
? None
: Some(dict->getDictfromDict("connector_webhook_details")->JSON.Encode.object),
connector_type: dict->getString("connector_type", ""),
connector_name: dict->getString("connector_name", ""),
profile_id: dict->getString("profile_id", ""),
disabled: dict->getBool("disabled", false),
test_mode: dict->getBool("test_mode", false),
}
let values = Window.getRequestPayload(wasmRequest, payLoadDetails)
let dict = Dict.fromArray([
("connector_account_details", connectorAccountDetails),
(
"additional_merchant_data",
connectorAdditionalMerchantData->isEmptyDict
? JSON.Encode.null
: connectorAdditionalMerchantData->JSON.Encode.object,
),
("connector_label", dict->getString("connector_label", "")->JSON.Encode.string),
("status", dict->getString("status", "active")->JSON.Encode.string),
(
"pm_auth_config",
dict->getDictfromDict("pm_auth_config")->isEmptyDict
? JSON.Encode.null
: dict->getDictfromDict("pm_auth_config")->JSON.Encode.object,
),
(
"connector_wallets_details",
dict->getDictfromDict("connector_wallets_details")->isEmptyDict
? JSON.Encode.null
: dict->getDictfromDict("connector_wallets_details")->JSON.Encode.object,
),
(
"metadata",
dict->getDictfromDict("metadata")->isEmptyDict
? Dict.make()->JSON.Encode.object
: dict->getDictfromDict("metadata")->JSON.Encode.object,
),
])
values
->getDictFromJsonObject
->Dict.toArray
->Array.concat(dict->Dict.toArray)
->Dict.fromArray
->JSON.Encode.object
}
let defaultSelectAllCards = (
pmts: array<paymentMethodEnabled>,
isUpdateFlow,
isPayoutFlow,
connector,
updateDetails,
) => {
open LogicUtils
if !isUpdateFlow {
let config =
(
isPayoutFlow
? Window.getPayoutConnectorConfig(connector)
: Window.getConnectorConfig(connector)
)->getDictFromJsonObject
pmts->Array.forEach(val => {
switch val.payment_method->getPaymentMethodFromString {
| Card => {
let arr =
config
->getArrayFromDict(val.payment_method_type, [])
->JSON.Encode.array
->getPaymentMethodMapper
let length =
val.card_provider
->Option.getOr([]->JSON.Encode.array->getPaymentMethodMapper)
->Array.length
val.card_provider
->Option.getOr([]->JSON.Encode.array->getPaymentMethodMapper)
->Array.splice(~start=0, ~remove=length, ~insert=arr)
}
| BankTransfer | BankRedirect => {
let arr =
config
->getArrayFromDict(val.payment_method_type, [])
->JSON.Encode.array
->getPaymentMethodMapper
let length =
val.provider->Option.getOr([]->JSON.Encode.array->getPaymentMethodMapper)->Array.length
val.provider
->Option.getOr([]->JSON.Encode.array->getPaymentMethodMapper)
->Array.splice(~start=0, ~remove=length, ~insert=arr)
}
| _ => ()
}
})
updateDetails(pmts)
}
}
let getConnectorPaymentMethodDetails = async (
~initialValues,
~setPaymentMethods,
~setMetaData,
~isUpdateFlow,
~isPayoutFlow,
~connector,
~updateDetails,
) => {
open LogicUtils
try {
let json = Window.getResponsePayload(initialValues)
let metaData = initialValues->getDictFromJsonObject->getJsonObjectFromDict("metadata")
let paymentMethodEnabled =
json
->getDictFromJsonObject
->getJsonObjectFromDict("payment_methods_enabled")
->getPaymentMethodEnabled
setPaymentMethods(_ => paymentMethodEnabled)
setMetaData(_ => metaData)
defaultSelectAllCards(
paymentMethodEnabled,
isUpdateFlow,
isPayoutFlow,
connector,
updateDetails,
)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong")
Exn.raiseError(err)
}
}
}
let getDisplayNameForProcessor = (connector: ConnectorTypes.processorTypes) =>
switch connector {
| ADYEN => "Adyen"
| CHECKOUT => "Checkout"
| BRAINTREE => "Braintree"
| BILLWERK => "Billwerk"
| AUTHORIZEDOTNET => "Authorize.net"
| STRIPE => "Stripe"
| KLARNA => "Klarna"
| GLOBALPAY => "Global Payments"
| BLUESNAP => "Bluesnap"
| AIRWALLEX => "Airwallex"
| WORLDPAY => "Worldpay"
| CYBERSOURCE => "Cybersource"
| COINGATE => "CoinGate"
| ELAVON => "Elavon"
| ACI => "ACI Worldwide"
| WORLDLINE => "Worldline"
| FISERV => "Fiserv Commerce Hub"
| SHIFT4 => "Shift4"
| RAPYD => "Rapyd"
| PAYU => "PayU"
| NUVEI => "Nuvei"
| MULTISAFEPAY => "MultiSafepay"
| DLOCAL => "dLocal"
| BAMBORA => "Bambora"
| MOLLIE => "Mollie"
| TRUSTPAY => "TrustPay"
| ZEN => "Zen"
| PAYPAL => "PayPal"
| COINBASE => "Coinbase"
| OPENNODE => "Opennode"
| NMI => "NMI"
| FORTE => "Forte"
| NEXINETS => "Nexinets"
| IATAPAY => "IATA Pay"
| BITPAY => "Bitpay"
| PHONYPAY => "Phony Pay"
| FAUXPAY => "Fauxpay"
| PRETENDPAY => "Pretendpay"
| CRYPTOPAY => "Cryptopay"
| CASHTOCODE => "CashtoCode"
| PAYME => "PayMe"
| GLOBEPAY => "GlobePay"
| POWERTRANZ => "Powertranz"
| TSYS => "TSYS"
| NOON => "Noon"
| STRIPE_TEST => "Stripe Dummy"
| PAYPAL_TEST => "Paypal Dummy"
| STAX => "Stax"
| GOCARDLESS => "GoCardless"
| VOLT => "Volt"
| PROPHETPAY => "Prophet Pay"
| BANKOFAMERICA => "Bank of America"
| HELCIM => "Helcim"
| PLACETOPAY => "Placetopay"
| MIFINITY => "MiFinity"
| ZSL => "ZSL"
| RAZORPAY => "Razorpay"
| BAMBORA_APAC => "Bambora Apac"
| ITAUBANK => "Itaubank"
| DATATRANS => "Datatrans"
| PLAID => "Plaid"
| SQUARE => "Square"
| PAYBOX => "Paybox"
| WELLSFARGO => "Wells Fargo"
| FISERVIPG => "Fiserv IPG"
| FIUU => "Fiuu"
| NOVALNET => "Novalnet"
| DEUTSCHEBANK => "Deutsche Bank"
| NEXIXPAY => "Nexixpay"
| JPMORGAN => "JP Morgan"
| XENDIT => "Xendit"
| INESPAY => "Inespay"
| MONERIS => "Moneris"
| REDSYS => "Redsys"
| HIPAY => "HiPay"
| PAYSTACK => "Paystack"
}
let getDisplayNameForPayoutProcessor = (payoutProcessor: ConnectorTypes.payoutProcessorTypes) =>
switch payoutProcessor {
| ADYEN => "Adyen"
| ADYENPLATFORM => "Adyen Platform"
| CYBERSOURCE => "Cybersource"
| EBANX => "Ebanx"
| PAYPAL => "PayPal"
| STRIPE => "Stripe"
| WISE => "Wise"
| NOMUPAY => "Nomupay"
}
let getDisplayNameForThreedsAuthenticator = threeDsAuthenticator =>
switch threeDsAuthenticator {
| THREEDSECUREIO => "3dsecure.io"
| NETCETERA => "Netcetera"
| CLICK_TO_PAY_MASTERCARD => "Mastercard Unified Click to Pay"
| JUSPAYTHREEDSSERVER => "Juspay 3DS Server"
| CLICK_TO_PAY_VISA => "Visa Unified Click to Pay"
}
let getDisplayNameForFRMConnector = frmConnector =>
switch frmConnector {
| Signifyd => "Signifyd"
| Riskifyed => "Riskified"
}
let getDisplayNameForOpenBankingProcessor = pmAuthenticationConnector => {
switch pmAuthenticationConnector {
| PLAID => "Plaid"
}
}
let getDisplayNameForTaxProcessor = taxProcessor => {
switch taxProcessor {
| TAXJAR => "Tax Jar"
}
}
let getDisplayNameForBillingProcessor = billingProcessor => {
switch billingProcessor {
| CHARGEBEE => "Chargebee"
}
}
let getDisplayNameForConnector = (~connectorType=ConnectorTypes.Processor, connector) => {
let connectorType = connector->String.toLowerCase->getConnectorNameTypeFromString(~connectorType)
switch connectorType {
| Processors(connector) => connector->getDisplayNameForProcessor
| PayoutProcessor(payoutProcessor) => payoutProcessor->getDisplayNameForPayoutProcessor
| ThreeDsAuthenticator(threeDsAuthenticator) =>
threeDsAuthenticator->getDisplayNameForThreedsAuthenticator
| FRM(frmConnector) => frmConnector->getDisplayNameForFRMConnector
| PMAuthenticationProcessor(pmAuthenticationConnector) =>
pmAuthenticationConnector->getDisplayNameForOpenBankingProcessor
| TaxProcessor(taxProcessor) => taxProcessor->getDisplayNameForTaxProcessor
| BillingProcessor(billingProcessor) => billingProcessor->getDisplayNameForBillingProcessor
| UnknownConnector(str) => str
}
}
// Need to remove connector and merge connector and connectorTypeVariants
let connectorTypeTuple = connectorType => {
switch connectorType {
| "payment_processor" => (PaymentProcessor, Processor)
| "payment_vas" => (PaymentVas, FRMPlayer)
| "payout_processor" => (PayoutProcessor, PayoutProcessor)
| "authentication_processor" => (AuthenticationProcessor, ThreeDsAuthenticator)
| "payment_method_auth" => (PMAuthProcessor, PMAuthenticationProcessor)
| "tax_processor" => (TaxProcessor, TaxProcessor)
| "billing_processor" => (BillingProcessor, BillingProcessor)
| _ => (PaymentProcessor, Processor)
}
}
let connectorTypeStringToTypeMapper = connector_type => {
switch connector_type {
| "payment_vas" => PaymentVas
| "payout_processor" => PayoutProcessor
| "authentication_processor" => AuthenticationProcessor
| "payment_method_auth" => PMAuthProcessor
| "tax_processor" => TaxProcessor
| "billing_processor" => BillingProcessor
| "payment_processor"
| _ =>
PaymentProcessor
}
}
let connectorTypeTypedValueToStringMapper = val => {
switch val {
| PaymentVas => "payment_vas"
| PayoutProcessor => "payout_processor"
| AuthenticationProcessor => "authentication_processor"
| PMAuthProcessor => "payment_method_auth"
| TaxProcessor => "tax_processor"
| PaymentProcessor => "payment_processor"
| BillingProcessor => "billing_processor"
}
}
let sortByName = (c1, c2) => {
open LogicUtils
compareLogic(c2->getConnectorNameString, c1->getConnectorNameString)
}
let existsInArray = (element, connectorList) => {
open ConnectorTypes
connectorList->Array.some(e =>
switch (e, element) {
| (Processors(p1), Processors(p2)) => p1 == p2
| (_, _) => false
}
)
}
// Need to refactor
let updateMetaData = (~metaData) => {
open LogicUtils
let apple_pay_combined = metaData->getDictFromJsonObject->getDictfromDict("apple_pay_combined")
let manual = apple_pay_combined->getDictfromDict("manual")
switch manual->Dict.keysToArray->Array.length > 0 {
| true => {
let applepay =
manual
->getDictfromDict("session_token_data")
->JSON.Encode.object
->Identity.jsonToAnyType
->convertMapObjectToDict
manual->Dict.set("session_token_data", applepay->JSON.Encode.object)
}
| false => ()
}
}
let sortByDisableField = (arr: array<'a>, getDisabledStatus: 'a => bool) => {
arr->Array.sort((a, b) =>
LogicUtils.numericArraySortComperator(
getDisabledStatus(a) ? 1.0 : 0.0,
getDisabledStatus(b) ? 1.0 : 0.0,
)
)
}
let connectorTypeFromConnectorName: string => connector = connectorName =>
switch connectorName {
| "juspaythreedsserver" => ThreeDsAuthenticator
| _ => Processor
}
| 17,197 | 9,643 |
hyperswitch-control-center | src/screens/Connectors/ThreeDsProcessors/ThreeDsProcessorTypes.res | .res | type steps = ConfigurationFields | Summary | Preview
| 10 | 9,644 |
hyperswitch-control-center | src/screens/Connectors/ThreeDsProcessors/ThreeDsProcessorHome.res | .res | @react.component
let make = () => {
open ThreeDsProcessorTypes
open ConnectorUtils
open APIUtils
open LogicUtils
let getURL = useGetURL()
let showToast = ToastState.useShowToast()
let url = RescriptReactRouter.useUrl()
let updateAPIHook = useUpdateMethod(~showErrorToast=false)
let fetchDetails = useGetMethod()
let connectorName = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("name", "")
let connectorID = HSwitchUtils.getConnectorIDFromUrl(url.path->List.toArray, "")
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (initialValues, setInitialValues) = React.useState(_ => Dict.make()->JSON.Encode.object)
let (currentStep, setCurrentStep) = React.useState(_ => ConfigurationFields)
let fetchConnectorListResponse = ConnectorListHook.useFetchConnectorList()
let activeBusinessProfile =
Recoil.useRecoilValueFromAtom(
HyperswitchAtom.businessProfilesAtom,
)->MerchantAccountUtils.getValueFromBusinessProfile
let isUpdateFlow = switch url.path->HSwitchUtils.urlPath {
| list{"3ds-authenticators", "new"} => false
| _ => true
}
let getConnectorDetails = async () => {
try {
let connectorUrl = getURL(~entityName=V1(CONNECTOR), ~methodType=Get, ~id=Some(connectorID))
let json = await fetchDetails(connectorUrl)
setInitialValues(_ => json)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to update!")
Exn.raiseError(err)
}
| _ => Exn.raiseError("Something went wrong")
}
}
let getDetails = async () => {
try {
setScreenState(_ => Loading)
let _ = await Window.connectorWasmInit()
if isUpdateFlow {
await getConnectorDetails()
setCurrentStep(_ => Preview)
} else {
setCurrentStep(_ => ConfigurationFields)
}
setScreenState(_ => Success)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong")
setScreenState(_ => Error(err))
}
| _ => setScreenState(_ => Error("Something went wrong"))
}
}
let connectorDetails = React.useMemo(() => {
try {
if connectorName->LogicUtils.isNonEmptyString {
let dict = Window.getAuthenticationConnectorConfig(connectorName)
dict
} else {
Dict.make()->JSON.Encode.object
}
} catch {
| Exn.Error(e) => {
Js.log2("FAILED TO LOAD CONNECTOR CONFIG", e)
let err = Exn.message(e)->Option.getOr("Something went wrong")
setScreenState(_ => PageLoaderWrapper.Error(err))
Dict.make()->JSON.Encode.object
}
}
}, [connectorName])
let (
bodyType,
connectorAccountFields,
connectorMetaDataFields,
_,
connectorWebHookDetails,
connectorLabelDetailField,
connectorAdditionalMerchantData,
) = getConnectorFields(connectorDetails)
React.useEffect(() => {
let initialValuesToDict = initialValues->LogicUtils.getDictFromJsonObject
if !isUpdateFlow {
initialValuesToDict->Dict.set(
"profile_id",
activeBusinessProfile.profile_id->JSON.Encode.string,
)
initialValuesToDict->Dict.set(
"connector_label",
`${connectorName}_${activeBusinessProfile.profile_name}`->JSON.Encode.string,
)
}
None
}, [connectorName, activeBusinessProfile.profile_id])
React.useEffect(() => {
if connectorName->LogicUtils.isNonEmptyString {
getDetails()->ignore
}
None
}, [connectorName])
let onSubmit = async (values, _) => {
try {
let body =
generateInitialValuesDict(
~values,
~connector=connectorName,
~bodyType,
~isLiveMode={false},
~connectorType=ConnectorTypes.ThreeDsAuthenticator,
)->ignoreFields(connectorID, connectorIgnoredField)
let connectorUrl = getURL(
~entityName=V1(CONNECTOR),
~methodType=Post,
~id=isUpdateFlow ? Some(connectorID) : None,
)
let response = await updateAPIHook(connectorUrl, body, Post)
let _ = await fetchConnectorListResponse()
setInitialValues(_ => response)
setCurrentStep(_ => Summary)
} 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)
setCurrentStep(_ => ConfigurationFields)
} else {
showToast(~message=errorMessage, ~toastType=ToastError)
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
}
Nullable.null
}
let validateMandatoryField = values => {
let errors = Dict.make()
let valuesFlattenJson = values->JsonFlattenUtils.flattenObject(true)
validateConnectorRequiredFields(
connectorName->getConnectorNameTypeFromString(~connectorType=ThreeDsAuthenticator),
valuesFlattenJson,
connectorAccountFields,
connectorMetaDataFields,
connectorWebHookDetails,
connectorLabelDetailField,
errors->JSON.Encode.object,
)
}
let summaryPageButton = switch currentStep {
| Preview => React.null
| _ =>
<Button
text="Done"
buttonType=Primary
onClick={_ =>
RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/3ds-authenticators"))}
/>
}
<PageLoaderWrapper screenState>
<div className="flex flex-col gap-10 overflow-scroll h-full w-full">
<BreadCrumbNavigation
path=[
connectorID === "new"
? {
title: "3DS Authenticator",
link: "/3ds-authenticators",
warning: `You have not yet completed configuring your ${connectorName->LogicUtils.snakeToTitle} connector. Are you sure you want to go back?`,
}
: {
title: "3DS Authenticator",
link: "/3ds-authenticators",
},
]
currentPageTitle={connectorName->getDisplayNameForConnector(
~connectorType=ThreeDsAuthenticator,
)}
cursorStyle="cursor-pointer"
/>
<div
className="bg-white rounded-lg border h-3/4 overflow-scroll shadow-boxShadowMultiple show-scrollbar">
{switch currentStep {
| ConfigurationFields =>
<Form initialValues={initialValues} onSubmit validate={validateMandatoryField}>
<ConnectorAccountDetailsHelper.ConnectorHeaderWrapper
connector=connectorName
connectorType=ThreeDsAuthenticator
headerButton={<AddDataAttributes
attributes=[("data-testid", "connector-submit-button")]>
<FormRenderer.SubmitButton loadingText="Processing..." text="Connect and Proceed" />
</AddDataAttributes>}>
<div className="flex flex-col gap-2 p-2 md:px-10">
<ConnectorAccountDetailsHelper.BusinessProfileRender
isUpdateFlow selectedConnector={connectorName}
/>
</div>
<div className={`flex flex-col gap-2 p-2 md:p-10`}>
<ConnectorAccountDetailsHelper.ConnectorConfigurationFields
connector={connectorName->getConnectorNameTypeFromString(
~connectorType=ThreeDsAuthenticator,
)}
connectorAccountFields
selectedConnector={connectorName
->getConnectorNameTypeFromString(~connectorType=ThreeDsAuthenticator)
->getConnectorInfo}
connectorMetaDataFields
connectorWebHookDetails
connectorLabelDetailField
connectorAdditionalMerchantData
/>
</div>
</ConnectorAccountDetailsHelper.ConnectorHeaderWrapper>
<FormValuesSpy />
</Form>
| Summary | Preview =>
<ConnectorAccountDetailsHelper.ConnectorHeaderWrapper
connector=connectorName
connectorType=ThreeDsAuthenticator
headerButton={summaryPageButton}>
<ConnectorPreview.ConnectorSummaryGrid
connectorInfo={ConnectorInterface.mapDictToConnectorPayload(
ConnectorInterface.connectorInterfaceV1,
initialValues->LogicUtils.getDictFromJsonObject,
)}
connector=connectorName
setCurrentStep={_ => ()}
getConnectorDetails={Some(getConnectorDetails)}
/>
</ConnectorAccountDetailsHelper.ConnectorHeaderWrapper>
}}
</div>
</div>
</PageLoaderWrapper>
}
| 1,914 | 9,645 |
hyperswitch-control-center | src/screens/Connectors/ThreeDsProcessors/ThreeDsTableEntity.res | .res | open ConnectorTypes
type colType =
| Name
| TestMode
| Status
| Disabled
| MerchantConnectorId
| ConnectorLabel
let defaultColumns = [Name, MerchantConnectorId, ConnectorLabel, Status, Disabled, TestMode]
let getHeading = colType => {
switch colType {
| Name => Table.makeHeaderInfo(~key="connector_name", ~title="Processor")
| TestMode => Table.makeHeaderInfo(~key="test_mode", ~title="Test Mode")
| Status => Table.makeHeaderInfo(~key="status", ~title="Integration status")
| Disabled => Table.makeHeaderInfo(~key="disabled", ~title="Disabled")
| ConnectorLabel => Table.makeHeaderInfo(~key="connector_label", ~title="Connector Label")
| MerchantConnectorId =>
Table.makeHeaderInfo(~key="merchant_connector_id", ~title="Merchant Connector Id")
}
}
let connectorStatusStyle = connectorStatus =>
switch connectorStatus->String.toLowerCase {
| "active" => "text-green-700"
| _ => "text-grey-800 opacity-50"
}
let getCell = (connector: connectorPayload, colType): Table.cell => {
switch colType {
| Name =>
CustomCell(
<HelperComponents.ConnectorCustomCell
connectorName=connector.connector_name connectorType={ThreeDsAuthenticator}
/>,
"",
)
| TestMode => Text(connector.test_mode ? "True" : "False")
| 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>,
"",
)
| ConnectorLabel => Text(connector.connector_label)
| MerchantConnectorId => DisplayCopyCell(connector.merchant_connector_id)
}
}
let comparatorFunction = (connector1: connectorPayload, connector2: connectorPayload) => {
connector1.connector_name->String.localeCompare(connector2.connector_name)
}
let sortPreviouslyConnectedList = arr => {
Array.toSorted(arr, comparatorFunction)
}
let getPreviouslyConnectedList: JSON.t => array<connectorPayload> = json => {
let data = ConnectorInterface.mapJsonArrayToConnectorPayloads(
ConnectorInterface.connectorInterfaceV1,
json,
AuthenticationProcessor,
)
data
}
let threeDsAuthenticatorEntity = (path: string, ~authorization: CommonAuthTypes.authorization) => {
EntityType.makeEntity(
~uri=``,
~getObjects=getPreviouslyConnectedList,
~defaultColumns,
~getHeading,
~getCell,
~dataKey="",
~getShowLink={
connec =>
GroupAccessUtils.linkForGetShowLinkViaAccess(
~url=GlobalVars.appendDashboardPath(
~url=`/${path}/${connec.merchant_connector_id}?name=${connec.connector_name}`,
),
~authorization,
)
},
)
}
| 665 | 9,646 |
hyperswitch-control-center | src/screens/Connectors/ThreeDsProcessors/ThreeDsConnectorList.res | .res | @react.component
let make = () => {
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Success)
let (configuredConnectors, setConfiguredConnectors) = React.useState(_ => [])
let (offset, setOffset) = React.useState(_ => 0)
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
let (searchText, setSearchText) = React.useState(_ => "")
let (filteredConnectorData, setFilteredConnectorData) = React.useState(_ => [])
let connectorList = ConnectorInterface.useConnectorArrayMapper(
~interface=ConnectorInterface.connectorInterfaceV1,
~retainInList=AuthenticationProcessor,
)
let filterLogic = ReactDebounce.useDebounced(ob => {
open LogicUtils
let (searchText, arr) = ob
let filteredList = if searchText->isNonEmptyString {
arr->Array.filter((obj: Nullable.t<ConnectorTypes.connectorPayload>) => {
switch Nullable.toOption(obj) {
| Some(obj) =>
isContainingStringLowercase(obj.connector_name, searchText) ||
isContainingStringLowercase(obj.merchant_connector_id, searchText) ||
isContainingStringLowercase(obj.connector_label, searchText)
| None => false
}
})
} else {
arr
}
setFilteredConnectorData(_ => filteredList)
}, ~wait=200)
let getConnectorList = async _ => {
try {
let threeDsConnectorsList =
connectorList->Array.filter(item => item.connector_type === AuthenticationProcessor)
ConnectorUtils.sortByDisableField(threeDsConnectorsList, connectorPayload =>
connectorPayload.disabled
)
setConfiguredConnectors(_ => threeDsConnectorsList)
setFilteredConnectorData(_ => threeDsConnectorsList->Array.map(Nullable.make))
setScreenState(_ => Success)
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Error("Failed to fetch"))
}
}
React.useEffect(() => {
getConnectorList()->ignore
None
}, [])
<div>
<PageUtils.PageHeading
title={"3DS Authentication Manager"}
subTitle={"Connect and manage 3DS authentication providers to enhance the conversions"}
/>
<PageLoaderWrapper screenState>
<div className="flex flex-col gap-10">
<RenderIf condition={configuredConnectors->Array.length > 0}>
<LoadedTable
title="Connected Processors"
actualData={filteredConnectorData}
totalResults={filteredConnectorData->Array.length}
resultsPerPage=20
entity={ThreeDsTableEntity.threeDsAuthenticatorEntity(
`3ds-authenticators`,
~authorization=userHasAccess(~groupAccess=ConnectorsManage),
)}
filters={<TableSearchFilter
data={configuredConnectors->Array.map(Nullable.make)}
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}
/>}
offset
setOffset
currrentFetchCount={configuredConnectors->Array.map(Nullable.make)->Array.length}
collapseTableRow=false
/>
</RenderIf>
<ProcessorCards
configuredConnectors={ConnectorInterface.mapConnectorPayloadToConnectorType(
ConnectorInterface.connectorInterfaceV1,
ConnectorTypes.ThreeDsAuthenticator,
configuredConnectors,
)}
connectorsAvailableForIntegration={featureFlagDetails.isLiveMode
? ConnectorUtils.threedsAuthenticatorListForLive
: ConnectorUtils.threedsAuthenticatorList}
urlPrefix="3ds-authenticators/new"
connectorType=ConnectorTypes.ThreeDsAuthenticator
/>
</div>
</PageLoaderWrapper>
</div>
}
| 857 | 9,647 |
hyperswitch-control-center | src/screens/Connectors/TaxProcessor/TaxProcessorList.res | .res | @react.component
let make = () => {
let connectorList = ConnectorInterface.useConnectorArrayMapper(
~interface=ConnectorInterface.connectorInterfaceV1,
~retainInList=TaxProcessor,
)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Success)
let (configuredConnectors, setConfiguredConnectors) = React.useState(_ => [])
let (offset, setOffset) = React.useState(_ => 0)
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
let (searchText, setSearchText) = React.useState(_ => "")
let (filteredConnectorData, setFilteredConnectorData) = React.useState(_ => [])
let filterLogic = ReactDebounce.useDebounced(ob => {
open LogicUtils
let (searchText, arr) = ob
let filteredList = if searchText->isNonEmptyString {
arr->Array.filter((obj: Nullable.t<ConnectorTypes.connectorPayload>) => {
switch Nullable.toOption(obj) {
| Some(obj) =>
isContainingStringLowercase(obj.connector_name, searchText) ||
isContainingStringLowercase(obj.merchant_connector_id, searchText) ||
isContainingStringLowercase(obj.connector_label, searchText)
| None => false
}
})
} else {
arr
}
setFilteredConnectorData(_ => filteredList)
}, ~wait=200)
let getConnectorList = async _ => {
try {
ConnectorUtils.sortByDisableField(connectorList, connectorPayload =>
connectorPayload.disabled
)
setConfiguredConnectors(_ => connectorList)
setFilteredConnectorData(_ => connectorList->Array.map(Nullable.make))
setScreenState(_ => Success)
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Error("Failed to fetch"))
}
}
React.useEffect(() => {
getConnectorList()->ignore
None
}, [])
<div>
<PageUtils.PageHeading
title={"Tax Processor"} subTitle={"Connect and configure Tax Processor"}
/>
<PageLoaderWrapper screenState>
<div className="flex flex-col gap-10">
<RenderIf condition={configuredConnectors->Array.length > 0}>
<LoadedTable
title="Connected Processors"
actualData={filteredConnectorData}
totalResults={filteredConnectorData->Array.length}
resultsPerPage=20
entity={TaxProcessorTableEntity.taxProcessorEntity(
`tax-processor`,
~authorization=userHasAccess(~groupAccess=ConnectorsManage),
)}
filters={<TableSearchFilter
data={configuredConnectors->Array.map(Nullable.make)}
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
/>}
offset
setOffset
currrentFetchCount={configuredConnectors->Array.map(Nullable.make)->Array.length}
collapseTableRow=false
/>
</RenderIf>
<ProcessorCards
configuredConnectors={ConnectorInterface.mapConnectorPayloadToConnectorType(
ConnectorInterface.connectorInterfaceV1,
ConnectorTypes.TaxProcessor,
configuredConnectors,
)}
connectorsAvailableForIntegration=ConnectorUtils.taxProcessorList
urlPrefix="tax-processor/new"
connectorType=ConnectorTypes.TaxProcessor
/>
</div>
</PageLoaderWrapper>
</div>
}
| 754 | 9,648 |
hyperswitch-control-center | src/screens/Connectors/TaxProcessor/TaxProcessorTableEntity.res | .res | open ConnectorTypes
type colType =
| Name
| TestMode
| Status
| Disabled
| MerchantConnectorId
| ConnectorLabel
let defaultColumns = [Name, MerchantConnectorId, ConnectorLabel, Status, Disabled, TestMode]
let getHeading = colType => {
switch colType {
| Name => Table.makeHeaderInfo(~key="connector_name", ~title="Processor")
| TestMode => Table.makeHeaderInfo(~key="test_mode", ~title="Test Mode")
| Status => Table.makeHeaderInfo(~key="status", ~title="Integration status")
| Disabled => Table.makeHeaderInfo(~key="disabled", ~title="Disabled")
| ConnectorLabel => Table.makeHeaderInfo(~key="connector_label", ~title="Connector Label")
| MerchantConnectorId =>
Table.makeHeaderInfo(~key="merchant_connector_id", ~title="Merchant Connector Id")
}
}
let connectorStatusStyle = connectorStatus =>
switch connectorStatus->String.toLowerCase {
| "active" => "text-green-700"
| _ => "text-grey-800 opacity-50"
}
let getCell = (connector: connectorPayload, colType): Table.cell => {
switch colType {
| Name =>
CustomCell(
<HelperComponents.ConnectorCustomCell
connectorName=connector.connector_name connectorType={TaxProcessor}
/>,
"",
)
| TestMode => Text(connector.test_mode ? "True" : "False")
| 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>,
"",
)
| ConnectorLabel => Text(connector.connector_label)
| MerchantConnectorId =>
CustomCell(
<HelperComponents.CopyTextCustomComp
customTextCss="w-36 truncate whitespace-nowrap"
displayValue=Some(connector.merchant_connector_id)
/>,
"",
)
}
}
let comparatorFunction = (connector1: connectorPayload, connector2: connectorPayload) => {
connector1.connector_name->String.localeCompare(connector2.connector_name)
}
let sortPreviouslyConnectedList = arr => {
Array.toSorted(arr, comparatorFunction)
}
let getPreviouslyConnectedList: JSON.t => array<connectorPayload> = json => {
let data = ConnectorInterface.mapJsonArrayToConnectorPayloads(
ConnectorInterface.connectorInterfaceV1,
json,
TaxProcessor,
)
data
}
let taxProcessorEntity = (path: string, ~authorization: CommonAuthTypes.authorization) => {
EntityType.makeEntity(
~uri=``,
~getObjects=getPreviouslyConnectedList,
~defaultColumns,
~getHeading,
~getCell,
~dataKey="",
~getShowLink={
connec =>
GroupAccessUtils.linkForGetShowLinkViaAccess(
~url=GlobalVars.appendDashboardPath(
~url=`/${path}/${connec.merchant_connector_id}?name=${connec.connector_name}`,
),
~authorization,
)
},
)
}
| 696 | 9,649 |
hyperswitch-control-center | src/screens/Connectors/TaxProcessor/TaxProcessorHome.res | .res | module MenuOption = {
open HeadlessUI
@react.component
let make = (~disableConnector, ~isConnectorDisabled) => {
let showPopUp = PopUpState.useShowPopUp()
let openConfirmationPopUp = _ => {
showPopUp({
popUpType: (Warning, WithIcon),
heading: "Confirm Action?",
description: `You are about to ${isConnectorDisabled
? "Enable"
: "Disable"->String.toLowerCase} this connector. This might impact your desired routing configurations. Please confirm to proceed.`->React.string,
handleConfirm: {
text: "Confirm",
onClick: _ => disableConnector(isConnectorDisabled)->ignore,
},
handleCancel: {text: "Cancel"},
})
}
let connectorStatusAvailableToSwitch = isConnectorDisabled ? "Enable" : "Disable"
<Popover \"as"="div" className="relative inline-block text-left">
{_ => <>
<Popover.Button> {_ => <Icon name="menu-option" size=28 />} </Popover.Button>
<Popover.Panel className="absolute z-20 right-5 top-4">
{panelProps => {
<div
id="neglectTopbarTheme"
className="relative flex flex-col bg-white py-1 overflow-hidden rounded ring-1 ring-black ring-opacity-5 w-40">
{<Navbar.MenuOption
text={connectorStatusAvailableToSwitch}
onClick={_ => {
panelProps["close"]()
openConfirmationPopUp()
}}
/>}
</div>
}}
</Popover.Panel>
</>}
</Popover>
}
}
@react.component
let make = () => {
open TaxProcessorTypes
open ConnectorUtils
open APIUtils
open LogicUtils
let getURL = useGetURL()
let showToast = ToastState.useShowToast()
let url = RescriptReactRouter.useUrl()
let updateAPIHook = useUpdateMethod(~showErrorToast=false)
let fetchDetails = useGetMethod()
let updateDetails = useUpdateMethod()
let connectorName = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("name", "")
let connectorID = HSwitchUtils.getConnectorIDFromUrl(url.path->List.toArray, "")
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (initialValues, setInitialValues) = React.useState(_ => Dict.make()->JSON.Encode.object)
let (currentStep, setCurrentStep) = React.useState(_ => ConfigurationFields)
let fetchConnectorListResponse = ConnectorListHook.useFetchConnectorList()
let activeBusinessProfile =
Recoil.useRecoilValueFromAtom(
HyperswitchAtom.businessProfilesAtom,
)->MerchantAccountUtils.getValueFromBusinessProfile
let isUpdateFlow = switch url.path->HSwitchUtils.urlPath {
| list{"tax-processor", "new"} => false
| _ => true
}
let connectorInfo = ConnectorInterface.mapDictToConnectorPayload(
ConnectorInterface.connectorInterfaceV1,
initialValues->LogicUtils.getDictFromJsonObject,
)
let isConnectorDisabled = connectorInfo.disabled
let disableConnector = async isConnectorDisabled => {
try {
let connectorID = connectorInfo.merchant_connector_id
let disableConnectorPayload = ConnectorUtils.getDisableConnectorPayload(
connectorInfo.connector_type->ConnectorUtils.connectorTypeTypedValueToStringMapper,
isConnectorDisabled,
)
let url = getURL(~entityName=V1(CONNECTOR), ~methodType=Post, ~id=Some(connectorID))
let _ = await updateDetails(url, disableConnectorPayload->JSON.Encode.object, Post)
showToast(~message="Successfully Saved the Changes", ~toastType=ToastSuccess)
RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/tax-processor"))
} catch {
| Exn.Error(_) => showToast(~message="Failed to Disable connector!", ~toastType=ToastError)
}
}
let getConnectorDetails = async () => {
try {
let connectorUrl = getURL(~entityName=V1(CONNECTOR), ~methodType=Get, ~id=Some(connectorID))
let json = await fetchDetails(connectorUrl)
setInitialValues(_ => json)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to update!")
Exn.raiseError(err)
}
| _ => Exn.raiseError("Something went wrong")
}
}
let getDetails = async () => {
try {
setScreenState(_ => Loading)
let _ = await Window.connectorWasmInit()
if isUpdateFlow {
await getConnectorDetails()
setCurrentStep(_ => Preview)
} else {
setCurrentStep(_ => ConfigurationFields)
}
setScreenState(_ => Success)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong")
setScreenState(_ => Error(err))
}
| _ => setScreenState(_ => Error("Something went wrong"))
}
}
let connectorDetails = React.useMemo(() => {
try {
if connectorName->LogicUtils.isNonEmptyString {
let dict = Window.getTaxProcessorConfig(connectorName)
dict
} else {
Dict.make()->JSON.Encode.object
}
} catch {
| Exn.Error(e) => {
Js.log2("FAILED TO LOAD CONNECTOR CONFIG", e)
let err = Exn.message(e)->Option.getOr("Something went wrong")
setScreenState(_ => PageLoaderWrapper.Error(err))
Dict.make()->JSON.Encode.object
}
}
}, [connectorName])
let (
bodyType,
connectorAccountFields,
connectorMetaDataFields,
_,
connectorWebHookDetails,
connectorLabelDetailField,
connectorAdditionalMerchantData,
) = getConnectorFields(connectorDetails)
React.useEffect(() => {
let initialValuesToDict = initialValues->LogicUtils.getDictFromJsonObject
if !isUpdateFlow {
initialValuesToDict->Dict.set(
"profile_id",
activeBusinessProfile.profile_id->JSON.Encode.string,
)
initialValuesToDict->Dict.set(
"connector_label",
`${connectorName}_${activeBusinessProfile.profile_name}`->JSON.Encode.string,
)
}
None
}, [connectorName, activeBusinessProfile.profile_id])
React.useEffect(() => {
if connectorName->LogicUtils.isNonEmptyString {
getDetails()->ignore
} else {
setScreenState(_ => Error("Connector name not found"))
}
None
}, [connectorName])
let updateBusinessProfileDetails = async mcaId => {
try {
let url = getURL(
~entityName=V1(BUSINESS_PROFILE),
~methodType=Post,
~id=Some(activeBusinessProfile.profile_id),
)
let body = Dict.make()
body->Dict.set("tax_connector_id", mcaId->JSON.Encode.string)
body->Dict.set("is_tax_connector_enabled", true->JSON.Encode.bool)
let _ = await updateDetails(url, body->Identity.genericTypeToJson, Post)
} catch {
| _ => showToast(~message=`Failed to update`, ~toastType=ToastState.ToastError)
}
}
let onSubmit = async (values, _) => {
try {
let body =
generateInitialValuesDict(
~values,
~connector=connectorName,
~bodyType,
~isLiveMode={false},
~connectorType=ConnectorTypes.TaxProcessor,
)->ignoreFields(connectorID, connectorIgnoredField)
let connectorUrl = getURL(
~entityName=V1(CONNECTOR),
~methodType=Post,
~id=isUpdateFlow ? Some(connectorID) : None,
)
let response = await updateAPIHook(connectorUrl, body, Post)
if !isUpdateFlow {
let mcaId =
response
->getDictFromJsonObject
->getString("merchant_connector_id", "")
let _ = await updateBusinessProfileDetails(mcaId)
}
let _ = await fetchConnectorListResponse()
setInitialValues(_ => response)
setCurrentStep(_ => Summary)
} 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)
setCurrentStep(_ => ConfigurationFields)
} else {
showToast(~message=errorMessage, ~toastType=ToastError)
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
}
Nullable.null
}
let validateMandatoryField = values => {
let errors = Dict.make()
let valuesFlattenJson = values->JsonFlattenUtils.flattenObject(true)
validateConnectorRequiredFields(
connectorName->getConnectorNameTypeFromString(~connectorType=TaxProcessor),
valuesFlattenJson,
connectorAccountFields,
connectorMetaDataFields,
connectorWebHookDetails,
connectorLabelDetailField,
errors->JSON.Encode.object,
)
}
let connectorStatusStyle = connectorStatus =>
switch connectorStatus {
| true => "border bg-red-600 bg-opacity-40 border-red-400 text-red-500"
| false => "border bg-green-600 bg-opacity-40 border-green-700 text-green-700"
}
let summaryPageButton = switch currentStep {
| Preview =>
<div className="flex gap-6 items-center">
<div
className={`px-4 py-2 rounded-full w-fit font-medium text-sm !text-black ${isConnectorDisabled->connectorStatusStyle}`}>
{(isConnectorDisabled ? "DISABLED" : "ENABLED")->React.string}
</div>
<MenuOption disableConnector isConnectorDisabled />
</div>
| _ =>
<Button
text="Done"
buttonType=Primary
onClick={_ => RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/tax-processor"))}
/>
}
<PageLoaderWrapper screenState>
<div className="flex flex-col gap-10 overflow-scroll h-full w-full">
<BreadCrumbNavigation
path=[
connectorID === "new"
? {
title: "Tax Processor",
link: "/tax-processor",
warning: `You have not yet completed configuring your ${connectorName->LogicUtils.snakeToTitle} connector. Are you sure you want to go back?`,
}
: {
title: "Tax Porcessor",
link: "/tax-processor",
},
]
currentPageTitle={connectorName->ConnectorUtils.getDisplayNameForConnector(
~connectorType=TaxProcessor,
)}
cursorStyle="cursor-pointer"
/>
<div
className="bg-white rounded-lg border h-3/4 overflow-scroll shadow-boxShadowMultiple show-scrollbar">
{switch currentStep {
| ConfigurationFields =>
<Form initialValues={initialValues} onSubmit validate={validateMandatoryField}>
<ConnectorAccountDetailsHelper.ConnectorHeaderWrapper
connector=connectorName
connectorType={TaxProcessor}
headerButton={<AddDataAttributes
attributes=[("data-testid", "connector-submit-button")]>
<FormRenderer.SubmitButton loadingText="Processing..." text="Connect and Proceed" />
</AddDataAttributes>}>
<div className="flex flex-col gap-2 p-2 md:px-10">
<ConnectorAccountDetailsHelper.BusinessProfileRender
isUpdateFlow selectedConnector={connectorName}
/>
</div>
<div className="flex flex-col gap-2 p-2 md:p-10">
<div className="grid grid-cols-2 flex-1">
<ConnectorAccountDetailsHelper.ConnectorConfigurationFields
connector={connectorName->getConnectorNameTypeFromString(
~connectorType=TaxProcessor,
)}
connectorAccountFields
selectedConnector={connectorName
->getConnectorNameTypeFromString(~connectorType=TaxProcessor)
->getConnectorInfo}
connectorMetaDataFields
connectorWebHookDetails
connectorLabelDetailField
connectorAdditionalMerchantData
/>
</div>
</div>
</ConnectorAccountDetailsHelper.ConnectorHeaderWrapper>
<FormValuesSpy />
</Form>
| Summary | Preview =>
<ConnectorAccountDetailsHelper.ConnectorHeaderWrapper
connector=connectorName connectorType={TaxProcessor} headerButton={summaryPageButton}>
<ConnectorPreview.ConnectorSummaryGrid
connectorInfo={ConnectorInterface.mapDictToConnectorPayload(
ConnectorInterface.connectorInterfaceV1,
initialValues->LogicUtils.getDictFromJsonObject,
)}
connector=connectorName
setCurrentStep
getConnectorDetails={Some(getConnectorDetails)}
/>
</ConnectorAccountDetailsHelper.ConnectorHeaderWrapper>
}}
</div>
</div>
</PageLoaderWrapper>
}
| 2,843 | 9,650 |
hyperswitch-control-center | src/screens/Connectors/TaxProcessor/TaxProcessorTypes.res | .res | type steps = ConfigurationFields | Summary | Preview
| 10 | 9,651 |
hyperswitch-control-center | src/screens/Connectors/FraudAndRisk/FRMTypes.res | .res | type filterType = Connector | FRMPlayer | ThreedsAuthenticator
type flowType = PreAuth | PostAuth
type frmActionType = CancelTxn | AutoRefund | ManualReview | Process
let getDisableConnectorPayload = (connectorInfo, previousConnectorState) => {
let dictToJson = connectorInfo->LogicUtils.getDictFromJsonObject
[
("connector_type", dictToJson->LogicUtils.getString("connector_type", "")->JSON.Encode.string),
("disabled", !previousConnectorState->JSON.Encode.bool),
]->Dict.fromArray
}
| 119 | 9,652 |
hyperswitch-control-center | src/screens/Connectors/FraudAndRisk/FRMTableUtils.res | .res | let getArrayDataFromJson = (json, itemToObjMapper) => {
json
->JSON.Decode.array
->Option.getOr([])
->Belt.Array.keepMap(JSON.Decode.object)
->FRMUtils.filterList(~removeFromList=Connector)
->Array.map(itemToObjMapper)
}
let getPreviouslyConnectedList: JSON.t => array<ConnectorTypes.connectorPayload> = json => {
let data = ConnectorInterface.mapJsonArrayToConnectorPayloads(
ConnectorInterface.connectorInterfaceV1,
json,
PaymentVas,
)
data
}
let connectorEntity = (path: string, ~authorization: CommonAuthTypes.authorization) => {
EntityType.makeEntity(
~uri=``,
~getObjects=getPreviouslyConnectedList,
~defaultColumns=ConnectorTableUtils.defaultColumns,
~getHeading=ConnectorTableUtils.getHeading,
~getCell=ConnectorTableUtils.getTableCell(~connectorType=FRMPlayer),
~dataKey="",
~getShowLink={
connec =>
GroupAccessUtils.linkForGetShowLinkViaAccess(
~url=GlobalVars.appendDashboardPath(
~url=`/${path}/${connec.merchant_connector_id}?name=${connec.connector_name}`,
),
~authorization,
)
},
)
}
| 272 | 9,653 |
hyperswitch-control-center | src/screens/Connectors/FraudAndRisk/FRMIntegrationFields.res | .res | module AdvanceSettings = {
@react.component
let make = (~isUpdateFlow, ~frmName, ~renderCountrySelector) => {
let (isFRMSettings, setIsFRMSettings) = React.useState(_ => isUpdateFlow)
let form = ReactFinalForm.useForm()
let inputLabel: ReactFinalForm.fieldRenderPropsInput = {
name: `input`,
onBlur: _ => (),
onChange: ev => {
let value = ev->Identity.formReactEventToBool
setIsFRMSettings(_ => value)
},
onFocus: _ => (),
value: {isFRMSettings->JSON.Encode.bool},
checked: true,
}
let businessProfileValue =
Recoil.useRecoilValueFromAtom(
HyperswitchAtom.businessProfilesAtom,
)->MerchantAccountUtils.getValueFromBusinessProfile
React.useEffect(() => {
if !isUpdateFlow {
form.change("profile_id", businessProfileValue.profile_id->JSON.Encode.string)
}
None
}, [businessProfileValue.profile_id])
<>
<div className="flex gap-2 items-center p-2">
<BoolInput input={inputLabel} isDisabled={isUpdateFlow} boolCustomClass="rounded-full" />
<p className="font-semibold !text-black opacity-50 ">
{"Show advanced settings"->React.string}
</p>
</div>
<RenderIf condition={renderCountrySelector && isFRMSettings}>
<ConnectorAccountDetailsHelper.BusinessProfileRender
isUpdateFlow selectedConnector={frmName}
/>
</RenderIf>
</>
}
}
module IntegrationFieldsForm = {
open FRMUtils
@react.component
let make = (
~selectedFRMName,
~initialValues,
~onSubmit,
~renderCountrySelector=true,
~pageState=PageLoaderWrapper.Success,
~setCurrentStep,
~frmName,
~isUpdateFlow,
) => {
let buttonText = switch pageState {
| Error("") => "Try Again"
| Loading => "Loading..."
| _ => isUpdateFlow ? "Update" : "Connect and Finish"
}
let validateRequiredFields = (
valuesFlattenJson,
~fields: array<ConnectorTypes.connectorIntegrationField>,
~errors,
) => {
fields->Array.forEach(field => {
let key = field.name
let value =
valuesFlattenJson
->Dict.get(key)
->Option.getOr(""->JSON.Encode.string)
->LogicUtils.getStringFromJson("")
if field.isRequired->Option.getOr(true) && value->String.length === 0 {
Dict.set(errors, key, `Please enter ${field.label->Option.getOr("")}`->JSON.Encode.string)
}
})
}
let validateCountryCurrency = (valuesFlattenJson, ~errors) => {
let profileId = valuesFlattenJson->LogicUtils.getString("profile_id", "")
if profileId->String.length <= 0 {
Dict.set(errors, "Profile Id", `Please select your business profile`->JSON.Encode.string)
}
}
let selectedFRMInfo = selectedFRMName->ConnectorUtils.getConnectorInfo
let validate = values => {
let errors = Dict.make()
let valuesFlattenJson = values->JsonFlattenUtils.flattenObject(true)
//checking for required fields
valuesFlattenJson->validateRequiredFields(
~fields=selectedFRMInfo.validate->Option.getOr([]),
~errors,
)
if renderCountrySelector {
valuesFlattenJson->validateCountryCurrency(~errors)
}
errors->JSON.Encode.object
}
let validateMandatoryField = values => {
let errors = Dict.make()
let valuesFlattenJson = values->JsonFlattenUtils.flattenObject(true)
//checking for required fields
valuesFlattenJson->validateRequiredFields(
~fields=selectedFRMInfo.validate->Option.getOr([]),
~errors,
)
if renderCountrySelector {
valuesFlattenJson->validateCountryCurrency(~errors)
}
errors->JSON.Encode.object
}
<Form initialValues onSubmit validate={validateMandatoryField}>
<div className="flex">
<div className="grid grid-cols-2 flex-1 gap-5">
<div className="flex flex-col gap-3">
<AdvanceSettings isUpdateFlow frmName renderCountrySelector />
{selectedFRMInfo.validate
->Option.getOr([])
->Array.mapWithIndex((field, index) => {
let parse =
field.encodeToBase64->Option.getOr(false) ? base64Parse : leadingSpaceStrParser
let format = field.encodeToBase64->Option.getOr(false) ? Some(base64Format) : None
<div key={index->Int.toString}>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-black"
field={FormRenderer.makeFieldInfo(
~label=field.label->Option.getOr(""),
~name={field.name},
~placeholder=field.placeholder->Option.getOr(""),
~description=field.description->Option.getOr(""),
~isRequired=true,
~parse,
~format?,
)}
/>
<ConnectorAccountDetailsHelper.ErrorValidation fieldName={field.name} validate />
</div>
})
->React.array}
</div>
<div className="flex flex-row mt-6 md:mt-0 md:justify-self-end h-min">
{if pageState === Loading {
<Button buttonType={Primary} buttonState={Loading} text=buttonText />
} else {
<div className="flex gap-5">
<Button
buttonType={Secondary}
text="Back"
onClick={_ => setCurrentStep(prev => prev->FRMInfo.getPrevStep)}
/>
<FormRenderer.SubmitButton loadingText="Processing..." text=buttonText />
</div>
}}
</div>
</div>
</div>
<FormValuesSpy />
</Form>
}
}
@react.component
let make = (
~setCurrentStep,
~selectedFRMName,
~retrivedValues=None,
~setInitialValues,
~isUpdateFlow,
) => {
open FRMUtils
open FRMInfo
open APIUtils
open Promise
open CommonAuthHooks
let getURL = useGetURL()
let showToast = ToastState.useShowToast()
let frmName = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("name", "")
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let mixpanelEvent = MixpanelHook.useSendEvent()
let fetchConnectorListResponse = ConnectorListHook.useFetchConnectorList()
let (pageState, setPageState) = React.useState(_ => PageLoaderWrapper.Success)
let {merchantId} = useCommonAuthInfo()->Option.getOr(defaultAuthInfo)
let initialValues = React.useMemo(() => {
open LogicUtils
switch retrivedValues {
| Some(json) => {
let initialValuesObj = json->getDictFromJsonObject
let frmAccountDetailsObj =
initialValuesObj->getObj("connector_account_details", Dict.make())
frmAccountDetailsObj->Dict.set(
"auth_type",
selectedFRMName->getFRMAuthType->JSON.Encode.string,
)
initialValuesObj->Dict.set(
"connector_account_details",
frmAccountDetailsObj->JSON.Encode.object,
)
initialValuesObj->JSON.Encode.object
}
| None =>
generateInitialValuesDict(~selectedFRMName, ~isLiveMode={featureFlagDetails.isLiveMode})
}
}, [retrivedValues])
let frmID =
retrivedValues
->Option.getOr(Dict.make()->JSON.Encode.object)
->LogicUtils.getDictFromJsonObject
->LogicUtils.getString("merchant_connector_id", "")
let submitText = if !isUpdateFlow {
"FRM Player Created Successfully!"
} else {
"Details Updated!"
}
let updateDetails = useUpdateMethod()
let frmUrl = if frmID->String.length <= 0 {
getURL(~entityName=V1(FRAUD_RISK_MANAGEMENT), ~methodType=Post)
} else {
getURL(~entityName=V1(FRAUD_RISK_MANAGEMENT), ~methodType=Post, ~id=Some(frmID))
}
let updateMerchantDetails = async () => {
let info =
[
("data", "signifyd"->JSON.Encode.string),
("type", "single"->JSON.Encode.string),
]->Dict.fromArray
let body =
[
("frm_routing_algorithm", info->JSON.Encode.object),
("merchant_id", merchantId->JSON.Encode.string),
]
->Dict.fromArray
->JSON.Encode.object
let url = getURL(~entityName=V1(MERCHANT_ACCOUNT), ~methodType=Post)
try {
let _ = await updateDetails(url, body, Post)
} catch {
| _ => ()
}
Nullable.null
}
let setFRMValues = async body => {
open LogicUtils
try {
let response = await updateDetails(frmUrl, body, Post)
let _ = updateMerchantDetails()
let _ = await fetchConnectorListResponse()
setInitialValues(_ => response)
setCurrentStep(prev => prev->getNextStep)
showToast(~message=submitText, ~toastType=ToastSuccess)
setPageState(_ => Success)
} 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)
setPageState(_ => Error(""))
} else {
showToast(~message=errorMessage, ~toastType=ToastError)
setPageState(_ => Error(""))
}
}
}
Nullable.null
}
let onSubmit = (values, _) => {
mixpanelEvent(~eventName="frm_step2")
setPageState(_ => Loading)
let body = isUpdateFlow ? values->ignoreFields : values
setFRMValues(body)->ignore
Nullable.null->resolve
}
<IntegrationFieldsForm
selectedFRMName initialValues onSubmit pageState isUpdateFlow setCurrentStep frmName
/>
}
| 2,287 | 9,654 |
hyperswitch-control-center | src/screens/Connectors/FraudAndRisk/FRMSelect.res | .res | module NewProcessorCards = {
open FRMInfo
@react.component
let make = (~configuredFRMs: array<ConnectorTypes.connectorTypes>) => {
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
let mixpanelEvent = MixpanelHook.useSendEvent()
let frmAvailableForIntegration = frmList
let unConfiguredFRMs = frmAvailableForIntegration->Array.filter(total =>
configuredFRMs
->Array.find(item =>
item->ConnectorUtils.getConnectorNameString === total->ConnectorUtils.getConnectorNameString
)
->Option.isNone
)
let handleClick = frmName => {
mixpanelEvent(~eventName=`connect_frm_${frmName}`)
RescriptReactRouter.push(
GlobalVars.appendDashboardPath(~url=`/fraud-risk-management/new?name=${frmName}`),
)
}
let unConfiguredFRMCount = unConfiguredFRMs->Array.length
let descriptedFRMs = (frmList: array<ConnectorTypes.connectorTypes>, heading) => {
<>
<h2
className="font-bold text-xl text-black text-opacity-75 dark:text-white dark:text-opacity-75">
{heading->React.string}
</h2>
<div className="grid gap-4 lg:grid-cols-4 md:grid-cols-2 grid-cols-1 mb-5">
{frmList
->Array.mapWithIndex((frm, i) => {
let frmName = frm->ConnectorUtils.getConnectorNameString
let frmInfo = frm->ConnectorUtils.getConnectorInfo
<CardUtils.CardLayout key={Int.toString(i)} width="w-full">
<div className="flex gap-2 items-center mb-3">
<GatewayIcon
gateway={frmName->String.toUpperCase} className="w-10 h-10 rounded-lg"
/>
<h1 className="text-xl font-semibold break-all">
{frmName->LogicUtils.capitalizeString->React.string}
</h1>
</div>
<div className="overflow-hidden text-gray-400 flex-1 mb-6">
{frmInfo.description->React.string}
</div>
<ACLButton
text="Connect"
authorization={userHasAccess(~groupAccess=ConnectorsManage)}
buttonType=Secondary
buttonSize=Small
onClick={_ => handleClick(frmName)}
leftIcon={CustomIcon(
<Icon
name="plus"
size=16
className="text-jp-gray-900 fill-opacity-50 dark:jp-gray-text_darktheme"
/>,
)}
/>
</CardUtils.CardLayout>
})
->React.array}
</div>
</>
}
let headerText = "Connect a new fraud & risk management player"
<RenderIf condition={unConfiguredFRMCount > 0}>
<div className="flex flex-col gap-4">
{frmAvailableForIntegration->descriptedFRMs(headerText)}
</div>
</RenderIf>
}
}
@react.component
let make = () => {
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let isMobileView = MatchMedia.useMatchMedia("(max-width: 844px)")
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
let (
configuredFRMs: array<ConnectorTypes.connectorPayload>,
setConfiguredFRMs,
) = React.useState(_ => [])
let (filteredFRMData, setFilteredFRMData) = React.useState(_ => [])
let (offset, setOffset) = React.useState(_ => 0)
let (searchText, setSearchText) = React.useState(_ => "")
let connectorList = ConnectorInterface.useConnectorArrayMapper(
~interface=ConnectorInterface.connectorInterfaceV1,
~retainInList=PaymentProcessor,
)
let frmConnectorList = ConnectorInterface.useConnectorArrayMapper(
~interface=ConnectorInterface.connectorInterfaceV1,
~retainInList=PaymentVas,
)
let customUI =
<HelperComponents.BluredTableComponent
infoText="No connectors configured yet. Try connecting a connector."
buttonText="Take me to connectors"
onClickElement={React.null}
onClickUrl="connectors"
moduleName="Fraud & Risk Management"
moduleSubtitle="Connect and configure processors to screen transactions and mitigate fraud"
/>
let getConnectorList = async _ => {
try {
let processorsList =
connectorList->Array.filter(item => item.connector_type === PaymentProcessor)
let connectorsCount = processorsList->Array.length
if connectorsCount > 0 {
setConfiguredFRMs(_ => frmConnectorList)
setFilteredFRMData(_ => frmConnectorList->Array.map(Nullable.make))
setScreenState(_ => Success)
} else {
setScreenState(_ => Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Error("Failed to fetch"))
}
}
React.useEffect(() => {
getConnectorList()->ignore
None
}, [])
// TODO: Convert it to remote filter
let filterLogic = ReactDebounce.useDebounced(ob => {
open LogicUtils
let (searchText, arr) = ob
let filteredList = if searchText->isNonEmptyString {
arr->Array.filter((frmPlayer: Nullable.t<ConnectorTypes.connectorPayload>) => {
switch Nullable.toOption(frmPlayer) {
| Some(frmPlayer) =>
isContainingStringLowercase(frmPlayer.connector_name, searchText) ||
isContainingStringLowercase(frmPlayer.merchant_connector_id, searchText) ||
isContainingStringLowercase(frmPlayer.connector_label, searchText)
| None => false
}
})
} else {
arr
}
setFilteredFRMData(_ => filteredList)
}, ~wait=200)
<PageLoaderWrapper screenState customUI>
<div className="flex flex-col gap-10 ">
<PageUtils.PageHeading
title="Fraud & Risk Management"
subTitle="Connect and configure processors to screen transactions and mitigate fraud"
/>
<RenderIf condition={configuredFRMs->Array.length > 0}>
<LoadedTable
title="Connected Processors"
actualData={filteredFRMData}
totalResults={filteredFRMData->Array.length}
filters={<TableSearchFilter
data={configuredFRMs->Array.map(Nullable.make)}
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={FRMTableUtils.connectorEntity(
"fraud-risk-management",
~authorization={userHasAccess(~groupAccess=ConnectorsManage)},
)}
currrentFetchCount={configuredFRMs->Array.length}
collapseTableRow=false
/>
</RenderIf>
<NewProcessorCards
configuredFRMs={ConnectorInterface.mapConnectorPayloadToConnectorType(
ConnectorInterface.connectorInterfaceV1,
ConnectorTypes.FRMPlayer,
configuredFRMs,
)}
/>
<RenderIf condition={!isMobileView}>
<img alt="frm-banner" className="w-full max-w-[1400px] mb-10" src="/assets/frmBanner.svg" />
</RenderIf>
</div>
</PageLoaderWrapper>
}
| 1,642 | 9,655 |
hyperswitch-control-center | src/screens/Connectors/FraudAndRisk/FRMInfo.res | .res | open FRMTypes
let frmList: array<ConnectorTypes.connectorTypes> = [FRM(Signifyd), FRM(Riskifyed)]
let flowTypeList = [PreAuth, PostAuth]
let getFRMAuthType = (connector: ConnectorTypes.connectorTypes) => {
switch connector {
| FRM(Signifyd) => "HeaderKey"
| FRM(Riskifyed) => "BodyKey"
| _ => ""
}
}
let stepsArr: array<ConnectorTypes.steps> = [PaymentMethods, IntegFields, SummaryAndTest]
let getNextStep: ConnectorTypes.steps => ConnectorTypes.steps = currentStep => {
switch currentStep {
| PaymentMethods => IntegFields
| IntegFields => SummaryAndTest
| SummaryAndTest => SummaryAndTest
| _ => Preview
}
}
let getPrevStep: ConnectorTypes.steps => ConnectorTypes.steps = currentStep => {
switch currentStep {
| IntegFields => PaymentMethods
| SummaryAndTest => IntegFields
| _ => Preview
}
}
let getFlowTypeNameString = flowType => {
switch flowType {
| PreAuth => "pre"
| PostAuth => "post"
}
}
let getFlowTypeVariantFromString = flowTypeString => {
switch flowTypeString {
| "pre" => PreAuth
| _ => PostAuth
}
}
let getFlowTypeLabel = flowType => {
switch flowType->getFlowTypeVariantFromString {
| PreAuth => "Pre Auth"
| PostAuth => "Post Auth"
}
}
let frmPreActionList = [CancelTxn]
let frmPostActionList = [ManualReview]
let getActionTypeNameString = flowType => {
switch flowType {
| CancelTxn => "cancel_txn"
| AutoRefund => "auto_refund"
| ManualReview => "manual_review"
| Process => "process"
}
}
let getActionTypeNameVariantFromString = flowType => {
switch flowType {
| "auto_refund" => AutoRefund
| "manual_review" => ManualReview
| "process" => Process
| "cancel_txn" | _ => CancelTxn
}
}
let getActionTypeLabel = actionType => {
switch actionType->getActionTypeNameVariantFromString {
| CancelTxn => "Cancel Transactions"
| AutoRefund => "Auto Refund"
| ManualReview => "Manual Review"
| Process => "Process Transactions"
}
}
let flowTypeAllOptions = flowTypeList->Array.map(getFlowTypeNameString)
let getActionTypeAllOptions = flowType => {
switch flowType->getFlowTypeVariantFromString {
| PreAuth => frmPreActionList->Array.map(getActionTypeNameString)
| PostAuth => frmPostActionList->Array.map(getActionTypeNameString)
}
}
let ignoredField = [
"business_country",
"business_label",
"business_sub_label",
"connector_label",
"merchant_connector_id",
"connector_name",
"profile_id",
"applepay_verified_domains",
"additional_merchant_data",
]
let actionDescriptionForFlow = flowType => {
switch flowType {
| PreAuth => "PreAuth flow - fraudulent transactions are cancelled before authorization."
| PostAuth => "PostAuth flow - fraudulent transactions are flagged for a manual review before amount capture."
}
}
| 736 | 9,656 |
hyperswitch-control-center | src/screens/Connectors/FraudAndRisk/FRMConfigure.res | .res | @react.component
let make = () => {
open FRMUtils
open APIUtils
open ConnectorTypes
open LogicUtils
open FRMInfo
let getURL = useGetURL()
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let url = RescriptReactRouter.useUrl()
let fetchDetails = useGetMethod()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (initialValues, setInitialValues) = React.useState(_ => Dict.make()->JSON.Encode.object)
let frmName = UrlUtils.useGetFilterDictFromUrl("")->getString("name", "")
let frmID = HSwitchUtils.getConnectorIDFromUrl(url.path->List.toArray, "")
let initStep = PaymentMethods
let isUpdateFlow = switch url.path->HSwitchUtils.urlPath {
| list{"fraud-risk-management", "new"} => false
| _ => true
}
let (currentStep, setCurrentStep) = React.useState(_ => isUpdateFlow ? Preview : initStep)
let selectedFRMName: ConnectorTypes.connectorTypes = React.useMemo(() => {
let frmName = frmName->ConnectorUtils.getConnectorNameTypeFromString(~connectorType=FRMPlayer)
setInitialValues(_ => {
generateInitialValuesDict(~selectedFRMName=frmName, ~isLiveMode=featureFlagDetails.isLiveMode)
})
setCurrentStep(_ => isUpdateFlow ? Preview : initStep)
frmName
}, [frmName])
let getFRMDetails = async url => {
try {
let res = await fetchDetails(url)
setInitialValues(_ => res)
setScreenState(_ => Success)
setCurrentStep(prev => prev->getNextStep)
} catch {
| _ => setScreenState(_ => Error("Error Occured!"))
}
}
React.useEffect(() => {
if frmID !== "new" {
setScreenState(_ => Loading)
let url = getURL(~entityName=V1(FRAUD_RISK_MANAGEMENT), ~methodType=Get, ~id=Some(frmID))
getFRMDetails(url)->ignore
} else {
setScreenState(_ => Success)
}
None
}, [])
let path: array<BreadCrumbNavigation.breadcrumb> = []
if frmID === "new" {
path
->Array.push({
title: {"Fraud Risk Management"},
link: "/fraud-risk-management",
warning: `You have not yet completed configuring your ${selectedFRMName
->ConnectorUtils.getConnectorNameString
->snakeToTitle} player. Are you sure you want to go back?`,
mixPanelCustomString: ` ${selectedFRMName->ConnectorUtils.getConnectorNameString}`,
})
->ignore
} else {
path
->Array.push({
title: {"Fraud Risk Management"},
link: "/fraud-risk-management",
})
->ignore
}
<PageLoaderWrapper screenState>
<div className="flex flex-col gap-8 h-full">
<BreadCrumbNavigation
path currentPageTitle={frmName->capitalizeString} cursorStyle="cursor-pointer"
/>
<RenderIf condition={currentStep !== Preview}>
<ConnectorHome.ConnectorCurrentStepIndicator currentStep stepsArr />
</RenderIf>
<div className="bg-white rounded border h-3/4 p-2 md:p-6 overflow-scroll">
{switch currentStep {
| IntegFields =>
<FRMIntegrationFields
setCurrentStep
selectedFRMName
setInitialValues
retrivedValues=Some(initialValues)
isUpdateFlow
/>
| PaymentMethods =>
<FRMPaymentMethods
setCurrentStep retrivedValues=Some(initialValues) setInitialValues isUpdateFlow
/>
| SummaryAndTest
| Preview =>
<FRMSummary initialValues currentStep />
| _ => React.null
}}
</div>
</div>
</PageLoaderWrapper>
}
| 883 | 9,657 |
hyperswitch-control-center | src/screens/Connectors/FraudAndRisk/FRMSummary.res | .res | module InfoField = {
open LogicUtils
@react.component
let make = (~label, ~flowTypeValue) => {
<div className="flex flex-col gap-2 mb-7">
<h4 className="text-lg font-semibold underline"> {label->snakeToTitle->React.string} </h4>
<div className="flex flex-col gap-1">
<h3 className="break-all">
<span className="font-semibold mr-3"> {"Flow :"->React.string} </span>
{flowTypeValue->React.string}
</h3>
</div>
</div>
}
}
module ConfigInfo = {
open LogicUtils
open ConnectorTypes
open FRMInfo
@react.component
let make = (~frmConfigs) => {
frmConfigs
->Array.mapWithIndex((config, i) => {
<div className="grid grid-cols-2 md:w-1/2 ml-12 my-12" key={i->Int.toString}>
<h4 className="text-lg font-semibold"> {config.gateway->snakeToTitle->React.string} </h4>
<div>
{config.payment_methods
->Array.mapWithIndex((paymentMethod, ind) => {
if paymentMethod.payment_method_types->Option.getOr([])->Array.length == 0 {
<InfoField
key={ind->Int.toString}
label={paymentMethod.payment_method}
flowTypeValue={paymentMethod.flow->getFlowTypeLabel}
/>
} else {
paymentMethod.payment_method_types
->Option.getOr([])
->Array.mapWithIndex(
(paymentMethodType, index) => {
<RenderIf condition={index == 0}>
<InfoField
key={index->Int.toString}
label={paymentMethod.payment_method}
flowTypeValue={paymentMethodType.flow->getFlowTypeLabel}
/>
</RenderIf>
},
)
->React.array
}
})
->React.array}
</div>
</div>
})
->React.array
}
}
@react.component
let make = (~initialValues, ~currentStep) => {
open LogicUtils
open FRMUtils
open APIUtils
open ConnectorTypes
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let url = RescriptReactRouter.useUrl()
let showToast = ToastState.useShowToast()
let mixpanelEvent = MixpanelHook.useSendEvent()
let frmInfo = ConnectorInterface.mapDictToConnectorPayload(
ConnectorInterface.connectorInterfaceV1,
initialValues->getDictFromJsonObject,
)
let isfrmDisabled = initialValues->getDictFromJsonObject->getBool("disabled", false)
let frmConfigs = switch frmInfo.frm_configs {
| Some(config) => config
| _ => []
}
let disableFRM = async isFRMDisabled => {
try {
let frmID = initialValues->getDictFromJsonObject->getString("merchant_connector_id", "")
let disableFRMPayload = initialValues->FRMTypes.getDisableConnectorPayload(isFRMDisabled)
let url = getURL(~entityName=V1(FRAUD_RISK_MANAGEMENT), ~methodType=Post, ~id=Some(frmID))
let _ = await updateDetails(url, disableFRMPayload->JSON.Encode.object, Post)
showToast(~message=`Successfully Saved the Changes`, ~toastType=ToastSuccess)
RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/fraud-risk-management"))
} catch {
| Exn.Error(_) => showToast(~message=`Failed to Disable connector!`, ~toastType=ToastError)
}
}
<div>
<div className="flex justify-between border-b sticky top-0 bg-white pb-2">
<div className="flex gap-2 items-center">
<GatewayIcon gateway={String.toUpperCase(frmInfo.connector_name)} className=size />
<h2 className="text-xl font-semibold">
{frmInfo.connector_name->capitalizeString->React.string}
</h2>
</div>
{switch currentStep {
| Preview =>
<div className="flex gap-6 items-center">
<p
className={`text-fs-13 font-bold ${isfrmDisabled ? "text-red-800" : "text-green-700"}`}>
{(isfrmDisabled ? "INACTIVE" : "ACTIVE")->React.string}
</p>
<ConnectorPreview.MenuOption
updateStepValue={ConnectorTypes.PaymentMethods}
disableConnector={disableFRM}
isConnectorDisabled={isfrmDisabled}
pageName={url.path->LogicUtils.getListHead}
/>
</div>
| _ =>
<Button
onClick={_ => {
mixpanelEvent(~eventName="frm_step3")
RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/fraud-risk-management"))
}}
text="Done"
buttonType={Primary}
/>
}}
</div>
<div>
<div className="grid grid-cols-2 md:w-1/2 m-12">
<h4 className="text-lg font-semibold"> {"Profile id"->React.string} </h4>
<div> {frmInfo.profile_id->React.string} </div>
</div>
<RenderIf condition={frmConfigs->Array.length > 0}>
<ConfigInfo frmConfigs />
</RenderIf>
</div>
</div>
}
| 1,186 | 9,658 |
hyperswitch-control-center | src/screens/Connectors/FraudAndRisk/FRMPaymentMethods.res | .res | module ToggleSwitch = {
open FRMUtils
@react.component
let make = (~isOpen, ~handleOnChange, ~isToggleDisabled) => {
let cursorType = isToggleDisabled ? "cursor-not-allowed" : "cursor-pointer"
let enabledClasses = if isOpen {
`bg-green-700 ${cursorType} ${toggleDefaultStyle}`
} else {
`bg-gray-300 ${cursorType} ${toggleDefaultStyle}`
}
let enabledSpanClasses = if isOpen {
`translate-x-7 ${accordionDefaultStyle}`
} else {
`translate-x-1 ${accordionDefaultStyle}`
}
<HeadlessUI.Switch checked={isOpen} onChange={_ => handleOnChange()} className={enabledClasses}>
{_checked => {
<>
<div ariaHidden=true className={enabledSpanClasses} />
</>
}}
</HeadlessUI.Switch>
}
}
module FormField = {
open FRMInfo
@react.component
let make = (~fromConfigIndex, ~paymentMethodIndex, ~options, ~label, ~description) => {
<div className="w-max">
<div className="flex">
<h3 className="font-semibold text-bold text-lg pb-2">
{label->LogicUtils.snakeToTitle->React.string}
</h3>
<div className="w-10 h-7 text-gray-300">
<ToolTip
description
tooltipWidthClass="w-96"
toolTipFor={<Icon name="info-circle" size=15 />}
toolTipPosition=ToolTip.Top
/>
</div>
</div>
<div className={`grid grid-cols-2 md:grid-cols-4 gap-4`}>
<FormRenderer.FieldRenderer
field={FormRenderer.makeFieldInfo(
~label="",
~name=`frm_configs[${fromConfigIndex}].payment_methods[${paymentMethodIndex}].flow`,
~customInput=InputFields.radioInput(
~options=options->Array.map((item): SelectBox.dropdownOption => {
{
label: item->getFlowTypeLabel,
value: item,
}
}),
~buttonText="options",
~baseComponentCustomStyle="flex",
~customStyle="flex gap-2 !overflow-visible",
),
)}
/>
</div>
</div>
}
}
module CheckBoxRenderer = {
open FRMUtils
open FRMInfo
@react.component
let make = (
~fromConfigIndex,
~frmConfigInfo: ConnectorTypes.frm_config,
~frmConfigs,
~connectorPaymentMethods,
~isUpdateFlow,
) => {
let showPopUp = PopUpState.useShowPopUp()
let frmConfigInput = ReactFinalForm.useField("frm_configs").input
let setConfigJson = {frmConfigInput.onChange}
let isToggleDisabled = switch connectorPaymentMethods {
| Some(paymentMethods) => paymentMethods->Dict.keysToArray->Array.length <= 0
| _ => true
}
let initToggleValue = isUpdateFlow
? frmConfigInfo.payment_methods->Array.length > 0
: !isToggleDisabled
let (isOpen, setIsOpen) = React.useState(_ => initToggleValue)
let showConfitmation = () => {
showPopUp({
popUpType: (Warning, WithIcon),
heading: "Heads up!",
description: {
"Disabling the current toggle will result in the permanent deletion of all configurations associated with it"->React.string
},
handleConfirm: {
text: "Yes, disable it",
onClick: {
_ => {
frmConfigInfo.payment_methods = []
setIsOpen(_ => !isOpen)
setConfigJson(frmConfigs->Identity.anyTypeToReactEvent)
}
},
},
handleCancel: {
text: "No",
onClick: {
_ => ()
},
},
})
}
let handleOnChange = () => {
if !isToggleDisabled {
if !isOpen {
switch connectorPaymentMethods {
| Some(paymentMethods) => {
frmConfigInfo.payment_methods = paymentMethods->generateFRMPaymentMethodsConfig
setConfigJson(frmConfigs->Identity.anyTypeToReactEvent)
}
| _ => ()
}
setIsOpen(_ => !isOpen)
} else if frmConfigInfo.payment_methods->Array.length > 0 {
if isUpdateFlow {
showConfitmation()
} else {
frmConfigInfo.payment_methods = []
setConfigJson(frmConfigs->Identity.anyTypeToReactEvent)
setIsOpen(_ => !isOpen)
}
}
}
}
React.useEffect(() => {
if isOpen && !isUpdateFlow {
switch connectorPaymentMethods {
| Some(paymentMethods) => {
frmConfigInfo.payment_methods = paymentMethods->generateFRMPaymentMethodsConfig
setConfigJson(frmConfigs->Identity.anyTypeToReactEvent)
}
| _ => ()
}
}
None
}, [])
<div>
<div
className="w-full px-5 py-3 bg-light-gray-bg flex items-center gap-3 justify-between border">
<div className="font-semibold text-bold text-lg">
{frmConfigInfo.gateway->LogicUtils.snakeToTitle->React.string}
</div>
<div className="mt-2">
{if isToggleDisabled {
<ToolTip
description="No payment methods available"
toolTipFor={<ToggleSwitch isOpen handleOnChange isToggleDisabled />}
toolTipPosition=ToolTip.Top
/>
} else {
<ToggleSwitch isOpen handleOnChange isToggleDisabled />
}}
</div>
</div>
{frmConfigInfo.payment_methods
->Array.mapWithIndex((paymentMethodInfo, index) => {
<RenderIf condition={isOpen} key={index->Int.toString}>
<Accordion
key={index->Int.toString}
initialExpandedArray=[0]
accordion={[
{
title: paymentMethodInfo.payment_method->LogicUtils.snakeToTitle,
renderContent: () => {
<div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
<FormField
options={flowTypeAllOptions}
label="Choose one of the flows"
fromConfigIndex
paymentMethodIndex={index->Int.toString}
description="i. \"PreAuth\" - facilitate transaction verification prior to payment authorization.
ii. \"PostAuth\" - facilitate transaction validation post-authorization, before amount capture."
/>
</div>
},
renderContentOnTop: None,
},
]}
accordianTopContainerCss="border"
accordianBottomContainerCss="p-5"
contentExpandCss="px-10 pb-6 pt-3 !border-t-0"
titleStyle="font-semibold text-bold text-md"
/>
</RenderIf>
})
->React.array}
</div>
}
}
module PaymentMethodsRenderer = {
open FRMUtils
open LogicUtils
@react.component
let make = (~isUpdateFlow) => {
let (pageState, setPageState) = React.useState(_ => PageLoaderWrapper.Loading)
let frmConfigInput = ReactFinalForm.useField("frm_configs").input
let frmConfigs = parseFRMConfig(frmConfigInput.value)
let (connectorConfig, setConnectorConfig) = React.useState(_ => Dict.make())
let setConfigJson = frmConfigInput.onChange
let fetchConnectorListResponse = ConnectorListHook.useFetchConnectorList()
let getConfiguredConnectorDetails = async () => {
try {
let response = await fetchConnectorListResponse()
let connectorsConfig =
response
->getArrayFromJson([])
->Array.map(getDictFromJsonObject)
->FRMUtils.filterList(~removeFromList=FRMPlayer)
->FRMUtils.filterList(~removeFromList=ThreedsAuthenticator)
->getConnectorConfig
let updateFRMConfig =
connectorsConfig
->createAllOptions
->Array.map(defaultConfig => {
switch frmConfigs->Array.find(item => item.gateway === defaultConfig.gateway) {
| Some(config) => config
| _ => defaultConfig
}
})
setConnectorConfig(_ => connectorsConfig)
setConfigJson(updateFRMConfig->Identity.anyTypeToReactEvent)
setPageState(_ => Success)
} catch {
| _ => setPageState(_ => Error("Failed to fetch"))
}
}
React.useEffect(() => {
getConfiguredConnectorDetails()->ignore
None
}, [])
<PageLoaderWrapper screenState={pageState}>
<div className="flex flex-col gap-4">
{frmConfigs
->Array.mapWithIndex((configInfo, i) => {
<CheckBoxRenderer
key={i->Int.toString}
frmConfigInfo={configInfo}
frmConfigs
connectorPaymentMethods={connectorConfig->Dict.get(configInfo.gateway)}
isUpdateFlow
fromConfigIndex={i->Int.toString}
/>
})
->React.array}
</div>
</PageLoaderWrapper>
}
}
@react.component
let make = (~setCurrentStep, ~retrivedValues=None, ~setInitialValues, ~isUpdateFlow: bool) => {
open FRMInfo
open FRMUtils
open LogicUtils
let mixpanelEvent = MixpanelHook.useSendEvent()
let initialValues = retrivedValues->Option.getOr(Dict.make()->JSON.Encode.object)
let onSubmit = (values, _) => {
open Promise
mixpanelEvent(~eventName="frm_step1")
let valuesDict = values->getDictFromJsonObject
// filter connector frm config having no payment method config
let filteredArray =
valuesDict
->getJsonObjectFromDict("frm_configs")
->parseFRMConfig
->Array.filter(config => config.payment_methods->Array.length > 0)
valuesDict->Dict.set(
"frm_configs",
filteredArray->Array.length > 0
? filteredArray->Identity.genericTypeToJson
: JSON.Encode.null,
)
setInitialValues(_ => valuesDict->JSON.Encode.object)
setCurrentStep(prev => prev->getNextStep)
Nullable.null->resolve
}
let validate = _values => {
let errors = Dict.make()
errors->JSON.Encode.object
}
<Form initialValues onSubmit validate>
<div className="flex">
<div className="flex flex-col w-full">
<div className="w-full flex justify-end mb-5">
<FormRenderer.SubmitButton text="Proceed" />
</div>
<div className="flex flex-col gap-2 col-span-3">
<PaymentMethodsRenderer isUpdateFlow />
</div>
</div>
</div>
<FormValuesSpy />
</Form>
}
| 2,348 | 9,659 |
hyperswitch-control-center | src/screens/Connectors/FraudAndRisk/FRMUtils.res | .res | open FRMInfo
open FRMTypes
@val external btoa: string => string = "btoa"
@val external atob: string => string = "atob"
let leadingSpaceStrParser = (~value, ~name as _) => {
let str = value->JSON.Decode.string->Option.getOr("")
str->String.replaceRegExp(%re("/^[\s]+/"), "")->JSON.Encode.string
}
let base64Parse = (~value, ~name as _) => {
value->JSON.Decode.string->Option.getOr("")->btoa->JSON.Encode.string
}
let base64Format = (~value, ~name as _) => {
value->JSON.Decode.string->Option.getOr("")->atob->JSON.Encode.string
}
let toggleDefaultStyle = "mb-2 relative inline-flex flex-shrink-0 h-6 w-12 border-2 rounded-full transition-colors ease-in-out duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-opacity-75 items-center"
let accordionDefaultStyle = "border pointer-events-none inline-block h-3 w-3 rounded-full bg-white dark:bg-white shadow-lg transform ring-0 transition ease-in-out duration-200"
let size = "w-14 h-14"
let generateInitialValuesDict = (~selectedFRMName, ~isLiveMode) => {
let frmAccountDetailsDict =
[
("auth_type", selectedFRMName->getFRMAuthType->JSON.Encode.string),
]->LogicUtils.getJsonFromArrayOfJson
[
("connector_name", selectedFRMName->ConnectorUtils.getConnectorNameString->JSON.Encode.string),
("connector_type", "payment_vas"->JSON.Encode.string),
("disabled", false->JSON.Encode.bool),
("test_mode", !isLiveMode->JSON.Encode.bool),
("connector_account_details", frmAccountDetailsDict),
("frm_configs", []->JSON.Encode.array),
]
->Dict.fromArray
->JSON.Encode.object
}
let parseFRMConfig = json => {
json->JSON.Decode.array->Option.getOr([])->ConnectorInterfaceUtils.convertFRMConfigJsonToObj
}
let getPaymentMethod = paymentMethod => {
open LogicUtils
let paymentMethodDict = paymentMethod->getDictFromJsonObject
let paymentMethodTypeArr = paymentMethodDict->getArrayFromDict("payment_method_types", [])
let pmTypesArr =
paymentMethodTypeArr->Array.map(item =>
item->getDictFromJsonObject->getString("payment_method_type", "")
)
(paymentMethodDict->getString("payment_method", ""), pmTypesArr->getUniqueArray)
}
let parseConnectorConfig = dict => {
open LogicUtils
let pmDict = Dict.make()
let connectorPaymentMethods = dict->getArrayFromDict("payment_methods_enabled", [])
connectorPaymentMethods->Array.forEach(item => {
let (pmName, pmTypes) = item->getPaymentMethod
pmDict->Dict.set(pmName, pmTypes)
})
(getString(dict, "connector_name", ""), pmDict)
}
let updatePaymentMethodsDict = (prevPaymentMethodsDict, pmName, currentPmTypes) => {
open LogicUtils
switch prevPaymentMethodsDict->Dict.get(pmName) {
| Some(prevPmTypes) => {
let pmTypesArr = prevPmTypes->Array.concat(currentPmTypes)
prevPaymentMethodsDict->Dict.set(pmName, pmTypesArr->getUniqueArray)
}
| _ => prevPaymentMethodsDict->Dict.set(pmName, currentPmTypes)
}
}
let updateConfigDict = (configDict, connectorName, paymentMethodsDict) => {
switch configDict->Dict.get(connectorName) {
| Some(prevPaymentMethodsDict) =>
paymentMethodsDict
->Dict.keysToArray
->Array.forEach(pmName =>
updatePaymentMethodsDict(
prevPaymentMethodsDict,
pmName,
paymentMethodsDict->Dict.get(pmName)->Option.getOr([]),
)
)
| _ => configDict->Dict.set(connectorName, paymentMethodsDict)
}
}
let getConnectorConfig = connectors => {
let configDict = Dict.make()
connectors->Array.forEach(connector => {
let (connectorName, paymentMethodsDict) = connector->parseConnectorConfig
updateConfigDict(configDict, connectorName, paymentMethodsDict)
})
configDict
}
let filterList = (items, ~removeFromList) => {
open LogicUtils
items->Array.filter(dict => {
let isConnector = dict->getString("connector_type", "") !== "payment_vas"
let isThreedsConnector = dict->getString("connector_type", "") !== "authentication_processor"
switch removeFromList {
| Connector => !isConnector
| FRMPlayer => isConnector
| ThreedsAuthenticator => isThreedsConnector
}
})
}
let createAllOptions = connectorsConfig => {
open ConnectorTypes
connectorsConfig
->Dict.keysToArray
->Array.map(connectorName => {
gateway: connectorName,
payment_methods: [],
})
}
let generateFRMPaymentMethodsConfig = (paymentMethodsDict): array<
ConnectorTypes.frm_payment_method,
> => {
open ConnectorTypes
paymentMethodsDict
->Dict.keysToArray
->Array.map(paymentMethodName => {
{
payment_method: paymentMethodName,
flow: getFlowTypeNameString(PreAuth),
}
})
}
let ignoreFields = json => {
json
->LogicUtils.getDictFromJsonObject
->Dict.toArray
->Array.filter(entry => {
let (key, _val) = entry
!(ignoredField->Array.includes(key))
})
->Dict.fromArray
->JSON.Encode.object
}
| 1,250 | 9,660 |
hyperswitch-control-center | src/screens/Connectors/PMAuthenticationProcessor/PMAuthenticationTypes.res | .res | type steps = ConfigurationFields | Summary | Preview
| 10 | 9,661 |
hyperswitch-control-center | src/screens/Connectors/PMAuthenticationProcessor/PMAuthenticationTableEntity.res | .res | open ConnectorTypes
type colType =
| Name
| TestMode
| Status
| Disabled
| MerchantConnectorId
| ConnectorLabel
let defaultColumns = [Name, MerchantConnectorId, ConnectorLabel, Status, Disabled, TestMode]
let getHeading = colType => {
switch colType {
| Name => Table.makeHeaderInfo(~key="connector_name", ~title="Processor")
| TestMode => Table.makeHeaderInfo(~key="test_mode", ~title="Test Mode")
| Status => Table.makeHeaderInfo(~key="status", ~title="Integration status")
| Disabled => Table.makeHeaderInfo(~key="disabled", ~title="Disabled")
| ConnectorLabel => Table.makeHeaderInfo(~key="connector_label", ~title="Connector Label")
| MerchantConnectorId =>
Table.makeHeaderInfo(~key="merchant_connector_id", ~title="Merchant Connector Id")
}
}
let connectorStatusStyle = connectorStatus =>
switch connectorStatus->String.toLowerCase {
| "active" => "text-green-700"
| _ => "text-grey-800 opacity-50"
}
let getCell = (connector: connectorPayload, colType): Table.cell => {
switch colType {
| Name =>
CustomCell(
<HelperComponents.ConnectorCustomCell
connectorName=connector.connector_name connectorType={PMAuthenticationProcessor}
/>,
"",
)
| TestMode => Text(connector.test_mode ? "True" : "False")
| 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>,
"",
)
| ConnectorLabel => Text(connector.connector_label)
| MerchantConnectorId =>
CustomCell(
<HelperComponents.CopyTextCustomComp
customTextCss="w-36 truncate whitespace-nowrap"
displayValue=Some(connector.merchant_connector_id)
/>,
"",
)
}
}
let comparatorFunction = (connector1: connectorPayload, connector2: connectorPayload) => {
connector1.connector_name->String.localeCompare(connector2.connector_name)
}
let sortPreviouslyConnectedList = arr => {
Array.toSorted(arr, comparatorFunction)
}
let getPreviouslyConnectedList: JSON.t => array<connectorPayload> = json => {
let data = ConnectorInterface.mapJsonArrayToConnectorPayloads(
ConnectorInterface.connectorInterfaceV1,
json,
PMAuthProcessor,
)
data
}
let pmAuthenticationEntity = (path: string, ~authorization: CommonAuthTypes.authorization) => {
EntityType.makeEntity(
~uri=``,
~getObjects=getPreviouslyConnectedList,
~defaultColumns,
~getHeading,
~getCell,
~dataKey="",
~getShowLink={
connec =>
GroupAccessUtils.linkForGetShowLinkViaAccess(
~url=GlobalVars.appendDashboardPath(
~url=`/${path}/${connec.merchant_connector_id}?name=${connec.connector_name}`,
),
~authorization,
)
},
)
}
| 701 | 9,662 |
hyperswitch-control-center | src/screens/Connectors/PMAuthenticationProcessor/PMAuthenticationHome.res | .res | module MenuOption = {
open HeadlessUI
@react.component
let make = (~disableConnector, ~isConnectorDisabled) => {
let showPopUp = PopUpState.useShowPopUp()
let openConfirmationPopUp = _ => {
showPopUp({
popUpType: (Warning, WithIcon),
heading: "Confirm Action?",
description: `You are about to ${isConnectorDisabled
? "Enable"
: "Disable"->String.toLowerCase} this connector. This might impact your desired routing configurations. Please confirm to proceed.`->React.string,
handleConfirm: {
text: "Confirm",
onClick: _ => disableConnector(isConnectorDisabled)->ignore,
},
handleCancel: {text: "Cancel"},
})
}
let connectorStatusAvailableToSwitch = isConnectorDisabled ? "Enable" : "Disable"
<Popover \"as"="div" className="relative inline-block text-left">
{_popoverProps => <>
<Popover.Button> {_ => <Icon name="menu-option" size=28 />} </Popover.Button>
<Popover.Panel className="absolute z-20 right-5 top-4">
{panelProps => {
<div
id="neglectTopbarTheme"
className="relative flex flex-col bg-white py-1 overflow-hidden rounded ring-1 ring-black ring-opacity-5 w-40">
{<>
<Navbar.MenuOption
text={connectorStatusAvailableToSwitch}
onClick={_ => {
panelProps["close"]()
openConfirmationPopUp()
}}
/>
</>}
</div>
}}
</Popover.Panel>
</>}
</Popover>
}
}
@react.component
let make = () => {
open PMAuthenticationTypes
open ConnectorUtils
open APIUtils
open LogicUtils
let getURL = useGetURL()
let showToast = ToastState.useShowToast()
let url = RescriptReactRouter.useUrl()
let updateAPIHook = useUpdateMethod(~showErrorToast=false)
let fetchDetails = useGetMethod()
let updateDetails = useUpdateMethod()
let connectorName = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("name", "")
let connectorID = HSwitchUtils.getConnectorIDFromUrl(url.path->List.toArray, "")
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (initialValues, setInitialValues) = React.useState(_ => Dict.make()->JSON.Encode.object)
let (currentStep, setCurrentStep) = React.useState(_ => ConfigurationFields)
let fetchConnectorListResponse = ConnectorListHook.useFetchConnectorList()
let activeBusinessProfile =
Recoil.useRecoilValueFromAtom(
HyperswitchAtom.businessProfilesAtom,
)->MerchantAccountUtils.getValueFromBusinessProfile
let isUpdateFlow = switch url.path->HSwitchUtils.urlPath {
| list{"pm-authentication-processor", "new"} => false
| _ => true
}
let connectorInfo = ConnectorInterface.mapDictToConnectorPayload(
ConnectorInterface.connectorInterfaceV1,
initialValues->LogicUtils.getDictFromJsonObject,
)
let isConnectorDisabled = connectorInfo.disabled
let disableConnector = async isConnectorDisabled => {
try {
let connectorID = connectorInfo.merchant_connector_id
let disableConnectorPayload = ConnectorUtils.getDisableConnectorPayload(
connectorInfo.connector_type->ConnectorUtils.connectorTypeTypedValueToStringMapper,
isConnectorDisabled,
)
let url = getURL(~entityName=V1(CONNECTOR), ~methodType=Post, ~id=Some(connectorID))
let _ = await updateDetails(url, disableConnectorPayload->JSON.Encode.object, Post)
showToast(~message="Successfully Saved the Changes", ~toastType=ToastSuccess)
RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/pm-authentication-processor"))
} catch {
| Exn.Error(_) => showToast(~message="Failed to Disable connector!", ~toastType=ToastError)
}
}
let getConnectorDetails = async () => {
try {
let connectorUrl = getURL(~entityName=V1(CONNECTOR), ~methodType=Get, ~id=Some(connectorID))
let json = await fetchDetails(connectorUrl)
setInitialValues(_ => json)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to update!")
Exn.raiseError(err)
}
| _ => Exn.raiseError("Something went wrong")
}
}
let getDetails = async () => {
try {
setScreenState(_ => Loading)
let _ = await Window.connectorWasmInit()
if isUpdateFlow {
await getConnectorDetails()
setCurrentStep(_ => Preview)
} else {
setCurrentStep(_ => ConfigurationFields)
}
setScreenState(_ => Success)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong")
setScreenState(_ => Error(err))
}
| _ => setScreenState(_ => Error("Something went wrong"))
}
}
let connectorDetails = React.useMemo(() => {
try {
if connectorName->LogicUtils.isNonEmptyString {
let dict = Window.getPMAuthenticationProcessorConfig(connectorName)
dict
} else {
Dict.make()->JSON.Encode.object
}
} catch {
| Exn.Error(e) => {
Js.log2("FAILED TO LOAD CONNECTOR CONFIG", e)
let err = Exn.message(e)->Option.getOr("Something went wrong")
setScreenState(_ => PageLoaderWrapper.Error(err))
Dict.make()->JSON.Encode.object
}
}
}, [connectorName])
let (
bodyType,
connectorAccountFields,
connectorMetaDataFields,
_,
connectorWebHookDetails,
connectorLabelDetailField,
connectorAdditionalMerchantData,
) = getConnectorFields(connectorDetails)
React.useEffect(() => {
let initialValuesToDict = initialValues->LogicUtils.getDictFromJsonObject
if !isUpdateFlow {
initialValuesToDict->Dict.set(
"profile_id",
activeBusinessProfile.profile_id->JSON.Encode.string,
)
initialValuesToDict->Dict.set(
"connector_label",
`${connectorName}_${activeBusinessProfile.profile_name}`->JSON.Encode.string,
)
}
None
}, [connectorName, activeBusinessProfile.profile_id])
React.useEffect(() => {
if connectorName->LogicUtils.isNonEmptyString {
getDetails()->ignore
} else {
setScreenState(_ => Error("Connector name not found"))
}
None
}, [connectorName])
let onSubmit = async (values, _) => {
try {
let body =
generateInitialValuesDict(
~values,
~connector=connectorName,
~bodyType,
~isLiveMode={false},
~connectorType=ConnectorTypes.PMAuthenticationProcessor,
)->ignoreFields(connectorID, connectorIgnoredField)
let connectorUrl = getURL(
~entityName=V1(CONNECTOR),
~methodType=Post,
~id=isUpdateFlow ? Some(connectorID) : None,
)
let response = await updateAPIHook(connectorUrl, body, Post)
let _ = await fetchConnectorListResponse()
setInitialValues(_ => response)
setCurrentStep(_ => Summary)
} 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)
setCurrentStep(_ => ConfigurationFields)
} else {
showToast(~message=errorMessage, ~toastType=ToastError)
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
}
Nullable.null
}
let validateMandatoryField = values => {
let errors = Dict.make()
let valuesFlattenJson = values->JsonFlattenUtils.flattenObject(true)
validateConnectorRequiredFields(
connectorName->getConnectorNameTypeFromString(~connectorType=PMAuthenticationProcessor),
valuesFlattenJson,
connectorAccountFields,
connectorMetaDataFields,
connectorWebHookDetails,
connectorLabelDetailField,
errors->JSON.Encode.object,
)
}
let connectorStatusStyle = connectorStatus =>
switch connectorStatus {
| true => "border bg-red-600 bg-opacity-40 border-red-400 text-red-500"
| false => "border bg-green-600 bg-opacity-40 border-green-700 text-green-700"
}
let summaryPageButton = switch currentStep {
| Preview =>
<div className="flex gap-6 items-center">
<div
className={`px-4 py-2 rounded-full w-fit font-medium text-sm !text-black ${isConnectorDisabled->connectorStatusStyle}`}>
{(isConnectorDisabled ? "DISABLED" : "ENABLED")->React.string}
</div>
<MenuOption disableConnector isConnectorDisabled />
</div>
| _ =>
<Button
text="Done"
buttonType=Primary
onClick={_ =>
RescriptReactRouter.push(
GlobalVars.appendDashboardPath(~url="/pm-authentication-processor"),
)}
/>
}
<PageLoaderWrapper screenState>
<div className="flex flex-col gap-10 overflow-scroll h-full w-full">
<BreadCrumbNavigation
path=[
connectorID === "new"
? {
title: "PM Authentication Processor",
link: "/pm-authentication-processor",
warning: `You have not yet completed configuring your ${connectorName->LogicUtils.snakeToTitle} connector. Are you sure you want to go back?`,
}
: {
title: "PM Authentication Porcessor",
link: "/pm-authentication-processor",
},
]
currentPageTitle={connectorName->ConnectorUtils.getDisplayNameForConnector(
~connectorType=PMAuthenticationProcessor,
)}
cursorStyle="cursor-pointer"
/>
<div
className="bg-white rounded-lg border h-3/4 overflow-scroll shadow-boxShadowMultiple show-scrollbar">
{switch currentStep {
| ConfigurationFields =>
<Form initialValues={initialValues} onSubmit validate={validateMandatoryField}>
<ConnectorAccountDetailsHelper.ConnectorHeaderWrapper
connector=connectorName
connectorType={PMAuthenticationProcessor}
headerButton={<AddDataAttributes
attributes=[("data-testid", "connector-submit-button")]>
<FormRenderer.SubmitButton loadingText="Processing..." text="Connect and Proceed" />
</AddDataAttributes>}>
<div className="flex flex-col gap-2 p-2 md:px-10">
<ConnectorAccountDetailsHelper.BusinessProfileRender
isUpdateFlow selectedConnector={connectorName}
/>
</div>
<div className={`flex flex-col gap-2 p-2 md:p-10`}>
<div className="grid grid-cols-2 flex-1">
<ConnectorAccountDetailsHelper.ConnectorConfigurationFields
connector={connectorName->getConnectorNameTypeFromString(
~connectorType=PMAuthenticationProcessor,
)}
connectorAccountFields
selectedConnector={connectorName
->getConnectorNameTypeFromString(~connectorType=PMAuthenticationProcessor)
->getConnectorInfo}
connectorMetaDataFields
connectorWebHookDetails
connectorLabelDetailField
connectorAdditionalMerchantData
/>
</div>
</div>
</ConnectorAccountDetailsHelper.ConnectorHeaderWrapper>
<FormValuesSpy />
</Form>
| Summary | Preview =>
<ConnectorAccountDetailsHelper.ConnectorHeaderWrapper
connector=connectorName
connectorType={PMAuthenticationProcessor}
headerButton={summaryPageButton}>
<ConnectorPreview.ConnectorSummaryGrid
connectorInfo
connector=connectorName
getConnectorDetails={Some(getConnectorDetails)}
setCurrentStep={_ => ()}
/>
<div />
</ConnectorAccountDetailsHelper.ConnectorHeaderWrapper>
}}
</div>
</div>
</PageLoaderWrapper>
}
| 2,679 | 9,663 |
hyperswitch-control-center | src/screens/Connectors/PMAuthenticationProcessor/PMAuthenticationConnectorList.res | .res | @react.component
let make = () => {
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Success)
let (configuredConnectors, setConfiguredConnectors) = React.useState(_ => [])
let (offset, setOffset) = React.useState(_ => 0)
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
let (searchText, setSearchText) = React.useState(_ => "")
let (filteredConnectorData, setFilteredConnectorData) = React.useState(_ => [])
let connectorList = ConnectorInterface.useConnectorArrayMapper(
~interface=ConnectorInterface.connectorInterfaceV1,
~retainInList=PMAuthProcessor,
)
let filterLogic = ReactDebounce.useDebounced(ob => {
open LogicUtils
let (searchText, arr) = ob
let filteredList = if searchText->isNonEmptyString {
arr->Array.filter((obj: Nullable.t<ConnectorTypes.connectorPayload>) => {
switch Nullable.toOption(obj) {
| Some(obj) =>
isContainingStringLowercase(obj.connector_name, searchText) ||
isContainingStringLowercase(obj.merchant_connector_id, searchText) ||
isContainingStringLowercase(obj.connector_label, searchText)
| None => false
}
})
} else {
arr
}
setFilteredConnectorData(_ => filteredList)
}, ~wait=200)
let getConnectorList = async _ => {
try {
ConnectorUtils.sortByDisableField(connectorList, connectorPayload =>
connectorPayload.disabled
)
setConfiguredConnectors(_ => connectorList)
setFilteredConnectorData(_ => connectorList->Array.map(Nullable.make))
setScreenState(_ => Success)
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Error("Failed to fetch"))
}
}
React.useEffect(() => {
getConnectorList()->ignore
None
}, [])
<div>
<PageUtils.PageHeading
title={"PM Authentication Processor"}
subTitle={"Connect and configure open banking providers to verify customer bank accounts"}
/>
<PageLoaderWrapper screenState>
<div className="flex flex-col gap-10">
<RenderIf condition={configuredConnectors->Array.length > 0}>
<LoadedTable
title="Connected Processors"
actualData={filteredConnectorData}
totalResults={filteredConnectorData->Array.length}
resultsPerPage=20
entity={PMAuthenticationTableEntity.pmAuthenticationEntity(
`pm-authentication-processor`,
~authorization=userHasAccess(~groupAccess=ConnectorsManage),
)}
filters={<TableSearchFilter
data={configuredConnectors->Array.map(Nullable.make)}
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
/>}
offset
setOffset
currrentFetchCount={configuredConnectors->Array.map(Nullable.make)->Array.length}
collapseTableRow=false
/>
</RenderIf>
<ProcessorCards
configuredConnectors={ConnectorInterface.mapConnectorPayloadToConnectorType(
ConnectorInterface.connectorInterfaceV1,
ConnectorTypes.PMAuthenticationProcessor,
configuredConnectors,
)}
connectorsAvailableForIntegration=ConnectorUtils.pmAuthenticationConnectorList
urlPrefix="pm-authentication-processor/new"
connectorType=ConnectorTypes.PMAuthenticationProcessor
/>
</div>
</PageLoaderWrapper>
</div>
}
| 774 | 9,664 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorAccountDetailsHelper.res | .res | let connectorsWithIntegrationSteps: array<ConnectorTypes.connectorTypes> = [
Processors(ADYEN),
Processors(CHECKOUT),
Processors(STRIPE),
Processors(PAYPAL),
]
module MultiConfigInp = {
@react.component
let make = (~label, ~fieldsArray: array<ReactFinalForm.fieldRenderProps>) => {
let enabledList = (fieldsArray[0]->Option.getOr(ReactFinalForm.fakeFieldRenderProps)).input
let valueField = (fieldsArray[1]->Option.getOr(ReactFinalForm.fakeFieldRenderProps)).input
let input: ReactFinalForm.fieldRenderPropsInput = {
name: "string",
onBlur: _ => (),
onChange: ev => {
let value = ev->Identity.formReactEventToArrayOfString
valueField.onChange(value->Identity.anyTypeToReactEvent)
enabledList.onChange(value->Identity.anyTypeToReactEvent)
},
onFocus: _ => (),
value: enabledList.value,
checked: true,
}
<TextInput input placeholder={`Enter ${label->LogicUtils.snakeToTitle}`} />
}
}
let renderValueInp = (~label) => (fieldsArray: array<ReactFinalForm.fieldRenderProps>) => {
<MultiConfigInp fieldsArray label />
}
let multiValueInput = (~label, ~fieldName1, ~fieldName2) => {
open FormRenderer
makeMultiInputFieldInfoOld(
~label,
~comboCustomInput=renderValueInp(~label),
~inputFields=[
makeInputFieldInfo(~name=`${fieldName1}`),
makeInputFieldInfo(~name=`${fieldName2}`),
],
(),
)
}
let inputField = (
~name,
~field,
~label,
~connector,
~getPlaceholder,
~checkRequiredFields,
~disabled,
~description,
~toolTipPosition: ToolTip.toolTipPosition=ToolTip.Right,
(),
) =>
FormRenderer.makeFieldInfo(
~label,
~name,
~description,
~toolTipPosition,
~customInput=InputFields.textInput(~isDisabled=disabled),
~placeholder=switch getPlaceholder {
| Some(fun) => fun(label)
| None => `Enter ${label->LogicUtils.snakeToTitle}`
},
~isRequired=switch checkRequiredFields {
| Some(fun) => fun(connector, field)
| None => true
},
)
module ErrorValidation = {
@react.component
let make = (~fieldName, ~validate) => {
open LogicUtils
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let appPrefix = LogicUtils.useUrlPrefix()
let imageStyle = "w-4 h-4 my-auto border-gray-100"
let errorDict = formState.values->validate->getDictFromJsonObject
let {touched} = ReactFinalForm.useField(fieldName).meta
let err = touched ? errorDict->Dict.get(fieldName) : None
<RenderIf condition={err->Option.isSome}>
<div
className={`flex flex-row items-center text-orange-950 dark:text-orange-400 pt-2 text-base font-medium text-start ml-1`}>
<div className="flex mr-2">
<img className=imageStyle src={`${appPrefix}/icons/warning.svg`} alt="warning" />
</div>
{React.string(err->Option.getOr(""->JSON.Encode.string)->getStringFromJson(""))}
</div>
</RenderIf>
}
}
module RenderConnectorInputFields = {
open ConnectorTypes
@react.component
let make = (
~connector: connectorTypes,
~selectedConnector,
~details,
~name,
~keysToIgnore: array<string>=[],
~checkRequiredFields=?,
~getPlaceholder=?,
~isLabelNested=true,
~disabled=false,
~description="",
) => {
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
open ConnectorUtils
open LogicUtils
let keys = details->Dict.keysToArray->Array.filter(ele => !Array.includes(keysToIgnore, ele))
keys
->Array.mapWithIndex((field, i) => {
let label = details->getString(field, "")
let formName = isLabelNested ? `${name}.${field}` : name
<RenderIf condition={label->isNonEmptyString} key={i->Int.toString}>
<AddDataAttributes attributes=[("data-testid", label->titleToSnake->String.toLowerCase)]>
<div key={label}>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={switch (connector, field) {
| (Processors(PAYPAL), "key1") =>
multiValueInput(
~label,
~fieldName1="connector_account_details.key1",
~fieldName2="metadata.paypal_sdk.client_id",
)
| _ =>
inputField(
~name=formName,
~field,
~label,
~connector,
~checkRequiredFields,
~getPlaceholder,
~disabled,
~description,
(),
)
}}
/>
<ErrorValidation
fieldName=formName
validate={validate(
~selectedConnector,
~dict=details,
~fieldName=formName,
~isLiveMode={featureFlagDetails.isLiveMode},
)}
/>
</div>
</AddDataAttributes>
</RenderIf>
})
->React.array
}
}
module CashToCodeSelectBox = {
open ConnectorTypes
@react.component
let make = (
~opts: array<string>,
~dict,
~selectedCashToCodeMthd: cashToCodeMthd,
~connector,
~selectedConnector,
) => {
open LogicUtils
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let p2RegularTextStyle = `${HSwitchUtils.getTextClass((P2, Medium))} text-grey-700 opacity-50`
let (showWalletConfigurationModal, setShowWalletConfigurationModal) = React.useState(_ => false)
let (country, setSelectedCountry) = React.useState(_ => "")
let selectedCountry = country => {
setShowWalletConfigurationModal(_ => !showWalletConfigurationModal)
setSelectedCountry(_ => country)
}
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let isSelected = (country): bool => {
let formValues =
formState.values
->getDictFromJsonObject
->getDictfromDict("connector_account_details")
->getDictfromDict("auth_key_map")
->getDictfromDict(country)
let wasmValues =
dict
->getDictfromDict(country)
->getDictfromDict((selectedCashToCodeMthd: cashToCodeMthd :> string)->String.toLowerCase)
->Dict.keysToArray
wasmValues
->Array.find(ele => formValues->getString(ele, "")->String.length <= 0)
->Option.isNone
}
<div>
{opts
->Array.mapWithIndex((country, index) => {
<div key={index->Int.toString} className="flex items-center gap-2 break-words p-2">
<div onClick={_ => selectedCountry(country)}>
<CheckBoxIcon isSelected={country->isSelected} />
</div>
<p className=p2RegularTextStyle> {React.string(country->snakeToTitle)} </p>
</div>
})
->React.array}
<Modal
modalHeading={`Additional Details to enable`}
headerTextClass={`${textColor.primaryNormal} font-bold text-xl`}
showModal={showWalletConfigurationModal}
setShowModal={setShowWalletConfigurationModal}
paddingClass=""
revealFrom=Reveal.Right
modalClass="w-full p-4 md:w-1/3 !h-full overflow-y-scroll !overflow-x-hidden rounded-none text-jp-gray-900"
childClass={""}>
<div>
<RenderConnectorInputFields
details={dict
->getDictfromDict(country)
->getDictfromDict(
(selectedCashToCodeMthd: cashToCodeMthd :> string)->String.toLowerCase,
)}
name={`connector_account_details.auth_key_map.${country}`}
connector
selectedConnector
/>
<div className="flex flex-col justify-center mt-4">
<Button
text={"Proceed"}
buttonType=Primary
onClick={_ => setShowWalletConfigurationModal(_ => false)}
/>
</div>
</div>
</Modal>
</div>
}
}
module CashToCodeMethods = {
open ConnectorTypes
@react.component
let make = (~connectorAccountFields, ~selectedConnector, ~connector) => {
open ConnectorUtils
let dict = connectorAccountFields->getAuthKeyMapFromConnectorAccountFields
let (selectedCashToCodeMthd, setCashToCodeMthd) = React.useState(_ => #Classic)
let tabs = [#Classic, #Evoucher]
let tabList: array<Tabs.tab> = tabs->Array.map(tab => {
let tab: Tabs.tab = {
title: (tab: cashToCodeMthd :> string),
renderContent: () =>
<CashToCodeSelectBox
opts={dict->Dict.keysToArray}
dict={dict}
selectedCashToCodeMthd
connector
selectedConnector
/>,
}
tab
})
<Tabs
tabs=tabList
disableIndicationArrow=true
showBorder=false
includeMargin=false
lightThemeColor="black"
defaultClasses="font-ibm-plex w-max flex flex-auto flex-row items-center justify-center px-6 font-semibold text-body"
onTitleClick={tabIndex => {
setCashToCodeMthd(_ => tabs->LogicUtils.getValueFromArray(tabIndex, #Classic))
}}
/>
}
}
module ConnectorConfigurationFields = {
open ConnectorTypes
@react.component
let make = (
~connectorAccountFields,
~connector: connectorTypes,
~selectedConnector: integrationFields,
~connectorMetaDataFields,
~connectorWebHookDetails,
~isUpdateFlow=false,
~connectorLabelDetailField,
~connectorAdditionalMerchantData,
) => {
<div className="flex flex-col">
{switch connector {
| Processors(CASHTOCODE) =>
<CashToCodeMethods connectorAccountFields connector selectedConnector />
| _ =>
<RenderConnectorInputFields
details={connectorAccountFields}
name={"connector_account_details"}
getPlaceholder={ConnectorUtils.getPlaceHolder}
connector
selectedConnector
/>
}}
<RenderConnectorInputFields
details={connectorLabelDetailField}
name={"connector_label"}
connector
selectedConnector
isLabelNested=false
description="This is an unique label you can generate and pass in order to identify this connector account on your Hyperswitch dashboard and reports. Eg: if your profile label is 'default', connector label can be 'stripe_default'"
/>
<ConnectorMetaData connectorMetaDataFields />
<ConnectorAdditionalMerchantData connector connectorAdditionalMerchantData />
<RenderConnectorInputFields
details={connectorWebHookDetails}
name={"connector_webhook_details"}
checkRequiredFields={ConnectorUtils.getWebHookRequiredFields}
connector
selectedConnector
/>
</div>
}
}
module BusinessProfileRender = {
@react.component
let make = (~isUpdateFlow: bool, ~selectedConnector) => {
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let {setDashboardPageState} = React.useContext(GlobalProvider.defaultContext)
let businessProfiles = Recoil.useRecoilValueFromAtom(HyperswitchAtom.businessProfilesAtom)
let defaultBusinessProfile = businessProfiles->MerchantAccountUtils.getValueFromBusinessProfile
let connectorLabelOnChange = ReactFinalForm.useField(`connector_label`).input.onChange
let (showModalFromOtherScreen, setShowModalFromOtherScreen) = React.useState(_ => false)
let hereTextStyle = isUpdateFlow
? "text-grey-700 opacity-50 cursor-not-allowed"
: `${textColor.primaryNormal} cursor-pointer`
<>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-black"
field={FormRenderer.makeFieldInfo(
~label="Profile",
~isRequired=true,
~name="profile_id",
~customInput=(~input, ~placeholder as _) =>
InputFields.selectInput(
~deselectDisable=true,
~disableSelect={isUpdateFlow || businessProfiles->HomeUtils.isDefaultBusinessProfile},
~customStyle="max-h-48",
~options={
businessProfiles->MerchantAccountUtils.businessProfileNameDropDownOption
},
~buttonText="Select Profile",
)(
~input={
...input,
onChange: {
ev => {
let profileName = (
businessProfiles
->Array.find((ele: HSwitchSettingTypes.profileEntity) =>
ele.profile_id === ev->Identity.formReactEventToString
)
->Option.getOr(defaultBusinessProfile)
).profile_name
connectorLabelOnChange(
`${selectedConnector}_${profileName}`->Identity.stringToFormReactEvent,
)
input.onChange(ev)
}
},
},
~placeholder="",
),
)}
/>
<RenderIf condition={!isUpdateFlow}>
<div className="text-gray-400 text-sm mt-3">
<span> {"Manage your list of profiles."->React.string} </span>
<span
className={`ml-1 ${hereTextStyle}`}
onClick={_ => {
setDashboardPageState(_ => #HOME)
RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/business-profiles"))
}}>
{React.string("here.")}
</span>
</div>
</RenderIf>
<BusinessProfile isFromSettings=false showModalFromOtherScreen setShowModalFromOtherScreen />
</>
}
}
module VerifyConnectorModal = {
@react.component
let make = (
~showVerifyModal,
~setShowVerifyModal,
~connector,
~verifyErrorMessage,
~suggestedActionExists,
~suggestedAction,
~setVerifyDone,
) => {
<Modal
showModal={showVerifyModal}
setShowModal={setShowVerifyModal}
modalClass="w-full md:w-5/12 mx-auto top-1/3 relative"
childClass="p-0 m-0 -mt-8"
customHeight="border-0 h-fit"
showCloseIcon=false
headingClass="h-2 bg-orange-960 rounded-t-xl"
onCloseClickCustomFun={_ => {
setVerifyDone(_ => NoAttempt)
setShowVerifyModal(_ => false)
}}>
<div>
<div className="flex flex-col mb-2 p-2 m-2">
<div className="flex p-3">
<img
className="h-12 my-auto border-gray-100 w-fit mt-0"
src={`/icons/warning.svg`}
alt="warning"
/>
<div className="text-jp-gray-900">
<div
className="font-semibold ml-4 text-xl px-2 dark:text-jp-gray-text_darktheme dark:text-opacity-75">
{"Are you sure you want to proceed?"->React.string}
</div>
<div
className="whitespace-pre-line break-all flex flex-col gap-1 p-2 ml-4 text-base dark:text-jp-gray-text_darktheme dark:text-opacity-50 font-medium leading-7 opacity-50">
{`Received the following error from ${connector->LogicUtils.snakeToTitle}:`->React.string}
</div>
<div
className="whitespace-pre-line break-all flex flex-col gap-1 p-4 ml-6 text-base dark:text-jp-gray-text_darktheme dark:text-opacity-50 bg-red-100 rounded-md font-semibold">
{`${verifyErrorMessage->Option.getOr("")}`->React.string}
</div>
<RenderIf condition={suggestedActionExists}> {suggestedAction} </RenderIf>
</div>
</div>
<div className="flex flex-row justify-end gap-5 mt-4 mb-2 p-3">
<FormRenderer.SubmitButton
buttonType={Button.Secondary} loadingText="Processing..." text="Proceed Anyway"
/>
<Button
text="Cancel"
onClick={_ => {
setVerifyDone(_ => ConnectorTypes.NoAttempt)
setShowVerifyModal(_ => false)
}}
buttonType={Primary}
buttonSize={Small}
/>
</div>
</div>
</div>
</Modal>
}
}
// Wraps the component with Connector Icon + ConnectorName + Integration Steps Modal
module ConnectorHeaderWrapper = {
@react.component
let make = (
~children,
~headerButton,
~connector,
~handleShowModal=?,
~conditionForIntegrationSteps=true,
~connectorType=ConnectorTypes.Processor,
) => {
open ConnectorUtils
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let connectorNameFromType = connector->getConnectorNameTypeFromString
let setShowModalFunction = switch handleShowModal {
| Some(func) => func
| _ => _ => ()
}
<>
<div className="flex items-center justify-between border-b p-2 md:px-10 md:py-6">
<div className="flex gap-2 items-center">
<GatewayIcon gateway={connector->String.toUpperCase} />
<h2 className="text-xl font-semibold">
{connector->getDisplayNameForConnector(~connectorType)->React.string}
</h2>
</div>
<div className="flex flex-row mt-6 md:mt-0 md:justify-self-end h-min">
<RenderIf
condition={connectorsWithIntegrationSteps->Array.includes(connectorNameFromType) &&
conditionForIntegrationSteps}>
<a
className={`cursor-pointer px-4 py-3 flex text-sm ${textColor.primaryNormal} items-center mx-4`}
target="_blank"
onClick={_ => setShowModalFunction()}>
{React.string("View integration steps")}
<Icon name="external-link-alt" size=14 className="ml-2" />
</a>
</RenderIf>
{headerButton}
</div>
</div>
<RenderIf
condition={switch connectorNameFromType {
| Processors(BRAINTREE) => true
| _ => false
}}>
<HSwitchUtils.AlertBanner
bannerText="Disclaimer: Please ensure the payment currency matches the Braintree-configured currency for the given Merchant Account ID."
bannerType=Warning
/>
</RenderIf>
{children}
</>
}
}
| 4,195 | 9,665 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorPreview.res | .res | module InfoField = {
@react.component
let make = (~render, ~label) => {
let str = render->Option.getOr("")
<RenderIf condition={str->LogicUtils.isNonEmptyString}>
<div>
<h2 className="text-medium font-semibold"> {label->React.string} </h2>
<h3 className="text-base text-grey-700 opacity-70 break-all overflow-scroll font-semibold">
{str->React.string}
</h3>
</div>
</RenderIf>
}
}
module KeyAndCopyArea = {
@react.component
let make = (~copyValue) => {
let showToast = ToastState.useShowToast()
<div className="flex flex-col md:flex-row items-center">
<p
className="text-base text-grey-700 opacity-70 break-all overflow-scroll font-semibold w-89.5-per">
{copyValue->React.string}
</p>
<div
className="cursor-pointer"
onClick={_ => {
Clipboard.writeText(copyValue)
showToast(~message="Copied to Clipboard!", ~toastType=ToastSuccess)
}}>
<Icon name="nd-copy" className="cursor-pointer" />
</div>
</div>
}
}
module DeleteConnectorMenu = {
@react.component
let make = (~pageName="connector", ~connectorInfo: ConnectorTypes.connectorPayload) => {
open APIUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let deleteConnector = async () => {
try {
let connectorID = connectorInfo.merchant_connector_id
let url = getURL(~entityName=V1(CONNECTOR), ~methodType=Post, ~id=Some(connectorID))
let _ = await updateDetails(url, Dict.make()->JSON.Encode.object, Delete)
RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/connectors"))
} catch {
| _ => ()
}
}
let showPopUp = PopUpState.useShowPopUp()
let openConfirmationPopUp = _ => {
showPopUp({
popUpType: (Warning, WithIcon),
heading: "Confirm Action ? ",
description: `You are about to Delete this connector. This might impact your desired routing configurations. Please confirm to proceed.`->React.string,
handleConfirm: {
text: "Confirm",
onClick: _ => deleteConnector()->ignore,
},
handleCancel: {text: "Cancel"},
})
}
<AddDataAttributes attributes=[("data-testid", "delete-button"->String.toLowerCase)]>
<div>
<Button text="Delete" onClick={_ => openConfirmationPopUp()} />
</div>
</AddDataAttributes>
}
}
module MenuOption = {
open HeadlessUI
@react.component
let make = (
~updateStepValue=ConnectorTypes.IntegFields,
~disableConnector,
~isConnectorDisabled,
~pageName="connector",
) => {
let showPopUp = PopUpState.useShowPopUp()
let openConfirmationPopUp = _ => {
showPopUp({
popUpType: (Warning, WithIcon),
heading: "Confirm Action ? ",
description: `You are about to ${isConnectorDisabled
? "Enable"
: "Disable"->String.toLowerCase} this connector. This might impact your desired routing configurations. Please confirm to proceed.`->React.string,
handleConfirm: {
text: "Confirm",
onClick: _ => disableConnector(isConnectorDisabled)->ignore,
},
handleCancel: {text: "Cancel"},
})
}
let connectorStatusAvailableToSwitch = isConnectorDisabled ? "Enable" : "Disable"
<Popover \"as"="div" className="relative inline-block text-left">
{_popoverProps => <>
<Popover.Button> {_ => <Icon name="menu-option" size=28 />} </Popover.Button>
<Popover.Panel className="absolute z-20 right-5 top-4">
{panelProps => {
<div
id="neglectTopbarTheme"
className="relative flex flex-col bg-white py-1 overflow-hidden rounded ring-1 ring-black ring-opacity-5 w-40">
{<>
<Navbar.MenuOption
text={connectorStatusAvailableToSwitch}
onClick={_ => {
panelProps["close"]()
openConfirmationPopUp()
}}
/>
</>}
</div>
}}
</Popover.Panel>
</>}
</Popover>
}
}
module ConnectorSummaryGrid = {
open CommonAuthHooks
@react.component
let make = (
~connectorInfo: ConnectorTypes.connectorPayload,
~connector,
~setCurrentStep,
~updateStepValue=None,
~getConnectorDetails=None,
) => {
open ConnectorUtils
let url = RescriptReactRouter.useUrl()
let mixpanelEvent = MixpanelHook.useSendEvent()
let businessProfiles = HyperswitchAtom.businessProfilesAtom->Recoil.useRecoilValueFromAtom
let defaultBusinessProfile = businessProfiles->MerchantAccountUtils.getValueFromBusinessProfile
let currentProfileName =
businessProfiles
->Array.find((ele: HSwitchSettingTypes.profileEntity) =>
ele.profile_id === connectorInfo.profile_id
)
->Option.getOr(defaultBusinessProfile)
let {merchantId} = useCommonAuthInfo()->Option.getOr(defaultAuthInfo)
let copyValueOfWebhookEndpoint = getWebhooksUrl(
~connectorName={connectorInfo.merchant_connector_id},
~merchantId,
)
let (processorType, _) =
connectorInfo.connector_type
->connectorTypeTypedValueToStringMapper
->connectorTypeTuple
let {connector_name: connectorName} = connectorInfo
let connectorDetails = 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
}
dict
} else {
JSON.Encode.null
}
} catch {
| Exn.Error(e) => {
Js.log2("FAILED TO LOAD CONNECTOR CONFIG", e)
let _ = Exn.message(e)->Option.getOr("Something went wrong")
JSON.Encode.null
}
}
}, [connectorInfo.merchant_connector_id])
let (_, connectorAccountFields, _, _, _, _, _) = getConnectorFields(connectorDetails)
let isUpdateFlow = switch url.path->HSwitchUtils.urlPath {
| list{_, "new"} => false
| _ => true
}
<>
<div className="grid grid-cols-4 border-b md:px-10 py-8">
<h4 className="text-lg font-semibold"> {"Integration status"->React.string} </h4>
<AddDataAttributes attributes=[("data-testid", "connector_status"->String.toLowerCase)]>
<div
className={`text-black font-semibold text-sm ${connectorInfo.status->ConnectorTableUtils.connectorStatusStyle}`}>
{connectorInfo.status->String.toUpperCase->React.string}
</div>
</AddDataAttributes>
</div>
<div className="grid grid-cols-4 border-b md:px-10 py-8">
<div className="flex items-start">
<h4 className="text-lg font-semibold"> {"Webhook Endpoint"->React.string} </h4>
<ToolTip
height=""
description="Configure this endpoint in the processors dashboard under webhook settings for us to receive events from the processor"
toolTipFor={<Icon name="tooltip_info" className={`mt-1 ml-1`} />}
toolTipPosition=Top
tooltipWidthClass="w-fit"
/>
</div>
<div className="col-span-3">
<KeyAndCopyArea copyValue={copyValueOfWebhookEndpoint} />
</div>
</div>
<div className="grid grid-cols-4 border-b md:px-10 py-8">
<h4 className="text-lg font-semibold"> {"Profile"->React.string} </h4>
<div className="col-span-3 font-semibold text-base text-grey-700 opacity-70">
{`${currentProfileName.profile_name} - ${connectorInfo.profile_id}`->React.string}
</div>
</div>
<div className="grid grid-cols-4 border-b md:px-10">
<div className="flex items-start">
<h4 className="text-lg font-semibold py-8"> {"Credentials"->React.string} </h4>
</div>
<div className="flex flex-col gap-6 col-span-3">
<div className="flex gap-12">
<div className="flex flex-col gap-6 w-5/6 py-8">
<ConnectorPreviewHelper.PreviewCreds connectorAccountFields connectorInfo />
</div>
<RenderIf condition={isUpdateFlow}>
<ConnectorUpdateAuthCreds connectorInfo getConnectorDetails />
</RenderIf>
</div>
<RenderIf
condition={connectorInfo.connector_name->getConnectorNameTypeFromString ==
Processors(FIUU)}>
<div
className="flex border items-start bg-blue-800 border-blue-810 text-sm rounded-md gap-2 px-4 py-3">
<Icon name="info-vacent" size=18 />
<div>
<p className="mb-3">
{"To ensure mandates work correctly with Fiuu, please verify that the Source Verification Key for webhooks is set accurately in your configuration. Without the correct Source Verification Key, mandates may not function as expected."->React.string}
</p>
<p>
{"Please review your webhook settings and confirm that the Source Verification Key is properly configured to avoid any integration issues."->React.string}
</p>
</div>
</div>
</RenderIf>
</div>
<div />
</div>
{switch updateStepValue {
| Some(state) =>
<div className="grid grid-cols-4 border-b md:px-10 py-8">
<div className="flex items-start">
<h4 className="text-lg font-semibold"> {"PMTs"->React.string} </h4>
</div>
<div className="flex flex-col gap-6 col-span-3">
<div className="flex gap-12">
<div className="flex flex-col gap-6 col-span-3 w-5/6">
{connectorInfo.payment_methods_enabled
->Array.mapWithIndex((field, index) => {
<InfoField
key={index->Int.toString}
label={field.payment_method->LogicUtils.snakeToTitle}
render={Some(
field.payment_method_types
->Array.map(item => item.payment_method_type->LogicUtils.snakeToTitle)
->Array.reduce([], (acc, curr) => {
if !(acc->Array.includes(curr)) {
acc->Array.push(curr)
}
acc
})
->Array.joinWith(", "),
)}
/>
})
->React.array}
</div>
<RenderIf condition={isUpdateFlow}>
<div
className="cursor-pointer"
onClick={_ => {
mixpanelEvent(~eventName=`processor_update_payment_methods_${connector}`)
setCurrentStep(_ => state)
}}>
<ToolTip
height=""
description={`Update the ${connector} payment methods`}
toolTipFor={<Icon size=18 name="edit" className={` ml-2`} />}
toolTipPosition=Top
tooltipWidthClass="w-fit"
/>
</div>
</RenderIf>
</div>
<div
className="flex border items-start bg-blue-800 border-blue-810 text-sm rounded-md gap-2 px-4 py-3">
<Icon name="info-vacent" size=18 />
<p>
{"Improve conversion rate by conditionally managing PMTs visibility on checkout . Visit Settings >"->React.string}
<a
onClick={_ =>
RescriptReactRouter.push(
GlobalVars.appendDashboardPath(~url="/configure-pmts"),
)}
target="_blank"
className="text-primary underline cursor-pointer">
{"Configure PMTs at Checkout"->React.string}
</a>
</p>
</div>
</div>
</div>
| None => React.null
}}
</>
}
}
@react.component
let make = (
~connectorInfo,
~currentStep: ConnectorTypes.steps,
~setCurrentStep,
~isUpdateFlow,
~showMenuOption=true,
~setInitialValues,
~getPayPalStatus,
~getConnectorDetails=None,
) => {
open APIUtils
open ConnectorUtils
let {feedback, paypalAutomaticFlow} =
HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let showToast = ToastState.useShowToast()
let mixpanelEvent = MixpanelHook.useSendEvent()
let fetchConnectorListResponse = ConnectorListHook.useFetchConnectorList()
let connector = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("name", "")
let {setShowFeedbackModal} = React.useContext(GlobalProvider.defaultContext)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Success)
let connectorInfoDict = connectorInfo->LogicUtils.getDictFromJsonObject
let connectorInfo = ConnectorInterface.mapDictToConnectorPayload(
ConnectorInterface.connectorInterfaceV1,
connectorInfoDict,
)
let connectorCount =
ConnectorInterface.useConnectorArrayMapper(
~interface=ConnectorInterface.connectorInterfaceV1,
)->Array.length
let isFeedbackModalToBeOpen =
feedback && !isUpdateFlow && connectorCount <= HSwitchUtils.feedbackModalOpenCountForConnectors
let isConnectorDisabled = connectorInfo.disabled
let disableConnector = async isConnectorDisabled => {
try {
let connectorID = connectorInfo.merchant_connector_id
let disableConnectorPayload = getDisableConnectorPayload(
connectorInfo.connector_type->connectorTypeTypedValueToStringMapper,
isConnectorDisabled,
)
let url = getURL(~entityName=V1(CONNECTOR), ~methodType=Post, ~id=Some(connectorID))
let res = await updateDetails(url, disableConnectorPayload->JSON.Encode.object, Post)
fetchConnectorListResponse()->ignore
setInitialValues(_ => res)
showToast(~message=`Successfully Saved the Changes`, ~toastType=ToastSuccess)
} catch {
| Exn.Error(_) => showToast(~message=`Failed to Disable connector!`, ~toastType=ToastError)
}
}
let connectorStatusStyle = connectorStatus =>
switch connectorStatus {
| false => "border bg-green-600 bg-opacity-40 border-green-700 text-green-700"
| _ => "border bg-red-600 bg-opacity-40 border-red-400 text-red-500"
}
let mixpanelEventName = isUpdateFlow ? "processor_step3_onUpdate" : "processor_step3"
<PageLoaderWrapper screenState>
<div>
<div className="flex justify-between border-b p-2 md:px-10 md:py-6">
<div className="flex gap-2 items-center">
<GatewayIcon
gateway={connectorInfo.connector_name->String.toUpperCase} className="w-14 h-14"
/>
<h2 className="text-xl font-semibold">
{connectorInfo.connector_name->getDisplayNameForConnector->React.string}
</h2>
</div>
<div className="self-center">
{switch (
currentStep,
connector->getConnectorNameTypeFromString,
connectorInfo.status,
paypalAutomaticFlow,
) {
| (Preview, Processors(PAYPAL), "inactive", true) =>
<Button text="Sync" buttonType={Primary} onClick={_ => getPayPalStatus()->ignore} />
| (Preview, _, _, _) =>
<div className="flex gap-6 items-center">
<div
className={`px-4 py-2 rounded-full w-fit font-medium text-sm !text-black ${isConnectorDisabled->connectorStatusStyle}`}>
{(isConnectorDisabled ? "DISABLED" : "ENABLED")->React.string}
</div>
<RenderIf condition={showMenuOption}>
{switch (connector->getConnectorNameTypeFromString, paypalAutomaticFlow) {
| (Processors(PAYPAL), true) =>
<MenuOptionForPayPal
setCurrentStep
disableConnector
isConnectorDisabled
updateStepValue={ConnectorTypes.PaymentMethods}
connectorInfoDict
setScreenState
isUpdateFlow
setInitialValues
/>
| (_, _) => <MenuOption disableConnector isConnectorDisabled />
}}
</RenderIf>
</div>
| _ =>
<Button
onClick={_ => {
mixpanelEvent(~eventName=mixpanelEventName)
if isFeedbackModalToBeOpen {
setShowFeedbackModal(_ => true)
}
RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/connectors"))
}}
text="Done"
buttonType={Primary}
/>
}}
</div>
</div>
<ConnectorSummaryGrid
connectorInfo
connector
setCurrentStep
updateStepValue={Some(ConnectorTypes.PaymentMethods)}
getConnectorDetails
/>
</div>
</PageLoaderWrapper>
}
| 3,922 | 9,666 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorList.res | .res | @react.component
let make = () => {
open ConnectorUtils
let {showFeedbackModal, setShowFeedbackModal} = React.useContext(GlobalProvider.defaultContext)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (configuredConnectors, setConfiguredConnectors) = React.useState(_ => [])
let (previouslyConnectedData, setPreviouslyConnectedData) = React.useState(_ => [])
let (filteredConnectorData, setFilteredConnectorData) = React.useState(_ => [])
let (offset, setOffset) = React.useState(_ => 0)
let (searchText, setSearchText) = React.useState(_ => "")
let (processorModal, setProcessorModal) = React.useState(_ => false)
let connectorsList = ConnectorInterface.useConnectorArrayMapper(
~interface=ConnectorInterface.connectorInterfaceV1,
~retainInList=PaymentProcessor,
)
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let textStyle = HSwitchUtils.getTextClass((H2, Optional))
let subtextStyle = `${HSwitchUtils.getTextClass((P1, Regular))} text-grey-700 opacity-50`
let getConnectorListAndUpdateState = async () => {
try {
connectorsList->Array.reverse
sortByDisableField(connectorsList, connectorPayload => connectorPayload.disabled)
setFilteredConnectorData(_ => connectorsList->Array.map(Nullable.make))
setPreviouslyConnectedData(_ => connectorsList->Array.map(Nullable.make))
let list = ConnectorInterface.mapConnectorPayloadToConnectorType(
ConnectorInterface.connectorInterfaceV1,
ConnectorTypes.Processor,
connectorsList,
)
setConfiguredConnectors(_ => list)
setScreenState(_ => Success)
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Error("Failed to fetch"))
}
}
React.useEffect(() => {
getConnectorListAndUpdateState()->ignore
None
}, [])
let filterLogic = ReactDebounce.useDebounced(ob => {
open LogicUtils
let (searchText, arr) = ob
let filteredList = if searchText->isNonEmptyString {
arr->Array.filter((obj: Nullable.t<ConnectorTypes.connectorPayload>) => {
switch Nullable.toOption(obj) {
| Some(obj) =>
isContainingStringLowercase(obj.connector_name, searchText) ||
isContainingStringLowercase(obj.merchant_connector_id, searchText) ||
isContainingStringLowercase(obj.connector_label, searchText)
| None => false
}
})
} else {
arr
}
setFilteredConnectorData(_ => filteredList)
}, ~wait=200)
let isMobileView = MatchMedia.useMobileChecker()
let connectorsAvailableForIntegration = featureFlagDetails.isLiveMode
? connectorListForLive
: connectorList
<div>
<PageLoaderWrapper screenState>
<RenderIf
condition={!featureFlagDetails.isLiveMode && configuredConnectors->Array.length == 0}>
<div
className="flex flex-col md:flex-row border rounded-md bg-white gap-4 shadow-generic_shadow mb-12">
<div className="flex flex-col justify-evenly gap-6 pl-14 pb-14 pt-14 pr-2 md:pr-0">
<div className="flex flex-col gap-2.5">
<div>
<p className={textStyle}> {"No Test Credentials?"->React.string} </p>
<p className={textStyle}> {"Connect a Dummy Processor"->React.string} </p>
</div>
<p className={subtextStyle}>
{"Start simulating payments and refunds with a dummy processor setup."->React.string}
</p>
</div>
<Button
text="Connect Now"
buttonType={Primary}
customButtonStyle="group w-1/5"
rightIcon={CustomIcon(
<Icon name="thin-right-arrow" size=20 className="cursor-pointer" />,
)}
onClick={_ => {
setProcessorModal(_ => true)
}}
/>
</div>
<RenderIf condition={!isMobileView}>
<div className="h-30 md:w-[37rem] justify-end hidden laptop:block">
<img alt="dummy-connector" src="/assets/DummyConnectorImage.svg" />
</div>
</RenderIf>
</div>
</RenderIf>
<PageUtils.PageHeading
title="Payment Processors"
customHeadingStyle="mb-10"
subTitle="Connect a test processor and get started with testing your payments"
/>
<div className="flex flex-col gap-14">
<RenderIf condition={showFeedbackModal}>
<HSwitchFeedBackModal
showModal={showFeedbackModal}
setShowModal={setShowFeedbackModal}
modalHeading="Tell us about your integration experience"
feedbackVia="connected_a_connector"
/>
</RenderIf>
<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={ConnectorTableUtils.connectorEntity(
"connectors",
~authorization=userHasAccess(~groupAccess=ConnectorsManage),
)}
currrentFetchCount={filteredConnectorData->Array.length}
collapseTableRow=false
/>
</RenderIf>
<ProcessorCards
configuredConnectors
connectorsAvailableForIntegration
urlPrefix="connectors/new"
setProcessorModal
/>
<RenderIf condition={processorModal}>
<DummyProcessorModal
processorModal
setProcessorModal
urlPrefix="connectors/new"
configuredConnectors
connectorsAvailableForIntegration
/>
</RenderIf>
</div>
</PageLoaderWrapper>
</div>
}
| 1,380 | 9,667 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorAccountDetails.res | .res | @react.component
let make = (~setCurrentStep, ~setInitialValues, ~initialValues, ~isUpdateFlow) => {
open ConnectorUtils
open APIUtils
open LogicUtils
open ConnectorAccountDetailsHelper
let getURL = useGetURL()
let url = RescriptReactRouter.useUrl()
let showToast = ToastState.useShowToast()
let mixpanelEvent = MixpanelHook.useSendEvent()
let connector = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("name", "")
let connectorID = HSwitchUtils.getConnectorIDFromUrl(url.path->List.toArray, "")
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let updateDetails = useUpdateMethod(~showErrorToast=false)
let (verifyDone, setVerifyDone) = React.useState(_ => ConnectorTypes.NoAttempt)
let (showVerifyModal, setShowVerifyModal) = React.useState(_ => false)
let (verifyErrorMessage, setVerifyErrorMessage) = React.useState(_ => None)
let connectorTypeFromName = connector->getConnectorNameTypeFromString
let selectedConnector = React.useMemo(() => {
connectorTypeFromName->getConnectorInfo
}, [connector])
let defaultBusinessProfile = Recoil.useRecoilValueFromAtom(HyperswitchAtom.businessProfilesAtom)
let activeBusinessProfile =
defaultBusinessProfile->MerchantAccountUtils.getValueFromBusinessProfile
let connectorDetails = React.useMemo(() => {
try {
if connector->isNonEmptyString {
let dict = Window.getConnectorConfig(connector)
setScreenState(_ => Success)
dict
} else {
Dict.make()->JSON.Encode.object
}
} catch {
| Exn.Error(e) => {
Js.log2("FAILED TO LOAD CONNECTOR CONFIG", e)
let err = Exn.message(e)->Option.getOr("Something went wrong")
setScreenState(_ => PageLoaderWrapper.Error(err))
Dict.make()->JSON.Encode.object
}
}
}, [connector])
let (
bodyType,
connectorAccountFields,
connectorMetaDataFields,
isVerifyConnector,
connectorWebHookDetails,
connectorLabelDetailField,
connectorAdditionalMerchantData,
) = getConnectorFields(connectorDetails)
let (showModal, setShowModal) = React.useState(_ => false)
let updatedInitialVal = React.useMemo(() => {
let initialValuesToDict = initialValues->getDictFromJsonObject
// TODO: Refactor for generic case
if !isUpdateFlow {
if (
switch connectorTypeFromName {
| Processors(PAYPAL) => true
| _ => false
} &&
featureFlagDetails.paypalAutomaticFlow
) {
initialValuesToDict->Dict.set(
"connector_label",
initialValues
->getDictFromJsonObject
->getString("connector_label", "")
->JSON.Encode.string,
)
initialValuesToDict->Dict.set(
"profile_id",
initialValuesToDict->getString("profile_id", "")->JSON.Encode.string,
)
} else if connector->isNonEmptyString {
initialValuesToDict->Dict.set(
"connector_label",
`${connector}_${activeBusinessProfile.profile_name}`->JSON.Encode.string,
)
initialValuesToDict->Dict.set(
"profile_id",
activeBusinessProfile.profile_id->JSON.Encode.string,
)
}
}
if (
connectorTypeFromName->checkIsDummyConnector(featureFlagDetails.testProcessors) &&
!isUpdateFlow
) {
let apiKeyDict = [("api_key", "test_key"->JSON.Encode.string)]->Dict.fromArray
initialValuesToDict->Dict.set("connector_account_details", apiKeyDict->JSON.Encode.object)
initialValuesToDict->JSON.Encode.object
} else {
initialValues
}
}, [connector, activeBusinessProfile.profile_id])
let onSubmitMain = async values => {
open ConnectorTypes
try {
let body = generateInitialValuesDict(
~values,
~connector,
~bodyType,
~isLiveMode={featureFlagDetails.isLiveMode},
)
setScreenState(_ => Loading)
setCurrentStep(_ => PaymentMethods)
setScreenState(_ => Success)
setInitialValues(_ => body)
} catch {
| Exn.Error(e) => {
setShowVerifyModal(_ => false)
setVerifyDone(_ => ConnectorTypes.NoAttempt)
switch Exn.message(e) {
| Some(message) => {
let errMsg = message->parseIntoMyData
if errMsg.code->Option.getOr("")->String.includes("HE_01") {
showToast(
~message="This configuration already exists for the connector. Please try with a different country or label under advanced settings.",
~toastType=ToastState.ToastError,
)
setCurrentStep(_ => IntegFields)
setScreenState(_ => Success)
} else {
showToast(
~message="Failed to Save the Configuration!",
~toastType=ToastState.ToastError,
)
setScreenState(_ => Error(message))
}
}
| None => setScreenState(_ => Error("Failed to Fetch!"))
}
}
}
}
let onSubmitVerify = async values => {
try {
let body =
generateInitialValuesDict(
~values,
~connector,
~bodyType,
~isLiveMode={featureFlagDetails.isLiveMode},
)->ignoreFields(connectorID, verifyConnectorIgnoreField)
let url = getURL(~entityName=V1(CONNECTOR), ~methodType=Post, ~connector=Some(connector))
let _ = await updateDetails(url, body, Post)
setShowVerifyModal(_ => false)
onSubmitMain(values)->ignore
} catch {
| Exn.Error(e) =>
switch Exn.message(e) {
| Some(message) => {
let errorMessage = message->parseIntoMyData
setVerifyErrorMessage(_ => errorMessage.message)
setShowVerifyModal(_ => true)
setVerifyDone(_ => Failure)
}
| None => setScreenState(_ => Error("Failed to Fetch!"))
}
}
}
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 buttonText = switch verifyDone {
| NoAttempt =>
if !isUpdateFlow {
"Connect and Proceed"
} else {
"Proceed"
}
| Failure => "Try Again"
| _ => "Loading..."
}
let (suggestedAction, suggestedActionExists) = getSuggestedAction(~verifyErrorMessage, ~connector)
let handleShowModal = () => {
setShowModal(_ => true)
}
let mixpanelEventName = isUpdateFlow ? "processor_step1_onUpdate" : "processor_step1"
<PageLoaderWrapper screenState>
<Form
initialValues={updatedInitialVal}
onSubmit={(values, _) => {
mixpanelEvent(~eventName=mixpanelEventName)
onSubmit(
~values,
~onSubmitVerify,
~onSubmitMain,
~setVerifyDone,
~verifyDone,
~isVerifyConnector,
)
}}
validate={validateMandatoryField}
formClass="flex flex-col ">
<ConnectorHeaderWrapper
connector
headerButton={<AddDataAttributes attributes=[("data-testid", "connector-submit-button")]>
<FormRenderer.SubmitButton loadingText="Processing..." text=buttonText />
</AddDataAttributes>}
handleShowModal>
<div className="flex flex-col gap-2 p-2 md:px-10">
<ConnectorAccountDetailsHelper.BusinessProfileRender
isUpdateFlow selectedConnector={connector}
/>
</div>
<div className={`flex flex-col gap-2 p-2 md:px-10`}>
<div className="grid grid-cols-2 flex-1">
<ConnectorConfigurationFields
connector={connectorTypeFromName}
connectorAccountFields
selectedConnector
connectorMetaDataFields
connectorWebHookDetails
connectorLabelDetailField
connectorAdditionalMerchantData
/>
</div>
<IntegrationHelp.Render connector setShowModal showModal />
</div>
<FormValuesSpy />
</ConnectorHeaderWrapper>
<VerifyConnectorModal
showVerifyModal
setShowVerifyModal
connector
verifyErrorMessage
suggestedActionExists
suggestedAction
setVerifyDone
/>
</Form>
</PageLoaderWrapper>
}
| 1,946 | 9,668 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorPaymentMethod.res | .res | @react.component
let make = (~setCurrentStep, ~connector, ~setInitialValues, ~initialValues, ~isUpdateFlow) => {
open ConnectorUtils
open APIUtils
open PageLoaderWrapper
open LogicUtils
let getURL = useGetURL()
let _showAdvancedConfiguration = false
let mixpanelEvent = MixpanelHook.useSendEvent()
let fetchConnectorList = ConnectorListHook.useFetchConnectorList()
let (paymentMethodsEnabled, setPaymentMethods) = React.useState(_ =>
Dict.make()->JSON.Encode.object->getPaymentMethodEnabled
)
let (metaData, setMetaData) = React.useState(_ => Dict.make()->JSON.Encode.object)
let showToast = ToastState.useShowToast()
let connectorID = initialValues->getDictFromJsonObject->getOptionString("merchant_connector_id")
let (screenState, setScreenState) = React.useState(_ => Loading)
let updateAPIHook = useUpdateMethod(~showErrorToast=false)
let updateDetails = value => {
setPaymentMethods(_ => value->Array.copy)
}
let setPaymentMethodDetails = async () => {
try {
setScreenState(_ => Loading)
let _ = getConnectorPaymentMethodDetails(
~initialValues,
~setPaymentMethods,
~setMetaData,
~isUpdateFlow,
~isPayoutFlow=false,
~connector,
~updateDetails,
)
setScreenState(_ => Success)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong")
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
}
React.useEffect(() => {
setPaymentMethodDetails()->ignore
None
}, [connector])
let mixpanelEventName = isUpdateFlow ? "processor_step2_onUpdate" : "processor_step2"
let onSubmit = async (values, _form: ReactFinalForm.formApi) => {
mixpanelEvent(~eventName=mixpanelEventName)
try {
setScreenState(_ => Loading)
let obj: ConnectorTypes.wasmRequest = {
connector,
payment_methods_enabled: paymentMethodsEnabled,
}
let body =
constructConnectorRequestBody(obj, values)->ignoreFields(
connectorID->Option.getOr(""),
connectorIgnoredField,
)
let connectorUrl = getURL(~entityName=V1(CONNECTOR), ~methodType=Post, ~id=connectorID)
let response = await updateAPIHook(connectorUrl, body, Post)
let _ = await fetchConnectorList()
setInitialValues(_ => response)
setScreenState(_ => Success)
setCurrentStep(_ => ConnectorTypes.SummaryAndTest)
showToast(
~message=!isUpdateFlow ? "Connector Created Successfully!" : "Details Updated!",
~toastType=ToastSuccess,
)
} 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)
setCurrentStep(_ => ConnectorTypes.IntegFields)
} else {
showToast(~message=errorMessage, ~toastType=ToastError)
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
}
Nullable.null
}
<PageLoaderWrapper screenState>
<Form onSubmit initialValues={initialValues}>
<div className="flex flex-col">
<div className="flex justify-between border-b p-2 md:px-10 md:py-6">
<div className="flex gap-2 items-center">
<GatewayIcon gateway={connector->String.toUpperCase} />
<h2 className="text-xl font-semibold">
{connector->getDisplayNameForConnector->React.string}
</h2>
</div>
<div className="self-center">
<FormRenderer.SubmitButton text="Proceed" />
</div>
</div>
<div className="grid grid-cols-4 flex-1 p-2 md:p-10">
<div className="flex flex-col gap-6 col-span-3">
<HSwitchUtils.AlertBanner
bannerText="Please verify if the payment methods are turned on at the processor end as well."
bannerType=Warning
/>
<PaymentMethod.PaymentMethodsRender
_showAdvancedConfiguration
connector
paymentMethodsEnabled
updateDetails
setMetaData
isPayoutFlow=false
initialValues
setInitialValues
/>
</div>
</div>
</div>
<FormValuesSpy />
</Form>
</PageLoaderWrapper>
}
| 1,043 | 9,669 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorHome.res | .res | module ConnectorCurrentStepIndicator = {
@react.component
let make = (~currentStep: ConnectorTypes.steps, ~stepsArr) => {
let cols = stepsArr->Array.length->Int.toString
let currIndex = stepsArr->Array.findIndex(item => item === currentStep)
<div className=" w-full md:w-2/3">
<div className={`grid grid-cols-${cols} relative gap-2`}>
{stepsArr
->Array.mapWithIndex((step, i) => {
let isStepCompleted = i <= currIndex
let isPreviousStepCompleted = i < currIndex
let isCurrentStep = i == currIndex
let stepNumberIndicator = if isPreviousStepCompleted {
"border-black bg-white"
} else if isCurrentStep {
"bg-black"
} else {
"border-gray-300 bg-white"
}
let stepNameIndicator = isStepCompleted
? "text-black break-all"
: "text-jp-gray-700 break-all"
let textColor = isCurrentStep ? "text-white" : "text-grey-700"
let stepLineIndicator = isPreviousStepCompleted ? "bg-gray-700" : "bg-gray-200"
<div key={i->Int.toString} className="flex flex-col gap-2 font-semibold ">
<div className="flex items-center w-full">
<div
className={`h-8 w-8 flex items-center justify-center border rounded-full ${stepNumberIndicator}`}>
{if isPreviousStepCompleted {
<Icon name="check-black" size=20 />
} else {
<p className=textColor> {(i + 1)->Int.toString->React.string} </p>
}}
</div>
<RenderIf condition={i !== stepsArr->Array.length - 1}>
<div className={`h-0.5 ${stepLineIndicator} ml-2 flex-1`} />
</RenderIf>
</div>
<div className={stepNameIndicator}>
{step->ConnectorUtils.getStepName->React.string}
</div>
</div>
})
->React.array}
</div>
</div>
}
}
@react.component
let make = (~showStepIndicator=true, ~showBreadCrumb=true) => {
open ConnectorTypes
open ConnectorUtils
open APIUtils
let getURL = useGetURL()
let url = RescriptReactRouter.useUrl()
let updateDetails = useUpdateMethod()
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let showToast = ToastState.useShowToast()
let connector = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("name", "")
let connectorTypeFromName = connector->getConnectorNameTypeFromString
let profileIdFromUrl =
UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getOptionString("profile_id")
let connectorID = HSwitchUtils.getConnectorIDFromUrl(url.path->List.toArray, "")
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (initialValues, setInitialValues) = React.useState(_ => Dict.make()->JSON.Encode.object)
let (currentStep, setCurrentStep) = React.useState(_ => ConnectorTypes.IntegFields)
let fetchDetails = useGetMethod()
let isUpdateFlow = switch url.path->HSwitchUtils.urlPath {
| list{"connectors", "new"} => false
| _ => true
}
let setSetupAccountStatus = Recoil.useSetRecoilState(HyperswitchAtom.paypalAccountStatusAtom)
let getConnectorDetails = async () => {
try {
let connectorUrl = getURL(~entityName=V1(CONNECTOR), ~methodType=Get, ~id=Some(connectorID))
let json = await fetchDetails(connectorUrl)
setInitialValues(_ => json)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to update!")
Exn.raiseError(err)
}
| _ => Exn.raiseError("Something went wrong")
}
}
let profileID =
initialValues->LogicUtils.getDictFromJsonObject->LogicUtils.getOptionString("profile_id")
let getPayPalStatus = React.useCallback(async () => {
open PayPalFlowUtils
open LogicUtils
try {
setScreenState(_ => PageLoaderWrapper.Loading)
let profileId = switch profileID {
| Some(value) => value
| _ =>
switch profileIdFromUrl {
| Some(profileIdValue) => profileIdValue
| _ => Exn.raiseError("Profile Id not found!")
}
}
let paypalBody = generatePayPalBody(~connectorId={connectorID}, ~profileId=Some(profileId))
let url = getURL(~entityName=V1(PAYPAL_ONBOARDING_SYNC), ~methodType=Post)
let responseValue = await updateDetails(url, paypalBody, Post)
let paypalDict = responseValue->getDictFromJsonObject->getJsonObjectFromDict("paypal")
switch paypalDict->JSON.Classify.classify {
| String(str) => {
setSetupAccountStatus(_ => str->stringToVariantMapper)
setCurrentStep(_ => AutomaticFlow)
}
| Object(dict) =>
handleObjectResponse(
~dict,
~setInitialValues,
~connector,
~connectorType=Processor,
~handleStateToNextPage=_ => setCurrentStep(_ => PaymentMethods),
)
| _ => ()
}
setScreenState(_ => PageLoaderWrapper.Success)
} catch {
| Exn.Error(e) =>
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
if err->String.includes("Profile") {
showToast(~message="Profile Id not found. Try Again", ~toastType=ToastError)
}
setScreenState(_ => PageLoaderWrapper.Custom)
}
}, (connector, profileID, profileIdFromUrl, connectorID))
let commonPageState = () => {
if isUpdateFlow {
setCurrentStep(_ => Preview)
} else {
setCurrentStep(_ => ConnectorTypes.IntegFields)
}
setScreenState(_ => Success)
}
let determinePageState = () => {
switch (connectorTypeFromName, featureFlagDetails.paypalAutomaticFlow) {
| (Processors(PAYPAL), true) =>
PayPalFlowUtils.payPalPageState(
~setScreenState,
~url,
~setSetupAccountStatus,
~getPayPalStatus,
~setCurrentStep,
~isUpdateFlow,
)->ignore
| (_, _) => commonPageState()
}
}
let getDetails = async () => {
try {
setScreenState(_ => Loading)
let _ = await Window.connectorWasmInit()
if isUpdateFlow {
await getConnectorDetails()
}
determinePageState()
setScreenState(_ => Success)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong")
setScreenState(_ => Error(err))
}
| _ => setScreenState(_ => Error("Something went wrong"))
}
}
React.useEffect(() => {
if connector->LogicUtils.isNonEmptyString {
getDetails()->ignore
} else {
setScreenState(_ => Error("Connector name not found"))
}
None
}, [connector])
let customUiForPaypal =
<DefaultLandingPage
title="Oops, we hit a little bump on the road!"
customStyle={`py-16 !m-0 `}
overriddingStylesTitle="text-2xl font-semibold"
buttonText="Go back to processor"
overriddingStylesSubtitle="!text-sm text-grey-700 opacity-50 !w-3/4"
subtitle="We apologize for the inconvenience, but it seems like we encountered a hiccup while processing your request."
onClickHandler={_ => {
RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/connectors"))
setScreenState(_ => PageLoaderWrapper.Success)
}}
isButton=true
/>
<PageLoaderWrapper screenState customUI={customUiForPaypal}>
<div className="flex flex-col gap-10 overflow-scroll h-full w-full">
<RenderIf condition={showBreadCrumb}>
<BreadCrumbNavigation
path=[
connectorID === "new"
? {
title: "Processor",
link: "/connectors",
warning: `You have not yet completed configuring your ${connector->LogicUtils.snakeToTitle} connector. Are you sure you want to go back?`,
}
: {
title: "Processor",
link: "/connectors",
},
]
currentPageTitle={connector->getDisplayNameForConnector}
cursorStyle="cursor-pointer"
/>
</RenderIf>
<RenderIf condition={currentStep !== Preview && showStepIndicator}>
<ConnectorCurrentStepIndicator currentStep stepsArr />
</RenderIf>
<RenderIf
condition={connectorTypeFromName->checkIsDummyConnector(featureFlagDetails.testProcessors)}>
<HSwitchUtils.AlertBanner
bannerText="This is a test connector and will not be reflected on your payment processor dashboard."
bannerType=Warning
/>
</RenderIf>
<div
className="bg-white rounded-lg border h-3/4 overflow-scroll shadow-boxShadowMultiple show-scrollbar">
{switch currentStep {
| AutomaticFlow =>
switch connectorTypeFromName {
| Processors(PAYPAL) =>
<ConnectPayPal
connector isUpdateFlow setInitialValues initialValues setCurrentStep getPayPalStatus
/>
| _ => React.null
}
| IntegFields =>
<ConnectorAccountDetails setCurrentStep setInitialValues initialValues isUpdateFlow />
| PaymentMethods =>
<ConnectorPaymentMethod
setCurrentStep connector setInitialValues initialValues isUpdateFlow
/>
| SummaryAndTest
| Preview =>
// <PaymentProcessorSummary />
<ConnectorPreview
connectorInfo={initialValues}
currentStep
setCurrentStep
isUpdateFlow
setInitialValues
getPayPalStatus
getConnectorDetails={Some(getConnectorDetails)}
/>
}}
</div>
</div>
</PageLoaderWrapper>
}
| 2,257 | 9,670 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorPreviewHelper.res | .res | module InfoField = {
@react.component
let make = (~label, ~str) => {
<div className="flex items-center">
<h2 className="flex-[1] text-base font-semibold text-grey-700 opacity-70">
{label->React.string}
</h2>
<h3 className="flex-[3] border p-1.5 bg-gray-50 rounded-lg overflow-scroll whitespace-nowrap">
{str->React.string}
</h3>
</div>
}
}
module CredsInfoField = {
@react.component
let make = (~authKeys, ~connectorAccountFields) => {
open LogicUtils
let dict = authKeys->Identity.genericTypeToDictOfJson
dict
->Dict.keysToArray
->Array.filter(ele => ele !== "auth_type")
->Array.map(field => {
let value = dict->getString(field, "")
let label = connectorAccountFields->getString(field, "")
<InfoField label str=value />
})
->React.array
}
}
module CashtoCodeCredsInfo = {
@react.component
let make = (~authKeys: ConnectorTypes.currencyAuthKey) => {
open LogicUtils
let dict = authKeys.auth_key_map->Identity.genericTypeToDictOfJson
dict
->Dict.keysToArray
->Array.map(ele => {
let data = dict->getDictfromDict(ele)
let keys = data->Dict.keysToArray
{
<>
<InfoField label="Currency" str=ele />
{keys
->Array.map(ele => {
let value = data->getString(ele, "")
<InfoField label={ele->snakeToTitle} str=value />
})
->React.array}
</>
}
})
->React.array
}
}
module PreviewCreds = {
@react.component
let make = (~connectorAccountFields, ~connectorInfo: ConnectorTypes.connectorPayload) => {
switch connectorInfo.connector_account_details {
| HeaderKey(authKeys) => <CredsInfoField authKeys connectorAccountFields />
| BodyKey(bodyKey) => <CredsInfoField authKeys=bodyKey connectorAccountFields />
| SignatureKey(signatureKey) => <CredsInfoField authKeys=signatureKey connectorAccountFields />
| MultiAuthKey(multiAuthKey) => <CredsInfoField authKeys=multiAuthKey connectorAccountFields />
| CertificateAuth(certificateAuth) =>
<CredsInfoField authKeys=certificateAuth connectorAccountFields />
| CurrencyAuthKey(currencyAuthKey) => <CashtoCodeCredsInfo authKeys=currencyAuthKey />
| UnKnownAuthType(_) => React.null
}
}
}
| 589 | 9,671 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorTableUtils.res | .res | open ConnectorTypes
type colType =
| Name
| TestMode
| Status
| Disabled
| Actions
| ConnectorLabel
| PaymentMethods
| MerchantConnectorId
let defaultColumns = [
Name,
MerchantConnectorId,
ConnectorLabel,
Status,
Disabled,
TestMode,
Actions,
PaymentMethods,
]
let getConnectorObjectFromListViaId = (
connectorList: array<ConnectorTypes.connectorPayload>,
mca_id: string,
) => {
connectorList
->Array.find(ele => {ele.merchant_connector_id == mca_id})
->Option.getOr(
ConnectorInterface.mapDictToConnectorPayload(
ConnectorInterface.connectorInterfaceV1,
Dict.make(),
),
)
}
let getAllPaymentMethods = (paymentMethodsArray: array<paymentMethodEnabledType>) => {
let paymentMethods = paymentMethodsArray->Array.reduce([], (acc, item) => {
acc->Array.concat([item.payment_method->LogicUtils.capitalizeString])
})
paymentMethods
}
let getHeading = colType => {
switch colType {
| Name => Table.makeHeaderInfo(~key="connector_name", ~title="Processor")
| TestMode => Table.makeHeaderInfo(~key="test_mode", ~title="Test Mode")
| Status => Table.makeHeaderInfo(~key="status", ~title="Integration status")
| Disabled => Table.makeHeaderInfo(~key="disabled", ~title="Disabled")
| Actions => Table.makeHeaderInfo(~key="actions", ~title="")
| MerchantConnectorId =>
Table.makeHeaderInfo(~key="merchant_connector_id", ~title="Merchant Connector Id")
| 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 getTableCell = (~connectorType: ConnectorTypes.connector=Processor) => {
let getCell = (connector: connectorPayload, colType): Table.cell => {
switch colType {
| Name =>
CustomCell(
<HelperComponents.ConnectorCustomCell
connectorName=connector.connector_name connectorType
/>,
"",
)
| TestMode => Text(connector.test_mode ? "True" : "False")
| 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>,
"",
)
| ConnectorLabel => Text(connector.connector_label)
| Actions => Table.CustomCell(<div />, "")
| PaymentMethods =>
Table.CustomCell(
<div>
{connector.payment_methods_enabled
->getAllPaymentMethods
->Array.joinWith(", ")
->React.string}
</div>,
"",
)
| MerchantConnectorId =>
CustomCell(
<HelperComponents.CopyTextCustomComp
customTextCss="w-36 truncate whitespace-nowrap"
displayValue=Some(connector.merchant_connector_id)
/>,
"",
)
}
}
getCell
}
let comparatorFunction = (connector1: connectorPayload, connector2: connectorPayload) => {
connector1.connector_name->String.localeCompare(connector2.connector_name)
}
let sortPreviouslyConnectedList = arr => {
Array.toSorted(arr, comparatorFunction)
}
let getPreviouslyConnectedList: JSON.t => array<connectorPayload> = json => {
let data = ConnectorInterface.mapJsonArrayToConnectorPayloads(
ConnectorInterface.connectorInterfaceV1,
json,
PaymentProcessor,
)
data
}
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.merchant_connector_id}?name=${connec.connector_name}`,
),
~authorization,
)
},
)
}
| 984 | 9,672 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorUpdateAuthCreds.res | .res | @react.component
let make = (~connectorInfo: ConnectorTypes.connectorPayload, ~getConnectorDetails) => {
open ConnectorUtils
open APIUtils
open LogicUtils
open ConnectorAccountDetailsHelper
let mixpanelEvent = MixpanelHook.useSendEvent()
let getURL = useGetURL()
let updateAPIHook = useUpdateMethod(~showErrorToast=false)
let showToast = ToastState.useShowToast()
let (showModal, setShowFeedbackModal) = React.useState(_ => false)
// Need to remove connector and merge connector and connectorTypeVariants
let (processorType, connectorType) =
connectorInfo.connector_type
->connectorTypeTypedValueToStringMapper
->connectorTypeTuple
let {connector_name: connectorName} = connectorInfo
let connectorTypeFromName = connectorName->getConnectorNameTypeFromString(~connectorType)
let connectorDetails = 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
}
dict
} else {
JSON.Encode.null
}
} catch {
| Exn.Error(e) => {
Js.log2("FAILED TO LOAD CONNECTOR CONFIG", e)
let _ = Exn.message(e)->Option.getOr("Something went wrong")
JSON.Encode.null
}
}
}, [connectorInfo.merchant_connector_id])
let (
_,
connectorAccountFields,
connectorMetaDataFields,
_,
connectorWebHookDetails,
connectorLabelDetailField,
connectorAdditionalMerchantData,
) = getConnectorFields(connectorDetails)
let initialValues = React.useMemo(() => {
let authType = switch connectorInfo.connector_account_details {
| HeaderKey(authKeys) => authKeys.auth_type
| BodyKey(bodyKey) => bodyKey.auth_type
| SignatureKey(signatureKey) => signatureKey.auth_type
| MultiAuthKey(multiAuthKey) => multiAuthKey.auth_type
| CertificateAuth(certificateAuth) => certificateAuth.auth_type
| CurrencyAuthKey(currencyAuthKey) => currencyAuthKey.auth_type
| UnKnownAuthType(_) => ""
}
[
(
"connector_type",
connectorInfo.connector_type
->connectorTypeTypedValueToStringMapper
->JSON.Encode.string,
),
(
"connector_account_details",
[("auth_type", authType->JSON.Encode.string)]
->Dict.fromArray
->JSON.Encode.object,
),
("connector_webhook_details", connectorInfo.connector_webhook_details),
("connector_label", connectorInfo.connector_label->JSON.Encode.string),
("metadata", connectorInfo.metadata),
(
"additional_merchant_data",
connectorInfo.additional_merchant_data->checkEmptyJson
? JSON.Encode.null
: connectorInfo.additional_merchant_data,
),
]->LogicUtils.getJsonFromArrayOfJson
}, (
connectorInfo.connector_webhook_details,
connectorInfo.connector_label,
connectorInfo.metadata,
))
let onSubmit = async (values, _) => {
try {
let url = getURL(
~entityName=V1(CONNECTOR),
~methodType=Post,
~id=Some(connectorInfo.merchant_connector_id),
)
let _ = await updateAPIHook(url, values, Post)
switch getConnectorDetails {
| Some(fun) => fun()->ignore
| _ => ()
}
setShowFeedbackModal(_ => false)
} catch {
| _ => showToast(~message="Connector Failed to update", ~toastType=ToastError)
}
Nullable.null
}
let validateMandatoryField = values => {
let errors = Dict.make()
let valuesFlattenJson = values->JsonFlattenUtils.flattenObject(true)
validateConnectorRequiredFields(
connectorTypeFromName,
valuesFlattenJson,
connectorAccountFields,
connectorMetaDataFields,
connectorWebHookDetails,
connectorLabelDetailField,
errors->JSON.Encode.object,
)
}
let selectedConnector = React.useMemo(() => {
connectorTypeFromName->getConnectorInfo
}, [connectorName])
<>
<div
className="cursor-pointer py-2"
onClick={_ => {
mixpanelEvent(~eventName=`processor_update_creds_${connectorName}`)
setShowFeedbackModal(_ => true)
}}>
<ToolTip
height=""
description={`Update the ${connectorName} creds`}
toolTipFor={<Icon size=18 name="edit" className={`mt-1 ml-1`} />}
toolTipPosition=Top
tooltipWidthClass="w-fit"
/>
</div>
<Modal
closeOnOutsideClick=true
modalHeading={`Update Connector ${connectorName}`}
showModal
setShowModal=setShowFeedbackModal
childClass="p-1"
borderBottom=true
revealFrom=Reveal.Right
modalClass="w-full md:w-1/3 !h-full overflow-y-scroll !overflow-x-hidden rounded-none text-jp-gray-900">
<Form initialValues validate={validateMandatoryField} onSubmit>
<ConnectorConfigurationFields
connector={connectorTypeFromName}
connectorAccountFields
selectedConnector
connectorMetaDataFields
connectorWebHookDetails
connectorLabelDetailField
connectorAdditionalMerchantData
/>
<div className="flex p-1 justify-end mb-2">
<FormRenderer.SubmitButton text="Submit" />
</div>
<FormValuesSpy />
</Form>
</Modal>
</>
}
| 1,286 | 9,673 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorAdditionalMerchantData/ConnectorAdditionalMerchantDataUtils.res | .res | let connectorAdditionalMerchantDataMapper = name => {
switch name {
| "iban" => `additional_merchant_data.open_banking_recipient_data.account_data.iban.iban`
| "iban.name" => `additional_merchant_data.open_banking_recipient_data.account_data.${name}`
| "sort_code" => `additional_merchant_data.open_banking_recipient_data.account_data.bacs.sort_code`
| "account_number" => `additional_merchant_data.open_banking_recipient_data.account_data.bacs.account_number`
| "bacs.name" => `additional_merchant_data.open_banking_recipient_data.account_data.${name}`
| "wallet_id" => `additional_merchant_data.open_banking_recipient_data.wallet_id`
| "connector_recipient_id" => `additional_merchant_data.open_banking_recipient_data.connector_recipient_id`
| _ => `additional_merchant_data.${name}`
}
}
let connectorAdditionalMerchantDataValueInput = (
~connectorAdditionalMerchantData: CommonConnectorTypes.inputField,
) => {
open CommonConnectorHelper
let {\"type", name} = connectorAdditionalMerchantData
let formName = connectorAdditionalMerchantDataMapper(name)
switch \"type" {
| Text => textInput(~field={connectorAdditionalMerchantData}, ~formName)
| Select => selectInput(~field={connectorAdditionalMerchantData}, ~formName)
| Toggle => toggleInput(~field={connectorAdditionalMerchantData}, ~formName)
| MultiSelect => multiSelectInput(~field={connectorAdditionalMerchantData}, ~formName)
| _ => textInput(~field={connectorAdditionalMerchantData}, ~formName)
}
}
let modifiedOptions = options => {
// This change should be moved to wasm
let dropDownOptions = options->Array.map((item): SelectBox.dropdownOption => {
{
label: switch item {
| "account_data" => "Bank Scheme"
| "iban" => "Sepa"
| _ => item->LogicUtils.snakeToTitle
},
value: item,
}
})
dropDownOptions
}
| 449 | 9,674 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorAdditionalMerchantData/ConnectorAdditionalMerchantData.res | .res | @react.component
let make = (~connector, ~connectorAdditionalMerchantData) => {
open ConnectorTypes
{
switch connector {
| Processors(PLAID) => <PlaidAdditionalMerchantData connectorAdditionalMerchantData />
| _ => React.null
}
}
}
| 62 | 9,675 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorAdditionalMerchantData/PlaidAdditionalMerchantDataType.res | .res | type pliadAdditionalFields = [
| #open_banking_recipient_data
| #account_data
| #iban
| #bacs
| #connector_recipient_id
| #wallet_id
]
| 49 | 9,676 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorAdditionalMerchantData/PlaidAdditionalMerchantData.res | .res | module PlaidAdditionMerchantDataSelect = {
@react.component
let make = (
~setState,
~value="",
~options=[],
~buttonText="",
~label="",
~handler: option<ReactEvent.Form.t => unit>=?,
) => {
let input: ReactFinalForm.fieldRenderPropsInput = {
name: "string",
onBlur: _ => (),
onChange: ev => {
let val = ev->Identity.formReactEventToString
switch handler {
| Some(func) => func(ev)
| None => ()
}
setState(_ => val)
},
onFocus: _ => (),
value: value->JSON.Encode.string,
checked: true,
}
<>
<div>
<h2
className="font-semibold pt-2 pb-2 text-fs-13 text-jp-gray-900 dark:text-jp-gray-text_darktheme dark:text-opacity-50 ml-1">
{label->React.string}
<span className="text-red-950"> {"*"->React.string} </span>
</h2>
</div>
<SelectBox.BaseDropdown
allowMultiSelect=false
buttonText
input
options={options}
hideMultiSelectButtons=false
showSelectionAsChips=true
customButtonStyle="w-full"
fullLength=true
dropdownCustomWidth="w-full"
fixedDropDownDirection=TopLeft
/>
</>
}
}
@react.component
let make = (~connectorAdditionalMerchantData) => {
open LogicUtils
open ConnectorAdditionalMerchantDataUtils
open PlaidAdditionalMerchantDataType
let form = ReactFinalForm.useForm()
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let initialValues =
formState.values
->getDictFromJsonObject
->getDictfromDict("additional_merchant_data")
let initialOpenBankingData =
initialValues
->getDictfromDict((#open_banking_recipient_data: pliadAdditionalFields :> string))
->Dict.keysToArray
->getValueFromArray(0, "")
let initialAccountdata =
initialValues
->getDictfromDict((#open_banking_recipient_data: pliadAdditionalFields :> string))
->getDictfromDict((#account_data: pliadAdditionalFields :> string))
->Dict.keysToArray
->getValueFromArray(0, "")
let (openBankingRecipientData, setOpenBankingRecipientData) = React.useState(_ =>
initialOpenBankingData
)
let (accountData, setaccountData) = React.useState(_ => initialAccountdata)
let keys = connectorAdditionalMerchantData->Dict.keysToArray
let updateOpenBanking = _ => {
form.change(
"additional_merchant_data.open_banking_recipient_data",
JSON.Encode.null->Identity.genericTypeToJson,
)
setaccountData(_ => "")
}
let updateAccountData = _ => {
form.change(
"additional_merchant_data.open_banking_recipient_data.account_data",
JSON.Encode.null->Identity.genericTypeToJson,
)
}
{
keys
->Array.mapWithIndex((field, index) => {
<div key={index->Int.toString}>
{if field === (#open_banking_recipient_data: pliadAdditionalFields :> string) {
let fields =
connectorAdditionalMerchantData
->getDictfromDict(field)
->JSON.Encode.object
->convertMapObjectToDict
->CommonConnectorUtils.inputFieldMapper
<PlaidAdditionMerchantDataSelect
setState=setOpenBankingRecipientData
value=openBankingRecipientData
options={fields.options->modifiedOptions}
buttonText={`Select ${fields.label}`}
label={fields.label}
handler=updateOpenBanking
/>
} else if (
field === (#account_data: pliadAdditionalFields :> string) &&
openBankingRecipientData == (#account_data: pliadAdditionalFields :> string)
) {
let fields =
connectorAdditionalMerchantData
->getDictfromDict(field)
->JSON.Encode.object
->convertMapObjectToDict
->CommonConnectorUtils.inputFieldMapper
<PlaidAdditionMerchantDataSelect
setState=setaccountData
value=accountData
options={fields.options->modifiedOptions}
buttonText={`Select ${fields.label}`}
label={fields.label}
handler=updateAccountData
/>
} else if (
field === (#iban: pliadAdditionalFields :> string) &&
accountData == (#iban: pliadAdditionalFields :> string)
) {
let ibanKeys =
connectorAdditionalMerchantData->getArrayFromDict(
(#iban: pliadAdditionalFields :> string),
[],
)
ibanKeys
->Array.mapWithIndex((field, index) => {
let fields =
field
->convertMapObjectToDict
->CommonConnectorUtils.inputFieldMapper
<div key={index->Int.toString}>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={connectorAdditionalMerchantDataValueInput(
~connectorAdditionalMerchantData={fields},
)}
/>
</div>
})
->React.array
} else if (
field === (#bacs: pliadAdditionalFields :> string) &&
accountData == (#bacs: pliadAdditionalFields :> string)
) {
let bacsKeys =
connectorAdditionalMerchantData->getArrayFromDict(
(#bacs: pliadAdditionalFields :> string),
[],
)
bacsKeys
->Array.mapWithIndex((field, index) => {
let fields =
field
->convertMapObjectToDict
->CommonConnectorUtils.inputFieldMapper
<div key={index->Int.toString}>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={connectorAdditionalMerchantDataValueInput(
~connectorAdditionalMerchantData={fields},
)}
/>
</div>
})
->React.array
} else if (
field === (#connector_recipient_id: pliadAdditionalFields :> string) &&
openBankingRecipientData === (#connector_recipient_id: pliadAdditionalFields :> string)
) {
let connectorRecipientId =
connectorAdditionalMerchantData->getDictfromDict(
(#connector_recipient_id: pliadAdditionalFields :> string),
)
let fields =
connectorRecipientId
->JSON.Encode.object
->convertMapObjectToDict
->CommonConnectorUtils.inputFieldMapper
<div key={index->Int.toString}>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={connectorAdditionalMerchantDataValueInput(
~connectorAdditionalMerchantData={fields},
)}
/>
</div>
} else if (
field === (#wallet_id: pliadAdditionalFields :> string) &&
openBankingRecipientData == (#wallet_id: pliadAdditionalFields :> string)
) {
let walledId =
connectorAdditionalMerchantData->getDictfromDict(
(#wallet_id: pliadAdditionalFields :> string),
)
let fields =
walledId
->JSON.Encode.object
->convertMapObjectToDict
->CommonConnectorUtils.inputFieldMapper
<div key={index->Int.toString}>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={connectorAdditionalMerchantDataValueInput(
~connectorAdditionalMerchantData={fields},
)}
/>
</div>
} else {
React.null
}}
</div>
})
->React.array
}
}
| 1,702 | 9,677 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectPayPalFlow/PayPalFlowTypes.res | .res | type configurationTypes = Manual | Automatic | NotSelected
type setupAccountStatus =
| Connect_paypal_landing
| Redirecting_to_paypal
| Manual_setup_flow
| Account_not_found
| Payments_not_receivable
| Ppcp_custom_denied
| More_permissions_needed
| Email_not_verified
| Connector_integrated
type choiceDetailsType = {
displayText: string,
choiceDescription: string,
variantType: configurationTypes,
}
type errorPageInfoType = {
headerText: string,
subText: string,
buttonText?: string,
}
| 130 | 9,678 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectPayPalFlow/ConnectPayPal.res | .res | let h3Leading2TextClass = `${HSwitchUtils.getTextClass((H3, Leading_2))} text-grey-700`
let p1RegularTextClass = `${HSwitchUtils.getTextClass((P1, Regular))} text-grey-700 opacity-50`
let p1MediumTextClass = `${HSwitchUtils.getTextClass((P1, Medium))} text-grey-700`
let p2RedularTextClass = `${HSwitchUtils.getTextClass((P2, Regular))} text-grey-700 opacity-50`
let preRequisiteList = [
"You need to grant all the permissions to create and receive payments",
"Confirm your email id once PayPal sends you the mail",
]
module PayPalCreateNewAccountModal = {
@react.component
let make = (~butttonDisplayText, ~actionUrl, ~setScreenState) => {
let {globalUIConfig: {primaryColor}} = React.useContext(ThemeProvider.themeContext)
let initializePayPalWindow = () => {
try {
Window.payPalCreateAccountWindow()
} catch {
| Exn.Error(e) =>
switch Exn.message(e) {
| Some(message) => setScreenState(_ => PageLoaderWrapper.Error(message))
| None => setScreenState(_ => PageLoaderWrapper.Error("Failed to load paypal window!"))
}
}
}
React.useEffect(() => {
initializePayPalWindow()
None
}, [])
<AddDataAttributes attributes=[("data-paypal-button", "true")]>
<a
className={`!w-fit rounded-md ${primaryColor} text-white px-4 h-fit border py-3 flex items-center justify-center gap-2`}
href={`${actionUrl}&displayMode=minibrowser`}
target="PPFrame">
{butttonDisplayText->React.string}
<Icon name="thin-right-arrow" size=20 />
</a>
</AddDataAttributes>
}
}
module ManualSetupScreen = {
@react.component
let make = (
~connector,
~connectorAccountFields,
~selectedConnector,
~connectorMetaDataFields,
~connectorWebHookDetails,
~connectorLabelDetailField,
~connectorAdditionalMerchantData,
) => {
<div className="flex flex-col gap-8">
<ConnectorAccountDetailsHelper.ConnectorConfigurationFields
connector={connector->ConnectorUtils.getConnectorNameTypeFromString}
connectorAccountFields
selectedConnector
connectorMetaDataFields
connectorWebHookDetails
connectorLabelDetailField
connectorAdditionalMerchantData
/>
</div>
}
}
module LandingScreen = {
@react.component
let make = (~configuartionType, ~setConfigurationType) => {
let {
globalUIConfig: {primaryColor, font: {textColor}, border: {borderColor}},
} = React.useContext(ThemeProvider.themeContext)
let getBlockColor = value =>
configuartionType === value
? `${borderColor.primaryNormal} ${primaryColor} bg-opacity-10 `
: "border"
<div className="flex flex-col gap-10">
<div className="flex flex-col gap-4">
<p className=h3Leading2TextClass>
{"Do you have a PayPal business account?"->React.string}
</p>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 md:gap-8">
{PayPalFlowUtils.listChoices
->Array.mapWithIndex((items, index) => {
<div
key={index->Int.toString}
className={`p-6 flex flex-col gap-4 rounded-md cursor-pointer ${items.variantType->getBlockColor} rounded-md`}
onClick={_ => setConfigurationType(_ => items.variantType)}>
<div className="flex justify-between items-center">
<div className="flex gap-2 items-center ">
<p className=p1MediumTextClass> {items.displayText->React.string} </p>
</div>
<Icon
name={configuartionType === items.variantType ? "selected" : "nonselected"}
size=20
className={`cursor-pointer !${textColor.primaryNormal}`}
/>
</div>
<div className="flex gap-2 items-center ">
<p className=p1RegularTextClass> {items.choiceDescription->React.string} </p>
</div>
</div>
})
->React.array}
</div>
</div>
</div>
}
}
module ErrorPage = {
@react.component
let make = (~setupAccountStatus, ~actionUrl, ~getPayPalStatus, ~setScreenState) => {
let errorPageDetails = setupAccountStatus->PayPalFlowUtils.getPageDetailsForAutomatic
<div className="flex flex-col gap-6">
<div className="flex flex-col gap-6 p-8 bg-jp-gray-light_gray_bg">
<Icon name="error-icon" size=24 />
<div className="flex flex-col gap-2">
<RenderIf condition={errorPageDetails.headerText->LogicUtils.isNonEmptyString}>
<p className={`${p1RegularTextClass} !opacity-100`}>
{errorPageDetails.headerText->React.string}
</p>
</RenderIf>
<RenderIf condition={errorPageDetails.subText->LogicUtils.isNonEmptyString}>
<p className=p1RegularTextClass> {errorPageDetails.subText->React.string} </p>
</RenderIf>
</div>
<div className="flex gap-4 items-center">
<PayPalCreateNewAccountModal
actionUrl butttonDisplayText="Sign in / Sign up on PayPal" setScreenState
/>
<Button
text="Refresh status"
buttonType={Secondary}
buttonSize=Small
onClick={_ => getPayPalStatus()->ignore}
/>
</div>
<RenderIf condition={errorPageDetails.buttonText->Option.isSome}>
<PayPalCreateNewAccountModal
butttonDisplayText={errorPageDetails.buttonText->Option.getOr("")}
actionUrl
setScreenState
/>
</RenderIf>
</div>
</div>
}
}
module RedirectionToPayPalFlow = {
@react.component
let make = (~getPayPalStatus, ~profileId) => {
open APIUtils
open PayPalFlowTypes
open GlobalVars
let getURL = useGetURL()
let url = RescriptReactRouter.useUrl()
let path = url.path->List.toArray->Array.joinWith("/")
let connectorId = HSwitchUtils.getConnectorIDFromUrl(url.path->List.toArray, "")
let updateDetails = useUpdateMethod(~showErrorToast=false)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (actionUrl, setActionUrl) = React.useState(_ => "")
let getRedirectPaypalWindowUrl = async _ => {
open LogicUtils
try {
setScreenState(_ => PageLoaderWrapper.Loading)
let returnURL = `${getHostUrl}/${path}?name=paypal&is_back=true&is_simplified_paypal=true&profile_id=${profileId}`
let body = PayPalFlowUtils.generatePayPalBody(
~connectorId={connectorId},
~returnUrl=Some(returnURL),
)
let url = getURL(~entityName=V1(ACTION_URL), ~methodType=Post)
let response = await updateDetails(url, body, Post)
let actionURL =
response->getDictFromJsonObject->getDictfromDict("paypal")->getString("action_url", "")
setActionUrl(_ => actionURL)
setScreenState(_ => PageLoaderWrapper.Success)
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Error(""))
}
}
let setupAccountStatus = Recoil.useRecoilValueFromAtom(HyperswitchAtom.paypalAccountStatusAtom)
React.useEffect(() => {
getRedirectPaypalWindowUrl()->ignore
None
}, [])
<PageLoaderWrapper screenState>
{switch setupAccountStatus {
| Redirecting_to_paypal =>
<div className="flex flex-col gap-6">
<p className=h3Leading2TextClass>
{"Sign in / Sign up to auto-configure your credentials & webhooks"->React.string}
</p>
<div className="flex flex-col gap-2">
<p className={`${p1RegularTextClass} !opacity-100`}>
{"Things to keep in mind while signing up"->React.string}
</p>
{preRequisiteList
->Array.mapWithIndex((item, index) =>
<p className=p1RegularTextClass>
{`${(index + 1)->Int.toString}. ${item}`->React.string}
</p>
)
->React.array}
</div>
<div className="flex gap-4 items-center">
<PayPalCreateNewAccountModal
actionUrl butttonDisplayText="Sign in / Sign up on PayPal" setScreenState
/>
<Button
text="Refresh status "
buttonType={Secondary}
buttonSize=Small
onClick={_ => getPayPalStatus()->ignore}
/>
</div>
</div>
| _ => <ErrorPage setupAccountStatus actionUrl getPayPalStatus setScreenState />
}}
</PageLoaderWrapper>
}
}
@react.component
let make = (
~connector,
~isUpdateFlow,
~setInitialValues,
~initialValues,
~setCurrentStep,
~getPayPalStatus,
) => {
open LogicUtils
let url = RescriptReactRouter.useUrl()
let showToast = ToastState.useShowToast()
let showPopUp = PopUpState.useShowPopUp()
let updateConnectorAccountDetails = PayPalFlowUtils.useDeleteConnectorAccountDetails()
let deleteTrackingDetails = PayPalFlowUtils.useDeleteTrackingDetails()
let (setupAccountStatus, setSetupAccountStatus) = Recoil.useRecoilState(
HyperswitchAtom.paypalAccountStatusAtom,
)
let connectorValue = isUpdateFlow
? HSwitchUtils.getConnectorIDFromUrl(url.path->List.toArray, "")
: url.search->getDictFromUrlSearchParams->Dict.get("connectorId")->Option.getOr("")
let (connectorId, setConnectorId) = React.useState(_ => connectorValue)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Success)
let (configuartionType, setConfigurationType) = React.useState(_ => PayPalFlowTypes.NotSelected)
let selectedConnector =
connector->ConnectorUtils.getConnectorNameTypeFromString->ConnectorUtils.getConnectorInfo
let defaultBusinessProfile = Recoil.useRecoilValueFromAtom(HyperswitchAtom.businessProfilesAtom)
let activeBusinessProfile =
defaultBusinessProfile->MerchantAccountUtils.getValueFromBusinessProfile
let updatedInitialVal = React.useMemo(() => {
let initialValuesToDict = initialValues->getDictFromJsonObject
if !isUpdateFlow {
initialValuesToDict->Dict.set(
"connector_label",
initialValues
->getDictFromJsonObject
->getString("connector_label", "paypal_default")
->JSON.Encode.string,
)
initialValuesToDict->Dict.set(
"profile_id",
activeBusinessProfile.profile_id->JSON.Encode.string,
)
setInitialValues(_ => initialValuesToDict->JSON.Encode.object)
initialValuesToDict->JSON.Encode.object
} else {
initialValues
}
}, [initialValues])
let setConnectorAsActive = values => {
// sets the status as active and diabled as false
let dictOfInitialValues = values->getDictFromJsonObject
dictOfInitialValues->Dict.set("disabled", false->JSON.Encode.bool)
dictOfInitialValues->Dict.set("status", "active"->JSON.Encode.string)
setInitialValues(_ => dictOfInitialValues->JSON.Encode.object)
}
let updateConnectorDetails = async values => {
try {
setScreenState(_ => Loading)
let res = await updateConnectorAccountDetails(
values,
connectorId,
connector,
isUpdateFlow,
true,
"inactive",
)
if configuartionType === Manual {
setConnectorAsActive(res)
} else {
setInitialValues(_ => res)
}
let connectorId = res->getDictFromJsonObject->getString("merchant_connector_id", "")
setConnectorId(_ => connectorId)
setScreenState(_ => Success)
RescriptReactRouter.replace(
GlobalVars.appendDashboardPath(~url=`/connectors/${connectorId}?name=paypal`),
)
} catch {
| Exn.Error(e) =>
switch Exn.message(e) {
| Some(message) => Exn.raiseError(message)
| None => Exn.raiseError("")
}
}
}
let validateMandatoryFieldForPaypal = 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)
}
errors->JSON.Encode.object
}
let handleChangeAuthType = async values => {
try {
// This will only be called whenever there is a update flow
// And whenever we are changing the flow from Manual to Automatic or vice-versa
// To check if the flow is changed we are using auth type (BodyKey for Manual and SignatureKey for Automatic)
// It deletes the old tracking id associated with the connector id and deletes the connector credentials
setScreenState(_ => Loading)
let _ = await deleteTrackingDetails(connectorId, connector)
let _ = await updateConnectorDetails(values)
switch configuartionType {
| Automatic => setSetupAccountStatus(_ => Redirecting_to_paypal)
| Manual | _ => setCurrentStep(_ => ConnectorTypes.IntegFields)
}
setScreenState(_ => Success)
} catch {
| Exn.Error(_) => setScreenState(_ => Error("Unable to change the configuartion"))
}
}
let handleOnSubmit = async (values, _) => {
open PayPalFlowUtils
open ConnectorUtils
try {
let authType = initialValues->getAuthTypeFromConnectorDetails
// create flow
if !isUpdateFlow {
switch configuartionType {
| Automatic => {
await updateConnectorDetails(values)
setSetupAccountStatus(_ => Redirecting_to_paypal)
}
| Manual | _ => {
setConnectorAsActive(values)
setCurrentStep(_ => ConnectorTypes.IntegFields)
}
}
} // update flow if body type is changed
else if (
authType !==
PayPalFlowUtils.getBodyType(isUpdateFlow, configuartionType)
->String.toLowerCase
->ConnectorUtils.mapAuthType
) {
showPopUp({
popUpType: (Warning, WithIcon),
heading: "Warning changing configuration",
description: React.string(`Modifying the configuration will result in the loss of existing details associated with this connector. Are you certain you want to continue?`),
handleConfirm: {
text: "Proceed",
onClick: {_ => handleChangeAuthType(values)->ignore},
},
handleCancel: {text: "Cancel"},
})
} else {
// update flow if body type is not changed
switch configuartionType {
| Automatic => setCurrentStep(_ => ConnectorTypes.PaymentMethods)
| Manual | _ => {
setConnectorAsActive(values)
setCurrentStep(_ => ConnectorTypes.IntegFields)
}
}
}
} catch {
| Exn.Error(e) =>
switch Exn.message(e) {
| Some(message) => {
let errMsg = message->parseIntoMyData
if errMsg.code->Option.getOr("")->String.includes("HE_01") {
showToast(
~message="This configuration already exists for the connector. Please try with a different country or label under advanced settings.",
~toastType=ToastState.ToastError,
)
setCurrentStep(_ => ConnectorTypes.AutomaticFlow)
setSetupAccountStatus(_ => Connect_paypal_landing)
setScreenState(_ => Success)
} else {
showToast(
~message="Failed to Save the Configuration!",
~toastType=ToastState.ToastError,
)
setScreenState(_ => Error(message))
}
}
| None => setScreenState(_ => Error("Failed to Fetch!"))
}
}
Js.Nullable.null
}
let proceedButton = switch setupAccountStatus {
| Redirecting_to_paypal
| Account_not_found
| Payments_not_receivable
| Ppcp_custom_denied
| More_permissions_needed
| Email_not_verified =>
<Button
text="Change configuration"
buttonType={Primary}
onClick={_ => setSetupAccountStatus(_ => Connect_paypal_landing)}
/>
| _ =>
<FormRenderer.SubmitButton
loadingText="Processing..."
text="Proceed"
disabledParamter={configuartionType === NotSelected}
/>
}
<div className="w-full h-full flex flex-col justify-between">
<PageLoaderWrapper screenState>
<Form
initialValues={updatedInitialVal}
validate={validateMandatoryFieldForPaypal}
onSubmit={handleOnSubmit}>
<div>
<ConnectorAccountDetailsHelper.ConnectorHeaderWrapper
connector
headerButton={proceedButton}
conditionForIntegrationSteps={!(
PayPalFlowUtils.conditionForIntegrationSteps->Array.includes(setupAccountStatus)
)}>
<div className="flex flex-col gap-2 p-2 md:p-10">
{switch setupAccountStatus {
| Connect_paypal_landing =>
<div className="flex flex-col gap-2">
<div className="w-1/3">
<ConnectorAccountDetailsHelper.RenderConnectorInputFields
details={ConnectorUtils.connectorLabelDetailField}
name={"connector_label"}
connector={connector->ConnectorUtils.getConnectorNameTypeFromString}
selectedConnector
isLabelNested=false
disabled={isUpdateFlow}
description="This is an unique label you can generate and pass in order to identify this connector account on your Hyperswitch dashboard and reports. Eg: if your profile label is 'default', connector label can be 'stripe_default'"
/>
</div>
<ConnectorAccountDetailsHelper.BusinessProfileRender
isUpdateFlow selectedConnector={connector}
/>
<LandingScreen configuartionType setConfigurationType />
</div>
| Redirecting_to_paypal
| Account_not_found
| Payments_not_receivable
| Ppcp_custom_denied
| More_permissions_needed
| Email_not_verified =>
<RedirectionToPayPalFlow
getPayPalStatus
profileId={initialValues->getDictFromJsonObject->getString("profile_id", "")}
/>
| _ => React.null
}}
</div>
<FormValuesSpy />
</ConnectorAccountDetailsHelper.ConnectorHeaderWrapper>
</div>
</Form>
<div className="bg-jp-gray-light_gray_bg flex py-4 px-10 gap-2">
<img alt="paypal" src="/assets/PayPalFullLogo.svg" />
<p className=p2RedularTextClass>
{"| Hyperswitch is PayPal's trusted partner, your credentials are secure & never stored with us."->React.string}
</p>
</div>
</PageLoaderWrapper>
</div>
}
| 4,248 | 9,679 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectPayPalFlow/MenuOptionForPayPal.res | .res | @react.component
let make = (
~updateStepValue=ConnectorTypes.IntegFields,
~setCurrentStep,
~disableConnector,
~isConnectorDisabled,
~pageName="connector",
~connectorInfoDict,
~setScreenState,
~isUpdateFlow,
~setInitialValues,
) => {
open HeadlessUI
let showPopUp = PopUpState.useShowPopUp()
let showToast = ToastState.useShowToast()
let deleteTrackingDetails = PayPalFlowUtils.useDeleteTrackingDetails()
let updateConnectorAccountDetails = PayPalFlowUtils.useDeleteConnectorAccountDetails()
let setSetupAccountStatus = Recoil.useSetRecoilState(HyperswitchAtom.paypalAccountStatusAtom)
let connectorInfo = ConnectorInterface.mapDictToConnectorPayload(
ConnectorInterface.connectorInterfaceV1,
connectorInfoDict,
)
let openConfirmationPopUp = _ => {
showPopUp({
popUpType: (Warning, WithIcon),
heading: "Confirm Action ? ",
description: `You are about to ${isConnectorDisabled
? "Enable"
: "Disable"->String.toLowerCase} this connector. This might impact your desired routing configurations. Please confirm to proceed.`->React.string,
handleConfirm: {
text: "Confirm",
onClick: _ => disableConnector(isConnectorDisabled)->ignore,
},
handleCancel: {text: "Cancel"},
})
}
let connectorStatusAvailableToSwitch = isConnectorDisabled ? "Enable" : "Disable"
let updateConnectorAuthType = async values => {
try {
setScreenState(_ => PageLoaderWrapper.Loading)
let res = await updateConnectorAccountDetails(
values,
connectorInfo.merchant_connector_id,
connectorInfo.connector_name,
isUpdateFlow,
true,
"inactive",
)
setInitialValues(_ => res)
setScreenState(_ => Success)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong!")
Exn.raiseError(err)
}
}
}
let handleNewPayPalAccount = async () => {
try {
await deleteTrackingDetails(connectorInfo.merchant_connector_id, connectorInfo.connector_name)
await updateConnectorAuthType(connectorInfoDict->JSON.Encode.object)
setCurrentStep(_ => ConnectorTypes.AutomaticFlow)
setSetupAccountStatus(_ => PayPalFlowTypes.Redirecting_to_paypal)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong!")
showToast(~message=err, ~toastType=ToastError)
}
}
}
let popupForNewPayPalAccount = _ => {
showPopUp({
popUpType: (Warning, WithIcon),
heading: "Confirm Action ?",
description: `By changing this the old account details will be lost `->React.string,
handleConfirm: {
text: "Confirm",
onClick: _ => {
handleNewPayPalAccount()->ignore
},
},
handleCancel: {text: "Cancel"},
})
}
let authType = switch connectorInfo.connector_account_details {
| HeaderKey(authKeys) => authKeys.auth_type
| BodyKey(bodyKey) => bodyKey.auth_type
| SignatureKey(signatureKey) => signatureKey.auth_type
| MultiAuthKey(multiAuthKey) => multiAuthKey.auth_type
| CertificateAuth(certificateAuth) => certificateAuth.auth_type
| CurrencyAuthKey(currencyAuthKey) => currencyAuthKey.auth_type
| UnKnownAuthType(_) => ""
}
<Popover \"as"="div" className="relative inline-block text-left">
{_popoverProps => <>
<Popover.Button> {_ => <Icon name="menu-option" size=28 />} </Popover.Button>
<Popover.Panel className="absolute z-20 right-0 top-10">
{panelProps => {
<div
id="neglectTopbarTheme"
className="relative flex flex-col bg-white py-3 overflow-hidden rounded ring-1 ring-black ring-opacity-5 w-max">
{<>
<RenderIf condition={authType->ConnectorUtils.mapAuthType === #SignatureKey}>
<Navbar.MenuOption
text="Create new PayPal account"
onClick={_ => {
popupForNewPayPalAccount()
panelProps["close"]()
}}
/>
</RenderIf>
<Navbar.MenuOption
text="Change configurations"
onClick={_ => {
setCurrentStep(_ => ConnectorTypes.AutomaticFlow)
setSetupAccountStatus(_ => PayPalFlowTypes.Connect_paypal_landing)
}}
/>
<RenderIf condition={authType->ConnectorUtils.mapAuthType === #BodyKey}>
<Navbar.MenuOption
text="Update"
onClick={_ => {
setCurrentStep(_ => ConnectorTypes.IntegFields)
setSetupAccountStatus(_ => PayPalFlowTypes.Manual_setup_flow)
}}
/>
</RenderIf>
<RenderIf condition={authType->ConnectorUtils.mapAuthType === #SignatureKey}>
<Navbar.MenuOption
text="Update Payment Methods"
onClick={_ => {
setCurrentStep(_ => updateStepValue)
}}
/>
</RenderIf>
<Navbar.MenuOption
text={connectorStatusAvailableToSwitch}
onClick={_ => {
panelProps["close"]()
openConfirmationPopUp()
}}
/>
</>}
</div>
}}
</Popover.Panel>
</>}
</Popover>
}
| 1,194 | 9,680 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectPayPalFlow/PayPalFlowUtils.res | .res | let listChoices: array<PayPalFlowTypes.choiceDetailsType> = [
{
displayText: "No, I don't",
choiceDescription: "Don't worry, easily create & activate your PayPal account in minutes.",
variantType: Automatic,
},
{
displayText: "Yes, I have",
choiceDescription: "Simply login to your PayPal account and leave the rest to us. Or enter credentials manually.",
variantType: Manual,
},
]
let getPageDetailsForAutomatic: PayPalFlowTypes.setupAccountStatus => PayPalFlowTypes.errorPageInfoType = setupAccountStatus => {
switch setupAccountStatus {
| Account_not_found => {
headerText: "No account found for this email",
subText: "No account found for this email.",
}
| Payments_not_receivable => {
headerText: "You currently cannot receive payments due to restriction on your PayPal account",
subText: "An email has been sent to you explaining the issue. Please reach out to PayPal Customer Support for more information.",
}
| Ppcp_custom_denied => {
headerText: "Your application has been denied by PayPal",
subText: "PayPal denied your application to use Advanced Credit and Debit Card Payments.",
}
| More_permissions_needed => {
headerText: "PayPal requires you to grant all permissions",
subText: "You need to grant all the permissions to create and receive payments. Please click on the Signup to PayPal button and grant the permissions.",
buttonText: "Complete Signing up",
}
| Email_not_verified => {
headerText: "Your email is yet to be confirmed!",
subText: "Please confirm your email address on https://www.paypal.com/businessprofile/settings in order to receive payments.",
}
| _ => {
headerText: "",
subText: "",
}
}
}
let stringToVariantMapper = strValue => {
open PayPalFlowTypes
switch strValue {
| "account_not_found" => Account_not_found
| "payments_not_receivable" => Payments_not_receivable
| "ppcp_custom_denied" => Ppcp_custom_denied
| "more_permissions_needed" => More_permissions_needed
| "email_not_verified" => Email_not_verified
| "connector_integrated" => Connector_integrated
| _ => Account_not_found
}
}
let handleObjectResponse = (
~dict,
~setInitialValues,
~connector,
~handleStateToNextPage,
~connectorType,
) => {
open LogicUtils
let values = dict->getJsonObjectFromDict("connector_integrated")
let bodyTypeValue =
values
->getDictFromJsonObject
->getDictfromDict("connector_account_details")
->getString("auth_type", "")
let body = ConnectorUtils.generateInitialValuesDict(
~values,
~connector,
~bodyType=bodyTypeValue,
~connectorType,
)
setInitialValues(_ => body)
handleStateToNextPage()
}
let getBodyType = (isUpdateFlow, configuartionType) => {
open PayPalFlowTypes
isUpdateFlow
? switch configuartionType {
| Manual => "BodyKey"
| Automatic | NotSelected => "SignatureKey"
}
: "TemporaryAuth"
}
let generateConnectorPayloadPayPal = (
~profileId,
~connectorId,
~connector,
~bodyType,
~connectorLabel,
~disabled,
~status,
) => {
open ConnectorUtils
let initialValues =
[
("profile_id", profileId->JSON.Encode.string),
("connector_name", connector->String.toLowerCase->JSON.Encode.string),
("connector_type", "payment_processor"->JSON.Encode.string),
("disabled", disabled->JSON.Encode.bool),
("test_mode", true->JSON.Encode.bool),
("status", status->JSON.Encode.string),
("connector_label", connectorLabel->JSON.Encode.string),
]->LogicUtils.getJsonFromArrayOfJson
generateInitialValuesDict(~values={initialValues}, ~connector, ~bodyType)->ignoreFields(
connectorId,
connectorIgnoredField,
)
}
let generatePayPalBody = (~returnUrl=None, ~connectorId, ~profileId=None) => {
switch returnUrl {
| Some(returnURL) =>
[
("connector", "paypal"->JSON.Encode.string),
("return_url", returnURL->JSON.Encode.string),
("connector_id", connectorId->JSON.Encode.string),
]->LogicUtils.getJsonFromArrayOfJson
| _ =>
[
("connector", "paypal"->JSON.Encode.string),
("connector_id", connectorId->JSON.Encode.string),
("profile_id", profileId->Option.getOr("")->JSON.Encode.string),
]->LogicUtils.getJsonFromArrayOfJson
}
}
let conditionForIntegrationSteps: array<PayPalFlowTypes.setupAccountStatus> = [
Account_not_found,
Redirecting_to_paypal,
]
let useDeleteTrackingDetails = () => {
open APIUtils
let updateDetails = useUpdateMethod(~showErrorToast=false)
let getURL = useGetURL()
async (connectorId, connector) => {
try {
let url = getURL(~entityName=V1(RESET_TRACKING_ID), ~methodType=Post)
let body =
[
("connector_id", connectorId->JSON.Encode.string),
("connector", connector->JSON.Encode.string),
]->LogicUtils.getJsonFromArrayOfJson
let _ = await updateDetails(url, body, Post)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to update!")
Exn.raiseError(err)
}
}
}
}
let useDeleteConnectorAccountDetails = () => {
open LogicUtils
open APIUtils
let updateDetails = useUpdateMethod(~showErrorToast=false)
let getURL = useGetURL()
async (initialValues, connectorId, connector, isUpdateFlow, disabled, status) => {
try {
let dictOfJson = initialValues->getDictFromJsonObject
let profileIdValue = dictOfJson->getString("profile_id", "")
let body = generateConnectorPayloadPayPal(
~profileId=profileIdValue,
~connectorId,
~connector,
~bodyType="TemporaryAuth",
~connectorLabel={
dictOfJson->getString("connector_label", "")
},
~disabled,
~status,
)
let url = getURL(
~entityName=V1(CONNECTOR),
~methodType=Post,
~id=isUpdateFlow ? Some(connectorId) : None,
)
let res = await updateDetails(url, body, Post)
res
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
Exn.raiseError(err)
}
}
}
}
let getAuthTypeFromConnectorDetails = json => {
open LogicUtils
json
->getDictFromJsonObject
->getDictfromDict("connector_account_details")
->getString("auth_type", "")
->String.toLowerCase
->ConnectorUtils.mapAuthType
}
let payPalPageState = async (
~setScreenState: (PageLoaderWrapper.viewType => PageLoaderWrapper.viewType) => unit,
~url: RescriptReactRouter.url,
~setSetupAccountStatus,
~getPayPalStatus,
~setCurrentStep,
~isUpdateFlow,
) => {
open LogicUtils
try {
let isSimplifiedPayPalFlow =
url.search
->getDictFromUrlSearchParams
->Dict.get("is_simplified_paypal")
->Option.getOr("false")
->getBoolFromString(false)
let isRedirectedFromPaypalModal =
url.search
->getDictFromUrlSearchParams
->Dict.get("is_back")
->Option.getOr("false")
->getBoolFromString(false)
setSetupAccountStatus(_ => PayPalFlowTypes.Connect_paypal_landing)
if isRedirectedFromPaypalModal {
await getPayPalStatus()
} else if isUpdateFlow && !(isSimplifiedPayPalFlow && isRedirectedFromPaypalModal) {
setCurrentStep(_ => ConnectorTypes.Preview)
setScreenState(_ => Success)
} else {
setCurrentStep(_ => ConnectorTypes.AutomaticFlow)
setScreenState(_ => Success)
}
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong")
setScreenState(_ => Error(err))
}
| _ => setScreenState(_ => Error("Something went wrong"))
}
}
| 1,886 | 9,681 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/PaymentMethodAdditionalDetails/AdditionalDetailsSidebar.res | .res | module AdditionalDetailsSidebarComp = {
open ConnectorTypes
open ConnectorUtils
@react.component
let make = (
~method: option<ConnectorTypes.paymentMethodConfigType>,
~setMetaData,
~setShowWalletConfigurationModal,
~updateDetails,
~paymentMethodsEnabled,
~paymentMethod,
~onCloseClickCustomFun,
~setInitialValues,
~pmtName: string,
) => {
open LogicUtils
let connector = UrlUtils.useGetFilterDictFromUrl("")->getString("name", "")
let updateMetadata = json => {
setMetaData(_ => json)
switch method {
| Some(pmt) => paymentMethodsEnabled->addMethod(paymentMethod, pmt)->updateDetails
| _ => ()
}
}
let updatePaymentMethods = () => {
switch method {
| Some(pmt) => paymentMethodsEnabled->addMethod(paymentMethod, pmt)->updateDetails
| _ => ()
}
}
<div>
{switch paymentMethod->getPaymentMethodFromString {
| BankDebit =>
<BankDebit
setShowWalletConfigurationModal
update=updatePaymentMethods
paymentMethod
paymentMethodType=pmtName
setInitialValues
/>
| _ => React.null
}}
<RenderIf condition={paymentMethod->getPaymentMethodFromString !== BankDebit}>
{switch pmtName->getPaymentMethodTypeFromString {
| ApplePay =>
<ApplePayIntegration
connector setShowWalletConfigurationModal update=updateMetadata onCloseClickCustomFun
/>
| GooglePay =>
<GooglePayIntegration
connector setShowWalletConfigurationModal update=updateMetadata onCloseClickCustomFun
/>
| SamsungPay =>
<SamsungPayIntegration
connector
setShowWalletConfigurationModal
update=updatePaymentMethods
onCloseClickCustomFun
/>
| Paze =>
<PazeIntegration
connector
setShowWalletConfigurationModal
update=updatePaymentMethods
onCloseClickCustomFun
/>
| _ => React.null
}}
</RenderIf>
</div>
}
}
| 459 | 9,682 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/PaymentMethodAdditionalDetails/AdditionalDetailsSidebarHelper.res | .res | module Heading = {
@react.component
let make = (~title: string, ~iconName: string) => {
<>
<div className="flex gap-3 p-2 m-2">
<Icon name=iconName size=56 />
<div>
<div className="flex items-center gap-4">
<div className="leading-tight font-semibold text-fs-18"> {title->React.string} </div>
<div
className={`flex items-center gap-1 text-sm text-grey-700 font-semibold border rounded-full px-2 py-1 bg-orange-600/80 border-orange-500`}>
<div>
<Icon name={"ellipse-black"} size=4 />
</div>
<div> {"Test Mode"->React.string} </div>
</div>
</div>
<div className={` mt-2 text-sm text-hyperswitch_black opacity-50 font-normal`}>
{"Choose Configuration Method"->React.string}
</div>
</div>
</div>
<hr className="w-full mt-4" />
</>
}
}
module CustomTag = {
@react.component
let make = (~tagText="", ~tagSize=5, ~tagLeftIcon=None, ~tagCustomStyle="") => {
<div
className={`flex items-center gap-1 shadow-connectorTagShadow border rounded-full px-2 py-1 ${tagCustomStyle}`}>
{switch tagLeftIcon {
| Some(icon) =>
<div>
<Icon name={icon} size={tagSize} />
</div>
| None => React.null
}}
<div className={"text-hyperswitch_black text-sm font-medium text-green-960"}>
{tagText->React.string}
</div>
</div>
}
}
module InfoCard = {
@react.component
let make = (~children, ~customInfoStyle="") => {
<div
className={`rounded border bg-blue-800 border-blue-700 dark:border-blue-700 relative flex w-full p-6 `}>
<Icon className=customInfoStyle name="info-circle-unfilled" size=16 />
<div> {children} </div>
</div>
}
}
module Card = {
@react.component
let make = (~heading="", ~isSelected=false, ~children: React.element) => {
let {globalUIConfig: {font: {textColor}, border: {borderColor}}} = React.useContext(
ThemeProvider.themeContext,
)
<>
<div
className={`relative w-full p-6 rounded flex flex-col justify-between ${isSelected
? `bg-light_blue_bg ${borderColor.primaryNormal} dark: ${borderColor.primaryNormal}`
: ""}`}>
<div className="flex justify-between">
<div
className={`leading-tight font-semibold text-fs-18 ${isSelected
? `${textColor.primaryNormal}`
: "text-hyperswitch_black"} `}>
{heading->React.string}
</div>
<div>
<RadioIcon isSelected fill={`${textColor.primaryNormal}`} />
</div>
</div>
{children}
</div>
</>
}
}
module CustomSubText = {
@react.component
let make = () => {
<>
<p> {"Enable Apple Pay for iOS app with the following details:"->React.string} </p>
<ol className="list-decimal list-inside mt-1">
<li> {"Payment Processing Certificate from the processor"->React.string} </li>
<li> {" Apple Pay Merchant ID"->React.string} </li>
<li> {"Merchant Private Key"->React.string} </li>
</ol>
</>
}
}
module SimplifiedHelper = {
@react.component
let make = (
~customElement: option<React.element>,
~heading="",
~stepNumber="1",
~subText=None,
) => {
let {globalUIConfig: {backgroundColor, font: {textColor}}} = React.useContext(
ThemeProvider.themeContext,
)
let bgColor = "bg-white"
let stepColor = `${backgroundColor} text-white py-px px-2`
<div className={`flex flex-col py-8 px-6 gap-3 ${bgColor} cursor-pointer`}>
<div className={"flex justify-between "}>
<div className="flex gap-4">
<div>
<p className={`${stepColor} font-medium`}> {stepNumber->React.string} </p>
</div>
<div>
<p className={`font-medium text-base ${textColor.primaryNormal}`}>
{heading->React.string}
</p>
<RenderIf condition={subText->Option.isSome}>
<p className={`mt-2 text-base text-hyperswitch_black opacity-50 font-normal`}>
{subText->Option.getOr("")->React.string}
</p>
</RenderIf>
{switch customElement {
| Some(element) => element
| _ => React.null
}}
</div>
</div>
</div>
</div>
}
}
| 1,147 | 9,683 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/ConnectorMetaDataUtils.res | .res | let metaDataInputKeysToIgnore = ["google_pay", "apple_pay", "zen_apple_pay"]
let connectorMetaDataNameMapper = name => {
switch name {
| _ => `metadata.${name}`
}
}
let connectorMetaDataValueInput = (~connectorMetaDataFields: CommonConnectorTypes.inputField) => {
open CommonConnectorHelper
let {\"type", name} = connectorMetaDataFields
let formName = connectorMetaDataNameMapper(name)
{
switch (\"type", name) {
| (Select, "merchant_config_currency") => currencyField(~name=formName)
| (Text, _) => textInput(~field={connectorMetaDataFields}, ~formName)
| (Number, _) => numberInput(~field={connectorMetaDataFields}, ~formName)
| (Select, _) =>
selectInput(~field={connectorMetaDataFields}, ~formName, ~fixedDropDownDirection=TopLeft)
| (Toggle, _) => toggleInput(~field={connectorMetaDataFields}, ~formName)
| (MultiSelect, _) => multiSelectInput(~field={connectorMetaDataFields}, ~formName)
| _ => textInput(~field={connectorMetaDataFields}, ~formName)
}
}
}
| 257 | 9,684 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/ConnectorMetaData.res | .res | @react.component
let make = (~connectorMetaDataFields) => {
open LogicUtils
open ConnectorMetaDataUtils
let keys =
connectorMetaDataFields
->Dict.keysToArray
->Array.filter(ele => !Array.includes(metaDataInputKeysToIgnore, ele))
<>
{keys
->Array.mapWithIndex((field, index) => {
let fields =
connectorMetaDataFields
->getDictfromDict(field)
->JSON.Encode.object
->convertMapObjectToDict
->CommonConnectorUtils.inputFieldMapper
<div key={index->Int.toString}>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={connectorMetaDataValueInput(~connectorMetaDataFields={fields})}
/>
</div>
})
->React.array}
</>
}
| 178 | 9,685 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/GooglePay/GooglePayIntegrationTypes.res | .res | type merchantInfo = {
merchant_id: option<string>,
merchant_name: option<string>,
}
type allowedPaymentMethodsParameters = {
allowed_auth_methods: array<string>,
allowed_card_networks: array<string>,
}
type tokenizationSpecificationParameters = {
gateway: string,
gateway_merchant_id?: string,
\"stripe:version"?: string,
\"stripe:publishableKey"?: string,
}
type tokenSpecification = {
\"type": string,
parameters: tokenizationSpecificationParameters,
}
type allowedMethod = {
\"type": string,
parameters: allowedPaymentMethodsParameters,
tokenization_specification: tokenSpecification,
}
type allowedPaymentMethods = array<allowedMethod>
type zenGooglepay = {
terminal_uuid: string,
pay_wall_secret: string,
}
type googlePay = {merchant_info: merchantInfo, allowed_payment_methods: allowedPaymentMethods}
type googlePayConfig = Zen(zenGooglepay) | Standard(googlePay)
type inputType = Text | Toggle | Select
type inputField = {
name: string,
label: string,
placeholder: string,
required: bool,
options: array<string>,
\"type": inputType,
}
| 250 | 9,686 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/GooglePay/GooglePayZen.res | .res | @react.component
let make = (~connector, ~setShowWalletConfigurationModal, ~update, ~onCloseClickCustomFun) => {
open LogicUtils
open GooglePayUtils
let form = ReactFinalForm.useForm()
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let initialFormValue = React.useMemo(() => {
formState.values
->getDictFromJsonObject
->getDictfromDict("metadata")
->getDictfromDict("google_pay")
}, [])
let googlePayFields = React.useMemo(() => {
try {
if connector->isNonEmptyString {
Window.getConnectorConfig(connector)
->getDictFromJsonObject
->getDictfromDict("metadata")
->getArrayFromDict("google_pay", [])
} else {
[]
}
} catch {
| Exn.Error(e) => {
Js.log2("FAILED TO LOAD CONNECTOR CONFIG", e)
[]
}
}
}, [connector])
let setFormData = () => {
let value = zenGooglePayConfig(initialFormValue)
form.change("metadata.google_pay", value->Identity.genericTypeToJson)
}
React.useEffect(() => {
setFormData()
None
}, [])
let closeModal = () => {
onCloseClickCustomFun()
setShowWalletConfigurationModal(_ => false)
}
let onSubmit = () => {
let metadata =
formState.values->getDictFromJsonObject->getDictfromDict("metadata")->JSON.Encode.object
setShowWalletConfigurationModal(_ => false)
let _ = update(metadata)
Nullable.null->Promise.resolve
}
<>
{googlePayFields
->Array.mapWithIndex((field, index) => {
let googlePayField = field->convertMapObjectToDict->CommonConnectorUtils.inputFieldMapper
<div key={index->Int.toString}>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={googlePayValueInput(~googlePayField)}
/>
</div>
})
->React.array}
<div className={`flex gap-2 justify-end mt-4`}>
<Button
text="Cancel"
buttonType={Secondary}
onClick={_ => {
closeModal()->ignore
}}
/>
<Button
onClick={_ => {
onSubmit()->ignore
}}
text="Proceed"
buttonType={Primary}
buttonState={formState.values->validateZenFlow}
/>
</div>
<FormValuesSpy />
</>
}
| 569 | 9,687 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/GooglePay/GooglePayIntegration.res | .res | @react.component
let make = (~connector, ~setShowWalletConfigurationModal, ~update, ~onCloseClickCustomFun) => {
let featureFlag = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
<>
{switch connector->ConnectorUtils.getConnectorNameTypeFromString {
| Processors(ZEN) =>
<GooglePayZen connector update onCloseClickCustomFun setShowWalletConfigurationModal />
| Processors(CYBERSOURCE) =>
<>
<RenderIf condition={!featureFlag.googlePayDecryptionFlow}>
<GooglePayFlow connector setShowWalletConfigurationModal update onCloseClickCustomFun />
</RenderIf>
<RenderIf condition={featureFlag.googlePayDecryptionFlow}>
<GPayFlow connector setShowWalletConfigurationModal update onCloseClickCustomFun />
</RenderIf>
</>
| _ => <GooglePayFlow connector setShowWalletConfigurationModal update onCloseClickCustomFun />
}}
</>
}
| 198 | 9,688 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/GooglePay/GooglePayFlow.res | .res | @react.component
let make = (~connector, ~setShowWalletConfigurationModal, ~update, ~onCloseClickCustomFun) => {
open LogicUtils
open GooglePayUtils
let googlePayFields = React.useMemo(() => {
try {
if connector->isNonEmptyString {
Window.getConnectorConfig(connector)
->getDictFromJsonObject
->getDictfromDict("metadata")
->getArrayFromDict("google_pay", [])
} else {
[]
}
} catch {
| Exn.Error(e) => {
Js.log2("FAILED TO LOAD CONNECTOR CONFIG", e)
[]
}
}
}, [connector])
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let initialGooglePayDict = React.useMemo(() => {
formState.values->getDictFromJsonObject->getDictfromDict("metadata")
}, [])
let form = ReactFinalForm.useForm()
React.useEffect(() => {
if connector->isNonEmptyString {
let value = googlePay(initialGooglePayDict->getDictfromDict("google_pay"), connector)
switch value {
| Zen(data) => form.change("metadata.google_pay", data->Identity.genericTypeToJson)
| Standard(data) => form.change("metadata.google_pay", data->Identity.genericTypeToJson)
}
}
None
}, [connector])
let onSubmit = () => {
let metadata =
formState.values->getDictFromJsonObject->getDictfromDict("metadata")->JSON.Encode.object
setShowWalletConfigurationModal(_ => false)
let _ = update(metadata)
Nullable.null->Promise.resolve
}
let closeModal = () => {
onCloseClickCustomFun()
setShowWalletConfigurationModal(_ => false)
}
<>
{googlePayFields
->Array.mapWithIndex((field, index) => {
let googlePayField = field->convertMapObjectToDict->CommonConnectorUtils.inputFieldMapper
<div key={index->Int.toString}>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={googlePayValueInput(~googlePayField)}
/>
</div>
})
->React.array}
<div className={`flex gap-2 justify-end mt-4`}>
<Button
text="Cancel"
buttonType={Secondary}
onClick={_ => {
closeModal()->ignore
}}
/>
<Button
onClick={_ => {
onSubmit()->ignore
}}
text="Proceed"
buttonType={Primary}
buttonState={formState.values->validateGooglePay(connector)}
/>
</div>
<FormValuesSpy />
</>
}
| 597 | 9,689 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/GooglePay/GooglePayUtils.res | .res | open GooglePayIntegrationTypes
open LogicUtils
let allowedAuthMethod = ["PAN_ONLY"]
let allowedCardNetworks = ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"]
let getCustomGateWayName = connector => {
open ConnectorUtils
open ConnectorTypes
switch connector->getConnectorNameTypeFromString {
| Processors(CHECKOUT) => "checkoutltd"
| Processors(NUVEI) => "nuveidigital"
| Processors(AUTHORIZEDOTNET) => "authorizenet"
| Processors(GLOBALPAY) => "globalpayments"
| Processors(BANKOFAMERICA) | Processors(CYBERSOURCE) => "cybersource"
| Processors(FIUU) => "molpay"
| _ => connector
}
}
let allowedAuthMethodsArray = dict => {
let authMethodsArray =
dict
->getDictfromDict("parameters")
->getStrArrayFromDict("allowed_auth_methods", allowedAuthMethod)
authMethodsArray
}
let allowedPaymentMethodparameters = dict => {
allowed_auth_methods: dict->allowedAuthMethodsArray,
allowed_card_networks: allowedCardNetworks,
}
let tokenizationSpecificationParameters = (dict, connector) => {
open ConnectorUtils
open ConnectorTypes
let tokenizationSpecificationDict =
dict->getDictfromDict("tokenization_specification")->getDictfromDict("parameters")
switch connector->getConnectorNameTypeFromString {
| Processors(STRIPE) => {
gateway: connector,
\"stripe:version": tokenizationSpecificationDict->getString("stripe:version", "2018-10-31"),
\"stripe:publishableKey": tokenizationSpecificationDict->getString(
"stripe:publishableKey",
"",
),
}
| _ => {
gateway: connector->getCustomGateWayName,
gateway_merchant_id: tokenizationSpecificationDict->getString("gateway_merchant_id", ""),
}
}
}
let merchantInfo = dict => {
{
merchant_id: dict->getOptionString("merchant_id"),
merchant_name: dict->getOptionString("merchant_name"),
}
}
let tokenizationSpecification = (dict, connector) => {
\"type": "PAYMENT_GATEWAY",
parameters: dict->tokenizationSpecificationParameters(connector),
}
let allowedPaymentMethod = (dict, connector) => {
\"type": "CARD",
parameters: dict->allowedPaymentMethodparameters,
tokenization_specification: dict->tokenizationSpecification(connector),
}
let zenGooglePayConfig = dict => {
{
terminal_uuid: dict->getString("terminal_uuid", ""),
pay_wall_secret: dict->getString("pay_wall_secret", ""),
}
}
let validateZenFlow = values => {
let data =
values
->getDictFromJsonObject
->getDictfromDict("metadata")
->getDictfromDict("google_pay")
->zenGooglePayConfig
data.terminal_uuid->isNonEmptyString && data.pay_wall_secret->isNonEmptyString
? Button.Normal
: Button.Disabled
}
let googlePay = (dict, connector: string) => {
open ConnectorUtils
open ConnectorTypes
let merchantInfoDict = dict->getDictfromDict("merchant_info")
let allowedPaymentMethodDict =
dict
->getArrayFromDict("allowed_payment_methods", [])
->Array.get(0)
->Option.getOr(Dict.make()->JSON.Encode.object)
->getDictFromJsonObject
let standGooglePayConfig = {
merchant_info: merchantInfoDict->merchantInfo,
allowed_payment_methods: [allowedPaymentMethodDict->allowedPaymentMethod(connector)],
}
switch connector->getConnectorNameTypeFromString {
| Processors(ZEN) => Zen(dict->zenGooglePayConfig)
| _ => Standard(standGooglePayConfig)
}
}
let googlePayNameMapper = name => {
switch name {
| "merchant_id" => `metadata.google_pay.merchant_info.${name}`
| "merchant_name" => `metadata.google_pay.merchant_info.${name}`
| "allowed_auth_methods" => `metadata.google_pay.allowed_payment_methods[0].parameters.${name}`
| "terminal_uuid" => `metadata.google_pay.${name}`
| "pay_wall_secret" => `metadata.google_pay.${name}`
| _ =>
`metadata.google_pay.allowed_payment_methods[0].tokenization_specification.parameters.${name}`
}
}
let validateGooglePay = (values, connector) => {
open ConnectorUtils
open ConnectorTypes
let googlePayData =
values
->getDictFromJsonObject
->getDictfromDict("metadata")
->getDictfromDict("google_pay")
let merchantId = googlePayData->getDictfromDict("merchant_info")->getString("merchant_id", "")
let merchantName = googlePayData->getDictfromDict("merchant_info")->getString("merchant_name", "")
let allowedPaymentMethodDict =
googlePayData
->getArrayFromDict("allowed_payment_methods", [])
->getValueFromArray(0, JSON.Encode.null)
->getDictFromJsonObject
let allowedAuthMethodsArray =
allowedPaymentMethodDict
->getDictfromDict("parameters")
->getArrayFromDict("allowed_auth_methods", [])
let tokenizationSpecificationDict =
allowedPaymentMethodDict
->getDictfromDict("tokenization_specification")
->getDictfromDict("parameters")
switch connector->getConnectorNameTypeFromString {
| Processors(ZEN) =>
googlePayData->getString("terminal_uuid", "")->isNonEmptyString &&
googlePayData->getString("pay_wall_secret", "")->isNonEmptyString
? Button.Normal
: Button.Disabled
| Processors(STRIPE) =>
merchantId->isNonEmptyString &&
merchantName->isNonEmptyString &&
tokenizationSpecificationDict->getString("stripe:publishableKey", "")->isNonEmptyString &&
allowedAuthMethodsArray->Array.length > 0
? Button.Normal
: Button.Disabled
| _ =>
merchantId->isNonEmptyString &&
merchantName->isNonEmptyString &&
tokenizationSpecificationDict->getString("gateway_merchant_id", "")->isNonEmptyString &&
allowedAuthMethodsArray->Array.length > 0
? Button.Normal
: Button.Disabled
}
}
let googlePayValueInput = (~googlePayField: CommonConnectorTypes.inputField) => {
open CommonConnectorHelper
let {\"type", name} = googlePayField
let formName = googlePayNameMapper(name)
{
switch \"type" {
| Text => textInput(~field={googlePayField}, ~formName)
| Select => selectInput(~field={googlePayField}, ~formName)
| MultiSelect => multiSelectInput(~field={googlePayField}, ~formName)
| _ => textInput(~field={googlePayField}, ~formName)
}
}
}
| 1,512 | 9,690 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/GooglePay/GPayFlow/GPayFlow.res | .res | @react.component
let make = (~connector, ~setShowWalletConfigurationModal, ~update, ~onCloseClickCustomFun) => {
open GPayFlowTypes
open LogicUtils
open GPayFlowHelper
open GPayFlowUtils
open AdditionalDetailsSidebarHelper
let (googlePayIntegrationType, setGooglePayIntegrationType) = React.useState(_ =>
#payment_gateway
)
let (googlePayIntegrationStep, setGooglePayIntegrationStep) = React.useState(_ => Landing)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Success)
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let integrationType = React.useMemo(() => {
formState.values->getDictFromJsonObject->getDictfromDict("connector_wallets_details")
}, [])->getIntegrationTypeFromConnectorWalletDetailsGooglePay
let googlePayFields = React.useMemo(() => {
setScreenState(_ => PageLoaderWrapper.Loading)
try {
if connector->isNonEmptyString {
let dict =
Window.getConnectorConfig(connector)
->getDictFromJsonObject
->getDictfromDict("connector_wallets_details")
->getArrayFromDict("google_pay", [])
setScreenState(_ => PageLoaderWrapper.Success)
dict
} else {
setScreenState(_ => PageLoaderWrapper.Success)
[]
}
} catch {
| Exn.Error(e) => {
setScreenState(_ => PageLoaderWrapper.Error("Failed to load connector configuration"))
Js.log2("FAILED TO LOAD CONNECTOR CONFIG", e)
[]
}
}
}, [connector])
let setIntegrationType = () => {
if connector->isNonEmptyString {
setGooglePayIntegrationType(_ => integrationType->getGooglePayIntegrationTypeFromName)
}
}
React.useEffect(() => {
setIntegrationType()
None
}, [connector])
let closeModal = () => {
onCloseClickCustomFun()
setShowWalletConfigurationModal(_ => false)
}
<PageLoaderWrapper
screenState={screenState}
customLoader={<div className="mt-60 w-scrren flex flex-col justify-center items-center">
<div className="animate-spin mb-1">
<Icon name="spinner" size=20 />
</div>
</div>}
sectionHeight="!h-screen">
<Heading title="Google Pay" iconName="google_pay" />
{switch googlePayIntegrationStep {
| Landing =>
<Landing
googlePayIntegrationType closeModal setGooglePayIntegrationStep setGooglePayIntegrationType
/>
| Configure =>
<>
{switch googlePayIntegrationType {
| #payment_gateway =>
<GPayPaymentGatewayFlow
googlePayFields
googlePayIntegrationType
closeModal
connector
setShowWalletConfigurationModal
update
/>
| #direct =>
<GPayDirectFlow
googlePayFields
googlePayIntegrationType
closeModal
connector
setShowWalletConfigurationModal
update
/>
}}
</>
}}
</PageLoaderWrapper>
}
| 688 | 9,691 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/GooglePay/GPayFlow/GPayFlowUtils.res | .res | open GPayFlowTypes
open LogicUtils
let allowedCardNetworks = ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"]
let getCustomGateWayName = connector => {
open ConnectorUtils
open ConnectorTypes
switch connector->getConnectorNameTypeFromString {
| Processors(CHECKOUT) => "checkoutltd"
| Processors(NUVEI) => "nuveidigital"
| Processors(AUTHORIZEDOTNET) => "authorizenet"
| Processors(GLOBALPAY) => "globalpayments"
| Processors(BANKOFAMERICA) | Processors(CYBERSOURCE) => "cybersource"
| Processors(FIUU) => "molpay"
| _ => connector
}
}
let tokenizationSpecificationParameters = (
dict,
connector,
~googlePayIntegrationType: googlePayIntegrationType,
) => {
open ConnectorUtils
open ConnectorTypes
switch googlePayIntegrationType {
| #payment_gateway =>
switch connector->getConnectorNameTypeFromString {
| Processors(STRIPE) => {
gateway: connector,
\"stripe:version": dict->getString("stripe:version", "2018-10-31"),
\"stripe:publishableKey": dict->getString("stripe:publishableKey", ""),
}
| _ => {
gateway: connector->getCustomGateWayName,
gateway_merchant_id: dict->getString("gateway_merchant_id", ""),
}
}
| #direct => {
public_key: dict->getString("public_key", ""),
private_key: dict->getString("private_key", ""),
recipient_id: dict->getString("recipient_id", ""),
}
}
}
let tokenizationSpecification = (
dict,
connector,
~googlePayIntegrationType: googlePayIntegrationType,
) => {
{
\"type": (googlePayIntegrationType :> string)->String.toUpperCase,
parameters: dict
->getDictfromDict("tokenization_specification")
->getDictfromDict("parameters")
->tokenizationSpecificationParameters(connector, ~googlePayIntegrationType),
}
}
let merchantInfo = (dict, connector, ~googlePayIntegrationType: googlePayIntegrationType) => {
{
merchant_id: googlePayIntegrationType == #payment_gateway
? dict->getOptionString("merchant_id")
: None,
merchant_name: dict->getOptionString("merchant_name"),
tokenization_specification: dict->tokenizationSpecification(
connector,
~googlePayIntegrationType,
),
}
}
let googlePay = (
dict,
connector: string,
~googlePayIntegrationType: GPayFlowTypes.googlePayIntegrationType,
) => {
{
provider_details: {
merchant_info: dict
->getDictfromDict("provider_details")
->getDictfromDict("merchant_info")
->merchantInfo(connector, ~googlePayIntegrationType),
},
cards: {
allowed_auth_methods: dict
->getDictfromDict("cards")
->getStrArrayFromDict("allowed_auth_methods", []),
allowed_card_networks: allowedCardNetworks,
},
}
}
let isNonEmptyStringWithoutSpaces = str => {
str->String.trim->isNonEmptyString
}
let validateGooglePay = (values, connector, ~googlePayIntegrationType) => {
let data =
values
->getDictFromJsonObject
->getDictfromDict("connector_wallets_details")
->getDictfromDict("google_pay")
->googlePay(connector, ~googlePayIntegrationType)
switch googlePayIntegrationType {
| #payment_gateway =>
data.provider_details.merchant_info.merchant_name
->Option.getOr("")
->isNonEmptyStringWithoutSpaces &&
data.provider_details.merchant_info.merchant_id
->Option.getOr("")
->isNonEmptyStringWithoutSpaces &&
data.cards.allowed_auth_methods->Array.length > 0 &&
(data.provider_details.merchant_info.tokenization_specification.parameters.\"stripe:publishableKey"
->Option.getOr("")
->isNonEmptyStringWithoutSpaces ||
data.provider_details.merchant_info.tokenization_specification.parameters.gateway_merchant_id
->Option.getOr("")
->isNonEmptyStringWithoutSpaces)
? Button.Normal
: Button.Disabled
| #direct =>
data.provider_details.merchant_info.merchant_name
->Option.getOr("")
->isNonEmptyStringWithoutSpaces &&
data.cards.allowed_auth_methods->Array.length > 0 &&
data.provider_details.merchant_info.tokenization_specification.parameters.public_key
->Option.getOr("")
->isNonEmptyStringWithoutSpaces &&
data.provider_details.merchant_info.tokenization_specification.parameters.private_key
->Option.getOr("")
->isNonEmptyStringWithoutSpaces &&
data.provider_details.merchant_info.tokenization_specification.parameters.recipient_id
->Option.getOr("")
->isNonEmptyStringWithoutSpaces
? Button.Normal
: Button.Disabled
}
}
let ignoreDirectFields = ["public_key", "private_key", "recipient_id"]
let directFields = [
"merchant_name",
"public_key",
"private_key",
"recipient_id",
"allowed_auth_methods",
]
let getMetadataFromConnectorWalletDetailsGooglePay = (dict, connector) => {
open ConnectorUtils
let googlePayDict = dict->getDictfromDict("google_pay")
let merchantInfoDict =
googlePayDict->getDictfromDict("provider_details")->getDictfromDict("merchant_info")
let tokenSpecificationParametersDict =
merchantInfoDict->getDictfromDict("tokenization_specification")->getDictfromDict("parameters")
let tokenSpecificationParameters: GPayFlowTypes.tokenizationSpecificationParametersMetadata = switch connector->getConnectorNameTypeFromString {
| Processors(STRIPE) => {
gateway: tokenSpecificationParametersDict->getString("gateway", ""),
\"stripe:version": tokenSpecificationParametersDict->getString(
"stripe:version",
"2018-10-31",
),
\"stripe:publishableKey": tokenSpecificationParametersDict->getString(
"stripe:publishableKey",
"",
),
}
| _ => {
gateway: tokenSpecificationParametersDict->getString("gateway", ""),
gateway_merchant_id: tokenSpecificationParametersDict->getString("gateway_merchant_id", ""),
}
}
{
merchant_info: {
merchant_id: merchantInfoDict->getOptionString("merchant_id"),
merchant_name: merchantInfoDict->getOptionString("merchant_name"),
},
allowed_payment_methods: [
{
\"type": "CARD",
parameters: {
allowed_auth_methods: googlePayDict
->getDictfromDict("cards")
->getStrArrayFromDict("allowed_auth_methods", []),
allowed_card_networks: googlePayDict
->getDictfromDict("cards")
->getStrArrayFromDict("allowed_card_networks", []),
},
tokenization_specification: {
\"type": "PAYMENT_GATEWAY",
parameters: tokenSpecificationParameters,
},
},
],
}
}
let googlePayNameMapper = (
~name,
~googlePayIntegrationType: GPayFlowTypes.googlePayIntegrationType,
) => {
switch googlePayIntegrationType {
| #payment_gateway =>
switch name {
| "merchant_id" => `connector_wallets_details.google_pay.provider_details.merchant_info.${name}`
| "merchant_name" =>
`connector_wallets_details.google_pay.provider_details.merchant_info.${name}`
| "allowed_auth_methods" => `connector_wallets_details.google_pay.cards.${name}`
| "allowed_card_networks" => `connector_wallets_details.google_pay.cards.${name}`
| _ =>
`connector_wallets_details.google_pay.provider_details.merchant_info.tokenization_specification.parameters.${name}`
}
| #direct =>
switch name {
| "merchant_name" =>
`connector_wallets_details.google_pay.provider_details.merchant_info.${name}`
| "allowed_auth_methods" => `connector_wallets_details.google_pay.cards.${name}`
| "allowed_card_networks" => `connector_wallets_details.google_pay.cards.${name}`
| _ =>
`connector_wallets_details.google_pay.provider_details.merchant_info.tokenization_specification.parameters.${name}`
}
}
}
let googlePayValueInput = (
~googlePayField: CommonConnectorTypes.inputField,
~googlePayIntegrationType: GPayFlowTypes.googlePayIntegrationType,
) => {
open CommonConnectorHelper
let {\"type", name} = googlePayField
let formName = googlePayNameMapper(~name, ~googlePayIntegrationType)
{
switch \"type" {
| Text => textInput(~field={googlePayField}, ~formName)
| Select => selectInput(~field={googlePayField}, ~formName)
| MultiSelect => multiSelectInput(~field={googlePayField}, ~formName)
| _ => textInput(~field={googlePayField}, ~formName)
}
}
}
let getIntegrationTypeFromConnectorWalletDetailsGooglePay = dict => {
dict
->getDictfromDict("google_pay")
->getDictfromDict("provider_details")
->getDictfromDict("merchant_info")
->getDictfromDict("tokenization_specification")
->getString("type", "PAYMENT_GATEWAY")
}
let getGooglePayIntegrationTypeFromName = (name: string) => {
switch name {
| "PAYMENT_GATEWAY" => #payment_gateway
| "DIRECT" => #direct
| _ => #payment_gateway
}
}
| 2,076 | 9,692 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/GooglePay/GPayFlow/GPayFlowTypes.res | .res | // Type definitions for Google Pay Metadata
type merchantInfoMetadata = {
merchant_id: option<string>,
merchant_name: option<string>,
}
type allowedPaymentMethodsParametersMetadata = {
allowed_auth_methods: array<string>,
allowed_card_networks: array<string>,
}
type tokenizationSpecificationParametersMetadata = {
gateway?: string,
gateway_merchant_id?: string,
\"stripe:version"?: string,
\"stripe:publishableKey"?: string,
public_key?: string,
private_key?: string,
recipient_id?: string,
}
type tokenSpecificationMetadata = {
\"type": string,
parameters: tokenizationSpecificationParametersMetadata,
}
type allowedMethodMetadata = {
\"type": string,
parameters: allowedPaymentMethodsParametersMetadata,
tokenization_specification: tokenSpecificationMetadata,
}
type allowedPaymentMethodsMetadata = array<allowedMethodMetadata>
type googlePayMetadata = {
merchant_info: merchantInfoMetadata,
allowed_payment_methods: allowedPaymentMethodsMetadata,
}
// Type definitions for Google Pay Connector Wallet Details
type googlePayIntegrationType = [#payment_gateway | #direct]
type googlePayIntegrationSteps = Landing | Configure
type tokenizationSpecificationParameters = {
gateway?: string,
gateway_merchant_id?: string,
\"stripe:version"?: string,
\"stripe:publishableKey"?: string,
public_key?: string,
private_key?: string,
recipient_id?: string,
}
type tokenSpecification = {
\"type": string,
parameters: tokenizationSpecificationParameters,
}
type merchantInfo = {
merchant_id: option<string>,
merchant_name: option<string>,
tokenization_specification: tokenSpecification,
}
type providerDetails = {merchant_info: merchantInfo}
type cards = {
allowed_auth_methods: array<string>,
allowed_card_networks: array<string>,
}
type googlePay = {
provider_details: providerDetails,
cards: cards,
}
| 398 | 9,693 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/GooglePay/GPayFlow/GPayFlowHelper.res | .res | module Landing = {
@react.component
let make = (
~googlePayIntegrationType,
~closeModal,
~setGooglePayIntegrationStep,
~setGooglePayIntegrationType,
) => {
open GPayFlowTypes
open AdditionalDetailsSidebarHelper
<>
<div
className="p-6 m-2 cursor-pointer"
onClick={_ => setGooglePayIntegrationType(_ => #payment_gateway)}>
<Card heading="Payment Gateway" isSelected={googlePayIntegrationType === #payment_gateway}>
<div className={` mt-2 text-base text-hyperswitch_black opacity-50 font-normal`}>
{"Integrate Google Pay with your payment gateway."->React.string}
</div>
<div className="flex gap-2 mt-4">
<CustomTag tagText="Faster Configuration" tagSize=4 tagLeftIcon=Some("ellipse-green") />
<CustomTag tagText="Recommended" tagSize=4 tagLeftIcon=Some("ellipse-green") />
</div>
</Card>
</div>
<div
className="p-6 m-2 cursor-pointer" onClick={_ => setGooglePayIntegrationType(_ => #direct)}>
<Card heading="Direct" isSelected={googlePayIntegrationType === #direct}>
<div className={` mt-2 text-base text-hyperswitch_black opacity-50 font-normal`}>
{"Google Pay Decryption at Hyperswitch: Unlock from PSP dependency."->React.string}
</div>
<div className="flex gap-2 mt-4">
<CustomTag tagText="For Web & Mobile" tagSize=4 tagLeftIcon=Some("ellipse-green") />
<CustomTag
tagText="Additional Details Required" tagSize=4 tagLeftIcon=Some("ellipse-green")
/>
</div>
</Card>
</div>
<div className={`flex gap-2 justify-end m-2 p-6`}>
<Button
text="Cancel"
buttonType={Secondary}
onClick={_ => {
closeModal()
}}
/>
<Button
onClick={_ => setGooglePayIntegrationStep(_ => Configure)}
text="Continue"
buttonType={Primary}
/>
</div>
</>
}
}
| 490 | 9,694 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/GooglePay/GPayFlow/GPayDirectFlow.res | .res | @react.component
let make = (
~googlePayFields,
~googlePayIntegrationType,
~closeModal,
~connector,
~setShowWalletConfigurationModal,
~update,
) => {
open LogicUtils
open GPayFlowUtils
let form = ReactFinalForm.useForm()
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let initialGooglePayDict = React.useMemo(() => {
formState.values->getDictFromJsonObject->getDictfromDict("connector_wallets_details")
}, [])
let setFormData = () => {
if connector->isNonEmptyString {
let value = googlePay(
initialGooglePayDict->getDictfromDict("google_pay"),
connector,
~googlePayIntegrationType,
)
form.change("connector_wallets_details.google_pay", value->Identity.genericTypeToJson)
}
}
React.useEffect(() => {
setFormData()
None
}, [connector])
let onSubmit = () => {
let metadata =
formState.values->getDictFromJsonObject->getDictfromDict("metadata")->JSON.Encode.object
setShowWalletConfigurationModal(_ => false)
let _ = update(metadata)
Nullable.null->Promise.resolve
}
let googlePayFieldsForDirect = googlePayFields->Array.filter(field => {
let typedData = field->convertMapObjectToDict->CommonConnectorUtils.inputFieldMapper
directFields->Array.includes(typedData.name)
})
<>
{googlePayFieldsForDirect
->Array.mapWithIndex((field, index) => {
let googlePayField = field->convertMapObjectToDict->CommonConnectorUtils.inputFieldMapper
<div key={index->Int.toString}>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={googlePayValueInput(~googlePayField, ~googlePayIntegrationType)}
/>
</div>
})
->React.array}
<div className={`flex gap-2 justify-end mt-4`}>
<Button
text="Cancel"
buttonType={Secondary}
onClick={_ => {
closeModal()->ignore
}}
/>
<Button
onClick={_ => {
onSubmit()->ignore
}}
text="Proceed"
buttonType={Primary}
buttonState={formState.values->validateGooglePay(connector, ~googlePayIntegrationType)}
/>
</div>
<FormValuesSpy />
</>
}
| 550 | 9,695 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/GooglePay/GPayFlow/GPayPaymentGatewayFlow.res | .res | @react.component
let make = (
~googlePayFields,
~googlePayIntegrationType,
~closeModal,
~connector,
~setShowWalletConfigurationModal,
~update,
) => {
open LogicUtils
open GPayFlowUtils
let form = ReactFinalForm.useForm()
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let initialGooglePayDict = React.useMemo(() => {
formState.values->getDictFromJsonObject->getDictfromDict("connector_wallets_details")
}, [])
let googlePayFieldsForPaymentGateway = googlePayFields->Array.filter(field => {
let typedData = field->convertMapObjectToDict->CommonConnectorUtils.inputFieldMapper
!(ignoreDirectFields->Array.includes(typedData.name))
})
let setFormData = () => {
if connector->isNonEmptyString {
let value = googlePay(
initialGooglePayDict->getDictfromDict("google_pay"),
connector,
~googlePayIntegrationType,
)
form.change("connector_wallets_details.google_pay", value->Identity.genericTypeToJson)
}
}
React.useEffect(() => {
setFormData()
None
}, [connector])
let onSubmit = () => {
let connectorWalletDetails =
formState.values->getDictFromJsonObject->getDictfromDict("connector_wallets_details")
let metadataDetails =
connectorWalletDetails
->getMetadataFromConnectorWalletDetailsGooglePay(connector)
->Identity.genericTypeToJson
form.change("metadata.google_pay", metadataDetails)
setShowWalletConfigurationModal(_ => false)
let _ = update(metadataDetails)
Nullable.null->Promise.resolve
}
<>
{googlePayFieldsForPaymentGateway
->Array.mapWithIndex((field, index) => {
let googlePayField = field->convertMapObjectToDict->CommonConnectorUtils.inputFieldMapper
<div key={index->Int.toString}>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={googlePayValueInput(~googlePayField, ~googlePayIntegrationType)}
/>
</div>
})
->React.array}
<div className={`flex gap-2 justify-end mt-4`}>
<Button
text="Cancel"
buttonType={Secondary}
onClick={_ => {
closeModal()->ignore
}}
/>
<Button
onClick={_ => {
onSubmit()->ignore
}}
text="Proceed"
buttonType={Primary}
buttonState={formState.values->validateGooglePay(connector, ~googlePayIntegrationType)}
/>
</div>
<FormValuesSpy />
</>
}
| 597 | 9,696 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/BankDebit/BankDebitUtils.res | .res | open LogicUtils
open BankDebitTypes
let dropdownOptions = (connectors: array<string>) => {
connectors->Array.map((item): SelectBox.dropdownOption => {
label: item->snakeToTitle,
value: item,
})
}
let itemToObjMapper = dict => {
{
payment_method: dict->getString("payment_method", ""),
payment_method_type: dict->getString("payment_method_type", ""),
connector_name: dict->getString("connector_name", ""),
mca_id: dict->getString("mca_id", ""),
}
}
let validateSelectedPMAuth = (values, paymentMethodType) => {
let existingPaymentMethodValues =
values
->getDictFromJsonObject
->getDictfromDict("pm_auth_config")
->getArrayFromDict("enabled_payment_methods", [])
->JSON.Encode.array
->getArrayDataFromJson(itemToObjMapper)
let newPaymentMethodValues =
existingPaymentMethodValues->Array.filter(item => item.payment_method_type == paymentMethodType)
newPaymentMethodValues->Array.length > 0 ? Button.Normal : Button.Disabled
}
| 239 | 9,697 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/BankDebit/BankDebitTypes.res | .res | type pmAuthPaymentMethods = {
payment_method: string,
payment_method_type: string,
connector_name: string,
mca_id: string,
}
| 34 | 9,698 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/BankDebit/BankDebit.res | .res | module PMAuthProcessorInput = {
@react.component
let make = (
~options: array<SelectBox.dropdownOption>,
~fieldsArray: array<ReactFinalForm.fieldRenderProps>,
~paymentMethod: string,
~paymentMethodType: string,
~getPMConnectorId: ConnectorTypes.connectorTypes => string,
) => {
open LogicUtils
let (currentSelection, setCurrentSelection) = React.useState(_ => "")
let enabledList = (
fieldsArray->Array.get(0)->Option.getOr(ReactFinalForm.fakeFieldRenderProps)
).input
let input: ReactFinalForm.fieldRenderPropsInput = {
name: "string",
onBlur: _ => (),
onChange: ev => {
let value = ev->Identity.formReactEventToString
let getPaymentMethodsObject = connector => {
open BankDebitTypes
{
payment_method: paymentMethod,
payment_method_type: paymentMethodType,
connector_name: connector,
mca_id: getPMConnectorId(
connector->ConnectorUtils.getConnectorNameTypeFromString(
~connectorType=PMAuthenticationProcessor,
),
),
}
}
if value->isNonEmptyString {
let paymentMethodsObject = value->getPaymentMethodsObject
setCurrentSelection(_ => value)
let existingPaymentMethodsArray =
enabledList.value->getArrayDataFromJson(BankDebitUtils.itemToObjMapper)
let newPaymentMethodsArray =
existingPaymentMethodsArray->Array.filter(item =>
item.payment_method_type !== paymentMethodType
)
newPaymentMethodsArray->Array.push(paymentMethodsObject)
enabledList.onChange(newPaymentMethodsArray->Identity.anyTypeToReactEvent)
}
},
onFocus: _ => (),
value: currentSelection->JSON.Encode.string,
checked: true,
}
<SelectBox.BaseDropdown
allowMultiSelect=false
buttonText="Select PM Authentication Processor"
input
options
hideMultiSelectButtons=false
showSelectionAsChips=true
customButtonStyle="w-full"
fullLength=true
dropdownCustomWidth="w-full"
dropdownClassName={`${options->PaymentMethodConfigUtils.dropdownClassName}`}
/>
}
}
@react.component
let make = (
~setShowWalletConfigurationModal,
~update,
~paymentMethod,
~paymentMethodType,
~setInitialValues,
) => {
open LogicUtils
open BankDebitUtils
let connectorsListPMAuth = ConnectorInterface.useConnectorArrayMapper(
~interface=ConnectorInterface.connectorInterfaceV1,
~retainInList=PMAuthProcessor,
)
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let form = ReactFinalForm.useForm()
let pmAuthConnectorOptions =
connectorsListPMAuth->Array.map(item => item.connector_name)->removeDuplicate->dropdownOptions
let getPMConnectorId = (connector: ConnectorTypes.connectorTypes) => {
let connectorData = connectorsListPMAuth->Array.find(item => {
item.connector_name == connector->ConnectorUtils.getConnectorNameString
})
switch connectorData {
| Some(connectorData) => connectorData.merchant_connector_id
| None => ""
}
}
let onCancelClick = () => {
let existingPaymentMethodValues =
formState.values
->getDictFromJsonObject
->getDictfromDict("pm_auth_config")
->getArrayFromDict("enabled_payment_methods", [])
->JSON.Encode.array
->getArrayDataFromJson(itemToObjMapper)
let newPaymentMethodValues =
existingPaymentMethodValues->Array.filter(item =>
item.payment_method_type !== paymentMethodType
)
form.change(
"pm_auth_config.enabled_payment_methods",
newPaymentMethodValues->Identity.genericTypeToJson,
)
}
let closeModal = () => {
update()
onCancelClick()
setShowWalletConfigurationModal(_ => false)
}
let onSubmit = () => {
setShowWalletConfigurationModal(_ => false)
setInitialValues(_ => formState.values)
update()
Nullable.null->Promise.resolve
}
let renderValueInp = (options: array<SelectBox.dropdownOption>) => (
fieldsArray: array<ReactFinalForm.fieldRenderProps>,
) => {
<PMAuthProcessorInput options fieldsArray paymentMethod paymentMethodType getPMConnectorId />
}
let valueInput = (inputArg: PaymentMethodConfigTypes.valueInput) => {
open FormRenderer
makeMultiInputFieldInfoOld(
~label=`${inputArg.label}`,
~comboCustomInput=renderValueInp(inputArg.options),
~inputFields=[makeInputFieldInfo(~name=`${inputArg.name1}`), makeInputFieldInfo(~name=``)],
~isRequired=true,
(),
)
}
<div className="p-4">
<FormRenderer.FieldRenderer
field={valueInput({
name1: `pm_auth_config.enabled_payment_methods`,
name2: ``,
label: `Select the open banking verification provider to verify the bank accounts`,
options: pmAuthConnectorOptions,
})}
labelTextStyleClass="pt-2 pb-2 text-fs-13 text-jp-gray-900 dark:text-jp-gray-text_darktheme dark:text-opacity-50 ml-1 font-semibold"
/>
<div className={`flex gap-2 justify-end mt-4`}>
<Button text="Cancel" buttonType={Secondary} onClick={_ => closeModal()} />
<Button
onClick={_ => {
onSubmit()->ignore
}}
text="Proceed"
buttonType={Primary}
buttonState={validateSelectedPMAuth(formState.values, paymentMethodType)}
/>
</div>
<FormValuesSpy />
</div>
}
| 1,258 | 9,699 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/ApplePay/ApplePayIntegrationUtils.res | .res | open ApplePayIntegrationTypes
open LogicUtils
let paymentRequest = (dict, integrationType) => {
let paymentRequestDict =
dict
->getDictfromDict((integrationType: applePayIntegrationType :> string))
->getDictfromDict("payment_request_data")
let sessionTokenDict =
dict
->getDictfromDict((integrationType: applePayIntegrationType :> string))
->getDictfromDict("session_token_data")
{
label: sessionTokenDict->getString("display_name", "apple"),
supported_networks: paymentRequestDict->getStrArrayFromDict(
"supported_networks",
["visa", "masterCard", "amex", "discover"],
),
merchant_capabilities: paymentRequestDict->getStrArrayFromDict(
"merchant_capabilities",
["supports3DS"],
),
}
}
let sessionToken = (dict): sessionTokenData => {
let sessionTokenDict =
dict
->getDictfromDict((#manual: applePayIntegrationType :> string))
->getDictfromDict("session_token_data")
{
initiative: sessionTokenDict->getOptionString("initiative"),
certificate: sessionTokenDict->getOptionString("certificate"),
display_name: sessionTokenDict->getOptionString("display_name"),
certificate_keys: sessionTokenDict->getOptionString("certificate_keys"),
initiative_context: sessionTokenDict->getOptionString("initiative_context"),
merchant_identifier: sessionTokenDict->getOptionString("merchant_identifier"),
merchant_business_country: sessionTokenDict->getOptionString("merchant_business_country"),
payment_processing_details_at: sessionTokenDict->getOptionString(
"payment_processing_details_at",
),
payment_processing_certificate: sessionTokenDict->getOptionString(
"payment_processing_certificate",
),
payment_processing_certificate_key: sessionTokenDict->getOptionString(
"payment_processing_certificate_key",
),
}
}
let sessionTokenSimplified = (dict): sessionTokenSimplified => {
let sessionTokenDict =
dict
->getDictfromDict((#simplified: applePayIntegrationType :> string))
->getDictfromDict("session_token_data")
{
initiative_context: sessionTokenDict->getOptionString("initiative_context"),
merchant_business_country: sessionTokenDict->getOptionString("merchant_business_country"),
}
}
let manual = (dict): manual => {
{
session_token_data: dict->sessionToken,
payment_request_data: dict->paymentRequest(#manual),
}
}
let simplified = (dict): simplified => {
{
session_token_data: dict->sessionTokenSimplified,
payment_request_data: dict->paymentRequest(#simplified),
}
}
let zenApplePayConfig = dict => {
{
terminal_uuid: dict->getOptionString("terminal_uuid"),
pay_wall_secret: dict->getOptionString("pay_wall_secret"),
}
}
let applePayCombined = (dict, applePayIntegrationType) => {
let data: applePayConfig = switch applePayIntegrationType {
| #manual => #manual(dict->manual)
| #simplified => #simplified(dict->simplified)
}
let dict = Dict.make()
let _ = switch data {
| #manual(data) =>
dict->Dict.set((#manual: applePayIntegrationType :> string), data->Identity.genericTypeToJson)
| #simplified(data) =>
dict->Dict.set(
(#simplified: applePayIntegrationType :> string),
data->Identity.genericTypeToJson,
)
}
dict
}
let applePay = (
dict,
~connector: string="",
~applePayIntegrationType: option<applePayIntegrationType>=None,
(),
): applePay => {
open ConnectorUtils
open ConnectorTypes
switch connector->getConnectorNameTypeFromString {
| Processors(ZEN) => Zen(dict->zenApplePayConfig)
| _ => {
let integrationType = applePayIntegrationType->Option.getOr(#manual)
let data = {
apple_pay_combined: applePayCombined(dict, integrationType)->JSON.Encode.object,
}
ApplePayCombined(data)
}
}
}
let applePayNameMapper = (~name, ~integrationType: option<applePayIntegrationType>) => {
switch name {
| `terminal_uuid` => `metadata.apple_pay.${name}`
| `pay_wall_secret` => `metadata.apple_pay.${name}`
| _ =>
`metadata.apple_pay_combined.${(integrationType->Option.getOr(
#manual,
): applePayIntegrationType :> string)}.session_token_data.${name}`
}
}
let paymentProcessingMapper = state => {
switch state->String.toLowerCase {
| "connector" => #Connector
| "hyperswitch" => #Hyperswitch
| _ => #Connector
}
}
let initiativeMapper = state => {
switch state->String.toLowerCase {
| "ios" => #ios
| "web" => #web
| _ => #web
}
}
let applePayIntegrationTypeMapper = state => {
switch state->String.toLowerCase {
| "manual" => #manual
| "simplified" => #simplified
| _ => #manual
}
}
let ignoreFieldsonSimplified = [
"certificate",
"certificate_keys",
"merchant_identifier",
"display_name",
"initiative",
"payment_processing_details_at",
]
let validateZenFlow = values => {
let data =
values
->getDictFromJsonObject
->getDictfromDict("metadata")
->getDictfromDict("apple_pay")
->zenApplePayConfig
data.terminal_uuid->Option.isSome && data.pay_wall_secret->Option.isSome
? Button.Normal
: Button.Disabled
}
let validateInitiative = data => {
switch data.initiative {
| Some(value) => value->initiativeMapper == #web ? data.initiative_context->Option.isSome : true
| None => false
}
}
let validatePaymentProcessingDetailsAt = data => {
switch data.payment_processing_details_at {
| Some(value) =>
value->paymentProcessingMapper == #Hyperswitch
? data.payment_processing_certificate->Option.isSome &&
data.payment_processing_certificate_key->Option.isSome
: true
| None => false
}
}
let validateManualFlow = values => {
let data =
values
->getDictFromJsonObject
->getDictfromDict("metadata")
->getDictfromDict("apple_pay_combined")
->sessionToken
data->validateInitiative &&
data.certificate->Option.isSome &&
data.display_name->Option.isSome &&
data.merchant_identifier->Option.isSome &&
data->validatePaymentProcessingDetailsAt
? Button.Normal
: Button.Disabled
}
let validateSimplifedFlow = values => {
let data =
values
->getDictFromJsonObject
->getDictfromDict("metadata")
->getDictfromDict("apple_pay_combined")
->sessionTokenSimplified
data.initiative_context->Option.isSome && data.merchant_business_country->Option.isSome
? Button.Normal
: Button.Disabled
}
let constructVerifyApplePayReq = (values, connectorID) => {
let context =
values
->getDictFromJsonObject
->getDictfromDict("metadata")
->getDictfromDict("apple_pay_combined")
->sessionTokenSimplified
let domainName = context.initiative_context->Option.getOr("")
let data = {
domain_names: [domainName],
merchant_connector_account_id: connectorID,
}->JSON.stringifyAny
let body = switch data {
| Some(val) => val->LogicUtils.safeParse
| None => Dict.make()->JSON.Encode.object
}
body
}
| 1,673 | 9,700 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/ApplePay/ApplePayIntegrationTypes.res | .res | type sessionTokenData = {
initiative: option<string>,
certificate: option<string>,
display_name: option<string>,
certificate_keys: option<string>,
initiative_context: option<string>,
merchant_identifier: option<string>,
merchant_business_country: option<string>,
payment_processing_details_at: option<string>,
payment_processing_certificate: option<string>,
payment_processing_certificate_key: option<string>,
}
type sessionTokenSimplified = {
initiative_context: option<string>,
merchant_business_country: option<string>,
}
type paymentRequestData = {
label: string,
supported_networks: array<string>,
merchant_capabilities: array<string>,
}
type manual = {
session_token_data: sessionTokenData,
payment_request_data: paymentRequestData,
}
type simplified = {
session_token_data: sessionTokenSimplified,
payment_request_data: paymentRequestData,
}
type applePayIntegrationType = [#manual | #simplified]
type applePayConfig = [#manual(manual) | #simplified(simplified)]
type applePayIntegrationSteps = Landing | Configure | Verify
type simplifiedApplePayIntegartionTypes = EnterUrl | DownloadFile | HostUrl
type applePayCombined = {apple_pay_combined: Js.Json.t}
type zenConfig = {
terminal_uuid: option<string>,
pay_wall_secret: option<string>,
}
type applePay = ApplePayCombined(applePayCombined) | Zen(zenConfig)
type verifyApplePay = {
domain_names: array<string>,
merchant_connector_account_id: string,
}
type paymentProcessingState = [#Connector | #Hyperswitch]
type initiativeState = [#web | #ios]
type inputType = Text | Toggle | Select
type inputField = {
name: string,
label: string,
placeholder: string,
required: bool,
options: array<string>,
\"type": inputType,
}
| 387 | 9,701 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/ApplePay/ApplePayManualFlow.res | .res | open ApplePayIntegrationTypes
module PaymentProcessingDetailsAt = {
@react.component
let make = (~applePayField) => {
open LogicUtils
open ApplePayIntegrationUtils
let form = ReactFinalForm.useForm()
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let initalFormValue =
formState.values
->getDictFromJsonObject
->getDictfromDict("metadata")
->getDictfromDict("apple_pay_combined")
->manual
let initalProcessingAt =
initalFormValue.session_token_data.payment_processing_details_at
->Option.getOr((#Connector: paymentProcessingState :> string))
->paymentProcessingMapper
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let (processingAt, setProcessingAt) = React.useState(_ => initalProcessingAt)
let onChangeItem = (event: ReactEvent.Form.t) => {
let value =
event->Identity.formReactEventToString->ApplePayIntegrationUtils.paymentProcessingMapper
setProcessingAt(_ => value)
if value === #Connector {
form.change(
`${ApplePayIntegrationUtils.applePayNameMapper(
~name="payment_processing_certificate",
~integrationType=Some(#manual),
)}`,
JSON.Encode.null,
)
form.change(
`${ApplePayIntegrationUtils.applePayNameMapper(
~name="payment_processing_certificate_key",
~integrationType=Some(#manual),
)}`,
JSON.Encode.null,
)
}
}
<>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={CommonConnectorHelper.radioInput(
~field=applePayField,
~formName=`${ApplePayIntegrationUtils.applePayNameMapper(
~name=applePayField.name,
~integrationType=Some(#manual),
)}`,
~fill=textColor.primaryNormal,
~onItemChange=onChangeItem,
(),
)}
/>
{switch processingAt {
| #Hyperswitch =>
<div>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={FormRenderer.makeFieldInfo(
~label="Payment Processing Certificate",
~name={
`${ApplePayIntegrationUtils.applePayNameMapper(
~name="payment_processing_certificate",
~integrationType=Some(#manual),
)}`
},
~placeholder={`Enter Processing Certificate`},
~customInput=InputFields.textInput(),
~isRequired=true,
)}
/>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={FormRenderer.makeFieldInfo(
~label="Payment Processing Key",
~name={
`${ApplePayIntegrationUtils.applePayNameMapper(
~name="payment_processing_certificate_key",
~integrationType=Some(#manual),
)}`
},
~placeholder={`Enter Processing Key`},
~customInput=InputFields.multiLineTextInput(
~rows=Some(10),
~cols=Some(100),
~isDisabled=false,
~customClass="",
~leftIcon=React.null,
~maxLength=10000,
),
~isRequired=true,
)}
/>
</div>
| _ => React.null
}}
</>
}
}
module Initiative = {
@react.component
let make = (~applePayField) => {
open LogicUtils
open ApplePayIntegrationUtils
let form = ReactFinalForm.useForm()
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let initalFormValue =
formState.values
->getDictFromJsonObject
->getDictfromDict("metadata")
->getDictfromDict("apple_pay_combined")
->manual
let initalInitiative =
initalFormValue.session_token_data.initiative
->Option.getOr((#ios: initiativeState :> string))
->initiativeMapper
let (initiative, setInitiative) = React.useState(_ => initalInitiative)
let onChangeItem = (event: ReactEvent.Form.t) => {
let value = event->Identity.formReactEventToString->initiativeMapper
setInitiative(_ => value)
if value === #ios {
form.change(
`${ApplePayIntegrationUtils.applePayNameMapper(
~name="initiative_context",
~integrationType=Some(#manual),
)}`,
JSON.Encode.null,
)
}
}
let domainValues = [
[("label", "IOS/WEB"->JSON.Encode.string), ("value", "web"->JSON.Encode.string)]
->Dict.fromArray
->JSON.Encode.object,
[("label", "IOS"->JSON.Encode.string), ("value", "ios"->JSON.Encode.string)]
->Dict.fromArray
->JSON.Encode.object,
]
let initiativeOptions = domainValues->Array.map(item => {
let dict = item->getDictFromJsonObject
let a: SelectBox.dropdownOption = {
label: dict->getString("label", ""),
value: dict->getString("value", ""),
}
a
})
<>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={CommonConnectorHelper.selectInput(
~field={applePayField},
~formName={
ApplePayIntegrationUtils.applePayNameMapper(
~name="initiative",
~integrationType=Some(#manual),
)
},
~onItemChange=onChangeItem,
~opt=Some(initiativeOptions),
)}
/>
{switch initiative {
| #web =>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={CommonConnectorHelper.textInput(
~field={applePayField},
~formName={
ApplePayIntegrationUtils.applePayNameMapper(
~name="initiative_context",
~integrationType=Some(#manual),
)
},
)}
/>
| _ => React.null
}}
</>
}
}
@react.component
let make = (
~applePayFields,
~merchantBusinessCountry,
~setApplePayIntegrationSteps,
~setVefifiedDomainList,
) => {
open LogicUtils
open ApplePayIntegrationUtils
open ApplePayIntegrationHelper
let form = ReactFinalForm.useForm()
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let initalFormValue =
formState.values
->getDictFromJsonObject
->getDictfromDict("metadata")
->getDictfromDict("apple_pay_combined")
let setFormData = () => {
let value = applePayCombined(initalFormValue, #manual)
form.change("metadata.apple_pay_combined", value->Identity.genericTypeToJson)
}
React.useEffect(() => {
let _ = setFormData()
None
}, [])
let onSubmit = () => {
let data =
formState.values
->getDictFromJsonObject
->getDictfromDict("metadata")
->getDictfromDict("apple_pay_combined")
->manual
let domainName = data.session_token_data.initiative_context->Option.getOr("")
setVefifiedDomainList(_ => [domainName])
setApplePayIntegrationSteps(_ => ApplePayIntegrationTypes.Verify)
Nullable.null->Promise.resolve
}
let applePayManualFields =
applePayFields
->Array.mapWithIndex((field, index) => {
let applePayField = field->convertMapObjectToDict->CommonConnectorUtils.inputFieldMapper
let {name} = applePayField
<div key={index->Int.toString}>
{switch name {
| "payment_processing_details_at" => <PaymentProcessingDetailsAt applePayField />
| "initiative" => <Initiative applePayField />
| "initiative_context" => React.null
| "merchant_business_country" =>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={CommonConnectorHelper.selectInput(
~field={applePayField},
~opt={Some(merchantBusinessCountry)},
~formName={
ApplePayIntegrationUtils.applePayNameMapper(
~name="merchant_business_country",
~integrationType=Some(#manual),
)
},
)}
/>
| _ =>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={applePayValueInput(~applePayField, ~integrationType=Some(#manual))}
/>
}}
</div>
})
->React.array
<>
{applePayManualFields}
<div className="w-full flex gap-2 justify-end p-6">
<Button
text="Go Back"
buttonType={Secondary}
onClick={_ => {
setApplePayIntegrationSteps(_ => Landing)
}}
/>
<Button
text="Verify & Enable"
buttonType={Primary}
onClick={_ => {
onSubmit()->ignore
}}
buttonState={formState.values->validateManualFlow}
/>
</div>
// <FormValuesSpy />
</>
}
| 2,051 | 9,702 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/ApplePay/ApplePayIntegrationHelper.res | .res | open ApplePayIntegrationTypes
module SimplifiedHelper = {
@react.component
let make = (~customElement=?, ~heading="", ~stepNumber="1", ~subText=None) => {
let {globalUIConfig: {backgroundColor, font: {textColor}}} = React.useContext(
ThemeProvider.themeContext,
)
let bgColor = "bg-white"
let stepColor = `${backgroundColor} text-white py-px px-2`
<div className={`flex flex-col py-8 px-6 gap-3 ${bgColor} cursor-pointer`}>
<div className={"flex justify-between "}>
<div className="flex gap-4">
<div>
<p className={`${stepColor} font-medium`}> {stepNumber->React.string} </p>
</div>
<div>
<p className={`font-medium text-base ${textColor.primaryNormal}`}>
{heading->React.string}
</p>
<RenderIf condition={subText->Option.isSome}>
<p className={`mt-2 text-base text-hyperswitch_black opacity-50 font-normal`}>
{subText->Option.getOr("")->React.string}
</p>
</RenderIf>
{switch customElement {
| Some(element) => element
| _ => React.null
}}
</div>
</div>
</div>
</div>
}
}
module HostURL = {
@react.component
let make = (~prefix="") => {
let fieldInputVal = ReactFinalForm.useField(`${prefix}`).input
let fieldInput = switch fieldInputVal.value->JSON.Decode.string {
| Some(val) => val->LogicUtils.isNonEmptyString ? val : "domain_name"
| None => "domain_name"
}
<p className="mt-2">
{`${fieldInput}/.well-known/apple-developer-merchantid-domain-association`->React.string}
</p>
}
}
module SampleEmail = {
@react.component
let make = () => {
let showToast = ToastState.useShowToast()
let (isTextVisible, setIsTextVisible) = React.useState(_ => false)
let businessDescription = "<One sentence about your business>. The business operates across <XX> countries and has customers across the world."
let featureReqText = "We are using Hyperswitch, a Level 1 PCI DSS 3.2.1 compliant Payments Orchestrator, to manage payments on our website. In addition to Stripe, since we are using other processors as well to process payments across multiple geographies, we wanted to use Hyperswitch's Payment Processing certificate to decrypt Apple pay tokens and send the decrypted Apple pay tokens to Stripe. So, please enable processing decrypted Apple pay token feature on our Stripe account. We've attached Hyperswitch's PCI DSS AoC for reference."
let emailContent = `Stripe Account id: <Enter your account id>
A detailed business description:
${businessDescription}
Feature Request:
${featureReqText}`
let truncatedText = isTextVisible
? featureReqText
: featureReqText->String.slice(~start=0, ~end=50)
let truncatedTextElement =
<p className="flex gap-2">
{truncatedText->React.string}
<p
className="cursor-pointer text-blue-400 text-xl"
onClick={_ => setIsTextVisible(_ => true)}>
{"..."->React.string}
</p>
</p>
<div className="flex flex-col">
<span className="mt-2 text-base font-normal">
<span className="text-hyperswitch_black opacity-50">
{"Since the Apple Pay Web Domain flow involves decryption at Hyperswitch, you would need to write to Stripe support (support@stripe.com) to get this feature enabled for your Stripe account. You can use the following text in the email, attach our"->React.string}
</span>
<Link
to_={`/compliance`}
openInNewTab=false
className="text-blue-600 underline underline-offset-2 px-2 !opacity-100">
{"PCI DSS AoC certificate"->React.string}
</Link>
<span className="text-hyperswitch_black opacity-50">
{"and copy our Support team (biz@hyperswitch.io):"->React.string}
</span>
</span>
<div className="border border-gray-400 rounded-md flex flex-row gap-8 p-4 mt-4 bg-gray-200">
<div className="flex flex-col gap-4 ">
<span>
{"Stripe Account id: <Enter your account id:you can find it "->React.string}
<a
className="underline text-blue-400 underline-offset-1"
href="https://dashboard.stripe.com/settings/user">
{"here"->React.string}
</a>
<span> {">"->React.string} </span>
</span>
<span>
<p> {"A detailed business description:"->React.string} </p>
{businessDescription->React.string}
</span>
<span>
<p> {"Feature Request:"->React.string} </p>
{isTextVisible ? truncatedText->React.string : truncatedTextElement}
</span>
</div>
<Icon
name="nd-copy"
className="cursor-pointer h-fit w-fit"
onClick={_ => {
Clipboard.writeText(emailContent)
showToast(~message="Copied to Clipboard!", ~toastType=ToastSuccess)
}}
/>
</div>
</div>
}
}
module CustomTag = {
@react.component
let make = (~tagText="", ~tagSize=5, ~tagLeftIcon=None, ~tagCustomStyle="") => {
<div
className={`flex items-center gap-1 shadow-connectorTagShadow border rounded-full px-2 py-1 ${tagCustomStyle}`}>
{switch tagLeftIcon {
| Some(icon) =>
<div>
<Icon name={icon} size={tagSize} />
</div>
| None => React.null
}}
<div className={"text-hyperswitch_black text-sm font-medium text-green-960"}>
{tagText->React.string}
</div>
</div>
}
}
module InfoCard = {
@react.component
let make = (~children, ~customInfoStyle="") => {
<div
className={`rounded border bg-blue-800 border-blue-700 dark:border-blue-700 relative flex w-full p-6 `}>
<Icon className=customInfoStyle name="info-circle-unfilled" size=16 />
<div> {children} </div>
</div>
}
}
let applePayValueInput = (
~applePayField: CommonConnectorTypes.inputField,
~integrationType: option<applePayIntegrationType>=None,
) => {
open CommonConnectorHelper
let {\"type", name} = applePayField
let formName = ApplePayIntegrationUtils.applePayNameMapper(~name, ~integrationType)
{
switch \"type" {
| Text => textInput(~field={applePayField}, ~formName)
| Select => selectInput(~field={applePayField}, ~formName)
| MultiSelect => multiSelectInput(~field={applePayField}, ~formName)
| _ => textInput(~field={applePayField}, ~formName)
}
}
}
| 1,640 | 9,703 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/ApplePay/ApplePayZen.res | .res | @react.component
let make = (~applePayFields, ~update, ~closeModal, ~setShowWalletConfigurationModal) => {
open LogicUtils
open ApplePayIntegrationUtils
open ApplePayIntegrationHelper
let form = ReactFinalForm.useForm()
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let initalFormValue =
formState.values
->getDictFromJsonObject
->getDictfromDict("metadata")
->getDictfromDict("apple_pay")
let setFormData = () => {
let value = zenApplePayConfig(initalFormValue)
form.change("metadata.apple_pay", value->Identity.genericTypeToJson)
}
React.useEffect(() => {
setFormData()
None
}, [])
let onSubmit = () => {
let metadata =
formState.values->getDictFromJsonObject->getDictfromDict("metadata")->JSON.Encode.object
let _ = update(metadata)
setShowWalletConfigurationModal(_ => false)
Nullable.null->Promise.resolve
}
let applePayManualFields =
applePayFields
->Array.mapWithIndex((field, index) => {
let applePayField = field->convertMapObjectToDict->CommonConnectorUtils.inputFieldMapper
<div key={index->Int.toString}>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={applePayValueInput(~applePayField)}
/>
</div>
})
->React.array
<>
{applePayManualFields}
<div className="w-full flex gap-2 justify-end p-6">
<Button
text="Go Back"
buttonType={Secondary}
onClick={_ => {
// setShowWalletConfigurationModal(_ => false)
closeModal()
}}
/>
<Button
text="Verify & Enable"
buttonType={Primary}
onClick={_ => {
onSubmit()->ignore
}}
buttonState={formState.values->validateZenFlow}
/>
</div>
</>
}
| 459 | 9,704 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/ApplePay/ApplePayIntegration.res | .res | module Verified = {
@react.component
let make = (
~verifiedDomainList,
~setApplePayIntegrationType,
~appleIntegrationType,
~setApplePayIntegrationSteps,
~setShowWalletConfigurationModal,
~update,
) => {
open ApplePayIntegrationHelper
open ApplePayIntegrationTypes
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let form = ReactFinalForm.useForm()
let onSubmit = () => {
open LogicUtils
let data =
formState.values
->getDictFromJsonObject
->getDictfromDict("metadata")
->getDictfromDict("apple_pay_combined")
let applePayData = ApplePayIntegrationUtils.applePay(
data,
~applePayIntegrationType=Some(appleIntegrationType),
(),
)
switch applePayData {
| ApplePayCombined(data) =>
form.change(
"metadata.apple_pay_combined",
data.apple_pay_combined->Identity.genericTypeToJson,
)
| _ => ()
}
let metadata =
formState.values->getDictFromJsonObject->getDictfromDict("metadata")->JSON.Encode.object
let _ = update(metadata)
setShowWalletConfigurationModal(_ => false)
}
<>
<div className="p-6 m-2 cursor-pointer">
<p className="text-xs font-medium mt-4"> {" Web Domains"->React.string} </p>
{verifiedDomainList
->Array.mapWithIndex((domainUrl, index) => {
<div
key={Int.toString(index)}
className="mt-4 cursor-pointer"
onClick={_ => setApplePayIntegrationType(_ => #manual)}>
<div className={`relative w-full p-6 rounded flex flex-col justify-between border `}>
<div className="flex justify-between">
<div className={`font-medium text-base text-hyperswitch_black `}>
{domainUrl->String.length > 0 ? domainUrl->React.string : "Default"->React.string}
</div>
<div>
{switch appleIntegrationType {
| #simplified =>
<CustomTag
tagText="Verified"
tagSize=4
tagLeftIcon=Some("ellipse-green")
tagCustomStyle="bg-hyperswitch_green_trans"
/>
| #manual =>
<Icon
onClick={_ => setApplePayIntegrationSteps(_ => Configure)}
name={"arrow-right"}
size={15}
/>
}}
</div>
</div>
</div>
</div>
})
->React.array}
<div className={`flex gap-2 justify-end mt-4`}>
<Button
text="Reconfigure"
buttonType={Secondary}
onClick={_ => {
setApplePayIntegrationSteps(_ => Landing)
}}
/>
<Button
onClick={_ => {
onSubmit()
}}
text="Proceed"
buttonType={Primary}
/>
</div>
</div>
</>
}
}
module Landing = {
@react.component
let make = (
~connector,
~appleIntegrationType,
~closeModal,
~setApplePayIntegrationSteps,
~setApplePayIntegrationType,
) => {
open ApplePayIntegrationTypes
open AdditionalDetailsSidebarHelper
<>
{switch connector->ConnectorUtils.getConnectorNameTypeFromString {
| Processors(STRIPE)
| Processors(BANKOFAMERICA)
| Processors(CYBERSOURCE)
| Processors(FIUU) =>
<div
className="p-6 m-2 cursor-pointer"
onClick={_ => setApplePayIntegrationType(_ => #simplified)}>
<Card heading="Web Domain" isSelected={appleIntegrationType === #simplified}>
<div className={` mt-2 text-base text-hyperswitch_black opacity-50 font-normal`}>
{"Get Apple Pay enabled on your web domains by hosting a verification file, that’s it."->React.string}
</div>
<div className="flex gap-2 mt-4">
<CustomTag
tagText="Faster Configuration" tagSize=4 tagLeftIcon=Some("ellipse-green")
/>
<CustomTag tagText="Recommended" tagSize=4 tagLeftIcon=Some("ellipse-green") />
</div>
</Card>
</div>
| _ => React.null
}}
<div
className="p-6 m-2 cursor-pointer" onClick={_ => setApplePayIntegrationType(_ => #manual)}>
<Card heading="iOS Certificate" isSelected={appleIntegrationType === #manual}>
<div className={` mt-2 text-base text-hyperswitch_black opacity-50 font-normal`}>
<CustomSubText />
</div>
<div className="flex gap-2 mt-4">
<CustomTag tagText="For Web & Mobile" tagSize=4 tagLeftIcon=Some("ellipse-green") />
<CustomTag
tagText="Additional Details Required" tagSize=4 tagLeftIcon=Some("ellipse-green")
/>
</div>
</Card>
</div>
<div className={`flex gap-2 justify-end m-2 p-6`}>
<Button
text="Cancel"
buttonType={Secondary}
onClick={_ => {
closeModal()
}}
/>
<Button
onClick={_ => setApplePayIntegrationSteps(_ => Configure)}
text="Continue"
buttonType={Primary}
/>
</div>
</>
}
}
@react.component
let make = (~connector, ~setShowWalletConfigurationModal, ~update, ~onCloseClickCustomFun) => {
open APIUtils
open LogicUtils
open AdditionalDetailsSidebarHelper
open ApplePayIntegrationTypes
let getURL = useGetURL()
let fetchDetails = useGetMethod()
let (appleIntegrationType, setApplePayIntegrationType) = React.useState(_ => #manual)
let (applePayIntegrationStep, setApplePayIntegrationSteps) = React.useState(_ => Landing)
let (merchantBusinessCountry, setMerchantBusinessCountry) = React.useState(_ => [])
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Success)
let (verifiedDomainList, setVefifiedDomainList) = React.useState(_ => [])
let applePayFields = React.useMemo(() => {
try {
if connector->isNonEmptyString {
let dict =
Window.getConnectorConfig(connector)
->getDictFromJsonObject
->getDictfromDict("metadata")
->getArrayFromDict("apple_pay", [])
dict
} else {
[]
}
} catch {
| Exn.Error(e) => {
Js.log2("FAILED TO LOAD CONNECTOR CONFIG", e)
[]
}
}
}, [connector])
let getProcessorDetails = async () => {
try {
setScreenState(_ => Loading)
let paymentMethoConfigUrl = getURL(~entityName=V1(PAYMENT_METHOD_CONFIG), ~methodType=Get)
let res = await fetchDetails(
`${paymentMethoConfigUrl}?connector=${connector}&paymentMethodType=apple_pay`,
)
let countries =
res
->getDictFromJsonObject
->getArrayFromDict("countries", [])
->Array.map(item => {
let dict = item->getDictFromJsonObject
let a: SelectBox.dropdownOption = {
label: dict->getString("name", ""),
value: dict->getString("code", ""),
}
a
})
setMerchantBusinessCountry(_ => countries)
setScreenState(_ => Success)
} catch {
| _ => setScreenState(_ => Success)
}
}
let closeModal = () => {
onCloseClickCustomFun()
setShowWalletConfigurationModal(_ => false)
}
React.useEffect(() => {
if connector->String.length > 0 {
switch connector->ConnectorUtils.getConnectorNameTypeFromString {
| Processors(STRIPE)
| Processors(BANKOFAMERICA)
| Processors(CYBERSOURCE) =>
setApplePayIntegrationType(_ => #simplified)
| _ => setApplePayIntegrationType(_ => #manual)
}
getProcessorDetails()->ignore
}
None
}, [connector])
<PageLoaderWrapper
screenState={screenState}
customLoader={<div className="mt-60 w-scrren flex flex-col justify-center items-center">
<div className={`animate-spin mb-1`}>
<Icon name="spinner" size=20 />
</div>
</div>}
sectionHeight="!h-screen">
<div>
<Heading title="Apple Pay" iconName="applepay" />
{switch connector->ConnectorUtils.getConnectorNameTypeFromString {
| Processors(ZEN) =>
<ApplePayZen applePayFields update closeModal setShowWalletConfigurationModal />
| _ =>
switch applePayIntegrationStep {
| Landing =>
<Landing
connector
closeModal
setApplePayIntegrationSteps
appleIntegrationType
setApplePayIntegrationType
/>
| Configure =>
switch appleIntegrationType {
| #simplified =>
<ApplePaySimplifiedFlow
applePayFields
merchantBusinessCountry
setApplePayIntegrationSteps
setVefifiedDomainList
connector
/>
| #manual =>
<ApplePayManualFlow
applePayFields
merchantBusinessCountry
setApplePayIntegrationSteps
setVefifiedDomainList
/>
}
| Verify =>
<Verified
verifiedDomainList
setApplePayIntegrationType
setShowWalletConfigurationModal
setApplePayIntegrationSteps
appleIntegrationType
update
/>
}
}}
</div>
<FormValuesSpy />
</PageLoaderWrapper>
}
| 2,154 | 9,705 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorMetaData/ApplePay/ApplePaySimplifiedFlow.res | .res | open ApplePayIntegrationTypes
@react.component
let make = (
~applePayFields,
~merchantBusinessCountry,
~setApplePayIntegrationSteps,
~setVefifiedDomainList,
~connector,
) => {
open LogicUtils
open APIUtils
open ApplePayIntegrationHelper
open ApplePayIntegrationUtils
let getURL = useGetURL()
let updateAPIHook = useUpdateMethod(~showErrorToast=false)
let fetchApi = AuthHooks.useApiFetcher()
let showToast = ToastState.useShowToast()
let url = RescriptReactRouter.useUrl()
let form = ReactFinalForm.useForm()
let connectorID = HSwitchUtils.getConnectorIDFromUrl(url.path->List.toArray, "")
let {userInfo: {merchantId}} = React.useContext(UserInfoProvider.defaultContext)
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let initalFormValue =
formState.values
->getDictFromJsonObject
->getDictfromDict("metadata")
->getDictfromDict("apple_pay_combined")
let setFormData = () => {
let value = applePayCombined(initalFormValue, #simplified)
form.change("metadata.apple_pay_combined", value->Identity.genericTypeToJson)
}
React.useEffect(() => {
setFormData()
None
}, [])
let onSubmit = async () => {
try {
let body = formState.values->constructVerifyApplePayReq(connectorID)
let verifyAppleUrl = getURL(~entityName=V1(VERIFY_APPLE_PAY), ~methodType=Post)
let _ = await updateAPIHook(`${verifyAppleUrl}/${merchantId}`, body, Post)
let data =
formState.values
->getDictFromJsonObject
->getDictfromDict("metadata")
->getDictfromDict("apple_pay_combined")
->simplified
let domainName = data.session_token_data.initiative_context->Option.getOr("")
setVefifiedDomainList(_ => [domainName])
setApplePayIntegrationSteps(_ => ApplePayIntegrationTypes.Verify)
} catch {
| _ => showToast(~message="Failed to Verify", ~toastType=ToastState.ToastError)
}
Nullable.null
}
let downloadApplePayCert = () => {
open Promise
let downloadURL = Window.env.applePayCertificateUrl->Option.getOr("")
fetchApi(
downloadURL,
~method_=Get,
~xFeatureRoute=featureFlagDetails.xFeatureRoute,
~forceCookies=featureFlagDetails.forceCookies,
)
->then(Fetch.Response.blob)
->then(content => {
DownloadUtils.download(
~fileName=`apple-developer-merchantid-domain-association`,
~content,
~fileType="text/plain",
)
showToast(~toastType=ToastSuccess, ~message="File download complete")
resolve()
})
->catch(_ => {
showToast(
~toastType=ToastError,
~message="Oops, something went wrong with the download. Please try again.",
)
resolve()
})
->ignore
}
let downloadAPIKey =
<div className="mt-4">
<Button
text={"Download File"}
buttonType={Primary}
buttonSize={Small}
onClick={_ => downloadApplePayCert()}
buttonState={Normal}
/>
</div>
let applePaySimplifiedFields =
applePayFields
->Array.filter(field => {
let typedData = field->convertMapObjectToDict->CommonConnectorUtils.inputFieldMapper
!(ignoreFieldsonSimplified->Array.includes(typedData.name))
})
->Array.mapWithIndex((field, index) => {
let applePayField = field->convertMapObjectToDict->CommonConnectorUtils.inputFieldMapper
<div key={index->Int.toString}>
{switch applePayField.name {
| "merchant_business_country" =>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={CommonConnectorHelper.selectInput(
~field={applePayField},
~opt={Some(merchantBusinessCountry)},
~formName={
ApplePayIntegrationUtils.applePayNameMapper(
~name="merchant_business_country",
~integrationType=Some(#simplified),
)
},
)}
/>
| _ =>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={applePayValueInput(~applePayField, ~integrationType={Some(#simplified)})}
/>
}}
</div>
})
->React.array
<>
<SimplifiedHelper
customElement={applePaySimplifiedFields}
heading="Provide your sandbox domain where the verification file will be hosted"
subText=Some(
"Input the top-level domain (example.com) or sub-domain (checkout.example.com) where you wish to enable Apple Pay",
)
stepNumber="1"
/>
<hr className="w-full" />
<SimplifiedHelper
heading="Download domain verification file" stepNumber="2" customElement=downloadAPIKey
/>
<hr className="w-full" />
<SimplifiedHelper
heading="Host sandbox domain association file"
subText=Some(
"Host the downloaded verification file at your sandbox domain in the following location :-",
)
stepNumber="3"
customElement={<HostURL
prefix={`${ApplePayIntegrationUtils.applePayNameMapper(
~name="initiative_context",
~integrationType=Some(#simplified),
)}`}
/>}
/>
<RenderIf condition={featureFlagDetails.isLiveMode && featureFlagDetails.complianceCertificate}>
{switch connector->ConnectorUtils.getConnectorNameTypeFromString {
| Processors(STRIPE) =>
<>
<hr className="w-full" />
<SimplifiedHelper
heading="Get feature enabled from stripe"
subText=None
stepNumber="4"
customElement={<SampleEmail />}
/>
</>
| _ => React.null
}}
</RenderIf>
<div className="w-full flex gap-2 justify-end p-6">
<Button
text="Go Back"
buttonType={Secondary}
onClick={_ => {
setApplePayIntegrationSteps(_ => Landing)
}}
/>
<Button
text="Verify & Enable"
buttonType={Primary}
onClick={_ => {
onSubmit()->ignore
}}
buttonState={formState.values->validateSimplifedFlow}
/>
</div>
<FormValuesSpy />
</>
}
| 1,468 | 9,706 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/Common/CommonConnectorHelper.res | .res | let textInput = (~field: CommonConnectorTypes.inputField, ~formName) => {
let {placeholder, label, required} = field
FormRenderer.makeFieldInfo(
~label,
~name={formName},
~placeholder,
~customInput=InputFields.textInput(),
~isRequired=required,
)
}
let numberInput = (~field: CommonConnectorTypes.inputField, ~formName) => {
let {placeholder, label, required} = field
FormRenderer.makeFieldInfo(
~label,
~name={formName},
~placeholder,
~customInput=InputFields.numericTextInput(),
~isRequired=required,
)
}
let selectInput = (
~field: CommonConnectorTypes.inputField,
~formName,
~opt=None,
~onItemChange: option<ReactEvent.Form.t => unit>=?,
~fixedDropDownDirection=SelectBox.BottomRight,
) => {
let {label, required} = field
let options = switch opt {
| Some(value) => value
| None => field.options->SelectBox.makeOptions
}
FormRenderer.makeFieldInfo(~label={label}, ~isRequired=required, ~name={formName}, ~customInput=(
~input,
~placeholder as _,
) =>
InputFields.selectInput(
~customStyle="max-h-48",
~options={options},
~buttonText="Select Value",
~dropdownCustomWidth="",
~fixedDropDownDirection,
)(
~input={
...input,
onChange: event => {
let _ = switch onItemChange {
| Some(func) => func(event)
| _ => ()
}
input.onChange(event)
},
},
~placeholder="",
)
)
}
let multiSelectInput = (~field: CommonConnectorTypes.inputField, ~formName) => {
let {label, required, options} = field
FormRenderer.makeFieldInfo(
~label,
~isRequired=required,
~name={formName},
~customInput=InputFields.multiSelectInput(
~showSelectionAsChips=false,
~customStyle="max-h-48",
~customButtonStyle="pr-3",
~options={options->SelectBox.makeOptions},
~buttonText="Select Value",
),
)
}
let toggleInput = (~field: CommonConnectorTypes.inputField, ~formName) => {
let {label} = field
FormRenderer.makeFieldInfo(
~name={formName},
~label,
~customInput=InputFields.boolInput(~isDisabled=false, ~boolCustomClass="rounded-lg"),
)
}
let radioInput = (
~field: CommonConnectorTypes.inputField,
~formName,
~onItemChange: option<ReactEvent.Form.t => unit>=?,
~fill="",
(),
) => {
let {label, required, options} = field
FormRenderer.makeFieldInfo(~label={label}, ~isRequired=required, ~name={formName}, ~customInput=(
~input,
~placeholder as _,
) =>
InputFields.radioInput(
~customStyle="cursor-pointer gap-2",
~isHorizontal=false,
~options=options->SelectBox.makeOptions,
~buttonText="",
~fill,
)(
~input={
...input,
onChange: event => {
let _ = switch onItemChange {
| Some(func) => func(event)
| _ => ()
}
input.onChange(event)
},
},
~placeholder="",
)
)
}
let getCurrencyOption: CurrencyUtils.currencyCode => SelectBox.dropdownOption = currencyType => {
open CurrencyUtils
{
label: currencyType->getCurrencyCodeStringFromVariant,
value: currencyType->getCurrencyCodeStringFromVariant,
}
}
let currencyField = (
~name,
~options=CurrencyUtils.currencyList,
~disableSelect=false,
~toolTipText="",
) =>
FormRenderer.makeFieldInfo(
~label="Currency",
~isRequired=true,
~name,
~description=toolTipText,
~customInput=InputFields.selectInput(
~deselectDisable=true,
~disableSelect,
~customStyle="max-h-48",
~options=options->Array.map(getCurrencyOption),
~buttonText="Select Currency",
~fixedDropDownDirection=TopLeft,
~dropdownCustomWidth="",
),
)
| 965 | 9,707 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/Common/CommonConnectorUtils.res | .res | open CommonConnectorTypes
let inputTypeMapperr = ipType => {
switch ipType {
| "Text" => Text
| "Toggle" => Toggle
| "Select" => Select
| "MultiSelect" => MultiSelect
| "Radio" => Radio
| "Number" => Number
| _ => Text
}
}
let inputFieldMapper = dict => {
open LogicUtils
{
name: dict->getString("name", ""),
label: dict->getString("label", ""),
placeholder: dict->getString("placeholder", ""),
required: dict->getBool("required", true),
options: dict->getStrArray("options"),
\"type": dict->getString("type", "")->inputTypeMapperr,
}
}
| 169 | 9,708 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/Common/CommonConnectorTypes.res | .res | type inputType = Text | Number | Toggle | Radio | Select | MultiSelect
type inputField = {
name: string,
label: string,
placeholder: string,
required: bool,
options: array<string>,
\"type": inputType,
}
| 56 | 9,709 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorUIUtils/SuggestedActionHelper.res | .res | module SuggestedAction = {
@react.component
let make = () => {
<div
className="whitespace-pre-line break-all flex flex-col gap-1 p-2 ml-4 text-base dark:text-jp-gray-text_darktheme dark:text-opacity-50 font-medium leading-7 opacity-50 mt-4">
{`Suggested Action:`->React.string}
</div>
}
}
module StripSendingCreditCard = {
@react.component
let make = () => {
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
<>
<SuggestedAction />
<div
className="whitespace-pre-line break-word flex flex-col gap-1 bg-green-50 rounded-md font-medium p-4 ml-6">
<div className="inline gap-1">
{`Click `->React.string}
<a
className={`inline ${textColor.primaryNormal} underline`}
href="https://dashboard.stripe.com/settings/integration"
target="_blank">
{React.string("here")}
</a>
{` to turn on the "Enable raw card processing" toggle under the show advanced settings`->React.string}
</div>
</div>
</>
}
}
module StripeInvalidAPIKey = {
@react.component
let make = () => {
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
<>
<SuggestedAction />
<div
className="whitespace-pre-line break-word flex flex-col gap-1 bg-green-50 rounded-md font-medium p-4 ml-6">
<div className="inline gap-1">
{`Please use a secret API key. Click `->React.string}
<a
className={`inline ${textColor.primaryNormal} underline`}
href="https://dashboard.stripe.com/test/apikeys"
target="_blank">
{React.string("here")}
</a>
{` to find the Secret key of your stripe account from the list of your API keys`->React.string}
</div>
</div>
</>
}
}
module PaypalClientAuthenticationFalied = {
@react.component
let make = () => {
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
<>
<SuggestedAction />
<div
className="whitespace-pre-line break-word flex flex-col gap-1 bg-green-50 rounded-md font-medium p-4 ml-6">
<div className="inline gap-1">
{`Please use the correct credentials. Click `->React.string}
<a
className={`inline ${textColor.primaryNormal} underline`}
href="https://developer.paypal.com/dashboard/applications/sandbox"
target="_blank">
{React.string("here")}
</a>
{` to find the client secret and client key of your Paypal`->React.string}
</div>
</div>
</>
}
}
| 659 | 9,710 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorUIUtils/IntegrationHelp.res | .res | module Render = {
@react.component
let make = (~connector, ~showModal, ~setShowModal) => {
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let integrationSteps = switch connector->ConnectorUtils.getConnectorNameTypeFromString {
| Processors(STRIPE) =>
<div className="">
<ol className="list-decimal pl-4">
<li className="mb-8">
{React.string("In your Stripe Dashboard home page, Click on the ")}
<span className="font-bold"> {React.string("\"Developers\"")} </span>
{React.string(" tab (top-right of the dashboard) and navigate to ")}
<span className="font-bold"> {React.string("\"API Keys\"")} </span>
{React.string(" section")}
<a href={`/icons/stripe_apikey.png`} target="_blank">
<img
alt="stripe-api-key"
className="m-4 border rounded-lg border-gray-200"
style={maxWidth: "94%"}
src={`/icons/stripe_apikey.png`}
/>
</a>
</li>
<li className="mb-8">
{React.string(
"Copy the Secret and Public keys and add them to the Hyperswitch dashboard under Stripe",
)}
</li>
</ol>
<div className="p-8 my-4 bg-amber-100/75 border rounded-lg font-medium border-transparent ">
{React.string(
"Note: For Stripe to directly accept card on the account, make the following changes:",
)}
<ul className="list-disc mt-4 ml-4">
<li className="mb-4">
{React.string("Search for ")}
<span className="font-bold">
{React.string("Integrations > Advanced Options > Handle card information directly")}
</span>
</li>
<li className="mb-4">
{React.string(
"Currently, Hyperswitch supports the latest Payments Intent APIs of Stripe API that is created after 2019",
)}
</li>
<li className="mb-4">
{React.string(
"If the 'Handle card information directly' toggle cannot be turned on, please refer to this ",
)}
<a
className={`${textColor.primaryNormal} underline`}
href="https://support.stripe.com/questions/enabling-access-to-raw-card-data-apis"
target="_blank">
{React.string("link")}
</a>
</li>
</ul>
</div>
<a href={`/icons/stripe_helper.png`} target="_blank">
<img
alt="stripe-helper"
className="m-4 border rounded-lg border-gray-200"
style={maxWidth: "94%"}
src={`/icons/stripe_helper.png`}
/>
</a>
</div>
| Processors(ADYEN) =>
<div className="">
<ol className="list-decimal pl-4">
<li className="mb-8">
{React.string("In your Adyen Dashboard, Click on the ")}
<span className="font-bold"> {React.string("\"Developers\"")} </span>
{React.string(" tab and navigate to API credentials.")}
<a href={`/icons/adyen_apikey.png`} target="_blank">
<img
alt="adyen-api-key"
className="m-4 border rounded-lg border-gray-200"
src={`/icons/adyen_apikey.png`}
/>
</a>
</li>
<li className="mb-4">
{React.string(
"Copy the API key and Merchant Account ID and add them to the Hyperswitch dashboard under Adyen.",
)}
</li>
</ol>
<div
className="py-6 px-4 m-8 my-2 bg-amber-100/75 border rounded-lg font-medium border-transparent">
{React.string("For making card payment via Adyen, you need to enable full card payments.
You would have to contact the Adyen customer support and ask them to enable it for you for testing payments.")}
</div>
<a href={`/icons/adyen_merchantID.png`} target="_blank">
<img
alt="adyen-merchant-id"
className="m-8 border rounded-lg border-gray-200 w-3/4"
src={`/icons/adyen_merchantID.png`}
/>
</a>
<div className="flex flex-col items-center text-sm text-gray-400">
{React.string("Click on the top-right corner to find your Merchant ID.")}
</div>
</div>
| Processors(CHECKOUT) =>
<div className="">
<ol className="list-decimal pl-4">
<li className="mb-8">
{React.string("In your Stripe Dashboard home page, Click on ")}
<span className="font-bold"> {React.string("Developers > Keys")} </span>
{React.string(" . Click on the active access key in the \"Access Keys\" table.")}
</li>
<li className="mb-8">
{React.string(
"Click on Update key (top-right). In the Processing channels section copy the Channel ID and add them to Hyperswitch dashboard under Checkout",
)}
</li>
<li className="mb-8">
{React.string("Use the Public key and Secret key generated during the creation of the Checkout's API key and add them to the Hyperswitch dashboard.
For the hint about the key Click on the Developer tab and navigate to Keys")}
</li>
</ol>
<div
className="py-6 px-4 m-8 my-2 bg-amber-100/75 border rounded-lg font-medium border-transparent">
{React.string("For making card payment via Checkout, you need to enable full card payments.
You would have to contact the checkout.com customer support and ask them to enable it for you for testing payments.")}
</div>
<div className="mt-8 italic">
{React.string("Note: Secret key is displayed only once during the key creation.
New Checkout Public key and Secret key can be created in Developers > Keys > Create a new key.")}
</div>
</div>
| Processors(PAYPAL) =>
<div className="">
<ol className="list-decimal pl-4">
<li className="mb-8">
{React.string("In your Paypal Sandbox account, Click on the ")}
<span className="font-bold"> {React.string("\"Developer Dashboard\"")} </span>
{React.string(" and navigate to ")}
<span className="font-bold"> {React.string("\"API credentials\"")} </span>
{React.string(" tab ")}
<a
className={`$ underline`}
href="https://developer.paypal.com/dashboard/applications/sandbox"
target="_blank">
{React.string("here")}
</a>
</li>
<li className="mb-8">
{React.string(
"Copy the ClientID, Client Secret of the App name used under the REST API apps",
)}
<a href={`/icons/paypal_apikey.png`} target="_blank">
<img
alt="paypal-api-key"
className="m-4 border rounded-lg border-gray-200"
style={maxWidth: "94%"}
src={`/icons/paypal_apikey.png`}
/>
</a>
</li>
</ol>
</div>
| _ => React.null
}
<Modal
modalHeading={`Steps to integrate ${connector->LogicUtils.snakeToTitle}`}
headerTextClass={`${textColor.primaryNormal} font-bold text-xl`}
showModal
setShowModal
paddingClass=""
revealFrom=Reveal.Right
modalClass="w-1/3 !h-full overflow-scroll rounded-none text-jp-gray-900">
integrationSteps
</Modal>
}
}
| 1,764 | 9,711 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorUIUtils/PaymentMethod.res | .res | let isSelectedAll = (
selectedPaymentMethod: array<ConnectorTypes.paymentMethodEnabled>,
allPaymentMethods,
paymentMethod,
) => {
open ConnectorUtils
let paymentMethodObj = selectedPaymentMethod->getSelectedPaymentObj(paymentMethod)
switch paymentMethod->getPaymentMethodFromString {
| Card =>
paymentMethodObj.card_provider->Option.getOr([])->Array.length ==
allPaymentMethods->Array.length
| _ =>
paymentMethodObj.provider->Option.getOr([])->Array.length == allPaymentMethods->Array.length
}
}
module CardRenderer = {
open LogicUtils
open ConnectorTypes
open ConnectorUtils
open AdditionalDetailsSidebar
@react.component
let make = (
~updateDetails,
~paymentMethodsEnabled: array<paymentMethodEnabled>,
~paymentMethod,
~provider: array<paymentMethodConfigType>,
~_showAdvancedConfiguration,
~setMetaData,
~connector,
~initialValues,
~setInitialValues,
) => {
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let form = ReactFinalForm.useForm()
let (meteDataInitialValues, connectorWalletsInitialValues) = React.useMemo(() => {
let formValues = formState.values->getDictFromJsonObject
(
formValues->getDictfromDict("metadata"),
formValues->getDictfromDict("connector_wallets_details"),
)
}, [])
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let (showWalletConfigurationModal, setShowWalletConfigurationModal) = React.useState(_ => false)
let (selectedWallet, setSelectedWallet) = React.useState(_ => Dict.make()->itemProviderMapper)
let pmAuthProcessorList = ConnectorInterface.useConnectorArrayMapper(
~interface=ConnectorInterface.connectorInterfaceV1,
~retainInList=PMAuthProcessor,
)
let isPMAuthConnector = pmAuthProcessorList->Array.length > 0
let currentProfile = initialValues->getDictFromJsonObject->getString("profile_id", "")
let isProfileIdConfiguredPMAuth =
pmAuthProcessorList
->Array.filter(item => item.profile_id === currentProfile && !item.disabled)
->Array.length > 0
let shouldShowPMAuthSidebar =
featureFlagDetails.pmAuthenticationProcessor &&
isPMAuthConnector &&
isProfileIdConfiguredPMAuth
let selectedAll = isSelectedAll(paymentMethodsEnabled, provider, paymentMethod)
let paymentObj = paymentMethodsEnabled->getSelectedPaymentObj(paymentMethod)
let standardProviders =
paymentObj.provider->Option.getOr([]->JSON.Encode.array->getPaymentMethodMapper)
let cardProviders =
paymentObj.card_provider->Option.getOr([]->JSON.Encode.array->getPaymentMethodMapper)
let checkPaymentMethodType = (
obj: paymentMethodConfigType,
selectedMethod: paymentMethodConfigType,
) => obj.payment_method_type == selectedMethod.payment_method_type
let checkPaymentMethodTypeAndExperience = (
obj: paymentMethodConfigType,
selectedMethod: paymentMethodConfigType,
) => {
obj.payment_method_type == selectedMethod.payment_method_type &&
obj.payment_experience == selectedMethod.payment_experience
}
let showSideModal = methodVariant => {
((methodVariant === GooglePay ||
methodVariant === ApplePay ||
methodVariant === SamsungPay ||
methodVariant === Paze) &&
{
switch connector->getConnectorNameTypeFromString {
| Processors(TRUSTPAY)
| Processors(STRIPE_TEST) => false
| _ => true
}
}) || (paymentMethod->getPaymentMethodFromString === BankDebit && shouldShowPMAuthSidebar)
}
let removeOrAddMethods = (method: paymentMethodConfigType) => {
switch (
method.payment_method_type->getPaymentMethodTypeFromString,
paymentMethod->getPaymentMethodFromString,
connector->getConnectorNameTypeFromString,
) {
| (PayPal, Wallet, Processors(PAYPAL)) =>
if standardProviders->Array.some(obj => checkPaymentMethodTypeAndExperience(obj, method)) {
paymentMethodsEnabled->removeMethod(paymentMethod, method, connector)->updateDetails
} else {
paymentMethodsEnabled->addMethod(paymentMethod, method)->updateDetails
}
| (Klarna, PayLater, Processors(KLARNA)) =>
if standardProviders->Array.some(obj => checkPaymentMethodTypeAndExperience(obj, method)) {
paymentMethodsEnabled->removeMethod(paymentMethod, method, connector)->updateDetails
} else {
paymentMethodsEnabled->addMethod(paymentMethod, method)->updateDetails
}
| (_, Card, _) =>
if cardProviders->Array.some(obj => checkPaymentMethodType(obj, method)) {
paymentMethodsEnabled->removeMethod(paymentMethod, method, connector)->updateDetails
} else {
paymentMethodsEnabled->addMethod(paymentMethod, method)->updateDetails
}
| _ =>
if standardProviders->Array.some(obj => checkPaymentMethodType(obj, method)) {
paymentMethodsEnabled->removeMethod(paymentMethod, method, connector)->updateDetails
} else if showSideModal(method.payment_method_type->getPaymentMethodTypeFromString) {
setShowWalletConfigurationModal(_ => !showWalletConfigurationModal)
setSelectedWallet(_ => method)
} else {
paymentMethodsEnabled->addMethod(paymentMethod, method)->updateDetails
}
}
}
let updateSelectAll = (paymentMethod, isSelectedAll) => {
let arr = isSelectedAll ? [] : provider
paymentMethodsEnabled->Array.forEach(val => {
if val.payment_method_type === paymentMethod {
switch paymentMethod->getPaymentMethodTypeFromString {
| Credit | Debit =>
let length = val.card_provider->Option.getOr([])->Array.length
val.card_provider
->Option.getOr([])
->Array.splice(~start=0, ~remove=length, ~insert=arr)
->ignore
| _ =>
let length = val.provider->Option.getOr([])->Array.length
val.provider
->Option.getOr([])
->Array.splice(~start=0, ~remove=length, ~insert=arr)
->ignore
}
}
})
updateDetails(paymentMethodsEnabled)
}
let isSelected = selectedMethod => {
switch (
paymentMethod->getPaymentMethodFromString,
connector->getConnectorNameTypeFromString,
) {
| (Wallet, Processors(PAYPAL)) =>
standardProviders->Array.some(obj =>
checkPaymentMethodTypeAndExperience(obj, selectedMethod)
)
| (PayLater, Processors(KLARNA)) =>
standardProviders->Array.some(obj =>
checkPaymentMethodTypeAndExperience(obj, selectedMethod)
)
| _ =>
standardProviders->Array.some(obj => checkPaymentMethodType(obj, selectedMethod)) ||
cardProviders->Array.some(obj => checkPaymentMethodType(obj, selectedMethod))
}
}
let isNotVerifiablePaymentMethod = paymentMethodVariant => {
switch paymentMethodVariant {
| UnknownPaymentMethod(str) => str !== "is_verifiable"
| _ => true
}
}
let p2RegularTextStyle = `${HSwitchUtils.getTextClass((P2, Medium))} text-grey-700 opacity-50`
let removeSelectedWallet = () => {
form.change("metadata", meteDataInitialValues->Identity.genericTypeToJson)
form.change(
"connector_wallets_details",
connectorWalletsInitialValues->Identity.genericTypeToJson,
)
setSelectedWallet(_ => Dict.make()->itemProviderMapper)
}
let title = switch paymentMethod->getPaymentMethodFromString {
| BankDebit => paymentMethod->snakeToTitle
| Wallet => selectedWallet.payment_method_type->snakeToTitle
| _ => ""
}
let modalHeading = `Additional Details to enable ${title}`
<div className="flex flex-col gap-4 border rounded-md p-6">
<div>
<RenderIf
condition={paymentMethod->getPaymentMethodFromString->isNotVerifiablePaymentMethod}>
<div className="flex items-center border-b gap-2 py-2 break-all justify-between">
<p className="font-semibold text-bold text-lg">
{React.string(paymentMethod->snakeToTitle)}
</p>
<RenderIf
condition={paymentMethod->getPaymentMethodFromString !== Wallet &&
paymentMethod->getPaymentMethodFromString !== BankDebit}>
<AddDataAttributes
attributes=[
("data-testid", paymentMethod->String.concat("_")->String.concat("select_all")),
]>
<div className="flex gap-2 items-center">
{switch connector->getConnectorNameTypeFromString {
| Processors(KLARNA) =>
<RenderIf
condition={initialValues
->getDictFromJsonObject
->getDictfromDict("metadata")
->getString("klarna_region", "") === "Europe"}>
<div className="flex gap-2 items-center">
<BoolInput.BaseComponent
isSelected={selectedAll}
setIsSelected={_ => updateSelectAll(paymentMethod, selectedAll)}
isDisabled={false}
boolCustomClass="rounded-lg"
/>
<p className={p2RegularTextStyle}> {"Select all"->React.string} </p>
</div>
</RenderIf>
| _ =>
<div className="flex gap-2 items-center">
<BoolInput.BaseComponent
isSelected={selectedAll}
setIsSelected={_ => updateSelectAll(paymentMethod, selectedAll)}
isDisabled={false}
boolCustomClass="rounded-lg"
/>
<p className={p2RegularTextStyle}> {"Select all"->React.string} </p>
</div>
}}
</div>
</AddDataAttributes>
</RenderIf>
</div>
</RenderIf>
</div>
<RenderIf
condition={paymentMethod->getPaymentMethodFromString === Wallet &&
{
switch connector->getConnectorNameTypeFromString {
| Processors(ZEN) => true
| _ => false
}
}}>
<div className="border rounded p-2 bg-jp-gray-100 flex gap-4">
<Icon name="outage_icon" size=15 />
{"Zen doesn't support Googlepay and Applepay in sandbox."->React.string}
</div>
</RenderIf>
<div className={`grid ${_showAdvancedConfiguration ? "grid-cols-2" : "grid-cols-4"} gap-4`}>
{provider
->Array.mapWithIndex((value, i) => {
<div key={i->Int.toString}>
<div className="flex">
<AddDataAttributes
attributes=[
(
"data-testid",
`${paymentMethod
->String.concat("_")
->String.concat(value.payment_method_type)
->String.toLowerCase}`,
),
]>
<div className="flex items-center gap-2">
{switch connector->getConnectorNameTypeFromString {
| Processors(KLARNA) =>
<RenderIf
condition={!(
value.payment_experience->Option.getOr("") === "redirect_to_url" &&
initialValues
->getDictFromJsonObject
->getDictfromDict("metadata")
->getString("klarna_region", "") !== "Europe"
)}>
<div onClick={_ => removeOrAddMethods(value)} className="cursor-pointer">
<CheckBoxIcon isSelected={isSelected(value)} />
</div>
</RenderIf>
| _ =>
<div onClick={_ => removeOrAddMethods(value)} className="cursor-pointer">
<CheckBoxIcon isSelected={isSelected(value)} />
</div>
}}
{switch (
value.payment_method_type->getPaymentMethodTypeFromString,
paymentMethod->getPaymentMethodFromString,
connector->getConnectorNameTypeFromString,
) {
| (PayPal, Wallet, Processors(PAYPAL)) =>
<p
className={`${p2RegularTextStyle} cursor-pointer`}
onClick={_ => removeOrAddMethods(value)}>
{value.payment_experience->Option.getOr("") === "redirect_to_url"
? "PayPal Redirect"->React.string
: "PayPal SDK"->React.string}
</p>
| (Klarna, PayLater, Processors(KLARNA)) =>
<RenderIf
condition={!(
value.payment_experience->Option.getOr("") === "redirect_to_url" &&
initialValues
->getDictFromJsonObject
->getDictfromDict("metadata")
->getString("klarna_region", "") !== "Europe"
)}>
<p
className={`${p2RegularTextStyle} cursor-pointer`}
onClick={_ => removeOrAddMethods(value)}>
{value.payment_experience->Option.getOr("") === "redirect_to_url"
? "Klarna Checkout"->React.string
: "Klarna SDK"->React.string}
</p>
</RenderIf>
| (OpenBankingPIS, _, _) =>
<p
className={`${p2RegularTextStyle} cursor-pointer`}
onClick={_ => removeOrAddMethods(value)}>
{"Open Banking PIS"->React.string}
</p>
| _ =>
<p
className={`${p2RegularTextStyle} cursor-pointer`}
onClick={_ => removeOrAddMethods(value)}>
{React.string(value.payment_method_type->snakeToTitle)}
</p>
}}
</div>
</AddDataAttributes>
</div>
</div>
})
->React.array}
<RenderIf
condition={selectedWallet.payment_method_type->getPaymentMethodTypeFromString ===
ApplePay ||
selectedWallet.payment_method_type->getPaymentMethodTypeFromString === GooglePay ||
selectedWallet.payment_method_type->getPaymentMethodTypeFromString === SamsungPay ||
selectedWallet.payment_method_type->getPaymentMethodTypeFromString === Paze ||
(paymentMethod->getPaymentMethodFromString === BankDebit && shouldShowPMAuthSidebar)}>
<Modal
modalHeading
headerTextClass={`${textColor.primaryNormal} font-bold text-xl`}
headBgClass="sticky top-0 z-30 bg-white"
showModal={showWalletConfigurationModal}
setShowModal={setShowWalletConfigurationModal}
onCloseClickCustomFun={removeSelectedWallet}
paddingClass=""
revealFrom=Reveal.Right
modalClass="w-full md:w-1/3 !h-full overflow-y-scroll !overflow-x-hidden rounded-none text-jp-gray-900"
childClass={""}>
<AdditionalDetailsSidebarComp
method={Some(selectedWallet)}
setMetaData
setShowWalletConfigurationModal
updateDetails
paymentMethodsEnabled
paymentMethod
onCloseClickCustomFun={removeSelectedWallet}
setInitialValues
pmtName={selectedWallet.payment_method_type}
/>
</Modal>
</RenderIf>
</div>
</div>
}
}
module PaymentMethodsRender = {
open LogicUtils
open ConnectorUtils
open ConnectorTypes
@react.component
let make = (
~_showAdvancedConfiguration: bool,
~connector,
~paymentMethodsEnabled: array<paymentMethodEnabled>,
~updateDetails,
~setMetaData,
~isPayoutFlow,
~initialValues,
~setInitialValues,
) => {
let pmts = React.useMemo(() => {
(
isPayoutFlow
? Window.getPayoutConnectorConfig(connector)
: Window.getConnectorConfig(connector)
)->getDictFromJsonObject
}, [connector])
let keys = pmts->Dict.keysToArray->Array.filter(val => !Array.includes(configKeysToIgnore, val))
<div className="flex flex-col gap-12">
{keys
->Array.mapWithIndex((value, i) => {
let provider = pmts->getArrayFromDict(value, [])->JSON.Encode.array->getPaymentMethodMapper
switch value->getPaymentMethodTypeFromString {
| Credit | Debit =>
<div key={i->Int.toString}>
<CardRenderer
updateDetails
paymentMethodsEnabled
provider
paymentMethod={value}
_showAdvancedConfiguration=false
setMetaData
connector
initialValues
setInitialValues
/>
</div>
| _ =>
<div key={i->Int.toString}>
<CardRenderer
updateDetails
paymentMethodsEnabled
paymentMethod={value}
provider
_showAdvancedConfiguration=false
setMetaData
connector
initialValues
setInitialValues
/>
</div>
}
})
->React.array}
</div>
}
}
| 3,633 | 9,712 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorWalletDetails/Paze/PazeIntegration.res | .res | @react.component
let make = (~connector, ~setShowWalletConfigurationModal, ~update, ~onCloseClickCustomFun) => {
open LogicUtils
open PazeIntegrationUtils
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let form = ReactFinalForm.useForm()
let setPazeFormData = () => {
let initalFormValue =
formState.values
->getDictFromJsonObject
->getDictfromDict("connector_wallets_details")
->getDictfromDict("paze")
form.change(
"connector_wallets_details.paze",
initalFormValue->pazePayRequest->Identity.genericTypeToJson,
)
}
React.useEffect(() => {
if connector->isNonEmptyString {
setPazeFormData()
}
None
}, [connector])
let pazeFields = React.useMemo(() => {
try {
if connector->isNonEmptyString {
let samsungPayInputFields =
Window.getConnectorConfig(connector)
->getDictFromJsonObject
->getDictfromDict("connector_wallets_details")
->getArrayFromDict("paze", [])
samsungPayInputFields
} else {
[]
}
} catch {
| Exn.Error(_) => []
}
}, [connector])
let onSubmit = _ => {
update()
setShowWalletConfigurationModal(_ => false)
}
let onCancel = () => {
onCloseClickCustomFun()
setShowWalletConfigurationModal(_ => false)
}
let pazeInputFields =
pazeFields
->Array.mapWithIndex((field, index) => {
let pazeField = field->convertMapObjectToDict->CommonConnectorUtils.inputFieldMapper
<div key={index->Int.toString}>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black" field={pazeValueInput(~pazeField)}
/>
</div>
})
->React.array
<div className="p-2">
{pazeInputFields}
<div className={`flex gap-2 justify-end m-2 p-6`}>
<Button text="Cancel" buttonType={Secondary} onClick={_ => onCancel()} />
<Button
onClick={onSubmit}
text="Continue"
buttonType={Primary}
buttonState={formState.values->validatePaze}
/>
</div>
<FormValuesSpy />
</div>
}
| 554 | 9,713 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorWalletDetails/Paze/PazeIntegrationUtils.res | .res | open PazeIntegrationTypes
open LogicUtils
let pazePayRequest = dict => {
client_id: dict->getString("client_id", ""),
client_name: dict->getString("client_name", ""),
client_profile_id: dict->getString("client_profile_id", ""),
}
let pazeNameMapper = (~name) => {
`connector_wallets_details.paze.${name}`
}
let pazeValueInput = (~pazeField: CommonConnectorTypes.inputField) => {
open CommonConnectorHelper
let {\"type", name} = pazeField
let formName = pazeNameMapper(~name)
{
switch \"type" {
| Text => textInput(~field={pazeField}, ~formName)
| Select => selectInput(~field={pazeField}, ~formName)
| MultiSelect => multiSelectInput(~field={pazeField}, ~formName)
| Radio => radioInput(~field={pazeField}, ~formName, ())
| _ => textInput(~field={pazeField}, ~formName)
}
}
}
let validatePaze = (json: JSON.t) => {
let {client_id, client_name, client_profile_id} =
getDictFromJsonObject(json)
->getDictfromDict("connector_wallets_details")
->getDictfromDict("paze")
->pazePayRequest
client_id->isNonEmptyString &&
client_name->isNonEmptyString &&
client_profile_id->isNonEmptyString
? Button.Normal
: Button.Disabled
}
| 334 | 9,714 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorWalletDetails/Paze/PazeIntegrationTypes.res | .res | type paze = {
client_id: string,
client_name: string,
client_profile_id: string,
}
| 25 | 9,715 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorWalletDetails/SamsungPay/SamsungPayIntegrationUtils.res | .res | open SamsungPayIntegrationTypes
open LogicUtils
let samsungPayRequest = dict => {
merchant_business_country: dict->getString("merchant_business_country", ""),
merchant_display_name: dict->getString("merchant_display_name", ""),
service_id: dict->getString("service_id", ""),
allowed_brands: dict->getStrArrayFromDict(
"allowed_brands",
["visa", "masterCard", "amex", "discover"],
),
}
let samsungPayNameMapper = (~name) => {
`connector_wallets_details.samsung_pay.merchant_credentials.${name}`
}
let samsungPayValueInput = (~samsungPayField: CommonConnectorTypes.inputField, ~fill) => {
open CommonConnectorHelper
let {\"type", name} = samsungPayField
let formName = samsungPayNameMapper(~name)
{
switch \"type" {
| Text => textInput(~field={samsungPayField}, ~formName)
| Select => selectInput(~field={samsungPayField}, ~formName)
| MultiSelect => multiSelectInput(~field={samsungPayField}, ~formName)
| Radio => radioInput(~field={samsungPayField}, ~formName, ~fill, ())
| _ => textInput(~field={samsungPayField}, ~formName)
}
}
}
let validateSamsungPay = (json: JSON.t) => {
let {merchant_business_country, merchant_display_name, service_id, allowed_brands} =
getDictFromJsonObject(json)
->getDictfromDict("connector_wallets_details")
->getDictfromDict("samsung_pay")
->getDictfromDict("merchant_credentials")
->samsungPayRequest
merchant_business_country->isNonEmptyString &&
merchant_display_name->isNonEmptyString &&
service_id->isNonEmptyString &&
allowed_brands->Array.length > 0
? Button.Normal
: Button.Disabled
}
| 415 | 9,716 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorWalletDetails/SamsungPay/SamsungPayIntegration.res | .res | @react.component
let make = (~connector, ~setShowWalletConfigurationModal, ~update, ~onCloseClickCustomFun) => {
open APIUtils
open LogicUtils
open SamsungPayIntegrationUtils
let getURL = useGetURL()
let fetchDetails = useGetMethod()
let (merchantBusinessCountry, setMerchantBusinessCountry) = React.useState(_ => [])
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Success)
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let form = ReactFinalForm.useForm()
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let samsungPayFields = React.useMemo(() => {
try {
if connector->isNonEmptyString {
let samsungPayInputFields =
Window.getConnectorConfig(connector)
->getDictFromJsonObject
->getDictfromDict("connector_wallets_details")
->getArrayFromDict("samsung_pay", [])
samsungPayInputFields
} else {
[]
}
} catch {
| Exn.Error(e) => {
Js.log2("FAILED TO LOAD CONNECTOR CONFIG", e)
[]
}
}
}, [connector])
let setSamsungFormData = () => {
let initalFormValue =
formState.values
->getDictFromJsonObject
->getDictfromDict("connector_wallets_details")
->getDictfromDict("samsung_pay")
->getDictfromDict("merchant_credentials")
form.change(
"connector_wallets_details.samsung_pay.merchant_credentials",
initalFormValue->samsungPayRequest->Identity.genericTypeToJson,
)
}
let getProcessorDetails = async () => {
try {
setScreenState(_ => Loading)
let paymentMethoConfigUrl = getURL(~entityName=V1(PAYMENT_METHOD_CONFIG), ~methodType=Get)
let res = await fetchDetails(
`${paymentMethoConfigUrl}?connector=${connector}&paymentMethodType=samsung_pay`,
)
let countries =
res
->getDictFromJsonObject
->getArrayFromDict("countries", [])
->Array.map(item => {
let dict = item->getDictFromJsonObject
let countryList: SelectBox.dropdownOption = {
label: dict->getString("name", ""),
value: dict->getString("code", ""),
}
countryList
})
setMerchantBusinessCountry(_ => countries)
setSamsungFormData()
setScreenState(_ => Success)
} catch {
| _ => setScreenState(_ => Success)
}
}
React.useEffect(() => {
if connector->LogicUtils.isNonEmptyString {
getProcessorDetails()->ignore
}
None
}, [connector])
let onSubmit = () => {
update()
setShowWalletConfigurationModal(_ => false)
}
let onCancel = () => {
onCloseClickCustomFun()
setShowWalletConfigurationModal(_ => false)
}
let samsungPayFields =
samsungPayFields
->Array.mapWithIndex((field, index) => {
let samsungPayField = field->convertMapObjectToDict->CommonConnectorUtils.inputFieldMapper
let {name} = samsungPayField
<div key={index->Int.toString}>
{switch name {
| "merchant_business_country" =>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={CommonConnectorHelper.selectInput(
~field={samsungPayField},
~opt={Some(merchantBusinessCountry)},
~formName={
samsungPayNameMapper(~name="merchant_business_country")
},
)}
/>
| _ =>
<FormRenderer.FieldRenderer
labelClass="font-semibold !text-hyperswitch_black"
field={samsungPayValueInput(~samsungPayField, ~fill=textColor.primaryNormal)}
/>
}}
</div>
})
->React.array
<PageLoaderWrapper
screenState={screenState}
customLoader={<div className="mt-60 w-scrren flex flex-col justify-center items-center">
<div className={`animate-spin mb-1`}>
<Icon name="spinner" size=20 />
</div>
</div>}
sectionHeight="!h-screen">
<div className="p-2">
{samsungPayFields}
<div className={`flex gap-2 justify-end m-2 p-6`}>
<Button text="Cancel" buttonType={Secondary} onClick={_ => onCancel()} />
<Button
onClick={_ => onSubmit()}
text="Continue"
buttonType={Primary}
buttonState={formState.values->SamsungPayIntegrationUtils.validateSamsungPay}
/>
</div>
</div>
<FormValuesSpy />
</PageLoaderWrapper>
}
| 1,069 | 9,717 |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorWalletDetails/SamsungPay/SamsunPayIntegrationHelper.res | .res | 1 | 9,718 | |
hyperswitch-control-center | src/screens/Connectors/PaymentProcessor/ConnectorWalletDetails/SamsungPay/SamsungPayIntegrationTypes.res | .res | type samsungPay = {
merchant_business_country: string,
merchant_display_name: string,
service_id: string,
allowed_brands: array<string>,
}
| 34 | 9,719 |
hyperswitch-control-center | src/screens/Connectors/PayoutProcessor/PayoutProcessorHome.res | .res | module ConnectorCurrentStepIndicator = {
@react.component
let make = (~currentStep: ConnectorTypes.steps, ~stepsArr) => {
let cols = stepsArr->Array.length->Int.toString
let currIndex = stepsArr->Array.findIndex(item => item === currentStep)
<div className=" w-full md:w-2/3">
<div className={`grid grid-cols-${cols} relative gap-2`}>
{stepsArr
->Array.mapWithIndex((step, i) => {
let isStepCompleted = i <= currIndex
let isPreviousStepCompleted = i < currIndex
let isCurrentStep = i == currIndex
let stepNumberIndicator = if isPreviousStepCompleted {
"border-black bg-white"
} else if isCurrentStep {
"bg-black"
} else {
"border-gray-300 bg-white"
}
let stepNameIndicator = isStepCompleted
? "text-black break-all"
: "text-jp-gray-700 break-all"
let textColor = isCurrentStep ? "text-white" : "text-grey-700"
let stepLineIndicator = isPreviousStepCompleted ? "bg-gray-700" : "bg-gray-200"
<div key={i->Int.toString} className="flex flex-col gap-2 font-semibold ">
<div className="flex items-center w-full">
<div
className={`h-8 w-8 flex items-center justify-center border rounded-full ${stepNumberIndicator}`}>
{if isPreviousStepCompleted {
<Icon name="check-black" size=20 />
} else {
<p className=textColor> {(i + 1)->Int.toString->React.string} </p>
}}
</div>
<RenderIf condition={i !== stepsArr->Array.length - 1}>
<div className={`h-0.5 ${stepLineIndicator} ml-2 flex-1`} />
</RenderIf>
</div>
<div className={stepNameIndicator}>
{step->ConnectorUtils.getStepName->React.string}
</div>
</div>
})
->React.array}
</div>
</div>
}
}
module MenuOption = {
open HeadlessUI
@react.component
let make = (~disableConnector, ~isConnectorDisabled) => {
let showPopUp = PopUpState.useShowPopUp()
let openConfirmationPopUp = _ => {
showPopUp({
popUpType: (Warning, WithIcon),
heading: "Confirm Action?",
description: `You are about to ${isConnectorDisabled
? "Enable"
: "Disable"->String.toLowerCase} this connector. This might impact your desired routing configurations. Please confirm to proceed.`->React.string,
handleConfirm: {
text: "Confirm",
onClick: _ => disableConnector(isConnectorDisabled)->ignore,
},
handleCancel: {text: "Cancel"},
})
}
let connectorStatusAvailableToSwitch = isConnectorDisabled ? "Enable" : "Disable"
<Popover \"as"="div" className="relative inline-block text-left">
{_ => <>
<Popover.Button> {_ => <Icon name="menu-option" size=28 />} </Popover.Button>
<Popover.Panel className="absolute z-20 right-5 top-4">
{panelProps => {
<div
id="neglectTopbarTheme"
className="relative flex flex-col bg-white py-1 overflow-hidden rounded ring-1 ring-black ring-opacity-5 w-40">
{<Navbar.MenuOption
text={connectorStatusAvailableToSwitch}
onClick={_ => {
panelProps["close"]()
openConfirmationPopUp()
}}
/>}
</div>
}}
</Popover.Panel>
</>}
</Popover>
}
}
@react.component
let make = (~showStepIndicator=true, ~showBreadCrumb=true) => {
open ConnectorTypes
open ConnectorUtils
open APIUtils
let getURL = useGetURL()
let url = RescriptReactRouter.useUrl()
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let connector = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("name", "")
let connectorTypeFromName = connector->getConnectorNameTypeFromString
let connectorID = HSwitchUtils.getConnectorIDFromUrl(url.path->List.toArray, "")
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let updateDetails = useUpdateMethod()
let showToast = ToastState.useShowToast()
let (initialValues, setInitialValues) = React.useState(_ => Dict.make()->JSON.Encode.object)
let (currentStep, setCurrentStep) = React.useState(_ => ConnectorTypes.IntegFields)
let fetchDetails = useGetMethod()
let connectorInfo = ConnectorInterface.mapDictToConnectorPayload(
ConnectorInterface.connectorInterfaceV1,
initialValues->LogicUtils.getDictFromJsonObject,
)
let isUpdateFlow = switch url.path->HSwitchUtils.urlPath {
| list{"payoutconnectors", "new"} => false
| _ => true
}
let getConnectorDetails = async () => {
try {
let connectorUrl = getURL(~entityName=V1(CONNECTOR), ~methodType=Get, ~id=Some(connectorID))
let json = await fetchDetails(connectorUrl)
setInitialValues(_ => json)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to update!")
Exn.raiseError(err)
}
| _ => Exn.raiseError("Something went wrong")
}
}
let commonPageState = () => {
if isUpdateFlow {
setCurrentStep(_ => Preview)
} else {
setCurrentStep(_ => ConnectorTypes.IntegFields)
}
setScreenState(_ => Success)
}
let getDetails = async () => {
try {
setScreenState(_ => Loading)
let _ = await Window.connectorWasmInit()
if isUpdateFlow {
await getConnectorDetails()
}
commonPageState()
setScreenState(_ => Success)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Something went wrong")
setScreenState(_ => Error(err))
}
| _ => setScreenState(_ => Error("Something went wrong"))
}
}
let connectorStatusStyle = connectorStatus =>
switch connectorStatus {
| true => "border bg-red-600 bg-opacity-40 border-red-400 text-red-500"
| false => "border bg-green-600 bg-opacity-40 border-green-700 text-green-700"
}
let isConnectorDisabled = connectorInfo.disabled
let disableConnector = async isConnectorDisabled => {
try {
let connectorID = connectorInfo.merchant_connector_id
let disableConnectorPayload = getDisableConnectorPayload(
connectorInfo.connector_type->connectorTypeTypedValueToStringMapper,
isConnectorDisabled,
)
let url = getURL(~entityName=V1(CONNECTOR), ~methodType=Post, ~id=Some(connectorID))
let _ = await updateDetails(url, disableConnectorPayload->JSON.Encode.object, Post)
showToast(~message="Successfully Saved the Changes", ~toastType=ToastSuccess)
RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/payoutconnectors"))
} catch {
| Exn.Error(_) => showToast(~message="Failed to Disable connector!", ~toastType=ToastError)
}
}
let summaryPageButton = switch currentStep {
| Preview =>
<div className="flex gap-6 items-center">
<div
className={`px-4 py-2 rounded-full w-fit font-medium text-sm !text-black ${isConnectorDisabled->connectorStatusStyle}`}>
{(isConnectorDisabled ? "DISABLED" : "ENABLED")->React.string}
</div>
<MenuOption disableConnector isConnectorDisabled />
</div>
| _ =>
<Button
text="Done"
buttonType=Primary
onClick={_ =>
RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/payoutconnectors"))}
/>
}
React.useEffect(() => {
if connector->LogicUtils.isNonEmptyString {
getDetails()->ignore
} else {
setScreenState(_ => Error("Connector name not found"))
}
None
}, [connector])
<PageLoaderWrapper screenState>
<div className="flex flex-col gap-10 overflow-scroll h-full w-full">
<RenderIf condition={showBreadCrumb}>
<BreadCrumbNavigation
path=[
connectorID === "new"
? {
title: "Payout Processor",
link: "/payoutconnectors",
warning: `You have not yet completed configuring your ${connector->LogicUtils.snakeToTitle} connector. Are you sure you want to go back?`,
}
: {
title: "Payout Processor",
link: "/payoutconnectors",
},
]
currentPageTitle={connector->ConnectorUtils.getDisplayNameForConnector(
~connectorType=PayoutProcessor,
)}
cursorStyle="cursor-pointer"
/>
</RenderIf>
<RenderIf condition={currentStep !== Preview && showStepIndicator}>
<ConnectorCurrentStepIndicator currentStep stepsArr=payoutStepsArr />
</RenderIf>
<RenderIf
condition={connectorTypeFromName->checkIsDummyConnector(featureFlagDetails.testProcessors)}>
<HSwitchUtils.AlertBanner
bannerText="This is a test connector and will not be reflected on your payment processor dashboard."
bannerType=Warning
/>
</RenderIf>
<div
className="bg-white rounded-lg border h-3/4 overflow-scroll shadow-boxShadowMultiple show-scrollbar">
{switch currentStep {
| AutomaticFlow => React.null
| IntegFields =>
<PayoutProcessorAccountDetails
setCurrentStep setInitialValues initialValues isUpdateFlow
/>
| PaymentMethods =>
<PayoutProcessorPaymentMethod
setCurrentStep connector setInitialValues initialValues isUpdateFlow
/>
| SummaryAndTest
| Preview =>
<ConnectorAccountDetailsHelper.ConnectorHeaderWrapper
connector connectorType={PayoutProcessor} headerButton={summaryPageButton}>
<ConnectorPreview.ConnectorSummaryGrid
connectorInfo={ConnectorInterface.mapDictToConnectorPayload(
ConnectorInterface.connectorInterfaceV1,
initialValues->LogicUtils.getDictFromJsonObject,
)}
connector
setCurrentStep
updateStepValue={Some(ConnectorTypes.PaymentMethods)}
getConnectorDetails={Some(getConnectorDetails)}
/>
</ConnectorAccountDetailsHelper.ConnectorHeaderWrapper>
}}
</div>
</div>
</PageLoaderWrapper>
}
| 2,370 | 9,720 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.