Merge pull request 'feat(darkMode): current darkMode value is now saved in vn.userConfig.darkMode' (#12) from 3904-user_dark_mode into dev
gitea/salix-front/pipeline/head This commit looks good Details

Reviewed-on: #12
This commit is contained in:
Carlos Jimenez Ruiz 2022-04-20 14:28:20 +00:00
commit 25244272fd
12 changed files with 184 additions and 119 deletions

View File

@ -1,8 +1,10 @@
<script setup> <script setup>
import { useI18n } from 'vue-i18n';
import { useState } from 'src/composables/useState'; import { useState } from 'src/composables/useState';
import { useSession } from 'src/composables/useSession'; import { useSession } from 'src/composables/useSession';
import UserPanel from 'src/components/UserPanel.vue'; import UserPanel from 'src/components/UserPanel.vue';
const { t } = useI18n();
const session = useSession(); const session = useSession();
const state = useState(); const state = useState();
const user = state.getUser(); const user = state.getUser();
@ -16,12 +18,19 @@ function onToggleDrawer() {
<template> <template>
<q-header class="bg-dark" color="white" elevated bordered> <q-header class="bg-dark" color="white" elevated bordered>
<q-toolbar class="q-py-sm q-px-md"> <q-toolbar class="q-py-sm q-px-md">
<q-btn flat @click="onToggleDrawer()" round dense icon="menu" /> <q-btn flat @click="onToggleDrawer()" round dense icon="menu">
<q-tooltip bottom anchor="bottom right">
{{ t('globals.collapseMenu') }}
</q-tooltip>
</q-btn>
<router-link to="/"> <router-link to="/">
<q-btn flat round class="q-ml-xs" v-if="$q.screen.gt.xs"> <q-btn flat round class="q-ml-xs" v-if="$q.screen.gt.xs">
<q-avatar square size="md"> <q-avatar square size="md">
<q-img src="~/assets/logo_icon.svg" alt="Logo" /> <q-img src="~/assets/logo_icon.svg" alt="Logo" />
</q-avatar> </q-avatar>
<q-tooltip bottom>
{{ t('globals.backToDashboard') }}
</q-tooltip>
</q-btn> </q-btn>
</router-link> </router-link>
<q-toolbar-title shrink class="text-weight-bold">Salix</q-toolbar-title> <q-toolbar-title shrink class="text-weight-bold">Salix</q-toolbar-title>
@ -40,16 +49,23 @@ function onToggleDrawer() {
</q-list> </q-list>
</q-menu> </q-menu>
</q-btn> </q-btn>
<q-btn v-if="$q.screen.gt.xs" dense flat round size="md" icon="notifications" /> <q-btn v-if="$q.screen.gt.xs" dense flat round size="md" icon="notifications">
<q-tooltip bottom>
{{ t('globals.notifications') }}
</q-tooltip>
</q-btn>
<q-btn dense flat no-wrap> <q-btn dense flat no-wrap>
<q-avatar size="lg"> <q-avatar size="lg">
<q-img <q-img
:src="`/api/Images/user/160x160/${user.id}/download?access_token=${token}`" :src="`/api/Images/user/160x160/${user.id}/download?access_token=${token}`"
spinner-color="white" spinner-color="white"
/> >
</q-img>
</q-avatar> </q-avatar>
<q-tooltip>Account</q-tooltip>
<q-icon name="arrow_drop_down" size="s" /> <q-icon name="arrow_drop_down" size="s" />
<q-tooltip bottom>
{{ t('globals.userPanel') }}
</q-tooltip>
<UserPanel /> <UserPanel />
</q-btn> </q-btn>
</div> </div>

View File

@ -3,6 +3,7 @@ import { onMounted, computed } from 'vue';
import { Dark, useQuasar } from 'quasar'; import { Dark, useQuasar } from 'quasar';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import axios from 'axios';
import { useState } from 'src/composables/useState'; import { useState } from 'src/composables/useState';
import { useSession } from 'src/composables/useSession'; import { useSession } from 'src/composables/useSession';
@ -29,10 +30,11 @@ const token = session.getToken();
onMounted(async () => { onMounted(async () => {
try { try {
const stateRoles = state.getRoles().value const stateRoles = state.getRoles().value;
if (stateRoles.length === 0) { if (stateRoles.length === 0) {
await role.fetch(); await role.fetch();
} }
updatePreferences();
} catch (error) { } catch (error) {
quasar.notify({ quasar.notify({
message: t('errors.statusUnauthorized'), message: t('errors.statusUnauthorized'),
@ -42,39 +44,63 @@ onMounted(async () => {
} }
}); });
function updatePreferences() {
if (user.value.darkMode) {
darkMode.value = user.value.darkMode;
}
if (user.value.lang) {
locale.value = user.value.lang;
}
}
async function saveDarkMode(value) {
const query = `/api/UserConfigs/${user.value.id}`;
await axios.patch(query, {
darkMode: value,
});
user.value.darkMode = value;
}
async function saveLanguage(value) {
const query = `/api/Accounts/${user.value.id}`;
await axios.patch(query, {
lang: value,
});
}
function logout() { function logout() {
session.destroy(); session.destroy();
router.push('/login'); router.push('/login');
} }
</script> </script>
<template> <template>
<q-menu> <q-menu anchor="bottom left">
<div class="row no-wrap q-pa-md"> <div class="row no-wrap q-pa-md">
<div class="column"> <div class="column panel">
<div class="text-h6 q-mb-md">{{ t('components.userPanel.settings') }}</div> <div class="text-h6 q-mb-md">{{ t('components.userPanel.settings') }}</div>
<q-toggle <q-toggle
v-model="locale"
@update:model-value="saveLanguage"
:label="t(`globals.lang['${locale}']`)" :label="t(`globals.lang['${locale}']`)"
icon="public" icon="public"
color="orange" color="orange"
false-value="es" false-value="es"
true-value="en" true-value="en"
v-model="locale"
/> />
<q-toggle <q-toggle
v-model="darkMode" v-model="darkMode"
@update:model-value="saveDarkMode"
:label="t(`globals.theme`)"
checked-icon="dark_mode" checked-icon="dark_mode"
color="orange" color="orange"
unchecked-icon="light_mode" unchecked-icon="light_mode"
/> />
<q-btn color="orange" outline size="sm" label="Settings" icon="settings" />
</div> </div>
<q-separator vertical inset class="q-mx-lg" /> <q-separator vertical inset class="q-mx-lg" />
<div class="column items-center" style="min-width: 150px"> <div class="column items-center panel">
<q-avatar size="80px"> <q-avatar size="80px">
<q-img <q-img
:src="`/api/Images/user/160x160/${user.id}/download?access_token=${token}`" :src="`/api/Images/user/160x160/${user.id}/download?access_token=${token}`"
@ -90,7 +116,7 @@ function logout() {
<q-btn <q-btn
color="orange" color="orange"
flat flat
label="Log Out" :label="t('globals.logOut')"
size="sm" size="sm"
icon="logout" icon="logout"
@click="logout()" @click="logout()"
@ -100,3 +126,9 @@ function logout() {
</div> </div>
</q-menu> </q-menu>
</template> </template>
<style lang="scss" scoped>
.panel {
width: 150px;
}
</style>

View File

@ -10,24 +10,34 @@ jest.mock('vue-router', () => ({
}), }),
})); }));
describe('UserPanel', () => { describe('UserPanel onMounted()', () => {
describe('onMounted', () => { it('should define the user into state', async () => {
it.only('should define the user into state', async () => {
const userMock = { const userMock = {
user: { user: {
id: 1, id: 1,
name: 'myName', name: 'myName',
nickname: 'myNickName' nickname: 'myNickName',
lang: 'en',
userConfig: {
darkMode: 'false'
}
}, },
roles: [] roles: []
} }
const expectedUserData = {
id: 1,
name: 'myName',
nickname: 'myNickName',
lang: 'en',
darkMode: 'false'
}
jest.spyOn(axios, 'get').mockResolvedValue({ data: userMock }); jest.spyOn(axios, 'get').mockResolvedValue({ data: userMock });
const { vm } = createWrapper(UserPanel); const { vm } = createWrapper(UserPanel);
await flushPromises() await flushPromises()
const expectedUser = expect.objectContaining(userMock.user) expect(vm.state.getUser().value).toEqual(expectedUserData);
expect(vm.state.getUser().value).toEqual(expectedUser);
}); });
it('should logout and notify the expected error', async () => { it('should logout and notify the expected error', async () => {
@ -43,5 +53,4 @@ describe('UserPanel', () => {
{ 'type': 'negative' } { 'type': 'negative' }
)); ));
}); });
});
}); });

View File

@ -19,10 +19,25 @@ describe('useRole', () => {
} }
} }
]; ];
const expectedUser = { id: 1 } const fetchedUser = {
id: 999,
name: `T'Challa`,
nickname: 'Black Panther',
lang: 'en',
userConfig: {
darkMode: false,
}
}
const expectedUser = {
id: 999,
name: `T'Challa`,
nickname: 'Black Panther',
lang: 'en',
darkMode: false,
}
const expectedRoles = ['salesPerson', 'admin'] const expectedRoles = ['salesPerson', 'admin']
jest.spyOn(axios, 'get').mockResolvedValue({ jest.spyOn(axios, 'get').mockResolvedValue({
data: { roles: rolesData, user: expectedUser } data: { roles: rolesData, user: fetchedUser }
}); });
jest.spyOn(role.state, 'setUser'); jest.spyOn(role.state, 'setUser');

