File

src/app/district-mapping/district-mapping.page.ts

Implements

OnDestroy

Metadata

Index

Properties
Methods
Accessors

Constructor

constructor(profileService: ProfileService, preferences: SharedPreferences, deviceRegisterService: DeviceRegisterService, deviceInfo: DeviceInfo, headerService: AppHeaderService, commonUtilService: CommonUtilService, formAndFrameworkUtilService: FormAndFrameworkUtilService, router: Router, location: Location, appGlobalService: AppGlobalService, events: Events, platform: Platform, telemetryGeneratorService: TelemetryGeneratorService, formLocationFactory: FormLocationFactory, locationHandler: LocationHandler, profileHandler: ProfileHandler, tncUpdateHandlerService: TncUpdateHandlerService, externalIdVerificationService: ExternalIdVerificationService)
Parameters :
Name Type Optional
profileService ProfileService No
preferences SharedPreferences No
deviceRegisterService DeviceRegisterService No
deviceInfo DeviceInfo No
headerService AppHeaderService No
commonUtilService CommonUtilService No
formAndFrameworkUtilService FormAndFrameworkUtilService No
router Router No
location Location No
appGlobalService AppGlobalService No
events Events No
platform Platform No
telemetryGeneratorService TelemetryGeneratorService No
formLocationFactory FormLocationFactory No
locationHandler LocationHandler No
profileHandler ProfileHandler No
tncUpdateHandlerService TncUpdateHandlerService No
externalIdVerificationService ExternalIdVerificationService No

Methods

cancelEvent
cancelEvent(category?: string)
Parameters :
Name Type Optional
category string Yes
Returns : void
Private Async checkLocationMandatory
checkLocationMandatory()
Returns : any
clearUserLocationSelections
clearUserLocationSelections()
Returns : void
fieldConfig
fieldConfig()
Returns : void
generateLocationCaptured
generateLocationCaptured(isEdited: boolean)
Parameters :
Name Type Optional
isEdited boolean No
Returns : void
generateSubmitInteractEvent
generateSubmitInteractEvent(corReletionList)
Parameters :
Name Optional
corReletionList No
Returns : void
generateTelemetryForCategoryClicked
generateTelemetryForCategoryClicked(location)
Parameters :
Name Optional
location No
Returns : void
generateTelemetryForCategorySelect
generateTelemetryForCategorySelect(value, isState)
Parameters :
Name Optional
value No
isState No
Returns : void
Private getEnvironment
getEnvironment()
Returns : string
goBack
goBack(isNavClicked: boolean)
Parameters :
Name Type Optional
isNavClicked boolean No
Returns : void
handleDeviceBackButton
handleDeviceBackButton()
Returns : void
Private Async initialiseFormData
initialiseFormData(formRequest: FormRequest)
Parameters :
Name Type Optional
formRequest FormRequest No
Returns : any
Async initializeLoader
initializeLoader()
Returns : any
Async ionViewWillEnter
ionViewWillEnter()
Returns : any
ionViewWillLeave
ionViewWillLeave()
Returns : void
isChangedLocation
isChangedLocation(prev, curr)
Parameters :
Name Optional
prev No
curr No
Returns : any
isStateorDistrictChanged
isStateorDistrictChanged(locationCodes)
Parameters :
Name Optional
locationCodes No
Returns : any
ngOnDestroy
ngOnDestroy()
Returns : void
Async onDataLoadStatusChange
onDataLoadStatusChange($event)
Parameters :
Name Optional
$event No
Returns : any
Async onFormInitialize
onFormInitialize(formGroup: FormGroup)
Parameters :
Name Type Optional
formGroup FormGroup No
Returns : any
Async onFormValueChange
onFormValueChange(value: any)
Parameters :
Name Type Optional
value any No
Returns : any
redirectToLogin
redirectToLogin()
Returns : void
Private Async saveDeviceLocation
saveDeviceLocation()
Returns : any
Private setDefaultConfig
setDefaultConfig(fieldConfig: FieldConfig<any>)
Parameters :
Name Type Optional
fieldConfig FieldConfig<any> No
Returns : SbLocation
Private skipLocation
skipLocation()
Returns : void
Async submit
submit()
Returns : any

Properties

Public appGlobalService
Type : AppGlobalService
Private backButtonFunc
Type : Subscription
Public commonUtilService
Type : CommonUtilService
Public deviceInfo
Type : DeviceInfo
Decorators :
@Inject('DEVICE_INFO')
Public events
Type : Events
Optional formGroup
Type : FormGroup
Private Optional formValueSubscription
Type : Subscription
Public headerService
Type : AppHeaderService
hideClearButton
Type : boolean
Default value : false
Private initialFormLoad
Default value : true
isGoogleSignIn
Default value : false
Private isLocationUpdated
Default value : false
Private Optional loader
Type : any
Public location
Type : Location
locationFormConfig
Type : FieldConfig<any>[]
Default value : []
navigateToCourse
Type : number
Default value : 0
params
Public platform
Type : Platform
Private presetLocation
Type : literal type
Default value : {}
Private prevFormValue
Type : any
Default value : {}
Optional profile
Type : Profile
Public router
Type : Router
showNotNowFlag
Default value : false
Private Optional stateChangeSubscription
Type : Subscription
Public telemetryGeneratorService
Type : TelemetryGeneratorService
userData
Type : any

Accessors

isShowBackButton
getisShowBackButton()
source
getsource()
import { Location } from '@angular/common';
import { Component, Inject, OnDestroy } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { NavigationExtras, Router } from '@angular/router';
import { featureIdMap } from '@app/feature-id-map';
import { AppGlobalService, AppHeaderService, CommonUtilService, FormAndFrameworkUtilService } from '@app/services';
import { FormLocationFactory } from '@app/services/form-location-factory/form-location-factory';
import { LocationHandler } from '@app/services/location-handler';
import { ProfileHandler } from '@app/services/profile-handler';
import {
  AuditType, CorReleationDataType, Environment,
  ID, ImpressionType,
  InteractSubtype,
  InteractType,
  PageId
} from '@app/services/telemetry-constants';
import { TelemetryGeneratorService } from '@app/services/telemetry-generator.service';
import { Platform } from '@ionic/angular';
import { Events } from '@app/util/events';
import { Location as SbLocation } from '@project-sunbird/client-services/models/location';
import { FieldConfig } from 'common-form-elements';
import { concat, defer, of, Subscription } from 'rxjs';
import { delay, distinctUntilChanged, filter, mergeMap, pairwise, take, tap } from 'rxjs/operators';
import {
  AuditState, CorrelationData, DeviceInfo, DeviceRegisterRequest,
  DeviceRegisterService,
  FormRequest, LocationSearchResult, Profile, ProfileService,
  SharedPreferences
} from 'sunbird-sdk';
import { LocationConfig, PreferenceKey, ProfileConstants, RegexPatterns, RouterLinks } from '../../app/app.constant';
import { FormConstants } from '../form.constants';
import {ProfileType} from '@project-sunbird/sunbird-sdk';
import { TncUpdateHandlerService } from '@app/services/handlers/tnc-update-handler.service';
import { ExternalIdVerificationService } from '@app/services/externalid-verification.service';

@Component({
  selector: 'app-district-mapping',
  templateUrl: './district-mapping.page.html',
  styleUrls: ['./district-mapping.page.scss'],
})
export class DistrictMappingPage implements OnDestroy {
  get isShowBackButton(): boolean {
    if (window.history.state.isShowBackButton === undefined) {
      return true;
    }
    return window.history.state.isShowBackButton;
  }
  get source() {
    return window.history.state.source;
  }
  formGroup?: FormGroup;
  showNotNowFlag = false;
  locationFormConfig: FieldConfig<any>[] = [];
  hideClearButton : boolean = false;
  profile?: Profile;
  navigateToCourse = 0;
  isGoogleSignIn = false;
  userData: any;
  private backButtonFunc: Subscription;
  private presetLocation: { [locationType: string]: LocationSearchResult } = {};
  private loader?: any;
  private stateChangeSubscription?: Subscription;
  private prevFormValue: any = {};
  private formValueSubscription?: Subscription;
  private initialFormLoad = true;
  private isLocationUpdated = false;
  params;
  constructor(
    @Inject('PROFILE_SERVICE') private profileService: ProfileService,
    @Inject('SHARED_PREFERENCES') private preferences: SharedPreferences,
    @Inject('DEVICE_REGISTER_SERVICE') private deviceRegisterService: DeviceRegisterService,
    @Inject('DEVICE_INFO') public deviceInfo: DeviceInfo,
    public headerService: AppHeaderService,
    public commonUtilService: CommonUtilService,
    private formAndFrameworkUtilService: FormAndFrameworkUtilService,
    public router: Router,
    public location: Location,
    public appGlobalService: AppGlobalService,
    public events: Events,
    public platform: Platform,
    public telemetryGeneratorService: TelemetryGeneratorService,
    private formLocationFactory: FormLocationFactory,
    private locationHandler: LocationHandler,
    private profileHandler: ProfileHandler,
    private tncUpdateHandlerService: TncUpdateHandlerService,
    private externalIdVerificationService: ExternalIdVerificationService
  ) {
    this.appGlobalService.closeSigninOnboardingLoader();
    const extrasState = this.router.getCurrentNavigation().extras.state;
    this.navigateToCourse = extrasState.noOfStepsToCourseToc;
    this.isGoogleSignIn = extrasState.isGoogleSignIn;
    this.userData = this.isGoogleSignIn ? extrasState.userData : '';
    this.params = extrasState.payload;
  }
  goBack(isNavClicked: boolean) {
    this.telemetryGeneratorService.generateBackClickedNewTelemetry(
      !isNavClicked,
      this.getEnvironment(),
      PageId.LOCATION
    );
    this.telemetryGeneratorService.generateBackClickedTelemetry(PageId.DISTRICT_MAPPING, this.getEnvironment(),
      isNavClicked);
    this.location.back();
  }

  async ionViewWillEnter() {
    this.initializeLoader();
    this.profile = await this.profileService.getActiveSessionProfile({ requiredFields: ProfileConstants.REQUIRED_FIELDS }).toPromise();
    const isLoggedIn = this.appGlobalService.isUserLoggedIn();
    this.presetLocation = (await this.locationHandler.getAvailableLocation(
      this.profile.serverProfile ? this.profile.serverProfile : this.profile, isLoggedIn))
      .reduce<{ [code: string]: LocationSearchResult }>((acc, loc) => {
        if (loc) { acc[loc.type] = loc; }
        return acc;
      }, {});
    try {
        await this.initialiseFormData({
          ...FormConstants.LOCATION_MAPPING,
          subType: this.presetLocation['state'] ? this.presetLocation['state'].code : FormConstants.LOCATION_MAPPING.subType
        });
      } catch (e) {
        await this.initialiseFormData(FormConstants.LOCATION_MAPPING);
      }
    this.handleDeviceBackButton();
    this.checkLocationMandatory();
    this.telemetryGeneratorService.generateImpressionTelemetry(
      ImpressionType.PAGE_REQUEST, '',
      PageId.LOCATION,
      this.getEnvironment()
    );
    this.telemetryGeneratorService.generateImpressionTelemetry(
      ImpressionType.VIEW,
      '',
      PageId.DISTRICT_MAPPING,
      this.getEnvironment(), '', '', '', undefined,
      featureIdMap.location.LOCATION_CAPTURE);
    this.headerService.hideHeader();
    const correlationList: Array<CorrelationData> = [];
    this.telemetryGeneratorService.generatePageLoadedTelemetry(
      PageId.LOCATION,
      this.getEnvironment(),
      undefined,
      undefined,
      undefined,
      undefined,
      correlationList
    );
  }

