회원목록

This commit is contained in:
2025-08-01 16:45:26 +09:00
parent a996def67a
commit ed8c7eacba
191 changed files with 17491 additions and 0 deletions
@@ -0,0 +1,367 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/member_model.dart';
import '../../services/auth_service.dart';
import '../../services/club_service.dart';
import '../../services/member_service.dart';
import '../../utils/enum_mappings.dart';
class ClubSettingsScreen extends StatefulWidget {
static const routeName = '/club-settings';
const ClubSettingsScreen({super.key});
@override
_ClubSettingsScreenState createState() => _ClubSettingsScreenState();
}
class _ClubSettingsScreenState extends State<ClubSettingsScreen> {
final _formKey = GlobalKey<FormState>();
final _nameController = TextEditingController();
final _descriptionController = TextEditingController();
final _locationController = TextEditingController();
final _femaleHandicapController = TextEditingController();
String? _selectedAverageCalculationPeriod;
String? _selectedOwnerId;
List<Member> _members = [];
bool _isLoading = true;
bool _hasEditPermission = false;
@override
void initState() {
super.initState();
_loadData();
}
@override
void dispose() {
_nameController.dispose();
_descriptionController.dispose();
_locationController.dispose();
_femaleHandicapController.dispose();
super.dispose();
}
Future<void> _loadData() async {
setState(() {
_isLoading = true;
});
try {
// 클럽 정보 로드
final clubService = Provider.of<ClubService>(context, listen: false);
final club = clubService.currentClub;
if (club != null) {
_nameController.text = club.name;
_descriptionController.text = club.description ?? '';
_locationController.text = club.location ?? '';
_femaleHandicapController.text = club.femaleHandicap?.toString() ?? '';
_selectedAverageCalculationPeriod =
club.averageCalculationPeriod ?? 'total';
_selectedOwnerId = club.ownerId;
}
// 회원 목록 로드
final memberService = Provider.of<MemberService>(context, listen: false);
await memberService.fetchClubMembers();
setState(() {
_members = memberService.members;
});
// 권한 확인
final authService = Provider.of<AuthService>(context, listen: false);
final currentUserId = authService.currentUser?.id;
// 현재 사용자가 클럽 소유자이거나 관리자인지 확인
if (currentUserId != null) {
final currentMember = _members.firstWhere(
(member) => member.userId == currentUserId,
orElse: () => Member(
id: '',
userId: '',
name: '',
memberType: '',
clubId: club?.id ?? '',
email: '',
isActive: true,
),
);
setState(() {
_hasEditPermission =
club?.ownerId == currentUserId || // 클럽 소유자
currentMember.memberType == 'manager' || // 클럽 매니저
authService.currentUser?.role == 'admin'; // 시스템 관리자
});
}
} catch (error) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('데이터 로드 중 오류가 발생했습니다: $error')));
} finally {
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
Future<void> _saveClubInfo() async {
if (!_formKey.currentState!.validate()) {
return;
}
setState(() {
_isLoading = true;
});
try {
final clubService = Provider.of<ClubService>(context, listen: false);
final club = clubService.currentClub;
if (club != null) {
// 기본 업데이트 데이터 준비
final Map<String, dynamic> updates = {
'clubId': club.id,
'name': _nameController.text.trim(),
};
// 빈 문자열이 아닌 경우에만 추가 (null 값 명시적 처리)
if (_descriptionController.text.trim().isNotEmpty) {
updates['description'] = _descriptionController.text.trim();
} else if (_descriptionController.text.trim().isEmpty &&
club.description != null) {
// 기존에 값이 있었는데 지금 비어있으면 명시적으로 null 설정
updates['description'] = null;
}
if (_locationController.text.trim().isNotEmpty) {
updates['location'] = _locationController.text.trim();
} else if (_locationController.text.trim().isEmpty &&
club.location != null) {
updates['location'] = null;
}
if (_femaleHandicapController.text.trim().isNotEmpty) {
updates['femaleHandicap'] = int.parse(
_femaleHandicapController.text.trim(),
);
}
if (_selectedAverageCalculationPeriod != null) {
updates['averageCalculationPeriod'] =
_selectedAverageCalculationPeriod;
}
if (_selectedOwnerId != null) {
updates['ownerId'] = _selectedOwnerId;
}
// 모임장 변경 시에만 이메일 정보 추가
if (_selectedOwnerId != club.ownerId) {
// 모임장이 변경된 경우 해당 회원의 이메일 정보 찾기
final selectedMember = _members.firstWhere(
(member) => member.userId == _selectedOwnerId,
orElse: () => Member(
id: '',
userId: '',
name: '',
memberType: '',
clubId: club.id,
email: '',
isActive: true,
),
);
// 이메일이 있는 경우에만 추가 (빈 문자열이나 null은 전송하지 않음)
if (selectedMember.email.isNotEmpty) {
updates['ownerEmail'] = selectedMember.email;
}
}
await clubService.updateClub(club.id, updates);
if (context.mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('클럽 정보가 성공적으로 저장되었습니다')));
}
}
} catch (error) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('클럽 정보 저장 중 오류가 발생했습니다: $error')),
);
}
} finally {
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('클럽 설정')),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: Column(
children: [
if (!_hasEditPermission)
Container(
width: double.infinity,
padding: const EdgeInsets.all(16.0),
color: Colors.amber.shade100,
child: const Text(
'권한 알림: 클럽 설정을 변경하려면 클럽 소유자 또는 관리자 권한이 필요합니다.',
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 클럽 이름
TextFormField(
controller: _nameController,
decoration: const InputDecoration(
labelText: '클럽 이름',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return '클럽 이름을 입력해주세요';
}
return null;
},
enabled: _hasEditPermission,
),
// 설명
const SizedBox(height: 16),
TextFormField(
controller: _descriptionController,
decoration: const InputDecoration(
labelText: '설명',
border: OutlineInputBorder(),
),
maxLines: 3,
enabled: _hasEditPermission,
),
// 위치
const SizedBox(height: 16),
TextFormField(
controller: _locationController,
decoration: const InputDecoration(
labelText: '위치',
border: OutlineInputBorder(),
),
enabled: _hasEditPermission,
),
// 여성 기본 핸디캡
const SizedBox(height: 16),
TextFormField(
controller: _femaleHandicapController,
decoration: const InputDecoration(
labelText: '여성 기본 핸디캡',
border: OutlineInputBorder(),
),
keyboardType: TextInputType.number,
validator: (value) {
if (value != null && value.isNotEmpty) {
final handicap = int.tryParse(value);
if (handicap == null) {
return '숫자를 입력해주세요';
}
if (handicap < 0) {
return '0 이상의 값을 입력해주세요';
}
}
return null;
},
enabled: _hasEditPermission,
),
// 평균 산정 기준
const SizedBox(height: 16),
DropdownButtonFormField<String>(
decoration: const InputDecoration(
labelText: '평균 산정 기준',
border: OutlineInputBorder(),
),
value: _selectedAverageCalculationPeriod,
items: averageCalculationPeriodOptions.entries
.map(
(entry) => DropdownMenuItem<String>(
value: entry.key,
child: Text(entry.value),
),
)
.toList(),
onChanged: _hasEditPermission
? (value) {
setState(() {
_selectedAverageCalculationPeriod = value;
});
}
: null,
),
// 모임장 설정
const SizedBox(height: 16),
DropdownButtonFormField<String>(
decoration: const InputDecoration(
labelText: '모임장 설정',
border: OutlineInputBorder(),
),
value: _selectedOwnerId,
items: _members.map((member) {
return DropdownMenuItem<String>(
value: member.userId,
child: Text(
'${member.name} (${getMemberTypeLabel(member.memberType)})',
),
);
}).toList(),
onChanged: _hasEditPermission
? (value) {
setState(() {
_selectedOwnerId = value;
});
}
: null,
),
// 저장 버튼
const SizedBox(height: 24),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _hasEditPermission
? _saveClubInfo
: null,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 16.0,
),
),
child: const Text('저장'),
),
),
],
),
),
),
),
],
),
);
}
}
@@ -0,0 +1,394 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import '../../services/auth_service.dart';
import '../../services/club_service.dart';
import '../../services/member_service.dart';
import '../../services/event_service.dart';
import '../../models/club_model.dart';
import 'club_settings_screen.dart';
class DashboardScreen extends StatefulWidget {
const DashboardScreen({super.key});
@override
State<DashboardScreen> createState() => _DashboardScreenState();
}
class _DashboardScreenState extends State<DashboardScreen> {
bool _isLoading = false;
bool _isInit = false;
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (!_isInit) {
_loadDashboardData();
_isInit = true;
}
}
Future<void> _loadDashboardData() async {
setState(() {
_isLoading = true;
});
try {
final authService = Provider.of<AuthService>(context, listen: false);
final clubService = Provider.of<ClubService>(context, listen: false);
// 클럽 정보 로드
if (clubService.currentClub == null) {
await clubService.initialize(authService.token!);
}
// 회원 및 이벤트 서비스 초기화
if (clubService.currentClub != null) {
final memberService = Provider.of<MemberService>(context, listen: false);
final eventService = Provider.of<EventService>(context, listen: false);
memberService.initialize(authService.token!);
eventService.initialize(authService.token!);
// 회원 및 이벤트 데이터 로드
await Future.wait([
memberService.fetchClubMembers(),
eventService.fetchClubEvents(),
]);
}
} catch (e) {
// 오류 처리
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('데이터 로드 중 오류가 발생했습니다: $e')),
);
} finally {
setState(() {
_isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: _isLoading
? const Center(child: CircularProgressIndicator())
: RefreshIndicator(
onRefresh: _loadDashboardData,
child: Consumer3<ClubService, MemberService, EventService>(
builder: (context, clubService, memberService, eventService, _) {
final club = clubService.currentClub;
if (club == null) {
return const Center(
child: Text('클럽 정보를 불러올 수 없습니다'),
);
}
return SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 클럽 정보 카드
_buildClubInfoCard(club),
const SizedBox(height: 16),
// 통계 카드들
_buildStatisticsCards(
memberCount: memberService.members.length,
eventCount: eventService.events.length,
),
const SizedBox(height: 16),
// 최근 이벤트 목록
_buildRecentEventsList(eventService),
],
),
);
},
),
),
);
}
Widget _buildClubInfoCard(Club club) {
return Card(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Row(
children: [
if (club.logo != null)
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.network(
club.logo!,
width: 60,
height: 60,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return Container(
width: 60,
height: 60,
color: Colors.grey[300],
child: const Icon(Icons.sports_golf),
);
},
),
)
else
Container(
width: 60,
height: 60,
decoration: BoxDecoration(
color: Colors.blue[100],
borderRadius: BorderRadius.circular(8),
),
child: const Icon(
Icons.sports_golf,
size: 30,
color: Colors.blue,
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
club.name,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
if (club.description != null)
Text(
club.description!,
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
],
),
),
],
),
),
IconButton(
icon: const Icon(Icons.settings),
tooltip: '클럽 설정',
onPressed: () {
Navigator.of(context).pushNamed(ClubSettingsScreen.routeName);
},
),
],
),
const SizedBox(height: 16),
if (club.address != null)
_buildInfoRow(Icons.location_on, club.address!),
if (club.phone != null)
_buildInfoRow(Icons.phone, club.phone!),
if (club.email != null)
_buildInfoRow(Icons.email, club.email!),
if (club.website != null)
_buildInfoRow(Icons.language, club.website!),
],
),
),
);
}
Widget _buildInfoRow(IconData icon, String text) {
return Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: Row(
children: [
Icon(icon, size: 16, color: Colors.grey[600]),
const SizedBox(width: 8),
Expanded(
child: Text(
text,
style: TextStyle(fontSize: 14, color: Colors.grey[800]),
),
),
],
),
);
}
Widget _buildStatisticsCards({required int memberCount, required int eventCount}) {
return Row(
children: [
Expanded(
child: _buildStatCard(
title: '회원',
value: memberCount.toString(),
icon: Icons.people,
color: Colors.blue,
),
),
const SizedBox(width: 16),
Expanded(
child: _buildStatCard(
title: '이벤트',
value: eventCount.toString(),
icon: Icons.event,
color: Colors.orange,
),
),
],
);
}
Widget _buildStatCard({
required String title,
required String value,
required IconData icon,
required Color color,
}) {
return Card(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Icon(icon, size: 32, color: color),
const SizedBox(height: 8),
Text(
value,
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: color,
),
),
Text(
title,
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
),
),
],
),
),
);
}
Widget _buildRecentEventsList(EventService eventService) {
final events = eventService.events;
if (events.isEmpty) {
return const Card(
child: Padding(
padding: EdgeInsets.all(16.0),
child: Center(
child: Text('예정된 이벤트가 없습니다'),
),
),
);
}
// 날짜 기준으로 정렬 (가까운 날짜순)
final sortedEvents = [...events];
sortedEvents.sort((a, b) => a.startDate.compareTo(b.startDate));
// 앞으로 진행될 이벤트만 필터링 (최대 3개)
final upcomingEvents = sortedEvents
.where((event) => event.startDate.isAfter(DateTime.now()))
.take(3)
.toList();
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'다가오는 이벤트',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
TextButton(
onPressed: () {
// 이벤트 목록 화면으로 이동 (추후 구현)
},
child: const Text('모두 보기'),
),
],
),
const SizedBox(height: 8),
...upcomingEvents.map((event) => _buildEventCard(event)),
],
);
}
Widget _buildEventCard(event) {
final dateFormat = DateFormat('yyyy년 MM월 dd일 HH:mm');
return Card(
margin: const EdgeInsets.only(bottom: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
child: ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
title: Text(
event.title,
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 4),
Text(
dateFormat.format(event.startDate),
style: TextStyle(
color: Colors.grey[700],
),
),
if (event.location != null)
Text(
event.location!,
style: TextStyle(
color: Colors.grey[600],
),
),
],
),
trailing: const Icon(Icons.arrow_forward_ios, size: 16),
onTap: () {
// 이벤트 상세 화면으로 이동 (추후 구현)
},
),
);
}
}
+671
View File
@@ -0,0 +1,671 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import '../../services/auth_service.dart';
import '../../services/club_service.dart';
import '../../services/event_service.dart';
import '../../models/event_model.dart';
class EventsScreen extends StatefulWidget {
const EventsScreen({super.key});
@override
State<EventsScreen> createState() => _EventsScreenState();
}
class _EventsScreenState extends State<EventsScreen> {
bool _isInit = false;
String _searchQuery = '';
final TextEditingController _searchController = TextEditingController();
String _filterType = '전체'; // '전체', '예정', '지난'
@override
void dispose() {
_searchController.dispose();
super.dispose();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (!_isInit) {
_loadEvents();
_isInit = true;
}
}
Future<void> _loadEvents() async {
try {
final authService = Provider.of<AuthService>(context, listen: false);
final clubService = Provider.of<ClubService>(context, listen: false);
final eventService = Provider.of<EventService>(context, listen: false);
if (clubService.currentClub != null) {
eventService.initialize(authService.token!);
await eventService.fetchClubEvents();
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('이벤트 목록을 불러오는데 실패했습니다: $e')),
);
}
}
}
List<Event> _getFilteredEvents(List<Event> events) {
// 검색어 필터링
List<Event> filteredEvents = events;
if (_searchQuery.isNotEmpty) {
final query = _searchQuery.toLowerCase();
filteredEvents = filteredEvents.where((event) {
return event.title.toLowerCase().contains(query) ||
(event.description?.toLowerCase().contains(query) ?? false) ||
(event.location?.toLowerCase().contains(query) ?? false);
}).toList();
}
// 날짜 필터링
final now = DateTime.now();
if (_filterType == '예정') {
filteredEvents = filteredEvents.where((event) => event.startDate.isAfter(now)).toList();
} else if (_filterType == '지난') {
filteredEvents = filteredEvents.where((event) => event.startDate.isBefore(now)).toList();
}
// 날짜순 정렬
filteredEvents.sort((a, b) => a.startDate.compareTo(b.startDate));
return filteredEvents;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
// 검색 바
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: _searchController,
decoration: InputDecoration(
hintText: '이벤트 검색',
prefixIcon: const Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
contentPadding: const EdgeInsets.symmetric(vertical: 0),
suffixIcon: _searchQuery.isNotEmpty
? IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
_searchController.clear();
setState(() {
_searchQuery = '';
});
},
)
: null,
),
onChanged: (value) {
setState(() {
_searchQuery = value;
});
},
),
const SizedBox(height: 8),
// 필터 버튼들
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
_buildFilterChip('전체'),
const SizedBox(width: 8),
_buildFilterChip('예정'),
const SizedBox(width: 8),
_buildFilterChip('지난'),
],
),
),
],
),
),
// 이벤트 목록
Expanded(
child: Consumer<EventService>(
builder: (context, eventService, _) {
if (eventService.isLoading) {
return const Center(child: CircularProgressIndicator());
}
final filteredEvents = _getFilteredEvents(eventService.events);
if (filteredEvents.isEmpty) {
return Center(
child: Text(
_searchQuery.isEmpty
? '등록된 이벤트가 없습니다'
: '검색 결과가 없습니다',
),
);
}
return RefreshIndicator(
onRefresh: _loadEvents,
child: ListView.builder(
padding: const EdgeInsets.only(bottom: 16),
itemCount: filteredEvents.length,
itemBuilder: (context, index) {
final event = filteredEvents[index];
return _buildEventCard(event);
},
),
);
},
),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// 이벤트 추가 화면으로 이동 (추후 구현)
_showAddEventDialog();
},
backgroundColor: Colors.blue,
child: const Icon(Icons.add, color: Colors.white),
),
);
}
Widget _buildFilterChip(String label) {
final isSelected = _filterType == label;
return FilterChip(
label: Text(label),
selected: isSelected,
onSelected: (selected) {
setState(() {
_filterType = selected ? label : '전체';
});
},
backgroundColor: Colors.grey[200],
selectedColor: Colors.blue[100],
checkmarkColor: Colors.blue,
labelStyle: TextStyle(
color: isSelected ? Colors.blue[800] : Colors.black87,
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
),
);
}
Widget _buildEventCard(Event event) {
final dateFormat = DateFormat('yyyy년 MM월 dd일 HH:mm');
final now = DateTime.now();
final isPast = event.startDate.isBefore(now);
return Card(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
child: ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
leading: Container(
width: 48,
height: 48,
decoration: BoxDecoration(
color: isPast ? Colors.grey[200] : Colors.blue[100],
borderRadius: BorderRadius.circular(8),
),
child: Icon(
Icons.event,
color: isPast ? Colors.grey[600] : Colors.blue,
),
),
title: Text(
event.title,
style: TextStyle(
fontWeight: FontWeight.bold,
color: isPast ? Colors.grey[600] : Colors.black,
),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 4),
Text(
dateFormat.format(event.startDate),
style: TextStyle(
color: isPast ? Colors.grey[500] : Colors.grey[700],
),
),
if (event.location != null)
Text(
event.location!,
style: TextStyle(
color: isPast ? Colors.grey[500] : Colors.grey[600],
),
),
],
),
trailing: PopupMenuButton<String>(
icon: const Icon(Icons.more_vert),
onSelected: (value) {
if (value == 'edit') {
_showEditEventDialog(event);
} else if (value == 'delete') {
_showDeleteConfirmationDialog(event);
}
},
itemBuilder: (context) => [
const PopupMenuItem<String>(
value: 'edit',
child: Row(
children: [
Icon(Icons.edit, size: 18),
SizedBox(width: 8),
Text('수정'),
],
),
),
const PopupMenuItem<String>(
value: 'delete',
child: Row(
children: [
Icon(Icons.delete, size: 18, color: Colors.red),
SizedBox(width: 8),
Text('삭제', style: TextStyle(color: Colors.red)),
],
),
),
],
),
onTap: () {
// 이벤트 상세 화면으로 이동 (추후 구현)
_showEventDetailsDialog(event);
},
),
);
}
// 이벤트 추가 다이얼로그
void _showAddEventDialog() {
final titleController = TextEditingController();
final descriptionController = TextEditingController();
final locationController = TextEditingController();
DateTime selectedDate = DateTime.now().add(const Duration(days: 1));
TimeOfDay selectedTime = TimeOfDay.now();
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('이벤트 추가'),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: titleController,
decoration: const InputDecoration(
labelText: '제목',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 16),
TextField(
controller: descriptionController,
maxLines: 3,
decoration: const InputDecoration(
labelText: '설명',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 16),
TextField(
controller: locationController,
decoration: const InputDecoration(
labelText: '장소',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 16),
ListTile(
title: const Text('날짜'),
subtitle: Text(
DateFormat('yyyy년 MM월 dd일').format(selectedDate),
),
trailing: const Icon(Icons.calendar_today),
onTap: () async {
final pickedDate = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime.now(),
lastDate: DateTime.now().add(const Duration(days: 365)),
);
if (pickedDate != null && context.mounted) {
setState(() {
selectedDate = pickedDate;
});
}
},
),
ListTile(
title: const Text('시간'),
subtitle: Text(selectedTime.format(context)),
trailing: const Icon(Icons.access_time),
onTap: () async {
final pickedTime = await showTimePicker(
context: context,
initialTime: selectedTime,
);
if (pickedTime != null && context.mounted) {
setState(() {
selectedTime = pickedTime;
});
}
},
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('취소'),
),
ElevatedButton(
onPressed: () async {
if (titleController.text.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('제목은 필수 입력 항목입니다')),
);
return;
}
try {
final eventService = Provider.of<EventService>(context, listen: false);
final clubService = Provider.of<ClubService>(context, listen: false);
if (clubService.currentClub != null) {
// 날짜와 시간 결합
final eventDateTime = DateTime(
selectedDate.year,
selectedDate.month,
selectedDate.day,
selectedTime.hour,
selectedTime.minute,
);
await eventService.createEvent({
'title': titleController.text.trim(),
'description': descriptionController.text.trim(),
'location': locationController.text.trim(),
'startDate': eventDateTime.toIso8601String(),
'clubId': clubService.currentClub!.id,
'isActive': true,
});
if (mounted) {
Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('이벤트가 추가되었습니다')),
);
}
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('이벤트 추가에 실패했습니다: $e')),
);
}
},
child: const Text('추가'),
),
],
),
);
}
// 이벤트 수정 다이얼로그
void _showEditEventDialog(Event event) {
final titleController = TextEditingController(text: event.title);
final descriptionController = TextEditingController(text: event.description ?? '');
final locationController = TextEditingController(text: event.location ?? '');
DateTime selectedDate = event.startDate;
TimeOfDay selectedTime = TimeOfDay(
hour: event.startDate.hour,
minute: event.startDate.minute,
);
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('이벤트 수정'),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: titleController,
decoration: const InputDecoration(
labelText: '제목',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 16),
TextField(
controller: descriptionController,
maxLines: 3,
decoration: const InputDecoration(
labelText: '설명',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 16),
TextField(
controller: locationController,
decoration: const InputDecoration(
labelText: '장소',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 16),
ListTile(
title: const Text('날짜'),
subtitle: Text(
DateFormat('yyyy년 MM월 dd일').format(selectedDate),
),
trailing: const Icon(Icons.calendar_today),
onTap: () async {
final pickedDate = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime.now().subtract(const Duration(days: 365)),
lastDate: DateTime.now().add(const Duration(days: 365)),
);
if (pickedDate != null && context.mounted) {
setState(() {
selectedDate = pickedDate;
});
}
},
),
ListTile(
title: const Text('시간'),
subtitle: Text(selectedTime.format(context)),
trailing: const Icon(Icons.access_time),
onTap: () async {
final pickedTime = await showTimePicker(
context: context,
initialTime: selectedTime,
);
if (pickedTime != null && context.mounted) {
setState(() {
selectedTime = pickedTime;
});
}
},
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('취소'),
),
ElevatedButton(
onPressed: () async {
if (titleController.text.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('제목은 필수 입력 항목입니다')),
);
return;
}
try {
final eventService = Provider.of<EventService>(context, listen: false);
// 날짜와 시간 결합
final eventDateTime = DateTime(
selectedDate.year,
selectedDate.month,
selectedDate.day,
selectedTime.hour,
selectedTime.minute,
);
await eventService.updateEvent(event.id, {
'title': titleController.text.trim(),
'description': descriptionController.text.trim(),
'location': locationController.text.trim(),
'startDate': eventDateTime.toIso8601String(),
});
if (mounted) {
Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('이벤트가 업데이트되었습니다')),
);
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('이벤트 업데이트에 실패했습니다: $e')),
);
}
},
child: const Text('저장'),
),
],
),
);
}
// 이벤트 상세 정보 다이얼로그
void _showEventDetailsDialog(Event event) {
final dateFormat = DateFormat('yyyy년 MM월 dd일 HH:mm');
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(event.title),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.calendar_today, size: 16, color: Colors.blue),
const SizedBox(width: 8),
Text(dateFormat.format(event.startDate)),
],
),
const SizedBox(height: 8),
if (event.location != null) ...[
Row(
children: [
const Icon(Icons.location_on, size: 16, color: Colors.blue),
const SizedBox(width: 8),
Text(event.location!),
],
),
const SizedBox(height: 8),
],
if (event.description != null) ...[
const Divider(),
const SizedBox(height: 8),
Text(
event.description!,
style: const TextStyle(fontSize: 16),
),
],
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('닫기'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop();
_showEditEventDialog(event);
},
child: const Text('수정'),
),
],
),
);
}
// 이벤트 삭제 확인 다이얼로그
void _showDeleteConfirmationDialog(Event event) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('이벤트 삭제'),
content: Text('${event.title} 이벤트를 정말 삭제하시겠습니까?'),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('취소'),
),
TextButton(
onPressed: () async {
try {
final eventService = Provider.of<EventService>(context, listen: false);
await eventService.deleteEvent(event.id);
if (mounted) {
Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('이벤트가 삭제되었습니다')),
);
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('이벤트 삭제에 실패했습니다: $e')),
);
}
},
style: TextButton.styleFrom(foregroundColor: Colors.red),
child: const Text('삭제'),
),
],
),
);
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff