339 lines
13 KiB
Dart
339 lines
13 KiB
Dart
// 🔐 (마스터 계정용) 학생 계정 및 기기 관리 화면. 기기 UUID 초기화와 계정 삭제를 담당한다.
|
|
import 'dart:convert';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import '../config.dart';
|
|
|
|
// ==========================================
|
|
// 🔐 6. 학생 계정 및 기기 관리 화면 (기기 리셋 + 계정 삭제 완본)
|
|
// ==========================================
|
|
class StudentManagementScreen extends StatefulWidget {
|
|
const StudentManagementScreen({super.key});
|
|
|
|
@override
|
|
State<StudentManagementScreen> createState() =>
|
|
_StudentManagementScreenState();
|
|
}
|
|
|
|
class _StudentManagementScreenState extends State<StudentManagementScreen> {
|
|
List<dynamic> realStudents = [];
|
|
bool _isLoading = true;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_fetchStudents();
|
|
}
|
|
|
|
// 🌐 서버에서 전체 학생 목록 불러오기
|
|
Future<void> _fetchStudents() async {
|
|
setState(() => _isLoading = true);
|
|
try {
|
|
final response = await http.get(Uri.parse('$baseUrl/api/users'));
|
|
if (response.statusCode == 200) {
|
|
final data = jsonDecode(utf8.decode(response.bodyBytes));
|
|
setState(() {
|
|
realStudents = data['users'] ?? [];
|
|
_isLoading = false;
|
|
});
|
|
}
|
|
} catch (e) {
|
|
ScaffoldMessenger.of(
|
|
context,
|
|
).showSnackBar(SnackBar(content: Text('데이터 불러오기 실패: $e')));
|
|
setState(() => _isLoading = false);
|
|
}
|
|
}
|
|
|
|
// 🌐 서버로 기기 초기화(리셋) 명령 보내기
|
|
Future<void> _resetDevice(String studentId, String studentName) async {
|
|
showDialog(
|
|
context: context,
|
|
builder: (ctx) => AlertDialog(
|
|
title: const Text(
|
|
'⚠️ 기기 잠금 해제',
|
|
style: TextStyle(fontWeight: FontWeight.bold, color: Colors.purple),
|
|
),
|
|
content: Text('$studentName 학생의 스마트폰 기기 등록을 초기화하시겠습니까?'),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(ctx),
|
|
child: const Text('취소', style: TextStyle(color: Colors.grey)),
|
|
),
|
|
ElevatedButton(
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: Colors.purple,
|
|
foregroundColor: Colors.white,
|
|
),
|
|
onPressed: () async {
|
|
Navigator.pop(ctx);
|
|
try {
|
|
final response = await http.post(
|
|
Uri.parse('$baseUrl/api/users/reset'),
|
|
headers: {"Content-Type": "application/json"},
|
|
body: jsonEncode({"studentId": studentId}),
|
|
);
|
|
if (response.statusCode == 200) {
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
SnackBar(content: Text('✅ $studentName 학생 기기 초기화 완료!')),
|
|
);
|
|
_fetchStudents();
|
|
}
|
|
} catch (e) {
|
|
ScaffoldMessenger.of(
|
|
context,
|
|
).showSnackBar(const SnackBar(content: Text('❌ 초기화 통신 실패')));
|
|
}
|
|
},
|
|
child: const Text('초기화 승인'),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
// 🌐 [새 기능] 서버로 계정 완전 삭제 명령 보내기 함수
|
|
Future<void> _deleteUser(String studentId, String studentName) async {
|
|
showDialog(
|
|
context: context,
|
|
builder: (ctx) => AlertDialog(
|
|
title: const Text(
|
|
'🚨 계정 완전 삭제 경고',
|
|
style: TextStyle(fontWeight: FontWeight.bold, color: Colors.red),
|
|
),
|
|
content: Text(
|
|
'정말로 $studentName ($studentId) 학생의 계정을 시스템에서 탈퇴(삭제)시키겠습니까?\n\n이 작업은 되돌릴 수 없으며, 해당 학생은 다시 회원가입을 진행해야 합니다.',
|
|
),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(ctx),
|
|
child: const Text('취소', style: TextStyle(color: Colors.grey)),
|
|
),
|
|
ElevatedButton(
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: Colors.red,
|
|
foregroundColor: Colors.white,
|
|
),
|
|
onPressed: () async {
|
|
Navigator.pop(ctx);
|
|
try {
|
|
// 💡 http.delete 함수를 사용하여 서버에 계정 삭제 요청 발송!
|
|
final response = await http.delete(
|
|
Uri.parse('$baseUrl/api/users/delete'),
|
|
headers: {"Content-Type": "application/json"},
|
|
body: jsonEncode({"studentId": studentId}),
|
|
);
|
|
|
|
if (response.statusCode == 200) {
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
SnackBar(
|
|
content: Text('💥 $studentName 학생의 계정이 영구 삭제되었습니다.'),
|
|
),
|
|
);
|
|
_fetchStudents(); // 성공하면 목록 새로고침!
|
|
}
|
|
} catch (e) {
|
|
ScaffoldMessenger.of(
|
|
context,
|
|
).showSnackBar(const SnackBar(content: Text('❌ 계정 삭제 통신 실패')));
|
|
}
|
|
},
|
|
child: const Text('영구 삭제'),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
// 💡 _StudentManagementScreenState 클래스 내부에 붙여넣으세요.
|
|
void _showCreateUserDialog() {
|
|
final idController = TextEditingController();
|
|
final nameController = TextEditingController();
|
|
|
|
showDialog(
|
|
context: context,
|
|
builder: (context) => AlertDialog(
|
|
title: const Text('👤 신규 학생 계정 추가'),
|
|
content: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
TextField(
|
|
controller: idController,
|
|
decoration: const InputDecoration(labelText: '학번 입력 (예: 20101)'),
|
|
keyboardType: TextInputType.number,
|
|
),
|
|
const SizedBox(height: 8),
|
|
TextField(
|
|
controller: nameController,
|
|
decoration: const InputDecoration(labelText: '학생 이름 입력'),
|
|
),
|
|
],
|
|
),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(context),
|
|
child: const Text('취소'),
|
|
),
|
|
ElevatedButton(
|
|
onPressed: () async {
|
|
String studentId = idController.text.trim();
|
|
String name = nameController.text.trim();
|
|
|
|
if (studentId.isEmpty || name.isEmpty) {
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
const SnackBar(content: Text('⚠️ 학번과 이름을 모두 입력하세요.')),
|
|
);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
// ⚠️ 여기도 훗춧가룻님의 프로젝트 전역 baseUrl 변수명으로 맞춰주세요!
|
|
final response = await http.post(
|
|
Uri.parse('$baseUrl/api/users/create'),
|
|
headers: {"Content-Type": "application/json"},
|
|
body: jsonEncode({"studentId": studentId, "name": name}),
|
|
);
|
|
|
|
final res = jsonDecode(response.body);
|
|
if (res['status'] == 'success') {
|
|
Navigator.pop(context); // 팝업 닫기
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
SnackBar(content: Text('✅ ${res['message']}')),
|
|
);
|
|
_fetchStudents(); // 🔄 추가 완료 후 목록 새로고침 (기존 함수명 확인 필요)
|
|
} else {
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
SnackBar(content: Text('❌ ${res['message']}')),
|
|
);
|
|
}
|
|
} catch (e) {
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
const SnackBar(content: Text('❌ 학생 등록 실패 (통신 에러)')),
|
|
);
|
|
}
|
|
},
|
|
child: const Text('생성'),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
backgroundColor: Colors.grey[50],
|
|
appBar: AppBar(
|
|
title: const Text(
|
|
'학생 계정 및 기기 관리',
|
|
style: TextStyle(fontWeight: FontWeight.bold),
|
|
),
|
|
backgroundColor: Colors.purple,
|
|
foregroundColor: Colors.white,
|
|
actions: [
|
|
IconButton(
|
|
icon: const Icon(Icons.person_add_alt_1_rounded),
|
|
onPressed: () => _showCreateUserDialog(), // 팝업 띄우는 함수 제작하여 연결
|
|
),
|
|
IconButton(
|
|
icon: const Icon(Icons.refresh),
|
|
onPressed: _fetchStudents,
|
|
),
|
|
],
|
|
),
|
|
body: _isLoading
|
|
? const Center(child: CircularProgressIndicator(color: Colors.purple))
|
|
: realStudents.isEmpty
|
|
? const Center(
|
|
child: Text(
|
|
'가입된 학생 계정이 없습니다.',
|
|
style: TextStyle(color: Colors.grey, fontSize: 16),
|
|
),
|
|
)
|
|
: ListView.builder(
|
|
padding: const EdgeInsets.all(16),
|
|
itemCount: realStudents.length,
|
|
itemBuilder: (context, index) {
|
|
final student = realStudents[index];
|
|
final bool needsReset = student['device'] == "초기화 필요";
|
|
|
|
return Card(
|
|
elevation: 2,
|
|
margin: const EdgeInsets.only(bottom: 12),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(16),
|
|
),
|
|
child: ListTile(
|
|
contentPadding: const EdgeInsets.symmetric(
|
|
horizontal: 16,
|
|
vertical: 12,
|
|
),
|
|
leading: CircleAvatar(
|
|
backgroundColor: needsReset
|
|
? Colors.red[50]
|
|
: Colors.purple[50],
|
|
child: Icon(
|
|
needsReset ? Icons.lock_reset : Icons.person,
|
|
color: needsReset ? Colors.red : Colors.purple,
|
|
),
|
|
),
|
|
title: Text(
|
|
'${student['name']} (${student['id']})',
|
|
style: const TextStyle(
|
|
fontWeight: FontWeight.bold,
|
|
fontSize: 16,
|
|
),
|
|
),
|
|
subtitle: Text(
|
|
needsReset ? '기기 초기화 승인 대기중' : '정상 등록 상태',
|
|
style: TextStyle(
|
|
color: needsReset ? Colors.red : Colors.grey,
|
|
fontWeight: needsReset
|
|
? FontWeight.bold
|
|
: FontWeight.normal,
|
|
),
|
|
),
|
|
// 🕹️ 오른쪽 끝에 [기기 리셋] 버튼과 [쓰레기통(삭제)] 버튼을 나란히 배치하는 Row 레이아웃 기획
|
|
trailing: Row(
|
|
mainAxisSize: MainAxisSize.min, // 콤팩트하게 뭉치기
|
|
children: [
|
|
if (!needsReset)
|
|
OutlinedButton(
|
|
style: OutlinedButton.styleFrom(
|
|
foregroundColor: Colors.purple,
|
|
side: BorderSide(
|
|
color: Colors.purple.withValues(alpha: 0.5),
|
|
),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(8),
|
|
),
|
|
),
|
|
onPressed: () =>
|
|
_resetDevice(student['id'], student['name']),
|
|
child: const Text('기기 리셋'),
|
|
)
|
|
else
|
|
const Icon(Icons.check_circle, color: Colors.green),
|
|
|
|
const SizedBox(width: 8),
|
|
|
|
// 🔴 [새 버튼] 최고권한 마스터 전용 계정 영구 삭제 쓰레기통 버튼!
|
|
IconButton(
|
|
icon: const Icon(
|
|
Icons.delete_forever_rounded,
|
|
color: Colors.redAccent,
|
|
),
|
|
tooltip: '계정 영구 삭제',
|
|
onPressed: () =>
|
|
_deleteUser(student['id'], student['name']),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
},
|
|
),
|
|
);
|
|
}
|
|
}
|