ddbf3576b9fb121d0dea33da8d9c059d90ccd3f7956407418b4afd2955f4f507

Source Code:

const defaultInputCBRE = [{"url_options":null},{"url_options":null},{"selected_option":"Asia Pacific","url_options":{"Asia Pacific":"Australia,New Zealand,China,Hong Kong,Taiwan,Japan,South Korea,Indonesia,India,Philippines,Singapore,Thailand,Vietnam,Malaysia"}},{"selected_option":"Australia","url_options":{"Asia Pacific":"Australia,New Zealand,China,Hong Kong,Taiwan,Japan,South Korea,Indonesia,India,Philippines,Singapore,Thailand,Vietnam,Malaysia"}}]
const defaultInputSCB = [{"selected_option":"Business Support (BSC)","url_options":{"Global Business Function":"Business Support (BSC),CIB Corp %26 Inst Banking,Corporate Items,CPvB Commercial %26 PvB,Global Support Functions,Operations,RB Retail Banking,Technology %26 Innovation,Global Business Services"}},{"selected_option":"BSC COO","url_options":{"Business Function":"BSC COO,BSC Group Projects,BSC Other Centre,CIB Banking Platform,CIB Corporate Finance,CIB Financial Markets,CIB Global Banking,CIB Islamic Saadiq Banking,CIB Management,CIB Principal Finance,CIB Transaction Banking,COI Grp Approved Central ItemsCOI Ventures,CPvB Commercial Bank,CPvB Private Banking,CPvB Wealth Management,GSF Business Efficiency,GSF CCC Other Costs,GSF CEO %26 Others,GSF Compliance,GSF CorpAff Brand%26Mktg,GSF Corporate Development,GSF Directorate,GSF Finance,GSF Human Resources,GSF Internal Audit,GSF Investor Relations,GSF Legal,GSF Property,GSF Risk,GSF Strategy,GSF Treasury,OPS Business,OPS CCIB,Ops Central,OPS Central %26 Geographies,OPS Enablement%26Transformation,OPS PvB,OPS Trust, Data %26 Automation,OPS Wealth Management Total,RB Client Centre,RB Digital Banking,RB Distribution Network,RB Retail Banking,RB Retail Products,IT-CIO-CCIB,IT-CIO-Cloud Transformation,IT-CIO-FSTS,IT-CIO-Functions%26CDO,IT-CIO-GBS T%26C,IT-CIO-Governance%26Change,IT-CIO-Group CIO Management,IT-CIO-RBPWM,IT-CIO-Technology Services,ITO Technology Services,IT-Projects-CCIB,IT-Projects-CT,IT-Projects-FSTS,IT-Projects-Functions%26CDO,IT-Projects-GBS T%26C,IT-Projects-Governance%26Change,IT-Projects-RBPWM,IT-Proj-Technology Service,IT-TPS-CCIB,IT-TPS-Cloud Transformation,IT-TPS-CT,IT-TPS-FSTS,IT-TPS-Functions%26CDO,IT-TPS-RBPWM,IT-TPS-Technology Services,Business Services,Cash Operations,Client Care Centre,Compliance - Others,Financial Crime Compliance,Financial Crime Surveillance Unit,Financial Markets Operations,Global Banking Operations,Global Finance Services,Global People Services,Other Business Units,Private Banking,Product Control,Retail Banking,Risk Operations,Securities Services,Support,Technology,Trade Operations,Wealth Management"}},{"selected_option":"AME","url_options":{"AME":"Angola,Bahrain,Botswana,Cameroon,Cote d'Ivoire,Egypt,Gambia,Ghana,Iraq,Jordan,Kenya,Lebanon,Mauritius,Nigeria,Oman,Pakistan,Qatar,Saudi Arabia,Sierra Leone,South Africa,Tanzania,United Arab Emirates,Uganda,Zambia,Zimbabwe","ASA":"Australia,Bangladesh,Brunei Darussalam,India,India-GBS,Indonesia,Malaysia,Malaysia-GBS,Nepal,Philippines,Singapore,Sri Lanka,Thailand,Vietnam","EA":"Argentina,Brazil,Colombia,France,Germany,Guernsey,Ireland,Jersey,Poland-GBS,Sweden,Turkey,United Kingdom,United States","GCNA":"China,China-GBS,Hong Kong,Japan,South Korea,Taiwan"}},{"selected_option":"Angola","url_options":{"AME":"Angola,Bahrain,Botswana,Cameroon,Cote d'Ivoire,Egypt,Gambia,Ghana,Iraq,Jordan,Kenya,Lebanon,Mauritius,Nigeria,Oman,Pakistan,Qatar,Saudi Arabia,Sierra Leone,South Africa,Tanzania,United Arab Emirates,Uganda,Zambia,Zimbabwe","ASA":"Australia,Bangladesh,Brunei Darussalam,India,India-GBS,Indonesia,Malaysia,Malaysia-GBS,Nepal,Philippines,Singapore,Sri Lanka,Thailand,Vietnam","EA":"Argentina,Brazil,Colombia,France,Germany,Guernsey,Ireland,Jersey,Poland-GBS,Sweden,Turkey,United Kingdom,United States","GCNA":"China,China-GBS,Hong Kong,Japan,South Korea,Taiwan"}}]
const defaultSwitch = [{"url_options":null},{"url_options":null},{"selected_option":"Global","url_options":{"Global":"United-Arab-Emirates,United-States,Hong-Kong,United-Kingdom"}},{"selected_option":"United-Arab-Emirates","url_options":{"Global":"United-Arab-Emirates,United-States,Hong-Kong,United-Kingdom"}}]

function renderMenuOptions(data) {
  if(Array.isArray(data)) {
    let customSelect1Options = ``
    let customSelect2Options = ``
    let countrySelectOptions = ``
    let regionSelectOptions = ``
    
    let selectedOption1 = null
    let selectedOption2 = null
    let selectedRegion = null
    
    let labelCustomField1 = null
    let labelCustomField2 = null
    
    data.forEach((field, index) => {
      console.log(field)
      
      // custom option 1
      if (index === 0) {
        selectedOption1 = field.selected_option
        if (field.url_options) {
          labelCustomField1 = Object.keys(field.url_options)[0]
          customSelect1Options += `<option value="${selectedOption1}" selected>${selectedOption1}</option>`
          customSelect1Options += addOptionsToSelect(field, selectedOption1);
        }
        
      }
      
      // custom option 2
      if (index === 1) {
        selectedOption2 = field.selected_option
        if (selectedOption2) {
          if (field.url_options) {
            labelCustomField2 = Object.keys(field.url_options)[0]
            customSelect2Options += `<option value="${selectedOption2}" selected>${selectedOption2}</option>`
            customSelect2Options += addOptionsToSelect(field, selectedOption2);
          }
        }
      }
      
      // Region
      if (index === 2) {
        selectedRegion = field.selected_option
        if (selectedRegion) {
          if (field.url_options) {
            regionSelectOptions += `<option value="${selectedRegion}" selected>${selectedRegion}</option>`
            Object.keys(field.url_options).forEach(region => {
              if (region !== selectedRegion) regionSelectOptions += `<option value="${region}">${region}</option>`
            })
          }
        }
      }
      
      // Country
      if (index === 3) {
        let selectedCountry = field.selected_option
        if (selectedCountry) {
          if (field.url_options) {
            countrySelectOptions += `<option value="${field.selected_option}" selected>${field.selected_option}</option>`
            Object.keys(field.url_options).forEach(region => {
              field.url_options[region].split(',').forEach(country => {
                if (country !== selectedCountry) countrySelectOptions += `<option value="${country}">${country}</option>`
              })
            })
          }
        }
      }
      
    })
    
    let customSelect1 =''
    let customSelect2 =''
    
    if (labelCustomField1) customSelect1 = `<label class="custom-label">${labelCustomField1}</label><select  class="js-custom-select-1 custom-dashbord-select">${customSelect1Options}</select>`
    if (labelCustomField2) customSelect2 = `<label class="custom-label">${labelCustomField2}</label><select class="js-custom-select-2 custom-dashbord-select">${customSelect2Options}</select>`
    
    
    
    let customSelectRegion = `<label class="custom-label">Region</label><select class="js-custom-select-region custom-dashbord-select">${regionSelectOptions}</select>`
    let customSelectCountry = `<label class="custom-label">Country</label><select class="js-custom-select-country custom-dashbord-select">${countrySelectOptions}</select>`
    
    let buttonsContainer = document.querySelector('.avatar-block + .form-block .buttons')
    buttonsContainer.insertAdjacentHTML('beforebegin', customSelectRegion + customSelectCountry + customSelect1 + customSelect2)
  
    $('.js-custom-select-1').on('change', function(){
      let val = $(this).val()
      data[0].selected_option = val

      updateInputData(data)
    })
    
    $('.js-custom-select-2').on('change', function(){
      let val = $(this).val()
      data[1].selected_option = val
      
      updateInputData(data)
    })
    
    $('.js-custom-select-region').on('change', function(){
      let val = $(this).val()
      data[2].selected_option = val
      
      updateInputData(data)
    })
    
     $('.js-custom-select-country').on('change', function(){
      let val = $(this).val()
      data[3].selected_option = val
      
      updateInputData(data)
      
    })
  
  }
}