  async initializeLoader() {
    if (!this.loader) {
      this.loader = await this.commonUtilService.getLoader();
    }
  }

  handleDeviceBackButton() {
    if (this.isShowBackButton) {
      this.backButtonFunc = this.platform.backButton.subscribeWithPriority(10, () => {
        this.goBack(false);
      });
    }
  }

  ionViewWillLeave(): void {
    if (this.backButtonFunc) {
      this.backButtonFunc.unsubscribe();
    }
  }

  async submit() {
    this.saveDeviceLocation();
    const locationCodes = [];
    for(const acc in this.formGroup.value.children['persona']) {
      if (this.formGroup.value.children['persona'][acc]) {
        const location: SbLocation = this.formGroup.value.children['persona'][acc] as SbLocation;
        if (location.type) {
          locationCodes.push({
            type: location.type,
            code: location.code
          });
        }
      }
    }

    const corRelationList: CorrelationData[] =  locationCodes.map(r => ({ type: r.type, id: r.code || '' }));
    this.generateSubmitInteractEvent(corRelationList);
    this.telemetryGeneratorService.generateInteractTelemetry(
      this.isLocationUpdated ? InteractType.LOCATION_CHANGED : InteractType.LOCATION_UNCHANGED,
      this.isStateorDistrictChanged(locationCodes),
      this.getEnvironment(),
      PageId.DISTRICT_MAPPING,
      undefined,
      undefined,
      undefined,
      featureIdMap.location.LOCATION_CAPTURE,
      ID.SUBMIT_CLICKED
    );
    if (this.appGlobalService.isUserLoggedIn()) {
      if (!this.commonUtilService.networkInfo.isNetworkAvailable) {
        this.commonUtilService.showToast('INTERNET_CONNECTIVITY_NEEDED');
        return;
      }
      const name = this.formGroup.value['name'].replace(RegexPatterns.SPECIALCHARECTERSANDEMOJIS, '').trim();
      const userTypes = [];
      if (this.formGroup.value['persona'] && this.formGroup.value.children['persona'] && this.formGroup.value.children['persona']['subPersona'] && this.formGroup.value.children['persona']['subPersona'].length) {
        if (typeof this.formGroup.value.children['persona']['subPersona'] === 'string') {
          userTypes.push({
            type: this.formGroup.value['persona'],
            subType: this.formGroup.value.children['persona']['subPersona'] || undefined
          });
        }
        else if (Array.isArray(this.formGroup.value.children['persona']['subPersona'])) {
          for (let i = 0; i < this.formGroup.value.children['persona']['subPersona'].length; i++) {
            if(this.formGroup.value.children['persona']['subPersona'][i]){
              userTypes.push({
                "type": this.formGroup.value['persona'],
                "subType": this.formGroup.value.children['persona']['subPersona'][i]
              })
            }
          }
        }
      }
      else{
        userTypes.push({
          "type" : this.formGroup.value['persona']
        });
      }
      const req = {
        userId: this.appGlobalService.getCurrentUser().uid || this.profile.uid,
        profileLocation: locationCodes,
        ...(name ? { firstName: name } : {}),
        lastName: '',
        profileUserTypes: userTypes
      };
      if (this.isGoogleSignIn && this.userData.isMinor) {
          const navigationExtras: NavigationExtras = {
            state: {
              userData: {...this.userData,
                location: this.formGroup.value.children['persona'],
                profileUserTypes: userTypes,
                userId: this.appGlobalService.getCurrentUser().uid || this.profile.uid}
            }
          };
          this.router.navigate([RouterLinks.SIGNUP_EMAIL], navigationExtras);
      } else {
        if (this.isGoogleSignIn) {
          req['firstName'] = this.userData.name;
          req['dob'] = this.userData.dob;
        }
        const loader = await this.commonUtilService.getLoader();
        await loader.present();
        const isSSOUser = await this.tncUpdateHandlerService.isSSOUser(this.profile);
        this.profileService.updateServerProfile(req).toPromise()
          .then(async () => {
            await loader.dismiss();
            this.preferences.putString(PreferenceKey.SELECTED_USER_TYPE, this.formGroup.value.persona).toPromise().then();
            if (!(await this.commonUtilService.isDeviceLocationAvailable())) { // adding the device loc if not available
              await this.saveDeviceLocation();
            }
            this.isLocationUpdated = false;
            this.generateLocationCaptured(false);
            this.commonUtilService.showToast('PROFILE_UPDATE_SUCCESS');
            this.events.publish('loggedInProfile:update', req);
            if (this.isGoogleSignIn) {
              const categoriesProfileData = {
                hasFilledLocation: true,
                showOnlyMandatoryFields: true,
              };
              this.router.navigate([`/${RouterLinks.PROFILE}/${RouterLinks.CATEGORIES_EDIT}`], {
                state: categoriesProfileData
              });
            } else if (this.profile && (this.source === PageId.GUEST_PROFILE || this.source === PageId.PROFILE_NAME_CONFIRMATION_POPUP)) {
                this.location.back();
            } else if (this.profile && this.source === PageId.PROFILE) {
                this.location.back();
                this.events.publish('UPDATE_TABS', {type: 'SWITCH_TABS_USERTYPE'});
            } else {
              if (this.profile && !isSSOUser) {
                this.appGlobalService.showYearOfBirthPopup(this.profile.serverProfile);
              }
              if (this.appGlobalService.isJoinTraningOnboardingFlow) {
                window.history.go(-this.navigateToCourse);
                this.externalIdVerificationService.showExternalIdVerificationPopup();
              } else {
                this.events.publish('UPDATE_TABS', {type: 'SWITCH_TABS_USERTYPE'});
                this.events.publish('update_header');
              }
            }
          }).catch(async () => {
            await loader.dismiss();
            this.commonUtilService.showToast('PROFILE_UPDATE_FAILED');
            if (this.profile) {
              this.location.back();
            } else {
              if (this.profile && !isSSOUser) {
                this.appGlobalService.showYearOfBirthPopup(this.profile.serverProfile);
              }
              this.router.navigate([`/${RouterLinks.TABS}`]);
              this.events.publish('update_header');
            }
          });
      }
    } else if (this.source === PageId.GUEST_PROFILE) { // block for editing the device location
      this.generateLocationCaptured(true); // is dirtrict or location edit  = true
      await this.saveDeviceLocation();
      this.events.publish('refresh:profile');
      this.location.back();
    } else { // add or update the device loc
      await this.saveDeviceLocation();
      this.appGlobalService.setOnBoardingCompleted();
      const navigationExtras: NavigationExtras = {
        state: {
          loginMode: 'guest'
        }
      };
      this.telemetryGeneratorService.generateAuditTelemetry(
        this.getEnvironment(),
        AuditState.AUDIT_UPDATED,
        undefined,
        AuditType.SET_PROFILE,
        undefined,
        undefined,
        undefined,
        corRelationList
      );
      this.router.navigate([`/${RouterLinks.TABS}`], navigationExtras);
      this.events.publish('update_header');
    }
  }

