From b55155a4a1d5487129090e191da7d4823daba857 Mon Sep 17 00:00:00 2001 From: Pritish Budhiraja <77892330+PritishBudhiraja@users.noreply.github.com> Date: Wed, 29 Nov 2023 17:15:47 +0530 Subject: [PATCH] Enhancement - Dead Code Removal & Postinstall Checks (#28) --- .githooks/commit-msg | 6 +- .gitignore | 1 + package-lock.json | 169 ++++- package.json | 5 +- src/components/ActionsContainer.res | 8 - src/components/AdvancedSearchComponent.res | 17 - src/components/Alert.res | 35 - src/components/AuthWrapperUtils.res | 2 +- src/components/Banner.res | 37 - src/components/Base64ImageInput.res | 157 ----- src/components/ChartEntity/ChartEntity.res | 52 -- .../CustomCharts/HighchartBarChart.res | 119 ---- .../CustomCharts/HighchartSparkLineChart.res | 108 --- .../CustomCharts/HighchartTimeSeriesChart.res | 2 +- .../CustomCharts/LineChartUtils.res | 8 - src/components/custom-icons/LottieFiles.res | 4 - .../custom-icons/NoDataIllustration.res | 6 - .../hyperswitch/HyperSwitchApp.res | 2 +- .../FraudAndRisk/FRMIntegrationFields.res | 2 +- .../HyperSwitch/FraudAndRisk/FRMSummary.res | 3 +- .../HyperSwitch/FraudAndRisk/FRMUtils.res | 9 +- src/screens/HyperSwitch/HSMixPanel.res | 9 +- src/screens/HyperSwitch/HSwitchUtils.res | 6 - .../HyperSwitch/Sidebar/SidebarProvider.res | 5 - .../StripePlusPaypalUtils.res | 2 +- .../SwitchMerchant/SwitchMerchant.res | 2 +- src/utils/GlobalVars.res | 5 - src/utils/JsonFlattenUtils.res | 237 ------- src/utils/LogicUtils.res | 655 ------------------ src/utils/Parsers.res | 251 ------- src/utils/ResizeObserver.res | 10 +- src/utils/Reveal.res | 34 +- src/utils/SortUtils.res | 16 - src/utils/UrlFetchUtils.res | 78 --- 34 files changed, 181 insertions(+), 1881 deletions(-) delete mode 100644 src/components/ActionsContainer.res delete mode 100644 src/components/Alert.res delete mode 100644 src/components/Banner.res delete mode 100644 src/components/Base64ImageInput.res delete mode 100644 src/components/ChartEntity/ChartEntity.res delete mode 100644 src/components/CustomCharts/HighchartSparkLineChart.res delete mode 100644 src/components/custom-icons/NoDataIllustration.res delete mode 100644 src/utils/Parsers.res delete mode 100644 src/utils/SortUtils.res diff --git a/.githooks/commit-msg b/.githooks/commit-msg index d1144b41d..865cf65c2 100755 --- a/.githooks/commit-msg +++ b/.githooks/commit-msg @@ -11,11 +11,11 @@ npx prettier --write . npm run re:format # Define your commit message convention (e.g., starts with "feature:", "fix:", etc.) -commit_regex="^(merge-commit|feat|fix|chore|docs|style|refactor|test|enhancement).+" +commit_regex="^(Merge branch|feat|fix|chore|docs|style|refactor|test|enhancement).+" -if ! echo "$commit_msg" | grep -E "$commit_regex" ; then +if ! echo "$commit_msg" | grep -Ei "$commit_regex" ; then echo "Aborting commit. Your commit message does not follow the conventional format." - echo "Example - : - " + echo "Example - : - " exit 1 fi diff --git a/.gitignore b/.gitignore index 6394d14b5..a078048fb 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,4 @@ yarn.lock #package-lock.json user_data.sh *.pem +.bsb.lock \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 0967c7c52..6e047a0f3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,6 +7,7 @@ "": { "name": "rescript-euler-dashboard", "version": "1.0.1", + "hasInstallScript": true, "license": "MIT", "dependencies": { "@headlessui/react": "^1.2.0", @@ -5574,6 +5575,22 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/@jest/core/node_modules/babel-plugin-macros": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/babel-plugin-macros/-/babel-plugin-macros-3.1.0.tgz", + "integrity": "sha512-Cg7TFGpIr01vOQNODXOOaGz2NpCU5gl8x1qJFbb6hbZxR7XrcE2vtbAsTAbJ7/xwJtUuJEw8K8Zr/AE0LHlesg==", + "optional": true, + "peer": true, + "dependencies": { + "@babel/runtime": "^7.12.5", + "cosmiconfig": "^7.0.0", + "resolve": "^1.19.0" + }, + "engines": { + "node": ">=10", + "npm": ">=6" + } + }, "node_modules/@jest/core/node_modules/babel-preset-jest": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", @@ -17565,6 +17582,22 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/create-jest/node_modules/babel-plugin-macros": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/babel-plugin-macros/-/babel-plugin-macros-3.1.0.tgz", + "integrity": "sha512-Cg7TFGpIr01vOQNODXOOaGz2NpCU5gl8x1qJFbb6hbZxR7XrcE2vtbAsTAbJ7/xwJtUuJEw8K8Zr/AE0LHlesg==", + "optional": true, + "peer": true, + "dependencies": { + "@babel/runtime": "^7.12.5", + "cosmiconfig": "^7.0.0", + "resolve": "^1.19.0" + }, + "engines": { + "node": ">=10", + "npm": ">=6" + } + }, "node_modules/create-jest/node_modules/babel-preset-jest": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", @@ -25527,6 +25560,22 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/jest-cli/node_modules/babel-plugin-macros": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/babel-plugin-macros/-/babel-plugin-macros-3.1.0.tgz", + "integrity": "sha512-Cg7TFGpIr01vOQNODXOOaGz2NpCU5gl8x1qJFbb6hbZxR7XrcE2vtbAsTAbJ7/xwJtUuJEw8K8Zr/AE0LHlesg==", + "optional": true, + "peer": true, + "dependencies": { + "@babel/runtime": "^7.12.5", + "cosmiconfig": "^7.0.0", + "resolve": "^1.19.0" + }, + "engines": { + "node": ">=10", + "npm": ">=6" + } + }, "node_modules/jest-cli/node_modules/babel-preset-jest": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", @@ -31836,25 +31885,86 @@ "license": "MIT" }, "node_modules/node-notifier": { - "version": "5.4.5", - "resolved": "https://registry.npmjs.org/node-notifier/-/node-notifier-5.4.5.tgz", - "integrity": "sha512-tVbHs7DyTLtzOiN78izLA85zRqB9NvEXkAf014Vx3jtSvn/xBl6bR8ZYifj+dFcFrKI21huSQgJZ6ZtL3B4HfQ==", - "license": "MIT", + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/node-notifier/-/node-notifier-10.0.1.tgz", + "integrity": "sha512-YX7TSyDukOZ0g+gmzjB6abKu+hTGvO8+8+gIFDsRCU2t8fLV/P2unmt+LGFaIa4y64aX98Qksa97rgz4vMNeLQ==", + "optional": true, + "peer": true, "dependencies": { "growly": "^1.3.0", - "is-wsl": "^1.1.0", - "semver": "^5.5.0", + "is-wsl": "^2.2.0", + "semver": "^7.3.5", "shellwords": "^0.1.1", - "which": "^1.3.0" + "uuid": "^8.3.2", + "which": "^2.0.2" + } + }, + "node_modules/node-notifier/node_modules/is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "optional": true, + "peer": true, + "dependencies": { + "is-docker": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/node-notifier/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "optional": true, + "peer": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" } }, "node_modules/node-notifier/node_modules/semver": { - "version": "5.7.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", - "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", - "license": "ISC", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "optional": true, + "peer": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, "bin": { - "semver": "bin/semver" + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-notifier/node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "optional": true, + "peer": true, + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/node-notifier/node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "optional": true, + "peer": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" } }, "node_modules/node-releases": { @@ -36304,7 +36414,6 @@ "version": "0.10.0", "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.10.0.tgz", "integrity": "sha512-PgidR3wST3dDYKr6b4pJoqQFpPGNKDSCDx4cZoshjXipw3LzO7mG1My2pwEzz2JVkF+inx3xRpDeQLFQGH/hsQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -38731,6 +38840,26 @@ "node": ">= 6.0.0" } }, + "node_modules/react-scripts/node_modules/node-notifier": { + "version": "5.4.5", + "resolved": "https://registry.npmjs.org/node-notifier/-/node-notifier-5.4.5.tgz", + "integrity": "sha512-tVbHs7DyTLtzOiN78izLA85zRqB9NvEXkAf014Vx3jtSvn/xBl6bR8ZYifj+dFcFrKI21huSQgJZ6ZtL3B4HfQ==", + "dependencies": { + "growly": "^1.3.0", + "is-wsl": "^1.1.0", + "semver": "^5.5.0", + "shellwords": "^0.1.1", + "which": "^1.3.0" + } + }, + "node_modules/react-scripts/node_modules/node-notifier/node_modules/semver": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", + "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", + "bin": { + "semver": "bin/semver" + } + }, "node_modules/react-scripts/node_modules/npm-run-path": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", @@ -41288,7 +41417,6 @@ "version": "10.1.4", "resolved": "https://registry.npmjs.org/rescript/-/rescript-10.1.4.tgz", "integrity": "sha512-FFKlS9AG/XrLepWsyw7B+A9DtQBPWEPDPDKghV831Y2KGbie+eeFBOS0xtRHp0xbt7S0N2Dm6hhX+kTZQ/3Ybg==", - "dev": true, "hasInstallScript": true, "license": "SEE LICENSE IN LICENSE", "bin": { @@ -44517,6 +44645,19 @@ "is-typedarray": "^1.0.0" } }, + "node_modules/typescript": { + "version": "3.9.10", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.9.10.tgz", + "integrity": "sha512-w6fIxVE/H1PkLKcCPsFqKE7Kv7QUwhU8qQY2MueZXWx5cPZdwFupLgKK3vntcK98BtNHZtAF4LA/yl2a7k8R6Q==", + "peer": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=4.2.0" + } + }, "node_modules/ua-parser-js": { "version": "1.0.37", "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-1.0.37.tgz", diff --git a/package.json b/package.json index 8fe319b54..6ed8903ce 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "author": "Shiva Nandan ", "license": "MIT", "scripts": { - "pre-commit": "git config core.hooksPath .githooks && chmod +x .githooks/commit-msg && bash .githooks/commit-msg", + "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", "prod:start": "webpack serve --config webpack.dev.js", @@ -22,7 +22,8 @@ "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" + "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": { "hooks": { diff --git a/src/components/ActionsContainer.res b/src/components/ActionsContainer.res deleted file mode 100644 index ae28e4bcc..000000000 --- a/src/components/ActionsContainer.res +++ /dev/null @@ -1,8 +0,0 @@ -@react.component -let make = (~children) => { -
- {children->React.Children.map(element => { - element - })} -
-} diff --git a/src/components/AdvancedSearchComponent.res b/src/components/AdvancedSearchComponent.res index b4cc26895..13fd08b37 100644 --- a/src/components/AdvancedSearchComponent.res +++ b/src/components/AdvancedSearchComponent.res @@ -25,23 +25,6 @@ let make = ( let (showModal, setShowModal) = React.useState(_ => false) let onSubmit = (values, form: ReactFinalForm.formApi) => { - let _otherQueries = switch values->Js.Json.decodeObject { - | Some(dict) => - dict - ->Js.Dict.entries - ->Belt.Array.keepMap(entry => { - let (key, value) = entry - let stringVal = LogicUtils.getStringFromJson(value, "") - if stringVal !== "" { - Some(`${key}=${stringVal}`) - } else { - None - } - }) - ->Js.Array2.joinWith("&") - | _ => "" - } - open Promise fetchApi(url, ~bodyStr=Js.Json.stringify(values), ~method_=Fetch.Post, ()) diff --git a/src/components/Alert.res b/src/components/Alert.res deleted file mode 100644 index cf9bd3b7a..000000000 --- a/src/components/Alert.res +++ /dev/null @@ -1,35 +0,0 @@ -type alertType = SUCCESS | WARNING | ERROR | PRIMARY | INFO | LIGHT -@react.component -let make = (~title, ~alertType: alertType, ~className="", ~bodystr=?, ~bodyBullets=false) => { - let color = switch alertType { - | LIGHT => "text-gray-900 bg-gray-100 border-gray-900" - | SUCCESS => " bg-green-300 text-green-900 " - | WARNING => " bg-yellow-200 text-yellow-900 " - | ERROR => " bg-red-200 text-red-900 " - | PRIMARY => " bg-blue-200 text-blue-900 " - | _ => "" - } - - let dot = -
-
-
{React.string(title)}
- {switch bodystr { - | Some(text) => -
- {text - ->Js.Array2.map(text => { -
-
{bodyBullets ? {dot} : React.null}
-
{React.string(text)}
-
- }) - ->React.array} -
- | None => React.null - }} -
-} diff --git a/src/components/AuthWrapperUtils.res b/src/components/AuthWrapperUtils.res index 04a78c8b5..1124c89c2 100644 --- a/src/components/AuthWrapperUtils.res +++ b/src/components/AuthWrapperUtils.res @@ -1,4 +1,4 @@ -type parent = {postMessage: (. string, string) => unit} +type parent @val external window: 'a = "window" @val @scope("window") external parent: parent = "parent" diff --git a/src/components/Banner.res b/src/components/Banner.res deleted file mode 100644 index d87770b27..000000000 --- a/src/components/Banner.res +++ /dev/null @@ -1,37 +0,0 @@ -type actionBtn = { - btnText: string, - onClick: unit => unit, - customBtnStyle: string, -} - -@react.component -let make = ( - ~mainText, - ~subText, - ~wrapperStyle="p-5 mb-5 text-white font-medium text-xl ", - ~bgColor="bg-blue-900", - ~mainTextStyle="font-bold", - ~subTextStyle="", - ~actions: array=[], -) => { -
-
- %raw(`String.fromCodePoint(0x1F389)`) -
{mainText->React.string}
-
{subText->React.string}
- {actions - ->Js.Array2.mapi((btn, i) => { -
btn.onClick()} - className={`py-1 px-3 border-2 rounded text-base cursor-pointer hover:bg-white hover:text-blue-900 font-bold ${btn.customBtnStyle}`} - key={i->Belt.Int.toString}> - {btn.btnText->React.string} -
- }) - ->React.array} -
-
- -
-
-} diff --git a/src/components/Base64ImageInput.res b/src/components/Base64ImageInput.res deleted file mode 100644 index 7910f869a..000000000 --- a/src/components/Base64ImageInput.res +++ /dev/null @@ -1,157 +0,0 @@ -external toReactEvent: 'a => ReactEvent.Form.t = "%identity" -external strToDomImg: string => Webapi.Dom.Image.t = "%identity" -@send external drawImage: (Webapi.Canvas.Canvas2d.t, 'a, int, int) => unit = "drawImage" -@send external toDataURL: 'a => string = "toDataURL" -@get external width: Dom.element => string = "width" -@get external height: Dom.element => string = "height" -@set external src: (Dom.element, string) => unit = "src" -@new external image: unit => Dom.element = "Image" -@set external setWidth: (Dom.element, string) => unit = "width" -@set external setHeight: (Dom.element, string) => unit = "height" - -open Webapi.Canvas -type rotateType = Left | Right -@react.component -let make = ( - ~input: ReactFinalForm.fieldRenderPropsInput, - ~customButtonStyle=?, - ~customFileStyle="", - ~showImage=true, - ~showRotate=true, - ~showFileName=true, - ~reverseOrder=false, - ~buttonText, - ~positionCSS="", - ~imgCSS="", - ~leftIcon=React.null, - ~allowedType="image/*", - ~isInputDisabled=false, -) => { - let (fileName, setFilename) = React.useState(_ => "") - let (isNewUpload, setIsNewUpload) = React.useState(_ => false) - let (isfileTooLarge, setIsfileTooLarge) = React.useState(_ => false) - let showToast = ToastState.useShowToast() - - let orderCSS = reverseOrder ? "order-last" : "" - - let buttonStyle = switch customButtonStyle { - | Some(style) => style - | None => `font-bold whitespace-pre overflow-hidden justify-center h-10 - flex flex-row items-center text-jp-gray-800 dark:text-dark_theme dark:hover:text-jp-gray-300 cursor-pointer rounded-md border border-jp-gray-500 dark:border-jp-gray-960 bg-gradient-to-b from-jp-gray-250 to-jp-gray-200 dark:from-jp-gray-950 dark:to-jp-gray-950 dark:text-opacity-50 dark:text-jp-gray-text_darktheme hover:shadow hover:text-opacity-100 text-opacity-50 focus:outline-none focus:text-opacity-100 px-1` - } - let val = React.useMemo1(() => { - input.value->Js.Json.decodeString->Belt.Option.getWithDefault("") - }, [input.value]) - let canvas = React.useMemo0(() => - Webapi.Dom.document->Webapi.Dom.Document.createElement("canvas") - ) - let clearImage = _evt => { - setFilename(_ => "") - input.onChange(""->toReactEvent) - } - let onChange = evt => { - let target = ReactEvent.Form.target(evt) - let value = target["files"]["0"] - let size = value["size"] - setIsfileTooLarge(_ => size > 400000) - - if size > 400000 { - showToast(~message="File size too large, upload below 400kb", ~toastType=ToastError, ()) - } else if target["files"]->Js.Array2.length > 0 { - let filename = value["name"] - setFilename(_ => filename) - let fileReader = FileReader.reader - let _file = fileReader.readAsDataURL(. value) - fileReader.onload = e => { - let target = ReactEvent.Form.target(e) - let data = target["result"] - setIsNewUpload(_ => true) - input.onChange(toReactEvent(data)) - } - } - } - let transform = (transType, _evt) => { - let context = canvas->CanvasElement.getContext2d - let img = image() - src(img, val) - setWidth(canvas, height(img)) - setHeight(canvas, width(img)) - let a = switch transType { - | Left => { - context->Canvas2d.translate( - ~x=height(img)->Belt.Float.fromString->Belt.Option.getWithDefault(0.), - ~y=0., - ) - context->Canvas2d.rotate(90. *. (Js.Math._PI /. 180.)) - context->drawImage(img, 0, 0) - toDataURL(canvas) - } - - | Right => - context->Canvas2d.translate( - ~y=width(img)->Belt.Float.fromString->Belt.Option.getWithDefault(0.), - ~x=0., - ) - context->Canvas2d.rotate(-90. *. (Js.Math._PI /. 180.)) - context->drawImage(img, 0, 0) - toDataURL(canvas) - } - input.onChange(a->toReactEvent) - } -
-
-
- -
- {if isNewUpload && fileName != "" && !isfileTooLarge && showFileName { - <> -
- {React.string(fileName)} -
- - - - - } else { - React.null - }} -
- {if val != "" && !isfileTooLarge && showImage { -
- {if showRotate { - - - - } else { - React.null - }} -
- -
-
- } else { - React.null - }} -
-} diff --git a/src/components/ChartEntity/ChartEntity.res b/src/components/ChartEntity/ChartEntity.res deleted file mode 100644 index 2b595bc04..000000000 --- a/src/components/ChartEntity/ChartEntity.res +++ /dev/null @@ -1,52 +0,0 @@ -open AnalyticsTypesUtils - -type filterConfig = { - source: string, // source can be BATCH, KVLOGS basically which DB to fetch - modeValue: string, // modeValue can be ORDERS, TXN so here is the mode is orders we see data aggregated by the order_id and if mode is txn the data is aggregated by txn id simmilarly more mode can be added - filterValues?: Js.Json.t, // which all filters will be applicable for the single stats (those keys i.e merchant_id, payment_gateway etc.) - startTime: string, // start time from when data will fetch (later can be moved to the parent level) - endTime: string, // end time till when data should be fetched (later can be moved to the parent level) - customFilterValue: string, // custome filter key is the key by which stores the value of the applied customfilter in the url -} - -let filterConfig = { - source: "", - modeValue: "", - startTime: "", - endTime: "", - customFilterValue: "", -} - -type dataFetcherObj<'a> = { - metrics: 'a, // metrics are the stats i.e total volume, success rate etc. - bodyMaker: (string, filterConfig) => string, // to make the single stat body - timeSeriedBodyMaker: (string, filterConfig) => string, // to make the single stat timeseries body - transaformer: (string, Js.Json.t) => Js.Dict.t, // just in case if we are getting data from multiple places and we wanted to change the key or something so that we can identify it differently - url: string, // url from where data need to be fetched -} -type singleStatDataWidgetData = { - title: string, // title of the single stat - tooltipText: string, // tooltip of the single stat - deltaTooltipComponent: string => React.element, // delta tooltip hover compoment of the single stat - statType: AnalyticsTypesUtils.metricsType, // wheather the metric which we are showing is a Rate, Volume, Latency - showDelta: bool, // wheather to show the delta or not -} - -type singleStatEntity<'a> = { - dataFetcherObj: array>, - source: string, // from which source data has to be fetched - modeKey: string, // the key of mode dropdown i.e by order mode or by txn mode - filterKeys: array, // filter keys the keys of filter which is stored in the url - startTimeFilterKey: string, // end time filter key which we store in url(can be moved to parent level) - endTimeFilterKey: string, // end time filter key which we store in url (can be moved to parent level) - moduleName: string, // just the string module name which should be same across one module (later can be moved to the parent level) - customFilterKey: string, // customFilterKey the key which is used in url for the customfilter - metrixMapper: 'a => string, // it will map the current key with the the key which get from the api - getStatDetails: ( - 'a, - 'a => string, - dataState, - dataState, - dataState, - ) => singleStatDataWidgetData, -} diff --git a/src/components/CustomCharts/HighchartBarChart.res b/src/components/CustomCharts/HighchartBarChart.res index 4c9d790bc..81a46ab95 100644 --- a/src/components/CustomCharts/HighchartBarChart.res +++ b/src/components/CustomCharts/HighchartBarChart.res @@ -69,122 +69,3 @@ module HighBarChart1D = { } } } -open LineChartUtils -module HighBarChart2D = { - @react.component - let make = ( - ~rawData: array, - ~groupKey, - ~isHrizonatalBar: bool=true, - ~selectedMetrics: LineChartUtils.metricsConfig, - ) => { - let (groupBy1, groupBy2) = switch groupKey { - | Some(value) => ( - value->Belt.Array.get(0)->Belt.Option.getWithDefault(""), - value->Belt.Array.get(1)->Belt.Option.getWithDefault(""), - ) - | None => ("", "") - } - let (groupBy1, groupBy2) = (groupBy2, groupBy1) - let chartDictData = Js.Dict.empty() - rawData->Js.Array2.forEach(item => { - let dict = item->LogicUtils.getDictFromJsonObject - let groupBy = - dict->LogicUtils.getString( - groupBy1, - Js.Dict.get(dict, groupBy1) - ->Belt.Option.getWithDefault(""->Js.Json.string) - ->Js.Json.stringify, - ) - let groupBy = groupBy === "" ? "NA" : groupBy - - chartDictData->appendToDictValue(groupBy, item) - }) - let isMobileView = MatchMedia.useMobileChecker() - -
- { - let chartArr = { - chartDictData - ->Js.Dict.entries - ->Js.Array2.mapi((item, index) => { - let (_, value) = item -
- -
- }) - } - if isMobileView { - - } else { - chartArr->React.array - } - } -
- } -} - -module HighBarChart3D = { - @react.component - let make = ( - ~rawData: array, - ~groupKey, - ~isHrizonatalBar: bool=true, - ~selectedMetrics: LineChartUtils.metricsConfig, - ) => { - let (groupBy1, groupBy2, groupby3) = switch groupKey { - | Some(value) => ( - value->Belt.Array.get(0)->Belt.Option.getWithDefault(""), - value->Belt.Array.get(1)->Belt.Option.getWithDefault(""), - value->Belt.Array.get(2)->Belt.Option.getWithDefault(""), - ) - | None => ("", "", "") - } - let (groupBy1, groupBy2, groupby3) = (groupBy2, groupby3, groupBy1) - - let chartDictData = Js.Dict.empty() - rawData->Js.Array2.forEach(item => { - let dict = item->LogicUtils.getDictFromJsonObject - let groupBy1 = - dict->LogicUtils.getString( - groupBy1, - Js.Dict.get(dict, groupBy1) - ->Belt.Option.getWithDefault(""->Js.Json.string) - ->Js.Json.stringify, - ) - let groupBy1 = groupBy1 === "" ? "NA" : groupBy1 - let groupBy2 = - dict->LogicUtils.getString( - groupBy2, - Js.Dict.get(dict, groupBy2) - ->Belt.Option.getWithDefault(""->Js.Json.string) - ->Js.Json.stringify, - ) - let groupBy2 = groupBy2 === "" ? "NA" : groupBy2 - - chartDictData->appendToDictValue(groupBy1 ++ " / " ++ groupBy2, item) - }) - let isMobileView = MatchMedia.useMobileChecker() - -
- { - let chartArr = { - chartDictData - ->Js.Dict.entries - ->Js.Array2.mapi((item, index) => { - let (_, value) = item - -
- -
- }) - } - if isMobileView { - - } else { - chartArr->React.array - } - } -
- } -} diff --git a/src/components/CustomCharts/HighchartSparkLineChart.res b/src/components/CustomCharts/HighchartSparkLineChart.res deleted file mode 100644 index e48503dcc..000000000 --- a/src/components/CustomCharts/HighchartSparkLineChart.res +++ /dev/null @@ -1,108 +0,0 @@ -external objToJson: {..} => Js.Json.t = "%identity" - -type highcharts - -@module("highcharts") external highchartsModule: highcharts = "default" - -@react.component -let make = (~data, ~height=500, ~width=2600, ~axisVisible=false, ~lineChartOptions=?) => { - let defaultOptions = switch lineChartOptions { - | Some(val) => val - | _ => - { - "chart": { - "margin": [2, 0, 2, 0], - "borderWidth": 0, - "type": "line", - "width": width, - "height": height, - "style": { - "overflow": "visible", - }, - "backgroundColor": Js.Json.null, - "skipClone": false, - }, - "title": { - "text": "", - }, - "credits": { - "enabled": false, - }, - "xAxis": { - "labels": { - "enabled": false, - }, - "visible": false, - "title": { - "text": "", - }, - "startOnTick": false, - "endOnTick": false, - "tickPositions": [0], - }, - "yAxis": { - "labels": { - "enabled": false, - }, - "title": { - "text": "", - }, - "startOnTick": false, - "endOnTick": false, - "tickPositions": [], - }, - "legend": { - "enabled": false, - }, - "plotOptions": { - "series": { - "zones": [ - { - "value": 0, - "color": "#FF0000", - }, - ], - "lineColor": "#00FF00", - "animation": true, - "lineWidth": 2, - "shadow": false, - "states": { - "hover": { - "lineWidth": 3, - }, - }, - "marker": { - "radius": 1, - "states": { - "hover": { - "radius": 2, - }, - }, - }, - }, - "column": { - "negativeColor": "red", - "borderColor": "silver", - }, - }, - "series": [ - { - "data": data, - "pointStart": 0, - "color": Some("#006ae5"), - "fillColor": { - "linearGradient": (0, 0, 1, 1), - }, - }, - ], - "tooltip": { - "headerFormat": ``, - "pointFormat": ` Iteration Count {point.x} : Diff {point.y}% `, - "hideDelay": 0, - "outside": true, - "shared": true, - }, - }->objToJson - } - -} diff --git a/src/components/CustomCharts/HighchartTimeSeriesChart.res b/src/components/CustomCharts/HighchartTimeSeriesChart.res index e98402972..272474225 100644 --- a/src/components/CustomCharts/HighchartTimeSeriesChart.res +++ b/src/components/CustomCharts/HighchartTimeSeriesChart.res @@ -5,7 +5,7 @@ open DictionaryUtils external toJson: 'a => Js.Json.t = "%identity" -type ele = {childElementCount: int} +type ele external toElement: Dom.element => ele = "%identity" @send diff --git a/src/components/CustomCharts/LineChartUtils.res b/src/components/CustomCharts/LineChartUtils.res index a2c0d8281..fa44abd58 100644 --- a/src/components/CustomCharts/LineChartUtils.res +++ b/src/components/CustomCharts/LineChartUtils.res @@ -257,14 +257,6 @@ let appendToDictValue = (dict, key, value) => { dict->Js.Dict.set(key, updatedValue) } -let addToDictValueInt = (dict, key, value) => { - let updatedValue = switch dict->Js.Dict.get(key) { - | Some(val) => val + value - | None => value - } - dict->Js.Dict.set(key, updatedValue) -} - let addToDictValueFloat = (dict, key, value) => { let updatedValue = switch dict->Js.Dict.get(key) { | Some(val) => val +. value diff --git a/src/components/custom-icons/LottieFiles.res b/src/components/custom-icons/LottieFiles.res index a50291fbe..d358f2a34 100644 --- a/src/components/custom-icons/LottieFiles.res +++ b/src/components/custom-icons/LottieFiles.res @@ -8,10 +8,6 @@ let exitCheckBox = "uncheckbox.json" let enterSearchCross = "enterCross.json" let exitSearchCross = "exitCross.json" -//mettle -let enterCheckBoxPurple = "checkboxPurple.json" -let exitCheckBoxPurple = "uncheckboxPurple.json" - let lottieDict: Js.Dict.t = Js.Dict.empty() let useLottieJson = lottieFileName => { diff --git a/src/components/custom-icons/NoDataIllustration.res b/src/components/custom-icons/NoDataIllustration.res deleted file mode 100644 index c96c39c8e..000000000 --- a/src/components/custom-icons/NoDataIllustration.res +++ /dev/null @@ -1,6 +0,0 @@ -@react.component -let make = () => { - let urlPrefix = LogicUtils.useUrlPrefix() - - -} diff --git a/src/entryPoints/hyperswitch/HyperSwitchApp.res b/src/entryPoints/hyperswitch/HyperSwitchApp.res index 00317c5f0..65c6e216f 100644 --- a/src/entryPoints/hyperswitch/HyperSwitchApp.res +++ b/src/entryPoints/hyperswitch/HyperSwitchApp.res @@ -213,7 +213,7 @@ let make = () => {
+ className={`px-4 py-2 rounded whitespace-nowrap text-fs-13 ${modeStyles} font-semibold`}> {modeText->React.string}
} diff --git a/src/screens/HyperSwitch/FraudAndRisk/FRMIntegrationFields.res b/src/screens/HyperSwitch/FraudAndRisk/FRMIntegrationFields.res index b971318c1..ca20884e5 100644 --- a/src/screens/HyperSwitch/FraudAndRisk/FRMIntegrationFields.res +++ b/src/screens/HyperSwitch/FraudAndRisk/FRMIntegrationFields.res @@ -135,7 +135,7 @@ module IntegrationFieldsForm = { {selectedFRMInfo.connectorFields ->Array.mapWithIndex((field, index) => { - let parse = field.encodeToBase64 ? base64Parse : Parsers.leadingSpaceStrParser + let parse = field.encodeToBase64 ? base64Parse : leadingSpaceStrParser let format = field.encodeToBase64 ? Some(base64Format) : None
Belt.Int.toString}> diff --git a/src/screens/HyperSwitch/FraudAndRisk/FRMSummary.res b/src/screens/HyperSwitch/FraudAndRisk/FRMSummary.res index d9cd9fcb1..25cf6560a 100644 --- a/src/screens/HyperSwitch/FraudAndRisk/FRMSummary.res +++ b/src/screens/HyperSwitch/FraudAndRisk/FRMSummary.res @@ -83,8 +83,7 @@ let make = (~initialValues, ~currentStep, ~setCurrentStep, ~isUpdateFlow) => { showToast(~message=`Successfully Saved the Changes`, ~toastType=ToastSuccess, ()) RescriptReactRouter.push("/fraud-risk-management") } catch { - | Js.Exn.Error(e) => - let _err = Js.Exn.message(e)->Belt.Option.getWithDefault("Failed to Disable connector!") + | Js.Exn.Error(_) => showToast(~message=`Failed to Disable connector!`, ~toastType=ToastError, ()) } } diff --git a/src/screens/HyperSwitch/FraudAndRisk/FRMUtils.res b/src/screens/HyperSwitch/FraudAndRisk/FRMUtils.res index d27b08b9d..1c8228f7e 100644 --- a/src/screens/HyperSwitch/FraudAndRisk/FRMUtils.res +++ b/src/screens/HyperSwitch/FraudAndRisk/FRMUtils.res @@ -4,6 +4,11 @@ open FRMTypes @val external btoa: string => string = "btoa" @val external atob: string => string = "atob" +let leadingSpaceStrParser = (. ~value, ~name as _) => { + let str = value->Js.Json.decodeString->Belt.Option.getWithDefault("") + str->Js.String2.replaceByRe(%re("/^[\s]+/"), "")->Js.Json.string +} + let base64Parse = (. ~value, ~name as _) => { value->Js.Json.decodeString->Belt.Option.getWithDefault("")->btoa->Js.Json.string } @@ -19,7 +24,7 @@ let toggleDefaultStyle = "mb-2 relative inline-flex flex-shrink-0 h-6 w-12 borde let accordionDefaultStyle = "border pointer-events-none inline-block h-3 w-3 rounded-full bg-white dark:bg-white shadow-lg transform ring-0 transition ease-in-out duration-200" let size = "w-14 h-14 rounded-full" -let generateInitialValuesDict = (~selectedFRMInfo, ~isLiveMode=false, ()) => { +let generateInitialValuesDict = (~selectedFRMInfo, ~isLiveMode, ()) => { let frmAccountDetailsDict = [("auth_type", selectedFRMInfo.name->getFRMAuthType->Js.Json.string)] ->Js.Dict.fromArray @@ -110,7 +115,7 @@ let getConnectorConfig = connectors => { configDict } -let filterList = (items, ~removeFromList=FRMPlayer, ()) => { +let filterList = (items, ~removeFromList, ()) => { open LogicUtils items->Js.Array2.filter(dict => { let isConnector = dict->getString("connector_type", "") !== "payment_vas" diff --git a/src/screens/HyperSwitch/HSMixPanel.res b/src/screens/HyperSwitch/HSMixPanel.res index 7141927da..3b03952e0 100644 --- a/src/screens/HyperSwitch/HSMixPanel.res +++ b/src/screens/HyperSwitch/HSMixPanel.res @@ -43,14 +43,7 @@ let useSendEvent = () => { | Local => "localhost" } - let trackApi = async ( - ~email, - ~merchantId, - ~description: option=None, - ~requestId, - ~statusCode, - ~event, - ) => { + let trackApi = async (~email, ~merchantId, ~description, ~requestId, ~statusCode, ~event) => { let body = { "event": event, "properties": { diff --git a/src/screens/HyperSwitch/HSwitchUtils.res b/src/screens/HyperSwitch/HSwitchUtils.res index fcd548208..509b29e30 100644 --- a/src/screens/HyperSwitch/HSwitchUtils.res +++ b/src/screens/HyperSwitch/HSwitchUtils.res @@ -16,12 +16,6 @@ type browserDetailsObject = { let feedbackModalOpenCountForConnectors = 4 -let feedbackModalOpenCountForRouting = 2 - -let milestoneShowingCardCountForConnectors = 3 - -let milestoneShowingCardCountForRouting = 2 - external objToJson: {..} => Js.Json.t = "%identity" let errorClass = "text-sm leading-4 font-medium text-start ml-1 mt-2" diff --git a/src/screens/HyperSwitch/Sidebar/SidebarProvider.res b/src/screens/HyperSwitch/Sidebar/SidebarProvider.res index 88b9cafc4..1bd9e663d 100644 --- a/src/screens/HyperSwitch/Sidebar/SidebarProvider.res +++ b/src/screens/HyperSwitch/Sidebar/SidebarProvider.res @@ -22,11 +22,6 @@ let defaultValue = { let defaultContext = React.createContext(defaultValue) module Provider = { - let makeProps = (~value, ~children, ()) => - { - "value": value, - "children": children, - } let make = React.Context.provider(defaultContext) } diff --git a/src/screens/HyperSwitch/StripePlusPaypal/StripePlusPaypalUtils.res b/src/screens/HyperSwitch/StripePlusPaypal/StripePlusPaypalUtils.res index 369db35ee..bd4e35433 100644 --- a/src/screens/HyperSwitch/StripePlusPaypal/StripePlusPaypalUtils.res +++ b/src/screens/HyperSwitch/StripePlusPaypal/StripePlusPaypalUtils.res @@ -48,7 +48,7 @@ let getSidebarOptionsForStripePayalIntegration: ( link: "", }, { - title: "Test a Payment", + title: "Try Hyperswitch checkout", status: Boolean(enumValue.sPTestPayment)->getStatusValue( #sPTestPayment, currentPageStateEnum, diff --git a/src/screens/HyperSwitch/SwitchMerchant/SwitchMerchant.res b/src/screens/HyperSwitch/SwitchMerchant/SwitchMerchant.res index 35dc9bd1d..be38e39aa 100644 --- a/src/screens/HyperSwitch/SwitchMerchant/SwitchMerchant.res +++ b/src/screens/HyperSwitch/SwitchMerchant/SwitchMerchant.res @@ -121,7 +121,7 @@ module ExternalUser = { {menuProps =>
+ className="inline-flex whitespace-pre leading-5 justify-center text-sm font-medium px-4 py-2 font-medium rounded-md hover:bg-opacity-80 bg-white border"> {buttonProps => { <> {selectedMerchantID->React.string} diff --git a/src/utils/GlobalVars.res b/src/utils/GlobalVars.res index b8bd5bc1b..a768d486c 100644 --- a/src/utils/GlobalVars.res +++ b/src/utils/GlobalVars.res @@ -8,8 +8,3 @@ type appEnv = [#production | #sandbox | #integration | #development] let isLocalhost = Window.Location.hostname === "localhost" || Window.Location.hostname === "127.0.0.1" - -let dashboardAppUrlPrefix = switch Window.globalUrlPrefix { -| Some(prefix) => prefix === "" ? "/api" : prefix -| None => "/api" -} diff --git a/src/utils/JsonFlattenUtils.res b/src/utils/JsonFlattenUtils.res index 95ce1f84c..a7f398088 100644 --- a/src/utils/JsonFlattenUtils.res +++ b/src/utils/JsonFlattenUtils.res @@ -1,5 +1,3 @@ -open LogicUtils - external toNullable: Js.Json.t => Js.Nullable.t = "%identity" let rec flattenObject = (obj, addIndicatorForObject) => { @@ -39,127 +37,6 @@ let rec flattenObject = (obj, addIndicatorForObject) => { newDict } -let rec flattenObjectWithStringifiedJson = ( - obj, - addIndicatorForObject, - keepParent, - includeKeys, -) => { - let newDict = Js.Dict.empty() - switch obj->Js.Json.decodeObject { - | Some(obj) => - obj - ->Js.Dict.entries - ->Js.Array2.forEach(entry => { - let (key, value) = entry - - if value->toNullable->Js.Nullable.isNullable { - Js.Dict.set(newDict, key, value) - } else if includeKeys->Js.Array2.includes(key)->not { - Js.Dict.set(newDict, key, value) - } else { - switch value - ->Js.Json.decodeString - ->Belt.Option.getWithDefault("") - ->LogicUtils.safeParse - ->Js.Json.decodeObject { - | Some(_valueObj) => { - if addIndicatorForObject { - Js.Dict.set(newDict, key, Js.Json.object_(Js.Dict.empty())) - } - - let flattenedSubObj = flattenObjectWithStringifiedJson( - value->Js.Json.decodeString->Belt.Option.getWithDefault("")->LogicUtils.safeParse, - addIndicatorForObject, - keepParent, - includeKeys, - ) - - flattenedSubObj - ->Js.Dict.entries - ->Js.Array2.forEach(subEntry => { - let (subKey, subValue) = subEntry - let keyN = keepParent ? `${key}.${subKey}` : subKey - Js.Dict.set(newDict, keyN, subValue) - }) - } - - | None => Js.Dict.set(newDict, key, value) - } - } - }) - | _ => () - } - newDict -} -let rec flatten = (obj, addIndicatorForObject) => { - let newDict = Js.Dict.empty() - switch obj->Js.Json.classify { - | JSONObject(obj) => - obj - ->Js.Dict.entries - ->Js.Array2.forEach(entry => { - let (key, value) = entry - - if value->toNullable->Js.Nullable.isNullable { - Js.Dict.set(newDict, key, value) - } else { - switch value->Js.Json.classify { - | JSONObject(_valueObjDict) => { - if addIndicatorForObject { - Js.Dict.set(newDict, key, Js.Json.object_(Js.Dict.empty())) - } - - let flattenedSubObj = flatten(value, addIndicatorForObject) - - flattenedSubObj - ->Js.Dict.entries - ->Js.Array2.forEach(subEntry => { - let (subKey, subValue) = subEntry - Js.Dict.set(newDict, `${key}.${subKey}`, subValue) - }) - } - - | JSONArray(dictArray) => { - let stringArray = [] - let arrayArray = [] - dictArray->Js.Array2.forEachi((item, index) => { - switch item->Js.Json.classify { - | JSONString(_str) => - let _ = stringArray->Js.Array2.push(item) - | JSONObject(_obj) => { - let flattenedSubObj = flatten(item, addIndicatorForObject) - flattenedSubObj - ->Js.Dict.entries - ->Js.Array2.forEach( - subEntry => { - let (subKey, subValue) = subEntry - Js.Dict.set(newDict, `${key}[${index->string_of_int}].${subKey}`, subValue) - }, - ) - } - - | _ => - let _ = arrayArray->Js.Array2.push(item) - } - }) - if stringArray->Js.Array2.length > 0 { - Js.Dict.set(newDict, key, stringArray->Js.Json.array) - } - if arrayArray->Js.Array2.length > 0 { - Js.Dict.set(newDict, key, arrayArray->Js.Json.array) - } - } - - | _ => Js.Dict.set(newDict, key, value) - } - } - }) - | _ => () - } - newDict -} - let rec setNested = (dict, keys, value) => { if keys->Js.Array.length === 0 { () @@ -199,117 +76,3 @@ let unflattenObject = obj => { } newDict } - -let rec setNestedArr = (dict, keys, value) => { - if keys->Js.Array.length === 0 { - () - } else if keys->Js.Array.length === 1 { - if keys[0]->Belt.Option.getWithDefault("")->Js.String2.includes("[") { - let key = - ( - keys[0]->Belt.Option.getWithDefault("")->Js.String2.split("[") - )[0]->Belt.Option.getWithDefault("") - let indx = - Js.String2.substring( - keys[0]->Belt.Option.getWithDefault(""), - ~from=keys[0]->Belt.Option.getWithDefault("")->Js.String2.indexOf("[") + 1, - ~to_=keys[0]->Belt.Option.getWithDefault("")->Js.String2.indexOf("]"), - )->getIntFromString(0) - let valArr = switch Js.Dict.get(dict->getDictFromJsonObject, key) { - | Some(jsonArray) => - switch jsonArray->Js.Json.decodeArray { - | Some(arr) => { - while arr->Js.Array2.length < indx { - arr->Js.Array2.push(Js.Json.null)->ignore - } - arr - } - - | None => [] - } - | None => { - let arr = [] - while arr->Js.Array2.length < indx { - arr->Js.Array2.push(Js.Json.null)->ignore - } - - arr - } - } - - Js.Dict.set( - dict->getDictFromJsonObject, - key, - valArr->Js.Array2.concat([value])->Js.Json.array, - ) - } else { - Js.Dict.set(dict->getDictFromJsonObject, keys[0]->Belt.Option.getWithDefault(""), value) - } - } else if keys[0]->Belt.Option.getWithDefault("")->Js.String2.includes("[") { - let key = - ( - keys[0]->Belt.Option.getWithDefault("")->Js.String2.split("[") - )[0]->Belt.Option.getWithDefault("") - let indx = - Js.String2.substring( - keys[0]->Belt.Option.getWithDefault(""), - ~from=keys[0]->Belt.Option.getWithDefault("")->Js.String2.indexOf("[") + 1, - ~to_=keys[0]->Belt.Option.getWithDefault("")->Js.String2.indexOf("]"), - )->getIntFromString(0) - let subDict = switch Js.Dict.get(dict->getDictFromJsonObject, key) { - | Some(jsonArray) => - switch jsonArray->Js.Json.decodeArray { - | Some(arr) => { - while arr->Js.Array2.length < indx + 1 { - arr->Js.Array2.push(Js.Json.null)->ignore - } - arr[indx]->Belt.Option.getWithDefault(Js.Json.null) - } - - | None => dict - } - | None => { - let arr = [] - while arr->Js.Array2.length < indx + 1 { - arr->Js.Array2.push(Js.Json.null)->ignore - } - Js.Dict.set(dict->getDictFromJsonObject, key, arr->Js.Json.array) - arr[indx]->Belt.Option.getWithDefault(Js.Json.null) - } - } - let remainingKeys = keys->Js.Array2.sliceFrom(1) - setNestedArr(subDict, remainingKeys, value) - } else { - let key = keys[0]->Belt.Option.getWithDefault("") - let subDict = switch Js.Dict.get(dict->getDictFromJsonObject, key) { - | Some(json) => - switch json->Js.Json.decodeObject { - | Some(obj) => obj->Js.Json.object_ - | None => dict - } - | None => { - let subDict = Js.Dict.empty() - Js.Dict.set(dict->getDictFromJsonObject, key, subDict->Js.Json.object_) - subDict->Js.Json.object_ - } - } - let remainingKeys = keys->Js.Array2.sliceFrom(1) - setNestedArr(subDict, remainingKeys, value) - } -} - -let unflatten = obj => { - let newDict = Js.Dict.empty() - - switch obj->Js.Json.decodeObject { - | Some(dict) => - dict - ->Js.Dict.entries - ->Js.Array2.forEach(entry => { - let (key, value) = entry - setNestedArr(newDict->Js.Json.object_, key->Js.String2.split("."), value) - }) - | None => () - } - newDict -} diff --git a/src/utils/LogicUtils.res b/src/utils/LogicUtils.res index e9c5ecb9f..f3039cd6d 100644 --- a/src/utils/LogicUtils.res +++ b/src/utils/LogicUtils.res @@ -22,16 +22,6 @@ let stripV4 = path => { | _ => path } } -let useDefaultArr = json => { - React.useMemo1(() => { - json - ->Js.Json.decodeObject - ->Belt.Option.flatMap(dict => dict->Js.Dict.get("default")) - ->Belt.Option.flatMap(Js.Json.decodeArray) - ->Belt.Option.getWithDefault([]) - ->Belt.Array.keepMap(Js.Json.decodeString) - }, [json]) -} // parse a string into json and return optional json let safeParseOpt = st => { @@ -65,8 +55,6 @@ and logic = { logics: logics, } -type time = {day: string, start: string, end: string} - let getDictFromJsonObject = json => { switch json->Js.Json.decodeObject { | Some(dict) => dict @@ -115,17 +103,6 @@ let getNameFromEmail = email => { ->Js.Array2.joinWith(" ") } -let useValidateEmail = str => { - !Js.Re.test_( - %re(`/^(([^<>()[\]\.,;:\s@"]+(\.[^<>()[\]\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/`), - str->Js.String.trim, - ) -} - -let doSetState = (value, setter) => { - setter(_ => value) -} - let getOptionString = (dict, key) => { dict->Js.Dict.get(key)->Belt.Option.flatMap(Js.Json.decodeString) } @@ -134,10 +111,6 @@ let getString = (dict, key, default) => { getOptionString(dict, key)->Belt.Option.getWithDefault(default) } -let getStrVal = (~default="", dict, key) => { - getOptionString(dict, key)->Belt.Option.getWithDefault(default) -} - let getStringFromJson = (json: Js.Json.t, default) => { json->Js.Json.decodeString->Belt.Option.getWithDefault(default) } @@ -173,19 +146,10 @@ let getStrArray = (dict, key) => { ->Belt.Option.getWithDefault([]) ->Belt.Array.map(json => json->Js.Json.decodeString->Belt.Option.getWithDefault("")) } -let getBoolArray = (dict, key, default) => { - dict - ->getOptionalArrayFromDict(key) - ->Belt.Option.getWithDefault([]) - ->Belt.Array.map(json => json->Js.Json.decodeBoolean->Belt.Option.getWithDefault(default)) -} let getStrArrayFromJsonArray = jsonArr => { jsonArr->Belt.Array.keepMap(Js.Json.decodeString) } -let getIntArrayFromJsonArray = jsonArr => { - jsonArr->Belt.Array.keepMap(Js.Json.decodeNumber)->Js.Array2.map(Belt.Float.toInt) -} let getStrArryFromJson = arr => { arr @@ -198,9 +162,6 @@ let getOptionStrArrayFromJson = json => { json->Js.Json.decodeArray->Belt.Option.map(getStrArrayFromJsonArray) } -let getOptionIntArrayFromJson = json => { - json->Js.Json.decodeArray->Belt.Option.map(getIntArrayFromJsonArray) -} let getStrArrayFromDict = (dict, key, default) => { dict ->Js.Dict.get(key) @@ -212,10 +173,6 @@ let getOptionStrArrayFromDict = (dict, key) => { dict->Js.Dict.get(key)->Belt.Option.flatMap(getOptionStrArrayFromJson) } -let getOptionIntArrayFromDict = (dict, key) => { - dict->Js.Dict.get(key)->Belt.Option.flatMap(getOptionIntArrayFromJson) -} - let getNonEmptyString = str => { if str === "" { None @@ -232,40 +189,6 @@ let getNonEmptyArray = arr => { } } -let getReturnArray = (dict, key) => { - switch Js.Dict.get(dict, key) { - | Some(value) => - switch value->Js.Json.decodeArray { - | Some(jsonArr) => jsonArr->Js.Array2.reduce((acc, jsonItem) => { - switch jsonItem->Js.Json.decodeArray { - | Some(percentTuple) => - if percentTuple->Js.Array2.length === 2 { - let percent = switch Js.Json.decodeNumber( - percentTuple[0]->Belt.Option.getWithDefault(Js.Json.null), - ) { - | Some(num) => num->Belt.Float.toInt - | None => 0 - } - - let priorityArr = switch percentTuple[1] - ->Belt.Option.getWithDefault(Js.Json.null) - ->getOptionStrArrayFromJson { - | Some(x) => x - | None => [] - } - - let _ = Js.Array2.push(acc, (percent, priorityArr)) - } - | None => () - } - acc - }, [])->Some - | None => None - } - | None => None - } -} - let getOptionBool = (dict, key) => { dict->Js.Dict.get(key)->Belt.Option.flatMap(Js.Json.decodeBoolean) } @@ -312,10 +235,6 @@ let getFloatFromString = (str, default) => { } } -let getFloatFromOptionString = (str: option, default) => { - str->Belt.Option.getWithDefault("")->Belt.Float.fromString->Belt.Option.getWithDefault(default) -} - let getIntFromJson = (json, default) => { switch json->Js.Json.classify { | JSONString(str) => getIntFromString(str, default) @@ -380,382 +299,6 @@ let getObj = (dict, key, default) => { ->Belt.Option.getWithDefault(default) } -let getTime = (dict, key) => { - switch dict->Js.Dict.get(key) { - | Some(json) => { - let timeStr = getStringFromJson(json, "") - let (from, day) = - timeStr->Js.String2.length > 11 ? (4, Js.String.slice(~from=0, ~to_=3, timeStr)) : (0, "") - let time = timeStr->Js.String2.split("-")->Js.Array2.map(t => Js.String.sliceToEnd(~from, t)) - - if time->Js.Array2.length !== 2 { - {day, start: "00:00", end: "00:00"} - } else { - { - day, - start: time[0]->Belt.Option.getWithDefault("00:00"), - end: time[1]->Belt.Option.getWithDefault("00:00"), - } - } - } - - | None => {day: "", start: "", end: ""} - } -} - -let convertStringToFile = (~contentType="", str) => { - [str->Webapi__Blob.stringToBlobPart]->Webapi__File.makeWithOptions( - "", - Webapi__File.makeFilePropertyBag(~_type=contentType, ()), - ) -} - -let convertToMin = time => { - let t = - time - ->Js.String2.split(":") - ->Js.Array2.map(t => t->Belt.Int.fromString->Belt.Option.getWithDefault(0)) - t->Js.Array2.length === 2 - ? t[0]->Belt.Option.getWithDefault(0) * 60 + t[1]->Belt.Option.getWithDefault(0) - : 0 -} - -let parseCondition = condJson => { - switch condJson->Js.Json.decodeObject { - | Some(condDict) => { - let not = getBool(condDict, "not", false) - switch getOptionString(condDict, "key") { - | Some(key) => - switch getOptionStrArrayFromDict(condDict, "vals") { - | Some(vals) => Some(ComparisionCheck({key, not, vals})) - | None => None - } - | None => None - } - } - - | None => None - } -} - -let rec parseLogicsJsonArr = logicsJson => { - switch logicsJson->Js.Json.decodeArray { - | Some(logicsArr) => logicsArr->Js.Array2.reduce((acc, logicJson) => { - switch logicJson->Js.Json.decodeObject { - | Some(logicObj) => { - let condition = switch Js.Dict.get(logicObj, "cond") { - | Some(condJson) => - switch condJson->parseCondition { - | Some(condition) => condition - | None => NoCondition - } - - | None => NoCondition - } - switch Js.Dict.get(logicObj, "logics") { - | Some(logicsJson) => { - let subLogics = logicsJson->parseLogicsJsonArr - let logic = { - condition, - logics: subLogics, - } - let _ = Js.Array2.push(acc, logic) - } - - | None => () - } - - switch getReturnArray(logicObj, "return") { - | Some(returnArr) => { - let logic = { - condition, - logics: Return(returnArr), - } - let _ = Js.Array2.push(acc, logic) - } - - | None => () - } - } - - | None => () - } - acc - }, [])->IfElse - | None => Return([]) - } -} - -let useLogics = json => { - React.useMemo1(() => { - switch json->Js.Json.decodeObject { - | Some(obj) => - switch Js.Dict.get(obj, "logics") { - | Some(logicsJson) => logicsJson->parseLogicsJsonArr - | None => Return([]) - } - | None => Return([]) - } - }, [json]) -} - -let paddingChar = "\t" - -let rec printLogics = (logics, defaultArr, indentLevel) => { - let padding = Belt.Array.make(indentLevel, paddingChar)->Js.Array.joinWith("", _) - let isEmpty = switch logics { - | Return(strArr) => strArr->Js.Array2.length === 0 - | IfElse(logicsArr) => logicsArr->Js.Array2.length === 0 - } - - if isEmpty { - `${padding}//` - } else { - switch logics { - | Return(returArr) => { - let (overallPercent, code) = returArr->Js.Array.reducei((acc, info, i) => { - let (totalSoFar, codeSoFar) = acc - let (percent, strArr) = info - - let newTotal = totalSoFar + percent - let percentStr = newTotal->string_of_int - let newArr = strArr->Js.Array2.map(x => `"${x}"`)->Js.Array2.joinWith(", ") - - let prefix = if i === 0 { - `${padding}if` - } else { - ` else if` - } - let predicate = if newTotal === 100 { - ` else` - } else { - `${prefix} (percent <= ${percentStr})` - } - - let newCode = - codeSoFar ++ - `${predicate} {\n` ++ - `${padding}${paddingChar}priorities = [${newArr}]\n` ++ - `${padding}}` - - (totalSoFar + percent, newCode) - }, (0, ""), _) - - if overallPercent < 100 { - let strArr = defaultArr - let newArr = strArr->Js.Array2.map(x => `"${x}"`)->Js.Array2.joinWith(", ") - let newCode = - code ++ - ` else {\n` ++ - `${padding}${paddingChar}priorities = [${newArr}]\n` ++ - `${padding}}` - newCode - } else { - code - } - } - - | IfElse(logicsArr) => - logicsArr - ->Js.Array2.mapi((logic, i) => { - let conditionStr = switch logic.condition { - | NoCondition => "" - | NumericCondition(numericComparisionType) => { - let key = numericComparisionType.key - let validRules = numericComparisionType.validRules - - validRules - ->Js.Array2.map(rule => - switch rule { - | LessThan(num, inclusive) => { - let op = inclusive ? "<=" : "<" - `${key} ${op} ${num->string_of_int}` - } - - | GreaterThan(num, inclusive) => { - let op = inclusive ? ">=" : ">" - `${key} ${op} ${num->string_of_int}` - } - - | EqualTo(nums) => { - let numsStr = nums->Js.Array2.map(string_of_int)->Js.Array2.joinWith(", ") - `[${numsStr}].contains(${key})` - } - } - ) - ->Js.Array2.joinWith("\n") - } - - | ComparisionCheck(conditionCheck) => { - let key = conditionCheck.key - let vals = conditionCheck.vals - let _not = conditionCheck.not - - if vals->Js.Array2.length === 1 { - `${key} == "${vals[0]->Belt.Option.getWithDefault("")}"` - } else { - let valsArrStr = vals->Js.Array2.map(x => `"${x}"`)->Js.Array2.joinWith(", ") - `[${valsArrStr}].contains(${key})` - } - } - } - - let ifType = if i === 0 { - `${padding}if` - } else { - " else if" - } - - let start = switch logic.condition { - | NoCondition => " else" - | NumericCondition(_numericComparisionType) => `${ifType} (${conditionStr})` - | ComparisionCheck(_conditionCheck) => `${ifType} (${conditionStr})` - } - - let blockContent = printLogics(logic.logics, defaultArr, indentLevel + 1) - - `${start} { -${blockContent} -${padding}}` - }) - ->Js.Array2.joinWith("") - } - } -} - -let printableStrArray = strArray => { - strArray->Js.Array2.map(Js.Json.string)->Js.Json.array->Js.Json.stringify -} - -let getCode = (defaultArr, logics) => { - ` -def priorities = ${defaultArr->printableStrArray} -def randomPercent = System.currentTimeMillis() % 100 - - -${printLogics(logics, defaultArr, 0)} - -setGatewayPriority(priorities) - - ` -} - -let rec getLogicArrJson = (logicArr: array) => { - logicArr - ->Js.Array2.map(logic => { - let dict = Js.Dict.empty() - switch logic.condition { - | NoCondition => () - | NumericCondition(numericCond) => { - let condDict = Js.Dict.empty() - Js.Dict.set(condDict, "key", numericCond.key->Js.Json.string) - Js.Dict.set( - condDict, - "vals", - numericCond.validRules - ->Js.Array2.map(rule => { - switch rule { - | LessThan(int, bool) => - [ - (bool ? "lte" : "lt")->Js.Json.string, - int->Belt.Float.fromInt->Js.Json.number, - ]->Js.Json.array - | GreaterThan(int, bool) => - [ - (bool ? "gte" : "gt")->Js.Json.string, - int->Belt.Float.fromInt->Js.Json.number, - ]->Js.Json.array - | EqualTo(nums) => - { - let arr = ["eq"->Js.Json.string] - nums->Js.Array2.forEach( - num => { - let _ = Js.Array2.push(arr, num->Belt.Float.fromInt->Js.Json.number) - }, - ) - arr - }->Js.Json.array - } - }) - ->Js.Json.array, - ) - - Js.Dict.set(dict, "cond", condDict->Js.Json.object_) - } - - | ComparisionCheck(cond) => { - let condDict = Js.Dict.empty() - Js.Dict.set(condDict, "key", cond.key->Js.Json.string) - Js.Dict.set(condDict, "vals", cond.vals->Js.Array2.map(Js.Json.string)->Js.Json.array) - Js.Dict.set(condDict, "not", cond.not->Js.Json.boolean) - - Js.Dict.set(dict, "cond", condDict->Js.Json.object_) - } - } - switch logic.logics { - | Return(returnArr) => { - let returnArrJson = - returnArr - ->Js.Array2.map(tuple => { - let (percent, strArr) = tuple - - Js.Json.array([ - percent->Belt.Float.fromInt->Js.Json.number, - strArr->Js.Array2.map(Js.Json.string)->Js.Json.array, - ]) - }) - ->Js.Json.array - - Js.Dict.set(dict, "return", returnArrJson) - } - - | IfElse(subLogicArr) => Js.Dict.set(dict, "logics", subLogicArr->getLogicArrJson) - } - dict->Js.Json.object_ - }) - ->Js.Json.array -} - -let getJson = (logics: logics, defaultPriorities) => { - let logicsJson = switch logics { - | Return(_arr) => Js.Json.string("return statement") - | IfElse(arr) => arr->getLogicArrJson - } - - let dict = Js.Dict.empty() - Js.Dict.set(dict, "default", defaultPriorities->Js.Array2.map(Js.Json.string)->Js.Json.array) - Js.Dict.set(dict, "logics", logicsJson) - dict->Js.Json.object_ -} - -@set external setCookie: (DOMUtils.document, string) => unit = "cookie" -@get external getCookie: DOMUtils.document => Js.Nullable.t = "cookie" - -let getCookieVal = key => { - switch getCookie(DOMUtils.document)->Js.Nullable.toOption { - | Some(str) => { - let cookieInfoDict = - str - ->Js.String2.split(";") - ->Js.Array2.map(segment => { - let arr = segment->Js.String2.split("=") - let key = arr->Belt.Array.get(0)->Belt.Option.getWithDefault("")->Js.String2.trim - let value = arr->Belt.Array.get(1)->Belt.Option.getWithDefault("")->Js.String2.trim - (key, value) - }) - ->Js.Dict.fromArray - - cookieInfoDict->Js.Dict.get(key)->Belt.Option.getWithDefault("") - } - - | None => "" - } -} - -let setCookieVal = cookie => { - setCookie(DOMUtils.document, cookie) -} - let getDictFromUrlSearchParams = searchParams => { open Belt.Array searchParams @@ -774,16 +317,6 @@ let getDictFromUrlSearchParams = searchParams => { let setOptionString = (dict, key, optionStr) => optionStr->Belt.Option.mapWithDefault((), str => dict->Js.Dict.set(key, str->Js.Json.string)) -let setOptionFloat = (dict, key, optionFloat) => - optionFloat->Belt.Option.mapWithDefault((), float => - dict->Js.Dict.set(key, float->Js.Json.number) - ) - -let setOptionInt = (dict, key, optionInt) => - optionInt->Belt.Option.mapWithDefault((), int => - dict->Js.Dict.set(key, int->Belt.Float.fromInt->Js.Json.number) - ) - let setOptionBool = (dict, key, optionInt) => optionInt->Belt.Option.mapWithDefault((), bool => dict->Js.Dict.set(key, bool->Js.Json.boolean)) @@ -795,15 +328,6 @@ let setOptionDict = (dict, key, optionDictValue) => dict->Js.Dict.set(key, value->Js.Json.object_) ) -let getJsonFromStringOption = optionStr => - optionStr->Belt.Option.mapWithDefault(Js.Json.null, Js.Json.string) - -let getJsonFromFloatOption = optionFloat => - optionFloat->Belt.Option.mapWithDefault(Js.Json.null, Js.Json.number) - -let getJsonFromIntOption = optionInt => - optionInt->Belt.Option.mapWithDefault(Js.Json.null, v => v->Belt.Float.fromInt->Js.Json.number) - let capitalizeString = str => { Js.String2.toUpperCase(Js.String2.charAt(str, 0)) ++ Js.String2.substringToEnd(str, ~from=1) } @@ -841,43 +365,14 @@ let snakeToTitle = str => { ->Js.Array2.joinWith(" ") } -let urlToTitle = str => { - str - ->Js.String2.split("-") - ->Js.Array2.map(x => { - let firstLetter = x->Js.String2.charAt(0)->Js.String2.toUpperCase - let restLetters = x->Js.String2.substringToEnd(~from=1) - `${firstLetter}${restLetters}` - }) - ->Js.Array2.joinWith(" ") -} - let titleToSnake = str => { str->Js.String2.split(" ")->Js.Array2.map(Js.String2.toLowerCase)->Js.Array2.joinWith("_") } -let getOptionalDictFromDict = (dict, key) => { - switch dict->Js.Dict.get(key) { - | Some(json) => - switch json->Js.Json.decodeObject { - | Some(dict) => Some(dict) - | None => None - } - | None => None - } -} - let getIntFromString = (str, default) => { str->Belt.Int.fromString->Belt.Option.getWithDefault(default) } -let getIntFromOptionString = (optionStr, default) => { - switch optionStr { - | Some(str) => str->getIntFromString(default) - | None => default - } -} - let removeTrailingZero = (numeric_str: string) => { numeric_str->Belt.Float.fromString->Belt.Option.getWithDefault(0.)->Belt.Float.toString } @@ -990,31 +485,6 @@ let numericArraySortComperator = (a, b) => { } } -//agnostic of case -let alphabeticalSortFn = (e1, e2) => { - let e1 = e1->Js.String2.toLowerCase - let e2 = e2->Js.String2.toLowerCase - if e1 > e2 { - 1 - } else if e1 < e2 { - -1 - } else { - 0 - } -} - -let getHostnameQueryFromURL = url => { - let arr = url->Js.String2.split("?") - let queryDict = arr->Belt.Array.get(1)->Belt.Option.getWithDefault("")->getDictFromUrlSearchParams - (arr[0]->Belt.Option.getWithDefault(""), queryDict) -} - -let makeURLFromHostnameQuery = (host, queryDict) => { - let query = - queryDict->Js.Dict.entries->Js.Array2.map(((k, v)) => `${k}=${v}`)->Js.Array2.joinWith("&") - `${host}?${query}` -} - let isEmptyDict = dict => { dict->Js.Dict.keys->Js.Array2.length === 0 } @@ -1022,21 +492,6 @@ let stringReplaceAll = (str, old, new) => { str->Js.String2.split(old)->Js.Array2.joinWith(new) } -let getNullFloat = (dict, key) => { - switch Js.Dict.get(dict, key) { - | Some(value) => - switch value->Js.Json.decodeString { - | Some(val) => val->Belt.Float.fromString->Js.Nullable.fromOption - | None => - switch value->Js.Json.decodeNumber { - | Some(val) => val->Js.Nullable.return - | None => Js.Nullable.null - } - } - | None => Js.Nullable.null - } -} - let getUniqueArray = (arr: array<'t>) => { arr->Js.Array2.map(item => (item, ""))->Js.Dict.fromArray->Js.Dict.keys } @@ -1055,10 +510,6 @@ let getDictfromDict = (dict, key) => { let checkLeapYear = year => (mod(year, 4) === 0 && mod(year, 100) !== 0) || mod(year, 400) === 0 -let safeDivision = (~numerator: float, ~denominator: float) => { - denominator > 0. ? numerator /. denominator : 0. -} - let getValueFromArr = (arr, index, default) => arr->Belt.Array.get(index)->Belt.Option.getWithDefault(default) @@ -1081,41 +532,6 @@ let indianShortNum = labelValue => { shortNum(~labelValue, ~numberFormat=getDefaultNumberFormat(), ()) } -let getNumberString = ( - ~prefix="", - ~suffix="", - ~showDecimal=false, - ~toShortNum=false, - ~numberFormat="INR", - ~digits=2, - value, -) => { - if toShortNum { - `${prefix}${shortNum(~labelValue=value, ~numberFormat=getDefaultNumberFormat(), ())}${suffix}` - } else { - let valueSplitArr = Js.Float.toFixedWithPrecision(value, ~digits)->Js.String2.split(".") - - let decimalValue = - valueSplitArr - ->Belt.Array.get(1) - ->Belt.Option.getWithDefault("0") - ->Belt.Int.fromString - ->Belt.Option.getWithDefault(0) - let decimal = if valueSplitArr->Js.Array2.length > 1 && decimalValue !== 0 { - `.${valueSplitArr[1]->Belt.Option.getWithDefault("")}` - } else { - "" - } - let receivedValue = value->Js.Math.floor_float->Belt.Float.toString - let formattedvalue = if numberFormat === "INR" { - receivedValue->Js.String2.replaceByRe(%re("/(\d)(?=(?:(\d\d)+(\d)(?!\d))+(?!\d))/g"), "$1,") - } else { - receivedValue->Js.String2.replaceByRe(%re("/(\d)(?=(\d{3})+(?!\d))/g"), "$1,") - } - `${prefix}${formattedvalue}${showDecimal ? decimal : ""}${suffix}` - } -} - let convertNewLineSaperatedDataToArrayOfJson = text => { text ->Js.String2.split("\n") @@ -1133,51 +549,6 @@ let getListHead = (~default="", list) => { list->Belt.List.head->Belt.Option.getWithDefault(default) } -/* -metrics arr: the array which need to be merged i.e -[ - [ - { - "order_status": "1", - "time": "2023-07-24 00:00:00" - }, - { - "order_status": "3330", - "time": "2023-07-25 00:00:00" - }, - - ], - [ - { - "p2p_clicked": "1", - "time": "2023-07-24 00:00:00" - }, - { - "p2p_clicked": "3330", - "time": "2023-07-25 00:00:00" - }, - ] -] - -dictKey: key on which we wanted to merge i.e in the above case it will be time - -output will be : - -[ - { - "order_status": "1", - "time": "2023-07-24 00:00:00", - "p2p_clicked": "1" - }, - { - "order_status": "3330", - "time": "2023-07-25 00:00:00", - "p2p_clicked": "3330" - } -] - - -*/ let dataMerge = (~dataArr: array>, ~dictKey: array) => { let finalData = Js.Dict.empty() dataArr->Js.Array2.forEach(jsonArr => { @@ -1204,14 +575,6 @@ let dataMerge = (~dataArr: array>, ~dictKey: array) => finalData->Js.Dict.values } -let sumOfArrInt = (arr: array) => { - arr->Belt.Array.reduce(0, (acc, value) => acc + value) -} - -let sumOfArrFloat = (arr: array) => { - arr->Belt.Array.reduce(0., (acc, value) => acc +. value) -} - let getJsonFromStr = data => { if data !== "" { Js.Json.stringifyWithSpace(safeParse(data), 2) @@ -1220,21 +583,9 @@ let getJsonFromStr = data => { } } -let compareStr = (str1, str2) => { - str1->Js.String2.toLowerCase->Js.String2.includes(str2->Js.String2.toLowerCase) -} - //Extract Exn to Dict external toExnJson: exn => Js.Json.t = "%identity" -let exnToDict = exn => { - exn->toExnJson->getDictFromJsonObject -} - -let getJsonDict = val => { - val->Belt.Option.getWithDefault(Js.Dict.empty()->Js.Json.object_) -} - let compareLogic = (firstValue, secondValue) => { let (temp1, _) = firstValue let (temp2, _) = secondValue @@ -1248,12 +599,6 @@ let compareLogic = (firstValue, secondValue) => { } let getJsonFromArrayOfJson = arr => arr->Js.Dict.fromArray->Js.Json.object_ -let getNonEmptyStrFromOptionStr = (str, defaultValue) => { - switch str { - | Some(val) => val->Js.String2.trim !== "" ? val : defaultValue - | None => defaultValue - } -} let getTitle = name => { name diff --git a/src/utils/Parsers.res b/src/utils/Parsers.res deleted file mode 100644 index 8b15d23a8..000000000 --- a/src/utils/Parsers.res +++ /dev/null @@ -1,251 +0,0 @@ -external strArrToJsonArr: array => array = "%identity" -let numericParser = (. ~value, ~name as _) => { - value - ->Js.Json.decodeString - ->Belt.Option.flatMap(Belt.Float.fromString) - ->Belt.Option.getWithDefault(0.0) - ->Js.Json.number -} - -let numericNonZeroParser = (. ~value, ~name as _) => { - let num = - value - ->Js.Json.decodeString - ->Belt.Option.flatMap(Belt.Int.fromString) - ->Belt.Option.getWithDefault(0) - - if num === 0 { - Js.Json.null - } else { - num->Belt.Float.fromInt->Js.Json.number - } -} - -let otpParser = (. ~value, ~name as _) => { - value - ->Js.Json.decodeString - ->Belt.Option.getWithDefault("") - ->Js.String2.match_(%re("/[0-9]*/")) - ->Belt.Option.getWithDefault([]) - ->Js.Array2.joinWith("") - ->Js.Json.string -} - -let alphaNumericCapitalParser = (. ~value, ~name as _) => { - value - ->Js.Json.decodeString - ->Belt.Option.getWithDefault("") - ->Js.String2.match_(%re(`/[A-Z0-9]+/g`)) - ->Belt.Option.getWithDefault([]) - ->Js.Array2.joinWith("") - ->Js.Json.string -} - -let capitalParser = (. ~value, ~name as _) => { - value - ->Js.Json.decodeString - ->Belt.Option.getWithDefault("") - ->Js.String2.match_(%re(`/[A-Z]+/g`)) - ->Belt.Option.getWithDefault([]) - ->Js.Array2.joinWith("") - ->Js.Json.string -} - -let getLimitCheckedValue = val => { - let newValueFloat = LogicUtils.getFloatFromJson(val, 0.0) - if newValueFloat > 1000000000000000.00 { - newValueFloat->Belt.Float.toString->Js.String2.slice(~from=0, ~to_=15)->Js.Json.string - } else { - val - } -} - -let numericStrParser = (. ~value, ~name as _) => { - let finalVal = getLimitCheckedValue(value) - let num = - finalVal - ->Js.Json.decodeString - ->Belt.Option.flatMap(Belt.Int.fromString) - ->Belt.Option.getWithDefault(0) - - if num === 0 { - ""->Js.Json.string - } else { - num->Belt.Int.toString->Js.Json.string - } -} - -let leadingSpaceStrParser = (. ~value, ~name as _) => { - let str = value->Js.Json.decodeString->Belt.Option.getWithDefault("") - str->Js.String2.replaceByRe(%re("/^[\s]+/"), "")->Js.Json.string -} - -let removeSpaceParser = (. ~value, ~name as _) => { - let str = value->Js.Json.decodeString->Belt.Option.getWithDefault("") - str->Js.String2.replaceByRe(%re("/[\s]+/"), "")->Js.Json.string -} - -let floatNumericStrParser = (. ~value, ~name as _) => { - let finalVal = getLimitCheckedValue(value) - let val = LogicUtils.getStringFromJson(finalVal, "0.0") - - let isFloat = Js.Float.isFinite(Js.Float.fromString(val)) - let sliceFloat = val->Js.String2.slice(~from=0, ~to_=Js.String.length(val) - 1) - let isFloat2 = Js.Float.isFinite(Js.Float.fromString(sliceFloat)) - if !isFloat { - isFloat2 - ? val->Js.String2.slice(~from=0, ~to_=Js.String.length(val) - 1)->Js.Json.string - : "0.0"->Js.Json.string - } else { - finalVal - } -} -let toUpperCaseParser = (. ~value, ~name as _) => { - let str = value->Js.Json.decodeString->Belt.Option.getWithDefault("") - str->Js.String2.toUpperCase->Js.Json.string -} -let customFloatNumericStrParserWithPrecision = precisionVal => { - let floatNumericStrParserWithPrecision = (. ~value, ~name as _) => { - let finalVal = getLimitCheckedValue(value) - let val = LogicUtils.getStringFromJson(finalVal, "0.0") - let indexOfDec = val->Js.String2.indexOf(".") - - let isFloat = Js.Float.isFinite(Js.Float.fromString(val)) - let sliceFloat = val->Js.String2.slice(~from=0, ~to_=Js.String.length(val) - 1) - let isFloat2 = Js.Float.isFinite(Js.Float.fromString(sliceFloat)) - if !isFloat { - isFloat2 - ? val->Js.String2.slice(~from=0, ~to_=Js.String.length(val) - 1)->Js.Json.string - : "0.0"->Js.Json.string - } else if indexOfDec > 0 { - finalVal - ->Js.Json.decodeString - ->Belt.Option.getWithDefault("") - ->Js.String.slice(~from=0, ~to_={indexOfDec + precisionVal}) - ->Js.Json.string - } else { - finalVal - } - } - floatNumericStrParserWithPrecision -} - -let arrayParser = (. ~value, ~name as _) => { - let val = LogicUtils.getStringFromJson(value, "") - - val->Js.String2.split(",")->Js.Array2.filter(x => x !== "")->Js.Json.stringArray -} -let arrayParser2 = (. ~value, ~name as _) => { - let val = LogicUtils.getStringFromJson(value, "") - val->Js.String2.split(",")->Js.Json.stringArray -} -let numericArrayParser = (. ~value, ~name as _) => { - let valArr = switch Js.Json.classify(value) { - | JSONString(a) => a->Js.String2.split(",") - | JSONArray(arr) => arr->Js.Array2.reduce((acc, jsonItem) => { - switch jsonItem->Js.Json.decodeString { - | Some(str) => acc->Js.Array2.push(str)->ignore - | None => () - } - acc - }, []) - | _ => [] - } - - valArr->Js.Array2.reduce((acc, str) => { - switch str->Belt.Float.fromString { - | Some(a) => acc->Js.Array2.push(a->Js.Json.number)->ignore - | None => () - } - acc - }, [])->Js.Json.array -} - -let arrOfObjToArrOfObjValue = (. ~value, ~name as _) => { - let jsonArr = switch value->Js.Json.decodeArray { - | Some(dict_arr) => dict_arr->Js.Array2.reduce((acc, item) => { - switch Js.Json.decodeObject(item) { - | Some(obj) => { - let val = Js.Dict.values(obj) - let strval = LogicUtils.getStringFromJson( - val[0]->Belt.Option.getWithDefault(Js.Json.null), - "", - ) - - if strval != "" { - acc->Js.Array2.push(val[0]->Belt.Option.getWithDefault(Js.Json.null))->ignore - } - acc - } - - | None => acc - } - }, []) - | None => [] - } - jsonArr->Js.Json.array -} - -let arrayStrParser = (. ~value, ~name as _) => { - let x = - value - ->Js.Json.decodeArray - ->Belt.Option.getWithDefault([]) - ->Belt.Array.keepMap(Js.Json.decodeString) - - x->Js.Array2.joinWith(", ")->Js.Json.string -} - -let strFromArrayParser = (. ~value, ~name as _) => { - value - ->LogicUtils.getArrayFromJson([]) - ->LogicUtils.getStrArrayFromJsonArray - ->Js.Array2.joinWith(",") - ->Js.Json.string -} -let moneyFormat = (. ~value, ~name as _) => { - let value = value->LogicUtils.getStringFromJson("")->Js.String2.replaceByRe(%re("/[^0-9.,]/"), "") - let moneyArr = value->Js.String2.split(".") - let newFormat = if moneyArr->Js.Array2.length > 0 { - moneyArr[0] - ->Belt.Option.getWithDefault("") - ->LogicUtils.stringReplaceAll(",", "") - ->Js.String2.replaceByRe(%re("/\b0+/g"), "") - ->Js.String2.replaceByRe(%re("/(\d)(?=(?:(\d\d)+(\d)(?!\d))+(?!\d))/g"), "$1,") - } else { - "" - } - if moneyArr->Js.Array2.length > 1 { - ({newFormat == "" ? "0" : newFormat} ++ - "." ++ - moneyArr[1] - ->Belt.Option.getWithDefault("") - ->LogicUtils.stringReplaceAll(",", "") - ->Js.String.slice(~from=0, ~to_=2))->Js.Json.string - } else { - newFormat->Js.Json.string - } -} -let moneyFormatForiegn = (. ~value, ~name as _) => { - let value = value->LogicUtils.getStringFromJson("")->Js.String2.replaceByRe(%re("/[^0-9.,]/"), "") - let moneyArr = value->Js.String2.split(".") - let newFormat = if moneyArr->Js.Array2.length > 0 { - moneyArr[0] - ->Belt.Option.getWithDefault("") - ->LogicUtils.stringReplaceAll(",", "") - ->Js.String2.replaceByRe(%re("/\b0+/g"), "") - ->Js.String2.replaceByRe(%re("/(\d)(?=(\d{3})+(?!\d))/g"), "$1,") - } else { - "" - } - if moneyArr->Js.Array2.length > 1 { - ({newFormat == "" ? "0" : newFormat} ++ - "." ++ - moneyArr[1] - ->Belt.Option.getWithDefault("") - ->LogicUtils.stringReplaceAll(",", "") - ->Js.String.slice(~from=0, ~to_=2))->Js.Json.string - } else { - newFormat->Js.Json.string - } -} diff --git a/src/utils/ResizeObserver.res b/src/utils/ResizeObserver.res index e147d4f8b..ef72c0f89 100644 --- a/src/utils/ResizeObserver.res +++ b/src/utils/ResizeObserver.res @@ -1,7 +1,3 @@ -type observer = {observe: (. Dom.element) => unit} -type dimensions = { - height: float, - width: float, -} -type ele = {contentRect: dimensions} -@new external newResizerObserver: (Js.Array2.t => unit) => observer = "ResizeObserver" +type observer +type dimensions +@new external newResizerObserver: (Js.Array2.t => unit) => observer = "ResizeObserver" diff --git a/src/utils/Reveal.res b/src/utils/Reveal.res index 502aff3e3..22af0db26 100644 --- a/src/utils/Reveal.res +++ b/src/utils/Reveal.res @@ -1,33 +1 @@ -type postion = Top | Bottom | Left | Right | Center - -@react.component -let make = (~children, ~showReveal, ~duration="duration-500", ~revealFrom=Top) => { - open HeadlessUI - - let translateFrom = switch revealFrom { - | Top => "-translate-y-full scale-100" - | Bottom => "translate-y-full scale-100" - | Left => "translate-x-full scale-100" - | Right => "-translate-x-full scale-100" - | Center => "scale-50" - } - let translateTo = switch revealFrom { - | Top => "translate-y-0 scale-100" - | Bottom => "-translate-y-0 scale-100" - | Left => "translate-x-0 scale-100" - | Right => "-translate-x-0 scale-100" - | Center => "scale-100 " - } - - - children - -} +type postion = Top | Right diff --git a/src/utils/SortUtils.res b/src/utils/SortUtils.res deleted file mode 100644 index 9454eac44..000000000 --- a/src/utils/SortUtils.res +++ /dev/null @@ -1,16 +0,0 @@ -let sortByArrOrder = (dict: Js.Dict.t) => { - let sortByOrderOderedArr = (a: (string, 'a), b: (string, 'a)) => { - let (a, _) = a - let (b, _) = b - let positionInHeader = dict->Js.Dict.get(a)->Belt.Option.getWithDefault(0) - let positionInHeading = dict->Js.Dict.get(b)->Belt.Option.getWithDefault(0) - if positionInHeader < positionInHeading { - -1 - } else if positionInHeader > positionInHeading { - 1 - } else { - 0 - } - } - sortByOrderOderedArr -} diff --git a/src/utils/UrlFetchUtils.res b/src/utils/UrlFetchUtils.res index 5d36f5a69..96a0e566c 100644 --- a/src/utils/UrlFetchUtils.res +++ b/src/utils/UrlFetchUtils.res @@ -8,81 +8,3 @@ let getFilterValue = value => { Js.Json.string(value) } } - -let dictToSearchParam = (~dict: Js.Dict.t) => { - let arrVal = dict->Js.Dict.entries - let reducedValue = Belt.Array.reduce(arrVal, ("", ""), (acc, value) => { - let (key, item) = value - let (keyacc, itemacc) = acc - (key ++ keyacc, item ++ itemacc) - }) - let (key, value) = reducedValue - key ++ value -} - -let fetchAndMakeFilter = (arrFilterKeys: array, ~dict) => { - let arrVal = - dict - ->Js.Dict.entries - ->Belt.Array.keepMap(item => { - let (key, _) = item - arrFilterKeys->Js.Array2.includes(key) ? Some(item) : None - }) - - (arrVal->Js.Dict.fromArray, dictToSearchParam(~dict=arrVal->Js.Dict.fromArray)) -} -let useFetchFilterFromUrl = () => { - let url = RescriptReactRouter.useUrl() - let (state, setState) = React.useState(_ => Js.Dict.empty()) - let searchParams = url.search->Js.Global.decodeURI - //UPDATE need to handle the dict case directly here i we will be making local state here - let updateFetchedFilters = (setState, updatedValue: Js.Dict.t) => { - setState(prev => { - let changedValues = - updatedValue - ->Js.Dict.entries - ->Belt.Array.keepMap(entries => { - let (key, updatedValue) = entries - let previousValue = prev->Js.Dict.get(key)->Belt.Option.getWithDefault("") - if updatedValue !== previousValue { - Some("") - } else { - None - } - }) - - let updatedKeys = updatedValue->Js.Dict.keys - let prevKeys = prev->Js.Dict.keys - // key can be added which is been handled by above case and key is removed - // if we have item in updated key then remove it from prev key - // if any item is still present in the remainingPrevKeys then update is been changed - // either the keys is removed or either it is updated - let remainingPrevKeys = prevKeys->Belt.Array.keepMap(item => { - updatedKeys->Js.Array2.includes(item) ? None : Some(item) - }) - changedValues->Js.Array2.length > 0 || remainingPrevKeys->Js.Array2.length > 0 - ? updatedValue - : prev - }) - } - - let updateValue = - searchParams - ->Js.String2.split("&") - ->Belt.Array.keepMap(item => { - let arr = Js.String.split("=", item) - let (key, value) = ( - arr->Belt.Array.get(0)->Belt.Option.getWithDefault(""), - arr->Belt.Array.get(1)->Belt.Option.getWithDefault(""), - ) - Some((key, value)) - }) - ->Js.Dict.fromArray - - React.useEffect1(() => { - updateFetchedFilters(setState, updateValue) - None - }, [searchParams]) - - fetchAndMakeFilter(~dict=state) -}