학교 전용 공부 타이머(열품타) + 학년별 랭킹 기능 추가

학생 참여 유도를 위해 공부 시작/종료 타이머와 학년별(오늘/이번주/전체)
랭킹 화면을 대시보드에 추가. 로그인 응답에 학년 정보를 포함시켜
세션 저장/복원 전체 경로에 전달되도록 함.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-14 14:58:55 +09:00
co-authored by Claude Sonnet 5
parent 26e54a1798
commit a59a3054fb
9 changed files with 662 additions and 2 deletions
+12 -2
View File
@@ -16,18 +16,21 @@ class LoginResult {
final String? name;
final bool isDeviceMatched;
final String? errorMessage;
final int? grade; // 🎓 공부 타이머 학년별 랭킹에서 본인 학년을 기본값으로 쓰기 위함.
const LoginResult.masterSuccess({required this.studentId, required this.name})
: outcome = LoginOutcome.masterSuccess,
role = null,
isDeviceMatched = true,
errorMessage = null;
errorMessage = null,
grade = null;
const LoginResult.needsPasswordChange({
required this.studentId,
required this.name,
required this.role,
required this.isDeviceMatched,
this.grade,
}) : outcome = LoginOutcome.needsPasswordChange,
errorMessage = null;
@@ -36,6 +39,7 @@ class LoginResult {
required this.studentId,
required this.name,
required this.isDeviceMatched,
this.grade,
}) : outcome = LoginOutcome.success,
errorMessage = null;
@@ -44,7 +48,8 @@ class LoginResult {
role = null,
studentId = null,
name = null,
isDeviceMatched = false;
isDeviceMatched = false,
grade = null;
}
class LoginController extends ChangeNotifier {
@@ -101,6 +106,7 @@ class LoginController extends ChangeNotifier {
String name = '';
String studentId = '';
int isFirstLogin = 0;
int? grade;
var userObj = resData['user'];
if (userObj != null) {
@@ -114,6 +120,7 @@ class LoginController extends ChangeNotifier {
userObj['studentId']?.toString() ??
userObj['student_id']?.toString() ??
id;
grade = int.tryParse(userObj['grade']?.toString() ?? '');
var rawFirst = userObj['isFirstLogin'] ?? userObj['is_first_login'];
isFirstLogin = (rawFirst is bool)
@@ -126,6 +133,7 @@ class LoginController extends ChangeNotifier {
resData['studentName']?.toString() ??
'';
studentId = resData['studentId']?.toString() ?? id;
grade = int.tryParse(resData['grade']?.toString() ?? '');
var rawFirst = resData['isFirstLogin'] ?? resData['is_first_login'];
isFirstLogin = (rawFirst is bool)
@@ -153,6 +161,7 @@ class LoginController extends ChangeNotifier {
name: name,
role: role,
isDeviceMatched: isDeviceMatched,
grade: grade,
);
}
@@ -161,6 +170,7 @@ class LoginController extends ChangeNotifier {
studentId: studentId,
name: name,
isDeviceMatched: isDeviceMatched,
grade: grade,
);
} else {
String errorMsg = '로그인에 실패했습니다.';
+4
View File
@@ -9,12 +9,14 @@ class SavedSession {
final String userName;
final String role;
final bool isDeviceMatched;
final int? grade; // 🎓 공부 타이머 학년별 랭킹에서 본인 학년을 기본값으로 쓰기 위함.
const SavedSession({
required this.userId,
required this.userName,
required this.role,
required this.isDeviceMatched,
this.grade,
});
Map<String, dynamic> toJson() => {
@@ -22,6 +24,7 @@ class SavedSession {
'userName': userName,
'role': role,
'isDeviceMatched': isDeviceMatched,
'grade': grade,
};
factory SavedSession.fromJson(Map<String, dynamic> json) => SavedSession(
@@ -29,6 +32,7 @@ class SavedSession {
userName: json['userName'] as String,
role: json['role'] as String,
isDeviceMatched: json['isDeviceMatched'] as bool? ?? true,
grade: json['grade'] as int?,
);
}
@@ -0,0 +1,46 @@
// 🏆 학년별 공부시간 랭킹 화면의 기능(서버 통신/상태) 담당 컨트롤러.
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import '../config.dart';
class StudyRankingController extends ChangeNotifier {
final int grade;
StudyRankingController({required this.grade});
bool _isLoading = true;
String _period = 'today'; // today / week / total
List<dynamic> _ranking = [];
bool get isLoading => _isLoading;
String get period => _period;
List<dynamic> get ranking => _ranking;
Future<void> init() => fetchRanking();
Future<void> setPeriod(String period) async {
if (_period == period) return;
_period = period;
await fetchRanking();
}
Future<void> fetchRanking() async {
_isLoading = true;
notifyListeners();
try {
final response = await http.get(
Uri.parse('$baseUrl/api/study/ranking?grade=$grade&period=$_period'),
);
if (response.statusCode == 200) {
final data = jsonDecode(utf8.decode(response.bodyBytes));
_ranking = data['ranking'] ?? [];
}
} catch (_) {
// 조용히 무시 - 마지막으로 받아온 랭킹을 유지한다.
} finally {
_isLoading = false;
notifyListeners();
}
}
}
+146
View File
@@ -0,0 +1,146 @@
// ⏱️ 우리 학교 전용 "열품타" 공부 타이머 화면의 기능(서버 통신/상태) 담당 컨트롤러.
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import '../config.dart';
class StudyTimerController extends ChangeNotifier {
final String studentId;
final String studentName;
StudyTimerController({required this.studentId, required this.studentName});
bool _isLoading = true;
bool _isBusy = false; // 시작/종료 버튼 눌러서 서버 응답 기다리는 중
bool _isRunning = false;
DateTime? _startTime;
int _todaySeconds = 0;
int _weekSeconds = 0;
int _totalSeconds = 0;
Timer? _ticker;
bool _disposed = false;
bool get isLoading => _isLoading;
bool get isBusy => _isBusy;
bool get isRunning => _isRunning;
/// 지금 진행 중인 세션까지 포함한 "오늘" 누적 초. 실시간으로 똑딱거린다.
int get todaySecondsLive =>
_todaySeconds + (_isRunning ? _liveElapsedSeconds : 0);
int get weekSecondsLive =>
_weekSeconds + (_isRunning ? _liveElapsedSeconds : 0);
int get totalSecondsLive =>
_totalSeconds + (_isRunning ? _liveElapsedSeconds : 0);
/// 지금 세션 하나만의 경과 시간(타이머 화면 큰 숫자용).
int get _liveElapsedSeconds {
if (_startTime == null) return 0;
final diff = DateTime.now().difference(_startTime!).inSeconds;
return diff > 0 ? diff : 0;
}
int get liveElapsedSeconds => _liveElapsedSeconds;
void _safeNotify() {
if (!_disposed) notifyListeners();
}
Future<void> init() async {
await _fetchStatus();
}
@override
void dispose() {
_disposed = true;
_ticker?.cancel();
super.dispose();
}
Future<void> _fetchStatus() async {
try {
final response = await http.get(
Uri.parse('$baseUrl/api/study/status?studentId=$studentId'),
);
if (response.statusCode == 200) {
final data = jsonDecode(utf8.decode(response.bodyBytes));
_isRunning = data['isRunning'] == true;
_startTime = data['startTime'] != null
? DateTime.tryParse(data['startTime'])
: null;
_todaySeconds = (data['todaySeconds'] as num?)?.toInt() ?? 0;
_weekSeconds = (data['weekSeconds'] as num?)?.toInt() ?? 0;
_totalSeconds = (data['totalSeconds'] as num?)?.toInt() ?? 0;
_restartTickerIfNeeded();
}
} catch (_) {
// 조용히 무시 - 마지막으로 알던 상태를 유지한다.
} finally {
_isLoading = false;
_safeNotify();
}
}
void _restartTickerIfNeeded() {
_ticker?.cancel();
if (_isRunning) {
_ticker = Timer.periodic(
const Duration(seconds: 1),
(_) => _safeNotify(),
);
}
}
Future<(bool success, String message)> start() async {
_isBusy = true;
_safeNotify();
try {
final response = await http.post(
Uri.parse('$baseUrl/api/study/start'),
headers: {"Content-Type": "application/json"},
body: jsonEncode({"studentId": studentId, "studentName": studentName}),
);
final result = jsonDecode(utf8.decode(response.bodyBytes));
if (response.statusCode == 200 && result['status'] == 'success') {
_isRunning = true;
_startTime = DateTime.tryParse(result['startTime']);
_restartTickerIfNeeded();
return (true, '공부를 시작했습니다.');
}
return (false, '${result['message'] ?? '공부 시작 실패'}');
} catch (e) {
return (false, '네트워크 에러: $e');
} finally {
_isBusy = false;
_safeNotify();
}
}
Future<(bool success, String message)> stop() async {
_isBusy = true;
_safeNotify();
try {
final response = await http.post(
Uri.parse('$baseUrl/api/study/stop'),
headers: {"Content-Type": "application/json"},
body: jsonEncode({"studentId": studentId}),
);
final result = jsonDecode(utf8.decode(response.bodyBytes));
if (response.statusCode == 200 && result['status'] == 'success') {
_isRunning = false;
_startTime = null;
_ticker?.cancel();
await _fetchStatus(); // 오늘/이번주/전체 합계를 서버 값으로 다시 맞춘다.
final minutes =
((result['durationSeconds'] as num?)?.toInt() ?? 0) ~/ 60;
return (true, '이번 공부 시간: $minutes분 기록 완료!');
}
return (false, '${result['message'] ?? '공부 종료 실패'}');
} catch (e) {
return (false, '네트워크 에러: $e');
} finally {
_isBusy = false;
_safeNotify();
}
}
}