- translate leader board
This commit is contained in:
Alexandrina-Kuzeleva
2025-12-04 15:13:11 +03:00
parent 36f75beea9
commit 60e81a921e
3 changed files with 95 additions and 463 deletions

View File

@@ -2,15 +2,15 @@
<div class="min-h-screen p-6">
<!-- Заголовок -->
<div class="text-center mb-8">
<h1 class="text-3xl font-bold text-gray-800 mb-2">Таблица лидеров</h1>
<p class="text-gray-600">Рейтинг участников по набранным очкам</p>
<h1 class="text-3xl font-bold text-gray-800 mb-2">{{__('Leader board')}}</h1>
<p class="text-gray-600">{{__('Rating of participants by points scored')}}</p>
</div>
<!-- Карточка текущего пользователя и лучшего в группе -->
<div class="max-w-5xl mx-auto grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
<!-- Карточка текущего пользователя -->
<div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-teal-600">
<h3 class="text-lg font-semibold text-gray-800 mb-4">Ваша позиция</h3>
<h3 class="text-lg font-semibold text-gray-800 mb-4">{{__('Your position')}}</h3>
<div class="flex items-center justify-between">
<div class="flex items-center space-x-4">
<div class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
@@ -32,32 +32,32 @@
<div class="text-2xl font-bold text-gray-800">
#{{ currentUserPosition }}
</div>
<div class="text-sm text-gray-500">место</div>
<div class="text-sm text-gray-500">{{__('position')}}</div>
</div>
</div>
<!-- Прогресс до следующего места -->
<div v-if="pointsToNext > 0" class="mt-4 p-3 bg-blue-50 rounded-lg">
<div class="text-sm text-gray-600 mb-1">
До {{ nextPosition }} места нужно:
</div>
<div class="flex items-center justify-between">
<span class="text-lg font-bold text-blue-600">+{{ pointsToNext }} очков</span>
<span class="text-sm text-gray-500">
{{ nextPositionPoints - currentUser.points }} осталось
</span>
</div>
</div>
<div v-else class="mt-4 p-3 bg-green-50 rounded-lg">
<div class="text-sm text-green-600 font-semibold">
🎉 Вы занимаете первое место в своей группе!
</div>
</div>
<div class="text-sm text-gray-600 mb-1">
{{ __('To reach :position place:', { position: nextPosition }) }}
</div>
<div class="flex items-center justify-between">
<span class="text-lg font-bold text-blue-600">+{{ pointsToNext }} {{ __('points') }}</span>
<span class="text-sm text-gray-500">
{{ nextPositionPoints - currentUser.points }} {{ __('left') }}
</span>
</div>
</div>
<div v-else class="mt-4 p-3 bg-green-50 rounded-lg">
<div class="text-sm text-green-600 font-semibold">
🎉 {{ __('You are in first place in your group!') }}
</div>
</div>
</div>
<!-- Карточка лучшего в группе -->
<div class="bg-gradient-to-r from-yellow-400 to-orange-400 rounded-xl shadow-lg p-6 text-white">
<h3 class="text-lg font-semibold mb-4">Лучший в категории</h3>
<h3 class="text-lg font-semibold mb-4">{{ __('The best in the group') }}</h3>
<div class="flex items-center justify-between">
<div class="flex items-center space-x-4">
<div class="w-12 h-12 bg-white bg-opacity-20 rounded-full flex items-center justify-center">
@@ -78,7 +78,7 @@
</div>
<div class="text-right">
<div class="text-2xl font-bold">{{ topUserInGroup?.points || 0 }}</div>
<div class="text-sm text-opacity-80">очков</div>
<div class="text-sm text-opacity-80">{{ __('points') }}</div>
</div>
</div>
</div>
@@ -116,7 +116,7 @@
<p class="text-2xl font-bold text-gray-800">
{{ getGroupStats(group.role).count }}
</p>
<p class="text-sm text-gray-500">участников</p>
<p class="text-sm text-gray-500">{{ __('members') }}</p>
</div>
</div>
@@ -129,7 +129,7 @@
</h2>
<!-- Примечание о бонусах только для школьников -->
<p v-if="activeGroup === 'LMS Schoolchild'" class="text-white text-opacity-90 text-sm mt-1">
* Бонусные баллы рассчитываются как 1 балл за каждые 100 очков активности (максимум 10)
{{ __('* Bonus points are calculated as 1 point for every 100 activity points (maximum 10)!') }}
</p>
</div>
@@ -178,7 +178,7 @@
<div class="flex items-center space-x-6">
<!-- Бонусы (только для школьников) -->
<div v-if="user.isSchoolchild && user.bonus > 0" class="text-center">
<div class="text-xs text-gray-500 mb-1">Бонус</div>
<div class="text-xs text-gray-500 mb-1">{{ __('Bonus') }}</div>
<div class="flex items-center space-x-1">
<span class="text-lg font-bold text-orange-500">{{ user.bonus }}</span>
<span class="text-orange-400"></span>
@@ -187,7 +187,7 @@
<!-- Очки -->
<div class="text-center">
<div class="text-xs text-gray-500 mb-1">Очки</div>
<div class="text-xs text-gray-500 mb-1">{{ __('Points') }}</div>
<div class="text-xl font-bold text-gray-800">{{ user.points }}</div>
</div>
</div>
@@ -201,7 +201,7 @@
class="text-center py-12 text-gray-500"
>
<div class="text-6xl mb-4">🏆</div>
<p class="text-lg">Пока нет участников в этой категории</p>
<p class="text-lg">{{ __('There are no participants in this category yet.') }}</p>
</div>
</div>
@@ -218,9 +218,9 @@ const { userResource, allUsers } = store
// Группы ролей которые нас интересуют
const roleGroups = [
{ role: 'LMS Student', label: 'Студенты' },
{ role: 'Course Creator', label: 'Преподаватели' },
{ role: 'LMS Schoolchild', label: 'Школьники' }
{ role: 'LMS Student', label: __('Students') },
{ role: 'Course Creator', label: __('Teachers') },
{ role: 'LMS Schoolchild', label: __('Schoolchildren') }
]
// Определяем группу текущего пользователя
@@ -245,7 +245,7 @@ const logsResource = createResource({
limit_page_length: 10000
},
auto: false,
onError: (err) => console.error("Ошибка загрузки Energy Point Log:", err)
onError: (err) => console.error("Error loading Energy Point Log:", err)
})
const leaderboard = ref([])