  private async saveDeviceLocation() {
    const loader = await this.commonUtilService.getLoader();
    await loader.present();
    const req: DeviceRegisterRequest = {
      userDeclaredLocation: {
        ...(Object.keys(this.formGroup.value.children['persona']).reduce((acc, key) => {
          if (this.formGroup.value.children['persona'][key]) {
            acc[key] = (this.formGroup.value.children['persona'][key] as SbLocation).name;
            acc[key + 'Id'] = (this.formGroup.value.children['persona'][key] as SbLocation).id;
          }
          return acc;
        }, {})),
        declaredOffline: !this.commonUtilService.networkInfo.isNetworkAvailable
      }
    } as any;
    this.deviceRegisterService.registerDevice(req).toPromise();
    if (this.appGlobalService.isGuestUser) {
      this.preferences.putString(PreferenceKey.GUEST_USER_LOCATION, JSON.stringify(req.userDeclaredLocation)).toPromise();
    }
    this.preferences.putString(PreferenceKey.DEVICE_LOCATION, JSON.stringify(req.userDeclaredLocation)).toPromise();
    this.commonUtilService.handleToTopicBasedNotification();
    await loader.dismiss();
  }

  private async checkLocationMandatory() {
    let skipValues = [];
    await this.formAndFrameworkUtilService.getLocationConfig()
      .then((locationConfig) => {
        for (const field of locationConfig) {
          if (field.code === LocationConfig.CODE_SKIP) {
            skipValues = field.values;
            break;
          }
        }
      });
    for (const value of skipValues) {
      if (this.appGlobalService.isUserLoggedIn()) {
        if (!this.profile && value === LocationConfig.SKIP_USER) {
          this.showNotNowFlag = true;
        }
      } else if (!(this.source === PageId.GUEST_PROFILE) && value === LocationConfig.SKIP_DEVICE) {
        this.showNotNowFlag = true;
      }
    }
  }

  private skipLocation() {
    this.router.navigate([`/${RouterLinks.TABS}`]);
    this.events.publish('update_header');
  }

  private getEnvironment(): string {
    return (this.source === PageId.GUEST_PROFILE || this.source === PageId.PROFILE) ? Environment.USER : Environment.ONBOARDING;
  }

  cancelEvent(category?: string) {
    const correlationList: Array<CorrelationData> = [];
    /* New Telemetry */
    correlationList.push({ id: PageId.POPUP_CATEGORY, type: CorReleationDataType.CHILD_UI });
    this.telemetryGeneratorService.generateInteractTelemetry(
      InteractType.SELECT_CANCEL, '',
      this.getEnvironment(),
      PageId.LOCATION,
      undefined,
      undefined,
      undefined,
      correlationList
    );
  }

