diff --git a/.githooks/commit-msg b/.githooks/commit-msg index 865cf65c2..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 diff --git a/.github/workflows/release-new-version.yml b/.github/workflows/release-new-version.yml index 01ca10b53..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 @@ -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 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/.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 index 581d2402c..a4247f0cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,14 +3,18 @@ All notable changes to this project will be documented in this file. See [conven - - - -## 1.1.0 (2023-11-29) +## 1.0.4 (2023-12-04) -### Features +### Bug Fixes -- 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)) +- 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)) -**Full Changelog:** [`v1.0.2...v1.1.0`](https://github.com/juspay/hyperswitch-control-center/compare/v1.0.2...v1.1.0) +### 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) - - - diff --git a/README.md b/README.md index e3ca47a49..29d5b0d3f 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. @@ -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 bbe5ac822..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, @@ -22,4 +20,4 @@ "business_profile": false, "generate_report": false, "forgot_password": false -} \ No newline at end of file +} diff --git a/package-lock.json b/package-lock.json index a315ba727..195c36bdd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rescript-euler-dashboard", - "version": "1.0.2", + "version": "1.0.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rescript-euler-dashboard", - "version": "1.0.2", + "version": "1.0.5", "hasInstallScript": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index c2f9c4eac..4e94eab64 100644 --- a/package.json +++ b/package.json @@ -1,28 +1,22 @@ { - "name": "rescript-euler-dashboard", - "version": "1.0.2", + "name": "hyperswitch-dashboard", + "version": "1.0.5", "main": "index.js", "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/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 diff --git a/public/hyperswitch/module.js b/public/hyperswitch/module.js index d5143e314..d54684e76 100644 --- a/public/hyperswitch/module.js +++ b/public/hyperswitch/module.js @@ -62,3 +62,43 @@ function getParsedJson(str) { throw e; } } + +function getThreeDsKeys() { + if (wasm) { + return wasm.getThreeDsKeys(); + } else { + 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/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/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/HyperSwitchApp.res b/src/entryPoints/hyperswitch/HyperSwitchApp.res index e6a3c48a5..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">
@@ -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}> @@ -332,16 +334,32 @@ let make = () => { } + renderList={() => } renderShow={profileId => } /> - | list{"settings"} => - | list{"profile"} => - | list{"settings", "profile"} => - | list{"recon"} => - | list{"sdk"} => + | 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/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 95747840f..f4783826b 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", @@ -195,7 +219,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 +234,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 +242,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 } @@ -277,21 +303,35 @@ let reconTag = (recon, isReconEnabled) => : emptyComponent let getHyperSwitchAppSidebars = ( - ~isReconEnabled=false, + ~isReconEnabled: bool, ~featureFlagDetails: FeatureFlagUtils.featureFlag, ~userRole, (), ) => { - let {productionAccess, frm, payOut, recon, default, userManagement} = featureFlagDetails + let { + productionAccess, + frm, + payOut, + 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), - default->settings, + default->developers(userRole, systemMetrics), + 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 = { }}>
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") +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/Analytics/HSAnalyticsUtils.res b/src/screens/HyperSwitch/Analytics/HSAnalyticsUtils.res index 142b34ad9..516800622 100644 --- a/src/screens/HyperSwitch/Analytics/HSAnalyticsUtils.res +++ b/src/screens/HyperSwitch/Analytics/HSAnalyticsUtils.res @@ -174,14 +174,11 @@ 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 = () => { + let make = (~title, ~subTitle) => {
+
@@ -225,11 +225,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(_ => []) @@ -286,6 +281,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/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/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..4935c4cdf 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("")
@@ -47,6 +47,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/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/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/HSwitchUtils.res b/src/screens/HyperSwitch/HSwitchUtils.res index cdeb685ff..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 @@ -227,18 +129,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 = ( @@ -394,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 @@ -465,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/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}

