Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@skava-features/header / dist / src / state / session / container.js
Size: Mime:
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);
            }
        });
        this.loginWithGoogle = (data) => __awaiter(this, void 0, void 0, function* () {
            if (this.isRegisteredUser) {
                this.navigateToLoginSuccess();
                console.log('You are already logged in');
                return;
            }
            yield sessionApis
                .loginWithGoogle(data)
                .then(this.handleLoginResponse)
                // @todo if this fails, don't fetch?
                .catch(this.handleError);
            yield this.fetchProfile();
            this.navigateToLoginSuccess();
        });
        this.getTokenAuth = () => __awaiter(this, void 0, void 0, function* () {
            const response = yield sessionApis.getTwitterAuthToken();
            return response;
        });
        // shouldEnablePaymentRetrival, shouldEnableAddressRetrival
        this.fetchProfile = (shouldGetPayment, shouldGetAddress) => __awaiter(this, void 0, void 0, function* () {
            const profile = yield sessionApis
                .fetchUserProfile(shouldGetPayment, shouldGetAddress)
                .then(toUserProfileResponse)
                // @todo inline, but not sure on resolved result
                .then((response) => {
                userContainer.updateFrom(response);
                if (response.responseCode === '401') {
                    clearCookies();
                }
                // this.omniStore.loadUser(response)
                return response;
            })
                .catch(this.handleError);
            /**
             * Session expired check and navigation to the /signin page
             * in the user profile call
             */
            checkSessionExpiredOnMyAccount(profile);
            return Promise.resolve(profile);
        });
        /**
         * @desc this is in parallel, to not block requests
         */
        this.afterRegisterUser = () => __awaiter(this, void 0, void 0, function* () {
            // sessionApis.createList().then(toListResponse)
            // sessionApis.createSaveForLater().then(toListResponse)
            sessionApis
                .viewBag()
                .then(toBagResponse)
                .then((response) => {
                cartContainer.updateFrom(response);
            });
        });
        /**
         * moved out of flow to avoid guarenteed deopt
         */
        this._flow = () => __awaiter(this, void 0, void 0, function* () {
            const isNotLoggedIn = !this.isOrchestarionGuestUser || !this.isGuestUser || !this.isRegisteredUser;
            // const { listStore } = this.omniStore
            // @todo
            // const lastFlow = localStorage.get('last_flow')
            // const now = Date.now()
            // let diff = diffInMinutes(lastSaveTime, now)
            // if (diff < 5) {
            //   return ls.get('flow')
            // }
            // if (isNotLoggedIn) {
            //   console.log('Not Logged In - Creating Guest User')
            //   await this.registerGuestUser().then(this.afterRegisterUser)
            // }
            yield when(() => isNotLoggedIn, () => this.registerGuestUser()
            /**
             * @see https://jira.skava.net/browse/SECTEM-5129
             */
            // .then(this.afterRegisterUser)
            );
            // @todo - why is thi not being done?
            // await sessionApis.fetchUserProfile()
            /**
             * @todo ========= needs to heavily cache here
             *
             * @note, async will make it blocking, promise.all may be best
             */
            yield when(() => this.isGuestUser || this.isRegisteredUser, () => {
                return sessionApis.fetchList().then(toSyncListResponse);
                // .then(this.omniStore.loadLists)
            });
            yield when(() => isString(listContainer.favoriteListId) === true, () => {
                return (sessionApis
                    .fetchListItems(listContainer.favoriteListId)
                    .then(toFavoritesResponse)
                    // .then(this.omniStore.loadFavorites)
                    .catch(this.handleError));
            });
            yield when(() => isString(listContainer.saveForLaterListId) === true, () => {
                return (sessionApis
                    .fetchListItems(listContainer.saveForLaterListId)
                    .then(toSaveForLaterResponse)
                    // .then(this.omniStore.loadSaveForLater)
                    .catch(this.handleError));
            });
            // @michael
            // @todo
            // 1. then need to connect this with fixture/graphql
            // 2. and set events to update
            // 3. these could also be set individually per store
            //    or we can use graphql.readQuery but here
            //    we don't have graphql for these calls so
            //    we can also connect oneStorage to check graphql cache
            //      through a single interface (@example cache.has checks graphql)
            //
            // localStorage.set('last_flow', now)
            // localStorage.set('flow', {
            //   viewBag,
            //   storeCredit,
            //   favoritesList,
            // })
        });
        /**
         * @see https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
         * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
         * @see https://github.com/aretecode/awesome-deopt
         * ^ regarding try catch issues
         */
        this.flow = () => __awaiter(this, void 0, void 0, function* () {
            try {
                yield this._flow();
            }
            catch (error) {
                console.error(error);
                throw new Error('API Failed');
            }
        });
    }
    get guestUserCookie() {
        console.log('[COOKIE_CONFIG]', cookieConfig);
        return cookies.get(cookieConfig.guest);
    }
    get hasGuestUserCookie() {
        return cookies.has(cookieConfig.guest);
    }
    get hasOrchestartionGuestUserCookie() {
        return cookies.has(cookieConfig.orchestarionGuest);
    }
    get isGuestUser() {
        return this.hasGuestUserCookie;
    }
    get isOrchestarionGuestUser() {
        return this.hasOrchestartionGuestUserCookie;
    }
    get isRegisteredUser() {
        return this.hasUserCookie;
    }
    get hasUserCookie() {
        return cookies.has(cookieConfig.registered);
    }
    get userCookie() {
        return cookies.get(cookieConfig.registered);
    }
    // or could force only via props?
    get userName() {
        // @todo @userContainer
        // return this.userCookie || this.omniStore.userStore.userName
        return this.userCookie || userContainer.userName;
    }
    get isBuyerAdminUser() {
        return cookies.get(cookieConfig.buyerAdminNamespace) === 'ROLE_ACCOUNT_BUYER_ADMIN';
    }
    get isBuyerUser() {
        return cookies.get(cookieConfig.buyerAdminNamespace) === 'ROLE_BUYER';
    }
    /**
     * @desc much better perf to bind early
     * @see https://mobx.js.org/best/react-performance.html#bind-functions-early
     */
    handleError(error) {
        console.error(error);
    }
    navigateToLoginSuccess(isFromTwitter) {
        if (this.isRegisteredUser || isFromTwitter) {
            if (this.navigateBackTo) {
                oneRouter.update(this.navigateBackTo);
                this.navigateBackTo = '';
            }
            // normal login and register success flow
            else if (this.isBuyerAdminUser) {
                oneRouter.update(pathParams.myaccountDashboard);
            }
            else if (oneRouter.get('pathname') !== '/checkout') {
                oneRouter.update(pathParams.myaccountLanding);
            }
        }
    }
}
SessionContainer.debugName = 'Session';
const sessionContainer = new SessionContainer();
export default sessionContainer;
export { sessionContainer, SessionContainer, sessionApis, mapCookiesOnResponse, checkIsSessionExpired, checkSessionExpiredOnMyAccount, };
//# sourceMappingURL=container.js.map