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/UserManagement/UserRevamp/InviteMember.res
.res
@react.component let make = (~isInviteUserFlow=true, ~setNewRoleSelected=_ => ()) => { open APIUtils open LogicUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let showToast = ToastState.useShowToast() let {email} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let (loaderForInviteUsers, setLoaderForInviteUsers) = React.useState(_ => false) let authId = HyperSwitchEntryUtils.getSessionData(~key="auth_id") let {userInfo: {orgId, merchantId, profileId, userEntity}} = React.useContext( UserInfoProvider.defaultContext, ) let invitationFormInitialValues = React.useMemo(() => { /* INFO: For user_entity the default values (Organisation , Merchant , Profile) will be Organization -> (Current orgId , All Merchants, All Profiles) Merchant -> (Current orgId , Current merchantId , All Profiles) Profile -> (Current orgId , Current merchantId , Current profileId) */ let initialvalue = [("org_value", orgId->JSON.Encode.string)] if userEntity == #Tenant { initialvalue->Array.pushMany([ ("merchant_value", merchantId->JSON.Encode.string), ("profile_value", profileId->JSON.Encode.string), ]) } else if userEntity == #Organization { initialvalue->Array.pushMany([ ("merchant_value", merchantId->JSON.Encode.string), ("profile_value", profileId->JSON.Encode.string), ]) } else if userEntity == #Merchant { initialvalue->Array.pushMany([ ("merchant_value", merchantId->JSON.Encode.string), ("profile_value", profileId->JSON.Encode.string), ]) } else if userEntity == #Profile { initialvalue->Array.pushMany([ ("merchant_value", merchantId->JSON.Encode.string), ("profile_value", profileId->JSON.Encode.string), ]) } initialvalue->getJsonFromArrayOfJson }, [userEntity]) let inviteListOfUsersWithInviteMultiple = async values => { let url = getURL( ~entityName=V1(USERS), ~userType=#INVITE_MULTIPLE, ~methodType=Post, ~queryParamerters=Some(`auth_id=${authId}`), ) if !email { setLoaderForInviteUsers(_ => true) } let valDict = values->getDictFromJsonObject let role = valDict->getString("role_id", "") let emailList = valDict->getStrArray("email_list") let body = emailList ->Array.map(ele => [ ("email", ele->String.toLowerCase->JSON.Encode.string), ("name", ele->getNameFromEmail->JSON.Encode.string), ("role_id", role->JSON.Encode.string), ]->getJsonFromArrayOfJson ) ->JSON.Encode.array let response = await updateDetails(url, body, Post) let decodedResponse = response->getArrayFromJson([]) if !email { let invitedUserData = decodedResponse ->Array.mapWithIndex((ele, index) => { let responseDict = ele->getDictFromJsonObject if ( responseDict->getOptionString("error")->Option.isNone && responseDict->getString("password", "")->String.length > 0 ) { let passwordFromResponse = responseDict->getString("password", "") [ ("email", emailList->getValueFromArray(index, "")->JSON.Encode.string), ("password", passwordFromResponse->JSON.Encode.string), ]->getJsonFromArrayOfJson } else { JSON.Encode.null } }) ->Array.filter(ele => ele !== JSON.Encode.null) setLoaderForInviteUsers(_ => false) if invitedUserData->Array.length > 0 { DownloadUtils.download( ~fileName=`invited-users.txt`, ~content=invitedUserData->JSON.Encode.array->JSON.stringifyWithIndent(3), ~fileType="application/json", ) } } let (message, toastType) = if ( decodedResponse->Array.every(ele => ele->getDictFromJsonObject->getOptionString("error")->Option.isSome ) ) { ( "Error sending emails or creating users. Please check if the user already exists and try again.", ToastState.ToastError, ) } else if ( decodedResponse->Array.some(ele => { let error = ele->getDictFromJsonObject->getOptionString("error") error->Option.isSome && error->Option.getExn->String.includes("account already exists") }) ) { ("Some users already exist. Please check the details and try again.", ToastState.ToastWarning) } else { ( email ? `Invite(s) sent successfully via Email` : `The user accounts have been successfully created. The file with their credentials has been downloaded.`, ToastState.ToastSuccess, ) } showToast(~message, ~toastType) RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/users")) Nullable.null } let onSubmit = (values, _) => { inviteListOfUsersWithInviteMultiple(values) } <div className="flex flex-col overflow-y-scroll gap-4 h-85-vh"> <PageUtils.PageHeading title="Invite New Users" /> <BreadCrumbNavigation path=[{title: "Team management", link: "/users"}] currentPageTitle="Invite new users" /> <Form formClass="h-4/5 bg-white relative overflow-y-scroll flex flex-col gap-10 border rounded-md" key="invite-user-management" initialValues={invitationFormInitialValues} validate={values => values->UserUtils.validateForm(~fieldsToValidate=["email_list", "role_id"])} onSubmit> <NewUserInvitationForm /> </Form> <RenderIf condition={!email}> <LoaderModal showModal={loaderForInviteUsers} setShowModal={setLoaderForInviteUsers} text="Inviting Users" /> </RenderIf> </div> }
1,337
9,521
hyperswitch-control-center
src/screens/UserManagement/UserRevamp/ListRolesTableEntity.res
.res
open LogicUtils type rolesTableTypes = { role_name: string, role_scope: string, groups: array<JSON.t>, entity_name: string, } type rolesColTypes = | RoleName | RoleScope | EntityType | RoleGroupAccess let defaultColumnsForRoles = [RoleName, EntityType, RoleGroupAccess] let itemToObjMapperForRoles = dict => { { role_name: getString(dict, "role_name", ""), role_scope: getString(dict, "role_scope", ""), groups: getArrayFromDict(dict, "groups", []), entity_name: getString(dict, "entity_type", ""), } } let getHeadingForRoles = (colType: rolesColTypes) => { switch colType { | RoleName => Table.makeHeaderInfo(~key="role_name", ~title="Role name", ~showSort=true) | RoleScope => Table.makeHeaderInfo(~key="role_scope", ~title="Role scope") | EntityType => Table.makeHeaderInfo(~key="entity_type", ~title="Entity Type") | RoleGroupAccess => Table.makeHeaderInfo(~key="groups", ~title="Module permissions") } } let getCellForRoles = (data: rolesTableTypes, colType: rolesColTypes): Table.cell => { switch colType { | RoleName => Text(data.role_name->LogicUtils.snakeToTitle) | RoleScope => Text(data.role_scope->LogicUtils.capitalizeString) | EntityType => Text(data.entity_name->LogicUtils.capitalizeString) | RoleGroupAccess => Table.CustomCell( <div> {data.groups ->LogicUtils.getStrArrayFromJsonArray ->Array.map(item => `${item->LogicUtils.snakeToTitle}`) ->Array.joinWith(", ") ->React.string} </div>, "", ) } } let getrolesData: JSON.t => array<rolesTableTypes> = json => { getArrayDataFromJson(json, itemToObjMapperForRoles) } let rolesEntity = EntityType.makeEntity( ~uri="", ~getObjects=getrolesData, ~defaultColumns=defaultColumnsForRoles, ~allColumns=defaultColumnsForRoles, ~getHeading=getHeadingForRoles, ~getCell=getCellForRoles, ~dataKey="", )
497
9,522
hyperswitch-control-center
src/screens/UserManagement/UserRevamp/UserUtils.res
.res
let getMerchantSelectBoxOption = ( ~label, ~value, ~dropdownList: array<OMPSwitchTypes.ompListTypes>, ~showAllSelection=false, ) => { let allOptions: SelectBox.dropdownOption = { label, value, customRowClass: "!border-b py-2", textColor: "font-semibold", } let orgOptions = dropdownList->Array.map((item): SelectBox.dropdownOption => {label: item.name, value: item.id}) if showAllSelection { [allOptions, ...orgOptions] } else { orgOptions } } let validateEmptyValue = (key, errors) => { switch key { | "emailList" => Dict.set(errors, "email", "Please enter Invite mails"->JSON.Encode.string) | "roleType" => Dict.set(errors, "roleType", "Please enter a role"->JSON.Encode.string) | _ => Dict.set(errors, key, `Please enter a ${key->LogicUtils.snakeToTitle}`->JSON.Encode.string) } } let validateForm = (values, ~fieldsToValidate: array<string>) => { let errors = Dict.make() open LogicUtils let valuesDict = values->getDictFromJsonObject fieldsToValidate->Array.forEach(key => { let value = valuesDict->getJsonObjectFromDict(key) switch value { | Array(listofemails) => if listofemails->Array.length === 0 { key->validateEmptyValue(errors) } else { listofemails->Array.forEach(ele => { if ele->JSON.Decode.string->Option.getOr("")->HSwitchUtils.isValidEmail { errors->Dict.set("email", "Please enter a valid email"->JSON.Encode.string) } }) if listofemails->Array.length > 10 { errors->Dict.set("Invite limit exceeded", "Max 10 at a time."->JSON.Encode.string) } () } | String(roleType) => if roleType->LogicUtils.isEmptyString { key->validateEmptyValue(errors) } | _ => key->validateEmptyValue(errors) } }) errors->JSON.Encode.object } let itemToObjMapperForGetRoleInfro: Dict.t<JSON.t> => UserManagementTypes.userModuleType = dict => { open LogicUtils { parentGroup: getString(dict, "name", ""), description: getString(dict, "description", ""), groups: getStrArrayFromDict(dict, "groups", []), } } let itemToObjMapperFordetailedRoleInfo: Dict.t< JSON.t, > => UserManagementTypes.detailedUserModuleType = dict => { open LogicUtils let sortedscopes = getStrArrayFromDict(dict, "scopes", [])->Array.toSorted((item, _) => switch item { | "read" => -1. | "write" => 1. | _ => 0. } ) { parentGroup: getString(dict, "name", ""), description: getString(dict, "description", ""), scopes: sortedscopes, } } let modulesWithUserAccess = ( roleInfo: array<UserManagementTypes.userModuleType>, userAccessGroup: array<UserManagementTypes.detailedUserModuleType>, ) => { open UserManagementTypes let modulesWithAccess = [] let modulesWithoutAccess = [] //array of groupnames accessible to the specific user role let accessGroupNames = userAccessGroup->Array.map(item => item.parentGroup) roleInfo->Array.forEach(item => { if accessGroupNames->Array.includes(item.parentGroup) { let accessGroup = userAccessGroup->Array.find(group => group.parentGroup == item.parentGroup) switch accessGroup { | Some(val) => { let manipulatedObject = { parentGroup: item.parentGroup, description: val.description, scopes: val.scopes, } modulesWithAccess->Array.push(manipulatedObject) } | None => () } } else { let manipulatedObject = { parentGroup: item.parentGroup, description: item.description, scopes: [], } modulesWithoutAccess->Array.push(manipulatedObject) } }) (modulesWithAccess, modulesWithoutAccess) } let getNameAndIdFromDict: (Dict.t<JSON.t>, string) => UserManagementTypes.orgObjectType = ( dict, default, ) => { open LogicUtils dict->isEmptyDict ? { name: default, value: default, id: None, } : { name: dict->getString("name", ""), value: dict->getString("id", ""), id: dict->getOptionString("id"), } } let itemToObjMapper: Dict.t<JSON.t> => UserManagementTypes.userDetailstype = dict => { open LogicUtils { roleId: dict->getString("role_id", ""), roleName: dict->getString("role_name", ""), org: dict->getDictfromDict("org")->getNameAndIdFromDict("all_orgs"), merchant: dict->getDictfromDict("merchant")->getNameAndIdFromDict("all_merchants"), profile: dict->getDictfromDict("profile")->getNameAndIdFromDict("all_profiles"), status: dict->getString("status", ""), entityType: dict->getString("entity_type", ""), } } let valueToType = json => json->LogicUtils.getArrayDataFromJson(itemToObjMapper) let groupByMerchants: array<UserManagementTypes.userDetailstype> => Dict.t< array<UserManagementTypes.userDetailstype>, > = typedValue => { let dict = Dict.make() typedValue->Array.forEach(item => { switch dict->Dict.get(item.merchant.value) { | Some(value) => dict->Dict.set(item.merchant.value, [item, ...value]) | None => dict->Dict.set(item.merchant.value, [item]) } }) dict } let getLabelForStatus = value => { switch value { | "InvitationSent" => ( UserManagementTypes.InviteSent, "text-orange-950 bg-orange-950 bg-opacity-20", ) | "Active" => (UserManagementTypes.Active, "text-green-700 bg-green-700 bg-opacity-20") | _ => (UserManagementTypes.None, "text-grey-700 opacity-50") } } let stringToVariantMapperForAccess = accessAvailable => { open UserManagementTypes switch accessAvailable { | "write" => Write | "read" | _ => Read } } let makeSelectBoxOptions = result => { open LogicUtils result ->getObjectArrayFromJson ->Array.map(objectvalue => { let value: SelectBox.dropdownOption = { label: objectvalue->getString("role_name", ""), value: objectvalue->getString("role_id", ""), } value }) } let getEntityType = valueDict => { /* INFO: For the values (Organisation , Merchant , Profile) in form (Some(org_id) , all merchants , all profiles) --> get roles for organisation (Some(org_id) , Some(merchant_id) , all profiles) --> get roles for merchants (Some(org_id) , Some(merchant_id) , Some(profile_id)) --> get roles for profiles */ open LogicUtils let orgValue = valueDict->getOptionString("org_value") let merchantValue = valueDict->getOptionString("merchant_value") let profileValue = valueDict->getOptionString("profile_value") switch (orgValue, merchantValue, profileValue) { | (Some(_orgId), Some("all_merchants"), Some("all_profiles")) => "organization" | (Some(_orgId), Some(_merchnatId), Some("all_profiles")) => "merchant" | (Some(_orgId), Some(_merchnatId), Some(_profileId)) => "profile" | _ => "" } } let stringToVariantForAllSelection = formStringValue => switch formStringValue { | "all_merchants" => Some(#All_Merchants) | "all_profiles" => Some(#All_Profiles) | _ => None } let getVersion = (product: ProductTypes.productTypes) => { switch product { | Orchestration | DynamicRouting | CostObservability => UserInfoTypes.V1 | _ => UserInfoTypes.V2 } }
1,861
9,523
hyperswitch-control-center
src/screens/UserManagement/UserRevamp/ListRoles.res
.res
@react.component let make = () => { open APIUtils open ListRolesTableEntity let getURL = useGetURL() let fetchDetails = useGetMethod() let (screenStateRoles, setScreenStateRoles) = React.useState(_ => PageLoaderWrapper.Loading) let (rolesAvailableData, setRolesAvailableData) = React.useState(_ => []) let (rolesOffset, setRolesOffset) = React.useState(_ => 0) let {checkUserEntity} = React.useContext(UserInfoProvider.defaultContext) let mixpanelEvent = MixpanelHook.useSendEvent() let {userHasAccess} = GroupACLHooks.useUserGroupACLHook() let ( userModuleEntity: UserManagementTypes.userModuleTypes, setUserModuleEntity, ) = React.useState(_ => #Default) let getRolesAvailable = async (userModuleEntity: UserManagementTypes.userModuleTypes) => { setScreenStateRoles(_ => PageLoaderWrapper.Loading) try { let userDataURL = getURL( ~entityName=V1(USER_MANAGEMENT), ~methodType=Get, ~userRoleTypes=ROLE_LIST, ~queryParamerters=userModuleEntity == #Default ? None : Some(`entity_type=${(userModuleEntity :> string)->String.toLowerCase}`), ) let res = await fetchDetails(userDataURL) let rolesData = res->LogicUtils.getArrayDataFromJson(itemToObjMapperForRoles) setRolesAvailableData(_ => rolesData->Array.map(Nullable.make)) setUserModuleEntity(_ => userModuleEntity) setScreenStateRoles(_ => PageLoaderWrapper.Success) } catch { | _ => setScreenStateRoles(_ => PageLoaderWrapper.Error("")) } } React.useEffect(() => { getRolesAvailable(#Default)->ignore None }, []) <div className="relative mt-5 flex flex-col gap-6"> <PageLoaderWrapper screenState={screenStateRoles}> <div className="flex md:flex-row flex-col flex-1 gap-2 items-center justify-end"> <UserManagementHelper.UserOmpView views={UserManagementUtils.getUserManagementViewValues(~checkUserEntity)} selectedEntity=userModuleEntity onChange={getRolesAvailable} /> <ACLButton authorization={userHasAccess(~groupAccess=UsersManage)} text={"Create custom roles"} buttonType=Primary onClick={_ => { mixpanelEvent(~eventName="create_custom_role") RescriptReactRouter.push( GlobalVars.appendDashboardPath(~url="/users/create-custom-role"), ) }} customButtonStyle="w-fit" buttonState={checkUserEntity([#Profile]) ? Disabled : Normal} /> </div> <LoadedTable title="Roles" hideTitle=true actualData=rolesAvailableData totalResults={rolesAvailableData->Array.length} resultsPerPage=10 offset=rolesOffset setOffset=setRolesOffset entity={rolesEntity} currrentFetchCount={rolesAvailableData->Array.length} collapseTableRow=false tableheadingClass="h-12" customBorderClass="border !rounded-xl" tableHeadingTextClass="!font-normal" tableBorderClass="!border-none" nonFrozenTableParentClass="!rounded-xl" showSerialNumber=false /> </PageLoaderWrapper> </div> }
736
9,524
hyperswitch-control-center
src/screens/UserManagement/UserRevamp/GroupAccessUtils.res
.res
open CommonAuthTypes let linkForGetShowLinkViaAccess = (~authorization, ~url) => { authorization === Access ? url : `` } let cursorStyles = authorization => authorization === Access ? "cursor-pointer" : "cursor-not-allowed"
54
9,525
hyperswitch-control-center
src/screens/UserManagement/UserRevamp/CreateCustomRole.res
.res
module RenderCustomRoles = { @react.component let make = (~heading, ~description, ~groupName) => { let groupsInput = ReactFinalForm.useField(`groups`).input let groupsAdded = groupsInput.value->LogicUtils.getStrArryFromJson let (checkboxSelected, setCheckboxSelected) = React.useState(_ => groupsAdded->Array.includes(groupName) ) let onClickGroup = groupName => { if !(groupsAdded->Array.includes(groupName)) { let _ = groupsAdded->Array.push(groupName) groupsInput.onChange(groupsAdded->Identity.arrayOfGenericTypeToFormReactEvent) } else { let arr = groupsInput.value->LogicUtils.getStrArryFromJson let filteredValue = arr->Array.filter(value => {value !== groupName}) groupsInput.onChange(filteredValue->Identity.arrayOfGenericTypeToFormReactEvent) } setCheckboxSelected(prev => !prev) } <RenderIf condition={groupName->GroupACLMapper.mapStringToGroupAccessType !== OrganizationManage}> <div className="flex gap-6 items-start cursor-pointer" onClick={_ => onClickGroup(groupName)}> <div className="mt-1"> <CheckBoxIcon isSelected={checkboxSelected} size={Large} /> </div> <div className="flex flex-col gap-3 items-start"> <div className="font-semibold"> {heading->React.string} </div> <div className="text-base text-hyperswitch_black opacity-50 flex-1"> {description->React.string} </div> </div> </div> </RenderIf> } } module NewCustomRoleInputFields = { open UserManagementUtils open CommonAuthHooks @react.component let make = () => { let {userRole} = useCommonAuthInfo()->Option.getOr(defaultAuthInfo) <div className="flex justify-between"> <div className="flex flex-col gap-4 w-full"> <FormRenderer.FieldRenderer field={userRole->roleScope} fieldWrapperClass="w-4/5" labelClass="!text-black !text-base !-ml-[0.5px]" /> <FormRenderer.FieldRenderer field=createCustomRole fieldWrapperClass="w-4/5" labelClass="!text-black !text-base !-ml-[0.5px]" /> </div> <div className="absolute top-10 right-5"> <FormRenderer.SubmitButton text="Create role" loadingText="Loading..." /> </div> </div> } } @react.component let make = (~isInviteUserFlow=true, ~setNewRoleSelected=_ => (), ~baseUrl, ~breadCrumbHeader) => { open APIUtils open LogicUtils let getURL = useGetURL() let fetchDetails = useGetMethod() let updateDetails = useUpdateMethod() let initialValuesForForm = [ ("role_scope", "merchant"->JSON.Encode.string), ("groups", []->JSON.Encode.array), ]->Dict.fromArray let {permissionInfo, setPermissionInfo} = React.useContext(GlobalProvider.defaultContext) let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let (initalValue, setInitialValues) = React.useState(_ => initialValuesForForm) let paddingClass = isInviteUserFlow ? "p-10" : "" let marginClass = isInviteUserFlow ? "mt-5" : "" let showToast = ToastState.useShowToast() let onSubmit = async (values, _) => { try { // TODO - Seperate RoleName & RoleId in Backend. role_name as free text and role_id as snake_text setScreenState(_ => PageLoaderWrapper.Loading) let copiedJson = JSON.parseExn(JSON.stringify(values)) let url = getURL(~entityName=V1(USERS), ~userType=#CREATE_CUSTOM_ROLE, ~methodType=Post) let body = copiedJson->getDictFromJsonObject->JSON.Encode.object let roleNameValue = body->getDictFromJsonObject->getString("role_name", "")->String.trim->titleToSnake body->getDictFromJsonObject->Dict.set("role_name", roleNameValue->JSON.Encode.string) let _ = await updateDetails(url, body, Post) setScreenState(_ => PageLoaderWrapper.Success) RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url=`/${baseUrl}`)) } 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 === "UR_35" { setInitialValues(_ => values->LogicUtils.getDictFromJsonObject) setScreenState(_ => PageLoaderWrapper.Success) } else { showToast(~message=errorMessage, ~toastType=ToastError) setScreenState(_ => PageLoaderWrapper.Error(err)) } } } Nullable.null } let getPermissionInfo = async () => { try { setScreenState(_ => PageLoaderWrapper.Loading) let url = getURL( ~entityName=V1(USERS), ~userType=#GROUP_ACCESS_INFO, ~methodType=Get, ~queryParamerters=Some(`groups=true`), ) let res = await fetchDetails(url) let permissionInfoValue = res->getArrayDataFromJson(ProviderHelper.itemToObjMapperForGetInfo) setPermissionInfo(_ => permissionInfoValue) setScreenState(_ => PageLoaderWrapper.Success) } catch { | _ => setScreenState(_ => PageLoaderWrapper.Error("Something went wrong!")) } } React.useEffect(() => { if permissionInfo->Array.length === 0 { getPermissionInfo()->ignore } else { setScreenState(_ => PageLoaderWrapper.Success) } None }, []) <div className="flex flex-col overflow-y-scroll h-full"> <RenderIf condition={isInviteUserFlow}> <div className="flex flex-col gap-2"> <PageUtils.PageHeading title="Create custom role" subTitle="Adjust permissions to create custom roles that match your requirement" /> <BreadCrumbNavigation path=[{title: breadCrumbHeader, link: `/${baseUrl}`}] currentPageTitle="Create custom roles" /> </div> </RenderIf> <div className={`h-4/5 bg-white relative overflow-y-scroll flex flex-col gap-10 ${paddingClass} ${marginClass}`}> <PageLoaderWrapper screenState> <Form key="invite-user-management" initialValues={initalValue->JSON.Encode.object} validate={values => values->UserManagementUtils.validateFormForRoles} onSubmit formClass="flex flex-col gap-8"> <NewCustomRoleInputFields /> <div className="flex flex-col justify-between gap-12 show-scrollbar overflow-scroll"> {permissionInfo ->Array.mapWithIndex((ele, index) => { <RenderCustomRoles key={index->Int.toString} heading={`${ele.module_->snakeToTitle}`} description={ele.description} groupName={ele.module_} /> }) ->React.array} </div> <FormValuesSpy /> </Form> </PageLoaderWrapper> </div> </div> }
1,641
9,526
hyperswitch-control-center
src/screens/UserManagement/UserRevamp/UserManagementLanding.res
.res
@react.component let make = () => { let tabList: array<Tabs.tab> = [ { title: "Users", renderContent: () => <ListUsers />, }, { title: "Roles", renderContent: () => <ListRoles />, }, ] <div className="flex flex-col"> <div className="flex justify-between items-center"> <PageUtils.PageHeading title={"Team management"} /> </div> <div className="relative"> <Tabs tabs=tabList showBorder=true 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> </div> }
197
9,527
hyperswitch-control-center
src/screens/UserManagement/UserRevamp/ListUsers.res
.res
open ListUserTableEntity @react.component let make = () => { open APIUtils open LogicUtils let getURL = useGetURL() let fetchDetails = useGetMethod() let mixpanelEvent = MixpanelHook.useSendEvent() let {checkUserEntity} = React.useContext(UserInfoProvider.defaultContext) let {userHasAccess} = GroupACLHooks.useUserGroupACLHook() let (usersData, setUsersData) = React.useState(_ => []) let (usersFilterData, setUsersFilterData) = React.useState(_ => []) let (screenStateUsers, setScreenStateUsers) = React.useState(_ => PageLoaderWrapper.Loading) let (userOffset, setUserOffset) = React.useState(_ => 0) let (searchText, setSearchText) = React.useState(_ => "") let ( userModuleEntity: UserManagementTypes.userModuleTypes, setUserModuleEntity, ) = React.useState(_ => #Default) let sortByEmail = ( user1: ListUserTableEntity.userTableTypes, user2: ListUserTableEntity.userTableTypes, ) => { compareLogic(user2.email->String.toLowerCase, user1.email->String.toLowerCase) } let getUserData = async (userModuleEntity: UserManagementTypes.userModuleTypes) => { setScreenStateUsers(_ => PageLoaderWrapper.Loading) try { let userDataURL = getURL( ~entityName=V1(USER_MANAGEMENT), ~methodType=Get, ~userRoleTypes=USER_LIST, ~queryParamerters=userModuleEntity == #Default ? None : Some(`entity_type=${(userModuleEntity :> string)->String.toLowerCase}`), ) let res = await fetchDetails(userDataURL) let userData = res->getArrayDataFromJson(itemToObjMapperForUser) userData->Array.sort(sortByEmail) setUsersData(_ => userData->Array.map(Nullable.make)) setUsersFilterData(_ => userData->Array.map(Nullable.make)) setUserModuleEntity(_ => userModuleEntity) setScreenStateUsers(_ => PageLoaderWrapper.Success) } catch { | _ => setScreenStateUsers(_ => PageLoaderWrapper.Error("")) } } React.useEffect(() => { getUserData(#Default)->ignore None }, []) let filterLogicForUsers = ReactDebounce.useDebounced(ob => { let (searchText, arr) = ob let filteredList = if searchText->isNonEmptyString { arr->Array.filter((obj: Nullable.t<userTableTypes>) => { switch Nullable.toOption(obj) { | Some(obj) => isContainingStringLowercase(obj.email, searchText) | None => false } }) } else { arr } setUsersFilterData(_ => filteredList) }, ~wait=200) <PageLoaderWrapper screenState={screenStateUsers}> <div className="relative mt-5 w-full flex flex-col gap-12"> <div className="flex md:flex-row flex-col gap-2 items-center lg:absolute lg:right-0 lg:z-10"> <UserManagementHelper.UserOmpView views={UserManagementUtils.getUserManagementViewValues(~checkUserEntity)} selectedEntity=userModuleEntity onChange={getUserData} /> <ACLButton authorization={userHasAccess(~groupAccess=UsersManage)} text={"Invite users"} buttonType=Primary buttonSize={Medium} onClick={_ => { mixpanelEvent(~eventName="invite_users") RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/users/invite-users")) }} /> </div> <LoadedTable title="Users" hideTitle=true actualData=usersFilterData totalResults={usersFilterData->Array.length} filters={<TableSearchFilter data={usersData} filterLogic=filterLogicForUsers placeholder="Search by name or email.." customSearchBarWrapperWidth="w-full lg:w-1/3" customInputBoxWidth="w-full" searchVal=searchText setSearchVal=setSearchText />} resultsPerPage=10 offset=userOffset setOffset=setUserOffset entity={ListUserTableEntity.userEntity} currrentFetchCount={usersFilterData->Array.length} collapseTableRow=false tableheadingClass="h-12" tableHeadingTextClass="!font-normal" nonFrozenTableParentClass="!rounded-lg" showSerialNumber=false loadedTableParentClass="flex flex-col" /> </div> </PageLoaderWrapper> }
1,010
9,528
hyperswitch-control-center
src/screens/UserManagement/UserRevamp/DropdownWithLoading.res
.res
open HeadlessUI type dropDownState = Loading | Success | NoData let commonDropdownCss = "absolute md:max-h-36 md:min-h-fit overflow-scroll z-30 w-full bg-white rounded-sm shadow-lg focus:outline-none my-1 border border-jp-gray-lightmode_steelgray border-opacity-75 ring-1 ring-black ring-opacity-5" module DropDownItems = { @react.component let make = (~options: array<SelectBox.dropdownOption>, ~formKey, ~keyValueFromForm) => { let form = ReactFinalForm.useForm() let onItemSelect = value => { form.change(formKey, value->Identity.genericTypeToJson) } <Menu.Items className={`divide-y divide-gray-100 ${commonDropdownCss}`}> {_ => { <div className="px-1 py-1 "> {options ->Array.mapWithIndex((option, i) => <Menu.Item key={i->Int.toString}> {props => <div className="relative"> <div onClick={_ => option.value->onItemSelect} className={ let activeClasses = if props["active"] { "group flex justify-between rounded-md items-center w-full px-2 py-2 text-sm bg-gray-100 dark:bg-black" } else { "group flex justify-between rounded-md items-center w-full px-2 py-2 text-sm" } `${activeClasses} font-medium text-start` }> <div className="mr-5"> {option.label ->LogicUtils.snakeToTitle ->React.string} </div> <Tick isSelected={keyValueFromForm === option.value} /> </div> </div>} </Menu.Item> ) ->React.array} </div> }} </Menu.Items> } } module DropDownLoading = { @react.component let make = () => { <div className={`${commonDropdownCss} flex flex-col justify-center items-center p-6 gap-4`}> <div className={`flex flex-col text-center items-center animate-spin `}> <Icon name="spinner" size=20 /> </div> <p className="text-gray-600"> {"Fetching data..."->React.string} </p> </div> } } module DropDownNoData = { @react.component let make = () => { <div className={`${commonDropdownCss} flex justify-center items-center p-6`}> <p className="text-semibold text-gray-600 opacity-60"> {"No data to display"->React.string} </p> </div> } } @react.component let make = ( ~options: array<SelectBox.dropdownOption>, ~onClickDropDownApi, ~formKey, ~dropDownLoaderState: dropDownState, ~isRequired=false, ) => { open LogicUtils let formState: ReactFinalForm.formState = ReactFinalForm.useFormState( ReactFinalForm.useFormSubscription(["values"])->Nullable.make, ) let keyValueFromForm = formState.values->getDictFromJsonObject->getString(formKey, "") let getNameByLabel = value => { let filteredValueFromForm = options->Array.find(v => v.value === value) switch filteredValueFromForm { | Some(value) => value.label->snakeToTitle | None => "Select a role" } } let buttonValue = React.useMemo(() => { switch formState.values->getDictFromJsonObject->Dict.get(formKey) { | Some(value) => getNameByLabel(value->getStringFromJson("")) | None => "Select a role" } }, [keyValueFromForm]) <Menu \"as"="div" className="relative inline-block text-left p-1"> {_ => <> <Menu.Button className="w-full"> {props => { let arrow = props["open"] <div className="w-full flex flex-col"> <div className="flex justify-start pt-2 pb-2 text-fs-13 text-jp-gray-900 ml-1 font-semibold"> {"Role"->React.string} <RenderIf condition=isRequired> <span className="text-red-950"> {React.string("*")} </span> </RenderIf> </div> <div className="relative inline-flex whitespace-pre leading-5 justify-between text-sm py-3 px-4 font-medium rounded-md hover:bg-opacity-80 bg-white border w-full" onClick={_ => arrow ? () : onClickDropDownApi()->ignore}> <span className="px-1 text-fs-13 text-sm font-medium leading-5 whitespace-pre !text-gray-500"> {buttonValue->React.string} </span> <Icon className={`transition duration-[250ms] ml-1 mt-1 opacity-60 ${arrow ? "rotate-0" : "rotate-180"}`} name="arrow-without-tail" size=15 /> </div> </div> }} </Menu.Button> <Transition \"as"="div" className="relative" enter="transition ease-out duration-100" enterFrom="transform opacity-0 scale-95" enterTo="transform opacity-100 scale-100" leave="transition ease-in duration-75" leaveFrom="transform opacity-100 scale-100" leaveTo="transform opacity-0 scale-95"> {switch dropDownLoaderState { | Success => <DropDownItems options keyValueFromForm formKey /> | Loading => <DropDownLoading /> | NoData => <DropDownNoData /> }} </Transition> </>} </Menu> }
1,283
9,529
hyperswitch-control-center
src/screens/UserManagement/UserRevamp/UserManagementTypes.res
.res
type userManagementTypes = UsersTab | RolesTab type internalUserType = InternalViewOnly | InternalAdmin | NonInternal type admin = TenantAdmin | NonTenantAdmin @unboxed type groupAccessType = | OperationsView | OperationsManage | ConnectorsView | ConnectorsManage | WorkflowsView | WorkflowsManage | AnalyticsView | UsersView | UsersManage | MerchantDetailsView | MerchantDetailsManage | OrganizationManage | AccountView | AccountManage | UnknownGroupAccess(string) type resourceAccessType = | Payment | Refund | Dispute | Payout | Customer | Connector | Analytics | Routing | ThreeDsDecisionManager | SurchargeDecisionManager | ReconToken | ReconFiles | ReconAndSettlementAnalytics | ReconUpload | ReconReports | RunRecon | ReconConfig | Account | ApiKey | User | Mandate | WebhookEvent | Report | UnknownResourceAccess(string) open CommonAuthTypes type groupAccessJsonType = { operationsView: authorization, operationsManage: authorization, connectorsView: authorization, connectorsManage: authorization, workflowsView: authorization, workflowsManage: authorization, analyticsView: authorization, usersView: authorization, usersManage: authorization, merchantDetailsView: authorization, merchantDetailsManage: authorization, organizationManage: authorization, accountView: authorization, accountManage: authorization, } type getInfoType = { module_: string, description: string, } type userModuleType = { parentGroup: string, description: string, groups: array<string>, } type detailedUserModuleType = { parentGroup: string, description: string, scopes: array<string>, } type orgObjectType = { name: string, value: string, id: option<string>, } type userDetailstype = { roleId: string, roleName: string, org: orgObjectType, merchant: orgObjectType, profile: orgObjectType, status: string, entityType: string, } @unboxed type groupScopeType = Read | Write type allSelectionType = [#All_Merchants | #All_Profiles] type userActionType = SwitchUser | ManageUser | NoActionAccess type userStatusTypes = Active | InviteSent | None type userModuleTypes = [UserInfoTypes.entity | #Default] type usersOmpViewType = { label: string, entity: userModuleTypes, }
575
9,530
hyperswitch-control-center
src/screens/UserManagement/UserRevamp/UserManagementHelper.res
.res
open UserUtils module OrganisationSelection = { @react.component let make = () => { let showToast = ToastState.useShowToast() let internalSwitch = OMPSwitchHooks.useInternalSwitch() let orgList = Recoil.useRecoilValueFromAtom(HyperswitchAtom.orgListAtom) let {userInfo: {userEntity}} = React.useContext(UserInfoProvider.defaultContext) let disableSelect = switch userEntity { | #Tenant | #Organization | #Merchant | #Profile => true } let handleOnChange = async (event, input: ReactFinalForm.fieldRenderPropsInput) => { try { let _ = await internalSwitch(~expectedOrgId=Some(event->Identity.formReactEventToString)) input.onChange(event) } catch { | _ => showToast(~message="Something went wrong. Please try again", ~toastType=ToastError) } } let field = FormRenderer.makeFieldInfo( ~label="Select an organization", ~name="org_value", ~customInput=(~input, ~placeholder as _) => InputFields.selectInput( ~options=getMerchantSelectBoxOption( ~label="All organizations", ~value="all_organizations", ~dropdownList=orgList, ), ~deselectDisable=true, ~buttonText="Select an organization", ~fullLength=true, ~customButtonStyle="!rounded-lg", ~dropdownCustomWidth="!w-full", ~textStyle="!text-gray-500 truncate", ~disableSelect, )( ~input={ ...input, onChange: event => handleOnChange(event, input)->ignore, }, ~placeholder="Select an organization", ), ~isRequired=true, ) <FormRenderer.FieldRenderer field labelClass="font-semibold" /> } } module MerchantSelection = { @react.component let make = () => { let showToast = ToastState.useShowToast() let internalSwitch = OMPSwitchHooks.useInternalSwitch() let merchList = Recoil.useRecoilValueFromAtom(HyperswitchAtom.merchantListAtom) let {userInfo: {userEntity}} = React.useContext(UserInfoProvider.defaultContext) let (showSwitchingMerchant, setShowSwitchingMerchant) = React.useState(_ => false) let disableSelect = switch userEntity { | #Merchant | #Profile => true | #Tenant | #Organization => false } let v1MerchantList = merchList->Array.filter(merchant => merchant.productType === Some(Orchestration)) let handleOnChange = async (event, input: ReactFinalForm.fieldRenderPropsInput) => { try { let selectedMerchantValue = event->Identity.formReactEventToString if selectedMerchantValue->stringToVariantForAllSelection->Option.isNone { setShowSwitchingMerchant(_ => true) let _ = await internalSwitch(~expectedMerchantId=Some(selectedMerchantValue)) setShowSwitchingMerchant(_ => false) } input.onChange(event) } catch { | _ => showToast(~message="Something went wrong. Please try again", ~toastType=ToastError) } } let field = FormRenderer.makeFieldInfo( ~label="Merchants for access", ~name="merchant_value", ~customInput=(~input, ~placeholder as _) => InputFields.selectInput( ~options=getMerchantSelectBoxOption( ~label="All merchants", ~value="all_merchants", ~dropdownList=v1MerchantList, ~showAllSelection=true, ), ~deselectDisable=true, ~buttonText="Select a Merchant", ~fullLength=true, ~customButtonStyle="!rounded-lg", ~dropdownCustomWidth="!w-full", ~textStyle="!text-gray-500", ~disableSelect, )( ~input={ ...input, onChange: event => handleOnChange(event, input)->ignore, }, ~placeholder="Select a merchant", ), ) <> <FormRenderer.FieldRenderer field labelClass="font-semibold" /> <LoaderModal showModal={showSwitchingMerchant} setShowModal={setShowSwitchingMerchant} text="Switching merchant..." /> </> } } module ProfileSelection = { @react.component let make = () => { let showToast = ToastState.useShowToast() let internalSwitch = OMPSwitchHooks.useInternalSwitch() let profileList = Recoil.useRecoilValueFromAtom(HyperswitchAtom.profileListAtom) let {userInfo: {userEntity}} = React.useContext(UserInfoProvider.defaultContext) let form = ReactFinalForm.useForm() let formState: ReactFinalForm.formState = ReactFinalForm.useFormState( ReactFinalForm.useFormSubscription(["values"])->Nullable.make, ) let (showSwitchingProfile, setShowSwitchingProfile) = React.useState(_ => false) React.useEffect(() => { switch userEntity { | #Tenant | #Organization | #Merchant => form.change( "profile_value", (#All_Profiles: UserManagementTypes.allSelectionType :> string) ->String.toLowerCase ->JSON.Encode.string, ) | #Profile => () } None }, []) let disableSelect = switch userEntity { | #Profile => true | #Tenant | #Organization => { let selected_merchant = formState.values ->LogicUtils.getDictFromJsonObject ->LogicUtils.getString("merchant_value", "") switch selected_merchant->stringToVariantForAllSelection { | Some(#All_Merchants) => { form.change( "profile_value", (#All_Profiles: UserManagementTypes.allSelectionType :> string) ->String.toLowerCase ->JSON.Encode.string, ) true } | _ => false } } | #Merchant => false } let handleOnChange = async (event, input: ReactFinalForm.fieldRenderPropsInput) => { try { let selectedProfileValue = event->Identity.formReactEventToString if selectedProfileValue->stringToVariantForAllSelection->Option.isNone { setShowSwitchingProfile(_ => true) let _ = await internalSwitch(~expectedProfileId=Some(selectedProfileValue)) setShowSwitchingProfile(_ => false) } input.onChange(event) } catch { | _ => showToast(~message="Something went wrong. Please try again", ~toastType=ToastError) } } let field = FormRenderer.makeFieldInfo( ~label="Profiles for access", ~name="profile_value", ~customInput=(~input, ~placeholder as _) => InputFields.selectInput( ~options=getMerchantSelectBoxOption( ~label="All profiles", ~value="all_profiles", ~dropdownList=profileList, ~showAllSelection=true, ), ~deselectDisable=true, ~buttonText="Select a Profile", ~fullLength=true, ~customButtonStyle="!rounded-lg", ~dropdownCustomWidth="!w-full", ~textStyle="!text-gray-500", ~disableSelect, )( ~input={ ...input, onChange: event => handleOnChange(event, input)->ignore, }, ~placeholder="Select a merchant", ), ) <> <FormRenderer.FieldRenderer field labelClass="font-semibold" /> <LoaderModal showModal={showSwitchingProfile} setShowModal={setShowSwitchingProfile} text="Switching profile..." /> </> } } let inviteEmail = FormRenderer.makeFieldInfo( ~label="Enter email(s) ", ~name="email_list", ~customInput=(~input, ~placeholder as _) => { let showPlaceHolder = input.value->LogicUtils.getArrayFromJson([])->Array.length === 0 <PillInput name="email_list" placeholder={showPlaceHolder ? "Eg: abc.sa@wise.com" : ""} /> }, ~isRequired=true, ) module SwitchMerchantForUserAction = { @react.component let make = (~userInfoValue: UserManagementTypes.userDetailstype) => { let showToast = ToastState.useShowToast() let internalSwitch = OMPSwitchHooks.useInternalSwitch() let onSwitchForUserAction = async () => { try { let _ = await internalSwitch( ~expectedOrgId=userInfoValue.org.id, ~expectedMerchantId=userInfoValue.merchant.id, ~expectedProfileId=userInfoValue.profile.id, ) } catch { | _ => showToast(~message="Failed to perform operation!", ~toastType=ToastError) } } <Button text="Switch to update" customButtonStyle="!p-2" buttonType={PrimaryOutline} onClick={_ => onSwitchForUserAction()->ignore} /> } } let generateDropdownOptionsUserOMPViews = ( dropdownList: array<UserManagementTypes.usersOmpViewType>, getNameForId, ) => { let options: array<SelectBox.dropdownOption> = dropdownList->Array.map(( item ): SelectBox.dropdownOption => { switch item.entity { | #Default => { label: `${item.label}`, value: `${(item.entity :> string)}`, labelDescription: `(${(item.entity :> string)})`, description: `${item.label}`, } | _ => { label: `${item.entity->getNameForId}`, value: `${(item.entity :> string)}`, labelDescription: `(${(item.entity :> string)})`, description: `${item.entity->getNameForId}`, } } }) options } module UserOmpView = { @react.component let make = ( ~views: array<UserManagementTypes.usersOmpViewType>, ~selectedEntity: UserManagementTypes.userModuleTypes, ~onChange, ) => { let (_, getNameForId) = OMPSwitchHooks.useOMPData() let input: ReactFinalForm.fieldRenderPropsInput = { name: "name", onBlur: _ => (), onChange: ev => { let value = ev->Identity.formReactEventToString let selection = switch value { | "Default" => #Default | _ => value->UserInfoUtils.entityMapper } onChange(selection)->ignore }, onFocus: _ => (), value: (selectedEntity :> string)->JSON.Encode.string, checked: true, } let options = views->generateDropdownOptionsUserOMPViews(getNameForId) let displayName = switch selectedEntity { | #Default => "All" | _ => selectedEntity->getNameForId } <OMPSwitchHelper.OMPViewsComp input options displayName /> } }
2,347
9,531
hyperswitch-control-center
src/screens/Customers/CustomersEntity.res
.res
open CustomersType let defaultColumns = [ CustomerId, Name, Email, PhoneCountryCode, Phone, Description, Address, CreatedAt, ] let allColumns = [CustomerId, Name, Email, Phone, PhoneCountryCode, Description, Address, CreatedAt] let getHeading = colType => { switch colType { | CustomerId => Table.makeHeaderInfo(~key="customer_id", ~title="Customer Id") | Name => Table.makeHeaderInfo(~key="name", ~title="Customer Name") | Email => Table.makeHeaderInfo(~key="email", ~title="Email") | PhoneCountryCode => Table.makeHeaderInfo(~key="phone_country_code", ~title="Phone Country Code") | Phone => Table.makeHeaderInfo(~key="phone", ~title="Phone") | Description => Table.makeHeaderInfo(~key="description", ~title="Description") | Address => Table.makeHeaderInfo(~key="address", ~title="Address") | CreatedAt => Table.makeHeaderInfo(~key="created_at", ~title="Created") } } let getCell = (customersData, colType): Table.cell => { switch colType { | CustomerId => CustomCell( <HelperComponents.CopyTextCustomComp customTextCss="w-36 truncate whitespace-nowrap" displayValue={Some(customersData.customer_id)} copyValue={Some(customersData.customer_id)} />, "", ) | Name => Text(customersData.name) | Email => Text(customersData.email) | Phone => Text(customersData.phone) | PhoneCountryCode => Text(customersData.phone_country_code) | Description => Text(customersData.description) | Address => Date(customersData.address) | CreatedAt => Date(customersData.created_at) } } let itemToObjMapper = dict => { open LogicUtils { customer_id: dict->getString("customer_id", ""), name: dict->getString("name", ""), email: dict->getString("email", ""), phone: dict->getString("phone", ""), phone_country_code: dict->getString("phone_country_code", ""), description: dict->getString("description", ""), address: dict->getString("address", ""), created_at: dict->getString("created_at", ""), metadata: dict->getJsonObjectFromDict("metadata"), } } let getCustomers: JSON.t => array<customers> = json => { open LogicUtils getArrayDataFromJson(json, itemToObjMapper) } let customersEntity = EntityType.makeEntity( ~uri="", ~getObjects=getCustomers, ~defaultColumns, ~allColumns, ~getHeading, ~getCell, ~dataKey="", ~getShowLink={ customerData => GlobalVars.appendDashboardPath(~url=`/customers/${customerData.customer_id}`) }, )
620
9,532
hyperswitch-control-center
src/screens/Customers/ShowCustomers.res
.res
module CustomerInfo = { open CustomersEntity module Details = { @react.component let make = ( ~data, ~getHeading, ~getCell, ~excludeColKeys=[], ~detailsFields, ~justifyClassName="justify-start", ~widthClass="w-1/4", ~bgColor="bg-white dark:bg-jp-gray-lightgray_background", ~children=?, ) => { <OrderUtils.Section customCssClass={`border border-jp-gray-940 border-opacity-75 dark:border-jp-gray-960 ${bgColor} rounded-md p-5`}> <FormRenderer.DesktopRow> <div className={`flex flex-wrap ${justifyClassName} lg:flex-row flex-col dark:bg-jp-gray-lightgray_background dark:border-jp-gray-no_data_border`}> {detailsFields ->Array.mapWithIndex((colType, i) => { <RenderIf condition={!(excludeColKeys->Array.includes(colType))} key={Int.toString(i)}> <div className={`flex ${widthClass} items-center`}> <OrderUtils.DisplayKeyValueParams heading={getHeading(colType)} value={getCell(data, colType)} customMoneyStyle="!font-normal !text-sm" labelMargin="!py-0 mt-2" overiddingHeadingStyles="text-black text-sm font-medium" textColor="!font-normal !text-jp-gray-700" /> </div> </RenderIf> }) ->React.array} </div> </FormRenderer.DesktopRow> <RenderIf condition={children->Option.isSome}> {children->Option.getOr(React.null)} </RenderIf> </OrderUtils.Section> } } @react.component let make = (~dict) => { let customerData = itemToObjMapper(dict) <> <div className={`font-bold text-fs-16 dark:text-white dark:text-opacity-75 mt-4 mb-4`}> {"Summary"->React.string} </div> <Details data=customerData getHeading getCell detailsFields=allColumns /> </> } } module CustomerDetails = { open GlobalSearchBarUtils open GlobalSearchTypes open APIUtils @react.component let make = (~id) => { let getURL = useGetURL() let fetchData = APIUtils.useUpdateMethod() let (searchResults, setSearchResults) = React.useState(_ => []) let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let getSearchResults = async () => { setScreenState(_ => PageLoaderWrapper.Loading) try { let url = getURL(~entityName=V1(GLOBAL_SEARCH), ~methodType=Post) let body = [("query", id->JSON.Encode.string)]->LogicUtils.getJsonFromArrayOfJson let response = await fetchData(url, body, Post) let remote_results = response->parseResponse let data = { local_results: [], remote_results, searchText: id, } let (results, _) = data->SearchResultsPageUtils.getSearchresults setSearchResults(_ => results) setScreenState(_ => PageLoaderWrapper.Success) } catch { | _ => setScreenState(_ => PageLoaderWrapper.Success) } } React.useEffect(() => { getSearchResults()->ignore None }, []) <PageLoaderWrapper screenState> <div className="mt-5"> <SearchResultsPage.SearchResultsComponent searchResults searchText={id} /> </div> </PageLoaderWrapper> } } @react.component let make = (~id) => { open APIUtils let getURL = useGetURL() let fetchDetails = useGetMethod() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let (customersData, setCustomersData) = React.useState(_ => JSON.Encode.null) let fetchCustomersData = async () => { try { setScreenState(_ => PageLoaderWrapper.Loading) let customersUrl = getURL(~entityName=V1(CUSTOMERS), ~methodType=Get, ~id=Some(id)) let response = await fetchDetails(customersUrl) setCustomersData(_ => response) setScreenState(_ => PageLoaderWrapper.Success) } catch { | Exn.Error(e) => let err = Exn.message(e)->Option.getOr("Failed to Fetch!") setScreenState(_ => PageLoaderWrapper.Error(err)) } } React.useEffect(() => { fetchCustomersData()->ignore None }, []) <PageLoaderWrapper screenState> <div className="flex flex-col overflow-scroll"> <div className="mb-4 flex justify-between"> <div className="flex items-center"> <div> <PageUtils.PageHeading title="Customers" /> <BreadCrumbNavigation path=[{title: "Customers", link: "/customers"}] currentPageTitle=id cursorStyle="cursor-pointer" /> </div> <div /> </div> </div> <CustomerInfo dict={customersData->LogicUtils.getDictFromJsonObject} /> <CustomerDetails id /> </div> </PageLoaderWrapper> }
1,161
9,533
hyperswitch-control-center
src/screens/Customers/Customers.res
.res
@react.component let make = () => { open APIUtils open CustomersEntity let getURL = useGetURL() let fetchDetails = useGetMethod() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let (customersData, setCustomersData) = React.useState(_ => []) let pageDetailDict = Recoil.useRecoilValueFromAtom(LoadedTable.table_pageDetails) let defaultValue: LoadedTable.pageDetails = {offset: 0, resultsPerPage: 20} let pageDetail = pageDetailDict->Dict.get("customers")->Option.getOr(defaultValue) let (offset, setOffset) = React.useState(_ => pageDetail.offset) let total = 100 // TODO: take this value from API response [currenctly set to 5 pages] let limit = 20 // each api calls will retrun 50 results let getCustomersList = async () => { setScreenState(_ => PageLoaderWrapper.Loading) try { let customersUrl = getURL( ~entityName=V1(CUSTOMERS), ~methodType=Get, ~queryParamerters=Some(`limit=${limit->Int.toString}&offset=${offset->Int.toString}`), ) let response = await fetchDetails(customersUrl) let data = response->JSON.Decode.array->Option.getOr([]) let arr = Array.make(~length=offset, Dict.make()) if total <= offset { setOffset(_ => 0) } if total > 0 { let dataArr = data->Belt.Array.keepMap(JSON.Decode.object) let customersData = arr ->Array.concat(dataArr) ->Array.map(itemToObjMapper) ->Array.map(Nullable.make) setCustomersData(_ => customersData) } setScreenState(_ => PageLoaderWrapper.Success) } catch { | Exn.Error(e) => let err = Exn.message(e)->Option.getOr("Failed to Fetch!") setScreenState(_ => PageLoaderWrapper.Error(err)) } } React.useEffect(() => { getCustomersList()->ignore None }, [offset]) <PageLoaderWrapper screenState> <PageUtils.PageHeading title="Customers" subTitle="View all customers" /> <LoadedTableWithCustomColumns title="Customers" hideTitle=true actualData=customersData entity={customersEntity} resultsPerPage=20 showSerialNumber=true totalResults=total offset setOffset currrentFetchCount={customersData->Array.length} defaultColumns={defaultColumns} customColumnMapper={TableAtoms.customersMapDefaultCols} showSerialNumberInCustomizeColumns=false showResultsPerPageSelector=false sortingBasedOnDisabled=false showAutoScroll=true /> </PageLoaderWrapper> }
629
9,534
hyperswitch-control-center
src/screens/Customers/CustomersType.res
.res
type customers = { customer_id: string, name: string, email: string, phone: string, phone_country_code: string, description: string, address: string, created_at: string, metadata: JSON.t, } type customersColsType = | CustomerId | Name | Email | Phone | PhoneCountryCode | Description | Address | CreatedAt
96
9,535
hyperswitch-control-center
src/screens/Recon/Recon.res
.res
@react.component let make = () => { open APIUtils let getURL = useGetURL() let (redirectToken, setRedirecToken) = React.useState(_ => "") let fetchDetails = useGetMethod() let updateDetails = useUpdateMethod() let showToast = ToastState.useShowToast() let fetchMerchantAccountDetails = MerchantDetailsHook.useFetchMerchantDetails() let merchentDetails = HSwitchUtils.useMerchantDetailsValue() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let mixpanelEvent = MixpanelHook.useSendEvent() let isReconEnabled = merchentDetails.recon_status === Active let onClickForReconRequest = async () => { try { let url = getURL(~entityName=V1(RECON), ~reconType=#REQUEST, ~methodType=Get) let _ = await updateDetails(url, JSON.Encode.null, Post) let _ = await fetchMerchantAccountDetails() showToast( ~message=`Thank you for your interest in our reconciliation module. We are currently reviewing your request for access. We will follow up with you soon regarding next steps.`, ~toastType=ToastSuccess, ) } catch { | _ => showToast(~message=`Something went wrong. Please try again.`, ~toastType=ToastError) } } let openReconTab = async () => { try { if redirectToken->String.length === 0 { setScreenState(_ => PageLoaderWrapper.Loading) let url = getURL(~entityName=V1(RECON), ~reconType=#TOKEN, ~methodType=Get) let res = await fetchDetails(url) let token = res->LogicUtils.getDictFromJsonObject->LogicUtils.getString("token", "") setRedirecToken(_ => token) let link = "https://sandbox.hyperswitch.io/recon-dashboard/?token=" ++ token Window._open(link) setScreenState(_ => PageLoaderWrapper.Success) } else { let link = "https://sandbox.hyperswitch.io/recon-dashboard/?token=" ++ redirectToken Window._open(link) } } catch { | Exn.Error(e) => { let err = Exn.message(e)->Option.getOr("Failed to fetch Token!") setScreenState(_ => PageLoaderWrapper.Error(err)) } } } React.useEffect(() => { if isReconEnabled { let _ = openReconTab()->ignore } else { setScreenState(_ => PageLoaderWrapper.Success) } None }, []) let subTitleText = isReconEnabled ? "Streamline your reconciliation and settlement operations" : "Upgrade today to streamline your reconciliation and settlement operations" <PageLoaderWrapper screenState> <div className="h-screen overflow-scroll flex flex-col w-full "> <div className="flex flex-col overflow-scroll h-full gap-6"> <PageUtils.PageHeading title={isReconEnabled ? "Reconciliation" : "Activate Reconciliation"} subTitle=subTitleText /> {if isReconEnabled { <div className={`bg-white dark:bg-jp-gray-lightgray_background border-2 rounded dark:border-jp-gray-850 grid grid-cols-1 md:gap-5 p-2 md:p-8 h-2/3 items-center`}> <div className={`flex flex-col items-center w-4/6 md:w-2/6 justify-self-center gap-1`}> <div className={`text-center text-semibold text-s text-grey-700 opacity-60 dark:text-white`}> {"You will be redirected to the recon dashboard in a moment. (Enable pop-ups in your browser for auto-redirection.)"->React.string} </div> <Button text="Go to recon tab" buttonType={Primary} customButtonStyle="w-2/3 rounded-sm !bg-jp-blue-button_blue border border-jp-blue-border_blue mt-4" buttonSize={Small} buttonState={Normal} onClick={_v => { openReconTab()->ignore }} /> </div> </div> } else { <div className={`flex flex-col gap-5 bg-white dark:bg-jp-gray-lightgray_background border-2 rounded dark:border-jp-gray-850 md:gap-5 p-2 md:p-8 h-2/3 items-center justify-center`}> {if merchentDetails.recon_status === Requested { <div className={`text-center text-semibold text-s text-grey-700 opacity-60 dark:text-white`}> {"Thank you for your interest in our reconciliation module. We are currently reviewing your request for access. We will follow up with you soon regarding next steps."->React.string} </div> } else { <div className={`flex flex-col items-center w-2/3 justify-self-center gap-1 my-10`}> <div className={`font-bold text-xl dark:text-white`}> {"Drop us an email!"->React.string} </div> <div className={`text-center text-semibold text-s text-grey-700 opacity-60 dark:text-white`}> {"Once submitted, you should hear a response in 48 hours, often sooner."->React.string} </div> <Button text="Send an email" buttonType={Primary} customButtonStyle="w-2/3 rounded-sm !bg-jp-blue-button_blue border border-jp-blue-border_blue mt-4" buttonSize={Small} buttonState={Normal} onClick={_v => { mixpanelEvent(~eventName="recon_send_an_email") onClickForReconRequest()->ignore }} /> <div className={`flex text-center`}> <div className={`text-s text-grey-700 opacity-60 dark:text-white`}> {"or contact us on"->React.string} </div> <div className={`m-1`}> <Icon size=16 name="slack" /> </div> <div> <a className={`text-[#0000FF]`} href="https://hyperswitch-io.slack.com/?redir=%2Fssb%2Fredirect" target="_blank"> {"slack"->React.string} </a> </div> </div> </div> }} </div> }} </div> </div> </PageLoaderWrapper> }
1,437
9,536
hyperswitch-control-center
src/screens/Recon/ReconUtils.res
.res
open ReconTypes let getAuthStatusFromMessage = authStatus => switch authStatus { | "LoggedOut" => IframeLoggedOut | _ => IframeLoggedIn } let getEventTypeFromString = eventTypeString => switch eventTypeString { | "AuthenticationStatus" | _ => AuthenticationStatus }
70
9,537
hyperswitch-control-center
src/screens/Recon/ReconTypes.res
.res
type authStatus = IframeLoggedIn | IframeLoggedOut type eventType = AuthenticationStatus
19
9,538
hyperswitch-control-center
src/screens/Recon/ReconModule.res
.res
@react.component let make = (~urlList) => { open APIUtils open LogicUtils let getURL = useGetURL() let handleLogout = useHandleLogout() let fetchDetails = useGetMethod() let (redirectToken, setRedirectToken) = React.useState(_ => "") let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let (iframeLoaded, setIframeLoaded) = React.useState(_ => false) let iframeRef = React.useRef(Js.Nullable.null) let getReconToken = async () => { try { let url = getURL(~entityName=V1(RECON), ~reconType=#TOKEN, ~methodType=Get) let res = await fetchDetails(url) let token = res->LogicUtils.getDictFromJsonObject->LogicUtils.getString("token", "") setRedirectToken(_ => token) setScreenState(_ => PageLoaderWrapper.Success) } catch { | _ => setScreenState(_ => PageLoaderWrapper.Error("Something went wrong!")) } } let redirectUrl = switch urlList { | list{"upload-files"} => "upload-recon-files" | list{"run-recon"} => "run-recon/home" | list{"reports"} => "report/reconciliation" | list{"config-settings"} => "reconcilation-config" | list{"recon-analytics"} => "analytics-recon-and-settlement" | _ => "" // commented as not needed as of now // | list{"file-processor"} => "file-processor" } React.useEffect(() => { getReconToken()->ignore None }, (iframeLoaded, redirectUrl)) React.useEffect(() => { // Event listner to check if the session is expired in iframe let handleIframeMessage = event => { let dictFromEvent = event->Identity.genericTypeToJson->getDictFromJsonObject let eventType = dictFromEvent ->getString("data", "") ->safeParse ->getDictFromJsonObject ->getString("event", "") ->ReconUtils.getEventTypeFromString let status = dictFromEvent ->getString("data", "") ->safeParse ->getDictFromJsonObject ->getString("AuthenticationStatus", "") ->ReconUtils.getAuthStatusFromMessage if eventType == AuthenticationStatus && status == IframeLoggedOut { handleLogout()->ignore } } Window.addEventListener("message", handleIframeMessage) Some(() => Window.removeEventListener("message", handleIframeMessage)) }, []) <> { switch iframeRef.current->Js.Nullable.toOption { | Some(iframeEl) => { let tokenDict = [("token", redirectToken->JSON.Encode.string)]->Dict.fromArray let dict = [ ("eventType", "AuthenticationDetails"->JSON.Encode.string), ("payload", tokenDict->JSON.Encode.object), ]->Dict.fromArray iframeEl->IframeUtils.iframePostMessage(dict) } | None => () } <PageLoaderWrapper screenState> {if redirectToken->isNonEmptyString { <div className="h-85-vh overflow-scroll"> <iframe onLoad={_ => { setIframeLoaded(_ => true) }} id="recon-module" className="h-full w-full" src={`${Window.env.reconIframeUrl->Option.getOr("")}/${redirectUrl}`} height="100%" width="100%" ref={iframeRef->ReactDOM.Ref.domRef} /> </div> } else { <div className={`bg-white dark:bg-jp-gray-lightgray_background border-2 rounded dark:border-jp-gray-850 grid grid-cols-1 md:gap-5 p-2 md:p-8 h-2/3 items-center`}> <div className={`flex flex-col items-center w-4/6 md:w-2/6 justify-self-center gap-1`}> <div className={`text-center text-semibold text-s text-grey-700 opacity-60 dark:text-white`}> {"If you encounter any errors, please refresh the page to resolve the issue."->React.string} </div> <Button text="Refresh recon tab" buttonType={Primary} customButtonStyle="w-2/3 rounded-sm !bg-jp-blue-button_blue border border-jp-blue-border_blue mt-4" buttonSize={Small} buttonState={Normal} onClick={_v => { getReconToken()->ignore }} /> </div> </div> }} </PageLoaderWrapper> } </> }
1,027
9,539
hyperswitch-control-center
src/screens/SetupAccount/HSwitchSetupAccountUtils.res
.res
type stepCounterTypes = [ | #INITIALIZE | #CONNECTORS_CONFIGURED | #ROUTING_ENABLED | #GENERATE_SAMPLE_DATA | #COMPLETED ] let delayTime = 2000 let listOfStepCounter: array<stepCounterTypes> = [ #INITIALIZE, #CONNECTORS_CONFIGURED, #ROUTING_ENABLED, #GENERATE_SAMPLE_DATA, #COMPLETED, ] let constructBody = (~connectorName, ~json, ~profileId) => { open LogicUtils open ConnectorUtils let connectorAccountDict = json->getDictFromJsonObject->getDictfromDict("connector_auth") let bodyType = connectorAccountDict->Dict.keysToArray->Array.get(0)->Option.getOr("") let connectorAccountDetails = [ ("auth_type", bodyType->JSON.Encode.string), ("api_key", "test"->JSON.Encode.string), ]->getJsonFromArrayOfJson let initialValueForPayload = generateInitialValuesDict( ~values=[ ("profile_id", profileId->JSON.Encode.string), ("connector_account_details", connectorAccountDetails), ("connector_label", `${connectorName}_default`->JSON.Encode.string), ]->getJsonFromArrayOfJson, ~connector=connectorName, ~bodyType, ) let creditCardNetworkArray = json ->getDictFromJsonObject ->getArrayFromDict("credit", []) ->JSON.Encode.array ->getPaymentMethodMapper let debitCardNetworkArray = json ->getDictFromJsonObject ->getArrayFromDict("debit", []) ->JSON.Encode.array ->getPaymentMethodMapper let payLaterArray = json ->getDictFromJsonObject ->getArrayFromDict("pay_later", []) ->JSON.Encode.array ->getPaymentMethodMapper let walletArray = json ->getDictFromJsonObject ->getArrayFromDict("wallet", []) ->JSON.Encode.array ->getPaymentMethodMapper let paymentMethodsEnabledArray: array<ConnectorTypes.paymentMethodEnabled> = [ { payment_method: "card", payment_method_type: "credit", provider: [], card_provider: creditCardNetworkArray, }, { payment_method: "card", payment_method_type: "debit", provider: [], card_provider: debitCardNetworkArray, }, { payment_method: "pay_later", payment_method_type: "pay_later", provider: payLaterArray, card_provider: [], }, { payment_method: "wallet", payment_method_type: "wallet", provider: walletArray, card_provider: [], }, ] let requestPayload: ConnectorTypes.wasmRequest = { payment_methods_enabled: paymentMethodsEnabledArray, connector: connectorName, } let requestPayloadDict = requestPayload->constructConnectorRequestBody(initialValueForPayload) requestPayloadDict } type routingData = { connector_name: string, merchant_connector_id: string, } let constructRoutingPayload = (routingData: routingData) => { let innerRoutingDict = [ ("connector", routingData.connector_name->JSON.Encode.string), ("merchant_connector_id", routingData.merchant_connector_id->JSON.Encode.string), ]->LogicUtils.getJsonFromArrayOfJson [("split", 50.0->JSON.Encode.float), ("connector", innerRoutingDict)] ->Dict.fromArray ->JSON.Encode.object } let routingPayload = (profileId, routingData1: routingData, routingData2: routingData) => { let payload = [constructRoutingPayload(routingData1), constructRoutingPayload(routingData2)] RoutingUtils.getRoutingPayload( payload, "volume_split", "Initial volume based routing setup", "Volume based routing pre-configured by Hyperswitch", profileId, )->JSON.Encode.object }
855
9,540
hyperswitch-control-center
src/screens/SetupAccount/HSwitchSetupAccount.res
.res
@react.component let make = () => { open HSwitchSetupAccountUtils open APIUtils open HyperSwitchUtils let updateDetails = useUpdateMethod(~showErrorToast=false) let finalTickLottieFile = LottieFiles.useLottieJson("FinalTick.json") let (stepCounter, setStepCounter) = React.useState(_ => #INITIALIZE) let fetchConnectorListResponse = ConnectorListHook.useFetchConnectorList() let getURL = useGetURL() let activeBusinessProfile = HyperswitchAtom.businessProfilesAtom ->Recoil.useRecoilValueFromAtom ->MerchantAccountUtils.getValueFromBusinessProfile let indexOfStepCounterVal = listOfStepCounter->Array.indexOf(stepCounter) let { dashboardPageState, setDashboardPageState, integrationDetails, setIntegrationDetails, } = React.useContext(GlobalProvider.defaultContext) React.useEffect(() => { if dashboardPageState !== #HOME { RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/setup-account")) } None }, [dashboardPageState]) let apiCalls = async () => { try { open LogicUtils let url = getURL(~entityName=V1(CONNECTOR), ~methodType=Post) // * STRIPE && PAYPAL TEST let stripeTestBody = constructBody( ~connectorName="stripe_test", ~json=Window.getConnectorConfig("stripe_test"), ~profileId=activeBusinessProfile.profile_id, ) let stripeTest = (await updateDetails(url, stripeTestBody, Post))->getDictFromJsonObject let stripeTestRes = ConnectorInterface.mapDictToConnectorPayload( ConnectorInterface.connectorInterfaceV1, stripeTest, ) let paypalTestBody = constructBody( ~connectorName="paypal_test", ~json=Window.getConnectorConfig("paypal_test"), ~profileId=activeBusinessProfile.profile_id, ) let payPalTest = (await updateDetails(url, paypalTestBody, Post))->getDictFromJsonObject let payPalTestRes = ConnectorInterface.mapDictToConnectorPayload( ConnectorInterface.connectorInterfaceV1, payPalTest, ) let _ = await fetchConnectorListResponse() setStepCounter(_ => #CONNECTORS_CONFIGURED) // *ROUTING let payPalTestRouting = { connector_name: "paypal_test", merchant_connector_id: payPalTestRes.merchant_connector_id, } let stripTestRouting = { connector_name: "stripe_test", merchant_connector_id: stripeTestRes.merchant_connector_id, } let routingUrl = getURL(~entityName=V1(ROUTING), ~methodType=Post, ~id=None) let activatingId = ( await updateDetails( routingUrl, activeBusinessProfile.profile_id->routingPayload(stripTestRouting, payPalTestRouting), Post, ) ) ->getDictFromJsonObject ->getOptionString("id") let activateRuleURL = getURL(~entityName=V1(ROUTING), ~methodType=Post, ~id=activatingId) let _ = await updateDetails(activateRuleURL, Dict.make()->JSON.Encode.object, Post) setStepCounter(_ => #ROUTING_ENABLED) // *GENERATE_SAMPLE_DATA let generateSampleDataUrl = getURL(~entityName=V1(GENERATE_SAMPLE_DATA), ~methodType=Post) let _ = await updateDetails(generateSampleDataUrl, Dict.make()->JSON.Encode.object, Post) setStepCounter(_ => #GENERATE_SAMPLE_DATA) await delay(delayTime) setStepCounter(_ => #COMPLETED) await delay(delayTime) let body = HSwitchUtils.constructOnboardingBody( ~dashboardPageState, ~integrationDetails, ~is_done=true, ) let integrationUrl = getURL(~entityName=V1(INTEGRATION_DETAILS), ~methodType=Post) let _ = await updateDetails(integrationUrl, body, Post) setIntegrationDetails(_ => body->ProviderHelper.getIntegrationDetails) setDashboardPageState(_ => #INTEGRATION_DOC) } catch { | _ => { await delay(delayTime - 1000) setDashboardPageState(_ => #HOME) } } } let getDetails = async () => { if activeBusinessProfile.profile_id->LogicUtils.isNonEmptyString { apiCalls()->ignore } } React.useEffect(() => { getDetails()->ignore None }, []) if indexOfStepCounterVal <= 3 { <div className="flex flex-col gap-5 items-center justify-center h-screen w-screen"> <Loader /> <div className="font-bold text-xl"> {React.string("Setting up your control center")} </div> </div> } else { <div className="flex flex-col justify-center items-center h-screen w-screen"> <ReactSuspenseWrapper> <Lottie animationData={finalTickLottieFile} autoplay=true loop=false /> </ReactSuspenseWrapper> <div className="font-semibold text-2xl"> {React.string("Setup complete")} </div> </div> } }
1,131
9,541
hyperswitch-control-center
src/screens/Home/Home.res
.res
@react.component let make = (~setAppScreenState) => { open HomeUtils open PageUtils let greeting = getGreeting() let {userInfo: {recoveryCodesLeft}} = React.useContext(UserInfoProvider.defaultContext) let recoveryCode = recoveryCodesLeft->Option.getOr(0) <> <div className="flex flex-col gap-4"> <RenderIf condition={recoveryCodesLeft->Option.isSome && recoveryCode < 3}> <HomeUtils.LowRecoveryCodeBanner recoveryCode /> </RenderIf> <PendingInvitationsHome setAppScreenState /> </div> <div className="w-full gap-8 flex flex-col"> <PageHeading title={`${greeting}, it's great to see you!`} subTitle="Welcome to the home of your Payments Control Centre. It aims at providing your team with a 360-degree view of payments." /> <ControlCenter /> <DevResources /> </div> </> }
216
9,542
hyperswitch-control-center
src/screens/Home/HomeUtils.res
.res
open CardUtils open PageUtils open HSwitchUtils let headingStyle = `${getTextClass((P2, Medium))} text-grey-700 uppercase opacity-50 px-2` let paragraphTextVariant = `${getTextClass((P2, Medium))} text-grey-700 opacity-50` let subtextStyle = `${getTextClass((P1, Regular))} text-grey-700 opacity-50` let cardHeaderText = getTextClass((H3, Leading_2)) let hoverStyle = "cursor-pointer group-hover:shadow hover:shadow-homePageBoxShadow group" let boxCssHover = (~ishoverStyleRequired) => `flex flex-col bg-white border rounded-md pt-10 pl-10 gap-2 h-12.5-rem ${ishoverStyleRequired ? hoverStyle : ""}` let boxCss = "flex flex-col bg-white border rounded-md gap-4 p-7" let imageTransitionCss = "opacity-50 group-hover:opacity-100 transition ease-in-out duration-300" let cardHeaderTextStyle = `${cardHeaderText} text-grey-700` type resourcesTypes = { icon: string, headerText: string, subText: string, redirectLink: string, id: string, access: CommonAuthTypes.authorization, } let countries: array<ReactHyperJs.country> = [ { isoAlpha3: "USA", currency: "USD", countryName: "United States", isoAlpha2: "US", }, { isoAlpha3: "CHE", currency: "CHF", countryName: "Switzerland", isoAlpha2: "CH", }, { isoAlpha3: "DEU", currency: "EUR", countryName: "Germany", isoAlpha2: "DE", }, { isoAlpha3: "NLD", currency: "EUR", countryName: "Netherlands", isoAlpha2: "NL", }, { isoAlpha3: "AUS", currency: "AUD", countryName: "Australia", isoAlpha2: "AU", }, { isoAlpha3: "AUT", currency: "EUR", countryName: "Austria", isoAlpha2: "AT", }, { isoAlpha3: "GBR", currency: "GBP", countryName: "United Kingdom", isoAlpha2: "GB", }, { isoAlpha3: "CAN", currency: "CAD", countryName: "Canada", isoAlpha2: "CA", }, { isoAlpha3: "PLN", currency: "PLN", countryName: "Poland", isoAlpha2: "PL", }, { isoAlpha3: "CHN", currency: "CNY", countryName: "China", isoAlpha2: "CN", }, { isoAlpha3: "SWE", currency: "SEK", countryName: "Sweden", isoAlpha2: "SE", }, { isoAlpha3: "HKG", currency: "HKD", countryName: "Hongkong", isoAlpha2: "HK", }, ] let isDefaultBusinessProfile = details => details->Array.length === 1 module MerchantAuthInfo = { @react.component let make = () => { let merchantDetailsValue = useMerchantDetailsValue() let dataDict = [ ("merchant_id", merchantDetailsValue.merchant_id->JSON.Encode.string), ("publishable_key", merchantDetailsValue.publishable_key->JSON.Encode.string), ]->Dict.fromArray <Form initialValues={dataDict->JSON.Encode.object} formClass="md:ml-9 my-4"> <div className="flex flex-col lg:flex-row gap-3"> <div> <div className="font-semibold text-dark_black md:text-base text-sm"> {"Merchant ID"->React.string} </div> <div className="flex items-center"> <div className="font-medium text-dark_black opacity-40" style={overflowWrap: "anywhere"}> {merchantDetailsValue.merchant_id->React.string} </div> <CopyFieldValue fieldkey="merchant_id" /> </div> </div> <div> <div className="font-semibold text-dark_black md:text-base text-sm"> {"Publishable Key"->React.string} </div> <div className="flex items-center"> <div className="font-medium text-dark_black opacity-40" style={overflowWrap: "anywhere"}> {merchantDetailsValue.publishable_key->React.string} </div> <CopyFieldValue fieldkey="publishable_key" /> </div> </div> </div> </Form> } } module CheckoutCard = { @react.component let make = () => { let showPopUp = PopUpState.useShowPopUp() let mixpanelEvent = MixpanelHook.useSendEvent() let handleLogout = APIUtils.useHandleLogout() let {userHasAccess, hasAllGroupsAccess} = GroupACLHooks.useUserGroupACLHook() let isPlayground = HSLocalStorage.getIsPlaygroundFromLocalStorage() let connectorList = ConnectorInterface.useConnectorArrayMapper( ~interface=ConnectorInterface.connectorInterfaceV1, ) let isConfigureConnector = connectorList->Array.length > 0 let handleOnClick = _ => { if isPlayground { showPopUp({ popUpType: (Warning, WithIcon), heading: "Sign Up to Access All Features!", description: { "To unlock the potential and experience the full range of capabilities, simply sign up today. Join our community of explorers and gain access to an enhanced world of possibilities"->React.string }, handleConfirm: { text: "Sign up Now", onClick: { _ => handleLogout()->ignore }, }, }) } else { mixpanelEvent(~eventName=`try_test_payment`) RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url="/sdk")) } } let (title, description) = isConfigureConnector ? ( "Make a test payment - Try our unified checkout", "Test your connector by making a payment and visualise the user checkout experience", ) : ( "Demo our checkout experience", "Visualise the checkout experience by putting yourself in your user's shoes.", ) <CardLayout width="w-full md:w-1/2"> <CardHeader heading=title subHeading=description leftIcon=Some("checkout") /> <img alt="sdk" className="w-10/12 -mt-7 hidden md:block" src="/assets/sdk.svg" /> <CardFooter customFooterStyle="!m-1 !mt-2"> <ACLButton text="Try it out" authorization={hasAllGroupsAccess([ userHasAccess(~groupAccess=OperationsManage), userHasAccess(~groupAccess=ConnectorsManage), ])} buttonType={Secondary} buttonSize={Medium} onClick={handleOnClick} /> </CardFooter> </CardLayout> } } module ControlCenter = { @react.component let make = () => { let {isLiveMode} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let {checkUserEntity} = React.useContext(UserInfoProvider.defaultContext) let mixpanelEvent = MixpanelHook.useSendEvent() let isLiveModeEnabledStyles = isLiveMode ? "flex flex-col md:flex-row gap-5 w-full" : "flex flex-col gap-5 md:w-1/2 w-full" <div className="flex flex-col gap-5 md:flex-row"> <RenderIf condition={!isLiveMode}> <CheckoutCard /> </RenderIf> <div className=isLiveModeEnabledStyles> <CardLayout width="w-full" customStyle={isLiveMode ? "" : "h-4/6"}> <CardHeader heading="Integrate a connector" subHeading="Give a headstart to the control centre by connecting with more than 20+ gateways, payment methods, and networks." leftIcon=Some("connector") /> <CardFooter customFooterStyle="mt-5"> <Button text="+ Connect" buttonType={Secondary} buttonSize={Medium} onClick={_ => { RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="/connectors")) }} /> <img alt="connector-list" className="inline-block absolute bottom-0 right-0 lg:block lg:w-40 md:w-24 w-24" src="/assets/connectorsList.svg" /> </CardFooter> </CardLayout> <RenderIf condition={!checkUserEntity([#Profile])}> <CardLayout width="w-full" customStyle={isLiveMode ? "" : "h-3/6"}> <CardHeader heading="Credentials and Keys" subHeading="Your secret credentials to start integrating" leftIcon=Some("merchantInfo") customSubHeadingStyle="w-full max-w-none" /> <MerchantAuthInfo /> <CardFooter customFooterStyle="lg:-mt-0 lg:mb-12"> <Button text="Go to API keys" buttonType={Secondary} buttonSize={Medium} onClick={_ => { mixpanelEvent(~eventName="redirect_to_api_keys") RescriptReactRouter.push( GlobalVars.appendDashboardPath(~url="/developer-api-keys"), ) }} /> </CardFooter> </CardLayout> </RenderIf> </div> </div> } } module DevResources = { @react.component let make = () => { let mixpanelEvent = MixpanelHook.useSendEvent() <div className="mb-5"> <PageHeading title="Developer resources" subTitle="Couple of things developers need in handy can be found right here." /> <div className="flex flex-col md:flex-row gap-5"> <CardLayout width="w-full"> <CardHeader heading="Developer docs" subHeading="Everything you need to know to get the SDK up and running resides in here." leftIcon=Some("docs") /> <CardFooter customFooterStyle="mt-5"> <Button text="Visit" buttonType={Secondary} buttonSize={Medium} onClick={_ => { mixpanelEvent(~eventName=`dev_docs`) "https://hyperswitch.io/docs"->Window._open }} /> </CardFooter> </CardLayout> <CardLayout width="w-full"> <CardHeader heading="Product and tech blog" subHeading="Learn about payments, payment orchestration and all the tech behind it." leftIcon=Some("blogs") /> <CardFooter customFooterStyle="mt-5"> <Button text="Explore" buttonType={Secondary} buttonSize={Medium} onClick={_ => { mixpanelEvent(~eventName=`dev_tech_blog`) "https://hyperswitch.io/blog"->Window._open }} /> </CardFooter> </CardLayout> </div> </div> } } let getGreeting = () => { let dateTime = Date.now() let hours = Js.Date.fromFloat(dateTime)->Js.Date.getHours->Int.fromFloat if hours < 12 { "Good morning" } else if hours < 18 { "Good afternoon" } else { "Good evening" } } let homepageStepperItems = ["Configure control center", "Integrate into your app", "Go Live"] let responseDataMapper = (res: JSON.t, mapper: (Dict.t<JSON.t>, string) => JSON.t) => { open LogicUtils let arrayFromJson = res->getArrayFromJson([]) let resDict = Dict.make() arrayFromJson->Array.forEach(value => { let value1 = value->getDictFromJsonObject let key = value1->Dict.keysToArray->Array.get(0)->Option.getOr("") resDict->Dict.set(key, value1->mapper(key)) }) resDict } module LowRecoveryCodeBanner = { @react.component let make = (~recoveryCode) => { <HSwitchUtils.AlertBanner bannerText={`You are low on recovery-codes. Only ${recoveryCode->Int.toString} left.`} bannerType=Warning> <Button text="Regenerate recovery-codes" buttonType={Secondary} onClick={_ => RescriptReactRouter.push( GlobalVars.appendDashboardPath(~url=`/account-settings/profile`), )} /> </HSwitchUtils.AlertBanner> } }
2,841
9,543
hyperswitch-control-center
src/screens/Home/ProdIntent/ProdVerifyModal.res
.res
open ProdVerifyModalUtils open CardUtils @react.component let make = ( ~showModal, ~setShowModal, ~initialValues=Dict.make(), ~getProdVerifyDetails, ~productType: ProductTypes.productTypes, ) => { open APIUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let showToast = ToastState.useShowToast() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Success) let (isSubmitBtnDisabled, setIsSubmitBtnDisabled) = React.useState(_ => false) let {setShowProdIntentForm} = React.useContext(GlobalProvider.defaultContext) let mixpanelEvent = MixpanelHook.useSendEvent() let {userInfo: {version}} = React.useContext(UserInfoProvider.defaultContext) let updateProdDetails = async values => { try { let url = getURL(~entityName=V1(USERS), ~userType=#USER_DATA, ~methodType=Post) let bodyValues = values->getBody->JSON.Encode.object bodyValues ->LogicUtils.getDictFromJsonObject ->Dict.set("product_type", (Obj.magic(productType) :> string)->JSON.Encode.string) let body = [("ProdIntent", bodyValues)]->LogicUtils.getJsonFromArrayOfJson let _ = await updateDetails(url, body, Post) showToast( ~toastType=ToastSuccess, ~message="Successfully sent for verification!", ~autoClose=true, ) setScreenState(_ => Success) getProdVerifyDetails()->ignore setShowProdIntentForm(_ => false) } catch { | _ => setShowModal(_ => false) } Nullable.null } let onSubmit = (values, _) => { mixpanelEvent(~eventName="create_get_production_access_request") setScreenState(_ => PageLoaderWrapper.Loading) updateProdDetails(values) } let modalBody = { <> <div className="p-2 m-2"> <div className="py-5 px-3 flex justify-between align-top"> <CardHeader heading="Get access to Live environment" subHeading="We require some details for business verification. Once verified, our team will reach out and provide live credentials within a business day " 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> <div className="min-h-96"> <PageLoaderWrapper screenState sectionHeight="h-30-vh"> <Form key="prod-request-form" initialValues={initialValues->JSON.Encode.object} validate={values => values->validateForm(~fieldsToValidate=formFields)} onSubmit> <div className="flex flex-col gap-12 h-full w-full"> <FormRenderer.DesktopRow> <div className="flex flex-col gap-5"> {formFields ->Array.mapWithIndex((column, index) => <FormRenderer.FieldRenderer key={index->Int.toString} fieldWrapperClass="w-full" field={column->getFormField} errorClass labelClass="!text-black font-medium !-ml-[0.5px]" /> ) ->React.array} </div> </FormRenderer.DesktopRow> <div className="flex justify-end w-full pr-5 pb-3"> <FormRenderer.SubmitButton text="Book a call" buttonSize={Small} /> </div> </div> </Form> </PageLoaderWrapper> </div> </div> </> } <Modal showModal closeOnOutsideClick=true setShowModal childClass="p-0" borderBottom=true modalClass="w-full max-w-2xl mx-auto my-auto dark:!bg-jp-gray-lightgray_background"> modalBody </Modal> }
904
9,544
hyperswitch-control-center
src/screens/Home/ProdIntent/ProdIntentForm.res
.res
@react.component let make = (~isFromMilestoneCard=false, ~productType: ProductTypes.productTypes) => { open APIUtils open ProdVerifyModalUtils open CommonAuthHooks let fetchDetails = useGetMethod() let getURL = useGetURL() let {email} = useCommonAuthInfo()->Option.getOr(defaultAuthInfo) let {showProdIntentForm, setShowProdIntentForm, setIsProdIntentCompleted} = React.useContext( GlobalProvider.defaultContext, ) let {userInfo: {version, merchantId}} = React.useContext(UserInfoProvider.defaultContext) let (initialValues, setInitialValues) = React.useState(_ => Dict.make()) let getProdVerifyDetails = async () => { open LogicUtils try { let url = getURL( ~entityName=V1(USERS), ~userType=#USER_DATA, ~methodType=Get, ~queryParamerters=Some(`keys=ProdIntent`), ) let res = await fetchDetails(url) let firstValueFromArray = res->getArrayFromJson([])->getValueFromArray(0, JSON.Encode.null) let valueForProdIntent = firstValueFromArray->getDictFromJsonObject->getDictfromDict("ProdIntent") let hideHeader = valueForProdIntent->getBool(IsCompleted->getStringFromVariant, false) if !hideHeader { valueForProdIntent->Dict.set(POCemail->getStringFromVariant, email->JSON.Encode.string) } setIsProdIntentCompleted(_ => Some(hideHeader)) setInitialValues(_ => valueForProdIntent) } catch { | _ => () } } React.useEffect(() => { getProdVerifyDetails()->ignore None }, [merchantId]) <ProdVerifyModal showModal={showProdIntentForm} setShowModal={setShowProdIntentForm} initialValues getProdVerifyDetails productType /> }
426
9,545
hyperswitch-control-center
src/screens/Home/ProdIntent/ProdVerifyModalUtils.res
.res
let errorClass = "text-sm leading-4 font-medium text-start ml-1 mt-2" type prodFormColumnType = | POCemail | IsCompleted | BusinessName | Country | Website | POCName let getStringFromVariant = key => { switch key { | POCemail => "poc_email" | IsCompleted => "is_completed" | BusinessName => "legal_business_name" | Country => "business_location" | Website => "business_website" | POCName => "poc_name" } } let businessName = FormRenderer.makeFieldInfo( ~label="Legal Business Name", ~name=BusinessName->getStringFromVariant, ~placeholder="Eg: HyperSwitch Pvt Ltd", ~customInput=InputFields.textInput(), ~isRequired=true, ) let website = FormRenderer.makeFieldInfo( ~label="Business Website", ~name=Website->getStringFromVariant, ~placeholder="Enter a website", ~customInput=InputFields.textInput(), ~isRequired=true, ) let pocName = FormRenderer.makeFieldInfo( ~label="Contact Name", ~name=POCName->getStringFromVariant, ~placeholder="Eg: Jack Ryan", ~customInput=InputFields.textInput(), ~isRequired=true, ) let pocEmail = FormRenderer.makeFieldInfo( ~label="Contact Email", ~name=POCemail->getStringFromVariant, ~placeholder="Eg: jackryan@hyperswitch.io", ~customInput=InputFields.textInput(), ~isRequired=true, ) let countryField = FormRenderer.makeFieldInfo( ~label="Business Country", ~isRequired=true, ~name=Country->getStringFromVariant, ~customInput=InputFields.selectInput( ~deselectDisable=true, ~fullLength=true, ~customStyle="max-h-48", ~customButtonStyle="pr-3", ~options=CountryUtils.countriesList->Array.map(CountryUtils.getCountryOption), ~buttonText="Select Country", ), ) let validateEmptyValue = (key, errors) => { switch key { | POCemail => Dict.set( errors, key->getStringFromVariant, "Please enter a Point of Contact Email"->JSON.Encode.string, ) | BusinessName => Dict.set(errors, key->getStringFromVariant, "Please enter a Business Name"->JSON.Encode.string) | Country => Dict.set(errors, key->getStringFromVariant, "Please select a Country"->JSON.Encode.string) | Website => Dict.set(errors, key->getStringFromVariant, "Please enter a Website"->JSON.Encode.string) | POCName => Dict.set( errors, key->getStringFromVariant, "Please enter a Point of Contact Name"->JSON.Encode.string, ) | _ => () } } let getFormField = columnType => { switch columnType { | POCemail => pocEmail | BusinessName => businessName | Website => website | POCName => pocName | _ => countryField } } let formFields = [BusinessName, Country, Website, POCName, POCemail] let formFieldsForQuickStart = [BusinessName, Country, Website, POCName, POCemail] let validateCustom = (key, errors, value) => { switch key { | POCemail => if value->HSwitchUtils.isValidEmail { Dict.set(errors, key->getStringFromVariant, "Please enter valid email id"->JSON.Encode.string) } | Website => if ( !RegExp.test( %re("/^(https?:\/\/)?([A-Za-z0-9-]+\.)*[A-Za-z0-9-]{1,63}\.[A-Za-z]{2,6}$/i"), value, ) || value->String.includes("localhost") ) { Dict.set(errors, key->getStringFromVariant, "Please Enter Valid URL"->JSON.Encode.string) } | _ => () } } let validateForm = (values, ~fieldsToValidate: array<prodFormColumnType>) => { open LogicUtils let errors = Dict.make() let valuesDict = values->getDictFromJsonObject fieldsToValidate->Array.forEach(key => { let value = LogicUtils.getString(valuesDict, key->getStringFromVariant, "") value->String.length < 1 ? key->validateEmptyValue(errors) : key->validateCustom(errors, value) }) errors->JSON.Encode.object } let getJsonString = (valueDict, key) => { open LogicUtils valueDict->getString(key->getStringFromVariant, "")->JSON.Encode.string } let getBody = (values: JSON.t) => { open LogicUtils let valuesDict = values->getDictFromJsonObject let prodOnboardingpayload = Dict.make() prodOnboardingpayload->setOptionString( POCemail->getStringFromVariant, valuesDict->getOptionString(POCemail->getStringFromVariant), ) prodOnboardingpayload->setOptionBool(IsCompleted->getStringFromVariant, Some(true)) prodOnboardingpayload->setOptionString( BusinessName->getStringFromVariant, valuesDict->getOptionString(BusinessName->getStringFromVariant), ) prodOnboardingpayload->setOptionString( Country->getStringFromVariant, valuesDict->getOptionString(Country->getStringFromVariant), ) prodOnboardingpayload->setOptionString( Website->getStringFromVariant, valuesDict->getOptionString(Website->getStringFromVariant), ) prodOnboardingpayload->setOptionString( POCName->getStringFromVariant, valuesDict->getOptionString(POCName->getStringFromVariant), ) prodOnboardingpayload }
1,272
9,546
hyperswitch-control-center
src/screens/AlternatePaymentMethods/AltPaymentMethodsUtils.res
.res
open AltPaymentMethodsType let alternatePaymentConfiguration = [ { heading: "Enable Connectors & APMs", description: <span> {"Connect to your preferred payment providers and activate options like PayPal, Apple Pay, and other popular alternate payment methods."->React.string} </span>, buttonText: "Configure it", action: InternalRoute("/connectors"), }, { heading: "Integrate Hyperwidgets: Dual Checkout Experience", description: <div className="flex flex-col gap-4"> <ul className="list-disc pl-4 flex flex-col gap-2 mt-2"> <li> <span className="font-bold"> {"Unified Checkout"->React.string} </span> {": Access all supported APMs through our standard integration within your checkout flow"->React.string} </li> <li> <span className="font-bold"> {"Express Checkout"->React.string} </span> {": Enable one-click purchasing with automatic shipping information retrieval before customers reach checkout"->React.string} </li> </ul> </div>, buttonText: "Learn More", action: ExternalLink({ url: "https://docs.hyperswitch.io/explore-hyperswitch/merchant-controls/integration-guide/web/node-and-react", trackingEvent: "dev_docs", }), }, { heading: "Customize SDK Integration", description: <span> {"Tailor the SDK to your specific needs and branding for a consistent user experience."->React.string} </span>, buttonText: "Customize SDK", action: ExternalLink({ url: "https://docs.hyperswitch.io/explore-hyperswitch/merchant-controls/integration-guide/web/customization", trackingEvent: "dev_docs", }), }, { heading: "Enable Automatic Tax Calculation", description: <span> {"Ensure accurate and dynamic tax collection for Express Checkout wallets using TaxJar."->React.string} </span>, buttonText: "Setup TaxJar", action: ExternalLink({ url: "https://docs.hyperswitch.io/explore-hyperswitch/e-commerce-platform-plugins/automatic-tax-calculation-for-express-checkout-wallets", trackingEvent: "dev_docs", }), }, ] module APMConfigureStep = { @react.component let make = (~index, ~heading, ~description, ~action, ~buttonText) => { let mixpanelEvent = MixpanelHook.useSendEvent() <div className="flex flex-row gap-10 items-center justify-between p-4 rounded-xl shadow-cardShadow border border-nd_br_gray-500 cursor-pointer"> <div className="flex flex-row gap-4 items-start w-3/4"> <div className="w-6 h-6 rounded-full bg-nd_gray-150 flex items-center justify-center text-sm p-1 text-nd_gray-600 font-semibold"> {(index + 1)->React.int} </div> <div className="w-full gap-4 "> <div className="flex flex-col gap-1"> <span className="text-fs-16 text-nd_gray-700 font-semibold leading-24"> {heading->React.string} </span> <span className="text-fs-14 text-nd_gray-500 font-medium"> {description} </span> </div> </div> </div> <Button text=buttonText buttonType={Secondary} buttonSize={Medium} customButtonStyle="w-44" onClick={_ => { switch action { | InternalRoute(route) => RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url=route)) | ExternalLink({url, trackingEvent}) => { mixpanelEvent(~eventName=trackingEvent) url->Window._open } } }} /> </div> } }
864
9,547
hyperswitch-control-center
src/screens/AlternatePaymentMethods/AltPaymentMethodsType.res
.res
type actionType = | InternalRoute(string) | ExternalLink({url: string, trackingEvent: string}) type altConfigureStep = { heading: string, description: React.element, action: actionType, buttonText: string, }
53
9,548
hyperswitch-control-center
src/screens/AlternatePaymentMethods/AltPaymentMethods.res
.res
@react.component let make = () => { open PageUtils open AltPaymentMethodsUtils <div className="flex flex-1 flex-col gap-8 w-5/6 h-screen"> <PageHeading customHeadingStyle="gap-2 flex flex-col " title="Alternate Payment Methods" customTitleStyle="text-2xl text-center font-bold text-nd_gray-700 font-600" customSubTitleStyle="text-lg font-medium " subTitle="Augment your existing checkout using any Alternative Payment Method of your choice" /> <div className="w-full h-64 rounded-lg border border-nd_gray-50 gap-2 bg-nd_gray-25 flex justify-center items-center"> <img alt="alternatePaymentMethodsOnboarding" src="/AlternatePaymentMethods/AlternatePaymentMethodsOnboarding.svg" /> </div> <div className="w-full flex flex-col gap-4" /> {alternatePaymentConfiguration ->Array.mapWithIndex((item, idx) => <APMConfigureStep index=idx heading=item.heading description=item.description action=item.action buttonText=item.buttonText /> ) ->React.array} </div> }
279
9,549
hyperswitch-control-center
src/screens/Routing/RoutingStack.res
.res
open APIUtils @react.component let make = (~remainingPath, ~previewOnly=false) => { let getURL = useGetURL() let fetchDetails = useGetMethod() let url = RescriptReactRouter.useUrl() let pathVar = url.path->List.toArray->Array.joinWith("/") let (records, setRecords) = React.useState(_ => []) let (activeRoutingIds, setActiveRoutingIds) = React.useState(_ => []) let (routingType, setRoutingType) = React.useState(_ => []) let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let (tabIndex, setTabIndex) = React.useState(_ => 0) let setCurrentTabName = Recoil.useSetRecoilState(HyperswitchAtom.currentTabNameRecoilAtom) let (widthClass, marginClass) = React.useMemo(() => { previewOnly ? ("w-full", "mx-auto") : ("w-full", "mx-auto ") }, [previewOnly]) let tabs: array<Tabs.tab> = React.useMemo(() => { open Tabs [ { title: "Manage rules", renderContent: () => { records->Array.length > 0 ? <History records activeRoutingIds /> : <DefaultLandingPage height="90%" title="No Routing Rule Configured!" customStyle="py-16" overriddingStylesTitle="text-3xl font-semibold" /> }, }, { title: "Active configuration", renderContent: () => <ActiveRouting routingType />, }, ] }, [routingType]) let fetchRoutingRecords = async activeIds => { try { setScreenState(_ => PageLoaderWrapper.Loading) let routingUrl = `${getURL(~entityName=V1(ROUTING), ~methodType=Get)}?limit=100` let routingJson = await fetchDetails(routingUrl) let configuredRules = routingJson->RoutingUtils.getRecordsObject let recordsData = configuredRules ->Belt.Array.keepMap(JSON.Decode.object) ->Array.map(HistoryEntity.itemToObjMapper) // To sort the data in a format that active routing always comes at top of the table // For ref:https://rescript-lang.org/docs/manual/latest/api/js/array-2#sortinplacewith let sortedHistoryRecords = recordsData ->Array.toSorted((item1, item2) => { if activeIds->Array.includes(item1.id) { -1. } else if activeIds->Array.includes(item2.id) { 1. } else { 0. } }) ->Array.map(Nullable.make) setRecords(_ => sortedHistoryRecords) setScreenState(_ => PageLoaderWrapper.Success) } catch { | Exn.Error(e) => let err = Exn.message(e)->Option.getOr("Failed to Fetch!") setScreenState(_ => PageLoaderWrapper.Error(err)) } } let fetchActiveRouting = async () => { open LogicUtils try { setScreenState(_ => PageLoaderWrapper.Loading) let activeRoutingUrl = getURL(~entityName=V1(ACTIVE_ROUTING), ~methodType=Get) let routingJson = await fetchDetails(activeRoutingUrl) let routingArr = routingJson->getArrayFromJson([]) if routingArr->Array.length > 0 { let currentActiveIds = [] routingArr->Array.forEach(ele => { let id = ele->getDictFromJsonObject->getString("id", "") currentActiveIds->Array.push(id) }) await fetchRoutingRecords(currentActiveIds) setActiveRoutingIds(_ => currentActiveIds) setRoutingType(_ => routingArr) } else { await fetchRoutingRecords([]) let defaultFallback = [("kind", "default"->JSON.Encode.string)]->Dict.fromArray setRoutingType(_ => [defaultFallback->JSON.Encode.object]) setScreenState(_ => PageLoaderWrapper.Success) } } catch { | Exn.Error(e) => let err = Exn.message(e)->Option.getOr("Failed to Fetch!") setScreenState(_ => PageLoaderWrapper.Error(err)) } } React.useEffect(() => { fetchActiveRouting()->ignore None }, (pathVar, url.search)) let getTabName = index => index == 0 ? "active" : "history" <PageLoaderWrapper screenState> <div className={`${widthClass} ${marginClass} gap-2.5`}> <div className="flex flex-col gap-6"> <PageUtils.PageHeading title="Smart routing configuration" subTitle="Smart routing stack helps you to increase success rates and reduce costs by optimising your payment traffic across the various processors in the most customised yet reliable way. Set it up based on the preferred level of control" /> <ActiveRouting.LevelWiseRoutingSection types=[VOLUME_SPLIT, ADVANCED, DEFAULTFALLBACK] onRedirectBaseUrl="routing" /> </div> <RenderIf condition={!previewOnly}> <div className="flex flex-col gap-12"> <EntityScaffold entityName="HyperSwitch Priority Logic" remainingPath renderList={() => <Tabs initialIndex={tabIndex >= 0 ? tabIndex : 0} tabs showBorder=false includeMargin=false lightThemeColor="black" defaultClasses="!w-max flex flex-auto flex-row items-center justify-center px-6 font-semibold text-body" onTitleClick={indx => { setTabIndex(_ => indx) setCurrentTabName(_ => getTabName(indx)) }} />} /> </div> </RenderIf> </div> </PageLoaderWrapper> }
1,266
9,550
hyperswitch-control-center
src/screens/Routing/RoutingTypes.res
.res
type routingType = VOLUME_SPLIT | ADVANCED | DEFAULTFALLBACK | NO_ROUTING type formState = CreateConfig | EditConfig | ViewConfig | EditReplica type status = ACTIVE | APPROVED | PENDING | REJECTED type pageState = Preview | Create | Edit type variantType = Number | Enum_variant | Metadata_value | String_value | UnknownVariant(string) type logicalOperator = AND | OR | UnknownLogicalOperator(string) type val = StringArray(array<string>) | String(string) | Int(int) type historyColType = | Name | Type | Description | Created | LastUpdated | Status type colType = | Name | Description | Status | ConfigType | DateCreated | LastUpdated type operator = | IS | IS_NOT | GREATER_THAN | LESS_THAN | EQUAL_TO | CONTAINS | NOT_CONTAINS | NOT_EQUAL_TO | UnknownOperator(string) type modalValue = {conType: string, conText: React.element} type routingValueType = {heading: string, subHeading: string} type modalObj = (routingType, string) => modalValue type wasmModule = { getAllKeys: unit => array<string>, getAllPayoutKeys: unit => array<string>, getKeyType: string => string, getAllConnectors: unit => array<string>, getVariantValues: string => array<string>, getPayoutVariantValues: string => array<string>, } type gateway = { distribution: int, disableFallback: bool, gateway_name: string, } type volumeDistribution = { connector: string, split: int, } type routingOutputType = {override_3ds: string} type historyData = { id: string, name: string, profile_id: string, kind: string, description: string, modified_at: string, created_at: string, } type value = {\"type": string, value: JSON.t} type filterType = PaymentConnector | FRMPlayer | PayoutProcessor | PMAuthenticationProcessor | TaxProcessor type workFlowTypes = Routing | PayoutRouting | ThreedsRouting | SurchargeRouting type statement = { lhs: string, comparison: string, value: value, logical?: string, metadata?: JSON.t, } type connector = { connector: string, merchant_connector_id: string, } type volumeSplitConnectorSelectionData = { split: int, connector: connector, } type connectorSelectionData = | VolumeObject(volumeSplitConnectorSelectionData) | PriorityObject(connector) type surchargeDetailsSurchargePropertyValueType = {percentage?: float, amount?: float} type surchargeDetailsSurchargePropertyType = { \"type": string, value: surchargeDetailsSurchargePropertyValueType, } type surchargeDetailsType = { surcharge: surchargeDetailsSurchargePropertyType, tax_on_surcharge: surchargeDetailsSurchargePropertyValueType, } type connectorSelection = { \"type"?: string, data?: array<connectorSelectionData>, override_3ds?: string, surcharge_details?: Js.nullable<surchargeDetailsType>, } type rule = { name: string, connectorSelection: connectorSelection, statements: array<statement>, } type algorithmData = { defaultSelection: connectorSelection, rules: array<rule>, metadata: JSON.t, } type algorithm = {data: algorithmData, \"type"?: string} type advancedRouting = { name: string, description: string, algorithm: algorithm, } type statementSendType = {condition: array<statement>} type advancedRoutingType = { name: string, description: string, algorithm: algorithmData, }
819
9,551
hyperswitch-control-center
src/screens/Routing/RoutingUtils.res
.res
open RoutingTypes open LogicUtils external toWasm: Dict.t<JSON.t> => wasmModule = "%identity" let defaultThreeDsObjectValue: routingOutputType = { override_3ds: "three_ds", } let currentTimeInUTC = Js.Date.fromFloat(Date.now())->Js.Date.toUTCString let getCurrentUTCTime = () => { let currentDate = Date.now()->Js.Date.fromFloat let month = currentDate->Js.Date.getUTCMonth +. 1.0 let day = currentDate->Js.Date.getUTCDate let currMonth = month->Float.toString->String.padStart(2, "0") let currDay = day->Float.toString->String.padStart(2, "0") let currYear = currentDate->Js.Date.getUTCFullYear->Float.toString `${currYear}-${currMonth}-${currDay}` } let routingTypeMapper = routingType => { switch routingType { | "volume_split" => VOLUME_SPLIT | "advanced" => ADVANCED | "default" => DEFAULTFALLBACK | _ => NO_ROUTING } } let routingTypeName = routingType => { switch routingType { | VOLUME_SPLIT => "volume" | ADVANCED => "rule" | DEFAULTFALLBACK => "default" | NO_ROUTING => "" } } let getRoutingPayload = (data, routingType, name, description, profileId) => { let connectorsOrder = [("data", data->JSON.Encode.array), ("type", routingType->JSON.Encode.string)]->Dict.fromArray [ ("name", name->JSON.Encode.string), ("description", description->JSON.Encode.string), ("profile_id", profileId->JSON.Encode.string), ("algorithm", connectorsOrder->JSON.Encode.object), ]->Dict.fromArray } let getModalObj = (routingType, text) => { switch routingType { | ADVANCED => { conType: "Activate current configured configuration?", conText: { React.string( `If you want to activate the ${text} configuration, the advanced configuration, set previously will be lost. Are you sure you want to activate it?`, ) }, } | VOLUME_SPLIT => { conType: "Activate current configured configuration?", conText: { React.string( `If you want to activate the ${text} configuration, the volume based configuration, set previously will be lost. Are you sure you want to activate it?`, ) }, } | DEFAULTFALLBACK => { conType: "Save the Current Changes ?", conText: { React.string(`Do you want to save the current changes ?`) }, } | _ => { conType: "Activate Logic", conText: {React.string("Are you sure you want to ACTIVATE the logic?")}, } } } let getContent = routetype => switch routetype { | DEFAULTFALLBACK => { heading: "Default fallback ", subHeading: "Fallback is a priority order of all the configured processors which is used to route traffic standalone or when other routing rules are not applicable. You can reorder the list with simple drag and drop", } | VOLUME_SPLIT => { heading: "Volume Based Configuration", subHeading: "Route traffic across various processors by volume distribution", } | ADVANCED => { heading: "Rule Based Configuration", subHeading: "Route traffic across processors with advanced logic rules on the basis of various payment parameters", } | _ => { heading: "", subHeading: "", } } //Volume let getGatewayTypes = (arr: array<JSON.t>) => { let tempArr = arr->Array.map(value => { let val = value->getDictFromJsonObject let connectorDict = val->getDictfromDict("connector") let tempval = { distribution: val->getInt("split", 0), disableFallback: val->getBool("disableFallback", false), gateway_name: connectorDict->getString("merchant_connector_id", ""), } tempval }) tempArr } // Advanced let valueTypeMapper = dict => { let value = switch Dict.get(dict, "value")->Option.map(JSON.Classify.classify) { | Some(Array(arr)) => StringArray(arr->getStrArrayFromJsonArray) | Some(String(st)) => String(st) | Some(Number(num)) => Int(num->Float.toInt) | _ => String("") } value } let threeDsTypeMapper = dict => { let getRoutingOutputval = dict->getString("override_3ds", "three_ds") let val = { override_3ds: getRoutingOutputval, } val } let constructNameDescription = routingType => { let routingText = routingType->routingTypeName Dict.fromArray([ ( "name", `${routingText->capitalizeString} Based Routing-${getCurrentUTCTime()}`->JSON.Encode.string, ), ( "description", `This is a ${routingText} based routing created at ${currentTimeInUTC}`->JSON.Encode.string, ), ]) } module SaveAndActivateButton = { @react.component let make = ( ~onSubmit: (JSON.t, 'a) => promise<Nullable.t<JSON.t>>, ~handleActivateConfiguration, ) => { let formState: ReactFinalForm.formState = ReactFinalForm.useFormState( ReactFinalForm.useFormSubscription(["values"])->Nullable.make, ) let handleSaveAndActivate = async _ => { try { let onSubmitResponse = await onSubmit(formState.values, false) let currentActivatedFromJson = onSubmitResponse->getValFromNullableValue(JSON.Encode.null) let currentActivatedId = currentActivatedFromJson->getDictFromJsonObject->getString("id", "") let _ = await handleActivateConfiguration(Some(currentActivatedId)) } catch { | Exn.Error(e) => let _ = Exn.message(e)->Option.getOr("Failed to save and activate configuration!") } } <Button text={"Save and Activate Rule"} buttonType={Primary} buttonSize=Button.Small onClick={_ => { handleSaveAndActivate()->ignore }} customButtonStyle="w-1/5 rounded-sm" /> } } module ConfigureRuleButton = { @react.component let make = (~setShowModal) => { let formState: ReactFinalForm.formState = ReactFinalForm.useFormState( ReactFinalForm.useFormSubscription(["values"])->Nullable.make, ) <Button text={"Configure Rule"} buttonType=Primary buttonState={!formState.hasValidationErrors ? Normal : Disabled} onClick={_ => { setShowModal(_ => true) }} customButtonStyle="w-1/5" /> } } let checkIfValuePresent = dict => { let valueFromObject = dict->getDictfromDict("value") valueFromObject ->getArrayFromDict("value", []) ->Array.filter(ele => { ele != ""->JSON.Encode.string }) ->Array.length > 0 || valueFromObject->getString("value", "")->isNonEmptyString || valueFromObject->getFloat("value", -1.0) !== -1.0 || (valueFromObject->getDictfromDict("value")->getString("key", "")->isNonEmptyString && valueFromObject->getDictfromDict("value")->getString("value", "")->isNonEmptyString) } let validateConditionJson = (json, keys) => { switch json->JSON.Decode.object { | Some(dict) => keys->Array.every(key => dict->Dict.get(key)->Option.isSome) && dict->checkIfValuePresent | None => false } } let validateConditionsFor3ds = dict => { let conditionsArray = dict->getArrayFromDict("statements", []) conditionsArray->Array.every(value => { value->validateConditionJson(["comparison", "lhs"]) }) } let getRecordsObject = json => { switch JSON.Classify.classify(json) { | Object(jsonDict) => jsonDict->getArrayFromDict("records", []) | Array(jsonArray) => jsonArray | _ => [] } } let filter = (connector_type, ~retainInList) => { switch retainInList { | PaymentConnector => connector_type === "payment_processor" | FRMPlayer => connector_type === "payment_vas" | PayoutProcessor => connector_type === "payout_processor" | PMAuthenticationProcessor => connector_type === "payment_method_auth" | TaxProcessor => connector_type === "tax_processor" } } let filterConnectorList = (items: array<ConnectorTypes.connectorPayload>, ~retainInList) => { open ConnectorTypes items->Array.filter(connector => connector.connector_type ->ConnectorUtils.connectorTypeTypedValueToStringMapper ->filter(~retainInList) ) } let filterConnectorListJson = (json, ~retainInList) => { json ->getArrayFromJson([]) ->Array.map(getDictFromJsonObject) ->Array.filter(dict => dict->getString("connector_type", "")->filter(~retainInList)) } let filterConnectorListCoreJson = (json, ~retainInList) => { json ->Array.map(getDictFromJsonObject) ->Array.filter(dict => dict->getString("connector_type", "")->filter(~retainInList)) ->Array.map(JSON.Encode.object) } let urlToVariantMapper = (url: RescriptReactRouter.url) => { switch url.path->HSwitchUtils.urlPath { | list{"payoutrouting", _} => PayoutRouting | list{"3ds", _} => ThreedsRouting | list{"surcharge", _} => SurchargeRouting | _ => Routing } }
2,154
9,552
hyperswitch-control-center
src/screens/Routing/CustomModal.res
.res
module RoutingCustomModal = { @react.component let make = ( ~showModal, ~setShowModal, ~cancelButton, ~submitButton, ~headingText, ~subHeadingText, ~leftIcon, ~iconSize=25, ) => { <Modal showModal setShowModal modalClass="w-full md:w-4/12 mx-auto my-auto 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=leftIcon size=iconSize className="w-8" onClick={_ => setShowModal(_ => false)} /> <div className="flex flex-col gap-5"> <p className="font-bold text-2xl"> {headingText->React.string} </p> <p className=" text-hyperswitch_black opacity-50 font-medium"> {subHeadingText->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"> {cancelButton} {submitButton} </div> </Modal> } }
305
9,553
hyperswitch-control-center
src/screens/Routing/BasicDetailsForm.res
.res
open FormRenderer open RoutingTypes open LogicUtils let configurationNameInput = makeFieldInfo( ~label="Configuration Name", ~name="name", ~isRequired=true, ~placeholder="Enter Configuration Name", ~customInput=InputFields.textInput(~autoFocus=true), ) let descriptionInput = makeFieldInfo( ~label="Description", ~name="description", ~isRequired=true, ~placeholder="Add a description for your configuration", ~customInput=InputFields.multiLineTextInput( ~isDisabled=false, ~rows=Some(3), ~cols=None, ~customClass="text-sm", ), ) module BusinessProfileInp = { @react.component let make = (~setProfile, ~profile, ~options, ~label="", ~routingType=ADVANCED) => { let selectedConnectorsInput = ReactFinalForm.useField("algorithm.data").input <FormRenderer.FieldRenderer field={FormRenderer.makeFieldInfo(~label, ~isRequired=true, ~name="profile_id", ~customInput=( ~input, ~placeholder as _, ) => InputFields.selectInput( ~disableSelect={options->Array.length == 1}, ~deselectDisable=true, ~options, ~buttonText="", )( ~input={ ...input, value: profile->JSON.Encode.string, onChange: { ev => { setProfile(_ => ev->Identity.formReactEventToString) input.onChange(ev) let defaultAlgorithm = if routingType == VOLUME_SPLIT { []->Identity.anyTypeToReactEvent } else { AdvancedRoutingUtils.defaultAlgorithmData->Identity.anyTypeToReactEvent } selectedConnectorsInput.onChange(defaultAlgorithm) } }, }, ~placeholder="", ) )} /> } } @react.component let make = ( ~currentTabName="", ~formState=CreateConfig, ~setInitialValues=_ => (), ~isThreeDs=false, ~profile=?, ~setProfile=?, ~routingType=ADVANCED, ~showDescription=true, ) => { open MerchantAccountUtils let ip1 = ReactFinalForm.useField(`name`).input let ip2 = ReactFinalForm.useField(`description`).input let ip3 = ReactFinalForm.useField(`profile_id`).input let businessProfiles = Recoil.useRecoilValueFromAtom(HyperswitchAtom.businessProfilesAtom) let defaultBusinessProfile = businessProfiles->getValueFromBusinessProfile //Need to check if necessary let form = ReactFinalForm.useForm() React.useEffect(() => { form.change( "profile_id", profile->Option.getOr(defaultBusinessProfile.profile_id)->JSON.Encode.string, ) None }, []) <div className={` mb-6 p-4 bg-white dark:bg-jp-gray-lightgray_background rounded-md border border-jp-gray-600 dark:border-jp-gray-850`}> {if formState === ViewConfig { <div> <div className="flex flex-row justify-between gap-4"> <div className="flex flex-row gap-40"> <AddDataAttributes attributes=[("data-field", "Configuration Name")]> <div className="flex flex-col gap-2 items-start justify-between py-2"> <span className="text-gray-500 dark:text-gray-400"> {React.string("Configuration Name")} </span> <AddDataAttributes attributes=[("data-text", getStringFromJson(ip1.value, ""))]> <span className="font-semibold"> {React.string(getStringFromJson(ip1.value, ""))} </span> </AddDataAttributes> </div> </AddDataAttributes> <RenderIf condition=showDescription> <AddDataAttributes attributes=[("data-field", "Description")]> <div className="flex flex-col gap-2 items-start justify-between py-2"> <span className="text-gray-500 dark:text-gray-400"> {React.string("Description")} </span> <AddDataAttributes attributes=[("data-text", getStringFromJson(ip2.value, ""))]> <span className="font-semibold"> {React.string(getStringFromJson(ip2.value, ""))} </span> </AddDataAttributes> </div> </AddDataAttributes> </RenderIf> </div> </div> <div className="flex flex-row justify-between gap-4"> <div className="flex flex-row gap-48"> <AddDataAttributes attributes=[("data-field", "Profile Id")]> <div className="flex flex-col gap-2 items-start justify-between py-2"> <span className="text-gray-500 dark:text-gray-400"> {React.string("Profile")} </span> <AddDataAttributes attributes=[("data-text", getStringFromJson(ip3.value, ""))]> <span className="font-semibold"> <HelperComponents.BusinessProfileComponent profile_id={profile->Option.getOr(defaultBusinessProfile.profile_id)} /> </span> </AddDataAttributes> </div> </AddDataAttributes> </div> </div> </div> } else { <> <div className="flex"> <div className="w-full md:w-1/2 lg:w-1/3"> <RenderIf condition={!isThreeDs}> <BusinessProfileInp setProfile={setProfile->Option.getOr(_ => ())} profile={profile->Option.getOr(defaultBusinessProfile.profile_id)} options={businessProfiles->businessProfileNameDropDownOption} label="Profile" routingType /> </RenderIf> <FieldRenderer field=configurationNameInput /> <RenderIf condition=showDescription> <FieldRenderer field=descriptionInput /> </RenderIf> </div> </div> </> }} </div> }
1,302
9,554
hyperswitch-control-center
src/screens/Routing/HistoryEntity.res
.res
open LogicUtils open RoutingUtils open RoutingTypes let allColumns: array<historyColType> = [Name, Type, Description, Created, LastUpdated, Status] let itemToObjMapper = dict => { { id: getString(dict, "id", ""), name: getString(dict, "name", ""), profile_id: getString(dict, "profile_id", ""), kind: getString(dict, "kind", ""), description: getString(dict, "description", ""), modified_at: getString(dict, "modified_at", ""), created_at: getString(dict, "created_at", ""), } } let defaultColumns: array<historyColType> = [Name, Type, Description, Status] let getHeading: historyColType => Table.header = colType => { switch colType { | Name => Table.makeHeaderInfo(~key="name", ~title="Name of Control") | Type => Table.makeHeaderInfo(~key="kind", ~title="Type of Control") | Description => Table.makeHeaderInfo(~key="description", ~title="Description") | Status => Table.makeHeaderInfo(~key="status", ~title="Status", ~dataType=DropDown) | Created => Table.makeHeaderInfo(~key="created_at", ~title="Created") | LastUpdated => Table.makeHeaderInfo(~key="modified_at", ~title="Last Updated") } } let getTableCell = activeRoutingIds => { let getCell = (historyData: historyData, colType: historyColType): Table.cell => { switch colType { | Name => Text(historyData.name) | Type => Text(`${historyData.kind->routingTypeMapper->routingTypeName->capitalizeString} Based`) | Description => Text(historyData.description) | Created => Text(historyData.created_at) | LastUpdated => Text(historyData.modified_at) | Status => Label({ title: activeRoutingIds->Array.includes(historyData.id) ? "ACTIVE" : "INACTIVE"->String.toUpperCase, color: activeRoutingIds->Array.includes(historyData.id) ? LabelGreen : LabelGray, }) } } getCell } let getHistoryRules: JSON.t => array<historyData> = json => { getArrayDataFromJson(json, itemToObjMapper) } let historyEntity = ( activeRoutingIds: array<string>, ~authorization: CommonAuthTypes.authorization, ) => { EntityType.makeEntity( ~uri=``, ~getObjects=getHistoryRules, ~defaultColumns, ~allColumns, ~getHeading, ~getCell=getTableCell(activeRoutingIds), ~dataKey="records", ~getShowLink={ value => { GroupAccessUtils.linkForGetShowLinkViaAccess( ~url=GlobalVars.appendDashboardPath( ~url=`/routing/${value.kind ->routingTypeMapper ->routingTypeName}?id=${value.id}${activeRoutingIds->Array.includes(value.id) ? "&isActive=true" : ""}`, ), ~authorization, ) } }, ) }
653
9,555
hyperswitch-control-center
src/screens/Routing/RoutingConfigure.res
.res
open RoutingTypes open RoutingUtils @react.component let make = (~routingType) => { open LogicUtils let baseUrlForRedirection = "/routing" let url = RescriptReactRouter.useUrl() let (currentRouting, setCurrentRouting) = React.useState(() => NO_ROUTING) let (id, setId) = React.useState(() => None) let (isActive, setIsActive) = React.useState(_ => false) let connectorList = ConnectorInterface.useConnectorArrayMapper( ~interface=ConnectorInterface.connectorInterfaceV1, ~retainInList=ConnectorTypes.PaymentProcessor, ) React.useEffect(() => { let searchParams = url.search let filtersFromUrl = getDictFromUrlSearchParams(searchParams)->Dict.get("id") setId(_ => filtersFromUrl) switch routingType->String.toLowerCase { | "volume" => setCurrentRouting(_ => VOLUME_SPLIT) | "rule" => setCurrentRouting(_ => ADVANCED) | "default" => setCurrentRouting(_ => DEFAULTFALLBACK) | _ => setCurrentRouting(_ => NO_ROUTING) } let isActive = getDictFromUrlSearchParams(searchParams) ->Dict.get("isActive") ->Option.getOr("") ->getBoolFromString(false) setIsActive(_ => isActive) None }, [url.search]) <div className="flex flex-col overflow-auto gap-2"> <PageUtils.PageHeading title="Smart routing configuration" /> <History.BreadCrumbWrapper pageTitle={getContent(currentRouting).heading} baseLink={"/routing"}> {switch currentRouting { | VOLUME_SPLIT => <VolumeSplitRouting routingRuleId=id isActive connectorList urlEntityName=V1(ROUTING) baseUrlForRedirection /> | ADVANCED => <AdvancedRouting routingRuleId=id isActive setCurrentRouting connectorList urlEntityName=V1(ROUTING) baseUrlForRedirection /> | DEFAULTFALLBACK => <DefaultRouting urlEntityName=V1(DEFAULT_FALLBACK) baseUrlForRedirection connectorVariant=ConnectorTypes.PaymentProcessor /> | _ => <> </> }} </History.BreadCrumbWrapper> </div> }
484
9,556
hyperswitch-control-center
src/screens/Routing/History.res
.res
open HistoryEntity module HistoryTable = { @react.component let make = (~records, ~activeRoutingIds: array<string>) => { let {userHasAccess} = GroupACLHooks.useUserGroupACLHook() let (offset, setOffset) = React.useState(_ => 0) <LoadedTable title="History" hideTitle=true actualData=records entity={historyEntity( activeRoutingIds, ~authorization=userHasAccess(~groupAccess=WorkflowsManage), )} resultsPerPage=10 showSerialNumber=true totalResults={records->Array.length} offset setOffset currrentFetchCount={records->Array.length} /> } } module BreadCrumbWrapper = { @react.component let make = ( ~children, ~pageTitle, ~title="Smart Routing Configuration", ~baseLink="/routing", ) => { <> <BreadCrumbNavigation path=[ { title, link: baseLink, }, ] currentPageTitle={pageTitle} cursorStyle="cursor-pointer" /> {children} </> } } @react.component let make = (~records, ~activeRoutingIds: array<string>) => { <HistoryTable records activeRoutingIds /> }
283
9,557
hyperswitch-control-center
src/screens/Routing/ActiveRouting.res
.res
open RoutingTypes open RoutingUtils type viewType = Loading | Error(string) | Loaded module TopLeftIcons = { @react.component let make = (~routeType: routingType) => { switch routeType { | DEFAULTFALLBACK => <Icon name="fallback" size=25 className="w-11" /> | VOLUME_SPLIT => <Icon name="processorLevel" size=25 className="w-14" /> | ADVANCED => <Icon name="parameterLevel" size=25 className="w-20" /> | _ => React.null } } } module TopRightIcons = { @react.component let make = (~routeType: routingType) => { switch routeType { | VOLUME_SPLIT => <Icon name="quickSetup" size=25 className="w-28" /> | _ => React.null } } } module ActionButtons = { @react.component let make = (~routeType: routingType, ~onRedirectBaseUrl) => { let mixpanelEvent = MixpanelHook.useSendEvent() let {userHasAccess} = GroupACLHooks.useUserGroupACLHook() switch routeType { | VOLUME_SPLIT | ADVANCED => <ACLButton text={"Setup"} authorization={userHasAccess(~groupAccess=WorkflowsManage)} customButtonStyle="mx-auto w-full" buttonType={Secondary} buttonSize=Small onClick={_ => { RescriptReactRouter.push( GlobalVars.appendDashboardPath( ~url=`/${onRedirectBaseUrl}/${routingTypeName(routeType)}`, ), ) mixpanelEvent(~eventName=`${onRedirectBaseUrl}_setup_${routeType->routingTypeName}`) }} /> | DEFAULTFALLBACK => <ACLButton text={"Manage"} authorization={userHasAccess(~groupAccess=WorkflowsManage)} buttonType={Secondary} customButtonStyle="mx-auto w-full" buttonSize=Small onClick={_ => { RescriptReactRouter.push( GlobalVars.appendDashboardPath( ~url=`/${onRedirectBaseUrl}/${routingTypeName(routeType)}`, ), ) mixpanelEvent(~eventName=`${onRedirectBaseUrl}_setup_${routeType->routingTypeName}`) }} /> | _ => React.null } } } module ActiveSection = { @react.component let make = (~activeRouting, ~activeRoutingId, ~onRedirectBaseUrl) => { open LogicUtils let activeRoutingType = activeRouting->getDictFromJsonObject->getString("kind", "")->routingTypeMapper let {userHasAccess} = GroupACLHooks.useUserGroupACLHook() let routingName = switch activeRoutingType { | DEFAULTFALLBACK => "" | _ => `${activeRouting->getDictFromJsonObject->getString("name", "")->capitalizeString} - ` } let profileId = activeRouting->getDictFromJsonObject->getString("profile_id", "") <div className="relative flex flex-col flex-wrap bg-white border rounded w-full px-6 py-10 gap-12"> <div> <div className="absolute top-0 left-0 bg-green-700 text-white py-2 px-4 rounded-br font-semibold"> {"ACTIVE"->React.string} </div> <div className="flex flex-col my-6 pt-4 gap-2"> <div className=" flex gap-4 align-center"> <p className="text-lightgray_background font-semibold text-base"> {`${routingName}${getContent(activeRoutingType).heading}`->React.string} </p> <Icon name="primary-tag" size=25 className="w-20" /> </div> <RenderIf condition={profileId->isNonEmptyString}> <div className="flex gap-2"> <HelperComponents.BusinessProfileComponent profile_id={profileId} className="text-lightgray_background opacity-50 text-sm" /> <p className="text-lightgray_background opacity-50 text-sm"> {`: ${profileId}`->React.string} </p> </div> </RenderIf> </div> <div className="text-lightgray_background font-medium text-base opacity-50 text-fs-14 "> {`${getContent(activeRoutingType).heading} : ${getContent( activeRoutingType, ).subHeading}`->React.string} </div> <div className="flex gap-5 pt-6 w-1/4"> <ACLButton authorization={userHasAccess(~groupAccess=WorkflowsManage)} text="Manage" buttonType=Secondary customButtonStyle="w-2/3" buttonSize={Small} onClick={_ => { switch activeRoutingType { | DEFAULTFALLBACK => RescriptReactRouter.push( GlobalVars.appendDashboardPath( ~url=`/${onRedirectBaseUrl}/${routingTypeName(activeRoutingType)}`, ), ) | _ => RescriptReactRouter.push( GlobalVars.appendDashboardPath( ~url=`/${onRedirectBaseUrl}/${routingTypeName( activeRoutingType, )}?id=${activeRoutingId}&isActive=true`, ), ) } }} /> </div> </div> </div> } } module LevelWiseRoutingSection = { @react.component let make = (~types: array<routingType>, ~onRedirectBaseUrl) => { <div className="flex flex-col flex-wrap rounded w-full py-6 gap-5"> <div className="flex flex-wrap justify-evenly gap-9 items-stretch"> {types ->Array.mapWithIndex((value, index) => <div key={index->Int.toString} className="flex flex-1 flex-col bg-white border rounded px-5 py-5 gap-8"> <div className="flex flex-1 flex-col gap-7"> <div className="flex w-full items-center flex-wrap justify-between "> <TopLeftIcons routeType=value /> <TopRightIcons routeType=value /> </div> <div className="flex flex-1 flex-col gap-3"> <p className="text-base font-semibold text-lightgray_background"> {getContent(value).heading->React.string} </p> <p className="text-fs-14 font-medium opacity-50 text-lightgray_background"> {getContent(value).subHeading->React.string} </p> </div> </div> <ActionButtons routeType=value onRedirectBaseUrl /> </div> ) ->React.array} </div> </div> } } @react.component let make = (~routingType: array<JSON.t>) => { <div className="mt-4 flex flex-col gap-6"> {routingType ->Array.mapWithIndex((ele, i) => { let id = ele->LogicUtils.getDictFromJsonObject->LogicUtils.getString("id", "") <ActiveSection key={i->Int.toString} activeRouting={ele} activeRoutingId={id} onRedirectBaseUrl="routing" /> }) ->React.array} </div> }
1,578
9,558
hyperswitch-control-center
src/screens/Routing/AdvancedRouting/RulePreviewer.res
.res
open RoutingTypes open AdvancedRoutingUtils module GatewayView = { @react.component let make = (~gateways) => { let url = RescriptReactRouter.useUrl() let connectorType: ConnectorTypes.connectorTypeVariants = switch url->RoutingUtils.urlToVariantMapper { | PayoutRouting => ConnectorTypes.PayoutProcessor | _ => ConnectorTypes.PaymentProcessor } let connectorList = ConnectorInterface.useConnectorArrayMapper( ~interface=ConnectorInterface.connectorInterfaceV1, ~retainInList=connectorType, ) let getGatewayName = merchantConnectorId => { ( connectorList->ConnectorTableUtils.getConnectorObjectFromListViaId(merchantConnectorId) ).connector_label } let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext) <div className="flex flex-wrap gap-4 items-center"> {gateways ->Array.mapWithIndex((ruleGateway, index) => { let (connectorStr, percent) = switch ruleGateway { | PriorityObject(obj) => (obj.merchant_connector_id->getGatewayName, None) | VolumeObject(obj) => ( obj.connector.merchant_connector_id->getGatewayName, Some(obj.split), ) } <div key={Int.toString(index)} className={`my-2 h-6 md:h-8 flex items-center rounded-md border border-jp-gray-500 dark:border-jp-gray-960 font-medium ${textColor.primaryNormal} hover:${textColor.primaryNormal} bg-gradient-to-b from-jp-gray-250 to-jp-gray-200 dark:from-jp-gray-950 dark:to-jp-gray-950 focus:outline-none px-2 gap-1`}> {connectorStr->React.string} <RenderIf condition={percent->Option.isSome}> <span className="text-jp-gray-700 dark:text-jp-gray-600 ml-1"> {(percent->Option.getOr(0)->Int.toString ++ "%")->React.string} </span> </RenderIf> </div> }) ->React.array} </div> } } module ThreedsTypeView = { @react.component let make = (~threeDsType) => { let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext) <div className={`my-2 h-6 md:h-8 flex items-center rounded-md border border-jp-gray-500 font-medium ${textColor.primaryNormal} hover:${textColor.primaryNormal} bg-gradient-to-b from-jp-gray-250 to-jp-gray-200 focus:outline-none px-2 gap-1`}> {threeDsType->LogicUtils.capitalizeString->React.string} </div> } } module SurchargeCompressedView = { @react.component let make = (~surchargeType, ~surchargeTypeValue, ~surchargePercentage) => { let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext) <div className={`my-2 h-6 md:h-8 flex items-center rounded-md border border-jp-gray-500 font-medium ${textColor.primaryNormal} hover: ${textColor.primaryNormal} bg-gradient-to-b from-jp-gray-250 to-jp-gray-200 focus:outline-none px-2 gap-1`}> {`${surchargeType} -> ${surchargeTypeValue->Float.toString} | Tax on Surcharge -> ${surchargePercentage ->Option.getOr(0.0) ->Float.toString}` ->LogicUtils.capitalizeString ->React.string} </div> } } @react.component let make = (~ruleInfo: algorithmData, ~isFrom3ds=false, ~isFromSurcharge=false) => { open LogicUtils let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext) <div className=" bg-white border flex flex-col divide-y divide-jp-gray-600 border-jp-gray-600 "> <AddDataAttributes attributes=[("data-component", "rulePreviewer")]> <div> <div className="flex flex-col divide-y divide-jp-gray-600 border-t border-b"> {ruleInfo.rules ->Array.mapWithIndex((rule, index) => { let statementsArr = rule.statements let headingText = `Rule ${Int.toString(index + 1)}` let marginStyle = index === ruleInfo.rules->Array.length - 1 ? "mt-2" : "my-2" let threeDsType = rule.connectorSelection.override_3ds->Option.getOr("") let surchargeType = rule.connectorSelection.surcharge_details->SurchargeUtils.getDefaultSurchargeType let surchargePercent = surchargeType.surcharge.value.percentage->Option.getOr(0.0) let surchargeAmount = surchargeType.surcharge.value.amount->Option.getOr(0.0) let surchargeTypeValue = if surchargeAmount > 0.0 { surchargeAmount } else { surchargePercent } <div key={Int.toString(index)} className="flex flex-col items-center w-full px-4 pb-6"> <div style={marginTop: "-1.2rem"} className="text-jp-gray-700 dark:text-jp-gray-700 text-base font-semibold p-1 px-3 bg-jp-gray-50 dark:bg-jp-gray-950 rounded-full border border-jp-gray-600 dark:border-jp-gray-850"> {headingText->React.string} </div> <div className={`w-full flex flex-wrap items-center ${marginStyle}`}> <div className="flex flex-wrap gap-2"> {statementsArr ->Array.mapWithIndex((statement, index) => { let comparison = statement.comparison let typeString = statement.value.\"type" let logical = statement.logical->Option.getOr("") let operator = getOperatorFromComparisonType(comparison, typeString) let field = statement.lhs let metadataDict = statement.metadata ->Option.getOr(Dict.make()->JSON.Encode.object) ->getDictFromJsonObject let value = switch statement.value.value->JSON.Classify.classify { | Array(arr) => arr->Array.joinWithUnsafe(", ") | String(str) => str | Number(num) => num->Float.toString | Object(obj) => obj->LogicUtils.getString("value", "") | _ => "" } let metadataKeyValue = switch statement.value.value->JSON.Classify.classify { | Object(obj) => obj->LogicUtils.getString("key", "") | _ => "" } let metadataKey = metadataDict->getOptionString("key") <div key={Int.toString(index)} className="flex flex-wrap items-center gap-2"> <RenderIf condition={index !== 0}> <MakeRuleFieldComponent.TextView str=logical fontColor={`${textColor.primaryNormal}`} fontWeight="font-semibold" /> </RenderIf> <MakeRuleFieldComponent.TextView str=field /> <RenderIf condition={typeString == "metadata_variant"}> <MakeRuleFieldComponent.TextView str=metadataKeyValue /> </RenderIf> <RenderIf condition={metadataKey->Option.isSome}> <MakeRuleFieldComponent.TextView str={metadataKey->Option.getOr("")} /> </RenderIf> <MakeRuleFieldComponent.TextView str=operator fontColor="text-red-500" fontWeight="font-semibold" /> <MakeRuleFieldComponent.TextView str=value /> </div> }) ->React.array} </div> <RenderIf condition={rule.statements->Array.length > 0}> <Icon size=14 name="arrow-right" className="mx-4 text-jp-gray-700" /> </RenderIf> <RenderIf condition={isFrom3ds}> <ThreedsTypeView threeDsType /> </RenderIf> <RenderIf condition={!isFrom3ds}> <GatewayView gateways={rule.connectorSelection.data->Option.getOr([])} /> </RenderIf> <RenderIf condition={isFromSurcharge}> <SurchargeCompressedView surchargeType={surchargeType.surcharge.\"type"} surchargeTypeValue surchargePercentage={surchargeType.tax_on_surcharge.percentage} /> </RenderIf> </div> </div> }) ->React.array} </div> </div> </AddDataAttributes> </div> }
1,931
9,559
hyperswitch-control-center
src/screens/Routing/AdvancedRouting/AdvancedRoutingUtils.res
.res
let operatorTypeToStringMapper = (operator: RoutingTypes.operator) => { switch operator { | CONTAINS => "CONTAINS" | NOT_CONTAINS => "NOT_CONTAINS" | IS => "IS" | IS_NOT => "IS_NOT" | GREATER_THAN => "GREATER THAN" | LESS_THAN => "LESS THAN" | EQUAL_TO => "EQUAL TO" | NOT_EQUAL_TO => "NOT EQUAL_TO" | UnknownOperator(str) => str } } let operatorMapper: string => RoutingTypes.operator = value => { switch value { | "CONTAINS" => CONTAINS | "NOT_CONTAINS" => NOT_CONTAINS | "IS" => IS | "IS_NOT" => IS_NOT | "GREATER_THAN" | "GREATER THAN" => GREATER_THAN | "LESS_THAN" | "LESS THAN" => LESS_THAN | "EQUAL TO" => EQUAL_TO | "NOT EQUAL_TO" => NOT_EQUAL_TO | _ => UnknownOperator("") } } let getRoutingTypeName = (routingType: RoutingTypes.routingType) => { switch routingType { | VOLUME_SPLIT => "volume" | ADVANCED => "rule" | DEFAULTFALLBACK => "default" | NO_ROUTING => "" } } let getRoutingNameString = (~routingType) => { open LogicUtils let routingText = routingType->getRoutingTypeName `${routingText->capitalizeString} Based Routing-${RoutingUtils.getCurrentUTCTime()}` } let getRoutingDescriptionString = (~routingType) => { let routingText = routingType->getRoutingTypeName `This is a ${routingText} based routing created at ${RoutingUtils.currentTimeInUTC}` } let getWasmKeyType = (wasm, value) => { try { switch wasm { | Some(res) => res.RoutingTypes.getKeyType(value) | None => "" } } catch { | _ => "" } } let getWasmVariantValues = (wasm, value) => { try { switch wasm { | Some(res) => res.RoutingTypes.getVariantValues(value) | None => [] } } catch { | _ => [] } } let getWasmPayoutVariantValues = (wasm, value) => { try { switch wasm { | Some(res) => res.RoutingTypes.getPayoutVariantValues(value) | None => [] } } catch { | _ => [] } } let variantTypeMapper: string => RoutingTypes.variantType = variantType => { switch variantType { | "number" => Number | "enum_variant" => Enum_variant | "metadata_value" => Metadata_value | "str_value" => String_value | _ => UnknownVariant("") } } let getStatementValue: Dict.t<JSON.t> => RoutingTypes.value = valueDict => { open LogicUtils { \"type": valueDict->getString("type", ""), value: valueDict->getJsonObjectFromDict("value"), } } let statementTypeMapper: Dict.t<JSON.t> => RoutingTypes.statement = dict => { open LogicUtils { lhs: dict->getString("lhs", ""), comparison: dict->getString("comparison", ""), value: getStatementValue(dict->getDictfromDict("value")), logical: dict->getString("logical", ""), } } let conditionTypeMapper = (statementArr: array<JSON.t>) => { open LogicUtils let statements = statementArr->Array.reduce([], (acc, statementJson) => { let conditionArray = statementJson->getDictFromJsonObject->getArrayFromDict("condition", []) let arr = conditionArray->Array.mapWithIndex((conditionJson, index) => { let statementDict = conditionJson->getDictFromJsonObject let returnValue: RoutingTypes.statement = { lhs: statementDict->getString("lhs", ""), comparison: statementDict->getString("comparison", ""), logical: index === 0 ? "OR" : "AND", value: getStatementValue(statementDict->getDictfromDict("value")), } returnValue }) acc->Array.concat(arr) }) statements } let volumeSplitConnectorSelectionDataMapper: Dict.t< JSON.t, > => RoutingTypes.volumeSplitConnectorSelectionData = dict => { open LogicUtils { split: dict->getInt("split", 0), connector: { connector: dict->getDictfromDict("connector")->getString("connector", ""), merchant_connector_id: dict ->getDictfromDict("connector") ->getString("merchant_connector_id", ""), }, } } let priorityConnectorSelectionDataMapper: Dict.t<JSON.t> => RoutingTypes.connector = dict => { open LogicUtils { connector: dict->getString("connector", ""), merchant_connector_id: dict->getString("merchant_connector_id", ""), } } let connectorSelectionDataMapperFromJson: JSON.t => RoutingTypes.connectorSelectionData = json => { open LogicUtils let split = json->getDictFromJsonObject->getOptionInt("split") let dict = json->getDictFromJsonObject switch split { | Some(_) => VolumeObject(dict->volumeSplitConnectorSelectionDataMapper) | None => PriorityObject(dict->priorityConnectorSelectionDataMapper) } } let getDefaultSelection: Dict.t<JSON.t> => RoutingTypes.connectorSelection = defaultSelection => { open LogicUtils open RoutingTypes let override3dsValue = defaultSelection->getString("override_3ds", "") let surchargeDetailsOptionalValue = defaultSelection->Dict.get("surcharge_details") let surchargeDetailsValue = defaultSelection->getDictfromDict("surcharge_details") if override3dsValue->isNonEmptyString { { override_3ds: override3dsValue, } } else if surchargeDetailsOptionalValue->Option.isSome { let surchargeValue = surchargeDetailsValue->getDictfromDict("surcharge") { surcharge_details: { surcharge: { \"type": surchargeValue->getString("type", "rate"), value: { percentage: surchargeValue->getDictfromDict("value")->getFloat("percentage", 0.0), amount: surchargeValue->getDictfromDict("value")->getFloat("amount", 0.0), }, }, tax_on_surcharge: { percentage: surchargeDetailsValue ->getDictfromDict("tax_on_surcharge") ->getFloat("percentage", 0.0), }, }->Nullable.make, } } else { { \"type": defaultSelection->getString("type", ""), data: defaultSelection ->getArrayFromDict("data", []) ->Array.map(ele => ele->connectorSelectionDataMapperFromJson), } } } let getConnectorStringFromConnectorSelectionData = connectorSelectionData => { open RoutingTypes switch connectorSelectionData { | VolumeObject(obj) => { merchant_connector_id: obj.connector.merchant_connector_id, connector: obj.connector.connector, } | PriorityObject(obj) => { merchant_connector_id: obj.merchant_connector_id, connector: obj.connector, } } } let getSplitFromConnectorSelectionData = connectorSelectionData => { open RoutingTypes switch connectorSelectionData { | VolumeObject(obj) => obj.split | _ => 0 } } let ruleInfoTypeMapper: Dict.t<JSON.t> => RoutingTypes.algorithmData = json => { open LogicUtils let rulesArray = json->getArrayFromDict("rules", []) let defaultSelection = json->getDictfromDict("defaultSelection") let rulesModifiedArray = rulesArray->Array.map(rule => { let ruleDict = rule->getDictFromJsonObject let connectorsDict = ruleDict->getDictfromDict("connectorSelection") let connectorSelection = getDefaultSelection(connectorsDict) let ruleName = ruleDict->getString("name", "") let eachRule: RoutingTypes.rule = { name: ruleName, connectorSelection, statements: conditionTypeMapper(ruleDict->getArrayFromDict("statements", [])), } eachRule }) { rules: rulesModifiedArray, defaultSelection: getDefaultSelection(defaultSelection), metadata: json->getJsonObjectFromDict("metadata"), } } let getOperatorFromComparisonType = (comparison, variantType) => { switch comparison { | "equal" => switch variantType { | "number" => "EQUAL TO" | "enum_variant" => "IS" | "enum_variant_array" => "CONTAINS" | "str_value" => "EQUAL TO" | "metadata_variant" => "EQUAL TO" | _ => "IS" } | "not_equal" => switch variantType { | "enum_variant_array" => "NOT_CONTAINS" | "enum_variant" => "IS_NOT" | "str_value" => "NOT EQUAL_TO" | _ => "IS_NOT" } | "greater_than" => "GREATER_THAN" | "less_than" => "LESS_THAN" | _ => "" } } let isStatementMandatoryFieldsPresent = (statement: RoutingTypes.statement) => { open LogicUtils let statementValue = switch statement.value.value->JSON.Classify.classify { | Array(ele) => ele->Array.length > 0 | String(str) => str->isNonEmptyString | Object(objectValue) => { let key = objectValue->getString("key", "") let value = objectValue->getString("value", "") key->isNonEmptyString && value->isNonEmptyString } | _ => false } statement.lhs->isNonEmptyString && (statement.value.\"type"->isNonEmptyString && statementValue) } let algorithmTypeMapper: Dict.t<JSON.t> => RoutingTypes.algorithm = values => { open LogicUtils { data: values->getDictfromDict("data")->ruleInfoTypeMapper, \"type": values->getString("type", ""), } } let getRoutingTypesFromJson: JSON.t => RoutingTypes.advancedRouting = values => { open LogicUtils let valuesDict = values->getDictFromJsonObject { name: valuesDict->getString("name", ""), description: valuesDict->getString("description", ""), algorithm: valuesDict->getDictfromDict("algorithm")->algorithmTypeMapper, } } let validateStatements = statementsArray => { statementsArray->Array.every(isStatementMandatoryFieldsPresent) } let generateStatements = statements => { open LogicUtils let initialValueForStatement: RoutingTypes.statementSendType = { condition: [], } statements->Array.reduce([initialValueForStatement], (acc, statement) => { let statementDict = statement->getDictFromJsonObject let logicalOperator = statementDict->getString("logical", "")->String.toLowerCase let lastItem = acc->Array.get(acc->Array.length - 1)->Option.getOr({condition: []}) let condition: RoutingTypes.statement = { lhs: statementDict->getString("lhs", ""), comparison: switch statementDict->getString("comparison", "")->operatorMapper { | IS | EQUAL_TO | CONTAINS => "equal" | IS_NOT | NOT_CONTAINS | NOT_EQUAL_TO => "not_equal" | GREATER_THAN => "greater_than" | LESS_THAN => "less_than" | UnknownOperator(str) => str }, value: statementDict->getDictfromDict("value")->getStatementValue, metadata: statementDict->getJsonObjectFromDict("metadata"), } let newAcc = if logicalOperator === "or" { acc->Array.concat([ { condition: [condition], }, ]) } else { lastItem.condition->Array.push(condition) let filteredArr = acc->Array.filterWithIndex((_, i) => i !== acc->Array.length - 1) filteredArr->Array.push(lastItem) filteredArr } newAcc }) } let generateRule = rulesDict => { let modifiedRules = rulesDict->Array.map(ruleJson => { open LogicUtils let ruleDict = ruleJson->getDictFromJsonObject let statements = ruleDict->getArrayFromDict("statements", []) let modifiedStatements = statements->generateStatements { "name": ruleDict->getString("name", ""), "connectorSelection": ruleDict->getJsonObjectFromDict("connectorSelection"), "statements": modifiedStatements->Array.map(Identity.genericTypeToJson)->JSON.Encode.array, } }) modifiedRules } let defaultRule: RoutingTypes.rule = { name: "rule_1", connectorSelection: { \"type": "priority", }, statements: [ { lhs: "", comparison: "", value: { \"type": "number", value: ""->JSON.Encode.string, }, }, ], } let defaultAlgorithmData: RoutingTypes.algorithmData = { rules: [defaultRule], metadata: Dict.make()->JSON.Encode.object, defaultSelection: { \"type": "", data: [], }, } let initialValues: RoutingTypes.advancedRouting = { name: getRoutingNameString(~routingType=ADVANCED), description: getRoutingDescriptionString(~routingType=ADVANCED), algorithm: { data: defaultAlgorithmData, \"type": "", }, } let validateNameAndDescription = (~dict, ~errors, ~validateFields) => { open LogicUtils validateFields->Array.forEach(field => { if dict->getString(field, "")->String.trim->isEmptyString { errors->Dict.set(field, `Please provide ${field} field`->JSON.Encode.string) } }) }
3,023
9,560
hyperswitch-control-center
src/screens/Routing/AdvancedRouting/AdvancedRouting.res
.res
open APIUtils open RoutingTypes open AdvancedRoutingUtils open LogicUtils external toWasm: Dict.t<JSON.t> => RoutingTypes.wasmModule = "%identity" module Add3DSCondition = { @react.component let make = (~isFirst, ~id, ~isExpanded, ~threeDsType) => { let classStyle = "flex justify-center relative py-2 h-fit min-w-min hover:bg-jp-2-light-gray-100 focus:outline-none rounded-md items-center border-2 border-border_gray border-opacity-50 text-jp-2-light-gray-1200 px-4 transition duration-[250ms] ease-out-[cubic-bezier(0.33, 1, 0.68, 1)] overflow-hidden" let options: array<SelectBox.dropdownOption> = [ {value: "three_ds", label: "3DS"}, {value: "no_three_ds", label: "No 3DS"}, ] if isExpanded { <div className="flex flex-row ml-2"> <RenderIf condition={!isFirst}> <div className="w-8 h-10 border-jp-gray-700 ml-10 border-dashed border-b border-l " /> </RenderIf> <div className="flex flex-col gap-6 mt-6 mb-4 pt-0.5"> <div className="flex flex-wrap gap-4 -mt-2"> <div className=classStyle> {"Auth type"->React.string} </div> <div className=classStyle> {"= is Equal to"->React.string} </div> <FormRenderer.FieldRenderer field={FormRenderer.makeFieldInfo( ~label="", ~name=`${id}.connectorSelection.override_3ds`, ~customInput=InputFields.selectInput( ~options, ~buttonText="Select Field", ~customButtonStyle=`!-mt-5 ${classStyle} !rounded-md`, ~deselectDisable=true, ), )} /> </div> </div> </div> } else { <RulePreviewer.ThreedsTypeView threeDsType /> } } } module AddSurchargeCondition = { let classStyle = "flex justify-center relative py-2 h-fit min-w-min hover:bg-jp-2-light-gray-100 focus:outline-none rounded-md items-center border-2 border-border_gray border-opacity-50 text-jp-2-light-gray-1200 px-4 transition duration-[250ms] ease-out-[cubic-bezier(0.33, 1, 0.68, 1)] overflow-hidden" //keep the rate only for now. let options: array<SelectBox.dropdownOption> = [ {value: "rate", label: "Rate"}, {value: "fixed", label: "Fixed"}, ] @react.component let make = ( ~isFirst, ~id, ~isExpanded, ~surchargeType, ~surchargeTypeValue, ~surchargePercentage, ) => { let (surchargeValueType, setSurchargeValueType) = React.useState(_ => "") let surchargeTypeInput = ReactFinalForm.useField( `${id}.connectorSelection.surcharge_details.surcharge.type`, ).input React.useEffect(() => { let valueType = switch surchargeTypeInput.value->LogicUtils.getStringFromJson("") { | "rate" => "percentage" | "fixed" => "amount" | _ => "percentage" } setSurchargeValueType(_ => valueType) None }, [surchargeTypeInput.value]) { if isExpanded { <div className="flex flex-row ml-2"> <RenderIf condition={!isFirst}> <div className="w-8 h-10 border-jp-gray-700 ml-10 border-dashed border-b border-l " /> </RenderIf> <div className="flex flex-col gap-6 mt-6 mb-4 pt-0.5"> <div className="flex flex-wrap gap-4"> <div className=classStyle> {"Surcharge is"->React.string} </div> <FormRenderer.FieldRenderer field={FormRenderer.makeFieldInfo( ~label="", ~name=`${id}.connectorSelection.surcharge_details.surcharge.type`, ~customInput=InputFields.selectInput( ~options, ~buttonText="Select Surcharge Type", ~customButtonStyle=`!-mt-5 ${classStyle} !p-0 !rounded-md`, ~deselectDisable=true, ~textStyle="!px-2 !py-2", ), )} /> <FormRenderer.FieldRenderer field={FormRenderer.makeFieldInfo( ~label="", ~name=`${id}.connectorSelection.surcharge_details.surcharge.value.${surchargeValueType}`, ~customInput=InputFields.numericTextInput(~customStyle="!-mt-5", ~precision=2), )} /> </div> <div className="flex flex-wrap gap-4"> <div className=classStyle> {"Tax on Surcharge"->React.string} </div> <FormRenderer.FieldRenderer field={FormRenderer.makeFieldInfo( ~label="", ~name=`${id}.connectorSelection.surcharge_details.tax_on_surcharge.percentage`, ~customInput=InputFields.numericTextInput( ~precision=2, ~customStyle="!-mt-5", ~rightIcon=<Icon name="percent" size=16 />, ~rightIconCustomStyle="-ml-7 -mt-5", ), )} /> </div> </div> </div> } else { <RulePreviewer.SurchargeCompressedView surchargeType surchargeTypeValue surchargePercentage /> } } } } module Wrapper = { @react.component let make = ( ~id, ~heading, ~onClickAdd, ~onClickCopy=?, ~onClickRemove, ~gatewayOptions, ~isFirst=false, ~notFirstRule=true, ~isDragging=false, ~wasm, ~isFrom3ds=false, ~isFromSurcharge=false, ) => { let {globalUIConfig: {border: {borderColor}}} = React.useContext(ThemeProvider.themeContext) let showToast = ToastState.useShowToast() let isMobileView = MatchMedia.useMobileChecker() let (isExpanded, setIsExpanded) = React.useState(_ => true) let gateWaysInput = ReactFinalForm.useField(`${id}.connectorSelection.data`).input let name = ReactFinalForm.useField(`${id}.name`).input let conditionsInput = ReactFinalForm.useField(`${id}.statements`).input let threeDsType = ReactFinalForm.useField( `${id}.connectorSelection.override_3ds`, ).input.value->getStringFromJson("") let surchargeType = ReactFinalForm.useField( `${id}.connectorSelection.surcharge_details.surcharge.type`, ).input.value->getStringFromJson("") let surchargePercentage = ReactFinalForm.useField( `${id}.connectorSelection.surcharge_details.tax_on_surcharge.percentage`, ).input.value->getOptionFloatFromJson let surchargeValue = ReactFinalForm.useField( `${id}.connectorSelection.surcharge_details.surcharge.value`, ).input.value->getDictFromJsonObject let surchargePercent = surchargeValue->getFloat("percentage", 0.0) let surchargeAmount = surchargeValue->getFloat("amount", 0.0) let surchargeTypeValue = if surchargeAmount > 0.0 { surchargeAmount } else { surchargePercent } let areValidConditions = conditionsInput.value ->getArrayFromJson([]) ->Array.every(ele => ele->getDictFromJsonObject->statementTypeMapper->isStatementMandatoryFieldsPresent ) let handleClickExpand = _ => { if isFrom3ds { if threeDsType->String.length > 0 { setIsExpanded(p => !p) } else { showToast(~toastType=ToastWarning, ~message="Auth type not selected", ~autoClose=true) } } else if isFromSurcharge { if surchargeTypeValue > 0.0 { setIsExpanded(p => !p) } else { showToast(~toastType=ToastWarning, ~message="Invalid condition", ~autoClose=true) } } else { let gatewayArrPresent = gateWaysInput.value->getArrayFromJson([])->Array.length > 0 if gatewayArrPresent && areValidConditions { setIsExpanded(p => !p) } else if gatewayArrPresent { showToast(~toastType=ToastWarning, ~message="Invalid Conditions", ~autoClose=true) } else { showToast(~toastType=ToastWarning, ~message="No Gateway Selected", ~autoClose=true) } } } React.useEffect(() => { name.onChange(heading->String.toLowerCase->titleToSnake->Identity.stringToFormReactEvent) let gatewayArrPresent = gateWaysInput.value->getArrayFromJson([])->Array.length > 0 if gatewayArrPresent && areValidConditions { setIsExpanded(p => !p) } None }, []) let border = isDragging ? "border-dashed" : "border-solid" let flex = isExpanded ? "flex-col" : "flex-wrap items-center gap-4" let hoverCss = "transition-all duration-150 hover:bg-gray-200 active:scale-95 active:bg-gray-300 " let actionIconCss = "flex items-center justify-center p-2 bg-gray-100 dark:bg-jp-gray-970 rounded-xl border border-jp-gray-600 cursor-pointer h-8" let actions = <div className={`flex flex-row gap-3 md:gap-4 mr-4 w-1/3 items-center justify-end `}> <RenderIf condition={notFirstRule}> <ToolTip description="Drag Rule" toolTipFor={<div className={`${actionIconCss} ${hoverCss}`}> <Icon name="grip-vertical" className="text-jp-gray-700" size={14} /> </div>} toolTipPosition=Top /> </RenderIf> <ToolTip description="Add New Rule" toolTipFor={<div onClick={onClickAdd} className={`${actionIconCss} ${hoverCss}`}> <Icon name="plus" className="text-jp-gray-700" size={14} /> </div>} toolTipPosition=Top /> {switch onClickCopy { | Some(onClick) => <ToolTip description="Copy Rule" toolTipFor={<div onClick={onClick} className={`${actionIconCss} ${hoverCss}`}> <Icon name="nd-copy" className="text-jp-gray-700" size={12} /> </div>} toolTipPosition=Top /> | None => React.null }} <RenderIf condition={notFirstRule}> <ToolTip description="Delete Rule" toolTipFor={<div onClick={onClickRemove} className={`${actionIconCss} ${hoverCss}`}> <Icon name="trash" className="text-jp-gray-700" size={12} /> </div>} toolTipPosition=Top /> </RenderIf> </div> <div className="flex flex-col"> <div className={`flex flex-row tems-center justify-between z-10 -mt-6 mx-2`}> <RenderIf condition={!isMobileView}> <div className="hidden lg:flex w-1/3" /> </RenderIf> <div onClick={handleClickExpand} className={`cursor-pointer flex flex-row gap-2 items-center justify-between p-2 bg-blue-100 dark:bg-jp-gray-970 rounded-xl border ${borderColor.primaryNormal} dark:${borderColor.primaryNormal}`}> <div className="font-semibold pl-2 text-sm md:text-base"> {React.string(heading)} </div> <Icon name={isExpanded ? "angle-up" : "angle-down"} size={isMobileView ? 14 : 16} /> </div> {actions} </div> <div style={marginTop: "-17px"} className={`flex ${flex} p-4 py-6 bg-gray-50 dark:bg-jp-gray-lightgray_background rounded-md border ${border} ${borderColor.primaryNormal}`}> <RenderIf condition={!isFirst}> <AdvancedRoutingUIUtils.MakeRuleField id isExpanded wasm isFrom3ds isFromSurcharge /> </RenderIf> <RenderIf condition={!isFrom3ds && !isFromSurcharge}> <AddRuleGateway id gatewayOptions isExpanded isFirst /> </RenderIf> <RenderIf condition={isFrom3ds}> <Add3DSCondition isFirst id isExpanded threeDsType /> </RenderIf> <RenderIf condition={isFromSurcharge}> <AddSurchargeCondition isFirst id isExpanded surchargeType surchargeTypeValue surchargePercentage /> </RenderIf> </div> </div> } } module RuleBasedUI = { @react.component let make = ( ~gatewayOptions, ~wasm, ~initialRule, ~pageState, ~setCurrentRouting, ~baseUrlForRedirection, ) => { let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext) let rulesJsonPath = `algorithm.data.rules` let showToast = ToastState.useShowToast() let ruleInput = ReactFinalForm.useField(rulesJsonPath).input let (rules, setRules) = React.useState(_ => ruleInput.value->getArrayFromJson([])) React.useEffect(() => { ruleInput.onChange(rules->Identity.arrayOfGenericTypeToFormReactEvent) None }, [rules]) let isEmptyRule = rule => { defaultRule->Identity.genericTypeToJson->getDictFromJsonObject->Dict.delete("name") rule->getDictFromJsonObject->Dict.delete("name") defaultRule->Identity.genericTypeToJson == rule } let addRule = (index, copy) => { let existingRules = ruleInput.value->getArrayFromJson([]) if !copy && existingRules->Array.some(isEmptyRule) { showToast( ~message="Unable to add a new rule while an empty rule exists!", ~toastType=ToastState.ToastError, ) } else if copy { switch existingRules[index] { | Some(rule) => if isEmptyRule(rule) { showToast( ~message="Unable to copy an empty rule configuration!", ~toastType=ToastState.ToastError, ) } else { let newRule = rule->Identity.genericTypeToJson let newRules = existingRules->Array.concat([newRule]) ruleInput.onChange(newRules->Identity.arrayOfGenericTypeToFormReactEvent) } | None => () } } else { let newRule = defaultRule->Identity.genericTypeToJson let newRules = existingRules->Array.concat([newRule]) ruleInput.onChange(newRules->Identity.arrayOfGenericTypeToFormReactEvent) } } let removeRule = index => { let existingRules = ruleInput.value->getArrayFromJson([]) let newRules = existingRules->Array.filterWithIndex((_, i) => i !== index) ruleInput.onChange(newRules->Identity.arrayOfGenericTypeToFormReactEvent) } <div className="flex flex-col my-5"> <div className={`flex flex-wrap items-center justify-between p-4 py-8 bg-white dark:bg-jp-gray-lightgray_background rounded-md border border-jp-gray-600 dark:border-jp-gray-850 `}> <div> <div className="font-bold"> {React.string("Rule Based Configuration")} </div> <div className="flex flex-col gap-4"> <span className="w-full text-jp-gray-700 dark:text-jp-gray-700 text-justify"> {"Rule-Based Configuration allows for detailed smart routing logic based on multiple dimensions of a payment. You can create any number of conditions using various dimensions and logical operators."->React.string} </span> <span className="flex flex-col text-jp-gray-700"> {"For example:"->React.string} <p className="flex gap-2 items-center"> <div className="p-1 h-fit rounded-full bg-jp-gray-700 ml-2" /> {"If card_type = credit && amount > 100, route 60% to Stripe and 40% to Adyen."->React.string} </p> </span> <span className="text-jp-gray-700 text-sm"> <i> {"Ensure to enter the payment amount in the smallest currency unit (e.g., cents for USD, yen for JPY). For instance, pass 100 to charge $1.00 (USD) and ¥100 (JPY) since ¥ is a zero-decimal currency."->React.string} </i> </span> </div> </div> </div> {switch pageState { | Create => <> { let notFirstRule = ruleInput.value->getArrayFromJson([])->Array.length > 1 let rule = ruleInput.value->JSON.Decode.array->Option.getOr([]) let keyExtractor = (index, _rule, isDragging) => { let id = {`${rulesJsonPath}[${Int.toString(index)}]`} <Wrapper key={index->Int.toString} id heading={`Rule ${Int.toString(index + 1)}`} onClickAdd={_ => addRule(index, false)} onClickCopy={_ => addRule(index, true)} onClickRemove={_ => removeRule(index)} gatewayOptions notFirstRule isDragging wasm /> } if notFirstRule { <DragDropComponent listItems=rule setListItems={v => setRules(_ => v)} keyExtractor isHorizontal=false /> } else { rule ->Array.mapWithIndex((rule, index) => { keyExtractor(index, rule, false) }) ->React.array } } </> | Preview => switch initialRule { | Some(ruleInfo) => <RulePreviewer ruleInfo /> | None => React.null } | _ => React.null }} <div className="bg-white rounded-md flex gap-2 p-4 border-2"> <p className="text-jp-gray-700 dark:text-jp-gray-700"> {"In case the above rule fails, the routing will follow fallback routing. You can configure it"->React.string} </p> <p className={`${textColor.primaryNormal} cursor-pointer`} onClick={_ => { setCurrentRouting(_ => RoutingTypes.DEFAULTFALLBACK) RescriptReactRouter.replace( GlobalVars.appendDashboardPath(~url=`${baseUrlForRedirection}/default`), ) }}> {"here"->React.string} </p> </div> </div> } } @react.component let make = ( ~routingRuleId, ~isActive, ~setCurrentRouting, ~connectorList: array<ConnectorTypes.connectorPayload>, ~urlEntityName, ~baseUrlForRedirection, ) => { let getURL = useGetURL() let url = RescriptReactRouter.useUrl() let businessProfiles = Recoil.useRecoilValueFromAtom(HyperswitchAtom.businessProfilesAtom) let defaultBusinessProfile = businessProfiles->MerchantAccountUtils.getValueFromBusinessProfile let (profile, setProfile) = React.useState(_ => defaultBusinessProfile.profile_id) let (initialValues, setInitialValues) = React.useState(_ => initialValues->Identity.genericTypeToJson ) let (initialRule, setInitialRule) = React.useState(() => None) let showToast = ToastState.useShowToast() let fetchDetails = useGetMethod() let updateDetails = useUpdateMethod(~showErrorToast=false) let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let (wasm, setWasm) = React.useState(_ => None) let (formState, setFormState) = React.useState(_ => EditReplica) let (connectors, setConnectors) = React.useState(_ => []) let (pageState, setPageState) = React.useState(() => Create) let (showModal, setShowModal) = React.useState(_ => false) let currentTabName = Recoil.useRecoilValueFromAtom(HyperswitchAtom.currentTabNameRecoilAtom) let getConnectorsList = () => { setConnectors(_ => connectorList->Array.filter(connector => connector.connector_name !== "applepay") ) } let activeRoutingDetails = async () => { try { let routingUrl = getURL(~entityName=urlEntityName, ~methodType=Get, ~id=routingRuleId) let routingJson = await fetchDetails(routingUrl) let schemaValue = routingJson->getDictFromJsonObject let rulesValue = schemaValue->getObj("algorithm", Dict.make())->getDictfromDict("data") setInitialValues(_ => routingJson) setInitialRule(_ => Some(ruleInfoTypeMapper(rulesValue))) setProfile(_ => schemaValue->getString("profile_id", defaultBusinessProfile.profile_id)) setFormState(_ => ViewConfig) } catch { | Exn.Error(e) => let err = Exn.message(e)->Option.getOr("Something went wrong") Exn.raiseError(err) } } let getWasm = async () => { try { let wasmResult = await Window.connectorWasmInit() let wasm = wasmResult->getDictFromJsonObject->getObj("wasm", Dict.make()) setWasm(_ => Some(wasm->toWasm)) } catch { | _ => () } } React.useEffect(() => { let fetchDetails = async () => { try { setScreenState(_ => Loading) await getWasm() getConnectorsList() switch routingRuleId { | Some(_id) => { await activeRoutingDetails() setPageState(_ => Preview) } | None => setPageState(_ => Create) } setScreenState(_ => Success) } catch { | Exn.Error(e) => { let err = Exn.message(e)->Option.getOr("Something went wrong") setScreenState(_ => Error(err)) } } } fetchDetails()->ignore None }, [routingRuleId]) let validate = (values: JSON.t) => { let dict = values->LogicUtils.getDictFromJsonObject let convertedObject = values->AdvancedRoutingUtils.getRoutingTypesFromJson let errors = Dict.make() AdvancedRoutingUtils.validateNameAndDescription( ~dict, ~errors, ~validateFields=["name", "description"], ) let validateGateways = (connectorData: array<RoutingTypes.connectorSelectionData>) => { if connectorData->Array.length === 0 { Some("Need atleast 1 Gateway") } else { let isDistibuted = connectorData->Array.every(ele => { switch ele { | PriorityObject(_) => false | VolumeObject(_) => true } }) if isDistibuted { let distributionPercentageSum = connectorData->Array.reduce(0, (sum, value) => sum + value->AdvancedRoutingUtils.getSplitFromConnectorSelectionData ) let hasZero = connectorData->Array.some(ele => ele->AdvancedRoutingUtils.getSplitFromConnectorSelectionData === 0 ) let isDistributeChecked = !( connectorData->Array.some(ele => { ele->AdvancedRoutingUtils.getSplitFromConnectorSelectionData === 100 }) ) let isNotValid = isDistributeChecked && (distributionPercentageSum > 100 || hasZero || distributionPercentageSum !== 100) if isNotValid { Some("Distribution Percent not correct") } else { None } } else { None } } } let rulesArray = convertedObject.algorithm.data.rules if rulesArray->Array.length === 0 { errors->Dict.set(`Rules`, "Minimum 1 rule needed"->JSON.Encode.string) } else { rulesArray->Array.forEachWithIndex((rule, i) => { let connectorDetails = rule.connectorSelection.data->Option.getOr([]) switch connectorDetails->validateGateways { | Some(error) => errors->Dict.set(`Rule ${(i + 1)->Int.toString} - Gateway`, error->JSON.Encode.string) | None => () } if !AdvancedRoutingUtils.validateStatements(rule.statements) { errors->Dict.set( `Rule ${(i + 1)->Int.toString} - Condition`, `Invalid`->JSON.Encode.string, ) } }) } errors->JSON.Encode.object } let handleActivateConfiguration = async activatingId => { try { setScreenState(_ => Loading) let activateRuleURL = getURL(~entityName=urlEntityName, ~methodType=Post, ~id=activatingId) let _ = await updateDetails(activateRuleURL, Dict.make()->JSON.Encode.object, Post) showToast(~message="Successfully Activated !", ~toastType=ToastState.ToastSuccess) RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url=`${baseUrlForRedirection}?`)) setScreenState(_ => Success) } catch { | Exn.Error(e) => switch Exn.message(e) { | Some(message) => if message->String.includes("IR_16") { showToast(~message="Algorithm is activated!", ~toastType=ToastState.ToastSuccess) RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url=baseUrlForRedirection)) setScreenState(_ => Success) } else { showToast( ~message="Failed to Activate the Configuration!", ~toastType=ToastState.ToastError, ) setScreenState(_ => Error(message)) } | None => setScreenState(_ => Error("Something went wrong")) } } } let handleDeactivateConfiguration = async _ => { try { setScreenState(_ => Loading) let deactivateRoutingURL = `${getURL(~entityName=urlEntityName, ~methodType=Post)}/deactivate` let body = [("profile_id", profile->JSON.Encode.string)]->Dict.fromArray->JSON.Encode.object let _ = await updateDetails(deactivateRoutingURL, body, Post) showToast(~message="Successfully Deactivated !", ~toastType=ToastState.ToastSuccess) RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url=`${baseUrlForRedirection}?`)) setScreenState(_ => Success) } catch { | Exn.Error(e) => switch Exn.message(e) { | Some(message) => { showToast( ~message="Failed to Deactivate the Configuration!", ~toastType=ToastState.ToastError, ) setScreenState(_ => Error(message)) } | None => setScreenState(_ => Error("Something went wrong")) } } } let onSubmit = async (values, isSaveRule) => { try { setScreenState(_ => Loading) let valuesDict = values->getDictFromJsonObject let dataDict = valuesDict->getDictfromDict("algorithm")->getDictfromDict("data") let rulesDict = dataDict->getArrayFromDict("rules", []) let modifiedRules = rulesDict->generateRule let defaultSelection = dataDict ->getDictfromDict("defaultSelection") ->getStrArrayFromDict("data", []) ->Array.map(id => { { "connector": ( connectorList->ConnectorTableUtils.getConnectorObjectFromListViaId(id) ).connector_name, "merchant_connector_id": id, } }) let payload = { "name": valuesDict->getString("name", ""), "description": valuesDict->getString("description", ""), "profile_id": valuesDict->getString("profile_id", ""), "algorithm": { "type": "advanced", "data": { "defaultSelection": { "type": "priority", "data": defaultSelection, }, "metadata": dataDict->getJsonObjectFromDict("metadata"), "rules": modifiedRules, }, }, } let getActivateUrl = getURL(~entityName=urlEntityName, ~methodType=Post, ~id=None) let response = await updateDetails(getActivateUrl, payload->Identity.genericTypeToJson, Post) showToast( ~message="Successfully Created a new Configuration !", ~toastType=ToastState.ToastSuccess, ) setScreenState(_ => Success) setShowModal(_ => false) if isSaveRule { RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url=baseUrlForRedirection)) } Nullable.make(response) } catch { | Exn.Error(e) => let err = Exn.message(e)->Option.getOr("Failed to Fetch!") showToast(~message="Failed to Save the Configuration!", ~toastType=ToastState.ToastError) setShowModal(_ => false) setScreenState(_ => PageLoaderWrapper.Error(err)) Exn.raiseError(err) } } let connectorType = switch url->RoutingUtils.urlToVariantMapper { | PayoutRouting => RoutingTypes.PayoutProcessor | _ => RoutingTypes.PaymentConnector } let connectorOptions = React.useMemo(() => { connectors ->RoutingUtils.filterConnectorList(~retainInList=connectorType) ->Array.filter(item => item.profile_id === profile) ->Array.map((item): SelectBox.dropdownOption => { { label: item.disabled ? `${item.connector_label} (disabled)` : item.connector_label, value: item.merchant_connector_id, } }) }, (profile, connectors->Array.length)) <div className="my-6"> <PageLoaderWrapper screenState> {connectors->Array.length > 0 ? <Form initialValues={initialValues} validate onSubmit={(values, _) => onSubmit(values, true)}> <div className="w-full flex flex-row justify-between"> <div className="w-full"> <BasicDetailsForm formState={pageState == Preview ? ViewConfig : CreateConfig} currentTabName profile setProfile /> <RenderIf condition={formState != CreateConfig}> <div className="mb-5"> <RuleBasedUI gatewayOptions=connectorOptions wasm initialRule pageState setCurrentRouting baseUrlForRedirection /> {switch pageState { | Preview => <div className="flex flex-col md:flex-row gap-4 p-1"> <Button text={"Duplicate and Edit Configuration"} buttonType={isActive ? Primary : Secondary} onClick={_ => { setPageState(_ => Create) let manipualtedJSONValue = initialValues->DuplicateAndEditUtils.manipulateInitialValuesForDuplicate let rulesValue = manipualtedJSONValue ->getDictFromJsonObject ->getObj("algorithm", Dict.make()) ->getDictfromDict("data") setInitialValues(_ => initialValues->DuplicateAndEditUtils.manipulateInitialValuesForDuplicate ) setInitialRule(_ => Some(ruleInfoTypeMapper(rulesValue))) }} customButtonStyle="w-1/5" buttonState=Normal /> <RenderIf condition={!isActive}> <Button text={"Activate Configuration"} buttonType={Primary} onClick={_ => { handleActivateConfiguration(routingRuleId)->ignore }} customButtonStyle="w-1/5" buttonState=Normal /> </RenderIf> <RenderIf condition={isActive}> <Button text={"Deactivate Configuration"} buttonType={Secondary} onClick={_ => { handleDeactivateConfiguration()->ignore }} customButtonStyle="w-1/5" buttonState=Normal /> </RenderIf> </div> | Create => <RoutingUtils.ConfigureRuleButton setShowModal /> | _ => React.null }} </div> </RenderIf> <CustomModal.RoutingCustomModal showModal setShowModal cancelButton={<FormRenderer.SubmitButton text="Save Rule" buttonSize=Button.Small buttonType=Button.Secondary customSumbitButtonStyle="w-1/5 rounded-xl" tooltipWidthClass="w-48" />} submitButton={<AdvancedRoutingUIUtils.SaveAndActivateButton onSubmit handleActivateConfiguration />} headingText="Activate Current Configuration?" subHeadingText="Activating this configuration will override the current one. Alternatively, save it to access later from the configuration history. Please confirm." leftIcon="warning-modal" iconSize=35 /> </div> </div> <FormValuesSpy /> </Form> : <NoDataFound message="Please configure atleast 1 connector" renderType=InfoBox />} </PageLoaderWrapper> </div> }
7,389
9,561
hyperswitch-control-center
src/screens/Routing/AdvancedRouting/AdvancedRoutingUIUtils.res
.res
open AdvancedRoutingUtils open FormRenderer module LogicalOps = { @react.component let make = (~id) => { let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext) let logicalOpsInput = ReactFinalForm.useField(`${id}.logical`).input React.useEffect(() => { if logicalOpsInput.value->LogicUtils.getStringFromJson("")->String.length === 0 { logicalOpsInput.onChange("AND"->Identity.stringToFormReactEvent) } None }, []) let onChange = str => logicalOpsInput.onChange(str->Identity.stringToFormReactEvent) <ButtonGroup wrapperClass="flex flex-row mr-2 ml-1"> {["AND", "OR"] ->Array.mapWithIndex((text, i) => { let active = logicalOpsInput.value->LogicUtils.getStringFromJson("") === text <Button key={i->Int.toString} text onClick={_ => onChange(text)} textStyle={active ? `${textColor.primaryNormal}` : ""} textWeight={active ? "font-semibold" : "font-medium"} customButtonStyle={active ? "shadow-inner" : ""} buttonType={active ? SecondaryFilled : Secondary} /> }) ->React.array} </ButtonGroup> } } module OperatorInp = { @react.component let make = (~fieldsArray: array<ReactFinalForm.fieldRenderProps>, ~keyType) => { let defaultInput: ReactFinalForm.fieldRenderProps = { input: ReactFinalForm.makeInputRecord(""->JSON.Encode.string, _ => ()), meta: ReactFinalForm.makeCustomError(None), } let field = (fieldsArray->Array.get(0)->Option.getOr(defaultInput)).input let operator = (fieldsArray->Array.get(1)->Option.getOr(defaultInput)).input let valInp = (fieldsArray->Array.get(2)->Option.getOr(defaultInput)).input let (opVals, setOpVals) = React.useState(_ => []) let input: ReactFinalForm.fieldRenderPropsInput = { name: "string", onBlur: _ => (), onChange: ev => { let value = ev->Identity.formReactEventToString operator.onChange(value->Identity.anyTypeToReactEvent) }, onFocus: _ => (), value: operator.value ->LogicUtils.getStringFromJson("") ->operatorMapper ->operatorTypeToStringMapper ->JSON.Encode.string, checked: true, } React.useEffect(() => { let operatorVals = switch keyType->variantTypeMapper { | Enum_variant => ["IS", "CONTAINS", "IS_NOT", "NOT_CONTAINS"] | Number => ["EQUAL TO", "GREATER THAN", "LESS THAN"] | Metadata_value => ["EQUAL TO"] | String_value => ["EQUAL TO", "NOT EQUAL_TO"] | _ => [] } setOpVals(_ => operatorVals) if operator.value->JSON.Decode.string->Option.isNone { operator.onChange(operatorVals[0]->Identity.anyTypeToReactEvent) } None }, (field.value, valInp.value)) let descriptionDict = [ ("IS", "Includes only results that exactly match the filter value(s)."), ("CONTAINS", "Includes only results with any value for the filter property."), ("IS_NOT", "Includes results that does not match the filter value(s)."), ("NOT_CONTAINS", "Includes results except any value for the filter property."), ]->Dict.fromArray let disableSelect = field.value->JSON.Decode.string->Option.getOr("")->String.length === 0 let operatorOptions = opVals->Array.map(opVal => { let obj: SelectBox.dropdownOption = { label: opVal, value: opVal, } switch descriptionDict->Dict.get(opVal) { | Some(description) => {...obj, description} | None => obj } }) let textColorStyle = disableSelect ? "text-hyperswitch_red opacity-50" : "text-hyperswitch_red" <SelectBox.BaseDropdown allowMultiSelect=false buttonText="Select Operator" input options=operatorOptions hideMultiSelectButtons=true textStyle={`text-body ${textColorStyle}`} disableSelect /> } } module ValueInp = { @react.component let make = (~fieldsArray: array<ReactFinalForm.fieldRenderProps>, ~variantValues, ~keyType) => { let valueField = (fieldsArray[1]->Option.getOr(ReactFinalForm.fakeFieldRenderProps)).input let opField = (fieldsArray[2]->Option.getOr(ReactFinalForm.fakeFieldRenderProps)).input let typeField = (fieldsArray[3]->Option.getOr(ReactFinalForm.fakeFieldRenderProps)).input React.useEffect(() => { typeField.onChange( if keyType->variantTypeMapper === Metadata_value { "metadata_variant" } else if keyType->variantTypeMapper === String_value { "str_value" } else { switch opField.value->LogicUtils.getStringFromJson("")->operatorMapper { | IS | IS_NOT => "enum_variant" | CONTAINS | NOT_CONTAINS => "enum_variant_array" | _ => "number" } }->Identity.anyTypeToReactEvent, ) None }, [valueField.value]) let input: ReactFinalForm.fieldRenderPropsInput = { name: "string", onBlur: _ => (), onChange: ev => { let value = ev->Identity.formReactEventToArrayOfString valueField.onChange(value->Identity.anyTypeToReactEvent) }, onFocus: _ => (), value: valueField.value, checked: true, } switch opField.value->LogicUtils.getStringFromJson("")->operatorMapper { | CONTAINS | NOT_CONTAINS => <SelectBox.BaseDropdown allowMultiSelect=true buttonText="Select Value" input options={variantValues->SelectBox.makeOptions} hideMultiSelectButtons=true showSelectionAsChips={false} maxHeight="max-h-full sm:max-h-64" /> | IS | IS_NOT => { let val = valueField.value->LogicUtils.getStringFromJson("") <SelectBox.BaseDropdown allowMultiSelect=false buttonText={val->String.length === 0 ? "Select Value" : val} input options={variantValues->SelectBox.makeOptions} hideMultiSelectButtons=true fixedDropDownDirection=SelectBox.TopRight /> } | EQUAL_TO => switch keyType->variantTypeMapper { | String_value | Metadata_value => <TextInput input placeholder="Enter value" /> | _ => <NumericTextInput placeholder={"Enter value"} input /> } | NOT_EQUAL_TO => <TextInput input placeholder="Enter value" /> | LESS_THAN | GREATER_THAN => <NumericTextInput placeholder={"Enter value"} input /> | _ => React.null } } } module MetadataInp = { @react.component let make = (~fieldsArray: array<ReactFinalForm.fieldRenderProps>, ~keyType) => { let valueField = (fieldsArray[2]->Option.getOr(ReactFinalForm.fakeFieldRenderProps)).input let textInput: ReactFinalForm.fieldRenderPropsInput = { name: "string", onBlur: _ => { let value = valueField.value let val = value->LogicUtils.getStringFromJson("") let valSplit = String.split(val, ",") let arrStr = valSplit->Array.map(item => { String.trim(item) }) let finalVal = Array.joinWith(arrStr, ",")->JSON.Encode.string valueField.onChange(finalVal->Identity.anyTypeToReactEvent) }, onChange: ev => { let target = ReactEvent.Form.target(ev) let value = target["value"] valueField.onChange(value->Identity.anyTypeToReactEvent) }, onFocus: _ => (), value: valueField.value, checked: true, } <RenderIf condition={keyType->variantTypeMapper === Metadata_value}> <TextInput placeholder={"Enter Key"} input=textInput /> </RenderIf> } } let renderOperatorInp = keyType => (fieldsArray: array<ReactFinalForm.fieldRenderProps>) => { <OperatorInp fieldsArray keyType /> } let renderValueInp = (keyType: string, variantValues) => ( fieldsArray: array<ReactFinalForm.fieldRenderProps>, ) => { <ValueInp fieldsArray variantValues keyType /> } let renderMetaInput = keyType => (fieldsArray: array<ReactFinalForm.fieldRenderProps>) => { <MetadataInp fieldsArray keyType /> } let operatorInput = (id, keyType) => { makeMultiInputFieldInfoOld( ~label="", ~comboCustomInput=renderOperatorInp(keyType), ~inputFields=[ makeInputFieldInfo(~name=`${id}.lhs`), makeInputFieldInfo(~name=`${id}.comparison`), makeInputFieldInfo(~name=`${id}.value.value`), ], (), ) } let valueInput = (id, variantValues, keyType) => { let valuePath = if keyType->variantTypeMapper === Metadata_value { `value.value.value` } else { `value.value` } makeMultiInputFieldInfoOld( ~label="", ~comboCustomInput=renderValueInp(keyType, variantValues), ~inputFields=[ makeInputFieldInfo(~name=`${id}.lhs`), makeInputFieldInfo(~name=`${id}.${valuePath}`), makeInputFieldInfo(~name=`${id}.comparison`), makeInputFieldInfo(~name=`${id}.value.type`), ], (), ) } let metaInput = (id, keyType) => makeMultiInputFieldInfoOld( ~label="", ~comboCustomInput=renderMetaInput(keyType), ~inputFields=[ makeInputFieldInfo(~name=`${id}.value`), makeInputFieldInfo(~name=`${id}.operator`), makeInputFieldInfo(~name=`${id}.value.value.key`), ], (), ) module FieldInp = { @react.component let make = (~methodKeys, ~prefix, ~onChangeMethod) => { let url = RescriptReactRouter.useUrl() let field = ReactFinalForm.useField(`${prefix}.lhs`).input let op = ReactFinalForm.useField(`${prefix}.comparison`).input let val = ReactFinalForm.useField(`${prefix}.value.value`).input let convertedValue = React.useMemo(() => { let keyDescriptionMapper = switch url->RoutingUtils.urlToVariantMapper { | PayoutRouting => Window.getPayoutDescriptionCategory()->Identity.jsonToAnyType | _ => Window.getDescriptionCategory()->Identity.jsonToAnyType } keyDescriptionMapper->LogicUtils.convertMapObjectToDict }, []) let options = React.useMemo(() => convertedValue ->Dict.keysToArray ->Array.reduce([], (acc, ele) => { open LogicUtils convertedValue ->getArrayFromDict(ele, []) ->Array.forEach( value => { let dictValue = value->LogicUtils.getDictFromJsonObject let kindValue = dictValue->getString("kind", "") if methodKeys->Array.includes(kindValue) { let generatedSelectBoxOptionType: SelectBox.dropdownOption = { label: kindValue, value: kindValue, description: dictValue->getString("description", ""), optGroup: ele, } acc->Array.push(generatedSelectBoxOptionType)->ignore } }, ) acc }) , []) let input: ReactFinalForm.fieldRenderPropsInput = { name: "string", onBlur: _ => (), onChange: ev => { let value = ev->Identity.formReactEventToString onChangeMethod(value) field.onChange(value->Identity.anyTypeToReactEvent) op.onChange(""->Identity.anyTypeToReactEvent) val.onChange(""->Identity.anyTypeToReactEvent) }, onFocus: _ => (), value: field.value, checked: true, } <SelectBox.BaseDropdown allowMultiSelect=false buttonText="Select Field" input options hideMultiSelectButtons=true /> } } module RuleFieldBase = { @react.component let make = (~isFirst, ~id, ~isExpanded, ~onClick, ~wasm, ~isFrom3ds, ~isFromSurcharge) => { let url = RescriptReactRouter.useUrl() let (hover, setHover) = React.useState(_ => false) let (keyType, setKeyType) = React.useState(_ => "") let (variantValues, setVariantValues) = React.useState(_ => []) let field = ReactFinalForm.useField(`${id}.lhs`).input let setKeyTypeAndVariants = (wasm, value) => { let keyType = getWasmKeyType(wasm, value) let keyVariant = keyType->variantTypeMapper if keyVariant !== Number || keyVariant !== Metadata_value { let variantValues = switch url->RoutingUtils.urlToVariantMapper { | PayoutRouting => getWasmPayoutVariantValues(wasm, value) | _ => getWasmVariantValues(wasm, value) } setVariantValues(_ => variantValues) } setKeyType(_ => keyType) } let onChangeMethod = value => { setKeyTypeAndVariants(wasm, value) } let methodKeys = React.useMemo(() => { let value = field.value->LogicUtils.getStringFromJson("") if value->LogicUtils.isNonEmptyString { setKeyTypeAndVariants(wasm, value) } if isFrom3ds { Window.getThreeDsKeys() } else if isFromSurcharge { Window.getSurchargeKeys() } else { switch url->RoutingUtils.urlToVariantMapper { | PayoutRouting => Window.getAllPayoutKeys() | _ => Window.getAllKeys() } } }, [field.value]) <RenderIf condition={methodKeys->Array.length > 0}> {if isExpanded { <div className={`flex flex-wrap items-center px-1 ${hover ? "rounded-md bg-white dark:bg-black shadow" : ""}`}> <RenderIf condition={!isFirst}> <LogicalOps id /> </RenderIf> <div className="-mt-5 p-1"> <FieldWrapper label=""> <FieldInp methodKeys prefix=id onChangeMethod /> </FieldWrapper> </div> <div className="-mt-5"> <FieldRenderer field={metaInput(id, keyType)} /> </div> <div className="-mt-5"> <FieldRenderer field={operatorInput(id, keyType)} /> </div> <div className="-mt-5"> <FieldRenderer field={valueInput(id, variantValues, keyType)} /> </div> <RenderIf condition={!isFirst}> <div onClick onMouseEnter={_ => setHover(_ => true)} onMouseLeave={_ => setHover(_ => false)} className="flex items-center cursor-pointer rounded-full border border-jp-gray-500 dark:border-jp-gray-960 bg-red-400 hover:shadow focus:outline-none p-2"> <Icon size=10 className="text-gray-50 font-semibold" name="close" /> </div> </RenderIf> </div> } else { <MakeRuleFieldComponent.CompressedView isFirst id keyType /> }} </RenderIf> } } module MakeRuleField = { @react.component let make = (~id, ~isExpanded, ~wasm, ~isFrom3ds, ~isFromSurcharge) => { let ruleJsonPath = `${id}.statements` let conditionsInput = ReactFinalForm.useField(ruleJsonPath).input let fields = conditionsInput.value->JSON.Decode.array->Option.getOr([]) let plusBtnEnabled = true //fields->Array.every(validateConditionJson) let onPlusClick = _ => { if plusBtnEnabled { let toAdd = Dict.make() conditionsInput.onChange( Array.concat( fields, [toAdd->JSON.Encode.object], )->Identity.arrayOfGenericTypeToFormReactEvent, ) } } let onCrossClick = index => { conditionsInput.onChange( fields ->Array.filterWithIndex((_, i) => index !== i) ->Identity.arrayOfGenericTypeToFormReactEvent, ) } <div className="flex flex-wrap items-center"> {Array.mapWithIndex(fields, (_, i) => <RuleFieldBase key={i->Int.toString} onClick={_ => onCrossClick(i)} isFirst={i === 0} id={`${ruleJsonPath}[${i->Int.toString}]`} isExpanded wasm isFrom3ds isFromSurcharge /> )->React.array} {if isExpanded { <div onClick={onPlusClick} className={`focus:outline-none p-2 ml-8 mt-2 md:mt-0 flex items-center bg-white dark:bg-jp-gray-darkgray_background rounded-full border border-jp-gray-500 dark:border-jp-gray-960 text-jp-gray-900 dark:text-jp-gray-text_darktheme ${plusBtnEnabled ? "cursor-pointer text-opacity-75 dark:text-opacity-50 hover:text-opacity-100 dark:hover:text-opacity-75 hover:shadow" : "cursor-not-allowed text-opacity-50 dark:text-opacity-50"}`}> <Icon size=14 name="plus" /> </div> } else { <Icon size=14 name="arrow-right" className="ml-4" /> }} </div> } } let configurationNameInput = makeFieldInfo( ~label="Configuration Name", ~name="name", ~isRequired=true, ~placeholder="Enter Configuration Name", ~customInput=InputFields.textInput(~autoFocus=true), ) let descriptionInput = makeFieldInfo( ~label="Description", ~name="description", ~isRequired=true, ~placeholder="Add a description for your configuration", ~customInput=InputFields.multiLineTextInput( ~isDisabled=false, ~rows=Some(3), ~cols=None, ~customClass="text-sm", ), ) module ConfigureRuleButton = { @react.component let make = (~setShowModal, ~isConfigButtonEnabled) => { let formState: ReactFinalForm.formState = ReactFinalForm.useFormState( ReactFinalForm.useFormSubscription(["values"])->Nullable.make, ) <Button text={"Configure Rule"} buttonType=Primary buttonState={!formState.hasValidationErrors && isConfigButtonEnabled ? Normal : Disabled} onClick={_ => { setShowModal(_ => true) }} customButtonStyle="w-1/5" /> } } module SaveAndActivateButton = { @react.component let make = ( ~onSubmit: (JSON.t, 'a) => promise<Nullable.t<JSON.t>>, ~handleActivateConfiguration, ) => { let formState: ReactFinalForm.formState = ReactFinalForm.useFormState( ReactFinalForm.useFormSubscription(["values"])->Nullable.make, ) let handleSaveAndActivate = async _ => { try { let onSubmitResponse = await onSubmit(formState.values, false) let currentActivatedFromJson = onSubmitResponse->LogicUtils.getValFromNullableValue(JSON.Encode.null) let currentActivatedId = currentActivatedFromJson->LogicUtils.getDictFromJsonObject->LogicUtils.getString("id", "") let _ = await handleActivateConfiguration(Some(currentActivatedId)) } catch { | Exn.Error(e) => let _err = Exn.message(e)->Option.getOr("Failed to save and activate configuration!") } } <Button text={"Save and Activate Rule"} buttonType={Primary} buttonSize=Button.Small onClick={_ => { handleSaveAndActivate()->ignore }} customButtonStyle="w-1/5" /> } }
4,470
9,562
hyperswitch-control-center
src/screens/Routing/AdvancedRouting/AddRuleGateway.res
.res
external anyToEnum: 'a => RoutingTypes.connectorSelectionData = "%identity" @react.component let make = (~id, ~gatewayOptions, ~isFirst=false, ~isExpanded) => { let url = RescriptReactRouter.useUrl() let gateWaysInput = ReactFinalForm.useField(`${id}.connectorSelection.data`).input let gateWaysType = ReactFinalForm.useField(`${id}.connectorSelection.type`).input let isDistributeInput = ReactFinalForm.useField(`${id}.isDistribute`).input let isDistribute = isDistributeInput.value->LogicUtils.getBoolFromJson(false) let connectorType: ConnectorTypes.connectorTypeVariants = switch url->RoutingUtils.urlToVariantMapper { | PayoutRouting => ConnectorTypes.PayoutProcessor | _ => ConnectorTypes.PaymentProcessor } let connectorList = ConnectorInterface.useConnectorArrayMapper( ~interface=ConnectorInterface.connectorInterfaceV1, ~retainInList=connectorType, ) React.useEffect(() => { let typeString = if isDistribute { "volume_split" } else { "priority" } gateWaysType.onChange(typeString->Identity.anyTypeToReactEvent) None }, [isDistributeInput.value]) let selectedOptions = React.useMemo(() => { gateWaysInput.value ->JSON.Decode.array ->Option.getOr([]) ->Belt.Array.keepMap(item => { Some(AdvancedRoutingUtils.connectorSelectionDataMapperFromJson(item)) }) }, [gateWaysInput]) let input: ReactFinalForm.fieldRenderPropsInput = { name: "gateways", onBlur: _ => (), onChange: ev => { let newSelectedOptions = ev->Identity.formReactEventToArrayOfString if newSelectedOptions->Array.length === 0 { gateWaysInput.onChange([]->Identity.anyTypeToReactEvent) } else { let gatewaysArr = newSelectedOptions->Array.map(item => { open RoutingTypes let sharePercent = isDistribute ? 100 / newSelectedOptions->Array.length : 100 if isDistribute { { connector: { connector: ( connectorList->ConnectorTableUtils.getConnectorObjectFromListViaId(item) ).connector_name, merchant_connector_id: item, }, split: sharePercent, }->Identity.genericTypeToJson } else { { connector: ( connectorList->ConnectorTableUtils.getConnectorObjectFromListViaId(item) ).connector_name, merchant_connector_id: item, }->Identity.genericTypeToJson } }) gateWaysInput.onChange(gatewaysArr->Identity.anyTypeToReactEvent) } }, onFocus: _ => (), value: selectedOptions ->Array.map(option => AdvancedRoutingUtils.getConnectorStringFromConnectorSelectionData( option, ).merchant_connector_id->JSON.Encode.string ) ->JSON.Encode.array, checked: true, } let onClickDistribute = newDistributeValue => { open RoutingTypes let sharePercent = newDistributeValue ? 100 / selectedOptions->Array.length : 100 let gatewaysArr = selectedOptions->Array.mapWithIndex((item, i) => { let sharePercent = if i === selectedOptions->Array.length - 1 && newDistributeValue { 100 - sharePercent * i } else { sharePercent } switch item { | PriorityObject(obj) => { connector: { connector: ( connectorList->ConnectorTableUtils.getConnectorObjectFromListViaId( obj.merchant_connector_id, ) ).connector_name, merchant_connector_id: obj.merchant_connector_id, }, split: sharePercent, }->Identity.genericTypeToJson | VolumeObject(obj) => obj.connector->Identity.genericTypeToJson } }) gateWaysInput.onChange(gatewaysArr->Identity.anyTypeToReactEvent) } let updatePercentage = (item: RoutingTypes.connectorSelectionData, value) => { open RoutingTypes let slectedConnector = switch item { | PriorityObject(obj) => obj.connector | VolumeObject(obj) => AdvancedRoutingUtils.getConnectorStringFromConnectorSelectionData( VolumeObject(obj), ).merchant_connector_id } if value < 100 { let newList = selectedOptions->Array.map(option => { switch option { | PriorityObject(obj) => obj.connector->Identity.genericTypeToJson | VolumeObject(obj) => { ...obj, split: slectedConnector === AdvancedRoutingUtils.getConnectorStringFromConnectorSelectionData( VolumeObject(obj), ).merchant_connector_id ? value : obj.split, }->Identity.genericTypeToJson } }) gateWaysInput.onChange(newList->Identity.anyTypeToReactEvent) } } let removeItem = index => { input.onChange( selectedOptions ->Array.map(i => AdvancedRoutingUtils.getConnectorStringFromConnectorSelectionData(i).merchant_connector_id ) ->Array.filterWithIndex((_, i) => i !== index) ->Identity.anyTypeToReactEvent, ) } if isExpanded { <div className="flex flex-row ml-2"> <RenderIf condition={!isFirst}> <div className="w-8 h-10 border-jp-gray-700 ml-10 border-dashed border-b border-l " /> </RenderIf> <div className="flex flex-col gap-6 mt-6 mb-4 pt-0.5"> <div className="flex flex-wrap gap-4"> <div className="flex"> <SelectBox.BaseDropdown allowMultiSelect=true buttonText="Add Processors" buttonType=Button.SecondaryFilled hideMultiSelectButtons=true customButtonStyle="!bg-white " input options={gatewayOptions} fixedDropDownDirection=SelectBox.TopRight searchable=true defaultLeftIcon={FontAwesome("plus")} maxHeight="max-h-full sm:max-h-64" /> <span className="text-lg text-red-500 ml-1"> {React.string("*")} </span> </div> {selectedOptions ->Array.mapWithIndex((item, i) => { let key = Int.toString(i + 1) <div key className="flex flex-row"> <div className="w-min flex flex-row items-center justify-around gap-2 rounded-lg border border-jp-gray-500 dark:border-jp-gray-960 hover:text-opacity-100 dark:hover:text-jp-gray-text_darktheme dark:hover:text-opacity-75 text-jp-gray-900 text-opacity-50 hover:text-jp-gray-900 bg-gradient-to-b from-jp-gray-250 dark:text-opacity-50 focus:outline-none px-2 text-sm cursor-pointer"> <NewThemeUtils.Badge number={i + 1} /> <div> {React.string( ( connectorList->ConnectorTableUtils.getConnectorObjectFromListViaId( ( item->AdvancedRoutingUtils.getConnectorStringFromConnectorSelectionData ).merchant_connector_id, ) ).connector_label, )} </div> <RenderIf condition={isDistribute && selectedOptions->Array.length > 0}> {<> <input className="w-10 text-right outline-none bg-white dark:bg-jp-gray-970 px-1 border border-jp-gray-300 dark:border-jp-gray-850 rounded-md" name=key onChange={ev => { let val = ReactEvent.Form.target(ev)["value"] updatePercentage(item, val->Int.fromString->Option.getOr(0)) }} value={item ->AdvancedRoutingUtils.getSplitFromConnectorSelectionData ->Int.toString} type_="text" inputMode="text" /> <div> {React.string("%")} </div> </>} </RenderIf> <Icon name="close" size=10 className="mr-2 cursor-pointer " onClick={ev => { ev->ReactEvent.Mouse.stopPropagation removeItem(i) }} /> </div> </div> }) ->React.array} </div> <RenderIf condition={selectedOptions->Array.length > 0}> <div className="flex flex-col md:flex-row md:items-center gap-4 md:gap-3 lg:gap-4 lg:ml-6"> <div className={`flex flex-row items-center gap-4 md:gap-1 lg:gap-2`}> <CheckBoxIcon isSelected=isDistribute setIsSelected={v => { isDistributeInput.onChange(v->Identity.anyTypeToReactEvent) onClickDistribute(v) }} isDisabled=false /> <div> {React.string("Distribute")} </div> </div> </div> </RenderIf> </div> </div> } else { <RulePreviewer.GatewayView gateways={selectedOptions} /> } }
2,014
9,563
hyperswitch-control-center
src/screens/Routing/AdvancedRouting/DuplicateAndEditUtils.res
.res
let getIsDistributed = distributedType => distributedType === "volume_split" let getConditionValue = (conditionArray, manipulatedStatementsArray, statementIndex) => { open LogicUtils let manipuatedConditionArray = conditionArray->Array.mapWithIndex(( eachContent, conditionIndex, ) => { let conditionDict = eachContent->getDictFromJsonObject let valueType = conditionDict->getDictfromDict("value")->getString("type", "") let manipulatedConditionDict = conditionDict->Dict.copy manipulatedConditionDict->Dict.set( "comparison", conditionDict ->getString("comparison", "") ->AdvancedRoutingUtils.getOperatorFromComparisonType(valueType) ->JSON.Encode.string, ) if statementIndex > 0 && conditionIndex == 0 { // If two sub-rules are joined using "OR" in the API call, they will appear as separate objects, one after another, in the 'statement' array. manipulatedConditionDict->Dict.set("logical", "OR"->JSON.Encode.string) } else if conditionIndex > 0 { // If two sub-rules are joined using "AND" in the API call, they will appear as separate objects, one after another, in the 'condition' array. manipulatedConditionDict->Dict.set("logical", "AND"->JSON.Encode.string) } manipulatedStatementsArray->Array.push(manipulatedConditionDict->JSON.Encode.object) manipulatedConditionDict->JSON.Encode.object }) manipuatedConditionArray->JSON.Encode.array } let getStatementsArray = statementsArray => { open LogicUtils let manipulatedStatementsArrayCustom = [] let _ = statementsArray->Array.mapWithIndex((eachStatement, statementIndex) => { let statementDict = eachStatement->getDictFromJsonObject let conditionValue = statementDict ->getArrayFromDict("condition", []) ->getConditionValue(manipulatedStatementsArrayCustom, statementIndex) conditionValue }) manipulatedStatementsArrayCustom->JSON.Encode.array } let getRulesValue = rulesArray => { open LogicUtils let manipulatedRulesArray = rulesArray->Array.map(eachRule => { let eachRuleDict = eachRule->getDictFromJsonObject let rulesDict = eachRuleDict->Dict.copy rulesDict->Dict.set( "statements", eachRuleDict->getArrayFromDict("statements", [])->getStatementsArray, ) let isDistibuted = rulesDict ->getObj("connectorSelection", Dict.make()) ->getString("type", "priority") ->getIsDistributed rulesDict->Dict.set("isDistribute", isDistibuted->JSON.Encode.bool) rulesDict->JSON.Encode.object }) manipulatedRulesArray->JSON.Encode.array } let dataMapper = dataDict => { open LogicUtils let manipuledDataDict = dataDict->Dict.copy manipuledDataDict->Dict.set("rules", dataDict->getArrayFromDict("rules", [])->getRulesValue) manipuledDataDict->JSON.Encode.object } let getAlgo = algoDict => { open LogicUtils let manipulatedAlgoDIct = algoDict->Dict.copy manipulatedAlgoDIct->Dict.set("data", algoDict->getObj("data", Dict.make())->dataMapper) manipulatedAlgoDIct->JSON.Encode.object } let manipulateInitialValuesForDuplicate = json => { open LogicUtils let previewDict = json->getDictFromJsonObject let finalJson = previewDict->Dict.copy finalJson->Dict.set("algorithm", previewDict->getObj("algorithm", Dict.make())->getAlgo) finalJson->JSON.Encode.object }
798
9,564
hyperswitch-control-center
src/screens/Routing/DefaultRouting/DefaultRouting.res
.res
open APIUtils open MerchantAccountUtils @react.component let make = (~urlEntityName, ~baseUrlForRedirection, ~connectorVariant) => { open LogicUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let fetchDetails = useGetMethod() let showPopUp = PopUpState.useShowPopUp() let businessProfiles = HyperswitchAtom.businessProfilesAtom->Recoil.useRecoilValueFromAtom let defaultBusinessProfile = businessProfiles->MerchantAccountUtils.getValueFromBusinessProfile let (profile, setProfile) = React.useState(_ => defaultBusinessProfile.profile_id) let showToast = ToastState.useShowToast() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let (gateways, setGateways) = React.useState(() => []) let (defaultRoutingResponse, setDefaultRoutingResponse) = React.useState(_ => []) let modalObj = RoutingUtils.getModalObj(DEFAULTFALLBACK, "default") let typedConnectorValue = ConnectorInterface.useConnectorArrayMapper( ~interface=ConnectorInterface.connectorInterfaceV1, ~retainInList=connectorVariant, ) let {globalUIConfig: {primaryColor}} = React.useContext(ThemeProvider.themeContext) let settingUpConnectorsState = routingRespArray => { let profileList = routingRespArray->Array.filter(value => value->getDictFromJsonObject->getString("profile_id", "") === profile ) let connectorList = switch profileList->Array.get(0) { | Some(json) => json ->getDictFromJsonObject ->getArrayFromDict("connectors", []) | _ => routingRespArray } if connectorList->Array.length > 0 { setGateways(_ => connectorList) setScreenState(_ => PageLoaderWrapper.Success) } else { setScreenState(_ => PageLoaderWrapper.Custom) } } let getConnectorsList = async () => { try { setScreenState(_ => PageLoaderWrapper.Loading) let defaultFallbackUrl = `${getURL(~entityName=urlEntityName, ~methodType=Get)}/profile` let response = await fetchDetails(defaultFallbackUrl) let routingRespArray = response->getArrayFromJson([]) setDefaultRoutingResponse(_ => routingRespArray) settingUpConnectorsState(routingRespArray) } catch { | Exn.Error(e) => let err = Exn.message(e)->Option.getOr("Failed to Fetch!") setScreenState(_ => PageLoaderWrapper.Error(err)) } } React.useEffect(() => { getConnectorsList()->ignore None }, []) React.useEffect(() => { if defaultRoutingResponse->Array.length > 0 { settingUpConnectorsState(defaultRoutingResponse) } None }, [profile]) let handleChangeOrder = async () => { try { // TODO : change setScreenState(_ => PageLoaderWrapper.Loading) let defaultPayload = gateways let defaultFallbackUpdateUrl = `${getURL( ~entityName=urlEntityName, ~methodType=Post, )}/profile/${profile}` ( await updateDetails(defaultFallbackUpdateUrl, defaultPayload->JSON.Encode.array, Post) )->ignore RescriptReactRouter.replace( GlobalVars.appendDashboardPath(~url=`${baseUrlForRedirection}/default`), ) setScreenState(_ => PageLoaderWrapper.Success) showToast(~message="Configuration saved successfully!", ~toastType=ToastState.ToastSuccess) } catch { | Exn.Error(e) => let err = Exn.message(e)->Option.getOr("Something went wrong") setScreenState(_ => PageLoaderWrapper.Error(err)) }->ignore } let openConfirmationPopUp = _ => { showPopUp({ popUpType: (Warning, WithIcon), heading: modalObj.conType, description: modalObj.conText, handleConfirm: {text: "Yes, save it", onClick: _ => handleChangeOrder()->ignore}, handleCancel: {text: "No, don't save"}, }) } <div> <Form initialValues={Dict.make()->JSON.Encode.object}> <div className="w-full flex justify-between"> <BasicDetailsForm.BusinessProfileInp setProfile={setProfile} profile={profile} options={businessProfiles->businessProfileNameDropDownOption} label="Profile" /> </div> </Form> <PageLoaderWrapper screenState customUI={<NoDataFound message="Please connect atleast 1 connector" renderType=Painting />}> <div className="flex flex-col gap-4 p-6 my-6 bg-white dark:bg-jp-gray-lightgray_background rounded-md border border-jp-gray-600 dark:border-jp-gray-850"> <div className="flex flex-col lg:flex-row "> <div> <div className="font-bold mb-1"> {React.string("Default Fallback")} </div> <div className="text-jp-gray-800 dark:text-jp-gray-700 text-sm flex flex-col"> <p> {React.string( "Default Fallback is helpful when you wish to define a simple pecking order of priority among the configured connectors. You may add the gateway and do a simple drag and drop.", )} </p> <p> {React.string("For example: 1. Stripe, 2. Adyen, 3.Braintree")} </p> </div> </div> </div> { let keyExtractor = (index, gateway: JSON.t, isDragging) => { let style = isDragging ? "border rounded-md bg-jp-gray-100 dark:bg-jp-gray-950" : "" let connectorName = gateway->getDictFromJsonObject->getString("connector", "") let merchantConnectorId = gateway->getDictFromJsonObject->getString("merchant_connector_id", "") let connectorLabel = ConnectorTableUtils.getConnectorObjectFromListViaId( typedConnectorValue, merchantConnectorId, ).connector_label <div className={`h-14 px-3 flex flex-row items-center justify-between text-jp-gray-900 dark:text-jp-gray-600 border-jp-gray-500 dark:border-jp-gray-960 ${index !== 0 ? "border-t" : ""} ${style}`}> <div className="flex flex-row items-center gap-4 ml-2"> <Icon name="grip-vertical" size=14 className={"cursor-pointer"} /> <div className={`px-1.5 rounded-full ${primaryColor} text-white font-semibold text-sm`}> {React.string(Int.toString(index + 1))} </div> <div className="flex gap-1 items-center"> <p> {connectorName->React.string} </p> <p className="text-sm opacity-50 "> {`(${connectorLabel})`->React.string} </p> </div> </div> </div> } <div className="flex border border-jp-gray-500 dark:border-jp-gray-960 rounded-md "> <DragDropComponent listItems=gateways setListItems={v => setGateways(_ => v)} keyExtractor isHorizontal=false /> </div> } </div> <Button onClick={_ => { openConfirmationPopUp() }} text="Save Changes" buttonSize=Small buttonType=Primary leftIcon={FontAwesome("check")} loadingText="Activating..." buttonState={gateways->Array.length > 0 ? Button.Normal : Button.Disabled} /> </PageLoaderWrapper> </div> }
1,712
9,565
hyperswitch-control-center
src/screens/Routing/VolumeSplitRouting/VolumeSplitRouting.res
.res
open APIUtils open RoutingTypes open VolumeSplitRoutingPreviewer open LogicUtils module VolumeRoutingView = { open RoutingUtils @react.component let make = ( ~setScreenState, ~routingId, ~pageState, ~setPageState, ~connectors: array<ConnectorTypes.connectorPayload>, ~isActive, ~profile, ~setFormState, ~initialValues, ~onSubmit, ~urlEntityName, ~connectorList, ~baseUrlForRedirection, ) => { let getURL = useGetURL() let updateDetails = useUpdateMethod(~showErrorToast=false) let showToast = ToastState.useShowToast() let listLength = connectors->Array.length let (showModal, setShowModal) = React.useState(_ => false) let gateways = initialValues ->getJsonObjectFromDict("algorithm") ->getDictFromJsonObject ->getArrayFromDict("data", []) let handleActivateConfiguration = async activatingId => { try { setScreenState(_ => PageLoaderWrapper.Loading) let activateRuleURL = getURL(~entityName=urlEntityName, ~methodType=Post, ~id=activatingId) let _ = await updateDetails(activateRuleURL, Dict.make()->JSON.Encode.object, Post) showToast(~message="Successfully Activated !", ~toastType=ToastState.ToastSuccess) RescriptReactRouter.replace( GlobalVars.appendDashboardPath(~url=`${baseUrlForRedirection}?`), ) setScreenState(_ => Success) } catch { | Exn.Error(e) => switch Exn.message(e) { | Some(message) => if message->String.includes("IR_16") { showToast(~message="Algorithm is activated!", ~toastType=ToastState.ToastSuccess) RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url=baseUrlForRedirection)) setScreenState(_ => Success) } else { showToast( ~message="Failed to Activate the Configuration!", ~toastType=ToastState.ToastError, ) setScreenState(_ => Error(message)) } | None => setScreenState(_ => Error("Something went wrong")) } } } let handleDeactivateConfiguration = async _ => { try { setScreenState(_ => Loading) let deactivateRoutingURL = `${getURL( ~entityName=urlEntityName, ~methodType=Post, )}/deactivate` let body = [("profile_id", profile->JSON.Encode.string)]->Dict.fromArray->JSON.Encode.object let _ = await updateDetails(deactivateRoutingURL, body, Post) showToast(~message="Successfully Deactivated !", ~toastType=ToastState.ToastSuccess) RescriptReactRouter.replace( GlobalVars.appendDashboardPath(~url=`${baseUrlForRedirection}?`), ) setScreenState(_ => Success) } catch { | Exn.Error(e) => switch Exn.message(e) { | Some(message) => { showToast( ~message="Failed to Deactivate the Configuration!", ~toastType=ToastState.ToastError, ) setScreenState(_ => Error(message)) } | None => setScreenState(_ => Error("Something went wrong")) } } } let connectorOptions = React.useMemo(() => { connectors ->Array.filter(item => item.profile_id === profile) ->Array.map((item): SelectBox.dropdownOption => { { label: item.disabled ? `${item.connector_label} (disabled)` : item.connector_label, value: item.merchant_connector_id, } }) }, [profile]) <> <div className="flex flex-col gap-4 p-6 my-2 bg-white dark:bg-jp-gray-lightgray_background rounded-md border border-jp-gray-600 dark:border-jp-gray-850"> <div className="flex flex-col lg:flex-row "> <div> <div className="font-bold mb-1"> {React.string("Volume Based Configuration")} </div> <div className="text-jp-gray-800 dark:text-jp-gray-700 text-sm"> {"Volume Based Configuration is helpful when you want a specific traffic distribution for each of the configured connectors. For eg: Stripe (70%), Adyen (20%), Checkout (10%)."->React.string} </div> </div> </div> </div> <div className="flex w-full flex-start"> {switch pageState { | Create => <div className="flex flex-col gap-4"> {listLength > 0 ? <> <AddPLGateway id="algorithm.data" gatewayOptions={connectorOptions} isExpanded={true} isFirst={true} showPriorityIcon={false} showDistributionIcon={false} showFallbackIcon={false} dropDownButtonText="Add Processors" connectorList /> <ConfigureRuleButton setShowModal /> <CustomModal.RoutingCustomModal showModal setShowModal cancelButton={<FormRenderer.SubmitButton text="Save Rule" buttonSize=Button.Small buttonType=Button.Secondary customSumbitButtonStyle="w-1/5 rounded-lg" tooltipWidthClass="w-48" />} submitButton={<AdvancedRoutingUIUtils.SaveAndActivateButton onSubmit handleActivateConfiguration />} headingText="Activate Current Configuration?" subHeadingText="Activating this configuration will override the current one. Alternatively, save it to access later from the configuration history. Please confirm." leftIcon="warning-modal" iconSize=35 /> </> : <NoDataFound message="Please configure atleast 1 connector" renderType=InfoBox />} </div> | Preview => <div className="flex flex-col w-full gap-3"> <div className="flex flex-col gap-4 p-6 my-2 bg-white rounded-md border border-jp-gray-600 "> <GatewayView gateways={gateways->getGatewayTypes} connectorList /> </div> <div className="flex flex-col md:flex-row gap-4"> <Button text={"Duplicate & Edit Configuration"} buttonType={Secondary} onClick={_ => { setFormState(_ => RoutingTypes.EditConfig) setPageState(_ => Create) }} customButtonStyle="w-1/5" /> <RenderIf condition={!isActive}> <Button text={"Activate Configuration"} buttonType={Primary} onClick={_ => { handleActivateConfiguration(routingId)->ignore }} buttonState={Normal} /> </RenderIf> <RenderIf condition={isActive}> <Button text={"Deactivate Configuration"} buttonType={Primary} onClick={_ => { handleDeactivateConfiguration()->ignore }} buttonState=Normal /> </RenderIf> </div> </div> | _ => React.null }} </div> </> } } @react.component let make = ( ~routingRuleId, ~isActive, ~connectorList: array<ConnectorTypes.connectorPayload>, ~urlEntityName, ~baseUrlForRedirection, ) => { let getURL = useGetURL() let updateDetails = useUpdateMethod(~showErrorToast=false) let businessProfiles = Recoil.useRecoilValueFromAtom(HyperswitchAtom.businessProfilesAtom) let defaultBusinessProfile = businessProfiles->MerchantAccountUtils.getValueFromBusinessProfile let (profile, setProfile) = React.useState(_ => defaultBusinessProfile.profile_id) let (formState, setFormState) = React.useState(_ => RoutingTypes.EditReplica) let (initialValues, setInitialValues) = React.useState(_ => Dict.make()) let fetchDetails = useGetMethod() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let (pageState, setPageState) = React.useState(() => Create) let (connectors, setConnectors) = React.useState(_ => []) let currentTabName = Recoil.useRecoilValueFromAtom(HyperswitchAtom.currentTabNameRecoilAtom) let showToast = ToastState.useShowToast() let getConnectorsList = () => { setConnectors(_ => connectorList) } let activeRoutingDetails = async () => { let routingUrl = getURL(~entityName=urlEntityName, ~methodType=Get, ~id=routingRuleId) let routingJson = await fetchDetails(routingUrl) let routingJsonToDict = routingJson->getDictFromJsonObject setFormState(_ => ViewConfig) setInitialValues(_ => routingJsonToDict) setProfile(_ => routingJsonToDict->getString("profile_id", defaultBusinessProfile.profile_id)) } let getDetails = async _ => { try { setScreenState(_ => Loading) getConnectorsList() switch routingRuleId { | Some(_id) => { await activeRoutingDetails() setPageState(_ => Preview) } | None => { setInitialValues(_ => { let dict = VOLUME_SPLIT->RoutingUtils.constructNameDescription dict->Dict.set("profile_id", profile->JSON.Encode.string) dict->Dict.set( "algorithm", { "type": "volume_split", }->Identity.genericTypeToJson, ) dict }) setPageState(_ => Create) } } setScreenState(_ => Success) } catch { | Exn.Error(e) => { let err = Exn.message(e)->Option.getOr("Something went wrong") setScreenState(_ => PageLoaderWrapper.Error(err)) } } } let validate = (values: JSON.t) => { let errors = Dict.make() let dict = values->getDictFromJsonObject let validateGateways = dict => { let gateways = dict->getArrayFromDict("data", []) if gateways->Array.length === 0 { Some("Need atleast 1 Gateway") } else { let distributionPercentages = gateways->Belt.Array.keepMap(json => { json->JSON.Decode.object->Option.flatMap(val => val->(getOptionFloat(_, "split"))) }) let distributionPercentageSum = distributionPercentages->Array.reduce(0., (sum, distribution) => sum +. distribution) let hasZero = distributionPercentages->Array.some(ele => ele === 0.) let isDistributeChecked = !(distributionPercentages->Array.some(ele => ele === 100.0)) let isNotValid = isDistributeChecked && (distributionPercentageSum > 100. || hasZero || distributionPercentageSum !== 100.) if isNotValid { Some("Distribution Percent not correct") } else { None } } } let volumeBasedDistributionDict = dict->getObj("algorithm", Dict.make()) switch volumeBasedDistributionDict->validateGateways { | Some(error) => errors->Dict.set("Volume Based Distribution", error->JSON.Encode.string) | None => () } errors->JSON.Encode.object } let onSubmit = async (values, isSaveRule) => { try { setScreenState(_ => PageLoaderWrapper.Loading) let updateUrl = getURL(~entityName=urlEntityName, ~methodType=Post, ~id=None) let res = await updateDetails(updateUrl, values, Post) showToast( ~message="Successfully Created a new Configuration !", ~toastType=ToastState.ToastSuccess, ) setScreenState(_ => Success) if isSaveRule { RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url="/routing")) } Nullable.make(res) } catch { | Exn.Error(e) => let err = Exn.message(e)->Option.getOr("Something went wrong!") showToast(~message="Failed to Save the Configuration !", ~toastType=ToastState.ToastError) setScreenState(_ => PageLoaderWrapper.Error(err)) Exn.raiseError(err) } } React.useEffect(() => { getDetails()->ignore None }, [routingRuleId]) <div className="my-6"> <PageLoaderWrapper screenState> <Form onSubmit={(values, _) => onSubmit(values, true)} validate initialValues={initialValues->JSON.Encode.object}> <div className="w-full flex justify-between"> <div className="w-full"> <BasicDetailsForm currentTabName formState setInitialValues profile setProfile routingType=VOLUME_SPLIT /> </div> </div> <RenderIf condition={formState != CreateConfig}> <VolumeRoutingView setScreenState pageState setPageState connectors routingId={routingRuleId} isActive initialValues profile setFormState onSubmit urlEntityName connectorList baseUrlForRedirection /> </RenderIf> <FormValuesSpy /> </Form> </PageLoaderWrapper> </div> }
2,855
9,566
hyperswitch-control-center
src/screens/Routing/VolumeSplitRouting/VolumeSplitRoutingPreviewer.res
.res
open RoutingTypes module GatewayView = { @react.component let make = (~gateways, ~connectorList=?) => { let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext) let getGatewayName = name => { switch connectorList { | Some(list) => (list->ConnectorTableUtils.getConnectorObjectFromListViaId(name)).connector_label | None => name } } <div className="flex flex-wrap gap-4 items-center"> {gateways ->Array.mapWithIndex((ruleGateway, index) => { <div key={Int.toString(index)} className={`my-2 h-6 md:h-8 flex items-center rounded-md border border-jp-gray-500 dark:border-jp-gray-960 font-medium ${textColor.primaryNormal} hover:${textColor.primaryNormal} bg-gradient-to-b from-jp-gray-250 to-jp-gray-200 dark:from-jp-gray-950 dark:to-jp-gray-950 focus:outline-none px-2 gap-1`}> {ruleGateway.gateway_name->getGatewayName->React.string} {if ruleGateway.distribution !== 100 { <span className="text-jp-gray-700 dark:text-jp-gray-600 ml-1"> {(ruleGateway.distribution->Int.toString ++ "%")->React.string} </span> } else { React.null }} </div> }) ->React.array} </div> } }
348
9,567
hyperswitch-control-center
src/screens/TransactionViews/TransactionViewTypes.res
.res
type operationsTypes = Orders | Refunds | Disputes type viewTypes = All | Succeeded | Failed | Dropoffs | Cancelled | Pending | None
34
9,568
hyperswitch-control-center
src/screens/TransactionViews/TransactionView.res
.res
module TransactionViewCard = { @react.component let make = (~view, ~count="", ~onViewClick, ~isActiveView) => { open TransactionViewUtils let textClass = isActiveView ? "text-primary" : "font-semibold text-jp-gray-700" let countTextClass = isActiveView ? "text-primary" : "font-semibold text-jp-gray-900" let borderClass = isActiveView ? "border-primary" : "" <div className={`flex flex-col justify-center flex-auto gap-1 bg-white text-semibold border rounded-md px-4 py-2.5 w-14 my-8 cursor-pointer hover:bg-gray-50 ${borderClass}`} onClick={_ => onViewClick(view)}> <p className={textClass}> {view->getViewsDisplayName->React.string} </p> <RenderIf condition={!(count->LogicUtils.isEmptyString)}> <p className={countTextClass}> {count->React.string} </p> </RenderIf> </div> } } @react.component let make = (~entity=TransactionViewTypes.Orders) => { open APIUtils open LogicUtils open TransactionViewUtils let getURL = useGetURL() let fetchDetails = useGetMethod() let showToast = ToastState.useShowToast() let {updateExistingKeys, filterValueJson, filterKeys, setfilterKeys} = FilterContext.filterContext->React.useContext let (countRes, setCountRes) = React.useState(_ => Dict.make()->JSON.Encode.object) let (activeView: TransactionViewTypes.viewTypes, setActiveView) = React.useState(_ => TransactionViewTypes.All ) let customFilterKey = getCustomFilterKey(entity) let updateViewsFilterValue = (view: TransactionViewTypes.viewTypes) => { let customFilter = `[${view->getViewsString(countRes, entity)}]` updateExistingKeys(Dict.fromArray([(customFilterKey, customFilter)])) if !(filterKeys->Array.includes(customFilterKey)) { filterKeys->Array.push(customFilterKey) setfilterKeys(_ => filterKeys) } } let onViewClick = (view: TransactionViewTypes.viewTypes) => { setActiveView(_ => view) updateViewsFilterValue(view) } let defaultDate = HSwitchRemoteFilter.getDateFilteredObject(~range=30) let startTime = filterValueJson->getString(OrderUIUtils.startTimeFilterKey, defaultDate.start_time) let endTime = filterValueJson->getString(OrderUIUtils.endTimeFilterKey, defaultDate.end_time) let getAggregate = async () => { try { let url = switch entity { | Orders => getURL( ~entityName=V1(ORDERS_AGGREGATE), ~methodType=Get, ~queryParamerters=Some(`start_time=${startTime}&end_time=${endTime}`), ) | Refunds => getURL( ~entityName=V1(REFUNDS_AGGREGATE), ~methodType=Get, ~queryParamerters=Some(`start_time=${startTime}&end_time=${endTime}`), ) | Disputes => getURL( ~entityName=V1(DISPUTES_AGGREGATE), ~methodType=Get, ~queryParamerters=Some(`start_time=${startTime}&end_time=${endTime}`), ) } let response = await fetchDetails(url) setCountRes(_ => response) } catch { | _ => showToast(~toastType=ToastError, ~message="Failed to fetch views count", ~autoClose=true) } } let settingActiveView = () => { let appliedStatusFilter = filterValueJson->getArrayFromDict(customFilterKey, []) let setViewToAll = appliedStatusFilter->getStrArrayFromJsonArray->Array.toSorted(compareLogic) == countRes ->getDictFromJsonObject ->getDictfromDict("status_with_count") ->Dict.keysToArray ->Array.toSorted(compareLogic) if appliedStatusFilter->Array.length == 1 { let status = appliedStatusFilter ->getValueFromArray(0, ""->JSON.Encode.string) ->JSON.Decode.string ->Option.getOr("") let viewType = status->getViewTypeFromString(entity) switch viewType { | All => setActiveView(_ => None) | _ => setActiveView(_ => viewType) } } else if setViewToAll { setActiveView(_ => All) } else { setActiveView(_ => None) } } React.useEffect(() => { settingActiveView() None }, (filterValueJson, countRes)) React.useEffect(() => { getAggregate()->ignore None }, (startTime, endTime)) let viewsArray = switch entity { | Orders => paymentViewsArray | Refunds => refundViewsArray | Disputes => disputeViewsArray } viewsArray ->Array.mapWithIndex((item, i) => <TransactionViewCard key={i->Int.toString} view={item} count={getViewCount(item, countRes, entity)->Int.toString} onViewClick isActiveView={item == activeView} /> ) ->React.array }
1,157
9,569
hyperswitch-control-center
src/screens/TransactionViews/TransactionViewUtils.res
.res
open TransactionViewTypes let paymentViewsArray: array<viewTypes> = [All, Succeeded, Failed, Dropoffs, Cancelled] let refundViewsArray: array<viewTypes> = [All, Succeeded, Failed, Pending] let disputeViewsArray: array<viewTypes> = [All, Succeeded, Failed, Pending] let getCustomFilterKey = entity => switch entity { | Orders => "status" | Refunds => "refund_status" | Disputes => "dispute_status" } let getViewsDisplayName = (view: viewTypes) => { switch view { | All => "All" | Succeeded => "Succeeded" | Failed => "Failed" | Dropoffs => "Dropoffs" | Cancelled => "Cancelled" | Pending => "Pending" | _ => "" } } let getViewTypeFromString = (view, entity) => { switch entity { | Orders => switch view { | "succeeded" => Succeeded | "cancelled" => Cancelled | "failed" => Failed | "requires_payment_method" => Dropoffs | "pending" => Pending | _ => All } | Refunds => switch view { | "success" => Succeeded | "failure" => Failed | "pending" => Pending | _ => All } | Disputes => switch view { | "dispute_won" => Succeeded | "dispute_lost" => Failed | "dispute_opened" => Pending | _ => All } } } let getAllViewsString = obj => { open LogicUtils obj ->getDictFromJsonObject ->getDictfromDict("status_with_count") ->Dict.keysToArray ->Array.joinWith(",") } let getViewsString = (view, obj, entity) => { switch entity { | Orders => switch view { | All => getAllViewsString(obj) | Succeeded => "succeeded" | Failed => "failed" | Dropoffs => "requires_payment_method" | Cancelled => "cancelled" | Pending => "pending" | _ => "" } | Refunds => switch view { | All => getAllViewsString(obj) | Succeeded => "success" | Failed => "failure" | Pending => "pending" | _ => "" } | Disputes => switch view { | All => getAllViewsString(obj) | Succeeded => "dispute_won" | Failed => "dispute_lost" | Pending => "dispute_opened" | _ => "" } } } let getAllViewCount = obj => { open LogicUtils let countArray = obj ->getDictFromJsonObject ->getDictfromDict("status_with_count") ->Dict.valuesToArray countArray->Array.reduce(0, (acc, curr) => (acc->Int.toFloat +. curr->getFloatFromJson(0.0))->Float.toInt ) } let getViewCount = (view, obj, entity) => { open LogicUtils switch view { | All => getAllViewCount(obj) | _ => obj ->getDictFromJsonObject ->getDictfromDict("status_with_count") ->getInt(view->getViewsString(obj, entity), 0) } }
754
9,570
hyperswitch-control-center
src/screens/ConnectorV2/PaymentProcessorSummary.res
.res
type connectorSummarySection = AuthenticationKeys | Metadata | PMTs @react.component let make = (~baseUrl, ~showProcessorStatus=true, ~topPadding="p-6") => { open ConnectorUtils open LogicUtils open APIUtils open PageLoaderWrapper let (currentActiveSection, setCurrentActiveSection) = React.useState(_ => None) let (initialValues, setInitialValues) = React.useState(_ => Dict.make()->JSON.Encode.object) let (screenState, setScreenState) = React.useState(_ => Loading) let {userInfo: {merchantId}} = React.useContext(UserInfoProvider.defaultContext) let getURL = useGetURL() let fetchDetails = useGetMethod() let updateAPIHook = useUpdateMethod(~showErrorToast=false) let fetchConnectorListResponse = ConnectorListHook.useFetchConnectorList( ~entityName=V2(V2_CONNECTOR), ~version=V2, ) let url = RescriptReactRouter.useUrl() let connectorID = HSwitchUtils.getConnectorIDFromUrl(url.path->List.toArray, "") let removeFieldsFromRespose = json => { let dict = json->getDictFromJsonObject dict->Dict.delete("applepay_verified_domains") dict->Dict.delete("business_country") dict->Dict.delete("business_label") dict->Dict.delete("business_sub_label") dict->JSON.Encode.object } let getConnectorDetails = async () => { try { setScreenState(_ => Loading) let connectorUrl = getURL( ~entityName=V2(V2_CONNECTOR), ~methodType=Get, ~id=Some(connectorID), ) let json = await fetchDetails(connectorUrl, ~version=V2) setInitialValues(_ => json->removeFieldsFromRespose) setScreenState(_ => Success) } catch { | _ => setScreenState(_ => PageLoaderWrapper.Error("Failed to fetch details")) } } React.useEffect(() => { getConnectorDetails()->ignore None }, []) let handleClick = (section: option<connectorSummarySection>) => { if section->Option.isNone { setInitialValues(_ => JSON.stringify(initialValues)->safeParse) } setCurrentActiveSection(_ => section) } let checkCurrentEditState = (section: connectorSummarySection) => { switch currentActiveSection { | Some(active) => active == section | _ => false } } let data = initialValues->getDictFromJsonObject let connectorInfodict = ConnectorInterface.mapDictToConnectorPayload( ConnectorInterface.connectorInterfaceV2, data, ) let {connector_name: connectorName} = connectorInfodict let connectorDetails = React.useMemo(() => { try { let (processorType, _) = connectorInfodict.connector_type ->connectorTypeTypedValueToStringMapper ->connectorTypeTuple if connectorName->LogicUtils.isNonEmptyString { let dict = switch processorType { | PaymentProcessor => Window.getConnectorConfig(connectorName) | PayoutProcessor => Window.getPayoutConnectorConfig(connectorName) | AuthenticationProcessor => Window.getAuthenticationConnectorConfig(connectorName) | PMAuthProcessor => Window.getPMAuthenticationProcessorConfig(connectorName) | TaxProcessor => Window.getTaxProcessorConfig(connectorName) | BillingProcessor => BillingProcessorsUtils.getConnectorConfig(connectorName) | PaymentVas => JSON.Encode.null } dict } else { JSON.Encode.null } } catch { | Exn.Error(e) => { Js.log2("FAILED TO LOAD CONNECTOR CONFIG", e) let _ = Exn.message(e)->Option.getOr("Something went wrong") JSON.Encode.null } } }, [connectorInfodict.id]) let ( _, connectorAccountFields, connectorMetaDataFields, _, connectorWebHookDetails, connectorLabelDetailField, _, ) = getConnectorFields(connectorDetails) let onSubmit = async (values, _form: ReactFinalForm.formApi) => { try { setScreenState(_ => Loading) let connectorUrl = getURL( ~entityName=V2(V2_CONNECTOR), ~methodType=Put, ~id=Some(connectorID), ) let dict = values->getDictFromJsonObject dict->Dict.set("merchant_id", merchantId->JSON.Encode.string) switch currentActiveSection { | Some(AuthenticationKeys) => { dict->Dict.delete("id") dict->Dict.delete("profile_id") dict->Dict.delete("merchant_connector_id") dict->Dict.delete("connector_name") } | _ => { dict->Dict.delete("profile_id") dict->Dict.delete("id") dict->Dict.delete("connector_name") dict->Dict.delete("connector_account_details") } } let response = await updateAPIHook(connectorUrl, dict->JSON.Encode.object, Put, ~version=V2) let _ = await fetchConnectorListResponse() setCurrentActiveSection(_ => None) setInitialValues(_ => response->removeFieldsFromRespose) setScreenState(_ => Success) } catch { | _ => setScreenState(_ => PageLoaderWrapper.Error("Failed to update")) } Nullable.null } 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) } let connectorTypeFromName = connectorName->getConnectorNameTypeFromString validateConnectorRequiredFields( connectorTypeFromName, valuesFlattenJson, connectorAccountFields, connectorMetaDataFields, connectorWebHookDetails, connectorLabelDetailField, errors->JSON.Encode.object, ) } let ignoreKeys = connectorDetails ->getDictFromJsonObject ->Dict.keysToArray ->Array.filter(val => !Array.includes(["credit", "debit"], val)) <PageLoaderWrapper screenState> <BreadCrumbNavigation path=[ { title: "Connected Processors ", link: `${baseUrl}`, }, ] currentPageTitle={`${connectorName->getDisplayNameForConnector}`} dividerVal=Slash customTextClass="text-nd_gray-400 font-medium " childGapClass="gap-2" titleTextClass="text-ng_gray-600 font-medium" /> <Form onSubmit initialValues validate=validateMandatoryField> <div className={`flex flex-col gap-10 ${topPadding} `}> <div> <div className="flex flex-row gap-4 items-center"> <GatewayIcon gateway={connectorName->String.toUpperCase} className=" w-10 h-10 rounded-sm" /> <p className={`text-2xl font-semibold break-all`}> {`${connectorName->getDisplayNameForConnector} Summary`->React.string} </p> </div> </div> <div className="flex flex-col gap-12"> <div className="flex gap-10 max-w-3xl flex-wrap px-2"> <ConnectorWebhookPreview merchantId connectorName=connectorInfodict.id truncateDisplayValue=true /> <div className="flex flex-col gap-0.5-rem "> <h4 className="text-nd_gray-400 "> {"Profile"->React.string} </h4> {connectorInfodict.profile_id->React.string} </div> <RenderIf condition=showProcessorStatus> <div className="flex flex-col gap-0.5-rem "> <h4 className="text-nd_gray-400 "> {"Processor status"->React.string} </h4> <div className="flex flex-row gap-2 items-center "> <ConnectorHelperV2.ProcessorStatus connectorInfo=connectorInfodict /> </div> </div> </RenderIf> </div> <div className="flex flex-col gap-4"> <div className="flex justify-between border-b pb-4 px-2 items-end"> <p className="text-lg font-semibold text-nd_gray-600"> {"Authentication keys"->React.string} </p> <div className="flex gap-4"> {if checkCurrentEditState(AuthenticationKeys) { <> <Button text="Cancel" onClick={_ => handleClick(None)} buttonType={Secondary} buttonSize={Small} customButtonStyle="w-fit" /> <FormRenderer.SubmitButton text="Save" buttonSize={Small} customSumbitButtonStyle="w-fit" /> </> } else { <div className="flex gap-2 items-center cursor-pointer" onClick={_ => handleClick(Some(AuthenticationKeys))}> <Icon name="nd-edit" size=14 /> <a className="text-primary cursor-pointer"> {"Edit"->React.string} </a> </div> }} </div> </div> {if checkCurrentEditState(AuthenticationKeys) { <ConnectorAuthKeys initialValues showVertically=false /> } else { <ConnectorHelperV2.PreviewCreds connectorInfo=connectorInfodict connectorAccountFields customContainerStyle="grid grid-cols-2 gap-12 flex-wrap max-w-3xl " customElementStyle="px-2 " /> }} </div> <div className="flex flex-col gap-4"> <div className="flex justify-between border-b pb-4 px-2 items-end"> <p className="text-lg font-semibold text-nd_gray-600"> {"Metadata"->React.string} </p> <div className="flex gap-4"> {if checkCurrentEditState(Metadata) { <> <Button text="Cancel" onClick={_ => handleClick(None)} buttonType={Secondary} buttonSize={Small} customButtonStyle="w-fit" /> <FormRenderer.SubmitButton text="Save" buttonSize={Small} customSumbitButtonStyle="w-fit" /> </> } else { <div className="flex gap-2 items-center cursor-pointer" onClick={_ => handleClick(Some(Metadata))}> <Icon name="nd-edit" size=14 /> <a className="text-primary cursor-pointer"> {"Edit"->React.string} </a> </div> }} </div> </div> <div className="grid grid-cols-2 gap-10 flex-wrap max-w-3xl"> <ConnectorLabelV2 labelClass="font-normal" labelTextStyleClass="text-nd_gray-400" isInEditState={checkCurrentEditState(Metadata)} connectorInfo=connectorInfodict /> <ConnectorMetadataV2 labelTextStyleClass="text-nd_gray-400" labelClass="font-normal" isInEditState={checkCurrentEditState(Metadata)} connectorInfo=connectorInfodict /> <ConnectorWebhookDetails labelTextStyleClass="text-nd_gray-400" labelClass="font-normal" isInEditState={checkCurrentEditState(Metadata)} connectorInfo=connectorInfodict /> </div> </div> <div className="flex justify-between border-b pb-4 px-2 items-end"> <p className="text-lg font-semibold text-nd_gray-600"> {"PMTs"->React.string} </p> <div className="flex gap-4"> {if checkCurrentEditState(PMTs) { <> <Button text="Cancel" buttonType={Secondary} onClick={_ => handleClick(None)} buttonSize={Small} customButtonStyle="w-fit" /> <FormRenderer.SubmitButton text="Save" buttonSize={Small} customSumbitButtonStyle="w-fit" /> </> } else { <div className="flex gap-2 items-center cursor-pointer" onClick={_ => handleClick(Some(PMTs))}> <Icon name="nd-edit" size=14 /> <a className="text-primary cursor-pointer"> {"Edit"->React.string} </a> </div> }} </div> </div> <ConnectorPaymentMethodV2 initialValues isInEditState={checkCurrentEditState(PMTs)} ignoreKeys /> </div> </div> <FormValuesSpy /> </Form> </PageLoaderWrapper> }
2,805
9,571
hyperswitch-control-center
src/screens/NewAnalytics/NewAnalyticsContainerUtils.res
.res
open NewAnalyticsTypes let getPageVariant = string => { switch string { | "new-analytics-smart-retry" => NewAnalyticsSmartRetry | "new-analytics-refund" => NewAnalyticsRefund | "new-analytics-payment" | _ => NewAnalyticsPayment } } let getPageIndex = (url: RescriptReactRouter.url) => { switch url.path->HSwitchUtils.urlPath { | list{"new-analytics-smart-retry"} => 1 | list{"new-analytics-refund"} => 2 | list{"new-analytics-payment"} | _ => 0 } } let getPageFromIndex = index => { switch index { | 1 => NewAnalyticsSmartRetry | 2 => NewAnalyticsRefund | 0 | _ => NewAnalyticsPayment } } let renderValueInp = () => (_fieldsArray: array<ReactFinalForm.fieldRenderProps>) => { React.null } let compareToInput = (~comparisonKey) => { FormRenderer.makeMultiInputFieldInfoOld( ~label="", ~comboCustomInput=renderValueInp(), ~inputFields=[ FormRenderer.makeInputFieldInfo(~name=`${comparisonKey}`), FormRenderer.makeInputFieldInfo(~name=`extraKey`), ], (), ) } let ( startTimeFilterKey, endTimeFilterKey, smartRetryKey, compareToStartTimeKey, compareToEndTimeKey, comparisonKey, ) = ( "startTime", "endTime", "is_smart_retry_enabled", "compareToStartTime", "compareToEndTime", "comparison", ) let initialFixedFilterFields = (~compareWithStartTime, ~compareWithEndTime, ~events=?) => { let events = switch events { | Some(fn) => fn | _ => () => () } 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, ~events, ), ~inputFields=[], ~isRequired=false, ), }: EntityType.initialFilters<'t> ), ( { localFilter: None, field: FormRenderer.makeMultiInputFieldInfo( ~label="", ~comboCustomInput=InputFields.filterCompareDateRangeField( ~startKey=compareToStartTimeKey, ~endKey=compareToEndTimeKey, ~comparisonKey, ~format="YYYY-MM-DDTHH:mm:ss[Z]", ~showTime=true, ~disablePastDates={false}, ~disableFutureDates={true}, ~predefinedDays=[Today, Yesterday, Day(2.0), Day(7.0), Day(30.0), ThisMonth, LastMonth], ~numMonths=2, ~disableApply=false, ~compareWithStartTime, ~compareWithEndTime, ), ~inputFields=[], ), }: EntityType.initialFilters<'t> ), ( { localFilter: None, field: compareToInput(~comparisonKey), }: EntityType.initialFilters<'t> ), ] newArr }
821
9,572
hyperswitch-control-center
src/screens/NewAnalytics/NewAnalyticsHelper.res
.res
let tableBorderClass = "border-2 border-solid border-jp-gray-940 border-collapse border-opacity-30 dark:border-jp-gray-dark_table_border_color dark:border-opacity-30" module Card = { @react.component let make = (~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`}> {children} </div> } } module NoData = { @react.component let make = (~height="h-96") => { <div className={`${height} border-2 flex justify-center items-center border-dashed opacity-70 rounded-lg p-5 m-7`}> {"No entires in selected time period."->React.string} </div> } } module Shimmer = { @react.component let make = (~className="w-full h-96", ~layoutId) => { <FramerMotion.Motion.Div className={`${className} bg-gradient-to-r from-gray-100 via-gray-200 to-gray-100`} initial={{backgroundPosition: "-200% 0"}} animate={{backgroundPosition: "200% 0"}} transition={{duration: 1.5, ease: "easeInOut", repeat: 10000}} style={{backgroundSize: "200% 100%"}} layoutId /> } } module TabSwitch = { @react.component let make = (~viewType, ~setViewType) => { open NewAnalyticsTypes let (icon1Bg, icon1Color, icon1Name) = switch viewType { | Graph => ("bg-white", "text-grey-dark", "graph-dark") | Table => ("bg-grey-light", "", "graph") } let (icon2Bg, icon2Color, icon2Name) = switch viewType { | Graph => ("bg-grey-light", "text-grey-medium", "table-view") | Table => ("bg-white", "text-grey-dark", "table-view") } <div className="border border-gray-outline flex w-fit rounded-lg cursor-pointer h-fit"> <div className={`rounded-l-lg pl-3 pr-2 pt-2 pb-0.5 ${icon1Bg}`} onClick={_ => setViewType(Graph)}> <Icon className={icon1Color} name={icon1Name} size=25 /> </div> <div className="h-full border-l border-gray-outline" /> <div className={`rounded-r-lg pl-3 pr-2 pt-2 ${icon2Bg}`} onClick={_ => setViewType(Table)}> <Icon className={icon2Color} name=icon2Name size=25 /> </div> </div> } } module Tabs = { open NewAnalyticsTypes @react.component let make = ( ~option: optionType, ~setOption: optionType => unit, ~options: array<optionType>, ~showSingleTab=true, ) => { let getStyle = (value: string, index) => { let textStyle = value === option.value ? "bg-white text-grey-dark font-medium" : "bg-grey-light text-grey-medium" let borderStyle = index === 0 ? "" : "border-l" let borderRadius = if options->Array.length == 1 { "rounded-lg" } else if index === 0 { "rounded-l-lg" } else if index === options->Array.length - 1 { "rounded-r-lg" } else { "" } `${textStyle} ${borderStyle} ${borderRadius}` } <RenderIf condition={showSingleTab || options->Array.length > 1}> <div className="border border-gray-outline flex w-fit rounded-lg cursor-pointer text-sm h-fit"> {options ->Array.mapWithIndex((tabValue, index) => <div key={index->Int.toString} className={`px-3 py-2 ${tabValue.value->getStyle(index)} selection:bg-white`} onClick={_ => setOption(tabValue)}> {tabValue.label->React.string} </div> ) ->React.array} </div> </RenderIf> } } module CustomDropDown = { open NewAnalyticsTypes @react.component let make = ( ~buttonText: optionType, ~options: array<optionType>, ~setOption: optionType => unit, ~positionClass="right-0", ) => { open HeadlessUI let (arrow, setArrow) = React.useState(_ => false) <Menu \"as"="div" className="relative inline-block text-left"> {_ => <div> <Menu.Button className="inline-flex whitespace-pre leading-5 justify-center text-sm px-4 py-2 font-medium rounded-lg hover:bg-opacity-80 bg-white border"> {_ => { <> {buttonText.label->React.string} <Icon className={arrow ? `rotate-0 transition duration-[250ms] ml-1 mt-1 opacity-60` : `rotate-180 transition duration-[250ms] ml-1 mt-1 opacity-60`} name="arrow-without-tail" size=15 /> </> }} </Menu.Button> <Transition \"as"="span" enter="transition ease-out duration-100" enterFrom="transform opacity-0 scale-95" enterTo="transform opacity-100 scale-100" leave="transition ease-in duration-75" leaveFrom="transform opacity-100 scale-100" leaveTo="transform opacity-0 scale-95"> {<Menu.Items className={`absolute ${positionClass} z-50 w-max mt-2 origin-top-right bg-white dark:bg-jp-gray-950 divide-y divide-gray-100 rounded-md shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none`}> {props => { setArrow(_ => props["open"]) <div className="p-1"> {options ->Array.mapWithIndex((option, i) => <Menu.Item key={i->Int.toString}> {props => <div className="relative"> <button onClick={_ => setOption(option)} className={ let activeClasses = if props["active"] { "group flex rounded-md items-center w-full px-2 py-2 text-sm bg-gray-100 dark:bg-black" } else { "group flex rounded-md items-center w-full px-2 py-2 text-sm" } `${activeClasses} font-medium text-start` }> <div className="mr-5"> {option.label->React.string} </div> </button> </div>} </Menu.Item> ) ->React.array} </div> }} </Menu.Items>} </Transition> </div>} </Menu> } } module StatisticsCard = { open NewAnalyticsTypes @react.component let make = (~value, ~tooltipValue as _, ~direction, ~isOverviewComponent=false) => { let (bgColor, textColor) = switch direction { | Upward => ("bg-green-light", "text-green-dark") | Downward => ("bg-red-light", "text-red-dark") | No_Change => ("bg-gray-100", "text-gray-500") } let icon = switch direction { | Downward => <img alt="image" className="h-6 w-5 mb-1 mr-1" src={`/icons/arrow.svg`} /> | Upward | No_Change => <Icon className="mt-1 -mr-1" name="arrow-increasing" size=25 /> } let wrapperClass = isOverviewComponent ? "scale-[0.9]" : "" <div className={`${wrapperClass} ${bgColor} ${textColor} w-fit h-fit rounded-2xl flex px-2 pt-0.5`}> <div className="-mb-0.5 flex"> {icon} <div className="font-semibold text-sm pt-0.5 pr-0.5"> {`${value->LogicUtils.valueFormatter(Rate)}`->React.string} </div> </div> </div> } } module NoteSection = { @react.component let make = (~text) => { <div className="w-fit mx-7 mb-7 mt-3 py-3 px-4 bg-yellow-bg rounded-lg flex gap-2 font-medium"> <Icon name="info-vacent" size=16 /> <p className="text-grey-text text-sm"> {text->React.string} </p> </div> } } module ModuleHeader = { @react.component let make = (~title) => { <h2 className="font-semibold text-xl text-jp-gray-900 pb-5"> {title->React.string} </h2> } } module SmartRetryToggle = { open LogicUtils open NewAnalyticsContainerUtils @react.component let make = () => { let {updateExistingKeys, filterValue, filterValueJson} = React.useContext( FilterContext.filterContext, ) let (isEnabled, setIsEnabled) = React.useState(_ => false) React.useEffect(() => { let value = filterValueJson->getString(smartRetryKey, "true")->getBoolFromString(true) setIsEnabled(_ => value) None }, [filterValueJson]) let onClick = _ => { let updatedValue = !isEnabled let newValue = filterValue->Dict.copy newValue->Dict.set(smartRetryKey, updatedValue->getStringFromBool) newValue->updateExistingKeys } <div className="w-fit px-3 py-2 border rounded-lg bg-white gap-2 items-center h-fit inline-flex whitespace-pre leading-5 justify-center"> <BoolInput.BaseComponent isSelected={isEnabled} setIsSelected={onClick} isDisabled=false boolCustomClass="rounded-lg !bg-primary" toggleBorder="border-primary" /> <p className="!text-base text-grey-700 gap-2 inline-flex whitespace-pre justify-center font-medium text-start"> <span className="text-sm font-medium"> {"Include Payment Retries data"->React.string} </span> <ToolTip description="Your data will consist of all the payment retries that contributed to the success rate" toolTipFor={<div className="cursor-pointer"> <Icon name="info-vacent" size=13 className="mt-1" /> </div>} toolTipPosition=ToolTip.Top newDesign=true /> </p> </div> } } module OverViewStat = { open NewAnalyticsUtils open NewAnalyticsTypes @react.component let make = (~responseKey, ~data, ~getInfo, ~getValueFromObj, ~getStringFromVariant) => { open LogicUtils let {filterValueJson} = React.useContext(FilterContext.filterContext) let comparison = filterValueJson->getString("comparison", "")->DateRangeUtils.comparisonMapprer let currency = filterValueJson->getString((#currency: NewAnalyticsTypes.filters :> string), "") let primaryValue = getValueFromObj(data, 0, responseKey->getStringFromVariant) let secondaryValue = getValueFromObj(data, 1, responseKey->getStringFromVariant) let (value, direction) = calculatePercentageChange(~primaryValue, ~secondaryValue) let config = getInfo(~responseKey) let displyValue = valueFormatter(primaryValue, config.valueType, ~currency) <Card> <div className="p-6 flex flex-col gap-4 justify-between h-full gap-auto relative"> <div className="flex justify-between w-full items-end"> <div className="flex gap-1 items-center"> <div className="font-bold text-3xl"> {displyValue->React.string} </div> <div className="scale-[0.9]"> <RenderIf condition={comparison === EnableComparison}> <StatisticsCard value direction tooltipValue={valueFormatter(secondaryValue, config.valueType, ~currency)} /> </RenderIf> </div> </div> </div> <div className={"flex flex-col gap-1 text-black"}> <div className="font-semibold dark:text-white"> {config.titleText->React.string} </div> <div className="opacity-50 text-sm"> {config.description->React.string} </div> </div> </div> </Card> } }
2,843
9,573
hyperswitch-control-center
src/screens/NewAnalytics/NewAnalyticsUtils.res
.res
// colors let redColor = "#BA3535" let blue = "#1059C1B2" let green = "#0EB025B2" let barGreenColor = "#7CC88F" let sankyBlue = "#E4EFFF" let sankyRed = "#F7E0E0" let sankyLightBlue = "#91B7EE" let sankyLightRed = "#EC6262" open NewAnalyticsTypes let globalFilter: array<filters> = [#currency] let globalExcludeValue = [(#all_currencies: defaultFilters :> string)] let requestBody = ( ~startTime: string, ~endTime: string, ~metrics: array<metrics>, ~groupByNames: option<array<string>>=None, ~filter: option<JSON.t>, ~delta: option<bool>=None, ~granularity: option<string>=None, ~distributionValues: option<JSON.t>=None, ~mode: option<string>=None, ) => { let metrics = metrics->Array.map(v => (v: metrics :> string)) [ AnalyticsUtils.getFilterRequestBody( ~metrics=Some(metrics), ~delta=delta->Option.getOr(false), ~groupByNames, ~filter, ~startDateTime=startTime, ~endDateTime=endTime, ~granularity, ~distributionValues, ~mode, )->JSON.Encode.object, ]->JSON.Encode.array } let getMonthName = month => { switch month { | 0 => "Jan" | 1 => "Feb" | 2 => "Mar" | 3 => "Apr" | 4 => "May" | 5 => "Jun" | 6 => "Jul" | 7 => "Aug" | 8 => "Sep" | 9 => "Oct" | 10 => "Nov" | 11 => "Dec" | _ => "" } } let formatDateValue = (value: string, ~includeYear=false) => { let dateObj = value->DayJs.getDayJsForString if includeYear { `${dateObj.month()->getMonthName} ${dateObj.format("DD")} ${dateObj.year()->Int.toString} ` } else { `${dateObj.month()->getMonthName} ${dateObj.format("DD")}` } } let getLabelName = (~key, ~index, ~points) => { open LogicUtils let getDateObject = (array, index) => { array ->getValueFromArray(index, Dict.make()->JSON.Encode.object) ->getDictFromJsonObject ->getString(key, "") } if key === "time_bucket" { let pointsArray = points->getArrayFromJson([]) let startPoint = pointsArray->getDateObject(0) let endPoint = pointsArray->getDateObject(pointsArray->Array.length - 1) let startDate = startPoint->formatDateValue let endDate = endPoint->formatDateValue `${startDate} - ${endDate}` } else { `Series ${(index + 1)->Int.toString}` } } let calculatePercentageChange = (~primaryValue, ~secondaryValue) => { open NewAnalyticsTypes let change = primaryValue -. secondaryValue if secondaryValue === 0.0 || change === 0.0 { (0.0, No_Change) } else if change > 0.0 { let diff = change /. secondaryValue let percentage = diff *. 100.0 (percentage, Upward) } else { let diff = change *. -1.0 /. secondaryValue let percentage = diff *. 100.0 (percentage, Downward) } } let getToolTipConparision = (~primaryValue, ~secondaryValue) => { let (value, direction) = calculatePercentageChange(~primaryValue, ~secondaryValue) let (textColor, icon) = switch direction { | Upward => ("#12B76A", "▲") | Downward => ("#F04E42", "▼") | No_Change => ("#A0A0A0", "") } `<span style="color:${textColor};margin-left:7px;" >${icon}${value->LogicUtils.valueFormatter( Rate, )}</span>` } open LogicUtils // removes the NA buckets let filterQueryData = (query, key) => { query->Array.filter(data => { let valueDict = data->getDictFromJsonObject valueDict->getString(key, "")->isNonEmptyString }) } let sortQueryDataByDate = query => { query->Array.sort((a, b) => { let valueA = a->getDictFromJsonObject->getString("time_bucket", "") let valueB = b->getDictFromJsonObject->getString("time_bucket", "") compareLogic(valueB, valueA) }) query } let getMaxValue = (data: JSON.t, index: int, key: string) => { data ->getArrayFromJson([]) ->getValueFromArray(index, []->JSON.Encode.array) ->getArrayFromJson([]) ->Array.reduce(0.0, (acc, item) => { let value = item->getDictFromJsonObject->getFloat(key, 0.0) Math.max(acc, value) }) } let isEmptyGraph = (data: JSON.t, key: string) => { let primaryMaxValue = data->getMaxValue(0, key) let secondaryMaxValue = data->getMaxValue(1, key) Math.max(primaryMaxValue, secondaryMaxValue) == 0.0 } let checkTimePresent = (options, key) => { options->Array.reduce(false, (flag, item) => { let value = item->getDictFromJsonObject->getString(key, "NA") if value->isNonEmptyString && key == "time_bucket" { let dateObj = value->DayJs.getDayJsForString dateObj.format("HH") != "00" || flag } else { false } }) } let formatTime = time => { let hour = time->String.split(":")->Array.get(0)->Option.getOr("00")->Int.fromString->Option.getOr(0) let mimute = time->String.split(":")->Array.get(1)->Option.getOr("00")->Int.fromString->Option.getOr(0) let newHour = Int.mod(hour, 12) let newHour = newHour == 0 ? 12 : newHour let period = hour >= 12 ? "PM" : "AM" if mimute > 0 { `${newHour->Int.toString}:${mimute->Int.toString} ${period}` } else { `${newHour->Int.toString} ${period}` } } let getCategories = (data: JSON.t, index: int, key: string) => { let options = data ->getArrayFromJson([]) ->getValueFromArray(index, []->JSON.Encode.array) ->getArrayFromJson([]) let isShowTime = options->checkTimePresent(key) options->Array.map(item => { let value = item->getDictFromJsonObject->getString(key, "NA") if value->isNonEmptyString && key == "time_bucket" { let dateObj = value->DayJs.getDayJsForString let date = `${dateObj.month()->getMonthName} ${dateObj.format("DD")}` if isShowTime { let time = dateObj.format("HH:mm")->formatTime `${date}, ${time}` } else { date } } else { value } }) } let getMetaDataValue = (~data, ~index, ~key) => { data ->getArrayFromJson([]) ->getValueFromArray(index, Dict.make()->JSON.Encode.object) ->getDictFromJsonObject ->getFloat(key, 0.0) } let getBarGraphObj = ( ~array: array<JSON.t>, ~key: string, ~name: string, ~color, ): BarGraphTypes.dataObj => { let data = array->Array.map(item => { item->getDictFromJsonObject->getFloat(key, 0.0) }) let dataObj: BarGraphTypes.dataObj = { showInLegend: false, name, data, color, } dataObj } let bargraphTooltipFormatter = (~title, ~metricType) => { open BarGraphTypes ( @this (this: pointFormatter) => { let title = `<div style="font-size: 16px; font-weight: bold;">${title}</div>` let defaultValue = {color: "", x: "", y: 0.0, point: {index: 0}} let primartPoint = this.points->getValueFromArray(0, defaultValue) let getRowsHtml = (~iconColor, ~date, ~value, ~comparisionComponent="") => { let valueString = valueFormatter(value, metricType) `<div style="display: flex; align-items: center;"> <div style="width: 10px; height: 10px; background-color:${iconColor}; border-radius:3px;"></div> <div style="margin-left: 8px;">${date}${comparisionComponent}</div> <div style="flex: 1; text-align: right; font-weight: bold;margin-left: 25px;">${valueString}</div> </div>` } let tableItems = [ getRowsHtml(~iconColor=primartPoint.color, ~date=primartPoint.x, ~value=primartPoint.y), ]->Array.joinWith("") let content = ` <div style=" padding:5px 12px; display:flex; flex-direction:column; justify-content: space-between; gap: 7px;"> ${title} <div style=" margin-top: 5px; display:flex; flex-direction:column; gap: 7px;"> ${tableItems} </div> </div>` `<div style=" padding: 10px; width:fit-content; border-radius: 7px; background-color:#FFFFFF; padding:10px; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2); border: 1px solid #E5E5E5; position:relative;"> ${content} </div>` } )->asTooltipPointFormatter } let getColor = index => { [blue, green]->Array.get(index)->Option.getOr(blue) } let getAmountValue = (data, ~id) => { switch data->getOptionFloat(id) { | Some(value) => value /. 100.0 | _ => 0.0 } } let getLineGraphObj = ( ~array: array<JSON.t>, ~key: string, ~name: string, ~color, ~isAmount=false, ): LineGraphTypes.dataObj => { let data = array->Array.map(item => { let dict = item->getDictFromJsonObject if isAmount { dict->getAmountValue(~id=key) } else { dict->getFloat(key, 0.0) } }) let dataObj: LineGraphTypes.dataObj = { showInLegend: true, name, data, color, } dataObj } let getLineGraphData = (data, ~xKey, ~yKey, ~isAmount=false) => { data ->getArrayFromJson([]) ->Array.mapWithIndex((item, index) => { let name = getLabelName(~key=yKey, ~index, ~points=item) let color = index->getColor getLineGraphObj(~array=item->getArrayFromJson([]), ~key=xKey, ~name, ~color, ~isAmount) }) } let tooltipFormatter = ( ~secondaryCategories, ~title, ~metricType, ~comparison: option<DateRangeUtils.comparison>=None, ~currency="", ~reverse=false, ~suffix="", ~showNameInTooltip=false, ) => { open LineGraphTypes ( @this (this: pointFormatter) => { let title = `<div style="font-size: 16px; font-weight: bold;">${title}</div>` let defaultValue = {color: "", x: "", y: 0.0, point: {index: 0}, series: {name: ""}} let primaryIndex = reverse ? 1 : 0 let secondaryIndex = reverse ? 0 : 1 let primartPoint = this.points->getValueFromArray(primaryIndex, defaultValue) let secondaryPoint = this.points->getValueFromArray(secondaryIndex, defaultValue) let getRowsHtml = (~iconColor, ~date, ~name="", ~value, ~comparisionComponent="") => { let valueString = valueFormatter(value, metricType, ~currency, ~suffix) let key = showNameInTooltip ? name : date `<div style="display: flex; align-items: center;"> <div style="width: 10px; height: 10px; background-color:${iconColor}; border-radius:3px;"></div> <div style="margin-left: 8px;">${key}${comparisionComponent}</div> <div style="flex: 1; text-align: right; font-weight: bold;margin-left: 25px;">${valueString}</div> </div>` } let tableItems = [ getRowsHtml( ~iconColor=primartPoint.color, ~date=primartPoint.x, ~name=primartPoint.series.name, ~value=primartPoint.y, ~comparisionComponent={ switch comparison { | Some(value) => value == DateRangeUtils.EnableComparison ? getToolTipConparision( ~primaryValue=primartPoint.y, ~secondaryValue=secondaryPoint.y, ) : "" | None => "" } }, ), { switch comparison { | Some(value) => value == DateRangeUtils.EnableComparison ? getRowsHtml( ~iconColor=secondaryPoint.color, ~date=secondaryCategories->getValueFromArray(secondaryPoint.point.index, ""), ~value=secondaryPoint.y, ~name=secondaryPoint.series.name, ) : "" | None => "" } }, ]->Array.joinWith("") let content = ` <div style=" padding:5px 12px; border-left: 3px solid #0069FD; display:flex; flex-direction:column; justify-content: space-between; gap: 7px;"> ${title} <div style=" margin-top: 5px; display:flex; flex-direction:column; gap: 7px;"> ${tableItems} </div> </div>` `<div style=" padding: 10px; width:fit-content; border-radius: 7px; background-color:#FFFFFF; padding:10px; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2); border: 1px solid #E5E5E5; position:relative;"> ${content} </div>` } )->asTooltipPointFormatter } let generateFilterObject = (~globalFilters, ~localFilters=None) => { let filters = Dict.make() let globalFiltersList = globalFilter->Array.map(filter => { (filter: filters :> string) }) let parseStringValue = string => { string ->JSON.Decode.string ->Option.getOr("") ->String.split(",") ->Array.filter(value => { !(globalExcludeValue->Array.includes(value)) }) ->Array.map(JSON.Encode.string) } globalFilters ->Dict.toArray ->Array.forEach(item => { let (key, value) = item if globalFiltersList->Array.includes(key) && value->parseStringValue->Array.length > 0 { filters->Dict.set(key, value->parseStringValue->JSON.Encode.array) } }) switch localFilters { | Some(dict) => dict ->Dict.toArray ->Array.forEach(item => { let (key, value) = item filters->Dict.set(key, value) }) | None => () } filters->JSON.Encode.object } let getGranularityLabel = option => { switch option { | #G_ONEDAY => "Day-wise" | #G_ONEHOUR => "Hour-wise" | #G_THIRTYMIN => "30min-wise" | #G_FIFTEENMIN => "15min-wise" } } let defaulGranularity = { label: #G_ONEDAY->getGranularityLabel, value: (#G_ONEDAY: granularity :> string), } let getGranularityOptions = (~startTime, ~endTime) => { let startingPoint = startTime->DayJs.getDayJsForString let endingPoint = endTime->DayJs.getDayJsForString let gap = endingPoint.diff(startingPoint.toString(), "hour") // diff between points let options = if gap < 1 { [#G_THIRTYMIN, #G_FIFTEENMIN] } else if gap < 24 { [#G_ONEHOUR, #G_THIRTYMIN, #G_FIFTEENMIN] } else if gap < 168 { [#G_ONEDAY, #G_ONEHOUR] } else { [#G_ONEDAY] } options->Array.map(option => { label: option->getGranularityLabel, value: (option: granularity :> string), }) } let getDefaultGranularity = (~startTime, ~endTime, ~granularity) => { let options = getGranularityOptions(~startTime, ~endTime) if granularity { options->Array.get(options->Array.length - 1)->Option.getOr(defaulGranularity) } else { defaulGranularity } } let getGranularityGap = option => { switch option { | "G_ONEHOUR" => 60 | "G_THIRTYMIN" => 30 | "G_FIFTEENMIN" => 15 | "G_ONEDAY" | _ => 1440 } } let fillMissingDataPoints = ( ~data, ~startDate, ~endDate, ~timeKey="time_bucket", ~defaultValue: JSON.t, ~granularity: string, ~isoStringToCustomTimeZone: string => TimeZoneHook.dateTimeString, ~granularityEnabled, ) => { let dataDict = Dict.make() data->Array.forEach(item => { let time = switch (granularityEnabled, granularity != (#G_ONEDAY: granularity :> string)) { | (true, true) => { let value = item ->getDictFromJsonObject ->getObj("time_range", Dict.make()) let time = value->getString("start_time", "") let {year, month, date, hour, minute} = isoStringToCustomTimeZone(time) if ( granularity == (#G_THIRTYMIN: granularity :> string) || granularity == (#G_FIFTEENMIN: granularity :> string) ) { (`${year}-${month}-${date} ${hour}:${minute}`->DayJs.getDayJsForString).format( "YYYY-MM-DD HH:mm:ss", ) } else { (`${year}-${month}-${date} ${hour}:${minute}`->DayJs.getDayJsForString).format( "YYYY-MM-DD HH:00:00", ) } } | _ => item ->getDictFromJsonObject ->getString(timeKey, "") } let newItem = item->getDictFromJsonObject newItem->Dict.set("time_bucket", time->JSON.Encode.string) dataDict->Dict.set(time, newItem->JSON.Encode.object) }) let dataPoints = Dict.make() let startingPoint = startDate->DayJs.getDayJsForString let startingPoint = startingPoint.format("YYYY-MM-DD HH:00:00")->DayJs.getDayJsForString let endingPoint = endDate->DayJs.getDayJsForString let gap = "minute" let devider = granularity->getGranularityGap let limit = (endingPoint.diff(startingPoint.toString(), gap)->Int.toFloat /. devider->Int.toFloat) ->Math.floor ->Float.toInt let format = granularity != (#G_ONEDAY: granularity :> string) ? "YYYY-MM-DD HH:mm:ss" : "YYYY-MM-DD 00:00:00" for x in 0 to limit { let newDict = defaultValue->getDictFromJsonObject->Dict.copy let timeVal = startingPoint.add(x * devider, gap).format(format) switch dataDict->Dict.get(timeVal) { | Some(val) => { newDict->Dict.set(timeKey, timeVal->JSON.Encode.string) dataPoints->Dict.set(timeVal, val) } | None => { newDict->Dict.set(timeKey, timeVal->JSON.Encode.string) dataPoints->Dict.set(timeVal, newDict->JSON.Encode.object) } } } dataPoints->Dict.valuesToArray }
4,801
9,574
hyperswitch-control-center
src/screens/NewAnalytics/NewAnalyticsTypes.res
.res
type analyticsPages = Payment type viewType = Graph | Table type statisticsDirection = Upward | Downward | No_Change type analyticsPagesRoutes = | @as("new-analytics-payment") NewAnalyticsPayment | @as("new-analytics-smart-retry") NewAnalyticsSmartRetry | @as("new-analytics-refund") NewAnalyticsRefund type domain = [#payments | #refunds | #disputes] type dimension = [ | #connector | #payment_method | #payment_method_type | #card_network | #authentication_type | #error_reason | #refund_error_message | #refund_reason ] type status = [#charged | #failure | #success | #pending] type metrics = [ | #sessionized_smart_retried_amount | #sessionized_payments_success_rate | #sessionized_payment_processed_amount | #refund_processed_amount | #dispute_status_metric | #payments_distribution | #failure_reasons | #payments_distribution | #payment_success_rate | #failure_reasons | // Refunds #sessionized_refund_processed_amount | #sessionized_refund_success_count | #sessionized_refund_success_rate | #sessionized_refund_count | #sessionized_refund_error_message | #sessionized_refund_reason | // Authentication Analytics #authentication_count | #authentication_attempt_count | #authentication_success_count | #challenge_flow_count | #frictionless_flow_count | #frictionless_success_count | #challenge_attempt_count | #challenge_success_count | #authentication_funnel | #authentication_error_message ] type granularity = [ | #G_ONEDAY | #G_ONEHOUR | #G_THIRTYMIN | #G_FIFTEENMIN ] type requestBodyConfig = { metrics: array<metrics>, delta?: bool, groupBy?: array<dimension>, filters?: array<dimension>, customFilter?: dimension, applyFilterFor?: array<status>, excludeFilterValue?: array<status>, } type moduleEntity = { requestBodyConfig: requestBodyConfig, title: string, domain: domain, } type getObjects<'data> = { data: 'data, xKey: string, yKey: string, comparison?: DateRangeUtils.comparison, currency?: string, } type chartEntity<'t, 'chartOption, 'data> = { getObjects: (~params: getObjects<'data>) => 't, getChatOptions: 't => 'chartOption, } type optionType = {label: string, value: string} type metricType = | Smart_Retry | Default type singleStatConfig = { titleText: string, description: string, valueType: LogicUtilsTypes.valueType, } type filters = [#currency] type defaultFilters = [#all_currencies | #none]
661
9,575
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/NewPaymentAnalyticsUtils.res
.res
open LogicUtils let getColor = index => { open NewAnalyticsUtils [blue, green]->Array.get(index)->Option.getOr(blue) } let getAmountValue = (data, ~id) => { switch data->getOptionFloat(id) { | Some(value) => value /. 100.0 | _ => 0.0 } } let getLineGraphObj = ( ~array: array<JSON.t>, ~key: string, ~name: string, ~color, ~isAmount=false, ): LineGraphTypes.dataObj => { let data = array->Array.map(item => { let dict = item->getDictFromJsonObject if isAmount { dict->getAmountValue(~id=key) } else { dict->getFloat(key, 0.0) } }) let dataObj: LineGraphTypes.dataObj = { showInLegend: true, name, data, color, } dataObj } let getBarGraphData = (json: JSON.t, key: string, barColor: string): BarGraphTypes.data => { json ->getArrayFromJson([]) ->Array.mapWithIndex((item, index) => { let data = item ->getDictFromJsonObject ->getArrayFromDict("queryData", []) ->Array.map(item => { item->getDictFromJsonObject->getFloat(key, 0.0) }) let dataObj: BarGraphTypes.dataObj = { showInLegend: false, name: `Series ${(index + 1)->Int.toString}`, data, color: barColor, } dataObj }) } let getSmartRetryMetricType = isSmartRetryEnabled => { open NewAnalyticsTypes switch isSmartRetryEnabled { | true => Smart_Retry | false => Default } } let getEntityForSmartRetry = isEnabled => { open NewAnalyticsTypes open APIUtilsTypes switch isEnabled { | Smart_Retry => ANALYTICS_PAYMENTS | Default => ANALYTICS_PAYMENTS_V2 } }
468
9,576
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/NewPaymentAnalyticsEntity.res
.res
open NewAnalyticsTypes // OverView section let overviewSectionEntity: moduleEntity = { requestBodyConfig: { delta: true, metrics: [], }, title: "OverView Section", domain: #payments, } // Payments Lifecycle let paymentsLifeCycleEntity: moduleEntity = { requestBodyConfig: { delta: false, metrics: [#sessionized_payment_processed_amount], }, title: "Payments Lifecycle", domain: #payments, } let paymentsLifeCycleChartEntity: chartEntity< SankeyGraphTypes.sankeyPayload, SankeyGraphTypes.sankeyGraphOptions, PaymentsLifeCycleTypes.paymentLifeCycle, > = { getObjects: PaymentsLifeCycleUtils.paymentsLifeCycleMapper, getChatOptions: SankeyGraphUtils.getSankyGraphOptions, } // Payments Processed let paymentsProcessedEntity: moduleEntity = { requestBodyConfig: { delta: false, metrics: [#sessionized_payment_processed_amount], }, title: "Payments Processed", domain: #payments, } let paymentsProcessedChartEntity: chartEntity< LineGraphTypes.lineGraphPayload, LineGraphTypes.lineGraphOptions, JSON.t, > = { getObjects: PaymentsProcessedUtils.paymentsProcessedMapper, getChatOptions: LineGraphUtils.getLineGraphOptions, } let paymentsProcessedTableEntity = { open PaymentsProcessedUtils EntityType.makeEntity( ~uri=``, ~getObjects, ~dataKey="queryData", ~defaultColumns=visibleColumns, ~requiredSearchFieldsList=[], ~allColumns=visibleColumns, ~getCell, ~getHeading, ) } // Payments Success Rate let paymentsSuccessRateEntity: moduleEntity = { requestBodyConfig: { delta: false, metrics: [#sessionized_payments_success_rate], }, title: "Payments Success Rate", domain: #payments, } let paymentsSuccessRateChartEntity: chartEntity< LineGraphTypes.lineGraphPayload, LineGraphTypes.lineGraphOptions, JSON.t, > = { getObjects: PaymentsSuccessRateUtils.paymentsSuccessRateMapper, getChatOptions: LineGraphUtils.getLineGraphOptions, } // Successful Payments Distribution let successfulPaymentsDistributionEntity: moduleEntity = { requestBodyConfig: { delta: false, metrics: [#payments_distribution], }, title: "Successful Payments Distribution", domain: #payments, } let successfulPaymentsDistributionChartEntity: chartEntity< BarGraphTypes.barGraphPayload, BarGraphTypes.barGraphOptions, JSON.t, > = { getObjects: SuccessfulPaymentsDistributionUtils.successfulPaymentsDistributionMapper, getChatOptions: BarGraphUtils.getBarGraphOptions, } let successfulPaymentsDistributionTableEntity = { open SuccessfulPaymentsDistributionUtils EntityType.makeEntity( ~uri=``, ~getObjects, ~dataKey="queryData", ~defaultColumns=[], ~requiredSearchFieldsList=[], ~allColumns=[], ~getCell, ~getHeading, ) } // Failed Payments Distribution let failedPaymentsDistributionEntity: moduleEntity = { requestBodyConfig: { delta: false, metrics: [#payments_distribution], }, title: "Failed Payments Distribution", domain: #payments, } let failedPaymentsDistributionChartEntity: chartEntity< BarGraphTypes.barGraphPayload, BarGraphTypes.barGraphOptions, JSON.t, > = { getObjects: FailedPaymentsDistributionUtils.failedPaymentsDistributionMapper, getChatOptions: BarGraphUtils.getBarGraphOptions, } let failedPaymentsDistributionTableEntity = { open FailedPaymentsDistributionUtils EntityType.makeEntity( ~uri=``, ~getObjects, ~dataKey="queryData", ~defaultColumns=[], ~requiredSearchFieldsList=[], ~allColumns=[], ~getCell, ~getHeading, ) } // Payments Failure Reasons let failureReasonsEntity: moduleEntity = { requestBodyConfig: { delta: false, metrics: [#failure_reasons], groupBy: [#error_reason], }, title: "Failure Reasons ", domain: #payments, } let failureReasonsTableEntity = { open FailureReasonsPaymentsUtils EntityType.makeEntity( ~uri=``, ~getObjects, ~dataKey="queryData", ~defaultColumns=[], ~requiredSearchFieldsList=[], ~allColumns=[], ~getCell, ~getHeading, ) }
951
9,577
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/NewPaymentAnalytics.res
.res
@react.component let make = () => { open NewPaymentAnalyticsEntity let {newAnalyticsFilters} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom <div className="flex flex-col gap-14 mt-5 pt-7"> <div className="flex gap-2"> <NewAnalyticsHelper.SmartRetryToggle /> <RenderIf condition={newAnalyticsFilters}> <NewAnalyticsFilters domain={#payments} entityName={V1(ANALYTICS_PAYMENTS)} /> </RenderIf> </div> <NewPaymentsOverviewSection entity={overviewSectionEntity} /> <PaymentsLifeCycle entity={paymentsLifeCycleEntity} chartEntity={paymentsLifeCycleChartEntity} /> <PaymentsProcessed entity={paymentsProcessedEntity} chartEntity={paymentsProcessedChartEntity} /> <PaymentsSuccessRate entity={paymentsSuccessRateEntity} chartEntity={paymentsSuccessRateChartEntity} /> <SuccessfulPaymentsDistribution entity={successfulPaymentsDistributionEntity} chartEntity={successfulPaymentsDistributionChartEntity} /> <FailedPaymentsDistribution entity={failedPaymentsDistributionEntity} chartEntity={failedPaymentsDistributionChartEntity} /> <FailureReasonsPayments entity={failureReasonsEntity} /> </div> }
279
9,578
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/PaymentsProcessed/PaymentsProcessedTypes.res
.res
type paymentsProcessedCols = | Payment_Processed_Amount | Payment_Processed_Count | Total_Payment_Processed_Amount | Total_Payment_Processed_Count | Time_Bucket type responseKeys = [ | #payment_processed_amount | #payment_processed_amount_in_usd | #payment_processed_amount_without_smart_retrie | #payment_processed_amount_without_smart_retries_in_usd | #payment_processed_count | #payment_processed_count_without_smart_retries | #total_payment_processed_amount | #total_payment_processed_amount_in_usd | #total_payment_processed_amount_without_smart_retries | #total_payment_processed_amount_without_smart_retries_in_usd | #total_payment_processed_count | #total_payment_processed_count_without_smart_retries | #time_bucket ] type paymentsProcessedObject = { payment_processed_amount: float, payment_processed_count: int, total_payment_processed_amount: float, total_payment_processed_count: int, time_bucket: string, }
226
9,579
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/PaymentsProcessed/PaymentsProcessedUtils.res
.res
open PaymentsProcessedTypes open LogicUtils let getStringFromVariant = value => { switch value { | Payment_Processed_Amount => "payment_processed_amount" | Payment_Processed_Count => "payment_processed_count" | Total_Payment_Processed_Amount => "total_payment_processed_amount" | Total_Payment_Processed_Count => "total_payment_processed_count" | Time_Bucket => "time_bucket" } } let getVariantValueFromString = value => { switch value { | "payment_processed_amount" | "payment_processed_amount_in_usd" => Payment_Processed_Amount | "payment_processed_count" => Payment_Processed_Count | "total_payment_processed_amount" | "total_payment_processed_amount_in_usd" => Total_Payment_Processed_Amount | "total_payment_processed_count" => Total_Payment_Processed_Count | "time_bucket" | _ => Time_Bucket } } let isAmountMetric = key => { switch key->getVariantValueFromString { | Payment_Processed_Amount | Total_Payment_Processed_Amount => true | _ => false } } let paymentsProcessedMapper = ( ~params: NewAnalyticsTypes.getObjects<JSON.t>, ): LineGraphTypes.lineGraphPayload => { open LineGraphTypes open NewAnalyticsUtils let {data, xKey, yKey} = params let comparison = switch params.comparison { | Some(val) => Some(val) | None => None } let currency = params.currency->Option.getOr("") let primaryCategories = data->getCategories(0, yKey) let secondaryCategories = data->getCategories(1, yKey) let lineGraphData = data->getLineGraphData(~xKey, ~yKey, ~isAmount=xKey->isAmountMetric) open LogicUtilsTypes let metricType = switch xKey->getVariantValueFromString { | Payment_Processed_Amount => Amount | _ => Volume } let tooltipFormatter = tooltipFormatter( ~secondaryCategories, ~title="Payments Processed", ~metricType, ~comparison, ~currency, ) { chartHeight: DefaultHeight, chartLeftSpacing: DefaultLeftSpacing, categories: primaryCategories, data: lineGraphData, title: { text: "", }, yAxisMaxValue: None, yAxisMinValue: Some(0), tooltipFormatter, yAxisFormatter: LineGraphUtils.lineGraphYAxisFormatter( ~statType=Default, ~currency="", ~suffix="", ), legend: { useHTML: true, labelFormatter: LineGraphUtils.valueFormatter, }, } } let visibleColumns = [Time_Bucket] let tableItemToObjMapper: Dict.t<JSON.t> => paymentsProcessedObject = dict => { open NewAnalyticsUtils { payment_processed_amount: dict->getAmountValue( ~id=Payment_Processed_Amount->getStringFromVariant, ), payment_processed_count: dict->getInt(Payment_Processed_Count->getStringFromVariant, 0), total_payment_processed_amount: dict->getAmountValue( ~id=Total_Payment_Processed_Amount->getStringFromVariant, ), total_payment_processed_count: dict->getInt( Total_Payment_Processed_Count->getStringFromVariant, 0, ), time_bucket: dict->getString(Time_Bucket->getStringFromVariant, "NA"), } } let getObjects: JSON.t => array<paymentsProcessedObject> = json => { json ->LogicUtils.getArrayFromJson([]) ->Array.map(item => { tableItemToObjMapper(item->getDictFromJsonObject) }) } let getHeading = colType => { switch colType { | Payment_Processed_Amount => Table.makeHeaderInfo( ~key=Payment_Processed_Amount->getStringFromVariant, ~title="Amount", ~dataType=TextType, ) | Payment_Processed_Count => Table.makeHeaderInfo( ~key=Payment_Processed_Count->getStringFromVariant, ~title="Count", ~dataType=TextType, ) | Time_Bucket => Table.makeHeaderInfo(~key=Time_Bucket->getStringFromVariant, ~title="Date", ~dataType=TextType) | Total_Payment_Processed_Amount | Total_Payment_Processed_Count => Table.makeHeaderInfo(~key="", ~title="", ~dataType=TextType) } } let getCell = (obj, colType): Table.cell => { open NewAnalyticsUtils switch colType { | Payment_Processed_Amount => Text(obj.payment_processed_amount->valueFormatter(Amount)) | Payment_Processed_Count => Text(obj.payment_processed_count->Int.toString) | Time_Bucket => Text(obj.time_bucket->formatDateValue(~includeYear=true)) | Total_Payment_Processed_Amount | Total_Payment_Processed_Count => Text("") } } open NewAnalyticsTypes let dropDownOptions = [ {label: "By Amount", value: Payment_Processed_Amount->getStringFromVariant}, {label: "By Count", value: Payment_Processed_Count->getStringFromVariant}, ] let defaultMetric = { label: "By Amount", value: Payment_Processed_Amount->getStringFromVariant, } let defaulGranularity = { label: "Daily", value: (#G_ONEDAY: granularity :> string), } open NewAnalyticsTypes let getKey = (id, ~isSmartRetryEnabled=Smart_Retry, ~currency="") => { let key = switch id { | Time_Bucket => #time_bucket | Payment_Processed_Count => switch isSmartRetryEnabled { | Smart_Retry => #payment_processed_count | Default => #payment_processed_count_without_smart_retries } | Total_Payment_Processed_Count => switch isSmartRetryEnabled { | Smart_Retry => #total_payment_processed_count | Default => #total_payment_processed_count_without_smart_retries } | Payment_Processed_Amount => switch (isSmartRetryEnabled, currency->getTypeValue) { | (Smart_Retry, #all_currencies) => #payment_processed_amount_in_usd | (Smart_Retry, _) => #payment_processed_amount | (Default, #all_currencies) => #payment_processed_amount_without_smart_retries_in_usd | (Default, _) => #payment_processed_amount_without_smart_retrie } | Total_Payment_Processed_Amount => switch (isSmartRetryEnabled, currency->getTypeValue) { | (Smart_Retry, #all_currencies) => #total_payment_processed_amount_in_usd | (Smart_Retry, _) => #total_payment_processed_amount | (Default, #all_currencies) => #total_payment_processed_amount_without_smart_retries_in_usd | (Default, _) => #total_payment_processed_amount_without_smart_retries } } (key: responseKeys :> string) } let getMetaDataMapper = (key, ~isSmartRetryEnabled, ~currency) => { let field = key->getVariantValueFromString switch field { | Payment_Processed_Amount => Total_Payment_Processed_Amount->getKey(~currency, ~isSmartRetryEnabled) | Payment_Processed_Count | _ => Total_Payment_Processed_Count->getKey(~isSmartRetryEnabled) } } let modifyQueryData = (data, ~isSmartRetryEnabled, ~currency) => { let dataDict = Dict.make() data->Array.forEach(item => { let valueDict = item->getDictFromJsonObject let time = valueDict->getString(Time_Bucket->getStringFromVariant, "") let paymentProcessedCount = valueDict->getInt(Payment_Processed_Count->getKey(~isSmartRetryEnabled), 0) let paymentProcessedAmount = valueDict->getFloat(Payment_Processed_Amount->getKey(~currency, ~isSmartRetryEnabled), 0.0) switch dataDict->Dict.get(time) { | Some(prevVal) => { let key = Payment_Processed_Count->getStringFromVariant let prevProcessedCount = prevVal->getInt(key, 0) let key = Payment_Processed_Amount->getStringFromVariant let prevProcessedAmount = prevVal->getFloat(key, 0.0) let totalPaymentProcessedCount = paymentProcessedCount + prevProcessedCount let totalPaymentProcessedAmount = paymentProcessedAmount +. prevProcessedAmount prevVal->Dict.set( Payment_Processed_Count->getStringFromVariant, totalPaymentProcessedCount->JSON.Encode.int, ) prevVal->Dict.set( Payment_Processed_Amount->getStringFromVariant, totalPaymentProcessedAmount->JSON.Encode.float, ) dataDict->Dict.set(time, prevVal) } | None => { valueDict->Dict.set( Payment_Processed_Count->getStringFromVariant, paymentProcessedCount->JSON.Encode.int, ) valueDict->Dict.set( Payment_Processed_Amount->getStringFromVariant, paymentProcessedAmount->JSON.Encode.float, ) dataDict->Dict.set(time, valueDict) } } }) dataDict->Dict.valuesToArray->Array.map(JSON.Encode.object) }
2,014
9,580
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/PaymentsProcessed/PaymentsProcessed.res
.res
open NewAnalyticsTypes open NewAnalyticsHelper open NewPaymentAnalyticsEntity open PaymentsProcessedUtils open NewPaymentAnalyticsUtils module TableModule = { open LogicUtils open PaymentsProcessedTypes @react.component let make = (~data, ~className="") => { let (offset, setOffset) = React.useState(_ => 0) let defaultSort: Table.sortedObject = { key: "", order: Table.INC, } let tableBorderClass = "border-collapse border border-jp-gray-940 border-solid border-2 border-opacity-30 dark:border-jp-gray-dark_table_border_color dark:border-opacity-30" let paymentsProcessed = data ->Array.map(item => { item->getDictFromJsonObject->tableItemToObjMapper }) ->Array.map(Nullable.make) let defaultCols = [Payment_Processed_Amount, Payment_Processed_Count] let visibleColumns = defaultCols->Array.concat(visibleColumns) <div className> <LoadedTable visibleColumns title="Payments Processed" hideTitle=true actualData={paymentsProcessed} entity=paymentsProcessedTableEntity resultsPerPage=10 totalResults={paymentsProcessed->Array.length} offset setOffset defaultSort currrentFetchCount={paymentsProcessed->Array.length} tableLocalFilter=false tableheadingClass=tableBorderClass tableBorderClass ignoreHeaderBg=true showSerialNumber=true tableDataBorderClass=tableBorderClass isAnalyticsModule=true /> </div> } } module PaymentsProcessedHeader = { open NewAnalyticsUtils open LogicUtils open LogicUtilsTypes @react.component let make = ( ~data: JSON.t, ~viewType, ~setViewType, ~selectedMetric, ~setSelectedMetric, ~granularity, ~setGranularity, ~granularityOptions, ) => { let {filterValueJson} = React.useContext(FilterContext.filterContext) let comparison = filterValueJson->getString("comparison", "")->DateRangeUtils.comparisonMapprer let currency = filterValueJson->getString((#currency: filters :> string), "") let featureFlag = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let isSmartRetryEnabled = filterValueJson ->getString("is_smart_retry_enabled", "true") ->getBoolFromString(true) ->getSmartRetryMetricType let primaryValue = getMetaDataValue( ~data, ~index=0, ~key=selectedMetric.value->getMetaDataMapper(~currency, ~isSmartRetryEnabled), ) let secondaryValue = getMetaDataValue( ~data, ~index=1, ~key=selectedMetric.value->getMetaDataMapper(~currency, ~isSmartRetryEnabled), ) let (primaryValue, secondaryValue) = if ( selectedMetric.value->getMetaDataMapper(~currency, ~isSmartRetryEnabled)->isAmountMetric ) { (primaryValue /. 100.0, secondaryValue /. 100.0) } else { (primaryValue, secondaryValue) } let (value, direction) = calculatePercentageChange(~primaryValue, ~secondaryValue) let setViewType = value => { setViewType(_ => value) } let setSelectedMetric = value => { setSelectedMetric(_ => value) } let setGranularity = value => { setGranularity(_ => value) } let metricType = switch selectedMetric.value->getVariantValueFromString { | Payment_Processed_Amount => Amount | _ => Volume } <div className="w-full px-7 py-8 grid grid-cols-3"> <div className="flex gap-2 items-center"> <div className="text-fs-28 font-semibold"> {primaryValue->valueFormatter(metricType, ~currency)->React.string} </div> <RenderIf condition={comparison == EnableComparison}> <StatisticsCard value direction tooltipValue={secondaryValue->valueFormatter(metricType, ~currency)} /> </RenderIf> </div> <div className="flex justify-center"> <RenderIf condition={featureFlag.granularity}> <Tabs option={granularity} setOption={setGranularity} options={granularityOptions} showSingleTab=false /> </RenderIf> </div> <div className="flex gap-2 justify-end"> <CustomDropDown buttonText={selectedMetric} options={dropDownOptions} setOption={setSelectedMetric} /> <TabSwitch viewType setViewType /> </div> </div> } } @react.component let make = ( ~entity: moduleEntity, ~chartEntity: chartEntity< LineGraphTypes.lineGraphPayload, LineGraphTypes.lineGraphOptions, JSON.t, >, ) => { open LogicUtils open APIUtils open NewAnalyticsUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let isoStringToCustomTimeZone = TimeZoneHook.useIsoStringToCustomTimeZone() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let {filterValueJson} = React.useContext(FilterContext.filterContext) let (paymentsProcessedData, setPaymentsProcessedData) = React.useState(_ => JSON.Encode.array([])) let (paymentsProcessedTableData, setPaymentsProcessedTableData) = React.useState(_ => []) let (paymentsProcessedMetaData, setPaymentsProcessedMetaData) = React.useState(_ => JSON.Encode.array([]) ) let (selectedMetric, setSelectedMetric) = React.useState(_ => defaultMetric) let (viewType, setViewType) = React.useState(_ => Graph) let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let compareToStartTime = filterValueJson->getString("compareToStartTime", "") let compareToEndTime = filterValueJson->getString("compareToEndTime", "") let comparison = filterValueJson->getString("comparison", "")->DateRangeUtils.comparisonMapprer let currency = filterValueJson->getString((#currency: filters :> string), "") let featureFlag = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let defaulGranularity = getDefaultGranularity( ~startTime=startTimeVal, ~endTime=endTimeVal, ~granularity=featureFlag.granularity, ) let granularityOptions = getGranularityOptions(~startTime=startTimeVal, ~endTime=endTimeVal) let (granularity, setGranularity) = React.useState(_ => defaulGranularity) React.useEffect(() => { if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString { setGranularity(_ => defaulGranularity) } None }, (startTimeVal, endTimeVal)) let isSmartRetryEnabled = filterValueJson ->getString("is_smart_retry_enabled", "true") ->getBoolFromString(true) ->getSmartRetryMetricType let getPaymentsProcessed = async () => { setScreenState(_ => PageLoaderWrapper.Loading) try { let url = getURL( ~entityName=V1(ANALYTICS_PAYMENTS_V2), ~methodType=Post, ~id=Some((entity.domain: domain :> string)), ) let primaryBody = requestBody( ~startTime=startTimeVal, ~endTime=endTimeVal, ~delta=entity.requestBodyConfig.delta, ~metrics=entity.requestBodyConfig.metrics, ~granularity=granularity.value->Some, ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let secondaryBody = requestBody( ~startTime=compareToStartTime, ~endTime=compareToEndTime, ~delta=entity.requestBodyConfig.delta, ~metrics=entity.requestBodyConfig.metrics, ~granularity=granularity.value->Some, ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let primaryResponse = await updateDetails(url, primaryBody, Post) let primaryData = primaryResponse ->getDictFromJsonObject ->getArrayFromDict("queryData", []) ->modifyQueryData(~isSmartRetryEnabled, ~currency) ->sortQueryDataByDate let primaryMetaData = primaryResponse->getDictFromJsonObject->getArrayFromDict("metaData", []) setPaymentsProcessedTableData(_ => primaryData) let (secondaryMetaData, secondaryModifiedData) = switch comparison { | EnableComparison => { let secondaryResponse = await updateDetails(url, secondaryBody, Post) let secondaryData = secondaryResponse ->getDictFromJsonObject ->getArrayFromDict("queryData", []) ->modifyQueryData(~isSmartRetryEnabled, ~currency) let secondaryMetaData = secondaryResponse->getDictFromJsonObject->getArrayFromDict("metaData", []) let secondaryModifiedData = [secondaryData]->Array.map(data => { fillMissingDataPoints( ~data, ~startDate=compareToStartTime, ~endDate=compareToEndTime, ~timeKey="time_bucket", ~defaultValue={ "payment_count": 0, "payment_processed_amount": 0, "time_bucket": startTimeVal, }->Identity.genericTypeToJson, ~granularity=granularity.value, ~isoStringToCustomTimeZone, ~granularityEnabled=featureFlag.granularity, ) }) (secondaryMetaData, secondaryModifiedData) } | DisableComparison => ([], []) } if primaryData->Array.length > 0 { let primaryModifiedData = [primaryData]->Array.map(data => { fillMissingDataPoints( ~data, ~startDate=startTimeVal, ~endDate=endTimeVal, ~timeKey="time_bucket", ~defaultValue={ "payment_count": 0, "payment_processed_amount": 0, "time_bucket": startTimeVal, }->Identity.genericTypeToJson, ~granularity=granularity.value, ~isoStringToCustomTimeZone, ~granularityEnabled=featureFlag.granularity, ) }) setPaymentsProcessedData(_ => primaryModifiedData->Array.concat(secondaryModifiedData)->Identity.genericTypeToJson ) setPaymentsProcessedMetaData(_ => primaryMetaData->Array.concat(secondaryMetaData)->Identity.genericTypeToJson ) setScreenState(_ => PageLoaderWrapper.Success) } else { setScreenState(_ => PageLoaderWrapper.Custom) } } catch { | _ => setScreenState(_ => PageLoaderWrapper.Custom) } } React.useEffect(() => { if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString { getPaymentsProcessed()->ignore } None }, ( startTimeVal, endTimeVal, compareToStartTime, compareToEndTime, comparison, granularity.value, currency, isSmartRetryEnabled, )) let params = { data: paymentsProcessedData, xKey: selectedMetric.value, yKey: Time_Bucket->getStringFromVariant, comparison, currency, } let options = chartEntity.getObjects(~params)->chartEntity.getChatOptions <div> <ModuleHeader title={entity.title} /> <Card> <PageLoaderWrapper screenState customLoader={<Shimmer layoutId=entity.title />} customUI={<NoData />}> <PaymentsProcessedHeader data=paymentsProcessedMetaData viewType setViewType selectedMetric setSelectedMetric granularity setGranularity granularityOptions /> <div className="mb-5"> {switch viewType { | Graph => <LineGraph options className="mr-3" /> | Table => <TableModule data={paymentsProcessedTableData} className="mx-7" /> }} </div> </PageLoaderWrapper> </Card> </div> }
2,632
9,581
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/PaymentsOverviewSection/NewPaymentsOverviewSectionHelper.res
.res
module SmartRetryCard = { open NewAnalyticsHelper open NewPaymentsOverviewSectionTypes open NewPaymentsOverviewSectionUtils open NewAnalyticsUtils @react.component let make = (~responseKey: overviewColumns, ~data) => { open LogicUtils let {filterValueJson} = React.useContext(FilterContext.filterContext) let comparison = filterValueJson->getString("comparison", "")->DateRangeUtils.comparisonMapprer let currency = filterValueJson->getString((#currency: NewAnalyticsTypes.filters :> string), "") let config = getInfo(~responseKey) let primaryValue = getValueFromObj(data, 0, responseKey->getStringFromVariant) let secondaryValue = getValueFromObj(data, 1, responseKey->getStringFromVariant) let (value, direction) = calculatePercentageChange(~primaryValue, ~secondaryValue) <Card> <div className="p-6 flex flex-col gap-4 justify-between h-full gap-auto"> <div className="font-semibold dark:text-white"> {config.titleText->React.string} </div> <div className={"flex flex-col gap-1 justify-center text-black h-full"}> <img alt="connector-list" className="h-20 w-fit" src="/assets/smart-retry.svg" /> <div className="flex gap-1 items-center"> <div className="font-semibold text-2xl dark:text-white"> {`Saved ${valueFormatter(primaryValue, config.valueType, ~currency)}`->React.string} </div> <RenderIf condition={comparison === EnableComparison}> <StatisticsCard value direction isOverviewComponent=true tooltipValue={`${valueFormatter(secondaryValue, config.valueType)} USD`} /> </RenderIf> </div> <div className="opacity-50 text-sm"> {config.description->React.string} </div> </div> </div> </Card> } }
429
9,582
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/PaymentsOverviewSection/NewPaymentsOverviewSectionUtils.res
.res
open NewPaymentsOverviewSectionTypes let getStringFromVariant = value => { switch value { | Total_Smart_Retried_Amount => "total_smart_retried_amount" | Total_Success_Rate => "total_success_rate" | Total_Payment_Processed_Amount => "total_payment_processed_amount" | Total_Refund_Processed_Amount => "total_refund_processed_amount" | Total_Dispute => "total_dispute" } } let defaultValue = { total_smart_retried_amount: 0.0, total_success_rate: 0.0, total_payment_processed_amount: 0.0, total_refund_processed_amount: 0.0, total_dispute: 0, } ->Identity.genericTypeToJson ->LogicUtils.getDictFromJsonObject let getPayload = (~entity, ~metrics, ~startTime, ~endTime, ~filter=None) => { open NewAnalyticsTypes NewAnalyticsUtils.requestBody( ~startTime, ~endTime, ~delta=entity.requestBodyConfig.delta, ~metrics, ~filter, ) } let parseResponse = (response, key) => { open LogicUtils response ->getDictFromJsonObject ->getArrayFromDict(key, []) ->getValueFromArray(0, Dict.make()->JSON.Encode.object) ->getDictFromJsonObject } open NewAnalyticsTypes let getKey = (id, ~isSmartRetryEnabled=Smart_Retry, ~currency="") => { open LogicUtils let key = switch id { | Total_Dispute => #total_dispute | Total_Refund_Processed_Amount => switch currency->getTypeValue { | #all_currencies => #total_refund_processed_amount_in_usd | _ => #total_refund_processed_amount } | Total_Success_Rate => switch isSmartRetryEnabled { | Smart_Retry => #total_success_rate | Default => #total_success_rate_without_smart_retries } | Total_Smart_Retried_Amount => switch (isSmartRetryEnabled, currency->getTypeValue) { | (Smart_Retry, #all_currencies) => #total_smart_retried_amount_in_usd | (Smart_Retry, _) => #total_smart_retried_amount | (Default, #all_currencies) => #total_smart_retried_amount_without_smart_retries_in_usd | (Default, _) => #total_smart_retried_amount_without_smart_retries } | Total_Payment_Processed_Amount => switch (isSmartRetryEnabled, currency->getTypeValue) { | (Smart_Retry, #all_currencies) => #total_payment_processed_amount_in_usd | (Smart_Retry, _) => #total_payment_processed_amount | (Default, #all_currencies) => #total_payment_processed_amount_without_smart_retries_in_usd | (Default, _) => #total_payment_processed_amount_without_smart_retries } } (key: responseKeys :> string) } let setValue = (dict, ~data, ~ids: array<overviewColumns>, ~metricType, ~currency) => { open LogicUtils open NewAnalyticsUtils ids->Array.forEach(id => { let key = id->getStringFromVariant let value = switch id { | Total_Smart_Retried_Amount | Total_Payment_Processed_Amount => data ->getAmountValue(~id=id->getKey(~isSmartRetryEnabled=metricType, ~currency)) ->JSON.Encode.float | Total_Refund_Processed_Amount => data ->getAmountValue(~id={id->getKey(~currency)}) ->JSON.Encode.float | Total_Dispute => data ->getFloat(key, 0.0) ->JSON.Encode.float | _ => { let id = id->getKey(~isSmartRetryEnabled=metricType) data ->getFloat(id, 0.0) ->JSON.Encode.float } } dict->Dict.set(key, value) }) } let getInfo = (~responseKey: overviewColumns) => { open NewAnalyticsTypes switch responseKey { | Total_Smart_Retried_Amount => { titleText: "Total Payment Savings", description: "Amount saved via payment retries", valueType: Amount, } | Total_Success_Rate => { titleText: "Total Authorization Rate", description: "Overall successful payment intents divided by total payment intents excluding dropoffs", valueType: Rate, } | Total_Payment_Processed_Amount => { titleText: "Total Payments Processed", description: "The total amount of payments processed in the selected time range", valueType: Amount, } | Total_Refund_Processed_Amount => { titleText: "Total Refunds Processed", description: "The total amount of refund payments processed in the selected time range", valueType: Amount, } | Total_Dispute => { titleText: "All Disputes", description: "Total number of disputes irrespective of status in the selected time range", valueType: Volume, } } } let getValueFromObj = (data, index, responseKey) => { open LogicUtils data ->getArrayFromJson([]) ->getValueFromArray(index, Dict.make()->JSON.Encode.object) ->getDictFromJsonObject ->getFloat(responseKey, 0.0) }
1,191
9,583
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/PaymentsOverviewSection/NewPaymentsOverviewSectionTypes.res
.res
type overviewColumns = | Total_Smart_Retried_Amount | Total_Success_Rate | Total_Payment_Processed_Amount | Total_Refund_Processed_Amount | Total_Dispute type responseKeys = [ | #total_smart_retried_amount | #total_smart_retried_amount_in_usd | #total_smart_retried_amount_without_smart_retries | #total_smart_retried_amount_without_smart_retries_in_usd | #total_success_rate | #total_success_rate_without_smart_retries | #total_payment_processed_amount | #total_payment_processed_amount_in_usd | #total_payment_processed_amount_without_smart_retries | #total_payment_processed_amount_without_smart_retries_in_usd | #total_refund_processed_amount | #total_refund_processed_amount_in_usd | #total_dispute ] type dataObj = { total_smart_retried_amount: float, total_success_rate: float, total_payment_processed_amount: float, total_refund_processed_amount: float, total_dispute: int, }
247
9,584
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/PaymentsOverviewSection/NewPaymentsOverviewSection.res
.res
open NewAnalyticsTypes open NewPaymentsOverviewSectionTypes @react.component let make = (~entity: moduleEntity) => { open NewPaymentsOverviewSectionUtils open LogicUtils open APIUtils open NewAnalyticsHelper open NewAnalyticsUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let (data, setData) = React.useState(_ => []->JSON.Encode.array) let {filterValueJson} = React.useContext(FilterContext.filterContext) let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let metricType: metricType = filterValueJson ->getString("is_smart_retry_enabled", "true") ->getBoolFromString(true) ->NewPaymentAnalyticsUtils.getSmartRetryMetricType let compareToStartTime = filterValueJson->getString("compareToStartTime", "") let compareToEndTime = filterValueJson->getString("compareToEndTime", "") let comparison = filterValueJson->getString("comparison", "")->DateRangeUtils.comparisonMapprer let currency = filterValueJson->getString((#currency: filters :> string), "") let getData = async () => { setScreenState(_ => PageLoaderWrapper.Loading) try { let primaryData = defaultValue->Dict.copy let secondaryData = defaultValue->Dict.copy let paymentsUrl = getURL( ~entityName=V1(ANALYTICS_PAYMENTS_V2), ~methodType=Post, ~id=Some((#payments: domain :> string)), ) let refundsUrl = getURL( ~entityName=V1(ANALYTICS_REFUNDS), ~methodType=Post, ~id=Some((#refunds: domain :> string)), ) let disputesUrl = getURL( ~entityName=V1(ANALYTICS_DISPUTES), ~methodType=Post, ~id=Some((#disputes: domain :> string)), ) // primary date range let primaryBodyPayments = getPayload( ~entity, ~metrics=[ #sessionized_smart_retried_amount, #sessionized_payments_success_rate, #sessionized_payment_processed_amount, ], ~startTime=startTimeVal, ~endTime=endTimeVal, ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let primaryBodyRefunds = getPayload( ~entity, ~metrics=[#refund_processed_amount], ~startTime=startTimeVal, ~endTime=endTimeVal, ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let primaryBodyDisputes = getPayload( ~entity, ~metrics=[#dispute_status_metric], ~startTime=startTimeVal, ~endTime=endTimeVal, ~filter=None, ) let primaryResponsePayments = await updateDetails(paymentsUrl, primaryBodyPayments, Post) let primaryResponseRefunds = await updateDetails(refundsUrl, primaryBodyRefunds, Post) let primaryResponseDisputes = await updateDetails(disputesUrl, primaryBodyDisputes, Post) let primaryDataPayments = primaryResponsePayments->parseResponse("metaData") let primaryDataRefunds = primaryResponseRefunds->parseResponse("metaData") let primaryDataDisputes = primaryResponseDisputes->parseResponse("queryData") primaryData->setValue( ~data=primaryDataPayments, ~ids=[Total_Smart_Retried_Amount, Total_Success_Rate, Total_Payment_Processed_Amount], ~metricType, ~currency, ) primaryData->setValue( ~data=primaryDataRefunds, ~ids=[Total_Refund_Processed_Amount], ~metricType, ~currency, ) primaryData->setValue(~data=primaryDataDisputes, ~ids=[Total_Dispute], ~metricType, ~currency) let secondaryBodyPayments = getPayload( ~entity, ~metrics=[ #sessionized_smart_retried_amount, #sessionized_payments_success_rate, #sessionized_payment_processed_amount, ], ~startTime=compareToStartTime, ~endTime=compareToEndTime, ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let secondaryBodyRefunds = getPayload( ~entity, ~metrics=[#refund_processed_amount], ~startTime=compareToStartTime, ~endTime=compareToEndTime, ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let secondaryBodyDisputes = getPayload( ~entity, ~metrics=[#dispute_status_metric], ~startTime=compareToStartTime, ~endTime=compareToEndTime, ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let secondaryData = switch comparison { | EnableComparison => { let secondaryResponsePayments = await updateDetails( paymentsUrl, secondaryBodyPayments, Post, ) let secondaryResponseRefunds = await updateDetails(refundsUrl, secondaryBodyRefunds, Post) let secondaryResponseDisputes = await updateDetails( disputesUrl, secondaryBodyDisputes, Post, ) let secondaryDataPayments = secondaryResponsePayments->parseResponse("metaData") let secondaryDataRefunds = secondaryResponseRefunds->parseResponse("metaData") let secondaryDataDisputes = secondaryResponseDisputes->parseResponse("queryData") secondaryData->setValue( ~data=secondaryDataPayments, ~ids=[Total_Smart_Retried_Amount, Total_Success_Rate, Total_Payment_Processed_Amount], ~metricType, ~currency, ) secondaryData->setValue( ~data=secondaryDataRefunds, ~ids=[Total_Refund_Processed_Amount], ~metricType, ~currency, ) secondaryData->setValue( ~data=secondaryDataDisputes, ~ids=[Total_Dispute], ~metricType, ~currency, ) secondaryData->JSON.Encode.object } | DisableComparison => JSON.Encode.null } setData(_ => [primaryData->JSON.Encode.object, secondaryData]->JSON.Encode.array) setScreenState(_ => PageLoaderWrapper.Success) } catch { | _ => setScreenState(_ => PageLoaderWrapper.Success) } } React.useEffect(() => { if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString { getData()->ignore } None }, ( startTimeVal, endTimeVal, compareToStartTime, compareToEndTime, comparison, currency, metricType, )) <PageLoaderWrapper screenState customLoader={<Shimmer layoutId=entity.title />}> <div className="grid grid-cols-3 gap-6"> <NewPaymentsOverviewSectionHelper.SmartRetryCard data responseKey={Total_Smart_Retried_Amount} /> <div className="col-span-2 grid grid-cols-2 grid-rows-2 gap-6"> <OverViewStat data responseKey={Total_Success_Rate} getInfo getValueFromObj getStringFromVariant /> <OverViewStat data responseKey={Total_Payment_Processed_Amount} getInfo getValueFromObj getStringFromVariant /> <OverViewStat data responseKey={Total_Refund_Processed_Amount} getInfo getValueFromObj getStringFromVariant /> <OverViewStat data responseKey={Total_Dispute} getInfo getValueFromObj getStringFromVariant /> </div> </div> </PageLoaderWrapper> }
1,698
9,585
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/FailureReasonsPayments/FailureReasonsPaymentsTypes.res
.res
type failreResonsColsTypes = | Error_Reason | Failure_Reason_Count | Reasons_Count_Ratio | Total_Failure_Reasons_Count | Connector | Payment_Method | Payment_Method_Type | Authentication_Type type failreResonsObjectType = { error_reason: string, failure_reason_count: int, total_failure_reasons_count: int, reasons_count_ratio: float, connector: string, payment_method: string, payment_method_type: string, authentication_type: string, }
120
9,586
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/FailureReasonsPayments/FailureReasonsPaymentsUtils.res
.res
open NewAnalyticsTypes open FailureReasonsPaymentsTypes open LogicUtils let getStringFromVariant = value => { switch value { | Error_Reason => "error_reason" | Failure_Reason_Count => "failure_reason_count" | Reasons_Count_Ratio => "reasons_count_ratio" | Total_Failure_Reasons_Count => "total_failure_reasons_count" | Connector => "connector" | Payment_Method => "payment_method" | Payment_Method_Type => "payment_method_type" | Authentication_Type => "authentication_type" } } let getColumn = string => { switch string { | "connector" => Connector | "payment_method" => Payment_Method | "payment_method_type" => Payment_Method_Type | "authentication_type" => Authentication_Type | _ => Connector } } let tableItemToObjMapper: Dict.t<JSON.t> => failreResonsObjectType = dict => { { error_reason: dict->getString(Error_Reason->getStringFromVariant, ""), failure_reason_count: dict->getInt(Failure_Reason_Count->getStringFromVariant, 0), total_failure_reasons_count: dict->getInt(Total_Failure_Reasons_Count->getStringFromVariant, 0), reasons_count_ratio: dict->getFloat(Reasons_Count_Ratio->getStringFromVariant, 0.0), connector: dict->getString(Connector->getStringFromVariant, ""), payment_method: dict->getString(Payment_Method->getStringFromVariant, ""), payment_method_type: dict->getString(Payment_Method_Type->getStringFromVariant, ""), authentication_type: dict->getString(Authentication_Type->getStringFromVariant, ""), } } let getObjects: JSON.t => array<failreResonsObjectType> = json => { json ->LogicUtils.getArrayFromJson([]) ->Array.map(item => { tableItemToObjMapper(item->getDictFromJsonObject) }) } let getHeading = colType => { switch colType { | Error_Reason => Table.makeHeaderInfo( ~key=Error_Reason->getStringFromVariant, ~title="Error Reason", ~dataType=TextType, ) | Failure_Reason_Count => Table.makeHeaderInfo( ~key=Failure_Reason_Count->getStringFromVariant, ~title="Count", ~dataType=TextType, ) | Reasons_Count_Ratio => Table.makeHeaderInfo( ~key=Reasons_Count_Ratio->getStringFromVariant, ~title="Ratio (%)", ~dataType=TextType, ) | Total_Failure_Reasons_Count => Table.makeHeaderInfo( ~key=Total_Failure_Reasons_Count->getStringFromVariant, ~title="", ~dataType=TextType, ) | Connector => Table.makeHeaderInfo( ~key=Connector->getStringFromVariant, ~title="Connector", ~dataType=TextType, ) | Payment_Method => Table.makeHeaderInfo( ~key=Payment_Method->getStringFromVariant, ~title="Payment Method", ~dataType=TextType, ) | Payment_Method_Type => Table.makeHeaderInfo( ~key=Payment_Method_Type->getStringFromVariant, ~title="Payment Method Type", ~dataType=TextType, ) | Authentication_Type => Table.makeHeaderInfo( ~key=Authentication_Type->getStringFromVariant, ~title="Authentication Type", ~dataType=TextType, ) } } let getCell = (obj, colType): Table.cell => { switch colType { | Error_Reason => Text(obj.error_reason) | Failure_Reason_Count => Text(obj.failure_reason_count->Int.toString) | Reasons_Count_Ratio => Text(obj.reasons_count_ratio->valueFormatter(Rate)) | Total_Failure_Reasons_Count => Text(obj.total_failure_reasons_count->Int.toString) | Connector => Text(obj.connector) | Payment_Method => Text(obj.payment_method) | Payment_Method_Type => Text(obj.payment_method_type) | Authentication_Type => Text(obj.authentication_type) } } let getTableData = json => { json->getArrayDataFromJson(tableItemToObjMapper)->Array.map(Nullable.make) } let tabs = [ { label: "Connector", value: Connector->getStringFromVariant, }, { label: "Payment Method", value: Payment_Method->getStringFromVariant, }, { label: "Payment Method Type", value: Payment_Method_Type->getStringFromVariant, }, { label: "Authentication Type", value: Authentication_Type->getStringFromVariant, }, { label: "Payment Method + Payment Method Type", value: `${Payment_Method->getStringFromVariant},${Payment_Method_Type->getStringFromVariant}`, }, ] let defaulGroupBy = { label: "Connector", value: Connector->getStringFromVariant, } let modifyQuery = (queryData, metaData) => { let totalCount = switch metaData->Array.get(0) { | Some(val) => { let valueDict = val->getDictFromJsonObject let failure_reason_count = valueDict->getInt(Total_Failure_Reasons_Count->getStringFromVariant, 0) failure_reason_count } | _ => 0 } let modifiedQuery = if totalCount > 0 { queryData->Array.map(query => { let valueDict = query->getDictFromJsonObject let failure_reason_count = valueDict->getInt(Failure_Reason_Count->getStringFromVariant, 0) let ratio = failure_reason_count->Int.toFloat /. totalCount->Int.toFloat *. 100.0 valueDict->Dict.set(Reasons_Count_Ratio->getStringFromVariant, ratio->JSON.Encode.float) valueDict->JSON.Encode.object }) } else { queryData } modifiedQuery->Array.sort((queryA, queryB) => { let valueDictA = queryA->getDictFromJsonObject let valueDictB = queryB->getDictFromJsonObject let failure_reason_countA = valueDictA->getInt(Failure_Reason_Count->getStringFromVariant, 0) let failure_reason_countB = valueDictB->getInt(Failure_Reason_Count->getStringFromVariant, 0) compareLogic(failure_reason_countA, failure_reason_countB) }) modifiedQuery }
1,376
9,587
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/FailureReasonsPayments/FailureReasonsPayments.res
.res
open NewAnalyticsTypes open FailureReasonsPaymentsTypes open NewPaymentAnalyticsEntity open FailureReasonsPaymentsUtils open NewAnalyticsHelper module TableModule = { @react.component let make = (~data, ~className="", ~selectedTab: string) => { let (offset, setOffset) = React.useState(_ => 0) let defaultSort: Table.sortedObject = { key: "", order: Table.INC, } let defaultCols = [Error_Reason, Failure_Reason_Count, Reasons_Count_Ratio] let extraTabs = selectedTab->String.split(",")->Array.map(getColumn) let visibleColumns = defaultCols->Array.concat(extraTabs) let tableData = getTableData(data) <div className> <LoadedTable visibleColumns title="Failure Reasons Payments" hideTitle=true actualData={tableData} entity=failureReasonsTableEntity resultsPerPage=10 totalResults={tableData->Array.length} offset setOffset defaultSort currrentFetchCount={tableData->Array.length} tableLocalFilter=false tableheadingClass=tableBorderClass tableBorderClass ignoreHeaderBg=true tableDataBorderClass=tableBorderClass isAnalyticsModule=true /> </div> } } module FailureReasonsPaymentsHeader = { @react.component let make = (~groupBy, ~setGroupBy) => { let setGroupBy = value => { setGroupBy(_ => value) } <div className="w-full px-7 py-8 flex justify-between"> <Tabs option={groupBy} setOption={setGroupBy} options={tabs} /> </div> } } @react.component let make = (~entity: moduleEntity) => { open LogicUtils open APIUtils open NewAnalyticsUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let {filterValueJson} = React.useContext(FilterContext.filterContext) let (tableData, setTableData) = React.useState(_ => JSON.Encode.array([])) let (groupBy, setGroupBy) = React.useState(_ => defaulGroupBy) let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let currency = filterValueJson->getString((#currency: filters :> string), "") let getPaymentsProcessed = async () => { setScreenState(_ => PageLoaderWrapper.Loading) try { let url = getURL( ~entityName=V1(ANALYTICS_PAYMENTS), ~methodType=Post, ~id=Some((entity.domain: domain :> string)), ) let groupByNames = switch entity.requestBodyConfig.groupBy { | Some(dimentions) => dimentions ->Array.map(item => (item: dimension :> string)) ->Array.concat(groupBy.value->String.split(",")) ->Some | _ => None } let body = requestBody( ~startTime=startTimeVal, ~endTime=endTimeVal, ~delta=entity.requestBodyConfig.delta, ~metrics=entity.requestBodyConfig.metrics, ~groupByNames, ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let response = await updateDetails(url, body, Post) let metaData = response->getDictFromJsonObject->getArrayFromDict("metaData", []) let data = response ->getDictFromJsonObject ->getArrayFromDict("queryData", []) ->modifyQuery(metaData) if data->Array.length > 0 { setTableData(_ => data->JSON.Encode.array) setScreenState(_ => PageLoaderWrapper.Success) } else { setScreenState(_ => PageLoaderWrapper.Custom) } } catch { | _ => setScreenState(_ => PageLoaderWrapper.Custom) } } React.useEffect(() => { if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString { getPaymentsProcessed()->ignore } None }, [startTimeVal, endTimeVal, groupBy.value, currency]) <div> <ModuleHeader title={entity.title} /> <Card> <PageLoaderWrapper screenState customLoader={<Shimmer layoutId=entity.title />} customUI={<NoData />}> <FailureReasonsPaymentsHeader groupBy setGroupBy /> <div className="mb-5"> <TableModule data={tableData} className="mx-7" selectedTab={groupBy.value} /> </div> </PageLoaderWrapper> </Card> </div> }
1,042
9,588
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/PaymentsLifeCycle/PaymentsLifeCycleTypes.res
.res
type paymentLifeCycle = { normalSuccess: int, normalFailure: int, cancelled: int, smartRetriedSuccess: int, smartRetriedFailure: int, pending: int, partialRefunded: int, refunded: int, disputed: int, drop_offs: int, } type status = | Succeeded | Failed | Cancelled | Processing | RequiresCustomerAction | RequiresMerchantAction | RequiresPaymentMethod | RequiresConfirmation | RequiresCapture | PartiallyCaptured | PartiallyCapturedAndCapturable | Full_Refunded | Partial_Refunded | Dispute_Present | Null type query = { count: int, dispute_status: status, first_attempt: int, refunds_status: status, status: status, }
191
9,589
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/PaymentsLifeCycle/PaymentsLifeCycle.res
.res
open NewAnalyticsTypes open NewAnalyticsHelper open SankeyGraphTypes @react.component let make = ( ~entity: moduleEntity, ~chartEntity: chartEntity< sankeyPayload, sankeyGraphOptions, PaymentsLifeCycleTypes.paymentLifeCycle, >, ) => { open APIUtils open LogicUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let (data, setData) = React.useState(_ => JSON.Encode.null->PaymentsLifeCycleUtils.paymentLifeCycleResponseMapper ) let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let {filterValueJson} = React.useContext(FilterContext.filterContext) let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let isSmartRetryEnabled = filterValueJson->getString("is_smart_retry_enabled", "true") let getPaymentLieCycleData = async () => { setScreenState(_ => PageLoaderWrapper.Loading) try { let url = getURL(~entityName=V1(ANALYTICS_SANKEY), ~methodType=Post) let paymentLifeCycleBody = [ ("startTime", startTimeVal->JSON.Encode.string), ("endTime", endTimeVal->JSON.Encode.string), ] ->Dict.fromArray ->JSON.Encode.object let paymentLifeCycleResponse = await updateDetails(url, paymentLifeCycleBody, Post) if paymentLifeCycleResponse->PaymentsLifeCycleUtils.getTotalPayments > 0 { setData(_ => paymentLifeCycleResponse->PaymentsLifeCycleUtils.paymentLifeCycleResponseMapper( ~isSmartRetryEnabled=isSmartRetryEnabled->LogicUtils.getBoolFromString(true), ) ) setScreenState(_ => PageLoaderWrapper.Success) } else { setScreenState(_ => PageLoaderWrapper.Custom) } } catch { | _ => setScreenState(_ => PageLoaderWrapper.Custom) } } React.useEffect(() => { if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString { getPaymentLieCycleData()->ignore } None }, (startTimeVal, endTimeVal, isSmartRetryEnabled)) let params = { data, xKey: isSmartRetryEnabled, yKey: "", } let options = chartEntity.getChatOptions(chartEntity.getObjects(~params)) <div> <ModuleHeader title={entity.title} /> <Card> <PageLoaderWrapper screenState customLoader={<Shimmer layoutId=entity.title />} customUI={<NoData />}> <div className="my-10"> <SankeyGraph options={options} className="mr-3" /> </div> </PageLoaderWrapper> </Card> </div> }
612
9,590
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/PaymentsLifeCycle/PaymentsLifeCycleUtils.res
.res
open SankeyGraphTypes open LogicUtils open PaymentsLifeCycleTypes let getstatusVariantTypeFromString = value => { switch value { | "succeeded" => Succeeded | "failed" => Failed | "cancelled" => Cancelled | "processing" => Processing | "requires_customer_action" => RequiresCustomerAction | "requires_merchant_action" => RequiresMerchantAction | "requires_payment_method" => RequiresPaymentMethod | "requires_confirmation" => RequiresConfirmation | "requires_capture" => RequiresCapture | "partially_captured" => PartiallyCaptured | "partially_captured_and_capturable" => PartiallyCapturedAndCapturable | "full_refunded" => Full_Refunded | "partial_refunded" => Partial_Refunded | "dispute_present" => Dispute_Present | _ => Null } } let paymentLifeCycleResponseMapper = (json: JSON.t, ~isSmartRetryEnabled=true) => { let valueDict = [ "normal_success", "normal_failure", "pending", "cancelled", "drop_offs", "smart_retried_success", "smart_retried_failure", "partial_refunded", "refunded", "disputed", ] ->Array.map(item => (item, 0)) ->Dict.fromArray let queryItems = json ->getArrayFromJson([]) ->Array.map(query => { let queryDict = query->getDictFromJsonObject { count: queryDict->getInt("count", 0), dispute_status: queryDict->getString("dispute_status", "")->getstatusVariantTypeFromString, first_attempt: queryDict->getInt("first_attempt", 0), refunds_status: queryDict->getString("refunds_status", "")->getstatusVariantTypeFromString, status: queryDict->getString("status", "")->getstatusVariantTypeFromString, } }) queryItems->Array.forEach(query => { let includeSmartRetry = query.first_attempt == 1 || (query.first_attempt != 1 && isSmartRetryEnabled) switch query.status { | Succeeded => { // normal_success or smart_retried_success if query.first_attempt == 1 { valueDict->Dict.set( "normal_success", valueDict->getInt("normal_success", 0) + query.count, ) } else { valueDict->Dict.set( "smart_retried_success", valueDict->getInt("smart_retried_success", 0) + query.count, ) } if includeSmartRetry { // "refunded" or "partial_refunded" switch query.refunds_status { | Full_Refunded => valueDict->Dict.set("refunded", valueDict->getInt("refunded", 0) + query.count) | Partial_Refunded => valueDict->Dict.set( "partial_refunded", valueDict->getInt("partial_refunded", 0) + query.count, ) | _ => () } // "disputed" switch query.dispute_status { | Dispute_Present => valueDict->Dict.set("disputed", valueDict->getInt("disputed", 0) + query.count) | _ => () } } } | Failed => { valueDict->Dict.set("normal_failure", valueDict->getInt("normal_failure", 0) + query.count) if query.first_attempt != 1 { valueDict->Dict.set( "smart_retried_failure", valueDict->getInt("smart_retried_failure", 0) + query.count, ) } } | Cancelled => if includeSmartRetry { valueDict->Dict.set("cancelled", valueDict->getInt("cancelled", 0) + query.count) } else { valueDict->Dict.set( "smart_retried_failure", valueDict->getInt("smart_retried_failure", 0) + query.count, ) } | Processing => if includeSmartRetry { valueDict->Dict.set("pending", valueDict->getInt("pending", 0) + query.count) } else { valueDict->Dict.set( "smart_retried_failure", valueDict->getInt("smart_retried_failure", 0) + query.count, ) } | RequiresCustomerAction | RequiresMerchantAction | RequiresPaymentMethod | RequiresConfirmation | RequiresCapture | PartiallyCaptured | PartiallyCapturedAndCapturable | Null | _ => if includeSmartRetry { valueDict->Dict.set("drop_offs", valueDict->getInt("drop_offs", 0) + query.count) } else { valueDict->Dict.set( "smart_retried_failure", valueDict->getInt("smart_retried_failure", 0) + query.count, ) } } }) { normalSuccess: valueDict->getInt("normal_success", 0), normalFailure: valueDict->getInt("normal_failure", 0), cancelled: valueDict->getInt("cancelled", 0), smartRetriedSuccess: valueDict->getInt("smart_retried_success", 0), smartRetriedFailure: valueDict->getInt("smart_retried_failure", 0), pending: valueDict->getInt("pending", 0), partialRefunded: valueDict->getInt("partial_refunded", 0), refunded: valueDict->getInt("refunded", 0), disputed: valueDict->getInt("disputed", 0), drop_offs: valueDict->getInt("drop_offs", 0), } } let getTotalPayments = json => { let data = json->paymentLifeCycleResponseMapper let payment_initiated = data.normalSuccess + data.normalFailure + data.cancelled + data.pending + data.drop_offs payment_initiated } let transformData = (data: array<(string, int)>) => { let data = data->Array.map(item => { let (key, value) = item (key, value->Int.toFloat) }) let arr = data->Array.map(item => { let (_, value) = item value }) let minVal = arr->Math.minMany let maxVal = arr->Math.maxMany let total = arr->Array.reduce(0.0, (sum, count) => { sum +. count }) // Normalize Each Element let updatedData = data->Array.map(item => { let (key, count) = item let num = count -. minVal let dinom = maxVal -. minVal let normalizedValue = maxVal != minVal ? num /. dinom : 1.0 (key, normalizedValue) }) // Map to Target Range let updatedData = updatedData->Array.map(item => { let (key, count) = item let scaledValue = count *. (100.0 -. 10.0) +. 10.0 (key, scaledValue) }) // Adjust to Sum 100 let updatedData = updatedData->Array.map(item => { let (key, count) = item let mul = 100.0 /. total let finalValue = count *. mul (key, finalValue) }) // Round to Integers let updatedData = updatedData->Array.map(item => { let (key, count) = item let finalValue = (count *. 100.0)->Float.toInt (key, finalValue) }) updatedData->Dict.fromArray } let paymentsLifeCycleMapper = ( ~params: NewAnalyticsTypes.getObjects<paymentLifeCycle>, ): SankeyGraphTypes.sankeyPayload => { open NewAnalyticsUtils let {data, xKey} = params let isSmartRetryEnabled = xKey->getBoolFromString(true) let normalSuccess = data.normalSuccess let normalFailure = data.normalFailure let totalFailure = normalFailure + (isSmartRetryEnabled ? 0 : data.smartRetriedSuccess) let pending = data.pending let cancelled = data.cancelled let dropoff = data.drop_offs let disputed = data.disputed let refunded = data.refunded let partialRefunded = data.partialRefunded let smartRetriedFailure = isSmartRetryEnabled ? data.smartRetriedFailure : 0 let smartRetriedSuccess = isSmartRetryEnabled ? data.smartRetriedSuccess : 0 let success = normalSuccess + smartRetriedSuccess let valueDict = [ ("Succeeded on First Attempt", normalSuccess), ("Succeeded on Subsequent Attempts", smartRetriedSuccess), ("Failed", totalFailure), ("Smart Retried Failure", smartRetriedFailure), ("Pending", pending), ("Cancelled", cancelled), ("Drop-offs", dropoff), ("Dispute Raised", disputed), ("Refunds Issued", refunded), ("Partial Refunded", partialRefunded), ] ->Array.filter(item => { let (_, value) = item value > 0 }) ->transformData let total = success + totalFailure + pending + dropoff + cancelled let sankeyNodes = [ { id: "Payments Initiated", dataLabels: { align: "left", x: -130, name: total, }, }, { id: "Succeeded on First Attempt", dataLabels: { align: "right", x: 183, name: normalSuccess, }, }, { id: "Failed", dataLabels: { align: "left", x: 20, name: totalFailure, }, }, { id: "Pending", dataLabels: { align: "left", x: 20, name: pending, }, }, { id: "Cancelled", dataLabels: { align: "left", x: 20, name: cancelled, }, }, { id: "Drop-offs", dataLabels: { align: "left", x: 20, name: dropoff, }, }, { id: "Success", dataLabels: { align: "right", x: 65, name: success, }, }, { id: "Refunds Issued", dataLabels: { align: "right", x: 110, name: refunded, }, }, { id: "Partial Refunded", dataLabels: { align: "right", x: 115, name: partialRefunded, }, }, { id: "Dispute Raised", dataLabels: { align: "right", x: 105, name: disputed, }, }, { id: "Smart Retried Failure", dataLabels: { align: "right", x: 145, name: smartRetriedFailure, }, }, { id: "Succeeded on Subsequent Attempts", dataLabels: { align: "right", x: 235, name: smartRetriedSuccess, }, }, ] let normalSuccess = valueDict->getInt("Succeeded on First Attempt", 0) let smartRetriedSuccess = valueDict->getInt("Succeeded on Subsequent Attempts", 0) let totalFailure = valueDict->getInt("Failed", 0) let smartRetriedFailure = valueDict->getInt("Smart Retried Failure", 0) let pending = valueDict->getInt("Pending", 0) let cancelled = valueDict->getInt("Cancelled", 0) let dropoff = valueDict->getInt("Drop-offs", 0) let disputed = valueDict->getInt("Dispute Raised", 0) let refunded = valueDict->getInt("Refunds Issued", 0) let partialRefunded = valueDict->getInt("Partial Refunded", 0) let processedData = if isSmartRetryEnabled { [ ("Payments Initiated", "Succeeded on First Attempt", normalSuccess, sankyBlue), ("Payments Initiated", "Succeeded on Subsequent Attempts", smartRetriedSuccess, sankyBlue), // smart retry ("Payments Initiated", "Failed", totalFailure, sankyRed), ("Payments Initiated", "Pending", pending, sankyBlue), ("Payments Initiated", "Cancelled", cancelled, sankyRed), ("Payments Initiated", "Drop-offs", dropoff, sankyRed), ("Succeeded on First Attempt", "Success", normalSuccess, sankyBlue), ("Succeeded on Subsequent Attempts", "Success", smartRetriedSuccess, sankyBlue), ("Failed", "Smart Retried Failure", smartRetriedFailure, sankyRed), // smart retry ("Success", "Refunds Issued", refunded, sankyBlue), ("Success", "Partial Refunded", partialRefunded, sankyBlue), ("Success", "Dispute Raised", disputed, sankyRed), ] } else { [ ("Payments Initiated", "Success", normalSuccess, sankyBlue), ("Payments Initiated", "Failed", totalFailure, sankyRed), ("Payments Initiated", "Pending", pending, sankyBlue), ("Payments Initiated", "Cancelled", cancelled, sankyRed), ("Payments Initiated", "Drop-offs", dropoff, sankyRed), ("Success", "Refunds Issued", refunded, sankyBlue), ("Success", "Partial Refunded", partialRefunded, sankyBlue), ("Success", "Dispute Raised", disputed, sankyRed), ] } let title = { text: "", } let colors = if isSmartRetryEnabled { [ sankyLightBlue, // "Payments Initiated" sankyLightBlue, // "Succeeded on First Attempt" sankyLightBlue, // "Succeeded on Subsequent Attempts" sankyLightRed, // "Failed" sankyLightBlue, // "Pending" sankyLightRed, // "Cancelled" sankyLightRed, // "Drop-offs" sankyLightBlue, // "Success" sankyLightRed, // "Smart Retried Failure" sankyLightBlue, // "Refunds Issued" sankyLightBlue, // "Partial Refunded" sankyLightRed, // "Dispute Raised" ] } else { [ sankyLightBlue, // "Payments Initiated" sankyLightBlue, // "Success" sankyLightRed, // "Failed" sankyLightBlue, // "Pending" sankyLightRed, // "Cancelled" sankyLightRed, // "Drop-offs" sankyLightBlue, // "Refunds Issued" sankyLightBlue, // "Partial Refunded" sankyLightRed, // "Dispute Raised" ] } {data: processedData, nodes: sankeyNodes, title, colors} }
3,368
9,591
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/PaymentsSuccessRate/PaymentsSuccessRateUtils.res
.res
open PaymentsSuccessRateTypes let getStringFromVariant = value => { switch value { | Successful_Payments => "successful_payments" | Successful_Payments_Without_Smart_Retries => "successful_payments_without_smart_retries" | Total_Payments => "total_payments" | Payments_Success_Rate => "payments_success_rate" | Payments_Success_Rate_Without_Smart_Retries => "payments_success_rate_without_smart_retries" | Total_Success_Rate => "total_success_rate" | Total_Success_Rate_Without_Smart_Retries => "total_success_rate_without_smart_retries" | Time_Bucket => "time_bucket" } } let getVariantValueFromString = value => { switch value { | "successful_payments" => Successful_Payments | "successful_payments_without_smart_retries" => Successful_Payments_Without_Smart_Retries | "total_payments" => Total_Payments | "payments_success_rate" => Payments_Success_Rate | "payments_success_rate_without_smart_retries" => Payments_Success_Rate_Without_Smart_Retries | "total_success_rate" => Total_Success_Rate | "total_success_rate_without_smart_retries" => Total_Success_Rate_Without_Smart_Retries | "time_bucket" | _ => Time_Bucket } } let paymentsSuccessRateMapper = ( ~params: NewAnalyticsTypes.getObjects<JSON.t>, ): LineGraphTypes.lineGraphPayload => { open LineGraphTypes open NewAnalyticsUtils let {data, xKey, yKey} = params let comparison = switch params.comparison { | Some(val) => Some(val) | None => None } let primaryCategories = data->getCategories(0, yKey) let secondaryCategories = data->getCategories(1, yKey) let lineGraphData = data->getLineGraphData(~xKey, ~yKey) { chartHeight: DefaultHeight, chartLeftSpacing: DefaultLeftSpacing, categories: primaryCategories, data: lineGraphData, title: { text: "", }, yAxisMaxValue: 100->Some, yAxisMinValue: Some(0), tooltipFormatter: tooltipFormatter( ~secondaryCategories, ~title="Payments Success Rate", ~metricType=Rate, ~comparison, ), yAxisFormatter: LineGraphUtils.lineGraphYAxisFormatter( ~statType=Default, ~currency="", ~suffix="", ), legend: { useHTML: true, labelFormatter: LineGraphUtils.valueFormatter, }, } } open NewAnalyticsTypes let tabs = [{label: "Daily", value: (#G_ONEDAY: granularity :> string)}] let defaulGranularity = { label: "Hourly", value: (#G_ONEDAY: granularity :> string), } let getKeyForModule = (field, ~isSmartRetryEnabled) => { switch (field, isSmartRetryEnabled) { | (Payments_Success_Rate, Smart_Retry) => Payments_Success_Rate | (Payments_Success_Rate, Default) | _ => Payments_Success_Rate_Without_Smart_Retries }->getStringFromVariant } let getMetaDataMapper = (key, ~isSmartRetryEnabled) => { let field = key->getVariantValueFromString switch (field, isSmartRetryEnabled) { | (Payments_Success_Rate, Smart_Retry) => Total_Success_Rate | (Payments_Success_Rate, Default) | _ => Total_Success_Rate_Without_Smart_Retries }->getStringFromVariant }
802
9,592
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/PaymentsSuccessRate/PaymentsSuccessRateTypes.res
.res
type successRateCols = | Successful_Payments | Successful_Payments_Without_Smart_Retries | Total_Payments | Payments_Success_Rate | Payments_Success_Rate_Without_Smart_Retries | Total_Success_Rate | Total_Success_Rate_Without_Smart_Retries | Time_Bucket type payments_success_rate = { successful_payments: int, successful_payments_without_smart_retries: int, total_payments: int, payments_success_rate: float, payments_success_rate_without_smart_retries: float, total_success_rate: float, total_success_rate_without_smart_retries: float, time_bucket: string, }
152
9,593
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/PaymentsSuccessRate/PaymentsSuccessRate.res
.res
open NewAnalyticsTypes open NewAnalyticsHelper open LineGraphTypes open PaymentsSuccessRateUtils open NewPaymentAnalyticsUtils module PaymentsSuccessRateHeader = { open NewAnalyticsUtils open LogicUtils @react.component let make = (~data, ~keyValue, ~granularity, ~setGranularity, ~granularityOptions) => { let setGranularity = value => { setGranularity(_ => value) } let {filterValueJson} = React.useContext(FilterContext.filterContext) let comparison = filterValueJson->getString("comparison", "")->DateRangeUtils.comparisonMapprer let featureFlag = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let isSmartRetryEnabled = filterValueJson ->getString("is_smart_retry_enabled", "true") ->getBoolFromString(true) ->getSmartRetryMetricType let primaryValue = getMetaDataValue( ~data, ~index=0, ~key=keyValue->getMetaDataMapper(~isSmartRetryEnabled), ) let secondaryValue = getMetaDataValue( ~data, ~index=1, ~key=keyValue->getMetaDataMapper(~isSmartRetryEnabled), ) let (value, direction) = calculatePercentageChange(~primaryValue, ~secondaryValue) <div className="w-full px-7 py-8 grid grid-cols-3"> <div className="flex gap-2 items-center"> <div className="text-fs-28 font-semibold"> {primaryValue->valueFormatter(Rate)->React.string} </div> <RenderIf condition={comparison == EnableComparison}> <StatisticsCard value direction tooltipValue={secondaryValue->valueFormatter(Rate)} /> </RenderIf> </div> <div className="flex justify-center w-full"> <RenderIf condition={featureFlag.granularity}> <Tabs option={granularity} setOption={setGranularity} options={granularityOptions} showSingleTab=false /> </RenderIf> </div> </div> } } @react.component let make = ( ~entity: moduleEntity, ~chartEntity: chartEntity<lineGraphPayload, lineGraphOptions, JSON.t>, ) => { open LogicUtils open APIUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let isoStringToCustomTimeZone = TimeZoneHook.useIsoStringToCustomTimeZone() let (paymentsSuccessRateData, setPaymentsSuccessRateData) = React.useState(_ => JSON.Encode.array([]) ) let (paymentsSuccessRateMetaData, setpaymentsProcessedMetaData) = React.useState(_ => JSON.Encode.array([]) ) let {filterValueJson} = React.useContext(FilterContext.filterContext) let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let compareToStartTime = filterValueJson->getString("compareToStartTime", "") let compareToEndTime = filterValueJson->getString("compareToEndTime", "") let comparison = filterValueJson->getString("comparison", "")->DateRangeUtils.comparisonMapprer let currency = filterValueJson->getString((#currency: filters :> string), "") let isSmartRetryEnabled = filterValueJson ->getString("is_smart_retry_enabled", "true") ->getBoolFromString(true) ->getSmartRetryMetricType open NewAnalyticsUtils let featureFlag = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let defaulGranularity = getDefaultGranularity( ~startTime=startTimeVal, ~endTime=endTimeVal, ~granularity=featureFlag.granularity, ) let granularityOptions = getGranularityOptions(~startTime=startTimeVal, ~endTime=endTimeVal) let (granularity, setGranularity) = React.useState(_ => defaulGranularity) let getPaymentsSuccessRate = async () => { setScreenState(_ => PageLoaderWrapper.Loading) try { let url = getURL( ~entityName=V1(ANALYTICS_PAYMENTS_V2), ~methodType=Post, ~id=Some((entity.domain: domain :> string)), ) let primaryBody = requestBody( ~startTime=startTimeVal, ~endTime=endTimeVal, ~delta=entity.requestBodyConfig.delta, ~metrics=entity.requestBodyConfig.metrics, ~granularity=granularity.value->Some, ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let secondaryBody = requestBody( ~startTime=compareToStartTime, ~endTime=compareToEndTime, ~delta=entity.requestBodyConfig.delta, ~metrics=entity.requestBodyConfig.metrics, ~granularity=granularity.value->Some, ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let primaryResponse = await updateDetails(url, primaryBody, Post) let primaryData = primaryResponse ->getDictFromJsonObject ->getArrayFromDict("queryData", []) ->sortQueryDataByDate let primaryMetaData = primaryResponse->getDictFromJsonObject->getArrayFromDict("metaData", []) let (secondaryMetaData, secondaryModifiedData) = switch comparison { | EnableComparison => { let secondaryResponse = await updateDetails(url, secondaryBody, Post) let secondaryData = secondaryResponse->getDictFromJsonObject->getArrayFromDict("queryData", []) let secondaryMetaData = secondaryResponse->getDictFromJsonObject->getArrayFromDict("metaData", []) let secondaryModifiedData = [secondaryData]->Array.map(data => { fillMissingDataPoints( ~data, ~startDate=compareToStartTime, ~endDate=compareToEndTime, ~timeKey="time_bucket", ~defaultValue={ "payment_count": 0, "payment_processed_amount": 0, "time_bucket": startTimeVal, }->Identity.genericTypeToJson, ~granularity=granularity.value, ~isoStringToCustomTimeZone, ~granularityEnabled=featureFlag.granularity, ) }) (secondaryMetaData, secondaryModifiedData) } | DisableComparison => ([], []) } if primaryData->Array.length > 0 { let primaryModifiedData = [primaryData]->Array.map(data => { fillMissingDataPoints( ~data, ~startDate=startTimeVal, ~endDate=endTimeVal, ~timeKey=Time_Bucket->getStringFromVariant, ~defaultValue={ "payment_count": 0, "payment_success_rate": 0, "time_bucket": startTimeVal, }->Identity.genericTypeToJson, ~granularity=granularity.value, ~isoStringToCustomTimeZone, ~granularityEnabled=featureFlag.granularity, ) }) setPaymentsSuccessRateData(_ => primaryModifiedData->Array.concat(secondaryModifiedData)->Identity.genericTypeToJson ) setpaymentsProcessedMetaData(_ => primaryMetaData->Array.concat(secondaryMetaData)->Identity.genericTypeToJson ) setScreenState(_ => PageLoaderWrapper.Success) } else { setScreenState(_ => PageLoaderWrapper.Custom) } } catch { | _ => setScreenState(_ => PageLoaderWrapper.Custom) } } React.useEffect(() => { if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString { getPaymentsSuccessRate()->ignore } None }, ( startTimeVal, endTimeVal, compareToStartTime, compareToEndTime, comparison, currency, granularity, )) let mockDelay = async () => { if paymentsSuccessRateData != []->JSON.Encode.array { setScreenState(_ => Loading) await HyperSwitchUtils.delay(300) setScreenState(_ => Success) } } React.useEffect(() => { mockDelay()->ignore None }, [isSmartRetryEnabled]) let params = { data: paymentsSuccessRateData, xKey: Payments_Success_Rate->getKeyForModule(~isSmartRetryEnabled), yKey: Time_Bucket->getStringFromVariant, comparison, } let options = chartEntity.getObjects(~params)->chartEntity.getChatOptions <div> <ModuleHeader title={entity.title} /> <Card> <PageLoaderWrapper screenState customLoader={<Shimmer layoutId=entity.title />} customUI={<NoData />}> <PaymentsSuccessRateHeader data={paymentsSuccessRateMetaData} keyValue={Payments_Success_Rate->getStringFromVariant} granularity setGranularity granularityOptions /> <div className="mb-5"> <LineGraph options className="mr-3" /> </div> </PageLoaderWrapper> </Card> </div> }
1,944
9,594
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/FailedPaymentsDistribution/FailedPaymentsDistribution.res
.res
open NewAnalyticsTypes open NewAnalyticsHelper open NewPaymentAnalyticsEntity open BarGraphTypes open FailedPaymentsDistributionUtils open NewPaymentAnalyticsUtils module TableModule = { @react.component let make = (~data, ~className="", ~selectedTab: string) => { open LogicUtils let (offset, setOffset) = React.useState(_ => 0) let {filterValueJson} = React.useContext(FilterContext.filterContext) let isSmartRetryEnabled = filterValueJson ->getString("is_smart_retry_enabled", "true") ->getBoolFromString(true) ->getSmartRetryMetricType let defaultSort: Table.sortedObject = { key: "", order: Table.INC, } let defaultCol = isSmartRetryEnbldForFailedPmtDist(isSmartRetryEnabled) let visibleColumns = [selectedTab->getColumn]->Array.concat([defaultCol]) let tableData = getTableData(data) <div className> <LoadedTable visibleColumns title="Failed Payments Distribution" hideTitle=true actualData={tableData} entity=failedPaymentsDistributionTableEntity resultsPerPage=10 totalResults={tableData->Array.length} offset setOffset defaultSort currrentFetchCount={tableData->Array.length} tableLocalFilter=false tableheadingClass=tableBorderClass tableBorderClass ignoreHeaderBg=true tableDataBorderClass=tableBorderClass isAnalyticsModule=true /> </div> } } module FailedPaymentsDistributionHeader = { @react.component let make = (~viewType, ~setViewType, ~groupBy, ~setGroupBy) => { let setViewType = value => { setViewType(_ => value) } let setGroupBy = value => { setGroupBy(_ => value) } <div className="w-full px-7 py-8 flex justify-between"> <Tabs option={groupBy} setOption={setGroupBy} options={tabs} /> <div className="flex gap-2"> <TabSwitch viewType setViewType /> </div> </div> } } @react.component let make = ( ~entity: moduleEntity, ~chartEntity: chartEntity<barGraphPayload, barGraphOptions, JSON.t>, ) => { open LogicUtils open APIUtils open NewAnalyticsUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let {filterValueJson} = React.useContext(FilterContext.filterContext) let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Success) let (failedPaymentsDistribution, setfailedPaymentsDistribution) = React.useState(_ => JSON.Encode.array([]) ) let (viewType, setViewType) = React.useState(_ => Graph) let (groupBy, setGroupBy) = React.useState(_ => defaulGroupBy) let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let isSmartRetryEnabled = filterValueJson ->getString("is_smart_retry_enabled", "true") ->getBoolFromString(true) ->getSmartRetryMetricType let currency = filterValueJson->getString((#currency: filters :> string), "") let getFailedPaymentsDistribution = async () => { try { setScreenState(_ => PageLoaderWrapper.Loading) let url = getURL( ~entityName=V1(ANALYTICS_PAYMENTS), ~methodType=Post, ~id=Some((entity.domain: domain :> string)), ) let body = requestBody( ~startTime=startTimeVal, ~endTime=endTimeVal, ~delta=entity.requestBodyConfig.delta, ~metrics=entity.requestBodyConfig.metrics, ~groupByNames=[groupBy.value]->Some, ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let response = await updateDetails(url, body, Post) let responseData = response ->getDictFromJsonObject ->getArrayFromDict("queryData", []) ->filterQueryData(groupBy.value) if responseData->Array.length > 0 { setfailedPaymentsDistribution(_ => responseData->JSON.Encode.array) setScreenState(_ => PageLoaderWrapper.Success) } else { setScreenState(_ => PageLoaderWrapper.Custom) } } catch { | _ => setScreenState(_ => PageLoaderWrapper.Custom) } } React.useEffect(() => { if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString { getFailedPaymentsDistribution()->ignore } None }, [startTimeVal, endTimeVal, groupBy.value, currency]) let params = { data: failedPaymentsDistribution, xKey: Payments_Failure_Rate_Distribution->getKeyForModule(~isSmartRetryEnabled), yKey: groupBy.value, } let options = chartEntity.getChatOptions(chartEntity.getObjects(~params)) <div> <ModuleHeader title={entity.title} /> <Card> <PageLoaderWrapper screenState customLoader={<Shimmer layoutId=entity.title />} customUI={<NoData />}> <FailedPaymentsDistributionHeader viewType setViewType groupBy setGroupBy /> <div className="mb-5"> {switch viewType { | Graph => <BarGraph options className="mr-3" /> | Table => <TableModule data={failedPaymentsDistribution} className="mx-7" selectedTab={groupBy.value} /> }} </div> </PageLoaderWrapper> </Card> </div> }
1,241
9,595
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/FailedPaymentsDistribution/FailedPaymentsDistributionUtils.res
.res
open FailedPaymentsDistributionTypes open LogicUtils let getStringFromVariant = value => { switch value { | Payments_Failure_Rate_Distribution => "payments_failure_rate_distribution" | Payments_Failure_Rate_Distribution_Without_Smart_Retries => "payments_failure_rate_distribution_without_smart_retries" | Connector => "connector" | Payment_Method => "payment_method" | Payment_Method_Type => "payment_method_type" | Authentication_Type => "authentication_type" } } let getColumn = string => { switch string { | "connector" => Connector | "payment_method" => Payment_Method | "payment_method_type" => Payment_Method_Type | "authentication_type" => Authentication_Type | _ => Connector } } let failedPaymentsDistributionMapper = ( ~params: NewAnalyticsTypes.getObjects<JSON.t>, ): BarGraphTypes.barGraphPayload => { open BarGraphTypes open NewAnalyticsUtils let {data, xKey, yKey} = params let categories = [data]->JSON.Encode.array->getCategories(0, yKey) let barGraphData = getBarGraphObj( ~array=data->getArrayFromJson([]), ~key=xKey, ~name=xKey->snakeToTitle, ~color=redColor, ) let title = { text: "", } { categories, data: [barGraphData], title, tooltipFormatter: bargraphTooltipFormatter( ~title="Failed Payments Distribution", ~metricType=Rate, ), } } open NewAnalyticsTypes let tableItemToObjMapper: Dict.t<JSON.t> => failedPaymentsDistributionObject = dict => { { payments_failure_rate_distribution: dict->getFloat( Payments_Failure_Rate_Distribution->getStringFromVariant, 0.0, ), payments_failure_rate_distribution_without_smart_retries: dict->getFloat( Payments_Failure_Rate_Distribution_Without_Smart_Retries->getStringFromVariant, 0.0, ), connector: dict->getString(Connector->getStringFromVariant, ""), payment_method: dict->getString(Payment_Method->getStringFromVariant, ""), payment_method_type: dict->getString(Payment_Method_Type->getStringFromVariant, ""), authentication_type: dict->getString(Authentication_Type->getStringFromVariant, ""), } } let getObjects: JSON.t => array<failedPaymentsDistributionObject> = json => { json ->LogicUtils.getArrayFromJson([]) ->Array.map(item => { tableItemToObjMapper(item->getDictFromJsonObject) }) } let getHeading = colType => { switch colType { | Payments_Failure_Rate_Distribution => Table.makeHeaderInfo( ~key=Payments_Failure_Rate_Distribution->getStringFromVariant, ~title="Payments Failure Rate Distribution", ~dataType=TextType, ) | Payments_Failure_Rate_Distribution_Without_Smart_Retries => Table.makeHeaderInfo( ~key=Payments_Failure_Rate_Distribution_Without_Smart_Retries->getStringFromVariant, ~title="Payments Failure Rate Distribution", ~dataType=TextType, ) | Connector => Table.makeHeaderInfo( ~key=Connector->getStringFromVariant, ~title="Connector", ~dataType=TextType, ) | Payment_Method => Table.makeHeaderInfo( ~key=Payment_Method->getStringFromVariant, ~title="Payment Method", ~dataType=TextType, ) | Payment_Method_Type => Table.makeHeaderInfo( ~key=Payment_Method_Type->getStringFromVariant, ~title="Payment Method Type", ~dataType=TextType, ) | Authentication_Type => Table.makeHeaderInfo( ~key=Authentication_Type->getStringFromVariant, ~title="Authentication Type", ~dataType=TextType, ) } } let getCell = (obj, colType): Table.cell => { switch colType { | Payments_Failure_Rate_Distribution => Text(obj.payments_failure_rate_distribution->valueFormatter(Rate)) | Payments_Failure_Rate_Distribution_Without_Smart_Retries => Text(obj.payments_failure_rate_distribution_without_smart_retries->valueFormatter(Rate)) | Connector => Text(obj.connector) | Payment_Method => Text(obj.payment_method) | Payment_Method_Type => Text(obj.payment_method_type) | Authentication_Type => Text(obj.authentication_type) } } let getTableData = json => { json->getArrayDataFromJson(tableItemToObjMapper)->Array.map(Nullable.make) } let tabs = [ { label: "Connector", value: Connector->getStringFromVariant, }, { label: "Payment Method", value: Payment_Method->getStringFromVariant, }, { label: "Payment Method Type", value: Payment_Method_Type->getStringFromVariant, }, { label: "Authentication Type", value: Authentication_Type->getStringFromVariant, }, ] let defaulGroupBy = { label: "Connector", value: Connector->getStringFromVariant, } let getKeyForModule = (field, ~isSmartRetryEnabled) => { switch (field, isSmartRetryEnabled) { | (Payments_Failure_Rate_Distribution, Smart_Retry) => Payments_Failure_Rate_Distribution | (Payments_Failure_Rate_Distribution, Default) | _ => Payments_Failure_Rate_Distribution_Without_Smart_Retries }->getStringFromVariant } let isSmartRetryEnbldForFailedPmtDist = isEnabled => { switch isEnabled { | Smart_Retry => Payments_Failure_Rate_Distribution | Default => Payments_Failure_Rate_Distribution_Without_Smart_Retries } }
1,255
9,596
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/FailedPaymentsDistribution/FailedPaymentsDistributionTypes.res
.res
type failedPaymentsDistributionCols = | Payments_Failure_Rate_Distribution | Payments_Failure_Rate_Distribution_Without_Smart_Retries | Connector | Payment_Method | Payment_Method_Type | Authentication_Type type failedPaymentsDistributionObject = { payments_failure_rate_distribution: float, payments_failure_rate_distribution_without_smart_retries: float, connector: string, payment_method: string, payment_method_type: string, authentication_type: string, }
105
9,597
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/SuccessfulPaymentsDistribution/SuccessfulPaymentsDistributionUtils.res
.res
open SuccessfulPaymentsDistributionTypes open LogicUtils let getStringFromVariant = value => { switch value { | Payments_Success_Rate_Distribution => "payments_success_rate_distribution" | Payments_Success_Rate_Distribution_Without_Smart_Retries => "payments_success_rate_distribution_without_smart_retries" | Connector => "connector" | Payment_Method => "payment_method" | Payment_Method_Type => "payment_method_type" | Authentication_Type => "authentication_type" } } let getColumn = string => { switch string { | "connector" => Connector | "payment_method" => Payment_Method | "payment_method_type" => Payment_Method_Type | "authentication_type" => Authentication_Type | _ => Connector } } let successfulPaymentsDistributionMapper = ( ~params: NewAnalyticsTypes.getObjects<JSON.t>, ): BarGraphTypes.barGraphPayload => { open BarGraphTypes open NewAnalyticsUtils let {data, xKey, yKey} = params let categories = [data]->JSON.Encode.array->getCategories(0, yKey) let barGraphData = getBarGraphObj( ~array=data->getArrayFromJson([]), ~key=xKey, ~name=xKey->snakeToTitle, ~color=barGreenColor, ) let title = { text: "", } { categories, data: [barGraphData], title, tooltipFormatter: bargraphTooltipFormatter( ~title="Successful Payments Distribution", ~metricType=Rate, ), } } open NewAnalyticsTypes let tableItemToObjMapper: Dict.t<JSON.t> => successfulPaymentsDistributionObject = dict => { { payments_success_rate_distribution: dict->getFloat( Payments_Success_Rate_Distribution->getStringFromVariant, 0.0, ), payments_success_rate_distribution_without_smart_retries: dict->getFloat( Payments_Success_Rate_Distribution_Without_Smart_Retries->getStringFromVariant, 0.0, ), connector: dict->getString(Connector->getStringFromVariant, ""), payment_method: dict->getString(Payment_Method->getStringFromVariant, ""), payment_method_type: dict->getString(Payment_Method_Type->getStringFromVariant, ""), authentication_type: dict->getString(Authentication_Type->getStringFromVariant, ""), } } let getObjects: JSON.t => array<successfulPaymentsDistributionObject> = json => { json ->LogicUtils.getArrayFromJson([]) ->Array.map(item => { tableItemToObjMapper(item->getDictFromJsonObject) }) } let getHeading = colType => { switch colType { | Payments_Success_Rate_Distribution => Table.makeHeaderInfo( ~key=Payments_Success_Rate_Distribution->getStringFromVariant, ~title="Payments Success Rate", ~dataType=TextType, ) | Payments_Success_Rate_Distribution_Without_Smart_Retries => Table.makeHeaderInfo( ~key=Payments_Success_Rate_Distribution_Without_Smart_Retries->getStringFromVariant, ~title="Payments Success Rate", ~dataType=TextType, ) | Connector => Table.makeHeaderInfo( ~key=Connector->getStringFromVariant, ~title="Connector", ~dataType=TextType, ) | Payment_Method => Table.makeHeaderInfo( ~key=Payment_Method->getStringFromVariant, ~title="Payment Method", ~dataType=TextType, ) | Payment_Method_Type => Table.makeHeaderInfo( ~key=Payment_Method_Type->getStringFromVariant, ~title="Payment Method Type", ~dataType=TextType, ) | Authentication_Type => Table.makeHeaderInfo( ~key=Authentication_Type->getStringFromVariant, ~title="Authentication Type", ~dataType=TextType, ) } } let getCell = (obj, colType): Table.cell => { switch colType { | Payments_Success_Rate_Distribution => Text(obj.payments_success_rate_distribution->valueFormatter(Rate)) | Payments_Success_Rate_Distribution_Without_Smart_Retries => Text(obj.payments_success_rate_distribution_without_smart_retries->valueFormatter(Rate)) | Connector => Text(obj.connector) | Payment_Method => Text(obj.payment_method) | Payment_Method_Type => Text(obj.payment_method_type) | Authentication_Type => Text(obj.authentication_type) } } let getTableData = json => { json->getArrayDataFromJson(tableItemToObjMapper)->Array.map(Nullable.make) } let tabs = [ { label: "Connector", value: Connector->getStringFromVariant, }, { label: "Payment Method", value: Payment_Method->getStringFromVariant, }, { label: "Payment Method Type", value: Payment_Method_Type->getStringFromVariant, }, { label: "Authentication Type", value: Authentication_Type->getStringFromVariant, }, ] let defaulGroupBy = { label: "Connector", value: Connector->getStringFromVariant, } let getKeyForModule = (field, ~isSmartRetryEnabled) => { switch (field, isSmartRetryEnabled) { | (Payments_Success_Rate_Distribution, Smart_Retry) => Payments_Success_Rate_Distribution | (Payments_Success_Rate_Distribution, Default) | _ => Payments_Success_Rate_Distribution_Without_Smart_Retries }->getStringFromVariant } let isSmartRetryEnbldForSuccessPmtDist = isEnabled => { switch isEnabled { | Smart_Retry => Payments_Success_Rate_Distribution | Default => Payments_Success_Rate_Distribution_Without_Smart_Retries } }
1,238
9,598
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/SuccessfulPaymentsDistribution/SuccessfulPaymentsDistributionTypes.res
.res
type successfulPaymentsDistributionCols = | Payments_Success_Rate_Distribution | Payments_Success_Rate_Distribution_Without_Smart_Retries | Connector | Payment_Method | Payment_Method_Type | Authentication_Type type successfulPaymentsDistributionObject = { payments_success_rate_distribution: float, payments_success_rate_distribution_without_smart_retries: float, connector: string, payment_method: string, payment_method_type: string, authentication_type: string, }
103
9,599
hyperswitch-control-center
src/screens/NewAnalytics/PaymentAnalytics/SuccessfulPaymentsDistribution/SuccessfulPaymentsDistribution.res
.res
open NewAnalyticsTypes open NewAnalyticsHelper open NewPaymentAnalyticsEntity open BarGraphTypes open SuccessfulPaymentsDistributionUtils open NewPaymentAnalyticsUtils module TableModule = { open LogicUtils @react.component let make = (~data, ~className="", ~selectedTab: string) => { let (offset, setOffset) = React.useState(_ => 0) let defaultSort: Table.sortedObject = { key: "", order: Table.INC, } let {filterValueJson} = React.useContext(FilterContext.filterContext) let isSmartRetryEnabled = filterValueJson ->getString("is_smart_retry_enabled", "true") ->getBoolFromString(true) ->getSmartRetryMetricType let defaultCol = isSmartRetryEnabled->isSmartRetryEnbldForSuccessPmtDist let visibleColumns = [selectedTab->getColumn]->Array.concat([defaultCol]) let tableData = getTableData(data) <div className> <LoadedTable visibleColumns title="Successful Payments Distribution" hideTitle=true actualData={tableData} entity=successfulPaymentsDistributionTableEntity resultsPerPage=10 totalResults={tableData->Array.length} offset setOffset defaultSort currrentFetchCount={tableData->Array.length} tableLocalFilter=false tableheadingClass=tableBorderClass tableBorderClass ignoreHeaderBg=true tableDataBorderClass=tableBorderClass isAnalyticsModule=true /> </div> } } module SuccessfulPaymentsDistributionHeader = { @react.component let make = (~viewType, ~setViewType, ~groupBy, ~setGroupBy) => { let setViewType = value => { setViewType(_ => value) } let setGroupBy = value => { setGroupBy(_ => value) } <div className="w-full px-7 py-8 flex justify-between"> <Tabs option={groupBy} setOption={setGroupBy} options={tabs} /> <div className="flex gap-2"> <TabSwitch viewType setViewType /> </div> </div> } } @react.component let make = ( ~entity: moduleEntity, ~chartEntity: chartEntity<barGraphPayload, barGraphOptions, JSON.t>, ) => { open LogicUtils open APIUtils open NewAnalyticsUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let {filterValueJson} = React.useContext(FilterContext.filterContext) let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let (paymentsDistribution, setpaymentsDistribution) = React.useState(_ => JSON.Encode.array([])) let (viewType, setViewType) = React.useState(_ => Graph) let (groupBy, setGroupBy) = React.useState(_ => defaulGroupBy) let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let isSmartRetryEnabled = filterValueJson ->getString("is_smart_retry_enabled", "true") ->getBoolFromString(true) ->getSmartRetryMetricType let currency = filterValueJson->getString((#currency: filters :> string), "") let getPaymentsDistribution = async () => { setScreenState(_ => PageLoaderWrapper.Loading) try { let url = getURL( ~entityName=V1(ANALYTICS_PAYMENTS), ~methodType=Post, ~id=Some((entity.domain: domain :> string)), ) let body = requestBody( ~startTime=startTimeVal, ~endTime=endTimeVal, ~delta=entity.requestBodyConfig.delta, ~metrics=entity.requestBodyConfig.metrics, ~groupByNames=[groupBy.value]->Some, ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let response = await updateDetails(url, body, Post) let responseData = response ->getDictFromJsonObject ->getArrayFromDict("queryData", []) ->filterQueryData(groupBy.value) if responseData->Array.length > 0 { setpaymentsDistribution(_ => responseData->JSON.Encode.array) setScreenState(_ => PageLoaderWrapper.Success) } else { setScreenState(_ => PageLoaderWrapper.Custom) } } catch { | _ => setScreenState(_ => PageLoaderWrapper.Custom) } } React.useEffect(() => { if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString { getPaymentsDistribution()->ignore } None }, [startTimeVal, endTimeVal, groupBy.value, currency]) let params = { data: paymentsDistribution, xKey: Payments_Success_Rate_Distribution->getKeyForModule(~isSmartRetryEnabled), yKey: groupBy.value, } let options = chartEntity.getChatOptions(chartEntity.getObjects(~params)) <div> <ModuleHeader title={entity.title} /> <Card> <PageLoaderWrapper screenState customLoader={<Shimmer layoutId=entity.title />} customUI={<NoData />}> <SuccessfulPaymentsDistributionHeader viewType setViewType groupBy setGroupBy /> <div className="mb-5"> {switch viewType { | Graph => <BarGraph options className="mr-3" /> | Table => <TableModule data={paymentsDistribution} className="mx-7" selectedTab={groupBy.value} /> }} </div> </PageLoaderWrapper> </Card> </div> }
1,230
9,600
hyperswitch-control-center
src/screens/NewAnalytics/NewAuthenticationAnalytics/NewAuthenticationAnalyticsUtils.res
.res
open NewAuthenticationAnalyticsTypes open LogicUtils let defaultQueryData: queryDataType = { authentication_count: 0, authentication_attempt_count: 0, authentication_success_count: 0, challenge_flow_count: 0, challenge_attempt_count: 0, challenge_success_count: 0, frictionless_flow_count: 0, frictionless_success_count: 0, error_message_count: 0, authentication_funnel: 0, authentication_status: None, trans_status: None, error_message: "", authentication_connector: None, message_version: None, time_range: { start_time: "", end_time: "", }, time_bucket: "", } let defaultSecondFunnelData = { authentication_count: 0, authentication_attempt_count: 0, authentication_success_count: 0, challenge_flow_count: 0, challenge_attempt_count: 0, challenge_success_count: 0, frictionless_flow_count: 0, frictionless_success_count: 0, error_message_count: None, authentication_funnel: 0, authentication_status: None, trans_status: None, error_message: None, authentication_connector: None, message_version: None, time_range: { start_time: "", end_time: "", }, time_bucket: "", } let defaultMetaData: metaDataType = { total_error_message_count: 0, } let itemToObjMapperForQueryData: Dict.t<JSON.t> => queryDataType = dict => { { authentication_count: getInt(dict, "authentication_count", 0), authentication_attempt_count: getInt(dict, "authentication_attempt_count", 0), authentication_success_count: getInt(dict, "authentication_success_count", 0), challenge_flow_count: getInt(dict, "challenge_flow_count", 0), challenge_attempt_count: getInt(dict, "challenge_attempt_count", 0), challenge_success_count: getInt(dict, "challenge_success_count", 0), frictionless_flow_count: getInt(dict, "frictionless_flow_count", 0), frictionless_success_count: getInt(dict, "frictionless_success_count", 0), error_message_count: getInt(dict, "error_message_count", 0), authentication_funnel: getInt(dict, "authentication_funnel", 0), authentication_status: getOptionString(dict, "authentication_status"), trans_status: getOptionString(dict, "trans_status"), error_message: getString(dict, "error_message", ""), authentication_connector: getOptionString(dict, "authentication_connector"), message_version: getOptionString(dict, "message_version"), time_range: { start_time: getString(dict, "start_time", ""), end_time: getString(dict, "end_time", ""), }, time_bucket: getString(dict, "time_bucket", ""), } } let itemToObjMapperForSecondFunnelData: Dict.t<JSON.t> => secondFunnelDataType = dict => { { authentication_count: getInt(dict, "authentication_count", 0), authentication_attempt_count: getInt(dict, "authentication_attempt_count", 0), authentication_success_count: getInt(dict, "authentication_success_count", 0), challenge_flow_count: getInt(dict, "challenge_flow_count", 0), challenge_attempt_count: getInt(dict, "challenge_attempt_count", 0), challenge_success_count: getInt(dict, "challenge_success_count", 0), frictionless_flow_count: getInt(dict, "frictionless_flow_count", 0), frictionless_success_count: getInt(dict, "frictionless_success_count", 0), error_message_count: getOptionInt(dict, "error_message_count"), authentication_funnel: getInt(dict, "authentication_funnel", 0), authentication_status: getOptionString(dict, "authentication_status"), trans_status: getOptionString(dict, "trans_status"), error_message: getOptionString(dict, "error_message"), authentication_connector: getOptionString(dict, "authentication_connector"), message_version: getOptionString(dict, "message_version"), time_range: { start_time: getString(dict, "start_time", ""), end_time: getString(dict, "end_time", ""), }, time_bucket: getString(dict, "time_bucket", ""), } } let itemToObjMapperForMetaData: Dict.t<JSON.t> => metaDataType = dict => { { total_error_message_count: getInt(dict, "total_error_message_count", 0), } } let itemToObjMapperForInsightsData: Dict.t<JSON.t> => insightsDataType = dict => { { queryData: getArrayDataFromJson( dict->getArrayFromDict("queryData", [])->JSON.Encode.array, itemToObjMapperForQueryData, ), metaData: getArrayDataFromJson( dict->getArrayFromDict("metaData", [])->JSON.Encode.array, itemToObjMapperForMetaData, ), } } let itemToObjMapperForFunnelData: Dict.t<JSON.t> => funnelDataType = dict => { { payments_requiring_3ds_2_authentication: dict->getInt( "payments_requiring_3ds_2_authentication", 0, ), authentication_initiated: dict->getInt("authentication_initiated", 0), authentication_attemped: dict->getInt("authentication_attemped", 0), authentication_successful: dict->getInt("authentication_successful", 0), } } let metrics: array<LineChartUtils.metricsConfig> = [ { metric_name_db: "payments_requiring_3ds_2_authentication", metric_label: "Payments Requiring 3DS 2.0 Authentication", thresholdVal: None, step_up_threshold: None, metric_type: Rate, disabled: false, }, { metric_name_db: "authentication_initiated", metric_label: "Authentication Initiated", thresholdVal: None, step_up_threshold: None, metric_type: Rate, disabled: false, }, { metric_name_db: "authentication_attemped", metric_label: "Authentication Attempted", thresholdVal: None, step_up_threshold: None, metric_type: Rate, disabled: false, }, { metric_name_db: "authentication_successful", metric_label: "Authentication Successful", thresholdVal: None, step_up_threshold: None, metric_type: Rate, disabled: false, }, ] let getFunnelChartData = funnelData => { let funnelDict = Dict.make() funnelDict->Dict.set( "payments_requiring_3ds_2_authentication", (funnelData.payments_requiring_3ds_2_authentication->Int.toFloat /. funnelData.payments_requiring_3ds_2_authentication->Int.toFloat *. 100.0) ->Float.toString ->JSON.Encode.string, ) funnelDict->Dict.set( "authentication_initiated", (funnelData.authentication_initiated->Int.toFloat /. funnelData.payments_requiring_3ds_2_authentication->Int.toFloat *. 100.0) ->Float.toString ->JSON.Encode.string, ) funnelDict->Dict.set( "authentication_attemped", (funnelData.authentication_attemped->Int.toFloat /. funnelData.payments_requiring_3ds_2_authentication->Int.toFloat *. 100.0) ->Float.toString ->JSON.Encode.string, ) funnelDict->Dict.set( "authentication_successful", (funnelData.authentication_successful->Int.toFloat /. funnelData.payments_requiring_3ds_2_authentication->Int.toFloat *. 100.0) ->Float.toString ->JSON.Encode.string, ) let funnelDataArray = [funnelDict->JSON.Encode.object] funnelDataArray } let getMetricsData = (queryData: queryDataType) => { let dataArray = [ { title: "Payments Requiring 3DS authentication", value: queryData.authentication_count->Int.toFloat, valueType: Default, tooltip_description: "Total number of payments which requires 3DS 2.0 authentication", }, { title: "Authentication Success Rate", value: queryData.authentication_success_count->Int.toFloat /. queryData.authentication_count->Int.toFloat *. 100.0, valueType: Rate, tooltip_description: "Successful authentication requests over total authentication requests", }, { title: "Challenge Flow Rate", value: queryData.challenge_flow_count->Int.toFloat /. queryData.authentication_count->Int.toFloat *. 100.0, valueType: Rate, tooltip_description: "Challenge flow requests over total authentication requests", }, { title: "Frictionless Flow Rate", value: queryData.frictionless_flow_count->Int.toFloat /. queryData.authentication_count->Int.toFloat *. 100.0, valueType: Rate, tooltip_description: "Frictionless flow requests over total authentication requests", }, { title: "Challenge Attempt Rate", value: queryData.challenge_attempt_count->Int.toFloat /. queryData.challenge_flow_count->Int.toFloat *. 100.0, valueType: Rate, tooltip_description: "Attempted challenge requests over total challenge requests", }, { title: "Challenge Success Rate", value: queryData.challenge_success_count->Int.toFloat /. queryData.challenge_flow_count->Int.toFloat *. 100.0, valueType: Rate, tooltip_description: "Successful challenge requests over total challenge requests", }, { title: "Frictionless Success Rate", value: queryData.frictionless_success_count->Int.toFloat /. queryData.frictionless_flow_count->Int.toFloat *. 100.0, valueType: Rate, tooltip_description: "Successful frictionless requests over total frictionless requests", }, ] dataArray } let getUpdatedFilterValueJson = (filterValueJson: Dict.t<JSON.t>) => { let updatedFilterValueJson = Js.Dict.map(t => t, filterValueJson) let authConnectors = filterValueJson->getArrayFromDict("authentication_connector", [])->getNonEmptyArray let messageVersions = filterValueJson->getArrayFromDict("message_version", [])->getNonEmptyArray updatedFilterValueJson->LogicUtils.setOptionArray("authentication_connector", authConnectors) updatedFilterValueJson->LogicUtils.setOptionArray("message_version", messageVersions) updatedFilterValueJson->deleteNestedKeys(["startTime", "endTime"]) updatedFilterValueJson } let renderValueInp = () => (_fieldsArray: array<ReactFinalForm.fieldRenderProps>) => { React.null } let compareToInput = (~comparisonKey) => { FormRenderer.makeMultiInputFieldInfoOld( ~label="", ~comboCustomInput=renderValueInp(), ~inputFields=[ FormRenderer.makeInputFieldInfo(~name=`${comparisonKey}`), FormRenderer.makeInputFieldInfo(~name=`extraKey`), ], (), ) } let (startTimeFilterKey, endTimeFilterKey) = ("startTime", "endTime") let initialFixedFilterFields = (~events=?) => { let events = switch events { | Some(fn) => fn | _ => () => () } 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, ~events, ), ~inputFields=[], ~isRequired=false, ), }: EntityType.initialFilters<'t> ), ( { localFilter: None, field: compareToInput(~comparisonKey=""), }: EntityType.initialFilters<'t> ), ] newArr }
2,693
9,601
hyperswitch-control-center
src/screens/NewAnalytics/NewAuthenticationAnalytics/NewAuthenticationAnalytics.res
.res
@react.component let make = () => { open APIUtils open LogicUtils open NewAuthenticationAnalyticsUtils open NewAuthenticationAnalyticsHelper let getURL = useGetURL() let fetchDetails = useGetMethod() let updateDetails = useUpdateMethod() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let (queryData, setQueryData) = React.useState(_ => Dict.make()->itemToObjMapperForQueryData) let (funnelData, setFunnelData) = React.useState(_ => Dict.make()->itemToObjMapperForFunnelData) let {updateExistingKeys, filterValueJson, filterValue} = React.useContext( FilterContext.filterContext, ) let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let title = "Authentication Analytics" let (filterDataJson, setFilterDataJson) = React.useState(_ => None) let (dimensions, setDimensions) = React.useState(_ => []) let mixpanelEvent = MixpanelHook.useSendEvent() React.useEffect(() => { if startTimeVal->LogicUtils.isNonEmptyString && endTimeVal->LogicUtils.isNonEmptyString { mixpanelEvent(~eventName="authentication_analytics_date_filter") } None }, (startTimeVal, endTimeVal)) let dateDropDownTriggerMixpanelCallback = () => { mixpanelEvent(~eventName="authentication_analytics_date_filter_opened") } let loadInfo = async () => { try { let infoUrl = getURL(~entityName=V1(ANALYTICS_AUTHENTICATION_V2), ~methodType=Get) let infoDetails = await fetchDetails(infoUrl) 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 tabNames = HSAnalyticsUtils.getStringListFromArrayDict(dimensions) let getFilters = async () => { try { let analyticsfilterUrl = getURL( ~entityName=V1(ANALYTICS_AUTHENTICATION_V2_FILTERS), ~methodType=Post, ) let filterBody = NewAnalyticsUtils.requestBody( ~startTime=startTimeVal, ~endTime=endTimeVal, ~groupByNames=Some(tabNames), ~metrics=[], ~filter=None, ~delta=Some(true), ) ->getArrayFromJson([]) ->getValueFromArray(0, JSON.Encode.null) let filterData = await updateDetails(analyticsfilterUrl, filterBody, Post) setFilterDataJson(_ => Some(filterData)) } catch { | _ => setFilterDataJson(_ => None) } } let getMetricsDetails = async () => { setScreenState(_ => PageLoaderWrapper.Loading) try { let metricsUrl = getURL(~entityName=V1(ANALYTICS_AUTHENTICATION_V2), ~methodType=Post) let metricsRequestBody = NewAnalyticsUtils.requestBody( ~startTime=startTimeVal, ~endTime=endTimeVal, ~filter=Some(getUpdatedFilterValueJson(filterValueJson)->JSON.Encode.object), ~mode=Some("ORDER"), ~metrics=[ #authentication_count, #authentication_attempt_count, #authentication_success_count, #challenge_flow_count, #frictionless_flow_count, #frictionless_success_count, #challenge_attempt_count, #challenge_success_count, ], ~delta=Some(true), ) let metricsQueryResponse = await updateDetails(metricsUrl, metricsRequestBody, Post) let queryDataArray = metricsQueryResponse ->getDictFromJsonObject ->getArrayFromDict("queryData", []) ->JSON.Encode.array ->getArrayDataFromJson(itemToObjMapperForQueryData) let valueOfQueryData = queryDataArray->getValueFromArray(0, defaultQueryData) setQueryData(_ => valueOfQueryData) let secondFunnelRequestBody = NewAnalyticsUtils.requestBody( ~startTime=startTimeVal, ~endTime=endTimeVal, ~filter=Some(getUpdatedFilterValueJson(filterValueJson)->JSON.Encode.object), ~metrics=[#authentication_funnel], ~delta=Some(true), ) let secondFunnelQueryResponse = await updateDetails(metricsUrl, secondFunnelRequestBody, Post) let authenticationInitiated = ( secondFunnelQueryResponse ->getDictFromJsonObject ->getArrayFromDict("queryData", []) ->JSON.Encode.array ->getArrayDataFromJson(itemToObjMapperForSecondFunnelData) ->getValueFromArray(0, defaultSecondFunnelData) ).authentication_funnel let updatedFilters = Js.Dict.map(t => t, getUpdatedFilterValueJson(filterValueJson)) updatedFilters->Dict.set( "authentication_status", ["success"->JSON.Encode.string, "failed"->JSON.Encode.string]->JSON.Encode.array, ) let thirdFunnelRequestBody = NewAnalyticsUtils.requestBody( ~startTime=startTimeVal, ~endTime=endTimeVal, ~filter=Some(updatedFilters->JSON.Encode.object), ~metrics=[#authentication_funnel], ~delta=Some(true), ) let thirdFunnelQueryResponse = await updateDetails(metricsUrl, thirdFunnelRequestBody, Post) let authenticationAttempted = ( thirdFunnelQueryResponse ->getDictFromJsonObject ->getArrayFromDict("queryData", []) ->JSON.Encode.array ->getArrayDataFromJson(itemToObjMapperForSecondFunnelData) ->getValueFromArray(0, defaultSecondFunnelData) ).authentication_funnel let funnelDict = Dict.make()->itemToObjMapperForFunnelData funnelDict.authentication_initiated = authenticationInitiated funnelDict.authentication_attemped = authenticationAttempted funnelDict.payments_requiring_3ds_2_authentication = valueOfQueryData.authentication_count funnelDict.authentication_successful = valueOfQueryData.authentication_success_count setFunnelData(_ => funnelDict) setScreenState(_ => PageLoaderWrapper.Success) } catch { | Exn.Error(e) => let err = Exn.message(e)->Option.getOr("Failed to Fetch!") setScreenState(_ => PageLoaderWrapper.Error(err)) } } let setInitialFilters = HSwitchRemoteFilter.useSetInitialFilters( ~updateExistingKeys, ~startTimeFilterKey, ~endTimeFilterKey, ~origin="analytics", (), ) React.useEffect(() => { setInitialFilters() loadInfo()->ignore None }, []) React.useEffect(() => { if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString { getFilters()->ignore } None }, (startTimeVal, endTimeVal, dimensions)) React.useEffect(() => { if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString { getMetricsDetails()->ignore } None }, (startTimeVal, endTimeVal, filterValue)) let topFilterUi = switch filterDataJson { | Some(filterData) => <div className="flex flex-row"> <DynamicFilter title="AuthenticationAnalyticsV2" initialFilters={HSAnalyticsUtils.initialFilterFields(filterData)} options=[] popupFilterFields={HSAnalyticsUtils.options(filterData)} initialFixedFilters={initialFixedFilterFields(~events=dateDropDownTriggerMixpanelCallback)} defaultFilterKeys=[startTimeFilterKey, endTimeFilterKey] tabNames key="0" updateUrlWith=updateExistingKeys filterFieldsPortalName={HSAnalyticsUtils.filterFieldsPortalName} showCustomFilter=false refreshFilters=false /> </div> | None => <div className="flex flex-row"> <DynamicFilter title="AuthenticationAnalyticsV2" initialFilters=[] options=[] popupFilterFields=[] initialFixedFilters={initialFixedFilterFields(~events=dateDropDownTriggerMixpanelCallback)} defaultFilterKeys=[startTimeFilterKey, endTimeFilterKey] tabNames key="0" updateUrlWith=updateExistingKeys filterFieldsPortalName={HSAnalyticsUtils.filterFieldsPortalName} showCustomFilter=false refreshFilters=false /> </div> } <PageLoaderWrapper screenState customUI={<HSAnalyticsUtils.NoData title />}> <div> <PageUtils.PageHeading title /> <div className="flex justify-end mr-4"> <GenerateReport entityName={V1(AUTHENTICATION_REPORT)} /> </div> <div className="-ml-1 sticky top-0 z-10 p-1 bg-hyperswitch_background/70 py-1 rounded-lg my-2"> {topFilterUi} </div> <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3"> {getMetricsData(queryData) ->Array.mapWithIndex((metric, index) => <Card key={index->Int.toString} title={metric.title} value={metric.value} valueType={metric.valueType} description={metric.tooltip_description} /> ) ->React.array} </div> <RenderIf condition={funnelData.authentication_initiated > 0 && funnelData.payments_requiring_3ds_2_authentication > 0 && funnelData.authentication_attemped > 0 && funnelData.authentication_successful > 0}> <div className="border border-gray-200 mt-5 rounded-lg"> <FunnelChart data={getFunnelChartData(funnelData)} metrics={metrics} moduleName="Authentication Funnel" description=Some("Breakdown of ThreeDS 2.0 Journey") /> </div> </RenderIf> <Insights /> </div> </PageLoaderWrapper> }
2,198
9,602
hyperswitch-control-center
src/screens/NewAnalytics/NewAuthenticationAnalytics/NewAuthenticationAnalyticsTypes.res
.res
type timeRange = { start_time: string, end_time: string, } type queryDataType = { authentication_count: int, authentication_attempt_count: int, authentication_success_count: int, challenge_flow_count: int, challenge_attempt_count: int, challenge_success_count: int, frictionless_flow_count: int, frictionless_success_count: int, error_message_count: int, authentication_funnel: int, authentication_status: option<string>, trans_status: option<string>, error_message: string, authentication_connector: option<string>, message_version: option<string>, time_range: timeRange, time_bucket: string, } type timeRangeType = { startTime: string, endTime: string, } type secondFunnelDataType = { authentication_count: int, authentication_attempt_count: int, authentication_success_count: int, challenge_flow_count: int, challenge_attempt_count: int, challenge_success_count: int, frictionless_flow_count: int, frictionless_success_count: int, error_message_count: option<int>, authentication_funnel: int, authentication_status: option<string>, trans_status: option<string>, error_message: option<string>, authentication_connector: option<string>, message_version: option<string>, time_range: timeRange, time_bucket: string, } type funnelDataType = { mutable payments_requiring_3ds_2_authentication: int, mutable authentication_initiated: int, mutable authentication_attemped: int, mutable authentication_successful: int, } type metaDataType = {total_error_message_count: int} type insightsDataType = { queryData: array<queryDataType>, metaData: array<metaDataType>, } type metricsData = { title: string, value: float, valueType: LogicUtilsTypes.valueType, tooltip_description: string, }
396
9,603
hyperswitch-control-center
src/screens/NewAnalytics/NewAuthenticationAnalytics/NewAuthenticationAnalyticsHelper.res
.res
open LogicUtils open LogicUtilsTypes module Card = { @react.component let make = (~title: string, ~description: string, ~value: float, ~valueType: valueType) => { let valueString = valueFormatter(value, valueType) <div className="bg-white border rounded-lg p-4"> <div className="flex flex-col justify-between items-start gap-3"> <div className="text-2xl font-bold text-gray-800"> {valueString->React.string} </div> <div className="flex flex-row items-center gap-4"> <div className="text-sm font-medium text-gray-500"> {title->React.string} </div> <div className="cursor-pointer"> <ToolTip description={description} toolTipPosition={ToolTip.Top} /> </div> </div> </div> </div> } } module Insights = { @react.component let make = () => { open APIUtils open NewAuthenticationAnalyticsUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let (data, setData) = React.useState(_ => Dict.make()->itemToObjMapperForInsightsData) let {filterValueJson} = React.useContext(FilterContext.filterContext) let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let loadTable = async () => { setScreenState(_ => PageLoaderWrapper.Loading) try { let insightsUrl = getURL(~entityName=V1(ANALYTICS_AUTHENTICATION_V2), ~methodType=Post) let insightsRequestBody = NewAnalyticsUtils.requestBody( ~startTime=startTimeVal, ~endTime=endTimeVal, ~groupByNames=Some(["error_message"]), ~metrics=[#authentication_error_message], ~filter=Some(getUpdatedFilterValueJson(filterValueJson)->JSON.Encode.object), ~delta=Some(true), ) let infoQueryResponse = await updateDetails(insightsUrl, insightsRequestBody, Post) setData(_ => infoQueryResponse->getDictFromJsonObject->itemToObjMapperForInsightsData) setScreenState(_ => PageLoaderWrapper.Success) } catch { | Exn.Error(e) => let err = Exn.message(e)->Option.getOr("Failed to Fetch!") setScreenState(_ => PageLoaderWrapper.Error(err)) } } React.useEffect(() => { if startTimeVal->String.length > 0 && endTimeVal->String.length > 0 { loadTable()->ignore } None }, (startTimeVal, endTimeVal, filterValueJson)) <PageLoaderWrapper screenState customLoader={<p className="mt-6 text-center text-sm text-jp-gray-900"> {"Crunching the latest data…"->React.string} </p>}> <RenderIf condition={data.queryData->Array.length > 0}> <div className="mt-6 border rounded-lg p-4"> <p className="text-base uppercase font-medium text-nd_gray-800"> {"Insights"->React.string} </p> { data.queryData->Array.sort((a, b) => { a.error_message_count <= b.error_message_count ? 1. : -1. }) let queryDataArray = data.queryData let metaDataObj = data.metaData->getValueFromArray(0, defaultMetaData) queryDataArray ->Array.mapWithIndex((item, index) => { let errorPercentage = item.error_message_count->Int.toFloat /. metaDataObj.total_error_message_count->Int.toFloat *. 100.0 let formattedPercentage = `${errorPercentage->Js.Float.toFixedWithPrecision( ~digits=2, )} %` let isLastItem = index == queryDataArray->Array.length - 1 let borderClass = isLastItem ? "border-none" : "border-b" <div key={index->Int.toString} className={`flex bg-white ${borderClass} items-center justify-between`}> <div className="py-4 font-medium text-gray-900 whitespace-pre-wrap flex items-center"> <span className="inline-flex justify-center items-center bg-blue-200 text-blue-500 text-xs font-medium mr-3 w-6 h-6 rounded"> {(index + 1)->Int.toString->React.string} </span> <span className="max-w-2xl"> {item.error_message->React.string} </span> </div> <div className="px-6 py-4 font-medium"> {formattedPercentage->React.string} </div> </div> }) ->React.array } </div> </RenderIf> </PageLoaderWrapper> } }
1,078
9,604
hyperswitch-control-center
src/screens/NewAnalytics/NewAnalyticsFilters/NewAnalyticsFiltersUtils.res
.res
open NewAnalyticsTypes let defaultCurrency = { label: "All Currencies (Converted to USD*)", value: (#all_currencies: defaultFilters :> string), } let getOptions = json => { open LogicUtils let currencies = [] json ->getDictFromJsonObject ->getArrayFromDict("queryData", []) ->Array.forEach(value => { let valueDict = value->getDictFromJsonObject let key = valueDict->getString("dimension", "") if key == (#currency: filters :> string) { let values = valueDict ->getArrayFromDict("values", []) ->Array.map(item => { item->JSON.Decode.string->Option.getOr("") }) ->Array.filter(isNonEmptyString) ->Array.map(item => {label: item->snakeToTitle, value: item}) let values = [defaultCurrency]->Array.concat(values) currencies->Array.pushMany(values) } }) currencies }
214
9,605
hyperswitch-control-center
src/screens/NewAnalytics/NewAnalyticsFilters/NewAnalyticsFilters.res
.res
open LogicUtils open APIUtils open NewAnalyticsFiltersUtils open NewAnalyticsFiltersHelper open NewAnalyticsTypes module RefundsFilter = { @react.component let make = (~filterValueJson, ~dimensions, ~loadFilters, ~screenState, ~updateFilterContext) => { let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let (currencOptions, setCurrencOptions) = React.useState(_ => []) let (selectedCurrency, setSelectedCurrency) = React.useState(_ => defaultCurrency) let filterValueModifier = dict => { dict->Dict.set((#currency: filters :> string), selectedCurrency.value) dict } let responseHandler = json => { let options = json->getOptions setCurrencOptions(_ => options) } React.useEffect(() => { if ( startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString && dimensions->Array.length > 0 ) { setSelectedCurrency(_ => defaultCurrency) loadFilters(responseHandler)->ignore } None }, (startTimeVal, endTimeVal, dimensions)) React.useEffect(() => { updateFilterContext(filterValueModifier) None }, [selectedCurrency.value]) let setOption = value => { setSelectedCurrency(_ => value) } <PageLoaderWrapper screenState customLoader={<FilterLoader />}> <NewAnalyticsHelper.CustomDropDown buttonText={selectedCurrency} options={currencOptions} setOption positionClass="left-0" /> </PageLoaderWrapper> } } module PaymentsFilter = { @react.component let make = (~filterValueJson, ~dimensions, ~loadFilters, ~screenState, ~updateFilterContext) => { let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let (currencOptions, setCurrencOptions) = React.useState(_ => []) let (selectedCurrency, setSelectedCurrency) = React.useState(_ => defaultCurrency) let filterValueModifier = dict => { dict->Dict.set((#currency: filters :> string), selectedCurrency.value) dict } let responseHandler = json => { let options = json->getOptions setCurrencOptions(_ => options) } React.useEffect(() => { if ( startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString && dimensions->Array.length > 0 ) { setSelectedCurrency(_ => defaultCurrency) loadFilters(responseHandler)->ignore } None }, (startTimeVal, endTimeVal, dimensions)) React.useEffect(() => { updateFilterContext(filterValueModifier) None }, [selectedCurrency.value]) let setOption = value => { setSelectedCurrency(_ => value) } <PageLoaderWrapper screenState customLoader={<FilterLoader />}> <NewAnalyticsHelper.CustomDropDown buttonText={selectedCurrency} options={currencOptions} setOption positionClass="left-0" /> </PageLoaderWrapper> } } @react.component let make = (~entityName, ~domain) => { let getURL = useGetURL() let fetchDetails = useGetMethod() let updateDetails = useUpdateMethod() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let {filterValueJson, updateExistingKeys, filterValue} = React.useContext( FilterContext.filterContext, ) let (dimensions, setDimensions) = React.useState(_ => []) let domainString = (domain: NewAnalyticsTypes.domain :> string) let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let loadInfo = async () => { try { let infoUrl = getURL(~entityName, ~methodType=Get, ~id=Some(domainString)) let infoDetails = await fetchDetails(infoUrl) setDimensions(_ => infoDetails->getDictFromJsonObject->getArrayFromDict("dimensions", [])) } catch { | _ => () } } let loadFilters = async responseHandler => { setScreenState(_ => PageLoaderWrapper.Loading) try { let url = getURL(~entityName=V1(ANALYTICS_FILTERS), ~methodType=Post, ~id=Some(domainString)) let body = { startTime: startTimeVal, endTime: endTimeVal, groupByNames: HSAnalyticsUtils.getStringListFromArrayDict(dimensions), source: "BATCH", } ->AnalyticsUtils.filterBody ->JSON.Encode.object let response = await updateDetails(url, body, Post) response->responseHandler setScreenState(_ => PageLoaderWrapper.Success) } catch { | _ => () } } let updateFilterContext = valueModifier => { let newValue = filterValue->Dict.copy newValue->valueModifier->updateExistingKeys } React.useEffect(() => { loadInfo()->ignore None }, []) switch domain { | #payments => <PaymentsFilter dimensions loadFilters screenState updateFilterContext filterValueJson /> | #refunds => <RefundsFilter dimensions loadFilters screenState updateFilterContext filterValueJson /> | _ => React.null } }
1,170
9,606
hyperswitch-control-center
src/screens/NewAnalytics/NewAnalyticsFilters/NewAnalyticsFiltersHelper.res
.res
module FilterLoader = { @react.component let make = () => { <div className="rounded-lg bg-white border px-10 py-2"> <div className="animate-spin"> <Icon name="spinner" size=20 /> </div> </div> } }
67
9,607
hyperswitch-control-center
src/screens/NewAnalytics/NewRefundsAnalytics/NewRefundsAnalyticsEntity.res
.res
open NewAnalyticsTypes // OverView section let overviewSectionEntity: moduleEntity = { requestBodyConfig: { delta: true, metrics: [], }, title: "OverView Section", domain: #refunds, } // Refunds Processed let refundsProcessedEntity: moduleEntity = { requestBodyConfig: { delta: false, metrics: [#sessionized_refund_processed_amount], }, title: "Refunds Processed", domain: #refunds, } let refundsProcessedChartEntity: chartEntity< LineGraphTypes.lineGraphPayload, LineGraphTypes.lineGraphOptions, JSON.t, > = { getObjects: RefundsProcessedUtils.refundsProcessedMapper, getChatOptions: LineGraphUtils.getLineGraphOptions, } let refundsProcessedTableEntity = { open RefundsProcessedUtils EntityType.makeEntity( ~uri=``, ~getObjects, ~dataKey="queryData", ~defaultColumns=visibleColumns, ~requiredSearchFieldsList=[], ~allColumns=visibleColumns, ~getCell, ~getHeading, ) } // Refunds Success Rate let refundsSuccessRateEntity: moduleEntity = { requestBodyConfig: { delta: false, metrics: [#sessionized_refund_success_rate], }, title: "Refunds Success Rate", domain: #refunds, } let refundsSuccessRateChartEntity: chartEntity< LineGraphTypes.lineGraphPayload, LineGraphTypes.lineGraphOptions, JSON.t, > = { getObjects: RefundsSuccessRateUtils.refundsSuccessRateMapper, getChatOptions: LineGraphUtils.getLineGraphOptions, } // Successful Refunds Distribution let successfulRefundsDistributionEntity: moduleEntity = { requestBodyConfig: { delta: false, groupBy: [#connector], metrics: [#sessionized_refund_count, #sessionized_refund_success_count], }, title: "Successful Refunds Distribution By Connector", domain: #refunds, } let successfulRefundsDistributionChartEntity: chartEntity< BarGraphTypes.barGraphPayload, BarGraphTypes.barGraphOptions, JSON.t, > = { getObjects: SuccessfulRefundsDistributionUtils.successfulRefundsDistributionMapper, getChatOptions: BarGraphUtils.getBarGraphOptions, } let successfulRefundsDistributionTableEntity = { open SuccessfulRefundsDistributionUtils EntityType.makeEntity( ~uri=``, ~getObjects, ~dataKey="queryData", ~defaultColumns=[], ~requiredSearchFieldsList=[], ~allColumns=[], ~getCell, ~getHeading, ) } // Failed Refunds Distribution let failedRefundsDistributionEntity: moduleEntity = { requestBodyConfig: { delta: false, groupBy: [#connector], metrics: [#sessionized_refund_count], }, title: "Failed Refunds Distribution By Connector", domain: #refunds, } let failedRefundsDistributionChartEntity: chartEntity< BarGraphTypes.barGraphPayload, BarGraphTypes.barGraphOptions, JSON.t, > = { getObjects: FailedRefundsDistributionUtils.failedRefundsDistributionMapper, getChatOptions: BarGraphUtils.getBarGraphOptions, } let failedRefundsDistributionTableEntity = { open FailedRefundsDistributionUtils EntityType.makeEntity( ~uri=``, ~getObjects, ~dataKey="queryData", ~defaultColumns=[], ~requiredSearchFieldsList=[], ~allColumns=[], ~getCell, ~getHeading, ) } // Refunds Failure Reasons let failureReasonsEntity: moduleEntity = { requestBodyConfig: { delta: false, metrics: [#sessionized_refund_error_message], groupBy: [#refund_error_message, #connector], }, title: "Failed Refund Error Reasons", domain: #refunds, } let failureReasonsTableEntity = { open FailureReasonsRefundsUtils EntityType.makeEntity( ~uri=``, ~getObjects, ~dataKey="queryData", ~defaultColumns=[], ~requiredSearchFieldsList=[], ~allColumns=[], ~getCell, ~getHeading, ) } // Refunds Reasons let refundsReasonsEntity: moduleEntity = { requestBodyConfig: { delta: false, metrics: [#sessionized_refund_reason], groupBy: [#refund_reason, #connector], }, title: "Refund Reasons", domain: #refunds, } let refundsReasonsTableEntity = { open RefundsReasonsUtils EntityType.makeEntity( ~uri=``, ~getObjects, ~dataKey="queryData", ~defaultColumns=[], ~requiredSearchFieldsList=[], ~allColumns=[], ~getCell, ~getHeading, ) }
1,039
9,608
hyperswitch-control-center
src/screens/NewAnalytics/NewRefundsAnalytics/NewRefundsAnalytics.res
.res
@react.component let make = () => { open NewRefundsAnalyticsEntity let {newAnalyticsFilters} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom <div className="flex flex-col gap-14 mt-5 pt-7"> <RenderIf condition={newAnalyticsFilters}> <div className="flex gap-2"> <NewAnalyticsFilters domain={#refunds} entityName={V1(ANALYTICS_REFUNDS)} /> </div> </RenderIf> <RefundsOverviewSection entity={overviewSectionEntity} /> <RefundsProcessed entity={refundsProcessedEntity} chartEntity={refundsProcessedChartEntity} /> <RefundsSuccessRate entity={refundsSuccessRateEntity} chartEntity={refundsSuccessRateChartEntity} /> <SuccessfulRefundsDistribution entity={successfulRefundsDistributionEntity} chartEntity={successfulRefundsDistributionChartEntity} /> <FailedRefundsDistribution entity={failedRefundsDistributionEntity} chartEntity={failedRefundsDistributionChartEntity} /> <RefundsReasons entity={refundsReasonsEntity} /> <FailureReasonsRefunds entity={failureReasonsEntity} /> </div> }
272
9,609
hyperswitch-control-center
src/screens/NewAnalytics/NewRefundsAnalytics/RefundsReasons/RefundsReasons.res
.res
open NewAnalyticsTypes open RefundsReasonsTypes open NewRefundsAnalyticsEntity open RefundsReasonsUtils open NewAnalyticsHelper module TableModule = { @react.component let make = (~data, ~className="") => { let (offset, setOffset) = React.useState(_ => 0) let defaultSort: Table.sortedObject = { key: "", order: Table.INC, } let visibleColumns = [Refund_Reason, Refund_Reason_Count, Refund_Reason_Count_Ratio, Connector] let tableData = getTableData(data) <div className> <LoadedTable visibleColumns title="Refunds Reasons" hideTitle=true actualData={tableData} entity=refundsReasonsTableEntity resultsPerPage=10 totalResults={tableData->Array.length} offset setOffset defaultSort currrentFetchCount={tableData->Array.length} tableLocalFilter=false tableheadingClass=tableBorderClass tableBorderClass ignoreHeaderBg=true tableDataBorderClass=tableBorderClass isAnalyticsModule=true /> </div> } } @react.component let make = (~entity: moduleEntity) => { open LogicUtils open APIUtils open NewAnalyticsUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let {filterValueJson} = React.useContext(FilterContext.filterContext) let (tableData, setTableData) = React.useState(_ => JSON.Encode.array([])) let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let currency = filterValueJson->getString((#currency: filters :> string), "") let getRefundsProcessed = async () => { setScreenState(_ => PageLoaderWrapper.Loading) try { let url = getURL( ~entityName=V1(ANALYTICS_REFUNDS), ~methodType=Post, ~id=Some((entity.domain: domain :> string)), ) let groupByNames = switch entity.requestBodyConfig.groupBy { | Some(dimentions) => dimentions ->Array.map(item => (item: dimension :> string)) ->Some | _ => None } let body = requestBody( ~startTime=startTimeVal, ~endTime=endTimeVal, ~delta=entity.requestBodyConfig.delta, ~metrics=entity.requestBodyConfig.metrics, ~groupByNames, ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let response = await updateDetails(url, body, Post) let metaData = response->getDictFromJsonObject->getArrayFromDict("metaData", []) let data = response ->getDictFromJsonObject ->getArrayFromDict("queryData", []) ->modifyQuery(metaData) if data->Array.length > 0 { setTableData(_ => data->JSON.Encode.array) setScreenState(_ => PageLoaderWrapper.Success) } else { setScreenState(_ => PageLoaderWrapper.Custom) } } catch { | _ => setScreenState(_ => PageLoaderWrapper.Custom) } } React.useEffect(() => { if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString { getRefundsProcessed()->ignore } None }, [startTimeVal, endTimeVal, currency]) <div> <ModuleHeader title={entity.title} /> <Card> <PageLoaderWrapper screenState customLoader={<Shimmer layoutId=entity.title />} customUI={<NoData />}> <TableModule data={tableData} className="ml-6 mr-5 mt-6 mb-5" /> </PageLoaderWrapper> </Card> </div> }
872
9,610
hyperswitch-control-center
src/screens/NewAnalytics/NewRefundsAnalytics/RefundsReasons/RefundsReasonsUtils.res
.res
open RefundsReasonsTypes open LogicUtils let getStringFromVariant = value => { switch value { | Refund_Reason => "refund_reason" | Refund_Reason_Count => "refund_reason_count" | Total_Refund_Reason_Count => "total_refund_reason_count" | Refund_Reason_Count_Ratio => "refund_reason_count_ratio" | Connector => "connector" } } let tableItemToObjMapper: Dict.t<JSON.t> => failreResonsObjectType = dict => { { refund_reason: dict->getString(Refund_Reason->getStringFromVariant, ""), refund_reason_count: dict->getInt(Refund_Reason_Count->getStringFromVariant, 0), total_refund_reason_count: dict->getInt(Total_Refund_Reason_Count->getStringFromVariant, 0), refund_reason_count_ratio: dict->getFloat(Refund_Reason_Count_Ratio->getStringFromVariant, 0.0), connector: dict->getString(Connector->getStringFromVariant, ""), } } let getObjects: JSON.t => array<failreResonsObjectType> = json => { json ->LogicUtils.getArrayFromJson([]) ->Array.map(item => { tableItemToObjMapper(item->getDictFromJsonObject) }) } let getHeading = colType => { switch colType { | Refund_Reason => Table.makeHeaderInfo( ~key=Refund_Reason->getStringFromVariant, ~title="Refund Reason", ~dataType=TextType, ) | Refund_Reason_Count => Table.makeHeaderInfo( ~key=Refund_Reason_Count->getStringFromVariant, ~title="Count", ~dataType=TextType, ) | Total_Refund_Reason_Count => Table.makeHeaderInfo( ~key=Total_Refund_Reason_Count->getStringFromVariant, ~title="", ~dataType=TextType, ) | Refund_Reason_Count_Ratio => Table.makeHeaderInfo( ~key=Refund_Reason_Count_Ratio->getStringFromVariant, ~title="Ratio", ~dataType=TextType, ) | Connector => Table.makeHeaderInfo( ~key=Connector->getStringFromVariant, ~title="Connector", ~dataType=TextType, ) } } let getCell = (obj, colType): Table.cell => { switch colType { | Refund_Reason => Text(obj.refund_reason) | Refund_Reason_Count => Text(obj.refund_reason_count->Int.toString) | Total_Refund_Reason_Count => Text(obj.total_refund_reason_count->Int.toString) | Refund_Reason_Count_Ratio => Text(obj.refund_reason_count_ratio->LogicUtils.valueFormatter(Rate)) | Connector => Text(obj.connector) } } let getTableData = json => { json->getArrayDataFromJson(tableItemToObjMapper)->Array.map(Nullable.make) } let modifyQuery = (queryData, metaData) => { let totalCount = switch metaData->Array.get(0) { | Some(val) => { let valueDict = val->getDictFromJsonObject let failure_reason_count = valueDict->getInt(Total_Refund_Reason_Count->getStringFromVariant, 0) failure_reason_count } | _ => 0 } let modifiedQuery = if totalCount > 0 { queryData->Array.map(query => { let valueDict = query->getDictFromJsonObject let failure_reason_count = valueDict->getInt(Refund_Reason_Count->getStringFromVariant, 0) let ratio = failure_reason_count->Int.toFloat /. totalCount->Int.toFloat *. 100.0 valueDict->Dict.set(Refund_Reason_Count_Ratio->getStringFromVariant, ratio->JSON.Encode.float) valueDict->JSON.Encode.object }) } else { queryData } modifiedQuery->Array.sort((queryA, queryB) => { let valueDictA = queryA->getDictFromJsonObject let valueDictB = queryB->getDictFromJsonObject let failure_reason_countA = valueDictA->getInt(Refund_Reason_Count->getStringFromVariant, 0) let failure_reason_countB = valueDictB->getInt(Refund_Reason_Count->getStringFromVariant, 0) compareLogic(failure_reason_countA, failure_reason_countB) }) modifiedQuery }
968
9,611
hyperswitch-control-center
src/screens/NewAnalytics/NewRefundsAnalytics/RefundsReasons/RefundsReasonsTypes.res
.res
type failreResonsColsTypes = | Refund_Reason | Refund_Reason_Count | Total_Refund_Reason_Count | Refund_Reason_Count_Ratio | Connector type failreResonsObjectType = { connector: string, refund_reason: string, refund_reason_count: int, total_refund_reason_count: int, refund_reason_count_ratio: float, }
90
9,612
hyperswitch-control-center
src/screens/NewAnalytics/NewRefundsAnalytics/SuccessfulRefundsDistribution/SuccessfulRefundsDistributionTypes.res
.res
type successfulRefundsDistributionTypes = | Refunds_Success_Rate | Refund_Count | Refund_Success_Count | Connector type successfulRefundsDistributionObject = { refund_count: int, refund_success_count: int, refunds_success_rate: float, connector: string, }
66
9,613
hyperswitch-control-center
src/screens/NewAnalytics/NewRefundsAnalytics/SuccessfulRefundsDistribution/SuccessfulRefundsDistributionUtils.res
.res
open NewAnalyticsUtils open LogicUtils open SuccessfulRefundsDistributionTypes let getStringFromVariant = value => { switch value { | Refunds_Success_Rate => "refunds_success_rate" | Refund_Count => "refund_count" | Refund_Success_Count => "refund_success_count" | Connector => "connector" } } let successfulRefundsDistributionMapper = ( ~params: NewAnalyticsTypes.getObjects<JSON.t>, ): BarGraphTypes.barGraphPayload => { open BarGraphTypes let {data, xKey, yKey} = params let categories = [data]->JSON.Encode.array->getCategories(0, yKey) let barGraphData = getBarGraphObj( ~array=data->getArrayFromJson([]), ~key=xKey, ~name=xKey->snakeToTitle, ~color=barGreenColor, ) let title = { text: "", } let tooltipFormatter = bargraphTooltipFormatter( ~title="Successful Refunds Distribution", ~metricType=Rate, ) { categories, data: [barGraphData], title, tooltipFormatter, } } let tableItemToObjMapper: Dict.t<JSON.t> => successfulRefundsDistributionObject = dict => { { refund_count: dict->getInt(Refund_Count->getStringFromVariant, 0), refund_success_count: dict->getInt(Refund_Success_Count->getStringFromVariant, 0), refunds_success_rate: dict->getFloat(Refunds_Success_Rate->getStringFromVariant, 0.0), connector: dict->getString(Connector->getStringFromVariant, ""), } } let getObjects: JSON.t => array<successfulRefundsDistributionObject> = json => { json ->LogicUtils.getArrayFromJson([]) ->Array.map(item => { tableItemToObjMapper(item->getDictFromJsonObject) }) } let getHeading = colType => { switch colType { | Refunds_Success_Rate => Table.makeHeaderInfo( ~key=Refunds_Success_Rate->getStringFromVariant, ~title="Refunds Success Rate", ~dataType=TextType, ) | Connector => Table.makeHeaderInfo( ~key=Connector->getStringFromVariant, ~title="Connector", ~dataType=TextType, ) | _ => Table.makeHeaderInfo(~key="", ~title="", ~dataType=TextType) } } let getCell = (obj, colType): Table.cell => { switch colType { | Refunds_Success_Rate => Text(obj.refunds_success_rate->valueFormatter(Rate)) | Connector => Text(obj.connector) | _ => Text("") } } let getTableData = json => { json->getArrayDataFromJson(tableItemToObjMapper)->Array.map(Nullable.make) } let modifyQuery = query => { query->Array.map(value => { let valueDict = value->getDictFromJsonObject let refund_count = valueDict->getInt(Refund_Count->getStringFromVariant, 0)->Int.toFloat let refund_success_count = valueDict->getInt(Refund_Success_Count->getStringFromVariant, 0)->Int.toFloat let refunds_success_rate = refund_success_count /. refund_count *. 100.0 valueDict->Dict.set( Refunds_Success_Rate->getStringFromVariant, refunds_success_rate->JSON.Encode.float, ) valueDict->JSON.Encode.object }) }
754
9,614
hyperswitch-control-center
src/screens/NewAnalytics/NewRefundsAnalytics/SuccessfulRefundsDistribution/SuccessfulRefundsDistribution.res
.res
open NewAnalyticsTypes open NewAnalyticsHelper open NewRefundsAnalyticsEntity open BarGraphTypes open SuccessfulRefundsDistributionUtils open SuccessfulRefundsDistributionTypes module TableModule = { @react.component let make = (~data, ~className="") => { let (offset, setOffset) = React.useState(_ => 0) let defaultSort: Table.sortedObject = { key: "", order: Table.INC, } let visibleColumns = [Connector, Refunds_Success_Rate] let tableData = getTableData(data) <div className> <LoadedTable visibleColumns title="Successful Refunds Distribution" hideTitle=true actualData={tableData} entity=successfulRefundsDistributionTableEntity resultsPerPage=10 totalResults={tableData->Array.length} offset setOffset defaultSort currrentFetchCount={tableData->Array.length} tableLocalFilter=false tableheadingClass=tableBorderClass tableBorderClass ignoreHeaderBg=true tableDataBorderClass=tableBorderClass isAnalyticsModule=true /> </div> } } module SuccessfulRefundsDistributionHeader = { @react.component let make = (~viewType, ~setViewType) => { let setViewType = value => { setViewType(_ => value) } <div className="w-full px-8 pt-3 pb-3 flex justify-end"> <div className="flex gap-2"> <TabSwitch viewType setViewType /> </div> </div> } } @react.component let make = ( ~entity: moduleEntity, ~chartEntity: chartEntity<barGraphPayload, barGraphOptions, JSON.t>, ) => { open LogicUtils open APIUtils open NewAnalyticsUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let {filterValueJson} = React.useContext(FilterContext.filterContext) let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let (refundsDistribution, setrefundsDistribution) = React.useState(_ => JSON.Encode.array([])) let (viewType, setViewType) = React.useState(_ => Graph) let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let currency = filterValueJson->getString((#currency: filters :> string), "") let getRefundsDistribution = async () => { setScreenState(_ => PageLoaderWrapper.Loading) try { let url = getURL( ~entityName=V1(ANALYTICS_REFUNDS), ~methodType=Post, ~id=Some((entity.domain: domain :> string)), ) let body = requestBody( ~startTime=startTimeVal, ~endTime=endTimeVal, ~delta=entity.requestBodyConfig.delta, ~metrics=entity.requestBodyConfig.metrics, ~groupByNames=[Connector->getStringFromVariant]->Some, ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let response = await updateDetails(url, body, Post) let responseData = response->getDictFromJsonObject->getArrayFromDict("queryData", [])->modifyQuery if responseData->Array.length > 0 { setrefundsDistribution(_ => responseData->JSON.Encode.array) setScreenState(_ => PageLoaderWrapper.Success) } else { setScreenState(_ => PageLoaderWrapper.Custom) } } catch { | _ => setScreenState(_ => PageLoaderWrapper.Custom) } } React.useEffect(() => { if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString { getRefundsDistribution()->ignore } None }, [startTimeVal, endTimeVal, currency]) let params = { data: refundsDistribution, xKey: Refunds_Success_Rate->getStringFromVariant, yKey: Connector->getStringFromVariant, } let options = chartEntity.getChatOptions(chartEntity.getObjects(~params)) <div> <ModuleHeader title={entity.title} /> <Card> <PageLoaderWrapper screenState customLoader={<Shimmer layoutId=entity.title />} customUI={<NoData />}> <SuccessfulRefundsDistributionHeader viewType setViewType /> <div className="mb-5"> {switch viewType { | Graph => <BarGraph options className="mr-3" /> | Table => <TableModule data={refundsDistribution} className="mx-7" /> }} </div> </PageLoaderWrapper> </Card> </div> }
1,028
9,615
hyperswitch-control-center
src/screens/NewAnalytics/NewRefundsAnalytics/RefundsOverviewSection/RefundsOverviewSectionUtils.res
.res
open RefundsOverviewSectionTypes let getStringFromVariant = value => { switch value { | Total_Refund_Processed_Amount => "total_refund_processed_amount" | Total_Refund_Success_Rate => "total_refund_success_rate" | Successful_Refund_Count => "successful_refund_count" | Failed_Refund_Count => "failed_refund_count" | Pending_Refund_Count => "pending_refund_count" } } let defaultValue = { total_refund_processed_amount: 0.0, total_refund_success_rate: 0.0, successful_refund_count: 0, failed_refund_count: 0, pending_refund_count: 0, } ->Identity.genericTypeToJson ->LogicUtils.getDictFromJsonObject let parseResponse = (response, key) => { open LogicUtils response ->getDictFromJsonObject ->getArrayFromDict(key, []) ->getValueFromArray(0, Dict.make()->JSON.Encode.object) ->getDictFromJsonObject } let getValueFromObj = (data, index, responseKey) => { open LogicUtils data ->getArrayFromJson([]) ->getValueFromArray(index, Dict.make()->JSON.Encode.object) ->getDictFromJsonObject ->getFloat(responseKey, 0.0) } let getKey = (id, ~currency="") => { open LogicUtils let key = switch id { | Total_Refund_Success_Rate => #total_refund_success_rate | Successful_Refund_Count => #successful_refund_count | Failed_Refund_Count => #failed_refund_count | Pending_Refund_Count => #pending_refund_count | Total_Refund_Processed_Amount => switch currency->getTypeValue { | #all_currencies => #total_refund_processed_amount_in_usd | _ => #total_refund_processed_amount } } (key: responseKeys :> string) } open NewAnalyticsTypes let setValue = (dict, ~data, ~ids: array<overviewColumns>, ~currency) => { open NewAnalyticsUtils open LogicUtils ids->Array.forEach(id => { let key = id->getStringFromVariant let value = switch id { | Total_Refund_Processed_Amount => data->getAmountValue(~id=id->getKey(~currency))->JSON.Encode.float | _ => data ->getFloat(id->getStringFromVariant, 0.0) ->JSON.Encode.float } dict->Dict.set(key, value) }) } let getInfo = (~responseKey: overviewColumns) => { switch responseKey { | Total_Refund_Success_Rate => { titleText: "Refund Success Rate", description: "Successful refunds divided by total refunds", valueType: Rate, } | Total_Refund_Processed_Amount => { titleText: "Total Refunds Processed", description: "Total refunds processed amount on all successful refunds", valueType: Amount, } | Successful_Refund_Count => { titleText: "Successful Refunds", description: "Total number of refunds that were successfully processed", valueType: Volume, } | Failed_Refund_Count => { titleText: "Failed Refunds", description: "Total number of refunds that were failed during processing", valueType: Volume, } | Pending_Refund_Count => { titleText: "Pending Refunds", description: "Total number of refunds currently in pending state", valueType: Volume, } } } let modifyStatusCountResponse = response => { open LogicUtils let queryData = response->getDictFromJsonObject->getArrayFromDict("queryData", []) let mapDict = Dict.make() queryData->Array.forEach(query => { let value = query->getDictFromJsonObject let status = value->getString("refund_status", "") let count = value->getInt("refund_count", 0) if status == (#success: status :> string) { mapDict->Dict.set(Successful_Refund_Count->getStringFromVariant, count->JSON.Encode.int) } if status == (#failure: status :> string) { mapDict->Dict.set(Failed_Refund_Count->getStringFromVariant, count->JSON.Encode.int) } if status == (#pending: status :> string) { mapDict->Dict.set(Pending_Refund_Count->getStringFromVariant, count->JSON.Encode.int) } }) mapDict }
980
9,616
hyperswitch-control-center
src/screens/NewAnalytics/NewRefundsAnalytics/RefundsOverviewSection/RefundsOverviewSection.res
.res
open NewAnalyticsTypes open RefundsOverviewSectionTypes open RefundsOverviewSectionUtils open NewAnalyticsHelper open LogicUtils open APIUtils open NewAnalyticsUtils @react.component let make = (~entity: moduleEntity) => { let getURL = useGetURL() let updateDetails = useUpdateMethod() let (data, setData) = React.useState(_ => []->JSON.Encode.array) let {filterValueJson} = React.useContext(FilterContext.filterContext) let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Success) let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let compareToStartTime = filterValueJson->getString("compareToStartTime", "") let compareToEndTime = filterValueJson->getString("compareToEndTime", "") let comparison = filterValueJson->getString("comparison", "")->DateRangeUtils.comparisonMapprer let currency = filterValueJson->getString((#currency: filters :> string), "") let getData = async () => { setScreenState(_ => PageLoaderWrapper.Loading) try { let primaryData = defaultValue->Dict.copy let secondaryData = defaultValue->Dict.copy let refundsUrl = getURL( ~entityName=V1(ANALYTICS_REFUNDS), ~methodType=Post, ~id=Some((#refunds: domain :> string)), ) let amountRateBodyRefunds = requestBody( ~startTime=startTimeVal, ~endTime=endTimeVal, ~delta=entity.requestBodyConfig.delta, ~metrics=[#sessionized_refund_processed_amount, #sessionized_refund_success_rate], ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let filters = Dict.make() filters->Dict.set( "refund_status", [#success, #failure, #pending] ->Array.map(item => { (item: status :> string)->JSON.Encode.string }) ->JSON.Encode.array, ) let statusCountBodyRefunds = requestBody( ~startTime=startTimeVal, ~endTime=endTimeVal, ~groupByNames=["refund_status"]->Some, ~filter=generateFilterObject( ~globalFilters=filterValueJson, ~localFilters=filters->Some, )->Some, ~delta=entity.requestBodyConfig.delta, ~metrics=[#sessionized_refund_count], ) let amountRateResponseRefunds = await updateDetails(refundsUrl, amountRateBodyRefunds, Post) let statusCountResponseRefunds = await updateDetails(refundsUrl, statusCountBodyRefunds, Post) let amountRateDataRefunds = amountRateResponseRefunds->parseResponse("metaData") let statusCountDataRefunds = statusCountResponseRefunds->modifyStatusCountResponse primaryData->setValue( ~data=amountRateDataRefunds, ~ids=[Total_Refund_Processed_Amount, Total_Refund_Success_Rate], ~currency, ) primaryData->setValue( ~data=statusCountDataRefunds, ~ids=[Successful_Refund_Count, Failed_Refund_Count, Pending_Refund_Count], ~currency, ) let secondaryAmountRateBodyRefunds = requestBody( ~startTime=compareToStartTime, ~endTime=compareToEndTime, ~delta=entity.requestBodyConfig.delta, ~metrics=[#sessionized_refund_processed_amount, #sessionized_refund_success_rate], ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let secondaryStatusCountBodyRefunds = requestBody( ~startTime=compareToStartTime, ~endTime=compareToEndTime, ~groupByNames=["refund_status"]->Some, ~filter=generateFilterObject( ~globalFilters=filterValueJson, ~localFilters=filters->Some, )->Some, ~delta=entity.requestBodyConfig.delta, ~metrics=[#sessionized_refund_count], ) let secondaryData = switch comparison { | EnableComparison => { let secondaryResponseRefunds = await updateDetails( refundsUrl, secondaryAmountRateBodyRefunds, Post, ) let secondaryStatusCountResponseRefunds = await updateDetails( refundsUrl, secondaryStatusCountBodyRefunds, Post, ) let secondaryAmountRateDataRefunds = secondaryResponseRefunds->parseResponse("metaData") let secondaryStatusCountDataRefunds = secondaryStatusCountResponseRefunds->modifyStatusCountResponse secondaryData->setValue( ~data=secondaryAmountRateDataRefunds, ~ids=[Total_Refund_Processed_Amount, Total_Refund_Success_Rate], ~currency, ) secondaryData->setValue( ~data=secondaryStatusCountDataRefunds, ~ids=[Successful_Refund_Count, Failed_Refund_Count, Pending_Refund_Count], ~currency, ) secondaryData->JSON.Encode.object } | DisableComparison => JSON.Encode.null } setData(_ => [primaryData->JSON.Encode.object, secondaryData]->JSON.Encode.array) setScreenState(_ => PageLoaderWrapper.Success) } catch { | _ => setScreenState(_ => PageLoaderWrapper.Success) } } React.useEffect(() => { if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString { getData()->ignore } None }, (startTimeVal, endTimeVal, compareToStartTime, compareToEndTime, comparison, currency)) <PageLoaderWrapper screenState customLoader={<Shimmer layoutId=entity.title />}> <div className="grid grid-cols-3 grid-rows-2 gap-6"> <OverViewStat data responseKey={Total_Refund_Success_Rate} getInfo getValueFromObj getStringFromVariant /> <OverViewStat data responseKey={Total_Refund_Processed_Amount} getInfo getValueFromObj getStringFromVariant /> <OverViewStat data responseKey={Successful_Refund_Count} getInfo getValueFromObj getStringFromVariant /> <OverViewStat data responseKey={Failed_Refund_Count} getInfo getValueFromObj getStringFromVariant /> <OverViewStat data responseKey={Pending_Refund_Count} getInfo getValueFromObj getStringFromVariant /> </div> </PageLoaderWrapper> }
1,373
9,617
hyperswitch-control-center
src/screens/NewAnalytics/NewRefundsAnalytics/RefundsOverviewSection/RefundsOverviewSectionTypes.res
.res
type overviewColumns = | Total_Refund_Processed_Amount | Total_Refund_Success_Rate | Successful_Refund_Count | Failed_Refund_Count | Pending_Refund_Count type responseKeys = [ | #total_refund_processed_amount | #total_refund_processed_amount_in_usd | #total_refund_success_rate | #successful_refund_count | #failed_refund_count | #pending_refund_count ] type dataObj = { total_refund_processed_amount: float, total_refund_success_rate: float, successful_refund_count: int, failed_refund_count: int, pending_refund_count: int, }
152
9,618
hyperswitch-control-center
src/screens/NewAnalytics/NewRefundsAnalytics/RefundsProcessed/RefundsProcessed.res
.res
open NewAnalyticsTypes open NewAnalyticsHelper open NewRefundsAnalyticsEntity open RefundsProcessedUtils open RefundsProcessedTypes module TableModule = { open LogicUtils @react.component let make = (~data, ~className="") => { let (offset, setOffset) = React.useState(_ => 0) let defaultSort: Table.sortedObject = { key: "", order: Table.INC, } let tableBorderClass = "border-collapse border border-jp-gray-940 border-solid border-2 border-opacity-30 dark:border-jp-gray-dark_table_border_color dark:border-opacity-30" let refundsProcessed = data ->Array.map(item => { item->getDictFromJsonObject->tableItemToObjMapper }) ->Array.map(Nullable.make) let defaultCols = [Refund_Processed_Amount, Refund_Processed_Count] let visibleColumns = defaultCols->Array.concat(visibleColumns) <div className> <LoadedTable visibleColumns title="Refunds Processed" hideTitle=true actualData={refundsProcessed} entity=refundsProcessedTableEntity resultsPerPage=10 totalResults={refundsProcessed->Array.length} offset setOffset defaultSort currrentFetchCount={refundsProcessed->Array.length} tableLocalFilter=false tableheadingClass=tableBorderClass tableBorderClass ignoreHeaderBg=true showSerialNumber=true tableDataBorderClass=tableBorderClass isAnalyticsModule=true /> </div> } } module RefundsProcessedHeader = { open NewAnalyticsUtils open LogicUtils open LogicUtilsTypes @react.component let make = ( ~data: JSON.t, ~viewType, ~setViewType, ~selectedMetric, ~setSelectedMetric, ~granularity, ~setGranularity, ~granularityOptions, ) => { let {filterValueJson} = React.useContext(FilterContext.filterContext) let comparison = filterValueJson->getString("comparison", "")->DateRangeUtils.comparisonMapprer let currency = filterValueJson->getString((#currency: filters :> string), "") let featureFlag = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let primaryValue = getMetaDataValue( ~data, ~index=0, ~key=selectedMetric.value->getMetaDataMapper(~currency), ) let secondaryValue = getMetaDataValue( ~data, ~index=1, ~key=selectedMetric.value->getMetaDataMapper(~currency), ) let (primaryValue, secondaryValue) = if ( selectedMetric.value->getMetaDataMapper(~currency)->isAmountMetric ) { (primaryValue /. 100.0, secondaryValue /. 100.0) } else { (primaryValue, secondaryValue) } let (value, direction) = calculatePercentageChange(~primaryValue, ~secondaryValue) let setViewType = value => { setViewType(_ => value) } let setSelectedMetric = value => { setSelectedMetric(_ => value) } let setGranularity = value => { setGranularity(_ => value) } let metricType = switch selectedMetric.value->getVariantValueFromString { | Refund_Processed_Amount => Amount | _ => Volume } <div className="w-full px-7 py-8 grid grid-cols-3"> <div className="flex gap-2 items-center"> <div className="text-fs-28 font-semibold"> {primaryValue->valueFormatter(metricType, ~currency)->React.string} </div> <RenderIf condition={comparison == EnableComparison}> <StatisticsCard value direction tooltipValue={secondaryValue->valueFormatter(metricType, ~currency)} /> </RenderIf> </div> <div className="flex justify-center"> <RenderIf condition={featureFlag.granularity}> <Tabs option={granularity} setOption={setGranularity} options={granularityOptions} showSingleTab=false /> </RenderIf> </div> <div className="flex gap-2 justify-end"> <CustomDropDown buttonText={selectedMetric} options={dropDownOptions} setOption={setSelectedMetric} /> <TabSwitch viewType setViewType /> </div> </div> } } @react.component let make = ( ~entity: moduleEntity, ~chartEntity: chartEntity< LineGraphTypes.lineGraphPayload, LineGraphTypes.lineGraphOptions, JSON.t, >, ) => { open LogicUtils open APIUtils open NewAnalyticsUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let isoStringToCustomTimeZone = TimeZoneHook.useIsoStringToCustomTimeZone() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let {filterValueJson} = React.useContext(FilterContext.filterContext) let (refundsProcessedData, setRefundsProcessedData) = React.useState(_ => JSON.Encode.array([])) let (refundsProcessedTableData, setRefundsProcessedTableData) = React.useState(_ => []) let (refundsProcessedMetaData, setRefundsProcessedMetaData) = React.useState(_ => JSON.Encode.array([]) ) let (selectedMetric, setSelectedMetric) = React.useState(_ => defaultMetric) let (viewType, setViewType) = React.useState(_ => Graph) let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let compareToStartTime = filterValueJson->getString("compareToStartTime", "") let compareToEndTime = filterValueJson->getString("compareToEndTime", "") let comparison = filterValueJson->getString("comparison", "")->DateRangeUtils.comparisonMapprer let currency = filterValueJson->getString((#currency: filters :> string), "") let featureFlag = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let granularityOptions = getGranularityOptions(~startTime=startTimeVal, ~endTime=endTimeVal) let defaulGranularity = getDefaultGranularity( ~startTime=startTimeVal, ~endTime=endTimeVal, ~granularity=featureFlag.granularity, ) let (granularity, setGranularity) = React.useState(_ => defaulGranularity) React.useEffect(() => { if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString { setGranularity(_ => defaulGranularity) } None }, (startTimeVal, endTimeVal)) let getRefundsProcessed = async () => { setScreenState(_ => PageLoaderWrapper.Loading) try { let url = getURL( ~entityName=V1(ANALYTICS_PAYMENTS), ~methodType=Post, ~id=Some((entity.domain: domain :> string)), ) let primaryBody = requestBody( ~startTime=startTimeVal, ~endTime=endTimeVal, ~delta=entity.requestBodyConfig.delta, ~metrics=entity.requestBodyConfig.metrics, ~granularity=granularity.value->Some, ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let secondaryBody = requestBody( ~startTime=compareToStartTime, ~endTime=compareToEndTime, ~delta=entity.requestBodyConfig.delta, ~metrics=entity.requestBodyConfig.metrics, ~granularity=granularity.value->Some, ~filter=generateFilterObject(~globalFilters=filterValueJson)->Some, ) let primaryResponse = await updateDetails(url, primaryBody, Post) let primaryData = primaryResponse ->getDictFromJsonObject ->getArrayFromDict("queryData", []) ->modifyQueryData(~currency) ->sortQueryDataByDate let primaryMetaData = primaryResponse->getDictFromJsonObject->getArrayFromDict("metaData", []) setRefundsProcessedTableData(_ => primaryData) let (secondaryMetaData, secondaryModifiedData) = switch comparison { | EnableComparison => { let secondaryResponse = await updateDetails(url, secondaryBody, Post) let secondaryData = secondaryResponse ->getDictFromJsonObject ->getArrayFromDict("queryData", []) ->modifyQueryData(~currency) let secondaryMetaData = secondaryResponse->getDictFromJsonObject->getArrayFromDict("metaData", []) let secondaryModifiedData = [secondaryData]->Array.map(data => { fillMissingDataPoints( ~data, ~startDate=compareToStartTime, ~endDate=compareToEndTime, ~timeKey="time_bucket", ~defaultValue={ "payment_count": 0, "payment_processed_amount": 0, "time_bucket": startTimeVal, }->Identity.genericTypeToJson, ~granularity=granularity.value, ~isoStringToCustomTimeZone, ~granularityEnabled=featureFlag.granularity, ) }) (secondaryMetaData, secondaryModifiedData) } | DisableComparison => ([], []) } if primaryData->Array.length > 0 { let primaryModifiedData = [primaryData]->Array.map(data => { fillMissingDataPoints( ~data, ~startDate=startTimeVal, ~endDate=endTimeVal, ~timeKey="time_bucket", ~defaultValue={ "payment_count": 0, "payment_processed_amount": 0, "time_bucket": startTimeVal, }->Identity.genericTypeToJson, ~isoStringToCustomTimeZone, ~granularity=granularity.value, ~granularityEnabled=featureFlag.granularity, ) }) setRefundsProcessedData(_ => primaryModifiedData->Array.concat(secondaryModifiedData)->Identity.genericTypeToJson ) setRefundsProcessedMetaData(_ => primaryMetaData->Array.concat(secondaryMetaData)->Identity.genericTypeToJson ) setScreenState(_ => PageLoaderWrapper.Success) } else { setScreenState(_ => PageLoaderWrapper.Custom) } } catch { | _ => setScreenState(_ => PageLoaderWrapper.Custom) } } React.useEffect(() => { if startTimeVal->isNonEmptyString && endTimeVal->isNonEmptyString { getRefundsProcessed()->ignore } None }, ( startTimeVal, endTimeVal, compareToStartTime, compareToEndTime, comparison, currency, granularity.value, )) let params = { data: refundsProcessedData, xKey: selectedMetric.value->getKeyForModule, yKey: Time_Bucket->getStringFromVariant, comparison, currency, } let options = chartEntity.getObjects(~params)->chartEntity.getChatOptions <div> <ModuleHeader title={entity.title} /> <Card> <PageLoaderWrapper screenState customLoader={<Shimmer layoutId=entity.title />} customUI={<NoData />}> // Need to modify <RefundsProcessedHeader data=refundsProcessedMetaData viewType setViewType selectedMetric setSelectedMetric granularity setGranularity granularityOptions /> <div className="mb-5"> {switch viewType { | Graph => <LineGraph options className="mr-3" /> | Table => <TableModule data={refundsProcessedTableData} className="mx-7" /> }} </div> </PageLoaderWrapper> </Card> </div> }
2,545
9,619
hyperswitch-control-center
src/screens/NewAnalytics/NewRefundsAnalytics/RefundsProcessed/RefundsProcessedUtils.res
.res
open RefundsProcessedTypes open NewAnalyticsUtils open LogicUtils let getStringFromVariant = value => { switch value { | Refund_Processed_Amount => "refund_processed_amount" | Refund_Processed_Count => "refund_processed_count" | Total_Refund_Processed_Amount => "total_refund_processed_amount" | Total_Refund_Processed_Count => "total_refund_processed_count" | Time_Bucket => "time_bucket" } } let getVariantValueFromString = value => { switch value { | "refund_processed_amount" | "refund_processed_amount_in_usd" => Refund_Processed_Amount | "refund_processed_count" => Refund_Processed_Count | "total_refund_processed_amount" | "total_refund_processed_amount_in_usd" => Total_Refund_Processed_Amount | "total_refund_processed_count" => Total_Refund_Processed_Count | "time_bucket" | _ => Time_Bucket } } let isAmountMetric = key => { switch key->getVariantValueFromString { | Refund_Processed_Amount | Total_Refund_Processed_Amount => true | _ => false } } let refundsProcessedMapper = ( ~params: NewAnalyticsTypes.getObjects<JSON.t>, ): LineGraphTypes.lineGraphPayload => { open LineGraphTypes let {data, xKey, yKey} = params let currency = params.currency->Option.getOr("") let comparison = switch params.comparison { | Some(val) => Some(val) | None => None } let primaryCategories = data->getCategories(0, yKey) let secondaryCategories = data->getCategories(1, yKey) let lineGraphData = data->getLineGraphData(~xKey, ~yKey, ~isAmount=xKey->isAmountMetric) open LogicUtilsTypes let metricType = switch xKey->getVariantValueFromString { | Refund_Processed_Amount => Amount | _ => Volume } let tooltipFormatter = tooltipFormatter( ~secondaryCategories, ~title="Refunds Processed", ~metricType, ~comparison, ~currency, ) { chartHeight: DefaultHeight, chartLeftSpacing: DefaultLeftSpacing, categories: primaryCategories, data: lineGraphData, title: { text: "", }, yAxisMaxValue: None, yAxisMinValue: Some(0), tooltipFormatter, yAxisFormatter: LineGraphUtils.lineGraphYAxisFormatter( ~statType=Default, ~currency="", ~suffix="", ), legend: { useHTML: true, labelFormatter: LineGraphUtils.valueFormatter, }, } } let visibleColumns = [Time_Bucket] let tableItemToObjMapper: Dict.t<JSON.t> => refundsProcessedObject = dict => { { refund_processed_amount: dict->getAmountValue( ~id=Refund_Processed_Amount->getStringFromVariant, ), refund_processed_count: dict->getInt(Refund_Processed_Count->getStringFromVariant, 0), total_refund_processed_amount: dict->getAmountValue( ~id=Total_Refund_Processed_Amount->getStringFromVariant, ), total_refund_processed_count: dict->getInt( Total_Refund_Processed_Count->getStringFromVariant, 0, ), time_bucket: dict->getString(Time_Bucket->getStringFromVariant, "NA"), } } let getObjects: JSON.t => array<refundsProcessedObject> = json => { json ->LogicUtils.getArrayFromJson([]) ->Array.map(item => { tableItemToObjMapper(item->getDictFromJsonObject) }) } let getHeading = colType => { switch colType { | Refund_Processed_Amount => Table.makeHeaderInfo( ~key=Refund_Processed_Amount->getStringFromVariant, ~title="Amount", ~dataType=TextType, ) | Refund_Processed_Count => Table.makeHeaderInfo( ~key=Refund_Processed_Count->getStringFromVariant, ~title="Count", ~dataType=TextType, ) | Total_Refund_Processed_Amount | Total_Refund_Processed_Count => Table.makeHeaderInfo(~key="", ~title="", ~dataType=TextType) | Time_Bucket => Table.makeHeaderInfo(~key=Time_Bucket->getStringFromVariant, ~title="Date", ~dataType=TextType) } } let getCell = (obj, colType): Table.cell => { switch colType { | Refund_Processed_Amount => Text(obj.refund_processed_amount->valueFormatter(Amount)) | Refund_Processed_Count => Text(obj.refund_processed_count->Int.toString) | Time_Bucket => Text(obj.time_bucket->formatDateValue(~includeYear=true)) | Total_Refund_Processed_Amount | Total_Refund_Processed_Count => Text("") } } open NewAnalyticsTypes let dropDownOptions = [ {label: "By Amount", value: Refund_Processed_Amount->getStringFromVariant}, {label: "By Count", value: Refund_Processed_Count->getStringFromVariant}, ] let tabs = [{label: "Daily", value: (#G_ONEDAY: granularity :> string)}] let defaultMetric = { label: "By Amount", value: Refund_Processed_Amount->getStringFromVariant, } let defaulGranularity = { label: "Daily", value: (#G_ONEDAY: granularity :> string), } let getKeyForModule = key => { key->getVariantValueFromString->getStringFromVariant } let getKey = (id, ~currency="") => { let key = switch id { | Refund_Processed_Count => #refund_processed_count | Total_Refund_Processed_Count => #total_refund_processed_count | Time_Bucket => #time_bucket | Refund_Processed_Amount => switch currency->getTypeValue { | #all_currencies => #refund_processed_amount_in_usd | _ => #refund_processed_amount } | Total_Refund_Processed_Amount => switch currency->getTypeValue { | #all_currencies => #total_refund_processed_amount_in_usd | _ => #total_refund_processed_amount } } (key: responseKeys :> string) } let getMetaDataMapper = (key, ~currency) => { let field = key->getVariantValueFromString switch field { | Refund_Processed_Amount => Total_Refund_Processed_Amount->getKey(~currency) | Refund_Processed_Count | _ => Total_Refund_Processed_Count->getStringFromVariant } } let modifyQueryData = (data, ~currency) => { let dataDict = Dict.make() data->Array.forEach(item => { let valueDict = item->getDictFromJsonObject let time = valueDict->getString(Time_Bucket->getStringFromVariant, "") let key = Refund_Processed_Count->getStringFromVariant let refundProcessedCount = valueDict->getInt(key, 0) let key = Refund_Processed_Amount->getKey(~currency) let refundProcessedAmount = valueDict->getFloat(key, 0.0) switch dataDict->Dict.get(time) { | Some(prevVal) => { let key = Refund_Processed_Count->getStringFromVariant let prevProcessedCount = prevVal->getInt(key, 0) let key = Refund_Processed_Amount->getStringFromVariant let prevProcessedAmount = prevVal->getFloat(key, 0.0) let totalRefundProcessedCount = refundProcessedCount + prevProcessedCount let totalRefundProcessedAmount = refundProcessedAmount +. prevProcessedAmount prevVal->Dict.set( Refund_Processed_Count->getStringFromVariant, totalRefundProcessedCount->JSON.Encode.int, ) prevVal->Dict.set( Refund_Processed_Amount->getStringFromVariant, totalRefundProcessedAmount->JSON.Encode.float, ) dataDict->Dict.set(time, prevVal) } | None => { valueDict->Dict.set( Refund_Processed_Count->getStringFromVariant, refundProcessedCount->JSON.Encode.int, ) valueDict->Dict.set( Refund_Processed_Amount->getStringFromVariant, refundProcessedAmount->JSON.Encode.float, ) dataDict->Dict.set(time, valueDict) } } }) dataDict->Dict.valuesToArray->Array.map(JSON.Encode.object) }
1,881
9,620