feat(user): 사용자 자기정보 편집과 관리자 재설정 플로우를 연동

- lib/widgets/app_shell.dart에서 내 정보 다이얼로그를 추가하고 UserRepository.updateMe·비밀번호 변경 로직을 연결

- lib/features/masters/user/* 모듈에 phone·forcePasswordChange·passwordUpdatedAt 필드를 반영하고 reset-password/update-me API를 사용

- lib/core/validation/password_rules.dart을 신설해 비밀번호 정책 검증을 공통화하고 신규 위젯·테스트에서 재사용

- doc/stock_approval_system_api_v4.md 등 문서를 users 스펙 개편 내용으로 갱신하고 user_management_plan.md를 추가

- test/widgets/app_shell_test.dart 등에서 자기정보 수정·비밀번호 재설정 시나리오를 검증하고 기존 테스트를 보강
This commit is contained in:
JiWoong Sul
2025-10-26 17:05:47 +09:00
parent 9beb161527
commit 14624c4165
23 changed files with 1958 additions and 194 deletions

View File

@@ -2,13 +2,18 @@ import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:go_router/go_router.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart' as lucide;
import 'package:intl/intl.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import '../core/constants/app_sections.dart';
import '../core/permissions/permission_manager.dart';
import '../core/network/failure.dart';
import '../core/theme/theme_controller.dart';
import '../core/validation/password_rules.dart';
import '../features/auth/application/auth_service.dart';
import '../features/auth/domain/entities/auth_session.dart';
import '../features/masters/user/domain/entities/user.dart';
import '../features/masters/user/domain/repositories/user_repository.dart';
import 'components/superport_dialog.dart';
/// 앱 기본 레이아웃을 제공하는 셸 위젯. 사이드 네비게이션과 AppBar를 구성한다.
@@ -411,60 +416,631 @@ class _AccountMenuButton extends StatelessWidget {
return AnimatedBuilder(
animation: service,
builder: (context, _) {
final session = service.session;
return IconButton(
tooltip: '계정 정보',
tooltip: ' 정보',
icon: const Icon(lucide.LucideIcons.userRound),
onPressed: () => _handlePressed(context, session),
onPressed: () => _handlePressed(context),
);
},
);
}
Future<void> _handlePressed(
BuildContext context,
AuthSession? session,
) async {
final shouldLogout = await SuperportDialog.show<bool>(
Future<void> _handlePressed(BuildContext context) async {
final userRepository = GetIt.I<UserRepository>();
final result = await showDialog<_AccountDialogResult>(
context: context,
dialog: SuperportDialog(
title: '계정 정보',
description: session == null
? '로그인 정보를 찾을 수 없습니다.'
: '현재 로그인된 계정 세부 정보를 확인하세요.',
footer: Builder(
builder: (dialogContext) {
return Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ShadButton.outline(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('닫기'),
),
const SizedBox(width: 12),
ShadButton.destructive(
onPressed: session == null
? null
: () => Navigator.of(dialogContext).pop(true),
child: const Text('로그아웃'),
),
],
),
);
},
),
scrollable: session != null && session.permissions.length > 6,
child: _AccountInfoContent(session: session),
barrierDismissible: false,
builder: (_) => _AccountDialog(
authService: service,
userRepository: userRepository,
hostContext: context,
),
);
if (shouldLogout == true) {
await service.clearSession();
if (!context.mounted) return;
context.go(loginRoutePath);
switch (result) {
case _AccountDialogResult.logout:
await service.clearSession();
if (context.mounted) {
context.go(loginRoutePath);
}
break;
case _AccountDialogResult.passwordChanged:
final confirmed = await _showMandatoryLogoutDialog(context);
if (confirmed == true) {
await service.clearSession();
if (context.mounted) {
context.go(loginRoutePath);
}
}
break;
case _AccountDialogResult.none:
case null:
break;
}
}
Future<bool?> _showMandatoryLogoutDialog(BuildContext context) {
return SuperportDialog.show<bool>(
context: context,
barrierDismissible: false,
dialog: SuperportDialog(
title: '비밀번호 변경 완료',
description: '비밀번호가 변경되었습니다. 다시 로그인해주세요.',
showCloseButton: false,
primaryAction: ShadButton(
onPressed: () => Navigator.of(context, rootNavigator: true).pop(true),
child: const Text('확인'),
),
),
);
}
}
enum _AccountDialogResult { none, logout, passwordChanged }
class _AccountDialog extends StatefulWidget {
const _AccountDialog({
required this.authService,
required this.userRepository,
required this.hostContext,
});
final AuthService authService;
final UserRepository userRepository;
final BuildContext hostContext;
@override
State<_AccountDialog> createState() => _AccountDialogState();
}
class _AccountDialogState extends State<_AccountDialog> {
static final RegExp _emailRegExp = RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+$');
static final RegExp _phoneRegExp = RegExp(r'^[0-9+\-\s]{7,}$');
late final TextEditingController _emailController;
late final TextEditingController _phoneController;
String? _emailError;
String? _phoneError;
String? _generalError;
bool _isSaving = false;
late String _initialEmail;
late String _initialPhone;
AuthSession? get _session => widget.authService.session;
bool get _isDirty =>
_emailController.text.trim() != _initialEmail ||
_phoneController.text.trim() != _initialPhone;
bool get _canEdit => _session != null;
@override
void initState() {
super.initState();
final session = _session;
_initialEmail = session?.user.email ?? '';
_initialPhone = session?.user.phone ?? '';
_emailController = TextEditingController(text: _initialEmail)
..addListener(_handleChanged);
_phoneController = TextEditingController(text: _initialPhone)
..addListener(_handleChanged);
}
@override
void dispose() {
_emailController.dispose();
_phoneController.dispose();
super.dispose();
}
void _handleChanged() {
if ((_emailError != null || _phoneError != null) && mounted) {
setState(() {
_emailError = null;
_phoneError = null;
_generalError = null;
});
} else {
setState(() {});
}
}
@override
Widget build(BuildContext context) {
final session = _session;
return _wrapWithWillPop(
SuperportDialog(
title: '내 정보',
description: session == null
? '로그인 정보를 찾을 수 없습니다.'
: '${session.user.name}님의 계정 정보를 확인하고 수정하세요.',
scrollable: true,
showCloseButton: false,
footer: Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ShadButton.outline(
onPressed: _isSaving
? null
: () => Navigator.of(
context,
rootNavigator: true,
).pop(_AccountDialogResult.none),
child: const Text('닫기'),
),
const SizedBox(width: 12),
ShadButton.destructive(
onPressed: !_canEdit || _isSaving
? null
: () => Navigator.of(
context,
rootNavigator: true,
).pop(_AccountDialogResult.logout),
child: const Text('로그아웃'),
),
],
),
),
child: _AccountDialogBody(
session: session,
emailController: _emailController,
phoneController: _phoneController,
emailError: _emailError,
phoneError: _phoneError,
generalError: _generalError,
isSaving: _isSaving,
canEdit: _canEdit,
onSave: _saveProfile,
onPasswordChange: _handlePasswordChange,
canSave: _isDirty && !_isSaving && _canEdit,
),
),
);
}
Widget _wrapWithWillPop(Widget child) {
return WillPopScope(onWillPop: () async => !_isSaving, child: child);
}
Future<void> _saveProfile() async {
if (!_canEdit || _isSaving) {
return;
}
final email = _emailController.text.trim();
final phone = _phoneController.text.trim();
var hasError = false;
if (email.isEmpty || !_emailRegExp.hasMatch(email)) {
_emailError = '올바른 이메일 주소를 입력하세요.';
hasError = true;
}
if (phone.isEmpty || !_phoneRegExp.hasMatch(phone)) {
_phoneError = '연락처는 숫자/+, -/공백만 사용해 7자 이상 입력하세요.';
hasError = true;
}
if (hasError) {
setState(() {});
return;
}
setState(() {
_isSaving = true;
_generalError = null;
});
try {
final result = await widget.userRepository.updateMe(
UserProfileUpdateInput(email: email, phone: phone),
);
final updatedEmail = result.email ?? email;
final updatedPhone = result.mobileNo ?? phone;
_initialEmail = updatedEmail;
_initialPhone = updatedPhone;
if (_emailController.text != updatedEmail) {
_emailController.text = updatedEmail;
}
if (_phoneController.text != updatedPhone) {
_phoneController.text = updatedPhone;
}
final session = _session;
if (session != null) {
final updatedUser = session.user.copyWith(
email: updatedEmail,
phone: updatedPhone,
name: result.employeeName,
employeeNo: result.employeeNo,
);
widget.authService.updateSessionUser(updatedUser);
}
setState(() {
_isSaving = false;
_emailError = null;
_phoneError = null;
});
_showSnack('프로필 정보를 저장했습니다.');
} catch (error) {
final failure = Failure.from(error);
setState(() {
_isSaving = false;
_generalError = failure.describe();
});
}
}
Future<void> _handlePasswordChange() async {
if (!_canEdit || _isSaving) {
return;
}
final changed = await _PasswordChangeDialog.show(
context: context,
userRepository: widget.userRepository,
);
if (changed == true && mounted) {
Navigator.of(
context,
rootNavigator: true,
).pop(_AccountDialogResult.passwordChanged);
}
}
void _showSnack(String message) {
final messenger = ScaffoldMessenger.maybeOf(widget.hostContext);
messenger?.showSnackBar(SnackBar(content: Text(message)));
}
}
class _AccountDialogBody extends StatelessWidget {
const _AccountDialogBody({
required this.session,
required this.emailController,
required this.phoneController,
required this.emailError,
required this.phoneError,
required this.generalError,
required this.isSaving,
required this.canEdit,
required this.onSave,
required this.onPasswordChange,
required this.canSave,
});
final AuthSession? session;
final TextEditingController emailController;
final TextEditingController phoneController;
final String? emailError;
final String? phoneError;
final String? generalError;
final bool isSaving;
final bool canEdit;
final bool canSave;
final VoidCallback onSave;
final VoidCallback onPasswordChange;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
_AccountInfoContent(session: session),
const SizedBox(height: 24),
Divider(color: Theme.of(context).colorScheme.outlineVariant),
const SizedBox(height: 16),
Text('연락처 / 이메일 수정', style: Theme.of(context).textTheme.titleSmall),
const SizedBox(height: 12),
_LabeledField(
label: '이메일',
controller: emailController,
fieldKey: const ValueKey('account_email_field'),
enabled: canEdit && !isSaving,
keyboardType: TextInputType.emailAddress,
errorText: emailError,
),
const SizedBox(height: 12),
_LabeledField(
label: '연락처',
controller: phoneController,
fieldKey: const ValueKey('account_phone_field'),
enabled: canEdit && !isSaving,
keyboardType: TextInputType.phone,
errorText: phoneError,
),
if (generalError != null) ...[
const SizedBox(height: 12),
Text(
generalError!,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.error,
),
),
],
const SizedBox(height: 16),
Align(
alignment: Alignment.centerRight,
child: ShadButton(
onPressed: canSave ? onSave : null,
child: isSaving
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('저장'),
),
),
const SizedBox(height: 24),
Divider(color: Theme.of(context).colorScheme.outlineVariant),
const SizedBox(height: 16),
Text('보안', style: Theme.of(context).textTheme.titleSmall),
const SizedBox(height: 12),
ShadButton.outline(
onPressed: isSaving ? null : onPasswordChange,
child: const Text('비밀번호 변경'),
),
],
);
}
}
class _LabeledField extends StatelessWidget {
const _LabeledField({
required this.label,
required this.controller,
this.fieldKey,
this.enabled = true,
this.keyboardType,
this.errorText,
});
final String label;
final TextEditingController controller;
final Key? fieldKey;
final bool enabled;
final TextInputType? keyboardType;
final String? errorText;
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
final materialTheme = Theme.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: theme.textTheme.small),
const SizedBox(height: 6),
ShadInput(
key: fieldKey,
controller: controller,
enabled: enabled,
keyboardType: keyboardType,
),
if (errorText != null) ...[
const SizedBox(height: 6),
Text(
errorText!,
style: theme.textTheme.small.copyWith(
color: materialTheme.colorScheme.error,
),
),
],
],
);
}
}
class _PasswordChangeDialog extends StatefulWidget {
const _PasswordChangeDialog({required this.userRepository});
final UserRepository userRepository;
static Future<bool?> show({
required BuildContext context,
required UserRepository userRepository,
}) {
return showDialog<bool>(
context: context,
barrierDismissible: false,
builder: (_) => _PasswordChangeDialog(userRepository: userRepository),
);
}
@override
State<_PasswordChangeDialog> createState() => _PasswordChangeDialogState();
}
class _PasswordChangeDialogState extends State<_PasswordChangeDialog> {
final TextEditingController _currentController = TextEditingController();
final TextEditingController _newController = TextEditingController();
final TextEditingController _confirmController = TextEditingController();
String? _currentError;
String? _newError;
String? _confirmError;
String? _generalError;
bool _isSaving = false;
@override
void dispose() {
_currentController.dispose();
_newController.dispose();
_confirmController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SuperportDialog(
title: '비밀번호 변경',
showCloseButton: !_isSaving,
primaryAction: ShadButton(
onPressed: _isSaving ? null : _handleSubmit,
child: _isSaving
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('변경'),
),
secondaryAction: ShadButton.outline(
onPressed: _isSaving
? null
: () => Navigator.of(context, rootNavigator: true).pop(false),
child: const Text('취소'),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
_PasswordField(
label: '현재 비밀번호',
controller: _currentController,
fieldKey: const ValueKey('account_current_password'),
errorText: _currentError,
enabled: !_isSaving,
),
const SizedBox(height: 12),
_PasswordField(
label: '새 비밀번호',
controller: _newController,
fieldKey: const ValueKey('account_new_password'),
errorText: _newError,
enabled: !_isSaving,
helper: '8~24자, 대문자/소문자/숫자/특수문자 각 1자 이상 포함',
),
const SizedBox(height: 12),
_PasswordField(
label: '새 비밀번호 확인',
controller: _confirmController,
fieldKey: const ValueKey('account_confirm_password'),
errorText: _confirmError,
enabled: !_isSaving,
),
if (_generalError != null) ...[
const SizedBox(height: 12),
Text(
_generalError!,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.error,
),
),
],
],
),
);
}
Future<void> _handleSubmit() async {
if (_isSaving) return;
final current = _currentController.text.trim();
final next = _newController.text.trim();
final confirm = _confirmController.text.trim();
var hasError = false;
if (current.isEmpty) {
_currentError = '현재 비밀번호를 입력하세요.';
hasError = true;
} else {
_currentError = null;
}
if (!PasswordRules.isValid(next)) {
_newError = '비밀번호 정책을 만족하도록 입력하세요.';
hasError = true;
} else {
_newError = null;
}
if (next != confirm) {
_confirmError = '새 비밀번호가 일치하지 않습니다.';
hasError = true;
} else {
_confirmError = null;
}
if (hasError) {
setState(() {});
return;
}
setState(() {
_isSaving = true;
_generalError = null;
});
try {
await widget.userRepository.updateMe(
UserProfileUpdateInput(password: next, currentPassword: current),
);
if (mounted) {
Navigator.of(context, rootNavigator: true).pop(true);
}
} catch (error) {
final failure = Failure.from(error);
setState(() {
_generalError = failure.describe();
_isSaving = false;
});
}
}
}
class _PasswordField extends StatelessWidget {
const _PasswordField({
required this.label,
required this.controller,
this.helper,
this.errorText,
this.enabled = true,
this.fieldKey,
});
final String label;
final TextEditingController controller;
final String? helper;
final String? errorText;
final bool enabled;
final Key? fieldKey;
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
final materialTheme = Theme.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: theme.textTheme.small),
const SizedBox(height: 6),
ShadInput(
key: fieldKey,
controller: controller,
enabled: enabled,
obscureText: true,
),
if (helper != null)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(helper!, style: theme.textTheme.muted),
),
if (errorText != null)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
errorText!,
style: theme.textTheme.small.copyWith(
color: materialTheme.colorScheme.error,
),
),
),
],
);
}
}
/// 로그인된 계정의 핵심 정보를 보여주는 다이얼로그 본문.
@@ -499,6 +1075,7 @@ class _AccountInfoContent extends StatelessWidget {
_AccountInfoRow(label: '이름', value: user.name),
_AccountInfoRow(label: '사번', value: user.employeeNo ?? '-'),
_AccountInfoRow(label: '이메일', value: user.email ?? '-'),
_AccountInfoRow(label: '연락처', value: user.phone ?? '-'),
_AccountInfoRow(label: '기본 그룹', value: user.primaryGroupName ?? '-'),
_AccountInfoRow(label: '토큰 만료', value: expiryLabel),
_AccountInfoRow(