Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Price tiers. #1625

Merged
merged 1 commit into from
Aug 23, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 54 additions & 49 deletions core/store/lib/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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) })
Expand Down
7 changes: 3 additions & 4 deletions core/store/modules/product/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ const actions: ActionTree<ProductState, RootState> = {
* @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')
Expand All @@ -252,7 +252,7 @@ const actions: ActionTree<ProductState, RootState> = {
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
Expand Down Expand Up @@ -384,8 +384,7 @@ const actions: ActionTree<ProductState, RootState> = {
.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]
Expand Down
39 changes: 35 additions & 4 deletions core/store/modules/user/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,19 @@ const actions: ActionTree<UserState, RootState> = {
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')
}
Expand Down Expand Up @@ -144,7 +157,25 @@ const actions: ActionTree<UserState, RootState> = {
})
})
},
/**
* 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
*/
Expand All @@ -166,6 +197,7 @@ const actions: ActionTree<UserState, RootState> = {

if (res) {
context.commit(types.USER_INFO_LOADED, res)
context.dispatch('setUserGroup', res)
EventBus.$emit('user-after-loggedin', res)

resolve(res)
Expand All @@ -188,6 +220,7 @@ const actions: ActionTree<UserState, RootState> = {
.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)
Expand Down Expand Up @@ -273,11 +306,9 @@ const actions: ActionTree<UserState, RootState> = {
})
},
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
Expand Down
2 changes: 2 additions & 0 deletions core/store/modules/user/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ const user: Module<UserState, RootState> = {
state: {
token: '',
refreshToken: '',
groupToken: '',
groupId: null,
current: null,
current_storecode: '',
session_started: new Date(),
Expand Down
6 changes: 6 additions & 0 deletions core/store/modules/user/mutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ const mutations: MutationTree<UserState> = {
[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
},
Expand Down
2 changes: 2 additions & 0 deletions core/store/modules/user/types/UserState.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
export default interface UserState {
token: string,
refreshToken: string,
groupToken: string,
groupId: null,
current: {
email: string
} | null,
Expand Down
2 changes: 2 additions & 0 deletions core/store/mutation-types.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
11 changes: 11 additions & 0 deletions src/themes/default/components/core/blocks/Product/Related.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down