-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPtScreen.tsx
More file actions
406 lines (363 loc) · 11.5 KB
/
PtScreen.tsx
File metadata and controls
406 lines (363 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
import React, { useState, useEffect } from 'react';
import { View, StyleSheet, Text, FlatList, TouchableOpacity,ActivityIndicator, Alert} from 'react-native';
import { useTranslation } from 'react-i18next';
import { Calendar, LocaleConfig } from 'react-native-calendars';
import { authFetch } from './src/utils/api';
const PtScreen = ({ navigation }) => {
const { t, i18n } = useTranslation();
const now = new Date();
const currentYear = now.getFullYear();
const currentMonth = String(now.getMonth() + 1)
const [selectedDate, setSelectedDate] = useState('');
const [selectedMonth, setSelectedMonth] = useState(currentMonth);
const [selectedYear, setSelectedYear] = useState(currentYear);
const [ptCount, setPtCount] = useState(0);
const [markedDates, setMarkedDates] = useState({});
const [ptSchedules, setPtSchedules] = useState([]);
const [loading, setLoading] = useState(true);
const [currentMonthName, setCurrentMonthName] = useState('');
useEffect(() => {
if (!i18n.isInitialized) return;
const lang = i18n.language; // 현재 언어
LocaleConfig.locales[lang] = {
monthNames: t('calendar.monthNames', { returnObjects: true }),
monthNamesShort: t('calendar.monthNamesShort', { returnObjects: true }),
dayNames: t('calendar.dayNames', { returnObjects: true }),
dayNamesShort: t('calendar.dayNamesShort', { returnObjects: true }),
today: t('calendar.today'),
};
LocaleConfig.defaultLocale = lang;
}, [i18n.language, i18n.isInitialized]);
useEffect(() => {
if (!i18n.isInitialized) return;
const monthNames = t('calendar.monthNames', { returnObjects: true });
const currentMonthName = setCurrentMonthName(monthNames[selectedMonth-1]);
fetchPTMarks();
}, [i18n.isInitialized, selectedMonth, selectedYear]);
useEffect(() => {
const today = new Date();
const todayString = new Date().toLocaleDateString('en-CA'); // ✅ 로컬 YYYY-MM-DD
const dayOnly = today.getDate(); // 1~31 숫자
setSelectedDate(todayString);
fetchReservations(dayOnly);
}, []);
const statusTextMap: Record<string, string> = {
'0': 'pt.statusConfirmed',
'1': 'pt.statusPending',
'2': 'pt.statusCompleted',
};
const today = new Date();
const formatDate = (date: Date) =>
date.toISOString().split('T')[0];
const maxDate = new Date(today);
maxDate.setMonth(today.getMonth() + 3);
const convertTime = (dateStr) => {
const date = new Date(dateStr);
const hourStr = date.toLocaleTimeString('ko-KR', {
hour: 'numeric',
hour12: true // 24시간제, 원하면 true로 바꿔도 됨
});
return hourStr;
}
const getDisabledFutureDates = (fromDate, days) => {
const disabled = {};
for (let i = 1; i <= days; i++) {
const future = new Date(fromDate);
future.setDate(future.getDate() + i);
disabled[formatDate(future)] = {
disabled: true,
disableTouchEvent: true,
};
}
return disabled;
};
const disabledFutureDates = getDisabledFutureDates(maxDate, 90);
const onDayPress = (day) => {
const dayOnly = new Date(day.dateString).getDate();
setSelectedDate(day.dateString);
fetchReservations(dayOnly);
};
const fetchPTMarks = async () => {
try {
const response = await authFetch(`/reservations?month=${selectedMonth}&year=${selectedYear}`, {
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
setPtCount(data.total);
if (data.total > 0) {
const newMarks = {};
data.reservation_list.forEach(dateStr => {
if (dateStr.start_time) {
const dateKey = dateStr.start_time.split('T')[0];
newMarks[dateKey] = {
...markedDates[dateKey],
marked: true,
dotColor: 'red',
};
}
});
setMarkedDates(prev => ({
...prev,
...newMarks,
}));
}
} catch (error) {
console.error('Error fetching attendance:', error);
}
};
const fetchReservations = async (date) => {
const day = date ?? today.getDate();
try {
setLoading(true);
const response = await authFetch(`/reservations?month=${selectedMonth}&year=${selectedYear}&day=${day}`, {
headers: {
"Content-Type": "application/json",
},
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
console.log('API Response:', data);
if (data.total > 0) {
const formattedSchedules = data.reservation_list.map((item, index) => ({
id: item.id.toString(),
start_time: convertTime(item.start_time),
trainer_name: item.trainer_name,
complete: item.complete
}));
setPtSchedules(formattedSchedules);
} else {
console.log('No reservation_list in response');
setPtSchedules([]);
}
} catch (error) {
console.error('Error fetching reservations:', error);
Alert.alert(t('errors.error'), t('errors.fetchReservationsFailed'));
setPtSchedules([]);
} finally {
setLoading(false);
}
};
const renderPtScheduleItem = ({ item }) => (
<TouchableOpacity style={styles.scheduleItem}>
<Text style={styles.scheduleItemText}>{item.start_time}</Text>
<Text style={styles.scheduleItemText}>{item.trainer_name}</Text>
<Text style={[
styles.scheduleItemText,
item.complete === '0' && styles.statusConfirmed,
item.complete === '1' && styles.statusPending,
item.complete === '2' && styles.statusCompleted
]}>
{t(statusTextMap[String(item.complete)])}
</Text>
</TouchableOpacity>
);
return (
<View style={styles.container}>
<View style={styles.statsContainer}>
<View style={styles.statsItem}>
<Text style={styles.statsLabel}>{currentMonthName} {t('attendance.PTcount')} <View style={[styles.attendanceCircle]} /></Text>
<Text style={styles.statsValue}>{ptCount} {t('common.times')}</Text>
</View>
</View>
<Calendar
onDayPress={onDayPress}
markedDates={{markedDates,
...disabledFutureDates,
[selectedDate]: { selected: true, marked: true }
}}
monthFormat={t('calendar.monthFormat')}
enableSwipeMonths={true}
firstDay={0}
hideExtraDays={true}
maxDate={formatDate(maxDate)}
onVisibleMonthsChange={(months) => {
setSelectedMonth(months[0].month);
setSelectedYear(months[0].year);
}}
theme={{
monthTextColor: '#000',
selectedDayBackgroundColor: '#007AFF',
selectedDayTextColor: 'white',
arrowColor: '#007AFF',
textSectionTitleColor: '#000',
textDisabledColor: '#C7C7CD',
todayTextColor: '#007AFF',
selectedDayTextColor: 'white',
selectedDayBackgroundColor: '#007AFF',
dotColor: 'FF69B4',
selectedDotColor: '#007AFF',
disabledDotColor: '#C7C7CD',
disabledDayTextColor: '#C7C7CD',
monthTextColor: '#000',
textDayFontFamily: 'System',
textMonthFontFamily: 'System',
textDayHeaderFontFamily: 'System',
}}
dayComponent={({ date, state }) => {
const todayStr = new Date().toLocaleDateString('en-CA');
const isTodayOrPast = date.dateString <= todayStr;
const dayOfWeek = new Date(date.dateString).getDay();
let textColor = '#000';
if (dayOfWeek === 0) textColor = '#FF3B30';
else if (dayOfWeek === 6) textColor = '#007AFF';
if (!isTodayOrPast) textColor = '#C7C7CD';
const isSelected = date.dateString === selectedDate;
const isMarked = markedDates[date.dateString]?.marked;
return (
<TouchableOpacity
onPress={() => onDayPress(date)}
style={{
backgroundColor: isSelected ? '#007AFF' : 'transparent',
borderRadius: 20,
padding: 8,
alignItems: 'center',
}}
>
<Text
style={{
color: isSelected ? '#fff' : textColor,
fontWeight: isSelected ? 'bold' : 'normal',
}}
>
{date.day}
</Text>
{isMarked && (
<View
style={{
width: 7,
height: 7,
borderRadius: 3.5,
backgroundColor: markedDates[date.dateString].dotColor,
marginTop: 2,
}}
/>
)}
</TouchableOpacity>
);
}}
/>
<View style={styles.scheduleHeader}>
<Text style={styles.scheduleHeaderText}>PT 일정 ({selectedDate})</Text>
</View>
{loading ? (
<ActivityIndicator size="large" color="#007AFF" style={styles.loader} />
) : (
<FlatList
data={ptSchedules}
renderItem={renderPtScheduleItem}
keyExtractor={item => item.id}
style={styles.scheduleList}
ListEmptyComponent={() => (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}>예약된 PT가 없습니다.</Text>
</View>
)}
ListHeaderComponent={() => (
<View style={styles.scheduleListHeader}>
<Text style={styles.scheduleListHeaderText}>시간</Text>
<Text style={styles.scheduleListHeaderText}>강사</Text>
<Text style={styles.scheduleListHeaderText}>상태</Text>
</View>
)}
/>
)}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
padding: 16,
},
statsContainer: {
flexDirection: 'row',
justifyContent: 'space-around',
marginBottom: 20,
},
statsItem: {
alignItems: 'center',
flexDirection: 'column',
justifyContent: 'center',
},
statsLabel: {
fontSize: 16,
color: '#666',
marginBottom: 8,
},
statsValue: {
fontSize: 24,
fontWeight: 'bold',
color: '#000',
},
attendanceCircle: {
width: 14,
height: 14,
borderRadius: 7,
backgroundColor: '#FF69B4',
alignSelf: 'center',
marginTop: 8,
},
scheduleHeader: {
padding: 15,
backgroundColor: '#f4f4f4',
},
scheduleHeaderText: {
fontSize: 18,
fontWeight: 'bold',
},
scheduleList: {
flex: 1,
},
loader: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
emptyContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
emptyText: {
fontSize: 16,
color: '#888',
},
scheduleListHeader: {
flexDirection: 'row',
justifyContent: 'space-between',
padding: 10,
backgroundColor: '#f8f8f8',
borderBottomWidth: 1,
borderBottomColor: '#e0e0e0',
},
scheduleListHeaderText: {
flex: 1,
textAlign: 'center',
fontWeight: 'bold',
},
scheduleItem: {
flexDirection: 'row',
justifyContent: 'space-between',
padding: 15,
borderBottomWidth: 1,
borderBottomColor: '#e0e0e0',
},
scheduleItemText: {
flex: 1,
textAlign: 'center',
},
statusConfirmed: {
color: 'green',
},
statusPending: {
color: 'orange',
},
statusCompleted: {
color: 'gray',
},
});
export default PtScreen;