Reflex/src/views/admin/AdminConversationDetail.vue

571 lines
14 KiB
Vue
Raw Normal View History

<template>
<div class="admin-conversation-detail">
<div class="header-controls">
<button @click="goBack" class="back-btn">
&laquo; Назад к списку диалогов
</button>
</div>
<div v-if="loading" class="loading-indicator">
Загрузка сообщений...
</div>
<div v-if="error" class="error-message">
{{ error }}
</div>
<div v-if="conversation && !loading" class="conversation-container">
<h2>Просмотр диалога</h2>
<div class="conversation-info">
<h3>Информация о диалоге</h3>
<div class="info-grid">
<div class="info-item">
<div class="info-label">ID диалога</div>
<div class="info-value">{{ conversation._id }}</div>
</div>
<div class="info-item">
<div class="info-label">Дата создания</div>
<div class="info-value">{{ formatDate(conversation.createdAt) }}</div>
</div>
<div class="info-item">
<div class="info-label">Последняя активность</div>
<div class="info-value">{{ formatDate(conversation.updatedAt) }}</div>
</div>
</div>
</div>
<div class="participants-section">
<h3>Участники диалога</h3>
<div class="participants-list">
<div
v-for="participant in conversation.participants"
:key="participant._id"
class="participant-card"
>
<div class="participant-photo" v-if="getParticipantPhoto(participant)">
<img :src="getParticipantPhoto(participant)" alt="Фото пользователя">
</div>
<div class="participant-photo placeholder" v-else>
<div class="initials">{{ getInitials(participant.name) }}</div>
</div>
<div class="participant-info">
<div class="participant-name">{{ participant.name }}</div>
<div class="participant-email">{{ participant.email }}</div>
<button @click="viewUser(participant._id)" class="btn user-btn">
Профиль пользователя
</button>
</div>
</div>
</div>
</div>
<div class="messages-section">
<h3>История сообщений</h3>
<div v-if="loadingMessages" class="loading-messages">
Загрузка сообщений...
</div>
<div v-else-if="messages.length === 0" class="no-messages">
В диалоге нет сообщений
</div>
<div v-else class="messages-list">
<div
v-for="message in messages"
:key="message._id"
class="message-item"
:class="{ 'sender-1': message.sender._id === conversation.participants[0]._id, 'sender-2': message.sender._id === conversation.participants[1]._id }"
>
<div class="message-header">
<div class="message-sender">{{ message.sender.name }}</div>
<div class="message-time">{{ formatMessageTime(message.createdAt) }}</div>
</div>
<div class="message-content">{{ message.text }}</div>
<div class="message-status">
{{ getMessageStatus(message.status) }}
<span v-if="message.isEdited" class="edited-tag">(отредактировано)</span>
</div>
</div>
</div>
<div v-if="pagination.pages > 1" class="pagination">
<button
@click="changePage(currentPage - 1)"
:disabled="currentPage === 1"
class="pagination-btn"
>
&laquo; Более новые
</button>
<span class="pagination-info">
Страница {{ currentPage }} из {{ pagination.pages }}
</span>
<button
@click="changePage(currentPage + 1)"
:disabled="currentPage === pagination.pages"
class="pagination-btn"
>
Более старые &raquo;
</button>
</div>
</div>
</div>
</div>
</template>
<script>
import { ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';
export default {
name: 'AdminConversationDetail',
props: {
id: {
type: String,
required: true
}
},
setup(props) {
const router = useRouter();
const route = useRoute();
const conversation = ref(null);
const messages = ref([]);
const loading = ref(false);
const loadingMessages = ref(false);
const error = ref(null);
const currentPage = ref(1);
const pagination = ref({
page: 1,
limit: 50,
total: 0,
pages: 0
});
const loadConversation = async () => {
loading.value = true;
error.value = null;
try {
2025-05-26 00:00:26 +07:00
const token = localStorage.getItem('userToken'); // Исправлено с 'token' на 'userToken'
// Здесь мы используем маршрут для получения данных о диалоге
// Это должен быть запрос к API, который возвращает данные о конкретном диалоге
// На бэкенде такого маршрута может не быть, поэтому используем маршрут для получения списка диалогов
// и фильтруем результаты на клиенте
const response = await axios.get(
2025-05-25 23:54:16 +07:00
`/api/admin/conversations`,
{
params: { userId: props.id, limit: 1 }, // Временное решение, по API нужно реализовать маршрут GET /api/admin/conversations/:id
headers: {
Authorization: `Bearer ${token}`
}
}
);
if (response.data.conversations && response.data.conversations.length > 0) {
conversation.value = response.data.conversations.find(c => c._id === props.id);
if (!conversation.value) {
// Если не нашли диалог по ID, возьмем первый из ответа (временное решение)
conversation.value = response.data.conversations[0];
}
// Загружаем сообщения для диалога
loadMessages();
} else {
error.value = 'Диалог не найден';
}
} catch (err) {
console.error('Ошибка при загрузке данных диалога:', err);
error.value = 'Ошибка при загрузке информации о диалоге. Пожалуйста, попробуйте позже.';
} finally {
loading.value = false;
}
};
const loadMessages = async () => {
if (!conversation.value) return;
loadingMessages.value = true;
try {
2025-05-26 00:00:26 +07:00
const token = localStorage.getItem('userToken'); // Исправлено с 'token' на 'userToken'
const response = await axios.get(
2025-05-25 23:54:16 +07:00
`/api/admin/conversations/${conversation.value._id}/messages`,
{
params: {
page: currentPage.value,
limit: pagination.value.limit
},
headers: {
Authorization: `Bearer ${token}`
}
}
);
messages.value = response.data.messages;
pagination.value = response.data.pagination;
} catch (err) {
console.error('Ошибка при загрузке сообщений:', err);
error.value = 'Ошибка при загрузке сообщений. Пожалуйста, попробуйте позже.';
} finally {
loadingMessages.value = false;
}
};
// Переход назад к списку диалогов
const goBack = () => {
router.push({ name: 'AdminConversations' });
};
// Переход к профилю пользователя
const viewUser = (userId) => {
router.push({ name: 'AdminUserDetail', params: { id: userId } });
};
// Получение фотографии участника диалога
const getParticipantPhoto = (participant) => {
if (!participant || !participant.photos || participant.photos.length === 0) return null;
const profilePhoto = participant.photos.find(p => p.isProfilePhoto);
return profilePhoto ? profilePhoto.url : participant.photos[0].url;
};
// Получение инициалов пользователя
const getInitials = (name) => {
if (!name) return '?';
return name
.split(' ')
.map(n => n[0])
.join('')
.toUpperCase()
.substring(0, 2);
};
// Форматирование даты
const formatDate = (dateString) => {
if (!dateString) return 'Не указана';
const date = new Date(dateString);
return date.toLocaleString('ru-RU', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
};
// Форматирование времени сообщения
const formatMessageTime = (dateString) => {
if (!dateString) return '';
const date = new Date(dateString);
return date.toLocaleString('ru-RU', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
};
// Получение статуса сообщения
const getMessageStatus = (status) => {
switch(status) {
case 'sending': return 'Отправляется';
case 'delivered': return 'Доставлено';
case 'read': return 'Прочитано';
default: return status;
}
};
// Изменение страницы пагинации
const changePage = (page) => {
if (page < 1 || page > pagination.value.pages) return;
currentPage.value = page;
loadMessages();
};
onMounted(() => {
loadConversation();
});
return {
conversation,
messages,
loading,
loadingMessages,
error,
currentPage,
pagination,
goBack,
viewUser,
getParticipantPhoto,
getInitials,
formatDate,
formatMessageTime,
getMessageStatus,
changePage
};
}
}
</script>
<style scoped>
.admin-conversation-detail {
padding-bottom: 2rem;
}
.header-controls {
display: flex;
justify-content: space-between;
margin-bottom: 1.5rem;
}
.back-btn {
padding: 0.5rem 1rem;
background-color: #f5f5f5;
border: 1px solid #ddd;
border-radius: 4px;
cursor: pointer;
color: #333;
}
.loading-indicator {
text-align: center;
padding: 2rem;
color: #666;
}
.error-message {
padding: 1rem;
background-color: #ffebee;
color: #d32f2f;
border-radius: 4px;
margin-bottom: 1rem;
}
h2 {
margin-top: 0;
margin-bottom: 1.5rem;
color: #333;
}
h3 {
margin-top: 0;
margin-bottom: 1rem;
color: #333;
}
.conversation-container {
display: flex;
flex-direction: column;
gap: 2rem;
}
.conversation-info {
background-color: white;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
padding: 1.5rem;
}
.info-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1rem;
}
.info-item {
display: flex;
flex-direction: column;
}
.info-label {
font-size: 0.875rem;
color: #666;
margin-bottom: 0.25rem;
}
.info-value {
font-weight: 500;
}
.participants-section {
background-color: white;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
padding: 1.5rem;
}
.participants-list {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1.5rem;
}
.participant-card {
display: flex;
align-items: center;
gap: 1rem;
padding: 1rem;
border: 1px solid #eee;
border-radius: 6px;
}
.participant-photo {
width: 60px;
height: 60px;
border-radius: 50%;
overflow: hidden;
}
.participant-photo img {
width: 100%;
height: 100%;
object-fit: cover;
}
.participant-photo.placeholder {
display: flex;
align-items: center;
justify-content: center;
background-color: #ff3e68;
color: white;
font-weight: bold;
}
.participant-info {
flex: 1;
}
.participant-name {
font-weight: 500;
margin-bottom: 0.25rem;
}
.participant-email {
font-size: 0.875rem;
color: #666;
margin-bottom: 0.5rem;
}
.btn {
padding: 0.4rem 0.75rem;
border: none;
border-radius: 4px;
cursor: pointer;
font-weight: 500;
font-size: 0.875rem;
}
.user-btn {
background-color: #e3f2fd;
color: #1976d2;
}
.messages-section {
background-color: white;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
padding: 1.5rem;
}
.loading-messages {
text-align: center;
padding: 2rem;
color: #666;
}
.no-messages {
text-align: center;
padding: 2rem;
color: #666;
}
.messages-list {
display: flex;
flex-direction: column;
gap: 1rem;
}
.message-item {
padding: 1rem;
border-radius: 8px;
max-width: 80%;
}
.message-item.sender-1 {
background-color: #e3f2fd;
align-self: flex-start;
}
.message-item.sender-2 {
background-color: #f8bbd0;
align-self: flex-end;
}
.message-header {
display: flex;
justify-content: space-between;
margin-bottom: 0.5rem;
font-size: 0.875rem;
}
.message-sender {
font-weight: 500;
}
.message-time {
color: #666;
}
.message-content {
margin-bottom: 0.5rem;
white-space: pre-wrap;
}
.message-status {
text-align: right;
font-size: 0.75rem;
color: #666;
}
.edited-tag {
margin-left: 0.5rem;
font-style: italic;
}
.pagination {
display: flex;
justify-content: center;
align-items: center;
gap: 1rem;
margin-top: 1.5rem;
}
.pagination-btn {
padding: 0.5rem 1rem;
background-color: #f5f5f5;
border: 1px solid #ddd;
border-radius: 4px;
cursor: pointer;
}
.pagination-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.pagination-info {
color: #666;
}
</style>