File

src/app/profile/manage-user-profiles/manage-user-profiles.page.ts

Implements

OnInit

Metadata

Index

Properties
Methods

Constructor

constructor(profileService: ProfileService, sharedPreferences: SharedPreferences, appHeaderService: AppHeaderService, router: Router, commonUtilService: CommonUtilService, events: Events, telemetryGeneratorService: TelemetryGeneratorService, platform: Platform, location: Location, popoverCtrl: PopoverController, tncUpdateHandlerService: TncUpdateHandlerService)
Parameters :
Name Type Optional
profileService ProfileService No
sharedPreferences SharedPreferences No
appHeaderService AppHeaderService No
router Router No
commonUtilService CommonUtilService No
events Events No
telemetryGeneratorService TelemetryGeneratorService No
platform Platform No
location Location No
popoverCtrl PopoverController No
tncUpdateHandlerService TncUpdateHandlerService No

Methods

addUser
addUser()
Returns : void
Private handleBackButtonEvents
handleBackButtonEvents()
Returns : void
Private handleHeaderEvents
handleHeaderEvents($event)
Parameters :
Name Optional
$event No
Returns : void
ionViewWillEnter
ionViewWillEnter()
Returns : void
ionViewWillLeave
ionViewWillLeave()
Returns : void
ngOnInit
ngOnInit()
Returns : void
selectUser
selectUser(user, index)
Parameters :
Name Optional
user No
index No
Returns : void
Private Async showSwitchSuccessPopup
showSwitchSuccessPopup(name)
Parameters :
Name Optional
name No
Returns : any
switchUser
switchUser()
Returns : void

Properties

Public appName
Type : string
Default value : ''
Private backButtonFunc
Type : Subscription
Private headerObservable
Type : any
Public manageProfileList$
Type : Observable<ServerProfile[]>
Public platform
Type : Platform
Public sbCardConfig
Type : object
Default value : { size: 'medium', isBold: false, isSelectable: false, view: 'horizontal' }
Private selectedUser
Type : any
Public selectedUserIndex
Default value : -1
import { Component, OnInit, Inject } from '@angular/core';
import { AppHeaderService } from '@app/services/app-header.service';
import { RouterLinks, ProfileConstants, PreferenceKey } from '@app/app/app.constant';
import { Router } from '@angular/router';
import { CommonUtilService } from '@app/services/common-util.service';
import {
  ProfileService,
  CachedItemRequestSourceFrom,
  SharedPreferences,
  ServerProfile,
  CorrelationData
} from '@project-sunbird/sunbird-sdk';
import { AppGlobalService } from '@app/services/app-global-service.service';
import { Platform, PopoverController } from '@ionic/angular';
import { Events } from '@app/util/events';
import { Observable, EMPTY, combineLatest, Subscription } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { TelemetryGeneratorService } from '@app/services/telemetry-generator.service';
import { InteractType, Environment, PageId, ID, CorReleationDataType, ImpressionType } from '@app/services/telemetry-constants';
import { Location } from '@angular/common';
import { ToastNavigationComponent } from '@app/app/components/popups/toast-navigation/toast-navigation.component';
import { TncUpdateHandlerService } from '@app/services/handlers/tnc-update-handler.service';

@Component({
  selector: 'app-manage-user-profiles',
  templateUrl: './manage-user-profiles.page.html',
  styleUrls: ['./manage-user-profiles.page.scss'],
})
export class ManageUserProfilesPage implements OnInit {

  private selectedUser: any;
  private backButtonFunc: Subscription;
  private headerObservable: any;

  public sbCardConfig = {
    size: 'medium',
    isBold: false,
    isSelectable: false,
    view: 'horizontal'
  };
  public manageProfileList$: Observable<ServerProfile[]>;
  public selectedUserIndex = -1;
  public appName = '';