View File

@ -36,11 +36,15 @@ describe('session', () => {
id: 999, id: 999,
name: `T'Challa`, name: `T'Challa`,
nickname: 'Black Panther', nickname: 'Black Panther',
lang: 'en',
darkMode: false,
} }
const expectedUser = { const expectedUser = {
id: 0, id: 0,
name: '', name: '',
nickname: '', nickname: '',
lang: '',
darkMode: null,
} }
let user = state.getUser(); let user = state.getUser();
@ -60,7 +64,15 @@ describe('session', () => {
}); });
describe('login', () => { describe('login', () => {
it('should fetch the user roles and then set token in the sessionStorage', async () => { const expectedUser = {
id: 999,
name: `T'Challa`,
nickname: 'Black Panther',
lang: 'en',
userConfig: {
darkMode: false,
}
}
const rolesData = [ const rolesData = [
{ {
role: { role: {
@ -73,7 +85,8 @@ describe('session', () => {
} }
} }
]; ];
const expectedUser = { id: 1 }
it('should fetch the user roles and then set token in the sessionStorage', async () => {
const expectedRoles = ['salesPerson', 'admin'] const expectedRoles = ['salesPerson', 'admin']
jest.spyOn(axios, 'get').mockResolvedValue({ jest.spyOn(axios, 'get').mockResolvedValue({
data: { roles: rolesData, user: expectedUser } data: { roles: rolesData, user: expectedUser }
@ -96,20 +109,6 @@ describe('session', () => {
}); });
it('should fetch the user roles and then set token in the localStorage', async () => { it('should fetch the user roles and then set token in the localStorage', async () => {
const rolesData = [
{
role: {
name: 'salesPerson'
}
},
{
role: {
name: 'admin'
}
}
];
const expectedUser = { id: 1 }
const expectedRoles = ['salesPerson', 'admin'] const expectedRoles = ['salesPerson', 'admin']
jest.spyOn(axios, 'get').mockResolvedValue({ jest.spyOn(axios, 'get').mockResolvedValue({
data: { roles: rolesData, user: expectedUser } data: { roles: rolesData, user: expectedUser }

View File

@ -8,7 +8,14 @@ export function useRole() {
const { data } = await axios.get('/api/accounts/acl'); const { data } = await axios.get('/api/accounts/acl');
const roles = data.roles.map(userRoles => userRoles.role.name); const roles = data.roles.map(userRoles => userRoles.role.name);
state.setUser(data.user); const userData = {
id: data.user.id,
name: data.user.name,
nickname: data.user.nickname,
lang: data.user.lang || 'es',
darkMode: data.user.userConfig.darkMode,
}
state.setUser(userData);
state.setRoles(roles); state.setRoles(roles);
} }

View File

@ -30,6 +30,8 @@ export function useSession() {
id: 0, id: 0,
name: '', name: '',
nickname: '', nickname: '',
lang: '',
darkMode: null,
}); });
} }

View File

@ -4,6 +4,8 @@ const user = ref({
id: 0, id: 0,
name: '', name: '',
nickname: '', nickname: '',
lang: '',
darkMode: null,
}); });
const roles = ref([]); const roles = ref([]);
@ -17,6 +19,8 @@ export function useState() {
id: user.value.id, id: user.value.id,
name: user.value.name, name: user.value.name,
nickname: user.value.nickname, nickname: user.value.nickname,
lang: user.value.lang,
darkMode: user.value.darkMode,
}; };
}); });
} }
@ -26,6 +30,8 @@ export function useState() {
id: data.id, id: data.id,
name: data.name, name: data.name,
nickname: data.nickname, nickname: data.nickname,
lang: data.lang,
darkMode: data.darkMode,
}; };
} }

View File

@ -4,6 +4,12 @@ export default {
es: 'Spanish', es: 'Spanish',
en: 'English', en: 'English',
}, },
collapseMenu: 'Collapse left menu',
backToDashboard: 'Return to dashboard',
notifications: 'Notifications',
userPanel: 'User panel',
theme: 'Theme',
logOut: 'Log out',
}, },
errors: { errors: {
statusUnauthorized: 'Access denied', statusUnauthorized: 'Access denied',

View File

@ -4,6 +4,12 @@ export default {
es: 'Español', es: 'Español',
en: 'Inglés', en: 'Inglés',
}, },
collapseMenu: 'Contraer menú lateral',
backToDashboard: 'Volver al tablón',
notifications: 'Notificaciones',
userPanel: 'Panel de usuario',
theme: 'Tema',
logOut: 'Cerrar sesión',
}, },
errors: { errors: {
statusUnauthorized: 'Acceso denegado', statusUnauthorized: 'Acceso denegado',

View File

@ -1,6 +1,6 @@
<script setup> <script setup>
import { computed, ref } from 'vue'; import { ref } from 'vue';
import { Dark, useQuasar } from 'quasar'; import { useQuasar } from 'quasar';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import axios from 'axios'; import axios from 'axios';
@ -10,21 +10,12 @@ import { useSession } from 'src/composables/useSession';
const quasar = useQuasar(); const quasar = useQuasar();
const session = useSession(); const session = useSession();
const router = useRouter(); const router = useRouter();
const { t, locale } = useI18n(); const { t } = useI18n();
const username = ref(''); const username = ref('');
const password = ref(''); const password = ref('');
const keepLogin = ref(true); const keepLogin = ref(true);
const darkMode = computed({
get() {
return Dark.isActive;
},
set(value) {
Dark.set(value);
},
});
async function onSubmit() { async function onSubmit() {
try { try {
const { data } = await axios.post('/api/accounts/login', { const { data } = await axios.post('/api/accounts/login', {
@ -66,36 +57,11 @@ async function onSubmit() {
<template> <template>
<q-layout> <q-layout>
<q-header class="transparent">
<q-toolbar>
<q-space></q-space>
<q-toggle
:label="t(`globals.lang['${locale}']`)"
icon="public"
color="orange"
false-value="es"
true-value="en"
v-model="locale"
/>
<q-toggle
v-model="darkMode"
checked-icon="dark_mode"
color="orange"
unchecked-icon="light_mode"
/>
</q-toolbar>
</q-header>
<q-page-container> <q-page-container>
<q-page> <q-page>
<div id="login"> <div id="login">
<q-card class="login q-pa-xl"> <q-card class="login q-pa-xl">
<q-img <q-img src="~/assets/logo.svg" alt="Logo" fit="contain" :ratio="16 / 9" class="q-mb-md" />
src="~/assets/logo.svg"
alt="Logo"
fit="contain"
:ratio="16 / 9"
class="q-mb-md"
/>
<q-form @submit="onSubmit" class="q-gutter-md"> <q-form @submit="onSubmit" class="q-gutter-md">
<q-input <q-input
filled filled
@ -103,9 +69,7 @@ async function onSubmit() {
v-model="username" v-model="username"
:label="t('login.username')" :label="t('login.username')"
lazy-rules lazy-rules
:rules="[ :rules="[(val) => (val && val.length > 0) || 'Please type something']"
(val) => (val && val.length > 0) || 'Please type something',
]"
/> />
<q-input <q-input
filled filled
@ -114,15 +78,9 @@ async function onSubmit() {
v-model="password" v-model="password"
:label="t('login.password')" :label="t('login.password')"
lazy-rules lazy-rules
:rules="[ :rules="[(val) => (val && val.length > 0) || 'Please type something']"
(val) => (val && val.length > 0) || 'Please type something',
]"
/>
<q-toggle
v-model="keepLogin"
:label="t('login.keepLogin')"
color="orange"
/> />
<q-toggle v-model="keepLogin" :label="t('login.keepLogin')" color="orange" />
<div> <div>
<q-btn :label="t('login.submit')" type="submit" color="orange" /> <q-btn :label="t('login.submit')" type="submit" color="orange" />

View File

@ -18,8 +18,17 @@ describe('Login', () => {
}); });
it('should successfully set the token into session', async () => { it('should successfully set the token into session', async () => {
const expectedUser = {
id: 999,
name: `T'Challa`,
nickname: 'Black Panther',
lang: 'en',
userConfig: {
darkMode: false,
}
}
jest.spyOn(axios, 'post').mockResolvedValue({ data: { token: 'token' } }); jest.spyOn(axios, 'post').mockResolvedValue({ data: { token: 'token' } });
jest.spyOn(axios, 'get').mockResolvedValue({ data: { roles: [], user: { id: 1 } } }); jest.spyOn(axios, 'get').mockResolvedValue({ data: { roles: [], user: expectedUser } });
jest.spyOn(vm.quasar, 'notify') jest.spyOn(vm.quasar, 'notify')
expect(vm.session.getToken()).toEqual(''); expect(vm.session.getToken()).toEqual('');