methods/forgot/index.js

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

const formModel = {
    forgotButton: 'forgotbutton',
    username: 'username',
    phone_number: 'phone_number'
};

/**
 * @memberOf Useris
 * @function forgot
 *
 * @description Validate and recognize how to send the link of reset password (msisdn or mail).
 *
 * It must be used with the **smartforgot** 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 {String} [options.smsTemplate=''] **Optionals** if set,
 * will take the sms template to recover pin
 * @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 {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.forgot({
 *      element: document.getElementById('elementId'),
 *      regexObject: {
 *          msidn: '',
 *          pin: '',
 *          email: '',
 *          password: '',
 *          generic: '',
 *          genericPassword: ''
 *      }
 *  }, {
 *      onSuccess: function(userCredentials){
 *          console.log(userCredentials);
 *          callsToNewtonAdapter.forgot(userCredentials);
 *      },
 *      onError: function(error){
 *          console.log('Error:', error);
 *          manageError(error);
 *      },
 *      onTemplateLoaded: function(tmplInfo){
 *          console.log('Template loaded', tmplInfo);
 *      }
 *  });
 *
 *  @returns {object}
 *  **Msisdn case:**
 *  <pre>
 *      {
 *          msisdn: string
 *      }
 *  </pre>
 *  **Email case:**
 *  <pre>
 *      {
 *          email: string
 *      }
 *  </pre>
 */
export default class Forgot extends Method {
    init = (options) => {
        this.smartsectionObj = {
            subsection: 'smartforgot',
            loadForm: options.element || false,
            access_token: options.access_token || '',
            doNotLoad: options.doNotLoad || false
        };
        this.initUserView();
    };

    attachEvents = () => {
        const forgotButton = this.UserViewInstance.getElement(formModel.forgotButton);

        this.UserViewInstance.attachEvent(forgotButton, {
            eventName: 'click',
            event: (e) => {
                e.preventDefault();
                cleanError();

                let username = this.UserViewInstance.getValue(formModel.username);
                const phoneNumber = this.UserViewInstance.getElement(formModel.phone_number);

                try {
                    if (isVoid(username)) {
                        manageError('useris-error-msg');
                        return;
                    }

                    if (isValid(username, this.regexObject.msisdn)) {
                        if (config.get('enableAliasCheck')) {
                            if (username.indexOf('+') >= 0) {
                                username = username.replace('+', '');
                            }

                            Api.getAlias({
                                msisdn: username
                            }).then((response) => {
                                if (response && response.alias) {
                                    if (phoneNumber) {
                                        phoneNumber.value = response.alias;
                                    }

                                    const objToOnSuccess = {
                                        alias: response.alias
                                    };

                                    if (typeof this.options.smsTemplate !== 'undefined' && this.options.smsTemplate !== '') {
                                        objToOnSuccess.smsTemplate = this.options.smsTemplate;
                                    }
                                    this.callback('onSuccess', objToOnSuccess);
                                } else {
                                    global.logger.log('Empty Alias');
                                    manageError('useris-error-msg');
                                }
                            }).catch((error) => {
                                manageError(error);
                            });
                        } else {
                            if (phoneNumber) {
                                phoneNumber.value = username;
                            }

                            const objToOnSuccess = {
                                msisdn: username
                            };

                            if (typeof this.options.smsTemplate !== 'undefined' && this.options.smsTemplate !== '') {
                                objToOnSuccess.smsTemplate = this.options.smsTemplate;
                            }
                            this.callback('onSuccess', objToOnSuccess);
                        }
                    } else if (isValid(username, this.regexObject.email)) {
                        this.callback('onSuccess', { email: username });
                    } else {
                        manageError('useris-error-msg');
                    }
                } catch (error) {
                    manageError(error);
                }
            }
        });
    }
}