  private async initialiseFormData(
    formRequest: FormRequest
  ) {
    let locationMappingConfig: FieldConfig<any>[];
    try {
      locationMappingConfig = await this.formAndFrameworkUtilService.getFormFields(formRequest);
    } catch (e) {
      locationMappingConfig = await this.formAndFrameworkUtilService.getFormFields(FormConstants.LOCATION_MAPPING);
    }
    let selectedUserType = await this.preferences.getString(PreferenceKey.SELECTED_USER_TYPE).toPromise();
    const useCaseList =
      this.appGlobalService.isUserLoggedIn() ? ['SIGNEDIN_GUEST', 'SIGNEDIN'] : ['SIGNEDIN_GUEST', 'GUEST'];
    for (const config of locationMappingConfig) {
      if (config.code === 'name' && (this.source === PageId.PROFILE || this.source === PageId.PROFILE_NAME_CONFIRMATION_POPUP)
      && !this.isGoogleSignIn) {
        config.templateOptions.hidden = false;
        config.default = (this.profile && this.profile.serverProfile && this.profile.serverProfile.firstName) ?
        this.profile.serverProfile.firstName : this.profile.handle;
      } else if (config.code === 'name' && this.source !== PageId.PROFILE) {
        config.validations = [];
      }
      if (config.code === 'persona') {
        if (this.isGoogleSignIn && selectedUserType === ProfileType.NONE) {
          const guestUser = await this.commonUtilService.getGuestUserConfig();
          selectedUserType = (this.profile.serverProfile && !this.profile.serverProfile.profileUserType.type) ?
            guestUser.profileType : selectedUserType;
        }
        config.default = (this.profile && this.profile.serverProfile
        && this.profile.serverProfile.profileUserType.type
        && (this.profile.serverProfile.profileUserType.type !== ProfileType.OTHER.toUpperCase())) ?
        this.profile.serverProfile.profileUserType.type : selectedUserType;
        if (this.source === PageId.PROFILE) {
          config.templateOptions.hidden = false;
        }
      }

      config.default = this.prevFormValue[config.code] || config.default;

      if (config.templateOptions['dataSrc'] && config.templateOptions['dataSrc']['marker'] === 'SUPPORTED_PERSONA_LIST') {
        config.templateOptions.options = (await this.profileHandler.getSupportedUserTypes())
          .filter(userType => {
            return userType.isActive;
          })
          .map(p => ({
            label: p.name,
            value: p.code
          }));
        Object.keys(config.children).forEach((persona) => {
          config.children[persona].map((personaConfig) => {
            if (!useCaseList.includes(personaConfig.templateOptions['dataSrc']['params']['useCase']) && !this.isGoogleSignIn) {
              personaConfig.templateOptions['hidden'] = true;
              personaConfig.validations = [];
            }
            if (!personaConfig.templateOptions['dataSrc']) {
              return personaConfig;
            }
            personaConfig.default = this.setDefaultConfig(personaConfig);
            switch (personaConfig.templateOptions['dataSrc']['marker']) {
              case 'SUBPERSONA_LIST': {
                if (this.profile.serverProfile) {
                  if(personaConfig.templateOptions.multiple){
                    const subPersonaCodes = [];
                    if(!this.profile.serverProfile.profileUserTypes && !this.profile.serverProfile.profileUserTypes.length && this.profile.serverProfile.profileUserType) {
                      if(typeof this.profile.serverProfile.profileUserType === 'string'){
                        subPersonaCodes.push(this.profile.serverProfile.profileUserType);
                      } else if(this.profile.serverProfile.profileUserType.subType){
                        subPersonaCodes.push(this.profile.serverProfile.profileUserType.subType);
                      }
                    }
                    else if(this.profile.serverProfile.profileUserTypes && this.profile.serverProfile.profileUserTypes.length){
                      for( let i =0; i< this.profile.serverProfile.profileUserTypes.length; i++){
                        if(this.profile.serverProfile.profileUserTypes[i].subType){
                          subPersonaCodes.push(this.profile.serverProfile.profileUserTypes[i].subType);
                        }
                      }
                    }
                    personaConfig.default = subPersonaCodes;
                  }
                  else if(this.profile.serverProfile.profileUserType && this.profile.serverProfile.profileUserType.subType){
                    personaConfig.default = this.profile.serverProfile.profileUserType.subType;
                  }
                }
                break;
              }
              case 'STATE_LOCATION_LIST': {
                personaConfig.templateOptions.options = this.formLocationFactory.buildStateListClosure(personaConfig, this.initialFormLoad);
                break;
              }
              case 'LOCATION_LIST': {
                personaConfig.templateOptions.options = this.formLocationFactory.buildLocationListClosure(personaConfig,
                  this.initialFormLoad);
                break;
              }
            }

            personaConfig.default = (this.prevFormValue && this.prevFormValue.children && this.prevFormValue.children.persona) ?
              this.prevFormValue.children.persona[personaConfig.code] :
              personaConfig.default;

            return personaConfig;
          });
        });
      }
    }
    this.initialFormLoad = false;
    this.locationFormConfig = locationMappingConfig;
    this.hideClearButton = false;
     if(this.params){
    this.fieldConfig();
  }
  }
 
  private setDefaultConfig(fieldConfig: FieldConfig<any>): SbLocation {
    if (this.presetLocation[fieldConfig.code]) {
      return this.presetLocation[fieldConfig.code];
    }
    return null;
  }

