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/Recon/ReconScreens/ReconReports/ShowAllReports.res
.res
module ShowOrderDetails = { @react.component let make = ( ~data, ~getHeading, ~getCell, ~detailsFields, ~justifyClassName="justify-start", ~widthClass="w-full", ~bgColor="bg-white dark:bg-jp-gray-lightgray_background", ~isButtonEnabled=false, ~border="border border-jp-gray-940 border-opacity-75 dark:border-jp-gray-960", ~customFlex="flex-wrap", ~isHorizontal=false, ~isModal=false, ) => { <FormRenderer.DesktopRow itemWrapperClass=""> <div className={`grid grid-cols-2 dark:bg-jp-gray-lightgray_background dark:border-jp-gray-no_data_border `}> {detailsFields ->Array.mapWithIndex((colType, i) => { <div className=widthClass key={i->Int.toString}> <ReconReportsHelper.DisplayKeyValueParams heading={getHeading(colType)} value={getCell(data, colType)} customMoneyStyle="!font-normal !text-sm" labelMargin="!py-0 mt-2" overiddingHeadingStyles=" flex text-nd_gray-400 text-sm font-medium" isHorizontal /> </div> }) ->React.array} </div> </FormRenderer.DesktopRow> } } module OrderInfo = { @react.component let make = (~reportDetails, ~isModal) => { <div className="w-full mb-6 "> <ShowOrderDetails data=reportDetails getHeading={ReportsTableEntity.getHeading} getCell={ReportsTableEntity.getCell} detailsFields=[ OrderId, TransactionId, PaymentGateway, PaymentMethod, TxnAmount, SettlementAmount, TransactionDate, ] isButtonEnabled=true isModal /> </div> } } @react.component let make = (~isModal, ~setShowModal, ~selectedId) => { open ReconReportUtils let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let showToast = ToastState.useShowToast() let (reconReport, setReconReport) = React.useState(_ => Dict.make()->ReconReportUtils.getAllReportPayloadType ) let handleAboutPaymentsClick = () => { RescriptReactRouter.replace( GlobalVars.appendDashboardPath(~url=`/v2/recon/reports/${reconReport.transaction_id}`), ) } let fetchOrderDetails = async _ => { try { setScreenState(_ => Loading) setReconReport(_ => selectedId) setScreenState(_ => Success) } catch { | Exn.Error(e) => switch Exn.message(e) { | Some(message) => if message->String.includes("HE_02") { setScreenState(_ => Custom) } else { showToast(~message="Failed to Fetch!", ~toastType=ToastState.ToastError) setScreenState(_ => Error("Failed to Fetch!")) } | None => setScreenState(_ => Error("Failed to Fetch!")) } } } React.useEffect(() => { fetchOrderDetails()->ignore None }, []) switch reconReport.recon_status->getReconStatusTypeFromString { | Reconciled => <PageLoaderWrapper screenState customUI={<NoDataFound message="Payment does not exists in out record" renderType=NotFound />}> <div className="flex flex-col px-6"> <OrderInfo reportDetails=reconReport isModal /> </div> <Button text="OK" buttonType=Primary onClick={_ => setShowModal(_ => false)} customButtonStyle="w-full" /> </PageLoaderWrapper> | Unreconciled => <PageLoaderWrapper screenState customUI={<NoDataFound message="Payment does not exists in out record" renderType=NotFound />}> <div className="flex flex-col px-6"> <OrderInfo reportDetails=reconReport isModal /> <div className="gap-6 border-t"> <div className="flex flex-col gap-2 my-6"> <p className="text-nd_gray-400 text-sm font-medium"> {"Reason"->React.string} </p> <p className="text-base font-medium text-nd_gray-600"> {"Missing (Payment Gateway processed payment, but no bank settlement found."->React.string} </p> </div> </div> </div> <Button text="More Details " buttonType=Primary onClick={_ => handleAboutPaymentsClick()} customButtonStyle="w-full" /> </PageLoaderWrapper> | Missing => <PageLoaderWrapper screenState customUI={<NoDataFound message="Payment does not exists in out record" renderType=NotFound />}> <div className="flex flex-col px-6"> <OrderInfo reportDetails=reconReport isModal /> <div className="gap-6 border-t"> <div className="flex flex-col gap-2 my-6"> <p className="text-nd_gray-400 text-sm font-medium"> {"Reason"->React.string} </p> <p className="text-base font-medium text-nd_gray-600"> {"Missing (Payment Gateway processed payment, but no bank settlement found."->React.string} </p> </div> </div> </div> <Button text="OK" buttonType=Primary onClick={_ => setShowModal(_ => false)} customButtonStyle="w-full" /> </PageLoaderWrapper> } }
1,283
9,421
hyperswitch-control-center
src/Recon/ReconScreens/ReconReports/ReconReportUtils.res
.res
open ReportsTypes open LogicUtils let getArrayDictFromRes = res => { res->getDictFromJsonObject->getArrayFromDict("data", []) } let getSizeofRes = res => { res->getDictFromJsonObject->getInt("size", 0) } let getTabFromUrl = search => { switch search { | "tab=exceptions" => Exceptions | _ => All } } let getReconStatusTypeFromString = (reconStatus: string) => { switch reconStatus { | "Reconciled" => Reconciled | "Unreconciled" => Unreconciled | "Missing" => Missing | _ => Missing } } let getHeadersForCSV = () => { "Order ID,Transaction ID,Payment Gateway,Payment Method,Txn Amount,Settlement Amount,Recon Status,Transaction Date" } let generateDropdownOptionsCustomComponent: array<OMPSwitchTypes.ompListTypes> => array< SelectBox.dropdownOption, > = dropdownList => { let options: array<SelectBox.dropdownOption> = dropdownList->Array.map(( item ): SelectBox.dropdownOption => { let option: SelectBox.dropdownOption = { label: item.name, value: item.id, } option }) options } let getAllReportPayloadType = dict => { { transaction_id: dict->getString("transaction_id", ""), order_id: dict->getString("order_id", ""), payment_gateway: dict->getString("payment_gateway", ""), payment_method: dict->getString("payment_method", ""), txn_amount: dict->getFloat("txn_amount", 0.0), settlement_amount: dict->getFloat("settlement_amount", 0.0), recon_status: dict->getString("recon_status", ""), transaction_date: dict->getString("transaction_date", ""), } } let getArrayOfReportsListPayloadType = json => { json->Array.map(reportJson => { reportJson->getDictFromJsonObject->getAllReportPayloadType }) } let getReportsList: JSON.t => array<allReportPayload> = json => { LogicUtils.getArrayDataFromJson(json, getAllReportPayloadType) }
481
9,422
hyperswitch-control-center
src/Recon/ReconScreens/ReconReports/ReportsTableEntity.res
.res
open ReportsTypes open ReconReportUtils let defaultColumns: array<allColtype> = [ OrderId, TransactionId, PaymentGateway, PaymentMethod, TxnAmount, SettlementAmount, ReconStatus, TransactionDate, ] let allColumns: array<allColtype> = [ TransactionId, OrderId, PaymentGateway, PaymentMethod, TxnAmount, SettlementAmount, ReconStatus, TransactionDate, ] type reconStatus = | Reconciled | Unreconciled | Missing | None let getHeading = (colType: allColtype) => { switch colType { | TransactionId => Table.makeHeaderInfo(~key="transaction_id", ~title="Transaction ID") | OrderId => Table.makeHeaderInfo(~key="order_id", ~title="Order ID") | ReconStatus => Table.makeHeaderInfo(~key="recon_status", ~title="Recon Status") | PaymentGateway => Table.makeHeaderInfo(~key="payment_gateway", ~title="Payment Gateway") | PaymentMethod => Table.makeHeaderInfo(~key="payment_method", ~title="Payment Method") | SettlementAmount => Table.makeHeaderInfo(~key="settlement_amount", ~title="Settlement Amount ($)") | TxnAmount => Table.makeHeaderInfo(~key="txn_amount", ~title="Transaction Amount ($)") | TransactionDate => Table.makeHeaderInfo(~key="transaction_date", ~title="Transaction Date") } } let getCell = (report: allReportPayload, colType: allColtype): Table.cell => { switch colType { | TransactionId => Text(report.transaction_id) | OrderId => Text(report.order_id) | PaymentGateway => CustomCell( <HelperComponents.ConnectorCustomCell connectorName=report.payment_gateway connectorType={Processor} />, "", ) | PaymentMethod => Text(report.payment_method) | ReconStatus => Label({ title: {report.recon_status->String.toUpperCase}, color: switch report.recon_status->getReconStatusTypeFromString { | Reconciled => LabelGreen | Unreconciled => LabelRed | Missing => LabelOrange }, }) | TransactionDate => EllipsisText(report.transaction_date, "") | SettlementAmount => Text(Float.toString(report.settlement_amount)) | TxnAmount => Text(Float.toString(report.txn_amount)) } } let reportsEntity = (path: string, ~authorization: CommonAuthTypes.authorization) => { EntityType.makeEntity( ~uri=``, ~getObjects=getReportsList, ~defaultColumns, ~allColumns, ~getHeading, ~getCell, ~dataKey="reports", ~getShowLink={ connec => { GroupAccessUtils.linkForGetShowLinkViaAccess( ~url=GlobalVars.appendDashboardPath(~url=`/${path}/${connec.transaction_id}`), ~authorization, ) } }, ) }
646
9,423
hyperswitch-control-center
src/Recon/ReconScreens/ReconReports/ReconExceptionsUtils.res
.res
open ReportsTypes open LogicUtils let getExceptionMatrixPayloadType = dict => { { source: dict->getString("source", ""), order_id: dict->getString("order_id", ""), payment_gateway: dict->getString("payment_gateway", ""), settlement_date: dict->getString("settlement_date", ""), txn_amount: dict->getFloat("txn_amount", 0.0), fee_amount: dict->getFloat("fee_amount", 0.0), } } let getExceptionMatrixList: JSON.t => array<exceptionMatrixPayload> = json => { LogicUtils.getArrayDataFromJson(json, getExceptionMatrixPayloadType) } let getExceptionReportPayloadType = dict => { { transaction_id: dict->getString("transaction_id", ""), order_id: dict->getString("order_id", ""), payment_gateway: dict->getString("payment_gateway", ""), payment_method: dict->getString("payment_method", ""), recon_status: dict->getString("recon_status", ""), txn_amount: dict->getFloat("txn_amount", 0.0), exception_type: dict->getString("exception_type", ""), transaction_date: dict->getString("transaction_date", ""), settlement_amount: dict->getFloat("settlement_amount", 0.0), exception_matrix: dict ->getArrayFromDict("exception_matrix", []) ->JSON.Encode.array ->getExceptionMatrixList, } } let getExceptionReportsList: JSON.t => array<reportExceptionsPayload> = json => { LogicUtils.getArrayDataFromJson(json, getExceptionReportPayloadType) } let getArrayOfReportsListPayloadType = json => { json->Array.map(reportJson => { reportJson->getDictFromJsonObject->getExceptionReportPayloadType }) } let getArrayOfReportsAttemptsListPayloadType = json => { json->Array.map(reportJson => { reportJson->getDictFromJsonObject->getExceptionMatrixPayloadType }) } let getExceptionsStatusTypeFromString = string => { switch string { | "Amount Mismatch" => AmountMismatch | "Status Mismatch" => StatusMismatch | "Both" => Both | "Resolved" => Resolved | _ => Resolved } } let getExceptionStringFromStatus = status => { switch status { | AmountMismatch => "Amount Mismatch" | StatusMismatch => "Status Mismatch" | Both => "Amount & Status Mismatch" | Resolved => "Resolved" } } let validateNoteField = (values: JSON.t) => { let data = values->getDictFromJsonObject let errors = Dict.make() let errorMessage = if data->getString("note", "")->isEmptyString { "Note cannot be empty!" } else { "" } if errorMessage->isNonEmptyString { Dict.set(errors, "Error", errorMessage->JSON.Encode.string) } errors->JSON.Encode.object }
632
9,424
hyperswitch-control-center
src/Recon/ReconScreens/ReconReports/ReconReportsList.res
.res
@react.component let make = () => { open LogicUtils let (offset, setOffset) = React.useState(_ => 0) let {userHasAccess} = GroupACLHooks.useUserGroupACLHook() let (selectedId, setSelectedId) = React.useState(_ => Dict.make()->ReconReportUtils.getAllReportPayloadType ) let (showModal, setShowModal) = React.useState(_ => false) let (searchText, setSearchText) = React.useState(_ => "") let statusUI = ReportStatus.useGetAllReportStatus(selectedId) let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let fetchApi = AuthHooks.useApiFetcher() let (configuredReports, setConfiguredReports) = React.useState(_ => []) let (filteredReportsData, setFilteredReports) = React.useState(_ => []) let getReportsList = async _ => { try { setScreenState(_ => PageLoaderWrapper.Loading) let url = `${GlobalVars.getHostUrl}/test-data/recon/reconAllReports.json` let allReportsResponse = await fetchApi( url, ~method_=Get, ~xFeatureRoute=false, ~forceCookies=false, ) let response = await allReportsResponse->(res => res->Fetch.Response.json) let data = response->getDictFromJsonObject->getArrayFromDict("data", []) let reportsList = data->ReconReportUtils.getArrayOfReportsListPayloadType setConfiguredReports(_ => reportsList) setFilteredReports(_ => reportsList->Array.map(Nullable.make)) setScreenState(_ => Success) } catch { | _ => setScreenState(_ => PageLoaderWrapper.Error("Failed to fetch")) } } let modalHeading = { <div className="flex justify-between border-b"> <div className="flex gap-4 items-center m-8"> <p className="font-semibold text-nd_gray-600 text-lg leading-6"> {`Transaction ID: ${selectedId.transaction_id}`->React.string} </p> <div> {statusUI} </div> </div> <Icon name="modal-close-icon" className="cursor-pointer mr-4" size=30 onClick={_ => setShowModal(_ => false)} /> </div> } let filterLogic = ReactDebounce.useDebounced(ob => { let (searchText, arr) = ob let filteredList = if searchText->isNonEmptyString { arr->Array.filter((obj: Nullable.t<ReportsTypes.allReportPayload>) => { switch Nullable.toOption(obj) { | Some(obj) => isContainingStringLowercase(obj.transaction_id, searchText) || isContainingStringLowercase(obj.order_id, searchText) || isContainingStringLowercase(obj.recon_status, searchText) | None => false } }) } else { arr } setFilteredReports(_ => filteredList) }, ~wait=200) React.useEffect(() => { getReportsList()->ignore None }, []) <PageLoaderWrapper screenState> <div className="mt-9"> <RenderIf condition={configuredReports->Array.length === 0}> <div className="my-4"> <NoDataFound message={"No data available"} renderType={Painting} /> </div> </RenderIf> <Modal setShowModal showModal closeOnOutsideClick=true modalClass="flex flex-col w-1/3 h-screen float-right overflow-hidden !bg-white dark:!bg-jp-gray-lightgray_background" childClass="my-6 mx-2 h-full flex flex-col justify-between" customModalHeading=modalHeading> <ShowAllReports isModal=true setShowModal selectedId /> </Modal> <div className="flex flex-col mx-auto w-full h-full"> <RenderIf condition={configuredReports->Array.length > 0}> <LoadedTableWithCustomColumns title="All Reports" actualData={filteredReportsData} entity={ReportsTableEntity.reportsEntity( `v2/recon/reports`, ~authorization=userHasAccess(~groupAccess=UsersManage), )} resultsPerPage=10 filters={<TableSearchFilter data={configuredReports->Array.map(Nullable.make)} filterLogic placeholder="Search Transaction Id or Order Id or Recon Status" customSearchBarWrapperWidth="w-1/3" searchVal=searchText setSearchVal=setSearchText />} totalResults={filteredReportsData->Array.length} offset setOffset currrentFetchCount={configuredReports->Array.map(Nullable.make)->Array.length} customColumnMapper=TableAtoms.reconReportsDefaultCols defaultColumns={ReportsTableEntity.defaultColumns} showSerialNumberInCustomizeColumns=false sortingBasedOnDisabled=false hideTitle=true remoteSortEnabled=true onEntityClick={val => { setSelectedId(_ => val) setShowModal(_ => true) }} customizeColumnButtonIcon="nd-filter-horizontal" hideRightTitleElement=true showAutoScroll=true /> </RenderIf> </div> </div> </PageLoaderWrapper> }
1,152
9,425
hyperswitch-control-center
src/Recon/ReconScreens/ReconReports/ReconReportsHelper.res
.res
module DisplayKeyValueParams = { @react.component let make = ( ~showTitle: bool=true, ~heading: Table.header, ~value: Table.cell, ~isInHeader=false, ~isHorizontal=false, ~customMoneyStyle="", ~labelMargin="", ~customDateStyle="", ~wordBreak=true, ~overiddingHeadingStyles="", ~textColor="!font-medium !text-nd_gray-600", ) => { let marginClass = if labelMargin->LogicUtils.isEmptyString { "mt-4 py-0" } else { labelMargin } let fontClass = if isInHeader { "text-fs-20" } else { "text-fs-13" } let textColor = textColor->LogicUtils.isEmptyString ? "text-jp-gray-900 dark:text-white" : textColor let description = heading.description->Option.getOr("") { <AddDataAttributes attributes=[("data-label", heading.title)]> <div className={`flex ${isHorizontal ? "flex-row justify-between" : "flex-col gap-2"} py-4`}> <div className={`flex flex-row text-fs-11 ${isHorizontal ? "flex justify-start" : ""} text-jp-gray-900 text-opacity-50 dark:text-jp-gray-text_darktheme dark:text-opacity-50 `}> <div className={overiddingHeadingStyles}> {React.string(showTitle ? heading.title : " x")} </div> <RenderIf condition={description->LogicUtils.isNonEmptyString}> <div className="text-sm text-gray-500 mx-2 -mt-1 "> <ToolTip description={description} toolTipPosition={ToolTip.Top} /> </div> </RenderIf> </div> <div className={`${isHorizontal ? "flex justify-end" : ""} ${fontClass} font-semibold text-left ${textColor}`}> <Table.TableCell cell=value textAlign=Table.Left fontBold=true customMoneyStyle labelMargin=marginClass customDateStyle /> </div> </div> </AddDataAttributes> } } } module ListBaseComp = { @react.component let make = ( ~heading="", ~subHeading, ~arrow, ~showEditIcon=false, ~onEditClick=_ => (), ~isDarkBg=false, ~showDropdownArrow=true, ~placeHolder="Select Processor", ) => { let {globalUIConfig: {sidebarColor: {secondaryTextColor}}} = React.useContext( ThemeProvider.themeContext, ) let arrowClassName = isDarkBg ? `${arrow ? "rotate-180" : "-rotate-0"} transition duration-[250ms] opacity-70 ${secondaryTextColor}` : `${arrow ? "rotate-0" : "rotate-180"} transition duration-[250ms] opacity-70 ${secondaryTextColor}` let bgClass = subHeading->String.length > 0 ? "bg-white" : "bg-nd_gray-50" <div className={`flex flex-row cursor-pointer items-center px-4 gap-2 min-w-44 justify-between h-36-px ${bgClass} border rounded-lg border-nd_gray-100 shadow-sm`}> <div className="flex flex-row items-center gap-2"> <RenderIf condition={subHeading->String.length > 0}> <p className="overflow-scroll text-nowrap text-sm font-medium text-nd_gray-500 whitespace-pre "> {subHeading->React.string} </p> </RenderIf> <RenderIf condition={subHeading->String.length == 0}> <p className="overflow-scroll text-nowrap text-sm font-medium text-nd_gray-500 whitespace-pre "> {placeHolder->React.string} </p> </RenderIf> </div> <RenderIf condition={showDropdownArrow}> <Icon className={`${arrowClassName} ml-1`} name="nd-angle-down" size=12 /> </RenderIf> </div> } }
951
9,426
hyperswitch-control-center
src/Recon/ReconContainer/ReconOverviewContainer.res
.res
@react.component let make = (~showOnBoarding) => { open ReconOnboardingHelper { switch showOnBoarding { | false => <ReconOverviewContent /> | true => <ReconOnboardingLanding /> } } }
58
9,427
hyperswitch-control-center
src/Recon/ReconContainer/ReconConfigurationContainer.res
.res
@react.component let make = (~setShowOnBoarding, ~currentStep, ~setCurrentStep) => { <ReconConfiguration setShowOnBoarding currentStep setCurrentStep /> }
39
9,428
hyperswitch-control-center
src/Recon/ReconContainer/ReconReportsContainer.res
.res
@react.component let make = (~showOnBoarding) => { let url = RescriptReactRouter.useUrl() switch url.path->HSwitchUtils.urlPath { | list{"v2", "recon", "reports", ...remainingPath} => <EntityScaffold entityName="Payments" remainingPath access=Access renderList={() => <ReconReports showOnBoarding />} renderShow={(id, _) => <ShowReconExceptionReport showOnBoarding id />} /> | _ => React.null } }
123
9,429
hyperswitch-control-center
src/Recon/ReconApp/ReconApp.res
.res
@react.component let make = () => { open APIUtils open LogicUtils open ReconConfigurationUtils open VerticalStepIndicatorTypes open ReconConfigurationTypes open ReconOnboardingHelper let url = RescriptReactRouter.useUrl() let (showOnBoarding, setShowOnBoarding) = React.useState(_ => true) let (currentStep, setCurrentStep) = React.useState(() => { sectionId: (#orderDataConnection: sections :> string), subSectionId: None, }) let getURL = useGetURL() let fetchDetails = useGetMethod() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let getReconStatus = async () => { try { setScreenState(_ => PageLoaderWrapper.Loading) let url = getURL( ~entityName=V1(USERS), ~userType=#USER_DATA, ~methodType=Post, ~queryParamerters=Some("keys=ReconStatus"), ) let res = await fetchDetails(url) let reconStatusData = res ->getArrayDataFromJson(itemToObjMapperForReconStatusData) ->getValueFromArray(0, defaultReconStatusData) if reconStatusData.is_order_data_set && !reconStatusData.is_processor_data_set { setCurrentStep(_ => { sectionId: (#connectProcessors: sections :> string), subSectionId: None, }) } if reconStatusData.is_processor_data_set && reconStatusData.is_order_data_set { setCurrentStep(_ => {sectionId: (#finish: sections :> string), subSectionId: None}) setShowOnBoarding(_ => false) } setScreenState(_ => PageLoaderWrapper.Success) } catch { | Exn.Error(_e) => setScreenState(_ => PageLoaderWrapper.Error("Failed to fetch Recon Status!")) } } React.useEffect(() => { getReconStatus()->ignore None }, []) <PageLoaderWrapper screenState sectionHeight="!h-screen"> {switch url.path->HSwitchUtils.urlPath { | list{"v2", "recon"} => <ReconOnboardingLanding /> | list{"v2", "recon", "overview"} => <ReconOverviewContainer showOnBoarding /> | list{"v2", "recon", "configuration"} => <ReconConfigurationContainer setShowOnBoarding currentStep setCurrentStep /> | list{"v2", "recon", "reports", ..._} => <ReconReportsContainer showOnBoarding /> | _ => React.null }} </PageLoaderWrapper> }
587
9,430
hyperswitch-control-center
src/Recon/ReconApp/ReconSidebarValues.res
.res
open SidebarTypes let reconOnBoarding = { Link({ name: "Overview", link: `/v2/recon/overview`, access: Access, icon: "nd-overview", selectedIcon: "nd-overview-fill", }) } let reconReports = { Link({ name: "Reconciliation Report", link: `/v2/recon/reports`, access: Access, icon: "nd-reports", selectedIcon: "nd-reports-fill", }) } let reconSidebars = { let sidebar = [reconOnBoarding, reconReports] sidebar }
134
9,431
hyperswitch-control-center
src/libraries/XMLHttpRequest.res
.res
module XHR = { type t @send external addEventListener: (t, string, unit => unit) => unit = "addEventListener" @send external setRequestHeader: (t, string, string) => unit = "setRequestHeader" @send external open_: (t, string, string) => unit = "open" @send external send: (t, string) => unit = "send" @get external readyState: t => int = "readyState" @get external response: t => string = "response" @get external status: t => int = "status" @get external responseText: t => string = "responseText" } @new external new: unit => XHR.t = "XMLHttpRequest"
163
9,432
hyperswitch-control-center
src/libraries/SankeyHighcharts.res
.res
type title = {"text": string} type node = { id: string, color: string, name: string, dataLabels: {"x": int}, } type nodeColor = {color: string} type tooltiplink = { from: string, to: string, weight: float, total: float, fromColorIndex: string, toColorIndex: string, name: string, fromNode: nodeColor, toNode: nodeColor, } type tooltipNodeSeriesData = {total: float} type tooltipNodeSeries = {data: array<tooltipNodeSeriesData>} type tooltipnode = { id: string, name: string, sum: int, linksTo: array<tooltiplink>, linksFrom: array<tooltiplink>, key: string, fromNode: nodeColor, toNode: nodeColor, series: tooltipNodeSeries, color: string, level: int, } type series = { "keys": array<string>, "type": string, "name": string, "data": array<(string, string, int, int)>, "nodes": array<node>, "nodeWidth": int, "minLinkWidth": int, "dataLabels": JSON.t, "connectEnds": bool, } type credits = {"enabled": bool} type chart = {"height": int, "backgroundColor": string} type options = { title: title, series: array<JSON.t>, chart: chart, credits: credits, tooltip: { "shared": bool, "useHTML": bool, "headerFormat": string, "pointFormatter": option<Js_OO.Callback.arity1<tooltiplink => string>>, "nodeFormatter": option<Js_OO.Callback.arity1<tooltipnode => string>>, "valueDecimals": int, "backgroundColor": string, }, } type highcharts type highchartsSankey @module("highcharts") external highchartsModule: highcharts = "default" @module("highcharts/modules/sankey") external highchartsSankey: highcharts => unit = "default" module SankeyReact = { @module("highcharts-react-official") @react.component external make: (~highcharts: highcharts, ~options: JSON.t=?) => React.element = "default" } module SankeyReactJsonOption = { @module("highcharts-react-official") @react.component external make: (~highcharts: highcharts, ~options: JSON.t=?) => React.element = "default" }
567
9,433
hyperswitch-control-center
src/libraries/MixPanel.res
.res
type people = {set: JSON.t => unit} type mixpanel = {people: people} @module("mixpanel-browser") external mixpanel: mixpanel = "default" @send external distinctIdWrapper: (mixpanel, unit) => string = "get_distinct_id" let getDistinctId = distinctIdWrapper(mixpanel, _) @send external identifyWrapper: (mixpanel, string) => unit = "identify" let identify = identifyWrapper(mixpanel, ...) let wasInitialied = ref(false) @module("mixpanel-browser") external initOrig: (string, {..}) => unit = "init" let init = (str, obj) => { wasInitialied := true initOrig(str, obj) } @module("mixpanel-browser") external trackOrig: (string, {..}) => unit = "track" let track = (str, obj) => { if wasInitialied.contents { trackOrig(str, obj) } } @module("mixpanel-browser") external trackEventOrig: string => unit = "track"
227
9,434
hyperswitch-control-center
src/libraries/ApexCharts.res
.res
type zoom = {enabled: bool} type display = {show: bool} type padding = { left?: int, right?: int, top?: int, bottom?: int, } type chart = { height?: int, zoom?: zoom, toolbar?: display, padding?: padding, } type dataLabels = {enabled?: bool} type stroke = {curve: string} type title = { text?: string, align?: string, } type axis = { labels: display, axisBorder: display, axisTicks: display, } type tooltip = {enabled: bool} type options = { chart?: chart, dataLabels: dataLabels, stroke?: stroke, labels?: array<string>, title?: title, legend?: display, grid?: display, xaxis?: axis, yaxis?: axis, tooltip?: tooltip, colors?: array<string>, } type point = { x: float, y: float, } type objPoints = { name?: string, \"type"?: string, data: array<point>, } external userObjToJson: objPoints => JSON.t = "%identity" let objToJson = (arr: array<objPoints>) => { arr->Array.map(userObjToJson) } module ReactApexChart = { @module("react-apexcharts") @react.component external make: ( ~options: options, ~series: array<JSON.t>, ~\"type": string, ~height: string, ~width: string, ) => React.element = "default" }
341
9,435
hyperswitch-control-center
src/libraries/Highcharts.res
.res
type title = {"text": string, "style": JSON.t} type subtitle = {"text": string} type data_obj = {"name": string, "value": int, "color": string, "id": string} type new_series = {"type": string, "layoutAlgorithm": string, "data": array<data_obj>} type series = {"type": string, "name": string, "data": array<(float, float)>} type fillColorSeries = { linearGradient?: (int, int, int, int), color?: string, stops: ((int, string), (int, string)), } type tooltipPointer = {followPointer: bool} type dataLableStyle = { color: option<string>, fontSize: option<string>, } type yAxisRecord = {value: float, name: string} type dataLabels = { enabled: bool, formatter: option<Js_OO.Callback.arity1<JSON.t => string>>, useHTML: bool, } type seriesLine<'a> = { name: string, data: array<('a, Nullable.t<float>)>, color: option<string>, pointPlacement?: string, legendIndex: int, fillColor?: fillColorSeries, fillOpacity?: float, lineWidth?: int, opacity?: float, stroke?: string, tooltip?: tooltipPointer, fill?: string, connectNulls?: bool, dataLabels?: dataLabels, showInLegend?: bool, className?: string, } type series2<'t> = {"type": string, "name": string, "data": array<'t>} type series5 @obj external makeAreaSeries: (~\"type": string, ~something: bool) => series5 = "" @obj external makeSomethingSeries: (~\"type": string, ~something: (float, int, string)) => series5 = "" let x = makeAreaSeries(~\"type"="hello", ~something=false) let y = makeSomethingSeries(~\"type"="hello", ~something=(2., 1, "heloo")) type gridLine = {attr: JSON.t => unit} type pos type tick = { gridLine: gridLine, pos: float, } type eventYaxis = {ticks: Dict.t<gridLine>} type chartEventOnload = {yAxis: array<eventYaxis>} @val external thisChartEventOnLoad: chartEventOnload = "this" type chartEvent = {render: unit => unit} type chart = { "type": string, "zoomType": string, "margin": option<array<int>>, "backgroundColor": Nullable.t<string>, "height": option<int>, "width": option<int>, "events": option<chartEvent>, } type linearGradient = {"x1": int, "y1": int, "x2": int, "y2": int} type stop = (int, string) type fillColor = {"linearGradient": linearGradient, "stops": array<stop>} type hover = {"lineWidth": float} type states = {"hover": hover} type area = { "fillColor": option<fillColor>, "threshold": Nullable.t<string>, "lineWidth": float, "states": states, "pointStart": option<int>, "fillOpacity": float, } type boxplot = {"visible": bool} type marker = {"enabled": option<bool>, "radius": option<int>, "symbol": option<string>} type markerseries = {"marker": marker} type plotOptionshalo = {"size": option<int>} type plotOptionsHover = {"enabled": option<bool>, "halo": option<plotOptionshalo>} type plotOptionsStates = {"hover": option<plotOptionsHover>} type plotOptionsStateConfig = {"states": plotOptionsStates} type element = {visible: bool} type chartLegend = {series: array<element>} type legendItem = {chart: chartLegend} @send external show: element => unit = "show" @send external hide: element => unit = "hide" type eventClick = { "legendItemClick": option<Js_OO.Callback.arity2<(legendItem, ReactEvent.Keyboard.t) => unit>>, "mouseOver": option<string>, } // type plotOptionPoint = { // "mouseOver": option<Js_OO.Callback.arity1<JSON.t => unit>>, // "mouseOut": option<Js_OO.Callback.arity1<JSON.t => unit>>, // } // type pointEvents = {"events": option<plotOptionPoint>} type plotOptionSeries = { "marker": marker, "states": option<plotOptionsStates>, "events": option<eventClick>, // "point": option<pointEvents>, } // can be uncommented if require but pls check x asis does not breaks type xAxis = { // "visible": bool, // "labels": option<{ // "formatter": option<unit => string>, // "enabled": bool, // }>, "type": string, // "crosshair": option<JSON.t>, } type plotLinesLablesStyle = { color: option<string>, fontWeight: option<string>, background: option<string>, } type plotLineLable = {align: option<string>, style: option<plotLinesLablesStyle>} type plotLines = { label: option<plotLineLable>, dashStyle: option<string>, value: option<float>, width: option<int>, color: option<string>, } type chartCssObject = { color: string, backgroundColor: string, } // type yTickPostion type tickPositionerYaxis = {dataMin: float, dataMax: float} type yAxis = { "tickPositioner": option<Js_OO.Callback.arity1<tickPositionerYaxis => array<float>>>, "visible": bool, "title": JSON.t, "labels": option<{ "formatter": option<Js_OO.Callback.arity1<yAxisRecord => string>>, "enabled": bool, "useHTML": bool, }>, "plotLines": option<array<plotLines>>, // "opposite": option<bool>, // "gridLineColor": option<string>, // "gridLineDashStyle": option<string>, // "lineWidth": option<int>, } type seriesTooltip = { color: string, name: string, } type tooltipchart = { series: seriesTooltip, x: string, y: float, } type legendchart = {name: string} type credits = {"enabled": bool} type legendStyle = {"color": string, "cursor": string, "fontSize": string, "fontWeight": string} type tooltipPosition = { x: int, y: int, } type tooltipPoint = { plotX: int, plotY: int, } type a type b type plotPostion = {plotLeft: int, plotSizeX: int, plotSizeY: int, plotWidth: int, plotTop: int} type toltipPositioner = {chart: plotPostion} type tooltip = { "shared": bool, "enabled": bool, "useHTML": bool, "pointFormat": option<string>, "pointFormatter": option<Js_OO.Callback.arity1<tooltipchart => string>>, "headerFormat": option<string>, "hideDelay": int, "outside": bool, "positioner": option< Js_OO.Callback.arity4<(toltipPositioner, int, int, tooltipPoint) => tooltipPoint>, >, } type optionsJson<'a> = { chart: option<JSON.t>, title: JSON.t, series: array<'a>, plotOptions: option<JSON.t>, xAxis: JSON.t, yAxis: JSON.t, credits: credits, legend: JSON.t, tooltip?: JSON.t, } type options<'a> = { chart: option<JSON.t>, title: JSON.t, series: array<seriesLine<'a>>, plotOptions: option<JSON.t>, xAxis: JSON.t, yAxis: JSON.t, credits: credits, legend: JSON.t, tooltip?: JSON.t, } type chartType = { chartType: string, backgroundColor: Nullable.t<string>, } let makebarChart = ( ~chartType: string="", ~backgroundColor: Nullable.t<string>=Nullable.null, (), ) => { { "type": chartType, "backgroundColor": backgroundColor, } } type barChart = {"type": string, "backgroundColor": Nullable.t<string>} type barSeries = {data: array<JSON.t>} type xAxis1 = {"type": string} type barChartSeries = { color?: string, data: array<float>, name?: string, } type barChartTitle = {text: string} type barChartLabels = {formatter: option<Js_OO.Callback.arity1<yAxisRecord => string>>} type barLegend = {enabled: bool} type barChartXAxis = {categories: array<string>} type barChartYaxis = { gridLineColor: string, labels: option<barChartLabels>, title: barChartTitle, } //NOTE this can be removed type barOptions = { chart: barChart, title: JSON.t, series: array<barSeries>, xAxis: barChartXAxis, yAxis: barChartYaxis, credits: credits, legend: barLegend, } type highcharts @module("highcharts") @val external highcharts: highcharts = "default" @module("highcharts") external highchartsModule: highcharts = "default" @module("highcharts") @scope("default") external objectEach: (Dict.t<gridLine>, tick => unit) => unit = "objectEach" @module("highcharts/modules/treemap") external treeMapModule: highcharts => unit = "default" @module("highcharts/modules/sankey") external sankeyChartModule: highcharts => unit = "default" @module("highcharts/highcharts-more") external bubbleChartModule: highcharts => unit = "default" @module("highcharts/modules/sunburst") external sunburstChartModule: highcharts => unit = "default" // @module("highcharts-react-official") // external make: (~highcharts: highcharts, ~options: options=?) => React.element = "HighchartsReact" type afterChartCreated // type chartCallback = {afterChartCreated: afterChartCreated} type ticks type callBackYaxis // = {ticks: ticks} type chartCallback = {yAxis: array<JSON.t>} module HighchartsReact = { @module("highcharts-react-official") @react.component external make: ( ~highcharts: highcharts, ~options: options<'a>=?, ~callback: Js_OO.Callback.arity2<('a, chartCallback) => unit>=?, ) => React.element = "default" } module HighchartsReactDataJson = { @module("highcharts-react-official") @react.component external make: ( ~highcharts: highcharts, ~options: optionsJson<'a>=?, ~callback: Js_OO.Callback.arity2<('a, chartCallback) => unit>=?, ) => React.element = "default" } module BarChart = { @module("highcharts-react-official") @react.component external make: (~highcharts: highcharts, ~options: JSON.t=?) => React.element = "default" } module PieChart = { @module("highcharts-react-official") @react.component external make: (~highcharts: highcharts, ~options: JSON.t=?) => React.element = "default" } module Chart = { @module("highcharts-react-official") @react.component external make: (~highcharts: highcharts, ~options: JSON.t=?) => React.element = "default" } module DonutChart = { @module("highcharts-react-official") @react.component external make: (~highcharts: highcharts, ~options: JSON.t=?) => React.element = "default" }
2,618
9,436
hyperswitch-control-center
src/libraries/HeadlessUI.res
.res
module Transition = { @module("@headlessui/react") @react.component external make: ( ~\"as": string, ~show: bool=?, ~appear: bool=?, ~unmount: bool=?, ~enter: string=?, ~enterFrom: string=?, ~enterTo: string=?, ~leave: string=?, ~leaveFrom: string=?, ~leaveTo: string=?, ~beforeEnter: unit => unit=?, ~afterEnter: unit => unit=?, ~beforeLeave: unit => unit=?, ~afterLeave: unit => unit=?, ~className: string=?, ~children: React.element=?, ) => React.element = "Transition" module Child = { @module("@headlessui/react") @scope("Transition") @react.component external make: ( ~\"as": string=?, ~appear: bool=?, ~unmount: bool=?, ~enter: string=?, ~enterFrom: string=?, ~enterTo: string=?, ~leave: string=?, ~leaveFrom: string=?, ~leaveTo: string=?, ~beforeEnter: unit => unit=?, ~afterEnter: unit => unit=?, ~beforeLeave: unit => unit=?, ~afterLeave: unit => unit=?, ~children: React.element=?, ) => React.element = "Child" } } //--------------------------------------- module RadioGroup = { type optionRenderArgs = {"active": bool, "checked": bool, "disabled": bool} @module("@headlessui/react") @react.component external make: ( ~\"as": string=?, ~value: 't, ~className: string=?, ~onChange: 't => unit, ~disabled: bool=?, ~children: React.element=?, ) => React.element = "RadioGroup" module Option = { @module("@headlessui/react") @scope("RadioGroup") @react.component external make: ( ~\"as": string=?, ~value: 't, ~disabled: bool=?, ~className: string=?, ~children: optionRenderArgs => React.element, ) => React.element = "Option" } module Label = { @module("@headlessui/react") @scope("RadioGroup") @react.component external make: ( ~\"as": string=?, ~className: string=?, ~children: React.element=?, ) => React.element = "Label" } module Description = { @module("@headlessui/react") @scope("RadioGroup") @react.component external make: ( ~\"as": string=?, ~className: string=?, ~children: React.element=?, ) => React.element = "Description" } } //---------------------------------------------------- module Popover = { type popoverRenderArgs = {"open": bool} type overlayRenderArgs = {"open": bool} type buttonRenderArgs = {"open": bool} type panelRenderArgs = {"open": bool, "close": unit => unit} @module("@headlessui/react") @react.component external make: ( ~\"as": string=?, ~className: string=?, ~children: popoverRenderArgs => React.element=?, ) => React.element = "Popover" module Overlay = { @module("@headlessui/react") @scope("Popover") @react.component external make: ( ~\"as": string=?, ~className: string=?, ~children: overlayRenderArgs => React.element=?, ) => React.element = "Overlay" } module Button = { @module("@headlessui/react") @scope("Popover") @react.component external make: ( ~\"as": string=?, ~className: string=?, ~children: buttonRenderArgs => React.element=?, ) => React.element = "Button" } module Panel = { @module("@headlessui/react") @scope("Popover") @react.component external make: ( ~\"as": string=?, ~focus: bool=?, ~static: bool=?, ~unmount: bool=?, ~className: string=?, ~children: panelRenderArgs => React.element=?, ) => React.element = "Panel" } module Group = { @module("@headlessui/react") @scope("Popover") @react.component external make: (~\"as": string=?, ~className: string=?) => React.element = "Group" } } //--------------------------------------------------------- module Dialog = { type dialogRenderArgs = {"open": bool} type overlayRenderArgs = {"open": bool} type titleRenderArgs = {"open": bool} type descriptionRenderArgs = {"open": bool} @module("@headlessui/react") @react.component external make: ( ~\"open": bool=?, ~onClose: unit => unit=?, ~initialFocus: React.ref<unit>=?, ~\"as": string=?, ~static: bool=?, ~unmount: bool=?, ~className: string=?, ~children: dialogRenderArgs => React.element, ) => React.element = "Dialog" module Overlay = { @module("@headlessui/react") @scope("Dialog") @react.component external make: ( ~\"as": string=?, ~className: string=?, ) => // ~children: overlayRenderArgs => React.element, React.element = "Overlay" } module Title = { @module("@headlessui/react") @scope("Dialog") @react.component external make: ( ~\"as": string=?, ~className: string=?, ~children: titleRenderArgs => React.element, ) => React.element = "Title" } module Description = { @module("@headlessui/react") @scope("Dialog") @react.component external make: ( ~\"as": string=?, ~className: string=?, ~children: descriptionRenderArgs => React.element, ) => React.element = "Description" } } //-------------------------------------------- module Disclosure = { type disclosureRenderArgs = {"open": bool} type panelRenderArgs = {"open": bool} type buttonRenderArgs = {"open": bool} @module("@headlessui/react") @react.component external make: ( ~\"as": string=?, ~defaultOpen: bool=?, ~className: string=?, ~children: disclosureRenderArgs => React.element, ) => React.element = "Disclosure" module Panel = { @module("@headlessui/react") @scope("Disclosure") @react.component external make: ( ~\"as": string=?, ~static: bool=?, ~unmount: bool=?, ~className: string=?, ~children: panelRenderArgs => React.element, ) => React.element = "Panel" } module Button = { @module("@headlessui/react") @scope("Disclosure") @react.component external make: ( ~\"as": string=?, ~className: string=?, ~children: buttonRenderArgs => React.element, ) => React.element = "Button" } } //---------------------------------------------------- module Switch = { type switchRenderArgs = {"checked": bool} @module("@headlessui/react") @react.component external make: ( ~\"as": React.element=?, ~checked: bool, ~onChange: bool => unit, ~className: string=?, ~children: switchRenderArgs => React.element=?, ) => React.element = "Switch" module Label = { @module("@headlessui/react") @react.component external make: ( ~\"as": React.element=?, ~passive: bool=?, ~className: string, ) => React.element = "Label" } module Description = { @module("@headlessui/react") @react.component external make: (~\"as": React.element=?, ~className: string) => React.element = "Description" } module Group = { @module("@headlessui/react") @react.component external make: (~\"as": React.element=?, ~className: string) => React.element = "Group" } } //-------------------------------------------------------- module Listbox = { type listboxRenderArgs = {"open": bool, "disabled": bool} type buttonRenderArgs = {"open": bool, "disabled": bool} type labelRenderArgs = {"open": bool, "disabled": bool} type optionsRenderArgs = {"open": bool} type optionRenderArgs = {"active": bool, "selected": bool, "disabled": bool} @module("@headlessui/react") @react.component external make: ( ~\"as": React.element=?, ~disabled: bool=?, ~value: 't=?, ~className: string=?, ~onChange: 't => unit=?, ~children: listboxRenderArgs => React.element=?, ) => React.element = "Listbox" module Button = { @module("@headlessui/react") @scope("Listbox") @react.component external make: ( ~\"as": React.element=?, ~className: string=?, ~children: buttonRenderArgs => React.element=?, ) => React.element = "Button" } module Label = { @module("@headlessui/react") @scope("Listbox") @react.component external make: ( ~\"as": React.element=?, ~className: string=?, ~children: buttonRenderArgs => React.element=?, ) => React.element = "Label" } module Options = { @module("@headlessui/react") @scope("Listbox") @react.component external make: ( ~\"as": React.element=?, ~static: bool=?, ~unmount: bool=?, ~className: string=?, ~children: optionsRenderArgs => React.element=?, ) => React.element = "Options" } module Option = { @module("@headlessui/react") @scope("Listbox") @react.component external make: ( ~\"as": React.element=?, ~value: 't=?, ~disabled: bool=?, ~className: string=?, ~onClick: unit => unit=?, //added externally ~children: optionRenderArgs => React.element=?, ) => React.element = "Option" } } module Combobox = { type comboboxRenderArgs = {"open": bool, "disabled": bool} type buttonRenderArgs = {"open": bool, "disabled": bool} type labelRenderArgs = {"open": bool, "disabled": bool} type optionsRenderArgs = {"open": bool} type optionRenderArgs = {"active": bool, "selected": bool, "disabled": bool} @module("@headlessui/react") @react.component external make: ( ~\"as": React.element=?, ~disabled: bool=?, ~value: 't=?, ~className: string=?, ~onChange: 't => unit=?, ~children: comboboxRenderArgs => React.element=?, ) => React.element = "Combobox" module Input = { @module("@headlessui/react") @scope("Combobox") @react.component external make: ( ~\"as": string=?, ~className: string=?, ~autoFocus: bool=?, ~autoComplete: string=?, ~placeholder: string=?, ~displayValue: _ => string=?, ~onChange: 't => unit=?, ) => React.element = "Input" } module Button = { @module("@headlessui/react") @scope("Combobox") @react.component external make: ( ~\"as": React.element=?, ~className: string=?, ~children: buttonRenderArgs => React.element=?, ) => React.element = "Button" } module Label = { @module("@headlessui/react") @scope("Combobox") @react.component external make: ( ~\"as": React.element=?, ~className: string=?, ~children: buttonRenderArgs => React.element=?, ) => React.element = "Label" } module Options = { @module("@headlessui/react") @scope("Combobox") @react.component external make: ( ~\"as": React.element=?, ~static: bool=?, ~unmount: bool=?, ~className: string=?, ~children: optionsRenderArgs => React.element=?, ) => React.element = "Options" } module Option = { @module("@headlessui/react") @scope("Combobox") @react.component external make: ( ~\"as": React.element=?, ~value: 't=?, ~disabled: bool=?, ~className: string=?, ~onClick: unit => unit=?, ~children: optionRenderArgs => React.element=?, ) => React.element = "Option" } } //---------------------------------------------------- module Menu = { type buttonRenderArgs = {"open": bool} type menuRenderArgs = {"open": bool} type itemsRenderArgs = {"open": bool} type itemRenderArgs = {"active": bool, "disabled": bool} @module("@headlessui/react") @react.component external make: ( ~\"as": string=?, ~className: string=?, ~children: menuRenderArgs => React.element=?, ) => React.element = "Menu" module Items = { @module("@headlessui/react") @scope("Menu") @react.component external make: ( ~\"as": string=?, ~static: bool=?, ~unmount: bool=?, ~className: string=?, ~children: itemsRenderArgs => React.element=?, ) => React.element = "Items" } module Item = { @module("@headlessui/react") @scope("Menu") @react.component external make: ( ~\"as": string=?, ~className: string=?, ~disabled: bool=?, ~children: itemRenderArgs => React.element=?, ) => React.element = "Item" } module Button = { @module("@headlessui/react") @scope("Menu") @react.component external make: ( ~\"as": string=?, ~className: string=?, ~children: buttonRenderArgs => React.element=?, ) => React.element = "Button" } } type dropdownPosition = Left | Right | Top type value = String(string) | Array(array<string>) module SelectBoxHeadlessUI = { @react.component let make = ( ~value: value=String(""), ~setValue, ~options: array<SelectBox.dropdownOption>, ~children, ~dropdownPosition=Left, ~className="", ~deSelectAllowed=true, ~dropdownWidth="w-52", ) => { let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext) let transformedOptions = SelectBox.useTransformed(options) let dropdownPositionClass = switch dropdownPosition { | Left => "right-0" | Right => "left-0" | Top => "bottom-12" } let isMultiSelect = switch value { | String(_) => false | Array(_) => true } <div className="text-left"> <Menu \"as"="div" className="relative inline-block text-left"> {_ => <div> <Menu.Button className> {_ => children} </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 z-10 ${dropdownPositionClass} ${dropdownWidth} max-h-[225px] overflow-auto mt-2 p-1 origin-top-right bg-white dark:bg-jp-gray-950 rounded-md shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none`}> {_ => transformedOptions ->Array.mapWithIndex((option, index) => { let selected = switch value { | String(v) => v === option.value | Array(arr) => arr->Array.includes(option.value) } <Menu.Item key={index->Int.toString}> {props => <div onClick={ev => { if isMultiSelect { ev->ReactEvent.Mouse.stopPropagation ev->ReactEvent.Mouse.preventDefault } setValue(option.value) }} className={`group flex flex-row items-center justify-between rounded-md w-full p-2 text-sm cursor-pointer ${props["active"] ? "bg-gray-100 dark:bg-gray-700" : ""}`}> <div className="flex flex-row items-center gap-2"> {switch option.icon { | FontAwesome(iconName) => <Icon className="align-middle" size=12 name=iconName /> | CustomIcon(element) => element | Euler(iconName) => <Icon className="align-middle" size=12 name=iconName /> | _ => React.null }} <span className={selected ? `${textColor.primaryNormal} font-semibold` : ""}> {React.string(option.label)} </span> </div> {selected ? props["active"] && deSelectAllowed ? <Icon name="close" size=10 className="text-red-500 mr-1" /> : <Tick isSelected=selected /> : React.null} </div>} </Menu.Item> }) ->React.array} </Menu.Items> </Transition> </div>} </Menu> </div> } }
4,005
9,437
hyperswitch-control-center
src/libraries/SessionStorage.res
.res
type sessionStorage = { getItem: string => Nullable.t<string>, setItem: (string, string) => unit, removeItem: string => unit, } @val external sessionStorage: sessionStorage = "sessionStorage"
45
9,438
hyperswitch-control-center
src/libraries/MonacoEditor.res
.res
open LazyUtils type miniTypes = {enabled: bool} type setOptions = { readOnly: bool, fontSize?: option<int>, fontFamily?: option<string>, fontWeight?: option<string>, minimap?: miniTypes, } type props = { defaultLanguage: string, defaultValue?: string, value?: string, height?: string, theme?: string, width?: string, options?: setOptions, onChange?: string => unit, onValidate?: array<array<JSON.t>> => unit, onMount?: Monaco.Editor.IStandaloneCodeEditor.t => unit, } let make: props => React.element = reactLazy(() => { import_("@monaco-editor/react") })
150
9,439
hyperswitch-control-center
src/libraries/ReactFinalForm.res
.res
type fieldRenderPropsInput = { name: string, onBlur: ReactEvent.Focus.t => unit, onChange: ReactEvent.Form.t => unit, onFocus: ReactEvent.Focus.t => unit, value: JSON.t, checked: bool, } type fieldRenderPropsCustomInput<'t> = { name: string, onBlur: ReactEvent.Focus.t => unit, onChange: 't => unit, onFocus: ReactEvent.Focus.t => unit, value: JSON.t, checked: bool, } let makeInputRecord = (val, setVal): fieldRenderPropsInput => { { name: "", onBlur: _ => (), onChange: setVal, onFocus: _ => (), value: val, checked: false, } } external toTypedField: fieldRenderPropsInput => fieldRenderPropsCustomInput<'t> = "%identity" type fieldRenderPropsMeta = { active: bool, data: bool, dirty: bool, dirtySinceLastSubmit: bool, error: Nullable.t<string>, initial: bool, invalid: bool, modified: bool, modifiedSinceLastSubmit: bool, pristine: bool, submitError: Nullable.t<string>, submitFailed: bool, submitSucceeded: bool, submitting: bool, touched: bool, valid: bool, validating: bool, visited: bool, value: JSON.t, } let makeCustomError = error => { { active: true, data: true, dirty: true, dirtySinceLastSubmit: true, error: Nullable.fromOption(error), initial: true, invalid: true, modified: true, modifiedSinceLastSubmit: true, pristine: true, submitError: Nullable.null, submitFailed: true, submitSucceeded: true, submitting: true, touched: true, valid: true, validating: true, visited: true, value: JSON.Encode.null, } } type fieldRenderProps = { input: fieldRenderPropsInput, meta: fieldRenderPropsMeta, } type formValues = JSON.t type submitErrorResponse = { responseCode: string, responseMessage: string, status: string, } type formState = { dirty: bool, submitError: Nullable.t<string>, submitErrors: Nullable.t<JSON.t>, hasValidationErrors: bool, hasSubmitErrors: bool, submitting: bool, values: JSON.t, initialValues: JSON.t, errors: JSON.t, dirtySinceLastSubmit: bool, dirtyFields: Dict.t<bool>, dirtyFieldsSinceLastSubmit: Dict.t<bool>, submitSucceeded: bool, modifiedSinceLastSubmit: bool, } type unsubscribeFn = unit => unit type formApi = { batch: bool, blur: bool, change: (string, JSON.t) => unit, destroyOnUnregister: bool, focus: bool, getFieldState: string => option<fieldRenderPropsMeta>, getRegisteredFields: bool, getState: unit => formState, initialize: bool, isValidationPaused: bool, mutators: bool, pauseValidation: bool, registerField: bool, reset: Nullable.t<JSON.t> => unit, resetFieldState: string => unit, restart: bool, resumeValidation: bool, submit: unit => Promise.t<Nullable.t<JSON.t>>, subscribe: (formState => unit, JSON.t) => unsubscribeFn, } type formRenderProps = { form: formApi, handleSubmit: ReactEvent.Form.t => unit, submitError: string, values: JSON.t, // handleSubmit: ReactEvent.Form.t => Promise.t<Nullable.t<JSON.t>>, } @module("final-form") external formError: string = "FORM_ERROR" let subscribeToValues = [("values", true)]->Dict.fromArray let subscribeToPristine = [("pristine", true)]->Dict.fromArray module Form = { @module("react-final-form") @react.component external make: ( ~children: formRenderProps => React.element=?, ~component: bool=?, ~debug: bool=?, ~decorators: bool=?, ~form: string=?, ~initialValues: JSON.t=?, ~initialValuesEqual: bool=?, ~keepDirtyOnReinitialize: bool=?, ~mutators: bool=?, ~onSubmit: (formValues, formApi) => Promise.t<Nullable.t<JSON.t>>, ~render: formRenderProps => React.element=?, ~subscription: Dict.t<bool>, ~validate: JSON.t => JSON.t=?, ~validateOnBlur: bool=?, ) => React.element = "Form" } module Field = { @module("react-final-form") @react.component external make: ( ~afterSubmit: bool=?, ~allowNull: bool=?, ~beforeSubmit: bool=?, ~children: fieldRenderProps => React.element=?, ~component: string=?, ~data: bool=?, ~defaultValue: bool=?, ~format: (~value: JSON.t, ~name: string) => JSON.t=?, ~formatOnBlur: bool=?, ~initialValue: bool=?, ~isEqual: bool=?, ~multiple: bool=?, ~name: string, ~parse: (~value: JSON.t, ~name: string) => JSON.t=?, ~ref: bool=?, ~render: fieldRenderProps => React.element=?, ~subscription: bool=?, @as("type") ~type_: bool=?, ~validate: (option<string>, JSON.t) => Promise.t<Nullable.t<string>>=?, // (field_vale, form_object) ~validateFields: bool=?, ~value: bool=?, ~placeholder: string=?, ) => React.element = "Field" } type formSubscription = JSON.t let useFormSubscription = (keys): formSubscription => { React.useMemo(() => { let dict = Dict.make() keys->Array.forEach(key => { Dict.set(dict, key, JSON.Encode.bool(true)) }) dict->JSON.Encode.object }, []) } module FormSpy = { @module("react-final-form") @react.component external make: ( ~children: formState => React.element, ~component: bool=?, ~onChange: bool=?, ~render: formState => React.element=?, ~subscription: formSubscription, ) => React.element = "FormSpy" } @module("react-final-form") external useFormState: Nullable.t<JSON.t> => formState = "useFormState" @module("react-final-form") external useForm: unit => formApi = "useForm" @module("react-final-form") external useField: string => fieldRenderProps = "useField" type useFieldOption @obj external makeUseFieldOption: ( ~format: (~value: JSON.t, ~name: string) => JSON.t=?, ~parse: (~value: JSON.t, ~name: string) => JSON.t=?, unit, ) => useFieldOption = "" @module("react-final-form") external useFieldWithOptions: (string, useFieldOption) => fieldRenderProps = "useField" let makeFakeInput = ( ~value=JSON.Encode.null, ~onChange=_ => (), ~onBlur=_ => (), ~onFocus=_ => (), (), ) => { let input: fieldRenderPropsInput = { name: "--", onBlur, onChange, onFocus, value, checked: true, } input } let fakeFieldRenderProps = { input: makeFakeInput(), meta: makeCustomError(None), }
1,683
9,440
hyperswitch-control-center
src/libraries/CookieStorage.res
.res
@set external setCookie: (DOMUtils.document, string) => unit = "cookie" @get external getCookie: DOMUtils.document => Js.Nullable.t<string> = "cookie" let getCookieDict = () => { getCookie(DOMUtils.document) ->Nullable.toOption ->Option.getOr("") ->String.split(";") ->Array.map(value => { let arr = value->String.split("=") let key = arr->Array.get(0)->Option.getOr("")->String.trim let value = arr->Array.get(1)->Option.getOr("")->String.trim (key, value) }) ->Dict.fromArray } let getCookieVal = key => { getCookieDict()->Dict.get(key)->Option.getOr("") } let setCookieVal = cookie => { setCookie(DOMUtils.document, cookie) } let getDomainOfCookie = domain => { switch domain { | Some(domain) => domain | None => Window.Location.hostname } } let deleteCookie = (~cookieName, ~domain=?) => { let domainClause = `domain=${getDomainOfCookie(domain)}` setCookieVal(`${cookieName}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;${domainClause}`) setCookieVal(`${cookieName}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;`) }
322
9,441
hyperswitch-control-center
src/libraries/ReactBeautifulDND.res
.res
type droppableFunctionReturn type droppableMode = Standard | Virtual module DragDropContext = { @module("react-beautiful-dnd") @react.component external make: (~children: React.element=?, ~onDragEnd: 'a => unit) => React.element = "DragDropContext" } module Droppable = { @module("react-beautiful-dnd") @react.component external make: ( ~children: ('a, 'a) => React.element, ~droppableId: string, ~direction: string, ~\"type": string=?, ) => React.element = "Droppable" } module Draggable = { @module("react-beautiful-dnd") @react.component external make: ( ~children: ('a, 'a) => React.element, ~draggableId: string, ~index: int, ) => React.element = "Draggable" }
205
9,442
hyperswitch-control-center
src/libraries/HighchartsGanttChart.res
.res
type highcharts type highchartsGantt @module("highcharts/modules/gantt") external highchartsGantt: highcharts => unit = "default" @module("highcharts") external highchartsModule: highcharts = "default"
50
9,443
hyperswitch-control-center
src/libraries/recoil.js
.js
import { RecoilRoot, atom as recoilAtom, selector, useRecoilState, useRecoilValue, } from "recoil"; export function atom(key, defaultVal) { return recoilAtom({ key, default: defaultVal }); }
56
9,444
hyperswitch-control-center
src/libraries/ReactHyperJs.res
.res
type hyperloader type hyperPromise = promise<hyperloader> type sdkType = ELEMENT | WIDGET type paymentStatus = SUCCESS | INCOMPLETE | FAILED(string) | LOADING | PROCESSING | CHECKCONFIGURATION | CUSTOMSTATE type confirmParamType = {return_url: string} type confirmPaymentObj = {confirmParams: confirmParamType} type options type options2 type dataValueType type dataType = { elementType: string, complete: bool, empty: bool, collapsed: bool, value: dataValueType, } type paymentElement = {update: JSON.t => unit} type hyperType = { clientSecret: string, confirmPayment: JSON.t => Promise.t<JSON.t>, retrievePaymentIntent: string => Promise.t<JSON.t>, paymentRequest: JSON.t => JSON.t, getElement: string => Js.nullable<paymentElement>, update: JSON.t => unit, } type layout = { \"type": string, defaultCollapsed: bool, radios: bool, spacedAccordionItems: bool, } type layoutType = { layout: layout, paymentMethodOrder?: array<string>, } type appearanceTestType = {theme: string} type optionsTest = { clientSecret: string, appearance: appearanceTestType, hideIcon: bool, } type country = { isoAlpha3: string, currency: string, countryName: string, isoAlpha2: string, } type variables = { fontFamily: string, colorPrimary: string, fontSizeBase: string, colorBackground: string, } type appearanceType = { theme: string, variables: variables, rules: JSON.t, } type updateType = {appearance: appearanceType} @module("@juspay-tech/hyper-js") external loadHyper: string => hyperPromise = "loadHyper" @module("@juspay-tech/react-hyper-js") external useHyper: unit => hyperType = "useHyper" @module("@juspay-tech/react-hyper-js") external useWidgets: unit => hyperType = "useWidgets" module Elements = { @module("@juspay-tech/react-hyper-js") @react.component external make: ( ~options: options, ~stripe: hyperPromise, ~children: React.element, ) => React.element = "Elements" } module PaymentElement = { @module("@juspay-tech/react-hyper-js") @react.component external make: (~id: string, ~options: options2) => React.element = "PaymentElement" } module CardWidget = { @module("@juspay-tech/react-hyper-js") @react.component external make: (~id: string, ~options: options2) => React.element = "CardWidget" } module ElementsTest = { @module("@juspay-tech/react-hyper-js") @react.component external make: ( ~options: optionsTest, ~stripe: hyperPromise, ~children: React.element, ) => React.element = "Elements" } module PaymentElementTest = { @module("@juspay-tech/react-hyper-js") @react.component external make: (~id: string, ~options: options2) => React.element = "PaymentElement" }
695
9,445
hyperswitch-control-center
src/libraries/HighchartsHorizontalBarChart.res
.res
type title = {text: string, align?: string, useHTML?: bool} type tooltipRecord = {category: string, y: int} external asTooltipPointFormatter: Js_OO.Callback.arity1<'a> => tooltipRecord => string = "%identity" type tooltip = { pointFormatter: tooltipRecord => string, useHTML: bool, backgroundColor: string, borderColor: string, headerFormat: string, } type seriesOptions = {data: array<int>} type series = { name: string, data: array<float>, yData?: array<int>, options?: seriesOptions, \"type": string, } type yAxisRecord = {series: series, x: string, y: int} external asDataLabelFormatter: Js_OO.Callback.arity1<'a> => yAxisRecord => string = "%identity" type dataLabels = { enabled: bool, formatter?: yAxisRecord => string, useHTML: bool, } type bar = { dataLabels: dataLabels, colors: array<string>, colorByPoint: bool, borderColor: string, } type plotOptions = {bar: bar} type credits = {enabled: bool} type chart = {\"type": string, backgroundColor: string} type axis = {series: array<series>, categories: array<string>} type xAxisRecord = {axis: axis, value: string} external asXLabelFormatter: Js_OO.Callback.arity1<'a> => xAxisRecord => string = "%identity" type labels = { enabled: bool, formatter?: xAxisRecord => string, useHTML?: bool, } type xAxis = {categories: array<string>, lineWidth: int, opposite: bool, labels: labels} type yAxis = {min: int, title: title, labels: labels, gridLineWidth: int, visible: bool} type legend = {enabled: bool} type options = { chart: chart, title: title, subtitle: title, xAxis: xAxis, yAxis: yAxis, legend: legend, series: array<series>, plotOptions: option<plotOptions>, credits: credits, tooltip: tooltip, } type highcharts @module("highcharts") @val external highcharts: highcharts = "default" @module("highcharts") external highchartsModule: highcharts = "default" module HBarChart = { @module("highcharts-react-official") @react.component external make: (~highcharts: highcharts, ~options: JSON.t=?) => React.element = "default" } module Chart = { @module("highcharts-react-official") @react.component external make: (~highcharts: highcharts, ~options: JSON.t=?) => React.element = "default" }
584
9,446
hyperswitch-control-center
src/libraries/Document.res
.res
type domElement type document = {querySelectorAll: string => array<domElement>} @val external document: document = "document" @val @scope("document") external querySelector: string => Nullable.t<domElement> = "querySelector" @val @scope("document") external activeElement: Dom.element = "activeElement" @send external click: (domElement, unit) => unit = "click" @get external offsetWidth: Dom.element => int = "offsetWidth"
101
9,447
hyperswitch-control-center
src/libraries/HighchartsLine.res
.res
type title = {"text": string} type subtitle = {"text": string} type series = {"type": string, "name": string, "data": array<(float, float)>} type chart = { "type": string, "zoomType": string, "margin": option<array<int>>, "backgroundColor": Nullable.t<string>, "height": option<int>, } type linearGradient = {"x1": int, "y1": int, "x2": int, "y2": int} type stop = (int, string) type fillColor = {"linearGradient": linearGradient, "stops": array<stop>} type hover = {"lineWidth": int} type states = {"hover": hover} type area = { "fillColor": option<fillColor>, "threshold": Nullable.t<string>, "lineWidth": int, "states": states, "pointStart": option<int>, } type boxplot = {"visible": bool} type marker = {"enabled": bool} type markerseries = {"marker": marker} type plotOptions = {"area": area, "boxplot": boxplot, "series": markerseries} type xAxis = { "visible": bool, "labels": option<{ "formatter": option<unit => string>, "enabled": bool, }>, } type yAxis = {"visible": bool} type credits = {"enabled": bool} type legend = {"enabled": bool} type tooltip = { "enabled": bool, "pointFormat": option<string>, "pointFormatter": option<unit => string>, "headerFormat": option<string>, } type options = { chart: option<chart>, title: title, series: array<series>, plotOptions: option<plotOptions>, xAxis: xAxis, yAxis: yAxis, credits: credits, legend: legend, tooltip: tooltip, } type highcharts @module("highcharts") external highchartsModule: highcharts = "default" // @module("highcharts-react-official") // external make: (~highcharts: highcharts, ~options: options=?) => React.element = "HighchartsReact" module HighchartsReact = { @module("highcharts-react-official") @react.component external make: (~highcharts: highcharts, ~options: options=?) => React.element = "default" }
501
9,448
hyperswitch-control-center
src/libraries/Recoil.res
.res
module RecoilRoot = { @module("recoil") @react.component external make: (~children: React.element) => React.element = "RecoilRoot" } type recoilAtom<'v> = RecoilAtom('v) type recoilSelector<'v> = RecoilSelector('v) @module("./recoil") external atom: (string, 'v) => recoilAtom<'v> = "atom" @module("recoil") external useRecoilState: recoilAtom<'valueT> => ('valueT, ('valueT => 'valueT) => unit) = "useRecoilState" @module("recoil") external useSetRecoilState: recoilAtom<'valueT> => ('valueT => 'valueT) => unit = "useSetRecoilState" @module("recoil") external useRecoilValueFromAtom: recoilAtom<'valueT> => 'valueT = "useRecoilValue" module DebugObserver = { type snapshot @module("recoil") external useRecoilSnapshot: unit => snapshot = "useRecoilSnapshot" let doSomething: snapshot => unit = %raw(` function useSomeHook(snapshot) { console.log('DebugObserver :: The following atoms were modified:'); for (const node of snapshot.getNodes_UNSTABLE({isModified: true})) { console.debug("DebugObserver :: ", node.key, snapshot.getLoadable(node)); } } `) let useMake: unit => React.element = () => { let snapshot = useRecoilSnapshot() React.useEffect(() => { doSomething(snapshot) None }, [snapshot]) React.null } }
358
9,449
hyperswitch-control-center
src/libraries/FramerMotion.res
.res
type transition = { duration?: float, repeat?: int, repeatType?: string, staggerChildren?: float, ease?: string, stiffness?: int, restDelta?: int, @as("type") _type?: string, delayChildren?: float, delay?: float, } type animate = { scale?: float, rotate?: array<int>, borderRadius?: array<string>, y?: int, x?: int, opacity?: float, backgroundPosition?: string, height?: string, width?: string, background?: string, transition?: transition, } type style = {backgroundSize?: string, transformOrigin?: string} module Motion = { @module("framer-motion") @react.component external make: unit => React.element = "motion" module Div = { @module("framer-motion") @scope("motion") @react.component external make: ( ~key: string=?, ~animate: animate=?, ~className: string=?, ~layoutId: string=?, ~exit: animate=?, ~initial: animate=?, ~transition: transition=?, ~children: React.element=?, ~style: style=?, ~onAnimationComplete: unit => unit=?, ~onClick: unit => unit=?, ) => React.element = "div" } } module AnimatePresence = { @module("framer-motion") @react.component external make: ( ~mode: string=?, ~children: React.element=?, ~initial: bool=?, ~custom: int=?, ) => React.element = "AnimatePresence" } module TransitionComponent = { @react.component let make = (~id, ~children, ~className="", ~duration=0.3) => { <AnimatePresence mode="wait"> <Motion.Div key={id} initial={{y: 10, opacity: 0.0}} animate={{y: 0, opacity: 1.0}} exit={{y: -10, opacity: 0.0}} transition={{duration: duration}} className> {children} </Motion.Div> </AnimatePresence> } }
482
9,450
hyperswitch-control-center
src/libraries/RRule.res
.res
type recurrenceFrequency = | Daily | Weekly | Monthly | Yearly type recurrenceRule = { frequency: recurrenceFrequency, interval: int, byDay: option<array<int>>, byDate: option<array<int>>, byWeek: option<array<int>>, byMonth: option<array<int>>, byYear: option<array<int>>, } type durationUnit = | Second | Minute | Hour | Day type scheduleRuleRecipe = { recurrence: option<recurrenceRule>, dateWhitelist: option<array<Date.t>>, dateBlacklist: option<array<Date.t>>, durationUnit: durationUnit, durationAmount: int, } let durationSeconds: (durationUnit, int) => int = (dUnit, dAmount) => { switch dUnit { | Second => dAmount | Minute => dAmount * 60 | Hour => dAmount * 60 * 60 | Day => dAmount * 60 * 60 * 24 } } let isScheduled: (scheduleRuleRecipe, Date.t, Date.t, Date.t) => bool = ( recipe, startTime, endTime, currentTime, ) => { //check if date in date blacklist let getDay = date => { Float.toInt(Js.Date.getDay(date)) } let byDay = switch recipe.recurrence { | Some(recur) => switch recur.byDay { | Some(days) => { let day = getDay(currentTime) switch days->Array.find(x => x == day) { | Some(_a) => true | None => false } } | None => true } | None => true } let getDate = date => { Float.toInt(Js.Date.getDate(date)) } let byDate = switch recipe.recurrence { | Some(recur) => switch recur.byDate { | Some(days) => { let day = getDate(currentTime) switch days->Array.find(x => x == day) { | Some(_a) => true | None => false } } | None => true } | None => true } let getMonth = date => { Float.toInt(Js.Date.getMonth(date)) } let byMonth = switch recipe.recurrence { | Some(recur) => switch recur.byMonth { | Some(days) => { let day = getMonth(currentTime) switch days->Array.find(x => x == day) { | Some(_a) => true | None => false } } | None => true } | None => true } let getYear = date => { Float.toInt(Js.Date.getFullYear(date)) } let byYear = switch recipe.recurrence { | Some(recur) => switch recur.byYear { | Some(days) => { let day = getYear(currentTime) switch days->Array.find(x => x == day) { | Some(_a) => true | None => false } } | None => true } | None => true } let getWeek = date => { // let dat = getDate(date) // let da = getDay(date) // let a = Math.ceil(Int.toFloat(dat + da)) / 7 // a + 1 let firstWeekDay = Js.Date.makeWithYMD( ~year=Js.Date.getFullYear(date), ~month=Js.Date.getMonth(date), ~date=1.0, (), ) let offsetDate = Int.fromFloat(Js.Date.getDate(date)) + Int.fromFloat(Js.Date.getDay(firstWeekDay)) - 1 Math.Int.floor(Float.fromInt(offsetDate / 7)) + 1 } let byWeek = switch recipe.recurrence { | Some(recur) => switch recur.byWeek { | Some(days) => { let day = getWeek(currentTime) switch days->Array.find(x => x == day) { | Some(_) => true | None => false } } | None => true } | None => true } let frequencyCheck = switch recipe.recurrence { | Some(recur) => if recur.interval === 0 { false } else { switch recur.frequency { | Yearly => mod(getYear(currentTime) - getYear(startTime), recur.interval) == 0 | Monthly => mod( (currentTime->DayJs.getDayJsForJsDate).diff(Date.toString(startTime), "month"), recur.interval, ) == 0 | Weekly => mod( (currentTime->DayJs.getDayJsForJsDate).diff(Date.toString(startTime), "week"), recur.interval, ) == 0 | Daily => mod( (currentTime->DayJs.getDayJsForJsDate).diff(Date.toString(startTime), "day"), recur.interval, ) == 0 } } | None => true } let rest = startTime <= currentTime && currentTime <= endTime && byDay && byDate && byMonth && byYear && byWeek && frequencyCheck let isWhitelist = rest => { switch recipe.dateWhitelist { | Some(whitelist) => switch whitelist->Array.find(x => x == currentTime) { | Some(_a) => true | None => rest } | None => rest } } let isBlackList = rest => { switch recipe.dateBlacklist { | Some(blacklist) => switch blacklist->Array.find(x => x == currentTime) { | Some(_a) => false | None => rest } | None => rest } } isWhitelist(isBlackList(rest)) }
1,290
9,451
hyperswitch-control-center
src/libraries/LocalStorage.res
.res
@val @scope("localStorage") external getItem: string => Nullable.t<string> = "getItem" @val @scope("localStorage") external setItemOrig: (string, string) => unit = "setItem" @val @scope("localStorage") external removeItem: string => unit = "removeItem" @val @scope("localStorage") external clear: unit => unit = "clear" module InternalStorage = { type listener = unit => unit let listeners: array<listener> = [] let addEventListener = fn => { if !{listeners->Array.includes(fn)} { listeners->Array.push(fn)->ignore } } let removeEventListener = fn => { let index = listeners->Array.findIndex(x => x === fn) if index !== -1 { listeners->Array.splice(~start=index, ~remove=1, ~insert=[])->ignore } } let sendEvents = () => { listeners->Array.forEach(fn => fn()) } } let setItem = (key, val) => { setItemOrig(key, val) InternalStorage.sendEvents() } let useStorageValue = key => { let (value, setValue) = React.useState(() => getItem(key)) React.useEffect(() => { let oldValue = ref(getItem(key)) let handleStorage = _ => { let newValue = getItem(key) if oldValue.contents !== newValue { setValue(_ => newValue) oldValue.contents = newValue } } InternalStorage.addEventListener(handleStorage) Window.addEventListener3("storage", handleStorage, true) Some( () => { InternalStorage.removeEventListener(handleStorage) Window.removeEventListener("storage", handleStorage) }, ) }, []) React.useMemo(() => { /* LocalStorage. */ getItem(key)->Nullable.toOption }, (key, value)) }
387
9,452
hyperswitch-control-center
src/libraries/ReactSyntaxHighlighter.res
.res
type editorStyle @module("react-syntax-highlighter/dist/esm/styles/hljs") external lightfair: editorStyle = "googlecode" type style = { backgroundColor?: string, lineHeight?: string, fontSize?: string, paddingLeft?: string, padding?: string, } type props = { language?: string, style?: editorStyle, customStyle?: style, showLineNumbers?: bool, wrapLines?: bool, wrapLongLines?: bool, lineNumberContainerStyle?: style, children: string, } module SyntaxHighlighter = { @module("react-syntax-highlighter") @react.component external make: ( ~language: string=?, ~style: editorStyle=?, ~customStyle: style, ~showLineNumbers: bool, ~wrapLines: bool=?, ~wrapLongLines: bool=?, ~lineNumberContainerStyle: style, ~children: string, ) => React.element = "default" }
210
9,453
hyperswitch-control-center
src/libraries/FileReader.res
.res
type arg = ReactEvent.Form.t type file type read = { mutable onload: arg => unit, readAsText: string => unit, readAsBinaryString: string => unit, readAsDataURL: file => unit, result: string, onerror: string => unit, } @new external reader: read = "FileReader"
76
9,454
hyperswitch-control-center
src/libraries/GoogleAnalytics.res
.res
type eventType = { category: string, action: string, label: string, } type pageViewType = {hitType: string, page: string} type analyticsType = { initialize: string => unit, event: eventType => unit, send: pageViewType => unit, } @module("react-ga4") external analytics: analyticsType = "default" let send = object => { analytics.send(object) }
93
9,455
hyperswitch-control-center
src/libraries/Window.res
.res
type t type listener<'ev> = 'ev => unit type event = {data: string} @val @scope("window") external parent: 't = "parent" @val @scope("window") external addEventListener: (string, listener<'ev>) => unit = "addEventListener" @val @scope("window") external close: unit => unit = "close" @val @scope("window") external scrollTo: (float, float) => unit = "scrollTo" @val @scope("window") external addEventListener3: (string, listener<'ev>, bool) => unit = "addEventListener" @val @scope("window") external removeEventListener: (string, listener<'ev>) => unit = "removeEventListener" @val @scope("window") external postMessage: (JSON.t, string) => unit = "postMessage" @val @scope("window") external checkLoadHyper: option<ReactHyperJs.hyperloader> = "Hyper" @val @scope("window") external loadHyper: (string, JSON.t) => ReactHyperJs.hyperloader = "Hyper" type rec selectionObj = {\"type": string} @val @scope("window") external getSelection: unit => selectionObj = "getSelection" @val @scope("window") external navigator: JSON.t = "navigator" @val @scope("window") external connectorWasmInit: 'a => Promise.t<JSON.t> = "init" @val @scope("window") external getConnectorConfig: string => JSON.t = "getConnectorConfig" @val @scope("window") external getPayoutConnectorConfig: string => JSON.t = "getPayoutConnectorConfig" @val @scope("window") external getThreeDsKeys: unit => array<string> = "getThreeDsKeys" @val @scope("window") external getSurchargeKeys: unit => array<string> = "getSurchargeKeys" @val @scope("window") external getAllKeys: unit => array<string> = "getAllKeys" @val @scope("window") external getKeyType: string => string = "getKeyType" @val @scope("window") external getAllConnectors: unit => array<string> = "getAllConnectors" @val @scope("window") external getVariantValues: string => array<string> = "getVariantValues" @val @scope("window") external getDescriptionCategory: unit => JSON.t = "getDescriptionCategory" @val @scope("window") open ConnectorTypes external getRequestPayload: (wasmRequest, wasmExtraPayload) => JSON.t = "getRequestPayload" @val @scope("window") external getResponsePayload: 'a => JSON.t = "getResponsePayload" @val @scope("window") external getParsedJson: string => JSON.t = "getParsedJson" @val @scope("window") external innerWidth: int = "innerWidth" @val @scope("window") external innerHeight: int = "innerHeight" @val @scope("window") external globalUrlPrefix: option<string> = "urlPrefix" @val @scope("window") external payPalCreateAccountWindow: unit => unit = "payPalCreateAccountWindow" @val @scope("window") external isSecureContext: bool = "isSecureContext" @val @scope("window") external getAuthenticationConnectorConfig: string => JSON.t = "getAuthenticationConnectorConfig" @val @scope("window") external getPMAuthenticationProcessorConfig: string => JSON.t = "getPMAuthenticationProcessorConfig" @val @scope("window") external getTaxProcessorConfig: string => JSON.t = "getTaxProcessorConfig" @val @scope("window") external getAllPayoutKeys: unit => array<string> = "getAllPayoutKeys" @val @scope("window") external getPayoutVariantValues: string => array<string> = "getPayoutVariantValues" @val @scope("window") external getPayoutDescriptionCategory: unit => JSON.t = "getPayoutDescriptionCategory" module MatchMedia = { type matchEvent = { matches: bool, media: string, } type queryResponse = { matches: bool, addListener: (matchEvent => unit) => unit, removeListener: (matchEvent => unit) => unit, } } @val @scope("window") external matchMedia: string => MatchMedia.queryResponse = "matchMedia" @val @scope("window") external _open: string => unit = "open" module Location = { type location @val @scope("window") external location: location = "location" @val @scope(("window", "location")) external hostname: string = "hostname" @val @scope(("window", "location")) external reload: unit => unit = "reload" @val @scope(("window", "location")) external hardReload: bool => unit = "reload" @val @scope(("window", "location")) external replace: string => unit = "replace" @val @scope(("window", "location")) external assign: string => unit = "assign" @val @scope(("window", "location")) external origin: string = "origin" @val @scope(("window", "location")) external pathName: string = "pathname" @val @scope(("window", "location")) external href: string = "href" @set external setHref: (location, string) => unit = "href" } module Navigator = { @val @scope(("window", "navigator")) external userAgent: string = "userAgent" @val @scope(("window", "navigator")) external browserName: string = "appName" @val @scope(("window", "navigator")) external browserVersion: string = "appVersion" @val @scope(("window", "navigator")) external platform: string = "platform" @val @scope(("window", "navigator")) external browserLanguage: string = "language" } module Screen = { @val @scope(("window", "screen")) external screenHeight: string = "height" @val @scope(("window", "screen")) external screenWidth: string = "width" } type date = {getTimezoneOffset: unit => float} @new external date: unit => date = "Date" let date = date() let timeZoneOffset = date.getTimezoneOffset()->Float.toString type options = {timeZone: string} type dateTimeFormat = {resolvedOptions: unit => options} @val @scope("Intl") external dateTimeFormat: unit => dateTimeFormat = "DateTimeFormat" module History = { @val @scope(("window", "history")) external back: unit => unit = "back" @val @scope(("window", "history")) external forward: unit => unit = "forward" @val @scope(("window", "history")) external length: int = "length" } module ArrayBuffer = { type t } module Crypto = { module Subtle = { @val @scope(("window", "crypto", "subtle")) external importKey: (string, ArrayBuffer.t, {..}, bool, array<string>) => Promise.t<string> = "importKey" @val @scope(("window", "crypto", "subtle")) external decrypt: ({..}, string, ArrayBuffer.t) => Promise.t<string> = "decrypt" } } @val @scope("window") external prompt: string => string = "prompt" module Notification = { type notification = { permission: string, requestPermission: unit => Promise.t<string>, } @val @scope("window") external notification: Js.Null_undefined.t<notification> = "Notification" let requestPermission = switch notification->Js.Null_undefined.toOption { | Some(notif) => notif.requestPermission | None => () => Promise.resolve("") } } module FcWidget = { module User = { @val @scope(("window", "fcWidget", "user")) external setEmail: string => Promise.t<string> = "setEmail" @val @scope(("window", "fcWidget", "user")) external setFirstName: string => Promise.t<string> = "setFirstName" } } @val @scope("window") external fcWidget: 'a = "fcWidget" type boundingClient = {x: int, y: int, width: int, height: int} @send external getBoundingClientRect: Dom.element => boundingClient = "getBoundingClientRect" @val @scope("window") external appendStyle: HyperSwitchConfigTypes.customStylesTheme => unit = "appendStyle" @val @scope("window") external env: HyperSwitchConfigTypes.urlConfig = "_env_"
1,842
9,456
hyperswitch-control-center
src/libraries/Lottie.res
.res
open LazyUtils type props = { animationData: JSON.t, autoplay: bool, loop: bool, lottieRef?: React.ref<Nullable.t<Dom.element>>, initialSegment?: array<int>, } let make: props => React.element = reactLazy(() => import_("lottie-react"))
65
9,457
hyperswitch-control-center
src/libraries/ReactWindow.res
.res
module ListComponent = { type t @send external resetAfterIndex: (t, int, bool) => unit = "resetAfterIndex" @send external scrollToItem: (t, int, string) => unit = "scrollToItem" } module VariableSizeList = { @module("react-window") @react.component external make: ( ~ref: ListComponent.t => unit=?, ~children: 'a => React.element=?, ~height: int=?, ~overscanCount: int=?, ~itemCount: int=?, ~itemSize: _ => int=?, ~width: int=?, ~layout: string=?, ) => React.element = "VariableSizeList" }
163
9,458
hyperswitch-control-center
src/libraries/HighchartsPieChart.res
.res
type title = {text: string, align: string, useHTML: bool} type point = {name: string, percentage: float} type yAxisRecord = {point: point} type tooltipRecord = {name: string, y: int} type style = {color: string, opacity: string} external asTooltipPointFormatter: Js_OO.Callback.arity1<'a> => tooltipRecord => string = "%identity" type tooltip = { pointFormatter: tooltipRecord => string, useHTML: bool, backgroundColor: string, borderColor: string, headerFormat: string, } external asDataLabelFormatter: Js_OO.Callback.arity1<'a> => yAxisRecord => string = "%identity" type dataLabels = { enabled: bool, connectorShape: string, formatter: yAxisRecord => string, style: style, useHTML: bool, } type pie = { dataLabels: dataLabels, startAngle: int, endAngle: int, center: array<string>, size: string, colors: array<string>, borderColor?: string, } type series = { name: string, \"type": string, innerSize: string, data: array<(string, float)>, } type plotOptions = {pie: pie} type chart = {backgroundColor: string} type credits = {enabled: bool} type options = { title: title, subtitle: title, series: array<series>, plotOptions: option<plotOptions>, credits: credits, tooltip: tooltip, chart?: chart, } type highcharts @module("highcharts") @val external highcharts: highcharts = "default" @module("highcharts") external highchartsModule: highcharts = "default" module PieChart = { @module("highcharts-react-official") @react.component external make: (~highcharts: highcharts, ~options: JSON.t=?) => React.element = "default" } module Chart = { @module("highcharts-react-official") @react.component external make: (~highcharts: highcharts, ~options: JSON.t=?) => React.element = "default" }
462
9,459
hyperswitch-control-center
src/libraries/Monaco.res
.res
module Language = { type completionItemEnum type completionItemKind type model type languages type position = { lineNumber: int, column: int, } type word = { startColumn: int, endColumn: int, } type range = { startLineNumber: int, endLineNumber: int, startColumn: int, endColumn: int, } type labels = { label: string, insertText: string, range: range, } type suggestions = {suggestions: array<labels>} type completionItemProvider = {provideCompletionItems: (model, position) => suggestions} type internalModel = { startLineNumber: int, startColumn: int, endLineNumber: int, endColumn: int, } type regProvider @send external dispose: regProvider => unit = "dispose" @send external getWordUntilPosition: (model, position) => word = "getWordUntilPosition" @get external completionItemKind: languages => completionItemKind = "CompletionItemKind" @get external value: completionItemKind => completionItemEnum = "Value" @send external registerCompletionItemProvider: ( languages, string, completionItemProvider, ) => regProvider = "registerCompletionItemProvider" } // Monaco basic types type keyCode = {\"KEY_S": int} type monaco = {languages: Language.languages, \"KeyCode": keyCode} type lang = [#yaml | #sql] module Range = { type t @module("monaco-editor") @new external new: (int, int, int, int) => t = "Range" } type wordWrapOverride2 = [#off | #on | #inherit] type wordWrap = [#off | #on | #wordWrapColumn | #bounded] type linenumberSwitch = [#off | #on] type minimap = {enabled: bool} type options = { emptySelectionClipboard?: bool, formatOnType?: bool, wordWrapOverride2?: wordWrapOverride2, wordWrap?: wordWrap, lineNumbers?: linenumberSwitch, minimap?: minimap, roundedSelection?: bool, } type setPosition = { lineNumber: int, column: int, } type editor = { setPosition: setPosition => unit, focus: unit => unit, } module Editor = { module IStandaloneCodeEditor = { type t @send external deltaDecorations: (t, 'arr1, 'arr2) => 'decorators = "deltaDecorations" } @react.component @module("@monaco-editor/react") external make: ( ~height: string, ~theme: string, ~language: lang, ~onChange: string => unit, ~value: string, ~beforeMount: monaco => unit, ~options: options=?, ) => React.element = "default" }
639
9,460
hyperswitch-control-center
src/libraries/DayJs.res
.res
type relativeTime @module("dayjs/plugin/relativeTime") external relativeTime: relativeTime = "default" @module("dayjs/plugin/isToday") external isToday: relativeTime = "default" @module("dayjs/plugin/customParseFormat") external customParseFormat: relativeTime = "default" type rec dayJs = { isValid: unit => bool, toString: unit => string, toDate: unit => Date.t, add: (int, string) => dayJs, isSame: (string, string) => bool, subtract: (int, string) => dayJs, diff: (string, string) => int, year: unit => int, date: int => dayJs, endOf: string => dayJs, format: string => string, fromNow: unit => string, month: unit => int, isToday: unit => bool, } type extendable = {extend: relativeTime => unit} @module("dayjs") external dayJs: extendable = "default" @module("dayjs") external getDayJs: unit => dayJs = "default" @module("dayjs") external getDayJsForString: string => dayJs = "default" @module("dayjs") external getDayJsFromCustromFormat: (string, string, bool) => dayJs = "default" let getDayJsForJsDate = date => { date->Date.toString->getDayJsForString }
316
9,461
hyperswitch-control-center
src/libraries/ReactQRCode.res
.res
@module("react-qr-code") @react.component external make: ( ~value: string=?, ~style: string=?, ~size: int=?, ~viewBox: string=?, ) => React.element = "default"
53
9,462
hyperswitch-control-center
src/libraries/Shimmer.res
.res
type shimmerType = Small | Big @module("react-shimmer-effect") @react.component let make = (~styleClass="w-96 h-96", ~shimmerType: shimmerType=Small) => { let theme = ThemeProvider.useTheme() let shimmerClass = switch shimmerType { | Small => "animate-shimmer" | Big => "animate-shimmer-fast" } let background = switch theme { | Light => `linear-gradient(94.97deg, rgba(241, 242, 244, 0) 25.3%, #ebedf0 50.62%, rgba(241, 242, 244, 0) 74.27%)` | Dark => `linear-gradient(94.97deg, rgba(35, 36, 36, 0) 25.3%, #2c2d2d 50.62%, rgba(35, 36, 36, 0) 74.27%)` } <div className={`${shimmerClass} border border-solid border-[#ccd2e259] dark:border-[#2e2f3980] dark:bg-black bg-white ${styleClass}`} style={background: background} /> }
307
9,463
hyperswitch-control-center
src/libraries/JsDatePicker.res
.res
type input = {mutable value: string} type date = {toLocaleDateString: unit => string} type instance type options = { formatter?: (input, date, instance) => unit, position?: [#tr | #tl | #br | #bl | #c], } @module("js-datepicker") external datepicker: (string, options) => unit = "default"
80
9,464
hyperswitch-control-center
src/libraries/HighchartsGanttChartLazy.res
.res
open LazyUtils open HighchartsGanttChart type props = { highcharts: highcharts, options?: JSON.t, constructorType: string, } let make: props => React.element = reactLazy(() => import_("highcharts-react-official"))
55
9,465
hyperswitch-control-center
src/libraries/Clipboard.res
.res
type styleObj @get external style: Dom.element => styleObj = "style" @val @scope(("navigator", "clipboard")) external writeTextDoc: string => unit = "writeText" @val external document: 'a = "document" @set external setPosition: (styleObj, string) => unit = "position" @set external setLeft: (styleObj, string) => unit = "left" @send external select: (Dom.element, unit) => unit = "select" @send external remove: (Dom.element, unit) => unit = "remove" @val @scope(("window", "document", "body")) external prepend: 'a => unit = "prepend" @val @scope("document") external execCommand: string => unit = "execCommand" let writeText = (str: string) => { try { if Window.isSecureContext { writeTextDoc(str) } else { let textArea = document->DOMUtils.createElement("textarea") textArea->Webapi.Dom.Element.setInnerHTML(str) textArea->style->setPosition("absolute") textArea->style->setPosition("absolute") textArea->style->setLeft("-99999999px") textArea->prepend textArea->select() execCommand("copy") textArea->remove() } } catch { | _ => () } } module Copy = { @react.component let make = ( ~data, ~toolTipPosition: ToolTip.toolTipPosition=Left, ~copyElement=?, ~iconSize=15, ~outerPadding="p-2", ) => { let (tooltipText, setTooltipText) = React.useState(_ => "copy") let onCopyClick = ev => { ev->ReactEvent.Mouse.stopPropagation setTooltipText(_ => "copied") writeText([data]->Array.joinWithUnsafe("\n")) } let iconClass = "text-gray-600" <div className={`flex justify-end ${outerPadding}`} onMouseOut={_ => { setTooltipText(_ => "copy") }}> <div onClick={onCopyClick}> <ToolTip tooltipWidthClass="w-fit" bgColor={tooltipText == "copy" ? "" : "bg-green-950 text-white"} arrowBgClass={tooltipText == "copy" ? "" : "#36AF47"} description=tooltipText toolTipFor={switch copyElement { | Some(element) => element | None => <div className={`${iconClass} flex items-center cursor-pointer`}> <Icon name="nd-copy" className="opacity-70 h-7" size=iconSize /> </div> }} toolTipPosition tooltipPositioning=#absolute /> </div> </div> } }
621
9,466
hyperswitch-control-center
src/libraries/PDFViewer/PDFViewerTypes.res
.res
type pdfInfoNumPages = {numPages: int} type pdfInfoType = {_pdfInfo: pdfInfoNumPages} module Page = { @module("react-pdf") @react.component external make: ( ~pageNumber: int, ~renderAnnotationLayer: bool, ~renderTextLayer: bool, ~className: string=?, ~height: int=?, ~width: int=?, ~scale: int=?, ~loading: React.element=?, ~error: React.element=?, ) => React.element = "Page" } module DocumentPDF = { @module("react-pdf") @react.component external make: ( ~children: React.element, ~file: string, ~className: string=?, ~loading: React.element=?, ~onLoadSuccess: pdfInfoType => unit, ~noData: React.element=?, ~error: React.element=?, ) => React.element = "Document" }
210
9,467
hyperswitch-control-center
src/libraries/PDFViewer/ReactPDFViewerSinglePageLazy.res
.res
open LazyUtils type props = { url: string, width?: int, height?: int, className?: string, loading?: React.element, error?: React.element, } let make: props => React.element = reactLazy(() => import_("./ReactPDFViewerSinglePage.res.js"))
64
9,468
hyperswitch-control-center
src/libraries/PDFViewer/ReactPDFViewerSinglePage.res
.res
/* * Reference - https://github.com/wojtekmaj/react-pdf * If url is not provided the path of the pdf should be in public folder */ @module("react-pdf") external pdfjs: {..} = "pdfjs" pdfjs["GlobalWorkerOptions"]["workerSrc"] = `//unpkg.com/pdfjs-dist@${pdfjs["version"]}/build/pdf.worker.min.js` open PDFViewerTypes @react.component let make = (~url, ~className, ~loading, ~height=700, ~width=800, ~error) => { let (numPages, setNumPages) = React.useState(_ => 1) let onLoadSuccess = (pages: pdfInfoType) => { setNumPages(_ => pages._pdfInfo.numPages) } let noData = <div className="bg-white h-[70vh] flex items-center justify-center m-auto gap-2"> <Icon name="error-circle" size=16 /> {"Please upload the PDF File."->React.string} </div> <DocumentPDF file=url className onLoadSuccess error loading noData> {Array.fromInitializer(~length=numPages, i => i + 1) ->Array.mapWithIndex((ele, index) => { <Page key={`page_${index->Int.toString}`} pageNumber={ele} renderAnnotationLayer={true} renderTextLayer={false} height width loading /> }) ->React.array} </DocumentPDF> } let default = make
337
9,469
hyperswitch-control-center
src/libraries/bsfetch/Fetch__Iterator.ml
.ml
module Next = struct type 'a t external done_ : _ t -> bool option = "done" [@@bs.get] external value : 'a t -> 'a option = "value" [@@bs.get] [@@bs.return nullable] end type 'a t external next : 'a t -> 'a Next.t = "next" [@@bs.send] let rec forEach ~f t = let item = next t in match Next.(done_ item, value item) with | Some true, Some value -> f value [@bs] | Some true, None -> () | (Some false | None), Some value -> f value [@bs]; forEach ~f t | (Some false | None), None -> forEach ~f t
170
9,470
hyperswitch-control-center
src/libraries/bsfetch/Fetch__Iterator.mli
.mli
(** We need to bind to JavaScript Iterators for FormData functionality. But ideally this binding should be moved into BuckleScript itself. @see {{: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols}} *) module Next : sig type 'a t external done_ : _ t -> bool option = "done" [@@bs.get] external value : 'a t -> 'a option = "value" [@@bs.get] [@@bs.return nullable] end type 'a t val forEach : f:('a -> unit [@bs]) -> 'a t -> unit (** [forEach ~f iterator] runs [f] on each item returned by the [iterator]. This is not defined by the platform but a convenience function. *) external next : 'a t -> 'a Next.t = "next" [@@bs.send]
190
9,471
hyperswitch-control-center
src/libraries/bsfetch/Fetch.res
.res
type body type bodyInit type headers type headersInit type response type request type requestInit type abortController type signal /* external */ type arrayBuffer /* TypedArray */ type bufferSource /* Web IDL, either an arrayBuffer or arrayBufferView */ type formData /* XMLHttpRequest */ type readableStream /* Streams */ type urlSearchParams /* URL */ type blob type file module AbortController = { type t = abortController @get external signal: t => signal = "signal" @send external abort: t => unit = "abort" @new external make: unit => t = "AbortController" } type requestMethod = | Get | Head | Post | Put | Delete | Connect | Options | Trace | Patch | Other(string) let encodeRequestMethod = x => /* internal */ switch x { | Get => "GET" | Head => "HEAD" | Post => "POST" | Put => "PUT" | Delete => "DELETE" | Connect => "CONNECT" | Options => "OPTIONS" | Trace => "TRACE" | Patch => "PATCH" | Other(method_) => method_ } let decodeRequestMethod = x => /* internal */ switch x { | "GET" => Get | "HEAD" => Head | "POST" => Post | "PUT" => Put | "DELETE" => Delete | "CONNECT" => Connect | "OPTIONS" => Options | "TRACE" => Trace | "PATCH" => Patch | method_ => Other(method_) } type referrerPolicy = | None | NoReferrer | NoReferrerWhenDowngrade | SameOrigin | Origin | StrictOrigin | OriginWhenCrossOrigin | StrictOriginWhenCrossOrigin | UnsafeUrl let encodeReferrerPolicy = x => /* internal */ switch x { | NoReferrer => "no-referrer" | None => "" | NoReferrerWhenDowngrade => "no-referrer-when-downgrade" | SameOrigin => "same-origin" | Origin => "origin" | StrictOrigin => "strict-origin" | OriginWhenCrossOrigin => "origin-when-cross-origin" | StrictOriginWhenCrossOrigin => "strict-origin-when-cross-origin" | UnsafeUrl => "unsafe-url" } let decodeReferrerPolicy = x => /* internal */ switch x { | "no-referrer" => NoReferrer | "" => None | "no-referrer-when-downgrade" => NoReferrerWhenDowngrade | "same-origin" => SameOrigin | "origin" => Origin | "strict-origin" => StrictOrigin | "origin-when-cross-origin" => OriginWhenCrossOrigin | "strict-origin-when-cross-origin" => StrictOriginWhenCrossOrigin | "unsafe-url" => UnsafeUrl | e => raise(Failure("Unknown referrerPolicy: " ++ e)) } type requestType = | None /* default? unknown? just empty string in spec */ | Audio | Font | Image | Script | Style | Track | Video let decodeRequestType = x => /* internal */ switch x { | "audio" => Audio | "" => None | "font" => Font | "image" => Image | "script" => Script | "style" => Style | "track" => Track | "video" => Video | e => raise(Failure("Unknown requestType: " ++ e)) } type requestDestination = | None /* default? unknown? just empty string in spec */ | Document | Embed | Font | Image | Manifest | Media | Object | Report | Script | ServiceWorker | SharedWorker | Style | Worker | Xslt let decodeRequestDestination = x => /* internal */ switch x { | "document" => Document | "" => None | "embed" => Embed | "font" => Font | "image" => Image | "manifest" => Manifest | "media" => Media | "object" => Object | "report" => Report | "script" => Script | "serviceworker" => ServiceWorker | "sharedworder" => SharedWorker | "style" => Style | "worker" => Worker | "xslt" => Xslt | e => raise(Failure("Unknown requestDestination: " ++ e)) } type requestMode = | Navigate | SameOrigin | NoCORS | CORS let encodeRequestMode = x => /* internal */ switch x { | Navigate => "navigate" | SameOrigin => "same-origin" | NoCORS => "no-cors" | CORS => "cors" } let decodeRequestMode = x => /* internal */ switch x { | "navigate" => Navigate | "same-origin" => SameOrigin | "no-cors" => NoCORS | "cors" => CORS | e => raise(Failure("Unknown requestMode: " ++ e)) } type requestCredentials = | Omit | SameOrigin | Include let encodeRequestCredentials = x => /* internal */ switch x { | Omit => "omit" | SameOrigin => "same-origin" | Include => "include" } let decodeRequestCredentials = x => /* internal */ switch x { | "omit" => Omit | "same-origin" => SameOrigin | "include" => Include | e => raise(Failure("Unknown requestCredentials: " ++ e)) } type requestCache = | Default | NoStore | Reload | NoCache | ForceCache | OnlyIfCached let encodeRequestCache = x => /* internal */ switch x { | Default => "default" | NoStore => "no-store" | Reload => "reload" | NoCache => "no-cache" | ForceCache => "force-cache" | OnlyIfCached => "only-if-cached" } let decodeRequestCache = x => /* internal */ switch x { | "default" => Default | "no-store" => NoStore | "reload" => Reload | "no-cache" => NoCache | "force-cache" => ForceCache | "only-if-cached" => OnlyIfCached | e => raise(Failure("Unknown requestCache: " ++ e)) } type requestRedirect = | Follow | Error | Manual let encodeRequestRedirect = x => /* internal */ switch x { | Follow => "follow" | Error => "error" | Manual => "manual" } let decodeRequestRedirect = x => /* internal */ switch x { | "follow" => Follow | "error" => Error | "manual" => Manual | e => raise(Failure("Unknown requestRedirect: " ++ e)) } module HeadersInit = { type t = headersInit external make: {..} => t = "%identity" external makeWithDict: Js.Dict.t<string> => t = "%identity" external makeWithArray: array<(string, string)> => t = "%identity" } module Headers = { type t = headers @new external make: t = "Headers" @new external makeWithInit: headersInit => t = "Headers" @send external append: (t, string, string) => unit = "append" @send external delete: (t, string) => unit = "delete" /* entries */ /* very experimental */ @send @return({null_to_opt: null_to_opt}) external get: (t, string) => option<string> = "get" @send external has: (t, string) => bool = "has" /* keys */ /* very experimental */ @send external set: (t, string, string) => unit = "set" /* values */ /* very experimental */ } module BodyInit = { type t = bodyInit external make: string => t = "%identity" external makeWithBlob: blob => t = "%identity" external makeWithBufferSource: bufferSource => t = "%identity" external makeWithFormData: formData => t = "%identity" external makeWithUrlSearchParams: urlSearchParams => t = "%identity" } module Body = { module Impl = ( T: { type t }, ) => { @get external body: T.t => readableStream = "body" @get external bodyUsed: T.t => bool = "bodyUsed" @send external arrayBuffer: T.t => Js.Promise.t<arrayBuffer> = "arrayBuffer" @send external blob: T.t => Js.Promise.t<blob> = "blob" @send external formData: T.t => Js.Promise.t<formData> = "formData" @send external json: T.t => Js.Promise.t<Js.Json.t> = "json" @send external text: T.t => Js.Promise.t<string> = "text" } type t = body include Impl({ type t = t }) } module RequestInit = { type t = requestInit let map = (f, x) => /* internal */ switch x { | Some(v) => Some(f(v)) | None => None } @obj external make: ( ~method: string=?, ~headers: headersInit=?, ~body: bodyInit=?, ~referrer: string=?, ~referrerPolicy: string=?, ~mode: string=?, ~credentials: string=?, ~cache: string=?, ~redirect: string=?, ~integrity: string=?, ~keepalive: bool=?, ~signal: signal=?, ) => requestInit = "" let make = ( ~method_: option<requestMethod>=?, ~headers: option<headersInit>=?, ~body: option<bodyInit>=?, ~referrer: option<string>=?, ~referrerPolicy: referrerPolicy=None, ~mode: option<requestMode>=?, ~credentials: option<requestCredentials>=?, ~cache: option<requestCache>=?, ~redirect: option<requestRedirect>=?, ~integrity: string="", ~keepalive: option<bool>=?, ~signal: option<signal>=?, ) => make( ~method=?map(encodeRequestMethod, method_), ~headers?, ~body?, ~referrer?, ~referrerPolicy=encodeReferrerPolicy(referrerPolicy), ~mode=?map(encodeRequestMode, mode), ~credentials=?map(encodeRequestCredentials, credentials), ~cache=?map(encodeRequestCache, cache), ~redirect=?map(encodeRequestRedirect, redirect), ~integrity, ~keepalive?, ~signal?, ) } module Request = { type t = request include Body.Impl({ type t = t }) @new external make: string => t = "Request" @new external makeWithInit: (string, requestInit) => t = "Request" @new external makeWithRequest: t => t = "Request" @new external makeWithRequestInit: (t, requestInit) => t = "Request" @get external method__: t => string = "method" let method_: t => requestMethod = self => decodeRequestMethod(method__(self)) @get external url: t => string = "url" @get external headers: t => headers = "headers" @get external type_: t => string = "type" let type_: t => requestType = self => decodeRequestType(type_(self)) @get external destination: t => string = "destination" let destination: t => requestDestination = self => decodeRequestDestination(destination(self)) @get external referrer: t => string = "referrer" @get external referrerPolicy: t => string = "referrerPolicy" let referrerPolicy: t => referrerPolicy = self => decodeReferrerPolicy(referrerPolicy(self)) @get external mode: t => string = "mode" let mode: t => requestMode = self => decodeRequestMode(mode(self)) @get external credentials: t => string = "credentials" let credentials: t => requestCredentials = self => decodeRequestCredentials(credentials(self)) @get external cache: t => string = "cache" let cache: t => requestCache = self => decodeRequestCache(cache(self)) @get external redirect: t => string = "redirect" let redirect: t => requestRedirect = self => decodeRequestRedirect(redirect(self)) @get external integrity: t => string = "integrity" @get external keepalive: t => bool = "keepalive" @get external signal: t => signal = "signal" } module Response = { type t = response include Body.Impl({ type t = t }) @val external error: unit => t = "error" @val external redirect: string => t = "redirect" @val external redirectWithStatus: (string, int /* enum-ish */) => t = "redirect" @get external headers: t => headers = "headers" @get external ok: t => bool = "ok" @get external redirected: t => bool = "redirected" @get external status: t => int = "status" @get external statusText: t => string = "statusText" @get external type_: t => string = "type" @get external url: t => string = "url" @send external clone: t => t = "clone" } module FormData = { module EntryValue = { type t let classify: t => [> #String(string) | #File(file)] = t => if Js.typeof(t) == "string" { #String(Obj.magic(t)) } else { #File(Obj.magic(t)) } } module Iterator = Fetch__Iterator type t = formData @new external make: unit => t = "FormData" @send external append: (t, string, string) => unit = "append" @send external delete: (t, string) => unit = "delete" @send external get: (t, string) => option<EntryValue.t> = "get" @send external getAll: (t, string) => array<EntryValue.t> = "getAll" @send external set: (t, string, string) => unit = "set" @send external has: (t, string) => bool = "has" @send external keys: t => Iterator.t<string> = "keys" @send external values: t => Iterator.t<EntryValue.t> = "values" @send external appendObject: (t, string, {..}, ~filename: string=?) => unit = "append" @send external appendBlob: (t, string, blob, ~filename: string=?) => unit = "append" @send external appendFile: (t, string, file, ~filename: string=?) => unit = "append" @send external setObject: (t, string, {..}, ~filename: string=?) => unit = "set" @send external setBlob: (t, string, blob, ~filename: string=?) => unit = "set" @send external setFile: (t, string, file, ~filename: string=?) => unit = "set" @send external entries: t => Iterator.t<(string, EntryValue.t)> = "entries" } @val external fetch: string => Js.Promise.t<response> = "fetch" @val external fetchWithInit: (string, requestInit) => Js.Promise.t<response> = "fetch" @val external fetchWithRequest: request => Js.Promise.t<response> = "fetch" @val external fetchWithRequestInit: (request, requestInit) => Js.Promise.t<response> = "fetch"
3,627
9,472
hyperswitch-control-center
src/fragments/FragmentUtils.res
.res
1
9,473
hyperswitch-control-center
src/fragments/VerticalStepIndicator/VerticalStepIndicatorUtils.res
.res
open VerticalStepIndicatorTypes let default: section = { id: "", name: "", icon: "", subSections: None, } let getSectionById = (sections: array<section>, sectionId) => sections->Array.find(section => section.id === sectionId)->Option.getOr(default) let getSubSectionById = (subSections, subSectionId) => subSections->Array.find(subSection => subSection.id === subSectionId) let createStep = (sectionId, subSectionId) => {sectionId, subSectionId} let getFirstSubSection = subSections => subSections->Array.get(0) let getLastSubSection = subSections => subSections->Array.get(subSections->Array.length - 1) let findNextStep = (sections: array<section>, currentStep: step): option<step> => { let currentSection = sections->getSectionById(currentStep.sectionId) let currentSectionIndex = sections->Array.findIndex(section => section.id === currentStep.sectionId) switch (currentSection.subSections, currentStep.subSectionId) { | (Some(subSections), Some(subSectionId)) => { let currentSubIndex = subSections->Array.findIndex(sub => sub.id === subSectionId) if currentSubIndex < subSections->Array.length - 1 { subSections ->Array.get(currentSubIndex + 1) ->Option.map(nextSub => createStep(currentStep.sectionId, Some(nextSub.id))) } else { sections ->Array.get(currentSectionIndex + 1) ->Option.map(nextSection => { let firstSubSection = nextSection.subSections->Option.flatMap(getFirstSubSection) createStep(nextSection.id, firstSubSection->Option.map(sub => sub.id)) }) } } | (None, _) => sections ->Array.get(currentSectionIndex + 1) ->Option.map(nextSection => { let firstSubSection = nextSection.subSections->Option.flatMap(getFirstSubSection) createStep(nextSection.id, firstSubSection->Option.map(sub => sub.id)) }) | (_, None) => None } } let findPreviousStep = (sections: array<section>, currentStep: step): option<step> => { let currentSection = sections->getSectionById(currentStep.sectionId) let currentSectionIndex = sections->Array.findIndex(section => section.id === currentStep.sectionId) switch (currentSection.subSections, currentStep.subSectionId) { | (Some(subSections), Some(subSectionId)) => { let currentSubIndex = subSections->Array.findIndex(sub => sub.id === subSectionId) if currentSubIndex > 0 { subSections ->Array.get(currentSubIndex - 1) ->Option.map(prevSub => createStep(currentStep.sectionId, Some(prevSub.id))) } else { sections ->Array.get(currentSectionIndex - 1) ->Option.map(prevSection => { let lastSubSection = prevSection.subSections->Option.flatMap(getLastSubSection) createStep(prevSection.id, lastSubSection->Option.map(sub => sub.id)) }) } } | (None, _) => sections ->Array.get(currentSectionIndex - 1) ->Option.map(prevSection => { let lastSubSection = prevSection.subSections->Option.flatMap(getLastSubSection) createStep(prevSection.id, lastSubSection->Option.map(sub => sub.id)) }) | (_, None) => None } } let isFirstStep = (sections: array<section>, step: step): bool => { sections ->Array.get(0) ->Option.flatMap(firstSection => firstSection.subSections ->Option.flatMap(getFirstSubSection) ->Option.flatMap(firstSub => step.subSectionId->Option.map( subId => step.sectionId === firstSection.id && subId === firstSub.id, ) ) ) ->Option.getOr(false) } let isLastStep = (sections: array<section>, step: step): bool => { sections ->Array.get(sections->Array.length - 1) ->Option.flatMap(lastSection => lastSection.subSections ->Option.flatMap(getLastSubSection) ->Option.flatMap(lastSub => step.subSectionId->Option.map( subId => step.sectionId === lastSection.id && subId === lastSub.id, ) ) ) ->Option.getOr(false) } let getSectionFromStep = (sections: array<section>, step: step): option<section> => { sections->Array.find(section => getSectionById(sections, step.sectionId) === section) } let getSubSectionFromStep = (sections: array<section>, step: step): option<subSection> => { sections ->Array.find(section => section.id === step.sectionId) ->Option.flatMap(section => { section.subSections->Option.flatMap(subSections => { switch step.subSectionId { | Some(subSectionId) => subSections->Array.find(subSection => subSection.id === subSectionId) | None => None } }) }) } let findSectionIndex = (sections: array<section>, sectionId: string): int => { sections->Array.findIndex(section => section.id === sectionId) } let findSubSectionIndex = (subSections: array<subSection>, subSectionId: string): int => { subSections->Array.findIndex(subSection => subSection.id === subSectionId) }
1,176
9,474
hyperswitch-control-center
src/fragments/VerticalStepIndicator/VerticalStepIndicator.res
.res
open VerticalStepIndicatorTypes @react.component let make = ( ~titleElement: React.element, ~sections: array<section>, ~currentStep: step, ~backClick, ) => { open VerticalStepIndicatorUtils let rows = sections->Array.length->Int.toString let currIndex = sections->findSectionIndex(currentStep.sectionId) <div className="flex flex-col gap-y-6 h-774-px w-334-px sticky overflow-y-auto py-5"> <div className="flex items-center gap-x-3 px-6"> <Icon name="nd-arrow-left" className="text-nd_gray-600 cursor-pointer" onClick={_ => backClick()} customHeight="20" /> {titleElement} </div> <div className="w-full h-full p-2 md:p-6 border-r"> <div className={`grid grid-rows-${rows} relative gap-y-3.5`}> {sections ->Array.mapWithIndex((section, sectionIndex) => { let isStepCompleted = sectionIndex < currIndex let isCurrentStep = sectionIndex == currIndex let stepNameIndicator = if isCurrentStep { `text-nd_gray-700 break-all font-semibold` } else { ` text-nd_gray-400 font-medium` } let iconColor = if isCurrentStep { "text-gray-700" } else { "text-gray-400" } let sectionLineHeight = isCurrentStep && currentStep.subSectionId != None ? "h-5" : "h-6" <div key={section.id} className="font-semibold flex flex-col gap-y-2.5"> <div className="flex gap-x-3 items-center w-full relative z-10"> {if isStepCompleted { <div className="flex items-center justify-center rounded-full p-2 w-8 h-8 border"> <Icon className={`${iconColor}`} name="nd-check" /> </div> } else { <div className="flex items-center justify-center rounded-full p-2 w-8 h-8 border"> <Icon className={`${iconColor} pl-1 pt-1`} name={section.icon} /> </div> }} <RenderIf condition={sectionIndex != sections->Array.length - 1}> <div className={`absolute top-8 ${sectionLineHeight} left-4 border-l border-gray-150 z-0`} /> </RenderIf> <div className={stepNameIndicator}> {section.name->React.string} </div> </div> <div className="flex flex-col gap-y-2.5"> <RenderIf condition={isCurrentStep}> {switch section.subSections { | Some(subSections) => subSections ->Array.mapWithIndex((subSection, subSectionIndex) => { switch currentStep.subSectionId { | Some(subSectionId) => { let subStepIndex = subSections->findSubSectionIndex(subSectionId) let isSubStepCompleted = isStepCompleted || subSectionIndex < subStepIndex let isCurrentSubStep = subSectionIndex == subStepIndex && isCurrentStep let subSectionLineHeight = isCurrentSubStep ? "h-7" : "h-6" let subStepNameIndicator = if isCurrentSubStep { "text-blue-500 break-all font-semibold text-base pl-5" } else { "text-gray-400 break-all text-base font-medium pl-5" } <div key={subSection.id} className="flex gap-x-3 items-center p-2 rounded relative z-10"> <div className="h-4 w-4 flex items-center justify-center rounded"> {if isSubStepCompleted { <Icon name="nd-small-check" customHeight="12" /> } else if isCurrentSubStep { <Icon name="nd-radio" className="text-blue-500" customHeight="8" /> } else { <Icon name="nd-radio" className="text-gray-500" customHeight="8" /> }} </div> <div className={subStepNameIndicator}> {subSection.name->React.string} </div> <RenderIf condition={sectionIndex != sections->Array.length - 1 || subSectionIndex != subSections->Array.length - 1}> <div className={`absolute top-7 left-4 ${subSectionLineHeight} border-l border-gray-150 z-0`} /> </RenderIf> </div> } | None => React.null } }) ->React.array | None => React.null }} </RenderIf> </div> </div> }) ->React.array} </div> </div> </div> }
1,097
9,475
hyperswitch-control-center
src/fragments/VerticalStepIndicator/VerticalStepIndicatorTypes.res
.res
type identifier = {id: string, name: string} type rec section = { ...identifier, icon: string, subSections: option<array<subSection>>, } and subSection = { ...identifier, } type step = { sectionId: string, subSectionId: option<string>, }
67
9,476
hyperswitch-control-center
src/fragments/ConnectorFragments/ConnectorFragmentUtils.res
.res
let connectorLabelDetailField = Dict.fromArray([ ("connector_label", "Connector label"->JSON.Encode.string), ])
25
9,477
hyperswitch-control-center
src/fragments/ConnectorFragments/ConnectorHelperV2.res
.res
let textInput = (~field: CommonConnectorTypes.inputField, ~formName, ~customStyle=?) => { let {placeholder, label, required} = field let customStyle = { switch customStyle { | Some(val) => val | None => "" } } FormRenderer.makeFieldInfo( ~label, ~name={formName}, ~placeholder, ~customInput=InputFields.textInput(~customStyle), ~isRequired=required, ) } let selectInput = ( ~field: CommonConnectorTypes.inputField, ~formName, ~opt=None, ~onItemChange: option<ReactEvent.Form.t => unit>=?, ) => { let {label, required} = field let options = switch opt { | Some(value) => value | None => field.options->SelectBox.makeOptions } FormRenderer.makeFieldInfo(~label={label}, ~isRequired=required, ~name={formName}, ~customInput=( ~input, ~placeholder as _, ) => InputFields.selectInput( ~customStyle="max-h-48", ~options={options}, ~buttonText="Select Value", )( ~input={ ...input, onChange: event => { let _ = switch onItemChange { | Some(func) => func(event) | _ => () } input.onChange(event) }, }, ~placeholder="", ) ) } let multiSelectInput = (~field: CommonConnectorTypes.inputField, ~formName) => { let {label, required, options} = field FormRenderer.makeFieldInfo( ~label, ~isRequired=required, ~name={formName}, ~customInput=InputFields.multiSelectInput( ~showSelectionAsChips=false, ~customStyle="max-h-48", ~customButtonStyle="pr-3", ~options={options->SelectBox.makeOptions}, ~buttonText="Select Value", ), ) } let toggleInput = (~field: CommonConnectorTypes.inputField, ~formName) => { let {label} = field FormRenderer.makeFieldInfo( ~name={formName}, ~label, ~customInput=InputFields.boolInput(~isDisabled=false, ~boolCustomClass="rounded-lg"), ) } let radioInput = ( ~field: CommonConnectorTypes.inputField, ~formName, ~onItemChange: option<ReactEvent.Form.t => unit>=?, ~fill="", (), ) => { let {label, required, options} = field FormRenderer.makeFieldInfo(~label={label}, ~isRequired=required, ~name={formName}, ~customInput=( ~input, ~placeholder as _, ) => InputFields.radioInput( ~customStyle="cursor-pointer gap-2", ~isHorizontal=false, ~options=options->SelectBox.makeOptions, ~buttonText="", ~fill, )( ~input={ ...input, onChange: event => { let _ = switch onItemChange { | Some(func) => func(event) | _ => () } input.onChange(event) }, }, ~placeholder="", ) ) } let getCurrencyOption: CurrencyUtils.currencyCode => SelectBox.dropdownOption = currencyType => { open CurrencyUtils { label: currencyType->getCurrencyCodeStringFromVariant, value: currencyType->getCurrencyCodeStringFromVariant, } } let currencyField = ( ~name, ~options=CurrencyUtils.currencyList, ~disableSelect=false, ~toolTipText="", ) => FormRenderer.makeFieldInfo( ~label="Currency", ~isRequired=true, ~name, ~description=toolTipText, ~customInput=InputFields.selectInput( ~deselectDisable=true, ~disableSelect, ~customStyle="max-h-48", ~options=options->Array.map(getCurrencyOption), ~buttonText="Select Currency", ), ) module InfoField = { @react.component let make = (~label, ~str, ~customElementStyle="") => { <div className={`flex flex-col justify-center gap-0.5-rem ${customElementStyle} `}> <h2 className="flex-[1] text-nd_gray-400 "> {label->React.string} </h2> <h3 className="flex-[3] overflow-scroll whitespace-nowrap"> {str->React.string} </h3> </div> } } module CredsInfoField = { @react.component let make = ( ~authKeys, ~connectorAccountFields, ~customContainerStyle=?, ~customElementStyle="", ) => { open LogicUtils let customContainerCss = { switch customContainerStyle { | Some(val) => val | None => "flex flex-col gap-4" } } let dict = authKeys->Identity.genericTypeToDictOfJson <div className=customContainerCss> {dict ->Dict.keysToArray ->Array.filter(ele => ele !== "auth_type") ->Array.mapWithIndex((field, index) => { let value = dict->getString(field, "") let label = connectorAccountFields->getString(field, "") <InfoField key={index->Int.toString} label str=value customElementStyle /> }) ->React.array} </div> } } module CashtoCodeCredsInfo = { @react.component let make = (~authKeys: ConnectorTypes.currencyAuthKey) => { open LogicUtils let dict = authKeys.auth_key_map->Identity.genericTypeToDictOfJson dict ->Dict.keysToArray ->Array.map(ele => { let data = dict->getDictfromDict(ele) let keys = data->Dict.keysToArray { <> <InfoField label="Currency" str=ele /> {keys ->Array.map(ele => { let value = data->getString(ele, "") <InfoField label={ele->snakeToTitle} str=value /> }) ->React.array} </> } }) ->React.array } } module PreviewCreds = { @react.component let make = ( ~connectorAccountFields, ~connectorInfo: ConnectorTypes.connectorPayloadV2, ~customContainerStyle=?, ~customElementStyle=?, ) => { switch connectorInfo.connector_account_details { | HeaderKey(authKeys) => <CredsInfoField authKeys connectorAccountFields ?customContainerStyle ?customElementStyle /> | BodyKey(bodyKey) => <CredsInfoField authKeys=bodyKey connectorAccountFields ?customContainerStyle ?customElementStyle /> | SignatureKey(signatureKey) => <CredsInfoField authKeys=signatureKey connectorAccountFields ?customContainerStyle ?customElementStyle /> | MultiAuthKey(multiAuthKey) => <CredsInfoField authKeys=multiAuthKey connectorAccountFields ?customContainerStyle ?customElementStyle /> | CertificateAuth(certificateAuth) => <CredsInfoField authKeys=certificateAuth connectorAccountFields ?customContainerStyle ?customElementStyle /> | CurrencyAuthKey(currencyAuthKey) => <CashtoCodeCredsInfo authKeys=currencyAuthKey /> | UnKnownAuthType(_) => React.null } } } let connectorMetaDataValueInput = (~connectorMetaDataFields: CommonConnectorTypes.inputField) => { let {\"type", name} = connectorMetaDataFields let formName = `metadata.${name}` { switch (\"type", name) { | (Select, "merchant_config_currency") => currencyField(~name=formName) | (Text, _) => textInput(~field={connectorMetaDataFields}, ~formName, ~customStyle="rounded-xl") | (Select, _) => selectInput(~field={connectorMetaDataFields}, ~formName) | (Toggle, _) => toggleInput(~field={connectorMetaDataFields}, ~formName) | (MultiSelect, _) => multiSelectInput(~field={connectorMetaDataFields}, ~formName) | _ => textInput(~field={connectorMetaDataFields}, ~formName) } } } module ProcessorStatus = { @react.component let make = (~connectorInfo: ConnectorTypes.connectorPayloadV2) => { let form = ReactFinalForm.useForm() let updateConnectorStatus = (isSelected: bool) => { form.change("disabled", !isSelected->Identity.genericTypeToJson) form.submit()->ignore } <BoolInput.BaseComponent isSelected={!connectorInfo.disabled} setIsSelected={isSelected => updateConnectorStatus(isSelected)} isDisabled=false boolCustomClass="rounded-lg" /> } }
1,942
9,478
hyperswitch-control-center
src/fragments/ConnectorFragments/ConnectorPaymentMethodv2/PMTSelection.res
.res
module PMT = { @react.component let make = ( ~pmtData: ConnectorTypes.paymentMethodConfigTypeV2, ~pm, ~fieldsArray: array<ReactFinalForm.fieldRenderProps>, ~connector, ~formValues: ConnectorTypes.connectorPayloadV2, ) => { open ConnectorPaymentMethodV2Utils let pmInp = (fieldsArray[0]->Option.getOr(ReactFinalForm.fakeFieldRenderProps)).input let pmtArrayInp = (fieldsArray[1]->Option.getOr(ReactFinalForm.fakeFieldRenderProps)).input let pmEnabledInp = (fieldsArray[2]->Option.getOr(ReactFinalForm.fakeFieldRenderProps)).input let pmtInp = (fieldsArray[3]->Option.getOr(ReactFinalForm.fakeFieldRenderProps)).input let pmEnabledValue = formValues.payment_methods_enabled let pmtArrayValue = ( pmEnabledValue ->Array.find(ele => ele.payment_method_type == pm) ->Option.getOr({payment_method_type: "", payment_method_subtypes: []}) ).payment_method_subtypes let pmtValue = pmtArrayValue->Array.find(val => { if ( pmtData.payment_method_subtype->getPMTFromString == Credit || pmtData.payment_method_subtype->getPMTFromString == Debit ) { val.payment_method_subtype == pmtData.payment_method_subtype && val.card_networks->Array.get(0)->Option.getOr("") == pmtData.card_networks->Array.get(0)->Option.getOr("") } else { val.payment_method_subtype == pmtData.payment_method_subtype } }) let removeMethods = () => { let updatedPmtArray = pmtArrayValue->Array.filter(ele => if ( pmtData.payment_method_subtype->getPMTFromString == Credit || pmtData.payment_method_subtype->getPMTFromString == Debit ) { ele.payment_method_subtype != pmtData.payment_method_subtype || ele.card_networks->Array.get(0)->Option.getOr("") != pmtData.card_networks->Array.get(0)->Option.getOr("") } else { ele.payment_method_subtype != pmtData.payment_method_subtype } ) if updatedPmtArray->Array.length == 0 { let updatedPmArray = pmEnabledValue->Array.filter(ele => ele.payment_method_type != pm) if updatedPmArray->Array.length == 0 { pmEnabledInp.onChange([]->Identity.anyTypeToReactEvent) } else { pmEnabledInp.onChange(updatedPmArray->Identity.anyTypeToReactEvent) } } else { pmtArrayInp.onChange(updatedPmtArray->Identity.anyTypeToReactEvent) } } let update = isSelected => { if !isSelected { removeMethods() } else if !isMetaDataRequired(pmtData.payment_method_subtype, connector) { pmInp.onChange(pm->Identity.anyTypeToReactEvent) pmtInp.onChange(pmtData->Identity.anyTypeToReactEvent) } } <CheckBoxIcon isSelected={pmtValue->Option.isSome} setIsSelected={isSelected => update(isSelected)} /> } } let renderValueInp = (~pmtData, ~pm, ~connector, ~formValues) => ( fieldsArray: array<ReactFinalForm.fieldRenderProps>, ) => { <PMT pmtData pm fieldsArray connector formValues /> } let valueInput = (~pmtData, ~pmIndex, ~pmtIndex, ~pm, ~connector, ~formValues) => { open FormRenderer makeMultiInputFieldInfoOld( ~label=``, ~comboCustomInput=renderValueInp(~pmtData, ~pm, ~connector, ~formValues), ~inputFields=[ makeInputFieldInfo( ~name=`payment_methods_enabled[${pmIndex->Int.toString}].payment_method_type`, ), makeInputFieldInfo( ~name=`payment_methods_enabled[${pmIndex->Int.toString}].payment_method_subtypes`, ), makeInputFieldInfo(~name=`payment_methods_enabled`), makeInputFieldInfo( ~name=`payment_methods_enabled[${pmIndex->Int.toString}].payment_method_subtypes[${pmtIndex}]`, ), ], (), ) }
948
9,479
hyperswitch-control-center
src/fragments/ConnectorFragments/ConnectorPaymentMethodv2/ConnectorPaymentMethodV2.res
.res
/* PM - PaymentMethod PMT - PaymentMethodType PME - PaymentMethodExperience PMIndex - PaymentMethod Index PMTIndex - PaymentMethodType Index */ @react.component let make = (~initialValues, ~isInEditState, ~ignoreKeys=[]) => { open LogicUtils open ConnectorPaymentMethodV2Utils let connector = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("name", "") let pmts = React.useMemo(() => { try { Window.getConnectorConfig(connector)->getDictFromJsonObject } catch { | _ => Dict.make() } }, [connector]) let initialValue = React.useMemo(() => { let val = initialValues->getDictFromJsonObject ConnectorInterface.mapDictToConnectorPayload(ConnectorInterface.connectorInterfaceV2, val) }, [initialValues]) let defaultIgnoreKeys = ConnectorUtils.configKeysToIgnore->Array.concat(ignoreKeys) let paymentMethodValues = React.useMemo(() => { let newDict = Dict.make() let keys = pmts ->Dict.keysToArray ->Array.filter(val => !Array.includes(defaultIgnoreKeys, val)) keys->Array.forEach(key => { let pm = if key->getPMTFromString == Credit || key->getPMTFromString == Debit { "card" } else { key } let paymentMethodType = pmts->getArrayFromDict(key, []) let updatedData = paymentMethodType->Array.map( val => { let paymemtMethodType = val->getDictFromJsonObject->getString("payment_method_type", "") let paymemtMethodExperience = val->getDictFromJsonObject->getString("payment_experience", "") let wasmDict = val->getDictFromJsonObject let exisitngData = switch initialValue.payment_methods_enabled->Array.find( ele => { ele.payment_method_type == pm }, ) { | Some(data) => { let filterData = data.payment_method_subtypes->Array.filter( available => { // explicit check for card (for card we need to check the card network rather than the payment method type) if ( available.payment_method_subtype == key && available.card_networks->getValueFromArray(0, "") == paymemtMethodType ) { true } // explicit check for klarna (for klarna we need to check the payment experience rather than the payment method type) else if ( connector->ConnectorUtils.getConnectorNameTypeFromString == Processors(KLARNA) && available.payment_method_subtype->getPMTFromString == Klarna ) { switch available.payment_experience { | Some(str) => str == paymemtMethodExperience | None => false } } else if ( available.payment_method_subtype == paymemtMethodType && available.payment_method_subtype->getPMTFromString != Credit && available.payment_method_subtype->getPMTFromString != Debit ) { true } else { false } }, ) filterData->getValueFromArray(0, wasmDict->getPaymentMethodDictV2(key, connector)) } | None => wasmDict->getPaymentMethodDictV2(key, connector) } exisitngData }, ) let existingDataInDict = newDict->getArrayFromDict(pm, [])->getPaymentMethodMapper(connector, pm) newDict->Dict.set( pm, existingDataInDict->Array.concat(updatedData)->Identity.genericTypeToJson, ) }) newDict }, (initialValue, connector)) let formState: ReactFinalForm.formState = ReactFinalForm.useFormState( ReactFinalForm.useFormSubscription(["values"])->Nullable.make, ) let data = formState.values->getDictFromJsonObject let connData = ConnectorInterface.mapDictToConnectorPayload( ConnectorInterface.connectorInterfaceV2, data, ) <div className="flex flex-col gap-6 col-span-3"> <div className="max-w-3xl flex flex-col gap-8"> {paymentMethodValues ->Dict.keysToArray ->Array.mapWithIndex((pmValue, index) => { // determine the index of the payment method from the form state let isPMEnabled = connData.payment_methods_enabled->Array.findIndex(ele => ele.payment_method_type == pmValue ) let pmIndex = isPMEnabled == -1 ? connData.payment_methods_enabled->Array.length > 0 ? connData.payment_methods_enabled->Array.length : 0 : isPMEnabled switch pmValue->getPMFromString { | Card => <Card key={index->Int.toString} index pm=pmValue pmIndex paymentMethodValues connector isInEditState initialValues formValues=connData /> | _ => <OtherPaymentMethod key={index->Int.toString} index pm=pmValue pmIndex paymentMethodValues connector isInEditState initialValues formValues=connData /> } }) ->React.array} </div> </div> }
1,146
9,480
hyperswitch-control-center
src/fragments/ConnectorFragments/ConnectorPaymentMethodv2/ConnectorPaymentMethodV2Utils.res
.res
open ConnectorTypes open LogicUtils let getPMFromString = paymentMethod => { switch paymentMethod->String.toLowerCase { | "card" => Card | "debit" | "credit" => Card | "pay_later" => PayLater | "wallet" => Wallet | "bank_redirect" => BankRedirect | "bank_transfer" => BankTransfer | "crypto" => Crypto | "bank_debit" => BankDebit | _ => UnknownPaymentMethod(paymentMethod) } } let getPMTFromString = paymentMethodType => { switch paymentMethodType->String.toLowerCase { | "credit" => Credit | "debit" => Debit | "google_pay" => GooglePay | "apple_pay" => ApplePay | "paypal" => PayPal | "klarna" => Klarna | "open_banking_pis" => OpenBankingPIS | "samsung_pay" => SamsungPay | "paze" => Paze | "alipay" => AliPay | "wechatpay" => WeChatPay | "directcarrierbilling" => DirectCarrierBilling | _ => UnknownPaymentMethodType(paymentMethodType) } } let getPaymentExperience = (connector, pm, pmt, pme) => { switch pm->getPMFromString { | BankRedirect => None | _ => switch (ConnectorUtils.getConnectorNameTypeFromString(connector), pmt->getPMTFromString) { | (Processors(PAYPAL), PayPal) | (Processors(KLARNA), Klarna) => pme | (Processors(ZEN), GooglePay) | (Processors(ZEN), ApplePay) => Some("redirect_to_url") | (Processors(BRAINTREE), PayPal) => Some("invoke_sdk_client") | (Processors(GLOBALPAY), AliPay) | (Processors(GLOBALPAY), WeChatPay) | (Processors(STRIPE), WeChatPay) => Some("display_qr_code") | (_, GooglePay) | (_, ApplePay) | (_, SamsungPay) | (_, Paze) => Some("invoke_sdk_client") | (_, DirectCarrierBilling) => Some("collect_otp") | _ => Some("redirect_to_url") } } } let acceptedValues = dict => { let values = { type_: dict->getString("type", "enable_only"), list: dict->getStrArray("list"), } values.list->Array.length > 0 ? Some(values) : None } let getPaymentMethodDictV2 = (dict, pm, connector): ConnectorTypes.paymentMethodConfigTypeV2 => { let paymentMethodType = dict->getString("payment_method_subtype", dict->getString("payment_method_type", "")) let (cardNetworks, modifedPaymentMethodType) = switch pm->getPMTFromString { | Credit => { let cardNetworks = [paymentMethodType->JSON.Encode.string] let pmt = pm (cardNetworks, pmt) } | Debit => { let cardNetworks = [paymentMethodType->JSON.Encode.string] let pmt = pm (cardNetworks, pmt) } | _ => { let pmt = paymentMethodType ([], pmt) } } let cardNetworks = dict->getArrayFromDict("card_networks", cardNetworks) let minimumAmount = dict->getInt("minimum_amount", 0) let maximumAmount = dict->getInt("maximum_amount", 68607706) let recurringEnabled = dict->getBool("recurring_enabled", true) let installmentPaymentEnabled = dict->getBool("installment_payment_enabled", true) let paymentExperience = dict->getOptionString("payment_experience") let pme = getPaymentExperience(connector, pm, modifedPaymentMethodType, paymentExperience) let newPaymentMenthodDict = [ ("payment_method_subtype", modifedPaymentMethodType->JSON.Encode.string), ("card_networks", cardNetworks->JSON.Encode.array), ("minimum_amount", minimumAmount->JSON.Encode.int), ("maximum_amount", maximumAmount->JSON.Encode.int), ("recurring_enabled", recurringEnabled->JSON.Encode.bool), ("installment_payment_enabled", installmentPaymentEnabled->JSON.Encode.bool), ]->Dict.fromArray newPaymentMenthodDict->setOptionString("payment_experience", pme) newPaymentMenthodDict->ConnectorInterfaceUtils.getPaymentMethodTypesV2 } let getPaymentMethodMapper = (arr, connector, pm) => { arr->Array.map(val => { let dict = val->getDictFromJsonObject getPaymentMethodDictV2(dict, pm, connector) }) } let pmIcon = pm => switch pm->getPMFromString { | Card => "card" | PayLater => "pay_later" | Wallet => "nd-wallet" | BankRedirect | BankDebit | BankTransfer => "nd-bank" | _ => "" } let checkKlaranRegion = (connData: connectorPayloadV2) => switch connData.metadata ->getDictFromJsonObject ->getString("klarna_region", "") ->String.toLowerCase { | "europe" => true | _ => false } let pmtWithMetaData = [GooglePay, ApplePay, SamsungPay, Paze] let isMetaDataRequired = (pmt, connector) => { pmtWithMetaData->Array.includes(pmt->getPMTFromString) && { switch connector->ConnectorUtils.getConnectorNameTypeFromString { | Processors(TRUSTPAY) | Processors(STRIPE_TEST) => false | _ => true } } }
1,279
9,481
hyperswitch-control-center
src/fragments/ConnectorFragments/ConnectorPaymentMethodv2/PMSelectAll.res
.res
module PMSelectAll = { @react.component let make = ( ~availablePM: array<ConnectorTypes.paymentMethodConfigTypeV2>, ~fieldsArray: array<ReactFinalForm.fieldRenderProps>, ~pm, ~pmt, ) => { open LogicUtils open ConnectorPaymentMethodV2Utils let pmEnabledInp = (fieldsArray[0]->Option.getOr(ReactFinalForm.fakeFieldRenderProps)).input let pmEnabledValue = pmEnabledInp.value->getArrayDataFromJson(ConnectorInterfaceUtils.getPaymentMethodsEnabledV2) let pmArrayInp = (fieldsArray[1]->Option.getOr(ReactFinalForm.fakeFieldRenderProps)).input let (isSelectedAll, setIsSelectedAll) = React.useState(() => false) let removeAllPM = () => { if pm->getPMFromString == Card && pmt->getPMTFromString == Credit { let pmtData = pmEnabledValue->Array.find(ele => ele.payment_method_type == pm) let updatePMTData = switch pmtData { | Some(data) => data.payment_method_subtypes->Array.filter(ele => ele.payment_method_subtype->getPMTFromString != Credit ) | None => [] } let updatedData = [ ("payment_method_type", pm->JSON.Encode.string), ("payment_method_subtypes", updatePMTData->Identity.genericTypeToJson), ] ->Dict.fromArray ->Identity.anyTypeToReactEvent pmArrayInp.onChange(updatedData) } else if pm->getPMFromString == Card && pmt->getPMTFromString == Debit { let pmtData = pmEnabledValue->Array.find(ele => ele.payment_method_type == pm) let updatePMTData = switch pmtData { | Some(data) => data.payment_method_subtypes->Array.filter(ele => ele.payment_method_subtype->getPMTFromString != Debit ) | None => [] } let updatedData = [ ("payment_method_type", pm->JSON.Encode.string), ("payment_method_subtypes", updatePMTData->Identity.genericTypeToJson), ] ->Dict.fromArray ->Identity.anyTypeToReactEvent pmArrayInp.onChange(updatedData) } else { let updatedData = pmEnabledValue->Array.filter(ele => ele.payment_method_type != pm) pmEnabledInp.onChange(updatedData->Identity.anyTypeToReactEvent) } } let selectAllPM = () => { let pmtData = pmEnabledValue->Array.find(ele => ele.payment_method_type == pm) /* On "Select All" for credit: - Keep existing debit selections. - Add all credit payment methods. - Reason: Credit and debit are inside card PM. */ let updateData = if pm->getPMFromString == Card && pmt->getPMTFromString == Credit { let filterData = switch pmtData { | Some(data) => data.payment_method_subtypes ->Array.filter(ele => ele.payment_method_subtype->getPMTFromString != Credit) ->Array.concat(availablePM) | None => availablePM } filterData } else if pm->getPMFromString == Card && pmt->getPMTFromString == Debit { let filterData = switch pmtData { | Some(data) => data.payment_method_subtypes ->Array.filter(ele => ele.payment_method_subtype->getPMTFromString != Debit) ->Array.concat(availablePM) | None => availablePM } filterData } else { availablePM } let updatedData = [ ("payment_method_type", pm->JSON.Encode.string), ("payment_method_subtypes", updateData->Identity.genericTypeToJson), ] ->Dict.fromArray ->Identity.anyTypeToReactEvent pmArrayInp.onChange(updatedData) } let onClickSelectAll = isSelectedAll => { if isSelectedAll { selectAllPM() } else { removeAllPM() } setIsSelectedAll(_ => isSelectedAll) } let lengthoFPMSubTypes = pmArrayInp.value ->getDictFromJsonObject ->getArrayFromDict("payment_method_subtypes", []) ->Array.length React.useEffect(() => { let pmtData = pmEnabledValue->Array.find(ele => ele.payment_method_type == pm) let isPMEnabled = switch pmtData { | Some(data) => if pm->getPMFromString == Card && pmt->getPMTFromString == Credit { data.payment_method_subtypes ->Array.filter(ele => ele.payment_method_subtype->getPMTFromString == Credit) ->Array.length == availablePM->Array.length } else if pm->getPMFromString == Card && pmt->getPMTFromString == Debit { data.payment_method_subtypes ->Array.filter(ele => ele.payment_method_subtype->getPMTFromString == Debit) ->Array.length == availablePM->Array.length } else { data.payment_method_subtypes->Array.length == availablePM->Array.length } | None => false } setIsSelectedAll(_ => isPMEnabled) None }, [lengthoFPMSubTypes]) <div className="flex gap-2 items-center"> <p className="font-normal"> {"Select All"->React.string} </p> <BoolInput.BaseComponent isSelected={isSelectedAll} setIsSelected={isSelectedAll => onClickSelectAll(isSelectedAll)} isDisabled={false} boolCustomClass="rounded-lg" /> </div> } } let renderSelectAllValueInp = ( ~availablePM: array<ConnectorTypes.paymentMethodConfigTypeV2>, ~pm, ~pmt, ) => (fieldsArray: array<ReactFinalForm.fieldRenderProps>) => { <PMSelectAll availablePM fieldsArray pm pmt /> } let selectAllValueInput = ( ~availablePM: array<ConnectorTypes.paymentMethodConfigTypeV2>, ~pmIndex, ~pm, ~pmt, ) => { open FormRenderer makeMultiInputFieldInfoOld( ~label=``, ~comboCustomInput=renderSelectAllValueInp(~availablePM, ~pm, ~pmt), ~inputFields=[ makeInputFieldInfo(~name=`payment_methods_enabled`), makeInputFieldInfo(~name=`payment_methods_enabled[${pmIndex}]`), ], (), ) }
1,416
9,482
hyperswitch-control-center
src/fragments/ConnectorFragments/ConnectorPaymentMethodv2/Sections/Card.res
.res
module SelectedCardValues = { @react.component let make = (~initialValues, ~index) => { open LogicUtils open SectionHelper open ConnectorPaymentMethodV2Utils let data1 = initialValues->getDictFromJsonObject let data = ConnectorInterface.mapDictToConnectorPayload( ConnectorInterface.connectorInterfaceV2, data1, ) let cardData = data.payment_methods_enabled ->Array.filter(ele => ele.payment_method_type->getPMFromString == Card) ->Array.at(0) let credit = switch cardData { | Some(data) => data.payment_method_subtypes->Array.filter(ele => ele.payment_method_subtype->getPMTFromString == Credit ) | _ => [] } let debit = switch cardData { | Some(data) => data.payment_method_subtypes->Array.filter(ele => ele.payment_method_subtype->getPMTFromString == Debit ) | _ => [] } <> <SelectedPMT pmtData={credit} index pm="credit" /> <SelectedPMT pmtData={debit} index pm="debit" /> </> } } @react.component let make = ( ~index, ~pm, ~pmIndex, ~paymentMethodValues, ~connector, ~isInEditState, ~initialValues, ~formValues: ConnectorTypes.connectorPayloadV2, ) => { open LogicUtils open SectionHelper open ConnectorPaymentMethodV2Utils let data = paymentMethodValues ->getArrayFromDict("card", []) ->getPaymentMethodMapper(connector, pm) let credit = data->Array.filter(ele => ele.payment_method_subtype->getPMTFromString == Credit) let debit = data->Array.filter(ele => ele.payment_method_subtype->getPMTFromString == Debit) let paymentMethodTypeValues = formValues.payment_methods_enabled->Array.get(pmIndex) { if isInEditState { <> <div className="border border-nd_gray-150 rounded-xl overflow-hidden" key={`${index->Int.toString}-credit`}> <HeadingSection index pm availablePM=credit pmIndex pmt="credit" showSelectAll={true} /> <div className="flex gap-6 p-6 flex-wrap"> {credit ->Array.mapWithIndex((pmtData, i) => { // determine the index of the payment method type from the form state let pmtIndex = switch paymentMethodTypeValues { | Some(pmt) => { let isPMTEnabled = pmt.payment_method_subtypes->Array.findIndex(val => { if val.payment_method_subtype->getPMTFromString == Credit { val.card_networks->Array.some( networks => { pmtData.card_networks->Array.includes(networks) }, ) } else { false } }) isPMTEnabled == -1 ? pmt.payment_method_subtypes->Array.length : isPMTEnabled } | None => 0 } <PaymentMethodTypes pm pmtData pmIndex pmtIndex connector index=i label={pmtData.card_networks->Array.joinWith(",")} formValues /> }) ->React.array} </div> </div> <div className="border border-nd_gray-150 rounded-xl overflow-hidden" key={`${index->Int.toString}-debit`}> <HeadingSection index pm availablePM=debit pmIndex pmt="debit" showSelectAll={isInEditState} /> <div className="flex gap-6 p-6 flex-wrap"> {debit ->Array.mapWithIndex((pmtData, i) => { // determine the index of the payment method type from the form state let pmtIndex = switch paymentMethodTypeValues { | Some(pmt) => { let isPMTEnabled = pmt.payment_method_subtypes->Array.findIndex(val => { if val.payment_method_subtype->getPMTFromString == Debit { val.card_networks->Array.some( networks => { pmtData.card_networks->Array.includes(networks) }, ) } else { false } }) isPMTEnabled == -1 ? pmt.payment_method_subtypes->Array.length : isPMTEnabled } | None => 0 } <PaymentMethodTypes key={i->Int.toString} pm pmtData pmIndex pmtIndex connector index=i label={pmtData.card_networks->Array.joinWith(",")} formValues /> }) ->React.array} </div> </div> </> } else { <SelectedCardValues initialValues index /> } } }
1,066
9,483
hyperswitch-control-center
src/fragments/ConnectorFragments/ConnectorPaymentMethodv2/Sections/OtherPaymentMethod.res
.res
module SelectedCardValues = { @react.component let make = (~initialValues, ~index, ~pm) => { open LogicUtils open SectionHelper let data1 = initialValues->getDictFromJsonObject let data = ConnectorInterface.mapDictToConnectorPayload( ConnectorInterface.connectorInterfaceV2, data1, ) let paymentMethodData = data.payment_methods_enabled ->Array.filter(ele => ele.payment_method_type->String.toLowerCase == pm) ->Array.at(0) let pmtData = switch paymentMethodData { | Some(data) => data.payment_method_subtypes | _ => [] } <SelectedPMT pmtData index pm /> } } @react.component let make = ( ~index, ~pm, ~pmIndex, ~paymentMethodValues, ~connector, ~isInEditState, ~initialValues, ~formValues: ConnectorTypes.connectorPayloadV2, ) => { open LogicUtils open SectionHelper open AdditionalDetailsSidebar open ConnectorPaymentMethodV2Utils let formState: ReactFinalForm.formState = ReactFinalForm.useFormState( ReactFinalForm.useFormSubscription(["values"])->Nullable.make, ) let temp: array<ConnectorTypes.paymentMethodEnabled> = [ { payment_method: "", payment_method_type: "", }, ] let (meteDataInitialValues, connectorWalletsInitialValues) = React.useMemo(() => { ( formValues.metadata->Identity.genericTypeToJson, formValues.connector_webhook_details->Identity.genericTypeToJson, ) }, []) // let form = ReactFinalForm.useForm() let (showWalletConfigurationModal, setShowWalletConfigurationModal) = React.useState(_ => false) let (selectedWallet, setSelectedWallet) = React.useState(_ => Dict.make()->ConnectorInterfaceUtils.getPaymentMethodTypesV2 ) let (selectedPMTIndex, setSelectedPMTIndex) = React.useState(_ => 0) let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext) let data = formState.values->getDictFromJsonObject let connData: ConnectorTypes.connectorPayloadV2 = ConnectorInterface.mapDictToConnectorPayload( ConnectorInterface.connectorInterfaceV2, data, ) let availablePM = paymentMethodValues ->getArrayFromDict(pm, []) ->getPaymentMethodMapper(connector, pm) let showSelectAll = if ( pm->getPMFromString == Wallet || pm->getPMFromString == BankDebit || connector->ConnectorUtils.getConnectorNameTypeFromString == Processors(KLARNA) && connData->checkKlaranRegion || !isInEditState ) { false } else { true } let title = switch pm->getPMFromString { | BankDebit => pm->snakeToTitle | Wallet => selectedWallet.payment_method_subtype->snakeToTitle | _ => "" } let resetValues = () => { setShowWalletConfigurationModal(_ => false) // Need to refactor form.change("metadata", meteDataInitialValues->Identity.genericTypeToJson) form.change( "connector_wallets_details", connectorWalletsInitialValues->Identity.genericTypeToJson, ) // } let updateDetails = _val => { form.change( `payment_methods_enabled[${pmIndex->Int.toString}].payment_method_subtypes[${selectedPMTIndex->Int.toString}]`, selectedWallet->Identity.genericTypeToJson, ) form.change( `payment_methods_enabled[${pmIndex->Int.toString}].payment_method_type`, "wallet"->Identity.genericTypeToJson, ) } let onClick = (pmtData: ConnectorTypes.paymentMethodConfigTypeV2, pmtIndex) => { if isMetaDataRequired(pmtData.payment_method_subtype, connector) { setSelectedWallet(_ => pmtData) setSelectedPMTIndex(_ => pmtIndex) setShowWalletConfigurationModal(_ => true) } } let modalHeading = `Additional Details to enable ${title}` { if isInEditState { <div key={index->Int.toString} className="border border-nd_gray-150 rounded-xl overflow-hidden"> <HeadingSection index pm availablePM pmIndex pmt=pm showSelectAll /> <RenderIf condition={pm->getPMFromString === Wallet && { switch connector->ConnectorUtils.getConnectorNameTypeFromString { | Processors(ZEN) => true | _ => false } }}> <div className="border rounded p-2 bg-jp-gray-100 flex gap-4"> <Icon name="outage_icon" size=15 /> {"Zen doesn't support Googlepay and Applepay in sandbox."->React.string} </div> </RenderIf> <div className="flex gap-6 p-6 flex-wrap"> {availablePM ->Array.mapWithIndex((pmtData, i) => { let paymentMethodTypeValues = connData.payment_methods_enabled->Array.get(pmIndex) // determine the index of the payment method type from the form state let pmtIndex = switch paymentMethodTypeValues { | Some(pmt) => { let isPMTEnabled = pmt.payment_method_subtypes->Array.findIndex(val => val.payment_method_subtype == pmtData.payment_method_subtype ) isPMTEnabled == -1 ? pmt.payment_method_subtypes->Array.length : isPMTEnabled } | None => 0 } let label = switch ( pmtData.payment_method_subtype->getPMTFromString, pm->getPMFromString, connector->ConnectorUtils.getConnectorNameTypeFromString, ) { | (PayPal, Wallet, Processors(PAYPAL)) => pmtData.payment_experience->Option.getOr("") == "redirect_to_url" ? "PayPal Redirect" : "PayPal SDK" | (Klarna, PayLater, Processors(KLARNA)) => pmtData.payment_experience->Option.getOr("") == "redirect_to_url" ? "Klarna Checkout" : "Klarna SDK" | (OpenBankingPIS, _, _) => "Open Banking PIS" | _ => pmtData.payment_method_subtype->snakeToTitle } let showCheckbox = switch ( pmtData.payment_method_subtype->getPMTFromString, pm->getPMFromString, connector->ConnectorUtils.getConnectorNameTypeFromString, ) { | (Klarna, PayLater, Processors(KLARNA)) => !( pmtData.payment_experience->Option.getOr("") == "redirect_to_url" && connData->checkKlaranRegion ) | _ => true } <PaymentMethodTypes pm label pmtData pmIndex pmtIndex connector showCheckbox index=i onClick={Some(() => onClick(pmtData, pmtIndex))} formValues /> }) ->React.array} <RenderIf condition={pmtWithMetaData->Array.includes( selectedWallet.payment_method_subtype->getPMTFromString, )}> <Modal modalHeading headerTextClass={`${textColor.primaryNormal} font-bold text-xl`} headBgClass="sticky top-0 z-30 bg-white" showModal={showWalletConfigurationModal} setShowModal={setShowWalletConfigurationModal} onCloseClickCustomFun={resetValues} paddingClass="" revealFrom=Reveal.Right modalClass="w-full md:w-1/3 !h-full overflow-y-scroll !overflow-x-hidden rounded-none text-jp-gray-900" childClass={""}> <RenderIf condition={showWalletConfigurationModal}> // Need to refactor <AdditionalDetailsSidebarComp method={None} setMetaData={_ => ()} setShowWalletConfigurationModal updateDetails={_val => updateDetails(_val)} paymentMethodsEnabled=temp paymentMethod={pm} onCloseClickCustomFun={resetValues} setInitialValues={_ => ()} pmtName={selectedWallet.payment_method_subtype} /> </RenderIf> </Modal> </RenderIf> </div> </div> } else { <SelectedCardValues initialValues index=pmIndex pm /> } } }
1,851
9,484
hyperswitch-control-center
src/fragments/ConnectorFragments/ConnectorPaymentMethodv2/Sections/SectionHelper.res
.res
module Heading = { @react.component let make = (~heading) => { open ConnectorPaymentMethodV2Utils <div className="flex gap-2.5 items-center"> <div className="p-2 bg-white border rounded-md"> <Icon name={heading->pmIcon} /> </div> <p className="font-semibold"> {heading->LogicUtils.snakeToTitle->React.string} </p> </div> } } module PaymentMethodTypes = { @react.component let make = ( ~index, ~label, ~pmtData, ~pmIndex, ~pmtIndex, ~pm, ~connector, ~showCheckbox=true, ~onClick=None, ~formValues: ConnectorTypes.connectorPayloadV2, ) => { let handleClick = () => { switch onClick { | Some(onClick) => onClick() | None => () } } open FormRenderer <RenderIf key={index->Int.toString} condition={showCheckbox}> <AddDataAttributes key={index->Int.toString} attributes=[("data-testid", `${label}`)]> <div key={index->Int.toString} className={"flex gap-1.5 items-center"}> <div className="cursor-pointer" onClick={_ => handleClick()}> <FieldRenderer field={PMTSelection.valueInput( ~pmtData, ~pmIndex, ~pmtIndex=pmtIndex->Int.toString, ~pm, ~connector, ~formValues, )} /> </div> <p className="mt-4"> {label->React.string} </p> </div> </AddDataAttributes> </RenderIf> } } module HeadingSection = { @react.component let make = ( ~index, ~pm, ~availablePM: array<ConnectorTypes.paymentMethodConfigTypeV2>, ~pmIndex, ~pmt, ~showSelectAll, ) => { open FormRenderer <div className="flex justify-between bg-nd_gray-50 p-4 border-b"> <Heading heading=pmt /> <RenderIf condition={showSelectAll}> <div className="flex gap-2 items-center"> <AddDataAttributes key={index->Int.toString} attributes=[("data-testid", pm->String.concat("_")->String.concat("select_all"))]> <FieldRenderer field={PMSelectAll.selectAllValueInput( ~availablePM, ~pmIndex=pmIndex->Int.toString, ~pm, ~pmt, )} /> </AddDataAttributes> </div> </RenderIf> </div> } } module SelectedPMT = { @react.component let make = (~pmtData: array<ConnectorTypes.paymentMethodConfigTypeV2>, ~index, ~pm) => { open LogicUtils open ConnectorPaymentMethodV2Utils <RenderIf condition={pmtData->Array.length > 0}> <div className="border border-nd_gray-150 rounded-xl overflow-hidden" key={`${index->Int.toString}-debit`}> <div className="flex justify-between bg-nd_gray-50 p-4 border-b"> <Heading heading=pm /> </div> <div className="flex gap-8 p-6 flex-wrap"> {pmtData ->Array.mapWithIndex((data, i) => { let label = switch pm->getPMTFromString { | Credit | Debit => data.card_networks->Array.joinWith(",") | _ => data.payment_method_subtype->snakeToTitle } <AddDataAttributes key={i->Int.toString} attributes=[("data-testid", `${label}`)]> <div key={i->Int.toString} className={"flex gap-1.5 items-center"}> <p className="mt-4"> {label->React.string} </p> </div> </AddDataAttributes> }) ->React.array} </div> </div> </RenderIf> } }
898
9,485
hyperswitch-control-center
src/fragments/ConnectorFragments/ConnectorAuthKeys/ConnectorAuthKeysHelper.res
.res
let connectorsWithIntegrationSteps: array<ConnectorTypes.connectorTypes> = [ Processors(ADYEN), Processors(CHECKOUT), Processors(STRIPE), Processors(PAYPAL), ] module MultiConfigInp = { @react.component let make = (~label, ~fieldsArray: array<ReactFinalForm.fieldRenderProps>) => { let enabledList = (fieldsArray[0]->Option.getOr(ReactFinalForm.fakeFieldRenderProps)).input let valueField = (fieldsArray[1]->Option.getOr(ReactFinalForm.fakeFieldRenderProps)).input let input: ReactFinalForm.fieldRenderPropsInput = { name: "string", onBlur: _ => (), onChange: ev => { let value = ev->Identity.formReactEventToArrayOfString valueField.onChange(value->Identity.anyTypeToReactEvent) enabledList.onChange(value->Identity.anyTypeToReactEvent) }, onFocus: _ => (), value: enabledList.value, checked: true, } <TextInput input placeholder={`Enter ${label->LogicUtils.snakeToTitle}`} /> } } let renderValueInp = (~label) => (fieldsArray: array<ReactFinalForm.fieldRenderProps>) => { <MultiConfigInp fieldsArray label /> } let multiValueInput = (~label, ~fieldName1, ~fieldName2) => { open FormRenderer makeMultiInputFieldInfoOld( ~label, ~comboCustomInput=renderValueInp(~label), ~inputFields=[ makeInputFieldInfo(~name=`${fieldName1}`), makeInputFieldInfo(~name=`${fieldName2}`), ], (), ) } module ErrorValidation = { @react.component let make = (~fieldName, ~validate) => { open LogicUtils let formState: ReactFinalForm.formState = ReactFinalForm.useFormState( ReactFinalForm.useFormSubscription(["values"])->Nullable.make, ) let appPrefix = LogicUtils.useUrlPrefix() let imageStyle = "w-4 h-4 my-auto border-gray-100" let errorDict = formState.values->validate->getDictFromJsonObject let {touched} = ReactFinalForm.useField(fieldName).meta let err = touched ? errorDict->Dict.get(fieldName) : None <RenderIf condition={err->Option.isSome}> <div className={`flex flex-row items-center text-orange-950 dark:text-orange-400 pt-2 text-base font-medium text-start ml-1`}> <div className="flex mr-2"> <img className=imageStyle src={`${appPrefix}/icons/warning.svg`} alt="warning" /> </div> {React.string(err->Option.getOr(""->JSON.Encode.string)->getStringFromJson(""))} </div> </RenderIf> } } module RenderConnectorInputFields = { open ConnectorTypes @react.component let make = ( ~connector: connectorTypes, ~selectedConnector, ~details, ~name, ~keysToIgnore: array<string>=[], ~checkRequiredFields=?, ~getPlaceholder=?, ~isLabelNested=true, ~disabled=false, ~description="", ~labelTextStyleClass="", ~labelClass="font-semibold !text-hyperswitch_black", ) => { let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom // open ConnectorUtils open LogicUtils let keys = details->Dict.keysToArray->Array.filter(ele => !Array.includes(keysToIgnore, ele)) keys ->Array.mapWithIndex((field, i) => { let label = details->getString(field, "") let formName = isLabelNested ? `${name}.${field}` : name <RenderIf condition={label->isNonEmptyString} key={i->Int.toString}> <AddDataAttributes attributes=[("data-testid", label->titleToSnake->String.toLowerCase)]> <div key={label}> <FormRenderer.FieldRenderer labelClass labelTextStyleClass field={switch (connector, field) { | (Processors(PAYPAL), "key1") => multiValueInput( ~label, ~fieldName1="connector_account_details.key1", ~fieldName2="metadata.paypal_sdk.client_id", ) | _ => FormRenderer.makeFieldInfo( ~label, ~name=formName, ~description, ~toolTipPosition=Right, ~customInput=InputFields.textInput( ~isDisabled=disabled, ~customStyle="border rounded-xl", ), ~placeholder=switch getPlaceholder { | Some(fun) => fun(label) | None => `Enter ${label->LogicUtils.snakeToTitle}` }, ~isRequired=switch checkRequiredFields { | Some(fun) => fun(connector, field) | None => true }, ) }} /> <ErrorValidation fieldName=formName validate={ConnectorAuthKeyUtils.validate( ~selectedConnector, ~dict=details, ~fieldName=formName, ~isLiveMode={featureFlagDetails.isLiveMode}, )} /> </div> </AddDataAttributes> </RenderIf> }) ->React.array } } module CashToCodeSelectBox = { open ConnectorTypes @react.component let make = ( ~opts: array<string>, ~dict, ~selectedCashToCodeMthd: cashToCodeMthd, ~connector, ~selectedConnector, ) => { open LogicUtils let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext) let p2RegularTextStyle = `${HSwitchUtils.getTextClass((P2, Medium))} text-grey-700 opacity-50` let (showWalletConfigurationModal, setShowWalletConfigurationModal) = React.useState(_ => false) let (country, setSelectedCountry) = React.useState(_ => "") let selectedCountry = country => { setShowWalletConfigurationModal(_ => !showWalletConfigurationModal) setSelectedCountry(_ => country) } let formState: ReactFinalForm.formState = ReactFinalForm.useFormState( ReactFinalForm.useFormSubscription(["values"])->Nullable.make, ) let isSelected = (country): bool => { let formValues = formState.values ->getDictFromJsonObject ->getDictfromDict("connector_account_details") ->getDictfromDict("auth_key_map") ->getDictfromDict(country) let wasmValues = dict ->getDictfromDict(country) ->getDictfromDict((selectedCashToCodeMthd: cashToCodeMthd :> string)->String.toLowerCase) ->Dict.keysToArray wasmValues ->Array.find(ele => formValues->getString(ele, "")->String.length <= 0) ->Option.isNone } <div> {opts ->Array.mapWithIndex((country, index) => { <div key={index->Int.toString} className="flex items-center gap-2 break-words p-2"> <div onClick={_ => selectedCountry(country)}> <CheckBoxIcon isSelected={country->isSelected} /> </div> <p className=p2RegularTextStyle> {React.string(country->snakeToTitle)} </p> </div> }) ->React.array} <Modal modalHeading={`Additional Details to enable`} headerTextClass={`${textColor.primaryNormal} font-bold text-xl`} showModal={showWalletConfigurationModal} setShowModal={setShowWalletConfigurationModal} paddingClass="" revealFrom=Reveal.Right modalClass="w-full p-4 md:w-1/3 !h-full overflow-y-scroll !overflow-x-hidden rounded-none text-jp-gray-900" childClass={""}> <div> <RenderConnectorInputFields details={dict ->getDictfromDict(country) ->getDictfromDict( (selectedCashToCodeMthd: cashToCodeMthd :> string)->String.toLowerCase, )} name={`connector_account_details.auth_key_map.${country}`} connector selectedConnector /> <div className="flex flex-col justify-center mt-4"> <Button text={"Proceed"} buttonType=Primary onClick={_ => setShowWalletConfigurationModal(_ => false)} /> </div> </div> </Modal> </div> } } module CashToCodeMethods = { open ConnectorTypes @react.component let make = (~connectorAccountFields, ~selectedConnector, ~connector) => { open ConnectorUtils let dict = connectorAccountFields->getAuthKeyMapFromConnectorAccountFields let (selectedCashToCodeMthd, setCashToCodeMthd) = React.useState(_ => #Classic) let tabs = [#Classic, #Evoucher] let tabList: array<Tabs.tab> = tabs->Array.map(tab => { let tab: Tabs.tab = { title: (tab: cashToCodeMthd :> string), renderContent: () => <CashToCodeSelectBox opts={dict->Dict.keysToArray} dict={dict} selectedCashToCodeMthd connector selectedConnector />, } tab }) <Tabs tabs=tabList disableIndicationArrow=true showBorder=false includeMargin=false lightThemeColor="black" defaultClasses="font-ibm-plex w-max flex flex-auto flex-row items-center justify-center px-6 font-semibold text-body" onTitleClick={tabIndex => { setCashToCodeMthd(_ => tabs->LogicUtils.getValueFromArray(tabIndex, #Classic)) }} /> } } module ConnectorConfigurationFields = { open ConnectorTypes @react.component let make = ( ~connectorAccountFields, ~connector: connectorTypes, ~selectedConnector: integrationFields, ~isUpdateFlow=false, ~showVertically=true, ) => { <div className={`grid ${showVertically ? "grid-cols-1" : "grid-cols-2"} max-w-3xl gap-x-6 gap-y-3 `}> {switch connector { | Processors(CASHTOCODE) => <CashToCodeMethods connectorAccountFields connector selectedConnector /> | _ => <RenderConnectorInputFields details={connectorAccountFields} name={"connector_account_details"} getPlaceholder={ConnectorUtils.getPlaceHolder} connector selectedConnector /> }} </div> } }
2,344
9,486
hyperswitch-control-center
src/fragments/ConnectorFragments/ConnectorAuthKeys/ConnectorAuthKeys.res
.res
@react.component let make = ( ~initialValues, ~showVertically=true, ~processorType=ConnectorTypes.Processor, ~updateAccountDetails=true, ) => { open LogicUtils open ConnectorAuthKeysHelper let connector = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("name", "") let form = ReactFinalForm.useForm() let connectorTypeFromName = connector->ConnectorUtils.getConnectorNameTypeFromString(~connectorType=processorType) let selectedConnector = React.useMemo(() => { connectorTypeFromName->ConnectorUtils.getConnectorInfo }, [connector]) let (bodyType, connectorAccountFields) = React.useMemo(() => { try { if connector->isNonEmptyString { let dict = switch processorType { | Processor => Window.getConnectorConfig(connector) | PayoutProcessor => Window.getPayoutConnectorConfig(connector) | ThreeDsAuthenticator => Window.getAuthenticationConnectorConfig(connector) | PMAuthenticationProcessor => Window.getPMAuthenticationProcessorConfig(connector) | TaxProcessor => Window.getTaxProcessorConfig(connector) | BillingProcessor => BillingProcessorsUtils.getConnectorConfig(connector) | FRMPlayer => JSON.Encode.null } let connectorAccountDict = dict->getDictFromJsonObject->getDictfromDict("connector_auth") let bodyType = connectorAccountDict->Dict.keysToArray->getValueFromArray(0, "") let connectorAccountFields = connectorAccountDict->getDictfromDict(bodyType) (bodyType, connectorAccountFields) } else { ("", Dict.make()) } } catch { | Exn.Error(e) => { Js.log2("FAILED TO LOAD CONNECTOR AUTH KEYS CONFIG", e) ("", Dict.make()) } } }, [selectedConnector]) React.useEffect(() => { let updatedValues = initialValues->JSON.stringify->safeParse->getDictFromJsonObject if updateAccountDetails { let acc = [("auth_type", bodyType->JSON.Encode.string)] ->Dict.fromArray ->JSON.Encode.object let _ = updatedValues->Dict.set("connector_account_details", acc) } form.reset(updatedValues->JSON.Encode.object->Nullable.make) None }, [connector]) <ConnectorConfigurationFields connector={connectorTypeFromName} connectorAccountFields selectedConnector showVertically /> }
518
9,487
hyperswitch-control-center
src/fragments/ConnectorFragments/ConnectorAuthKeys/ConnectorAuthKeyUtils.res
.res
let validateRequiredFiled = (valuesFlattenJson, dict, fieldName, errors) => { open LogicUtils let newDict = getDictFromJsonObject(errors) dict ->Dict.keysToArray ->Array.forEach(_value => { let lastItem = fieldName->String.split(".")->Array.pop->Option.getOr("") let errorKey = dict->getString(lastItem, "") let value = valuesFlattenJson->getString(`${fieldName}`, "") if value->String.length === 0 { Dict.set(newDict, fieldName, `Please enter ${errorKey}`->JSON.Encode.string) } }) newDict->JSON.Encode.object } let validate = ( ~selectedConnector: ConnectorTypes.integrationFields, ~dict, ~fieldName, ~isLiveMode, ) => values => { let errors = Dict.make() let valuesFlattenJson = values->JsonFlattenUtils.flattenObject(true) let labelArr = dict->Dict.valuesToArray selectedConnector.validate ->Option.getOr([]) ->Array.forEachWithIndex((field, index) => { let key = field.name let value = valuesFlattenJson ->Dict.get(key) ->Option.getOr(""->JSON.Encode.string) ->LogicUtils.getStringFromJson("") let regexToUse = isLiveMode ? field.liveValidationRegex : field.testValidationRegex let validationResult = switch regexToUse { | Some(regex) => regex->RegExp.fromString->RegExp.test(value) | None => true } if field.isRequired->Option.getOr(true) && value->String.length === 0 { let errorLabel = labelArr ->Array.get(index) ->Option.getOr(""->JSON.Encode.string) ->LogicUtils.getStringFromJson("") Dict.set(errors, key, `Please enter ${errorLabel}`->JSON.Encode.string) } else if !validationResult && value->String.length !== 0 { let expectedFormat = isLiveMode ? field.liveExpectedFormat : field.testExpectedFormat let warningMessage = expectedFormat->Option.getOr("") Dict.set(errors, key, warningMessage->JSON.Encode.string) } }) let profileId = valuesFlattenJson->LogicUtils.getString("profile_id", "") if profileId->String.length === 0 { Dict.set(errors, "Profile Id", `Please select your business profile`->JSON.Encode.string) } validateRequiredFiled(valuesFlattenJson, dict, fieldName, errors->JSON.Encode.object) }
534
9,488
hyperswitch-control-center
src/fragments/ConnectorFragments/ConnectorLabel/ConnectorLabelV2.res
.res
@react.component let make = ( ~labelTextStyleClass="", ~labelClass="font-semibold", ~isInEditState, ~connectorInfo: ConnectorTypes.connectorPayloadV2, ) => { open LogicUtils open ConnectorHelperV2 let labelFieldDict = ConnectorFragmentUtils.connectorLabelDetailField let label = labelFieldDict->getString("connector_label", "") if isInEditState { <FormRenderer.FieldRenderer labelClass field={FormRenderer.makeFieldInfo( ~label, ~name="connector_label", ~placeholder="Enter Connector Label name", ~customInput=InputFields.textInput(~customStyle="rounded-xl "), ~isRequired=true, )} labelTextStyleClass /> } else { <InfoField label str={connectorInfo.connector_label} /> } }
181
9,489
hyperswitch-control-center
src/fragments/ConnectorFragments/ConnectorWebhookDetails/ConnectorWebhookPreview.res
.res
@react.component let make = ( ~merchantId, ~connectorName, ~textCss="", ~showFullText=false, ~showFullCopy=false, ~containerClass="flex", ~hideLabel=false, ~displayTextLength=?, ~truncateDisplayValue=false, ) => { let showToast = ToastState.useShowToast() let copyValueOfWebhookEndpoint = `${Window.env.apiBaseUrl}/webhooks/${merchantId}/${connectorName}` let displayValueOfWebhookEndpoint = `${Window.env.apiBaseUrl}...${connectorName}` let baseurl = `${Window.env.apiBaseUrl}` let shortDisplayValueofWebhookEndpoint = `${baseurl->String.slice( ~start=0, ~end=9, )}...${connectorName}` let displayValueOfWebhookEndpoint = switch displayTextLength { | Some(end) => copyValueOfWebhookEndpoint ->String.slice(~start=0, ~end) ->String.concat("...") | _ => displayValueOfWebhookEndpoint->String.slice( ~start=0, ~end=displayValueOfWebhookEndpoint->String.length, ) } let handleWebHookCopy = copyValue => { Clipboard.writeText(copyValue) showToast(~message="Copied to Clipboard!", ~toastType=ToastSuccess) } let valueOfWebhookEndPoint = { if showFullText { copyValueOfWebhookEndpoint } else if truncateDisplayValue { shortDisplayValueofWebhookEndpoint } else { displayValueOfWebhookEndpoint } } <div className="flex flex-col gap-2"> <RenderIf condition={!hideLabel}> <h4 className="text-nd_gray-400 "> {"Webhook Url"->React.string} </h4> </RenderIf> <div className=containerClass> <p className=textCss> {valueOfWebhookEndPoint->React.string} </p> <div className="ml-2"> <RenderIf condition={!showFullCopy}> <div onClick={_ => handleWebHookCopy(copyValueOfWebhookEndpoint)}> <Icon name="nd-copy" /> </div> </RenderIf> <RenderIf condition={showFullCopy}> <Button leftIcon={CustomIcon(<Icon name="nd-copy" />)} text="Copy" customButtonStyle="ml-4 w-5" onClick={_ => handleWebHookCopy(copyValueOfWebhookEndpoint)} /> </RenderIf> </div> </div> </div> }
566
9,490
hyperswitch-control-center
src/fragments/ConnectorFragments/ConnectorWebhookDetails/ConnectorWebhookDetails.res
.res
@react.component let make = ( ~showVertically=true, ~labelTextStyleClass="", ~labelClass="font-semibold ", ~isInEditState, ~connectorInfo: ConnectorTypes.connectorPayloadV2, ~processorType=ConnectorTypes.Processor, ) => { open LogicUtils open ConnectorHelperV2 let connector = UrlUtils.useGetFilterDictFromUrl("")->getString("name", "") let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let connectorTypeFromName = connector->ConnectorUtils.getConnectorNameTypeFromString(~connectorType=processorType) let selectedConnector = React.useMemo(() => { connectorTypeFromName->ConnectorUtils.getConnectorInfo }, [connector]) let connectorWebHookDetails = React.useMemo(() => { try { if connector->isNonEmptyString { let dict = switch processorType { | Processor => Window.getConnectorConfig(connector) | PayoutProcessor => Window.getPayoutConnectorConfig(connector) | ThreeDsAuthenticator => Window.getAuthenticationConnectorConfig(connector) | PMAuthenticationProcessor => Window.getPMAuthenticationProcessorConfig(connector) | TaxProcessor => Window.getTaxProcessorConfig(connector) | BillingProcessor => BillingProcessorsUtils.getConnectorConfig(connector) | FRMPlayer => JSON.Encode.null } dict->getDictFromJsonObject->getDictfromDict("connector_webhook_details") } else { Dict.make() } } catch { | Exn.Error(e) => { Js.log2("FAILED TO LOAD CONNECTOR WEBHOOK CONFIG", e) Dict.make() } } }, [selectedConnector]) let checkIfRequired = (connector, field) => { ConnectorUtils.getWebHookRequiredFields(connector, field) } let webHookDetails = connectorInfo.connector_webhook_details->getDictFromJsonObject let keys = connectorWebHookDetails->Dict.keysToArray <> {keys ->Array.mapWithIndex((field, index) => { let label = connectorWebHookDetails->getString(field, "") let value = webHookDetails->getString(field, "") <RenderIf key={index->Int.toString} condition={label->String.length > 0}> <div> {if isInEditState { <> <FormRenderer.FieldRenderer labelClass field={FormRenderer.makeFieldInfo( ~label, ~name={`connector_webhook_details.${field}`}, ~placeholder={label}, ~customInput=InputFields.textInput(~customStyle="rounded-xl "), ~isRequired=checkIfRequired(connectorTypeFromName, field), )} labelTextStyleClass /> <ConnectorAuthKeysHelper.ErrorValidation fieldName={`connector_webhook_details.${field}`} validate={ConnectorUtils.validate( ~selectedConnector, ~dict=connectorWebHookDetails, ~fieldName={`connector_webhook_details.${field}`}, ~isLiveMode={featureFlagDetails.isLiveMode}, )} /> </> } else { <RenderIf condition={value->String.length > 0}> <InfoField label str={value} /> </RenderIf> }} </div> </RenderIf> }) ->React.array} </> }
714
9,491
hyperswitch-control-center
src/fragments/ConnectorFragments/ConnectorMetadataV2/ConnectorMetadataV2.res
.res
@react.component let make = ( ~labelTextStyleClass="", ~labelClass="font-semibold !text-hyperswitch_black", ~isInEditState, ~connectorInfo: ConnectorTypes.connectorPayloadV2, ~processorType=ConnectorTypes.Processor, ) => { open LogicUtils open ConnectorMetaDataUtils open ConnectorHelperV2 let connector = UrlUtils.useGetFilterDictFromUrl("")->LogicUtils.getString("name", "") let connectorTypeFromName = connector->ConnectorUtils.getConnectorNameTypeFromString(~connectorType=processorType) let selectedConnector = React.useMemo(() => { connectorTypeFromName->ConnectorUtils.getConnectorInfo }, [connector]) let connectorMetaDataFields = React.useMemo(() => { try { if connector->isNonEmptyString { let dict = switch processorType { | Processor => Window.getConnectorConfig(connector) | PayoutProcessor => Window.getPayoutConnectorConfig(connector) | ThreeDsAuthenticator => Window.getAuthenticationConnectorConfig(connector) | PMAuthenticationProcessor => Window.getPMAuthenticationProcessorConfig(connector) | TaxProcessor => Window.getTaxProcessorConfig(connector) | BillingProcessor => BillingProcessorsUtils.getConnectorConfig(connector) | FRMPlayer => JSON.Encode.null } dict->getDictFromJsonObject->getDictfromDict("metadata") } else { Dict.make() } } catch { | Exn.Error(e) => { Js.log2("FAILED TO LOAD CONNECTOR METADATA CONFIG", e) Dict.make() } } }, [selectedConnector]) let keys = connectorMetaDataFields ->Dict.keysToArray ->Array.filter(ele => !Array.includes(metaDataInputKeysToIgnore, ele)) <> {keys ->Array.mapWithIndex((field, index) => { let fields = connectorMetaDataFields ->getDictfromDict(field) ->JSON.Encode.object ->convertMapObjectToDict ->CommonConnectorUtils.inputFieldMapper let {\"type", name, label} = fields let value = switch \"type" { | Text | Select | Toggle => connectorInfo.metadata->getDictFromJsonObject->getString(name, "") | _ => "" } { if isInEditState { <FormRenderer.FieldRenderer key={index->Int.toString} labelClass field={ConnectorHelperV2.connectorMetaDataValueInput(~connectorMetaDataFields={fields})} labelTextStyleClass /> } else { <RenderIf key={index->Int.toString} condition={value->isNonEmptyString}> <InfoField label str=value /> </RenderIf> } } }) ->React.array} </> }
596
9,492
hyperswitch-control-center
src/screens/HSwitchRemoteFilter.res
.res
type filterBody = { start_time: string, end_time: string, } let formateDateString = date => { date->Date.toISOString->TimeZoneHook.formattedISOString("YYYY-MM-DDTHH:mm:ss[Z]") } let getDateFilteredObject = (~range=7) => { let currentDate = Date.make() let end_time = currentDate->formateDateString let start_time = Js.Date.makeWithYMD( ~year=currentDate->Js.Date.getFullYear, ~month=currentDate->Js.Date.getMonth, ~date=currentDate->Js.Date.getDate, (), ) ->Js.Date.setDate((currentDate->Js.Date.getDate->Float.toInt - range)->Int.toFloat) ->Js.Date.fromFloat ->formateDateString { start_time, end_time, } } let useSetInitialFilters = ( ~updateExistingKeys, ~startTimeFilterKey, ~endTimeFilterKey, ~compareToStartTimeKey="", ~compareToEndTimeKey="", ~enableCompareTo=None, ~comparisonKey="", ~isInsightsPage=false, ~range=7, ~origin, (), ) => { open NewAnalyticsTypes let {filterValueJson} = FilterContext.filterContext->React.useContext () => { let inititalSearchParam = Dict.make() let defaultDate = getDateFilteredObject(~range) if filterValueJson->Dict.keysToArray->Array.length < 1 { let timeRange = origin !== "analytics" ? [(startTimeFilterKey, defaultDate.start_time)] : switch enableCompareTo { | Some(_) => { let ( compareToStartTime, compareToEndTime, ) = DateRangeUtils.getComparisionTimePeriod( ~startDate=defaultDate.start_time, ~endDate=defaultDate.end_time, ) [ (startTimeFilterKey, defaultDate.start_time), (endTimeFilterKey, defaultDate.end_time), (compareToStartTimeKey, compareToStartTime), (compareToEndTimeKey, compareToEndTime), (comparisonKey, (DateRangeUtils.DisableComparison :> string)), ] } | None => [ (startTimeFilterKey, defaultDate.start_time), (endTimeFilterKey, defaultDate.end_time), ] } if isInsightsPage { timeRange->Array.push(( (#currency: filters :> string), (#all_currencies: defaultFilters :> string), )) } timeRange->Array.forEach(item => { let (key, defaultValue) = item switch inititalSearchParam->Dict.get(key) { | Some(_) => () | None => inititalSearchParam->Dict.set(key, defaultValue) } }) inititalSearchParam->updateExistingKeys } } } module SearchBarFilter = { @react.component let make = (~placeholder, ~setSearchVal, ~searchVal) => { let (baseValue, setBaseValue) = React.useState(_ => "") let onChange = ev => { let value = ReactEvent.Form.target(ev)["value"] setBaseValue(_ => value) } React.useEffect(() => { let onKeyPress = event => { let keyPressed = event->ReactEvent.Keyboard.key if keyPressed == "Enter" { setSearchVal(_ => baseValue) } } Window.addEventListener("keydown", onKeyPress) Some(() => Window.removeEventListener("keydown", onKeyPress)) }, [baseValue]) React.useEffect(() => { if baseValue->String.length === 0 && searchVal->LogicUtils.isNonEmptyString { setSearchVal(_ => baseValue) } None }, [baseValue]) let inputSearch: ReactFinalForm.fieldRenderPropsInput = { name: "name", onBlur: _ => (), onChange, onFocus: _ => (), value: baseValue->JSON.Encode.string, checked: true, } <div className="w-max"> {InputFields.textInput( ~customStyle="rounded-lg placeholder:opacity-90", ~customPaddingClass="px-0", ~leftIcon=<Icon size=14 name="search" />, ~iconOpacity="opacity-100", ~leftIconCustomStyle="pl-4", ~inputStyle="!placeholder:opacity-90", ~customWidth="w-72", )(~input=inputSearch, ~placeholder)} </div> } } module RemoteTableFilters = { @react.component let make = ( ~apiType: Fetch.requestMethod=Get, ~setFilters, ~endTimeFilterKey, ~startTimeFilterKey, ~compareToStartTimeKey="", ~compareToEndTimeKey="", ~comparisonKey="", ~initialFilters, ~initialFixedFilter, ~setOffset, ~customLeftView, ~title="", ~submitInputOnEnter=false, ~entityName: APIUtilsTypes.entityTypeWithVersion, ~version=UserInfoTypes.V1, (), ) => { open LogicUtils open APIUtils let getURL = useGetURL() let {userInfo: transactionEntity} = React.useContext(UserInfoProvider.defaultContext) let { filterValue, updateExistingKeys, filterValueJson, reset, setfilterKeys, filterKeys, removeKeys, } = FilterContext.filterContext->React.useContext let defaultFilters = {""->JSON.Encode.string} let showToast = ToastState.useShowToast() React.useEffect(() => { if filterValueJson->Dict.keysToArray->Array.length === 0 { setFilters(_ => Some(Dict.make())) setOffset(_ => 0) } None }, []) let (filterDataJson, setFilterDataJson) = React.useState(_ => None) let updateDetails = useUpdateMethod() let defaultDate = getDateFilteredObject(~range=30) let start_time = filterValueJson->getString(startTimeFilterKey, defaultDate.start_time) let end_time = filterValueJson->getString(endTimeFilterKey, defaultDate.end_time) let fetchDetails = useGetMethod() let fetchAllFilters = async () => { try { let filterUrl = getURL(~entityName, ~methodType=apiType) setFilterDataJson(_ => None) let response = switch apiType { | Post => { let body = [ (startTimeFilterKey, start_time->JSON.Encode.string), (endTimeFilterKey, end_time->JSON.Encode.string), ]->getJsonFromArrayOfJson await updateDetails(filterUrl, body, Post, ~version) } | _ => await fetchDetails(filterUrl) } setFilterDataJson(_ => Some(response)) } catch { | _ => showToast(~message="Failed to load filters", ~toastType=ToastError) } } React.useEffect(() => { fetchAllFilters()->ignore None }, [transactionEntity]) let filterData = filterDataJson->Option.getOr(Dict.make()->JSON.Encode.object) let setInitialFilters = useSetInitialFilters( ~updateExistingKeys, ~startTimeFilterKey, ~endTimeFilterKey, ~compareToStartTimeKey, ~compareToEndTimeKey, ~comparisonKey, ~range=30, ~origin="orders", (), ) React.useEffect(() => { if filterValueJson->Dict.keysToArray->Array.length < 1 { setInitialFilters() } None }, [filterValueJson]) React.useEffect(() => { if filterValueJson->Dict.keysToArray->Array.length != 0 { setFilters(_ => Some(filterValueJson)) setOffset(_ => 0) } else { setFilters(_ => Some(Dict.make())) setOffset(_ => 0) } None }, [filterValue]) let dict = Recoil.useRecoilValueFromAtom(LoadedTable.sortAtom) let defaultSort: LoadedTable.sortOb = { sortKey: "", sortType: DSC, } let value = dict->Dict.get(title)->Option.getOr(defaultSort) React.useEffect(() => { if value.sortKey->isNonEmptyString { filterValue->Dict.set("filter", "") filterValue->updateExistingKeys } None }, [value->OrderTypes.getSortString, value.sortKey]) let getAllFilter = filterValue ->Dict.toArray ->Array.map(item => { let (key, value) = item (key, value->UrlFetchUtils.getFilterValue) }) ->Dict.fromArray let remoteFilters = React.useMemo(() => { filterData->initialFilters(getAllFilter, removeKeys, filterKeys, setfilterKeys) }, [getAllFilter]) let initialDisplayFilters = remoteFilters->Array.filter((item: EntityType.initialFilters<'t>) => item.localFilter->Option.isSome ) let remoteOptions = [] switch filterDataJson { | Some(_) => <Filter key="0" customLeftView defaultFilters fixedFilters={initialFixedFilter()} requiredSearchFieldsList=[] localFilters={initialDisplayFilters} localOptions=[] remoteOptions remoteFilters autoApply=false submitInputOnEnter defaultFilterKeys=[startTimeFilterKey, endTimeFilterKey] updateUrlWith={updateExistingKeys} clearFilters={() => reset()} title /> | _ => <Filter key="1" customLeftView defaultFilters fixedFilters={initialFixedFilter()} requiredSearchFieldsList=[] localFilters=[] localOptions=[] remoteOptions=[] remoteFilters=[] autoApply=false submitInputOnEnter defaultFilterKeys=[startTimeFilterKey, endTimeFilterKey] updateUrlWith={updateExistingKeys} clearFilters={() => reset()} title /> } } }
2,158
9,493
hyperswitch-control-center
src/screens/HSwitchUtilsTypes.res
.res
type browserDetailsObject = { userAgent: string, browserVersion: string, platform: string, browserName: string, browserLanguage: string, screenHeight: string, screenWidth: string, timeZoneOffset: string, clientCountry: Country.timezoneType, } type pageLevelVariant = | HOME | PAYMENTS | REFUNDS | DISPUTES | CONNECTOR | ROUTING | ANALYTICS_PAYMENTS | ANALYTICS_REFUNDS | SETTINGS | DEVELOPERS type textVariantType = | H1 | H2 | H3 | P1 | P2 | P3 type subVariantType = Regular | Medium | Leading_1 | Leading_2 | Optional type bannerType = Success | Warning | Error | Info
188
9,494
hyperswitch-control-center
src/screens/HSLocalStorage.res
.res
let getInfoFromLocalStorage = (~lStorageKey) => { let stringifiedJson = LocalStorage.getItem(lStorageKey)->LogicUtils.getValFromNullableValue("") stringifiedJson->LogicUtils.safeParse->LogicUtils.getDictFromJsonObject } let getBooleanFromLocalStorage = (~key) => { let stringifiedJson = LocalStorage.getItem(key)->LogicUtils.getValFromNullableValue("") stringifiedJson->LogicUtils.safeParse->LogicUtils.getBoolFromJson(false) } let getFromUserDetails = key => { getInfoFromLocalStorage(~lStorageKey="user")->LogicUtils.getString(key, "") } let getIsPlaygroundFromLocalStorage = () => { getBooleanFromLocalStorage(~key="isPlayground") } let setIsPlaygroundInLocalStorage = (val: bool) => { LocalStorage.setItem("isPlayground", val->JSON.Encode.bool->JSON.stringify) } let removeItemFromLocalStorage = (~key) => { LocalStorage.removeItem(key) }
204
9,495
hyperswitch-control-center
src/screens/MixpanelHook.res
.res
type functionType = (~eventName: string=?, ~email: string=?, ~description: option<string>=?) => unit let useSendEvent = () => { open GlobalVars open Window let fetchApi = AuthHooks.useApiFetcher() let {userInfo: {email: authInfoEmail, merchantId, name}} = React.useContext( UserInfoProvider.defaultContext, ) let deviceId = switch LocalStorage.getItem("deviceId")->Nullable.toOption { | Some(id) => id | None => authInfoEmail } let parseEmail = email => { email->String.length == 0 ? authInfoEmail : email } let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let {clientCountry} = HSwitchUtils.getBrowswerDetails() let country = clientCountry.isoAlpha2->CountryUtils.getCountryCodeStringFromVarient let environment = GlobalVars.hostType->getEnvironment let url = RescriptReactRouter.useUrl() let getUrlEndpoint = () => { switch GlobalVars.dashboardBasePath { | Some(_) => url.path->List.toArray->Array.get(1)->Option.getOr("") | _ => url.path->List.toArray->Array.get(0)->Option.getOr("") } } let trackApi = async ( ~email, ~merchantId, ~description, ~event, ~section, ~metadata=JSON.Encode.null, ) => { let mixpanel_token = Window.env.mixpanelToken let body = { "event": event, "properties": { "section": section, "metadata": metadata, "token": mixpanel_token, "distinct_id": deviceId, "$device_id": deviceId->String.split(":")->Array.get(1), "$screen_height": Screen.screenHeight, "$screen_width": Screen.screenWidth, "name": email, "merchantName": name, "email": email, "mp_lib": "restapi", "merchantId": merchantId, "environment": environment, "description": description, "lang": Navigator.browserLanguage, "$os": Navigator.platform, "$browser": Navigator.browserName, "mp_country_code": country, }, } try { let _ = await fetchApi( `${getHostUrl}/mixpanel/track`, ~method_=Post, ~bodyStr=`data=${body->JSON.stringifyAny->Option.getOr("")->encodeURI}`, ~xFeatureRoute=featureFlagDetails.xFeatureRoute, ~forceCookies=featureFlagDetails.forceCookies, ) } catch { | _ => () } } (~eventName, ~email="", ~description=None, ~section="", ~metadata=JSON.Encode.null) => { let section = section->LogicUtils.isNonEmptyString ? section : getUrlEndpoint() let eventName = eventName->String.toLowerCase if featureFlagDetails.mixpanel { trackApi( ~email={email->parseEmail}, ~merchantId, ~description, ~event={eventName}, ~section, ~metadata, )->ignore } } } let usePageView = () => { open GlobalVars open Window let fetchApi = AuthHooks.useApiFetcher() let {getUserInfoData} = React.useContext(UserInfoProvider.defaultContext) let environment = GlobalVars.hostType->getEnvironment let {clientCountry} = HSwitchUtils.getBrowswerDetails() let country = clientCountry.isoAlpha2->CountryUtils.getCountryCodeStringFromVarient let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom async (~path) => { let mixpanel_token = Window.env.mixpanelToken let {email, merchantId, name} = getUserInfoData() let body = { "event": "page_view", "properties": { "token": mixpanel_token, "distinct_id": email, "$device_id": email->String.split(":")->Array.get(1), "$screen_height": Screen.screenHeight, "$screen_width": Screen.screenWidth, "name": email, "merchantName": name, "email": email, "mp_lib": "restapi", "merchantId": merchantId, "environment": environment, "lang": Navigator.browserLanguage, "$os": Navigator.platform, "$browser": Navigator.browserName, "mp_country_code": country, "page": path, }, } try { if featureFlagDetails.mixpanel { let _ = await fetchApi( `${getHostUrl}/mixpanel/track`, ~method_=Post, ~bodyStr=`data=${body->JSON.stringifyAny->Option.getOr("")->encodeURI}`, ~xFeatureRoute=featureFlagDetails.xFeatureRoute, ~forceCookies=featureFlagDetails.forceCookies, ) } } catch { | _ => () } } } let useSetIdentity = () => { open GlobalVars let fetchApi = AuthHooks.useApiFetcher() let mixpanel_token = Window.env.mixpanelToken let featureFlagDetails = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom async (~distinctId) => { let name = distinctId->LogicUtils.getNameFromEmail let body = { "event": `$identify`, "properties": { "distinct_id": distinctId, "token": mixpanel_token, }, } let peopleProperties = { "$token": mixpanel_token, "$distinct_id": distinctId, "$set": { "$email": distinctId, "$first_name": name, }, } try { if featureFlagDetails.mixpanel { let _ = await fetchApi( `${getHostUrl}/mixpanel/track`, ~method_=Post, ~bodyStr=`data=${body->JSON.stringifyAny->Option.getOr("")->encodeURI}`, ~xFeatureRoute=featureFlagDetails.xFeatureRoute, ~forceCookies=featureFlagDetails.forceCookies, ) let _ = await fetchApi( `${getHostUrl}/mixpanel/engage`, ~method_=Post, ~bodyStr=`data=${peopleProperties->JSON.stringifyAny->Option.getOr("")->encodeURI}`, ~xFeatureRoute=featureFlagDetails.xFeatureRoute, ~forceCookies=featureFlagDetails.forceCookies, ) } } catch { | _ => () } } }
1,415
9,496
hyperswitch-control-center
src/screens/PendingInvitationsHome.res
.res
module InviteForMultipleInvitation = { @react.component let make = ( ~pendingInvites: array<PreLoginTypes.invitationResponseType>, ~acceptInvite, ~showModal, ~setShowModal, ) => { open LogicUtils let (acceptedInvites, setAcceptedInvites) = React.useState(_ => JSON.Encode.null->getArrayDataFromJson(PreLoginUtils.itemToObjectMapper) ) let acceptInviteOnClick = ele => setAcceptedInvites(_ => [...acceptedInvites, ele]) let checkIfInvitationAccepted = (entityId, entityType: UserInfoTypes.entity) => { acceptedInvites->Array.find(value => value.entityId === entityId && value.entityType === entityType ) } <div className="w-full bg-white px-6 py-3 flex items-center justify-between"> <div className="flex items-center gap-3"> <Icon size=40 name="group-users-without-circle" /> <div> {`You have `->React.string} <span className="font-bold"> {pendingInvites->Array.length->React.int} </span> <span> {` Pending Invites`->React.string} </span> </div> </div> <Button text="View Invitations" buttonType=SecondaryFilled customButtonStyle="!p-2" onClick={_ => setShowModal(_ => true)} /> <Modal showModal setShowModal paddingClass="" closeOnOutsideClick=true onCloseClickCustomFun={_ => ()} modalHeading="Pending Invitations" modalHeadingDescription="Please accept your pending merchant invitations" modalClass="w-1/2 m-auto !bg-white" childClass="my-5 mx-4 overflow-scroll !h-[35%]"> <div className="flex flex-col gap-4"> <div className="flex flex-col gap-10"> {pendingInvites ->Array.mapWithIndex((ele, index) => { <div className="w-full bg-white p-6 flex items-center justify-between border-1 rounded-xl !shadow-[0_2px_4px_0_rgba(0,0,0,_0.05)]" key={index->Int.toString}> <div className="flex items-center justify-between w-full"> <div className="flex items-center gap-3"> <Icon size=40 name="group-users-without-circle" /> <div> {`You've been invited to `->React.string} <span className="font-bold"> {( ele.entityName->isNonEmptyString ? ele.entityName : ele.entityId )->React.string} </span> {` as `->React.string} <span className="font-bold"> {ele.roleId->snakeToTitle->React.string} </span> </div> </div> {switch checkIfInvitationAccepted(ele.entityId, ele.entityType) { | Some(_) => <div className="flex items-center gap-1 text-green-accepted_green_800"> <Icon name="green-tick-without-background" /> {"Accepted"->React.string} </div> | None => <Button text="Accept" buttonType={PrimaryOutline} customButtonStyle="!p-2" onClick={_ => acceptInviteOnClick(ele)->ignore} /> }} </div> </div> }) ->React.array} </div> <div className="flex items-center justify-center"> <Button text="Accept Invites" buttonType={Primary} onClick={_ => { acceptInvite(acceptedInvites)->ignore }} buttonState={acceptedInvites->Array.length > 0 ? Normal : Disabled} /> </div> </div> </Modal> </div> } } module InviteForSingleInvitation = { @react.component let make = (~pendingInvites, ~acceptInvite) => { open LogicUtils let inviteValue = pendingInvites->getValueFromArray(0, Dict.make()->PreLoginUtils.itemToObjectMapper) <div className="w-full bg-white px-6 py-3 flex items-center justify-between"> <div className="flex items-center gap-3"> <Icon size=40 name="group-users-without-circle" /> <div> {`You've been invited to `->React.string} <span className="font-bold"> {( inviteValue.entityName->isNonEmptyString ? inviteValue.entityName : inviteValue.entityId )->React.string} </span> {` as `->React.string} <span className="font-bold"> {inviteValue.roleId->snakeToTitle->React.string} </span> </div> </div> <Button text="Accept" buttonType={PrimaryOutline} customButtonStyle="!p-2" onClick={_ => acceptInvite([inviteValue])->ignore} /> </div> } } @react.component let make = (~setAppScreenState) => { open APIUtils open LogicUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let (showModal, setShowModal) = React.useState(_ => false) let showToast = ToastState.useShowToast() let fetchDetails = useGetMethod() let (pendingInvites, setPendingInvites) = React.useState(_ => []) let getListOfMerchantIds = async () => { try { let url = getURL(~entityName=V1(USERS), ~userType=#LIST_INVITATION, ~methodType=Get) let listOfMerchants = await fetchDetails(url) setPendingInvites(_ => listOfMerchants->getArrayDataFromJson(PreLoginUtils.itemToObjectMapper) ) } catch { | _ => showToast(~message="Failed to fetch pending invitations!", ~toastType=ToastError) } } let acceptInvite = async acceptedInvitesArray => { try { setAppScreenState(_ => PageLoaderWrapper.Loading) let url = getURL(~entityName=V1(USERS), ~userType=#ACCEPT_INVITATION_HOME, ~methodType=Post) let body = acceptedInvitesArray ->Array.map((value: PreLoginTypes.invitationResponseType) => { let acceptedinvite: PreLoginTypes.acceptInviteRequest = { entity_id: value.entityId, entity_type: (value.entityType :> string)->String.toLowerCase, } acceptedinvite }) ->Identity.genericTypeToJson let _ = await updateDetails(url, body, Post) setShowModal(_ => false) getListOfMerchantIds()->ignore setAppScreenState(_ => Success) } catch { | _ => showToast(~message="Failed to accept invitations!", ~toastType=ToastError) } } React.useEffect(() => { getListOfMerchantIds()->ignore None }, []) <RenderIf condition={pendingInvites->Array.length !== 0}> <RenderIf condition={pendingInvites->Array.length === 1}> <InviteForSingleInvitation pendingInvites acceptInvite /> </RenderIf> <RenderIf condition={pendingInvites->Array.length > 1}> <InviteForMultipleInvitation pendingInvites acceptInvite showModal setShowModal /> </RenderIf> </RenderIf> }
1,634
9,497
hyperswitch-control-center
src/screens/HSwitchUtils.res
.res
open LogicUtils open HSLocalStorage open HyperswitchAtom module TextFieldRow = { @react.component let make = (~label, ~children, ~isRequired=true, ~labelWidth="w-72") => { <div className="flex mt-5"> <div className={`mt-2 ${labelWidth} text-gray-900/50 dark:text-jp-gray-text_darktheme dark:text-opacity-50 font-semibold text-fs-14`}> {label->React.string} <RenderIf condition={isRequired}> <span className="text-red-500"> {"*"->React.string} </span> </RenderIf> </div> children </div> } } module BackgroundImageWrapper = { @react.component let make = ( ~children=?, ~backgroundImageUrl="/images/hyperswitchImages/PostLoginBackground.svg", ~customPageCss="", ~isBackgroundFullScreen=true, ) => { let heightWidthCss = isBackgroundFullScreen ? "h-screen w-screen" : "h-full w-full" <RenderIf condition={children->Option.isSome}> <div className={`bg-no-repeat bg-center bg-hyperswitch_dark_bg bg-fixed ${customPageCss} ${heightWidthCss}`} style={ backgroundImage: `url(${backgroundImageUrl})`, backgroundSize: `cover`, }> {children->Option.getOr(React.null)} </div> </RenderIf> } } let feedbackModalOpenCountForConnectors = 4 let errorClass = "text-sm leading-4 font-medium text-start ml-1 mt-2" let getSearchOptionsForProcessors = (~processorList, ~getNameFromString) => { let searchOptionsForProcessors = processorList->Array.map(item => ( `Connect ${item->getNameFromString->capitalizeString}`, `/new?name=${item->getNameFromString}`, )) searchOptionsForProcessors } let isValidEmail = value => !RegExp.test( %re(`/^(([^<>()[\]\.,;:\s@"]+(\.[^<>()[\]\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/`), value, ) // TODO : Remove once user-management flow introduces let setUserDetails = (key, value) => { let localStorageData = getInfoFromLocalStorage(~lStorageKey="user") localStorageData->Dict.set(key, value) "user"->LocalStorage.setItem(localStorageData->JSON.stringifyAny->Option.getOr("")) } let useMerchantDetailsValue = () => Recoil.useRecoilValueFromAtom(merchantDetailsValueAtom) let getClientCountry = clientTimeZone => { Country.country ->Array.find(item => item.timeZones->Array.find(i => i == clientTimeZone)->Option.isSome) ->Option.getOr(Country.defaultTimeZone) } let getBrowswerDetails = () => { open Window open Window.Navigator open Window.Screen open HSwitchUtilsTypes let clientTimeZone = dateTimeFormat().resolvedOptions().timeZone let clientCountry = clientTimeZone->getClientCountry { userAgent, browserVersion, platform, browserName, browserLanguage, screenHeight, screenWidth, timeZoneOffset, clientCountry, } } let getBodyForFeedBack = (~email, ~values, ~modalType=HSwitchFeedBackModalUtils.FeedBackModal) => { open HSwitchFeedBackModalUtils let valueDict = values->getDictFromJsonObject let rating = valueDict->getInt("rating", 1) let bodyFields = [("email", email->JSON.Encode.string)] switch modalType { | FeedBackModal => bodyFields ->Array.pushMany([ ("category", valueDict->getString("category", "")->JSON.Encode.string), ("description", valueDict->getString("feedbacks", "")->JSON.Encode.string), ("rating", rating->Float.fromInt->JSON.Encode.float), ]) ->ignore | RequestConnectorModal => bodyFields ->Array.pushMany([ ("category", "request_connector"->JSON.Encode.string), ( "description", `[${valueDict->getString("connector_name", "")}]-[${valueDict->getString( "description", "", )}]`->JSON.Encode.string, ), ]) ->ignore } bodyFields->Dict.fromArray } let getMetaData = (newMetadata, metaData) => { switch newMetadata { | Some(data) => data | None => metaData } } let returnIntegrationJson = (integrationData: ProviderTypes.integration): JSON.t => { [ ("is_done", integrationData.is_done->JSON.Encode.bool), ("metadata", integrationData.metadata), ]->getJsonFromArrayOfJson } let constructOnboardingBody = ( ~dashboardPageState, ~integrationDetails: ProviderTypes.integrationDetailsType, ~is_done: bool, ~metadata: option<JSON.t>=?, ) => { let copyOfIntegrationDetails = integrationDetails switch dashboardPageState { | #INTEGRATION_DOC => { copyOfIntegrationDetails.integration_checklist.is_done = is_done copyOfIntegrationDetails.integration_checklist.metadata = getMetaData( metadata, copyOfIntegrationDetails.integration_checklist.metadata, ) } | #AUTO_CONNECTOR_INTEGRATION => { copyOfIntegrationDetails.connector_integration.is_done = is_done copyOfIntegrationDetails.connector_integration.metadata = getMetaData( metadata, copyOfIntegrationDetails.connector_integration.metadata, ) copyOfIntegrationDetails.pricing_plan.is_done = is_done copyOfIntegrationDetails.pricing_plan.metadata = getMetaData( metadata, copyOfIntegrationDetails.pricing_plan.metadata, ) } | #HOME => { copyOfIntegrationDetails.account_activation.is_done = is_done copyOfIntegrationDetails.account_activation.metadata = getMetaData( metadata, copyOfIntegrationDetails.account_activation.metadata, ) } | _ => () } [ ( "integration_checklist", copyOfIntegrationDetails.integration_checklist->returnIntegrationJson, ), ( "connector_integration", copyOfIntegrationDetails.connector_integration->returnIntegrationJson, ), ("pricing_plan", copyOfIntegrationDetails.pricing_plan->returnIntegrationJson), ("account_activation", copyOfIntegrationDetails.account_activation->returnIntegrationJson), ]->getJsonFromArrayOfJson } let getTextClass = variantType => { open HSwitchUtilsTypes switch variantType { | (H1, Optional) => "text-fs-28 font-semibold leading-10" | (H2, Optional) => "text-2xl font-semibold leading-8" | (H3, Leading_1) => "text-xl font-semibold leading-7" | (H3, Leading_2) => "text-lg font-semibold leading-7" | (P1, Regular) => "text-base font-normal leading-6" | (P1, Medium) => "text-base font-medium leading-6" | (P2, Regular) => "text-sm font-normal leading-5" | (P2, Medium) => "text-sm font-medium leading-5" | (P3, Regular) => "text-xs font-normal leading-4" | (P3, Medium) => "text-xs font-medium leading-4" | (_, _) => "" } } let noAccessControlText = "You do not have the required permissions to access this module. Please contact your admin." let noAccessControlTextForProcessors = "You do not have the required permissions to connect this processor. Please contact admin." let urlPath = urlPathList => { open GlobalVars switch dashboardBasePath { | Some(_) => switch urlPathList { | list{_, ...rest} => rest | _ => urlPathList } | _ => urlPathList } } let getConnectorIDFromUrl = (urlList, defaultValue) => { open GlobalVars switch dashboardBasePath { | Some(_) => if urlList->Array.includes("v2") { urlList->Array.get(4)->Option.getOr(defaultValue) } else { urlList->Array.get(2)->Option.getOr(defaultValue) } | _ => urlList->Array.get(1)->Option.getOr(defaultValue) } } module AlertBanner = { @react.component let make = (~bannerText, ~bannerType: HSwitchUtilsTypes.bannerType, ~children=?) => { let bgClass = switch bannerType { | Success => " bg-green-100" | Warning => "bg-orange-100" | Error => "bg-red-100" | Info => "bg-blue-150" } let iconName = switch bannerType { | Success => "green-tick-banner" | Warning => "warning-banner" | Error => "cross-banner" | Info => "info-banner" } <div className={`${bgClass} flex justify-between border border-none w-full py-4 px-4 rounded-md`}> <div className="flex items-center gap-4"> <Icon name=iconName size=20 /> {bannerText->React.string} </div> <div> {switch children { | Some(child) => child | None => React.null }} </div> </div> } }
2,116
9,498
hyperswitch-control-center
src/screens/Sidebar/SidebarSwitch.res
.res
module OrgMerchantSwitchCollapsed = { @react.component let make = () => { let {userInfo: {orgId, merchantId}} = React.useContext(UserInfoProvider.defaultContext) let style = "p-2 mx-auto my-0.5 text-white font-semibold fs-20 ring-1 ring-blue-800 ring-opacity-15 rounded uppercase " <div className="flex flex-col gap-2"> <div className={style}> {orgId->String.slice(~start=0, ~end=1)->React.string} </div> <div className={style}> {merchantId->String.slice(~start=0, ~end=1)->React.string} </div> </div> } } @react.component let make = (~isSidebarExpanded=false) => { let {userInfo: {roleId}} = React.useContext(UserInfoProvider.defaultContext) let {globalUIConfig: {sidebarColor: {borderColor}}} = React.useContext(ThemeProvider.themeContext) let isInternalUser = roleId->HyperSwitchUtils.checkIsInternalUser let expandedContent = { <RenderIf condition={!isInternalUser}> <div className={`flex justify-start items-center px-6 mt-7 border-b pb-4 ${borderColor}`}> <MerchantSwitch /> </div> </RenderIf> } <> <RenderIf condition={isSidebarExpanded}> expandedContent </RenderIf> <RenderIf condition={!isSidebarExpanded}> <OrgMerchantSwitchCollapsed /> </RenderIf> </> }
332
9,499
hyperswitch-control-center
src/screens/Sidebar/SidebarProvider.res
.res
open ProviderTypes let defaultValue = { isSidebarExpanded: false, setIsSidebarExpanded: _ => (), } let defaultContext = React.createContext(defaultValue) module Provider = { let make = React.Context.provider(defaultContext) } @react.component let make = (~children) => { let (isSidebarExpanded, setIsSidebarExpanded) = React.useState(_ => false) <Provider value={ isSidebarExpanded, setIsSidebarExpanded, }> children </Provider> }
106
9,500
hyperswitch-control-center
src/screens/Sidebar/SidebarTypes.res
.res
type optionType = { name: string, icon: string, link: string, access: CommonAuthTypes.authorization, searchOptions?: array<(string, string)>, remoteIcon?: bool, selectedIcon?: string, } type optionTypeWithTag = { name: string, icon: string, iconTag: string, iconStyles?: string, iconSize?: int, link: string, access: CommonAuthTypes.authorization, searchOptions?: array<(string, string)>, } type nestedOption = { name: string, link: string, access: CommonAuthTypes.authorization, searchOptions?: array<(string, string)>, remoteIcon?: bool, iconTag?: string, iconStyles?: string, iconSize?: int, } type subLevelItem = SubLevelLink(nestedOption) type sectionType = { name: string, icon: string, links: array<subLevelItem>, showSection: bool, selectedIcon?: string, } type headingType = { name: string, icon?: string, iconTag?: string, iconStyles?: string, iconSize?: int, } type customComponentType = {component: React.element} type topLevelItem = | CustomComponent(customComponentType) | Heading(headingType) | RemoteLink(optionType) | Link(optionType) | LinkWithTag(optionTypeWithTag) | Section(sectionType) type urlRoute = Local(string) | Remote(string) | LocalSection(array<(string, string)>)
331
9,501
hyperswitch-control-center
src/screens/Sidebar/OrgSidebar.res
.res
module OrgTile = { @react.component let make = ( ~orgID: string, ~isActive, ~orgSwitch, ~orgName: string, ~index: int, ~currentlyEditingId: option<int>, ~handleIdUnderEdit, ) => { open LogicUtils open APIUtils let {userHasAccess} = GroupACLHooks.useUserGroupACLHook() let getURL = useGetURL() let updateDetails = useUpdateMethod() let fetchDetails = useGetMethod() let showToast = ToastState.useShowToast() let setOrgList = Recoil.useSetRecoilState(HyperswitchAtom.orgListAtom) let {userInfo: {orgId}} = React.useContext(UserInfoProvider.defaultContext) let { globalUIConfig: { sidebarColor: {backgroundColor, primaryTextColor, secondaryTextColor, borderColor}, }, } = React.useContext(ThemeProvider.themeContext) let sortByOrgName = (org1: OMPSwitchTypes.ompListTypes, org2: OMPSwitchTypes.ompListTypes) => { compareLogic(org2.name->String.toLowerCase, org1.name->String.toLowerCase) } let getOrgList = async () => { try { let url = getURL(~entityName=V1(USERS), ~userType=#LIST_ORG, ~methodType=Get) let response = await fetchDetails(url) let orgData = response->getArrayDataFromJson(OMPSwitchUtils.orgItemToObjMapper) orgData->Array.sort(sortByOrgName) setOrgList(_ => orgData) } catch { | _ => { setOrgList(_ => [OMPSwitchUtils.ompDefaultValue(orgId, "")]) showToast(~message="Failed to fetch organisation list", ~toastType=ToastError) } } } let onSubmit = async (newOrgName: string) => { try { let values = {"organization_name": newOrgName}->Identity.genericTypeToJson let url = getURL(~entityName=V1(UPDATE_ORGANIZATION), ~methodType=Put, ~id=Some(orgID)) let _ = await updateDetails(url, values, Put) let _ = await getOrgList() showToast(~message="Updated organization name!", ~toastType=ToastSuccess) } catch { | _ => showToast(~message="Failed to update organization name!", ~toastType=ToastError) } } let validateInput = (organizationName: string) => { let errors = Dict.make() let regexForOrganizationName = "^([a-z]|[A-Z]|[0-9]|_|\\s)+$" let errorMessage = if organizationName->LogicUtils.isEmptyString { "Organization name cannot be empty" } else if organizationName->String.length > 64 { "Organization name cannot exceed 64 characters" } else if !RegExp.test(RegExp.fromString(regexForOrganizationName), organizationName) { "Organization name should not contain special characters" } else { "" } if errorMessage->LogicUtils.isNonEmptyString { errors->Dict.set("organizationName", errorMessage) } errors } let displayText = { let firstLetter = orgName->String.charAt(0)->String.toUpperCase if orgName == orgID { orgID ->String.slice(~start=orgID->String.length - 2, ~end=orgID->String.length) ->String.toUpperCase } else { firstLetter } } let isUnderEdit = currentlyEditingId->Option.isSome && currentlyEditingId->Option.getOr(0) == index let isEditingAnotherIndex = currentlyEditingId->Option.isSome && currentlyEditingId->Option.getOr(0) != index // Hover label and visibility class let hoverLabel1 = !isUnderEdit ? `group/parent` : `` let hoverInput2 = !isUnderEdit ? `invisible group-hover/parent:visible` : `` // Common CSS let baseCSS = `absolute max-w-xs left-full top-0 rounded-md z-50 shadow-md ${backgroundColor.sidebarSecondary}` let currentEditCSS = isUnderEdit ? `p-2 ${baseCSS} border-grey-400 border-opacity-40` : `${baseCSS} ${hoverInput2} shadow-lg ` let nonEditCSS = !isEditingAnotherIndex ? `p-2` : `` let ringClass = switch isActive { | true => "border-blue-811 ring-blue-811/20 ring-offset-0 ring-2" | false => "ring-grey-outline" } let handleClick = () => { if !isActive { orgSwitch(orgID)->ignore } } <div onClick={_ => handleClick()} className={`w-10 h-10 rounded-lg flex items-center justify-center relative cursor-pointer ${hoverLabel1} `}> <div className={`w-8 h-8 border cursor-pointer flex items-center justify-center rounded-md shadow-md ${ringClass} ${isActive ? `bg-white/20 ${primaryTextColor} border-sidebar-primaryTextColor` : ` ${secondaryTextColor} hover:bg-white/10 border-sidebar-secondaryTextColor/30`}`}> <span className="text-xs font-medium"> {displayText->React.string} </span> <div className={` ${currentEditCSS} ${nonEditCSS} border ${borderColor} border-opacity-40 `}> <InlineEditInput index labelText={orgName} subText={"Organization"} customStyle={` p-3 !h-12 ${backgroundColor.sidebarSecondary} ${hoverInput2}`} showEditIconOnHover=false customInputStyle={`${backgroundColor.sidebarSecondary} ${secondaryTextColor} text-sm h-4 ${hoverInput2} `} customIconComponent={<ToolTip description={orgID} customStyle="!whitespace-nowrap" toolTipFor={<div className="cursor-pointer"> <HelperComponents.CopyTextCustomComp customIconCss={`${secondaryTextColor}`} displayValue=Some("") copyValue=Some({orgID}) /> </div>} toolTipPosition=ToolTip.Right />} showEditIcon={isActive && userHasAccess(~groupAccess=OrganizationManage) === Access} handleEdit=handleIdUnderEdit isUnderEdit displayHoverOnEdit={currentlyEditingId->Option.isNone} validateInput labelTextCustomStyle={`${secondaryTextColor} truncate max-w-40`} customWidth="min-w-64" customIconStyle={`${secondaryTextColor}`} onSubmit /> </div> </div> </div> } } module NewOrgCreationModal = { @react.component let make = (~setShowModal, ~showModal, ~getOrgList) => { open APIUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let mixpanelEvent = MixpanelHook.useSendEvent() let showToast = ToastState.useShowToast() let createNewOrg = async values => { try { let url = getURL(~entityName=V1(USERS), ~userType=#CREATE_ORG, ~methodType=Post) mixpanelEvent(~eventName="create_new_org", ~metadata=values) let _ = await updateDetails(url, values, Post) getOrgList()->ignore showToast(~toastType=ToastSuccess, ~message="Org Created Successfully!", ~autoClose=true) } catch { | _ => showToast(~toastType=ToastError, ~message="Org Creation Failed", ~autoClose=true) } setShowModal(_ => false) Nullable.null } let onSubmit = (values, _) => { createNewOrg(values) } let orgName = FormRenderer.makeFieldInfo( ~label="Org Name", ~name="organization_name", ~placeholder="Eg: My New Org", ~customInput=InputFields.textInput(), ~isRequired=true, ) let merchantName = FormRenderer.makeFieldInfo( ~label="Merchant Name", ~name="merchant_name", ~placeholder="Eg: My New Merchant", ~customInput=InputFields.textInput(), ~isRequired=true, ) let validateForm = ( ~values: JSON.t, ~fieldstoValidate: array<OMPSwitchTypes.addOrgFormFields>, ) => { open LogicUtils let errors = Dict.make() let regexForOrgName = "^([a-z]|[A-Z]|[0-9]|_|\\s)+$" fieldstoValidate->Array.forEach(field => { let name = switch field { | OrgName => "Org" | MerchantName => "Merchant" } let value = switch field { | OrgName => "organization_name" | MerchantName => "merchant_name" } let fieldValue = values->getDictFromJsonObject->getString(value, "")->String.trim let errorMsg = if fieldValue->isEmptyString { `${name} name cannot be empty` } else if fieldValue->String.length > 64 { `${name} name too long` } else if !RegExp.test(RegExp.fromString(regexForOrgName), fieldValue) { `${name} name should not contain special characters` } else { "" } if errorMsg->isNonEmptyString { Dict.set(errors, value, errorMsg->JSON.Encode.string) } }) errors->JSON.Encode.object } let modalBody = { <div className="p-2 m-2"> <div className="py-5 px-3 flex justify-between align-top "> <CardUtils.CardHeader heading="Add a new org" subHeading="" customSubHeadingStyle="w-full !max-w-none pr-10" /> <div className="h-fit" onClick={_ => setShowModal(_ => false)}> <Icon name="close" className="border-2 p-2 rounded-2xl bg-gray-100 cursor-pointer" size=30 /> </div> </div> <Form key="new-org-creation" onSubmit validate={values => validateForm(~values, ~fieldstoValidate=[OrgName, MerchantName])}> <div className="flex flex-col gap-12 h-full w-full"> <FormRenderer.DesktopRow> <div className="flex flex-col gap-5"> <FormRenderer.FieldRenderer fieldWrapperClass="w-full" field={orgName} showErrorOnChange=true errorClass={ProdVerifyModalUtils.errorClass} labelClass="!text-black font-medium !-ml-[0.5px]" /> <FormRenderer.FieldRenderer fieldWrapperClass="w-full" field={merchantName} showErrorOnChange=true errorClass={ProdVerifyModalUtils.errorClass} labelClass="!text-black font-medium !-ml-[0.5px]" /> </div> </FormRenderer.DesktopRow> <div className="flex justify-end w-full pr-5 pb-3"> <FormRenderer.SubmitButton text="Add Org" buttonSize={Small} /> </div> </div> </Form> </div> } <Modal showModal closeOnOutsideClick=true setShowModal childClass="p-0" borderBottom=true modalClass="w-full max-w-xl mx-auto my-auto dark:!bg-jp-gray-lightgray_background"> modalBody </Modal> } } @react.component let make = () => { open APIUtils open LogicUtils open OMPSwitchUtils open OMPSwitchHelper let getURL = useGetURL() let fetchDetails = useGetMethod() let (orgList, setOrgList) = Recoil.useRecoilState(HyperswitchAtom.orgListAtom) let (showSwitchingOrg, setShowSwitchingOrg) = React.useState(_ => false) let (showEditOrgModal, setShowEditOrgModal) = React.useState(_ => false) let internalSwitch = OMPSwitchHooks.useInternalSwitch() let {userInfo: {orgId, roleId}} = React.useContext(UserInfoProvider.defaultContext) let {tenantUser} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let (showAddOrgModal, setShowAddOrgModal) = React.useState(_ => false) let isTenantAdmin = roleId->HyperSwitchUtils.checkIsTenantAdmin let isInternalUser = roleId->HyperSwitchUtils.checkIsInternalUser let showToast = ToastState.useShowToast() let sortByOrgName = (org1: OMPSwitchTypes.ompListTypes, org2: OMPSwitchTypes.ompListTypes) => { compareLogic(org2.name->String.toLowerCase, org1.name->String.toLowerCase) } let { globalUIConfig: {sidebarColor: {backgroundColor, hoverColor, secondaryTextColor, borderColor}}, } = React.useContext(ThemeProvider.themeContext) let getOrgList = async () => { try { let url = getURL(~entityName=V1(USERS), ~userType=#LIST_ORG, ~methodType=Get) let response = await fetchDetails(url) let orgData = response->getArrayDataFromJson(orgItemToObjMapper) orgData->Array.sort(sortByOrgName) setOrgList(_ => orgData) } catch { | _ => { setOrgList(_ => [ompDefaultValue(orgId, "")]) showToast(~message="Failed to fetch organisation list", ~toastType=ToastError) } } } React.useEffect(() => { if !isInternalUser { getOrgList()->ignore } else { setOrgList(_ => [ompDefaultValue(orgId, "")]) } None }, []) let orgSwitch = async value => { try { setShowSwitchingOrg(_ => true) let _ = await internalSwitch(~expectedOrgId=Some(value), ~changePath=true) setShowSwitchingOrg(_ => false) } catch { | _ => { showToast(~message="Failed to switch organisation", ~toastType=ToastError) setShowSwitchingOrg(_ => false) } } } let (currentlyEditingId, setUnderEdit) = React.useState(_ => None) let handleIdUnderEdit = (selectedEditId: option<int>) => { setUnderEdit(_ => selectedEditId) } <div className={`${backgroundColor.sidebarNormal} p-2 border-r w-14 ${borderColor}`}> // the org tiles <div className="flex flex-col gap-5 py-3 px-2 items-center justify-center "> {orgList ->Array.mapWithIndex((org, i) => { <OrgTile key={Int.toString(i)} orgID={org.id} isActive={org.id === orgId} orgSwitch orgName={org.name} index={i} handleIdUnderEdit currentlyEditingId /> }) ->React.array} <RenderIf condition={tenantUser && isTenantAdmin}> <div onClick={_ => setShowAddOrgModal(_ => true)} className={`w-8 h-8 mt-2 flex items-center justify-center cursor-pointer rounded-md border shadow-sm ${hoverColor} border-${backgroundColor.sidebarSecondary}`}> <Icon name="plus" size=20 className={secondaryTextColor} /> </div> </RenderIf> </div> <RenderIf condition={showAddOrgModal}> <NewOrgCreationModal setShowModal={setShowAddOrgModal} showModal={showAddOrgModal} getOrgList /> </RenderIf> <EditOrgName showModal={showEditOrgModal} setShowModal={setShowEditOrgModal} orgList orgId getOrgList /> <RenderIf condition={showAddOrgModal}> <NewOrgCreationModal setShowModal={setShowAddOrgModal} showModal={showAddOrgModal} getOrgList /> </RenderIf> <LoaderModal showModal={showSwitchingOrg} setShowModal={setShowSwitchingOrg} text="Switching organisation..." /> </div> }
3,565
9,502
hyperswitch-control-center
src/screens/Sidebar/Sidebar.res
.res
open HeadlessUI open SidebarTypes let defaultLinkSelectionCheck = (firstPart, tabLink) => { firstPart->LogicUtils.removeTrailingSlash === tabLink->LogicUtils.removeTrailingSlash } let getIconSize = buttonType => { switch buttonType { | "large" => 42 | "larger" => 65 | _ => 20 } } module MenuOption = { @react.component let make = (~text=?, ~children=?, ~onClick=?) => { let {globalUIConfig: {sidebarColor: {backgroundColor, secondaryTextColor}}} = React.useContext( ThemeProvider.themeContext, ) <button className={`px-4 py-3 flex text-sm w-full ${secondaryTextColor} cursor-pointer ${backgroundColor.sidebarSecondary} hover:bg-black/10`} ?onClick> {switch text { | Some(str) => React.string(str) | None => React.null }} {switch children { | Some(elem) => elem | None => React.null }} </button> } } module SidebarOption = { @react.component let make = (~isSidebarExpanded, ~name, ~icon, ~isSelected, ~selectedIcon=icon) => { let {globalUIConfig: {sidebarColor: {primaryTextColor, secondaryTextColor}}} = React.useContext( ThemeProvider.themeContext, ) let textBoldStyles = isSelected ? `${primaryTextColor} font-semibold` : `${secondaryTextColor} font-medium ` let iconColor = isSelected ? `${primaryTextColor}` : `${secondaryTextColor} ` let iconName = isSelected ? selectedIcon : icon if isSidebarExpanded { <div className="flex items-center gap-5"> <Icon size=18 name=iconName className=iconColor /> <div className={`text-sm ${textBoldStyles} whitespace-nowrap`}> {React.string(name)} </div> </div> } else { <Icon size=18 name=iconName className=iconColor /> } } } module SidebarSubOption = { @react.component let make = (~name, ~isSectionExpanded, ~isSelected, ~children=React.null, ~isSideBarExpanded) => { let {globalUIConfig: {sidebarColor: {hoverColor}}} = React.useContext( ThemeProvider.themeContext, ) let subOptionClass = isSelected ? `${hoverColor}` : "" let alignmentClasses = children == React.null ? "" : "flex flex-row items-center" <div className={`text-sm w-full ${alignmentClasses} ${isSectionExpanded ? "transition duration-[250ms] animate-textTransitionSideBar" : "transition duration-[1000ms] animate-textTransitionSideBarOff"} ${isSideBarExpanded ? "mx-2" : "mx-1"} border-light_grey `}> <div className="w-8" /> <div className={`${subOptionClass} w-full py-2.5 px-3 flex items-center ${hoverColor} whitespace-nowrap my-1 rounded-lg`}> {React.string(name)} {children} </div> </div> } } module SidebarItem = { @react.component let make = ( ~tabInfo, ~isSelected, ~isSidebarExpanded, ~setOpenItem=_ => (), ~onItemClickCustom=_ => (), ) => { let sidebarItemRef = React.useRef(Nullable.null) let {getSearchParamByLink} = React.useContext(UserPrefContext.userPrefContext) let getSearchParamByLink = link => getSearchParamByLink(String.substringToEnd(link, ~start=0)) let { globalUIConfig: {sidebarColor: {primaryTextColor, secondaryTextColor, hoverColor}}, } = React.useContext(ThemeProvider.themeContext) let selectedClass = if isSelected { ` ${hoverColor}` } else { ` hover:transition hover:duration-300 ` } let textColor = if isSelected { `text-sm font-semibold ${primaryTextColor}` } else { `text-sm font-medium ${secondaryTextColor} ` } let isMobileView = MatchMedia.useMobileChecker() let {setIsSidebarExpanded} = React.useContext(SidebarProvider.defaultContext) RippleEffectBackground.useHorizontalRippleHook(sidebarItemRef) let tabLinklement = switch tabInfo { | Link(tabOption) => { let {name, icon, link, access, ?selectedIcon} = tabOption let redirectionLink = `${link}${getSearchParamByLink(link)}` let onSidebarItemClick = _ => { isMobileView ? setIsSidebarExpanded(_ => false) : () setOpenItem(prev => {prev == name ? "" : name}) onItemClickCustom() } <RenderIf condition={access !== NoAccess}> <Link to_={GlobalVars.appendDashboardPath(~url=redirectionLink)}> <AddDataAttributes attributes=[ ("data-testid", name->String.replaceRegExp(%re("/\s/g"), "")->String.toLowerCase), ]> <div ref={sidebarItemRef->ReactDOM.Ref.domRef} onClick={onSidebarItemClick} className={`${textColor} relative overflow-hidden flex flex-row rounded-lg items-center cursor-pointer ${selectedClass} p-3 ${isSidebarExpanded ? "" : "mx-1"} ${hoverColor} my-0.5 `}> {switch selectedIcon { | Some(selectedIcon) => <SidebarOption name icon isSidebarExpanded isSelected selectedIcon /> | None => <SidebarOption name icon isSidebarExpanded isSelected /> }} </div> </AddDataAttributes> </Link> </RenderIf> } | RemoteLink(tabOption) => { let {name, icon, link, access, ?remoteIcon, ?selectedIcon} = tabOption let (remoteUi, link) = if remoteIcon->Option.getOr(false) { (<Icon name="external-link-alt" size=14 className="ml-3" />, link) } else { (React.null, `${link}${getSearchParamByLink(link)}`) } <RenderIf condition={access !== NoAccess}> <a href={link} target="_blank" className={`${textColor} flex flex-row items-center cursor-pointer ${selectedClass} p-3`}> {switch selectedIcon { | Some(selectedIcon) => <SidebarOption name icon isSidebarExpanded isSelected selectedIcon /> | None => <SidebarOption name icon isSidebarExpanded isSelected /> }} remoteUi </a> </RenderIf> } | LinkWithTag(tabOption) => { let {name, icon, iconTag, link, access, ?iconStyles, ?iconSize} = tabOption <RenderIf condition={access !== NoAccess}> <Link to_={GlobalVars.appendDashboardPath(~url=`${link}${getSearchParamByLink(link)}`)}> <div onClick={_ => isMobileView ? setIsSidebarExpanded(_ => false) : ()} className={`${textColor} flex flex-row items-center cursor-pointer transition duration-300 ${selectedClass} p-3 ${isSidebarExpanded ? "mx-2" : "mx-1"} ${hoverColor} my-0.5`}> <SidebarOption name icon isSidebarExpanded isSelected /> <RenderIf condition={isSidebarExpanded}> <Icon size={iconSize->Option.getOr(26)} name=iconTag className={`ml-2 ${iconStyles->Option.getOr("w-26 h-26")}`} /> </RenderIf> </div> </Link> </RenderIf> } | Heading(_) | Section(_) | CustomComponent(_) => React.null } tabLinklement } } module NestedSidebarItem = { @react.component let make = (~tabInfo, ~isSelected, ~isSideBarExpanded, ~isSectionExpanded) => { let {globalUIConfig: {sidebarColor: {primaryTextColor, secondaryTextColor}}} = React.useContext( ThemeProvider.themeContext, ) let {getSearchParamByLink} = React.useContext(UserPrefContext.userPrefContext) let getSearchParamByLink = link => getSearchParamByLink(Js.String2.substr(link, ~from=0)) let selectedClass = if isSelected { "font-semibold" } else { "font-medium rounded-lg hover:transition hover:duration-300" } let textColor = if isSelected { `${primaryTextColor}` } else { `${secondaryTextColor}` } let {setIsSidebarExpanded} = React.useContext(SidebarProvider.defaultContext) let isMobileView = MatchMedia.useMobileChecker() let nestedSidebarItemRef = React.useRef(Nullable.null) <RenderIf condition={isSideBarExpanded}> {switch tabInfo { | SubLevelLink(tabOption) => { let {name, link, access, ?iconTag, ?iconStyles, ?iconSize} = tabOption <RenderIf condition={access !== NoAccess}> <Link to_={GlobalVars.appendDashboardPath(~url=`${link}${getSearchParamByLink(link)}`)}> <AddDataAttributes attributes=[ ("data-testid", name->String.replaceRegExp(%re("/\s/g"), "")->String.toLowerCase), ]> <div ref={nestedSidebarItemRef->ReactDOM.Ref.domRef} onClick={_ => isMobileView ? setIsSidebarExpanded(_ => false) : ()} className={`${textColor} ${selectedClass} text-md relative overflow-hidden flex flex-row items-center cursor-pointer rounded-lg ml-3`}> <SidebarSubOption name isSectionExpanded isSelected isSideBarExpanded> <RenderIf condition={iconTag->Belt.Option.isSome && isSideBarExpanded}> <div className="ml-2"> <Icon size={iconSize->Option.getOr(26)} name={iconTag->Option.getOr("")} className={iconStyles->Option.getOr("w-26 h-26")} /> </div> </RenderIf> </SidebarSubOption> </div> </AddDataAttributes> </Link> </RenderIf> } }} </RenderIf> } } module NestedSectionItem = { @react.component let make = ( ~section: sectionType, ~isSectionExpanded, ~isAnySubItemSelected, ~textColor, ~cursor, ~toggleSectionExpansion, ~expandedTextColor, ~isElementShown, ~isSubLevelItemSelected, ~isSideBarExpanded, ) => { let { globalUIConfig: {sidebarColor: {primaryTextColor, secondaryTextColor, hoverColor}}, } = React.useContext(ThemeProvider.themeContext) let iconColor = isAnySubItemSelected ? `${primaryTextColor}` : `${secondaryTextColor} ` let iconOuterClass = if !isSideBarExpanded { `${isAnySubItemSelected ? "" : ""} rounded-lg p-4 rounded-lg` } else { "" } let bgColor = if isSideBarExpanded && isAnySubItemSelected && !isSectionExpanded { "" } else { "" } let sidebarNestedSectionRef = React.useRef(Nullable.null) let sectionExpandedAnimation = `rounded-lg transition duration-[250ms] ease-in-out` let iconName = isAnySubItemSelected ? section.selectedIcon->Option.getOr(section.icon) : section.icon <AddDataAttributes attributes=[ ("data-testid", section.name->String.replaceRegExp(%re("/\s/g"), "")->String.toLowerCase), ]> <div className={`transition duration-300`}> <div ref={sidebarNestedSectionRef->ReactDOM.Ref.domRef} className={`${isSideBarExpanded ? "" : "mx-1"} text-sm ${textColor} ${bgColor} relative overflow-hidden flex flex-row items-center justify-between p-3 rounded-lg ${cursor} ${isSectionExpanded ? "" : sectionExpandedAnimation} ${hoverColor} `} onClick=toggleSectionExpansion> <div className="flex-row items-center select-none min-w-max flex gap-5"> {if isSideBarExpanded { <div className=iconOuterClass> <Icon size=18 name=iconName className=iconColor /> </div> } else { <Icon size=18 name=iconName className=iconColor /> }} <RenderIf condition={isSideBarExpanded}> <div className={`text-sm ${expandedTextColor} whitespace-nowrap`}> {React.string(section.name)} </div> </RenderIf> </div> <RenderIf condition={isSideBarExpanded}> <Icon name={"nd-angle-down"} className={isSectionExpanded ? `-rotate-180 transition duration-[250ms] mr-2 ${secondaryTextColor} opacity-70` : `-rotate-0 transition duration-[250ms] mr-2 ${secondaryTextColor} opacity-70`} size=12 /> </RenderIf> </div> <RenderIf condition={isElementShown}> {section.links ->Array.mapWithIndex((subLevelItem, index) => { let isSelected = subLevelItem->isSubLevelItemSelected <NestedSidebarItem key={Int.toString(index)} isSelected isSideBarExpanded isSectionExpanded tabInfo=subLevelItem /> }) ->React.array} </RenderIf> </div> </AddDataAttributes> } } module SidebarNestedSection = { @react.component let make = ( ~section: sectionType, ~linkSelectionCheck, ~firstPart, ~isSideBarExpanded, ~openItem="", ~setOpenItem=_ => (), ~isSectionAutoCollapseEnabled=false, ) => { let {globalUIConfig: {sidebarColor: {primaryTextColor, secondaryTextColor}}} = React.useContext( ThemeProvider.themeContext, ) let isSubLevelItemSelected = tabInfo => { switch tabInfo { | SubLevelLink(item) => linkSelectionCheck(firstPart, item.link) } } let (isSectionExpanded, setIsSectionExpanded) = React.useState(_ => false) let (isElementShown, setIsElementShown) = React.useState(_ => false) let isAnySubItemSelected = section.links->Array.find(isSubLevelItemSelected)->Option.isSome React.useEffect(() => { if isSectionExpanded { setIsElementShown(_ => true) } else if isElementShown { let _ = setTimeout(() => { setIsElementShown(_ => false) }, 200) } None }, (isSectionExpanded, isSideBarExpanded)) React.useEffect(() => { if isSideBarExpanded { setIsSectionExpanded(_ => isAnySubItemSelected) } else { setIsSectionExpanded(_ => false) } None }, (isSideBarExpanded, isAnySubItemSelected)) let toggleSectionExpansion = React.useCallback(_ => { if !isSideBarExpanded { setTimeout(() => { setIsSectionExpanded(_ => true) }, 200)->ignore } else if isAnySubItemSelected { setIsSectionExpanded(_ => true) } else { setIsSectionExpanded(p => !p) } }, (setIsSectionExpanded, isSideBarExpanded, isAnySubItemSelected)) let textColor = { if isSideBarExpanded { if isAnySubItemSelected { `${primaryTextColor}` } else { `${secondaryTextColor} ` } } else if isAnySubItemSelected { `${primaryTextColor}` } else { `${secondaryTextColor} ` } } let cursor = if isAnySubItemSelected && isSideBarExpanded { `cursor-default` } else { `cursor-pointer` } let expandedTextColor = isAnySubItemSelected ? `${primaryTextColor} font-semibold` : `${secondaryTextColor} font-medium` let areAllSubLevelsHidden = section.links->Array.reduce(true, (acc, subLevelItem) => { acc && switch subLevelItem { | SubLevelLink({access}) => access === NoAccess } }) let isSectionExpanded = if isSectionAutoCollapseEnabled { openItem === section.name || isAnySubItemSelected } else { isSectionExpanded } let toggleSectionExpansion = if isSectionAutoCollapseEnabled { _ => setOpenItem(prev => {prev == section.name ? "" : section.name}) } else { toggleSectionExpansion } let isElementShown = if isSectionAutoCollapseEnabled { openItem == section.name || isAnySubItemSelected } else { isElementShown } <RenderIf condition={!areAllSubLevelsHidden}> <NestedSectionItem section isSectionExpanded isAnySubItemSelected textColor cursor toggleSectionExpansion expandedTextColor isElementShown isSubLevelItemSelected isSideBarExpanded /> </RenderIf> } } @react.component let make = ( ~sidebars: array<topLevelItem>, ~path, ~linkSelectionCheck=defaultLinkSelectionCheck, ~verticalOffset="120px", ~productSiebars: array<topLevelItem>, ) => { open CommonAuthHooks let { globalUIConfig: {sidebarColor: {backgroundColor, secondaryTextColor, hoverColor, borderColor}}, } = React.useContext(ThemeProvider.themeContext) let handleLogout = APIUtils.useHandleLogout(~eventName="user_signout_manual") let isMobileView = MatchMedia.useMobileChecker() let {onProductSelectClick} = React.useContext(ProductSelectionProvider.defaultContext) let sideBarRef = React.useRef(Nullable.null) let {email} = useCommonAuthInfo()->Option.getOr(defaultAuthInfo) let {userInfo: {roleId}} = React.useContext(UserInfoProvider.defaultContext) let isInternalUser = roleId->HyperSwitchUtils.checkIsInternalUser let (openItem, setOpenItem) = React.useState(_ => "") let {isSidebarExpanded, setIsSidebarExpanded} = React.useContext(SidebarProvider.defaultContext) let {showSideBar} = React.useContext(GlobalProvider.defaultContext) React.useEffect(() => { setIsSidebarExpanded(_ => !isMobileView) None }, [isMobileView]) let sidebarWidth = { switch isSidebarExpanded { | true => switch isMobileView { | true => "100%" | false => "275px" } | false => "275px" } } let profileMaxWidth = "150px" let level3 = tail => { switch List.tail(tail) { | Some(tail2) => switch List.head(tail2) { | Some(value2) => `/${value2}` | None => "/" } | None => "/" } } let level2 = tail => { switch List.tail(tail) { | Some(tail2) => switch List.head(tail2) { | Some(value2) => `/${value2}` ++ level3(tail2) | None => "/" } | None => "/" } } let firstPart = switch List.tail(path) { | Some(tail) => switch List.head(tail) { | Some(x) => /* condition is added to check for v2 routes . Eg: /v2/${productName}/${routeName} */ if x === "v2" { `/${x}` ++ level2(tail) } else { `/${x}` } | None => "/" } | None => "/" } let expansionClass = !isSidebarExpanded ? "-translate-x-full" : "" let sidebarMaxWidth = isMobileView ? "w-screen" : "w-max" let sidebarCollapseWidth = showSideBar ? "325px" : "56px" let sidebarContainerClassWidth = isMobileView ? "0px" : `${sidebarCollapseWidth}` let transformClass = "transform md:translate-x-0 transition" let sidebarScrollbarCss = ` @supports (-webkit-appearance: none){ .sidebar-scrollbar { scrollbar-width: auto; scrollbar-color: #8a8c8f; } .sidebar-scrollbar::-webkit-scrollbar { display: block; overflow: scroll; height: 4px; width: 5px; } .sidebar-scrollbar::-webkit-scrollbar-thumb { background-color: #8a8c8f; border-radius: 3px; } .sidebar-scrollbar::-webkit-scrollbar-track { display: none; } } ` let onItemClickCustom = (valueSelected: SidebarTypes.optionType) => { onProductSelectClick(valueSelected.name) } <div className={`${backgroundColor.sidebarNormal} flex group relative `}> <div ref={sideBarRef->ReactDOM.Ref.domRef} className={`flex h-full flex-col transition-all ease-in-out duration-200 relative inset-0`} style={ width: sidebarContainerClassWidth, } /> <div className={`absolute z-30 h-screen flex ${transformClass} duration-300 ease-in-out ${sidebarMaxWidth} ${expansionClass}`}> <OrgSidebar /> <RenderIf condition={showSideBar}> <div ref={sideBarRef->ReactDOM.Ref.domRef} className={`${backgroundColor.sidebarNormal} flex h-full flex-col transition-all duration-100 border-r ${borderColor} relative inset-0`} style={width: sidebarWidth}> <RenderIf condition={isMobileView}> <div className="flex align-center mt-4 mb-6 ml-1 pl-3 pr-4 gap-5 cursor-default"> <Icon className="mr-1" size=20 name="collapse-cross" customIconColor={`${secondaryTextColor}`} onClick={_ => setIsSidebarExpanded(_ => false)} /> </div> </RenderIf> <RenderIf condition={!isInternalUser}> <SidebarSwitch isSidebarExpanded /> </RenderIf> <div className="h-full overflow-y-scroll transition-transform duration-1000 overflow-x-hidden sidebar-scrollbar mt-4" style={height: `calc(100vh - ${verticalOffset})`}> <style> {React.string(sidebarScrollbarCss)} </style> <div className="p-2.5 pt-0"> {sidebars ->Array.mapWithIndex((tabInfo, index) => { switch tabInfo { | RemoteLink(record) | Link(record) => { let isSelected = linkSelectionCheck(firstPart, record.link) <SidebarItem key={Int.toString(index)} tabInfo isSelected isSidebarExpanded setOpenItem /> } | LinkWithTag(record) => { let isSelected = linkSelectionCheck(firstPart, record.link) <SidebarItem key={Int.toString(index)} tabInfo isSelected isSidebarExpanded /> } | Section(section) => <RenderIf condition={section.showSection} key={Int.toString(index)}> <SidebarNestedSection key={Int.toString(index)} section linkSelectionCheck firstPart isSideBarExpanded={isSidebarExpanded} openItem setOpenItem isSectionAutoCollapseEnabled=true /> </RenderIf> | Heading(headingOptions) => <div key={Int.toString(index)} className={`text-xs font-medium leading-5 text-[#5B6376] overflow-hidden border-l-2 rounded-lg border-transparent px-3 ${isSidebarExpanded ? "mx-2" : "mx-1"} mt-5 mb-3`}> {{isSidebarExpanded ? headingOptions.name : ""}->React.string} </div> | CustomComponent(customComponentOptions) => <RenderIf condition={isSidebarExpanded} key={Int.toString(index)}> customComponentOptions.component </RenderIf> } }) ->React.array} </div> <RenderIf condition={productSiebars->Array.length > 0}> <div className={"p-2.5"}> <div className={`text-xs font-semibold px-3 pt-6 pb-2 text-nd_gray-400 tracking-widest`}> {React.string("Other modular services"->String.toUpperCase)} </div> {productSiebars ->Array.mapWithIndex((tabInfo, index) => { switch tabInfo { | Section(section) => <RenderIf condition={section.showSection} key={Int.toString(index)}> <SidebarNestedSection key={Int.toString(index)} section linkSelectionCheck firstPart isSideBarExpanded={isSidebarExpanded} openItem setOpenItem isSectionAutoCollapseEnabled=true /> </RenderIf> | Link(record) => { let isSelected = linkSelectionCheck(firstPart, record.link) <SidebarItem key={Int.toString(index)} tabInfo isSelected isSidebarExpanded setOpenItem onItemClickCustom={_ => onItemClickCustom(record)} /> } | _ => React.null } }) ->React.array} </div> </RenderIf> </div> <div className={`flex items-center justify-between p-3 border-t ${borderColor} ${hoverColor}`}> <RenderIf condition={isSidebarExpanded}> <Popover className="relative inline-block text-left"> {popoverProps => <> <Popover.Button className={ let openClasses = if popoverProps["open"] { `group pl-3 border py-2 rounded-lg inline-flex items-center text-base font-medium hover:text-opacity-100 focus:outline-none` } else { `text-opacity-90 group pl-3 border py-2 rounded-lg inline-flex items-center text-base font-medium hover:text-opacity-100 focus:outline-none` } `${openClasses} border-none` }> {_ => <> <div className="flex items-center justify-between gap-x-3 "> <div className="bg-nd_gray-600 rounded-full p-1"> <Icon name="nd-user" size=16 /> </div> <ToolTip description=email toolTipFor={<RenderIf condition={isSidebarExpanded}> <div className={`w-[${profileMaxWidth}] text-sm font-medium text-left ${secondaryTextColor} dark:text-gray-600 text-ellipsis overflow-hidden`}> {email->React.string} </div> </RenderIf>} toolTipPosition=ToolTip.Top tooltipWidthClass="!w-fit !z-50" /> <div className={`flex flex-row`}> <Icon name="nd-dropdown-menu" size=18 className={`cursor-pointer ${secondaryTextColor}`} /> </div> </div> </>} </Popover.Button> <Transition \"as"="span" enter={"transition ease-out duration-200"} enterFrom="opacity-0 translate-y-1" enterTo="opacity-100 translate-y-0" leave={"transition ease-in duration-150"} leaveFrom="opacity-100 translate-y-0" leaveTo="opacity-0 translate-y-1"> <Popover.Panel className={`absolute !z-30 bottom-[100%] left-1 `}> {panelProps => { <div id="neglectTopbarTheme" className={`relative flex flex-col py-3 rounded-lg shadow-lg ring-1 ring-black ring-opacity-5 w-60 ${backgroundColor.sidebarSecondary}`}> <MenuOption onClick={_ => { panelProps["close"]() RescriptReactRouter.replace( GlobalVars.appendDashboardPath(~url="/account-settings/profile"), ) }} text="Profile" /> <MenuOption onClick={_ => { handleLogout()->ignore }} text="Sign out" /> </div> }} </Popover.Panel> </Transition> </>} </Popover> </RenderIf> </div> </div> </RenderIf> </div> </div> }
6,246
9,503
hyperswitch-control-center
src/screens/PayoutRouting/PayoutRoutingConfigure.res
.res
@react.component let make = (~routingType) => { open LogicUtils open RoutingTypes open RoutingUtils 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=PayoutProcessor, ) let baseUrlForRedirection = "/payoutrouting" 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={"/payoutrouting"}> {switch currentRouting { | VOLUME_SPLIT => <VolumeSplitRouting routingRuleId=id isActive connectorList urlEntityName=V1(PAYOUT_ROUTING) baseUrlForRedirection /> | ADVANCED => <AdvancedRouting routingRuleId=id isActive setCurrentRouting connectorList urlEntityName=V1(PAYOUT_ROUTING) baseUrlForRedirection /> | DEFAULTFALLBACK => <DefaultRouting urlEntityName=V1(PAYOUT_DEFAULT_FALLBACK) baseUrlForRedirection connectorVariant=ConnectorTypes.PayoutProcessor /> | _ => React.null }} </History.BreadCrumbWrapper> </div> }
505
9,504
hyperswitch-control-center
src/screens/PayoutRouting/PayoutHistoryTable.res
.res
open PayoutHistoryTableEntity @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={payoutHistoryEntity( activeRoutingIds, ~authorization=userHasAccess(~groupAccess=WorkflowsManage), )} resultsPerPage=10 showSerialNumber=true totalResults={records->Array.length} offset setOffset currrentFetchCount={records->Array.length} /> }
153
9,505
hyperswitch-control-center
src/screens/PayoutRouting/PayoutCurrentActiveRouting.res
.res
@react.component let make = (~routingType: array<JSON.t>) => { open LogicUtils <div className="mt-4 flex flex-col gap-6"> {routingType ->Array.mapWithIndex((ele, i) => { let id = ele->getDictFromJsonObject->getString("id", "") <ActiveRouting.ActiveSection key={i->Int.toString} activeRouting={ele} activeRoutingId={id} onRedirectBaseUrl="payoutrouting" /> }) ->React.array} </div> }
124
9,506
hyperswitch-control-center
src/screens/PayoutRouting/PayoutRoutingStack.res
.res
@react.component let make = (~remainingPath, ~previewOnly=false) => { open APIUtils 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 ? <PayoutHistoryTable records activeRoutingIds /> : <DefaultLandingPage height="90%" title="No Routing Rule Configured!" customStyle="py-16" overriddingStylesTitle="text-3xl font-semibold" /> }, }, { title: "Active configuration", renderContent: () => <PayoutCurrentActiveRouting routingType />, }, ] }, [routingType]) let fetchRoutingRecords = async activeIds => { try { setScreenState(_ => PageLoaderWrapper.Loading) let routingUrl = `${getURL(~entityName=V1(PAYOUT_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_PAYOUT_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 items-center justify-center"> <PageUtils.PageHeading title="Payout 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="payoutrouting" /> </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,284
9,507
hyperswitch-control-center
src/screens/PayoutRouting/PayoutHistoryTableEntity.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 payoutHistoryEntity = ( 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=`/payoutrouting/${value.kind ->routingTypeMapper ->routingTypeName}?id=${value.id}${activeRoutingIds->Array.includes(value.id) ? "&isActive=true" : ""}`, ), ~authorization, ) } }, ) }
657
9,508
hyperswitch-control-center
src/screens/Helpers/DefaultLandingPage.res
.res
@react.component let make = ( ~width="98%", ~height="100%", ~title="", ~subtitle="", ~customStyle="", ~isButton=false, ~buttonText="Home", ~onClickHandler=_ => (), ~overriddingStylesTitle="", ~overriddingStylesSubtitle="", ~showLogoutButton=false, ) => { let handleLogout = APIUtils.useHandleLogout() let appliedWidth = width === "98%" ? "98%" : width let appliedHeight = height === "100%" ? "100%" : height let onLogoutHandle = () => { handleLogout()->ignore } <div style={width: appliedWidth, height: appliedHeight} className={`m-5 bg-white dark:bg-jp-gray-lightgray_background dark:border-jp-gray-850 flex flex-col p-5 items-center justify-center ${customStyle}`}> <img alt="work-in-progress" src={`/assets/WorkInProgress.svg`} /> <RenderIf condition={title->String.length !== 0}> <div className={`font-bold mt-5 ${overriddingStylesTitle}`}> {title->React.string} </div> </RenderIf> <RenderIf condition={subtitle->String.length !== 0}> <div className={`mt-5 text-center text-semibold text-xl text-[#0E0E0E] ${overriddingStylesSubtitle}`}> {subtitle->React.string} </div> </RenderIf> <RenderIf condition={isButton}> <div className="mt-7 flex gap-4"> <Button text={buttonText} buttonSize={Large} onClick={_ => onClickHandler()} buttonType={Primary} /> <RenderIf condition={showLogoutButton}> <Button text="Logout" buttonSize={Large} onClick={_ => onLogoutHandle()} buttonType={Secondary} /> </RenderIf> </div> </RenderIf> </div> }
447
9,509
hyperswitch-control-center
src/screens/Helpers/HelperComponents.res
.res
module CopyTextCustomComp = { @react.component let make = ( ~displayValue=None, ~copyValue=None, ~customTextCss="", ~customParentClass="flex items-center gap-2", ~customOnCopyClick=() => (), ~customIconCss="h-7 opacity-70", ) => { let showToast = ToastState.useShowToast() let copyVal = switch copyValue { | Some(val) => val | None => switch displayValue { | Some(val) => val | None => "" } } let onCopyClick = ev => { ev->ReactEvent.Mouse.stopPropagation Clipboard.writeText(copyVal) customOnCopyClick() showToast(~message="Copied to Clipboard!", ~toastType=ToastSuccess) } switch displayValue { | Some(val) => <div className=customParentClass> <div className=customTextCss> {val->React.string} </div> <Icon name="nd-copy" onClick={ev => { onCopyClick(ev) }} className={`${customIconCss} cursor-pointer`} /> </div> | None => "NA"->React.string } } } module EllipsisText = { @react.component let make = ( ~displayValue, ~copyValue=None, ~endValue=17, ~showCopy=true, ~customTextStyle="", ~customEllipsisStyle="text-sm font-extrabold cursor-pointer", ~expandText=true, ~customOnCopyClick=_ => (), ) => { open LogicUtils let showToast = ToastState.useShowToast() let (isTextVisible, setIsTextVisible) = React.useState(_ => false) let handleClick = ev => { ev->ReactEvent.Mouse.stopPropagation if expandText { setIsTextVisible(_ => true) } } let copyVal = switch copyValue { | Some(val) => val | None => displayValue } let onCopyClick = ev => { ev->ReactEvent.Mouse.stopPropagation Clipboard.writeText(copyVal) customOnCopyClick() showToast(~message="Copied to Clipboard!", ~toastType=ToastSuccess) } <div className="flex text-nowrap gap-2"> <RenderIf condition={isTextVisible}> <div className={customTextStyle}> {displayValue->React.string} </div> </RenderIf> <RenderIf condition={!isTextVisible && displayValue->isNonEmptyString}> <div className="flex gap-1"> <p className={customTextStyle}> {`${displayValue->String.slice(~start=0, ~end=endValue)}`->React.string} </p> <RenderIf condition={displayValue->String.length > endValue}> <span className={customEllipsisStyle} onClick={ev => handleClick(ev)}> {"..."->React.string} </span> </RenderIf> </div> </RenderIf> <RenderIf condition={showCopy}> <Icon name="nd-copy" className="cursor-pointer opacity-70" onClick={ev => onCopyClick(ev)} /> </RenderIf> </div> } } module BluredTableComponent = { @react.component let make = ( ~infoText, ~buttonText="", ~onClickElement=React.null, ~onClickUrl="", ~paymentModal=false, ~setPaymentModal=_ => (), ~moduleName, ~moduleSubtitle=?, ~showRedirectCTA=true, ~headerRightButton=React.null, ) => { let dummyTableValueDict = [ ("payment_id", "##############"->JSON.Encode.string), ("merchant_id", "####"->JSON.Encode.string), ("status", "####"->JSON.Encode.string), ("amount", "####"->JSON.Encode.string), ("amount_capturable", "####"->JSON.Encode.string), ]->Dict.fromArray let dummyTableValue = Array.make(~length=5, dummyTableValueDict) let subTitle = moduleSubtitle->Option.isSome ? moduleSubtitle->Option.getOr("") : "" <div className="relative flex flex-col gap-8"> <div className="flex items-center justify-between "> <PageUtils.PageHeading title=moduleName subTitle /> <div> {headerRightButton} </div> </div> <div className="blur bg-white p-8"> {dummyTableValue ->Array.mapWithIndex((value, index) => { <div className="flex gap-8 my-10 justify-between" key={index->Int.toString}> {value ->Dict.keysToArray ->Array.mapWithIndex((tableVal, ind) => <div className="flex justify-center text-grey-700 opacity-50" key={ind->Int.toString}> {value->LogicUtils.getString(tableVal, "")->React.string} </div> ) ->React.array} </div> }) ->React.array} </div> <div className="absolute top-0 right-0 left-0 bottom-0 h-fit w-1/5 m-auto flex flex-col gap-6 items-center"> <p className="text-center text-grey-700 font-medium opacity-50"> {infoText->React.string} </p> <RenderIf condition={showRedirectCTA}> <Button text=buttonText buttonType={Primary} onClick={_ => { onClickUrl->LogicUtils.isNonEmptyString ? RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url=onClickUrl)) : setPaymentModal(_ => true) }} /> </RenderIf> </div> <RenderIf condition={paymentModal}> {onClickElement} </RenderIf> </div> } } module KeyAndCopyArea = { @react.component let make = (~copyValue, ~shadowClass="") => { let showToast = ToastState.useShowToast() <div className={`flex gap-4 border rounded-md py-2 px-4 items-center bg-white ${shadowClass}`}> <p className="text-base text-grey-700 opacity-70 col-span-2 truncate"> {copyValue->React.string} </p> <div className="px-2 py-1 border rounded-md flex gap-2 items-center cursor-pointer" onClick={_ => { Clipboard.writeText(copyValue) showToast(~message="Copied to Clipboard!", ~toastType=ToastSuccess) }}> <Icon name="nd-copy" customIconColor="rgb(156 163 175)" /> <p className="text-grey-700 opacity-50"> {"Copy"->React.string} </p> </div> </div> } } module ConnectorCustomCell = { @react.component let make = (~connectorName, ~connectorType: option<ConnectorTypes.connector>=?) => { let connector_Type = switch connectorType { | Some(connectorType) => connectorType | None => ConnectorTypes.Processor } if connectorName->LogicUtils.isNonEmptyString { <div className="flex items-center flex-nowrap break-all whitespace-nowrap mr-6"> <GatewayIcon gateway={connectorName->String.toUpperCase} className="w-6 h-6 mr-2" /> <div className="capitalize"> {connectorName ->ConnectorUtils.getDisplayNameForConnector(~connectorType=connector_Type) ->React.string} </div> </div> } else { "NA"->React.string } } } module BusinessProfileComponent = { @react.component let make = (~profile_id: string, ~className="") => { let {profile_name} = BusinessProfileHook.useGetBusinessProflile(profile_id) <div className="truncate whitespace-nowrap overflow-hidden"> {(profile_name->LogicUtils.isNonEmptyString ? profile_name : "NA")->React.string} </div> } } module ProfileNameComponent = { @react.component let make = (~profile_id: string, ~className="") => { let {name} = HyperswitchAtom.profileListAtom ->Recoil.useRecoilValueFromAtom ->Array.find(obj => obj.id == profile_id) ->Option.getOr({ id: profile_id, name: "NA", }) <div className> {(name->LogicUtils.isNonEmptyString ? name : "NA")->React.string} </div> } }
1,889
9,510
hyperswitch-control-center
src/screens/Helpers/PageLoaderWrapper.res
.res
@unboxed type viewType = Loading | Error(string) | Success | Custom module ScreenLoader = { @react.component let make = (~sectionHeight="h-80-vh") => { let loaderLottieFile = LottieFiles.useLottieJson("hyperswitch_loader.json") let loader = LottieFiles.useLottieJson("loader-circle.json") let {devThemeFeature} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let {userInfo: {themeId}} = React.useContext(UserInfoProvider.defaultContext) let {branding} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let showLoader = devThemeFeature && themeId->LogicUtils.isNonEmptyString <div className={`${sectionHeight} w-scrren flex flex-col justify-center items-center`}> <RenderIf condition={!branding}> <div className="w-20 h-16"> <ReactSuspenseWrapper> <div className="scale-400 pt-px"> <Lottie animationData={showLoader ? loader : loaderLottieFile} autoplay=true loop=true /> </div> </ReactSuspenseWrapper> </div> </RenderIf> <RenderIf condition={branding}> <Loader /> </RenderIf> </div> } } @react.component let make = ( ~children=?, ~screenState: viewType, ~customUI=?, ~sectionHeight="h-80-vh", ~customStyleForDefaultLandingPage="", ~customLoader=?, ~showLogoutButton=false, ) => { switch screenState { | Loading => switch customLoader { | Some(loader) => loader | _ => <ScreenLoader sectionHeight /> } | Error(_err) => <DefaultLandingPage title="Oops, we hit a little bump on the road!" customStyle={`py-16 !m-0 ${customStyleForDefaultLandingPage} ${sectionHeight}`} overriddingStylesTitle="text-2xl font-semibold" buttonText="Refresh" overriddingStylesSubtitle="!text-sm text-grey-700 opacity-50 !w-3/4" subtitle="We apologize for the inconvenience, but it seems like we encountered a hiccup while processing your request." onClickHandler={_ => Window.Location.hardReload(true)} isButton=true showLogoutButton /> | Success => switch children { | Some(ui) => ui | None => React.null } | Custom => switch customUI { | Some(ui) => ui | None => React.null } } }
604
9,511
hyperswitch-control-center
src/screens/Helpers/TableSearchFilter.res
.res
@react.component let make = ( ~data, ~filterLogic=_ => {()}, ~placeholder, ~searchVal, ~setSearchVal, ~customSearchBarWrapperWidth="w-1/4", ~customInputBoxWidth="w-72", ) => { let filterData = React.useCallback(filterLogic, []) React.useEffect(() => { filterData((searchVal, data)) None }, [searchVal]) let onChange = ev => { let value = ReactEvent.Form.target(ev)["value"] setSearchVal(_ => value) } let handleSubmit = (_, _) => {Nullable.null->Promise.resolve} let inputSearch: ReactFinalForm.fieldRenderPropsInput = { name: "search", onBlur: _ => (), onChange, onFocus: _ => (), value: searchVal->JSON.Encode.string, checked: true, } <AddDataAttributes attributes=[("data-testid", "table-search-filter")]> <div className=customSearchBarWrapperWidth> <ReactFinalForm.Form subscription=ReactFinalForm.subscribeToValues onSubmit=handleSubmit initialValues={""->JSON.Encode.string} render={_handleSubmit => { InputFields.textInput( ~leftIcon=<Icon name="search" size=16 />, ~customStyle=`!h-10 ${customInputBoxWidth}`, )(~input=inputSearch, ~placeholder) }} /> </div> </AddDataAttributes> }
323
9,512
hyperswitch-control-center
src/screens/Helpers/PageUtils.res
.res
module PageHeading = { @react.component let make = ( ~title, ~subTitle=?, ~customTitleStyle="", ~customSubTitleStyle="text-lg font-medium", ~customHeadingStyle="py-2", ~isTag=false, ~tagText="", ~customTagStyle="bg-extra-light-grey border-light-grey", ~leftIcon=None, ) => { let headerTextStyle = HSwitchUtils.getTextClass((H1, Optional)) <div className={`${customHeadingStyle}`}> {switch leftIcon { | Some(icon) => <Icon name={icon} size=56 /> | None => React.null }} <div className="flex items-center gap-4"> <div className={`${headerTextStyle} ${customTitleStyle}`}> {title->React.string} </div> <RenderIf condition=isTag> <div className={`text-sm text-grey-700 font-semibold border rounded-full px-2 py-1 ${customTagStyle}`}> {tagText->React.string} </div> </RenderIf> </div> {switch subTitle { | Some(text) => <RenderIf condition={text->LogicUtils.isNonEmptyString}> <div className={`opacity-50 mt-2 ${customSubTitleStyle}`}> {text->React.string} </div> </RenderIf> | None => React.null }} </div> } }
318
9,513
hyperswitch-control-center
src/screens/Helpers/CardUtils.res
.res
module CardHeader = { @react.component let make = ( ~heading, ~subHeading, ~leftIcon=None, ~customSubHeadingStyle="", ~customHeadingStyle="", ) => { <div className="md:flex gap-3"> {switch leftIcon { | Some(icon) => <img alt="image" className="h-6 inline-block align-top" src={`/icons/${icon}.svg`} /> | None => React.null }} <div className="w-full"> <div className={`text-xl font-semibold ${customHeadingStyle}`}> {heading->React.string} </div> <div className={`text-medium font-medium leading-7 opacity-50 mt-2 ${customSubHeadingStyle}`}> {subHeading->React.string} </div> </div> </div> } } module CardFooter = { @react.component let make = (~customFooterStyle="", ~children) => { <div className={`lg:ml-9 lg:mb-3 flex gap-5 ${customFooterStyle}`}> children </div> } } module CardLayout = { @react.component let make = (~width="w-1/2", ~children, ~customStyle="") => { <div className={`relative bg-white ${width} border p-6 rounded flex flex-col justify-between ${customStyle}`}> children </div> } }
316
9,514
hyperswitch-control-center
src/screens/Helpers/HSSelfServeSidebar.res
.res
type status = COMPLETED | ONGOING | PENDING type subOption = { title: string, status: status, } type sidebarOption = { title: string, status: status, link: string, subOptions?: array<subOption>, } @react.component let make = (~heading, ~sidebarOptions: array<sidebarOption>=[]) => { let {setDashboardPageState} = React.useContext(GlobalProvider.defaultContext) let {globalUIConfig: {font: {textColor}, backgroundColor}} = React.useContext( ThemeProvider.themeContext, ) let handleBackButton = _ => { setDashboardPageState(_ => #HOME) RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url="/home")) } let completedSteps = sidebarOptions->Array.filter(sidebarOption => sidebarOption.status === COMPLETED) let completedPercentage = (completedSteps->Array.length->Int.toFloat /. sidebarOptions->Array.length->Int.toFloat *. 100.0)->Float.toInt <div className="w-[288px] xl:w-[364px] h-screen bg-white shadow-sm shrink-0"> <div className="p-6 flex flex-col gap-3"> <div className="text-xl font-semibold"> {heading->React.string} </div> <div className={`${textColor.primaryNormal} flex gap-3 cursor-pointer`} onClick={handleBackButton}> <Icon name="back-to-home-icon" /> {"Exit to Homepage"->React.string} </div> </div> <div className="flex flex-col px-6 py-8 gap-2 border-y border-gray-200"> <span> {`${completedPercentage->Int.toString}% Completed`->React.string} </span> <div className="h-2 bg-gray-200"> <div className={`h-full ${backgroundColor}`} style={width: `${completedPercentage->Int.toString}%`} /> </div> </div> {sidebarOptions ->Array.mapWithIndex((sidebarOption, i) => { let (icon, indexBackground, indexColor, background, textColor) = switch sidebarOption.status { | COMPLETED => ("green-check", backgroundColor, "text-white", "", "") | PENDING => ( "lock-icon", "bg-blue-200", textColor.primaryNormal, "bg-jp-gray-light_gray_bg", "", ) | ONGOING => ("", backgroundColor, "text-white", "", textColor.primaryNormal) } let onClick = _ => { if sidebarOption.status === COMPLETED { RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url=sidebarOption.link)) } } let subOptionsArray = sidebarOption.subOptions->Option.getOr([]) <div key={i->Int.toString} className={`p-6 border-y border-gray-200 cursor-pointer ${background}`} onClick> <div key={i->Int.toString} className={`flex items-center ${textColor} font-medium gap-5`}> <span className={`${indexBackground} ${indexColor} rounded-sm w-1.1-rem h-1.1-rem flex justify-center items-center text-sm`}> {(i + 1)->Int.toString->React.string} </span> <div className="flex-1"> <ToolTip description={sidebarOption.title} toolTipFor={<div className="w-40 xl:w-60 text-ellipsis overflow-hidden whitespace-nowrap"> {sidebarOption.title->React.string} </div>} /> </div> <Icon name=icon size=20 /> </div> <RenderIf condition={sidebarOption.status === ONGOING && subOptionsArray->Array.length > 0}> <div className="my-4"> {subOptionsArray ->Array.mapWithIndex((subOption, i) => { let (subIcon, subIconColor, subBackground, subFont) = switch subOption.status { | COMPLETED => ("check", "green", "", "text-gray-600") | PENDING => ("nonselected", "text-gray-100", "", "text-gray-400") | ONGOING => ("nonselected", "", "bg-gray-100", "font-semibold") } <div key={i->Int.toString} className={`flex gap-1 items-center pl-6 py-2 rounded-md my-1 ${subBackground} ${subFont}`}> <Icon name=subIcon customIconColor=subIconColor customHeight="14" /> <span className="flex-1"> {subOption.title->React.string} </span> </div> }) ->React.array} </div> </RenderIf> </div> }) ->React.array} </div> }
1,072
9,515
hyperswitch-control-center
src/screens/UserManagement/UserRevamp/UserManagementUtils.res
.res
let errorClass = "text-sm leading-4 font-medium text-start ml-1 mt-2" let createCustomRole = FormRenderer.makeFieldInfo( ~label="Enter custom role name", ~name="role_name", ~customInput=InputFields.textInput(~autoComplete="off", ~autoFocus=false), ~isRequired=true, ) let roleScope = userRole => { let roleScopeArray = ["Merchant", "Organization"]->Array.map(item => { let option: SelectBox.dropdownOption = { label: item, value: item->String.toLowerCase, } option }) FormRenderer.makeFieldInfo( ~label="Role Scope", ~name="role_scope", ~customInput=InputFields.selectInput( ~options=roleScopeArray, ~buttonText="Select Option", ~deselectDisable=true, ~disableSelect=userRole === "org_admin" || userRole === "tenant_admin" ? false : true, ), ~isRequired=true, ) } let validateEmptyValue = (key, errors) => { switch key { | "emailList" => Dict.set(errors, "email", "Please enter Invite mails"->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 = LogicUtils.getArrayFromDict(valuesDict, key, []) if value->Array.length === 0 { key->validateEmptyValue(errors) } else { value->Array.forEach(ele => { if ele->JSON.Decode.string->Option.getOr("")->HSwitchUtils.isValidEmail { errors->Dict.set("email", "Please enter a valid email"->JSON.Encode.string) } }) () } }) errors->JSON.Encode.object } let validateFormForRoles = values => { let errors = Dict.make() open LogicUtils let valuesDict = values->getDictFromJsonObject if valuesDict->getString("role_scope", "")->isEmptyString { Dict.set(errors, "role_scope", "Role scope is required"->JSON.Encode.string) } if valuesDict->getString("role_name", "")->isEmptyString { Dict.set(errors, "role_name", "Role name is required"->JSON.Encode.string) } if valuesDict->getString("role_name", "")->String.length > 64 { Dict.set(errors, "role_name", "Role name should be less than 64 characters"->JSON.Encode.string) } if valuesDict->getArrayFromDict("groups", [])->Array.length === 0 { Dict.set(errors, "groups", "Roles required"->JSON.Encode.string) } errors->JSON.Encode.object } let tabIndeToVariantMapper = index => { open UserManagementTypes switch index { | 0 => UsersTab | _ => RolesTab } } let getUserManagementViewValues = (~checkUserEntity) => { open UserManagementTypes let org = { label: "Organization", entity: #Organization, } let merchant = { label: "Merchant", entity: #Merchant, } let profile = { label: "Profile", entity: #Profile, } let default = { label: "All", entity: #Default, } if checkUserEntity([#Organization, #Tenant]) { [default, org, merchant, profile] } else if checkUserEntity([#Merchant]) { [default, merchant, profile] } else { [default] } } let stringToVariantMapperInternalUser: string => UserManagementTypes.internalUserType = roleId => { switch roleId { | "internal_view_only" => InternalViewOnly | "internal_admin" => InternalAdmin | _ => NonInternal } } let stringToVariantMapperTenantAdmin: string => UserManagementTypes.admin = roleId => { switch roleId { | "tenant_admin" => TenantAdmin | _ => NonTenantAdmin } }
932
9,516
hyperswitch-control-center
src/screens/UserManagement/UserRevamp/ListUserTableEntity.res
.res
open LogicUtils type role = Admin | ViewOnly | Operator | Developer | OrgAdmin | CustomerSupport | IAM | None type userStatus = Active | InviteSent | None type rolesType = { role_id: string, role_name: string, } type userTableTypes = { email: string, roles: array<rolesType>, } type userColTypes = | Email | Role let defaultColumnsForUser = [Email, Role] type roleColTypes = | CreatedOn | Role | CreatedBy | Description | ActiveUsers let itemToObjectMapperForRoles = dict => { { role_id: dict->getString("role_id", ""), role_name: dict->getString("role_name", ""), } } let itemToObjMapperForUser = dict => { { email: getString(dict, "email", ""), roles: dict->getJsonObjectFromDict("roles")->getArrayDataFromJson(itemToObjectMapperForRoles), } } let getHeadingForUser = (colType: userColTypes) => { switch colType { | Email => Table.makeHeaderInfo(~key="email", ~title="Email") | Role => Table.makeHeaderInfo(~key="role", ~title="Role") } } let customCellForRoles = listOfRoles => { if listOfRoles->Array.length > 1 { <div className="flex gap-1 items-center"> <Icon size=18 name="person" /> {"Multiple roles"->React.string} </div> } else { let firstRole = listOfRoles->LogicUtils.getValueFromArray( 0, { role_id: "", role_name: "", }, ) <div className="flex gap-1 items-center"> <Icon size=18 name="person" /> {firstRole.role_name->LogicUtils.snakeToTitle->LogicUtils.capitalizeString->React.string} </div> } } let getCellForUser = (data: userTableTypes, colType: userColTypes): Table.cell => { switch colType { | Email => Text(data.email) | Role => CustomCell(data.roles->customCellForRoles, "") } } let getUserData: JSON.t => array<userTableTypes> = json => { getArrayDataFromJson(json, itemToObjMapperForUser) } let userEntity = EntityType.makeEntity( ~uri="", ~getObjects=getUserData, ~defaultColumns=defaultColumnsForUser, ~allColumns=defaultColumnsForUser, ~getHeading=getHeadingForUser, ~getCell=getCellForUser, ~dataKey="", ~getShowLink=userId => GlobalVars.appendDashboardPath(~url=`/users/details?email=${userId.email}`), )
600
9,517
hyperswitch-control-center
src/screens/UserManagement/UserRevamp/NewUserInvitationForm.res
.res
let p1MediumTextClass = HSwitchUtils.getTextClass((P1, Medium)) let p2MediumTextClass = HSwitchUtils.getTextClass((P2, Medium)) let p3MediumTextClass = HSwitchUtils.getTextClass((P3, Medium)) let p3RegularTextClass = HSwitchUtils.getTextClass((P3, Regular)) module ModuleAccessRenderer = { @react.component let make = (~elem: UserManagementTypes.detailedUserModuleType, ~index, ~customCss="") => { open UserUtils let iconForAccess = access => switch access->stringToVariantMapperForAccess { | Read => "eye-outlined" | Write => "pencil-outlined" } <div key={index->Int.toString} className={`flex justify-between ${customCss}`}> <div className="flex flex-col gap-2 basis-3/5 "> <p className=p2MediumTextClass> {elem.parentGroup->React.string} </p> <p className=p3RegularTextClass> {elem.description->React.string} </p> </div> <div className="flex gap-2 h-fit "> {elem.scopes ->Array.map(item => { <p className={`py-0.5 px-2 rounded-full bg-gray-200 ${p3RegularTextClass} flex gap-1 items-center`}> <Icon name={item->iconForAccess} size=12 /> <span> {(item :> string)->LogicUtils.camelCaseToTitle->React.string} </span> </p> }) ->React.array} </div> </div> } } module RoleAccessOverview = { @react.component let make = (~roleDict, ~role) => { open LogicUtils let detailedUserAccess = roleDict ->getDictfromDict(role) ->getJsonObjectFromDict("parent_groups") ->getArrayDataFromJson(UserUtils.itemToObjMapperFordetailedRoleInfo) let roleInfo = Recoil.useRecoilValueFromAtom(HyperswitchAtom.moduleListRecoil) let (modulesWithAccess, moduleWithoutAccess) = UserUtils.modulesWithUserAccess( roleInfo, detailedUserAccess, ) <div className="flex flex-col gap-8"> {modulesWithAccess ->Array.mapWithIndex((elem, index) => { <ModuleAccessRenderer elem index /> }) ->React.array} {moduleWithoutAccess ->Array.mapWithIndex((elem, index) => { <ModuleAccessRenderer elem index customCss="text-grey-200" /> }) ->React.array} </div> } } module NoteComponent = { @react.component let make = () => { let {userInfo: {orgId, merchantId, profileId, userEntity}} = React.useContext( UserInfoProvider.defaultContext, ) // TODO : Chnage id to name once backend starts sending name in userinfo let descriptionBasedOnEntity = switch userEntity { | #Tenant | #Organization => `You can only invite people for ${orgId} here. To invite users to another organisation, please switch the organisation.` | #Merchant => `You can only invite people for ${merchantId} here. To invite users to another merchant, please switch the merchant.` | #Profile => `You can only invite people for ${profileId} here. To invite users to another profile, please switch the profile.` } <div className="flex gap-2 items-start justify-start"> <Icon name="info-vacent" size=18 customIconColor="!text-gray-400" /> <span className={`${p3RegularTextClass} text-gray-500`}> {descriptionBasedOnEntity->React.string} </span> </div> } } @react.component let make = () => { open APIUtils open LogicUtils open UserUtils open UserManagementHelper let getURL = useGetURL() let fetchDetails = useGetMethod() let (roleDict, setRoleDict) = React.useState(_ => Dict.make()) let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let roleTypeValue = ReactFinalForm.useField(`role_id`).input.value->getStringFromJson("")->getNonEmptyString let (roleNameValue, setRoleNameValue) = React.useState(_ => "") let (options, setOptions) = React.useState(_ => []->SelectBox.makeOptions) let (dropDownLoaderState, setDropDownLoaderState) = React.useState(_ => DropdownWithLoading.Success ) let formState: ReactFinalForm.formState = ReactFinalForm.useFormState( ReactFinalForm.useFormSubscription(["values"])->Nullable.make, ) let getMemberAcessBasedOnRole = async _ => { try { setScreenState(_ => PageLoaderWrapper.Loading) let url = getURL( ~entityName=V1(USER_MANAGEMENT), ~userRoleTypes=ROLE_ID, ~id=roleTypeValue, ~methodType=Get, ) let res = await fetchDetails(url) setRoleNameValue(_ => res->getDictFromJsonObject->getString("role_name", "")) setRoleDict(prevDict => { prevDict->Dict.set(roleTypeValue->Option.getOr(""), res) prevDict }) setScreenState(_ => PageLoaderWrapper.Success) } catch { | Exn.Error(e) => { let err = Exn.message(e)->Option.getOr("Failed to Fetch!") setScreenState(_ => PageLoaderWrapper.Error(err)) } } } React.useEffect(() => { if roleTypeValue->Option.isSome { getMemberAcessBasedOnRole()->ignore } None }, [roleTypeValue]) let onClickDropDownApi = async () => { try { setDropDownLoaderState(_ => DropdownWithLoading.Loading) let roleEntity = formState.values->getDictFromJsonObject->getEntityType let url = getURL( ~entityName=V1(USERS), ~userType=#LIST_ROLES_FOR_INVITE, ~methodType=Get, ~queryParamerters=Some(`entity_type=${roleEntity}`), ) let result = await fetchDetails(url) setOptions(_ => result->makeSelectBoxOptions) if result->getArrayFromJson([])->Array.length > 0 { setDropDownLoaderState(_ => DropdownWithLoading.Success) } else { setDropDownLoaderState(_ => DropdownWithLoading.NoData) } } catch { | _ => setDropDownLoaderState(_ => DropdownWithLoading.NoData) } } <div className="flex flex-col h-full"> <div className="grid grid-cols-1 sm:grid-cols-3 lg:grid-cols-6 xl:gap-6 items-end p-6 !pb-10 border-b"> <div className="col-span-1 sm:col-span-2 lg:col-span-5 w-full"> <FormRenderer.FieldRenderer field=inviteEmail labelClass="!text-black !text-base !-ml-[0.5px]" /> </div> <div className="col-span-1 sm:col-span-1 lg:col-span-1 w-full p-1"> <FormRenderer.SubmitButton text={"Send Invite"} loadingText="Loading..." buttonSize={Small} customSumbitButtonStyle="w-full !h-12" tooltipForWidthClass="w-full" /> </div> </div> <div className="grid grid-cols-1 lg:grid-cols-6 gap-6 h-full"> <div className="col-span-1 lg:col-span-3 border-r p-6 flex flex-col gap-4"> <OrganisationSelection /> <MerchantSelection /> <ProfileSelection /> <DropdownWithLoading options onClickDropDownApi formKey="role_id" dropDownLoaderState isRequired=true /> <NoteComponent /> </div> <div className="col-span-1 lg:col-span-3 p-6 flex flex-col gap-4"> {switch roleTypeValue { | Some(role) => <> <p className={`${p1MediumTextClass} !font-semibold py-2`}> {`Role Description - '${roleNameValue->snakeToTitle}'`->React.string} </p> <PageLoaderWrapper screenState> <div className="border rounded-md p-4 flex flex-col"> <RoleAccessOverview roleDict role /> </div> </PageLoaderWrapper> </> | None => <> <p className={`${p1MediumTextClass} !font-semibold`}> {"Role Description"->React.string} </p> <p className={`${p3RegularTextClass} text-gray-400`}> {"Choose a role to see its description"->React.string} </p> </> }} </div> </div> </div> }
1,991
9,518
hyperswitch-control-center
src/screens/UserManagement/UserRevamp/UserInfo.res
.res
let h2OptionalStyle = HSwitchUtils.getTextClass((H2, Optional)) module UserAction = { @react.component let make = (~value: UserManagementTypes.userDetailstype) => { open UserManagementTypes let url = RescriptReactRouter.useUrl() let {userHasAccess} = GroupACLHooks.useUserGroupACLHook() let userEmail = url.search ->LogicUtils.getDictFromUrlSearchParams ->Dict.get("email") ->Option.getOr("") let {userInfo: {orgId, merchantId, profileId, email}} = React.useContext( UserInfoProvider.defaultContext, ) let decideWhatToShow = { if userEmail === email { // User cannot update its own role NoActionAccess } else if userHasAccess(~groupAccess=UsersManage) === NoAccess { // User doesn't have user write access NoActionAccess } else if ( // Profile level user value.org.id->Option.getOr("") === orgId && value.merchant.id->Option.getOr("") === merchantId && value.profile.id->Option.getOr("") === profileId ) { ManageUser } else if ( // Merchant level user value.org.id->Option.getOr("") === orgId && value.merchant.id->Option.getOr("") === merchantId && value.profile.id->Option.isNone ) { ManageUser } else if ( // Org level user value.org.id->Option.getOr("") === orgId && value.merchant.id->Option.isNone && value.profile.id->Option.isNone ) { ManageUser } else { SwitchUser } } switch decideWhatToShow { | ManageUser => <ManageUserModal userInfoValue={value} /> | SwitchUser => <UserManagementHelper.SwitchMerchantForUserAction userInfoValue={value} /> | NoActionAccess => React.null } } } module TableRowForUserDetails = { @react.component let make = ( ~arrayValue: array<UserManagementTypes.userDetailstype>, ~parentIndex, ~noOfElementsInParent, ) => { open LogicUtils let tableElementCss = "text-left py-4 px-4 h-fit w-fit" let noOfElementsForMerchants = arrayValue->Array.length let borderStyle = index => noOfElementsForMerchants - 1 == index && parentIndex != noOfElementsInParent - 1 ? "border-b" : "" let cssValueWithMultipleValues = noOfElementsForMerchants > 1 ? "align-top" : "align-center" arrayValue ->Array.mapWithIndex((value, index) => { let (statusValue, statusColor) = value.status->UserUtils.getLabelForStatus let profileName = value.profile.name->isEmptyString ? value.profile.value : value.profile.name let merchantName = value.merchant.name->isEmptyString ? value.merchant.value : value.merchant.name <tr className={`${index->borderStyle}`}> <RenderIf condition={index == 0}> <td className={`${tableElementCss} ${cssValueWithMultipleValues} font-semibold`} rowSpan={noOfElementsForMerchants}> {merchantName->capitalizeString->React.string} </td> </RenderIf> <td className=tableElementCss> {profileName->React.string} </td> <td className=tableElementCss> {value.roleName->snakeToTitle->capitalizeString->React.string} </td> <td className=tableElementCss> <p className={`${statusColor} px-4 py-1 w-fit rounded-full`}> {(statusValue :> string)->React.string} </p> </td> <td className={`${tableElementCss} text-right`}> <UserAction value /> </td> </tr> }) ->React.array } } module UserAccessInfo = { @react.component let make = (~userData: array<UserManagementTypes.userDetailstype>) => { let tableHeaderCss = "py-2 px-4 text-sm font-normal text-gray-400" let groupByMerchantData = userData->UserUtils.groupByMerchants let getObjectForThekey = key => switch groupByMerchantData->Dict.get(key) { | Some(value) => value | None => [] } let noOfElementsInParent = groupByMerchantData ->Dict.keysToArray ->Array.length <div className="overflow-x-auto"> <table className="min-w-full border-collapse border-spacing-0"> <thead className="border-b"> <tr> <th className={`${tableHeaderCss} w-[15%] text-left`}> {"Merchants"->React.string} </th> <th className={`${tableHeaderCss} w-[15%] text-left`}> {"Profile Name"->React.string} </th> <th className={`${tableHeaderCss} w-[30%] text-left`}> {"Role"->React.string} </th> <th className={`${tableHeaderCss} w-[20%] text-left`}> {"Status"->React.string} </th> <th className={`${tableHeaderCss} w-[10%] text-left`}> {""->React.string} </th> </tr> </thead> <tbody> {groupByMerchantData ->Dict.keysToArray ->Array.mapWithIndex((items, parentIndex) => { <TableRowForUserDetails arrayValue={items->getObjectForThekey} parentIndex noOfElementsInParent /> }) ->React.array} </tbody> </table> </div> } } module UserDetails = { @react.component let make = (~userData: array<UserManagementTypes.userDetailstype>) => { open LogicUtils let url = RescriptReactRouter.useUrl() let userEmail = url.search ->getDictFromUrlSearchParams ->Dict.get("email") ->Option.getOr("") <div className="flex flex-col bg-white rounded-xl border p-6 gap-12"> <div className="flex gap-4"> <img alt="user_icon" src={`/icons/user_icon.svg`} className="h-16 w-16" /> <div> <p className=h2OptionalStyle> {userEmail->getNameFromEmail->React.string} </p> <p className="text-grey-600 opacity-40"> {userEmail->React.string} </p> </div> </div> <i className="font-semibold text-gray-400"> {"*Some roles are profile specific and may not be available for all profiles"->React.string} </i> <UserAccessInfo userData /> </div> } } @react.component let make = () => { open APIUtils open LogicUtils open UserUtils let getURL = useGetURL() let updateMethod = useUpdateMethod() let url = RescriptReactRouter.useUrl() let userEmail = url.search ->getDictFromUrlSearchParams ->Dict.get("email") ->Option.getOr("") let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let (userData, setUserData) = React.useState(_ => JSON.Encode.null->valueToType) let userDetailsFetch = async () => { try { setScreenState(_ => PageLoaderWrapper.Loading) let url = getURL(~entityName=V1(USERS), ~userType=#USER_DETAILS, ~methodType=Post) let body = [("email", userEmail->JSON.Encode.string)]->getJsonFromArrayOfJson let response = await updateMethod(url, body, Post) setUserData(_ => response->valueToType) setScreenState(_ => PageLoaderWrapper.Success) } catch { | _ => setScreenState(_ => PageLoaderWrapper.Error("Failed to fetch user details!")) } } React.useEffect(() => { userDetailsFetch()->ignore None }, []) <div className="flex flex-col overflow-y-scroll gap-12"> <div className="flex flex-col gap-2"> <PageUtils.PageHeading title={"Team management"} /> <BreadCrumbNavigation path=[{title: "Team management", link: "/users"}] currentPageTitle=userEmail cursorStyle="cursor-pointer" /> </div> <PageLoaderWrapper screenState> <UserDetails userData /> </PageLoaderWrapper> </div> }
1,899
9,519
hyperswitch-control-center
src/screens/UserManagement/UserRevamp/ManageUserModal.res
.res
let h2OptionalStyle = HSwitchUtils.getTextClass((H2, Optional)) let p1MediumStyle = HSwitchUtils.getTextClass((P1, Medium)) let p2RegularStyle = HSwitchUtils.getTextClass((P1, Regular)) let itemParentContainerCss = "flex flex-wrap gap-4 md:justify-between items-center" let itemsContainerCss = "flex flex-col items-start w-full md:w-auto" module ChangeRoleSection = { @react.component let make = (~defaultRole, ~options) => { open APIUtils open LogicUtils let getURL = useGetURL() let url = RescriptReactRouter.useUrl() let showToast = ToastState.useShowToast() let updateDetails = useUpdateMethod() let (userRole, setUserRole) = React.useState(_ => defaultRole) let userEmail = url.search ->getDictFromUrlSearchParams ->Dict.get("email") ->Option.getOr("") let input: ReactFinalForm.fieldRenderPropsInput = { name: "string", onBlur: _ => (), onChange: ev => { let value = ev->Identity.formReactEventToString setUserRole(_ => value) }, onFocus: _ => (), value: userRole->JSON.Encode.string, checked: true, } let updateRole = async () => { try { let url = getURL(~entityName=V1(USERS), ~methodType=Post, ~userType={#UPDATE_ROLE}) let body = [ ("email", userEmail->JSON.Encode.string), ("role_id", userRole->JSON.Encode.string), ]->getJsonFromArrayOfJson let _ = await updateDetails(url, body, Post) showToast(~message="Role successfully updated!", ~toastType=ToastSuccess) RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url="/users")) } catch { | _ => showToast(~message="Failed to update the role", ~toastType=ToastError) } } <div className=itemParentContainerCss> <div className=itemsContainerCss> <p className=p1MediumStyle> {"Change user role"->React.string} </p> <p className={`${p2RegularStyle} text-gray-400`}> {"Change the role in the current scope"->React.string} </p> </div> <div className="flex gap-4 items-center"> <SelectBox.BaseDropdown options searchable=false input hideMultiSelectButtons=true deselectDisable=true allowMultiSelect=false buttonText="Select role" fullLength=true /> <Button text="Update" buttonType=Secondary buttonState=Normal buttonSize={Small} onClick={_ => updateRole()->ignore} /> </div> </div> } } module ResendInviteSection = { @react.component let make = (~invitationStatus) => { open APIUtils open LogicUtils let getURL = useGetURL() let showToast = ToastState.useShowToast() let url = RescriptReactRouter.useUrl() let updateDetails = useUpdateMethod() let authId = HyperSwitchEntryUtils.getSessionData(~key="auth_id") let (statusValue, _) = invitationStatus->UserUtils.getLabelForStatus let userEmail = url.search ->getDictFromUrlSearchParams ->Dict.get("email") ->Option.getOr("") let resendInvite = async () => { try { let url = getURL( ~entityName=V1(USERS), ~userType=#RESEND_INVITE, ~methodType=Post, ~queryParamerters=Some(`auth_id=${authId}`), ) let body = [("email", userEmail->JSON.Encode.string)]->getJsonFromArrayOfJson let _ = await updateDetails(url, body, Post) showToast(~message="Invite resend. Please check your email.", ~toastType=ToastSuccess) } catch { | _ => showToast(~message="Failed to send the invite. Please try again!", ~toastType=ToastError) } } <div className=itemParentContainerCss> <div className=itemsContainerCss> <p className=p1MediumStyle> {"Resend invite"->React.string} </p> <p className={`${p2RegularStyle} text-gray-400`}> {"Resend invite to user"->React.string} </p> </div> <Button text="Resend" buttonType={Secondary} leftIcon={FontAwesome("paper-plane-outlined")} onClick={_ => resendInvite()->ignore} buttonState={statusValue === Active ? Button.Disabled : Button.Normal} /> </div> } } module DeleteUserRole = { @react.component let make = (~setShowModal) => { open APIUtils open LogicUtils let getURL = useGetURL() let showToast = ToastState.useShowToast() let url = RescriptReactRouter.useUrl() let updateDetails = useUpdateMethod() let showPopUp = PopUpState.useShowPopUp() let userEmail = url.search ->getDictFromUrlSearchParams ->Dict.get("email") ->Option.getOr("") let deleteUser = async () => { try { let url = getURL(~entityName=V1(USERS), ~methodType=Post, ~userType={#USER_DELETE}) let body = [("email", userEmail->JSON.Encode.string)]->getJsonFromArrayOfJson let _ = await updateDetails(url, body, Delete) showToast(~message=`User has been successfully deleted.`, ~toastType=ToastSuccess) RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url="/users")) } catch { | _ => showToast(~message=`Failed to delete the user.`, ~toastType=ToastError) } } let deleteConfirmation = () => { showPopUp({ popUpType: (Warning, WithIcon), heading: `Are you sure you want to delete this user?`, description: React.string(`This action cannot be undone. Deleting the user will permanently remove all associated data from this account. Press Confirm to delete.`), handleConfirm: {text: "Confirm", onClick: _ => deleteUser()->ignore}, handleCancel: {text: "Back"}, }) } <div className=itemParentContainerCss> <div className=itemsContainerCss> <p className=p1MediumStyle> {"Delete user role"->React.string} </p> <p className={`${p2RegularStyle} text-gray-400`}> {"User will be deleted from the current role"->React.string} </p> </div> <Button text="Delete" customButtonStyle="bg-white !text-red-400 " buttonType={Secondary} leftIcon={FontAwesome("delete")} onClick={_ => { setShowModal(_ => false) deleteConfirmation() }} /> </div> } } module ManageUserModalBody = { @react.component let make = (~options, ~defaultRole, ~invitationStatus, ~setShowModal) => { <div className="flex flex-col gap-16 p-2"> <p className="text-gray-600 text-start"> {"Perform various user-related actions such as modifying roles, removing users, or sending a new invitation."->React.string} </p> <div className="flex flex-col gap-6 "> <ChangeRoleSection options defaultRole /> <hr /> <ResendInviteSection invitationStatus /> <hr /> <DeleteUserRole setShowModal /> </div> </div> } } module ManageUserModal = { @react.component let make = (~showModal, ~setShowModal, ~userInfoValue: UserManagementTypes.userDetailstype) => { open APIUtils let getURL = useGetURL() let fetchDetails = useGetMethod() let (options, setOptions) = React.useState(_ => []) let fetchListOfRoles = async () => { try { let url = getURL( ~entityName=V1(USERS), ~userType=#LIST_ROLES_FOR_ROLE_UPDATE, ~methodType=Get, ~queryParamerters=Some(`entity_type=${userInfoValue.entityType}`), ) let response = await fetchDetails(url) setOptions(_ => response->UserUtils.makeSelectBoxOptions) } catch { | _ => setOptions(_ => [userInfoValue.roleId]->SelectBox.makeOptions) } } React.useEffect(() => { fetchListOfRoles()->ignore None }, []) <Modal showModal modalHeading="Manage user" modalHeadingClass=h2OptionalStyle setShowModal closeOnOutsideClick=true modalClass="m-auto !bg-white md:w-2/5 w-full"> <ManageUserModalBody options defaultRole={userInfoValue.roleId} invitationStatus={userInfoValue.status} setShowModal /> </Modal> } } @react.component let make = (~userInfoValue: UserManagementTypes.userDetailstype) => { let (showModal, setShowModal) = React.useState(_ => false) <> <Button text="Manage user" buttonType=Secondary buttonSize=Medium onClick={_ => setShowModal(_ => true)} /> <RenderIf condition={showModal}> <ManageUserModal userInfoValue showModal setShowModal /> </RenderIf> </> }
2,106
9,520