@@ -52,7 +50,7 @@ module AdvanceSettings = {
- >
+
}
}
diff --git a/src/screens/HyperSwitch/FraudAndRisk/FRMPaymentMethods.res b/src/screens/HyperSwitch/FraudAndRisk/FRMPaymentMethods.res
index 1c16dbcce..f3966caab 100644
--- a/src/screens/HyperSwitch/FraudAndRisk/FRMPaymentMethods.res
+++ b/src/screens/HyperSwitch/FraudAndRisk/FRMPaymentMethods.res
@@ -1,6 +1,3 @@
-external convertToJsonDict: 't => Js.Dict.t = "%identity"
-external asJson: 'a => ReactEvent.Form.t = "%identity"
-
module RadioSection = {
open ConnectorTypes
open FRMTypes
@@ -26,7 +23,7 @@ module RadioSection = {
| ActionType => paymentMethodTypeInfo.action = option
}
- setConfigJson(frmConfigs->asJson)
+ setConfigJson(frmConfigs->Identity.anyTypeToReactEvent)
}
@@ -147,7 +144,7 @@ module CheckBoxRenderer = {
_ => {
frmConfigInfo.payment_methods = []
setIsOpen(_ => !isOpen)
- setConfigJson(frmConfigs->asJson)
+ setConfigJson(frmConfigs->Identity.anyTypeToReactEvent)
}
},
},
@@ -166,7 +163,7 @@ module CheckBoxRenderer = {
switch connectorPaymentMethods {
| Some(paymentMethods) => {
frmConfigInfo.payment_methods = paymentMethods->generateFRMPaymentMethodsConfig
- setConfigJson(frmConfigs->asJson)
+ setConfigJson(frmConfigs->Identity.anyTypeToReactEvent)
}
| _ => ()
}
@@ -176,7 +173,7 @@ module CheckBoxRenderer = {
showConfitmation()
} else {
frmConfigInfo.payment_methods = []
- setConfigJson(frmConfigs->asJson)
+ setConfigJson(frmConfigs->Identity.anyTypeToReactEvent)
setIsOpen(_ => !isOpen)
}
}
@@ -188,7 +185,7 @@ module CheckBoxRenderer = {
switch connectorPaymentMethods {
| Some(paymentMethods) => {
frmConfigInfo.payment_methods = paymentMethods->generateFRMPaymentMethodsConfig
- setConfigJson(frmConfigs->asJson)
+ setConfigJson(frmConfigs->Identity.anyTypeToReactEvent)
}
| _ => ()
}
@@ -298,7 +295,7 @@ module PaymentMethodsRenderer = {
})
setConnectorConfig(_ => connectorsConfig)
- setConfigJson(updateFRMConfig->asJson)
+ setConfigJson(updateFRMConfig->Identity.anyTypeToReactEvent)
setPageState(_ => Success)
} catch {
| _ => setPageState(_ => Error("Failed to fetch"))
@@ -345,7 +342,7 @@ let make = (~setCurrentStep, ~retrivedValues=None, ~setInitialValues, ~isUpdateF
->parseFRMConfig
->Js.Array2.filter(config => config.payment_methods->Js.Array2.length > 0)
- valuesDict->Js.Dict.set("frm_configs", filteredArray->toJson)
+ valuesDict->Js.Dict.set("frm_configs", filteredArray->Identity.genericTypeToJson)
setInitialValues(_ => valuesDict->Js.Json.object_)
setCurrentStep(prev => prev->getNextStep)
diff --git a/src/screens/HyperSwitch/FraudAndRisk/FRMSummary.res b/src/screens/HyperSwitch/FraudAndRisk/FRMSummary.res
index 255e5eff6..a967599f2 100644
--- a/src/screens/HyperSwitch/FraudAndRisk/FRMSummary.res
+++ b/src/screens/HyperSwitch/FraudAndRisk/FRMSummary.res
@@ -130,20 +130,6 @@ let make = (~initialValues, ~currentStep, ~setCurrentStep, ~isUpdateFlow) => {
}}
-
-
{"Processor Mode"->React.string}
-
- {if frmInfo.test_mode {
-
- {"TEST MODE"->React.string}
-
- } else {
-
- {"LIVE MODE"->React.string}
-
- }}
-
-
{"Profile id"->React.string}
{frmInfo.profile_id->React.string}
diff --git a/src/screens/HyperSwitch/FraudAndRisk/FRMUtils.res b/src/screens/HyperSwitch/FraudAndRisk/FRMUtils.res
index 1c8228f7e..14d5aa999 100644
--- a/src/screens/HyperSwitch/FraudAndRisk/FRMUtils.res
+++ b/src/screens/HyperSwitch/FraudAndRisk/FRMUtils.res
@@ -17,8 +17,6 @@ let base64Format = (. ~value, ~name as _) => {
value->Js.Json.decodeString->Belt.Option.getWithDefault("")->atob->Js.Json.string
}
-external toJson: 'a => Js.Json.t = "%identity"
-
let toggleDefaultStyle = "mb-2 relative inline-flex flex-shrink-0 h-6 w-12 border-2 rounded-full transition-colors ease-in-out duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-opacity-75 items-center"
let accordionDefaultStyle = "border pointer-events-none inline-block h-3 w-3 rounded-full bg-white dark:bg-white shadow-lg transform ring-0 transition ease-in-out duration-200"
diff --git a/src/screens/HyperSwitch/HSwitchUtils.res b/src/screens/HyperSwitch/HSwitchUtils.res
index 5a67af218..82f70eb8a 100644
--- a/src/screens/HyperSwitch/HSwitchUtils.res
+++ b/src/screens/HyperSwitch/HSwitchUtils.res
@@ -16,7 +16,6 @@ type browserDetailsObject = {
let feedbackModalOpenCountForConnectors = 4
-external objToJson: {..} => Js.Json.t = "%identity"
let errorClass = "text-sm leading-4 font-medium text-start ml-1 mt-2"
type pageLevelVariant =
diff --git a/src/screens/HyperSwitch/Home/CommonConnectorFlow/SetupConnector.res b/src/screens/HyperSwitch/Home/CommonConnectorFlow/SetupConnector.res
index 84e126a53..82cdf8b01 100644
--- a/src/screens/HyperSwitch/Home/CommonConnectorFlow/SetupConnector.res
+++ b/src/screens/HyperSwitch/Home/CommonConnectorFlow/SetupConnector.res
@@ -133,9 +133,11 @@ module ConfigureProcessor = {
nextButton={
}>
-
+
+
+
string = "%identity"
open CardUtils
open PageUtils
open HSwitchUtils
diff --git a/src/screens/HyperSwitch/Home/QuickStart/IntegrateYourApp/IntegrateFromScratch.res b/src/screens/HyperSwitch/Home/QuickStart/IntegrateYourApp/IntegrateFromScratch.res
index a85045ad2..073c4f22d 100644
--- a/src/screens/HyperSwitch/Home/QuickStart/IntegrateYourApp/IntegrateFromScratch.res
+++ b/src/screens/HyperSwitch/Home/QuickStart/IntegrateYourApp/IntegrateFromScratch.res
@@ -14,6 +14,7 @@ let make = (
let (currentStep, setCurrentStep) = React.useState(_ => DownloadTestAPIKey)
let {setQuickStartPageState} = React.useContext(GlobalProvider.defaultContext)
let isLastStep = currentStep === DisplayPaymentConfirmation
+ let updateEnumInRecoil = EnumVariantHook.useUpdateEnumInRecoil()
let theme = switch ThemeProvider.useTheme() {
| Dark => "vs-dark"
@@ -25,10 +26,18 @@ let make = (
buttonState={Normal}
buttonType={PrimaryOutline}
text="Back"
- onClick={_ =>
- currentStep === DownloadTestAPIKey
- ? setQuickStartPageState(_ => IntegrateApp(CHOOSE_INTEGRATION))
- : setCurrentStep(_ => getNavigationStepForStandardIntegration(~currentStep, ()))}
+ onClick={_ => {
+ let prevStep = getNavigationStepForStandardIntegration(~currentStep, ())
+ if currentStep === DownloadTestAPIKey {
+ setQuickStartPageState(_ => IntegrateApp(CHOOSE_INTEGRATION))
+ } else {
+ let _ = updateEnumInRecoil([
+ (String("pending"), currentStep->getPolyMorphicVariantOfIntegrationSubStep),
+ (String("ongoing"), prevStep->getPolyMorphicVariantOfIntegrationSubStep),
+ ])
+ setCurrentStep(_ => prevStep)
+ }
+ }}
buttonSize=Small
/>
@@ -40,9 +49,13 @@ let make = (
if isLastStep {
markAsDone()->ignore
} else {
- setCurrentStep(_ =>
- getNavigationStepForStandardIntegration(~currentStep, ~forward=true, ())
- )
+ let nextStep = getNavigationStepForStandardIntegration(~currentStep, ~forward=true, ())
+ let _ = updateEnumInRecoil([
+ (String("completed"), currentStep->getPolyMorphicVariantOfIntegrationSubStep),
+ (String("ongoing"), nextStep->getPolyMorphicVariantOfIntegrationSubStep),
+ ])
+
+ setCurrentStep(_ => nextStep)
}
}}
buttonSize=Small
diff --git a/src/screens/HyperSwitch/Home/QuickStart/IntegrateYourApp/IntegrateYourAppUtils.res b/src/screens/HyperSwitch/Home/QuickStart/IntegrateYourApp/IntegrateYourAppUtils.res
index 35abaf046..2b24edd6b 100644
--- a/src/screens/HyperSwitch/Home/QuickStart/IntegrateYourApp/IntegrateYourAppUtils.res
+++ b/src/screens/HyperSwitch/Home/QuickStart/IntegrateYourApp/IntegrateYourAppUtils.res
@@ -45,3 +45,26 @@ let getNavigationStepForStandardIntegration = (
| DisplayPaymentConfirmation => forward ? DisplayPaymentConfirmation : DisplayCheckout
}
}
+
+let getPolyMorphicVariantOfIntegrationSubStep: standardIntegrationSteps => QuickStartTypes.sectionHeadingVariant = (
+ currentStep: standardIntegrationSteps,
+) => {
+ switch currentStep {
+ | DownloadTestAPIKey => #DownloadTestAPIKey
+ | CreatePayment => #CreatePayment
+ | DisplayCheckout => #DisplayCheckout
+ | DisplayPaymentConfirmation => #DisplayPaymentConfirmation
+ }
+}
+
+let getPolyMorphicVariantOfMigrateFromStripe: migrateFromStripeSteps => QuickStartTypes.sectionHeadingVariant = (
+ currentStep: migrateFromStripeSteps,
+) => {
+ switch currentStep {
+ | DownloadAPIKey => #DownloadTestAPIKeyStripe
+ | InstallDeps => #InstallDeps
+ | ReplaceAPIKeys => #ReplaceAPIKeys
+ | ReconfigureCheckout => #ReconfigureCheckout
+ | LoadCheckout => #LoadCheckout
+ }
+}
diff --git a/src/screens/HyperSwitch/Home/QuickStart/IntegrateYourApp/MigrateFromStripe.res b/src/screens/HyperSwitch/Home/QuickStart/IntegrateYourApp/MigrateFromStripe.res
index 0d1b1f156..562726bee 100644
--- a/src/screens/HyperSwitch/Home/QuickStart/IntegrateYourApp/MigrateFromStripe.res
+++ b/src/screens/HyperSwitch/Home/QuickStart/IntegrateYourApp/MigrateFromStripe.res
@@ -14,6 +14,7 @@ let make = (
let (currentStep, setCurrentStep) = React.useState(_ => DownloadAPIKey)
let {setQuickStartPageState} = React.useContext(GlobalProvider.defaultContext)
let isLastStep = currentStep === LoadCheckout
+ let updateEnumInRecoil = EnumVariantHook.useUpdateEnumInRecoil()
let theme = switch ThemeProvider.useTheme() {
| Dark => "vs-dark"
@@ -25,10 +26,18 @@ let make = (
buttonState={Normal}
buttonType={PrimaryOutline}
text="Back"
- onClick={_ =>
- currentStep === DownloadAPIKey
- ? setQuickStartPageState(_ => IntegrateApp(CHOOSE_INTEGRATION))
- : setCurrentStep(_ => getNavigationStepForMigrateFromStripe(~currentStep, ()))}
+ onClick={_ => {
+ let prevStep = getNavigationStepForMigrateFromStripe(~currentStep, ())
+ if currentStep === DownloadAPIKey {
+ setQuickStartPageState(_ => IntegrateApp(CHOOSE_INTEGRATION))
+ } else {
+ let _ = updateEnumInRecoil([
+ (String("pending"), currentStep->getPolyMorphicVariantOfMigrateFromStripe),
+ (String("ongoing"), prevStep->getPolyMorphicVariantOfMigrateFromStripe),
+ ])
+ setCurrentStep(_ => prevStep)
+ }
+ }}
buttonSize=Small
/>
@@ -40,9 +49,12 @@ let make = (
if isLastStep {
markAsDone()->ignore
} else {
- setCurrentStep(_ =>
- getNavigationStepForMigrateFromStripe(~currentStep, ~forward=true, ())
- )
+ let nextStep = getNavigationStepForMigrateFromStripe(~currentStep, ~forward=true, ())
+ let _ = updateEnumInRecoil([
+ (String("completed"), currentStep->getPolyMorphicVariantOfMigrateFromStripe),
+ (String("ongoing"), nextStep->getPolyMorphicVariantOfMigrateFromStripe),
+ ])
+ setCurrentStep(_ => nextStep)
}
}}
buttonSize=Small
diff --git a/src/screens/HyperSwitch/Home/QuickStart/QuickStartTypes.res b/src/screens/HyperSwitch/Home/QuickStart/QuickStartTypes.res
index 34f0e65c2..caa84a5ac 100644
--- a/src/screens/HyperSwitch/Home/QuickStart/QuickStartTypes.res
+++ b/src/screens/HyperSwitch/Home/QuickStart/QuickStartTypes.res
@@ -47,6 +47,10 @@ type sectionHeadingVariant = [
| #TestPayment
| #IntegrationMethod
| #IntegrationCompleted
+ | #DownloadTestAPIKey
+ | #CreatePayment
+ | #DisplayCheckout
+ | #DisplayPaymentConfirmation
| #StripeConnected
| #PaypalConnected
| #SPRoutingConfigured
@@ -56,6 +60,11 @@ type sectionHeadingVariant = [
| #SetupWoocomWebhook
| #IsMultipleConfiguration
| #GoLive
+ | #DownloadTestAPIKeyStripe
+ | #InstallDeps
+ | #ReplaceAPIKeys
+ | #ReconfigureCheckout
+ | #LoadCheckout
]
type processorType = {
@@ -85,7 +94,17 @@ type responseType = {
configureWoocom: bool,
setupWoocomWebhook: bool,
isMultipleConfiguration: bool,
+ downloadTestAPIKeyStripe: string,
+ installDeps: string,
+ replaceAPIKeys: string,
+ reconfigureCheckout: string,
+ loadCheckout: string,
+ downloadTestAPIKey: string,
+ createPayment: string,
+ displayCheckout: string,
+ displayPaymentConfirmation: string,
}
+
type requestObjectType =
| ProcesorType(processorType)
| RoutingType(routingType)
@@ -93,5 +112,6 @@ type requestObjectType =
| IntegrationMethod(integrationMethod)
| ConnectorChoice(connectorChoice)
| Boolean(bool)
+ | String(string)
type valueType = String(string) | Boolean(bool)
diff --git a/src/screens/HyperSwitch/Home/QuickStart/QuickStartUtils.res b/src/screens/HyperSwitch/Home/QuickStart/QuickStartUtils.res
index 4ae161e6c..7de1e90e6 100644
--- a/src/screens/HyperSwitch/Home/QuickStart/QuickStartUtils.res
+++ b/src/screens/HyperSwitch/Home/QuickStart/QuickStartUtils.res
@@ -169,6 +169,13 @@ let getTypedValueFromDict = valueString => {
->getDictfromDict(#IntegrationMethod->getStringFromVariant)
->getIntegrationType,
integrationCompleted: value->getBool(#IntegrationCompleted->getStringFromVariant, false),
+ downloadTestAPIKey: value->getString(#DownloadTestAPIKey->getStringFromVariant, ""),
+ createPayment: value->getString(#CreatePayment->getStringFromVariant, ""),
+ displayCheckout: value->getString(#DisplayCheckout->getStringFromVariant, ""),
+ displayPaymentConfirmation: value->getString(
+ #DisplayPaymentConfirmation->getStringFromVariant,
+ "",
+ ),
stripeConnected: value
->getDictfromDict(#StripeConnected->getStringFromVariant)
->getProcessorType,
@@ -183,6 +190,11 @@ let getTypedValueFromDict = valueString => {
configureWoocom: value->getBool(#ConfigureWoocom->getStringFromVariant, false),
setupWoocomWebhook: value->getBool(#SetupWoocomWebhook->getStringFromVariant, false),
isMultipleConfiguration: value->getBool(#IsMultipleConfiguration->getStringFromVariant, false),
+ downloadTestAPIKeyStripe: value->getString(#DownloadTestAPIKeyStripe->getStringFromVariant, ""),
+ installDeps: value->getString(#InstallDeps->getStringFromVariant, ""),
+ replaceAPIKeys: value->getString(#ReplaceAPIKeys->getStringFromVariant, ""),
+ reconfigureCheckout: value->getString(#ReconfigureCheckout->getStringFromVariant, ""),
+ loadCheckout: value->getString(#LoadCheckout->getStringFromVariant, ""),
}
typedValue
}
@@ -231,6 +243,17 @@ let getStatusValue = (comparator: valueType, enumVariant, dashboardPageState) =>
boolValue ? COMPLETED : dashboardPageState === enumVariant ? ONGOING : PENDING
}
}
+
+let getStatusFromString = statusString => {
+ open HSSelfServeSidebar
+ switch statusString->Js.String2.toUpperCase {
+ | "PENDING" => PENDING
+ | "COMPLETED" => COMPLETED
+ | "ONGOING" => ONGOING
+ | _ => PENDING
+ }
+}
+
let sidebarTextBasedOnVariant = choiceState =>
switch choiceState {
| #MigrateFromStripe => "Hyperswitch For Stripe Users"
@@ -276,23 +299,23 @@ let getSidebarOptionsForIntegrateYourApp: (
subOptions: [
{
title: "Download Test API Keys",
- status: PENDING,
+ status: enumValue.downloadTestAPIKeyStripe->getStatusFromString,
},
{
title: "Install Dependencies",
- status: PENDING,
+ status: enumValue.installDeps->getStatusFromString,
},
{
title: "Replace API keys",
- status: PENDING,
+ status: enumValue.replaceAPIKeys->getStatusFromString,
},
{
title: "Reconfigure Checkout Form",
- status: PENDING,
+ status: enumValue.reconfigureCheckout->getStatusFromString,
},
{
title: "Load Hyperswitch Checkout",
- status: PENDING,
+ status: enumValue.loadCheckout->getStatusFromString,
},
],
},
@@ -317,19 +340,19 @@ let getSidebarOptionsForIntegrateYourApp: (
subOptions: [
{
title: "Download Test API Key",
- status: PENDING,
+ status: enumValue.downloadTestAPIKey->getStatusFromString,
},
{
title: "Create a Payment",
- status: PENDING,
+ status: enumValue.createPayment->getStatusFromString,
},
{
title: "Display Hyperswitch Checkout",
- status: PENDING,
+ status: enumValue.displayCheckout->getStatusFromString,
},
{
title: "Display Payment Confirmation",
- status: PENDING,
+ status: enumValue.displayPaymentConfirmation->getStatusFromString,
},
],
},
@@ -571,6 +594,7 @@ let generateBodyBasedOnType = (parentVariant: sectionHeadingVariant, value: requ
]->getJsonFromArrayOfJson
| Boolean(_) => (parentVariant :> string)->Js.Json.string
+ | String(str) => str->Js.Json.string
}
}
diff --git a/src/screens/HyperSwitch/Hooks/EnumVariantHook.res b/src/screens/HyperSwitch/Hooks/EnumVariantHook.res
index ae31a0902..0a7ae6a37 100644
--- a/src/screens/HyperSwitch/Hooks/EnumVariantHook.res
+++ b/src/screens/HyperSwitch/Hooks/EnumVariantHook.res
@@ -48,6 +48,10 @@ let useUpdateEnumInRecoil = () => {
let booleanDict = [((enumVariant :> string), true->Js.Json.boolean)]->Js.Dict.fromArray
enumDictsArray->Array.push(booleanDict)
}
+ | String(str) => {
+ let stringDict = [((enumVariant :> string), str->Js.Json.string)]->Js.Dict.fromArray
+ enumDictsArray->Array.push(stringDict)
+ }
| _ => enumDictsArray->Array.push(bodyValForApi->getDictFromJsonObject)
}
})
diff --git a/src/screens/HyperSwitch/Order/OrderUIUtils.res b/src/screens/HyperSwitch/Order/OrderUIUtils.res
index 661ca040a..2514bd116 100644
--- a/src/screens/HyperSwitch/Order/OrderUIUtils.res
+++ b/src/screens/HyperSwitch/Order/OrderUIUtils.res
@@ -100,7 +100,6 @@ let filterUrl = `${HSwitchGlobalVars.hyperSwitchApiPrefix}/payments/filter`
let (startTimeFilterKey, endTimeFilterKey) = ("start_time", "end_time")
-external toDict: 't => Js.Dict.t = "%identity"
let filterByData = (txnArr, value) => {
open LogicUtils
let searchText = value->getStringFromJson("")
@@ -110,7 +109,7 @@ let filterByData = (txnArr, value) => {
->Belt.Array.keepMap(data => {
let valueArr =
data
- ->toDict
+ ->Identity.genericTypeToDictOfJson
->Js.Dict.entries
->Js.Array2.map(item => {
let (_, value) = item
diff --git a/src/screens/HyperSwitch/Refunds/RefundUtils.res b/src/screens/HyperSwitch/Refunds/RefundUtils.res
index 99c9c4868..2421f3469 100644
--- a/src/screens/HyperSwitch/Refunds/RefundUtils.res
+++ b/src/screens/HyperSwitch/Refunds/RefundUtils.res
@@ -48,7 +48,6 @@ let customUI =
let (startTimeFilterKey, endTimeFilterKey) = ("start_time", "end_time")
-external toDict: 't => Js.Dict.t = "%identity"
let filterByData = (txnArr, value) => {
open LogicUtils
let searchText = value->getStringFromJson("")
@@ -58,7 +57,7 @@ let filterByData = (txnArr, value) => {
->Belt.Array.keepMap(data => {
let valueArr =
data
- ->toDict
+ ->Identity.genericTypeToDictOfJson
->Js.Dict.entries
->Js.Array2.map(item => {
let (_, value) = item
diff --git a/src/screens/HyperSwitch/Routing/RoutingStack.res b/src/screens/HyperSwitch/Routing/RoutingStack.res
index 0deba0211..169da83b8 100644
--- a/src/screens/HyperSwitch/Routing/RoutingStack.res
+++ b/src/screens/HyperSwitch/Routing/RoutingStack.res
@@ -1,5 +1,4 @@
open APIUtils
-external toJson: 'a => Js.Json.t = "%identity"
@react.component
let make = (~remainingPath, ~previewOnly=false) => {
let fetchDetails = useGetMethod()
diff --git a/src/screens/HyperSwitch/RoutingRevamp/AddRuleGateway.res b/src/screens/HyperSwitch/RoutingRevamp/AddRuleGateway.res
index 63effeb51..d3ea4e15b 100644
--- a/src/screens/HyperSwitch/RoutingRevamp/AddRuleGateway.res
+++ b/src/screens/HyperSwitch/RoutingRevamp/AddRuleGateway.res
@@ -1,8 +1,3 @@
-external arrToReactEvent: array => ReactEvent.Form.t = "%identity"
-external toReactEvent: 'a => ReactEvent.Form.t = "%identity"
-external formEventToStrArr: ReactEvent.Form.t => array = "%identity"
-external formEventToStr: ReactEvent.Form.t => string = "%identity"
-external toJson: 'a => Js.Json.t = "%identity"
external anyToEnum: 'a => AdvancedRoutingTypes.connectorSelectionData = "%identity"
@react.component
@@ -22,7 +17,7 @@ let make = (~id, ~gatewayOptions, ~isFirst=false, ~isExpanded=false) => {
} else {
"priority"
}
- gateWaysType.onChange(typeString->toReactEvent)
+ gateWaysType.onChange(typeString->Identity.anyTypeToReactEvent)
None
}, [isDistributeInput.value])
@@ -39,10 +34,10 @@ let make = (~id, ~gatewayOptions, ~isFirst=false, ~isExpanded=false) => {
name: "gateways",
onBlur: _ev => (),
onChange: ev => {
- let newSelectedOptions = ev->formEventToStrArr
+ let newSelectedOptions = ev->Identity.formReactEventToArrayOfString
if newSelectedOptions->Js.Array2.length === 0 {
- gateWaysInput.onChange([]->toReactEvent)
+ gateWaysInput.onChange([]->Identity.anyTypeToReactEvent)
} else {
let gatewaysArr = newSelectedOptions->Js.Array2.map(item => {
open AdvancedRoutingTypes
@@ -57,17 +52,17 @@ let make = (~id, ~gatewayOptions, ~isFirst=false, ~isExpanded=false) => {
merchant_connector_id: item,
},
split: sharePercent,
- }->toJson
+ }->Identity.genericTypeToJson
} else {
{
connector: (
connectorList->ConnectorTableUtils.getConnectorNameViaId(item)
).connector_name,
merchant_connector_id: item,
- }->toJson
+ }->Identity.genericTypeToJson
}
})
- gateWaysInput.onChange(gatewaysArr->toReactEvent)
+ gateWaysInput.onChange(gatewaysArr->Identity.anyTypeToReactEvent)
}
},
onFocus: _ev => (),
@@ -101,12 +96,12 @@ let make = (~id, ~gatewayOptions, ~isFirst=false, ~isExpanded=false) => {
merchant_connector_id: obj.merchant_connector_id,
},
split: sharePercent,
- }->toJson
+ }->Identity.genericTypeToJson
- | VolumeObject(obj) => obj.connector->toJson
+ | VolumeObject(obj) => obj.connector->Identity.genericTypeToJson
}
})
- gateWaysInput.onChange(gatewaysArr->toReactEvent)
+ gateWaysInput.onChange(gatewaysArr->Identity.anyTypeToReactEvent)
}
let updatePercentage = (item: AdvancedRoutingTypes.connectorSelectionData, value) => {
@@ -121,7 +116,7 @@ let make = (~id, ~gatewayOptions, ~isFirst=false, ~isExpanded=false) => {
if value < 100 {
let newList = selectedOptions->Js.Array2.map(option => {
switch option {
- | PriorityObject(obj) => obj.connector->toJson
+ | PriorityObject(obj) => obj.connector->Identity.genericTypeToJson
| VolumeObject(obj) =>
{
...obj,
@@ -131,10 +126,10 @@ let make = (~id, ~gatewayOptions, ~isFirst=false, ~isExpanded=false) => {
).merchant_connector_id
? value
: obj.split,
- }->toJson
+ }->Identity.genericTypeToJson
}
})
- gateWaysInput.onChange(newList->toReactEvent)
+ gateWaysInput.onChange(newList->Identity.anyTypeToReactEvent)
}
}
@@ -145,7 +140,7 @@ let make = (~id, ~gatewayOptions, ~isFirst=false, ~isExpanded=false) => {
AdvancedRoutingUtils.getConnectorStringFromConnectorSelectionData(i).merchant_connector_id
)
->Array.filterWithIndex((_, i) => i !== index)
- ->toReactEvent,
+ ->Identity.anyTypeToReactEvent,
)
}
@@ -234,7 +229,7 @@ let make = (~id, ~gatewayOptions, ~isFirst=false, ~isExpanded=false) => {
{
- isDistributeInput.onChange(v->toReactEvent)
+ isDistributeInput.onChange(v->Identity.anyTypeToReactEvent)
onClickDistribute(v)
}}
isDisabled=false
diff --git a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res
index 3ce8c81c7..076b6c8cd 100644
--- a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res
+++ b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res
@@ -3,9 +3,6 @@ open AdvancedRoutingTypes
open AdvancedRoutingUtils
open LogicUtils
-external toForm: string => ReactEvent.Form.t = "%identity"
-external toJson: 'a => Js.Json.t = "%identity"
-external arrToFormEvent: array<'a> => ReactEvent.Form.t = "%identity"
external toWasm: Js.Dict.t => RoutingTypes.wasmModule = "%identity"
let defaultRule = {
@@ -124,7 +121,7 @@ module Wrapper = {
}
React.useEffect0(() => {
- name.onChange(heading->Js.String2.toLowerCase->titleToSnake->toForm)
+ name.onChange(heading->Js.String2.toLowerCase->titleToSnake->Identity.stringToFormReactEvent)
let gatewayArrPresent = gateWaysInput.value->getArrayFromJson([])->Js.Array2.length > 0
@@ -242,23 +239,23 @@ module RuleBasedUI = {
let (rules, setRules) = React.useState(_ => ruleInput.value->getArrayFromJson([]))
React.useEffect1(() => {
- ruleInput.onChange(rules->arrToFormEvent)
+ ruleInput.onChange(rules->Identity.arrayOfGenericTypeToFormReactEvent)
None
}, [rules])
let addRule = (index, copy) => {
let existingRules = ruleInput.value->getArrayFromJson([])
let newRule = copy
- ? existingRules[index]->Belt.Option.getWithDefault(defaultRule->toJson)
- : defaultRule->toJson
+ ? existingRules[index]->Belt.Option.getWithDefault(defaultRule->Identity.genericTypeToJson)
+ : defaultRule->Identity.genericTypeToJson
let newRules = existingRules->Js.Array2.concat([newRule])
- ruleInput.onChange(newRules->arrToFormEvent)
+ ruleInput.onChange(newRules->Identity.arrayOfGenericTypeToFormReactEvent)
}
let removeRule = index => {
let existingRules = ruleInput.value->getArrayFromJson([])
let newRules = existingRules->Array.filterWithIndex((_, i) => i !== index)
- ruleInput.onChange(newRules->arrToFormEvent)
+ ruleInput.onChange(newRules->Identity.arrayOfGenericTypeToFormReactEvent)
}
@@ -340,7 +337,9 @@ let make = (~routingRuleId, ~isActive, ~setCurrentRouting) => {
let businessProfiles = Recoil.useRecoilValueFromAtom(HyperswitchAtom.businessProfilesAtom)
let defaultBusinessProfile = businessProfiles->MerchantAccountUtils.getValueFromBusinessProfile
let (profile, setProfile) = React.useState(_ => defaultBusinessProfile.profile_id)
- let (initialValues, setInitialValues) = React.useState(_ => initialValues->toJson)
+ let (initialValues, setInitialValues) = React.useState(_ =>
+ initialValues->Identity.genericTypeToJson
+ )
let (initialRule, setInitialRule) = React.useState(() => None)
let showToast = ToastState.useShowToast()
let fetchDetails = useGetMethod()
@@ -594,7 +593,7 @@ let make = (~routingRuleId, ~isActive, ~setCurrentRouting) => {
}
let getActivateUrl = getURL(~entityName=ROUTING, ~methodType=Post, ~id=None, ())
- let response = await updateDetails(getActivateUrl, payload->toJson, Post)
+ let response = await updateDetails(getActivateUrl, payload->Identity.genericTypeToJson, Post)
showToast(
~message="Successfully Created a new Configuration !",
diff --git a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res
index 28e1d3092..10d32844e 100644
--- a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res
+++ b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res
@@ -2,11 +2,7 @@ open AdvancedRoutingTypes
open AdvancedRoutingUtils
open FormRenderer
-external arrToFormEvent: array<'a> => ReactEvent.Form.t = "%identity"
-external toForm: 'a => ReactEvent.Form.t = "%identity"
external strToFormEvent: Js.String.t => ReactEvent.Form.t = "%identity"
-external formEventToStr: ReactEvent.Form.t => string = "%identity"
-external formEventToStrArr: ReactEvent.Form.t => array
= "%identity"
module LogicalOps = {
@react.component
@@ -55,8 +51,8 @@ module OperatorInp = {
name: "string",
onBlur: _ev => (),
onChange: ev => {
- let value = ev->formEventToStr
- operator.onChange(value->toForm)
+ let value = ev->Identity.formReactEventToString
+ operator.onChange(value->Identity.anyTypeToReactEvent)
},
onFocus: _ev => (),
value: operator.value,
@@ -74,7 +70,7 @@ module OperatorInp = {
setOpVals(_ => operatorVals)
if operator.value->Js.Json.decodeString->Belt.Option.isNone {
- operator.onChange(operatorVals[0]->toForm)
+ operator.onChange(operatorVals[0]->Identity.anyTypeToReactEvent)
}
None
}, (field.value, valInp.value))
@@ -139,7 +135,7 @@ module ValueInp = {
| NOT_CONTAINS => "enum_variant_array"
| _ => "number"
}
- }->toForm,
+ }->Identity.anyTypeToReactEvent,
)
None
}, [valueField.value])
@@ -148,8 +144,8 @@ module ValueInp = {
name: "string",
onBlur: _ev => (),
onChange: ev => {
- let value = ev->formEventToStrArr
- valueField.onChange(value->toForm)
+ let value = ev->Identity.formReactEventToArrayOfString
+ valueField.onChange(value->Identity.anyTypeToReactEvent)
},
onFocus: _ev => (),
value: valueField.value,
@@ -209,12 +205,12 @@ module MetadataInp = {
})
let finalVal = Js.Array2.joinWith(arrStr, ",")->Js.Json.string
- valueField.onChange(finalVal->toForm)
+ valueField.onChange(finalVal->Identity.anyTypeToReactEvent)
},
onChange: ev => {
let target = ReactEvent.Form.target(ev)
let value = target["value"]
- valueField.onChange(value->toForm)
+ valueField.onChange(value->Identity.anyTypeToReactEvent)
},
onFocus: _ev => (),
value: valueField.value,
@@ -295,11 +291,11 @@ module FieldInp = {
name: "string",
onBlur: _ev => (),
onChange: ev => {
- let value = ev->formEventToStr
+ let value = ev->Identity.formReactEventToString
onChangeMethod(value)
- field.onChange(value->toForm)
- op.onChange(""->toForm)
- val.onChange(""->toForm)
+ field.onChange(value->Identity.anyTypeToReactEvent)
+ op.onChange(""->Identity.anyTypeToReactEvent)
+ val.onChange(""->Identity.anyTypeToReactEvent)
},
onFocus: _ev => (),
value: field.value,
@@ -401,12 +397,21 @@ module MakeRuleField = {
let onPlusClick = _ => {
if plusBtnEnabled {
let toAdd = Js.Dict.empty()
- conditionsInput.onChange(Js.Array2.concat(fields, [toAdd->Js.Json.object_])->arrToFormEvent)
+ conditionsInput.onChange(
+ Js.Array2.concat(
+ fields,
+ [toAdd->Js.Json.object_],
+ )->Identity.arrayOfGenericTypeToFormReactEvent,
+ )
}
}
let onCrossClick = index => {
- conditionsInput.onChange(fields->Array.filterWithIndex((_, i) => index !== i)->arrToFormEvent)
+ conditionsInput.onChange(
+ fields
+ ->Array.filterWithIndex((_, i) => index !== i)
+ ->Identity.arrayOfGenericTypeToFormReactEvent,
+ )
}
diff --git a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res
index 0c342c5a1..45e55a43c 100644
--- a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res
+++ b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res
@@ -1,5 +1,3 @@
-external toJson: 'a => Js.Json.t = "%identity"
-
let getCurrentDetailedUTCTime = () => {
Js.Date.fromFloat(Js.Date.now())->Js.Date.toUTCString
}
@@ -410,7 +408,7 @@ let generateRule = rulesDict => {
{
"name": ruleDict->getString("name", ""),
"connectorSelection": ruleDict->getJsonObjectFromDict("connectorSelection"),
- "statements": modifiedStatements->Js.Array2.map(toJson)->Js.Json.array,
+ "statements": modifiedStatements->Js.Array2.map(Identity.genericTypeToJson)->Js.Json.array,
}
})
modifiedRules
diff --git a/src/screens/HyperSwitch/RoutingRevamp/BasicDetailsForm.res b/src/screens/HyperSwitch/RoutingRevamp/BasicDetailsForm.res
index 647bc5b71..ab7949efb 100644
--- a/src/screens/HyperSwitch/RoutingRevamp/BasicDetailsForm.res
+++ b/src/screens/HyperSwitch/RoutingRevamp/BasicDetailsForm.res
@@ -2,9 +2,6 @@ open FormRenderer
open LogicUtils
open AdvancedRoutingTypes
-external fromFormEvent: ReactEvent.Form.t => 'a = "%identity"
-external formEventToStr: ReactEvent.Form.t => string = "%identity"
-
let configurationNameInput = makeFieldInfo(
~label="Configuration Name",
~name="name",
@@ -43,7 +40,7 @@ module BusinessProfileInp = {
value: profile->Js.Json.string,
onChange: {
ev => {
- setProfile(_ => ev->formEventToStr)
+ setProfile(_ => ev->Identity.formReactEventToString)
input.onChange(ev)
}
},
diff --git a/src/screens/HyperSwitch/SDKPayment/SDKPage.res b/src/screens/HyperSwitch/SDKPayment/SDKPage.res
index 2e37537e2..4c37a06ed 100644
--- a/src/screens/HyperSwitch/SDKPayment/SDKPage.res
+++ b/src/screens/HyperSwitch/SDKPayment/SDKPage.res
@@ -1,7 +1,4 @@
let h3Leading2Style = HSwitchUtils.getTextClass(~textVariant=H3, ~h3TextVariant=Leading_2, ())
-external toJson: 'a => Js.Json.t = "%identity"
-external formEventToStr: ReactEvent.Form.t => string = "%identity"
-external strToFormEvent: Js.String.t => ReactEvent.Form.t = "%identity"
module SDKConfiguarationFields = {
open MerchantAccountUtils
@@ -55,8 +52,10 @@ module SDKConfiguarationFields = {
value: (initialValues.amount / 100)->string_of_int->Js.Json.string,
onChange: {
ev => {
- let eventValueToInt = ev->formEventToStr->LogicUtils.getIntFromString(0)
- let valInCents = (eventValueToInt * 100)->string_of_int->strToFormEvent
+ let eventValueToInt =
+ ev->Identity.formReactEventToString->LogicUtils.getIntFromString(0)
+ let valInCents =
+ (eventValueToInt * 100)->string_of_int->Identity.stringToFormReactEvent
input.onChange(valInCents)
}
},
@@ -140,7 +139,7 @@ let make = () => {
+ | Successful =>
+
+
+
+ {"Business Profile successfully created! Set up your payments settings like webhooks, return url for your new profile before trying a payment."->React.string}
+
+
{
+ if updatedProfileId->Js.String2.length > 0 {
+ RescriptReactRouter.replace(`/payment-settings/${updatedProfileId}`)
+ setModalState(_ => Edit)
+ }
+ }}
+ customButtonStyle="!w-1/3 mt-6"
+ />
+
}}
+ let modalHeaderText = switch modalState {
+ | Edit | Loading => "Add Business Profile Name"
+ | Successful => "Configure payment settings"
+ }
+
@@ -78,6 +124,7 @@ let make = (
let (showModal, setShowModal) = React.useState(_ => false)
let (modalState, setModalState) = React.useState(_ => Edit)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Success)
+ let (updatedProfileId, setUpdatedProfileId) = React.useState(_ => "")
let businessProfileValues =
HyperswitchAtom.businessProfilesAtom
@@ -90,7 +137,10 @@ let make = (
try {
setScreenState(_ => PageLoaderWrapper.Loading)
let url = getURL(~entityName=BUSINESS_PROFILE, ~methodType=Post, ())
- let _ = await updateDetails(url, body, Post)
+ let response = await updateDetails(url, body, Post)
+ setUpdatedProfileId(_ =>
+ response->LogicUtils.getDictFromJsonObject->LogicUtils.getString("profile_id", "")
+ )
fetchBusinessProfiles()->ignore
showToast(~message="Your Entry added successfully", ~toastType=ToastState.ToastSuccess, ())
if !isFromSettings {
@@ -100,9 +150,12 @@ let make = (
} catch {
| _ => setScreenState(_ => PageLoaderWrapper.Error(""))
}
- isFromSettings ? setShowModal(_ => false) : setShowModalFromOtherScreen(_ => false)
- setModalState(_ => Edit)
- setShowModal(_ => false)
+
+ if !isFromSettings {
+ setShowModalFromOtherScreen(_ => false)
+ }
+ setModalState(_ => Successful)
+
Js.Nullable.null
}
@@ -114,11 +167,16 @@ let make = (
-
+
+
Js.Array2.length > 1}>
+
+
Js.Array2.length}
/>
@@ -146,6 +212,8 @@ let make = (
showModal={showModalFromOtherScreen}
setShowModal={setShowModalFromOtherScreen}
list={businessProfileValues}
+ updatedProfileId
+ setModalState
/>
diff --git a/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res b/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res
index 35814ca2c..fc7e3f54f 100644
--- a/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res
+++ b/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res
@@ -1,6 +1,5 @@
open RoutingTypes
external toWasm: Js.Dict.t
=> wasmModule = "%identity"
-external arrToFormEvent: array<'a> => ReactEvent.Form.t = "%identity"
module ActiveRulePreview = {
open LogicUtils
@@ -42,20 +41,20 @@ module Configure3DSRule = {
let ruleInput = ReactFinalForm.useField("algorithm.rules").input
let (rules, setRules) = React.useState(_ => ruleInput.value->LogicUtils.getArrayFromJson([]))
React.useEffect1(() => {
- ruleInput.onChange(rules->arrToFormEvent)
+ ruleInput.onChange(rules->Identity.arrayOfGenericTypeToFormReactEvent)
None
}, [rules])
let addRule = (index, _copy) => {
let existingRules = ruleInput.value->LogicUtils.getArrayFromJson([])
let newRule = existingRules[index]->Belt.Option.getWithDefault(Js.Json.null)
let newRules = existingRules->Js.Array2.concat([newRule])
- ruleInput.onChange(newRules->arrToFormEvent)
+ ruleInput.onChange(newRules->Identity.arrayOfGenericTypeToFormReactEvent)
}
let removeRule = index => {
let existingRules = ruleInput.value->LogicUtils.getArrayFromJson([])
let newRules = existingRules->Array.filterWithIndex((_, i) => i !== index)
- ruleInput.onChange(newRules->arrToFormEvent)
+ ruleInput.onChange(newRules->Identity.arrayOfGenericTypeToFormReactEvent)
}
@@ -103,7 +102,9 @@ let make = () => {
let fetchDetails = useGetMethod(~showErrorToast=false, ())
let updateDetails = useUpdateMethod(~showErrorToast=false, ())
let (wasm, setWasm) = React.useState(_ => None)
- let (initialValues, _setInitialValues) = React.useState(_ => buildInitial3DSValue->toJson)
+ let (initialValues, _setInitialValues) = React.useState(_ =>
+ buildInitial3DSValue->Identity.genericTypeToJson
+ )
let (initialRule, setInitialRule) = React.useState(() => None)
let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading)
let (pageView, setPageView) = React.useState(_ => NEW)
@@ -185,7 +186,7 @@ let make = () => {
let threeDsPayload = values->buildThreeDsPayloadBody
let getActivateUrl = getURL(~entityName=THREE_DS, ~methodType=Put, ())
- let _ = await updateDetails(getActivateUrl, threeDsPayload->toJson, Put)
+ let _ = await updateDetails(getActivateUrl, threeDsPayload->Identity.genericTypeToJson, Put)
fetchDetails()->ignore
setShowWarning(_ => true)
RescriptReactRouter.replace(`/3ds`)
diff --git a/src/screens/HyperSwitch/ThreeDSFlow/ThreeDSUtils.res b/src/screens/HyperSwitch/ThreeDSFlow/ThreeDSUtils.res
index dd71cc234..fbfcef590 100644
--- a/src/screens/HyperSwitch/ThreeDSFlow/ThreeDSUtils.res
+++ b/src/screens/HyperSwitch/ThreeDSFlow/ThreeDSUtils.res
@@ -1,5 +1,3 @@
-external toJson: 'a => Js.Json.t = "%identity"
-
type pageState = NEW | LANDING
let statementObject: array
= [
diff --git a/src/screens/analyticsScreens/AnalyticsCommonComponents.res b/src/screens/analyticsScreens/AnalyticsCommonComponents.res
deleted file mode 100644
index bde445c44..000000000
--- a/src/screens/analyticsScreens/AnalyticsCommonComponents.res
+++ /dev/null
@@ -1,2816 +0,0 @@
-external toString: option => string = "%identity"
-external convertToStrDict: 't => Js.Json.t = "%identity"
-external evToString: ReactEvent.Form.t => string = "%identity"
-external objToJson: {..} => Js.Json.t = "%identity"
-external toJson: exn => Js.Json.t = "%identity"
-external toRespJson: Fetch.Response.t => Js.Json.t = "%identity"
-@get external keyCode: 'a => int = "keyCode"
-external formEventToStr: ReactEvent.Form.t => string = "%identity"
-type window
-@val external window: window = "window"
-@scope("window") @val external parent: window = "parent"
-
-external formEventToBoolean: ReactEvent.Form.t => bool = "%identity"
-open LogicUtils
-open Promise
-type modalView = SavedList | SaveNew
-module SavedViewTable = {
- @react.component
- let make = (~actualData, ~modifiedTableEntity) => {
- let (offset, setOffset) = React.useState(_ => 0)
- let searchText = ReactFinalForm.useField("searchTable").input.value
- let search_class = "text-gray-400 dark:text-gray-600"
- let searchTable = FormRenderer.makeFieldInfo(
- ~label="",
- ~name="searchTable",
- ~placeholder="Search ",
- ~customInput=InputFields.textInput(
- ~customStyle="w-64",
- ~autoComplete="off",
- ~leftIcon= ,
- (),
- ),
- (),
- )
-
- let actualData = React.useMemo2(() => {
- actualData->SaveViewEntity.filterBySearchText(searchText)
- }, (searchText, actualData))
- <>
-
- Js.Array2.length}
- totalResults={actualData->Js.Array2.length}
- resultsPerPage=15
- ignoreHeaderBg=true
- />
- >
- }
-}
-
-module AnalyticsSaveViewNew = {
- @react.component
- let make = (
- ~moduleName: string,
- ~tabNames: array,
- ~startTimeFilterKey,
- ~endTimeFilterKey,
- ) => {
- let isMobileView = MatchMedia.useMobileChecker()
- let {updateExistingKeys} = React.useContext(AnalyticsUrlUpdaterContext.urlUpdaterContext)
- let deleteSaveView = AnalyticsHooks.useDeleteSaveView()
-
- let {
- savedViewList,
- setRefetchCounter,
- isDefaultSaveViewPresent,
- defaultSaveView,
- appliedSaveView,
- applySaveView,
- setAppliedSaveView,
- } = React.useContext(SaveViewContext.defaultContext)
- let urlDict = UrlUtils.useGetFilterDictFromUrl("")
- let url = RescriptReactRouter.useUrl()
- let showToast = ToastState.useShowToast()
- let saveView = AnalyticsHooks.useSaveView()
- let updateSaveView = AnalyticsHooks.useUpdateSaveView()
- let (showModal, setShowModal) = React.useState(_ => false)
- let (selectedView, setSelectedView) = React.useState(_ => "")
- let (editView, setEditView) = React.useState(_ => appliedSaveView)
- let filterDict = Js.Dict.empty()
- tabNames->Js.Array2.forEach(key => {
- filterDict->Js.Dict.set(key, "")
- })
- let dateCreatedObject =
- AnalyticsUtils.getDateCreatedObject()
- ->Js.Dict.entries
- ->Js.Array2.map(entry => {
- let (key, value) = entry
- let value = value->getStringFromJson("")
- (key, value)
- })
- ->Js.Dict.fromArray
-
- let defaultSearchDict = DictionaryUtils.mergeDicts([dateCreatedObject, filterDict])
-
- let disableSaveButton = React.useMemo2(() => {
- let excludeKeys = appliedSaveView.includeDateRange
- ? []
- : [startTimeFilterKey, endTimeFilterKey]
- let dict1 = SaveViewEntity.getFilterDict(
- ~url=appliedSaveView.url,
- ~prefix="",
- ~excludeKeys,
- (),
- )
- let dict2 = SaveViewEntity.getFilterDict(
- ~url=url.search->Js.Global.decodeURI,
- ~prefix="",
- ~excludeKeys,
- (),
- )
-
- DictionaryUtils.equalDicts(dict1, dict2)
- }, (url.search, appliedSaveView))
-
- let options = React.useMemo1(() => {
- [
- {
- let opt: SelectBox.dropdownOption = {
- label: "Base View",
- value: "baseView",
- icon: CustomRightIcon(
- )}
- showBorder=false
- customButtonStyle="invisible"
- buttonType={NonFilled}
- buttonSize={XSmall}
- buttonVariant=Rounded
- />,
- ),
- }
- opt
- },
- ]->Js.Array2.concat(
- savedViewList->Js.Array2.map(ele => {
- let opt: SelectBox.dropdownOption = {
- label: ele.name,
- value: ele.name,
- textColor: "group",
- icon: CustomRightIcon(
- )}
- showBorder=false
- customButtonStyle="invisible group-hover:visible p-2"
- onClick={ev => {
- ev->ReactEvent.Mouse.stopPropagation
- ev->ReactEvent.Mouse.preventDefault
- setEditView(_ => ele)
- setShowModal(_ => true)
- }}
- buttonType={NonFilled}
- buttonSize={XSmall}
- buttonVariant=Rounded
- />,
- ),
- }
- opt
- }),
- )
- }, [savedViewList->Array.joinWith(",")])
-
- let modalHeading = "Save Dashboard View"
- let modalHeadingDescription = ""
- let submitButtonText = editView.id === "" ? "Save Dashboard View" : "Update Dashboard View"
- let submitButtonIcon = "new-save"
- let loadingText = "Saving..."
-
- let saveView = bodyDict => {
- let name = bodyDict->getString("name", "Default View")
- if name === appliedSaveView.name {
- updateSaveView(
- ~bodyStr=bodyDict->Js.Json.object_->Js.Json.stringify,
- ~id=appliedSaveView.id,
- )
- } else {
- saveView(~bodyStr=bodyDict->Js.Json.object_->Js.Json.stringify)
- }
- ->then(response => {
- switch response {
- | Success => {
- showToast(~message="Saved Successfully", ~toastType=ToastSuccess, ())
- setRefetchCounter(prev => prev + 1)
- setShowModal(_ => false)
- }
-
- | Error(errorMessage) => {
- let errorMessage = errorMessage->Belt.Option.getWithDefault("")
- showToast(~message=errorMessage, ~toastType=ToastError, ())
- }
- }
- Js.Nullable.null->resolve
- })
- ->catch(_err => {
- Js.Nullable.null->resolve
- })
- }
-
- let saveViewFn = bodyDict => {
- if isDefaultSaveViewPresent {
- let bodyStr =
- [("isDefault", false->Js.Json.boolean)]
- ->Js.Dict.fromArray
- ->Js.Json.object_
- ->Js.Json.stringify
- updateSaveView(~bodyStr, ~id=defaultSaveView.id)
- ->then(response => {
- switch response {
- | Success => saveView(bodyDict)
- | Error(errorMessage) => {
- let errorMessage = errorMessage->Belt.Option.getWithDefault("")
- showToast(~message=errorMessage, ~toastType=ToastError, ())
- Js.Nullable.null->resolve
- }
- }
- })
- ->catch(_err => {
- Js.Nullable.null->resolve
- })
- } else {
- saveView(bodyDict)
- }
- }
-
- let initialValues = React.useMemo1(() => {
- if editView.id === "" {
- Js.Json.null
- } else {
- let selectors = []
- if editView.includeDateRange {
- selectors->Js.Array2.push("Save with current timestamp"->Js.Json.string)->ignore
- }
- if editView.isDefault {
- selectors->Js.Array2.push("Make this view Default"->Js.Json.string)->ignore
- }
- let initialValues =
- [
- ("name", editView.name->Js.Json.string),
- ("description", editView.description->Js.Json.string),
- ("selectors", selectors->Js.Json.array),
- ]
- ->Js.Dict.fromArray
- ->Js.Json.object_
- initialValues
- }
- }, [editView])
-
- let validate = (values: Js.Json.t) => {
- let errors = Js.Dict.empty()
- let valuesDict = values->getDictFromJsonObject
-
- ["name"]->Js.Array2.forEach(key => {
- let value = valuesDict->getString(key, "")
- if value == "" {
- errors->Js.Dict.set(key, `${key->capitalizeString} Required`->Js.Json.string)
- }
- if (
- savedViewList->Js.Array2.map(ele => ele.name)->Js.Array2.includes(value) &&
- editView.id === ""
- ) {
- errors->Js.Dict.set(key, `${key->capitalizeString} already exits`->Js.Json.string)
- }
- })
-
- errors->Js.Json.object_
- }
-
- let onSubmit = (values, _) => {
- let valuesDict = values->getDictFromJsonObject
-
- let name = valuesDict->getString("name", "")
- let description = valuesDict->getString("description", "")
- let selectors = valuesDict->getStrArrayFromDict("selectors", [])
- let isDefault = selectors->Js.Array2.includes("Make this view Default")
- let includeDateRange = selectors->Js.Array2.includes("Save with current timestamp")
- let url = {
- urlDict
- ->Js.Dict.entries
- ->Belt.Array.keepMap(entry => {
- let (key, value) = entry
- let value = switch value->Js.Json.classify {
- | JSONFalse => "false"
- | JSONTrue => "true"
- | JSONNull => ""
- | JSONString(string) => string
- | JSONNumber(float) => float->Belt.Float.toString
- | JSONObject(_) => ""
- | JSONArray(array) => `[${array->Js.Array2.toString}]`
- }
- if (key !== "startTime" && key !== "endTime") || includeDateRange {
- Some(`${key}=${value}`)
- } else {
- None
- }
- })
- ->Js.Array2.joinWith("&")
- }
-
- let bodyDict = Js.Dict.empty()
- bodyDict->Js.Dict.set("tab", moduleName->Js.Json.string)
- bodyDict->Js.Dict.set("url", url->Js.Json.string)
- bodyDict->Js.Dict.set("name", name->Js.Json.string)
- bodyDict->Js.Dict.set("description", description->Js.Json.string)
- if includeDateRange {
- bodyDict->Js.Dict.set("includeDateRange", includeDateRange->Js.Json.boolean)
- }
- if isDefault {
- bodyDict->Js.Dict.set("isDefault", isDefault->Js.Json.boolean)
- }
- saveViewFn(bodyDict)
- }
-
- let handleDelete = () => {
- deleteSaveView(~id=editView.id)
- ->then(response => {
- switch response {
- | Success => {
- showToast(~message=`${editView.name} deleted Successfully`, ~toastType=ToastSuccess, ())
- setEditView(_ => defaultSaveView)
- setRefetchCounter(prev => prev + 1)
- setShowModal(_ => false)
- }
-
- | Error(errorMessage) => {
- let errorMessage = errorMessage->Belt.Option.getWithDefault("")
- showToast(~message=errorMessage, ~toastType=ToastError, ())
- }
- }
- Js.Nullable.null->resolve
- })
- ->catch(_err => {
- Js.Nullable.null->resolve
- })
- ->ignore
- }
-
- let modalWidth = "sm:w-128"
-
- let savedViewInput: ReactFinalForm.fieldRenderPropsInput = {
- name: "savedView",
- onBlur: _ev => (),
- onChange: ev => {
- let appliedVal = ev->formEventToStr
- if appliedVal === "baseView" {
- updateExistingKeys(defaultSearchDict)
- setAppliedSaveView(_ => SaveViewEntity.defaultSaveView)
- } else {
- switch savedViewList->Js.Array2.find(ele => ele.name === appliedVal) {
- | Some(view) => applySaveView(view)
- | None => ()
- }
- }
- setSelectedView(_ => appliedVal)
- },
- onFocus: _ev => (),
- value: selectedView->Js.Json.string,
- checked: true,
- }
- let saveViewButton = {
- {
- setShowModal(_ => true)
- }}
- customIconMargin={isMobileView ? "mr-1" : "ml-1"}
- />
- }
-
-
-
- {if savedViewList->Js.Array2.length > 0 {
- ,
- )
- buttonState={disableSaveButton ? Disabled : Normal}
- buttonType={FilterAdd}
- onClick={_ => {
- setEditView(_ => defaultSaveView)
- setShowModal(_ => true)
- }}
- customButtonStyle="w-full"
- customIconMargin={isMobileView ? "mr-1" : "ml-1"}
- />}
- />
- } else {
- saveViewButton
- }}
-
-
-
-
-
-
-
- }
-}
-
-module AnalyticsSaveView = {
- @react.component
- let make = (
- ~moduleName: string,
- ~tabNames: array,
- ~startTimeFilterKey,
- ~endTimeFilterKey,
- ) => {
- let isMobileView = MatchMedia.useMobileChecker()
- let {updateExistingKeys, filterValueJson} = React.useContext(
- AnalyticsUrlUpdaterContext.urlUpdaterContext,
- )
-
- let (startTime, endTime) = React.useMemo1(() => {
- (
- filterValueJson->getString(startTimeFilterKey, ""),
- filterValueJson->getString(endTimeFilterKey, ""),
- )
- }, [filterValueJson])
-
- let dateFilterUrl = React.useMemo2(() => {
- `&${startTimeFilterKey}=${startTime}&${endTimeFilterKey}=${endTime}`
- }, (startTime, endTime))
-
- let {
- savedViewList,
- refetchCounter,
- setRefetchCounter,
- isDefaultSaveViewPresent,
- defaultSaveView,
- appliedSaveView,
- applySaveView,
- setAppliedSaveView,
- } = React.useContext(SaveViewContext.defaultContext)
- let urlDict = UrlUtils.useGetFilterDictFromUrl("")
- let url = RescriptReactRouter.useUrl()
- let showToast = ToastState.useShowToast()
- let saveView = AnalyticsHooks.useSaveView()
- let updateSaveView = AnalyticsHooks.useUpdateSaveView()
- let (showModal, setShowModal) = React.useState(_ => false)
- let (newSave, setNewSave) = React.useState(_ => true)
- let (modalView, setModalView) = React.useState(_ => SavedList)
- let filterDict = Js.Dict.empty()
- tabNames->Js.Array2.forEach(key => {
- filterDict->Js.Dict.set(key, "")
- })
- let dateCreatedObject =
- AnalyticsUtils.getDateCreatedObject()
- ->Js.Dict.entries
- ->Js.Array2.map(entry => {
- let (key, value) = entry
- let value = value->getStringFromJson("")
- (key, value)
- })
- ->Js.Dict.fromArray
-
- let defaultSearchDict = DictionaryUtils.mergeDicts([dateCreatedObject, filterDict])
-
- let disableSaveButton = React.useMemo2(() => {
- let excludeKeys = appliedSaveView.includeDateRange
- ? []
- : [startTimeFilterKey, endTimeFilterKey]
- let dict1 = SaveViewEntity.getFilterDict(
- ~url=appliedSaveView.url,
- ~prefix="",
- ~excludeKeys,
- (),
- )
- let dict2 = SaveViewEntity.getFilterDict(
- ~url=url.search->Js.Global.decodeURI,
- ~prefix="",
- ~excludeKeys,
- (),
- )
-
- DictionaryUtils.equalDicts(dict1, dict2)
- }, (url.search, appliedSaveView))
-
- let saveViewName = React.useMemo1(() => {
- appliedSaveView.name
- }, [appliedSaveView])
-
- let actualData = React.useMemo1(() => {
- savedViewList->Js.Array2.map(Js.Nullable.return)
- }, [savedViewList])
-
- let modifiedTableEntity = React.useMemo4(() => {
- ...SaveViewEntity.saveFilterListEntity,
- getCell: SaveViewEntity.getCell(
- dateFilterUrl,
- setRefetchCounter,
- isDefaultSaveViewPresent,
- defaultSaveView,
- setShowModal,
- applySaveView,
- ),
- }, (refetchCounter, isDefaultSaveViewPresent, defaultSaveView, dateFilterUrl))
-
- let (
- modalHeading,
- modalHeadingDescription,
- submitButtonText,
- submitButtonIcon,
- loadingText,
- ) = switch modalView {
- | SavedList => (
- "Load Dashboard View",
- "Load a set of applied filters, selected dimensions and data mode from your saved views",
- "Load Base View",
- "undo-alt",
- "Loading...",
- )
- | SaveNew => (
- "Save Dashboard View",
- "You can save the configuration of the current dashboard as a default view or with a timestamp and load it whenever needed.",
- newSave ? "Save New View" : "Update View",
- "plus",
- "Saving...",
- )
- }
-
- let saveView = bodyDict => {
- let name = bodyDict->getString("name", "Default View")
- if name === appliedSaveView.name {
- updateSaveView(
- ~bodyStr=bodyDict->Js.Json.object_->Js.Json.stringify,
- ~id=appliedSaveView.id,
- )
- } else {
- saveView(~bodyStr=bodyDict->Js.Json.object_->Js.Json.stringify)
- }
- ->then(response => {
- switch response {
- | Success => {
- showToast(~message="Saved Successfully", ~toastType=ToastSuccess, ())
- setRefetchCounter(prev => prev + 1)
- setShowModal(_ => false)
- }
-
- | Error(errorMessage) => {
- let errorMessage = errorMessage->Belt.Option.getWithDefault("")
- showToast(~message=errorMessage, ~toastType=ToastError, ())
- }
- }
- Js.Nullable.null->resolve
- })
- ->catch(_err => {
- Js.Nullable.null->resolve
- })
- }
-
- let saveViewFn = bodyDict => {
- if isDefaultSaveViewPresent {
- let bodyStr =
- [("isDefault", false->Js.Json.boolean)]
- ->Js.Dict.fromArray
- ->Js.Json.object_
- ->Js.Json.stringify
- updateSaveView(~bodyStr, ~id=defaultSaveView.id)
- ->then(response => {
- switch response {
- | Success => saveView(bodyDict)
- | Error(errorMessage) => {
- let errorMessage = errorMessage->Belt.Option.getWithDefault("")
- showToast(~message=errorMessage, ~toastType=ToastError, ())
- Js.Nullable.null->resolve
- }
- }
- })
- ->catch(_err => {
- Js.Nullable.null->resolve
- })
- } else {
- saveView(bodyDict)
- }
- }
-
- let initialValues = React.useMemo1(() => {
- if appliedSaveView.name === "Default View" {
- Js.Json.null
- } else {
- let selectors = []
- if appliedSaveView.includeDateRange {
- selectors->Js.Array2.push("Save with current time interval"->Js.Json.string)->ignore
- }
- if appliedSaveView.isDefault {
- selectors->Js.Array2.push("Make this view Default"->Js.Json.string)->ignore
- }
- let initialValues =
- [
- ("name", appliedSaveView.name->Js.Json.string),
- ("description", appliedSaveView.description->Js.Json.string),
- ("selectors", selectors->Js.Json.array),
- ]
- ->Js.Dict.fromArray
- ->Js.Json.object_
- initialValues
- }
- }, [appliedSaveView])
-
- let validate = (values: Js.Json.t) => {
- let errors = Js.Dict.empty()
- let valuesDict = values->getDictFromJsonObject
-
- switch modalView {
- | SaveNew =>
- let name = valuesDict->getString("name", "Default View")
- setNewSave(_ => name !== appliedSaveView.name)
- ["name"]->Js.Array2.forEach(key => {
- let value = valuesDict->getString(key, "")
- if value == "" {
- errors->Js.Dict.set(key, `${key->capitalizeString} Required`->Js.Json.string)
- }
- })
- | SavedList => ()
- }
-
- errors->Js.Json.object_
- }
-
- let onSubmit = (values, _) => {
- let valuesDict = values->getDictFromJsonObject
-
- switch modalView {
- | SaveNew => {
- let name = valuesDict->getString("name", "")
- let description = valuesDict->getString("description", "")
- let selectors = valuesDict->getStrArrayFromDict("selectors", [])
- let isDefault = selectors->Js.Array2.includes("Make this view Default")
- let includeDateRange = selectors->Js.Array2.includes("Save with current time interval")
- let url = {
- urlDict
- ->Js.Dict.entries
- ->Belt.Array.keepMap(entry => {
- let (key, value) = entry
- let value = switch value->Js.Json.classify {
- | JSONFalse => "false"
- | JSONTrue => "true"
- | JSONNull => ""
- | JSONString(string) => string
- | JSONNumber(float) => float->Belt.Float.toString
- | JSONObject(_) => ""
- | JSONArray(array) => `[${array->Js.Array2.toString}]`
- }
- if (key !== "startTime" && key !== "endTime") || includeDateRange {
- Some(`${key}=${value}`)
- } else {
- None
- }
- })
- ->Js.Array2.joinWith("&")
- }
-
- let bodyDict = Js.Dict.empty()
- bodyDict->Js.Dict.set("tab", moduleName->Js.Json.string)
- bodyDict->Js.Dict.set("url", url->Js.Json.string)
- bodyDict->Js.Dict.set("name", name->Js.Json.string)
- bodyDict->Js.Dict.set("description", description->Js.Json.string)
- if includeDateRange {
- bodyDict->Js.Dict.set("includeDateRange", includeDateRange->Js.Json.boolean)
- }
- if isDefault {
- bodyDict->Js.Dict.set("isDefault", isDefault->Js.Json.boolean)
- }
- saveViewFn(bodyDict)
- }
-
- | SavedList => {
- updateExistingKeys(defaultSearchDict)
- setAppliedSaveView(_ => SaveViewEntity.defaultSaveView)
- setShowModal(_ => false)
- Js.Nullable.null->resolve
- }
- }
- }
-
- let savedViewComp =
-
- {if actualData->Js.Array2.length > 0 {
-
-
-
-
- {
- setModalView(_ => SavedList)
- setShowModal(_ => true)
- }}
- />
- }
- tooltipWidthClass="w-fit"
- />
- } else {
- React.null
- }}
- {
- setModalView(_ => SaveNew)
- setShowModal(_ => true)
- }}
- customIconMargin={isMobileView ? "mr-1" : "ml-1"}
- />
-
-
- }
-}
-
-module FiltersComponent = {
- @react.component
- let make = (
- ~filterEntity: AnalyticsUtils.filterEntity<'t>,
- ~downloadDataButtonUi: React.element=React.null,
- ) => {
- open AnalyticsUtils
- let iframe_padding = parent !== window ? "px-5" : ""
- let getFilterData = AnalyticsHooks.useGetFiltersData()
- let {updateExistingKeys, filterValue} = React.useContext(
- AnalyticsUrlUpdaterContext.urlUpdaterContext,
- )
-
- let {
- initialFilters,
- filterDropDownOptions,
- initialFixedFilters,
- defaultFilterKeys,
- filterKeys,
- } = filterEntity
-
- let filterBody = switch filterEntity {
- | {filterBody} => filterBody
- | _ => AnalyticsUtils.filterBody
- }
-
- let source = switch filterEntity {
- | {source} => source
- | _ => "BATCH"
- }
- let customFilterKey = switch filterEntity {
- | {customFilterKey} => customFilterKey
- | _ => ""
- }
-
- let filterKeys = filterKeys
- let filteredTabKeys = filterKeys
-
- let getModuleFilters = UrlUtils.useGetFilterDictFromUrl("")
- let startTimeVal = getModuleFilters->getString(startTimeFilterKey, "")
-
- let endTimeVal = getModuleFilters->getString(endTimeFilterKey, "")
-
- let filterBody = React.useMemo3(() => {
- let filterBodyEntity: AnalyticsUtils.filterBodyEntity = {
- startTime: startTimeVal,
- endTime: endTimeVal,
- groupByNames: filteredTabKeys,
- source,
- mode: ?filterValue->Js.Dict.get("mode"),
- }
- filterBody(filterBodyEntity)
- }, (startTimeVal, endTimeVal, filteredTabKeys->Js.Array2.joinWith(",")))
-
- let filterDataOrig = getFilterData(filterEntity.uri, Fetch.Post, filterBody)
- let filterData = filterDataOrig->Belt.Option.getWithDefault(Js.Json.object_(Js.Dict.empty()))
-
- let filterDataOrigTabNames = React.useMemo2(() => {
- switch filterDataOrig {
- | Some(filterData) =>
- Some(
- {
- "queryData": filterData
- ->getDictFromJsonObject
- ->getJsonObjectFromDict("queryData")
- ->getArrayFromJson([])
- ->Js.Array2.filter(item => {
- let itemDict = item->getDictFromJsonObject
- let dimension = itemDict->getString("dimension", "")
- filteredTabKeys->Js.Array2.includes(dimension)
- })
- ->Js.Json.array,
- }->LineChartUtils.objToJson,
- )
- | None => None
- }
- }, (filterDataOrig, filteredTabKeys))
-
- switch filterDataOrigTabNames {
- | Some(filterData) =>
-
-
-
- | None =>
-
-
-
- }
- }
-}
-
-module FiltersComponentNew = {
- @react.component
- let make = (
- ~filterEntity: AnalyticsUtils.filterEntityNew<'t>,
- ~downloadDataButtonUi: React.element=React.null,
- ~domain="txns",
- ) => {
- open AnalyticsUtils
- let betaEndPointConfig = React.useContext(BetaEndPointConfigProvider.betaEndPointConfig)
- let iframe_padding = parent !== window ? "px-5" : ""
- let parentToken = AuthWrapperUtils.useTokenParent(Original)
-
- let sortingParams = React.useMemo1((): option => {
- switch filterEntity {
- | {sortingColumnLegend} =>
- Some({
- sortDimension: sortingColumnLegend,
- ordering: #Desc,
- })
- | _ => None
- }
- }, [filterEntity.sortingColumnLegend])
-
- let obj = React.useContext(AnalyticsUrlUpdaterContext.urlUpdaterContext)
- let updateExistingKeys = obj.updateExistingKeys
-
- let {initialFilters, initialFixedFilters, defaultFilterKeys, filterKeys} = filterEntity
- let (initialFilterVals, setInitialFilterVals) = React.useState(_ =>
- filterKeys
- ->Js.Array2.map(ele => (ele, ["Loading..."->Js.Json.string]->Js.Json.array))
- ->Js.Dict.fromArray
- )
-
- let customFilterKey = switch filterEntity {
- | {customFilterKey} => customFilterKey
- | _ => ""
- }
-
- let filteredTabKeys = filterKeys
-
- let getModuleFilters = UrlUtils.useGetFilterDictFromUrl("")
- let startTimeVal = getModuleFilters->getString(startTimeFilterKey, "")
- let fetchApi = AuthHooks.useApiFetcher(~betaEndpointConfig=?betaEndPointConfig, ())
- let addLogsAroundFetch = EulerAnalyticsLogUtils.useAddLogsAroundFetchNew()
- let endTimeVal = getModuleFilters->getString(endTimeFilterKey, "")
- let buttonOnClick = React.useCallback4(metric => {
- let timeObj = Js.Dict.fromArray([
- ("start", startTimeVal->Js.Json.string),
- ("end", endTimeVal->Js.Json.string),
- ])
- let tableBody = AnalyticsNewUtils.apiBodyMaker(
- ~timeObj,
- ~metric,
- ~groupBy=[metric],
- ~sortingParams?,
- ~domain,
- ~dataLimit=300.,
- (),
- )
- if (
- initialFilterVals
- ->getArrayFromDict(metric, [])
- ->Js.Array2.includes("Loading..."->Js.Json.string)
- ) {
- fetchApi(
- `/api/q/analyticsEndPoint`,
- ~method_=Post,
- ~bodyStr=tableBody->Js.Json.stringify,
- ~authToken=parentToken,
- ~headers=[("QueryType", "Filter")]->Js.Dict.fromArray,
- (),
- )
- ->addLogsAroundFetch(~logTitle="Filter Api")
- ->then(text => {
- let jsonObj = convertNewLineSaperatedDataToArrayOfJson(text)
- let resArr =
- jsonObj
- ->Js.Array2.reduce(
- (arr, ele) => {
- let dictValue =
- ele
- ->getDictFromJsonObject
- ->Js.Dict.values
- ->Js.Array2.map(
- item => {
- switch item->Js.Json.classify {
- | JSONString(str) => str
- | JSONNumber(num) => num->Belt.Float.toString
- | JSONTrue => "TRUE"
- | JSONFalse => "FALSE"
- | _ => ""
- }->Js.Json.string
- },
- )
- arr->Js.Array2.concat(dictValue)
- },
- [],
- )
- ->Js.Array2.filter(
- ele => {
- ele->getStringFromJson("") !== ""
- },
- )
- setInitialFilterVals(
- prev => {
- let newDict = prev->Js.Dict.entries->Js.Dict.fromArray
- newDict->Js.Dict.set(metric, resArr->Js.Json.array)
- newDict
- },
- )
- resolve()
- })
- ->catch(_err => {
- resolve()
- })
- ->ignore
- }
- }, (startTimeVal, endTimeVal, initialFilterVals, sortingParams))
-
-
- Js.Json.object_, buttonOnClick)}
- options=[]
- popupFilterFields=[]
- initialFixedFilters={initialFixedFilters(Js.Json.null)}
- defaultFilterKeys
- tabNames=filteredTabKeys
- updateUrlWith=updateExistingKeys //
- key="0"
- showCustomFilter=true
- customViewTop=downloadDataButtonUi
- moduleName=filterEntity.moduleName
- customFilterKey
- filterFieldsPortalName=""
- showSelectFiltersSearch=true
- revampedFilter=true
- />
-
- }
-}
-
-module DownloadCsv = {
- @react.component
- let make = (
- ~title: string,
- ~tableData: Js.Array2.t>,
- ~visibleColumns: Js.Array2.t<'colType>,
- ~colMapper,
- ~getHeading: 'colType => Table.header,
- ) => {
- let isMobileView = MatchMedia.useMobileChecker()
- let actualDataOrig =
- tableData
- ->Belt.Array.keepMap(item => item->Js.Nullable.toOption)
- ->Js.Array2.map(convertToStrDict)
-
- let headerNames = visibleColumns->Belt.Array.keepMap(head => {
- let item = head->getHeading
- let title = head->colMapper
- title !== "" ? Some(item.title) : None
- })
- let initialValues = visibleColumns->Belt.Array.keepMap(head => {
- let title = head->colMapper
- title !== "" ? Some(title) : None
- })
-
- let handleDownloadClick = _ev => {
- let header = headerNames->Js.Array2.joinWith(",")
-
- let csv =
- actualDataOrig
- ->Js.Array2.map(allRows => {
- let allRowsDict =
- Js.Json.decodeObject(allRows)->Belt.Option.getWithDefault(Js.Dict.empty())
- initialValues
- ->Js.Array2.map(col => {
- let str =
- Js.Dict.get(allRowsDict, col)
- ->Belt.Option.getWithDefault(Js.Json.null)
- ->Js.Json.stringify
-
- let strArr = str->Js.String2.split(".")
-
- let newStr = if (
- strArr->Js.Array2.length === 2 && str->Belt.Float.fromString->Belt.Option.isSome
- ) {
- let newDecimal =
- strArr
- ->Belt.Array.get(1)
- ->Belt.Option.getWithDefault("00")
- ->Js.String2.slice(~from=0, ~to_=2)
- strArr->Belt.Array.get(0)->Belt.Option.getWithDefault("0") ++ "." ++ newDecimal
- } else {
- str
- }
- newStr
- })
- ->Js.Array2.joinWith(",")
- })
- ->Js.Array2.joinWith("\n")
- let finalCsv = header ++ "\n" ++ csv
- let currentTime = Js.Date.now()->Js.Float.toString
- DownloadUtils.downloadOld(~fileName=`${title}_${currentTime}.csv`, ~content=finalCsv)
- }
-
-
- }
-}
-
-module DownloadRawData = {
- @react.component
- let make = (
- ~totalVolume,
- ~downloadDataEntity: AnalyticsUtils.downloadDataEntity,
- ~moduleName,
- ) => {
- let {addConfig, getConfig} = React.useContext(UserPrefContext.userPrefContext)
- let previouslySelectedColumnsUserPrefKey = `download_data_column_${moduleName}`
- let previouslySelectedDownloadData = switch getConfig(previouslySelectedColumnsUserPrefKey) {
- | Some(jsonVal) =>
- jsonVal
- ->LogicUtils.getStrArryFromJson
- ->Js.Array2.filter(item => {downloadDataEntity.downloadRawDataCols->Js.Array2.includes(item)})
- | None => []
- }
- let fetchApi = AuthHooks.useApiFetcher()
- let (showModal, setShowModal) = React.useState(_ => false)
- let (downloadData, setDownloadData) = React.useState(() => previouslySelectedDownloadData)
- let showToast = ToastState.useShowToast()
- let (buttonState, setButtonState) = React.useState(_ => Button.Normal)
- let isMobileView = MatchMedia.useMobileChecker()
-
- let (isCheckboxSelected, setIsCheckboxSelected) = React.useState(_ => false)
- let getModuleFilters = UrlUtils.useGetFilterDictFromUrl("")
-
- let parentToken = AuthWrapperUtils.useTokenParent(Original)
- let downloadDataUrl = downloadDataEntity.uri
-
- let modalHeadingDescription = switch downloadDataEntity {
- | {description} => description
- | _ => ""
- }
-
- let {timeKeys, downloadRawDataCols, downloadDataBody} = downloadDataEntity
-
- let {startTimeKey, endTimeKey} = timeKeys
- let startDateTime = getModuleFilters->getString(startTimeKey, "")
-
- let endDateTime = getModuleFilters->getString(endTimeKey, "")
- let formattedOptions = React.useMemo1(() => {
- downloadRawDataCols->Js.Array2.map((x): SelectBox.dropdownOption => {
- {label: x->snakeToTitle, value: x}
- })
- }, [downloadRawDataCols])
-
- let handleDownloadClick = _ev => {
- setShowModal(_ => true)
- }
- let setIsCheckboxSelected = value => {
- setIsCheckboxSelected(_ => value)
- }
-
- let onSubmit = values => {
- setDownloadData(_ => values)
- addConfig(previouslySelectedColumnsUserPrefKey, values->Js.Json.stringArray)
- setButtonState(_ => Button.Loading)
- setShowModal(_ => false)
-
- let downloadDataEntity: AnalyticsUtils.downloadDataApiBodyEntity = {
- startTime: startDateTime,
- endTime: endDateTime,
- columns: values,
- compressed: isCheckboxSelected,
- }
-
- if downloadDataUrl !== "" {
- fetchApi(
- downloadDataUrl,
- ~bodyStr=downloadDataBody(downloadDataEntity),
- ~method_=Fetch.Post,
- ~authToken=parentToken,
- ~headers=[("QueryType", "DownloadData")]->Js.Dict.fromArray,
- (),
- )
- ->then(resp => {
- let statusCode = resp->Fetch.Response.status
- setShowModal(_ => false)
- setButtonState(_ => Button.Normal)
- if statusCode !== 200 {
- showToast(~toastType=ToastError, ~message=`Something went wrong`, ~autoClose=true, ())
- }
- resp->Fetch.Response.json
- })
- ->then(res => {
- let downloadDataUrl = res->getDictFromJsonObject->getString("signedURL", "")
- Webapi.Dom.window
- ->Webapi.Dom.Window.open_(~url=downloadDataUrl, ~name="_blank", ())
- ->ignore
-
- resolve()
- })
- ->catch(_err => {
- resolve()
- })
- ->ignore
- }
- }
- if downloadRawDataCols->Js.Array2.length > 0 {
- <>
- {if isMobileView {
- React.null
- } else {
-
-
-
- }}
-
- >
- } else {
- React.null
- }
- }
-}
-
-module SankeyWithDropDown = {
- @react.component
- let make = (
- ~data,
- ~activeTab,
- ~dataLoading,
- ~sankeyConfig,
- ~startNodeLable="Total Volume",
- ~endNodeLable="Status",
- ~loaderType: AnalyticsUtils.loaderType,
- ) => {
- let (sankeyCardinality, setSankeyCardinality) = React.useState(_ => 5)
- let selectInput: ReactFinalForm.fieldRenderPropsInput = {
- name: "snakey_cardinality",
- onBlur: _ev => (),
- onChange: ev => {
- setSankeyCardinality(_ => {
- ev->formEventToStr->Belt.Int.fromString->Belt.Option.getWithDefault(5)
- })
- },
- onFocus: _ev => (),
- value: sankeyCardinality->Belt.Int.toString->Js.Json.string,
- checked: true,
- }
- let selectInputOption = React.useMemo0(() => {
- ["5", "10"]
- ->SelectBox.makeOptions
- ->Js.Array2.map(item => {
- ...item,
- label: `Top ${item.label}`,
- })
- })
-
- let buttonText = React.useMemo1(() => {
- `Top ${sankeyCardinality->Js.String.make} `
- }, [sankeyCardinality])
-
- let field =
- )
- ellipsisOnly=true
- customButtonStyle="min-w-full justify-between"
- />}
- hideMultiSelectButtons=true
- deselectDisable=true
- buttonType=Button.Primary
- marginTop="mt-10 min-w-full" // mt-10 because the height of the small button is 10
- />
-
-
- }
-}
-
-module ErrorModalContent = {
- @react.component
- let make = (
- ~str: string,
- ~entity: EntityType.entityType<'modalColType, 'modalTable>,
- ~filterByData,
- ~showModalBarChart: string,
- ~colName: string,
- ) => {
- React.useEffect0(() => {
- let onKeyDown = (event: 'a) => {
- let key = event->keyCode
- if key === 13 {
- event->ReactEvent.Keyboard.preventDefault
- }
- }
-
- Window.addEventListener("keydown", onKeyDown)
-
- Some(() => Window.removeEventListener("keydown", onKeyDown))
- })
- let (offset, setOffset) = React.useState(() => 0)
- let searchText = ReactFinalForm.useField("searchTable").input.value
- let search_class = "text-gray-400 dark:text-gray-600"
- let (theme, _setTheme) = React.useContext(ThemeProvider.themeContext)
- let splitString =
- Js.String2.split(str, "$$")->Js.Array2.map(errStr =>
- Js.String2.splitByRe(Js.String2.trim(errStr), %re("/\s*[(%)]\s*/"))
- )
-
- let actualData12 = if Js.Array2.length(splitString[0]->Belt.Option.getWithDefault([])) > 1 {
- splitString->Js.Array2.map(arr => {
- let arr = Belt.Array.keepMap(arr, item => item)
-
- Js.Dict.fromArray(
- [
- (colName, arr->Belt.Array.get(0)),
- ("percent", arr->Belt.Array.get(1)),
- ("volume", arr->Belt.Array.get(4)),
- ]->Js.Array2.map(item => {
- let (key, value) = item
- (key, value->Belt.Option.getWithDefault("")->Js.Json.string)
- }),
- )
- })
- } else {
- []
- }
- let data = if Js.Array2.length(actualData12) !== 0 {
- actualData12
- ->Js.Array2.map(arr => arr->Js.Json.object_)
- ->Js.Json.array
- ->entity.getObjects
- ->Js.Array2.map(Js.Nullable.return)
- } else {
- []
- }
- let actualData = React.useMemo2(() => {
- data->filterByData(searchText)
- }, (searchText, data))
-
- let searchTable = FormRenderer.makeFieldInfo(
- ~label="",
- ~name="searchTable",
- ~placeholder="Search ",
- ~customInput=InputFields.textInput(
- ~customStyle="w-64",
- ~autoComplete="off",
- ~leftIcon= ,
- (),
- ),
- (),
- )
-
- // chart data
-
- let categoryData = actualData12->Js.Array2.map(json => {
- json->getString(colName, "")
- })
-
- let chartData = if Js.Array2.length(actualData12) !== 0 {
- actualData12->Js.Array2.map(json => {
- {
- "unit": json->getString(colName, ""),
- "y": json->getFloat("percent", 0.0),
- }
- })
- } else {
- []
- }
-
- let options: Js.Json.t = React.useMemo4(() => {
- let data = [
- {
- "data": chartData,
- },
- ]
- let categories = categoryData
- let title = {snakeToTitle(colName)}
- let gridLineColor = switch theme {
- | Dark => "#2e2f39"
- | Light => "#e6e6e6"
- }
- {
- "chart": {
- "type": "column",
- "zoomType": "x",
- "backgroundColor": Js.Nullable.null,
- },
- "title": {
- "enabled": false,
- "style": LineChartUtils.chartTitleStyle(theme),
- "text": title,
- "margin": 40,
- },
- "tooltip": {
- "enabled": true,
- "useHTML": true,
- "pointFormat": ` {point.y}%
`,
- "headerFormat": "{point.key}"->Some,
- "hideDelay": 0,
- "backgroundColor": "white",
- "valueDecimals": 2,
- "outside": true,
- },
- "yAxis": {
- "gridLineColor": gridLineColor,
- "min": 0,
- "title": {
- "enabled": true,
- "style": LineChartUtils.chartTitleStyle(theme),
- "text": title,
- "margin": 20,
- },
- "labels": {
- "format": "{text}%"->Some,
- "enabled": true,
- "useHTML": true,
- }->Some,
- },
- "xAxis": {
- "categories": categories,
- },
- "plotOptions": {
- "column": {
- "stacking": "Normal",
- },
- },
- "legend": {
- "enabled": false,
- },
- "series": data,
- "credits": {
- "enabled": false,
- },
- }->objToJson
- }, (chartData, categoryData, colName, theme))
- if showModalBarChart == "Table" {
-
-
- Js.Array2.length}
- offset
- setOffset
- entity
- defaultSort={
- key: "volume",
- order: Table.INC,
- }
- currrentFetchCount={actualData->Js.Array2.length}
- title="Analytics Error Summary Table OnClickDetails"
- hideTitle=true
- resultsPerPage=10
- highlightText={searchText->getStringFromJson("")}
- />
-
- } else {
-
- }
- }
-}
-
-module ErrorOnCellClick = {
- @react.component
- let make = (
- ~val,
- ~str,
- ~entity: EntityType.entityType<'modalColType, 'modalTable>,
- ~filterByData,
- ~colName: string,
- ) => {
- let topNValues = None
- let (showErrorTableModal, setShowErrorTableModal) = React.useState(_ => false)
- let (showModalBarChart, setShowModalBarChart) = React.useState(_ => "Table")
- let (modalErrorHeading, setModalErrorHeading) = React.useState(_ => "")
- let (defaultFilter, _) = Recoil.useRecoilState(AnalyticsHooks.defaultFilter)
- let defaultFilterDict = defaultFilter->safeParse->getDictFromJsonObject
- let activeTab =
- defaultFilterDict
- ->getArrayFromDict("activeTab", [])
- ->Js.Array2.map(key => {
- key->getStringFromJson("")
- })
- let defaultFilters = defaultFilterDict->getJsonObjectFromDict("filter")->getDictFromJsonObject
- let dictKeys = val->Js.Dict.keys
- let filters = defaultFilters->getJsonObjectFromDict("filters")->getDictFromJsonObject
- let filterKeys = filters->Js.Dict.keys
-
- let cellText = switch topNValues {
- | Some(topNValues) =>
- Js.String2.split(str, "$$")
- ->Js.Array2.map(item => {
- let itemU = item->Js.String2.split("(")
- let lastElement =
- itemU->Belt.Array.get(itemU->Js.Array2.length - 1)->Belt.Option.getWithDefault("")
- let item = item->Js.String2.replace(`(${lastElement}`, "")
- (
- lastElement
- ->Js.String2.replace(")", "")
- ->Js.String.trim
- ->Belt.Int.fromString
- ->Belt.Option.getWithDefault(0),
- item,
- )
- })
- ->Js.Array2.sortInPlaceWith((item1, item2) => {
- let (x1, _y1) = item1
- let (x2, _y2) = item2
- if x1 > x2 {
- -1
- } else if x1 == x2 {
- 0
- } else {
- 1
- }
- })
- ->Js.Array2.mapi((item, index) => {
- let (_, value) = item
- index < topNValues ? Some(value) : None
- })
- ->Belt.Array.keepMap(item => item)
- ->Js.Array2.joinWith(`\n`)
-
- | None => Js.String2.split(str, "$$")->Js.Array2.joinWith(`\n`)
- }
- let cellText = Js.String2.split(cellText, "(")->Js.Array2.joinWith(` (`)
-
- activeTab->Js.Array2.forEach(key => {
- if !(filterKeys->Js.Array2.includes(key)) {
- filterKeys->Js.Array2.push(key)->ignore
- }
- })
- filterKeys->Js.Array2.forEach(key => {
- let value = val->getString(key, "")
- if dictKeys->Js.Array2.includes(key) && value !== "" {
- filters->Js.Dict.set(key, [value->Js.Json.string]->Js.Json.array)
- }
- })
-
- let valStr =
- activeTab
- ->Js.Array2.map(key => {
- val->getJsonObjectFromDict(key)
- })
- ->Js.Array2.joinWith(", ")
-
- let keyStr = activeTab->Js.Array2.map(snakeToTitle)->Js.Array2.joinWith(", ")
-
- let heading = `${keyStr} : ${valStr}`
-
- let onClick = _ => {
- setShowErrorTableModal(_ => true)
- setModalErrorHeading(_ => heading)
- }
-
- let renderModalChart = ev => {
- if ev == "Table" {
- setShowModalBarChart(_ => "Table")
- } else {
- setShowModalBarChart(_ => "Bar Chart")
- }
- }
-
- let modalInput: ReactFinalForm.fieldRenderPropsInput = {
- name: "modalInput",
- onBlur: _ev => (),
- onChange: ev => renderModalChart(ev->evToString),
- onFocus: _ev => (),
- value: ""->Js.Json.string,
- checked: true,
- }
-
- <>
-
-
- {React.string(cellText)}
-
}
- />
-
- {if showErrorTableModal {
-
-
-
- } else {
- React.null
- }}
- >
- }
-}
-
-module OnCellClick = {
- @react.component
- let make = (
- ~val,
- ~num,
- ~mapper,
- ~tabValues: array,
- ~domain: string,
- ~customFilterKey: option=?,
- ~summaryTableOnClickEntity,
- ~filterByData,
- ) => {
- let clearFormattingValue =
- ReactFinalForm.useField("enableFormattedData").input.value
- ->Js.Json.decodeBoolean
- ->Belt.Option.getWithDefault(false)
- let (showTableModal, setShowTableModal) = React.useState(_ => false)
- let (modalHeading, setModalHeading) = React.useState(_ => "")
- let (defaultFilter, _) = Recoil.useRecoilState(AnalyticsHooks.defaultFilter)
- let {filterValue} = React.useContext(AnalyticsUrlUpdaterContext.urlUpdaterContext)
- let defaultFilterDict = defaultFilter->safeParse->getDictFromJsonObject
- let activeTab =
- defaultFilterDict
- ->getArrayFromDict("activeTab", [])
- ->Js.Array2.map(key => {
- key->getStringFromJson("")
- })
- let defaultFilters = defaultFilterDict->getJsonObjectFromDict("filter")->getDictFromJsonObject
- let dictKeys = val->Js.Dict.keys
- let filters = defaultFilters->getJsonObjectFromDict("filters")->getDictFromJsonObject
- let filterKeys = filters->Js.Dict.keys
- let getTitle = key => {
- (
- tabValues
- ->Js.Array2.filter(item => {
- item.value == key
- })
- ->Belt.Array.get(0)
- ->Belt.Option.getWithDefault({title: "", value: "", isRemovable: false})
- ).title
- }
-
- activeTab->Js.Array2.forEach(key => {
- if !(filterKeys->Js.Array2.includes(key)) {
- filterKeys->Js.Array2.push(key)->ignore
- }
- })
- filterKeys->Js.Array2.forEach(key => {
- let value = val->getString(key, "")
- if dictKeys->Js.Array2.includes(key) && value !== "" {
- filters->Js.Dict.set(key, [value->Js.Json.string]->Js.Json.array)
- }
- })
- let currentCustomFilterValue = switch customFilterKey {
- | Some(customFilterKey) =>
- filterValue->Js.Dict.get(customFilterKey)->Belt.Option.getWithDefault("")
- | None => ""
- }
-
- defaultFilters->Js.Dict.set("filters", filters->Js.Json.object_)
- if currentCustomFilterValue !== "" {
- defaultFilters->Js.Dict.set("customFilter", currentCustomFilterValue->Js.Json.string)
- }
-
- let valStr =
- activeTab
- ->Js.Array2.map(key => {
- val->getJsonObjectFromDict(key)
- })
- ->Js.Array2.joinWith(", ")
-
- let keyStr = activeTab->Js.Array2.map(getTitle)->Js.Array2.joinWith(", ")
-
- let heading = `${keyStr} : ${valStr}`
- let search_class = "text-gray-400 dark:text-gray-600"
- let searchTable = FormRenderer.makeFieldInfo(
- ~label="",
- ~name="searchTable",
- ~placeholder="Search ",
- ~customInput=InputFields.textInput(
- ~customStyle="w-64",
- ~autoComplete="off",
- ~leftIcon= ,
- (),
- ),
- (),
- )
-
- let onClick = _ => {
- setShowTableModal(_ => true)
- setModalHeading(_ => heading)
- }
- <>
-
- {React.string({clearFormattingValue ? num->Belt.Float.toString : num->mapper})}
-
- {if showTableModal {
-
-
-
- } else {
- React.null
- }}
- >
- }
-}
-
-module BaseTableComponent = {
- @react.component
- let make = (
- ~filters: (string, string),
- ~tableData: Js.Json.t,
- ~defaultSort: string,
- ~tableDataLoading: bool,
- ~transactionTableDefaultCols,
- ~newDefaultCols: array<'colType>,
- ~newAllCols: array<'colType>,
- ~getTransactionTable: Js.Json.t => array<'t>,
- ~colMapper: 'colType => string,
- ~tableEntity: EntityType.entityType<'colType, 't>,
- ~tableGlobalFilter: option<(array>, Js.Json.t) => array>>,
- ~activeTab,
- ~text,
- ~showDeltaToggleUi: option=?,
- ~loaderType: AnalyticsUtils.loaderType,
- ) => {
- open DynamicTableUtils
- let actualData = React.useMemo2(() => {
- let data = tableData->getDictFromJsonObject
- let value =
- data
- ->getJsonObjectFromDict("queryData")
- ->getTransactionTable
- ->Js.Array2.map(Js.Nullable.return)
- value
- }, (tableData, getTransactionTable))
- let {parentAuthInfo} = React.useContext(TokenContextProvider.tokenContext)
- let userInfoText = React.useMemo1(() => {
- switch parentAuthInfo {
- | Some(info) => `${info.merchantId}_tab_performance_table_table_${info.username}_currentTime` // tab name also need to be added based on tab currentTime need to be added
- | None => ""
- }
- }, [parentAuthInfo])
- let isMobileView = MatchMedia.useMobileChecker()
- let (showColumnSelector, setShowColumnSelector) = React.useState(() => false)
- let (offset, setOffset) = React.useState(_ => 0)
- let (_, setCounter) = React.useState(_ => 1)
- let refetch = React.useCallback1(_ => {
- setCounter(p => p + 1)
- }, [setCounter])
- let {defaultColumns} = tableEntity
- let visibleColumns = Recoil.useRecoilValueFromAtom(transactionTableDefaultCols)
- let (startTimeFilter, endTimeFilter) = filters
- let downloadDataText = `${userInfoText}_${startTimeFilter}_${endTimeFilter}`
- let defaultSort: Table.sortedObject = {
- key: defaultSort,
- order: Table.INC,
- }
-
- let rightTitleElement = React.useMemo2(() => {
- )}
- buttonType=SecondaryFilled
- buttonSize=Small
- onClick={_ => setShowColumnSelector(_ => true)}
- />
- }, (setShowColumnSelector, isMobileView))
-
- let modifiedTableEntity = React.useMemo3(() => {
- {
- ...tableEntity,
- defaultColumns: newDefaultCols,
- allColumns: Some(newAllCols),
- }
- }, (tableEntity, newDefaultCols, newAllCols))
-
- let filterKeysJson = ReactFinalForm.useField("searchField").input.value
-
- let clearFormattingValue =
- ReactFinalForm.useField("enableFormattedData").input.value
- ->Js.Json.decodeBoolean
- ->Belt.Option.getWithDefault(false)
-
- let actualData = React.useMemo2(() => {
- switch tableGlobalFilter {
- | Some(tableGlobalFilter) => actualData->tableGlobalFilter(filterKeysJson)
- | None => actualData
- }
- }, (actualData, filterKeysJson))
- let search_class = "text-gray-400 dark:text-gray-600"
-
- let clearFormattingToggleUi = FormRenderer.makeFieldInfo(
- ~name="enableFormattedData",
- ~label="Clear Formatting",
- ~customInput=InputFields.boolInput(~isDisabled=false),
- (),
- )
-
- let initialFilterFields = FormRenderer.makeFieldInfo(
- ~label="",
- ~name="searchField",
- ~placeholder="Search",
- ~customInput=InputFields.textInput(
- ~customStyle=`w-64 tableSearch`,
- ~autoComplete="off",
- ~leftIcon= ,
- (),
- ),
- (),
- )
-
- let filt = React.useMemo6(() => {
-
- Js.Array2.length}
- defaultColumns
- activeColumnsAtom={transactionTableDefaultCols}
- setShowColumnSelector
- showColumnSelector
- sortingBasedOnDisabled=false
- orderdColumnBasedOnDefaultCol=true
- showSerialNumber=false
- mandatoryOptions=activeTab
- />
-
- }, (
- modifiedTableEntity,
- actualData,
- transactionTableDefaultCols,
- setShowColumnSelector,
- showColumnSelector,
- defaultColumns,
- ))
-
- let clearFormattedDataButton = switch showDeltaToggleUi {
- | Some(toggleUi) =>
-
-
- {React.null}
- {toggleUi}
-
-
-
- | None =>
-
- }
-
- let bottomMargin = "-mb-13"
- let tableBorderClass = "border-collapse border border-jp-gray-940 border-solid border-2 rounded-sm border-opacity-30 dark:border-jp-gray-dark_table_border_color dark:border-opacity-30"
- let downloadCsv =
-
- let frozenIndex = activeTab->Js.Array2.length
-
-
- {if loaderType === Shimmer && tableDataLoading {
-
- } else {
- {
- <>
-
-
-
- {React.string(text)}
-
-
- {if tableDataLoading && loaderType === SideLoader {
-
-
-
- } else {
- React.null
- }}
-
-
-
-
-
-
- Js.Array2.length}
- filters={filt}
- offset
- setOffset
- defaultSort
- rightTitleElement={rightTitleElement}
- currrentFetchCount={actualData->Js.Array2.length}
- clearFormattedDataButton
- downloadCsv={downloadCsv}
- tableLocalFilter=true
- tableheadingClass=tableBorderClass
- tableBorderClass
- tableDataBorderClass=tableBorderClass
- frozenUpto={isMobileView ? 1 : frozenIndex}
- highlightText={filterKeysJson->getStringFromJson("")}
- clearFormatting=clearFormattingValue
- isAnalyticsModule=true
- showTableOnMobileView=true
- />
-
-
- >
- }
- }}
-
-
- }
-}
-
-let useTableSankeyWrapper = (
- ~sankeyEntity: option,
- ~colMapper: 'colType => string,
- ~analyticsTableEntity: AnalyticsUtils.analyticsTableEntity<'colType, 't>,
- ~text,
-) => {
- let getModuleFilters = UrlUtils.useGetFilterDictFromUrl("")
- let parentToken = AuthWrapperUtils.useTokenParent(Original)
-
- let activeTab = React.useMemo1(() => {
- getModuleFilters->getOptionStrArrayFromDict(`${analyticsTableEntity.moduleName}.tabName`)
- }, [getModuleFilters])
-
- let (activeTabState, setActiveTabState) = React.useState(_ => activeTab)
-
- let {
- tableEntity,
- defaultSortCol,
- deltaMetrics,
- isIndustry,
- distributionArray,
- metrics,
- tableUpdatedHeading,
- tableGlobalFilter,
- moduleName,
- filterKeys,
- timeKeys,
- modeKey,
- moduleNamePrefix,
- source,
- } = analyticsTableEntity
- let tableSelectedColumnUserPrefKey = `dynamicTable_selected_columns_${moduleName}`
- let tableMetrics = metrics
-
- let tableCustomFilterKey = switch analyticsTableEntity {
- | {customFilterKey} => customFilterKey
- | _ => ""
- }
-
- let defaultSort = defaultSortCol
- let {getObjects} = tableEntity
- let getTransactionTable = getObjects
- let (tableLoading, setTableLoading) = React.useState(_ => false)
- let (tableHeaderLoading, setShowTableHeaderLoading) = React.useState(_ => false)
- let {getHeading, allColumns, defaultColumns} = tableEntity
- let allMetricColumn = defaultColumns
- let activeTabStr = activeTab->Belt.Option.getWithDefault([])->Js.Array2.joinWith("-")
- let {startTimeKey, endTimeKey} = timeKeys
- let (startTimeFilterKey, endTimeFilterKey) = (startTimeKey, endTimeKey)
- let (showDelta, setShowDelta) = React.useState(_ => false)
- // with prefix will be specific for the component level filter but without prefix will be at the overall level filters
- let getAllFilter = UrlUtils.useGetFilterDictFromUrl("")
- let showDeltaInput: ReactFinalForm.fieldRenderPropsInput = {
- name: "showDelta",
- onBlur: _ev => (),
- onChange: ev => setShowDelta(_ => ev->formEventToBoolean),
- onFocus: _ev => (),
- value: showDelta->Js.Json.boolean,
- checked: false,
- }
-
- // without prefix only table related Filters
- let getTopLevelFilter = React.useMemo1(() => {
- getAllFilter
- ->Js.Dict.entries
- ->Belt.Array.keepMap(item => {
- let (key, value) = item
- let keyArr = key->Js.String2.split(".")
- let prefix = keyArr->Belt.Array.get(0)->Belt.Option.getWithDefault("")
- if prefix === moduleName && prefix !== "" {
- None
- } else {
- Some((prefix, value))
- }
- })
- ->Js.Dict.fromArray
- }, [getAllFilter])
-
- let allColumns = allColumns->Belt.Option.getWithDefault([])
- let defaultTableColumn = switch analyticsTableEntity {
- | {defaultColumn} => defaultColumn
- | {tableEntity} => tableEntity.allColumns->Belt.Option.getWithDefault([])
- }
-
- let consumeSankeyFetchedData = React.useMemo1(() => {
- switch sankeyEntity {
- | Some(sankeyEntity) => sankeyEntity.fetchData
- | None => false
- }
- }, [sankeyEntity])
- // NOTE ideally these filters keys should be passed in datatable entity or if we make a entity for the table and sankey
-
- let (_, setDefaultFilter) = Recoil.useRecoilState(AnalyticsHooks.defaultFilter)
-
- let mode = switch modeKey {
- | Some(modeKey) => Some(getTopLevelFilter->getString(modeKey, ""))
- | None => Some("ORDER")
- }
-
- let allFilterKeys = Js.Array2.concat(
- [startTimeFilterKey, endTimeFilterKey, mode->Belt.Option.getWithDefault("")],
- filterKeys,
- )
-
- let (topFiltersToSearchParam, customFilter) = React.useMemo1(() => {
- let filterSearchParam =
- getTopLevelFilter
- ->Js.Dict.entries
- ->Belt.Array.keepMap(entry => {
- let (key, value) = entry
- if allFilterKeys->Js.Array2.includes(key) {
- switch value->Js.Json.classify {
- | JSONString(str) => `${key}=${str}`->Some
- | JSONNumber(num) => `${key}=${num->Js.String.make}`->Some
- | JSONArray(arr) => `${key}=[${arr->Js.String.make}]`->Some
- | _ => None
- }
- } else {
- None
- }
- })
- ->Js.Array2.joinWith("&")
-
- (filterSearchParam, getTopLevelFilter->LogicUtils.getString(tableCustomFilterKey, ""))
- }, [getTopLevelFilter])
-
- let filterValueFromUrl = React.useMemo1(() => {
- getTopLevelFilter
- ->Js.Dict.entries
- ->Belt.Array.keepMap(entries => {
- let (key, value) = entries
- filterKeys->Js.Array2.includes(key) ? Some((key, value)) : None
- })
- ->Js.Dict.fromArray
- ->Js.Json.object_
- ->Some
- }, [topFiltersToSearchParam])
-
- let startTimeFromUrl = React.useMemo1(() => {
- getTopLevelFilter->getString(startTimeFilterKey, "")
- }, [topFiltersToSearchParam])
- let endTimeFromUrl = React.useMemo1(() => {
- getTopLevelFilter->getString(endTimeFilterKey, "")
- }, [topFiltersToSearchParam])
- let {addConfig, getConfig} = React.useContext(UserPrefContext.userPrefContext)
- let fetchApi = AuthHooks.useApiFetcher()
-
- let (statusDict, setStatusDict) = React.useState(_ => Js.Dict.empty())
- let addLogsAroundFetch = EulerAnalyticsLogUtils.useAddLogsAroundFetch()
- let (sankeyLoading, setSankeyLoading) = React.useState(_ => true)
- let (sankeyFetchedData, setSankeyFetchedData) = React.useState(_ => None)
- let (sankeyLoaderType, setSankeyLoaderType) = React.useState(_ => AnalyticsUtils.Shimmer)
-
- let (tableData, setTableData) = React.useState(_ => None)
- let (tableInfoData, setTableInfoData) = React.useState(_ => Js.Json.object_(Js.Dict.empty()))
- let (tableLoaderType, setTableLoaderType) = React.useState(_ => AnalyticsUtils.Shimmer)
-
- let defaultTableColumn = React.useMemo0(() => {
- let defaultColumnsFromPref = switch getConfig(tableSelectedColumnUserPrefKey) {
- | Some(jsonVal) => jsonVal->LogicUtils.getStrArryFromJson
- | None => []
- }
-
- let defaultColumnFromUserPref = defaultTableColumn->Belt.Array.keepMap(item => {
- let getHeadingType = item->getHeading
- let key = getHeadingType.key
- defaultColumnsFromPref->Js.Array2.includes(key) ? Some(item) : None
- })
-
- if defaultColumnFromUserPref->Js.Array2.length === 0 {
- defaultTableColumn
- } else {
- defaultColumnFromUserPref
- }
- })
-
- let newDefaultCols = React.useMemo1(() => {
- activeTabState
- ->Belt.Option.getWithDefault([])
- ->Belt.Array.keepMap(item => {
- allMetricColumn
- ->Belt.Array.keepMap(
- columnItem => {
- let val = columnItem->getHeading
- val.key === item ? Some(columnItem) : None
- },
- )
- ->Belt.Array.get(0)
- })
- ->Belt.Array.concat(defaultTableColumn)
- }, [activeTabState->Belt.Option.getWithDefault([])->Js.Array2.joinWith("-")])
-
- let newAllCols = React.useMemo1(() => {
- allMetricColumn
- ->Belt.Array.keepMap(item => {
- let val = item->getHeading
- activeTabState->Belt.Option.getWithDefault([])->Js.Array2.includes(val.key)
- ? Some(item)
- : None
- })
- ->Belt.Array.concat(allColumns)
- }, [activeTabState->Belt.Option.getWithDefault([])->Js.Array2.joinWith("-")])
-
- let transactionTableDefaultCols = React.useMemo2(() => {
- Recoil.atom(.
- `${moduleName}${moduleNamePrefix}DefaultCols${activeTabState
- ->Belt.Option.getWithDefault([])
- ->Js.Array2.joinWith("-")}`,
- newDefaultCols,
- )
- }, (
- newDefaultCols,
- `${moduleName}DefaultCols${activeTabState
- ->Belt.Option.getWithDefault([])
- ->Js.Array2.joinWith("-")}`,
- ))
-
- let visibleColumns = Recoil.useRecoilValueFromAtom(transactionTableDefaultCols)
-
- React.useEffect1(() => {
- let visibleColumnsUpdated =
- visibleColumns
- ->Belt.Array.keepMap(item => {
- let item = item->getHeading
- let itemKey = item.key
- activeTabState->Belt.Option.getWithDefault([])->Js.Array2.includes(itemKey)
- ? None
- : Some(itemKey->Js.Json.string)
- })
- ->Js.Json.array
- addConfig(tableSelectedColumnUserPrefKey, visibleColumnsUpdated)
- None
- }, [visibleColumns])
-
- let deltaPrefixArr = switch analyticsTableEntity {
- | {colDependentDeltaPrefixArr} =>
- visibleColumns->Belt.Array.keepMap(item => item->colDependentDeltaPrefixArr)
- | {deltaPrefixArr} => deltaPrefixArr
- }
-
- let tableOverallBodyEntity: AnalyticsUtils.tableApiBodyEntity = {
- startTimeFromUrl,
- endTimeFromUrl,
- ?filterValueFromUrl,
- deltaMetrics,
- isIndustry,
- deltaPrefixArr,
- tableMetrics,
- ?mode,
- customFilter,
- moduleName,
- showDeltaMetrics: false,
- source,
- }
-
- let overallBody = switch analyticsTableEntity {
- | {tableSummaryBody} => tableSummaryBody(tableOverallBodyEntity)
- | _ => AnalyticsUtils.generateTablePayloadFromEntity(tableOverallBodyEntity)
- }
-
- let tableApiBodyEntity = {
- ...tableOverallBodyEntity,
- currenltySelectedTab: ?activeTab,
- ?distributionArray,
- showDeltaMetrics: showDelta,
- }
- let tableBody = switch analyticsTableEntity {
- | {tableBodyEntity} => tableBodyEntity(tableApiBodyEntity)
- | _ => AnalyticsUtils.generateTablePayloadFromEntity(tableApiBodyEntity)
- }
-
- let (updatedCell, showDeltaToggleUi) = switch analyticsTableEntity {
- | {getUpdatedCell} => (
- getUpdatedCell(tableApiBodyEntity),
- Some(InputFields.boolInput(~input=showDeltaInput, ~placeholder="", ~isDisabled=false)),
- )
- | {tableEntity} => (tableEntity.getCell, None)
- }
-
- React.useEffect5(() => {
- // overall values in table header
- setShowTableHeaderLoading(_ => true)
- setSankeyLoading(_ => true)
- setTableInfoData(_ => Js.Json.object_(Js.Dict.empty()))
- if startTimeFromUrl !== "" && endTimeFromUrl !== "" && parentToken->Belt.Option.isSome {
- fetchApi(
- tableEntity.uri,
- ~method_=Post,
- ~bodyStr=overallBody,
- ~authToken=parentToken,
- ~headers=[("QueryType", "TableInfo")]->Js.Dict.fromArray,
- (),
- )
- ->addLogsAroundFetch(~logTitle="Table info Data Api", ~setStatusDict)
- ->thenResolve(json => {
- setTableInfoData(_ => json)
- setShowTableHeaderLoading(_ => false)
- })
- ->catch(_err => {
- setTableInfoData(_ => Js.Json.object_(Js.Dict.empty()))
- setShowTableHeaderLoading(_ => false)
- resolve()
- })
- ->ignore
- }
- None
- }, (
- topFiltersToSearchParam,
- parentToken,
- customFilter,
- mode,
- deltaPrefixArr->Js.Array2.joinWith(""),
- ))
- React.useEffect6(() => {
- setTableLoading(_ => true)
- setSankeyLoading(_ => true)
- if (
- startTimeFromUrl !== "" &&
- endTimeFromUrl !== "" &&
- parentToken->Belt.Option.isSome &&
- activeTab->Belt.Option.isSome
- ) {
- fetchApi(
- tableEntity.uri,
- ~method_=Post,
- ~bodyStr=tableBody,
- ~authToken=parentToken,
- ~headers=[("QueryType", "TableSankey")]->Js.Dict.fromArray,
- (),
- )
- ->addLogsAroundFetch(~logTitle="Table and Sankey Data Api", ~setStatusDict)
- ->thenResolve(json => {
- setActiveTabState(_ => activeTab)
- setTableData(_ => json->Some)
- if !consumeSankeyFetchedData {
- setSankeyFetchedData(
- _ => Some(
- json->getDictFromJsonObject->getJsonObjectFromDict("queryData")->getArrayFromJson([]),
- ),
- )
- }
- setSankeyLoading(_ => false)
- setTableLoading(_ => false)
- })
- ->catch(_err => {
- setActiveTabState(_ => activeTab)
- setTableData(_ => Js.Json.object_(Js.Dict.empty())->Some)
- if !consumeSankeyFetchedData {
- setSankeyFetchedData(_ => Some([]))
- }
- setSankeyLoading(_ => false)
- setTableLoading(_ => false)
- resolve()
- })
- ->ignore
- }
- None
- }, (
- topFiltersToSearchParam,
- `${activeTabStr}${deltaPrefixArr->Js.Array2.joinWith("")}`,
- parentToken,
- customFilter,
- mode,
- showDelta,
- ))
-
- let tableEntity = React.useMemo3(() => {
- let data = tableInfoData->getDictFromJsonObject
- let tableInfoDesc =
- tableData->Belt.Option.getWithDefault(Js.Json.object_(Js.Dict.empty()))->getDictFromJsonObject
- let value = data->getJsonObjectFromDict("queryData")->getTransactionTable->Belt.Array.get(0)
- let metaData =
- tableInfoDesc->getArrayFromDict("metaData", [])->AnalyticsUtils.deltaTimeRangeMapper
-
- let getHeading = switch tableUpdatedHeading {
- | Some(tableUpdatedHeading) => tableUpdatedHeading(~item=value, ~dateObj=Some(metaData), ~mode)
- | None => getHeading
- }
-
- {
- ...tableEntity,
- getHeading,
- getCell: updatedCell,
- }
- }, (tableInfoData, showDelta, tableData))
- let sampleAiBodyMaker =
- analyticsTableEntity.sampleApiBody->Belt.Option.getWithDefault(AnalyticsUtils.sampleApiBody)
- let sampleApiBody = {...tableApiBodyEntity, ?filterValueFromUrl}
- let dict = sampleAiBodyMaker(sampleApiBody)
-
- React.useEffect1(() => {
- setDefaultFilter(._ => dict)
- None
- }, [dict])
-
- // sankey fetch
- React.useEffect4(() => {
- setSankeyLoading(_ => true)
- switch sankeyEntity {
- | Some(sankeyEntity) =>
- if sankeyEntity.fetchData {
- if startTimeFromUrl !== "" && endTimeFromUrl !== "" && parentToken->Belt.Option.isSome {
- fetchApi(
- sankeyEntity.uri,
- ~method_=Post,
- ~bodyStr=[
- AnalyticsUtils.getFilterRequestBody(
- ~groupByNames=sankeyEntity.groupByNames,
- ~filter=filterValueFromUrl,
- ~metrics=sankeyEntity.sankeyMetrics,
- ~delta=false,
- ~mode,
- ~startDateTime=startTimeFromUrl,
- ~endDateTime=endTimeFromUrl,
- ~customFilter,
- ~source=sankeyEntity.source,
- (),
- )->Js.Json.object_,
- ]
- ->Js.Json.array
- ->Js.Json.stringify,
- ~authToken=parentToken,
- ~headers=[("QueryType", "Sankey")]->Js.Dict.fromArray,
- (),
- )
- ->addLogsAroundFetch(~logTitle="Sankey Data Api")
- ->thenResolve(json => {
- setSankeyFetchedData(
- _ => Some(
- json
- ->getDictFromJsonObject
- ->getJsonObjectFromDict("queryData")
- ->getArrayFromJson([]),
- ),
- )
-
- setSankeyLoading(_ => false)
- })
- ->catch(_err => {
- setSankeyFetchedData(_ => Some([]))
- setSankeyLoading(_ => false)
- resolve()
- })
- ->ignore
- }
- }
-
- | None => ()
- }
-
- None
- }, (sankeyEntity, topFiltersToSearchParam, customFilter, mode))
-
- let (sankeyLevels, startNodeLable, endNodeLable) = React.useMemo2(() => {
- switch sankeyEntity {
- | Some(sankeyEntity) =>
- sankeyEntity.fetchData
- ? (sankeyEntity.groupByNames, sankeyEntity.startNodeLable, sankeyEntity.endNodeLable)
- : (activeTabState, "Total Volume", "Status")
- | None => (activeTabState, "Total Volume", "Status")
- }
- }, (activeTabState, sankeyEntity))
-
- let tableDataLoading = {tableLoading || tableHeaderLoading}
- React.useEffect2(() => {
- if tableData !== None && tableDataLoading === false {
- setTableLoaderType(_ => SideLoader)
- }
- None
- }, (tableData, tableDataLoading))
- React.useEffect3(() => {
- if sankeyFetchedData !== None && (sankeyLoading || tableDataLoading) == false {
- setSankeyLoaderType(_ => SideLoader)
- }
- None
- }, (sankeyFetchedData, tableDataLoading, sankeyLoading))
-
- let tableSankeyUi = () => {
- [
- {
- if statusDict->Js.Dict.values->Js.Array2.includes(504) {
-
- } else {
-
- }
- },
- {
- switch sankeyEntity {
- | Some(sankeyEntity) =>
-
- | None => React.null
- }
- },
- ]
- }
- tableSankeyUi
-}
-
-module TabDetails = {
- @react.component
- let make = (
- ~chartEntity: DynamicChart.entity,
- ~activeTab,
- ~sankeyEntity: option,
- ~colMapper: 'colType => string,
- ~modeKey=?,
- ~moduleName,
- ~updateUrl: Js.Dict.t => unit,
- ~text="Summary Table",
- ~analyticsTableEntity: option>,
- ) => {
- let tableSankeyWrapper = useTableSankeyWrapper()
-
-
-
- {switch analyticsTableEntity {
- | Some(analyticsTableEntity) =>
-
- {tableSankeyWrapper(~sankeyEntity, ~colMapper, ~text, ~analyticsTableEntity)->React.array}
-
- | None => React.null
- }}
-
- }
-}
-
-module ParentAnalyticsComponentV1 = {
- @react.component
- let make = (
- ~chartEntity as _: DynamicChart.entity,
- ~sankeyEntity as _: option=?,
- ~tabValues as _: array,
- ~colMapper as _: 'colType => string,
- ~stepsForModule=[],
- ~modeKey as _: option=?,
- ~analyticsTableEntity as _: option>=?,
- ~children=React.null,
- ~totalVolume=0,
- ~setTotalVolume=_ => (),
- ) => {
- let {filterValue} = React.useContext(AnalyticsUrlUpdaterContext.urlUpdaterContext)
- let isMobileView = MatchMedia.useMobileChecker()
-
- let getModuleFilters = UrlUtils.useGetFilterDictFromUrl("")
-
- let {parentAuthInfo} = React.useContext(TokenContextProvider.tokenContext)
-
- let authInfo = switch parentAuthInfo {
- | Some(info) => info
- | None => HyperSwitchAuthTypes.getDummyAuthInfoForToken("")
- }
-
- let updateComponentPrefrences = UrlUtils.useUpdateUrlWith(~prefix="")
-
- React.useEffect1(() => {
- updateComponentPrefrences(~dict=filterValue)
- None
- }, [filterValue])
-
- // as there should be always date and mode so added this condition
- if getModuleFilters->Js.Dict.entries->Js.Array2.length > 0 && authInfo.token !== "" {
-
- // case when no filters but download data is required
-
-
- } else {
- React.null
- }
- }
-}
-
-module ParentAnalyticsComponentNew = {
- @react.component
- let make = (~stepsForModule=[], ~domain="txns", ~children=React.null, ~totalVolume=0) => {
- let {filterValue} = React.useContext(AnalyticsUrlUpdaterContext.urlUpdaterContext)
- let isMobileView = MatchMedia.useMobileChecker()
-
- let getModuleFilters = UrlUtils.useGetFilterDictFromUrl("")
-
- let {parentAuthInfo} = React.useContext(TokenContextProvider.tokenContext)
-
- let authInfo = switch parentAuthInfo {
- | Some(info) => info
- | None => HyperSwitchAuthTypes.getDummyAuthInfoForToken("")
- }
-
- let updateComponentPrefrences = UrlUtils.useUpdateUrlWith(~prefix="")
-
- React.useEffect1(() => {
- updateComponentPrefrences(~dict=filterValue)
- None
- }, [filterValue])
-
- // as there should be always date and mode so added this condition
- if getModuleFilters->Js.Dict.entries->Js.Array2.length > 0 && authInfo.token !== "" {
-
- // case when no filters but download data is required
-
-
- } else {
- React.null
- }
- }
-}
-
-module OnCellClickDistribution = {
- @react.component
- let make = (
- ~valDict,
- ~value="Click to view",
- ~tabValues: array,
- ~domain: string,
- ~customFilterKey: option=?,
- ~summaryTableOnClickEntity,
- ~filterByData,
- ~metrics,
- ~groupBy,
- ~defSort: Table.sortedObject,
- ~defaultFiltersToModal=?,
- ) => {
- let (showTableModal, setShowTableModal) = React.useState(_ => false)
- let (modalHeading, setModalHeading) = React.useState(_ => "")
- let (defaultFilter, _) = Recoil.useRecoilState(AnalyticsHooks.defaultFilter)
- let {filterValue} = React.useContext(AnalyticsUrlUpdaterContext.urlUpdaterContext)
- let defaultFilterDict = defaultFilter->safeParse->getDictFromJsonObject
- let activeTab =
- defaultFilterDict
- ->getArrayFromDict("activeTab", [])
- ->Js.Array2.map(key => {
- key->getStringFromJson("")
- })
-
- let defaultFilters = defaultFilterDict->getJsonObjectFromDict("filter")->getDictFromJsonObject
- let dictKeys = valDict->Js.Dict.keys
- let filters = defaultFilters->getJsonObjectFromDict("filters")->getDictFromJsonObject
- let filterKeys = filters->Js.Dict.keys
- let getTitle = key => {
- (
- tabValues
- ->Js.Array2.filter(item => {
- item.value == key
- })
- ->Belt.Array.get(0)
- ->Belt.Option.getWithDefault({title: "", value: "", isRemovable: false})
- ).title
- }
-
- activeTab->Js.Array2.forEach(key => {
- if !(filterKeys->Js.Array2.includes(key)) {
- filterKeys->Js.Array2.push(key)->ignore
- }
- })
- filterKeys->Js.Array2.forEach(key => {
- let value = valDict->getString(key, "")
- if dictKeys->Js.Array2.includes(key) && value !== "" {
- filters->Js.Dict.set(key, [value->Js.Json.string]->Js.Json.array)
- }
- })
- let currentCustomFilterValue = switch customFilterKey {
- | Some(customFilterKey) =>
- filterValue->Js.Dict.get(customFilterKey)->Belt.Option.getWithDefault("")
- | None => ""
- }
-
- defaultFilters->Js.Dict.set("filters", filters->Js.Json.object_)
- if currentCustomFilterValue !== "" {
- defaultFilters->Js.Dict.set("customFilter", currentCustomFilterValue->Js.Json.string)
- }
-
- let valStr =
- activeTab
- ->Js.Array2.map(key => {
- valDict->getJsonObjectFromDict(key)
- })
- ->Js.Array2.joinWith(", ")
-
- let keyStr = activeTab->Js.Array2.map(getTitle)->Js.Array2.joinWith(", ")
-
- let heading = `${keyStr} : ${valStr}`
- let search_class = "text-gray-400 dark:text-gray-600"
- let searchTable = FormRenderer.makeFieldInfo(
- ~label="",
- ~name="searchTable",
- ~placeholder="Search ",
- ~customInput=InputFields.textInput(
- ~customStyle="w-64",
- ~autoComplete="off",
- ~leftIcon= ,
- (),
- ),
- (),
- )
-
- let onClick = _ => {
- setShowTableModal(_ => true)
- setModalHeading(_ => heading)
- }
- <>
-
- {React.string(`${value}`)}
-
- {if showTableModal {
-
-
-
- } else {
- React.null
- }}
- >
- }
-}
diff --git a/src/screens/login/HSwitchLoginFlow/HyperSwitchAuthUtils.res b/src/screens/login/HSwitchLoginFlow/HyperSwitchAuthUtils.res
index 8e2c7905a..3b8e7ccdc 100644
--- a/src/screens/login/HSwitchLoginFlow/HyperSwitchAuthUtils.res
+++ b/src/screens/login/HSwitchLoginFlow/HyperSwitchAuthUtils.res
@@ -1,5 +1,4 @@
open HyperSwitchAuthTypes
-external formEventToStr: ReactEvent.Form.t => string = "%identity"
module TermsAndCondition = {
@react.component
diff --git a/src/server/Server.res b/src/server/Server.res
index 1851223e1..087289adc 100644
--- a/src/server/Server.res
+++ b/src/server/Server.res
@@ -37,8 +37,6 @@ if appName === Some("hyperswitch") {
Fs.writeFileSync("dist/hyperswitch/hyperswitch.html", htmlInFs)
}
-external asJson: {..} => Js.Json.t = "%identity"
-
type encodeType = {encoding: string}
@module("child_process")
diff --git a/src/utils/FullscreenUtils.res b/src/utils/FullscreenUtils.res
index 2ea6c8da6..ab21842f5 100644
--- a/src/utils/FullscreenUtils.res
+++ b/src/utils/FullscreenUtils.res
@@ -1,5 +1,3 @@
-external toBool: 'a => bool = "%identity"
-
type elem = {
requestFullscreen: (. unit) => unit,
mozRequestFullScreen: (. unit) => unit,
@@ -19,26 +17,28 @@ type document = {
@val external document: document = "document"
let enableFullscreen = () => {
+ open Identity
let elem = document.documentElement
- if elem.requestFullscreen->toBool {
+ if elem.requestFullscreen->genericTypeToBool {
elem.requestFullscreen(.)
- } else if elem.mozRequestFullScreen->toBool {
+ } else if elem.mozRequestFullScreen->genericTypeToBool {
elem.mozRequestFullScreen(.) // Firefox
- } else if elem.webkitRequestFullscreen->toBool {
+ } else if elem.webkitRequestFullscreen->genericTypeToBool {
elem.webkitRequestFullscreen(.) // Chrome, Safari, and Opera
- } else if elem.msRequestFullscreen->toBool {
+ } else if elem.msRequestFullscreen->genericTypeToBool {
elem.msRequestFullscreen(.) // Internet Explorer/Edge
}
}
let exitFullscreen = () => {
- if document.exitFullscreen->toBool {
+ open Identity
+ if document.exitFullscreen->genericTypeToBool {
document.exitFullscreen(.)
- } else if document.mozCancelFullScreen->toBool {
+ } else if document.mozCancelFullScreen->genericTypeToBool {
document.mozCancelFullScreen(.) // Firefox
- } else if document.msExitFullscreen->toBool {
+ } else if document.msExitFullscreen->genericTypeToBool {
document.msExitFullscreen(.) // Internet Explorer/Edge
- } else if document.webkitExitFullscreen->toBool {
+ } else if document.webkitExitFullscreen->genericTypeToBool {
document.webkitExitFullscreen(.) // Chrome, Safari, and Opera
}
}
diff --git a/src/utils/JsonFlattenUtils.res b/src/utils/JsonFlattenUtils.res
index a7f398088..e4c5fbef0 100644
--- a/src/utils/JsonFlattenUtils.res
+++ b/src/utils/JsonFlattenUtils.res
@@ -1,5 +1,3 @@
-external toNullable: Js.Json.t => Js.Nullable.t = "%identity"
-
let rec flattenObject = (obj, addIndicatorForObject) => {
let newDict = Js.Dict.empty()
switch obj->Js.Json.decodeObject {
@@ -9,7 +7,7 @@ let rec flattenObject = (obj, addIndicatorForObject) => {
->Js.Array2.forEach(entry => {
let (key, value) = entry
- if value->toNullable->Js.Nullable.isNullable {
+ if value->Identity.jsonToNullableJson->Js.Nullable.isNullable {
Js.Dict.set(newDict, key, value)
} else {
switch value->Js.Json.decodeObject {