From aaa47a137ddb81bf2136c3e71d9aee34af48c5fc Mon Sep 17 00:00:00 2001 From: Pritish Budhiraja <77892330+PritishBudhiraja@users.noreply.github.com> Date: Fri, 1 Dec 2023 18:11:35 +0530 Subject: [PATCH 01/27] chore: remove dead code (#38) Co-authored-by: Jeeva Ramachandran <120017870+JeevaRamu0104@users.noreply.github.com> --- src/screens/login/AuthTypes.res | 72 ------- .../HSwitchLoginFlow/HyperSwitchAuthForm.res | 17 -- .../HSwitchLoginFlow/HyperSwitchAuthTypes.res | 4 - .../HSwitchLoginFlow/HyperSwitchAuthUtils.res | 46 ---- src/server/NodeJs.res | 6 +- src/server/Server.res | 9 - src/utils/AnalyticsNewUtils.res | 39 ---- src/utils/AnalyticsTypesUtils.res | 196 ------------------ src/utils/ArrayUtils.res | 24 --- src/utils/CurrencyFormatUtils.res | 10 - src/utils/DateRangeUtils.res | 9 - src/utils/DictionaryUtils.res | 44 +--- src/utils/Formatter.res | 46 ---- src/utils/HyperSwitchUtils.res | 17 -- 14 files changed, 2 insertions(+), 537 deletions(-) delete mode 100644 src/utils/Formatter.res diff --git a/src/screens/login/AuthTypes.res b/src/screens/login/AuthTypes.res index d0d87d6e6..cf51ce9fc 100644 --- a/src/screens/login/AuthTypes.res +++ b/src/screens/login/AuthTypes.res @@ -1,73 +1 @@ type authorization = NoAccess | Read | ReadWrite | Checker -open LogicUtils - -let getAccessTypeFromString = str => { - switch str { - | "R" => Read - | "Read" => Read - | "RW" => ReadWrite - | "ReadWrite" => ReadWrite - | "Write" => ReadWrite - | "CHECKER" => Checker - | _ => NoAccess - } -} - -let getAccessTypeFromBool = boolean => { - switch boolean { - | true => ReadWrite - | false => NoAccess - } -} - -let getArrayData = (dict, key) => { - switch Js.Dict.get(dict, key) { - | Some(value) => - switch value->Js.Json.decodeArray { - | Some(arr) => - let loginRoleArray = arr->Js.Array2.reduce((acc, item) => { - switch item->Js.Json.decodeString { - | Some(str) => - let _ = Js.Array2.push(acc, str) - | None => () - } - acc - }, []) - loginRoleArray - | None => [] - } - | None => [] - } -} - -let getAccessType = (accessType: Js.Nullable.t) => { - switch accessType->Js.Nullable.toOption { - | Some(str) => getAccessTypeFromString(str) - | None => NoAccess - } -} - -let getConvertedAuthInfoType = (dict, key) => { - let access = getString(dict, key, "NA") - getAccessType(access->Js.Nullable.return) -} - -let bestOf = (authorizations: array) => { - authorizations->Js.Array2.includes(ReadWrite) - ? ReadWrite - : authorizations->Js.Array2.includes(Checker) - ? Checker - : authorizations->Js.Array2.includes(Read) - ? Read - : NoAccess -} - -let worstOf = (authorizations: array) => { - authorizations->Js.Array2.includes(NoAccess) - ? NoAccess - : authorizations->Js.Array2.includes(Read) - ? Read - : authorizations->Js.Array2.includes(Checker) - ? Checker - : ReadWrite -} diff --git a/src/screens/login/HSwitchLoginFlow/HyperSwitchAuthForm.res b/src/screens/login/HSwitchLoginFlow/HyperSwitchAuthForm.res index c4e0885ef..18c1d0752 100644 --- a/src/screens/login/HSwitchLoginFlow/HyperSwitchAuthForm.res +++ b/src/screens/login/HSwitchLoginFlow/HyperSwitchAuthForm.res @@ -36,20 +36,3 @@ module ResetPasswordForm = { } } - -module ResendVerifyEmailForm = { - @react.component - let make = (~disableBtn) => { -
- -
- } -} diff --git a/src/screens/login/HSwitchLoginFlow/HyperSwitchAuthTypes.res b/src/screens/login/HSwitchLoginFlow/HyperSwitchAuthTypes.res index c8d4a9beb..16d723ecc 100644 --- a/src/screens/login/HSwitchLoginFlow/HyperSwitchAuthTypes.res +++ b/src/screens/login/HSwitchLoginFlow/HyperSwitchAuthTypes.res @@ -9,10 +9,6 @@ type authInfo = { type authStatus = LoggedOut | LoggedIn(authInfo) | CheckingAuthStatus open LogicUtils -let getBoolFromSideBarConfig = dict => { - dict->getDictfromDict("sideBarConfig") -} - let getAuthInfo = (json, str) => { let dict = json->JsonFlattenUtils.flattenObject(false) let emailKey = "email" diff --git a/src/screens/login/HSwitchLoginFlow/HyperSwitchAuthUtils.res b/src/screens/login/HSwitchLoginFlow/HyperSwitchAuthUtils.res index 2e79f95aa..599639e1a 100644 --- a/src/screens/login/HSwitchLoginFlow/HyperSwitchAuthUtils.res +++ b/src/screens/login/HSwitchLoginFlow/HyperSwitchAuthUtils.res @@ -306,52 +306,6 @@ module ToggleLiveTestMode = { } } -module InfoWithBack = { - @react.component - let make = (~authType, ~setAuthType) => { - let showInfoWithBack = switch authType { - | MagicLinkEmailSent - | ForgetPassword - | ForgetPasswordEmailSent - | ResendVerifyEmailSent - | ResendVerifyEmail => true - | _ => false - } - - - - -
{ - let backState = switch authType { - | MagicLinkEmailSent => SignUP - | ForgetPasswordEmailSent => ForgetPassword - | ResendVerifyEmailSent => ResendVerifyEmail - | ForgetPassword | _ => LoginWithPassword - } - setAuthType(_ => backState) - }}> - -
{"Back"->React.string}
-
-
- {switch authType { - | MagicLinkEmailSent | ForgetPasswordEmailSent | ResendVerifyEmailSent => -
- -
- | _ => React.null - }} -
-
- } -} - module Header = { @react.component let make = (~authType, ~setAuthType, ~email) => { diff --git a/src/server/NodeJs.res b/src/server/NodeJs.res index 45612dc7b..6a13d8ffb 100644 --- a/src/server/NodeJs.res +++ b/src/server/NodeJs.res @@ -1,9 +1,5 @@ type promisifyable - -type execResponse = { - stdout: string, - stderr: string, -} +type execResponse type promiseableExecFile = (. string, array) => Promise.t module Util = { diff --git a/src/server/Server.res b/src/server/Server.res index c2bed2f80..1851223e1 100644 --- a/src/server/Server.res +++ b/src/server/Server.res @@ -31,15 +31,6 @@ module ServerHandler = { external handler: (Http.request, Http.response, options) => Promise.t = "serve-handler" } -let execFile = Util.promisify(ChildProcess.execFile) - -let optionalReplace = (mainStr, from, optionalReplacement) => { - switch optionalReplacement { - | Some(replacementText) => mainStr->Js.String2.replace(from, replacementText) - | None => mainStr - } -} - if appName === Some("hyperswitch") { let htmlInFs = Fs.readFileSync("dist/hyperswitch/index.html", {"encoding": "utf8"}) diff --git a/src/utils/AnalyticsNewUtils.res b/src/utils/AnalyticsNewUtils.res index d9bfb018d..39f5cd689 100644 --- a/src/utils/AnalyticsNewUtils.res +++ b/src/utils/AnalyticsNewUtils.res @@ -41,21 +41,6 @@ let calculateHistoricTime = ( } } -let calculateDelta = ( - ~currentValue: float, - ~previousValue: float, - ~statType: AnalyticsTypesUtils.metricsType, -) => { - let delta = switch statType { - | Volume | Latency | Amount => - ((currentValue -. previousValue) /. previousValue *. 100.) - ->Js.Float.toFixedWithPrecision(~digits=2) - | Rate | NegativeRate => (currentValue -. previousValue)->Js.Float.toFixedWithPrecision(~digits=2) - } - - Js.Float.fromString(delta) -} - let makeFilters = (~filters: Js.Json.t, ~cardinalityArr) => { let decodeFilter = filters->getDictFromJsonObject @@ -528,27 +513,3 @@ let apiBodyMaker = ( finalBody->Js.Dict.set("interval", timeObj->Js.Json.object_) finalBody->Js.Json.object_ } - -let domainFromModeValue = modeValue => - if modeValue === "ORDER" { - "orders" - } else { - "txns" - } - -let getModeName = mode => { - if mode === "txns" { - "Transactions" - } else { - "Orders" - } -} - -let filterAddButtonFn = showDropDown => { -
- {React.string("+Add")} -
-} diff --git a/src/utils/AnalyticsTypesUtils.res b/src/utils/AnalyticsTypesUtils.res index 4df30b27b..0104d829d 100644 --- a/src/utils/AnalyticsTypesUtils.res +++ b/src/utils/AnalyticsTypesUtils.res @@ -10,199 +10,3 @@ type timeObj = { apiStartTime: float, apiEndTime: float, } - -let timeObj = { - apiStartTime: 0., - apiEndTime: 0., -} - -// type txnmetrics = -// | TotalVolume -// | SuccessVolume -// | SuccessRate -// | ConflictTxnRate -// | AverageLatency -// | AvgTicketSize -// | TotalAmount - -// type txndimension = -// | PaymentGateway -// | OrderType -// | TxnLatency -// | BusinessRegion -// | Currency -// | TicketSize -// | SsEmi -// | PgRrrorMessage -// | TxnFlowType -// | CardBrand -// | PreviousTxnStatus -// | RunDate -// | Lob -// | AuthType -// | PaymentStatus -// | MerchantId -// | TxnType -// | TokenRepeat -// | EmiType -// | ActualPaymentStatus -// | IsTokenBin -// | EmiBank -// | StatusSyncSource -// | Bank -// | IsTxnConflicted -// | PaymentMethodType -// | PaymentMethodSubtype -// | CardExpMonth -// | CardExpYear -// | UsingStoredCard -// | RunMonth -// | Card_issuerCountry -// | PaymentFlow -// | EmiTenure - -// let txnmetrics = [ -// TotalVolume, -// SuccessVolume, -// SuccessRate, -// ConflictTxnRate, -// AverageLatency, -// AvgTicketSize, -// TotalAmount, -// ] - -// let txndimension = [ -// Bank, -// MerchantId, -// PaymentGateway, -// PaymentMethodType, -// OrderType, -// TxnLatency, -// BusinessRegion, -// Currency, -// TicketSize, -// SsEmi, -// PgRrrorMessage, -// TxnFlowType, -// CardBrand, -// PreviousTxnStatus, -// RunDate, -// Lob, -// AuthType, -// PaymentStatus, -// TxnType, -// TokenRepeat, -// EmiType, -// ActualPaymentStatus, -// IsTokenBin, -// EmiBank, -// StatusSyncSource, -// IsTxnConflicted, -// PaymentMethodSubtype, -// CardExpMonth, -// CardExpYear, -// UsingStoredCard, -// RunMonth, -// Card_issuerCountry, -// PaymentFlow, -// EmiTenure, -// ] - -// type timeFilter = T_ONEDAY | T_SEVENDAY | T_THIRTYDAY | T_SIXTYDAY -// type granularValue = G_ONEMIN | G_FIVEMIN | G_FIFTEENMIN | G_ONEHOUR | G_ONEDAY -// type lastDays = Day(float) | Week(float) | Month(float) | Today | Yesterday -// type sortOrder = ASC | DESC - -// let sortOrderMapper = sortOrder => { -// switch sortOrder { -// | ASC => "ASC" -// | DESC => "DESC" -// } -// } - -// let txnMetricsMapper = (metric: txnmetrics) => { -// switch metric { -// | TotalVolume => "total_volume" -// | SuccessVolume => "success_volume" -// | SuccessRate => "success_rate" -// | ConflictTxnRate => "conflict_txn_rate" -// | AverageLatency => "average_latency" -// | AvgTicketSize => "avg_ticket_size" -// | TotalAmount => "total_amount" -// } -// } - -// let txnMetricsTypeMapper = (metric: txnmetrics) => { -// switch metric { -// | TotalVolume => Volume -// | SuccessVolume => Volume -// | SuccessRate => Rate -// | ConflictTxnRate => Rate -// | AverageLatency => Latency -// | AvgTicketSize => Amount -// | TotalAmount => Amount -// } -// } - -// let txnDimsMapper = (dims: txndimension) => { -// switch dims { -// | PaymentGateway => "payment_gateway" -// | OrderType => "order_type" -// | TxnLatency => "txn_latency" -// | BusinessRegion => "business_region" -// | Currency => "currency" -// | TicketSize => "ticket_size" -// | SsEmi => "is_emi" -// | PgRrrorMessage => "pg_error_message" -// | TxnFlowType => "txn_flow_type" -// | CardBrand => "card_brand" -// | PreviousTxnStatus => "previous_txn_status" -// | RunDate => "run_date" -// | Lob => "lob" -// | AuthType => "auth_type" -// | PaymentStatus => "payment_status" -// | MerchantId => "merchant_id" -// | TxnType => "txn_type" -// | TokenRepeat => "token_repeat" -// | EmiType => "emi_type" -// | ActualPaymentStatus => "actual_payment_status" -// | IsTokenBin => "is_token_bin" -// | EmiBank => "emi_bank" -// | StatusSyncSource => "status_sync_source" -// | Bank => "bank" -// | IsTxnConflicted => "is_txn_conflicted" -// | PaymentMethodType => "payment_method_type" -// | PaymentMethodSubtype => "payment_method_subtype" -// | CardExpMonth => "card_exp_month" -// | CardExpYear => "card_exp_year" -// | UsingStoredCard => "using_stored_card" -// | RunMonth => "run_month" -// | Card_issuerCountry => "card_issuer_country" -// | PaymentFlow => "payment_flow" -// | EmiTenure => "emi_tenure" -// } -// } - -let metricsTypeMapper = metricsType => { - switch metricsType { - | Latency => "Latency" - | Volume => "Volume" - | Rate => "Rate" - | Amount => "Amount" - | NegativeRate => "NegativeRate" - } -} - -let metricsTypeMapperOPP = metricsType => { - switch metricsType { - | "Latency" => Latency - | "Volume" => Volume - | "Rate" => Rate - | "Amount" => Amount - | "NegativeRate" => NegativeRate - | _ => - raise( - Invalid_argument(`invalid values, only Volume, Rate, Amount,NegativeRate is accepted as values`), - ) - } -} diff --git a/src/utils/ArrayUtils.res b/src/utils/ArrayUtils.res index a06f90d92..3c60d55a3 100644 --- a/src/utils/ArrayUtils.res +++ b/src/utils/ArrayUtils.res @@ -6,27 +6,3 @@ let getUniqueStrArray = (arr: array) => { ->Js.Dict.fromArray ->Js.Dict.keys } - -let getUniqueIntArr = (arr: array) => { - arr - ->Js.Array2.map(item => { - (item->Belt.Int.toString, 0) - }) - ->Js.Dict.fromArray - ->Js.Dict.keys - ->Js.Array2.map(item => item->Belt.Int.fromString->Belt.Option.getWithDefault(0)) -} - -let getUniqueFloatArr = (arr: array) => { - arr - ->Js.Array2.map(item => { - (item->Belt.Float.toString, 0) - }) - ->Js.Dict.fromArray - ->Js.Dict.keys - ->Js.Array2.map(item => item->Belt.Float.fromString->Belt.Option.getWithDefault(0.)) -} - -let arrayDiff = (arra, arrb) => { - arra->Js.Array2.copy->Js.Array2.filter(item => !(arrb->Js.Array2.includes(item))) -} diff --git a/src/utils/CurrencyFormatUtils.res b/src/utils/CurrencyFormatUtils.res index 76857cf16..ae8dbb3d1 100644 --- a/src/utils/CurrencyFormatUtils.res +++ b/src/utils/CurrencyFormatUtils.res @@ -2,13 +2,3 @@ type currencyFormat = | IND | USD | DefaultConvert -/* Add more currencies here */ - -let getCountryCurrencyFromString = currency => { - switch currency { - | "IND" => IND - | "USD" => USD - | _ => DefaultConvert - /* Add more currencies here */ - } -} diff --git a/src/utils/DateRangeUtils.res b/src/utils/DateRangeUtils.res index e6104656b..bd06e14dd 100644 --- a/src/utils/DateRangeUtils.res +++ b/src/utils/DateRangeUtils.res @@ -186,12 +186,3 @@ let changeTimeFormat = (~customTimezoneToISOString, ~date, ~time, ~format) => { ) TimeZoneHook.formattedISOString(dateTimeCheck, format) } - -let daysBetween2dates = (~firstDate, ~secondDate) => { - let timeleft = secondDate -. firstDate - let days = - Js.Math.ceil_float( - Js.Math.ceil_float(Js.Math.ceil_float(timeleft /. 1000.) /. 60.) /. 60., - ) /. 24. - days -} diff --git a/src/utils/DictionaryUtils.res b/src/utils/DictionaryUtils.res index fab8e413e..c58239f53 100644 --- a/src/utils/DictionaryUtils.res +++ b/src/utils/DictionaryUtils.res @@ -29,14 +29,6 @@ let appnedDataToKey = (dict, key, value) => { dict->Js.Dict.set(key, updatedValue) } -let appnedArrDataToKey = (dict, key, value) => { - let updatedValue = switch dict->Js.Dict.get(key) { - | Some(val) => Belt.Array.concat(val, value) - | None => value - } - dict->Js.Dict.set(key, updatedValue) -} - let mergeDicts = (arrDict: array>) => { arrDict->Js.Array2.reduce((acc, dict) => { acc->Js.Array2.concat(dict->Js.Dict.entries) @@ -61,19 +53,7 @@ let equalDicts = (dictionary1, dictionary2) => { ->Belt.Option.isNone } -let updateDict = (dict, key, value) => { - let updatedValue = switch dict->Js.Dict.get(key) { - | Some(val) => { - let _ = val->Js.Array2.push(value) - val - } - - | None => [value] - } - dict->Js.Dict.set(key, updatedValue) -} - -let checkEqualJsonDicts = (~checkKeys=[], ~ignoreKeys=[], dictionary1, dictionary2) => { +let checkEqualJsonDicts = (~checkKeys, ~ignoreKeys, dictionary1, dictionary2) => { let dictionary1 = dictionary1->Js.Json.object_->JsonFlattenUtils.flattenObject(false) let dictionary2 = dictionary2->Js.Json.object_->JsonFlattenUtils.flattenObject(false) @@ -125,25 +105,3 @@ let checkEqualJsonDicts = (~checkKeys=[], ~ignoreKeys=[], dictionary1, dictionar let copyOfDict = dict => { dict->Js.Dict.entries->Js.Array2.copy->Js.Dict.fromArray } - -let sortKeysByAlphaOrder = dict => { - dict - ->Js.Dict.entries - ->Js.Array2.sortInPlaceWith((item1, item2) => { - let (key1, _) = item1 - let (key2, _) = item2 - - key1 <= key2 ? -1 : 1 - }) - ->Js.Dict.fromArray -} - -let filterDictFromArray = (dict, array) => { - dict - ->Js.Dict.entries - ->Js.Array2.filter(item => { - let (key, _) = item - !(array->Js.Array2.includes(key)) - }) - ->Js.Dict.fromArray -} diff --git a/src/utils/Formatter.res b/src/utils/Formatter.res deleted file mode 100644 index 32eec613a..000000000 --- a/src/utils/Formatter.res +++ /dev/null @@ -1,46 +0,0 @@ -let numericArrayStringFormat = (. ~value, ~name as _) => { - LogicUtils.getArrayFromJson(value, [])->Js.Array2.joinWith(",")->Js.Json.string -} -let upperCaseFormat = (. ~value, ~name as _) => { - value->LogicUtils.getStringFromJson("")->Js.String2.toUpperCase->Js.Json.string -} -let lowerCaseFormat = (. ~value, ~name as _) => { - value->LogicUtils.getStringFromJson("")->Js.String2.toLowerCase->Js.Json.string -} -let numericArrayStrArrayFormat = (. ~value, ~name as _) => { - let val = switch Js.Json.decodeArray(value) { - | Some(arr) => arr->Js.Array2.reduce((acc, jsonItem) => { - switch jsonItem->Js.Json.decodeNumber { - | Some(num) => { - let _ = acc->Js.Array2.push(num->Belt.Float.toString->Js.Json.string) - } - - | None => () - } - acc - }, []) - - | _ => [] - } - - val->Js.Json.array -} - -let numericStrFormat = (. ~value, ~name as _) => { - value->Js.Json.decodeNumber->Belt.Option.getWithDefault(0.0)->Belt.Float.toString->Js.Json.string -} - -let strArrayFormat = (. ~value, ~name as _) => { - let strVal = value->Js.Json.decodeString->Belt.Option.getWithDefault("") - - let arr = - strVal - ->Js.String2.split(",") - ->Js.Array2.map(Js.String2.trim) - ->Belt.Array.keepMap(LogicUtils.getNonEmptyString) - - arr->Js.Json.stringArray -} -let trimString = (. ~value, ~name as _) => { - value->LogicUtils.getStringFromJson("")->Js.String2.trim->Js.Json.string -} diff --git a/src/utils/HyperSwitchUtils.res b/src/utils/HyperSwitchUtils.res index 366056b01..3aa77c8f6 100644 --- a/src/utils/HyperSwitchUtils.res +++ b/src/utils/HyperSwitchUtils.res @@ -2,23 +2,6 @@ let fetchRequestIdFromAPI = res => { Fetch.Headers.get("x-request-id")(res->Fetch.Response.headers)->Belt.Option.getWithDefault("") } -//to remove -let getErrorStringifiedJson = (json, key) => { - json - ->Js.Json.decodeObject - ->Belt.Option.getWithDefault(Js.Dict.empty()) - ->LogicUtils.getJsonObjectFromDict(key) - ->Js.Json.stringifyAny - ->Belt.Option.getWithDefault("") -} - -let parseErrorJson = json => { - open LogicUtils - let valuesDict = json->getDictFromJsonObject - let errorDict = valuesDict->getObj("error", Js.Dict.empty()) - errorDict->getString("message", "") -} - let getMixpanelRouteName = (pageTitle, url: RescriptReactRouter.url) => { switch (url.path, url.search) { | (list{"payments", ""}, _) From 5310ae8740753e3ff85679e82783d0e4c9cda822 Mon Sep 17 00:00:00 2001 From: Sagar naik Date: Fri, 1 Dec 2023 19:22:02 +0530 Subject: [PATCH 02/27] feat: logs change (#45) --- .../hyperswitch/HyperSwitchApp.res | 4 +++- src/entryPoints/hyperswitch/SidebarValues.res | 20 ++++++++++++++----- .../HomePageOverviewComponent.res | 10 +++++++++- .../HyperSwitch/PaymentLogs/PaymentLogs.res | 6 +++--- 4 files changed, 30 insertions(+), 10 deletions(-) diff --git a/src/entryPoints/hyperswitch/HyperSwitchApp.res b/src/entryPoints/hyperswitch/HyperSwitchApp.res index e6a3c48a5..98f767eae 100644 --- a/src/entryPoints/hyperswitch/HyperSwitchApp.res +++ b/src/entryPoints/hyperswitch/HyperSwitchApp.res @@ -323,7 +323,9 @@ let make = () => { | list{"monitoring"} => comingSoonPage | list{"developer-api-keys"} => | list{"developer-system-metrics"} => - Js.String2.includes("internal_")}> + Js.String2.includes("internal_") && + featureFlagDetails.systemMetrics}> diff --git a/src/entryPoints/hyperswitch/SidebarValues.res b/src/entryPoints/hyperswitch/SidebarValues.res index 95747840f..35f4ecf5b 100644 --- a/src/entryPoints/hyperswitch/SidebarValues.res +++ b/src/entryPoints/hyperswitch/SidebarValues.res @@ -195,7 +195,7 @@ let apiKeys = SubLevelLink({ searchOptions: [("View API Keys", "")], }) -let systemMetrics = SubLevelLink({ +let systemMetric = SubLevelLink({ name: "System Metrics", link: `/developer-system-metrics`, access: ReadWrite, @@ -210,7 +210,7 @@ let webhooks = SubLevelLink({ searchOptions: [("View Webhooks", "")], }) -let developers = (isDevelopersEnabled, ~userRole) => { +let developers = (isDevelopersEnabled, userRole, systemMetrics) => { let isInternalUser = userRole->Js.String2.includes("internal_") isDevelopersEnabled @@ -218,7 +218,9 @@ let developers = (isDevelopersEnabled, ~userRole) => { name: "Developers", icon: "developer", showSection: true, - links: isInternalUser ? [apiKeys, webhooks, systemMetrics] : [apiKeys, webhooks], + links: isInternalUser && systemMetrics + ? [apiKeys, webhooks, systemMetric] + : [apiKeys, webhooks], }) : emptyComponent } @@ -282,7 +284,15 @@ let getHyperSwitchAppSidebars = ( ~userRole, (), ) => { - let {productionAccess, frm, payOut, recon, default, userManagement} = featureFlagDetails + let { + productionAccess, + frm, + payOut, + recon, + default, + userManagement, + systemMetrics, + } = featureFlagDetails let sidebar = [ productionAccess->productionAccessComponent, default->home, @@ -290,7 +300,7 @@ let getHyperSwitchAppSidebars = ( default->analytics, default->connectors, default->workflow, - default->developers(~userRole), + default->developers(userRole, systemMetrics), default->settings, [frm, payOut, recon]->Js.Array2.includes(true)->proFeatures, frm->fraudAndRisk, diff --git a/src/screens/HyperSwitch/Analytics/HomePageOverview/HomePageOverviewComponent.res b/src/screens/HyperSwitch/Analytics/HomePageOverview/HomePageOverviewComponent.res index c341829a4..03f95e8de 100644 --- a/src/screens/HyperSwitch/Analytics/HomePageOverview/HomePageOverviewComponent.res +++ b/src/screens/HyperSwitch/Analytics/HomePageOverview/HomePageOverviewComponent.res @@ -245,12 +245,20 @@ module OverviewInfo = { @react.component let make = () => { + let {systemMetrics} = + HyperswitchAtom.featureFlagAtom + ->Recoil.useRecoilValueFromAtom + ->LogicUtils.safeParse + ->FeatureFlagUtils.featureFlagType +

{"Overview"->React.string}

- + + +
diff --git a/src/screens/HyperSwitch/PaymentLogs/PaymentLogs.res b/src/screens/HyperSwitch/PaymentLogs/PaymentLogs.res index 25f62e929..c7de1280b 100644 --- a/src/screens/HyperSwitch/PaymentLogs/PaymentLogs.res +++ b/src/screens/HyperSwitch/PaymentLogs/PaymentLogs.res @@ -18,10 +18,10 @@ module PrettyPrintJson = { let parseJsonValue = () => { try { - let parsedValue = Window.getParsedJson(jsonToDisplay)->Js.Json.stringifyWithSpace(3) + let parsedValue = jsonToDisplay->Js.Json.parseExn->Js.Json.stringifyWithSpace(3) setParsedJson(_ => parsedValue) } catch { - | _ => setParsedJson(_ => "") + | _ => setParsedJson(_ => jsonToDisplay) } } React.useEffect1(() => { @@ -97,7 +97,7 @@ module ApiDetailsComponent = { let headerStyle = "text-fs-13 font-medium text-grey-700 break-all" let logType = paymentDetailsValue->Js.Dict.get("request_id")->Belt.Option.isSome ? Payment : Sdk let apiName = switch logType { - | Payment => paymentDetailsValue->getString("api_name", "default value") + | Payment => paymentDetailsValue->getString("api_flow", "default value")->camelCaseToTitle | Sdk => paymentDetailsValue->getString("event_name", "default value") }->PaymentUtils.nameToURLMapper(~payment_id=paymentId, ()) let createdTime = paymentDetailsValue->getString("created_at", "00000") From a18471d2fc64c04a6d04357ae9fb313d35caed58 Mon Sep 17 00:00:00 2001 From: Pritish Budhiraja <77892330+PritishBudhiraja@users.noreply.github.com> Date: Fri, 1 Dec 2023 20:08:12 +0530 Subject: [PATCH 03/27] feat: page heading addition (#31) Co-authored-by: Jeeva Ramachandran <120017870+JeevaRamu0104@users.noreply.github.com> --- .gitignore | 2 +- CHANGELOG.md | 7 +- README.md | 2 +- config/FeatureFlag.json | 2 +- .../hyperswitch/HyperSwitchApp.res | 18 ++- src/entryPoints/hyperswitch/SidebarValues.res | 94 +++++++----- src/libraries/Clipboard.res | 2 +- .../Analytics/HSAnalyticsUtils.res | 3 +- .../PaymentsAnalytics/PaymentAnalytics.res | 9 +- .../RefundsAnalytics/RefundsAnalytics.res | 9 +- .../SystemMetrics/SystemMetricsAnalytics.res | 9 +- .../UserAnalytics/UserJourneyAnalytics.res | 9 +- .../Connectors/ConnectorAccountDetails.res | 16 ++- .../HyperSwitch/Connectors/ConnectorList.res | 26 ++-- .../HyperSwitch/Connectors/ConnectorUtils.res | 4 +- .../HyperSwitch/Developer/KeyManagement.res | 6 +- .../PublishableAndHashKeySection.res | 12 +- src/screens/HyperSwitch/Disputes/Disputes.res | 21 ++- .../HyperSwitch/FraudAndRisk/FRMConfigure.res | 3 - .../HyperSwitch/FraudAndRisk/FRMSelect.res | 26 +--- .../HyperSwitch/Helpers/HelperComponents.res | 6 +- src/screens/HyperSwitch/Home/HomeV2.res | 25 ++-- src/screens/HyperSwitch/Order/Orders.res | 4 +- src/screens/HyperSwitch/Order/ShowOrder.res | 6 + src/screens/HyperSwitch/Recon/Recon.res | 16 --- src/screens/HyperSwitch/Refunds/Refund.res | 2 +- ...sinessSettings.res => BusinessDetails.res} | 10 +- ...usinessMapping.res => BusinessProfile.res} | 9 +- .../Settings/HSwitchSettingTypes.res | 17 --- .../HyperSwitch/Settings/HSwitchSettings.res | 135 ++++-------------- src/screens/HyperSwitch/Sidebar/Sidebar.res | 2 +- .../SwitchMerchant/SwitchMerchant.res | 2 +- .../UserManagement/HSwitchShowUserData.res | 9 +- .../UserManagement/HSwitchUserRoleEntry.res | 2 +- src/screens/HyperSwitch/Utils/PageUtils.res | 5 +- 35 files changed, 247 insertions(+), 283 deletions(-) rename src/screens/HyperSwitch/Settings/{BusinessSettings.res => BusinessDetails.res} (94%) rename src/screens/HyperSwitch/Settings/BusinessMapping/{BusinessMapping.res => BusinessProfile.res} (95%) diff --git a/.gitignore b/.gitignore index a078048fb..c1ebc1891 100644 --- a/.gitignore +++ b/.gitignore @@ -19,4 +19,4 @@ yarn.lock #package-lock.json user_data.sh *.pem -.bsb.lock \ No newline at end of file +.bsb.lock diff --git a/CHANGELOG.md b/CHANGELOG.md index 581d2402c..ccce7288b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,8 @@ # Changelog + All notable changes to this project will be documented in this file. See [conventional commits](https://www.conventionalcommits.org/) for commit guidelines. -- - - +--- ## 1.1.0 (2023-11-29) @@ -12,6 +13,6 @@ All notable changes to this project will be documented in this file. See [conven **Full Changelog:** [`v1.0.2...v1.1.0`](https://github.com/juspay/hyperswitch-control-center/compare/v1.0.2...v1.1.0) -- - - +--- -Changelog generated by [cocogitto](https://github.com/cocogitto/cocogitto). \ No newline at end of file +Changelog generated by [cocogitto](https://github.com/cocogitto/cocogitto). diff --git a/README.md b/README.md index e3ca47a49..a01f6bafd 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ The `feedback` feature flag enables the ability for users to provide direct prod The `test_processors` feature flag allows enabling sandbox/test payment processors for testing purposes. When enabled, developers and testers can add test payment processors like Stripe Test or PayPal Test to trial payments flows without touching live transactions or making processor API calls. -#### User Management +#### User Management / Team The `user_management` feature flag enables user administration capabilities. When enabled, administrators can add, edit, and remove user accounts from the organization. They can also manage user roles and permissions that control access to different features and data. diff --git a/config/FeatureFlag.json b/config/FeatureFlag.json index bbe5ac822..64501c151 100644 --- a/config/FeatureFlag.json +++ b/config/FeatureFlag.json @@ -22,4 +22,4 @@ "business_profile": false, "generate_report": false, "forgot_password": false -} \ No newline at end of file +} diff --git a/src/entryPoints/hyperswitch/HyperSwitchApp.res b/src/entryPoints/hyperswitch/HyperSwitchApp.res index 98f767eae..4ed82e6da 100644 --- a/src/entryPoints/hyperswitch/HyperSwitchApp.res +++ b/src/entryPoints/hyperswitch/HyperSwitchApp.res @@ -334,16 +334,26 @@ let make = () => { } + renderList={() => } renderShow={profileId => } /> - | list{"settings"} => - | list{"profile"} => - | list{"settings", "profile"} => | list{"recon"} => | list{"sdk"} => | list{"3ds"} => + | list{"account-settings"} => + + + + | list{"account-settings", "profile"} => + | list{"business-details"} => + + + + | list{"business-profiles"} => + + + | list{"quick-start"} => determineQuickStartPageState() | list{"woocommerce"} => determineWooCommerce() | list{"stripe-plus-paypal"} => determineStripePlusPayPal() diff --git a/src/entryPoints/hyperswitch/SidebarValues.res b/src/entryPoints/hyperswitch/SidebarValues.res index 35f4ecf5b..679aead89 100644 --- a/src/entryPoints/hyperswitch/SidebarValues.res +++ b/src/entryPoints/hyperswitch/SidebarValues.res @@ -73,25 +73,13 @@ let disputes = SubLevelLink({ searchOptions: [("View dispute operations", "")], }) -let userManagement = SubLevelLink({ - name: "Users", - link: `/users`, - access: ReadWrite, - searchOptions: [("View user management", "")], -}) - -let operations = (isOperationsEnabled, isUserManagementEnabled) => { - let linksArray = if isUserManagementEnabled { - [payments, refunds, disputes, userManagement] - } else { - [payments, refunds, disputes] - } +let operations = isOperationsEnabled => { isOperationsEnabled ? Section({ name: "Operations", icon: "hswitch-operations", showSection: true, - links: linksArray, + links: [payments, refunds, disputes], }) : emptyComponent } @@ -171,22 +159,58 @@ let workflow = isWorkflowEnabled => }) : emptyComponent -let settings = isSettingsEnabled => - isSettingsEnabled - ? Link({ - name: "Settings", - icon: "hswitch-settings", - link: `/settings`, - access: ReadWrite, - searchOptions: [ - ("Configure business units ", "?type=units"), - ("Configure business settings", "?type=business"), - ("View profile ", "/profile"), - ("Change password", "/profile"), - ("Manage your personal profile and preferences", "/profile"), - ], - }) - : emptyComponent +let userManagement = SubLevelLink({ + name: "Team", + link: `/users`, + access: ReadWrite, + searchOptions: [("View team management", "")], +}) + +let accountSettings = SubLevelLink({ + name: "Account Settings", + link: `/account-settings`, + access: ReadWrite, + searchOptions: [ + ("View profile", "/profile"), + ("Change password", "/profile"), + ("Manage your personal profile and preferences", "/profile"), + ], +}) + +let businessDetails = SubLevelLink({ + name: "Business Details", + link: `/business-details`, + access: ReadWrite, + searchOptions: [("Configure business details", "")], +}) + +let businessProfiles = SubLevelLink({ + name: "Business Profiles", + link: `/business-profiles`, + access: ReadWrite, + searchOptions: [("Configure business profiles", "")], +}) + +let settings = (~isSampleDataEnabled, ~isUserManagementEnabled, ~isBusinessProfileEnabled) => { + let settingsLinkArray = [businessDetails] + + if isBusinessProfileEnabled { + settingsLinkArray->Js.Array2.push(businessProfiles)->ignore + } + if isSampleDataEnabled { + settingsLinkArray->Js.Array2.push(accountSettings)->ignore + } + if isUserManagementEnabled { + settingsLinkArray->Js.Array2.push(userManagement)->ignore + } + + Section({ + name: "Settings", + icon: "hswitch-settings", + showSection: true, + links: settingsLinkArray, + }) +} let apiKeys = SubLevelLink({ name: "API Keys", @@ -291,17 +315,23 @@ let getHyperSwitchAppSidebars = ( recon, default, userManagement, + sampleData, + businessProfile, systemMetrics, } = featureFlagDetails let sidebar = [ productionAccess->productionAccessComponent, default->home, - default->operations(userManagement), + default->operations, default->analytics, default->connectors, default->workflow, default->developers(userRole, systemMetrics), - default->settings, + settings( + ~isUserManagementEnabled=userManagement, + ~isBusinessProfileEnabled=businessProfile, + ~isSampleDataEnabled=sampleData, + ), [frm, payOut, recon]->Js.Array2.includes(true)->proFeatures, frm->fraudAndRisk, payOut->payoutConnectors, diff --git a/src/libraries/Clipboard.res b/src/libraries/Clipboard.res index f822823da..e80262fdf 100644 --- a/src/libraries/Clipboard.res +++ b/src/libraries/Clipboard.res @@ -64,7 +64,7 @@ module Copy = { }}>
{ module NoData = { @react.component - let make = () => { + let make = (~title, ~subTitle) => {
+
@@ -92,7 +92,7 @@ module NewProcessorCards = {
setShowModal(_ => true)} className="text-blue-900 cursor-pointer underline underline-offset-4 font-medium"> - {"Can't find the connector of you're choice?"->React.string} + {"Can't find the processor of you're choice?"->React.string}
@@ -124,11 +124,11 @@ module NewProcessorCards = {
{if showIcons { <> - {connectorsAvailableForIntegration->iconsConnectors("Connect a new connector", true)} + {connectorsAvailableForIntegration->iconsConnectors("Connect a new processor", true)} { {featureFlagDetails.testProcessors ->ConnectorUtils.dummyConnectorList - ->iconsConnectors("Connect a test connector", false)} + ->iconsConnectors("Connect a test processor", false)} } } else { @@ -136,10 +136,10 @@ module NewProcessorCards = { {featureFlagDetails.testProcessors ->ConnectorUtils.dummyConnectorList - ->descriptedConnectors("Connect a test connector", false)} + ->descriptedConnectors("Connect a test processor", false)} {connectorsAvailableForIntegration->descriptedConnectors( - "Connect a new connector", + "Connect a new processor", true, )} @@ -163,11 +163,6 @@ let make = (~isPayoutFlow=false) => { open ConnectorUtils let {showFeedbackModal, setShowFeedbackModal} = React.useContext(GlobalProvider.defaultContext) let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) - let featureFlagDetails = - HyperswitchAtom.featureFlagAtom - ->Recoil.useRecoilValueFromAtom - ->LogicUtils.safeParse - ->FeatureFlagUtils.featureFlagType let (configuredConnectors, setConfiguredConnectors) = React.useState(_ => []) let (previouslyConnectedData, setPreviouslyConnectedData) = React.useState(_ => []) let (filteredConnectorData, setFilteredConnectorData) = React.useState(_ => []) @@ -224,6 +219,12 @@ let make = (~isPayoutFlow=false) => { let entityPrefix = isPayoutFlow ? "payout" : ""
+ { />
- - - diff --git a/src/screens/HyperSwitch/Connectors/ConnectorUtils.res b/src/screens/HyperSwitch/Connectors/ConnectorUtils.res index b11a400b2..c8541627b 100644 --- a/src/screens/HyperSwitch/Connectors/ConnectorUtils.res +++ b/src/screens/HyperSwitch/Connectors/ConnectorUtils.res @@ -434,11 +434,11 @@ let phonypayInfo = { } let stripeTestInfo = { - description: "A stripe test connector to test payments and refunds without real world consequences.", + description: "A stripe test processor to test payments and refunds without real world consequences.", } let paypalTestInfo = { - description: "A paypal test connector to simulate payment flows and experience hyperswitch checkout.", + description: "A paypal test processor to simulate payment flows and experience hyperswitch checkout.", } let wiseInfo = { diff --git a/src/screens/HyperSwitch/Developer/KeyManagement.res b/src/screens/HyperSwitch/Developer/KeyManagement.res index d3c3f61a2..667f31fc1 100644 --- a/src/screens/HyperSwitch/Developer/KeyManagement.res +++ b/src/screens/HyperSwitch/Developer/KeyManagement.res @@ -421,8 +421,10 @@ module ApiKeysTable = { module KeysManagement = { @react.component let make = () => { -
- +
+
diff --git a/src/screens/HyperSwitch/Developer/PublishableAndHashKeySection.res b/src/screens/HyperSwitch/Developer/PublishableAndHashKeySection.res index 031d8861e..c1a1080ac 100644 --- a/src/screens/HyperSwitch/Developer/PublishableAndHashKeySection.res +++ b/src/screens/HyperSwitch/Developer/PublishableAndHashKeySection.res @@ -3,7 +3,9 @@ let make = () => { let hyperswitchMixPanel = HSMixPanel.useSendEvent() let url = RescriptReactRouter.useUrl() let fetchDetails = APIUtils.useGetMethod() - let (merchantInfo, setMerchantInfo) = React.useState(() => Js.Dict.empty()) + let (merchantInfo, setMerchantInfo) = React.useState(() => + Js.Json.null->HSwitchMerchantAccountUtils.getMerchantDetails + ) let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let getMerchantDetails = async () => { @@ -12,9 +14,7 @@ let make = () => { let accountUrl = APIUtils.getURL(~entityName=MERCHANT_ACCOUNT, ~methodType=Get, ()) let merchantDetails = await fetchDetails(accountUrl) let merchantInfo = merchantDetails->HSwitchMerchantAccountUtils.getMerchantDetails - - setMerchantInfo(_ => merchantInfo->HSwitchMerchantAccountUtils.parseMerchantJson) - + setMerchantInfo(_ => merchantInfo) setScreenState(_ => PageLoaderWrapper.Success) } catch { | Js.Exn.Error(e) => @@ -29,7 +29,7 @@ let make = () => { None }) - let paymentResponsHashKey = merchantInfo->LogicUtils.getString("payment_response_hash_key", "") + let paymentResponsHashKey = merchantInfo.payment_response_hash_key->Belt.Option.getWithDefault("")
@@ -66,7 +66,7 @@ let make = () => {
LogicUtils.getString("publishable_key", "")} + displayValue={merchantInfo.publishable_key} customTextCss="break-all text-sm font-semibold text-jp-gray-800 text-opacity-75" customParentClass="flex items-center gap-5" customOnCopyClick={() => { diff --git a/src/screens/HyperSwitch/Disputes/Disputes.res b/src/screens/HyperSwitch/Disputes/Disputes.res index c7af67253..60397188f 100644 --- a/src/screens/HyperSwitch/Disputes/Disputes.res +++ b/src/screens/HyperSwitch/Disputes/Disputes.res @@ -57,9 +57,22 @@ let make = () => { }, ~wait=200) let customUI = - + <> +
+ +

+ {"Missing disputes? Disputes might not be supported for your payment processor or might not yet have been integrated with hyperswitch. Please check the"->React.string} + + {" feature matrix "->React.string} + + {"for your processor."->React.string} +

+
+ + let {generateReport} = HyperswitchAtom.featureFlagAtom @@ -68,7 +81,7 @@ let make = () => { ->FeatureFlagUtils.featureFlagType
- +
diff --git a/src/screens/HyperSwitch/FraudAndRisk/FRMConfigure.res b/src/screens/HyperSwitch/FraudAndRisk/FRMConfigure.res index 39467a555..7919ffbeb 100644 --- a/src/screens/HyperSwitch/FraudAndRisk/FRMConfigure.res +++ b/src/screens/HyperSwitch/FraudAndRisk/FRMConfigure.res @@ -108,9 +108,6 @@ let make = () => { - - -
{switch currentStep { | IntegFields => diff --git a/src/screens/HyperSwitch/FraudAndRisk/FRMSelect.res b/src/screens/HyperSwitch/FraudAndRisk/FRMSelect.res index f89ab452d..82c783905 100644 --- a/src/screens/HyperSwitch/FraudAndRisk/FRMSelect.res +++ b/src/screens/HyperSwitch/FraudAndRisk/FRMSelect.res @@ -94,28 +94,10 @@ module NewProcessorCards = { } } -module FRMProPackageInfo = { - @react.component - let make = () => { -
- -
- {"This feature is a part of the \"Pro\" plan. You can explore the feature on sandbox, however you will have to subscribe to \"Pro\" plan for using on production"->React.string} -
-
- } -} - @react.component let make = () => { open FRMInfo open UIUtils - let featureFlagDetails = - HyperswitchAtom.featureFlagAtom - ->Recoil.useRecoilValueFromAtom - ->LogicUtils.safeParse - ->FeatureFlagUtils.featureFlagType let url = RescriptReactRouter.useUrl() let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let fetchDetails = APIUtils.useGetMethod() @@ -135,6 +117,7 @@ let make = () => { onClickElement={React.null} onClickUrl="connectors" moduleName="Fraud & Risk Management" + moduleSubtitle="Connect and configure processors to screen transactions and mitigate fraud" mixPanelEventName={`${url.path->LogicUtils.getListHead}_take_me_to_connectors`} /> @@ -190,9 +173,10 @@ let make = () => {
- - - + diff --git a/src/screens/HyperSwitch/Helpers/HelperComponents.res b/src/screens/HyperSwitch/Helpers/HelperComponents.res index 7f93b042b..5b2e34ba6 100644 --- a/src/screens/HyperSwitch/Helpers/HelperComponents.res +++ b/src/screens/HyperSwitch/Helpers/HelperComponents.res @@ -47,6 +47,7 @@ module BluredTableComponent = { ~paymentModal=false, ~setPaymentModal=_ => (), ~moduleName, + ~moduleSubtitle=?, ~mixPanelEventName=?, ~showRedirectCTA=true, ~headerRightButton=React.null, @@ -63,9 +64,12 @@ module BluredTableComponent = { let dummyTableValue = Belt.Array.make(5, dummyTableValueDict) + let subTitle = + moduleSubtitle->Belt.Option.isSome ? moduleSubtitle->Belt.Option.getWithDefault("") : "" +
- +
{headerRightButton}
diff --git a/src/screens/HyperSwitch/Home/HomeV2.res b/src/screens/HyperSwitch/Home/HomeV2.res index a12a7d4cc..aeb99cfba 100644 --- a/src/screens/HyperSwitch/Home/HomeV2.res +++ b/src/screens/HyperSwitch/Home/HomeV2.res @@ -338,6 +338,7 @@ module Resources = { @react.component let make = () => { + let greeting = HomeUtils.getGreeting() let isMobileView = MatchMedia.useMobileChecker() let {isProdIntentCompleted} = React.useContext(GlobalProvider.defaultContext) let enumDetails = Recoil.useRecoilValueFromAtom(HyperswitchAtom.enumVariantAtom) @@ -349,13 +350,19 @@ let make = () => { isProdIntentCompleted, ] -
- {if checkingConditions->Js.Array2.includes(false) { - - } else { - - }} - - -
+ <> + +
+ {if checkingConditions->Js.Array2.includes(false) { + + } else { + + }} + + +
+ } diff --git a/src/screens/HyperSwitch/Order/Orders.res b/src/screens/HyperSwitch/Order/Orders.res index 403c79bd5..5b72e0235 100644 --- a/src/screens/HyperSwitch/Order/Orders.res +++ b/src/screens/HyperSwitch/Order/Orders.res @@ -87,7 +87,9 @@ let make = (~previewOnly=false) => {
- +
diff --git a/src/screens/HyperSwitch/Order/ShowOrder.res b/src/screens/HyperSwitch/Order/ShowOrder.res index 6f62b4a29..6740bca8d 100644 --- a/src/screens/HyperSwitch/Order/ShowOrder.res +++ b/src/screens/HyperSwitch/Order/ShowOrder.res @@ -381,6 +381,12 @@ module Attempts = { }
+
+ + + {`You can validate the information shown here by cross checking the hyperswitch payment attempt identifier (Attempt ID) in your payment processor portal.`->React.string} + +

{"Payment Attempts"->React.string}

{ -
- -
- {"This feature is a part of the \"Pro\" plan. You have to subscribe to \"Pro\" plan to use this feature"->React.string} -
-
- } -} - @react.component let make = () => { open APIUtils @@ -79,9 +66,6 @@ let make = () => {
- - -
{
- +
diff --git a/src/screens/HyperSwitch/Settings/BusinessSettings.res b/src/screens/HyperSwitch/Settings/BusinessDetails.res similarity index 94% rename from src/screens/HyperSwitch/Settings/BusinessSettings.res rename to src/screens/HyperSwitch/Settings/BusinessDetails.res index 108245660..0d1daf80e 100644 --- a/src/screens/HyperSwitch/Settings/BusinessSettings.res +++ b/src/screens/HyperSwitch/Settings/BusinessDetails.res @@ -121,12 +121,10 @@ let make = () => {
-
- {React.string("Business Settings")} -

- {"Manage contact details about your business. You may also add different business entities in order to connect with right processors."->React.string} -

-
+
Js.Json.object_} diff --git a/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessMapping.res b/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessProfile.res similarity index 95% rename from src/screens/HyperSwitch/Settings/BusinessMapping/BusinessMapping.res rename to src/screens/HyperSwitch/Settings/BusinessMapping/BusinessProfile.res index 86def3d90..a3543e558 100644 --- a/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessMapping.res +++ b/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessProfile.res @@ -156,13 +156,18 @@ let make = ( updateMerchantDetails(values)->ignore Js.Nullable.null } - let tableHeaderText = isFromWebhooks ? "Webhooks" : "Business profiles" + let tableHeaderText = isFromWebhooks ? "Webhooks" : "Business Profiles"
-
{tableHeaderText->React.string}
+ { - switch pageType { - | "business" => Business - | "units" => Units - | "mandate" => Mandate - | _ => LandingPage - } -} -let headingTypeMapper = (pageTypeValue: pageType) => { - switch pageTypeValue { - | Business => "Business Settings" - | Units => "Business Units" - | Mandate => "Mandate Settings" - | _ => "" - } -} type profileEntity = { merchant_id: string, diff --git a/src/screens/HyperSwitch/Settings/HSwitchSettings.res b/src/screens/HyperSwitch/Settings/HSwitchSettings.res index 8788dd6f8..70dff45bf 100644 --- a/src/screens/HyperSwitch/Settings/HSwitchSettings.res +++ b/src/screens/HyperSwitch/Settings/HSwitchSettings.res @@ -1,20 +1,5 @@ open HSwitchSettingTypes -let businessSettings = { - heading: "Business Settings", - subHeading: "Add and manage primary or secondary contact and general details about your business.", - redirect: "business", - cardName: #BUSINESS_SETTINGS, -} - -let businessUnits = { - heading: "Business Profile Configuration", - subHeading: "Add and manage labels to represent different businesses across countries.", - redirect: "units", - buttonText: "Add Configuration", - cardName: #BUSINESS_UNITS, -} - let deleteSampleData = { heading: "Delete Sample Data", subHeading: "Delete all the generated sample data.", @@ -23,16 +8,6 @@ let deleteSampleData = { cardName: #DELETE_SAMPLE_DATA, } -let moduleLevelSettings = [ - { - heading: "Mandate Settings", - subHeading: "Add and manage mandate related details for all connector configurations.", - redirect: "mandate", - isComingSoon: true, - cardName: #MANDATE_SETTINGS, - }, -] - module TileComponent = { @react.component let make = ( @@ -159,98 +134,38 @@ module PersonalSettings = { ->LogicUtils.safeParse ->FeatureFlagUtils.featureFlagType let personalSettings = if featureFlagDetails.sampleData { - [businessSettings, businessUnits, deleteSampleData] - } else if featureFlagDetails.businessProfile { - [businessSettings, businessUnits] + [deleteSampleData] } else { - [businessSettings] + [] } -
-
- {React.string("Personal Settings ")} -

- {"Set your defaults on module level, profile level, and platform level. This module is editable only by admins and view only for other members."->React.string} -

-
-
- {personalSettings - ->Array.mapWithIndex((sections, index) => - Belt.Option.getWithDefault("")} - isComingSoon={sections.isComingSoon->Belt.Option.getWithDefault(false)} - buttonText={sections.buttonText->Belt.Option.getWithDefault("Add Details")} - redirectUrl={sections.redirectUrl} - isApiCall={sections.isApiCall->Belt.Option.getWithDefault(false)} - cardName={sections.cardName} - /> - ) - ->React.array} -
-
- } -} -module ModuleSettings = { - @react.component - let make = () => { -
-
- {React.string("Module Level Settings")} -

- {"Set your defaults on module level, profile level, and platform level. This module is editable only by admins and view only for other members."->React.string} -

-
-
- {moduleLevelSettings - ->Array.mapWithIndex((sections, index) => - Belt.Option.getWithDefault("")} - isComingSoon={sections.isComingSoon->Belt.Option.getWithDefault(false)} - redirectUrl={sections.redirectUrl} - cardName={sections.cardName} - /> - ) - ->React.array} -
+
+ {personalSettings + ->Array.mapWithIndex((sections, index) => + Belt.Option.getWithDefault("")} + isComingSoon={sections.isComingSoon->Belt.Option.getWithDefault(false)} + buttonText={sections.buttonText->Belt.Option.getWithDefault("Add Details")} + redirectUrl={sections.redirectUrl} + isApiCall={sections.isApiCall->Belt.Option.getWithDefault(false)} + cardName={sections.cardName} + /> + ) + ->React.array}
} } @react.component let make = () => { - let (currentPage, setCurrentPage) = React.useState(() => LandingPage) - - let url = RescriptReactRouter.useUrl() - React.useEffect1(() => { - let searchParams = url.search - let filtersFromUrl = - LogicUtils.getDictFromUrlSearchParams(searchParams) - ->Js.Dict.get("type") - ->Belt.Option.getWithDefault("") - setCurrentPage(_ => filtersFromUrl->typeMapper) - None - }, [url.search]) - -
- {switch currentPage { - | Business => - headingTypeMapper} baseLink={"/settings"} title="Settings"> - - - | Units => - headingTypeMapper} baseLink={"/settings"} title="Settings"> - - - | LandingPage => - | _ => React.null - }} -
+ <> + + + } diff --git a/src/screens/HyperSwitch/Sidebar/Sidebar.res b/src/screens/HyperSwitch/Sidebar/Sidebar.res index e12131857..14f392d0c 100644 --- a/src/screens/HyperSwitch/Sidebar/Sidebar.res +++ b/src/screens/HyperSwitch/Sidebar/Sidebar.res @@ -672,7 +672,7 @@ let make = ( { RescriptReactRouter.replace( - `${HSwitchGlobalVars.hyperSwitchFEPrefix}/settings/profile`, + `${HSwitchGlobalVars.hyperSwitchFEPrefix}/account-settings/profile`, ) }} text="Profile" diff --git a/src/screens/HyperSwitch/SwitchMerchant/SwitchMerchant.res b/src/screens/HyperSwitch/SwitchMerchant/SwitchMerchant.res index be38e39aa..1e5d74966 100644 --- a/src/screens/HyperSwitch/SwitchMerchant/SwitchMerchant.res +++ b/src/screens/HyperSwitch/SwitchMerchant/SwitchMerchant.res @@ -184,7 +184,7 @@ module ExternalUser = { `${activeClasses} text-blue-900 flex gap-2 font-medium w-56` }> - {"Add a new Merchant"->React.string} + {"Add a new merchant"->React.string} }
diff --git a/src/screens/HyperSwitch/UserManagement/HSwitchShowUserData.res b/src/screens/HyperSwitch/UserManagement/HSwitchShowUserData.res index c4dfd9ce9..521a96fb6 100644 --- a/src/screens/HyperSwitch/UserManagement/HSwitchShowUserData.res +++ b/src/screens/HyperSwitch/UserManagement/HSwitchShowUserData.res @@ -73,10 +73,17 @@ let make = () => { let getRoleForUser = async () => { try { + // TODO - Temp fix - Backend fix awaited let url = getURL( ~entityName=USER_MANAGEMENT, ~userRoleTypes=ROLE_ID, - ~id=Some(currentSelectedUser.role_id), + ~id={ + Some( + currentSelectedUser.role_id === "org_admin" + ? "merchant_admin" + : currentSelectedUser.role_id, + ) + }, ~methodType=Get, (), ) diff --git a/src/screens/HyperSwitch/UserManagement/HSwitchUserRoleEntry.res b/src/screens/HyperSwitch/UserManagement/HSwitchUserRoleEntry.res index 9cb817dbb..3a2a13480 100644 --- a/src/screens/HyperSwitch/UserManagement/HSwitchUserRoleEntry.res +++ b/src/screens/HyperSwitch/UserManagement/HSwitchUserRoleEntry.res @@ -118,7 +118,7 @@ let make = () => {
{<>
diff --git a/src/screens/HyperSwitch/Utils/PageUtils.res b/src/screens/HyperSwitch/Utils/PageUtils.res index 48423eca2..8aa725761 100644 --- a/src/screens/HyperSwitch/Utils/PageUtils.res +++ b/src/screens/HyperSwitch/Utils/PageUtils.res @@ -14,7 +14,6 @@ module PageHeading = {
{switch leftIcon { | Some(icon) => - | None => React.null }}
@@ -28,7 +27,9 @@ module PageHeading = {
{switch subTitle { | Some(text) => -
{text->React.string}
+ Js.String2.length > 0}> +
{text->React.string}
+
| None => React.null }}
From 769987ddff414945f77780c7a2c7702c90a0d642 Mon Sep 17 00:00:00 2001 From: Pritish Budhiraja <77892330+PritishBudhiraja@users.noreply.github.com> Date: Mon, 4 Dec 2023 12:02:19 +0530 Subject: [PATCH 04/27] chore: dead code removal (#47) --- .../PublishableAndHashKeySection.res | 1 + .../HSwitchSandboxOnboarding/CodeSnippets.res | 14 - .../OnboardingChecklist.res | 129 -------- .../UserOnboardingUIUtils.res | 105 ------- .../UserOnboardingUtils.res | 17 -- .../BusinessMapping/BusinessMappingUtils.res | 9 - .../BusinessMapping/BusinessProfile.res | 55 +--- .../Settings/HSwitchMerchantAccountUtils.res | 276 +----------------- .../Settings/HSwitchProfileSettings.res | 4 +- 9 files changed, 10 insertions(+), 600 deletions(-) delete mode 100644 src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/OnboardingChecklist.res diff --git a/src/screens/HyperSwitch/Developer/PublishableAndHashKeySection.res b/src/screens/HyperSwitch/Developer/PublishableAndHashKeySection.res index c1a1080ac..4935c4cdf 100644 --- a/src/screens/HyperSwitch/Developer/PublishableAndHashKeySection.res +++ b/src/screens/HyperSwitch/Developer/PublishableAndHashKeySection.res @@ -47,6 +47,7 @@ let make = () => {
{ app.listen(4242, () => console.log("Node server listening on port 4242!"));` -let reactInstallationDisplayCheckout: string = `npm install @juspay-tech/hyper-js -npm install @juspay-tech/react-hyper-js` - -let reactImportDisplayCheckout: string = `import React, { useState, useEffect } from "react"; -import { loadHyper } from "@juspay-tech/hyper-js"; -import { HyperElements } from "@juspay-tech/react-hyper-js";` - -let nodeDisplayCheckout: string = `const hyperPromise = loadHyper("YOUR_PUBLISHABLE_KEY"); -const [clientSecret, setClientSecret] = useState(""); -// store a reference to hyper -const hyper = useHyper();` - let reactDisplayPaymentConfirmation: string = `const handleSubmit = async (e) => { e.preventDefault(); if (!hyper || !widgets) { diff --git a/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/OnboardingChecklist.res b/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/OnboardingChecklist.res deleted file mode 100644 index b635ef8e7..000000000 --- a/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/OnboardingChecklist.res +++ /dev/null @@ -1,129 +0,0 @@ -@react.component -let make = () => { - open APIUtils - let url = RescriptReactRouter.useUrl() - let updateDetails = useUpdateMethod() - let { - integrationDetails, - setIntegrationDetails, - setDashboardPageState, - setShowProdIntentForm, - } = React.useContext(GlobalProvider.defaultContext) - - let stepperValue = HSwitchVerticalStepper.getStepperValue(~integrationDetails) - - let typeOfIntegrationDocs = - LogicUtils.getDictFromUrlSearchParams(url.search) - ->Js.Dict.get("type") - ->Belt.Option.getWithDefault("") - - let markAsDone = currentRoute => - async () => { - try { - let url = getURL(~entityName=INTEGRATION_DETAILS, ~methodType=Post, ()) - let body = HSwitchUtils.constructOnboardingBody( - ~dashboardPageState=#INTEGRATION_DOC, - ~integrationDetails, - ~is_done=true, - ~metadata=[ - ("is_skip", false->Js.Json.boolean), - ( - "integrationType", - currentRoute->UserOnboardingUtils.variantToTextMapperForBuildHS->Js.Json.string, - ), - ] - ->Js.Dict.fromArray - ->Js.Json.object_, - (), - ) - let _res = await updateDetails(url, body, Post) - setIntegrationDetails(_ => body->ProviderHelper.getIntegrationDetails) - RescriptReactRouter.replace("/home") - setDashboardPageState(_ => #HOME) - setShowProdIntentForm(_ => true) - } catch { - | _ => () - } - } - - let handleBackButton = () => { - RescriptReactRouter.push("/home") - setDashboardPageState(_ => #HOME) - } - let isFromOnboardingChecklist = integrationDetails.integration_checklist.is_done - -
-
-
-
- {
-
- {switch (url.path, typeOfIntegrationDocs) { - | (list{"onboarding-checklist"}, "migrate-from-stripe") => - - | (list{"onboarding-checklist"}, "integrate-from-scratch") => - - | (list{"onboarding-checklist"}, "sample-projects") => - - | (list{"onboarding-checklist"}, "woocommerce-plugin") => - - | _ => -
- -
- -
- }} -
-
} -
-
-} diff --git a/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/UserOnboardingUIUtils.res b/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/UserOnboardingUIUtils.res index 95ae3309c..8724636b1 100644 --- a/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/UserOnboardingUIUtils.res +++ b/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/UserOnboardingUIUtils.res @@ -1074,108 +1074,3 @@ let getTabsForIntegration = ( | _ => [] } } - -module GitHubLanguageFilters = { - @react.component - let make = ( - ~frontEndLang: languages, - ~setFrontEndLang, - ~backEndLang: languages, - ~setBackEndLang, - ~isFromOnboardingChecklist=false, - ) => { - let hyperswitchMixPanel = HSMixPanel.useSendEvent() - let url = RescriptReactRouter.useUrl() - let urlHead = url.path->LogicUtils.getListHead - - let backendLangInput: ReactFinalForm.fieldRenderPropsInput = { - name: "Backend", - onBlur: _ev => (), - onChange: ev => { - let val = ev->formEventToStr->getLangauge - setBackEndLang(_ => val) - hyperswitchMixPanel(~eventName=Some(`${urlHead}_${(val :> string)}`), ()) - }, - onFocus: _ev => (), - value: (backEndLang :> string)->Js.Json.string, - checked: true, - } - let frontendLangInput: ReactFinalForm.fieldRenderPropsInput = { - name: "Frontend", - onBlur: _ev => (), - onChange: ev => { - let val = ev->formEventToStr->getLangauge - setFrontEndLang(_ => val) - hyperswitchMixPanel(~eventName=Some(`${urlHead}_${(val :> string)}`), ()) - }, - onFocus: _ev => (), - value: (frontEndLang :> string)->Js.Json.string, - checked: true, - } - - let frontendDropdownText = { - frontEndLang === #ChooseLanguage ? "Choose Frontend" : (frontEndLang :> string) - } - let backendDropdownText = { - backEndLang === #ChooseLanguage ? "Choose Backend" : (backEndLang :> string) - } - - Js.Json.object_}> -
- Js.Array2.map((lang): SelectBox.dropdownOption => { - {value: (lang :> string), label: (lang :> string)} - })} - customButtonStyle="!rounded-md" - hideMultiSelectButtons=true - buttonClickFn={e => { - hyperswitchMixPanel(~eventName=Some(`${urlHead}_${e->Js.String2.replace(" ", "")}`), ()) - }} - autoApply=false - customStyle="!rounded-md" - baseComponent={
- - } -} diff --git a/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/UserOnboardingUtils.res b/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/UserOnboardingUtils.res index d28ab4aa8..261db46a0 100644 --- a/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/UserOnboardingUtils.res +++ b/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/UserOnboardingUtils.res @@ -195,15 +195,6 @@ let getCreateAPayment = (lang: languages): string => { } } -let getDisplayPaymentConfirmation = (lang: languages): string => { - open CodeSnippets - switch lang { - | #ReactJs => reactDisplayPaymentConfirmation - | #Node => nodeDisplayPaymentConfirmation - | _ => "" - } -} - let getMainPageText = currentRoute => switch currentRoute { | MigrateFromStripe => "Migrate from Stripe" @@ -220,14 +211,6 @@ let getLanguages = currentRoute => | _ => ([], []) } -let getHeadingTextForRequestOnlyPlat = platform => - switch platform { - | #BigCommerce => "Big Commerce" - | #Android => "Android" - | #IOS => "IOS" - | _ => "" - } - // To be refactored let getFilteredList = ( frontEndLang: languages, diff --git a/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessMappingUtils.res b/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessMappingUtils.res index 424944dfe..6a21fd6cd 100644 --- a/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessMappingUtils.res +++ b/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessMappingUtils.res @@ -1,6 +1,4 @@ open HSwitchSettingTypes -open CountryUtils -let errorClass = "text-sm leading-4 font-medium text-start ml-1 mt-2" type modalFields = ProfileName @@ -10,13 +8,6 @@ let getStringFromVariant = key => { } } -let defaultCountry = "UnitedStatesOfAmerica" -let defaultLabel = "default" - -let getFormatedCountryName = countryCode => { - countryCode->getCountryCodeFromString->getCountryFromCountryCode->splitCountryNameWithSpace -} - let labelField = FormRenderer.makeFieldInfo( ~label="Profile Name", ~name="profile_name", diff --git a/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessProfile.res b/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessProfile.res index a3543e558..384f1d88f 100644 --- a/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessProfile.res +++ b/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessProfile.res @@ -62,51 +62,6 @@ module AddEntryBtn = { } } -module BusinessUnitText = { - @react.component - let make = () => { -
-
- {"How this works?"->React.string} -
-
    -

    - {"If you have multiple business units, add them here by providing the country and a label for each unit. We have created a default business unit during your sign up"->React.string} -

    -

    - {"For Eg: If you have clothing and shoe business units in both US & GB and the 'US clothing' unit has to be your default business unit, then create the following units:"->React.string} -

    -
      -
    • {"Country = US, label = default"->React.string}
    • -
    • {"Country = US, label = shoe"->React.string}
    • -
    • {"Country = GB, label = clothing"->React.string}
    • -
    • {"Country = GB, label = shoe"->React.string}
    • -
    -

    {"Note: "->React.string}

    -
      -
    • - {"When creating a connector, you need to attach it to a business unit."->React.string} -
    • -
    • - - {"If you have more than one business unit, you need to send the business_country & business_label fields during"->React.string} - - - Window._open( - "https://api-reference.hyperswitch.io/docs/hyperswitch-api-reference/60bae82472db8-payments-create", - )} - target="_blank"> - {"payments/create API request"->React.string} - -
    • -
    -
-
- } -} - @react.component let make = ( ~isFromSettings=true, @@ -182,9 +137,13 @@ let make = ( currrentFetchCount={businessProfileValues->Js.Array2.length} /> // -
- -
+ +
+ +
+
diff --git a/src/screens/HyperSwitch/Settings/HSwitchMerchantAccountUtils.res b/src/screens/HyperSwitch/Settings/HSwitchMerchantAccountUtils.res index e88c87089..ac05ee285 100644 --- a/src/screens/HyperSwitch/Settings/HSwitchMerchantAccountUtils.res +++ b/src/screens/HyperSwitch/Settings/HSwitchMerchantAccountUtils.res @@ -1,196 +1,4 @@ open HSwitchSettingTypes -let merchantName = FormRenderer.makeFieldInfo( - ~label="Name", - ~name="merchant_name", - ~placeholder="Enter your name", - ~customInput=InputFields.textInput(), - ~isRequired=true, - (), -) - -let webhookVersion = FormRenderer.makeFieldInfo( - ~label="Webhook Version", - ~name="webhook_version", - ~placeholder="Enter webhooks version", - ~customInput=InputFields.textInput(~autoComplete="off", ()), - ~isRequired=false, - (), -) - -let webhookUsername = FormRenderer.makeFieldInfo( - ~label="Webhook Username", - ~name="webhook_username", - ~placeholder="Enter webhooks username", - ~customInput=InputFields.textInput(~autoComplete="off", ()), - ~isRequired=false, - (), -) - -let createdPaymentToggle = FormRenderer.makeFieldInfo( - ~label="", - ~name="payment_created_enabled", - ~customInput=InputFields.boolInput(~isDisabled=false), - ~isRequired=false, - (), -) - -let succeededPaymentToggle = FormRenderer.makeFieldInfo( - ~label="", - ~name="payment_succeeded_enabled", - ~customInput=InputFields.boolInput(~isDisabled=true), - ~isRequired=false, - (), -) - -let failedPaymentToggle = FormRenderer.makeFieldInfo( - ~label="", - ~name="payment_failed_enabled", - ~customInput=InputFields.boolInput(~isDisabled=true), - ~isRequired=false, - (), -) - -let webhookPassword = FormRenderer.makeFieldInfo( - ~label="Webhook Password", - ~name="webhook_password", - ~placeholder="Enter webhook password", - ~customInput=InputFields.textInput( - ~type_="password", - ~autoComplete="off", - ~leftIcon={ - - }, - (), - ), - ~isRequired=false, - (), -) - -let primaryContactPerson = FormRenderer.makeFieldInfo( - ~label="Primary Contact Person", - ~name="primary_contact_person", - ~placeholder="Primary Contact Person", - ~customInput=InputFields.textInput(), - ~isRequired=true, - (), -) - -let secondaryContactPerson = FormRenderer.makeFieldInfo( - ~label="Secondary Contact Person", - ~name="secondary_contact_person", - ~placeholder="Secondary Contact Person", - ~customInput=InputFields.textInput(), - ~isRequired=true, - (), -) - -let website = FormRenderer.makeFieldInfo( - ~label="Website", - ~name="website", - ~placeholder="https://www.example.com", - ~customInput=InputFields.textInput(), - ~isRequired=false, - (), -) - -let aboutBusiness = FormRenderer.makeFieldInfo( - ~label="About Business", - ~name="about_business", - ~placeholder="About Business", - ~customInput=InputFields.multiLineTextInput( - ~isDisabled=false, - ~customClass="w-96", - ~rows=Some(6), - ~cols=Some(4), - (), - ), - ~isRequired=true, - (), -) - -let addressL1 = FormRenderer.makeFieldInfo( - ~label="", - ~name="line1", - ~placeholder="", - ~customInput=InputFields.textInput(), - (), -) - -let addressL2 = FormRenderer.makeFieldInfo( - ~label="", - ~name="line2", - ~placeholder="", - ~customInput=InputFields.textInput(), - (), -) -let addressL3 = FormRenderer.makeFieldInfo( - ~label="", - ~name="line3", - ~placeholder="", - ~customInput=InputFields.textInput(), - (), -) - -let addressCity = FormRenderer.makeFieldInfo( - ~label="", - ~name="city", - ~placeholder="City", - ~customInput=InputFields.textInput(), - (), -) - -let addressState = FormRenderer.makeFieldInfo( - ~label="", - ~name="state", - ~placeholder="State", - ~customInput=InputFields.textInput(), - (), -) - -let addressZip = FormRenderer.makeFieldInfo( - ~label="", - ~name="zip", - ~placeholder="Zip", - ~customInput=InputFields.textInput(), - (), -) - -let primaryEmail = FormRenderer.makeFieldInfo( - ~label="Primary Email", - ~name="primary_email", - ~placeholder="Primary Email", - ~isRequired=true, - ~customInput=InputFields.textInput(), - (), -) - -let secondaryEmail = FormRenderer.makeFieldInfo( - ~label="Secondary Email", - ~name="secondary_email", - ~placeholder="Secondary Email", - ~isRequired=true, - ~customInput=InputFields.textInput(), - (), -) - -let primaryPhone = FormRenderer.makeFieldInfo( - ~label="Primary Phone", - ~name="primary_phone", - ~placeholder="Primary Phone", - ~isRequired=true, - ~customInput=InputFields.textInput(), - (), -) - -let secondaryPhone = FormRenderer.makeFieldInfo( - ~label="Secondar Phone", - ~name="secondary_phone", - ~placeholder="Secondary Phone", - ~isRequired=true, - ~customInput=InputFields.textInput(), - (), -) - let parseKey = api_key => { api_key->Js.String2.slice(~from=0, ~to_=6)->Js.String2.concat(Js.String2.repeat("*", 20)) } @@ -244,60 +52,6 @@ let confirmPasswordCheck = (value, key, confirmKey, passwordKey, valuesDict, err } } -let validateChangePasswordForm = ( - values: Js.Json.t, - ~setIsDisabled=_ => (), - keys: array, -) => { - open LogicUtils - let valuesDict = switch values->Js.Json.decodeObject { - | Some(dict) => - dict - ->Js.Dict.entries - ->Array.reduce(Js.Dict.empty(), (acc, entry) => { - let (key, value) = entry - switch value->Js.Json.decodeString { - | Some(strVal) => Js.Dict.set(acc, key, strVal->Js.Json.string) - | None => () - } - acc - }) - | None => Js.Dict.empty() - } - - let errors = Js.Dict.empty() - - keys->Js.Array2.forEach(key => { - let value = valuesDict->getString(key, "") - - // empty check - if value == "" { - switch key { - | "oldPassword" => Js.Dict.set(errors, key, "Please enter your Old Password"->Js.Json.string) - | "password" => Js.Dict.set(errors, key, "Please enter your New Password"->Js.Json.string) - | "comfirmPassword" => - Js.Dict.set(errors, key, "Please enter your New Password Once Again"->Js.Json.string) - | _ => - Js.Dict.set( - errors, - key, - `${key->LogicUtils.capitalizeString} cannot be empty`->Js.Json.string, - ) - } - } - - // password check - passwordKeyValidation(value, key, "password", errors) - - // confirm password check - confirmPasswordCheck(value, key, "comfirmPassword", "password", valuesDict, errors) - }) - - errors == Js.Dict.empty() ? setIsDisabled(_ => false) : setIsDisabled(_ => true) - - errors->Js.Json.object_ -} - let parseBussinessProfileJson = (profileRecord: profileEntity) => { open LogicUtils let { @@ -366,32 +120,6 @@ let parseMerchantJson = (merchantDict: merchantPayload) => { merchantInfo } -let convertJsontoDict = (values: Js.Json.t) => { - switch values->Js.Json.decodeObject { - | Some(dict) => - dict - ->Js.Dict.entries - ->Array.reduce(Js.Dict.empty(), (acc, entry) => { - let (key, value) = entry - switch key { - | "primary_business_details" => - switch value->Js.Json.decodeArray { - | Some(strVal) => Js.Dict.set(acc, key, strVal->Js.Json.array) - | None => () - } - | _ => - switch value->Js.Json.decodeString { - | Some(strVal) => Js.Dict.set(acc, key, strVal->Js.Json.string) - | None => () - } - } - - acc - }) - | None => Js.Dict.empty() - } -} - let constructWebhookDetailsObject = webhookDetailsDict => { open LogicUtils let webhookDetails = { @@ -809,11 +537,9 @@ let useFetchMerchantDetails = () => { try { let accountUrl = APIUtils.getURL(~entityName=MERCHANT_ACCOUNT, ~methodType=Get, ()) let merchantDetailsJSON = await fetchDetails(accountUrl) - setMerchantDetailsValue(._ => merchantDetailsJSON->Js.Json.stringify) } catch { - | Js.Exn.Error(e) => - let _err = Js.Exn.message(e)->Belt.Option.getWithDefault("Failed to Fetch!") + | _ => () } } } diff --git a/src/screens/HyperSwitch/Settings/HSwitchProfileSettings.res b/src/screens/HyperSwitch/Settings/HSwitchProfileSettings.res index 9c81f4689..40478cbdf 100644 --- a/src/screens/HyperSwitch/Settings/HSwitchProfileSettings.res +++ b/src/screens/HyperSwitch/Settings/HSwitchProfileSettings.res @@ -28,9 +28,7 @@ module MerchantDetailsSection = { setMerchantInfo(_ => requiredInfo) setScreenState(_ => PageLoaderWrapper.Success) } catch { - | Js.Exn.Error(e) => - let _err = Js.Exn.message(e)->Belt.Option.getWithDefault("Failed to Fetch!") - setScreenState(_ => PageLoaderWrapper.Custom) + | Js.Exn.Error(_) => setScreenState(_ => PageLoaderWrapper.Custom) } } React.useEffect0(() => { From 7bfd823339a0dad5c0df6a6f75b4f68658b2856c Mon Sep 17 00:00:00 2001 From: Pritish Budhiraja <77892330+PritishBudhiraja@users.noreply.github.com> Date: Mon, 4 Dec 2023 14:53:43 +0530 Subject: [PATCH 05/27] chore: workflow-changes (#49) --- .github/workflows/release-new-version.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/release-new-version.yml b/.github/workflows/release-new-version.yml index 01ca10b53..73640cfb7 100644 --- a/.github/workflows/release-new-version.yml +++ b/.github/workflows/release-new-version.yml @@ -30,9 +30,9 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@v4 - # with: - # fetch-depth: 0 - # token: ${{ secrets.AUTO_RELEASE_PAT }} + with: + fetch-depth: 0 + token: ${{ secrets.AUTO_RELEASE_PAT }} - name: Install Rust uses: dtolnay/rust-toolchain@master From 68c61169e048e54892b71df8ed5844b3d00138e0 Mon Sep 17 00:00:00 2001 From: Jeeva Ramachandran Date: Mon, 4 Dec 2023 15:11:11 +0530 Subject: [PATCH 06/27] 1.0.3 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index a315ba727..01c1d9929 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rescript-euler-dashboard", - "version": "1.0.2", + "version": "1.0.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rescript-euler-dashboard", - "version": "1.0.2", + "version": "1.0.3", "hasInstallScript": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index c2f9c4eac..8e36174b9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rescript-euler-dashboard", - "version": "1.0.2", + "version": "1.0.3", "main": "index.js", "author": "Shiva Nandan ", "license": "MIT", From 0133ff13a7e915c4c796bd98fbaf92400690531a Mon Sep 17 00:00:00 2001 From: Jeeva Ramachandran <120017870+JeevaRamu0104@users.noreply.github.com> Date: Mon, 4 Dec 2023 15:26:43 +0530 Subject: [PATCH 07/27] chore: remove dead code (#50) --- src/screens/HyperSwitch/HSwitchUtils.res | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/screens/HyperSwitch/HSwitchUtils.res b/src/screens/HyperSwitch/HSwitchUtils.res index cdeb685ff..68048672a 100644 --- a/src/screens/HyperSwitch/HSwitchUtils.res +++ b/src/screens/HyperSwitch/HSwitchUtils.res @@ -227,18 +227,6 @@ let getBrowswerDetails = () => { } } -let getLabelToCountryMapper = primary_business_details => { - primary_business_details->Array.reduce(Js.Dict.empty(), ( - acc, - currentDetail: HSwitchSettingTypes.businessEntity, - ) => { - let labelsYet = acc->Js.Dict.get(currentDetail.country)->Belt.Option.getWithDefault([]) - labelsYet->Array.push(currentDetail.business) - acc->Js.Dict.set(currentDetail.country, labelsYet) - acc - }) -} - module BackgroundImageWrapper = { @react.component let make = ( From eebee659a8326aa32ebcbe2d06c21e8487bea377 Mon Sep 17 00:00:00 2001 From: Pritish Budhiraja <77892330+PritishBudhiraja@users.noreply.github.com> Date: Mon, 4 Dec 2023 15:38:59 +0530 Subject: [PATCH 08/27] fix: dead code removal (#52) --- package.json | 2 +- .../UserManagement/HSwitchUserRoleEntity.res | 50 ------------------- 2 files changed, 1 insertion(+), 51 deletions(-) diff --git a/package.json b/package.json index 8e36174b9..0ca190a14 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "rescript-euler-dashboard", + "name": "hyperswitch-dashboard", "version": "1.0.3", "main": "index.js", "author": "Shiva Nandan ", diff --git a/src/screens/HyperSwitch/UserManagement/HSwitchUserRoleEntity.res b/src/screens/HyperSwitch/UserManagement/HSwitchUserRoleEntity.res index d27ae6dfb..23afdc956 100644 --- a/src/screens/HyperSwitch/UserManagement/HSwitchUserRoleEntity.res +++ b/src/screens/HyperSwitch/UserManagement/HSwitchUserRoleEntity.res @@ -31,10 +31,6 @@ type roleColTypes = | Description | ActiveUsers -let defaultColumnsForRole = [Role, Description, CreatedBy, CreatedOn, ActiveUsers] - -let allColumnsForRole = [Role, Description, CreatedBy, CreatedOn, ActiveUsers] - let itemToObjMapperForUser = dict => { { user_id: getString(dict, "user_id", ""), @@ -74,18 +70,6 @@ let itemToObjMapperForRole = dict => { } } -let getHeadingForRole = colType => { - switch colType { - | Role => Table.makeHeaderInfo(~key="role", ~title="Role name", ~showSort=true, ()) - | Description => - Table.makeHeaderInfo(~key="description", ~title="Description", ~showSort=true, ()) - | CreatedBy => Table.makeHeaderInfo(~key="created_by", ~title="Created By", ~showSort=true, ()) - | CreatedOn => Table.makeHeaderInfo(~key="created_on", ~title="Created On", ~showSort=true, ()) - | ActiveUsers => - Table.makeHeaderInfo(~key="activeUsers", ~title="Active Users", ~showSort=true, ()) - } -} - let roleToVariantMapper = role => { switch role->Js.String2.toUpperCase { | "ADMIN" => Admin @@ -149,32 +133,10 @@ let getCellForUser = (data: userTableTypes, colType: userColTypes): Table.cell = } } -let getCellForRole = (data: roleTableTypes, colType: roleColTypes): Table.cell => { - let role = data.role_id->roleToVariantMapper - switch colType { - | Role => - CustomCell( -
getCssMapperForRole}`}> - {data.role_id->Js.String2.toUpperCase->React.string} -
, - "", - ) - | Description => Text(data.role_id) - | CreatedBy => Text(data.role_id) - | CreatedOn => Date(data.role_id) - | ActiveUsers => Text(data.role_id) - } -} - let getUserData: Js.Json.t => array = json => { getArrayDataFromJson(json, itemToObjMapperForUser) } -let getRoleData: Js.Json.t => array = json => { - getArrayDataFromJson(json, itemToObjMapperForRole) -} - let userEntity = EntityType.makeEntity( ~uri="", ~getObjects=getUserData, @@ -186,15 +148,3 @@ let userEntity = EntityType.makeEntity( ~getShowLink={userId => `/users/${userId.user_id}?state=user`}, (), ) - -// let roleEntity = EntityType.makeEntity( -// ~uri="", -// ~getObjects=getRoleData, -// ~defaultColumns=defaultColumnsForRole, -// ~allColumns=allColumnsForRole, -// ~getHeading=getHeadingForRole, -// ~getCell=getCellForRole, -// ~dataKey="", -// ~getShowLink={roleId => `/users/${roleId.role_id}?state=role`}, -// (), -// ) From 6978bf6814fb856c67a0fe409638982239c1af80 Mon Sep 17 00:00:00 2001 From: Pritish Budhiraja <77892330+PritishBudhiraja@users.noreply.github.com> Date: Mon, 4 Dec 2023 16:00:24 +0530 Subject: [PATCH 09/27] fix: remove CHANGELOG.md (#53) --- .githooks/commit-msg | 2 +- .prettierignore | 1 + CHANGELOG.md | 18 ------------------ 3 files changed, 2 insertions(+), 19 deletions(-) create mode 100644 .prettierignore delete mode 100644 CHANGELOG.md diff --git a/.githooks/commit-msg b/.githooks/commit-msg index 865cf65c2..0848397bd 100755 --- a/.githooks/commit-msg +++ b/.githooks/commit-msg @@ -11,7 +11,7 @@ npx prettier --write . npm run re:format # Define your commit message convention (e.g., starts with "feature:", "fix:", etc.) -commit_regex="^(Merge branch|feat|fix|chore|docs|style|refactor|test|enhancement).+" +commit_regex="^(Merge branch|feat|fix|chore|docs|style|refactor|test|enhancement):.+" if ! echo "$commit_msg" | grep -Ei "$commit_regex" ; then echo "Aborting commit. Your commit message does not follow the conventional format." diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..83b694704 --- /dev/null +++ b/.prettierignore @@ -0,0 +1 @@ +CHANGELOG.md \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index ccce7288b..000000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,18 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. See [conventional commits](https://www.conventionalcommits.org/) for commit guidelines. - ---- - -## 1.1.0 (2023-11-29) - -### Features - -- Add-release-new-version-action ([`880a10e`](https://github.com/juspay/hyperswitch-control-center/commit/880a10e0695284bb76a6e4cf156774a8a6e0fb01)) -- Add change log template ([`9475c4a`](https://github.com/juspay/hyperswitch-control-center/commit/9475c4a2863c12110a4f8bf2826fa68cdba7ab09)) - -**Full Changelog:** [`v1.0.2...v1.1.0`](https://github.com/juspay/hyperswitch-control-center/compare/v1.0.2...v1.1.0) - ---- - -Changelog generated by [cocogitto](https://github.com/cocogitto/cocogitto). From 20d93eb1186ad2e3e12f7628276a658aa13ca692 Mon Sep 17 00:00:00 2001 From: github-actions <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 4 Dec 2023 10:32:48 +0000 Subject: [PATCH 10/27] chore(version): v1.0.4 --- CHANGELOG.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..a4247f0cb --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,21 @@ +# Changelog +All notable changes to this project will be documented in this file. See [conventional commits](https://www.conventionalcommits.org/) for commit guidelines. + +- - - + +## 1.0.4 (2023-12-04) + +### Bug Fixes + +- Dead code removal ([#52](https://github.com/juspay/hyperswitch-control-center/pull/52)) ([`eebee65`](https://github.com/juspay/hyperswitch-control-center/commit/eebee659a8326aa32ebcbe2d06c21e8487bea377)) +- Remove CHANGELOG.md ([#53](https://github.com/juspay/hyperswitch-control-center/pull/53)) ([`6978bf6`](https://github.com/juspay/hyperswitch-control-center/commit/6978bf6814fb856c67a0fe409638982239c1af80)) + +### Miscellaneous Tasks + +- Remove dead code ([#50](https://github.com/juspay/hyperswitch-control-center/pull/50)) ([`0133ff1`](https://github.com/juspay/hyperswitch-control-center/commit/0133ff13a7e915c4c796bd98fbaf92400690531a)) + +**Full Changelog:** [`v1.0.3...v1.0.4`](https://github.com/juspay/hyperswitch-control-center/compare/v1.0.3...v1.0.4) + +- - - + +Changelog generated by [cocogitto](https://github.com/cocogitto/cocogitto). \ No newline at end of file From 4ef0b5707aa9293ae3904858daaf645fa69fc7cc Mon Sep 17 00:00:00 2001 From: Pritish Budhiraja <77892330+PritishBudhiraja@users.noreply.github.com> Date: Mon, 4 Dec 2023 16:32:55 +0530 Subject: [PATCH 11/27] chore: Release new version workflow fixes (#54) --- .github/workflows/release-new-version.yml | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/.github/workflows/release-new-version.yml b/.github/workflows/release-new-version.yml index 73640cfb7..ade4f1982 100644 --- a/.github/workflows/release-new-version.yml +++ b/.github/workflows/release-new-version.yml @@ -1,19 +1,19 @@ name: Release a new hyperswitch version -# on: -# schedule: -# - cron: "30 14 * * 0-4" # Run workflow at 8 PM IST every Sunday-Thursday +on: + schedule: + - cron: "30 14 * * 0-4" # Run workflow at 8 PM IST every Sunday-Thursday -# workflow_dispatch: + workflow_dispatch: -# concurrency: -# group: ${{ github.workflow }}-${{ github.ref }} -# cancel-in-progress: true +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true -on: - pull_request_target: - types: - - closed +# on: +# pull_request_target: +# types: +# - closed env: # Allow more retries for network requests in cargo (downloading crates) and From a1d2f140fbf1be884d853fa2059a9a2f8260628f Mon Sep 17 00:00:00 2001 From: Jeeva Ramachandran <120017870+JeevaRamu0104@users.noreply.github.com> Date: Mon, 4 Dec 2023 19:26:00 +0530 Subject: [PATCH 12/27] chore: Sdk feature flag (#57) --- src/entryPoints/hyperswitch/HyperSwitchApp.res | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/entryPoints/hyperswitch/HyperSwitchApp.res b/src/entryPoints/hyperswitch/HyperSwitchApp.res index 4ed82e6da..40bfc27a9 100644 --- a/src/entryPoints/hyperswitch/HyperSwitchApp.res +++ b/src/entryPoints/hyperswitch/HyperSwitchApp.res @@ -338,8 +338,14 @@ let make = () => { renderShow={profileId => } /> - | list{"recon"} => - | list{"sdk"} => + | list{"recon"} => + + + + | list{"sdk"} => + + + | list{"3ds"} => | list{"account-settings"} => From 83b7de41866dffbd813f9867568f265a22a66a16 Mon Sep 17 00:00:00 2001 From: Jeeva Ramachandran Date: Mon, 4 Dec 2023 19:39:17 +0530 Subject: [PATCH 13/27] 1.0.4 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 01c1d9929..1fc199e78 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rescript-euler-dashboard", - "version": "1.0.3", + "version": "1.0.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rescript-euler-dashboard", - "version": "1.0.3", + "version": "1.0.4", "hasInstallScript": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index 0ca190a14..ebe297495 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hyperswitch-dashboard", - "version": "1.0.3", + "version": "1.0.4", "main": "index.js", "author": "Shiva Nandan ", "license": "MIT", From e5498620de2411d3cf8317fe768052f42c855f45 Mon Sep 17 00:00:00 2001 From: Jeeva Ramachandran Date: Mon, 4 Dec 2023 19:40:20 +0530 Subject: [PATCH 14/27] 1.0.5 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 1fc199e78..195c36bdd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rescript-euler-dashboard", - "version": "1.0.4", + "version": "1.0.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rescript-euler-dashboard", - "version": "1.0.4", + "version": "1.0.5", "hasInstallScript": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index ebe297495..8329a0739 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hyperswitch-dashboard", - "version": "1.0.4", + "version": "1.0.5", "main": "index.js", "author": "Shiva Nandan ", "license": "MIT", From 4fbaee4bf0b1b65b08513bd9208e49f154911ae0 Mon Sep 17 00:00:00 2001 From: Riddhiagrawal001 <50551695+Riddhiagrawal001@users.noreply.github.com> Date: Tue, 5 Dec 2023 11:32:43 +0530 Subject: [PATCH 15/27] fix: warning icon added (#59) Co-authored-by: Riddhi Agrawal --- public/hyperswitch/icons/warning.svg | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 public/hyperswitch/icons/warning.svg diff --git a/public/hyperswitch/icons/warning.svg b/public/hyperswitch/icons/warning.svg new file mode 100644 index 000000000..b7e56b83f --- /dev/null +++ b/public/hyperswitch/icons/warning.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file From b31e24c28442b3f4a11506ba9a43c371f5c864d9 Mon Sep 17 00:00:00 2001 From: Riddhi Agrawal Date: Tue, 5 Dec 2023 11:50:58 +0530 Subject: [PATCH 16/27] enhancement: 3ds code refactor and bugfixes --- .../RoutingRevamp/AdvancedRouting.res | 95 ++---------- .../RoutingRevamp/AdvancedRoutingUtils.res | 85 ++++++++++- .../Previewers/RulePreviewer.res | 7 +- .../ThreeDSFlow/HSwitchThreeDS.res | 49 +++---- .../HyperSwitch/ThreeDSFlow/ThreeDSUtils.res | 137 +++++++----------- 5 files changed, 170 insertions(+), 203 deletions(-) diff --git a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res index cccabcc27..ed2143086 100644 --- a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res +++ b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res @@ -45,21 +45,6 @@ module Add3DSCondition = { @react.component let make = (~isFirst, ~id) => { let classStyle = "flex justify-center relative py-2 h-fit min-w-min hover:bg-jp-2-light-gray-100 focus:outline-none rounded-md items-center border-2 border-border_gray border-opacity-50 text-jp-2-light-gray-1200 px-4 transition duration-[250ms] ease-out-[cubic-bezier(0.33, 1, 0.68, 1)] overflow-hidden" - let (dropdownval, setDropdownval) = React.useState(_ => "three_ds") - let field = ReactFinalForm.useField(`${id}.routingOutput.override_3ds`).input - - let input: ReactFinalForm.fieldRenderPropsInput = { - name: `${id}.routingOutput.override_3ds`, - onBlur: _ev => (), - onChange: ev => { - let value = ev->AdvancedRoutingUIUtils.formEventToStr - field.onChange(value->toForm) - setDropdownval(_ => value) - }, - onFocus: _ev => (), - value: dropdownval->Js.Json.string, - checked: true, - } let options: array = [ {value: "three_ds", label: "3DS"}, @@ -74,13 +59,19 @@ module Add3DSCondition = {
{"Auth type"->React.string}
{"= is Equal to"->React.string}
-
@@ -572,65 +563,7 @@ let make = (~routingRuleId, ~isActive, ~setCurrentRouting) => { let rulesDict = dataDict->getArrayFromDict("rules", []) - let modifiedRules = rulesDict->Js.Array2.map(ruleJson => { - let ruleDict = ruleJson->getDictFromJsonObject - let statements = ruleDict->getArrayFromDict("statements", []) - - let modifiedStatements = statements->Array.reduce( - [ - { - condition: [], - }, - ], - (acc, statement) => { - let statementDict = statement->getDictFromJsonObject - let logicalOperator = statementDict->getString("logical", "")->Js.String2.toLowerCase - - let lastItem = - acc - ->Belt.Array.get(acc->Js.Array2.length - 1) - ->Belt.Option.getWithDefault({condition: []}) - - let condition = { - lhs: statementDict->getString("lhs", ""), - comparison: switch statementDict->getString("comparison", "")->operatorMapper { - | IS - | EQUAL_TO - | CONTAINS => "equal" - | IS_NOT - | NOT_CONTAINS - | NOT_EQUAL_TO => "not_equal" - | GREATER_THAN => "greater_than" - | LESS_THAN => "less_than" - | UnknownOperator(str) => str - }, - value: statementDict->getDictfromDict("value")->getStatementValue, - metadata: statementDict->getJsonObjectFromDict("metadata"), - } - - let newAcc = if logicalOperator === "or" { - acc->Js.Array2.concat([ - { - condition: [condition], - }, - ]) - } else { - lastItem.condition->Array.push(condition) - let filteredArr = - acc->Array.filterWithIndex((_, i) => i !== acc->Js.Array2.length - 1) - filteredArr->Array.push(lastItem) - filteredArr - } - - newAcc - }, - ) - { - "name": ruleDict->getString("name", ""), - "connectorSelection": ruleDict->getJsonObjectFromDict("connectorSelection"), - "statements": modifiedStatements->Js.Array2.map(toJson)->Js.Json.array, - } - }) + let modifiedRules = rulesDict->generateRule let defaultSelection = dataDict diff --git a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res index 92451c08c..47f9faea6 100644 --- a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res +++ b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res @@ -1,5 +1,6 @@ open LogicUtils open AdvancedRoutingTypes +external toJson: 'a => Js.Json.t = "%identity" let getCurrentDetailedUTCTime = () => { Js.Date.fromFloat(Js.Date.now())->Js.Date.toUTCString @@ -169,11 +170,19 @@ let connectorSelectionDataMapperFromJson: Js.Json.t => connectorSelectionData = let getDefaultSelection: Js.Dict.t< Js.Json.t, > => AdvancedRoutingTypes.connectorSelection = defaultSelection => { - { - \"type": defaultSelection->getString("type", ""), - data: defaultSelection - ->getArrayFromDict("data", []) - ->Js.Array2.map(ele => ele->connectorSelectionDataMapperFromJson), + let override3dsValue = defaultSelection->getString("override_3ds", "") + + if override3dsValue->Js.String2.length > 0 { + { + override_3ds: override3dsValue, + } + } else { + { + \"type": defaultSelection->getString("type", ""), + data: defaultSelection + ->getArrayFromDict("data", []) + ->Js.Array2.map(ele => ele->connectorSelectionDataMapperFromJson), + } } } @@ -321,3 +330,69 @@ let getRoutingTypesFromJson = (values: Js.Json.t) => { let validateStatements = statementsArray => { statementsArray->Js.Array2.every(isStatementMandatoryFieldsPresent) } + +let generateStatements = statements => { + statements->Array.reduce( + [ + { + condition: [], + }, + ], + (acc, statement) => { + let statementDict = statement->LogicUtils.getDictFromJsonObject + let logicalOperator = + statementDict->LogicUtils.getString("logical", "")->Js.String2.toLowerCase + + let lastItem = + acc->Belt.Array.get(acc->Js.Array2.length - 1)->Belt.Option.getWithDefault({condition: []}) + + let condition = { + lhs: statementDict->LogicUtils.getString("lhs", ""), + comparison: switch statementDict->LogicUtils.getString("comparison", "")->operatorMapper { + | IS + | EQUAL_TO + | CONTAINS => "equal" + | IS_NOT + | NOT_CONTAINS + | NOT_EQUAL_TO => "not_equal" + | GREATER_THAN => "greater_than" + | LESS_THAN => "less_than" + | UnknownOperator(str) => str + }, + value: statementDict->LogicUtils.getDictfromDict("value")->getStatementValue, + metadata: statementDict->LogicUtils.getJsonObjectFromDict("metadata"), + } + + let newAcc = if logicalOperator === "or" { + acc->Js.Array2.concat([ + { + condition: [condition], + }, + ]) + } else { + lastItem.condition->Array.push(condition) + let filteredArr = acc->Array.filterWithIndex((_, i) => i !== acc->Js.Array2.length - 1) + filteredArr->Array.push(lastItem) + filteredArr + } + + newAcc + }, + ) +} + +let generateRule = rulesDict => { + let modifiedRules = rulesDict->Js.Array2.map(ruleJson => { + let ruleDict = ruleJson->LogicUtils.getDictFromJsonObject + let statements = ruleDict->LogicUtils.getArrayFromDict("statements", []) + + let modifiedStatements = statements->generateStatements + + { + "name": ruleDict->LogicUtils.getString("name", ""), + "connectorSelection": ruleDict->LogicUtils.getJsonObjectFromDict("connectorSelection"), + "statements": modifiedStatements->Js.Array2.map(toJson)->Js.Json.array, + } + }) + modifiedRules +} diff --git a/src/screens/HyperSwitch/RoutingRevamp/Previewers/RulePreviewer.res b/src/screens/HyperSwitch/RoutingRevamp/Previewers/RulePreviewer.res index a85510891..7686ad9b7 100644 --- a/src/screens/HyperSwitch/RoutingRevamp/Previewers/RulePreviewer.res +++ b/src/screens/HyperSwitch/RoutingRevamp/Previewers/RulePreviewer.res @@ -28,7 +28,7 @@ module GatewayView = { } @react.component -let make = (~ruleInfo: algorithmData, ~isfrom3ds=false) => { +let make = (~ruleInfo: algorithmData, ~isFrom3ds=false) => { open LogicUtils
{ let value = switch statement.value.value->Js.Json.classify { | JSONArray(arr) => arr->Js.Array2.joinWith(", ") | JSONString(str) => str + | JSONNumber(num) => num->Belt.Float.toString | _ => "" } @@ -97,13 +98,13 @@ let make = (~ruleInfo: algorithmData, ~isfrom3ds=false) => { Js.Array2.length > 0}> - +
{threeDsType->LogicUtils.capitalizeString->React.string}
- + Belt.Option.getWithDefault([])} /> diff --git a/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res b/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res index c7e55f912..0d5335c23 100644 --- a/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res +++ b/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res @@ -9,7 +9,12 @@ module ActiveRulePreview = { let ruleInfo = initialRule->Belt.Option.getWithDefault(Js.Dict.empty()) let name = ruleInfo->getString("name", "") let description = ruleInfo->getString("description", "") - let ruleInfo = ruleInfo->getJsonObjectFromDict("rules")->RoutingUtils.ruleInfoTypeMapper + + let ruleInfo = + ruleInfo + ->getJsonObjectFromDict("algorithm") + ->getDictFromJsonObject + ->AdvancedRoutingUtils.ruleInfoTypeMapper Belt.Option.isSome}>
@@ -25,7 +30,7 @@ module ActiveRulePreview = { {description->React.string}

- +
} @@ -34,7 +39,7 @@ module ActiveRulePreview = { module Configure3DSRule = { @react.component let make = (~wasm) => { - let ruleInput = ReactFinalForm.useField("json.rules").input + let ruleInput = ReactFinalForm.useField("algorithm.rules").input let (rules, setRules) = React.useState(_ => ruleInput.value->LogicUtils.getArrayFromJson([])) React.useEffect1(() => { ruleInput.onChange(rules->arrToFormEvent) @@ -58,7 +63,7 @@ module Configure3DSRule = { let notFirstRule = ruleInput.value->LogicUtils.getArrayFromJson([])->Js.Array2.length > 1 let rule = ruleInput.value->Js.Json.decodeArray->Belt.Option.getWithDefault([]) let keyExtractor = (index, _rule, isDragging) => { - let id = {`json.rules[${string_of_int(index)}]`} + let id = {`algorithm.rules[${string_of_int(index)}]`} let i = 1 { let fetchDetails = useGetMethod(~showErrorToast=false, ()) let updateDetails = useUpdateMethod(~showErrorToast=false, ()) let (wasm, setWasm) = React.useState(_ => None) - let (initialValues, _setInitialValues) = React.useState(_ => - buildInitial3DSValue->Js.Json.object_ - ) + let (initialValues, _setInitialValues) = React.useState(_ => buildInitial3DSValue->toJson) let (initialRule, setInitialRule) = React.useState(() => None) let (screenState, setScreenState) = React.useState(_ => PageLoaderWrapper.Loading) let (pageView, setPageView) = React.useState(_ => NEW) @@ -123,18 +126,14 @@ let make = () => { try { let threeDsUrl = getURL(~entityName=THREE_DS, ~methodType=Get, ()) let threeDsRuleDetail = await fetchDetails(threeDsUrl) - let schemaValue = - threeDsRuleDetail - ->getDictFromJsonObject - ->getObj("program", Js.Dict.empty()) - ->getObj("metadata", Js.Dict.empty()) - ->getObj("schema", Js.Dict.empty()) + let responseDict = threeDsRuleDetail->getDictFromJsonObject + let programValue = responseDict->getObj("program", Js.Dict.empty()) let intitialValue = [ - ("name", schemaValue->LogicUtils.getString("name", "")->Js.Json.string), - ("description", schemaValue->LogicUtils.getString("description", "")->Js.Json.string), - ("rules", schemaValue->LogicUtils.getObj("json", Js.Dict.empty())->Js.Json.object_), + ("name", responseDict->LogicUtils.getString("name", "")->Js.Json.string), + ("description", responseDict->LogicUtils.getString("description", "")->Js.Json.string), + ("algorithm", programValue->Js.Json.object_), ]->Js.Dict.fromArray setInitialRule(_ => Some(intitialValue)) @@ -183,24 +182,10 @@ let make = () => { let onSubmit = async (values, _) => { try { setScreenState(_ => Loading) - let dict = values->LogicUtils.getDictFromJsonObject - - let json = dict->LogicUtils.getJsonObjectFromDict("json")->LogicUtils.getDictFromJsonObject - - let description = dict->LogicUtils.getString("description", "") - let name = dict->LogicUtils.getString("name", "") - - let metadata = - [ - ("name", name->Js.Json.string), - ("description", description->Js.Json.string), - ("schema", dict->Js.Json.object_), - ]->Js.Dict.fromArray - - let threeDsPayload = buildThreeDsPayloadBody(json, wasm, metadata, name) + let threeDsPayload = values->buildThreeDsPayloadBody let getActivateUrl = getURL(~entityName=THREE_DS, ~methodType=Put, ()) - let _response = await updateDetails(getActivateUrl, threeDsPayload->Js.Json.object_, Put) + let _response = await updateDetails(getActivateUrl, threeDsPayload->toJson, 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 42d2fda37..1997f8c2a 100644 --- a/src/screens/HyperSwitch/ThreeDSFlow/ThreeDSUtils.res +++ b/src/screens/HyperSwitch/ThreeDSFlow/ThreeDSUtils.res @@ -1,55 +1,51 @@ -external toJson: 'a => array = "%identity" -type conditonType = { - \"logical.operator"?: string, - field: string, - real_field: string, - operator: string, - value: string, -} +external toJson: 'a => Js.Json.t = "%identity" type pageState = NEW | LANDING -open RoutingUtils -let conditions: array = [ +let statementObject: array = [ { - field: "amount", - real_field: "amount", - operator: "EQUAL TO", - value: "", + lhs: "amount", + value: { + \"type": "number", + value: ""->Js.Json.string, + }, + comparison: "EQUAL TO", }, { - \"logical.operator": "AND", - field: "currency", - real_field: "currency", - operator: "IS", - value: "", + logical: "AND", + value: { + \"type": "number", + value: ""->Js.Json.string, + }, + lhs: "currency", + comparison: "IS", }, ] -let constructNameDescription = - [ - ("name", `3DS Rule-${getCurrentUTCTime()}`->Js.Json.string), - ("description", `This is a Three-Ds Rule created at ${currentTimeInUTC}`->Js.Json.string), - ]->Js.Dict.fromArray - -let buildInitial3DSValue = { - let routingValueOutput = [("override_3ds", "three_ds"->Js.Json.string)]->Js.Dict.fromArray - let defaultValue = - [ - ("gateways", []->Js.Json.array), - ("conditions", conditions->toJson->Js.Json.array), - ("routingOutput", routingValueOutput->Js.Json.object_), - ]->Js.Dict.fromArray - - let initialJson = [("rules", [defaultValue->Js.Json.object_]->Js.Json.array)]->Js.Dict.fromArray - - let initialValueJson = constructNameDescription +type threeDsRoutingType = { + name: string, + description: string, + algorithm: AdvancedRoutingTypes.algorithmData, +} - initialValueJson->Js.Dict.set("json", initialJson->Js.Json.object_) - initialValueJson->Js.Dict.set("code", ""->Js.Json.string) +let rules: AdvancedRoutingTypes.rule = { + name: "rule_1", + connectorSelection: { + override_3ds: "three_ds", + }, + statements: statementObject, +} - // initialValueJson->Js.Dict.set("routingOutput", routingValueOutput->Js.Json.object_) - initialValueJson +let buildInitial3DSValue: threeDsRoutingType = { + name: `3DS Rule-${RoutingUtils.getCurrentUTCTime()}`, + description: `This is a Three-Ds Rule created at ${RoutingUtils.currentTimeInUTC}`, + algorithm: { + rules: [rules], + defaultSelection: { + override_3ds: "", + }, + metadata: Js.Json.null, + }, } let pageStateMapper = pageType => { @@ -59,58 +55,35 @@ let pageStateMapper = pageType => { } } -let generateRule = (index, statement, ~threeDsValue, ()) => { - let ruleObj = Js.Dict.fromArray([ - ("name", `rule_${string_of_int(index + 1)}`->Js.Json.string), - ("statements", statement->Js.Json.array), - ]) - ruleObj->Js.Dict.set("routingOutput", threeDsValue->Js.Json.object_) - ruleObj -} -let constuctAlgorithmValue = (rules, metadata) => { +let constuctAlgorithmValue = rules => { let defaultSelection = [("override_3ds", Js.Json.null)]->Js.Dict.fromArray let algorithm = [ ("defaultSelection", defaultSelection->Js.Json.object_), ("rules", rules->Js.Json.array), - ("metadata", metadata->Js.Json.object_), ]->Js.Dict.fromArray algorithm } -let buildThreeDsPayloadBody = (dict, wasm, metadata, name) => { - open LogicUtils - let threeDsPayload = [("name", name->Js.Json.string)]->Js.Dict.fromArray - - let rules = [] - - let _payload = - dict - ->getArrayFromDict("rules", []) - ->Array.reduceWithIndex([], (acc, priorityLogicObj, index) => { - switch priorityLogicObj->Js.Json.decodeObject { - | Some(priorityLogicObj) => { - let statement = generateStatement( - priorityLogicObj->getArrayFromDict("conditions", []), - wasm, - ) - let threeDsValue = priorityLogicObj->getObj("routingOutput", Js.Dict.empty()) - - let ruleObj = generateRule(index, statement, ~threeDsValue, ()) - - rules->Array.push(ruleObj->Js.Json.object_) - } - - | None => () - } - acc - }) - - let algorithm = constuctAlgorithmValue(rules, metadata) - - threeDsPayload->Js.Dict.set("algorithm", algorithm->Js.Json.object_) +let buildThreeDsPayloadBody = values => { + let valuesDict = values->LogicUtils.getDictFromJsonObject + let dataDict = valuesDict->LogicUtils.getDictfromDict("algorithm") + let rulesDict = dataDict->LogicUtils.getArrayFromDict("rules", []) + + let modifiedRules = rulesDict->AdvancedRoutingUtils.generateRule + + let threeDsPayload = { + "name": valuesDict->LogicUtils.getString("name", ""), + "algorithm": { + "defaultSelection": { + "override_3ds": null, + }, + "rules": modifiedRules, + "metadata": Js.Dict.empty()->Js.Json.object_, + }, + } threeDsPayload } From df353e7828f0c84137ae15927bb20735cca03792 Mon Sep 17 00:00:00 2001 From: Riddhi Agrawal Date: Tue, 5 Dec 2023 12:15:58 +0530 Subject: [PATCH 17/27] fix: css issue --- src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res index ed2143086..65d7a4209 100644 --- a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res +++ b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res @@ -66,7 +66,7 @@ module Add3DSCondition = { ~customInput=InputFields.selectInput( ~options, ~buttonText="Select Field", - ~customButtonStyle=`!-mt-5 ${classStyle} !rounded-md `, + ~customButtonStyle=`!-mt-5 ${classStyle} !rounded-md`, ~deselectDisable=true, (), ), From f43b7024e6411753072949c1089debd29fdf4dfe Mon Sep 17 00:00:00 2001 From: Riddhi Agrawal Date: Tue, 5 Dec 2023 12:44:48 +0530 Subject: [PATCH 18/27] fix: validation check changes --- src/components/MakeRuleFieldComponent.res | 18 ++++++++++-------- .../HyperSwitch/Routing/RoutingUtils.res | 2 +- .../HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res | 2 +- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/components/MakeRuleFieldComponent.res b/src/components/MakeRuleFieldComponent.res index 82d779019..f53de64e7 100644 --- a/src/components/MakeRuleFieldComponent.res +++ b/src/components/MakeRuleFieldComponent.res @@ -2,22 +2,24 @@ external strToFormEvent: Js.String.t => ReactEvent.Form.t = "%identity" let validateConditionJson = json => { open LogicUtils let checkValue = dict => { - dict + let valueFromObject = dict->getDictfromDict("value") + + valueFromObject ->getArrayFromDict("value", []) ->Js.Array2.filter(ele => { ele != ""->Js.Json.string }) ->Js.Array2.length > 0 || - dict->getString("value", "") !== "" || - dict->getFloat("value", -1.0) !== -1.0 || - dict->getString("operator", "") == "IS NULL" || - dict->getString("operator", "") == "IS NOT NULL" + valueFromObject->getString("value", "") !== "" || + valueFromObject->getFloat("value", -1.0) !== -1.0 || + valueFromObject->getString("comparison", "") == "IS NULL" || + valueFromObject->getString("comparison", "") == "IS NOT NULL" } + switch json->Js.Json.decodeObject { | Some(dict) => - ["operator", "real_field"]->Js.Array2.every(key => - dict->Js.Dict.get(key)->Belt.Option.isSome - ) && dict->checkValue + ["comparison", "lhs"]->Js.Array2.every(key => dict->Js.Dict.get(key)->Belt.Option.isSome) && + dict->checkValue | None => false } } diff --git a/src/screens/HyperSwitch/Routing/RoutingUtils.res b/src/screens/HyperSwitch/Routing/RoutingUtils.res index 079bfea39..b3ad9c285 100644 --- a/src/screens/HyperSwitch/Routing/RoutingUtils.res +++ b/src/screens/HyperSwitch/Routing/RoutingUtils.res @@ -695,7 +695,7 @@ let validateConditions = dict => { } let validateConditionsEvenIfOneExists = dict => { - let conditionsArray = dict->LogicUtils.getArrayFromDict("conditions", []) + let conditionsArray = dict->LogicUtils.getArrayFromDict("statements", []) let vector = Js.Vector.make(conditionsArray->Js.Array2.length, false) conditionsArray->Array.forEachWithIndex((value, index) => { diff --git a/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res b/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res index 0d5335c23..9eecdbd8d 100644 --- a/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res +++ b/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res @@ -206,7 +206,7 @@ let make = () => { RoutingUtils.validateNameAndDescription(~dict, ~errors) - switch dict->Js.Dict.get("json")->Belt.Option.flatMap(Js.Json.decodeObject) { + switch dict->Js.Dict.get("algorithm")->Belt.Option.flatMap(Js.Json.decodeObject) { | Some(jsonDict) => { let index = 1 let rules = jsonDict->LogicUtils.getArrayFromDict("rules", []) From 4f69afe1946bd431fb6e8a31ee621358ff28ad12 Mon Sep 17 00:00:00 2001 From: Pritish Budhiraja <77892330+PritishBudhiraja@users.noreply.github.com> Date: Tue, 5 Dec 2023 12:46:36 +0530 Subject: [PATCH 19/27] chore: signed commit added. (#62) Co-authored-by: Jeeva Ramachandran <120017870+JeevaRamu0104@users.noreply.github.com> --- .githooks/commit-msg | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/.githooks/commit-msg b/.githooks/commit-msg index 0848397bd..cfc7fde59 100755 --- a/.githooks/commit-msg +++ b/.githooks/commit-msg @@ -10,12 +10,20 @@ commit_msg=$(cat "$commit_msg_file") npx prettier --write . npm run re:format -# Define your commit message convention (e.g., starts with "feature:", "fix:", etc.) -commit_regex="^(Merge branch|feat|fix|chore|docs|style|refactor|test|enhancement):.+" +# Define your commit message convention (e.g., starts with "feat:", "fix:", etc.) +commit_regex="^(Merge branch|(feat|fix|chore|refactor|docs|test|style|enhancement):).+" -if ! echo "$commit_msg" | grep -Ei "$commit_regex" ; then - echo "Aborting commit. Your commit message does not follow the conventional format." - echo "Example - : - " + +if git log -1 --show-signature &> /dev/null; then + if ! echo "$commit_msg" | grep -Ei "$commit_regex" ; then + echo "Aborting commit. Your commit message does not follow the conventional format." + echo "The commit message should begin with one of the following keywords followed by a colon: 'feat', 'fix', 'chore', 'refactor', 'docs', 'test' or 'style'. For example, it should be formatted like this: 'feat: - '" + exit 1 + fi +else + echo "~~~~**** Error: Commit Signature Missing. ****~~~~" + echo "Please make sure to sign your commits. You can sign your commit by using the '-S' option with 'git commit'." + echo "Example: git commit -S -m 'Your commit message'" exit 1 fi From 5bfae972ac4cd2f367d26317c203b2c9d425535d Mon Sep 17 00:00:00 2001 From: Lokesh Jain <56452497+jainlokesh318@users.noreply.github.com> Date: Tue, 5 Dec 2023 12:54:16 +0530 Subject: [PATCH 20/27] chore: Cleanup Configs (#48) Co-authored-by: Lokesh Jain Co-authored-by: Pritish Budhiraja <77892330+PritishBudhiraja@users.noreply.github.com> Co-authored-by: Jeeva Ramachandran <120017870+JeevaRamu0104@users.noreply.github.com> --- package.json | 16 +++------ src/components/LoadedTable.res | 2 +- src/components/Loader.res | 13 ++++--- .../hyperswitch/HyperSwitchApp.res | 2 +- tests/bsconfig.json | 34 ------------------- tests/marketplace/unit_test/InitTest.res | 13 ------- webpack.common.js | 15 +------- 7 files changed, 14 insertions(+), 81 deletions(-) delete mode 100644 tests/bsconfig.json delete mode 100644 tests/marketplace/unit_test/InitTest.res diff --git a/package.json b/package.json index 8329a0739..4e94eab64 100644 --- a/package.json +++ b/package.json @@ -5,24 +5,18 @@ "author": "Shiva Nandan ", "license": "MIT", "scripts": { + "setup-env": "chmod +x ./replace_env.sh && ./replace_env.sh", "pre-commit": "bash .githooks/commit-msg", - "start": "chmod +x ./replace_env.sh && ./replace_env.sh && cp env-config.js ./public/hyperswitch && APP_VERSION=$npm_package_version && appName=hyperswitch webpack serve --config webpack.dev.js", - "start:server_compiler": "webpack --config webpack.server.js --watch", + "start": "npm run setup-env && cp env-config.js ./public/hyperswitch && APP_VERSION=$npm_package_version && appName=hyperswitch webpack serve --config webpack.dev.js", + "serve": "npm run setup-env && cp env-config.js ./dist/hyperswitch && node dist/server/server.js", "prod:start": "webpack serve --config webpack.dev.js", - "build:prod": "chmod +x ./replace_env.sh && ./replace_env.sh && cp env-config.js ./public/hyperswitch && APP_VERSION=$npm_package_version && webpack --config webpack.prod.js", - "ssr_sript_build": "BRANCH_NAME=ssr webpack --config webpack.prod.js", - "ssr_run_server": "node --watch dist/server/server.js", "build:netlify": "webpack --config webpack.prod.js --env netlifyHosted", + "build:test": "cd tests && npx rescript build -with-deps", + "build:prod": "npm run setup-env && cp env-config.js ./public/hyperswitch && APP_VERSION=$npm_package_version && webpack --config webpack.prod.js", "re:build": "rescript", "re:clean": "rescript clean", "re:start": "rescript build -w", "re:format": "rescript format -all", - "use-prod-ec": "mv public/_redirects_for_prod public/_redirects", - "serve": "chmod +x ./replace_env.sh && ./replace_env.sh && cp env-config.js ./dist/hyperswitch && node dist/server/server.js", - "build:test": "cd tests && npx rescript build -with-deps", - "clean:test": "cd tests && npx rescript clean -with-deps", - "unit:test": "cd tests && npx rescript build -with-deps && jest unit_test", - "revert:test": "cd tests && npx rescript clean -with-deps && cd .. && npx rescript build -with-deps", "postinstall": "git config core.hooksPath .githooks && chmod +x .githooks/commit-msg" }, "husky": { diff --git a/src/components/LoadedTable.res b/src/components/LoadedTable.res index e7380840a..06ba7fd10 100644 --- a/src/components/LoadedTable.res +++ b/src/components/LoadedTable.res @@ -774,7 +774,7 @@ let make = ( ? "" : `${isMinHeightRequired ? noScrollbar ? "" : "overflow-x-scroll" : "overflow-scroll"}` let loadedTable = -
+
{switch dataView { | Table => { let children = diff --git a/src/components/Loader.res b/src/components/Loader.res index 5ed36be52..cbf78e93b 100644 --- a/src/components/Loader.res +++ b/src/components/Loader.res @@ -25,20 +25,19 @@ let make = (
- {React.string(loadingText)} {children}
-
- - + + +
- - -
+
+ +
diff --git a/src/entryPoints/hyperswitch/HyperSwitchApp.res b/src/entryPoints/hyperswitch/HyperSwitchApp.res index 40bfc27a9..ba84d8950 100644 --- a/src/entryPoints/hyperswitch/HyperSwitchApp.res +++ b/src/entryPoints/hyperswitch/HyperSwitchApp.res @@ -229,7 +229,7 @@ let make = () => {
+ className="w-full h-screen overflow-x-scroll xl:overflow-x-hidden overflow-y-scroll">
diff --git a/tests/bsconfig.json b/tests/bsconfig.json deleted file mode 100644 index a0c7873e6..000000000 --- a/tests/bsconfig.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "editor-ui", - "jsx": { - "version": 4, - "mode": "classic" - }, - "bsc-flags": ["-bs-super-errors"], - "sources": [ - { - "dir": "../src", - "subdirs": true - }, - { - "dir": "../tests", - "subdirs": true, - "type": "dev" - } - ], - "suffix": ".bs.js", - "namespace": true, - "ppx-flags": [], - "package-specs": { - "module": "commonjs", - "in-source": true - }, - "bs-dev-dependencies": ["@glennsl/rescript-jest"], - "bs-dependencies": [ - "@rescript/react", - "rescript-webapi", - "bs-fetch", - "@ryyppy/rescript-promise", - "rescript-debounce-react" - ] -} diff --git a/tests/marketplace/unit_test/InitTest.res b/tests/marketplace/unit_test/InitTest.res deleted file mode 100644 index 76f513b3d..000000000 --- a/tests/marketplace/unit_test/InitTest.res +++ /dev/null @@ -1,13 +0,0 @@ -open Jest -open Expect - -let () = { - describe("Test", () => { - let expectedValue = "test" - let actualValue = "test" - - test("Test", () => { - expect(actualValue)->toEqual(expectedValue) - }) - }) -} diff --git a/webpack.common.js b/webpack.common.js index 687b6dd56..966c1a507 100644 --- a/webpack.common.js +++ b/webpack.common.js @@ -6,23 +6,10 @@ const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin" const tailwindcss = require("tailwindcss"); const MonacoWebpackPlugin = require("monaco-editor-webpack-plugin"); -const appEntryPoint = { - hyperswitch: "hyperswitch/HyperSwitchEntry", -}; - -function getAppEntryPoint(appName) { - const path = appEntryPoint[appName]; - if (path) { - return `./src/entryPoints/${path}.bs.js`; - } else { - return undefined; - } -} - module.exports = (appName = "hyperswitch", publicPath = "auto") => { const isDevelopment = process.env.NODE_ENV !== "production"; let entryObj = { - app: getAppEntryPoint(appName), + app: `./src/entryPoints/hyperswitch/HyperSwitchEntry.bs.js`, }; return { entry: entryObj, From b220415bc390a5129e82e1b59dc6115a35cb6f84 Mon Sep 17 00:00:00 2001 From: Pritish Budhiraja <77892330+PritishBudhiraja@users.noreply.github.com> Date: Tue, 5 Dec 2023 13:24:35 +0530 Subject: [PATCH 21/27] chore: dead code removal (#55) Co-authored-by: Jeeva Ramachandran <120017870+JeevaRamu0104@users.noreply.github.com> Co-authored-by: Jeeva Ramachandran Co-authored-by: Riddhiagrawal001 <50551695+Riddhiagrawal001@users.noreply.github.com> Co-authored-by: Riddhi Agrawal Co-authored-by: Lokesh Jain <56452497+jainlokesh318@users.noreply.github.com> Co-authored-by: Lokesh Jain --- README.md | 8 - config/FeatureFlag.json | 2 - .../hyperswitch/FeatureFlagUtils.res | 4 - .../hyperswitch/HyperSwitchEntry.res | 4 +- src/entryPoints/hyperswitch/SidebarValues.res | 2 +- .../Analytics/HSAnalyticsUtils.res | 6 +- .../HyperSwitch/Developer/DeveloperUtils.res | 16 +- .../HyperSwitch/Developer/Webhooks.res | 2 +- src/screens/HyperSwitch/HSwitchUtils.res | 151 ------------------ .../HSwitchSandboxOnboarding/CodeSnippets.res | 52 ------ .../UserOnboarding.res | 3 - .../HyperSwitch/Settings/BusinessDetails.res | 2 +- .../BusinessMapping/BusinessMappingEntity.res | 11 -- .../Settings/HSwitchMerchantAccountUtils.res | 2 +- .../HSwitchUserManagementUtils.res | 1 - .../UserManagement/HSwitchUserRoleEntity.res | 15 -- 16 files changed, 7 insertions(+), 274 deletions(-) diff --git a/README.md b/README.md index a01f6bafd..29d5b0d3f 100644 --- a/README.md +++ b/README.md @@ -152,14 +152,6 @@ The `production_access` feature flag enables a flow for users to request live pr The `quick_start` feature flag enables the simplified onboarding flow for new users, where he connects to processors, configure payment routing and testing a payment, all in one flow. -#### Stripe plus paypal - -The `stripe_plus_paypal` feature flag enables access to simplified multi-processor connectivity through Stripe and PayPal. When turned on, users are guided through a streamlined setup flow to connect both Stripe and PayPal accounts and experience it in a checkout page. - -#### Woocommerce - -The `woocommerce` feature flag controls the visibility of WooCommerce integration with Hyperswitch flow within the dashboard. When enabled, users will have access to the step-by-step guide to integrate the woocommerce plugin for hyperswitch. - #### Open SDK The `open_sdk` feature flag enables access to the Checkout Page web SDK from within the dashboard. When enabled, developers can preview the SDK from within the dashboard and make payments. diff --git a/config/FeatureFlag.json b/config/FeatureFlag.json index 64501c151..99a695198 100644 --- a/config/FeatureFlag.json +++ b/config/FeatureFlag.json @@ -4,8 +4,6 @@ "magic_link": false, "production_access": false, "quick_start": false, - "stripe_plus_paypal": false, - "woocommerce": false, "open_sdk": false, "switch_merchant": false, "audit_trail": false, diff --git a/src/entryPoints/hyperswitch/FeatureFlagUtils.res b/src/entryPoints/hyperswitch/FeatureFlagUtils.res index 150c8cff9..30c58f237 100644 --- a/src/entryPoints/hyperswitch/FeatureFlagUtils.res +++ b/src/entryPoints/hyperswitch/FeatureFlagUtils.res @@ -4,8 +4,6 @@ type featureFlag = { testLiveToggle: bool, magicLink: bool, quickStart: bool, - stripePlusPayPal: bool, - wooCommerce: bool, openSDK: bool, switchMerchant: bool, testLiveMode: option, @@ -34,8 +32,6 @@ let featureFlagType = (featureFlags: Js.Json.t) => { testLiveToggle: dict->getBool("test_live_toggle", false), magicLink: dict->getBool("magic_link", false), quickStart: dict->getBool("quick_start", false), - stripePlusPayPal: dict->getBool("stripe_plus_paypal", false), - wooCommerce: dict->getBool("woocommerce", false), openSDK: dict->getBool("open_sdk", false), switchMerchant: dict->getBool("switch_merchant", false), testLiveMode: dict->getOptionBool("test_live_mode"), diff --git a/src/entryPoints/hyperswitch/HyperSwitchEntry.res b/src/entryPoints/hyperswitch/HyperSwitchEntry.res index 29c8550bd..08f76fcd6 100644 --- a/src/entryPoints/hyperswitch/HyperSwitchEntry.res +++ b/src/entryPoints/hyperswitch/HyperSwitchEntry.res @@ -75,9 +75,7 @@ module HyperSwitchEntryComponent = { (await postDetails(url, Js.Dict.empty()->Js.Json.object_, Post))->Js.Json.stringify setFeatureFlag(._ => stringifiedResponse) } catch { - | Js.Exn.Error(e) => { - let _err = Js.Exn.message(e)->Belt.Option.getWithDefault("Failed to Fetch!") - } + | _ => () } } diff --git a/src/entryPoints/hyperswitch/SidebarValues.res b/src/entryPoints/hyperswitch/SidebarValues.res index 679aead89..f4783826b 100644 --- a/src/entryPoints/hyperswitch/SidebarValues.res +++ b/src/entryPoints/hyperswitch/SidebarValues.res @@ -303,7 +303,7 @@ let reconTag = (recon, isReconEnabled) => : emptyComponent let getHyperSwitchAppSidebars = ( - ~isReconEnabled=false, + ~isReconEnabled: bool, ~featureFlagDetails: FeatureFlagUtils.featureFlag, ~userRole, (), diff --git a/src/screens/HyperSwitch/Analytics/HSAnalyticsUtils.res b/src/screens/HyperSwitch/Analytics/HSAnalyticsUtils.res index 44ea205b3..516800622 100644 --- a/src/screens/HyperSwitch/Analytics/HSAnalyticsUtils.res +++ b/src/screens/HyperSwitch/Analytics/HSAnalyticsUtils.res @@ -174,10 +174,6 @@ let getStringListFromArrayDict = metrics => { metrics->Js.Array2.map(item => item->getDictFromJsonObject->getString("name", "")) } -let getCustomFormattedFloatDate = (floatDate, format) => { - floatDate->Js.Date.fromFloat->Js.Date.toISOString->Table.dateFormat(format) -} - module NoData = { @react.component let make = (~title, ~subTitle) => { @@ -209,7 +205,7 @@ let generateTablePayload = ( ~isIndustry: bool, ~mode: option, ~customFilter, - ~showDeltaMetrics=false, + ~showDeltaMetrics, ~moduleName as _: string, ~source: string="BATCH", (), diff --git a/src/screens/HyperSwitch/Developer/DeveloperUtils.res b/src/screens/HyperSwitch/Developer/DeveloperUtils.res index 9b366d562..b0701f9b3 100644 --- a/src/screens/HyperSwitch/Developer/DeveloperUtils.res +++ b/src/screens/HyperSwitch/Developer/DeveloperUtils.res @@ -1,22 +1,10 @@ open HSwitchSettingTypes -let titleClass = "md:font-bold font-semibold md:text-fs-16 text-fs-13 text-jp-gray-900 text-opacity-75 dark:text-white dark:text-opacity-75" - -let paymentsEvents = ["succeeded", "failed", "processing", "action_required"] -let refundsEvents = ["succeeded", "failed"] -let disputesEvents = ["opened", "expired", "accepted", "cancelled", "challenged", "won", "lost"] - -let webhookEventsDict = - [ - ("payment", paymentsEvents->Js.Array2.map(Js.Json.string)->Js.Json.array), - ("refund", refundsEvents->Js.Array2.map(Js.Json.string)->Js.Json.array), - ("dispute", disputesEvents->Js.Array2.map(Js.Json.string)->Js.Json.array), - ]->Js.Dict.fromArray let validateAPIKeyForm = ( values: Js.Json.t, ~setIsDisabled=_ => (), keys: array, - ~setShowCustomDate=_ => (), + ~setShowCustomDate, (), ) => { let errors = Js.Dict.empty() @@ -81,7 +69,6 @@ let getRecordTypeFromString = value => { type apiKey = { key_id: string, - merchant_id: string, name: string, description: string, prefix: string, @@ -93,7 +80,6 @@ type apiKey = { let itemToObjMapper = dict => { open LogicUtils { - merchant_id: getString(dict, "merchant_id", ""), key_id: getString(dict, "key_id", ""), name: getString(dict, "name", ""), description: getString(dict, "description", ""), diff --git a/src/screens/HyperSwitch/Developer/Webhooks.res b/src/screens/HyperSwitch/Developer/Webhooks.res index 35685e3d7..8859c8995 100644 --- a/src/screens/HyperSwitch/Developer/Webhooks.res +++ b/src/screens/HyperSwitch/Developer/Webhooks.res @@ -71,7 +71,7 @@ let make = (~webhookOnly=false, ~showFormOnly=false, ~profileId="") => { open HSwitchSettingTypes HSwitchMerchantAccountUtils.validateMerchantAccountForm( ~values, - ~setIsDisabled, + ~setIsDisabled=Some(setIsDisabled), ~fieldsToValidate={ [WebhookUrl, ReturnUrl]->Js.Array2.filter(urlField => urlField === WebhookUrl || !webhookOnly diff --git a/src/screens/HyperSwitch/HSwitchUtils.res b/src/screens/HyperSwitch/HSwitchUtils.res index 68048672a..3e704b363 100644 --- a/src/screens/HyperSwitch/HSwitchUtils.res +++ b/src/screens/HyperSwitch/HSwitchUtils.res @@ -92,95 +92,6 @@ module ConnectorCustomCell = { } } } -module HelpDeskSection = { - @react.component - let make = (~helpdeskModal, ~setHelpdeskModal) => { - let hyperswitchMixPanel = HSMixPanel.useSendEvent() - let url = RescriptReactRouter.useUrl() - let textStyle = "font-medium text-fs-14" - let {setShowFeedbackModal} = React.useContext(GlobalProvider.defaultContext) - let handleMixpanelEvents = eventName => { - [url.path->LogicUtils.getListHead, `global`]->Js.Array2.forEach(ele => - hyperswitchMixPanel(~pageName=ele, ~contextName="helpdesk", ~actionName=eventName, ()) - ) - } - let handleFeedbackClicked = _ => { - setShowFeedbackModal(_ => true) - "submitfeedback"->handleMixpanelEvents - } - - let hoverEffectStyle = "flex gap-3 cursor-pointer hover:border hover:border-blue-700 hover:rounded-md hover:!shadow-[0_0_4px_2px_rgba(0,_112,_255,_0.15)] p-3 border border-transparent" - <> - - -
handleFeedbackClicked()}> - -

{"Submit feedback"->React.string}

-
-
{ - "contactonslack"->handleMixpanelEvents - Window._open("https://hyperswitch-io.slack.com/ssb/redirect") - }}> - -

{"Connect on Slack"->React.string}

-
-
{ - "joindiscord"->handleMixpanelEvents - Window._open("https://discord.gg/an7gRdWkhw") - }}> - -

{"Join Discord"->React.string}

-
-
-
- { - open ReactEvent.Mouse - ev->stopPropagation - setHelpdeskModal(prevValue => { - let globalEventText = !prevValue ? "global_helpdesk_open" : "global_helpdesk_close" - let localEventText = !prevValue ? "helpdesk_open" : "helpdesk_close" - let currentPath = url.path->LogicUtils.getListHead - - [`${currentPath}_${localEventText}`, globalEventText]->Js.Array2.forEach(ele => - hyperswitchMixPanel(~eventName=Some(ele), ()) - ) - !prevValue - }) - }} - /> - - } -} - -let pathToVariantMapper = routeName => { - switch routeName { - | "home" => HOME - | "payments" => PAYMENTS - | "refunds" => REFUNDS - | "disputes" => DISPUTES - | "connectors" => CONNECTOR - | "routing" => ROUTING - | "analytics-payments" => ANALYTICS_PAYMENTS - | "analytics-refunds" => ANALYTICS_REFUNDS - | "settings" => SETTINGS - | "developers" => DEVELOPERS - | _ => HOME - } -} let isValidEmail = value => !Js.Re.test_( @@ -188,15 +99,6 @@ let isValidEmail = value => value, ) -let isUserJourneyAnalyticsAccessAvailable = email => email->Js.String2.includes("juspay") - -let convertJsonArrayToArrayOfString = (. val) => { - val - ->Js.Json.decodeArray - ->Belt.Option.getWithDefault([]) - ->Js.Array2.map(ele => ele->Js.Json.decodeString->Belt.Option.getWithDefault("")) -} - let useMerchantDetailsValue = () => Recoil.useRecoilValueFromAtom(merchantDetailsValueAtom)->safeParse @@ -382,49 +284,9 @@ let constructOnboardingBody = ( ("account_activation", copyOfIntegrationDetails.account_activation->returnIntegrationJson), ])->Js.Json.object_ } -module OnboardingChecklistTile = { - @react.component - let make = (~setShowOnboardingModal) => { - let hyperswitchMixPanel = HSMixPanel.useSendEvent() - let url = RescriptReactRouter.useUrl() -
{ - setShowOnboardingModal(_ => true) - - [url.path->LogicUtils.getListHead, "global"]->Js.Array2.forEach(ele => - hyperswitchMixPanel(~eventName=Some(`${ele}_onboarding_checklist`), ()) - ) - }}> -
-
{"Onboarding Checklist"->React.string}
- - - - -
- -
- } -} let isEmptyString = str => str->Js.String2.length <= 0 -let parseUrl = url => { - url - ->Js.Global.decodeURI - ->Js.String2.split("&") - ->Belt.Array.keepMap(str => { - let arr = str->Js.String2.split("=") - let key = arr->Belt.Array.get(0)->Belt.Option.getWithDefault("-") - let val = arr->Belt.Array.sliceToEnd(1)->Js.Array2.joinWith("=") - key === "" || val === "" ? None : Some((key, val)) - }) - ->Js.Dict.fromArray -} - type textVariantType = | H1 | H2 @@ -453,19 +315,6 @@ let getTextClass = (~textVariant, ~h3TextVariant=Leading_1, ~paragraphTextVarian } } -module CardLoader = { - @react.component - let make = () => { -
-
-
- -
-
-
- } -} - let checkStripePlusPayPal = (enumDetails: QuickStartTypes.responseType) => { enumDetails.stripeConnected.processorID->Js.String2.length > 0 && enumDetails.paypalConnected.processorID->Js.String2.length > 0 && diff --git a/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/CodeSnippets.res b/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/CodeSnippets.res index 173d9658c..aa89ea871 100644 --- a/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/CodeSnippets.res +++ b/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/CodeSnippets.res @@ -733,55 +733,3 @@ app.post("/create-payment", async (req, res) => { }); app.listen(4242, () => console.log("Node server listening on port 4242!"));` - -let reactDisplayPaymentConfirmation: string = `const handleSubmit = async (e) => { - e.preventDefault(); - if (!hyper || !widgets) { - // hyper-js has not yet loaded. - // Make sure to disable form submission until hyper-js has loaded. - return; - } - setIsLoading(true); - const { error } = await hyper.confirmPayment({ - widgets, - confirmParams: { - // Make sure to change this to your payment completion page - return_url: "https://example.com/complete", - }, - }); - // This point will only be reached if there is an immediate error occurring while confirming the payment. Otherwise, your customer will be redirected to your "return_url" - // For some payment flows such as Sofort, iDEAL, your customer will be redirected to an intermediate page to complete authorization of the payment, and then redirected to the "return_url". - if (error.type === "validation_error") { - setMessage(error.message); - } else { - setMessage("An unexpected error occurred."); - } - setIsLoading(false); -};` - -let nodeDisplayPaymentConfirmation: string = `//Look for a parameter called "payment_intent_client_secret" in the url which gives a payment ID, which is then used to retrieve the status of the payment - -const paymentID = new URLSearchParams(window.location.search).get( - "payment_intent_client_secret" -); - -if (!paymentID) { - return; -} - -hyper.retrievePaymentIntent(paymentID).then(({ paymentIntent }) => { - switch (paymentIntent.status) { - case "succeeded": - setMessage("Payment succeeded!"); - break; - case "processing": - setMessage("Your payment is processing."); - break; - case "requires_payment_method": - setMessage("Your payment was not successful, please try again."); - break; - default: - setMessage("Something went wrong."); - break; - } -});` diff --git a/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/UserOnboarding.res b/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/UserOnboarding.res index e3a384156..b1207806f 100644 --- a/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/UserOnboarding.res +++ b/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/UserOnboarding.res @@ -1,6 +1,3 @@ -let headerTextCss = "font-semibold text-grey-700 text-xl" -let subTextCss = "font-normal text-grey-700 opacity-50 text-base" - let buildHyperswitch: array = [ { headerIcon: "migrate-from-stripe", diff --git a/src/screens/HyperSwitch/Settings/BusinessDetails.res b/src/screens/HyperSwitch/Settings/BusinessDetails.res index 0d1daf80e..2db63dcb1 100644 --- a/src/screens/HyperSwitch/Settings/BusinessDetails.res +++ b/src/screens/HyperSwitch/Settings/BusinessDetails.res @@ -133,7 +133,7 @@ let make = () => { validateMerchantAccountForm( ~values, ~fieldsToValidate=[PrimaryPhone, PrimaryEmail, Website, SecondaryEmail, SecondaryPhone], - ~setIsDisabled, + ~setIsDisabled=Some(setIsDisabled), ~initialData={merchantInfo->Js.Json.object_}, ) }}> diff --git a/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessMappingEntity.res b/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessMappingEntity.res index 425b75fb8..2a585cacb 100644 --- a/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessMappingEntity.res +++ b/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessMappingEntity.res @@ -51,17 +51,6 @@ let getItems: Js.Json.t => array = json => { LogicUtils.getArrayDataFromJson(json, itemToObjMapper) } -let apiKeysTableEntity = EntityType.makeEntity( - ~uri="", - ~getObjects=getItems, - ~defaultColumns, - ~allColumns, - ~getHeading, - ~dataKey="", - ~getCell, - (), -) - let businessProfileTabelEntity = showLink => EntityType.makeEntity( ~uri="", diff --git a/src/screens/HyperSwitch/Settings/HSwitchMerchantAccountUtils.res b/src/screens/HyperSwitch/Settings/HSwitchMerchantAccountUtils.res index ac05ee285..42fceaaae 100644 --- a/src/screens/HyperSwitch/Settings/HSwitchMerchantAccountUtils.res +++ b/src/screens/HyperSwitch/Settings/HSwitchMerchantAccountUtils.res @@ -396,7 +396,7 @@ let validateCustom = (key, errors, value) => { let validateMerchantAccountForm = ( ~values: Js.Json.t, ~fieldsToValidate: array, - ~setIsDisabled=?, + ~setIsDisabled, ~initialData, ) => { let errors = Js.Dict.empty() diff --git a/src/screens/HyperSwitch/UserManagement/HSwitchUserManagementUtils.res b/src/screens/HyperSwitch/UserManagement/HSwitchUserManagementUtils.res index b4ed31ea3..c1e09ca0b 100644 --- a/src/screens/HyperSwitch/UserManagement/HSwitchUserManagementUtils.res +++ b/src/screens/HyperSwitch/UserManagement/HSwitchUserManagementUtils.res @@ -156,7 +156,6 @@ let roleListResponseMapper: Js.Dict.t< > => HSwitchUserRoleEntity.roleListResponse = dict => { open LogicUtils { - permissions: dict->getStrArray("permissions"), role_id: dict->getString("role_id", ""), role_name: dict->getString("role_name", ""), } diff --git a/src/screens/HyperSwitch/UserManagement/HSwitchUserRoleEntity.res b/src/screens/HyperSwitch/UserManagement/HSwitchUserRoleEntity.res index 23afdc956..f362e2413 100644 --- a/src/screens/HyperSwitch/UserManagement/HSwitchUserRoleEntity.res +++ b/src/screens/HyperSwitch/UserManagement/HSwitchUserRoleEntity.res @@ -7,7 +7,6 @@ type userStatus = Active | InviteSent | None type userTableTypes = { user_id: string, email: string, - last_modified_at: string, name: string, role_id: string, role_name: string, @@ -39,17 +38,10 @@ let itemToObjMapperForUser = dict => { role_id: getString(dict, "role_id", ""), role_name: getString(dict, "role_name", ""), status: getString(dict, "status", ""), - last_modified_at: getString(dict, "last_modified_at", ""), } } -type roleTableTypes = { - permissions: array, - role_id: string, -} - type roleListResponse = { - permissions: array, role_id: string, role_name: string, } @@ -63,13 +55,6 @@ let getHeadingForUser = (colType: userColTypes) => { } } -let itemToObjMapperForRole = dict => { - { - permissions: dict->getStrArray("permissions"), - role_id: dict->getString("role_id", ""), - } -} - let roleToVariantMapper = role => { switch role->Js.String2.toUpperCase { | "ADMIN" => Admin From 0f846c02bc4002367bab8f398adf81aaded91e16 Mon Sep 17 00:00:00 2001 From: Riddhi Agrawal Date: Tue, 5 Dec 2023 15:03:35 +0530 Subject: [PATCH 22/27] fix: validations issue fix + 3ds keys updated --- public/hyperswitch/module.js | 8 ++++++ src/components/MakeRuleFieldComponent.res | 18 ++++++------- src/libraries/Window.res | 3 +++ .../HyperSwitch/Routing/RoutingUtils.res | 26 ++++++++++++++++++- .../RoutingRevamp/AdvancedRouting.res | 8 +++--- .../RoutingRevamp/AdvancedRoutingUIUtils.res | 7 ++--- .../ThreeDSFlow/HSwitchThreeDS.res | 2 +- 7 files changed, 53 insertions(+), 19 deletions(-) diff --git a/public/hyperswitch/module.js b/public/hyperswitch/module.js index d5143e314..c2ebfc248 100644 --- a/public/hyperswitch/module.js +++ b/public/hyperswitch/module.js @@ -62,3 +62,11 @@ function getParsedJson(str) { throw e; } } + +function getThreeDsKeys() { + if (wasm) { + return wasm.getThreeDsKeys(); + } else { + return []; + } +} diff --git a/src/components/MakeRuleFieldComponent.res b/src/components/MakeRuleFieldComponent.res index f53de64e7..82d779019 100644 --- a/src/components/MakeRuleFieldComponent.res +++ b/src/components/MakeRuleFieldComponent.res @@ -2,24 +2,22 @@ external strToFormEvent: Js.String.t => ReactEvent.Form.t = "%identity" let validateConditionJson = json => { open LogicUtils let checkValue = dict => { - let valueFromObject = dict->getDictfromDict("value") - - valueFromObject + dict ->getArrayFromDict("value", []) ->Js.Array2.filter(ele => { ele != ""->Js.Json.string }) ->Js.Array2.length > 0 || - valueFromObject->getString("value", "") !== "" || - valueFromObject->getFloat("value", -1.0) !== -1.0 || - valueFromObject->getString("comparison", "") == "IS NULL" || - valueFromObject->getString("comparison", "") == "IS NOT NULL" + dict->getString("value", "") !== "" || + dict->getFloat("value", -1.0) !== -1.0 || + dict->getString("operator", "") == "IS NULL" || + dict->getString("operator", "") == "IS NOT NULL" } - switch json->Js.Json.decodeObject { | Some(dict) => - ["comparison", "lhs"]->Js.Array2.every(key => dict->Js.Dict.get(key)->Belt.Option.isSome) && - dict->checkValue + ["operator", "real_field"]->Js.Array2.every(key => + dict->Js.Dict.get(key)->Belt.Option.isSome + ) && dict->checkValue | None => false } } diff --git a/src/libraries/Window.res b/src/libraries/Window.res index 8a326afbb..4c6514868 100644 --- a/src/libraries/Window.res +++ b/src/libraries/Window.res @@ -38,6 +38,9 @@ external getConnectorConfig: string => Js.Json.t = "getConnectorConfig" @val @scope("window") external getPayoutConnectorConfig: string => Js.Json.t = "getPayoutConnectorConfig" +@val @scope("window") +external getThreeDsKeys: unit => array = "getThreeDsKeys" + @val @scope("window") open ConnectorTypes external getRequestPayload: (wasmRequest, wasmExtraPayload) => Js.Json.t = "getRequestPayload" diff --git a/src/screens/HyperSwitch/Routing/RoutingUtils.res b/src/screens/HyperSwitch/Routing/RoutingUtils.res index b3ad9c285..8cf4a6b0f 100644 --- a/src/screens/HyperSwitch/Routing/RoutingUtils.res +++ b/src/screens/HyperSwitch/Routing/RoutingUtils.res @@ -688,6 +688,30 @@ let validateNameAndDescription = (~dict, ~errors) => { }) } +let validateConditionJsonFor3ds = json => { + let checkValue = dict => { + let valueFromObject = dict->getDictfromDict("value") + + valueFromObject + ->getArrayFromDict("value", []) + ->Js.Array2.filter(ele => { + ele != ""->Js.Json.string + }) + ->Js.Array2.length > 0 || + valueFromObject->getString("value", "") !== "" || + valueFromObject->getFloat("value", -1.0) !== -1.0 || + valueFromObject->getString("comparison", "") == "IS NULL" || + valueFromObject->getString("comparison", "") == "IS NOT NULL" + } + + switch json->Js.Json.decodeObject { + | Some(dict) => + ["comparison", "lhs"]->Js.Array2.every(key => dict->Js.Dict.get(key)->Belt.Option.isSome) && + dict->checkValue + | None => false + } +} + let validateConditions = dict => { dict ->LogicUtils.getArrayFromDict("conditions", []) @@ -699,7 +723,7 @@ let validateConditionsEvenIfOneExists = dict => { let vector = Js.Vector.make(conditionsArray->Js.Array2.length, false) conditionsArray->Array.forEachWithIndex((value, index) => { - let res = value->MakeRuleFieldComponent.validateConditionJson + let res = value->validateConditionJsonFor3ds vector->Js.Vector.set(index, res) }) diff --git a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res index 65d7a4209..b147f8b23 100644 --- a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res +++ b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRouting.res @@ -91,7 +91,7 @@ module Wrapper = { ~notFirstRule=true, ~isDragging=false, ~wasm, - ~isfrom3ds=false, + ~isFrom3ds=false, ) => { let showToast = ToastState.useShowToast() let isMobileView = MatchMedia.useMobileChecker() @@ -221,12 +221,12 @@ module Wrapper = { ${border} border-blue-700`}> - + - + - +
diff --git a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res index 48c1b2341..9866d6621 100644 --- a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res +++ b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res @@ -318,7 +318,7 @@ module FieldInp = { module RuleFieldBase = { @react.component - let make = (~isFirst, ~id, ~isExpanded, ~onClick, ~wasm) => { + let make = (~isFirst, ~id, ~isExpanded, ~onClick, ~wasm, ~isFrom3ds) => { let (hover, setHover) = React.useState(_ => false) let (paymentMethod, setpaymentMethod) = React.useState(_ => []) let (keyType, setKeyType) = React.useState(_ => "") @@ -341,7 +341,7 @@ module RuleFieldBase = { React.useEffect0(() => { let methodKeys = switch wasm { - | Some(res) => res.getAllKeys() + | Some(res) => isFrom3ds ? Window.getThreeDsKeys() : res.getAllKeys() | None => [] } let value = field.value->LogicUtils.getStringFromJson("") @@ -394,7 +394,7 @@ module RuleFieldBase = { module MakeRuleField = { @react.component - let make = (~id, ~isExpanded, ~wasm) => { + let make = (~id, ~isExpanded, ~wasm, ~isFrom3ds) => { let ruleJsonPath = `${id}.statements` let conditionsInput = ReactFinalForm.useField(ruleJsonPath).input let fields = conditionsInput.value->Js.Json.decodeArray->Belt.Option.getWithDefault([]) @@ -419,6 +419,7 @@ module MakeRuleField = { id={`${ruleJsonPath}[${i->Belt.Int.toString}]`} isExpanded wasm + isFrom3ds /> )->React.array} {if isExpanded { diff --git a/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res b/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res index 9eecdbd8d..0398d7bcb 100644 --- a/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res +++ b/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res @@ -75,7 +75,7 @@ module Configure3DSRule = { notFirstRule isDragging wasm - isfrom3ds=true + isFrom3ds=true /> } if notFirstRule { From c6f72e478eec317c868ed000dfd931e4c837c9cb Mon Sep 17 00:00:00 2001 From: Riddhi Agrawal Date: Tue, 5 Dec 2023 15:19:54 +0530 Subject: [PATCH 23/27] fix: added wasm functions to window --- public/hyperswitch/module.js | 32 +++++++++++++++++++ src/libraries/Window.res | 12 +++++++ .../RoutingRevamp/AdvancedRoutingUIUtils.res | 7 ++-- 3 files changed, 48 insertions(+), 3 deletions(-) diff --git a/public/hyperswitch/module.js b/public/hyperswitch/module.js index c2ebfc248..d54684e76 100644 --- a/public/hyperswitch/module.js +++ b/public/hyperswitch/module.js @@ -70,3 +70,35 @@ function getThreeDsKeys() { return []; } } + +function getAllKeys() { + if (wasm) { + return wasm.getAllKeys(); + } else { + return []; + } +} + +function getKeyType(str) { + if (wasm) { + return wasm.getKeyType(str); + } else { + return ""; + } +} + +function getAllConnectors() { + if (wasm) { + return wasm.getAllConnectors(); + } else { + return []; + } +} + +function getVariantValues(str) { + if (wasm) { + return wasm.getVariantValues(str); + } else { + return []; + } +} \ No newline at end of file diff --git a/src/libraries/Window.res b/src/libraries/Window.res index 4c6514868..211d31224 100644 --- a/src/libraries/Window.res +++ b/src/libraries/Window.res @@ -41,6 +41,18 @@ external getPayoutConnectorConfig: string => Js.Json.t = "getPayoutConnectorConf @val @scope("window") external getThreeDsKeys: unit => array = "getThreeDsKeys" +@val @scope("window") +external getAllKeys: unit => array = "getAllKeys" + +@val @scope("window") +external getKeyType: string => string = "getKeyType" + +@val @scope("window") +external getAllConnectors: unit => array = "getAllConnectors" + +@val @scope("window") +external getVariantValues: string => array = "getVariantValues" + @val @scope("window") open ConnectorTypes external getRequestPayload: (wasmRequest, wasmExtraPayload) => Js.Json.t = "getRequestPayload" diff --git a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res index 9866d6621..efbc7d3e8 100644 --- a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res +++ b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res @@ -340,9 +340,10 @@ module RuleFieldBase = { } React.useEffect0(() => { - let methodKeys = switch wasm { - | Some(res) => isFrom3ds ? Window.getThreeDsKeys() : res.getAllKeys() - | None => [] + let methodKeys = if isFrom3ds { + Window.getThreeDsKeys() + } else { + Window.getAllKeys() } let value = field.value->LogicUtils.getStringFromJson("") if value->Js.String2.length > 0 { From 34614ad8890a64e22e4352fc27fd030b0d81e72e Mon Sep 17 00:00:00 2001 From: Riddhi Agrawal Date: Tue, 5 Dec 2023 15:47:13 +0530 Subject: [PATCH 24/27] fix: comments addressed --- .../HyperSwitch/Routing/RoutingUtils.res | 31 +++++++++---------- .../RoutingRevamp/AdvancedRoutingUIUtils.res | 19 +++++------- .../RoutingRevamp/AdvancedRoutingUtils.res | 21 ++++++------- 3 files changed, 33 insertions(+), 38 deletions(-) diff --git a/src/screens/HyperSwitch/Routing/RoutingUtils.res b/src/screens/HyperSwitch/Routing/RoutingUtils.res index 8cf4a6b0f..79d419daa 100644 --- a/src/screens/HyperSwitch/Routing/RoutingUtils.res +++ b/src/screens/HyperSwitch/Routing/RoutingUtils.res @@ -688,26 +688,25 @@ let validateNameAndDescription = (~dict, ~errors) => { }) } -let validateConditionJsonFor3ds = json => { - let checkValue = dict => { - let valueFromObject = dict->getDictfromDict("value") - - valueFromObject - ->getArrayFromDict("value", []) - ->Js.Array2.filter(ele => { - ele != ""->Js.Json.string - }) - ->Js.Array2.length > 0 || - valueFromObject->getString("value", "") !== "" || - valueFromObject->getFloat("value", -1.0) !== -1.0 || - valueFromObject->getString("comparison", "") == "IS NULL" || - valueFromObject->getString("comparison", "") == "IS NOT NULL" - } +let checkIfValuePresent = dict => { + let valueFromObject = dict->getDictfromDict("value") + valueFromObject + ->getArrayFromDict("value", []) + ->Js.Array2.filter(ele => { + ele != ""->Js.Json.string + }) + ->Js.Array2.length > 0 || + valueFromObject->getString("value", "") !== "" || + valueFromObject->getFloat("value", -1.0) !== -1.0 || + valueFromObject->getString("comparison", "") == "IS NULL" || + valueFromObject->getString("comparison", "") == "IS NOT NULL" +} +let validateConditionJsonFor3ds = json => { switch json->Js.Json.decodeObject { | Some(dict) => ["comparison", "lhs"]->Js.Array2.every(key => dict->Js.Dict.get(key)->Belt.Option.isSome) && - dict->checkValue + dict->checkIfValuePresent | None => false } } diff --git a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res index efbc7d3e8..28e1d3092 100644 --- a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res +++ b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res @@ -320,7 +320,6 @@ module RuleFieldBase = { @react.component let make = (~isFirst, ~id, ~isExpanded, ~onClick, ~wasm, ~isFrom3ds) => { let (hover, setHover) = React.useState(_ => false) - let (paymentMethod, setpaymentMethod) = React.useState(_ => []) let (keyType, setKeyType) = React.useState(_ => "") let (variantValues, setVariantValues) = React.useState(_ => []) let field = ReactFinalForm.useField(`${id}.lhs`).input @@ -339,21 +338,19 @@ module RuleFieldBase = { setKeyTypeAndVariants(wasm, value) } - React.useEffect0(() => { - let methodKeys = if isFrom3ds { - Window.getThreeDsKeys() - } else { - Window.getAllKeys() - } + let methodKeys = React.useMemo0(() => { let value = field.value->LogicUtils.getStringFromJson("") if value->Js.String2.length > 0 { setKeyTypeAndVariants(wasm, value) } - setpaymentMethod(_ => methodKeys) - None + if isFrom3ds { + Window.getThreeDsKeys() + } else { + Window.getAllKeys() + } }) - Js.Array2.length > 0}> + Js.Array2.length > 0}> {if isExpanded {
- +
diff --git a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res index 47f9faea6..0ddac5ce5 100644 --- a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res +++ b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res @@ -339,16 +339,15 @@ let generateStatements = statements => { }, ], (acc, statement) => { - let statementDict = statement->LogicUtils.getDictFromJsonObject - let logicalOperator = - statementDict->LogicUtils.getString("logical", "")->Js.String2.toLowerCase + let statementDict = statement->getDictFromJsonObject + let logicalOperator = statementDict->getString("logical", "")->Js.String2.toLowerCase let lastItem = acc->Belt.Array.get(acc->Js.Array2.length - 1)->Belt.Option.getWithDefault({condition: []}) let condition = { - lhs: statementDict->LogicUtils.getString("lhs", ""), - comparison: switch statementDict->LogicUtils.getString("comparison", "")->operatorMapper { + lhs: statementDict->getString("lhs", ""), + comparison: switch statementDict->getString("comparison", "")->operatorMapper { | IS | EQUAL_TO | CONTAINS => "equal" @@ -359,8 +358,8 @@ let generateStatements = statements => { | LESS_THAN => "less_than" | UnknownOperator(str) => str }, - value: statementDict->LogicUtils.getDictfromDict("value")->getStatementValue, - metadata: statementDict->LogicUtils.getJsonObjectFromDict("metadata"), + value: statementDict->getDictfromDict("value")->getStatementValue, + metadata: statementDict->getJsonObjectFromDict("metadata"), } let newAcc = if logicalOperator === "or" { @@ -383,14 +382,14 @@ let generateStatements = statements => { let generateRule = rulesDict => { let modifiedRules = rulesDict->Js.Array2.map(ruleJson => { - let ruleDict = ruleJson->LogicUtils.getDictFromJsonObject - let statements = ruleDict->LogicUtils.getArrayFromDict("statements", []) + let ruleDict = ruleJson->getDictFromJsonObject + let statements = ruleDict->getArrayFromDict("statements", []) let modifiedStatements = statements->generateStatements { - "name": ruleDict->LogicUtils.getString("name", ""), - "connectorSelection": ruleDict->LogicUtils.getJsonObjectFromDict("connectorSelection"), + "name": ruleDict->getString("name", ""), + "connectorSelection": ruleDict->getJsonObjectFromDict("connectorSelection"), "statements": modifiedStatements->Js.Array2.map(toJson)->Js.Json.array, } }) From b581e0e52cffe52e09fae06253f4ab81bdc2a4cb Mon Sep 17 00:00:00 2001 From: Riddhi Agrawal Date: Tue, 5 Dec 2023 15:57:50 +0530 Subject: [PATCH 25/27] fix: opened LogicUtils at the top of the function --- src/screens/HyperSwitch/ThreeDSFlow/ThreeDSUtils.res | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/screens/HyperSwitch/ThreeDSFlow/ThreeDSUtils.res b/src/screens/HyperSwitch/ThreeDSFlow/ThreeDSUtils.res index 1997f8c2a..dd71cc234 100644 --- a/src/screens/HyperSwitch/ThreeDSFlow/ThreeDSUtils.res +++ b/src/screens/HyperSwitch/ThreeDSFlow/ThreeDSUtils.res @@ -68,14 +68,16 @@ let constuctAlgorithmValue = rules => { } let buildThreeDsPayloadBody = values => { - let valuesDict = values->LogicUtils.getDictFromJsonObject - let dataDict = valuesDict->LogicUtils.getDictfromDict("algorithm") - let rulesDict = dataDict->LogicUtils.getArrayFromDict("rules", []) + open LogicUtils + + let valuesDict = values->getDictFromJsonObject + let dataDict = valuesDict->getDictfromDict("algorithm") + let rulesDict = dataDict->getArrayFromDict("rules", []) let modifiedRules = rulesDict->AdvancedRoutingUtils.generateRule let threeDsPayload = { - "name": valuesDict->LogicUtils.getString("name", ""), + "name": valuesDict->getString("name", ""), "algorithm": { "defaultSelection": { "override_3ds": null, From be091cabbeff1411452e92c1633404f606603c16 Mon Sep 17 00:00:00 2001 From: Riddhi Agrawal Date: Tue, 5 Dec 2023 16:15:57 +0530 Subject: [PATCH 26/27] fix: warnings removed --- .../RoutingRevamp/AdvancedRoutingUtils.res | 111 +++++++++--------- 1 file changed, 58 insertions(+), 53 deletions(-) diff --git a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res index 0ddac5ce5..d4d89ed02 100644 --- a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res +++ b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res @@ -1,12 +1,11 @@ open LogicUtils -open AdvancedRoutingTypes external toJson: 'a => Js.Json.t = "%identity" let getCurrentDetailedUTCTime = () => { Js.Date.fromFloat(Js.Date.now())->Js.Date.toUTCString } -let defaultThreeDsObjectValue = { +let defaultThreeDsObjectValue: AdvancedRoutingTypes.connectorSelection = { override_3ds: "three_ds", } @@ -98,14 +97,14 @@ let variantTypeMapper: string => AdvancedRoutingTypes.variantType = variantType } } -let getStatementValue = valueDict => { +let getStatementValue: Js.Dict.t => AdvancedRoutingTypes.value = valueDict => { { \"type": valueDict->getString("type", ""), value: valueDict->getJsonObjectFromDict("value"), } } -let statementTypeMapper = dict => { +let statementTypeMapper: Js.Dict.t => AdvancedRoutingTypes.statement = dict => { lhs: dict->getString("lhs", ""), comparison: dict->getString("comparison", ""), value: getStatementValue(dict->getDictfromDict("value")), @@ -118,12 +117,13 @@ let conditionTypeMapper = (statementArr: array) => { let arr = conditionArray->Js.Array2.mapi((conditionJson, index) => { let statementDict = conditionJson->getDictFromJsonObject - { + let returnValue: AdvancedRoutingTypes.statement = { lhs: statementDict->getString("lhs", ""), comparison: statementDict->getString("comparison", ""), logical: index === 0 ? "OR" : "AND", value: getStatementValue(statementDict->getDictfromDict("value")), } + returnValue }) acc->Js.Array2.concat(arr) }) @@ -132,6 +132,7 @@ let conditionTypeMapper = (statementArr: array) => { } let routingTypeMapper = (str: string) => { + open AdvancedRoutingTypes switch str->Js.String2.toLowerCase { | "priority" => PRIORITY | "volume_split" => VOLUME_SPLIT @@ -139,7 +140,9 @@ let routingTypeMapper = (str: string) => { } } -let volumeSplitConnectorSelectionDataMapper = dict => { +let volumeSplitConnectorSelectionDataMapper: Js.Dict.t< + Js.Json.t, +> => AdvancedRoutingTypes.volumeSplitConnectorSelectionData = dict => { { split: dict->getInt("split", 0), connector: { @@ -151,14 +154,16 @@ let volumeSplitConnectorSelectionDataMapper = dict => { } } -let priorityConnectorSelectionDataMapper = dict => { +let priorityConnectorSelectionDataMapper: Js.Dict.t< + Js.Json.t, +> => AdvancedRoutingTypes.connector = dict => { { connector: dict->getString("connector", ""), merchant_connector_id: dict->getString("merchant_connector_id", ""), } } -let connectorSelectionDataMapperFromJson: Js.Json.t => connectorSelectionData = json => { +let connectorSelectionDataMapperFromJson: Js.Json.t => AdvancedRoutingTypes.connectorSelectionData = json => { let split = json->getDictFromJsonObject->getOptionInt("split") let dict = json->getDictFromJsonObject switch split { @@ -187,6 +192,7 @@ let getDefaultSelection: Js.Dict.t< } let getConnectorStringFromConnectorSelectionData = connectorSelectionData => { + open AdvancedRoutingTypes switch connectorSelectionData { | VolumeObject(obj) => { merchant_connector_id: obj.connector.merchant_connector_id, @@ -200,13 +206,14 @@ let getConnectorStringFromConnectorSelectionData = connectorSelectionData => { } let getSplitFromConnectorSelectionData = connectorSelectionData => { + open AdvancedRoutingTypes switch connectorSelectionData { | VolumeObject(obj) => obj.split | _ => 0 } } -let ruleInfoTypeMapper = json => { +let ruleInfoTypeMapper: Js.Dict.t => AdvancedRoutingTypes.algorithmData = json => { let rulesArray = json->getArrayFromDict("rules", []) let defaultSelection = json->getDictfromDict("defaultSelection") @@ -260,6 +267,7 @@ let getGatewaysArrayFromValueData = data => { } let getModalObj = (routingType, text) => { + open AdvancedRoutingTypes switch routingType { | ADVANCED => { conType: "Activate current configured configuration?", @@ -310,14 +318,14 @@ let isStatementMandatoryFieldsPresent = (statement: AdvancedRoutingTypes.stateme statementValue) } -let algorithmTypeMapper = values => { +let algorithmTypeMapper: Js.Dict.t => AdvancedRoutingTypes.algorithm = values => { { data: values->getDictfromDict("data")->ruleInfoTypeMapper, \"type": values->getString("type", ""), } } -let getRoutingTypesFromJson = (values: Js.Json.t) => { +let getRoutingTypesFromJson: Js.Json.t => AdvancedRoutingTypes.advancedRouting = values => { let valuesDict = values->getDictFromJsonObject { @@ -331,53 +339,50 @@ let validateStatements = statementsArray => { statementsArray->Js.Array2.every(isStatementMandatoryFieldsPresent) } +let initialValueForStatement: AdvancedRoutingTypes.statementSendType = { + condition: [], +} + let generateStatements = statements => { - statements->Array.reduce( - [ - { - condition: [], + statements->Array.reduce([initialValueForStatement], (acc, statement) => { + let statementDict = statement->getDictFromJsonObject + let logicalOperator = statementDict->getString("logical", "")->Js.String2.toLowerCase + + let lastItem = + acc->Belt.Array.get(acc->Js.Array2.length - 1)->Belt.Option.getWithDefault({condition: []}) + + let condition: AdvancedRoutingTypes.statement = { + lhs: statementDict->getString("lhs", ""), + comparison: switch statementDict->getString("comparison", "")->operatorMapper { + | IS + | EQUAL_TO + | CONTAINS => "equal" + | IS_NOT + | NOT_CONTAINS + | NOT_EQUAL_TO => "not_equal" + | GREATER_THAN => "greater_than" + | LESS_THAN => "less_than" + | UnknownOperator(str) => str }, - ], - (acc, statement) => { - let statementDict = statement->getDictFromJsonObject - let logicalOperator = statementDict->getString("logical", "")->Js.String2.toLowerCase - - let lastItem = - acc->Belt.Array.get(acc->Js.Array2.length - 1)->Belt.Option.getWithDefault({condition: []}) + value: statementDict->getDictfromDict("value")->getStatementValue, + metadata: statementDict->getJsonObjectFromDict("metadata"), + } - let condition = { - lhs: statementDict->getString("lhs", ""), - comparison: switch statementDict->getString("comparison", "")->operatorMapper { - | IS - | EQUAL_TO - | CONTAINS => "equal" - | IS_NOT - | NOT_CONTAINS - | NOT_EQUAL_TO => "not_equal" - | GREATER_THAN => "greater_than" - | LESS_THAN => "less_than" - | UnknownOperator(str) => str + let newAcc = if logicalOperator === "or" { + acc->Js.Array2.concat([ + { + condition: [condition], }, - value: statementDict->getDictfromDict("value")->getStatementValue, - metadata: statementDict->getJsonObjectFromDict("metadata"), - } - - let newAcc = if logicalOperator === "or" { - acc->Js.Array2.concat([ - { - condition: [condition], - }, - ]) - } else { - lastItem.condition->Array.push(condition) - let filteredArr = acc->Array.filterWithIndex((_, i) => i !== acc->Js.Array2.length - 1) - filteredArr->Array.push(lastItem) - filteredArr - } + ]) + } else { + lastItem.condition->Array.push(condition) + let filteredArr = acc->Array.filterWithIndex((_, i) => i !== acc->Js.Array2.length - 1) + filteredArr->Array.push(lastItem) + filteredArr + } - newAcc - }, - ) + newAcc + }) } let generateRule = rulesDict => { From c2c66bad558ea93d4145bd60c6c179da11872d6b Mon Sep 17 00:00:00 2001 From: Riddhi Agrawal Date: Tue, 5 Dec 2023 16:19:32 +0530 Subject: [PATCH 27/27] fix: warnings removed --- .../RoutingRevamp/AdvancedRoutingUtils.res | 24 +++++++++++++++---- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res index d4d89ed02..37cb47e07 100644 --- a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res +++ b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res @@ -1,4 +1,3 @@ -open LogicUtils external toJson: 'a => Js.Json.t = "%identity" let getCurrentDetailedUTCTime = () => { @@ -45,6 +44,7 @@ let getRoutingTypeName = (routingType: AdvancedRoutingTypes.routing) => { } let getRoutingNameString = (~routingType) => { + open LogicUtils let routingText = routingType->getRoutingTypeName `${routingText->capitalizeString} Based Routing-${getCurrentShortUTCTime()}` } @@ -98,6 +98,7 @@ let variantTypeMapper: string => AdvancedRoutingTypes.variantType = variantType } let getStatementValue: Js.Dict.t => AdvancedRoutingTypes.value = valueDict => { + open LogicUtils { \"type": valueDict->getString("type", ""), value: valueDict->getJsonObjectFromDict("value"), @@ -105,13 +106,17 @@ let getStatementValue: Js.Dict.t => AdvancedRoutingTypes.value = valu } let statementTypeMapper: Js.Dict.t => AdvancedRoutingTypes.statement = dict => { - lhs: dict->getString("lhs", ""), - comparison: dict->getString("comparison", ""), - value: getStatementValue(dict->getDictfromDict("value")), - logical: dict->getString("logical", ""), + open LogicUtils + { + lhs: dict->getString("lhs", ""), + comparison: dict->getString("comparison", ""), + value: getStatementValue(dict->getDictfromDict("value")), + logical: dict->getString("logical", ""), + } } let conditionTypeMapper = (statementArr: array) => { + open LogicUtils let statements = statementArr->Array.reduce([], (acc, statementJson) => { let conditionArray = statementJson->getDictFromJsonObject->getArrayFromDict("condition", []) @@ -143,6 +148,7 @@ let routingTypeMapper = (str: string) => { let volumeSplitConnectorSelectionDataMapper: Js.Dict.t< Js.Json.t, > => AdvancedRoutingTypes.volumeSplitConnectorSelectionData = dict => { + open LogicUtils { split: dict->getInt("split", 0), connector: { @@ -157,6 +163,7 @@ let volumeSplitConnectorSelectionDataMapper: Js.Dict.t< let priorityConnectorSelectionDataMapper: Js.Dict.t< Js.Json.t, > => AdvancedRoutingTypes.connector = dict => { + open LogicUtils { connector: dict->getString("connector", ""), merchant_connector_id: dict->getString("merchant_connector_id", ""), @@ -164,6 +171,7 @@ let priorityConnectorSelectionDataMapper: Js.Dict.t< } let connectorSelectionDataMapperFromJson: Js.Json.t => AdvancedRoutingTypes.connectorSelectionData = json => { + open LogicUtils let split = json->getDictFromJsonObject->getOptionInt("split") let dict = json->getDictFromJsonObject switch split { @@ -175,6 +183,7 @@ let connectorSelectionDataMapperFromJson: Js.Json.t => AdvancedRoutingTypes.conn let getDefaultSelection: Js.Dict.t< Js.Json.t, > => AdvancedRoutingTypes.connectorSelection = defaultSelection => { + open LogicUtils let override3dsValue = defaultSelection->getString("override_3ds", "") if override3dsValue->Js.String2.length > 0 { @@ -214,6 +223,7 @@ let getSplitFromConnectorSelectionData = connectorSelectionData => { } let ruleInfoTypeMapper: Js.Dict.t => AdvancedRoutingTypes.algorithmData = json => { + open LogicUtils let rulesArray = json->getArrayFromDict("rules", []) let defaultSelection = json->getDictfromDict("defaultSelection") @@ -319,6 +329,7 @@ let isStatementMandatoryFieldsPresent = (statement: AdvancedRoutingTypes.stateme } let algorithmTypeMapper: Js.Dict.t => AdvancedRoutingTypes.algorithm = values => { + open LogicUtils { data: values->getDictfromDict("data")->ruleInfoTypeMapper, \"type": values->getString("type", ""), @@ -326,6 +337,7 @@ let algorithmTypeMapper: Js.Dict.t => AdvancedRoutingTypes.algorithm } let getRoutingTypesFromJson: Js.Json.t => AdvancedRoutingTypes.advancedRouting = values => { + open LogicUtils let valuesDict = values->getDictFromJsonObject { @@ -344,6 +356,7 @@ let initialValueForStatement: AdvancedRoutingTypes.statementSendType = { } let generateStatements = statements => { + open LogicUtils statements->Array.reduce([initialValueForStatement], (acc, statement) => { let statementDict = statement->getDictFromJsonObject let logicalOperator = statementDict->getString("logical", "")->Js.String2.toLowerCase @@ -387,6 +400,7 @@ let generateStatements = statements => { let generateRule = rulesDict => { let modifiedRules = rulesDict->Js.Array2.map(ruleJson => { + open LogicUtils let ruleDict = ruleJson->getDictFromJsonObject let statements = ruleDict->getArrayFromDict("statements", [])