Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
- import { Router } from '@angular/router';
- // import {Component} from '@angular/core';
- // import {FormControl} from '@angular/forms';
- import { Observable } from 'rxjs/Observable';
- import { startWith } from 'rxjs/operators/startWith';
- import { map } from 'rxjs/operators/map';
- import { FormControl, FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';
- import { TranslateService } from '@ngx-translate/core';
- import { AlertService, UserService, SnackService, OrderService } from '../services/index';
- import { ALLOW_SOCIAL_LOGIN, LANGUAGE_MAP } from '../app.constants';
- const countries = require("i18n-iso-countries");
- /* Google Analytics */
- declare var gtag: any;
- @Component({
- moduleId: module.id.toString(),
- selector: 'app-register',
- templateUrl: 'register.component.html'
- })
- export class RegisterComponent implements OnInit {
- @Input() view: string;
- @Output() onShowallChanged: EventEmitter<any> = new EventEmitter<any>();
- @Output() onRegisterSuccess: EventEmitter<any> = new EventEmitter<any>();
- @Output() onFormChange: EventEmitter<any> = new EventEmitter<any>();
- model: any = {}; /* TODO: reduntant ?*/
- loading = false;
- loadingInvoice = false;
- showCountryWarning = false;
- countryInvalid = false;
- registerForm: any; /* main account register form */
- // companyForm: any; /* form for company details*/
- showPassword: boolean = false;
- showAllfields: boolean = false;
- allowSocialRegister: boolean;
- companyFormDisabled: boolean;
- loadedCountries: any[];
- filteredOptions: any[];
- // filteredCountries: any;
- /* map back-end api errors */
- apiErrorsMap: any;
- viewMode: string;
- currentUser: any;
- lang: string; // 2 char: "et"
- langLong: string; // 5 char: "et_EE"
- loadingUser: boolean; // whether loading user data and form is disabled for changes
- languageMap: any; // lang map from constants.ts
- constructor(
- private router: Router,
- private userService: UserService,
- private alertService: AlertService,
- private fb: FormBuilder,
- private translateService: TranslateService,
- private snackService: SnackService,
- private orderService: OrderService) {
- this.allowSocialRegister = ALLOW_SOCIAL_LOGIN;
- countries.registerLocale(require("i18n-iso-countries/langs/en.json"));
- countries.registerLocale(require("i18n-iso-countries/langs/et.json"));
- }
- get email() { return this.registerForm.get('email'); }
- get password() { return this.registerForm.get('password'); }
- get name() { return this.registerForm.get('name'); }
- get country() { return this.registerForm.get('country'); }
- get company_name() { return this.registerForm.get('company_name'); }
- get company_reg_nr() { return this.registerForm.get('company_reg_nr'); }
- get company_vat_nr() { return this.registerForm.get('company_vat_nr'); }
- get company_address() { return this.registerForm.get('company_address'); }
- get invoice_email() { return this.registerForm.get('invoice_email'); }
- // get language() { return this.loginForm.get('language'); }
- // password change
- get old_password(){ return this.registerForm.get('old_password');}
- get new_password(){ return this.registerForm.get('new_password');}
- ngOnInit() {
- this.setLanguage();
- this.createRegisterForm();
- this.loadCountries();
- this.setViewMode();
- // this.currentUser = this.userService.getUser();
- console.log("REGISTER COMPONENT VIEW: ", this.viewMode);
- }
- setLanguage() {
- this.lang = this.translateService.currentLang;
- if (!this.lang) {
- this.lang = this.translateService.defaultLang;
- }
- this.langLong = LANGUAGE_MAP[this.lang];
- this.languageMap = LANGUAGE_MAP;
- }
- setViewMode() {
- /* stupid quickhack > should have written the component in a different way*/
- let viewCase;
- if (this.view == 'account') {
- console.log(this.view);
- viewCase = 'order'
- } else {
- viewCase = this.view;
- }
- switch(viewCase) {
- case 'order': {
- this.viewMode = 'order';
- this.showAllfields = true;
- // this.showPassword = false;
- // In case of order -> country is needed for VAT
- this.registerForm.controls["country"].setValidators([Validators.required, Validators.minLength(2)]);
- this.registerForm.controls["invoice_email"].setValidators([Validators.required, Validators.email]);
- this.currentUser = this.userService.getUser();
- if (this.currentUser) {
- this.setAccountData();
- this.getInvoiceData();
- this.companyFormDisabled = true;
- } else {
- this.checkCountry();
- }
- break;
- }
- default: {
- this.viewMode = 'register';
- break;
- }
- }
- }
- setAccountData() {
- // name, email, password
- this.registerForm.controls['name'].setValue(this.currentUser.displayName);
- this.registerForm.controls['email'].setValue(this.currentUser.email);
- this.registerForm.controls['language'].setValue(this.currentUser.language);
- this.registerForm.controls['password'].setValidators([]);
- /* dummy value, TODO: find a better solution - disable pw required for example! */
- // this.registerForm.controls['password'].setValue("Klm123456000000000000000000000000000000000000000000");
- }
- getInvoiceData() {
- this.orderService.getInvoiceDetails().subscribe(
- data => {
- if (data.data) {
- this.setInvoiceData(data);
- }
- },
- error => {
- this.snackService.showTranslatedSnack("ORDER.UNABLE_GET_INVOICE_DETAILS", "OK");
- });
- }
- setInvoiceData(data) {
- // console.log("########## setInvoiceData: ", data);
- let country = this.loadedCountries.filter( (country) => country.value === data.data.country)
- this.registerForm.controls['country'].setValue(country[0]);
- this.registerForm.controls['company_name'].setValue(data.data.name);
- this.registerForm.controls['company_reg_nr'].setValue(data.data.registrationNr);
- this.registerForm.controls['company_vat_nr'].setValue(data.data.VATnr);
- this.registerForm.controls['company_address'].setValue(data.data.address);
- this.registerForm.controls['invoice_email'].setValue(data.data.invoiceEmail);
- this.checkCountry();
- }
- checkCountry() {
- if ((this.registerForm.controls['country'].valid) && (this.registerForm.get('country').value) ) {
- this.showCountryWarning = false;
- this.countryInvalid = false;
- // console.log("checkCountry: country CORRECT!");
- } else {
- this.showCountryWarning = true;
- this.registerForm.controls['country'].setErrors({'incorrect': true});
- this.countryInvalid = true;
- // console.log("checkCountry: country INVALID!");
- // this.snackService.showTranslatedSnack("ORDER.COUNTRY_REQUIRED_FOR_INVOICES", "OK");
- }
- }
- cancelInvoiceDetailsChange() {
- this.companyFormDisabled = true;
- this.getInvoiceData();
- }
- updateInvoiceDetails() {
- this.loadingInvoice = true;
- const invoiceData = this.prepareSaveUser(true)
- this.orderService.changeInvoiceDetails(invoiceData).subscribe(
- data => {
- // console.log(data);
- if (data.data) {
- this.setInvoiceData(data);
- this.companyFormDisabled = true;
- this.snackService.showTranslatedSnack("ORDER.INVOICE_DETAILS_SAVED", "OK");
- this.emitFormValidity();
- gtag('event', 'add_payment_info'); /* Send GA event */
- }
- this.loadingInvoice = false;
- },
- error => {
- this.snackService.showTranslatedSnack("ORDER.UNABLE_SAVE_INVOICE_DETAILS", "OK");
- this.loadingInvoice = false;
- });
- /* TODO: html preloader progress bar */
- }
- updateAccountDetails() {
- this.loadingUser = true;
- const userAccountData = this.prepareSaveUserAccount();
- // console.log("userAccountData: ", userAccountData);
- if (userAccountData.email != this.currentUser.email) {
- return this.alertService.error("ACCOUNT.UNABLE_TO_SAVE_ACCOUNT");
- }
- this.userService.update(userAccountData).subscribe(
- data => {
- // console.log(data);
- if (data.data && data.status == "success") {
- // this.setAccountData(); // TODO: once backend returns user/or data object
- // Switch language immediately
- this.translateService.use(userAccountData.language.substring(0, 2));
- // Manipulate the currentUser localstorage obj with new updated values
- this.userService.updateUserAccount(userAccountData.language, userAccountData.displayName);
- this.snackService.showTranslatedSnack("ACCOUNT.ACCOUNT_DETAILS_SAVED", "OK");
- // Send GA event
- gtag('event', 'update_account_details', {
- 'event_category' : 'client_app',
- 'event_label' : userAccountData.email,
- });
- }
- this.loadingUser = false;
- },
- error => {
- this.snackService.showTranslatedSnack("ACCOUNT.UNABLE_TO_SAVE_ACCOUNT", "OK");
- this.loadingUser = false;
- });
- }
- emitFormValidity() {
- if (this.registerForm.valid) {
- this.onFormChange.emit({valid: true});
- } else {
- this.onFormChange.emit({valid: false});
- }
- }
- loadCountries() {
- const lang = this.translateService.currentLang ? this.translateService.currentLang : "en";
- const countriesLocale = countries.getNames(lang);
- // console.log("countriesLocale: ", countriesLocale);
- this.loadedCountries = [];
- for (const key of Object.keys(countriesLocale)) {
- this.loadedCountries.push({ display: countriesLocale[key], value: key.toLowerCase() });
- }
- this.filteredOptions = this.loadedCountries;
- // console.log("this.loadedCountries: ", this.loadedCountries);
- this.registerCountryChanges();
- }
- registerCountryChanges() {
- this.registerForm.controls['country'].valueChanges.subscribe(val => {
- this.filteredOptions = this.loadedCountries.filter(
- (country) => typeof val === 'string' ? country.display.toLowerCase().startsWith(val.toLowerCase()) : this.loadCountries
- )
- /* Make sure that value is an object*/
- if ((typeof val === 'object') && (val.display && val.value)) {
- this.countryInvalid = false;
- } else {
- this.registerForm.controls['country'].setErrors({'incorrect': true});
- this.countryInvalid = true;
- }
- if (this.viewMode == "order") {
- this.checkCountry();
- }
- });
- }
- displayCountry(user?): string | undefined {
- return user ? user.display : undefined;
- }
- resetApiErrorsMap() {
- this.apiErrorsMap = {
- displayName: null,
- email: null,
- password: null,
- country: null,
- name: null,
- registrationNr: null,
- VATnr: null,
- address: null,
- invoiceEmail: null,
- language: null,
- };
- }
- register() {
- this.loading = true;
- const regData = this.prepareSaveUser();
- // console.log("regData: ", regData);
- // this.apiErrorsMap = {};
- this.resetApiErrorsMap();
- this.userService.create(regData)
- .subscribe(
- data => {
- // console.log(data);
- if ( (data.status === "success") && (data.data) ) {
- const hash = btoa(regData.userDetails.email + ":" + regData.userDetails.password);
- this.userService.setUser(data.data, true, hash);
- this.snackService.showTranslatedSnack("REGISTER.REGISTRATION_SUCCESS", "OK");
- this.alertService.success("REGISTER.REGISTRATION_SUCCESS", true);
- /* IF registration view > route to new order */
- if (this.viewMode === 'register') {
- this.router.navigate(['/orders/new']);
- }
- if (this.viewMode === 'order') {
- this.showPassword = false;
- this.companyFormDisabled = true;
- }
- this.onRegisterSuccess.emit(data.data);
- this.currentUser = this.userService.getUser();
- gtag('event', 'sign_up', { method : 'Sille account' }); /* Send GA event */
- } else if (data.status !== "success") {
- if (data.message === "Validation failed") {
- this.alertService.error("REGISTER.VALIDATION_FAILED");
- } else {
- console.log("alert data.message: ", data.message);
- this.alertService.error(data.message);
- }
- this.handleFieldErrors(data);
- } else {
- this.loading = false;
- }
- // TODO: set user & navigate to order form
- this.loading = false;
- },
- error => {
- console.log("alert error data.message: ", error);
- this.alertService.error(error);
- this.loading = false;
- });
- }
- handleFieldErrors(data: any) {
- const fieldsMap = {
- displayName: "name",
- email: "email",
- password: "password",
- country: "country",
- name: "company_name",
- registrationNr: "company_reg_nr",
- VATnr: "company_vat_nr",
- address: "company_address",
- invoiceEmail: "invoice_email",
- language: "language"
- };
- if (data.fieldErrors) {
- const fields = data.fieldErrors;
- for (const key of Object.keys(fields)) {
- let fieldPieces = key.split(".");
- let field = fieldPieces.pop();
- // console.log(field + " - " + fields[key].message);
- if (fieldsMap[field]) {
- this.registerForm.controls[fieldsMap[field]].setErrors({'incorrect': true});
- this.apiErrorsMap[fieldsMap[field]] = fields[key].message;
- }
- }
- // console.log(this.apiErrorsMap);
- }
- }
- createRegisterForm() {
- this.registerForm = this.fb.group({
- "name": ['', [ Validators.minLength(2) ] ],
- "email": ['', [ Validators.required, Validators.email ] ],
- // ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d_!@#$%&\/\"{}()=?+'-*~|]{8,}$
- "password": ['', [ Validators.required, Validators.minLength(8), Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d_!@#$%&\/\"{}()=?+'\-*~|]{8,}$/) ] ],
- // "password": ['', [ Validators.required, Validators.minLength(8), Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/) ] ],
- "country": ['', [ Validators.minLength(2) ] ], /* TODO: letters only */ /* TODO: eu vat warning eu riikide puhul? */
- "company_name": ['', [ Validators.minLength(2), Validators.maxLength(100) ] ],
- "company_reg_nr": ['', [ Validators.minLength(2), Validators.maxLength(100) ] ],
- "company_vat_nr": ['', [ Validators.minLength(2), Validators.maxLength(100) ] ], /* TODO: et puhul kmkr validaator?*/
- "company_address": ['', [ Validators.minLength(2), Validators.maxLength(200) ] ],
- "invoice_email": ['', [ Validators.email ] ],
- "language": [this.lang],
- "old_password": ['', [ Validators.minLength(8)]],
- "new_password": ['', [Validators.required, Validators.minLength(8), Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d_!@#$%&\/\"{}()=?+'\-*~|]{8,}$/) ] ]
- });
- this.onFormChanges();
- }
- prepareSaveUser(only_invoice?: boolean): any {
- /* TODO: küsi siin juba vormi lang väärtust!= */
- const formModel = this.registerForm.value;
- // console.log("this.translateService.currentLang: ", this.translateService.currentLang);
- // console.log("prepareSaveUser > formModel: ", formModel);
- const registerData = {
- userDetails: {
- email: formModel.email,
- displayName: formModel.name,
- language: LANGUAGE_MAP[this.translateService.currentLang],
- password: formModel.password,
- },
- invoiceDetails: {
- country: formModel.country.value,
- name: formModel.company_name,
- registrationNr: formModel.company_reg_nr,
- VATnr: formModel.company_vat_nr,
- address: formModel.company_address,
- invoiceEmail: formModel.invoice_email
- }
- }
- if (only_invoice) {
- return registerData.invoiceDetails;
- } else {
- return registerData;
- }
- }
- prepareSaveUserAccount() {
- const formModel = this.registerForm.value;
- let langToUse;
- if ((formModel.language) && (formModel.language.length == 5) ) {
- // console.log("formModel.language.length: ", formModel.language.length);
- langToUse = formModel.language;
- } else {
- langToUse = LANGUAGE_MAP[this.translateService.currentLang];
- }
- const userAccountData = {
- email: formModel.email,
- displayName: formModel.name,
- language: langToUse,
- }
- return userAccountData;
- }
- // In case of a valid registration e-mail we'll set the invoice email already as the default
- onFormChanges() {
- this.registerForm.controls['email'].valueChanges.subscribe(val => {
- if (val) {
- if (this.registerForm.controls['email'].valid) {
- this.registerForm.controls['invoice_email'].setValue(val);
- }
- }
- });
- this.registerForm.valueChanges.subscribe( val => {
- const formData = {
- valid: this.registerForm.valid,
- data: val,
- }
- if ( (this.currentUser) && (this.companyFormDisabled) ) {
- this.onFormChange.emit(formData);
- }
- // console.log("registerForm.valueChanges: ", val);
- // console.log("registerForm.valid: ", this.registerForm.valid);
- });
- if (this.currentUser) {
- this.registerForm.controls['country'].valueChanges.subscribe(val => {
- // console.log("country val: ", val);
- this.checkCountry();
- });
- }
- }
- // change password for registered user
- onChangePasswordSubmit() {
- this.changePassword();
- }
- changePassword() {
- const oldpassword = this.registerForm.get('old_password').value;
- const newpassword = this.registerForm.get('new_password').value;
- const data = {
- oldPassword: oldpassword,
- newPassword: newpassword
- }
- if (newpassword) {
- this.userService.updatePassword(data).subscribe(
- data => {
- // console.log(data);
- if (data.status == "success") {
- this.userService.updateUserHash(newpassword);
- this.snackService.showTranslatedSnack("ACCOUNT.PASSWORD_CHANGE_SUCCESS", "OK");
- this.alertService.success("ACCOUNT.PASSWORD_CHANGE_SUCCESS");
- this.resetChangePasswordForm();
- } else if (data.status == "fail") {
- this.snackService.showTranslatedSnack("ACCOUNT.PASSWORD_DOES_NOT_MATCH", "OK");
- this.alertService.error("ACCOUNT.PASSWORD_DOES_NOT_MATCH");
- }
- },
- error => {
- });
- ;
- }
- }
- resetChangePasswordForm(){
- this.registerForm.controls['old_password'].setValue(null);
- this.registerForm.controls['new_password'].setValue(null)
- }
- /* TODO: remove this useless wrapper */
- onRegisterSubmit() {
- this.register();
- }
- googleRegister() {
- // console.log("TODO: register with google");
- }
- facebookRegister() {
- // console.log("TODO: register with facebook");
- }
- toggleAllFields() {
- this.showAllfields = !this.showAllfields;
- this.onShowallChanged.emit(this.showAllfields);
- gtag('event', 'toggle_showallfields', {
- 'event_category' : 'client_app',
- 'event_label' : this.showAllfields,
- });
- }
- }
Add Comment
Please, Sign In to add comment