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/components/Graphs/BarGraph/BarGraphUtils.res
.res
// constants let fontFamily = "Arial, sans-serif" let darkGray = "#666666" let gridLineColor = "#e6e6e6" open BarGraphTypes let getBarGraphOptions = (barGraphOptions: barGraphPayload) => { let {categories, data, title, tooltipFormatter} = barGraphOptions let style = { fontFamily, fontSize: "12px", color: darkGray, } { chart: { \"type": "bar", spacingLeft: 20, spacingRight: 20, }, title: { text: "", }, xAxis: { categories, labels: { align: "center", style, }, tickWidth: 1, tickmarkPlacement: "on", endOnTick: false, startOnTick: false, gridLineWidth: 1, gridLineDashStyle: "Dash", gridLineColor, min: 0, }, yAxis: { title, labels: { align: "center", style, }, gridLineWidth: 1, gridLineDashStyle: "Solid", gridLineColor, tickInterval: 25, min: 0, max: 100, }, tooltip: { style: { padding: "0px", fontFamily, // Set the desired font family fontSize: "14px", // Optional: Set the font size }, shape: "square", shadow: false, backgroundColor: "transparent", borderColor: "transparent", borderWidth: 0.0, formatter: tooltipFormatter, useHTML: true, shared: true, // Allows multiple series' data to be shown in a single tooltip }, plotOptions: { bar: { marker: { enabled: false, }, pointPadding: 0.2, }, }, series: data, credits: { enabled: false, }, } }
444
10,121
hyperswitch-control-center
src/components/Graphs/PieGraph/PieGraphUtils.res
.res
open PieGraphTypes let getPieChartOptions = (pieGraphOptions: pieGraphPayload<'t>) => { let { data, title, legendFormatter, tooltipFormatter, chartSize, startAngle, endAngle, legend, } = pieGraphOptions let pieGraphTitle = { ...title, align: "center", verticalAlign: "bottom", // Centered vertically within the chart y: 9, // Adjust this value to fine-tune vertical position x: 0, style: { fontSize: "14px", fontWeight: "400", color: "#797979", fontStyle: "InterDisplay", }, useHTML: true, } { chart: { \"type": "pie", height: 200, width: 200, spacing: [0, 0, 0, 0], margin: [0, 0, 0, 0], }, accessibility: { enabled: false, // Disables accessibility features }, title: pieGraphTitle, plotOptions: { pie: { innerSize: "50%", // Creates the donut shape startAngle, // Start angle for full donut endAngle, // End angle for full donut showInLegend: true, // Ensures each point shows in the legend dataLabels: { enabled: false, }, // borderRadius: 8, size: chartSize, // center: ["50%", "83%"], }, }, tooltip: { style: { padding: "0px", fontFamily: "Inter Display, sans-serif", // Set the desired font family fontSize: "14px", // Optional: Set the font size }, shadow: false, backgroundColor: "transparent", borderWidth: 0.0, formatter: tooltipFormatter, useHTML: true, }, series: data, credits: { enabled: false, }, legend: { ...legend, labelFormatter: legendFormatter, }, } } let pieGraphColorSeries = [ "#72BEF4", "#CB80DC", "#BCBD22", "#5CB7AF", "#F36960", "#9467BD", "#7F7F7F", ] let pieGraphTooltipFormatter = ( ~title: string, ~valueFormatterType: LogicUtilsTypes.valueType, ~currency="", ~suffix="", ) => { ( @this (this: PieGraphTypes.pointFormatter) => { let value = this.y < 0.0 ? this.y *. -1.0 : this.y let valueString = value->LogicUtils.valueFormatter(valueFormatterType, ~currency, ~suffix) let title = `<div style="font-size: 16px; font-weight: bold;">${title}</div>` let tableItems = ` <div style="display: flex; align-items: center;"> <div style="width: 10px; height: 10px; background-color:${this.color}; border-radius:3px;"></div> <div style="margin-left: 8px;">${this.point.name}</div> <div style="flex: 1; text-align: right; font-weight: bold;margin-left: 25px;">${valueString}</div> </div> ` let content = ` <div style=" padding:5px 12px; display:flex; flex-direction:column; justify-content: space-between; gap: 7px;"> ${title} <div style=" margin-top: 5px; display:flex; flex-direction:column; gap: 7px;"> ${tableItems} </div> </div>` `<div style=" padding: 10px; width:fit-content; border-radius: 7px; background-color:#FFFFFF; padding:10px; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2); border: 1px solid #E5E5E5; position:relative;"> ${content} </div>` } )->PieGraphTypes.asTooltipPointFormatter } let pieGraphLegendFormatter = () => { ( @this (this: PieGraphTypes.legendLabelFormatter) => { let name = this.name->LogicUtils.snakeToTitle let title = `<div style="font-size: 10px; font-weight: bold;">${name} | ${this.y->Int.toString}</div>` title } )->PieGraphTypes.asLegendPointFormatter } let getCategoryWisePieChartPayload = ( ~data: array<categoryWiseBreakDown>, ~chartSize, ~toolTipStyle: toolTipStyle, ~showInLegend: bool=true, ~legend: legend, ) => { let totalAmount = data->Array.reduce(0.0, (acc, item) => { acc +. item.total }) let horizontalAlignTitle = switch showInLegend { | true => -95 | false => 0 } let title: PieGraphTypes.title = { text: ` <div className="flex flex-col items-center justify-center"> <p class="text-center mt-1 text-gray-800 text-2xl font-semibold font-inter-style">${totalAmount->LogicUtils.valueFormatter( toolTipStyle.valueFormatterType, )}</p> <p class="text-sm text-grey-500 font-inter-style px-4">${toolTipStyle.title}</p> </div> `, x: horizontalAlignTitle, } let pieGraphData = data->Array.mapWithIndex((ele, index) => { let data: PieGraphTypes.pieGraphDataType = { name: ele.name, y: ele.total, color: switch ele.color { | Some(color) => color | None => pieGraphColorSeries[index]->Option.getOr("") }, } data }) let pieGraphDataObj: PieGraphTypes.dataObj<'t> = { \"type": "pie", innerSize: "80%", showInLegend, name: "", data: pieGraphData, } let pieChatData = [pieGraphDataObj] let payLoad: PieGraphTypes.pieGraphPayload<'t> = { data: pieChatData, title, tooltipFormatter: pieGraphTooltipFormatter( ~title=toolTipStyle.title, ~valueFormatterType=toolTipStyle.valueFormatterType, ), legendFormatter: pieGraphLegendFormatter(), chartSize, startAngle: 0, endAngle: 360, legend, } payLoad }
1,542
10,122
hyperswitch-control-center
src/components/Graphs/PieGraph/PieGraphTypes.res
.res
type info = {index: int} type toolTipSeris = {name: string} type point = {name: string} type pointFormatter = { color: string, x: string, y: float, series: toolTipSeris, point: point, } type legendLabelFormatter = {name: string, y: int} external asTooltipPointFormatter: Js_OO.Callback.arity1<'a> => pointFormatter => string = "%identity" external asLegendPointFormatter: Js_OO.Callback.arity1<'a> => legendLabelFormatter => string = "%identity" type categories = array<string> type crosshair = bool type lineWidth = int type tickWidth = int type align = string type color = string type y = int type gridLineWidth = int type gridLineColor = string type gridLineDashStyle = string type tickmarkPlacement = string type endOnTick = bool type startOnTick = bool type min = int type showInLegend = bool type name = string type enabled = {enabled: bool} type credits = { ...enabled, } type style = { color: color, fontWeight?: string, fontSize?: string, fontStyle?: string, width?: string, dashStyle?: string, } type title = { text: string, align?: string, verticalAlign?: string, x?: int, y?: int, style?: style, useHTML?: bool, } type legend = { verticalAlign?: string, symbolRadius?: int, enabled: bool, layout?: string, align?: string, x?: int, // Adjust for fine-tuning the position y?: int, itemMarginBottom?: int, floating?: bool, labelFormatter?: legendLabelFormatter => string, } type dataLabels = { enabled: bool, distance?: int, style?: style, } type pie = { innerSize?: string, showInLegend: bool, startAngle: int, endAngle: int, center?: array<string>, size?: string, dataLabels: dataLabels, borderRadius?: int, } type cssStyle = { fontFamily: string, fontSize: string, padding: string, } type tooltip = { shape?: string, backgroundColor?: string, borderColor?: string, useHTML: bool, formatter: pointFormatter => string, shared?: bool, style?: cssStyle, borderWidth?: float, shadow?: bool, } type plotOptions = {pie: pie} type pieGraphDataType = { name: string, y: float, color?: string, } type dataObj<'t> = { \"type": string, innerSize: string, showInLegend: showInLegend, name: name, data: array<pieGraphDataType>, pointWidth?: int, pointPadding?: float, } type chart = { \"type": string, height: int, width: int, spacing: array<int>, margin: array<int>, } type pieCartData<'t> = array<dataObj<'t>> type pieGraphOptions<'t> = { chart: chart, accessibility: enabled, title?: title, plotOptions: plotOptions, series: pieCartData<'t>, legend?: legend, credits?: credits, tooltip?: tooltip, } type pieGraphPayload<'t> = { data: pieCartData<'t>, title: title, tooltipFormatter: pointFormatter => string, legendFormatter: legendLabelFormatter => string, chartSize: string, startAngle: int, endAngle: int, legend: legend, } type categoryWiseBreakDown = { name: string, total: float, color?: string, } type toolTipStyle = { title: string, valueFormatterType: LogicUtilsTypes.valueType, }
845
10,123
hyperswitch-control-center
src/components/Graphs/PieGraph/PieGraph.res
.res
external pieGraphOptionsToJson: PieGraphTypes.pieGraphOptions<'t> => JSON.t = "%identity" @react.component let make = (~options: PieGraphTypes.pieGraphOptions<'t>, ~className="") => { <div className> <Highcharts.DonutChart options={options->pieGraphOptionsToJson} highcharts={Highcharts.highcharts} /> </div> }
88
10,124
hyperswitch-control-center
src/components/Graphs/StackedBarGraph/StackedBarGraphUtils.res
.res
let fontFamily = "InterDisplay, sans-serif" let darkGray = "#525866" open StackedBarGraphTypes let getStackedBarGraphOptions = ( stackedBarGraphOptions: stackedBarGraphPayload, ~yMax, ~labelItemDistance, ) => { let {categories, data, labelFormatter} = stackedBarGraphOptions let style = { fontFamily, fontSize: "12px", color: darkGray, fill: darkGray, } { chart: { \"type": "bar", height: 80, spacingRight: 0, spacingLeft: 0, spacingTop: 0, style, }, title: { text: "", visible: false, }, xAxis: { categories, visible: false, }, yAxis: { title: { text: "", }, stackLabels: { enabled: true, }, visible: false, max: yMax, }, legend: { align: "left", x: 0, verticalAlign: "bottom", y: 10, floating: false, symbolHeight: 10, symbolWidth: 10, symbolRadius: 2, reversed: true, itemDistance: labelItemDistance, labelFormatter, }, tooltip: { enabled: false, }, plotOptions: { bar: { stacking: "normal", dataLabels: { enabled: false, }, borderWidth: 3, pointWidth: 30, borderRadius: 5, }, }, series: data, credits: { enabled: false, }, } } let stackedBarGraphLabelFormatter = (~statType: LogicUtilsTypes.valueType, ~currency="") => { open LogicUtils ( @this (this: labelFormatter) => { let name = this.name let yData = this.yData->getValueFromArray(0, 0)->Int.toFloat let formattedValue = LogicUtils.valueFormatter(yData, statType, ~currency) let title = `<div style="color: #525866; font-weight: 500;">${name}<span style="color: #99A0AE"> | ${formattedValue}</span></div>` title } )->asLabelFormatter }
531
10,125
hyperswitch-control-center
src/components/Graphs/StackedBarGraph/StackedBarGraph.res
.res
external stackedBarGraphOptionsToJson: StackedBarGraphTypes.stackedBarGraphOptions => JSON.t = "%identity" @react.component let make = (~options: StackedBarGraphTypes.stackedBarGraphOptions, ~className="") => { <div className> <Highcharts.Chart options={options->stackedBarGraphOptionsToJson} highcharts={Highcharts.highcharts} /> </div> }
90
10,126
hyperswitch-control-center
src/components/Graphs/StackedBarGraph/StackedBarGraphTypes.res
.res
type \"type" = string type spacingLeft = int type spacingRight = int type categories = array<string> type align = string type color = string type gridLineWidth = int type gridLineColor = string type gridLineDashStyle = string type tickmarkPlacement = string type endOnTick = bool type startOnTick = bool type tickInterval = int type tickWidth = int type min = int type max = int type showInLegend = bool type name = string type title = {text: string, visible: bool} type yAxisTitle = {text: string} type style = { color: color, fontFamily: string, fontSize: string, fill: string, } type enabled = {enabled: bool} type credits = { ...enabled, } type bar = { stacking: string, dataLabels: enabled, borderWidth: int, pointWidth: int, borderRadius: int, } type plotOptions = {bar: bar} type labels = { align: align, style: style, } type chart = { \"type": \"type", height: int, spacingRight: spacingRight, spacingLeft: spacingLeft, spacingTop: int, style: style, } type dataObj = { name: name, data: array<float>, color: color, } type data = array<dataObj> type yAxis = { title: yAxisTitle, visible: bool, stackLabels: enabled, max: int, } type xAxis = { categories: categories, visible: bool, } type point = {index: int} type pointFormatter = {point: point} type labelFormatter = {name: string, yData: array<int>} external asTooltipPointFormatter: Js_OO.Callback.arity1<'a> => pointFormatter => string = "%identity" external asLabelFormatter: Js_OO.Callback.arity1<'a> => labelFormatter => string = "%identity" type cssStyle = { fontFamily: string, fontSize: string, padding: string, } type tooltip = {enabled: bool} type legend = { align: string, verticalAlign: string, floating: bool, x: int, y: int, symbolHeight: int, symbolWidth: int, symbolRadius: int, itemDistance: int, reversed: bool, labelFormatter: labelFormatter => string, } type stackedBarGraphOptions = { chart: chart, title: title, xAxis: xAxis, yAxis: yAxis, plotOptions: plotOptions, series: data, credits: credits, tooltip: tooltip, legend: legend, } type payloadTitle = {text: string} type stackedBarGraphPayload = { categories: categories, data: data, labelFormatter: labelFormatter => string, }
614
10,127
hyperswitch-control-center
src/components/tooltip/ToolTip.resi
.resi
type toolTipPosition = Top | Bottom | Left | Right | TopRight | TopLeft | BottomLeft | BottomRight type contentPosition = Left | Right | Middle | Default type toolTipSize = Large | Medium | Small | XSmall type tooltipPositioning = [#absolute | #fixed | #static] @react.component let make: ( ~description: string=?, ~descriptionComponent: React.element=?, ~tooltipPositioning: tooltipPositioning=?, ~toolTipFor: React.element=?, ~tooltipWidthClass: string=?, ~tooltipForWidthClass: string=?, ~toolTipPosition: toolTipPosition=?, ~customStyle: string=?, ~arrowCustomStyle: string=?, ~textStyleGap: string=?, ~arrowBgClass: string=?, ~bgColor: string=?, ~contentAlign: contentPosition=?, ~justifyClass: string=?, ~flexClass: string=?, ~height: string=?, ~textStyle: string=?, ~hoverOnToolTip: bool=?, ~tooltipArrowSize: int=?, ~visibleOnClick: bool=?, ~descriptionComponentClass: string=?, ~isRelative: bool=?, ~dismissable: bool=?, ~newDesign: bool=?, ~iconOpacityVal: string=?, ) => React.element
296
10,128
hyperswitch-control-center
src/components/tooltip/ACLToolTip.res
.res
open ToolTip @react.component let make = ( ~authorization, ~noAccessDescription=HSwitchUtils.noAccessControlText, ~description="", ~descriptionComponent=React.null, ~tooltipPositioning: tooltipPositioning=#fixed, ~toolTipFor=?, ~tooltipWidthClass="w-fit", ~tooltipForWidthClass="", ~toolTipPosition: option<toolTipPosition>=?, ~customStyle="", ~arrowCustomStyle="", ~textStyleGap="", ~arrowBgClass="", ~bgColor="", ~contentAlign: contentPosition=Middle, ~justifyClass="justify-center", ~flexClass="flex-col", ~height="h-full", ~textStyle="text-fs-11", ~hoverOnToolTip=false, ~tooltipArrowSize=5, ~visibleOnClick=false, ~descriptionComponentClass="flex flex-row-reverse", ~isRelative=true, ~dismissable=false, ) => { let description = authorization === CommonAuthTypes.Access ? description : noAccessDescription <ToolTip description descriptionComponent tooltipPositioning ?toolTipFor tooltipWidthClass tooltipForWidthClass ?toolTipPosition customStyle arrowCustomStyle textStyleGap arrowBgClass bgColor contentAlign justifyClass flexClass height textStyle hoverOnToolTip tooltipArrowSize visibleOnClick descriptionComponentClass isRelative dismissable /> }
343
10,129
hyperswitch-control-center
src/components/tooltip/ACLToolTip.resi
.resi
@react.component let make: ( ~authorization: CommonAuthTypes.authorization, ~noAccessDescription: string=?, ~description: string=?, ~descriptionComponent: React.element=?, ~tooltipPositioning: ToolTip.tooltipPositioning=?, ~toolTipFor: React.element=?, ~tooltipWidthClass: string=?, ~tooltipForWidthClass: string=?, ~toolTipPosition: ToolTip.toolTipPosition=?, ~customStyle: string=?, ~arrowCustomStyle: string=?, ~textStyleGap: string=?, ~arrowBgClass: string=?, ~bgColor: string=?, ~contentAlign: ToolTip.contentPosition=?, ~justifyClass: string=?, ~flexClass: string=?, ~height: string=?, ~textStyle: string=?, ~hoverOnToolTip: bool=?, ~tooltipArrowSize: int=?, ~visibleOnClick: bool=?, ~descriptionComponentClass: string=?, ~isRelative: bool=?, ~dismissable: bool=?, ) => React.element
238
10,130
hyperswitch-control-center
src/components/tooltip/ToolTip.res
.res
type toolTipPosition = Top | Bottom | Left | Right | TopRight | TopLeft | BottomLeft | BottomRight type contentPosition = Left | Right | Middle | Default type toolTipSize = Large | Medium | Small | XSmall @send external getBoundingClientRect: Dom.element => Window.boundingClient = "getBoundingClientRect" type tooltipPositioning = [#fixed | #absolute | #static] let toolTipArrowBorder = 4 module TooltipMainWrapper = { @react.component let make = ( ~children, ~visibleOnClick, ~hoverOnToolTip, ~setIsToolTipVisible, ~isRelative, ~flexClass, ~height, ~contentAlign, ~justifyClass, ) => { let relativeClass = isRelative ? "relative" : "" let flexCss = hoverOnToolTip ? "inline-flex" : "flex" let alignClass = switch contentAlign { | Left => "items-start" | Right => "items-end" | Middle => "items-center" | Default => "" } let timeoutRef = React.useRef(None) let handleMouseOver = _ => { if !visibleOnClick { switch timeoutRef.current { | Some(timerId) => clearTimeout(timerId) | None => () } setIsToolTipVisible(_ => true) } } let handleClick = _ => { if visibleOnClick { switch timeoutRef.current { | Some(timerId) => clearTimeout(timerId) | None => () } setIsToolTipVisible(_ => true) } } let handleMouseOut = _ => { if hoverOnToolTip { timeoutRef.current = setTimeout(() => { setIsToolTipVisible(_ => false) }, 200)->Some } else { setIsToolTipVisible(_ => false) } } <AddDataAttributes attributes=[("data-tooltip", "tooltip")]> <div className={`${relativeClass} ${flexCss} ${flexClass} ${height} ${alignClass} ${justifyClass}`} onMouseOver=handleMouseOver onClick=handleClick onMouseOut=handleMouseOut> children </div> </AddDataAttributes> } } module TooltipWrapper = { let getToolTipFixedStyling = ( ~hoverOnToolTip, ~positionX, ~positionY, ~tooltipWidth, ~tooltipHeight, ~tooltipArrowSize, ~componentWidth, ~componentHeight, ~position, ) => { let toolTipTopPosition = switch position { | Top => hoverOnToolTip ? positionY - tooltipHeight - toolTipArrowBorder - (tooltipArrowSize - 5) - 4 : positionY - tooltipHeight - toolTipArrowBorder - 4 | Right => positionY - tooltipHeight / 2 + componentHeight / 2 | Bottom => hoverOnToolTip ? positionY + componentHeight + toolTipArrowBorder + (tooltipArrowSize - 5) + 4 : positionY + componentHeight + toolTipArrowBorder + 4 | BottomLeft | BottomRight => positionY + componentHeight + toolTipArrowBorder + 4 | Left => positionY - tooltipHeight / 2 + componentHeight / 2 | TopLeft | TopRight => positionY - tooltipHeight - toolTipArrowBorder - 4 } let toolTipLeftPosition = switch position { | Top => positionX - tooltipWidth / 2 + componentWidth / 2 | Right => hoverOnToolTip ? positionX + componentWidth + toolTipArrowBorder + (tooltipArrowSize - 5) + 4 : positionX + componentWidth + toolTipArrowBorder + 4 | Bottom => positionX - tooltipWidth / 2 + componentWidth / 2 | Left => hoverOnToolTip ? positionX - tooltipWidth - toolTipArrowBorder + 2 - (tooltipArrowSize - 5) - 4 : positionX - tooltipWidth - toolTipArrowBorder + 2 - 4 | TopLeft | BottomLeft => positionX + componentWidth / 2 - tooltipWidth + 9 | TopRight | BottomRight => positionX + componentWidth / 2 - 9 } ReactDOMStyle.make( ~top=`${toolTipTopPosition->Int.toString}px`, ~left=`${toolTipLeftPosition->Int.toString}px`, (), ) } let getToolTipAbsoluteStyling = ( ~tooltipArrowHeight, ~tooltipHeightFloat, ~tooltipArrowWidth, ~tooltipWidth, ~componentWidth, ~componentHeight, ~position, ) => { let toolTipTopPosition = switch position { | Top => tooltipArrowHeight /. componentHeight->Int.toFloat *. -100.0 +. tooltipHeightFloat /. componentHeight->Int.toFloat *. -100.0 | Right => 50.0 -. tooltipHeightFloat /. componentHeight->Int.toFloat *. 50.0 | Bottom => 100.0 +. tooltipArrowHeight /. componentHeight->Int.toFloat *. 100.0 | BottomLeft => 100.0 +. tooltipArrowHeight /. componentHeight->Int.toFloat *. 100.0 | BottomRight => 100.0 +. tooltipArrowHeight /. componentHeight->Int.toFloat *. 100.0 | Left => 50.0 -. tooltipHeightFloat /. componentHeight->Int.toFloat *. 50.0 | TopLeft => tooltipArrowHeight /. componentHeight->Int.toFloat *. -100.0 +. tooltipHeightFloat /. componentHeight->Int.toFloat *. -100.0 | TopRight => tooltipArrowHeight /. componentHeight->Int.toFloat *. -100.0 +. tooltipHeightFloat /. componentHeight->Int.toFloat *. -100.0 } let toolTipLeftPosition = switch position { | Top => 50.0 -. tooltipWidth->Int.toFloat /. componentWidth->Int.toFloat *. 50.0 | Right => 100.0 +. tooltipArrowWidth->Int.toFloat /. componentWidth->Int.toFloat *. 100.0 | Bottom => 50.0 -. tooltipWidth->Int.toFloat /. componentWidth->Int.toFloat *. 50.0 | Left => tooltipArrowWidth->Int.toFloat /. componentWidth->Int.toFloat *. -100.0 +. tooltipWidth->Int.toFloat /. componentWidth->Int.toFloat *. -100.0 | TopLeft => tooltipWidth->Int.toFloat /. componentWidth->Int.toFloat *. -50.0 | BottomLeft => tooltipWidth->Int.toFloat /. componentWidth->Int.toFloat *. -50.0 | TopRight => 100.0 +. tooltipWidth->Int.toFloat /. componentWidth->Int.toFloat *. -60.0 | BottomRight => 100.0 +. tooltipWidth->Int.toFloat /. componentWidth->Int.toFloat *. -60.0 } ReactDOMStyle.make( ~top=`${toolTipTopPosition->Float.toString}%`, ~left=`${toolTipLeftPosition->Float.toString}%`, (), ) } @react.component let make = ( ~isToolTipVisible, ~descriptionComponent, ~description, ~hoverOnToolTip, ~tooltipPositioning: tooltipPositioning, ~tooltipWidthClass, ~toolTipRef, ~textStyle, ~bgColor, ~customStyle, ~positionX, ~positionY, ~tooltipArrowHeight, ~tooltipHeightFloat, ~tooltipArrowWidth, ~tooltipWidth, ~tooltipHeight, ~tooltipArrowSize, ~componentWidth, ~componentHeight, ~toolTipPosition, ~defaultPosition, ~children, ) => { let descriptionExists = description->LogicUtils.isNonEmptyString || descriptionComponent != React.null let textStyle = textStyle let fontWeight = "font-semibold" let borderRadius = "rounded" let tooltipOpacity = isToolTipVisible && descriptionExists ? "opacity-100" : "opacity-0" let pointerEvents = if isToolTipVisible && hoverOnToolTip { "" } else { " pointer-events-none" } let toolTipPositionString = switch tooltipPositioning { | #fixed => "fixed" | #absolute => "absolute" | #static => "static" } let paddingClass = "p-3" let tooltipPositionStyle = if tooltipPositioning === #fixed { getToolTipFixedStyling( ~hoverOnToolTip, ~positionX, ~positionY, ~tooltipWidth, ~tooltipHeight, ~tooltipArrowSize, ~componentWidth, ~componentHeight, ~position=toolTipPosition->Option.getOr(defaultPosition), ) } else { getToolTipAbsoluteStyling( ~tooltipArrowHeight, ~tooltipHeightFloat, ~tooltipArrowWidth, ~tooltipWidth, ~componentWidth, ~componentHeight, ~position=toolTipPosition->Option.getOr(defaultPosition), ) } <div className={`${tooltipOpacity} ${pointerEvents}`}> <div className={`${toolTipPositionString} ${tooltipWidthClass} z-50 h-auto break-words`} style={ReactDOMStyle.combine(tooltipPositionStyle, ReactDOMStyle.make(~hyphens="auto", ()))} ref={toolTipRef->ReactDOM.Ref.domRef}> <div className={`relative whitespace-pre-line max-w-xs text-left ${paddingClass} ${textStyle} ${fontWeight} ${borderRadius} ${bgColor} ${customStyle}`}> children </div> </div> </div> } } module DescriptionSection = { @react.component let make = ( ~description, ~descriptionComponent, ~textStyleGap, ~descriptionComponentClass, ~setIsToolTipVisible, ~dismissable, ) => { <div className={textStyleGap}> {description ->String.split("\n") ->Array.filter(str => str->LogicUtils.isNonEmptyString) ->Array.mapWithIndex((item, i) => { <AddDataAttributes attributes=[("data-text", item)] key={i->Int.toString}> <div key={item} className="flex flex-col gap-1"> {React.string(item)} </div> </AddDataAttributes> }) ->React.array} <div className=descriptionComponentClass> <RenderIf condition=dismissable> <Icon name="popUpClose" className="stroke-jp-2-dark-gray-2000 cursor-pointer" parentClass="mt-5 mr-4" size=20 onClick={_ => setIsToolTipVisible(prev => !prev)} /> </RenderIf> {descriptionComponent} </div> </div> } } module TooltipFor = { @react.component let make = (~toolTipFor, ~tooltipForWidthClass, ~componentRef, ~opacityVal="50") => { let tooltipInfoIcon = "tooltip_info" let tooltipInfoIconSize = 16 let iconStrokeColor = "" <div className={`inline h-min desktop:flex ${tooltipForWidthClass}`} ref={componentRef->ReactDOM.Ref.domRef}> {switch toolTipFor { | Some(element) => element | None => <Icon name=tooltipInfoIcon size=tooltipInfoIconSize className={`opacity-${opacityVal} hover:opacity-100 dark:brightness-50 dark:opacity-35 dark:invert dark:hover:opacity-70 ${iconStrokeColor}`} /> }} </div> } } module Arrow = { let getArrowFixedPosition = ( ~hoverOnToolTip, ~positionX, ~positionY, ~tooltipArrowSize, ~componentWidth, ~componentHeight, ~arrowColor, ~position, ) => { let arrowTopPosition = switch position { | Top => hoverOnToolTip ? positionY - toolTipArrowBorder - (tooltipArrowSize - 5) - 5 : positionY - toolTipArrowBorder - 5 | TopLeft | TopRight => positionY - toolTipArrowBorder - 4 | Bottom | BottomRight | BottomLeft => positionY + componentHeight + 4 // | Left => positionY + componentHeight / 2 - toolTipArrowBorder - 20 | _ => positionY + componentHeight / 2 - toolTipArrowBorder } let arrowLeftPosition = switch position { | Left => hoverOnToolTip ? positionX - toolTipArrowBorder - (tooltipArrowSize - 5) - 4 : positionX - toolTipArrowBorder - 4 | Right => positionX + componentWidth + 4 | TopRight | BottomRight | TopLeft | BottomLeft => positionX + componentWidth / 2 - 5 | _ => positionX + componentWidth / 2 - 5 } let tooltipArrowpixel = `${tooltipArrowSize->Int.toString}px` let borderWidth = switch position { | Top => `${tooltipArrowpixel} ${tooltipArrowpixel} 0` | TopLeft => `${tooltipArrowpixel} ${tooltipArrowpixel} 0` | TopRight => `${tooltipArrowpixel} ${tooltipArrowpixel} 0` | Right => `${tooltipArrowpixel} ${tooltipArrowpixel} ${tooltipArrowpixel} 0` | Bottom => `0 ${tooltipArrowpixel} ${tooltipArrowpixel}` | BottomLeft => `0 ${tooltipArrowpixel} ${tooltipArrowpixel}` | BottomRight => `0 ${tooltipArrowpixel} ${tooltipArrowpixel}` | Left => `${tooltipArrowpixel} 0 ${tooltipArrowpixel} ${tooltipArrowpixel}` } let borderTopColor = if position === Top || position === TopLeft || position === TopRight { arrowColor } else { "transparent" } let borderRightColor = position === Right ? arrowColor : "transparent" let borderBottomColor = if ( position === Bottom || position === BottomLeft || position === BottomRight ) { arrowColor } else { "transparent" } let borderLeftColor = position === Left ? arrowColor : "transparent" ReactDOMStyle.make( ~top=`${arrowTopPosition->Int.toString}px`, ~left=`${arrowLeftPosition->Int.toString}px`, ~borderWidth, ~width="0", ~height="0", ~borderTopColor, ~borderRightColor, ~borderLeftColor, ~borderBottomColor, (), ) } let getArrowAbsolutePosition = ( ~tooltipArrowWidth, ~tooltipArrowHeight, ~tooltipHeightFloat, ~tooltipWidth, ~arrowColor, ~position, ) => { //calculations are in relative to the tooltip text let arrowTopPosition = switch position { | Top => 100.0 -. tooltipArrowHeight /. tooltipHeightFloat *. -10.0 | TopLeft => 100.0 -. tooltipArrowHeight /. tooltipHeightFloat *. -10.0 | TopRight => 100.0 -. tooltipArrowHeight /. tooltipHeightFloat *. -10.0 | Bottom => tooltipArrowHeight /. tooltipHeightFloat *. -100.0 | BottomRight => tooltipArrowHeight /. tooltipHeightFloat *. -100.0 | BottomLeft => tooltipArrowHeight /. tooltipHeightFloat *. -100.0 | _ => 50.0 -. tooltipArrowHeight /. tooltipHeightFloat *. 50.0 } let arrowLeftPosition = switch position { | Left => 100.0 +. tooltipArrowWidth->Int.toFloat /. tooltipWidth->Int.toFloat | Right => tooltipArrowWidth->Int.toFloat /. tooltipWidth->Int.toFloat *. -100.0 | _ => 50.0 -. tooltipArrowWidth->Int.toFloat /. tooltipWidth->Int.toFloat *. 50.0 } let borderWidth = switch position { | Top => "5px 5px 0" | TopLeft => "5px 5px 0" | TopRight => "5px 5px 0" | Right => "5px 5px 5px 0" | Bottom => "0 5px 5px" | BottomLeft => "0 5px 5px" | BottomRight => "0 5px 5px" | Left => "5px 0 5px 5px" } let borderTopColor = if position === Top || position === TopLeft || position === TopRight { arrowColor } else { "transparent" } let borderRightColor = position === Right ? arrowColor : "transparent" let borderBottomColor = if ( position === Bottom || position === BottomLeft || position === BottomRight ) { arrowColor } else { "transparent" } let borderLeftColor = position === Left ? arrowColor : "transparent" ReactDOMStyle.make( ~top=`${arrowTopPosition->Float.toString}%`, ~left=`${arrowLeftPosition->Float.toString}%`, ~borderWidth, ~width="0", ~height="0", ~borderTopColor, ~borderRightColor, ~borderLeftColor, ~borderBottomColor, (), ) } @react.component let make = ( ~toolTipArrowRef, ~arrowCustomStyle, ~tooltipPositioning: tooltipPositioning, ~toolTipPosition, ~hoverOnToolTip, ~positionX, ~positionY, ~tooltipArrowWidth, ~tooltipArrowHeight, ~tooltipHeightFloat, ~tooltipArrowSize, ~tooltipWidth, ~componentWidth, ~componentHeight, ~bgColor, ~arrowBgClass, ~defaultPosition, ) => { let theme = ThemeProvider.useTheme() let arrowBackGroundClass = switch theme { | Light => "#000" | Dark => "#fff" } let arrowColor = if ( arrowBgClass->LogicUtils.isNonEmptyString && bgColor->LogicUtils.isNonEmptyString ) { arrowBgClass } else { arrowBackGroundClass } let tooltipArrowPosition = switch toolTipPosition { | Some(position) => if tooltipPositioning === #fixed { getArrowFixedPosition( ~hoverOnToolTip, ~positionX, ~positionY, ~tooltipArrowSize, ~componentWidth, ~componentHeight, ~arrowColor, ~position, ) } else { getArrowAbsolutePosition( ~tooltipArrowWidth, ~tooltipArrowHeight, ~tooltipHeightFloat, ~tooltipWidth, ~arrowColor, ~position, ) } | None => getArrowFixedPosition( ~hoverOnToolTip, ~positionX, ~positionY, ~tooltipArrowSize, ~componentWidth, ~componentHeight, ~arrowColor, ~position=defaultPosition, ) } let toolTipPositionString = switch tooltipPositioning { | #fixed => "fixed" | #absolute => "absolute" | #static => "static" } <div style=tooltipArrowPosition ref={toolTipArrowRef->ReactDOM.Ref.domRef} className={`${arrowCustomStyle} ${toolTipPositionString} border-solid z-50 w-auto`} /> } } let getDefaultPosition = ( ~positionX, ~positionY, ~componentWidth, ~componentHeight, ~tooltipWidth, ~tooltipHeight, ) => { let tBoundingMidHeight = (componentHeight + tooltipHeight) / 2 let tBoundingMidWidth = (componentWidth + tooltipWidth) / 2 if Window.innerWidth / 2 > positionX { let rightPosition = if Window.innerHeight < tBoundingMidHeight + positionY { if positionX < tBoundingMidWidth { TopRight } else { Top } } else if 0 < tBoundingMidHeight - positionY { if positionX < tBoundingMidWidth { BottomRight } else { Bottom } } else { Right } rightPosition } else { let leftPosition = if Window.innerHeight < tBoundingMidHeight + positionY { if Window.innerWidth < positionX + tBoundingMidWidth { TopLeft } else { Top } } else if 0 < tBoundingMidHeight - positionY { if Window.innerWidth < positionX + tBoundingMidWidth { BottomLeft } else { Bottom } } else { Left } leftPosition } } @react.component let make = ( ~description="", ~descriptionComponent=React.null, ~tooltipPositioning: tooltipPositioning=#fixed, ~toolTipFor=?, ~tooltipWidthClass="w-fit", ~tooltipForWidthClass="", ~toolTipPosition: option<toolTipPosition>=?, ~customStyle="", ~arrowCustomStyle="", ~textStyleGap="", ~arrowBgClass="", ~bgColor="", ~contentAlign: contentPosition=Middle, ~justifyClass="justify-center", ~flexClass="flex-col", ~height="h-full", ~textStyle="text-xs leading-5", ~hoverOnToolTip=false, ~tooltipArrowSize=5, ~visibleOnClick=false, ~descriptionComponentClass="flex flex-row-reverse", ~isRelative=true, ~dismissable=false, ~newDesign=false, ~iconOpacityVal="50", (), ) => { let (isToolTipVisible, setIsToolTipVisible) = React.useState(_ => false) let toolTipRef = React.useRef(Nullable.null) let componentRef = React.useRef(Nullable.null) let toolTipArrowRef = React.useRef(Nullable.null) React.useEffect(() => { if isToolTipVisible { let handleScroll = _ => { setIsToolTipVisible(_ => false) } Window.addEventListener3("scroll", handleScroll, true) Some(() => Window.removeEventListener("scroll", handleScroll)) } else { None } }, [isToolTipVisible]) let getBoundingRectInfo = (ref: React.ref<Nullable.t<Dom.element>>, getter) => { ref.current->Nullable.toOption->Option.map(getBoundingClientRect)->Option.mapOr(0, getter) } let tooltipWidth = toolTipRef->getBoundingRectInfo(val => val.width) let tooltipHeight = toolTipRef->getBoundingRectInfo(val => val.height) let tooltipHeightFloat = tooltipHeight->Int.toFloat let tooltipArrowWidth = toolTipArrowRef->getBoundingRectInfo(val => val.width) let tooltipArrowHeight = toolTipArrowRef->getBoundingRectInfo(val => val.height)->Int.toFloat let positionX = componentRef->getBoundingRectInfo(val => val.x) let positionY = componentRef->getBoundingRectInfo(val => val.y) let componentWidth = componentRef->getBoundingRectInfo(val => val.width) let componentHeight = componentRef->getBoundingRectInfo(val => val.height) let tooltipBgClass = newDesign ? "bg-white rounded-lg shadow-lg ring-1 ring-black ring-opacity-5 text-jp-gray-800" : "dark:bg-jp-gray-tooltip_bg_dark bg-jp-gray-tooltip_bg_light dark:text-jp-gray-lightgray_background dark:text-opacity-75 text-jp-gray-text_darktheme text-opacity-75" let bgColor = bgColor->LogicUtils.isEmptyString ? tooltipBgClass : bgColor let defaultPosition = getDefaultPosition( ~positionX, ~positionY, ~componentWidth, ~componentHeight, ~tooltipWidth, ~tooltipHeight, ) <TooltipMainWrapper visibleOnClick hoverOnToolTip setIsToolTipVisible isRelative flexClass height contentAlign justifyClass> <TooltipFor toolTipFor tooltipForWidthClass componentRef opacityVal=iconOpacityVal /> <TooltipWrapper isToolTipVisible descriptionComponent description hoverOnToolTip tooltipPositioning tooltipWidthClass toolTipRef textStyle bgColor customStyle positionX positionY tooltipArrowHeight tooltipHeightFloat tooltipArrowWidth tooltipWidth tooltipHeight tooltipArrowSize componentWidth componentHeight toolTipPosition defaultPosition> <DescriptionSection description descriptionComponent textStyleGap descriptionComponentClass setIsToolTipVisible dismissable /> <Arrow toolTipArrowRef arrowCustomStyle tooltipPositioning hoverOnToolTip positionX positionY tooltipArrowWidth tooltipArrowHeight tooltipHeightFloat tooltipArrowSize tooltipWidth componentWidth componentHeight bgColor arrowBgClass toolTipPosition defaultPosition /> </TooltipWrapper> </TooltipMainWrapper> }
5,612
10,131
hyperswitch-control-center
src/components/priority-logics/AddPLGateway.res
.res
type gateway = RoutingTypes.volumeSplitConnectorSelectionData module GatewayView = { @react.component let make = (~gateways: array<gateway>) => { let url = RescriptReactRouter.useUrl() let {globalUIConfig: {font: {textColor}}} = React.useContext(ThemeProvider.themeContext) let connectorType: ConnectorTypes.connectorTypeVariants = switch url->RoutingUtils.urlToVariantMapper { | PayoutRouting => ConnectorTypes.PayoutProcessor | _ => ConnectorTypes.PaymentProcessor } let connectorList = ConnectorInterface.useConnectorArrayMapper( ~interface=ConnectorInterface.connectorInterfaceV1, ~retainInList=connectorType, ) let getGatewayName = merchantConnectorId => { ( connectorList->ConnectorTableUtils.getConnectorObjectFromListViaId(merchantConnectorId) ).connector_label } <div className="flex flex-wrap gap-4 items-center"> {gateways ->Array.mapWithIndex((ruleGateway, index) => { <div key={Int.toString(index)} className={`my-2 h-6 md:h-8 flex items-center rounded-md border border-jp-gray-500 dark:border-jp-gray-960 font-medium ${textColor.primaryNormal} hover:${textColor.primaryNormal} bg-gradient-to-b from-jp-gray-250 to-jp-gray-200 dark:from-jp-gray-950 dark:to-jp-gray-950 focus:outline-none px-2 gap-1`}> {React.string(ruleGateway.connector.merchant_connector_id->getGatewayName)} <RenderIf condition={ruleGateway.split !== 0}> <span className="text-jp-gray-700 dark:text-jp-gray-600 ml-1"> {React.string(ruleGateway.split->Int.toString ++ "%")} </span> </RenderIf> </div> }) ->React.array} </div> } } @react.component let make = ( ~id, ~gatewayOptions, ~isFirst=false, ~isExpanded=false, ~showPriorityIcon=true, ~showDistributionIcon=true, ~showFallbackIcon=true, ~dropDownButtonText="Add Gateways", ~connectorList, ) => { let gateWaysInput = ReactFinalForm.useField(`${id}`).input let gateWayName = merchantConnectorID => { connectorList->ConnectorTableUtils.getConnectorObjectFromListViaId(merchantConnectorID) } let isDistribute = id === "algorithm.data" || !( gateWaysInput.value ->LogicUtils.getArrayFromJson([]) ->Array.some(ele => ele->LogicUtils.getDictFromJsonObject->LogicUtils.getFloat("distribution", 0.0) === 100.0 ) ) let selectedOptions = gateWaysInput.value ->JSON.Decode.array ->Option.getOr([]) ->Belt.Array.keepMap(item => item ->JSON.Decode.object ->Option.flatMap(dict => { let connectorDict = dict->LogicUtils.getDictfromDict("connector") let obj: gateway = { connector: { connector: connectorDict->LogicUtils.getString("connector", ""), merchant_connector_id: connectorDict->LogicUtils.getString("merchant_connector_id", ""), }, split: dict->LogicUtils.getInt("split", 100), } Some(obj) }) ) let input: ReactFinalForm.fieldRenderPropsInput = { name: "gateways", onBlur: _ => (), onChange: ev => { let newSelectedOptions = ev->Identity.formReactEventToArrayOfString if newSelectedOptions->Array.length === 0 { gateWaysInput.onChange([]->Identity.anyTypeToReactEvent) } else { let sharePercent = isDistribute ? 100 / newSelectedOptions->Array.length : 100 let gatewaysArr = newSelectedOptions->Array.mapWithIndex((item, i) => { let sharePercent = if i === newSelectedOptions->Array.length - 1 && isDistribute { 100 - sharePercent * i } else { sharePercent } let obj: gateway = { connector: { connector: gateWayName(item).connector_name, merchant_connector_id: item, }, split: sharePercent, } obj }) gateWaysInput.onChange(gatewaysArr->Identity.anyTypeToReactEvent) } }, onFocus: _ => (), value: selectedOptions ->Array.map(selectedOption => selectedOption.connector.merchant_connector_id->JSON.Encode.string ) ->JSON.Encode.array, checked: true, } let updatePercentage = (item: gateway, value) => { if value < 100 { let newList = selectedOptions->Array.map(option => { if option.connector.connector === item.connector.connector { {...option, split: value} } else { option } }) gateWaysInput.onChange(newList->Identity.anyTypeToReactEvent) } } let removeItem = index => { input.onChange( selectedOptions ->Array.map(selectedOption => selectedOption.connector.merchant_connector_id) ->Array.filterWithIndex((_, i) => i !== index) ->Identity.anyTypeToReactEvent, ) } if isExpanded { <div className="flex flex-row ml-2"> <RenderIf condition={!isFirst}> <div className="w-8 h-10 border-jp-gray-700 ml-10 border-dashed border-b border-l " /> </RenderIf> <div className="flex flex-col gap-6 mt-6 mb-4 pt-0.5"> <div className="flex flex-wrap gap-4"> <div className="flex"> <SelectBox.BaseDropdown allowMultiSelect=true buttonText=dropDownButtonText buttonType=Button.SecondaryFilled hideMultiSelectButtons=true customButtonStyle="bg-white dark:bg-jp-gray-darkgray_background" input options={gatewayOptions} fixedDropDownDirection=SelectBox.TopRight searchable=true defaultLeftIcon={FontAwesome("plus")} maxHeight="max-h-full sm:max-h-64" /> <span className="text-lg text-red-500 ml-1"> {React.string("*")} </span> </div> {selectedOptions ->Array.mapWithIndex((item, i) => { let key = Int.toString(i + 1) { <div className="flex flex-row" key> <div className="w-min flex flex-row items-center justify-around gap-2 h-10 rounded-md border border-jp-gray-500 dark:border-jp-gray-960 text-jp-gray-900 hover:text-opacity-100 dark:text-jp-gray-text_darktheme dark:hover:text-jp-gray-text_darktheme dark:hover:text-opacity-75 text-opacity-50 hover:text-jp-gray-900 bg-gradient-to-b from-jp-gray-250 to-jp-gray-200 dark:from-jp-gray-950 dark:to-jp-gray-950 dark:text-opacity-50 focus:outline-none px-1 "> <NewThemeUtils.Badge number={i + 1} /> <div> {gateWayName( item.connector.merchant_connector_id, ).connector_label->React.string} </div> <Icon name="close" size=10 className="mr-2 cursor-pointer " onClick={ev => { ev->ReactEvent.Mouse.stopPropagation removeItem(i) }} /> <RenderIf condition={isDistribute && selectedOptions->Array.length > 0}> {<> <input className="w-10 text-right outline-none bg-white dark:bg-jp-gray-970 px-1 border border-jp-gray-300 dark:border-jp-gray-850 rounded-md" name=key onChange={ev => { let val = ReactEvent.Form.target(ev)["value"] updatePercentage(item, val->Int.fromString->Option.getOr(0)) }} value={item.split->Int.toString} type_="text" inputMode="text" /> <div> {React.string("%")} </div> </>} </RenderIf> </div> </div> } }) ->React.array} </div> </div> </div> } else { <GatewayView gateways=selectedOptions /> } }
1,911
10,132
hyperswitch-control-center
src/components/SingleStats/SingleStatEntity.res
.res
open AnalyticsTypesUtils type filterConfig = { source: string, // source can be BATCH, KVLOGS basically which DB to fetch modeValue: string, // modeValue can be ORDERS, TXN so here is the mode is orders we see data aggregated by the order_id and if mode is txn the data is aggregated by txn id simmilarly more mode can be added filterValues?: JSON.t, // which all filters will be applicable for the single stats (those keys i.e merchant_id, payment_gateway etc.) startTime: string, // start time from when data will fetch (later can be moved to the parent level) endTime: string, // end time till when data should be fetched (later can be moved to the parent level) customFilterValue: string, // custome filter key is the key by which stores the value of the applied customfilter in the url granularity?: (int, string), } type dataFetcherObj<'a> = { metrics: 'a, // metrics are the stats i.e total volume, success rate etc. bodyMaker: (string, filterConfig) => string, // to make the single stat body timeSeriedBodyMaker: (string, filterConfig) => string, // to make the single stat timeseries body transaformer: (string, JSON.t) => Dict.t<JSON.t>, // just in case if we are getting data from multiple places and we wanted to change the key or something so that we can identify it differently url: string, // url from where data need to be fetched domain: string, timeColumn: string, } type singleStatDataWidgetData = { title: string, // title of the single stat tooltipText: string, // tooltip of the single stat // deltaTooltipComponent: string => React.element, // delta tooltip hover compoment of the single stat statType: AnalyticsTypesUtils.metricsType, // wheather the metric which we are showing is a Rate, Volume, Latency showDelta: bool, // wheather to show the delta or not } type singleStatEntity<'a> = { dataFetcherObj: array<dataFetcherObj<'a>>, source: string, // from which source data has to be fetched modeKey: string, // the key of mode dropdown i.e by order mode or by txn mode filterKeys: array<string>, // filter keys the keys of filter which is stored in the url startTimeFilterKey: string, // end time filter key which we store in url(can be moved to parent level) endTimeFilterKey: string, // end time filter key which we store in url (can be moved to parent level) moduleName: string, // just the string module name which should be same across one module (later can be moved to the parent level) customFilterKey: string, // customFilterKey the key which is used in url for the customfilter metrixMapper: 'a => string, // it will map the current key with the the key which get from the api getStatDetails: ( 'a, 'a => string, dataState<JSON.t>, dataState<JSON.t>, dataState<JSON.t>, ) => singleStatDataWidgetData, jsonTransformer?: (string, array<JSON.t>) => array<JSON.t>, }
720
10,133
hyperswitch-control-center
src/components/modal/ModalContainer.res
.res
module ModalHeading = { @react.component let make = (~title, ~hideModal) => { let handleClick = React.useCallback(_ => { hideModal() }, [hideModal]) <div className="bg-purple-300 p-4 text-lg flex flex-row justify-between"> <div> {title->React.string} </div> <button className="text-purple-700" onClick=handleClick> <Icon name="times" /> </button> </div> } } module Modal = { external convertToWebapiEvent: ReactEvent.Mouse.t => Webapi.Dom.Event.t = "%identity" @react.component let make = (~modalProps: ModalsState.modalProps, ~hideModalAtIndex, ~index) => { let hideModal = React.useCallback(() => { hideModalAtIndex(index) }, (hideModalAtIndex, index)) let handleOutsideClick = React.useCallback(_ => { if modalProps.closeOnClickOutside { hideModal() } }, (modalProps.closeOnClickOutside, hideModal)) let stopPropagation = React.useCallback(ev => { ev->convertToWebapiEvent->Webapi.Dom.Event.stopPropagation }, []) <div className="absolute inset-0 overflow-scroll bg-gray-500 bg-opacity-50 flex flex-col items-center" onClick=handleOutsideClick> <div className="w-full md:w-4/5 lg:w-3/5 md:my-40 shadow-lg" onClick=stopPropagation> <ModalHeading title=modalProps.title hideModal /> <div className="bg-white p-4"> {modalProps.getContent(hideModal)} </div> </div> </div> } } @react.component let make = (~children) => { let (openModals, setOpenModals) = Recoil.useRecoilState(ModalsState.openModals) let hideModalAtIndex = React.useCallback(index => { setOpenModals(prevArr => { Array.filterWithIndex( prevArr, (_, i) => { i !== index }, ) }) }, [setOpenModals]) let fontClass = "font-ibm-plex" <div className={`relative ${fontClass}`}> children <div> {openModals ->Array.mapWithIndex((modalProps, i) => { <Modal key={Int.toString(i)} modalProps index=i hideModalAtIndex /> }) ->React.array} </div> </div> }
552
10,134
hyperswitch-control-center
src/Hypersense/HypersenseContainer/HypersenseHomeContainer.res
.res
@react.component let make = () => { <HypersenseHome /> }
19
10,135
hyperswitch-control-center
src/Hypersense/HypersenseContainer/HypersenseConfigurationContainer.res
.res
@react.component let make = () => { <HypersenseConfiguration /> }
19
10,136
hyperswitch-control-center
src/Hypersense/HypersenseScreens/HypersenseHome.res
.res
@react.component let make = () => { open APIUtils open LogicUtils open PageUtils let getURL = useGetURL() let fetchDetails = useGetMethod() let mixpanelEvent = MixpanelHook.useSendEvent() let onExploreClick = async () => { let hypersenseTokenUrl = getURL( ~entityName=V1(HYPERSENSE), ~methodType=Get, ~hypersenseType=#TOKEN, ) let res = await fetchDetails(hypersenseTokenUrl) let token = res->getDictFromJsonObject->getString("token", "") mixpanelEvent(~eventName="cost_observability-redirect") let url = `${Window.env.hypersenseUrl}/login?auth_token=${token}` url->Window._open } <div className="flex flex-1 flex-col gap-14 items-center justify-center w-full h-screen"> <img alt="hypersenseOnboarding" src="/assets/DefaultHomeHypersenseCard.svg" /> <div className="flex flex-col gap-8 items-center"> <div className="border rounded-md text-nd_green-200 border-nd_green-200 font-semibold p-1.5 text-sm w-fit"> {"Cost Observability"->React.string} </div> <PageHeading customHeadingStyle="gap-3 flex flex-col items-center" title="AI Ops tool built for Payments Cost Observability " customTitleStyle="text-2xl text-center font-bold text-nd_gray-700 font-500" customSubTitleStyle="text-fs-16 font-normal text-center max-w-700" subTitle="Audit, Observe and Optimize payment costs to uncover cost-saving opportunities" /> <Button text="Explore Cost Observability" onClick={_ => { mixpanelEvent(~eventName="cost_observability_explore") onExploreClick()->ignore }} customTextPaddingClass="pr-0" rightIcon={CustomIcon(<Icon name="nd-angle-right" size=16 className="cursor-pointer" />)} buttonType=Primary buttonSize=Large buttonState=Normal /> </div> </div> }
501
10,137
hyperswitch-control-center
src/Hypersense/HypersenseScreens/HypersenseConfiguration.res
.res
@react.component let make = () => { open PageUtils let mixpanelEvent = MixpanelHook.useSendEvent() let {setCreateNewMerchant} = React.useContext(ProductSelectionProvider.defaultContext) let userHasCreateMerchantAccess = OMPCreateAccessHook.useOMPCreateAccessHook([ #tenant_admin, #org_admin, ]) <div className="flex flex-1 flex-col gap-14 items-center justify-center w-full h-screen"> <img alt="hypersenseOnboarding" src="/assets/DefaultHomeHypersenseCard.svg" /> <div className="flex flex-col gap-8 items-center"> <div className="border rounded-md text-nd_green-200 border-nd_green-200 font-semibold p-1.5 text-sm w-fit"> {"Cost Observability"->React.string} </div> <PageHeading customHeadingStyle="gap-3 flex flex-col items-center" title="AI Ops tool built for Payments Cost Observability " customTitleStyle="text-2xl text-center font-bold text-nd_gray-700 font-500" customSubTitleStyle="text-fs-16 font-normal text-center max-w-700" subTitle="Audit, Observe and Optimize payment costs to uncover cost-saving opportunities" /> <ACLButton authorization={userHasCreateMerchantAccess} text="Get Started" onClick={_ => { mixpanelEvent(~eventName="cost_observability_get_started_new_merchant") setCreateNewMerchant(ProductTypes.CostObservability) }} customTextPaddingClass="pr-0" rightIcon={CustomIcon(<Icon name="nd-angle-right" size=16 className="cursor-pointer" />)} buttonType=Primary buttonSize=Large buttonState=Normal /> </div> </div> }
415
10,138
hyperswitch-control-center
src/Hypersense/HypersenseApp/HypersenseApp.res
.res
@react.component let make = () => { let url = RescriptReactRouter.useUrl() { switch url.path->HSwitchUtils.urlPath { | list{"v2", "cost-observability"} => <HypersenseConfigurationContainer /> | list{"v2", "cost-observability", "home"} => <HypersenseHomeContainer /> | _ => React.null } } }
93
10,139
hyperswitch-control-center
src/Hypersense/HypersenseApp/HypersenseSidebarValues.res
.res
open SidebarTypes let hypersenseConfiguration = { Link({ name: "Home", link: `/v2/cost-observability/home`, icon: "home", access: Access, selectedIcon: "home", }) } let hypersenseSidebars = { [hypersenseConfiguration] }
68
10,140
hyperswitch-control-center
src/container/TransactionContainer.res
.res
@react.component let make = () => { open HSwitchUtils open HyperswitchAtom let url = RescriptReactRouter.useUrl() let {userHasAccess} = GroupACLHooks.useUserGroupACLHook() let {userInfo: {transactionEntity}} = React.useContext(UserInfoProvider.defaultContext) let {payOut} = featureFlagAtom->Recoil.useRecoilValueFromAtom <div key={(transactionEntity :> string)}> {switch url.path->urlPath { | list{"payments", ...remainingPath} => <AccessControl authorization={userHasAccess(~groupAccess=OperationsView)}> <FilterContext key="payments" index="payments"> <EntityScaffold entityName="Payments" remainingPath access=Access renderList={() => <Orders />} renderCustomWithOMP={(id, profileId, merchantId, orgId) => <ShowOrder id profileId merchantId orgId />} /> </FilterContext> </AccessControl> | list{"payouts", ...remainingPath} => <AccessControl isEnabled={payOut} authorization={userHasAccess(~groupAccess=OperationsView)}> <FilterContext key="payouts" index="payouts"> <EntityScaffold entityName="Payouts" remainingPath access=Access renderList={() => <PayoutsList />} renderCustomWithOMP={(id, profileId, merchantId, orgId) => <ShowPayout id profileId merchantId orgId />} /> </FilterContext> </AccessControl> | list{"refunds", ...remainingPath} => <AccessControl authorization={userHasAccess(~groupAccess=OperationsView)}> <FilterContext key="refunds" index="refunds"> <EntityScaffold entityName="Refunds" remainingPath access=Access renderList={() => <Refund />} renderCustomWithOMP={(id, profileId, merchantId, orgId) => <ShowRefund id profileId merchantId orgId />} /> </FilterContext> </AccessControl> | list{"disputes", ...remainingPath} => <AccessControl authorization={userHasAccess(~groupAccess=OperationsView)}> <FilterContext key="disputes" index="disputes"> <EntityScaffold entityName="Disputes" remainingPath access=Access renderList={() => <Disputes />} renderCustomWithOMP={(id, profileId, merchantId, orgId) => <ShowDisputes id profileId merchantId orgId />} /> </FilterContext> </AccessControl> | list{"unauthorized"} => <UnauthorizedPage /> | _ => <NotFoundPage /> }} </div> }
612
10,141
hyperswitch-control-center
src/container/BusinessProfileContainer.res
.res
/* Modules that depend on Business Profiles data are located within this container. */ @react.component let make = () => { open HSwitchUtils open HyperswitchAtom let url = RescriptReactRouter.useUrl() let featureFlagDetails = featureFlagAtom->Recoil.useRecoilValueFromAtom let fetchBusinessProfiles = BusinessProfileHook.useFetchBusinessProfiles() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let setUpBussinessProfileContainer = async () => { try { setScreenState(_ => PageLoaderWrapper.Loading) let _ = await fetchBusinessProfiles() setScreenState(_ => PageLoaderWrapper.Success) } catch { | _ => setScreenState(_ => PageLoaderWrapper.Error("")) } } React.useEffect(() => { setUpBussinessProfileContainer()->ignore None }, []) <PageLoaderWrapper screenState={screenState} sectionHeight="!h-screen" showLogoutButton=true> {switch url.path->urlPath { // Business Profile Modules | list{"business-details"} => <AccessControl isEnabled=featureFlagDetails.default authorization={Access}> <BusinessDetails /> </AccessControl> | list{"business-profiles"} => <AccessControl authorization=Access> <BusinessProfile /> </AccessControl> | list{"unauthorized"} => <UnauthorizedPage /> | _ => <NotFoundPage /> }} </PageLoaderWrapper> }
318
10,142
hyperswitch-control-center
src/container/ConnectorContainer.res
.res
/* Modules that depend on Connector and Business Profiles data are located within this container. */ @react.component let make = () => { open HSwitchUtils open HyperswitchAtom let url = RescriptReactRouter.useUrl() let {userHasAccess} = GroupACLHooks.useUserGroupACLHook() let featureFlagDetails = featureFlagAtom->Recoil.useRecoilValueFromAtom let fetchConnectorListResponse = ConnectorListHook.useFetchConnectorList() let fetchBusinessProfiles = BusinessProfileHook.useFetchBusinessProfiles() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let setUpConnectoreContainer = async () => { try { setScreenState(_ => PageLoaderWrapper.Loading) if ( userHasAccess(~groupAccess=ConnectorsView) === Access || userHasAccess(~groupAccess=WorkflowsView) === Access || userHasAccess(~groupAccess=WorkflowsManage) === Access ) { let _ = await fetchConnectorListResponse() let _ = await fetchBusinessProfiles() } setScreenState(_ => PageLoaderWrapper.Success) } catch { | _ => setScreenState(_ => PageLoaderWrapper.Error("")) } } React.useEffect(() => { setUpConnectoreContainer()->ignore None }, []) <PageLoaderWrapper screenState={screenState} sectionHeight="!h-screen" showLogoutButton=true> {switch url.path->urlPath { // Connector Modules | list{"connectors", ...remainingPath} => <AccessControl authorization={userHasAccess(~groupAccess=ConnectorsView)}> <EntityScaffold entityName="Connectors" remainingPath renderList={() => <ConnectorList />} renderNewForm={() => <ConnectorHome />} renderShow={(_, _) => <ConnectorHome />} /> </AccessControl> | list{"payoutconnectors", ...remainingPath} => <AccessControl isEnabled={featureFlagDetails.payOut} authorization={userHasAccess(~groupAccess=ConnectorsView)}> <EntityScaffold entityName="PayoutConnectors" remainingPath renderList={() => <PayoutProcessorList />} renderNewForm={() => <PayoutProcessorHome />} renderShow={(_, _) => <PayoutProcessorHome />} /> </AccessControl> | list{"3ds-authenticators", ...remainingPath} => <AccessControl authorization={userHasAccess(~groupAccess=ConnectorsView)} isEnabled={featureFlagDetails.threedsAuthenticator}> <EntityScaffold entityName="3DS Authenticator" remainingPath renderList={() => <ThreeDsConnectorList />} renderNewForm={() => <ThreeDsProcessorHome />} renderShow={(_, _) => <ThreeDsProcessorHome />} /> </AccessControl> | list{"pm-authentication-processor", ...remainingPath} => <AccessControl authorization={userHasAccess(~groupAccess=ConnectorsView)} isEnabled={featureFlagDetails.pmAuthenticationProcessor}> <EntityScaffold entityName="PM Authentication Processor" remainingPath renderList={() => <PMAuthenticationConnectorList />} renderNewForm={() => <PMAuthenticationHome />} renderShow={(_, _) => <PMAuthenticationHome />} /> </AccessControl> | list{"tax-processor", ...remainingPath} => <AccessControl authorization={userHasAccess(~groupAccess=ConnectorsView)} isEnabled={featureFlagDetails.taxProcessor}> <EntityScaffold entityName="Tax Processor" remainingPath renderList={() => <TaxProcessorList />} renderNewForm={() => <TaxProcessorHome />} renderShow={(_, _) => <TaxProcessorHome />} /> </AccessControl> | list{"fraud-risk-management", ...remainingPath} => <AccessControl isEnabled={featureFlagDetails.frm} authorization={userHasAccess(~groupAccess=ConnectorsView)}> <EntityScaffold entityName="risk-management" remainingPath renderList={() => <FRMSelect />} renderNewForm={() => <FRMConfigure />} renderShow={(_, _) => <FRMConfigure />} /> </AccessControl> | list{"configure-pmts", ...remainingPath} => <AccessControl authorization={userHasAccess(~groupAccess=ConnectorsView)} isEnabled={featureFlagDetails.configurePmts}> <FilterContext key="ConfigurePmts" index="ConfigurePmts"> <EntityScaffold entityName="ConfigurePMTs" remainingPath renderList={() => <PaymentMethodList />} renderShow={(_, _) => <PaymentSettings webhookOnly=false showFormOnly=false />} /> </FilterContext> </AccessControl> // Routing | list{"routing", ...remainingPath} => <AccessControl authorization={userHasAccess(~groupAccess=WorkflowsView)}> <EntityScaffold entityName="Routing" remainingPath renderList={() => <RoutingStack remainingPath />} renderShow={(routingType, _) => <RoutingConfigure routingType />} /> </AccessControl> | list{"payoutrouting", ...remainingPath} => <AccessControl isEnabled={featureFlagDetails.payOut} authorization={userHasAccess(~groupAccess=WorkflowsView)}> <EntityScaffold entityName="PayoutRouting" remainingPath renderList={() => <PayoutRoutingStack remainingPath />} renderShow={(routingType, _) => <PayoutRoutingConfigure routingType />} /> </AccessControl> | list{"payment-settings", ...remainingPath} => <EntityScaffold entityName="PaymentSettings" remainingPath renderList={() => <PaymentSettingsList />} renderShow={(_, _) => <PaymentSettings webhookOnly=false showFormOnly=false />} /> | list{"webhooks", ...remainingPath} => <AccessControl isEnabled={featureFlagDetails.devWebhooks} authorization=Access> <FilterContext key="webhooks" index="webhooks"> <EntityScaffold entityName="Webhooks" remainingPath access=Access renderList={() => <Webhooks />} renderShow={(id, _) => <WebhooksDetails id />} /> </FilterContext> </AccessControl> | list{"unauthorized"} => <UnauthorizedPage /> | _ => <NotFoundPage /> }} </PageLoaderWrapper> }
1,406
10,143
hyperswitch-control-center
src/container/MerchantAccountContainer.res
.res
/* Modules that depend on Merchant data are located within this container. */ @react.component let make = (~setAppScreenState) => { open HSwitchUtils open HyperswitchAtom let url = RescriptReactRouter.useUrl() let (surveyModal, setSurveyModal) = React.useState(_ => false) let { userHasAccess, hasAnyGroupAccess, hasAllGroupsAccess, userHasResourceAccess, } = GroupACLHooks.useUserGroupACLHook() let featureFlagDetails = featureFlagAtom->Recoil.useRecoilValueFromAtom let {checkUserEntity} = React.useContext(UserInfoProvider.defaultContext) let merchantDetailsTypedValue = Recoil.useRecoilValueFromAtom(merchantDetailsValueAtom) <div> {switch url.path->urlPath { | list{"home"} => <Home setAppScreenState /> | list{"recon"} => <AccessControl isEnabled={featureFlagDetails.recon && !checkUserEntity([#Profile])} authorization={userHasResourceAccess(~resourceAccess=ReconToken)}> <Recon /> </AccessControl> | list{"upload-files"} => <AccessControl isEnabled={featureFlagDetails.recon && !checkUserEntity([#Profile])} authorization={userHasResourceAccess(~resourceAccess=ReconUpload)}> <ReconModule urlList={url.path->urlPath} /> </AccessControl> | list{"run-recon"} => <AccessControl isEnabled={featureFlagDetails.recon && !checkUserEntity([#Profile])} authorization={userHasResourceAccess(~resourceAccess=RunRecon)}> <ReconModule urlList={url.path->urlPath} /> </AccessControl> | list{"recon-analytics"} => <AccessControl isEnabled={featureFlagDetails.recon && !checkUserEntity([#Profile])} authorization={userHasResourceAccess(~resourceAccess=ReconAndSettlementAnalytics)}> <ReconModule urlList={url.path->urlPath} /> </AccessControl> | list{"reports"} => <AccessControl isEnabled={featureFlagDetails.recon && !checkUserEntity([#Profile])} authorization={userHasResourceAccess(~resourceAccess=ReconReports)}> <ReconModule urlList={url.path->urlPath} /> </AccessControl> | list{"config-settings"} => <AccessControl isEnabled={featureFlagDetails.recon && !checkUserEntity([#Profile])} authorization={userHasResourceAccess(~resourceAccess=ReconConfig)}> <ReconModule urlList={url.path->urlPath} /> </AccessControl> // Commented as not needed now // | list{"file-processor"} => // <AccessControl // isEnabled={featureFlagDetails.recon && !checkUserEntity([#Profile])} // authorization={userHasResourceAccess(~resourceAccess=ReconFiles)}> // <ReconModule urlList={url.path->urlPath} /> // </AccessControl> | list{"sdk"} => <AccessControl isEnabled={!featureFlagDetails.isLiveMode} authorization={hasAllGroupsAccess([ userHasAccess(~groupAccess=OperationsManage), userHasAccess(~groupAccess=ConnectorsManage), ])}> <SDKPage /> </AccessControl> | list{"unauthorized"} => <UnauthorizedPage /> | _ => <NotFoundPage /> }} <RenderIf condition={!featureFlagDetails.isLiveMode && // TODO: Remove `MerchantDetailsManage` permission in future hasAnyGroupAccess( userHasAccess(~groupAccess=MerchantDetailsManage), userHasAccess(~groupAccess=AccountManage), ) === Access && !checkUserEntity([#Profile]) && merchantDetailsTypedValue.merchant_name->Option.isNone}> <SbxOnboardingSurvey showModal=surveyModal setShowModal=setSurveyModal /> </RenderIf> </div> }
868
10,144
hyperswitch-control-center
src/container/APMContainer.res
.res
@react.component let make = () => { let url = RescriptReactRouter.useUrl() { switch url.path->HSwitchUtils.urlPath { | list{"apm"} => <AltPaymentMethods /> | _ => React.null } } }
59
10,145
hyperswitch-control-center
src/container/NewAnalyticsContainer.res
.res
@react.component let make = () => { open NewAnalyticsContainerUtils open LogicUtils open APIUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let url = RescriptReactRouter.useUrl() let {newAnalyticsSmartRetries, newAnalyticsRefunds} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let {updateExistingKeys} = React.useContext(FilterContext.filterContext) let (tabIndex, setTabIndex) = React.useState(_ => url->getPageIndex) let {filterValueJson} = React.useContext(FilterContext.filterContext) let startTimeVal = filterValueJson->getString("startTime", "") let endTimeVal = filterValueJson->getString("endTime", "") let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let {updateAnalytcisEntity} = OMPSwitchHooks.useUserInfo() let {userInfo: {analyticsEntity}, checkUserEntity} = React.useContext( UserInfoProvider.defaultContext, ) let mixpanelEvent = MixpanelHook.useSendEvent() let tempRecallAmountMetrics = async () => { try { //Currency Conversion is failing in Backend for the first time so to fix that we are the calling the api for one time and ignoring the error setScreenState(_ => Loading) let url = getURL( ~entityName=V1(ANALYTICS_PAYMENTS_V2), ~methodType=Post, ~id=Some("payments"), ) let date = (Date.make()->Date.toString->DayJs.getDayJsForString).format( "YYYY-MM-DDTHH:mm:00[Z]", ) let body = NewAnalyticsUtils.requestBody( ~startTime=date, ~endTime=date, ~metrics=[#sessionized_payment_processed_amount], ~filter=None, ) let _ = await updateDetails(url, body, Post) setScreenState(_ => Success) } catch { | _ => // Ignore the error setScreenState(_ => Success) } } React.useEffect(() => { tempRecallAmountMetrics()->ignore None }, []) React.useEffect(() => { let url = (getPageFromIndex(tabIndex) :> string) RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url)) None }, [tabIndex]) let setInitialFilters = HSwitchRemoteFilter.useSetInitialFilters( ~updateExistingKeys, ~startTimeFilterKey, ~endTimeFilterKey, ~compareToStartTimeKey, ~compareToEndTimeKey, ~origin="analytics", ~isInsightsPage=true, ~enableCompareTo=Some(true), ~range=6, ~comparisonKey, (), ) React.useEffect(() => { setInitialFilters() None }, []) //This is to trigger the mixpanel event to see active analytics users React.useEffect(() => { if startTimeVal->LogicUtils.isNonEmptyString && endTimeVal->LogicUtils.isNonEmptyString { mixpanelEvent(~eventName="new_analytics_payment_date_filter") } None }, (startTimeVal, endTimeVal)) let dateDropDownTriggerMixpanelCallback = () => { mixpanelEvent(~eventName="new_analytics_payment_date_filter_opened") } let tabs: array<Tabs.tab> = [ { title: "Payments", renderContent: () => <div className="mt-5"> <NewPaymentAnalytics /> </div>, }, ] if newAnalyticsSmartRetries { tabs->Array.push({ title: "Smart Retries", renderContent: () => <NewSmartRetryAnalytics />, }) } if newAnalyticsRefunds { tabs->Array.push({ title: "Refunds", renderContent: () => <NewRefundsAnalytics />, }) } <PageLoaderWrapper key={(analyticsEntity :> string)} screenState> <div> <PageUtils.PageHeading title="Insights" /> <div className="-ml-1 sticky top-0 z-30 p-1 bg-hyperswitch_background/70 py-1 rounded-lg my-2"> <DynamicFilter title="NewAnalytics" initialFilters=[] options=[] popupFilterFields=[] initialFixedFilters={initialFixedFilterFields( ~compareWithStartTime=startTimeVal, ~compareWithEndTime=endTimeVal, ~events=dateDropDownTriggerMixpanelCallback, )} defaultFilterKeys=[ startTimeFilterKey, endTimeFilterKey, compareToStartTimeKey, compareToEndTimeKey, comparisonKey, ] tabNames=[] key="0" updateUrlWith=updateExistingKeys filterFieldsPortalName={HSAnalyticsUtils.filterFieldsPortalName} showCustomFilter=false refreshFilters=false /> </div> <Portal to="NewAnalyticsOMPView"> <OMPSwitchHelper.OMPViews views={OMPSwitchUtils.analyticsViewList(~checkUserEntity)} selectedEntity={analyticsEntity} onChange={updateAnalytcisEntity} entityMapper=UserInfoUtils.analyticsEntityMapper /> </Portal> <Tabs initialIndex={url->getPageIndex} tabs onTitleClick={tabId => setTabIndex(_ => tabId)} disableIndicationArrow=true showBorder=true includeMargin=false lightThemeColor="black" defaultClasses="font-ibm-plex w-max flex flex-auto flex-row items-center justify-center px-6 font-semibold text-body" textStyle="text-blue-600" selectTabBottomBorderColor="bg-blue-600" /> </div> </PageLoaderWrapper> }
1,249
10,146
hyperswitch-control-center
src/container/AnalyticsContainer.res
.res
@react.component let make = () => { open HSwitchUtils open HyperswitchAtom let url = RescriptReactRouter.useUrl() let {userHasAccess} = GroupACLHooks.useUserGroupACLHook() let {userInfo: {analyticsEntity}, checkUserEntity} = React.useContext( UserInfoProvider.defaultContext, ) let {performanceMonitor, disputeAnalytics, authenticationAnalytics} = featureFlagAtom->Recoil.useRecoilValueFromAtom <div key={(analyticsEntity :> string)}> {switch url.path->urlPath { | list{"analytics-payments"} => <AccessControl authorization={userHasAccess(~groupAccess=AnalyticsView)}> <FilterContext key="PaymentsAnalytics" index="PaymentsAnalytics"> <PaymentAnalytics /> </FilterContext> </AccessControl> | list{"analytics-refunds"} => <AccessControl authorization={userHasAccess(~groupAccess=AnalyticsView)}> <FilterContext key="PaymentsRefunds" index="PaymentsRefunds"> <RefundsAnalytics /> </FilterContext> </AccessControl> | list{"analytics-disputes"} => <AccessControl isEnabled={disputeAnalytics} authorization={userHasAccess(~groupAccess=AnalyticsView)}> <FilterContext key="DisputeAnalytics" index="DisputeAnalytics"> <DisputeAnalytics /> </FilterContext> </AccessControl> | list{"analytics-authentication"} => <AccessControl isEnabled={authenticationAnalytics && [#Tenant, #Organization, #Merchant]->checkUserEntity} authorization={userHasAccess(~groupAccess=AnalyticsView)}> <FilterContext key="AuthenticationAnalytics" index="AuthenticationAnalytics"> <NewAuthenticationAnalytics /> </FilterContext> </AccessControl> | list{"performance-monitor"} => <AccessControl authorization={userHasAccess(~groupAccess=AnalyticsView)} isEnabled={performanceMonitor}> <FilterContext key="PerformanceMonitor" index="PerformanceMonitor"> <PerformanceMonitor domain="payments" /> </FilterContext> </AccessControl> | list{"unauthorized"} => <UnauthorizedPage /> | _ => <NotFoundPage /> }} </div> }
468
10,147
hyperswitch-control-center
src/container/UserManagementContainer.res
.res
/* This container holds the APIs needed for all user management-related modules. It ensures that the necessary data is available before any user management component loads. Pre-requisite APIs : - ROLE_INFO : To get the list available authorizations for modules */ @react.component let make = () => { open HSwitchUtils open APIUtils let getURL = useGetURL() let fetchDetails = useGetMethod() let url = RescriptReactRouter.useUrl() let {userHasAccess} = GroupACLHooks.useUserGroupACLHook() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let setRoleInfo = Recoil.useSetRecoilState(HyperswitchAtom.moduleListRecoil) let fetchModuleList = async () => { try { if userHasAccess(~groupAccess=UsersManage) === Access { let url = getURL( ~entityName=V1(USERS), ~userType=#ROLE_INFO, ~methodType=Get, ~queryParamerters=Some(`groups=true`), ) let res = await fetchDetails(url) let roleInfo = res->LogicUtils.getArrayDataFromJson(UserUtils.itemToObjMapperForGetRoleInfro) setRoleInfo(_ => roleInfo) } setScreenState(_ => PageLoaderWrapper.Success) } catch { | _ => setScreenState(_ => PageLoaderWrapper.Error("")) } } React.useEffect(() => { fetchModuleList()->ignore None }, []) <PageLoaderWrapper screenState={screenState} sectionHeight="!h-screen" showLogoutButton=true> {switch url.path->urlPath { // User Management modules | list{"users", "invite-users"} => <AccessControl authorization={userHasAccess(~groupAccess=UsersManage)}> <InviteMember /> </AccessControl> | list{"users", "create-custom-role"} => <AccessControl authorization={userHasAccess(~groupAccess=UsersManage)}> <CreateCustomRole baseUrl="users" breadCrumbHeader="Team management" /> </AccessControl> | list{"users", ...remainingPath} => <AccessControl authorization={userHasAccess(~groupAccess=UsersView)}> <EntityScaffold entityName="UserManagement" remainingPath renderList={_ => <UserManagementLanding />} renderShow={(_, _) => <UserInfo />} /> </AccessControl> | list{"unauthorized"} => <UnauthorizedPage /> | _ => <NotFoundPage /> }} </PageLoaderWrapper> }
560
10,148
hyperswitch-control-center
src/APIUtils/APIUtilsTypes.res
.res
type entityName = | CONNECTOR | ROUTING | MERCHANT_ACCOUNT | UPDATE_ORGANIZATION | REFUNDS | REFUND_FILTERS | DISPUTES | DISPUTE_FILTERS | PAYOUTS | PAYOUTS_FILTERS | ANALYTICS_FILTERS | ANALYTICS_PAYMENTS | ANALYTICS_DISPUTES | ANALYTICS_REFUNDS | ANALYTICS_AUTHENTICATION | ANALYTICS_AUTHENTICATION_V2 | ANALYTICS_AUTHENTICATION_V2_FILTERS | API_KEYS | ORDERS | ORDER_FILTERS | ORDERS_AGGREGATE | REFUNDS_AGGREGATE | DISPUTES_AGGREGATE | DEFAULT_FALLBACK | SDK_EVENT_LOGS | WEBHOOK_EVENTS | WEBHOOK_EVENTS_ATTEMPTS | WEBHOOKS_EVENTS_RETRY | WEBHOOKS_EVENT_LOGS | CONNECTOR_EVENT_LOGS | GENERATE_SAMPLE_DATA | USERS | RECON | INTEGRATION_DETAILS | FRAUD_RISK_MANAGEMENT | USER_MANAGEMENT | THREE_DS | BUSINESS_PROFILE | VERIFY_APPLE_PAY | PAYMENT_REPORT | REFUND_REPORT | DISPUTE_REPORT | AUTHENTICATION_REPORT | PAYPAL_ONBOARDING | PAYPAL_ONBOARDING_SYNC | ACTION_URL | RESET_TRACKING_ID | SURCHARGE | CUSTOMERS | PAYMENT_METHODS | PAYMENT_METHODS_DETAILS | ACCEPT_DISPUTE | DISPUTES_ATTACH_EVIDENCE | PAYOUT_DEFAULT_FALLBACK | PAYOUT_ROUTING | ACTIVE_PAYOUT_ROUTING | ACTIVE_ROUTING | GLOBAL_SEARCH | PAYMENT_METHOD_CONFIG | API_EVENT_LOGS | ANALYTICS_PAYMENTS_V2 | ANALYTICS_SANKEY | HYPERSENSE | SIMULATE_INTELLIGENT_ROUTING | INTELLIGENT_ROUTING_RECORDS | INTELLIGENT_ROUTING_GET_STATISTICS type v2entityNameType = | CUSTOMERS | V2_CONNECTOR | V2_ORDERS_LIST | PAYMENT_METHOD_LIST | RETRIEVE_PAYMENT_METHOD | V2_ORDER_FILTERS | USERS | TOTAL_TOKEN_COUNT | MERCHANT_ACCOUNT type userRoleTypes = USER_LIST | ROLE_LIST | ROLE_ID | NONE type reconType = [#TOKEN | #REQUEST | #NONE] type hypersenseType = [#TOKEN | #HOME | #NONE] type userType = [ | #CONNECT_ACCOUNT | #SIGNUP | #SIGNINV2 | #SIGNOUT | #FORGOT_PASSWORD | #RESET_PASSWORD | #VERIFY_EMAIL_REQUEST | #VERIFY_EMAILV2 | #ACCEPT_INVITE_FROM_EMAIL | #SET_METADATA | #GROUP_ACCESS_INFO | #ROLE_INFO | #MERCHANT_DATA | #USER_DATA | #USER_DELETE | #USER_UPDATE | #UPDATE_ROLE | #INVITE_MULTIPLE | #RESEND_INVITE | #CREATE_ORG | #CREATE_MERCHANT | #GET_GROUP_ACL | #CREATE_CUSTOM_ROLE | #FROM_EMAIL | #USER_INFO | #ROTATE_PASSWORD | #BEGIN_TOTP | #VERIFY_TOTP | #VERIFY_RECOVERY_CODE | #GENERATE_RECOVERY_CODES | #TERMINATE_TWO_FACTOR_AUTH | #CHECK_TWO_FACTOR_AUTH_STATUS | #RESET_TOTP | #GET_AUTH_LIST | #AUTH_SELECT | #SIGN_IN_WITH_SSO | #CHANGE_PASSWORD | #SWITCH_ORG | #SWITCH_MERCHANT_NEW | #SWITCH_PROFILE | #LIST_ORG | #LIST_MERCHANT | #LIST_PROFILE | #LIST_ROLES_FOR_INVITE | #SWITCH_ORG | #SWITCH_PROFILE | #ROLE_INFO | #LIST_INVITATION | #ACCEPT_INVITATION_PRE_LOGIN | #USER_DETAILS | #LIST_ROLES_FOR_ROLE_UPDATE | #ACCEPT_INVITATION_HOME | #CHECK_TWO_FACTOR_AUTH_STATUS_V2 | #NONE ] type entityTypeWithVersion = V1(entityName) | V2(v2entityNameType) type getUrlTypes = ( ~entityName: entityTypeWithVersion, ~methodType: Fetch.requestMethod, ~id: option<string>=?, ~connector: option<string>=?, ~userType: userType=?, ~userRoleTypes: userRoleTypes=?, ~reconType: reconType=?, ~hypersenseType: hypersenseType=?, ~queryParamerters: option<string>=?, ) => string
1,114
10,149
hyperswitch-control-center
src/APIUtils/APIUtils.res
.res
open LogicUtils open APIUtilsTypes exception JsonException(JSON.t) let getV2Url = ( ~entityName: v2entityNameType, ~userType: userType=#NONE, ~methodType: Fetch.requestMethod, ~id=None, ~profileId, ~merchantId, ~queryParamerters: option<string>=None, ) => { let connectorBaseURL = "v2/connector-accounts" let peymantsBaseURL = "v2/payments" switch entityName { | CUSTOMERS => switch (methodType, id) { | (Get, None) => "v2/customers/list" | (Get, Some(customerId)) => `v2/customers/${customerId}` | _ => "" } | V2_CONNECTOR => switch methodType { | Get => switch id { | Some(connectorID) => `${connectorBaseURL}/${connectorID}` | None => `v2/profiles/${profileId}/connector-accounts` } | Put => switch id { | Some(connectorID) => `${connectorBaseURL}/${connectorID}` | None => connectorBaseURL } | Post => switch id { | Some(connectorID) => `${connectorBaseURL}/${connectorID}` | None => connectorBaseURL } | _ => "" } | V2_ORDERS_LIST => switch methodType { | Get => switch id { | Some(key_id) => switch queryParamerters { | Some(queryParams) => `${peymantsBaseURL}/${key_id}?${queryParams}` | None => `${peymantsBaseURL}/${key_id}` } | None => switch queryParamerters { | Some(queryParams) => `${peymantsBaseURL}/list?${queryParams}` | None => `${peymantsBaseURL}/list?limit=100` } } | _ => "" } | V2_ORDER_FILTERS => "v2/payments/profile/filter" | PAYMENT_METHOD_LIST => switch id { | Some(customerId) => `v2/customers/${customerId}/saved-payment-methods` | None => "" } | TOTAL_TOKEN_COUNT => `v2/customers/total-payment-methods` | RETRIEVE_PAYMENT_METHOD => switch id { | Some(paymentMethodId) => `v2/payment-methods/${paymentMethodId}` | None => "" } /* MERCHANT ACCOUNT DETAILS (Get,Post and Put) */ | MERCHANT_ACCOUNT => `v2/merchant-accounts/${merchantId}` | USERS => let userUrl = `user` switch userType { | #CREATE_MERCHANT => switch queryParamerters { | Some(params) => `v2/${userUrl}/${(userType :> string)->String.toLowerCase}?${params}` | None => `v2/${userUrl}/${(userType :> string)->String.toLowerCase}` } | #LIST_MERCHANT => `v2/${userUrl}/list/merchant` | #SWITCH_MERCHANT_NEW => `v2/${userUrl}/switch/merchant` | #LIST_PROFILE => `v2/${userUrl}/list/profile` | _ => "" } } } let useGetURL = () => { let {getUserInfoData} = React.useContext(UserInfoProvider.defaultContext) let getUrl = ( ~entityName: entityTypeWithVersion, ~methodType: Fetch.requestMethod, ~id=None, ~connector=None, ~userType: userType=#NONE, ~userRoleTypes: userRoleTypes=NONE, ~reconType: reconType=#NONE, ~hypersenseType: hypersenseType=#NONE, ~queryParamerters: option<string>=None, ) => { let {transactionEntity, analyticsEntity, userEntity, merchantId, profileId} = getUserInfoData() let connectorBaseURL = `account/${merchantId}/connectors` let endpoint = switch entityName { | V1(entityNameType) => switch entityNameType { /* GLOBAL SEARCH */ | GLOBAL_SEARCH => switch methodType { | Post => switch id { | Some(topic) => `analytics/v1/search/${topic}` | None => `analytics/v1/search` } | _ => "" } /* MERCHANT ACCOUNT DETAILS (Get and Post) */ | MERCHANT_ACCOUNT => `accounts/${merchantId}` /* ORGANIZATION UPDATE */ | UPDATE_ORGANIZATION => switch methodType { | Put => switch id { | Some(id) => `organization/${id}` | None => `organization` } | _ => "" } /* CUSTOMERS DETAILS */ | CUSTOMERS => switch methodType { | Get => switch id { | Some(customerId) => `customers/${customerId}` | None => switch queryParamerters { | Some(queryParams) => `customers/list?${queryParams}` | None => `customers/list?limit=500` } } | _ => "" } | PAYMENT_METHODS => switch methodType { | Get => "payemnt_methods" | _ => "" } | PAYMENT_METHODS_DETAILS => switch methodType { | Get => switch id { | Some(id) => `payemnt_methods/${id}` | None => `payemnt_methods` } | _ => "" } /* CONNECTORS & FRAUD AND RISK MANAGEMENT */ | FRAUD_RISK_MANAGEMENT | CONNECTOR => switch methodType { | Get => switch id { | Some(connectorID) => `${connectorBaseURL}/${connectorID}` | None => switch userEntity { | #Tenant | #Organization | #Merchant | #Profile => `account/${merchantId}/profile/connectors` } } | Post | Delete => switch connector { | Some(_con) => `account/connectors/verify` | None => switch id { | Some(connectorID) => `${connectorBaseURL}/${connectorID}` | None => connectorBaseURL } } | _ => "" } /* OPERATIONS */ | REFUND_FILTERS => switch methodType { | Get => switch transactionEntity { | #Merchant => `refunds/v2/filter` | #Profile => `refunds/v2/profile/filter` | _ => `refunds/v2/filter` } | _ => "" } | ORDER_FILTERS => switch methodType { | Get => switch transactionEntity { | #Merchant => `payments/v2/filter` | #Profile => `payments/v2/profile/filter` | _ => `payments/v2/filter` } | _ => "" } | DISPUTE_FILTERS => switch methodType { | Get => switch transactionEntity { | #Profile => `disputes/profile/filter` | #Merchant | _ => `disputes/filter` } | _ => "" } | PAYOUTS_FILTERS => switch methodType { | Post => switch transactionEntity { | #Merchant => `payouts/filter` | #Profile => `payouts/profile/filter` | _ => `payouts/filter` } | _ => "" } | ORDERS => switch methodType { | Get => switch id { | Some(key_id) => switch queryParamerters { | Some(queryParams) => `payments/${key_id}?${queryParams}` | None => `payments/${key_id}` } | None => switch transactionEntity { | #Merchant => `payments/list?limit=100` | #Profile => `payments/profile/list?limit=100` | _ => `payments/list?limit=100` } } | Post => switch transactionEntity { | #Merchant => `payments/list` | #Profile => `payments/profile/list` | _ => `payments/list` } | _ => "" } | ORDERS_AGGREGATE => switch methodType { | Get => switch queryParamerters { | Some(queryParams) => switch transactionEntity { | #Merchant => `payments/aggregate?${queryParams}` | #Profile => `payments/profile/aggregate?${queryParams}` | _ => `payments/aggregate?${queryParams}` } | None => `payments/aggregate` } | _ => `payments/aggregate` } | REFUNDS => switch methodType { | Get => switch id { | Some(key_id) => switch queryParamerters { | Some(queryParams) => `refunds/${key_id}?${queryParams}` | None => `refunds/${key_id}` } | None => switch queryParamerters { | Some(queryParams) => switch transactionEntity { | #Merchant => `refunds/list?${queryParams}` | #Profile => `refunds/profile/list?limit=100` | _ => `refunds/list?limit=100` } | None => `refunds/list?limit=100` } } | Post => switch id { | Some(_keyid) => switch transactionEntity { | #Merchant => `refunds/list` | #Profile => `refunds/profile/list` | _ => `refunds/list` } | None => `refunds` } | _ => "" } | REFUNDS_AGGREGATE => switch methodType { | Get => switch queryParamerters { | Some(queryParams) => switch transactionEntity { | #Profile => `refunds/profile/aggregate?${queryParams}` | #Merchant | _ => `refunds/aggregate?${queryParams}` } | None => `refunds/aggregate` } | _ => `refunds/aggregate` } | DISPUTES => switch methodType { | Get => switch id { | Some(dispute_id) => `disputes/${dispute_id}` | None => switch queryParamerters { | Some(queryParams) => switch transactionEntity { | #Profile => `disputes/profile/list?${queryParams}&limit=10000` | #Merchant | _ => `disputes/list?${queryParams}&limit=10000` } | None => switch transactionEntity { | #Profile => `disputes/profile/list?limit=10000` | #Merchant | _ => `disputes/list?limit=10000` } } } | _ => "" } | DISPUTES_AGGREGATE => switch methodType { | Get => switch queryParamerters { | Some(queryParams) => switch transactionEntity { | #Profile => `disputes/profile/aggregate?${queryParams}` | #Merchant | _ => `disputes/aggregate?${queryParams}` } | None => `disputes/aggregate` } | _ => `disputes/aggregate` } | PAYOUTS => switch methodType { | Get => switch id { | Some(payout_id) => `payouts/${payout_id}` | None => switch transactionEntity { | #Merchant => `payouts/list?limit=100` | #Profile => `payouts/profile/list?limit=10000` | _ => `payouts/list?limit=100` } } | Post => switch transactionEntity { | #Merchant => `payouts/list` | #Profile => `payouts/profile/list` | _ => `payouts/list` } | _ => "" } /* ROUTING */ | DEFAULT_FALLBACK => `routing/default` | ROUTING => switch methodType { | Get => switch id { | Some(routingId) => `routing/${routingId}` | None => switch userEntity { | #Tenant | #Organization | #Merchant | #Profile => `routing/list/profile` } } | Post => switch id { | Some(routing_id) => `routing/${routing_id}/activate` | _ => `routing` } | _ => "" } | ACTIVE_ROUTING => `routing/active` /* ANALYTICS V2 */ | ANALYTICS_PAYMENTS_V2 => switch methodType { | Post => switch id { | Some(domain) => switch analyticsEntity { | #Tenant | #Organization => `analytics/v2/org/metrics/${domain}` | #Merchant => `analytics/v2/merchant/metrics/${domain}` | #Profile => `analytics/v2/profile/metrics/${domain}` } | _ => "" } | _ => "" } /* ANALYTICS */ | ANALYTICS_REFUNDS | ANALYTICS_PAYMENTS | ANALYTICS_DISPUTES | ANALYTICS_AUTHENTICATION => switch methodType { | Get => switch id { // Need to write seperate enum for info api | Some(domain) => switch analyticsEntity { | #Tenant | #Organization => `analytics/v1/org/${domain}/info` | #Merchant => `analytics/v1/merchant/${domain}/info` | #Profile => `analytics/v1/profile/${domain}/info` } | _ => "" } | Post => switch id { | Some(domain) => switch analyticsEntity { | #Tenant | #Organization => `analytics/v1/org/metrics/${domain}` | #Merchant => `analytics/v1/merchant/metrics/${domain}` | #Profile => `analytics/v1/profile/metrics/${domain}` } | _ => "" } | _ => "" } | ANALYTICS_AUTHENTICATION_V2 => switch methodType { | Get => switch analyticsEntity { | #Tenant | #Organization | #Merchant | #Profile => `analytics/v1/auth_events/info` } | Post => switch analyticsEntity { | #Tenant | #Organization | #Merchant | #Profile => `analytics/v1/metrics/auth_events` } | _ => "" } | ANALYTICS_AUTHENTICATION_V2_FILTERS => switch methodType { | Post => switch analyticsEntity { | #Tenant | #Organization | #Merchant | #Profile => `analytics/v1/filters/auth_events` } | _ => "" } | ANALYTICS_FILTERS => switch methodType { | Post => switch id { | Some(domain) => switch analyticsEntity { | #Tenant | #Organization => `analytics/v1/org/filters/${domain}` | #Merchant => `analytics/v1/merchant/filters/${domain}` | #Profile => `analytics/v1/profile/filters/${domain}` } | _ => "" } | _ => "" } | API_EVENT_LOGS => switch methodType { | Get => switch queryParamerters { | Some(params) => `analytics/v1/profile/api_event_logs?${params}` | None => `` } | _ => "" } | ANALYTICS_SANKEY => switch methodType { | Post => switch analyticsEntity { | #Tenant | #Organization => `analytics/v1/org/metrics/sankey` | #Merchant => `analytics/v1/merchant/metrics/sankey` | #Profile => `analytics/v1/profile/metrics/sankey` } | _ => "" } /* PAYOUTS ROUTING */ | PAYOUT_DEFAULT_FALLBACK => `routing/payouts/default` | PAYOUT_ROUTING => switch methodType { | Get => switch id { | Some(routingId) => `routing/${routingId}` | _ => switch userEntity { | #Tenant | #Organization | #Merchant | #Profile => `routing/payouts/list/profile` } } | Put => switch id { | Some(routingId) => `routing/${routingId}` | _ => `routing/payouts` } | Post => switch id { | Some(routing_id) => `routing/payouts/${routing_id}/activate` | _ => `routing/payouts` } | _ => "" } | ACTIVE_PAYOUT_ROUTING => `routing/payouts/active` /* THREE DS ROUTING */ | THREE_DS => `routing/decision` /* SURCHARGE ROUTING */ | SURCHARGE => `routing/decision/surcharge` /* RECONCILIATION */ | RECON => `recon/${(reconType :> string)->String.toLowerCase}` | HYPERSENSE => `hypersense/${(hypersenseType :> string)->String.toLowerCase}` /* REPORTS */ | PAYMENT_REPORT => switch transactionEntity { | #Tenant | #Organization => `analytics/v1/org/report/payments` | #Merchant => `analytics/v1/merchant/report/payments` | #Profile => `analytics/v1/profile/report/payments` } | REFUND_REPORT => switch transactionEntity { | #Tenant | #Organization => `analytics/v1/org/report/refunds` | #Merchant => `analytics/v1/merchant/report/refunds` | #Profile => `analytics/v1/profile/report/refunds` } | DISPUTE_REPORT => switch transactionEntity { | #Tenant | #Organization => `analytics/v1/org/report/dispute` | #Merchant => `analytics/v1/merchant/report/dispute` | #Profile => `analytics/v1/profile/report/dispute` } | AUTHENTICATION_REPORT => switch transactionEntity { | #Tenant | #Organization => `analytics/v1/org/report/authentications` | #Merchant => `analytics/v1/merchant/report/authentications` | #Profile => `analytics/v1/profile/report/authentications` } /* EVENT LOGS */ | SDK_EVENT_LOGS => `analytics/v1/profile/sdk_event_logs` | WEBHOOK_EVENTS => `events/profile/list` | WEBHOOK_EVENTS_ATTEMPTS => switch id { | Some(id) => `events/${merchantId}/${id}/attempts` | None => `events/${merchantId}/attempts` } | WEBHOOKS_EVENTS_RETRY => switch id { | Some(id) => `events/${merchantId}/${id}/retry` | None => `events/${merchantId}/retry` } | WEBHOOKS_EVENT_LOGS => switch methodType { | Get => switch queryParamerters { | Some(params) => `analytics/v1/profile/outgoing_webhook_event_logs?${params}` | None => `analytics/v1/outgoing_webhook_event_logs` } | _ => "" } | CONNECTOR_EVENT_LOGS => switch methodType { | Get => switch queryParamerters { | Some(params) => `analytics/v1/profile/connector_event_logs?${params}` | None => `analytics/v1/connector_event_logs` } | _ => "" } /* SAMPLE DATA */ | GENERATE_SAMPLE_DATA => `user/sample_data` /* VERIFY APPLE PAY */ | VERIFY_APPLE_PAY => switch id { | Some(merchant_id) => `verify/apple_pay/${merchant_id}` | None => `verify/apple_pay` } /* PAYPAL ONBOARDING */ | PAYPAL_ONBOARDING => `connector_onboarding` | PAYPAL_ONBOARDING_SYNC => `connector_onboarding/sync` | ACTION_URL => `connector_onboarding/action_url` | RESET_TRACKING_ID => `connector_onboarding/reset_tracking_id` /* BUSINESS PROFILE */ | BUSINESS_PROFILE => switch methodType { | Get => switch userEntity { | #Tenant | #Organization | #Merchant | #Profile => `account/${merchantId}/profile` } | Post => switch id { | Some(id) => `account/${merchantId}/business_profile/${id}` | None => `account/${merchantId}/business_profile` } | _ => `account/${merchantId}/business_profile` } /* API KEYS */ | API_KEYS => switch methodType { | Get => `api_keys/${merchantId}/list` | Post => switch id { | Some(key_id) => `api_keys/${merchantId}/${key_id}` | None => `api_keys/${merchantId}` } | Delete => `api_keys/${merchantId}/${id->Option.getOr("")}` | _ => "" } /* DISPUTES EVIDENCE */ | ACCEPT_DISPUTE => switch id { | Some(id) => `disputes/accept/${id}` | None => `disputes` } | DISPUTES_ATTACH_EVIDENCE => switch id { | Some(id) => `disputes/evidence/${id}` | _ => `disputes/evidence` } /* PMTS COUNTRY-CURRENCY DETAILS */ | PAYMENT_METHOD_CONFIG => `payment_methods/filter` /* USER MANGEMENT REVAMP */ | USER_MANAGEMENT => { let userUrl = `user` switch userRoleTypes { | USER_LIST => switch queryParamerters { | Some(queryParams) => `${userUrl}/user/list?${queryParams}` | None => `${userUrl}/user/list` } | ROLE_LIST => switch queryParamerters { | Some(queryParams) => `${userUrl}/role/list?${queryParams}` | None => `${userUrl}/role/list` } | ROLE_ID => switch id { | Some(key_id) => `${userUrl}/role/${key_id}/v2` | None => "" } | _ => "" } } /* INTELLIGENT ROUTING */ | SIMULATE_INTELLIGENT_ROUTING => switch queryParamerters { | Some(queryParams) => `simulate/${merchantId}?${queryParams}` | None => `simulate/${merchantId}` } | INTELLIGENT_ROUTING_RECORDS => switch queryParamerters { | Some(queryParams) => `simulate/${merchantId}/get-records?${queryParams}` | None => `simulate/${merchantId}/get-records` } | INTELLIGENT_ROUTING_GET_STATISTICS => `simulate/${merchantId}/get-statistics` /* USERS */ | USERS => let userUrl = `user` switch userType { // DASHBOARD LOGIN / SIGNUP | #CONNECT_ACCOUNT => switch queryParamerters { | Some(params) => `${userUrl}/connect_account?${params}` | None => `${userUrl}/connect_account` } | #SIGNINV2 => `${userUrl}/v2/signin` | #CHANGE_PASSWORD => `${userUrl}/change_password` | #SIGNUP | #SIGNOUT | #RESET_PASSWORD | #VERIFY_EMAIL_REQUEST | #FORGOT_PASSWORD | #ROTATE_PASSWORD => switch queryParamerters { | Some(params) => `${userUrl}/${(userType :> string)->String.toLowerCase}?${params}` | None => `${userUrl}/${(userType :> string)->String.toLowerCase}` } // POST LOGIN QUESTIONARE | #SET_METADATA => switch queryParamerters { | Some(params) => `${userUrl}/${(userType :> string)->String.toLowerCase}?${params}` | None => `${userUrl}/${(userType :> string)->String.toLowerCase}` } // USER DATA | #USER_DATA => switch queryParamerters { | Some(params) => `${userUrl}/data?${params}` | None => `${userUrl}/data` } | #MERCHANT_DATA => `${userUrl}/data` | #USER_INFO => userUrl // USER GROUP ACCESS | #GET_GROUP_ACL => `${userUrl}/role/v2` | #ROLE_INFO => `${userUrl}/parent/list` | #GROUP_ACCESS_INFO => switch queryParamerters { | Some(params) => `${userUrl}/permission_info?${params}` | None => `${userUrl}/permission_info` } // USER ACTIONS | #USER_DELETE => `${userUrl}/user/delete` | #USER_UPDATE => `${userUrl}/update` | #UPDATE_ROLE => `${userUrl}/user/${(userType :> string)->String.toLowerCase}` // INVITATION INSIDE DASHBOARD | #RESEND_INVITE => `${userUrl}/user/resend_invite` | #ACCEPT_INVITATION_HOME => `${userUrl}/user/invite/accept` | #INVITE_MULTIPLE => switch queryParamerters { | Some(params) => `${userUrl}/user/${(userType :> string)->String.toLowerCase}?${params}` | None => `${userUrl}/user/${(userType :> string)->String.toLowerCase}` } // ACCEPT INVITE PRE_LOGIN | #ACCEPT_INVITATION_PRE_LOGIN => `${userUrl}/user/invite/accept/pre_auth` // CREATE_ORG | #CREATE_ORG => `user/create_org` // CREATE MERCHANT | #CREATE_MERCHANT => switch queryParamerters { | Some(params) => `${userUrl}/${(userType :> string)->String.toLowerCase}?${params}` | None => `${userUrl}/${(userType :> string)->String.toLowerCase}` } | #SWITCH_ORG => `${userUrl}/switch/org` | #SWITCH_MERCHANT_NEW => `${userUrl}/switch/merchant` | #SWITCH_PROFILE => `${userUrl}/switch/profile` // Org-Merchant-Profile List | #LIST_ORG => `${userUrl}/list/org` | #LIST_MERCHANT => `${userUrl}/list/merchant` | #LIST_PROFILE => `${userUrl}/list/profile` // CREATE ROLES | #CREATE_CUSTOM_ROLE => `${userUrl}/role` // EMAIL FLOWS | #FROM_EMAIL => `${userUrl}/from_email` | #VERIFY_EMAILV2 => `${userUrl}/v2/verify_email` | #ACCEPT_INVITE_FROM_EMAIL => switch queryParamerters { | Some(params) => `${userUrl}/${(userType :> string)->String.toLowerCase}?${params}` | None => `${userUrl}/${(userType :> string)->String.toLowerCase}` } // SPT FLOWS (Totp) | #BEGIN_TOTP => `${userUrl}/2fa/totp/begin` | #CHECK_TWO_FACTOR_AUTH_STATUS_V2 => `${userUrl}/2fa/v2` | #VERIFY_TOTP => `${userUrl}/2fa/totp/verify` | #VERIFY_RECOVERY_CODE => `${userUrl}/2fa/recovery_code/verify` | #GENERATE_RECOVERY_CODES => `${userUrl}/2fa/recovery_code/generate` | #TERMINATE_TWO_FACTOR_AUTH => switch queryParamerters { | Some(params) => `${userUrl}/2fa/terminate?${params}` | None => `${userUrl}/2fa/terminate` } | #CHECK_TWO_FACTOR_AUTH_STATUS => `${userUrl}/2fa` | #RESET_TOTP => `${userUrl}/2fa/totp/reset` // SPT FLOWS (SSO) | #GET_AUTH_LIST => switch queryParamerters { | Some(params) => `${userUrl}/auth/list?${params}` | None => `${userUrl}/auth/list` } | #SIGN_IN_WITH_SSO => `${userUrl}/oidc` | #AUTH_SELECT => `${userUrl}/auth/select` // user-management revamp | #LIST_ROLES_FOR_INVITE => switch queryParamerters { | Some(params) => `${userUrl}/role/list/invite?${params}` | None => "" } | #LIST_INVITATION => `${userUrl}/list/invitation` | #USER_DETAILS => `${userUrl}/user` | #LIST_ROLES_FOR_ROLE_UPDATE => switch queryParamerters { | Some(params) => `${userUrl}/role/list/update?${params}` | None => "" } | #NONE => "" } /* TO BE CHECKED */ | INTEGRATION_DETAILS => `user/get_sandbox_integration_details` } | V2(entityNameForv2) => getV2Url( ~entityName=entityNameForv2, ~userType, ~id, ~methodType, ~queryParamerters, ~profileId, ~merchantId, ) } `${Window.env.apiBaseUrl}/${endpoint}` } getUrl } let useHandleLogout = (~eventName="user_sign_out") => { let getURL = useGetURL() let mixpanelEvent = MixpanelHook.useSendEvent() let {setAuthStateToLogout} = React.useContext(AuthInfoProvider.authStatusContext) let clearRecoilValue = ClearRecoilValueHook.useClearRecoilValue() let fetchApi = AuthHooks.useApiFetcher() let {xFeatureRoute, forceCookies} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom () => { try { let logoutUrl = getURL(~entityName=V1(USERS), ~methodType=Post, ~userType=#SIGNOUT) open Promise mixpanelEvent(~eventName) let _ = fetchApi(logoutUrl, ~method_=Post, ~xFeatureRoute, ~forceCookies) ->then(Fetch.Response.json) ->then(json => { json->resolve }) ->catch(_err => { JSON.Encode.null->resolve }) setAuthStateToLogout() clearRecoilValue() LocalStorage.clear() } catch { | _ => LocalStorage.clear() } } } let sessionExpired = ref(false) let responseHandler = async ( ~url, ~res, ~showToast: ToastState.showToastFn, ~showErrorToast: bool, ~showPopUp: PopUpState.popUpProps => unit, ~isPlayground, ~popUpCallBack, ~handleLogout, ~sendEvent: ( ~eventName: string, ~email: string=?, ~description: option<'a>=?, ~section: string=?, ~metadata: JSON.t=?, ) => unit, ) => { let json = try { await res->(res => res->Fetch.Response.json) } catch { | _ => JSON.Encode.null } let responseStatus = res->Fetch.Response.status let responseHeaders = res->Fetch.Response.headers if responseStatus >= 500 && responseStatus < 600 { let xRequestId = responseHeaders->Fetch.Headers.get("x-request-id")->Option.getOr("") let metaData = [ ("url", url->JSON.Encode.string), ("response", json), ("status", responseStatus->JSON.Encode.int), ("x-request-id", xRequestId->JSON.Encode.string), ]->getJsonFromArrayOfJson sendEvent(~eventName="API Error", ~description=Some(responseStatus), ~metadata=metaData) } let noAccessControlText = "You do not have the required permissions to access this module. Please contact your admin." switch responseStatus { | 200 => json | _ => { let errorDict = json->getDictFromJsonObject->getObj("error", Dict.make()) let errorStringifiedJson = errorDict->JSON.Encode.object->JSON.stringify if isPlayground && responseStatus === 403 { popUpCallBack() } else if showErrorToast { switch responseStatus { | 400 => { let errorCode = errorDict->getString("code", "") switch errorCode->CommonAuthUtils.errorSubCodeMapper { | HE_02 | UR_33 => RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url="/home")) | _ => () } } | 401 => if !sessionExpired.contents { showToast(~toastType=ToastWarning, ~message="Session Expired", ~autoClose=false) handleLogout()->ignore AuthUtils.redirectToLogin() sessionExpired := true } | 403 => showPopUp({ popUpType: (Warning, WithIcon), heading: "Access Forbidden", description: { noAccessControlText->React.string }, handleConfirm: { text: "Close", onClick: { _ => () }, }, }) | 404 => { let errorCode = errorDict->getString("code", "") switch errorCode->CommonAuthUtils.errorSubCodeMapper { | HE_02 => RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url="/home")) | _ => () } } | _ => showToast( ~toastType=ToastError, ~message=errorDict->getString("message", "Error Occured"), ~autoClose=false, ) } } Exn.raiseError(errorStringifiedJson) } } } let catchHandler = ( ~err, ~showErrorToast, ~showToast: ToastState.showToastFn, ~isPlayground, ~popUpCallBack, ) => { switch Exn.message(err) { | Some(msg) => Exn.raiseError(msg) | None => { if isPlayground { popUpCallBack() } else if showErrorToast { showToast(~toastType=ToastError, ~message="Something Went Wrong", ~autoClose=false) } Exn.raiseError("Failed to Fetch") } } } let useGetMethod = (~showErrorToast=true) => { let {userInfo: {merchantId, profileId}} = React.useContext(UserInfoProvider.defaultContext) let fetchApi = AuthHooks.useApiFetcher() let showToast = ToastState.useShowToast() let showPopUp = PopUpState.useShowPopUp() let handleLogout = useHandleLogout() let sendEvent = MixpanelHook.useSendEvent() let isPlayground = HSLocalStorage.getIsPlaygroundFromLocalStorage() let popUpCallBack = () => showPopUp({ popUpType: (Warning, WithIcon), heading: "Sign Up to Access All Features!", description: { "To unlock the potential and experience the full range of capabilities, simply sign up today. Join our community of explorers and gain access to an enhanced world of possibilities"->React.string }, handleConfirm: { text: "Sign up Now", onClick: { _ => handleLogout()->ignore }, }, }) let {xFeatureRoute, forceCookies} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom async (url, ~version=UserInfoTypes.V1) => { try { let res = await fetchApi( url, ~method_=Get, ~xFeatureRoute, ~forceCookies, ~merchantId, ~profileId, ~version, ) await responseHandler( ~url, ~res, ~showErrorToast, ~showToast, ~showPopUp, ~isPlayground, ~popUpCallBack, ~handleLogout, ~sendEvent, ) } catch { | Exn.Error(e) => catchHandler(~err={e}, ~showErrorToast, ~showToast, ~isPlayground, ~popUpCallBack) | _ => Exn.raiseError("Something went wrong") } } } let useUpdateMethod = (~showErrorToast=true) => { let {userInfo: {merchantId, profileId}} = React.useContext(UserInfoProvider.defaultContext) let fetchApi = AuthHooks.useApiFetcher() let showToast = ToastState.useShowToast() let showPopUp = PopUpState.useShowPopUp() let handleLogout = useHandleLogout() let sendEvent = MixpanelHook.useSendEvent() let isPlayground = HSLocalStorage.getIsPlaygroundFromLocalStorage() let popUpCallBack = () => showPopUp({ popUpType: (Warning, WithIcon), heading: "Sign Up to Access All Features!", description: { "To unlock the potential and experience the full range of capabilities, simply sign up today. Join our community of explorers and gain access to an enhanced world of possibilities"->React.string }, handleConfirm: { text: "Sign up Now", onClick: { _ => handleLogout()->ignore }, }, }) let {xFeatureRoute, forceCookies} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom async ( url, body, method, ~bodyFormData=?, ~headers=Dict.make(), ~contentType=AuthHooks.Headers("application/json"), ~version=UserInfoTypes.V1, ) => { try { let res = await fetchApi( url, ~method_=method, ~bodyStr=body->JSON.stringify, ~bodyFormData, ~headers, ~contentType, ~xFeatureRoute, ~forceCookies, ~merchantId, ~profileId, ~version, ) await responseHandler( ~url, ~res, ~showErrorToast, ~showToast, ~isPlayground, ~showPopUp, ~popUpCallBack, ~handleLogout, ~sendEvent, ) } catch { | Exn.Error(e) => catchHandler(~err={e}, ~showErrorToast, ~showToast, ~isPlayground, ~popUpCallBack) | _ => Exn.raiseError("Something went wrong") } } }
8,405
10,150
hyperswitch-control-center
src/context/FilterContext.res
.res
type filterUpdater = { query: string, filterValue: Dict.t<string>, updateExistingKeys: Dict.t<string> => unit, removeKeys: array<string> => unit, filterKeys: array<string>, setfilterKeys: (array<string> => array<string>) => unit, filterValueJson: Dict.t<JSON.t>, reset: unit => unit, } let filterUpdater = { query: "", filterValue: Dict.make(), updateExistingKeys: _dict => (), removeKeys: _arr => (), filterValueJson: Dict.make(), filterKeys: [], setfilterKeys: _ => (), reset: () => (), } let filterContext = React.createContext(filterUpdater) module Provider = { let make = React.Context.provider(filterContext) } @react.component let make = (~index: string, ~children) => { open FilterUtils open LogicUtils open SessionStorage let query = React.useMemo(() => {ref("")}, []) let (filterKeys, setfilterKeys) = React.useState(_ => []) let searcParamsToDict = query.contents->parseFilterString let (filterDict, setfilterDict) = React.useState(_ => searcParamsToDict) let clearSessionStorage = () => { sessionStorage.removeItem(index) sessionStorage.removeItem(`${index}-list`) setfilterKeys(_ => []) } let updateFilter = React.useMemo(() => { let updateFilter = (dict: Dict.t<string>) => { setfilterDict(prev => { let prevDictArr = prev ->Dict.toArray ->Belt.Array.keepMap( item => { let (key, value) = item switch dict->Dict.get(key) { | Some(_) => None | None => !(value->isEmptyString) ? Some(item) : None } }, ) let currentDictArr = dict ->Dict.toArray ->Array.filter( item => { let (_, value) = item !(value->isEmptyString) }, ) let updatedDict = Array.concat(prevDictArr, currentDictArr)->Dict.fromArray let dict = if DictionaryUtils.equalDicts(updatedDict, prev) { prev } else { updatedDict } query := dict->FilterUtils.parseFilterDict dict }) } let reset = () => { let dict = Dict.make() setfilterDict(_ => dict) query := dict->FilterUtils.parseFilterDict clearSessionStorage() } let removeKeys = (arr: array<string>) => { setfilterDict(prev => { let updatedDict = prev->Dict.toArray->Array.copy->Dict.fromArray->DictionaryUtils.deleteKeys(arr) let updatedDict = if arr == ["amount"] { updatedDict->DictionaryUtils.deleteKeys(["start_amount", "end_amount", "amount_option"]) } else { updatedDict } let dict = if DictionaryUtils.equalDicts(updatedDict, prev) { prev } else { updatedDict } query := dict->FilterUtils.parseFilterDict dict }) clearSessionStorage() } { query: query.contents, filterValue: filterDict, updateExistingKeys: updateFilter, removeKeys, filterKeys, setfilterKeys, filterValueJson: filterDict ->Dict.toArray ->Array.map(item => { let (key, value) = item (key, value->UrlFetchUtils.getFilterValue) }) ->Dict.fromArray, reset, } }, (filterDict, setfilterDict, filterKeys)) React.useEffect(() => { switch sessionStorage.getItem(index)->Nullable.toOption { | Some(value) => value->FilterUtils.parseFilterString->updateFilter.updateExistingKeys | None => () } let keys = [] switch sessionStorage.getItem(`${index}-list`)->Nullable.toOption { | Some(value) => switch value->JSON.parseExn->JSON.Decode.array { | Some(arr) => arr->Array.forEach(item => { switch item->JSON.Decode.string { | Some(str) => keys->Array.push(str)->ignore | _ => () } }) setfilterKeys(_ => keys) | None => () } | None => () } Some(() => clearSessionStorage()) }, []) React.useEffect(() => { if !(query.contents->String.length < 1) { sessionStorage.setItem(index, query.contents) } sessionStorage.setItem( `${index}-list`, filterKeys->Array.map(item => item->JSON.Encode.string)->JSON.Encode.array->JSON.stringify, ) None }, (query.contents, filterKeys)) <Provider value={updateFilter}> children </Provider> }
1,043
10,151
hyperswitch-control-center
src/context/UserPrefContext.res
.res
// will be used in future // docfor the user preference https://docs.google.com/document/d/1BM_UgHLuN0U-cXfRYqN6wWSq-5KUiqojinCfBrUEiVo/edit open UserPrefUtils external userPrefToJson: userPref => JSON.t = "%identity" external dictUserPrefToStr: Dict.t<userPref> => string = "%identity" let userPrefSetter: (Dict.t<userPref> => Dict.t<userPref>) => unit = _ => () let defaultUserPref: Dict.t<userPref> = Dict.make() let defaultUserModuleWisePref: moduleVisePref = {} type filter = { userPref: Dict.t<userPref>, setUserPref: (Dict.t<userPref> => Dict.t<userPref>) => unit, lastVisitedTab: string, getSearchParamByLink: string => string, addConfig: (string, JSON.t) => unit, getConfig: string => option<JSON.t>, } let userPrefObj: filter = { userPref: defaultUserPref, setUserPref: userPrefSetter, lastVisitedTab: "", getSearchParamByLink: _str => "", addConfig: (_str, _json) => (), getConfig: _str => None, } let userPrefContext = React.createContext(userPrefObj) module Provider = { let make = React.Context.provider(userPrefContext) } @react.component let make = (~children) => { // this fetch will only happen once after that context will be updated each time when url chnaged and it keep hitting the update api let userPrefInitialVal: Dict.t<userPref> = UserPrefUtils.getUserPref() let {authStatus} = React.useContext(AuthInfoProvider.authStatusContext) let username = switch authStatus { | LoggedIn(authType) => switch authType { | Auth(_) => "" } | _ => "" } let (userPref, setUserPref) = React.useState(_ => userPrefInitialVal) let url = RescriptReactRouter.useUrl() let urlPathConcationation = `/${url.path ->LogicUtils.stripV4 ->List.toArray ->Array.joinWith("/")}` // UPDATE THE LAST VISITED TAB React.useEffect(() => { if urlPathConcationation !== "/" { setUserPref(prev => { let currentConfig = prev->Dict.get(username)->Option.getOr({}) let updatedPrev = currentConfig let updatedValue = if ( urlPathConcationation !== updatedPrev.lastVisitedTab->Option.getOr("") ) { {...updatedPrev, lastVisitedTab: urlPathConcationation} } else { updatedPrev } prev->Dict.set(username, updatedValue) UserPrefUtils.saveUserPref(prev) prev }) } None }, (urlPathConcationation, username)) // UPDATE THE searchParams IN LAST VISITED TAB React.useEffect(() => { setUserPref(prev => { let currentConfig = prev->Dict.get(username)->Option.getOr({}) let updatedPrev = currentConfig let moduleWisePref = switch updatedPrev { | {moduleVisePref} => moduleVisePref | _ => Dict.make() } let currentModulePerf = moduleWisePref->Dict.get(urlPathConcationation)->Option.getOr(defaultUserModuleWisePref) let filteredUrlSearch = url.search ->LogicUtils.getDictFromUrlSearchParams ->DictionaryUtils.deleteKeys([ // all absolute datetime keys to be added here, to ensure absolute dateranges are not persisted "startTime", "endTime", "filters.dateCreated.lte", "filters.dateCreated.gte", "filters.dateCreated.opt", // to be fixed and removed from here ]) ->Dict.toArray ->Array.map( item => { let (key, value) = item `${key}=${value}` }, ) ->Array.joinWith("&") let isMarketplaceApp = urlPathConcationation == "/marketplace" moduleWisePref->Dict.set( urlPathConcationation, { ...currentModulePerf, searchParams: isMarketplaceApp ? "" : filteredUrlSearch, }, ) let updatedCurrentConfig = { ...updatedPrev, moduleVisePref: moduleWisePref, } prev->Dict.set(username, updatedCurrentConfig) UserPrefUtils.saveUserPref(prev) prev }) None }, (url.search, username)) // UPDATE THE CURRENT PREF TO THE DATA SOURCE React.useEffect(() => { UserPrefUtils.saveUserPref(userPref) None }, [userPref]) let addConfig = (key, value) => { setUserPref(prev => { let currentConfig = prev->Dict.get(username)->Option.getOr({}) let updatedPrev = currentConfig let moduleWisePref = switch updatedPrev { | {moduleVisePref} => moduleVisePref | _ => Dict.make() } let currentModulePerf = moduleWisePref->Dict.get(urlPathConcationation)->Option.getOr(defaultUserModuleWisePref) let moduleConfig = switch currentModulePerf { | {moduleConfig} => moduleConfig | _ => Dict.make() } moduleConfig->Dict.set(key, value) moduleWisePref->Dict.set(urlPathConcationation, {...currentModulePerf, moduleConfig}) let updatedCurrentConfig = { ...updatedPrev, moduleVisePref: moduleWisePref, } prev->Dict.set(username, updatedCurrentConfig) UserPrefUtils.saveUserPref(prev) prev }) } let getConfig = key => { let currentConfig = userPref->Dict.get(username)->Option.getOr({}) let updatedPrev = currentConfig switch updatedPrev { | {moduleVisePref} => switch moduleVisePref ->Dict.get(urlPathConcationation) ->Option.getOr(defaultUserModuleWisePref) { | {moduleConfig} => moduleConfig->Dict.get(key) | _ => None } | _ => None } } // not adding to useMemo as it doesn't triggers sometimes let userPrefString = userPref ->Dict.toArray ->Array.map(item => { let (key, value) = item (key, value->userPrefToJson) }) ->LogicUtils.getJsonFromArrayOfJson ->JSON.stringify let value = React.useMemo(() => { let currentConfig = userPref->Dict.get(username)->Option.getOr({}) let updatedPrev = currentConfig let lastVisitedTab = switch updatedPrev { | {lastVisitedTab} => lastVisitedTab | _ => "" } let moduleVisePref = switch updatedPrev { | {moduleVisePref} => moduleVisePref | _ => Dict.make() } let getSearchParamByLink = link => { let searchParam = UserPrefUtils.getSearchParams(moduleVisePref, ~key=link) // this is for removing the v4 from the link searchParam->LogicUtils.isNonEmptyString ? `?${searchParam}` : "" } { userPref, setUserPref, lastVisitedTab, getSearchParamByLink, addConfig, getConfig, } }, (userPrefString, setUserPref, addConfig, getConfig)) <Provider value={value}> children </Provider> }
1,660
10,152
hyperswitch-control-center
src/context/ButtonGroupContext.res
.res
type buttonInfo = { isFirst: bool, isLast: bool, } let defaultButtonInfo = { isFirst: true, isLast: true, } let buttonGroupContext = React.createContext(defaultButtonInfo) module Parent = { let make = React.Context.provider(buttonGroupContext) }
63
10,153
hyperswitch-control-center
src/context/TableFilterSectionContext.res
.res
let filterSectionContext = React.createContext(false) module Provider = { let make = React.Context.provider(filterSectionContext) } @react.component let make = (~children, ~isFilterSection) => { <Provider value=isFilterSection> children </Provider> }
56
10,154
hyperswitch-control-center
src/context/RefreshStateContext.res
.res
let defaultSetter = (_: int => int) => () let refreshStateContext = React.createContext((0, defaultSetter)) let make = React.Context.provider(refreshStateContext)
37
10,155
hyperswitch-control-center
src/context/DropdownTextWeighContextWrapper.res
.res
let selectedTextWeightContext = React.createContext(false) module Provider = { let make = React.Context.provider(selectedTextWeightContext) } @react.component let make = (~children, ~isDropdownSelectedTextDark) => { <Provider value=isDropdownSelectedTextDark> <div> children </div> </Provider> }
70
10,156
hyperswitch-control-center
src/context/ThemeUtils.res
.res
let useThemeFromEvent = () => { let (eventTheme, setEventTheme) = React.useState(_ => None) React.useEffect(() => { let setEventThemeVal = (eventName, dict) => { if eventName === "AuthenticationDetails" { let payloadDict = dict->Dict.get("payload")->Option.flatMap(obj => obj->JSON.Decode.object) let theme = payloadDict->Option.mapOr("", finalDict => LogicUtils.getString(finalDict, "theme", "")) setEventTheme(_ => Some(theme)) } else if eventName == "themeToggle" { let theme = LogicUtils.getString(dict, "payload", "") setEventTheme(_ => Some(theme)) } else { Js.log2(`Event name is ${eventName}`, dict) } } let handleEventMessage = (ev: Dom.event) => { let optionalDict = HandlingEvents.getEventDict(ev) switch optionalDict { | Some(dict) => { let optionalEventName = dict->Dict.get("eventType")->Option.flatMap(obj => obj->JSON.Decode.string) switch optionalEventName { | Some(eventName) => setEventThemeVal(eventName, dict) | None => Js.log2("Event Data is not found", dict) } } | None => () } } Window.addEventListener("message", handleEventMessage) Some(() => Window.removeEventListener("message", handleEventMessage)) }, []) eventTheme }
308
10,157
hyperswitch-control-center
src/context/ThemeProvider.res
.res
type theme = Light | Dark let defaultSetter = _ => () type themeType = LightTheme type x = {theme: string} type customUIConfig = { globalUIConfig: UIConfig.t, theme: theme, themeSetter: theme => unit, configCustomDomainTheme: JSON.t => unit, getThemesJson: (string, JSON.t, bool) => promise<JSON.t>, } let newDefaultConfig: HyperSwitchConfigTypes.customStylesTheme = { settings: { colors: { primary: "#006DF9", secondary: "#303E5F", background: "#006df9", }, sidebar: { primary: "#FCFCFD", secondary: "#FFFFFF", hoverColor: "#D9DDE5", primaryTextColor: "#1C6DEA", secondaryTextColor: "#525866", borderColor: "#ECEFF3", }, typography: { fontFamily: "Roboto, sans-serif", fontSize: "14px", headingFontSize: "24px", textColor: "#006DF9", linkColor: "#3498db", linkHoverColor: "#005ED6", }, buttons: { primary: { backgroundColor: "#1272f9", textColor: "#ffffff", hoverBackgroundColor: "#0860dd", }, secondary: { backgroundColor: "#f3f3f3", textColor: "#626168", hoverBackgroundColor: "#fcfcfd", }, }, borders: { defaultRadius: "4px", borderColor: "#1272F9", }, spacing: { padding: "16px", margin: "16px", }, }, urls: { faviconUrl: None, logoUrl: None, }, } let themeContext = { globalUIConfig: UIConfig.defaultUIConfig, theme: Light, themeSetter: defaultSetter, configCustomDomainTheme: _ => (), getThemesJson: (_, _, _) => JSON.Encode.null->Promise.resolve, } let themeContext = React.createContext(themeContext) module Parent = { let make = React.Context.provider(themeContext) } let useTheme = () => { let {theme} = React.useContext(themeContext) theme } @react.component let make = (~children) => { let eventTheme = ThemeUtils.useThemeFromEvent() let fetchApi = AuthHooks.useApiFetcher() let isCurrentlyDark = MatchMedia.useMatchMedia("(prefers-color-scheme: dark)") let initialTheme = Light let (themeState, setThemeBase) = React.useState(() => initialTheme) let theme = switch eventTheme { | Some("Dark") => Dark | Some(_val) => Light | None => if window !== Window.parent { Light } else { themeState } } let setTheme = React.useCallback(value => { setThemeBase(_ => value) }, [setThemeBase]) React.useEffect(() => { setTheme(initialTheme) None }, [isCurrentlyDark]) let themeClassName = switch theme { | Dark => "dark" | Light => "" } let configCustomDomainTheme = React.useCallback((uiConfg: JSON.t) => { open LogicUtils let dict = uiConfg->getDictFromJsonObject let settings = dict->getDictfromDict("settings") let url = dict->getDictfromDict("urls") let colorsConfig = settings->getDictfromDict("colors") let sidebarConfig = settings->getDictfromDict("sidebar") let typography = settings->getDictfromDict("typography") let borders = settings->getDictfromDict("borders") let spacing = settings->getDictfromDict("spacing") let colorsBtnPrimary = settings->getDictfromDict("buttons")->getDictfromDict("primary") let colorsBtnSecondary = settings->getDictfromDict("buttons")->getDictfromDict("secondary") let {settings: defaultSettings, _} = newDefaultConfig let value: HyperSwitchConfigTypes.customStylesTheme = { settings: { colors: { primary: colorsConfig->getString("primary", defaultSettings.colors.primary), secondary: colorsConfig->getString("secondary", defaultSettings.colors.secondary), background: colorsConfig->getString("background", defaultSettings.colors.background), }, sidebar: { // This 'colorsConfig' will be replaced with 'sidebarConfig', and the 'sidebar' key will be changed to 'primary' after API Changes. primary: colorsConfig->getString("sidebar", defaultSettings.sidebar.primary), // This 'colorsConfig' will be replaced with 'sidebarConfig' once the API changes are done. secondary: sidebarConfig->getString("secondary", defaultSettings.sidebar.secondary), hoverColor: sidebarConfig->getString("hoverColor", defaultSettings.sidebar.hoverColor), // This property is currently required to support current sidebar changes. It will be removed in a future update. primaryTextColor: sidebarConfig->getString( "primaryTextColor", defaultSettings.sidebar.primaryTextColor, ), secondaryTextColor: sidebarConfig->getString( "secondaryTextColor", defaultSettings.sidebar.secondaryTextColor, ), borderColor: sidebarConfig->getString("borderColor", defaultSettings.sidebar.borderColor), }, typography: { fontFamily: typography->getString("fontFamily", defaultSettings.typography.fontFamily), fontSize: typography->getString("fontSize", defaultSettings.typography.fontSize), headingFontSize: typography->getString( "headingFontSize", defaultSettings.typography.headingFontSize, ), textColor: typography->getString("textColor", defaultSettings.typography.textColor), linkColor: typography->getString("linkColor", defaultSettings.typography.linkColor), linkHoverColor: typography->getString( "linkHoverColor", defaultSettings.typography.linkHoverColor, ), }, buttons: { primary: { backgroundColor: colorsBtnPrimary->getString( "backgroundColor", defaultSettings.buttons.primary.backgroundColor, ), textColor: colorsBtnPrimary->getString( "textColor", defaultSettings.buttons.primary.textColor, ), hoverBackgroundColor: colorsBtnPrimary->getString( "hoverBackgroundColor", defaultSettings.buttons.primary.hoverBackgroundColor, ), }, secondary: { backgroundColor: colorsBtnSecondary->getString( "backgroundColor", defaultSettings.buttons.secondary.backgroundColor, ), textColor: colorsBtnSecondary->getString( "textColor", defaultSettings.buttons.secondary.textColor, ), hoverBackgroundColor: colorsBtnSecondary->getString( "hoverBackgroundColor", defaultSettings.buttons.secondary.hoverBackgroundColor, ), }, }, borders: { defaultRadius: borders->getString("defaultRadius", defaultSettings.borders.defaultRadius), borderColor: borders->getString("borderColor", defaultSettings.borders.borderColor), }, spacing: { padding: spacing->getString("padding", defaultSettings.spacing.padding), margin: spacing->getString("margin", defaultSettings.spacing.margin), }, }, urls: { faviconUrl: url->getOptionString("faviconUrl"), logoUrl: url->getOptionString("logoUrl"), }, } Window.appendStyle(value) }, []) let configureFavIcon = (faviconUrl: option<string>) => { try { open DOMUtils let a = createElement(DOMUtils.document, "link") let _ = setAttribute(a, "href", `${faviconUrl->Option.getOr("/HyperswitchFavicon.png")}`) let _ = setAttribute(a, "rel", "shortcut icon") let _ = setAttribute(a, "type", "image/x-icon") let _ = appendHead(a) } catch { | _ => Exn.raiseError("Error on configuring favicon") } } let updateThemeURLs = themesData => { open LogicUtils open HyperSwitchConfigTypes try { let urlsDict = themesData->getDictFromJsonObject->getDictfromDict("urls") let existingEnv = DOMUtils.window._env_ let val = { faviconUrl: urlsDict ->getString("faviconUrl", existingEnv.urlThemeConfig.faviconUrl->Option.getOr("")) ->getNonEmptyString, logoUrl: urlsDict ->getString("logoUrl", existingEnv.urlThemeConfig.logoUrl->Option.getOr("")) ->getNonEmptyString, } let updatedUrlConfig = { ...existingEnv, urlThemeConfig: val, } DOMUtils.window._env_ = updatedUrlConfig configureFavIcon(updatedUrlConfig.urlThemeConfig.faviconUrl)->ignore updatedUrlConfig.urlThemeConfig.faviconUrl } catch { | _ => Exn.raiseError("Error while updating theme URL and favicon") } } let getThemesJson = async (themesID, configRes, devThemeFeature) => { open LogicUtils //will remove configRes once feature flag is removed. try { let themeJson = if !devThemeFeature || themesID->isEmptyString { let dict = configRes->getDictFromJsonObject->getDictfromDict("theme") let {settings: defaultSettings, _} = newDefaultConfig let defaultStyle = { "settings": { "colors": { "primary": dict->getString("primary_color", defaultSettings.colors.primary), "sidebar": dict->getString("sidebar_primary", defaultSettings.sidebar.primary), }, "sidebar": { "secondary": dict->getString("sidebar_secondary", defaultSettings.sidebar.secondary), "hoverColor": dict->getString( "sidebar_hover_color", defaultSettings.sidebar.hoverColor, ), "primaryTextColor": dict->getString( "sidebar_primary_text_color", defaultSettings.sidebar.primaryTextColor, ), "secondaryTextColor": dict->getString( "sidebar_secondary_text_color", defaultSettings.sidebar.secondaryTextColor, ), "borderColor": dict->getString( "sidebar_border_color", defaultSettings.sidebar.borderColor, ), }, "buttons": { "primary": { "backgroundColor": dict->getString( "primary_color", defaultSettings.buttons.primary.backgroundColor, ), "hoverBackgroundColor": dict->getString( "primary_hover_color", defaultSettings.buttons.primary.hoverBackgroundColor, ), }, }, }, } defaultStyle->Identity.genericTypeToJson } else { let url = `${GlobalVars.getHostUrl}/themes/${themesID}/theme.json` let themeResponse = await fetchApi( `${url}`, ~method_=Get, ~xFeatureRoute=true, ~forceCookies=false, ) let themesData = await themeResponse->(res => res->Fetch.Response.json) themesData } updateThemeURLs(themeJson)->ignore configCustomDomainTheme(themeJson)->ignore themeJson } catch { | _ => { let defaultStyle = {"settings": newDefaultConfig.settings}->Identity.genericTypeToJson updateThemeURLs(defaultStyle)->ignore configCustomDomainTheme(defaultStyle)->ignore defaultStyle } } } let value = React.useMemo(() => { { globalUIConfig: UIConfig.defaultUIConfig, theme, themeSetter: setTheme, configCustomDomainTheme, getThemesJson, } }, (theme, setTheme)) React.useEffect(() => { if theme === Dark { setTheme(Light) } None }, []) <Parent value> <div className=themeClassName> <div className="bg-jp-gray-100 dark:bg-jp-gray-darkgray_background text-gray-700 dark:text-gray-200 red:bg-red"> children </div> </div> </Parent> }
2,558
10,158
hyperswitch-control-center
src/context/DataTableFilterOpenContext.res
.res
let defaultValue: Dict.t<bool> = Dict.make() let setDefaultValue: (string, bool) => unit = (_key, _b) => () let filterOpenContext = React.createContext((defaultValue, setDefaultValue)) let make = React.Context.provider(filterOpenContext)
55
10,159
hyperswitch-control-center
src/context/ReactSuspenseWrapper.res
.res
@react.component let make = (~children, ~loadingText="Loading...") => { <React.Suspense fallback={<Loader loadingText />}> <ErrorBoundary> children </ErrorBoundary> </React.Suspense> }
50
10,160
hyperswitch-control-center
src/context/AuthInfoProvider.res
.res
open AuthProviderTypes type defaultProviderTypes = { authStatus: authStatus, setAuthStatus: authStatus => unit, setAuthStateToLogout: unit => unit, setAuthMethods: ( array<SSOTypes.authMethodResponseType> => array<SSOTypes.authMethodResponseType> ) => unit, authMethods: array<SSOTypes.authMethodResponseType>, } let defaultContextValue = { authStatus: CheckingAuthStatus, setAuthStatus: _ => (), setAuthStateToLogout: _ => (), setAuthMethods: _ => (), authMethods: AuthUtils.defaultListOfAuth, } let authStatusContext = React.createContext(defaultContextValue) module Provider = { let make = React.Context.provider(authStatusContext) } @react.component let make = (~children) => { let (authStatus, setAuth) = React.useState(_ => CheckingAuthStatus) let (authMethods, setAuthMethods) = React.useState(_ => []) let setAuthStatus = React.useCallback((newAuthStatus: authStatus) => { switch newAuthStatus { | LoggedIn(info) => switch info { | Auth(totpInfo) => if totpInfo.token->Option.isSome { setAuth(_ => newAuthStatus) AuthUtils.setDetailsToLocalStorage(totpInfo, "USER_INFO") } else { setAuth(_ => LoggedOut) CommonAuthUtils.clearLocalStorage() } } | PreLogin(preLoginInfo) => setAuth(_ => newAuthStatus) AuthUtils.setDetailsToLocalStorage(preLoginInfo, "PRE_LOGIN_INFO") | LoggedOut => { setAuth(_ => LoggedOut) CommonAuthUtils.clearLocalStorage() } | CheckingAuthStatus => setAuth(_ => CheckingAuthStatus) } }, [setAuth]) let setAuthStateToLogout = React.useCallback(() => { setAuth(_ => LoggedOut) CommonAuthUtils.clearLocalStorage() CookieStorage.deleteCookie(~cookieName="login_token", ~domain=GlobalVars.hostName) }, []) <Provider value={ authStatus, setAuthStatus, setAuthStateToLogout, setAuthMethods, authMethods, }> children </Provider> }
484
10,161
hyperswitch-control-center
src/context/FormAuthContext.res
.res
let formAuthContext = React.createContext(CommonAuthTypes.Access) let make = React.Context.provider(formAuthContext)
23
10,162
hyperswitch-control-center
src/context/BetaEndPointConfigProvider.res
.res
let defaultSetter = _ => () let defaultValue: option<AuthHooks.betaEndpoint> = None let betaEndPointConfig = React.createContext(defaultValue) let make = React.Context.provider(betaEndPointConfig)
41
10,163
hyperswitch-control-center
src/context/AddAttributesContext.res
.res
let ignoreAttributesContext = React.createContext(false) module Provider = { let make = React.Context.provider(ignoreAttributesContext) } @react.component let make = (~children, ~ignoreAttributes) => { <Provider value=ignoreAttributes> <div> children </div> </Provider> }
63
10,164
hyperswitch-control-center
src/context/SingleStatContext.res
.res
open AnalyticsTypesUtils open SingleStatEntity open DictionaryUtils open Promise open LogicUtils open AnalyticsNewUtils type singleStatComponent = { singleStatData: option<Dict.t<dataState<JSON.t>>>, singleStatTimeSeries: option<Dict.t<dataState<JSON.t>>>, singleStatDelta: option<Dict.t<dataState<JSON.t>>>, singleStatLoader: Dict.t<AnalyticsUtils.loaderType>, singleStatIsVisible: (bool => bool) => unit, } let singleStatComponentDefVal = { singleStatData: None, singleStatTimeSeries: None, singleStatDelta: None, singleStatLoader: Dict.make(), singleStatIsVisible: _ => (), } let singleStatContext = React.createContext(singleStatComponentDefVal) module Provider = { let make = React.Context.provider(singleStatContext) } @react.component let make = ( ~children, ~singleStatEntity: singleStatEntity<'a>, ~setSingleStatTime=_ => (), ~setIndividualSingleStatTime=_ => (), ) => { let { moduleName, modeKey, source, customFilterKey, startTimeFilterKey, endTimeFilterKey, filterKeys, dataFetcherObj, metrixMapper, } = singleStatEntity let {userInfo: {merchantId, profileId}} = React.useContext(UserInfoProvider.defaultContext) let jsonTransFormer = switch singleStatEntity { | {jsonTransformer} => jsonTransformer | _ => (_val, arr) => arr } let {filterValueJson} = React.useContext(FilterContext.filterContext) let getAllFilter = filterValueJson let (isSingleStatVisible, setSingleStatIsVisible) = React.useState(_ => false) let parentToken = AuthWrapperUtils.useTokenParent(Original) let addLogsAroundFetch = AnalyticsLogUtilsHook.useAddLogsAroundFetchNew() let betaEndPointConfig = React.useContext(BetaEndPointConfigProvider.betaEndPointConfig) let fetchApi = AuthHooks.useApiFetcher() let {xFeatureRoute, forceCookies} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let getTopLevelSingleStatFilter = React.useMemo(() => { getAllFilter ->Dict.toArray ->Belt.Array.keepMap(item => { let (key, value) = item let keyArr = key->String.split(".") let prefix = keyArr->Array.get(0)->Option.getOr("") if prefix === moduleName && prefix->LogicUtils.isNonEmptyString { None } else { Some((prefix, value)) } }) ->Dict.fromArray }, [getAllFilter]) let (topFiltersToSearchParam, customFilter, modeValue) = React.useMemo(() => { let modeValue = Some(getTopLevelSingleStatFilter->LogicUtils.getString(modeKey, "")) let allFilterKeys = Array.concat( [startTimeFilterKey, endTimeFilterKey, modeValue->Option.getOr("")], filterKeys, ) let filterSearchParam = getTopLevelSingleStatFilter ->Dict.toArray ->Belt.Array.keepMap(entry => { let (key, value) = entry if allFilterKeys->Array.includes(key) { switch value->JSON.Classify.classify { | String(str) => `${key}=${str}`->Some | Number(num) => `${key}=${num->String.make}`->Some | Array(arr) => `${key}=[${arr->String.make}]`->Some | _ => None } } else { None } }) ->Array.joinWith("&") ( filterSearchParam, getTopLevelSingleStatFilter->LogicUtils.getString(customFilterKey, ""), modeValue, ) }, [getTopLevelSingleStatFilter]) let filterValueFromUrl = React.useMemo(() => { getTopLevelSingleStatFilter ->Dict.toArray ->Belt.Array.keepMap(entries => { let (key, value) = entries filterKeys->Array.includes(key) ? Some((key, value)) : None }) ->getJsonFromArrayOfJson ->Some }, [topFiltersToSearchParam]) let startTimeFromUrl = React.useMemo(() => { getTopLevelSingleStatFilter->LogicUtils.getString(startTimeFilterKey, "") }, [topFiltersToSearchParam]) let endTimeFromUrl = React.useMemo(() => { getTopLevelSingleStatFilter->LogicUtils.getString(endTimeFilterKey, "") }, [topFiltersToSearchParam]) let initialValue = dataFetcherObj ->Array.map(item => { let {metrics} = item let updatedMetrics = metrics->metrixMapper (updatedMetrics, Loading) }) ->Dict.fromArray let initialValueLoader = dataFetcherObj ->Array.map(item => { let {metrics} = item let updatedMetrics = metrics->metrixMapper (updatedMetrics, AnalyticsUtils.Shimmer) }) ->Dict.fromArray let (singleStatStateData, setSingleStatStateData) = React.useState(_ => initialValue) let (singleStatTimeSeries, setSingleStatTimeSeries) = React.useState(_ => initialValue) let (singleStatStateDataHistoric, setSingleStatStateDataHistoric) = React.useState(_ => initialValue ) let (singleStatLoader, setSingleStatLoader) = React.useState(_ => initialValueLoader) let ( singleStatFetchedWithCurrentDependency, setIsSingleStatFetchedWithCurrentDependency, ) = React.useState(_ => false) React.useEffect(() => { if ( startTimeFromUrl->LogicUtils.isNonEmptyString && endTimeFromUrl->LogicUtils.isNonEmptyString && parentToken->Option.isSome ) { setIsSingleStatFetchedWithCurrentDependency(_ => false) } None }, (endTimeFromUrl, startTimeFromUrl, filterValueFromUrl, parentToken, customFilter, modeValue)) React.useEffect(() => { if !singleStatFetchedWithCurrentDependency && isSingleStatVisible { setIsSingleStatFetchedWithCurrentDependency(_ => true) let granularity = LineChartUtils.getGranularityNew( ~startTime=startTimeFromUrl, ~endTime=endTimeFromUrl, ) let filterConfigCurrent = { source, modeValue: modeValue->Option.getOr(""), filterValues: ?filterValueFromUrl, startTime: startTimeFromUrl, endTime: endTimeFromUrl, customFilterValue: customFilter, // will add later granularity: ?granularity->Array.get(0), } let (hStartTime, hEndTime) = AnalyticsNewUtils.calculateHistoricTime( ~startTime=startTimeFromUrl, ~endTime=endTimeFromUrl, ) let filterConfigHistoric = { ...filterConfigCurrent, startTime: hStartTime, endTime: hEndTime, } setSingleStatTime(_ => { let a: timeObj = { apiStartTime: Date.now(), apiEndTime: 0., } a }) dataFetcherObj ->Array.mapWithIndex((urlConfig, index) => { let {url, metrics} = urlConfig let updatedMetrics = metrics->metrixMapper setIndividualSingleStatTime( prev => { let individualTime = prev->Dict.toArray->Dict.fromArray individualTime->Dict.set(index->Int.toString, Date.now()) individualTime }, ) setSingleStatStateData( prev => { let prevDict = prev->copyOfDict Dict.set(prevDict, updatedMetrics, Loading) prevDict }, ) setSingleStatTimeSeries( prev => { let prevDict = prev->copyOfDict Dict.set(prevDict, updatedMetrics, Loading) prevDict }, ) setSingleStatStateDataHistoric( prev => { let prevDict = prev->copyOfDict Dict.set(prevDict, updatedMetrics, Loading) prevDict }, ) let timeObj = Dict.fromArray([ ("start", filterConfigCurrent.startTime->JSON.Encode.string), ("end", filterConfigCurrent.endTime->JSON.Encode.string), ]) let historicTimeObj = Dict.fromArray([ ("start", filterConfigHistoric.startTime->JSON.Encode.string), ("end", filterConfigHistoric.endTime->JSON.Encode.string), ]) let granularityConfig = switch filterConfigCurrent { | {granularity} => granularity | _ => (1, "hour") } let singleStatHistoricDataFetch = fetchApi( `${url}?api-type=singlestat&time=historic&metrics=${updatedMetrics}`, ~method_=Post, ~bodyStr=apiBodyMaker( ~timeObj=historicTimeObj, ~metric=updatedMetrics, ~filterValueFromUrl=?filterConfigHistoric.filterValues, ~customFilterValue=filterConfigHistoric.customFilterValue, ~domain=urlConfig.domain, )->JSON.stringify, ~headers=[("QueryType", "SingleStatHistoric")]->Dict.fromArray, ~betaEndpointConfig=?betaEndPointConfig, ~xFeatureRoute, ~forceCookies, ~merchantId, ~profileId, ) ->addLogsAroundFetch( ~logTitle=`SingleStat histotic data for metrics ${metrics->metrixMapper}`, ) ->then( text => { let jsonObj = convertNewLineSaperatedDataToArrayOfJson(text) let jsonObj = jsonTransFormer(updatedMetrics, jsonObj) resolve({ setSingleStatStateDataHistoric( prev => { let prevDict = prev->copyOfDict Dict.set( prevDict, updatedMetrics, Loaded(jsonObj->Array.get(0)->Option.getOr(JSON.Encode.object(Dict.make()))), ) prevDict }, ) Loaded(JSON.Encode.object(Dict.make())) }) }, ) ->catch( _err => { setSingleStatStateDataHistoric( prev => { let prevDict = prev->copyOfDict Dict.set(prevDict, updatedMetrics, LoadedError) prevDict }, ) resolve(LoadedError) }, ) let singleStatDataFetch = fetchApi( `${url}?api-type=singlestat&metrics=${updatedMetrics}`, ~method_=Post, ~bodyStr=apiBodyMaker( ~timeObj, ~metric=updatedMetrics, ~filterValueFromUrl=?filterConfigCurrent.filterValues, ~customFilterValue=filterConfigCurrent.customFilterValue, ~domain=urlConfig.domain, )->JSON.stringify, ~headers=[("QueryType", "SingleStat")]->Dict.fromArray, ~betaEndpointConfig=?betaEndPointConfig, ~xFeatureRoute, ~forceCookies, ~merchantId, ~profileId, ) ->addLogsAroundFetch(~logTitle=`SingleStat data for metrics ${metrics->metrixMapper}`) ->then( text => { let jsonObj = convertNewLineSaperatedDataToArrayOfJson(text) let jsonObj = jsonTransFormer(updatedMetrics, jsonObj) setSingleStatStateData( prev => { let prevDict = prev->copyOfDict Dict.set( prevDict, updatedMetrics, Loaded(jsonObj->Array.get(0)->Option.getOr(JSON.Encode.object(Dict.make()))), ) prevDict }, ) resolve(Loaded(JSON.Encode.object(Dict.make()))) }, ) ->catch( _err => { setSingleStatStateData( prev => { let prevDict = prev->copyOfDict Dict.set(prevDict, updatedMetrics, LoadedError) prevDict }, ) resolve(LoadedError) }, ) let singleStatDataFetchTimeSeries = fetchApi( `${url}?api-type=singlestat-timeseries&metrics=${updatedMetrics}`, ~method_=Post, ~bodyStr=apiBodyMaker( ~timeObj, ~metric=updatedMetrics, ~filterValueFromUrl=?filterConfigCurrent.filterValues, ~granularityConfig, ~customFilterValue=filterConfigCurrent.customFilterValue, ~domain=urlConfig.domain, ~timeCol=urlConfig.timeColumn, )->JSON.stringify, ~headers=[("QueryType", "SingleStat Time Series")]->Dict.fromArray, ~betaEndpointConfig=?betaEndPointConfig, ~xFeatureRoute, ~forceCookies, ~merchantId, ~profileId, ) ->addLogsAroundFetch( ~logTitle=`SingleStat Time Series data for metrics ${metrics->metrixMapper}`, ) ->then( text => { let jsonObj = convertNewLineSaperatedDataToArrayOfJson(text)->Array.map( item => { item ->getDictFromJsonObject ->Dict.toArray ->Array.map( dictEn => { let (key, value) = dictEn (key === `${urlConfig.timeColumn}_time` ? "time" : key, value) }, ) ->Dict.fromArray ->JSON.Encode.object }, ) let jsonObj = jsonTransFormer(updatedMetrics, jsonObj) setSingleStatTimeSeries( prev => { let prevDict = prev->copyOfDict Dict.set(prevDict, updatedMetrics, Loaded(jsonObj->JSON.Encode.array)) prevDict }, ) resolve(Loaded(JSON.Encode.object(Dict.make()))) }, ) ->catch( _err => { setSingleStatTimeSeries( prev => { let prevDict = prev->copyOfDict Dict.set(prevDict, updatedMetrics, LoadedError) prevDict }, ) resolve(LoadedError) }, ) [singleStatDataFetchTimeSeries, singleStatHistoricDataFetch, singleStatDataFetch] ->Promise.all ->Promise.thenResolve( value => { let ssH = value->Array.get(0)->Option.getOr(LoadedError) let ssT = value->Array.get(1)->Option.getOr(LoadedError) let ssD = value->Array.get(2)->Option.getOr(LoadedError) let isLoaded = val => { switch val { | Loaded(_) => true | _ => false } } setSingleStatLoader( prev => { let prevDict = prev->copyOfDict if isLoaded(ssH) && isLoaded(ssT) && isLoaded(ssD) { Dict.set(prevDict, updatedMetrics, AnalyticsUtils.SideLoader) } prevDict }, ) setIndividualSingleStatTime( prev => { let individualTime = prev->Dict.toArray->Dict.fromArray individualTime->Dict.set( index->Int.toString, Date.now() -. individualTime->Dict.get(index->Int.toString)->Option.getOr(Date.now()), ) individualTime }, ) if index === dataFetcherObj->Array.length - 1 { setSingleStatTime( prev => { ...prev, apiEndTime: Date.now(), }, ) } }, ) ->ignore }) ->ignore } None }, (singleStatFetchedWithCurrentDependency, isSingleStatVisible)) let value = React.useMemo(() => { { singleStatData: Some(singleStatStateData), singleStatTimeSeries: Some(singleStatTimeSeries), singleStatDelta: Some(singleStatStateDataHistoric), singleStatLoader, singleStatIsVisible: setSingleStatIsVisible, } }, (singleStatStateData, singleStatTimeSeries, singleStatLoader, setSingleStatIsVisible)) <Provider value> children </Provider> }
3,461
10,165
hyperswitch-control-center
src/context/UserTimeZoneProvider.res
.res
open UserTimeZoneTypes let defaultSetter = _ => () let userTimeContext = React.createContext((IST, defaultSetter)) module TimeZone = { let make = React.Context.provider(userTimeContext) } @react.component let make = (~children) => { let (zone, setZoneBase) = React.useState(_ => UserTimeZoneTypes.IST) let setZone = React.useCallback(value => { setZoneBase(_ => value) }, [setZoneBase]) <TimeZone value=(zone, setZone)> children </TimeZone> }
115
10,166
hyperswitch-control-center
src/context/TokenContextProvider.res
.res
let defaultTokenSetter = _ => () let defaultDictSetter = _ => () type tokenContextObjectType = { token: option<string>, setToken: (option<string> => option<string>) => unit, tokenDetailsDict: Dict.t<JSON.t>, setTokenDetailsDict: (Dict.t<JSON.t> => Dict.t<JSON.t>) => unit, parentAuthInfo: option<AuthProviderTypes.authInfo>, } let defaultTokenObj = { token: None, setToken: defaultTokenSetter, tokenDetailsDict: Dict.make(), setTokenDetailsDict: defaultDictSetter, parentAuthInfo: Some(AuthUtils.getAuthInfo(JSON.Encode.object(Dict.make()))), } let tokenContext = React.createContext(defaultTokenObj) module Parent = { let make = React.Context.provider(tokenContext) } @react.component let make = (~children) => { let currentToken = AuthWrapperUtils.useTokenParent(Default) let (token, setToken) = React.useState(_ => currentToken) let (tokenDetailsDict, setTokenDetailsDict) = React.useState(_ => Dict.make()) let tokenContextObjext = React.useMemo(() => { let parentAuthInfo = Some( AuthUtils.getAuthInfo(tokenDetailsDict->LogicUtils.getJsonObjectFromDict("tokenDict")), ) { token, setToken, tokenDetailsDict, setTokenDetailsDict, parentAuthInfo, } }, (token, tokenDetailsDict, setToken, setTokenDetailsDict)) <Parent value=tokenContextObjext> children </Parent> }
336
10,167
hyperswitch-control-center
src/context/DateFormatProvider.res
.res
let defaultValue = "MMM DD, YYYY hh:mm A" let dateFormatContext = React.createContext(defaultValue) @live let make = React.Context.provider(dateFormatContext)
35
10,168
hyperswitch-control-center
src/context/DatatableContext.res
.res
let defaultValue: Dict.t<array<JSON.t>> = Dict.make() let setDefaultValue: (string, array<JSON.t>) => unit = (_string, _arr) => () let datatableContext = React.createContext((defaultValue, setDefaultValue)) let make = React.Context.provider(datatableContext)
61
10,169
hyperswitch-control-center
src/context/ChartContext.res
.res
open AnalyticsTypesUtils open Promise open LogicUtils type chartComponent = { topChartData: option<dataState<JSON.t>>, bottomChartData: option<dataState<JSON.t>>, topChartLegendData: option<dataState<JSON.t>>, bottomChartLegendData: option<dataState<JSON.t>>, setTopChartVisible: (bool => bool) => unit, setBottomChartVisible: (bool => bool) => unit, setGranularity: (option<string> => option<string>) => unit, granularity: option<string>, } let chartComponentDefVal = { topChartData: None, bottomChartData: None, topChartLegendData: None, bottomChartLegendData: None, setTopChartVisible: _ => (), setBottomChartVisible: _ => (), setGranularity: _ => (), granularity: None, } let cardinalityMapperToNumber = cardinality => { switch cardinality { | Some(cardinality) => switch cardinality { | "TOP_5" => 5. | "TOP_10" => 10. | _ => 5. } | None => 5. } } let getGranularityMapper = (granularity: string) => { let granularityArr = granularity->String.split(" ")->Array.map(item => item->String.trim) if granularity === "Daily" { (1, "day") } else if granularity === "Weekly" { (1, "week") } else if granularity === "Hourly" { (1, "hour") } else { ( granularityArr->Array.get(0)->Option.getOr("1")->Int.fromString->Option.getOr(1), granularityArr->Array.get(1)->Option.getOr("week"), ) } } let chartContext = React.createContext(chartComponentDefVal) module Provider = { let make = React.Context.provider(chartContext) } @react.component let make = (~children, ~chartEntity: DynamicChart.entity, ~chartId="", ~defaultFilter=?) => { let {filterValueJson} = React.useContext(FilterContext.filterContext) let getAllFilter = filterValueJson let (activeTab, activeTabStr) = React.useMemo(() => { let activeTabOptionalArr = getAllFilter->getOptionStrArrayFromDict(`${chartEntity.moduleName}.tabName`) (activeTabOptionalArr, activeTabOptionalArr->Option.getOr([])->Array.joinWith(",")) }, [getAllFilter]) let parentToken = AuthWrapperUtils.useTokenParent(Original) let addLogsAroundFetch = AnalyticsLogUtilsHook.useAddLogsAroundFetchNew() let betaEndPointConfig = React.useContext(BetaEndPointConfigProvider.betaEndPointConfig) let fetchApi = AuthHooks.useApiFetcher() let jsonTransFormer = switch chartEntity { | {jsonTransformer} => jsonTransformer | _ => (_val, arr) => arr } let (topChartData, setTopChartData) = React.useState(_ => Loading) let (topChartVisible, setTopChartVisible) = React.useState(_ => false) let (bottomChartData, setBottomChartData) = React.useState(_ => Loading) let (bottomChartVisible, setBottomChartVisible) = React.useState(_ => false) let (topChartDataLegendData, setTopChartDataLegendData) = React.useState(_ => Loading) let (bottomChartDataLegendData, setBottomChartDataLegendData) = React.useState(_ => Loading) let {userInfo: {merchantId, profileId}} = React.useContext(UserInfoProvider.defaultContext) let getGranularity = LineChartUtils.getGranularityNewStr let {filterValue} = React.useContext(FilterContext.filterContext) let (currentTopMatrix, currentBottomMetrix) = chartEntity.currentMetrics let (startTimeFilterKey, endTimeFilterKey) = chartEntity.dateFilterKeys let defaultFilters = [startTimeFilterKey, endTimeFilterKey] let {allFilterDimension} = chartEntity let {xFeatureRoute, forceCookies} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let sortingParams = React.useMemo((): option<AnalyticsNewUtils.sortedBasedOn> => { switch chartEntity { | {sortingColumnLegend} => Some({ sortDimension: sortingColumnLegend, ordering: #Desc, }) | _ => None } }, [chartEntity.sortingColumnLegend]) let allFilterKeys = Array.concat(defaultFilters, allFilterDimension) let customFilterKey = switch chartEntity { | {customFilterKey} => customFilterKey | _ => "" } let getAllFilter = filterValue ->Dict.toArray ->Array.map(item => { let (key, value) = item (key, value->UrlFetchUtils.getFilterValue) }) ->Dict.fromArray let getTopLevelChartFilter = React.useMemo(() => { getAllFilter ->Dict.toArray ->Belt.Array.keepMap(item => { let (key, value) = item let keyArr = key->String.split(".") let prefix = keyArr->Array.get(0)->Option.getOr("") if prefix === chartId && prefix->isNonEmptyString { None } else { Some((prefix, value)) } }) ->Dict.fromArray }, [getAllFilter]) let (topFiltersToSearchParam, customFilter) = React.useMemo(() => { let filterSearchParam = getTopLevelChartFilter ->Dict.toArray ->Belt.Array.keepMap(entry => { let (key, value) = entry if allFilterKeys->Array.includes(key) { switch value->JSON.Classify.classify { | String(str) => `${key}=${str}`->Some | Number(num) => `${key}=${num->String.make}`->Some | Array(arr) => `${key}=[${arr->String.make}]`->Some | _ => None } } else { None } }) ->Array.joinWith("&") (filterSearchParam, getTopLevelChartFilter->getString(customFilterKey, "")) }, [getTopLevelChartFilter]) let customFilter = switch defaultFilter { | Some(defaultFilter) => customFilter->isEmptyString ? defaultFilter : `${defaultFilter} and ${customFilter}` | _ => customFilter } let getChartCompFilters = React.useMemo(() => { getAllFilter ->Dict.toArray ->Belt.Array.keepMap(item => { let (key, value) = item let keyArr = key->String.split(".") let prefix = keyArr->Array.get(0)->Option.getOr("") let fitlerName = keyArr->Array.get(1)->Option.getOr("") // when chart id is not there then there won't be any prefix so the prefix will the filter name if chartId->isEmptyString { Some((prefix, value)) } else if prefix === chartId && fitlerName->isNonEmptyString { Some((fitlerName, value)) } else { None } }) ->Dict.fromArray }, [getAllFilter]) let (startTimeFromUrl, endTimeFromUrl, filterValueFromUrl) = React.useMemo(() => { let startTimeFromUrl = getTopLevelChartFilter->getString(startTimeFilterKey, "") let endTimeFromUrl = getTopLevelChartFilter->getString(endTimeFilterKey, "") let filterValueFromUrl = getTopLevelChartFilter ->Dict.toArray ->Belt.Array.keepMap(entries => { let (key, value) = entries chartEntity.allFilterDimension->Array.includes(key) ? Some((key, value)) : None }) ->Dict.fromArray ->JSON.Encode.object ->Some (startTimeFromUrl, endTimeFromUrl, filterValueFromUrl) }, [topFiltersToSearchParam]) let cardinalityFromUrl = getChartCompFilters->getString("cardinality", "TOP_5") let chartTopMetricFromUrl = getChartCompFilters->getString("chartTopMetric", currentTopMatrix) let chartBottomMetricFromUrl = getChartCompFilters->getString("chartBottomMetric", currentBottomMetrix) let (granularity, setGranularity) = React.useState(_ => None) let current_granularity = if ( startTimeFromUrl->isNonEmptyString && endTimeFromUrl->isNonEmptyString ) { getGranularity(~startTime=startTimeFromUrl, ~endTime=endTimeFromUrl) } else { [] } React.useEffect(() => { setGranularity(prev => { current_granularity->Array.includes(prev->Option.getOr("")) ? prev : current_granularity->Array.get(0) }) None }, (startTimeFromUrl, endTimeFromUrl)) let ( topChartFetchWithCurrentDependecyChange, setTopChartFetchWithCurrentDependecyChange, ) = React.useState(_ => false) let ( bottomChartFetchWithCurrentDependecyChange, setBottomChartFetchWithCurrentDependecyChange, ) = React.useState(_ => false) React.useEffect(() => { let chartType = getChartCompFilters->getString( "chartType", chartEntity.chartTypes->Array.get(0)->Option.getOr(Line)->DynamicChart.chartMapper, ) if ( startTimeFromUrl->isNonEmptyString && endTimeFromUrl->isNonEmptyString && parentToken->Option.isSome && (granularity->Option.isSome || chartType !== "Line Chart") && current_granularity->Array.includes(granularity->Option.getOr("")) ) { setTopChartFetchWithCurrentDependecyChange(_ => false) } None }, ( parentToken, current_granularity->Array.joinWith("-") ++ granularity->Option.getOr("") ++ cardinalityFromUrl ++ chartTopMetricFromUrl ++ customFilter ++ startTimeFromUrl ++ endTimeFromUrl, activeTabStr, filterValueFromUrl, sortingParams, )) React.useEffect(() => { let chartType = getChartCompFilters->getString( "chartType", chartEntity.chartTypes->Array.get(0)->Option.getOr(Line)->DynamicChart.chartMapper, ) if ( startTimeFromUrl->isNonEmptyString && endTimeFromUrl->isNonEmptyString && parentToken->Option.isSome && (granularity->Option.isSome || chartType !== "Line Chart") && current_granularity->Array.includes(granularity->Option.getOr("")) ) { setBottomChartFetchWithCurrentDependecyChange(_ => false) } None }, ( parentToken, current_granularity->Array.joinWith("-") ++ granularity->Option.getOr("") ++ chartBottomMetricFromUrl ++ startTimeFromUrl ++ cardinalityFromUrl ++ customFilter ++ endTimeFromUrl, activeTabStr, filterValueFromUrl, sortingParams, )) React.useEffect(() => { if !topChartFetchWithCurrentDependecyChange && topChartVisible { setTopChartFetchWithCurrentDependecyChange(_ => true) switch chartEntity.uriConfig->Array.find(item => { let metrics = switch item.metrics->Array.get(0) { | Some(metrics) => metrics.metric_label | None => "" } metrics === chartTopMetricFromUrl }) { | Some(value) => { setTopChartDataLegendData(_ => Loading) setTopChartData(_ => Loading) let cardinality = cardinalityMapperToNumber(Some(cardinalityFromUrl)) let timeObj = Dict.fromArray([ ("start", startTimeFromUrl->JSON.Encode.string), ("end", endTimeFromUrl->JSON.Encode.string), ]) let (metric, secondaryMetrics) = switch value.metrics->Array.get(0) { | Some(metrics) => (metrics.metric_name_db, metrics.secondryMetrics) | None => ("", None) } let timeCol = value.timeCol let metricsArr = switch secondaryMetrics { | Some(value) => [value.metric_name_db, metric] | None => [metric] } let granularityConfig = granularity->Option.getOr("")->getGranularityMapper metricsArr ->Array.map(metric => { fetchApi( `${value.uri}?api-type=Chart-timeseries&metrics=${metric}`, ~method_=Post, ~bodyStr=AnalyticsNewUtils.apiBodyMaker( ~timeObj, ~groupBy=?activeTab, ~metric, ~filterValueFromUrl?, ~cardinality, ~granularityConfig, ~customFilterValue=customFilter, ~sortingParams?, ~timeCol, ~domain=value.domain->Option.getOr(""), )->JSON.stringify, ~headers=[("QueryType", "Chart Time Series")]->Dict.fromArray, ~betaEndpointConfig=?betaEndPointConfig, ~xFeatureRoute, ~forceCookies, ~merchantId, ~profileId, ) ->addLogsAroundFetch(~logTitle=`Chart fetch`) ->then( text => { let jsonObj = convertNewLineSaperatedDataToArrayOfJson(text)->Array.map( item => { item ->getDictFromJsonObject ->Dict.toArray ->Array.map( dictEn => { let (key, value) = dictEn (key === `${timeCol}_time` ? "time" : key, value) }, ) ->Dict.fromArray ->JSON.Encode.object }, ) resolve(jsonTransFormer(metric, jsonObj)->JSON.Encode.array) }, ) ->catch( _err => { resolve(JSON.Encode.null) }, ) }) ->Promise.all ->then(metricsArr => { resolve( setTopChartData( _ => Loaded( dataMerge( ~dataArr=metricsArr->Array.map(item => item->getArrayFromJson([])), ~dictKey=Array.concat(activeTab->Option.getOr([]), ["time"]), )->JSON.Encode.array, ), ), ) }) ->ignore fetchApi( `${value.uri}?api-type=Chart-legend&metrics=${metric}`, ~method_=Post, ~bodyStr=AnalyticsNewUtils.apiBodyMaker( ~timeObj, ~groupBy=?activeTab, ~metric, ~cardinality, ~filterValueFromUrl?, ~customFilterValue=customFilter, ~sortingParams?, ~domain=value.domain->Option.getOr(""), )->JSON.stringify, ~headers=[("QueryType", "Chart Legend")]->Dict.fromArray, ~betaEndpointConfig=?betaEndPointConfig, ~xFeatureRoute, ~forceCookies, ~merchantId, ~profileId, ) ->addLogsAroundFetch(~logTitle=`Chart legend Data`) ->then(text => { let jsonObj = convertNewLineSaperatedDataToArrayOfJson(text)->JSON.Encode.array resolve(setTopChartDataLegendData(_ => Loaded(jsonObj))) }) ->catch(_err => { resolve(setTopChartDataLegendData(_ => LoadedError)) }) ->ignore } | None => () } } None }, (topChartFetchWithCurrentDependecyChange, topChartVisible)) React.useEffect(() => { if !bottomChartFetchWithCurrentDependecyChange && bottomChartVisible { setBottomChartFetchWithCurrentDependecyChange(_ => true) switch chartEntity.uriConfig->Array.find(item => { let metrics = switch item.metrics->Array.get(0) { | Some(metrics) => metrics.metric_label | None => "" } metrics === chartBottomMetricFromUrl }) { | Some(value) => { setBottomChartDataLegendData(_ => Loading) setBottomChartData(_ => Loading) let cardinality = cardinalityMapperToNumber(Some(cardinalityFromUrl)) let timeObj = Dict.fromArray([ ("start", startTimeFromUrl->JSON.Encode.string), ("end", endTimeFromUrl->JSON.Encode.string), ]) let (metric, secondaryMetrics) = switch value.metrics->Array.get(0) { | Some(metrics) => (metrics.metric_name_db, metrics.secondryMetrics) | None => ("", None) } let metricsArr = switch secondaryMetrics { | Some(value) => [value.metric_name_db, metric] | None => [metric] } let timeCol = value.timeCol let granularityConfig = granularity->Option.getOr("")->getGranularityMapper metricsArr ->Array.map(metric => { fetchApi( `${value.uri}?api-type=Chart-timeseries&metrics=${metric}`, ~method_=Post, ~bodyStr=AnalyticsNewUtils.apiBodyMaker( ~timeObj, ~groupBy=?activeTab, ~metric, ~filterValueFromUrl?, ~cardinality, ~granularityConfig, ~customFilterValue=customFilter, ~sortingParams?, ~timeCol=value.timeCol, ~domain=value.domain->Option.getOr(""), )->JSON.stringify, ~headers=[("QueryType", "Chart Time Series")]->Dict.fromArray, ~betaEndpointConfig=?betaEndPointConfig, ~xFeatureRoute, ~forceCookies, ~merchantId, ~profileId, ) ->addLogsAroundFetch(~logTitle=`Chart fetch bottomChart`) ->then( text => { let jsonObj = convertNewLineSaperatedDataToArrayOfJson(text)->Array.map( item => { item ->getDictFromJsonObject ->Dict.toArray ->Array.map( dictEn => { let (key, value) = dictEn (key === `${timeCol}_time` ? "time" : key, value) }, ) ->Dict.fromArray ->JSON.Encode.object }, ) resolve(jsonTransFormer(metric, jsonObj)->JSON.Encode.array) }, ) ->catch( _err => { resolve(JSON.Encode.null) }, ) }) ->Promise.all ->then(metricsArr => { let data = dataMerge( ~dataArr=metricsArr->Array.map(item => item->getArrayFromJson([])), ~dictKey=Array.concat(activeTab->Option.getOr([]), ["time"]), )->JSON.Encode.array resolve(setBottomChartData(_ => Loaded(data))) }) ->ignore fetchApi( `${value.uri}?api-type=Chart-legend&metrics=${metric}`, ~method_=Post, ~bodyStr=AnalyticsNewUtils.apiBodyMaker( ~timeObj, ~groupBy=?activeTab, ~metric, ~cardinality, ~filterValueFromUrl?, ~customFilterValue=customFilter, ~sortingParams?, ~domain=value.domain->Option.getOr(""), )->JSON.stringify, ~headers=[("QueryType", "Chart Legend")]->Dict.fromArray, ~betaEndpointConfig=?betaEndPointConfig, ~xFeatureRoute, ~forceCookies, ~merchantId, ~profileId, ) ->addLogsAroundFetch(~logTitle=`Chart legend Data`) ->then(text => { let jsonObj = convertNewLineSaperatedDataToArrayOfJson(text)->JSON.Encode.array resolve(setBottomChartDataLegendData(_ => Loaded(jsonObj))) }) ->catch(_err => { resolve(setBottomChartDataLegendData(_ => LoadedError)) }) ->ignore } | None => () } } None }, (bottomChartFetchWithCurrentDependecyChange, bottomChartVisible)) let chartData = React.useMemo(() => { (topChartData, topChartDataLegendData, bottomChartData, bottomChartDataLegendData) }, (topChartData, topChartDataLegendData, bottomChartData, bottomChartDataLegendData)) let value = React.useMemo(() => { let ( topChartData, topChartDataLegendData, bottomChartData, bottomChartDataLegendData, ) = chartData { topChartData: Some(topChartData), bottomChartData: Some(bottomChartData), topChartLegendData: Some(topChartDataLegendData), bottomChartLegendData: Some(bottomChartDataLegendData), setTopChartVisible, setBottomChartVisible, setGranularity, granularity, } }, (chartData, setTopChartVisible, setBottomChartVisible, setGranularity, granularity)) <Provider value> children </Provider> } module SDKAnalyticsChartContext = { @react.component let make = ( ~children, ~chartEntity: DynamicChart.entity, ~selectedTrends, ~filterMapper, ~chartId="", ~defaultFilter=?, ~dataMergerAndTransformer, ~segmentValue: option<array<string>>=?, ~differentTimeValues: option<array<AnalyticsUtils.timeRanges>>=?, ) => { let {xFeatureRoute, forceCookies} = HyperswitchAtom.featureFlagAtom->Recoil.useRecoilValueFromAtom let parentToken = AuthWrapperUtils.useTokenParent(Original) let addLogsAroundFetch = AnalyticsLogUtilsHook.useAddLogsAroundFetchNew() let betaEndPointConfig = React.useContext(BetaEndPointConfigProvider.betaEndPointConfig) let fetchApi = AuthHooks.useApiFetcher() let jsonTransFormer = switch chartEntity { | {jsonTransformer} => jsonTransformer | _ => (_val, arr) => arr } let {userInfo: {merchantId, profileId}} = React.useContext(UserInfoProvider.defaultContext) let (topChartData, setTopChartData) = React.useState(_ => Loading) let (topChartVisible, setTopChartVisible) = React.useState(_ => false) let bottomChartData = Loading let (_bottomChartVisible, setBottomChartVisible) = React.useState(_ => false) let (topChartDataLegendData, setTopChartDataLegendData) = React.useState(_ => Loading) let bottomChartDataLegendData = Loading let getGranularity = LineChartUtils.getGranularityNewStr let {filterValue} = React.useContext(FilterContext.filterContext) let (currentTopMatrix, currentBottomMetrix) = chartEntity.currentMetrics let (startTimeFilterKey, endTimeFilterKey) = chartEntity.dateFilterKeys let defaultFilters = [startTimeFilterKey, endTimeFilterKey] let {allFilterDimension} = chartEntity let allFilterKeys = Array.concat(defaultFilters, allFilterDimension) let customFilterKey = switch chartEntity { | {customFilterKey} => customFilterKey | _ => "" } let getAllFilter = filterValue ->Dict.toArray ->Array.map(item => { let (key, value) = item (key, value->UrlFetchUtils.getFilterValue) }) ->Dict.fromArray let getTopLevelChartFilter = React.useMemo(() => { getAllFilter ->Dict.toArray ->Belt.Array.keepMap(item => { let (key, value) = item let keyArr = key->String.split(".") let prefix = keyArr->Array.get(0)->Option.getOr("") if prefix === chartId && prefix->isNonEmptyString { None } else { Some((prefix, value)) } }) ->Dict.fromArray }, [getAllFilter]) let (topFiltersToSearchParam, customFilter) = React.useMemo(() => { let filterSearchParam = getTopLevelChartFilter ->Dict.toArray ->Belt.Array.keepMap(entry => { let (key, value) = entry if allFilterKeys->Array.includes(key) { switch value->JSON.Classify.classify { | String(str) => `${key}=${str}`->Some | Number(num) => `${key}=${num->String.make}`->Some | Array(arr) => `${key}=[${arr->String.make}]`->Some | _ => None } } else { None } }) ->Array.joinWith("&") (filterSearchParam, getTopLevelChartFilter->getString(customFilterKey, "")) }, [getTopLevelChartFilter]) let customFilter = switch defaultFilter { | Some(defaultFilter) => customFilter->isEmptyString ? defaultFilter : `${defaultFilter} and ${customFilter}` | _ => customFilter } let getChartCompFilters = React.useMemo(() => { getAllFilter ->Dict.toArray ->Belt.Array.keepMap(item => { let (key, value) = item let keyArr = key->String.split(".") let prefix = keyArr->Array.get(0)->Option.getOr("") let fitlerName = keyArr->Array.get(1)->Option.getOr("") // when chart id is not there then there won't be any prefix so the prefix will the filter name if chartId->isEmptyString { Some((prefix, value)) } else if prefix === chartId && fitlerName->isNonEmptyString { Some((fitlerName, value)) } else { None } }) ->Dict.fromArray }, [getAllFilter]) let (startTimeFromUrl, endTimeFromUrl, filterValueFromUrl) = React.useMemo(() => { let startTimeFromUrl = getTopLevelChartFilter->getString(startTimeFilterKey, "") let endTimeFromUrl = getTopLevelChartFilter->getString(endTimeFilterKey, "") let filterValueFromUrl = getTopLevelChartFilter ->Dict.toArray ->Belt.Array.keepMap(entries => { let (key, value) = entries chartEntity.allFilterDimension->Array.includes(key) ? Some((key, value)) : None }) ->getJsonFromArrayOfJson ->Some (startTimeFromUrl, endTimeFromUrl, filterValueFromUrl) }, [topFiltersToSearchParam]) let currentTimeRanges: AnalyticsUtils.timeRanges = { fromTime: startTimeFromUrl, toTime: endTimeFromUrl, } let differentTimeValues = Array.concat( [currentTimeRanges], differentTimeValues->Option.getOr([]), ) let cardinalityFromUrl = getChartCompFilters->getString("cardinality", "TOP_5") let _chartTopMetricFromUrl = getChartCompFilters->getString("chartTopMetric", currentTopMatrix) let _chartBottomMetricFromUrl = getChartCompFilters->getString("chartBottomMetric", currentBottomMetrix) let (granularity, setGranularity) = React.useState(_ => None) let current_granularity = if ( startTimeFromUrl->isNonEmptyString && endTimeFromUrl->isNonEmptyString ) { getGranularity(~startTime=startTimeFromUrl, ~endTime=endTimeFromUrl) } else { [] } React.useEffect(() => { setGranularity(prev => { current_granularity->Array.includes(prev->Option.getOr("")) ? prev : current_granularity->Array.get(0) }) None }, (startTimeFromUrl, endTimeFromUrl)) let ( topChartFetchWithCurrentDependecyChange, setTopChartFetchWithCurrentDependecyChange, ) = React.useState(_ => false) React.useEffect( () => { let chartType = getChartCompFilters->getString( "chartType", chartEntity.chartTypes->Array.get(0)->Option.getOr(Line)->DynamicChart.chartMapper, ) if ( startTimeFromUrl->isNonEmptyString && endTimeFromUrl->isNonEmptyString && parentToken->Option.isSome && (granularity->Option.isSome || chartType !== "Line Chart") && current_granularity->Array.includes(granularity->Option.getOr("")) ) { setTopChartFetchWithCurrentDependecyChange(_ => false) } None }, ( parentToken, current_granularity->Array.joinWith("-") ++ granularity->Option.getOr("") ++ cardinalityFromUrl ++ selectedTrends->Array.joinWith(",") ++ customFilter ++ startTimeFromUrl ++ segmentValue->Option.getOr([])->Array.joinWith(",") ++ endTimeFromUrl, filterValueFromUrl, differentTimeValues ->Array.map(item => `${item.fromTime}${item.toTime}`) ->Array.joinWith(","), ), ) React.useEffect(() => { if !topChartFetchWithCurrentDependecyChange && topChartVisible { setTopChartFetchWithCurrentDependecyChange(_ => true) let metricsSDK = "total_volume" switch chartEntity.uriConfig->Array.find(item => { let metrics = switch item.metrics->Array.get(0) { | Some(metrics) => metrics.metric_name_db | None => "" } metrics === metricsSDK }) { | Some(value) => { let timeCol = value.timeCol setTopChartDataLegendData(_ => Loading) setTopChartData(_ => Loading) let cardinality = cardinalityMapperToNumber(Some(cardinalityFromUrl)) let metric = switch value.metrics->Array.get(0) { | Some(metrics) => metrics.metric_name_db | None => "" } let granularityConfig = granularity->Option.getOr("")->getGranularityMapper switch differentTimeValues->Array.get(0) { | Some(timeObjOrig) => { let timeObj = Dict.fromArray([ ("start", timeObjOrig.fromTime->JSON.Encode.string), ("end", timeObjOrig.toTime->JSON.Encode.string), ]) fetchApi( `${value.uri}?api-type=Chart-timeseries&metrics=${metric}&top5`, ~method_=Post, ~bodyStr=AnalyticsNewUtils.apiBodyMaker( ~timeObj, ~groupBy=?segmentValue, ~metric, ~cardinality, ~filterValueFromUrl?, ~customFilterValue=customFilter, ~timeCol, ~domain=value.domain->Option.getOr(""), )->JSON.stringify, ~headers=[("QueryType", "Chart Time Series")]->Dict.fromArray, ~betaEndpointConfig=?betaEndPointConfig, ~xFeatureRoute, ~forceCookies, ~merchantId, ~profileId, ) ->addLogsAroundFetch(~logTitle=`Chart fetch`) ->then(text => { let groupedArr = convertNewLineSaperatedDataToArrayOfJson(text)->Array.map( item => { item ->getDictFromJsonObject ->Dict.toArray ->Belt.Array.keepMap( dictOrigItem => { let (key, value) = dictOrigItem segmentValue->Option.getOr([])->Array.includes(key) ? Some(value->JSON.Decode.string->Option.getOr("")) : None }, ) ->Array.joinWith("-dimension-") }, ) selectedTrends ->Array.map( item => { fetchApi( `${value.uri}?api-type=Chart-timeseries&metrics=${metric}&trend=${item}`, ~method_=Post, ~bodyStr=AnalyticsNewUtils.apiBodyMaker( ~timeObj, ~groupBy=?segmentValue, ~metric, ~filterValueFromUrl?, ~granularityConfig, ~customFilterValue=customFilter, ~timeCol, ~jsonFormattedFilter=item->filterMapper, ~domain=value.domain->Option.getOr(""), )->JSON.stringify, ~headers=[("QueryType", "Chart Time Series")]->Dict.fromArray, ~betaEndpointConfig=?betaEndPointConfig, ~xFeatureRoute, ~forceCookies, ~merchantId, ~profileId, ) ->addLogsAroundFetch(~logTitle=`Chart fetch`) ->then( text => resolve(( item, `${timeObjOrig.fromTime} to ${timeObjOrig.toTime}`, jsonTransFormer( metric, convertNewLineSaperatedDataToArrayOfJson(text)->Belt.Array.keepMap( item => { let origDictArr = item ->getDictFromJsonObject ->Dict.toArray ->Belt.Array.keepMap( origDictArrItem => { let (key, value) = origDictArrItem segmentValue->Option.getOr([])->Array.includes(key) ? Some(value->JSON.Decode.string->Option.getOr("")) : None }, ) ->Array.joinWith("-dimension-") groupedArr->Array.includes(origDictArr) ? Some( item ->getDictFromJsonObject ->Dict.toArray ->Array.map( dictEn => { let (key, value) = dictEn (key === `${timeCol}_time` ? "time" : key, value) }, ) ->Dict.fromArray ->JSON.Encode.object, ) : None }, ), )->JSON.Encode.array, )), ) ->catch(_err => resolve((item, "", []->JSON.Encode.array))) }, ) ->Promise.all ->Promise.thenResolve( dataArr => { setTopChartData( _ => Loaded( dataMergerAndTransformer( ~selectedTrends, ~data=dataArr, ~segments=?segmentValue, ~startTime=startTimeFromUrl, ~endTime=endTimeFromUrl, ~granularityConfig, (), ), ), ) }, ) ->ignore resolve() }) ->catch(_err => resolve()) ->ignore } | None => () } } | None => () } } None }, (topChartFetchWithCurrentDependecyChange, topChartVisible)) // React.useEffect(() => { // if !bottomChartFetchWithCurrentDependecyChange && bottomChartVisible { // setBottomChartFetchWithCurrentDependecyChange(_ => true) // let metricsSDK = "total_volume" // switch chartEntity.uriConfig->Array.find(item => { // let metrics = switch item.metrics->Array.get(0) { // | Some(metrics) => metrics.metric_name_db // | None => "" // } // metrics === metricsSDK // }) { // | Some(value) => { // setBottomChartDataLegendData(_ => Loading) // setBottomChartData(_ => Loading) // let cardinality = cardinalityMapperToNumber(Some(cardinalityFromUrl)) // let metric = switch value.metrics->Array.get(0) { // | Some(metrics) => metrics.metric_name_db // | None => "" // } // let granularityConfig = // granularity->Option.getOr("")->getGranularityMapper // differentTimeValues // ->Array.map(timeObjOrig => { // let timeObj = Dict.fromArray([ // ("start", timeObjOrig.fromTime->JSON.Encode.string), // ("end", timeObjOrig.toTime->JSON.Encode.string), // ]) // selectedTrends->Array.map( // item => { // fetchApi( // `${value.uri}?api-type=Chart-timeseries&metrics=${metric}&trend=${item}`, // ~method_=Post, // ~bodyStr=AnalyticsNewUtils.apiBodyMaker( // ~timeObj, // ~groupBy=?segmentValue, // ~metric, // ~filterValueFromUrl?, // ~cardinality, // ~customFilterValue=customFilter, // ~jsonFormattedFilter=item->filterMapper, // ~domain=value.domain->Option.getOr(""), // (), // )->JSON.stringify, // ~headers=[("QueryType", "Chart Time Series")]->Dict.fromArray, // ~betaEndpointConfig=?betaEndPointConfig, // (), // ) // ->addLogsAroundFetch(~logTitle=`Chart fetch`) // ->then( // text => // resolve(( // item, // `${timeObjOrig.fromTime} to ${timeObjOrig.toTime}`, // convertNewLineSaperatedDataToArrayOfJson(text)->JSON.Encode.array, // )), // ) // ->catch(_err => resolve((item, "", []->JSON.Encode.array))) // }, // ) // }) // ->Array.concatMany // ->Promise.all // ->Promise.thenResolve(dataArr => { // setBottomChartData( // _ => Loaded( // dataMergerAndTransformer( // ~selectedTrends, // ~data=dataArr, // ~segments=?segmentValue, // ~startTime=startTimeFromUrl, // ~endTime=endTimeFromUrl, // ~granularityConfig, // (), // ), // ), // ) // }) // ->ignore // } // | None => () // } // } // None // }, (bottomChartFetchWithCurrentDependecyChange, bottomChartVisible)) let chartData = React.useMemo(() => { (topChartData, topChartDataLegendData, bottomChartData, bottomChartDataLegendData) }, (topChartData, topChartDataLegendData, bottomChartData, bottomChartDataLegendData)) let value = React.useMemo(() => { let ( topChartData, topChartDataLegendData, bottomChartData, bottomChartDataLegendData, ) = chartData { topChartData: Some(topChartData), bottomChartData: Some(bottomChartData), topChartLegendData: Some(topChartDataLegendData), bottomChartLegendData: Some(bottomChartDataLegendData), setTopChartVisible, setBottomChartVisible, setGranularity, granularity, } }, (chartData, setTopChartVisible, setBottomChartVisible, setGranularity, granularity)) <Provider value> children </Provider> } }
8,362
10,170
hyperswitch-control-center
src/context/LoadedTableContext.res
.res
type infoData external toInfoData: 'a => array<Nullable.t<infoData>> = "%identity" let arr: array<Nullable.t<infoData>> = [] let loadedTableContext = React.createContext(arr) let make = React.Context.provider(loadedTableContext)
58
10,171
hyperswitch-control-center
src/context/MatchMedia.res
.res
let useMatchMedia = mediaQuery => { let mediaQueryList = React.useMemo(() => { Window.matchMedia(mediaQuery) }, [mediaQuery]) let (isMatched, setIsMatched) = React.useState(_ => { mediaQueryList.matches }) React.useEffect(() => { let screenTest = (ev: Window.MatchMedia.matchEvent) => { let matched = ev.matches setIsMatched(_prev => matched) } mediaQueryList.addListener(screenTest) Some(() => mediaQueryList.removeListener(screenTest)) }, [mediaQueryList]) isMatched } let useMobileChecker = () => { useMatchMedia("(max-width: 700px)") } let useScreenSizeChecker = (~screenSize) => { useMatchMedia(`(max-width: ${screenSize}px)`) }
183
10,172
hyperswitch-control-center
src/Interface/ConnectorInterface/ConnectorInterfaceUtils.res
.res
open ConnectorTypes open LogicUtils let connectorAuthTypeMapper = (str): connectorAuthType => { switch str->String.toLowerCase { | "headerkey" => HeaderKey | "bodykey" => BodyKey | "signaturekey" => SignatureKey | "multiauthkey" => MultiAuthKey | "currencyauthkey" => CurrencyAuthKey | "certificateauth" => CertificateAuth | _ => UnKnownAuthType } } let getHeaderAuth = (dict): headerKey => { auth_type: dict->getString("auth_type", ""), api_key: dict->getString("api_key", ""), } let getBodyKeyAuth = (dict): bodyKey => { auth_type: dict->getString("auth_type", ""), api_key: dict->getString("api_key", ""), key1: dict->getString("key1", ""), } let getSignatureKeyAuth = (dict): signatureKey => { auth_type: dict->getString("auth_type", ""), api_key: dict->getString("api_key", ""), key1: dict->getString("key1", ""), api_secret: dict->getString("api_secret", ""), } let getMultiAuthKeyAuth = (dict): multiAuthKey => { auth_type: dict->getString("auth_type", ""), api_key: dict->getString("api_key", ""), key1: dict->getString("key1", ""), api_secret: dict->getString("api_secret", ""), key2: dict->getString("key2", ""), } let getCurrencyAuthKey = (dict): currencyAuthKey => { auth_type: dict->getString("auth_type", ""), auth_key_map: dict->getDictfromDict("auth_key_map"), } let getCertificateAuth = (dict): certificateAuth => { auth_type: dict->getString("auth_type", ""), certificate: dict->getString("certificate", ""), private_key: dict->getString("private_key", ""), } let getAccountDetails = (dict): connectorAuthTypeObj => { let authType = dict->getString("auth_type", "")->connectorAuthTypeMapper switch authType { | HeaderKey => HeaderKey(dict->getHeaderAuth) | BodyKey => BodyKey(dict->getBodyKeyAuth) | SignatureKey => SignatureKey(dict->getSignatureKeyAuth) | MultiAuthKey => MultiAuthKey(dict->getMultiAuthKeyAuth) | CurrencyAuthKey => CurrencyAuthKey(dict->getCurrencyAuthKey) | CertificateAuth => CertificateAuth(dict->getCertificateAuth) | UnKnownAuthType => UnKnownAuthType(JSON.Encode.null) } } let parsePaymentMethodType = paymentMethodType => { let paymentMethodTypeDict = paymentMethodType->getDictFromJsonObject { payment_method_type: paymentMethodTypeDict->getString("payment_method_type", ""), flow: paymentMethodTypeDict->getString("flow", ""), action: paymentMethodTypeDict->getString("action", ""), } } let parsePaymentMethodResponse = paymentMethod => { let paymentMethodDict = paymentMethod->getDictFromJsonObject let payment_method_types = paymentMethodDict ->getArrayFromDict("payment_method_types", []) ->Array.map(parsePaymentMethodType) let flow = paymentMethodDict->getString("flow", "") { payment_method: paymentMethodDict->getString("payment_method", ""), payment_method_types, flow, } } let parsePaymentMethod = paymentMethod => { let paymentMethodDict = paymentMethod->getDictFromJsonObject let flow = paymentMethodDict->getString("flow", "") { payment_method: paymentMethodDict->getString("payment_method", ""), flow, } } let convertFRMConfigJsonToObjResponse = json => { json->Array.map(config => { let configDict = config->getDictFromJsonObject let payment_methods = configDict->getArrayFromDict("payment_methods", [])->Array.map(parsePaymentMethodResponse) { gateway: configDict->getString("gateway", ""), payment_methods, } }) } let convertFRMConfigJsonToObj = json => { json->Array.map(config => { let configDict = config->getDictFromJsonObject let payment_methods = configDict->getArrayFromDict("payment_methods", [])->Array.map(parsePaymentMethod) { gateway: configDict->getString("gateway", ""), payment_methods, } }) } let getPaymentMethodTypes = (dict): paymentMethodConfigType => { open ConnectorUtils { payment_method_type: dict->getString("payment_method_type", ""), payment_experience: dict->getOptionString("payment_experience"), card_networks: dict->getStrArrayFromDict("card_networks", []), accepted_countries: dict->getDictfromDict("accepted_countries")->acceptedValues, accepted_currencies: dict->getDictfromDict("accepted_currencies")->acceptedValues, minimum_amount: dict->getOptionInt("minimum_amount"), maximum_amount: dict->getOptionInt("maximum_amount"), recurring_enabled: dict->getOptionBool("recurring_enabled"), installment_payment_enabled: dict->getOptionBool("installment_payment_enabled"), } } let getPaymentMethodTypesV2 = (dict): ConnectorTypes.paymentMethodConfigTypeV2 => { open ConnectorUtils { payment_method_subtype: dict->getString("payment_method_subtype", ""), payment_experience: dict->getOptionString("payment_experience"), card_networks: dict->getStrArrayFromDict("card_networks", []), accepted_countries: dict->getDictfromDict("accepted_countries")->acceptedValues, accepted_currencies: dict->getDictfromDict("accepted_currencies")->acceptedValues, minimum_amount: dict->getOptionInt("minimum_amount"), maximum_amount: dict->getOptionInt("maximum_amount"), recurring_enabled: dict->getOptionBool("recurring_enabled"), installment_payment_enabled: dict->getOptionBool("installment_payment_enabled"), } } let getPaymentMethodsEnabled: Dict.t<JSON.t> => paymentMethodEnabledType = dict => { { payment_method: dict->getString("payment_method", ""), payment_method_types: dict ->Dict.get("payment_method_types") ->Option.getOr(Dict.make()->JSON.Encode.object) ->getArrayDataFromJson(getPaymentMethodTypes), } } let mapDictToConnectorPayload = (dict): connectorPayload => { { connector_type: dict ->getString("connector_type", "") ->ConnectorUtils.connectorTypeStringToTypeMapper, connector_name: dict->getString("connector_name", ""), connector_label: dict->getString("connector_label", ""), connector_account_details: dict ->getObj("connector_account_details", Dict.make()) ->getAccountDetails, test_mode: dict->getBool("test_mode", true), disabled: dict->getBool("disabled", true), payment_methods_enabled: dict ->Dict.get("payment_methods_enabled") ->Option.getOr(Dict.make()->JSON.Encode.object) ->getArrayDataFromJson(getPaymentMethodsEnabled), profile_id: dict->getString("profile_id", ""), merchant_connector_id: dict->getString("merchant_connector_id", ""), frm_configs: dict->getArrayFromDict("frm_configs", [])->convertFRMConfigJsonToObjResponse, status: dict->getString("status", "inactive"), connector_webhook_details: dict ->Dict.get("connector_webhook_details") ->Option.getOr(JSON.Encode.null), metadata: dict->getObj("metadata", Dict.make())->JSON.Encode.object, additional_merchant_data: dict ->getObj("additional_merchant_data", Dict.make()) ->JSON.Encode.object, } } let getPaymentMethodsEnabledV2: Dict.t<JSON.t> => paymentMethodEnabledTypeV2 = dict => { { payment_method_type: dict->getString("payment_method_type", ""), payment_method_subtypes: dict ->Dict.get("payment_method_subtypes") ->Option.getOr(Dict.make()->JSON.Encode.object) ->getArrayDataFromJson(getPaymentMethodTypesV2), } } let mapDictToConnectorPayloadV2 = (dict): connectorPayloadV2 => { { connector_type: dict ->getString("connector_type", "") ->ConnectorUtils.connectorTypeStringToTypeMapper, connector_name: dict->getString("connector_name", ""), connector_label: dict->getString("connector_label", ""), connector_account_details: dict ->getObj("connector_account_details", Dict.make()) ->getAccountDetails, disabled: dict->getBool("disabled", true), payment_methods_enabled: dict ->getJsonObjectFromDict("payment_methods_enabled") ->getArrayDataFromJson(getPaymentMethodsEnabledV2), profile_id: dict->getString("profile_id", ""), id: dict->getString("id", ""), frm_configs: dict->getArrayFromDict("frm_configs", [])->convertFRMConfigJsonToObjResponse, status: dict->getString("status", "inactive"), connector_webhook_details: dict->getJsonObjectFromDict("connector_webhook_details"), metadata: dict->getObj("metadata", Dict.make())->JSON.Encode.object, additional_merchant_data: dict ->getObj("additional_merchant_data", Dict.make()) ->JSON.Encode.object, feature_metadata: dict ->getObj("feature_metadata", Dict.make()) ->JSON.Encode.object, } } let filter = (connectorType, ~retainInList) => { switch (retainInList, connectorType) { | (PaymentProcessor, PaymentProcessor) | (PaymentVas, PaymentVas) | (PayoutProcessor, PayoutProcessor) | (AuthenticationProcessor, AuthenticationProcessor) | (PMAuthProcessor, PMAuthProcessor) | (TaxProcessor, TaxProcessor) | (BillingProcessor, BillingProcessor) => true | _ => false } } let filterConnectorList = (items: array<ConnectorTypes.connectorPayload>, retainInList) => { items->Array.filter(connector => connector.connector_type->filter(~retainInList)) } let filterConnectorListV2 = (items: array<ConnectorTypes.connectorPayloadV2>, retainInList) => { items->Array.filter(connector => connector.connector_type->filter(~retainInList)) } let mapConnectorPayloadToConnectorType = ( ~connectorType=ConnectorTypes.Processor, connectorsList: array<ConnectorTypes.connectorPayload>, ) => { connectorsList->Array.map(connectorDetail => connectorDetail.connector_name->ConnectorUtils.getConnectorNameTypeFromString(~connectorType) ) } let mapConnectorPayloadToConnectorTypeV2 = ( ~connectorType=ConnectorTypes.Processor, connectorsList: array<ConnectorTypes.connectorPayloadV2>, ) => { connectorsList->Array.map(connectorDetail => connectorDetail.connector_name->ConnectorUtils.getConnectorNameTypeFromString(~connectorType) ) } let mapJsonArrayToConnectorPayloads = (json, retainInList) => { json ->getArrayFromJson([]) ->Array.map(connectorJson => { let data = connectorJson->getDictFromJsonObject->mapDictToConnectorPayload data }) ->filterConnectorList(retainInList) } let mapJsonArrayToConnectorPayloadsV2 = (json, retainInList) => { json ->getArrayFromJson([]) ->Array.map(connectorJson => { let data = connectorJson->getDictFromJsonObject->mapDictToConnectorPayloadV2 data }) ->filterConnectorListV2(retainInList) }
2,489
10,173
hyperswitch-control-center
src/Interface/ConnectorInterface/ConnectorInterface.res
.res
open ConnectorTypes open ConnectorInterfaceUtils // Interface module type ConnectorInterface = { type mapperInput type mapperOutput type filterCriteria type input type output let mapDictToConnectorPayload: mapperInput => mapperOutput let mapJsonArrayToConnectorPayloads: (JSON.t, filterCriteria) => array<mapperOutput> let mapConnectorPayloadToConnectorType: (input, array<mapperOutput>) => array<output> } // Each module implements the ConnectorInterface but uses different types. // Module Implementation for V1 module V1: ConnectorInterface with type mapperInput = Dict.t<JSON.t> and type mapperOutput = connectorPayload and type filterCriteria = ConnectorTypes.connectorTypeVariants and type input = ConnectorTypes.connector and type output = ConnectorTypes.connectorTypes = { type mapperInput = Dict.t<JSON.t> type mapperOutput = connectorPayload type filterCriteria = ConnectorTypes.connectorTypeVariants type input = ConnectorTypes.connector type output = ConnectorTypes.connectorTypes let mapDictToConnectorPayload = (dict: mapperInput): mapperOutput => mapDictToConnectorPayload(dict) let mapJsonArrayToConnectorPayloads = (json: JSON.t, retainInList: filterCriteria) => mapJsonArrayToConnectorPayloads(json, retainInList) let mapConnectorPayloadToConnectorType = ( connectorType: input, connectorList: array<mapperOutput>, ): array<output> => mapConnectorPayloadToConnectorType(~connectorType, connectorList) } // Module Implementation for V2 module V2: ConnectorInterface with type mapperInput = Dict.t<JSON.t> and type mapperOutput = connectorPayloadV2 and type filterCriteria = ConnectorTypes.connectorTypeVariants and type input = ConnectorTypes.connector and type output = ConnectorTypes.connectorTypes = { type mapperInput = Dict.t<JSON.t> type mapperOutput = connectorPayloadV2 type filterCriteria = ConnectorTypes.connectorTypeVariants type input = ConnectorTypes.connector type output = ConnectorTypes.connectorTypes let mapDictToConnectorPayload = (dict: mapperInput): mapperOutput => mapDictToConnectorPayloadV2(dict) let mapJsonArrayToConnectorPayloads = (json: JSON.t, retainInList: filterCriteria) => mapJsonArrayToConnectorPayloadsV2(json, retainInList) let mapConnectorPayloadToConnectorType = ( connectorType: input, connectorList: array<mapperOutput>, ): array<output> => mapConnectorPayloadToConnectorTypeV2(~connectorType, connectorList) } //parametric polymorphism, connectorInterfaceFCM is a type that takes 5 type parameters // This allows for parametric polymorphism, meaning we can generalize the ConnectorInterface module with different types ('a, 'b, etc.). type connectorInterfaceFCM<'a, 'b, 'c, 'd, 'e> = module(ConnectorInterface with type mapperInput = 'a and type mapperOutput = 'b and type filterCriteria = 'c and type input = 'd and type output = 'e ) //Creating Instances of the Interface //Defines connectorInterfaceV1 as an instance of ConnectorInterface using V1. let connectorInterfaceV1: connectorInterfaceFCM< Dict.t<JSON.t>, connectorPayload, ConnectorTypes.connectorTypeVariants, ConnectorTypes.connector, ConnectorTypes.connectorTypes, > = module(V1) // Defines connectorInterfaceV2 using V2. let connectorInterfaceV2: connectorInterfaceFCM< Dict.t<JSON.t>, connectorPayloadV2, ConnectorTypes.connectorTypeVariants, ConnectorTypes.connector, ConnectorTypes.connectorTypes, > = module(V2) // Generic Function: mapDictToConnectorPayload // This function takes: // 1. A module L implementing ConnectorInterface. // 2. An input of type a (mapperInput). // 3. It calls L.mapDictToConnectorPayload and returns the mapped output. let mapDictToConnectorPayload = ( type a b c d e, module(L: ConnectorInterface with type mapperInput = a and type mapperOutput = b and type filterCriteria = c and type input = d and type output = e ), inp: a, ): b => { L.mapDictToConnectorPayload(inp) } let mapJsonArrayToConnectorPayloads = ( type a b c d e, module(L: ConnectorInterface with type mapperInput = a and type mapperOutput = b and type filterCriteria = c and type input = d and type output = e ), inp: JSON.t, filterCriteria: c, ): array<b> => { L.mapJsonArrayToConnectorPayloads(inp, filterCriteria) } let mapConnectorPayloadToConnectorType = ( type a b c d e, module(L: ConnectorInterface with type mapperInput = a and type mapperOutput = b and type filterCriteria = c and type input = d and type output = e ), inp1: d, inp2: array<b>, ): array<e> => { L.mapConnectorPayloadToConnectorType(inp1, inp2) } let useConnectorArrayMapper = (~interface, ~retainInList=PaymentProcessor) => { let json = Recoil.useRecoilValueFromAtom(HyperswitchAtom.connectorListAtom) let data = mapJsonArrayToConnectorPayloads(interface, json, retainInList) data }
1,220
10,174
hyperswitch-control-center
src/hooks/DateRefreshHooks.res
.res
open DayJs open DateRangeUtils let useConstructQueryOnBasisOfOpt = () => { let customTimezoneToISOString = TimeZoneHook.useCustomTimeZoneToIsoString() let isoStringToCustomTimeZone = TimeZoneHook.useIsoStringToCustomTimeZone() let isoStringToCustomTimezoneInFloat = TimeZoneHook.useIsoStringToCustomTimeZoneInFloat() let todayDayJsObj = Date.make()->Date.toString->getDayJsForString let todayDate = todayDayJsObj.format("YYYY-MM-DD") let todayTime = todayDayJsObj.format("HH:mm:ss") (~queryString, ~disableFutureDates, ~disablePastDates, ~startKey, ~endKey, ~optKey) => { if queryString->String.includes(optKey) { try { let arrQuery = queryString->String.split("&") let tempArr = arrQuery->Array.filter(x => x->String.includes(optKey)) let tempArr = tempArr[0]->Option.getOr("")->String.split("=") let optVal = tempArr[1]->Option.getOr("") let customrange: customDateRange = switch optVal { | "today" => Today | "yesterday" => Yesterday | "tomorrow" => Tomorrow | "last_month" => LastMonth | "this_month" => ThisMonth | "next_month" => NextMonth | st => { let arr = st->String.split("_") let _ = arr[0]->Option.getOr("") == "next" let anchor = arr[2]->Option.getOr("") let val = arr[1]->Option.getOr("") switch anchor { | "days" => Day(val->Float.fromString->Option.getOr(0.0)) | "hours" => Hour(val->Float.fromString->Option.getOr(0.0)) | "mins" => Hour(val->Float.fromString->Option.getOr(0.0) /. 60.0) | _ => Today } } } let (stDate, enDate, stTime, enTime) = getPredefinedStartAndEndDate( todayDayJsObj, isoStringToCustomTimeZone, isoStringToCustomTimezoneInFloat, customTimezoneToISOString, customrange, disableFutureDates, disablePastDates, todayDate, todayTime, ) let stTimeStamp = changeTimeFormat( ~date=stDate, ~time=stTime, ~customTimezoneToISOString, ~format="YYYY-MM-DDTHH:mm:ss.SSS[Z]", ) let enTimeStamp = changeTimeFormat( ~date=enDate, ~time=enTime, ~customTimezoneToISOString, ~format="YYYY-MM-DDTHH:mm:ss.SSS[Z]", ) let updatedArr = arrQuery->Array.map(x => if x->String.includes(startKey) { `${startKey}=${stTimeStamp}` } else if x->String.includes(endKey) { `${endKey}=${enTimeStamp}` } else { x } ) updatedArr->Array.joinWith("&") } catch { | _error => queryString } } else { queryString } } }
707
10,175
hyperswitch-control-center
src/hooks/OutsideClick.res
.res
external ffToDomType: Dom.eventTarget => Dom.node_like<'a> = "%identity" external ffToWebDom: Nullable.t<Dom.element> => Nullable.t<Webapi.Dom.Element.t> = "%identity" type ref = | ArrayOfRef(array<React.ref<Nullable.t<Dom.element>>>) | RefArray(React.ref<array<Nullable.t<Dom.element>>>) let useOutsideClick = ( ~refs: ref, ~containerRefs: option<React.ref<Nullable.t<Dom.element>>>=?, ~isActive, ~events=["click"], ~callback, ) => { let eventCallback = UseEvent.useEvent0(callback) React.useEffect(() => { if isActive { let handleClick = (e: Dom.event) => { let targ = Webapi.Dom.Event.target(e) let isInsideClick = switch refs { | ArrayOfRef(refs) => refs->Array.reduce(false, (acc, ref: React.ref<Nullable.t<Dom.element>>) => { let isClickInsideRef = switch ffToWebDom(ref.current)->Nullable.toOption { | Some(element) => element->Webapi.Dom.Element.contains(~child=ffToDomType(targ)) | None => false } acc || isClickInsideRef }) | RefArray(refs) => refs.current ->Array.slice(~start=0, ~end=-1) ->Array.reduce(false, (acc, ref: Nullable.t<Dom.element>) => { let isClickInsideRef = switch ffToWebDom(ref)->Nullable.toOption { | Some(element) => element->Webapi.Dom.Element.contains(~child=ffToDomType(targ)) | None => false } acc || isClickInsideRef }) } let isClickInsideOfContainer = switch containerRefs { | Some(ref) => switch ffToWebDom(ref.current)->Nullable.toOption { | Some(element) => element->Webapi.Dom.Element.contains(~child=ffToDomType(targ)) | None => false } | None => true } if !isInsideClick && isClickInsideOfContainer { eventCallback() } } setTimeout(() => { events->Array.forEach( event => { Webapi.Dom.window->Webapi.Dom.Window.addEventListener(event, handleClick) }, ) }, 50)->ignore Some( () => { events->Array.forEach(event => Webapi.Dom.window->Webapi.Dom.Window.removeEventListener(event, handleClick) ) }, ) } else { None } }, [isActive]) }
566
10,176
hyperswitch-control-center
src/hooks/PopUpState.res
.res
type popUpType = Success | Primary | Secondary | Danger | Warning | Denied type iconType = WithIcon | WithoutIcon type popUpSize = Small | Large type popupAction = { text: string, icon?: Button.iconType, onClick?: ReactEvent.Mouse.t => unit, } type popUpProps = { heading: string, description: React.element, popUpType: (popUpType, iconType), handleCancel?: popupAction, handleConfirm: popupAction, popUpSize?: popUpSize, showCloseIcon?: bool, } let defaultOpenPopUp: array<popUpProps> = [] let openPopUp = Recoil.atom("openPopUp", defaultOpenPopUp) let useShowPopUp = () => { let setOpenPopUp = Recoil.useSetRecoilState(openPopUp) React.useCallback((popUpProps: popUpProps) => { setOpenPopUp(prevArr => prevArr->Array.concat([popUpProps])) }, [setOpenPopUp]) }
224
10,177
hyperswitch-control-center
src/hooks/SnackBarState.res
.res
type snackbarType = | General | Success | Error | Warning | Information type snackbarProps = { snackbarKey: string, heading: string, body: string, snackbarType: snackbarType, actionElement: React.element, onClose?: unit => unit, } let defaultOpenSnackbar: array<snackbarProps> = [] let openSnackbar = Recoil.atom("openSnackbar", defaultOpenSnackbar) type showSnackbarFn = ( ~heading: string, ~body: string, ~snackbarType: snackbarType, ~actionElement: React.element=?, ~onClose: unit => unit=?, unit, ) => unit
154
10,178
hyperswitch-control-center
src/hooks/ApiProgressHooks.res
.res
let pendingRequestCount = Recoil.atom("pendingRequestCount", 0)
16
10,179
hyperswitch-control-center
src/hooks/ToastState.res
.res
type toastType = | ToastError | ToastWarning | ToastInfo | ToastSuccess type toastProps = { toastKey: string, message: string, toastType: toastType, autoClose: bool, toastDuration: int, buttonText?: string, helpLink?: string, toastElement: React.element, } let randomString = (length, chars) => { Array.make(~length, 0)->Array.reduce("", (acc, _) => { let charIndex = Math.Int.random(0, chars->String.length) let newChar = chars->String.charAt(charIndex) acc ++ newChar }) } let makeToastProps = ( ~message, ~toastType, ~autoClose=false, ~toastDuration=0, ~buttonText=?, ~helpLink=?, ~toastElement=React.null, ) => { let rString = randomString(32, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") { toastKey: rString, message, toastType, autoClose, toastDuration, ?buttonText, ?helpLink, toastElement, } } let defaultOpenToasts: array<toastProps> = [] let openToasts = Recoil.atom("openToasts", defaultOpenToasts) type showToastFn = ( ~message: string, ~toastType: toastType, ~toastDuration: int=?, ~autoClose: bool=?, ~buttonText: string=?, ~helpLink: string=?, ~toastElement: React.element=?, ) => unit let useShowToast = (): showToastFn => { let setOpenToasts = Recoil.useSetRecoilState(openToasts) React.useMemo1(() => { ( ~message, ~toastType: toastType, ~toastDuration=0, ~autoClose=false, ~buttonText=?, ~helpLink=?, ~toastElement=React.null, ) => { let toastProps = makeToastProps( ~message, ~toastType, ~toastDuration, ~autoClose, ~buttonText?, ~helpLink?, ~toastElement, ) setOpenToasts(prevArr => prevArr->Array.concat([toastProps])) } }, [setOpenToasts]) }
514
10,180
hyperswitch-control-center
src/hooks/AuthHooks.res
.res
type contentType = Headers(string) | Unknown let headersForXFeature = (~uri, ~headers) => { if ( uri->String.includes("lottie-files") || uri->String.includes("config/merchant") || uri->String.includes("config/feature") ) { headers->Dict.set("Content-Type", `application/json`) } else { headers->Dict.set("x-feature", "integ-custom") } } let getHeaders = ( ~uri, ~headers, ~contentType=Headers("application/json"), ~xFeatureRoute, ~token, ~merchantId, ~profileId, ~version: UserInfoTypes.version, ) => { let isMixpanel = uri->String.includes("mixpanel") let headerObj = if isMixpanel { [ ("Content-Type", "application/x-www-form-urlencoded"), ("accept", "application/json"), ]->Dict.fromArray } else { switch (token, version) { | (Some(str), V1) => { headers->Dict.set("authorization", `Bearer ${str}`) headers->Dict.set("api-key", `hyperswitch`) } | (Some(str), V2) => headers->Dict.set("authorization", `Bearer ${str}`) | _ => () } switch contentType { | Headers(headerString) => headers->Dict.set("Content-Type", headerString) | Unknown => () } if xFeatureRoute { headersForXFeature(~headers, ~uri) } // this header is specific to Intelligent Routing (Dynamic Routing) if uri->String.includes("simulate") { headers->Dict.set("x-feature", "dynamo-simulator") } // headers for V2 headers->Dict.set("X-Profile-Id", profileId) headers->Dict.set("X-Merchant-Id", merchantId) headers } Fetch.HeadersInit.make(headerObj->Identity.dictOfAnyTypeToObj) } type betaEndpoint = { betaApiStr: string, originalApiStr: string, replaceStr: string, } let useApiFetcher = () => { open Promise let {authStatus, setAuthStateToLogout} = React.useContext(AuthInfoProvider.authStatusContext) let setReqProgress = Recoil.useSetRecoilState(ApiProgressHooks.pendingRequestCount) React.useCallback( ( uri, ~bodyStr: string="", ~bodyFormData=None, ~headers=Dict.make(), ~method_: Fetch.requestMethod, ~betaEndpointConfig=?, ~contentType=Headers("application/json"), ~xFeatureRoute, ~forceCookies, ~merchantId="", ~profileId="", ~version=UserInfoTypes.V1, ) => { let token = { switch authStatus { | PreLogin(info) => info.token | LoggedIn(info) => switch info { | Auth(_) => AuthUtils.getUserInfoDetailsFromLocalStorage().token } | _ => None } } let uri = switch betaEndpointConfig { | Some(val) => String.replace(uri, val.replaceStr, val.originalApiStr) | None => uri } let body = switch method_ { | Get => resolve(None) | _ => switch bodyFormData { | Some(formDataVal) => resolve(Some(Fetch.BodyInit.makeWithFormData(formDataVal))) | None => resolve(Some(Fetch.BodyInit.make(bodyStr))) } } body->then(body => { setReqProgress(p => p + 1) Fetch.fetchWithInit( uri, Fetch.RequestInit.make( ~method_, ~body?, ~credentials={forceCookies ? SameOrigin : Omit}, ~headers=getHeaders( ~headers, ~uri, ~contentType, ~token, ~xFeatureRoute, ~merchantId, ~profileId, ~version, ), ), ) ->catch( err => { setReqProgress(p => p - 1) reject(err) }, ) ->then( resp => { setReqProgress(p => p - 1) if resp->Fetch.Response.status === 401 { switch authStatus { | LoggedIn(_) => LocalStorage.clear() setAuthStateToLogout() AuthUtils.redirectToLogin() resolve(resp) | _ => resolve(resp) } } else { resolve(resp) } }, ) }) }, [], ) }
983
10,181
hyperswitch-control-center
src/hooks/ModalsState.res
.res
type hideModalFn = unit => unit type modalProps = { title: string, getContent: hideModalFn => React.element, closeOnClickOutside: bool, } let defaultOpenModals: array<modalProps> = [] let openModals = Recoil.atom("openModals", defaultOpenModals)
68
10,182
hyperswitch-control-center
src/hooks/TimeZoneHook.res
.res
type dateTimeString = { year: string, month: string, date: string, hour: string, minute: string, second: string, } type dateTimeFloat = { year: float, month: float, date: float, hour: float, minute: float, second: float, } let formatter = str => { let strLen = str->String.length strLen == 0 ? "00" : strLen == 1 ? `0${str}` : str } let dateTimeObjectToDate = (dateTimeObject: dateTimeFloat) => { Js.Date.makeWithYMDHMS( ~year=dateTimeObject.year, ~month=dateTimeObject.month -. 1.0, ~date=dateTimeObject.date, ~hours=dateTimeObject.hour, ~minutes=dateTimeObject.minute, ~seconds=dateTimeObject.second, (), ) } let stringToFloat = element => { switch Float.fromString(element) { | Some(a) => a | _ => 0.0 } } let dateTimeStringToDateTimeFloat = (dateTime: dateTimeString) => { { year: dateTime.year->stringToFloat, month: dateTime.month->stringToFloat, date: dateTime.date->stringToFloat, hour: dateTime.hour->stringToFloat, minute: dateTime.minute->stringToFloat, second: dateTime.second->stringToFloat, } } let formattedDateTimeFloat = (dateTime: dateTimeFloat, format: string) => { (dateTime->dateTimeObjectToDate->Date.toString->DayJs.getDayJsForString).format(format) } let formattedDateTimeString = (dateTime: dateTimeString, format: string) => { formattedDateTimeFloat(dateTime->dateTimeStringToDateTimeFloat, format) } let formattedISOString = (dateTimeIsoString: string, format: string) => { // 2021-08-29T18:30:00.000Z let tempTimeDateString = dateTimeIsoString->String.replace("Z", "") let tempTimeDate = tempTimeDateString->String.split("T") let time = tempTimeDate[1] let date = tempTimeDate[0] let dateComponents = date->Option.getOr("")->String.split("-") let timeComponents = time->Option.getOr("")->String.split(":") let dateTimeObject: dateTimeFloat = { year: dateComponents[0]->Option.getOr("")->stringToFloat, month: dateComponents[1]->Option.getOr("")->stringToFloat, date: dateComponents[2]->Option.getOr("")->stringToFloat, hour: timeComponents[0]->Option.getOr("")->stringToFloat, minute: timeComponents[1]->Option.getOr("")->stringToFloat, second: timeComponents[2]->Option.getOr("")->stringToFloat, } formattedDateTimeFloat(dateTimeObject, format) } let en_USStringToDateTimeObject = dateTimeIsoString => { let tempTimeDateString = dateTimeIsoString->String.replace(",", "") let tempTimeDate = tempTimeDateString->Js.String2.splitByRe(%re("/\s/"))->Array.map(val => val->Option.getOr("")) let time = tempTimeDate[1] let date = tempTimeDate[0] let dateComponents = date->Option.getOr("")->String.split("/") let timeComponents = time->Option.getOr("")->String.split(":") let tempHour = switch Float.fromString(timeComponents[0]->Option.getOr("")) { | Some(a) => a | _ => 0.0 } let fullTempHour = tempTimeDate[2]->Option.getOr("") === "AM" ? tempHour === 12.0 ? 0.0 : tempHour : tempHour < 12.0 ? tempHour +. 12.0 : tempHour let hourInString = Float.toString(fullTempHour) let dateTimeObject: dateTimeString = { year: formatter(dateComponents[2]->Option.getOr("")), month: formatter(dateComponents[0]->Option.getOr("")), date: formatter(dateComponents[1]->Option.getOr("")), hour: formatter(hourInString), minute: formatter(timeComponents[1]->Option.getOr("")), second: formatter(timeComponents[2]->Option.getOr("")), } dateTimeObject } type timeZoneObject = {timeZone: string} @send external toLocaleString: (Date.t, string, timeZoneObject) => string = "toLocaleString" let convertTimeZone = (date, timezoneString) => { let localTimeString = Date.fromString(date) localTimeString ->toLocaleString("en-US", {timeZone: timezoneString}) ->String.replaceRegExp(%re("/\s/g"), " ") } let useCustomTimeZoneToIsoString = () => { let (zone, _setZone) = React.useContext(UserTimeZoneProvider.userTimeContext) let customTimezoneToISOString = React.useCallback((year, month, day, hours, minutes, seconds) => { let selectedTimeZoneData = TimeZoneData.getTimeZoneData(zone) let timeZoneData = selectedTimeZoneData let timezone = timeZoneData.offset let monthString = String.length(month) == 1 ? `0${month}` : month let dayString = String.length(day) == 1 ? `0${day}` : day let hoursString = formatter(hours) let minutesString = formatter(minutes) let secondsString = formatter(seconds) let fullTimeManagedString = year ++ "-" ++ monthString ++ "-" ++ dayString ++ "T" ++ hoursString ++ ":" ++ minutesString ++ ":" ++ secondsString ++ timezone let newFormedDate = Date.fromString(fullTimeManagedString) let isoFormattedDate = Date.toISOString(newFormedDate) isoFormattedDate }, [zone]) customTimezoneToISOString } let useIsoStringToCustomTimeZone = () => { let (zone, _setZone) = React.useContext(UserTimeZoneProvider.userTimeContext) let isoStringToCustomTimezone = React.useCallback(isoString => { let selectedTimeZoneData = TimeZoneData.getTimeZoneData(zone) let selectedTimeZoneAlias = selectedTimeZoneData.region let timezoneConvertedString = convertTimeZone(isoString, selectedTimeZoneAlias) let customDateTime: dateTimeString = en_USStringToDateTimeObject(timezoneConvertedString) customDateTime }, [zone]) isoStringToCustomTimezone } let useIsoStringToCustomTimeZoneInFloat = () => { let (zone, _setZone) = React.useContext(UserTimeZoneProvider.userTimeContext) let isoStringToCustomTimezoneInFloat = React.useCallback(isoString => { let selectedTimeZoneData = TimeZoneData.getTimeZoneData(zone) let selectedTimeZoneAlias = selectedTimeZoneData.region let timezoneConvertedString = convertTimeZone(isoString, selectedTimeZoneAlias) let customDateTimeString: dateTimeString = en_USStringToDateTimeObject(timezoneConvertedString) let customDateTime = dateTimeStringToDateTimeFloat(customDateTimeString) customDateTime }, [zone]) isoStringToCustomTimezoneInFloat }
1,567
10,183
hyperswitch-control-center
src/Recoils/TableAtoms.res
.res
let historyDefaultCols = Recoil.atom("hyperSwitchHistoryDefaultCols", HistoryEntity.defaultColumns) let refundsMapDefaultCols = Recoil.atom("refundsMapDefaultCols", RefundEntity.defaultColumns) let payoutsMapDefaultCols = Recoil.atom("payoutsMapDefaultCols", PayoutsEntity.defaultColumns) let ordersMapDefaultCols = Recoil.atom("ordersMapDefaultCols", OrderEntity.defaultColumns) let disputesMapDefaultCols = Recoil.atom("disputesMapDefaultCols", DisputesEntity.defaultColumns) let apiDefaultCols = Recoil.atom("hyperSwitchApiDefaultCols", DeveloperUtils.defaultColumns) let customersMapDefaultCols = Recoil.atom("customersMapDefaultCols", CustomersEntity.defaultColumns) let revenueRecoveryMapDefaultCols = Recoil.atom( "revenueRecoveryMapDefaultCols", RevenueRecoveryEntity.defaultColumns, ) let reconReportsDefaultCols = Recoil.atom( "reconReportsDefaultCols", ReportsTableEntity.defaultColumns, ) let reconExceptionReportsDefaultCols = Recoil.atom( "reconExceptionReportsDefaultCols", ReportsExceptionTableEntity.defaultColumns, )
236
10,184
hyperswitch-control-center
src/Recoils/HyperswitchAtom.res
.res
type accessMapping = { groups: Map.t<UserManagementTypes.groupAccessType, CommonAuthTypes.authorization>, resources: Map.t<UserManagementTypes.resourceAccessType, CommonAuthTypes.authorization>, } let ompDefaultValue: OMPSwitchTypes.ompListTypes = {id: "", name: ""} let merchantDetailsValueAtom: Recoil.recoilAtom<HSwitchSettingTypes.merchantPayload> = Recoil.atom( "merchantDetailsValue", JSON.Encode.null->MerchantAccountDetailsMapper.getMerchantDetails, ) let businessProfilesAtom = Recoil.atom( "businessProfileDetails", JSON.Encode.null->BusinessProfileMapper.getArrayOfBusinessProfile, ) let connectorListAtom: Recoil.recoilAtom<JSON.t> = Recoil.atom( "connectorListAtom", JSON.Encode.null, ) let enumVariantAtom = Recoil.atom("enumVariantDetails", "") let featureFlagAtom: Recoil.recoilAtom<FeatureFlagUtils.featureFlag> = Recoil.atom( "featureFlag", JSON.Encode.null->FeatureFlagUtils.featureFlagType, ) let merchantSpecificConfigAtom: Recoil.recoilAtom< FeatureFlagUtils.merchantSpecificConfig, > = Recoil.atom("merchantSpecificConfig", JSON.Encode.null->FeatureFlagUtils.merchantSpecificConfig) let paypalAccountStatusAtom: Recoil.recoilAtom<PayPalFlowTypes.setupAccountStatus> = Recoil.atom( "paypalAccountStatusAtom", PayPalFlowTypes.Connect_paypal_landing, ) // TODO: remove this after userGroupPermissionsAtom is stable let userPermissionAtom: Recoil.recoilAtom<UserManagementTypes.groupAccessJsonType> = Recoil.atom( "userPermissionAtom", GroupACLMapper.defaultValueForGroupAccessJson, ) let userGroupACLAtom: Recoil.recoilAtom<option<accessMapping>> = Recoil.atom( "userGroupACLAtom", None, ) let switchMerchantListAtom: Recoil.recoilAtom< array<SwitchMerchantUtils.switchMerchantListResponse>, > = Recoil.atom("switchMerchantListAtom", [SwitchMerchantUtils.defaultValue]) let currentTabNameRecoilAtom = Recoil.atom("currentTabName", "ActiveTab") let globalSeacrchAtom: Recoil.recoilAtom<GlobalSearchTypes.defaultResult> = Recoil.atom( "globalSearch", { GlobalSearchTypes.local_results: [], remote_results: [], searchText: "", }, ) let orgListAtom: Recoil.recoilAtom<array<OMPSwitchTypes.ompListTypes>> = Recoil.atom( "orgListAtom", [ompDefaultValue], ) let merchantListAtom: Recoil.recoilAtom<array<OMPSwitchTypes.ompListTypes>> = Recoil.atom( "merchantListAtom", [ompDefaultValue], ) let profileListAtom: Recoil.recoilAtom<array<OMPSwitchTypes.ompListTypes>> = Recoil.atom( "profileListAtom", [ompDefaultValue], ) let moduleListRecoil: Recoil.recoilAtom<array<UserManagementTypes.userModuleType>> = Recoil.atom( "moduleListRecoil", [], )
651
10,185
hyperswitch-control-center
src/IntelligentRouting/IntelligentRoutingApp/IntelligentRoutingSidebarValues.res
.res
open SidebarTypes let intelligentRoutingHome = { Link({ name: "Configuration", link: `/v2/dynamic-routing`, icon: "nd-overview", access: Access, searchOptions: [("Intelligent Routing home", ""), ("Intelligent Routing configuration", "")], selectedIcon: "nd-overview-fill", }) } let intelligentRoutingSidebars = { [intelligentRoutingHome] }
89
10,186
hyperswitch-control-center
src/IntelligentRouting/IntelligentRoutingApp/IntelligentRoutingApp.res
.res
@react.component let make = () => { let url = RescriptReactRouter.useUrl() { switch url.path->HSwitchUtils.urlPath { | list{"v2", "dynamic-routing"} => <IntelligentRoutingHome /> | list{"v2", "dynamic-routing", "home"} => <IntelligentRoutingConfiguration /> | list{"v2", "dynamic-routing", "dashboard"} => <IntelligentRoutingAnalytics /> | _ => React.null } } }
106
10,187
hyperswitch-control-center
src/IntelligentRouting/IntelligentRoutingScreens/IntelligentRoutingHelper.res
.res
open IntelligentRoutingTypes let defaultTimeRange = {minDate: "", maxDate: ""} let simulatorBanner = <div className="absolute z-10 top-76-px left-0 w-full py-4 px-10 bg-orange-50 flex justify-between items-center"> <div className="flex gap-4 items-center"> <Icon name="nd-information-triangle" size=24 /> <p className="text-nd_gray-600 text-base leading-6 font-medium"> {"You are in demo environment and this is sample setup."->React.string} </p> </div> </div> let displayLegend = gatewayKeys => { let colors = ["#BCBD22", "#CB80DC", "#72BEF4", "#7856FF", "#4B6D8C"] let legendColor = index => colors->Array.get(index)->Option.getOr("") gatewayKeys->Array.mapWithIndex((key, index) => { <div className="flex gap-1 items-center" key={key}> <div className="w-3 h-3 rounded-sm" style={ReactDOM.Style.make(~backgroundColor=legendColor(index), ())} /> <p className="text-grey-100 font-normal leading-3 !text-fs-13 text-nowrap"> {key->React.string} </p> </div> }) } let stepperHeading = (~title: string, ~subTitle: string) => <div className="flex flex-col gap-y-1"> <p className="text-2xl font-semibold text-nd_gray-700 leading-9"> {title->React.string} </p> <p className="text-sm text-nd_gray-400 font-medium leading-5"> {subTitle->React.string} </p> </div> let displayDateRange = (~minDate, ~maxDate) => { let getDateObj = value => value->DayJs.getDayJsForString let date = value => { NewAnalyticsUtils.formatDateValue(value, ~includeYear=true) } let time = value => { let dateObj = getDateObj(value) dateObj.format("HH:mm")->NewAnalyticsUtils.formatTime } let diff = DateRangeUtils.getStartEndDiff(minDate, maxDate) if date(minDate) == date(maxDate) { `${time(minDate)} - ${time(maxDate)} ${date(minDate)}` } else if diff < (2->Int.toFloat *. 24. *. 60. *. 60. -. 1.) *. 1000. { `${time(minDate)} ${date(minDate)} - ${time(maxDate)} ${date(maxDate)}` } else { `${date(minDate)} - ${date(maxDate)}` } } let getDateTime = value => { let dateObj = value->DayJs.getDayJsForString let _date = `${dateObj.month()->NewAnalyticsUtils.getMonthName} ${dateObj.format("DD")}` let time = dateObj.format("HH:mm")->NewAnalyticsUtils.formatTime `${time}` } let columnGraphOptions = (stats: JSON.t): ColumnGraphTypes.columnGraphPayload => { let statsData = stats->IntelligentRoutingUtils.responseMapper let timeSeriesData = statsData.time_series_data let baseLineData = timeSeriesData->Array.map(item => { let data: ColumnGraphTypes.dataObj = { name: getDateTime(item.time_stamp), y: item.revenue.baseline, color: "#B992DD", } data }) let modelData = timeSeriesData->Array.map(item => { let data: ColumnGraphTypes.dataObj = { name: getDateTime(item.time_stamp), y: item.revenue.model, color: "#1E90FF", } data }) { title: { text: "Revenue Uplift", align: "left", x: 10, y: 10, }, data: [ { showInLegend: true, name: "Without Intelligence", colorByPoint: false, data: baseLineData, color: "#B992DD", }, { showInLegend: true, name: "With Intelligence", colorByPoint: false, data: modelData, color: "#1E90FF", }, ], tooltipFormatter: ColumnGraphUtils.columnGraphTooltipFormatter( ~title="Revenue Uplift", ~metricType=FormattedAmount, ~comparison=Some(EnableComparison), ), yAxisFormatter: ColumnGraphUtils.columnGraphYAxisFormatter( ~statType=AmountWithSuffix, ~currency="$", ~suffix="M", ~scaleFactor=1000000.0, ), } } let lineGraphOptions = (stats: JSON.t, ~isSmallScreen=false): LineGraphTypes.lineGraphPayload => { let statsData = stats->IntelligentRoutingUtils.responseMapper let timeSeriesData = statsData.time_series_data let timeSeriesArray = timeSeriesData->Array.map(item => { getDateTime(item.time_stamp) }) let baselineSuccessRate = timeSeriesData->Array.map(item => item.success_rate.baseline) let modelSuccessRate = timeSeriesData->Array.map(item => item.success_rate.model) let calculateYAxisMinValue = { let dataArray = baselineSuccessRate->Array.copy dataArray->Array.sort((val1, val2) => { val1 <= val2 ? -1. : 1. }) Some(dataArray->Array.get(0)->Option.getOr(0.0)->Float.toInt) } let chartHeight = isSmallScreen ? 600 : 350 { chartHeight: Custom(chartHeight), chartLeftSpacing: Custom(0), title: { text: "Overall Authorization Rate", align: "left", x: 10, y: 10, style: { fontSize: "14px", color: "#525866", fontWeight: "600", }, }, categories: timeSeriesArray, data: [ { showInLegend: true, name: "Without Intelligence", data: baselineSuccessRate, color: "#B992DD", }, { showInLegend: true, name: "With Intelligence", data: modelSuccessRate, color: "#1E90FF", }, ], tooltipFormatter: NewAnalyticsUtils.tooltipFormatter( ~title="Authorization Rate", ~metricType=Rate, ~currency="", ~comparison=Some(EnableComparison), ~secondaryCategories=timeSeriesArray, ~reverse=true, ~suffix="%", ~showNameInTooltip=true, ), yAxisMaxValue: Some(100), yAxisMinValue: calculateYAxisMinValue, yAxisFormatter: LineGraphUtils.lineGraphYAxisFormatter( ~statType=AmountWithSuffix, ~currency="", ~suffix="%", ), legend: { useHTML: true, labelFormatter: LineGraphUtils.valueFormatter, align: "center", verticalAlign: "top", floating: false, margin: 30, }, } } let lineColumnGraphOptions = ( stats, ~timeStamp, ): LineAndColumnGraphTypes.lineColumnGraphPayload => { open LogicUtils let statsData = stats->IntelligentRoutingUtils.responseMapper let timeSeriesData = statsData.time_series_data let gatewayData = switch timeSeriesData->Array.get(0) { | Some(statsData) => statsData.volume_distribution_as_per_sr | None => JSON.Encode.null } let gatewayKeys = gatewayData ->LogicUtils.getDictFromJsonObject ->Dict.keysToArray gatewayKeys->Array.sort((key1, key2) => { key1 <= key2 ? -1. : 1. }) let mapPSPJson = (json): volDist => { let dict = json->getDictFromJsonObject { baseline_volume: dict->getInt("baseline_volume", 0), model_volume: dict->getInt("model_volume", 0), success_rate: dict->getFloat("success_rate", 0.0), } } let data = timeSeriesData ->Array.filter(item => { item.time_stamp == timeStamp }) ->Array.get(0) let baseline = [] let model = [] let successRate = [] switch data { | Some(data) => { let val = data.volume_distribution_as_per_sr let dict = val->getDictFromJsonObject gatewayKeys->Array.forEach(item => { let pspData = dict->Dict.get(item) let data = switch pspData { | Some(pspData) => pspData->mapPSPJson | None => { baseline_volume: 0, model_volume: 0, success_rate: 0.0, } } baseline->Array.push(data.baseline_volume->Int.toFloat) model->Array.push(data.model_volume->Int.toFloat) successRate->Array.push(data.success_rate) }) } | None => () } let style: LineAndColumnGraphTypes.style = { fontFamily: LineAndColumnGraphUtils.fontFamily, color: LineAndColumnGraphUtils.darkGray, fontSize: "14px", } { titleObj: { chartTitle: { text: "Processor Wise Transaction Distribution With Auth Rate", align: "left", x: 10, y: 10, style: { fontSize: "14px", color: "#525866", fontWeight: "600", }, }, xAxisTitle: { text: "", style, }, yAxisTitle: { text: "Transaction Count", style, }, oppositeYAxisTitle: { text: "Authorization Rate", style, }, }, categories: gatewayKeys, data: [ { showInLegend: true, name: "Processor's Auth Rate", \"type": "column", data: successRate, color: "#93AACD", yAxis: 0, }, { showInLegend: true, name: "Without Intelligence Transactions", \"type": "line", data: baseline, color: "#A785D8", yAxis: 1, }, { showInLegend: true, name: "With Intelligence Transactions", \"type": "line", data: model, color: "#4185F4", yAxis: 1, }, ], tooltipFormatter: LineAndColumnGraphUtils.lineColumnGraphTooltipFormatter( ~title="Metrics", ~metricType=Amount, ~currency="", ~showNameInTooltip=true, ), yAxisFormatter: LineAndColumnGraphUtils.lineColumnGraphYAxisFormatter( ~statType=AmountWithSuffix, ~currency="", ~suffix="%", ), minValY2: 0, maxValY2: 100, legend: { useHTML: true, labelFormatter: LineAndColumnGraphUtils.labelFormatter, symbolPadding: -7, symbolWidth: 0, symbolHeight: 0, symbolRadius: 4, align: "center", verticalAlign: "top", floating: false, itemDistance: 30, margin: 30, }, } } let getTypedData = (stats: JSON.t) => { open LogicUtils let statsData = stats->IntelligentRoutingUtils.responseMapper let timeSeriesData = statsData.time_series_data let gatewayData = switch timeSeriesData->Array.get(0) { | Some(statsData) => statsData.volume_distribution_as_per_sr | None => JSON.Encode.null } let gatewayKeys = gatewayData ->LogicUtils.getDictFromJsonObject ->Dict.keysToArray gatewayKeys->Array.sort((key1, key2) => { key1 <= key2 ? -1. : 1. }) let mapPSPJson = (json): volDist => { let dict = json->getDictFromJsonObject { baseline_volume: dict->getInt("baseline_volume", 0), model_volume: dict->getInt("model_volume", 0), success_rate: dict->getFloat("success_rate", 0.0), } } let successData = processor => timeSeriesData->Array.map(item => { let val = item.volume_distribution_as_per_sr let dict = val->getDictFromJsonObject let pspData = dict->Dict.get(processor) let data = switch pspData { | Some(pspData) => pspData->mapPSPJson | None => { baseline_volume: 0, model_volume: 0, success_rate: 0.0, } } data }) successData } let getKeys = (stats: JSON.t) => { let statsData = stats->IntelligentRoutingUtils.responseMapper let timeSeriesData = statsData.time_series_data let gatewayData = switch timeSeriesData->Array.get(0) { | Some(statsData) => statsData.volume_distribution_as_per_sr | None => JSON.Encode.null } let gatewayKeys = gatewayData ->LogicUtils.getDictFromJsonObject ->Dict.keysToArray gatewayKeys->Array.sort((key1, key2) => { key1 <= key2 ? -1. : 1. }) gatewayKeys } let pieGraphOptionsActual = (stats: JSON.t): PieGraphTypes.pieGraphPayload<int> => { let gatewayKeys = getKeys(stats) let successData = getTypedData(stats) let distribution = gatewayKeys->Array.map(processor => successData(processor) ->Array.map(item => { item.baseline_volume }) ->Array.reduce(0, (acc, val) => { acc + val }) ) let colors = ["#D9DA98", "#EAB9F5", "#6BBDF6", "#AC9EE7", "#498FD0"] let data: array<PieGraphTypes.pieGraphDataType> = gatewayKeys->Array.mapWithIndex(( key, index, ) => { let dataObj: PieGraphTypes.pieGraphDataType = { name: key, y: distribution->Array.get(index)->Option.getOr(0)->Int.toFloat, color: colors->Array.get(index)->Option.getOr(""), } dataObj }) let data: PieGraphTypes.pieCartData<int> = [ { \"type": "", name: "", showInLegend: false, data, innerSize: "70%", }, ] { chartSize: "80%", title: { text: "Without Intelligence", }, data, tooltipFormatter: PieGraphUtils.pieGraphTooltipFormatter( ~title="Transactions", ~valueFormatterType=Amount, ), legendFormatter: PieGraphUtils.pieGraphLegendFormatter(), startAngle: 0, endAngle: 360, legend: { enabled: false, }, } } let pieGraphOptionsSimulated = (stats: JSON.t): PieGraphTypes.pieGraphPayload<int> => { let gatewayKeys = getKeys(stats) let successData = getTypedData(stats) let distribution = gatewayKeys->Array.map(processor => successData(processor) ->Array.map(item => item.model_volume) ->Array.reduce(0, (acc, val) => { acc + val }) ) let colors = ["#D9DA98", "#EAB9F5", "#6BBDF6", "#AC9EE7", "#498FD0"] let data: array<PieGraphTypes.pieGraphDataType> = gatewayKeys->Array.mapWithIndex(( key, index, ) => { let dataObj: PieGraphTypes.pieGraphDataType = { name: key, y: distribution->Array.get(index)->Option.getOr(0)->Int.toFloat, color: colors->Array.get(index)->Option.getOr(""), } dataObj }) let data: PieGraphTypes.pieCartData<int> = [ { \"type": "", name: "", showInLegend: false, data, innerSize: "70%", }, ] { chartSize: "80%", title: { text: "With Intelligence", }, data, tooltipFormatter: PieGraphUtils.pieGraphTooltipFormatter( ~title="Transactions", ~valueFormatterType=Amount, ), legendFormatter: PieGraphUtils.pieGraphLegendFormatter(), startAngle: 0, endAngle: 360, legend: { enabled: false, }, } } let columnGraphOptionsAuthRate = (stats: JSON.t): ColumnGraphTypes.columnGraphPayload => { let statsData = stats->IntelligentRoutingUtils.responseMapper let timeSeriesData = statsData.time_series_data let colors = ["#CFB430", "#D9A3E6", "#97CFF7", "#A18AFF", "#4B6C8B"] let baseLineData = timeSeriesData->Array.mapWithIndex((item, index) => { let data: ColumnGraphTypes.dataObj = { name: getDateTime(item.time_stamp), y: item.revenue.baseline, color: colors->Array.get(index)->Option.getOr(""), } data }) { title: { text: "Auth Rate based on Acquirers", align: "left", x: 10, y: 10, }, data: [ { showInLegend: false, name: "Actual", colorByPoint: false, data: baseLineData, color: "#B992DD", }, ], tooltipFormatter: ColumnGraphUtils.columnGraphTooltipFormatter( ~title="Revenue Uplift", ~metricType=FormattedAmount, ~comparison=Some(EnableComparison), ), yAxisFormatter: ColumnGraphUtils.columnGraphYAxisFormatter( ~statType=AmountWithSuffix, ~currency="$", ~suffix="M", ~scaleFactor=1000000.0, ), } }
4,137
10,188
hyperswitch-control-center
src/IntelligentRouting/IntelligentRoutingScreens/IntelligentRoutingReviewFieldsEntity.res
.res
open IntelligentRoutingTypes open LogicUtils let defaultColumns = [FileName, TotalAmount, NumberOfTransaction, Processors, PaymentMethodTypes] let allColumns = [FileName, TotalAmount, NumberOfTransaction, Processors, PaymentMethodTypes] let getHeading = colType => { switch colType { | NumberOfTransaction => Table.makeHeaderInfo(~key="total", ~title="Number of Transactions") | TotalAmount => Table.makeHeaderInfo(~key="total_amount", ~title="Total Amount") | FileName => Table.makeHeaderInfo(~key="file_name", ~title="File Name") | Processors => Table.makeHeaderInfo(~key="processors", ~title="Processors") | PaymentMethodTypes => Table.makeHeaderInfo(~key="payment_method_types", ~title="Payment Method Types") } } let concatStringArray = arr => { arr->Array.map(s => s->String.trim)->Array.joinWith(", ") } let getCell = (reviewFields, colType): Table.cell => { switch colType { | NumberOfTransaction => Text(reviewFields.total->Int.toString) | TotalAmount => Text(formatAmount(reviewFields.total_amount, "USD")) | FileName => Text(reviewFields.file_name) | Processors => Text(concatStringArray(reviewFields.processors)) | PaymentMethodTypes => Text(concatStringArray(reviewFields.payment_method_types->Array.map(LogicUtils.getTitle))) } } let itemToObjMapper = dict => { { total: dict->getInt("total", 0), total_amount: dict->getInt("total_amount", 0), file_name: dict->getString("file_name", ""), processors: dict->getStrArray("processors"), payment_method_types: dict->getStrArray("payment_method_types"), } } let getReviewFields: JSON.t => reviewFields = json => { json->getDictFromJsonObject->itemToObjMapper }
404
10,189
hyperswitch-control-center
src/IntelligentRouting/IntelligentRoutingScreens/IntelligentRoutingTransactionsEntity.res
.res
open LogicUtils open IntelligentRoutingTypes type cols = | PaymentID | PaymentMethodType | TxnAmount | Status | CardNetwork | ActualGateway | SuggestedGateway | SuccessRateUplift | CreatedAt let defaultColumns = [ PaymentID, PaymentMethodType, CardNetwork, TxnAmount, Status, ActualGateway, SuggestedGateway, SuccessRateUplift, CreatedAt, ] let getHeading = colType => { switch colType { | PaymentID => Table.makeHeaderInfo(~key="txn_no", ~title="Payment ID") | PaymentMethodType => Table.makeHeaderInfo(~key="payment_method_type", ~title="Payment Method Type") | CardNetwork => Table.makeHeaderInfo(~key="card_network", ~title="Card Network") | TxnAmount => Table.makeHeaderInfo(~key="tax_amount", ~title="Txn Amount ($)") | Status => Table.makeHeaderInfo(~key="payment_status", ~title="Status") | ActualGateway => Table.makeHeaderInfo(~key="payment_gateway", ~title="Actual Gateway") | SuggestedGateway => Table.makeHeaderInfo(~key="model_connector", ~title="Suggested Gateway") | SuccessRateUplift => Table.makeHeaderInfo(~key="suggested_uplift", ~title="Auth Rate Uplift") | CreatedAt => Table.makeHeaderInfo(~key="last_updated", ~title="Timestamp") } } module CurrencyCell = { @react.component let make = (~amount, ~currency) => { <p className="whitespace-nowrap"> {`${amount} ${currency}`->React.string} </p> } } module UpliftCell = { @react.component let make = (~uplift: float) => { let upliftClass = uplift > 0.0 ? "text-green-500" : "" let icon = uplift > 0.0 ? "nd-arrow-up-no-underline" : "" let upliftAmount = uplift > 0.0 ? uplift->Float.toString : "-" <div className={`flex gap-1 ${upliftClass}`}> <Icon name={icon} size=10 /> <p> {upliftAmount->React.string} </p> <RenderIf condition={uplift > 0.0}> <Icon name="percent" size=10 /> </RenderIf> </div> } } let getCell = (~transactionsData: transactionObj, colType): Table.cell => { switch colType { | PaymentID => CustomCell( <HelperComponents.EllipsisText displayValue={transactionsData.payment_attempt_id} />, "", ) | PaymentMethodType => Text(transactionsData.payment_method_type->LogicUtils.getTitle) | CardNetwork => Text(transactionsData.card_network) | TxnAmount => Text(transactionsData.amount->Float.toString) | Status => Label({ title: transactionsData.payment_status ? "Success" : "Failed", color: transactionsData.payment_status ? LabelGreen : LabelRed, }) | ActualGateway => Text(transactionsData.payment_gateway) | SuggestedGateway => Text(transactionsData.model_connector) | SuccessRateUplift => CustomCell(<UpliftCell uplift=transactionsData.suggested_uplift />, "") | CreatedAt => DateWithCustomDateStyle(transactionsData.created_at, "MMM DD, YYYY hh:mm:ss A") } } let itemToObjectMapper = dict => { { txn_no: dict->getInt("txn_no", 0), payment_intent_id: dict->getString("payment_intent_id", ""), payment_attempt_id: dict->getString("payment_attempt_id", ""), amount: dict->getFloat("amount", 0.0), payment_gateway: dict->getString("payment_gateway", ""), payment_status: dict->getBool("payment_status", false), card_network: dict->getString("card_network", ""), payment_method_type: dict->getString("payment_method_type", ""), order_currency: dict->getString("order_currency", ""), model_connector: dict->getString("model_connector", ""), suggested_uplift: dict->getFloat("suggested_uplift", 0.0), created_at: dict->getString("created_at", ""), } } let getTransactionsData: JSON.t => array<transactionObj> = json => { let dict = json->getDictFromJsonObject let simulatorOutcome = dict->getArrayFromDict("simulation_outcome_of_each_txn", []) getArrayDataFromJson(simulatorOutcome->JSON.Encode.array, itemToObjectMapper) } let transactionDetailsEntity = () => { EntityType.makeEntity( ~uri=``, ~getObjects=getTransactionsData, ~defaultColumns, ~getHeading, ~getCell=(transactionDetails, cols) => getCell(~transactionsData=transactionDetails, cols), ~dataKey="", ) }
1,069
10,190
hyperswitch-control-center
src/IntelligentRouting/IntelligentRoutingScreens/IntelligentRoutingStatsResponse.res
.res
let response = { "overall_success_rate": { "baseline": 90.32, "model": 99.96, }, "total_failed_payments": { "baseline": 2904, "model": 12, }, "total_revenue": { "baseline": 8359285.0, "model": 9621580.0, }, "faar": { "baseline": 94.31, "model": 99.94, }, "time_series_data": [ { "time_stamp": "2025-03-05 16:29:18", "success_rate": { "baseline": 80.55, "model": 99.9, }, "revenue": { "baseline": 1515323.0, "model": 2021657.0, }, "volume_distribution_as_per_sr": { "PSP9": { "success_rate": 0.7924528301886793, "baseline_volume": 106, "model_volume": 4, }, "PSP11": { "success_rate": 0.7530864197530864, "baseline_volume": 81, "model_volume": 0, }, "PSP8": { "success_rate": 0.9814814814814815, "baseline_volume": 108, "model_volume": 7, }, "PSP6": { "success_rate": 0.6956521739130435, "baseline_volume": 253, "model_volume": 2, }, "PSP3": { "success_rate": 0.6276703967446592, "baseline_volume": 983, "model_volume": 0, }, "PSP7": { "success_rate": 0.49795918367346936, "baseline_volume": 245, "model_volume": 0, }, "PSP1": { "success_rate": 1.0, "baseline_volume": 1260, "model_volume": 5977, }, "PSP10": { "success_rate": 0.4205607476635514, "baseline_volume": 107, "model_volume": 0, }, "PSP5": { "success_rate": 0.8643617021276596, "baseline_volume": 376, "model_volume": 2, }, "PSP2": { "success_rate": 0.9208899876390606, "baseline_volume": 809, "model_volume": 6, }, "PSP12": { "success_rate": 0.8514739229024944, "baseline_volume": 882, "model_volume": 2, }, "PSP4": { "success_rate": 0.6848101265822785, "baseline_volume": 790, "model_volume": 0, }, }, }, { "time_stamp": "2025-03-05 16:23:43", "success_rate": { "baseline": 85.03, "model": 99.92, }, "revenue": { "baseline": 3167516.0, "model": 3942100.0, }, "volume_distribution_as_per_sr": { "PSP10": { "success_rate": 0.9054054054054054, "baseline_volume": 74, "model_volume": 0, }, "PSP12": { "success_rate": 0.9091940976163451, "baseline_volume": 881, "model_volume": 1, }, "PSP1": { "success_rate": 1.0, "baseline_volume": 1525, "model_volume": 5980, }, "PSP2": { "success_rate": 0.9168490153172867, "baseline_volume": 914, "model_volume": 8, }, "PSP3": { "success_rate": 0.7712264150943396, "baseline_volume": 848, "model_volume": 0, }, "PSP5": { "success_rate": 0.9251497005988024, "baseline_volume": 334, "model_volume": 2, }, "PSP9": { "success_rate": 0.9120879120879121, "baseline_volume": 91, "model_volume": 4, }, "PSP4": { "success_rate": 0.7723156532988357, "baseline_volume": 773, "model_volume": 0, }, "PSP6": { "success_rate": 0.834061135371179, "baseline_volume": 229, "model_volume": 1, }, "PSP8": { "success_rate": 0.9669421487603306, "baseline_volume": 121, "model_volume": 4, }, "PSP7": { "success_rate": 0.8757763975155279, "baseline_volume": 161, "model_volume": 0, }, "PSP11": { "success_rate": 0.9591836734693877, "baseline_volume": 49, "model_volume": 0, }, }, }, { "time_stamp": "2025-03-05 16:28:22", "success_rate": { "baseline": 87.62, "model": 99.94, }, "revenue": { "baseline": 4853730.0, "model": 5812116.0, }, "volume_distribution_as_per_sr": { "PSP8": { "success_rate": 0.9736842105263158, "baseline_volume": 114, "model_volume": 7, }, "PSP4": { "success_rate": 0.8131241084165478, "baseline_volume": 701, "model_volume": 0, }, "PSP11": { "success_rate": 0.9655172413793104, "baseline_volume": 58, "model_volume": 0, }, "PSP3": { "success_rate": 0.8548812664907651, "baseline_volume": 758, "model_volume": 0, }, "PSP7": { "success_rate": 0.900709219858156, "baseline_volume": 141, "model_volume": 0, }, "PSP10": { "success_rate": 0.9552238805970149, "baseline_volume": 67, "model_volume": 0, }, "PSP12": { "success_rate": 0.9318681318681319, "baseline_volume": 910, "model_volume": 3, }, "PSP6": { "success_rate": 0.8837209302325582, "baseline_volume": 215, "model_volume": 2, }, "PSP9": { "success_rate": 0.8157894736842105, "baseline_volume": 76, "model_volume": 4, }, "PSP2": { "success_rate": 0.9401129943502825, "baseline_volume": 885, "model_volume": 3, }, "PSP5": { "success_rate": 0.9529780564263323, "baseline_volume": 319, "model_volume": 6, }, "PSP1": { "success_rate": 1.0, "baseline_volume": 1756, "model_volume": 5975, }, }, }, { "time_stamp": "2025-03-05 16:36:33", "success_rate": { "baseline": 89.16, "model": 99.96, }, "revenue": { "baseline": 6544454.0, "model": 7673448.0, }, "volume_distribution_as_per_sr": { "PSP10": { "success_rate": 0.9523809523809523, "baseline_volume": 63, "model_volume": 0, }, "PSP12": { "success_rate": 0.9310722100656456, "baseline_volume": 914, "model_volume": 2, }, "PSP8": { "success_rate": 0.9897959183673469, "baseline_volume": 98, "model_volume": 6, }, "PSP2": { "success_rate": 0.9357429718875502, "baseline_volume": 996, "model_volume": 9, }, "PSP9": { "success_rate": 0.8131868131868132, "baseline_volume": 91, "model_volume": 2, }, "PSP1": { "success_rate": 1.0, "baseline_volume": 1677, "model_volume": 5978, }, "PSP3": { "success_rate": 0.8941176470588236, "baseline_volume": 765, "model_volume": 0, }, "PSP4": { "success_rate": 0.8480243161094225, "baseline_volume": 658, "model_volume": 0, }, "PSP5": { "success_rate": 0.9534883720930233, "baseline_volume": 344, "model_volume": 2, }, "PSP7": { "success_rate": 0.9202898550724637, "baseline_volume": 138, "model_volume": 0, }, "PSP11": { "success_rate": 0.9259259259259259, "baseline_volume": 54, "model_volume": 0, }, "PSP6": { "success_rate": 0.9356435643564357, "baseline_volume": 202, "model_volume": 1, }, }, }, { "time_stamp": "2025-03-05 16:26:24", "success_rate": { "baseline": 90.32, "model": 99.96, }, "revenue": { "baseline": 8359285.0, "model": 9621580.0, }, "volume_distribution_as_per_sr": { "PSP6": { "success_rate": 0.9558823529411765, "baseline_volume": 204, "model_volume": 2, }, "PSP4": { "success_rate": 0.8671532846715329, "baseline_volume": 685, "model_volume": 0, }, "PSP8": { "success_rate": 1.0, "baseline_volume": 107, "model_volume": 4, }, "PSP12": { "success_rate": 0.9374358974358974, "baseline_volume": 975, "model_volume": 2, }, "PSP2": { "success_rate": 0.9378947368421052, "baseline_volume": 950, "model_volume": 4, }, "PSP10": { "success_rate": 0.9871794871794872, "baseline_volume": 78, "model_volume": 0, }, "PSP11": { "success_rate": 0.9615384615384616, "baseline_volume": 52, "model_volume": 0, }, "PSP5": { "success_rate": 0.9501466275659824, "baseline_volume": 341, "model_volume": 5, }, "PSP1": { "success_rate": 1.0, "baseline_volume": 1646, "model_volume": 5979, }, "PSP9": { "success_rate": 0.8924731182795699, "baseline_volume": 93, "model_volume": 4, }, "PSP3": { "success_rate": 0.9267605633802817, "baseline_volume": 710, "model_volume": 0, }, "PSP7": { "success_rate": 1.0, "baseline_volume": 159, "model_volume": 0, }, }, }, ], "overall_success_rate_improvement": 10.67, }->Identity.genericTypeToJson
3,741
10,191
hyperswitch-control-center
src/IntelligentRouting/IntelligentRoutingScreens/IntelligentRoutingAnalytics.res
.res
module GetProductionAccess = { @react.component let make = () => { let mixpanelEvent = MixpanelHook.useSendEvent() let {isProdIntentCompleted, setShowProdIntentForm} = React.useContext( GlobalProvider.defaultContext, ) let isProdIntent = isProdIntentCompleted->Option.getOr(false) let productionAccessString = isProdIntent ? "Production Access Requested" : "Get Production Access" switch isProdIntentCompleted { | Some(_) => <Button text=productionAccessString buttonType=Primary buttonSize=Medium buttonState=Normal onClick={_ => { if !isProdIntent { setShowProdIntentForm(_ => true) mixpanelEvent(~eventName="intelligent_routing_get_production_access") } }} /> | None => <Shimmer styleClass="h-10 px-4 py-3 m-2 ml-2 mb-3 dark:bg-black bg-white rounded" shimmerType={Small} /> } } } module TransactionsTable = { @react.component let make = (~setTimeRange) => { open APIUtils open LogicUtils open IntelligentRoutingTypes let getURL = useGetURL() let fetchDetails = useGetMethod() let showToast = ToastState.useShowToast() let (tableData, setTableData) = React.useState(() => []) let (offset, setOffset) = React.useState(() => 0) let (totalCount, setTotalCount) = React.useState(_ => 0) let (tabIndex, setTabIndex) = React.useState(_ => 0) let (screenState, setScreenState) = React.useState(() => PageLoaderWrapper.Loading) let limit = 50 let fetchTableData = async () => { try { setScreenState(_ => PageLoaderWrapper.Loading) let url = getURL( ~entityName=V1(INTELLIGENT_ROUTING_RECORDS), ~methodType=Get, ~queryParamerters=Some(`limit=${limit->Int.toString}&offset=${offset->Int.toString}`), ) let res = await fetchDetails(url) let total = res->getDictFromJsonObject->getInt("total_payment_count", 0) let arr = res->getDictFromJsonObject->getArrayFromDict("simulation_outcome_of_each_txn", []) let data = arr ->JSON.Encode.array ->getArrayDataFromJson(IntelligentRoutingTransactionsEntity.itemToObjectMapper) data->Array.sort((t1, t2) => { let t1 = t1.created_at let t2 = t2.created_at t1 <= t2 ? -1. : 1. }) let minDate = switch data->Array.get(0) { | Some(txn) => txn.created_at | None => "" } let _maxDate = switch data->Array.get(data->Array.length - 1) { | Some(txn) => txn.created_at | None => "" } setTimeRange(prev => {...prev, minDate}) if total <= offset { setOffset(_ => 0) } if total > 0 { let dataDictArr = arr->Belt.Array.keepMap(JSON.Decode.object) let arr = Array.make(~length=offset, Dict.make()) let txnData = arr ->Array.concat(dataDictArr) ->Array.map(IntelligentRoutingTransactionsEntity.itemToObjectMapper) let list = txnData->Array.map(Nullable.make) setTotalCount(_ => total) setTableData(_ => list) } setScreenState(_ => PageLoaderWrapper.Success) } catch { | _ => { setScreenState(_ => PageLoaderWrapper.Loading) showToast(~message="Failed to fetch transaction details", ~toastType=ToastError) } } } React.useEffect(() => { fetchTableData()->ignore None }, [offset]) let table = data => <LoadedTable title="Intelligent Routing Transactions" hideTitle=true actualData=data totalResults=totalCount resultsPerPage=10 offset setOffset entity={IntelligentRoutingTransactionsEntity.transactionDetailsEntity()} currrentFetchCount={data->Array.length} tableheadingClass="h-12" tableHeadingTextClass="!font-normal" nonFrozenTableParentClass="!rounded-lg" loadedTableParentClass="flex flex-col pt-6" showAutoScroll=true /> let failedTxnTableData = tableData->Array.filter(txn => switch txn->Nullable.toOption { | Some(transaction) => transaction.payment_status === false | None => false } ) let tabs: array<Tabs.tab> = React.useMemo(() => { open Tabs [ { title: "All", renderContent: () => {table(tableData)}, }, { title: "Failed", renderContent: () => {table(failedTxnTableData)}, }, ] }, [tableData]) <PageLoaderWrapper screenState={screenState}> <div className="flex flex-col gap-2"> <div className="text-nd_gray-600 font-semibold text-fs-18"> {"Transactions Details"->React.string} </div> <Tabs initialIndex={tabIndex >= 0 ? tabIndex : 0} tabs showBorder=true includeMargin=false defaultClasses="!w-max flex flex-auto flex-row items-center justify-center px-6 font-semibold text-body" onTitleClick={index => { setTabIndex(_ => index) }} selectTabBottomBorderColor="bg-primary" customBottomBorderColor="bg-nd_gray-150" /> </div> </PageLoaderWrapper> } } module Card = { @react.component let make = ( ~title: string, ~actualValue: float, ~simulatedValue: float, ~valueFormat=false, ~statType=LogicUtilsTypes.Default, ~currency="", ~amountFormat=false, ) => { open LogicUtils let displayValue = value => switch (amountFormat, valueFormat) { | (true, false) => value->Float.toInt->formatAmount(currency) | (false, true) => value->valueFormatter(statType, ~currency) | (_, _) => value->valueFormatter(statType, ~currency) } let getPercentageChange = (~primaryValue, ~secondaryValue) => { let (value, direction) = NewAnalyticsUtils.calculatePercentageChange( ~primaryValue, ~secondaryValue, ) let (textColor, icon) = switch direction { | Upward => ("#12B76A", "nd-arrow-up-no-underline") | Downward => ("#F04E42", "nd-arrow-down-no-underline") | No_Change => ("#A0A0A0", "") } <div className={`flex gap-2`}> <Icon name={icon} size=12 /> <p className={textColor}> {value->valueFormatter(Rate)->React.string} </p> </div> } <div className="flex flex-col gap-6 items-start border rounded-xl border-nd_gray-150 p-4"> <div className="w-full flex items-center justify-between"> <p className="text-nd_gray-500 text-md leading-4 font-medium"> {title->React.string} </p> </div> <div className="w-full flex gap-6"> <div className="w-full flex flex-col gap-2 items-start justify-between"> <p className="text-nd_gray-400 text-sm leading-4 font-medium"> {"Without Intelligence"->React.string} </p> <p className="text-nd_gray-500 font-semibold leading-8 text-lg text-nowrap"> {displayValue(actualValue)->React.string} </p> </div> <div className="w-full flex flex-col gap-2 items-start justify-between"> <p className="text-nd_gray-400 text-sm leading-4 font-medium"> {"With Intelligence"->React.string} </p> <div className="flex gap-4"> <p className="text-nd_gray-700 font-semibold leading-8 text-lg text-nowrap"> {displayValue(simulatedValue)->React.string} </p> <div className="flex items-center gap-1 text-green-800 bg-green-200 rounded-md px-2 text-sm leading-1 font-semibold"> {getPercentageChange(~primaryValue=simulatedValue, ~secondaryValue=actualValue)} </div> </div> </div> </div> </div> } } module MetricCards = { @react.component let make = (~data) => { let dataTyped = data->IntelligentRoutingUtils.responseMapper let authorizationRate = dataTyped.overall_success_rate let faar = dataTyped.faar <div className="grid grid-cols-2 gap-6"> <Card title="Authorization Rate" actualValue={authorizationRate.baseline} simulatedValue={authorizationRate.model} valueFormat=true statType=Rate /> <Card title="First Attempt Authorization Rate (FAAR)" actualValue={faar.baseline} simulatedValue={faar.model} valueFormat=true statType=Rate /> </div> } } module Overview = { @react.component let make = (~data) => { <div className="mt-10"> <MetricCards data /> </div> } } @react.component let make = () => { open IntelligentRoutingHelper open APIUtils let getURL = useGetURL() let fetchDetails = useGetMethod() let showToast = ToastState.useShowToast() let {setShowSideBar} = React.useContext(GlobalProvider.defaultContext) let (screenState, setScreenState) = React.useState(() => PageLoaderWrapper.Success) let (stats, setStats) = React.useState(_ => JSON.Encode.null) let (selectedTimeStamp, setSelectedTimeStamp) = React.useState(() => "") let (timeStampOptions, setTimeStampOptions) = React.useState(() => []) let (gateways, setGateways) = React.useState(() => []) let (timeRange, setTimeRange) = React.useState(() => defaultTimeRange) let getStatistics = async () => { try { setScreenState(_ => PageLoaderWrapper.Loading) let url = getURL(~entityName=V1(INTELLIGENT_ROUTING_GET_STATISTICS), ~methodType=Get) let response = await fetchDetails(url) setStats(_ => response) let statsData = (response->IntelligentRoutingUtils.responseMapper).time_series_data let gatewayData = switch statsData->Array.get(0) { | Some(statsData) => statsData.volume_distribution_as_per_sr | None => JSON.Encode.null } statsData->Array.sort((t1, t2) => { let t1 = t1.time_stamp let t2 = t2.time_stamp t1 <= t2 ? -1. : 1. }) let minDate = switch statsData->Array.get(0) { | Some(txn) => txn.time_stamp | None => "" } let maxDate = switch statsData->Array.get(statsData->Array.length - 1) { | Some(txn) => txn.time_stamp | None => "" } setTimeRange(_ => {minDate, maxDate}) let timeStampArray = statsData->Array.map(item => { item.time_stamp }) setTimeStampOptions(_ => timeStampArray) setSelectedTimeStamp(_ => timeStampArray->Array.get(0)->Option.getOr("")) let gatewayKeys = gatewayData ->LogicUtils.getDictFromJsonObject ->Dict.keysToArray gatewayKeys->Array.sort((key1, key2) => { key1 <= key2 ? -1. : 1. }) setGateways(_ => gatewayKeys) setScreenState(_ => PageLoaderWrapper.Success) } catch { | _ => { setScreenState(_ => PageLoaderWrapper.Success) showToast(~message="Failed to fetch statistics data", ~toastType=ToastError) } } } React.useEffect(() => { setShowSideBar(_ => true) getStatistics()->ignore None }, []) let makeOption = (keys): array<SelectBox.dropdownOption> => { keys->Array.map(key => { let options: SelectBox.dropdownOption = {label: getDateTime(key), value: key} options }) } let input: ReactFinalForm.fieldRenderPropsInput = { name: "name", onBlur: _ => (), onChange: ev => { let value = ev->Identity.formReactEventToString setSelectedTimeStamp(_ => value) }, onFocus: _ => (), value: selectedTimeStamp->JSON.Encode.string, checked: true, } let dateRange = displayDateRange(~minDate=timeRange.minDate, ~maxDate=timeRange.maxDate) let customScrollStyle = `max-h-40 overflow-scroll px-1 pt-1 border-pink-400` let dropdownContainerStyle = `rounded-md border border-1 border md:w-40 md:max-w-50` <PageLoaderWrapper screenState={screenState}> <div className="absolute z-20 top-76-px left-0 w-full py-3 px-10 bg-orange-50 flex justify-between items-center"> <div className="flex gap-4 items-center"> <Icon name="nd-information-triangle" size=24 /> <p className="text-nd_gray-600 text-base leading-6 font-medium"> {"You are in demo environment and this is sample setup."->React.string} </p> </div> <GetProductionAccess /> </div> <div className="mt-10"> <div className="flex items-center justify-between"> <PageUtils.PageHeading title="Intelligent Routing Uplift Analysis" /> <p className="text-nd_gray-500 font-medium"> {dateRange->React.string} </p> </div> <div className="flex flex-col gap-12"> <Overview data=stats /> <div className="flex flex-col gap-6"> <div className="text-nd_gray-600 font-semibold text-fs-18"> {"Insights"->React.string} </div> <div className="grid grid-cols-2 gap-4"> <div className="flex flex-col border rounded-lg p-4"> <div className="flex justify-between"> <p className="text-fs-14 text-nd_gray-600 font-semibold leading-17"> {"Overall Transaction Distribution"->React.string} </p> </div> <div className="w-full flex justify-center my-8"> <div className="flex flex-col lg:flex-row gap-3 "> {displayLegend(gateways)->React.array} </div> </div> <div className="flex justify-center"> <div className="flex flex-col xl:flex-row items-center justify-around gap-8 xl:gap-2 tablet:gap-16"> <PieGraph options={PieGraphUtils.getPieChartOptions(pieGraphOptionsActual(stats))} /> <PieGraph options={PieGraphUtils.getPieChartOptions(pieGraphOptionsSimulated(stats))} /> </div> </div> </div> <div className="border rounded-lg p-4"> <LineGraph options={LineGraphUtils.getLineGraphOptions( lineGraphOptions( stats, ~isSmallScreen=MatchMedia.useScreenSizeChecker(~screenSize="1279"), ), )} /> </div> </div> <div className="border rounded-lg p-4 flex flex-col"> <div className="relative"> <div className="!w-full flex justify-end absolute z-10 top-0 right-0 left-0"> <SelectBox.BaseDropdown allowMultiSelect=false buttonText="Select timestamp" input searchable=false deselectDisable=true customButtonStyle="!rounded-lg" options={makeOption(timeStampOptions)} marginTop="mt-10" hideMultiSelectButtons=true addButton=false fullLength=true shouldDisplaySelectedOnTop=true customSelectionIcon={CustomIcon(<Icon name="nd-check" />)} customScrollStyle dropdownContainerStyle /> </div> </div> <LineAndColumnGraph options={LineAndColumnGraphUtils.getLineColumnGraphOptions( lineColumnGraphOptions(stats, ~timeStamp=selectedTimeStamp), )} /> </div> </div> <TransactionsTable setTimeRange /> </div> </div> </PageLoaderWrapper> }
3,791
10,192
hyperswitch-control-center
src/IntelligentRouting/IntelligentRoutingScreens/IntelligentRoutingUtils.res
.res
open VerticalStepIndicatorTypes open IntelligentRoutingTypes let dataSource = [Historical, Realtime] let fileTypes = [Sample, Upload] let realtime = [StreamLive] let dataTypeVariantToString = dataType => switch dataType { | Historical => "Historical Data" | Realtime => "Realtime Data" } let sections = [ { id: "analyze", name: "Choose Your Data Source", icon: "nd-shield", subSections: None, }, { id: "review", name: "Review Data Summary", icon: "nd-flag", subSections: None, }, ] let getFileTypeHeading = fileType => { switch fileType { | Sample => "Try with Our Sample Data" | Upload => "Upload Your Transaction Data" } } let getFileTypeDescription = fileType => { switch fileType { | Sample => "Explore how it works using our pre-loaded transaction data (anonymized) to see potential auth uplift" | Upload => "Upload a day's transaction data to identify uplift opportunities by simulating payments via our router" } } let getFileTypeIconName = fileType => { switch fileType { | Sample => "SAMPLEFILE" | Upload => "UPLOADFILE" } } let getRealtimeHeading = realtime => { switch realtime { | StreamLive => "Stream Live Data via SDK" } } let getRealtimeDescription = realtime => { switch realtime { | StreamLive => "Integrate our SDK to passively observe insights on auth uplift using our simulator" } } let getRealtimeIconName = realtime => { switch realtime { | StreamLive => "STREAMLIVEDATA" } } module StepCard = { @react.component let make = ( ~stepName, ~description, ~isSelected, ~onClick, ~iconName, ~isDisabled=false, ~showDemoLabel=false, ) => { let ringClass = switch isSelected { | true => "border-blue-811 ring-blue-811/20 ring-offset-0 ring-2" | false => "ring-grey-outline" } let tooltipText = isDisabled ? "Feature available only in production" : "" let icon = isSelected ? "blue-circle" : "hollow-circle" let stepComponent = <div key={stepName} className={`flex items-center gap-x-2.5 border ${ringClass} rounded-lg p-4 transition-shadow ${isDisabled ? " opacity-50" : "cursor-pointer"} justify-between`} onClick={!isDisabled ? onClick : _ => ()}> <div className="flex items-center gap-x-2.5"> <img alt={iconName} src={`/IntelligentRouting/${iconName}.svg`} className="w-8 h-8" /> <div className="flex flex-col gap-1"> <div className="flex items-center gap-2"> <h3 className="font-medium text-grey-900"> {stepName->React.string} </h3> <RenderIf condition={showDemoLabel}> <span className="bg-nd_green-100 rounded-md"> <p className="text-nd_green-500 text-sm font-semibold px-2 py-0.5"> {"Demo"->React.string} </p> </span> </RenderIf> </div> <p className="text-sm text-gray-500"> {description->React.string} </p> </div> </div> <Icon name=icon customHeight="20" /> </div> <> <RenderIf condition={isDisabled}> <ToolTip description=tooltipText toolTipFor={stepComponent} justifyClass="justify-end" toolTipPosition=Right /> </RenderIf> <RenderIf condition={!isDisabled}> {stepComponent} </RenderIf> </> } } open LogicUtils let getStats = json => { let dict = json->getDictFromJsonObject { baseline: dict->getFloat("baseline", 0.0), model: dict->getFloat("model", 0.0), } } let mapTimeSeriesData = (arr: array<JSON.t>) => { arr->Array.map(item => { let dict = item->getDictFromJsonObject { time_stamp: dict->getString("time_stamp", ""), success_rate: dict->getJsonObjectFromDict("success_rate")->getStats, revenue: dict->getJsonObjectFromDict("revenue")->getStats, volume_distribution_as_per_sr: dict->getJsonObjectFromDict("volume_distribution_as_per_sr"), } }) } let responseMapper = (response: JSON.t) => { let dict = response->getDictFromJsonObject { overall_success_rate: dict->getJsonObjectFromDict("overall_success_rate")->getStats, total_failed_payments: dict->getJsonObjectFromDict("total_failed_payments")->getStats, total_revenue: dict->getJsonObjectFromDict("total_revenue")->getStats, faar: dict->getJsonObjectFromDict("faar")->getStats, time_series_data: dict->getArrayFromDict("time_series_data", [])->mapTimeSeriesData, overall_success_rate_improvement: dict->getFloat("overall_success_rate_improvement", 0.0), } }
1,176
10,193
hyperswitch-control-center
src/IntelligentRouting/IntelligentRoutingScreens/IntelligentRoutingConfiguration.res
.res
module Review = { @react.component let make = (~reviewFields, ~isUpload=false) => { open IntelligentRoutingReviewFieldsEntity open APIUtils open LogicUtils let getURL = useGetURL() let updateDetails = useUpdateMethod() let showToast = ToastState.useShowToast() let mixpanelEvent = MixpanelHook.useSendEvent() let (showLoading, setShowLoading) = React.useState(() => false) let reviewFields = reviewFields->getReviewFields let queryParamerters = isUpload ? "upload_data=true" : "upload_data=false" let loaderLottieFile = LottieFiles.useLottieJson("spinner.json") let uploadData = async () => { try { setShowLoading(_ => true) let url = getURL( ~entityName=V1(SIMULATE_INTELLIGENT_ROUTING), ~methodType=Post, ~queryParamerters=Some(queryParamerters), ) let response = await updateDetails(url, JSON.Encode.null, Post) let msg = response->getDictFromJsonObject->getString("message", "")->String.toLowerCase if msg === "simulation successful" { RescriptReactRouter.replace( GlobalVars.appendDashboardPath(~url="v2/dynamic-routing/dashboard"), ) } setShowLoading(_ => false) } catch { | _ => setShowLoading(_ => false) showToast(~message="Upload data failed", ~toastType=ToastError) } } let handleNext = _ => { uploadData()->ignore mixpanelEvent(~eventName="intelligent_routing_upload_data") } let modalBody = <div className=""> <div className="text-xl p-3 m-3 font-semibold text-nd_gray-700"> {"Running Intelligence Routing "->React.string} </div> <hr /> <div className="flex flex-col gap-12 items-center pt-10 pb-6 px-6"> <div className="w-8"> <span className="px-3"> <span className={`flex items-center`}> <div className="scale-400 pt-px"> <Lottie animationData={loaderLottieFile} autoplay=true loop=true /> </div> </span> </span> </div> <p className="text-center text-nd_gray-600"> {"Please wait while we are analyzing data. Our intelligent models are working to determine the potential authentication rate uplift."->React.string} </p> </div> </div> <div> <div className="w-500-px"> {IntelligentRoutingHelper.stepperHeading( ~title="Review Data Summary", ~subTitle="Explore insights in the dashboard", )} <div className="mt-6"> <VaultCustomerSummary.Details data=reviewFields getHeading getCell detailsFields=allColumns widthClass="" justifyClassName="grid grid-cols-none" /> </div> <Button text="Explore Insights" customButtonStyle={`w-full mt-6 hover:opacity-80 ${showLoading ? "cursor-wait" : ""}`} buttonType=Primary onClick={_ => handleNext()} rightIcon={showLoading ? CustomIcon( <span className="px-3"> <span className={`flex items-center mx-2 animate-spin`}> <Loadericon size=14 iconColor="text-white" /> </span> </span>, ) : NoIcon} /> </div> <Modal showModal=showLoading closeOnOutsideClick=false setShowModal=setShowLoading childClass="p-0" borderBottom=true modalClass="w-full max-w-xl mx-auto my-auto dark:!bg-jp-gray-lightgray_background"> {modalBody} </Modal> </div> } } module Analyze = { @react.component let make = (~onNextClick, ~setReviewFields, ~setIsUpload) => { open IntelligentRoutingUtils open IntelligentRoutingTypes let showToast = ToastState.useShowToast() let mixpanelEvent = MixpanelHook.useSendEvent() let (selectedField, setSelectedField) = React.useState(() => IntelligentRoutingTypes.Sample) let (text, setText) = React.useState(() => "Next") React.useEffect(() => { setIsUpload(_ => selectedField === Upload) None }, [selectedField]) //TODO: wasm function call to fetch review fields let getReviewData = async () => { try { let response = { "total": 74894, "total_amount": 26317180.359999552, "file_name": "baseline_data.csv", "processors": ["PSP1", "PSP2", "PSP3", "PSP4", "PSP5"], "payment_method_types": ["APPLEPAY", "CARD", "AMAZONPAY"], }->Identity.genericTypeToJson setReviewFields(_ => response) } catch { | _ => showToast( ~message="Something went wrong while fetching the review data", ~toastType=ToastError, ) } } let steps = ["Preparing sample data"] let loadButton = async () => { for i in 0 to Array.length(steps) - 1 { setText(_ => steps[i]->Option.getOr("")) await HyperSwitchUtils.delay(800) } getReviewData()->ignore onNextClick() mixpanelEvent(~eventName="intelligent_routing_analyze_data") } let handleNext = _ => { loadButton()->ignore } let dataSourceHeading = title => <div className="text-nd_gray-400 text-xs font-semibold tracking-wider"> {title->String.toUpperCase->React.string} </div> <div className="w-500-px"> {IntelligentRoutingHelper.stepperHeading( ~title="Choose Your Data Source", ~subTitle="Select a data source to begin your simulation", )} <div className="flex flex-col gap-4 mt-10"> {dataSource ->Array.map(dataSource => { switch dataSource { | Historical => <> {dataSourceHeading(dataSource->dataTypeVariantToString)} {fileTypes ->Array.map(item => { let fileTypeHeading = item->getFileTypeHeading let fileTypeDescription = item->getFileTypeDescription let fileTypeIcon = item->getFileTypeIconName let isSelected = selectedField === item <StepCard stepName={fileTypeHeading} description={fileTypeDescription} isSelected onClick={_ => setSelectedField(_ => item)} iconName=fileTypeIcon isDisabled={item === Upload} showDemoLabel={item === Sample ? true : false} /> }) ->React.array} </> | Realtime => <> {dataSourceHeading(dataSource->dataTypeVariantToString)} {realtime ->Array.map(item => { let realtimeHeading = item->getRealtimeHeading let realtimeDescription = item->getRealtimeDescription let realtimeIcon = item->getRealtimeIconName <StepCard stepName={realtimeHeading} description={realtimeDescription} isSelected=false onClick={_ => ()} iconName=realtimeIcon isDisabled={item === StreamLive} /> }) ->React.array} </> } }) ->React.array} <Button text customButtonStyle={`w-full mt-6 hover:opacity-80 ${text != "Next" ? "cursor-wait" : ""}`} buttonType={Primary} onClick={_ => handleNext()} rightIcon={text != "Next" ? CustomIcon( <span className="px-3"> <span className={`flex items-center mx-2 animate-spin`}> <Loadericon size=14 iconColor="text-white" /> </span> </span>, ) : NoIcon} buttonState={Normal} /> </div> </div> } } @react.component let make = () => { open IntelligentRoutingUtils open VerticalStepIndicatorTypes open VerticalStepIndicatorUtils let {setShowSideBar} = React.useContext(GlobalProvider.defaultContext) let (reviewFields, setReviewFields) = React.useState(_ => Dict.make()->JSON.Encode.object) let (isUpload, setIsUpload) = React.useState(() => false) let (currentStep, setNextStep) = React.useState(() => { sectionId: "analyze", subSectionId: None, }) let getNextStep = (currentStep: step): option<step> => { findNextStep(sections, currentStep) } let onNextClick = () => { switch getNextStep(currentStep) { | Some(nextStep) => setNextStep(_ => nextStep) | None => () } } React.useEffect(() => { setShowSideBar(_ => false) None }, []) let backClick = () => { RescriptReactRouter.replace(GlobalVars.appendDashboardPath(~url="/v2/dynamic-routing")) setShowSideBar(_ => true) } let intelligentRoutingTitleElement = <> <h1 className="text-medium font-semibold text-gray-600"> {`Simulate Intelligent Routing`->React.string} </h1> </> <div className="h-774-px w-full"> {IntelligentRoutingHelper.simulatorBanner} <div className="flex flex-row mt-5 py-10 h-774-px"> <VerticalStepIndicator titleElement=intelligentRoutingTitleElement sections currentStep backClick /> <div className="mx-12 mt-16 overflow-y-auto"> {switch currentStep { | {sectionId: "analyze"} => <Analyze onNextClick setReviewFields setIsUpload /> | {sectionId: "review"} => <Review reviewFields isUpload /> | _ => React.null }} </div> </div> </div> }
2,252
10,194
hyperswitch-control-center
src/IntelligentRouting/IntelligentRoutingScreens/IntelligentRoutingTypes.res
.res
type timeRange = { minDate: string, maxDate: string, } type dataType = Historical | Realtime type file = Sample | Upload type realtime = StreamLive type reviewFieldsColsType = | NumberOfTransaction | TotalAmount | FileName | Processors | PaymentMethodTypes type reviewFields = { total: int, total_amount: int, file_name: string, processors: array<string>, payment_method_types: array<string>, } type transactionObj = { txn_no: int, payment_intent_id: string, payment_attempt_id: string, amount: float, payment_gateway: string, payment_status: bool, card_network: string, created_at: string, payment_method_type: string, order_currency: string, model_connector: string, suggested_uplift: float, } type transactionDetails = { total_payment_count: string, simulation_outcome_of_each_txn: array<transactionObj>, } type stats = { baseline: float, model: float, } type volDist = { success_rate: float, baseline_volume: int, model_volume: int, } type timeSeriesData = { time_stamp: string, success_rate: stats, revenue: stats, volume_distribution_as_per_sr: JSON.t, } type statistics = { overall_success_rate: stats, total_failed_payments: stats, total_revenue: stats, faar: stats, time_series_data: array<timeSeriesData>, overall_success_rate_improvement: float, }
340
10,195
hyperswitch-control-center
src/IntelligentRouting/IntelligentRoutingScreens/IntelligentRoutingHome.res
.res
@react.component let make = () => { let {setCreateNewMerchant, activeProduct} = React.useContext( ProductSelectionProvider.defaultContext, ) let userHasCreateMerchantAccess = OMPCreateAccessHook.useOMPCreateAccessHook([ #tenant_admin, #org_admin, ]) let mixpanelEvent = MixpanelHook.useSendEvent() let onTryDemoClick = () => { mixpanelEvent(~eventName="intelligent_routing_explore_simulator") if activeProduct == DynamicRouting { RescriptReactRouter.push(GlobalVars.appendDashboardPath(~url="v2/dynamic-routing/home")) } else { setCreateNewMerchant(ProductTypes.DynamicRouting) } } <div className="flex flex-1 flex-col gap-14 items-center justify-center w-full h-screen"> <img alt="intelligentRouting" src="/IntelligentRouting/IntelligentRoutingOnboarding.svg" /> <div className="flex flex-col gap-8 items-center"> <div className="border rounded-md text-nd_green-200 border-nd_green-200 font-semibold p-1.5 text-sm w-fit"> {"Intelligent Routing"->React.string} </div> <PageUtils.PageHeading customHeadingStyle="gap-3 flex flex-col items-center" title="Uplift your Payment Authorization Rate" customTitleStyle="text-2xl text-center font-bold text-nd_gray-700 font-500" customSubTitleStyle="text-fs-16 font-normal text-center max-w-700" subTitle="Real-time ML based algorithms and rule-based constraints to route payments optimally" /> <ACLButton authorization={userHasCreateMerchantAccess} text="Explore Simulator" onClick={_ => onTryDemoClick()} rightIcon={CustomIcon(<Icon name="nd-angle-right" size=15 />)} customTextPaddingClass="pr-0" buttonType=Primary buttonSize=Large buttonState=Normal /> </div> </div> }
455
10,196
hyperswitch-control-center
src/mockData/TimeZoneData.res
.res
open UserTimeZoneTypes let getTimeZoneData = timeZoneType => { switch timeZoneType { | GMT => { offset: "+00:00", region: "Africa/Abidjan", title: "GMT", } | EAT => { offset: "+03:00", region: "Africa/Addis_Ababa", title: "EAT", } | CET => { offset: "+01:00", region: "Africa/Algiers", title: "CET", } | WAT => { offset: "+01:00", region: "Africa/Bangui", title: "WAT", } | CAT => { offset: "+02:00", region: "Africa/Blantyre", title: "CAT", } | EET => { offset: "+02:00", region: "Africa/Cairo", title: "EET", } | CEST => { offset: "+02:00", region: "Africa/Ceuta", title: "CEST", } | SAST => { offset: "+02:00", region: "Africa/Johannesburg", title: "SAST", } | HDT => { offset: "-09:00", region: "America/Adak", title: "HDT", } | AKDT => { offset: "-08:00", region: "America/Anchorage", title: "AKDT", } | AST => { offset: "-04:00", region: "America/Anguilla", title: "AST", } | EST => { offset: "-05:00", region: "America/Atikokan", title: "EST", } | CDT => { offset: "-05:00", region: "America/Bahia_Banderas", title: "CDT", } | CST => { offset: "-06:00", region: "America/Belize", title: "CST", } | MDT => { offset: "-06:00", region: "America/Boise", title: "MDT", } | MST => { offset: "-07:00", region: "America/Creston", title: "MST", } | EDT => { offset: "-04:00", region: "America/Detroit", title: "EDT", } | ADT => { offset: "-03:00", region: "America/Glace_Bay", title: "ADT", } | PDT => { offset: "-07:00", region: "America/Los_Angeles", title: "PDT", } | NDT => { offset: "-02:30", region: "America/St_Johns", title: "NDT", } | AEST => { offset: "+10:00", region: "Antarctica/Macquarie", title: "AEST", } | NZST => { offset: "+12:00", region: "Antarctica/McMurdo", title: "NZST", } | EEST => { offset: "+03:00", region: "Asia/Amman", title: "EEST", } | HKT => { offset: "+08:00", region: "Asia/Hong_Kong", title: "HKT", } | WIB => { offset: "+07:00", region: "Asia/Jakarta", title: "WIB", } | WIT => { offset: "+09:00", region: "Asia/Jayapura", title: "WIT", } | IDT => { offset: "+03:00", region: "Asia/Jerusalem", title: "IDT", } | PKT => { offset: "+05:00", region: "Asia/Karachi", title: "PKT", } | IST => { offset: "+05:30", region: "Asia/Kolkata", title: "IST", } | WITA => { offset: "+08:00", region: "Asia/Makassar", title: "WITA", } | PST => { offset: "+08:00", region: "Asia/Manila", title: "PST", } | KST => { offset: "+09:00", region: "Asia/Pyongyang", title: "KST", } | JST => { offset: "+09:00", region: "Asia/Tokyo", title: "JST", } | WEST => { offset: "+01:00", region: "Atlantic/Canary", title: "WEST", } | ACST => { offset: "+09:30", region: "Australia/Adelaide", title: "ACST", } | AWST => { offset: "+08:00", region: "Australia/Perth", title: "AWST", } | BST => { offset: "+01:00", region: "Europe/Guernsey", title: "BST", } | MSK => { offset: "+03:00", region: "Europe/Moscow", title: "MSK", } | ChST => { offset: "+10:00", region: "Pacific/Guam", title: "ChST", } | HST => { offset: "-10:00", region: "Pacific/Honolulu", title: "HST", } | SST => { offset: "-11:00", region: "Pacific/Midway", title: "SST", } | UTC => { offset: "+00:00", region: "UTC", title: "UTC", } } }
1,446
10,197
hyperswitch-control-center
cypress/start_hyperswitch.sh
.sh
#!/bin/bash git clone --depth 1 https://github.com/juspay/hyperswitch curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose # Navigate to the cloned directory cd hyperswitch sed 's|juspaydotin/hyperswitch-router:standalone|juspaydotin/hyperswitch-router:nightly|g' docker-compose.yml > docker-compose.tmp mv docker-compose.tmp docker-compose.yml # Specify the correct file path to the TOML file # File path of the TOML file toml_file="config/docker_compose.toml" # Adjust the path if necessary # Ensure the file exists if [[ ! -f "$toml_file" ]]; then echo "Error: File $toml_file not found!" exit 1 fi # Use sed to remove the [network_tokenization_service] section and all its keys sed '/^\[network_tokenization_service\]/,/^\[.*\]/d' "$toml_file" > temp.toml mv temp.toml "$toml_file" echo "[network_tokenization_service] section removed from $toml_file." # Start Docker Compose services in detached mode chmod +x /usr/local/bin/docker-compose docker-compose up -d pg redis-standalone migration_runner hyperswitch-server hyperswitch-web mailhog
308
10,198
hyperswitch-control-center
cypress/e2e/start.cy.js
.js
describe("template spec", () => { it("passes", () => { cy.visit("/"); cy.contains("Hey there,").should("be.visible"); }); });
36
10,199
hyperswitch-control-center
cypress/e2e/9-profile/profile.cy.js
.js
0
10,200
hyperswitch-control-center
cypress/e2e/1-auth/auth.cy.js
.js
import * as helper from "../../support/helper"; import SignInPage from "../../support/pages/auth/SignInPage"; import SignUpPage from "../../support/pages/auth/SignUpPage"; import ResetPasswordPage from "../../support/pages/auth/ResetPasswordPage"; import { reset } from "mixpanel-browser"; const signinPage = new SignInPage(); const signupPage = new SignUpPage(); const resetPasswordPage = new ResetPasswordPage(); describe("Sign up", () => { it("should verify all components on the sign-up page", () => { cy.visit_signupPage(); signupPage.headerText.should("contain", "Welcome to Hyperswitch"); signupPage.signInLink.should("contain", "Sign in"); signupPage.emailInput.should( "have.attr", "placeholder", "Enter your Email", ); signupPage.signUpButton .contains("Get started, for free!") .should("be.visible"); signupPage.signUpButton.should("be.disabled"); signupPage.footerText.should("be.visible"); signinPage.tcText.should("be.visible"); }); it("should display an error message for an invalid email", () => { const invalidEmails = [ "@#$%", "plainaddress", "missing@domain", "user@.com", "user@domain..com", "user@domain,com", "user@domain.123", "user@domain.c", "user@domain.", "user@.com", "12345678", "abc@@xy.zi", "@com.in", "abc.in", "abc..xyz@abc.com", ]; cy.visit_signupPage(); invalidEmails.forEach((invalidEmail) => { signupPage.emailInput.clear(); signupPage.emailInput.type(invalidEmail).blur(); signupPage.invalidInputError .should("be.visible") .and("contain", "Please enter valid Email ID"); signupPage.signUpButton.should("be.disabled"); signupPage.emailInput.clear().type(Cypress.env("CYPRESS_USERNAME")); signupPage.invalidInputError.should("not.exist"); }); }); it("should show success message page after using magic link", () => { cy.visit_signupPage(); signinPage.signUpLink.click(); signupPage.emailInput.type(Cypress.env("CYPRESS_USERNAME")); signupPage.signUpButton.click(); signupPage.headerText.should("contain", "Please check your inbox"); signupPage.headerText .next("div") .should("contain", "A magic link has been sent to") .should("contain", Cypress.env("CYPRESS_USERNAME")); signupPage.footerText.should("be.visible").should("contain", "Cancel"); }); it("should be able to sign up using magic link", () => { const email = helper.generateUniqueEmail(); const password = Cypress.env("CYPRESS_PASSWORD"); cy.visit_signupPage(); signupPage.emailInput.type(email); signupPage.signUpButton.click(); signupPage.headerText.should("contain", "Please check your inbox"); cy.redirect_from_mail_inbox(); // Skip 2FA signinPage.skip2FAButton.click(); // Set password resetPasswordPage.createPassword.type(password); resetPasswordPage.confirmPassword.type(password); resetPasswordPage.confirmButton.click(); // Login to dashboard signinPage.emailInput.type(email); signinPage.passwordInput.type(password); signinPage.signinButton.click(); // Skip 2FA signinPage.skip2FAButton.click(); cy.url().should("include", "/dashboard/home"); }); it("should navigate back to the login page when the `cancel` button in signup page is clicked", () => { cy.visit_signupPage(); signinPage.signUpLink.click(); signupPage.emailInput.type(Cypress.env("CYPRESS_USERNAME")); signupPage.signUpButton.click(); signupPage.footerText.click(); cy.url().should("include", "/login"); }); it("should verify password masking while signup", () => { const email = helper.generateUniqueEmail(); const password = Cypress.env("CYPRESS_PASSWORD"); cy.visit_signupPage(); signupPage.emailInput.type(email); signupPage.signUpButton.click(); cy.redirect_from_mail_inbox(); signinPage.skip2FAButton.click(); resetPasswordPage.createPassword .should("have.attr", "type", "password") .type(password); resetPasswordPage.confirmPassword .should("have.attr", "type", "password") .type(password); resetPasswordPage.eyeIcon.eq(0).click(); resetPasswordPage.createPassword.should("have.attr", "type", "text"); resetPasswordPage.createPassword.should("have.value", password); resetPasswordPage.eyeIcon.click(); resetPasswordPage.confirmPassword.should("have.attr", "type", "text"); resetPasswordPage.confirmPassword.should("have.value", password); }); }); describe("Sign in", () => { it("should verify all required components on the login page", () => { cy.visit("/"); cy.url().should("include", "/dashboard/login"); signinPage.headerText.should("contain", "Hey there, Welcome back!"); signinPage.signUpLink.should("contain", "Sign up"); signinPage.emailInput.should("be.visible"); signupPage.emailInput.should( "have.attr", "placeholder", "Enter your Email", ); signinPage.passwordInput.should("be.visible"); signupPage.passwordInput.should( "have.attr", "placeholder", "Enter your Password", ); signinPage.signinButton.should("be.visible"); signinPage.tcText.should("exist"); signinPage.footerText.should("exist"); }); it("should return to login page when clicked on 'Sign in'", () => { cy.visit("/"); signinPage.signUpLink.click(); cy.url().should("include", "/register"); signupPage.headerText.should("contain", "Welcome to Hyperswitch"); signupPage.signInLink.click(); cy.url().should("include", "/login"); signinPage.headerText.should("contain", "Hey there, Welcome back!"); }); it("should successfully login in with valid credentials", () => { const email = helper.generateUniqueEmail(); cy.signup_API(email, Cypress.env("CYPRESS_PASSWORD")); cy.visit("/"); signinPage.emailInput.type(email); signinPage.passwordInput.type(Cypress.env("CYPRESS_PASSWORD")); signinPage.signinButton.click(); signinPage.skip2FAButton.click(); cy.url().should("include", "/dashboard/home"); }); it("should display an error message with invalid credentials", () => { cy.visit("/"); signinPage.emailInput.type("abc@gmail.com"); signinPage.passwordInput.type("aAbcd?"); signinPage.signinButton.click(); signinPage.invalidCredsToast.should("be.visible"); }); it("should login successfully with email containing spaces", () => { const email = helper.generateUniqueEmail(); cy.visit("/"); cy.signup_API(email, Cypress.env("CYPRESS_PASSWORD")); cy.login_UI(email, Cypress.env("CYPRESS_PASSWORD")); cy.url().should("include", "/dashboard/home"); }); it("should verify all components on the signin page", () => { cy.visit("/"); signinPage.headerText.should("contain", "Hey there, Welcome back!"); signinPage.signUpLink.should("contain", "Sign up"); signinPage.emailInput.should("be.visible"); signupPage.emailInput.should( "have.attr", "placeholder", "Enter your Email", ); signinPage.passwordInput.should("be.visible"); signupPage.passwordInput.should( "have.attr", "placeholder", "Enter your Password", ); signinPage.forgetPasswordLink .should("be.visible") .and("contains.text", "Forgot Password?"); signinPage.signinButton.should("be.visible"); signinPage.emailSigninLink .should("be.visible") .and("contains.text", "sign in with an email"); signinPage.tcText.should("exist"); signinPage.footerText.should("exist"); }); it("should display only email field when 'sign in with an email' is clicked", () => { cy.visit("/"); cy.get('[data-testid="password"]').should("exist"); cy.get('[data-testid="forgot-password"]').should("exist"); signinPage.emailSigninLink.click(); cy.get('[data-testid="password"]').should("not.exist"); cy.get('[data-testid="forgot-password"]').should("not.exist"); }); it("should verify components displayed in 2FA setup page", () => { const email = helper.generateUniqueEmail(); cy.signup_API(email, Cypress.env("CYPRESS_PASSWORD")); cy.visit("/"); signinPage.emailInput.type(email); signinPage.passwordInput.type(Cypress.env("CYPRESS_PASSWORD")); signinPage.signinButton.click(); signinPage.headerText2FA.should( "contain", "Enable Two Factor Authentication", ); signinPage.instructions2FA .should("contain", "Use any authenticator app to complete the setup") .and( "contain", "Follow these steps to configure two factor authentication", ) .and( "contain", "Scan the QR code shown on the screen with your authenticator application", ) .and( "contain", "Enter the OTP code displayed on the authenticator app in below text field or textbox", ); signinPage.otpBox2FA.should( "contain", "Enter a 6-digit authentication code generated by you authenticator app", ); signinPage.otpBox2FA .children() .eq(1) .find("div.w-16.h-16") .should("have.length", 6); signinPage.skip2FAButton.should("be.visible"); signinPage.enable2FA .should("be.visible") .and("be.disabled") .and("contain", "Enable 2FA"); signinPage.footerText2FA .should("be.visible") .contains("Log in with a different account?"); signinPage.footerText2FA.should("contain", "Click here to log out."); }); it("should display error message with invalid TOTP in 2FA page", () => { const email = helper.generateUniqueEmail(); cy.signup_API(email, Cypress.env("CYPRESS_PASSWORD")); const otp = "123456"; cy.visit("/"); signinPage.emailInput.type(email); signinPage.passwordInput.type(Cypress.env("CYPRESS_PASSWORD")); signinPage.signinButton.click(); signinPage.otpBox2FA .children() .eq(1) .find("div.w-16.h-16") .each(($input, index) => { cy.wrap($input).type(otp.charAt(index)); }); signinPage.enable2FA.click(); cy.contains("Invalid TOTP").should("be.visible"); }); it("should navigate to homepage when 2FA is skipped", () => { const email = helper.generateUniqueEmail(); cy.signup_API(email, Cypress.env("CYPRESS_PASSWORD")); cy.visit("/"); signinPage.emailInput.type(email); signinPage.passwordInput.type(Cypress.env("CYPRESS_PASSWORD")); signinPage.signinButton.click(); signinPage.headerText2FA.should( "contain", "Enable Two Factor Authentication", ); signinPage.skip2FAButton.click(); cy.url().should("include", "/dashboard/home"); }); it("should navigate to signin page when 'Click here to log out.' is clicked in 2FA page", () => { const email = helper.generateUniqueEmail(); cy.signup_API(email, Cypress.env("CYPRESS_PASSWORD")); cy.visit("/"); signinPage.emailInput.type(email); signinPage.passwordInput.type(Cypress.env("CYPRESS_PASSWORD")); signinPage.signinButton.click(); signinPage.headerText2FA.should( "contain", "Enable Two Factor Authentication", ); signinPage.footerText2FA.children().eq(0).click(); signinPage.headerText.should("contain", "Hey there, Welcome back!"); }); }); describe("Forgot password", () => { it("should verify all components in forgot passowrd page", () => { cy.visit("/"); signinPage.forgetPasswordLink.click(); cy.url().should("include", "/dashboard/forget-password"); signinPage.forgetPasswordHeader.should("contain", "Forgot Password?"); signinPage.emailInput.should("be.visible"); signinPage.emailInput .children() .eq(0) .should("have.attr", "placeholder", "Enter your Email"); signinPage.resetPasswordButton.should("be.visible").and("be.disabled"); signinPage.cancelForgetPassword .should("be.visible") .and("contain", "Cancel"); }); it("should display fail toast when unregistered email is used", () => { cy.visit("/"); signinPage.forgetPasswordLink.click(); signinPage.emailInput.type("abcde@gmail.com"); signinPage.resetPasswordButton.click(); cy.get(`[data-toast="Forgot Password Failed, Try again"]`) .should("be.visible") .and("contain", "Forgot Password Failed, Try again"); }); it("should display success message when registered email is used", () => { const email = helper.generateUniqueEmail(); cy.signup_API(email, Cypress.env("CYPRESS_PASSWORD")); cy.visit("/"); signinPage.forgetPasswordLink.click(); signinPage.emailInput.type(email); signinPage.resetPasswordButton.click(); cy.get(`[data-toast="Please check your registered e-mail"]`) .should("be.visible") .and("contain", "Please check your registered e-mail"); cy.get(`[data-testid="card-header"]`).should( "contain", "Please check your inbox", ); cy.get(`[class="flex-col items-center justify-center"]`) .children() .eq(0) .should("contain", "A reset password link has been sent to"); cy.get(`[class="flex-col items-center justify-center"]`) .children() .eq(1) .should("contain", email); cy.get(`[class="w-full flex justify-center"]`).should("contain", "Cancel"); }); it("should reset password through mail and login successfully", () => { const email = helper.generateUniqueEmail(); let new_password = "Test@123"; cy.signup_API(email, Cypress.env("CYPRESS_PASSWORD")); cy.visit("/"); signinPage.forgetPasswordLink.click(); signinPage.emailInput.type(email); signinPage.resetPasswordButton.click(); cy.redirect_from_mail_inbox(); signinPage.skip2FAButton.click(); resetPasswordPage.newPasswordField.type(new_password); resetPasswordPage.confirmPasswordField.type(new_password); resetPasswordPage.confirmButton.click(); cy.url().should("include", "/login"); cy.get(`[data-toast="Password Changed Successfully"]`).should( "contain", "Password Changed Successfully", ); signinPage.emailInput.type(email); signinPage.passwordInput.type(new_password); signinPage.signinButton.click(); signinPage.skip2FAButton.click(); cy.url().should("include", "/dashboard/home"); }); });
3,326
10,201
hyperswitch-control-center
cypress/e2e/5-analytics/PerformanceMonitor.cy.js
.js
0
10,202
hyperswitch-control-center
cypress/e2e/8-settings/users.cy.js
.js
import * as helper from "../../support/helper"; import HomePage from "../../support/pages/homepage/HomePage"; const homePage = new HomePage(); beforeEach(function () { const email = helper.generateUniqueEmail(); cy.visit_signupPage(); cy.sign_up_with_email(email, Cypress.env("CYPRESS_PASSWORD")); cy.url().should("include", "/dashboard/home"); homePage.enterMerchantName.type("Test_merchant"); homePage.onboardingSubmitButton.click(); }); describe("Users", () => { it("should successfully invite a user and verify received invite", () => { cy.get('[data-testid="settings"]').click(); cy.get('[data-testid="users"]').click(); cy.get('[data-button-for="inviteUsers"]').click(); cy.get('[class="w-full cursor-text"]').type(helper.generateUniqueEmail()); cy.get( '[class="bg-gray-200 w-full h-[calc(100%-16px)] my-2 flex items-center px-4"]', ).click(); cy.get( '[class="relative inline-flex whitespace-pre leading-5 justify-between text-sm py-3 px-4 font-medium rounded-md hover:bg-opacity-80 bg-white border w-full"]', ).click(); cy.get('[class="mr-5"]').eq(0).click(); cy.get('[data-button-for="sendInvite"').click(); cy.visit(Cypress.env("MAIL_URL")); cy.get("div.messages > div:nth-child(1)").click(); cy.wait(1000); cy.get("iframe").then(($iframe) => { cy.get('[class="ng-binding"]').should( "contain", "You have been invited to join Hyperswitch Community", ); }); }); });
373
10,203
hyperswitch-control-center
cypress/e2e/4-connectors/connector.cy.js
.js
describe("connector", () => { const password = Cypress.env("CYPRESS_PASSWORD"); const username = `cypress${Math.round(+new Date() / 1000)}@gmail.com`; const getIframeBody = () => { return cy .get("iframe") .its("0.contentDocument.body") .should("not.be.empty") .then(cy.wrap); }; const selectRange = (range, shouldPaymentExist) => { cy.get("[data-date-picker=dateRangePicker]").click(); cy.get("[data-date-picker-predifined=predefined-options]").should("exist"); cy.get(`[data-daterange-dropdown-value="${range}"]`) .should("exist") .click(); if (shouldPaymentExist) { cy.get("[data-table-location=Orders_tr1_td1]").should("exist"); } else { cy.get("[data-table-location=Orders_tr1_td1]").should("not.exist"); } }; before(() => { cy.visit("/dashboard/login"); cy.url().should("include", "/login"); cy.get("[data-testid=card-header]").should( "contain", "Hey there, Welcome back!", ); cy.get("[data-testid=card-subtitle]") .should("contain", "Sign up") .click({ force: true }); cy.url().should("include", "/register"); cy.get("[data-testid=auth-submit-btn]").should("exist"); cy.get("[data-testid=tc-text]").should("exist"); cy.get("[data-testid=footer]").should("exist"); cy.sign_up_with_email(username, password); cy.get('[data-form-label="Business name"]').should("exist"); cy.get("[data-testid=merchant_name]").type("test_business"); cy.get("[data-button-for=startExploring]").click(); }); beforeEach(function () { if (this.currentTest.title !== "Create a dummy connector") { cy.visit("/dashboard/login"); cy.url().should("include", "/login"); cy.get("[data-testid=card-header]").should( "contain", "Hey there, Welcome back!", ); cy.get("[data-testid=email]").type(username); cy.get("[data-testid=password]").type(password); cy.get('button[type="submit"]').click({ force: true }); cy.get("[data-testid=skip-now]").click({ force: true }); } }); it("Create a dummy connector", () => { cy.get("[data-testid=connectors]").click(); cy.get("[data-testid=paymentprocessors]").click(); cy.contains("Payment Processors").should("be.visible"); cy.contains("Connect a Dummy Processor").should("be.visible"); cy.get("[data-button-for=connectNow]").click({ force: true, }); cy.get('[data-component="modal:Connect a Dummy Processor"]', { timeout: 10000, }) .find("button") .should("have.length", 4); cy.contains("Stripe Dummy").should("be.visible"); cy.get('[data-testid="stripe_test"]').find("button").click({ force: true }); cy.url().should("include", "/dashboard/connectors"); cy.contains("Credentials").should("be.visible"); cy.get("[name=connector_account_details\\.api_key]") .clear() .type("dummy_api_key"); cy.get("[name=connector_label]").clear().type("stripe_test_default_label"); cy.get("[data-button-for=connectAndProceed]").click(); cy.get("[data-testid=credit_select_all]").click(); cy.get("[data-testid=credit_mastercard]").click(); cy.get("[data-testid=debit_cartesbancaires]").click(); cy.get("[data-testid=pay_later_klarna]").click(); cy.get("[data-testid=wallet_we_chat_pay]").click(); cy.get("[data-button-for=proceed]").click(); cy.get('[data-toast="Connector Created Successfully!"]', { timeout: 10000, }).click(); cy.get("[data-button-for=done]").click(); cy.url().should("include", "/dashboard/connectors"); cy.contains("stripe_test_default_label") .scrollIntoView() .should("be.visible"); }); it("Use the SDK to process a payment", () => { cy.clearCookies("login_token"); cy.get("[data-testid=connectors]").click(); cy.get("[data-testid=paymentprocessors]").click(); cy.contains("Payment Processors").should("be.visible"); cy.get("[data-testid=home]").first().click(); cy.get("[data-button-for=tryItOut]").click(); cy.get('[data-breadcrumb="Explore Demo Checkout Experience"]').should( "exist", ); cy.get('[data-value="unitedStates(USD)"]').click(); cy.get('[data-dropdown-value="Germany (EUR)"]').click(); cy.get("[data-testid=amount]").find("input").clear().type("77"); cy.get("[data-button-for=showPreview]").click(); cy.wait(2000); getIframeBody() .find("[data-testid=cardNoInput]", { timeout: 20000 }) .should("exist") .type("4242424242424242"); getIframeBody() .find("[data-testid=expiryInput]") .should("exist") .type("0127"); getIframeBody().find("[data-testid=cvvInput]").should("exist").type("492"); cy.get("[data-button-for=payEUR77]").should("exist").click(); cy.contains("Payment Successful").should("exist"); }); it("Verify Time Range Filters after Payment in Payment Operations Page", () => { cy.get("[data-testid=operations]").click(); cy.get("[data-testid=payments]").click(); cy.contains("Payment Operations").should("be.visible"); const today = new Date(); const date30DaysAgo = new Date(today); date30DaysAgo.setDate(today.getDate() - 30); const formattedDate30DaysAgo = date30DaysAgo.toLocaleDateString("en-US", { year: "numeric", month: "short", day: "2-digit", }) + " - Now"; cy.get(`[data-button-text='${formattedDate30DaysAgo}']`).should("exist"); cy.get("[data-table-location=Orders_tr1_td1]").should("exist"); cy.get("[data-icon=customise-columns]").should("exist"); const timeRanges = [ { range: "Last 30 Mins", shouldPaymentExist: true }, { range: "Last 1 Hour", shouldPaymentExist: true }, { range: "Last 2 Hours", shouldPaymentExist: true }, { range: "Today", shouldPaymentExist: true }, { range: "Yesterday", shouldPaymentExist: false }, { range: "Last 2 Days", shouldPaymentExist: true }, { range: "Last 7 Days", shouldPaymentExist: true }, { range: "Last 30 Days", shouldPaymentExist: true }, { range: "This Month", shouldPaymentExist: true }, { range: "Last Month", shouldPaymentExist: false }, ]; timeRanges.forEach(({ range, shouldPaymentExist }) => { selectRange(range, shouldPaymentExist); }); }); // it("Verify Custom Range in Time Range Filters after Payment in Payment Operations Page", () => { // cy.get("[data-testid=operations]").click(); // cy.get("[data-testid=payments]").click(); // cy.contains("Payment Operations").should("exist"); // const today = new Date(); // const date30DaysAgo = new Date(today); // date30DaysAgo.setDate(today.getDate() - 30); // const formattedDate30DaysAgo = date30DaysAgo.toLocaleDateString("en-US", { // year: "numeric", // month: "short", // day: "2-digit", // }); // cy.get(`[data-button-text='${formattedDate30DaysAgo} - Now']`).should( // "exist", // ); // cy.get(`[data-button-text='${formattedDate30DaysAgo} - Now']`).click(); // cy.get("[data-date-picker-predifined=predefined-options]").should("exist"); // cy.get('[data-daterange-dropdown-value="Custom Range"]') // .should("exist") // .click(); // cy.get("[data-date-picker-section=date-picker-calendar]").should("exist"); // const formattedDate = today.toLocaleDateString("en-US", { // year: "numeric", // month: "short", // day: "2-digit", // }); // const selectDate = today.toLocaleDateString("en-US", { // year: "numeric", // month: "short", // day: "numeric", // }); // cy.get(`[data-testid="${selectDate}"]`).click(); // cy.get("[data-button-for=apply]").click(); // const isStartDate = date30DaysAgo.getDate() === 1; // const isEndDate = // today.getDate() === // new Date(today.getFullYear(), today.getMonth() + 1, 0).getDate(); // if (isStartDate && isEndDate) { // cy.get(`[data-button-text='This Month']`).should("exist"); // } else { // cy.get( // `[data-button-text='${formattedDate30DaysAgo} - ${formattedDate}']`, // ).should("exist"); // } // cy.get("[data-table-location=Orders_tr1_td1]").should("exist"); // }); it("Verify Search for Payment Using Existing Payment ID in Payment Operations Page", () => { cy.get("[data-testid=operations]").click(); cy.get("[data-testid=payments]").click(); cy.contains("Payment Operations").should("be.visible"); cy.get("span").contains("...").click(); cy.get("[data-table-location=Orders_tr1_td2]") .invoke("text") .then((expectedPaymentId) => { cy.get('[data-id="Search for payment ID"]').should("exist"); cy.get('[data-id="Search for payment ID"]') .click() .type(`${expectedPaymentId}{enter}`); cy.get("[data-table-location=Orders_tr1_td1]").should("exist"); cy.get("span").contains("...").click(); cy.get("[data-table-location=Orders_tr1_td2]") .invoke("text") .should((actualPaymentId) => { expect(expectedPaymentId).to.eq(actualPaymentId); }); }); }); it("Verify Search for Payment Using Invalid Payment ID in Payment Operations Page", () => { cy.get("[data-testid=operations]").click(); cy.get("[data-testid=payments]").click(); cy.contains("Payment Operations").should("be.visible"); cy.get('[data-id="Search for payment ID"]').should("exist"); const paymentIds = ["abacd", "something", "createdAt"]; paymentIds.forEach((id) => { cy.get('[data-id="Search for payment ID"]').click(); cy.get('[data-id="Search for payment ID"]').type(`${id}{enter}`); cy.get("[data-table-location=Orders_tr1_td1]").should("not.exist"); cy.get('[placeholder="Search for payment ID"]').click().clear(); }); }); });
2,565
10,204
hyperswitch-control-center
cypress/e2e/2-homepage/homepage.cy.js
.js
import * as helper from "../../support/helper"; import SignInPage from "../../support/pages/auth/SignInPage"; import SignUpPage from "../../support/pages/auth/SignUpPage"; const signinPage = new SignInPage(); const signupPage = new SignUpPage(); describe("Sign up", () => { let email = ""; // check if the permissions and access level allow the test to run beforeEach(function () { if (Cypress.env("RBAC") == "") { email = helper.generateUniqueEmail(); cy.signup_API(email, Cypress.env("CYPRESS_PASSWORD")); } // add valid param check else { const testName = Cypress.currentTest.title; const tags = testName.match(/@([a-zA-Z0-9_-]+)/g) || []; // Extract all tags from the test name // Check if the test case name contains any of the tags in ["org", "merchant", "profile"] const containsAccessLevelTag = tags.some((tag) => ["@org", "@merchant", "@profile"].includes(tag), ); if (containsAccessLevelTag) { cy.checkPermissionsFromTestName("@account " + testName).then( (shouldSkip) => { if (shouldSkip) { this.skip(); // Skip if test is skippable } // Create user with role passed from env // TODO: create a function to pass role and access level to create the user email = helper.generateUniqueEmail(); cy.signup_API(email, Cypress.env("CYPRESS_PASSWORD")); }, ); } else { this.skip(); // Skip if no access level tag } } }); it("@merchant should run for both org and custom role", () => { cy.visit("/"); signinPage.emailInput.type(email); signinPage.passwordInput.type(Cypress.env("CYPRESS_PASSWORD")); signinPage.signinButton.click(); signinPage.skip2FAButton.click(); cy.url().should("include", "/dashboard/home"); cy.get("[class='md:max-w-40 max-w-16']").click(); cy.get("[data-icon='nd-plus']").click({ force: true }); cy.get("[name='profile_name']").clear().type("new_profile_name"); cy.get("[data-button-for='addProfile']").click(); }); it("should only for org user", () => { cy.visit("/"); }); // it("should process a payment using the SDK", () => { // }); });
526
10,205
hyperswitch-control-center
cypress/e2e/7-developers/PaymentSettings.cy.js
.js
0
10,206
hyperswitch-control-center
cypress/e2e/6-workflow/PaymentRouting.cy.js
.js
import * as helper from "../../support/helper"; import SignInPage from "../../support/pages/auth/SignInPage"; import HomePage from "../../support/pages/homepage/HomePage"; import PaymentRouting from "../../support/pages/workflow/paymentRouting/PaymentRouting"; import DefaultFallback from "../../support/pages/workflow/paymentRouting/DefaultFallback"; import VolumeBasedConfiguration from "../../support/pages/workflow/paymentRouting/VolumeBasedConfiguration"; const signinPage = new SignInPage(); const homePage = new HomePage(); const paymentRouting = new PaymentRouting(); const defaultFallback = new DefaultFallback(); const volumeBasedConfiguration = new VolumeBasedConfiguration(); beforeEach(function () { const email = helper.generateUniqueEmail(); cy.signup_API(email, Cypress.env("CYPRESS_PASSWORD")); cy.login_UI(email, Cypress.env("CYPRESS_PASSWORD")); }); describe("Volume based routing", () => { it("should display valid message when no connectors are connected", () => { homePage.workflow.click(); homePage.routing.click(); paymentRouting.volumeBasedRoutingSetupButton.click(); cy.get('[class="px-3 text-fs-16"]').should( "contains.text", "Please configure atleast 1 connector", ); }); it("should display all elements in volume based routing page", () => { let merchant_id; homePage.merchantID .eq(0) .invoke("text") .then((text) => { merchant_id = text; cy.createDummyConnectorAPI(merchant_id, "stripe_test_1"); }); homePage.workflow.click(); homePage.routing.click(); paymentRouting.volumeBasedRoutingSetupButton.click(); cy.url().should("include", "/routing/volume"); //verify page header paymentRouting.volumeBasedRoutingHeader.should( "contain", "Smart routing configuration", ); //verify selected profile homePage.profileDropdown.click(); let profileID; homePage.profileDropdownList .children() .eq(1) .invoke("text") .then((text) => { profileID = text; let convertedStr = profileID.replace("pro", " (pro") + ")"; cy.get(`[data-button-text="${convertedStr}"]`).should( "contain", convertedStr, ); }); // verify Configuration Name placeholder const currentDate = new Date(); let formattedDate = currentDate.toISOString().split("T")[0]; cy.get(`[placeholder="Enter Configuration Name"]`).should( "have.value", "Volume Based Routing-" + formattedDate, ); // verify Description placeholder cy.get(`[name="description"]`).should( "contain", "This is a volume based routing created at", ); // verify added connector in dropdown volumeBasedConfiguration.connectorDropdown.click(); cy.get(`[value="stripe_test_1"]`).should("contain", "stripe_test_1"); }); it("should save new Volume based configuration", () => { let merchant_id; homePage.merchantID .eq(0) .invoke("text") .then((text) => { merchant_id = text; cy.createDummyConnectorAPI(merchant_id, "stripe_test_1"); }); homePage.workflow.click(); homePage.routing.click(); paymentRouting.volumeBasedRoutingSetupButton.click(); cy.url().should("include", "/routing/volume"); cy.get(`[placeholder="Enter Configuration Name"]`).type( "Test volume based config", ); volumeBasedConfiguration.connectorDropdown.click(); cy.get(`[value="stripe_test_1"]`).click(); cy.get(`[data-button-for="configureRule"]`).click(); cy.get(`[data-button-for="saveRule"]`).click(); cy.get(`[data-toast="Successfully Created a new Configuration !"]`).should( "contain", "Successfully Created a new Configuration !", ); cy.get(`[data-table-location="History_tr1_td2"]`).should( "contain", "Test volume based config", ); cy.get(`[data-label="INACTIVE"]`).should("contain", "INACTIVE"); }); it("should save and activate Volume based configuration", () => { let merchant_id; homePage.merchantID .eq(0) .invoke("text") .then((text) => { merchant_id = text; cy.createDummyConnectorAPI(merchant_id, "stripe_test_1"); }); homePage.workflow.click(); homePage.routing.click(); paymentRouting.volumeBasedRoutingSetupButton.click(); cy.url().should("include", "/routing/volume"); cy.get(`[placeholder="Enter Configuration Name"]`).type( "Test volume based config", ); volumeBasedConfiguration.connectorDropdown.click(); cy.get(`[value="stripe_test_1"]`).click(); cy.get(`[data-button-for="configureRule"]`).click(); cy.get(`[data-button-for="saveAndActivateRule"]`).click(); cy.get(`[data-toast="Successfully Activated !"]`).should( "contain", "Successfully Activated !", ); cy.get(`[data-table-location="History_tr1_td2"]`).should( "contain", "Test volume based config", ); cy.get(`[data-label="ACTIVE"]`).should("contain", "ACTIVE"); }); }); describe("Rule based routing", () => { it("should display valid message when no connectors are connected", () => { homePage.workflow.click(); homePage.routing.click(); paymentRouting.ruleBasedRoutingSetupButton.click(); cy.get('[class="px-3 text-fs-16"]').should( "contains.text", "Please configure atleast 1 connector", ); }); }); describe("Payment default fallback", () => { it("should display valid message when no connectors are connected", () => { homePage.workflow.click(); homePage.routing.click(); paymentRouting.defaultFallbackManageButton.click(); cy.get('[class="px-3 text-2xl mt-32 "]').should( "contains.text", "Please connect atleast 1 connector", ); }); it("should display connected connectors in the list", () => { let merchant_id; cy.get('[style="overflow-wrap: anywhere;"]') .eq(0) .invoke("text") .then((text) => { merchant_id = text; cy.createDummyConnectorAPI(merchant_id, "stripe_test_1"); }); homePage.connectors.click(); homePage.paymentProcessors.click(); homePage.workflow.click(); homePage.routing.click(); paymentRouting.defaultFallbackManageButton.click(); defaultFallback.defaultFallbackList .children() .eq(0) .should("contains.text", "stripe_test_1"); }); it.skip("should be able to change the order by dragging and updating", () => { let merchant_id; cy.get('[style="overflow-wrap: anywhere;"]') .eq(0) .invoke("text") .then((text) => { merchant_id = text; cy.createDummyConnectorAPI(merchant_id, "stripe_test_1"); cy.createDummyConnectorAPI(merchant_id, "stripe_test_2"); }); homePage.workflow.click(); homePage.routing.click(); paymentRouting.defaultFallbackManageButton.click(); defaultFallback.defaultFallbackList .children() .eq(0) .should("contains.text", "stripe_test_1"); defaultFallback.defaultFallbackList .children() .eq(1) .should("contains.text", "stripe_test_2"); ///TODO: Add drag and drop functionality defaultFallback.defaultFallbackList .children() .eq(0) .should("contains.text", "stripe_test_2"); defaultFallback.defaultFallbackList .children() .eq(1) .should("contains.text", "stripe_test_1"); }); });
1,710
10,207
hyperswitch-control-center
cypress/e2e/3-operations/paymentOperations.cy.js
.js
import * as helper from "../../support/helper"; import HomePage from "../../support/pages/homepage/HomePage"; import PaymentOperations from "../../support/pages/operations/PaymentOperations"; const homePage = new HomePage(); const paymentOperations = new PaymentOperations(); beforeEach(function () { const email = helper.generateUniqueEmail(); cy.signup_API(email, Cypress.env("CYPRESS_PASSWORD")); cy.login_UI(email, Cypress.env("CYPRESS_PASSWORD")); }); const columnSize = 23; const requiredColumnsSize = 14; describe("Payment Operations", () => { it("should verify all components in Payment Operations page", () => { homePage.operations.click(); homePage.paymentOperations.click(); //Header cy.get(`[class="text-fs-28 font-semibold leading-10 "]`).should( "contain", "Payment Operations", ); // Transaction view cy.get(`[class="flex gap-6 justify-around"]`) .children() .eq(0) .should("have.text", "All0"); cy.get(`[class="flex gap-6 justify-around"]`) .children() .eq(1) .should("have.text", "Succeeded0"); cy.get(`[class="flex gap-6 justify-around"]`) .children() .eq(2) .should("have.text", "Failed0"); cy.get(`[class="flex gap-6 justify-around"]`) .children() .eq(3) .should("have.text", "Dropoffs0"); cy.get(`[class="flex gap-6 justify-around"]`) .children() .eq(4) .should("have.text", "Cancelled0"); // Search box paymentOperations.searchBox.should( "have.attr", "placeholder", "Search for payment ID", ); //Date selector, View dropdown, Add filters paymentOperations.dateSelector.should("be.visible"); paymentOperations.viewDropdown.should("be.visible"); paymentOperations.addFilters.should("be.visible"); cy.get(`[class="items-center text-2xl text-black font-bold mb-4"]`).should( "have.text", "No results found", ); cy.get(`[data-button-for="expandTheSearchToThePrevious90Days"]`).should( "have.text", "Expand the search to the previous 90 days", ); cy.get(`[class="flex justify-center"]`).should( "have.text", "Or try the following:Try a different search parameterAdjust or remove filters and search once more", ); }); it("should verify all components in Payment Operations page when a payment exists", () => { let merchant_id; homePage.merchantID .eq(0) .invoke("text") .then((text) => { merchant_id = text; cy.createDummyConnectorAPI(merchant_id, "stripe_test_1"); cy.createPaymentAPI(merchant_id).then((response) => { homePage.operations.click(); homePage.paymentOperations.click(); //Header cy.get(`[class="text-fs-28 font-semibold leading-10 "]`).should( "contain", "Payment Operations", ); // Transaction view cy.get(`[class="flex gap-6 justify-around"]`) .children() .eq(0) .should("have.text", "All1"); cy.get(`[class="flex gap-6 justify-around"]`) .children() .eq(1) .should("have.text", "Succeeded1"); // Search box paymentOperations.searchBox.should( "have.attr", "placeholder", "Search for payment ID", ); // Add filters, Date selector, View dropdown, Column button paymentOperations.addFilters.should("be.visible"); paymentOperations.dateSelector.should("be.visible"); paymentOperations.viewDropdown.should("be.visible"); paymentOperations.columnButton.should("be.visible"); // Table headers const expectedHeaders = [ "S.No", "Payment ID", "Connector", "Profile Id", "Amount", "Payment Status", "Payment Method", "Payment Method Type", "Card Network", "Connector Transaction ID", "Customer Email", "Merchant Order Reference Id", "Description", "Metadata", "Created", ]; cy.get("table thead tr th").each(($el, index) => { cy.wrap($el).should("have.text", expectedHeaders[index]); }); // Payment details in table row cy.get(`[data-table-location="Orders_tr1_td1"]`).contains("1"); cy.get(`[data-table-location="Orders_tr1_td2"]`) .contains("...") .click(); cy.get(`[data-table-location="Orders_tr1_td2"]`).contains( response.body.payment_id, ); cy.get(`[data-table-location="Orders_tr1_td3"]`).contains( "Stripe Dummy", ); cy.get(`[data-table-location="Orders_tr1_td4"]`).contains( response.body.profile_id, ); cy.get(`[data-table-location="Orders_tr1_td5"]`).contains( `${response.body.amount / 100}` + " " + `${response.body.currency}`, ); cy.get(`[data-table-location="Orders_tr1_td6"]`).contains( response.body.status.toUpperCase(), ); cy.get(`[data-table-location="Orders_tr1_td7"]`).contains( response.body.payment_method, ); cy.get(`[data-table-location="Orders_tr1_td8"]`).contains( response.body.payment_method_type, ); cy.get(`[data-table-location="Orders_tr1_td9"]`).contains("NA"); cy.get(`[data-table-location="Orders_tr1_td10"]`).contains( response.body.connector_transaction_id, ); cy.get(`[data-table-location="Orders_tr1_td11"]`).contains( response.body.email, ); cy.get(`[data-table-location="Orders_tr1_td12"]`).contains( response.body.merchant_order_reference_id, ); cy.get(`[class="text-sm font-extrabold cursor-pointer"]`).click(); cy.get(`[data-table-location="Orders_tr1_td13"]`).contains( response.body.description, ); cy.get(`[data-table-location="Orders_tr1_td14"]`).contains( JSON.stringify(response.body.metadata), ); }); }); }); //Columns it("Should display all default columns and allow selecting/deselecting columns", () => { const columns = { expected: [ "Merchant Order Reference Id", "Metadata", "Payment Status", "Payment Method Type", "Payment Method", "Payment ID", "Customer Email", "Description", "Created", "Connector Transaction ID", "Connector", "Amount", "AmountCapturable", "Authentication Type", "Profile Id", "Capture Method", "Client Secret", "Currency", "Customer ID", "Merchant ID", "Setup Future Usage", "Attempt count", ], optional: [ "AmountCapturable", "Authentication Type", "Capture Method", "Client Secret", "Currency", "Customer ID", "Merchant ID", "Setup Future Usage", "Attempt count", ], mandatory: [ "Merchant Order Reference Id", "Metadata", "Payment Status", "Payment Method Type", "Payment Method", "Payment ID", "Customer Email", "Description", "Created", "Connector Transaction ID", "Connector", "Amount", ], }; let merchant_id; homePage.merchantID .eq(0) .invoke("text") .then((text) => { merchant_id = text; cy.createDummyConnectorAPI(merchant_id, "stripe_test_1"); cy.createPaymentAPI(merchant_id); }); homePage.operations.click(); homePage.paymentOperations.click(); cy.get('button[data-button-for="CustomIcon"]').click(); columns.expected.forEach((column) => { cy.contains(column).should("exist"); }); cy.get( '[data-component="modal:Table Columns"] [data-dropdown-numeric]', ).each(($el) => { cy.wrap($el).click(); }); cy.contains("button", `${columnSize} Columns Selected`).should( "be.visible", ); columns.optional.forEach((column) => { cy.get(`[data-dropdown-value="${column}"]`).click(); }); cy.contains("button", `${requiredColumnsSize} Columns Selected`).should( "be.visible", ); cy.get( '[data-component="modal:Table Columns"] [data-icon="modal-close-icon"]', ).click(); columns.mandatory.forEach((column) => { cy.get(`[data-table-heading="${column}"]`).should("exist"); }); columns.optional.forEach((column) => { cy.get(`[data-table-heading="${column}"]`).should("not.exist"); }); }); it("Should display matching columns when searching for valid column names", () => { let merchant_id; homePage.merchantID .eq(0) .invoke("text") .then((text) => { merchant_id = text; cy.createDummyConnectorAPI(merchant_id, "stripe_test_1"); cy.createPaymentAPI(merchant_id); }); homePage.operations.click(); homePage.paymentOperations.click(); cy.get('button[data-button-for="CustomIcon"]').should("be.visible").click(); cy.get(".border > .rounded-md").should( "be.visible", "have.attr", "placeholder", `Search in ${columnSize} options`, ); ["Merchant", "Profile", "Payment"].forEach((searchTerm) => { cy.get(`input[placeholder="Search in ${columnSize} options"]`) .clear() .type(searchTerm); cy.contains(searchTerm).should("exist"); }); }); it("Should show 'No matching records found' when searching for invalid column names", () => { let merchant_id; homePage.merchantID .eq(0) .invoke("text") .then((text) => { merchant_id = text; cy.createDummyConnectorAPI(merchant_id, "stripe_test_1"); cy.createPaymentAPI(merchant_id); }); homePage.operations.click(); homePage.paymentOperations.click(); cy.get('button[data-button-for="CustomIcon"]').click(); cy.get(`input[placeholder="Search in ${columnSize} options"]`).should( "be.visible", ); ["abacd", "something", "createdAt"].forEach((searchTerm) => { cy.get(`input[placeholder="Search in ${columnSize} options"]`) .clear() .type(searchTerm); cy.contains("No matching records found").should("be.visible"); }); cy.get('[data-icon="searchExit"]').click(); cy.get( '[data-component="modal:Table Columns"] [data-dropdown-numeric]', ).should("have.length", columnSize); }); //Search bar // Filters // Views // Date Selector // Payment details page });
2,469
10,208
hyperswitch-control-center
cypress/support/e2e.js
.js
// *********************************************************** // This example support/e2e.js is processed and // loaded automatically before your test files. // // This is a great place to put global configuration and // behavior that modifies Cypress. // // You can change the location of this file or turn off // automatically serving support files with the // 'supportFile' configuration option. // // You can read more here: // https://on.cypress.io/configuration // *********************************************************** // Import commands.js using ES2015 syntax: import "@cypress/code-coverage/support"; import "./commands"; // Alternatively you can use CommonJS syntax: // require('./commands')
131
10,209
hyperswitch-control-center
cypress/support/permissions.js
.js
// Define roles and permissions for each section export const rolePermissions = { admin: { operations: "write", connectors: "write", analytics: "read", workflows: "write", reconOps: "write", reconReports: "write", users: "write", account: "write", }, customer_support: { operations: "read", connectors: "read", analytics: "read", reconOps: "read", reconReports: "read", users: "read", account: "read", }, developer: { operations: "read", connectors: "read", analytics: "read", reconOps: "read", reconReports: "read", users: "read", account: "write", }, iam_admin: { operations: "read", connectors: "read", analytics: "read", users: "write", account: "read", }, operator: { operations: "write", connectors: "read", analytics: "read", workflows: "read", reconOps: "write", reconReports: "read", users: "read", account: "read", }, view_only: { operations: "read", connectors: "read", analytics: "read", workflows: "read", reconOps: "read", reconReports: "read", users: "read", account: "read", }, }; // Define access levels for each user role export const accessLevels = ["org", "merchant", "profile"]; // Permissions matrix to check role-access-level combinations export const permissionsMatrix = { org: { operations: ["admin"], connectors: ["admin"], analytics: ["admin"], workflows: ["admin"], reconOps: ["admin"], reconReports: ["admin"], users: ["admin"], account: ["admin"], }, merchant: { operations: [ "admin", "customer_support", "developer", "iam_admin", "operator", "view_only", ], connectors: [ "admin", "customer_support", "developer", "iam_admin", "operator", "view_only", ], analytics: [ "admin", "customer_support", "developer", "iam_admin", "operator", "view_only", ], workflows: ["admin", "operator", "view_only"], reconOps: [ "admin", "customer_support", "developer", "operator", "view_only", ], reconReports: [ "admin", "customer_support", "developer", "operator", "view_only", ], users: [ "admin", "customer_support", "developer", "iam_admin", "operator", "view_only", ], account: [ "admin", "customer_support", "developer", "iam_admin", "operator", "view_only", ], }, profile: { operations: [ "admin", "customer_support", "developer", "iam_admin", "operator", "view_only", ], connectors: [ "admin", "customer_support", "developer", "iam_admin", "operator", "view_only", ], analytics: [ "admin", "customer_support", "developer", "iam_admin", "operator", "view_only", ], workflows: ["admin", "operator", "view_only"], users: [ "admin", "customer_support", "developer", "iam_admin", "operator", "view_only", ], account: [ "admin", "customer_support", "developer", "iam_admin", "operator", "view_only", ], }, }; // Function to check if a role has permission to access a section export const hasPermission = (role, section, permission) => { return rolePermissions[role] && rolePermissions[role][section] === permission; }; // Function to check if role has access to the section at a certain access level export const hasAccessLevelPermission = (accessLevel, role, section) => { return ( permissionsMatrix[accessLevel] && permissionsMatrix[accessLevel][section]?.includes(role) ); };
952
10,210
hyperswitch-control-center
cypress/support/helper.js
.js
module.exports = { generateUniqueEmail, generateDateTimeString }; function generateUniqueEmail() { const email = `cypress+org_admin_${Math.floor(new Date().getTime() / 1000)}@test.com`; return email; } function generateDateTimeString() { const now = new Date(); return now .toISOString() .replace(/[-:.T]/g, "") .slice(0, 14); }
95
10,211
hyperswitch-control-center
cypress/support/commands.js
.js
// *********************************************** // This example commands.js shows you how to // create various custom commands and overwrite // existing commands. // // For more comprehensive examples of custom // commands please read more here: // https://on.cypress.io/custom-commands // *********************************************** // // // -- This is a parent command -- // Cypress.Commands.add('login', (email, password) => { ... }) // // // -- This is a child command -- // Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... }) // // // -- This is a dual command -- // Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... }) // // // -- This will overwrite an existing command -- // Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... }) import { v4 as uuidv4 } from "uuid"; import * as helper from "../support/helper"; import SignInPage from "../support/pages/auth/SignInPage"; import SignUpPage from "../support/pages/auth/SignUpPage"; import ResetPasswordPage from "../support/pages/auth/ResetPasswordPage"; import { rolePermissions, hasPermission, hasAccessLevelPermission, } from "../support/permissions"; const signinPage = new SignInPage(); const signupPage = new SignUpPage(); const resetPasswordPage = new ResetPasswordPage(); // Custom command to check permissions and decide whether to skip or run the test Cypress.Commands.add("checkPermissionsFromTestName", (testName) => { const rbac = Cypress.env("RBAC").split(","); const userAccessLevel = rbac[0]; // "Access Level" const userRole = rbac[1]; // "Role" // Extract tags from the test name using a regex const regex = /@([a-zA-Z0-9_-]+)/g; const tags = [...testName.matchAll(regex)].map((match) => match[1]); // Parse the tags from test case name and get "section" and "accessLevel" const sectionTag = tags.find((tag) => [ "operations", "connectors", "analytics", "workflows", "reconOps", "reconReports", "users", "account", ].includes(tag), ); const accessLevelTag = tags.find((tag) => ["org", "merchant", "profile"].includes(tag), ); const permissionTag = rolePermissions[userRole] && rolePermissions[userRole][sectionTag]; // Default values if no tags are found in the name const requiredSection = sectionTag || "users"; // Default to 'analytics' const requiredAccessLevel = accessLevelTag || "org"; // Default to 'org' const requiredPermission = permissionTag || "write"; // Default to 'write' // Check access level and run the test based on the user’s access level if (userAccessLevel === "profile") { // If the user is at 'profile' access level, run tests with the 'profile' tag only if (!tags.includes("profile")) { Cypress.log({ name: "Test skipped", message: `Skipping test for "${requiredSection}" section: User access level from env is 'profile' and this test is not tagged with 'profile'`, }); return true; } } else if (userAccessLevel === "merchant") { // If the user is at 'merchant' access level, run tests with 'merchant' or 'profile' tag if (!tags.includes("merchant") && !tags.includes("profile")) { Cypress.log({ name: "Test skipped", message: `Skipping test for "${requiredSection}" section: User access level from env is 'merchant' and this test is not tagged with 'merchant' or 'profile'`, }); return true; // Skip the test } } else if (userAccessLevel === "org") { // If the user is at 'org' access level, run tests with 'org', 'merchant', or 'profile' tag if ( !tags.includes("org") && !tags.includes("merchant") && !tags.includes("profile") ) { Cypress.log({ name: "Test skipped", message: `Skipping test for "${requiredSection}" section: User access level from env is 'org' and this test is not tagged with 'org', 'merchant', or 'profile'`, }); return true; // Skip the test } } // Validate if user has access level permission to the section const canAccess = hasAccessLevelPermission( userAccessLevel, userRole, requiredSection, ); if (!canAccess) { Cypress.log({ name: "Test Skipped", message: `Skipping ${requiredSection} test due to insufficient access level`, }); return true; // Skip the test } // Validate if user has the correct permission (read/write) const hasCorrectPermission = hasPermission( userRole, requiredSection, requiredPermission, ); if (!hasCorrectPermission) { Cypress.log({ name: "Test Skipped", message: `Skipping ${requiredSection} test due to insufficient permissions (${requiredPermission})`, }); return true; // Skip the test } }); Cypress.Commands.add("visit_signupPage", () => { cy.visit("/"); signinPage.signUpLink.click(); cy.url().should("include", "/register"); }); Cypress.Commands.add("enable_email_feature_flag", () => { cy.intercept("GET", "/dashboard/config/feature?domain=", { statusCode: 200, body: { theme: { primary_color: "#006DF9", primary_hover_color: "#005ED6", sidebar_color: "#242F48", }, endpoints: { api_url: "http://localhost:9000/api", }, features: { email: true, }, }, }).as("getFeatureData"); cy.visit("/"); cy.wait("@getFeatureData"); }); Cypress.Commands.add("mock_magic_link_signin_success", (user_email = "") => { const email = user_email.length > 0 ? user_email : Cypress.env("CYPRESS_USERNAME"); cy.intercept("POST", "/api/user/connect_account?auth_id=&domain=", { statusCode: 200, body: { is_email_sent: true, }, }).as("getMagicLinkSuccess"); }); Cypress.Commands.add("signup_API", (name = "", pass = "") => { const username = name.length > 0 ? name : Cypress.env("CYPRESS_USERNAME"); const password = pass.length > 0 ? pass : Cypress.env("CYPRESS_PASSWORD"); cy.request({ method: "POST", url: `http://localhost:8080/user/signup_with_merchant_id`, headers: { "Content-Type": "application/json", "api-key": "test_admin", }, body: { email: username, password: password, company_name: helper.generateDateTimeString(), name: "Cypress_test_user", }, }) .then((response) => { expect(response.status).to.be.within(200, 299); }) .should((response) => { // Check if there was an error in the response if (response.status >= 400) { throw new Error(`Request failed with status: ${response.status}`); } }); }); Cypress.Commands.add("login_API", (name = "", pass = "") => { const username = name.length > 0 ? name : Cypress.env("CYPRESS_USERNAME"); const password = pass.length > 0 ? pass : Cypress.env("CYPRESS_PASSWORD"); // /user/signin cy.request({ method: "POST", url: `http://localhost:9000/api/user/signin`, headers: { "Content-Type": "application/json", }, body: { email: username, password: password, country: "IN" }, }); }); Cypress.Commands.add("login_UI", (name = "", pass = "") => { cy.visit("/"); const username = name.length > 0 ? name : Cypress.env("CYPRESS_USERNAME"); const password = pass.length > 0 ? pass : Cypress.env("CYPRESS_PASSWORD"); signinPage.emailInput.type(username); signinPage.passwordInput.type(password); signinPage.signinButton.click(); signinPage.skip2FAButton.click(); }); Cypress.Commands.add("createAPIKey", (merchant_id) => { return cy .request({ method: "POST", url: `http://localhost:8080/api_keys/${merchant_id}`, headers: { "Content-Type": "application/json", Accept: "application/json", "api-key": "test_admin", }, body: { name: "API Key 1", description: null, expiration: "2060-09-23T01:02:03.000Z", }, }) .then((response) => { const apiKey = response.body.api_key; return apiKey; }); }); Cypress.Commands.add( "createDummyConnectorAPI", (merchant_id, connector_label) => { cy.createAPIKey(merchant_id).then((apiKey) => { cy.request({ method: "POST", url: `http://localhost:8080/account/${merchant_id}/connectors`, headers: { "Content-Type": "application/json", Accept: "application/json", "api-key": apiKey, // Pass the apiKey here }, body: { connector_type: "payment_processor", connector_name: "stripe_test", connector_label: `${connector_label}`, connector_account_details: { api_key: "test_key", auth_type: "HeaderKey", }, status: "active", test_mode: true, payment_methods_enabled: [ { payment_method: "card", payment_method_types: [ { payment_method_type: "debit", card_networks: ["Mastercard"], minimum_amount: 0, maximum_amount: 68607706, recurring_enabled: true, installment_payment_enabled: false, }, { payment_method_type: "debit", card_networks: ["Visa"], minimum_amount: 0, maximum_amount: 68607706, recurring_enabled: true, installment_payment_enabled: false, }, ], }, { payment_method: "card", payment_method_types: [ { payment_method_type: "credit", card_networks: ["Mastercard"], minimum_amount: 0, maximum_amount: 68607706, recurring_enabled: true, installment_payment_enabled: false, }, { payment_method_type: "credit", card_networks: ["Visa"], minimum_amount: 0, maximum_amount: 68607706, recurring_enabled: true, installment_payment_enabled: false, }, ], }, ], }, }); }); }, ); Cypress.Commands.add("create_connector_UI", () => { cy.get("[data-testid=connectors]").click(); cy.get("[data-testid=paymentprocessors]").click(); cy.contains("Payment Processors").should("be.visible"); cy.contains("Connect a Dummy Processor").should("be.visible"); cy.get("[data-button-for=connectNow]").click({ force: true, }); cy.get('[data-component="modal:Connect a Dummy Processor"]', { timeout: 10000, }) .find("button") .should("have.length", 4); cy.contains("Stripe Dummy").should("be.visible"); cy.get('[data-testid="stripe_test"]').find("button").click({ force: true }); cy.url().should("include", "/dashboard/connectors"); cy.contains("Credentials").should("be.visible"); cy.get("[name=connector_account_details\\.api_key]") .clear() .type("dummy_api_key"); cy.get("[name=connector_label]").clear().type("stripe_test_default_label"); cy.get("[data-button-for=connectAndProceed]").click(); cy.get("[data-testid=credit_select_all]").click(); cy.get("[data-testid=credit_mastercard]").click(); cy.get("[data-testid=debit_cartesbancaires]").click(); cy.get("[data-testid=pay_later_klarna]").click(); cy.get("[data-testid=wallet_we_chat_pay]").click(); cy.get("[data-button-for=proceed]").click(); cy.get('[data-toast="Connector Created Successfully!"]', { timeout: 10000, }).click(); cy.get("[data-button-for=done]").click(); cy.url().should("include", "/dashboard/connectors"); cy.contains("stripe_test_default_label") .scrollIntoView() .should("be.visible"); }); Cypress.Commands.add("deleteConnector", (mca_id) => { let token = window.localStorage.getItem("login"); let { merchant_id = "" } = JSON.parse( window.localStorage.getItem("merchant"), ); cy.request({ method: "DELETE", url: `http://localhost:9000/api/account/${merchant_id}/connectors/${mca_id}`, headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); }); Cypress.Commands.add("createPaymentAPI", (merchant_id) => { cy.createAPIKey(merchant_id).then((apiKey) => { cy.request({ method: "POST", url: `http://localhost:8080/payments`, headers: { "Content-Type": "application/json", Accept: "application/json", "api-key": apiKey, // Pass the apiKey here }, body: { amount: 10000, currency: "USD", confirm: true, capture_method: "automatic", customer_id: "test_customer", authentication_type: "no_three_ds", return_url: "https://google.com", email: "abc@test.com", name: "Joseph Doe", phone: "999999999", phone_country_code: "+65", merchant_order_reference_id: "abcd", description: "Its my first payment", statement_descriptor_name: "Juspay", statement_descriptor_suffix: "Router", payment_method: "card", payment_method_type: "credit", payment_method_data: { card: { card_number: "4242424242424242", card_exp_month: "01", card_exp_year: "2027", card_holder_name: "joseph Doe", card_cvc: "100", nick_name: "hehe", }, }, billing: { address: { city: "Toronto", country: "CA", line1: "1562", line2: "HarrisonStreet", line3: "HarrisonStreet", zip: "M3C 0C1", state: "ON", first_name: "Joseph", last_name: "Doe", }, phone: { number: "8056594427", country_code: "+91", }, email: "abc@test.com", }, shipping: { address: { city: "Toronto", country: "CA", line1: "1562", line2: "HarrisonStreet", line3: "HarrisonStreet", zip: "M3C 0C1", state: "ON", first_name: "Joseph", last_name: "Doe", }, phone: { number: "8056594427", country_code: "+91", }, email: "abc@test.com", }, metadata: { key: "value", }, }, }); }); }); Cypress.Commands.add("process_payment_sdk_UI", () => { cy.clearCookies("login_token"); cy.get("[data-testid=connectors]").click(); cy.get("[data-testid=paymentprocessors]").click(); cy.contains("Payment Processors").should("be.visible"); cy.get("[data-testid=home]").first().click(); cy.get("[data-button-for=tryItOut]").click(); cy.get('[data-breadcrumb="Explore Demo Checkout Experience"]').should( "exist", ); cy.get("[data-testid=amount]").find("input").clear().type("77"); cy.get("[data-button-for=showPreview]").click(); cy.wait(2000); getIframeBody() .find("[data-testid=cardNoInput]", { timeout: 20000 }) .should("exist") .type("4242424242424242"); getIframeBody() .find("[data-testid=expiryInput]") .should("exist") .type("0127"); getIframeBody() .find("[data-testid=cvvInput]") .should("exist") .scrollIntoView() .type("492"); cy.get("[data-button-for=payUSD77]").click(); cy.contains("Payment Successful").should("exist"); // cy.get("[data-button-for=goToPayment]").click(); // cy.url().should("include", "dashboard/payments"); }); Cypress.Commands.add("sign_up_with_email", (username, password) => { cy.url().should("include", "/register"); signupPage.emailInput.type(username); signupPage.signUpButton.click(); cy.get("[data-testid=card-header]").should( "contain", "Please check your inbox", ); cy.visit(Cypress.env("MAIL_URL")); cy.get("div.messages > div:nth-child(2)").click(); cy.wait(1000); cy.get("iframe").then(($iframe) => { // Verify email const doc = $iframe.contents(); const verifyEmail = doc.find("a").get(0); cy.visit(verifyEmail.href); signinPage.skip2FAButton.click(); // Set password resetPasswordPage.createPassword.type(password); resetPasswordPage.confirmPassword.type(password); resetPasswordPage.confirmButton.click(); // Login to dashboard signinPage.emailInput.type(username); signinPage.passwordInput.type(password); signinPage.signinButton.click(); // Skip 2FA signinPage.skip2FAButton.click(); }); }); Cypress.Commands.add("redirect_from_mail_inbox", () => { cy.visit(Cypress.env("MAIL_URL")); cy.get("div.messages > div:nth-child(2)").click(); cy.wait(1000); cy.get("iframe").then(($iframe) => { // Verify email const doc = $iframe.contents(); const verifyEmail = doc.find("a").get(0); cy.visit(verifyEmail.href); }); }); const getIframeBody = () => { return cy .get("iframe") .its("0.contentDocument.body") .should("not.be.empty") .then(cy.wrap); };
4,247
10,212
hyperswitch-control-center
cypress/support/pages/homepage/HomePage.js
.js
class HomePage { // Onboarding get enterMerchantName() { return cy.get('[name="merchant_name"]'); } get onboardingSubmitButton() { return cy.get('[data-button-for="startExploring"]'); } get orgDropdown() { return cy.get(); } get merchantDropdown() { return cy.get(); } get profileDropdown() { return cy.get('[class="md:max-w-40 max-w-16"]'); } get profileDropdownList() { return cy.get( '[class="max-h-72 overflow-scroll px-1 pt-1 sidebar-scrollbar"]', ); } get merchantID() { return cy.get('[style="overflow-wrap: anywhere;"]'); } //Sidebar //Operations get operations() { return cy.get("[data-testid=operations]"); } get paymentOperations() { return cy.get("[data-testid=payments]"); } //Connectors get connectors() { return cy.get("[data-testid=connectors]"); } get paymentProcessors() { return cy.get("[data-testid=paymentprocessors]"); } //Workflow get workflow() { return cy.get('[data-testid="workflow"]'); } get routing() { return cy.get('[data-testid="routing"]'); } } export default HomePage;
290
10,213
hyperswitch-control-center
cypress/support/pages/workflow/paymentRouting/VolumeBasedConfiguration.js
.js
class VolumeBasedConfiguration { get connectorDropdown() { return cy.get(`[data-value="addProcessors"]`); } } export default VolumeBasedConfiguration;
34
10,214
hyperswitch-control-center
cypress/support/pages/workflow/paymentRouting/DefaultFallback.js
.js
class DefaultFallback { get defaultFallbackList() { return cy.get('[class="flex flex-col w-full"]'); } get saveChangesButton() { return cy.get('data-button-for="saveChanges"'); } } export default DefaultFallback;
55
10,215
hyperswitch-control-center
cypress/support/pages/workflow/paymentRouting/PaymentRouting.js
.js
class PaymentRouting { // get volumeBasedRoutingSetupButton() { return cy.get('[data-button-for="setup"]').eq(0); } get volumeBasedRoutingHeader() { return cy.get('[class="flex items-center gap-4"]'); } get ruleBasedRoutingSetupButton() { return cy.get('[data-button-for="setup"]').eq(1); } get defaultFallbackManageButton() { return cy.get('[data-button-for="manage"]'); } } export default PaymentRouting;
109
10,216
hyperswitch-control-center
cypress/support/pages/operations/PaymentOperations.js
.js
class PaymentOperations { get searchBox() { return cy.get(`[name="name"]`); } get dateSelector() { return cy.get(`[data-testid="date-range-selector"]`); } get viewDropdown() { return cy.get(`[class="flex h-fit rounded-lg hover:bg-opacity-80"]`); } get addFilters() { return cy.get(`[data-icon="plus"]`); } get generateReports() { return cy.get(`[data-button-for="generateReports"]`); } get columnButton() { return cy.get(`[data-button-for="CustomIcon"]`); } } export default PaymentOperations;
144
10,217
hyperswitch-control-center
cypress/support/pages/auth/ResetPasswordPage.js
.js
class ResetPasswordPage { get createPassword() { return cy.get('[name="create_password"]'); } get confirmPassword() { return cy.get('[data-testid="comfirm_password"]').children().eq(1); } get eyeIcon() { return cy.get('[data-icon="eye-slash"]'); } get confirmButton() { return cy.get('[data-button-for="confirm"]'); } get newPasswordField() { return cy.get(`[data-testid="create_password"]`); } get confirmPasswordField() { return cy.get(`[data-testid="comfirm_password"]`); } } export default ResetPasswordPage;
137
10,218
hyperswitch-control-center
cypress/support/pages/auth/SignUpPage.js
.js
class SignUpPage { get headerText() { return cy.get('[data-testid="card-header"]'); } get signInLink() { return cy.get('[data-testid="card-subtitle"]'); } get emailInput() { return cy.get('[data-testid="email"]').children().first(); } get passwordInput() { return cy.get('[data-testid="password"]').children().eq(1); } get signUpButton() { return cy.get('[data-testid="auth-submit-btn"]').children().eq(1); } get invalidInputError() { return cy.get("[data-form-error]"); } get footerText() { return cy.get('[data-testid="card-foot-text"]'); } signup(email, password) { cy.visit("/register"); this.emailInput.type(email); this.passwordInput.type(password); this.signUpButton.click(); } } export default SignUpPage;
195
10,219
hyperswitch-control-center
cypress/support/pages/auth/SignInPage.js
.js
class SignInPage { get emailInput() { return cy.get('[data-testid="email"]'); } get passwordInput() { return cy.get('[data-testid="password"]'); } get signinButton() { return cy.get('[data-button-for="continue"]'); } get signUpLink() { return cy.get("#card-subtitle"); } get headerText() { return cy.get("#card-header"); } get tcText() { return cy.get("#tc-text"); } get footerText() { return cy.get("#footer"); } get forgetPasswordLink() { return cy.get('[data-testid="forgot-password"]'); } get emailSigninLink() { return cy.get('[data-testid="card-foot-text"]'); } get invalidCredsToast() { return cy.get('[data-toast="Incorrect email or password"]'); } // 2FA setup get headerText2FA() { return cy.get('[class="text-2xl font-semibold leading-8 text-grey-900"]'); } get instructions2FA() { return cy.get('[class="flex flex-col gap-10 col-span-3"]'); } get otpBox2FA() { return cy.get('[class="flex flex-col gap-4 items-center"]'); } get skip2FAButton() { return cy.get('[data-testid="skip-now"]'); } get enable2FA() { return cy.get('[data-button-for="enable2FA"]'); } get footerText2FA() { return cy.get('[class="text-grey-200 flex gap-2"]'); } //Forget password get forgetPasswordHeader() { return cy.get('[data-testid="card-header"]'); } get resetPasswordButton() { return cy.get('[data-testid="auth-submit-btn"]').children().eq(1); } get cancelForgetPassword() { return cy.get('[data-testid="card-foot-text"]'); } } export default SignInPage;
432
10,220