move_users #5

Merged
vbuglov merged 4 commits from move_users into master 2024-04-03 09:28:15 +00:00
50 changed files with 3798 additions and 776 deletions
Showing only changes of commit 28c13c00ec - Show all commits

View File

@ -1,27 +1,43 @@
const devUsersList = [
{
"id": 1,
"first_name": "Leanne",
"last_name": "Graham",
"serviceId": [1, 3],
"firstName": "Leanne 1",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
"is_active": true
},
{
"id": 2,
"first_name": "Leanne",
"last_name": "Graham",
"serviceId": [1],
"firstName": "Leanne 2",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
"is_active": true
},
{
"id": 3,
"first_name": "Leanne",
"last_name": "Graham",
"serviceId": [2, 3],
"firstName": "Leanne 3",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 4,
"serviceId": [3],
"firstName": "Leanne 4",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 5,
"serviceId": [4, 5],
"firstName": "Leanne 5",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
"is_active": true
},
]

View File

@ -14,6 +14,16 @@ const adapter_config = {
last_name: "lastName",
email: "email",
role: "role",
service_id: "serviceId",
}
const server_config = {
id: "id",
firstName: "first_name",
lastName: "last_name",
email: "email",
role: "role",
serviceId: "service_id",
}
class Users {
@ -26,6 +36,7 @@ class Users {
constructor(apiAddr, params = {mode: 'prod'}) {
this.apiAddr = apiAddr
this.config = adapter_config
this.server_config = server_config
this.mode = params.mode
}
@ -52,7 +63,7 @@ class Users {
*/
async getUsersByServiceId(id, mode) {
if (mode === "dev") {
return devUsersList
return devUsersList.filter((user) => user.serviceId.includes(id))
}
let res = await get(`${this.apiAddr}/users/by_server/${id}`)
let updatedUsers = convertList(res.data, {config: this.config})
@ -65,7 +76,7 @@ class Users {
* @returns {Promise<Object>}
*/
async createUser(userData) {
const newUser = await post(`${this.apiAddr}/users`, userData)
const newUser = await post(`${this.apiAddr}/users`, convertObject(userData, {config: this.server_config}))
return convertObject(newUser, {config: this.config})
}
@ -77,7 +88,7 @@ class Users {
async updateUser(userData) {
const updatedUserData = {...userData}
delete updatedUserData.id
const newUser = await put(`${this.apiAddr}/users/${userData.id}`, updatedUserData)
const newUser = await put(`${this.apiAddr}/users/${userData.id}`, convertObject(updatedUserData, {config: this.server_config}))
return convertObject(newUser, {config: this.config})
}

View File

@ -2,15 +2,16 @@
import {mapGetters} from 'vuex'
export default {
name: 'AppPageHeader',
inject: ['serviceOfServices'],
props: {
serviceOfServices: {
type: Object,
default: () => {}
},
},
computed: {
...mapGetters('services', ['selectedService']),
},
methods: {
saveData: function () {
console.log('saveData')
return this.serviceOfServices.isSaveServices(true)
},
}
}
</script>
@ -25,17 +26,9 @@ export default {
<i class="ri-reply-line" />
На главную
</a>
<button
:class="`w-fit text-white font-medium rounded-full text-sm px-5 py-2.5 text-center me-2 mx-2 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800 ${!selectedSite ? 'bg-blue-200' : 'bg-blue-700 hover:bg-blue-800 focus:outline-none focus:ring-4 focus:ring-blue-300'}`"
:disabled="!selectedSite"
@click="saveData"
>
<i class="ri-save-line cursor-pointer" />
Сохранить изменения
</button>
</div>
<div class="flex">
Версия 0.0.1
Версия 0.9.0
</div>
</div>
</template>

View File

@ -1,9 +1,13 @@
<script>
import {mapGetters} from 'vuex'
export default {
name: 'NewSiteButton',
inject: ['serviceOfServices'],
name: 'NewServiceButton',
props: {
serviceOfServices: {
type: Object,
default: () => {}
},
name: {
default: "",
type: String
@ -17,8 +21,12 @@ export default {
type: Object
}
},
computed: {
...mapGetters('services', ['selectedService']),
},
methods: {
addNewServiceLayout() {
if (this.selectedService?.id === -1) return
this.serviceOfServices.addNewServiceLayout()
}
}

View File

@ -5,7 +5,11 @@ export default {
color: {
type: String,
default: 'purple'
}
},
disable: {
type: Boolean,
default: false
},
},
}
</script>
@ -13,7 +17,8 @@ export default {
<template>
<button
type="button"
:class="`rounded-md bg-${color}-700 hover:bg-fuchsia-700 transition-all cursor-pointer text-white p-2`"
:class="`rounded-md bg-${color}-700 hover:bg-fuchsia-700 transition-all text-white p-2 ${disable ? 'opacity-50 cursor-auto' : 'cursor-pointer'}`"
:disabled="disable"
>
<slot />
</button>

View File

@ -72,7 +72,15 @@ export default {
withTablefy: {
type: Boolean,
default: true
}
},
layout: {
type: String,
default: "fitDataFill"
},
responsiveLayout: {
type: String,
default: "collapse"
},
},
data() {
return {
@ -111,7 +119,8 @@ export default {
locale: "ru",
langs: localization(),
height: this.height || "250px",
responsiveLayout: "collapse",
layout: this.layout,
responsiveLayout: this.responsiveLayout,
placeholder: "Нет записей",
movableColumns: true,
autoResize: false,

View File

@ -291,9 +291,6 @@ const makedFiltering = (id, filterParams, selectedFilter, clearFilters) => {
el.onchange = (e) => {
if(e.target.value) {
selectOptions[0].removeAttribute('selected')
console.log('e', e)
console.log('selectFilters[0]', selectFilters[0])
console.log('selectOptions[0][0]', selectOptions[0])
selectedFilter(e.target.value)
} else {
clearFilters()
@ -305,7 +302,6 @@ const makedFiltering = (id, filterParams, selectedFilter, clearFilters) => {
buttonClearFilters.onclick = () => {
clearFilters()
selectOptions[0].setAttribute('selected', 'selected')
console.log('selectFilters[0]', selectFilters[0])
}
}
}

View File

@ -4,10 +4,15 @@ import {mapGetters} from 'vuex'
import Input from '@atoms/VInput.vue'
import Textarea from '@atoms/VTextarea.vue'
import VDoubleSwitch from '@atoms/VDoubleSwitch.vue'
import VButton from '@atoms/VButton.vue'
import { directive } from 'vue-tippy';
export default {
name: 'EditServiceCard',
components: {Input, Textarea, VDoubleSwitch},
directives: {
tippy: directive
},
components: {Input, Textarea, VDoubleSwitch, VButton},
props: {
id: {
default: -1,
@ -29,7 +34,10 @@ export default {
},
cancelEditService() {
this.serviceOfServices.cancelSelectedService(this.id)
}
},
saveData: function () {
return this.serviceOfServices.setIsSaveServices(true)
},
}
}
</script>
@ -43,16 +51,17 @@ export default {
secondColor="#2563eb"
firstTitle="Офлайн"
secondTitle="Онлайн"
:isCheck="selectedService.is_online"
:isCheck="selectedService?.is_online"
position="col"
labelClass="items-start pb-2"
switchClass="mt-1"
switchClass="switcher mt-1"
@switched="(e) => editData({key: 'is_online', value: e})"
/>
</div>
<Input
id="name"
name="name"
:value="selectedService.name"
:value="selectedService?.name"
inputClass="!w-[90%] py-2"
placeholder="Указать путь"
:onChange="editData"
@ -60,6 +69,8 @@ export default {
<div>
<i
v-tippy="{ content: 'закрыть сервис' }"
name="closeButton"
test-id="closeButton"
class="ri-close-line cursor-pointer"
@click="cancelEditService"
/>
@ -68,8 +79,9 @@ export default {
<div class="flex items-center mb-2 w-full">
<span class="mr-2 min-w-[80px]">Порт:</span>
<Input
id="port"
name="port"
:value="`${selectedService.port}`"
:value="`${selectedService?.port}`"
inputClass="py-2"
placeholder="Порт"
:onChange="editData"
@ -78,8 +90,9 @@ export default {
<div class="flex items-center mb-2 w-full">
<span class="mr-2 min-w-[80px]">IP proxy:</span>
<Input
id="proxyIp"
name="proxy_ip"
:value="selectedService.proxy_ip"
:value="selectedService?.proxy_ip"
inputClass="py-2"
placeholder="IP proxy"
:onChange="editData"
@ -88,18 +101,31 @@ export default {
<div class="flex items-center w-full mb-2">
<span class="mr-2 min-w-[80px]">IP устр-ва:</span>
<Input
id="deviceIp"
name="device_ip"
:value="selectedService.device_ip"
:value="selectedService?.device_ip"
inputClass="py-2"
placeholder="IP устройства"
:onChange="editData"
/>
</div>
<Textarea
id="description"
name="description"
:value="selectedService.description"
:value="selectedService?.description"
textareaClass="py-2"
placeholder="Описание..."
:onChange="editData"
/>
<div class="flex justify-end items-center w-full mt-2">
<VButton
:class="`w-fit text-white font-medium rounded-full text-sm px-5 py-1 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800 ${!selectedService ? 'bg-blue-200' : 'bg-blue-700 hover:bg-blue-800 focus:outline-none focus:ring-4 focus:ring-blue-300'}`"
:disable="!selectedService"
color="blue"
@click="saveData"
>
<i class="ri-save-line cursor-pointer" />
Сохранить
</VButton>
</div>
</template>

View File

@ -1,16 +1,28 @@
<!-- eslint-disable vue/prop-name-casing -->
<script>
import {mapActions, mapGetters} from 'vuex'
import {mapGetters} from 'vuex'
import EditCard from './EditServiceCard.vue'
import { directive } from 'vue-tippy';
export default {
name: 'ServiceCard',
directives: {
tippy: directive
},
components: {EditCard},
props: {
serviceOfServices: {
default: () => ({}),
type: Object
},
caseOfUsersInService: {
type: Object,
default: () => {}
},
uploadUsers: {
default: () => ([]),
type: Function
},
id: {
default: -1,
type: Number
@ -53,38 +65,27 @@ export default {
},
computed: {
...mapGetters('services', ["selectedService", "routes", 'isSaveData']),
__btnClass__() {
if (this.forcedBtnClass) return this.forcedBtnClass
return `${this.btnClass} cursor-pointer w-full bg-transparent hover:bg-primary text-primary font-semibold hover:text-white py-1 text-ssm px-4 border border-primary hover:border-transparent rounded-lg text-center transition_up`
}
},
watch: {
isSaveData: function (newVal) {
console.log('newVal', newVal)
// console.log('newVal', newVal)
if (newVal) {
this.saveServiceData()
}
},
isOnline: function (newVal) {
console.log('newVal', newVal)
// console.log('newVal', newVal)
this.status = this.setStatus(newVal)
}
},
mounted() {
},
methods: {
...mapActions('services', ["saveservice", "createNewservice", 'removeservice', 'updateRoutesWithApi', 'closeRoutesList']),
...mapActions('users', ["fetchUsersList"]),
toggle () {
this.open = !this.open
this.onToggle({isOpen: this.open})
},
setStatus (isOnline) {
return isOnline ? {title: 'enable', color: 'bg-green-700'} : {title: 'disable', color: 'bg-red-700'}
return this.status = isOnline ? {title: 'enable', color: 'bg-green-700'} : {title: 'disable', color: 'bg-red-700'}
},
editService (service) {
this.serviceOfServices.selectService(service)
// this.serviceOfServices.openRoutesList()
this.caseOfUsersInService.getUsersWithSelectService(service, 'dev')
},
saveServiceData () {
if (this.selectedService.id == -1) {
@ -93,7 +94,8 @@ export default {
port: this.selectedService.port,
device_ip: this.selectedService.device_ip,
proxy_ip: this.selectedService.proxy_ip,
description: this.selectedService.description
description: this.selectedService.description,
is_online: this.selectedService.is_online,
}
this.serviceOfServices.createNewService(data)
} else {
@ -136,12 +138,14 @@ export default {
class="absolute flex flex-row top-0 right-0 p-3 bg-white rounded-lg shadow-lg z-10"
>
<button
test-id="canelButton"
class="flex items-center text-xs text-white bg-blue-700 p-1 mr-2 rounded-lg shadow"
@click="deleteService(false)"
>
Отменить
</button>
<button
test-id="deletedButton"
class="flex items-center p-1 text-xs text-white bg-slate-700 rounded-lg shadow"
@click="serviceOfServices.removeService(id)"
>

View File

@ -13,6 +13,14 @@ export default {
type: Object,
default: () => {}
},
caseOfUsersInService: {
type: Object,
default: () => {}
},
uploadUsers: {
type: Function,
default: () => ([])
}
},
setup (props) {
const {serviceOfServices} = toRefs(props)
@ -44,6 +52,8 @@ export default {
:id="service.id"
:key="service.name"
:serviceOfServices="serviceOfServices"
:caseOfUsersInService="caseOfUsersInService"
:uploadUsers="uploadUsers"
:service="service"
:name="service.name"
:port="`${service.port}`"

View File

@ -8,7 +8,7 @@ export default {
<template>
<div
class="p-4 shadow-md rounded-md border border-slate-200"
class="w-fit p-4 shadow-md rounded-md border border-slate-200"
>
<slot />
</div>

View File

@ -6,7 +6,7 @@ export default {
</script>
<template>
<div class="flex items-center">
<div class="flex justify-between">
<h2 class="text-xl font-w-500 mr-6">
<slot name="title" />
</h2>

View File

@ -0,0 +1,377 @@
<script>
import {mapGetters} from 'vuex'
import Input from '@atoms/VInput.vue'
import VButton from "@atoms/VButton.vue"
import {generatePassword, isFullLengthPassword, equalPasswords, isRepeatPasswordEmpty} from './helpers/validation.js'
export default {
name: 'UserEditor',
components: {Input, VButton},
props: {
id: {
default: -1,
type: Number
},
serviceOfUsers: {
default: () => ({}),
type: Object
},
},
data() {
return {
repeatPassword: '',
showNewPassword: false,
newPasswordType: 'password',
showRepeatPassword: false,
repeatPasswordType: 'password',
errorPassword: null,
}
},
computed: {
...mapGetters('services', ["selectedService"]),
...mapGetters('users', ['selectedUser']),
},
mounted() {
},
methods: {
editData (params) {
if (params.key === 'password') {
this.errorPassword = isFullLengthPassword(params.value)
this.serviceOfUsers.editUserByService(params)
if (this.errorPassword) return
this.errorPassword = equalPasswords(params.value, this.repeatPassword)
this.serviceOfUsers.editUserByService(params)
if (this.errorPassword) return
}
if (params.key === 'repeat_password') {
this.repeatPassword = params.value
this.errorPassword = equalPasswords(this.selectedUser.password, this.repeatPassword)
if (this.errorPassword) return
}
this.serviceOfUsers.editUserByService(params)
},
saveUser() {
// console.log('Save user')
this.errorPassword = isRepeatPasswordEmpty(this.selectedUser.password, this.repeatPassword)
if (this.errorPassword) return
this.serviceOfUsers.saveUpdatedDataUser(this.selectedService.id)
this.serviceOfUsers.setStatusUser('inactive')
},
getPassword () {
const pass = generatePassword()
this.serviceOfUsers.editUserByService({key: 'password', value: pass})
this.errorPassword = equalPasswords(pass, this.repeatPassword)
},
togglePass () {
this.showNewPassword = !this.showNewPassword
this.newPasswordType = this.showNewPassword ? 'text' : 'password'
},
toggleRepeatPass () {
this.showRepeatPassword = !this.showRepeatPassword
this.repeatPasswordType = this.showRepeatPassword ? 'text' : 'password'
}
}
}
</script>
<template>
<div class="grid gap-6 mb-6 md:grid-cols-2">
<div class="hidden">
<div class="relative hidden">
<Input
id="id"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full py-1 pl-2 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 "
placeholder=""
name="id"
type="text"
value="1"
autocomplete="off"
:onChange="editData"
/>
</div>
</div><div class="">
<div class="relative ">
<label
for="lastName"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300 text-left "
>
Фамилия
</label>
<Input
id="lastName"
required=""
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full py-1 pl-2 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 "
name="lastName"
type="text"
:value="selectedUser?.lastName"
InputClass="py-2"
placeholder="Фамилия"
:onChange="editData"
/>
</div>
</div><div class="">
<div class="relative ">
<label
for="firstName"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300 text-left "
>
Имя
</label>
<Input
id="firstName"
required=""
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full py-1 pl-2 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 "
name="firstName"
type="text"
:value="selectedUser?.firstName"
autocomplete="off"
placeholder="Имя"
:onChange="editData"
/>
</div>
</div><div class="">
<div class="relative ">
<label
for="secondName"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300 text-left "
>
Отчество
</label>
<Input
id="secondName"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full py-1 pl-2 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 "
name="secondName"
type="text"
:value="selectedUser?.secondName"
autocomplete="off"
placeholder="Отчество"
:onChange="editData"
/>
</div>
</div><div class="">
<div class="relative ">
<label
for="email"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300 text-left "
>
Почта
</label>
<Input
id="email"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full py-1 pl-2 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 "
name="email"
type="mail"
:value="selectedUser?.email"
autocomplete="off"
placeholder="example@ya.ru"
:onChange="editData"
/>
</div>
</div><div class="">
<div class="relative ">
<label
for="login"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300 text-left "
>
Логин
</label>
<Input
id="login"
required=""
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full py-1 pl-2 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 "
name="login"
type="login"
:value="selectedUser?.login"
autocomplete="off"
placeholder="Логин"
:onChange="editData"
/>
</div>
</div><div class="">
<div class="relative ">
<label
for="position"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300 text-left "
>
Должность
</label>
<Input
id="position"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full py-1 pl-2 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 "
name="position"
type="text"
:value="selectedUser?.position"
autocomplete="off"
placeholder="Должность"
:onChange="editData"
/>
</div>
</div><div class="">
<div class="relative ">
<label
for="phone"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300 text-left "
>
Телефон
</label>
<Input
id="phone"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full py-1 pl-2 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 "
name="phone"
type="tel"
:value="selectedUser?.phone"
autocomplete="off"
placeholder="123-45-678"
:onChange="editData"
/>
</div>
</div><div class="">
<div class="relative ">
<label
for="company"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300 text-left "
>
Компания
</label>
<Input
id="company"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full py-1 pl-2 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 "
name="company"
type="text"
:value="selectedUser?.company"
autocomplete="off"
placeholder="Компания"
:onChange="editData"
/>
</div>
</div><div class="col-span-2">
<div class="relative col-span-2">
<label
for="notes"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300 text-left "
>
notes
</label>
<Input
id="notes"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full py-1 pl-2 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 "
name="notes"
type="text"
:value="selectedUser?.notes"
autocomplete="off"
placeholder="notes"
:onChange="editData"
/>
</div>
</div><div class="">
<div class="relative ">
<label
for="password"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300 text-left "
>
Новый пароль
</label>
<Input
id="password"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full py-1 pl-2 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 "
name="password"
:type="newPasswordType"
:value="selectedUser?.password"
autocomplete="off"
:placeholder="`${showNewPassword ? '' : '•••••••••'}`"
:onChange="editData"
/>
<i
id="showPass"
ref="showPass"
class="cursor-pointer transition-all text-slate-500 hover:text-slate-800 absolute ri-eye-line bottom-[4px] right-[7px]"
:class="{'hidden': showNewPassword, '': !showNewPassword}"
@click="togglePass"
/>
<i
id="hidePass"
ref="hidePass"
class="cursor-pointer transition-all text-slate-500 hover:text-slate-800 absolute ri-eye-off-line bottom-[4px] right-[7px]"
:class="{'hidden': !showNewPassword, '': showNewPassword}"
@click="togglePass"
/>
</div>
</div><div class="">
<div class="relative ">
<label
for="repeat_password"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300 text-left "
>
Повторить пароль
</label>
<Input
id="repeatPassword"
ref="repeatPassword"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full py-1 pl-2 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 "
name="repeat_password"
:type="repeatPasswordType"
:value="repeatPassword"
autocomplete="off"
:placeholder="`${showRepeatPassword ? '' : '•••••••••'}`"
:onChange="editData"
/>
<i
id="showRepeatPass"
ref="showRepeatPass"
class="cursor-pointer transition-all text-slate-500 hover:text-slate-800 absolute ri-eye-line bottom-[4px] right-[7px]"
:class="{'hidden': showRepeatPassword, '': !showRepeatPassword}"
@click="toggleRepeatPass"
/>
<i
id="hideRepeatPass"
ref="hideRepeatPass"
class="cursor-pointer transition-all text-slate-500 hover:text-slate-800 absolute ri-eye-off-line bottom-[4px] right-[7px]"
:class="{'hidden': !showRepeatPassword, '': showRepeatPassword}"
@click="toggleRepeatPass"
/>
</div>
<div
v-if="errorPassword"
class="text-red-500 text-xs mt-1"
>
{{ errorPassword }}
</div>
</div>
</div>
<div class="flex justify-between gap-6 mb-6">
<div>
<VButton
type="button"
class=""
color="blue"
@click="getPassword"
>
<i class="ri-key-2-line" />
Сгенерировать пароль
</VButton>
</div>
<div class="flex gap-4 justify-end">
<div>
<VButton
type="button"
class=""
color="purple"
>
<i class="ri-printer-line" />
Распечатать
</VButton>
</div>
<div>
<VButton
color="blue"
test-id="save-user"
:disable="errorPassword !== null"
@click="saveUser"
>
<i class="ri-save-line cursor-pointer" />
Сохранить
</VButton>
</div>
</div>
</div>
</template>

View File

@ -0,0 +1,44 @@
<script>
import {mapGetters} from 'vuex'
import {tableColumns} from './helpers/TableColumns'
import VTabulator from '@molecules/Tabulator/VTabulator.vue';
export default {
name: 'UsersForSelection',
components: {VTabulator},
props: {
id: {
type: Number,
default: null
},
caseOfUsersInService: {
type: Object,
default: () => ({})
},
},
data() {
return {
}
},
computed: {
...mapGetters('users', ["usersWithoutService"])
},
methods: {
getColumns(addUser) {
return tableColumns({typeUsers: 'addUsers', addUser})
},
addUser(user) {
this.caseOfUsersInService.addUserToService(user.id)
},
}
}
</script>
<template>
<div>
<VTabulator
:dataSource="usersWithoutService"
:columns="getColumns(addUser)"
/>
</div>
</template>

View File

@ -1,52 +1,67 @@
<script>
import ModuleContainer from "@organisms/UsersManager/UsersManagerContainer.vue";
import UsersTable from "@organisms/UsersManager/UsersManagerUsersTable.vue";
import UsersEditor from "@organisms/UsersManager/UsersManagerUserEditor.vue";
import ManagerTitle from "@organisms/UsersManager/UsersManagerTitle.vue";
import ModuleContainer from "@organisms/UsersManager/Container.vue";
import UsersTable from "@organisms/UsersManager/UsersTable.vue";
import UserEditor from "@organisms/UsersManager/UserEditor.vue";
import UsersForSelecting from "@organisms/UsersManager/UsersForSelection.vue";
import ManagerTitle from "@organisms/UsersManager/Title.vue";
import VButton from "@atoms/VButton.vue";
import {mapGetters} from 'vuex'
export default {
name: 'UsersManager',
components: {ModuleContainer, UsersTable, UsersEditor, ManagerTitle, VButton},
components: {ModuleContainer, UsersTable, UserEditor, UsersForSelecting, ManagerTitle, VButton},
props: {
serviceOfUsers: {
type: Object,
default: () => ({})
},
caseOfUsersInService: {
type: Object,
default: () => ({})
},
selectedService: {
type: Object,
default: () => ({})
}
},
data() {
return {
componentState: 'view' // view | create | select
}
},
computed: {
...mapGetters('users', ["usersList"]),
gridCols() {
return this.componentState === 'view' ? 'grid-cols-1' : 'grid-cols-2'
...mapGetters('users', ['userStatus', 'usersWithService']),
},
watch: {
selectedService: function (newValue, oldValue) {
console.log('newValue.id', newValue.id)
if (newValue.id !== oldValue.id) {
this.serviceOfUsers.setStatusUser('inactive')
}
},
},
methods: {
openUserPanelOfCreate() {
this.componentState = 'create'
this.serviceOfUsers.createNewUser()
this.serviceOfUsers.setStatusUser('create')
},
openUserPanelOfSelect() {
this.componentState = 'select'
this.serviceOfUsers.fetchUsersOffSite()
this.serviceOfUsers.setStatusUser('select')
this.serviceOfUsers.getUsersWithoutService(this.selectedService.id)
},
closeUserPanel() {
this.componentState = 'view'
this.serviceOfUsers.setStatusUser('inactive')
}
}
}
</script>
<template>
<form>
<div
class="grid grid-cols-12 gap-4"
:class="`${gridCols}`"
class="w-full flex justify-between grow gap-4"
:class="``"
>
<ModuleContainer :class="[{'col-span-12': componentState === 'view', 'col-span-4': componentState !== 'view' }]">
<ModuleContainer>
<ManagerTitle class="mb-4">
<template #title>
<span>Список пользователей</span>
@ -56,27 +71,38 @@ export default {
<VButton
color="blue"
test-id="toggle-new-user"
:disable="userStatus === 'create'"
@click="openUserPanelOfCreate"
>
<i class="ri-user-add-line" />
Создать пользователя
</VButton>
<VButton
color="purple"
test-id="toggle-add-user"
:disable="userStatus === 'select'"
@click="openUserPanelOfSelect"
>
<i class="ri-user-received-fill" />
Добавить существующего
</VButton>
</div>
</template>
</ManagerTitle>
<UsersTable :usersList="usersList" />
<UsersTable
:users="usersWithService"
:serviceOfUsers="serviceOfUsers"
:caseOfUsersInService="caseOfUsersInService"
/>
</ModuleContainer>
<ModuleContainer
v-if="componentState === 'create'"
class="col-span-8"
v-if="userStatus === 'create'"
class="w-full"
>
<ManagerTitle
test-id="new-user-container"
class="!justify-end gap-3"
>
<ManagerTitle test-id="new-user-container">
<template #title>
<span>Создать пользователя</span>
</template>
@ -86,17 +112,47 @@ export default {
color="gray"
@click="closeUserPanel"
>
<i class="ri-close-line" />
Закрыть
</VButton>
</template>
</ManagerTitle>
<UsersEditor />
<UserEditor :serviceOfUsers="serviceOfUsers" />
</ModuleContainer>
<ModuleContainer
v-if="componentState === 'select'"
class="col-span-8"
v-if="userStatus === 'edit'"
class="w-full"
>
<ManagerTitle
test-id="edit-user-container"
class="!justify-end gap-3"
>
<template #title>
<span>Редактировать пользователя</span>
</template>
<template #control>
<VButton
class="close-button"
color="gray"
@click="closeUserPanel"
>
<i class="ri-close-line" />
Закрыть
</VButton>
</template>
</ManagerTitle>
<UserEditor
:serviceOfUsers="serviceOfUsers"
/>
</ModuleContainer>
<ModuleContainer
v-if="userStatus === 'select'"
class="w-full col-span-8"
>
<ManagerTitle
test-id="select-user-container"
class="!justify-end gap-3"
>
<ManagerTitle>
<template #title>
<span>Выбрать пользователя</span>
</template>
@ -106,11 +162,13 @@ export default {
color="gray"
@click="closeUserPanel"
>
<i class="ri-close-line" />
Закрыть
</VButton>
</template>
</ManagerTitle>
<UsersEditor />
<UsersForSelecting :caseOfUsersInService="caseOfUsersInService" />
</ModuleContainer>
</div>
</form>
</template>

View File

@ -1,17 +0,0 @@
<script>
export default {
name: 'UsersManagerUserEditor',
components: {},
data() {
return {
}
},
}
</script>
<template>
<div>
UsersManagerUserEditor
</div>
</template>

View File

@ -1,101 +0,0 @@
<script>
import VTabulator from '@molecules/VTabulator/VTabulator.vue';
export default {
name: 'UsersManagerUsersTable',
components: {VTabulator},
props: {
usersList: {
type: Array,
default: () => []
},
},
data() {
const editItem = (item) => this.editItem(item)
const deleteItem = (item) => this.deleteItem(item)
return {
rerenderStep: 3,
columns: [
{
field: "id",
title: "ID",
width: 100,
sorter: "number",
},
{
field: "first_name",
title: "First Name",
width: 150,
sorter: "string",
},
{
field: "last_name",
title: "Last Name",
width: 150,
sorter: "string",
},
{
field: "role",
title: "Role",
width: 150,
sorter: "string",
},
{
title: "Actions",
formatter: (cell) => {
const record = cell.getRow().getData();
const id = record.id;
return `
<button action="edit" class="text-white mr-2 text-xs bg-blue-700 hover:bg-blue-800 focus:outline-none focus:ring-4 focus:ring-blue-300 font-medium rounded-full text-sm px-3 py-2 text-center mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-900">
<i action="edit" class="ri-pencil-line"></i>
</button>
<input action="toggle-remove" type="checkbox" id="remove-option-${id}" value="" class="hidden peer" required="">
<label for="remove-option-${id}" class="peer-checked:hidden cursor-pointer inline-text text-white text-xs bg-red-700 hover:bg-red-800 focus:outline-none focus:ring-4 focus:ring-red-300 font-medium rounded-full text-sm px-3 py-2 text-center mb-2 dark:bg-red-600 dark:hover:bg-red-700 dark:focus:ring-red-900"
>
<i class="ri-delete-bin-line"></i>
</label>
<label action="remove" for="remove-option-${id}" class="hidden cursor-pointer mr-2 peer-checked:flex text-white text-xs bg-red-700 hover:bg-red-800 focus:outline-none focus:ring-4 focus:ring-red-300 font-medium rounded-full text-sm px-3 py-2 text-center mb-2 dark:bg-red-600 dark:hover:bg-red-700 dark:focus:ring-red-900"
>
<i action="remove" class="ri-check-line"></i>
</label>
<label action="close-remove" for="remove-option-${id}" class="hidden cursor-pointer peer-checked:flex text-white text-xs bg-gray-700 hover:bg-gray-800 focus:outline-none focus:ring-4 focus:ring-gray-300 font-medium rounded-full text-sm px-3 py-2 text-center mb-2 dark:bg-gray-600 dark:hover:bg-gray-700 dark:focus:ring-gray-900">
<i class="ri-close-line"></i>
</label>
`;
},
cellClick: function(e, cell) {
const action = e.target.getAttribute('action');
if (action === 'edit') {
editItem(cell.getRow().getData());
} else if (action === 'remove') {
deleteItem(cell.getRow().getData());
}
},
}],
}
},
methods: {
editItem(item) {
console.log('Edit item:', item);
},
deleteItem(item) {
console.log('Delete item:', item);
},
}
}
</script>
<template>
<div
class="flex flex-col max-h-[70vh] mb-14"
>
<div>
<VTabulator
:dataSource="usersList"
:columns="columns"
/>
</div>
</div>
</template>

View File

@ -0,0 +1,58 @@
<script>
import {mapGetters} from 'vuex'
import {tableColumns} from './helpers/TableColumns'
import VTabulator from '@molecules/Tabulator/VTabulator.vue'
export default {
name: 'UsersTable',
components: {VTabulator},
props: {
users: {
type: Array,
default: () => []
},
serviceOfUsers: {
type: Object,
default: () => ({})
},
caseOfUsersInService: {
type: Object,
default: () => ({})
},
},
computed: {
...mapGetters('users', ['userStatus', 'selectedUser']),
},
mounted () {
},
methods: {
editUser(user) {
if (this.userStatus === 'edit') return
this.serviceOfUsers.setSelectedUser(user.id)
this.serviceOfUsers.setStatusUser('edit')
},
deleteUser(user) {
this.caseOfUsersInService.deleteUserFromService(user.id)
if (this.selectedUser?.id === user.id) {
this.serviceOfUsers.setStatusUser('select')
}
},
getColumns(editUser, deleteUser) {
return tableColumns({typeUsers: 'serviceUsers', editUser, deleteUser})
}
}
}
</script>
<template>
<div
class="flex flex-col max-h-[70vh] mb-14"
>
<div>
<VTabulator
:dataSource="users"
:columns="getColumns(editUser, deleteUser)"
/>
</div>
</div>
</template>

View File

@ -0,0 +1,100 @@
const tableColumns = ({typeUsers, addUser, editUser, deleteUser}) => {
return [
{
field: "id",
title: "ID",
width: 100,
sorter: "number",
},
{
field: "firstName",
title: "Имя",
width: 150,
sorter: "string",
},
{
field: "lastName",
title: "Фамилия",
width: 150,
sorter: "string",
},
// {
// field: "role",
// title: "Роль",
// width: 150,
// sorter: "string",
// },
// {
// field: "second_name",
// title: "Отчество",
// width: 150,
// sorter: "string",
// },
// {
// field: "email",
// title: "email",
// width: 150,
// sorter: "string",
// },
// {
// field: "position",
// title: "Должность",
// width: 150,
// sorter: "string",
// },
// {
// field: "notes",
// title: "notes",
// width: 150,
// sorter: "string",
// },
{
title: "Actions",
width: `${typeUsers === 'serviceUsers' ? '135' : '70'}`,
formatter: (cell) => {
const record = cell.getRow().getData();
const id = record.id;
if (typeUsers === 'serviceUsers') {
return `<button action="edit" class="text-white mr-2 text-xs bg-blue-700 hover:bg-blue-800 focus:outline-none focus:ring-4 focus:ring-blue-300 font-medium rounded-full text-sm px-3 py-2 text-center mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-900">
<i action="edit" class="ri-pencil-line" style="font-size: 16px"> </i>
</button>
<input action="toggle-remove" type="checkbox" id="remove-option-${id}" value="" class="hidden peer" required="">
<label for="remove-option-${id}" class="peer-checked:hidden cursor-pointer inline-text text-white text-xs bg-red-700 hover:bg-red-800 focus:outline-none focus:ring-4 focus:ring-red-300 font-medium rounded-full text-sm px-3 py-2 text-center mb-2 dark:bg-red-600 dark:hover:bg-red-700 dark:focus:ring-red-900"
>
<i class="ri-user-unfollow-line" style="font-size: 16px"></i>
</label>
<label action="remove" for="remove-option-${id}" class="hidden cursor-pointer mr-2 peer-checked:flex text-white text-xs bg-red-700 hover:bg-red-800 focus:outline-none focus:ring-4 focus:ring-red-300 font-medium rounded-full text-sm px-3 py-2 text-center mb-2 dark:bg-red-600 dark:hover:bg-red-700 dark:focus:ring-red-900"
>
<i action="remove" class="ri-check-line" style="font-size: 16px"></i>
</label>
<label action="close-remove" for="remove-option-${id}" class="hidden cursor-pointer peer-checked:flex text-white text-xs bg-gray-700 hover:bg-gray-800 focus:outline-none focus:ring-4 focus:ring-gray-300 font-medium rounded-full text-sm px-3 py-2 text-center mb-2 dark:bg-gray-600 dark:hover:bg-gray-700 dark:focus:ring-gray-900">
<i class="ri-close-line" style="font-size: 16px"></i>
</label>`
}
if (typeUsers === 'addUsers') {
return `<button action="add" class="text-white mr-2 text-xs bg-blue-700 hover:bg-blue-800 focus:outline-none focus:ring-4 focus:ring-blue-300 font-medium rounded-full text-sm px-3 py-2 text-center mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-900">
<i action="add" class="ri-user-add-line" style="font-size: 16px"></i>
</button>`
}
},
cellClick: function(e, cell) {
const action = e.target.getAttribute('action');
switch (action) {
case 'add':
addUser(cell.getRow().getData());
break;
case 'edit':
editUser(cell.getRow().getData());
break;
case'remove':
deleteUser(cell.getRow().getData());
break;
}
},
}]
}
export { tableColumns }

View File

@ -0,0 +1,24 @@
const generatePassword = () => {
const chars = "0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ"
const passLength = 8
let pass = ''
for (let i = 0; i <= passLength; i++) {
const randomNumber = Math.floor(Math.random() * chars.length)
pass += chars.substring(randomNumber, randomNumber + 1)
}
// console.log('pass', pass)
return pass
}
const equalPasswords = (password, repeatPassword) => {
return password !== repeatPassword ? 'Пароли не совпадают' : null
}
const isFullLengthPassword = (password) => {
return password.length < 8 ? 'Пароль должен быть не менее 8 символов' : null
}
const isRepeatPasswordEmpty = (password, repeatPassword) => {
return password && !repeatPassword ? 'Поле не может быть пустым' : null
}
export {generatePassword, isFullLengthPassword, equalPasswords, isRepeatPasswordEmpty}

View File

@ -1,6 +1,5 @@
<script>
import {computed} from 'vue'
import {mapActions, mapGetters} from 'vuex'
import {mapGetters} from 'vuex'
import {useStore} from '@store/index.js'
import AdapterOfServices from '@adapters/adapterOfServices/Services'
@ -10,17 +9,12 @@ import ServiceOfServices from '@services/serviceOfServices/Services.js'
import CaseOfUsersInService from '@useCases/CaseOfUsersInService.js'
import PageHeader from "@atoms/AppPageHeader.vue"
import SiteList from "@organisms/ServicesList/ServicesList.vue"
import SiteManager from "@organisms/UsersManager/UsersManager.vue"
import ServicesList from "@organisms/ServicesList/ServicesList.vue"
import UsersManager from "@organisms/UsersManager/UsersManager.vue"
export default {
name: 'SitesManagerPage',
components: {SiteManager, SiteList, PageHeader},
provide() {
return {
serviceOfServices: computed(() => this.serviceOfServices),
}
},
name: 'ServicesManagerPage',
components: {UsersManager, ServicesList, PageHeader},
setup() {
const url = import.meta.env.VITE_API_ADDR
@ -31,7 +25,6 @@ export default {
const serviceOfUsers = new ServiceOfUsers(adapterOfUsers, store)
const serviceOfServices = new ServiceOfServices(adapterOfServices, store)
// serviceOfServices.fetchServicesList()
const caseOfUsersInService = new CaseOfUsersInService(serviceOfUsers, serviceOfServices)
@ -42,35 +35,30 @@ export default {
}
},
computed: {
...mapGetters('services', ["sites", "routes", "newRoute", "selectedServiceState"]),
...mapGetters('services', ["services", "routes", "newRoute", "selectedService"]),
},
mounted () {
// this.uploadServices()
},
methods: {
...mapActions('services', ["uploadServices", "uploadAndSelectService"]),
...mapActions('users', ["fetchUsersList"]),
async selectSite(siteId, mode = 'prod') {
await this.fetchUsersList({siteId, mode})
this.uploadAndSelectService(siteId)
return "ok"
}
}
}
</script>
<template>
<div class="p-6">
<PageHeader class="me-2 mb-6" />
<SiteList
<PageHeader
:serviceOfServices="serviceOfServices"
class="me-2 mb-6"
/>
<ServicesList
:serviceOfServices="serviceOfServices"
:caseOfUsersInService="caseOfUsersInService"
:selectSite="selectSite"
/>
<SiteManager
v-if="selectedServiceState === 'active'"
<UsersManager
v-if="selectedService"
:serviceOfUsers="serviceOfUsers"
:caseOfUsersInService="caseOfUsersInService"
:selectedService="selectedService"
/>
</div>
</template>

View File

@ -1,16 +1,16 @@
import {createRouter, createWebHistory} from "vue-router";
import SitesManagerPage from "@pages/SitesManagerPage/SitesManagerPage.vue"
import ServicesManagerPage from "@pages/ServicesManagerPage/ServicesManagerPage.vue"
const routes = [
{
path: "/",
name: "sites",
component: SitesManagerPage
component: ServicesManagerPage
},
{
path: "/users/:mod",
name: "users",
component: import("@pages/UserManage/ButtonModal.vue")
component: import("@pages/UserManage/index.vue")
},
];

View File

@ -16,6 +16,7 @@ class ServiceOfServices {
async addNewServiceLayout() {
const newService = {"port": "", "name": "", id: -1}
this.store.dispatch('services/addedNewServiceLayout', newService)
return newService
}
async createNewService(newService) {
@ -28,6 +29,11 @@ class ServiceOfServices {
}
async selectService(service) {
const services = this.store.getters['services/services']
if (services[0]?.id === -1) {
const updatedServices = removedNewService(services)
this.store.dispatch('services/saveServices', updatedServices)
}
this.store.dispatch('services/changeSelectedService', service)
}
@ -48,14 +54,15 @@ class ServiceOfServices {
this.store.dispatch('services/editSelectedService', selectedService)
}
async isSaveServices(event) {
async setIsSaveServices(event) {
this.store.dispatch('services/changeIsSaveData', event)
return event
}
async saveService(editService) {
async saveService(updateService) {
this.store.commit('services/setIsSaveData', false)
this.store.commit('services/setSelectedService', null)
const editedService = await this.adapterOfServices.updateService(editService)
const editedService = await this.adapterOfServices.updateService(updateService)
const services = this.store.getters['services/services']
const updatedServices = !isEmpty(editedService) ? updatedService(editedService, services) : services
// console.log('updatedServices', updatedServices)
@ -64,12 +71,16 @@ class ServiceOfServices {
}
async removeService(id) {
const deletedSiteId = await this.adapterOfServices.deleteService(id)
const deletedServiceId = await this.adapterOfServices.deleteService(id)
const services = this.store.getters['services/services']
const updatedServices = deletedSiteId ? deletedService(deletedSiteId, services) : null
const updatedServices = deletedServiceId ? deletedService(deletedServiceId, services) : null
this.store.dispatch('services/saveService', updatedServices)
}
async resetStore() {
this.store.dispatch('services/resetStore')
}
}
export default ServiceOfServices

View File

@ -1,31 +1,31 @@
const addedService = (addedSite, sites) => {
const sitesWithoutNewSite = removedNewService(sites)
return [addedSite,...sitesWithoutNewSite]
const addedService = (addedService, services) => {
const servicesWithoutNewSite = removedNewService(services)
return [addedService,...servicesWithoutNewSite]
}
const updatedService = (updatedSite, sites) => {
if (updatedSite.id) {
const editIdx = sites.findIndex(service => service.id === updatedSite.id)
const beforeEdit = sites.slice(0, editIdx)
const afterEdit = sites.slice(editIdx + 1)
const withEdit = [...beforeEdit, updatedSite]
const updatedService = (updatedService, services) => {
if (updatedService.id) {
const editIdx = services.findIndex(service => service.id === updatedService.id)
const beforeEdit = services.slice(0, editIdx)
const afterEdit = services.slice(editIdx + 1)
const withEdit = [...beforeEdit, updatedService]
return [...withEdit, ...afterEdit]
}
}
const removedNewService = (sites) => {
if (sites.length > 0) {
const firstSite = sites[0]
const removedNewService = (services) => {
if (services.length > 0) {
const firstSite = services[0]
const isNewSite = firstSite.id === -1
sites = isNewSite ? sites.slice(1) : sites
return sites
services = isNewSite ? services.slice(1) : services
return services
}
}
const deletedService = (deletedSiteId, sites) => {
const deletedService = (deletedSiteId, services) => {
if (deletedSiteId) {
const deleteIdx = sites.findIndex(service => service.id === deletedSiteId)
return sites.slice(0, deleteIdx).concat(sites.slice(deleteIdx + 1))
const deleteIdx = services.findIndex(service => service.id === deletedSiteId)
return services.slice(0, deleteIdx).concat(services.slice(deleteIdx + 1))
}
}

View File

@ -1,3 +1,5 @@
import { addedUser, getUserById, updatedUser, usersWithThisService, usersWithoutThisService, addServiceIdToUser, deleteServiceIdFromUser } from "./helpers"
class UsersOfServices {
constructor(adapter, store) {
this.adapter = adapter
@ -6,34 +8,183 @@ class UsersOfServices {
/**
*
* @param {Array} users
* @returns {Promise<Array>}
*/
async saveSiteUsers(users) {
await this.store.dispatch('users/saveSiteUsers', users)
return users
}
/**
*
* @param {Array} users
* @returns {Promise<Array>}
*/
async saveUsersWithoutSite(users) {
await this.store.dispatch('users/saveUsersWithoutSite', users)
return users
}
/**
*
* @param serviceId
* @param {String} mode
* @returns {Promise<void>}
*/
async fetchUsersByService(serviceId) {
const users = await this.adapter.getUsersByServiceId(serviceId)
await this.saveSiteUsers(users)
async getUsers(mode) {
const users = await this.adapter.getUsers({mode})
// await this.saveSiteUsers(users)
this.store.dispatch('users/updateUsers', users)
return users
}
/**
*
* @param {Number} serviceId
* @param {String} mode
* @returns {Promise<void>}
*/
async getUsersByService(serviceId, mode) {
const users = await this.adapter.getUsers({mode})
const usersWithService = await this.adapter.getUsersByServiceId(serviceId, mode)
const usersWithoutService = usersWithoutThisService(serviceId, users)
// await this.saveSiteUsers(users)
this.store.dispatch('users/updateUsers', users)
this.store.dispatch('users/updateUsersWithService', usersWithService)
this.store.dispatch('users/updateUsersWithoutService', usersWithoutService)
return usersWithService
}
/**
*
* @param {Number} serviceId
* @returns {Promise<void>}
*/
async getUsersWithoutService(serviceId) {
const users = this.store.getters['users/users']
const filteredUsers = usersWithoutThisService(serviceId, users)
// await this.saveSiteUsers(users)
// console.log('filteredUsers', filteredUsers)
this.store.dispatch('users/updateUsersWithoutService', filteredUsers)
return filteredUsers
}
/**
*
* @returns {Promise<Object>}
*/
async createNewUser() {
// const createdUser = await this.adapter.createUser(userData)
const newUser = {id: -1, firstName: '',lastName: '', role: '', email: '', password: '', serviceId: []}
// const users = this.store.getters['users/users']
// const updatedUsers = addedUser(newUser, users)
this.store.dispatch('users/updateSelectedUser', newUser)
return newUser
}
/**
*
* @returns {Promise<Object>}
*/
async getSelectedUser() {
const selectedUser = this.store.getters['users/selectedUser']
return selectedUser
}
/**
*
* @param {Number} selectedUserId
* @returns {Promise<Object>}
*/
async setSelectedUser(selectedUserId) {
const selectedUser = getUserById(selectedUserId, this.store.getters['users/users'])
this.store.dispatch('users/updateSelectedUser', selectedUser)
return selectedUser
}
/**
*
* @param {String} status
* @returns {Promise<String>}
*/
async setStatusUser(status) {
this.store.dispatch('users/updateUserStatus', status)
return status
}
/**
*
* @param {Number} selectedUserId
* @param {Number} serviceId
* @returns {Promise<Object>}
*/
async addUserToService(selectedUserId, serviceId) {
// const addedUser = await this.adapter.addUser(selectedUserId, serviceId) // Запрос на обновление пользователя с новым service_id
const users = this.store.getters['users/users']
const updatedUsers = addServiceIdToUser(selectedUserId, serviceId, users)
const usersWithService = usersWithThisService(serviceId, updatedUsers)
const usersWithoutService = usersWithoutThisService(serviceId, updatedUsers)
this.store.dispatch('users/updateUsers', updatedUsers)
this.store.dispatch('users/updateUsersWithService', usersWithService)
this.store.dispatch('users/updateUsersWithoutService', usersWithoutService)
// return addedUser
}
/**
*
* @param {Object} params
* @returns {Promise<Object>}
*/
async editUserByService(params) {
const selectedUser = this.store.getters['users/selectedUser']
// console.log('selectedService', selectedService)
if (selectedUser) {
selectedUser[params.key] = params.value
this.store.dispatch('users/updateSelectedUser', selectedUser)
return selectedUser
}
}
/**
*
* @param {Number} selectedUserId
* @param {Number} serviceId
* @returns {Promise<Object>}
*/
async deleteUserFromService(selectedUserId, serviceId) {
// const deletedUser = await this.adapter.addUser(selectedUserId, serviceId) // Запрос на обновление пользователя с новым service_id???
const users = this.store.getters['users/users']
const updatedUsers = deleteServiceIdFromUser(selectedUserId, serviceId, users)
const usersWithService = usersWithThisService(serviceId, updatedUsers)
const usersWithoutService = usersWithoutThisService(serviceId, updatedUsers)
this.store.dispatch('users/updateUsers', updatedUsers)
this.store.dispatch('users/updateUsersWithService', usersWithService)
this.store.dispatch('users/updateUsersWithoutService', usersWithoutService)
// return deletedUser
}
/**
*
* @param {Number} serviceId - updated data for selected user, send to server
* @returns {Promise<Object>}
*/
async saveUpdatedDataUser(serviceId) {
// console.log('serviceId', serviceId)
const selectedUser = this.store.getters['users/selectedUser']
// const userStatus = this.store.getters['users/userStatus']
if (selectedUser && selectedUser.id) {
if (selectedUser.id === -1) {
const users = this.store.getters['users/users']
const userData = {...selectedUser,
id: users.length + 1, // временно пока нет данных с сервера
serviceId: [serviceId],
}
// const createdUser = await this.adapter.createUser(userData) // Запрос на создание нового пользователя
// const updatedUsers = addedUser(createdUser, users)
const updatedUsers = addedUser(userData, users)
const usersWithService = usersWithThisService(serviceId, updatedUsers)
const usersWithoutService = usersWithoutThisService(serviceId, updatedUsers)
this.store.dispatch('users/updateUsers', updatedUsers)
this.store.dispatch('users/updateUsersWithService', usersWithService)
this.store.dispatch('users/updateUsersWithoutService', usersWithoutService)
// return createdUser
}
if (selectedUser.id !== -1) {
// console.log('selectedUser', selectedUser)
// const updatedUser = await this.adapter.updateUser(selectedUser) // Запрос на обновление пользователя с новыми данными
const users = this.store.getters['users/usersWithService']
const updatedUsers = updatedUser(selectedUser, users)
this.store.dispatch('users/updateUsersWithService', updatedUsers)
// return updatedUser
}
}
}
async resetStore() {
this.store.dispatch('users/resetStore')
}
}
export default UsersOfServices

View File

@ -0,0 +1,67 @@
const addedUser = (newUser, users) => {
const usersWithoutNewSite = removedNewUser(users)
return [newUser,...usersWithoutNewSite]
}
const getUserById = (id, users) => {
return users.find(user => user.id === id)
}
const usersWithThisService = (serviceId, users) => {
// console.log('serviceId', serviceId)
return users.filter((user) => user.serviceId.includes(serviceId))
}
const usersWithoutThisService = (serviceId, users) => {
return users.filter((user) => {
return !user.serviceId.includes((serviceId))
})
}
const addServiceIdToUser = (selectedUserId, serviceId, users) => {
if (selectedUserId && serviceId) {
const editIdx = users.findIndex(user => user.id === selectedUserId)
const beforeEdit = users.slice(0, editIdx)
const afterEdit = users.slice(editIdx + 1)
const withEdit = [...beforeEdit, {...users[editIdx], serviceId: [...users[editIdx].serviceId, serviceId]}]
return [...withEdit, ...afterEdit]
}
}
const deleteServiceIdFromUser = (selectedUserId, serviceId, users) => {
if (selectedUserId && serviceId) {
const editIdx = users.findIndex(user => user.id === selectedUserId)
const beforeEdit = users.slice(0, editIdx)
const afterEdit = users.slice(editIdx + 1)
const withEdit = [...beforeEdit, {...users[editIdx], serviceId: users[editIdx].serviceId.filter((id) => id !== serviceId)}]
return [...withEdit, ...afterEdit]
}
}
const updatedUser = (updatedUser, users) => {
if (updatedUser.id) {
const editIdx = users.findIndex(user => user.id === updatedUser.id)
const beforeEdit = users.slice(0, editIdx)
const afterEdit = users.slice(editIdx + 1)
const withEdit = [...beforeEdit, updatedUser]
return [...withEdit, ...afterEdit]
}
}
const removedNewUser = (users) => {
if (users.length > 0) {
const firstUser = users[0]
const isNewUser = firstUser.id === -1
users = isNewUser ? users.slice(1) : users
return users
}
}
const deletedUser = (deletedUserId, users) => {
if (deletedUserId) {
const deleteIdx = users.findIndex(user => user.id === deletedUserId)
return users.slice(0, deleteIdx).concat(users.slice(deleteIdx + 1))
}
}
export { addedUser, getUserById, usersWithThisService, usersWithoutThisService, addServiceIdToUser, deleteServiceIdFromUser, updatedUser, removedNewUser, deletedUser }

View File

@ -20,7 +20,7 @@ const state = {
const getters = {
isSaveData: (state) => state.isSaveData,
services: (state) => state.newService ? [state.newService, ...state.services] : state.services,
services: (state) => state.services,
routes: (state) => state.routes,
routesLib: (state) => state.routesLib,
selectedServiceState: (state) => state.selectedServiceState,
@ -36,50 +36,38 @@ const mutations = {
setServicesState: (state, payload) => state.servicesState = payload,
setSelectedService: (state, payload) => state.selectedService = payload,
setNewService: (state, payload) => state.newService = payload,
resetStore: (state) => {
for (let key in initState) {
state[key] = initState[key]
}
}
};
const actions = {
addedNewServiceLayout: ({commit, getters}, newService) => {
console.log('newSevice', newService)
commit('setServices', [newService,...getters.services])
commit('setSelectedService', newService)
// commit('setRoutes', [])
// commit('setRoutesState', "active")
},
createNewService: async ({commit}, updatedServices) => {
if (!isEmpty(updatedServices)) {
// const newService = updatedSites[0]
// const updatedRoutes = addedNewRoute(newService, state.routes)
// commit('setRoutes', updatedRoutes)
// dispatch('updateRoutesWithApi', newService)
return commit('setServices', updatedServices)
}
},
breakeAddingSite: ({commit}) => {
commit('setSelectedService', null)
},
changeSelectedService: async ({commit}, siteProps) => {
commit('setSelectedService', siteProps)
},
editSelectedService: async ({commit}, selectedService) => {
// const selectedSite = getters.selectedSite
// selectedSite[payload.key] = payload.value
console.log('selectedService', selectedService)
commit('setSelectedService', selectedService)
},
changeIsSaveData: ({commit}, payload) => {
commit('setIsSaveData', payload)
},
saveServices: async ({commit}, services) => {
// const sites = await services.getServices()
commit('setServices', services)
commit('setServicesState', 'active')
console.log('services', services)
// console.log('services', services)
},
saveService: async ({commit}, updatedServices) => {
// commit('setIsSaveData', false)
// commit('setSelectedService', null)
commit('setServices', updatedServices)
},
@ -89,22 +77,12 @@ const actions = {
commit('setServices', updatedServices)
commit('setNewService', null)
}
// commit('setRoutesState', "await")
},
removeService: async ({commit}, updatedSites) => {
// const deletedSiteId = await services.deleteService(id)
// const updatedSites = deletedSite(deletedSiteId, getters.sites)
if (!isEmpty(updatedSites)) return commit('setServices', updatedSites)
},
uploadAndSelectService: ({state}, id) => {
state.selectedSite = state.services.find(site => site.id === id)
state.selectedSiteState = 'active'
},
resetStore: ({state}) => {
Object.entries(initState).forEach(([k,v]) => {
state[k] = v
})
resetStore: ({commit}) => {
commit('resetStore')
},
};

View File

@ -1,11 +1,16 @@
import Users from '@helpers/Users/Users.js';
// import Users from '@helpers/Users/Users.js';
const path = import.meta.env.VITE_API_ADDR
const UsersService = new Users(path)
// const path = import.meta.env.VITE_API_ADDR
// const UsersService = new Users(path)
const initState = {
usersList: [],
componentState: 'disabled',
userStatus: 'inactive',
selectedUser: null,
users: [],
usersWithService: [],
usersWithoutService: [],
};
const state = {
@ -13,20 +18,39 @@ const state = {
};
const getters = {
usersList: (state) => state.usersList,
componentState: (state) => state.componentState
userStatus: (state) => state.userStatus,
selectedUser: (state) => state.selectedUser,
users: (state) => state.users,
usersWithService: (state) => state.usersWithService,
usersWithoutService: (state) => state.usersWithoutService,
};
const mutations = {
setUsersList: (state, payload) => state.usersList = payload,
setComponentState: (state, payload) => state.componentState = payload
setUserStatus: (state, payload) => state.userStatus = payload,
setSelectedUser: (state, payload) => state.selectedUser = payload,
setUsers: (state, payload) => state.users = payload,
setUsersWithService: (state, payload) => state.usersWithService = payload,
setUsersWithoutService: (state, payload) => state.usersWithoutService = payload,
};
const actions = {
fetchUsersList: async ({commit}, {siteId, mode}) => {
const usersList = await UsersService.getUsersBySiteId(siteId, mode)
commit('setUsersList', usersList)
commit('setComponentState', 'active')
updateUsers: async ({commit}, users) => {
commit('setUsers', users)
// console.log('users', users)
},
updateUserStatus: async ({commit}, userStatus) => {
commit('setUserStatus', userStatus)
},
updateSelectedUser: async ({commit}, selectedUser) => {
commit('setSelectedUser', selectedUser)
},
updateUsersWithService: async ({commit}, users) => {
commit('setUsersWithService', users)
},
updateUsersWithoutService: async ({commit}, users) => {
commit('setUsersWithoutService', users)
},
resetStore: ({state}) => {
Object.entries(initState).forEach(([k, v]) => {

View File

@ -4,17 +4,60 @@ class UsersInService {
this.serviceOfServices = serviceOfServices
}
async fetchUsersByService() {
const selectedService = this.serviceOfServices.getSelectedService()
async getUsersWithSelectService(selectedService, mode) {
await this.serviceOfServices.selectService(selectedService)
await this.serviceOfUsers.getUsersByService(selectedService.id, mode)
}
async addUserToService(userId) {
const selectedService = await this.serviceOfServices.getSelectedService()
if (!selectedService) {
console.error('fetchUsersByService: Service not found')
return []
console.error('addUserToService: Service not found')
return {}
}
this.serviceOfUsers.fetchUsersByService(selectedService.id)
if (!userId) {
console.error('addUserToService: User not selected')
return {}
}
this.serviceOfUsers.addUserToService(userId, selectedService.id)
}
async fetchUsersWithoutService() {
async deleteUserFromService(userId) {
const selectedService = await this.serviceOfServices.getSelectedService()
if (!selectedService) {
console.error('removeUserFromService: Service not found')
return {}
}
if (!userId) {
console.error('removeUserFromService: User not selected')
return {}
}
this.serviceOfUsers.deleteUserFromService(userId, selectedService.id)
}
async saveEditedData() {
const selectedService = await this.serviceOfServices.getSelectedService()
if (!selectedService) {
console.error('saveEditedData: Service not found')
return {}
}
if (selectedService.id == -1) {
const data = {
name: selectedService.name,
port: selectedService.port,
device_ip: selectedService.device_ip,
proxy_ip: selectedService.proxy_ip,
description: selectedService.description,
is_online: selectedService.is_online,
}
const newService = await this.serviceOfServices.createNewService(data)
console.log('newService', newService)
this.serviceOfUsers.saveUpdatedDataUser(newService.id)
} else {
// this.updateRoutesWithApi(this.selectedService)
this.serviceOfServices.saveService(selectedService)
this.serviceOfUsers.saveUpdatedDataUser(selectedService.id)
}
}
}

View File

@ -44,7 +44,7 @@ describe('test for AdapterOfUsers', () => {
data: apiUser,
})
const user = await adapterOfUsers.createUser()
const user = await adapterOfUsers.createUser(appUser)
expect(user).toEqual(appUser)
})

View File

@ -1,67 +1,232 @@
import {describe, expect, test, beforeEach} from "vitest";
import { expect, test, describe, vi, beforeEach} from "vitest"
import AdapterOfServices from '@adapters/adapterOfServices/Services'
import ServiceOfServices from '@services/serviceOfServices/Services.js'
import {addedService, updatedService, removedNewService, deletedService} from '@services/serviceOfServices/helpers.js'
import { createStore } from 'vuex'
import {store as services} from "@/store/modules/services"
import axios from "axios";
class AdapterOfServices {
constructor() {
}
vi.mock('axios')
async getServices() {
return [{id: 1, name: 'service1'}, {id: 2, name: 'service2'}]
}
const defaultServices = [
{
"id": 1,
"created_at": "2024-03-06T17:31:31.948355541+03:00",
"updated_at": "2024-03-06T17:31:31.948355541+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "https://jsonplaceholder.typicode.com/",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
},
{
"id": 2,
"created_at": "2024-03-07T11:43:51.026265459+03:00",
"updated_at": "2024-03-07T13:35:12.506368972+03:00",
"deleted_at": null,
"name": "new 2",
"port": 4548,
"proxy_ip": "172.25.78.151",
"site_ip": "172.25.78.151",
"internet_uri": "",
"description": "new site 2",
"is_online": true
},
{
"id": 3,
"created_at": "2024-03-07T11:43:51.027148541+03:00",
"updated_at": "2024-03-07T13:35:24.919273428+03:00",
"deleted_at": null,
"name": "new 3",
"port": 2527,
"proxy_ip": "172.25.78.151",
"site_ip": "172.25.78.151",
"internet_uri": "",
"description": "new site 3...",
"is_online": true
}
]
const services = {
namespaced: true,
state: {
servicesList: [],
const resServices = [
{
"id": 1,
"created_at": "2024-03-06T17:31:31.948355541+03:00",
"updated_at": "2024-03-06T17:31:31.948355541+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"device_ip": "https://jsonplaceholder.typicode.com/",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
},
mutations: {
setServicesList(state, services) {
state.servicesList = services
},
},
getters: {
servicesList: state => {
return state.servicesList
}
},
actions: {
resetStore({state}) {
state.servicesList = []
},
saveServices({commit}, services) {
commit('setServicesList', services)
}
{
"id": 2,
"created_at": "2024-03-07T11:43:51.026265459+03:00",
"updated_at": "2024-03-07T13:35:12.506368972+03:00",
"deleted_at": null,
"name": "new 2",
"port": 4548,
"proxy_ip": "172.25.78.151",
"device_ip": "172.25.78.151",
"internet_uri": "",
"description": "new site 2",
"is_online": true
},
{
"id": 3,
"created_at": "2024-03-07T11:43:51.027148541+03:00",
"updated_at": "2024-03-07T13:35:24.919273428+03:00",
"deleted_at": null,
"name": "new 3",
"port": 2527,
"proxy_ip": "172.25.78.151",
"device_ip": "172.25.78.151",
"internet_uri": "",
"description": "new site 3...",
"is_online": true
}
]
describe('tests for ServiceOfServices', () => {
const adapterOfServices = new AdapterOfServices()
describe("tests services of services", () => {
const store = createStore({
plugins: [],
modules: {
services,
services
},
})
beforeEach( async() => {
await store.dispatch('services/resetStore')
beforeEach(() => {
store.dispatch('services/resetStore')
})
test('init', () => {
const adapterOfServices = new AdapterOfServices(import.meta.env.VITE_API_ADDR)
const serviceOfServices = new ServiceOfServices(adapterOfServices, store)
expect(serviceOfServices).toBeDefined()
axios.get.mockResolvedValue({
data: defaultServices,
})
test('test of fetchServicesList', async () => {
const serviceOfServices = new ServiceOfServices(adapterOfServices, store)
test('Upload services', async () => {
await serviceOfServices.fetchServices()
const services = store.getters['services/services']
const usersList = store.getters['services/servicesList']
expect(services).toEqual([]) // empty services array of store
const uploadServices = await serviceOfServices.fetchServices()
expect(uploadServices).toEqual(resServices) // full services array of store
expect(usersList).toEqual([{id: 1, name: 'service1'}, {id: 2, name: 'service2'}])
})
test('Added new service layout to services', async () => {
const expectedserviceData = {"port": "", "name": "", id: -1}
const newService = await serviceOfServices.addNewServiceLayout()
expect({newService}).toEqual({newService: expectedserviceData})
})
test('Added new service to array services of service with func addedService', async () => {
const newService = {
id: 4,
created_at: "2024-03-07T11:43:51.027148541+03:00",
updated_at: "2024-03-07T13:35:24.919273428+03:00",
deleted_at: null,
name: 'test add new service',
port: 2534,
device_ip: '172.25.78.151',
proxy_ip: '172.25.78.151',
internet_uri: '',
description: 'test add new service description',
is_online: true
}
const updatedServices = addedService(newService, resServices)
expect(updatedServices[0].name).toEqual('test add new service')
expect(updatedServices[0].description).toEqual('test add new service description')
expect(updatedServices[0].port).toEqual(2534)
})
test('Set isSaveData - if need save service', async () => {
const isSaveData = false
expect(isSaveData).toEqual(false) // default value is false
const isSaveDataChanged = await serviceOfServices.setIsSaveServices(true)
expect(isSaveDataChanged).toEqual(true) // if need save service - true
})
test('Saving service after editing with func updateService', async () => {
const selectedEditedService =
{
"id": 3,
"created_at": "2024-03-07T11:43:51.027148541+03:00",
"updated_at": "2024-03-07T13:35:24.919273428+03:00",
"deleted_at": null,
"name": "edited test name",
"port": 5555,
"proxy_ip": "172.25.78.151",
"device_ip": "172.25.78.151",
"internet_uri": "",
"description": "edited description field",
"is_online": true
}
const updatedServices = updatedService(selectedEditedService, resServices)
const editedService = updatedServices.find(service => service.id === 3)
expect(editedService.name).toEqual('edited test name')
expect(editedService.port).toEqual(5555)
expect(editedService.description).toEqual('edited description field')
})
test('Updated services after deleting new service with only layout with func removedNewService', async () => {
store.commit('services/setServices', resServices)
const newService = await serviceOfServices.addNewServiceLayout()
const servicesWithNewServiceLayout = addedService(newService, resServices)
const forDeleteService = servicesWithNewServiceLayout.find(service => service.id === -1)
expect(forDeleteService).toBeDefined() // before delete service
const updatedServices = removedNewService(servicesWithNewServiceLayout)
const deletedServiceStore = updatedServices.find(service => service.id === -1)
expect(deletedServiceStore).toBeUndefined() // after delete service
})
test('Updated services after deleting selected service with func deletedService', async () => {
const deleteServiceId = 3
const forDeleteService = resServices.find(service => service.id === 3)
expect(forDeleteService).toBeDefined() // before delete service
const updatedServices = deletedService(deleteServiceId, resServices)
const deletedServiceStore = updatedServices.find(service => service.id === 3)
expect(deletedServiceStore).toBeUndefined() // after delete service
})
})

View File

@ -1,36 +1,245 @@
import {describe, expect, test, beforeEach} from "vitest";
import {expect, test, describe, vi, beforeEach} from "vitest"
import AdapterOfUsers from '@adapters/adapterOfUsers/Users'
import ServiceOfUsers from '@services/serviceOfUsers/Users.js'
import {adapterOfUsers, store} from './MockData.js'
import {appUser} from '@mocks/users.js'
import {
addedUser,
getUserById,
usersWithThisService,
usersWithoutThisService,
addServiceIdToUser,
deleteServiceIdFromUser,
updatedUser,
removedNewUser,
deletedUser
} from '@services/serviceOfUsers/helpers.js'
import { createStore } from 'vuex'
import {store as users} from "@/store/modules/users"
import axios from "axios";
describe('test for ServiceOfUsers', () => {
vi.mock('axios')
const defaultUsers = [
{
"id": 1,
"serviceId": [1, 3],
"firstName": "Leanne 1",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 2,
"serviceId": [1],
"firstName": "Leanne 2",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 3,
"serviceId": [2, 3],
"firstName": "Leanne 3",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 4,
"serviceId": [3],
"firstName": "Leanne 4",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 5,
"serviceId": [4, 5],
"firstName": "Leanne 5",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
]
describe("tests services of users", () => {
const store = createStore({
plugins: [],
modules: {
users
},
})
beforeEach(() => {
store.dispatch('users/resetStore')
})
const adapterOfUsers = new AdapterOfUsers(import.meta.env.VITE_API_ADDR)
const serviceOfUsers = new ServiceOfUsers(adapterOfUsers, store)
beforeEach( async() => {
await store.dispatch('users/resetStore')
axios.get.mockResolvedValue({
data: defaultUsers,
})
test('init', () => {
expect(serviceOfUsers).toBeDefined()
test('Upload users by selected service', async () => {
const uploadUsers = await serviceOfUsers.getUsersByService(1, 'dev')
const expectedUsers = defaultUsers.filter(user => user.serviceId.includes(1))
expect(expectedUsers).toEqual(uploadUsers) // users array selected service
})
test('saveSiteUsers', async () => {
await serviceOfUsers.saveSiteUsers([appUser])
const storeUsers = store.getters['users/siteUsers']
expect(storeUsers).toEqual([appUser])
test('Upload users without selected service', async () => {
const uploadUsers = usersWithoutThisService(1, defaultUsers)
const expectedUsers = defaultUsers.filter(user => !user.serviceId.includes(1))
expect(expectedUsers).toEqual(uploadUsers) // users array without selected service
})
test('saveUsersWithoutSite', async () => {
await serviceOfUsers.saveUsersWithoutSite([appUser])
const storeUsers = store.getters['users/usersWithoutSite']
expect(storeUsers).toEqual([appUser])
test('Added new user layout to user editor', async () => {
const newUser = {id: -1, firstName: '',lastName: '', role: '', email: '', password: '', serviceId: []}
const expectUser = await serviceOfUsers.createNewUser()
expect({newUser: expectUser}).toEqual({newUser})
})
test('fetchUsersByService', async () => {
const serviceId = 1
await serviceOfUsers.fetchUsersByService(serviceId)
const storeUsers = store.getters['users/siteUsers']
expect(storeUsers).toEqual([appUser])
test('Added user to array users of selected service', async () => {
const newUser = {
"id": 6,
"serviceId": [4, 5],
"first_name": "Leanne 5",
"last_name": "Graham",
"email": "test@mail.ru",
"role": "admin",
}
const updatedUsers = addedUser(newUser, defaultUsers)
const addedNewUser = updatedUsers.find(user => user.id === 6)
expect(addedNewUser).toEqual(newUser)
})
test('Get user by id from array users', async () => {
const selectedIdUser = 3
const selectedUser = getUserById(selectedIdUser, defaultUsers)
expect(selectedUser.id).toEqual(selectedIdUser)
})
test('Filtered users of selected service', async () => {
const selectedIdService = 3
const usersWithSelectedService = usersWithThisService(selectedIdService, defaultUsers)
expect(usersWithSelectedService).toHaveLength(3)
usersWithSelectedService.map((user) => {
return expect(user.serviceId.includes(selectedIdService)).toBe(true)
})
})
test('Filtered users of not selected service', async () => {
const selectedIdService = 3
const usersWithSelectedService = usersWithoutThisService(selectedIdService, defaultUsers)
expect(usersWithSelectedService).toHaveLength(2)
usersWithSelectedService.map((user) => {
return expect(!user.serviceId.includes(selectedIdService)).toBe(true)
})
})
test('Added selected service to user with func addServiceIdToUser', async () => {
const updatedUsers = addServiceIdToUser(4, 2, defaultUsers)
const selectedUserWithoutService = defaultUsers.find(user => user.id === 4).serviceId.includes(2)
const selectedUserWithService = updatedUsers.find(user => user.id === 4).serviceId.includes(2)
expect(selectedUserWithoutService).toBe(false)
expect(selectedUserWithService).toBe(true)
})
test('Deleted user from array users of selected service with func deleteServiceIdFromUser', async () => {
const updatedUsers = deleteServiceIdFromUser(3, 2, defaultUsers)
const selectedUserWithoutService = defaultUsers.find(user => user.id === 3).serviceId.includes(2)
const selectedUserWithService = updatedUsers.find(user => user.id === 3).serviceId.includes(2)
expect(selectedUserWithoutService).toBe(true)
expect(selectedUserWithService).toBe(false)
})
test('Edited user updated in array users', async () => {
const editerUser =
{
"id": 3,
"serviceId": [2, 3],
"first_name": "Leanne 3 updated", // edited field
"last_name": "Graham updated", // edited field
"email": "test@mail.ru",
"role": "admin",
}
const beforeEditUser = defaultUsers.find(user => user.id === 3)
expect(beforeEditUser.first_name).not.toEqual('Leanne 3 updated') // check that user was not edited
expect(beforeEditUser.last_name).not.toEqual('Graham updated') // check that user was not edited
const updatedUsers = updatedUser(editerUser, defaultUsers)
const getEditedUser = updatedUsers.find(user => user.id === 3)
expect(getEditedUser.first_name).toEqual('Leanne 3 updated') // check that user was edited
expect(getEditedUser.last_name).toEqual('Graham updated') // check that user was edited
})
test('Removed new user layout from array users', async () => {
const newUser = {id: -1, first_name: '',last_name: '', role: '', email: '', password: '', serviceId: []}
const updatedUsers = addedUser(newUser, defaultUsers)
const beforeDeleteUser = updatedUsers.find(user => user.id === -1)
expect(beforeDeleteUser).toBeDefined() // before delete user
const afterDeleteUser = removedNewUser(updatedUsers)
const deletedServiceStore = afterDeleteUser.find(service => service.id === -1)
expect(deletedServiceStore).toBeUndefined() // after delete user
})
test('Updated users after deleting selected user with func deletedUser', async () => {
const deleteUserId = 3
const forDeleteUser = defaultUsers.find(user => user.id === 3)
expect(forDeleteUser).toBeDefined() // before delete user
const updatedUsers = deletedUser(deleteUserId, defaultUsers)
const afterDeletingUser = updatedUsers.find(user => user.id === 3)
expect(afterDeletingUser).toBeUndefined() // after delete user
})
})

View File

@ -1,6 +1,7 @@
import {expect, test, describe, vi, beforeEach} from "vitest"
import AdapterOfServices from '@adapters/adapterOfServices/Services'
import ServiceOfServices from '@services/serviceOfServices/Services.js'
import {addedService, updatedService, removedNewService, deletedService} from '@services/serviceOfServices/helpers.js'
import { createStore } from 'vuex'
import {store as services} from "@/store/modules/services"
import axios from "axios";
@ -125,7 +126,7 @@ describe("tests services store with vuex", () => {
})
test('Added new service layout to services of store', async () => {
const expectedSiteData = {"port": "", "name": "", id: -1}
const expectedserviceData = {"port": "", "name": "", id: -1}
await serviceOfServices.addNewServiceLayout()
@ -138,11 +139,38 @@ describe("tests services store with vuex", () => {
services
}
).toEqual({
selectedService: expectedSiteData,
services: [expectedSiteData]
selectedService: expectedserviceData,
services: [expectedserviceData]
})
})
test('Added new service to services of store', async () => {
const newService = {
id: 4,
created_at: "2024-03-07T11:43:51.027148541+03:00",
updated_at: "2024-03-07T13:35:24.919273428+03:00",
deleted_at: null,
name: 'test add new service',
port: 2534,
device_ip: '172.25.78.151',
proxy_ip: '172.25.78.151',
internet_uri: '',
description: 'test add new service description',
is_online: true
}
store.commit('services/setServices', resServices)
const updatedServices = addedService(newService, store.getters['services/services'])
store.commit('services/setServices', updatedServices)
const services = store.getters['services/services']
expect(services[0].name).toEqual('test add new service')
expect(services[0].description).toEqual('test add new service description')
expect(services[0].port).toEqual(2534)
})
test('Selected service - for edit fields values in this service', async () => {
const editedService =
@ -168,6 +196,20 @@ describe("tests services store with vuex", () => {
})
test('Set isSaveData - if need save service', async () => {
const isSaveData = store.getters['services/isSaveData']
expect(isSaveData).toEqual(false) // default value is false
await serviceOfServices.setIsSaveServices(true)
const isSaveDataChanged = store.getters['services/isSaveData']
expect(isSaveDataChanged).toEqual(true) // if need save service - true
})
test('Edited fields values in selected service of store', async () => {
const selectedForEditService =
@ -195,56 +237,168 @@ describe("tests services store with vuex", () => {
const selectedService = store.getters['services/selectedService']
// console.log('Edited fields 4 test', selectedService)
expect(selectedService.name).toEqual('edited test name')
expect(selectedService.port).toEqual(5555)
expect(selectedService.description).toEqual('edited description field')
})
// test("test uploadAndSelectService function", async () => {
// const mockData = [
// {
// "id": 1,
// "created_at": "2024-02-22T17:08:37.715772388+03:00",
// "updated_at": "2024-02-26T14:11:38.64094899+03:00",
// "deleted_at": null,
// "name": "jsonplaceholder.typicode.com",
// "port": 9965,
// "proxy_ip": "172.25.78.153",
// "site_ip": "172.25.78.153",
// "internet_uri": "localhost",
// "description": "localhost",
// "is_online": true
// }
// ]
test('Updated services in store after editing selected service', async () => {
// axios.get.mockResolvedValue({
// data: mockData,
// })
const editedService =
{
"id": 3,
"created_at": "2024-03-07T11:43:51.027148541+03:00",
"updated_at": "2024-03-07T13:35:24.919273428+03:00",
"deleted_at": null,
"name": "edited and updated test service",
"port": 3436,
"proxy_ip": "172.25.78.151",
"device_ip": "172.25.78.151",
"internet_uri": "",
"description": "edited and updated test service description",
"is_online": true
}
// await store.dispatch('services/uploadSites')
// store.dispatch('services/uploadAndSelectService', 1)
store.commit('services/setServices', resServices)
// const selectedSite = store.getters['services/selectedSite']
// const selectedSiteState = store.getters['services/selectedSiteState']
const defaultServices = store.getters['services/services']
const forEditService = defaultServices.find(service => service.id === 3)
// expect(selectedSite).toEqual({
// "id": 1,
// "created_at": "2024-02-22T17:08:37.715772388+03:00",
// "updated_at": "2024-02-26T14:11:38.64094899+03:00",
// "deleted_at": null,
// "name": "jsonplaceholder.typicode.com",
// "port": 9965,
// "proxy_ip": "172.25.78.153",
// "device_ip": "172.25.78.153",
// "internet_uri": "localhost",
// "description": "localhost",
// "is_online": true
// })
// expect(selectedSiteState).toEqual('active')
// })
expect(forEditService.name).toEqual('new 3') // default value
expect(forEditService.description).toEqual('new site 3...') // default value
expect(forEditService.port).toEqual(2527) // default value
const updatedServices = updatedService(editedService, defaultServices)
store.commit('services/setServices', updatedServices)
const services = store.getters['services/services']
const editedServiceStore = services.find(service => service.id === 3)
expect(editedServiceStore.name).toEqual('edited and updated test service')
expect(editedServiceStore.description).toEqual('edited and updated test service description')
expect(editedServiceStore.port).toEqual(3436)
})
test('Canceled selected service in store', async () => {
const selectedForEditService =
{
"id": 3,
"created_at": "2024-03-07T11:43:51.027148541+03:00",
"updated_at": "2024-03-07T13:35:24.919273428+03:00",
"deleted_at": null,
"name": "new 3",
"port": 2527,
"proxy_ip": "172.25.78.151",
"device_ip": "172.25.78.151",
"internet_uri": "",
"description": "new site 3...",
"is_online": true
}
await serviceOfServices.selectService(selectedForEditService)
const selectedService = store.getters['services/selectedService']
expect(selectedService.name).not.toBe(null) // Service is selected
expect(selectedService.id).toEqual(3) // Service is selected
expect(selectedService.name).toEqual('new 3') // Service is selected
await serviceOfServices.cancelSelectedService(3)
const cancelSelectedService = store.getters['services/selectedService']
expect(cancelSelectedService).toBe(null) // Canceled selected Service
})
test('Updated services in store after deleting new service with only layout', async () => {
store.commit('services/setServices', resServices)
await serviceOfServices.addNewServiceLayout()
const servicesWithNewServiceLayout = store.getters['services/services']
const forDeleteService = servicesWithNewServiceLayout.find(service => service.id === -1)
expect(forDeleteService).toBeDefined() // before delete service
const updatedServices = removedNewService(servicesWithNewServiceLayout)
store.commit('services/setServices', updatedServices)
const services = store.getters['services/services']
const deletedServiceStore = services.find(service => service.id === -1)
expect(deletedServiceStore).toBeUndefined() // after delete service
})
test('Updated services in store after deleting selected service', async () => {
const deleteServiceId = 3
store.commit('services/setServices', resServices)
const defaultServices = store.getters['services/services']
const forDeleteService = defaultServices.find(service => service.id === 3)
expect(forDeleteService).toBeDefined() // before delete service
const updatedServices = deletedService(deleteServiceId, defaultServices)
store.commit('services/setServices', updatedServices)
const services = store.getters['services/services']
const deletedServiceStore = services.find(service => service.id === 3)
expect(deletedServiceStore).toBeUndefined() // after delete service
})
test('Reset store', async () => {
const selectedForEditService =
{
"id": 3,
"created_at": "2024-03-07T11:43:51.027148541+03:00",
"updated_at": "2024-03-07T13:35:24.919273428+03:00",
"deleted_at": null,
"name": "new 3",
"port": 2527,
"proxy_ip": "172.25.78.151",
"device_ip": "172.25.78.151",
"internet_uri": "",
"description": "new site 3...",
"is_online": true
}
await serviceOfServices.selectService(selectedForEditService)
const selectedService = store.getters['services/selectedService']
expect(selectedService.name).not.toBe(null) // Service is selected
expect(selectedService.id).toEqual(3) // Service is selected
expect(selectedService.name).toEqual('new 3') // Service is selected
await serviceOfServices.addNewServiceLayout()
const services = store.getters['services/services']
expect(services.name).not.toStrictEqual([]) // Not empty services
expect(services[0].id).toEqual(-1) // New Service
await serviceOfServices.resetStore()
const resetSelectedService = store.getters['services/selectedService']
const resetServices = store.getters['services/services']
// console.log('Reset store 11 test', resetSelectedService)
expect(resetSelectedService).toBe(null) // After reset store
expect(resetServices).toStrictEqual([]) // After reset store
})
})

View File

@ -1,12 +1,56 @@
import { expect, test, describe, vi, beforeEach} from "vitest";
import {expect, test, describe, vi, beforeEach} from "vitest"
import AdapterOfUsers from '@adapters/adapterOfUsers/Users'
import ServiceOfUsers from '@services/serviceOfUsers/Users.js'
import { createStore } from 'vuex'
import {store as users} from "@/store/modules/users"
import axios from "axios";
vi.mock('axios')
describe("tests services store with vuex", () => {
const defaultUsers = [
{
"id": 1,
"serviceId": [1, 3],
"firstName": "Leanne 1",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 2,
"serviceId": [1],
"firstName": "Leanne 2",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 3,
"serviceId": [2, 3],
"firstName": "Leanne 3",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 4,
"serviceId": [3],
"firstName": "Leanne 4",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 5,
"serviceId": [4, 5],
"firstName": "Leanne 5",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
]
describe("tests users store with vuex", () => {
const store = createStore({
plugins: [],
modules: {
@ -18,37 +62,270 @@ describe("tests services store with vuex", () => {
store.dispatch('users/resetStore')
})
test('test fetchUsersList function', async () => {
const mockData = [
{
"id": 1,
"first_name": "Leanne",
"last_name": "Graham",
"email": "test@mail.ru",
"role": "admin",
"is_active": true
}
]
const adapterOfUsers = new AdapterOfUsers(import.meta.env.VITE_API_ADDR)
const serviceOfUsers = new ServiceOfUsers(adapterOfUsers, store)
axios.get.mockResolvedValue({
data: mockData,
data: defaultUsers,
})
const expectedData = [
test('Upload Users', async () => {
const users = store.getters['users/users']
expect(users).toEqual([]) // empty users array of store
await serviceOfUsers.getUsers('dev')
const uploadUsers = store.getters['users/users']
expect(uploadUsers).not.toBe([]) // full services array of store
expect(uploadUsers.length).toBeGreaterThan(0) // full services array of store
})
test('Upload users with selected service to store', async () => {
await serviceOfUsers.getUsersByService(1, 'dev')
const expectedUsers = defaultUsers.filter(user => user.serviceId.includes(1))
const usersWithService = store.getters['users/usersWithService']
expect(expectedUsers).toEqual(usersWithService) // users array selected service
})
test('Upload users withhout selected service to store', async () => {
await serviceOfUsers.getUsers('dev')
await serviceOfUsers.getUsersWithoutService(1)
const usersWithoutService = store.getters['users/usersWithoutService']
usersWithoutService.map(user => {
expect(user.serviceId).not.toBe(1)
})
})
test('Created and added new user layout to selected user in store', async () => {
const newUser = await serviceOfUsers.createNewUser()
const newUserStore = store.getters['users/selectedUser']
expect(newUserStore.id).toBe(-1) // new user layout check id
expect(newUserStore).toEqual(newUser) // new user layout equal
})
test('Get selected user from store', async () => {
await serviceOfUsers.createNewUser()
const selectedUser = await serviceOfUsers.getSelectedUser()
const selectedUserStore = store.getters['users/selectedUser']
expect(selectedUserStore).toEqual(selectedUser)
})
test('Set selected user in store', async () => {
await serviceOfUsers.getUsers('dev')
await serviceOfUsers.createNewUser()
const selectedNewUserStore = store.getters['users/selectedUser']
expect(selectedNewUserStore.id).toBe(-1) // new user layout check id
const updatedUser = await serviceOfUsers.setSelectedUser(3)
const updatedUserStore = store.getters['users/selectedUser']
expect(updatedUserStore.id).toBe(3) // updated user check id
expect(updatedUserStore).toEqual(updatedUser)
})
test('Set status user in store', async () => {
const defaultUserStatus = store.getters['users/userStatus']
expect(defaultUserStatus).toBe('inactive')
const updatedUserStatus = await serviceOfUsers.setStatusUser('active')
const updatedUserStatusStore = store.getters['users/userStatus']
expect(updatedUserStatus).toBe('active')
expect(updatedUserStatusStore).toEqual(updatedUserStatus)
})
test('Added user to users with selected service of store', async () => {
await serviceOfUsers.getUsers('dev')
await serviceOfUsers.addUserToService(5, 2)
const usersWithServices = store.getters['users/usersWithService']
// console.log('usersWithServices', usersWithServices)
const userAddedService = usersWithServices.find(user => user.id === 5)
expect(userAddedService).toBeDefined()
expect(userAddedService.serviceId.includes(2)).toBe(true)
})
test('Editing fields values in selected user', async () => {
const forEditUser =
{
"id": 1,
"first_name": "Leanne",
"last_name": "Graham",
"id": 5,
"serviceId": [4, 5],
"firstName": "Leanne 5",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
"is_active": true
}
]
await store.dispatch('users/fetchUsersList', {siteId: 1, mode: "prod"})
const sites = store.getters['users/usersList']
await serviceOfUsers.getUsers('dev')
const users = store.getters['users/users']
const userBeforeEdit = users.find(user => user.id === 5)
expect(userBeforeEdit).toEqual(forEditUser)
await serviceOfUsers.setSelectedUser(5)
await serviceOfUsers.editUserByService({key: "firstName", value: "Leanne 5 edited"})
await serviceOfUsers.editUserByService({key: "lastName", value: "Graham edited"})
const editedUser = store.getters['users/selectedUser']
expect(editedUser.firstName).toEqual("Leanne 5 edited")
expect(editedUser.lastName).toEqual("Graham edited")
await serviceOfUsers.editUserByService({key: "firstName", value: "Leanne 5"}) // return to default value
await serviceOfUsers.editUserByService({key: "lastName", value: "Graham"}) // return to default value
})
test('Deleted user from users with selected service of store', async () => {
await serviceOfUsers.getUsers('dev')
await serviceOfUsers.deleteUserFromService(5, 4)
const usersWithServices = store.getters['users/usersWithService']
const usersWithoutServices = store.getters['users/usersWithoutService']
const userWithService = usersWithServices.find(user => user.id === 5)
const userWithoutService = usersWithoutServices.find(user => user.id === 5)
expect(userWithService).toBeUndefined() // user with service deleted
expect(userWithoutService).toBeDefined() // user without service added
expect(userWithoutService.serviceId.includes(4)).toBe(false) // selected service was deleted from user serviceId
})
test('Saving new user to array users of selected service', async () => {
const newUser =
{
"id": -1,
"serviceId": [],
"firstName": "Leanne 5 New",
"lastName": "Graham New",
"email": "test@mail.ru",
"role": "admin",
}
await serviceOfUsers.getUsers('dev')
store.dispatch('users/updateSelectedUser', newUser)
const users = store.getters['users/users']
const countUsers = users.length
await serviceOfUsers.saveUpdatedDataUser(3)
const usersWithService = store.getters['users/usersWithService']
const newUserAfterAdding = usersWithService.find(user => user.id === countUsers + 1) // Пока не получаем нового юзера с бэка, поэтому задаём id по количеству всех юзеров
expect(newUserAfterAdding).toBeDefined()
expect(newUserAfterAdding.id).toEqual(countUsers + 1)
expect(newUserAfterAdding.firstName).toEqual("Leanne 5 New")
expect(newUserAfterAdding.lastName).toEqual("Graham New")
})
test('Saving edited user to array users of selected service', async () => {
const editedUser =
{
"id": 3,
"serviceId": [2, 3],
"firstName": "Leanne 3 Edited",
"lastName": "Graham Edited",
"email": "test@mail.ru",
"role": "admin",
}
await serviceOfUsers.getUsers('dev')
store.dispatch('users/updateSelectedUser', editedUser)
await serviceOfUsers.saveUpdatedDataUser(2)
const usersWithService = store.getters['users/usersWithService']
const userAfterUpdating = usersWithService.find(user => user.id === 3)
// console.log('userAfterUpdating', userAfterUpdating)
expect(userAfterUpdating).toBeDefined()
expect(userAfterUpdating.id).toEqual(3)
expect(userAfterUpdating.firstName).toEqual("Leanne 3 Edited")
expect(userAfterUpdating.lastName).toEqual("Graham Edited")
})
test('Reset store', async () => {
const selectedUser =
{
"id": 5,
"serviceId": [4, 5],
"firstName": "Leanne 5",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
}
await serviceOfUsers.getUsers('dev')
await serviceOfUsers.setSelectedUser(5)
await serviceOfUsers.setStatusUser('active')
const selectedUserStore = store.getters['users/selectedUser']
const users = store.getters['users/users']
const userStatus = store.getters['users/userStatus']
expect(selectedUser).toEqual(selectedUserStore) // User is selected
expect(users).not.toStrictEqual([]) // Not empty users
expect(userStatus).toEqual('active') // New user status
await serviceOfUsers.resetStore()
const resetSelectedUser = store.getters['users/selectedUser']
const resetUsers = store.getters['users/users']
const resetUserStatus = store.getters['users/userStatus']
// console.log('Reset store 11 test', resetSelectedService)
expect(resetSelectedUser).toBe(null) // After reset store
expect(resetUsers).toStrictEqual([]) // After reset store
expect(resetUserStatus).toEqual('inactive') // After reset store
expect(sites).toEqual(expectedData)
})
})

View File

@ -1,7 +1,6 @@
import {describe, expect, test, beforeEach} from "vitest";
import CaseOfUsersInService from '@useCases/CaseOfUsersInService.js'
import {serviceOfUsers, serviceOfServices, store} from './MockData.js'
import {appUser} from '@mocks/users.js'
describe('tests for caseOfUsersInService', () => {
@ -17,12 +16,6 @@ describe('tests for caseOfUsersInService', () => {
expect(caseOfUsersInService).toBeDefined()
})
test('fetchUsersByService', async () => {
await caseOfUsersInService.fetchUsersByService()
const storeUsers = store.getters['users/siteUsers']
expect(storeUsers).toEqual([appUser])
})
// test('fetchUsersWithoutService', async () => {
// await caseOfUsersInService.fetchUsersWithoutService()
// const storeUsers = store.getters['users/usersWithoutSite']

View File

@ -1,6 +1,6 @@
import {test, describe, expect, vi } from 'vitest'
import { mount} from '@vue/test-utils'
import VTabulator from '@molecules/VTabulator/VTabulator.vue';
import VTabulator from '@molecules/Tabulator/VTabulator.vue';
describe("tests VTabulator component", () => {

View File

@ -0,0 +1,168 @@
import { mount, config} from '@vue/test-utils'
import { expect, test, describe, vi, beforeEach } from 'vitest'
import EditServiceCard from "@organisms/ServicesList/EditServiceCard.vue"
import { createStore } from 'vuex'
import axios from "axios";
import {store as services} from "@/store/modules/services"
import AdapterOfServices from '@adapters/adapterOfServices/Services'
import ServiceOfServices from '@services/serviceOfServices/Services.js'
config.showDeprecationWarnings = false
vi.mock('axios')
describe("tests EditServiceCard component", () => {
const store = createStore({
plugins: [],
modules: {
services,
},
})
const defaultServices = [
{
"id": 1,
"created_at": "2024-03-06T17:31:31.948355541+03:00",
"updated_at": "2024-03-06T17:31:31.948355541+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "https://jsonplaceholder.typicode.com/",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
},
]
const resServices = [
{
"id": 1,
"created_at": "2024-03-06T17:31:31.948355541+03:00",
"updated_at": "2024-03-06T17:31:31.948355541+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"device_ip": "https://jsonplaceholder.typicode.com/",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
},
]
axios.get.mockResolvedValue({
data: defaultServices,
})
beforeEach(async () => {
await store.dispatch('services/resetStore')
})
const adapterOfServices = new AdapterOfServices(import.meta.env.VITE_API_ADDR)
const serviceOfServices = new ServiceOfServices(adapterOfServices, store)
test('EditServiceCard mounted with vuex', async () => {
store.commit('services/setSelectedService', resServices[0])
const selectedService = store.getters['services/selectedService']
const wrapper = mount(EditServiceCard, {
// shallow: true,
global: {
plugins: [store]
},
props: {
serviceOfServices,
id: 1,
},
})
expect(selectedService).not.toBeNull()
expect(selectedService.id).toBe(1)
expect(wrapper.html()).toContain('flex justify-between items-center mb-2')
expect(wrapper.html()).toContain('Онлайн')
expect(wrapper.html()).toContain('Офлайн')
expect(wrapper.text()).toContain('Сохранить')
})
test("Cancel selected service in EditServiceCard", async () => {
config.showDeprecationWarnings = false
await serviceOfServices.fetchServices()
store.commit('services/setSelectedService', resServices[0])
const wrapper = mount(EditServiceCard, {
global: {
plugins: [store]
},
props: {
serviceOfServices,
id: 1,
},
})
wrapper.vm.cancelEditService()
const selectedService = store.getters['services/selectedService']
expect(selectedService).toBeNull()
})
test("Editing selected service in EditServiceCard", async () => {
store.commit('services/setSelectedService', resServices[0])
const wrapper = mount(EditServiceCard, {
global: {
plugins: [store]
},
props: {
serviceOfServices,
id: 1,
},
})
const selectedService = store.getters['services/selectedService']
expect(selectedService.is_online).toEqual(true)
wrapper.vm.editData({key: 'is_online', value: false})
const selectedServiceAfterEditing = store.getters['services/selectedService']
expect(selectedServiceAfterEditing.is_online).toEqual(false)
})
test("Set isSaveData for selected service in EditServiceCard", async () => {
store.commit('services/setSelectedService', resServices[0])
const wrapper = mount(EditServiceCard, {
global: {
plugins: [store]
},
props: {
serviceOfServices,
id: 1,
},
})
const isSaveData = store.getters['services/isSaveData']
expect(isSaveData).toEqual(false)
wrapper.vm.saveData()
const isSaveDataUpdated = store.getters['services/isSaveData']
expect(isSaveDataUpdated).toEqual(true)
})
})

View File

@ -0,0 +1,306 @@
import { mount} from '@vue/test-utils'
import { expect, test, describe, vi, beforeEach } from 'vitest'
import ServiceCard from "@organisms/ServicesList/ServiceCard.vue"
import { createStore} from 'vuex'
import axios from "axios";
import {store as services} from "@/store/modules/services"
import {store as users} from "@/store/modules/users"
import AdapterOfServices from '@adapters/adapterOfServices/Services'
import ServiceOfServices from '@services/serviceOfServices/Services.js'
import AdapterOfUsers from '@adapters/adapterOfUsers/Users'
import ServiceOfUsers from '@services/serviceOfUsers/Users.js'
import CaseOfUsersInService from '@useCases/CaseOfUsersInService.js'
vi.mock('axios')
describe("tests Service Card component", () => {
const store = createStore({
plugins: [],
modules: {
services,
users
},
})
const defaultServices = [
{
"id": 1,
"created_at": "2024-03-06T17:31:31.948355541+03:00",
"updated_at": "2024-03-06T17:31:31.948355541+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "https://jsonplaceholder.typicode.com/",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
},
]
const resServices = [
{
"id": 1,
"created_at": "2024-03-06T17:31:31.948355541+03:00",
"updated_at": "2024-03-06T17:31:31.948355541+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"device_ip": "https://jsonplaceholder.typicode.com/",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
},
]
axios.get.mockResolvedValue({
data: defaultServices,
})
const adapterOfServices = new AdapterOfServices(import.meta.env.VITE_API_ADDR)
const serviceOfServices = new ServiceOfServices(adapterOfServices, store)
const adapterOfUsers = new AdapterOfUsers(import.meta.env.VITE_API_ADDR)
const serviceOfUsers = new ServiceOfUsers(adapterOfUsers, store)
const caseOfUsersInService = new CaseOfUsersInService(serviceOfUsers, serviceOfServices)
beforeEach(() => {
store.dispatch('services/resetStore')
})
test('Service Card mounted with vuex', async () => {
const wrapper = mount(ServiceCard, {
// shallow: true,
global: {
plugins: [store]
},
props: {
serviceOfServices,
caseOfUsersInService,
},
})
// console.log('wrapper.html', wrapper.html())
await serviceOfServices.fetchServices()
store.commit('services/setServicesState', 'active')
const uploadServices = store.getters['services/services']
// const servicesState = store.getters['services/servicesState']
expect(uploadServices).toEqual(resServices) // full services array of store
expect(wrapper.html()).toContain('block w-full p-6 bg-white')
expect(wrapper.text()).toContain('статус')
expect(wrapper.text()).toContain('Порт')
})
test('View EditCard component after select service', async () => {
store.commit('services/setSelectedService', resServices[0])
const selectedService = store.getters['services/selectedService']
const wrapper = mount(ServiceCard, {
global: {
plugins: [store]
},
props: {
serviceOfServices,
caseOfUsersInService,
id: 1,
},
})
const wrapperHtml = wrapper.html()
expect(selectedService).not.toBeNull()
expect(selectedService.id).toBe(1)
expect(wrapperHtml).toContain('Сохранить')
expect(wrapper.find('textarea[name="description"]'))
})
test("Renders buttons - 'Отменить' and 'Удалить' in this service, after click to button delete service", async () => {
beforeEach(() => {
store.dispatch('services/resetStore')
})
const wrapper = mount(ServiceCard, {
global: {
plugins: [store]
},
props: {
serviceOfServices,
caseOfUsersInService,
id: 1,
},
data () {
return {
isDelete: false,
}
},
})
await wrapper.setData({ isDelete: true })
await wrapper.get('.ri-close-line').trigger('click')
expect(wrapper.html()).toContain('Отменить')
expect(wrapper.html()).toContain('Удалить')
})
test("Cancel Renders buttons - 'Отменить' and 'Удалить' in this service, after click to button cancel delete service", async () => {
beforeEach(() => {
store.dispatch('services/resetStore')
})
const wrapper = mount(ServiceCard, {
global: {
plugins: [store]
},
props: {
serviceOfServices,
caseOfUsersInService,
id: 1,
},
data () {
return {
isDelete: true,
}
},
})
// console.log('wrapper.html', wrapper.html())
await wrapper.get('[test-id="canelButton"]').trigger('click')
expect(wrapper.html()).not.toContain('Отменить')
expect(wrapper.html()).not.toContain('Удалить')
})
test('Set setStatus for prop isOnline in ServiceCard', async () => {
const wrapper = mount(ServiceCard, {
global: {
plugins: [store]
},
props: {
serviceOfServices,
isOnline: false
},
data () {
return {
status: {title: 'disable', color: 'bg-red-700'}
}
},
})
// console.log('wrapper.html', wrapper.vm.status)
const defaultStatus = wrapper.vm.status
expect(defaultStatus.title).toContain('disable')
expect(defaultStatus.color).toContain('bg-red-700')
wrapper.vm.setStatus(true)
expect(wrapper.vm.status.title).toBe('enable')
expect(wrapper.html()).toContain('bg-green-700')
})
test('For Editing selected user in ServiceCard', async () => {
const forEditService = {
"id": 1,
"created_at": "2024-03-06T17:31:31.948355541+03:00",
"updated_at": "2024-03-06T17:31:31.948355541+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"device_ip": "https://jsonplaceholder.typicode.com/",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
}
const wrapper = mount(ServiceCard, {
global: {
plugins: [store]
},
props: {
caseOfUsersInService
},
})
const selectedService = store.getters['services/selectedService']
expect(selectedService).toBeNull()
await wrapper.vm.editService(forEditService)
const selectedUserAfterEdit = store.getters['services/selectedService']
const usersWithService = store.getters['users/usersWithService']
expect(selectedUserAfterEdit).not.toBeNull()
expect(selectedUserAfterEdit.id).toBe(1)
usersWithService.map(user => {
expect(user.serviceId.include(1)).toBe(true)
})
})
test("View buttons - 'Отменить' and 'Удалить' after change isDelete for selected service in ServiceCard", async () => {
beforeEach(() => {
store.dispatch('services/resetStore')
})
const wrapper = mount(ServiceCard, {
global: {
plugins: [store]
},
props: {
serviceOfServices,
id: 1,
},
data () {
return {
isDelete: false,
}
},
})
// console.log('wrapper.html', wrapper.html())
const defaultIsDelete = wrapper.vm.isDelete
expect(defaultIsDelete).toBe(false)
await wrapper.get('.ri-close-line').trigger('click') // Рендер отрисовывает только с помощью триггером
// wrapper.vm.deleteService(true)
const updatedIsDelete = wrapper.vm.isDelete
// console.log('wrapper.html', wrapper.html())
expect(updatedIsDelete).toBe(true)
expect(wrapper.html()).toContain('Отменить')
expect(wrapper.html()).toContain('Удалить')
})
})

View File

@ -0,0 +1,154 @@
import { mount} from '@vue/test-utils'
import { expect, test, describe, vi } from 'vitest'
import { toRefs } from 'vue'
import ServicesList from "@organisms/ServicesList/ServicesList.vue"
import { createStore } from 'vuex'
import axios from "axios";
import {store as services} from "@/store/modules/services"
import {store as users} from "@/store/modules/users"
import AdapterOfServices from '@adapters/adapterOfServices/Services.js'
import ServiceOfServices from '@services/serviceOfServices/Services.js'
import AdapterOfUsers from '@adapters/adapterOfUsers/Users'
import ServiceOfUsers from '@services/serviceOfUsers/Users.js'
import CaseOfUsersInService from '@useCases/CaseOfUsersInService.js'
vi.mock('axios')
describe("tests Services List component", () => {
const store = createStore({
plugins: [],
modules: {
services,
users
},
})
const defaultServices = [
{
"id": 1,
"created_at": "2024-03-06T17:31:31.948355541+03:00",
"updated_at": "2024-03-06T17:31:31.948355541+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "https://jsonplaceholder.typicode.com/",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
},
{
"id": 2,
"created_at": "2024-03-07T11:43:51.026265459+03:00",
"updated_at": "2024-03-07T13:35:12.506368972+03:00",
"deleted_at": null,
"name": "new 2",
"port": 4548,
"proxy_ip": "172.25.78.151",
"site_ip": "172.25.78.151",
"internet_uri": "",
"description": "new site 2",
"is_online": true
},
{
"id": 3,
"created_at": "2024-03-07T11:43:51.027148541+03:00",
"updated_at": "2024-03-07T13:35:24.919273428+03:00",
"deleted_at": null,
"name": "new 3",
"port": 2527,
"proxy_ip": "172.25.78.151",
"site_ip": "172.25.78.151",
"internet_uri": "",
"description": "new site 3...",
"is_online": true
}
]
const resServices = [
{
"id": 1,
"created_at": "2024-03-06T17:31:31.948355541+03:00",
"updated_at": "2024-03-06T17:31:31.948355541+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"device_ip": "https://jsonplaceholder.typicode.com/",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
},
{
"id": 2,
"created_at": "2024-03-07T11:43:51.026265459+03:00",
"updated_at": "2024-03-07T13:35:12.506368972+03:00",
"deleted_at": null,
"name": "new 2",
"port": 4548,
"proxy_ip": "172.25.78.151",
"device_ip": "172.25.78.151",
"internet_uri": "",
"description": "new site 2",
"is_online": true
},
{
"id": 3,
"created_at": "2024-03-07T11:43:51.027148541+03:00",
"updated_at": "2024-03-07T13:35:24.919273428+03:00",
"deleted_at": null,
"name": "new 3",
"port": 2527,
"proxy_ip": "172.25.78.151",
"device_ip": "172.25.78.151",
"internet_uri": "",
"description": "new site 3...",
"is_online": true
}
]
axios.get.mockResolvedValue({
data: defaultServices,
})
const adapterOfServices = new AdapterOfServices(import.meta.env.VITE_API_ADDR)
const serviceOfServices = new ServiceOfServices(adapterOfServices, store)
const adapterOfUsers = new AdapterOfUsers(import.meta.env.VITE_API_ADDR)
const serviceOfUsers = new ServiceOfUsers(adapterOfUsers, store)
const caseOfUsersInService = new CaseOfUsersInService(serviceOfUsers, serviceOfServices)
test('Services List mounted with vuex', async () => {
const wrapper = mount(ServicesList, {
// shallow: true,
global: {
plugins: [store]
},
props: {
serviceOfServices,
caseOfUsersInService,
},
setup (props) {
const {serviceOfServices} = toRefs(props)
serviceOfServices.value.fetchServices()
},
})
// console.log('wrapper.vm', wrapper.vm)
await serviceOfServices.fetchServices()
const uploadServices = store.getters['services/services']
expect(uploadServices).toEqual(resServices) // full services array of store
expect(wrapper.html()).toContain('grid grid-cols-1')
expect(wrapper.text()).toContain('Добавить сайт')
})
})

View File

@ -0,0 +1,163 @@
import { mount} from '@vue/test-utils'
import {createStore} from "vuex"
import { expect, test, describe, vi, beforeEach } from 'vitest'
import UsersManager from '@organisms/UsersManager/UsersManager.vue'
import axios from "axios"
import {store as services} from "@/store/modules/services"
import {store as users} from "@/store/modules/users"
import AdapterOfServices from '@adapters/adapterOfServices/Services'
import ServiceOfServices from '@services/serviceOfServices/Services.js'
import AdapterOfUsers from '@adapters/adapterOfUsers/Users'
import ServiceOfUsers from '@services/serviceOfUsers/Users.js'
import CaseOfUsersInService from '@useCases/CaseOfUsersInService.js'
vi.mock('axios')
describe("tests UsersManager component", () => {
const store = createStore({
plugins: [],
modules: {
services,
users
},
})
vi.mock('tabulator-tables', () => {
const mockTabulator = vi.fn().mockImplementation(() => ({
// Mock implementation details
}));
return { TabulatorFull: mockTabulator }; // Adjust based on what you're trying to mock
});
const adapterOfServices = new AdapterOfServices(import.meta.env.VITE_API_ADDR)
const serviceOfServices = new ServiceOfServices(adapterOfServices, store)
const adapterOfUsers = new AdapterOfUsers(import.meta.env.VITE_API_ADDR)
const serviceOfUsers = new ServiceOfUsers(adapterOfUsers, store)
const caseOfUsersInService = new CaseOfUsersInService(serviceOfUsers, serviceOfServices)
const mockData = [
{
"id": 1,
"serviceId": [1, 3],
"firstName": "Leanne 1",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
]
axios.get.mockResolvedValue({
data: mockData,
})
beforeEach(async () => {
store.dispatch('users/resetStore')
})
test('UsersManager mounted with vuex', async () => {
const wrapper = mount(UsersManager, {
global: {
plugins: [store],
props: {
serviceOfUsers
}
}
})
const userStatus = store.getters['users/userStatus']
expect(userStatus).toBe('inactive')
expect(wrapper.html()).toContain('w-full flex justify-between grow gap-4')
expect(wrapper.text()).toContain('Список пользователей')
})
test('View UserEditor component, after click to create user button', async () => {
await serviceOfUsers.getUsersByService(1, 'dev')
const wrapper = mount(UsersManager, {
global: {
plugins: [store]
},
props: {
serviceOfUsers
}
})
const buttonCreate = wrapper.find('[test-id="toggle-new-user"]')
await buttonCreate.trigger('click')
const userStatus = store.getters['users/userStatus']
const wrapperHtml = wrapper.html()
expect(userStatus).toBe('create')
expect(wrapperHtml).toContain('Создать пользователя')
expect(wrapperHtml).toContain('Закрыть')
expect(wrapper.find('[test-id="new-user-container"]'))
})
test('View UserEditor component, after click to select user button', async () => {
await serviceOfUsers.getUsersByService(1, 'dev')
const wrapper = mount(UsersManager, {
global: {
plugins: [store]
},
props: {
serviceOfUsers,
caseOfUsersInService,
},
})
const buttonSelect = wrapper.find('[test-id="toggle-add-user"]')
await buttonSelect.trigger('click')
const userStatus = store.getters['users/userStatus']
const wrapperHtml = wrapper.html()
expect(userStatus).toBe('select')
expect(wrapperHtml).toContain('Выбрать пользователя')
expect(wrapperHtml).toContain('Закрыть')
expect(wrapper.find('[action="add"]'))
})
test('Close UsersForSelection, after change userStatus', async () => {
await serviceOfUsers.getUsersByService(1, 'dev')
await serviceOfUsers.setStatusUser('select')
const wrapper = mount(UsersManager, {
global: {
plugins: [store]
},
props: {
serviceOfUsers,
caseOfUsersInService,
},
})
const userStatus = store.getters['users/userStatus']
const wrapperHtml = wrapper.html()
expect(userStatus).toBe('select')
expect(wrapperHtml).toContain('Выбрать пользователя')
expect(wrapperHtml).toContain('Закрыть')
expect(wrapper.find('[action="add"]'))
wrapper.vm.closeUserPanel()
const userStatusAfterClose = store.getters['users/userStatus']
expect(userStatusAfterClose).toBe('inactive')
})
})

View File

@ -1,6 +1,6 @@
import {test, describe, expect} from 'vitest'
import { mount} from '@vue/test-utils'
import UsersManagerContainer from '@organisms/UsersManager/UsersManagerContainer.vue';
import UsersManagerContainer from '@organisms/UsersManager/Container.vue';
describe("tests UsersManagerContainer component", () => {
test('mount test of UsersManagerContainer', async () => {

View File

@ -0,0 +1,181 @@
import { expect, test, describe, vi, beforeEach } from 'vitest'
import {createStore, mapGetters} from "vuex"
import { mount} from '@vue/test-utils'
import UsersSelection from '@organisms/UsersManager/UsersForSelection.vue'
import VTabulator from '@molecules/Tabulator/VTabulator.vue'
import axios from "axios"
import {store as services} from "@/store/modules/services"
import {store as users} from "@/store/modules/users"
import AdapterOfServices from '@adapters/adapterOfServices/Services'
import ServiceOfServices from '@services/serviceOfServices/Services.js'
import AdapterOfUsers from '@adapters/adapterOfUsers/Users'
import ServiceOfUsers from '@services/serviceOfUsers/Users.js'
import CaseOfUsersInService from '@useCases/CaseOfUsersInService.js'
vi.mock('axios')
const defaultUsers = [
{
"id": 1,
"serviceId": [1, 3],
"firstName": "Leanne 1",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 2,
"serviceId": [1],
"firstName": "Leanne 2",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 3,
"serviceId": [2, 3],
"firstName": "Leanne 3",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 4,
"serviceId": [3],
"firstName": "Leanne 4",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 5,
"serviceId": [4, 5],
"firstName": "Leanne 5",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
]
describe("tests UsersForSelection component", () => {
const store = createStore({
plugins: [],
modules: {
services,
users
},
})
beforeEach(async () => {
store.dispatch('users/resetStore')
})
vi.mock('tabulator-tables', () => {
const mockTabulator = vi.fn().mockImplementation(() => ({
// Mock implementation details
}))
return { TabulatorFull: mockTabulator }; // Adjust based on what you're trying to mock
})
axios.get.mockResolvedValue({
data: defaultUsers,
})
const adapterOfServices = new AdapterOfServices(import.meta.env.VITE_API_ADDR)
const serviceOfServices = new ServiceOfServices(adapterOfServices, store)
const adapterOfUsers = new AdapterOfUsers(import.meta.env.VITE_API_ADDR)
const serviceOfUsers = new ServiceOfUsers(adapterOfUsers, store)
const caseOfUsersInService = new CaseOfUsersInService(serviceOfUsers, serviceOfServices)
test('mount test of UsersManagerUsersTable', async () => {
const wrapper = mount(UsersSelection, {
global: {
plugins: [store],
props: {
caseOfUsersInService
}
}
})
expect(wrapper.exists()).toBe(true)
})
test('Added user to selected Service', async () => {
const selectedService = [
{
"id": 1,
"created_at": "2024-03-06T17:31:31.948355541+03:00",
"updated_at": "2024-03-06T17:31:31.948355541+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"device_ip": "https://jsonplaceholder.typicode.com/",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
},
]
const addedUser = {
"id": 3,
"serviceId": [2, 3],
"firstName": "Leanne 3",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
}
await serviceOfServices.fetchServices()
await serviceOfServices.selectService(selectedService[0])
await serviceOfUsers.getUsersByService(1, 'dev')
await serviceOfUsers.setSelectedUser(addedUser.id)
const wrapper = mount(UsersSelection, {
global: {
plugins: [store]
},
components: {VTabulator},
props: {
serviceOfUsers,
caseOfUsersInService,
users: defaultUsers,
},
computed: {
...mapGetters('users', ['selectedUser', 'usersWithoutService']),
},
})
const usersWithServices = store.getters['users/usersWithService']
const forDeleteUserFromService = usersWithServices.find(user => user.id === addedUser.id)
expect(forDeleteUserFromService).toBeUndefined()
wrapper.vm.addUser(addedUser)
setTimeout(() => {
const usersWithServicesAfterDelete = store.getters['users/usersWithService']
const usersWithoutService = store.getters['users/usersWithoutService']
const userFromServiceAfterDelete = usersWithServicesAfterDelete.find(user => user.id === addedUser.id)
const userWithoutServiceAfterDelete = usersWithoutService.find(user => user.id === addedUser.id)
expect(userFromServiceAfterDelete).toBeDefined()
expect(userWithoutServiceAfterDelete).toBeUndefined()
expect(userWithoutServiceAfterDelete.id).toEqual(addedUser.id)
}, 100)
})
})

View File

@ -0,0 +1,226 @@
import { expect, test, describe, vi, beforeEach } from 'vitest'
import {createStore, mapGetters} from "vuex"
import { mount} from '@vue/test-utils'
import UsersTable from '@organisms/UsersManager/UsersTable.vue'
import VTabulator from '@molecules/Tabulator/VTabulator.vue'
import axios from "axios"
import {store as services} from "@/store/modules/services"
import {store as users} from "@/store/modules/users"
import AdapterOfServices from '@adapters/adapterOfServices/Services'
import ServiceOfServices from '@services/serviceOfServices/Services.js'
import AdapterOfUsers from '@adapters/adapterOfUsers/Users'
import ServiceOfUsers from '@services/serviceOfUsers/Users.js'
import CaseOfUsersInService from '@useCases/CaseOfUsersInService.js'
vi.mock('axios')
const defaultUsers = [
{
"id": 1,
"serviceId": [1, 3],
"firstName": "Leanne 1",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 2,
"serviceId": [1],
"firstName": "Leanne 2",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 3,
"serviceId": [2, 3],
"firstName": "Leanne 3",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 4,
"serviceId": [3],
"firstName": "Leanne 4",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 5,
"serviceId": [4, 5],
"firstName": "Leanne 5",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
]
describe("tests UsersManagerUsersTable component", () => {
const store = createStore({
plugins: [],
modules: {
services,
users
},
})
beforeEach(async () => {
store.dispatch('users/resetStore')
})
vi.mock('tabulator-tables', () => {
const mockTabulator = vi.fn().mockImplementation(() => ({
// Mock implementation details
}))
return { TabulatorFull: mockTabulator }; // Adjust based on what you're trying to mock
})
axios.get.mockResolvedValue({
data: defaultUsers,
})
const adapterOfServices = new AdapterOfServices(import.meta.env.VITE_API_ADDR)
const serviceOfServices = new ServiceOfServices(adapterOfServices, store)
const adapterOfUsers = new AdapterOfUsers(import.meta.env.VITE_API_ADDR)
const serviceOfUsers = new ServiceOfUsers(adapterOfUsers, store)
const caseOfUsersInService = new CaseOfUsersInService(serviceOfUsers, serviceOfServices)
test('mount test of UsersManagerUsersTable', async () => {
const wrapper = mount(UsersTable, {
global: {
plugins: [store],
props: {
serviceOfUsers
}
}
})
expect(wrapper.exists()).toBe(true)
})
test('For Editing select current user in UserEditor', async () => {
const forEditUser = {
"id": 1,
"serviceId": [1, 3],
"firstName": "Leanne 1",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
}
await serviceOfUsers.getUsers()
const wrapper = mount(UsersTable, {
global: {
plugins: [store]
},
components: {VTabulator},
props: {
serviceOfUsers
},
computed: {
...mapGetters('users', ['userStatus']),
},
})
const selectedUser = store.getters['users/selectedUser']
expect(selectedUser).toBeNull()
expect(wrapper.vm.userStatus).toBe('inactive')
wrapper.vm.editUser(forEditUser)
const selectedUserAfterEdit = store.getters['users/selectedUser']
const userStatus = store.getters['users/userStatus']
expect(selectedUserAfterEdit).not.toBeNull()
expect(selectedUserAfterEdit.id).toEqual(forEditUser.id)
expect(userStatus).toBe('edit')
})
test('Delete user from selected Service', async () => {
const selectedService = [
{
"id": 1,
"created_at": "2024-03-06T17:31:31.948355541+03:00",
"updated_at": "2024-03-06T17:31:31.948355541+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"device_ip": "https://jsonplaceholder.typicode.com/",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
},
]
const forDeleteUser = {
"id": 2,
"serviceId": [1],
"firstName": "Leanne 2",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
}
await serviceOfServices.fetchServices()
await serviceOfServices.selectService(selectedService[0])
await serviceOfUsers.getUsersByService(1, 'dev')
await serviceOfUsers.setSelectedUser(forDeleteUser.id)
const wrapper = mount(UsersTable, {
global: {
plugins: [store]
},
components: {VTabulator},
props: {
serviceOfUsers,
caseOfUsersInService,
users: defaultUsers,
},
computed: {
...mapGetters('users', ['selectedUser']),
},
})
const usersWithServices = store.getters['users/usersWithService']
const userStatus = store.getters['users/userStatus']
const forDeleteUserFromService = usersWithServices.find(user => user.id === forDeleteUser.id)
expect(forDeleteUserFromService).not.toBeNull()
expect(userStatus).toBe('inactive')
wrapper.vm.deleteUser(forDeleteUser)
setTimeout(() => {
const userStatusAfterDelete = store.getters['users/userStatus']
const usersWithServicesAfterDelete = store.getters['users/usersWithService']
const usersWithoutService = store.getters['users/usersWithoutService']
const userFromServiceAfterDelete = usersWithServicesAfterDelete.find(user => user.id === forDeleteUser.id)
const userWithoutServiceAfterDelete = usersWithoutService.find(user => user.id === forDeleteUser.id)
expect(userStatusAfterDelete).toBe('select')
expect(userFromServiceAfterDelete).toBeUndefined()
expect(userWithoutServiceAfterDelete).toBeDefined()
expect(userWithoutServiceAfterDelete.id).toEqual(forDeleteUser.id)
}, 100)
})
})

View File

@ -1,6 +1,6 @@
import {test, describe, expect} from 'vitest'
import { mount} from '@vue/test-utils'
import UsersManagerTitle from '@organisms/UsersManager/UsersManagerTitle.vue';
import UsersManagerTitle from '@organisms/UsersManager/Title.vue';
describe("tests UsersManagerTitle component", () => {
test('mount test of UsersManagerTitle', async () => {

View File

@ -0,0 +1,323 @@
import { mount} from '@vue/test-utils'
import { expect, test, describe, vi, beforeEach } from 'vitest'
import UserEditor from '@organisms/UsersManager/UserEditor.vue';
import { createStore, mapGetters } from 'vuex'
import axios from "axios"
import {store as users} from "@/store/modules/users"
import {store as services} from "@/store/modules/services"
import AdapterOfUsers from '@adapters/adapterOfUsers/Users'
import ServiceOfUsers from '@services/serviceOfUsers/Users.js'
vi.mock('axios')
const defaultUsers = [
{
"id": 1,
"serviceId": [1, 3],
"firstName": "Leanne 1",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 2,
"serviceId": [1],
"firstName": "Leanne 2",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 3,
"serviceId": [2, 3],
"firstName": "Leanne 3",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 4,
"serviceId": [3],
"firstName": "Leanne 4",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
{
"id": 5,
"serviceId": [4, 5],
"firstName": "Leanne 5",
"lastName": "Graham",
"email": "test@mail.ru",
"role": "admin",
},
]
describe("tests UserEditor component", () => {
const store = createStore({
plugins: [],
modules: {
services,
users
},
})
beforeEach( async () => {
store.dispatch('users/resetStore')
})
axios.get.mockResolvedValue({
data: defaultUsers,
})
const adapterOfUsers = new AdapterOfUsers(import.meta.env.VITE_API_ADDR)
const serviceOfUsers = new ServiceOfUsers(adapterOfUsers, store)
test('UserEditor mounted with vuex', async () => {
const wrapper = mount(UserEditor, {
shallow: true,
global: {
plugins: [store]
},
props: {
serviceOfUsers
}
})
expect(wrapper.exists()).toBe(true)
})
test('Editing selected user in UserEditor', async () => {
store.dispatch('users/updateSelectedUser', defaultUsers[0])
const wrapper = mount(UserEditor, {
shallow: true,
global: {
plugins: [store]
},
props: {
serviceOfUsers
},
})
const selectedUser = store.getters['users/selectedUser']
expect(selectedUser.firstName).toBe('Leanne 1')
wrapper.vm.editData({key: 'firstName', value: 'test Editing'})
const selectedUserAfterEdit = store.getters['users/selectedUser']
expect(selectedUserAfterEdit.firstName).toBe('test Editing')
})
test('Saving after editing selected user in UserEditor', async () => {
const resServices = [
{
"id": 1,
"created_at": "2024-03-06T17:31:31.948355541+03:00",
"updated_at": "2024-03-06T17:31:31.948355541+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"device_ip": "https://jsonplaceholder.typicode.com/",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
},
]
const editedUser = {
"id": 3,
"serviceId": [1, 3],
"firstName": "Leanne 3 edited",
"lastName": "Graham edited",
"email": "test@mail.ru",
"role": "admin",
}
await serviceOfUsers.getUsersByService(resServices[0].id, 'dev')
store.dispatch('services/editSelectedService', resServices)
store.dispatch('users/updateSelectedUser', editedUser)
const wrapper = mount(UserEditor, {
shallow: true,
global: {
plugins: [store]
},
props: {
serviceOfUsers
},
computed: {
...mapGetters('services', ["selectedService"]),
...mapGetters('users', ['selectedUser']),
},
})
const selectedUser = store.getters['users/selectedUser']
wrapper.vm.saveUser()
const updatedUsersWithService = store.getters['users/usersWithService']
const userStatus = store.getters['users/userStatus']
const updatedUser = updatedUsersWithService.find(user => user.id === selectedUser.id)
expect(userStatus).toBe('inactive')
expect(updatedUser.firstName).toBe(editedUser.firstName)
expect(updatedUser.lastName).toBe(editedUser.lastName)
})
test('Saving after creating new user in UserEditor', async () => {
const resServices = [
{
"id": 1,
"created_at": "2024-03-06T17:31:31.948355541+03:00",
"updated_at": "2024-03-06T17:31:31.948355541+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"device_ip": "https://jsonplaceholder.typicode.com/",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
},
]
const newUser = {
"id": -1,
"serviceId": [],
"firstName": "Leanne 3 new",
"lastName": "Graham new",
"email": "test@mail.ru",
"role": "admin",
}
await serviceOfUsers.getUsersByService(resServices[0].id, 'dev')
store.dispatch('services/editSelectedService', resServices)
store.dispatch('users/updateSelectedUser', newUser)
const wrapper = mount(UserEditor, {
shallow: true,
global: {
plugins: [store]
},
props: {
serviceOfUsers
},
computed: {
...mapGetters('services', ["selectedService"]),
...mapGetters('users', ['selectedUser']),
},
})
wrapper.vm.saveUser()
const updatedUsersWithService = store.getters['users/usersWithService']
const userStatus = store.getters['users/userStatus']
const updatedUser = updatedUsersWithService[0]
expect(userStatus).toBe('inactive')
expect(updatedUser.firstName).toBe(newUser.firstName)
expect(updatedUser.lastName).toBe(newUser.lastName)
})
test('Get Password for selected user in UserEditor', async () => {
const editedUser = {
"id": 3,
"serviceId": [1, 3],
"firstName": "Leanne 3 edited",
"lastName": "Graham edited",
"email": "test@mail.ru",
"role": "admin",
}
store.dispatch('users/updateSelectedUser', editedUser)
const wrapper = mount(UserEditor, {
shallow: true,
global: {
plugins: [store]
},
props: {
serviceOfUsers
},
})
const selectedUser = store.getters['users/selectedUser']
expect(selectedUser).not.toHaveProperty('password')
wrapper.vm.getPassword()
const selectedUserAfterAddPass = store.getters['users/selectedUser']
expect(selectedUserAfterAddPass).toHaveProperty('password')
})
test('toggle view field Password for selected user in UserEditor', async () => {
const wrapper = mount(UserEditor, {
shallow: true,
global: {
plugins: [store]
},
props: {
serviceOfUsers
},
data() {
return {
showNewPassword: false,
newPasswordType: 'password',
}
},
})
// await wrapper.setData({ showNewPassword: true })
// console.log('passwordField', passwordField.attributes().type)
wrapper.vm.togglePass()
expect(wrapper.vm.showNewPassword).toBe(true)
expect(wrapper.vm.newPasswordType).toBe('text')
})
test('toggle view field RepeatPassword for selected user in UserEditor', async () => {
const wrapper = mount(UserEditor, {
shallow: true,
global: {
plugins: [store]
},
props: {
serviceOfUsers
},
data() {
return {
showRepeatPassword: false,
repeatPasswordType: 'password',
}
},
})
wrapper.vm.toggleRepeatPass()
expect(wrapper.vm.showRepeatPassword).toBe(true)
expect(wrapper.vm.repeatPasswordType).toBe('text')
})
})

View File

@ -1,125 +0,0 @@
import { mount} from '@vue/test-utils'
import { expect, test, describe, vi, beforeEach } from 'vitest'
import UsersManager from '@organisms/UsersManager/UsersManager.vue';
import axios from "axios";
import {store, serviceOfUsers} from './StaticMocks.js'
vi.mock('axios')
describe("tests SitesManagerPage component mounted with vuex", () => {
vi.mock('tabulator-tables', () => {
const mockTabulator = vi.fn().mockImplementation(() => ({
// Mock implementation details
}));
return { TabulatorFull: mockTabulator }; // Adjust based on what you're trying to mock
});
beforeEach(async () => {
store.dispatch('users/resetStore')
const mockData = [
{
"id": 1,
"created_at": "2024-02-22T17:08:37.715772388+03:00",
"updated_at": "2024-02-26T14:11:38.64094899+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "172.25.78.153",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
}
]
axios.get.mockResolvedValue({
data: mockData,
})
await store.dispatch('services/uploadSites')
store.dispatch('services/uploadAndSelectService', 1)
})
test('test UsersManager mounted with vuex', async () => {
const wrapper = mount(UsersManager, {
global: {
plugins: [store],
props: {
serviceOfUsers
}
}
})
const componentState = wrapper.vm.componentState
const gridCols = wrapper.vm.gridCols
expect(componentState).toBe('view')
expect(gridCols).toBe('grid-cols-1')
})
test('test UsersManager create user button', async () => {
const wrapper = mount(UsersManager, {
global: {
plugins: [store]
},
props: {
serviceOfUsers
}
})
await wrapper.vm.openUserPanelOfCreate()
let componentState = wrapper.vm.componentState
let gridCols = wrapper.vm.gridCols
let wrapperHtml = wrapper.html()
expect(componentState).toBe('create')
expect(gridCols).toBe('grid-cols-2')
expect(wrapperHtml).toContain("new-user-container")
await wrapper.vm.openUserPanelOfSelect()
wrapperHtml = wrapper.html()
componentState = wrapper.vm.componentState
gridCols = wrapper.vm.gridCols
expect(componentState).toBe('select')
expect(gridCols).toBe('grid-cols-2')
expect(wrapperHtml).toContain("Выбрать пользователя")
expect(wrapperHtml).toContain("Выбрать пользователя")
await wrapper.vm.closeUserPanel()
wrapperHtml = wrapper.html()
componentState = wrapper.vm.componentState
gridCols = wrapper.vm.gridCols
expect(componentState).toBe('view')
expect(gridCols).toBe('grid-cols-1')
expect(wrapperHtml).not.toContain("Выбрать пользователя")
expect(wrapperHtml).not.toContain("new-user-container")
})
test('test UsersManager select user button', async () => {
const wrapper = mount(UsersManager, {
shallow: true,
global: {
plugins: [store]
},
props: {
serviceOfUsers
}
})
await wrapper.vm.openUserPanelOfSelect()
const usersOffSite = store.getters['users/usersOffSite']
const componentState = wrapper.vm.componentState
const gridCols = wrapper.vm.gridCols
expect(componentState).toBe('select')
expect(gridCols).toBe('grid-cols-2')
expect(usersOffSite).toEqual([{id: 1, name: 'user1'}, {id: 2, name: 'user2'}])
})
})

View File

@ -1,17 +0,0 @@
import {test, describe, expect} from 'vitest'
import { mount} from '@vue/test-utils'
import UsersManagerUsersTable from '@organisms/UsersManager/UsersManagerUsersTable.vue';
describe("tests UsersManagerUsersTable component", () => {
test('mount test of UsersManagerUsersTable', async () => {
const wrapper = mount(UsersManagerUsersTable, {
shallow: true,
})
expect(wrapper.exists()).toBe(true)
})
})

View File

@ -1,56 +0,0 @@
import { mount} from '@vue/test-utils'
import { expect, test, describe, vi, beforeEach } from 'vitest'
import UsersManagerUserEditor from '@organisms/UsersManager/UsersManagerUserEditor.vue';
import { createStore } from 'vuex'
import {store as users} from '@/store/modules/users';
import axios from "axios";
vi.mock('axios')
describe("tests UsersManagerUserEditor component mounted with vuex", () => {
const store = createStore({
plugins: [],
modules: {
users
},
})
beforeEach( async () => {
store.dispatch('users/resetStore')
const mockData = [
{
"id": 1,
"created_at": "2024-02-22T17:08:37.715772388+03:00",
"updated_at": "2024-02-26T14:11:38.64094899+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "172.25.78.153",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
}
]
axios.get.mockResolvedValue({
data: mockData,
})
await store.dispatch('services/uploadSites')
store.dispatch('services/uploadAndSelectService', 1)
})
test('tests UsersManager mounted with vuex', async () => {
const wrapper = mount(UsersManagerUserEditor, {
shallow: true,
global: {
plugins: [store]
}
})
expect(wrapper.exists()).toBe(true)
})
})

View File

@ -1,15 +1,17 @@
import { mount} from '@vue/test-utils'
import { expect, test, describe, vi } from 'vitest'
import Sites from '@pages/SitesManagerPage/SitesManagerPage.vue';
import Services from '@pages/ServicesManagerPage/ServicesManagerPage.vue';
import { createStore } from 'vuex'
import {store as services} from '@/store/modules/services';
import {store as users} from '@/store/modules/users';
import axios from "axios";
import {store as services} from "@/store/modules/services"
import {store as users} from "@/store/modules/users"
import AdapterOfServices from '@adapters/adapterOfServices/Services'
import ServiceOfServices from '@services/serviceOfServices/Services.js'
vi.mock('axios')
describe("tests App mounted with vuex", () => {
describe("tests Services Manager Page component", () => {
const store = createStore({
plugins: [],
modules: {
@ -18,48 +20,64 @@ describe("tests App mounted with vuex", () => {
},
})
const mockData = [
const defaultServices = [
{
"id": 1,
"first_name": "Leanne",
"last_name": "Graham",
"email": "test@mail.ru",
"role": "admin",
"is_active": true
}
"created_at": "2024-03-06T17:31:31.948355541+03:00",
"updated_at": "2024-03-06T17:31:31.948355541+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "https://jsonplaceholder.typicode.com/",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
},
]
const resServices = [
{
"id": 1,
"created_at": "2024-03-06T17:31:31.948355541+03:00",
"updated_at": "2024-03-06T17:31:31.948355541+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"device_ip": "https://jsonplaceholder.typicode.com/",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
},
]
axios.get.mockResolvedValue({
data: mockData,
data: defaultServices,
})
test('tests App mounted with vuex', async () => {
const wrapper = mount(Sites, {
shallow: true,
const adapterOfServices = new AdapterOfServices(import.meta.env.VITE_API_ADDR)
const serviceOfServices = new ServiceOfServices(adapterOfServices, store)
test('Services Manager Page mounted with vuex', async () => {
const wrapper = mount(Services, {
// shallow: true,
global: {
plugins: [store]
}
})
const siteId = 1
const answer = await wrapper.vm.selectSite(siteId, "production")
// console.log('wrapper.vm', wrapper.vm)
const usersList = store.getters['users/usersList']
const componentState = store.getters['users/componentState']
const selectedService = store.getters['services/selectedService']
await serviceOfServices.fetchServices()
expect(usersList).toEqual([{
"id": 1,
"first_name": "Leanne",
"last_name": "Graham",
"email": "test@mail.ru",
"role": "admin",
"is_active": true
}])
expect(componentState).toEqual('active')
expect(selectedService).toBe(null)
expect(answer).toBe("ok")
const uploadServices = store.getters['services/services']
expect(uploadServices).toEqual(resServices) // full services array of store
expect(wrapper.html()).toContain('me-2 mb-6')
expect(wrapper.text()).toContain('На главную')
})
})