Guest User

Untitled

a guest
Apr 3rd, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
  2. import { Router } from '@angular/router';
  3.  
  4. // import {Component} from '@angular/core';
  5. // import {FormControl} from '@angular/forms';
  6. import { Observable } from 'rxjs/Observable';
  7. import { startWith } from 'rxjs/operators/startWith';
  8. import { map } from 'rxjs/operators/map';
  9.  
  10. import { FormControl, FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';
  11. import { TranslateService } from '@ngx-translate/core';
  12.  
  13. import { AlertService, UserService, SnackService, OrderService } from '../services/index';
  14.  
  15. import { ALLOW_SOCIAL_LOGIN, LANGUAGE_MAP } from '../app.constants';
  16.  
  17. const countries = require("i18n-iso-countries");
  18.  
  19. /* Google Analytics */
  20. declare var gtag: any;
  21.  
  22. @Component({
  23.     moduleId: module.id.toString(),
  24.     selector: 'app-register',
  25.     templateUrl: 'register.component.html'
  26. })
  27.  
  28. export class RegisterComponent implements OnInit {
  29.  
  30.     @Input() view: string;
  31.  
  32.     @Output() onShowallChanged: EventEmitter<any> = new EventEmitter<any>();
  33.     @Output() onRegisterSuccess: EventEmitter<any> = new EventEmitter<any>();
  34.     @Output() onFormChange: EventEmitter<any> = new EventEmitter<any>();
  35.  
  36.     model: any = {}; /* TODO: reduntant ?*/
  37.     loading = false;
  38.     loadingInvoice = false;
  39.     showCountryWarning = false;
  40.     countryInvalid = false;
  41.  
  42.     registerForm: any; /* main account register form */
  43.     // companyForm: any; /* form for company details*/
  44.  
  45.     showPassword: boolean = false;
  46.     showAllfields: boolean = false;
  47.  
  48.     allowSocialRegister: boolean;
  49.     companyFormDisabled: boolean;
  50.  
  51.     loadedCountries: any[];
  52.     filteredOptions: any[];
  53.     // filteredCountries: any;
  54.  
  55.     /* map back-end api errors */
  56.     apiErrorsMap: any;
  57.  
  58.     viewMode: string;
  59.     currentUser: any;
  60.  
  61.     lang: string; // 2 char: "et"
  62.     langLong: string; // 5 char: "et_EE"
  63.     loadingUser: boolean; // whether loading user data and form is disabled for changes
  64.     languageMap: any; // lang map from constants.ts
  65.  
  66.     constructor(
  67.         private router: Router,
  68.         private userService: UserService,
  69.         private alertService: AlertService,
  70.         private fb: FormBuilder,
  71.         private translateService: TranslateService,
  72.         private snackService: SnackService,
  73.         private orderService: OrderService) {
  74.  
  75.         this.allowSocialRegister =  ALLOW_SOCIAL_LOGIN;
  76.  
  77.         countries.registerLocale(require("i18n-iso-countries/langs/en.json"));
  78.         countries.registerLocale(require("i18n-iso-countries/langs/et.json"));
  79.     }
  80.  
  81.     get email() { return this.registerForm.get('email'); }
  82.     get password() { return this.registerForm.get('password'); }
  83.     get name() { return this.registerForm.get('name'); }
  84.     get country() { return this.registerForm.get('country'); }
  85.     get company_name() { return this.registerForm.get('company_name'); }
  86.     get company_reg_nr() { return this.registerForm.get('company_reg_nr'); }
  87.     get company_vat_nr() { return this.registerForm.get('company_vat_nr'); }
  88.     get company_address() { return this.registerForm.get('company_address'); }
  89.     get invoice_email() { return this.registerForm.get('invoice_email'); }
  90.  
  91.     // get language() { return this.loginForm.get('language'); }
  92.     // password change
  93.     get old_password(){ return this.registerForm.get('old_password');}
  94.     get new_password(){ return this.registerForm.get('new_password');}
  95.  
  96.     ngOnInit() {
  97.  
  98.         this.setLanguage();
  99.         this.createRegisterForm();
  100.         this.loadCountries();
  101.         this.setViewMode();
  102.         // this.currentUser = this.userService.getUser();
  103.         console.log("REGISTER COMPONENT VIEW: ", this.viewMode);
  104.     }
  105.  
  106.     setLanguage() {
  107.         this.lang = this.translateService.currentLang;
  108.         if (!this.lang) {
  109.             this.lang = this.translateService.defaultLang;
  110.         }
  111.         this.langLong = LANGUAGE_MAP[this.lang];
  112.         this.languageMap = LANGUAGE_MAP;
  113.     }
  114.  
  115.     setViewMode() {
  116.  
  117.         /* stupid quickhack > should have written the component in a different way*/
  118.         let viewCase;
  119.         if (this.view == 'account') {
  120.             console.log(this.view);
  121.            
  122.             viewCase = 'order'
  123.         } else {
  124.             viewCase = this.view;
  125.         }
  126.  
  127.         switch(viewCase) {
  128.             case 'order': {
  129.                 this.viewMode = 'order';
  130.                 this.showAllfields = true;
  131.                 // this.showPassword = false;
  132.                 // In case of order -> country is needed for VAT
  133.                 this.registerForm.controls["country"].setValidators([Validators.required, Validators.minLength(2)]);
  134.                 this.registerForm.controls["invoice_email"].setValidators([Validators.required, Validators.email]);
  135.                 this.currentUser = this.userService.getUser();
  136.                 if (this.currentUser) {
  137.                     this.setAccountData();
  138.                     this.getInvoiceData();
  139.                     this.companyFormDisabled = true;
  140.                 } else {
  141.                     this.checkCountry();
  142.                 }
  143.  
  144.                 break;
  145.             }
  146.             default: {
  147.                 this.viewMode = 'register';
  148.                 break;
  149.             }
  150.         }
  151.     }
  152.  
  153.     setAccountData() {
  154.         // name, email, password
  155.         this.registerForm.controls['name'].setValue(this.currentUser.displayName);
  156.         this.registerForm.controls['email'].setValue(this.currentUser.email);
  157.         this.registerForm.controls['language'].setValue(this.currentUser.language);
  158.         this.registerForm.controls['password'].setValidators([]);
  159.         /* dummy value, TODO: find a better solution - disable pw required for example! */
  160.         // this.registerForm.controls['password'].setValue("Klm123456000000000000000000000000000000000000000000");
  161.  
  162.     }
  163.  
  164.     getInvoiceData() {
  165.         this.orderService.getInvoiceDetails().subscribe(
  166.                 data => {
  167.                     if (data.data) {
  168.                         this.setInvoiceData(data);
  169.                     }
  170.                 },
  171.                 error => {
  172.                     this.snackService.showTranslatedSnack("ORDER.UNABLE_GET_INVOICE_DETAILS", "OK");
  173.                 });
  174.     }
  175.  
  176.     setInvoiceData(data) {
  177.  
  178.         // console.log("########## setInvoiceData: ", data);
  179.         let country = this.loadedCountries.filter( (country) => country.value === data.data.country)
  180.         this.registerForm.controls['country'].setValue(country[0]);
  181.         this.registerForm.controls['company_name'].setValue(data.data.name);
  182.         this.registerForm.controls['company_reg_nr'].setValue(data.data.registrationNr);
  183.         this.registerForm.controls['company_vat_nr'].setValue(data.data.VATnr);
  184.         this.registerForm.controls['company_address'].setValue(data.data.address);
  185.         this.registerForm.controls['invoice_email'].setValue(data.data.invoiceEmail);
  186.  
  187.         this.checkCountry();
  188.  
  189.     }
  190.  
  191.     checkCountry() {
  192.  
  193.         if ((this.registerForm.controls['country'].valid) && (this.registerForm.get('country').value) ) {
  194.             this.showCountryWarning = false;
  195.             this.countryInvalid = false;
  196.             // console.log("checkCountry: country CORRECT!");
  197.         } else {            
  198.             this.showCountryWarning = true;
  199.             this.registerForm.controls['country'].setErrors({'incorrect': true});
  200.             this.countryInvalid = true;
  201.             // console.log("checkCountry: country INVALID!");
  202.             // this.snackService.showTranslatedSnack("ORDER.COUNTRY_REQUIRED_FOR_INVOICES", "OK");
  203.         }
  204.     }
  205.  
  206.     cancelInvoiceDetailsChange() {
  207.         this.companyFormDisabled = true;
  208.         this.getInvoiceData();
  209.     }
  210.  
  211.     updateInvoiceDetails() {
  212.  
  213.         this.loadingInvoice = true;
  214.         const invoiceData = this.prepareSaveUser(true)
  215.         this.orderService.changeInvoiceDetails(invoiceData).subscribe(
  216.                 data => {
  217.                     // console.log(data);
  218.                     if (data.data) {
  219.                         this.setInvoiceData(data);
  220.                         this.companyFormDisabled = true;
  221.                         this.snackService.showTranslatedSnack("ORDER.INVOICE_DETAILS_SAVED", "OK");
  222.                         this.emitFormValidity();
  223.                         gtag('event', 'add_payment_info'); /* Send GA event */
  224.                     }
  225.                     this.loadingInvoice = false;
  226.                 },
  227.                 error => {
  228.                     this.snackService.showTranslatedSnack("ORDER.UNABLE_SAVE_INVOICE_DETAILS", "OK");
  229.                     this.loadingInvoice = false;
  230.                 });
  231.  
  232.         /* TODO: html preloader progress bar */
  233.     }
  234.  
  235.     updateAccountDetails() {
  236.         this.loadingUser = true;
  237.         const userAccountData = this.prepareSaveUserAccount();
  238.         // console.log("userAccountData: ", userAccountData);
  239.  
  240.         if (userAccountData.email != this.currentUser.email) {
  241.             return this.alertService.error("ACCOUNT.UNABLE_TO_SAVE_ACCOUNT");
  242.         }
  243.  
  244.         this.userService.update(userAccountData).subscribe(
  245.                 data => {
  246.                     // console.log(data);
  247.                     if (data.data && data.status == "success") {
  248.                        
  249.                         // this.setAccountData(); // TODO: once backend returns user/or data object
  250.                        
  251.                         // Switch language immediately
  252.                         this.translateService.use(userAccountData.language.substring(0, 2));
  253.                         // Manipulate the currentUser localstorage obj with new updated values
  254.                         this.userService.updateUserAccount(userAccountData.language, userAccountData.displayName);
  255.                         this.snackService.showTranslatedSnack("ACCOUNT.ACCOUNT_DETAILS_SAVED", "OK");
  256.  
  257.                         // Send GA event
  258.                         gtag('event', 'update_account_details', {
  259.                             'event_category' : 'client_app',
  260.                             'event_label' : userAccountData.email,
  261.                         });
  262.  
  263.                     }
  264.                     this.loadingUser = false;
  265.                 },
  266.                 error => {
  267.                     this.snackService.showTranslatedSnack("ACCOUNT.UNABLE_TO_SAVE_ACCOUNT", "OK");
  268.                     this.loadingUser = false;
  269.                 });
  270.  
  271.     }
  272.  
  273.     emitFormValidity() {
  274.         if (this.registerForm.valid) {
  275.             this.onFormChange.emit({valid: true});
  276.         } else {
  277.             this.onFormChange.emit({valid: false});
  278.         }
  279.     }
  280.  
  281.     loadCountries() {
  282.  
  283.         const lang = this.translateService.currentLang ? this.translateService.currentLang : "en";
  284.         const countriesLocale = countries.getNames(lang);
  285.         // console.log("countriesLocale: ", countriesLocale);
  286.  
  287.         this.loadedCountries = [];
  288.         for (const key of Object.keys(countriesLocale)) {
  289.           this.loadedCountries.push({ display: countriesLocale[key], value: key.toLowerCase() });
  290.         }
  291.         this.filteredOptions = this.loadedCountries;
  292.  
  293.         // console.log("this.loadedCountries: ", this.loadedCountries);
  294.         this.registerCountryChanges();
  295.     }
  296.  
  297.     registerCountryChanges() {
  298.         this.registerForm.controls['country'].valueChanges.subscribe(val => {
  299.             this.filteredOptions = this.loadedCountries.filter(
  300.                     (country) => typeof val === 'string' ? country.display.toLowerCase().startsWith(val.toLowerCase()) : this.loadCountries
  301.                 )
  302.  
  303.             /* Make sure that value is an object*/
  304.             if ((typeof val === 'object') && (val.display && val.value)) {
  305.                 this.countryInvalid = false;
  306.             } else {
  307.                 this.registerForm.controls['country'].setErrors({'incorrect': true});
  308.                 this.countryInvalid = true;
  309.             }
  310.  
  311.             if (this.viewMode == "order") {
  312.                 this.checkCountry();
  313.             }
  314.  
  315.         });
  316.        
  317.     }
  318.  
  319.     displayCountry(user?): string | undefined {
  320.         return user ? user.display : undefined;
  321.     }
  322.  
  323.     resetApiErrorsMap() {
  324.         this.apiErrorsMap = {
  325.             displayName: null,
  326.             email: null,
  327.             password: null,
  328.             country: null,
  329.             name: null,
  330.             registrationNr: null,
  331.             VATnr: null,
  332.             address: null,
  333.             invoiceEmail: null,
  334.             language: null,
  335.         };
  336.     }
  337.  
  338.     register() {
  339.         this.loading = true;
  340.         const regData = this.prepareSaveUser();
  341.         // console.log("regData: ", regData);
  342.         // this.apiErrorsMap = {};
  343.         this.resetApiErrorsMap();
  344.         this.userService.create(regData)
  345.             .subscribe(
  346.                 data => {
  347.                     // console.log(data);
  348.                     if ( (data.status === "success") && (data.data) ) {
  349.                         const hash = btoa(regData.userDetails.email + ":" + regData.userDetails.password);
  350.                         this.userService.setUser(data.data, true, hash);
  351.  
  352.                         this.snackService.showTranslatedSnack("REGISTER.REGISTRATION_SUCCESS", "OK");
  353.                         this.alertService.success("REGISTER.REGISTRATION_SUCCESS", true);
  354.  
  355.                         /* IF registration view > route to new order */
  356.                         if (this.viewMode === 'register') {
  357.                             this.router.navigate(['/orders/new']);
  358.                         }
  359.  
  360.                         if (this.viewMode === 'order') {
  361.                             this.showPassword = false;
  362.                             this.companyFormDisabled = true;
  363.                         }
  364.  
  365.                         this.onRegisterSuccess.emit(data.data);
  366.                         this.currentUser = this.userService.getUser();
  367.  
  368.                         gtag('event', 'sign_up', { method : 'Sille account' }); /* Send GA event */
  369.  
  370.                     } else if (data.status !== "success") {
  371.                         if (data.message === "Validation failed") {
  372.                             this.alertService.error("REGISTER.VALIDATION_FAILED");
  373.                         } else {
  374.                             console.log("alert data.message: ", data.message);
  375.                             this.alertService.error(data.message);
  376.                         }
  377.                         this.handleFieldErrors(data);
  378.                     } else {
  379.                         this.loading = false;
  380.                     }
  381.  
  382.                     // TODO: set user & navigate to order form
  383.                     this.loading = false;
  384.                 },
  385.                 error => {
  386.                     console.log("alert error data.message: ", error);
  387.                     this.alertService.error(error);
  388.                     this.loading = false;
  389.                 });
  390.     }
  391.  
  392.     handleFieldErrors(data: any) {
  393.  
  394.         const fieldsMap = {
  395.             displayName: "name",
  396.             email: "email",
  397.             password: "password",
  398.             country: "country",
  399.             name: "company_name",
  400.             registrationNr: "company_reg_nr",
  401.             VATnr: "company_vat_nr",
  402.             address: "company_address",
  403.             invoiceEmail: "invoice_email",
  404.             language: "language"
  405.         };
  406.  
  407.         if (data.fieldErrors) {
  408.             const fields = data.fieldErrors;
  409.             for (const key of Object.keys(fields)) {
  410.                 let fieldPieces = key.split(".");
  411.                 let field = fieldPieces.pop();
  412.                 // console.log(field + " - " + fields[key].message);
  413.                 if (fieldsMap[field]) {
  414.                     this.registerForm.controls[fieldsMap[field]].setErrors({'incorrect': true});
  415.                     this.apiErrorsMap[fieldsMap[field]] = fields[key].message;
  416.                 }
  417.             }
  418.             // console.log(this.apiErrorsMap);
  419.         }
  420.     }
  421.  
  422.     createRegisterForm() {
  423.         this.registerForm = this.fb.group({
  424.             "name": ['', [ Validators.minLength(2) ] ],
  425.             "email": ['', [ Validators.required, Validators.email ] ],
  426.             // ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d_!@#$%&\/\"{}()=?+'-*~|]{8,}$
  427.             "password": ['', [ Validators.required, Validators.minLength(8), Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d_!@#$%&\/\"{}()=?+'\-*~|]{8,}$/) ] ],
  428.             // "password": ['', [ Validators.required, Validators.minLength(8), Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/) ] ],
  429.             "country": ['', [ Validators.minLength(2) ] ], /* TODO: letters only */ /* TODO: eu vat warning eu riikide puhul? */
  430.             "company_name": ['', [ Validators.minLength(2), Validators.maxLength(100) ] ],
  431.             "company_reg_nr": ['', [ Validators.minLength(2), Validators.maxLength(100) ] ],
  432.             "company_vat_nr": ['', [ Validators.minLength(2), Validators.maxLength(100) ] ], /* TODO: et puhul kmkr validaator?*/
  433.             "company_address": ['', [ Validators.minLength(2), Validators.maxLength(200) ] ],
  434.             "invoice_email": ['', [ Validators.email ] ],
  435.             "language": [this.lang],
  436.             "old_password": ['', [ Validators.minLength(8)]],
  437.             "new_password": ['', [Validators.required, Validators.minLength(8), Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d_!@#$%&\/\"{}()=?+'\-*~|]{8,}$/) ] ]
  438.         });
  439.  
  440.         this.onFormChanges();
  441.     }
  442.  
  443.  
  444.  
  445.     prepareSaveUser(only_invoice?: boolean): any {
  446.  
  447.         /* TODO: küsi siin juba vormi lang väärtust!= */
  448.  
  449.         const formModel = this.registerForm.value;
  450.         // console.log("this.translateService.currentLang: ", this.translateService.currentLang);
  451.         // console.log("prepareSaveUser > formModel: ", formModel);
  452.  
  453.         const registerData = {
  454.             userDetails: {
  455.                 email: formModel.email,
  456.                 displayName: formModel.name,
  457.                 language: LANGUAGE_MAP[this.translateService.currentLang],
  458.                 password: formModel.password,
  459.             },
  460.             invoiceDetails: {
  461.                 country: formModel.country.value,
  462.                 name: formModel.company_name,
  463.                 registrationNr: formModel.company_reg_nr,
  464.                 VATnr: formModel.company_vat_nr,
  465.                 address: formModel.company_address,
  466.                 invoiceEmail: formModel.invoice_email
  467.             }
  468.         }
  469.         if (only_invoice) {
  470.             return registerData.invoiceDetails;
  471.         } else {
  472.             return registerData;
  473.         }
  474.     }
  475.  
  476.     prepareSaveUserAccount() {
  477.         const formModel = this.registerForm.value;
  478.         let langToUse;
  479.         if ((formModel.language) && (formModel.language.length == 5) ) {
  480.             // console.log("formModel.language.length: ", formModel.language.length);
  481.             langToUse = formModel.language;
  482.         } else {
  483.             langToUse = LANGUAGE_MAP[this.translateService.currentLang];
  484.         }
  485.  
  486.         const userAccountData = {
  487.             email: formModel.email,
  488.             displayName: formModel.name,
  489.             language: langToUse,
  490.         }
  491.  
  492.         return userAccountData;
  493.     }
  494.  
  495.     // In case of a valid registration e-mail we'll set the invoice email already as the default
  496.     onFormChanges() {
  497.         this.registerForm.controls['email'].valueChanges.subscribe(val => {
  498.             if (val) {
  499.                 if (this.registerForm.controls['email'].valid) {
  500.                     this.registerForm.controls['invoice_email'].setValue(val);  
  501.                 }
  502.             }
  503.         });
  504.  
  505.         this.registerForm.valueChanges.subscribe( val => {
  506.             const formData = {
  507.               valid: this.registerForm.valid,
  508.               data: val,
  509.             }
  510.             if ( (this.currentUser) && (this.companyFormDisabled) ) {
  511.               this.onFormChange.emit(formData);
  512.             }
  513.             // console.log("registerForm.valueChanges: ", val);
  514.             // console.log("registerForm.valid: ", this.registerForm.valid);
  515.         });
  516.  
  517.         if (this.currentUser) {
  518.             this.registerForm.controls['country'].valueChanges.subscribe(val => {
  519.                     // console.log("country val: ", val);
  520.                     this.checkCountry();
  521.                 });
  522.         }
  523.     }
  524.  
  525.     // change password for registered user
  526.     onChangePasswordSubmit() {
  527.         this.changePassword();
  528.     }
  529.  
  530.     changePassword() {
  531.         const oldpassword = this.registerForm.get('old_password').value;
  532.         const newpassword = this.registerForm.get('new_password').value;
  533.         const data = {
  534.             oldPassword: oldpassword,
  535.             newPassword: newpassword
  536.         }
  537.         if (newpassword) {
  538.             this.userService.updatePassword(data).subscribe(
  539.                 data => {
  540.                     // console.log(data);
  541.                     if (data.status == "success") {
  542.                         this.userService.updateUserHash(newpassword);
  543.                         this.snackService.showTranslatedSnack("ACCOUNT.PASSWORD_CHANGE_SUCCESS", "OK");
  544.                         this.alertService.success("ACCOUNT.PASSWORD_CHANGE_SUCCESS");
  545.                         this.resetChangePasswordForm();
  546.                     } else if (data.status == "fail") {
  547.                         this.snackService.showTranslatedSnack("ACCOUNT.PASSWORD_DOES_NOT_MATCH", "OK");
  548.                         this.alertService.error("ACCOUNT.PASSWORD_DOES_NOT_MATCH");
  549.                     }
  550.  
  551.                 },
  552.                 error => {
  553.  
  554.                 });
  555.             ;
  556.         }
  557.     }
  558.     resetChangePasswordForm(){
  559.         this.registerForm.controls['old_password'].setValue(null);
  560.         this.registerForm.controls['new_password'].setValue(null)
  561.     }
  562.  
  563.     /* TODO: remove this useless wrapper */
  564.     onRegisterSubmit() {
  565.         this.register();
  566.     }
  567.  
  568.     googleRegister() {
  569.         // console.log("TODO: register with google");
  570.     }
  571.  
  572.     facebookRegister() {
  573.         // console.log("TODO: register with facebook");
  574.     }
  575.  
  576.     toggleAllFields() {
  577.         this.showAllfields = !this.showAllfields;
  578.         this.onShowallChanged.emit(this.showAllfields);
  579.         gtag('event', 'toggle_showallfields', {
  580.           'event_category' : 'client_app',
  581.           'event_label' : this.showAllfields,
  582.         });
  583.     }
  584.  
  585. }
Add Comment
Please, Sign In to add comment