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/Connectors/PayoutProcessor/PayoutProcessorList.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 {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
let connectorList = ConnectorInterface.useConnectorArrayMapper(
~interface=ConnectorInterface.connectorInterfaceV1,
~retainInList=PayoutProcessor,
)
let getConnectorListAndUpdateState = async () => {
try {
connectorList->Array.reverse
ConnectorUtils.sortByDisableField(connectorList, connectorPayload =>
connectorPayload.disabled
)
setFilteredConnectorData(_ => connectorList->Array.map(Nullable.make))
setPreviouslyConnectedData(_ => connectorList->Array.map(Nullable.make))
let list = ConnectorInterface.mapConnectorPayloadToConnectorType(
ConnectorInterface.connectorInterfaceV1,
ConnectorTypes.PayoutProcessor,
connectorList,
)
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)
<div>
<PageLoaderWrapper screenState>
<PageUtils.PageHeading
title="Payout Processors"
customHeadingStyle="mb-10"
subTitle="Connect and manage payout processors for disbursements and settlements"
/>
<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={PayoutProcessorTableEntity.payoutProcessorEntity(
"payoutconnectors",
~authorization=userHasAccess(~groupAccess=ConnectorsManage),
)}
currrentFetchCount={filteredConnectorData->Array.length}
collapseTableRow=false
/>
</RenderIf>
<ProcessorCards
configuredConnectors
connectorsAvailableForIntegration={payoutConnectorList}
connectorType={PayoutProcessor}
urlPrefix="payoutconnectors/new"
setProcessorModal
/>
<RenderIf condition={processorModal}>
<DummyProcessorModal
processorModal
setProcessorModal
urlPrefix="payoutconnectors/new"
configuredConnectors
connectorsAvailableForIntegration={payoutConnectorList}
/>
</RenderIf>
</div>
</PageLoaderWrapper>
</div>
}
| 976 | 9,721 |
hyperswitch-control-center | src/screens/Connectors/PayoutProcessor/PayoutProcessorAccountDetails.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("")->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(~connectorType=PayoutProcessor)
let defaultBusinessProfile = Recoil.useRecoilValueFromAtom(HyperswitchAtom.businessProfilesAtom)
let activeBusinessProfile =
defaultBusinessProfile->MerchantAccountUtils.getValueFromBusinessProfile
let connectorDetails = React.useMemo(() => {
try {
if connector->isNonEmptyString {
let dict = Window.getPayoutConnectorConfig(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 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},
~connectorType=ConnectorTypes.PayoutProcessor,
)
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},
~connectorType=ConnectorTypes.PayoutProcessor,
)->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
connectorType={PayoutProcessor}
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">
<ConnectorAccountDetailsHelper.ConnectorConfigurationFields
connector={connector->getConnectorNameTypeFromString(~connectorType=PayoutProcessor)}
connectorAccountFields
selectedConnector={connector
->getConnectorNameTypeFromString(~connectorType=PayoutProcessor)
->getConnectorInfo}
connectorMetaDataFields
connectorWebHookDetails
connectorLabelDetailField
connectorAdditionalMerchantData
/>
</div>
<IntegrationHelp.Render connector setShowModal showModal />
</div>
<FormValuesSpy />
</ConnectorHeaderWrapper>
<VerifyConnectorModal
showVerifyModal
setShowVerifyModal
connector
verifyErrorMessage
suggestedActionExists
suggestedAction
setVerifyDone
/>
</Form>
</PageLoaderWrapper>
}
| 1,878 | 9,722 |
hyperswitch-control-center | src/screens/Connectors/PayoutProcessor/PayoutProcessorPaymentMethod.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=true,
~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,
)
// Need to refactor
let metaData = body->getDictFromJsonObject->getDictfromDict("metadata")->JSON.Encode.object
let _ = ConnectorUtils.updateMetaData(~metaData)
//
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=true
initialValues
setInitialValues
/>
</div>
</div>
</div>
<FormValuesSpy />
</Form>
</PageLoaderWrapper>
}
| 1,085 | 9,723 |
hyperswitch-control-center | src/screens/Connectors/PayoutProcessor/PayoutProcessorTableEntity.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 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 getCell = (connector: connectorPayload, colType): Table.cell => {
switch colType {
| Name =>
CustomCell(
<HelperComponents.ConnectorCustomCell
connectorName=connector.connector_name connectorType={PayoutProcessor}
/>,
"",
)
| 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)
/>,
"",
)
}
}
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,
PayoutProcessor,
)
data
}
let payoutProcessorEntity = (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,
)
},
)
}
| 876 | 9,724 |
hyperswitch-control-center | src/screens/Hooks/BusinessProfileHook.res | .res | let useFetchBusinessProfiles = () => {
open APIUtils
let getURL = useGetURL()
let fetchDetails = useGetMethod()
let setBusinessProfiles = Recoil.useSetRecoilState(HyperswitchAtom.businessProfilesAtom)
async _ => {
try {
let url = getURL(~entityName=V1(BUSINESS_PROFILE), ~methodType=Get)
let res = await fetchDetails(url)
setBusinessProfiles(_ => res->BusinessProfileMapper.getArrayOfBusinessProfile)
Nullable.make(res->BusinessProfileMapper.getArrayOfBusinessProfile)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
Exn.raiseError(err)
}
}
}
}
let useGetBusinessProflile = profileId => {
HyperswitchAtom.businessProfilesAtom
->Recoil.useRecoilValueFromAtom
->Array.find(profile => profile.profile_id == profileId)
->Option.getOr(MerchantAccountUtils.defaultValueForBusinessProfile)
}
| 226 | 9,725 |
hyperswitch-control-center | src/screens/Hooks/ConnectorListHook.res | .res | open APIUtils
open APIUtilsTypes
let useFetchConnectorList = (~entityName=V1(CONNECTOR), ~version=UserInfoTypes.V1) => {
let getURL = useGetURL()
let fetchDetails = useGetMethod()
let setConnectorList = HyperswitchAtom.connectorListAtom->Recoil.useSetRecoilState
async _ => {
try {
let url = getURL(~entityName, ~methodType=Get)
let res = await fetchDetails(url, ~version)
setConnectorList(_ => res)
res
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
Exn.raiseError(err)
}
}
}
}
| 165 | 9,726 |
hyperswitch-control-center | src/screens/Hooks/MerchantSpecificConfigHook.res | .res | /**
* @module MerchantSpecificConfigHook
*
* @description This exposes a hook to fetch the merchant specific config
* and to check if the merchant has access to config
*
* @functions
* - fetchMerchantSpecificConfig : fetches the list of user group level access
* - useIsFeatureEnabledForMerchant: checks if the merchant has access
* @params
* - config : merchant config
*
*
*
*/
type useMerchantSpecificConfig = {
fetchMerchantSpecificConfig: unit => promise<unit>,
useIsFeatureEnabledForMerchant: FeatureFlagUtils.config => bool,
merchantSpecificConfig: FeatureFlagUtils.merchantSpecificConfig,
}
let useMerchantSpecificConfig = () => {
open APIUtils
let updateAPIHook = useUpdateMethod(~showErrorToast=false)
let setMerchantSpecificConfig =
HyperswitchAtom.merchantSpecificConfigAtom->Recoil.useSetRecoilState
let {userInfo: {orgId, merchantId, profileId}} = React.useContext(UserInfoProvider.defaultContext)
let merchantSpecificConfig =
HyperswitchAtom.merchantSpecificConfigAtom->Recoil.useRecoilValueFromAtom
let fetchMerchantSpecificConfig = async () => {
try {
let domain = HyperSwitchEntryUtils.getSessionData(~key="domain", ~defaultValue="")
let merchantConfigURL = ` ${GlobalVars.getHostUrlWithBasePath}/config/merchant?domain=${domain}` // todo: domain shall be removed from query params later
let body =
[
("org_id", orgId->JSON.Encode.string),
("merchant_id", merchantId->JSON.Encode.string),
("profile_id", profileId->JSON.Encode.string),
]->LogicUtils.getJsonFromArrayOfJson
let response = await updateAPIHook(merchantConfigURL, body, Post)
let mapMerchantSpecificConfig = response->FeatureFlagUtils.merchantSpecificConfig
setMerchantSpecificConfig(_ => mapMerchantSpecificConfig)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
Exn.raiseError(err)
}
}
}
let useIsFeatureEnabledForMerchant = (config: FeatureFlagUtils.config) => {
// check if the merchant has access to the config
config.orgId->Option.isNone &&
config.merchantId->Option.isNone &&
config.profileId->Option.isNone
}
{fetchMerchantSpecificConfig, useIsFeatureEnabledForMerchant, merchantSpecificConfig}
}
| 539 | 9,727 |
hyperswitch-control-center | src/screens/Hooks/OMPSwitchHooks.res | .res | type userInfo = {
getUserInfo: unit => promise<UserInfoTypes.userInfo>,
updateTransactionEntity: UserInfoTypes.entity => unit,
updateAnalytcisEntity: UserInfoTypes.entity => unit,
}
let useUserInfo = () => {
open LogicUtils
let fetchApi = AuthHooks.useApiFetcher()
let {setUserInfoData, userInfo} = React.useContext(UserInfoProvider.defaultContext)
let url = `${Window.env.apiBaseUrl}/user`
let {xFeatureRoute, forceCookies} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let getUserInfo = async () => {
try {
let res = await fetchApi(
`${url}`,
~method_=Get,
~xFeatureRoute,
~forceCookies,
~merchantId={userInfo.merchantId},
~profileId={userInfo.profileId},
)
let response = await res->(res => res->Fetch.Response.json)
let userInfo = response->getDictFromJsonObject->UserInfoUtils.itemMapper
userInfo
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
Exn.raiseError(err)
}
}
}
let updateTransactionEntity = (transactionEntity: UserInfoTypes.entity) => {
let updateInfo = {
...userInfo,
transactionEntity,
}
setUserInfoData(updateInfo)
}
let updateAnalytcisEntity = (analyticsEntity: UserInfoTypes.entity) => {
let updateInfo = {
...userInfo,
analyticsEntity,
}
setUserInfoData(updateInfo)
}
{getUserInfo, updateTransactionEntity, updateAnalytcisEntity}
}
let useOrgSwitch = () => {
open APIUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let {getUserInfo} = useUserInfo()
let showToast = ToastState.useShowToast()
let mixpanelEvent = MixpanelHook.useSendEvent()
let {setAuthStatus} = React.useContext(AuthInfoProvider.authStatusContext)
async (~expectedOrgId, ~currentOrgId, ~defaultValue, ~version=UserInfoTypes.V1) => {
try {
if expectedOrgId !== currentOrgId {
let url = getURL(~entityName=V1(USERS), ~userType=#SWITCH_ORG, ~methodType=Post)
let body =
[("org_id", expectedOrgId->JSON.Encode.string)]->LogicUtils.getJsonFromArrayOfJson
mixpanelEvent(~eventName=`switch_org`, ~metadata=expectedOrgId->JSON.Encode.string)
let responseDict = await updateDetails(url, body, Post, ~version)
setAuthStatus(LoggedIn(Auth(AuthUtils.getAuthInfo(responseDict))))
let userInfoRes = await getUserInfo()
showToast(
~message=`Your organization has been switched successfully.`,
~toastType=ToastSuccess,
)
userInfoRes
} else {
defaultValue
}
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
Exn.raiseError(err)
}
}
}
}
let useMerchantSwitch = () => {
open APIUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let showToast = ToastState.useShowToast()
let {getUserInfo} = useUserInfo()
let mixpanelEvent = MixpanelHook.useSendEvent()
let {setAuthStatus} = React.useContext(AuthInfoProvider.authStatusContext)
async (~expectedMerchantId, ~currentMerchantId, ~defaultValue, ~version=UserInfoTypes.V1) => {
try {
if expectedMerchantId !== currentMerchantId {
let body =
[
("merchant_id", expectedMerchantId->JSON.Encode.string),
]->LogicUtils.getJsonFromArrayOfJson
let responseDict = switch version {
| V1 => {
let url = getURL(
~entityName=V1(USERS),
~userType=#SWITCH_MERCHANT_NEW,
~methodType=Post,
)
await updateDetails(url, body, Post)
}
| V2 => {
let url = getURL(
~entityName=V2(USERS),
~userType=#SWITCH_MERCHANT_NEW,
~methodType=Post,
)
await updateDetails(url, body, Post, ~version=V2)
}
}
mixpanelEvent(
~eventName=`switch_merchant`,
~metadata=expectedMerchantId->JSON.Encode.string,
)
setAuthStatus(LoggedIn(Auth(AuthUtils.getAuthInfo(responseDict))))
let userInfoRes = await getUserInfo()
showToast(~message=`Your merchant has been switched successfully.`, ~toastType=ToastSuccess)
userInfoRes
} else {
defaultValue
}
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
Exn.raiseError(err)
}
}
}
}
let useProfileSwitch = () => {
open APIUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let showToast = ToastState.useShowToast()
let {getUserInfo} = useUserInfo()
let mixpanelEvent = MixpanelHook.useSendEvent()
let {setAuthStatus} = React.useContext(AuthInfoProvider.authStatusContext)
async (~expectedProfileId, ~currentProfileId, ~defaultValue, ~version=UserInfoTypes.V1) => {
try {
// Need to remove the Empty string check once userInfo contains the profileId
if expectedProfileId !== currentProfileId && currentProfileId->LogicUtils.isNonEmptyString {
let url = getURL(~entityName=V1(USERS), ~userType=#SWITCH_PROFILE, ~methodType=Post)
let body =
[("profile_id", expectedProfileId->JSON.Encode.string)]->LogicUtils.getJsonFromArrayOfJson
mixpanelEvent(~eventName=`switch_profile`, ~metadata=expectedProfileId->JSON.Encode.string)
let responseDict = await updateDetails(url, body, Post, ~version)
setAuthStatus(LoggedIn(Auth(AuthUtils.getAuthInfo(responseDict))))
let userInfoRes = await getUserInfo()
showToast(~message=`Your profile has been switched successfully.`, ~toastType=ToastSuccess)
userInfoRes
} else {
defaultValue
}
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
Exn.raiseError(err)
}
}
}
}
let useInternalSwitch = () => {
let orgSwitch = useOrgSwitch()
let merchSwitch = useMerchantSwitch()
let profileSwitch = useProfileSwitch()
let {userInfo, setUserInfoData} = React.useContext(UserInfoProvider.defaultContext)
let url = RescriptReactRouter.useUrl()
async (
~expectedOrgId=None,
~expectedMerchantId=None,
~expectedProfileId=None,
~version=UserInfoTypes.V1,
~changePath=false,
) => {
try {
let userInfoResFromSwitchOrg = await orgSwitch(
~expectedOrgId=expectedOrgId->Option.getOr(userInfo.orgId),
~currentOrgId=userInfo.orgId,
~defaultValue=userInfo,
~version,
)
let userInfoResFromSwitchMerch = await merchSwitch(
~expectedMerchantId=expectedMerchantId->Option.getOr(userInfoResFromSwitchOrg.merchantId),
~currentMerchantId=userInfoResFromSwitchOrg.merchantId,
~defaultValue=userInfoResFromSwitchOrg,
~version,
)
let userInfoFromProfile = await profileSwitch(
~expectedProfileId=expectedProfileId->Option.getOr(userInfoResFromSwitchMerch.profileId),
~currentProfileId=userInfoResFromSwitchMerch.profileId,
~defaultValue=userInfoResFromSwitchMerch,
~version,
)
setUserInfoData(userInfoFromProfile)
if changePath {
// When the internal switch is triggered from the dropdown,
// and the current path is "/dashboard/payment/id",
// update the path to "/dashboard/payment" by removing the "id" part.
let currentUrl = GlobalVars.extractModulePath(~path=url.path, ~query="", ~end=2)
RescriptReactRouter.replace(currentUrl)
}
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to switch!")
Exn.raiseError(err)
}
}
}
}
let useOMPData = () => {
open OMPSwitchUtils
let merchantList = Recoil.useRecoilValueFromAtom(HyperswitchAtom.merchantListAtom)
let orgList = Recoil.useRecoilValueFromAtom(HyperswitchAtom.orgListAtom)
let profileList = Recoil.useRecoilValueFromAtom(HyperswitchAtom.profileListAtom)
let {userInfo} = React.useContext(UserInfoProvider.defaultContext)
let getList: unit => OMPSwitchTypes.ompList = _ => {
{
orgList,
merchantList,
profileList,
}
}
let getNameForId = entityType =>
switch entityType {
| #Organization => currentOMPName(orgList, userInfo.orgId)
| #Merchant => currentOMPName(merchantList, userInfo.merchantId)
| #Profile => currentOMPName(profileList, userInfo.profileId)
| _ => ""
}
(getList, getNameForId)
}
| 2,063 | 9,728 |
hyperswitch-control-center | src/screens/Hooks/AnalyticsLogUtilsHook.res | .res | let useAddLogsAroundFetch = () => {
let addLogsAroundFetch = (~setStatusDict=?, ~logTitle, fetchPromise) => {
let setStatusDict = switch setStatusDict {
| Some(fn) => fn
| None => _ => ()
}
setStatusDict(prev => {
let dict =
prev
->Dict.toArray
->Array.filter(entry => {
let (key, _value) = entry
key !== logTitle
})
->Dict.fromArray
dict
})
open Promise
fetchPromise
->then(resp => {
let status = resp->Fetch.Response.status
setStatusDict(prev => {
prev->Dict.set(logTitle, status)
prev
})
if status >= 400 {
Exn.raiseError("err")->reject
} else {
resolve(resp)
}
})
->then(res => res->(res => res->Fetch.Response.json))
->thenResolve(json => {
json
})
->catch(err => {
reject(err)
})
}
addLogsAroundFetch
}
let useAddLogsAroundFetchNew = () => {
let addLogsAroundFetch = (~setStatusDict=?, ~logTitle, fetchPromise) => {
let setStatusDict = switch setStatusDict {
| Some(fn) => fn
| None => _ => ()
}
setStatusDict(prev => {
let dict =
prev
->Dict.toArray
->Array.filter(entry => {
let (key, _value) = entry
key !== logTitle
})
->Dict.fromArray
dict
})
open Promise
fetchPromise
->then(resp => {
let status = resp->Fetch.Response.status
setStatusDict(prev => {
prev->Dict.set(logTitle, status)
prev
})
if status >= 400 {
Exn.raiseError("err")->reject
} else {
resolve(resp)
}
})
->then(res => res->Fetch.Response.text)
->thenResolve(text => {
// will add the check for n line saperated is the length is 0 then no data
// if (
// Array.length(
// json
// ->LogicUtils.getDictFromJsonObject
// ->LogicUtils.getJsonObjectFromDict("queryData")
// ->LogicUtils.getArrayFromJson([]),
// ) === 0
// ) {
// addLogs(
// ~moduleName,
// ~event=`${logTitle} Fetch Ends with no data`,
// ~environment=GlobalVars.environment,
// (),
// )
// }
text
})
->catch(err => {
reject(err)
})
}
addLogsAroundFetch
}
| 603 | 9,729 |
hyperswitch-control-center | src/screens/Hooks/MerchantDetailsHook.res | .res | let useFetchMerchantDetails = () => {
let getURL = APIUtils.useGetURL()
let setMerchantDetailsValue = HyperswitchAtom.merchantDetailsValueAtom->Recoil.useSetRecoilState
let fetchDetails = APIUtils.useGetMethod()
async (~version: UserInfoTypes.version=V1) => {
try {
let merchantDetailsJSON = switch version {
| V1 => {
let accountUrl = getURL(~entityName=V1(MERCHANT_ACCOUNT), ~methodType=Get)
await fetchDetails(accountUrl)
}
| V2 => {
let accountUrl = getURL(~entityName=V2(MERCHANT_ACCOUNT), ~methodType=Get)
await fetchDetails(accountUrl, ~version=V2)
}
}
let jsonToTypedValue = merchantDetailsJSON->MerchantAccountDetailsMapper.getMerchantDetails
setMerchantDetailsValue(_ => jsonToTypedValue)
jsonToTypedValue
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to fetch merchant details!")
Exn.raiseError(err)
}
}
}
}
| 248 | 9,730 |
hyperswitch-control-center | src/screens/Hooks/ClearRecoilValueHook.res | .res | let useClearRecoilValue = () => {
open HyperswitchAtom
let setMerchantDetailsValue = merchantDetailsValueAtom->Recoil.useSetRecoilState
let setBusinessProfilesAtom = businessProfilesAtom->Recoil.useSetRecoilState
let setConnectorListAtom = connectorListAtom->Recoil.useSetRecoilState
let setEnumVariantAtom = enumVariantAtom->Recoil.useSetRecoilState
let setPaypalAccountStatusAtom = paypalAccountStatusAtom->Recoil.useSetRecoilState
let setUserPermissionAtom = userPermissionAtom->Recoil.useSetRecoilState
let setUserGroupACLAtom = userGroupACLAtom->Recoil.useSetRecoilState
let setSwitchMerchantListAtom = switchMerchantListAtom->Recoil.useSetRecoilState
let setCurrentTabNameRecoilAtom = currentTabNameRecoilAtom->Recoil.useSetRecoilState
let setOrgListRecoilAtom = orgListAtom->Recoil.useSetRecoilState
let setMerchantListRecoilAtom = merchantListAtom->Recoil.useSetRecoilState
let setProfileListRecoilAtom = profileListAtom->Recoil.useSetRecoilState
let setModuleListListRecoilAtom = moduleListRecoil->Recoil.useSetRecoilState
let clearRecoilValue = () => {
setMerchantDetailsValue(_ => JSON.Encode.null->MerchantAccountDetailsMapper.getMerchantDetails)
setBusinessProfilesAtom(_ => JSON.Encode.null->BusinessProfileMapper.getArrayOfBusinessProfile)
setConnectorListAtom(_ => JSON.Encode.null)
setEnumVariantAtom(_ => "")
setPaypalAccountStatusAtom(_ => PayPalFlowTypes.Connect_paypal_landing)
setUserPermissionAtom(_ => GroupACLMapper.defaultValueForGroupAccessJson)
setUserGroupACLAtom(_ => None)
setSwitchMerchantListAtom(_ => [SwitchMerchantUtils.defaultValue])
setCurrentTabNameRecoilAtom(_ => "ActiveTab")
setOrgListRecoilAtom(_ => [ompDefaultValue])
setMerchantListRecoilAtom(_ => [ompDefaultValue])
setProfileListRecoilAtom(_ => [ompDefaultValue])
setModuleListListRecoilAtom(_ => [])
}
clearRecoilValue
}
| 480 | 9,731 |
hyperswitch-control-center | src/screens/Hooks/TotpHooks.res | .res | let useVerifyTotp = () => {
open APIUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
async (body, methodType) => {
try {
let url = getURL(~entityName=V1(USERS), ~userType=#VERIFY_TOTP, ~methodType)
let response = await updateDetails(url, body, methodType)
response
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
Exn.raiseError(err)
}
}
}
}
let useVerifyRecoveryCode = () => {
open APIUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
async body => {
try {
let url = getURL(~entityName=V1(USERS), ~userType=#VERIFY_RECOVERY_CODE, ~methodType=Post)
let response = await updateDetails(url, body, Post)
response
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
Exn.raiseError(err)
}
}
}
}
| 266 | 9,732 |
hyperswitch-control-center | src/screens/Hooks/GroupACLHooks.res | .res | /**
* @module GroupACLHook
*
* @description This exposes a hook to call the list of user group access
* and to check if the user has access to that group
*
* @functions
* - fetchUserGroupACL : fetches the list of user group level access
* - userHasAccess: checks if the user has access to that group or not
* @params
* - groupAccess : group to check if the user has access or not
*
*
*/
open CommonAuthTypes
type userGroupACLType = {
fetchUserGroupACL: unit => promise<UserManagementTypes.groupAccessJsonType>,
userHasResourceAccess: (
~resourceAccess: UserManagementTypes.resourceAccessType,
) => CommonAuthTypes.authorization,
userHasAccess: (
~groupAccess: UserManagementTypes.groupAccessType,
) => CommonAuthTypes.authorization,
hasAnyGroupAccess: (
CommonAuthTypes.authorization,
CommonAuthTypes.authorization,
) => CommonAuthTypes.authorization,
hasAllGroupsAccess: array<CommonAuthTypes.authorization> => CommonAuthTypes.authorization,
}
let useUserGroupACLHook = () => {
open APIUtils
open LogicUtils
open GroupACLMapper
open HyperswitchAtom
let getURL = useGetURL()
let fetchDetails = useGetMethod()
let (userGroupACL, setuserGroupACL) = Recoil.useRecoilState(userGroupACLAtom)
let setuserPermissionJson = Recoil.useSetRecoilState(userPermissionAtom)
let fetchUserGroupACL = async () => {
try {
let url = getURL(~entityName=V1(USERS), ~userType=#GET_GROUP_ACL, ~methodType=Get)
let response = await fetchDetails(url)
let dict = response->getDictFromJsonObject
let groupsAccessValue = getStrArrayFromDict(dict, "groups", [])
let resourcesAccessValue = getStrArrayFromDict(dict, "resources", [])
let userGroupACLMap =
groupsAccessValue->Array.map(ele => ele->mapStringToGroupAccessType)->convertValueToMapGroup
let resourceACLMap =
resourcesAccessValue
->Array.map(ele => ele->mapStringToResourceAccessType)
->convertValueToMapResources
setuserGroupACL(_ => Some({
groups: userGroupACLMap,
resources: resourceACLMap,
}))
let permissionJson =
groupsAccessValue->Array.map(ele => ele->mapStringToGroupAccessType)->getGroupAccessJson
setuserPermissionJson(_ => permissionJson)
permissionJson
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
Exn.raiseError(err)
}
}
}
let userHasAccess = (~groupAccess) => {
switch userGroupACL {
| Some(groupACLValue) =>
switch groupACLValue.groups->Map.get(groupAccess) {
| Some(value) => value
| None => NoAccess
}
| None => NoAccess
}
}
let userHasResourceAccess = (~resourceAccess) => {
switch userGroupACL {
| Some(groupACLValue) =>
switch groupACLValue.resources->Map.get(resourceAccess) {
| Some(value) => value
| None => NoAccess
}
| None => NoAccess
}
}
let hasAnyGroupAccess = (group1, group2) =>
switch (group1, group2) {
| (NoAccess, NoAccess) => NoAccess
| (_, _) => Access
}
let hasAllGroupsAccess = groups => {
groups->Array.every(group => group === Access) ? Access : NoAccess
}
{
fetchUserGroupACL,
userHasResourceAccess,
userHasAccess,
hasAnyGroupAccess,
hasAllGroupsAccess,
}
}
| 843 | 9,733 |
hyperswitch-control-center | src/screens/Hooks/OMPCreateAccessHook.res | .res | type adminType = [#tenant_admin | #org_admin | #merchant_admin | #non_admin]
let roleIdVariantMapper: string => adminType = roleId => {
switch roleId {
| "tenant_admin" => #tenant_admin
| "org_admin" => #org_admin
| "merchant_admin" => #merchant_admin
| _ => #non_admin
}
}
let useOMPCreateAccessHook: array<adminType> => CommonAuthTypes.authorization = allowedRoles => {
let {userInfo: {roleId}} = React.useContext(UserInfoProvider.defaultContext)
let roleIdTypedValue = roleId->roleIdVariantMapper
allowedRoles->Array.includes(roleIdTypedValue) ? Access : NoAccess
}
| 151 | 9,734 |
hyperswitch-control-center | src/screens/OMPSwitch/OMPSwitchUtils.res | .res | open OMPSwitchTypes
let ompDefaultValue = (currUserId, currUserName) => {
id: currUserId,
name: {currUserName->LogicUtils.isEmptyString ? currUserId : currUserName},
}
let currentOMPName = (list: array<ompListTypes>, id: string) => {
switch list->Array.find(user => user.id == id) {
| Some(user) => user.name
| None => id
}
}
let orgItemToObjMapper = dict => {
open LogicUtils
{
id: dict->getString("org_id", ""),
name: {
dict->getString("org_name", "")->isEmptyString
? dict->getString("org_id", "")
: dict->getString("org_name", "")
},
}
}
let merchantItemToObjMapper: Dict.t<'t> => OMPSwitchTypes.ompListTypes = dict => {
open LogicUtils
{
id: dict->getString("merchant_id", ""),
name: {
dict->getString("merchant_name", "")->isEmptyString
? dict->getString("merchant_id", "")
: dict->getString("merchant_name", "")
},
productType: dict->getString("product_type", "")->ProductUtils.getProductVariantFromString,
version: dict->getString("version", "v1")->UserInfoUtils.versionMapper,
}
}
let profileItemToObjMapper = dict => {
open LogicUtils
{
id: dict->getString("profile_id", ""),
name: {
dict->getString("profile_name", "")->isEmptyString
? dict->getString("profile_id", "")
: dict->getString("profile_name", "")
},
}
}
let org = {
lable: "Organization",
entity: #Organization,
}
let merchant = {
lable: "Merchant",
entity: #Merchant,
}
let profile = {
lable: "Profile",
entity: #Profile,
}
let transactionViewList = (~checkUserEntity): ompViews => {
if checkUserEntity([#Tenant, #Merchant, #Organization]) {
[merchant, profile]
} else if checkUserEntity([#Profile]) {
[profile]
} else {
[]
}
}
let analyticsViewList = (~checkUserEntity): ompViews => {
if checkUserEntity([#Tenant, #Organization]) {
[org, merchant, profile]
} else if checkUserEntity([#Merchant]) {
[merchant, profile]
} else if checkUserEntity([#Profile]) {
[profile]
} else {
[]
}
}
let keyExtractorForMerchantid = item => {
open LogicUtils
let dict = item->getDictFromJsonObject
dict->getString("merchant_id", "")
}
| 587 | 9,735 |
hyperswitch-control-center | src/screens/OMPSwitch/MerchantSwitch.res | .res | module NewMerchantCreationModal = {
@react.component
let make = (~setShowModal, ~showModal, ~getMerchantList) => {
open APIUtils
let getURL = useGetURL()
let mixpanelEvent = MixpanelHook.useSendEvent()
let updateDetails = useUpdateMethod()
let showToast = ToastState.useShowToast()
let {activeProduct} = React.useContext(ProductSelectionProvider.defaultContext)
let createNewMerchant = async values => {
try {
switch activeProduct {
| Orchestration
| DynamicRouting
| CostObservability => {
let url = getURL(~entityName=V1(USERS), ~userType=#CREATE_MERCHANT, ~methodType=Post)
let _ = await updateDetails(url, values, Post)
}
| _ => {
let url = getURL(~entityName=V2(USERS), ~userType=#CREATE_MERCHANT, ~methodType=Post)
let _ = await updateDetails(url, values, Post, ~version=V2)
}
}
mixpanelEvent(~eventName="create_new_merchant", ~metadata=values)
getMerchantList()->ignore
showToast(
~toastType=ToastSuccess,
~message="Merchant Created Successfully!",
~autoClose=true,
)
} catch {
| _ => showToast(~toastType=ToastError, ~message="Merchant Creation Failed", ~autoClose=true)
}
setShowModal(_ => false)
Nullable.null
}
let initialValues = React.useMemo(() => {
let dict = Dict.make()
dict->Dict.set(
"product_type",
(Obj.magic(activeProduct) :> string)->String.toLowerCase->JSON.Encode.string,
)
dict->JSON.Encode.object
}, [activeProduct])
let onSubmit = (values, _) => {
open LogicUtils
let dict = values->getDictFromJsonObject
let trimmedData = dict->getString("company_name", "")->String.trim
Dict.set(dict, "company_name", trimmedData->JSON.Encode.string)
createNewMerchant(dict->JSON.Encode.object)
}
let merchantName = FormRenderer.makeFieldInfo(
~label="Merchant Name",
~name="company_name",
~customInput=(~input, ~placeholder as _) =>
InputFields.textInput()(
~input={
...input,
onChange: event =>
ReactEvent.Form.target(event)["value"]
->String.trimStart
->Identity.stringToFormReactEvent
->input.onChange,
},
~placeholder="Eg: My New Merchant",
),
~isRequired=true,
)
let validateForm = (values: JSON.t) => {
open LogicUtils
let errors = Dict.make()
let companyName = values->getDictFromJsonObject->getString("company_name", "")->String.trim
let regexForCompanyName = "^([a-z]|[A-Z]|[0-9]|_|\\s)+$"
let errorMessage = if companyName->isEmptyString {
"Merchant name cannot be empty"
} else if companyName->String.length > 64 {
"Merchant name cannot exceed 64 characters"
} else if !RegExp.test(RegExp.fromString(regexForCompanyName), companyName) {
"Merchant name should not contain special characters"
} else {
""
}
if errorMessage->isNonEmptyString {
Dict.set(errors, "company_name", errorMessage->JSON.Encode.string)
}
errors->JSON.Encode.object
}
let modalBody = {
<div className="">
<div className="pt-3 m-3 flex justify-between">
<CardUtils.CardHeader
heading="Add a new merchant"
subHeading=""
customSubHeadingStyle="w-full !max-w-none pr-10"
/>
<div className="h-fit" onClick={_ => setShowModal(_ => false)}>
<Icon name="modal-close-icon" className="cursor-pointer" size=30 />
</div>
</div>
<hr />
<Form key="new-merchant-creation" onSubmit validate={validateForm} initialValues>
<div className="flex flex-col h-full w-full">
<div className="py-10">
<FormRenderer.DesktopRow>
<FormRenderer.FieldRenderer
fieldWrapperClass="w-full"
field={merchantName}
showErrorOnChange=true
errorClass={ProdVerifyModalUtils.errorClass}
labelClass="!text-black font-medium !-ml-[0.5px]"
/>
</FormRenderer.DesktopRow>
</div>
<hr className="mt-4" />
<div className="flex justify-end w-full p-3">
<FormRenderer.SubmitButton text="Add Merchant" buttonSize=Small />
</div>
</div>
</Form>
</div>
}
<Modal
showModal
closeOnOutsideClick=true
setShowModal
childClass="p-0"
borderBottom=true
modalClass="w-full max-w-xl mx-auto my-auto dark:!bg-jp-gray-lightgray_background">
modalBody
</Modal>
}
}
@react.component
let make = () => {
open APIUtils
open LogicUtils
open OMPSwitchUtils
open OMPSwitchHelper
let getURL = useGetURL()
let fetchDetails = useGetMethod()
let showToast = ToastState.useShowToast()
let internalSwitch = OMPSwitchHooks.useInternalSwitch()
let {userInfo: {merchantId}} = React.useContext(UserInfoProvider.defaultContext)
let (showModal, setShowModal) = React.useState(_ => false)
let (merchantList, setMerchantList) = Recoil.useRecoilState(HyperswitchAtom.merchantListAtom)
let isMobileView = MatchMedia.useMobileChecker()
let merchantDetailsTypedValue = Recoil.useRecoilValueFromAtom(
HyperswitchAtom.merchantDetailsValueAtom,
)
let (showSwitchingMerch, setShowSwitchingMerch) = React.useState(_ => false)
let (arrow, setArrow) = React.useState(_ => false)
let {
globalUIConfig: {
sidebarColor: {backgroundColor, primaryTextColor, borderColor, secondaryTextColor},
},
} = React.useContext(ThemeProvider.themeContext)
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let {devModularityV2} = featureFlagDetails
let {setActiveProductValue} = React.useContext(ProductSelectionProvider.defaultContext)
let getV2MerchantList = async () => {
try {
let v2MerchantListUrl = getURL(
~entityName=V2(USERS),
~userType=#LIST_MERCHANT,
~methodType=Get,
)
let v2MerchantResponse = await fetchDetails(v2MerchantListUrl, ~version=V2)
v2MerchantResponse->getArrayFromJson([])
} catch {
| _ => []
}
}
let getMerchantList = async () => {
try {
let v1MerchantListUrl = getURL(
~entityName=V1(USERS),
~userType=#LIST_MERCHANT,
~methodType=Get,
)
let v1MerchantResponse = await fetchDetails(v1MerchantListUrl)
let v2MerchantList = if devModularityV2 {
await getV2MerchantList()
} else {
[]
}
let concatenatedList = v1MerchantResponse->getArrayFromJson([])->Array.concat(v2MerchantList)
let response =
concatenatedList->LogicUtils.uniqueObjectFromArrayOfObjects(keyExtractorForMerchantid)
let concatenatedListTyped = response->getMappedValueFromArrayOfJson(merchantItemToObjMapper)
setMerchantList(_ => concatenatedListTyped)
} catch {
| _ => {
setMerchantList(_ => [ompDefaultValue(merchantId, "")])
showToast(~message="Failed to fetch merchant list", ~toastType=ToastError)
}
}
}
let switchMerch = async value => {
try {
setShowSwitchingMerch(_ => true)
let merchantData =
merchantList
->Array.find(merchant => merchant.id == value)
->Option.getOr(ompDefaultValue(merchantId, ""))
let version = merchantData.version->Option.getOr(UserInfoTypes.V1)
let productType = merchantData.productType->Option.getOr(Orchestration)
let _ = await internalSwitch(~expectedMerchantId=Some(value), ~version, ~changePath=true)
setActiveProductValue(productType)
setShowSwitchingMerch(_ => false)
} catch {
| _ => {
showToast(~message="Failed to switch merchant", ~toastType=ToastError)
setShowSwitchingMerch(_ => false)
}
}
}
let input: ReactFinalForm.fieldRenderPropsInput = {
name: "name",
onBlur: _ => (),
onChange: ev => {
let value = ev->Identity.formReactEventToString
switchMerch(value)->ignore
},
onFocus: _ => (),
value: merchantId->JSON.Encode.string,
checked: true,
}
let widthClass = isMobileView ? "w-full" : "md:w-60 md:max-w-80"
let roundedClass = isMobileView ? "rounded-none" : "rounded-md"
let addItemBtnStyle = `w-full ${borderColor} border-t-0`
let customScrollStyle = `max-h-72 overflow-scroll px-1 pt-1 ${borderColor}`
let dropdownContainerStyle = `${roundedClass} border border-1 ${borderColor} ${widthClass}`
let subHeading = {currentOMPName(merchantList, merchantId)}
React.useEffect(() => {
if subHeading != merchantDetailsTypedValue.merchant_name->Option.getOr("") {
getMerchantList()->ignore
}
None
}, [merchantDetailsTypedValue.merchant_name])
let toggleChevronState = () => {
setArrow(prev => !prev)
}
let updatedMerchantList: array<
OMPSwitchTypes.ompListTypesCustom,
> = merchantList->Array.mapWithIndex((item, i) => {
let customComponent =
<MerchantDropdownItem
key={Int.toString(i)}
merchantName=item.name
productType={switch item.productType {
| Some(product) => product
| None => Orchestration
}}
index=i
currentId=item.id
getMerchantList
switchMerch
/>
let listItem: OMPSwitchTypes.ompListTypesCustom = {
id: item.id,
name: item.name,
customComponent,
}
listItem
})
<div className="w-fit">
<SelectBox.BaseDropdown
allowMultiSelect=false
buttonText=""
input
deselectDisable=true
options={updatedMerchantList->generateDropdownOptionsCustomComponent}
marginTop={`mt-12 ${borderColor} shadow-generic_shadow`}
hideMultiSelectButtons=true
addButton=false
customStyle={`!border-none w-fit ${backgroundColor.sidebarSecondary} !${borderColor} `}
searchable=true
baseComponent={<ListBaseComp user=#Merchant heading="Merchant" subHeading arrow />}
baseComponentCustomStyle={`!border-none`}
bottomComponent={<AddNewOMPButton
user=#Merchant
setShowModal
customStyle={`${backgroundColor.sidebarSecondary} ${primaryTextColor} ${borderColor} !border-none`}
addItemBtnStyle
customHRTagStyle={`${borderColor}`}
/>}
toggleChevronState
customScrollStyle
dropdownContainerStyle
shouldDisplaySelectedOnTop=true
customSearchStyle={`${backgroundColor.sidebarSecondary} ${secondaryTextColor} ${borderColor}`}
searchInputPlaceHolder="Search Merchant Account or ID"
placeholderCss={`text-fs-13 ${backgroundColor.sidebarSecondary}`}
/>
<RenderIf condition={showModal}>
<NewMerchantCreationModal setShowModal showModal getMerchantList />
</RenderIf>
<LoaderModal
showModal={showSwitchingMerch}
setShowModal={setShowSwitchingMerch}
text="Switching merchant..."
/>
</div>
}
| 2,638 | 9,736 |
hyperswitch-control-center | src/screens/OMPSwitch/SwitchMerchantForInternal.res | .res | @react.component
let make = () => {
let showToast = ToastState.useShowToast()
let showPopUp = PopUpState.useShowPopUp()
let internalSwitch = OMPSwitchHooks.useInternalSwitch()
let (value, setValue) = React.useState(() => "")
let {userInfo: {merchantId}} = React.useContext(UserInfoProvider.defaultContext)
let input = React.useMemo((): ReactFinalForm.fieldRenderPropsInput => {
{
name: "-",
onBlur: _ => (),
onChange: ev => {
let value = {ev->ReactEvent.Form.target}["value"]
if value->String.includes("<script>") || value->String.includes("</script>") {
showPopUp({
popUpType: (Warning, WithIcon),
heading: `Script Tags are not allowed`,
description: React.string(`Input cannot contain <script>, </script> tags`),
handleConfirm: {text: "OK"},
})
}
let val = value->String.replace("<script>", "")->String.replace("</script>", "")
setValue(_ => val)
},
onFocus: _ => (),
value: JSON.Encode.string(value),
checked: false,
}
}, [value])
let switchMerchant = async () => {
try {
let _ = await internalSwitch(~expectedMerchantId=Some(value))
} catch {
| _ => showToast(~message="Failed to switch the merchant! Try again.", ~toastType=ToastError)
}
}
let handleKeyUp = event => {
if event->ReactEvent.Keyboard.keyCode === 13 {
switchMerchant()->ignore
}
}
<div className="flex items-center gap-4">
<div
className={`p-3 rounded-lg whitespace-nowrap text-fs-13 bg-hyperswitch_green_trans border-hyperswitch_green_trans text-hyperswitch_green font-semibold`}>
{merchantId->React.string}
</div>
<TextInput input customWidth="w-80" placeholder="Switch merchant" onKeyUp=handleKeyUp />
</div>
}
| 446 | 9,737 |
hyperswitch-control-center | src/screens/OMPSwitch/OMPSwitchHelper.res | .res | module ListBaseComp = {
@react.component
let make = (
~heading="",
~subHeading,
~arrow,
~showEditIcon=false,
~onEditClick=_ => (),
~isDarkBg=false,
~showDropdownArrow=true,
~user: UserInfoTypes.entity,
) => {
let {globalUIConfig: {sidebarColor: {secondaryTextColor}}} = React.useContext(
ThemeProvider.themeContext,
)
let arrowClassName = isDarkBg
? `${arrow
? "rotate-180"
: "-rotate-0"} transition duration-[250ms] opacity-70 ${secondaryTextColor}`
: `${arrow
? "rotate-0"
: "rotate-180"} transition duration-[250ms] opacity-70 ${secondaryTextColor}`
<>
{switch user {
| #Merchant =>
<div
className={`text-sm cursor-pointer font-semibold ${secondaryTextColor} hover:bg-opacity-80 flex flex-col gap-1`}>
<span className={`text-xs ${secondaryTextColor} opacity-50 font-medium`}>
{"Merchant Account"->React.string}
</span>
<div className="text-left flex gap-2 w-13.5-rem justify-between">
<p
className={`fs-10 ${secondaryTextColor} overflow-scroll text-nowrap whitespace-pre `}>
{subHeading->React.string}
</p>
{showDropdownArrow
? <Icon className={`${arrowClassName} ml-1`} name="nd-angle-down" size=12 />
: React.null}
</div>
</div>
| #Profile =>
<div
className="flex flex-row cursor-pointer items-center p-3 gap-2 md:min-w-44 justify-between h-8 bg-white border rounded-lg border-nd_gray-100 shadow-sm">
<div className="md:max-w-40 max-w-16">
<p
className="overflow-scroll text-nowrap text-sm font-medium text-nd_gray-500 whitespace-pre">
<span className={`text-xs text-nd_gray-400 font-medium`}>
{"Profile : "->React.string}
</span>
{React.string(subHeading)}
</p>
</div>
{showDropdownArrow
? <Icon className={`${arrowClassName} ml-1`} name="nd-angle-down" size=12 />
: React.null}
</div>
| _ => React.null
}}
</>
}
}
module AddNewOMPButton = {
@react.component
let make = (
~user: UserInfoTypes.entity,
~setShowModal,
~customPadding="",
~customStyle="",
~customHRTagStyle="",
~addItemBtnStyle="",
) => {
let allowedRoles = switch user {
| #Organization => [#tenant_admin]
| #Merchant => [#tenant_admin, #org_admin]
| #Profile => [#tenant_admin, #org_admin, #merchant_admin]
| _ => []
}
let hasOMPCreateAccess = OMPCreateAccessHook.useOMPCreateAccessHook(allowedRoles)
let cursorStyles = GroupAccessUtils.cursorStyles(hasOMPCreateAccess)
<ACLDiv
authorization={hasOMPCreateAccess}
noAccessDescription="You do not have the required permissions for this action. Please contact your admin."
onClick={_ => setShowModal(_ => true)}
isRelative=false
contentAlign=Default
tooltipForWidthClass="!h-full"
className={`${cursorStyles} ${customPadding} ${addItemBtnStyle}`}
showTooltip={hasOMPCreateAccess == Access}>
{<>
<hr className={customHRTagStyle} />
<div
className={` flex items-center gap-2 font-medium px-3.5 py-3 text-sm ${customStyle}`}>
<Icon name="nd-plus" size=15 />
{`Create new`->React.string}
</div>
</>}
</ACLDiv>
}
}
module OMPViewBaseComp = {
@react.component
let make = (~displayName, ~arrow) => {
let arrowUpClass = "rotate-0 transition duration-[250ms] opacity-70"
let arrowDownClass = "rotate-180 transition duration-[250ms] opacity-70"
let truncatedDisplayName = if displayName->String.length > 15 {
<HelperComponents.EllipsisText
displayValue=displayName endValue=15 showCopy=false expandText=false
/>
} else {
{displayName->React.string}
}
<div
className="flex items-center text-sm font-medium cursor-pointer border-1.5 border-double border-transparent secondary-gradient-button rounded-lg h-40-px">
<div className="flex flex-col items-start">
<div className="text-left flex items-center gap-1 p-2">
<Icon name="settings-new" size=18 />
<p className="text-jp-gray-900 fs-10 overflow-scroll text-nowrap">
{`View data for:`->React.string}
</p>
<span className="text-primary text-nowrap"> {truncatedDisplayName} </span>
<Icon
className={`${arrow ? arrowDownClass : arrowUpClass} ml-1`}
name="arrow-without-tail"
size=15
/>
</div>
</div>
</div>
}
}
let generateDropdownOptionsOMPViews = (dropdownList: OMPSwitchTypes.ompViews, getNameForId) => {
let options: array<SelectBox.dropdownOption> = dropdownList->Array.map((
item
): SelectBox.dropdownOption => {
{
label: `${item.entity->getNameForId}`,
value: `${(item.entity :> string)}`,
labelDescription: `(${item.lable})`,
description: `${item.entity->getNameForId}`,
}
})
options
}
module OMPViewsComp = {
@react.component
let make = (~input, ~options, ~displayName, ~entityMapper=UserInfoUtils.entityMapper) => {
let (arrow, setArrow) = React.useState(_ => false)
let toggleChevronState = () => {
setArrow(prev => !prev)
}
let customScrollStyle = "md:max-h-72 md:overflow-scroll md:px-1 md:pt-1"
let dropdownContainerStyle = "rounded-lg border md:w-full md:shadow-md"
<div className="flex h-fit rounded-lg hover:bg-opacity-80">
<SelectBox.BaseDropdown
allowMultiSelect=false
buttonText=""
input
deselectDisable=true
customButtonStyle="!rounded-md"
options
marginTop="mt-8"
hideMultiSelectButtons=false
addButton=false
customStyle="md:rounded"
searchable=false
baseComponent={<OMPViewBaseComp displayName arrow />}
baseComponentCustomStyle="bg-white rounded-lg"
optionClass="font-inter text-fs-14 font-normal leading-5"
selectClass="font-inter text-fs-14 font-normal leading-5 font-semibold"
labelDescriptionClass="font-inter text-fs-12 font-normal leading-4"
customDropdownOuterClass="!border-none !w-full"
toggleChevronState
customScrollStyle
dropdownContainerStyle
shouldDisplaySelectedOnTop=true
descriptionOnHover=true
textEllipsisForDropDownOptions=true
/>
</div>
}
}
module OMPViews = {
@react.component
let make = (
~views: OMPSwitchTypes.ompViews,
~selectedEntity: UserInfoTypes.entity,
~onChange,
~entityMapper=UserInfoUtils.entityMapper,
) => {
let (_, getNameForId) = OMPSwitchHooks.useOMPData()
let input: ReactFinalForm.fieldRenderPropsInput = {
name: "name",
onBlur: _ => (),
onChange: ev => {
let value = ev->Identity.formReactEventToString
onChange(value->UserInfoUtils.entityMapper)->ignore
},
onFocus: _ => (),
value: (selectedEntity :> string)->JSON.Encode.string,
checked: true,
}
let options = views->generateDropdownOptionsOMPViews(getNameForId)
let displayName = selectedEntity->getNameForId
<OMPViewsComp input options displayName />
}
}
module MerchantDropdownItem = {
@react.component
let make = (
~merchantName,
~productType,
~index: int,
~currentId,
~getMerchantList,
~switchMerch,
) => {
open LogicUtils
open APIUtils
open ProductTypes
open ProductUtils
let (currentlyEditingId, setUnderEdit) = React.useState(_ => None)
let handleIdUnderEdit = (selectedEditId: option<int>) => {
setUnderEdit(_ => selectedEditId)
}
let {
globalUIConfig: {sidebarColor: {backgroundColor, hoverColor, secondaryTextColor}},
} = React.useContext(ThemeProvider.themeContext)
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let showToast = ToastState.useShowToast()
let {userInfo: {merchantId, version}} = React.useContext(UserInfoProvider.defaultContext)
let (showSwitchingMerch, setShowSwitchingMerch) = React.useState(_ => false)
let isUnderEdit =
currentlyEditingId->Option.isSome && currentlyEditingId->Option.getOr(0) == index
let isMobileView = MatchMedia.useMobileChecker()
let productTypeIconMapper = productType => {
switch productType {
| Orchestration => "orchestrator-home"
| Recon => "recon-home"
| Recovery => "recovery-home"
| Vault => "vault-home"
| CostObservability => "nd-piggy-bank"
| DynamicRouting => "intelligent-routing-home"
| _ => "orchestrator-home"
}
}
let isActive = currentId == merchantId
let leftIconCss = {isActive && !isUnderEdit ? "" : isUnderEdit ? "hidden" : "invisible"}
let leftIcon = if isActive && !isUnderEdit {
<Icon name="nd-check" className={`${leftIconCss} ${secondaryTextColor}`} />
} else if isActive && isUnderEdit {
React.null
} else if !isActive && !isUnderEdit {
<ToolTip
description={productType->getProductDisplayName}
customStyle="!whitespace-nowrap"
toolTipFor={<Icon
name={productType->productTypeIconMapper}
className={`${secondaryTextColor} opacity-50`}
size=14
/>}
toolTipPosition=ToolTip.Top
/>
} else {
React.null // Default case
}
let validateInput = (merchantName: string) => {
let errors = Dict.make()
let regexForMerchantName = "^([a-z]|[A-Z]|[0-9]|_|\\s)+$"
let errorMessage = if merchantName->isEmptyString {
"Merchant name cannot be empty"
} else if merchantName->String.length > 64 {
"Merchant name cannot exceed 64 characters"
} else if !RegExp.test(RegExp.fromString(regexForMerchantName), merchantName) {
"Merchant name should not contain special characters"
} else {
""
}
if errorMessage->isNonEmptyString {
Dict.set(errors, "merchant_name", errorMessage->JSON.Encode.string)
}
errors
}
let handleMerchantSwitch = id => {
if !isActive {
switchMerch(id)->ignore
}
}
let onSubmit = async (newMerchantName: string) => {
try {
if version == V2 {
let body =
[("merchant_name", newMerchantName->JSON.Encode.string)]->getJsonFromArrayOfJson
let accountUrl = getURL(
~entityName=V2(MERCHANT_ACCOUNT),
~methodType=Put,
~id=Some(merchantId),
)
let _ = await updateDetails(accountUrl, body, Put)
} else {
let body =
[
("merchant_id", merchantId->JSON.Encode.string),
("merchant_name", newMerchantName->JSON.Encode.string),
]->getJsonFromArrayOfJson
let accountUrl = getURL(
~entityName=V1(MERCHANT_ACCOUNT),
~methodType=Post,
~id=Some(merchantId),
)
let _ = await updateDetails(accountUrl, body, Post)
}
getMerchantList()->ignore
showToast(~message="Updated Merchant name!", ~toastType=ToastSuccess)
} catch {
| _ => showToast(~message="Failed to update Merchant name!", ~toastType=ToastError)
}
}
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
<>
<div className={`rounded-lg mb-1`}>
<InlineEditInput
index
labelText=merchantName
customStyle={`w-full cursor-pointer mb-0 ${backgroundColor.sidebarSecondary} ${hoverColor} `}
handleEdit=handleIdUnderEdit
isUnderEdit
showEditIcon={isActive && userHasAccess(~groupAccess=MerchantDetailsManage) === Access}
showEditIconOnHover={!isMobileView}
onSubmit
labelTextCustomStyle={` truncate max-w-28 ${isActive
? `${secondaryTextColor}`
: `${secondaryTextColor}`}`}
validateInput
customInputStyle={`!py-0 ${secondaryTextColor}`}
customIconComponent={<ToolTip
description={currentId}
customStyle="!whitespace-nowrap"
toolTipFor={<div className="cursor-pointer">
<HelperComponents.CopyTextCustomComp
customIconCss={`${secondaryTextColor}`}
displayValue=Some("")
copyValue=Some({currentId})
/>
</div>}
toolTipPosition=ToolTip.Right
/>}
customIconStyle={isActive ? `${secondaryTextColor}` : ""}
handleClick={_ => handleMerchantSwitch(currentId)}
customWidth="min-w-56"
leftIcon
/>
</div>
<LoaderModal
showModal={showSwitchingMerch}
setShowModal={setShowSwitchingMerch}
text="Switching merchant..."
/>
</>
}
}
module ProfileDropdownItem = {
@react.component
let make = (~profileName, ~index: int, ~currentId) => {
open LogicUtils
open APIUtils
let (currentlyEditingId, setUnderEdit) = React.useState(_ => None)
let handleIdUnderEdit = (selectedEditId: option<int>) => {
setUnderEdit(_ => selectedEditId)
}
let internalSwitch = OMPSwitchHooks.useInternalSwitch()
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let fetchDetails = useGetMethod()
let showToast = ToastState.useShowToast()
let {userInfo: {profileId, version}} = React.useContext(UserInfoProvider.defaultContext)
let (showSwitchingProfile, setShowSwitchingProfile) = React.useState(_ => false)
let isUnderEdit =
currentlyEditingId->Option.isSome && currentlyEditingId->Option.getOr(0) == index
let (_, setProfileList) = Recoil.useRecoilState(HyperswitchAtom.profileListAtom)
let isMobileView = MatchMedia.useMobileChecker()
let isActive = currentId == profileId
let getProfileList = async () => {
try {
let response = switch version {
| V1 => {
let url = getURL(~entityName=V1(USERS), ~userType=#LIST_PROFILE, ~methodType=Get)
await fetchDetails(url)
}
| V2 => {
let url = getURL(~entityName=V2(USERS), ~userType=#LIST_PROFILE, ~methodType=Get)
await fetchDetails(url, ~version=V2)
}
}
setProfileList(_ => response->getArrayDataFromJson(OMPSwitchUtils.profileItemToObjMapper))
} catch {
| _ => {
setProfileList(_ => [OMPSwitchUtils.ompDefaultValue(profileId, "")])
showToast(~message="Failed to fetch profile list", ~toastType=ToastError)
}
}
}
let validateInput = (profileName: string) => {
let errors = Dict.make()
let regexForProfileName = "^([a-z]|[A-Z]|[0-9]|_|\\s)+$"
let errorMessage = if profileName->isEmptyString {
"Profile name cannot be empty"
} else if profileName->String.length > 64 {
"Profile name cannot exceed 64 characters"
} else if !RegExp.test(RegExp.fromString(regexForProfileName), profileName) {
"Profile name should not contain special characters"
} else {
""
}
if errorMessage->isNonEmptyString {
Dict.set(errors, "profile_name", errorMessage->JSON.Encode.string)
}
errors
}
let profileSwitch = async value => {
try {
setShowSwitchingProfile(_ => true)
let _ = await internalSwitch(~expectedProfileId=Some(value), ~changePath=true)
setShowSwitchingProfile(_ => false)
} catch {
| _ => {
showToast(~message="Failed to switch profile", ~toastType=ToastError)
setShowSwitchingProfile(_ => false)
}
}
}
let handleProfileSwitch = id => {
if !isActive {
profileSwitch(id)->ignore
}
}
let onSubmit = async (newProfileName: string) => {
try {
let body = [("profile_name", newProfileName->JSON.Encode.string)]->getJsonFromArrayOfJson
let accountUrl = getURL(
~entityName=V1(BUSINESS_PROFILE),
~methodType=Post,
~id=Some(profileId),
)
let _ = await updateDetails(accountUrl, body, Post)
let _ = await getProfileList()
showToast(~message="Updated Profile name!", ~toastType=ToastSuccess)
} catch {
| _ => showToast(~message="Failed to update Profile name!", ~toastType=ToastError)
}
}
let leftIconCss = {isActive && !isUnderEdit ? "" : isUnderEdit ? "hidden" : "invisible"}
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
<>
<div
className={`rounded-lg mb-1 ${isUnderEdit
? `hover:bg-transparent`
: `hover:bg-jp-gray-100`}`}>
<InlineEditInput
index
labelText=profileName
customStyle="w-full cursor-pointer !bg-transparent mb-0"
handleEdit=handleIdUnderEdit
isUnderEdit
showEditIcon={isActive &&
userHasAccess(~groupAccess=MerchantDetailsManage) === Access &&
version == V1}
showEditIconOnHover={!isMobileView}
onSubmit
labelTextCustomStyle={` truncate max-w-28 ${isActive ? " text-nd_gray-700" : ""}`}
validateInput
customInputStyle="!py-0 text-nd_gray-600"
customIconComponent={<ToolTip
description={currentId}
customStyle="!whitespace-nowrap"
toolTipFor={<div className="cursor-pointer">
<HelperComponents.CopyTextCustomComp
displayValue=Some("") copyValue=Some(currentId) customIconCss="text-nd_gray-600"
/>
</div>}
toolTipPosition=ToolTip.Right
/>}
customIconStyle={isActive ? "text-nd_gray-600" : ""}
handleClick={_ => handleProfileSwitch(currentId)}
customWidth="min-w-48"
leftIcon={<Icon name="nd-check" className={`${leftIconCss}`} />}
/>
</div>
<LoaderModal
showModal={showSwitchingProfile}
setShowModal={setShowSwitchingProfile}
text="Switching profile..."
/>
</>
}
}
let generateDropdownOptions: (
array<OMPSwitchTypes.ompListTypes>,
~customIconCss: string,
) => array<SelectBox.dropdownOption> = (dropdownList, ~customIconCss) => {
let options: array<SelectBox.dropdownOption> = dropdownList->Array.map((
item
): SelectBox.dropdownOption => {
{
label: item.name,
value: item.id,
icon: Button.CustomRightIcon(
<ToolTip
description={item.id}
customStyle="!whitespace-nowrap"
toolTipFor={<div className="cursor-pointer">
<HelperComponents.CopyTextCustomComp
displayValue=Some("") copyValue=Some({item.id}) customIconCss
/>
</div>}
toolTipPosition=ToolTip.TopRight
/>,
),
}
})
options
}
let generateDropdownOptionsCustomComponent: array<OMPSwitchTypes.ompListTypesCustom> => array<
SelectBox.dropdownOption,
> = dropdownList => {
let options: array<SelectBox.dropdownOption> = dropdownList->Array.map((
item
): SelectBox.dropdownOption => {
let option: SelectBox.dropdownOption = {
label: item.name,
value: item.id,
customComponent: item.customComponent,
icon: Button.CustomRightIcon(
<ToolTip
description={item.id}
customStyle="!whitespace-nowrap"
toolTipFor={<div className="cursor-pointer">
<HelperComponents.CopyTextCustomComp displayValue=Some("") copyValue=Some({item.id}) />
</div>}
toolTipPosition=ToolTip.TopRight
/>,
),
}
option
})
options
}
module EditOrgName = {
@react.component
let make = (~showModal, ~setShowModal, ~orgList, ~orgId, ~getOrgList) => {
open LogicUtils
open APIUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let showToast = ToastState.useShowToast()
let initialValues =
[
("organization_name", OMPSwitchUtils.currentOMPName(orgList, orgId)->JSON.Encode.string),
]->Dict.fromArray
let validateForm = (values: JSON.t) => {
let errors = Dict.make()
let organizationName =
values->getDictFromJsonObject->getString("organization_name", "")->String.trim
let regexForOrganizationName = "^([a-z]|[A-Z]|[0-9]|_|\\s)+$"
let errorMessage = if organizationName->isEmptyString {
"Organization name cannot be empty"
} else if organizationName->String.length > 64 {
"Organization name cannot exceed 64 characters"
} else if !RegExp.test(RegExp.fromString(regexForOrganizationName), organizationName) {
"Organization name should not contain special characters"
} else {
""
}
if errorMessage->isNonEmptyString {
Dict.set(errors, "organization_name", errorMessage->JSON.Encode.string)
}
errors->JSON.Encode.object
}
let orgName = FormRenderer.makeFieldInfo(
~label="Org Name",
~name="organization_name",
~placeholder=`Eg: Hyperswitch`,
~customInput=InputFields.textInput(),
~isRequired=true,
)
let onSubmit = async (values, _) => {
try {
let url = getURL(~entityName=V1(UPDATE_ORGANIZATION), ~methodType=Put, ~id=Some(orgId))
let _ = await updateDetails(url, values, Put)
let _ = await getOrgList()
showToast(~message="Updated organization name!", ~toastType=ToastSuccess)
} catch {
| _ => showToast(~message="Failed to update organization name!", ~toastType=ToastError)
}
setShowModal(_ => false)
Nullable.null
}
<>
<Modal modalHeading="Edit Org name" showModal setShowModal modalClass="w-1/4 m-auto">
<Form initialValues={initialValues->JSON.Encode.object} onSubmit validate={validateForm}>
<div className="flex flex-col gap-12 h-full w-full">
<FormRenderer.DesktopRow>
<FormRenderer.FieldRenderer
fieldWrapperClass="w-full"
field={orgName}
labelClass="!text-black font-medium !-ml-[0.5px]"
/>
</FormRenderer.DesktopRow>
<div className="flex justify-end w-full pr-5 pb-3">
<FormRenderer.SubmitButton
text="Submit changes" buttonSize={Small} loadingText="Processing..."
/>
</div>
</div>
</Form>
</Modal>
</>
}
}
| 5,412 | 9,738 |
hyperswitch-control-center | src/screens/OMPSwitch/OMPSwitchTypes.res | .res | // TODO: remove productType optional
type ompListTypes = {
id: string,
name: string,
productType?: ProductTypes.productTypes,
version?: UserInfoTypes.version,
}
type ompListTypesCustom = {...ompListTypes, customComponent: React.element}
type opmView = {
lable: string,
entity: UserInfoTypes.entity,
}
type ompViews = array<opmView>
type ompList = {
orgList: array<ompListTypes>,
merchantList: array<ompListTypes>,
profileList: array<ompListTypes>,
}
type adminType = [#tenant_admin | #org_admin | #merchant_admin | #non_admin]
type addOrgFormFields = OrgName | MerchantName
| 156 | 9,739 |
hyperswitch-control-center | src/screens/OMPSwitch/OrgSwitch.res | .res | module SwitchOrg = {
@react.component
let make = (~setShowModal) => {
let showToast = ToastState.useShowToast()
let showPopUp = PopUpState.useShowPopUp()
let internalSwitch = OMPSwitchHooks.useInternalSwitch()
let (value, setValue) = React.useState(() => "")
let {globalUIConfig: {sidebarColor: {backgroundColor}}} = React.useContext(
ThemeProvider.themeContext,
)
let input = React.useMemo((): ReactFinalForm.fieldRenderPropsInput => {
{
name: "-",
onBlur: _ => (),
onChange: ev => {
let value = {ev->ReactEvent.Form.target}["value"]
if value->String.includes("<script>") || value->String.includes("</script>") {
showPopUp({
popUpType: (Warning, WithIcon),
heading: `Script Tags are not allowed`,
description: React.string(`Input cannot contain <script>, </script> tags`),
handleConfirm: {text: "OK"},
})
}
let val = value->String.replace("<script>", "")->String.replace("</script>", "")
setValue(_ => val)
},
onFocus: _ => (),
value: JSON.Encode.string(value),
checked: false,
}
}, [value])
let switchOrg = async () => {
try {
setShowModal(_ => true)
let _ = await internalSwitch(~expectedOrgId=Some(value))
setShowModal(_ => false)
} catch {
| _ => {
showToast(~message="Failed to switch the org! Try again.", ~toastType=ToastError)
setShowModal(_ => false)
}
}
}
let handleKeyUp = event => {
if event->ReactEvent.Keyboard.keyCode === 13 {
switchOrg()->ignore
}
}
<TextInput
input
customWidth="w-80"
placeholder="Switch org"
onKeyUp=handleKeyUp
customStyle={`!text-grey-300 !placeholder-grey-200 placeholder: text-sm font-inter-style ${backgroundColor.sidebarSecondary}`}
customDashboardClass="h-11 text-base font-normal shadow-jp-2-xs"
/>
}
}
module NewOrgCreationModal = {
@react.component
let make = (~setShowModal, ~showModal, ~getOrgList) => {
open APIUtils
let getURL = useGetURL()
let mixpanelEvent = MixpanelHook.useSendEvent()
let updateDetails = useUpdateMethod()
let showToast = ToastState.useShowToast()
let createNewOrg = async values => {
try {
let url = getURL(~entityName=V1(USERS), ~userType=#CREATE_ORG, ~methodType=Post)
mixpanelEvent(~eventName="create_new_org", ~metadata=values)
let _ = await updateDetails(url, values, Post)
getOrgList()->ignore
showToast(~toastType=ToastSuccess, ~message="Org Created Successfully!", ~autoClose=true)
} catch {
| _ => showToast(~toastType=ToastError, ~message="Org Creation Failed", ~autoClose=true)
}
setShowModal(_ => false)
Nullable.null
}
let onSubmit = (values, _) => {
createNewOrg(values)
}
let orgName = FormRenderer.makeFieldInfo(
~label="Org Name",
~name="organization_name",
~placeholder="Eg: My New Org",
~customInput=InputFields.textInput(),
~isRequired=true,
)
let merchantName = FormRenderer.makeFieldInfo(
~label="Merchant Name",
~name="merchant_name",
~placeholder="Eg: My New Merchant",
~customInput=InputFields.textInput(),
~isRequired=true,
)
let validateForm = (
~values: JSON.t,
~fieldstoValidate: array<OMPSwitchTypes.addOrgFormFields>,
) => {
open LogicUtils
let errors = Dict.make()
let regexForOrgName = "^([a-z]|[A-Z]|[0-9]|_|\\s)+$"
fieldstoValidate->Array.forEach(field => {
let name = switch field {
| OrgName => "Org"
| MerchantName => "Merchant"
}
let value = switch field {
| OrgName => "organization_name"
| MerchantName => "merchant_name"
}
let fieldValue = values->getDictFromJsonObject->getString(value, "")->String.trim
let errorMsg = if fieldValue->isEmptyString {
`${name} name cannot be empty`
} else if fieldValue->String.length > 64 {
`${name} name too long`
} else if !RegExp.test(RegExp.fromString(regexForOrgName), fieldValue) {
`${name} name should not contain special characters`
} else {
""
}
if errorMsg->isNonEmptyString {
Dict.set(errors, value, errorMsg->JSON.Encode.string)
}
})
errors->JSON.Encode.object
}
let modalBody = {
<div className="p-2 m-2">
<div className="py-5 px-3 flex justify-between align-top ">
<CardUtils.CardHeader
heading="Add a new org" subHeading="" customSubHeadingStyle="w-full !max-w-none pr-10"
/>
<div className="h-fit" onClick={_ => setShowModal(_ => false)}>
<Icon
name="close" className="border-2 p-2 rounded-2xl bg-gray-100 cursor-pointer" size=30
/>
</div>
</div>
<Form
key="new-org-creation"
onSubmit
validate={values => validateForm(~values, ~fieldstoValidate=[OrgName, MerchantName])}>
<div className="flex flex-col gap-12 h-full w-full">
<FormRenderer.DesktopRow>
<div className="flex flex-col gap-5">
<FormRenderer.FieldRenderer
fieldWrapperClass="w-full"
field={orgName}
showErrorOnChange=true
errorClass={ProdVerifyModalUtils.errorClass}
labelClass="!text-black font-medium !-ml-[0.5px]"
/>
<FormRenderer.FieldRenderer
fieldWrapperClass="w-full"
field={merchantName}
showErrorOnChange=true
errorClass={ProdVerifyModalUtils.errorClass}
labelClass="!text-black font-medium !-ml-[0.5px]"
/>
</div>
</FormRenderer.DesktopRow>
<div className="flex justify-end w-full pr-5 pb-3">
<FormRenderer.SubmitButton text="Add Org" buttonSize={Small} />
</div>
</div>
</Form>
</div>
}
<Modal
showModal
closeOnOutsideClick=true
setShowModal
childClass="p-0"
borderBottom=true
modalClass="w-full max-w-xl mx-auto my-auto dark:!bg-jp-gray-lightgray_background">
modalBody
</Modal>
}
}
@react.component
let make = () => {
open APIUtils
open LogicUtils
open OMPSwitchUtils
open OMPSwitchHelper
let getURL = useGetURL()
let fetchDetails = useGetMethod()
let showToast = ToastState.useShowToast()
let internalSwitch = OMPSwitchHooks.useInternalSwitch()
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
let {userInfo: {orgId, roleId}} = React.useContext(UserInfoProvider.defaultContext)
let (orgList, setOrgList) = Recoil.useRecoilState(HyperswitchAtom.orgListAtom)
let {tenantUser} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let (showSwitchingOrg, setShowSwitchingOrg) = React.useState(_ => false)
let (showEditOrgModal, setShowEditOrgModal) = React.useState(_ => false)
let (showAddOrgModal, setShowAddOrgModal) = React.useState(_ => false)
let (arrow, setArrow) = React.useState(_ => false)
let isTenantAdmin = roleId->HyperSwitchUtils.checkIsTenantAdmin
let {globalUIConfig: {sidebarColor: {backgroundColor, secondaryTextColor}}} = React.useContext(
ThemeProvider.themeContext,
)
let getOrgList = async () => {
try {
let url = getURL(~entityName=V1(USERS), ~userType=#LIST_ORG, ~methodType=Get)
let response = await fetchDetails(url)
setOrgList(_ => response->getArrayDataFromJson(orgItemToObjMapper))
} catch {
| _ => {
setOrgList(_ => [ompDefaultValue(orgId, "")])
showToast(~message="Failed to fetch organisation list", ~toastType=ToastError)
}
}
}
React.useEffect(() => {
getOrgList()->ignore
None
}, [])
let orgSwitch = async value => {
try {
setShowSwitchingOrg(_ => true)
let _ = await internalSwitch(~expectedOrgId=Some(value))
setShowSwitchingOrg(_ => false)
} catch {
| _ => {
showToast(~message="Failed to switch organisation", ~toastType=ToastError)
setShowSwitchingOrg(_ => false)
}
}
}
let onEditClick = e => {
setShowEditOrgModal(_ => true)
e->ReactEvent.Mouse.stopPropagation
}
let input: ReactFinalForm.fieldRenderPropsInput = {
name: "name",
onBlur: _ => (),
onChange: ev => {
let value = ev->Identity.formReactEventToString
orgSwitch(value)->ignore
},
onFocus: _ => (),
value: orgId->JSON.Encode.string,
checked: true,
}
let toggleChevronState = () => {
setArrow(prev => !prev)
}
let customHRTagStyle = "border-t border-blue-830"
let customPadding = "py-1 w-full"
let customStyle = `w-56 ${secondaryTextColor} ${backgroundColor.sidebarSecondary} dark:bg-black hover:text-gray-100 !w-full`
let customScrollStyle = `${backgroundColor.sidebarSecondary} max-h-72 overflow-scroll px-1 pt-1`
let dropdownContainerStyle = "min-w-[15rem] rounded"
let showOrgDropdown = !(tenantUser && isTenantAdmin && orgList->Array.length >= 20)
let orgDropdown =
<SelectBox.BaseDropdown
allowMultiSelect=false
buttonText=""
input
deselectDisable=true
customButtonStyle="!rounded-md"
options={orgList->generateDropdownOptions(~customIconCss="text-grey-200")}
marginTop="mt-14"
hideMultiSelectButtons=true
addButton=false
customStyle={`${backgroundColor.sidebarSecondary} hover:!bg-black/10 rounded !w-full`}
customSelectStyle={`${backgroundColor.sidebarSecondary} hover:!bg-black/10 rounded`}
searchable=false
baseComponent={<ListBaseComp
user=#Organization
heading="Org"
subHeading={currentOMPName(orgList, orgId)}
arrow
showEditIcon={userHasAccess(~groupAccess=OrganizationManage) === Access}
onEditClick
isDarkBg=true
/>}
baseComponentCustomStyle={`border-blue-820 rounded ${backgroundColor.sidebarSecondary} rounded text-white`}
bottomComponent={<RenderIf condition={tenantUser && isTenantAdmin}>
<OMPSwitchHelper.AddNewOMPButton
user=#Organization
setShowModal={setShowAddOrgModal}
customPadding
customStyle
customHRTagStyle
/>
</RenderIf>}
optionClass={`${secondaryTextColor} text-fs-14`}
selectClass={`${secondaryTextColor} text-fs-14`}
customDropdownOuterClass="!border-none !w-full"
fullLength=true
toggleChevronState
customScrollStyle
dropdownContainerStyle
shouldDisplaySelectedOnTop=true
/>
let orgBaseComp =
<ListBaseComp
user=#Organization
heading="Org"
subHeading=orgId
arrow
showEditIcon={userHasAccess(~groupAccess=OrganizationManage) === Access}
onEditClick
isDarkBg=true
showDropdownArrow=false
/>
let orgComp = showOrgDropdown ? orgDropdown : orgBaseComp
<div className="w-full py-3.5 px-2 ">
<div className="flex flex-col gap-4">
{orgComp}
<RenderIf condition={!showOrgDropdown}>
<SwitchOrg setShowModal={setShowSwitchingOrg} />
</RenderIf>
</div>
<EditOrgName
showModal={showEditOrgModal} setShowModal={setShowEditOrgModal} orgList orgId getOrgList
/>
<RenderIf condition={showAddOrgModal}>
<NewOrgCreationModal
setShowModal={setShowAddOrgModal} showModal={showAddOrgModal} getOrgList
/>
</RenderIf>
<LoaderModal
showModal={showSwitchingOrg}
setShowModal={setShowSwitchingOrg}
text="Switching organisation..."
/>
</div>
}
| 2,903 | 9,740 |
hyperswitch-control-center | src/screens/OMPSwitch/ProfileSwitch.res | .res | module NewProfileCreationModal = {
@react.component
let make = (~setShowModal, ~showModal, ~getProfileList) => {
open APIUtils
let getURL = useGetURL()
let mixpanelEvent = MixpanelHook.useSendEvent()
let updateDetails = useUpdateMethod()
let showToast = ToastState.useShowToast()
let createNewProfile = async values => {
try {
let url = getURL(~entityName=V1(BUSINESS_PROFILE), ~methodType=Post)
let body = values
mixpanelEvent(~eventName="create_new_profile", ~metadata=values)
let _ = await updateDetails(url, body, Post)
getProfileList()->ignore
showToast(
~toastType=ToastSuccess,
~message="Profile Created Successfully!",
~autoClose=true,
)
} catch {
| _ => showToast(~toastType=ToastError, ~message="Profile Creation Failed", ~autoClose=true)
}
setShowModal(_ => false)
Nullable.null
}
let onSubmit = (values, _) => {
open LogicUtils
let dict = values->getDictFromJsonObject
let trimmedData = dict->getString("profile_name", "")->String.trim
Dict.set(dict, "profile_name", trimmedData->JSON.Encode.string)
createNewProfile(dict->JSON.Encode.object)
}
let profileName = FormRenderer.makeFieldInfo(
~label="Profile Name",
~name="profile_name",
~customInput=(~input, ~placeholder as _) =>
InputFields.textInput()(
~input={
...input,
onChange: event =>
ReactEvent.Form.target(event)["value"]
->String.trimStart
->Identity.stringToFormReactEvent
->input.onChange,
},
~placeholder="Eg: My New Profile",
),
~isRequired=true,
)
let validateForm = (values: JSON.t) => {
open LogicUtils
let errors = Dict.make()
let profileName = values->getDictFromJsonObject->getString("profile_name", "")->String.trim
let regexForProfileName = "^([a-z]|[A-Z]|[0-9]|_|\\s)+$"
let errorMessage = if profileName->isEmptyString {
"Profile name cannot be empty"
} else if profileName->String.length > 64 {
"Profile name cannot exceed 64 characters"
} else if !RegExp.test(RegExp.fromString(regexForProfileName), profileName) {
"Profile name should not contain special characters"
} else {
""
}
if errorMessage->isNonEmptyString {
Dict.set(errors, "profile_name", errorMessage->JSON.Encode.string)
}
errors->JSON.Encode.object
}
let modalBody =
<div className="">
<div className="pt-3 m-3 flex justify-between">
<CardUtils.CardHeader
heading="Add a new profile"
subHeading=""
customSubHeadingStyle="w-full !max-w-none pr-10"
/>
<div className="h-fit" onClick={_ => setShowModal(_ => false)}>
<Icon name="modal-close-icon" className="cursor-pointer" size=30 />
</div>
</div>
<hr />
<Form key="new-profile-creation" onSubmit validate={validateForm}>
<div className="flex flex-col h-full w-full">
<div className="py-10">
<FormRenderer.DesktopRow>
<FormRenderer.FieldRenderer
fieldWrapperClass="w-full"
field={profileName}
errorClass={ProdVerifyModalUtils.errorClass}
labelClass="!text-black font-medium !-ml-[0.5px]"
/>
</FormRenderer.DesktopRow>
</div>
<hr className="mt-4" />
<div className="flex justify-end w-full p-3">
<FormRenderer.SubmitButton text="Add Profile" buttonSize=Small />
</div>
</div>
</Form>
</div>
<Modal
showModal
closeOnOutsideClick=true
setShowModal
childClass="p-0"
borderBottom=true
modalClass="w-full max-w-xl mx-auto my-auto dark:!bg-jp-gray-lightgray_background">
{modalBody}
</Modal>
}
}
@react.component
let make = () => {
open APIUtils
open LogicUtils
open OMPSwitchUtils
open OMPSwitchHelper
let getURL = useGetURL()
let fetchDetails = useGetMethod()
let showToast = ToastState.useShowToast()
let internalSwitch = OMPSwitchHooks.useInternalSwitch()
let (showModal, setShowModal) = React.useState(_ => false)
let {userInfo: {profileId, version}} = React.useContext(UserInfoProvider.defaultContext)
let (profileList, setProfileList) = Recoil.useRecoilState(HyperswitchAtom.profileListAtom)
let (showSwitchingProfile, setShowSwitchingProfile) = React.useState(_ => false)
let (arrow, setArrow) = React.useState(_ => false)
let businessProfiles = Recoil.useRecoilValueFromAtom(HyperswitchAtom.businessProfilesAtom)
let isMobileView = MatchMedia.useMobileChecker()
let widthClass = isMobileView ? "w-full" : "md:w-[14rem] md:max-w-[20rem]"
let roundedClass = isMobileView ? "rounded-none" : "rounded-md"
let getProfileList = async () => {
try {
let response = switch version {
| V1 => {
let url = getURL(~entityName=V1(USERS), ~userType=#LIST_PROFILE, ~methodType=Get)
await fetchDetails(url)
}
| V2 => {
let url = getURL(~entityName=V2(USERS), ~userType=#LIST_PROFILE, ~methodType=Get)
await fetchDetails(url, ~version=V2)
}
}
setProfileList(_ => response->getArrayDataFromJson(profileItemToObjMapper))
} catch {
| _ => {
setProfileList(_ => [ompDefaultValue(profileId, "")])
showToast(~message="Failed to fetch profile list", ~toastType=ToastError)
}
}
}
let customStyle = "text-primary bg-white dark:bg-black hover:bg-jp-gray-100 text-nowrap w-full"
let addItemBtnStyle = "w-full"
let customScrollStyle = "max-h-72 overflow-scroll px-1 pt-1"
let dropdownContainerStyle = `${roundedClass} border border-1 ${widthClass}`
let profileSwitch = async value => {
try {
setShowSwitchingProfile(_ => true)
let _ = await internalSwitch(~expectedProfileId=Some(value))
setShowSwitchingProfile(_ => false)
} catch {
| _ => {
showToast(~message="Failed to switch profile", ~toastType=ToastError)
setShowSwitchingProfile(_ => false)
}
}
}
let input: ReactFinalForm.fieldRenderPropsInput = {
name: "name",
onBlur: _ => (),
onChange: ev => {
let value = ev->Identity.formReactEventToString
profileSwitch(value)->ignore
},
onFocus: _ => (),
value: profileId->JSON.Encode.string,
checked: true,
}
// TODO : remove businessProfiles as dependancy in remove-business-profile-add-as-a-section pr
React.useEffect(() => {
getProfileList()->ignore
None
}, [businessProfiles])
let toggleChevronState = () => {
setArrow(prev => !prev)
}
let updatedProfileList: array<
OMPSwitchTypes.ompListTypesCustom,
> = profileList->Array.mapWithIndex((item, i) => {
let customComponent =
<ProfileDropdownItem key={Int.toString(i)} profileName=item.name index=i currentId=item.id />
let listItem: OMPSwitchTypes.ompListTypesCustom = {
id: item.id,
name: item.name,
customComponent,
}
listItem
})
let bottomComponent = switch version {
| V1 => <AddNewOMPButton user=#Profile setShowModal customStyle addItemBtnStyle />
| V2 => React.null
}
<>
<SelectBox.BaseDropdown
allowMultiSelect=false
buttonText=""
input
deselectDisable=true
customButtonStyle="!rounded-md"
options={updatedProfileList->generateDropdownOptionsCustomComponent}
marginTop="mt-10"
hideMultiSelectButtons=true
addButton=false
searchable=true
customStyle="w-fit "
baseComponent={<ListBaseComp
user={#Profile} heading="Profile" subHeading={currentOMPName(profileList, profileId)} arrow
/>}
bottomComponent
customDropdownOuterClass="!border-none "
fullLength=true
toggleChevronState
customScrollStyle
dropdownContainerStyle
shouldDisplaySelectedOnTop=true
placeholderCss="text-fs-13"
/>
<RenderIf condition={showModal}>
<NewProfileCreationModal setShowModal showModal getProfileList />
</RenderIf>
<LoaderModal
showModal={showSwitchingProfile}
setShowModal={setShowSwitchingProfile}
text="Switching profile..."
/>
</>
}
| 2,043 | 9,741 |
hyperswitch-control-center | src/screens/Analytics/AnalyticsTypes.res | .res | type infoMetrics =
| Latency
| ApiName
| Status_code
let getStringFromVarient = value =>
switch value {
| Latency => "latency"
| ApiName => "api_name"
| Status_code => "status_code"
}
type weeklyStateCol = {
refKey: string,
newKey: string,
}
type chartItemType = {
key: string,
title: string,
tooltipText: string,
value: string,
delta: float,
data: array<(float, float)>,
statType: string,
lineColor: option<string>,
graphBgColor: string,
isIncreasing: bool,
statsPercentage: string,
arrowIcon: React.element,
}
type connectorTileType = {
name: string,
logo: string,
}
type chartOption = {
name: string,
key: string,
type_: LineChartUtils.dropDownMetricType,
avg: float,
}
type analyticsType = PAYMENT | REFUND | AUTHENTICATION | UNKNOWN
let getAnalyticsType = moduleName => {
switch moduleName {
| "Payments" => PAYMENT
| "Refunds" => REFUND
| _ => UNKNOWN
}
}
let getModuleName = analyticsType => {
switch analyticsType {
| PAYMENT => "Payments"
| REFUND => "Refunds"
| AUTHENTICATION => "Authentication"
| UNKNOWN => ""
}
}
type refundColType =
| SuccessRate
| Count
| SuccessCount
| ProcessedAmount
| Connector
| RefundMethod
| Currency
| Status
| NoCol
let defaultRefundColumns = [Connector, RefundMethod, Currency, Status]
let allRefundColumns = [SuccessRate, Count, SuccessCount]
type refundTableType = {
refund_success_rate: float,
refund_count: float,
refund_success_count: float,
refund_processed_amount: float,
connector: string,
refund_method: string,
currency: string,
refund_status: string,
}
type refundsSingleState = {
refund_success_rate: float,
refund_count: int,
refund_success_count: int,
refund_processed_amount: float,
}
type refundsSingleStateSeries = {
refund_success_rate: float,
refund_count: int,
refund_success_count: int,
time_series: string,
refund_processed_amount: float,
}
type disputeColType =
| Connector
| DisputeStage
| TotalAmountDisputed
| TotalDisputeLostAmount
| NoCol
let defaultDisputeColumns = [Connector, DisputeStage]
let allDisputeColumns = [TotalAmountDisputed, TotalDisputeLostAmount]
type disputeTableType = {
connector: string,
dispute_stage: string,
total_amount_disputed: float,
total_dispute_lost_amount: float,
}
type disputeSingleStateType = {
total_amount_disputed: float,
total_dispute_lost_amount: float,
}
type disputeSingleSeriesState = {
total_amount_disputed: float,
total_dispute_lost_amount: float,
time_series: string,
}
type paymentColType =
| SuccessRate
| Count
| SuccessCount
| ProcessedAmount
| AvgTicketSize
| Connector
| PaymentErrorMessage
| PaymentMethod
| PaymentMethodType
| Currency
| AuthType
| ClientSource
| ClientVersion
| Status
| WeeklySuccessRate
| NoCol
let defaultPaymentColumns = [
Connector,
PaymentMethod,
PaymentMethodType,
Currency,
AuthType,
Status,
ClientSource,
ClientVersion,
]
let allPaymentColumns = [SuccessRate, WeeklySuccessRate, Count, SuccessCount, PaymentErrorMessage]
type commonMetrics = {
payment_success_rate: float,
payment_count: int,
payment_success_count: int,
retries_count: int,
retries_amount_processe: float,
connector_success_rate: float,
payment_processed_amount: float,
payment_avg_ticket_size: float,
}
type paymentsSingleState = {
...commonMetrics,
currency: string,
}
type paymentsSingleStateSeries = {
...commonMetrics,
time_series: string,
}
type error_message_type = {
reason: string,
count: int,
percentage: float,
}
type paymentTableType = {
payment_success_rate: float,
payment_count: float,
payment_success_count: float,
payment_processed_amount: float,
payment_error_message: array<error_message_type>,
avg_ticket_size: float,
connector: string,
payment_method: string,
payment_method_type: string,
currency: string,
authentication_type: string,
client_source: string,
client_version: string,
refund_status: string,
weekly_payment_success_rate: string,
}
type nestedEntityType = {
default?: DynamicChart.entity,
userPieChart?: DynamicChart.entity,
userBarChart?: DynamicChart.entity,
userFunnelChart?: DynamicChart.entity,
}
type authenticationSingleStat = {
authentication_count: int,
authentication_success_count: int,
authentication_attempt_count: int,
challenge_flow_count: int,
challenge_attempt_count: int,
challenge_success_count: int,
frictionless_flow_count: int,
frictionless_success_count: int,
}
type authenticationSingleStatSeries = {
authentication_count: int,
authentication_success_count: int,
authentication_attempt_count: int,
challenge_flow_count: int,
challenge_attempt_count: int,
challenge_success_count: int,
frictionless_flow_count: int,
frictionless_success_count: int,
time_series: string,
}
| 1,225 | 9,742 |
hyperswitch-control-center | src/screens/Analytics/AnalyticsNew.res | .res | module MetricsState = {
@react.component
let make = (
~singleStatEntity,
~filterKeys,
~startTimeFilterKey,
~endTimeFilterKey,
~moduleName,
~heading,
~formaPayload: option<DynamicSingleStat.singleStatBodyEntity => string>=?,
) => {
<div>
<h2 className="font-bold text-xl text-black text-opacity-80"> {heading->React.string} </h2>
<DynamicSingleStat
entity=singleStatEntity
startTimeFilterKey
endTimeFilterKey
filterKeys
moduleName
showPercentage=false
statSentiment={singleStatEntity.statSentiment->Option.getOr(Dict.make())}
?formaPayload
/>
</div>
}
}
module TableWrapper = {
open LogicUtils
@react.component
let make = (
~dateKeys,
~filterKeys,
~activeTab,
~defaultSort,
~getTable: JSON.t => array<'t>,
~colMapper: 'colType => string,
~tableEntity: EntityType.entityType<'colType, 't>,
~deltaMetrics: array<string>,
~deltaArray: array<string>,
~tableUpdatedHeading as _,
~tableGlobalFilter: option<(array<Nullable.t<'t>>, JSON.t) => array<Nullable.t<'t>>>,
~moduleName,
~weeklyTableMetricsCols,
~distributionArray=None,
~formatData=None,
) => {
let {globalUIConfig: {font: {textColor}, border: {borderColor}}} = React.useContext(
ThemeProvider.themeContext,
)
let customFilter = Recoil.useRecoilValueFromAtom(AnalyticsAtoms.customFilterAtom)
let {filterValueJson} = React.useContext(FilterContext.filterContext)
let filterValueDict = filterValueJson
let fetchDetails = APIUtils.useUpdateMethod()
let (showTable, setShowTable) = React.useState(_ => false)
let {getHeading, allColumns, defaultColumns} = tableEntity
let activeTabStr = activeTab->Option.getOr([])->Array.joinWith("-")
let (startTimeFilterKey, endTimeFilterKey) = dateKeys
let (tableDataLoading, setTableDataLoading) = React.useState(_ => true)
let (tableData, setTableData) = React.useState(_ => []->Array.map(Nullable.make))
let getTopLevelFilter = React.useMemo(() => {
filterValueDict
->Dict.toArray
->Belt.Array.keepMap(item => {
let (key, value) = item
let keyArr = key->String.split(".")
let prefix = keyArr->Array.get(0)->Option.getOr("")
if prefix === moduleName && prefix->LogicUtils.isNonEmptyString {
None
} else {
Some((prefix, value))
}
})
->Dict.fromArray
}, [filterValueDict])
let allColumns = allColumns->Option.getOr([])
let allFilterKeys = Array.concat([startTimeFilterKey, endTimeFilterKey], filterKeys)
let topFiltersToSearchParam = React.useMemo(() => {
let filterSearchParam =
getTopLevelFilter
->Dict.toArray
->Belt.Array.keepMap(entry => {
let (key, value) = entry
if allFilterKeys->Array.includes(key) {
switch value->JSON.Classify.classify {
| String(str) => `${key}=${str}`->Some
| Number(num) => `${key}=${num->String.make}`->Some
| Array(arr) => `${key}=[${arr->String.make}]`->Some
| _ => None
}
} else {
None
}
})
->Array.joinWith("&")
filterSearchParam
}, [getTopLevelFilter])
let filterValueFromUrl = React.useMemo(() => {
getTopLevelFilter
->Dict.toArray
->Belt.Array.keepMap(entries => {
let (key, value) = entries
filterKeys->Array.includes(key) ? Some((key, value)) : None
})
->Dict.fromArray
->JSON.Encode.object
->Some
}, [topFiltersToSearchParam])
let startTimeFromUrl = React.useMemo(() => {
getTopLevelFilter->getString(startTimeFilterKey, "")
}, [topFiltersToSearchParam])
let endTimeFromUrl = React.useMemo(() => {
getTopLevelFilter->getString(endTimeFilterKey, "")
}, [topFiltersToSearchParam])
let parseData = json => {
let data = json->getDictFromJsonObject
let value = data->getJsonObjectFromDict("queryData")->getArrayFromJson([])
value
}
let generateIDFromKeys = (keys, dict) => {
keys
->Option.getOr([])
->Array.map(key => {
dict->Dict.get(key)
})
->Array.joinWithUnsafe("")
}
open AnalyticsTypes
let getUpdatedData = (data, weeklyData, cols) => {
let dataArr = data->parseData
let weeklyArr = weeklyData->parseData
dataArr
->Array.map(item => {
let dataDict = item->getDictFromJsonObject
let dataKey = activeTab->generateIDFromKeys(dataDict)
weeklyArr->Array.forEach(newItem => {
let weekklyDataDict = newItem->getDictFromJsonObject
let weekklyDataKey = activeTab->generateIDFromKeys(weekklyDataDict)
if dataKey === weekklyDataKey {
cols->Array.forEach(
obj => {
switch weekklyDataDict->Dict.get(obj.refKey) {
| Some(val) => dataDict->Dict.set(obj.newKey, val)
| _ => ()
}
},
)
}
})
dataDict->JSON.Encode.object
})
->JSON.Encode.array
->getTable
->Array.map(Nullable.make)
}
open Promise
let getWeeklyData = (data, cols) => {
let weeklyDateRange = HSwitchRemoteFilter.getDateFilteredObject()
let weeklyTableReqBody = AnalyticsUtils.generateTablePayload(
~startTimeFromUrl=weeklyDateRange.start_time,
~endTimeFromUrl=weeklyDateRange.end_time,
~filterValueFromUrl,
~currenltySelectedTab=activeTab,
~deltaMetrics,
~isIndustry=false,
~distributionArray=None,
~deltaPrefixArr=deltaArray,
~tableMetrics=[],
~mode=None,
~customFilter,
~moduleName,
~showDeltaMetrics=true,
(),
)
fetchDetails(tableEntity.uri, weeklyTableReqBody, Post)
->thenResolve(json => {
setTableData(_ => getUpdatedData(data, json, cols))
setTableDataLoading(_ => false)
setShowTable(_ => true)
})
->catch(_ => {
setTableDataLoading(_ => false)
resolve()
})
->ignore
}
let updateTableData = json => {
switch weeklyTableMetricsCols {
| Some(cols) => getWeeklyData(json, cols)->ignore
| None => {
let data = json->getDictFromJsonObject
let value = data->getJsonObjectFromDict("queryData")->getTable->Array.map(Nullable.make)
setTableData(_ => value)
setTableDataLoading(_ => false)
setShowTable(_ => true)
}
}
}
React.useEffect(() => {
setShowTable(_ => false)
if (
startTimeFromUrl->LogicUtils.isNonEmptyString && endTimeFromUrl->LogicUtils.isNonEmptyString
) {
let tableReqBody = HSAnalyticsUtils.generateTablePayload(
~startTimeFromUrl,
~endTimeFromUrl,
~filterValueFromUrl,
~currenltySelectedTab=activeTab,
~deltaMetrics,
~isIndustry=false,
~distributionArray,
~deltaPrefixArr=deltaArray,
~tableMetrics=[],
~mode=None,
~customFilter,
~moduleName,
~showDeltaMetrics=true,
(),
)
fetchDetails(tableEntity.uri, tableReqBody, Post)
->thenResolve(json => json->updateTableData)
->catch(_ => {
setTableDataLoading(_ => false)
resolve()
})
->ignore
}
None
}, (topFiltersToSearchParam, activeTabStr, customFilter))
let newDefaultCols = React.useMemo(() => {
activeTab
->Option.getOr([])
->Belt.Array.keepMap(item => {
defaultColumns
->Belt.Array.keepMap(
columnItem => {
let val = columnItem->getHeading
val.key === item ? Some(columnItem) : None
},
)
->Array.get(0)
})
->Array.concat(allColumns)
}, [activeTabStr])
let newAllCols = React.useMemo(() => {
defaultColumns
->Belt.Array.keepMap(item => {
let val = item->getHeading
activeTab->Option.getOr([])->Array.includes(val.key) ? Some(item) : None
})
->Array.concat(allColumns)
}, [activeTabStr])
let transactionTableDefaultCols = React.useMemo(() => {
Recoil.atom(`${moduleName}DefaultCols${activeTabStr}`, newDefaultCols)
}, (newDefaultCols, `${moduleName}DefaultCols${activeTabStr}`))
let modifyData = data => {
switch formatData {
| Some(fun) => data->fun
| None => data
}
}
showTable
? <>
<div className="h-full -mx-4 overflow-scroll">
<Form>
<Analytics.BaseTableComponent
filters=(startTimeFromUrl, endTimeFromUrl)
tableData={tableData->modifyData}
tableDataLoading
transactionTableDefaultCols
defaultSort
newDefaultCols
newAllCols
tableEntity
colMapper
tableGlobalFilter
activeTab={activeTab->Option.getOr([])}
/>
</Form>
</div>
<RenderIf condition={tableData->Array.length > 0}>
<div
className={`flex items-start ${borderColor.primaryNormal} text-sm rounded-md gap-2 px-4 py-3`}>
<Icon name="info-vacent" className={`${textColor.primaryNormal} mt-1`} size=18 />
{"'NA' denotes those incomplete or failed payments with no assigned values for the corresponding parameters due to reasons like customer drop-offs, technical failures, etc."->React.string}
</div>
</RenderIf>
</>
: <Loader />
}
}
module TabDetails = {
@react.component
let make = (
~chartEntity: DynamicChart.entity,
~activeTab,
~defaultSort: string,
~getTable: JSON.t => array<'t>,
~colMapper: 'colType => string,
~distributionArray,
~tableEntity: option<EntityType.entityType<'colType, 't>>,
~deltaMetrics: array<string>,
~deltaArray: array<string>,
~tableUpdatedHeading: option<
(~item: option<'t>, ~dateObj: option<AnalyticsUtils.prevDates>, 'colType) => Table.header,
>,
~tableGlobalFilter: option<(array<Nullable.t<'t>>, JSON.t) => array<Nullable.t<'t>>>,
~moduleName,
~updateUrl: Dict.t<string> => unit,
~weeklyTableMetricsCols,
~formatData=None,
) => {
let wrapperClass = "bg-white border rounded-lg p-8 mt-3 mb-7"
let tabTitleMapper = Dict.make()
let tab =
<div className=wrapperClass>
<DynamicChart
entity=chartEntity
selectedTab=activeTab
chartId=moduleName
updateUrl
enableBottomChart=false
tabTitleMapper
showTableLegend=false
showMarkers=true
legendType=HighchartTimeSeriesChart.Points
comparitionWidget=true
/>
{switch tableEntity {
| Some(tableEntity) =>
<TableWrapper
dateKeys=chartEntity.dateFilterKeys
filterKeys=chartEntity.allFilterDimension
activeTab
getTable
colMapper
defaultSort
tableEntity
deltaMetrics
deltaArray
tableUpdatedHeading
tableGlobalFilter
moduleName
weeklyTableMetricsCols
distributionArray
formatData
/>
| None => React.null
}}
</div>
{tab}
}
}
module OverallSummary = {
open LogicUtils
@react.component
let make = (
~filteredTabVales,
~moduleName,
~filteredTabKeys,
~chartEntity: DynamicChart.entity,
~defaultSort,
~getTable,
~colMapper,
~distributionArray=None,
~tableEntity,
~deltaMetrics: array<string>,
~deltaArray: array<string>,
~tableUpdatedHeading: option<
(~item: option<'t>, ~dateObj: option<AnalyticsUtils.prevDates>, 'colType) => Table.header,
>=?,
~tableGlobalFilter: option<(array<Nullable.t<'t>>, JSON.t) => array<Nullable.t<'t>>>=?,
~weeklyTableMetricsCols=?,
~formatData=None,
~startTimeFilterKey,
~endTimeFilterKey,
~heading,
) => {
let {filterValue, filterValueJson, updateExistingKeys} = React.useContext(
FilterContext.filterContext,
)
let initTab = switch filteredTabKeys->Array.get(0) {
| Some(val) => [val]
| None => filteredTabKeys
}
let (activeTav, setActiveTab) = React.useState(_ =>
filterValueJson->getStrArrayFromDict(`${moduleName}.tabName`, initTab)
)
let setInitialFilters = HSwitchRemoteFilter.useSetInitialFilters(
~updateExistingKeys,
~startTimeFilterKey,
~endTimeFilterKey,
~origin="analytics",
(),
)
React.useEffect(() => {
setInitialFilters()
None
}, [])
let activeTab = React.useMemo(() => {
Some(
filterValueJson
->getStrArrayFromDict(`${moduleName}.tabName`, activeTav)
->Array.filter(item => item->LogicUtils.isNonEmptyString),
)
}, [filterValueJson])
let setActiveTab = React.useMemo(() => {
(str: string) => {
setActiveTab(_ => str->String.split(","))
}
}, [setActiveTab])
let updateUrlWithPrefix = React.useMemo(() => {
(chartType: string) => {
(dict: Dict.t<string>) => {
let prev = filterValue
let prevDictArr =
prev
->Dict.toArray
->Belt.Array.keepMap(item => {
let (key, _) = item
switch dict->Dict.get(key) {
| Some(_) => None
| None => Some(item)
}
})
let currentDict =
dict
->Dict.toArray
->Belt.Array.keepMap(item => {
let (key, value) = item
if value->LogicUtils.isNonEmptyString {
Some((`${moduleName}${chartType}.${key}`, value))
} else {
None
}
})
updateExistingKeys(Array.concat(prevDictArr, currentDict)->Dict.fromArray)
}
}
}, [updateExistingKeys])
<div>
<h2 className="font-bold text-xl text-black text-opacity-80"> {heading->React.string} </h2>
<DynamicTabs
tabs=filteredTabVales
maxSelection=3
tabId=moduleName
setActiveTab
updateUrlDict={dict => {
let updateUrlWithPrefix = updateUrlWithPrefix("")
updateUrlWithPrefix(dict)
}}
tabContainerClass="analyticsTabs"
initalTab=?activeTab
/>
<TabDetails
chartEntity
activeTab
defaultSort
distributionArray
getTable
colMapper
tableEntity
deltaMetrics
deltaArray
tableUpdatedHeading
tableGlobalFilter
moduleName
updateUrl={dict => {
let updateUrlWithPrefix = updateUrlWithPrefix("")
updateUrlWithPrefix(dict)
}}
weeklyTableMetricsCols
formatData
/>
</div>
}
}
| 3,603 | 9,743 |
hyperswitch-control-center | src/screens/Analytics/ErrorReasons.res | .res | type errorObject = {
error_reason: string,
count: int,
percentage: float,
}
type cols =
| ErrorReason
| Count
| Percentage
let visibleColumns = [ErrorReason, Count, Percentage]
let colMapper = (col: cols) => {
switch col {
| ErrorReason => "error_reason"
| Count => "count"
| Percentage => "percentage"
}
}
let tableItemToObjMapper: 'a => errorObject = dict => {
open LogicUtils
{
error_reason: dict->getString(ErrorReason->colMapper, "NA"),
count: dict->getInt(Count->colMapper, 0),
percentage: dict->getFloat(Percentage->colMapper, 0.0),
}
}
let getObjects: JSON.t => array<errorObject> = json => {
open LogicUtils
json
->LogicUtils.getArrayFromJson([])
->Array.map(item => {
tableItemToObjMapper(item->getDictFromJsonObject)
})
}
let getHeading = colType => {
let key = colType->colMapper
switch colType {
| ErrorReason => Table.makeHeaderInfo(~key, ~title="Error Reason", ~dataType=TextType)
| Count => Table.makeHeaderInfo(~key, ~title="Count", ~dataType=TextType)
| Percentage => Table.makeHeaderInfo(~key, ~title="Percentage", ~dataType=TextType)
}
}
let getCell = (errorObj, colType): Table.cell => {
switch colType {
| ErrorReason => Text(errorObj.error_reason)
| Count => Text(errorObj.count->Int.toString)
| Percentage => Text(errorObj.percentage->Float.toString)
}
}
let tableEntity = EntityType.makeEntity(
~uri=``,
~getObjects,
~dataKey="queryData",
~defaultColumns=visibleColumns,
~requiredSearchFieldsList=[],
~allColumns=visibleColumns,
~getCell,
~getHeading,
)
@react.component
let make = (~errors: array<AnalyticsTypes.error_message_type>) => {
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let (showModal, setShowModal) = React.useState(_ => false)
let (offset, setOffset) = React.useState(_ => 0)
let defaultSort: Table.sortedObject = {
key: "",
order: Table.INC,
}
let getCellText = {
let errorStr = switch errors->Array.get(0) {
| Some(val) => val.reason->String.slice(~start=0, ~end=15)
| _ => "Error Reasons"
}
`${errorStr}...`
}
let tableData = if errors->Array.length > 0 {
errors->Array.map(item => {
{
error_reason: item.reason,
percentage: item.percentage,
count: item.count,
}->Nullable.make
})
} else {
[]
}
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"
<>
{if errors->Array.length > 0 {
<div
className={`underline underline-offset-4 font-medium cursor-pointer ${textColor.primaryNormal}`}
onClick={_ => setShowModal(_ => !showModal)}>
{getCellText->React.string}
</div>
} else {
{"NA"->React.string}
}}
<Modal
closeOnOutsideClick=true
modalHeading="Top 5 Error Reasons"
showModal
setShowModal
modalClass="w-full max-w-xl mx-auto md:mt-44 ">
<LoadedTable
visibleColumns
title="Analytics Error Reasons"
hideTitle=true
actualData={tableData}
entity=tableEntity
resultsPerPage=10
totalResults={tableData->Array.length}
offset
setOffset
defaultSort
currrentFetchCount={tableData->Array.length}
tableLocalFilter=false
tableheadingClass=tableBorderClass
tableBorderClass
ignoreHeaderBg=true
tableDataBorderClass=tableBorderClass
isAnalyticsModule=true
/>
</Modal>
</>
}
| 944 | 9,744 |
hyperswitch-control-center | src/screens/Analytics/Analytics.res | .res | @get external keyCode: 'a => int = "keyCode"
open LogicUtils
module BaseTableComponent = {
@react.component
let make = (
~filters as _,
~tableData,
~defaultSort: string,
~tableDataLoading: bool,
~transactionTableDefaultCols,
~newDefaultCols: array<'colType>,
~newAllCols: array<'colType>,
~colMapper as _,
~tableEntity: EntityType.entityType<'colType, 't>,
~tableGlobalFilter as _,
~activeTab as _,
) => {
open DynamicTableUtils
let (offset, setOffset) = React.useState(_ => 0)
let (_, setCounter) = React.useState(_ => 1)
let refetch = React.useCallback(_ => {
setCounter(p => p + 1)
}, [setCounter])
let visibleColumns = Recoil.useRecoilValueFromAtom(transactionTableDefaultCols)
let defaultSort: Table.sortedObject = {
key: defaultSort,
order: Table.INC,
}
let modifiedTableEntity = React.useMemo(() => {
{
...tableEntity,
defaultColumns: newDefaultCols,
allColumns: Some(newAllCols),
}
}, (tableEntity, newDefaultCols, newAllCols))
let tableBorderClass = "border-collapse border border-jp-gray-940 border-solid border-2 rounded-md border-opacity-30 dark:border-jp-gray-dark_table_border_color dark:border-opacity-30 mt-7"
<div className="flex flex-1 flex-col m-5">
<RefetchContextProvider value=refetch>
{if tableDataLoading {
<DynamicTableUtils.TableDataLoadingIndicator showWithData={true} />
} else {
<div className="relative">
<div
className="absolute font-bold text-xl bg-white w-full text-black text-opacity-75 dark:bg-jp-gray-950 dark:text-white dark:text-opacity-75">
{React.string("Payments Summary")}
</div>
<LoadedTable
visibleColumns
title="Summary Table"
hideTitle=true
actualData={tableData}
entity=modifiedTableEntity
resultsPerPage=10
totalResults={tableData->Array.length}
offset
setOffset
defaultSort
currrentFetchCount={tableData->Array.length}
tableLocalFilter=false
tableheadingClass=tableBorderClass
tableBorderClass
tableDataBorderClass=tableBorderClass
isAnalyticsModule=true
/>
</div>
}}
</RefetchContextProvider>
</div>
}
}
module TableWrapper = {
@react.component
let make = (
~dateKeys,
~filterKeys,
~activeTab,
~defaultSort,
~getTable: JSON.t => array<'t>,
~colMapper: 'colType => string,
~tableEntity: EntityType.entityType<'colType, 't>,
~deltaMetrics: array<string>,
~deltaArray: array<string>,
~tableUpdatedHeading as _,
~tableGlobalFilter: option<(array<Nullable.t<'t>>, JSON.t) => array<Nullable.t<'t>>>,
~moduleName,
~weeklyTableMetricsCols,
~distributionArray=None,
~formatData=None,
) => {
let {globalUIConfig: {font: {textColor}, border: {borderColor}}} = React.useContext(
ThemeProvider.themeContext,
)
let customFilter = Recoil.useRecoilValueFromAtom(AnalyticsAtoms.customFilterAtom)
let {filterValueJson} = React.useContext(FilterContext.filterContext)
let filterValueDict = filterValueJson
let fetchDetails = APIUtils.useUpdateMethod()
let (showTable, setShowTable) = React.useState(_ => false)
let {getHeading, allColumns, defaultColumns} = tableEntity
let activeTabStr = activeTab->Option.getOr([])->Array.joinWith("-")
let (startTimeFilterKey, endTimeFilterKey) = dateKeys
let (tableDataLoading, setTableDataLoading) = React.useState(_ => true)
let (tableData, setTableData) = React.useState(_ => []->Array.map(Nullable.make))
let getTopLevelFilter = React.useMemo(() => {
filterValueDict
->Dict.toArray
->Belt.Array.keepMap(item => {
let (key, value) = item
let keyArr = key->String.split(".")
let prefix = keyArr->Array.get(0)->Option.getOr("")
if prefix === moduleName && prefix->LogicUtils.isNonEmptyString {
None
} else {
Some((prefix, value))
}
})
->Dict.fromArray
}, [filterValueDict])
let allColumns = allColumns->Option.getOr([])
let allFilterKeys = Array.concat([startTimeFilterKey, endTimeFilterKey], filterKeys)
let topFiltersToSearchParam = React.useMemo(() => {
let filterSearchParam =
getTopLevelFilter
->Dict.toArray
->Belt.Array.keepMap(entry => {
let (key, value) = entry
if allFilterKeys->Array.includes(key) {
switch value->JSON.Classify.classify {
| String(str) => `${key}=${str}`->Some
| Number(num) => `${key}=${num->String.make}`->Some
| Array(arr) => `${key}=[${arr->String.make}]`->Some
| _ => None
}
} else {
None
}
})
->Array.joinWith("&")
filterSearchParam
}, [getTopLevelFilter])
let filterValueFromUrl = React.useMemo(() => {
getTopLevelFilter
->Dict.toArray
->Belt.Array.keepMap(entries => {
let (key, value) = entries
filterKeys->Array.includes(key) ? Some((key, value)) : None
})
->Dict.fromArray
->JSON.Encode.object
->Some
}, [topFiltersToSearchParam])
let startTimeFromUrl = React.useMemo(() => {
getTopLevelFilter->getString(startTimeFilterKey, "")
}, [topFiltersToSearchParam])
let endTimeFromUrl = React.useMemo(() => {
getTopLevelFilter->getString(endTimeFilterKey, "")
}, [topFiltersToSearchParam])
let parseData = json => {
let data = json->getDictFromJsonObject
let value = data->getJsonObjectFromDict("queryData")->getArrayFromJson([])
value
}
let generateIDFromKeys = (keys, dict) => {
keys
->Option.getOr([])
->Array.map(key => {
dict->Dict.get(key)
})
->Array.joinWithUnsafe("")
}
open AnalyticsTypes
let getUpdatedData = (data, weeklyData, cols) => {
let dataArr = data->parseData
let weeklyArr = weeklyData->parseData
dataArr
->Array.map(item => {
let dataDict = item->getDictFromJsonObject
let dataKey = activeTab->generateIDFromKeys(dataDict)
weeklyArr->Array.forEach(newItem => {
let weekklyDataDict = newItem->getDictFromJsonObject
let weekklyDataKey = activeTab->generateIDFromKeys(weekklyDataDict)
if dataKey === weekklyDataKey {
cols->Array.forEach(
obj => {
switch weekklyDataDict->Dict.get(obj.refKey) {
| Some(val) => dataDict->Dict.set(obj.newKey, val)
| _ => ()
}
},
)
}
})
dataDict->JSON.Encode.object
})
->JSON.Encode.array
->getTable
->Array.map(Nullable.make)
}
open Promise
let getWeeklyData = async (data, cols) => {
let weeklyDateRange = HSwitchRemoteFilter.getDateFilteredObject()
let weeklyTableReqBody = AnalyticsUtils.generateTablePayload(
~startTimeFromUrl=weeklyDateRange.start_time,
~endTimeFromUrl=weeklyDateRange.end_time,
~filterValueFromUrl,
~currenltySelectedTab=activeTab,
~deltaMetrics,
~isIndustry=false,
~distributionArray=None,
~deltaPrefixArr=deltaArray,
~tableMetrics=[],
~mode=None,
~customFilter,
~moduleName,
~showDeltaMetrics=true,
(),
)
fetchDetails(tableEntity.uri, weeklyTableReqBody, Post)
->thenResolve(json => {
setTableData(_ => getUpdatedData(data, json, cols))
setTableDataLoading(_ => false)
setShowTable(_ => true)
})
->catch(_ => {
setTableDataLoading(_ => false)
resolve()
})
->ignore
}
React.useEffect(() => {
setShowTable(_ => false)
if (
startTimeFromUrl->LogicUtils.isNonEmptyString && endTimeFromUrl->LogicUtils.isNonEmptyString
) {
let tableReqBody = HSAnalyticsUtils.generateTablePayload(
~startTimeFromUrl,
~endTimeFromUrl,
~filterValueFromUrl,
~currenltySelectedTab=activeTab,
~deltaMetrics,
~isIndustry=false,
~distributionArray,
~deltaPrefixArr=deltaArray,
~tableMetrics=[],
~mode=None,
~customFilter,
~moduleName,
~showDeltaMetrics=true,
(),
)
fetchDetails(tableEntity.uri, tableReqBody, Post)
->thenResolve(json => {
switch weeklyTableMetricsCols {
| Some(cols) => getWeeklyData(json, cols)->ignore
| _ => {
let data = json->getDictFromJsonObject
let value =
data->getJsonObjectFromDict("queryData")->getTable->Array.map(Nullable.make)
setTableData(_ => value)
setTableDataLoading(_ => false)
setShowTable(_ => true)
}
}
})
->catch(_ => {
setTableDataLoading(_ => false)
resolve()
})
->ignore
}
None
}, (topFiltersToSearchParam, activeTabStr, customFilter))
let newDefaultCols = React.useMemo(() => {
activeTab
->Option.getOr([])
->Belt.Array.keepMap(item => {
defaultColumns
->Belt.Array.keepMap(
columnItem => {
let val = columnItem->getHeading
val.key === item ? Some(columnItem) : None
},
)
->Array.get(0)
})
->Array.concat(allColumns)
}, [activeTabStr])
let newAllCols = React.useMemo(() => {
defaultColumns
->Belt.Array.keepMap(item => {
let val = item->getHeading
activeTab->Option.getOr([])->Array.includes(val.key) ? Some(item) : None
})
->Array.concat(allColumns)
}, [activeTabStr])
let transactionTableDefaultCols = React.useMemo(() => {
Recoil.atom(`${moduleName}DefaultCols${activeTabStr}`, newDefaultCols)
}, (newDefaultCols, `${moduleName}DefaultCols${activeTabStr}`))
let modifyData = data => {
switch formatData {
| Some(fun) => data->fun
| None => data
}
}
showTable
? <>
<div className="h-full -mx-4 overflow-scroll">
<Form>
<BaseTableComponent
filters=(startTimeFromUrl, endTimeFromUrl)
tableData={tableData->modifyData}
tableDataLoading
transactionTableDefaultCols
defaultSort
newDefaultCols
newAllCols
tableEntity
colMapper
tableGlobalFilter
activeTab={activeTab->Option.getOr([])}
/>
</Form>
</div>
<RenderIf condition={tableData->Array.length > 0}>
<div
className={`flex items-start ${borderColor.primaryNormal} text-sm rounded-md gap-2 px-4 py-3`}>
<Icon name="info-vacent" className={`${textColor.primaryNormal} mt-1`} size=18 />
{"'NA' denotes those incomplete or failed payments with no assigned values for the corresponding parameters due to reasons like customer drop-offs, technical failures, etc."->React.string}
</div>
</RenderIf>
</>
: <Loader />
}
}
module TabDetails = {
@react.component
let make = (
~chartEntity: DynamicChart.entity,
~activeTab,
~defaultSort: string,
~getTable: JSON.t => array<'t>,
~colMapper: 'colType => string,
~distributionArray,
~tableEntity: option<EntityType.entityType<'colType, 't>>,
~deltaMetrics: array<string>,
~deltaArray: array<string>,
~tableUpdatedHeading: option<
(~item: option<'t>, ~dateObj: option<AnalyticsUtils.prevDates>) => 'colType => Table.header,
>,
~tableGlobalFilter: option<(array<Nullable.t<'t>>, JSON.t) => array<Nullable.t<'t>>>,
~moduleName,
~updateUrl: Dict.t<string> => unit,
~weeklyTableMetricsCols,
~formatData=None,
) => {
open AnalyticsTypes
let analyticsType = moduleName->getAnalyticsType
let id =
activeTab
->Option.getOr(["tab"])
->Array.reduce("", (acc, tabName) => {acc->String.concat(tabName)})
let isMobileView = MatchMedia.useMobileChecker()
let wrapperClass = React.useMemo(() =>
switch analyticsType {
| AUTHENTICATION => `h-auto basis-full mt-4 ${isMobileView ? "w-full" : "w-1/2"}`
| _ => "bg-white border rounded-lg p-8 mt-3 mb-7"
}
, [isMobileView])
let tabTitleMapper = switch analyticsType {
| AUTHENTICATION =>
[
("browser_name", "browser"),
("component", "checkout_platform"),
("platform", "customer_device"),
]->Dict.fromArray
| _ => Dict.make()
}
let comparitionWidget = switch analyticsType {
| AUTHENTICATION => false
| _ => true
}
let tab =
<div className=wrapperClass>
<DynamicChart
entity=chartEntity
selectedTab=activeTab
chartId=moduleName
updateUrl
enableBottomChart=false
showTableLegend=false
showMarkers=true
legendType=HighchartTimeSeriesChart.Points
tabTitleMapper
comparitionWidget
/>
{switch tableEntity {
| Some(tableEntity) =>
<TableWrapper
dateKeys=chartEntity.dateFilterKeys
filterKeys=chartEntity.allFilterDimension
activeTab
getTable
colMapper
defaultSort
tableEntity
deltaMetrics
deltaArray
tableUpdatedHeading
tableGlobalFilter
moduleName
weeklyTableMetricsCols
distributionArray
formatData
/>
| None => React.null
}}
</div>
switch analyticsType {
| AUTHENTICATION => tab
| _ => <FramerMotion.TransitionComponent id={id}> {tab} </FramerMotion.TransitionComponent>
}
}
}
open AnalyticsTypes
@react.component
let make = (
~pageTitle="",
~startTimeFilterKey: string,
~endTimeFilterKey: string,
~chartEntity: nestedEntityType,
~defaultSort: string,
~tabKeys: array<string>,
~tabValues: array<DynamicTabs.tab>,
~initialFilters: JSON.t => array<EntityType.initialFilters<'t>>,
~initialFixedFilters: (JSON.t, ~events: unit => unit=?) => array<EntityType.initialFilters<'t>>,
~options: JSON.t => array<EntityType.optionType<'t>>,
~getTable: JSON.t => array<'a>,
~colMapper: 'colType => string,
~tableEntity: option<EntityType.entityType<'colType, 't>>=?,
~deltaMetrics: array<string>,
~deltaArray: array<string>,
~singleStatEntity: DynamicSingleStat.entityType<'singleStatColType, 'b, 'b2>,
~filterUri: option<string>,
~tableUpdatedHeading: option<
(~item: option<'t>, ~dateObj: option<AnalyticsUtils.prevDates>) => 'colType => Table.header,
>=?,
~tableGlobalFilter: option<(array<Nullable.t<'t>>, JSON.t) => array<Nullable.t<'t>>>=?,
~moduleName: string,
~weeklyTableMetricsCols=?,
~distributionArray=None,
~formatData=None,
) => {
let analyticsType = moduleName->getAnalyticsType
let {filterValue, updateExistingKeys, filterValueJson} = React.useContext(
FilterContext.filterContext,
)
let {checkUserEntity} = React.useContext(UserInfoProvider.defaultContext)
let defaultFilters = [startTimeFilterKey, endTimeFilterKey]
let (filteredTabKeys, filteredTabVales) = (tabKeys, tabValues)
let chartEntity1 = chartEntity.default // User Journey - SemiDonut (Payment Metrics), Others - Default Chart Entity
let pieChartEntity = chartEntity.userPieChart // SemiDonut (User Metrics)
let barChartEntity = chartEntity.userBarChart // HorizontalBar (User Metrics)
let funnelChartEntity = chartEntity.userFunnelChart // Funnel (All Metrics)
let chartEntity1 = switch chartEntity1 {
| Some(chartEntity) => Some({...chartEntity, allFilterDimension: filteredTabKeys})
| None => None
}
let filterValueDict = filterValueJson
let mixpanelEvent = MixpanelHook.useSendEvent()
let url = RescriptReactRouter.useUrl()
let urlArray = url.path->List.toArray
let analyticsTypeName = switch urlArray[1] {
| Some(val) => val->kebabToSnakeCase
| _ => ""
}
let (activeTav, setActiveTab) = React.useState(_ =>
filterValueDict->getStrArrayFromDict(`${moduleName}.tabName`, filteredTabKeys)
)
let setActiveTab = React.useMemo(() => {
(str: string) => {
setActiveTab(_ => str->String.split(","))
}
}, [setActiveTab])
let startTimeVal = filterValueDict->getString(startTimeFilterKey, "")
let endTimeVal = filterValueDict->getString(endTimeFilterKey, "")
let {updateAnalytcisEntity} = OMPSwitchHooks.useUserInfo()
let {userInfo: {analyticsEntity}} = React.useContext(UserInfoProvider.defaultContext)
let updateUrlWithPrefix = React.useMemo(() => {
(chartType: string) => {
(dict: Dict.t<string>) => {
let prev = filterValue
let prevDictArr =
prev
->Dict.toArray
->Belt.Array.keepMap(item => {
let (key, _) = item
switch dict->Dict.get(key) {
| Some(_) => None
| None => Some(item)
}
})
let currentDict =
dict
->Dict.toArray
->Belt.Array.keepMap(item => {
let (key, value) = item
if value->LogicUtils.isNonEmptyString {
Some((`${moduleName}${chartType}.${key}`, value))
} else {
None
}
})
updateExistingKeys(Array.concat(prevDictArr, currentDict)->Dict.fromArray)
}
}
}, [updateExistingKeys])
let setInitialFilters = HSwitchRemoteFilter.useSetInitialFilters(
~updateExistingKeys,
~startTimeFilterKey,
~endTimeFilterKey,
~origin="analytics",
(),
)
React.useEffect(() => {
setInitialFilters()
None
}, [])
let filterBody = React.useMemo(() => {
let filterBodyEntity: AnalyticsUtils.filterBodyEntity = {
startTime: startTimeVal,
endTime: endTimeVal,
groupByNames: filteredTabKeys,
source: "BATCH",
}
AnalyticsUtils.filterBody(filterBodyEntity)
}, (startTimeVal, endTimeVal, filteredTabKeys->Array.joinWith(",")))
open APIUtils
open Promise
let (filterDataJson, setFilterDataJson) = React.useState(_ => None)
let updateDetails = useUpdateMethod()
let {filterValueJson} = FilterContext.filterContext->React.useContext
let startTimeVal = filterValueJson->getString("startTime", "")
let endTimeVal = filterValueJson->getString("endTime", "")
React.useEffect(() => {
setFilterDataJson(_ => None)
if startTimeVal->LogicUtils.isNonEmptyString && endTimeVal->LogicUtils.isNonEmptyString {
try {
switch filterUri {
| Some(filterUri) =>
updateDetails(filterUri, filterBody->JSON.Encode.object, Post)
->thenResolve(json => setFilterDataJson(_ => Some(json)))
->catch(_ => resolve())
->ignore
| None => ()
}
} catch {
| _ => ()
}
}
None
}, (startTimeVal, endTimeVal, filterBody->JSON.Encode.object->JSON.stringify))
let filterData = filterDataJson->Option.getOr(Dict.make()->JSON.Encode.object)
//This is to trigger the mixpanel event to see active analytics users
React.useEffect(() => {
if startTimeVal->LogicUtils.isNonEmptyString && endTimeVal->LogicUtils.isNonEmptyString {
mixpanelEvent(~eventName=`${analyticsTypeName}_date_filter`)
}
None
}, (startTimeVal, endTimeVal))
let activeTab = React.useMemo(() => {
Some(
filterValueDict
->getStrArrayFromDict(`${moduleName}.tabName`, activeTav)
->Array.filter(item => item->LogicUtils.isNonEmptyString),
)
}, [filterValueDict])
let isMobileView = MatchMedia.useMobileChecker()
let dateDropDownTriggerMixpanelCallback = () => {
mixpanelEvent(~eventName=`${analyticsTypeName}_date_filter_opened`)
}
let tabDetailsClass = React.useMemo(() => {
isMobileView ? "flex flex-col gap-4 my-4" : "flex flex-row gap-4 my-4"
}, [isMobileView])
let topFilterUi = switch filterDataJson {
| Some(filterData) => {
let filterData = switch analyticsType {
| AUTHENTICATION => {
let filteredDims = ["payment_method", "payment_experience", "source"]
let queryData =
filterData
->getDictFromJsonObject
->getJsonObjectFromDict("queryData")
->getArrayFromJson([])
->Array.filter(dimension => {
let dim = dimension->getDictFromJsonObject->getString("dimension", "")
filteredDims->Array.includes(dim)->not
})
->JSON.Encode.array
[("queryData", queryData)]->Dict.fromArray->JSON.Encode.object
}
| _ => filterData
}
<div className="flex flex-row">
<DynamicFilter
initialFilters={initialFilters(filterData)}
options=[]
popupFilterFields={options(filterData)}
initialFixedFilters={initialFixedFilters(
filterData,
~events=dateDropDownTriggerMixpanelCallback,
)}
defaultFilterKeys=defaultFilters
tabNames=tabKeys
updateUrlWith=updateExistingKeys
key="0"
filterFieldsPortalName={HSAnalyticsUtils.filterFieldsPortalName}
showCustomFilter=false
refreshFilters=false
/>
</div>
}
| None =>
<div className="flex flex-row">
<DynamicFilter
initialFilters=[]
options=[]
popupFilterFields=[]
initialFixedFilters={initialFixedFilters(
filterData,
~events=dateDropDownTriggerMixpanelCallback,
)}
defaultFilterKeys=defaultFilters
tabNames=tabKeys
updateUrlWith=updateExistingKeys //
key="1"
filterFieldsPortalName={HSAnalyticsUtils.filterFieldsPortalName}
showCustomFilter=false
refreshFilters=false
/>
</div>
}
<RenderIf condition={filterValueDict->Dict.toArray->Array.length > 0}>
{switch chartEntity1 {
| Some(chartEntity) =>
<div>
<div className="flex items-center justify-between">
<PageUtils.PageHeading title=pageTitle />
// Refactor required
<div className="mr-4">
<RenderIf condition={moduleName == "Refunds" || moduleName == "Disputes"}>
<OMPSwitchHelper.OMPViews
views={OMPSwitchUtils.analyticsViewList(~checkUserEntity)}
selectedEntity={analyticsEntity}
onChange={updateAnalytcisEntity}
entityMapper=UserInfoUtils.analyticsEntityMapper
/>
</RenderIf>
</div>
</div>
<div className="mt-2 -ml-1"> topFilterUi </div>
<div>
<div className="mt-5">
<DynamicSingleStat
entity=singleStatEntity
startTimeFilterKey
endTimeFilterKey
filterKeys=chartEntity.allFilterDimension
moduleName
showPercentage=false
statSentiment={singleStatEntity.statSentiment->Option.getOr(Dict.make())}
/>
</div>
<div className="flex flex-row">
{switch analyticsType {
| AUTHENTICATION =>
<div className="flex flex-col bg-transparent w-full h-max">
{switch funnelChartEntity {
| Some(funnelChartEntity) =>
<div className={tabDetailsClass}>
<TabDetails
chartEntity={{...funnelChartEntity, moduleName: `${moduleName}Funnel`}}
activeTab={None}
defaultSort
getTable
distributionArray
colMapper
tableEntity
deltaMetrics
deltaArray
tableUpdatedHeading
tableGlobalFilter
moduleName={`${moduleName}Funnel`}
updateUrl={dict => {
let updateUrlWithPrefix = updateUrlWithPrefix("Funnel")
updateUrlWithPrefix(dict)
}}
weeklyTableMetricsCols
/>
</div>
| None => React.null
}}
<div className={tabDetailsClass}>
{switch barChartEntity {
| Some(barChartEntity) =>
<TabDetails
chartEntity={{...barChartEntity, moduleName: `${moduleName}Bar`}}
activeTab={Some(["browser_name"])}
defaultSort
getTable
colMapper
tableEntity
distributionArray
deltaMetrics
deltaArray
tableUpdatedHeading
tableGlobalFilter
moduleName={`${moduleName}Bar`}
updateUrl={dict => {
let updateUrlWithPrefix = updateUrlWithPrefix("Bar")
updateUrlWithPrefix(dict)
}}
weeklyTableMetricsCols
/>
| None => React.null
}}
</div>
{switch pieChartEntity {
| Some(pieChartEntity) =>
<div className={tabDetailsClass}>
<TabDetails
chartEntity={pieChartEntity}
activeTab={Some(["platform"])}
defaultSort
getTable
colMapper
tableEntity
distributionArray
deltaMetrics
deltaArray
tableUpdatedHeading
tableGlobalFilter
moduleName
updateUrl={dict => {
let updateUrlWithPrefix = updateUrlWithPrefix("")
updateUrlWithPrefix(dict)
}}
weeklyTableMetricsCols
/>
<TabDetails
chartEntity={pieChartEntity}
activeTab={Some(["component"])}
defaultSort
getTable
colMapper
distributionArray
tableEntity
deltaMetrics
deltaArray
tableUpdatedHeading
tableGlobalFilter
moduleName
updateUrl={dict => {
let updateUrlWithPrefix = updateUrlWithPrefix("")
updateUrlWithPrefix(dict)
}}
weeklyTableMetricsCols
/>
</div>
| None => React.null
}}
</div>
| _ =>
<div className="flex flex-col h-full overflow-scroll w-full mt-5">
<DynamicTabs
tabs=filteredTabVales
maxSelection=3
tabId=moduleName
setActiveTab
updateUrlDict={dict => {
let updateUrlWithPrefix = updateUrlWithPrefix("")
updateUrlWithPrefix(dict)
}}
tabContainerClass="analyticsTabs"
initalTab=?activeTab
/>
<TabDetails
chartEntity
activeTab
defaultSort
distributionArray
getTable
colMapper
tableEntity
deltaMetrics
deltaArray
tableUpdatedHeading
tableGlobalFilter
moduleName
updateUrl={dict => {
let updateUrlWithPrefix = updateUrlWithPrefix("")
updateUrlWithPrefix(dict)
}}
weeklyTableMetricsCols
formatData
/>
</div>
}}
</div>
</div>
</div>
| _ => React.null
}}
</RenderIf>
}
| 6,365 | 9,745 |
hyperswitch-control-center | src/screens/Analytics/AnalyticsAtoms.res | .res | let customFilterAtom: Recoil.recoilAtom<string> = Recoil.atom("customFilterAtom", "")
let completionProvider: Recoil.recoilAtom<option<Monaco.Language.regProvider>> = Recoil.atom(
"completionProvider",
None,
)
| 53 | 9,746 |
hyperswitch-control-center | src/screens/Analytics/HSAnalyticsUtils.res | .res | let filterFieldsPortalName = "analytics"
let setPrecision = (num, ~digit=2) => {
num->Float.toFixedWithPrecision(~digits=digit)->Js.Float.fromString
}
let getQueryData = json => {
open LogicUtils
json->getDictFromJsonObject->getArrayFromDict("queryData", [])
}
let options: JSON.t => array<EntityType.optionType<'t>> = json => {
open LogicUtils
json
->getDictFromJsonObject
->getOptionalArrayFromDict("queryData")
->Option.flatMap(arr => {
arr
->Array.map(dimensionObject => {
let dimensionObject = dimensionObject->getDictFromJsonObject
let dimension = getString(dimensionObject, "dimension", "")
let dimensionTitleCase = `Select ${snakeToTitle(dimension)}`
let value = getArrayFromDict(dimensionObject, "values", [])->getStrArrayFromJsonArray
let dropdownOptions: EntityType.optionType<'t> = {
urlKey: dimension,
field: {
FormRenderer.makeFieldInfo(
~label="",
~name=dimension,
~customInput=InputFields.multiSelectInput(
~options={
value
->SelectBox.makeOptions
->Array.map(
item => {
let value = {...item, label: item.value}
value
},
)
},
~buttonText=dimensionTitleCase,
~showSelectionAsChips=false,
~searchable=true,
~showToolTip=true,
~showNameAsToolTip=true,
~customButtonStyle="bg-none",
),
)
},
parser: val => val,
localFilter: None,
}
dropdownOptions
})
->Some
})
->Option.getOr([])
}
let filterByData = (txnArr, value) => {
let searchText = LogicUtils.getStringFromJson(value, "")
txnArr
->Belt.Array.keepMap(Nullable.toOption)
->Belt.Array.keepMap((data: 't) => {
let valueArr =
data
->Identity.genericTypeToDictOfJson
->Dict.toArray
->Array.map(item => {
let (_, value) = item
value->JSON.Decode.string->Option.getOr("")->String.toLowerCase->String.includes(searchText)
})
->Array.reduce(false, (acc, item) => item || acc)
if valueArr {
data->Nullable.make->Some
} else {
None
}
})
}
let initialFilterFields = json => {
open LogicUtils
let dropdownValue =
json
->getDictFromJsonObject
->getOptionalArrayFromDict("queryData")
->Option.flatMap(arr => {
arr
->Belt.Array.keepMap(item => {
let dimensionObject = item->getDictFromJsonObject
let dimensionValue = getString(dimensionObject, "dimension", "")
// TODO: Add support for custom labels. This can be achieved either through backend support (by making dimension an array of objects) or frontend support (via a custom label field).
let dimensionLabel = switch dimensionValue {
| "acs_reference_number" => "issuer"
| _ => dimensionValue
}
let dimensionTitleCase = `Select ${snakeToTitle(dimensionLabel)}`
let value = getArrayFromDict(dimensionObject, "values", [])->getStrArrayFromJsonArray
Some(
(
{
field: FormRenderer.makeFieldInfo(
~label=dimensionLabel,
~name=dimensionValue,
~customInput=InputFields.filterMultiSelectInput(
~options=value->FilterSelectBox.makeOptions,
~buttonText=dimensionTitleCase,
~showSelectionAsChips=false,
~searchable=true,
~showToolTip=true,
~showNameAsToolTip=true,
~customButtonStyle="bg-none",
(),
),
),
localFilter: Some(filterByData),
}: EntityType.initialFilters<'t>
),
)
})
->Some
})
->Option.getOr([])
dropdownValue
}
let (startTimeFilterKey, endTimeFilterKey, optFilterKey) = ("startTime", "endTime", "opt")
let initialFixedFilterFields = (_json, ~events=?) => {
let events = switch events {
| Some(fn) => fn
| None => _ => ()
}
let newArr = [
(
{
localFilter: None,
field: FormRenderer.makeMultiInputFieldInfo(
~label="",
~comboCustomInput=InputFields.filterDateRangeField(
~startKey=startTimeFilterKey,
~endKey=endTimeFilterKey,
~format="YYYY-MM-DDTHH:mm:ss[Z]",
~showTime=true,
~disablePastDates={false},
~disableFutureDates={true},
~predefinedDays=[
Hour(0.5),
Hour(1.0),
Hour(2.0),
Today,
Yesterday,
Day(2.0),
Day(7.0),
Day(30.0),
ThisMonth,
LastMonth,
],
~numMonths=2,
~disableApply=false,
~dateRangeLimit=180,
~optFieldKey=optFilterKey,
~events,
),
~inputFields=[],
~isRequired=false,
),
}: EntityType.initialFilters<'t>
),
]
newArr
}
let getStringListFromArrayDict = metrics => {
open LogicUtils
metrics->Array.map(item => item->getDictFromJsonObject->getString("name", ""))
}
module NoData = {
@react.component
let make = (~title) => {
<div className="p-5">
<PageUtils.PageHeading title />
<NoDataFound message="No Data Available" renderType=Painting>
<Button
text={"Make a Payment"}
buttonSize={Small}
onClick={_ => RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/home"))}
buttonType={Primary}
/>
</NoDataFound>
</div>
}
}
let generateTablePayload = (
~startTimeFromUrl: string,
~endTimeFromUrl: string,
~filterValueFromUrl: option<JSON.t>,
~currenltySelectedTab: option<array<string>>,
~tableMetrics: array<string>,
~distributionArray: option<array<JSON.t>>,
~deltaMetrics: array<string>,
~deltaPrefixArr: array<string>,
~isIndustry: bool,
~mode: option<string>,
~customFilter,
~showDeltaMetrics,
~moduleName as _,
~source: string="BATCH",
(),
) => {
open AnalyticsUtils
let metrics = tableMetrics
let startTime = startTimeFromUrl
let endTime = endTimeFromUrl
let deltaDateArr =
{deltaMetrics->Array.length === 0}
? []
: generateDateArray(~startTime, ~endTime, ~deltaPrefixArr)
let deltaPayload = generatedeltaTablePayload(
~deltaDateArr,
~metrics=deltaMetrics,
~groupByNames=currenltySelectedTab,
~source,
~mode,
~deltaPrefixArr,
~filters=filterValueFromUrl,
~customFilter,
~showDeltaMetrics,
)
let tableBodyWithNonDeltaMetrix = if metrics->Array.length > 0 {
[
getFilterRequestBody(
~groupByNames=currenltySelectedTab,
~filter=filterValueFromUrl,
~metrics=Some(metrics),
~delta=showDeltaMetrics,
~mode,
~startDateTime=startTime,
~endDateTime=endTime,
~customFilter,
~source,
),
]
} else {
[]
}
let tableBodyWithDeltaMetrix = if deltaMetrics->Array.length > 0 {
switch distributionArray {
| Some(distributionArray) =>
distributionArray->Array.map(arr =>
getFilterRequestBody(
~groupByNames=currenltySelectedTab,
~filter=filterValueFromUrl,
~metrics=Some(deltaMetrics),
~delta=showDeltaMetrics,
~mode,
~startDateTime=startTime,
~distributionValues=Some(arr),
~endDateTime=endTime,
~customFilter,
~source,
)
)
| None => [
getFilterRequestBody(
~groupByNames=currenltySelectedTab,
~filter=filterValueFromUrl,
~metrics=Some(deltaMetrics),
~delta=showDeltaMetrics,
~mode,
~startDateTime=startTime,
~endDateTime=endTime,
~customFilter,
~source,
),
]
}
} else {
[]
}
let tableIndustryPayload = if isIndustry {
[
getFilterRequestBody(
~groupByNames=currenltySelectedTab,
~filter=filterValueFromUrl,
~metrics=Some(deltaMetrics),
~delta=showDeltaMetrics,
~mode,
~prefix=Some("industry"),
~startDateTime=startTime,
~endDateTime=endTime,
~customFilter,
~source,
),
]
} else {
[]
}
let tableBodyValues =
tableBodyWithNonDeltaMetrix->Array.concatMany([tableBodyWithDeltaMetrix, tableIndustryPayload])
let tableBody =
tableBodyValues->Array.concat(deltaPayload)->Array.map(JSON.Encode.object)->JSON.Encode.array
tableBody
}
| 2,049 | 9,747 |
hyperswitch-control-center | src/screens/Analytics/AnalyticsUtils.res | .res | type node = {childNodes: array<Dom.element>}
@val external document: Dom.element = "document"
@send
external getElementsByClassName: ('a, string) => array<node> = "getElementsByClassName"
external toNode: Dom.element => node = "%identity"
type timeRanges = {
fromTime: string,
toTime: string,
}
type loaderType = SideLoader | Shimmer
type prevDates = {
currentSr: timeRanges,
prev7DaySr: timeRanges,
yesterdaySr: timeRanges,
currentWeekSr: timeRanges,
currentMonthSr: timeRanges,
industrySr: timeRanges,
}
type timeKeys = {
startTimeKey: string,
endTimeKey: string,
}
type filterBodyEntity = {
startTime: string,
endTime: string,
groupByNames: array<string>,
source: string,
mode?: string,
}
// check the ISOLATING FILTERS Component section https://docs.google.com/document/d/1Wub6jhmKqJVrxthYZ_y8BNUOGv9MW_wU3LsY5shYdUE/edit for more info
type filterEntity<'t> = {
uri: string,
moduleName: string,
initialFixedFilters: JSON.t => array<EntityType.initialFilters<'t>>,
initialFilters: JSON.t => array<EntityType.initialFilters<'t>>,
filterDropDownOptions: JSON.t => array<EntityType.optionType<'t>>,
filterKeys: array<string>,
timeKeys: timeKeys,
defaultFilterKeys: array<string>,
source?: string,
filterBody?: filterBodyEntity => string,
customFilterKey?: string,
}
type filterEntityNew<'t> = {
uri: string,
moduleName: string,
initialFixedFilters: JSON.t => array<EntityType.initialFilters<'t>>,
initialFilters: (JSON.t, string => unit) => array<EntityType.initialFilters<'t>>,
filterKeys: array<string>,
timeKeys: timeKeys,
defaultFilterKeys: array<string>,
source?: string,
filterBody?: filterBodyEntity => string,
customFilterKey?: string,
sortingColumnLegend?: string,
}
type downloadDataApiBodyEntity = {
startTime: string,
endTime: string,
columns: array<string>,
compressed: bool,
}
type downloadDataEntity = {
uri: string,
downloadRawDataCols: array<string>,
downloadDataBody: downloadDataApiBodyEntity => string,
moduleName?: string,
timeKeys: timeKeys,
description?: string,
customFilterKey?: string,
}
type tableApiBodyEntity = {
startTimeFromUrl: string,
endTimeFromUrl: string,
filterValueFromUrl?: JSON.t,
currenltySelectedTab?: array<string>,
deltaMetrics: array<string>,
isIndustry: bool,
distributionArray?: array<JSON.t>,
deltaPrefixArr: array<string>,
tableMetrics: array<string>,
mode?: string,
customFilter: string,
moduleName: string,
showDeltaMetrics: bool,
source: string,
}
type newApiBodyEntity = {
timeObj: Dict.t<JSON.t>,
metric?: string,
groupBy?: array<Js_string.t>,
granularityConfig?: (int, string),
cardinality?: float,
filterValueFromUrl?: JSON.t,
customFilterValue?: string,
jsonFormattedFilter?: JSON.t,
cardinalitySortDims?: string,
domain: string,
}
type analyticsTableEntity<'colType, 't> = {
metrics: array<string>,
deltaMetrics: array<string>,
headerMetrics: array<string>,
distributionArray: option<array<JSON.t>>,
tableEntity: EntityType.entityType<'colType, 't>,
deltaPrefixArr: array<string>,
isIndustry: bool,
tableUpdatedHeading: option<
(
~item: option<'t>,
~dateObj: option<prevDates>,
~mode: option<string>,
'colType,
) => Table.header,
>,
tableGlobalFilter: option<(array<Nullable.t<'t>>, JSON.t) => array<Nullable.t<'t>>>,
moduleName: string,
defaultSortCol: string,
filterKeys: array<string>,
timeKeys: timeKeys,
modeKey: option<string>,
moduleNamePrefix: string,
getUpdatedCell?: (tableApiBodyEntity, 't, 'colType) => Table.cell,
defaultColumn?: array<'colType>,
colDependentDeltaPrefixArr?: 'colType => option<string>,
source: string,
tableSummaryBody?: tableApiBodyEntity => string,
tableBodyEntity?: tableApiBodyEntity => string,
sampleApiBody?: tableApiBodyEntity => string,
customFilterKey?: string,
newTableBodyMaker?: newApiBodyEntity => JSON.t,
jsonTransformer?: (string, array<JSON.t>, array<string>) => array<JSON.t>,
}
type statSentiment = Positive | Negative | Neutral
let (startTimeFilterKey, endTimeFilterKey, optFilterKey) = ("startTime", "endTime", "opt")
let getDateCreatedObject = () => {
let currentDate = Date.now()
let filterCreatedDict = Dict.make()
let currentTimestamp = currentDate->Js.Date.fromFloat->Date.toISOString
let dateFormat = "YYYY-MM-DDTHH:mm:[00][Z]"
Dict.set(
filterCreatedDict,
endTimeFilterKey,
JSON.Encode.string(currentTimestamp->TimeZoneHook.formattedISOString(dateFormat)),
)
let prevTime = {
let presentDayInString = Js.Date.fromFloat(currentDate)
Js.Date.setHoursMS(presentDayInString, ~hours=0.0, ~minutes=0.0, ~seconds=0.0, ())
}
let defaultStartTime = {
JSON.Encode.string(
prevTime
->Js.Date.fromFloat
->Date.toISOString
->TimeZoneHook.formattedISOString("YYYY-MM-DDTHH:mm:[00][Z]"),
)
}
Dict.set(filterCreatedDict, startTimeFilterKey, defaultStartTime)
Dict.set(filterCreatedDict, "opt", JSON.Encode.string("today"))
filterCreatedDict
}
open LogicUtils
let getFilterRequestBody = (
~granularity: option<string>=None,
~groupByNames: option<array<string>>=None,
~filter: option<JSON.t>=None,
~metrics: option<array<string>>=None,
~delta: bool=true,
~prefix: option<string>=None,
~distributionValues: option<JSON.t>=None,
~startDateTime,
~endDateTime,
~cardinality: option<string>=None,
~mode: option<string>=None,
~customFilter: string="",
~source: string="BATCH",
) => {
let body: Dict.t<JSON.t> = Dict.make()
let timeRange = Dict.make()
let timeSeries = Dict.make()
Dict.set(timeRange, "startTime", startDateTime->JSON.Encode.string)
Dict.set(timeRange, "endTime", endDateTime->JSON.Encode.string)
Dict.set(body, "timeRange", timeRange->JSON.Encode.object)
switch groupByNames {
| Some(groupByNames) =>
if groupByNames->Array.length != 0 {
Dict.set(
body,
"groupByNames",
groupByNames
->ArrayUtils.getUniqueStrArray
->Belt.Array.keepMap(item => Some(item->JSON.Encode.string))
->JSON.Encode.array,
)
}
| None => ()
}
switch filter {
| Some(filters) =>
if !(filters->checkEmptyJson) {
Dict.set(body, "filters", filters)
}
| None => ()
}
switch distributionValues {
| Some(distributionValues) =>
if !(distributionValues->checkEmptyJson) {
Dict.set(body, "distribution", distributionValues)
}
| None => ()
}
if customFilter->isNonEmptyString {
Dict.set(body, "customFilter", customFilter->JSON.Encode.string)
}
switch granularity {
| Some(granularity) => {
Dict.set(timeSeries, "granularity", granularity->JSON.Encode.string)
Dict.set(body, "timeSeries", timeSeries->JSON.Encode.object)
}
| None => ()
}
switch cardinality {
| Some(cardinality) => Dict.set(body, "cardinality", cardinality->JSON.Encode.string)
| None => ()
}
switch mode {
| Some(mode) => Dict.set(body, "mode", mode->JSON.Encode.string)
| None => ()
}
switch prefix {
| Some(prefix) => Dict.set(body, "prefix", prefix->JSON.Encode.string)
| None => ()
}
Dict.set(body, "source", source->JSON.Encode.string)
switch metrics {
| Some(metrics) =>
if metrics->Array.length != 0 {
Dict.set(
body,
"metrics",
metrics
->ArrayUtils.getUniqueStrArray
->Belt.Array.keepMap(item => Some(item->JSON.Encode.string))
->JSON.Encode.array,
)
}
| None => ()
}
if delta {
Dict.set(body, "delta", true->JSON.Encode.bool)
}
body
}
let filterBody = (filterBodyEntity: filterBodyEntity) => {
let (startTime, endTime) = try {
(
(filterBodyEntity.startTime->DayJs.getDayJsForString).subtract(
1,
"day",
).toDate()->Date.toISOString,
(filterBodyEntity.endTime->DayJs.getDayJsForString).add(1, "day").toDate()->Date.toISOString,
)
} catch {
| _ => (filterBodyEntity.startTime, filterBodyEntity.endTime)
}
getFilterRequestBody(
~startDateTime=startTime,
~endDateTime=endTime,
~groupByNames=Some(filterBodyEntity.groupByNames),
~source=filterBodyEntity.source,
)
}
let deltaDate = (~fromTime: string, ~_toTime: string, ~typeTime: string) => {
let fromTime = fromTime
let nowtime = Date.make()->Date.toString->DayJs.getDayJsForString
let dateTimeFormat = "YYYY-MM-DDTHH:mm:ss[Z]"
if typeTime == "last7" {
let last7FromTime = (fromTime->DayJs.getDayJsForString).subtract(7, "day")
let last7ToTime = (fromTime->DayJs.getDayJsForString).subtract(1, "day")
let timeArray = Dict.fromArray([
("fromTime", last7FromTime.format(dateTimeFormat)),
("toTime", last7ToTime.format(dateTimeFormat)),
])
[timeArray]
} else if typeTime == "yesterday" {
let yesterdayFromTime =
Js.Date.fromFloat(
Js.Date.setHoursMS(
nowtime.subtract(1, "day").toDate(),
~hours=0.0,
~minutes=0.0,
~seconds=0.0,
(),
),
)->DayJs.getDayJsForJsDate
let yesterdayToTime =
Js.Date.fromFloat(
Js.Date.setHoursMS(
nowtime.subtract(1, "day").toDate(),
~hours=23.0,
~minutes=59.0,
~seconds=59.0,
(),
),
)->DayJs.getDayJsForJsDate
let timeArray = Dict.fromArray([
("fromTime", yesterdayFromTime.format(dateTimeFormat)),
("toTime", yesterdayToTime.format(dateTimeFormat)),
])
[timeArray]
} else if typeTime == "currentmonth" {
let currentMonth = Js.Date.fromFloat(Js.Date.setDate(Date.make(), 1.0))
let currentMonthFromTime =
Js.Date.fromFloat(
Js.Date.setHoursMS(currentMonth, ~hours=0.0, ~minutes=0.0, ~seconds=0.0, ()),
)
->Date.toString
->DayJs.getDayJsForString
let currentMonthToTime = nowtime
let timeArray = Dict.fromArray([
("fromTime", currentMonthFromTime.format(dateTimeFormat)),
("toTime", currentMonthToTime.format(dateTimeFormat)),
])
[timeArray]
} else if typeTime == "currentweek" {
let currentWeekFromTime = Date.make()->DateTimeUtils.getStartOfWeek(Monday)
let currentWeekToTime = Date.make()->DayJs.getDayJsForJsDate
let timeArray = Dict.fromArray([
("fromTime", currentWeekFromTime.format(dateTimeFormat)),
("toTime", currentWeekToTime.format(dateTimeFormat)),
])
[timeArray]
} else {
let timeArray = Dict.make()
[timeArray]
}
}
let generateDateArray = (~startTime, ~endTime, ~deltaPrefixArr) => {
let dateArray = Array.map(deltaPrefixArr, x =>
deltaDate(~fromTime=startTime, ~_toTime=endTime, ~typeTime=x)
)
dateArray
}
let generatePayload = (
~startTime,
~endTime,
~metrics,
~delta,
~mode: option<string>=None,
~groupByNames,
~prefix,
~source,
~filters: option<JSON.t>,
~customFilter,
) => {
let timeArr = Dict.fromArray([
("startTime", startTime->JSON.Encode.string),
("endTime", endTime->JSON.Encode.string),
])
let newDict = switch groupByNames {
| Some(groupByNames) =>
Dict.fromArray([
("timeRange", timeArr->JSON.Encode.object),
("metrics", metrics->getJsonFromArrayOfString),
("groupByNames", groupByNames->getJsonFromArrayOfString),
("prefix", prefix->JSON.Encode.string),
("source", source->JSON.Encode.string),
("delta", delta->JSON.Encode.bool),
])
| None =>
Dict.fromArray([
("timeRange", timeArr->JSON.Encode.object),
("metrics", metrics->getJsonFromArrayOfString),
("prefix", prefix->JSON.Encode.string),
("source", source->JSON.Encode.string),
("delta", delta->JSON.Encode.bool),
])
}
switch mode {
| Some(mode) => Dict.set(newDict, "mode", mode->JSON.Encode.string)
| None => ()
}
if customFilter->isNonEmptyString {
Dict.set(newDict, "customFilter", customFilter->JSON.Encode.string)
}
switch filters {
| Some(filters) =>
if !(filters->checkEmptyJson) {
Dict.set(newDict, "filters", filters)
}
| None => ()
}
newDict
}
let generatedeltaTablePayload = (
~deltaDateArr,
~metrics,
~groupByNames: option<array<string>>,
~source,
~mode: option<string>,
~deltaPrefixArr,
~filters: option<JSON.t>,
~showDeltaMetrics=false,
~customFilter,
) => {
let dictOfDates = Array.flat(deltaDateArr)
let tablePayload = Belt.Array.zipBy(dictOfDates, deltaPrefixArr, (x, y) =>
generatePayload(
~startTime=x->Dict.get("fromTime")->Option.getOr(""),
~endTime=x->Dict.get("toTime")->Option.getOr(""),
~metrics,
~groupByNames,
~mode,
~prefix=y,
~source,
~delta=showDeltaMetrics,
~filters,
~customFilter,
)
)
tablePayload
}
let generateTablePayload = (
~startTimeFromUrl: string,
~endTimeFromUrl: string,
~filterValueFromUrl: option<JSON.t>,
~currenltySelectedTab: option<array<string>>,
~tableMetrics: array<string>,
~distributionArray: option<array<JSON.t>>,
~deltaMetrics: array<string>,
~deltaPrefixArr: array<string>,
~isIndustry: bool,
~mode: option<string>,
~customFilter,
~showDeltaMetrics=false,
~moduleName as _,
~source: string="BATCH",
(),
) => {
let metrics = tableMetrics
let startTime = startTimeFromUrl
let endTime = endTimeFromUrl
let deltaDateArr =
{deltaMetrics->Array.length === 0}
? []
: generateDateArray(~startTime, ~endTime, ~deltaPrefixArr)
let deltaPayload = generatedeltaTablePayload(
~deltaDateArr,
~metrics=deltaMetrics,
~groupByNames=currenltySelectedTab,
~source,
~mode,
~deltaPrefixArr,
~filters=filterValueFromUrl,
~customFilter,
~showDeltaMetrics,
)
let tableBodyWithNonDeltaMetrix = if metrics->Array.length > 0 {
[
getFilterRequestBody(
~groupByNames=currenltySelectedTab,
~filter=filterValueFromUrl,
~metrics=Some(metrics),
~delta=showDeltaMetrics,
~mode,
~startDateTime=startTime,
~endDateTime=endTime,
~customFilter,
~source,
),
]
} else {
[]
}
let tableBodyWithDeltaMetrix = if deltaMetrics->Array.length > 0 {
[
getFilterRequestBody(
~groupByNames=currenltySelectedTab,
~filter=filterValueFromUrl,
~metrics=Some(deltaMetrics),
~delta=showDeltaMetrics,
~mode,
~startDateTime=startTime,
~endDateTime=endTime,
~customFilter,
~source,
),
]
} else {
[]
}
let tableIndustryPayload = if isIndustry {
[
getFilterRequestBody(
~groupByNames=currenltySelectedTab,
~filter=filterValueFromUrl,
~metrics=Some(deltaMetrics),
~delta=showDeltaMetrics,
~mode,
~prefix=Some("industry"),
~startDateTime=startTime,
~endDateTime=endTime,
~customFilter,
~source,
),
]
} else {
[]
}
let tableBodyValues =
tableBodyWithNonDeltaMetrix->Array.concatMany([tableBodyWithDeltaMetrix, tableIndustryPayload])
let distributionPayload = switch distributionArray {
| Some(distributionArray) =>
distributionArray->Array.map(arr =>
getFilterRequestBody(
~groupByNames=currenltySelectedTab,
~filter=filterValueFromUrl,
~delta=false,
~mode,
~distributionValues=Some(arr),
~startDateTime=startTime,
~endDateTime=endTime,
~customFilter,
~source,
)
)
| None => []
}
let tableBody =
tableBodyValues
->Array.concatMany([deltaPayload, distributionPayload])
->Array.map(JSON.Encode.object)
->JSON.Encode.array
tableBody
}
let singlestatDeltaTooltipFormat = (value: float, timeRanges: timeRanges) => (statType: string) => {
let timeText = if timeRanges.fromTime->isNonEmptyString && timeRanges.toTime->isNonEmptyString {
`${"\n"} ${timeRanges.fromTime
->Date.fromString
->DateTimeUtils.utcToIST
->TimeZoneHook.formattedISOString("YYYY-MM-DD HH:mm:ss")}- ${"\n"} ${timeRanges.toTime
->Date.fromString
->DateTimeUtils.utcToIST
->TimeZoneHook.formattedISOString("YYYY-MM-DD HH:mm:ss")}`
} else {
""
}
let tooltipComp = if timeText->isNonEmptyString {
if statType === "Latency" || statType === "NegativeRate" {
if value > 0. {
let text = "Increased by "
let value = Math.abs(value)->Float.toString ++ "%"
<div className="whitespace-pre-line">
<AddDataAttributes attributes=[("data-text", text)]>
<div> {React.string(text)} </div>
</AddDataAttributes>
<AddDataAttributes attributes=[("data-numeric", value)]>
<div className="text-red-500 text-base font-bold font-fira-code">
{React.string(value)}
</div>
</AddDataAttributes>
{React.string(`comparing to ${timeText}`)}
</div>
} else if value < 0. {
let text = "Decreased by "
let value = value->Float.toString ++ "%"
<div className="whitespace-pre-line">
<AddDataAttributes attributes=[("data-text", text)]>
<div> {React.string(text)} </div>
</AddDataAttributes>
<AddDataAttributes attributes=[("data-numeric", value)]>
<div className="text-status-green text-base font-bold font-fira-code">
{React.string(value)}
</div>
</AddDataAttributes>
{React.string(`comparing to ${timeText}`)}
</div>
} else {
let text = "Changed by "
let value = value->Float.toString ++ "%"
<div className="whitespace-pre-line">
<AddDataAttributes attributes=[("data-text", text)]>
<div> {React.string(text)} </div>
</AddDataAttributes>
<AddDataAttributes attributes=[("data-numeric", value)]>
<div className="text-sankey_labels text-base font-bold font-fira-code">
{React.string(value)}
</div>
</AddDataAttributes>
{React.string(`comparing to ${timeText}`)}
</div>
}
} else if value < 0. {
let text = "Decreased by "
let value = Math.abs(value)->Float.toString ++ "%"
<div className="whitespace-pre-line">
<AddDataAttributes attributes=[("data-text", text)]>
<div> {React.string(text)} </div>
</AddDataAttributes>
<AddDataAttributes attributes=[("data-numeric", value)]>
<div className="text-red-500 text-base font-bold font-fira-code">
{React.string(value)}
</div>
</AddDataAttributes>
{React.string(`comparing to ${timeText}`)}
</div>
} else if value > 0. {
let text = "Increased by "
let value = value->Float.toString ++ "%"
<div className="whitespace-pre-line">
<AddDataAttributes attributes=[("data-text", text)]>
<div> {React.string(text)} </div>
</AddDataAttributes>
<AddDataAttributes attributes=[("data-numeric", value)]>
<div className="text-status-green text-base font-bold font-fira-code">
{React.string(value)}
</div>
</AddDataAttributes>
{React.string(`comparing to ${timeText}`)}
</div>
} else {
let text = "Changed by "
let value = value->Float.toString ++ "%"
<div className="whitespace-pre-line">
<AddDataAttributes attributes=[("data-text", text)]>
<div> {React.string(text)} </div>
</AddDataAttributes>
<AddDataAttributes attributes=[("data-numeric", value)]>
<div className="text-sankey_labels text-base font-bold font-fira-code">
{React.string(value)}
</div>
</AddDataAttributes>
{React.string(`comparing to ${timeText}`)}
</div>
}
} else {
{React.string("")}
}
<div className="p-2"> {tooltipComp} </div>
}
let sumOfArr = (arr: array<int>) => {
arr->Array.reduce(0, (acc, value) => acc + value)
}
let sumOfArrFloat = (arr: array<float>) => {
arr->Array.reduce(0., (acc, value) => acc +. value)
}
module NoDataFoundPage = {
@react.component
let make = () => {
let filterOnClick = () => {
let element = document->getElementsByClassName("showFilterButton")->Array.get(0)
switch element {
| Some(domElement) => {
let nodeElement = domElement.childNodes->Array.get(0)
switch nodeElement {
| Some(btnElement) => btnElement->DOMUtils.click()
| None => ()
}
}
| None => ()
}
}
let dateRangeOnClick = () => {
let element = document->getElementsByClassName("daterangSelection")->Array.get(0)
switch element {
| Some(domElement) => {
let nodeElement = domElement.childNodes->Array.get(0)
switch nodeElement {
| Some(ele) => {
let nodeElement = (ele->toNode).childNodes->Array.get(0)
switch nodeElement {
| Some(btnElement) => btnElement->DOMUtils.click()
| None => ()
}
}
| None => ()
}
}
| None => ()
}
}
<NoDataFound
renderType={LoadError}
message="Reduce the Range or narrow down the result by applying filter">
<div className="flex gap-4 mt-5 noDataFoundPage">
<Button text="Apply Filters" buttonType=Pagination onClick={_ => filterOnClick()} />
<Button text="Reduce DateRange" buttonType=Pagination onClick={_ => dateRangeOnClick()} />
</div>
</NoDataFound>
}
}
type analyticsSegmentDescription = {
title: string,
description: string,
}
type openingTab = NewTab | SameTab
module RedirectToOrderTableModal = {
type tableDetails = {
orderId: string,
merchantId: string,
timestamp: string,
error_message: string,
order_status: string,
}
type colType =
| OrderID
| MerchantID
| Timestamp
| Error_Message
| Order_Status
}
module NoDataFound = {
@react.component
let make = () => {
<div className="w-full flex flex-col items-center m-auto py-4">
<div className="font-normal mt-2"> {React.string("No Data Found")} </div>
<div className="text-gray-400 mt-2 max-w-[260px] text-center">
{React.string("We couldn’t fetch any data for this. Please refresh this page.")}
</div>
</div>
}
}
type getFilters = {
startTime: string,
endTime: string,
filterValueFromUrl?: JSON.t,
}
let filterMetrics = metrics => {
metrics->Array.filter(ele => {
let metricName = ele->getDictFromJsonObject->getString("name", "")
!String.includes(metricName, "sessionized") &&
metricName != "failure_reasons" &&
metricName != "payments_distribution"
})
}
| 5,831 | 9,748 |
hyperswitch-control-center | src/screens/Analytics/RefundsAnalytics/RefundsAnalyticsEntity.res | .res | open LogicUtils
open DynamicSingleStat
open AnalyticsTypes
open HSAnalyticsUtils
let domain = "refunds"
let colMapper = (col: refundColType) => {
switch col {
| SuccessRate => "refund_success_rate"
| Count => "refund_count"
| SuccessCount => "refund_success_count"
| ProcessedAmount => "refund_processed_amount"
| Connector => "connector"
| RefundMethod => "refund_method"
| Currency => "currency"
| Status => "refund_status"
| NoCol => ""
}
}
let tableItemToObjMapper: 'a => refundTableType = dict => {
{
refund_success_rate: dict->getFloat(SuccessRate->colMapper, 0.0),
refund_count: dict->getFloat(Count->colMapper, 0.0),
refund_success_count: dict->getFloat(SuccessCount->colMapper, 0.0),
refund_processed_amount: dict->getFloat(ProcessedAmount->colMapper, 0.0),
connector: dict->getString(Connector->colMapper, "NA")->snakeToTitle,
refund_method: dict->getString(RefundMethod->colMapper, "NA")->snakeToTitle,
currency: dict->getString(Currency->colMapper, "NA")->snakeToTitle,
refund_status: dict->getString(Status->colMapper, "NA")->snakeToTitle,
}
}
let getUpdatedHeading = (~item as _, ~dateObj as _) => {
let getHeading = colType => {
let key = colType->colMapper
switch colType {
| SuccessRate => Table.makeHeaderInfo(~key, ~title="Success Rate", ~dataType=NumericType)
| Count => Table.makeHeaderInfo(~key, ~title="Refund Count", ~dataType=NumericType)
| SuccessCount =>
Table.makeHeaderInfo(~key, ~title="Refund Success Count", ~dataType=NumericType)
| ProcessedAmount =>
Table.makeHeaderInfo(~key, ~title="Refund Processed Amount", ~dataType=NumericType)
| Connector => Table.makeHeaderInfo(~key, ~title="Connector", ~dataType=DropDown)
| Currency => Table.makeHeaderInfo(~key, ~title="Currency", ~dataType=DropDown)
| RefundMethod => Table.makeHeaderInfo(~key, ~title="RefundMethod", ~dataType=DropDown)
| Status => Table.makeHeaderInfo(~key, ~title="Status", ~dataType=DropDown)
| NoCol => Table.makeHeaderInfo(~key, ~title="")
}
}
getHeading
}
let getCell = (refundTable: refundTableType, colType: refundColType): Table.cell => {
let usaNumberAbbreviation = labelValue => {
shortNum(~labelValue, ~numberFormat=getDefaultNumberFormat())
}
let percentFormat = value => {
`${value->Float.toFixedWithPrecision(~digits=2)}%`
}
switch colType {
| SuccessRate => Numeric(refundTable.refund_success_rate, percentFormat)
| Count => Numeric(refundTable.refund_count, usaNumberAbbreviation)
| SuccessCount => Numeric(refundTable.refund_success_count, usaNumberAbbreviation)
| ProcessedAmount => Numeric(refundTable.refund_processed_amount /. 100.00, usaNumberAbbreviation)
| Connector => Text(refundTable.connector)
| RefundMethod => Text(refundTable.refund_method)
| Currency => Text(refundTable.currency)
| Status => Text(refundTable.refund_status)
| NoCol => Text("")
}
}
let getRefundTable: JSON.t => array<refundTableType> = json => {
json
->LogicUtils.getArrayFromJson([])
->Array.map(item => {
tableItemToObjMapper(item->getDictFromJsonObject)
})
}
let refundTableEntity = (~uri) =>
EntityType.makeEntity(
~uri,
~getObjects=getRefundTable,
~dataKey="queryData",
~defaultColumns=defaultRefundColumns,
~requiredSearchFieldsList=[startTimeFilterKey, endTimeFilterKey],
~allColumns=allRefundColumns,
~getCell,
~getHeading=getUpdatedHeading(~item=None, ~dateObj=None),
)
let singleStateInitialValue = {
refund_success_rate: 0.0,
refund_count: 0,
refund_success_count: 0,
refund_processed_amount: 0.0,
}
let singleStateSeriesInitialValue = {
refund_success_rate: 0.0,
refund_count: 0,
refund_success_count: 0,
time_series: "",
refund_processed_amount: 0.0,
}
let singleStateItemToObjMapper = json => {
json
->JSON.Decode.object
->Option.map(dict => {
refund_success_rate: dict->getFloat("refund_success_rate", 0.0),
refund_count: dict->getInt("refund_count", 0),
refund_success_count: dict->getInt("refund_success_count", 0),
refund_processed_amount: dict->getFloat("refund_processed_amount_in_usd", 0.0),
})
->Option.getOr({
singleStateInitialValue
})
}
let singleStateSeriesItemToObjMapper = json => {
json
->JSON.Decode.object
->Option.map(dict => {
refund_success_rate: dict->getFloat("refund_success_rate", 0.0)->setPrecision,
refund_count: dict->getInt("refund_count", 0),
refund_success_count: dict->getInt("refund_success_count", 0),
time_series: dict->getString("time_bucket", ""),
refund_processed_amount: dict->getFloat("refund_processed_amount", 0.0)->setPrecision,
})
->Option.getOr({
singleStateSeriesInitialValue
})
}
let itemToObjMapper = json => {
let refund_count = ref(0)
let refund_processed_amount = ref(0.0)
let refund_success_count = ref(0)
let refund_success_rate = ref(0.0)
let dataObj = json->getQueryData->Array.map(json => singleStateItemToObjMapper(json))
dataObj->Array.forEach(item => {
refund_count := refund_count.contents + item.refund_count
refund_processed_amount := refund_processed_amount.contents +. item.refund_processed_amount
refund_success_count := refund_success_count.contents + item.refund_success_count
refund_success_rate := refund_success_rate.contents +. item.refund_success_rate
})
[
{
refund_success_rate: refund_success_rate.contents,
refund_count: refund_count.contents,
refund_success_count: refund_success_count.contents,
refund_processed_amount: refund_processed_amount.contents,
},
]
}
let timeSeriesObjMapper = json =>
json->getQueryData->Array.map(json => singleStateSeriesItemToObjMapper(json))
type colT =
| SuccessRate
| Count
| SuccessCount
| ProcessedAmount
let defaultColumns: array<DynamicSingleStat.columns<colT>> = [
{
sectionName: "",
columns: [SuccessRate, Count, SuccessCount, ProcessedAmount]->generateDefaultStateColumns,
},
]
let compareLogic = (firstValue, secondValue) => {
let (temp1, _) = firstValue
let (temp2, _) = secondValue
if temp1 == temp2 {
0.
} else if temp1 > temp2 {
-1.
} else {
1.
}
}
let constructData = (key, singlestatTimeseriesData: array<refundsSingleStateSeries>) => {
switch key {
| "refund_success_rate" =>
singlestatTimeseriesData
->Array.map(ob => (
ob.time_series
->DateTimeUtils.parseAsFloat
->Js.Date.fromFloat
->DateTimeUtils.utcToISTDate
->Js.Date.valueOf,
ob.refund_success_rate,
))
->Array.toSorted(compareLogic)
| "refund_count" =>
singlestatTimeseriesData
->Array.map(ob => (
ob.time_series
->DateTimeUtils.parseAsFloat
->Js.Date.fromFloat
->DateTimeUtils.utcToISTDate
->Js.Date.valueOf,
ob.refund_count->Int.toFloat,
))
->Array.toSorted(compareLogic)
| "refund_success_count" =>
singlestatTimeseriesData
->Array.map(ob => (
ob.time_series
->DateTimeUtils.parseAsFloat
->Js.Date.fromFloat
->DateTimeUtils.utcToISTDate
->Js.Date.valueOf,
ob.refund_success_count->Int.toFloat,
))
->Array.toSorted(compareLogic)
| "refund_processed_amount" =>
singlestatTimeseriesData
->Array.map(ob => (
ob.time_series
->DateTimeUtils.parseAsFloat
->Js.Date.fromFloat
->DateTimeUtils.utcToISTDate
->Js.Date.valueOf,
ob.refund_processed_amount /. 100.00,
))
->Array.toSorted(compareLogic)
| _ => []
}
}
let getStatData = (
singleStatData: refundsSingleState,
timeSeriesData: array<refundsSingleStateSeries>,
deltaTimestampData: DynamicSingleStat.deltaRange,
colType,
_mode,
) => {
switch colType {
| SuccessRate => {
title: `${domain->LogicUtils.getFirstLetterCaps} Success Rate`,
tooltipText: "Successful refund over total refund initiated",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.refund_success_rate,
deltaTimestampData.currentSr,
),
value: singleStatData.refund_success_rate,
delta: {
Js.Float.fromString(
Float.toFixedWithPrecision(singleStatData.refund_success_rate, ~digits=2),
)
},
data: constructData("refund_success_rate", timeSeriesData),
statType: "Rate",
showDelta: false,
}
| Count => {
title: "Overall Refunds",
tooltipText: "Total refund initiated",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.refund_count->Int.toFloat,
deltaTimestampData.currentSr,
),
value: singleStatData.refund_count->Int.toFloat,
delta: {
Js.Float.fromString(
Float.toFixedWithPrecision(singleStatData.refund_count->Int.toFloat, ~digits=2),
)
},
data: constructData("refund_count", timeSeriesData),
statType: "Volume",
showDelta: false,
}
| SuccessCount => {
title: "Success Refunds",
tooltipText: "Total successful refunds",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.refund_success_count->Int.toFloat,
deltaTimestampData.currentSr,
),
value: singleStatData.refund_success_count->Int.toFloat,
delta: {
Js.Float.fromString(
Float.toFixedWithPrecision(singleStatData.refund_success_count->Int.toFloat, ~digits=2),
)
},
data: constructData("refund_success_count", timeSeriesData),
statType: "Volume",
showDelta: false,
}
| ProcessedAmount => {
title: `Processed Amount`,
tooltipText: `Total amount processed successfully`,
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.refund_processed_amount /. 100.00,
deltaTimestampData.currentSr,
),
value: singleStatData.refund_processed_amount /. 100.00,
delta: {
Js.Float.fromString(
Float.toFixedWithPrecision(singleStatData.refund_processed_amount /. 100.00, ~digits=2),
)
},
data: constructData("refund_processed_amount", timeSeriesData),
statType: "Amount",
showDelta: false,
}
}
}
let getStatSentiment = {
open AnalyticsUtils
[
("Success Refunds", Negative),
("Overall Refunds", Negative),
("Processed Amount", Negative),
]->Dict.fromArray
}
let getSingleStatEntity: ('a, string) => DynamicSingleStat.entityType<'colType, 't, 't2> = (
metrics,
uri,
) => {
urlConfig: [
{
uri,
metrics: metrics->getStringListFromArrayDict,
},
],
getObjects: itemToObjMapper,
getTimeSeriesObject: timeSeriesObjMapper,
defaultColumns,
getData: getStatData,
totalVolumeCol: None,
matrixUriMapper: _ => uri,
statSentiment: getStatSentiment,
}
let metricsConfig: array<LineChartUtils.metricsConfig> = [
{
metric_name_db: "refund_success_rate",
metric_label: "Success Rate",
metric_type: Rate,
thresholdVal: None,
step_up_threshold: None,
},
{
metric_name_db: "refund_count",
metric_label: "Volume",
metric_type: Volume,
thresholdVal: None,
step_up_threshold: None,
},
]
let chartEntity = (tabKeys, ~uri) =>
DynamicChart.makeEntity(
~uri=String(uri),
~filterKeys=tabKeys,
~dateFilterKeys=(startTimeFilterKey, endTimeFilterKey),
~currentMetrics=("refund_success_rate", "refund_count"), // 2nd metric will be static and we won't show the 2nd metric option to the first metric
~cardinality=[],
~granularity=[],
~chartTypes=[Line],
~uriConfig=[
{
uri,
timeSeriesBody: DynamicChart.getTimeSeriesChart,
legendBody: DynamicChart.getLegendBody,
metrics: metricsConfig,
timeCol: "time_bucket",
filterKeys: tabKeys,
},
],
~moduleName="Refunds Analytics",
)
| 3,009 | 9,749 |
hyperswitch-control-center | src/screens/Analytics/RefundsAnalytics/RefundsAnalytics.res | .res | open RefundsAnalyticsEntity
open APIUtils
open HSAnalyticsUtils
@react.component
let make = () => {
let getURL = useGetURL()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (metrics, setMetrics) = React.useState(_ => [])
let (dimensions, setDimensions) = React.useState(_ => [])
let fetchDetails = useGetMethod()
let updateDetails = useUpdateMethod()
let loadInfo = async () => {
open LogicUtils
try {
let infoUrl = getURL(~entityName=V1(ANALYTICS_REFUNDS), ~methodType=Get, ~id=Some(domain))
let infoDetails = await fetchDetails(infoUrl)
let metrics =
infoDetails
->getDictFromJsonObject
->getArrayFromDict("metrics", [])
->AnalyticsUtils.filterMetrics
setMetrics(_ => metrics)
setDimensions(_ => infoDetails->getDictFromJsonObject->getArrayFromDict("dimensions", []))
setScreenState(_ => PageLoaderWrapper.Success)
} catch {
| Exn.Error(e) => {
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
}
let getRefundDetails = async () => {
open LogicUtils
try {
setScreenState(_ => PageLoaderWrapper.Loading)
let refundUrl = getURL(~entityName=V1(REFUNDS), ~methodType=Post, ~id=Some("refund-post"))
let body = Dict.make()
body->Dict.set("limit", 100->Int.toFloat->JSON.Encode.float)
let refundDetails = await updateDetails(refundUrl, body->JSON.Encode.object, Post)
let data = refundDetails->getDictFromJsonObject->getArrayFromDict("data", [])
if data->Array.length < 1 {
setScreenState(_ => PageLoaderWrapper.Custom)
} else {
await loadInfo()
}
} catch {
| Exn.Error(e) =>
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
React.useEffect(() => {
getRefundDetails()->ignore
None
}, [])
let tabKeys = HSAnalyticsUtils.getStringListFromArrayDict(dimensions)
let tabValues = tabKeys->Array.mapWithIndex((key, index) => {
let a: DynamicTabs.tab = {
title: key->LogicUtils.snakeToTitle,
value: key,
isRemovable: index > 2,
}
a
})
let title = "Refunds Analytics"
let analyticsfilterUrl = getURL(
~entityName=V1(ANALYTICS_FILTERS),
~methodType=Post,
~id=Some(domain),
)
let refundAnalyticsUrl = getURL(
~entityName=V1(ANALYTICS_PAYMENTS),
~methodType=Post,
~id=Some(domain),
)
<PageLoaderWrapper screenState customUI={<NoData title />}>
<Analytics
pageTitle=title
filterUri=Some(analyticsfilterUrl)
key="RefundsAnalytics"
moduleName="Refunds"
deltaMetrics=["refund_success_rate", "refund_count", "refund_success_count"]
chartEntity={default: chartEntity(tabKeys, ~uri=refundAnalyticsUrl)}
tabKeys
tabValues
options={options}
singleStatEntity={getSingleStatEntity(metrics, refundAnalyticsUrl)}
getTable={getRefundTable}
colMapper
tableEntity={refundTableEntity(~uri=refundAnalyticsUrl)}
defaultSort="total_volume"
deltaArray=[]
tableUpdatedHeading=getUpdatedHeading
tableGlobalFilter={filterByData}
startTimeFilterKey={startTimeFilterKey}
endTimeFilterKey={endTimeFilterKey}
initialFilters={initialFilterFields}
initialFixedFilters={initialFixedFilterFields}
/>
</PageLoaderWrapper>
}
| 879 | 9,750 |
hyperswitch-control-center | src/screens/Analytics/PerformanceMonitor/PerformanceMonitor.res | .res | @react.component
let make = (~domain="payments") => {
open APIUtils
open LogicUtils
open HSAnalyticsUtils
open PerformanceMonitorEntity
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let fetchDetails = useGetMethod()
let defaultFilters = [startTimeFilterKey, endTimeFilterKey]
let {updateExistingKeys, filterValueJson} = React.useContext(FilterContext.filterContext)
let startTimeVal = filterValueJson->getString("startTime", "")
let endTimeVal = filterValueJson->getString("endTime", "")
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (dimensions, setDimensions) = React.useState(_ => []->dimensionObjMapper)
let setInitialFilters = HSwitchRemoteFilter.useSetInitialFilters(
~updateExistingKeys,
~startTimeFilterKey,
~endTimeFilterKey,
~origin="analytics",
(),
)
let {checkUserEntity, userInfo: {analyticsEntity}} = React.useContext(
UserInfoProvider.defaultContext,
)
let mixpanelEvent = MixpanelHook.useSendEvent()
let {updateAnalytcisEntity} = OMPSwitchHooks.useUserInfo()
let filterBody = (~groupBy) => {
let filterBodyEntity: AnalyticsUtils.filterBodyEntity = {
startTime: startTimeVal,
endTime: endTimeVal,
groupByNames: groupBy,
source: "BATCH",
}
AnalyticsUtils.filterBody(filterBodyEntity)
}
let fetchFilterData = async dimensions => {
try {
let groupBy = getStringListFromArrayDict(dimensions)
let filterUrl = getURL(~entityName=V1(ANALYTICS_FILTERS), ~methodType=Post, ~id=Some(domain))
let res = await updateDetails(filterUrl, filterBody(~groupBy)->JSON.Encode.object, Post)
let dim =
res
->getDictFromJsonObject
->getJsonObjectFromDict("queryData")
->getArrayFromJson([])
->dimensionObjMapper
setDimensions(_ => dim)
setScreenState(_ => PageLoaderWrapper.Success)
} catch {
| _ => ()
}
}
let loadInfo = async () => {
try {
setScreenState(_ => Loading)
let infoUrl = getURL(~entityName=V1(ANALYTICS_PAYMENTS), ~methodType=Get, ~id=Some(domain))
let infoDetails = await fetchDetails(infoUrl)
let dimensions = infoDetails->getDictFromJsonObject->getArrayFromDict("dimensions", [])
fetchFilterData(dimensions)->ignore
} catch {
| Exn.Error(e) =>
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
React.useEffect(() => {
setInitialFilters()
None
}, [])
let dateDropDownTriggerMixpanelCallback = () => {
mixpanelEvent(~eventName="performance_monitor_date_filter_opened")
}
React.useEffect(() => {
if startTimeVal->LogicUtils.isNonEmptyString && endTimeVal->LogicUtils.isNonEmptyString {
mixpanelEvent(~eventName="performance_monitor_date_filter")
loadInfo()->ignore
}
None
}, (startTimeVal, endTimeVal))
let topFilterUi =
<div className="flex flex-row">
<DynamicFilter
initialFilters=[]
options=[]
popupFilterFields=[]
initialFixedFilters={initialFixedFilterFields(
Dict.make()->JSON.Encode.object,
~events=dateDropDownTriggerMixpanelCallback,
)}
defaultFilterKeys=defaultFilters
tabNames=[]
key="1"
updateUrlWith=updateExistingKeys
filterFieldsPortalName={HSAnalyticsUtils.filterFieldsPortalName}
showCustomFilter=false
refreshFilters=false
/>
</div>
<PageLoaderWrapper screenState>
<div className="flex flex-col gap-5">
<div className="flex items-center justify-between ">
<PageUtils.PageHeading title="Performance Monitor" subTitle="" />
<div className="mr-5">
<OMPSwitchHelper.OMPViews
views={OMPSwitchUtils.analyticsViewList(~checkUserEntity)}
selectedEntity={analyticsEntity}
onChange={updateAnalytcisEntity}
entityMapper=UserInfoUtils.analyticsEntityMapper
/>
</div>
</div>
<div
className="-ml-1 sticky top-0 z-30 p-1 bg-hyperswitch_background py-3 -mt-3 rounded-lg border">
topFilterUi
</div>
<div className="flex flex-col gap-3">
<div className="grid grid-cols-4 grid-rows-1 gap-3">
<div className="flex flex-col gap-3">
<GaugeChartPerformance
startTimeVal endTimeVal entity={getSuccessRatePerformanceEntity}
/>
<GaugeFailureRate
startTimeVal
endTimeVal
entity1={overallPaymentCount}
entity2={getFailureRateEntity}
dimensions
/>
</div>
<div className="col-span-3">
<BarChartPerformance
domain startTimeVal endTimeVal dimensions entity={getStatusPerformanceEntity}
/>
</div>
</div>
<div className="grid grid-cols-2 grid-rows-1 gap-3">
<BarChartPerformance
domain
startTimeVal
endTimeVal
dimensions
entity={getPerformanceEntity(
~filters=[#payment_method],
~groupBy=[#payment_method],
~groupByKeys=[#payment_method],
~title="Payment Distribution By Payment Method",
)}
/>
<BarChartPerformance
domain
startTimeVal
endTimeVal
dimensions
entity={getPerformanceEntity(
~filters=[#connector],
~groupBy=[#connector],
~groupByKeys=[#connector],
~title="Payment Distribution By Connector",
)}
/>
</div>
<TablePerformance
startTimeVal endTimeVal entity={getFailureEntity} getTableData visibleColumns tableEntity
/>
<div className="grid grid-cols-2 grid-rows-1 gap-3">
<PieChartPerformance
domain startTimeVal endTimeVal dimensions entity={getConnectorFailureEntity}
/>
<PieChartPerformance
domain startTimeVal endTimeVal dimensions entity={getPaymentMethodFailureEntity}
/>
</div>
<div className="grid grid-cols-2 grid-rows-1 gap-3">
<PieChartPerformance
domain
startTimeVal
endTimeVal
dimensions
entity={getConnectorPaymentMethodFailureEntity}
/>
</div>
</div>
</div>
</PageLoaderWrapper>
}
| 1,455 | 9,751 |
hyperswitch-control-center | src/screens/Analytics/PerformanceMonitor/PerformanceMonitorTypes.res | .res | type performance = [#ConnectorPerformance | #PaymentMethodPerormance]
type dimension = [#connector | #payment_method | #payment_method_type | #status | #no_value]
type status = [#charged | #failure | #payment_method_awaited]
type metrics = [#payment_count | #connector_success_rate]
type distribution = [#payment_error_message | #TOP_5]
type paymentDistribution = {
payment_count: int,
status: string,
connector?: string,
payment_method?: string,
}
type dimensionRecord = {
dimension: dimension,
values: array<string>,
}
type dimensions = array<dimensionRecord>
type stackBarSeriesRecord = {
name: string,
data: array<int>,
color: string,
}
type categories = array<string>
type series = array<stackBarSeriesRecord>
type yAxis = {text: string}
type xAxis = {text: string}
type title = {text: string}
type colors = array<string>
type donutPieSeriesRecord = {
name: string,
y: int,
}
type stackBarChartData = {
categories: categories,
series: series,
}
type gaugeData = {value: float}
type donutChatData = {series: series}
type chartDataConfig = {
groupByKeys: array<dimension>,
plotChartBy?: array<status>,
yLabels?: array<string>,
name?: metrics,
}
type distributionType = {
distributionFor: string,
distributionCardinality: string,
}
type requestBodyConfig = {
metrics: array<metrics>,
delta?: bool,
groupBy?: array<dimension>,
filters?: array<dimension>,
customFilter?: dimension,
applyFilterFor?: array<status>,
excludeFilterValue?: array<status>,
distribution?: distributionType,
}
type args<'t1> = {
array: array<JSON.t>,
config: chartDataConfig,
optionalArgs?: 't1,
}
type entity<'t, 't1> = {
requestBodyConfig: requestBodyConfig,
configRequiredForChartData: chartDataConfig,
getChartData: (~args: args<'t1>) => 't,
title: string,
getChartOption: 't => JSON.t,
}
| 468 | 9,752 |
hyperswitch-control-center | src/screens/Analytics/PerformanceMonitor/PerformanceUtils.res | .res | open PerformanceMonitorTypes
open LogicUtils
let paymentDistributionInitialValue = {
payment_count: 0,
status: "",
connector: "",
payment_method: "",
}
let distributionObjMapper = dict => {
{
payment_count: dict->getDictFromJsonObject->getInt("payment_count", 0),
status: dict->getDictFromJsonObject->getString("status", ""),
connector: dict->getDictFromJsonObject->getString("connector", ""),
payment_method: dict->getDictFromJsonObject->getString("payment_method", ""),
}
}
let paymentDistributionObjMapper = json => {
json
->getDictFromJsonObject
->getArrayFromDict("queryData", [])
->Array.map(dict => dict->distributionObjMapper)
}
let defaultDimesions = {
dimension: #no_value,
values: [],
}
let getSpecificDimension = (dimensions: dimensions, dimension: dimension) => {
dimensions
->Array.filter(ele => ele.dimension == dimension)
->Array.at(0)
->Option.getOr(defaultDimesions)
}
let getGroupByForPerformance = (~dimensions: array<dimension>) => {
dimensions->Array.map(v => (v: dimension :> string))
}
let getMetricForPerformance = (~metrics: array<metrics>) =>
metrics->Array.map(v => (v: metrics :> string))
let getFilterForPerformance = (
~dimensions: dimensions,
~filters: option<array<dimension>>,
~custom: option<dimension>=None,
~customValue: option<array<status>>=None,
~excludeFilterValue: option<array<status>>=None,
) => {
let filtersDict = Dict.make()
let customFilter = custom->Option.getOr(#no_value)
switch filters {
| Some(val) => {
val->Array.forEach(filter => {
let data = if filter == customFilter {
customValue->Option.getOr([])->Array.map(v => (v: status :> string))
} else {
getSpecificDimension(dimensions, filter).values
}
let updatedFilters = switch excludeFilterValue {
| Some(excludeValues) =>
data->Array.filter(item => {
!(excludeValues->Array.map(v => (v: status :> string))->Array.includes(item))
})
| None => data
}->Array.map(str => str->JSON.Encode.string)
filtersDict->Dict.set((filter: dimension :> string), updatedFilters->JSON.Encode.array)
})
filtersDict->JSON.Encode.object->Some
}
| None => None
}
}
let getTimeRange = (startTime, endTime) => {
[
("startTime", startTime->JSON.Encode.string),
("endTimeVal", endTime->JSON.Encode.string),
]->getJsonFromArrayOfJson
}
let requestBody = (
~dimensions: dimensions,
~startTime: string,
~endTime: string,
~metrics: array<metrics>,
~groupBy: option<array<dimension>>=None,
~filters: option<array<dimension>>=[]->Some,
~customFilter: option<dimension>=None,
~excludeFilterValue: option<array<status>>=None,
~applyFilterFor: option<array<status>>=None,
~distribution: option<distributionType>=None,
~delta: option<bool>=None,
) => {
let metrics = getMetricForPerformance(~metrics)
let filter = getFilterForPerformance(
~dimensions,
~filters,
~custom=customFilter,
~customValue=applyFilterFor,
~excludeFilterValue,
)
let groupByNames = switch groupBy {
| Some(vals) => getGroupByForPerformance(~dimensions=vals)->Some
| None => None
}
let distributionValues = distribution->Identity.genericTypeToJson->Some
[
AnalyticsUtils.getFilterRequestBody(
~metrics=Some(metrics),
~delta=delta->Option.getOr(false),
~distributionValues,
~groupByNames,
~filter,
~startDateTime=startTime,
~endDateTime=endTime,
)->JSON.Encode.object,
]->JSON.Encode.array
}
let getGroupByKey = (dict, keys: array<dimension>) => {
let key =
keys
->Array.map(key => {
dict->getDictFromJsonObject->getString((key: dimension :> string), "")
})
->Array.joinWith(":")
key
}
let getGroupByDataForStatusAndPaymentCount = (array, keys: array<dimension>) => {
let result = Dict.make()
array->Array.forEach(entry => {
let key = getGroupByKey(entry, keys)
let connectorResult = Dict.get(result, key)
switch connectorResult {
| None => {
let newConnectorResult = Dict.make()
let st = entry->getDictFromJsonObject->getString("status", "")
let pc = entry->getDictFromJsonObject->getInt("payment_count", 0)
Dict.set(result, key, newConnectorResult)
Dict.set(newConnectorResult, st, pc)
}
| Some(connectorResult) => {
let st = entry->getDictFromJsonObject->getString("status", "")
let pc = entry->getDictFromJsonObject->getInt("payment_count", 0)
let currentCount = Dict.get(connectorResult, st)->Belt.Option.getWithDefault(0)
Dict.set(connectorResult, st, currentCount + pc)
}
}
})
result
}
module Card = {
@react.component
let make = (~title, ~children) => {
<div
className={`h-full flex flex-col justify-between border rounded-lg dark:border-jp-gray-850 bg-white dark:bg-jp-gray-lightgray_background overflow-hidden singlestatBox px-7 py-5`}>
<div className={"flex gap-2 items-center text-jp-gray-700 font-bold self-start mb-5"}>
<div className="font-semibold text-base text-black dark:text-white">
{title->React.string}
</div>
</div>
{children}
</div>
}
}
let customUI = (title, ~height="h-96") =>
<Card title>
<div
className={`w-full ${height} border-2 flex justify-center items-center border-dashed opacity-70 rounded-lg p-5`}>
{"No Data"->React.string}
</div>
</Card>
| 1,387 | 9,753 |
hyperswitch-control-center | src/screens/Analytics/PerformanceMonitor/PerformanceMonitorEntity.res | .res | open PerformanceMonitorTypes
open LogicUtils
let getDimensionNameFromString = dimension => {
switch dimension {
| "connector" => #connector
| "payment_method" => #payment_method
| "payment_method_type" => #payment_method_type
| "status" => #status
| _ => #no_value
}
}
let dimensionMapper = dict => {
dimension: dict->getString("dimension", "")->getDimensionNameFromString,
values: dict->getStrArray("values"),
}
let dimensionObjMapper = (dimensions: array<JSON.t>) => {
dimensions->JSON.Encode.array->getArrayDataFromJson(dimensionMapper)
}
let defaultDimesions = {
dimension: #no_value,
values: [],
}
let getSuccessRatePerformanceEntity: entity<gaugeData, option<string>> = {
getChartData: GaugeChartPerformanceUtils.getGaugeData,
requestBodyConfig: {
delta: true,
metrics: [#connector_success_rate],
},
configRequiredForChartData: {
groupByKeys: [],
name: #connector_success_rate,
},
title: "Payment Success Rate",
getChartOption: GaugeChartPerformanceUtils.gaugeOption,
}
let overallPaymentCount: entity<gaugeData, option<string>> = {
getChartData: GaugeChartPerformanceUtils.getGaugeData,
requestBodyConfig: {
delta: true,
metrics: [#payment_count],
filters: [#status],
excludeFilterValue: [#payment_method_awaited],
},
configRequiredForChartData: {
groupByKeys: [],
name: #payment_count,
},
title: "Overall Payment Count",
getChartOption: GaugeFailureRateUtils.falureGaugeOption,
}
let getFailureRateEntity: entity<gaugeData, float> = {
getChartData: GaugeFailureRateUtils.getFailureRateData,
requestBodyConfig: {
metrics: [#payment_count],
filters: [#status],
customFilter: #status,
applyFilterFor: [#failure],
},
configRequiredForChartData: {
groupByKeys: [],
name: #payment_count,
},
title: "Payments Failure Rate",
getChartOption: GaugeFailureRateUtils.falureGaugeOption,
}
let getStatusPerformanceEntity: entity<stackBarChartData, option<string>> = {
requestBodyConfig: {
metrics: [#payment_count],
groupBy: [#status],
filters: [#status],
excludeFilterValue: [#payment_method_awaited],
},
configRequiredForChartData: {
groupByKeys: [#status],
yLabels: ["Status"],
},
getChartData: BarChartPerformanceUtils.getStackedBarData,
title: "Payment Distribution By Status",
getChartOption: BarChartPerformanceUtils.getBarOption,
}
let getPerformanceEntity = (
~groupBy: array<dimension>,
~filters: array<dimension>,
~groupByKeys: array<dimension>,
~title: string,
): entity<stackBarChartData, option<string>> => {
requestBodyConfig: {
metrics: [#payment_count],
groupBy: [#status, ...groupBy],
filters: [#status, ...filters],
customFilter: #status,
applyFilterFor: [#failure, #charged],
},
configRequiredForChartData: {
groupByKeys: [...groupByKeys],
plotChartBy: [#failure, #charged],
},
getChartData: BarChartPerformanceUtils.getStackedBarData,
title,
getChartOption: BarChartPerformanceUtils.getBarOption,
}
let getConnectorFailureEntity: entity<array<donutPieSeriesRecord>, option<string>> = {
requestBodyConfig: {
metrics: [#payment_count],
groupBy: [#connector, #status],
filters: [#connector, #status],
customFilter: #status,
applyFilterFor: [#failure],
},
configRequiredForChartData: {
groupByKeys: [#connector],
},
getChartData: PieChartPerformanceUtils.getDonutCharData,
title: "Connector Wise Payment Failure",
getChartOption: PieChartPerformanceUtils.getPieChartOptions,
}
let getPaymentMethodFailureEntity: entity<array<donutPieSeriesRecord>, option<string>> = {
requestBodyConfig: {
metrics: [#payment_count],
groupBy: [#payment_method, #status],
filters: [#payment_method, #status],
customFilter: #status,
applyFilterFor: [#failure],
},
configRequiredForChartData: {
groupByKeys: [#payment_method],
},
getChartData: PieChartPerformanceUtils.getDonutCharData,
title: "Method Wise Payment Failure",
getChartOption: PieChartPerformanceUtils.getPieChartOptions,
}
let getConnectorPaymentMethodFailureEntity: entity<array<donutPieSeriesRecord>, option<string>> = {
requestBodyConfig: {
metrics: [#payment_count],
groupBy: [#connector, #payment_method, #status],
filters: [#connector, #payment_method, #status],
customFilter: #status,
applyFilterFor: [#failure],
},
configRequiredForChartData: {
groupByKeys: [#connector, #payment_method],
},
getChartData: PieChartPerformanceUtils.getDonutCharData,
title: "Connector + Payment Method Wise Payment Failure",
getChartOption: PieChartPerformanceUtils.getPieChartOptions,
}
type errorObject = {
reason: string,
count: int,
connector: string,
}
type cols =
| ErrorReason
| Count
| Connector
let visibleColumns = [Connector, ErrorReason, Count]
let colMapper = (col: cols) => {
switch col {
| ErrorReason => "reason"
| Count => "count"
| Connector => "connector"
}
}
let getTableData = (array: array<JSON.t>) => {
let data = []
array->Array.forEach(item => {
let valueDict = item->getDictFromJsonObject
let connector = valueDict->getString((#connector: dimension :> string), "")
let paymentErrorMessage =
valueDict->getArrayFromDict((#payment_error_message: distribution :> string), [])
if connector->isNonEmptyString && paymentErrorMessage->Array.length > 0 {
paymentErrorMessage->Array.forEach(value => {
let errorDict = value->getDictFromJsonObject
let obj = {
reason: errorDict->getString(ErrorReason->colMapper, ""),
count: errorDict->getInt(Count->colMapper, 0),
connector,
}
data->Array.push(obj)
})
}
})
data->Array.sort((a, b) => {
let rowValue_a = a.count
let rowValue_b = b.count
rowValue_a <= rowValue_b ? 1. : -1.
})
data
}
let tableItemToObjMapper: 'a => errorObject = dict => {
{
reason: dict->getString(ErrorReason->colMapper, "NA"),
count: dict->getInt(Count->colMapper, 0),
connector: dict->getString(Connector->colMapper, "NA"),
}
}
let getObjects: JSON.t => array<errorObject> = json => {
json
->LogicUtils.getArrayFromJson([])
->Array.map(item => {
tableItemToObjMapper(item->getDictFromJsonObject)
})
}
let getHeading = colType => {
let key = colType->colMapper
switch colType {
| ErrorReason => Table.makeHeaderInfo(~key, ~title="Error Reason", ~dataType=TextType)
| Count => Table.makeHeaderInfo(~key, ~title="Total Occurences", ~dataType=TextType)
| Connector => Table.makeHeaderInfo(~key, ~title="Connector", ~dataType=TextType)
}
}
let getCell = (errorObj, colType): Table.cell => {
switch colType {
| ErrorReason => Text(errorObj.reason)
| Count => Text(errorObj.count->Int.toString)
| Connector => Text(errorObj.connector)
}
}
let tableEntity = EntityType.makeEntity(
~uri=``,
~getObjects,
~dataKey="queryData",
~defaultColumns=visibleColumns,
~requiredSearchFieldsList=[],
~allColumns=visibleColumns,
~getCell,
~getHeading,
)
let getFailureEntity: entity<array<errorObject>, option<string>> = {
getChartOption: _ => Dict.make()->JSON.Encode.object,
getChartData: (~args as _) => [],
requestBodyConfig: {
metrics: [#connector_success_rate],
groupBy: [#connector],
distribution: {
distributionFor: (#payment_error_message: distribution :> string),
distributionCardinality: (#TOP_5: distribution :> string),
},
},
configRequiredForChartData: {
groupByKeys: [#connector],
},
title: "Payment Failures",
}
| 1,915 | 9,754 |
hyperswitch-control-center | src/screens/Analytics/PerformanceMonitor/TablePerformance/TablePerformance.res | .res | let tableBorderClass = "border-collapse border border-jp-gray-940 border-opacity-30 dark:border-jp-gray-dark_table_border_color dark:border-opacity-30"
@react.component
let make = (
~startTimeVal,
~endTimeVal,
~entity: PerformanceMonitorTypes.entity<'t, 't1>,
~domain="payments",
~getTableData,
~visibleColumns,
~tableEntity,
) => {
open APIUtils
open LogicUtils
open PerformanceMonitorTypes
let getURL = useGetURL()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let updateDetails = useUpdateMethod()
let (offset, setOffset) = React.useState(_ => 0)
let (tableData, setTableData) = React.useState(_ => [])
let defaultSort: Table.sortedObject = {
key: "",
order: Table.INC,
}
let chartFetch = async () => {
try {
let url = getURL(~entityName=V1(ANALYTICS_PAYMENTS), ~methodType=Post, ~id=Some(domain))
let body = PerformanceUtils.requestBody(
~dimensions=[],
~excludeFilterValue=entity.requestBodyConfig.excludeFilterValue,
~startTime=startTimeVal,
~endTime=endTimeVal,
~filters=entity.requestBodyConfig.filters,
~metrics=entity.requestBodyConfig.metrics,
~groupBy=entity.requestBodyConfig.groupBy,
~customFilter=entity.requestBodyConfig.customFilter,
~applyFilterFor=entity.requestBodyConfig.applyFilterFor,
~distribution=entity.requestBodyConfig.distribution,
)
let res = await updateDetails(url, body, Post)
let arr =
res
->getDictFromJsonObject
->getArrayFromDict("queryData", [])
let items = getTableData(arr)
let tableData = if items->Array.length > 0 {
items->Array.map(Nullable.make)
} else {
[]
}
setTableData(_ => tableData)
if arr->Array.length > 0 {
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Custom)
}
}
React.useEffect(() => {
if startTimeVal->LogicUtils.isNonEmptyString && endTimeVal->LogicUtils.isNonEmptyString {
chartFetch()->ignore
}
None
}, [])
<PageLoaderWrapper
screenState
customLoader={<Shimmer styleClass="w-full h-96" />}
customUI={PerformanceUtils.customUI(entity.title)}>
<PerformanceUtils.Card title="Payment Failures">
<LoadedTable
visibleColumns
title="Performance Monitor"
hideTitle=true
actualData={tableData}
entity=tableEntity
resultsPerPage=5
totalResults={tableData->Array.length}
offset
setOffset
defaultSort
currrentFetchCount={tableData->Array.length}
tableLocalFilter=false
tableheadingClass=tableBorderClass
ignoreHeaderBg=true
tableDataBorderClass=tableBorderClass
isAnalyticsModule=true
/>
</PerformanceUtils.Card>
</PageLoaderWrapper>
}
| 720 | 9,755 |
hyperswitch-control-center | src/screens/Analytics/PerformanceMonitor/TablePerformance/TablePerformanceUtils.res | .res | 1 | 9,756 | |
hyperswitch-control-center | src/screens/Analytics/PerformanceMonitor/GaugeChart/GaugeChartPerformance.res | .res | @react.component
let make = (
~startTimeVal,
~endTimeVal,
~entity: PerformanceMonitorTypes.entity<'t, 't1>,
~domain="payments",
) => {
open APIUtils
open LogicUtils
open Highcharts
let getURL = useGetURL()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let updateDetails = useUpdateMethod()
let (gaugeOption, setGaugeOptions) = React.useState(_ => JSON.Encode.null)
let _ = bubbleChartModule(highchartsModule)
let chartFetch = async () => {
try {
let url = getURL(~entityName=V1(ANALYTICS_PAYMENTS), ~methodType=Post, ~id=Some(domain))
let body = PerformanceUtils.requestBody(
~dimensions=[],
~excludeFilterValue=entity.requestBodyConfig.excludeFilterValue,
~startTime=startTimeVal,
~endTime=endTimeVal,
~delta=entity.requestBodyConfig.delta,
~filters=entity.requestBodyConfig.filters,
~metrics=entity.requestBodyConfig.metrics,
~groupBy=entity.requestBodyConfig.groupBy,
~customFilter=entity.requestBodyConfig.customFilter,
~applyFilterFor=entity.requestBodyConfig.applyFilterFor,
)
let res = await updateDetails(url, body, Post)
let arr =
res
->getDictFromJsonObject
->getArrayFromDict("queryData", [])
if arr->Array.length > 0 {
let configData = entity.getChartData(
~args={array: arr, config: entity.configRequiredForChartData},
)
let options = entity.getChartOption(configData)
setGaugeOptions(_ => options)
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Custom)
}
}
React.useEffect(() => {
if startTimeVal->LogicUtils.isNonEmptyString && endTimeVal->LogicUtils.isNonEmptyString {
chartFetch()->ignore
}
None
}, [])
<PageLoaderWrapper
screenState
customLoader={<Shimmer styleClass="w-full h-40" />}
customUI={PerformanceUtils.customUI(entity.title, ~height="h-40")}>
<PerformanceUtils.Card title=entity.title>
<Chart options={gaugeOption} highcharts />
</PerformanceUtils.Card>
</PageLoaderWrapper>
}
| 549 | 9,757 |
hyperswitch-control-center | src/screens/Analytics/PerformanceMonitor/GaugeChart/GaugeChartPerformanceUtils.res | .res | open PerformanceMonitorTypes
let getGaugeData = (~args) => {
let {array, config} = args
let key = switch config.name {
| Some(val) => (val: metrics :> string)
| _ => ""
}
let value = switch array->Array.get(0) {
| Some(val) => {
let rate =
val
->JSON.Decode.object
->Option.getOr(Dict.make())
->Dict.get(key)
->Option.getOr(0.0->JSON.Encode.float)
->JSON.Decode.float
->Option.getOr(0.0)
rate
}
| None => 0.0
}
{
value: value,
}
}
let gaugeOption = (data: gaugeData) =>
{
"chart": {
"type": "gauge",
"plotBackgroundColor": null,
"plotBackgroundImage": null,
"plotBorderWidth": 0,
"plotShadow": false,
"height": "75%",
},
"pane": {
"startAngle": -90,
"endAngle": 89.9,
"background": null,
"center": ["50%", "75%"],
"size": "110%",
},
"yAxis": {
"min": 0,
"max": 100,
"tickPixelInterval": 72,
"tickPosition": "inside",
"tickColor": "#FFFFFF",
"tickLength": 20,
"tickWidth": 2,
"minorTickInterval": null,
"labels": {
"distance": 20,
"style": {
"fontSize": "14px",
},
},
"lineWidth": 0,
"plotBands": [
{
"from": 0,
"to": 50,
"color": "#DA6C68", // red
"thickness": 20,
"borderRadius": "50%",
},
{
"from": 50,
"to": 75,
"color": "#E3945C", // yellow
"thickness": 20,
"borderRadius": "50%",
},
{
"from": 75,
"to": 100,
"color": "#7AAF73", // green
"thickness": 20,
"borderRadius": "50%",
},
],
},
"title": {
"text": "",
},
"credits": {
"enabled": false,
},
"series": [
{
"name": "",
"data": [
data.value
->Float.toFixedWithPrecision(~digits=2)
->Float.fromString
->Option.getOr(0.0),
],
"tooltip": {
"valueSuffix": "%",
},
"dial": {
"radius": "80%",
"backgroundColor": "gray",
"baseWidth": 12,
"baseLength": "0%",
"rearLength": "0%",
},
"pivot": {
"backgroundColor": "gray",
"radius": 6,
},
"dataLabels": {
"format": `{y} %`,
"borderWidth": 0,
"style": {
"fontSize": "18px",
},
},
},
],
}->Identity.genericObjectOrRecordToJson
| 769 | 9,758 |
hyperswitch-control-center | src/screens/Analytics/PerformanceMonitor/GaugeChart/CustomGraphs/GaugeFailureRateUtils.res | .res | open PerformanceMonitorTypes
let getFailureRateData = (~args) => {
let count = args.optionalArgs->Option.getOr(0.0)
let failureCount = GaugeChartPerformanceUtils.getGaugeData(~args).value
let rate = failureCount /. count *. 100.0
let value: PerformanceMonitorTypes.gaugeData = {value: rate}
value
}
let falureGaugeOption = (data: gaugeData) =>
{
"chart": {
"type": "gauge",
"plotBackgroundColor": null,
"plotBackgroundImage": null,
"plotBorderWidth": 0,
"plotShadow": false,
"height": "75%",
},
"pane": {
"startAngle": -90,
"endAngle": 89.9,
"background": null,
"center": ["50%", "75%"],
"size": "110%",
},
"yAxis": {
"min": 0,
"max": 100,
"tickPixelInterval": 72,
"tickPosition": "inside",
"tickColor": "#FFFFFF",
"tickLength": 20,
"tickWidth": 2,
"minorTickInterval": null,
"labels": {
"distance": 20,
"style": {
"fontSize": "14px",
},
},
"lineWidth": 0,
"plotBands": [
{
"from": 0,
"to": 25,
"color": "#7AAF73", // red
"thickness": 20,
"borderRadius": "50%",
},
{
"from": 25,
"to": 50,
"color": "#E3945C", // yellow
"thickness": 20,
"borderRadius": "50%",
},
{
"from": 50,
"to": 100,
"color": "#DA6C68", // green
"thickness": 20,
"borderRadius": "50%",
},
],
},
"title": {
"text": "",
},
"credits": {
"enabled": false,
},
"series": [
{
"name": "",
"data": [
data.value
->Float.toFixedWithPrecision(~digits=2)
->Float.fromString
->Option.getOr(0.0),
],
"tooltip": {
"valueSuffix": "%",
},
"dial": {
"radius": "80%",
"backgroundColor": "gray",
"baseWidth": 12,
"baseLength": "0%",
"rearLength": "0%",
},
"pivot": {
"backgroundColor": "gray",
"radius": 6,
},
"dataLabels": {
"format": `{y} %`,
"borderWidth": 0,
"style": {
"fontSize": "18px",
},
},
},
],
}->Identity.genericObjectOrRecordToJson
| 699 | 9,759 |
hyperswitch-control-center | src/screens/Analytics/PerformanceMonitor/GaugeChart/CustomGraphs/GaugeFailureRate.res | .res | @react.component
let make = (
~startTimeVal,
~endTimeVal,
~entity1: PerformanceMonitorTypes.entity<PerformanceMonitorTypes.gaugeData, 't1>,
~entity2: PerformanceMonitorTypes.entity<PerformanceMonitorTypes.gaugeData, float>,
~domain="payments",
~dimensions,
) => {
open APIUtils
open LogicUtils
open Highcharts
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let (gaugeOption, setGaugeOptions) = React.useState(_ => JSON.Encode.null)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let fetchExactData = async overallData => {
try {
let url = getURL(~entityName=V1(ANALYTICS_PAYMENTS), ~methodType=Post, ~id=Some(domain))
let body = PerformanceUtils.requestBody(
~dimensions,
~startTime=startTimeVal,
~endTime=endTimeVal,
~delta=entity2.requestBodyConfig.delta,
~filters=entity2.requestBodyConfig.filters,
~metrics=entity2.requestBodyConfig.metrics,
~customFilter=entity2.requestBodyConfig.customFilter,
~applyFilterFor=entity2.requestBodyConfig.applyFilterFor,
)
let res = await updateDetails(url, body, Post)
let arr =
res
->getDictFromJsonObject
->getArrayFromDict("queryData", [])
if arr->Array.length > 0 && overallData > 0.0 {
let value = entity2.getChartData(
~args={
array: arr,
config: entity2.configRequiredForChartData,
optionalArgs: overallData,
},
)
let options = entity2.getChartOption(value)
setGaugeOptions(_ => options)
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Custom)
}
}
let fetchOverallData = async () => {
try {
let url = getURL(~entityName=V1(ANALYTICS_PAYMENTS), ~methodType=Post, ~id=Some(domain))
let body = PerformanceUtils.requestBody(
~dimensions,
~startTime=startTimeVal,
~endTime=endTimeVal,
~delta=entity1.requestBodyConfig.delta,
~metrics=entity1.requestBodyConfig.metrics,
~filters=entity1.requestBodyConfig.filters,
~applyFilterFor=entity1.requestBodyConfig.applyFilterFor,
~customFilter=entity1.requestBodyConfig.customFilter,
~excludeFilterValue=entity1.requestBodyConfig.excludeFilterValue,
)
let res = await updateDetails(url, body, Post)
let arr =
res
->getDictFromJsonObject
->getArrayFromDict("queryData", [])
if arr->Array.length > 0 {
let overallData = entity1.getChartData(
~args={array: arr, config: entity1.configRequiredForChartData},
).value
fetchExactData(overallData)->ignore
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Custom)
}
}
React.useEffect(() => {
if startTimeVal->LogicUtils.isNonEmptyString && endTimeVal->LogicUtils.isNonEmptyString {
fetchOverallData()->ignore
}
None
}, [])
<PageLoaderWrapper
screenState
customLoader={<Shimmer styleClass="w-full h-40" />}
customUI={PerformanceUtils.customUI(entity2.title, ~height="h-40")}>
<PerformanceUtils.Card title=entity2.title>
<Chart options={gaugeOption} highcharts />
</PerformanceUtils.Card>
</PageLoaderWrapper>
}
| 847 | 9,760 |
hyperswitch-control-center | src/screens/Analytics/PerformanceMonitor/BarChartPerformance/BarChartPerformance.res | .res | @react.component
let make = (
~domain,
~startTimeVal,
~endTimeVal,
~dimensions,
~entity: PerformanceMonitorTypes.entity<'t, 't1>,
) => {
open APIUtils
open LogicUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let (barOption, setBarOptions) = React.useState(_ => JSON.Encode.null)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let chartFetch = async () => {
try {
let metricsUrl = getURL(
~entityName=V1(ANALYTICS_PAYMENTS),
~methodType=Post,
~id=Some(domain),
)
let body = PerformanceUtils.requestBody(
~dimensions,
~startTime=startTimeVal,
~excludeFilterValue=entity.requestBodyConfig.excludeFilterValue,
~endTime=endTimeVal,
~filters=entity.requestBodyConfig.filters,
~metrics=entity.requestBodyConfig.metrics,
~groupBy=entity.requestBodyConfig.groupBy,
~customFilter=entity.requestBodyConfig.customFilter,
~applyFilterFor=entity.requestBodyConfig.applyFilterFor,
)
let res = await updateDetails(metricsUrl, body, Post)
let arr =
res
->getDictFromJsonObject
->getArrayFromDict("queryData", [])
if arr->Array.length > 0 {
let configData = entity.getChartData(
~args={array: arr, config: entity.configRequiredForChartData},
)
let options = entity.getChartOption(configData)
setBarOptions(_ => options)
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Custom)
}
}
React.useEffect(() => {
if startTimeVal->LogicUtils.isNonEmptyString && endTimeVal->LogicUtils.isNonEmptyString {
chartFetch()->ignore
}
None
}, [dimensions])
<PageLoaderWrapper
screenState
customLoader={<Shimmer styleClass="w-full h-96" />}
customUI={PerformanceUtils.customUI(entity.title)}>
<PerformanceUtils.Card title=entity.title>
<HighchartBarChart.RawBarChart options={barOption} />
</PerformanceUtils.Card>
</PageLoaderWrapper>
}
| 525 | 9,761 |
hyperswitch-control-center | src/screens/Analytics/PerformanceMonitor/BarChartPerformance/BarChartPerformanceUtils.res | .res | open PerformanceMonitorTypes
let getBarOption = data =>
{
"chart": {
"type": `column`,
},
"xAxis": {
"categories": data.categories,
"title": {
"text": "",
},
},
"title": {
"text": "",
},
"yAxis": {
"min": 0,
"stackLabels": {
"enabled": true,
},
"title": {
"text": "",
},
},
"legend": {
"align": "right", // Align the legend to the right
"verticalAlign": "middle", // Vertically center the legend
"layout": "vertical", // Use a vertical layout for legend items
"enabled": true,
"itemStyle": LineChartUtils.legendItemStyle("12px"),
"itemHiddenStyle": {
"color": "rgba(53, 64, 82, 0.2)",
"cursor": "pointer",
"fontWeight": "500",
"fontStyle": "normal",
},
"itemHoverStyle": LineChartUtils.legendItemStyle("12px"),
"symbolRadius": 4,
"symbolPaddingTop": 5,
"itemMarginBottom": 10,
},
"tooltip": {
"headerFormat": "<b>{point.x}</b><br/>",
"pointFormat": "{series.name}: {point.y}<br/>Total: {point.stackTotal}",
},
"plotOptions": {
"column": {
"stacking": "normal",
"borderRadius": 3,
"dataLabels": {
"enabled": true,
},
},
},
"credits": {
"enabled": false, // Disable the Highcharts credits
},
"series": data.series,
}->Identity.genericObjectOrRecordToJson
let getBarchartColor = name => {
switch name {
| "failure" => "#DA6C68"
| "charged" => "#7AAF73"
| "authentication_pending" => "#E3945C"
| "authentication_failed" => "#E18494"
| "pending" => "#B6A1D2"
| "payment_method_awaited" => "#80A3F8"
| "authorized" => "#5398A7"
| _ => "#79B8F3"
}
}
let getStackedBarData = (~args) => {
let {array, config} = args
let {groupByKeys} = config
let grouped = PerformanceUtils.getGroupByDataForStatusAndPaymentCount(array, groupByKeys)
let keys = grouped->Dict.keysToArray
let finalResult = Dict.make()
let categories = []
let _ = keys->Array.forEach(v => {
let dict = grouped->Dict.get(v)->Option.getOr(Dict.make())
let plotChartBy = switch config.plotChartBy {
| Some(val) => val->Array.map(item => (item: status :> string))
| None => dict->Dict.keysToArray
}
let _ = plotChartBy->Array.forEach(ele => {
switch dict->Dict.get(ele) {
| None => {
let val = 0
let arr = finalResult->Dict.get(ele)->Option.getOr([])
arr->Array.push(val)
let _ = finalResult->Dict.set(ele, arr)
}
| Some(val) => {
let val = val
let arr = finalResult->Dict.get(ele)->Option.getOr([])
arr->Array.push(val)
let _ = finalResult->Dict.set(ele, arr)
}
}
})
categories->Array.push(v)
})
let series =
finalResult
->Dict.keysToArray
->Array.map(val => {
{
name: val,
data: finalResult->Dict.get(val)->Option.getOr([]),
color: val->getBarchartColor,
}
})
let updatedCategories = switch config.yLabels {
| Some(labels) => labels
| None => categories
}
{
categories: updatedCategories,
series,
}
}
| 919 | 9,762 |
hyperswitch-control-center | src/screens/Analytics/PerformanceMonitor/PieChartPerformance/PieChartPerformanceUtils.res | .res | open LogicUtils
open PerformanceMonitorTypes
let getPieChartOptions = series => {
{
"chart": {
"type": "pie",
},
"tooltip": {
"valueSuffix": ``,
},
"subtitle": {
"text": "",
},
"title": {
"text": "",
},
"colors": [
"#80A3F8",
"#7AAF73",
"#DA6C68",
"#5398A7",
"#E18494",
"#79B8F3",
"#B6A1D2",
"#E3945C",
"#FFAB99",
"#679FDF",
],
"plotOptions": {
"pie": {
"center": ["50%", "50%"],
"allowPointSelect": true,
"cursor": `pointer`,
"dataLabels": {
"enabled": true,
"distance": -15, // Set distance for the label inside the slice
"format": `{point.percentage:.0f}%`,
},
"showInLegend": true,
},
},
"legend": {
"align": "right", // Align the legend to the right
"verticalAlign": "middle", // Vertically center the legend
"layout": "vertical", // Use a vertical layout for legend items
"width": "35%",
"enabled": true,
"itemStyle": LineChartUtils.legendItemStyle("12px"),
"itemHiddenStyle": {
"color": "rgba(53, 64, 82, 0.2)",
"cursor": "pointer",
"fontWeight": "500",
"fontStyle": "normal",
},
"itemHoverStyle": LineChartUtils.legendItemStyle("12px"),
"symbolRadius": 4,
"symbolPaddingTop": 5,
"itemMarginBottom": 10,
},
"credits": {
"enabled": false, // Disable the Highcharts credits
},
"series": [
{
"name": "Total",
"colorByPoint": true,
"innerSize": "60%",
"data": series,
},
],
}->Identity.genericTypeToJson
}
let getDonutCharData = (~args) => {
let {array, config} = args
let {groupByKeys} = config
let grouped = PerformanceUtils.getGroupByDataForStatusAndPaymentCount(array, groupByKeys)
let keys = grouped->Dict.keysToArray
let series: array<donutPieSeriesRecord> = keys->Array.map(val => {
let dict = grouped->Dict.get(val)->Option.getOr(Dict.make())
{
name: val,
y: dict->getInt("failure", 0),
}
})
series
}
| 638 | 9,763 |
hyperswitch-control-center | src/screens/Analytics/PerformanceMonitor/PieChartPerformance/PieChartPerformance.res | .res | @react.component
let make = (
~domain,
~startTimeVal,
~endTimeVal,
~dimensions,
~entity: PerformanceMonitorTypes.entity<'t, 't1>,
) => {
open APIUtils
open LogicUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let (options, setBarOptions) = React.useState(_ => JSON.Encode.null)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let chartFetch = async () => {
try {
let metricsUrl = getURL(
~entityName=V1(ANALYTICS_PAYMENTS),
~methodType=Post,
~id=Some(domain),
)
let body = PerformanceUtils.requestBody(
~dimensions,
~excludeFilterValue=entity.requestBodyConfig.excludeFilterValue,
~startTime=startTimeVal,
~endTime=endTimeVal,
~filters=entity.requestBodyConfig.filters,
~metrics=entity.requestBodyConfig.metrics,
~groupBy=entity.requestBodyConfig.groupBy,
~customFilter=entity.requestBodyConfig.customFilter,
~applyFilterFor=entity.requestBodyConfig.applyFilterFor,
)
let res = await updateDetails(metricsUrl, body, Post)
let arr =
res
->getDictFromJsonObject
->getArrayFromDict("queryData", [])
if arr->Array.length > 0 {
let configData = entity.getChartData(
~args={array: arr, config: entity.configRequiredForChartData},
)
let options = entity.getChartOption(configData)
setBarOptions(_ => options)
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Custom)
}
}
React.useEffect(() => {
if startTimeVal->LogicUtils.isNonEmptyString && endTimeVal->LogicUtils.isNonEmptyString {
chartFetch()->ignore
}
None
}, [dimensions])
<PageLoaderWrapper
screenState
customLoader={<Shimmer styleClass="w-full h-96" />}
customUI={PerformanceUtils.customUI(entity.title)}>
<PerformanceUtils.Card title=entity.title>
<HighchartPieChart.RawPieChart options={options} />
</PerformanceUtils.Card>
</PageLoaderWrapper>
}
| 523 | 9,764 |
hyperswitch-control-center | src/screens/Analytics/GlobalSearch/GlobalSearchBarHelper.res | .res | open LogicUtils
open GlobalSearchTypes
module RenderedComponent = {
open String
@react.component
let make = (~ele, ~searchText) => {
let defaultStyle = "font-medium text-fs-14 text-lightgray_background opacity-50"
listOfMatchedText(ele, searchText)
->Array.mapWithIndex((item, index) => {
let key = index->Int.toString
let element = item->React.string
if item->toLowerCase == searchText->toLowerCase && searchText->isNonEmptyString {
<mark key className={`border-searched_text_border bg-yellow-searched_text ${defaultStyle}`}>
element
</mark>
} else {
<span key className=defaultStyle> element </span>
}
})
->React.array
}
}
module SearchBox = {
@react.component
let make = (~openModalOnClickHandler) => {
let iconBoxCss = "w-5 h-5 border border-gray-200 bg-white flex rounded-sm items-center justify-center cursor-pointer "
let cmdIcon = Window.Navigator.platform->String.includes("Mac") ? "⌘" : "^"
let shortcutIcons = {
<>
<div className="flex flex-row text-nd_gray-400 gap-1">
<div className={`${iconBoxCss} `}> {cmdIcon->React.string} </div>
<div className={`${iconBoxCss} text-xs`}> {"K"->React.string} </div>
</div>
</>
}
let isMobileView = MatchMedia.useMobileChecker()
if isMobileView {
<Icon size=14 name="search" className="mx-2" onClick={openModalOnClickHandler} />
} else {
<div
className={`flex w-80 gap-2 items-center text-grey-800 text-opacity-40 font-semibold justify-between py-2 px-3 rounded-lg border border-jp-gray-border_gray hover:cursor-text shadow-sm bg-nd_gray-100`}
onClick={openModalOnClickHandler}>
<div className="flex gap-2 ">
<Icon size=14 name="search" />
<p className="hidden lg:inline-block text-sm font-medium"> {"Search"->React.string} </p>
</div>
<div className="text-semibold text-sm hidden md:block cursor-pointer"> shortcutIcons </div>
</div>
}
}
}
module EmptyResult = {
open FramerMotion.Motion
@react.component
let make = (~prefix, ~searchText) => {
<Div layoutId="empty" initial={{scale: 0.9, opacity: 0.0}} animate={{scale: 1.0, opacity: 1.0}}>
<div className="flex flex-col w-full h-fit p-7 justify-center items-center gap-6">
<img alt="no-result" className="w-1/9" src={`${prefix}/icons/globalSearchNoResult.svg`} />
<div className="w-3/5 text-wrap text-center break-all">
{`No Results for " ${searchText} "`->React.string}
</div>
</div>
</Div>
}
}
module OptionWrapper = {
@react.component
let make = (~index, ~value, ~children, ~selectedOption, ~redirectOnSelect) => {
let activeClass = value == selectedOption ? "bg-gray-100 rounded-lg" : ""
<div
onClick={_ => value->redirectOnSelect}
className={`flex ${activeClass} flex-row truncate hover:bg-gray-100 cursor-pointer hover:rounded-lg p-2 group items-center`}
key={index->Int.toString}>
{children}
</div>
}
}
module ModalWrapper = {
open FramerMotion.Motion
@react.component
let make = (~showModal, ~setShowModal, ~children) => {
let borderRadius = ["15px", "15px", "15px", "15px"]
<Modal
showModal
setShowModal
modalClass="w-full md:w-7/12 lg:w-6/12 xl:w-6/12 2xl:w-4/12 mx-auto"
paddingClass="pt-24"
closeOnOutsideClick=true
bgClass="bg-transparent dark:bg-transparent border-transparent dark:border-transparent shadow-transparent">
<Div
layoutId="search"
key="search"
initial={{borderRadius, scale: 0.9}}
animate={{borderRadius, scale: 1.0}}
className={"flex flex-col bg-white gap-2 overflow-hidden py-2 !show-scrollbar"}>
{children}
</Div>
</Modal>
}
}
module ShowMoreLink = {
@react.component
let make = (
~section: resultType,
~cleanUpFunction=() => {()},
~textStyleClass="",
~searchText,
) => {
let totalCount = section.total_results
let generateLink = (path, domain) => {
`${path}?query=${searchText}&domain=${domain}`
}
let onClick = _ => {
let link = switch section.section {
| PaymentAttempts => generateLink("payment-attempts", "payment_attempts")
| SessionizerPaymentAttempts =>
generateLink("payment-attempts", "sessionizer_payment_attempts")
| PaymentIntents => generateLink("payment-intents", "payment_intents")
| SessionizerPaymentIntents => generateLink("payment-intents", "sessionizer_payment_intents")
| Refunds => generateLink("refunds-global", "refunds")
| SessionizerPaymentRefunds => generateLink("refunds-global", "sessionizer_refunds")
| Disputes => generateLink("dispute-global", "disputes")
| SessionizerPaymentDisputes => generateLink("dispute-global", "sessionizer_disputes")
| Local
| Others
| Default => ""
}
GlobalVars.appendDashboardPath(~url=link)->RescriptReactRouter.push
cleanUpFunction()
}
<RenderIf condition={totalCount > 10}>
{
let suffix = totalCount > 1 ? "s" : ""
let linkText = `View ${totalCount->Int.toString} result${suffix}`
switch section.section {
| SessionizerPaymentAttempts
| SessionizerPaymentIntents
| SessionizerPaymentRefunds
| SessionizerPaymentDisputes
| PaymentAttempts
| PaymentIntents
| Refunds
| Disputes =>
<div
onClick
className={`font-medium cursor-pointer underline underline-offset-2 opacity-50 ${textStyleClass}`}>
{linkText->React.string}
</div>
| Local
| Default
| Others => React.null
}
}
</RenderIf>
}
}
module KeyValueFilter = {
open GlobalSearchBarUtils
@react.component
let make = (~filter) => {
let itemValue =
filter.categoryType
->getcategoryFromVariant
->String.toLocaleLowerCase
<div className="font-medium px-2 py-1">
{`Enter ${itemValue} (e.g.,${filter.placeholder})`->React.string}
</div>
}
}
module FilterOption = {
@react.component
let make = (~onClick, ~value, ~placeholder=None, ~filter, ~selectedFilter=None, ~viewType) => {
let activeBg = "bg-gray-200"
let wrapperBg = "bg-gray-400/40"
let rounded = "rounded-lg"
let (activeWrapperClass, activeClass) = switch selectedFilter {
| Some(val) =>
filter == val
? (`${activeBg} ${rounded}`, `${wrapperBg}`)
: (`hover:${activeBg} hover:${rounded}`, `hover:${wrapperBg} ${activeBg}`)
| None => (`hover:${activeBg} hover:${rounded} `, `hover:${wrapperBg} ${activeBg}`)
}
switch viewType {
| FiltersSugsestions =>
<div
className={`flex justify-between p-2 group items-center cursor-pointer ${activeWrapperClass}`}
onClick>
<div className={`${activeClass} py-1 px-2 rounded-md flex gap-1 items-center w-fit`}>
<span className="font-medium text-sm"> {value->React.string} </span>
</div>
<RenderIf condition={placeholder->Option.isSome}>
<div className="text-sm opacity-70"> {placeholder->Option.getOr("")->React.string} </div>
</RenderIf>
</div>
| _ =>
<span
className={`${activeClass} py-1 px-2 rounded-md flex gap-1 items-center w-fit cursor-pointer font-medium text-sm`}
onClick>
{value->React.string}
</span>
}
}
}
module NoResults = {
@react.component
let make = () => {
<div className="text-sm p-2"> {"No Results"->React.string} </div>
}
}
module FilterResultsComponent = {
open GlobalSearchBarUtils
open FramerMotion.Motion
@react.component
let make = (
~categorySuggestions: array<categoryOption>,
~activeFilter,
~searchText,
~setAllFilters,
~selectedFilter,
~setSelectedFilter,
~onFilterClicked,
~onSuggestionClicked,
~viewType=FiltersSugsestions,
) => {
let filterKey = activeFilter->String.split(filterSeparator)->getValueFromArray(0, "")
let filters = categorySuggestions->Array.filter(category => {
if activeFilter->isNonEmptyString {
let categoryType = category.categoryType->getcategoryFromVariant
if searchText->getEndChar == filterSeparator {
`${categoryType}${filterSeparator}` == `${filterKey}${filterSeparator}`
} else {
categoryType->String.includes(filterKey)
}
} else {
true
}
})
let checkFilterKey = list => {
switch list->Array.get(0) {
| Some(value) =>
value.categoryType->getcategoryFromVariant === filterKey && value.options->Array.length > 0
| _ => false
}
}
let updateAllFilters = () => {
if filters->Array.length == 1 {
switch filters->Array.get(0) {
| Some(filter) =>
if filter.options->Array.length > 0 && filters->checkFilterKey {
let filterValue = activeFilter->String.split(filterSeparator)->getValueFromArray(1, "")
let options = if filterValue->isNonEmptyString {
filter.options->Array.filter(option => option->String.includes(filterValue))
} else {
filter.options
}
let newFilters = options->Array.map(option => {
let value = {
categoryType: filter.categoryType,
options: [option],
placeholder: filter.placeholder,
}
value
})
setAllFilters(_ => newFilters)
} else {
setAllFilters(_ => filters)
}
| _ => ()
}
} else {
setAllFilters(_ => filters)
}
}
React.useEffect(() => {
updateAllFilters()
None
}, [activeFilter])
React.useEffect(() => {
setSelectedFilter(_ => None)
None
}, [filters->Array.length])
let optionsFlexClass = viewType != FiltersSugsestions ? "flex flex-wrap gap-3 px-2 pt-2" : ""
let filterOptions = index => {
if viewType != FiltersSugsestions {
index < sectionsViewResultsCount
} else {
true
}
}
let isFreeTextKey = if filters->Array.length == 1 {
switch filters->Array.get(0) {
| Some(val) => val.options->Array.length == 0
| None => false
}
} else {
false
}
let sectionHeader = isFreeTextKey ? "" : "Suggested Filters"
<RenderIf condition={filters->Array.length > 0}>
<Div
initial={{opacity: 0.5}}
animate={{opacity: 0.5}}
layoutId="categories-section"
className="px-2 pt-2 border-t dark:border-jp-gray-960">
<Div layoutId="categories-title" className="font-bold px-2">
{sectionHeader->String.toUpperCase->React.string}
</Div>
<div>
<RenderIf condition={filters->Array.length === 1 && filters->checkFilterKey}>
<div className="h-full max-h-[450px] overflow-scroll sidebar-scrollbar">
<style> {React.string(sidebarScrollbarCss)} </style>
{switch filters->Array.get(0) {
| Some(value) =>
let filterValue =
activeFilter->String.split(filterSeparator)->getValueFromArray(1, "")
let options = if filterValue->isNonEmptyString {
value.options->Array.filter(option => option->String.includes(filterValue))
} else {
value.options
}
if options->Array.length > 0 {
<div className=optionsFlexClass>
{options
->Array.filterWithIndex((_, index) => {
index->filterOptions
})
->Array.map(option => {
let filter = {
categoryType: value.categoryType,
options: [option],
placeholder: value.placeholder,
}
let itemValue = `${value.categoryType
->getcategoryFromVariant
->String.toLocaleLowerCase} : ${option}`
<FilterOption
onClick={_ => option->onSuggestionClicked}
value=itemValue
filter
selectedFilter
viewType
/>
})
->React.array}
</div>
} else {
<NoResults />
}
| _ => <NoResults />
}}
</div>
</RenderIf>
<RenderIf condition={!(filters->Array.length === 1 && filters->checkFilterKey)}>
<div className=optionsFlexClass>
{if isFreeTextKey {
filters
->Array.map(filter => {
<KeyValueFilter filter />
})
->React.array
} else {
filters
->Array.map(category => {
let itemValue = `${category.categoryType
->getcategoryFromVariant
->String.toLocaleLowerCase} ${filterSeparator} `
<FilterOption
onClick={_ => category->onFilterClicked}
value=itemValue
placeholder={Some(category.placeholder)}
filter={category}
selectedFilter
viewType
/>
})
->React.array
}}
</div>
</RenderIf>
</div>
</Div>
</RenderIf>
}
}
module SearchResultsComponent = {
open FramerMotion.Motion
@react.component
let make = (
~searchResults,
~searchText,
~setShowModal,
~selectedOption,
~redirectOnSelect,
~categorySuggestions,
~activeFilter,
~setAllFilters,
~selectedFilter,
~setSelectedFilter,
~onFilterClicked,
~onSuggestionClicked,
~viewType,
~prefix,
~filtersEnabled,
) => {
<div className={"w-full overflow-auto text-base max-h-[60vh] focus:outline-none sm:text-sm "}>
<RenderIf condition={filtersEnabled}>
<FilterResultsComponent
categorySuggestions
activeFilter
searchText
setAllFilters
selectedFilter
onFilterClicked
onSuggestionClicked
setSelectedFilter
viewType
/>
</RenderIf>
{switch viewType {
| Load =>
<div className="mb-24">
<Loader />
</div>
| EmptyResult => <EmptyResult prefix searchText />
| _ =>
<Div className="mt-3 border-t" layoutId="border">
{searchResults
->Array.mapWithIndex((section: resultType, index) => {
<Div
key={Int.toString(index)}
layoutId={`${section.section->getSectionHeader} ${Int.toString(index)}`}
className={`px-3 mb-3 py-1`}>
<Div
layoutId={`${section.section->getSectionHeader}-${index->Belt.Int.toString}`}
className="text-lightgray_background px-2 pb-1 flex justify-between ">
<div className="font-bold opacity-50">
{section.section->getSectionHeader->String.toUpperCase->React.string}
</div>
<ShowMoreLink
section
cleanUpFunction={() => {setShowModal(_ => false)}}
textStyleClass="text-xs"
searchText
/>
</Div>
{section.results
->Array.mapWithIndex((item, i) => {
let elementsArray = item.texts
<OptionWrapper
key={Int.toString(i)} index={i} value={item} selectedOption redirectOnSelect>
{elementsArray
->Array.mapWithIndex(
(item, index) => {
let elementValue = item->JSON.Decode.string->Option.getOr("")
<RenderIf
condition={elementValue->isNonEmptyString} key={index->Int.toString}>
<RenderedComponent ele=elementValue searchText />
<RenderIf condition={index >= 0 && index < elementsArray->Array.length - 1}>
<span className="mx-2 text-lightgray_background opacity-50">
{">"->React.string}
</span>
</RenderIf>
</RenderIf>
},
)
->React.array}
</OptionWrapper>
})
->React.array}
</Div>
})
->React.array}
</Div>
}}
</div>
}
}
module ModalSearchBox = {
open GlobalSearchBarUtils
open FramerMotion.Motion
open ReactEvent.Keyboard
@react.component
let make = (
~inputRef: React.ref<'a>,
~leftIcon,
~setShowModal,
~setFilterText,
~localSearchText,
~setLocalSearchText,
~allOptions,
~selectedOption,
~setSelectedOption,
~redirectOnSelect,
~allFilters,
~selectedFilter,
~setSelectedFilter,
~viewType,
~activeFilter,
~onFilterClicked,
~onSuggestionClicked,
~categorySuggestions,
~searchText,
) => {
let (errorMessage, setErrorMessage) = React.useState(_ => "")
let tabKey = 9
let arrowDown = 40
let arrowUp = 38
let enterKey = 13
let spaceKey = 32
let input: ReactFinalForm.fieldRenderPropsInput = {
{
name: "global_search",
onBlur: _ => (),
onChange: ev => {
let value = {ev->ReactEvent.Form.target}["value"]
setLocalSearchText(_ => value)
},
onFocus: _ => (),
value: localSearchText->JSON.Encode.string,
checked: false,
}
}
let getNextIndex = (selectedIndex, options) => {
let count = options->Array.length
selectedIndex == count - 1 ? 0 : Int.mod(selectedIndex + 1, count)
}
let getPrevIndex = (selectedIndex, options) => {
let count = options->Array.length
selectedIndex === 0 ? count - 1 : Int.mod(selectedIndex - 1, count)
}
let tabKeyPressHandler = e => {
revertFocus(~inputRef)
let keyPressed = e->keyCode
switch viewType {
| EmptyResult | Load => ()
| Results => {
let index = allOptions->Array.findIndex(item => {
item == selectedOption
})
if keyPressed == tabKey {
let newIndex = getNextIndex(index, allOptions)
switch allOptions->Array.get(newIndex) {
| Some(val) => setSelectedOption(_ => val)
| _ => ()
}
}
}
| FiltersSugsestions => {
let index = allFilters->Array.findIndex(item => {
switch selectedFilter {
| Some(val) => item == val
| _ => false
}
})
if keyPressed == tabKey {
let newIndex = getNextIndex(index, allFilters)
switch allFilters->Array.get(newIndex) {
| Some(val) => setSelectedFilter(_ => val->Some)
| _ => ()
}
}
}
}
}
React.useEffect(() => {
Window.addEventListener("keydown", tabKeyPressHandler)
Some(() => Window.removeEventListener("keydown", tabKeyPressHandler))
}, (selectedFilter, selectedOption))
let handleKeyDown = e => {
let keyPressed = e->keyCode
switch viewType {
| Results => {
let index = allOptions->Array.findIndex(item => {
item == selectedOption
})
if keyPressed == arrowDown {
let newIndex = getNextIndex(index, allOptions)
switch allOptions->Array.get(newIndex) {
| Some(val) => setSelectedOption(_ => val)
| _ => ()
}
} else if keyPressed == arrowUp {
let newIndex = getPrevIndex(index, allOptions)
switch allOptions->Array.get(newIndex) {
| Some(val) => setSelectedOption(_ => val)
| _ => ()
}
} else if keyPressed == enterKey {
selectedOption->redirectOnSelect
}
}
| FiltersSugsestions => {
let index = allFilters->Array.findIndex(item => {
switch selectedFilter {
| Some(val) => item == val
| _ => false
}
})
if keyPressed == arrowDown {
let newIndex = getNextIndex(index, allFilters)
switch allFilters->Array.get(newIndex) {
| Some(val) => setSelectedFilter(_ => val->Some)
| _ => ()
}
} else if keyPressed == arrowUp {
let newIndex = getPrevIndex(index, allFilters)
switch allFilters->Array.get(newIndex) {
| Some(val) => setSelectedFilter(_ => val->Some)
| _ => ()
}
} else if keyPressed == enterKey {
switch selectedFilter {
| Some(filter) =>
if activeFilter->String.includes(filterSeparator) {
switch filter.options->Array.get(0) {
| Some(val) => val->onSuggestionClicked
| _ => ()
}
} else {
filter->onFilterClicked
}
| _ => ()
}
}
}
| EmptyResult | Load => ()
}
if keyPressed == spaceKey {
setFilterText("")
} else {
let values = localSearchText->String.split(" ")
let filter = values->getValueFromArray(values->Array.length - 1, "")
if activeFilter !== filter {
setFilterText(filter)
}
}
}
let filterKey = activeFilter->String.split(filterSeparator)->getValueFromArray(0, "")
let filters = categorySuggestions->Array.filter(category => {
if activeFilter->isNonEmptyString {
let categoryType = category.categoryType->getcategoryFromVariant
if searchText->getEndChar == filterSeparator {
`${categoryType}${filterSeparator}` == `${filterKey}${filterSeparator}`
} else {
categoryType->String.includes(filterKey)
}
} else {
true
}
})
let validateForm = _ => {
let errors = Dict.make()
if localSearchText->validateQuery && filters->Array.length == 0 {
setErrorMessage(_ =>
"Only one free-text search is allowed and additional text will be ignored."
)
} else if !(localSearchText->validateQuery) {
setErrorMessage(_ => "")
}
errors->JSON.Encode.object
}
let textColor = errorMessage->isNonEmptyString ? "text-red-900" : "text-jp-gray-900"
<Form
key="global-search"
initialValues={Dict.make()->JSON.Encode.object}
validate={values => values->validateForm}
onSubmit={(_, _) => Nullable.null->Promise.resolve}>
<LabelVisibilityContext showLabel=false>
<FormRenderer.FieldRenderer
field={FormRenderer.makeFieldInfo(
~label="",
~name="global_search",
~customInput=(~input as _, ~placeholder as _) => {
<Div layoutId="input" className="h-fit bg-white">
<div className={`flex flex-row items-center `}>
{leftIcon}
<div className="w-full overflow-scroll flex flex-row items-center">
<input
ref={inputRef->ReactDOM.Ref.domRef}
autoComplete="off"
autoFocus=true
placeholder="Search"
className={`w-full pr-2 pl-2 ${textColor} text-opacity-75 focus:text-opacity-100 placeholder-jp-gray-900 focus:outline-none rounded h-10 text-lg font-normal placeholder-opacity-50 `}
name={input.name}
label="No"
value=localSearchText
type_="text"
checked={false}
onChange=input.onChange
onKeyUp=handleKeyDown
/>
</div>
<div
className="bg-gray-200 py-1 px-2 rounded-md flex gap-1 items-center mr-5 cursor-pointer ml-2 opacity-70"
onClick={_ => {
setShowModal(_ => false)
}}>
<span className="opacity-40 font-bold text-sm"> {"Esc"->React.string} </span>
<Icon size=15 name="times" parentClass="flex justify-end opacity-30" />
</div>
</div>
<RenderIf condition={errorMessage->isNonEmptyString}>
<div className="text-sm text-red-900 ml-12 pl-2">
{errorMessage->React.string}
</div>
</RenderIf>
</Div>
},
~isRequired=false,
)}
/>
</LabelVisibilityContext>
</Form>
}
}
| 5,685 | 9,765 |
hyperswitch-control-center | src/screens/Analytics/GlobalSearch/GlobalSearchBarUtils.res | .res | open GlobalSearchTypes
open LogicUtils
let defaultRoute = "/search"
let global_search_activate_key = "k"
let filterSeparator = ":"
let sectionsViewResultsCount = 4
let getEndChar = string => {
string->String.charAt(string->String.length - 1)
}
let matchInSearchOption = (searchOptions, searchText, name, link, ~sectionName) => {
searchOptions
->Option.getOr([])
->Array.filter(item => {
let (searchKey, _) = item
checkStringStartsWithSubstring(~itemToCheck=searchKey, ~searchText)
})
->Array.map(item => {
let (searchKey, redirection) = item
{
texts: [
sectionName->JSON.Encode.string,
name->JSON.Encode.string,
searchKey->JSON.Encode.string,
],
redirect_link: `${link}${redirection}`->JSON.Encode.string,
}
})
}
let getLocalMatchedResults = (searchText, tabs) => {
open SidebarTypes
let results = tabs->Array.reduce([], (acc, item) => {
switch item {
| Link(tab)
| RemoteLink(tab) => {
if checkStringStartsWithSubstring(~itemToCheck=tab.name, ~searchText) {
let matchedEle = {
texts: [""->JSON.Encode.string, tab.name->JSON.Encode.string],
redirect_link: tab.link->JSON.Encode.string,
}
acc->Array.push(matchedEle)
}
let matchedSearchValues = matchInSearchOption(
tab.searchOptions,
searchText,
tab.name,
tab.link,
~sectionName="",
)
acc->Array.concat(matchedSearchValues)
}
| Section(sectionObj) => {
let sectionSearchedValues = sectionObj.links->Array.reduce([], (insideAcc, item) => {
switch item {
| SubLevelLink(tab) => {
if (
checkStringStartsWithSubstring(~itemToCheck=sectionObj.name, ~searchText) ||
checkStringStartsWithSubstring(~itemToCheck=tab.name, ~searchText)
) {
let matchedEle = {
texts: [sectionObj.name->JSON.Encode.string, tab.name->JSON.Encode.string],
redirect_link: tab.link->JSON.Encode.string,
}
insideAcc->Array.push(matchedEle)
}
let matchedSearchValues = matchInSearchOption(
tab.searchOptions,
searchText,
tab.name,
tab.link,
~sectionName=sectionObj.name,
)
insideAcc->Array.concat(matchedSearchValues)
}
}
})
acc->Array.concat(sectionSearchedValues)
}
| LinkWithTag(tab) => {
if checkStringStartsWithSubstring(~itemToCheck=tab.name, ~searchText) {
let matchedEle = {
texts: [tab.name->JSON.Encode.string],
redirect_link: tab.link->JSON.Encode.string,
}
acc->Array.push(matchedEle)
}
let matchedSearchValues = matchInSearchOption(
tab.searchOptions,
searchText,
tab.name,
tab.link,
~sectionName="",
)
acc->Array.concat(matchedSearchValues)
}
| Heading(_) | CustomComponent(_) => acc->Array.concat([])
}
})
{
section: Local,
results,
total_results: results->Array.length,
}
}
let getElements = (hits, section) => {
let getAmount = (value, amountKey, currencyKey) => {
let amount = (value->getFloat(amountKey, 0.0) /. 100.0)->Belt.Float.toString
let currency = value->getString(currencyKey, "")
`${amount} ${currency}`
}
let getValues = item => {
let value = item->JSON.Decode.object->Option.getOr(Dict.make())
let payId = value->getString("payment_id", "")
let amount = value->getAmount("amount", "currency")
let status = value->getString("status", "")
let profileId = value->getString("profile_id", "")
let merchantId = value->getString("merchant_id", "")
let orgId = value->getString("organization_id", "")
let metadata = {
orgId,
merchantId,
profileId,
}
(payId, amount, status, metadata)
}
switch section {
| PaymentAttempts | SessionizerPaymentAttempts =>
hits->Array.map(item => {
let (payId, amount, status, metadata) = item->getValues
{
texts: [payId, amount, status]->Array.map(JSON.Encode.string),
redirect_link: `/payments/${payId}/${metadata.profileId}/${metadata.merchantId}/${metadata.orgId}`->JSON.Encode.string,
}
})
| PaymentIntents | SessionizerPaymentIntents =>
hits->Array.map(item => {
let (payId, amount, status, metadata) = item->getValues
{
texts: [payId, amount, status]->Array.map(JSON.Encode.string),
redirect_link: `/payments/${payId}/${metadata.profileId}/${metadata.merchantId}/${metadata.orgId}`->JSON.Encode.string,
}
})
| Refunds | SessionizerPaymentRefunds =>
hits->Array.map(item => {
let value = item->JSON.Decode.object->Option.getOr(Dict.make())
let refId = value->getString("refund_id", "")
let amount = value->getAmount("refund_amount", "currency")
let status = value->getString("refund_status", "")
let profileId = value->getString("profile_id", "")
let orgId = value->getString("organization_id", "")
let merchantId = value->getString("merchant_id", "")
{
texts: [refId, amount, status]->Array.map(JSON.Encode.string),
redirect_link: `/refunds/${refId}/${profileId}/${merchantId}/${orgId}`->JSON.Encode.string,
}
})
| Disputes | SessionizerPaymentDisputes =>
hits->Array.map(item => {
let value = item->JSON.Decode.object->Option.getOr(Dict.make())
let disId = value->getString("dispute_id", "")
let amount = value->getAmount("dispute_amount", "currency")
let status = value->getString("dispute_status", "")
let profileId = value->getString("profile_id", "")
let orgId = value->getString("organization_id", "")
let merchantId = value->getString("merchant_id", "")
{
texts: [disId, amount, status]->Array.map(JSON.Encode.string),
redirect_link: `/${disId}/${profileId}/${merchantId}/${orgId}`->JSON.Encode.string,
}
})
| Local
| Others
| Default => []
}
}
let getItemFromArray = (results, key1, key2, resultsData) => {
switch (resultsData->Dict.get(key1), resultsData->Dict.get(key2)) {
| (Some(data), Some(sessionizerData)) => {
let intentsCount = data.total_results
let sessionizerCount = sessionizerData.total_results
if intentsCount > 0 && sessionizerCount > 0 {
if intentsCount >= sessionizerCount {
results->Array.push(data)
} else {
results->Array.push(sessionizerData)
}
} else if intentsCount > 0 {
results->Array.push(data)
} else {
results->Array.push(sessionizerData)
}
}
| (None, Some(sessionizerData)) => results->Array.push(sessionizerData)
| (Some(data), None) => results->Array.push(data)
| _ => ()
}
}
let getRemoteResults = json => {
let data = Dict.make()
json
->JSON.Decode.array
->Option.getOr([])
->Array.forEach(item => {
let value = item->JSON.Decode.object->Option.getOr(Dict.make())
let section = value->getString("index", "")->getSectionVariant
let hints =
value
->getArrayFromDict("hits", [])
->Array.filterWithIndex((_, index) => index < sectionsViewResultsCount)
let total_results = value->getInt("count", hints->Array.length)
let key = value->getString("index", "")
if hints->Array.length > 0 {
data->Dict.set(
key,
{
section,
results: hints->getElements(section),
total_results,
},
)
}
})
let results = []
// intents
let key1 = PaymentIntents->getSectionIndex
let key2 = SessionizerPaymentIntents->getSectionIndex
getItemFromArray(results, key1, key2, data)
// Attempts
let key1 = PaymentAttempts->getSectionIndex
let key2 = SessionizerPaymentAttempts->getSectionIndex
getItemFromArray(results, key1, key2, data)
// Refunds
let key1 = Refunds->getSectionIndex
let key2 = SessionizerPaymentRefunds->getSectionIndex
getItemFromArray(results, key1, key2, data)
// Disputes
let key1 = Disputes->getSectionIndex
let key2 = SessionizerPaymentDisputes->getSectionIndex
getItemFromArray(results, key1, key2, data)
results
}
let getDefaultResult = searchText => {
{
section: Default,
results: [
{
texts: ["Show all results for"->JSON.Encode.string, searchText->JSON.Encode.string],
redirect_link: `/search?query=${searchText}`->JSON.Encode.string,
},
],
total_results: 1,
}
}
let getDefaultOption = searchText => {
{
texts: ["Show all results for"->JSON.Encode.string, searchText->JSON.Encode.string],
redirect_link: `/search?query=${searchText}`->JSON.Encode.string,
}
}
let getAllOptions = (results: array<GlobalSearchTypes.resultType>) => {
results->Array.flatMap(item => item.results)
}
let parseResponse = response => {
response
->getArrayFromJson([])
->Array.map(json => {
let item = json->getDictFromJsonObject
{
count: item->getInt("count", 0),
hits: item->getArrayFromDict("hits", []),
index: item->getString("index", ""),
}
})
}
let generateSearchBody = (~searchText, ~merchant_id) => {
if !(searchText->CommonAuthUtils.isValidEmail) {
let filters =
[
("customer_email", [searchText->JSON.Encode.string]->JSON.Encode.array),
]->getJsonFromArrayOfJson
[("query", merchant_id->JSON.Encode.string), ("filters", filters)]->getJsonFromArrayOfJson
} else {
[("query", searchText->JSON.Encode.string)]->getJsonFromArrayOfJson
}
}
let categoryList = [
Payment_Method,
Payment_Method_Type,
Currency,
Connector,
Customer_Email,
Card_Network,
Card_Last_4,
Status,
Payment_id,
Amount,
]
let getcategoryFromVariant = category => {
switch category {
| Payment_Method => "payment_method"
| Payment_Method_Type => "payment_method_type"
| Currency => "currency"
| Connector => "connector"
| Customer_Email => "customer_email"
| Card_Network => "card_network"
| Card_Last_4 => "card_last_4"
| Date => "date"
| Status => "status"
| Payment_id => "payment_id"
| Amount => "amount"
}
}
let getDefaultPlaceholderValue = category => {
switch category {
| Payment_Method => "payment_method:card"
| Payment_Method_Type => "payment_method_type:credit"
| Currency => "currency:USD"
| Connector => "connector:stripe"
| Customer_Email => "customer_email:abc@abc.com"
| Card_Network => "card_network:visa"
| Card_Last_4 => "card_last_4:2326"
| Date => "date:today"
| Status => "status:charged"
| Payment_id => "payment_id:pay_xxxxxxxxx"
| Amount => "amount:100"
}
}
let getCategoryVariantFromString = category => {
switch category {
| "payment_method" => Payment_Method
| "payment_method_type" => Payment_Method_Type
| "connector" => Connector
| "currency" => Currency
| "customer_email" => Customer_Email
| "card_network" => Card_Network
| "card_last_4" => Card_Last_4
| "payment_id" => Payment_id
| "status" => Status
| "date" | _ => Date
}
}
let generatePlaceHolderValue = (category, options) => {
switch options->Array.get(0) {
| Some(value) => `${category->getcategoryFromVariant}:${value}`
| _ => category->getDefaultPlaceholderValue
}
}
let getCategorySuggestions = json => {
let suggestions = Dict.make()
json
->getDictFromJsonObject
->getArrayFromDict("queryData", [])
->Array.forEach(item => {
let itemDict = item->getDictFromJsonObject
let key = itemDict->getString("dimension", "")
let value =
itemDict
->getArrayFromDict("values", [])
->Array.map(value => {
value->JSON.Decode.string->Option.getOr("")
})
->Array.filter(item => item->String.length > 0)
if key->isNonEmptyString && value->Array.length > 0 {
suggestions->Dict.set(key, value)
}
})
categoryList->Array.map(category => {
let options = suggestions->Dict.get(category->getcategoryFromVariant)->Option.getOr([])
{
categoryType: category,
options,
placeholder: generatePlaceHolderValue(category, options),
}
})
}
let paymentsGroupByNames = [
"connector",
"payment_method",
"payment_method_type",
"currency",
"status",
"profile_id",
"card_network",
"merchant_id",
]
let refundsGroupByNames = ["currency", "refund_status", "connector", "refund_type", "profile_id"]
let disputesGroupByNames = ["connector", "dispute_stage"]
let getFilterBody = groupByNames =>
{
let defaultDate = HSwitchRemoteFilter.getDateFilteredObject(~range=7)
let filterBodyEntity: AnalyticsUtils.filterBodyEntity = {
startTime: defaultDate.start_time,
endTime: defaultDate.end_time,
groupByNames,
source: "BATCH",
}
AnalyticsUtils.filterBody(filterBodyEntity)
}->Identity.genericTypeToJson
let generateFilter = (queryArray: array<string>) => {
let filter = Dict.make()
queryArray->Array.forEach(query => {
let keyValuePair =
query
->String.split(filterSeparator)
->Array.filter(query => {
query->String.trim->isNonEmptyString
})
let key = keyValuePair->getValueFromArray(0, "")
let value = keyValuePair->getValueFromArray(1, "")
switch filter->Dict.get(key) {
| Some(prevArr) =>
if !(prevArr->Array.includes(value)) && value->isNonEmptyString {
filter->Dict.set(key, prevArr->Array.concat([value]))
}
| _ =>
if value->isNonEmptyString {
filter->Dict.set(key, [value])
}
}
})
filter
->Dict.toArray
->Array.map(item => {
let (key, value) = item
let newValue = if key == Amount->getcategoryFromVariant {
value->Array.map(item => {
item->Float.fromString->Option.getOr(0.0)->JSON.Encode.float
})
} else {
value->Array.map(JSON.Encode.string)
}
(key, newValue->JSON.Encode.array)
})
->Dict.fromArray
}
let generateQuery = searchQuery => {
let filters = []
let queryText = ref("")
searchQuery
->String.split(" ")
->Array.filter(query => {
query->String.trim->isNonEmptyString
})
->Array.forEach(query => {
if RegExp.test(%re("/^[^:\s]+:[^:\s]*$/"), query) {
let key = query->String.split(filterSeparator)->Array.get(0)->Option.getOr("")
if key == Amount->getcategoryFromVariant {
let valueString =
query
->String.split(filterSeparator)
->Array.get(1)
->Option.getOr("")
if valueString->isNonEmptyString && RegExp.test(%re("/^\d+(\.\d+)?$/"), valueString) {
let value = (valueString
->Float.fromString
->Option.getOr(0.0) *. 100.00)->Float.toString
let filter = `${Amount->getcategoryFromVariant}${filterSeparator}${value}`
filters->Array.push(filter)
}
} else {
filters->Array.push(query)
}
} else if !(query->CommonAuthUtils.isValidEmail) {
let filter = `${Customer_Email->getcategoryFromVariant}${filterSeparator}${query}`
filters->Array.push(filter)
} else if queryText.contents->isEmptyString {
queryText := query
}
})
let body = {
let filterObj = filters->generateFilter
let query = if filters->Array.length > 0 && filterObj->Dict.keysToArray->Array.length > 0 {
[("filters", filterObj->JSON.Encode.object)]
} else {
[]
}
let query =
query->Array.concat([("query", queryText.contents->String.trim->JSON.Encode.string)])
query->Dict.fromArray
}
body
}
let validateQuery = searchQuery => {
let freeTextCount = ref(0)
searchQuery
->String.split(" ")
->Array.filter(query => {
query->String.trim->isNonEmptyString
})
->Array.forEach(query => {
if !RegExp.test(%re("/^[^:\s]+:[^:\s]+$/"), query) {
freeTextCount := freeTextCount.contents + 1
}
})
freeTextCount.contents > 1
}
let getViewType = (~state, ~searchResults) => {
switch state {
| Loading => Load
| Loaded =>
if searchResults->Array.length > 0 {
Results
} else {
EmptyResult
}
| Idle => FiltersSugsestions
}
}
let getSearchValidation = query => {
let paylod = query->generateQuery
let query = paylod->getString("query", "")->String.trim
!(paylod->getObj("filters", Dict.make())->isEmptyDict && query->isEmptyString)
}
let sidebarScrollbarCss = `
@supports (-webkit-appearance: none){
.sidebar-scrollbar {
scrollbar-width: auto;
scrollbar-color: #8a8c8f;
}
.sidebar-scrollbar::-webkit-scrollbar {
display: block;
overflow: scroll;
height: 4px;
width: 5px;
}
.sidebar-scrollbar::-webkit-scrollbar-thumb {
background-color: #8a8c8f;
border-radius: 3px;
}
.sidebar-scrollbar::-webkit-scrollbar-track {
display: none;
}
}
`
let revertFocus = (~inputRef: React.ref<'a>) => {
switch inputRef.current->Js.Nullable.toOption {
| Some(elem) => elem->MultipleFileUpload.focus
| None => ()
}
}
| 4,275 | 9,766 |
hyperswitch-control-center | src/screens/Analytics/GlobalSearch/GlobalSearchBar.res | .res | @react.component
let make = () => {
open GlobalSearchTypes
open GlobalSearchBarUtils
open LogicUtils
open GlobalSearchBarHelper
let getURL = APIUtils.useGetURL()
let prefix = useUrlPrefix()
let setGLobalSearchResults = HyperswitchAtom.globalSeacrchAtom->Recoil.useSetRecoilState
let fetchDetails = APIUtils.useUpdateMethod()
let (state, setState) = React.useState(_ => Idle)
let (showModal, setShowModal) = React.useState(_ => false)
let (searchText, setSearchText) = React.useState(_ => "")
let (activeFilter, setActiveFilter) = React.useState(_ => "")
let (localSearchText, setLocalSearchText) = React.useState(_ => "")
let (selectedOption, setSelectedOption) = React.useState(_ => ""->getDefaultOption)
let (allOptions, setAllOptions) = React.useState(_ => [])
let (selectedFilter, setSelectedFilter) = React.useState(_ => None)
let (allFilters, setAllFilters) = React.useState(_ => [])
let (categorieSuggestionResponse, setCategorieSuggestionResponse) = React.useState(_ =>
Dict.make()->JSON.Encode.object
)
let {userInfo: {version}} = React.useContext(UserInfoProvider.defaultContext)
let (searchResults, setSearchResults) = React.useState(_ => [])
let merchentDetails = HSwitchUtils.useMerchantDetailsValue()
let isReconEnabled = merchentDetails.recon_status === Active
let hswitchTabs = SidebarValues.useGetHsSidebarValues(~isReconEnabled)
let loader = LottieFiles.useLottieJson("loader-circle.json")
let {globalSearch, globalSearchFilters} =
HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
let isShowRemoteResults = globalSearch && userHasAccess(~groupAccess=OperationsView) === Access
let mixpanelEvent = MixpanelHook.useSendEvent()
let inputRef = React.useRef(Nullable.null)
let filtersEnabled = globalSearchFilters
let redirectOnSelect = element => {
mixpanelEvent(~eventName="global_search_redirect")
let redirectLink = element.redirect_link->JSON.Decode.string->Option.getOr(defaultRoute)
if redirectLink->isNonEmptyString {
setShowModal(_ => false)
GlobalVars.appendDashboardPath(~url=redirectLink)->RescriptReactRouter.push
}
}
let getCategoryOptions = async () => {
setState(_ => Loading)
try {
let paymentsUrl = getURL(
~entityName=V1(ANALYTICS_FILTERS),
~methodType=Post,
~id=Some("payments"),
)
let paymentsResponse = await fetchDetails(
paymentsUrl,
paymentsGroupByNames->getFilterBody,
Post,
)
setCategorieSuggestionResponse(_ => paymentsResponse)
setState(_ => Idle)
} catch {
| _ => setState(_ => Idle)
}
}
let getSearchResults = async results => {
try {
let local_results = []
let url = getURL(~entityName=V1(GLOBAL_SEARCH), ~methodType=Post)
let body = searchText->generateQuery
mixpanelEvent(~eventName="global_search", ~metadata=body->JSON.Encode.object)
let response = await fetchDetails(url, body->JSON.Encode.object, Post)
results->Array.forEach((item: resultType) => {
switch item.section {
| Local => local_results->Array.pushMany(item.results)
| _ => ()
}
})
let remote_results = response->parseResponse
setGLobalSearchResults(_ => {
local_results,
remote_results,
searchText,
})
let values = response->getRemoteResults
results->Array.pushMany(values)
let defaultItem = searchText->getDefaultResult
let finalResults = results->Array.length > 0 ? [defaultItem]->Array.concat(results) : []
setSearchResults(_ => finalResults)
setState(_ => Loaded)
} catch {
| _ => setState(_ => Loaded)
}
}
React.useEffect(() => {
let allOptions = searchResults->getAllOptions
setAllOptions(_ => allOptions)
setSelectedOption(_ => searchText->getDefaultOption)
None
}, [searchResults])
React.useEffect(_ => {
let results = []
if (
searchText->isNonEmptyString &&
searchText->getSearchValidation &&
!(searchText->validateQuery)
) {
setState(_ => Loading)
let localResults: resultType = searchText->getLocalMatchedResults(hswitchTabs)
if localResults.results->Array.length > 0 {
results->Array.push(localResults)
}
if isShowRemoteResults {
getSearchResults(results)->ignore
} else {
let defaultItem = searchText->getDefaultResult
let finalResults = results->Array.length > 0 ? [defaultItem]->Array.concat(results) : []
setSearchResults(_ => finalResults)
setState(_ => Loaded)
}
} else {
setState(_ => Idle)
setSearchResults(_ => [])
}
None
}, [searchText])
let setFilterText = value => {
setActiveFilter(_ => value)
}
React.useEffect(_ => {
setSearchText(_ => "")
setLocalSearchText(_ => "")
setFilterText("")
setSelectedFilter(_ => None)
None
}, [showModal])
let onKeyPress = event => {
open ReactEvent.Keyboard
let metaKey = event->metaKey
let keyPressed = event->key
let ctrlKey = event->ctrlKey
let cmdKey = Window.Navigator.platform->String.includes("Mac")
if (
(cmdKey && metaKey && keyPressed == global_search_activate_key) ||
(ctrlKey && keyPressed == global_search_activate_key)
) {
setShowModal(_ => true)
event->preventDefault
}
}
React.useEffect(() => {
if userHasAccess(~groupAccess=AnalyticsView) === Access && version == V1 {
getCategoryOptions()->ignore
}
Window.addEventListener("keydown", onKeyPress)
Some(() => Window.removeEventListener("keydown", onKeyPress))
}, [])
let openModalOnClickHandler = _ => {
setShowModal(_ => true)
}
let setGlobalSearchText = ReactDebounce.useDebounced(value => {
setSearchText(_ => value)
}, ~wait=500)
let onFilterClicked = category => {
let newFilter = category.categoryType->getcategoryFromVariant
let lastString = searchText->getEndChar
if activeFilter->isNonEmptyString && lastString !== filterSeparator {
let end = searchText->String.length - activeFilter->String.length
let newText = searchText->String.substring(~start=0, ~end)
setLocalSearchText(_ => `${newText} ${newFilter}:`)
setFilterText(newFilter)
} else if lastString !== filterSeparator {
setLocalSearchText(_ => `${searchText} ${newFilter}:`)
setFilterText(newFilter)
}
revertFocus(~inputRef)
}
let onSuggestionClicked = option => {
let value = activeFilter->String.split(filterSeparator)->getValueFromArray(1, "")
let key = if value->isNonEmptyString {
let end = searchText->String.length - (value->String.length + 1)
searchText->String.substring(~start=0, ~end)
} else {
searchText
}
let saparater = searchText->getEndChar == filterSeparator ? "" : filterSeparator
setLocalSearchText(_ => `${key}${saparater}${option}`)
setFilterText("")
revertFocus(~inputRef)
}
React.useEffect(() => {
setGlobalSearchText(localSearchText)
None
}, [localSearchText])
let leftIcon = switch state {
| Loading =>
<div className="w-14 overflow-hidden mr-1">
<div className="w-24 -ml-5 ">
<Lottie animationData={loader} autoplay=true loop=true />
</div>
</div>
| _ =>
<div id="leftIcon" className="self-center py-3 pl-5 pr-4">
<Icon size=18 name="search" />
</div>
}
let viewType = getViewType(~state, ~searchResults)
let categorySuggestions = {getCategorySuggestions(categorieSuggestionResponse)}
<div className="w-max">
<SearchBox openModalOnClickHandler />
<RenderIf condition={showModal}>
<ModalWrapper showModal setShowModal>
<div className="w-full">
<ModalSearchBox
inputRef
leftIcon
setShowModal
setFilterText
localSearchText
setLocalSearchText
allOptions
selectedOption
setSelectedOption
allFilters
selectedFilter
setSelectedFilter
viewType
redirectOnSelect
activeFilter
onFilterClicked
onSuggestionClicked
categorySuggestions
searchText
/>
{switch viewType {
| Results | Load | EmptyResult =>
<SearchResultsComponent
searchResults
searchText
setShowModal
selectedOption
redirectOnSelect
categorySuggestions
activeFilter
setAllFilters
selectedFilter
setSelectedFilter
onFilterClicked
onSuggestionClicked
viewType
prefix
filtersEnabled
/>
| FiltersSugsestions =>
<RenderIf condition={filtersEnabled}>
<FilterResultsComponent
categorySuggestions
activeFilter
searchText
setAllFilters
selectedFilter
onFilterClicked
onSuggestionClicked
setSelectedFilter
/>
</RenderIf>
}}
</div>
</ModalWrapper>
</RenderIf>
</div>
}
| 2,157 | 9,767 |
hyperswitch-control-center | src/screens/Analytics/GlobalSearch/GlobalSearchTypes.res | .res | type section =
| Local
| PaymentIntents
| PaymentAttempts
| Refunds
| Disputes
| SessionizerPaymentAttempts
| SessionizerPaymentIntents
| SessionizerPaymentRefunds
| SessionizerPaymentDisputes
| Others
| Default
type metadataType = {
profileId: string,
orgId: string,
merchantId: string,
}
type element = {
texts: array<JSON.t>,
redirect_link: JSON.t,
}
type resultType = {
section: section,
results: array<element>,
total_results: int,
}
let getSectionHeader = section => {
switch section {
| Local => "Go To"
| PaymentIntents | SessionizerPaymentIntents => "Payment Intents"
| PaymentAttempts | SessionizerPaymentAttempts => "Payment Attempts"
| Refunds | SessionizerPaymentRefunds => "Refunds"
| Disputes | SessionizerPaymentDisputes => "Disputes"
| Others => "Others"
| Default => ""
}
}
let getSectionVariant = string => {
switch string {
| "payment_attempts" => PaymentAttempts
| "payment_intents" => PaymentIntents
| "refunds" => Refunds
| "disputes" => Disputes
| "sessionizer_payment_attempts" => SessionizerPaymentAttempts
| "sessionizer_payment_intents" => SessionizerPaymentIntents
| "sessionizer_refunds" => SessionizerPaymentRefunds
| "sessionizer_disputes" => SessionizerPaymentDisputes
| _ => Local
}
}
let getSectionIndex = string => {
switch string {
| PaymentAttempts => "payment_attempts"
| PaymentIntents => "payment_intents"
| Refunds => "refunds"
| Disputes => "disputes"
| SessionizerPaymentAttempts => "sessionizer_payment_attempts"
| SessionizerPaymentIntents => "sessionizer_payment_intents"
| SessionizerPaymentRefunds => "sessionizer_refunds"
| SessionizerPaymentDisputes => "sessionizer_disputes"
| _ => ""
}
}
type remoteResult = {
count: int,
hits: array<JSON.t>,
index: string,
}
type defaultResult = {
local_results: array<element>,
remote_results: array<remoteResult>,
searchText: string,
}
type state = Loading | Loaded | Idle
type category =
| Payment_Method
| Payment_Method_Type
| Connector
| Customer_Email
| Card_Network
| Card_Last_4
| Date
| Currency
| Status
| Payment_id
| Amount
type categoryOption = {
categoryType: category,
options: array<string>,
placeholder: string,
}
type viewType =
| Load
| Results
| FiltersSugsestions
| EmptyResult
| 647 | 9,768 |
hyperswitch-control-center | src/screens/Analytics/Logs/PaymentLogs/PaymentLogs.res | .res | @react.component
let make = (~paymentId, ~createdAt) => {
open LogTypes
open APIUtils
let getURL = useGetURL()
let apiLogsUrl = getURL(
~entityName=V1(API_EVENT_LOGS),
~methodType=Get,
~queryParamerters=Some(`type=Payment&payment_id=${paymentId}`),
)
let sdkLogsUrl = getURL(~entityName=V1(SDK_EVENT_LOGS), ~methodType=Post, ~id=Some(paymentId))
let startTime = createdAt->Date.fromString->Date.getTime -. 1000. *. 60. *. 5.
let startTime = startTime->Js.Date.fromFloat->Date.toISOString
let endTime = createdAt->Date.fromString->Date.getTime +. 1000. *. 60. *. 60. *. 3.
let endTime = endTime->Js.Date.fromFloat->Date.toISOString
let sdkPostBody = [
("paymentId", paymentId->JSON.Encode.string),
(
"timeRange",
[("startTime", startTime->JSON.Encode.string), ("endTime", endTime->JSON.Encode.string)]
->Dict.fromArray
->JSON.Encode.object,
),
]->LogicUtils.getJsonFromArrayOfJson
let webhookLogsUrl = getURL(
~entityName=V1(WEBHOOKS_EVENT_LOGS),
~methodType=Get,
~queryParamerters=Some(`payment_id=${paymentId}`),
)
let connectorLogsUrl = getURL(
~entityName=V1(CONNECTOR_EVENT_LOGS),
~methodType=Get,
~queryParamerters=Some(`type=Payment&payment_id=${paymentId}`),
)
let urls = [
{
url: apiLogsUrl,
apiMethod: Get,
},
{
url: sdkLogsUrl,
apiMethod: Post,
body: sdkPostBody,
},
{
url: webhookLogsUrl,
apiMethod: Get,
},
{
url: connectorLogsUrl,
apiMethod: Get,
},
]
<AuditLogUI id={paymentId} urls logType={#PAYMENT} />
}
| 481 | 9,769 |
hyperswitch-control-center | src/screens/Analytics/Logs/RefundLogs/RefundLogs.res | .res | @react.component
let make = (~refundId, ~paymentId) => {
open LogTypes
open APIUtils
let getURL = useGetURL()
let webhookLogsUrl = getURL(
~entityName=V1(WEBHOOKS_EVENT_LOGS),
~methodType=Get,
~queryParamerters=Some(`payment_id=${paymentId}&refund_id=${refundId}`),
)
let refundsLogsUrl = getURL(
~entityName=V1(API_EVENT_LOGS),
~methodType=Get,
~queryParamerters=Some(`type=Refund&payment_id=${paymentId}&refund_id=${refundId}`),
)
let connectorLogsUrl = getURL(
~entityName=V1(CONNECTOR_EVENT_LOGS),
~methodType=Get,
~queryParamerters=Some(`payment_id=${paymentId}&refund_id=${refundId}`),
)
let urls = [
{
url: refundsLogsUrl,
apiMethod: Get,
},
{
url: webhookLogsUrl,
apiMethod: Get,
},
{
url: connectorLogsUrl,
apiMethod: Get,
},
]
<AuditLogUI id={paymentId} urls logType={#REFUND} />
}
| 280 | 9,770 |
hyperswitch-control-center | src/screens/Analytics/Logs/LogUtils/AuditLogUI.res | .res | module LogDetailsSection = {
open LogTypes
open LogicUtils
@react.component
let make = (~logDetails) => {
let isValidNonEmptyValue = value => {
switch value->JSON.Classify.classify {
| Bool(_) | String(_) | Number(_) | Object(_) => true
| _ => false
}
}
<div className="pb-3 px-5 py-3">
{logDetails.data
->Dict.toArray
->Array.filter(item => {
let (key, value) = item
!(LogUtils.detailsSectionFilterKeys->Array.includes(key)) && value->isValidNonEmptyValue
})
->Array.map(item => {
let (key, value) = item
<div className="text-sm font-medium text-gray-700 flex">
<span className="w-2/5"> {key->snakeToTitle->React.string} </span>
<span
className="w-3/5 overflow-scroll cursor-pointer relative hover:bg-gray-50 p-1 rounded">
<ReactSyntaxHighlighter.SyntaxHighlighter
wrapLines={true}
wrapLongLines=true
style={ReactSyntaxHighlighter.lightfair}
language="json"
showLineNumbers={false}
lineNumberContainerStyle={{
paddingLeft: "0px",
backgroundColor: "red",
padding: "0px",
}}
customStyle={{
backgroundColor: "transparent",
fontSize: "0.875rem",
padding: "0px",
}}>
{value->JSON.stringify}
</ReactSyntaxHighlighter.SyntaxHighlighter>
</span>
</div>
})
->React.array}
</div>
}
}
module TabDetails = {
open LogTypes
@react.component
let make = (~activeTab, ~moduleName="", ~logDetails, ~selectedOption) => {
open LogicUtils
let id =
activeTab
->Option.getOr(["tab"])
->Array.reduce("", (acc, tabName) => {acc->String.concat(tabName)})
let currTab = activeTab->Option.getOr([])->Array.get(0)->Option.getOr("")
let tab =
<div>
{switch currTab->getLogTypefromString {
| Logdetails => <LogDetailsSection logDetails />
| Event
| Request =>
<div className="px-5 py-3">
<RenderIf condition={logDetails.request->isNonEmptyString}>
<div className="flex justify-end">
<HelperComponents.CopyTextCustomComp
displayValue=Some("")
copyValue={Some(logDetails.request)}
customTextCss="text-nowrap"
/>
</div>
<PrettyPrintJson jsonToDisplay=logDetails.request />
</RenderIf>
<RenderIf condition={logDetails.request->isEmptyString}>
<NoDataFound
customCssClass={"my-6"} message="No Data Available" renderType=Painting
/>
</RenderIf>
</div>
| Metadata
| Response =>
<div className="px-5 py-3">
<RenderIf
condition={logDetails.response->isNonEmptyString &&
selectedOption.optionType !== WEBHOOKS}>
<div className="flex justify-end">
<HelperComponents.CopyTextCustomComp
displayValue=Some("")
copyValue={Some(logDetails.response)}
customTextCss="text-nowrap"
/>
</div>
<PrettyPrintJson jsonToDisplay={logDetails.response} />
</RenderIf>
<RenderIf
condition={logDetails.response->isEmptyString ||
selectedOption.optionType === WEBHOOKS}>
<NoDataFound
customCssClass={"my-6"} message="No Data Available" renderType=Painting
/>
</RenderIf>
</div>
| _ => React.null
}}
</div>
<FramerMotion.TransitionComponent id={id}> {tab} </FramerMotion.TransitionComponent>
}
}
@react.component
let make = (~id, ~urls, ~logType: LogTypes.pageType) => {
open LogicUtils
open LogUtils
open LogTypes
open APIUtils
let {merchantId} =
CommonAuthHooks.useCommonAuthInfo()->Option.getOr(CommonAuthHooks.defaultAuthInfo)
let fetchDetails = useGetMethod(~showErrorToast=false)
let fetchPostDetils = useUpdateMethod()
let (data, setData) = React.useState(_ => [])
let isError = React.useMemo(() => {ref(false)}, [])
let (logDetails, setLogDetails) = React.useState(_ => {
response: "",
request: "",
data: Dict.make(),
})
let (selectedOption, setSelectedOption) = React.useState(_ => {
value: 0,
optionType: API_EVENTS,
})
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (collapseTab, setCollapseTab) = React.useState(_ => false)
let (activeTab, setActiveTab) = React.useState(_ => ["Log Details"])
let tabKeys = tabkeys->Array.map(item => {
item->getTabKeyName(selectedOption.optionType)
})
let tabValues = tabKeys->Array.map(key => {
let a: DynamicTabs.tab = {
title: key,
value: key,
isRemovable: false,
}
a
})
React.useEffect(_ => {
setActiveTab(_ => ["Log Details"])
setCollapseTab(prev => !prev)
None
}, [logDetails])
let activeTab = React.useMemo(() => {
Some(activeTab)
}, [activeTab])
let setActiveTab = React.useMemo(() => {
(str: string) => {
setActiveTab(_ => str->String.split(","))
}
}, [setActiveTab])
let getDetails = async () => {
let logs = []
if !(id->HSwitchOrderUtils.isTestData) {
let promiseArr = urls->Array.map(url => {
switch url.apiMethod {
| Post => {
let body = switch url.body {
| Some(val) => val
| _ => Dict.make()->JSON.Encode.object
}
fetchPostDetils(url.url, body, Post)
}
| _ => fetchDetails(url.url)
}
})
let resArr = await PromiseUtils.allSettledPolyfill(promiseArr)
resArr->Array.forEach(json => {
// clasify btw json value and error response
switch JSON.Classify.classify(json) {
| Array(arr) =>
// add to the logs only if array is non empty
switch arr->Array.get(0) {
| Some(dict) =>
switch dict->getDictFromJsonObject->getLogType {
| SDK => logs->Array.pushMany(arr->parseSdkResponse)->ignore
| CONNECTOR | API_EVENTS | WEBHOOKS => logs->Array.pushMany(arr)->ignore
}
| _ => ()
}
| String(_) => isError.contents = true
| _ => ()
}
})
if logs->Array.length === 0 && isError.contents {
setScreenState(_ => PageLoaderWrapper.Error("Failed to Fetch!"))
} else {
setScreenState(_ => PageLoaderWrapper.Success)
logs->Array.sort(sortByCreatedAt)
setData(_ => logs)
switch logs->Array.get(0) {
| Some(value) => {
let initialData = value->getDictFromJsonObject
initialData->setDefaultValue(setLogDetails, setSelectedOption)
}
| _ => ()
}
}
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
}
React.useEffect(() => {
getDetails()->ignore
None
}, [])
let prevLogType = ref("")
let timeLine =
<div className="flex flex-col w-2/5 overflow-y-scroll no-scrollbar pt-7 pl-5">
<div className="flex flex-col">
{data
->Array.mapWithIndex((detailsValue, index) => {
let showLogType =
prevLogType.contents !== detailsValue->getDictFromJsonObject->getLogType->getTagName
prevLogType := detailsValue->getDictFromJsonObject->getLogType->getTagName
<ApiDetailsComponent
key={index->Int.toString}
dataDict={detailsValue->getDictFromJsonObject}
setLogDetails
setSelectedOption
selectedOption
index
logsDataLength={data->Array.length - 1}
getLogType
nameToURLMapper={nameToURLMapper(~id={id}, ~merchantId)}
filteredKeys
showLogType
/>
})
->React.array}
</div>
</div>
let codeBlock =
<RenderIf
condition={logDetails.response->isNonEmptyString || logDetails.request->isNonEmptyString}>
<div
className="flex flex-col gap-4 border-l-2 border-border-light-grey show-scrollbar scroll-smooth overflow-scroll w-3/5">
<div className="sticky top-0 bg-white z-10">
<DynamicTabs
tabs=tabValues
maxSelection=1
setActiveTab
initalTab=tabKeys
tabContainerClass="px-2"
updateCollapsableTabs=collapseTab
showAddMoreTabs=false
/>
</div>
<TabDetails activeTab logDetails selectedOption />
</div>
</RenderIf>
open OrderUtils
<PageLoaderWrapper
screenState
customLoader={<p className=" text-center text-sm text-jp-gray-900">
{"Crunching the latest data…"->React.string}
</p>}
customUI={<NoDataFound
message={`No logs available for this ${(logType :> string)->String.toLowerCase}`}
/>}>
{<>
<RenderIf condition={id->HSwitchOrderUtils.isTestData || data->Array.length === 0}>
<div
className="flex items-center gap-2 bg-white w-full border-2 p-3 !opacity-100 rounded-lg text-md font-medium">
<Icon name="info-circle-unfilled" size=16 />
<div className={`text-lg font-medium opacity-50`}>
{`No logs available for this ${(logType :> string)->String.toLowerCase}`->React.string}
</div>
</div>
</RenderIf>
<RenderIf condition={!(id->HSwitchOrderUtils.isTestData || data->Array.length === 0)}>
<Section
customCssClass={`bg-white dark:bg-jp-gray-lightgray_background rounded-md pt-2 pb-4 flex gap-7 justify-between h-48-rem !max-h-50-rem !min-w-[55rem] max-w-[72rem] overflow-scroll`}>
{timeLine}
{codeBlock}
</Section>
</RenderIf>
</>}
</PageLoaderWrapper>
}
| 2,397 | 9,771 |
hyperswitch-control-center | src/screens/Analytics/Logs/LogUtils/ApiDetailsComponent.res | .res | open LogicUtils
open LogTypes
@react.component
let make = (
~dataDict,
~setLogDetails,
~selectedOption,
~setSelectedOption,
~index,
~logsDataLength,
~getLogType,
~nameToURLMapper,
~filteredKeys=[],
~showLogType=true,
) => {
let {globalUIConfig: {border: {borderColor}}} = React.useContext(ThemeProvider.themeContext)
let headerStyle = "text-sm font-medium text-gray-700 break-all"
let logType = dataDict->getLogType
let apiName = switch logType {
| API_EVENTS => dataDict->getString("api_flow", "default value")->camelCaseToTitle
| SDK => dataDict->getString("event_name", "default value")
| CONNECTOR =>
dataDict->getString("flow", "default value")->LogUtils.apiNameMapper->camelCaseToTitle
| WEBHOOKS => dataDict->getString("event_type", "default value")->snakeToTitle
}->nameToURLMapper
let createdTime = dataDict->getString("created_at", "00000")
let requestObject = switch logType {
| API_EVENTS | CONNECTOR => dataDict->getString("request", "")
| SDK =>
dataDict
->Dict.toArray
->Array.filter(entry => {
let (key, _) = entry
filteredKeys->Array.includes(key)->not
})
->getJsonFromArrayOfJson
->JSON.stringify
| WEBHOOKS => dataDict->getString("content", "")
}
let responseObject = switch logType {
| API_EVENTS => dataDict->getString("response", "")
| CONNECTOR => dataDict->getString("masked_response", "")
| SDK => {
let isErrorLog = dataDict->getString("log_type", "") === "ERROR"
isErrorLog ? dataDict->getString("value", "") : ""
}
| WEBHOOKS => dataDict->getString("outgoing_webhook_event_type", "")
}
let statusCode = switch logType {
| API_EVENTS | CONNECTOR => dataDict->getInt("status_code", 200)->Int.toString
| SDK => dataDict->getString("log_type", "INFO")
| WEBHOOKS => dataDict->getBool("is_error", false) ? "500" : "200"
}
let method = switch logType {
| API_EVENTS => dataDict->getString("http_method", "")
| CONNECTOR => dataDict->getString("method", "")
| SDK => ""
| WEBHOOKS => "POST"
}
let statusCodeTextColor = switch logType {
| SDK =>
switch statusCode {
| "INFO" => "blue-500"
| "ERROR" => "red-400"
| "WARNING" => "yellow-800"
| _ => "gray-700 opacity-50"
}
| WEBHOOKS =>
switch statusCode {
| "200" => "green-700"
| "500" | _ => "gray-700 opacity-50"
}
| API_EVENTS | CONNECTOR =>
switch statusCode {
| "200" => "green-700"
| "500" => "gray-700 opacity-50"
| "400" | "422" => "orange-950"
| _ => "gray-700 opacity-50"
}
}
let statusCodeBg = switch logType {
| SDK =>
switch statusCode {
| "INFO" => "blue-100"
| "ERROR" => "red-100"
| "WARNING" => "yellow-100"
| _ => "gray-100"
}
| WEBHOOKS =>
switch statusCode {
| "200" => "green-50"
| "500" | _ => "gray-100"
}
| API_EVENTS | CONNECTOR =>
switch statusCode {
| "200" => "green-50"
| "500" => "gray-100"
| "400" | "422" => "orange-100"
| _ => "gray-100"
}
}
let isSelected = selectedOption.value === index
let stepperColor = isSelected
? switch logType {
| SDK =>
switch statusCode {
| "INFO" => "blue-500"
| "ERROR" => "red-400"
| "WARNING" => "yellow-300"
| _ => "gray-700 opacity-50"
}
| WEBHOOKS =>
switch statusCode {
| "200" => "green-700"
| "500" | _ => "gray-700 opacity-50"
}
| API_EVENTS | CONNECTOR =>
switch statusCode {
| "200" => "green-700"
| "500" => "gray-700 opacity-50"
| "400" | "422" => "orange-950"
| _ => "gray-700 opacity-50"
}
}
: "gray-200"
let stepperBorderColor = isSelected
? switch logType {
| SDK =>
switch statusCode {
| "INFO" => "blue-500"
| "ERROR" => "red-400"
| "WARNING" => "orange-500"
| _ => "gray-600"
}
| WEBHOOKS =>
switch statusCode {
| "200" => "green-700"
| "500" | _ => "gray-700 opacity-50"
}
| API_EVENTS | CONNECTOR =>
switch statusCode {
| "200" => "green-700"
| "500" => "gray-600"
| "400" | "422" => "orange-950"
| _ => "gray-600"
}
}
: "gray-200"
let statusCodeBorderColor = switch logType {
| SDK =>
switch statusCode {
| "INFO" => `${borderColor.primaryNormal}`
| "ERROR" => "border border-red-400"
| "WARNING" => "border border-yellow-800"
| _ => "border border-gray-700 opacity-50"
}
| WEBHOOKS =>
switch statusCode {
| "200" => "border border-green-700"
| "500" | _ => "border border-gray-700 opacity-80"
}
| API_EVENTS | CONNECTOR =>
switch statusCode {
| "200" => "border border-green-700"
| "500" => "border border-gray-700 opacity-50"
| "400" | "422" => "border border-orange-950"
| _ => "border border-gray-700 opacity-50"
}
}
let borderClass = isSelected ? `${statusCodeBorderColor} rounded-md` : "border border-transparent"
let iconName = switch logType {
| SDK => "desktop"
| WEBHOOKS => "anchor"
| API_EVENTS => "api-icon"
| CONNECTOR => "connector-icon"
}
<div className="flex items-start gap-4">
<div className="flex flex-col items-center h-full my-4 relative">
<RenderIf condition={showLogType}>
<Icon name=iconName size=12 className="text-jp-gray-900" />
<div
className={`h-full border-${stepperBorderColor} border-dashed rounded divide-x-2 border-2 my-1`}
/>
</RenderIf>
<div className={`w-fit h-fit p-1 border rounded-md bg-${stepperColor} border-gray-300`} />
<div
className={`h-full border-${stepperBorderColor} border-dashed rounded divide-x-2 border-2 my-1`}
/>
<RenderIf condition={index === logsDataLength}>
<div className={`w-fit h-fit p-1 border rounded-md bg-${stepperColor} border-gray-300`} />
</RenderIf>
</div>
<div className="flex flex-col gap-3 w-full">
<RenderIf condition={showLogType}>
<span
className={`text-base font-bold break-all flex gap-1 leading-none my-4 text-jp-gray-900`}>
{`${logType->getTagName}`->React.string}
</span>
</RenderIf>
<div
className={`flex gap-6 items-start w-full py-3 px-3 cursor-pointer ${borderClass} mb-6
`}
key={selectedOption.value->Int.toString}
onClick={_ => {
setLogDetails(_ => {
response: responseObject,
request: requestObject,
data: dataDict,
})
setSelectedOption(_ => {
value: index,
optionType: logType,
})
}}>
<div className="flex flex-col gap-1">
<div className="flex gap-3">
<div className={`bg-${statusCodeBg} h-fit w-fit px-2 py-1 rounded-md`}>
<p className={`text-${statusCodeTextColor} text-sm font-bold `}>
{statusCode->React.string}
</p>
</div>
{switch logType {
| SDK =>
<p className={`${headerStyle} mt-1 ${isSelected ? "" : "opacity-80"}`}>
{apiName->String.toLowerCase->snakeToTitle->React.string}
</p>
| API_EVENTS | WEBHOOKS | CONNECTOR =>
<p className={`${headerStyle} ${isSelected ? "" : "opacity-80"}`}>
<span className="mr-3 border-2 px-1 py-0.5 rounded text-sm">
{method->String.toUpperCase->React.string}
</span>
<span className="leading-7"> {apiName->React.string} </span>
</p>
}}
</div>
<div className={`${headerStyle} opacity-40 flex gap-1`}>
{createdTime->Js.Date.fromString->Js.Date.toUTCString->React.string}
</div>
</div>
</div>
</div>
</div>
}
| 2,370 | 9,772 |
hyperswitch-control-center | src/screens/Analytics/Logs/LogUtils/LogsWrapper.res | .res | module EventLogMobileView = {
@react.component
let make = (~wrapperFor: LogTypes.pageType) => {
<>
<div className="font-bold text-lg mb-5"> {"Events and logs"->React.string} </div>
<div
className="flex items-center gap-2 bg-white w-fit border-2 p-3 !opacity-100 rounded-lg text-md font-medium">
<Icon name="info-circle-unfilled" size=16 />
<div className={`text-lg font-medium opacity-50`}>
{`To view logs for this ${(wrapperFor :> string)->String.toLowerCase} please switch to desktop mode`->React.string}
</div>
</div>
</>
}
}
@react.component
let make = (~wrapperFor, ~children) => {
let {auditTrail} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let isSmallDevice = MatchMedia.useMatchMedia("(max-width: 700px)")
<div className="overflow-x-scroll">
<RenderIf condition={isSmallDevice}>
<EventLogMobileView wrapperFor />
</RenderIf>
<RenderIf condition={!isSmallDevice && auditTrail}> {children} </RenderIf>
</div>
}
| 280 | 9,773 |
hyperswitch-control-center | src/screens/Analytics/Logs/LogUtils/LogUtils.res | .res | let sortByCreatedAt = (log1, log2) => {
open LogicUtils
let getKey = dict => dict->getDictFromJsonObject->getString("created_at", "")->Date.fromString
let keyA = log1->getKey
let keyB = log2->getKey
compareLogic(keyA, keyB)
}
type flowType =
| PaymentsCancel
| PaymentsCapture
| PaymentsConfirm
| PaymentsCreate
| PaymentsStart
| PaymentsUpdate
| RefundsCreate
| RefundsUpdate
| DisputesEvidenceSubmit
| AttachDisputeEvidence
| RetrieveDisputeEvidence
| IncomingWebhookReceive
| NotDefined
let itemToObjMapper = flowString => {
switch flowString {
| "PaymentsCancel" => PaymentsCancel
| "PaymentsCapture" => PaymentsCapture
| "PaymentsConfirm" => PaymentsConfirm
| "PaymentsCreate" => PaymentsCreate
| "PaymentsStart" => PaymentsStart
| "PaymentsUpdate" => PaymentsUpdate
| "RefundsCreate" => RefundsCreate
| "RefundsUpdate" => RefundsUpdate
| "DisputesEvidenceSubmit" => DisputesEvidenceSubmit
| "AttachDisputeEvidence" => AttachDisputeEvidence
| "RetrieveDisputeEvidence" => RetrieveDisputeEvidence
| "IncomingWebhookReceive" => IncomingWebhookReceive
| _ => NotDefined
}
}
// will be removed once the backend does the URl mapping
let nameToURLMapper = (~id, ~merchantId) => {
urlName =>
switch urlName->itemToObjMapper {
| PaymentsCancel => `/payments/${id}/cancel`
| PaymentsCapture => `/payments/${id}/capture`
| PaymentsConfirm => `/payments/${id}/confirm`
| PaymentsCreate => "/payments"
| PaymentsStart => `/payments/redirect/${id}/${merchantId}`
| PaymentsUpdate => `/payments/${id}`
| RefundsCreate => "/refunds"
| RefundsUpdate => `/refunds/${id}`
| DisputesEvidenceSubmit | AttachDisputeEvidence => "/disputes/evidence"
| RetrieveDisputeEvidence => `/disputes/evidence/${id}`
| IncomingWebhookReceive | NotDefined => urlName
}
}
let filteredKeys = [
"value",
"merchant_id",
"created_at_precise",
"component",
"platform",
"version",
]
let detailsSectionFilterKeys = [
"content",
"created_at",
"event_type",
"flow_type",
"api_flow",
"request",
"response",
"user_agent",
"ip_addr",
"flow",
"masked_response",
"http_method",
"hs_latency",
"status_code",
]
@module("js-sha256") external sha256: string => string = "sha256"
let parseSdkResponse = arr => {
open LogicUtils
let sourceMapper = source => {
switch source {
| "ORCA-LOADER" => "HYPERLOADER"
| "ORCA-PAYMENT-PAGE"
| "STRIPE_PAYMENT_SHEET" => "PAYMENT_SHEET"
| other => other
}
}
let sdkLogsArray = arr->Array.map(event => {
let eventDict = event->getDictFromJsonObject
let eventName = eventDict->getString("event_name", "")
let timestamp = eventDict->getString("created_at_precise", "")
let logType = eventDict->getString("log_type", "")
let updatedEventName =
logType === "INFO" ? eventName->String.replace("Call", "Response") : eventName
eventDict->Dict.set("event_name", updatedEventName->JSON.Encode.string)
eventDict->Dict.set("event_id", sha256(updatedEventName ++ timestamp)->JSON.Encode.string)
eventDict->Dict.set(
"source",
eventDict->getString("source", "")->sourceMapper->JSON.Encode.string,
)
eventDict->Dict.set(
"checkout_platform",
eventDict->getString("component", "")->JSON.Encode.string,
)
eventDict->Dict.set("customer_device", eventDict->getString("platform", "")->JSON.Encode.string)
eventDict->Dict.set("sdk_version", eventDict->getString("version", "")->JSON.Encode.string)
eventDict->Dict.set("event_name", updatedEventName->JSON.Encode.string)
eventDict->Dict.set("created_at", timestamp->JSON.Encode.string)
eventDict->JSON.Encode.object
})
let logsArr = sdkLogsArray->Array.filter(sdkLog => {
let eventDict = sdkLog->getDictFromJsonObject
let eventName = eventDict->getString("event_name", "")
let filteredEventNames = ["OrcaElementsCalled"]
filteredEventNames->Array.includes(eventName)->not
})
logsArr
}
let apiNameMapper = apiName => {
switch apiName {
| "PSync" => "Payments Sync"
| _ => apiName
}
}
| 1,107 | 9,774 |
hyperswitch-control-center | src/screens/Analytics/Logs/LogUtils/PrettyPrintJson.res | .res | open LogicUtils
@react.component
let make = (
~jsonToDisplay,
~headerText=None,
~maxHeightClass="max-h-25-rem",
~overrideBackgroundColor="bg-hyperswitch_background",
) => {
let showToast = ToastState.useShowToast()
let (parsedJson, setParsedJson) = React.useState(_ => "")
let parseJsonValue = () => {
try {
let parsedValue = jsonToDisplay->JSON.parseExn->JSON.stringifyWithIndent(3)
setParsedJson(_ => parsedValue)
} catch {
| _ => setParsedJson(_ => jsonToDisplay)
}
}
React.useEffect(() => {
parseJsonValue()->ignore
None
}, [jsonToDisplay])
let handleOnClickCopy = (~parsedValue) => {
Clipboard.writeText(parsedValue)
showToast(~message="Copied to Clipboard!", ~toastType=ToastSuccess)
}
let copyParsedJson =
<div onClick={_ => handleOnClickCopy(~parsedValue=parsedJson)} className="cursor-pointer">
<Icon name="nd-copy" />
</div>
<div className="flex flex-col gap-2">
<RenderIf condition={parsedJson->isNonEmptyString}>
{<>
<RenderIf condition={headerText->Option.isSome}>
<div className="flex justify-between items-center">
<p className="font-bold text-fs-16 text-jp-gray-900 text-opacity-75">
{headerText->Option.getOr("")->React.string}
</p>
{copyParsedJson}
</div>
</RenderIf>
<div className="overflow-auto">
<ReactSyntaxHighlighter.SyntaxHighlighter
style={ReactSyntaxHighlighter.lightfair}
language="json"
showLineNumbers={true}
lineNumberContainerStyle={{
paddingLeft: "0px",
backgroundColor: "red",
padding: "100px",
}}
customStyle={{
backgroundColor: "transparent",
lineHeight: "1.7rem",
fontSize: "0.875rem",
padding: "5px",
}}>
{parsedJson}
</ReactSyntaxHighlighter.SyntaxHighlighter>
</div>
</>}
</RenderIf>
<RenderIf condition={parsedJson->isEmptyString}>
<div className="flex flex-col justify-start items-start gap-2 h-25-rem">
<p className="font-bold text-fs-16 text-jp-gray-900 text-opacity-75">
{headerText->Option.getOr("")->React.string}
</p>
<p className="font-normal text-fs-14 text-jp-gray-900 text-opacity-50">
{"Failed to load!"->React.string}
</p>
</div>
</RenderIf>
</div>
}
| 623 | 9,775 |
hyperswitch-control-center | src/screens/Analytics/Logs/LogUtils/LogTypes.res | .res | type logType = SDK | API_EVENTS | WEBHOOKS | CONNECTOR
type pageType = [#PAYMENT | #REFUND | #DISPUTE]
type eventLogs = Logdetails | Request | Response | Event | Metadata | Unknown
type logDetails = {
response: string,
request: string,
data: Dict.t<JSON.t>,
}
type selectedObj = {
value: int,
optionType: logType,
}
let tabkeys: array<eventLogs> = [Logdetails, Request, Response]
let getLogType = dict => {
if dict->Dict.get("connector_name")->Option.isSome {
CONNECTOR
} else if dict->Dict.get("request_id")->Option.isSome {
API_EVENTS
} else if dict->Dict.get("component")->Option.isSome {
SDK
} else {
WEBHOOKS
}
}
let getTagName = tag => {
switch tag {
| SDK => "SDK"
| API_EVENTS => "API"
| WEBHOOKS => "WEBHOOKS"
| CONNECTOR => "CONNECTOR"
}
}
let getTabKeyName = (key: eventLogs, option: logType) => {
switch option {
| SDK =>
switch key {
| Logdetails => "Log Details"
| Request => "Event"
| Response => "Metadata"
| _ => ""
}
| _ =>
switch key {
| Logdetails => "Log Details"
| Request => "Request"
| Response => "Response"
| _ => ""
}
}
}
let getLogTypefromString = log => {
switch log {
| "Log Details" => Logdetails
| "Request" => Request
| "Response" => Response
| "Event" => Event
| "Metadata" => Metadata
| _ => Unknown
}
}
let setDefaultValue = (initialData, setLogDetails, setSelectedOption) => {
open LogicUtils
switch initialData->getLogType {
| API_EVENTS => {
let request = initialData->getString("request", "")
let response = initialData->getString("response", "")
setLogDetails(_ => {
response,
request,
data: initialData,
})
setSelectedOption(_ => {
value: 0,
optionType: API_EVENTS,
})
}
| SDK => {
let request =
initialData
->Dict.toArray
->Array.filter(entry => {
let (key, _) = entry
LogUtils.filteredKeys->Array.includes(key)->not
})
->getJsonFromArrayOfJson
->JSON.stringify
let response =
initialData->getString("log_type", "") === "ERROR"
? initialData->getString("value", "")
: ""
setLogDetails(_ => {
response,
request,
data: initialData,
})
setSelectedOption(_ => {
value: 0,
optionType: SDK,
})
}
| CONNECTOR => {
let request = initialData->getString("request", "")
let response = initialData->getString("masked_response", "")
setLogDetails(_ => {
response,
request,
data: initialData,
})
setSelectedOption(_ => {
value: 0,
optionType: CONNECTOR,
})
}
| WEBHOOKS => {
let request = initialData->getString("content", "")
let response = initialData->getString("outgoing_webhook_event_type", "")
setLogDetails(_ => {
response,
request,
data: initialData,
})
setSelectedOption(_ => {
value: 0,
optionType: WEBHOOKS,
})
}
}
}
type urls = {
url: string,
apiMethod: Fetch.requestMethod,
body?: JSON.t,
}
| 824 | 9,776 |
hyperswitch-control-center | src/screens/Analytics/Logs/DisputeLogs/DisputeLogs.res | .res | @react.component
let make = (~paymentId, ~disputeId) => {
open LogTypes
open APIUtils
let getURL = useGetURL()
let webhookLogsUrl = getURL(
~entityName=V1(WEBHOOKS_EVENT_LOGS),
~methodType=Get,
~queryParamerters=Some(`payment_id=${paymentId}&dispute_id=${disputeId}`),
)
let disputesLogsUrl = getURL(
~entityName=V1(API_EVENT_LOGS),
~methodType=Get,
~queryParamerters=Some(`type=Dispute&payment_id=${paymentId}&dispute_id=${disputeId}`),
)
let connectorLogsUrl = getURL(
~entityName=V1(CONNECTOR_EVENT_LOGS),
~methodType=Get,
~queryParamerters=Some(`payment_id=${paymentId}&dispute_id=${disputeId}`),
)
let urls = [
{
url: disputesLogsUrl,
apiMethod: Get,
},
{
url: webhookLogsUrl,
apiMethod: Get,
},
{
url: connectorLogsUrl,
apiMethod: Get,
},
]
<AuditLogUI id={paymentId} urls logType={#DISPUTE} />
}
| 287 | 9,777 |
hyperswitch-control-center | src/screens/Analytics/DisputeAnalytics/DisputeAnalytics.res | .res | open DisputeAnalyticsEntity
open APIUtils
open HSAnalyticsUtils
@react.component
let make = () => {
let getURL = useGetURL()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (metrics, setMetrics) = React.useState(_ => [])
let (dimensions, setDimensions) = React.useState(_ => [])
let fetchDetails = useGetMethod()
let loadInfo = async () => {
setScreenState(_ => PageLoaderWrapper.Loading)
open LogicUtils
try {
let infoUrl = getURL(~entityName=V1(ANALYTICS_DISPUTES), ~methodType=Get, ~id=Some("dispute"))
let infoDetails = await fetchDetails(infoUrl)
let metrics =
infoDetails
->getDictFromJsonObject
->getArrayFromDict("metrics", [])
->AnalyticsUtils.filterMetrics
setMetrics(_ => metrics)
setDimensions(_ => infoDetails->getDictFromJsonObject->getArrayFromDict("dimensions", []))
setScreenState(_ => PageLoaderWrapper.Success)
} catch {
| Exn.Error(e) =>
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
React.useEffect(() => {
loadInfo()->ignore
None
}, [])
let tabKeys = getStringListFromArrayDict(dimensions)
let tabValues = tabKeys->Array.mapWithIndex((key, index) => {
let a: DynamicTabs.tab = {
title: key->LogicUtils.snakeToTitle,
value: key,
isRemovable: index > 2,
}
a
})
let title = "Disputes Analytics"
let analyticsfilterUrl = getURL(
~entityName=V1(ANALYTICS_FILTERS),
~methodType=Post,
~id=Some(domain),
)
let disputeAnalyticsUrl = getURL(
~entityName=V1(ANALYTICS_PAYMENTS),
~methodType=Post,
~id=Some(domain),
)
<PageLoaderWrapper screenState customUI={<NoData title />}>
<Analytics
pageTitle=title
filterUri=Some(analyticsfilterUrl)
key="DisputesAnalytics"
moduleName="Disputes"
deltaMetrics={getStringListFromArrayDict(metrics)}
chartEntity={default: chartEntity(tabKeys, ~uri=disputeAnalyticsUrl)}
tabKeys
tabValues
options
singleStatEntity={getSingleStatEntity(metrics, ~uri=disputeAnalyticsUrl)}
getTable={getDisputeTable}
colMapper
tableEntity={disputeTableEntity(~uri=disputeAnalyticsUrl)}
defaultSort="total_volume"
deltaArray=[]
tableUpdatedHeading=getUpdatedHeading
tableGlobalFilter=filterByData
startTimeFilterKey
endTimeFilterKey
initialFilters=initialFilterFields
initialFixedFilters=initialFixedFilterFields
/>
</PageLoaderWrapper>
}
| 664 | 9,778 |
hyperswitch-control-center | src/screens/Analytics/DisputeAnalytics/DisputeAnalyticsEntity.res | .res | type pageStateType = Loading | Failed | Success | NoData
open LogicUtils
open DynamicSingleStat
open HSAnalyticsUtils
open AnalyticsTypes
let domain = "disputes"
let makeMultiInputFieldInfo = FormRenderer.makeMultiInputFieldInfo
let makeInputFieldInfo = FormRenderer.makeInputFieldInfo
let colMapper = (col: disputeColType) => {
switch col {
| Connector => "connector"
| DisputeStage => "dispute_stage"
| TotalAmountDisputed => "total_amount_disputed"
| TotalDisputeLostAmount => "total_dispute_lost_amount"
| NoCol => ""
}
}
let reverseColMapper = (column: string) => {
switch column {
| "total_amount_disputed" => TotalAmountDisputed
| "total_dispute_lost_amount" => TotalDisputeLostAmount
| "connector" => Connector
| "dispute_stage" => DisputeStage
| _ => NoCol
}
}
let percentFormat = value => {
`${value->Float.toFixedWithPrecision(~digits=2)}%`
}
let distribution =
[
("distributionFor", "dispute_error_message"->JSON.Encode.string),
("distributionCardinality", "TOP_5"->JSON.Encode.string),
]->LogicUtils.getJsonFromArrayOfJson
let tableItemToObjMapper: Dict.t<JSON.t> => disputeTableType = dict => {
{
connector: dict->getString(Connector->colMapper, "NA"),
dispute_stage: dict->getString(DisputeStage->colMapper, "NA"),
total_amount_disputed: dict->getFloat(TotalAmountDisputed->colMapper, 0.0),
total_dispute_lost_amount: dict->getFloat(TotalDisputeLostAmount->colMapper, 0.0),
}
}
let getUpdatedHeading = (~item as _, ~dateObj as _) => {
let getHeading = colType => {
let key = colType->colMapper
switch colType {
| Connector => Table.makeHeaderInfo(~key, ~title="Connector", ~dataType=NumericType)
| DisputeStage => Table.makeHeaderInfo(~key, ~title="Dispute Stage", ~dataType=NumericType)
| TotalAmountDisputed =>
Table.makeHeaderInfo(~key, ~title="Total Amount Disputed", ~dataType=NumericType)
| TotalDisputeLostAmount =>
Table.makeHeaderInfo(~key, ~title="Total Dispute Lost Amount", ~dataType=NumericType)
| NoCol => Table.makeHeaderInfo(~key, ~title="")
}
}
getHeading
}
let getCell = (disputeTable: disputeTableType, colType): Table.cell => {
let usaNumberAbbreviation = labelValue => {
shortNum(~labelValue, ~numberFormat=getDefaultNumberFormat())
}
switch colType {
| TotalAmountDisputed =>
Numeric(disputeTable.total_amount_disputed /. 100.00, usaNumberAbbreviation)
| TotalDisputeLostAmount =>
Numeric(disputeTable.total_dispute_lost_amount /. 100.00, usaNumberAbbreviation)
| Connector => Text(disputeTable.connector)
| DisputeStage => Text(disputeTable.dispute_stage)
| NoCol => Text("")
}
}
let getDisputeTable: JSON.t => array<disputeTableType> = json => {
json
->LogicUtils.getArrayFromJson([])
->Array.map(item => {
tableItemToObjMapper(item->getDictFromJsonObject)
})
}
let makeFieldInfo = FormRenderer.makeFieldInfo
let disputeTableEntity = (~uri) =>
EntityType.makeEntity(
~uri,
~getObjects=getDisputeTable,
~dataKey="queryData",
~defaultColumns=defaultDisputeColumns,
~requiredSearchFieldsList=[startTimeFilterKey, endTimeFilterKey],
~allColumns=allDisputeColumns,
~getCell,
~getHeading=getUpdatedHeading(~item=None, ~dateObj=None),
)
let singleStateInitialValue = {
total_amount_disputed: 0.0,
total_dispute_lost_amount: 0.0,
}
let singleStateSeriesInitialValue = {
total_amount_disputed: 0.0,
total_dispute_lost_amount: 0.0,
time_series: "",
}
let singleStateItemToObjMapper = json => {
json
->JSON.Decode.object
->Option.map(dict => {
total_amount_disputed: dict->getFloat("total_amount_disputed", 0.0),
total_dispute_lost_amount: dict->getFloat("total_dispute_lost_amount", 0.0),
})
->Option.getOr({
singleStateInitialValue
})
}
let singleStateSeriesItemToObjMapper = json => {
json
->JSON.Decode.object
->Option.map(dict => {
total_amount_disputed: dict->getFloat("total_amount_disputed", 0.0),
total_dispute_lost_amount: dict->getFloat("total_dispute_lost_amount", 0.0),
time_series: dict->getString("time_bucket", ""),
})
->Option.getOr({
singleStateSeriesInitialValue
})
}
let itemToObjMapper = json => {
json->getQueryData->Array.map(singleStateItemToObjMapper)
}
let timeSeriesObjMapper = json =>
json->getQueryData->Array.map(json => singleStateSeriesItemToObjMapper(json))
type colT =
| TotalAmountDisputed
| TotalDisputeLostAmount
let getColumns = [
{
sectionName: "",
columns: [TotalAmountDisputed, TotalDisputeLostAmount]->generateDefaultStateColumns,
},
]
let compareLogic = (firstValue, secondValue) => {
let (temp1, _) = firstValue
let (temp2, _) = secondValue
if temp1 == temp2 {
0
} else if temp1 > temp2 {
-1
} else {
1
}
}
let constructData = (
key,
singlestatTimeseriesData: array<AnalyticsTypes.disputeSingleSeriesState>,
) => {
switch key {
| "total_amount_disputed" =>
singlestatTimeseriesData->Array.map(ob => (
ob.time_series->DateTimeUtils.parseAsFloat,
ob.total_amount_disputed /. 100.00,
))
| "total_dispute_lost_amount" =>
singlestatTimeseriesData->Array.map(ob => (
ob.time_series->DateTimeUtils.parseAsFloat,
ob.total_dispute_lost_amount /. 100.00,
))
| _ => []
}
}
let getStatData = (
singleStatData: disputeSingleStateType,
timeSeriesData: array<disputeSingleSeriesState>,
deltaTimestampData: DynamicSingleStat.deltaRange,
colType,
_mode,
) => {
switch colType {
| TotalAmountDisputed => {
title: `Total Amount Disputed`,
tooltipText: "Total amount that is disputed",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.total_amount_disputed /. 100.00,
deltaTimestampData.currentSr,
),
value: singleStatData.total_amount_disputed /. 100.00,
delta: {
Js.Float.fromString(
Float.toFixedWithPrecision(singleStatData.total_amount_disputed /. 100.00, ~digits=2),
)
},
data: constructData("total_amount_disputed", timeSeriesData),
statType: "Volume",
showDelta: false,
}
| TotalDisputeLostAmount => {
title: `Total Dispute Lost Amount`,
tooltipText: "Total amount lost due to a dispute",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.total_dispute_lost_amount /. 100.00,
deltaTimestampData.currentSr,
),
value: singleStatData.total_dispute_lost_amount /. 100.00,
delta: {
Js.Float.fromString(
Float.toFixedWithPrecision(singleStatData.total_dispute_lost_amount /. 100.00, ~digits=2),
)
},
data: constructData("total_dispute_lost_amount", timeSeriesData),
statType: "Volume",
showDelta: false,
}
}
}
let getSingleStatEntity = (metrics, ~uri) => {
urlConfig: [
{
uri,
metrics: metrics->getStringListFromArrayDict,
},
],
getObjects: itemToObjMapper,
getTimeSeriesObject: timeSeriesObjMapper,
defaultColumns: getColumns,
getData: getStatData,
totalVolumeCol: None,
matrixUriMapper: _ => uri,
}
let metricsConfig: array<LineChartUtils.metricsConfig> = [
{
metric_name_db: "total_amount_disputed",
metric_label: "Total Amount Disputed",
metric_type: Amount,
thresholdVal: None,
step_up_threshold: None,
legendOption: (Current, Overall),
},
{
metric_name_db: "total_dispute_lost_amount",
metric_label: "Total Dispute Lost Amount",
metric_type: Amount,
thresholdVal: None,
step_up_threshold: None,
legendOption: (Average, Overall),
},
]
let chartEntity = (tabKeys, ~uri) =>
DynamicChart.makeEntity(
~uri=String(uri),
~filterKeys=tabKeys,
~dateFilterKeys=(startTimeFilterKey, endTimeFilterKey),
~currentMetrics=("Dispute Status Metric", "Total Amount Disputed"), // 2nd metric will be static and we won't show the 2nd metric option to the first metric
~cardinality=[],
~granularity=[],
~chartTypes=[Line],
~uriConfig=[
{
uri,
timeSeriesBody: DynamicChart.getTimeSeriesChart,
legendBody: DynamicChart.getLegendBody,
metrics: metricsConfig,
timeCol: "time_bucket",
filterKeys: tabKeys,
},
],
~moduleName="Dispute Analytics",
)
| 2,212 | 9,779 |
hyperswitch-control-center | src/screens/Analytics/PaymentsAnalytics/SmartRetryAnalytics.res | .res | open DynamicSingleStat
let domain = "payments"
open HSAnalyticsUtils
open LogicUtils
type paymentsSingleState = {
successful_smart_retries: int,
total_smart_retries: int,
smart_retried_amount: float,
currency: string,
}
type paymentsSingleStateSeries = {
successful_smart_retries: int,
total_smart_retries: int,
smart_retried_amount: float,
time_series: string,
currency: string,
}
let singleStateInitialValue = {
successful_smart_retries: 0,
total_smart_retries: 0,
smart_retried_amount: 0.0,
currency: "NA",
}
let singleStateSeriesInitialValue = {
successful_smart_retries: 0,
total_smart_retries: 0,
smart_retried_amount: 0.0,
time_series: "",
currency: "NA",
}
let singleStateItemToObjMapper = json => {
json
->JSON.Decode.object
->Option.map(dict => {
successful_smart_retries: dict->getInt("successful_smart_retries", 0),
total_smart_retries: dict->getInt("total_smart_retries", 0),
smart_retried_amount: dict->getFloat("smart_retried_amount", 0.0),
currency: dict->getString("currency", "NA"),
})
->Option.getOr({
singleStateInitialValue
})
}
let singleStateSeriesItemToObjMapper = json => {
json
->JSON.Decode.object
->Option.map(dict => {
successful_smart_retries: dict->getInt("successful_smart_retries", 0),
total_smart_retries: dict->getInt("total_smart_retries", 0),
smart_retried_amount: dict->getFloat("smart_retried_amount", 0.0),
time_series: dict->getString("time_bucket", ""),
currency: dict->getString("currency", "NA"),
})
->Option.getOr({
singleStateSeriesInitialValue
})
}
let itemToObjMapper = json => {
json->getQueryData->Array.map(singleStateItemToObjMapper)
}
let timeSeriesObjMapper = json =>
json->getQueryData->Array.map(json => singleStateSeriesItemToObjMapper(json))
type colT =
| SuccessfulSmartRetries
| TotalSmartRetries
| SmartRetriedAmount
let constructData = (key, singlestatTimeseriesData: array<paymentsSingleStateSeries>) => {
switch key {
| "successful_smart_retries" =>
singlestatTimeseriesData->Array.map(ob => (
ob.time_series->DateTimeUtils.parseAsFloat,
ob.successful_smart_retries->Int.toFloat,
))
| "smart_retried_amount" =>
singlestatTimeseriesData
->Array.map(ob => (
ob.time_series->DateTimeUtils.parseAsFloat,
ob.smart_retried_amount /. 100.00,
))
->Array.toSorted(compareLogic)
| "total_smart_retries" =>
singlestatTimeseriesData->Array.map(ob => (
ob.time_series->DateTimeUtils.parseAsFloat,
ob.total_smart_retries->Int.toFloat,
))
| _ => []
}
}
let getStatData = (
singleStatData: paymentsSingleState,
timeSeriesData: array<paymentsSingleStateSeries>,
deltaTimestampData: DynamicSingleStat.deltaRange,
colType,
_mode,
) => {
switch colType {
| TotalSmartRetries => {
title: "Smart Retries made",
tooltipText: "Total number of retries that were attempted after a failed payment attempt.",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.total_smart_retries->Int.toFloat,
deltaTimestampData.currentSr,
),
value: singleStatData.total_smart_retries->Int.toFloat,
delta: {
singleStatData.total_smart_retries->Int.toFloat
},
data: constructData("total_smart_retries", timeSeriesData),
statType: "Volume",
showDelta: false,
}
| SuccessfulSmartRetries => {
title: "Successful Smart Retries",
tooltipText: "Total number of retries that succeeded out of all the retry attempts.",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.successful_smart_retries->Int.toFloat,
deltaTimestampData.currentSr,
),
value: singleStatData.successful_smart_retries->Int.toFloat,
delta: {
singleStatData.successful_smart_retries->Int.toFloat
},
data: constructData("successful_smart_retries", timeSeriesData),
statType: "Volume",
showDelta: false,
}
| SmartRetriedAmount => {
title: `Smart Retries Savings`,
tooltipText: "Total savings in amount terms from retrying failed payments again through a second processor.",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.smart_retried_amount /. 100.00,
deltaTimestampData.currentSr,
),
value: singleStatData.smart_retried_amount /. 100.00,
delta: {
Js.Float.fromString(
Float.toFixedWithPrecision(singleStatData.smart_retried_amount /. 100.00, ~digits=2),
)
},
data: constructData("smart_retried_amount", timeSeriesData),
statType: "Amount",
showDelta: false,
label: singleStatData.currency,
}
}
}
let getSmartRetriesSingleStatEntity = (metrics, defaultColumns, ~uri) => {
urlConfig: [
{
uri,
metrics: metrics->getStringListFromArrayDict,
},
],
getObjects: itemToObjMapper,
getTimeSeriesObject: timeSeriesObjMapper,
defaultColumns,
getData: getStatData,
totalVolumeCol: None,
matrixUriMapper: _ => uri,
}
let getSmartRetriesAmountSingleStatEntity = (metrics, defaultColumns, ~uri) => {
urlConfig: [
{
uri,
metrics: metrics->getStringListFromArrayDict,
},
],
getObjects: itemToObjMapper,
getTimeSeriesObject: timeSeriesObjMapper,
defaultColumns,
getData: getStatData,
totalVolumeCol: None,
matrixUriMapper: _ => uri,
}
let smartRetrivesColumns: array<DynamicSingleStat.columns<colT>> = [
{
sectionName: "",
columns: [
{
colType: SuccessfulSmartRetries,
},
{
colType: TotalSmartRetries,
},
],
},
]
let smartRetrivesAmountColumns: array<DynamicSingleStat.columns<colT>> = [
{
sectionName: "",
columns: [
{
colType: SmartRetriedAmount,
chartType: Table,
},
],
},
]
@react.component
let make = (~moduleName) => {
open APIUtils
let getURL = useGetURL()
let smartRetryAnalyticsUrl = getURL(
~entityName=V1(ANALYTICS_PAYMENTS_V2),
~methodType=Post,
~id=Some(domain),
)
let smartRetrieMetrics = [
"successful_smart_retries",
"total_smart_retries",
"smart_retried_amount",
]
let formatMetrics = arrMetrics => {
arrMetrics->Array.map(metric => {
[
("name", metric->JSON.Encode.string),
("desc", ""->JSON.Encode.string),
]->LogicUtils.getJsonFromArrayOfJson
})
}
let singleStatEntity = getSmartRetriesSingleStatEntity(
smartRetrieMetrics->formatMetrics,
smartRetrivesColumns,
~uri=smartRetryAnalyticsUrl,
)
let singleStatAMountEntity = getSmartRetriesSingleStatEntity(
smartRetrieMetrics->formatMetrics,
smartRetrivesAmountColumns,
~uri=smartRetryAnalyticsUrl,
)
let formaPayload = (singleStatBodyEntity: DynamicSingleStat.singleStatBodyEntity) => {
[
AnalyticsUtils.getFilterRequestBody(
~filter=None,
~metrics=singleStatBodyEntity.metrics,
~delta=?singleStatBodyEntity.delta,
~startDateTime=singleStatBodyEntity.startDateTime,
~endDateTime=singleStatBodyEntity.endDateTime,
~mode=singleStatBodyEntity.mode,
~groupByNames=Some(["currency"]),
~customFilter=?singleStatBodyEntity.customFilter,
~source=?singleStatBodyEntity.source,
~granularity=singleStatBodyEntity.granularity,
~prefix=singleStatBodyEntity.prefix,
)->JSON.Encode.object,
]
->JSON.Encode.array
->JSON.stringify
}
<div>
<h2 className="font-bold text-xl text-black text-opacity-80">
{"Smart Retries"->React.string}
</h2>
<div className={`flex items-start text-sm rounded-md gap-2 py-2 opacity-60`}>
{"Note: Only date range filters are supported currently for Smart Retry metrics"->React.string}
</div>
<div className="relative">
<DynamicSingleStat
entity={singleStatEntity}
startTimeFilterKey
endTimeFilterKey
filterKeys=[]
moduleName
showPercentage=false
statSentiment={singleStatEntity.statSentiment->Option.getOr(Dict.make())}
/>
<div
className="absolute top-0 w-full h-full grid grid-cols-3 grid-rows-2 pointer-events-none">
<div className="col-span-2 h-96 " />
<div className="row-span-2 h-full !pointer-events-auto">
<DynamicSingleStat
entity=singleStatAMountEntity
startTimeFilterKey
endTimeFilterKey
filterKeys=[]
moduleName
showPercentage=false
statSentiment={singleStatAMountEntity.statSentiment->Option.getOr(Dict.make())}
formaPayload
/>
</div>
</div>
</div>
</div>
}
| 2,196 | 9,780 |
hyperswitch-control-center | src/screens/Analytics/PaymentsAnalytics/PaymentAnalytics.res | .res | @react.component
let make = () => {
open LogicUtils
open Promise
open PaymentAnalyticsEntity
open APIUtils
open HSAnalyticsUtils
let updateDetails = useUpdateMethod()
let defaultFilters = [startTimeFilterKey, endTimeFilterKey]
let (filterDataJson, setFilterDataJson) = React.useState(_ => None)
let {updateExistingKeys, filterValueJson} = React.useContext(FilterContext.filterContext)
let filterData = filterDataJson->Option.getOr(Dict.make()->JSON.Encode.object)
let getURL = useGetURL()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (metrics, setMetrics) = React.useState(_ => [])
let (dimensions, setDimensions) = React.useState(_ => [])
let fetchDetails = useGetMethod()
let {updateAnalytcisEntity} = OMPSwitchHooks.useUserInfo()
let {userInfo: {analyticsEntity}, checkUserEntity} = React.useContext(
UserInfoProvider.defaultContext,
)
let mixpanelEvent = MixpanelHook.useSendEvent()
let loadInfo = async () => {
try {
let infoUrl = getURL(~entityName=V1(ANALYTICS_PAYMENTS), ~methodType=Get, ~id=Some(domain))
let infoDetails = await fetchDetails(infoUrl)
// Need to be removed
let ignoreSessionizedPayment =
infoDetails
->getDictFromJsonObject
->getArrayFromDict("metrics", [])
->AnalyticsUtils.filterMetrics
setMetrics(_ => ignoreSessionizedPayment)
setDimensions(_ => infoDetails->getDictFromJsonObject->getArrayFromDict("dimensions", []))
setScreenState(_ => PageLoaderWrapper.Success)
} catch {
| Exn.Error(e) =>
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
let getPaymetsDetails = async () => {
try {
setScreenState(_ => PageLoaderWrapper.Loading)
let paymentUrl = getURL(~entityName=V1(ORDERS), ~methodType=Get)
let paymentDetails = await fetchDetails(paymentUrl)
let data = paymentDetails->getDictFromJsonObject->getArrayFromDict("data", [])
if data->Array.length < 0 {
setScreenState(_ => PageLoaderWrapper.Custom)
} else {
await loadInfo()
}
} catch {
| Exn.Error(e) =>
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
let generalMetrics = [
"payment_success_rate",
"payment_count",
"payment_success_count",
"connector_success_rate",
]
let analyticsAmountMetrics = [
"payment_success_rate",
"avg_ticket_size",
"payment_processed_amount",
]
let formatMetrics = arrMetrics => {
arrMetrics->Array.map(metric => {
[
("name", metric->JSON.Encode.string),
("desc", ""->JSON.Encode.string),
]->LogicUtils.getJsonFromArrayOfJson
})
}
React.useEffect(() => {
getPaymetsDetails()->ignore
None
}, [])
let tabKeys = getStringListFromArrayDict(dimensions)
let tabValues =
tabKeys
->Array.mapWithIndex((key, index) => {
let a: DynamicTabs.tab = if key === "payment_method_type" {
{
title: "Payment Method + Payment Method Type",
value: "payment_method,payment_method_type",
isRemovable: index > 2,
}
} else {
{
title: key->LogicUtils.snakeToTitle,
value: key,
isRemovable: index > 2,
}
}
a
})
->Array.concat([
{
title: "Payment Method Type",
value: "payment_method_type",
isRemovable: true,
},
])
let formatData = (data: array<RescriptCore.Nullable.t<AnalyticsTypes.paymentTableType>>) => {
let actualdata =
data
->Array.map(Nullable.toOption)
->Array.reduce([], (arr, value) => {
switch value {
| Some(val) => arr->Array.concat([val])
| _ => arr
}
})
actualdata->Array.sort((a, b) => {
let success_count_a = a.payment_success_count
let success_count_b = b.payment_success_count
success_count_a <= success_count_b ? 1. : -1.
})
actualdata->Array.map(Nullable.make)
}
let title = "Payments Analytics"
let formaPayload = (singleStatBodyEntity: DynamicSingleStat.singleStatBodyEntity) => {
[
AnalyticsUtils.getFilterRequestBody(
~filter=singleStatBodyEntity.filter,
~metrics=singleStatBodyEntity.metrics,
~delta=?singleStatBodyEntity.delta,
~startDateTime=singleStatBodyEntity.startDateTime,
~endDateTime=singleStatBodyEntity.endDateTime,
~mode=singleStatBodyEntity.mode,
~groupByNames=Some(["currency"]),
~customFilter=?singleStatBodyEntity.customFilter,
~source=?singleStatBodyEntity.source,
~granularity=singleStatBodyEntity.granularity,
~prefix=singleStatBodyEntity.prefix,
)->JSON.Encode.object,
]
->JSON.Encode.array
->JSON.stringify
}
let setInitialFilters = HSwitchRemoteFilter.useSetInitialFilters(
~updateExistingKeys,
~startTimeFilterKey,
~endTimeFilterKey,
~origin="analytics",
(),
)
let dateDropDownTriggerMixpanelCallback = () => {
mixpanelEvent(~eventName="analytics_payments_date_filter_opened")
}
React.useEffect(() => {
setInitialFilters()
None
}, [])
let startTimeVal = filterValueJson->getString("startTime", "")
let endTimeVal = filterValueJson->getString("endTime", "")
let analyticsfilterUrl = getURL(
~entityName=V1(ANALYTICS_FILTERS),
~methodType=Post,
~id=Some(domain),
)
let paymentAnalyticsUrl = getURL(
~entityName=V1(ANALYTICS_PAYMENTS),
~methodType=Post,
~id=Some(domain),
)
let filterBody = React.useMemo(() => {
let filterBodyEntity: AnalyticsUtils.filterBodyEntity = {
startTime: startTimeVal,
endTime: endTimeVal,
groupByNames: tabKeys,
source: "BATCH",
}
AnalyticsUtils.filterBody(filterBodyEntity)
}, (startTimeVal, endTimeVal, tabKeys->Array.joinWith(",")))
let body = filterBody->JSON.Encode.object
React.useEffect(() => {
setFilterDataJson(_ => None)
if startTimeVal->LogicUtils.isNonEmptyString && endTimeVal->LogicUtils.isNonEmptyString {
try {
updateDetails(analyticsfilterUrl, body, Post)
->thenResolve(json => setFilterDataJson(_ => Some(json)))
->catch(_ => resolve())
->ignore
} catch {
| _ => ()
}
}
None
}, (startTimeVal, endTimeVal, body->JSON.stringify))
//This is to trigger the mixpanel event to see active analytics users
React.useEffect(() => {
if startTimeVal->LogicUtils.isNonEmptyString && endTimeVal->LogicUtils.isNonEmptyString {
mixpanelEvent(~eventName="analytics_payments_date_filter")
}
None
}, [startTimeVal, endTimeVal])
let topFilterUi = switch filterDataJson {
| Some(filterData) =>
<div className="flex flex-row">
<DynamicFilter
title="PaymentAnalytics"
initialFilters={initialFilterFields(filterData)}
options=[]
popupFilterFields={options(filterData)}
initialFixedFilters={initialFixedFilterFields(
filterData,
~events=dateDropDownTriggerMixpanelCallback,
)}
defaultFilterKeys=defaultFilters
tabNames=tabKeys
updateUrlWith=updateExistingKeys
key="0"
filterFieldsPortalName={HSAnalyticsUtils.filterFieldsPortalName}
showCustomFilter=false
refreshFilters=false
/>
</div>
| None =>
<div className="flex flex-row">
<DynamicFilter
title="PaymentAnalytics"
initialFilters=[]
options=[]
popupFilterFields=[]
initialFixedFilters={initialFixedFilterFields(
filterData,
~events=dateDropDownTriggerMixpanelCallback,
)}
defaultFilterKeys=defaultFilters
tabNames=tabKeys
updateUrlWith=updateExistingKeys //
key="1"
filterFieldsPortalName={HSAnalyticsUtils.filterFieldsPortalName}
showCustomFilter=false
refreshFilters=false
/>
</div>
}
open AnalyticsNew
<PageLoaderWrapper screenState customUI={<NoData title />}>
<div className="flex flex-col gap-5">
<div className="flex items-center justify-between ">
<PageUtils.PageHeading title />
<Portal to="PaymentAnalyticsOMPView">
<OMPSwitchHelper.OMPViews
views={OMPSwitchUtils.analyticsViewList(~checkUserEntity)}
selectedEntity={analyticsEntity}
onChange={updateAnalytcisEntity}
entityMapper=UserInfoUtils.analyticsEntityMapper
/>
</Portal>
</div>
<div
className="-ml-1 sticky top-0 z-30 p-1 bg-hyperswitch_background/70 py-1 rounded-lg my-2">
topFilterUi
</div>
<div className="flex flex-col gap-14">
<MetricsState
heading="Payments Overview"
singleStatEntity={getSingleStatEntity(
generalMetrics->formatMetrics,
generalMetricsColumns,
~uri=paymentAnalyticsUrl,
)}
filterKeys=tabKeys
startTimeFilterKey
endTimeFilterKey
moduleName="general_metrics"
/>
<MetricsState
heading="Amount Metrics"
singleStatEntity={getSingleStatEntity(
analyticsAmountMetrics->formatMetrics,
amountMetricsColumns,
~uri=paymentAnalyticsUrl,
)}
filterKeys=tabKeys
startTimeFilterKey
endTimeFilterKey
moduleName="payments_analytics_amount"
formaPayload
/>
<SmartRetryAnalytics moduleName="payments_smart_retries" />
<OverallSummary
filteredTabVales=tabValues
moduleName="overall_summary"
filteredTabKeys={tabKeys}
chartEntity={chartEntity(tabKeys, ~uri=paymentAnalyticsUrl)}
defaultSort="total_volume"
getTable={getPaymentTable}
colMapper
distributionArray={Some([distribution])}
tableEntity={Some(paymentTableEntity(~uri=paymentAnalyticsUrl))}
deltaMetrics=["payment_success_rate", "payment_count", "payment_success_count"]
deltaArray=[]
tableGlobalFilter=filterByData
weeklyTableMetricsCols
formatData={Some(formatData)}
startTimeFilterKey
endTimeFilterKey
heading="Payments Trends"
/>
</div>
</div>
</PageLoaderWrapper>
}
| 2,436 | 9,781 |
hyperswitch-control-center | src/screens/Analytics/PaymentsAnalytics/PaymentAnalyticsEntity.res | .res | type pageStateType = Loading | Failed | Success | NoData
open LogicUtils
open DynamicSingleStat
open HSAnalyticsUtils
open AnalyticsTypes
let domain = "payments"
let makeMultiInputFieldInfo = FormRenderer.makeMultiInputFieldInfo
let makeInputFieldInfo = FormRenderer.makeInputFieldInfo
let colMapper = (col: paymentColType) => {
switch col {
| SuccessRate => "payment_success_rate"
| Count => "payment_count"
| SuccessCount => "payment_success_count"
| PaymentErrorMessage => "payment_error_message"
| ProcessedAmount => "payment_processed_amount"
| AvgTicketSize => "avg_ticket_size"
| Connector => "connector"
| PaymentMethod => "payment_method"
| PaymentMethodType => "payment_method_type"
| Currency => "currency"
| AuthType => "authentication_type"
| Status => "status"
| ClientSource => "client_source"
| ClientVersion => "client_version"
| WeeklySuccessRate => "weekly_payment_success_rate"
| NoCol => ""
}
}
let reverseColMapper = (column: string) => {
switch column {
| "payment_success_rate" => SuccessRate
| "payment_count" => Count
| "payment_success_count" => SuccessCount
| "payment_processed_amount" => ProcessedAmount
| "avg_ticket_size" => AvgTicketSize
| "connector" => Connector
| "payment_method" => PaymentMethod
| "payment_method_type" => PaymentMethodType
| "currency" => Currency
| "authentication_type" => AuthType
| "status" => Status
| "weekly_payment_success_rate" => WeeklySuccessRate
| _ => NoCol
}
}
let weeklyTableMetricsCols = [
{
refKey: SuccessRate->colMapper,
newKey: WeeklySuccessRate->colMapper,
},
]
let percentFormat = value => {
`${value->Float.toFixedWithPrecision(~digits=2)}%`
}
let getWeeklySR = dict => {
switch dict->LogicUtils.getOptionFloat(WeeklySuccessRate->colMapper) {
| Some(val) => val->percentFormat
| _ => "NA"
}
}
let distribution =
[
("distributionFor", "payment_error_message"->JSON.Encode.string),
("distributionCardinality", "TOP_5"->JSON.Encode.string),
]
->Dict.fromArray
->JSON.Encode.object
let tableItemToObjMapper: Dict.t<JSON.t> => paymentTableType = dict => {
let parseErrorReasons = dict => {
dict
->getArrayFromDict(PaymentErrorMessage->colMapper, [])
->Array.map(errorJson => {
let dict = errorJson->getDictFromJsonObject
{
reason: dict->getString("reason", ""),
count: dict->getInt("count", 0),
percentage: dict->getFloat("percentage", 0.0),
}
})
}
{
payment_success_rate: dict->getFloat(SuccessRate->colMapper, 0.0),
payment_count: dict->getFloat(Count->colMapper, 0.0),
payment_success_count: dict->getFloat(SuccessCount->colMapper, 0.0),
payment_processed_amount: dict->getFloat(ProcessedAmount->colMapper, 0.0),
avg_ticket_size: dict->getFloat(AvgTicketSize->colMapper, 0.0),
connector: dict->getString(Connector->colMapper, "NA")->snakeToTitle,
payment_method: dict->getString(PaymentMethod->colMapper, "NA")->snakeToTitle,
payment_method_type: dict->getString(PaymentMethodType->colMapper, "NA")->snakeToTitle,
currency: dict->getString(Currency->colMapper, "NA")->snakeToTitle,
authentication_type: dict->getString(AuthType->colMapper, "NA")->snakeToTitle,
refund_status: dict->getString(Status->colMapper, "NA")->snakeToTitle,
client_source: dict->getString(ClientSource->colMapper, "NA")->snakeToTitle,
client_version: dict->getString(ClientVersion->colMapper, "NA")->snakeToTitle,
weekly_payment_success_rate: dict->getWeeklySR->String.toUpperCase,
payment_error_message: dict->parseErrorReasons,
}
}
let getUpdatedHeading = (~item as _, ~dateObj as _) => {
let getHeading = colType => {
let key = colType->colMapper
switch colType {
| SuccessRate => Table.makeHeaderInfo(~key, ~title="Success Rate", ~dataType=NumericType)
| WeeklySuccessRate =>
Table.makeHeaderInfo(~key, ~title="Current Week S.R", ~dataType=NumericType)
| Count => Table.makeHeaderInfo(~key, ~title="Payment Count", ~dataType=NumericType)
| SuccessCount =>
Table.makeHeaderInfo(~key, ~title="Payment Success Count", ~dataType=NumericType)
| ProcessedAmount =>
Table.makeHeaderInfo(~key, ~title="Payment Processed Amount", ~dataType=NumericType)
| PaymentErrorMessage =>
Table.makeHeaderInfo(~key, ~title="Top 5 Error Reasons", ~dataType=TextType)
| AvgTicketSize => Table.makeHeaderInfo(~key, ~title="Avg Ticket Size", ~dataType=NumericType)
| Connector => Table.makeHeaderInfo(~key, ~title="Connector", ~dataType=DropDown)
| Currency => Table.makeHeaderInfo(~key, ~title="Currency", ~dataType=DropDown)
| PaymentMethod => Table.makeHeaderInfo(~key, ~title="Payment Method", ~dataType=DropDown)
| PaymentMethodType =>
Table.makeHeaderInfo(~key, ~title="Payment Method Type", ~dataType=DropDown)
| AuthType => Table.makeHeaderInfo(~key, ~title="Authentication Type", ~dataType=DropDown)
| Status => Table.makeHeaderInfo(~key, ~title="Status", ~dataType=DropDown)
| ClientSource => Table.makeHeaderInfo(~key, ~title="Client Source", ~dataType=DropDown)
| ClientVersion => Table.makeHeaderInfo(~key, ~title="Client Version", ~dataType=DropDown)
| NoCol => Table.makeHeaderInfo(~key, ~title="")
}
}
getHeading
}
let getCell = (paymentTable, colType): Table.cell => {
let usaNumberAbbreviation = labelValue => {
shortNum(~labelValue, ~numberFormat=getDefaultNumberFormat())
}
switch colType {
| SuccessRate => Numeric(paymentTable.payment_success_rate, percentFormat)
| Count => Numeric(paymentTable.payment_count, usaNumberAbbreviation)
| SuccessCount => Numeric(paymentTable.payment_success_count, usaNumberAbbreviation)
| ProcessedAmount =>
Numeric(paymentTable.payment_processed_amount /. 100.00, usaNumberAbbreviation)
| AvgTicketSize => Numeric(paymentTable.avg_ticket_size /. 100.00, usaNumberAbbreviation)
| Connector => Text(paymentTable.connector)
| PaymentMethod => Text(paymentTable.payment_method)
| PaymentMethodType => Text(paymentTable.payment_method_type)
| Currency => Text(paymentTable.currency)
| AuthType => Text(paymentTable.authentication_type)
| Status => Text(paymentTable.refund_status)
| ClientSource => Text(paymentTable.client_source)
| ClientVersion => Text(paymentTable.client_version)
| WeeklySuccessRate => Text(paymentTable.weekly_payment_success_rate)
| PaymentErrorMessage =>
Table.CustomCell(<ErrorReasons errors={paymentTable.payment_error_message} />, "NA")
| NoCol => Text("")
}
}
let getPaymentTable: JSON.t => array<paymentTableType> = json => {
json
->LogicUtils.getArrayFromJson([])
->Array.map(item => {
tableItemToObjMapper(item->getDictFromJsonObject)
})
}
let makeFieldInfo = FormRenderer.makeFieldInfo
let paymentTableEntity = (~uri) =>
EntityType.makeEntity(
~uri,
~getObjects=getPaymentTable,
~dataKey="queryData",
~defaultColumns=defaultPaymentColumns,
~requiredSearchFieldsList=[startTimeFilterKey, endTimeFilterKey],
~allColumns=allPaymentColumns,
~getCell,
~getHeading=getUpdatedHeading(~item=None, ~dateObj=None),
)
let singleStateInitialValue = {
payment_success_rate: 0.0,
payment_count: 0,
retries_count: 0,
retries_amount_processe: 0.0,
payment_success_count: 0,
currency: "NA",
connector_success_rate: 0.0,
payment_processed_amount: 0.0,
payment_avg_ticket_size: 0.0,
}
let singleStateSeriesInitialValue = {
payment_success_rate: 0.0,
payment_count: 0,
retries_count: 0,
retries_amount_processe: 0.0,
payment_success_count: 0,
time_series: "",
payment_processed_amount: 0.0,
connector_success_rate: 0.0,
payment_avg_ticket_size: 0.0,
}
let singleStateItemToObjMapper = json => {
json
->JSON.Decode.object
->Option.map(dict => {
payment_success_rate: dict->getFloat("payment_success_rate", 0.0),
payment_count: dict->getInt("payment_count", 0),
payment_success_count: dict->getInt("payment_success_count", 0),
payment_processed_amount: dict->getFloat("payment_processed_amount", 0.0),
currency: dict->getString("currency", "NA"),
payment_avg_ticket_size: dict->getFloat("avg_ticket_size", 0.0),
retries_count: dict->getInt("retries_count", 0),
retries_amount_processe: dict->getFloat("retries_amount_processed", 0.0),
connector_success_rate: dict->getFloat("connector_success_rate", 0.0),
})
->Option.getOr({
singleStateInitialValue
})
}
let singleStateSeriesItemToObjMapper = json => {
json
->JSON.Decode.object
->Option.map(dict => {
payment_success_rate: dict->getFloat("payment_success_rate", 0.0)->setPrecision,
payment_count: dict->getInt("payment_count", 0),
payment_success_count: dict->getInt("payment_success_count", 0),
time_series: dict->getString("time_bucket", ""),
payment_processed_amount: dict->getFloat("payment_processed_amount", 0.0)->setPrecision,
payment_avg_ticket_size: dict->getFloat("avg_ticket_size", 0.0)->setPrecision,
retries_count: dict->getInt("retries_count", 0),
retries_amount_processe: dict->getFloat("retries_amount_processed", 0.0),
connector_success_rate: dict->getFloat("connector_success_rate", 0.0),
})
->Option.getOr({
singleStateSeriesInitialValue
})
}
let itemToObjMapper = json => {
json->getQueryData->Array.map(singleStateItemToObjMapper)
}
let timeSeriesObjMapper = json =>
json->getQueryData->Array.map(json => singleStateSeriesItemToObjMapper(json))
type colT =
| SuccessRate
| Count
| SuccessCount
| ProcessedAmount
| AvgTicketSize
| SuccessfulSmartRetries
| TotalSmartRetries
| SmartRetriedAmount
| ConnectorSuccessRate
let generalMetricsColumns: array<DynamicSingleStat.columns<colT>> = [
{
sectionName: "",
columns: [SuccessRate, ConnectorSuccessRate, Count, SuccessCount]->generateDefaultStateColumns,
},
]
let amountMetricsColumns: array<DynamicSingleStat.columns<colT>> = [
{
sectionName: "",
columns: [
{
colType: ProcessedAmount,
chartType: Table,
},
{
colType: AvgTicketSize,
chartType: Table,
},
],
},
]
let compareLogic = (firstValue, secondValue) => {
let (temp1, _) = firstValue
let (temp2, _) = secondValue
if temp1 == temp2 {
0.
} else if temp1 > temp2 {
-1.
} else {
1.
}
}
let constructData = (
key,
singlestatTimeseriesData: array<AnalyticsTypes.paymentsSingleStateSeries>,
) => {
switch key {
| "payment_success_rate" =>
singlestatTimeseriesData
->Array.map(ob => (ob.time_series->DateTimeUtils.parseAsFloat, ob.payment_success_rate))
->Array.toSorted(compareLogic)
| "payment_count" =>
singlestatTimeseriesData
->Array.map(ob => (ob.time_series->DateTimeUtils.parseAsFloat, ob.payment_count->Int.toFloat))
->Array.toSorted(compareLogic)
| "payment_success_count" =>
singlestatTimeseriesData
->Array.map(ob => (
ob.time_series->DateTimeUtils.parseAsFloat,
ob.payment_success_count->Int.toFloat,
))
->Array.toSorted(compareLogic)
| "payment_processed_amount" =>
singlestatTimeseriesData
->Array.map(ob => (
ob.time_series->DateTimeUtils.parseAsFloat,
ob.payment_processed_amount /. 100.00,
))
->Array.toSorted(compareLogic)
| "payment_avg_ticket_size" =>
singlestatTimeseriesData
->Array.map(ob => (
ob.time_series->DateTimeUtils.parseAsFloat,
ob.payment_avg_ticket_size /. 100.00,
))
->Array.toSorted(compareLogic)
| "retries_count" =>
singlestatTimeseriesData->Array.map(ob => (
ob.time_series->DateTimeUtils.parseAsFloat,
ob.retries_count->Int.toFloat,
))
| "retries_amount_processed" =>
singlestatTimeseriesData
->Array.map(ob => (
ob.time_series->DateTimeUtils.parseAsFloat,
ob.retries_amount_processe /. 100.00,
))
->Array.toSorted(compareLogic)
| "connector_success_rate" =>
singlestatTimeseriesData
->Array.map(ob => (ob.time_series->DateTimeUtils.parseAsFloat, ob.connector_success_rate))
->Array.toSorted(compareLogic)
| _ => []
}
}
let getStatData = (
singleStatData: paymentsSingleState,
timeSeriesData: array<paymentsSingleStateSeries>,
deltaTimestampData: DynamicSingleStat.deltaRange,
colType,
_mode,
) => {
switch colType {
| SuccessRate => {
title: "Overall Success Rate",
tooltipText: "Total successful payments processed out of total payments created (This includes user dropouts at shopping cart and checkout page)",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.payment_success_rate,
deltaTimestampData.currentSr,
),
value: singleStatData.payment_success_rate,
delta: {
singleStatData.payment_success_rate
},
data: constructData("payment_success_rate", timeSeriesData),
statType: "Rate",
showDelta: false,
}
| Count => {
title: "Overall Payments",
tooltipText: "Total payments initiated",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.payment_count->Int.toFloat,
deltaTimestampData.currentSr,
),
value: singleStatData.payment_count->Int.toFloat,
delta: {
singleStatData.payment_count->Int.toFloat
},
data: constructData("payment_count", timeSeriesData),
statType: "Volume",
showDelta: false,
}
| SuccessCount => {
title: "Success Payments",
tooltipText: "Total number of payments with status as succeeded. ",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.payment_success_count->Int.toFloat,
deltaTimestampData.currentSr,
),
value: singleStatData.payment_success_count->Int.toFloat,
delta: {
Js.Float.fromString(
Float.toFixedWithPrecision(singleStatData.payment_success_count->Int.toFloat, ~digits=2),
)
},
data: constructData("payment_success_count", timeSeriesData),
statType: "Volume",
showDelta: false,
}
| ProcessedAmount => {
title: `Processed Amount`,
tooltipText: "Sum of amount of all payments with status = succeeded (Please note that there could be payments which could be authorized but not captured. Such payments are not included in the processed amount, because non-captured payments will not be settled to your merchant account by your payment processor)",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.payment_processed_amount /. 100.00,
deltaTimestampData.currentSr,
),
value: singleStatData.payment_processed_amount /. 100.00,
delta: {
Js.Float.fromString(
Float.toFixedWithPrecision(singleStatData.payment_processed_amount /. 100.00, ~digits=2),
)
},
data: constructData("payment_processed_amount", timeSeriesData),
statType: "Amount",
showDelta: false,
label: singleStatData.currency,
}
| AvgTicketSize => {
title: `Avg Ticket Size`,
tooltipText: "The total amount for which payments were created divided by the total number of payments created.",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.payment_avg_ticket_size /. 100.00,
deltaTimestampData.currentSr,
),
value: singleStatData.payment_avg_ticket_size /. 100.00,
delta: {
Js.Float.fromString(
Float.toFixedWithPrecision(singleStatData.payment_avg_ticket_size /. 100.00, ~digits=2),
)
},
data: constructData("payment_avg_ticket_size", timeSeriesData),
statType: "Volume",
showDelta: false,
label: singleStatData.currency,
}
| TotalSmartRetries => {
title: "Smart Retries made",
tooltipText: "Total number of retries that were attempted after a failed payment attempt (Note: Only date range filters are supoorted currently)",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.retries_count->Int.toFloat,
deltaTimestampData.currentSr,
),
value: singleStatData.retries_count->Int.toFloat,
delta: {
singleStatData.retries_count->Int.toFloat
},
data: constructData("retries_count", timeSeriesData),
statType: "Volume",
showDelta: false,
}
| SuccessfulSmartRetries => {
title: "Successful Smart Retries",
tooltipText: "Total number of retries that were attempted after a failed payment attempt (Note: Only date range filters are supoorted currently)",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.retries_count->Int.toFloat,
deltaTimestampData.currentSr,
),
value: singleStatData.retries_count->Int.toFloat,
delta: {
singleStatData.retries_count->Int.toFloat
},
data: constructData("retries_count", timeSeriesData),
statType: "Volume",
showDelta: false,
}
| SmartRetriedAmount => {
title: `Smart Retries Savings`,
tooltipText: "Total savings in amount terms from retrying failed payments again through a second processor (Note: Only date range filters are supoorted currently)",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.retries_amount_processe /. 100.00,
deltaTimestampData.currentSr,
),
value: singleStatData.retries_amount_processe /. 100.00,
delta: {
Js.Float.fromString(
Float.toFixedWithPrecision(singleStatData.retries_amount_processe /. 100.00, ~digits=2),
)
},
data: constructData("retries_amount_processe", timeSeriesData),
statType: "Amount",
showDelta: false,
}
| ConnectorSuccessRate => {
title: "Confirmed Success Rate",
tooltipText: "Total successful payments processed out of all user confirmed payments",
deltaTooltipComponent: AnalyticsUtils.singlestatDeltaTooltipFormat(
singleStatData.connector_success_rate,
deltaTimestampData.currentSr,
),
value: singleStatData.connector_success_rate,
delta: {
singleStatData.connector_success_rate
},
data: constructData("connector_success_rate", timeSeriesData),
statType: "Rate",
showDelta: false,
}
}
}
let getSingleStatEntity = (metrics, defaultColumns, ~uri) => {
urlConfig: [
{
uri,
metrics: metrics->getStringListFromArrayDict,
},
],
getObjects: itemToObjMapper,
getTimeSeriesObject: timeSeriesObjMapper,
defaultColumns,
getData: getStatData,
totalVolumeCol: None,
matrixUriMapper: _ => uri,
}
let metricsConfig: array<LineChartUtils.metricsConfig> = [
{
metric_name_db: "payment_success_rate",
metric_label: "Success Rate",
metric_type: Rate,
thresholdVal: None,
step_up_threshold: None,
legendOption: (Current, Overall),
},
{
metric_name_db: "payment_count",
metric_label: "Volume",
metric_type: Volume,
thresholdVal: None,
step_up_threshold: None,
legendOption: (Average, Overall),
},
]
let chartEntity = (tabKeys, ~uri) =>
DynamicChart.makeEntity(
~uri=String(uri),
~filterKeys=tabKeys,
~dateFilterKeys=(startTimeFilterKey, endTimeFilterKey),
~currentMetrics=("Success Rate", "Volume"), // 2nd metric will be static and we won't show the 2nd metric option to the first metric
~cardinality=[],
~granularity=[],
~chartTypes=[Line],
~uriConfig=[
{
uri,
timeSeriesBody: DynamicChart.getTimeSeriesChart,
legendBody: DynamicChart.getLegendBody,
metrics: metricsConfig,
timeCol: "time_bucket",
filterKeys: tabKeys,
},
],
~moduleName="Payment Analytics",
~enableLoaders=true,
)
| 4,901 | 9,782 |
hyperswitch-control-center | src/screens/Analytics/GlobalSearchResults/SearchResultsPageUtils.res | .res | let getSearchresults = (result: GlobalSearchTypes.defaultResult) => {
open GlobalSearchTypes
let results = []
if result.local_results->Array.length > 0 {
results->Array.push({
section: Local,
results: result.local_results,
total_results: results->Array.length,
})
}
let data = Dict.make()
result.remote_results->Array.forEach(value => {
let remoteResults = value.hits->Array.map(item => {
{
texts: [item],
redirect_link: ""->JSON.Encode.string,
}
})
if remoteResults->Array.length > 0 {
data->Dict.set(
value.index,
{
section: value.index->getSectionVariant,
results: remoteResults,
total_results: value.count,
},
)
}
})
open GlobalSearchBarUtils
// intents
let key1 = PaymentIntents->getSectionIndex
let key2 = SessionizerPaymentIntents->getSectionIndex
getItemFromArray(results, key1, key2, data)
// Attempts
let key1 = PaymentAttempts->getSectionIndex
let key2 = SessionizerPaymentAttempts->getSectionIndex
getItemFromArray(results, key1, key2, data)
// Refunds
let key1 = Refunds->getSectionIndex
let key2 = SessionizerPaymentRefunds->getSectionIndex
getItemFromArray(results, key1, key2, data)
// Disputes
let key1 = Disputes->getSectionIndex
let key2 = SessionizerPaymentDisputes->getSectionIndex
getItemFromArray(results, key1, key2, data)
(results, result.searchText)
}
| 373 | 9,783 |
hyperswitch-control-center | src/screens/Analytics/GlobalSearchResults/SearchResultsPage.res | .res | module RenderSearchResultBody = {
open GlobalSearchTypes
open LogicUtils
@react.component
let make = (~section: resultType) => {
let redirectOnSelect = element => {
let redirectLink = element.redirect_link->JSON.Decode.string->Option.getOr("")
if redirectLink->isNonEmptyString {
GlobalVars.appendDashboardPath(~url=redirectLink)->RescriptReactRouter.replace
}
}
switch section.section {
| Local =>
section.results
->Array.mapWithIndex((item, indx) => {
let elementsArray = item.texts
<div
className={`p-2 text-sm cursor-pointer hover:bg-gray-100 -ml-2`}
key={indx->Int.toString}
onClick={_ => redirectOnSelect(item)}>
{elementsArray
->Array.mapWithIndex((item, index) => {
let elementValue = item->JSON.Decode.string->Option.getOr("")
<RenderIf condition={elementValue->isNonEmptyString} key={index->Int.toString}>
<span
key={index->Int.toString}
className=" font-medium text-lightgray_background opacity-60 underline underline-offset-4">
{elementValue->React.string}
</span>
<RenderIf condition={index >= 0 && index < elementsArray->Array.length - 1}>
<span className="mx-2 text-lightgray_background opacity-60">
{">"->React.string}
</span>
</RenderIf>
</RenderIf>
})
->React.array}
</div>
})
->React.array
| PaymentIntents | SessionizerPaymentIntents =>
<PaymentIntentTable.PreviewTable data={section.results} />
| PaymentAttempts | SessionizerPaymentAttempts =>
<PaymentAttemptTable.PreviewTable data={section.results} />
| Refunds | SessionizerPaymentRefunds => <RefundsTable.PreviewTable data={section.results} />
| Disputes | SessionizerPaymentDisputes => <DisputeTable.PreviewTable data={section.results} />
| Others | Default => "Not implemented"->React.string
}
}
}
module SearchResultsComponent = {
open GlobalSearchTypes
@react.component
let make = (~searchResults, ~searchText) => {
searchResults
->Array.mapWithIndex((section: resultType, i) => {
let borderClass = searchResults->Array.length > 0 ? "" : "border-b dark:border-jp-gray-960"
<div className={`py-5 ${borderClass}`} key={i->Int.toString}>
<div className="flex justify-between">
<div className="text-lightgray_background font-bold text-lg pb-2">
{section.section->getSectionHeader->React.string}
</div>
<GlobalSearchBarHelper.ShowMoreLink
section textStyleClass="text-sm pt-2 font-medium text-blue-900" searchText
/>
</div>
<RenderSearchResultBody section />
</div>
})
->React.array
}
}
@react.component
let make = () => {
open LogicUtils
open SearchResultsPageUtils
open GlobalSearchTypes
open GlobalSearchBarUtils
let getURL = APIUtils.useGetURL()
let fetchDetails = APIUtils.useUpdateMethod()
let url = RescriptReactRouter.useUrl()
let prefix = useUrlPrefix()
let (state, setState) = React.useState(_ => Idle)
let (searchText, setSearchText) = React.useState(_ => "")
let (searchResults, setSearchResults) = React.useState(_ => [])
let globalSearchResult = HyperswitchAtom.globalSeacrchAtom->Recoil.useRecoilValueFromAtom
let merchentDetails = HSwitchUtils.useMerchantDetailsValue()
let isReconEnabled = merchentDetails.recon_status === Active
let hswitchTabs = SidebarValues.useGetHsSidebarValues(~isReconEnabled)
let query = UrlUtils.useGetFilterDictFromUrl("")->getString("query", "")
let {globalSearch} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
let isShowRemoteResults = globalSearch && userHasAccess(~groupAccess=OperationsView) === Access
let getSearchResults = async results => {
try {
let url = getURL(~entityName=V1(GLOBAL_SEARCH), ~methodType=Post)
let body = query->generateQuery
let response = await fetchDetails(url, body->JSON.Encode.object, Post)
let local_results = []
results->Array.forEach((item: resultType) => {
switch item.section {
| Local => local_results->Array.pushMany(item.results)
| _ => ()
}
})
let remote_results = response->parseResponse
let data = {
local_results,
remote_results,
searchText: query,
}
let (results, text) = data->getSearchresults
setSearchResults(_ => results)
setSearchText(_ => text)
setState(_ => Loaded)
} catch {
| _ => setState(_ => Loaded)
}
}
React.useEffect(() => {
let (results, text) = globalSearchResult->getSearchresults
if text->isNonEmptyString {
setSearchResults(_ => results)
setSearchText(_ => text)
setState(_ => Loaded)
} else if query->isNonEmptyString {
let results = []
setState(_ => Loading)
let localResults: resultType = query->GlobalSearchBarUtils.getLocalMatchedResults(hswitchTabs)
if localResults.results->Array.length > 0 {
results->Array.push(localResults)
}
if isShowRemoteResults {
getSearchResults(results)->ignore
} else {
if results->Array.length > 0 {
setSearchResults(_ => results)
} else {
setSearchResults(_ => [])
}
setState(_ => Loaded)
}
} else {
setState(_ => Idle)
setSearchResults(_ => [])
}
None
}, [query, url.search])
<div>
<PageUtils.PageHeading title="Search results" />
{switch state {
| Loading =>
<div className="my-14 py-4">
<Loader />
</div>
| _ =>
if searchResults->Array.length === 0 {
<GlobalSearchBarHelper.EmptyResult prefix searchText />
} else {
<SearchResultsComponent searchResults searchText={query} />
}
}}
</div>
}
| 1,434 | 9,784 |
hyperswitch-control-center | src/screens/Analytics/GlobalSearchResults/GlobalSearchTables/ResultsTableUtils.res | .res | 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 useGetData = () => {
open LogicUtils
let getURL = APIUtils.useGetURL()
async (
~updateDetails: (
string,
JSON.t,
Fetch.requestMethod,
~bodyFormData: Fetch.formData=?,
~headers: Dict.t<'a>=?,
~contentType: AuthHooks.contentType=?,
~version: UserInfoTypes.version=?,
) => promise<JSON.t>,
~offset,
~query,
~path,
) => {
let body = query->GlobalSearchBarUtils.generateQuery
body->Dict.set("offset", offset->Int.toFloat->JSON.Encode.float)
body->Dict.set("count", 10->Int.toFloat->JSON.Encode.float)
try {
let url = getURL(~entityName=V1(GLOBAL_SEARCH), ~methodType=Post, ~id=Some(path))
let res = await updateDetails(url, body->JSON.Encode.object, Post)
let data = res->LogicUtils.getDictFromJsonObject->LogicUtils.getArrayFromDict("hits", [])
let total = res->getDictFromJsonObject->getInt("count", 0)
(data, total)
} catch {
| Exn.Error(_) => Exn.raiseError("Something went wrong!")
}
}
}
| 317 | 9,785 |
hyperswitch-control-center | src/screens/Analytics/GlobalSearchResults/GlobalSearchTables/Disputes/DisputeTableEntity.res | .res | let domain = "disputes"
type disputesObject = {
dispute_id: string,
dispute_amount: float,
currency: string,
dispute_status: string,
payment_id: string,
attempt_id: string,
merchant_id: string,
connector_status: string,
connector_dispute_id: string,
connector_reason: string,
connector_reason_code: int,
challenge_required_by: int,
connector_created_at: int,
connector_updated_at: int,
created_at: int,
modified_at: int,
connector: string,
evidence: string,
profile_id: string,
merchant_connector_id: string,
sign_flag: int,
timestamp: string,
organization_id: string,
}
type cols =
| DisputeId
| DisputeAmount
| Currency
| DisputeStatus
| PaymentId
| AttemptId
| MerchantId
| ConnectorStatus
| ConnectorDisputeId
| ConnectorReason
| ConnectorReasonCode
| ChallengeRequiredBy
| ConnectorCreatedAt
| ConnectorUpdatedAt
| CreatedAt
| ModifiedAt
| Connector
| Evidence
| ProfileId
| MerchantConnectorId
| SignFlag
| Timestamp
| OrganizationId
let visibleColumns = [DisputeId, PaymentId, DisputeStatus, DisputeAmount, Currency, Connector]
let colMapper = (col: cols) => {
switch col {
| DisputeId => "dispute_id"
| DisputeAmount => "dispute_amount"
| Currency => "currency"
| DisputeStatus => "dispute_status"
| PaymentId => "payment_id"
| AttemptId => "attempt_id"
| MerchantId => "merchant_id"
| ConnectorStatus => "connector_status"
| ConnectorDisputeId => "connector_dispute_id"
| ConnectorReason => "connector_reason"
| ConnectorReasonCode => "connector_reason_code"
| ChallengeRequiredBy => "challenge_required_by"
| ConnectorCreatedAt => "connector_created_at"
| ConnectorUpdatedAt => "connector_updated_at"
| CreatedAt => "created_at"
| ModifiedAt => "modified_at"
| Connector => "connector"
| Evidence => "evidence"
| ProfileId => "profile_id"
| MerchantConnectorId => "merchant_connector_id"
| SignFlag => "sign_flag"
| Timestamp => "timestamp"
| OrganizationId => "organization_id"
}
}
let tableItemToObjMapper: Dict.t<JSON.t> => disputesObject = dict => {
open LogicUtils
{
dispute_id: dict->getString(DisputeId->colMapper, "NA"),
dispute_amount: dict->getFloat(DisputeAmount->colMapper, 0.0),
currency: dict->getString(Currency->colMapper, "NA"),
dispute_status: dict->getString(DisputeStatus->colMapper, "NA"),
payment_id: dict->getString(PaymentId->colMapper, "NA"),
attempt_id: dict->getString(AttemptId->colMapper, "NA"),
merchant_id: dict->getString(MerchantId->colMapper, "NA"),
connector_status: dict->getString(ConnectorStatus->colMapper, "NA"),
connector_dispute_id: dict->getString(ConnectorDisputeId->colMapper, "NA"),
connector_reason: dict->getString(ConnectorReason->colMapper, "NA"),
connector_reason_code: dict->getInt(ConnectorReasonCode->colMapper, 0),
challenge_required_by: dict->getInt(ChallengeRequiredBy->colMapper, 0),
connector_created_at: dict->getInt(ConnectorCreatedAt->colMapper, 0),
connector_updated_at: dict->getInt(ConnectorUpdatedAt->colMapper, 0),
created_at: dict->getInt(CreatedAt->colMapper, 0),
modified_at: dict->getInt(ModifiedAt->colMapper, 0),
connector: dict->getString(Connector->colMapper, "NA"),
evidence: dict->getString(Evidence->colMapper, "NA"),
profile_id: dict->getString(ProfileId->colMapper, "NA"),
merchant_connector_id: dict->getString(MerchantConnectorId->colMapper, "NA"),
sign_flag: dict->getInt(SignFlag->colMapper, 0),
timestamp: dict->getString(Timestamp->colMapper, "NA"),
organization_id: dict->getString(OrganizationId->colMapper, "NA"),
}
}
let getObjects: JSON.t => array<disputesObject> = json => {
open LogicUtils
json
->LogicUtils.getArrayFromJson([])
->Array.map(item => {
tableItemToObjMapper(item->getDictFromJsonObject)
})
}
let getHeading = colType => {
let key = colType->colMapper
switch colType {
| DisputeId => Table.makeHeaderInfo(~key, ~title="Dispute Id", ~dataType=TextType)
| DisputeAmount => Table.makeHeaderInfo(~key, ~title="Dispute Amount", ~dataType=TextType)
| Currency => Table.makeHeaderInfo(~key, ~title="Currency", ~dataType=TextType)
| DisputeStatus => Table.makeHeaderInfo(~key, ~title="Dispute Status", ~dataType=TextType)
| PaymentId => Table.makeHeaderInfo(~key, ~title="Payment Id", ~dataType=TextType)
| AttemptId => Table.makeHeaderInfo(~key, ~title="Attempt Id", ~dataType=TextType)
| MerchantId => Table.makeHeaderInfo(~key, ~title="Merchant Id", ~dataType=TextType)
| ConnectorStatus => Table.makeHeaderInfo(~key, ~title="Connector Status", ~dataType=TextType)
| ConnectorDisputeId =>
Table.makeHeaderInfo(~key, ~title="Connector Dispute Id", ~dataType=TextType)
| ConnectorReason => Table.makeHeaderInfo(~key, ~title="Connector Reason", ~dataType=TextType)
| ConnectorReasonCode =>
Table.makeHeaderInfo(~key, ~title="Connector Reason Code", ~dataType=TextType)
| ChallengeRequiredBy =>
Table.makeHeaderInfo(~key, ~title="Challenge Required By", ~dataType=TextType)
| ConnectorCreatedAt =>
Table.makeHeaderInfo(~key, ~title="Connector Created At", ~dataType=TextType)
| ConnectorUpdatedAt =>
Table.makeHeaderInfo(~key, ~title="Connector Updated At", ~dataType=TextType)
| CreatedAt => Table.makeHeaderInfo(~key, ~title="Created At", ~dataType=TextType)
| ModifiedAt => Table.makeHeaderInfo(~key, ~title="Modified At", ~dataType=TextType)
| Connector => Table.makeHeaderInfo(~key, ~title="Connector", ~dataType=TextType)
| Evidence => Table.makeHeaderInfo(~key, ~title="Evidence", ~dataType=TextType)
| ProfileId => Table.makeHeaderInfo(~key, ~title="Profile Id", ~dataType=TextType)
| MerchantConnectorId =>
Table.makeHeaderInfo(~key, ~title="Merchant Connector Id", ~dataType=TextType)
| SignFlag => Table.makeHeaderInfo(~key, ~title="Sign Flag", ~dataType=TextType)
| Timestamp => Table.makeHeaderInfo(~key, ~title="Timestamp", ~dataType=TextType)
| OrganizationId => Table.makeHeaderInfo(~key, ~title="Organization Id", ~dataType=TextType)
}
}
let getCell = (disputeObj, colType): Table.cell => {
let disputeStatus = disputeObj.dispute_status->HSwitchOrderUtils.statusVariantMapper
switch colType {
| DisputeId =>
CustomCell(
<HSwitchOrderUtils.CopyLinkTableCell
url={`/disputes/${disputeObj.dispute_id}/${disputeObj.profile_id}/${disputeObj.merchant_id}/${disputeObj.organization_id}`}
displayValue={disputeObj.dispute_id}
copyValue={Some(disputeObj.dispute_id)}
/>,
"",
)
| DisputeAmount =>
CustomCell(
<OrderEntity.CurrencyCell
amount={(disputeObj.dispute_amount /. 100.0)->Float.toString} currency={disputeObj.currency}
/>,
"",
)
| Currency => Text(disputeObj.currency)
| DisputeStatus =>
Label({
title: disputeObj.dispute_status->String.toUpperCase,
color: switch disputeStatus {
| Succeeded
| PartiallyCaptured =>
LabelGreen
| Failed
| Cancelled =>
LabelRed
| Processing
| RequiresCustomerAction
| RequiresConfirmation
| RequiresPaymentMethod =>
LabelBlue
| _ => LabelLightGray
},
})
| PaymentId => Text(disputeObj.payment_id)
| AttemptId => Text(disputeObj.attempt_id)
| MerchantId => Text(disputeObj.merchant_id)
| ConnectorStatus => Text(disputeObj.connector_status)
| ConnectorDisputeId => Text(disputeObj.connector_dispute_id)
| ConnectorReason => Text(disputeObj.connector_reason)
| ConnectorReasonCode => Text(disputeObj.connector_reason_code->Int.toString)
| ChallengeRequiredBy => Text(disputeObj.challenge_required_by->Int.toString)
| ConnectorCreatedAt => Text(disputeObj.connector_created_at->Int.toString)
| ConnectorUpdatedAt => Text(disputeObj.connector_updated_at->Int.toString)
| CreatedAt => Text(disputeObj.created_at->Int.toString)
| ModifiedAt => Text(disputeObj.modified_at->Int.toString)
| Connector => Text(disputeObj.connector)
| Evidence => Text(disputeObj.evidence)
| ProfileId => Text(disputeObj.profile_id)
| MerchantConnectorId => Text(disputeObj.merchant_connector_id)
| SignFlag => Text(disputeObj.sign_flag->Int.toString)
| Timestamp => Text(disputeObj.timestamp)
| OrganizationId => Text(disputeObj.organization_id)
}
}
let tableEntity = EntityType.makeEntity(
~uri=``,
~getObjects,
~dataKey="queryData",
~defaultColumns=visibleColumns,
~requiredSearchFieldsList=[],
~allColumns=visibleColumns,
~getCell,
~getHeading,
~getShowLink={
dispute =>
GlobalVars.appendDashboardPath(
~url=`/disputes/${dispute.dispute_id}/${dispute.profile_id}/${dispute.merchant_id}/${dispute.organization_id}`,
)
},
)
| 2,269 | 9,786 |
hyperswitch-control-center | src/screens/Analytics/GlobalSearchResults/GlobalSearchTables/Disputes/DisputeTable.res | .res | module PreviewTable = {
open DisputeTableEntity
open ResultsTableUtils
open GlobalSearchTypes
@react.component
let make = (~data) => {
let defaultSort: Table.sortedObject = {
key: "",
order: Table.INC,
}
let tableData =
data
->Array.map(item => {
let data = item.texts->Array.get(0)->Option.getOr(Dict.make()->JSON.Encode.object)
data->JSON.Decode.object->Option.getOr(Dict.make())
})
->Array.filter(dict => dict->Dict.keysToArray->Array.length > 0)
->Array.map(item => item->tableItemToObjMapper->Nullable.make)
<LoadedTable
visibleColumns
title=domain
hideTitle=true
actualData={tableData}
entity=tableEntity
resultsPerPage=10
totalResults={tableData->Array.length}
offset={0}
setOffset={_ => ()}
defaultSort
currrentFetchCount={tableData->Array.length}
tableLocalFilter=false
tableheadingClass=tableBorderClass
tableBorderClass
ignoreHeaderBg=true
tableDataBorderClass=tableBorderClass
isAnalyticsModule=false
showResultsPerPageSelector=false
paginationClass="hidden"
/>
}
}
@react.component
let make = () => {
open APIUtils
open DisputeTableEntity
let updateDetails = useUpdateMethod()
let fetchTableData = ResultsTableUtils.useGetData()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (data, setData) = React.useState(_ => [])
let (totalCount, setTotalCount) = React.useState(_ => 0)
let widthClass = "w-full"
let heightClass = ""
let defaultValue: LoadedTable.pageDetails = {offset: 0, resultsPerPage: 10}
let pageDetailDict = Recoil.useRecoilValueFromAtom(LoadedTable.table_pageDetails)
let pageDetail = pageDetailDict->Dict.get(domain)->Option.getOr(defaultValue)
let setPageDetails = Recoil.useSetRecoilState(LoadedTable.table_pageDetails)
let (offset, setOffset) = React.useState(_ => pageDetail.offset)
let searchText = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("query", "")
let path = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("domain", "")
let clearPageDetails = () => {
let newDict = pageDetailDict->Dict.toArray->Dict.fromArray
newDict->Dict.set(domain, defaultValue)
setPageDetails(_ => newDict)
}
let getData = async () => {
setScreenState(_ => PageLoaderWrapper.Loading)
try {
let (data, total) = await fetchTableData(~updateDetails, ~offset, ~query={searchText}, ~path)
let arr = Array.make(~length=offset, Dict.make())
if total <= offset {
setOffset(_ => 0)
}
if total > 0 {
let dataDictArr = data->Belt.Array.keepMap(JSON.Decode.object)
let orderData = arr->Array.concat(dataDictArr)->Array.map(tableItemToObjMapper)
let list = orderData->Array.map(Nullable.make)
setTotalCount(_ => total)
setData(_ => list)
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Error("Something went wrong!"))
}
}
React.useEffect(() => {
if searchText->String.length > 0 {
getData()->ignore
} else {
setScreenState(_ => PageLoaderWrapper.Success)
}
Some(
() => {
clearPageDetails()
},
)
}, (offset, searchText))
open ResultsTableUtils
<div className={`flex flex-col mx-auto h-full ${widthClass} ${heightClass} min-h-[50vh]`}>
<PageUtils.PageHeading title="Disputes" />
<PageLoaderWrapper screenState>
<LoadedTable
visibleColumns
title=domain
hideTitle=true
actualData=data
entity=tableEntity
resultsPerPage=10
showSerialNumber=true
totalResults={totalCount}
offset
setOffset
currrentFetchCount={data->Array.length}
tableLocalFilter=false
tableheadingClass=tableBorderClass
tableBorderClass
ignoreHeaderBg=true
tableDataBorderClass=tableBorderClass
isAnalyticsModule=false
showResultsPerPageSelector=false
/>
</PageLoaderWrapper>
</div>
}
| 1,034 | 9,787 |
hyperswitch-control-center | src/screens/Analytics/GlobalSearchResults/GlobalSearchTables/PaymentAttempt/PaymentAttemptEntity.res | .res | let domain = "payment_attempts"
type paymentAttemptObject = {
payment_id: string,
merchant_id: string,
status: string,
amount: float,
currency: string,
amount_captured: float,
customer_id: string,
description: string,
return_url: string,
connector_id: string,
statement_descriptor_name: string,
statement_descriptor_suffix: string,
created_at: int,
modified_at: int,
last_synced: int,
setup_future_usage: string,
off_session: string,
client_secret: string,
active_attempt_id: string,
business_country: string,
business_label: string,
attempt_count: int,
sign_flag: int,
timestamp: string,
confirm: bool,
multiple_capture_count: int,
attempt_id: string,
save_to_locker: string,
connector: string,
error_message: string,
offer_amount: string,
surcharge_amount: string,
tax_amount: string,
payment_method_id: string,
payment_method: string,
connector_transaction_id: string,
capture_method: string,
capture_on: string,
authentication_type: string,
cancellation_reason: string,
amount_to_capture: string,
mandate_id: string,
payment_method_type: string,
payment_experience: string,
error_reason: string,
amount_capturable: string,
merchant_connector_id: string,
net_amount: string,
unified_code: string,
unified_message: string,
client_source: string,
client_version: string,
profile_id: string,
organization_id: string,
}
type cols =
| PaymentId
| MerchantId
| Status
| Amount
| Currency
| AmountCaptured
| CustomerId
| Description
| ReturnUrl
| ConnectorId
| StatementDescriptorName
| StatementDescriptorSuffix
| CreatedAt
| ModifiedAt
| LastSynced
| SetupFutureUsage
| OffSession
| ClientSecret
| ActiveAttemptId
| BusinessCountry
| BusinessLabel
| AttemptCount
| SignFlag
| Timestamp
| Confirm
| MultipleCaptureCount
| AttemptId
| SaveToLocker
| Connector
| ErrorMessage
| OfferAmount
| SurchargeAmount
| TaxAmount
| PaymentMethodId
| PaymentMethod
| ConnectorTransactionId
| CaptureMethod
| CaptureOn
| AuthenticationType
| CancellationReason
| AmountToCapture
| MandateId
| PaymentMethodType
| PaymentExperience
| ErrorReason
| AmountCapturable
| MerchantConnectorId
| NetAmount
| UnifiedCode
| UnifiedMessage
| ClientSource
| ClientVersion
| ProfileId
| OrganizationId
let visibleColumns = [
PaymentId,
MerchantId,
Status,
Amount,
Currency,
Connector,
PaymentMethod,
PaymentMethodType,
]
let colMapper = (col: cols) => {
switch col {
| PaymentId => "payment_id"
| MerchantId => "merchant_id"
| Status => "status"
| Amount => "amount"
| Currency => "currency"
| AmountCaptured => "amount_captured"
| CustomerId => "customer_id"
| Description => "description"
| ReturnUrl => "return_url"
| ConnectorId => "connector_id"
| StatementDescriptorName => "statement_descriptor_name"
| StatementDescriptorSuffix => "statement_descriptor_suffix"
| CreatedAt => "created_at"
| ModifiedAt => "modified_at"
| LastSynced => "last_synced"
| SetupFutureUsage => "setup_future_usage"
| OffSession => "off_session"
| ClientSecret => "client_secret"
| ActiveAttemptId => "active_attempt_id"
| BusinessCountry => "business_country"
| BusinessLabel => "business_label"
| AttemptCount => "attempt_count"
| SignFlag => "sign_flag"
| Timestamp => "@timestamp"
| Confirm => "confirm"
| MultipleCaptureCount => "multiple_capture_count"
| AttemptId => "attempt_id"
| SaveToLocker => "save_to_locker"
| Connector => "connector"
| ErrorMessage => "error_message"
| OfferAmount => "offer_amount"
| SurchargeAmount => "surcharge_amount"
| TaxAmount => "tax_amount"
| PaymentMethodId => "payment_method_id"
| PaymentMethod => "payment_method"
| ConnectorTransactionId => "connector_transaction_id"
| CaptureMethod => "capture_method"
| CaptureOn => "capture_on"
| AuthenticationType => "authentication_type"
| CancellationReason => "cancellation_reason"
| AmountToCapture => "amount_to_capture"
| MandateId => "mandate_id"
| PaymentMethodType => "payment_method_type"
| PaymentExperience => "payment_experience"
| ErrorReason => "error_reason"
| AmountCapturable => "amount_capturable"
| MerchantConnectorId => "merchant_connector_id"
| NetAmount => "net_amount"
| UnifiedCode => "unified_code"
| UnifiedMessage => "unified_message"
| ClientSource => "client_source"
| ClientVersion => "client_version"
| ProfileId => "profile_id"
| OrganizationId => "organization_id"
}
}
let tableItemToObjMapper: Dict.t<JSON.t> => paymentAttemptObject = dict => {
open LogicUtils
{
payment_id: dict->getString(PaymentId->colMapper, "NA"),
merchant_id: dict->getString(MerchantId->colMapper, "NA"),
status: dict->getString(Status->colMapper, "NA"),
amount: dict->getFloat(Amount->colMapper, 0.0),
currency: dict->getString(Currency->colMapper, "NA"),
amount_captured: dict->getFloat(AmountCaptured->colMapper, 0.0),
customer_id: dict->getString(CustomerId->colMapper, "NA"),
description: dict->getString(Description->colMapper, "NA"),
return_url: dict->getString(ReturnUrl->colMapper, "NA"),
connector_id: dict->getString(ConnectorId->colMapper, "NA"),
statement_descriptor_name: dict->getString(StatementDescriptorName->colMapper, "NA"),
statement_descriptor_suffix: dict->getString(StatementDescriptorSuffix->colMapper, "NA"),
created_at: dict->getInt(CreatedAt->colMapper, 0),
modified_at: dict->getInt(ModifiedAt->colMapper, 0),
last_synced: dict->getInt(LastSynced->colMapper, 0),
setup_future_usage: dict->getString(SetupFutureUsage->colMapper, "NA"),
off_session: dict->getString(OffSession->colMapper, "NA"),
client_secret: dict->getString(ClientSecret->colMapper, "NA"),
active_attempt_id: dict->getString(ActiveAttemptId->colMapper, "NA"),
business_country: dict->getString(BusinessCountry->colMapper, "NA"),
business_label: dict->getString(BusinessLabel->colMapper, "NA"),
attempt_count: dict->getInt(AttemptCount->colMapper, 0),
sign_flag: dict->getInt(SignFlag->colMapper, 0),
timestamp: dict->getString(Timestamp->colMapper, "NA"),
confirm: dict->getBool(Confirm->colMapper, false),
multiple_capture_count: dict->getInt(MultipleCaptureCount->colMapper, 0),
attempt_id: dict->getString(AttemptId->colMapper, "NA"),
save_to_locker: dict->getString(SaveToLocker->colMapper, "NA"),
connector: dict->getString(Connector->colMapper, "NA"),
error_message: dict->getString(ErrorMessage->colMapper, "NA"),
offer_amount: dict->getString(OfferAmount->colMapper, "NA"),
surcharge_amount: dict->getString(SurchargeAmount->colMapper, "NA"),
tax_amount: dict->getString(TaxAmount->colMapper, "NA"),
payment_method_id: dict->getString(PaymentMethodId->colMapper, "NA"),
payment_method: dict->getString(PaymentMethod->colMapper, "NA"),
connector_transaction_id: dict->getString(ConnectorTransactionId->colMapper, "NA"),
capture_method: dict->getString(CaptureMethod->colMapper, "NA"),
capture_on: dict->getString(CaptureOn->colMapper, "NA"),
authentication_type: dict->getString(AuthenticationType->colMapper, "NA"),
cancellation_reason: dict->getString(CancellationReason->colMapper, "NA"),
amount_to_capture: dict->getString(AmountToCapture->colMapper, "NA"),
mandate_id: dict->getString(MerchantId->colMapper, "NA"),
payment_method_type: dict->getString(PaymentMethodType->colMapper, "NA"),
payment_experience: dict->getString(PaymentExperience->colMapper, "NA"),
error_reason: dict->getString(ErrorReason->colMapper, "NA"),
amount_capturable: dict->getString(AmountCapturable->colMapper, "NA"),
merchant_connector_id: dict->getString(MerchantConnectorId->colMapper, "NA"),
net_amount: dict->getString(NetAmount->colMapper, "NA"),
unified_code: dict->getString(UnifiedCode->colMapper, "NA"),
unified_message: dict->getString(UnifiedMessage->colMapper, "NA"),
client_source: dict->getString(ClientSource->colMapper, "NA"),
client_version: dict->getString(ClientVersion->colMapper, "NA"),
profile_id: dict->getString(ProfileId->colMapper, "NA"),
organization_id: dict->getString(OrganizationId->colMapper, "NA"),
}
}
let getObjects: JSON.t => array<paymentAttemptObject> = json => {
open LogicUtils
json
->LogicUtils.getArrayFromJson([])
->Array.map(item => {
tableItemToObjMapper(item->getDictFromJsonObject)
})
}
let getHeading = colType => {
let key = colType->colMapper
switch colType {
| PaymentId => Table.makeHeaderInfo(~key, ~title="Payment ID", ~dataType=TextType)
| MerchantId => Table.makeHeaderInfo(~key, ~title="Merchant ID", ~dataType=TextType)
| Status => Table.makeHeaderInfo(~key, ~title="Status", ~dataType=TextType)
| Amount => Table.makeHeaderInfo(~key, ~title="Amount", ~dataType=TextType)
| Currency => Table.makeHeaderInfo(~key, ~title="Currency", ~dataType=TextType)
| AmountCaptured => Table.makeHeaderInfo(~key, ~title="Amount Captured", ~dataType=TextType)
| CustomerId => Table.makeHeaderInfo(~key, ~title="Customer Id", ~dataType=TextType)
| Description => Table.makeHeaderInfo(~key, ~title="Description", ~dataType=TextType)
| ReturnUrl => Table.makeHeaderInfo(~key, ~title="Return Url", ~dataType=TextType)
| ConnectorId => Table.makeHeaderInfo(~key, ~title="Connector Id", ~dataType=TextType)
| StatementDescriptorName =>
Table.makeHeaderInfo(~key, ~title="Statement Descriptor Name", ~dataType=TextType)
| StatementDescriptorSuffix =>
Table.makeHeaderInfo(~key, ~title="Statement Descriptor Suffix", ~dataType=TextType)
| CreatedAt => Table.makeHeaderInfo(~key, ~title="Created At", ~dataType=TextType)
| ModifiedAt => Table.makeHeaderInfo(~key, ~title="Modified At", ~dataType=TextType)
| LastSynced => Table.makeHeaderInfo(~key, ~title="Last Synced", ~dataType=TextType)
| SetupFutureUsage => Table.makeHeaderInfo(~key, ~title="Setup Future Usage", ~dataType=TextType)
| OffSession => Table.makeHeaderInfo(~key, ~title="Off Session", ~dataType=TextType)
| ClientSecret => Table.makeHeaderInfo(~key, ~title="Client Secret", ~dataType=TextType)
| ActiveAttemptId => Table.makeHeaderInfo(~key, ~title="Active Attempt Id", ~dataType=TextType)
| BusinessCountry => Table.makeHeaderInfo(~key, ~title="Business Country", ~dataType=TextType)
| BusinessLabel => Table.makeHeaderInfo(~key, ~title="Business Label", ~dataType=TextType)
| AttemptCount => Table.makeHeaderInfo(~key, ~title="Attempt Count", ~dataType=TextType)
| SignFlag => Table.makeHeaderInfo(~key, ~title="Sign Flag", ~dataType=TextType)
| Timestamp => Table.makeHeaderInfo(~key, ~title="Time Stamp", ~dataType=TextType)
| Confirm => Table.makeHeaderInfo(~key, ~title="Confirm", ~dataType=TextType)
| MultipleCaptureCount =>
Table.makeHeaderInfo(~key, ~title="Multiple Capture Count", ~dataType=TextType)
| AttemptId => Table.makeHeaderInfo(~key, ~title="Attempt Id", ~dataType=TextType)
| SaveToLocker => Table.makeHeaderInfo(~key, ~title="Save To Locker", ~dataType=TextType)
| Connector => Table.makeHeaderInfo(~key, ~title="Connector", ~dataType=TextType)
| ErrorMessage => Table.makeHeaderInfo(~key, ~title="Error Message", ~dataType=TextType)
| OfferAmount => Table.makeHeaderInfo(~key, ~title="Offer Amount", ~dataType=TextType)
| SurchargeAmount => Table.makeHeaderInfo(~key, ~title="Surcharge Amount", ~dataType=TextType)
| TaxAmount => Table.makeHeaderInfo(~key, ~title="Tax Amount", ~dataType=TextType)
| PaymentMethodId => Table.makeHeaderInfo(~key, ~title="Payment Method Id", ~dataType=TextType)
| PaymentMethod => Table.makeHeaderInfo(~key, ~title="Payment Method", ~dataType=TextType)
| ConnectorTransactionId =>
Table.makeHeaderInfo(~key, ~title="Connector Transaction Id", ~dataType=TextType)
| CaptureMethod => Table.makeHeaderInfo(~key, ~title="Capture Method", ~dataType=TextType)
| CaptureOn => Table.makeHeaderInfo(~key, ~title="Capture On", ~dataType=TextType)
| AuthenticationType =>
Table.makeHeaderInfo(~key, ~title="Authentication Type", ~dataType=TextType)
| CancellationReason =>
Table.makeHeaderInfo(~key, ~title="Cancellation Reason", ~dataType=TextType)
| AmountToCapture => Table.makeHeaderInfo(~key, ~title="Amount To Capture", ~dataType=TextType)
| MandateId => Table.makeHeaderInfo(~key, ~title="Mandate Id", ~dataType=TextType)
| PaymentMethodType =>
Table.makeHeaderInfo(~key, ~title="Payment Method Type", ~dataType=TextType)
| PaymentExperience => Table.makeHeaderInfo(~key, ~title="Payment Experience", ~dataType=TextType)
| ErrorReason => Table.makeHeaderInfo(~key, ~title="Error Reason", ~dataType=TextType)
| AmountCapturable => Table.makeHeaderInfo(~key, ~title="Amount Capturable", ~dataType=TextType)
| MerchantConnectorId =>
Table.makeHeaderInfo(~key, ~title="Merchant Connector Id", ~dataType=TextType)
| NetAmount => Table.makeHeaderInfo(~key, ~title="Net Amount", ~dataType=TextType)
| UnifiedCode => Table.makeHeaderInfo(~key, ~title="Unified Code", ~dataType=TextType)
| UnifiedMessage => Table.makeHeaderInfo(~key, ~title="Unified Message", ~dataType=TextType)
| ClientSource => Table.makeHeaderInfo(~key, ~title="Client Source", ~dataType=TextType)
| ClientVersion => Table.makeHeaderInfo(~key, ~title="Client Version", ~dataType=TextType)
| ProfileId => Table.makeHeaderInfo(~key, ~title="Profile Id", ~dataType=TextType)
| OrganizationId => Table.makeHeaderInfo(~key, ~title="Organization Id", ~dataType=TextType)
}
}
let getCell = (paymentObj, colType): Table.cell => {
switch colType {
| PaymentId =>
CustomCell(
<HSwitchOrderUtils.CopyLinkTableCell
url={`/payments/${paymentObj.payment_id}/${paymentObj.profile_id}/${paymentObj.merchant_id}/${paymentObj.organization_id}`}
displayValue={paymentObj.payment_id}
copyValue={Some(paymentObj.payment_id)}
/>,
"",
)
| MerchantId => Text(paymentObj.merchant_id)
| Status =>
let orderStatus = paymentObj.status->HSwitchOrderUtils.paymentAttemptStatusVariantMapper
Label({
title: paymentObj.status->String.toUpperCase,
color: switch orderStatus {
| #CHARGED
| #PARTIAL_CHARGED
| #COD_INITIATED
| #AUTO_REFUNDED =>
LabelGreen
| #AUTHENTICATION_FAILED
| #ROUTER_DECLINED
| #AUTHORIZATION_FAILED
| #CAPTURE_FAILED
| #VOID_FAILED
| #FAILURE =>
LabelRed
| #AUTHENTICATION_PENDING
| #AUTHORIZING
| #VOID_INITIATED
| #CAPTURE_INITIATED
| #PENDING =>
LabelOrange
| _ => LabelLightGray
},
})
| Amount =>
CustomCell(
<OrderEntity.CurrencyCell
amount={(paymentObj.amount /. 100.0)->Float.toString} currency={paymentObj.currency}
/>,
"",
)
| Currency => Text(paymentObj.currency)
| AmountCaptured =>
CustomCell(
<OrderEntity.CurrencyCell
amount={(paymentObj.amount_captured /. 100.0)->Float.toString}
currency={paymentObj.currency}
/>,
"",
)
| CustomerId => Text(paymentObj.customer_id)
| Description => Text(paymentObj.description)
| ReturnUrl => Text(paymentObj.return_url)
| ConnectorId => Text(paymentObj.connector_id)
| StatementDescriptorName => Text(paymentObj.statement_descriptor_name)
| StatementDescriptorSuffix => Text(paymentObj.statement_descriptor_suffix)
| CreatedAt => Text(paymentObj.created_at->Int.toString)
| ModifiedAt => Text(paymentObj.modified_at->Int.toString)
| LastSynced => Text(paymentObj.last_synced->Int.toString)
| SetupFutureUsage => Text(paymentObj.setup_future_usage)
| OffSession => Text(paymentObj.off_session)
| ClientSecret => Text(paymentObj.client_secret)
| ActiveAttemptId => Text(paymentObj.active_attempt_id)
| BusinessCountry => Text(paymentObj.business_country)
| BusinessLabel => Text(paymentObj.business_label)
| AttemptCount => Text(paymentObj.attempt_count->Int.toString)
| SignFlag => Text(paymentObj.sign_flag->Int.toString)
| Timestamp => Text(paymentObj.timestamp)
| Confirm => Text(paymentObj.confirm->LogicUtils.getStringFromBool)
| MultipleCaptureCount => Text(paymentObj.multiple_capture_count->Int.toString)
| AttemptId => Text(paymentObj.attempt_id)
| SaveToLocker => Text(paymentObj.save_to_locker)
| Connector => Text(paymentObj.connector)
| ErrorMessage => Text(paymentObj.error_message)
| OfferAmount => Text(paymentObj.offer_amount)
| SurchargeAmount => Text(paymentObj.surcharge_amount)
| TaxAmount => Text(paymentObj.tax_amount)
| PaymentMethodId => Text(paymentObj.payment_method_id)
| PaymentMethod => Text(paymentObj.payment_method)
| ConnectorTransactionId => Text(paymentObj.connector_transaction_id)
| CaptureMethod => Text(paymentObj.capture_method)
| CaptureOn => Text(paymentObj.capture_on)
| AuthenticationType => Text(paymentObj.authentication_type)
| CancellationReason => Text(paymentObj.cancellation_reason)
| AmountToCapture => Text(paymentObj.amount_to_capture)
| MandateId => Text(paymentObj.mandate_id)
| PaymentMethodType => Text(paymentObj.payment_method_type)
| PaymentExperience => Text(paymentObj.payment_experience)
| ErrorReason => Text(paymentObj.error_reason)
| AmountCapturable => Text(paymentObj.amount_capturable)
| MerchantConnectorId => Text(paymentObj.merchant_connector_id)
| NetAmount => Text(paymentObj.net_amount)
| UnifiedCode => Text(paymentObj.unified_code)
| UnifiedMessage => Text(paymentObj.unified_message)
| ClientSource => Text(paymentObj.client_source)
| ClientVersion => Text(paymentObj.client_version)
| ProfileId => Text(paymentObj.profile_id)
| OrganizationId => Text(paymentObj.organization_id)
}
}
let tableEntity = EntityType.makeEntity(
~uri=``,
~getObjects,
~dataKey="queryData",
~defaultColumns=visibleColumns,
~requiredSearchFieldsList=[],
~allColumns=visibleColumns,
~getCell,
~getHeading,
~getShowLink={
order =>
GlobalVars.appendDashboardPath(
~url=`/payments/${order.payment_id}/${order.profile_id}/${order.merchant_id}/${order.organization_id}`,
)
},
)
| 4,637 | 9,788 |
hyperswitch-control-center | src/screens/Analytics/GlobalSearchResults/GlobalSearchTables/PaymentAttempt/PaymentAttemptTable.res | .res | module PreviewTable = {
open PaymentAttemptEntity
open GlobalSearchTypes
open ResultsTableUtils
@react.component
let make = (~data) => {
let defaultSort: Table.sortedObject = {
key: "",
order: Table.INC,
}
let tableData =
data
->Array.map(item => {
let data = item.texts->Array.get(0)->Option.getOr(Dict.make()->JSON.Encode.object)
data->JSON.Decode.object->Option.getOr(Dict.make())
})
->Array.filter(dict => dict->Dict.keysToArray->Array.length > 0)
->Array.map(item => item->tableItemToObjMapper->Nullable.make)
<LoadedTable
visibleColumns
title=domain
hideTitle=true
actualData={tableData}
entity=tableEntity
resultsPerPage=10
totalResults={tableData->Array.length}
offset={0}
setOffset={_ => ()}
defaultSort
currrentFetchCount={tableData->Array.length}
tableLocalFilter=false
tableheadingClass=tableBorderClass
tableBorderClass
ignoreHeaderBg=true
tableDataBorderClass=tableBorderClass
isAnalyticsModule=false
showResultsPerPageSelector=false
paginationClass="hidden"
/>
}
}
@react.component
let make = () => {
open APIUtils
open PaymentAttemptEntity
let updateDetails = useUpdateMethod()
let fetchTableData = ResultsTableUtils.useGetData()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (data, setData) = React.useState(_ => [])
let (totalCount, setTotalCount) = React.useState(_ => 0)
let widthClass = "w-full"
let heightClass = ""
let defaultValue: LoadedTable.pageDetails = {offset: 0, resultsPerPage: 10}
let pageDetailDict = Recoil.useRecoilValueFromAtom(LoadedTable.table_pageDetails)
let setPageDetails = Recoil.useSetRecoilState(LoadedTable.table_pageDetails)
let pageDetail = pageDetailDict->Dict.get(domain)->Option.getOr(defaultValue)
let (offset, setOffset) = React.useState(_ => pageDetail.offset)
let searchText = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("query", "")
let path = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("domain", "")
let clearPageDetails = () => {
let newDict = pageDetailDict->Dict.toArray->Dict.fromArray
newDict->Dict.set(domain, defaultValue)
setPageDetails(_ => newDict)
}
let getData = async () => {
setScreenState(_ => PageLoaderWrapper.Loading)
try {
let (data, total) = await fetchTableData(~updateDetails, ~offset, ~query={searchText}, ~path)
let arr = Array.make(~length=offset, Dict.make())
if total <= offset {
setOffset(_ => 0)
}
if total > 0 {
let dataDictArr = data->Belt.Array.keepMap(JSON.Decode.object)
let orderData = arr->Array.concat(dataDictArr)->Array.map(tableItemToObjMapper)
let list = orderData->Array.map(Nullable.make)
setTotalCount(_ => total)
setData(_ => list)
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Error("Something went wrong!"))
}
}
React.useEffect(() => {
if searchText->String.length > 0 {
getData()->ignore
} else {
setScreenState(_ => PageLoaderWrapper.Success)
}
Some(
() => {
clearPageDetails()
},
)
}, (offset, searchText))
open ResultsTableUtils
<div className={`flex flex-col mx-auto h-full ${widthClass} ${heightClass} min-h-[50vh]`}>
<PageUtils.PageHeading title="Payment Attempt" />
<PageLoaderWrapper screenState>
<LoadedTable
visibleColumns
title=domain
hideTitle=true
actualData=data
entity=tableEntity
resultsPerPage=10
showSerialNumber=true
totalResults={totalCount}
offset
setOffset
currrentFetchCount={data->Array.length}
tableLocalFilter=false
tableheadingClass=tableBorderClass
tableBorderClass
ignoreHeaderBg=true
tableDataBorderClass=tableBorderClass
isAnalyticsModule=false
showResultsPerPageSelector=false
/>
</PageLoaderWrapper>
</div>
}
| 1,031 | 9,789 |
hyperswitch-control-center | src/screens/Analytics/GlobalSearchResults/GlobalSearchTables/Refunds/RefundsTable.res | .res | module PreviewTable = {
@react.component
let make = (~data) => {
open RefundsTableEntity
open GlobalSearchTypes
let defaultSort: Table.sortedObject = {
key: "",
order: Table.INC,
}
let tableData =
data
->Array.map(item => {
let data = item.texts->Array.get(0)->Option.getOr(Dict.make()->JSON.Encode.object)
data->JSON.Decode.object->Option.getOr(Dict.make())
})
->Array.filter(dict => dict->Dict.keysToArray->Array.length > 0)
->Array.map(item => item->tableItemToObjMapper->Nullable.make)
open ResultsTableUtils
<LoadedTable
visibleColumns
title=domain
hideTitle=true
actualData={tableData}
entity=tableEntity
resultsPerPage=10
totalResults={tableData->Array.length}
offset={0}
setOffset={_ => ()}
defaultSort
currrentFetchCount={tableData->Array.length}
tableLocalFilter=false
tableheadingClass=tableBorderClass
tableBorderClass
ignoreHeaderBg=true
tableDataBorderClass=tableBorderClass
isAnalyticsModule=false
showResultsPerPageSelector=false
paginationClass="hidden"
/>
}
}
@react.component
let make = () => {
open APIUtils
open RefundsTableEntity
let updateDetails = useUpdateMethod()
let fetchTableData = ResultsTableUtils.useGetData()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (data, setData) = React.useState(_ => [])
let (totalCount, setTotalCount) = React.useState(_ => 0)
let widthClass = "w-full"
let heightClass = ""
let defaultValue: LoadedTable.pageDetails = {offset: 0, resultsPerPage: 10}
let pageDetailDict = Recoil.useRecoilValueFromAtom(LoadedTable.table_pageDetails)
let pageDetail = pageDetailDict->Dict.get(domain)->Option.getOr(defaultValue)
let setPageDetails = Recoil.useSetRecoilState(LoadedTable.table_pageDetails)
let (offset, setOffset) = React.useState(_ => pageDetail.offset)
let searchText = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("query", "")
let path = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("domain", "")
let clearPageDetails = () => {
let newDict = pageDetailDict->Dict.toArray->Dict.fromArray
newDict->Dict.set(domain, defaultValue)
setPageDetails(_ => newDict)
}
let getData = async () => {
setScreenState(_ => PageLoaderWrapper.Loading)
try {
let (data, total) = await fetchTableData(~updateDetails, ~offset, ~query={searchText}, ~path)
let arr = Array.make(~length=offset, Dict.make())
if total <= offset {
setOffset(_ => 0)
}
if total > 0 {
let dataDictArr = data->Belt.Array.keepMap(JSON.Decode.object)
let orderData = arr->Array.concat(dataDictArr)->Array.map(tableItemToObjMapper)
let list = orderData->Array.map(Nullable.make)
setTotalCount(_ => total)
setData(_ => list)
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Error("Something went wrong!"))
}
}
React.useEffect(() => {
if searchText->String.length > 0 {
getData()->ignore
} else {
setScreenState(_ => PageLoaderWrapper.Success)
}
Some(
() => {
clearPageDetails()
},
)
}, (offset, searchText))
open ResultsTableUtils
<div className={`flex flex-col mx-auto h-full ${widthClass} ${heightClass} min-h-[50vh]`}>
<PageUtils.PageHeading title="Refunds" />
<PageLoaderWrapper screenState>
<LoadedTable
visibleColumns
title=domain
hideTitle=true
actualData=data
entity=tableEntity
resultsPerPage=10
showSerialNumber=true
totalResults={totalCount}
offset
setOffset
currrentFetchCount={data->Array.length}
tableLocalFilter=false
tableheadingClass=tableBorderClass
tableBorderClass
ignoreHeaderBg=true
tableDataBorderClass=tableBorderClass
isAnalyticsModule=false
showResultsPerPageSelector=false
/>
</PageLoaderWrapper>
</div>
}
| 1,033 | 9,790 |
hyperswitch-control-center | src/screens/Analytics/GlobalSearchResults/GlobalSearchTables/Refunds/RefundsTableEntity.res | .res | let domain = "refunds"
type refundsObject = {
internal_reference_id: string,
refund_id: string,
payment_id: string,
merchant_id: string,
connector_transaction_id: string,
connector: string,
connector_refund_id: string,
external_reference_id: string,
refund_type: string,
total_amount: float,
currency: string,
refund_amount: float,
refund_status: string,
sent_to_gateway: bool,
refund_error_message: string,
refund_arn: string,
created_at: int,
modified_at: int,
description: string,
attempt_id: string,
refund_reason: string,
refund_error_code: string,
sign_flag: int,
timestamp: string,
profile_id: string,
organization_id: string,
}
type cols =
| InternalReferenceId
| RefundId
| PaymentId
| MerchantId
| ConnectorTransactionId
| Connector
| ConnectorRefundId
| ExternalReferenceId
| RefundType
| TotalAmount
| Currency
| RefundAmount
| Refundstatus
| SentToGateway
| RefundErrorMessage
| RefundArn
| CreatedAt
| ModifiedAt
| Description
| AttemptId
| RefundReason
| RefundErrorCode
| SignFlag
| Timestamp
| ProfileId
| OrganizationId
let visibleColumns = [RefundId, PaymentId, Refundstatus, TotalAmount, Currency, Connector]
let colMapper = (col: cols) => {
switch col {
| InternalReferenceId => "internal_reference_id"
| RefundId => "refund_id"
| PaymentId => "payment_id"
| MerchantId => "merchant_id"
| ConnectorTransactionId => "connector_transaction_id"
| Connector => "connector"
| ConnectorRefundId => "connector_refund_id"
| ExternalReferenceId => "external_reference_id"
| RefundType => "refund_type"
| TotalAmount => "total_amount"
| Currency => "currency"
| RefundAmount => "refund_amount"
| Refundstatus => "refund_status"
| SentToGateway => "sent_to_gateway"
| RefundErrorMessage => "refund_error_message"
| RefundArn => "refund_arn"
| CreatedAt => "created_at"
| ModifiedAt => "modified_at"
| Description => "description"
| AttemptId => "attempt_id"
| RefundReason => "refund_reason"
| RefundErrorCode => "refund_error_code"
| SignFlag => "sign_flag"
| Timestamp => "timestamp"
| ProfileId => "profile_id"
| OrganizationId => "organization_id"
}
}
let tableItemToObjMapper: Dict.t<JSON.t> => refundsObject = dict => {
open LogicUtils
{
internal_reference_id: dict->getString(InternalReferenceId->colMapper, "NA"),
refund_id: dict->getString(RefundId->colMapper, "NA"),
payment_id: dict->getString(PaymentId->colMapper, "NA"),
merchant_id: dict->getString(MerchantId->colMapper, "NA"),
connector_transaction_id: dict->getString(ConnectorTransactionId->colMapper, "NA"),
connector: dict->getString(Connector->colMapper, "NA"),
connector_refund_id: dict->getString(ConnectorRefundId->colMapper, "NA"),
external_reference_id: dict->getString(ExternalReferenceId->colMapper, "NA"),
refund_type: dict->getString(RefundType->colMapper, "NA"),
total_amount: dict->getFloat(TotalAmount->colMapper, 0.0),
currency: dict->getString(Currency->colMapper, "NA"),
refund_amount: dict->getFloat(RefundAmount->colMapper, 0.0),
refund_status: dict->getString(Refundstatus->colMapper, "NA"),
sent_to_gateway: dict->getBool(SentToGateway->colMapper, false),
refund_error_message: dict->getString(RefundErrorMessage->colMapper, "NA"),
refund_arn: dict->getString(RefundArn->colMapper, "NA"),
created_at: dict->getInt(CreatedAt->colMapper, 0),
modified_at: dict->getInt(ModifiedAt->colMapper, 0),
description: dict->getString(Description->colMapper, "NA"),
attempt_id: dict->getString(AttemptId->colMapper, "NA"),
refund_reason: dict->getString(RefundReason->colMapper, "NA"),
refund_error_code: dict->getString(RefundErrorCode->colMapper, "NA"),
sign_flag: dict->getInt(SignFlag->colMapper, 0),
timestamp: dict->getString(Timestamp->colMapper, "NA"),
profile_id: dict->getString(ProfileId->colMapper, "NA"),
organization_id: dict->getString(OrganizationId->colMapper, "NA"),
}
}
let getObjects: JSON.t => array<refundsObject> = json => {
open LogicUtils
json
->LogicUtils.getArrayFromJson([])
->Array.map(item => {
tableItemToObjMapper(item->getDictFromJsonObject)
})
}
let getHeading = colType => {
let key = colType->colMapper
switch colType {
| InternalReferenceId =>
Table.makeHeaderInfo(~key, ~title="Internal Reference Id ", ~dataType=TextType)
| RefundId => Table.makeHeaderInfo(~key, ~title="Refund Id", ~dataType=TextType)
| PaymentId => Table.makeHeaderInfo(~key, ~title="Payment Id", ~dataType=TextType)
| MerchantId => Table.makeHeaderInfo(~key, ~title="Merchant Id", ~dataType=TextType)
| ConnectorTransactionId =>
Table.makeHeaderInfo(~key, ~title="Connector Transaction Id", ~dataType=TextType)
| Connector => Table.makeHeaderInfo(~key, ~title="Connector", ~dataType=TextType)
| ConnectorRefundId =>
Table.makeHeaderInfo(~key, ~title="Connector Refund Id", ~dataType=TextType)
| ExternalReferenceId =>
Table.makeHeaderInfo(~key, ~title="External Reference Id", ~dataType=TextType)
| RefundType => Table.makeHeaderInfo(~key, ~title="Refund Type", ~dataType=TextType)
| TotalAmount => Table.makeHeaderInfo(~key, ~title="Total Amount", ~dataType=TextType)
| Currency => Table.makeHeaderInfo(~key, ~title="Currency", ~dataType=TextType)
| RefundAmount => Table.makeHeaderInfo(~key, ~title="Refund Amount", ~dataType=TextType)
| Refundstatus => Table.makeHeaderInfo(~key, ~title="Refund Status", ~dataType=TextType)
| SentToGateway => Table.makeHeaderInfo(~key, ~title="Sent To Gateway", ~dataType=TextType)
| RefundErrorMessage =>
Table.makeHeaderInfo(~key, ~title="Refund Error Message", ~dataType=TextType)
| RefundArn => Table.makeHeaderInfo(~key, ~title="Refund Arn", ~dataType=TextType)
| CreatedAt => Table.makeHeaderInfo(~key, ~title="Created At", ~dataType=TextType)
| ModifiedAt => Table.makeHeaderInfo(~key, ~title="Modified At", ~dataType=TextType)
| Description => Table.makeHeaderInfo(~key, ~title="Description", ~dataType=TextType)
| AttemptId => Table.makeHeaderInfo(~key, ~title="Attempt Id", ~dataType=TextType)
| RefundReason => Table.makeHeaderInfo(~key, ~title="Refund Reason", ~dataType=TextType)
| RefundErrorCode => Table.makeHeaderInfo(~key, ~title="Refund Error Code", ~dataType=TextType)
| SignFlag => Table.makeHeaderInfo(~key, ~title="Sign Flag", ~dataType=TextType)
| Timestamp => Table.makeHeaderInfo(~key, ~title="Timestamp", ~dataType=TextType)
| ProfileId => Table.makeHeaderInfo(~key, ~title="Profile Id", ~dataType=TextType)
| OrganizationId => Table.makeHeaderInfo(~key, ~title="Organization Id", ~dataType=TextType)
}
}
let getCell = (refundsObj, colType): Table.cell => {
switch colType {
| InternalReferenceId => Text(refundsObj.internal_reference_id)
| RefundId =>
CustomCell(
<HSwitchOrderUtils.CopyLinkTableCell
url={`/refunds/${refundsObj.refund_id}/${refundsObj.profile_id}/${refundsObj.merchant_id}/${refundsObj.organization_id}`}
displayValue={refundsObj.refund_id}
copyValue={Some(refundsObj.refund_id)}
/>,
"",
)
| PaymentId => Text(refundsObj.payment_id)
| MerchantId => Text(refundsObj.merchant_id)
| ConnectorTransactionId => Text(refundsObj.connector_transaction_id)
| Connector => Text(refundsObj.connector)
| ConnectorRefundId => Text(refundsObj.connector_refund_id)
| ExternalReferenceId => Text(refundsObj.external_reference_id)
| RefundType => Text(refundsObj.refund_type)
| TotalAmount =>
CustomCell(
<OrderEntity.CurrencyCell
amount={(refundsObj.total_amount /. 100.0)->Float.toString} currency={refundsObj.currency}
/>,
"",
)
| Currency => Text(refundsObj.currency)
| RefundAmount =>
CustomCell(
<OrderEntity.CurrencyCell
amount={(refundsObj.refund_amount /. 100.0)->Float.toString} currency={refundsObj.currency}
/>,
"",
)
| Refundstatus =>
let refundStatus = refundsObj.refund_status->HSwitchOrderUtils.refundStatusVariantMapper
Label({
title: refundsObj.refund_status->String.toUpperCase,
color: switch refundStatus {
| Success => LabelGreen
| Failure => LabelRed
| Pending => LabelYellow
| _ => LabelLightGray
},
})
| SentToGateway => Text(refundsObj.sent_to_gateway->LogicUtils.getStringFromBool)
| RefundErrorMessage => Text(refundsObj.refund_error_message)
| RefundArn => Text(refundsObj.refund_arn)
| CreatedAt => Text(refundsObj.created_at->Int.toString)
| ModifiedAt => Text(refundsObj.modified_at->Int.toString)
| Description => Text(refundsObj.description)
| AttemptId => Text(refundsObj.attempt_id)
| RefundReason => Text(refundsObj.refund_reason)
| RefundErrorCode => Text(refundsObj.refund_error_code)
| SignFlag => Text(refundsObj.sign_flag->Int.toString)
| Timestamp => Text(refundsObj.timestamp)
| ProfileId => Text(refundsObj.profile_id)
| OrganizationId => Text(refundsObj.organization_id)
}
}
let tableEntity = EntityType.makeEntity(
~uri=``,
~getObjects,
~dataKey="queryData",
~defaultColumns=visibleColumns,
~requiredSearchFieldsList=[],
~allColumns=visibleColumns,
~getCell,
~getHeading,
~getShowLink={
refund =>
GlobalVars.appendDashboardPath(
~url=`/refunds/${refund.refund_id}/${refund.profile_id}/${refund.merchant_id}/${refund.organization_id}`,
)
},
)
| 2,522 | 9,791 |
hyperswitch-control-center | src/screens/Analytics/GlobalSearchResults/GlobalSearchTables/PaymentIntent/PaymentIntentEntity.res | .res | let domain = "payment_intents"
type paymentIntentObject = {
payment_id: string,
merchant_id: string,
status: string,
amount: float,
currency: string,
amount_captured: float,
customer_id: string,
description: string,
return_url: string,
connector_id: string,
statement_descriptor_name: string,
statement_descriptor_suffix: string,
created_at: int,
modified_at: int,
last_synced: int,
setup_future_usage: string,
off_session: string,
client_secret: string,
active_attempt_id: string,
business_country: string,
business_label: string,
attempt_count: int,
sign_flag: int,
timestamp: string,
profile_id: string,
organization_id: string,
}
type cols =
| PaymentId
| MerchantId
| Status
| Amount
| Currency
| AmountCaptured
| CustomerId
| Description
| ReturnUrl
| ConnectorId
| StatementDescriptorName
| StatementDescriptorSuffix
| CreatedAt
| ModifiedAt
| LastSynced
| SetupFutureUsage
| OffSession
| ClientSecret
| ActiveAttemptId
| BusinessCountry
| BusinessLabel
| AttemptCount
| SignFlag
| Timestamp
| ProfileId
| OrganizationId
let visibleColumns = [
PaymentId,
MerchantId,
Status,
Amount,
Currency,
ActiveAttemptId,
BusinessCountry,
BusinessLabel,
AttemptCount,
]
let colMapper = (col: cols) => {
switch col {
| PaymentId => "payment_id"
| MerchantId => "merchant_id"
| Status => "status"
| Amount => "amount"
| Currency => "currency"
| AmountCaptured => "amount_captured"
| CustomerId => "customer_id"
| Description => "description"
| ReturnUrl => "return_url"
| ConnectorId => "connector_id"
| StatementDescriptorName => "statement_descriptor_name"
| StatementDescriptorSuffix => "statement_descriptor_suffix"
| CreatedAt => "created_at"
| ModifiedAt => "modified_at"
| LastSynced => "last_synced"
| SetupFutureUsage => "setup_future_usage"
| OffSession => "off_session"
| ClientSecret => "client_secret"
| ActiveAttemptId => "active_attempt_id"
| BusinessCountry => "business_country"
| BusinessLabel => "business_label"
| AttemptCount => "attempt_count"
| SignFlag => "sign_flag"
| Timestamp => "@timestamp"
| ProfileId => "profile_id"
| OrganizationId => "organization_id"
}
}
let tableItemToObjMapper: Dict.t<JSON.t> => paymentIntentObject = dict => {
open LogicUtils
{
payment_id: dict->getString(PaymentId->colMapper, "NA"),
merchant_id: dict->getString(MerchantId->colMapper, "NA"),
status: dict->getString(Status->colMapper, "NA"),
amount: dict->getFloat(Amount->colMapper, 0.0),
currency: dict->getString(Currency->colMapper, "NA"),
amount_captured: dict->getFloat(AmountCaptured->colMapper, 0.0),
customer_id: dict->getString(CustomerId->colMapper, "NA"),
description: dict->getString(Description->colMapper, "NA"),
return_url: dict->getString(ReturnUrl->colMapper, "NA"),
connector_id: dict->getString(ConnectorId->colMapper, "NA"),
statement_descriptor_name: dict->getString(StatementDescriptorName->colMapper, "NA"),
statement_descriptor_suffix: dict->getString(StatementDescriptorSuffix->colMapper, "NA"),
created_at: dict->getInt(CreatedAt->colMapper, 0),
modified_at: dict->getInt(ModifiedAt->colMapper, 0),
last_synced: dict->getInt(LastSynced->colMapper, 0),
setup_future_usage: dict->getString(SetupFutureUsage->colMapper, "NA"),
off_session: dict->getString(OffSession->colMapper, "NA"),
client_secret: dict->getString(ClientSecret->colMapper, "NA"),
active_attempt_id: dict->getString(ActiveAttemptId->colMapper, "NA"),
business_country: dict->getString(BusinessCountry->colMapper, "NA"),
business_label: dict->getString(BusinessLabel->colMapper, "NA"),
attempt_count: dict->getInt(AttemptCount->colMapper, 0),
sign_flag: dict->getInt(SignFlag->colMapper, 0),
timestamp: dict->getString(Timestamp->colMapper, "NA"),
profile_id: dict->getString(ProfileId->colMapper, "NA"),
organization_id: dict->getString(OrganizationId->colMapper, "NA"),
}
}
let getObjects: JSON.t => array<paymentIntentObject> = json => {
open LogicUtils
json
->LogicUtils.getArrayFromJson([])
->Array.map(item => {
tableItemToObjMapper(item->getDictFromJsonObject)
})
}
let getHeading = colType => {
let key = colType->colMapper
switch colType {
| PaymentId => Table.makeHeaderInfo(~key, ~title="Payment Id", ~dataType=TextType)
| MerchantId => Table.makeHeaderInfo(~key, ~title="Merchant Id", ~dataType=TextType)
| Status => Table.makeHeaderInfo(~key, ~title="Status", ~dataType=TextType)
| Amount => Table.makeHeaderInfo(~key, ~title="Amount", ~dataType=TextType)
| Currency => Table.makeHeaderInfo(~key, ~title="Currency", ~dataType=TextType)
| AmountCaptured => Table.makeHeaderInfo(~key, ~title="Amount Captured", ~dataType=TextType)
| CustomerId => Table.makeHeaderInfo(~key, ~title="Customer Id", ~dataType=TextType)
| Description => Table.makeHeaderInfo(~key, ~title="Description", ~dataType=TextType)
| ReturnUrl => Table.makeHeaderInfo(~key, ~title="Return Url", ~dataType=TextType)
| ConnectorId => Table.makeHeaderInfo(~key, ~title="Connector Id", ~dataType=TextType)
| StatementDescriptorName =>
Table.makeHeaderInfo(~key, ~title="Statement Descriptor Name", ~dataType=TextType)
| StatementDescriptorSuffix =>
Table.makeHeaderInfo(~key, ~title="Statement Descriptor Suffix", ~dataType=TextType)
| CreatedAt => Table.makeHeaderInfo(~key, ~title="Created At", ~dataType=TextType)
| ModifiedAt => Table.makeHeaderInfo(~key, ~title="Modified At", ~dataType=TextType)
| LastSynced => Table.makeHeaderInfo(~key, ~title="Last Synced", ~dataType=TextType)
| SetupFutureUsage => Table.makeHeaderInfo(~key, ~title="Setup Future Usage", ~dataType=TextType)
| OffSession => Table.makeHeaderInfo(~key, ~title="Off Session", ~dataType=TextType)
| ClientSecret => Table.makeHeaderInfo(~key, ~title="Client Secret", ~dataType=TextType)
| ActiveAttemptId => Table.makeHeaderInfo(~key, ~title="Active Attempt Id", ~dataType=TextType)
| BusinessCountry => Table.makeHeaderInfo(~key, ~title="Business Country", ~dataType=TextType)
| BusinessLabel => Table.makeHeaderInfo(~key, ~title="Business Label", ~dataType=TextType)
| AttemptCount => Table.makeHeaderInfo(~key, ~title="Attempt Count", ~dataType=TextType)
| SignFlag => Table.makeHeaderInfo(~key, ~title="Sign Flag", ~dataType=TextType)
| Timestamp => Table.makeHeaderInfo(~key, ~title="Time Stamp", ~dataType=TextType)
| ProfileId => Table.makeHeaderInfo(~key, ~title="Profile Id", ~dataType=TextType)
| OrganizationId => Table.makeHeaderInfo(~key, ~title="Organization Id", ~dataType=TextType)
}
}
let getCell = (paymentObj, colType): Table.cell => {
let orderStatus = paymentObj.status->HSwitchOrderUtils.statusVariantMapper
switch colType {
| PaymentId =>
CustomCell(
<HSwitchOrderUtils.CopyLinkTableCell
url={`/payments/${paymentObj.payment_id}/${paymentObj.profile_id}/${paymentObj.merchant_id}/${paymentObj.organization_id}`}
displayValue={paymentObj.payment_id}
copyValue={Some(paymentObj.payment_id)}
/>,
"",
)
| MerchantId => Text(paymentObj.merchant_id)
| Status =>
Label({
title: paymentObj.status->String.toUpperCase,
color: switch orderStatus {
| Succeeded
| PartiallyCaptured =>
LabelGreen
| Failed
| Cancelled =>
LabelRed
| Processing
| RequiresCustomerAction
| RequiresConfirmation
| RequiresPaymentMethod =>
LabelBlue
| _ => LabelLightGray
},
})
| Amount =>
CustomCell(
<OrderEntity.CurrencyCell
amount={(paymentObj.amount /. 100.0)->Float.toString} currency={paymentObj.currency}
/>,
"",
)
| Currency => Text(paymentObj.currency)
| AmountCaptured =>
CustomCell(
<OrderEntity.CurrencyCell
amount={(paymentObj.amount_captured /. 100.0)->Float.toString}
currency={paymentObj.currency}
/>,
"",
)
| CustomerId => Text(paymentObj.customer_id)
| Description => Text(paymentObj.description)
| ReturnUrl => Text(paymentObj.return_url)
| ConnectorId => Text(paymentObj.connector_id)
| StatementDescriptorName => Text(paymentObj.statement_descriptor_name)
| StatementDescriptorSuffix => Text(paymentObj.statement_descriptor_suffix)
| CreatedAt => Text(paymentObj.created_at->Int.toString)
| ModifiedAt => Text(paymentObj.modified_at->Int.toString)
| LastSynced => Text(paymentObj.last_synced->Int.toString)
| SetupFutureUsage => Text(paymentObj.setup_future_usage)
| OffSession => Text(paymentObj.off_session)
| ClientSecret => Text(paymentObj.client_secret)
| ActiveAttemptId => Text(paymentObj.active_attempt_id)
| BusinessCountry => Text(paymentObj.business_country)
| BusinessLabel => Text(paymentObj.business_label)
| AttemptCount => Text(paymentObj.attempt_count->Int.toString)
| SignFlag => Text(paymentObj.sign_flag->Int.toString)
| Timestamp => Text(paymentObj.timestamp)
| ProfileId => Text(paymentObj.profile_id)
| OrganizationId => Text(paymentObj.organization_id)
}
}
let tableEntity = EntityType.makeEntity(
~uri=``,
~getObjects,
~dataKey="queryData",
~defaultColumns=visibleColumns,
~requiredSearchFieldsList=[],
~allColumns=visibleColumns,
~getCell,
~getHeading,
~getShowLink={
order => {
GlobalVars.appendDashboardPath(
~url=`/payments/${order.payment_id}/${order.profile_id}/${order.merchant_id}/${order.organization_id}`,
)
}
},
)
| 2,454 | 9,792 |
hyperswitch-control-center | src/screens/Analytics/GlobalSearchResults/GlobalSearchTables/PaymentIntent/PaymentIntentTable.res | .res | module PreviewTable = {
@react.component
let make = (~data) => {
open GlobalSearchTypes
open PaymentIntentEntity
let defaultSort: Table.sortedObject = {
key: "",
order: Table.INC,
}
let tableData =
data
->Array.map(item => {
let data = item.texts->Array.get(0)->Option.getOr(Dict.make()->JSON.Encode.object)
data->JSON.Decode.object->Option.getOr(Dict.make())
})
->Array.filter(dict => dict->Dict.keysToArray->Array.length > 0)
->Array.map(item => item->tableItemToObjMapper->Nullable.make)
open ResultsTableUtils
<LoadedTable
visibleColumns
title=domain
hideTitle=true
actualData={tableData}
entity=tableEntity
resultsPerPage=10
totalResults={tableData->Array.length}
offset={0}
setOffset={_ => ()}
defaultSort
currrentFetchCount={tableData->Array.length}
tableLocalFilter=false
tableheadingClass=tableBorderClass
tableBorderClass
ignoreHeaderBg=true
tableDataBorderClass=tableBorderClass
isAnalyticsModule=false
showResultsPerPageSelector=false
paginationClass="hidden"
/>
}
}
@react.component
let make = () => {
open APIUtils
open PaymentIntentEntity
let updateDetails = useUpdateMethod()
let fetchTableData = ResultsTableUtils.useGetData()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (data, setData) = React.useState(_ => [])
let (totalCount, setTotalCount) = React.useState(_ => 0)
let widthClass = "w-full"
let heightClass = ""
let defaultValue: LoadedTable.pageDetails = {offset: 0, resultsPerPage: 10}
let pageDetailDict = Recoil.useRecoilValueFromAtom(LoadedTable.table_pageDetails)
let setPageDetails = Recoil.useSetRecoilState(LoadedTable.table_pageDetails)
let pageDetail = pageDetailDict->Dict.get(domain)->Option.getOr(defaultValue)
let (offset, setOffset) = React.useState(_ => pageDetail.offset)
let searchText = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("query", "")
let path = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("domain", "")
let clearPageDetails = () => {
let newDict = pageDetailDict->Dict.toArray->Dict.fromArray
newDict->Dict.set(domain, defaultValue)
setPageDetails(_ => newDict)
}
let getData = async () => {
setScreenState(_ => PageLoaderWrapper.Loading)
try {
let (data, total) = await fetchTableData(~updateDetails, ~offset, ~query={searchText}, ~path)
let arr = Array.make(~length=offset, Dict.make())
if total <= offset {
setOffset(_ => 0)
}
if total > 0 {
let dataDictArr = data->Belt.Array.keepMap(JSON.Decode.object)
let orderData = arr->Array.concat(dataDictArr)->Array.map(tableItemToObjMapper)
let list = orderData->Array.map(Nullable.make)
setTotalCount(_ => total)
setData(_ => list)
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Error("Something went wrong!"))
}
}
React.useEffect(() => {
if searchText->String.length > 0 {
getData()->ignore
} else {
setScreenState(_ => PageLoaderWrapper.Success)
}
Some(
() => {
clearPageDetails()
},
)
}, (offset, searchText))
open ResultsTableUtils
<div className={`flex flex-col mx-auto h-full ${widthClass} ${heightClass} min-h-[50vh]`}>
<PageUtils.PageHeading title="Payment Intent" />
<PageLoaderWrapper screenState>
<LoadedTable
visibleColumns
title=domain
hideTitle=true
actualData=data
entity=tableEntity
resultsPerPage=10
showSerialNumber=true
totalResults={totalCount}
offset
setOffset
currrentFetchCount={data->Array.length}
tableLocalFilter=false
tableheadingClass=tableBorderClass
tableBorderClass
ignoreHeaderBg=true
tableDataBorderClass=tableBorderClass
isAnalyticsModule=false
showResultsPerPageSelector=false
/>
</PageLoaderWrapper>
</div>
}
| 1,031 | 9,793 |
hyperswitch-control-center | src/screens/Analytics/AuthenticationAnalytics/AuthenticationAnalyticsEntity.res | .res | open LogicUtils
open DynamicSingleStat
open HSAnalyticsUtils
open AnalyticsTypes
let singleStatInitialValue = {
authentication_count: 0,
authentication_success_count: 0,
authentication_attempt_count: 0,
challenge_flow_count: 0,
challenge_attempt_count: 0,
challenge_success_count: 0,
frictionless_flow_count: 0,
frictionless_success_count: 0,
}
let singleStatSeriesInitialValue = {
authentication_count: 0,
authentication_success_count: 0,
authentication_attempt_count: 0,
challenge_flow_count: 0,
challenge_attempt_count: 0,
challenge_success_count: 0,
frictionless_flow_count: 0,
frictionless_success_count: 0,
time_series: "",
}
let singleStatItemToObjMapper = json => {
json
->JSON.Decode.object
->Option.map(dict => {
authentication_count: dict->getInt("authentication_count", 0),
authentication_success_count: dict->getInt("authentication_success_count", 0),
authentication_attempt_count: dict->getInt("authentication_attempt_count", 0),
challenge_flow_count: dict->getInt("challenge_flow_count", 0),
challenge_attempt_count: dict->getInt("challenge_attempt_count", 0),
challenge_success_count: dict->getInt("challenge_success_count", 0),
frictionless_flow_count: dict->getInt("frictionless_flow_count", 0),
frictionless_success_count: dict->getInt("frictionless_success_count", 0),
})
->Option.getOr({
singleStatInitialValue
})
}
let singleStatSeriesItemToObjMapper = json => {
json
->JSON.Decode.object
->Option.map(dict => {
time_series: dict->getString("time_bucket", ""),
authentication_count: dict->getInt("authentication_count", 0),
authentication_success_count: dict->getInt("authentication_success_count", 0),
authentication_attempt_count: dict->getInt("authentication_attempt_count", 0),
challenge_flow_count: dict->getInt("challenge_flow_count", 0),
challenge_attempt_count: dict->getInt("challenge_attempt_count", 0),
challenge_success_count: dict->getInt("challenge_success_count", 0),
frictionless_flow_count: dict->getInt("frictionless_flow_count", 0),
frictionless_success_count: dict->getInt("frictionless_success_count", 0),
})
->Option.getOr({
singleStatSeriesInitialValue
})
}
let itemToObjMapper = json => {
json->getQueryData->Array.map(singleStatItemToObjMapper)
}
let timeSeriesObjMapper = json =>
json->getQueryData->Array.map(json => singleStatSeriesItemToObjMapper(json))
type colT =
| AuthenticationCount
| AuthenticationSuccessRate
| ChallengeFlowRate
| FrictionlessFlowRate
| ChallengeAttemptRate
| ChallengeSuccessRate
| FrictionlessSuccessRate
let defaultColumns: array<DynamicSingleStat.columns<colT>> = [
{
sectionName: "",
columns: [
AuthenticationCount,
AuthenticationSuccessRate,
ChallengeFlowRate,
FrictionlessFlowRate,
ChallengeAttemptRate,
ChallengeSuccessRate,
FrictionlessSuccessRate,
]->generateDefaultStateColumns,
},
]
let compareLogic = (firstValue, secondValue) => {
let (temp1, _) = firstValue
let (temp2, _) = secondValue
if temp1 == temp2 {
0.
} else if temp1 > temp2 {
-1.
} else {
1.
}
}
let constructData = (key, singlestatTimeseriesData: array<authenticationSingleStatSeries>) => {
switch key {
| AuthenticationCount =>
singlestatTimeseriesData->Array.map(ob => {
(ob.time_series->DateTimeUtils.parseAsFloat, ob.authentication_count->Int.toFloat)
})
| AuthenticationSuccessRate =>
singlestatTimeseriesData->Array.map(ob => {
(
ob.time_series->DateTimeUtils.parseAsFloat,
ob.authentication_success_count->Int.toFloat *.
100. /.
ob.authentication_attempt_count->Int.toFloat,
)
})
| ChallengeFlowRate =>
singlestatTimeseriesData->Array.map(ob => {
(
ob.time_series->DateTimeUtils.parseAsFloat,
ob.challenge_flow_count->Int.toFloat *. 100. /. ob.authentication_count->Int.toFloat,
)
})
| FrictionlessFlowRate =>
singlestatTimeseriesData->Array.map(ob => {
(
ob.time_series->DateTimeUtils.parseAsFloat,
ob.frictionless_flow_count->Int.toFloat *. 100. /. ob.authentication_count->Int.toFloat,
)
})
| ChallengeAttemptRate =>
singlestatTimeseriesData->Array.map(ob => {
(
ob.time_series->DateTimeUtils.parseAsFloat,
ob.challenge_attempt_count->Int.toFloat *. 100. /. ob.challenge_flow_count->Int.toFloat,
)
})
| ChallengeSuccessRate =>
singlestatTimeseriesData->Array.map(ob => {
(
ob.time_series->DateTimeUtils.parseAsFloat,
ob.challenge_success_count->Int.toFloat *. 100. /. ob.challenge_flow_count->Int.toFloat,
)
})
| FrictionlessSuccessRate =>
singlestatTimeseriesData->Array.map(ob => {
(
ob.time_series->DateTimeUtils.parseAsFloat,
ob.frictionless_success_count->Int.toFloat *.
100. /.
ob.frictionless_flow_count->Int.toFloat,
)
})
}->Array.toSorted(compareLogic)
}
let getStatData = (
singleStatData: authenticationSingleStat,
timeSeriesData: array<authenticationSingleStatSeries>,
_deltaTimestampData: DynamicSingleStat.deltaRange,
colType,
_mode,
) => {
switch colType {
| AuthenticationCount => {
title: "Payments requiring 3DS Authentication",
tooltipText: "Total number of payments which require 3DS 2.0 Authentication.",
deltaTooltipComponent: _ => React.null,
value: singleStatData.authentication_count->Int.toFloat,
delta: 0.0,
data: constructData(AuthenticationCount, timeSeriesData),
statType: "Volume",
showDelta: false,
}
| AuthenticationSuccessRate => {
title: "Authentication Success Rate",
tooltipText: "Successful Authentication Requests over Total Requests.",
deltaTooltipComponent: _ => React.null,
value: singleStatData.authentication_success_count->Int.toFloat *.
100.0 /.
singleStatData.authentication_count->Int.toFloat,
delta: 0.0,
data: constructData(AuthenticationSuccessRate, timeSeriesData),
statType: "Rate",
showDelta: false,
}
| ChallengeFlowRate => {
title: "Challenge Flow Rate",
tooltipText: "Payments requiring a challenge to be passed over total number of payments which require 3DS 2.0 Authentication.",
deltaTooltipComponent: _ => React.null,
value: singleStatData.challenge_flow_count->Int.toFloat *.
100.0 /.
singleStatData.authentication_count->Int.toFloat,
delta: 0.0,
data: constructData(ChallengeFlowRate, timeSeriesData),
statType: "Rate",
showDelta: false,
}
| FrictionlessFlowRate => {
title: "Frictionless Flow Rate",
tooltipText: "Payments going through a frictionless flow over total number of payments which require 3DS 2.0 Authentication.",
deltaTooltipComponent: _ => React.null,
value: singleStatData.frictionless_flow_count->Int.toFloat *.
100.0 /.
singleStatData.authentication_count->Int.toFloat,
delta: 0.0,
data: constructData(FrictionlessFlowRate, timeSeriesData),
statType: "Rate",
showDelta: false,
}
| ChallengeAttemptRate => {
title: "Challenge Attempt Rate",
tooltipText: "Percentage of payments where user attempted the challenge.",
deltaTooltipComponent: _ => React.null,
value: singleStatData.challenge_attempt_count->Int.toFloat *.
100. /.
singleStatData.challenge_flow_count->Int.toFloat,
delta: 0.0,
data: constructData(ChallengeAttemptRate, timeSeriesData),
statType: "Rate",
showDelta: false,
}
| ChallengeSuccessRate => {
title: "Challenge Success Rate",
tooltipText: "Total number of payments authenticated where user successfully attempted the challenge over the total number of payments requiring a challenge to be passed.",
deltaTooltipComponent: _ => React.null,
value: singleStatData.challenge_success_count->Int.toFloat *.
100. /.
singleStatData.challenge_flow_count->Int.toFloat,
delta: 0.0,
data: constructData(ChallengeSuccessRate, timeSeriesData),
statType: "Rate",
showDelta: false,
}
| FrictionlessSuccessRate => {
title: "Frictionless Success Rate",
tooltipText: "Total number of payments authenticated over a frictionless flow successfully over the total number of payments going through a frictionless flow.",
deltaTooltipComponent: _ => React.null,
value: singleStatData.frictionless_success_count->Int.toFloat *.
100. /.
singleStatData.frictionless_flow_count->Int.toFloat,
delta: 0.0,
data: constructData(FrictionlessSuccessRate, timeSeriesData),
statType: "Rate",
showDelta: false,
}
}
}
let getSingleStatEntity: 'a => DynamicSingleStat.entityType<'colType, 't, 't2> = metrics => {
urlConfig: [
{
uri: `${Window.env.apiBaseUrl}/analytics/v1/metrics/auth_events`,
metrics: metrics->getStringListFromArrayDict,
},
],
getObjects: itemToObjMapper,
getTimeSeriesObject: timeSeriesObjMapper,
defaultColumns,
getData: getStatData,
totalVolumeCol: None,
matrixUriMapper: _ => `${Window.env.apiBaseUrl}/analytics/v1/metrics/auth_events`,
statSentiment: Dict.make(),
statThreshold: Dict.make(),
}
let paymentMetricsConfig: array<LineChartUtils.metricsConfig> = [
{
metric_name_db: "authentication_count",
metric_label: "Volume",
metric_type: Volume,
thresholdVal: None,
step_up_threshold: None,
legendOption: (Average, Overall),
},
]
let authenticationMetricsConfig: array<LineChartUtils.metricsConfig> = [
{
metric_name_db: "authentication_count",
metric_label: "Volume",
metric_type: Volume,
thresholdVal: None,
step_up_threshold: None,
legendOption: (Average, Overall),
},
]
let authenticationFunnelMetricsConfig: array<LineChartUtils.metricsConfig> = [
{
metric_name_db: "authentication_count",
metric_label: "Payments requiring 3DS 2.0 Authentication",
metric_type: Volume,
thresholdVal: None,
step_up_threshold: None,
legendOption: (Average, Overall),
},
{
metric_name_db: "authentication_attempt_count",
metric_label: "Authentication Request Attempt",
metric_type: Volume,
thresholdVal: None,
step_up_threshold: None,
legendOption: (Average, Overall),
},
{
metric_name_db: "authentication_success_count",
metric_label: "Authentication Request Successful",
metric_type: Volume,
thresholdVal: None,
step_up_threshold: None,
legendOption: (Average, Overall),
},
{
metric_name_db: "frictionless_flow_count",
metric_label: "Frictionless Attempted",
disabled: true,
metric_type: Volume,
thresholdVal: None,
step_up_threshold: None,
legendOption: (Average, Overall),
},
{
metric_name_db: "challenge_attempt_count",
metric_label: "Authentication Attempted",
metric_type: Volume,
thresholdVal: None,
step_up_threshold: None,
legendOption: (Average, Overall),
data_transformation_func: dict => {
let total_auth_attempts =
dict->getFloat("challenge_attempt_count", 0.0) +.
dict->getFloat("frictionless_flow_count", 0.0)
dict->Dict.set("challenge_attempt_count", total_auth_attempts->JSON.Encode.float)
dict
},
},
{
metric_name_db: "frictionless_success_count",
metric_label: "Frictionless Successful",
disabled: true,
metric_type: Volume,
thresholdVal: None,
step_up_threshold: None,
legendOption: (Average, Overall),
},
{
metric_name_db: "challenge_success_count",
metric_label: "Authentication Successful",
metric_type: Volume,
thresholdVal: None,
step_up_threshold: None,
legendOption: (Average, Overall),
data_transformation_func: dict => {
let total_auth_attempts =
dict->getFloat("challenge_success_count", 0.0) +.
dict->getFloat("frictionless_success_count", 0.0)
dict->Dict.set("challenge_success_count", total_auth_attempts->JSON.Encode.float)
dict
},
},
]
let commonAuthenticationChartEntity = tabKeys =>
DynamicChart.makeEntity(
~uri=String(`${Window.env.apiBaseUrl}/analytics/v1/metrics/auth_events`),
~filterKeys=tabKeys,
~dateFilterKeys=(startTimeFilterKey, endTimeFilterKey),
~currentMetrics=("Success Rate", "Volume"), // 2nd metric will be static and we won't show the 2nd metric option to the first metric
~cardinality=[],
~granularity=[],
~chartTypes=[SemiDonut],
~uriConfig=[
{
uri: `${Window.env.apiBaseUrl}/analytics/v1/metrics/auth_events`,
timeSeriesBody: DynamicChart.getTimeSeriesChart,
legendBody: DynamicChart.getLegendBody,
metrics: paymentMetricsConfig,
timeCol: "time_bucket",
filterKeys: tabKeys,
},
],
~moduleName="User Journey Analytics",
~getGranularity={
(~startTime as _, ~endTime as _) => {
[""]
}
},
)
let authenticationFunnelChartEntity = tabKeys => {
...commonAuthenticationChartEntity(tabKeys),
chartTypes: [Funnel],
uriConfig: [
{
uri: `${Window.env.apiBaseUrl}/analytics/v1/metrics/auth_events`,
timeSeriesBody: DynamicChart.getTimeSeriesChart,
legendBody: DynamicChart.getLegendBody,
metrics: authenticationFunnelMetricsConfig,
timeCol: "time_bucket",
filterKeys: tabKeys,
},
],
chartDescription: "Breakdown of ThreeDS 2.0 Journey",
}
| 3,261 | 9,794 |
hyperswitch-control-center | src/screens/Analytics/AuthenticationAnalytics/AuthenticationAnalytics.res | .res | open AuthenticationAnalyticsEntity
open APIUtils
open HSAnalyticsUtils
@react.component
let make = () => {
let getURL = useGetURL()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (metrics, setMetrics) = React.useState(_ => [])
let (dimensions, setDimensions) = React.useState(_ => [])
let fetchDetails = useGetMethod()
let loadInfo = async () => {
open LogicUtils
try {
let infoUrl = getURL(
~entityName=V1(ANALYTICS_AUTHENTICATION),
~methodType=Get,
~id=Some("auth_events"),
)
let infoDetails = await fetchDetails(infoUrl)
setMetrics(_ => infoDetails->getDictFromJsonObject->getArrayFromDict("metrics", []))
setDimensions(_ => infoDetails->getDictFromJsonObject->getArrayFromDict("dimensions", []))
setScreenState(_ => PageLoaderWrapper.Success)
} catch {
| Exn.Error(e) =>
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
let getAuthenticationsData = async () => {
try {
setScreenState(_ => PageLoaderWrapper.Loading)
await loadInfo()
} catch {
| Exn.Error(e) =>
let err = Exn.message(e)->Option.getOr("Failed to Fetch!")
setScreenState(_ => PageLoaderWrapper.Error(err))
}
}
React.useEffect(() => {
getAuthenticationsData()->ignore
None
}, [])
let tabKeys = getStringListFromArrayDict(dimensions)
let tabValues = tabKeys->Array.mapWithIndex((key, index) => {
let a: DynamicTabs.tab = {
title: key->LogicUtils.snakeToTitle,
value: key,
isRemovable: index > 2,
}
a
})
let title = "Authentication Analytics"
<div>
<PageLoaderWrapper screenState customUI={<NoData title />}>
<Analytics
pageTitle=title
filterUri=None
key="AuthenticationAnalytics"
moduleName="Authentication"
deltaMetrics={getStringListFromArrayDict(metrics)}
chartEntity={
default: commonAuthenticationChartEntity(tabKeys),
userFunnelChart: authenticationFunnelChartEntity(tabKeys),
}
tabKeys
tabValues
options
singleStatEntity={getSingleStatEntity(metrics)}
getTable={_ => []}
colMapper={_ => ""}
defaultSort="total_volume"
deltaArray=[]
tableGlobalFilter=filterByData
startTimeFilterKey
endTimeFilterKey
initialFilters=initialFilterFields
initialFixedFilters=initialFixedFilterFields
/>
</PageLoaderWrapper>
</div>
}
| 616 | 9,795 |
hyperswitch-control-center | src/screens/Analytics/HomePageOverview/HomePageOverviewComponent.res | .res | open HomeUtils
module ConnectorOverview = {
@react.component
let make = () => {
open ConnectorUtils
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
let {globalUIConfig: {primaryColor}} = React.useContext(ThemeProvider.themeContext)
let connectorsList = ConnectorInterface.useConnectorArrayMapper(
~interface=ConnectorInterface.connectorInterfaceV1,
~retainInList=ConnectorTypes.PaymentProcessor,
)
let configuredConnectors =
connectorsList->Array.map(paymentMethod =>
paymentMethod.connector_name->getConnectorNameTypeFromString
)
let getConnectorIconsList = () => {
let icons =
configuredConnectors
->Array.filterWithIndex((_, i) => i <= 2)
->Array.mapWithIndex((connector, index) => {
let iconStyle = `${index === 0 ? "" : "-ml-4"} z-${(30 - index * 10)->Int.toString}`
<GatewayIcon
key={index->Int.toString}
gateway={connector->getConnectorNameString->String.toUpperCase}
className={`w-12 h-12 rounded-full border-3 border-white ${iconStyle} bg-white`}
/>
})
let icons =
configuredConnectors->Array.length > 3
? icons->Array.concat([
<div
key="concat-number"
className={`w-12 h-12 flex items-center justify-center text-white font-medium rounded-full border-3 border-white -ml-3 z-0 ${primaryColor}`}>
{`+${(configuredConnectors->Array.length - 3)->Int.toString}`->React.string}
</div>,
])
: icons
<div className="flex"> {icons->React.array} </div>
}
<RenderIf condition={configuredConnectors->Array.length > 0}>
<div className=boxCss>
{getConnectorIconsList()}
<div className="flex items-center gap-2">
<p className=cardHeaderTextStyle>
{`${configuredConnectors->Array.length->Int.toString} Active Processors`->React.string}
</p>
</div>
<ACLButton
text="+ Add More"
authorization={userHasAccess(~groupAccess=ConnectorsView)}
buttonType={PrimaryOutline}
customButtonStyle="w-10 !px-3"
buttonSize={Small}
onClick={_ => {
GlobalVars.appendDashboardPath(~url="/connectors")->RescriptReactRouter.push
}}
/>
</div>
</RenderIf>
}
}
module OverviewInfo = {
open APIUtils
@react.component
let make = () => {
let getURL = useGetURL()
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let {sampleData} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let updateDetails = useUpdateMethod()
let showToast = ToastState.useShowToast()
let generateSampleData = async () => {
try {
let generateSampleDataUrl = getURL(~entityName=V1(GENERATE_SAMPLE_DATA), ~methodType=Post)
let _ = await updateDetails(
generateSampleDataUrl,
[("record", 50.0->JSON.Encode.float)]->Dict.fromArray->JSON.Encode.object,
Post,
)
showToast(~message="Sample data generated successfully.", ~toastType=ToastSuccess)
Window.Location.reload()
} catch {
| _ => ()
}
}
<RenderIf condition={sampleData}>
<div className="flex bg-white border rounded-md gap-2 px-9 py-3">
<Icon name="info-vacent" className={`${textColor.primaryNormal}`} size=20 />
<span>
{"To view more points on the above graph, you need to make payments or"->React.string}
</span>
<span
className="underline cursor-pointer -mx-1 font-medium underline-offset-2"
onClick={_ => generateSampleData()->ignore}>
{"generate"->React.string}
</span>
<span> {"sample data"->React.string} </span>
</div>
</RenderIf>
}
}
@react.component
let make = () => {
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
<div className="flex flex-col gap-4">
<p className=headingStyle> {"Overview"->React.string} </p>
<div className="grid grid-cols-1 md:grid-cols-3 w-full gap-4">
<ConnectorOverview />
<RenderIf condition={userHasAccess(~groupAccess=AnalyticsView) === Access}>
<PaymentOverview />
</RenderIf>
</div>
<OverviewInfo />
</div>
}
| 1,053 | 9,796 |
hyperswitch-control-center | src/screens/Analytics/HomePageOverview/PaymentsOverview/PaymentOverview.res | .res | @react.component
let make = () => {
open HSAnalyticsUtils
open APIUtils
let getURL = useGetURL()
let metrics = [
"payment_success_rate",
"payment_count",
"payment_success_count",
]->Array.map(key => {
[("name", key->JSON.Encode.string)]->Dict.fromArray->JSON.Encode.object
})
let analyticsUrl = getURL(
~entityName=V1(ANALYTICS_PAYMENTS),
~methodType=Post,
~id=Some("payments"),
)
let singleStatEntity = PaymentOverviewUtils.getSingleStatEntity(metrics, analyticsUrl)
let dateDict = HSwitchRemoteFilter.getDateFilteredObject()
<DynamicSingleStat
entity={singleStatEntity}
startTimeFilterKey
endTimeFilterKey
filterKeys=[]
moduleName="Payments"
defaultStartDate={dateDict.start_time}
defaultEndDate={dateDict.end_time}
showPercentage=false
statSentiment={singleStatEntity.statSentiment->Option.getOr(Dict.make())}
wrapperClass="w-full h-full -mt-4"
/>
}
| 243 | 9,797 |
hyperswitch-control-center | src/screens/Analytics/HomePageOverview/PaymentsOverview/PaymentOverviewUtils.res | .res | open PaymentAnalyticsEntity
open HSAnalyticsUtils
let defaultColumns: array<DynamicSingleStat.columns<colT>> = [
{
sectionName: "",
columns: [
{
colType: SuccessRate,
},
],
},
]
let getSingleStatEntity: ('a, string) => DynamicSingleStat.entityType<'colType, 't, 't2> = (
metrics,
uri,
) => {
urlConfig: [
{
uri,
metrics: metrics->getStringListFromArrayDict,
},
],
getObjects: itemToObjMapper,
getTimeSeriesObject: timeSeriesObjMapper,
defaultColumns,
getData: getStatData,
totalVolumeCol: None,
matrixUriMapper: _ => uri,
}
| 163 | 9,798 |
hyperswitch-control-center | src/screens/SelfServe/HSwitchProdOnboarding/CheckoutHelper.res | .res | let getOption = %raw(`
function (clientSecret) {
return {
clientSecret,
appearance: {
theme: "charcoal",
variables: {
colorPrimary: "#006DF9",
spacingUnit: "13px",
},
rules: {
".Input": {
borderRadius: "8px",
border: "1px solid #D6D9E0",
},
".Tab": {
borderRadius: "0px",
display: "flex",
gap: "8px",
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
},
".Tab:hover": {
display: "flex",
gap: "8px",
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
padding: "15px 32px",
background: "rgba(0, 109, 249, 0.1)",
border: "1px solid #006DF9",
borderRadius: "112px",
color: "#0c0b0b",
fontWeight: "700",
},
".Tab--selected": {
display: "flex",
gap: "8px",
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
padding: "15px 32px",
background: "rgba(0, 109, 249, 0.1)",
border: "1px solid #006DF9",
borderRadius: "112px",
color: "#0c0b0b",
fontWeight: "700",
},
".Label": {
color: "rgba(45, 50, 65, 0.5)",
marginBottom: "3px",
},
".CheckboxLabel": {
color: "rgba(45, 50, 65, 0.5)",
},
".TabLabel": {
overflowWrap: "break-word",
},
".Tab--selected:hover": {
display: "flex",
gap: "8px",
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
padding: "15px 32px",
background: "rgba(0, 109, 249, 0.1)",
border: "1px solid #006DF9",
borderRadius: "112px",
color: "#0c0b0b",
fontWeight: "700",
},
},
},
fonts: [
{
cssSrc:
"https://fonts.googleapis.com/css2?family=Orbitron:wght@400;500;600;700&display=swap",
},
{
cssSrc:
"https://fonts.googleapis.com/css2?family=Quicksand:wght@400;500;600;700&family=Qwitcher+Grypen:wght@400;700&display=swap",
},
{
cssSrc: "https://fonts.googleapis.com/css2?family=Combo&display=swap",
},
{
family: "something",
src: "https://fonts.gstatic.com/s/combo/v21/BXRlvF3Jh_fIhj0lDO5Q82f1.woff2",
weight: "700",
},
],
locale: "en",
loader: "always",
};}`)
let getOptionReturnUrl = %raw(`
function (returnUrl){
return {
fields: {
billingDetails: {
address: {
country: "auto",
city: "auto",
},
},
},
layout: {
type: "tabs",
defaultCollapsed: false,
radios: true,
spacedAccordionItems: false,
},
showCardFormByDefault: false,
wallets: {
walletReturnUrl: returnUrl,
applePay: "auto",
googlePay: "auto",
style: {
theme: "dark",
type: "default",
height: 48,
},
},
}
}
`)
| 928 | 9,799 |
hyperswitch-control-center | src/screens/SelfServe/HSwitchSandboxOnboarding/UserOnboardingUIUtils.res | .res | open UserOnboardingTypes
open UserOnboardingUtils
open LogicUtils
module ProgressBar = {
@react.component
let make = (~tabs, ~tabIndex) => {
let {globalUIConfig: {primaryColor}} = React.useContext(ThemeProvider.themeContext)
let defaultStyle = currentIndex => {
currentIndex < tabIndex + 1
? `${primaryColor} h-1.5 w-full`
: `${primaryColor} opacity-10 h-1.5 w-full`
}
<div className="flex w-full">
{tabs
->Array.mapWithIndex((_val, i) =>
<div key={Int.toString(i)} className={`${i->defaultStyle}`} />
)
->React.array}
</div>
}
}
module PublishableKeyArea = {
@react.component
let make = () => {
let merchantDetailsValue = HSwitchUtils.useMerchantDetailsValue()
<HelperComponents.KeyAndCopyArea copyValue={merchantDetailsValue.publishable_key} />
}
}
module PaymentResponseHashKeyArea = {
@react.component
let make = () => {
let merchantDetailsValue = HSwitchUtils.useMerchantDetailsValue()
<HelperComponents.KeyAndCopyArea
copyValue={merchantDetailsValue.payment_response_hash_key->Option.getOr("")}
/>
}
}
module DownloadAPIKeyButton = {
@react.component
let make = (
~buttonText,
~currentRoute=OnboardingDefault,
~currentTabName="",
~buttonStyle="",
) => {
let getURL = APIUtils.useGetURL()
let updateDetails = APIUtils.useUpdateMethod(~showErrorToast=false)
let showToast = ToastState.useShowToast()
let (showCopyToClipboard, setShowCopyToClipboard) = React.useState(_ => false)
let apiKeyGeneration = async () => {
try {
let url = getURL(~entityName=V1(API_KEYS), ~methodType=Post)
let body =
[
("name", "DefaultAPIKey"->JSON.Encode.string),
("description", "Default Value of the API key"->JSON.Encode.string),
("expiration", "never"->JSON.Encode.string),
]->Dict.fromArray
let res = await updateDetails(url, body->JSON.Encode.object, Post)
let apiKey = res->getDictFromJsonObject->getString("api_key", "")
DownloadUtils.downloadOld(~fileName=`apiKey.txt`, ~content=apiKey)
Clipboard.writeText(apiKey)
await HyperSwitchUtils.delay(1000)
showToast(
~message="Api Key has been generated & Copied to clipboard",
~toastType=ToastState.ToastSuccess,
)
setShowCopyToClipboard(_ => true)
await HyperSwitchUtils.delay(2000)
setShowCopyToClipboard(_ => false)
} catch {
| _ => showToast(~message="Api Key Generation Failed", ~toastType=ToastState.ToastError)
}
}
let downloadZip = async () => {
await HyperSwitchUtils.delay(1500)
showToast(~message="Plugin file has been downloaded!", ~toastType=ToastState.ToastSuccess)
}
let button =
<div className="flex items-center gap-5">
<Button
text=buttonText
buttonSize={Medium}
buttonType={Primary}
customButtonStyle={`!w-1/3 ${buttonStyle}`}
rightIcon={FontAwesome("download-api-key")}
onClick={_ => {
switch currentTabName {
| "downloadWordpressPlugin" => downloadZip()->ignore
| _ => apiKeyGeneration()->ignore
}
}}
/>
<RenderIf condition=showCopyToClipboard>
<div className="text-green-700 text-lg"> {"Copied to clipboard"->React.string} </div>
</RenderIf>
</div>
switch currentRoute {
| WooCommercePlugin =>
<a href="https://hyperswitch.io/zip/hyperswitch-checkout.zip"> {button} </a>
| _ => button
}
}
}
module DownloadAPIKey = {
@react.component
let make = (~currentRoute, ~currentTabName) => {
<div className="flex flex-col gap-10">
<HSwitchUtils.AlertBanner
bannerText="API key once misplaced cannot be restored. If misplaced, please re-generate a new key from Dashboard > Developers."
bannerType=Warning
/>
<div className="p-10 bg-gray-50 border rounded flex flex-col gap-6">
<div className="flex flex-col gap-2.5">
<div className="text-base text-grey-900 font-medium">
{"Test API Key"->React.string}
</div>
<p className="text-sm text-grey-50">
{"Use this key to authenticate all API requests from your application’s server"->React.string}
</p>
</div>
<DownloadAPIKeyButton buttonText="Download API key" currentRoute currentTabName />
</div>
</div>
}
}
module DownloadWordPressPlugin = {
@react.component
let make = (~currentRoute, ~currentTabName) => {
<DownloadAPIKeyButton buttonText="Download Plugin" currentRoute currentTabName />
}
}
module TabsContentWrapper = {
@react.component
let make = (~children, ~tabIndex, ~currentRoute, ~customUi=React.null) => {
let textClass = switch currentRoute {
| WooCommercePlugin => "text-lg"
| _ => "text-base"
}
<div className="!h-full !w-full py-5 flex flex-col gap-4">
<div className="flex justify-between w-full items-center">
<p className={`${textClass} font-medium py-2`}>
{getContentBasedOnIndex(~currentRoute, ~tabIndex)->React.string}
</p>
</div>
{customUi}
<div className="border bg-jp-gray-light_gray_bg h-full rounded-md p-6 overflow-scroll">
{children}
</div>
</div>
}
}
module HeaderComponentView = {
@react.component
let make = (~value, ~headerText, ~langauge: languages) => {
let showToast = ToastState.useShowToast()
<div
className="flex flex-row justify-between items-center flex-wrap border-b px-4 py-6 text-gray-900">
<p className="font-medium text-base"> {headerText->React.string} </p>
<div className="flex gap-2">
<div className="py-1 px-4 border rounded-md flex gap-2 items-center">
<Icon name={`${(langauge :> string)->String.toLowerCase}`} size=16 />
<p> {(langauge :> string)->React.string} </p>
</div>
<div
className="py-1 px-4 border rounded-md flex gap-2 items-center cursor-pointer"
onClick={_ => {
Clipboard.writeText(value)
showToast(~message="Copied to Clipboard!", ~toastType=ToastSuccess)
}}>
<Icon name="nd-copy" className="cursor-pointer" />
<p> {"Copy"->React.string} </p>
</div>
</div>
</div>
}
}
module ShowCodeEditor = {
@react.component
let make = (~value, ~theme, ~headerText, ~customHeight="8vh", ~langauge: languages) => {
<ReactSuspenseWrapper>
<MonacoEditorLazy
defaultLanguage="javascript"
height=customHeight
width="w-[90vh]"
theme
value
readOnly=true
minimap=false
showCopy=false
headerComponent={<HeaderComponentView value headerText langauge />}
/>
</ReactSuspenseWrapper>
}
}
module DiffCodeEditor = {
@react.component
let make = (~valueToShow: migratestripecode, ~langauge: languages) => {
let _oldValue = valueToShow.from
let newValue = valueToShow.to
<div
className="flex flex-col gap-6 border bg-white overflow-x-scroll w-full !shadow-hyperswitch_box_shadow rounded-md">
<HeaderComponentView value=newValue headerText="Replace" langauge />
// Add Diff Editior
<div className="p-4" />
</div>
}
}
module BackendFrontendPlatformLangDropDown = {
@react.component
let make = (
~frontEndLang: languages,
~setFrontEndLang,
~backEndLang: languages,
~setBackEndLang,
~isFromLanding=false,
~currentRoute,
~platform: platforms,
~setPlatform,
) => {
let platfromInput: ReactFinalForm.fieldRenderPropsInput = {
name: "Platform Selecr",
onBlur: _ => (),
onChange: ev => {
let val = ev->Identity.formReactEventToString->getPlatform
setPlatform(_ => val)
},
onFocus: _ => (),
value: (platform :> string)->JSON.Encode.string,
checked: true,
}
let options = platforms->Array.map((op): SelectBox.dropdownOption => {
{value: (op :> string), label: (op :> string)}
})
let backendLangInput: ReactFinalForm.fieldRenderPropsInput = {
name: "BackEnd",
onBlur: _ => (),
onChange: ev => {
let val = ev->Identity.formReactEventToString->getLangauge
setBackEndLang(_ => val)
},
onFocus: _ => (),
value: (backEndLang :> string)->JSON.Encode.string,
checked: true,
}
let frontendLangInput: ReactFinalForm.fieldRenderPropsInput = {
name: "FrontEnd",
onBlur: _ => (),
onChange: ev => {
let val = ev->Identity.formReactEventToString->getLangauge
setFrontEndLang(_ => val)
},
onFocus: _ => (),
value: (frontEndLang :> string)->JSON.Encode.string,
checked: true,
}
let (frontendLangauge, backendLangauge) = currentRoute->getLanguages
let frontendDropdownText = {
frontEndLang === #ChooseLanguage ? "Choose Frontend" : (frontEndLang :> string)
}
let backendDropdownText = {
backEndLang === #ChooseLanguage ? "Choose Backend" : (backEndLang :> string)
}
<Form initialValues={Dict.make()->JSON.Encode.object}>
<div className="flex flex-row gap-4 flex-wrap">
<RenderIf condition={!isFromLanding && currentRoute !== SampleProjects}>
<SelectBox.BaseDropdown
allowMultiSelect=false
buttonText="Select Platform"
input={platfromInput}
options
hideMultiSelectButtons=true
deselectDisable=true
defaultLeftIcon=CustomIcon(<Icon name="show-filters" size=14 />)
baseComponent={<Button
text={(platform :> string)}
buttonSize=Button.Small
leftIcon=Button.CustomIcon(
<Icon size=20 name={`${(platform :> string)->String.toLowerCase}`} />,
)
rightIcon=Button.CustomIcon(<Icon className="pl-2 " size=20 name="chevron-down" />)
ellipsisOnly=true
customButtonStyle="!bg-white !border"
/>}
/>
</RenderIf>
<RenderIf condition={!(requestOnlyPlatforms->Array.includes(platform))}>
<SelectBox.BaseDropdown
allowMultiSelect=false
buttonText="Select Frontend"
deselectDisable=true
input={frontendLangInput}
options={frontendLangauge->Array.map((lang): SelectBox.dropdownOption => {
{value: (lang :> string), label: (lang :> string)}
})}
hideMultiSelectButtons=true
autoApply=false
customStyle="!rounded-md"
baseComponent={<Button
text=frontendDropdownText
buttonSize=Button.Small
leftIcon=Button.CustomIcon(
<Icon size=20 name={`${(frontEndLang :> string)->String.toLowerCase}`} />,
)
rightIcon=Button.CustomIcon(<Icon className="pl-2 " size=20 name="chevron-down" />)
ellipsisOnly=true
buttonType=Secondary
/>}
/>
<SelectBox.BaseDropdown
allowMultiSelect=false
buttonText="Select Backend"
input={backendLangInput}
deselectDisable=true
options={backendLangauge->Array.map((lang): SelectBox.dropdownOption => {
{value: (lang :> string), label: (lang :> string)}
})}
hideMultiSelectButtons=true
baseComponent={<Button
text=backendDropdownText
buttonSize=Button.Small
leftIcon=Button.CustomIcon(
<Icon size=20 name={`${(backEndLang :> string)->String.toLowerCase}`} />,
)
rightIcon=Button.CustomIcon(<Icon className="pl-2 " size=20 name="chevron-down" />)
ellipsisOnly=true
buttonType=Secondary
/>}
/>
</RenderIf>
</div>
</Form>
}
}
module LanguageTag = {
@react.component
let make = (~frontendLang="", ~backendLang="") => {
<RenderIf condition={frontendLang->isNonEmptyString && backendLang->isNonEmptyString}>
<div className="flex gap-2 items-center">
<Icon name={`${frontendLang}`} size=25 />
<Icon name={`${backendLang}`} size=25 />
</div>
</RenderIf>
}
}
let headerTextCss = "font-semibold text-grey-700 text-xl"
let subTextCss = "font-normal text-grey-700 opacity-50 text-base"
module LandingPageTileForIntegrateDocs = {
@react.component
let make = (
~headerIcon,
~headerText,
~subText,
~buttonText,
~customIconCss,
~url,
~isIconImg,
~imagePath,
~leftSection,
~isFromOnboardingChecklist,
~subTextCustomValues,
~buttonType: Button.buttonType=Secondary,
~isSkipButton=false,
~isTileVisible=true,
~rightIcon,
~customRedirection=?,
) => {
open APIUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod(~showErrorToast=false)
let {
integrationDetails,
setIntegrationDetails,
dashboardPageState,
setDashboardPageState,
} = React.useContext(GlobalProvider.defaultContext)
let redirect = () => {
if customRedirection->Option.isSome {
RescriptReactRouter.replace(
GlobalVars.appendDashboardPath(
~url=`/${customRedirection->Option.getOr("")}?type=${url}`,
),
)
} else {
RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url=`/onboarding?type=${url}`))
}
}
let skipAndContinue = async () => {
try {
let url = getURL(~entityName=V1(INTEGRATION_DETAILS), ~methodType=Post)
let metaDataDict = Dict.fromArray([("is_skip", true->JSON.Encode.bool)])->JSON.Encode.object
let body = HSwitchUtils.constructOnboardingBody(
~dashboardPageState,
~integrationDetails,
~is_done=false,
~metadata=metaDataDict,
)
let _ = await updateDetails(url, body, Post)
setIntegrationDetails(_ => body->ProviderHelper.getIntegrationDetails)
} catch {
| _ => ()
}
setDashboardPageState(_ => #HOME)
}
<RenderIf condition={!isFromOnboardingChecklist || isTileVisible}>
<div
className="p-8 border rounded-md flex flex-col gap-7 justify-between bg-white w-full md:w-1/3">
<div className="flex justify-between flex-wrap">
{if isIconImg {
<div className="w-30 h-8">
<img alt="image" src=imagePath />
</div>
} else {
<Icon size=35 name=headerIcon className=customIconCss />
}}
<RenderIf condition={rightIcon->Option.isSome}>
{rightIcon->Option.getOr(React.null)}
</RenderIf>
{leftSection}
</div>
<div className="flex flex-col gap-2">
<p className=headerTextCss> {headerText->React.string} </p>
<RenderIf condition={subText->Option.isSome}>
<p className=subTextCss> {subText->Option.getOr("")->React.string} </p>
</RenderIf>
<div>
<RenderIf condition={subTextCustomValues->Option.isSome}>
<div className={`flex flex-col gap-3 mt-4`}>
{subTextCustomValues
->Option.getOr([])
->Array.mapWithIndex((val, index) => {
<div key={index->Int.toString} className=subTextCss> {val->React.string} </div>
})
->React.array}
</div>
</RenderIf>
</div>
</div>
<Button
text=buttonText
buttonType
onClick={_ => isSkipButton ? skipAndContinue()->ignore : redirect()}
/>
</div>
</RenderIf>
}
}
module LandingPageTileForGithub = {
@react.component
let make = (~headerIcon, ~customIconCss, ~url, ~displayFrontendLang, ~displayBackendLang) => {
let redirect = () => {
Window._open(url)
}
<div
className={`p-5 border rounded-md flex flex-col gap-4 justify-between bg-white cursor-pointer hover:bg-jp-gray-light_gray_bg`}
onClick={_ => redirect()}>
<div>
<div className="flex items-center justify-between">
<div className="flex items-center">
<p className=headerTextCss> {displayFrontendLang->React.string} </p>
<Icon name="small-dot" />
<p className=headerTextCss> {displayBackendLang->React.string} </p>
</div>
<Icon name="open-new-tab" customIconColor="black" />
</div>
</div>
<div className="flex items-center gap-3">
<Icon size=20 name=headerIcon className=customIconCss />
<div className="text-md text-grey-600"> {"Web"->React.string} </div>
</div>
</div>
}
}
module Section = {
@react.component
let make = (
~sectionHeaderText,
~sectionSubText,
~subSectionArray: array<UserOnboardingTypes.sectionContentType>,
~leftSection=<> </>,
~isFromOnboardingChecklist=false,
~isGithubSection=false,
~customRedirection=?,
) => {
<div className="flex flex-col gap-6">
<div className="flex justify-between items-center flex-wrap">
<div className="flex flex-col gap-1">
<p className=headerTextCss> {sectionHeaderText->React.string} </p>
<p className=subTextCss> {sectionSubText->React.string} </p>
</div>
{leftSection}
</div>
<div
className={` ${isGithubSection
? "grid grid-cols-1 md:grid-cols-3"
: "flex md:flex-row flex-col items-center flex-wrap gap-16"} gap-6`}>
{subSectionArray
->Array.mapWithIndex((subSectionValue, index) => {
isGithubSection
? <LandingPageTileForGithub
key={index->Int.toString}
headerIcon=subSectionValue.headerIcon
customIconCss=subSectionValue.customIconCss
url=subSectionValue.url
displayFrontendLang={subSectionValue.displayFrontendLang->Option.getOr("")}
displayBackendLang={subSectionValue.displayBackendLang->Option.getOr("")}
/>
: <LandingPageTileForIntegrateDocs
key={index->Int.toString}
headerIcon=subSectionValue.headerIcon
headerText={subSectionValue.headerText->Option.getOr("")}
subText=subSectionValue.subText
buttonText=subSectionValue.buttonText
customIconCss=subSectionValue.customIconCss
url=subSectionValue.url
isIconImg={subSectionValue.isIconImg->Option.getOr(false)}
imagePath={subSectionValue.imagePath->Option.getOr("")}
leftSection={<LanguageTag
frontendLang={subSectionValue.frontEndLang->Option.getOr("")}
backendLang={subSectionValue.backEndLang->Option.getOr("")}
/>}
isFromOnboardingChecklist
subTextCustomValues=subSectionValue.subTextCustomValues
buttonType={subSectionValue.buttonType->Option.getOr(Secondary)}
isSkipButton={subSectionValue.isSkipButton->Option.getOr(false)}
isTileVisible={subSectionValue.isTileVisible->Option.getOr(true)}
rightIcon={subSectionValue.rightIcon}
customRedirection={customRedirection->Option.getOr("")}
/>
})
->React.array}
</div>
</div>
}
}
module CreatePayment = {
@react.component
let make = (~currentRoute, ~tabIndex, ~defaultEditorStyle, ~backEndLang, ~theme) => {
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
<TabsContentWrapper
currentRoute
tabIndex
customUi={<p className="text-base font-normal py-2 flex gap-2">
{"For the complete API schema, refer "->React.string}
<p
className={`${textColor.primaryNormal} underline cursor-pointer`}
onClick={_ =>
Window._open(
"https://api-reference.hyperswitch.io/docs/hyperswitch-api-reference/60bae82472db8-payments-create",
)}>
{"API docs"->React.string}
</p>
</p>}>
<div className=defaultEditorStyle>
<RenderIf condition={backEndLang->getInstallDependencies->isNonEmptyString}>
<ShowCodeEditor
value={backEndLang->getInstallDependencies}
theme
headerText="Installation"
langauge=backEndLang
/>
<div className="w-full h-px bg-jp-gray-700" />
</RenderIf>
<ShowCodeEditor
value={backEndLang->getCreateAPayment}
theme
headerText="Request"
customHeight="25vh"
langauge=backEndLang
/>
</div>
</TabsContentWrapper>
}
}
let getTabsForIntegration = (
~currentRoute,
~tabIndex,
~frontEndLang,
~theme,
~backEndLang,
~publishablekeyMerchant,
) => {
open Tabs
let defaultEditorStyle = "flex flex-col gap-8 bg-white flex flex-col px-6 py-4 border !shadow-hyperswitch_box_shadow rounded-md"
// let updateDetails = APIUtils.useUpdateMethod(~showErrorToast=false)
// let {integrationDetails, setIntegrationDetails, dashboardPageState} = React.useContext(
// GlobalProvider.defaultContext,
// )
switch currentRoute {
| MigrateFromStripe => [
{
title: "1. Download API Key",
renderContent: () =>
<TabsContentWrapper currentRoute tabIndex>
<DownloadAPIKey currentRoute currentTabName="downloadApiKey" />
</TabsContentWrapper>,
},
{
title: "2. Install Dependencies",
renderContent: () =>
<TabsContentWrapper currentRoute tabIndex>
<div className=defaultEditorStyle>
<ShowCodeEditor
value={frontEndLang->getMigrateFromStripeDX(backEndLang)}
theme
headerText="Installation"
langauge=backEndLang
/>
</div>
</TabsContentWrapper>,
},
{
title: "3. Replace API Key",
renderContent: () =>
<TabsContentWrapper currentRoute tabIndex>
<DiffCodeEditor valueToShow={backEndLang->getReplaceAPIkeys} langauge=backEndLang />
</TabsContentWrapper>,
},
{
title: "4. Reconfigure Checkout Form",
renderContent: () =>
<TabsContentWrapper currentRoute tabIndex customUi={<PublishableKeyArea />}>
<DiffCodeEditor valueToShow={frontEndLang->getCheckoutForm} langauge=frontEndLang />
</TabsContentWrapper>,
},
{
title: "5. Load HyperSwitch Checkout",
renderContent: () =>
<TabsContentWrapper currentRoute tabIndex customUi={<PublishableKeyArea />}>
<DiffCodeEditor
valueToShow={frontEndLang->getHyperswitchCheckout} langauge=frontEndLang
/>
</TabsContentWrapper>,
},
]
| IntegrateFromScratch => [
{
title: "1. Download API Key",
renderContent: () =>
<TabsContentWrapper currentRoute tabIndex>
<DownloadAPIKey currentRoute currentTabName="downloadApiKey" />
</TabsContentWrapper>,
},
{
title: "2. Create a Payment",
renderContent: () =>
<CreatePayment currentRoute tabIndex defaultEditorStyle backEndLang theme />,
},
{
title: "3. Display Checkout Page",
renderContent: () =>
<TabsContentWrapper currentRoute tabIndex customUi={<PublishableKeyArea />}>
<div className=defaultEditorStyle>
<RenderIf condition={frontEndLang->getInstallDependencies->isNonEmptyString}>
<ShowCodeEditor
value={frontEndLang->getInstallDependencies}
theme
headerText="Installation"
langauge=frontEndLang
/>
<div className="w-full h-px bg-jp-gray-700" />
</RenderIf>
<RenderIf condition={frontEndLang->getInstallDependencies->isNonEmptyString}>
<ShowCodeEditor
value={frontEndLang->getImports} theme headerText="Imports" langauge=frontEndLang
/>
<div className="w-full h-px bg-jp-gray-700" />
</RenderIf>
<RenderIf condition={frontEndLang->getLoad->isNonEmptyString}>
<ShowCodeEditor
value={frontEndLang->getLoad} theme headerText="Load" langauge=frontEndLang
/>
<div className="w-full h-px bg-jp-gray-700" />
</RenderIf>
<RenderIf condition={frontEndLang->getInitialize->isNonEmptyString}>
<ShowCodeEditor
value={frontEndLang->getInitialize}
theme
headerText="Initialize"
langauge=frontEndLang
/>
<div className="w-full h-px bg-jp-gray-700" />
</RenderIf>
<RenderIf
condition={frontEndLang->getCheckoutFormForDisplayCheckoutPage->isNonEmptyString}>
<ShowCodeEditor
value={frontEndLang->getCheckoutFormForDisplayCheckoutPage}
theme
headerText="Checkout Form"
langauge=frontEndLang
/>
</RenderIf>
</div>
</TabsContentWrapper>,
},
{
title: "4. Display Payment Confirmation",
renderContent: () =>
<TabsContentWrapper currentRoute tabIndex customUi={<PublishableKeyArea />}>
<div className=defaultEditorStyle>
<RenderIf condition={frontEndLang->getHandleEvents->isNonEmptyString}>
<ShowCodeEditor
value={frontEndLang->getHandleEvents}
theme
headerText="Handle Events"
customHeight="20vh"
langauge=frontEndLang
/>
<div className="w-full h-px bg-jp-gray-700" />
</RenderIf>
<RenderIf condition={frontEndLang->getDisplayConformation->isNonEmptyString}>
<ShowCodeEditor
value={frontEndLang->getDisplayConformation}
theme
headerText="Display Payment Confirmation"
customHeight="20vh"
langauge=frontEndLang
/>
</RenderIf>
</div>
</TabsContentWrapper>,
},
]
| SampleProjects => [
{
title: "1. Download API Key",
renderContent: () =>
<TabsContentWrapper currentRoute tabIndex>
<DownloadAPIKey currentRoute currentTabName="1.downloadaPIkey" />
</TabsContentWrapper>,
},
{
title: "2. Explore Sample Project",
renderContent: () =>
<TabsContentWrapper
currentRoute
tabIndex
customUi={<p className="text-base font-normal py-2 flex gap-2">
{"Explore Sample Projects, make use of the publishable key wherever needed "->React.string}
</p>}>
<div className="flex flex-col gap-5">
<div className=defaultEditorStyle>
<HelperComponents.KeyAndCopyArea
copyValue=publishablekeyMerchant
shadowClass="shadow shadow-hyperswitch_box_shadow md:!w-max"
/>
</div>
<div className=defaultEditorStyle>
<Section
sectionHeaderText="Clone a sample project"
sectionSubText="Try out your choice of integration by cloning sample project"
subSectionArray={getFilteredList(frontEndLang, backEndLang, githubCodespaces)}
isGithubSection=true
/>
</div>
</div>
</TabsContentWrapper>,
},
]
| WooCommercePlugin => [
{
title: "1. Connect",
renderContent: () =>
<TabsContentWrapper currentRoute tabIndex>
<div
className="bg-white p-7 flex flex-col gap-6 border !shadow-hyperswitch_box_shadow rounded-md">
<DownloadWordPressPlugin currentRoute currentTabName="downloadWordpressPlugin" />
</div>
</TabsContentWrapper>,
},
{
title: "2. Configure",
renderContent: () =>
<div>
<TabsContentWrapper currentRoute tabIndex={1}>
<div
className="bg-white p-7 flex flex-col gap-6 border !shadow-hyperswitch_box_shadow rounded-md">
<img
alt="wordpress"
style={
height: "400px",
width: "100%",
objectFit: "cover",
objectPosition: "0% 12%",
}
src="https://hyperswitch.io/img/site/wordpress_hyperswitch_settings.png"
/>
</div>
</TabsContentWrapper>
<TabsContentWrapper currentRoute tabIndex={2}>
<DownloadAPIKey currentRoute currentTabName="downloadApiKey" />
</TabsContentWrapper>
<TabsContentWrapper currentRoute tabIndex={3}>
<PublishableKeyArea />
</TabsContentWrapper>
<TabsContentWrapper currentRoute tabIndex={4}>
<PaymentResponseHashKeyArea />
</TabsContentWrapper>
<TabsContentWrapper currentRoute tabIndex={5}>
<div
className="bg-white p-7 flex flex-col gap-6 border !shadow-hyperswitch_box_shadow rounded-md">
<img
alt="wordpress-settings"
style={
height: "120px",
width: "100%",
objectFit: "cover",
objectPosition: "0% 52%",
}
src="https://hyperswitch.io/img/site/wordpress_hyperswitch_settings.png"
/>
</div>
<PaymentSettings webhookOnly=true />
</TabsContentWrapper>
<TabsContentWrapper currentRoute tabIndex={6}>
<div
className="bg-white p-7 flex flex-col gap-6 border !shadow-hyperswitch_box_shadow rounded-md">
<img
alt="wordpress-settings"
style={
height: "120px",
width: "100%",
objectFit: "cover",
objectPosition: "0% 100%",
}
src="https://hyperswitch.io/img/site/wordpress_hyperswitch_settings.png"
/>
</div>
</TabsContentWrapper>
<div className="mt-4">
{React.string(
"Additionally, you can configure the other settings such as appearance, layout, etc as per your requirements.",
)}
</div>
</div>,
},
]
| _ => []
}
}
| 7,121 | 9,800 |
hyperswitch-control-center | src/screens/SelfServe/HSwitchSandboxOnboarding/UserOnboardingTypes.res | .res | type onboardingSteps =
ChoosePlan | Connectors | SDKIntegration | IntegrationCheckList | AccountActivation
type languages = [
| #Node
| #Ruby
| #Java
| #Python
| #Net
| #Rust
| #Shell
| #HTML
| #ReactJs
| #Next
| #Php
| #Kotlin
| #Go
| #ChooseLanguage
]
type platforms = [#Web | #IOS | #Android | #Woocommerce | #BigCommerce | #ReactNative]
type buildHyperswitchTypes =
MigrateFromStripe | IntegrateFromScratch | OnboardingDefault | WooCommercePlugin | SampleProjects
type stepperValueType = {
collapsedText: string,
renderComponent: React.element,
}
type sectionContentType = {
headerIcon: string,
headerText?: string,
subText?: string,
buttonText: string,
customIconCss: string,
openToNewWindow?: bool,
url: string,
isIconImg?: bool,
imagePath?: string,
frontEndLang?: string,
backEndLang?: string,
subTextCustomValues?: array<string>,
buttonType?: Button.buttonType,
displayFrontendLang?: string,
displayBackendLang?: string,
isSkipButton?: bool,
isTileVisible?: bool,
rightIcon?: React.element,
}
type migratestripecode = {
from: string,
to: string,
}
| 321 | 9,801 |
hyperswitch-control-center | src/screens/SelfServe/HSwitchSandboxOnboarding/IntegrationDocs.res | .res | module RequestPage = {
@react.component
let make = (~requestedPlatform, ~currentRoute) => {
open UserOnboardingTypes
open UserOnboardingUtils
open APIUtils
open CommonAuthHooks
let {email} = useCommonAuthInfo()->Option.getOr(defaultAuthInfo)
let getURL = useGetURL()
let requestedValue = requestedPlatform->Option.getOr("")->LogicUtils.capitalizeString
let (isSubmitButtonEnabled, setIsSubmitButtonEnabled) = React.useState(_ => true)
let showToast = ToastState.useShowToast()
let updateDetails = useUpdateMethod()
let handleSubmitRequest = async () => {
try {
let url = getURL(~entityName=V1(USERS), ~userType=#USER_DATA, ~methodType=Post)
let values =
[
("rating", 5.0->JSON.Encode.float),
("category", "Platform Request"->JSON.Encode.string),
("feedbacks", `Request for ${requestedValue}`->JSON.Encode.string),
]->LogicUtils.getJsonFromArrayOfJson
let requestedBody = HSwitchUtils.getBodyForFeedBack(~email, ~values)->JSON.Encode.object
let body = [("Feedback", requestedBody)]->LogicUtils.getJsonFromArrayOfJson
let _ = await updateDetails(url, body, Post)
showToast(
~toastType=ToastSuccess,
~message="Request submitted successfully!",
~autoClose=false,
)
setIsSubmitButtonEnabled(_ => false)
} catch {
| _ => ()
}
}
React.useEffect(() => {
setIsSubmitButtonEnabled(_ => true)
None
}, [requestedValue])
let handleButtonClick = () => {
switch currentRoute {
| MigrateFromStripe =>
switch requestedValue->getPlatform {
| #IOS => Window._open("https://hyperswitch.io/docs/migrateFromStripe/migrateFromStripeIos")
| #Android =>
Window._open("https://hyperswitch.io/docs/migrateFromStripe/migrateFromStripeAndroid")
| #ReactNative =>
Window._open("https://hyperswitch.io/docs/migrateFromStripe/migrateFromStripeRN")
| _ => handleSubmitRequest()->ignore
}
| _ => handleSubmitRequest()->ignore
}
}
let buttonText = () => {
switch currentRoute {
| MigrateFromStripe =>
switch requestedValue->getPlatform {
| #IOS | #Android | #ReactNative => "Go to Developers Docs"
| _ => "I'm Interested"
}
| _ => "I'm Interested"
}
}
let subText = () => {
switch currentRoute {
| MigrateFromStripe =>
switch requestedValue->getPlatform {
| #IOS | #Android | #ReactNative =>
`You can access the Integration docs for ${requestedValue} plugin on our Developer docs, we will be updating it here shortly.`
| _ => "Our team is currently working to make this available for you soon.Please reach out to us on our Slack for any queries."
}
| _ => "Our team is currently working to make this available for you soon.Please reach out to us on our Slack for any queries."
}
}
<div
className="border bg-jp-gray-light_gray_bg h-full rounded-md p-6 overflow-scroll flex flex-col justify-center items-center gap-6">
<Icon name={requestedValue->String.toLowerCase} size=180 className="!scale-200" />
<div className="flex flex-col gap-2 items-center justify-center">
<p className="text-2xl font-semibold text-grey-700">
{`${requestedValue} (Coming Soon)`->React.string}
</p>
<p className="text-base font-semibold text-grey-700 opacity-50 w-1/2 text-center">
{subText()->React.string}
</p>
</div>
<Button
text={buttonText()}
buttonType={Primary}
onClick={_ => handleButtonClick()}
buttonState={isSubmitButtonEnabled ? Normal : Disabled}
/>
</div>
}
}
@react.component
let make = (
~currentRoute,
~isFromOnboardingChecklist=false,
~markAsDone=?,
~languageSelection=true,
) => {
open UserOnboardingUtils
open UserOnboardingTypes
let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext)
let (tabIndex, setTabIndex) = React.useState(_ => 0)
let (frontEndLang, setFrontEndLang) = React.useState(_ =>
currentRoute === SampleProjects ? #ChooseLanguage : #ReactJs
)
let (backEndLang, setBackEndLang) = React.useState(_ =>
currentRoute === SampleProjects ? #ChooseLanguage : #Node
)
let (platform, setPlatform) = React.useState(_ => #Web)
let merchantDetails = Recoil.useRecoilValueFromAtom(HyperswitchAtom.merchantDetailsValueAtom)
let publishablekeyMerchant = merchantDetails.publishable_key
let theme = switch ThemeProvider.useTheme() {
| Dark => "vs-dark"
| Light => "light"
}
open Tabs
let tabs = UserOnboardingUIUtils.getTabsForIntegration(
~currentRoute,
~tabIndex,
~frontEndLang,
~theme,
~backEndLang,
~publishablekeyMerchant,
)
let handleMarkAsDone = () => {
switch markAsDone {
| Some(fun) => fun()->ignore
| _ => ()->ignore
}
}
let handleDeveloperDocs = () => {
switch currentRoute {
| MigrateFromStripe => Window._open("https://hyperswitch.io/docs/migrateFromStripe")
| IntegrateFromScratch => Window._open("https://hyperswitch.io/docs/quickstart")
| WooCommercePlugin =>
Window._open(
"https://hyperswitch.io/docs/sdkIntegrations/wooCommercePlugin/wooCommercePluginSetup",
)
| _ => Window._open("https://hyperswitch.io/docs/")
}
}
let getRequestedPlatforms = () => {
if requestOnlyPlatforms->Array.includes(platform) {
Some((platform :> string))
} else if !([#Node]->Array.includes(backEndLang)) && currentRoute === MigrateFromStripe {
Some((backEndLang :> string))
} else {
None
}
}
let buttonStyle =
tabIndex === tabs->Array.length - 1
? `!border !rounded-md bg-white !${textColor.primaryNormal}`
: "!rounded-md"
let requestedPlatform = getRequestedPlatforms()
<div className="w-full h-full flex flex-col bg-white">
<UserOnboardingUIUtils.ProgressBar tabs tabIndex />
<div className="flex flex-col w-full h-full p-6 gap-4 ">
<div
className={`flex ${languageSelection ? "justify-between" : "justify-end"} flex-wrap gap-2`}>
<RenderIf condition=languageSelection>
<UserOnboardingUIUtils.BackendFrontendPlatformLangDropDown
frontEndLang
setFrontEndLang
backEndLang
setBackEndLang
currentRoute
platform
setPlatform
/>
</RenderIf>
<RenderIf condition={!isFromOnboardingChecklist}>
<Button
text={"Mark as done"}
customButtonStyle=buttonStyle
buttonType={Secondary}
buttonSize={Small}
buttonState={tabIndex === tabs->Array.length - 1 ? Normal : Disabled}
onClick={_ => handleMarkAsDone()}
/>
</RenderIf>
</div>
{if requestedPlatform->Option.isSome {
<RequestPage requestedPlatform currentRoute />
} else {
<div className="flex flex-col my-4">
<Tabs
initialIndex={tabIndex}
tabs
showBorder=false
includeMargin=false
lightThemeColor="black"
renderedTabClassName="!h-full"
gapBetweenTabs="gap-0"
borderSelectionStyle="border-l-1 border-r-1 border-t-1 !p-4 !border-grey-600 !w-full"
borderDefaultStyle="border-b-1 !p-4 !border-grey-600 "
showBottomBorder=false
defaultClasses="w-max flex flex-auto flex-row items-center justify-center px-6 font-semibold text-body"
onTitleClick={indx => {
setTabIndex(_ => indx)
}}
/>
<RenderIf condition={tabIndex !== tabs->Array.length - 1}>
<div className="flex my-4 w-full justify-end">
<Button
text={"Next Step"}
customButtonStyle=buttonStyle
rightIcon={CustomIcon(
<Icon
name="arrow-right"
size=15
className="mr-1 jp-gray-900 fill-opacity-50 dark:jp-gray-text_darktheme"
/>,
)}
buttonType={Secondary}
buttonSize={Small}
onClick={_ => {
setTabIndex(indx => indx + 1)
}}
/>
</div>
</RenderIf>
<div className="flex gap-1 flex-wrap pb-5 justify-between ">
<div className="flex gap-2">
<p className="text-base font-normal text-grey-700">
{"Explore our detailed developer documentation on our"->React.string}
</p>
<p
className={`text-base font-semibold ${textColor.primaryNormal} cursor-pointer underline`}
onClick={_ => handleDeveloperDocs()}>
{"Developer Docs"->React.string}
</p>
</div>
</div>
</div>
}}
</div>
</div>
}
| 2,143 | 9,802 |
hyperswitch-control-center | src/screens/SelfServe/HSwitchSandboxOnboarding/CodeSnippets.res | .res | let reactImports = `import React, { useState, useEffect } from "react";
import { loadHyper } from "@juspay-tech/hyper-js";
import { HyperElements } from "@juspay-tech/react-hyper-js";`
let htmlHandleEvents = `async function handleSubmit(e) {
e.preventDefault();
setLoading(true);
const { error } = await hyper.confirmPayment({
widgets,
confirmParams: {
// Make sure to change this to your payment completion page
return_url: "https://example.com/complete",
},
});
// This point will only be reached if there is an immediate error occurring while confirming the payment. Otherwise, your customer will be redirected to your "return_url".
// For some payment flows such as Sofort, iDEAL, your customer will be redirected to an intermediate page to complete authorization of the payment, and then redirected to the "return_url".
if (error.type === "validation_error") {
showMessage(error.message);
} else {
showMessage("An unexpected error occurred.");
}
setLoading(false);
}`
let reactHandleEvent = "const handleSubmit = async (e) => {
e.preventDefault();
if (!hyper || !widgets) {
// hyper-js has not yet loaded.
// Make sure to disable form submission until hyper-js has loaded.
return;
}
setIsLoading(true);
const { error, status } = await hyper.confirmPayment({
widgets,
confirmParams: {
// Make sure to change this to your payment completion page
return_url: `https://example.com/complete`,
},
});
// This point will only be reached if there is an immediate error occurring while confirming the payment. Otherwise, your customer will be redirected to your `return_url`
// For some payment flows such as Sofort, iDEAL, your customer will be redirected to an intermediate page to complete authorization of the payment, and then redirected to the `return_url`.
if (error) {
if (error.type === `validation_error`) {
setMessage(error.message);
} else {
setMessage(`An unexpected error occurred.`);
}
} else {
setMessage(`Your payment is ${status}`)
}
setIsLoading(false);
};"
let htmlDisplayConfirmation = `// Fetches the payment status after payment submission
async function checkStatus() {
const clientSecret = new URLSearchParams(window.location.search).get(
"payment_intent_client_secret"
);
if (!clientSecret) {
return;
}
const { payment } = await hyper.retrievePayment(clientSecret);
switch (payment.status) {
case "succeeded":
showMessage("Payment succeeded!");
break;
case "processing":
showMessage("Your payment is processing.");
break;
case "requires_payment_method":
showMessage("Your payment was not successful, please try again.");
break;
default:
showMessage("Something went wrong.");
break;
}
}`
let reactDisplayConfirmation = `
//Look for a parameter called "payment_intent_client_secre" in the url which gives a payment ID, which is then used to retrieve the status of the payment
const paymentID = new URLSearchParams(window.location.search).get(
"payment_intent_client_secret"
);
if (!paymentID) {
return;
}
hyper.retrievePaymentIntent(paymentID).then(({ paymentIntent }) => {
switch (paymentIntent.status) {
case "succeeded":
setMessage("Payment succeeded!");
break;
case "processing":
setMessage("Your payment is processing.");
break;
case "requires_payment_method":
setMessage("Your payment was not successful, please try again.");
break;
default:
setMessage("Something went wrong.");
break;
}
});`
let htmlLoad = `<script src="https://beta.hyperswitch.io/v1/HyperLoader.js"></script>
<form id="payment-form">
<div id="unified-checkout">
<!--HyperLoader injects the Unified Checkout-->
</div>
<button id="submit">
<div class="spinner hidden" id="spinner"></div>
<span id="button-text">Pay now</span>
</button>
<div id="payment-message" class="hidden"></div>
</form>`
let reactLoad = `const hyperPromise = loadHyper("YOUR_PUBLISHABLE_KEY");
const [clientSecret, setClientSecret] = useState("");`
let htmlInitialize = `async function initialize() {
const response = await fetch("/create-payment", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ items: [{ id: "xl-tshirt" }], country: "US" }),
});
const { clientSecret } = await response.json();
const appearance = {
theme: "midnight",
};
const hyper = Hyper(YOUR_PUBLISHABLE_KEY);
widgets = hyper.widgets({ appearance, clientSecret });
var unifiedCheckoutOptions = {
wallets: {
walletReturnUrl: 'https://example.com/complete',
//Mandatory parameter for Wallet Flows such as Googlepay, Paypal and Applepay
},
};
const unifiedCheckout = widgets.create("payment", unifiedCheckoutOptions);
unifiedCheckout.mount("#unified-checkout");
}`
let reactInitialize = "
useEffect(() => {
fetch(`/create-payment-intent`, {
method: `POST`,
body: JSON.stringify({ items: [{ id: `xl-tshirt` }], country: `US` }),
}).then(async (result) => {
var { clientSecret } = await result.json();
setClientSecret(clientSecret);
});
}, []);
<>
{clientSecret && (
<HyperElements options={{ clientSecret }} hyper={hyperPromise}>
<CheckoutForm return_url={`${window.location.origin}/completion}` />
</HyperElements>
)}
</> "
let reactCheckoutFormDisplayCheckoutPage = "import { UnifiedCheckout, useHyper, useWidgets } from '@juspay-tech/react-hyper-js';
// store a reference to hyper
const hyper = useHyper();
var unifiedCheckoutOptions = {
wallets: {
walletReturnUrl: 'https://example.com/complete',
//Mandatory parameter for Wallet Flows such as Googlepay, Paypal and Applepay
},
};
<form id='payment-form' onSubmit={handleSubmit}>
<UnifiedCheckout id='unified-checkout' options={unifiedCheckoutOptions} />
<button id='submit'>
<span id='button-text'>
{isLoading ? <div className='spinner' id='spinner'></div> : 'Pay Now'}
</span>
</button>
{/* Show any error or success messages */}
{message && <div id='payment-message'>{message}</div>}
</form>"
let nodeInstallDependencies = `npm install @juspay-tech/hyperswitch-node`
let reactInstallDependencies = `npm install @juspay-tech/hyper-js
npm install @juspay-tech/react-hyper-js`
let rubyRequestPayment = `require 'net/http'
require 'sinatra'
require 'json'
require 'uri'
hyper_switch_api_key = 'HYPERSWITCH_API_KEY'
hyper_switch_api_base_url = 'https://sandbox.hyperswitch.io/payments'
set :static, true
set :port, 4242
# Securely calculate the order amount
def calculate_order_amount(_items)
# Replace this constant with a calculation of the order's amount
# Calculate the order total on the server to prevent
# people from directly manipulating the amount on the client
1400
end
# An endpoint to start the payment process
post '/create-payment' do
data = JSON.parse(request.body.read)
# If you have two or more “business_country” + “business_label” pairs configured in your Hyperswitch dashboard,
# please pass the fields business_country and business_label in this request body.
# For accessing more features, you can check out the request body schema for payments-create API here :
# https://api-reference.hyperswitch.io/docs/hyperswitch-api-reference/60bae82472db8-payments-create
payload = { amount: calculate_order_amount(data['items']), currency: 'USD' }.to_json
uri = URI.parse(hyper_switch_api_base_url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path,
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'api-key' => hyper_switch_api_key)
request.body = payload
response = http.request(request)
response_data = JSON.parse(response.body)
{
clientSecret: response_data['client_secret']
}.to_json
end`
let javaRequestPayment = `package com.hyperswitch.sample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Paths;
import static spark.Spark.post;
import static spark.Spark.staticFiles;
import static spark.Spark.port;
import org.json.JSONObject;
public class server {
public static void main(String[] args) {
port(4242);
staticFiles.externalLocation(Paths.get("public").toAbsolutePath().toString());
post("/create-payment", (request, response) -> {
response.type("application/json");
/*
If you have two or more “business_country” + “business_label” pairs configured in your Hyperswitch dashboard,
please pass the fields business_country and business_label in this request body.
For accessing more features, you can check out the request body schema for payments-create API here :
https://api-reference.hyperswitch.io/docs/hyperswitch-api-reference/60bae82472db8-payments-create
*/
String payload = "{ \"amount\": 100, \"currency\": \"USD\" }";
String response_string = createPayment(payload);
JSONObject response_json = new JSONObject(response_string);
String client_secret = response_json.getString("client_secret");
JSONObject final_response = new JSONObject();
final_response.put("clientSecret", client_secret);
return final_response;
});
}
private static String createPayment(String payload) {
try {
String HYPER_SWITCH_API_KEY = "HYPERSWITCH_API_KEY";
String HYPER_SWITCH_API_BASE_URL = "https://sandbox.hyperswitch.io/payments";
URL url = new URL(HYPER_SWITCH_API_BASE_URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("api-key", HYPER_SWITCH_API_KEY);
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = payload.getBytes("utf-8");
os.write(input, 0, input.length);
}
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
return response.toString();
}
} else {
return "HTTP request failed with response code: " + responseCode;
}
} catch (IOException e) {
return e.getMessage();
}
}
}`
let pythonRequestPayment = `#! /usr/bin/env python3.6
"""
Python 3.6 or newer required.
"""
import http.client
import json
import os
from flask import Flask, render_template, jsonify, request
app = Flask(__name__,
static_folder='public',
static_url_path='',
template_folder='public')
def calculate_order_amount(items):
# Replace this constant with a calculation of the order's amount
# Calculate the order total on the server to prevent
# people from directly manipulating the amount on the client
return 1400
@app.route('/create-payment', methods=['POST'])
def create_payment():
try:
conn = http.client.HTTPSConnection("sandbox.hyperswitch.io")
# If you have two or more “business_country” + “business_label” pairs configured in your Hyperswitch dashboard,
# please pass the fields business_country and business_label in this request body.
# For accessing more features, you can check out the request body schema for payments-create API here :
# https://api-reference.hyperswitch.io/docs/hyperswitch-api-reference/60bae82472db8-payments-create
payload = "{\n \"amount\": 100,\n \"currency\": \"USD\"\n}"
headers = {
'Content-Type': "application/json",
'Accept': "application/json",
'api-key': "HYPERSWITCH_API_KEY",
}
conn.request("POST", "/payments", payload, headers)
res = conn.getresponse()
data = json.loads(res.read())
return jsonify({'clientSecret': data['client_secret']})
except Exception as e:
return jsonify(error=str(e)), 403
if __name__ == '__main__':
app.run(port=4242)`
let netRequestPayment = `using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
namespace HyperswitchExample
{
public class Program
{
public static void Main(string[] args)
{
WebHost.CreateDefaultBuilder(args)
.UseUrls("http://0.0.0.0:4242")
.UseWebRoot("public")
.UseStartup<Startup>()
.Build()
.Run();
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddNewtonsoftJson();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment()) app.UseDeveloperExceptionPage();
app.UseRouting();
app.UseStaticFiles();
app.UseEndpoints(endpoints => endpoints.MapControllers());
}
}
[Route("create-payment")]
[ApiController]
public class PaymentIntentApiController : Controller
{
[HttpPost]
public async Task<ActionResult> CreateAsync(PaymentIntentCreateRequest request)
{
string HYPER_SWITCH_API_KEY = "HYPERSWITCH_API_KEY";
string HYPER_SWITCH_API_BASE_URL = "https://sandbox.hyperswitch.io/payments";
/*
If you have two or more “business_country” + “business_label” pairs configured in your Hyperswitch dashboard,
please pass the fields business_country and business_label in this request body.
For accessing more features, you can check out the request body schema for payments-create API here :
https://api-reference.hyperswitch.io/docs/hyperswitch-api-reference/60bae82472db8-payments-create
*/
var payload = new { amount = CalculateOrderAmount(request.Items), currency = "USD" };
using (var httpClient = new System.Net.Http.HttpClient())
{
httpClient.DefaultRequestHeaders.Add("api-key", HYPER_SWITCH_API_KEY);
var jsonPayload = JsonConvert.SerializeObject(payload);
var content = new System.Net.Http.StringContent(jsonPayload, System.Text.Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(HYPER_SWITCH_API_BASE_URL, content);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
dynamic responseData = JsonConvert.DeserializeObject(responseContent);
return Json(new {clientSecret = responseData.client_secret});
}
else
{
return Json(new {error = "Request failed"});
}
}
}
private int CalculateOrderAmount(Item[] items)
{
return 1400;
}
public class Item
{
[JsonProperty("id")]
public string Id { get; set; }
}
public class PaymentIntentCreateRequest
{
[JsonProperty("items")]
public Item[] Items { get; set; }
}
}
}`
let rustRequestPayment = `extern crate reqwest;
use reqwest::header;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut headers = header::HeaderMap::new();
headers.insert("Content-Type", "application/json".parse().unwrap());
headers.insert("Accept", "application/json".parse().unwrap());
headers.insert("api-key", "YOUR_API_KEY".parse().unwrap());
let client = reqwest::blocking::Client::new();
let res = client.post("https://sandbox.hyperswitch.io/payments")
.headers(headers)
.body(r#"
{
"amount": 100,
"currency": "USD"
}
"#
)
.send()?
.text()?;
println!("{}", res);
Ok(())
}`
let shellRequestPayment = `curl --location --request POST 'https://sandbox.hyperswitch.io/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: YOUR_API_KEY' \
--data-raw '{
"amount": 100,
"currency": "USD"
}'`
let phpRequestPayment = `<?php
require_once '../vendor/autoload.php';
require_once '../secrets.php';
$HYPER_SWITCH_API_KEY = $hyperswitch_secret_key;
$HYPER_SWITCH_API_BASE_URL = "https://sandbox.hyperswitch.io/payments";
function calculateOrderAmount(array $items): int {
// Replace this constant with a calculation of the order's amount
// Calculate the order total on the server to prevent
// people from directly manipulating the amount on the client
return 1400;
}
try {
$jsonStr = file_get_contents('php://input');
$jsonObj = json_decode($jsonStr);
/*
If you have two or more “business_country” + “business_label” pairs configured in your Hyperswitch dashboard,
please pass the fields business_country and business_label in this request body.
For accessing more features, you can check out the request body schema for payments-create API here :
https://api-reference.hyperswitch.io/docs/hyperswitch-api-reference/60bae82472db8-payments-create
*/
$payload = json_encode(array(
"amount" => calculateOrderAmount($jsonObj->items),
"currency" => "USD"
));
$ch = curl_init($HYPER_SWITCH_API_BASE_URL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'api-key: ' . $HYPER_SWITCH_API_KEY
));
$responseFromAPI = curl_exec($ch);
if ($responseFromAPI === false) {
$output = json_encode(array("error" => curl_error($ch)), 403);
}
curl_close($ch);
$decoded_response = json_decode($responseFromAPI, true);
$output=array("clientSecret" => $decoded_response['client_secret']);
echo json_encode($output);
} catch (Exception $e) {
echo json_encode(array("error" => $e->getMessage()), 403);
}`
let goRequestPayment = `package main
import (
"encoding/json"
"log"
"fmt"
"net/http"
"bytes"
)
const HYPER_SWITCH_API_KEY = "HYPERSWITCH_API_KEY"
const HYPER_SWITCH_API_BASE_URL = "https://sandbox.hyperswitch.io"
func createPaymentHandler(w http.ResponseWriter, r *http.Request) {
/*
If you have two or more “business_country” + “business_label” pairs configured in your Hyperswitch dashboard,
please pass the fields business_country and business_label in this request body.
For accessing more features, you can check out the request body schema for payments-create API here :
https://api-reference.hyperswitch.io/docs/hyperswitch-api-reference/60bae82472db8-payments-create
*/
payload := []byte("{"amount": 100, "currency": "USD"}")
client := &http.Client{}
req, err := http.NewRequest("POST", HYPER_SWITCH_API_BASE_URL+"/payments", bytes.NewBuffer(payload))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("api-key", HYPER_SWITCH_API_KEY)
resp, err := client.Do(req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
http.Error(w, fmt.Sprintf("API request failed with status code: %d", resp.StatusCode), http.StatusInternalServerError)
return
}
var data map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(map[string]interface{}{"clientSecret": data["client_secret"]})
}
func main() {
fs := http.FileServer(http.Dir("public"))
http.Handle("/", fs)
http.HandleFunc("/create-payment", createPaymentHandler)
addr := "localhost:4242"
log.Printf("Listening on %s ...", addr)
log.Fatal(http.ListenAndServe(addr, nil))
}`
let nodeReplaceApiKey: UserOnboardingTypes.migratestripecode = {
from: `// FROM
const stripe = require("stripe")("your_stripe_api_key");
const paymentIntent = await stripe.paymentIntents.create({...})`,
to: `//TO
const hyper = require("@juspay-tech/hyperswitch-node")("your_hyperswitch_api_key");
const paymentIntent = await stripe.paymentIntents.create({...})`,
}
let reactCheckoutForm: UserOnboardingTypes.migratestripecode = {
from: `// FROM
import { PaymentElement, useStripe, useElements,} from "@stripe/react-stripe-js";`,
to: `//TO
import { UnifiedCheckout, useStripe, useElements,} from "@juspay-tech/react-hyper-js";`,
}
let htmlCheckoutForm: UserOnboardingTypes.migratestripecode = {
from: `// FROM
<script src="https://js.stripe.com/v3/"></script>`,
to: `//TO
<script src="https://beta.hyperswitch.io/v1/HyperLoader.js"></script>`,
}
let reactHyperSwitchCheckout: UserOnboardingTypes.migratestripecode = {
from: `// FROM
const stripePromise = loadStripe("your_stripe_publishable_key");`,
to: `//TO
const hyperPromise = loadHyper("your_hyperswitch_publishable_key");
`,
}
let htmlHyperSwitchCheckout: UserOnboardingTypes.migratestripecode = {
from: `// FROM
const stripe = Stripe("your_stripe_publishable_key");`,
to: `// To
const hyper = Hyper("your_hyperswitch_publishable_key"); `,
}
let nodeMigrateFromStripeDXForReact = `npm install @juspay-tech/react-hyper-js
npm install @juspay-tech/hyper-js
npm install @juspay-tech/hyperswitch-node
`
let nodeMigrateFromStripeDXForHTML = `npm install @juspay-tech/hyperswitch-node`
let nodeCreateAPayment: string = `const express = require("express");
const app = express();
const hyperswitch = require("@juspay-tech/hyperswitch-node")('HYPERSWITCH_API_KEY');
app.use(express.static("public"));
app.use(express.json());
const calculateOrderAmount = (items) => {
return 1345;
};
app.post("/create-payment", async (req, res) => {
const { items } = req.body;
/*
If you have two or more "business_country" + "business_label" pairs configured in your Hyperswitch dashboard,
please pass the fields business_country and business_label in this request body.
For accessing more features, you can check out the request body schema for payments-create API here :
https://api-reference.hyperswitch.io/docs/hyperswitch-api-reference/60bae82472db8-payments-create
*/
const paymentIntent = await hyperswitch.paymentIntents.create({
amount: calculateOrderAmount(items),
currency: "USD",
});
res.send({
clientSecret: paymentIntent.client_secret,
});
});
app.listen(4242, () => console.log("Node server listening on port 4242!"));`
| 5,419 | 9,803 |
hyperswitch-control-center | src/screens/SelfServe/HSwitchSandboxOnboarding/UserOnboardingUtils.res | .res | open UserOnboardingTypes
let migrateStripfrontEndLang: array<languages> = [#ReactJs, #HTML]
let migrateStripBackEndLang: array<languages> = [#Node, #Python, #Go, #Ruby, #Java, #Net, #Php]
let integrateFromScratchfrontEndLang: array<languages> = [#ReactJs, #HTML]
let integrateFromScratchBackEndlang: array<languages> = [
#Node,
#Python,
#Go,
#Ruby,
#Java,
#Net,
#Php,
]
let platforms: array<platforms> = [#Web, #IOS, #Android, #BigCommerce, #ReactNative]
let requestOnlyPlatforms: array<platforms> = [#BigCommerce, #IOS, #Android, #ReactNative]
let getContentBasedOnIndex = (~currentRoute, ~tabIndex) =>
switch currentRoute {
| MigrateFromStripe =>
switch tabIndex {
| 0 => "Start by downloading your Test API Key and keeping it handy."
| 1 => "Install Hyperswitch's SDK and server side dependencies from npm.This is to add Hyperswitch dependencies to your application, along with your existing Stripe dependencies."
| 2 => "Replace the Stripe API key with Hyperswitch API key on the server side and modify the endpoint for the payment intent API.So, the Payment Intent API call previously being made to Stripe server will now be routed to Hyperswitch server."
| 3 => "Reconfigure checkout form to import from Hyperswitch.This will import the Hyperswitch Unified checkout dependencies."
| 4 => "Call loadHyper() with you Hyperswitch publishable key to configure the SDK library, from your website.This will load and invoke the Hyperswitch Checkout experience instead of the Stripe UI Elements."
| _ => ""
}
| IntegrateFromScratch =>
switch tabIndex {
| 0 => "Start by downloading your Test API Key and keeping it handy."
| 1 => "Once your customer is ready to pay, create a payment from your server to establish the intent of the customer to start payment."
| 2 => "Open the Hyperswitch checkout for your user inside an iFrame to display the payment methods."
| 3 => "Handle the response and display the thank you page to the user."
| _ => ""
}
| WooCommercePlugin =>
switch tabIndex {
| 0 => "Start by downloading the Hyperswitch Checkout Plugin, and installing it on your WordPress Admin Dashboard. Activate the Plugin post installation."
| 1 => "Step 1. Navigate to Woocommerce > Settings section in the dashboard. Click on the \"Payments\" tab and you should be able to find Hyperswitch listed in the Payment Methods table. Click on \"Hyperswitch\" to land on the Hyperswitch Plugin Settings page."
| 2 => "Step 2. Generate an API Key and paste it in your WooCommerce Plugin Settings."
| 3 => "Step 3. Copy your Publishable Key and paste it in your WooCommerce Plugin Settings."
| 4 => "Step 4. Copy your Payment Response Hash Key and paste it in your WooCommerce Plugin Settings."
| 5 => "Step 5. Configure your Webhook URL. You can find the Webhook URL on your Plugin Settings page under \"Enable Webhook\" Section."
| 6 => "Step 6. Save the changes"
| 7 => "Step 1. Configure connector(s) and start accepting payments."
| 8 => "Step 2. Configure a Routing Configuration to route payments to optimise your payment traffic across the various configured processors (only if you want to support multiple processors)"
| 9 => "Step 3. View and Manage your WooCommerce Order Payments on the Hyperswitch Dashboard."
| _ => ""
}
| _ => ""
}
let getLangauge = (str): languages => {
switch str->String.toLowerCase {
| "reactjs" => #ReactJs
| "node" => #Node
| "ruby" => #Ruby
| "java" => #Java
| "net" => #Net
| "rust" => #Rust
| "php" => #Php
| "shell" => #Shell
| "python" => #Python
| "html" => #HTML
| "go" => #Go
| "next" => #Next
| _ => #ChooseLanguage
}
}
let getPlatform = (str): platforms => {
switch str->String.toLowerCase {
| "web" => #Web
| "ios" => #IOS
| "android" => #Android
| "bigcommerce" => #BigCommerce
| "reactnative" => #ReactNative
| _ => #Web
}
}
let getMigrateFromStripeDX = (frontendlang: languages, backendlang: languages): string => {
open CodeSnippets
switch (frontendlang, backendlang) {
| (#ReactJs, #Node) => nodeMigrateFromStripeDXForReact
| (#HTML, #Node) => nodeMigrateFromStripeDXForHTML
| _ => ""
}
}
let getInstallDependencies = (lang: languages): string => {
open CodeSnippets
switch lang {
| #ReactJs => reactInstallDependencies
| #Node => nodeInstallDependencies
| _ => ""
}
}
let getImports = (lang: languages): string => {
open CodeSnippets
switch lang {
| #ReactJs => reactImports
| _ => ""
}
}
let getLoad = (lang: languages): string => {
open CodeSnippets
switch lang {
| #ReactJs => reactLoad
| #HTML => htmlLoad
| _ => ""
}
}
let getInitialize = (lang: languages): string => {
open CodeSnippets
switch lang {
| #ReactJs => reactInitialize
| #HTML => htmlInitialize
| _ => ""
}
}
let getCheckoutFormForDisplayCheckoutPage = (lang: languages): string => {
open CodeSnippets
switch lang {
| #ReactJs => reactCheckoutFormDisplayCheckoutPage
| _ => ""
}
}
let getHandleEvents = (lang: languages): string => {
open CodeSnippets
switch lang {
| #ReactJs => reactHandleEvent
| #HTML => htmlHandleEvents
| _ => ""
}
}
let getDisplayConformation = (lang: languages): string => {
open CodeSnippets
switch lang {
| #ReactJs => reactDisplayConfirmation
| #HTML => htmlDisplayConfirmation
| _ => ""
}
}
let getReplaceAPIkeys = (lang: languages) => {
open CodeSnippets
switch lang {
| #Node => nodeReplaceApiKey
| _ => {from: "", to: ""}
}
}
let getCheckoutForm = (lang: languages) => {
open CodeSnippets
switch lang {
| #ReactJs => reactCheckoutForm
| #HTML => htmlCheckoutForm
| _ => {from: "", to: ""}
}
}
let getHyperswitchCheckout = (lang: languages) => {
open CodeSnippets
switch lang {
| #ReactJs => reactHyperSwitchCheckout
| #HTML => htmlHyperSwitchCheckout
| _ => {from: "", to: ""}
}
}
let getCreateAPayment = (lang: languages): string => {
open CodeSnippets
switch lang {
| #Node => nodeCreateAPayment
| #Ruby => rubyRequestPayment
| #Java => javaRequestPayment
| #Python => pythonRequestPayment
| #Net => netRequestPayment
| #Rust => rustRequestPayment
| #Shell => shellRequestPayment
| #Go => goRequestPayment
| #Php => phpRequestPayment
| _ => ""
}
}
let getMainPageText = currentRoute =>
switch currentRoute {
| MigrateFromStripe => "Migrate from Stripe"
| IntegrateFromScratch => "Let's start integrating from Scratch"
| WooCommercePlugin => "Let's start your WooCommerce Integration"
| _ => "Explore, Build and Integrate"
}
let getLanguages = currentRoute =>
switch currentRoute {
| MigrateFromStripe => (migrateStripfrontEndLang, migrateStripBackEndLang)
| IntegrateFromScratch => (integrateFromScratchfrontEndLang, integrateFromScratchBackEndlang)
| SampleProjects => (integrateFromScratchfrontEndLang, integrateFromScratchBackEndlang)
| _ => ([], [])
}
// To be refactored
let getFilteredList = (
frontEndLang: languages,
backEndLang: languages,
githubcodespaces: array<sectionContentType>,
) => {
let felang = Some((frontEndLang :> string)->String.toLowerCase)
let belang = Some((backEndLang :> string)->String.toLowerCase)
if felang === Some("chooselanguage") && belang === Some("chooselanguage") {
githubcodespaces
} else {
let filteredList = githubcodespaces->Array.filter(value => {
if felang === Some("chooselanguage") {
value.backEndLang === belang
} else if belang === Some("chooselanguage") {
value.frontEndLang == felang
} else {
value.frontEndLang == felang && value.backEndLang === belang
}
})
filteredList
}
}
let variantToTextMapperForBuildHS = currentRoute => {
switch currentRoute {
| MigrateFromStripe => "migrateFromStripe"
| IntegrateFromScratch => "integrateFromScratch"
| WooCommercePlugin => "wooCommercePlugin"
| _ => "onboarding"
}
}
let githubCodespaces: array<UserOnboardingTypes.sectionContentType> = [
{
headerIcon: "github",
buttonText: "View Docs",
customIconCss: "",
url: "https://github.com/juspay/hyperswitch-html-node",
frontEndLang: "html",
backEndLang: "node",
displayFrontendLang: "HTML",
displayBackendLang: "Node",
},
{
headerIcon: "github",
buttonText: "View Docs",
customIconCss: "",
url: "https://github.com/juspay/hyperswitch-html-python",
frontEndLang: "html",
backEndLang: "python",
displayFrontendLang: "HTML",
displayBackendLang: "Python",
},
{
headerIcon: "github",
buttonText: "View Docs",
customIconCss: "",
url: "https://github.com/juspay/hyperswitch-html-php",
frontEndLang: "html",
backEndLang: "php",
displayFrontendLang: "HTML",
displayBackendLang: "PHP",
},
{
headerIcon: "github",
buttonText: "View Docs",
customIconCss: "",
url: "https://github.com/juspay/hyperswitch-html-go",
frontEndLang: "html",
backEndLang: "go",
displayFrontendLang: "HTML",
displayBackendLang: "Go",
},
{
headerIcon: "github",
buttonText: "View Docs",
customIconCss: "",
url: "https://github.com/juspay/hyperswitch-html-java",
frontEndLang: "html",
backEndLang: "java",
displayFrontendLang: "HTML",
displayBackendLang: "Java",
},
{
headerIcon: "github",
buttonText: "View Docs",
customIconCss: "",
url: "https://github.com/juspay/hyperswitch-html-ruby",
frontEndLang: "html",
backEndLang: "ruby",
displayFrontendLang: "HTML",
displayBackendLang: "Ruby",
},
{
headerIcon: "github",
buttonText: "View Docs",
customIconCss: "",
url: "https://github.com/juspay/hyperswitch-html-dotnet",
frontEndLang: "html",
backEndLang: "net",
displayFrontendLang: "HTML",
displayBackendLang: ".Net",
},
{
headerIcon: "github",
buttonText: "View Docs",
customIconCss: "",
url: "https://github.com/juspay/hyperswitch-react-node",
frontEndLang: "reactjs",
backEndLang: "node",
displayFrontendLang: "React-Js",
displayBackendLang: "Node",
},
{
headerIcon: "github",
buttonText: "View Docs",
customIconCss: "",
url: "https://github.com/juspay/hyperswitch-next-node",
frontEndLang: "next",
backEndLang: "node",
displayFrontendLang: "Next-React-Ts",
displayBackendLang: "Node",
},
{
headerIcon: "github",
buttonText: "View Docs",
customIconCss: "",
url: "https://github.com/juspay/hyperswitch-react-dotnet",
frontEndLang: "reactjs",
backEndLang: "net",
displayFrontendLang: "React-Js",
displayBackendLang: ".Net",
},
{
headerIcon: "github",
buttonText: "View Docs",
customIconCss: "",
url: "https://github.com/juspay/hyperswitch-react-ruby",
frontEndLang: "reactjs",
backEndLang: "ruby",
displayFrontendLang: "React-Js",
displayBackendLang: "Ruby",
},
{
headerIcon: "github",
buttonText: "View Docs",
customIconCss: "",
url: "https://github.com/juspay/hyperswitch-react-java",
frontEndLang: "reactjs",
backEndLang: "java",
displayFrontendLang: "React-Js",
displayBackendLang: "Java",
},
{
headerIcon: "github",
buttonText: "View Docs",
customIconCss: "",
url: "https://github.com/juspay/hyperswitch-react-python",
frontEndLang: "reactjs",
backEndLang: "python",
displayFrontendLang: "React-Js",
displayBackendLang: "Python",
},
{
headerIcon: "github",
buttonText: "View Docs",
customIconCss: "",
url: "https://github.com/juspay/hyperswitch-react-php",
frontEndLang: "reactjs",
backEndLang: "php",
displayFrontendLang: "React-Js",
displayBackendLang: "PHP",
},
{
headerIcon: "github",
buttonText: "View Docs",
customIconCss: "",
url: "https://github.com/juspay/hyperswitch-react-go",
frontEndLang: "reactjs",
backEndLang: "go",
displayFrontendLang: "React-Js",
displayBackendLang: "Go",
},
]
| 3,323 | 9,804 |
hyperswitch-control-center | src/screens/SelfServe/HSwitchSandboxOnboarding/UserOnboarding.res | .res | let buildHyperswitch: array<UserOnboardingTypes.sectionContentType> = [
{
headerIcon: "migrate-from-stripe",
headerText: "Migrate from Stripe",
buttonText: "Start Integration",
customIconCss: "!w-96",
url: "migrate-from-stripe",
isIconImg: true,
imagePath: "/assets/MigrateFromStripe.svg",
subTextCustomValues: ["Low Code", "Blazing Fast Go-Live", "Stripe Compatible"],
},
{
headerIcon: "woocommerce-plugin",
headerText: "WooCommerce Integration",
buttonText: "Start Integration",
customIconCss: "!w-96",
url: "woocommerce-plugin",
rightIcon: <Icon name="new-setup" size=25 className="w-20" />,
isIconImg: true,
imagePath: "/assets/WooCommercePlugin.svg",
subTextCustomValues: [
"No Code, Blazing Fast Go-Live",
"A Seamless Checkout Experience",
"Orders Management",
],
},
]
let integrateHyperswitch: array<UserOnboardingTypes.sectionContentType> = [
{
headerIcon: "github",
headerText: "Clone a sample project",
buttonText: "Start Integration",
customIconCss: "!w-15",
url: "sample-projects",
subTextCustomValues: ["Supports 20+ languages", "Minimal integration steps", "Fastest!"],
buttonType: Primary,
rightIcon: <Icon name="quickSetup" size=25 className="w-28" />,
},
{
headerIcon: "integrate-from-scratch",
headerText: "Standard Integration",
buttonText: "Start Integration",
customIconCss: "!w-20",
url: "integrate-from-scratch",
subTextCustomValues: [
"40+ Payment Processors",
"60+ Payment Methods",
"Unlimited Customizations",
],
},
]
module DefaultDocsPage = {
@react.component
let make = () => {
<div className="flex flex-col gap-12 p-8">
<UserOnboardingUIUtils.Section
sectionHeaderText="Integrate Hyperswitch"
sectionSubText="Start by cloning a project or Integrating from scratch"
subSectionArray=integrateHyperswitch
/>
<div className="border-1 bg-grey-700 opacity-50 w-full" />
<UserOnboardingUIUtils.Section
sectionHeaderText="Other Integration" sectionSubText="" subSectionArray=buildHyperswitch
/>
</div>
}
}
@react.component
let make = () => {
open UserOnboardingTypes
let url = RescriptReactRouter.useUrl()
let searchParams = url.search
let filtersFromUrl =
LogicUtils.getDictFromUrlSearchParams(searchParams)->Dict.get("type")->Option.getOr("")
let (currentRoute, setCurrentRoute) = React.useState(_ => OnboardingDefault)
let {
integrationDetails,
setIntegrationDetails,
dashboardPageState,
setDashboardPageState,
} = React.useContext(GlobalProvider.defaultContext)
React.useEffect(() => {
if dashboardPageState !== #HOME {
RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/onboarding"))
}
None
}, [dashboardPageState])
React.useEffect(() => {
let routeType = switch filtersFromUrl {
| "migrate-from-stripe" => MigrateFromStripe
| "integrate-from-scratch" => IntegrateFromScratch
| "sample-projects" => SampleProjects
| "woocommerce-plugin" => WooCommercePlugin
| _ => OnboardingDefault
}
setCurrentRoute(_ => routeType)
setDashboardPageState(_ => #INTEGRATION_DOC)
None
}, [url.search])
open APIUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod(~showErrorToast=false)
let skipAndContinue = async () => {
try {
let url = getURL(~entityName=V1(INTEGRATION_DETAILS), ~methodType=Post)
let metaDataDict = Dict.fromArray([("is_skip", true->JSON.Encode.bool)])->JSON.Encode.object
let body = HSwitchUtils.constructOnboardingBody(
~dashboardPageState,
~integrationDetails,
~is_done=false,
~metadata=metaDataDict,
)
let _ = await updateDetails(url, body, Post)
setIntegrationDetails(_ => body->ProviderHelper.getIntegrationDetails)
} catch {
| _ => ()
}
setDashboardPageState(_ => #HOME)
}
let markAsDone = async () => {
try {
let url = getURL(~entityName=V1(INTEGRATION_DETAILS), ~methodType=Post)
let body = HSwitchUtils.constructOnboardingBody(
~dashboardPageState,
~integrationDetails,
~is_done=true,
~metadata=[
("is_skip", false->JSON.Encode.bool),
(
"integrationType",
currentRoute->UserOnboardingUtils.variantToTextMapperForBuildHS->JSON.Encode.string,
),
]->LogicUtils.getJsonFromArrayOfJson,
)
let _ = await updateDetails(url, body, Post)
setIntegrationDetails(_ => body->ProviderHelper.getIntegrationDetails)
setDashboardPageState(_ => #HOME)
} catch {
| Exn.Error(e) =>
let err = Exn.message(e)->Option.getOr("Something went wrong")
Exn.raiseError(err)
}
}
<div
className="h-screen w-full bg-no-repeat bg-cover "
style={
backgroundImage: `url(/images/hyperswitchImages/PostLoginBackground.svg)`,
}>
<div
className="h-screen w-screen md:w-pageWidth11 md:mx-auto overflow-hidden grid grid-cols-1 md:grid-cols-[12rem,1fr,18rem] md:grid-rows-[4rem,1fr] py-10 px-4 gap-x-2 gap-y-8 grid-flow-row md:grid-flow-row">
<div className="justify-self-center md:justify-self-start row-span-1">
<Icon name="hyperswitch-text-icon" size=28 className="cursor-pointer w-40 " />
</div>
<div
className="row-span-1 col-span-1 flex justify-center items-start w-full text-lg font-semibold">
{currentRoute->UserOnboardingUtils.getMainPageText->React.string}
</div>
<Button
text="Skip & Explore Dashboard"
customButtonStyle="row-span-1 col-span-1 justify-self-center md:justify-self-end !rounded-md"
buttonType={PrimaryOutline}
onClick={_ => skipAndContinue()->ignore}
/>
<div
className="h-75-vh md:h-full w-full col-span-1 md:col-span-3 border rounded-md bg-white overflow-scroll">
{switch currentRoute {
| MigrateFromStripe
| IntegrateFromScratch
| SampleProjects =>
<IntegrationDocs currentRoute markAsDone />
| WooCommercePlugin => <IntegrationDocs currentRoute markAsDone languageSelection=false />
| _ => <DefaultDocsPage />
}}
</div>
</div>
</div>
}
| 1,609 | 9,805 |
hyperswitch-control-center | src/screens/SwitchMerchant/SwitchMerchantUtils.res | .res | type switchMerchantListResponse = {
merchant_id: string,
merchant_name: string,
is_active: bool,
role_id: string,
role_name: string,
org_id: string,
}
let defaultValue = {
merchant_id: "",
merchant_name: "",
is_active: false,
role_id: "",
role_name: "",
org_id: "",
}
let convertListResponseToTypedResponse = json => {
open LogicUtils
json
->getArrayFromJson([])
->Array.map(ele => {
let dictOfElement = ele->getDictFromJsonObject
let merchantId = dictOfElement->getString("merchant_id", "")
let merchantName =
dictOfElement->getString("merchant_name", merchantId)->isNonEmptyString
? dictOfElement->getString("merchant_name", merchantId)
: merchantId
let role_id = dictOfElement->getString("role_id", "")
let role_name = dictOfElement->getString("role_name", "")
let org_id = dictOfElement->getString("org_id", "")
{
merchant_id: merchantId,
merchant_name: merchantName,
is_active: dictOfElement->getBool("is_active", false),
role_id,
role_name,
org_id,
}
})
}
| 277 | 9,806 |
hyperswitch-control-center | src/screens/Developer/PaymentSettings/PaymentSettingsList.res | .res | @react.component
let make = (
~isFromSettings=true,
~showModalFromOtherScreen=false,
~setShowModalFromOtherScreen=_bool => (),
) => {
open PaymentSettingsListEntity
let (offset, setOffset) = React.useState(_ => 0)
let {userHasAccess, hasAnyGroupAccess} = GroupACLHooks.useUserGroupACLHook()
let businessProfileValues = HyperswitchAtom.businessProfilesAtom->Recoil.useRecoilValueFromAtom
<RenderIf condition=isFromSettings>
<div className="relative h-full">
<div className="flex flex-col-reverse md:flex-col">
<PageUtils.PageHeading
title="Payment settings"
subTitle="Set up and monitor transaction webhooks for real-time notifications."
/>
<LoadedTable
title="Payment settings"
hideTitle=true
resultsPerPage=7
visibleColumns
entity={webhookProfileTableEntity(
// TODO: Remove `MerchantDetailsManage` permission in future
~authorization={
hasAnyGroupAccess(
userHasAccess(~groupAccess=MerchantDetailsManage),
userHasAccess(~groupAccess=AccountManage),
)
},
)}
showSerialNumber=true
actualData={businessProfileValues->Array.map(Nullable.make)}
totalResults={businessProfileValues->Array.length}
offset
setOffset
currrentFetchCount={businessProfileValues->Array.length}
/>
</div>
</div>
</RenderIf>
}
| 324 | 9,807 |
hyperswitch-control-center | src/screens/Developer/PaymentSettings/PaymentSettingsMetadata.res | .res | module MetadataAuthenticationInput = {
@react.component
let make = (~index, ~allowEdit, ~isDisabled) => {
open LogicUtils
open FormRenderer
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let (key, setKey) = React.useState(_ => "")
let (metaValue, setValue) = React.useState(_ => "")
let getMetadatKeyValues = () => {
let metadataKeyValueDict =
formState.values
->getDictFromJsonObject
->getDictfromDict("metadata")
let key = metadataKeyValueDict->Dict.keysToArray->LogicUtils.getValueFromArray(index, "")
let customMetadataVal = metadataKeyValueDict->getOptionString(key)
switch customMetadataVal {
| Some(value) => (key, value)
| _ => ("", "")
}
}
React.useEffect(() => {
let (metadataKey, customMetadataVal) = getMetadatKeyValues()
setValue(_ => customMetadataVal)
setKey(_ => metadataKey)
None
}, [])
let form = ReactFinalForm.useForm()
let keyInput: ReactFinalForm.fieldRenderPropsInput = {
name: "string",
onBlur: _ => {
let (metadataKey, customMetadataVal) = getMetadatKeyValues()
//When we try to change just key field.
if metadataKey->String.length > 0 {
let name = `metadata.${metadataKey}`
let newKey = `metadata.${key}`
form.change(name, JSON.Encode.null)
if key->String.length > 0 {
form.change(newKey, customMetadataVal->JSON.Encode.string)
}
}
//When we empty the key field , then just put a new key field name, keeping the value field the same.
if (
metadataKey->String.length <= 0 && metaValue->String.length > 0 && key->String.length > 0
) {
let field = `metadata.${key}`
form.change(field, metaValue->JSON.Encode.string)
}
},
onChange: ev => {
let value = ReactEvent.Form.target(ev)["value"]
let regexForProfileName = "^([a-z]|[A-Z]|[0-9]|_|-)+$"
let isValid = if value->String.length <= 2 {
true
} else if (
value->isEmptyString ||
value->String.length > 64 ||
!RegExp.test(RegExp.fromString(regexForProfileName), value)
) {
false
} else {
true
}
if value->String.length <= 0 {
let name = `metadata.${key}`
form.change(name, JSON.Encode.null)
}
//Not allow users to enter just integers
switch (value->getOptionIntFromString->Option.isNone, isValid) {
| (true, true) => setKey(_ => value)
| _ => ()
}
},
onFocus: _ => (),
value: key->JSON.Encode.string,
checked: true,
}
let valueInput: ReactFinalForm.fieldRenderPropsInput = {
name: "string",
onBlur: _ => {
if key->String.length > 0 {
let name = `metadata.${key}`
form.change(name, metaValue->JSON.Encode.string)
}
},
onChange: ev => {
let value = ReactEvent.Form.target(ev)["value"]
setValue(_ => value)
},
onFocus: _ => (),
value: metaValue->JSON.Encode.string,
checked: true,
}
<DesktopRow wrapperClass="flex-1">
<div className="mt-5">
<TextInput
input={keyInput} placeholder={"Enter key"} isDisabled={isDisabled && !allowEdit}
/>
</div>
<div className="mt-5">
<TextInput
input={valueInput} placeholder={"Enter value"} isDisabled={isDisabled && !allowEdit}
/>
</div>
</DesktopRow>
}
}
module MetadataHeaders = {
@react.component
let make = (~setAllowEdit, ~allowEdit) => {
open LogicUtils
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let metadataKeyValueDict =
formState.values
->getDictFromJsonObject
->getDictfromDict("metadata")
let (showModal, setShowModal) = React.useState(_ => false)
let (isDisabled, setDisabled) = React.useState(_ => true)
let allowEditConfiguration = () => {
setAllowEdit(_ => true)
setShowModal(_ => false)
}
React.useEffect(() => {
let isEmpty = metadataKeyValueDict->LogicUtils.isEmptyDict
setDisabled(_ => !isEmpty)
setAllowEdit(_ => isEmpty)
None
}, [])
<div className="flex-1">
<div className="flex flex-row justify-between items-center gap-4 ">
<p
className={`ml-4 text-xl dark:text-jp-gray-text_darktheme dark:text-opacity-50 !text-grey-700 font-semibold `}>
{"Custom Metadata Headers"->React.string}
</p>
<RenderIf
condition={!(metadataKeyValueDict->LogicUtils.isEmptyDict) && isDisabled && !allowEdit}>
<div
className="flex gap-2 items-center cursor-pointer"
onClick={_ => setShowModal(_ => true)}>
<Icon name="nd-edit" size=14 />
<a className="text-primary cursor-pointer"> {"Edit"->React.string} </a>
</div>
</RenderIf>
</div>
<div className="grid grid-cols-5 gap-2">
{Array.fromInitializer(~length=2, i => i)
->Array.mapWithIndex((_, index) =>
<div key={index->Int.toString} className="col-span-4">
<MetadataAuthenticationInput index={index} allowEdit isDisabled />
</div>
)
->React.array}
</div>
<Modal
showModal
setShowModal
modalClass="w-full md:w-4/12 mx-auto my-40 border-t-8 border-t-orange-960 rounded-xl">
<div className="relative flex items-start px-4 pb-10 pt-8 gap-4">
<Icon
name="warning-outlined" size=25 className="w-8" onClick={_ => setShowModal(_ => false)}
/>
<div className="flex flex-col gap-5">
<p className="font-bold text-2xl"> {"Edit the Current Configuration"->React.string} </p>
<p className=" text-hyperswitch_black opacity-50 font-medium">
{"Editing the current configuration will override the current active configuration."->React.string}
</p>
</div>
<Icon
className="absolute top-2 right-2"
name="hswitch-close"
size=22
onClick={_ => setShowModal(_ => false)}
/>
</div>
<div className="flex items-end justify-end gap-4">
<Button
buttonType=Button.Primary onClick={_ => allowEditConfiguration()} text="Proceed"
/>
<Button
buttonType=Button.Secondary onClick={_ => setShowModal(_ => false)} text="Cancel"
/>
</div>
</Modal>
</div>
}
}
@react.component
let make = (~busiProfieDetails, ~setBusiProfie, ~setScreenState, ~profileId="") => {
open APIUtils
open LogicUtils
open FormRenderer
open MerchantAccountUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let url = RescriptReactRouter.useUrl()
let id = HSwitchUtils.getConnectorIDFromUrl(url.path->List.toArray, profileId)
let showToast = ToastState.useShowToast()
let fetchBusinessProfiles = BusinessProfileHook.useFetchBusinessProfiles()
let (allowEdit, setAllowEdit) = React.useState(_ => false)
let onSubmit = async (values, _) => {
try {
setScreenState(_ => PageLoaderWrapper.Loading)
let valuesDict = values->getDictFromJsonObject
let url = getURL(~entityName=V1(BUSINESS_PROFILE), ~methodType=Post, ~id=Some(id))
let body = valuesDict->JSON.Encode.object->getMetdataKeyValuePayload->JSON.Encode.object
let res = await updateDetails(url, body, Post)
setBusiProfie(_ => res->BusinessProfileMapper.businessProfileTypeMapper)
showToast(~message=`Details updated`, ~toastType=ToastState.ToastSuccess)
setScreenState(_ => PageLoaderWrapper.Success)
setAllowEdit(_ => false)
fetchBusinessProfiles()->ignore
} catch {
| _ => {
setScreenState(_ => PageLoaderWrapper.Success)
showToast(~message=`Failed to updated`, ~toastType=ToastState.ToastError)
}
}
Nullable.null
}
<ReactFinalForm.Form
key="auth"
initialValues={busiProfieDetails->parseBussinessProfileJson->JSON.Encode.object}
subscription=ReactFinalForm.subscribeToValues
onSubmit
render={({handleSubmit}) => {
<form onSubmit={handleSubmit} className="flex flex-col gap-8 h-full w-full py-6 px-4">
<MetadataHeaders setAllowEdit allowEdit />
<DesktopRow>
<div className="flex justify-end w-full gap-2">
<RenderIf condition=allowEdit>
<SubmitButton
text="Update"
buttonType=Button.Primary
buttonSize=Button.Medium
disabledParamter={!allowEdit}
/>
<Button
buttonType=Button.Secondary
onClick={_ =>
RescriptReactRouter.push(
GlobalVars.appendDashboardPath(~url="/payment-settings"),
)}
text="Cancel"
/>
</RenderIf>
</div>
</DesktopRow>
// <FormValuesSpy />
</form>
}}
/>
}
| 2,214 | 9,808 |
hyperswitch-control-center | src/screens/Developer/PaymentSettings/PaymentSettingsListEntity.res | .res | open HSwitchSettingTypes
open BusinessMappingUtils
type columns =
| ProfileName
| ReturnUrl
| WebhookUrl
let visibleColumns = [WebhookUrl, ReturnUrl, ProfileName]
let defaultColumns = [ProfileName, ReturnUrl, WebhookUrl]
let allColumns = [ProfileName, ReturnUrl, WebhookUrl]
let getHeading = colType => {
switch colType {
| ProfileName => Table.makeHeaderInfo(~key="profile_name", ~title="Profile Name")
| ReturnUrl => Table.makeHeaderInfo(~key="return_url", ~title="Return URL")
| WebhookUrl => Table.makeHeaderInfo(~key="webhook_url", ~title="Webhook URL")
}
}
let getCell = (item: profileEntity, colType): Table.cell => {
switch colType {
| ProfileName => Text(item.profile_name)
| ReturnUrl => Text(item.return_url->Option.getOr(""))
| WebhookUrl => Text(item.webhook_details.webhook_url->Option.getOr(""))
}
}
let itemToObjMapper = dict => {
open LogicUtils
{
profile_id: getString(dict, "profile_id", ""),
profile_name: getString(dict, ProfileName->getStringFromVariant, ""),
merchant_id: getString(dict, "merchant_id", ""),
return_url: getOptionString(dict, "return_url"),
payment_response_hash_key: getOptionString(dict, "payment_response_hash_key"),
webhook_details: dict
->getObj("webhook_details", Dict.make())
->BusinessProfileMapper.constructWebhookDetailsObject,
authentication_connector_details: dict
->getObj("webhook_details", Dict.make())
->BusinessProfileMapper.constructAuthConnectorObject,
collect_shipping_details_from_wallet_connector: getOptionBool(
dict,
"collect_shipping_details_from_wallet_connector",
),
always_collect_shipping_details_from_wallet_connector: dict->getOptionBool(
"always_collect_shipping_details_from_wallet_connector",
),
collect_billing_details_from_wallet_connector: dict->getOptionBool(
"collect_billing_details_from_wallet_connector",
),
always_collect_billing_details_from_wallet_connector: dict->getOptionBool(
"always_collect_billing_details_from_wallet_connector",
),
outgoing_webhook_custom_http_headers: None,
metadata: None,
is_connector_agnostic_mit_enabled: None,
is_auto_retries_enabled: dict->getOptionBool("is_auto_retries_enabled"),
max_auto_retries_enabled: dict->getOptionInt("max_auto_retries_enabled"),
is_click_to_pay_enabled: dict->getOptionBool("is_click_to_pay_enabled"),
authentication_product_ids: Some(
dict
->getDictfromDict("authentication_product_ids")
->JSON.Encode.object,
),
force_3ds_challenge: None,
is_debit_routing_enabled: None,
}
}
let getItems: JSON.t => array<profileEntity> = json => {
LogicUtils.getArrayDataFromJson(json, itemToObjMapper)
}
let webhookProfileTableEntity = (~authorization: CommonAuthTypes.authorization) =>
EntityType.makeEntity(
~uri="",
~getObjects=getItems,
~defaultColumns,
~allColumns,
~getHeading,
~dataKey="",
~getCell,
~getShowLink={
profile =>
GroupAccessUtils.linkForGetShowLinkViaAccess(
~url=GlobalVars.appendDashboardPath(~url=`/payment-settings/${profile.profile_id}`),
~authorization,
)
},
)
| 741 | 9,809 |
hyperswitch-control-center | src/screens/Developer/PaymentSettings/PaymentSettings.res | .res | module InfoViewForWebhooks = {
@react.component
let make = (~heading, ~subHeading, ~isCopy=false) => {
let showToast = ToastState.useShowToast()
let onCopyClick = ev => {
ev->ReactEvent.Mouse.stopPropagation
Clipboard.writeText(subHeading)
showToast(~message="Copied to Clipboard!", ~toastType=ToastSuccess)
}
<div className={`flex flex-col gap-2 m-2 md:m-4 w-1/2`}>
<p className="font-semibold text-fs-15"> {heading->React.string} </p>
<div className="flex gap-2 break-all w-full items-start">
<p className="font-medium text-fs-14 text-black opacity-50"> {subHeading->React.string} </p>
<RenderIf condition={isCopy}>
<Icon
name="nd-copy"
className="cursor-pointer"
onClick={ev => {
onCopyClick(ev)
}}
/>
</RenderIf>
</div>
</div>
}
}
module AuthenticationInput = {
@react.component
let make = (~index, ~allowEdit, ~isDisabled) => {
open LogicUtils
open FormRenderer
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let (key, setKey) = React.useState(_ => "")
let (metaValue, setValue) = React.useState(_ => "")
let getOutGoingWebhook = () => {
let outGoingWebhookDict =
formState.values
->getDictFromJsonObject
->getDictfromDict("outgoing_webhook_custom_http_headers")
let key = outGoingWebhookDict->Dict.keysToArray->LogicUtils.getValueFromArray(index, "")
let outGoingWebHookVal = outGoingWebhookDict->getOptionString(key)
switch outGoingWebHookVal {
| Some(value) => (key, value)
| _ => ("", "")
}
}
React.useEffect(() => {
let (outGoingWebhookKey, outGoingWebHookValue) = getOutGoingWebhook()
setValue(_ => outGoingWebHookValue)
setKey(_ => outGoingWebhookKey)
None
}, [])
React.useEffect(() => {
if allowEdit {
setValue(_ => "")
}
None
}, [allowEdit])
let form = ReactFinalForm.useForm()
let keyInput: ReactFinalForm.fieldRenderPropsInput = {
name: "string",
onBlur: _ => (),
onChange: ev => {
let value = ReactEvent.Form.target(ev)["value"]
let regexForProfileName = "^([a-z]|[A-Z]|[0-9]|_|-)+$"
let isValid = if value->String.length <= 2 {
true
} else if (
value->isEmptyString ||
value->String.length > 64 ||
!RegExp.test(RegExp.fromString(regexForProfileName), value)
) {
false
} else {
true
}
if value->String.length <= 0 {
let name = `outgoing_webhook_custom_http_headers.${key}`
form.change(name, JSON.Encode.null)
}
//Not allow users to enter just integers
switch (value->getOptionIntFromString->Option.isNone, isValid) {
| (true, true) => setKey(_ => value)
| _ => ()
}
},
onFocus: _ => (),
value: key->JSON.Encode.string,
checked: true,
}
let valueInput: ReactFinalForm.fieldRenderPropsInput = {
name: "string",
onBlur: _ => {
if key->String.length > 0 {
let name = `outgoing_webhook_custom_http_headers.${key}`
form.change(name, metaValue->JSON.Encode.string)
}
},
onChange: ev => {
let value = ReactEvent.Form.target(ev)["value"]
setValue(_ => value)
},
onFocus: _ => (),
value: metaValue->JSON.Encode.string,
checked: true,
}
<DesktopRow wrapperClass="flex-1">
<div className="mt-5">
<TextInput
input={keyInput} placeholder={"Enter key"} isDisabled={isDisabled && !allowEdit}
/>
</div>
<div className="mt-5">
<TextInput
input={valueInput} placeholder={"Enter value"} isDisabled={isDisabled && !allowEdit}
/>
</div>
</DesktopRow>
}
}
module WebHookAuthenticationHeaders = {
@react.component
let make = (~setAllowEdit, ~allowEdit) => {
open LogicUtils
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let form = ReactFinalForm.useForm()
let outGoingWebhookDict =
formState.values
->getDictFromJsonObject
->getDictfromDict("outgoing_webhook_custom_http_headers")
let (showModal, setShowModal) = React.useState(_ => false)
let (isDisabled, setDisabled) = React.useState(_ => true)
let allowEditConfiguration = () => {
form.change(`outgoing_webhook_custom_http_headers`, JSON.Encode.null)
setAllowEdit(_ => true)
setShowModal(_ => false)
}
React.useEffect(() => {
let isEmpty = outGoingWebhookDict->LogicUtils.isEmptyDict
setDisabled(_ => !isEmpty)
setAllowEdit(_ => isEmpty)
None
}, [])
<div className="flex-1">
<div className="flex flex-row justify-between items-center gap-4 ">
<p
className={`text-xl dark:text-jp-gray-text_darktheme dark:text-opacity-50 !text-grey-700 font-semibold ml-4`}>
{"Custom Headers"->React.string}
</p>
<RenderIf
condition={!(outGoingWebhookDict->LogicUtils.isEmptyDict) && isDisabled && !allowEdit}>
<div
className="flex gap-2 items-center cursor-pointer"
onClick={_ => setShowModal(_ => true)}>
<Icon name="nd-edit" size=14 />
<a className="text-primary cursor-pointer"> {"Edit"->React.string} </a>
</div>
</RenderIf>
</div>
<div className="grid grid-cols-5 gap-2">
{Array.fromInitializer(~length=4, i => i)
->Array.mapWithIndex((_, index) =>
<div key={index->Int.toString} className="col-span-4">
<AuthenticationInput index={index} allowEdit isDisabled />
</div>
)
->React.array}
</div>
<Modal
showModal
setShowModal
modalClass="w-full md:w-4/12 mx-auto my-40 border-t-8 border-t-orange-960 rounded-xl">
<div className="relative flex items-start px-4 pb-10 pt-8 gap-4">
<Icon
name="warning-outlined" size=25 className="w-8" onClick={_ => setShowModal(_ => false)}
/>
<div className="flex flex-col gap-5">
<p className="font-bold text-2xl"> {"Edit the Current Configuration"->React.string} </p>
<p className=" text-hyperswitch_black opacity-50 font-medium">
{"Editing the current configuration will override the current active configuration."->React.string}
</p>
</div>
<Icon
className="absolute top-2 right-2"
name="hswitch-close"
size=22
onClick={_ => setShowModal(_ => false)}
/>
</div>
<div className="flex items-end justify-end gap-4">
<Button
buttonType=Button.Primary onClick={_ => allowEditConfiguration()} text="Proceed"
/>
<Button
buttonType=Button.Secondary onClick={_ => setShowModal(_ => false)} text="Cancel"
/>
</div>
</Modal>
</div>
}
}
module WebHookSection = {
@react.component
let make = (~busiProfieDetails, ~setBusiProfie, ~setScreenState, ~profileId="") => {
open APIUtils
open LogicUtils
open FormRenderer
open MerchantAccountUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let url = RescriptReactRouter.useUrl()
let id = HSwitchUtils.getConnectorIDFromUrl(url.path->List.toArray, profileId)
let showToast = ToastState.useShowToast()
let fetchBusinessProfiles = BusinessProfileHook.useFetchBusinessProfiles()
let (allowEdit, setAllowEdit) = React.useState(_ => false)
let onSubmit = async (values, _) => {
try {
setScreenState(_ => PageLoaderWrapper.Loading)
let valuesDict = values->getDictFromJsonObject
let url = getURL(~entityName=V1(BUSINESS_PROFILE), ~methodType=Post, ~id=Some(id))
let body = valuesDict->JSON.Encode.object->getCustomHeadersPayload->JSON.Encode.object
let res = await updateDetails(url, body, Post)
setBusiProfie(_ => res->BusinessProfileMapper.businessProfileTypeMapper)
showToast(~message=`Details updated`, ~toastType=ToastState.ToastSuccess)
setScreenState(_ => PageLoaderWrapper.Success)
setAllowEdit(_ => false)
fetchBusinessProfiles()->ignore
} catch {
| _ => {
setScreenState(_ => PageLoaderWrapper.Success)
showToast(~message=`Failed to updated`, ~toastType=ToastState.ToastError)
}
}
Nullable.null
}
<ReactFinalForm.Form
key="auth"
initialValues={busiProfieDetails->parseBussinessProfileJson->JSON.Encode.object}
subscription=ReactFinalForm.subscribeToValues
onSubmit
render={({handleSubmit}) => {
<form onSubmit={handleSubmit} className="flex flex-col gap-8 h-full w-full py-6 px-4">
<WebHookAuthenticationHeaders setAllowEdit allowEdit />
<DesktopRow>
<div className="flex justify-end w-full gap-2">
<RenderIf condition=allowEdit>
<SubmitButton
text="Update"
buttonType=Button.Primary
buttonSize=Button.Medium
disabledParamter={!allowEdit}
/>
<Button
buttonType=Button.Secondary
onClick={_ =>
RescriptReactRouter.push(
GlobalVars.appendDashboardPath(~url="/payment-settings"),
)}
text="Cancel"
/>
</RenderIf>
</div>
</DesktopRow>
// <FormValuesSpy />
</form>
}}
/>
}
}
module WebHook = {
@react.component
let make = () => {
open FormRenderer
<div className="ml-4 mt-4">
<FieldRenderer
field={DeveloperUtils.webhookUrl}
labelClass="!text-fs-15 !text-grey-700 font-semibold"
fieldWrapperClass="max-w-xl"
/>
</div>
}
}
module ReturnUrl = {
@react.component
let make = () => {
open FormRenderer
<>
<DesktopRow>
<FieldRenderer
field={DeveloperUtils.returnUrl}
errorClass={HSwitchUtils.errorClass}
labelClass="!text-fs-15 !text-grey-700 font-semibold"
fieldWrapperClass="max-w-xl"
/>
</DesktopRow>
</>
}
}
type options = {
name: string,
key: string,
}
module CollectDetails = {
@react.component
let make = (~title, ~subTitle, ~options: array<options>) => {
open LogicUtils
open FormRenderer
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let valuesDict = formState.values->getDictFromJsonObject
let initValue = options->Array.some(option => valuesDict->getBool(option.key, false))
let (isSelected, setIsSelected) = React.useState(_ => initValue)
let form = ReactFinalForm.useForm()
let onClick = key => {
options->Array.forEach(option => {
form.change(option.key, (option.key === key)->JSON.Encode.bool)
})
}
let p2RegularTextStyle = `${HSwitchUtils.getTextClass((P1, Medium))} text-grey-700 opacity-50`
React.useEffect(() => {
if isSelected {
let value = options->Array.some(option => valuesDict->getBool(option.key, false))
if !value {
switch options->Array.get(0) {
| Some(name) => form.change(name.key, true->JSON.Encode.bool)
| _ => ()
}
}
} else {
options->Array.forEach(option => form.change(option.key, false->JSON.Encode.bool))
}
None
}, [isSelected])
<DesktopRow>
<div className="w-full border-t border-gray-200 pt-8">
<div className="flex justify-between items-center">
<div className="flex-1 ">
<p className="font-semibold text-fs-15"> {title->React.string} </p>
<p className="font-medium text-fs-14 text-black opacity-50 pt-2">
{subTitle->React.string}
</p>
</div>
<BoolInput.BaseComponent
isSelected
setIsSelected={_ => setIsSelected(val => !val)}
isDisabled=false
boolCustomClass="rounded-lg"
/>
</div>
<RenderIf condition={isSelected}>
<div className="mt-4">
{options
->Array.mapWithIndex((option, index) =>
<div
key={index->Int.toString}
className="flex gap-2 mb-3 items-center cursor-pointer"
onClick={_ => onClick(option.key)}>
<RadioIcon
isSelected={valuesDict->getBool(option.key, false)} fill="text-green-700"
/>
<div className=p2RegularTextStyle>
{option.name->LogicUtils.snakeToTitle->React.string}
</div>
</div>
)
->React.array}
</div>
</RenderIf>
</div>
</DesktopRow>
}
}
module AutoRetries = {
@react.component
let make = (~setCheckMaxAutoRetry) => {
open FormRenderer
open DeveloperUtils
open LogicUtils
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let form = ReactFinalForm.useForm()
let errorClass = "text-sm leading-4 font-medium text-start ml-1 mt-2"
let isAutoRetryEnabled =
formState.values->getDictFromJsonObject->getBool("is_auto_retries_enabled", false)
if !isAutoRetryEnabled {
form.change("max_auto_retries_enabled", JSON.Encode.null->Identity.genericTypeToJson)
setCheckMaxAutoRetry(_ => false)
} else {
setCheckMaxAutoRetry(_ => true)
}
<>
<DesktopRow>
<FieldRenderer
labelClass="!text-fs-15 !text-grey-700 font-semibold"
fieldWrapperClass="w-full flex justify-between items-center border-t border-gray-200 pt-8 "
field={makeFieldInfo(
~name="is_auto_retries_enabled",
~label="Auto Retries",
~customInput=InputFields.boolInput(~isDisabled=false, ~boolCustomClass="rounded-lg"),
)}
/>
</DesktopRow>
<RenderIf condition={isAutoRetryEnabled}>
<FieldRenderer
field={maxAutoRetries}
errorClass
labelClass="!text-fs-15 !text-grey-700 font-semibold"
fieldWrapperClass="max-w-xl mx-4"
/>
</RenderIf>
</>
}
}
module ClickToPaySection = {
@react.component
let make = () => {
open FormRenderer
open LogicUtils
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
let formState: ReactFinalForm.formState = ReactFinalForm.useFormState(
ReactFinalForm.useFormSubscription(["values"])->Nullable.make,
)
let connectorListAtom = ConnectorInterface.useConnectorArrayMapper(
~interface=ConnectorInterface.connectorInterfaceV1,
~retainInList=AuthenticationProcessor,
)
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let connectorView = userHasAccess(~groupAccess=ConnectorsView) === Access
let isClickToPayEnabled =
formState.values->getDictFromJsonObject->getBool("is_click_to_pay_enabled", false)
let dropDownOptions = connectorListAtom->Array.map((item): SelectBox.dropdownOption => {
{
label: `${item.connector_label} - ${item.merchant_connector_id}`,
value: item.merchant_connector_id,
}
})
<RenderIf condition={featureFlagDetails.clickToPay && connectorView}>
<DesktopRow>
<FieldRenderer
labelClass="!text-fs-15 !text-grey-700 font-semibold"
fieldWrapperClass="w-full flex justify-between items-center border-t border-gray-200 pt-8 "
field={makeFieldInfo(
~name="is_click_to_pay_enabled",
~label="Click to Pay",
~customInput=InputFields.boolInput(~isDisabled=false, ~boolCustomClass="rounded-lg"),
~description="Click to Pay is a secure, seamless digital payment solution that lets customers checkout quickly using saved cards without entering details",
~toolTipPosition=Right,
)}
/>
</DesktopRow>
<RenderIf condition={isClickToPayEnabled}>
<DesktopRow>
<FormRenderer.FieldRenderer
labelClass="!text-fs-15 !text-grey-700 font-semibold"
field={FormRenderer.makeFieldInfo(
~label="Click to Pay - Connector ID",
~name="authentication_product_ids.click_to_pay",
~placeholder="",
~customInput=InputFields.selectInput(
~options=dropDownOptions,
~buttonText="Select Click to Pay - Connector ID",
~deselectDisable=true,
),
)}
/>
</DesktopRow>
</RenderIf>
</RenderIf>
}
}
@react.component
let make = (~webhookOnly=false, ~showFormOnly=false, ~profileId="") => {
open DeveloperUtils
open APIUtils
open HSwitchUtils
open MerchantAccountUtils
open HSwitchSettingTypes
open FormRenderer
let getURL = useGetURL()
let url = RescriptReactRouter.useUrl()
let id = HSwitchUtils.getConnectorIDFromUrl(url.path->List.toArray, profileId)
let businessProfileDetails = BusinessProfileHook.useGetBusinessProflile(id)
let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom
let showToast = ToastState.useShowToast()
let updateDetails = useUpdateMethod()
let (busiProfieDetails, setBusiProfie) = React.useState(_ => businessProfileDetails)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (checkMaxAutoRetry, setCheckMaxAutoRetry) = React.useState(_ => true)
let bgClass = webhookOnly ? "" : "bg-white dark:bg-jp-gray-lightgray_background"
let fetchBusinessProfiles = BusinessProfileHook.useFetchBusinessProfiles()
React.useEffect(() => {
if businessProfileDetails.profile_id->LogicUtils.isNonEmptyString {
setBusiProfie(_ => businessProfileDetails)
setScreenState(_ => Success)
}
None
}, [businessProfileDetails.profile_id])
let threedsConnectorList = ConnectorInterface.useConnectorArrayMapper(
~interface=ConnectorInterface.connectorInterfaceV1,
~retainInList=AuthenticationProcessor,
)
let isBusinessProfileHasThreeds = threedsConnectorList->Array.some(item => item.profile_id == id)
let fieldsToValidate = () => {
let defaultFieldsToValidate =
[WebhookUrl, ReturnUrl]->Array.filter(urlField => urlField === WebhookUrl || !webhookOnly)
if checkMaxAutoRetry {
defaultFieldsToValidate->Array.push(MaxAutoRetries)
}
defaultFieldsToValidate
}
let onSubmit = async (values, _) => {
try {
open LogicUtils
setScreenState(_ => PageLoaderWrapper.Loading)
let valuesDict = values->getDictFromJsonObject
let url = getURL(~entityName=V1(BUSINESS_PROFILE), ~methodType=Post, ~id=Some(id))
let body = valuesDict->JSON.Encode.object->getBusinessProfilePayload->JSON.Encode.object
let res = await updateDetails(url, body, Post)
setBusiProfie(_ => res->BusinessProfileMapper.businessProfileTypeMapper)
showToast(~message=`Details updated`, ~toastType=ToastState.ToastSuccess)
setScreenState(_ => PageLoaderWrapper.Success)
fetchBusinessProfiles()->ignore
} catch {
| _ => {
setScreenState(_ => PageLoaderWrapper.Success)
showToast(~message=`Failed to updated`, ~toastType=ToastState.ToastError)
}
}
Nullable.null
}
<PageLoaderWrapper screenState>
<div className={`${showFormOnly ? "" : "py-4 md:py-10"} h-full flex flex-col`}>
<RenderIf condition={!showFormOnly}>
<BreadCrumbNavigation
path=[
{
title: "Payment Settings",
link: "/payment-settings",
},
]
currentPageTitle={busiProfieDetails.profile_name}
cursorStyle="cursor-pointer"
/>
</RenderIf>
<div className={`${showFormOnly ? "" : "mt-4"} flex flex-col gap-6`}>
<div
className={`w-full ${showFormOnly
? ""
: "border border-jp-gray-500 rounded-md dark:border-jp-gray-960"} ${bgClass} `}>
<ReactFinalForm.Form
key="merchantAccount"
initialValues={busiProfieDetails->parseBussinessProfileJson->JSON.Encode.object}
subscription=ReactFinalForm.subscribeToValues
validate={values => {
MerchantAccountUtils.validateMerchantAccountForm(
~values,
~fieldsToValidate={fieldsToValidate()},
~isLiveMode=featureFlagDetails.isLiveMode,
)
}}
onSubmit
render={({handleSubmit}) => {
<form
onSubmit={handleSubmit}
className={`${showFormOnly
? ""
: "px-2 py-4"} flex flex-col gap-7 overflow-hidden`}>
<div className="flex items-center">
<InfoViewForWebhooks
heading="Profile Name" subHeading=busiProfieDetails.profile_name
/>
<InfoViewForWebhooks
heading="Profile ID" subHeading=busiProfieDetails.profile_id isCopy=true
/>
</div>
<div className="flex items-center">
<InfoViewForWebhooks
heading="Merchant ID" subHeading={busiProfieDetails.merchant_id}
/>
<InfoViewForWebhooks
heading="Payment Response Hash Key"
subHeading={busiProfieDetails.payment_response_hash_key->Option.getOr("NA")}
isCopy=true
/>
</div>
<CollectDetails
title={"Collect billing details from wallets"}
subTitle={"Enable automatic collection of billing information when customers connect their wallets"}
options=[
{
name: "only if required by connector",
key: "collect_billing_details_from_wallet_connector",
},
{
name: "always",
key: "always_collect_billing_details_from_wallet_connector",
},
]
/>
<CollectDetails
title={"Collect shipping details from wallets"}
subTitle={"Enable automatic collection of shipping information when customers connect their wallets"}
options=[
{
name: "only if required by connector",
key: "collect_shipping_details_from_wallet_connector",
},
{
name: "always",
key: "always_collect_shipping_details_from_wallet_connector",
},
]
/>
<DesktopRow>
<FieldRenderer
labelClass="!text-fs-15 !text-grey-700 font-semibold"
fieldWrapperClass="w-full flex justify-between items-center border-t border-gray-200 pt-8 "
field={makeFieldInfo(
~name="is_connector_agnostic_mit_enabled",
~label="Connector Agnostic",
~customInput=InputFields.boolInput(
~isDisabled=false,
~boolCustomClass="rounded-lg ",
),
)}
/>
</DesktopRow>
<DesktopRow>
<FieldRenderer
labelClass="!text-fs-15 !text-grey-700 font-semibold"
fieldWrapperClass="w-full flex justify-between items-center border-t border-gray-200 pt-8 "
field={makeFieldInfo(
~name="force_3ds_challenge",
~label="Force 3DS Challenge",
~customInput=InputFields.boolInput(
~isDisabled=false,
~boolCustomClass="rounded-lg ",
),
)}
/>
</DesktopRow>
<RenderIf condition={featureFlagDetails.debitRouting}>
<DesktopRow>
<FieldRenderer
labelClass="!text-fs-15 !text-grey-700 font-semibold"
fieldWrapperClass="w-full flex justify-between items-center border-t border-gray-200 pt-8 "
field={makeFieldInfo(
~name="is_debit_routing_enabled",
~label="Debit Routing",
~customInput=InputFields.boolInput(
~isDisabled=false,
~boolCustomClass="rounded-lg ",
),
)}
/>
</DesktopRow>
</RenderIf>
<ClickToPaySection />
<AutoRetries setCheckMaxAutoRetry />
<RenderIf condition={isBusinessProfileHasThreeds}>
<DesktopRow wrapperClass="pt-4 flex !flex-col gap-4">
<FieldRenderer
field={threedsConnectorList
->Array.map(item => item.connector_name)
->authenticationConnectors}
errorClass
labelClass="!text-fs-15 !text-grey-700 font-semibold "
fieldWrapperClass="max-w-xl"
/>
<FieldRenderer
field={threeDsRequestorUrl}
errorClass
labelClass="!text-fs-15 !text-grey-700 font-semibold"
fieldWrapperClass="max-w-xl"
/>
<FieldRenderer
field={threeDsRequestoApprUrl}
errorClass
labelClass="!text-fs-15 !text-grey-700 font-semibold"
fieldWrapperClass="max-w-xl"
/>
</DesktopRow>
</RenderIf>
<ReturnUrl />
<WebHook />
<DesktopRow>
<div className="flex justify-end w-full gap-2">
<SubmitButton
text="Update" buttonType=Button.Primary buttonSize=Button.Medium
/>
<Button
buttonType=Button.Secondary
onClick={_ =>
RescriptReactRouter.push(
GlobalVars.appendDashboardPath(~url="/payment-settings"),
)}
text="Cancel"
/>
</div>
</DesktopRow>
<FormValuesSpy />
</form>
}}
/>
</div>
<div className={` py-4 md:py-10 h-full flex flex-col `}>
<div
className={`border border-jp-gray-500 rounded-md dark:border-jp-gray-960"} ${bgClass}`}>
<WebHookSection busiProfieDetails setBusiProfie setScreenState profileId />
</div>
</div>
<div className="py-4 md:py-10 h-full flex flex-col">
<div
className={`border border-jp-gray-500 rounded-md dark:border-jp-gray-960"} ${bgClass}`}>
<PaymentSettingsMetadata busiProfieDetails setBusiProfie setScreenState profileId />
</div>
</div>
</div>
</div>
</PageLoaderWrapper>
}
| 6,291 | 9,810 |
hyperswitch-control-center | src/screens/Developer/Webhooks/WebhooksDetails.res | .res | module TabDetails = {
@react.component
let make = (~activeTab: WebhooksTypes.tabs, ~selectedEvent: WebhooksTypes.attemptType) => {
open LogicUtils
let keyTextClass = HSwitchUtils.getTextClass((P1, Medium))
let valTextClass = HSwitchUtils.getTextClass((P1, Regular))
let requestBody = selectedEvent.request.body
let responseBody = selectedEvent.response.body
let requestHeaders = selectedEvent.request.headers
let responseHeaders = selectedEvent.response.headers
let statusCode = selectedEvent.response.statusCode
let errorMessage = selectedEvent.response.errorMessage
let noResponse = statusCode === 404
let headerKeyValUI = header => {
let item = index => {
let val = header->getValueFromArray(index, "")
if val->String.length > 30 {
<HelperComponents.EllipsisText displayValue=val endValue=20 expandText=false />
} else {
val->React.string
}
}
<div className="flex flex-col lg:flex-row">
<span className={keyTextClass}> {item(0)} </span>
<span className="hidden lg:inline-block"> {":"->React.string} </span>
<span className="lg:whitespace-pre"> {" "->React.string} </span>
<span className={valTextClass}> {item(1)} </span>
</div>
}
let headersValues = headers => {
let headersArray = headers->getArrayFromJson([])
let headerDataItem = headersArray->Array.map(header => {
header
->getStrArryFromJson
->headerKeyValUI
})
<div> {headerDataItem->React.array} </div>
}
<div className="h-[44rem] !max-h-[72rem] overflow-scroll mt-4">
{switch activeTab {
| Request =>
<div className="flex flex-col w-[98%] pl-3">
<div> {"Headers"->React.string} </div>
<div className="m-3 p-3 border border-grey-300 rounded-md max-w-[90%]">
{headersValues(requestHeaders)}
</div>
<div className="flex justify-between">
<div className=" mt-2"> {"Body"->React.string} </div>
<HelperComponents.CopyTextCustomComp
displayValue=Some("") copyValue={Some(requestBody)} customTextCss="text-nowrap"
/>
</div>
<RenderIf condition={requestBody->isNonEmptyString}>
<PrettyPrintJson jsonToDisplay=requestBody />
</RenderIf>
<RenderIf condition={requestBody->isEmptyString}>
<div> {"No Request"->React.string} </div>
</RenderIf>
</div>
| Response =>
<div className="pl-4">
<div className="flex items-center gap-2 mb-2">
<div> {"Status Code: "->React.string} </div>
<TableUtils.LabelCell
labelColor={WebhooksUtils.labelColor(statusCode)} text={statusCode->Int.toString}
/>
</div>
<div> {"Headers"->React.string} </div>
<div className="m-3 p-3 border border-grey-300 rounded-md max-w-[40rem]">
{headersValues(responseHeaders)}
</div>
<RenderIf condition={errorMessage->Option.isSome}>
<div className="flex gap-2">
<div> {"Error Message:"->React.string} </div>
<div> {errorMessage->Option.getOr("")->React.string} </div>
</div>
</RenderIf>
<div className="flex justify-between mr-2">
<div className="mt-2"> {"Body"->React.string} </div>
<RenderIf condition={!noResponse}>
<HelperComponents.CopyTextCustomComp
displayValue=Some("") copyValue={Some(responseBody)} customTextCss="text-nowrap"
/>
</RenderIf>
</div>
<RenderIf condition={responseBody->isEmptyString}>
<div> {"No Response"->React.string} </div>
</RenderIf>
<RenderIf condition={responseBody->isNonEmptyString}>
<RenderIf condition={noResponse}>
<div className="text-center"> {"No Response"->React.string} </div>
</RenderIf>
<RenderIf condition={!noResponse}>
<PrettyPrintJson jsonToDisplay=responseBody />
</RenderIf>
</RenderIf>
</div>
}}
</div>
}
}
@react.component
let make = (~id) => {
open APIUtils
open LogicUtils
open WebhooksUtils
let getURL = useGetURL()
let fetchDetails = useGetMethod()
let updateDetails = useUpdateMethod()
let showToast = ToastState.useShowToast()
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (data, setData) = React.useState(_ => JSON.Encode.null)
let (offset, setOffset) = React.useState(_ => 0)
let (selectedEvent, setSelectedEvent) = React.useState(_ =>
Dict.make()->itemToObjectMapperAttempts
)
let fetchWebhooksEventDetails = async () => {
try {
setScreenState(_ => Loading)
let url = getURL(~entityName=V1(WEBHOOK_EVENTS_ATTEMPTS), ~methodType=Get, ~id=Some(id))
let response = await fetchDetails(url)
let item =
response
->getArrayDataFromJson(itemToObjectMapperAttempts)
->Array.find(field => {
field.eventId == id
})
switch item {
| Some(item) => setSelectedEvent(_ => item)
| None => ()
}
setData(_ => response)
setScreenState(_ => Success)
} catch {
| Exn.Error(e) =>
switch Exn.message(e) {
| Some(message) => {
let errorCode = message->safeParse->getDictFromJsonObject->getString("code", "")
let errorMessage = message->safeParse->getDictFromJsonObject->getString("message", "")
switch errorCode->CommonAuthUtils.errorSubCodeMapper {
| HE_02 => showToast(~message=errorMessage, ~toastType=ToastError)
| _ =>
showToast(~message="Failed to fetch data", ~toastType=ToastError)
setScreenState(_ => PageLoaderWrapper.Error("Failed to fetch data"))
}
}
| None => {
showToast(~message="Failed to fetch data", ~toastType=ToastError)
setScreenState(_ => PageLoaderWrapper.Error("Failed to fetch data"))
}
}
}
}
let retryWebhook = async () => {
try {
let url = getURL(
~entityName=V1(WEBHOOKS_EVENTS_RETRY),
~methodType=Post,
~id=Some(selectedEvent.eventId),
)
let _ = await updateDetails(url, Dict.make()->JSON.Encode.object, Post)
fetchWebhooksEventDetails()->ignore
} catch {
| Exn.Error(_) => showToast(~message="Failed to retry webhook", ~toastType=ToastError)
}
}
let handleClickItem = (val: WebhooksTypes.attemptTable) => {
let item =
data
->getArrayDataFromJson(itemToObjectMapperAttempts)
->Array.find(field => {
field.eventId == val.eventId
})
->Option.getOr(Dict.make()->itemToObjectMapperAttempts)
setSelectedEvent(_ => item)
}
React.useEffect(() => {
fetchWebhooksEventDetails()->ignore
None
}, [])
let attemptTableArr = data->getArrayDataFromJson(itemToObjectMapperAttemptsTable)
let table =
<LoadedTable
title=" "
hideTitle=true
actualData={attemptTableArr->Array.map(Nullable.make)}
totalResults={attemptTableArr->Array.length}
resultsPerPage=20
entity={WebhooksDetailsTableEntity.webhooksDetailsEntity()}
onEntityClick={val => handleClickItem(val)}
offset
setOffset
currrentFetchCount={attemptTableArr->Array.map(Nullable.make)->Array.length}
collapseTableRow=false
showSerialNumber=true
highlightSelectedRow=true
/>
let tabList: array<Tabs.tab> = [
{
title: "Request",
renderContent: () => <TabDetails activeTab=Request selectedEvent />,
},
{
title: "Response",
renderContent: () => <TabDetails activeTab=Response selectedEvent />,
},
]
let details =
<Tabs
tabs=tabList
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"
textStyle="text-blue-600"
selectTabBottomBorderColor="bg-blue-600"
/>
<div className="flex flex-col gap-4">
<PageUtils.PageHeading title="Webhooks" subTitle="" />
<BreadCrumbNavigation
path=[{title: "Webhooks", link: "/webhooks"}]
currentPageTitle="Webhooks home"
cursorStyle="cursor-pointer"
/>
<PageLoaderWrapper screenState>
<div className="grid grid-cols-2 ">
<div> {table} </div>
<div className="flex flex-col border border-grey-300 bg-white">
<RenderIf condition={!(selectedEvent.deliveryAttempt->LogicUtils.isEmptyString)}>
<div className="flex justify-between items-center mx-5 mt-5">
<TableUtils.LabelCell
labelColor=LabelGreen text={selectedEvent.deliveryAttempt->LogicUtils.snakeToTitle}
/>
<Button
text="Retry Webhook" onClick={_ => retryWebhook()->ignore} buttonSize=XSmall
/>
</div>
</RenderIf>
<div> {details} </div>
</div>
</div>
</PageLoaderWrapper>
</div>
}
| 2,211 | 9,811 |
hyperswitch-control-center | src/screens/Developer/Webhooks/Webhooks.res | .res | @react.component
let make = () => {
open APIUtils
open WebhooksUtils
let getURL = useGetURL()
let updateDetails = useUpdateMethod()
let {userHasAccess} = GroupACLHooks.useUserGroupACLHook()
let (webhooksData, setWebhooksData) = React.useState(_ => [])
let defaultValue: LoadedTable.pageDetails = {offset: 0, resultsPerPage: 20}
let pageDetailDict = Recoil.useRecoilValueFromAtom(LoadedTable.table_pageDetails)
let pageDetail = pageDetailDict->Dict.get("Webhooks")->Option.getOr(defaultValue)
let (totalCount, setTotalCount) = React.useState(_ => 0)
let (offset, setOffset) = React.useState(_ => pageDetail.offset)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let {updateExistingKeys, filterValueJson, reset, filterValue} =
FilterContext.filterContext->React.useContext
let businessProfileValues = HyperswitchAtom.businessProfilesAtom->Recoil.useRecoilValueFromAtom
let (searchText, setSearchText) = React.useState(_ => "")
let webhookURL = switch businessProfileValues->Array.get(0) {
| Some(val) => val.webhook_details.webhook_url->Option.getOr("")
| None => ""
}
let isWebhookUrlConfigured = webhookURL->LogicUtils.isNonEmptyString
let message = isWebhookUrlConfigured
? "No data found, try searching with different filters or try refreshing using the button below"
: "Webhook UI is not configured please do it from payment settings"
let refreshPage = () => {
reset()
}
let customUI =
<NoDataFound message renderType=Painting>
<RenderIf condition={isWebhookUrlConfigured}>
<div className="m-2">
<Button text="Refresh" buttonType=Primary onClick={_ => refreshPage()} />
</div>
</RenderIf>
</NoDataFound>
React.useEffect(() => {
if filterValueJson->Dict.keysToArray->Array.length != 0 {
setOffset(_ => 0)
}
None
}, [filterValue])
let initialDisplayFilters =
[]->Array.filter((item: EntityType.initialFilters<'t>) => item.localFilter->Option.isSome)
let setInitialFilters = HSwitchRemoteFilter.useSetInitialFilters(
~updateExistingKeys,
~startTimeFilterKey,
~endTimeFilterKey,
~compareToStartTimeKey="",
~compareToEndTimeKey="",
~comparisonKey="",
~range=30,
~origin="orders",
(),
)
let setData = (~total, ~data) => {
let arr = Array.make(~length=offset, Dict.make())
if total <= offset {
setOffset(_ => 0)
}
if total > 0 {
let webhookDictArr = data->Belt.Array.keepMap(JSON.Decode.object)
let webhookData =
arr
->Array.concat(webhookDictArr)
->Array.map(itemToObjectMapper)
let list = webhookData
setTotalCount(_ => total)
setWebhooksData(_ => list)
setScreenState(_ => PageLoaderWrapper.Success)
} else {
setScreenState(_ => PageLoaderWrapper.Custom)
}
}
let fetchWebhooks = async () => {
open LogicUtils
setScreenState(_ => PageLoaderWrapper.Loading)
try {
let defaultDate = HSwitchRemoteFilter.getDateFilteredObject(~range=30)
let start_time = filterValueJson->getString(startTimeFilterKey, defaultDate.start_time)
let end_time = filterValueJson->getString(endTimeFilterKey, defaultDate.end_time)
let payload = Dict.make()
if searchText->isNonEmptyString {
payload->Dict.set("object_id", searchText->JSON.Encode.string)
} else {
payload->Dict.set("limit", 50->Int.toFloat->JSON.Encode.float)
payload->Dict.set("offset", offset->Int.toFloat->JSON.Encode.float)
payload->Dict.set("created_after", start_time->JSON.Encode.string)
payload->Dict.set("created_before", end_time->JSON.Encode.string)
}
let url = getURL(~entityName=V1(WEBHOOK_EVENTS), ~methodType=Post)
let response = await updateDetails(url, payload->JSON.Encode.object, Post)
let totalCount = response->getDictFromJsonObject->getInt("total_count", 0)
let events = response->getDictFromJsonObject->getArrayFromDict("events", [])
if !isWebhookUrlConfigured || events->Array.length <= 0 {
setScreenState(_ => Custom)
} else {
setData(~total=totalCount, ~data=events)
setScreenState(_ => Success)
}
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Error("Failed to fetch"))
}
}
React.useEffect(() => {
fetchWebhooks()->ignore
if filterValueJson->Dict.keysToArray->Array.length < 1 {
setInitialFilters()
}
None
}, (filterValueJson, offset, searchText))
let filtersUI = React.useMemo(() => {
<Filter
key="0"
title="Webhooks"
defaultFilters={""->JSON.Encode.string}
fixedFilters={initialFixedFilter()}
requiredSearchFieldsList=[]
localFilters={initialDisplayFilters}
localOptions=[]
remoteOptions=[]
remoteFilters=[]
autoApply=false
submitInputOnEnter=true
defaultFilterKeys=[startTimeFilterKey, endTimeFilterKey]
updateUrlWith={updateExistingKeys}
customLeftView={<HSwitchRemoteFilter.SearchBarFilter
placeholder="Search for object ID" setSearchVal=setSearchText searchVal=searchText
/>}
clearFilters={() => reset()}
/>
}, [])
<>
<PageUtils.PageHeading title="Webhooks" subTitle="" />
{filtersUI}
<PageLoaderWrapper screenState customUI>
<LoadedTable
title=" "
actualData={webhooksData->Array.map(Nullable.make)}
totalResults=totalCount
resultsPerPage=20
entity={WebhooksTableEntity.webhooksEntity(
`webhooks`,
~authorization=userHasAccess(~groupAccess=AccountManage),
)}
hideTitle=true
offset
setOffset
currrentFetchCount={webhooksData->Array.map(Nullable.make)->Array.length}
collapseTableRow=false
showSerialNumber=true
/>
</PageLoaderWrapper>
</>
}
| 1,430 | 9,812 |
hyperswitch-control-center | src/screens/Developer/Webhooks/WebhooksUtils.res | .res | open WebhooksTypes
open LogicUtils
let tabkeys: array<tabs> = [Request, Response]
let labelColor = (statusCode): TableUtils.labelColor => {
switch statusCode {
| 200 => LabelGreen
| 400
| 404
| 422 =>
LabelRed
| 500 => LabelGray
| _ => LabelGreen
}
}
let itemToObjectMapper: dict<JSON.t> => webhookObject = dict => {
eventId: dict->getString("event_id", ""),
eventClass: dict->getString("event_class", ""),
eventType: dict->getString("event_type", ""),
merchantId: dict->getString("merchant_id", ""),
profileId: dict->getString("profile_id", ""),
objectId: dict->getString("object_id", ""),
isDeliverySuccessful: dict->getBool("is_delivery_successful", false),
initialAttemptId: dict->getString("initial_attempt_id", ""),
created: dict->getString("created", ""),
}
let requestMapper = json => {
body: json->getDictFromJsonObject->getString("body", ""),
headers: json->getDictFromJsonObject->getJsonObjectFromDict("headers"),
}
let responseMapper = json => {
body: json->getDictFromJsonObject->getString("body", ""),
headers: json->getDictFromJsonObject->getJsonObjectFromDict("headers"),
errorMessage: json->getDictFromJsonObject->getString("error_message", "")->getNonEmptyString,
statusCode: json->getDictFromJsonObject->getInt("status_code", 0),
}
let itemToObjectMapperAttempts: dict<JSON.t> => attemptType = dict => {
eventId: dict->getString("event_id", ""),
eventClass: dict->getString("event_class", ""),
eventType: dict->getString("event_type", ""),
merchantId: dict->getString("merchant_id", ""),
profileId: dict->getString("profile_id", ""),
objectId: dict->getString("object_id", ""),
isDeliverySuccessful: dict->getBool("is_delivery_successful", false),
initialAttemptId: dict->getString("initial_attempt_id", ""),
created: dict->getString("created", ""),
deliveryAttempt: dict->getString("delivery_attempt", ""),
request: dict->getJsonObjectFromDict("request")->requestMapper,
response: dict->getJsonObjectFromDict("response")->responseMapper,
}
let itemToObjectMapperAttemptsTable: dict<JSON.t> => attemptTable = dict => {
isDeliverySuccessful: dict->getBool("is_delivery_successful", false),
deliveryAttempt: dict->getString("delivery_attempt", ""),
eventId: dict->getString("event_id", ""),
created: dict->getString("created", ""),
}
let (startTimeFilterKey, endTimeFilterKey) = ("start_time", "end_time")
let getAllowedDateRange = {
let endDate = Date.now()->Js.Date.fromFloat->DateTimeUtils.toUtc->DayJs.getDayJsForJsDate //->Date.toISOString->JSON.Encode.string
let startDate = endDate.subtract(90, "day")
let dateObject: Calendar.dateObj = {
startDate: startDate.toString(),
endDate: endDate.toString(),
}
dateObject
}
let initialFixedFilter = () => [
(
{
localFilter: None,
field: FormRenderer.makeMultiInputFieldInfo(
~label="",
~comboCustomInput=InputFields.filterDateRangeField(
~startKey=startTimeFilterKey,
~endKey=endTimeFilterKey,
~format="YYYY-MM-DDTHH:mm:ss[Z]",
~showTime=false,
~disablePastDates={false},
~disableFutureDates={true},
~predefinedDays=[
Hour(0.5),
Hour(1.0),
Hour(2.0),
Today,
Yesterday,
Day(2.0),
Day(7.0),
Day(30.0),
ThisMonth,
LastMonth,
],
~numMonths=2,
~disableApply=false,
~dateRangeLimit=90,
~allowedDateRange=getAllowedDateRange,
),
~inputFields=[],
~isRequired=false,
),
}: EntityType.initialFilters<'t>
),
]
| 906 | 9,813 |
hyperswitch-control-center | src/screens/Developer/Webhooks/WebhooksTypes.res | .res | type tabs = Request | Response
type webhookObject = {
eventId: string,
merchantId: string,
profileId: string,
objectId: string,
eventType: string,
eventClass: string,
isDeliverySuccessful: bool,
initialAttemptId: string,
created: string,
}
type webhook = {
events: array<webhookObject>,
total_count: int,
}
type request = {
body: string,
headers: JSON.t,
}
type response = {
body: string,
errorMessage: option<string>,
headers: JSON.t,
statusCode: int,
}
type attemptType = {
eventId: string,
merchantId: string,
profileId: string,
objectId: string,
eventType: string,
eventClass: string,
isDeliverySuccessful: bool,
initialAttemptId: string,
created: string,
request: request,
response: response,
deliveryAttempt: string,
}
type attempts = array<attemptType>
type attemptTable = {
isDeliverySuccessful: bool,
deliveryAttempt: string,
eventId: string,
created: string,
}
| 239 | 9,814 |
hyperswitch-control-center | src/screens/Developer/Webhooks/WebhooksTableEntity.res | .res | open WebhooksTypes
type colType =
| EventId
| EventClass
| EventType
| MerchantId
| ProfileId
| ObjectId
| IsDeliverySuccessful
| InitialAttemptId
| Created
let defaultColumns = [
EventId,
ObjectId,
ProfileId,
EventClass,
EventType,
IsDeliverySuccessful,
Created,
]
let getHeading = colType => {
switch colType {
| EventId => Table.makeHeaderInfo(~key="event_id", ~title="Event Id")
| EventClass => Table.makeHeaderInfo(~key="event_class", ~title="Event Class")
| EventType => Table.makeHeaderInfo(~key="event_type", ~title="Event Type")
| MerchantId => Table.makeHeaderInfo(~key="merchant_id", ~title="Merchant Id")
| ProfileId => Table.makeHeaderInfo(~key="profile_id", ~title="Profile Id")
| ObjectId => Table.makeHeaderInfo(~key="object_id", ~title="Object Id")
| IsDeliverySuccessful =>
Table.makeHeaderInfo(~key="is_delivery_successful", ~title="Delivery Status")
| InitialAttemptId => Table.makeHeaderInfo(~key="initial_attempt_id", ~title="Initial Attempt Id")
| Created => Table.makeHeaderInfo(~key="created", ~title="Created")
}
}
let getCell = (webhook: webhookObject, colType): Table.cell => {
switch colType {
| EventId => DisplayCopyCell(webhook.eventId)
| EventClass => Text(webhook.eventClass)
| EventType => Text(webhook.eventType)
| MerchantId => Text(webhook.merchantId)
| ProfileId => Text(webhook.profileId)
| ObjectId => DisplayCopyCell(webhook.objectId)
| IsDeliverySuccessful =>
Text(webhook.isDeliverySuccessful->LogicUtils.getStringFromBool->LogicUtils.capitalizeString)
| InitialAttemptId => DisplayCopyCell(webhook.initialAttemptId)
| Created => Date(webhook.created)
}
}
let getPreviouslyConnectedList: JSON.t => array<webhookObject> = json => {
LogicUtils.getArrayDataFromJson(json, WebhooksUtils.itemToObjectMapper)
}
let webhooksEntity = (path: string, ~authorization: CommonAuthTypes.authorization) => {
EntityType.makeEntity(
~uri=``,
~getObjects=getPreviouslyConnectedList,
~defaultColumns,
~getHeading,
~getCell,
~dataKey="",
~getShowLink={
webhook =>
GroupAccessUtils.linkForGetShowLinkViaAccess(
~url=GlobalVars.appendDashboardPath(~url=`/${path}/${webhook.initialAttemptId}`),
~authorization,
)
},
)
}
| 585 | 9,815 |
hyperswitch-control-center | src/screens/Developer/Webhooks/WebhooksDetailsTableEntity.res | .res | open WebhooksTypes
type colType =
| IsDeliverySuccessful
| DeliveryAttempt
| EventId
| Created
let defaultColumns = [IsDeliverySuccessful, DeliveryAttempt, Created]
let getHeading = colType => {
switch colType {
| IsDeliverySuccessful =>
Table.makeHeaderInfo(~key="is_delivery_successful", ~title="Delivery Status")
| DeliveryAttempt => Table.makeHeaderInfo(~key="delivery_attempt", ~title="Delivery Attempt")
| EventId => Table.makeHeaderInfo(~key="event_id", ~title="Event Id")
| Created => Table.makeHeaderInfo(~key="created", ~title="Created")
}
}
let getCell = (webhook: attemptTable, colType): Table.cell => {
switch colType {
| IsDeliverySuccessful =>
Text(webhook.isDeliverySuccessful->LogicUtils.getStringFromBool->LogicUtils.capitalizeString)
| DeliveryAttempt => Text(webhook.deliveryAttempt)
| EventId => DisplayCopyCell(webhook.eventId)
| Created => Date(webhook.created)
}
}
let getPreviouslyConnectedList: JSON.t => array<attemptTable> = json => {
LogicUtils.getArrayDataFromJson(json, WebhooksUtils.itemToObjectMapperAttemptsTable)
}
let webhooksDetailsEntity = () => {
EntityType.makeEntity(
~uri=``,
~getObjects=getPreviouslyConnectedList,
~defaultColumns,
~getHeading,
~getCell,
~dataKey="",
)
}
| 316 | 9,816 |
hyperswitch-control-center | src/screens/Developer/APIKeys/KeyManagement.res | .res | module ApiEditModal = {
open DeveloperUtils
open HSwitchUtils
open HSwitchSettingTypes
@react.component
let make = (
~setShowModal,
~getAPIKeyDetails: unit => promise<unit>,
~initialValues,
~showModal,
~action=Create,
~keyId=?,
) => {
let getURL = APIUtils.useGetURL()
let (apiKey, setApiKey) = React.useState(_ => "")
let (showCustomDate, setShowCustomDate) = React.useState(_ => false)
let (modalState, setModalState) = React.useState(_ => action)
let showToast = ToastState.useShowToast()
let updateDetails = APIUtils.useUpdateMethod()
let setShowCustomDate = val => {
setShowCustomDate(_ => val)
}
React.useEffect(() => {
setShowCustomDate(false)
setModalState(_ => action)
None
}, [showModal])
let downloadKey = _ => {
DownloadUtils.downloadOld(~fileName=`apiKey.txt`, ~content=apiKey)
}
let primaryBtnText = switch action {
| Update => "Update"
| _ => "Create"
}
let modalheader = switch action {
| Update => "Update API Key"
| _ => "Create API Key"
}
let onSubmit = async (values, _) => {
try {
let valuesDict = values->LogicUtils.getDictFromJsonObject
let body = Dict.make()
Dict.set(body, "name", valuesDict->LogicUtils.getString("name", "")->JSON.Encode.string)
let description = valuesDict->LogicUtils.getString("description", "")
Dict.set(body, "description", description->JSON.Encode.string)
let expirationDate = valuesDict->LogicUtils.getString("expiration_date", "")
let expriryValue = switch valuesDict
->LogicUtils.getString("expiration", "")
->getRecordTypeFromString {
| Custom => expirationDate
| _ => Never->getStringFromRecordType
}
Dict.set(body, "expiration", expriryValue->JSON.Encode.string)
setModalState(_ => Loading)
let url = switch action {
| Update => {
let key_id = keyId->Option.getOr("")
getURL(~entityName=V1(API_KEYS), ~methodType=Post, ~id=Some(key_id))
}
| _ => getURL(~entityName=V1(API_KEYS), ~methodType=Post)
}
let json = await updateDetails(url, body->JSON.Encode.object, Post)
let keyDict = json->LogicUtils.getDictFromJsonObject
setApiKey(_ => keyDict->LogicUtils.getString("api_key", ""))
switch action {
| Update => setShowModal(_ => false)
| _ => {
Clipboard.writeText(keyDict->LogicUtils.getString("api_key", ""))
setModalState(_ => Success)
}
}
let _ = getAPIKeyDetails()
} catch {
| Exn.Error(e) =>
switch Exn.message(e) {
| Some(_error) =>
showToast(~message="Api Key Generation Failed", ~toastType=ToastState.ToastError)
| None => ()
}
setModalState(_ => SettingApiModalError)
}
Nullable.null
}
let modalBody =
<div>
{switch modalState {
| Loading => <Loader />
| Update
| Create =>
<ReactFinalForm.Form
key="API-key"
initialValues={initialValues->JSON.Encode.object}
subscription=ReactFinalForm.subscribeToPristine
validate={values =>
validateAPIKeyForm(values, ["name", "expiration"], ~setShowCustomDate)}
onSubmit
render={({handleSubmit}) => {
<LabelVisibilityContext showLabel=false>
<form onSubmit={handleSubmit} className="flex flex-col gap-3 h-full w-full">
<FormRenderer.DesktopRow>
<TextFieldRow label={apiName.label} labelWidth="w-48" isRequired=false>
<FormRenderer.FieldRenderer
fieldWrapperClass="w-96" field=apiName errorClass
/>
</TextFieldRow>
<TextFieldRow label={apiDescription.label} labelWidth="w-48" isRequired=false>
<FormRenderer.FieldRenderer
fieldWrapperClass="w-96" field=apiDescription errorClass
/>
</TextFieldRow>
<TextFieldRow label={keyExpiry.label} labelWidth="w-48" isRequired=false>
<FormRenderer.FieldRenderer
fieldWrapperClass="w-96" field=keyExpiry errorClass
/>
</TextFieldRow>
{if showCustomDate {
<TextFieldRow
label={keyExpiryCustomDate.label} labelWidth="w-48" isRequired=false>
<FormRenderer.FieldRenderer
fieldWrapperClass="w-96" field=keyExpiryCustomDate errorClass
/>
</TextFieldRow>
} else {
React.null
}}
</FormRenderer.DesktopRow>
<FormRenderer.DesktopRow>
<div className="flex justify-end gap-5 mt-5 mb-1 -mr-2">
<Button
text="Cancel"
onClick={_ => setShowModal(_ => false)}
buttonType={Secondary}
buttonSize={Small}
/>
<FormRenderer.SubmitButton text=primaryBtnText buttonSize={Small} />
</div>
</FormRenderer.DesktopRow>
</form>
</LabelVisibilityContext>
}}
/>
| SettingApiModalError => <ErrorUI text=primaryBtnText />
| Success => <SuccessUI apiKey downloadFun=downloadKey />
}}
</div>
<Modal
showModal
modalHeading={modalheader}
setShowModal
closeOnOutsideClick=true
modalClass="w-full max-w-2xl m-auto !bg-white dark:!bg-jp-gray-lightgray_background">
modalBody
</Modal>
}
}
module ApiKeyAddBtn = {
open DeveloperUtils
@react.component
let make = (~getAPIKeyDetails) => {
let mixpanelEvent = MixpanelHook.useSendEvent()
let {userHasAccess, hasAnyGroupAccess} = GroupACLHooks.useUserGroupACLHook()
let (showModal, setShowModal) = React.useState(_ => false)
let initialValues = Dict.make()
initialValues->Dict.set("expiration", Never->getStringFromRecordType->JSON.Encode.string)
let isMobileView = MatchMedia.useMobileChecker()
<>
<ApiEditModal showModal setShowModal initialValues getAPIKeyDetails />
<ACLButton
text="Create New API Key"
leftIcon={CustomIcon(
<Icon
name="plus" size=12 className="jp-gray-900 fill-opacity-50 dark:jp-gray-text_darktheme"
/>,
)}
// TODO: Remove `MerchantDetailsManage` permission in future
authorization={hasAnyGroupAccess(
userHasAccess(~groupAccess=MerchantDetailsManage),
userHasAccess(~groupAccess=AccountManage),
)}
buttonType=Secondary
buttonSize={isMobileView ? XSmall : Small}
customTextSize={isMobileView ? "text-xs" : ""}
onClick={_ => {
mixpanelEvent(~eventName="create_new_api_key")
setShowModal(_ => true)
}}
/>
</>
}
}
module TableActionsCell = {
open DeveloperUtils
open HSwitchSettingTypes
@react.component
let make = (~keyId, ~getAPIKeyDetails: unit => promise<unit>, ~data: apiKey) => {
let getURL = APIUtils.useGetURL()
let showToast = ToastState.useShowToast()
let (showModal, setShowModal) = React.useState(_ => false)
let showPopUp = PopUpState.useShowPopUp()
let deleteDetails = APIUtils.useUpdateMethod()
let {userHasAccess, hasAnyGroupAccess} = GroupACLHooks.useUserGroupACLHook()
let showButtons = hasAnyGroupAccess(
userHasAccess(~groupAccess=MerchantDetailsManage),
userHasAccess(~groupAccess=AccountManage),
)
let deleteKey = async () => {
try {
let body = Dict.make()
Dict.set(body, "key_id", keyId->JSON.Encode.string)
Dict.set(body, "revoked", true->JSON.Encode.bool)
let deleteUrl = getURL(~entityName=V1(API_KEYS), ~methodType=Delete, ~id=Some(keyId))
(await deleteDetails(deleteUrl, body->JSON.Encode.object, Delete))->ignore
getAPIKeyDetails()->ignore
} catch {
| Exn.Error(e) =>
switch Exn.message(e) {
| Some(_error) =>
showToast(~message="Failed to delete API key", ~toastType=ToastState.ToastError)
| None => ()
}
}
}
let openPopUp = _ => {
showPopUp({
popUpType: (Warning, WithIcon),
heading: `Delete API Key`,
description: React.string(`Are you sure you want to DELETE the API Key?`),
handleConfirm: {
text: `Yes, delete it`,
onClick: _ => {
deleteKey()->ignore
},
},
handleCancel: {text: `No, don't delete`, onClick: _ => ()},
})
}
let initialValues = Dict.fromArray([
("name", data.name->JSON.Encode.string),
("description", data.description->JSON.Encode.string),
])
if data.expiration == Never {
initialValues->Dict.set("expiration", Never->getStringFromRecordType->JSON.Encode.string)
} else {
initialValues->Dict.set("expiration", Custom->getStringFromRecordType->JSON.Encode.string)
initialValues->Dict.set("expiration_date", data.expiration_date->JSON.Encode.string)
}
<div>
<ApiEditModal
showModal setShowModal initialValues={initialValues} getAPIKeyDetails keyId action={Update}
/>
<div className="invisible cursor-pointer group-hover:visible flex ">
<ACLDiv
showTooltip={showButtons == Access}
authorization={showButtons}
onClick={_ => {
setShowModal(_ => true)
}}>
<Icon
name="edit"
size=14
className="text-jp-gray-700 hover:text-jp-gray-900 dark:hover:text-white mr-4 mb-1"
/>
</ACLDiv>
<ACLDiv
authorization={showButtons}
showTooltip={showButtons == Access}
onClick={_ => {
openPopUp()
}}>
<Icon
name="delete"
size=14
className="text-jp-gray-700 hover:text-jp-gray-900 dark:hover:text-white mr-3 mb-1"
/>
</ACLDiv>
</div>
</div>
}
}
module ApiKeysTable = {
open DeveloperUtils
open HSwitchSettingTypes
@react.component
let make = () => {
let getURL = APIUtils.useGetURL()
let fetchDetails = APIUtils.useGetMethod()
let (offset, setOffset) = React.useState(_ => 0)
let (data, setData) = React.useState(_ => [])
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let getAPIKeyDetails = async () => {
try {
let apiKeyListUrl = getURL(~entityName=V1(API_KEYS), ~methodType=Get)
let apiKeys = await fetchDetails(apiKeyListUrl)
setData(_ => apiKeys->getItems)
setScreenState(_ => PageLoaderWrapper.Success)
} catch {
| Exn.Error(e) =>
switch Exn.message(e) {
| Some(msg) => setScreenState(_ => PageLoaderWrapper.Error(msg))
| None => setScreenState(_ => PageLoaderWrapper.Error("Error"))
}
}
}
React.useEffect(() => {
getAPIKeyDetails()->ignore
None
}, [])
let getCell = (item: apiKey, colType): Table.cell => {
let appendString = str => str->String.concat(String.repeat("*", 10))
switch colType {
| Name => Text(item.name)
| Description => Text(item.description)
| Prefix => Text(item.prefix->appendString)
| Created => Date(item.created)
| Expiration =>
if item.expiration == Never {
Text(item.expiration_date->LogicUtils.getFirstLetterCaps)
} else {
Date(item.expiration_date)
}
| CustomCell =>
Table.CustomCell(<TableActionsCell keyId={item.key_id} getAPIKeyDetails data=item />, "")
}
}
let visibleColumns = Recoil.useRecoilValueFromAtom(TableAtoms.apiDefaultCols)
let apiKeysTableEntity = EntityType.makeEntity(
~uri="",
~getObjects=getItems,
~defaultColumns,
~allColumns,
~getHeading,
~dataKey="data",
~getCell,
)
<PageLoaderWrapper screenState>
{<div className="relative mt-10 md:mt-0">
<h2
className="font-bold absolute top-2 md:top-6 left-0 text-xl text-black text-opacity-75 dark:text-white dark:text-opacity-75">
{"API Keys"->React.string}
</h2>
<LoadedTable
title="Keys"
hideTitle=true
resultsPerPage=7
visibleColumns
entity=apiKeysTableEntity
showSerialNumber=true
actualData={data->Array.map(Nullable.make)}
totalResults={data->Array.length}
offset
setOffset
currrentFetchCount={data->Array.length}
tableActions={<div className="mt-0 md:mt-5">
<ApiKeyAddBtn getAPIKeyDetails />
</div>}
/>
</div>}
</PageLoaderWrapper>
}
}
module KeysManagement = {
@react.component
let make = () => {
<div>
<PageUtils.PageHeading
title="Keys" subTitle="Manage API keys and credentials for integrated payment services"
/>
<ApiKeysTable />
<PublishableAndHashKeySection />
</div>
}
}
| 3,110 | 9,817 |
hyperswitch-control-center | src/screens/Developer/APIKeys/DeveloperUtils.res | .res | open HSwitchSettingTypes
let validateAPIKeyForm = (
values: JSON.t,
~setIsDisabled=_ => (),
keys: array<string>,
~setShowCustomDate,
) => {
let errors = Dict.make()
let valuesDict = values->LogicUtils.getDictFromJsonObject
keys->Array.forEach(key => {
let value = LogicUtils.getString(valuesDict, key, "")
if value->LogicUtils.isEmptyString {
switch key {
| "name" => Dict.set(errors, key, "Please enter name"->JSON.Encode.string)
| "description" => Dict.set(errors, key, "Please enter description"->JSON.Encode.string)
| "expiration" => Dict.set(errors, key, "Please select expiry"->JSON.Encode.string)
| _ => ()
}
} else if key == "expiration" && value->String.toLowerCase != "never" {
setShowCustomDate(true)
let date = LogicUtils.getString(valuesDict, "expiration_date", "")
if date->LogicUtils.isEmptyString {
Dict.set(errors, "expiration_date", "Please select expiry date"->JSON.Encode.string)
}
} else if key == "expiration" && value->String.toLowerCase == "never" {
setShowCustomDate(false)
} else if (
value->LogicUtils.isNonEmptyString &&
(key === "webhook_url" || key === "return_url") &&
!(value->String.includes("localhost")) &&
!RegExp.test(
%re(
"/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i"
),
value,
)
) {
Dict.set(errors, key, "Please Enter Valid URL"->JSON.Encode.string)
} else if (key === "webhook_url" || key === "return_url") && value->String.length <= 0 {
Dict.set(errors, key, "Please Enter Valid URL"->JSON.Encode.string)
}
})
errors == Dict.make() ? setIsDisabled(_ => false) : setIsDisabled(_ => true)
errors->JSON.Encode.object
}
type apiKeyExpiryType = Never | Custom
let getStringFromRecordType = value => {
switch value {
| Never => "never"
| Custom => "custom"
}
}
let getRecordTypeFromString = value => {
switch value->String.toLowerCase {
| "never" => Never
| _ => Custom
}
}
type apiKey = {
key_id: string,
name: string,
description: string,
prefix: string,
created: string,
expiration: apiKeyExpiryType,
expiration_date: string,
}
let itemToObjMapper = dict => {
open LogicUtils
{
key_id: getString(dict, "key_id", ""),
name: getString(dict, "name", ""),
description: getString(dict, "description", ""),
prefix: getString(dict, "prefix", ""),
created: getString(dict, "created", ""),
expiration: getString(dict, "expiration", "")->getRecordTypeFromString,
expiration_date: getString(dict, "expiration", ""),
}
}
let getHeading = colType => {
switch colType {
| Name => Table.makeHeaderInfo(~key="name", ~title="Name")
| Description => Table.makeHeaderInfo(~key="description", ~title="Description")
| Prefix => Table.makeHeaderInfo(~key="key", ~title="API Key Prefix")
| Created => Table.makeHeaderInfo(~key="created", ~title="Created")
| Expiration => Table.makeHeaderInfo(~key="expiration", ~title="Expiration")
| CustomCell => Table.makeHeaderInfo(~key="", ~title="")
}
}
let defaultColumns = [Prefix, Name, Description, Created, Expiration, CustomCell]
let allColumns = [Prefix, Name, Description, Created, Expiration, CustomCell]
let getItems: JSON.t => array<apiKey> = json => {
LogicUtils.getArrayDataFromJson(json, itemToObjMapper)
}
let apiName = FormRenderer.makeFieldInfo(
~label="Name",
~name="name",
~placeholder="Name",
~customInput=InputFields.textInput(),
~isRequired=true,
)
let apiDescription = FormRenderer.makeFieldInfo(
~label="Description",
~name="description",
~placeholder="Description",
~customInput=InputFields.textInput(),
~isRequired=true,
)
let makeOptions: array<string> => array<SelectBox.dropdownOption> = options => {
options->Array.map(str => {
let option: SelectBox.dropdownOption = {label: str->LogicUtils.snakeToTitle, value: str}
option
})
}
let keyExpiry = FormRenderer.makeFieldInfo(
~label="Expiration",
~name="expiration",
~customInput=InputFields.selectInput(
~options=["never", "custom"]->makeOptions,
~buttonText="Select Option",
),
)
let keyExpiryCustomDate = FormRenderer.makeFieldInfo(
~label="",
~name="expiration_date",
~customInput=InputFields.singleDatePickerInput(
~disablePastDates=true,
~format="YYYY-MM-DDTHH:mm:ss.SSS[Z]",
),
)
let webhookUrl = FormRenderer.makeFieldInfo(
~label="Webhook URL",
~name="webhook_url",
~placeholder="Enter Webhook URL",
~customInput=InputFields.textInput(~autoComplete="off"),
~isRequired=false,
)
let returnUrl = FormRenderer.makeFieldInfo(
~label="Return URL",
~name="return_url",
~placeholder="Enter Return URL",
~customInput=InputFields.textInput(~autoComplete="off"),
~isRequired=false,
)
let authenticationConnectors = connectorList =>
FormRenderer.makeFieldInfo(
~label="Authentication Connectors",
~name="authentication_connectors",
~customInput=InputFields.multiSelectInput(
~options=connectorList->SelectBox.makeOptions,
~buttonText="Select Field",
~showSelectionAsChips=false,
~customButtonStyle=`!rounded-md`,
~fixedDropDownDirection=TopRight,
),
~isRequired=false,
)
let threeDsRequestorUrl = FormRenderer.makeFieldInfo(
~label="3DS Requestor URL",
~name="three_ds_requestor_url",
~placeholder="Enter 3DS Requestor URL",
~customInput=InputFields.textInput(~autoComplete="off"),
~isRequired=false,
)
let threeDsRequestoApprUrl = FormRenderer.makeFieldInfo(
~label="3DS Requestor App URL",
~name="three_ds_requestor_app_url",
~placeholder="Enter 3DS Requestor App URL",
~customInput=InputFields.textInput(~autoComplete="off"),
~isRequired=false,
)
let maxAutoRetries = FormRenderer.makeFieldInfo(
~label="Max Auto Retries",
~name="max_auto_retries_enabled",
~placeholder="Enter number of max auto retries",
~customInput=InputFields.numericTextInput(),
~isRequired=true,
)
module ErrorUI = {
@react.component
let make = (~text) => {
<div className="flex p-5">
<img className="w-12 h-12 my-auto border-gray-100" src={`/icons/error.svg`} alt="warning" />
<div className="text-jp-gray-900">
<div
className="font-bold ml-4 text-xl px-2 dark:text-jp-gray-text_darktheme dark:text-opacity-75">
{React.string(`API ${text} Failed`)}
</div>
<div
className="whitespace-pre-line flex flex-col gap-1 p-2 ml-4 text-fs-13 dark:text-jp-gray-text_darktheme dark:text-opacity-50">
{`Unable to ${text} a API key. Please try again later.`->React.string}
</div>
</div>
</div>
}
}
module SuccessUI = {
@react.component
let make = (~downloadFun, ~apiKey) => {
<div>
<div className="flex p-5">
<Icon className="align-middle fill-blue-600 self-center" size=40 name="info-circle" />
<div className="text-jp-gray-900 ml-4">
<div
className="font-bold text-xl px-2 dark:text-jp-gray-text_darktheme dark:text-opacity-75">
{React.string("Download the API Key")}
</div>
<div className="bg-gray-100 p-3 m-2">
<HelperComponents.CopyTextCustomComp
displayValue={Some(apiKey)}
copyValue={Some(apiKey)}
customTextCss="break-all text-sm font-semibold text-jp-gray-800 text-opacity-75"
customParentClass="flex items-center gap-5"
/>
</div>
<HSwitchUtils.AlertBanner
bannerType=Info
bannerText="Please note down the API key for your future use as you won't be able to view it later."
/>
</div>
</div>
<div className="flex justify-end gap-5 mt-5 mb-1 mr-1">
<Button
leftIcon={CustomIcon(<Icon name="download" size=17 className="ml-3 mr-2" />)}
text="Download the key"
onClick={_ => {
downloadFun()
}}
buttonType={Primary}
buttonSize={Small}
/>
</div>
</div>
}
}
| 2,356 | 9,818 |
hyperswitch-control-center | src/screens/Developer/APIKeys/PublishableAndHashKeySection.res | .res | @react.component
let make = () => {
let getURL = APIUtils.useGetURL()
let fetchDetails = APIUtils.useGetMethod()
let (merchantInfo, setMerchantInfo) = React.useState(() =>
JSON.Encode.null->MerchantAccountDetailsMapper.getMerchantDetails
)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let getMerchantDetails = async () => {
setScreenState(_ => PageLoaderWrapper.Loading)
try {
let accountUrl = getURL(~entityName=V1(MERCHANT_ACCOUNT), ~methodType=Get)
let merchantDetails = await fetchDetails(accountUrl)
let merchantInfo = merchantDetails->MerchantAccountDetailsMapper.getMerchantDetails
setMerchantInfo(_ => merchantInfo)
setScreenState(_ => PageLoaderWrapper.Success)
} catch {
| Exn.Error(e) =>
setScreenState(_ => PageLoaderWrapper.Error(Exn.message(e)->Option.getOr("Error")))
}
}
React.useEffect(() => {
getMerchantDetails()->ignore
None
}, [])
let paymentResponsHashKey = merchantInfo.payment_response_hash_key->Option.getOr("")
<PageLoaderWrapper screenState sectionHeight="h-40-vh">
<div className="mt-10">
<h2
className="font-bold text-xl pb-3 text-black text-opacity-75 dark:text-white dark:text-opacity-75">
{"Publishable Key and Payment Response Hash Key"->React.string}
</h2>
<div
className="px-2 py-4 border border-jp-gray-500 dark:border-jp-gray-960 bg-white dark:bg-jp-gray-lightgray_background rounded-md">
<FormRenderer.DesktopRow>
<div className="flex flex-col gap-1 md:gap-4 mb-4 md:mb-0">
<div className="flex">
<div className="break-all text-md text-base text-grey-700 font-semibold">
{"Publishable Key"->React.string}
</div>
<div className="ml-1 mt-0.5 h-5 w-5">
<ToolTip
tooltipWidthClass="w-fit"
description="Visit Dev Docs"
toolTipFor={<div
className="cursor-pointer"
onClick={_ => {
"https://hyperswitch.io/docs"->Window._open
}}>
<Icon name="open_arrow" size=12 />
</div>}
toolTipPosition=ToolTip.Top
/>
</div>
</div>
<HelperComponents.CopyTextCustomComp
displayValue={Some(merchantInfo.publishable_key)}
customTextCss="break-all text-sm truncate md:whitespace-normal font-semibold text-jp-gray-800 text-opacity-75"
customParentClass="flex items-center gap-5"
customIconCss="text-jp-gray-700"
/>
</div>
<RenderIf condition={paymentResponsHashKey->String.length !== 0}>
<div className="flex flex-col gap-2 md:gap-4">
<div className="break-all text-md text-base text-grey-700 font-semibold">
{"Payment Response Hash Key"->React.string}
</div>
<HelperComponents.CopyTextCustomComp
displayValue={Some(paymentResponsHashKey)}
customTextCss="break-all truncate md:whitespace-normal text-sm font-semibold text-jp-gray-800 text-opacity-75"
customParentClass="flex items-center gap-5"
customIconCss="text-jp-gray-700"
/>
</div>
</RenderIf>
</FormRenderer.DesktopRow>
</div>
</div>
</PageLoaderWrapper>
}
| 820 | 9,819 |
hyperswitch-control-center | src/screens/Settings/MerchantAccountUtils.res | .res | open HSwitchSettingTypes
let parseKey = api_key => {
api_key->String.slice(~start=0, ~end=6)->String.concat(String.repeat("*", 20))
}
let parseBussinessProfileJson = (profileRecord: profileEntity) => {
open LogicUtils
let {
merchant_id,
profile_id,
profile_name,
webhook_details,
return_url,
payment_response_hash_key,
authentication_connector_details,
collect_shipping_details_from_wallet_connector,
outgoing_webhook_custom_http_headers,
metadata,
is_connector_agnostic_mit_enabled,
collect_billing_details_from_wallet_connector,
always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector,
is_auto_retries_enabled,
max_auto_retries_enabled,
is_click_to_pay_enabled,
authentication_product_ids,
force_3ds_challenge,
is_debit_routing_enabled,
} = profileRecord
let profileInfo =
[
("merchant_id", merchant_id->JSON.Encode.string),
("profile_id", profile_id->JSON.Encode.string),
("profile_name", profile_name->JSON.Encode.string),
]->Dict.fromArray
profileInfo->setDictNull("return_url", return_url)
profileInfo->setOptionBool(
"collect_shipping_details_from_wallet_connector",
collect_shipping_details_from_wallet_connector,
)
profileInfo->setOptionBool(
"collect_billing_details_from_wallet_connector",
collect_billing_details_from_wallet_connector,
)
profileInfo->setOptionBool(
"always_collect_billing_details_from_wallet_connector",
always_collect_billing_details_from_wallet_connector,
)
profileInfo->setOptionBool(
"always_collect_shipping_details_from_wallet_connector",
always_collect_shipping_details_from_wallet_connector,
)
profileInfo->setOptionBool("is_auto_retries_enabled", is_auto_retries_enabled)
profileInfo->setOptionInt("max_auto_retries_enabled", max_auto_retries_enabled)
profileInfo->setDictNull("webhook_url", webhook_details.webhook_url)
profileInfo->setOptionString("webhook_version", webhook_details.webhook_version)
profileInfo->setOptionString("webhook_username", webhook_details.webhook_username)
profileInfo->setOptionString("webhook_password", webhook_details.webhook_password)
profileInfo->setOptionBool("payment_created_enabled", webhook_details.payment_created_enabled)
profileInfo->setOptionBool("payment_succeeded_enabled", webhook_details.payment_succeeded_enabled)
profileInfo->setOptionBool("payment_failed_enabled", webhook_details.payment_failed_enabled)
profileInfo->setOptionString("payment_response_hash_key", payment_response_hash_key)
profileInfo->setOptionArray(
"authentication_connectors",
authentication_connector_details.authentication_connectors,
)
profileInfo->setOptionString(
"three_ds_requestor_url",
authentication_connector_details.three_ds_requestor_url,
)
profileInfo->setOptionString(
"three_ds_requestor_app_url",
authentication_connector_details.three_ds_requestor_app_url,
)
profileInfo->setOptionBool("force_3ds_challenge", force_3ds_challenge)
profileInfo->setOptionBool("is_debit_routing_enabled", is_debit_routing_enabled)
profileInfo->setOptionBool("is_connector_agnostic_mit_enabled", is_connector_agnostic_mit_enabled)
profileInfo->setOptionBool("is_click_to_pay_enabled", is_click_to_pay_enabled)
profileInfo->setOptionJson("authentication_product_ids", authentication_product_ids)
profileInfo->setOptionDict(
"outgoing_webhook_custom_http_headers",
outgoing_webhook_custom_http_headers,
)
profileInfo->setOptionDict("metadata", metadata)
profileInfo
}
let parseMerchantJson = (merchantDict: merchantPayload) => {
open LogicUtils
let {merchant_details, merchant_name, publishable_key, primary_business_details} = merchantDict
let primary_business_details = primary_business_details->Array.map(detail => {
let {country, business} = detail
let props = [
("country", country->JSON.Encode.string),
("business", business->JSON.Encode.string),
]
props->Dict.fromArray->JSON.Encode.object
})
let merchantInfo =
[
("primary_business_details", primary_business_details->JSON.Encode.array),
("publishable_key", publishable_key->JSON.Encode.string),
("publishable_key_hide", publishable_key->parseKey->JSON.Encode.string),
]->Dict.fromArray
merchantInfo->setOptionString("merchant_name", merchant_name)
merchantInfo->setOptionString("about_business", merchant_details.about_business)
merchantInfo->setOptionString("primary_email", merchant_details.primary_email)
merchantInfo->setOptionString("primary_phone", merchant_details.primary_phone)
merchantInfo->setOptionString("primary_contact_person", merchant_details.primary_contact_person)
merchantInfo->setOptionString("website", merchant_details.website)
merchantInfo->setOptionString("secondary_phone", merchant_details.secondary_phone)
merchantInfo->setOptionString("secondary_email", merchant_details.secondary_email)
merchantInfo->setOptionString(
"secondary_contact_person",
merchant_details.secondary_contact_person,
)
merchantInfo->setOptionString("primary_phone", merchant_details.primary_phone)
merchantInfo->setOptionString("line1", merchant_details.address.line1)
merchantInfo->setOptionString("line2", merchant_details.address.line2)
merchantInfo->setOptionString("line3", merchant_details.address.line3)
merchantInfo->setOptionString("city", merchant_details.address.city)
merchantInfo->setOptionString("state", merchant_details.address.state)
merchantInfo->setOptionString("zip", merchant_details.address.zip)
merchantInfo
}
let getCustomHeadersPayload = (values: JSON.t) => {
open LogicUtils
let customHeaderDict = Dict.make()
let valuesDict = values->getDictFromJsonObject
let outGoingWebHookCustomHttpHeaders = Dict.make()
let formValues = valuesDict->getDictfromDict("outgoing_webhook_custom_http_headers")
let _ =
valuesDict
->getDictfromDict("outgoing_webhook_custom_http_headers")
->Dict.keysToArray
->Array.forEach(val => {
outGoingWebHookCustomHttpHeaders->setOptionString(
val,
formValues->getString(val, "")->getNonEmptyString,
)
})
let _ =
valuesDict
->getDictfromDict("outgoing_webhook_custom_http_headers")
->Dict.keysToArray
->Array.forEach(val => {
outGoingWebHookCustomHttpHeaders->setOptionString(
val,
formValues->getString(val, "")->getNonEmptyString,
)
})
customHeaderDict->setOptionDict(
"outgoing_webhook_custom_http_headers",
Some(outGoingWebHookCustomHttpHeaders),
)
customHeaderDict
}
let getMetdataKeyValuePayload = (values: JSON.t) => {
open LogicUtils
let customHeaderDict = Dict.make()
let valuesDict = values->getDictFromJsonObject
let customMetadataVal = Dict.make()
let formValues = valuesDict->getDictfromDict("metadata")
let _ =
valuesDict
->getDictfromDict("metadata")
->Dict.keysToArray
->Array.forEach(val => {
customMetadataVal->setOptionString(val, formValues->getString(val, "")->getNonEmptyString)
})
let _ =
valuesDict
->getDictfromDict("metadata")
->Dict.keysToArray
->Array.forEach(val => {
customMetadataVal->setOptionString(val, formValues->getString(val, "")->getNonEmptyString)
})
customHeaderDict->setOptionDict("metadata", Some(customMetadataVal))
customHeaderDict
}
let getBusinessProfilePayload = (values: JSON.t) => {
open LogicUtils
let valuesDict = values->getDictFromJsonObject
let webhookSettingsValue = Dict.make()
webhookSettingsValue->setOptionString(
"webhook_version",
valuesDict->getOptionString("webhook_version"),
)
webhookSettingsValue->setOptionString(
"webhook_username",
valuesDict->getOptionString("webhook_username"),
)
webhookSettingsValue->setOptionString(
"webhook_password",
valuesDict->getOptionString("webhook_password"),
)
webhookSettingsValue->setDictNull(
"webhook_url",
valuesDict->getString("webhook_url", "")->getNonEmptyString,
)
webhookSettingsValue->setOptionBool(
"payment_created_enabled",
valuesDict->getOptionBool("payment_created_enabled"),
)
webhookSettingsValue->setOptionBool(
"payment_succeeded_enabled",
valuesDict->getOptionBool("payment_succeeded_enabled"),
)
webhookSettingsValue->setOptionBool(
"payment_failed_enabled",
valuesDict->getOptionBool("payment_failed_enabled"),
)
let authenticationConnectorDetails = Dict.make()
authenticationConnectorDetails->setOptionArray(
"authentication_connectors",
valuesDict->getArrayFromDict("authentication_connectors", [])->getNonEmptyArray,
)
authenticationConnectorDetails->setOptionString(
"three_ds_requestor_url",
valuesDict->getString("three_ds_requestor_url", "")->getNonEmptyString,
)
authenticationConnectorDetails->setOptionString(
"three_ds_requestor_app_url",
valuesDict->getString("three_ds_requestor_app_url", "")->getNonEmptyString,
)
let profileDetailsDict = Dict.make()
profileDetailsDict->setDictNull(
"return_url",
valuesDict->getString("return_url", "")->getNonEmptyString,
)
profileDetailsDict->setOptionBool(
"collect_shipping_details_from_wallet_connector",
valuesDict->getOptionBool("collect_shipping_details_from_wallet_connector"),
)
profileDetailsDict->setOptionBool(
"always_collect_shipping_details_from_wallet_connector",
valuesDict->getOptionBool("always_collect_shipping_details_from_wallet_connector"),
)
profileDetailsDict->setOptionBool(
"collect_billing_details_from_wallet_connector",
valuesDict->getOptionBool("collect_billing_details_from_wallet_connector"),
)
profileDetailsDict->setOptionBool(
"always_collect_billing_details_from_wallet_connector",
valuesDict->getOptionBool("always_collect_billing_details_from_wallet_connector"),
)
profileDetailsDict->setOptionBool(
"is_auto_retries_enabled",
valuesDict->getOptionBool("is_auto_retries_enabled"),
)
profileDetailsDict->setOptionInt(
"max_auto_retries_enabled",
valuesDict->getOptionInt("max_auto_retries_enabled"),
)
profileDetailsDict->setOptionBool(
"is_connector_agnostic_mit_enabled",
valuesDict->getOptionBool("is_connector_agnostic_mit_enabled"),
)
profileDetailsDict->setOptionBool(
"force_3ds_challenge",
valuesDict->getOptionBool("force_3ds_challenge"),
)
profileDetailsDict->setOptionBool(
"is_debit_routing_enabled",
valuesDict->getOptionBool("is_debit_routing_enabled"),
)
profileDetailsDict->setOptionDict(
"webhook_details",
!(webhookSettingsValue->isEmptyDict) ? Some(webhookSettingsValue) : None,
)
profileDetailsDict->setOptionDict(
"authentication_connector_details",
!(authenticationConnectorDetails->isEmptyDict) ? Some(authenticationConnectorDetails) : None,
)
profileDetailsDict->setOptionBool(
"is_click_to_pay_enabled",
valuesDict->getOptionBool("is_click_to_pay_enabled"),
)
let authenticationProductIds = valuesDict->getJsonObjectFromDict("authentication_product_ids")
if !(authenticationProductIds->getDictFromJsonObject->isEmptyDict) {
profileDetailsDict->Dict.set("authentication_product_ids", authenticationProductIds)
}
profileDetailsDict
}
let getSettingsPayload = (values: JSON.t, merchantId) => {
open LogicUtils
let valuesDict = values->getDictFromJsonObject
let addressDetailsValue = Dict.make()
addressDetailsValue->setOptionString("line1", valuesDict->getOptionString("line1"))
addressDetailsValue->setOptionString("line2", valuesDict->getOptionString("line2"))
addressDetailsValue->setOptionString("line3", valuesDict->getOptionString("line3"))
addressDetailsValue->setOptionString("city", valuesDict->getOptionString("city"))
addressDetailsValue->setOptionString("state", valuesDict->getOptionString("state"))
addressDetailsValue->setOptionString("zip", valuesDict->getOptionString("zip"))
let merchantDetailsValue = Dict.make()
merchantDetailsValue->setOptionString(
"primary_contact_person",
valuesDict->getOptionString("primary_contact_person"),
)
let primaryEmail = valuesDict->getOptionString("primary_email")
if primaryEmail->Option.getOr("")->isNonEmptyString {
merchantDetailsValue->setOptionString("primary_email", primaryEmail)
}
merchantDetailsValue->setOptionString(
"primary_phone",
valuesDict->getOptionString("primary_phone"),
)
merchantDetailsValue->setOptionString(
"secondary_contact_person",
valuesDict->getOptionString("secondary_contact_person"),
)
let secondaryEmail = valuesDict->getOptionString("secondary_email")
if secondaryEmail->Option.getOr("")->isNonEmptyString {
merchantDetailsValue->setOptionString(
"secondary_email",
valuesDict->getOptionString("secondary_email"),
)
}
merchantDetailsValue->setOptionString(
"secondary_phone",
valuesDict->getOptionString("secondary_phone"),
)
merchantDetailsValue->setOptionString("website", valuesDict->getOptionString("website"))
merchantDetailsValue->setOptionString(
"about_business",
valuesDict->getOptionString("about_business"),
)
merchantDetailsValue->setOptionString(
"about_business",
valuesDict->getOptionString("about_business"),
)
!(addressDetailsValue->isEmptyDict)
? merchantDetailsValue->Dict.set("address", addressDetailsValue->JSON.Encode.object)
: ()
let primary_business_details =
valuesDict
->LogicUtils.getArrayFromDict("primary_business_details", [])
->Array.map(detail => {
let detailDict = detail->LogicUtils.getDictFromJsonObject
let detailDict =
[
("business", detailDict->getString("business", "")->JSON.Encode.string),
("country", detailDict->getString("country", "")->JSON.Encode.string),
]->Dict.fromArray
detailDict->JSON.Encode.object
})
let settingsPayload = Dict.fromArray([
("merchant_id", merchantId->JSON.Encode.string),
("locker_id", "m0010"->JSON.Encode.string),
])
settingsPayload->setOptionDict(
"merchant_details",
!(merchantDetailsValue->isEmptyDict) ? Some(merchantDetailsValue) : None,
)
settingsPayload->setOptionString("merchant_name", valuesDict->getOptionString("merchant_name"))
settingsPayload->setOptionArray(
"primary_business_details",
primary_business_details->getNonEmptyArray,
)
settingsPayload->JSON.Encode.object
}
let validationFieldsMapper = key => {
switch key {
| PrimaryEmail => "primary_email"
| SecondaryEmail => "secondary_email"
| PrimaryPhone => "primary_phone"
| SecondaryPhone => "secondary_phone"
| Website => "website"
| WebhookUrl => "webhook_url"
| ReturnUrl => "return_url"
| AuthenticationConnectors(_) => "authentication_connectors"
| ThreeDsRequestorUrl => "three_ds_requestor_url"
| UnknownValidateFields(key) => key
| MaxAutoRetries => "max_auto_retries_enabled"
| ThreeDsRequestorAppUrl => "three_ds_requestor_app_url"
}
}
let checkValueChange = (~initialDict, ~valuesDict) => {
open LogicUtils
let initialKeys = Dict.keysToArray(initialDict)
let updatedKeys = Dict.keysToArray(valuesDict)
let key =
initialDict
->Dict.keysToArray
->Array.find(key => {
switch key {
| "collect_shipping_details_from_wallet_connector" => {
let initialValue = initialDict->LogicUtils.getBool(key, false)
let updatedValue = valuesDict->LogicUtils.getBool(key, false)
initialValue !== updatedValue
}
| "outgoing_webhook_custom_http_headers" => {
let initialDictLength =
initialDict
->getDictfromDict("outgoing_webhook_custom_http_headers")
->Dict.keysToArray
let updatedDictLength =
valuesDict
->getDictfromDict("outgoing_webhook_custom_http_headers")
->Dict.keysToArray
initialDictLength != updatedDictLength
}
| "metadata" => {
let initialDictLength =
initialDict
->getDictfromDict("metadata")
->Dict.keysToArray
let updatedDictLength =
valuesDict
->getDictfromDict("metadata")
->Dict.keysToArray
initialDictLength != updatedDictLength
}
| _ => {
let initialValue = initialDict->getString(key, "")
let updatedValue = valuesDict->getString(key, "")
initialValue !== updatedValue
}
}
})
key->Option.isSome || updatedKeys > initialKeys
}
let validateEmptyArray = (key, errors, arrayValue) => {
switch key {
| AuthenticationConnectors(_) =>
if arrayValue->Array.length === 0 {
Dict.set(
errors,
key->validationFieldsMapper,
"Please select authentication connector"->JSON.Encode.string,
)
}
| _ => ()
}
}
let validateCustom = (key, errors, value, isLiveMode) => {
switch key {
| PrimaryEmail | SecondaryEmail =>
if value->HSwitchUtils.isValidEmail {
Dict.set(
errors,
key->validationFieldsMapper,
"Please enter valid email id"->JSON.Encode.string,
)
}
| PrimaryPhone | SecondaryPhone =>
if !RegExp.test(%re("/^(?:\+\d{1,15}?[.-])??\d{3}?[.-]?\d{3}[.-]?\d{3,9}$/"), value) {
Dict.set(
errors,
key->validationFieldsMapper,
"Please enter valid phone number"->JSON.Encode.string,
)
}
| Website | WebhookUrl | ReturnUrl | ThreeDsRequestorUrl => {
let regexUrl = isLiveMode
? RegExp.test(%re("/^https:\/\//i"), value) || value->String.includes("localhost")
: RegExp.test(%re("/^(http|https):\/\//i"), value)
if !regexUrl {
Dict.set(errors, key->validationFieldsMapper, "Please Enter Valid URL"->JSON.Encode.string)
}
}
| ThreeDsRequestorAppUrl =>
if value->LogicUtils.isEmptyString {
Dict.set(errors, key->validationFieldsMapper, "URL cannot be empty"->JSON.Encode.string)
} else {
let httpUrlValid = isLiveMode
? RegExp.test(%re("/^https:\/\//i"), value) || value->String.includes("localhost")
: RegExp.test(%re("/^(http|https):\/\//i"), value)
let deepLinkValid = RegExp.test(%re("/^[a-zA-Z][a-zA-Z0-9]*:\/\//i"), value)
if !(httpUrlValid || deepLinkValid) {
Dict.set(
errors,
key->validationFieldsMapper,
"Please enter a valid URL or Mobile Deeplink"->JSON.Encode.string,
)
}
}
| _ => ()
}
}
let validateMerchantAccountForm = (
~values: JSON.t,
~fieldsToValidate: array<validationFields>,
~isLiveMode,
) => {
// Need to refactor
open LogicUtils
let errors = Dict.make()
let valuesDict = values->getDictFromJsonObject
fieldsToValidate->Array.forEach(key => {
switch key {
| MaxAutoRetries => {
let value = getInt(valuesDict, key->validationFieldsMapper, 0)
if !RegExp.test(%re("/^(?:[1-5])$/"), value->Int.toString) {
Dict.set(
errors,
key->validationFieldsMapper,
"Please enter integer value from 1 to 5"->JSON.Encode.string,
)
}
}
| _ => {
let value = getString(valuesDict, key->validationFieldsMapper, "")->getNonEmptyString
switch value {
| Some(str) => key->validateCustom(errors, str, isLiveMode)
| _ => ()
}
}
}
})
let threedsArray = getArrayFromDict(valuesDict, "authentication_connectors", [])->getNonEmptyArray
let threedsUrl = getString(valuesDict, "three_ds_requestor_url", "")->getNonEmptyString
let threedsAppUrl = getString(valuesDict, "three_ds_requestor_app_url", "")->getNonEmptyString
switch threedsArray {
| Some(valArr) => {
let url = getString(valuesDict, "three_ds_requestor_url", "")
AuthenticationConnectors(valArr)->validateEmptyArray(errors, valArr)
ThreeDsRequestorUrl->validateCustom(errors, url, isLiveMode)
}
| _ => ()
}
switch threedsUrl {
| Some(str) => {
let arr = getArrayFromDict(valuesDict, "authentication_connectors", [])
AuthenticationConnectors(arr)->validateEmptyArray(errors, arr)
ThreeDsRequestorUrl->validateCustom(errors, str, isLiveMode)
}
| _ => ()
}
switch threedsAppUrl {
| Some(str) => {
let arr = getArrayFromDict(valuesDict, "authentication_connectors", [])
AuthenticationConnectors(arr)->validateEmptyArray(errors, arr)
ThreeDsRequestorAppUrl->validateCustom(errors, str, isLiveMode)
}
| _ => ()
}
errors->JSON.Encode.object
}
let defaultValueForBusinessProfile = {
merchant_id: "",
profile_id: "",
profile_name: "",
return_url: None,
payment_response_hash_key: None,
webhook_details: {
webhook_version: None,
webhook_username: None,
webhook_password: None,
webhook_url: None,
payment_created_enabled: None,
payment_succeeded_enabled: None,
payment_failed_enabled: None,
},
authentication_connector_details: {
authentication_connectors: None,
three_ds_requestor_url: None,
three_ds_requestor_app_url: None,
},
collect_shipping_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
always_collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
metadata: None,
is_connector_agnostic_mit_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
force_3ds_challenge: None,
is_debit_routing_enabled: None,
}
let getValueFromBusinessProfile = businessProfileValue => {
businessProfileValue->Array.get(0)->Option.getOr(defaultValueForBusinessProfile)
}
let businessProfileNameDropDownOption = arrBusinessProfile =>
arrBusinessProfile->Array.map(ele => {
let obj: SelectBox.dropdownOption = {
label: {`${ele.profile_name} (${ele.profile_id})`},
value: ele.profile_id,
}
obj
})
| 5,115 | 9,820 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.