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ACTK,aAAcD,KAIlB/O,EAAKoP,iCAsBMC,EAAgC,IAAY,OAAD,6BAEtD,MAAMC,QAAuB,qBAAsBC,OAAOrF,IACxDU,QAAQ4E,KAAK,qCAAqCtF,QAGpD,IAAKoF,EACH,OAGF,MAAMG,EAAgBH,EAAeI,aAAaC,gBAC5CrB,EAAcgB,EAAeM,iBAAiBC,cAG9C7P,QAAmC,qCACnCA,EAAKoP,gCACX,MAGMU,EAAU,IAAI,IACdC,EAA0C,CAC9CzB,YAAAA,EACA0B,UANgB,IASZC,EAAuBR,GAAgB,IAAIS,MAAOC,UAAY,IASpE,OARAL,EAAQM,IAAI,mBAAsCL,EAAqB,CACrEnO,KAAM,IACNuD,OAAQ,mBACRkL,QAAQ,EACRC,SAAU,OACVC,OAAQN,IAGHF,KAGIS,EAA8B,KACzC,MACMT,GADU,IAAI,KACgBU,IAClC,oBAQF,OAJEV,GACA,cAAeA,GACf,gBAAiBA,EAEEA,EAAsB","sources":["webpack://leadsbridge/./src/components/ConnectedPopupWindow/utils.ts","webpack://leadsbridge/./src/dataTracking/utils.ts","webpack://leadsbridge/./src/features/auth/bridgeByUrl/utils.ts","webpack://leadsbridge/./src/features/nbee/FieldsMappingForm/SendTestLeadSubForm/utils.ts","webpack://leadsbridge/./src/features/nbee/FieldsMappingForm/utils.ts","webpack://leadsbridge/./src/features/nbee/IncomingDataContent/utils.ts","webpack://leadsbridge/./src/features/nbee/IntegrationCredentialsContent/AppAuthCredentialForm/fields/utils.ts","webpack://leadsbridge/./src/features/nbee/IntegrationCredentialsContent/AppAuthCredentialForm/utils.ts","webpack://leadsbridge/./src/features/nbee/IntegrationCredentialsContent/utils.ts","webpack://leadsbridge/./src/features/nbee/SimpleBridgeBuilderForm/fields/AppSelector/utils.ts","webpack://leadsbridge/./src/features/nbee/SimpleBridgeBuilderForm/fields/IntegrationSettings/utils.ts","webpack://leadsbridge/./src/features/nbee/utils.ts","webpack://leadsbridge/./src/pages/BridgeByUrlCallback/utils.ts","webpack://leadsbridge/./src/services/apiAuthClient/utils.ts"],"sourcesContent":["import { useEffect, useState, MutableRefObject } from 'react'\n\ntype LbMessageEvent = {\n isLbMessage: boolean\n [key: string]: unknown\n}\n\nexport const calculateToCenterWindow = (w: number, h: number) => {\n const dualScreenLeft =\n window.screenLeft !== undefined ? window.screenLeft : window.screenX\n const dualScreenTop =\n window.screenTop !== undefined ? window.screenTop : window.screenY\n const width = window.innerWidth\n ? window.innerWidth\n : document.documentElement.clientWidth\n ? document.documentElement.clientWidth\n : screen.width\n const height = window.innerHeight\n ? window.innerHeight\n : document.documentElement.clientHeight\n ? document.documentElement.clientHeight\n : screen.height\n const systemZoom = width / window.screen.availWidth\n const left = (width - w) / 2 / systemZoom + dualScreenLeft\n const top = (height - h) / 2 / systemZoom + dualScreenTop\n\n return {\n left,\n top,\n }\n}\n\n// Send initial data to popup\nexport const postInitialDataToPopup = ({\n initialData,\n popup,\n skipOriginCheck,\n}: {\n initialData?: any\n popup: Window\n skipOriginCheck?: boolean\n}) => {\n if (!initialData) {\n return\n }\n\n const message: LbMessageEvent = {\n ...initialData,\n isLbMessage: true,\n }\n const targetOrigin = skipOriginCheck ? '*' : window.location.origin\n\n // better to dalay the postMessage to be sure popup is properly loaded\n setTimeout(() => {\n popup.postMessage(message, targetOrigin)\n }, 1500)\n}\n\n// Listen for message returned from popup\nexport const usePopupMessageReceiver = (\n popup: MutableRefObject\n) => {\n const [dataFromPopup, setDataFromPopup] = useState>()\n\n const messageReceiverFn = function (event: MessageEvent) {\n if (event.data.isLbMessage) {\n // console.log('Data received back from popup: ', event.data)\n setDataFromPopup(event.data)\n }\n }\n useEffect(() => {\n if (popup) {\n window.addEventListener('message', messageReceiverFn)\n }\n return () => window.removeEventListener('message', messageReceiverFn)\n }, [popup])\n\n return {\n dataFromPopup,\n }\n}\n\nexport const makePopupFeatures = (\n widthPx: number,\n heightPx: number\n): string => {\n const positionValues = calculateToCenterWindow(widthPx, heightPx)\n\n const params: Record = {\n scrollbars: 'no',\n resizable: 'no',\n status: 'no',\n toolbar: 'no',\n menubar: 'no',\n width: widthPx,\n height: heightPx,\n left: positionValues.left,\n top: positionValues.top,\n }\n\n return Object.keys(params)\n .map((k) => `${k}=${params[k]}`)\n .join(',')\n}\n\n// Calculate dynamic popup sizes to avoid overflow scrollbar\nconst defaultPopupWeight = 900\nconst defaultPopupHeight = 600\n\nexport const getPopupWeight = () => {\n const currentWidth = window.screen.availWidth\n if (currentWidth < defaultPopupWeight) {\n return (95 * currentWidth) / 100\n } else {\n return defaultPopupWeight\n }\n}\n\nexport const getPopupHeight = () => {\n const currentHeight = window.screen.availHeight\n if (currentHeight < defaultPopupHeight) {\n return (90 * currentHeight) / 100\n } else {\n return defaultPopupHeight\n }\n}\n","import { CognitoUserInterface } from '@aws-amplify/ui-components'\nimport { BridgeFormValues, AppConfigurationType } from 'Nbee'\nimport { matchPath } from 'react-router'\nimport { appRoutes } from '@app/routes'\nimport { TrackingStep } from 'DataTracking'\n\nexport const extractUserIdFromCognitoUser = (user?: CognitoUserInterface) => {\n const slaveUserId: string =\n user && user.attributes && user.attributes['custom:legacySlaveUserId']\n ? 'SUID-' + user.attributes['custom:legacySlaveUserId']\n : 'SUID-0'\n\n const mainUserId: string =\n user && user.attributes && user.attributes['custom:legacyUserId']\n ? 'UID-' + user.attributes['custom:legacyUserId']\n : 'UID-0'\n\n const userId = slaveUserId === 'SUID-0' ? mainUserId : slaveUserId\n const accountId: string =\n user?.attributes && user.attributes['custom:legacyUserId']\n\n return {\n userId,\n accountId,\n }\n}\n\nexport const extractEmailFromCognitoUser = (\n user?: CognitoUserInterface\n): {\n email: string | undefined\n} => {\n const cognitoEmail: string | undefined =\n user && user.attributes && user.attributes.email\n // when doing social authentication we'll receive an email that contains `+EXTERNAL`, we need to strip that text out to avoid sending dups to segment\n const email = cognitoEmail?.replace('+EXTERNAL', '')\n\n return {\n email,\n }\n}\n\nexport const makeNbeeTrackingParams = (\n formValues: BridgeFormValues,\n type?: AppConfigurationType\n) => {\n // in case a type (source or destination) is passed, we can add more info\n const currentAppParams = type\n ? {\n appId: formValues[type].appId,\n appName: formValues.ui && formValues.ui[type]?.selectedAppName,\n integrationId: formValues[type].integrationId,\n integrationName:\n formValues.ui && formValues.ui[type]?.selectedIntegrationName,\n }\n : {}\n\n return {\n sourceAppId: formValues.source.appId,\n sourceAppName: formValues.ui?.source?.selectedAppName,\n destinationAppId: formValues.destination.appId,\n destinationAppName: formValues.ui?.destination?.selectedAppName,\n bridgeId: formValues.ui?.bridgeId,\n bridgeName: formValues.name,\n ...currentAppParams,\n }\n}\n\nexport const makePricingTrackingStep = (\n locationPathname: string\n): TrackingStep | undefined => {\n const isInPricing = matchPath(locationPathname, {\n path: appRoutes.pricing.path,\n exact: true,\n })\n const isInCheckout = matchPath(locationPathname, {\n path: appRoutes.checkout.path,\n exact: true,\n })\n\n return isInPricing ? 'Table' : isInCheckout ? 'Checkout' : undefined\n}\n","import { BbuPartnersName } from '@app/enums/bridgeByUrl'\n\nconst invalidBbuUrlErrors: Record<\n BbuPartnersName,\n { message: string; link: string; linkText: string }\n> = {\n [BbuPartnersName.facebookConversionLeads]: {\n message:\n 'Your URL is not valid, please check again from App Store or contact support.',\n link: 'https://business.facebook.com/events_manager2/',\n linkText: 'Go back to Meta Events Manager',\n },\n [BbuPartnersName.facebook]: {\n message:\n 'Your URL is not valid, please check again from App Store or contact support.',\n link: 'https://business.facebook.com/business/app-store/',\n linkText: 'Go back to Meta Business App Store',\n },\n [BbuPartnersName.tiktok]: {\n message:\n 'Your URL is not valid, please check again from your TikTok for Business dashboard or contact support.',\n link: 'https://www.tiktok.com/business/it/apps/tiktok',\n linkText: 'Go back to TikTok',\n },\n [BbuPartnersName.app]: {\n message: 'Your URL is not valid, please contact support.',\n link: 'https://www.leadsbridge.com',\n linkText: 'Go back to LeadsBridge',\n },\n}\n\n// generic messages added as fallback, if partnerName is not one of the allowed partners you should not reach this error block\nexport const getInvalidBbuUrlErrors = (partnerName: BbuPartnersName) =>\n invalidBbuUrlErrors[partnerName] || {\n message: 'Your URL is not valid, please contact support.',\n link: 'https://leadsbridge.com/contact-us/',\n linkText: 'Contact support',\n }\n","import { BridgeFormValues, MappedField } from 'Nbee'\nimport {\n ApiBridgeFieldDefinition,\n ApiTestFieldsMappingErrorItem,\n ApiTestFieldsMappingRequestBody,\n ApiTestableFieldsResponse,\n} from 'BackendApi'\nimport { FormikErrors } from 'formik'\n\nexport const tranformApiResponseToFormValues = (\n apiResponse: ApiTestableFieldsResponse\n) =>\n (apiResponse?.data || []).map((field) => ({\n id: field.id,\n label: field.label,\n value: field.lastValue,\n }))\n\n// We use this function to adapt formik state to performa API post request\n// to test fields mapping\nexport const transformFormValuesToTestMappingRequest = (\n fieldsMappingValues?: MappedField[]\n): ApiTestFieldsMappingRequestBody => {\n // Filter to ensure every field has a destinationFieldId defined\n const validFields = (fieldsMappingValues || []).filter(\n (field): field is MappedField & { destinationFieldId: string } =>\n !!field.destinationFieldId\n )\n\n // Now TypeScript knows destinationFieldId is guaranteed to be a string\n return validFields.map((field) => ({\n destinationFieldId: field.destinationFieldId,\n mappingType: field.mappingType,\n // Assuming you need to transform each MappedFieldMapping to ApiMappedField\n mapping: [...field.mapping],\n }))\n}\n\n// transform api response (test fields mapping) into a formik error state\nexport const fromApiTestReponseToFormErrors = (\n destinationFields: ApiBridgeFieldDefinition[],\n apiResult: ApiTestFieldsMappingErrorItem[]\n) => {\n const errors = destinationFields.map((field) => {\n const hasError = apiResult.find(\n ({ destinationFieldId }) => destinationFieldId === field.id\n )\n if (hasError) {\n return hasError.mapping.some((i) => i.sourceFieldId)\n ? {\n sourceFieldId: hasError.message,\n }\n : { destinationText: hasError.message }\n }\n return null\n })\n\n // some weird casting here since our error structure is more complex than formik built-in\n return {\n fieldsMapping: errors as any,\n } as FormikErrors\n}\n","import { MappedField, MappedFieldMapping } from 'Nbee'\n\nexport const isFieldMappingEmpty = (mapping: MappedFieldMapping): boolean =>\n !(mapping.sourceFieldId || mapping.text || mapping.formula?.id)\n\nexport const isFieldMapped = (field: MappedField): boolean =>\n field.mapping.some((m) => !isFieldMappingEmpty(m))\n\nexport const isFieldUnmapped = (field: MappedField): boolean =>\n !isFieldMapped(field)\n\nexport const getShowUnmappedInitialState = (\n fieldsMappingValues?: MappedField[]\n): boolean => {\n // to understand if the initial state for showUnmapped is true or false, we need to check\n // if all required fields are already mapped.\n const requiredFields = (fieldsMappingValues || []).filter((f) => f.isRequired)\n\n // when we have no required fields\n if (!requiredFields.length) {\n const allAreUnmapped = (fieldsMappingValues || []).every(\n (f) => !isFieldMapped(f)\n )\n // if all fields are not mapped, we need to return true and show unmapped field as initial state\n // instead is something is mapped we return false so that we don't show unmapped field as initial state, but we only show the mapped ones\n return allAreUnmapped\n }\n\n // we proceed to check the case where we have required fields\n const allRequiredAreMapped = requiredFields.length\n ? requiredFields.every((f) => isFieldMapped(f))\n : false\n\n // if all required fields are already mapped we can hide the not mapped fields\n return !allRequiredAreMapped\n}\n","import { App } from 'Nbee'\n\nexport const getListenerAppName = (appData: App | null | undefined): string => {\n const id = appData?.id || 0\n if (id === 1191) return 'your webhook system'\n if (id === 1208) return 'your email system'\n\n return appData?.name ?? ''\n}\n","import { IntegrationFormFieldType } from 'Nbee'\nimport { ApiAppSettingTypes } from 'BackendApi'\n\nexport const fieldsForSmartSelect: IntegrationFormFieldType[] = ['dropdown']\nexport const fieldsForSmartCreatableSelect: ApiAppSettingTypes[] = ['tags']\nexport const fieldsForSmartVerifyEmail: ApiAppSettingTypes[] = [\n 'validate_email',\n 'validate_email_multi',\n]\nexport const fieldsForDomain: IntegrationFormFieldType[] = [\n 'domain',\n 'subdomain',\n]\nexport const fieldsForToggle: IntegrationFormFieldType[] = ['toggle']\nexport const fieldsForInput: IntegrationFormFieldType[] = [\n 'text',\n 'number',\n 'password',\n 'textarea',\n 'datetime',\n 'code',\n 'email',\n 'url',\n]\n","import {\n ApiAppSchemaField,\n ApiAppSchemaFieldTypes,\n ApiIntegration,\n ApiSaveIntegrationRequestBody,\n ApiSettingValue,\n ApiSettingAcceptedValues,\n} from 'BackendApi'\nimport { IntegrationFormField, IntegrationFormValues } from 'Nbee'\nimport { PersistentSessionStorageKeys } from '@app/enums/persistentLocalStorageKeys'\n\nconst emptyValueByType: Record<\n ApiAppSchemaFieldTypes,\n ApiSettingAcceptedValues\n> = {\n password: '',\n textarea: '',\n code: '',\n number: '',\n datetime: '',\n domain: '',\n dropdown: '',\n email: '',\n text: '',\n tags: [],\n url: '',\n subdomain: '',\n toggle: false,\n validate_email: '',\n validate_email_multi: '',\n google_picker: '',\n}\n\n// we set a default value if api returns it only if field has not child, in this way we avoid infinite refetching loop\n// if no default value is provided we set an empty value depending of the type of the field\nconst getDefaultFromApi = (field: ApiAppSchemaField) =>\n field.default || field.default === 0\n ? field.default\n : emptyValueByType[field.type] ?? ''\n\nexport const makeIntegrationFormItemFromApiSchemaField = ({\n field,\n existingField,\n}: {\n field: ApiAppSchemaField\n existingField?: ApiSettingValue\n}): IntegrationFormField => {\n // const existingIntegration\n return {\n id: field.id,\n value: existingField?.value ?? getDefaultFromApi(field),\n label: field.label,\n type: field.type,\n isRequired: field.required,\n selectValues: field.data,\n hide: field.hide,\n default: field.default,\n tooltip: field.tooltip,\n docUrl: field.docUrl,\n hasChild: field.hasChild,\n format: field.format,\n refreshable: field.refreshable,\n }\n}\n\nexport const makeIntegrationFormInitialValues = (\n appAuthSchema: ApiAppSchemaField[],\n appName: string,\n existingIntegration?: ApiIntegration\n): IntegrationFormValues => {\n return {\n name: existingIntegration?.name || '',\n credentials: appAuthSchema.map((field) => {\n const existingField = (existingIntegration?.credentials || []).find(\n ({ key }) => key === field.id\n )\n return makeIntegrationFormItemFromApiSchemaField({ field, existingField })\n }),\n ui: {\n existingIntegrationCredentials: existingIntegration?.credentials || [],\n },\n }\n}\n\nexport const transformIntegrationFormValuesToApiSaveRequestBody = (\n formValues: IntegrationFormValues,\n appId: number\n): ApiSaveIntegrationRequestBody => {\n /**\n * TRANSFORM EMPTY STRING ARRAYS INTO EMPTY ARRAYS\n * This function removes any array fields that only contain an empty string.\n * We add these empty strings to fields with email validation types (e.g. cc and bcc)\n * in order to render the corresponding Email Validation component.\n * However, the API does not accept these empty strings, so we remove them before\n * sending the form data to the API whenever users do not add any value to these fields.\n */\n\n const credentials = (formValues.credentials || []).map(\n ({ id, value, type }) => {\n if (\n type === 'validate_email_multi' &&\n Array.isArray(value) &&\n value.length === 1 &&\n value[0] === ''\n ) {\n return {\n key: id,\n value: [],\n }\n }\n return {\n key: id,\n value,\n }\n }\n )\n\n return {\n name: formValues.name,\n integrationId: formValues.integrationId,\n appId,\n credentials,\n }\n}\n\ntype RedirectParamsCredentials = Record<\n IntegrationFormField['id'],\n IntegrationFormField['value']\n>\n\nconst prepareCredentialObject = (credentials: IntegrationFormField[]) => {\n return credentials.reduce((acc, field) => {\n return {\n ...acc,\n [field.id]: field.value,\n }\n }, {} as RedirectParamsCredentials)\n}\n\nconst storeCredentials = (credentials: IntegrationFormField[]) => {\n const credentialsAsObject = prepareCredentialObject(credentials)\n sessionStorage.setItem(\n PersistentSessionStorageKeys.integrationAuthFlowCredentials,\n JSON.stringify(credentialsAsObject)\n )\n}\n\nexport const retrieveStoredCredentials = (): Record => {\n const storedCredentials = sessionStorage.getItem(\n PersistentSessionStorageKeys.integrationAuthFlowCredentials\n )\n\n try {\n const parsedCredentials: Record = JSON.parse(\n storedCredentials || '{}'\n )\n return parsedCredentials\n } catch {\n return []\n }\n}\n\nconst encodeUriParamsForV1 = (obj: RedirectParamsCredentials) =>\n window.btoa(JSON.stringify(obj))\n\nexport const decodeUriParamsFromV1 = (encodedValue?: string) => {\n try {\n return JSON.parse(window.atob(encodedValue || '{}'))\n } catch {\n return null\n }\n}\n\nexport const startOAuthFlow = ({\n credentials,\n redirectUri,\n appId,\n integrationId,\n isLegacy,\n}: {\n credentials: IntegrationFormField[]\n redirectUri: string\n appId: number\n integrationId?: number\n isLegacy: boolean\n}) => {\n // first thing we store the appId to session storage, so we can get it later\n sessionStorage.setItem(\n PersistentSessionStorageKeys.integrationAuthFlowAppId,\n `${appId}`\n )\n\n if (integrationId) {\n sessionStorage.setItem('instanceId', `${integrationId}`)\n }\n\n // ONLY LEGACY\n\n if (isLegacy) {\n // then we prepare an object to be encoded and sent as query string\n const credentialsAsObject = prepareCredentialObject(credentials)\n const encodedCredentials = encodeUriParamsForV1(credentialsAsObject)\n\n // we build the url and redirect the user to v1 who will create the integration\n // and will return a legacy integration id (v1)\n const uriHasQueryStringParams = redirectUri.includes('?')\n const oauthRedirectUri = `${redirectUri}${\n uriHasQueryStringParams ? '&' : '?'\n }providerId=${appId}¶ms=${encodedCredentials}`\n\n // if `integrationId` is passed it means we are editing an existing integration, so we need to add it to the redirect url\n // in this way v1 will now that is an edit and it won't create a new integration (SB-427)\n window.location.href = integrationId\n ? `${oauthRedirectUri}&instanceId=${integrationId}`\n : oauthRedirectUri\n } else {\n // then we store the credentials to session storage, so we can get it later\n storeCredentials(credentials)\n\n window.location.href = redirectUri\n /* window.location.href =\n '/integration/oauth2/callback?code=4/0AdQt8qiPlchf8d02DuQmZZsPgIpdPg6RerbPQFudHaKNpbZT0G4WAelBKCUiy-t8emtMJA&options=test&otherParam=test2' */\n }\n}\n","type PostMessageData = {\n isLbMessage: true\n integrationId: number\n integrationName: string\n}\n\nexport const sendIntegrationDataToParentWindow = (\n newIntegrationId: number,\n newIntegrationName: string\n) => {\n const parentWindow = window.opener\n if (!parentWindow) {\n return\n }\n\n const message: PostMessageData = {\n isLbMessage: true,\n integrationId: newIntegrationId,\n integrationName: newIntegrationName,\n }\n\n setTimeout(() => {\n // just be sure all segment events have been sent, before killing this window from the parent\n parentWindow.postMessage(message, '*')\n }, 300)\n}\n","import { App } from 'Nbee'\nimport { SelectValue } from '@components/Form/InputSmartSelect'\n\nexport const tranformApiAppsToSelectOptions = (\n apiApps?: App[]\n): SelectValue[] =>\n (apiApps || []).map((app) => ({\n value: `${app.id}`,\n parentAppId: app.parentAppId,\n label: app.name,\n logoUri: app.logoUriSmall,\n }))\n\nexport const getAppOptionFromAppId = (\n appId?: number,\n allOptions?: SelectValue[]\n) => (allOptions || []).find((option) => option.value === `${appId}`)\n","import { ApiAppSetting, ApiAppSettingTypes } from 'BackendApi'\nimport { SelectValue } from '@components/Form/InputSmartSelect'\nimport {\n AppConfigurationType,\n AppIntegrationSetting,\n BridgeFormValues,\n} from 'Nbee'\nimport FacebookService from '@app/services/FacebookService'\nimport { FormikErrors, FormikTouched } from 'formik'\nimport { InputFeedbackStatus } from '@components/Basic/InputFeedback'\n\n/*\n * Grouping setting field types to render specific components\n * example if in future we need to handle type `datatime` with a component\n * that is not a simple input (maybe a datetime-picker) we can take it off\n * from the `fieldsForInput` array and move it into a new one that will be handle\n * inside the main `IntegrationSettings` component\n */\nexport const fieldsForGooglePicker: ApiAppSettingTypes[] = ['google_picker']\n\nexport const fieldsForSmartSelect: ApiAppSettingTypes[] = ['dropdown']\nexport const fieldsForSmartCreatableSelect: ApiAppSettingTypes[] = ['tags']\nexport const fieldsForToggle: ApiAppSettingTypes[] = ['toggle']\nexport const fieldsForInput: ApiAppSettingTypes[] = [\n 'text',\n 'number',\n 'password',\n 'domain',\n 'textarea',\n 'datetime',\n 'code',\n 'email',\n 'url',\n 'subdomain',\n]\n\n/*\n * Helper to transorm formik value into react-select format\n */\nexport const transformSettingDataInSelectOptions = (\n settingData?: { id: string | number; text: string }[]\n): SelectValue[] =>\n (settingData || []).map(({ id, text }) => ({\n value: id,\n label: text,\n }))\n\nexport const getAppIntegrationSettingsIndex = (fieldId: string, settings: AppIntegrationSetting[]): number => {\n let index: number = 0\n for(const setting of settings) {\n if (setting.key === fieldId) {\n break\n }\n index++\n }\n return index\n}\n\n/*\n * Since setting fields are quite complex and we ar not using formik FieldArray\n * we need an helper to easly retrive error and touched state in order to properly\n * build our error feedback object of type `InputFeedbackStatus`\n */\nexport const getSettingFieldError = ({\n type,\n touched,\n errors,\n index,\n}: {\n type: AppConfigurationType\n touched: FormikTouched\n errors: FormikErrors\n index: number\n}): {\n isTouched: boolean\n errorMessage: string\n fieldStatus?: InputFeedbackStatus\n} => {\n const touchedSettings = ((touched[type]?.settings &&\n touched[type]?.settings) ||\n []) as boolean[]\n const errorsSettings = ((errors && errors[type] && errors[type]?.settings) ||\n []) as unknown as string[]\n const isTouched = touchedSettings[index]\n const errorMessage = errorsSettings[index]\n\n return {\n isTouched,\n errorMessage,\n fieldStatus: errorMessage\n ? {\n error: errorMessage,\n }\n : undefined,\n }\n}\n\n/*\n * This function is used to handle the \"create new form\" option if setting field is \"Facebook form\"\n * `callback` parameter is used to update form state\n */\nexport const handleCreateNewFacebookForm = (\n integrationSettings: AppIntegrationSetting[],\n callback: (payload?: {\n formID: string\n // eslint-disable-next-line camelcase\n form_url: string\n pageID: string\n name: string\n }) => void\n) => {\n if (!window.FB) {\n FacebookService.createScriptFb()\n }\n\n const pageIdSetting = integrationSettings.find((s) => s.key === 'pageId')\n const adAccountSetting = integrationSettings.find(\n (s) => s.key === 'advertiserAdAccountId'\n )\n\n const pageIdValue = pageIdSetting?.value\n const adAccountValue = adAccountSetting?.value as string\n\n if (!pageIdValue || !adAccountValue) {\n console.error('Missing adAccountValue or pageIdSetting')\n return\n }\n\n const fbUI = FB.ui as any\n\n fbUI(\n {\n method: 'lead_gen',\n page_id: pageIdValue,\n ad_account_id: adAccountValue.replace('act_', ''),\n },\n callback\n )\n}\n\n/*\n * Starting from setting fields returned from api, which are all empty,\n * we ne to return a new formik setting field state which include old values\n * for existing settings and default values for new ones\n */\nexport const fillNewSettingsWithExistingValues = (\n newAndEmptySettings: ApiAppSetting[],\n existingSettingsWithValues: AppIntegrationSetting[]\n): AppIntegrationSetting[] =>\n newAndEmptySettings.map((newEmptySetting) => {\n const oldSetting = existingSettingsWithValues.find(\n ({ key }) => key === newEmptySetting.id\n )\n if (oldSetting) {\n return oldSetting\n }\n\n // we set `false` for type toggle and `0` for type number\n // everything else it's safe to keep it as empty string (also if is an array of string)\n // inputs will always handle it as empty value\n return {\n key: newEmptySetting.id,\n value:\n newEmptySetting.default || newEmptySetting.default === 0\n ? newEmptySetting.default // if we have a default value we set it\n : newEmptySetting.type === 'toggle'\n ? false\n : newEmptySetting.type === 'number'\n ? 0\n : '',\n }\n })\n","import { StepBarStep } from '@components/StepBar'\nimport { useTranslation } from 'react-i18next'\nimport { useHistory } from 'react-router-dom'\nimport { appRoutes } from '@app/routes'\nimport {\n ApiBridgeAvailablePermissionCheckResponse,\n ApiBridgeAvailablePermissionChecklist,\n} from 'BackendApi'\nimport { useFormikContext } from 'formik'\nimport { useAppDispatch } from '@app/store/hooks'\nimport { useUpdateBridge } from '@app/api/updateBridge'\nimport { useCreateNewBridge } from '@app/api/createNewBridge'\nimport {\n closeAlertMessage,\n sendToast,\n setPath,\n} from '@app/store/actions/ApplicationConfigurationActions'\nimport { transformBridgeFormValuesToApiSaveBridgeBody } from '@app/api/utils/bridge'\nimport { BridgeFormValues } from 'Nbee'\n\nexport const makeNbeeSteps = (\n currentStepIndex?: number,\n bridgeId?: number | string,\n isWelcomeMessage?: boolean\n): StepBarStep[] => {\n const { t } = useTranslation()\n const history = useHistory()\n\n const step1Route = bridgeId\n ? appRoutes.nbeeStep1Edit.makeUrl(`${bridgeId}`)\n : appRoutes.nbeeStep1New.makeUrl()\n\n const step2Route = bridgeId ? appRoutes.nbeeStep2.makeUrl(`${bridgeId}`) : '/'\n\n if (currentStepIndex === undefined) {\n return []\n }\n\n // STEP 1\n if (currentStepIndex === 0) {\n return [\n {\n title: t('nbee.bridgeBuilder.step1Title'),\n label: t('nbee.bridgeBuilder.step1Title'),\n },\n {\n title: t('nbee.bridgeBuilder.step2Title'),\n label: t('nbee.bridgeBuilder.step2Title'),\n },\n {\n title: t('nbee.bridgeBuilder.step3Title'),\n label: t('nbee.bridgeBuilder.step3Title'),\n },\n ]\n }\n\n // STEP 2\n if (currentStepIndex === 1) {\n return [\n {\n title: t('nbee.bridgeBuilder.step1Title'),\n label: t('nbee.bridgeBuilder.step1Title'),\n onStepClick: () => {\n history.push(step1Route)\n },\n },\n {\n title: isWelcomeMessage\n ? t('nbee.bridgeBuilder.step2TitleWelcome')\n : t('nbee.bridgeBuilder.step2Title'),\n label: isWelcomeMessage\n ? t('nbee.bridgeBuilder.step2TitleWelcome')\n : t('nbee.bridgeBuilder.step2Title'),\n },\n {\n title: t('nbee.bridgeBuilder.step3Title'),\n label: t('nbee.bridgeBuilder.step3Title'),\n },\n ]\n }\n\n // STEP 3\n if (currentStepIndex === 2) {\n return [\n {\n title: t('nbee.bridgeBuilder.step1Title'),\n label: t('nbee.bridgeBuilder.step1Title'),\n onStepClick: () => {\n history.push(step1Route)\n },\n },\n {\n title: t('nbee.bridgeBuilder.step2Title'),\n label: t('nbee.bridgeBuilder.step2Title'),\n onStepClick: () => {\n history.push(step2Route)\n },\n },\n {\n title: t('nbee.bridgeBuilder.step3Title'),\n label: t('nbee.bridgeBuilder.step3Title'),\n },\n ]\n }\n\n return []\n}\n\n// this function is used to calculate the initial state of the shouldCheckPermissions state in Step2/FieldsMappingForm\nexport const calculateInitialShouldCheckPermissionsState = (\n payload: ApiBridgeAvailablePermissionCheckResponse | undefined\n): boolean => {\n const permissionChecklist = payload?.data.permissionChecklist\n const executeCheck = payload?.data.executeCheck\n\n if (permissionChecklist?.length !== 0 && executeCheck) {\n return true\n } else {\n return false\n }\n}\nexport const useUpdateBridgeToPricing = (\n bridgeId?: string | number | undefined,\n reasonId?: string,\n minimumPlanRequired?: number\n) => {\n const formik = useFormikContext()\n const history = useHistory()\n const dispatch = useAppDispatch()\n const { mutate: updateBridge } = useUpdateBridge()\n const { mutate: createNewBridge } = useCreateNewBridge()\n const prevPath = history.location.pathname\n\n const handleError = () => {\n dispatch(\n sendToast({\n title: 'Error',\n message: 'Bridge update failed. Please try again.',\n color: 'negative',\n })\n )\n }\n\n const handleClick = () => {\n const formValues = formik.values\n const bridgeData = transformBridgeFormValuesToApiSaveBridgeBody(formValues)\n\n if (bridgeId) {\n updateBridge(\n {\n bridgeData: bridgeData,\n bridgeId: `${bridgeId}`,\n },\n {\n onSuccess: () => {\n dispatch(setPath(prevPath))\n history.push(\n appRoutes.pricing.makeUrlWithState(reasonId, minimumPlanRequired)\n )\n dispatch(closeAlertMessage())\n },\n onError: handleError,\n }\n )\n } else {\n createNewBridge(bridgeData, {\n onSuccess: (data) => {\n const createdBridgeId = data?.data?.bridge?.id\n const newPath = appRoutes.nbeeStep1Edit.makeUrl(`${createdBridgeId}`)\n dispatch(setPath(newPath))\n history.push(\n appRoutes.pricing.makeUrlWithState(reasonId, minimumPlanRequired)\n )\n dispatch(closeAlertMessage())\n },\n onError: handleError,\n })\n }\n }\n\n return handleClick\n}\n","import { PersistentBbuData } from 'LeadsBridgeApp'\nimport { axiosInterceptor } from '@app/services/axiosInterceptor'\nimport { endpoints, getApiErrorMessage } from '@app/api/config'\nimport { BbuParnersFullName } from '@app/enums/bridgeByUrl'\nimport { PersistentLocalStorageKeys } from '@app/enums/persistentLocalStorageKeys'\n\nexport const validatePersistentBbuData = (\n bbuData?: Partial\n): boolean => {\n // wee need a try/catch statement to validate `new URL` constructor\n try {\n const isValidSourceLogo =\n bbuData?.source?.logo && new URL(bbuData?.source?.logo)\n const isValidDestinationLogo =\n bbuData?.destination?.logo && new URL(bbuData?.destination?.logo)\n const isValidRedirectUri =\n bbuData?.requestUri && new URL(bbuData.requestUri)\n return Boolean(\n isValidSourceLogo && isValidDestinationLogo && isValidRedirectUri\n )\n } catch {\n return false\n }\n}\n\nexport const userStatusForSurvey = ['NEW', 'DRAFT']\n\nexport const retryButtonPartnerLink: Record = {\n [BbuParnersFullName.tiktok]: 'https://ads.tiktok.com',\n}\n\nconst setupBridge = async ({ requestUri }: { requestUri: string }) => {\n const axiosInstance = await axiosInterceptor()\n const apiResponse: string = await axiosInstance\n .post(endpoints.setupBridge, { requestUri })\n .then((response) => response.data?.callbackPath)\n return apiResponse\n}\n\n// This function is just a simplified version of what we'll do in future.\n// We still don't have partners with external flow (except FB, which is a custom Fbe)\n// So we return always tru\nexport const checkIfExternalFlowIsRequiredOrSetupBridge = ({\n partnerFullName,\n onSetupBridgeError,\n requestUri,\n}: {\n partnerFullName: BbuParnersFullName\n onSetupBridgeError: (errorMessage: string) => void\n requestUri: string\n}) => {\n const isExternalFlowRequired = partnerFullName !== 'tiktok' // we'll add logic in future\n if (isExternalFlowRequired) {\n // do something (probably it's going to redirect user to a new route eg: /bbu/external-flow/:partnerName or /fbe\n return\n }\n\n // if external flow is not required (eg. tiktok)\n console.log(`Partner does not have external flow, let's setup the bridge`)\n setupBridge({ requestUri })\n .then((callbackPath) => {\n window.sessionStorage.removeItem(\n PersistentLocalStorageKeys.bbuPersistentData\n )\n\n if (process.env.REACT_USE_MOCK_API === 'true') {\n console.log('Simulating redirect to: ' + callbackPath)\n } else {\n window.location.href = callbackPath || `${process.env.REACT_APP_V1_URL}`\n }\n })\n .catch((error) => {\n onSetupBridgeError(getApiErrorMessage({ error }))\n })\n}\n","import { CognitoUserInterface } from '@aws-amplify/ui-components'\nimport { CognitoDevice } from 'LeadsBridgeApp'\nimport { Auth } from 'aws-amplify'\nimport Cookies from 'universal-cookie'\nimport { PersistentCookiesKeys } from '@app/enums/persistentCookiesKeys'\nimport {\n CognitoUserPool,\n CognitoUser,\n CognitoUserSession,\n CognitoIdToken,\n CognitoRefreshToken,\n CognitoAccessToken,\n} from 'amazon-cognito-identity-js'\n\ninterface HandleSignupCognitoProps {\n username: string\n idToken: string\n accessToken: string\n refreshToken: string\n}\n\nexport const signInUserSessionCognito = ({\n username,\n idToken,\n accessToken,\n refreshToken,\n}: HandleSignupCognitoProps) => {\n const userPool = new CognitoUserPool({\n UserPoolId: process.env.REACT_APP_USER_POOL_ID || '',\n ClientId: process.env.REACT_APP_USER_POOL_WEB_CLIENT_ID || '',\n })\n const cognitoIdToken = new CognitoIdToken({\n IdToken: idToken,\n })\n const cognitoAccessToken = new CognitoAccessToken({\n AccessToken: accessToken,\n })\n const cognitoRefreshToken = new CognitoRefreshToken({\n RefreshToken: refreshToken,\n })\n\n const user = new CognitoUser({\n Username: username,\n Pool: userPool,\n })\n\n user.setSignInUserSession(\n new CognitoUserSession({\n AccessToken: cognitoAccessToken,\n IdToken: cognitoIdToken,\n RefreshToken: cognitoRefreshToken,\n })\n )\n\n user.getCachedDeviceKeyAndPassword()\n}\n\nexport const getUserDevice = (user: CognitoUserInterface): Promise => {\n return new Promise((resolve, reject) => {\n user.getDevice({\n onSuccess: (deviceKey: CognitoDevice) => {\n resolve(deviceKey.Device?.DeviceKey || '')\n },\n onFailure: (error?: string) => {\n reject(error || '')\n },\n })\n })\n}\n\ntype CognitoSessionData = {\n accessToken: string\n deviceKey: string\n}\n\n// allow to cache cognito accessToken and deviceKey\nexport const fetchAndPersistCognitoSession = async () => {\n // getting cognito session\n const cognitoSession = await Auth.currentSession().catch((error) => {\n console.warn(`'Cannot authenticate the request: ${error}`)\n })\n\n if (!cognitoSession) {\n return\n }\n\n const expirationSec = cognitoSession.getIdToken().getExpiration()\n const accessToken = cognitoSession.getAccessToken().getJwtToken()\n\n // getting user device\n const user: CognitoUserInterface = await Auth.currentAuthenticatedUser()\n await user.getCachedDeviceKeyAndPassword()\n const deviceKey = '' // await getUserDevice(user)\n\n // preparing data for cookie storage\n const cookies = new Cookies()\n const congnitoSessionData: CognitoSessionData = {\n accessToken,\n deviceKey,\n }\n // setting cookie expiration to match cognito session expiration\n const cookieExpirationSecs = expirationSec - new Date().getTime() / 1000\n cookies.set(PersistentCookiesKeys.CognitoSession, congnitoSessionData, {\n path: '/',\n domain: process.env.REACT_APP_V1_COOKIE_DOMAIN,\n secure: true,\n sameSite: 'none',\n maxAge: cookieExpirationSecs,\n })\n\n return congnitoSessionData\n}\n\nexport const getCognitoPersistentSession = () => {\n const cookies = new Cookies()\n const congnitoSessionData = cookies.get(\n PersistentCookiesKeys.CognitoSession\n ) as CognitoSessionData\n\n const isValidData =\n congnitoSessionData &&\n 'deviceKey' in congnitoSessionData &&\n 'accessToken' in congnitoSessionData\n\n return isValidData ? congnitoSessionData : null\n}\n"],"names":["postInitialDataToPopup","initialData","popup","skipOriginCheck","message","isLbMessage","targetOrigin","window","location","origin","setTimeout","postMessage","usePopupMessageReceiver","dataFromPopup","setDataFromPopup","useState","messageReceiverFn","event","data","useEffect","addEventListener","removeEventListener","makePopupFeatures","widthPx","heightPx","positionValues","w","h","dualScreenLeft","undefined","screenLeft","screenX","dualScreenTop","screenTop","screenY","width","innerWidth","document","documentElement","clientWidth","screen","height","innerHeight","clientHeight","systemZoom","availWidth","left","top","calculateToCenterWindow","params","scrollbars","resizable","status","toolbar","menubar","Object","keys","map","k","join","getPopupWeight","currentWidth","getPopupHeight","currentHeight","availHeight","extractUserIdFromCognitoUser","user","slaveUserId","attributes","userId","accountId","makeNbeeTrackingParams","formValues","type","currentAppParams","appId","appName","ui","selectedAppName","integrationId","integrationName","selectedIntegrationName","sourceAppId","source","sourceAppName","destinationAppId","destination","destinationAppName","bridgeId","bridgeName","name","makePricingTrackingStep","locationPathname","isInPricing","path","exact","isInCheckout","invalidBbuUrlErrors","link","linkText","getInvalidBbuUrlErrors","partnerName","tranformApiResponseToFormValues","apiResponse","field","id","label","value","lastValue","transformFormValuesToTestMappingRequest","fieldsMappingValues","filter","destinationFieldId","mappingType","mapping","fromApiTestReponseToFormErrors","destinationFields","apiResult","fieldsMapping","hasError","find","some","i","sourceFieldId","destinationText","isFieldMapped","m","text","formula","isFieldUnmapped","getShowUnmappedInitialState","requiredFields","f","isRequired","length","every","getListenerAppName","appData","fieldsForSmartSelect","fieldsForSmartCreatableSelect","fieldsForDomain","fieldsForToggle","fieldsForInput","emptyValueByType","password","textarea","code","number","datetime","domain","dropdown","email","tags","url","subdomain","toggle","validate_email","validate_email_multi","google_picker","getDefaultFromApi","default","makeIntegrationFormItemFromApiSchemaField","existingField","required","selectValues","hide","tooltip","docUrl","hasChild","format","refreshable","makeIntegrationFormInitialValues","appAuthSchema","existingIntegration","credentials","key","existingIntegrationCredentials","transformIntegrationFormValuesToApiSaveRequestBody","Array","isArray","prepareCredentialObject","reduce","acc","retrieveStoredCredentials","storedCredentials","sessionStorage","getItem","JSON","parse","startOAuthFlow","redirectUri","isLegacy","setItem","credentialsAsObject","encodedCredentials","btoa","stringify","uriHasQueryStringParams","includes","oauthRedirectUri","href","storeCredentials","sendIntegrationDataToParentWindow","newIntegrationId","newIntegrationName","parentWindow","opener","tranformApiAppsToSelectOptions","apiApps","app","parentAppId","logoUri","logoUriSmall","getAppOptionFromAppId","allOptions","option","fieldsForGooglePicker","transformSettingDataInSelectOptions","settingData","getSettingFieldError","touched","errors","index","touchedSettings","settings","errorMessage","isTouched","fieldStatus","error","handleCreateNewFacebookForm","integrationSettings","callback","FB","pageIdSetting","s","adAccountSetting","pageIdValue","adAccountValue","console","fbUI","method","page_id","ad_account_id","replace","fillNewSettingsWithExistingValues","newAndEmptySettings","existingSettingsWithValues","newEmptySetting","oldSetting","makeNbeeSteps","currentStepIndex","isWelcomeMessage","t","history","step1Route","step2Route","title","onStepClick","push","calculateInitialShouldCheckPermissionsState","payload","permissionChecklist","executeCheck","useUpdateBridgeToPricing","reasonId","minimumPlanRequired","formik","dispatch","mutate","updateBridge","createNewBridge","prevPath","pathname","handleError","color","bridgeData","values","onSuccess","onError","createdBridgeId","bridge","newPath","validatePersistentBbuData","bbuData","isValidSourceLogo","logo","URL","isValidDestinationLogo","isValidRedirectUri","requestUri","Boolean","userStatusForSurvey","retryButtonPartnerLink","signInUserSessionCognito","username","idToken","accessToken","refreshToken","userPool","UserPoolId","ClientId","cognitoIdToken","IdToken","cognitoAccessToken","AccessToken","cognitoRefreshToken","RefreshToken","Username","Pool","setSignInUserSession","getCachedDeviceKeyAndPassword","fetchAndPersistCognitoSession","cognitoSession","catch","warn","expirationSec","getIdToken","getExpiration","getAccessToken","getJwtToken","cookies","congnitoSessionData","deviceKey","cookieExpirationSecs","Date","getTime","set","secure","sameSite","maxAge","getCognitoPersistentSession","get"],"sourceRoot":""}