feat [P-227]: назначение тестов по кнопке
This commit is contained in:
1 parent
b83ecd147b
commit
305d4228c8
5 files changed
+170
-80
No files matched your search
@@ -48,7 +48,7 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { computed, ref } from 'vue';
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { getEmployees, spravURL } from '@/utils/axios-api';
|
||||
import { checkremote } from '@/utils/universal_functions.js';
|
||||
|
||||
@@ -59,6 +59,18 @@ export default {
|
||||
emits: ['update:modelValue'],
|
||||
setup(props, { emit }) {
|
||||
const selectedEmployees = ref(props.modelValue || []);
|
||||
|
||||
// Watch for external changes to modelValue
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(newValue) => {
|
||||
if (newValue !== undefined) {
|
||||
selectedEmployees.value = [...newValue];
|
||||
}
|
||||
},
|
||||
{ deep: true },
|
||||
);
|
||||
|
||||
const groupedEmployees = ref([]);
|
||||
const allEmployees = computed(() => [...groupedEmployees.value]);
|
||||
|
||||
@@ -89,7 +101,7 @@ export default {
|
||||
if (selectedEmployees.value.length === allEmployees.value.length) {
|
||||
selectedEmployees.value = [];
|
||||
} else {
|
||||
selectedEmployees.value = allEmployees.value.map(emp => emp.id);
|
||||
selectedEmployees.value = allEmployees.value.map((emp) => emp.id);
|
||||
}
|
||||
emit('update:modelValue', selectedEmployees.value);
|
||||
};
|
||||
@@ -101,7 +113,7 @@ export default {
|
||||
handleSelectAll,
|
||||
checkremote,
|
||||
spravURL,
|
||||
allEmployees
|
||||
allEmployees,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -17,32 +17,6 @@
|
||||
variant="outlined"
|
||||
></v-textarea>
|
||||
</div>
|
||||
<v-divider></v-divider>
|
||||
<div class="flex-grow-0 flex-shrink-1 d-flex">
|
||||
<div class="d-flex align-center">
|
||||
<span class="text-overline text-grey text-center">Публикация новости: </span>
|
||||
<v-switch
|
||||
v-model="localForm.createnews"
|
||||
class="px-2"
|
||||
density="comfortable"
|
||||
hide-details
|
||||
color="primary"
|
||||
:label="localForm.createnews ? 'да' : 'нет'"
|
||||
></v-switch>
|
||||
</div>
|
||||
<div class="d-flex align-center ml-2" v-if="isTestRoute">
|
||||
<span class="text-overline text-grey text-center">Назначить: </span>
|
||||
<v-switch
|
||||
v-model="localForm.appoint"
|
||||
class="px-2"
|
||||
density="comfortable"
|
||||
hide-details
|
||||
color="primary"
|
||||
:label="localForm.appoint ? 'да' : 'нет'"
|
||||
></v-switch>
|
||||
<SearcEmployess v-if="localForm.appoint" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-overline text-grey">Дата и время:</div>
|
||||
<div class="d-flex justify-space-around">
|
||||
<div class="d-flex ga-3 align-center">
|
||||
|
||||
@@ -94,6 +94,19 @@
|
||||
</v-img>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Выбор сотрудников для назначения теста -->
|
||||
<div v-if="isTest" class="mt-4">
|
||||
<v-divider class="mb-4"></v-divider>
|
||||
<p class="text-subtitle-1 mb-2">Назначить тест сотрудникам (необязательно)</p>
|
||||
<SearcEmployess
|
||||
v-model="selectedEmployees"
|
||||
@update:modelValue="val => selectedEmployees = val"
|
||||
/>
|
||||
<p v-if="selectedEmployees?.length" class="mt-2 text-grey">
|
||||
Выбрано сотрудников: {{ selectedEmployees.length }}
|
||||
</p>
|
||||
</div>
|
||||
</v-card-text>
|
||||
</template>
|
||||
<v-card-actions>
|
||||
@@ -291,14 +304,15 @@
|
||||
|
||||
<script>
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { createVote, getEmployees, createTest } from '@/utils/axios-api';
|
||||
import { createVote, getEmployees, createTest, assignTest } from '@/utils/axios-api';
|
||||
import DateSelect from '@/components/UI/date-select.vue';
|
||||
import MainInfo from '@/components/vote/ConstructorVote/MainInfo.vue';
|
||||
import CreatedVote from '@/components/vote/ConstructorVote/CreatedVote.vue';
|
||||
import NewQuestion from '@/components/vote/ConstructorVote/NewQuestion.vue';
|
||||
import SearcEmployess from '@/components/UI/SearcEmployess.vue';
|
||||
|
||||
export default {
|
||||
components: { NewQuestion, CreatedVote, MainInfo, DateSelect },
|
||||
components: { NewQuestion, CreatedVote, MainInfo, DateSelect, SearcEmployess },
|
||||
props: {
|
||||
isTest: {
|
||||
type: Boolean,
|
||||
@@ -328,6 +342,7 @@ export default {
|
||||
|
||||
const testImage = ref(null); // Для хранения основного изображения теста
|
||||
const imagePreview = ref(null); // Для превью изображения
|
||||
const selectedEmployees = ref([]); // Для хранения выбранных сотрудников
|
||||
|
||||
const rules = {
|
||||
required: (value) => !!value || 'Это поле обязательно для заполнения',
|
||||
@@ -381,7 +396,7 @@ export default {
|
||||
// Для тестов добавляем начальные ответы с right_wrong полем
|
||||
const initialAnswers = props.isTest ? [
|
||||
{ text: '', image: null, right_wrong: false },
|
||||
{ text: '', image: null, right_wrong: false }
|
||||
{ text: '', image: null, right_wrong: false },
|
||||
] : [];
|
||||
|
||||
form.value.questions.push({
|
||||
@@ -427,20 +442,6 @@ export default {
|
||||
};
|
||||
|
||||
const saveVoting = async () => {
|
||||
const hasEmptyQuestions = quests.value.includes(false);
|
||||
const hasInvalidAnswers = validateAnswers();
|
||||
|
||||
if (
|
||||
!form.value.title ||
|
||||
!form.value.description ||
|
||||
form.value.questions.length < 1 ||
|
||||
hasEmptyQuestions ||
|
||||
hasInvalidAnswers
|
||||
) {
|
||||
errorMessage.value = 'Все обязательные поля и ответы должны быть заполнены';
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (props.isTest) {
|
||||
// Подготавливаем данные для теста
|
||||
@@ -449,33 +450,44 @@ export default {
|
||||
description: form.value.description,
|
||||
datestart: form.value.startDate,
|
||||
dateend: form.value.endDate,
|
||||
image: testImage.value, // Используем загруженное изображение теста
|
||||
pass_perc: Number(testSettings.value.pass_perc),
|
||||
time: Number(testSettings.value.time),
|
||||
question_count: Number(testSettings.value.question_count),
|
||||
attemps_number: Number(testSettings.value.attemps_number),
|
||||
questions: form.value.questions.map(q => ({
|
||||
text: q.text,
|
||||
image: q.image,
|
||||
settings: q.settings || {},
|
||||
settings: q.settings,
|
||||
answers: q.answers.map(a => ({
|
||||
text: a.text,
|
||||
image: a.image,
|
||||
right_wrong: a.right_wrong || false
|
||||
}))
|
||||
}))
|
||||
})),
|
||||
image: testImage.value,
|
||||
pass_perc: Number(testSettings.value.pass_perc),
|
||||
time: Number(testSettings.value.time),
|
||||
question_count: Number(testSettings.value.question_count),
|
||||
attemps_number: Number(testSettings.value.attemps_number)
|
||||
};
|
||||
await createTest(testData);
|
||||
|
||||
const result = await createTest(testData);
|
||||
|
||||
// Если есть выбранные сотрудники, назначаем тест
|
||||
if (selectedEmployees.value?.length > 0) {
|
||||
await assignTest(result.id, selectedEmployees.value);
|
||||
}
|
||||
|
||||
isVoteCreated.value = true;
|
||||
emit('updating');
|
||||
} else {
|
||||
// Стандартное создание голосования
|
||||
await createVote(form.value);
|
||||
isVoteCreated.value = true;
|
||||
emit('updating');
|
||||
}
|
||||
|
||||
isVoteCreated.value = true;
|
||||
emit('updating', 'active');
|
||||
} catch (error) {
|
||||
console.error("Ошибка при создании:", error);
|
||||
errorMessage.value = `Ошибка при создании: ${error.message || error}`;
|
||||
console.error('Ошибка при создании:', error);
|
||||
let errorMessage = 'Произошла ошибка при создании';
|
||||
if (error.response?.data?.message) {
|
||||
errorMessage += ': ' + error.response.data.message;
|
||||
}
|
||||
alert(errorMessage);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -510,6 +522,7 @@ export default {
|
||||
};
|
||||
testImage.value = null;
|
||||
imagePreview.value = null;
|
||||
selectedEmployees.value = [];
|
||||
step.value = 0;
|
||||
isVoteCreated.value = false;
|
||||
};
|
||||
|
||||
@@ -247,11 +247,21 @@ async function createTest(testData) {
|
||||
|
||||
async function assignTest(testId, employeeIds) {
|
||||
try {
|
||||
const response = await axiosApiInstance.post('/api/tests/assigntest/', {
|
||||
testId,
|
||||
employeeIds
|
||||
});
|
||||
return response.data;
|
||||
// Получаем информацию о тесте для определения даты окончания
|
||||
const testDetails = await getTestDetail(testId);
|
||||
const completion_date = testDetails.dateend;
|
||||
|
||||
// Преобразуем employeeIds в обычный массив, если это Proxy
|
||||
const userIds = Array.from(employeeIds).map(id => Number(id));
|
||||
console.log('Назначение теста для пользователей:', userIds);
|
||||
|
||||
// Назначаем тест каждому выбранному сотруднику
|
||||
const promises = userIds.map(userId =>
|
||||
assignTestToUser(userId, testId, completion_date)
|
||||
);
|
||||
|
||||
await Promise.all(promises);
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Ошибка назначения теста:', error);
|
||||
throw error;
|
||||
@@ -278,6 +288,27 @@ async function deleteTest(id) {
|
||||
}
|
||||
}
|
||||
|
||||
async function assignTestToUser(userId, testId, completionDate) {
|
||||
try {
|
||||
console.log('Отправка запроса на назначение теста:', {
|
||||
user_id: userId,
|
||||
test_id: testId,
|
||||
completion_date: completionDate
|
||||
});
|
||||
|
||||
const response = await axiosApiInstance.post('/api/tests/testingview/', {
|
||||
user_id: Number(userId),
|
||||
test_id: Number(testId),
|
||||
completion_date: new Date(completionDate).toISOString()
|
||||
});
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error("Ошибка назначения теста пользователю:", error);
|
||||
console.error("Детали ошибки:", error.response?.data);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export {
|
||||
axiosApiInstance,
|
||||
@@ -298,4 +329,5 @@ export {
|
||||
assignTest,
|
||||
getTestDetail,
|
||||
deleteTest,
|
||||
assignTestToUser,
|
||||
}
|
||||
@@ -7,11 +7,13 @@
|
||||
<!-- Вкладка назначенные -->
|
||||
<v-window-item class="my-2 w-75 mx-auto h-100">
|
||||
<CatalogTest :activeTab="activeTab" :testingCard="getAllTests" title="Назначенные">
|
||||
<template #buttons>
|
||||
<v-btn class="mr-2 text-teal-darken-1" color="#00897B1F" elevation="0">
|
||||
<template #buttons="{ cardValue }">
|
||||
<v-btn class="mr-2 text-teal-darken-1" color="#00897B1F" elevation="0" @click="goToTest(cardValue.id)">
|
||||
Тренироваться
|
||||
</v-btn>
|
||||
<v-btn color="teal-darken-1" elevation="0"> Пройти</v-btn>
|
||||
<v-btn color="teal-darken-1" elevation="0" @click="startTest(cardValue.id)">
|
||||
Пройти тест
|
||||
</v-btn>
|
||||
</template>
|
||||
</CatalogTest>
|
||||
</v-window-item>
|
||||
@@ -19,10 +21,13 @@
|
||||
<!-- Вкладка завершенных -->
|
||||
<v-window-item class="w-75 mx-auto">
|
||||
<CatalogTest :activeTab="activeTab" :testingCard="getAllTests" title="Завершенные">
|
||||
<template #buttons>
|
||||
<v-btn class="mr-2 text-teal-darken-1" color="#00897B1F" elevation="0">
|
||||
<template #buttons="{ cardValue }">
|
||||
<v-btn class="mr-2 text-teal-darken-1" color="#00897B1F" elevation="0" @click="showResults(cardValue.id)">
|
||||
Результаты
|
||||
</v-btn>
|
||||
<v-btn v-if="cardValue.remaining_attempts > 0" color="teal-darken-1" elevation="0" @click="retryTest(cardValue.id)">
|
||||
Пересдать ({{ cardValue.remaining_attempts }})
|
||||
</v-btn>
|
||||
</template>
|
||||
</CatalogTest>
|
||||
</v-window-item>
|
||||
@@ -85,7 +90,13 @@
|
||||
<v-dialog v-model="addDialog" max-width="800">
|
||||
<v-card>
|
||||
<v-card-title>Назначить сотруднику</v-card-title>
|
||||
<SearcEmployess />
|
||||
<SearcEmployess
|
||||
:modelValue="selectedEmployees"
|
||||
@update:modelValue="handleEmployeeSelection"
|
||||
/>
|
||||
<v-card-text v-if="selectedEmployees?.length">
|
||||
Выбрано сотрудников: {{ selectedEmployees.length }}
|
||||
</v-card-text>
|
||||
<v-card-actions>
|
||||
<v-spacer />
|
||||
<v-btn color="grey" @click="addDialog = false">Отмена</v-btn>
|
||||
@@ -129,11 +140,19 @@ export default {
|
||||
const selectedTestId = ref(null);
|
||||
|
||||
const getTestById = () => {
|
||||
let status =
|
||||
activeTab.value === 0 ? '?status=active' : activeTab.value === 1 ? '?status=completed' : '';
|
||||
// В каталоге показываем все тесты
|
||||
const status = activeTab.value === 2 ? '' :
|
||||
activeTab.value === 0 ? '?status=active' :
|
||||
activeTab.value === 1 ? '?status=completed' : '';
|
||||
|
||||
console.log('Запрашиваем тесты со статусом:', status);
|
||||
|
||||
axiosApiInstance
|
||||
.get(`/api/tests/gettests/${status}`)
|
||||
.then((resp) => (getAllTests.value = resp.data))
|
||||
.get(`/api/tests/gettests${status}`)
|
||||
.then((resp) => {
|
||||
console.log('Получен ответ от сервера:', resp.data);
|
||||
getAllTests.value = resp.data;
|
||||
})
|
||||
.finally(() => {
|
||||
if (activeTab.value === 0) {
|
||||
currentTest.value = getAllTests.value.length;
|
||||
@@ -179,25 +198,60 @@ export default {
|
||||
}
|
||||
};
|
||||
|
||||
const selectedEmployees = ref([]);
|
||||
|
||||
const handleEmployeeSelection = (value) => {
|
||||
console.log('handleEmployeeSelection:', value);
|
||||
selectedEmployees.value = value;
|
||||
};
|
||||
|
||||
const assignTestToEmployee = async () => {
|
||||
try {
|
||||
const selectedEmployees = document.querySelectorAll('input[name="employee"]:checked');
|
||||
const employeeIds = Array.from(selectedEmployees).map(el => el.value);
|
||||
const selectedIds = selectedEmployees.value?.map(id => Number(id)) || [];
|
||||
console.log('Текущие выбранные сотрудники:', selectedIds);
|
||||
|
||||
if (employeeIds.length === 0) {
|
||||
if (!selectedIds.length) {
|
||||
alert('Выберите хотя бы одного сотрудника');
|
||||
return;
|
||||
}
|
||||
|
||||
await assignTest(selectedTestId.value, employeeIds);
|
||||
console.log('Назначаем тест:', selectedTestId.value, 'сотрудникам:', selectedIds);
|
||||
|
||||
// Получим текущего пользователя
|
||||
const currentUserId = accountStore.user.id;
|
||||
|
||||
// Создаем новый массив с текущим пользователем
|
||||
const employeesWithCurrent = [...selectedEmployees.value];
|
||||
if (!employeesWithCurrent.includes(currentUserId)) {
|
||||
employeesWithCurrent.push(currentUserId);
|
||||
}
|
||||
|
||||
await assignTest(selectedTestId.value, employeesWithCurrent);
|
||||
|
||||
addDialog.value = false;
|
||||
selectedEmployees.value = []; // очищаем выбор после назначения
|
||||
getTestById();
|
||||
} catch (error) {
|
||||
console.error('Ошибка при назначении теста:', error);
|
||||
alert('Произошла ошибка при назначении теста');
|
||||
}
|
||||
};
|
||||
|
||||
// Начать прохождение теста
|
||||
const startTest = (id) => {
|
||||
router.push(`/test/testdetail/${id}?mode=exam`);
|
||||
};
|
||||
|
||||
// Показать результаты теста
|
||||
const showResults = (id) => {
|
||||
router.push(`/test/results/${id}`);
|
||||
};
|
||||
|
||||
// Попытка пересдачи теста
|
||||
const retryTest = (id) => {
|
||||
router.push(`/test/testdetail/${id}?mode=retry`);
|
||||
};
|
||||
|
||||
return {
|
||||
activeTab,
|
||||
tabs,
|
||||
@@ -210,7 +264,12 @@ export default {
|
||||
openAddDialog,
|
||||
deleteTest,
|
||||
assignTestToEmployee,
|
||||
getTestById
|
||||
getTestById,
|
||||
startTest,
|
||||
showResults,
|
||||
retryTest,
|
||||
selectedEmployees,
|
||||
handleEmployeeSelection
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user