  async onFormInitialize(formGroup: FormGroup) {
    this.formGroup = formGroup;
    if (this.formValueSubscription) {
      this.formValueSubscription.unsubscribe();
    }
    this.formValueSubscription = this.formGroup.valueChanges.pipe(
      filter((v) => v['children'] && !!Object.keys(v['children']).length),
      distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)),
      pairwise(),
      delay(100),
      filter(() => this.formGroup.dirty),
      tap(([prev, curr]) => {
        const changeField = this.isChangedLocation(prev, curr);
        if (changeField) {
          this.isLocationUpdated = true;
          this.generateTelemetryForCategoryClicked(changeField);
        }
      })
    ).subscribe();
  }

  async onFormValueChange(value: any) {
  }

  async onDataLoadStatusChange($event) {
    if ('LOADING' === $event) {
      await this.loader.present();
    } else {
      await this.loader.dismiss();
      const subPersonaFormControl = this.formGroup.get('children.persona.subPersona');
      if (subPersonaFormControl && !subPersonaFormControl.value) {
        subPersonaFormControl.patchValue(this.profile.serverProfile.profileUserType.subType || null);
      }
      if (!this.stateChangeSubscription) {
        this.stateChangeSubscription = concat(
          of(this.formGroup.get('persona').value),
          this.formGroup.get('persona').valueChanges
        ).pipe(
          distinctUntilChanged(),
          delay(100),
          mergeMap(() => defer(() => {
            return this.formGroup.get('children.persona.state').valueChanges.pipe(
              distinctUntilChanged(),
              take(1)
            );
          }))
        ).subscribe(async (newStateValue) => {
          if (!newStateValue) { return; }
          this.locationFormConfig = undefined;
          this.stateChangeSubscription = undefined;
          this.loader.present();
          this.formGroup.value.children.persona.subPersona = [];
          this.prevFormValue = { ...this.formGroup.value };
          this.initialiseFormData({
            ...FormConstants.LOCATION_MAPPING,
            subType: (newStateValue as SbLocation).code,
          }).catch((e) => {
            console.error(e);
            this.initialiseFormData(FormConstants.LOCATION_MAPPING);
          });
        });
      }
    }
  }

  generateTelemetryForCategorySelect(value, isState) {
    const corRelationList: CorrelationData[] = [{ id: PageId.POPUP_CATEGORY, type: CorReleationDataType.CHILD_UI }];
    corRelationList.push({
      id: value || '',
      type: isState ? CorReleationDataType.STATE : CorReleationDataType.DISTRICT
    });
    this.telemetryGeneratorService.generateInteractTelemetry(
      InteractType.SELECT_SUBMIT, '',
      this.getEnvironment(),
      PageId.LOCATION,
      undefined,
      undefined,
      undefined,
      corRelationList
    );
  }

  clearUserLocationSelections() {
    const stateFormControl = this.formGroup.get('children.persona.state');
    /* istanbul ignore else */
    if (stateFormControl) {
      stateFormControl.patchValue(null);
    }
    const correlationList: Array<CorrelationData> = [];
    correlationList.push({ id: PageId.POPUP_CATEGORY, type: CorReleationDataType.CHILD_UI });
    this.telemetryGeneratorService.generateInteractTelemetry(
      InteractType.SELECT_CANCEL, '',
      this.getEnvironment(),
      PageId.LOCATION,
      undefined,
      undefined,
      undefined,
      correlationList
    );
  }

  generateSubmitInteractEvent(corReletionList) {
    this.telemetryGeneratorService.generateInteractTelemetry(
      InteractType.SELECT_SUBMIT, '',
      this.getEnvironment(),
      PageId.LOCATION,
      undefined,
      undefined,
      undefined,
      corReletionList
    );
  }

  ngOnDestroy() {
    if (this.formValueSubscription) {
      this.formValueSubscription.unsubscribe();
    }
  }

  isChangedLocation(prev, curr) {
    if(prev.persona!= curr.persona){
      this.telemetryGeneratorService.generateInteractTelemetry(
        InteractType.ROLE_CHANGED, '',
        this.getEnvironment(),
        PageId.LOCATION,
        undefined,
        undefined,
        undefined,
        undefined,
        curr.persona
      );
    }
    let newLocation;
    Object.keys(curr['children']['persona']).forEach((key) => {
      if (curr['children']['persona'][key] && (!prev['children']['persona'][key] ||
       (curr['children']['persona'][key].code !== prev['children']['persona'][key].code))) {
        newLocation = curr['children']['persona'][key];
      }
    });
    return newLocation;
  }

  generateTelemetryForCategoryClicked(location) {
    const correlationList: Array<CorrelationData> = [];
    correlationList.push({
    id: location.name,
    type: location.type.charAt(0).toUpperCase() + location.type.slice(1)
    });
    this.telemetryGeneratorService.generateInteractTelemetry(
      InteractType.SELECT_CATEGORY, '',
      this.getEnvironment(),
      PageId.LOCATION,
      undefined,
      undefined,
      undefined,
      correlationList
    );
  }

  isStateorDistrictChanged(locationCodes) {
    let changeStatus;
    locationCodes.forEach((d) => {
      if (!changeStatus && d.type === 'state' && this.presetLocation['state']
      && (d.code !== this.presetLocation['state'].code)) {
        changeStatus = InteractSubtype.STATE_DIST_CHANGED;
      } else if (!changeStatus && d.type === 'district' && this.presetLocation['district']
      && (d.code !== this.presetLocation['district'].code)) {
        changeStatus = InteractSubtype.DIST_CHANGED;
      }
    });
    return changeStatus;
  }

  generateLocationCaptured(isEdited: boolean) {
    this.telemetryGeneratorService.generateInteractTelemetry(
      InteractType.TOUCH,
      InteractSubtype.LOCATION_CAPTURED,
      this.getEnvironment(),
      PageId.DISTRICT_MAPPING,
      undefined,
      {
        isEdited
      }, undefined,
      featureIdMap.location.LOCATION_CAPTURE);
  }

  redirectToLogin() {
    this.router.navigate([RouterLinks.SIGN_IN]);
  }
  fieldConfig(){
    this.locationFormConfig.forEach(element => {
      if(element.code  != this.params.code){
        element.templateOptions.hidden = true;
        element.templateOptions.disabled = true;
        if( this.params.children){
          let keys = Object.keys(element.children);
          keys.forEach(key => {
            element.children[key].forEach(childEl => {
              childEl.templateOptions.hidden =true;
              childEl.templateOptions.disabled =true;
              this.hideClearButton = true;
             });
          });
        }
      }
    });
  }
}
<ion-content>
  <div class="dm-header ion-padding" [ngClass]="{'dm-header-new': !isShowBackButton}">
    <span role="button" aria-label="back"><ion-icon *ngIf="isShowBackButton" name="arrow-back" role="button" aria-label="back" (click)="goBack(true)"
      class="top-back-button"></ion-icon></span>
      <span class="preference-info" role="heading" aria-level="1" *ngIf="!isGoogleSignIn">{{ 'SET_PREFERENCE' | translate }}</span>
      <span class="preference-info" role="heading" aria-level="1" *ngIf="isGoogleSignIn">{{'FRMELEMNTS_LBL_STEP' | translate:{'page_number': '2/4'} }}</span>
    <button class="pull-right sb-btn-sm sb-btn-outline-info" (click)="skipLocation()"
      *ngIf="showNotNowFlag">{{'NOT_NOW'| translate}}</button>
  </div>
  <div class="ion-padding" *ngIf="!profile">
    <div class="heading"><strong>{{'YOUR_LOCATION'| translate}}</strong></div>
    <div class="sub-heading">{{'YOUR_LOCATION_DETAILS' | translate}}</div>
  </div>

  <div class="login-header" *ngIf="isGoogleSignIn">
    To discover relevant content update the following details:
