import ngModule from '../module'; /** * Saves and loads the application configuration. */ export default class Config { constructor($http, vnApp, $translate, $window) { Object.assign(this, { $http, vnApp, $translate, storage: $window.localStorage, user: {}, local: {} }); this.params = [ 'warehouseFk', 'companyFk', 'bankFk' ]; } initialize() { for (let param of this.params) this.local[param] = this.getItem(param); return this.$http.get('UserConfigs/getUserConfig') .then(res => { for (let param of this.params) this.user[param] = res.data[param]; }) .finally(() => this.mergeParams()); } mergeParams() { for (let param of this.params) { let local = this.local[param]; this[param] = local != null && local != '' ? local : this.user[param]; } } setUser(param, value) { this.user[param] = value; this.mergeParams(); let params = {[param]: value}; return this.$http.post('UserConfigs/setUserConfig', params) .then(() => this.showSaved()); } setLocal(param, value) { this.setItem(param, value); this.local[param] = value; this.mergeParams(); this.showSaved(); } showSaved() { this.vnApp.showSuccess(this.$translate.instant('Data saved!')); } getItem(key) { let value = this.storage[key]; return value !== undefined ? JSON.parse(value) : value; } setItem(key, value) { if (value == null) this.storage.removeItem(key); else this.storage[key] = JSON.stringify(value); } } Config.$inject = ['$http', 'vnApp', '$translate', '$window']; ngModule.service('vnConfig', Config);