Files
school-attendance/lib/ui/device_checkout_ledger_page.dart
T
sihoo edf0444b71 프로필 꾸미기 미리보기 테두리/체험 버튼 추가, 확인 버튼 엔터 지원, 비밀번호 홀드 보기 추가
- 프로필 꾸미기: 미리보기 중인 큰 타일의 테두리도 테마 색으로 바뀌게 수정,
  미구매 템플릿에 "체험하기" 버튼을 따로 둬서 사기 전에도 눌러볼 수 있게 함
- 앱 전반의 확인/삭제/저장 같은 다이얼로그 기본 액션 버튼에 autofocus를 줘서
  엔터 키로도 눌리게 함 (텍스트 입력이 있는 다이얼로그는 입력창 쪽에
  autofocus + onSubmitted를 달아 입력 중 바로 엔터로 제출되게 처리)
- HoldToRevealPasswordField 위젯 추가 - 눈 아이콘을 누르고 있는 동안만
  비밀번호가 평문으로 보임. 로그인/간편인증/초기 비밀번호 변경 화면에 적용
2026-10-01 05:52:57 +00:00

513 lines
23 KiB
Dart

// 📋 선생님용 "스마트기기 반출 대장" 화면 (UI 전용). 오늘 신청된 반출 요청을 보여주고 승인/거절한다.
// 서버 통신/상태는 lib/function/device_checkout_ledger_controller.dart가 담당한다.
import 'package:flutter/material.dart';
import '../function/device_checkout_ledger_controller.dart';
import '../theme/app_palette.dart';
import 'app_notice.dart';
import 'title_pill.dart';
class DeviceCheckoutLedgerPage extends StatefulWidget {
final String? teacherId;
final String? teacherName;
const DeviceCheckoutLedgerPage({super.key, this.teacherId, this.teacherName});
@override
State<DeviceCheckoutLedgerPage> createState() =>
_DeviceCheckoutLedgerPageState();
}
class _DeviceCheckoutLedgerPageState extends State<DeviceCheckoutLedgerPage> {
final DeviceCheckoutLedgerController _controller =
DeviceCheckoutLedgerController();
@override
void initState() {
super.initState();
_controller.init();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Future<void> _approve(int id) async {
final (_, message) = await _controller.approve(
id,
teacherId: widget.teacherId ?? '간편인증',
teacherName: widget.teacherName ?? '간편인증 선생',
);
if (!mounted) return;
AppNotice.show(context, message);
}
Future<void> _reject(int id) async {
final (_, message) = await _controller.reject(id);
if (!mounted) return;
AppNotice.show(context, message);
}
// 🙌 [전체 학생 허용] 한 명씩 누르기 귀찮을 때, 대기 중인 요청을 한 번에 전부 승인한다.
// 1시간 59분 넘는 장시간 요청은 자동으로 제외되어 대기중으로 남는다 - 따로 검토가 필요해서.
void _showApproveAllConfirmDialog() {
final pendingCount = _controller.requests
.where((r) => r['status'] == 'PENDING')
.length;
if (pendingCount == 0) {
AppNotice.show(context, '승인 대기 중인 요청이 없습니다.');
return;
}
final approvableCount = _controller.autoApprovableIds.length;
final excludedCount = pendingCount - approvableCount;
showDialog(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('전체 학생 허용'),
content: Text(
excludedCount > 0
? '대기 중인 요청 $pendingCount건 중 $approvableCount건을 승인합니다.\n'
'장시간(1시간 59분 이상) 요청 $excludedCount건은 제외되어 "많은 시간요청 학생"에서 따로 확인해야 합니다.'
: '대기 중인 요청 $pendingCount건을 한 번에 전부 승인하시겠습니까?',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('취소', style: TextStyle(color: Colors.grey)),
),
ElevatedButton(
autofocus: true,
style: ElevatedButton.styleFrom(
backgroundColor: AppPalette.ink,
foregroundColor: AppPalette.paper,
),
onPressed: () async {
Navigator.pop(dialogContext);
final (_, message) = await _controller.approveAllPending(
teacherId: widget.teacherId ?? '간편인증',
teacherName: widget.teacherName ?? '간편인증 선생',
);
if (!mounted) return;
AppNotice.show(context, message);
},
child: const Text('전체 승인'),
),
],
),
);
}
// 🚨 [많은 시간요청 학생] 1시간 59분 넘게 신청한 대기 중인 요청만 따로 모아 보여준다.
// 학생이 시간을 비정상적으로 길게 적어냈을 수 있으니, 전체 승인 전에 훑어보는 용도.
void _showLongRequestsDialog() {
showDialog(
context: context,
builder: (dialogContext) => AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
title: const Row(
children: [
Icon(Icons.warning_amber_rounded, color: AppPalette.warning),
SizedBox(width: 8),
Text('많은 시간요청 학생'),
],
),
content: SizedBox(
width: 380,
child: ListenableBuilder(
listenable: _controller,
builder: (context, _) {
final longRequests = _controller.longPendingRequests;
if (longRequests.isEmpty) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: 16),
child: Text(
'1시간 59분 넘게 신청한 대기 중인 요청이 없습니다.',
style: TextStyle(color: Colors.grey),
),
);
}
return ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 400),
child: ListView.separated(
shrinkWrap: true,
itemCount: longRequests.length,
separatorBuilder: (_, _) => const Divider(height: 20),
itemBuilder: (context, index) {
final r = longRequests[index];
final hours = _controller.durationHours(r);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'${r['studentName']} (${r['studentId']})',
style: const TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
Text(
'${_timeRange(r['requestedStart'], r['requestedEnd'])} '
'(약 ${hours?.toStringAsFixed(1)}시간)',
style: const TextStyle(
color: AppPalette.warning,
fontWeight: FontWeight.bold,
fontSize: 13,
),
),
const SizedBox(height: 2),
Text(
r['purpose'],
style: TextStyle(
color: Colors.grey[700],
fontSize: 13,
),
),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: _controller.isWorking
? null
: () {
Navigator.pop(dialogContext);
_reject(r['id']);
},
style: OutlinedButton.styleFrom(
foregroundColor: AppPalette.danger,
side: const BorderSide(
color: AppPalette.danger,
),
),
child: const Text('거절'),
),
),
const SizedBox(width: 8),
Expanded(
child: ElevatedButton(
onPressed: _controller.isWorking
? null
: () {
Navigator.pop(dialogContext);
_approve(r['id']);
},
style: ElevatedButton.styleFrom(
backgroundColor: AppPalette.ink,
foregroundColor: AppPalette.paper,
),
child: const Text('승인'),
),
),
],
),
],
);
},
),
);
},
),
),
actions: [
TextButton(
autofocus: true,
onPressed: () => Navigator.pop(dialogContext),
child: const Text('닫기'),
),
],
),
);
}
// 🖐️ [하드웨어 자동 감지 전까지 임시] 기기를 실제로 돌려받았을 때 누르는 버튼.
Future<void> _confirmReturn(int id) async {
final (_, message) = await _controller.confirmReturn(id);
if (!mounted) return;
AppNotice.show(context, message);
}
({Color color, String label}) _statusInfo(String status) {
switch (status) {
case 'PENDING':
return (color: AppPalette.warning, label: '대기중');
case 'APPROVED':
return (color: AppPalette.approved, label: '승인됨');
case 'RETURNED':
return (color: Colors.grey, label: '반납완료');
case 'REJECTED':
return (color: AppPalette.danger, label: '거절됨');
default:
return (color: Colors.grey, label: status);
}
}
String _timeRange(String start, String end) {
// "YYYY-MM-DD HH:MM:SS" -> "HH:MM"
String hm(String full) => full.length >= 16 ? full.substring(11, 16) : full;
return '${hm(start)} ~ ${hm(end)}';
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: _controller,
builder: (context, _) {
final requests = _controller.requests;
final pendingCount = requests
.where((r) => r['status'] == 'PENDING')
.length;
final longCount = _controller.longPendingRequests.length;
return Scaffold(
backgroundColor: AppPalette.mist,
appBar: AppBar(
backgroundColor: Colors.transparent,
foregroundColor: AppPalette.ink,
elevation: 0,
centerTitle: true,
title: const TitlePill('스마트기기 반출 대장'),
actions: [
IconButton(
icon: const Icon(Icons.refresh_rounded),
onPressed: _controller.fetchAll,
tooltip: '새로고침',
),
IconButton(
icon: const Icon(Icons.done_all_rounded),
onPressed: _showApproveAllConfirmDialog,
tooltip: '전체 학생 허용',
),
IconButton(
icon: Badge(
isLabelVisible: longCount > 0,
label: Text('$longCount'),
backgroundColor: AppPalette.danger,
child: const Icon(Icons.warning_amber_rounded),
),
onPressed: _showLongRequestsDialog,
tooltip: '많은 시간요청 학생',
),
],
),
body: _controller.isLoading
? const Center(child: CircularProgressIndicator())
: Column(
children: [
if (pendingCount > 0)
Container(
width: double.infinity,
margin: const EdgeInsets.all(16),
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 10,
),
decoration: BoxDecoration(
color: AppPalette.warningBg,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: AppPalette.warning),
),
child: Text(
'승인 대기 중인 요청이 $pendingCount건 있습니다.',
style: TextStyle(
color: AppPalette.warning,
fontWeight: FontWeight.bold,
),
),
),
Expanded(
child: requests.isEmpty
? const Center(
child: Text(
'오늘 신청된 반출 요청이 없습니다.',
style: TextStyle(color: Colors.grey),
),
)
: ListView.builder(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
itemCount: requests.length,
itemBuilder: (context, index) {
final r = requests[index];
final String status = r['status'];
final info = _statusInfo(status);
final bool isPending = status == 'PENDING';
// 🚨 1시간 59분 넘게 신청했으면 상태와 무관하게 빨간 테두리로 눈에 띄게.
final bool isLong = _controller.isLongRequest(
r,
);
return Card(
elevation: 0,
color: AppPalette.paper,
margin: const EdgeInsets.only(bottom: 10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: isLong
? const BorderSide(
color: AppPalette.danger,
width: 2,
)
: (isPending
? const BorderSide(
color: AppPalette.warning,
)
: const BorderSide(
color: AppPalette.sage,
)),
),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Text(
'${r['studentName']} (${r['studentId']})',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
),
),
),
Container(
padding:
const EdgeInsets.symmetric(
horizontal: 10,
vertical: 4,
),
decoration: BoxDecoration(
color: info.color.withValues(
alpha: 0.12,
),
borderRadius:
BorderRadius.circular(20),
),
child: Text(
info.label,
style: TextStyle(
color: info.color,
fontWeight: FontWeight.bold,
fontSize: 12,
),
),
),
],
),
const SizedBox(height: 6),
Text(
_timeRange(
r['requestedStart'],
r['requestedEnd'],
),
style: TextStyle(
color: Colors.grey[700],
fontSize: 13,
),
),
const SizedBox(height: 2),
Text(
r['purpose'],
style: TextStyle(
color: Colors.grey[700],
fontSize: 13,
),
),
if (status == 'APPROVED' &&
r['approvedByTeacherName'] !=
null) ...[
const SizedBox(height: 2),
Text(
'${r['approvedByTeacherName']} 선생님이 허용했습니다',
style: TextStyle(
color: AppPalette.approved,
fontSize: 12,
fontWeight: FontWeight.w600,
),
),
],
if (isPending) ...[
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: OutlinedButton(
onPressed:
_controller.isWorking
? null
: () => _reject(r['id']),
style:
OutlinedButton.styleFrom(
foregroundColor:
AppPalette.danger,
side: const BorderSide(
color:
AppPalette.danger,
),
),
child: const Text('거절'),
),
),
const SizedBox(width: 8),
Expanded(
child: ElevatedButton(
onPressed:
_controller.isWorking
? null
: () => _approve(r['id']),
style:
ElevatedButton.styleFrom(
backgroundColor:
AppPalette.ink,
foregroundColor:
AppPalette.paper,
),
child: const Text('승인'),
),
),
],
),
],
if (status == 'APPROVED') ...[
const SizedBox(height: 12),
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
onPressed: _controller.isWorking
? null
: () =>
_confirmReturn(r['id']),
style: OutlinedButton.styleFrom(
foregroundColor:
Colors.grey[800],
side: BorderSide(
color: Colors.grey[400]!,
),
),
icon: const Icon(
Icons
.assignment_turned_in_outlined,
size: 18,
),
label: const Text('기기 반납 확인'),
),
),
],
],
),
),
);
},
),
),
],
),
);
},
);
}
}