This commit is contained in:
2025-04-17 23:32:39 +09:00
commit 5b719b6766
105 changed files with 25653 additions and 0 deletions
+160
View File
@@ -0,0 +1,160 @@
<template>
<div class="club-create-container">
<div class="club-create-card">
<h2>클럽 생성</h2>
<p class="info-text">볼링 클럽을 생성하여 회원들을 관리하고 활동을 시작해보세요.</p>
<form @submit.prevent="handleCreateClub">
<div class="form-group">
<label for="clubName">클럽 이름</label>
<InputText id="clubName" v-model="clubName" class="w-full" :class="{'p-invalid': clubNameError}" />
<small v-if="clubNameError" class="p-error">{{ clubNameError }}</small>
</div>
<div class="form-group">
<label for="clubDescription">클럽 설명</label>
<Textarea id="clubDescription" v-model="clubDescription" rows="4" class="w-full" :class="{'p-invalid': clubDescriptionError}" />
<small v-if="clubDescriptionError" class="p-error">{{ clubDescriptionError }}</small>
</div>
<div class="form-group">
<label for="clubLocation">활동 볼링장</label>
<InputText id="clubLocation" v-model="clubLocation" class="w-full" />
</div>
<div class="form-group">
<label for="clubContact">연락처</label>
<InputText id="clubContact" v-model="clubContact" class="w-full" />
</div>
<Button type="submit" label="클럽 생성하기" class="w-full" :loading="loading" />
</form>
</div>
<Toast />
</div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useToast } from 'primevue/usetoast';
import clubService from '@/services/clubService';
import { useAuthStore } from '@/stores/authStore';
import axios from 'axios'
const toast = useToast();
const authStore = useAuthStore();
const router = useRouter();
const clubName = ref('');
const clubDescription = ref('');
const clubLocation = ref('');
const clubContact = ref('');
const loading = ref(false);
const clubNameError = ref('');
const clubDescriptionError = ref('');
onMounted(() => {
authStore.loadUserInfo();
});
const validateForm = () => {
let isValid = true;
// 클럽 이름 유효성 검사
if (!clubName.value) {
clubNameError.value = '클럽 이름을 입력해주세요.';
isValid = false;
} else {
clubNameError.value = '';
}
// 클럽 설명 유효성 검사
if (!clubDescription.value) {
clubDescriptionError.value = '클럽 설명을 입력해주세요.';
isValid = false;
} else {
clubDescriptionError.value = '';
}
return isValid;
};
const handleCreateClub = async () => {
if (!validateForm()) return;
if (!authStore.user) {
toast.add({ severity: 'error', summary: '오류', detail: '로그인이 필요합니다.', life: 3000 });
return;
}
loading.value = true;
try {
const response = await clubService.createClub({
name: clubName.value,
description: clubDescription.value,
location: clubLocation.value,
contact: clubContact.value,
ownerEmail: authStore.user.email
});
// 클럽 ID 저장
const clubId = response.data.id;
localStorage.setItem('clubId', clubId);
// 성공 메시지
toast.add({ severity: 'success', summary: '성공', detail: '클럽이 성공적으로 생성되었습니다.', life: 3000 });
// 클럽 페이지로 이동
router.push('/club');
} catch (error) {
console.error('클럽 생성 오류:', error);
// 오류 메시지 처리
const errorMessage = error.response?.data?.message || '클럽 생성에 실패했습니다. 다시 시도해주세요.';
toast.add({ severity: 'error', summary: '오류', detail: errorMessage, life: 3000 });
} finally {
loading.value = false;
}
};
</script>
<style scoped>
.club-create-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 80vh;
padding: 2rem 0;
}
.club-create-card {
width: 100%;
max-width: 600px;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
background-color: white;
}
.info-text {
margin-bottom: 1.5rem;
color: #666;
}
.form-group {
margin-bottom: 1.5rem;
}
.form-group label {
display: block;
margin-bottom: 0.5rem;
font-weight: 500;
}
.w-full {
width: 100%;
}
</style>
+299
View File
@@ -0,0 +1,299 @@
<template>
<div class="club-dashboard">
<h2>클럽 대시보드</h2>
<div v-if="loading" class="card flex justify-content-center">
<ProgressSpinner />
</div>
<div v-else class="grid">
<!-- 회원 통계 카드 -->
<div class="col-12 md:col-6 lg:col-3">
<div class="dashboard-card">
<div class="card-header">
<i class="pi pi-users"></i>
<h3>회원 현황</h3>
</div>
<div class="card-content">
<p> 회원: {{ memberStats.totalCount }}</p>
<p>정회원: {{ memberStats.regularCount }}</p>
<p>준회원: {{ memberStats.associateCount }}</p>
</div>
<div class="card-footer">
<Button label="회원 관리" icon="pi pi-arrow-right" @click="navigateTo('/club/members')" />
</div>
</div>
</div>
<!-- 다음 모임 카드 -->
<div class="col-12 md:col-6 lg:col-3">
<div class="dashboard-card">
<div class="card-header">
<i class="pi pi-calendar"></i>
<h3>다음 모임</h3>
</div>
<div class="card-content" v-if="nextMeeting">
<p>일시: {{ formatDate(nextMeeting.date) }}</p>
<p>장소: {{ nextMeeting.location || '미정' }}</p>
<p>참가 예정: {{ nextMeeting.participantsCount }}</p>
</div>
<div class="card-content" v-else>
<p>예정된 모임이 없습니다.</p>
</div>
<div class="card-footer">
<Button label="모임 관리" icon="pi pi-arrow-right" @click="navigateTo('/club/events')" />
</div>
</div>
</div>
<!-- 최근 모임 통계 카드 -->
<div class="col-12 md:col-6 lg:col-3">
<div class="dashboard-card">
<div class="card-header">
<i class="pi pi-chart-bar"></i>
<h3>최근 모임</h3>
</div>
<div class="card-content" v-if="lastMeeting">
<p>일시: {{ formatDate(lastMeeting.date) }}</p>
<p>참가자: {{ lastMeeting.participantsCount }}</p>
<p>게임 : {{ lastMeeting.games }}게임</p>
</div>
<div class="card-content" v-else>
<p>최근 모임 기록이 없습니다.</p>
</div>
<div class="card-footer">
<Button label="기록 보기" icon="pi pi-arrow-right" @click="navigateTo('/club/events')" />
</div>
</div>
</div>
<!-- 점수 통계 카드 -->
<div class="col-12 md:col-6 lg:col-3">
<div class="dashboard-card">
<div class="card-header">
<i class="pi pi-chart-line"></i>
<h3>점수 통계</h3>
</div>
<div class="card-content">
<p>최고 게임: {{ scoreStats.topGame || 0 }}</p>
<p>평균 점수: {{ scoreStats.averageScore || 0 }}</p>
<p>전체 게임: {{ scoreStats.totalGames || 0 }}게임</p>
</div>
<div class="card-footer">
<Button label="통계 보기" icon="pi pi-arrow-right" @click="navigateTo('/club/statistics')" />
</div>
</div>
</div>
</div>
<div class="grid mt-4">
<!-- 상위 회원 순위 -->
<div class="col-12 md:col-6">
<div class="dashboard-card">
<div class="card-header">
<h3>에버리지 순위</h3>
</div>
<DataTable :value="topMembers" :rows="5" stripedRows responsiveLayout="scroll">
<Column field="rank" header="#" :body="rankTemplate" style="width: 10%"></Column>
<Column field="name" header="이름" style="width: 30%"></Column>
<Column field="average" header="에버리지" :body="averageTemplate" style="width: 20%"></Column>
<Column field="games" header="게임 수" style="width: 20%"></Column>
<Column field="handicap" header="핸디캡" style="width: 20%"></Column>
</DataTable>
</div>
</div>
<!-- 최근 모임 목록 -->
<div class="col-12 md:col-6">
<div class="dashboard-card">
<div class="card-header">
<h3>최근 모임</h3>
</div>
<DataTable :value="recentMeetings" :rows="5" stripedRows responsiveLayout="scroll">
<Column field="date" header="일시" :body="dateTemplate" style="width: 25%"></Column>
<Column field="title" header="제목" style="width: 40%"></Column>
<Column field="participants" header="참가자" style="width: 15%"></Column>
<Column field="games" header="게임 수" style="width: 20%"></Column>
</DataTable>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import apiClient from '@/services/api';
import dayjs from 'dayjs';
import { useToast } from 'primevue/usetoast';
const router = useRouter();
const toast = useToast();
// 데이터 상태 변수들
const loading = ref(false);
const clubId = ref(null);
// 회원 통계
const memberStats = ref({
totalCount: 0,
regularCount: 0,
associateCount: 0
});
// 다음 모임 정보
const nextMeeting = ref(null);
// 최근 모임 정보
const lastMeeting = ref(null);
// 점수 통계
const scoreStats = ref({
topGame: 0,
averageScore: 0,
totalGames: 0
});
// 상위 회원 목록
const topMembers = ref([]);
// 최근 모임 목록
const recentMeetings = ref([]);
// 날짜 포맷 함수
const formatDate = (date) => {
return dayjs(date).format('YYYY-MM-DD HH:mm');
};
// 템플릿 함수들
const rankTemplate = (rowData, column) => {
return rowData.rank || topMembers.value.indexOf(rowData) + 1;
};
const averageTemplate = (rowData) => {
return rowData.average ? rowData.average.toFixed(1) : '0.0';
};
const dateTemplate = (rowData) => {
return formatDate(rowData.date);
};
// 데이터 로드 함수
const loadDashboardData = async () => {
if (!clubId.value) {
console.error('클럽 ID가 없습니다.');
return;
}
try {
loading.value = true;
// 회원 통계 로드
const membersResponse = await apiClient.post('/api/club/members/stats', {
clubId: clubId.value
});
memberStats.value = membersResponse.data;
// 다음 모임 정보 로드
const nextMeetingResponse = await apiClient.post('/api/club/meetings/next', {
clubId: clubId.value
});
nextMeeting.value = nextMeetingResponse.data;
// 최근 모임 정보 로드
const lastMeetingResponse = await apiClient.post('/api/club/meetings/last', {
clubId: clubId.value
});
lastMeeting.value = lastMeetingResponse.data;
// 점수 통계 로드
const scoreStatsResponse = await apiClient.post('/api/club/scores/stats', {
clubId: clubId.value
});
scoreStats.value = scoreStatsResponse.data;
// 상위 회원 목록 로드
const topMembersResponse = await apiClient.post('/api/club/members/top', {
clubId: clubId.value
});
topMembers.value = topMembersResponse.data;
// 최근 모임 목록 로드
const recentMeetingsResponse = await apiClient.post('/api/club/meetings/recent', {
clubId: clubId.value
});
recentMeetings.value = recentMeetingsResponse.data;
} catch (error) {
console.error('대시보드 데이터 로딩 오류:', error);
toast.add({
severity: 'error',
summary: '오류',
detail: '대시보드 데이터를 불러오는 중 오류가 발생했습니다.',
life: 3000
});
} finally {
loading.value = false;
}
};
// 페이지 이동 함수
const navigateTo = (path) => {
router.push(path);
};
// 컴포넌트 마운트 시 데이터 로드
onMounted(async () => {
clubId.value = localStorage.getItem('clubId') || null;
await loadDashboardData();
});
</script>
<style scoped>
.club-dashboard {
padding: 1rem;
}
.dashboard-card {
background: #ffffff;
border-radius: 10px;
padding: 1rem;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
height: 100%;
display: flex;
flex-direction: column;
}
.card-header {
display: flex;
align-items: center;
margin-bottom: 1rem;
gap: 0.5rem;
}
.card-header i {
font-size: 1.5rem;
color: var(--primary-color);
}
.card-header h3 {
margin: 0;
color: var(--text-color);
font-size: 1.2rem;
}
.card-content {
flex: 1;
margin-bottom: 1rem;
}
.card-content p {
margin: 0.5rem 0;
color: var(--text-color-secondary);
}
.card-footer {
margin-top: auto;
}
</style>
+201
View File
@@ -0,0 +1,201 @@
<template>
<div class="event-calendar-container">
<div class="header">
<h2>이벤트 캘린더</h2>
<Button label="이벤트 관리" icon="pi pi-cog" @click="navigateToEventManagement" />
</div>
<FullCalendar
:options="calendarOptions"
class="calendar-wrapper"
/>
<!-- 이벤트 상세 다이얼로그 -->
<EventDetailsDialog
v-model:visible="eventDetailsDialog"
:event="selectedEvent"
:getEventTypeName="getEventTypeName"
:getEventTypeSeverity="getEventTypeSeverity"
:getStatusName="getStatusName"
:getStatusSeverity="getStatusSeverity"
:formatDate="formatDate"
@edit="navigateToEventManagement"
@remove-participant="removeParticipant"
/>
<Toast />
</div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useToast } from 'primevue/usetoast';
import FullCalendar from '@fullcalendar/vue3';
import dayGridPlugin from '@fullcalendar/daygrid';
import interactionPlugin from '@fullcalendar/interaction';
import koLocale from '@fullcalendar/core/locales/ko';
import EventDetailsDialog from '@/components/event/EventDetailsDialog.vue';
import eventService from '@/services/eventService';
import {
getEventTypeName,
getEventTypeSeverity,
getStatusName,
getStatusSeverity,
formatDate
} from '@/utils/eventUtils';
const router = useRouter();
const toast = useToast();
// 상태 변수
const events = ref([]);
const selectedEvent = ref({});
const eventDetailsDialog = ref(false);
const loading = ref(false);
const clubId = ref(localStorage.getItem('clubId') || null);
// 페이지 로드 시 데이터 가져오기
onMounted(async () => {
await fetchEvents();
});
// 이벤트 목록 가져오기
const fetchEvents = async () => {
loading.value = true;
try {
const eventData = await eventService.getEvents(clubId.value);
events.value = eventData.map(event => ({
id: event.id,
title: event.title,
start: event.startDate,
end: event.endDate,
extendedProps: {
...event
},
backgroundColor: getEventColor(event.eventType),
borderColor: getEventColor(event.eventType),
textColor: '#ffffff'
}));
} catch (error) {
console.error('이벤트 목록을 가져오는 중 오류 발생:', error);
toast.add({ severity: 'error', summary: '오류', detail: '이벤트 목록을 가져오는 중 오류가 발생했습니다.', life: 3000 });
} finally {
loading.value = false;
}
};
// 이벤트 타입에 따른 색상 지정
const getEventColor = (eventType) => {
switch (eventType) {
case '정기전':
return '#FF5722'; // 주황색
case '번개':
return '#2196F3'; // 파란색
case '연습':
return '#4CAF50'; // 초록색
case '교류전':
return '#9C27B0'; // 보라색
case '이벤트':
return '#FFC107'; // 노란색
case '기타':
return '#607D8B'; // 회색
default:
return '#3f51b5'; // 기본색
}
};
// 캘린더 이벤트 클릭 핸들러
const handleEventClick = (info) => {
const eventId = info.event.id;
viewEventDetails(eventId);
};
// 이벤트 상세 보기
const viewEventDetails = async (eventId) => {
try {
selectedEvent.value = await eventService.getEventById(eventId);
eventDetailsDialog.value = true;
} catch (error) {
console.error('이벤트 상세 정보를 가져오는 중 오류 발생:', error);
toast.add({ severity: 'error', summary: '오류', detail: '이벤트 상세 정보를 가져오는 중 오류가 발생했습니다.', life: 3000 });
}
};
// 참가자 제거
const removeParticipant = async (participant) => {
try {
await eventService.removeParticipant(selectedEvent.value.id, participant.id);
// 참가자 목록에서 제거
selectedEvent.value.participants = selectedEvent.value.participants.filter(p => p.id !== participant.id);
toast.add({ severity: 'success', summary: '성공', detail: '참가자가 제거되었습니다.', life: 3000 });
} catch (error) {
console.error('참가자 제거 중 오류 발생:', error);
const errorMessage = error.response?.data?.message || '참가자 제거 중 오류가 발생했습니다.';
toast.add({ severity: 'error', summary: '오류', detail: errorMessage, life: 3000 });
}
};
// 이벤트 관리 페이지로 이동
const navigateToEventManagement = () => {
router.push('/club/events');
};
// 캘린더 옵션
const calendarOptions = computed(() => ({
plugins: [dayGridPlugin, interactionPlugin],
initialView: 'dayGridMonth',
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,dayGridWeek'
},
events: events.value,
eventClick: handleEventClick,
locale: 'ko',
height: 'auto',
eventTimeFormat: {
hour: '2-digit',
minute: '2-digit',
meridiem: false,
hour12: false
},
dayMaxEvents: true
}));
</script>
<style scoped>
.event-calendar-container {
padding: 1rem;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1.5rem;
}
.calendar-wrapper {
height: calc(100vh - 200px);
margin-bottom: 2rem;
}
:deep(.fc-event) {
cursor: pointer;
}
:deep(.fc-toolbar-title) {
font-size: 1.5rem !important;
}
:deep(.fc-daygrid-day-number) {
font-size: 1rem;
}
:deep(.fc-col-header-cell-cushion) {
font-weight: 600;
}
</style>
+480
View File
@@ -0,0 +1,480 @@
<template>
<div class="event-management-container">
<div class="header">
<h2>이벤트 관리</h2>
<div class="header-buttons">
<Button label="캘린더 보기" icon="pi pi-calendar" class="p-button-outlined mr-2" @click="navigateToCalendar" />
<Button label="이벤트 추가" icon="pi pi-plus" @click="openNewEventDialog" />
</div>
</div>
<!-- 이벤트 목록 -->
<DataTable
:value="events"
:loading="loading"
:paginator="true"
:rows="10"
:rowsPerPageOptions="[5, 10, 20, 50]"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
currentPageReportTemplate="{first}에서 {last}까지 {totalRecords} 중"
responsiveLayout="scroll"
stripedRows
filterDisplay="menu"
v-model:filters="filters"
class="mt-4"
>
<Column field="id" header="ID" sortable style="width: 5%"></Column>
<Column field="title" header="제목" sortable style="width: 20%">
<template #filter="{ filterModel, filterCallback }">
<InputText v-model="filterModel.value" @input="filterCallback()" class="p-column-filter" placeholder="제목으로 검색" />
</template>
</Column>
<Column field="eventType" header="유형" sortable style="width: 10%">
<template #body="slotProps">
<Badge :value="getEventTypeName(slotProps.data.eventType)" :severity="getEventTypeSeverity(slotProps.data.eventType)" />
</template>
<template #filter="{ filterModel, filterCallback }">
<Dropdown v-model="filterModel.value" @change="filterCallback()" :options="eventTypeOptions" optionLabel="name" optionValue="value" placeholder="유형 선택" class="p-column-filter" />
</template>
</Column>
<Column field="startDate" header="시작일" sortable style="width: 12%">
<template #body="slotProps">
{{ formatDate(slotProps.data.startDate) }}
</template>
<template #filter="{ filterModel, filterCallback }">
<Calendar v-model="filterModel.value" @date-select="filterCallback()" dateFormat="yy-mm-dd" placeholder="날짜 선택" />
</template>
</Column>
<Column field="endDate" header="종료일" sortable style="width: 12%">
<template #body="slotProps">
{{ formatDate(slotProps.data.endDate) }}
</template>
</Column>
<Column field="location" header="장소" sortable style="width: 15%"></Column>
<Column field="maxParticipants" header="최대 인원" sortable style="width: 8%"></Column>
<Column field="status" header="상태" sortable style="width: 8%">
<template #body="slotProps">
<Badge :value="slotProps.data.status" :severity="getStatusSeverity(slotProps.data.status)" />
</template>
</Column>
<Column header="작업" style="width: 10%">
<template #body="slotProps">
<div class="flex gap-2">
<Button icon="pi pi-eye" class="p-button-rounded p-button-text" @click="viewEventDetails(slotProps.data)" />
<Button icon="pi pi-pencil" class="p-button-rounded p-button-text" @click="editEvent(slotProps.data)" />
<Button icon="pi pi-trash" class="p-button-rounded p-button-text p-button-danger" @click="confirmDeleteEvent(slotProps.data)" />
</div>
</template>
</Column>
</DataTable>
<!-- 이벤트 다이얼로그 -->
<EventDialog
v-model:visible="eventDialog"
:event="event || {}"
:isNew="!event?.id"
:submitted="submitted"
@save="saveEvent"
@hide="hideDialog"
/>
<!-- 이벤트 상세 정보 다이얼로그 -->
<EventDetailsDialog
v-model:visible="detailsDialog"
:event="event || {}"
:getEventTypeName="getEventTypeName"
:getEventTypeSeverity="getEventTypeSeverity"
:getStatusName="getStatusName"
:getStatusSeverity="getStatusSeverity"
:formatDate="formatDate"
:availableMembers="clubMembers"
@edit="editFromDetails"
@hide="hideDialog"
@participant-updated="fetchEvents"
@score-updated="fetchEvents"
/>
<!-- 삭제 확인 다이얼로그 -->
<Dialog v-model:visible="deleteEventDialog" :style="{ width: '450px' }" header="확인" :modal="true">
<div class="confirmation-content">
<i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem" />
<span v-if="event">{{ event.title }} 이벤트를 삭제하시겠습니까?</span>
</div>
<template #footer>
<Button label="아니오" icon="pi pi-times" class="p-button-text" @click="deleteEventDialog = false" />
<Button label="예" icon="pi pi-check" class="p-button-danger" @click="deleteEvent" />
</template>
</Dialog>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { useToast } from 'primevue/usetoast';
import { useRoute } from 'vue-router';
import { useClubStore } from '@/stores/clubStore';
import eventService from '@/services/eventService';
import clubService from '@/services/clubService';
import ScoreManagement from '@/components/event/ScoreManagement.vue';
import ParticipantManagement from '@/components/event/ParticipantManagement.vue';
import TabView from 'primevue/tabview';
import TabPanel from 'primevue/tabpanel';
import Dialog from 'primevue/dialog';
import Button from 'primevue/button';
import EventDialog from '@/components/event/EventDialog.vue';
import EventDetailsDialog from '@/components/event/EventDetailsDialog.vue';
const toast = useToast();
const route = useRoute();
const clubStore = useClubStore();
// 상태 관리
const events = ref([]);
const event = ref({});
const eventDialog = ref(false);
const deleteEventDialog = ref(false);
const detailsDialog = ref(false);
const loading = ref(false);
const submitted = ref(false);
const clubId = ref(localStorage.getItem('clubId') || null);
// 필터 상태
const filters = ref({
title: { value: null, matchMode: 'contains' },
eventType: { value: null, matchMode: 'equals' },
startDate: { value: null, matchMode: 'equals' }
});
// 이벤트 유형 옵션
const eventTypeOptions = [
{ name: '정기전', value: '정기전' },
{ name: '토너먼트', value: '토너먼트' },
{ name: '연습', value: '연습' },
{ name: '친선전', value: '친선전' },
{ name: '기타', value: '기타' }
];
// 클럽 멤버 목록
const clubMembers = ref([]);
// 이벤트 목록 가져오기
const fetchEvents = async () => {
loading.value = true;
try {
const response = await eventService.getEvents(clubId.value);
events.value = response;
} catch (error) {
toast.add({
severity: 'error',
summary: '오류',
detail: '이벤트 목록을 가져오는데 실패했습니다.',
life: 3000
});
} finally {
loading.value = false;
}
};
// 클럽 멤버 목록 가져오기
const fetchClubMembers = async () => {
try {
const response = await clubService.getClubMembers(clubId.value);
clubMembers.value = response.data.map(member => ({
id: member.memberId || member.id, // memberId 또는 id 필드 사용
name: member.name,
memberType: member.memberType
}));
} catch (error) {
toast.add({
severity: 'error',
summary: '오류',
detail: '클럽 멤버 목록을 가져오는 중 오류가 발생했습니다.',
life: 3000
});
}
};
// 컴포넌트 마운트 시 데이터 로드
onMounted(async () => {
if (!clubId.value) {
toast.add({
severity: 'error',
summary: '오류',
detail: '클럽 정보가 없습니다.',
life: 3000
});
return;
}
await Promise.all([
fetchEvents(),
fetchClubMembers()
]);
});
// 날짜 포맷 함수
const formatDate = (date) => {
if (!date) return '';
const d = new Date(date);
return d.toLocaleString('ko-KR', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
});
};
// 이벤트 유형에 따른 Badge 스타일
const getEventTypeSeverity = (type) => {
switch (type) {
case '정기전': return 'success';
case '토너먼트': return 'warning';
case '연습': return 'info';
case '친선전': return 'primary';
default: return 'secondary';
}
};
// 이벤트 유형 이름 반환
const getEventTypeName = (type) => {
return type || '기타';
};
// 이벤트 상태 이름 반환
const getStatusName = (status) => {
switch (status) {
case '준비': return '준비';
case '진행중': return '진행중';
case '완료': return '완료';
case '취소': return '취소';
default: return '알 수 없음';
}
};
// 이벤트 상태에 따른 Badge 스타일
const getStatusSeverity = (status) => {
switch (status) {
case '준비': return 'info';
case '진행중': return 'warning';
case '완료': return 'success';
case '취소': return 'danger';
default: return 'secondary';
}
};
// 새 이벤트 다이얼로그 열기
const openNewEventDialog = () => {
event.value = {
clubId: clubId.value,
status: '준비',
eventType: '정기전',
title: '',
description: '',
startDate: null,
endDate: null,
location: '',
maxParticipants: 0,
teamCount: 1,
gameCount: 1,
laneCount: 0,
participantFee: 0
};
submitted.value = false;
eventDialog.value = true;
};
// 이벤트 수정 다이얼로그 열기
const editEvent = (eventData) => {
event.value = { ...eventData };
submitted.value = false;
eventDialog.value = true;
};
// 이벤트 상세 정보 보기
const viewEventDetails = async (eventData) => {
try {
const response = await eventService.getEventById(eventData.id);
event.value = response;
detailsDialog.value = true;
} catch (error) {
toast.add({
severity: 'error',
summary: '오류',
detail: '이벤트 상세 정보를 가져오는데 실패했습니다.',
life: 3000
});
}
};
// 상세 보기에서 수정으로 전환
const editFromDetails = () => {
detailsDialog.value = false;
eventDialog.value = true;
};
// 다이얼로그 닫기
const hideDialog = () => {
eventDialog.value = false;
detailsDialog.value = false;
deleteEventDialog.value = false;
event.value = {};
submitted.value = false;
};
// 이벤트 삭제 확인
const confirmDeleteEvent = (eventData) => {
event.value = eventData;
deleteEventDialog.value = true;
};
// 이벤트 저장
const saveEvent = async (eventData) => {
try {
if (eventData.id) {
// 이벤트 수정
const response = await eventService.updateEvent({
...eventData,
clubId: clubId.value
});
const updatedEvent = response;
const index = events.value.findIndex(e => e.id === updatedEvent.id);
if (index !== -1) {
events.value[index] = updatedEvent;
}
} else {
// 이벤트 생성
const response = await eventService.createEvent({
...eventData,
clubId: clubId.value
});
events.value.push(response);
}
toast.add({
severity: 'success',
summary: '성공',
detail: eventData.id ? '이벤트가 수정되었습니다.' : '이벤트가 생성되었습니다.',
life: 3000
});
hideDialog();
} catch (error) {
toast.add({
severity: 'error',
summary: '오류',
detail: eventData.id ? '이벤트 수정에 실패했습니다.' : '이벤트 생성에 실패했습니다.',
life: 3000
});
}
};
// 이벤트 삭제
const deleteEvent = async () => {
try {
await eventService.deleteEvent(clubId.value, event.value.id);
toast.add({
severity: 'success',
summary: '성공',
detail: '이벤트가 삭제되었습니다.',
life: 3000
});
deleteEventDialog.value = false;
const index = events.value.findIndex(e => e.id === event.value.id);
if (index > -1) {
events.value.splice(index, 1);
}
event.value = {};
} catch (error) {
toast.add({
severity: 'error',
summary: '오류',
detail: '이벤트 삭제에 실패했습니다.',
life: 3000
});
}
};
// 참가자 제거
const removeParticipant = async (participant) => {
try {
await eventService.removeParticipant(event.value.id, participant.id);
toast.add({
severity: 'success',
summary: '성공',
detail: '참가자가 제거되었습니다.',
life: 3000
});
// 참가자 목록 업데이트
const index = event.value.participants.findIndex(p => p.id === participant.id);
if (index > -1) {
event.value.participants.splice(index, 1);
}
} catch (error) {
toast.add({
severity: 'error',
summary: '오류',
detail: '참가자 제거에 실패했습니다.',
life: 3000
});
}
};
// 점수 입력 페이지로 이동
const goToScoreEntry = () => {
const url = `/club/events/${event.value.id}/scores?clubId=${clubId.value}`;
window.location.href = url;
};
// 이벤트 캘린더 페이지로 이동
const navigateToCalendar = () => {
const url = `/club/calendar?clubId=${clubId.value}`;
window.location.href = url;
};
</script>
<style scoped>
.event-management-container {
padding: 2rem;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 2rem;
}
.header h2 {
margin: 0;
}
.header-buttons {
display: flex;
gap: 0.5rem;
}
.confirmation-content {
display: flex;
align-items: center;
justify-content: center;
gap: 1rem;
}
.flex {
display: flex;
}
.gap-2 {
gap: 0.5rem;
}
:deep(.p-datatable) {
margin-top: 1rem;
}
:deep(.p-column-filter) {
width: 100%;
}
</style>
@@ -0,0 +1,558 @@
<template>
<div class="member-management">
<div class="header">
<h2>회원 관리</h2>
<Button label="새 회원 추가" icon="pi pi-plus" @click="openNewMemberDialog" />
</div>
<div class="filter-section">
<div class="grid">
<div class="col-12 md:col-6">
<div class="w-full">
<i class="pi pi-search" />
<InputText v-model="filters.searchText" placeholder="이름, 전화번호, 이메일로 검색" class="w-full searchText" />
</div>
</div>
<div class="col-12 md:col-6 text-right">
<Button icon="pi pi-filter" label="상세 필터" @click="filterDialog = true"
:class="{'p-button-info': isFilterActive}" />
</div>
</div>
</div>
<DataTable :value="filteredMembers" :paginator="true" :rows="10"
:rowsPerPageOptions="[5, 10, 20]"
stripedRows responsiveLayout="scroll">
<Column field="name" header="이름" sortable style="width: 15%"></Column>
<Column field="gender" header="성별" sortable style="width: 10%"></Column>
<Column field="memberType" header="회원 유형" sortable style="width: 15%">
<template #body="slotProps">
<span :class="getMemberTypeClass(slotProps.data.memberType)">
{{ slotProps.data.memberType }}
</span>
</template>
</Column>
<Column field="handicap" header="핸디캡" sortable style="width: 10%"></Column>
<Column field="average" header="에버리지" sortable style="width: 10%"></Column>
<Column field="games" header="게임 수" sortable style="width: 10%"></Column>
<Column field="joinDate" header="가입일" sortable style="width: 10%">
<template #body="slotProps">
{{ formatDate(slotProps.data.joinDate) }}
</template>
</Column>
<Column field="status" header="상태" sortable style="width: 10%">
<template #body="slotProps">
<span :class="`status-${slotProps.data.status}`">
{{ getStatusLabel(slotProps.data.status) }}
</span>
</template>
</Column>
<Column header="관리" style="width: 15%">
<template #body="slotProps">
<Button icon="pi pi-pencil" class="p-button-rounded p-button-success mr-2"
@click="editMember(slotProps.data)" />
<Button icon="pi pi-trash" class="p-button-rounded p-button-danger"
@click="confirmDeleteMember(slotProps.data)" />
</template>
</Column>
</DataTable>
<!-- 회원 추가/수정 다이얼로그 -->
<Dialog v-model:visible="memberDialog" :style="{width: '450px'}"
:header="dialogMode === 'new' ? '새 회원 추가' : '회원 정보 수정'"
:modal="true" class="p-fluid">
<div class="field">
<label for="name">이름</label>
<InputText id="name" v-model="member.name" required autofocus />
</div>
<div class="field">
<label for="gender">성별</label>
<Dropdown id="gender" v-model="member.gender" :options="genderOptions"
optionLabel="name" placeholder="성별 선택" />
</div>
<div class="field">
<label for="memberType">회원 유형</label>
<Dropdown id="memberType" v-model="member.memberTypeObj" :options="memberTypes"
optionLabel="name" placeholder="회원 유형 선택" />
</div>
<div class="field">
<label for="phone">전화번호</label>
<InputText id="phone" v-model="member.phone" />
</div>
<div class="field">
<label for="email">이메일</label>
<InputText id="email" v-model="member.email" />
</div>
<div class="field">
<label for="handicap">핸디캡</label>
<InputText id="handicap" v-model="member.handicap" type="number" min="0" max="50" />
</div>
<div class="field">
<label for="status">상태</label>
<Dropdown id="status" v-model="member.status" :options="statusOptions"
optionLabel="label" optionValue="value" placeholder="상태 선택" />
</div>
<template #footer>
<Button label="취소" icon="pi pi-times" class="p-button-text" @click="hideDialog" />
<Button label="저장" icon="pi pi-check" class="p-button-text" @click="saveMember" />
</template>
</Dialog>
<!-- 삭제 확인 다이얼로그 -->
<Dialog v-model:visible="deleteDialog" :style="{width: '450px'}"
header="회원 삭제" :modal="true">
<div class="confirmation-content">
<i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem" />
<span v-if="selectedMember">정말로 <b>{{ selectedMember.name }}</b> 회원을 삭제하시겠습니까?</span>
</div>
<template #footer>
<Button label="아니오" icon="pi pi-times" class="p-button-text" @click="deleteDialog = false" />
<Button label="예" icon="pi pi-check" class="p-button-text" @click="deleteMember" />
</template>
</Dialog>
<!-- 상세 필터 다이얼로그 -->
<Dialog v-model:visible="filterDialog" header="상세 필터" :style="{width: '450px'}" :modal="true">
<div class="grid p-fluid">
<div class="col-12 md:col-4">
<div class="field">
<label>회원 유형</label>
<MultiSelect v-model="filters.memberTypes" :options="memberTypes" optionLabel="name"
placeholder="선택" class="w-full" />
</div>
</div>
<div class="col-12 md:col-4">
<div class="field">
<label>성별</label>
<MultiSelect v-model="filters.genders" :options="genderOptions" optionLabel="name"
placeholder="선택" class="w-full" />
</div>
</div>
<div class="col-12 md:col-4">
<div class="field">
<label>상태</label>
<MultiSelect v-model="filters.statuses" :options="statusOptions" optionLabel="label"
placeholder="선택" class="w-full" />
</div>
</div>
<div class="col-12 md:col-4">
<div class="field">
<label>핸디캡</label>
<div class="p-inputgroup">
<InputNumber v-model="filters.handicapFrom" placeholder="최소" class="p-inputgroup-left" size="small" />
<InputNumber v-model="filters.handicapTo" placeholder="최대" class="p-inputgroup-right" size="small" />
</div>
</div>
</div>
<div class="col-12 md:col-4">
<div class="field">
<label>에버리지</label>
<div class="p-inputgroup">
<InputNumber v-model="filters.averageFrom" placeholder="최소" mode="decimal"
:minFractionDigits="1" :maxFractionDigits="1" class="p-inputgroup-left" size="small" />
<InputNumber v-model="filters.averageTo" placeholder="최대" mode="decimal"
:minFractionDigits="1" :maxFractionDigits="1" class="p-inputgroup-right" size="small" />
</div>
</div>
</div>
<div class="col-12 md:col-4">
<div class="field">
<label>게임 </label>
<div class="p-inputgroup">
<InputNumber v-model="filters.gamesFrom" placeholder="최소" class="p-inputgroup-left" size="small" />
<InputNumber v-model="filters.gamesTo" placeholder="최대" class="p-inputgroup-right" size="small" />
</div>
</div>
</div>
</div>
<template #footer>
<Button label="필터 초기화" icon="pi pi-refresh" class="p-button-text" @click="resetFilters" />
<Button label="적용" icon="pi pi-check" @click="applyFilters" />
</template>
</Dialog>
</div>
</template>
<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useToast } from 'primevue/usetoast';
import Button from 'primevue/button';
import InputText from 'primevue/inputtext';
import MultiSelect from 'primevue/multiselect';
import InputNumber from 'primevue/inputnumber';
import Dialog from 'primevue/dialog';
import DataTable from 'primevue/datatable';
import Column from 'primevue/column';
import apiClient from '@/services/api';
import clubService from '@/services/clubService';
const toast = useToast();
// 회원 유형 목록
const memberTypes = ref([
{ name: '정회원', code: 'regular' },
{ name: '준회원', code: 'associate' },
{ name: '운영진', code: 'admin' },
{ name: '모임장', code: 'owner' }
]);
// 성별 옵션
const genderOptions = ref([
{ name: '남성', code: 'male' },
{ name: '여성', code: 'female' }
]);
// 회원 목록
const members = ref([]);
// 현재 클럽 ID
const clubId = ref(localStorage.getItem('clubId') || null);
// 데이터 로딩 상태
const loading = ref(true);
// 다이얼로그 상태
const memberDialog = ref(false);
const deleteDialog = ref(false);
const filterDialog = ref(false);
const dialogMode = ref('new');
const member = ref({});
const selectedMember = ref(null);
// 필터
const filters = reactive({
searchText: '',
memberTypes: [],
genders: [],
statuses: [],
handicapFrom: null,
handicapTo: null,
averageFrom: null,
averageTo: null,
gamesFrom: null,
gamesTo: null
});
// 필터 활성화 여부 확인
const isFilterActive = computed(() => {
return filters.memberTypes.length > 0 ||
filters.genders.length > 0 ||
filters.statuses.length > 0 ||
filters.handicapFrom ||
filters.handicapTo ||
filters.averageFrom ||
filters.averageTo ||
filters.gamesFrom ||
filters.gamesTo;
});
// 필터링된 회원 목록
const filteredMembers = computed(() => {
if (!members.value) return [];
return members.value.filter(member => {
// 기본 검색 (이름, 전화번호, 이메일)
if (filters.searchText) {
const searchText = filters.searchText.toLowerCase();
const matchesSearch =
member.name?.toLowerCase().includes(searchText) ||
member.phone?.toLowerCase().includes(searchText) ||
member.email?.toLowerCase().includes(searchText);
if (!matchesSearch) return false;
}
// 회원 유형 필터
if (filters.memberTypes.length > 0 &&
!filters.memberTypes.some(type => type.name === member.memberType)) {
return false;
}
// 성별 필터
if (filters.genders.length > 0 &&
!filters.genders.some(gender => gender.name === member.gender)) {
return false;
}
// 상태 필터
if (filters.statuses.length > 0 &&
!filters.statuses.some(status => status.value === member.status)) {
return false;
}
// 핸디캡 범위 필터
if (filters.handicapFrom !== null && member.handicap < filters.handicapFrom) return false;
if (filters.handicapTo !== null && member.handicap > filters.handicapTo) return false;
// 에버리지 범위 필터
if (filters.averageFrom !== null && member.average < filters.averageFrom) return false;
if (filters.averageTo !== null && member.average > filters.averageTo) return false;
// 게임 수 범위 필터
if (filters.gamesFrom !== null && member.games < filters.gamesFrom) return false;
if (filters.gamesTo !== null && member.games > filters.gamesTo) return false;
return true;
});
});
// 필터 초기화
const resetFilters = () => {
filters.memberTypes = [];
filters.genders = [];
filters.statuses = [];
filters.handicapFrom = null;
filters.handicapTo = null;
filters.averageFrom = null;
filters.averageTo = null;
filters.gamesFrom = null;
filters.gamesTo = null;
};
// 필터 적용
const applyFilters = () => {
filterDialog.value = false;
};
// 날짜 형식 변환 함수
const formatDate = (dateStr) => {
if (!dateStr) return '';
const date = new Date(dateStr);
return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`;
};
// 회원 상태 표시 함수
const getStatusLabel = (status) => {
switch (status) {
case 'active': return '활성';
case 'inactive': return '비활성';
case 'suspended': return '정지';
case 'deleted': return '삭제됨';
default: return status;
}
};
// 컴포넌트 마운트 시 데이터 로드
onMounted(async () => {
try {
loading.value = true;
await loadMembers();
} catch (error) {
console.error('회원 데이터 로딩 오류:', error);
toast.add({ severity: 'error', summary: '오류', detail: '회원 데이터 로딩 중 오류가 발생했습니다.', life: 3000 });
} finally {
loading.value = false;
}
});
// 회원 목록 로드 함수
const loadMembers = async () => {
if (!clubId.value) {
console.error('클럽 ID가 없습니다.');
return;
}
try {
const response = await clubService.getClubMembers(clubId.value);
members.value = response.data || [];
} catch (error) {
console.error('회원 목록 로딩 중 오류 발생:', error);
throw error;
}
};
// 회원 유형에 따른 클래스 반환
const getMemberTypeClass = (type) => {
switch (type) {
case '모임장': return 'member-type-owner';
case '운영진': return 'member-type-admin';
case '정회원': return 'member-type-regular';
case '준회원': return 'member-type-associate';
default: return '';
}
};
// 새 회원 추가 다이얼로그 열기
const openNewMemberDialog = () => {
member.value = {
name: '',
gender: null,
memberTypeObj: null,
phone: '',
email: '',
handicap: 0
};
dialogMode.value = 'new';
memberDialog.value = true;
};
// 회원 수정 다이얼로그 열기
const editMember = (data) => {
member.value = { ...data };
dialogMode.value = 'edit';
memberDialog.value = true;
};
// 다이얼로그 닫기
const hideDialog = () => {
memberDialog.value = false;
};
// 회원 저장
const saveMember = async () => {
try {
if (dialogMode.value === 'new') {
await clubService.addClubMember(clubId.value, member.value);
toast.add({ severity: 'success', summary: '성공', detail: '새 회원이 추가되었습니다.', life: 3000 });
} else {
await clubService.updateClubMember(clubId.value, member.value.id, member.value);
toast.add({ severity: 'success', summary: '성공', detail: '회원 정보가 수정되었습니다.', life: 3000 });
}
hideDialog();
await loadMembers();
} catch (error) {
console.error('회원 저장 중 오류:', error);
toast.add({ severity: 'error', summary: '오류', detail: '회원 정보 저장 중 오류가 발생했습니다.', life: 3000 });
}
};
// 회원 삭제 확인
const confirmDeleteMember = (data) => {
selectedMember.value = data;
deleteDialog.value = true;
};
// 회원 삭제
const deleteMember = async () => {
try {
await clubService.deleteClubMember(clubId.value, selectedMember.value.id);
deleteDialog.value = false;
toast.add({ severity: 'success', summary: '성공', detail: '회원이 삭제되었습니다.', life: 3000 });
await loadMembers();
} catch (error) {
console.error('회원 삭제 중 오류:', error);
toast.add({ severity: 'error', summary: '오류', detail: '회원 삭제 중 오류가 발생했습니다.', life: 3000 });
}
};
const statusOptions = ref([
{ label: '활성', value: 'active' },
{ label: '비활성', value: 'inactive' },
{ label: '정지', value: 'suspended' }
]);
</script>
<style scoped>
.member-management {
padding: 1rem;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
}
.header h2 {
margin: 0;
}
.filter-section {
margin-bottom: 1rem;
}
.member-type-regular {
color: #3B82F6;
font-weight: bold;
}
.member-type-associate {
color: #10B981;
font-weight: bold;
}
.member-type-admin {
color: #F59E0B;
font-weight: bold;
}
.member-type-owner {
color: #EF4444;
font-weight: bold;
}
/* 필터 다이얼로그 스타일 */
:deep(.p-dialog-content) {
padding: 1rem;
}
:deep(.field) {
margin-bottom: 0.75rem;
}
:deep(.field label) {
display: block;
margin-bottom: 0.25rem;
font-size: 0.875rem;
color: var(--text-color-secondary);
}
:deep(.p-inputnumber-input) {
padding: 0.25rem 0.5rem;
}
/* InputGroup 스타일 */
:deep(.p-inputgroup) {
display: flex;
width: 100%;
position: relative;
}
:deep(.p-inputgroup .p-inputnumber) {
flex: 1;
}
:deep(.p-inputgroup .p-inputnumber-input) {
border-radius: 0;
width: 100%;
padding-left: 0.5rem !important;
}
:deep(.p-inputgroup-left .p-inputnumber-input) {
border-top-left-radius: 6px;
border-bottom-left-radius: 6px;
border-right: none;
}
:deep(.p-inputgroup-right .p-inputnumber-input) {
border-top-right-radius: 6px;
border-bottom-right-radius: 6px;
border-left: 1px solid var(--surface-border);
}
:deep(.p-inputgroup .p-inputnumber:focus-within) {
z-index: 1;
}
/* 검색 필드 스타일 */
:deep(.filter-section) {
position: relative;
}
:deep(.filter-section .searchText) {
width: 100%;
padding-left: 2.5rem !important;
}
:deep(.filter-section .pi-search) {
position: absolute;
left: 0.75rem;
top: 50%;
transform: translateY(-50%);
color: var(--text-color-secondary);
z-index: 2;
}
</style>
+609
View File
@@ -0,0 +1,609 @@
<template>
<div class="score-management">
<div class="header">
<div class="meeting-info">
<h2>{{ meetingTitle }}</h2>
<div class="meeting-details">
<span><i class="pi pi-calendar"></i> {{ meetingDate }}</span>
<span><i class="pi pi-map-marker"></i> {{ meetingLocation }}</span>
<span><i class="pi pi-users"></i> 참가자: {{ participants.length }}</span>
</div>
</div>
<div class="actions">
<Button label="저장" icon="pi pi-save" @click="saveAllScores" />
<Button label="내보내기" icon="pi pi-file-excel" class="p-button-success ml-2" @click="exportScores" />
<Button label="뒤로" icon="pi pi-arrow-left" class="p-button-secondary ml-2" @click="goBack" />
</div>
</div>
<div class="card">
<TabView>
<TabPanel header="점수 입력">
<div class="filter-section mb-3">
<div class="grid">
<div class="col-12 md:col-4">
<span class="p-input-icon-left w-full">
<i class="pi pi-search" />
<InputText v-model="filters.global" placeholder="이름 검색" class="w-full" />
</span>
</div>
<div class="col-12 md:col-4">
<Dropdown v-model="filters.team" :options="teamOptions" optionLabel="name"
placeholder="팀 선택" class="w-full" />
</div>
<div class="col-12 md:col-4">
<MultiSelect v-model="selectedGames" :options="gameOptions" optionLabel="name"
placeholder="게임 선택" class="w-full" />
</div>
</div>
</div>
<DataTable :value="filteredParticipants" :paginator="true" :rows="10"
stripedRows responsiveLayout="scroll"
v-model:expandedRows="expandedRows">
<Column :expander="true" headerStyle="width: 3rem" />
<Column field="name" header="이름" sortable style="width: 15%"></Column>
<Column field="teamNumber" header="팀" sortable style="width: 8%"></Column>
<Column field="handicap" header="핸디캡" sortable style="width: 10%">
<template #body="slotProps">
<InputNumber v-model="slotProps.data.handicap"
:min="0" :max="50"
@blur="calculateTotal(slotProps.data)" />
</template>
</Column>
<template v-for="game in gameCount" :key="game">
<Column :field="`game${game}`" :header="`G${game}`" sortable style="width: 8%">
<template #body="slotProps">
<InputNumber v-model="slotProps.data[`game${game}`]"
:min="0" :max="300"
@blur="calculateTotal(slotProps.data)" />
</template>
</Column>
</template>
<Column field="totalPins" header="총점" sortable style="width: 10%"></Column>
<Column field="totalWithHandicap" header="핸디포함" sortable style="width: 10%"></Column>
<Column field="average" header="에버리지" sortable style="width: 10%"></Column>
<template #expansion="slotProps">
<div class="score-history p-3">
<h4>이전 점수 기록</h4>
<DataTable :value="slotProps.data.history" responsiveLayout="scroll">
<Column field="date" header="날짜"></Column>
<Column field="location" header="장소"></Column>
<Column v-for="game in 3" :key="game" :field="`game${game}`" :header="`G${game}`"></Column>
<Column field="average" header="에버리지"></Column>
</DataTable>
</div>
</template>
</DataTable>
</TabPanel>
<TabPanel header="팀별 점수">
<div class="team-scores">
<div class="grid">
<div v-for="team in teamScores" :key="team.teamNumber" class="col-12 md:col-6 lg:col-4">
<div class="team-card">
<div class="team-header">
<h3> {{ team.teamNumber }}</h3>
<div class="team-stats">
<span>인원: {{ team.members.length }}</span>
<span>평균: {{ team.average.toFixed(1) }}</span>
</div>
</div>
<DataTable :value="team.members" responsiveLayout="scroll">
<Column field="name" header="이름"></Column>
<Column v-for="game in gameCount" :key="game" :field="`game${game}`" :header="`G${game}`"></Column>
<Column field="totalWithHandicap" header="총점"></Column>
</DataTable>
<div class="team-totals">
<div class="grid">
<div v-for="game in gameCount" :key="game" class="col">
<div class="game-total">
<span>G{{ game }}: {{ team.gameTotals[game-1] }}</span>
</div>
</div>
<div class="col">
<div class="game-total total">
<span>총점: {{ team.total }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</TabPanel>
<TabPanel header="개인 순위">
<div class="ranking-filters mb-3">
<div class="grid">
<div class="col-12 md:col-4">
<Dropdown v-model="rankingType" :options="rankingOptions" optionLabel="name"
placeholder="순위 유형" class="w-full" />
</div>
<div class="col-12 md:col-4">
<Dropdown v-model="rankingGame" :options="gameRankingOptions" optionLabel="name"
placeholder="게임 선택" class="w-full" />
</div>
</div>
</div>
<DataTable :value="individualRankings" :paginator="true" :rows="10"
stripedRows responsiveLayout="scroll">
<Column field="rank" header="순위" style="width: 8%">
<template #body="slotProps">
<span class="rank-badge" :class="getRankClass(slotProps.data.rank)">
{{ slotProps.data.rank }}
</span>
</template>
</Column>
<Column field="name" header="이름" sortable style="width: 15%"></Column>
<Column field="teamNumber" header="팀" sortable style="width: 8%"></Column>
<Column field="handicap" header="핸디캡" sortable style="width: 10%"></Column>
<Column v-if="rankingGame.code === 'all'"
v-for="game in gameCount" :key="game"
:field="`game${game}`" :header="`G${game}`" sortable style="width: 8%"></Column>
<Column v-if="rankingGame.code !== 'all'"
:field="rankingGame.code" :header="rankingGame.name" sortable style="width: 12%"></Column>
<Column field="totalPins" header="총점" sortable style="width: 10%"></Column>
<Column field="totalWithHandicap" header="핸디포함" sortable style="width: 10%"></Column>
<Column field="average" header="에버리지" sortable style="width: 10%"></Column>
</DataTable>
</TabPanel>
<TabPanel header="팀 순위">
<DataTable :value="teamRankings" :paginator="true" :rows="10"
stripedRows responsiveLayout="scroll">
<Column field="rank" header="순위" style="width: 8%">
<template #body="slotProps">
<span class="rank-badge" :class="getRankClass(slotProps.data.rank)">
{{ slotProps.data.rank }}
</span>
</template>
</Column>
<Column field="teamNumber" header="팀" style="width: 8%"></Column>
<Column field="memberCount" header="인원" style="width: 8%"></Column>
<Column v-for="game in gameCount" :key="game" :field="`game${game}`" :header="`G${game}`" style="width: 10%"></Column>
<Column field="total" header="총점" style="width: 10%"></Column>
<Column field="average" header="평균" style="width: 10%"></Column>
</DataTable>
</TabPanel>
</TabView>
</div>
<!-- 내보내기 다이얼로그 -->
<Dialog v-model:visible="exportDialog" :style="{width: '450px'}"
header="점수 내보내기" :modal="true">
<div class="export-options">
<div class="field">
<label for="exportFormat">파일 형식</label>
<Dropdown id="exportFormat" v-model="exportFormat" :options="exportFormatOptions"
optionLabel="name" placeholder="형식 선택" class="w-full" />
</div>
<div class="field">
<label for="exportContent">내보낼 내용</label>
<MultiSelect id="exportContent" v-model="exportContent" :options="exportContentOptions"
optionLabel="name" placeholder="내용 선택" class="w-full" />
</div>
</div>
<template #footer>
<Button label="취소" icon="pi pi-times" class="p-button-text" @click="exportDialog = false" />
<Button label="내보내기" icon="pi pi-download" @click="downloadExport" />
</template>
</Dialog>
</div>
</template>
<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useToast } from 'primevue/usetoast';
import scoreService from '@/services/scoreService';
import meetingService from '@/services/meetingService';
const router = useRouter();
const route = useRoute();
const toast = useToast();
const clubId = ref(localStorage.getItem('clubId') || null);
// 모임 정보
const meetingId = ref(route.query.meetingId || null);
const meetingTitle = ref('');
const meetingDate = ref('');
const meetingLocation = ref('');
// 점수 관련 상태
const participants = ref([]);
const expandedRows = ref([]);
const gameCount = ref(3);
const loading = ref(false);
// 필터 관련 상태
const filters = reactive({
global: '',
team: null
});
// 팀 옵션
const teamOptions = ref([
{ name: '전체 팀', code: null }
]);
// 게임 옵션
const gameOptions = computed(() => {
return Array.from({ length: gameCount.value }, (_, i) => ({
name: `게임 ${i + 1}`,
code: `game${i + 1}`
}));
});
const selectedGames = ref([]);
// 순위 관련 상태
const rankingType = ref({ name: '핸디포함', code: 'handicap' });
const rankingOptions = ref([
{ name: '스크래치', code: 'scratch' },
{ name: '핸디포함', code: 'handicap' }
]);
const rankingGame = ref({ name: '전체', code: 'all' });
const gameRankingOptions = computed(() => {
const options = [{ name: '전체', code: 'all' }];
for (let i = 1; i <= gameCount.value; i++) {
options.push({ name: `게임 ${i}`, code: `game${i}` });
}
return options;
});
// 내보내기 관련 상태
const exportDialog = ref(false);
const exportFormat = ref({ name: 'Excel', code: 'xlsx' });
const exportFormatOptions = ref([
{ name: 'Excel', code: 'xlsx' },
{ name: 'CSV', code: 'csv' },
{ name: 'PDF', code: 'pdf' }
]);
const exportContent = ref([]);
const exportContentOptions = ref([
{ name: '개인 점수', code: 'individual' },
{ name: '팀별 점수', code: 'team' },
{ name: '개인 순위', code: 'individual_rank' },
{ name: '팀 순위', code: 'team_rank' }
]);
// 필터링된 참가자 목록
const filteredParticipants = computed(() => {
if (!participants.value) return [];
return participants.value.filter(participant => {
// 이름 필터
if (filters.global && !participant.name.toLowerCase().includes(filters.global.toLowerCase())) {
return false;
}
// 팀 필터
if (filters.team && participant.teamNumber !== filters.team.code) {
return false;
}
return true;
});
});
// 팀별 점수
const teamScores = computed(() => {
const teams = {};
// 팀별로 참가자 그룹화
participants.value.forEach(participant => {
const teamNumber = participant.teamNumber;
if (!teams[teamNumber]) {
teams[teamNumber] = {
teamNumber,
members: [],
gameTotals: Array(gameCount.value).fill(0),
total: 0,
average: 0
};
}
teams[teamNumber].members.push(participant);
// 게임별 팀 총점 계산
for (let i = 1; i <= gameCount.value; i++) {
const gameScore = participant[`game${i}`];
const handicap = participant.handicap || 0;
teams[teamNumber].gameTotals[i-1] += (gameScore + handicap);
}
// 팀 총점 계산
teams[teamNumber].total += participant.totalWithHandicap || 0;
});
// 팀 평균 계산
Object.values(teams).forEach(team => {
if (team.members.length > 0) {
team.average = team.total / (team.members.length * gameCount.value);
}
});
return Object.values(teams).sort((a, b) => a.teamNumber - b.teamNumber);
});
// 개인 순위
const individualRankings = computed(() => {
if (!participants.value.length) return [];
const field = rankingType.value.code === 'handicap' ? 'totalWithHandicap' : 'totalPins';
const gameField = rankingGame.value.code;
let sortedParticipants = [...participants.value];
if (gameField === 'all') {
// 전체 게임 기준 정렬
sortedParticipants.sort((a, b) => b[field] - a[field]);
} else {
// 특정 게임 기준 정렬
sortedParticipants.sort((a, b) => {
const scoreA = (a[gameField] || 0) + (rankingType.value.code === 'handicap' ? (a.handicap || 0) : 0);
const scoreB = (b[gameField] || 0) + (rankingType.value.code === 'handicap' ? (b.handicap || 0) : 0);
return scoreB - scoreA;
});
}
// 순위 부여
return sortedParticipants.map((participant, index) => ({
...participant,
rank: index + 1
}));
});
// 팀 순위
const teamRankings = computed(() => {
if (!teamScores.value.length) return [];
const rankedTeams = teamScores.value.map(team => ({
...team,
memberCount: team.members.length,
game1: team.gameTotals[0],
game2: team.gameTotals[1],
game3: team.gameTotals[2]
}));
// 총점 기준 정렬
rankedTeams.sort((a, b) => b.total - a.total);
// 순위 부여
return rankedTeams.map((team, index) => ({
...team,
rank: index + 1
}));
});
// 순위 클래스 반환
const getRankClass = (rank) => {
if (rank === 1) return 'rank-first';
if (rank === 2) return 'rank-second';
if (rank === 3) return 'rank-third';
return '';
};
// 총점 및 에버리지 계산
const calculateTotal = (participant) => {
let totalPins = 0;
let validGames = 0;
// 총점 계산
for (let i = 1; i <= gameCount.value; i++) {
const score = participant[`game${i}`];
if (score && score > 0) {
totalPins += score;
validGames++;
}
}
participant.totalPins = totalPins;
participant.totalWithHandicap = totalPins + (participant.handicap * validGames);
participant.average = validGames > 0 ? (totalPins / validGames).toFixed(1) : 0;
};
// 모든 점수 저장
const saveAllScores = async () => {
try {
loading.value = true;
await scoreService.saveScores(meetingId.value, participants.value);
toast.add({ severity: 'success', summary: '성공', detail: '점수가 성공적으로 저장되었습니다.', life: 3000 });
} catch (error) {
console.error('점수 저장 중 오류 발생:', error);
toast.add({ severity: 'error', summary: '오류', detail: '점수 저장 중 오류가 발생했습니다.', life: 3000 });
} finally {
loading.value = false;
}
};
// 점수 내보내기 다이얼로그 열기
const exportScores = () => {
exportContent.value = [exportContentOptions.value[0]];
exportDialog.value = true;
};
// 점수 내보내기 다운로드
const downloadExport = async () => {
try {
const format = exportFormat.value.code;
const content = exportContent.value.map(item => item.code);
await scoreService.exportScores(meetingId.value, format, content);
exportDialog.value = false;
toast.add({ severity: 'success', summary: '성공', detail: '점수가 성공적으로 내보내졌습니다.', life: 3000 });
} catch (error) {
console.error('점수 내보내기 중 오류 발생:', error);
toast.add({ severity: 'error', summary: '오류', detail: '점수 내보내기 중 오류가 발생했습니다.', life: 3000 });
}
};
// 뒤로 가기
const goBack = () => {
router.push('/clubs/meetings');
};
// 컴포넌트 마운트 시 데이터 로드
onMounted(async () => {
if (!clubId.value) {
toast.add({ severity: 'error', summary: '오류', detail: '클럽 ID가 설정되지 않았습니다.', life: 3000 });
return;
}
if (!meetingId.value) {
toast.add({ severity: 'error', summary: '오류', detail: '모임 ID가 설정되지 않았습니다.', life: 3000 });
router.push('/clubs/meetings');
return;
}
loading.value = true;
try {
// 모임 정보 가져오기
const meetingResponse = await meetingService.getMeetingById(meetingId.value);
const meeting = meetingResponse.data;
meetingTitle.value = meeting.title;
meetingDate.value = new Date(meeting.date).toLocaleDateString();
meetingLocation.value = meeting.location;
gameCount.value = meeting.gameCount || 3;
// 점수 데이터 가져오기
const scoresResponse = await scoreService.getMeetingScores(meetingId.value);
participants.value = scoresResponse.data;
// 팀 옵션 설정
const teams = new Set(participants.value.map(p => p.teamNumber));
teamOptions.value = [
{ name: '전체 팀', code: null },
...Array.from(teams).map(team => ({ name: `${team}`, code: team }))
];
// 각 참가자의 총점 및 에버리지 계산
participants.value.forEach(participant => {
calculateTotal(participant);
});
} catch (error) {
console.error('데이터 로드 중 오류 발생:', error);
toast.add({ severity: 'error', summary: '오류', detail: '데이터를 로드하는 중 오류가 발생했습니다.', life: 3000 });
} finally {
loading.value = false;
}
});
</script>
<style scoped>
.score-management {
padding: 1rem;
}
.header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 1.5rem;
}
.meeting-info h2 {
margin: 0 0 0.5rem 0;
}
.meeting-details {
display: flex;
gap: 1rem;
color: #666;
}
.meeting-details i {
margin-right: 0.25rem;
}
.filter-section {
margin-bottom: 1rem;
}
.score-history h4 {
margin-top: 0;
margin-bottom: 1rem;
}
.team-card {
background-color: #f8f9fa;
border-radius: 8px;
padding: 1rem;
margin-bottom: 1.5rem;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
.team-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
}
.team-header h3 {
margin: 0;
}
.team-stats {
display: flex;
gap: 1rem;
font-size: 0.9rem;
}
.team-totals {
margin-top: 1rem;
padding-top: 0.5rem;
border-top: 1px solid #ddd;
}
.game-total {
text-align: center;
font-weight: bold;
padding: 0.5rem;
background-color: #f0f0f0;
border-radius: 4px;
}
.game-total.total {
background-color: #e6f7ff;
}
.rank-badge {
display: inline-block;
width: 2rem;
height: 2rem;
line-height: 2rem;
text-align: center;
border-radius: 50%;
font-weight: bold;
}
.rank-first {
background-color: #ffd700;
color: #333;
}
.rank-second {
background-color: #c0c0c0;
color: #333;
}
.rank-third {
background-color: #cd7f32;
color: #fff;
}
.export-options {
padding: 1rem 0;
}
</style>
+338
View File
@@ -0,0 +1,338 @@
<template>
<div class="statistics-container">
<div v-if="loading" class="loading">
<div class="spinner"></div>
<p>통계 데이터를 불러오는 ...</p>
</div>
<div v-else>
<div class="period-selector">
<select v-model="selectedPeriod" @change="loadStatistics">
<option value="30">최근 30</option>
<option value="90">최근 90</option>
<option value="180">최근 180</option>
<option value="365">최근 1</option>
</select>
</div>
<div class="stats-summary">
<div class="stat-card">
<h3>회원 현황</h3>
<p>전체 회원: {{ stats.summary.totalMembers }}</p>
<p>활동 회원: {{ stats.summary.activeMembers }}</p>
<p>평균 참석률: {{ stats.summary.averageAttendance }}%</p>
</div>
<div class="stat-card">
<h3>점수 현황</h3>
<p>최고 점수: {{ stats.summary.highestGame }}</p>
<p>평균 점수: {{ stats.summary.averageScore }}</p>
<p> 게임 : {{ stats.summary.totalGames }}게임</p>
</div>
<div class="stat-card">
<h3>모임 현황</h3>
<p> 모임 : {{ stats.summary.totalMeetings }}</p>
<p>평균 참가자: {{ stats.summary.averageParticipants }}</p>
<p>모임당 게임 : {{ stats.summary.averageGamesPerMeeting }}게임</p>
</div>
</div>
<div class="charts-container">
<div class="chart-card">
<h3>점수 분포</h3>
<BarChart
:data="scoreDistributionChartData"
:options="scoreDistributionChartOptions"
/>
</div>
<div class="chart-card">
<h3>참석률 추이</h3>
<LineChart
:data="attendanceTrendChartData"
:options="attendanceTrendChartOptions"
/>
</div>
</div>
<div class="rankings-container">
<div class="rankings-card">
<h3>회원 순위</h3>
<table>
<thead>
<tr>
<th>순위</th>
<th>이름</th>
<th>평균</th>
<th>게임 </th>
<th>핸디캡</th>
<th>참석률</th>
</tr>
</thead>
<tbody>
<tr v-for="(member, index) in stats.memberRankings" :key="member.id">
<td>{{ index + 1 }}</td>
<td>{{ member.name }}</td>
<td>{{ member.average }}</td>
<td>{{ member.games }}</td>
<td>{{ member.handicap }}</td>
<td>{{ member.attendance }}%</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="meetings-container">
<div class="meetings-card">
<h3>모임별 통계</h3>
<table>
<thead>
<tr>
<th>날짜</th>
<th>제목</th>
<th>참가자</th>
<th>게임 </th>
<th>평균 점수</th>
</tr>
</thead>
<tbody>
<tr v-for="meeting in stats.meetingStats" :key="meeting.date">
<td>{{ formatDate(meeting.date) }}</td>
<td>{{ meeting.title }}</td>
<td>{{ meeting.participants }}</td>
<td>{{ meeting.games }}게임</td>
<td>{{ meeting.averageScore }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</template>
<script>
import { ref, onMounted, computed } from 'vue';
import { Bar as BarChart, Line as LineChart } from 'vue-chartjs';
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, LineElement, PointElement, Title, Tooltip, Legend } from 'chart.js';
import apiClient from '@/services/api';
ChartJS.register(CategoryScale, LinearScale, BarElement, LineElement, PointElement, Title, Tooltip, Legend);
export default {
name: 'Statistics',
components: {
BarChart,
LineChart
},
setup() {
const stats = ref({
summary: {},
scoreDistribution: [],
attendanceTrend: [],
memberRankings: [],
meetingStats: []
});
const selectedPeriod = ref('90');
const loading = ref(false);
const loadStatistics = async () => {
loading.value = true;
try {
const clubId = localStorage.getItem('clubId');
const response = await apiClient.post('/api/club/statistics', {
clubId,
days: parseInt(selectedPeriod.value)
});
stats.value = response.data;
} catch (error) {
console.error('통계 데이터 로드 오류:', error);
} finally {
loading.value = false;
}
};
const formatDate = (dateString) => {
const date = new Date(dateString);
return date.toLocaleDateString('ko-KR', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
};
const scoreDistributionChartData = computed(() => ({
labels: stats.value.scoreDistribution?.map(d => d.range) || [],
datasets: [{
label: '게임 수',
data: stats.value.scoreDistribution?.map(d => d.count) || [],
backgroundColor: '#4CAF50'
}]
}));
const scoreDistributionChartOptions = {
responsive: true,
plugins: {
legend: {
display: false
},
title: {
display: false
}
}
};
const attendanceTrendChartData = computed(() => ({
labels: stats.value.attendanceTrend?.map(d => formatDate(d.date)) || [],
datasets: [{
label: '참석률',
data: stats.value.attendanceTrend?.map(d => d.attendance) || [],
borderColor: '#2196F3',
tension: 0.1
}]
}));
const attendanceTrendChartOptions = {
responsive: true,
plugins: {
legend: {
display: false
}
},
scales: {
y: {
beginAtZero: true,
max: 100
}
}
};
onMounted(() => {
loadStatistics();
});
return {
stats,
selectedPeriod,
loading,
loadStatistics,
formatDate,
scoreDistributionChartData,
scoreDistributionChartOptions,
attendanceTrendChartData,
attendanceTrendChartOptions
};
}
};
</script>
<style scoped>
.statistics-container {
padding: 20px;
}
.loading {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 200px;
}
.spinner {
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.period-selector {
margin-bottom: 20px;
}
.period-selector select {
padding: 8px;
border-radius: 4px;
border: 1px solid #ddd;
}
.stats-summary {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.stat-card {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.stat-card h3 {
margin-top: 0;
margin-bottom: 15px;
color: #333;
}
.charts-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.chart-card {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.chart-card h3 {
margin-top: 0;
margin-bottom: 15px;
color: #333;
}
.rankings-container,
.meetings-container {
margin-bottom: 30px;
}
.rankings-card,
.meetings-card {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 10px;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f5f5f5;
font-weight: 600;
}
tr:hover {
background-color: #f9f9f9;
}
</style>
@@ -0,0 +1,398 @@
<template>
<div class="subscription-management">
<h2>구독/결제 관리</h2>
<!-- 현재 구독 상태 -->
<div v-if="currentSubscription" class="current-subscription">
<h3>현재 구독 정보</h3>
<div class="subscription-info">
<p><strong>플랜:</strong> {{ currentSubscription.planName }}</p>
<p><strong>상태:</strong> {{ currentSubscription.status }}</p>
<p><strong>시작일:</strong> {{ formatDate(currentSubscription.startDate) }}</p>
<p><strong>만료일:</strong> {{ formatDate(currentSubscription.endDate) }}</p>
</div>
</div>
<!-- 구독 플랜 목록 -->
<div class="subscription-plans">
<h3>이용 가능한 플랜</h3>
<div class="plans-grid">
<div v-for="plan in plans" :key="plan.id" class="plan-card">
<h4>{{ plan.name }}</h4>
<p class="price"> {{ formatPrice(plan.price) }}</p>
<ul class="features">
<li v-for="feature in plan.features" :key="feature.id">
{{ feature.name }}
</li>
</ul>
<button
class="subscribe-btn"
:disabled="isCurrentPlan(plan.id)"
@click="subscribeToPlan(plan.id)">
{{ isCurrentPlan(plan.id) ? '현재 이용중' : '구독하기' }}
</button>
</div>
</div>
</div>
<!-- 기능 구매 섹션 -->
<div class="features-section">
<h3>추가 기능</h3>
<div class="features-grid">
<div v-for="feature in availableFeatures" :key="feature.id" class="feature-card">
<div class="feature-header">
<h4>{{ feature.name }}</h4>
<span class="feature-status" :class="{ 'active': isFeatureActive(feature.id) }">
{{ isFeatureActive(feature.id) ? '사용중' : '미사용' }}
</span>
</div>
<p class="description">{{ feature.description }}</p>
<p class="price">{{ formatPrice(feature.price) }}</p>
<div class="duration-select" v-if="!isFeatureActive(feature.id)">
<select v-model="feature.selectedDuration">
<option value="1">1개월</option>
<option value="3">3개월</option>
<option value="6">6개월</option>
<option value="12">12개월</option>
</select>
</div>
<button
class="feature-btn"
:disabled="isFeatureActive(feature.id)"
@click="purchaseFeature(feature)">
{{ isFeatureActive(feature.id) ? '이용중' : '구매하기' }}
</button>
</div>
</div>
</div>
<!-- 기능 구매 내역 -->
<div class="feature-history">
<h3>기능 구매 내역</h3>
<table v-if="featurePayments.length > 0">
<thead>
<tr>
<th>구매일</th>
<th>기능</th>
<th>기간</th>
<th>금액</th>
<th>만료일</th>
<th>상태</th>
</tr>
</thead>
<tbody>
<tr v-for="payment in featurePayments" :key="payment.id">
<td>{{ formatDate(payment.purchaseDate) }}</td>
<td>{{ payment.featureName }}</td>
<td>{{ payment.duration }}개월</td>
<td>{{ formatPrice(payment.amount) }}</td>
<td>{{ formatDate(payment.expiryDate) }}</td>
<td>{{ payment.status }}</td>
</tr>
</tbody>
</table>
<p v-else>기능 구매 내역이 없습니다.</p>
</div>
<!-- 결제 내역 -->
<div class="payment-history">
<h3>결제 내역</h3>
<table v-if="payments.length > 0">
<thead>
<tr>
<th>결제일</th>
<th>플랜</th>
<th>금액</th>
<th>상태</th>
</tr>
</thead>
<tbody>
<tr v-for="payment in payments" :key="payment.id">
<td>{{ formatDate(payment.paymentDate) }}</td>
<td>{{ payment.planName }}</td>
<td>{{ formatPrice(payment.amount) }}</td>
<td>{{ payment.status }}</td>
</tr>
</tbody>
</table>
<p v-else>결제 내역이 없습니다.</p>
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import apiClient from '@/services/api';
const router = useRouter();
const currentSubscription = ref(null);
const plans = ref([]);
const payments = ref([]);
const availableFeatures = ref([]);
const featurePayments = ref([]);
const activeFeatures = ref([]);
// 날짜 포맷팅
const formatDate = (date) => {
return new Date(date).toLocaleDateString('ko-KR');
};
// 가격 포맷팅
const formatPrice = (price) => {
return price.toLocaleString('ko-KR');
};
// 현재 구독중인 플랜인지 확인
const isCurrentPlan = (planId) => {
return currentSubscription.value?.planId === planId;
};
// 기능이 활성화되어 있는지 확인
const isFeatureActive = (featureId) => {
return activeFeatures.value.some(f =>
f.featureId === featureId && new Date(f.expiryDate) > new Date()
);
};
// 현재 구독 정보 로드
const loadCurrentSubscription = async () => {
try {
const response = await apiClient.get('/api/subscriptions/current');
currentSubscription.value = response.data;
} catch (error) {
console.error('구독 정보 로드 실패:', error);
}
};
// 구독 플랜 목록 로드
const loadPlans = async () => {
try {
const response = await apiClient.get('/api/subscriptions/plans');
plans.value = response.data;
} catch (error) {
console.error('플랜 목록 로드 실패:', error);
}
};
// 결제 내역 로드
const loadPayments = async () => {
try {
const response = await apiClient.get('/api/subscriptions/payments');
payments.value = response.data;
} catch (error) {
console.error('결제 내역 로드 실패:', error);
}
};
// 사용 가능한 기능 목록 로드
const loadAvailableFeatures = async () => {
try {
const response = await apiClient.get('/api/features/available');
availableFeatures.value = response.data.map(feature => ({
...feature,
selectedDuration: 1
}));
} catch (error) {
console.error('기능 목록 로드 실패:', error);
}
};
// 활성화된 기능 목록 로드
const loadActiveFeatures = async () => {
try {
const response = await apiClient.get('/api/features/active');
activeFeatures.value = response.data;
} catch (error) {
console.error('활성화된 기능 로드 실패:', error);
}
};
// 기능 구매 내역 로드
const loadFeaturePayments = async () => {
try {
const response = await apiClient.get('/api/features/payments');
featurePayments.value = response.data;
} catch (error) {
console.error('기능 구매 내역 로드 실패:', error);
}
};
// 플랜 구독
const subscribeToPlan = async (planId) => {
try {
await apiClient.post('/api/subscriptions/subscribe', { planId });
await loadCurrentSubscription();
// TODO: 결제 프로세스 구현
} catch (error) {
console.error('구독 신청 실패:', error);
}
};
// 기능 구매
const purchaseFeature = async (feature) => {
try {
await apiClient.post('/api/features/purchase', {
featureId: feature.id,
duration: feature.selectedDuration
});
await Promise.all([
loadActiveFeatures(),
loadFeaturePayments()
]);
} catch (error) {
console.error('기능 구매 실패:', error);
}
};
onMounted(async () => {
await Promise.all([
loadCurrentSubscription(),
loadPlans(),
loadPayments(),
loadAvailableFeatures(),
loadActiveFeatures(),
loadFeaturePayments()
]);
});
</script>
<style scoped>
.subscription-management {
padding: 20px;
max-width: 1200px;
margin: 0 auto;
}
.current-subscription {
background: #f8f9fa;
padding: 20px;
border-radius: 8px;
margin-bottom: 30px;
}
.plans-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
margin: 20px 0;
}
.plan-card {
background: white;
border: 1px solid #dee2e6;
border-radius: 8px;
padding: 20px;
text-align: center;
}
.plan-card .price {
font-size: 1.5em;
color: #0d6efd;
margin: 15px 0;
}
.features {
list-style: none;
padding: 0;
margin: 20px 0;
}
.features li {
margin: 10px 0;
}
.subscribe-btn {
background: #0d6efd;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
}
.subscribe-btn:disabled {
background: #6c757d;
cursor: not-allowed;
}
.features-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin: 20px 0;
}
.feature-card {
background: white;
border: 1px solid #dee2e6;
border-radius: 8px;
padding: 20px;
}
.feature-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.feature-status {
font-size: 0.9em;
padding: 4px 8px;
border-radius: 4px;
background: #e9ecef;
}
.feature-status.active {
background: #198754;
color: white;
}
.description {
color: #6c757d;
margin: 10px 0;
}
.duration-select {
margin: 10px 0;
}
.duration-select select {
width: 100%;
padding: 8px;
border-radius: 4px;
border: 1px solid #dee2e6;
}
.feature-btn {
width: 100%;
background: #0d6efd;
color: white;
border: none;
padding: 10px;
border-radius: 4px;
cursor: pointer;
}
.feature-btn:disabled {
background: #6c757d;
cursor: not-allowed;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #dee2e6;
}
th {
background: #f8f9fa;
}
</style>