methods/userRegistration/index.js

import { cleanError, manageError } from '../../errorManager';
import { isVoid, isValid } from '../../validation';
import config from '../../config';
import Method from '../Method';

const formModel = {
    buttonAddEmail: 'frmAddEmail',
    buttonSkip: 'frmAddEmailSkip',
    buttonCancelAddEmail: 'frmAddEmailReturn',
    email: 'email',
    switchEye: 'add_mail_password_switch_type',
    password: 'password'
};

/**
 * @memberOf Useris
 * @function userRegistration
 *
 * @description Validate and recognize the object to add a new newton identity.
 *
 * Remember to check if an identy is already present.
 * If yes you have to delete the old and add the new one
 *
 *
 * It must be used with the **smartaddemail** template;
 *
 * @param {Object} options Options object
 * @param {Object} [options.element=false] The div element where the html's tmpl will be injected
 * @param {Object} [options.regexObject={}]
 * **Optionals** Contains all the regular expressions for input validation
 * (msisdn, pin, email, password and generic regex are allowed)
 * @param {String} [options.acccess_token=''] **Optionals** if true,
 * the tmpl calls will be called with the params access_token filled
 * @param {Boolean} [options.doNotLoad=false] **Optionals** if true,
 * this params will tell useris to not load the template (It doesn't make the apicall)
 * @param {String} [options.smsTemplate=''] the template of the sms sent (msisdn add identity)
 * @param {boolean} [options.skipRegister=0] allow a user to have a generic identity
 * @param {boolean} [options.ohterParams=0] params to substitute for mail
 * @param {Object} callbackObject Manage the success and error callback
 * @param {function} [callbackObject.onSuccess='no-default']
 * Success callback (code managed by the app)
 * @param {function} [callbackObject.onError='no-default'] Error callback (code managed by the app)
 * @param {function} [callbackObject.onTemplateLoaded='no-default']
 * Callback executed when the template has been loaded.
 *
 * @example
 *  Useris.userRegistration({
 *      element: document.getElementById('elementId'),
 *      regexObject: {
 *          msidn: '',
 *          pin: '',
 *          email: '',
 *          password: '',
 *          generic: '',
 *          genericPassword: ''
 *      },
 *      skipRegister: 1,
 *      smsTemplate: 'Hello, welcome to the service!',
 *      otherParams: '{}'
 *  }, {
 *      onSuccess: function(userCredentials){
 *          // remember to check if an identy is already present.
 *          // If yes you have to delete the old and add the new one
 *          callsToNewton.addIdentity(userCredentials);
 *      },
 *      onCancel: function(){
 *          window.location.href = '#!';
 *      }
 *      onError: function(error){
 *          console.log('Error:', error);
 *          manageError(error);
 *      },
 *      onTemplateLoaded: function(tmplInfo){
 *          console.log('Template loaded', tmplInfo);
 *      }
 *  });
 *
 * @returns {object}
 *  **Email case:**
 *  <pre>
 *  {
 *      email: string,
 *      password: string,
 *      skipped: boolean,
 *      type: 'email',
 *      smsTemplate: string,
 *      params: Object
 *  }
 *  </pre>
 *  **Skipped case:**
 *  <pre>
 *  {
 *      skipped: boolean,
 *      type: 'generic',
 *      smsTemplate: string
 *  }
 *  </pre>
 */
export default class UserRegistration extends Method {
    init = (options) => {
        this.smartsectionObj = {
            subsection: 'smartaddemail',
            skip: options.skipRegister || 0,
            loadForm: options.element || false,
            access_token: options.access_token || '',
            doNotLoad: options.doNotLoad || false
        };
        this.initUserView();
    };

    attachEvents = () => {
        const buttonAddEmail = this.UserViewInstance.getElement(formModel.buttonAddEmail);
        const buttonSkip = this.UserViewInstance.getElement(formModel.buttonSkip);
        const buttonCancelAddEmail = this.UserViewInstance
            .getElement(formModel.buttonCancelAddEmail);
        const switchEye = this.UserViewInstance.getElement(formModel.switchEye);

        this.UserViewInstance.attachEvent(buttonAddEmail, {
            eventName: 'click',
            event: (e) => {
                e.preventDefault();
                cleanError();
                const email = this.UserViewInstance.getValue('email');
                const password = this.UserViewInstance.getValue('password');
                const parObj = {
                    EMAIL: email,
                    USERNAME: email
                };

                try {
                    if (isVoid(email) || !isValid(email, this.regexObject.email)) {
                        manageError('useris-error-msg');
                        return;
                    }

                    if (isVoid(password) || !isValid(password, this.regexObject.password)) {
                        manageError('useris-error-password');
                        return;
                    }
                    let params = {};
                    if (this.options.otherParams) {
                        params = Object.keys(this.options.otherParams).reduce((obj, key) => {
                            obj[key] = parObj[this.options.otherParams[key].replace(':', '')];
                            return obj;
                        }, {});
                    }
                    this.callback('onSuccess', {
                        email,
                        password,
                        params,
                        skipped: 0,
                        type: 'email',
                        smsTemplate: config.get('redirectToMipRegisterAtStart') ? this.options.smsTemplate : false,
                    });
                } catch (error) {
                    manageError(error);
                }
            }
        });

        if (this.options.skipRegister || config.get('skipRegister')) {
            this.UserViewInstance.attachEvent(buttonSkip, {
                eventName: 'click',
                event: (e) => {
                    e.preventDefault();
                    this.callback('onSuccess', {
                        skipped: 1,
                        type: 'generic',
                        smsTemplate: this.options.smsTemplate
                    });
                }
            });
        }

        if (switchEye) {
            this.UserViewInstance.attachEvent(switchEye, {
                eventName: 'click',
                event: (e) => {
                    e.preventDefault();
                    this.UserViewInstance.switchInputType(formModel.password, switchEye.id);
                }
            });
        }

        this.UserViewInstance.attachEvent(buttonCancelAddEmail, {
            eventName: 'click',
            event: (e) => {
                e.preventDefault();
                this.callback('onCancel');
            }
        });
    }
}