feat: 대규모 코드베이스 개선 - 백엔드 통합성 강화 및 UI 일관성 완성
- CLAUDE.md 대폭 개선: 개발 가이드라인 및 프로젝트 상태 문서화 - 백엔드 API 통합: 모든 엔티티 간 Foreign Key 관계 완벽 구현 - UI 일관성 강화: shadcn_ui 컴포넌트 표준화 적용 - 데이터 모델 개선: DTO 및 모델 클래스 백엔드 스키마와 100% 일치 - 사용자 관리: 회사 연결, 중복 검사, 입력 검증 기능 추가 - 창고 관리: 우편번호 연결, 중복 검사 기능 강화 - 회사 관리: 우편번호 연결, 중복 검사 로직 구현 - 장비 관리: 불필요한 카테고리 필드 제거, 벤더-모델 관계 정리 - 우편번호 시스템: 검색 다이얼로그 Provider 버그 수정 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -3,31 +3,31 @@ import 'package:flutter/material.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:superport/models/user_model.dart';
|
||||
import 'package:superport/domain/usecases/user/create_user_usecase.dart';
|
||||
import 'package:superport/domain/usecases/user/check_username_availability_usecase.dart';
|
||||
import 'package:superport/domain/repositories/user_repository.dart';
|
||||
import 'package:superport/domain/repositories/company_repository.dart';
|
||||
import 'package:superport/data/datasources/remote/user_remote_datasource.dart';
|
||||
import 'package:superport/core/errors/failures.dart';
|
||||
|
||||
/// 사용자 폼 컨트롤러 (서버 API v0.2.1 대응)
|
||||
/// Clean Architecture Presentation Layer - 필수 필드 검증 강화 및 전화번호 UI 개선
|
||||
class UserFormController extends ChangeNotifier {
|
||||
final CreateUserUseCase _createUserUseCase = GetIt.instance<CreateUserUseCase>();
|
||||
final CheckUsernameAvailabilityUseCase _checkUsernameUseCase = GetIt.instance<CheckUsernameAvailabilityUseCase>();
|
||||
final UserRepository _userRepository = GetIt.instance<UserRepository>();
|
||||
final CompanyRepository _companyRepository = GetIt.instance<CompanyRepository>();
|
||||
final UserRemoteDataSource _userRemoteDataSource = GetIt.instance<UserRemoteDataSource>();
|
||||
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
|
||||
|
||||
// 상태 변수
|
||||
bool _isLoading = false;
|
||||
String? _error;
|
||||
|
||||
// 폼 필드 (서버 API v0.2.1 스키마 대응)
|
||||
// 폼 필드 (백엔드 스키마 완전 일치)
|
||||
bool isEditMode = false;
|
||||
int? userId;
|
||||
String name = ''; // 필수
|
||||
String username = ''; // 필수, 유니크, 3자 이상
|
||||
String email = ''; // 필수, 유니크, 이메일 형식
|
||||
String password = ''; // 필수, 6자 이상
|
||||
String email = ''; // 선택
|
||||
String? phone; // 선택, "010-1234-5678" 형태
|
||||
UserRole role = UserRole.staff; // 필수, 새 권한 시스템
|
||||
int? companiesId; // 필수, 회사 ID (백엔드 요구사항)
|
||||
|
||||
// 전화번호 UI 지원 (드롭다운 + 텍스트 필드)
|
||||
String phonePrefix = '010'; // 010, 02, 031 등
|
||||
@@ -42,17 +42,21 @@ class UserFormController extends ChangeNotifier {
|
||||
'070', // 인터넷전화
|
||||
];
|
||||
|
||||
// 사용자명 중복 확인
|
||||
bool _isCheckingUsername = false;
|
||||
bool? _isUsernameAvailable;
|
||||
String? _lastCheckedUsername;
|
||||
Timer? _usernameCheckTimer;
|
||||
// 이메일 중복 확인 (저장 시점 검사용)
|
||||
bool _isCheckingEmailDuplicate = false;
|
||||
String? _emailDuplicateMessage;
|
||||
|
||||
// 회사 목록 (드롭다운용)
|
||||
Map<int, String> _companies = {};
|
||||
bool _isLoadingCompanies = false;
|
||||
|
||||
// Getters
|
||||
bool get isLoading => _isLoading;
|
||||
String? get error => _error;
|
||||
bool get isCheckingUsername => _isCheckingUsername;
|
||||
bool? get isUsernameAvailable => _isUsernameAvailable;
|
||||
bool get isCheckingEmailDuplicate => _isCheckingEmailDuplicate;
|
||||
String? get emailDuplicateMessage => _emailDuplicateMessage;
|
||||
Map<int, String> get companies => _companies;
|
||||
bool get isLoadingCompanies => _isLoadingCompanies;
|
||||
|
||||
/// 현재 전화번호 (드롭다운 + 텍스트 필드 → 통합 형태)
|
||||
String get combinedPhoneNumber {
|
||||
@@ -63,16 +67,22 @@ class UserFormController extends ChangeNotifier {
|
||||
/// 필수 필드 완성 여부 확인
|
||||
bool get isFormValid {
|
||||
return name.isNotEmpty &&
|
||||
username.isNotEmpty &&
|
||||
email.isNotEmpty &&
|
||||
password.isNotEmpty &&
|
||||
_isUsernameAvailable == true;
|
||||
companiesId != null;
|
||||
}
|
||||
|
||||
UserFormController({this.userId}) {
|
||||
isEditMode = userId != null;
|
||||
if (isEditMode) {
|
||||
_loadUser();
|
||||
// 모든 초기화는 initialize() 메서드에서만 수행
|
||||
}
|
||||
|
||||
/// 비동기 초기화 메서드
|
||||
Future<void> initialize() async {
|
||||
// 항상 회사 목록부터 로드 (사용자 정보에서 회사 검증을 위해)
|
||||
await _loadCompanies();
|
||||
|
||||
// 수정 모드인 경우에만 사용자 정보 로드
|
||||
if (isEditMode && userId != null) {
|
||||
await _loadUser();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,27 +109,29 @@ class UserFormController extends ChangeNotifier {
|
||||
notifyListeners();
|
||||
|
||||
try {
|
||||
final result = await _userRepository.getUserById(userId!);
|
||||
// UserDto에서 직접 companiesId를 가져오기 위해 DataSource 사용
|
||||
final userDto = await _userRemoteDataSource.getUser(userId!);
|
||||
|
||||
// UserDto에서 정보 추출 (null safety 보장)
|
||||
name = userDto.name ?? '';
|
||||
email = userDto.email ?? '';
|
||||
companiesId = userDto.companiesId;
|
||||
|
||||
// 전화번호 UI 분리 (서버: "010-1234-5678" → UI: 접두사 + 번호)
|
||||
if (userDto.phone != null && userDto.phone!.isNotEmpty) {
|
||||
final phoneData = PhoneNumberUtil.splitForUI(userDto.phone);
|
||||
phonePrefix = phoneData['prefix'] ?? '010';
|
||||
phoneNumber = phoneData['number'] ?? '';
|
||||
phone = userDto.phone;
|
||||
}
|
||||
|
||||
// 회사가 목록에 없는 경우 처리
|
||||
if (companiesId != null && !_companies.containsKey(companiesId)) {
|
||||
debugPrint('Warning: 사용자의 회사 ID ($companiesId)가 회사 목록에 없습니다.');
|
||||
// 임시로 "알 수 없는 회사" 항목 추가
|
||||
_companies[companiesId!] = '알 수 없는 회사 (ID: $companiesId)';
|
||||
}
|
||||
|
||||
result.fold(
|
||||
(failure) {
|
||||
_error = _mapFailureToString(failure);
|
||||
},
|
||||
(user) {
|
||||
name = user.name;
|
||||
username = user.username;
|
||||
email = user.email;
|
||||
role = user.role;
|
||||
|
||||
// 전화번호 UI 분리 (서버: "010-1234-5678" → UI: 접두사 + 번호)
|
||||
if (user.phone != null && user.phone!.isNotEmpty) {
|
||||
final phoneData = PhoneNumberUtil.splitForUI(user.phone);
|
||||
phonePrefix = phoneData['prefix'] ?? '010';
|
||||
phoneNumber = phoneData['number'] ?? '';
|
||||
phone = user.phone;
|
||||
}
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
_error = '사용자 정보를 불러올 수 없습니다: ${e.toString()}';
|
||||
} finally {
|
||||
@@ -128,40 +140,87 @@ class UserFormController extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
/// 사용자명 중복 확인 (서버 API v0.2.1 대응)
|
||||
void checkUsernameAvailability(String value) {
|
||||
if (value.isEmpty || value == _lastCheckedUsername || value.length < 3) {
|
||||
return;
|
||||
}
|
||||
/// 회사 목록 로드
|
||||
Future<void> _loadCompanies() async {
|
||||
_isLoadingCompanies = true;
|
||||
notifyListeners();
|
||||
|
||||
// 디바운싱 (500ms 대기)
|
||||
_usernameCheckTimer?.cancel();
|
||||
_usernameCheckTimer = Timer(const Duration(milliseconds: 500), () async {
|
||||
_isCheckingUsername = true;
|
||||
notifyListeners();
|
||||
try {
|
||||
final result = await _companyRepository.getCompanies();
|
||||
|
||||
try {
|
||||
final params = CheckUsernameAvailabilityParams(username: value);
|
||||
final result = await _checkUsernameUseCase(params);
|
||||
|
||||
result.fold(
|
||||
(failure) {
|
||||
_isUsernameAvailable = null;
|
||||
debugPrint('사용자명 중복 확인 실패: ${failure.message}');
|
||||
},
|
||||
(isAvailable) {
|
||||
_isUsernameAvailable = isAvailable;
|
||||
_lastCheckedUsername = value;
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
_isUsernameAvailable = null;
|
||||
debugPrint('사용자명 중복 확인 오류: $e');
|
||||
} finally {
|
||||
_isCheckingUsername = false;
|
||||
notifyListeners();
|
||||
}
|
||||
});
|
||||
result.fold(
|
||||
(failure) {
|
||||
debugPrint('회사 목록 로드 실패: ${failure.message}');
|
||||
},
|
||||
(paginatedResponse) {
|
||||
_companies = {};
|
||||
for (final company in paginatedResponse.items) {
|
||||
if (company.id != null) {
|
||||
_companies[company.id!] = company.name;
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('회사 목록 로드 오류: $e');
|
||||
} finally {
|
||||
_isLoadingCompanies = false;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// 이메일 중복 검사 (저장 시점에만 실행)
|
||||
Future<bool> checkDuplicateEmail(String email) async {
|
||||
if (email.isEmpty) return true;
|
||||
|
||||
_isCheckingEmailDuplicate = true;
|
||||
_emailDuplicateMessage = null;
|
||||
notifyListeners();
|
||||
|
||||
try {
|
||||
// GET /users 엔드포인트를 사용하여 이메일 중복 확인
|
||||
final result = await _userRepository.getUsers();
|
||||
|
||||
return result.fold(
|
||||
(failure) {
|
||||
_emailDuplicateMessage = '중복 검사 중 오류가 발생했습니다';
|
||||
notifyListeners();
|
||||
return false;
|
||||
},
|
||||
(paginatedResponse) {
|
||||
final users = paginatedResponse.items;
|
||||
|
||||
// 수정 모드일 경우 자기 자신 제외
|
||||
final isDuplicate = users.any((user) =>
|
||||
user.email?.toLowerCase() == email.toLowerCase() &&
|
||||
(!isEditMode || user.id != userId)
|
||||
);
|
||||
|
||||
if (isDuplicate) {
|
||||
_emailDuplicateMessage = '이미 사용 중인 이메일입니다';
|
||||
} else {
|
||||
_emailDuplicateMessage = null;
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
return !isDuplicate;
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
_emailDuplicateMessage = '네트워크 오류가 발생했습니다';
|
||||
notifyListeners();
|
||||
return false;
|
||||
} finally {
|
||||
_isCheckingEmailDuplicate = false;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// 중복 검사 메시지 초기화
|
||||
void clearDuplicateMessage() {
|
||||
_emailDuplicateMessage = null;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 사용자 저장 (서버 API v0.2.1 대응)
|
||||
@@ -173,27 +232,13 @@ class UserFormController extends ChangeNotifier {
|
||||
}
|
||||
formKey.currentState?.save();
|
||||
|
||||
// 필수 필드 검증 강화
|
||||
// 필수 필드 검증
|
||||
if (name.trim().isEmpty) {
|
||||
onResult('이름을 입력해주세요.');
|
||||
return;
|
||||
}
|
||||
if (username.trim().isEmpty) {
|
||||
onResult('사용자명을 입력해주세요.');
|
||||
return;
|
||||
}
|
||||
if (email.trim().isEmpty) {
|
||||
onResult('이메일을 입력해주세요.');
|
||||
return;
|
||||
}
|
||||
if (!isEditMode && password.trim().isEmpty) {
|
||||
onResult('비밀번호를 입력해주세요.');
|
||||
return;
|
||||
}
|
||||
|
||||
// 신규 등록 시 사용자명 중복 확인
|
||||
if (!isEditMode && _isUsernameAvailable != true) {
|
||||
onResult('사용자명 중복을 확인해주세요.');
|
||||
if (companiesId == null) {
|
||||
onResult('회사를 선택해주세요.');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -209,17 +254,14 @@ class UserFormController extends ChangeNotifier {
|
||||
// 사용자 수정
|
||||
final userToUpdate = User(
|
||||
id: userId,
|
||||
username: username,
|
||||
email: email,
|
||||
name: name,
|
||||
email: email.isNotEmpty ? email : null,
|
||||
phone: phoneNumber.isEmpty ? null : phoneNumber,
|
||||
role: role,
|
||||
);
|
||||
|
||||
final result = await _userRepository.updateUser(
|
||||
userId!,
|
||||
userToUpdate,
|
||||
newPassword: password.isNotEmpty ? password : null,
|
||||
);
|
||||
|
||||
result.fold(
|
||||
@@ -232,7 +274,7 @@ class UserFormController extends ChangeNotifier {
|
||||
name: name,
|
||||
email: email.isEmpty ? null : email,
|
||||
phone: phoneNumber.isEmpty ? null : phoneNumber,
|
||||
companiesId: 1, // TODO: 실제 회사 선택 기능 필요
|
||||
companiesId: companiesId!, // 선택된 회사 ID 사용
|
||||
);
|
||||
|
||||
final result = await _createUserUseCase(params);
|
||||
@@ -251,10 +293,6 @@ class UserFormController extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
/// 역할 한글명 반환
|
||||
String getRoleDisplayName(UserRole role) {
|
||||
return role.displayName;
|
||||
}
|
||||
|
||||
/// 입력값 유효성 검증 (실시간)
|
||||
Map<String, String?> validateFields() {
|
||||
@@ -264,26 +302,10 @@ class UserFormController extends ChangeNotifier {
|
||||
errors['name'] = '이름을 입력해주세요.';
|
||||
}
|
||||
|
||||
if (username.trim().isEmpty) {
|
||||
errors['username'] = '사용자명을 입력해주세요.';
|
||||
} else if (username.length < 3) {
|
||||
errors['username'] = '사용자명은 3자 이상이어야 합니다.';
|
||||
} else if (!RegExp(r'^[a-zA-Z0-9_]+$').hasMatch(username)) {
|
||||
errors['username'] = '사용자명은 영문, 숫자, 언더스코어만 사용 가능합니다.';
|
||||
}
|
||||
|
||||
if (email.trim().isEmpty) {
|
||||
errors['email'] = '이메일을 입력해주세요.';
|
||||
} else if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(email)) {
|
||||
if (email.isNotEmpty && !RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(email)) {
|
||||
errors['email'] = '올바른 이메일 형식이 아닙니다.';
|
||||
}
|
||||
|
||||
if (!isEditMode && password.trim().isEmpty) {
|
||||
errors['password'] = '비밀번호를 입력해주세요.';
|
||||
} else if (!isEditMode && password.length < 6) {
|
||||
errors['password'] = '비밀번호는 6자 이상이어야 합니다.';
|
||||
}
|
||||
|
||||
if (phoneNumber.isNotEmpty && !RegExp(r'^\d{7,8}$').hasMatch(phoneNumber)) {
|
||||
errors['phone'] = '전화번호는 7-8자리 숫자로 입력해주세요.';
|
||||
}
|
||||
@@ -311,7 +333,6 @@ class UserFormController extends ChangeNotifier {
|
||||
/// 컨트롤러 해제
|
||||
@override
|
||||
void dispose() {
|
||||
_usernameCheckTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ class UserListController extends BaseListController<User> {
|
||||
bool filterItem(User item, String query) {
|
||||
final q = query.toLowerCase();
|
||||
return item.name.toLowerCase().contains(q) ||
|
||||
item.email.toLowerCase().contains(q) ||
|
||||
(item.email?.toLowerCase().contains(q) ?? false) ||
|
||||
item.username.toLowerCase().contains(q);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import 'package:shadcn_ui/shadcn_ui.dart';
|
||||
import 'package:superport/utils/validators.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:superport/screens/user/controllers/user_form_controller.dart';
|
||||
import 'package:superport/models/user_model.dart';
|
||||
import 'package:superport/utils/formatters/korean_phone_formatter.dart';
|
||||
|
||||
// 사용자 등록/수정 화면 (UI만 담당, 상태/로직 분리)
|
||||
@@ -17,24 +16,26 @@ class UserFormScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _UserFormScreenState extends State<UserFormScreen> {
|
||||
final TextEditingController _passwordController = TextEditingController();
|
||||
final TextEditingController _confirmPasswordController = TextEditingController();
|
||||
bool _showPassword = false;
|
||||
bool _showConfirmPassword = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_passwordController.dispose();
|
||||
_confirmPasswordController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ChangeNotifierProvider(
|
||||
create: (_) => UserFormController(
|
||||
userId: widget.userId,
|
||||
),
|
||||
create: (_) {
|
||||
final controller = UserFormController(
|
||||
userId: widget.userId,
|
||||
);
|
||||
// 비동기 초기화 호출
|
||||
if (widget.userId != null) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
controller.initialize();
|
||||
});
|
||||
}
|
||||
return controller;
|
||||
},
|
||||
child: Consumer<UserFormController>(
|
||||
builder: (context, controller, child) {
|
||||
return Scaffold(
|
||||
@@ -60,170 +61,56 @@ class _UserFormScreenState extends State<UserFormScreen> {
|
||||
onSaved: (value) => controller.name = value!,
|
||||
),
|
||||
|
||||
// 사용자명 (신규 등록 시만)
|
||||
if (!controller.isEditMode) ...[
|
||||
_buildTextField(
|
||||
label: '사용자명 *',
|
||||
initialValue: controller.username,
|
||||
hintText: '로그인에 사용할 사용자명 (3자 이상)',
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return '사용자명을 입력해주세요';
|
||||
}
|
||||
if (value.length < 3) {
|
||||
return '사용자명은 3자 이상이어야 합니다';
|
||||
}
|
||||
if (controller.isUsernameAvailable == false) {
|
||||
return '이미 사용 중인 사용자명입니다';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
onChanged: (value) {
|
||||
controller.username = value;
|
||||
controller.checkUsernameAvailability(value);
|
||||
},
|
||||
onSaved: (value) => controller.username = value!,
|
||||
suffixIcon: controller.isCheckingUsername
|
||||
? const SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(12.0),
|
||||
child: ShadProgress(),
|
||||
),
|
||||
)
|
||||
: controller.isUsernameAvailable != null
|
||||
? Icon(
|
||||
controller.isUsernameAvailable!
|
||||
? Icons.check_circle
|
||||
: Icons.cancel,
|
||||
color: controller.isUsernameAvailable!
|
||||
? Colors.green
|
||||
: Colors.red,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
|
||||
// 비밀번호 (*필수)
|
||||
_buildPasswordField(
|
||||
label: '비밀번호 *',
|
||||
controller: _passwordController,
|
||||
hintText: '비밀번호를 입력하세요 (6자 이상)',
|
||||
obscureText: !_showPassword,
|
||||
onToggleVisibility: () {
|
||||
setState(() {
|
||||
_showPassword = !_showPassword;
|
||||
});
|
||||
},
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return '비밀번호를 입력해주세요';
|
||||
}
|
||||
if (value.length < 6) {
|
||||
return '비밀번호는 6자 이상이어야 합니다';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
onSaved: (value) => controller.password = value!,
|
||||
),
|
||||
|
||||
// 비밀번호 확인
|
||||
_buildPasswordField(
|
||||
label: '비밀번호 확인',
|
||||
controller: _confirmPasswordController,
|
||||
hintText: '비밀번호를 다시 입력하세요',
|
||||
obscureText: !_showConfirmPassword,
|
||||
onToggleVisibility: () {
|
||||
setState(() {
|
||||
_showConfirmPassword = !_showConfirmPassword;
|
||||
});
|
||||
},
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return '비밀번호를 다시 입력해주세요';
|
||||
}
|
||||
if (value != _passwordController.text) {
|
||||
return '비밀번호가 일치하지 않습니다';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
],
|
||||
|
||||
// 수정 모드에서 비밀번호 변경 (선택사항)
|
||||
if (controller.isEditMode) ...[
|
||||
ShadAccordion<int>(
|
||||
children: [
|
||||
ShadAccordionItem(
|
||||
value: 1,
|
||||
title: const Text('비밀번호 변경'),
|
||||
child: Column(
|
||||
children: [
|
||||
_buildPasswordField(
|
||||
label: '새 비밀번호',
|
||||
controller: _passwordController,
|
||||
hintText: '변경할 경우만 입력하세요',
|
||||
obscureText: !_showPassword,
|
||||
onToggleVisibility: () {
|
||||
setState(() {
|
||||
_showPassword = !_showPassword;
|
||||
});
|
||||
},
|
||||
validator: (value) {
|
||||
if (value != null && value.isNotEmpty && value.length < 6) {
|
||||
return '비밀번호는 6자 이상이어야 합니다';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
onSaved: (value) => controller.password = value ?? '',
|
||||
),
|
||||
|
||||
_buildPasswordField(
|
||||
label: '새 비밀번호 확인',
|
||||
controller: _confirmPasswordController,
|
||||
hintText: '비밀번호를 다시 입력하세요',
|
||||
obscureText: !_showConfirmPassword,
|
||||
onToggleVisibility: () {
|
||||
setState(() {
|
||||
_showConfirmPassword = !_showConfirmPassword;
|
||||
});
|
||||
},
|
||||
validator: (value) {
|
||||
if (_passwordController.text.isNotEmpty && value != _passwordController.text) {
|
||||
return '비밀번호가 일치하지 않습니다';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
|
||||
|
||||
// 이메일 (*필수)
|
||||
// 이메일 (선택)
|
||||
_buildTextField(
|
||||
label: '이메일 *',
|
||||
label: '이메일',
|
||||
initialValue: controller.email,
|
||||
hintText: '이메일을 입력하세요',
|
||||
hintText: '이메일을 입력하세요 (선택사항)',
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return '이메일을 입력해주세요';
|
||||
if (value != null && value.isNotEmpty) {
|
||||
return validateEmail(value);
|
||||
}
|
||||
return validateEmail(value);
|
||||
return null;
|
||||
},
|
||||
onSaved: (value) => controller.email = value!,
|
||||
onSaved: (value) => controller.email = value ?? '',
|
||||
),
|
||||
|
||||
// 전화번호 (선택)
|
||||
_buildPhoneNumberSection(controller),
|
||||
|
||||
// 권한 (*필수)
|
||||
_buildRoleDropdown(controller),
|
||||
// 회사 선택 (*필수)
|
||||
_buildCompanyDropdown(controller),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// 중복 검사 상태 메시지 영역 (고정 높이)
|
||||
SizedBox(
|
||||
height: 40,
|
||||
child: Center(
|
||||
child: controller.isCheckingEmailDuplicate
|
||||
? const Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
ShadProgress(),
|
||||
SizedBox(width: 8),
|
||||
Text('중복 검사 중...'),
|
||||
],
|
||||
)
|
||||
: controller.emailDuplicateMessage != null
|
||||
? Text(
|
||||
controller.emailDuplicateMessage!,
|
||||
style: const TextStyle(
|
||||
color: Colors.red,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
)
|
||||
: Container(),
|
||||
),
|
||||
),
|
||||
|
||||
// 오류 메시지 표시
|
||||
if (controller.error != null)
|
||||
Padding(
|
||||
@@ -237,7 +124,7 @@ class _UserFormScreenState extends State<UserFormScreen> {
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: ShadButton(
|
||||
onPressed: controller.isLoading
|
||||
onPressed: controller.isLoading || controller.isCheckingEmailDuplicate
|
||||
? null
|
||||
: () => _onSaveUser(controller),
|
||||
size: ShadButtonSize.lg,
|
||||
@@ -267,7 +154,7 @@ class _UserFormScreenState extends State<UserFormScreen> {
|
||||
void Function(String)? onChanged,
|
||||
Widget? suffixIcon,
|
||||
}) {
|
||||
final controller = TextEditingController(text: initialValue);
|
||||
final controller = TextEditingController(text: initialValue.isNotEmpty ? initialValue : '');
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 16.0),
|
||||
child: Column(
|
||||
@@ -289,34 +176,6 @@ class _UserFormScreenState extends State<UserFormScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
// 비밀번호 필드 위젯
|
||||
Widget _buildPasswordField({
|
||||
required String label,
|
||||
required TextEditingController controller,
|
||||
required String hintText,
|
||||
required bool obscureText,
|
||||
required VoidCallback onToggleVisibility,
|
||||
String? Function(String?)? validator,
|
||||
void Function(String?)? onSaved,
|
||||
}) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(label, style: const TextStyle(fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 4),
|
||||
ShadInputFormField(
|
||||
controller: controller,
|
||||
obscureText: obscureText,
|
||||
placeholder: Text(hintText),
|
||||
validator: validator,
|
||||
onSaved: onSaved,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 전화번호 입력 섹션 (통합 입력 필드)
|
||||
Widget _buildPhoneNumberSection(UserFormController controller) {
|
||||
@@ -328,7 +187,7 @@ class _UserFormScreenState extends State<UserFormScreen> {
|
||||
const Text('전화번호', style: TextStyle(fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 4),
|
||||
ShadInputFormField(
|
||||
controller: TextEditingController(text: controller.combinedPhoneNumber),
|
||||
controller: TextEditingController(text: controller.combinedPhoneNumber ?? ''),
|
||||
placeholder: const Text('010-1234-5678'),
|
||||
keyboardType: TextInputType.phone,
|
||||
inputFormatters: [
|
||||
@@ -354,48 +213,64 @@ class _UserFormScreenState extends State<UserFormScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
// 권한 드롭다운 (새 UserRole 시스템)
|
||||
Widget _buildRoleDropdown(UserFormController controller) {
|
||||
// 회사 선택 드롭다운
|
||||
Widget _buildCompanyDropdown(UserFormController controller) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text('권한 *', style: TextStyle(fontWeight: FontWeight.bold)),
|
||||
const Text('회사 *', style: TextStyle(fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 4),
|
||||
ShadSelect<UserRole>(
|
||||
selectedOptionBuilder: (context, value) => Text(value.displayName ?? ''),
|
||||
placeholder: const Text('권한을 선택하세요'),
|
||||
options: UserRole.values.map((role) {
|
||||
return ShadOption(
|
||||
value: role,
|
||||
child: Text(role.displayName),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (value) {
|
||||
if (value != null) {
|
||||
controller.role = value;
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'권한 설명:\n'
|
||||
'• 관리자: 전체 시스템 관리 및 모든 기능 접근\n'
|
||||
'• 매니저: 중간 관리 기능 및 승인 권한\n'
|
||||
'• 직원: 기본 사용 기능만 접근 가능',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
),
|
||||
controller.isLoadingCompanies
|
||||
? const ShadProgress()
|
||||
: ShadSelect<int?>(
|
||||
selectedOptionBuilder: (context, value) {
|
||||
if (value == null) {
|
||||
return const Text('회사를 선택하세요');
|
||||
}
|
||||
final companyName = controller.companies[value];
|
||||
return Text(companyName ?? '알 수 없는 회사 (ID: $value)');
|
||||
},
|
||||
placeholder: const Text('회사를 선택하세요'),
|
||||
initialValue: controller.companiesId,
|
||||
options: controller.companies.entries.map((entry) {
|
||||
return ShadOption(
|
||||
value: entry.key,
|
||||
child: Text(entry.value),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (value) {
|
||||
if (value != null) {
|
||||
controller.companiesId = value;
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// 저장 버튼 클릭 시 사용자 저장
|
||||
void _onSaveUser(UserFormController controller) async {
|
||||
// 먼저 폼 유효성 검사
|
||||
if (controller.formKey.currentState?.validate() != true) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 폼 데이터 저장
|
||||
controller.formKey.currentState?.save();
|
||||
|
||||
// 이메일 중복 검사 (저장 시점)
|
||||
final emailIsUnique = await controller.checkDuplicateEmail(controller.email);
|
||||
|
||||
if (!emailIsUnique) {
|
||||
// 중복이 발견되면 저장하지 않음
|
||||
return;
|
||||
}
|
||||
|
||||
// 이메일 중복이 없으면 저장 진행
|
||||
await controller.saveUser((error) {
|
||||
if (error != null) {
|
||||
ShadToaster.of(context).show(
|
||||
|
||||
@@ -312,7 +312,7 @@ class _UserListState extends State<UserList> {
|
||||
),
|
||||
),
|
||||
Text(
|
||||
user.email,
|
||||
user.email ?? '',
|
||||
style: ShadcnTheme.bodyMedium,
|
||||
),
|
||||
Text(
|
||||
|
||||
Reference in New Issue
Block a user