  constructor(
    @Inject('PROFILE_SERVICE') private profileService: ProfileService,
    @Inject('SHARED_PREFERENCES') private sharedPreferences: SharedPreferences,
    private appHeaderService: AppHeaderService,
    private router: Router,
    private commonUtilService: CommonUtilService,
    private events: Events,
    private telemetryGeneratorService: TelemetryGeneratorService,
    public platform: Platform,
    private location: Location,
    private popoverCtrl: PopoverController,
    private tncUpdateHandlerService: TncUpdateHandlerService
  ) {
    this.manageProfileList$ = combineLatest([
      this.profileService.getActiveSessionProfile({ requiredFields: ProfileConstants.REQUIRED_FIELDS }),
      this.profileService.managedProfileManager.getManagedServerProfiles({
        from: CachedItemRequestSourceFrom.SERVER,
        requiredFields: ProfileConstants.REQUIRED_FIELDS
      })
    ]).pipe(
      map(([activeProfile, profiles]) => {
        return profiles.filter(p => p.id !== activeProfile.uid);
      }),
      catchError(err => {
        this.commonUtilService.showToast('ERROR_WHILE_FETCHING_USERS');
        console.error(err);
        return EMPTY;
      })
    );
  }

  ngOnInit() {
    this.sharedPreferences.getString('app_name').toPromise().then(value => {
      this.appName = value;
    });
  }

  ionViewWillEnter() {
    this.appHeaderService.showHeaderWithBackButton();
    this.handleBackButtonEvents();
    this.headerObservable = this.appHeaderService.headerEventEmitted$.subscribe(eventName => {
      this.handleHeaderEvents(eventName);
    });
    this.telemetryGeneratorService.generateImpressionTelemetry(
      ImpressionType.VIEW,
      '',
      PageId.MANAGE_USERS,
      Environment.USER,
    );
  }

  ionViewWillLeave() {
    if (this.headerObservable) {
      this.headerObservable.unsubscribe();
    }
    if (this.backButtonFunc) {
      this.backButtonFunc.unsubscribe();
    }
  }

  private handleBackButtonEvents() {
    this.backButtonFunc = this.platform.backButton.subscribeWithPriority(0, async () => {
      this.telemetryGeneratorService.generateBackClickedTelemetry(
        PageId.MANAGE_USERS,
        Environment.USER,
        false
      );
      this.location.back();
    });
  }

  selectUser(user, index) {
    this.selectedUserIndex = index;
    this.selectedUser = user;
  }

  switchUser() {
    if (!this.selectedUser || !this.selectedUser.id) {
      return;
    }
    const cData: Array<CorrelationData> = [
      { id: this.selectedUser.id || '', type: CorReleationDataType.SWITCHED_USER }
    ];
    this.telemetryGeneratorService.generateInteractTelemetry(
      InteractType.SELECT_ADD,
      '',
      Environment.USER,
      PageId.CREATE_MANAGED_USER,
      undefined,
      undefined,
      undefined,
      cData,
      ID.BTN_SWITCH
    );
    this.profileService.managedProfileManager.switchSessionToManagedProfile({ uid: this.selectedUser.id }).toPromise().then(async res => {
      this.events.publish(AppGlobalService.USER_INFO_UPDATED);
      this.events.publish('loggedInProfile:update');
      if(this.selectedUser.profileUserType && this.selectedUser.profileUserType.type){
        await this.sharedPreferences.putString(PreferenceKey.SELECTED_USER_TYPE, this.selectedUser.profileUserType.type).toPromise();
        this.events.publish('UPDATE_TABS', {type: 'SWITCH_TABS_USERTYPE'});
      }
      this.showSwitchSuccessPopup(this.selectedUser.firstName);
      this.tncUpdateHandlerService.checkForTncUpdate();
    }).catch(err => {
      this.commonUtilService.showToast('ERROR_WHILE_SWITCHING_USER');
      console.error(err);
    });
  }

  addUser() {
    this.telemetryGeneratorService.generateInteractTelemetry(
      InteractType.SELECT_ADD,
      '',
      Environment.USER,
      PageId.MANAGE_USERS,
      undefined,
      undefined,
      undefined,
      undefined,
      ID.BTN_ADD
    );

    if (!this.commonUtilService.networkInfo.isNetworkAvailable) {
      this.commonUtilService.showToast('NEED_INTERNET_TO_CHANGE');
      return;
    }

    this.router.navigate([`/${RouterLinks.PROFILE}/${RouterLinks.SUB_PROFILE_EDIT}`]);
  }

  private handleHeaderEvents($event) {
    if($event.name == 'back')
    {
      this.telemetryGeneratorService.generateBackClickedTelemetry(
        PageId.MANAGE_USERS,
        Environment.USER,
        true);
    }
  }