let detectSucessAlert = () => {
  let avatarBlockSuccessAlert = document.querySelector('.avatar-block .alert.success')
  if (avatarBlockSuccessAlert) {
    if (!avatarBlockSuccessAlert.classList.value.includes('touched')) {
      let webhookData = {
        "email" : document.querySelector('.form-block .input-group:nth-of-type(1) input').value,
        "name" : document.querySelector('.form-block .input-group:nth-of-type(2) input').value,
        "region" : $('.js-custom-select-region').val(),
        "country": $('.js-custom-select-country').val(),
        "custom_field_1": `${$('.js-custom-select-1').val()}`,
        "custom_field_2": `${$('.js-custom-select-2').val()}`
      }
      $.ajax({
        type : 'POST',
        url : 'https://hooks.zapier.com/hooks/catch/7151953/ok26j86/',  
        data: JSON.stringify(webhookData),
        success:function (data) {
          console.log('webhook success data');
          console.log(data);
          console.log(webhookData)
        },
        error: function(xhr, status, error) {}
      })
      avatarBlockSuccessAlert.classList.add('touched')
    }
  }
  setTimeout(() => detectSucessAlert(), 500)
}
function updateInputData(data) {
  document.querySelectorAll('.input-group label').forEach(label => {
    if (label.innerText === 'Country') {
      var $input = label.nextElementSibling;
    }
  })
  var $input = $('.form-block .input-group:nth-of-type(3) input').val(JSON.stringify(data));
  var e = document.createEvent('HTMLEvents');
  e.initEvent('input', true, true);
  $input[0].dispatchEvent(e);
  console.log(data)
  console.log($input.val())
}

function addOptionsToSelect(field, selected) {
  if (field.url_options === null) return ''
  let array = field.url_options[Object.keys(field.url_options)[0]].split(',')
  let options = '';
  console.log(array)
  array.forEach(option => {
    let mutatedOption = decodeURI(option).replace('%26', '').trim()
    if (mutatedOption !== selected.trim()) options += `<option value="${mutatedOption}">${mutatedOption}</option>`
  })
  return options;
}
function IsJsonString(str) {
  try {
      JSON.parse(str);
  } catch (e) {
      return false;
  }
  return true;
}
let detectDashboardPage = () => {
  if (location.href.includes('/dashboard')) {
    let input = document.querySelector('.form-block .input-group:nth-of-type(3) input')
    if (input) {
      document.querySelectorAll('.input-group label').forEach(label => {
        if (label.innerText === 'Country') {
          input = label.nextElementSibling;
        }
      })
      if (!input.classList.value.includes('touched')) {
        console.log('valid json?' + IsJsonString(input.value))
        if (IsJsonString(input.value)) {
          let data = JSON.parse(input.value)
          console.log(data)
          detectSucessAlert()
          renderMenuOptions(data)
        } else {
          $.ajax({
            type : 'GET',
            url : '/api/ownerships',  
            success:function (data) {
              // CBRE : Unlimited Access
              if (data[0].product_id === 32607) {
                input.value = JSON.stringify(defaultInputCBRE)
                let data = JSON.parse(input.value)
                console.log(input.value)
                detectSucessAlert()
                renderMenuOptions(data)
              }
              if (data[0].product_id === 31798) {
                input.value = JSON.stringify(defaultInputSCB)
                let data = JSON.parse(input.value)
                console.log(input.value)
                detectSucessAlert()
                renderMenuOptions(data)
              }
              if (data[0].product_id === 31797) {
                input.value = JSON.stringify(defaultSwitch)
                let data = JSON.parse(input.value)
                console.log(input.value)
                detectSucessAlert()
                renderMenuOptions(data)
              }
            },
            error: function(xhr, status, error) {}
          })
        }
        input.classList.add('touched')
      }
    }
  }
  setTimeout(() => detectDashboardPage(), 500)
}
detectDashboardPage()