View File

@@ -1,439 +1,7 @@
<template>
<div class="min-h-screen p-6">
<!-- Заголовок -->
<div class="text-center mb-8">
<h1 class="text-3xl font-bold text-gray-800 mb-2">Таблица лидеров</h1>
<p class="text-gray-600">Рейтинг участников по набранным очкам</p>
<h1 class="text-3xl font-bold text-gray-800 mb-2">Тестовая страница</h1>
</div>
<!-- Карточка текущего пользователя и лучшего в группе -->
<div class="max-w-5xl mx-auto grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
<!-- Карточка текущего пользователя -->
<div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-teal-600">
<h3 class="text-lg font-semibold text-gray-800 mb-4">Ваша позиция</h3>
<div class="flex items-center justify-between">
<div class="flex items-center space-x-4">
<div class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
<span class="text-blue-600 font-bold text-lg">
{{ currentUserInitial }}
</span>
</div>
<div>
<a
:href="`/lms/user/${currentUser.username}`"
class="font-semibold text-gray-800 hover:text-blue-600 transition-colors"
>
{{ currentUser.full_name }}
</a>
<p class="text-sm text-gray-500">{{ currentUser.username }}</p>
</div>
</div>
<div class="text-right">
<div class="text-2xl font-bold text-gray-800">
#{{ currentUserPosition }}
</div>
<div class="text-sm text-gray-500">место</div>
</div>
</div>
<!-- Прогресс до следующего места -->
<div v-if="pointsToNext > 0" class="mt-4 p-3 bg-blue-50 rounded-lg">
<div class="text-sm text-gray-600 mb-1">
До {{ nextPosition }} места нужно:
</div>
<div class="flex items-center justify-between">
<span class="text-lg font-bold text-blue-600">+{{ pointsToNext }} очков</span>
<span class="text-sm text-gray-500">
{{ nextPositionPoints - currentUser.points }} осталось
</span>
</div>
</div>
<div v-else class="mt-4 p-3 bg-green-50 rounded-lg">
<div class="text-sm text-green-600 font-semibold">
🎉 Вы занимаете первое место в своей группе!
</div>
</div>
</div>
<!-- Карточка лучшего в группе -->
<div class="bg-gradient-to-r from-yellow-400 to-orange-400 rounded-xl shadow-lg p-6 text-white">
<h3 class="text-lg font-semibold mb-4">Лучший в категории</h3>
<div class="flex items-center justify-between">
<div class="flex items-center space-x-4">
<div class="w-12 h-12 bg-white bg-opacity-20 rounded-full flex items-center justify-center">
<span class="font-bold text-lg">👑</span>
</div>
<div>
<a
v-if="topUserInGroup"
:href="`/lms/user/${topUserInGroup.username}`"
class="font-semibold hover:underline transition-colors"
>
{{ topUserInGroup.full_name }}
</a>
<!--<p class="text-sm text-opacity-80" v-if="topUserInGroup">
{{ topUserInGroup.username }}
</p>-->
</div>
</div>
<div class="text-right">
<div class="text-2xl font-bold">{{ topUserInGroup?.points || 0 }}</div>
<div class="text-sm text-opacity-80">очков</div>
</div>
</div>
</div>
</div>
<!-- Переключение групп -->
<div class="flex justify-center mb-8">
<div class="bg-white rounded-lg shadow-sm p-1 flex space-x-1">
<button
v-for="group in roleGroups"
:key="group.role"
@click="activeGroup = group.role"
:class="[
'px-4 py-2 rounded-md text-sm font-medium transition-all duration-200',
activeGroup === group.role
? getGroupButtonClass(group.role)
: 'text-gray-600 hover:text-gray-800 hover:bg-gray-100'
]"
>
{{ group.label }}
</button>
</div>
</div>
<!-- Статистика -->
<div class="max-w-5xl mx-auto mt-6 grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
<div
v-for="group in roleGroups"
:key="group.role"
class="bg-white rounded-lg shadow-sm p-4 border-l-4 cursor-pointer hover:shadow-md transition-shadow"
:class="getGroupBorderClass(group.role)"
@click="activeGroup = group.role"
>
<h3 class="font-semibold text-gray-700 mb-2">{{ group.label }}</h3>
<p class="text-2xl font-bold text-gray-800">
{{ getGroupStats(group.role).count }}
</p>
<p class="text-sm text-gray-500">участников</p>
</div>
</div>
<!-- Таблица лидеров -->
<div class="max-w-5xl mx-auto bg-white rounded-xl shadow-lg overflow-hidden">
<!-- Заголовок таблицы -->
<div :class="['px-6 py-4 bg-gradient-to-r', getGroupGradientClass(activeGroup)]">
<h2 class="text-xl font-bold text-white">
{{ activeGroupLabel }} - Топ {{ currentLeaderboard.length }}
</h2>
<!-- Примечание о бонусах только для школьников -->
<p v-if="activeGroup === 'LMS Schoolchild'" class="text-white text-opacity-90 text-sm mt-1">
* Бонусные баллы рассчитываются как 1 балл за каждые 100 очков активности (максимум 10)
</p>
</div>
<!-- Список участников -->
<div class="divide-y divide-gray-100">
<div
v-for="(user, index) in currentLeaderboard"
:key="user.user"
class="px-6 py-4 hover:bg-gray-50 transition-colors duration-150"
>
<div class="flex items-center justify-between">
<!-- Место и информация -->
<div class="flex items-center space-x-4">
<!-- Место -->
<div
:class="[
'w-8 h-8 rounded-full flex items-center justify-center text-white font-bold text-sm',
index === 0 ? 'bg-yellow-400' :
index === 1 ? 'bg-gray-400' :
index === 2 ? 'bg-orange-400' : 'bg-blue-400'
]"
>
{{ index + 1 }}
</div>
<!-- Аватар и имя -->
<div class="flex items-center space-x-3">
<div class="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
<span class="text-blue-600 font-bold text-sm">
{{ getUserInitial(user) }}
</span>
</div>
<div>
<a
:href="`/lms/user/${user.username}`"
class="font-semibold text-gray-800 hover:text-blue-600 transition-colors"
>
{{ user.full_name }}
</a>
<!--<p class="text-sm text-gray-500">{{ user.username }}</p>-->
</div>
</div>
</div>
<!-- Очки и бонусы -->
<div class="flex items-center space-x-6">
<!-- Бонусы (только для школьников) -->
<div v-if="user.isSchoolchild && user.bonus > 0" class="text-center">
<div class="text-xs text-gray-500 mb-1">Бонус</div>
<div class="flex items-center space-x-1">
<span class="text-lg font-bold text-orange-500">{{ user.bonus }}</span>
<span class="text-orange-400"></span>
</div>
</div>
<!-- Очки -->
<div class="text-center">
<div class="text-xs text-gray-500 mb-1">Очки</div>
<div class="text-xl font-bold text-gray-800">{{ user.points }}</div>
</div>
</div>
</div>
</div>
</div>
<!-- Пустое состояние -->
<div
v-if="currentLeaderboard.length === 0"
class="text-center py-12 text-gray-500"
>
<div class="text-6xl mb-4">🏆</div>
<p class="text-lg">Пока нет участников в этой категории</p>
</div>
</div>
</div>
</template>
<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { usersStore } from '@/stores/user'
import { createResource } from 'frappe-ui'
const store = usersStore()
const { userResource, allUsers } = store
// Группы ролей которые нас интересуют
const roleGroups = [
{ role: 'LMS Student', label: 'Студенты' },
{ role: 'Course Creator', label: 'Преподаватели' },
{ role: 'LMS Schoolchild', label: 'Школьники' }
]
// Определяем группу текущего пользователя
function getUserRoleGroup(userRoles) {
if (!userRoles) return 'LMS Student'
const validRole = userRoles.find(role =>
roleGroups.some(group => group.role === role)
)
return validRole || 'LMS Student'
}
const activeGroup = ref('LMS Student')
const usersList = computed(() => allUsers.data || [])
const usersCount = computed(() => usersList.value.length)
const logsResource = createResource({
url: "frappe.client.get_list",
params: {
doctype: "Energy Point Log",
fields: ["user", "points"],
limit_page_length: 10000
},
auto: false,
onError: (err) => console.error("Ошибка загрузки Energy Point Log:", err)
})
const leaderboard = ref([])
// Текущий пользователь
const currentUser = computed(() => {
return userResource.data || {}
})
// Инициалы текущего пользователя
const currentUserInitial = computed(() => {
if (currentUser.value.full_name) {
return currentUser.value.full_name.charAt(0).toUpperCase()
}
return currentUser.value.name?.charAt(0).toUpperCase() || 'U'
})
// Получить инициалы пользователя
function getUserInitial(user) {
return user.full_name?.charAt(0).toUpperCase() || user.username?.charAt(0).toUpperCase() || 'U'
}
// Устанавливаем активную группу на основе ролей текущего пользователя
watch([currentUser, usersList], () => {
if (currentUser.value.roles && usersList.value.length > 0) {
const userGroup = getUserRoleGroup(currentUser.value.roles)
activeGroup.value = userGroup
}
})
// Активная группа label
const activeGroupLabel = computed(() => {
const group = roleGroups.find(g => g.role === activeGroup.value)
return group ? group.label : ''
})
// Текущий лидерборд для активной группы
const currentLeaderboard = computed(() => {
return leaderboard.value
.filter(user => user.roles.includes(activeGroup.value))
.slice(0, 50)
})
// Лучший пользователь в активной группе
const topUserInGroup = computed(() => {
return currentLeaderboard.value[0]
})
// Позиция текущего пользователя в активной группе
const currentUserPosition = computed(() => {
const userInLeaderboard = currentLeaderboard.value.findIndex(
user => user.user === currentUser.value.name
)
return userInLeaderboard !== -1 ? userInLeaderboard + 1 : '-'
})
// Очки текущего пользователя
const currentUserPoints = computed(() => {
const userEntry = leaderboard.value.find(user => user.user === currentUser.value.name)
return userEntry ? userEntry.points : 0
})
// Очки до следующего места
const pointsToNext = computed(() => {
const userIndex = currentLeaderboard.value.findIndex(
user => user.user === currentUser.value.name
)
if (userIndex === -1 || userIndex === 0) return 0
const currentUserPoints = currentLeaderboard.value[userIndex].points
const nextUserPoints = currentLeaderboard.value[userIndex - 1].points
return nextUserPoints - currentUserPoints + 1
})
// Следующая позиция
const nextPosition = computed(() => {
const userIndex = currentLeaderboard.value.findIndex(
user => user.user === currentUser.value.name
)
return userIndex > 0 ? userIndex : 1
})
// Очки следующего пользователя
const nextPositionPoints = computed(() => {
const userIndex = currentLeaderboard.value.findIndex(
user => user.user === currentUser.value.name
)
return userIndex > 0 ? currentLeaderboard.value[userIndex - 1].points : currentUserPoints.value
})
// Классы для групп
function getGroupButtonClass(role) {
const classes = {
'LMS Student': 'bg-teal-400 text-white shadow-md',
'Course Creator': 'bg-teal-600 text-white shadow-md',
'LMS Schoolchild': 'bg-teal-200 text-white shadow-md'
}
return classes[role] || 'bg-blue-500 text-white shadow-md'
}
function getGroupGradientClass(role) {
const classes = {
'LMS Student': 'from-teal-400 to-teal-500',
'Course Creator': 'from-teal-600 to-teal-700',
'LMS Schoolchild': 'from-teal-300 to-teal-400'
}
return classes[role] || 'from-blue-500 to-blue-600'
}
function getGroupBorderClass(role) {
const classes = {
'LMS Student': 'border-teal-400',
'Course Creator': 'border-teal-600',
'LMS Schoolchild': 'border-teal-300'
}
return classes[role] || 'border-blue-400'
}
// Статистика по группам
function getGroupStats(role) {
const groupUsers = leaderboard.value.filter(user => user.roles.includes(role))
return {
count: groupUsers.length,
totalPoints: groupUsers.reduce((sum, user) => sum + user.points, 0)
}
}
function calculateLeaderboard() {
if (!logsResource.data) return
const pointsMap = {}
// Считаем сумму очков для каждого пользователя
logsResource.data.forEach(log => {
if (!pointsMap[log.user]) pointsMap[log.user] = 0
pointsMap[log.user] += log.points
})
// Создаем leaderboard только для пользователей с нужными ролями
leaderboard.value = Object.keys(pointsMap)
.map(user => {
const u = usersList.value.find(x => x.name === user)
// Пропускаем пользователей без данных или без нужных ролей
if (!u) return null
// Проверяем есть ли у пользователя нужные роли
const hasValidRole = u.roles && u.roles.some(role =>
roleGroups.some(group => group.role === role)
)
if (!hasValidRole) return null
// Пропускаем пользователей с отрицательными или нулевыми баллами
if (pointsMap[user] < 0) return null
// Определяем является ли пользователь школьником
const isSchoolchild = u.roles.includes('LMS Schoolchild')
// Вычисляем бонус только для школьников
const bonus = isSchoolchild ? Math.min(Math.floor(pointsMap[user] / 100), 10) : 0
return {
user,
points: pointsMap[user],
full_name: u.full_name,
username: u.username,
roles: u.roles || [],
bonus: bonus,
isSchoolchild: isSchoolchild // Добавляем флаг для удобства
}
})
.filter(user => user !== null)
.sort((a, b) => b.points - a.points)
}
onMounted(async () => {
await allUsers.reload()
await logsResource.reload()
calculateLeaderboard()
})
</script>
<style scoped>
/* Плавные переходы */
button, .hover\:bg-gray-50 {
transition: all 0.2s ease-in-out;
}
</style>