Learn more  » Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Bower components Debian packages RPM packages NuGet packages

skava / @skava-features/header   js

Repository URL to install this package:

Version: 0.1.7 

/ dist / src / state / session / container.js

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
// modules/libs
import { oneRouter } from '@skava/router';
import { isString } from 'exotic';
import { when } from 'xmobx/mobx';
import { cookies } from '@skava/cookies';
import { getTyped } from 'composition';
import { isErrorLikeResponse } from '@skava/is-error-like-response';
import ObservableContainer from 'src/bootstrapper/connectData/ObservableContainer';
// ===========================
// state... SHOULD NOT IMPORT SO MANY IN HERE, ENSURE THEY DO NOT IMPORT EACH OTHER
// @example @issue before
// session <====> cart
// session <====> shoppingList
// ===========================
// @note => user/payments => session
import { userContainer } from 'src/state/user/container';
import { toastMessage, responseMessage } from 'src/state/errorView/_fixture';
import { errorContainer } from 'src/state/errorView/container';
// was importing this, changed to .apis as a split to avoid that
import { cartContainer } from 'state/cart/container';
// => listContainer => state/cart/container
import { listContainer } from 'state/list/container';
// safe
import { listContainerApi } from 'state/list/container.list';
// => shoppingListContainer => state/cart/container => sessionContainer
import { shoppingListContainer } from 'src/state/shoppingList/container';
// clear
import { favoritesContainer } from 'state/favorites/container';
import { signinContainer } from 'src/views/widgets/Authentication/container';
// domain config
import { cookieConfig } from 'src/bootstrapper/api/config';
import { pathParams } from 'src/bootstrapper/routes/pathParams';
import { LogOutQuery } from './queries';
import { sessionApis } from './container.apis';
import { fromResponseToLoginToast, toSyncListResponse, checkIsSessionExpired, isRegisterSuccess, toBagResponse, toFavoritesResponse, toSaveForLaterResponse, mapCookiesOnResponse, isLoginSuccess, createRecentlyViewedList, toUserProfileResponse, clearCookies, checkSessionExpiredOnMyAccount, } from './deps';
class SessionContainer extends ObservableContainer {
    constructor() {
        super(...arguments);
        this.navigateBackTo = '';
        // @note disabled
        // {"message":"TypeError: Cannot read property 'isB2B' of undefined\n    at Object.330 (/media/ephemeral0/jenkins/.jenkins/workspace/New_Storefront_Build/reference-store/src/views/atoms/Main/index.tsx:1:1)\n    at i (/media/ephemeral0/jenkins/.jenkins/workspace/New_Storefront_Build/reference-store/webpack/bootstrap:2:1)\n    at Module.433 (/media/ephemeral0/jenkins/.jenkins/workspace/New_Storefront_Build/reference-store/src/views/atoms/Main/index.tsx:1:1)\n    at i (/media/ephemeral0/jenkins/.jenkins/workspace/New_Storefront_Build/reference-store/webpack/bootstrap:2:1)\n    at internalTickCallback (internal/process/next_tick.js:77:7)\n    at _tickCallback (internal/process/next_tick.js:47:5)\n    at listOnTimeout (timers.js:294:7)\n    at processTimers (timers.js:268:5)\n","timestamp":"2018-12-14T00:51:36.496Z","type":"err","process_id":1,"app_name":"reference-store"}
        // get isB2B(): boolean {
        //   return process.env.BUSINESS_RELATIONSHIP === 'B2B'
        // }
        // get isB2C(): boolean {
        //   return process.env.BUSINESS_RELATIONSHIP === 'B2C'
        // }
        this.handleProps = (props) => {
            // extract
            // const { userStore, favoritesStore, cartDetailStore } = this.omniStore
            // const { cartDetailStore } = this.omniStore
            // cosnt  { favoritesStore } = this.omniStore
            const { cartCount } = cartContainer;
            // @todo @userContainer
            // const { userName } = userStore
            const userName = userContainer.userName;
            return Object.assign({}, props, { container: this, hasGuestUserCookie: this.hasGuestUserCookie, hasUserCookie: this.hasUserCookie, isGuestUser: this.isGuestUser, isRegisteredUser: this.isRegisteredUser, userCookie: this.userCookie, cartCount,
                userName });
        };
        this.registerUser = (data, securityParams) => __awaiter(this, void 0, void 0, function* () {
            const user = yield sessionApis
                .registerUser(data, securityParams)
                // .then(this.mapCookiesOnResponse)
                // .then(() => {
                //   // now this happens 2x
                //   sessionApis.createList().then(toListResponse)
                //   sessionApis.createSaveForLater().then(toListResponse)
                //   sessionApis.viewBag().then(toBagResponse)
                // })
                .then(this.handleRegisterResponse)
                .catch(this.handleError);
            /**
             * @todo this should be an array @@perf
             */
            let profile = '';
            let security = '';
            const { string } = getTyped(user);
            const userStatus = string('properties.state.status');
            if (userStatus === responseMessage.accountCreationSuccess ||
                userStatus === responseMessage.registerMailFailure) {
                profile = yield sessionApis
                    .fetchUserProfile()
                    .then(toUserProfileResponse)
                    .then((response) => __awaiter(this, void 0, void 0, function* () {
                    if (this.isRegisteredUser) {
                        console.log('registerUser createSaveForLaterList');
                        yield this.getAllListAPI();
                    }
                    console.log('Loaded User Profile');
                    userContainer.updateFrom(response);
                    // this.omniStore.loadUser(response)
                    this.navigateToLoginSuccess();
                }))
                    .catch(this.handleError);
                if (process.env.API_LAYER === 'Stream') {
                    security = yield sessionApis.updateSecurity(securityParams, true);
                }
                // .then((response: unknown) => {
                //   console.log('security Question response', response)
                //   userContainer.updateFrom(response)
                // })
            }
            // may not want to do it this way
            // may want to show a loader in interfacestore
            // & then go to the other page
            // oneRouter.replace('/myaccount')
            return Promise.all([user, profile, security]).then(result => {
                console.log(result);
            });
        });
        this.getAllListAPI = () => __awaiter(this, void 0, void 0, function* () {
            const response = yield listContainerApi.getAllList().then((listResponse) => {
                shoppingListContainer.updateFrom(listResponse);
                favoritesContainer.checkAndUpdateFavorites(listResponse);
                listContainerApi.createSaveForLaterList(listResponse);
            });
            return response;
        });
        /**
         * @todo @fixme this is to be done on graphql side!!!
         */
        this.adminRegisterAccount = (data) => __awaiter(this, void 0, void 0, function* () {
            const registerData = {
                firstName: data['first-name'],
                lastName: data['last-name'],
                phoneNumber: data['phone-number'],
                email: data.email,
                name: data['organization-name'],
                // password: '',
                street1: data['address-line-one'],
                street2: data['address-line-two'] || '',
                street3: '',
                city: data.city,
                country: data.country,
                state: data.state,
                county: '',
                zipCode: data.postalCode,
                taxId: data['tax-identifier'],
                dunsNumber: isString(data.duns) ? data.duns : '',
            };
            const response = yield sessionApis.adminRegisterAccount(registerData);
            if (isErrorLikeResponse(response)) {
                errorContainer.setError({
                    errorMessage: response.responseMessage || '',
                });
            }
            else {
                oneRouter.update('/');
                errorContainer.setError({
                    errorMessage: toastMessage.registerSuccess,
                });
            }
        });
        this.updateProfile = (profileData) => __awaiter(this, void 0, void 0, function* () {
            const response = yield sessionApis.updateProfile(profileData).catch(this.handleError);
            this.fetchProfile();
            return response;
            // .then(this.fetchProfile)
        });
        this.updateSecurity = (data) => __awaiter(this, void 0, void 0, function* () {
            yield sessionApis.updateSecurity(data).catch(this.handleError);
        });
        this.getSecurityQuestions = (data) => __awaiter(this, void 0, void 0, function* () {
            yield sessionApis.getSecurityQuestions(data).catch(this.handleError);
        });
        this.resetPasswordThroughSms = (data) => __awaiter(this, void 0, void 0, function* () {
            const response = yield sessionApis.resetPasswordThroughSms(data).catch(this.handleError);
            return response;
        });
        this.resetPasswordThroughEmail = (data) => __awaiter(this, void 0, void 0, function* () {
            const response = yield sessionApis.resetPasswordThroughEmail(data).catch(this.handleError);
            return response;
        });
        this.validateByEmail = (data) => __awaiter(this, void 0, void 0, function* () {
            const response = yield sessionApis.validateByEmail(data).catch(this.handleError);
            return response;
        });
        this.userActivation = (data) => __awaiter(this, void 0, void 0, function* () {
            const response = yield sessionApis.userActivation(data).catch(this.handleError);
            return response;
        });
        this.resetPasswordThroughSecurityQuestions = (data) => __awaiter(this, void 0, void 0, function* () {
            const response = yield sessionApis
                .resetPasswordThroughSecurityQuestions(data)
                .catch(this.handleError);
            return response;
        });
        this.updatePassword = (password) => __awaiter(this, void 0, void 0, function* () {
            const response = yield sessionApis.updatePassword(password).catch(this.handleError);
            return response;
        });
        // @todo - use routes here so it is configurable in 1 place
        this.registerGuestUser = () => __awaiter(this, void 0, void 0, function* () {
            if (this.isOrchestarionGuestUser || this.isGuestUser) {
                console.log('Already a guest!');
                return false;
            }
            else {
                console.log('No active user found creating guest');
                typeof window === 'object' && console.log(document.cookie);
                const guest = yield sessionApis.registerGuestUser();
                const profile = yield sessionApis
                    .fetchUserProfile()
                    .then(toUserProfileResponse)
                    .then((response) => {
                    userContainer.updateFrom(response);
                })
                    .then(createRecentlyViewedList);
                return Promise.all([guest, profile]).then(result => {
                    typeof window === 'object' &&
                        console.log('[Cookie Monster]', 'Registered Guest User', document.cookie);
                });
            }
        });
        /**
         * @todo show toast
         */
        this.logOut = () => __awaiter(this, void 0, void 0, function* () {
            const response = yield this.client.query({
                query: LogOutQuery,
                variables: {},
                // network-only?
                fetchPolicy: 'no-cache',
            });
            clearCookies();
            // oneRouter.replace('/logout')
            // oneRouter.reload()
            errorContainer.setError({
                errorMessage: 'Signed out',
            });
            // window.location.reload()
            // return response.data.logOut
        });
        this.handleLoginResponse = (response) => {
            const isLoginSuccessful = isLoginSuccess(response);
            if (isLoginSuccessful) {
                console.log('You are logged in');
                mapCookiesOnResponse(response);
            }
            else {
                signinContainer.gotoFreezeSignIn(response);
                const toastText = fromResponseToLoginToast(response);
                errorContainer.setError({
                    errorMessage: toastText,
                });
                console.log('Something Strange In The Neighborhood', response);
            }
            return isLoginSuccessful;
        };
        this.handleRegisterResponse = (response) => {
            const { string } = getTyped(response);
            // @todo use isErrorLikeResponse to check response success/Failure
            if (isRegisterSuccess(response)) {
                favoritesContainer.createFavoritesList();
                listContainerApi.createDefaultListForSave();
                console.log('User created Successfully');
            }
            else {
                errorContainer.setError({
                    errorMessage: string('properties.state.status') || '',
                });
                console.log('Something Strange In The User creation', response);
            }
            return response;
        };
        this.logIn = (data) => __awaiter(this, void 0, void 0, function* () {
            if (this.isRegisteredUser) {
                this.navigateToLoginSuccess();
                return true;
            }
            const loginUser = yield sessionApis
                .logIn(data)
                .then(this.handleLoginResponse)
                .catch(this.handleError);
            const withProfile = yield sessionApis
                .fetchUserProfile(true, true)
                .then(toUserProfileResponse)
                .then((response) => __awaiter(this, void 0, void 0, function* () {
                if (this.isRegisteredUser) {
                    console.log('logIn createSaveForLaterList');
                    yield this.getAllListAPI();
                }
                userContainer.updateFrom(response);
                // @note this is different than others
                // when we load user then return response
                // this.omniStore.loadUser(response)
            }))
                .then(() => {
                this.navigateToLoginSuccess();
                return true;
            })
                .catch(this.handleError);
            /**
             * @see https://jira.skava.net/browse/SKB2B-2403
             */
            if (loginUser) {
                yield cartContainer.viewCart();
            }
            return Promise.all([loginUser, withProfile]).then(result => {
                return result[0];
                // console.log('Logged In')
            });
        });
        this.loginWithFacebook = (data) => __awaiter(this, void 0, void 0, function* () {
            if (this.isRegisteredUser) {
                this.navigateToLoginSuccess();
                console.log('You are already logged in');
                return;
            }
            yield sessionApis
                .loginWithFacebook(data)
                .then(this.handleLoginResponse)
                // @todo if this fails, don't fetch?
                .catch(this.handleError);
            yield this.fetchProfile();
            this.navigateToLoginSuccess();
        });
        this.loginWithTwitter = (data) => __awaiter(this, void 0, void 0, function* () {
            if (this.isRegisteredUser) {
                this.navigateToLoginSuccess();
                console.log('You are already logged in');
                return;
            }
            let loginResponse = '';
            yield sessionApis
                .loginWithTwitter(data)
                .then((response) => {
                loginResponse = response;
                this.handleLoginResponse(response);
            })
                // @todo if this fails, don't fetch?
                .catch(this.handleError);
            yield this.fetchProfile();
            if (isLoginSuccess(loginResponse)) {
                this.navigateToLoginSuccess(true);
            }
        });
Loading ...