diff --git a/core/store/lib/search.js b/core/store/lib/search.js index 0013bced5c..e88b61899d 100644 --- a/core/store/lib/search.js +++ b/core/store/lib/search.js @@ -4,6 +4,7 @@ import { currentStoreView } from './multistore' import hash from 'object-hash' import config from 'config' import fetch from 'isomorphic-fetch' +import rootStore from '../' export function isOnline () { if (typeof navigator !== 'undefined') { @@ -45,25 +46,15 @@ function search (elasticQuery) { url = url + '/' + encodeURIComponent(elasticQuery.index) + '/' + encodeURIComponent(elasticQuery.type) + '/_search' url = url + '?' + buildURLQuery(httpQuery) - return new Promise((resolve, reject) => { - global.$VS.db.usersCollection.getItem('current-user', (err, userData) => { - if (err) console.log(err) - if (userData && userData.groupToken) { - elasticQuery.body.groupToken = userData.groupToken - } - fetch(url, { - method: 'POST', - mode: 'cors', - headers: { - 'Accept': 'application/json', - 'Content-Type': 'application/json' - }, - body: JSON.stringify(elasticQuery.body) - }).then(resp => { - resolve(resp.json()) - }) - }) - }) + + return fetch(url, { method: 'POST', + mode: 'cors', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json' + }, + body: JSON.stringify(elasticQuery.body) + }).then(resp => { return resp.json() }) } /** * Helper function to handle ElasticSearch Results @@ -102,7 +93,7 @@ function _handleEsResult (resp, start = 0, size = 50) { * @param {Int} size page size * @return {Promise} */ -export function quickSearchByQuery ({ query, start = 0, size = 50, entityType = 'product', sort = '', index = null, excludeFields = null, includeFields = null, skipCache = false }) { +export function quickSearchByQuery ({ query, start = 0, size = 50, entityType = 'product', sort = '', index = null, excludeFields = null, includeFields = null }) { size = parseInt(size) if (size <= 0) size = 50 if (start < 0) start = 0 @@ -120,41 +111,55 @@ export function quickSearchByQuery ({ query, start = 0, size = 50, entityType = if (excludeFields) esQuery._sourceExclude = excludeFields if (includeFields) esQuery._sourceInclude = includeFields + + if (config.usePriceTiers && (entityType === 'product') && rootStore.state.user.groupId) { + esQuery.body.groupId = rootStore.state.user.groupId + } + const cache = global.$VS.db.elasticCacheCollection // switch to appcache? - const cacheKey = hash(esQuery) let servedFromCache = false + const cacheKey = hash(esQuery) const benchmarkTime = new Date() - if (!skipCache) { - cache.getItem(cacheKey, (err, res) => { - if (err) console.log(err) - if (res !== null) { - res.cache = true - res.noresults = false - res.offline = !isOnline() // TODO: refactor it to checking ES heartbit - resolve(res) - console.debug('Result from cache for ' + cacheKey + ' (' + entityType + '), ms=' + (new Date().getTime() - benchmarkTime.getTime())) - servedFromCache = true - } else { - if (!isOnline()) { - console.debug('No results and offline ' + cacheKey + ' (' + entityType + '), ms=' + (new Date().getTime() - benchmarkTime.getTime())) - res = { - items: [], - total: 0, - start: 0, - perPage: 0, - aggregations: {}, - offline: true, - cache: true, - noresults: true - } - servedFromCache = true - resolve(res) + + cache.getItem(cacheKey, (err, res) => { + if (err) console.log(err) + if (res !== null) { + res.cache = true + res.noresults = false + res.offline = !isOnline() // TODO: refactor it to checking ES heartbit + resolve(res) + console.debug('Result from cache for ' + cacheKey + ' (' + entityType + '), ms=' + (new Date().getTime() - benchmarkTime.getTime())) + servedFromCache = true + } else { + if (!isOnline()) { + console.debug('No results and offline ' + cacheKey + ' (' + entityType + '), ms=' + (new Date().getTime() - benchmarkTime.getTime())) + res = { + items: [], + total: 0, + start: 0, + perPage: 0, + aggregations: {}, + offline: true, + cache: true, + noresults: true } + servedFromCache = true + resolve(res) } - }).catch((err) => { - console.error('Cannot read cache for ' + cacheKey + ', ' + err) - }) + } + }).catch((err) => { + console.error('Cannot read cache for ' + cacheKey + ', ' + err) + }) + + /* use only for cache */ + if (esQuery.body.groupId) { + delete esQuery.body.groupId } + + if (config.usePriceTiers && rootStore.state.user.groupToken) { + esQuery.body.groupToken = rootStore.state.user.groupToken + } + search(esQuery).then((resp) => { // we're always trying to populate cache - when online const res = _handleEsResult(resp, start, size) cache.setItem(cacheKey, res).catch((err) => { console.error('Cannot store cache for ' + cacheKey + ', ' + err) }) diff --git a/core/store/modules/product/actions.ts b/core/store/modules/product/actions.ts index 83940b9731..3f28aa495b 100644 --- a/core/store/modules/product/actions.ts +++ b/core/store/modules/product/actions.ts @@ -236,7 +236,7 @@ const actions: ActionTree = { * @param {Int} size page size * @return {Promise} */ - list (context, { query, start = 0, size = 50, entityType = 'product', sort = '', cacheByKey = 'sku', prefetchGroupProducts = true, updateState = false, meta = {}, excludeFields = null, includeFields = null, configuration = null, append = false, skipCache = false }) { + list (context, { query, start = 0, size = 50, entityType = 'product', sort = '', cacheByKey = 'sku', prefetchGroupProducts = true, updateState = false, meta = {}, excludeFields = null, includeFields = null, configuration = null, append = false }) { let isCacheable = (includeFields === null && excludeFields === null) if (isCacheable) { console.debug('Entity cache is enabled for productList') @@ -252,7 +252,7 @@ const actions: ActionTree = { includeFields = config.entities.product.includeFields } } - return quickSearchByQuery({ query, start, size, entityType, sort, excludeFields, includeFields, skipCache }).then((resp) => { + return quickSearchByQuery({ query, start, size, entityType, sort, excludeFields, includeFields }).then((resp) => { if (resp.items && resp.items.length) { // preconfigure products; eg: after filters for (let product of resp.items) { product.errors = {} // this is an object to store validation result for custom options and others @@ -384,8 +384,7 @@ const actions: ActionTree = { .query('match', key, options[key]) .build(), prefetchGroupProducts: false, - updateState: false, - skipCache: skipCache + updateState: false }).then((res) => { if (res && res.items && res.items.length) { let prd = res.items[0] diff --git a/core/store/modules/user/actions.ts b/core/store/modules/user/actions.ts index 286a77006d..7e6c11debc 100644 --- a/core/store/modules/user/actions.ts +++ b/core/store/modules/user/actions.ts @@ -25,6 +25,19 @@ const actions: ActionTree = { if (res) { context.commit(types.USER_TOKEN_CHANGED, { newToken: res }) EventBus.$emit('session-after-authorized') + + if (config.usePriceTiers) { + global.$VS.db.usersCollection.getItem('current-user', (err, userData) => { + if (err) { + console.error(err) + return + } + + if (userData) { + context.dispatch('setUserGroup', userData) + } + }) + } } else { EventBus.$emit('session-after-nonauthorized') } @@ -144,7 +157,25 @@ const actions: ActionTree = { }) }) }, + /** + * Update user groupToken and groupId in state + * @param context + * @param userData + */ + setUserGroup(context, userData) { + if (config.usePriceTiers) { + if (userData.groupToken) { + context.commit(types.USER_GROUP_TOKEN_CHANGED, userData.groupToken) + } + if (userData.group_id) { + context.commit(types.USER_GROUP_CHANGED, userData.group_id) + } + } else { + context.commit(types.USER_GROUP_TOKEN_CHANGED, '') + context.commit(types.USER_GROUP_CHANGED, null) + } + }, /** * Load current user profile */ @@ -166,6 +197,7 @@ const actions: ActionTree = { if (res) { context.commit(types.USER_INFO_LOADED, res) + context.dispatch('setUserGroup', res) EventBus.$emit('user-after-loggedin', res) resolve(res) @@ -188,6 +220,7 @@ const actions: ActionTree = { .then((resp) => { if (resp.resultCode === 200) { context.commit(types.USER_INFO_LOADED, resp.result) // this also stores the current user to localForage + context.dispatch('setUserGroup', resp.result) } if (!resolvedFromCache && resp.resultCode === 200) { EventBus.$emit('user-after-loggedin', resp.result) @@ -273,11 +306,9 @@ const actions: ActionTree = { }) }, clearCurrentUser (context) { - global.$VS.db.usersCollection.getItem('current-user', (err) => { - if (err) console.log(err) - + context.commit(types.USER_GROUP_TOKEN_CHANGED, '') + context.commit(types.USER_GROUP_CHANGED, null) context.commit(types.USER_INFO_LOADED, null) - }) }, /** * Logout user diff --git a/core/store/modules/user/index.ts b/core/store/modules/user/index.ts index a6a05877ee..a571c8f407 100644 --- a/core/store/modules/user/index.ts +++ b/core/store/modules/user/index.ts @@ -77,6 +77,8 @@ const user: Module = { state: { token: '', refreshToken: '', + groupToken: '', + groupId: null, current: null, current_storecode: '', session_started: new Date(), diff --git a/core/store/modules/user/mutations.ts b/core/store/modules/user/mutations.ts index 981cdfe13c..3e2b69f63b 100644 --- a/core/store/modules/user/mutations.ts +++ b/core/store/modules/user/mutations.ts @@ -13,6 +13,12 @@ const mutations: MutationTree = { [types.USER_START_SESSION] (state) { state.session_started = new Date() }, + [types.USER_GROUP_TOKEN_CHANGED] (state, token) { + state.groupToken = token + }, + [types.USER_GROUP_CHANGED] (state, groupId) { + state.groupId = groupId + }, [types.USER_INFO_LOADED] (state, currentUser) { state.current = currentUser }, diff --git a/core/store/modules/user/types/UserState.ts b/core/store/modules/user/types/UserState.ts index de68dae27b..c988370270 100644 --- a/core/store/modules/user/types/UserState.ts +++ b/core/store/modules/user/types/UserState.ts @@ -1,6 +1,8 @@ export default interface UserState { token: string, refreshToken: string, + groupToken: string, + groupId: null, current: { email: string } | null, diff --git a/core/store/mutation-types.js b/core/store/mutation-types.js index c5d616a00d..2c7a898ccd 100644 --- a/core/store/mutation-types.js +++ b/core/store/mutation-types.js @@ -64,6 +64,8 @@ export const USER_ORDERS_HISTORY_LOADED = SN_USER + '/ORDERS_HISTORY_LOADED' export const USER_START_SESSION = SN_USER + '/START_SESSION' export const USER_END_SESSION = SN_USER + '/END_SESSION' export const USER_UPDATE_PREFERENCES = SN_USER + '/UPDATE_PREFERENCES' +export const USER_GROUP_TOKEN_CHANGED = SN_USER + '/GROUP_TOKEN_CHANGED' +export const USER_GROUP_CHANGED = SN_USER + 'GROUP_ID_CHANGED' export const SN_SYNC = 'sync' export const SYNC_ADD_TASK = SN_SYNC + '/ADD_TASK' diff --git a/src/themes/default/components/core/blocks/Product/Related.vue b/src/themes/default/components/core/blocks/Product/Related.vue index c44a894631..d078499a0e 100644 --- a/src/themes/default/components/core/blocks/Product/Related.vue +++ b/src/themes/default/components/core/blocks/Product/Related.vue @@ -41,6 +41,17 @@ export default { }, created () { this.$bus.$on('product-after-load', this.refreshList) + + if (config.usePriceTiers) { + this.$bus.$on('user-after-loggedin', this.refreshList) + this.$bus.$on('user-after-logout', this.refreshList) + } + }, + beforeDestroy () { + if (config.usePriceTiers) { + this.$bus.$off('user-after-loggedin', this.refreshList) + this.$bus.$off('user-after-logout', this.refreshList) + } }, destroyed () { this.$bus.$off('product-after-load', this.refreshList)