src/app/profile/guest-edit/guest-edit.page.ts
OnInit
OnDestroy
selector | app-guest-edit |
styleUrls | ./guest-edit.page.scss |
templateUrl | ./guest-edit.page.html |
constructor(profileService: ProfileService, frameworkService: FrameworkService, frameworkUtilService: FrameworkUtilService, preferences: SharedPreferences, appGlobalService: AppGlobalService, commonUtilService: CommonUtilService, fb: FormBuilder, translate: TranslateService, events: Events, telemetryGeneratorService: TelemetryGeneratorService, headerService: AppHeaderService, router: Router, location: Location, profileHandler: ProfileHandler, segmentationTagService: SegmentationTagService, onboardingConfigurationService: OnboardingConfigurationService, formAndFrameworkUtilService: FormAndFrameworkUtilService)
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||
Parameters :
|
Private Async _dismissLoader | ||||
_dismissLoader(loader?)
|
||||
Parameters :
Returns :
any
|
Private Async addAttributeSubscription |
addAttributeSubscription()
|
Returns :
any
|
extractProfileForTelemetry | ||||
extractProfileForTelemetry(formVal)
|
||||
Parameters :
Returns :
any
|
Private getCategoriesAndUpdateAttributes | ||||||
getCategoriesAndUpdateAttributes(userType: string)
|
||||||
Parameters :
Returns :
void
|
Async getSyllabusDetails |
getSyllabusDetails()
|
Returns :
any
|
ionViewWillEnter |
ionViewWillEnter()
|
Returns :
void
|
ionViewWillLeave |
ionViewWillLeave()
|
Returns :
void
|
ngOnDestroy |
ngOnDestroy()
|
Returns :
void
|
Async ngOnInit |
ngOnInit()
|
Returns :
any
|
onCategoryChanged | ||||||
onCategoryChanged(name, event)
|
||||||
This method is added as we are not getting subject value in reset form method
Parameters :
Returns :
void
|
Private onGradeChange |
onGradeChange()
|
Returns :
Observable<string[]>
|
Private onMediumChange |
onMediumChange()
|
Returns :
Observable<string[]>
|
onProfileTypeChange |
onProfileTypeChange()
|
Returns :
void
|
Async onSubmit |
onSubmit()
|
Call on Submit the form
Returns :
unknown
|
Private onSyllabusChange |
onSyllabusChange()
|
Returns :
Observable<string[]>
|
publishProfileEvents | ||||
publishProfileEvents(formVal)
|
||||
Parameters :
Returns :
void
|
refreshSegmentTags |
refreshSegmentTags()
|
Returns :
void
|
submitEditForm | ||||||
submitEditForm(formVal, loader)
|
||||||
This will submit edit form.
Parameters :
Returns :
void
|
submitNewUserForm | ||||||
submitNewUserForm(formVal, loader)
|
||||||
It will submit new user form
Parameters :
Returns :
void
|
Private updateAttributeStreamsnSetValidators | ||||||
updateAttributeStreamsnSetValidators(attributes: literal type)
|
||||||
Parameters :
Returns :
Array<any>
|
validateName |
validateName()
|
It will validate the name field.
Returns :
any
|
Public appGlobalService |
Type : AppGlobalService
|
boardList |
Type : Array<any>
|
Default value : []
|
boardOptions |
Type : object
|
Default value : {
title: this.commonUtilService.translateMessage('BOARD').toLocaleUpperCase(),
cssClass: 'select-box'
}
|
btnColor |
Type : string
|
Default value : '#8FC4FF'
|
categories |
Type : Array<any>
|
Default value : []
|
classOptions |
Type : object
|
Default value : {
title: this.commonUtilService.translateMessage('CLASS').toLocaleUpperCase(),
cssClass: 'select-box'
}
|
Public commonUtilService |
Type : CommonUtilService
|
Private formControlSubscriptions |
Type : Subscription
|
Private framework |
Type : Framework
|
frameworkId |
Type : string
|
Default value : ''
|
Public gradeList |
Type : literal type[]
|
Default value : []
|
guestEditForm |
Type : FormGroup
|
isCurrentUser |
Default value : true
|
isFormValid |
Default value : true
|
isNewUser |
Default value : false
|
loader |
Type : any
|
Public mediumList |
Type : literal type[]
|
Default value : []
|
mediumOptions |
Type : object
|
Default value : {
title: this.commonUtilService.translateMessage('MEDIUM_OF_INSTRUCTION').toLocaleUpperCase(),
cssClass: 'select-box'
}
|
previousProfileType |
profile |
Type : any
|
Default value : {}
|
profileForTelemetry |
Type : any
|
Default value : {}
|
ProfileType |
Default value : ProfileType
|
Public profileTypeList |
Type : []
|
Default value : []
|
Public subjectList |
Type : literal type[]
|
Default value : []
|
subjectsOptions |
Type : object
|
Default value : {
title: this.commonUtilService.translateMessage('SUBJECTS').toLocaleUpperCase(),
cssClass: 'select-box'
}
|
Public supportedProfileAttributes |
Type : literal type
|
Default value : {}
|
Public supportedUserTypes |
Type : Array<any>
|
Default value : []
|
Public syllabusList |
Type : literal type[]
|
Default value : []
|
syllabusOptions |
Type : object
|
Default value : {
title: this.commonUtilService.translateMessage('BOARD').toLocaleUpperCase(),
cssClass: 'select-box'
}
|
unregisterBackButton |
Type : any
|
userName |
Type : string
|
Default value : ''
|
syllabusControl |
getsyllabusControl()
|
boardControl |
getboardControl()
|
mediumControl |
getmediumControl()
|
gradeControl |
getgradeControl()
|
subjectControl |
getsubjectControl()
|
import { Router } from '@angular/router';
import { Events } from '@app/util/events';
import { TranslateService } from '@ngx-translate/core';
import { Component, Inject, OnInit, OnDestroy } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import isEqual from 'lodash/isEqual';
import {
Framework,
FrameworkCategoryCodesGroup,
FrameworkService,
FrameworkUtilService,
GetFrameworkCategoryTermsRequest,
GetSuggestedFrameworksRequest,
Profile,
ProfileService,
ProfileSource,
ProfileType,
SharedPreferences,
FrameworkCategoryCode,
CachedItemRequestSourceFrom
} from 'sunbird-sdk';
import { CommonUtilService } from '@app/services/common-util.service';
import { AppGlobalService } from '@app/services/app-global-service.service';
import { TelemetryGeneratorService } from '@app/services/telemetry-generator.service';
import {
Environment,
ImpressionType,
InteractSubtype,
InteractType,
ObjectType,
PageId,
} from '@app/services/telemetry-constants';
import { AppHeaderService } from '@app/services/app-header.service';
import {PreferenceKey, ProfileConstants, RegexPatterns, RouterLinks} from '@app/app/app.constant';
import { Location } from '@angular/common';
import { Observable, Subscription, combineLatest } from 'rxjs';
import { delay, tap } from 'rxjs/operators';
import { ProfileHandler } from '@app/services/profile-handler';
import { FormAndFrameworkUtilService, OnboardingConfigurationService } from '@app/services';
import { SegmentationTagService, TagPrefixConstants } from '@app/services/segmentation-tag/segmentation-tag.service';
@Component({
selector: 'app-guest-edit',
templateUrl: './guest-edit.page.html',
styleUrls: ['./guest-edit.page.scss'],
})
export class GuestEditPage implements OnInit, OnDestroy {
private framework: Framework;
ProfileType = ProfileType;
guestEditForm: FormGroup;
profile: any = {};
categories: Array<any> = [];
boardList: Array<any> = [];
userName = '';
frameworkId = '';
loader: any;
isNewUser = false;
unregisterBackButton: any;
isCurrentUser = true;
isFormValid = true;
previousProfileType;
profileForTelemetry: any = {};
btnColor = '#8FC4FF';
private formControlSubscriptions: Subscription;
public syllabusList: { name: string, code: string }[] = [];
public mediumList: { name: string, code: string }[] = [];
public gradeList: { name: string, code: string }[] = [];
public subjectList: { name: string, code: string }[] = [];
public supportedProfileAttributes: { [key: string]: string } = {};
public supportedUserTypes: Array<any> = [];
private availableProfileTypes = [
{ profileType: ProfileType.STUDENT, name: this.commonUtilService.translateMessage('USER_TYPE_2') },
{ profileType: ProfileType.TEACHER, name: this.commonUtilService.translateMessage('USER_TYPE_1') },
{ profileType: ProfileType.ADMIN, name: this.commonUtilService.translateMessage('LEADER') },
{ profileType: ProfileType.PARENT, name: this.commonUtilService.translateMessage('USER_TYPE_5') },
{ profileType: ProfileType.OTHER, name: this.commonUtilService.translateMessage('USER_TYPE_3') }
];
public profileTypeList = [];
syllabusOptions = {
title: this.commonUtilService.translateMessage('BOARD').toLocaleUpperCase(),
cssClass: 'select-box'
};
boardOptions = {
title: this.commonUtilService.translateMessage('BOARD').toLocaleUpperCase(),
cssClass: 'select-box'
};
mediumOptions = {
title: this.commonUtilService.translateMessage('MEDIUM_OF_INSTRUCTION').toLocaleUpperCase(),
cssClass: 'select-box'
};
classOptions = {
title: this.commonUtilService.translateMessage('CLASS').toLocaleUpperCase(),
cssClass: 'select-box'
};
subjectsOptions = {
title: this.commonUtilService.translateMessage('SUBJECTS').toLocaleUpperCase(),
cssClass: 'select-box'
};
get syllabusControl(): FormControl {
return this.guestEditForm.get('syllabus') as FormControl;
}
get boardControl(): FormControl {
return this.guestEditForm.get('boards') as FormControl;
}
get mediumControl(): FormControl {
return this.guestEditForm.get('medium') as FormControl;
}
get gradeControl(): FormControl {
return this.guestEditForm.get('grades') as FormControl;
}
get subjectControl(): FormControl {
return this.guestEditForm.get('subjects') as FormControl;
}
constructor(
@Inject('PROFILE_SERVICE') private profileService: ProfileService,
@Inject('FRAMEWORK_SERVICE') private frameworkService: FrameworkService,
@Inject('FRAMEWORK_UTIL_SERVICE') private frameworkUtilService: FrameworkUtilService,
@Inject('SHARED_PREFERENCES') private preferences: SharedPreferences,
public appGlobalService: AppGlobalService,
public commonUtilService: CommonUtilService,
private fb: FormBuilder,
private translate: TranslateService,
private events: Events,
private telemetryGeneratorService: TelemetryGeneratorService,
private headerService: AppHeaderService,
private router: Router,
private location: Location,
private profileHandler: ProfileHandler,
private segmentationTagService: SegmentationTagService,
private onboardingConfigurationService: OnboardingConfigurationService,
private formAndFrameworkUtilService: FormAndFrameworkUtilService
) {
if (this.router.getCurrentNavigation().extras.state) {
this.isNewUser = Boolean(this.router.getCurrentNavigation().extras.state.isNewUser);
this.isCurrentUser = Boolean(this.router.getCurrentNavigation().extras.state.isCurrentUser);
}
if (this.router.getCurrentNavigation().extras.state) {
this.profile = this.router.getCurrentNavigation().extras.state.profile || {};
} else {
this.profile = {};
}
this.guestEditForm = this.fb.group({
name: [this.profile.handle || ''],
profileType: [this.profile.profileType || ProfileType.STUDENT],
syllabus: [],
boards: [],
medium: [],
grades: [],
subjects: []
});
this.previousProfileType = this.profile.profileType;
this.profileForTelemetry = Object.assign({}, this.profile);
}
async ngOnInit() {
this.telemetryGeneratorService.generateImpressionTelemetry(
ImpressionType.VIEW, '',
PageId.CREATE_USER,
Environment.USER, this.isNewUser ? '' : this.profile.uid, this.isNewUser ? '' : ObjectType.USER
);
this.telemetryGeneratorService.generateInteractTelemetry(
InteractType.TOUCH,
this.isNewUser ? InteractSubtype.CREATE_USER_INITIATED : InteractSubtype.EDIT_USER_INITIATED,
Environment.USER,
PageId.CREATE_USER
);
this.getCategoriesAndUpdateAttributes(this.profile.profileType || undefined);
this.supportedUserTypes = await this.profileHandler.getSupportedUserTypes(this.onboardingConfigurationService.getAppConfig().overriddenDefaultChannelId);
}
private async addAttributeSubscription() {
const subscriptionArray: Array<any> = this.updateAttributeStreamsnSetValidators(this.supportedProfileAttributes);
this.formControlSubscriptions = combineLatest(subscriptionArray).subscribe();
}
ionViewWillEnter() {
const headerTitle = this.isNewUser ? this.commonUtilService.translateMessage('CREATE_USER') :
this.commonUtilService.translateMessage('EDIT_PROFILE');
this.headerService.showHeaderWithBackButton([], headerTitle);
this.getSyllabusDetails();
}
ionViewWillLeave() {
if (this.unregisterBackButton) {
this.unregisterBackButton.unsubscribe();
}
}
ngOnDestroy() {
this.formControlSubscriptions.unsubscribe();
}
onProfileTypeChange() {
if (this.formControlSubscriptions) {
this.formControlSubscriptions.unsubscribe();
}
this.getCategoriesAndUpdateAttributes(this.guestEditForm.value.profileType);
this.guestEditForm.patchValue({
syllabus: [],
boards: [],
grades: [],
subjects: [],
medium: []
});
this.btnColor = '#8FC4FF';
}
async getSyllabusDetails() {
this.loader = await this.commonUtilService.getLoader();
await this.loader.present();
const getSuggestedFrameworksRequest: GetSuggestedFrameworksRequest = {
from: CachedItemRequestSourceFrom.SERVER,
language: this.translate.currentLang,
requiredCategories: FrameworkCategoryCodesGroup.DEFAULT_FRAMEWORK_CATEGORIES
};
this.frameworkUtilService.getActiveChannelSuggestedFrameworkList(getSuggestedFrameworksRequest).toPromise()
.then(async (frameworks: Framework[]) => {
if (!frameworks || !frameworks.length) {
await this.loader.dismiss();
this.commonUtilService.showToast('NO_DATA_FOUND');
return;
}
this.syllabusList = frameworks.map(r => ({ name: r.name, code: r.identifier }));
this.syllabusControl.patchValue([this.profile.syllabus && this.profile.syllabus[0]] || []);
await this.loader.dismiss();
});
}
private onSyllabusChange(): Observable<string[]> {
return this.syllabusControl.valueChanges.pipe(
tap(async (value) => {
if (!Array.isArray(value)) {
this.syllabusControl.patchValue([value]);
return;
}
if (!value.length) {
return;
}
await this.commonUtilService.getLoader().then((loader) => {
this.loader = loader;
this.loader.present();
});
try {
this.framework = await this.frameworkService.getFrameworkDetails({
from: CachedItemRequestSourceFrom.SERVER,
frameworkId: value[0],
requiredCategories: FrameworkCategoryCodesGroup.DEFAULT_FRAMEWORK_CATEGORIES
}).toPromise();
const boardCategoryTermsRequet: GetFrameworkCategoryTermsRequest = {
frameworkId: this.framework.identifier,
requiredCategories: [FrameworkCategoryCode.BOARD],
currentCategoryCode: FrameworkCategoryCode.BOARD,
language: this.translate.currentLang
};
const boardTerm = (await this.frameworkUtilService.getFrameworkCategoryTerms(boardCategoryTermsRequet).toPromise())
.find(b => b.name === (this.syllabusList.find((s) => s.code === value[0]).name));
this.boardControl.patchValue([boardTerm.code]);
const nextCategoryTermsRequet: GetFrameworkCategoryTermsRequest = {
frameworkId: this.framework.identifier,
requiredCategories: [FrameworkCategoryCode.MEDIUM],
prevCategoryCode: FrameworkCategoryCode.BOARD,
currentCategoryCode: FrameworkCategoryCode.MEDIUM,
language: this.translate.currentLang,
selectedTermsCodes: this.boardControl.value
};
this.mediumList = (await this.frameworkUtilService.getFrameworkCategoryTerms(nextCategoryTermsRequet).toPromise())
.map(t => ({ name: t.name, code: t.code }));
if (!this.mediumControl.value) {
this.mediumControl.patchValue(this.profile.medium || []);
} else {
this.mediumControl.patchValue([]);
}
} catch (e) {
console.error(e);
} finally {
this.loader.dismiss();
}
})
);
}
private onMediumChange(): Observable<string[]> {
return this.mediumControl.valueChanges.pipe(
tap(async (value) => {
if (!value.length) {
return;
}
await this.commonUtilService.getLoader().then((loader) => {
this.loader = loader;
this.loader.present();
});
try {
const nextCategoryTermsRequet: GetFrameworkCategoryTermsRequest = {
frameworkId: this.framework.identifier,
requiredCategories: [FrameworkCategoryCode.GRADE_LEVEL],
prevCategoryCode: FrameworkCategoryCode.MEDIUM,
currentCategoryCode: FrameworkCategoryCode.GRADE_LEVEL,
language: this.translate.currentLang,
selectedTermsCodes: this.mediumControl.value
};
this.gradeList = (await this.frameworkUtilService.getFrameworkCategoryTerms(nextCategoryTermsRequet).toPromise())
.map(t => ({ name: t.name, code: t.code }));
if (!this.gradeControl.value) {
this.gradeControl.patchValue(this.profile.grade || []);
} else {
this.gradeControl.patchValue([]);
}
} catch (e) {
console.error(e);
} finally {
this.loader.dismiss();
}
})
);
}
private onGradeChange(): Observable<string[]> {
return this.gradeControl.valueChanges.pipe(
tap(async () => {
try {
const nextCategoryTermsRequet: GetFrameworkCategoryTermsRequest = {
frameworkId: this.framework.identifier,
requiredCategories: [FrameworkCategoryCode.SUBJECT],
prevCategoryCode: FrameworkCategoryCode.GRADE_LEVEL,
currentCategoryCode: FrameworkCategoryCode.SUBJECT,
language: this.translate.currentLang,
selectedTermsCodes: this.gradeControl.value
};
this.subjectList = (await this.frameworkUtilService.getFrameworkCategoryTerms(nextCategoryTermsRequet).toPromise())
.map(t => ({ name: t.name, code: t.code }));
if (!this.subjectControl.value) {
this.subjectControl.patchValue(this.profile.subject || []);
} else {
this.subjectControl.patchValue([]);
}
} catch (e) {
console.error(e);
} finally {
if (this.loader) {
this.loader.dismiss();
}
}
})
);
}
/**
* This method is added as we are not getting subject value in reset form method
*/
onCategoryChanged(name, event) {
if (event.detail.value && event.detail.value.length) {
const oldAttribute: any = {};
const newAttribute: any = {};
oldAttribute[name] = this.profileForTelemetry[name] ? this.profileForTelemetry[name] : '';
newAttribute[name] = event.detail.value ? event.detail.value : '';
if (!isEqual(oldAttribute, newAttribute)) {
this.appGlobalService.generateAttributeChangeTelemetry(oldAttribute, newAttribute, PageId.GUEST_PROFILE);
}
if (name === 'subject') {
this.profileForTelemetry.subject = event.detail.value ? event.detail.value : '';
}
}
}
/**
* Call on Submit the form
*/
async onSubmit() {
if (!this.isFormValid) {
this.commonUtilService.showToast(this.commonUtilService.translateMessage('NEED_INTERNET_TO_CHANGE'));
return;
}
const loader = await this.commonUtilService.getLoader();
const formVal = this.guestEditForm.value;
if (!formVal.profileType) {
this.commonUtilService.showToast('USER_TYPE_SELECT_WARNING');
return false;
} else if (!this.validateName()) {
this.commonUtilService.showToast(
this.commonUtilService.translateMessage('PLEASE_SELECT', this.commonUtilService.translateMessage('FULL_NAME')), false, 'red-toast');
} else if (formVal.boards && formVal.boards.length === 0) {
this.appGlobalService.generateSaveClickedTelemetry(
this.extractProfileForTelemetry(formVal), 'failed', PageId.EDIT_USER, InteractSubtype.SAVE_CLICKED);
this.commonUtilService.showToast(
this.commonUtilService.translateMessage('PLEASE_SELECT', this.commonUtilService.translateMessage('BOARD')), false, 'red-toast');
return false;
} else if (formVal.medium && formVal.medium.length === 0 && !!this.supportedProfileAttributes['medium']) {
this.appGlobalService.generateSaveClickedTelemetry(
this.extractProfileForTelemetry(formVal), 'failed', PageId.EDIT_USER, InteractSubtype.SAVE_CLICKED);
this.commonUtilService.showToast(
this.commonUtilService.translateMessage('PLEASE_SELECT', this.commonUtilService.translateMessage('MEDIUM')), false, 'red-toast');
return false;
} else if (formVal.grades && formVal.grades.length === 0 && !!this.supportedProfileAttributes['gradeLevel']) {
this.appGlobalService.generateSaveClickedTelemetry(
this.extractProfileForTelemetry(formVal), 'failed', PageId.EDIT_USER, InteractSubtype.SAVE_CLICKED);
this.commonUtilService.showToast(
this.commonUtilService.translateMessage('PLEASE_SELECT', this.commonUtilService.translateMessage('CLASS')), false, 'red-toast');
return false;
} else {
await loader.present();
if (this.isNewUser) {
this.submitNewUserForm(formVal, loader);
} else {
this.submitEditForm(formVal, loader);
}
this.appGlobalService.generateSaveClickedTelemetry(
this.extractProfileForTelemetry(formVal), 'passed', PageId.EDIT_USER, InteractSubtype.SAVE_CLICKED);
}
}
/**
* It will validate the name field.
*/
validateName() {
const name = this.guestEditForm.getRawValue().name;
if (name) {
return Boolean(name.trim().length);
} else {
return false;
}
}
extractProfileForTelemetry(formVal): any {
const profileReq: any = {};
profileReq.board = formVal.boards;
profileReq.grade = formVal.grades;
profileReq.subject = formVal.subjects;
profileReq.medium = formVal.medium;
profileReq.profileType = formVal.profileType;
profileReq.syllabus = (!formVal.syllabus.length) ? [] : [formVal.syllabus];
return profileReq;
}
/**
* This will submit edit form.
*/
submitEditForm(formVal, loader): void {
const req = {} as Profile;
req.board = formVal.boards;
req.grade = formVal.grades;
req.subject = formVal.subjects;
req.medium = formVal.medium;
req.uid = this.profile.uid;
req.handle = (formVal.name.replace(RegexPatterns.SPECIALCHARECTERSANDEMOJIS, '')).trim();
req.profileType = formVal.profileType;
req.source = this.profile.source;
req.createdAt = this.profile.createdAt;
req.syllabus = (!formVal.syllabus.length) ? [] : [formVal.syllabus];
if (formVal.grades && formVal.grades.length > 0) {
formVal.grades.forEach(gradeCode => {
for (let i = 0; i < this.gradeList.length; i++) {
if (this.gradeList[i].code === gradeCode) {
if (!req.gradeValue) {
req.gradeValue = {};
}
req.gradeValue[this.gradeList[i].code] = this.gradeList[i].name;
break;
}
}
});
}
this.profileService.updateProfile(req)
.subscribe(() => {
this._dismissLoader(loader);
this.commonUtilService.showToast(this.commonUtilService.translateMessage('PROFILE_UPDATE_SUCCESS'));
this.telemetryGeneratorService.generateInteractTelemetry(
InteractType.OTHER,
InteractSubtype.EDIT_USER_SUCCESS,
Environment.USER,
PageId.EDIT_USER
);
if (this.isCurrentUser) {
this.commonUtilService.handleToTopicBasedNotification();
this.publishProfileEvents(formVal);
} else {
this.location.back();
}
this.refreshSegmentTags();
}, () => {
this._dismissLoader(loader);
this.commonUtilService.showToast(this.commonUtilService.translateMessage('PROFILE_UPDATE_FAILED'));
});
}
refreshSegmentTags() {
this.profileService.getActiveSessionProfile({ requiredFields: ProfileConstants.REQUIRED_FIELDS }).toPromise()
.then(async (res: any) => {
this.profile = res;
const tagObj = {
board: res.board,
grade: res.grade,
syllabus: res.syllabus,
medium: res.medium,
};
window['segmentation'].SBTagService.pushTag(tagObj, TagPrefixConstants.USER_ATRIBUTE, true);
window['segmentation'].SBTagService.pushTag(res.profileType, TagPrefixConstants.USER_ROLE, true);
this.segmentationTagService.evalCriteria();
});
}
publishProfileEvents(formVal) {
// Publish event if the all the fields are submitted
if (formVal.syllabus && formVal.syllabus.length
&& (formVal.boards && formVal.boards.length)
&& (formVal.grades && formVal.grades.length)
&& (formVal.medium && formVal.medium.length)
&& (formVal.subjects && formVal.subjects.length)) {
this.events.publish('onboarding-card:completed', { isOnBoardingCardCompleted: true });
} else {
this.events.publish('onboarding-card:completed', { isOnBoardingCardCompleted: false });
}
this.events.publish('refresh:profile');
this.events.publish('refresh:onboardingcard');
if (this.previousProfileType && this.previousProfileType !== formVal.profileType) {
if (this.previousProfileType && this.previousProfileType !== formVal.profileType) {
this.preferences.putString(PreferenceKey.SELECTED_USER_TYPE, formVal.profileType).toPromise().then();
if (formVal.profileType === ProfileType.ADMIN) {
this.preferences.putString(PreferenceKey.SELECTED_USER_TYPE, ProfileType.ADMIN).toPromise().then();
this.router.navigate([RouterLinks.SIGN_IN]);
}
}
}
if (formVal.profileType !== ProfileType.ADMIN) {
this.location.back();
}
}
/**
* It will submit new user form
*/
submitNewUserForm(formVal, loader): void {
const req = {} as Profile;
req.board = formVal.boards;
req.grade = formVal.grades;
req.subject = formVal.subjects;
req.medium = formVal.medium;
req.handle = formVal.name.trim();
req.profileType = formVal.profileType;
req.source = ProfileSource.LOCAL;
req.syllabus = (!formVal.syllabus.length) ? [] : [formVal.syllabus];
if (formVal.grades && formVal.grades.length > 0) {
formVal.grades.forEach(gradeCode => {
for (let i = 0; i < this.gradeList.length; i++) {
if (this.gradeList[i].code === gradeCode) {
if (!req.gradeValue) {
req.gradeValue = {};
}
req.gradeValue[this.gradeList[i].code] = this.gradeList[i].name;
break;
}
}
});
}
this.profileService.createProfile(req, req.source).subscribe(() => {
this._dismissLoader(loader);
this.commonUtilService.showToast(this.commonUtilService.translateMessage('USER_CREATED_SUCCESSFULLY'));
this.telemetryGeneratorService.generateInteractTelemetry(
InteractType.OTHER, InteractSubtype.CREATE_USER_SUCCESS, Environment.USER, PageId.CREATE_USER);
this.location.back();
}, () => {
this._dismissLoader(loader);
this.commonUtilService.showToast(this.commonUtilService.translateMessage('FILL_THE_MANDATORY_FIELDS'));
});
}
private async _dismissLoader(loader?) {
if (loader) {
await loader.dismiss();
} else if (this.loader) {
await this.loader.dismiss();
this.loader = undefined;
}
}
private updateAttributeStreamsnSetValidators(attributes: { [key: string]: string }): Array<any> {
const subscriptionArray = [];
Object.keys(attributes).forEach((attribute) => {
switch (attribute) {
case 'board':
subscriptionArray.push(this.onSyllabusChange());
break;
case 'medium':
subscriptionArray.push(this.onMediumChange());
break;
case 'gradeLevel':
subscriptionArray.push(this.onGradeChange());
break;
}
});
subscriptionArray.push(this.guestEditForm.valueChanges.pipe(
delay(250),
tap(() => {
this.btnColor = this.guestEditForm.valid ? '#006DE5' : '#8FC4FF';
})
));
return subscriptionArray;
}
private getCategoriesAndUpdateAttributes(userType: string) {
this.formAndFrameworkUtilService.getFrameworkCategoryList(userType).then((categories) => {
if (categories && categories.supportedFrameworkConfig && categories.supportedAttributes) {
this.categories = categories.supportedFrameworkConfig;
this.supportedProfileAttributes = categories.supportedAttributes;
this.addAttributeSubscription();
}
});
}
}
<ion-content>
<form [formGroup]="guestEditForm">
<ion-list (ionChange)="onProfileTypeChange()" class="MT6" *ngIf="supportedUserTypes && supportedUserTypes.length">
<ion-radio-group formControlName="profileType">
<ion-label class="type-label ion-text-uppercase">
{{ 'USER_TYPE' | translate }}<ion-text>
<span class="ge-danger"> *</span>
</ion-text>
</ion-label>
<ion-item lines="none" *ngFor="let userType of supportedUserTypes">
<ion-label [ngClass]="{'highlight-radio': guestEditForm?.value?.profileType === userType.code }">
{{ userType.translations | translateJson }}
</ion-label>
<ion-radio [value]="userType.code" class="MR10" slot="start"></ion-radio>
</ion-item>
</ion-radio-group>
</ion-list>
<ion-item class="ge-item-16">
<ion-label position="stacked" class="label-font ge-label ion-text-uppercase">{{ 'NAME' | translate }}<ion-text>
<span class="ge-danger"> *</span>
</ion-text>
</ion-label>
<ion-input formControlName="name" dir="{{commonUtilService.getAppDirection()}}"
placeholder="{{'NAME_HINT' | translate }}"></ion-input>
</ion-item>
<div *ngIf="categories.length>0">
<!-- Syllabus -->
<ion-item class="ge-item-16" *ngIf="!!supportedProfileAttributes['board'] && categories[0].code==='category1'">
<ion-label *ngIf="!!supportedProfileAttributes['board']" position="stacked" class="label-font ge-label ion-text-uppercase">{{categories[0].label | translateJson}} ‎
<ion-text>
<span class="ge-danger"> *</span>
</ion-text>
</ion-label>
<ion-select *ngIf="!!supportedProfileAttributes['board']" [disabled]="!syllabusList.length" multiple="false" formControlName="syllabus"
[interfaceOptions]="syllabusOptions" class="ion-text-capitalize" (ionChange)="onCategoryChanged('board',$event)"
placeholder="{{ syllabusList.length ? (categories[0].placeHolder | translateJson) : ('NO_DATA_FOUND' | translate) }}"
okText="{{'BTN_SUBMIT' | translate}}" cancelText="{{'CANCEL' | translate}}">
<ion-select-option *ngFor="let eachSyllabus of syllabusList" value="{{eachSyllabus?.code}}">
{{eachSyllabus.name | aliased}}‎
</ion-select-option>
</ion-select>
</ion-item>
<!-- Medium -->
<ion-item class="ge-item-16" *ngIf="!!supportedProfileAttributes['medium'] && categories.length>1 && categories[1].code==='category2'">
<ion-label *ngIf="!!supportedProfileAttributes['medium']" position="stacked" class="label-font ge-label ion-text-uppercase">
{{categories[1].label | translateJson}}
<ion-text>
<span class="ge-danger"> *</span>
</ion-text>
</ion-label>
<ion-select *ngIf="!!supportedProfileAttributes['medium']" multiple="true" class="ion-text-capitalize"
[disabled]="(!mediumList.length || !(guestEditForm.value.boards != ''))" [interfaceOptions]="mediumOptions"
formControlName="medium" (ionChange)="onCategoryChanged('medium', $event)"
placeholder="{{ mediumList.length ? (categories[1].placeHolder | translateJson) : ('NO_DATA_FOUND' | translate) }}"
okText="{{'BTN_SUBMIT' | translate}}" cancelText="{{'CANCEL' | translate}}">
<ion-select-option *ngFor="let medium of mediumList" class="ion-text-capitalize" value="{{medium?.code}}">
{{medium?.name}}
</ion-select-option>
</ion-select>
</ion-item>
<!-- Grade -->
<ion-item class="ge-item-16" *ngIf="!!supportedProfileAttributes['gradeLevel'] && categories.length>2 && categories[2].code==='category3'">
<ion-label *ngIf="!!supportedProfileAttributes['gradeLevel']" position="stacked" class="label-font ge-label ion-text-uppercase">{{categories[2].label | translateJson}}<ion-text>
<span class="ge-danger"> *</span>
</ion-text>
</ion-label>
<ion-select *ngIf="!!supportedProfileAttributes['gradeLevel']" multiple="true" class="ion-text-capitalize"
[disabled]="(!gradeList.length || !(guestEditForm.value.medium != ''))" [interfaceOptions]="classOptions"
formControlName="grades" (ionChange)="onCategoryChanged('grade',$event)"
placeholder="{{ gradeList.length ? (categories[2].placeHolder | translateJson) : ('NO_DATA_FOUND' | translate) }}"
okText="{{'BTN_SUBMIT' | translate}}" cancelText="{{'CANCEL' | translate}}">
<ion-select-option *ngFor="let grade of gradeList" class="ion-text-capitalize" value="{{grade?.code}}">
{{grade?.name}}
</ion-select-option>
</ion-select>
</ion-item>
<!-- Subjects -->
<ion-item class="ge-item-16" *ngIf="!!supportedProfileAttributes['subject'] && categories.length>3 && categories[3].code==='category4'">
<ion-label *ngIf="!!supportedProfileAttributes['subject']" position="stacked" class="label-font ge-label ion-text-uppercase">{{categories[3].label | translateJson}}
</ion-label>
<ion-select *ngIf="!!supportedProfileAttributes['subject']" multiple="true" [interfaceOptions]="subjectsOptions" class="ion-text-capitalize"
[disabled]="(!subjectList.length || !(guestEditForm.value.grades != ''))" formControlName="subjects"
(ionChange)="onCategoryChanged('subject', $event)"
placeholder="{{ subjectList.length ? (categories[3].placeHolder | translateJson) : ('NO_DATA_FOUND' | translate) }}"
okText="{{'BTN_SUBMIT' | translate}}" cancelText="{{'CANCEL' | translate}}">
<ion-select-option *ngFor="let subject of subjectList" class="ion-text-capitalize" value="{{subject?.code}}">
{{subject?.name}}
</ion-select-option>
</ion-select>
</ion-item>
</div>
</form>
</ion-content>
<div class="ion-padding ion-no-border" style="background: white;">
<button class="sb-btn sb-btn-md sb-btn-primary PR35 W100 ellipsis btn-block ion-text-uppercase"
[style.background-color]="btnColor" (click)="onSubmit()">{{'SAVE' | translate}}</button>
</div>
./guest-edit.page.scss
@import "src/assets/styles/_variables.scss";
@import "src/assets/styles/_helper.scss";
:host {
ion-label {
flex: unset !important;
}
.list-header-md {
padding-bottom: 0 !important;
margin-bottom: 13px;
}
.item-md {
margin-bottom: 0 !important;
.radio-md[item-left] {
margin-right: 10px !important;
}
}
.ge-label {
@extend .MB8;
color: map-get($colors, title);
}
.ge-danger{
color: map-get($colors, danger);
}
.ge-item-16{
width: calc(100% - 16px);
--padding-start: 0px;
@extend .ML16;
@extend .MB6;
}
.highlight-radio {
color: map-get($colors, primary);
}
ion-list-header ion-label {
margin-bottom: 0 !important;
}
.label-md[stacked] {
font-weight: 700 !important;
}
.list-md {
margin-bottom: 0 !important;
}
ion-label.type-label {
margin-bottom: 0 !important;
margin-left: 16px;
font-weight: 500 !important;
color: $gray-300;
font-size: 0.75rem;
}
.label-font {
font-weight: 600 !important;
}
}
.multiple-select-alert .alert-head {
padding: 8px 20px 8px !important;
}
.multiple-select-alert .alert-checkbox-label {
text-transform: capitalize !important;
}
.red-toast {
.toast-container {
background-color: map-get($colors, vivid_red);
#toast-hdr-6 {
padding-left: 69px !important;
}
.toast-message {
padding-left: 40px !important;
}
.toast-message:before {
content: "\f19f";
font-family: Ionicons, sans-serif;
-webkit-font-smoothing: antialiased;
font-style: normal;
font-variant: normal;
font-weight: 400 !important;
line-height: 1;
padding-left: 30px !important;
padding-right: 16px !important;
padding-bottom: 5px !important;
text-rendering: auto;
text-transform: none;
margin-bottom: 29px !important;
margin-top: 28px !important;
margin-left: -39px !important;
position: static;
font-size: 2.1rem;
}
}
}