{ 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") diff --git a/src/screens/HyperSwitch/Recon/Recon.res b/src/screens/HyperSwitch/Recon/Recon.res index b30c546f6..ff93d36c5 100644 --- a/src/screens/HyperSwitch/Recon/Recon.res +++ b/src/screens/HyperSwitch/Recon/Recon.res @@ -1,16 +1,3 @@ -module ReconProPackageInfo = { - @react.component - let make = () => { -
- -
- {"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/Routing/RoutingUtils.res b/src/screens/HyperSwitch/Routing/RoutingUtils.res index 079bfea39..79d419daa 100644 --- a/src/screens/HyperSwitch/Routing/RoutingUtils.res +++ b/src/screens/HyperSwitch/Routing/RoutingUtils.res @@ -688,6 +688,29 @@ let validateNameAndDescription = (~dict, ~errors) => { }) } +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->checkIfValuePresent + | None => false + } +} + let validateConditions = dict => { dict ->LogicUtils.getArrayFromDict("conditions", []) @@ -695,11 +718,11 @@ 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) => { - 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 cccabcc27..b147f8b23 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}
-
@@ -100,7 +91,7 @@ module Wrapper = { ~notFirstRule=true, ~isDragging=false, ~wasm, - ~isfrom3ds=false, + ~isFrom3ds=false, ) => { let showToast = ToastState.useShowToast() let isMobileView = MatchMedia.useMobileChecker() @@ -230,12 +221,12 @@ module Wrapper = { ${border} border-blue-700`}> - + - + - +
@@ -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/AdvancedRoutingUIUtils.res b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res index 48c1b2341..28e1d3092 100644 --- a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res +++ b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUIUtils.res @@ -318,9 +318,8 @@ 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(_ => "") let (variantValues, setVariantValues) = React.useState(_ => []) let field = ReactFinalForm.useField(`${id}.lhs`).input @@ -339,20 +338,19 @@ module RuleFieldBase = { setKeyTypeAndVariants(wasm, value) } - React.useEffect0(() => { - let methodKeys = switch wasm { - | Some(res) => res.getAllKeys() - | None => [] - } + 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 {
- +
@@ -394,7 +392,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 +417,7 @@ module MakeRuleField = { id={`${ruleJsonPath}[${i->Belt.Int.toString}]`} isExpanded wasm + isFrom3ds /> )->React.array} {if isExpanded { diff --git a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res index 92451c08c..37cb47e07 100644 --- a/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res +++ b/src/screens/HyperSwitch/RoutingRevamp/AdvancedRoutingUtils.res @@ -1,11 +1,10 @@ -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", } @@ -45,6 +44,7 @@ let getRoutingTypeName = (routingType: AdvancedRoutingTypes.routing) => { } let getRoutingNameString = (~routingType) => { + open LogicUtils let routingText = routingType->getRoutingTypeName `${routingText->capitalizeString} Based Routing-${getCurrentShortUTCTime()}` } @@ -97,32 +97,38 @@ let variantTypeMapper: string => AdvancedRoutingTypes.variantType = variantType } } -let getStatementValue = valueDict => { +let getStatementValue: Js.Dict.t => AdvancedRoutingTypes.value = valueDict => { + open LogicUtils { \"type": valueDict->getString("type", ""), value: valueDict->getJsonObjectFromDict("value"), } } -let statementTypeMapper = dict => { - lhs: dict->getString("lhs", ""), - comparison: dict->getString("comparison", ""), - value: getStatementValue(dict->getDictfromDict("value")), - logical: dict->getString("logical", ""), +let statementTypeMapper: Js.Dict.t => AdvancedRoutingTypes.statement = dict => { + open LogicUtils + { + lhs: dict->getString("lhs", ""), + comparison: dict->getString("comparison", ""), + value: getStatementValue(dict->getDictfromDict("value")), + logical: dict->getString("logical", ""), + } } let conditionTypeMapper = (statementArr: array) => { + open LogicUtils let statements = statementArr->Array.reduce([], (acc, statementJson) => { let conditionArray = statementJson->getDictFromJsonObject->getArrayFromDict("condition", []) 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) }) @@ -131,6 +137,7 @@ let conditionTypeMapper = (statementArr: array) => { } let routingTypeMapper = (str: string) => { + open AdvancedRoutingTypes switch str->Js.String2.toLowerCase { | "priority" => PRIORITY | "volume_split" => VOLUME_SPLIT @@ -138,7 +145,10 @@ let routingTypeMapper = (str: string) => { } } -let volumeSplitConnectorSelectionDataMapper = dict => { +let volumeSplitConnectorSelectionDataMapper: Js.Dict.t< + Js.Json.t, +> => AdvancedRoutingTypes.volumeSplitConnectorSelectionData = dict => { + open LogicUtils { split: dict->getInt("split", 0), connector: { @@ -150,14 +160,18 @@ let volumeSplitConnectorSelectionDataMapper = dict => { } } -let priorityConnectorSelectionDataMapper = dict => { +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", ""), } } -let connectorSelectionDataMapperFromJson: Js.Json.t => connectorSelectionData = json => { +let connectorSelectionDataMapperFromJson: Js.Json.t => AdvancedRoutingTypes.connectorSelectionData = json => { + open LogicUtils let split = json->getDictFromJsonObject->getOptionInt("split") let dict = json->getDictFromJsonObject switch split { @@ -169,15 +183,25 @@ 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), + open LogicUtils + 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), + } } } let getConnectorStringFromConnectorSelectionData = connectorSelectionData => { + open AdvancedRoutingTypes switch connectorSelectionData { | VolumeObject(obj) => { merchant_connector_id: obj.connector.merchant_connector_id, @@ -191,13 +215,15 @@ 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 => { + open LogicUtils let rulesArray = json->getArrayFromDict("rules", []) let defaultSelection = json->getDictfromDict("defaultSelection") @@ -251,6 +277,7 @@ let getGatewaysArrayFromValueData = data => { } let getModalObj = (routingType, text) => { + open AdvancedRoutingTypes switch routingType { | ADVANCED => { conType: "Activate current configured configuration?", @@ -301,14 +328,16 @@ let isStatementMandatoryFieldsPresent = (statement: AdvancedRoutingTypes.stateme statementValue) } -let algorithmTypeMapper = values => { +let algorithmTypeMapper: Js.Dict.t => AdvancedRoutingTypes.algorithm = values => { + open LogicUtils { data: values->getDictfromDict("data")->ruleInfoTypeMapper, \"type": values->getString("type", ""), } } -let getRoutingTypesFromJson = (values: Js.Json.t) => { +let getRoutingTypesFromJson: Js.Json.t => AdvancedRoutingTypes.advancedRouting = values => { + open LogicUtils let valuesDict = values->getDictFromJsonObject { @@ -321,3 +350,67 @@ let getRoutingTypesFromJson = (values: Js.Json.t) => { let validateStatements = statementsArray => { statementsArray->Js.Array2.every(isStatementMandatoryFieldsPresent) } + +let initialValueForStatement: AdvancedRoutingTypes.statementSendType = { + condition: [], +} + +let generateStatements = statements => { + open LogicUtils + 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 + }, + 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 + }) +} + +let generateRule = rulesDict => { + let modifiedRules = rulesDict->Js.Array2.map(ruleJson => { + open LogicUtils + let ruleDict = ruleJson->getDictFromJsonObject + let statements = ruleDict->getArrayFromDict("statements", []) + + let modifiedStatements = statements->generateStatements + + { + "name": ruleDict->getString("name", ""), + "connectorSelection": ruleDict->getJsonObjectFromDict("connectorSelection"), + "statements": modifiedStatements->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/SelfServe/HSwitchSandboxOnboarding/CodeSnippets.res b/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/CodeSnippets.res index 8b1f40afd..aa89ea871 100644 --- a/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/CodeSnippets.res +++ b/src/screens/HyperSwitch/SelfServe/HSwitchSandboxOnboarding/CodeSnippets.res @@ -699,8 +699,6 @@ npm install @juspay-tech/hyperswitch-node ` let nodeMigrateFromStripeDXForHTML = `npm install @juspay-tech/hyperswitch-node` -let reactCreateAPayment: string = `npm install @juspay-tech/hyperswitch-node` - let nodeCreateAPayment: string = `const express = require("express"); const app = express(); @@ -735,67 +733,3 @@ app.post("/create-payment", async (req, res) => { }); 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) { - // 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/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/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/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/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..2db63dcb1 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_} @@ -135,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/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/BusinessMapping.res b/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessProfile.res similarity index 69% rename from src/screens/HyperSwitch/Settings/BusinessMapping/BusinessMapping.res rename to src/screens/HyperSwitch/Settings/BusinessMapping/BusinessProfile.res index 86def3d90..384f1d88f 100644 --- a/src/screens/HyperSwitch/Settings/BusinessMapping/BusinessMapping.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, @@ -156,13 +111,18 @@ let make = ( updateMerchantDetails(values)->ignore Js.Nullable.null } - let tableHeaderText = isFromWebhooks ? "Webhooks" : "Business profiles" + let tableHeaderText = isFromWebhooks ? "Webhooks" : "Business Profiles"
-
{tableHeaderText->React.string}
+ Js.Array2.length} /> // -
- -
+ +
+ +
+
diff --git a/src/screens/HyperSwitch/Settings/HSwitchMerchantAccountUtils.res b/src/screens/HyperSwitch/Settings/HSwitchMerchantAccountUtils.res index e88c87089..42fceaaae 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 = { @@ -668,7 +396,7 @@ let validateCustom = (key, errors, value) => { let validateMerchantAccountForm = ( ~values: Js.Json.t, ~fieldsToValidate: array, - ~setIsDisabled=?, + ~setIsDisabled, ~initialData, ) => { let errors = Js.Dict.empty() @@ -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(() => { diff --git a/src/screens/HyperSwitch/Settings/HSwitchSettingTypes.res b/src/screens/HyperSwitch/Settings/HSwitchSettingTypes.res index b90b6c725..424420470 100644 --- a/src/screens/HyperSwitch/Settings/HSwitchSettingTypes.res +++ b/src/screens/HyperSwitch/Settings/HSwitchSettingTypes.res @@ -131,23 +131,6 @@ type personalSettings = { redirectUrl?: string, isApiCall?: bool, } -type pageType = Business | Units | Notifications | Mandate | LandingPage -let typeMapper = (pageType: 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/ThreeDSFlow/HSwitchThreeDS.res b/src/screens/HyperSwitch/ThreeDSFlow/HSwitchThreeDS.res index c7e55f912..0398d7bcb 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 } if notFirstRule { @@ -98,9 +103,7 @@ let make = () => { 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`) @@ -221,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", []) diff --git a/src/screens/HyperSwitch/ThreeDSFlow/ThreeDSUtils.res b/src/screens/HyperSwitch/ThreeDSFlow/ThreeDSUtils.res index 42d2fda37..dd71cc234 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,37 @@ 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) => { +let buildThreeDsPayloadBody = values => { 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 valuesDict = values->getDictFromJsonObject + let dataDict = valuesDict->getDictfromDict("algorithm") + let rulesDict = dataDict->getArrayFromDict("rules", []) + + let modifiedRules = rulesDict->AdvancedRoutingUtils.generateRule + + let threeDsPayload = { + "name": valuesDict->getString("name", ""), + "algorithm": { + "defaultSelection": { + "override_3ds": null, + }, + "rules": modifiedRules, + "metadata": Js.Dict.empty()->Js.Json.object_, + }, + } threeDsPayload } 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/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 d27ae6dfb..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, @@ -31,10 +30,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", ""), @@ -43,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, } @@ -67,25 +55,6 @@ let getHeadingForUser = (colType: userColTypes) => { } } -let itemToObjMapperForRole = dict => { - { - permissions: dict->getStrArray("permissions"), - role_id: dict->getString("role_id", ""), - } -} - -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 +118,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 +133,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`}, -// (), -// ) 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 }}
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", ""}, _) 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,