  private async showSwitchSuccessPopup(name) {
    const confirm = await this.popoverCtrl.create({
      component: ToastNavigationComponent,
      componentProps: {
        message: this.commonUtilService.translateMessage('SUCCESSFULLY_SWITCHED_USER', { '%app': this.appName, '%user': name }),
        description: this.commonUtilService.translateMessage('UPDATE_YOUR_PREFERENCE_FROM_PROFILE', { app_name: this.appName }),
        actionsButtons: [
          {
            btntext: this.commonUtilService.translateMessage('GO_TO_PROFILE'),
            btnClass: 'btn-right'
          }
        ]
      },
      cssClass: 'sb-popover'
    });
    await confirm.present();
    setTimeout(() => {
      if (confirm) {
        confirm.dismiss();
      }
    }, 3000);
    const { data } = await confirm.onDidDismiss();
    console.log(data);
    if (data) {
      this.router.navigate([`/${RouterLinks.PROFILE_TAB}`]);
    }
  }

}
<ion-content>

  <section>
    <div>
      <p class="mu-title">{{'USE_APP_AS' | translate: {'%s': appName} }}</p>
    </div>

    <div class="add-user">
      <ion-button fill="outline" expand="block" (click)="addUser()" class="m-8 ion-text-capitalize">
        <span class="add-size">+</span> {{'ADD_USER' | translate}}
      </ion-button>
    </div>

    <div class="mx-8 manage-user-section">
      <div class="manage-user-item" [ngClass]="{'mu-selected-user':selectedUserIndex===i, '':selectedUserIndex!==i}" *ngFor="let user of (manageProfileList$ | async); let i = index">
        <sb-member-card 
          [title]="user.firstName"
          [identifier]="user.id"
          [initial]="user.firstName | initial"
          [cardImg]="selectedUserIndex === i ? 'assets/imgs/dark_blue_check.svg' : platform.is('ios') ? 'random.png' : ''"
          [indexOfMember] = "i"
          [config]="sbCardConfig"
          (cardClick)="selectUser(user, i)">
        </sb-member-card>
      </div>
    </div>

  </section>

</ion-content>

<ion-footer>
  <ion-row>
    <ion-col>
      <ion-button class="ion-text-capitalize mb-16" expand="block" [disabled]="selectedUserIndex === -1"
        (click)="switchUser()">{{'SWITCH_USER' | translate}}
      </ion-button>
    </ion-col>
  </ion-row>
</ion-footer>

./manage-user-profiles.page.scss

@import "src/assets/styles/_variables.scss";

.mu-title{
  font-size: 1rem;
  font-weight: bold;
  color: map-get($colors, granite_gray);
  margin: 16px;
}

.mu-selected-user{
  border: 0.5px solid map-get($colors, primary_blue);
  border-radius: 2px;
  background-color: map-get($colors, pale_blue_e0);
  position: relative;
}

.mu-selected-checkbox{
  position: absolute;
  right: 0.625rem;
  top: 30%;
}

.mu-dissable-checkbox{
  display: none;
}
ion-button{
  height: 2.5rem !important;
}

.add-user{
  padding: 0 8px;
  ion-button{
    --background: #{map-get($colors, light_grayish_green)} !important;
    color: $green;
  }
}

ion-footer{
  ion-button{
    --background: #{$blue} !important;
  }
}

.add-size{
  font-size: 1.5rem;
  padding-right: 8px;
}

.button-outline{
  --background: #{map-get($colors, pale_blue)} !important;
  --border-color: #{map-get($colors, pale_blue)} !important;
}

.sb-new-btn {
  background-color: $blue;
  color: map-get($colors, white);
  width: 100%;
  height: 2.5rem;
  box-shadow: 0 2px 7px 0 rgba(0, 0, 0, 0.25);
  font-family: "Noto Sans", sans-serif;
  font-size: 1rem;
}

.sb-new-btn-success {
  background-color: map-get($colors, light_grayish_green);
  color: $green;
  width: 100%;
  height: 2.5rem;
  box-shadow: 0 2px 7px 0 rgba(0, 0, 0, 0.25);
  font-family: "Noto Sans", sans-serif;
  font-size: 1rem;
}
Legend
Html element
Component
Html element with directive

results matching ""

    No results matching ""