</div>

  <div class="px-16">
    <sb-form *ngIf="locationFormConfig && locationFormConfig.length"
             [platform]="'mobile'"
             [config]="locationFormConfig"
             (initialize)="onFormInitialize($event)"
             (valueChanges)="onFormValueChange($event)"
             (dataLoadStatus)="onDataLoadStatusChange($event)">
    </sb-form>
  </div>
  <div class="login-content" *ngIf="isGoogleSignIn">
    <label>Already have an account?</label>
    <button class="login-info sb-btn sb-btn-normal sb-btn-outline-primary text-uppercase"
      aria-label="Already have an account? Login here" tabindex="0" (click)="redirectToLogin()"
      type="submit">Login</button>
  </div>
  <div class="bottom-section"></div>
  <div class="ios-footer" *ngIf="platform.is('ios')">
    <div class="btn-info" *ngIf="locationFormConfig && locationFormConfig.length">
      <button class="block-button-clear"
              [ngClass]="{'blur-clear-btn': formGroup?.invalid}" [disabled]="formGroup?.invalid"
              (click)="clearUserLocationSelections()">{{'CLEAR' | translate}}
      </button>
      <button class="block-button-save"
              [ngClass]="{'blur-save-btn': formGroup?.invalid}" [disabled]="formGroup?.invalid"
              (click)="submit()">{{'BTN_SUBMIT' | translate}}
      </button>
    </div>
  </div>
</ion-content>
<div class="footer" *ngIf="platform.is('android')">
  <div class="btn-info" *ngIf="locationFormConfig && locationFormConfig.length">
    <button class="block-button-clear"
            [ngClass]="{'blur-clear-btn': formGroup?.invalid || hideClearButton}" [disabled]="formGroup?.invalid || hideClearButton"
            (click)="clearUserLocationSelections()">{{'CLEAR' | translate}}
    </button>
    <button class="block-button-save"
            [ngClass]="{'blur-save-btn': formGroup?.invalid}" [disabled]="formGroup?.invalid"
            (click)="submit()">{{'BTN_SUBMIT' | translate}}
    </button>
  </div>
</div>

./district-mapping.page.scss

@import "src/assets/styles/_variables.scss";
@import "src/assets/styles/_custom-mixins";

:host {
    .input-container {
        border: 0.5px solid map-get($colors, primary_black);
        padding: 11px;

        .input {
            border: map-get($colors, white);
            outline: none;
        }

        .input-icon {
            float: right;
            font-size: 1.25rem;
            color: map-get($colors, primary_black);
        }
    }

    .font-size-13{
      font-size: 0.813rem;
    }
    
    .error-input{
      border-bottom: 1.5px solid map-get($colors, bright_red_e7) !important;
    }

    .label {
        font-size: 0.813rem;
        padding-left: 16px;
        color: map-get($colors, primary_black);
    }

    .name {
        padding-bottom: 16px;
        padding-bottom: 22px;
    }

    input:-internal-autofill-selected {
        background-color: white !important;
    }

    .margin-top-6 {
        margin-top: 6vh;
    }

    .name-feild {
        width: 100%;
        border-right: white;
        border-top: white;
        border-left: white;
        border-bottom: 0.5px solid map-get($colors, primary_black);
        padding-bottom: 6px;
        padding-left: 11px;
        font-size: 0.813rem;
        outline: none;
    }

    input::placeholder {
        padding-left: 16px;
    }

    .oneline-input {
        border-left: white;
        border-right: white;
        border-top: white;
        border-bottom: 0.5px solid map-get($colors, primary_black);
        width:100%;
        outline: none;
    }

    .disableInput {
        background-color: map-get($colors, white_eb);
    }
    .danger {
        color: red;
    }

    .disabled-button {
        opacity: 0.5;
    }

    .input-label {
        font-weight: 200;
        font-size: $font-size-base;
        color: map-get($colors, gray_79);
    }

    .margin-top {
        margin-top: 20px;
    }

    .margin-bottom {
        margin-bottom: 20px;
    }

    .showList {
        box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
        max-height: 12.5rem;
        overflow-y: scroll;

        ul {
            list-style-type: none;
        }

        li {
            padding: 8px 0px 8px 8px;
        }
    }

    .footer {
        width: 100%;
        bottom: 0;
    }
    .ios-footer {
        width: 100%;
        bottom: 1em;
        position: fixed;
    }

    .heading {
        color: $blue;
        text-align: center;
        font-size: $font-size-base;
        margin: 16px 0px 16px 0px;
    }

    .sub-heading {
        color: map-get($colors, primary_black);
        font-size: 0.75rem;
        margin: 16px 0px 25px 0px;
    }

    .top-back-button {
        font-size: 1.25rem;
        @include rtl() {
            float: right;
        }
    }

    ::-webkit-scrollbar {
        width: 0.313rem;
    }

    ::-webkit-scrollbar-track {
        box-shadow: inset 0 0 5px grey;
        border-radius: 10px;
    }

    ::-webkit-scrollbar-thumb {
        background: map-get($colors, gray_81);
        border-radius: 10px;
    }

    ::-webkit-scrollbar-thumb:hover {
        background: map-get($colors, gray_ba);
    }

    .block-button-save{
        color: white;
        background-color: $blue;
        font-size: 1rem;
        padding: 8px 0;
        margin-left: 18px;
        border: 2px solid $blue;
        width: 45%;
      }
      .block-button-clear{
        color: $blue;
        background-color: white;
        font-size: 1rem;
        padding: 8px 0;
        border: 2px solid $blue;
        width: 45%;
        margin-left: 0.7rem;
      }
    .arrow-icon {
        right: 0.938rem;
        top: 50%;
        width: 1.375rem;
        float: right;
        @include rtl {
            float: left;
            margin-left: 10px;
        }
        &.animate {
            position: relative;
            animation: upDownAnimate 5s linear infinite;
            animation-duration: 0.9s;
        }
    }
    .btn-info{
        padding: 20px
    }
    .login-info{
        border: none !important;
    }
    .preference-info{
        font-size: 1.125rem;
        position: absolute;
        margin-left: 10px;
    }

    .blur-clear-btn{
        color: $primary-100 !important;
        border-color: 2px solid $primary-100 !important;
    }
    .blur-save-btn{
        background-color: map-get($colors, light_blue_color) !important;
        border-color: 2px solid $primary-100 !important;
    }
}

@keyframes upDownAnimate {
    0% {right: 0;}
    50% {right: 10px;}
    100% {right: 0;}
}

.ios ::ng-deep .sb-modal {
    bottom: calc(env(safe-area-inset-bottom) + 20px) !important;
}

.bottom-section {
    width: 4.688rem;
    height: 4.688rem;
}

.dm-header-new {
    padding-bottom: 2rem;
}

.login-header {
    font-size: 1.2rem;
    font-weight: 700;
    text-align: center;
    padding: 1.5rem 1rem 1.5rem 1rem;
}

  .login-content {
      text-align: center;
      padding-top: 1rem;
  }

  label {
    display: inline-block;
    font-weight: 700;
  }

  :host ::ng-deep {
    --sbt-pill-bg-active: #004594;
    --sbt-pill-text-hover: #ffffff;
    --sbt-pill-hs: 212,100%;
    --sbt-pill-bg: hsl(var(--sbt-pill-hs), 90%);
    --sbt-box-shadow-black: rgba(0, 0, 0, 0.1);
    --sbt-box-shadow-3px: 0.1875rem 0.1875rem 0.125rem 0 var(--sbt-box-shadow-black);
    --sbt-theme-purple-selectbox: #6841B3;
    --sbt-theme-purple-selectbox-lbg: #F2EEFF;
    --sbt-bradius: 0.125rem;
    --sbt-bradius-24: calc(var(--sbt-bradius) * 12);
  
    .cfe-multiselect-container {
        ul, li {
            margin: 0;
            padding: 0;
            list-style: none;
          }
      
      margin-bottom: 1rem;
  
      .cfe-multiselect-field {
        display: flex;
  
        height: 2.76rem;
        line-height: 2.5rem;
        border-radius: var(--sbt-bradius-24) !important;
  
        font-weight: 700;
        font-size: .75rem;
        width: 100%;
        min-height: 2rem;
  
        border: 1px solid gray;
        padding: 0.188rem 1.25rem;
        white-space: normal;
        outline: 0;
        min-width: 14rem;
        box-shadow: var(--sbt-box-shadow-3px);
        transition: box-shadow .1s ease, width .1s ease;
  
        -webkit-tap-highlight-color: transparent;
        text-align: left;
  
        .cfe-multiselect-field-label-container {
          height: 100%;
          width: 100%;
          overflow: hidden;
  
          order: 1;
          flex-grow: 1;
          border-bottom-color: transparent !important;
  
          ul {
            height: 100%;
            width: 100%;
            overflow: hidden;
  
            white-space: nowrap;
            text-overflow: ellipsis;
            padding-left: 0 !important;
          }
  
          .cfe-multiselect-field-label {
            display: inline;
            font-size: 0.95rem !important;
          }
        }
  
        .cfe-multiselect-field-caret {
          order: 2;
          flex-shrink: 0;
  
          box-sizing: border-box;
          padding-right: .75rem;
          top: .3rem !important
        }
      }

      .sb-modal ul {
        list-style-type: none;
      }
    }
  }
Legend
Html element
Component
Html element with directive

results matching ""

    No results matching ""