결재 템플릿 단계 적용 구현

- ApprovalTemplate 엔티티·DTO·원격 리포지토리 추가
- ApprovalController에 템플릿 로딩/적용 상태와 assignSteps 호출 연동
- ApprovalPage 단계 탭에 템플릿 선택 UI 및 적용 확인 다이얼로그 구현
- 템플릿 적용 단위 테스트와 IMPLEMENTATION_TASKS 현황 갱신
This commit is contained in:
JiWoong Sul
2025-09-25 00:21:12 +09:00
parent b6e50464d2
commit c3010965ad
63 changed files with 10179 additions and 1436 deletions

View File

@@ -2,6 +2,10 @@ import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport_v2/core/constants/app_sections.dart';
import 'package:superport_v2/widgets/app_layout.dart';
import 'package:superport_v2/widgets/components/filter_bar.dart';
import '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
import '../../domain/entities/customer.dart';
@@ -137,173 +141,145 @@ class _CustomerEnabledPageState extends State<_CustomerEnabledPage> {
? false
: (result.page * result.pageSize) < result.total;
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
final showReset = _searchController.text.isNotEmpty ||
_controller.typeFilter != CustomerTypeFilter.all ||
_controller.statusFilter != CustomerStatusFilter.all;
return AppLayout(
title: '회사(고객사) 관리',
subtitle: '고객사 기본 정보와 연락처, 주소를 관리합니다.',
breadcrumbs: const [
AppBreadcrumbItem(label: '대시보드', path: dashboardRoutePath),
AppBreadcrumbItem(label: '마스터', path: '/masters/customers'),
AppBreadcrumbItem(label: '고객사'),
],
actions: [
ShadButton(
leading: const Icon(LucideIcons.plus, size: 16),
onPressed: _controller.isSubmitting
? null
: () => _openCustomerForm(context),
child: const Text('신규 등록'),
),
],
toolbar: FilterBar(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('회사(고객사) 관리', style: theme.textTheme.h2),
const SizedBox(height: 6),
Text(
'고객사 기본 정보와 연락처, 주소를 관리합니다.',
style: theme.textTheme.muted,
),
],
),
),
const SizedBox(width: 16),
ShadButton(
onPressed: _controller.isSubmitting
? null
: () => _openCustomerForm(context),
child: const Text('신규 등록'),
),
],
),
const SizedBox(height: 24),
ShadCard(
title: Text('검색 및 필터', style: theme.textTheme.h3),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
spacing: 16,
runSpacing: 16,
children: [
SizedBox(
width: 260,
child: ShadInput(
controller: _searchController,
focusNode: _searchFocus,
placeholder: const Text('고객사코드, 고객사명 검색'),
leading: const Icon(LucideIcons.search, size: 16),
onSubmitted: (_) => _applyFilters(),
),
),
SizedBox(
width: 200,
child: ShadSelect<CustomerTypeFilter>(
key: ValueKey(_controller.typeFilter),
initialValue: _controller.typeFilter,
selectedOptionBuilder: (context, value) =>
Text(_typeLabel(value)),
onChanged: (value) {
if (value == null) return;
_controller.updateTypeFilter(value);
},
options: CustomerTypeFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_typeLabel(filter)),
),
)
.toList(),
),
),
SizedBox(
width: 200,
child: ShadSelect<CustomerStatusFilter>(
key: ValueKey(_controller.statusFilter),
initialValue: _controller.statusFilter,
selectedOptionBuilder: (context, value) =>
Text(_statusLabel(value)),
onChanged: (value) {
if (value == null) return;
_controller.updateStatusFilter(value);
},
options: CustomerStatusFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_statusLabel(filter)),
),
)
.toList(),
),
),
ShadButton.outline(
onPressed: _controller.isLoading
? null
: _applyFilters,
child: const Text('검색 적용'),
),
if (_searchController.text.isNotEmpty ||
_controller.typeFilter != CustomerTypeFilter.all ||
_controller.statusFilter !=
CustomerStatusFilter.all)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateTypeFilter(
CustomerTypeFilter.all,
);
_controller.updateStatusFilter(
CustomerStatusFilter.all,
);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
),
],
SizedBox(
width: 260,
child: ShadInput(
controller: _searchController,
focusNode: _searchFocus,
placeholder: const Text('고객사코드, 고객사명 검색'),
leading: const Icon(LucideIcons.search, size: 16),
onSubmitted: (_) => _applyFilters(),
),
),
const SizedBox(height: 24),
ShadCard(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('고객사 목록', style: theme.textTheme.h3),
Text('$totalCount건', style: theme.textTheme.muted),
],
),
footer: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'페이지 $currentPage / $totalPages',
style: theme.textTheme.small,
),
Row(
children: [
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || currentPage <= 1
? null
: () => _controller.fetch(page: currentPage - 1),
child: const Text('이전'),
SizedBox(
width: 200,
child: ShadSelect<CustomerTypeFilter>(
key: ValueKey(_controller.typeFilter),
initialValue: _controller.typeFilter,
selectedOptionBuilder: (context, value) =>
Text(_typeLabel(value)),
onChanged: (value) {
if (value == null) return;
_controller.updateTypeFilter(value);
},
options: CustomerTypeFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_typeLabel(filter)),
),
const SizedBox(width: 8),
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || !hasNext
? null
: () => _controller.fetch(page: currentPage + 1),
child: const Text('다음'),
),
],
),
],
),
child: _controller.isLoading
? const Padding(
padding: EdgeInsets.all(48),
child: Center(child: CircularProgressIndicator()),
)
: customers.isEmpty
.toList(),
),
),
SizedBox(
width: 200,
child: ShadSelect<CustomerStatusFilter>(
key: ValueKey(_controller.statusFilter),
initialValue: _controller.statusFilter,
selectedOptionBuilder: (context, value) =>
Text(_statusLabel(value)),
onChanged: (value) {
if (value == null) return;
_controller.updateStatusFilter(value);
},
options: CustomerStatusFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_statusLabel(filter)),
),
)
.toList(),
),
),
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
if (showReset)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateTypeFilter(CustomerTypeFilter.all);
_controller.updateStatusFilter(
CustomerStatusFilter.all,
);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
),
child: ShadCard(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('고객사 목록', style: theme.textTheme.h3),
Text('$totalCount건', style: theme.textTheme.muted),
],
),
footer: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'페이지 $currentPage / $totalPages',
style: theme.textTheme.small,
),
Row(
children: [
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || currentPage <= 1
? null
: () => _controller.fetch(page: currentPage - 1),
child: const Text('이전'),
),
const SizedBox(width: 8),
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || !hasNext
? null
: () => _controller.fetch(page: currentPage + 1),
child: const Text('다음'),
),
],
),
],
),
child: _controller.isLoading
? const Padding(
padding: EdgeInsets.all(48),
child: Center(child: CircularProgressIndicator()),
)
: customers.isEmpty
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
@@ -315,10 +291,8 @@ class _CustomerEnabledPageState extends State<_CustomerEnabledPage> {
customers: customers,
onEdit: _controller.isSubmitting
? null
: (customer) => _openCustomerForm(
context,
customer: customer,
),
: (customer) =>
_openCustomerForm(context, customer: customer),
onDelete: _controller.isSubmitting
? null
: _confirmDelete,
@@ -326,8 +300,6 @@ class _CustomerEnabledPageState extends State<_CustomerEnabledPage> {
? null
: _restoreCustomer,
),
),
],
),
);
},

View File

@@ -6,6 +6,7 @@ class GroupDto {
GroupDto({
this.id,
required this.groupName,
this.description,
this.isDefault = false,
this.isActive = true,
this.isDeleted = false,
@@ -16,6 +17,7 @@ class GroupDto {
final int? id;
final String groupName;
final String? description;
final bool isDefault;
final bool isActive;
final bool isDeleted;
@@ -27,6 +29,7 @@ class GroupDto {
return GroupDto(
id: json['id'] as int?,
groupName: json['group_name'] as String,
description: json['description'] as String?,
isDefault: (json['is_default'] as bool?) ?? false,
isActive: (json['is_active'] as bool?) ?? true,
isDeleted: (json['is_deleted'] as bool?) ?? false,
@@ -39,6 +42,7 @@ class GroupDto {
Group toEntity() => Group(
id: id,
groupName: groupName,
description: description,
isDefault: isDefault,
isActive: isActive,
isDeleted: isDeleted,

View File

@@ -18,6 +18,7 @@ class GroupRepositoryRemote implements GroupRepository {
int page = 1,
int pageSize = 20,
String? query,
bool? isDefault,
bool? isActive,
}) async {
final response = await _api.get<Map<String, dynamic>>(
@@ -26,10 +27,48 @@ class GroupRepositoryRemote implements GroupRepository {
'page': page,
'page_size': pageSize,
if (query != null && query.isNotEmpty) 'q': query,
if (isDefault != null) 'is_default': isDefault,
if (isActive != null) 'is_active': isActive,
},
options: Options(responseType: ResponseType.json),
);
return GroupDto.parsePaginated(response.data ?? const {});
}
@override
Future<Group> create(GroupInput input) async {
final response = await _api.post<Map<String, dynamic>>(
_basePath,
data: input.toPayload(),
options: Options(responseType: ResponseType.json),
);
final data = (response.data?['data'] as Map<String, dynamic>?) ?? {};
return GroupDto.fromJson(data).toEntity();
}
@override
Future<Group> update(int id, GroupInput input) async {
final response = await _api.patch<Map<String, dynamic>>(
'$_basePath/$id',
data: input.toPayload(),
options: Options(responseType: ResponseType.json),
);
final data = (response.data?['data'] as Map<String, dynamic>?) ?? {};
return GroupDto.fromJson(data).toEntity();
}
@override
Future<void> delete(int id) async {
await _api.delete<void>('$_basePath/$id');
}
@override
Future<Group> restore(int id) async {
final response = await _api.post<Map<String, dynamic>>(
'$_basePath/$id/restore',
options: Options(responseType: ResponseType.json),
);
final data = (response.data?['data'] as Map<String, dynamic>?) ?? {};
return GroupDto.fromJson(data).toEntity();
}
}

View File

@@ -1,7 +1,12 @@
/// 그룹(권한 집합) 엔티티
///
/// - SRP: 그룹의 속성 정보만 표현한다.
/// - presentation/data 레이어의 구현 세부사항을 포함하지 않는다.
class Group {
Group({
this.id,
required this.groupName,
this.description,
this.isDefault = false,
this.isActive = true,
this.isDeleted = false,
@@ -10,18 +15,35 @@ class Group {
this.updatedAt,
});
/// PK (null 이면 신규 생성)
final int? id;
/// 그룹명
final String groupName;
/// 그룹 설명(선택)
final String? description;
/// 기본 그룹 여부
final bool isDefault;
/// 사용 여부
final bool isActive;
/// 삭제 여부(소프트 삭제)
final bool isDeleted;
/// 비고 메모
final String? note;
/// 타임스탬프
final DateTime? createdAt;
final DateTime? updatedAt;
Group copyWith({
int? id,
String? groupName,
String? description,
bool? isDefault,
bool? isActive,
bool? isDeleted,
@@ -32,6 +54,7 @@ class Group {
return Group(
id: id ?? this.id,
groupName: groupName ?? this.groupName,
description: description ?? this.description,
isDefault: isDefault ?? this.isDefault,
isActive: isActive ?? this.isActive,
isDeleted: isDeleted ?? this.isDeleted,
@@ -41,3 +64,30 @@ class Group {
);
}
}
/// 그룹 생성/수정 입력 모델
class GroupInput {
GroupInput({
required this.groupName,
this.description,
this.isDefault = false,
this.isActive = true,
this.note,
});
final String groupName;
final String? description;
final bool isDefault;
final bool isActive;
final String? note;
Map<String, dynamic> toPayload() {
return {
'group_name': groupName,
'description': description,
'is_default': isDefault,
'is_active': isActive,
'note': note,
};
}
}

View File

@@ -3,10 +3,24 @@ import 'package:superport_v2/core/common/models/paginated_result.dart';
import '../entities/group.dart';
abstract class GroupRepository {
/// 그룹 목록 조회
Future<PaginatedResult<Group>> list({
int page = 1,
int pageSize = 20,
String? query,
bool? isDefault,
bool? isActive,
});
/// 그룹 신규 등록
Future<Group> create(GroupInput input);
/// 그룹 정보 수정
Future<Group> update(int id, GroupInput input);
/// 그룹 삭제(소프트)
Future<void> delete(int id);
/// 그룹 복구
Future<Group> restore(int id);
}

View File

@@ -0,0 +1,152 @@
import 'package:flutter/foundation.dart';
import 'package:superport_v2/core/common/models/paginated_result.dart';
import '../../domain/entities/group.dart';
import '../../domain/repositories/group_repository.dart';
enum GroupDefaultFilter { all, defaultOnly, nonDefault }
enum GroupStatusFilter { all, activeOnly, inactiveOnly }
/// 그룹 마스터 화면 상태 컨트롤러
///
/// - 목록 조회 및 필터, 페이징 상태를 담당한다.
/// - 생성/수정/삭제/복구 요청을 래핑하여 UI와 통신한다.
class GroupController extends ChangeNotifier {
GroupController({required GroupRepository repository})
: _repository = repository;
final GroupRepository _repository;
PaginatedResult<Group>? _result;
bool _isLoading = false;
bool _isSubmitting = false;
String _query = '';
GroupDefaultFilter _defaultFilter = GroupDefaultFilter.all;
GroupStatusFilter _statusFilter = GroupStatusFilter.all;
String? _errorMessage;
PaginatedResult<Group>? get result => _result;
bool get isLoading => _isLoading;
bool get isSubmitting => _isSubmitting;
String get query => _query;
GroupDefaultFilter get defaultFilter => _defaultFilter;
GroupStatusFilter get statusFilter => _statusFilter;
String? get errorMessage => _errorMessage;
Future<void> fetch({int page = 1}) async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
try {
final isDefault = switch (_defaultFilter) {
GroupDefaultFilter.all => null,
GroupDefaultFilter.defaultOnly => true,
GroupDefaultFilter.nonDefault => false,
};
final isActive = switch (_statusFilter) {
GroupStatusFilter.all => null,
GroupStatusFilter.activeOnly => true,
GroupStatusFilter.inactiveOnly => false,
};
final response = await _repository.list(
page: page,
pageSize: _result?.pageSize ?? 20,
query: _query.isEmpty ? null : _query,
isDefault: isDefault,
isActive: isActive,
);
_result = response;
} catch (e) {
_errorMessage = e.toString();
} finally {
_isLoading = false;
notifyListeners();
}
}
void updateQuery(String value) {
_query = value;
notifyListeners();
}
void updateDefaultFilter(GroupDefaultFilter filter) {
_defaultFilter = filter;
notifyListeners();
}
void updateStatusFilter(GroupStatusFilter filter) {
_statusFilter = filter;
notifyListeners();
}
Future<Group?> create(GroupInput input) async {
_setSubmitting(true);
try {
final created = await _repository.create(input);
await fetch(page: 1);
return created;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return null;
} finally {
_setSubmitting(false);
}
}
Future<Group?> update(int id, GroupInput input) async {
_setSubmitting(true);
try {
final updated = await _repository.update(id, input);
await fetch(page: _result?.page ?? 1);
return updated;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return null;
} finally {
_setSubmitting(false);
}
}
Future<bool> delete(int id) async {
_setSubmitting(true);
try {
await _repository.delete(id);
await fetch(page: _result?.page ?? 1);
return true;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return false;
} finally {
_setSubmitting(false);
}
}
Future<Group?> restore(int id) async {
_setSubmitting(true);
try {
final restored = await _repository.restore(id);
await fetch(page: _result?.page ?? 1);
return restored;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return null;
} finally {
_setSubmitting(false);
}
}
void clearError() {
_errorMessage = null;
notifyListeners();
}
void _setSubmitting(bool value) {
_isSubmitting = value;
notifyListeners();
}
}

View File

@@ -1,40 +1,726 @@
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport_v2/core/constants/app_sections.dart';
import 'package:superport_v2/widgets/app_layout.dart';
import 'package:superport_v2/widgets/components/filter_bar.dart';
import '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
import '../../domain/entities/group.dart';
import '../../domain/repositories/group_repository.dart';
import '../controllers/group_controller.dart';
class GroupPage extends StatelessWidget {
const GroupPage({super.key});
@override
Widget build(BuildContext context) {
return const SpecPage(
title: '그룹 관리',
summary: '권한 그룹 정의와 기본여부 설정을 제공합니다.',
sections: [
SpecSection(
title: '입력 폼',
items: [
'그룹명 [Text]',
'그룹설명 [Text]',
'기본여부 [Switch]',
'사용여부 [Switch]',
'비고 [Text]',
final enabled = Environment.flag('FEATURE_GROUPS_ENABLED');
if (!enabled) {
return SpecPage(
title: '그룹 관리',
summary: '권한 그룹 정의와 기본 여부 설정을 제공합니다.',
trailing: ShadBadge(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(LucideIcons.info, size: 14),
const SizedBox(width: 6),
Text('비활성화 (백엔드 준비 중)'),
],
),
),
),
sections: const [
SpecSection(
title: '입력 폼',
items: [
'그룹명 [Text]',
'설명 [Textarea]',
'기본여부 [Switch]',
'사용여부 [Switch]',
'비고 [Textarea]',
],
),
SpecSection(
title: '수정 폼',
items: ['그룹명 [ReadOnly]', '생성일시 [ReadOnly]'],
),
SpecSection(
title: '테이블 리스트',
description: '1행 예시',
table: SpecTable(
columns: ['번호', '그룹명', '설명', '기본여부', '사용여부', '비고', '변경일시'],
rows: [
['1', '관리자', '시스템 전체 권한', 'Y', 'Y', '-', '2024-03-01 10:00'],
],
),
),
],
);
}
return const _GroupEnabledPage();
}
}
class _GroupEnabledPage extends StatefulWidget {
const _GroupEnabledPage();
@override
State<_GroupEnabledPage> createState() => _GroupEnabledPageState();
}
class _GroupEnabledPageState extends State<_GroupEnabledPage> {
late final GroupController _controller;
final TextEditingController _searchController = TextEditingController();
final FocusNode _searchFocus = FocusNode();
final DateFormat _dateFormat = DateFormat('yyyy-MM-dd HH:mm');
String? _lastError;
@override
void initState() {
super.initState();
_controller = GroupController(repository: GetIt.I<GroupRepository>())
..addListener(_handleControllerUpdate);
WidgetsBinding.instance.addPostFrameCallback((_) {
_controller.fetch();
});
}
void _handleControllerUpdate() {
final error = _controller.errorMessage;
if (error != null && error != _lastError && mounted) {
_lastError = error;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(error)));
_controller.clearError();
}
}
@override
void dispose() {
_controller.removeListener(_handleControllerUpdate);
_controller.dispose();
_searchController.dispose();
_searchFocus.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
return AnimatedBuilder(
animation: _controller,
builder: (context, _) {
final result = _controller.result;
final groups = result?.items ?? const <Group>[];
final totalCount = result?.total ?? 0;
final currentPage = result?.page ?? 1;
final totalPages = result == null || result.pageSize == 0
? 1
: (result.total / result.pageSize).ceil().clamp(1, 9999);
final hasNext = result == null
? false
: (result.page * result.pageSize) < result.total;
final showReset = _searchController.text.isNotEmpty ||
_controller.defaultFilter != GroupDefaultFilter.all ||
_controller.statusFilter != GroupStatusFilter.all;
return AppLayout(
title: '그룹 관리',
subtitle: '권한 그룹 정의와 기본 여부, 사용 상태를 관리합니다.',
breadcrumbs: const [
AppBreadcrumbItem(label: '대시보드', path: dashboardRoutePath),
AppBreadcrumbItem(label: '마스터', path: '/masters/groups'),
AppBreadcrumbItem(label: '그룹'),
],
),
SpecSection(
title: '수정 폼',
items: ['그룹명 [ReadOnly]', '생성일시 [ReadOnly]'],
),
SpecSection(
title: '테이블 리스트',
description: '1행 예시',
table: SpecTable(
columns: ['번호', '그룹명', '설명', '기본여부', '사용여부', '비고', '변경일시'],
rows: [
['1', '관리자', '시스템 전체 권한', 'Y', 'Y', '-', '2024-03-01 10:00'],
actions: [
ShadButton(
leading: const Icon(LucideIcons.plus, size: 16),
onPressed:
_controller.isSubmitting ? null : () => _openGroupForm(context),
child: const Text('신규 등록'),
),
],
toolbar: FilterBar(
children: [
SizedBox(
width: 260,
child: ShadInput(
controller: _searchController,
focusNode: _searchFocus,
placeholder: const Text('그룹명, 설명 검색'),
leading: const Icon(LucideIcons.search, size: 16),
onSubmitted: (_) => _applyFilters(),
),
),
SizedBox(
width: 200,
child: ShadSelect<GroupDefaultFilter>(
key: ValueKey(_controller.defaultFilter),
initialValue: _controller.defaultFilter,
selectedOptionBuilder: (context, filter) =>
Text(_defaultLabel(filter)),
onChanged: (value) {
if (value == null) return;
_controller.updateDefaultFilter(value);
_controller.fetch(page: 1);
},
options: GroupDefaultFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_defaultLabel(filter)),
),
)
.toList(),
),
),
SizedBox(
width: 200,
child: ShadSelect<GroupStatusFilter>(
key: ValueKey(_controller.statusFilter),
initialValue: _controller.statusFilter,
selectedOptionBuilder: (context, filter) =>
Text(_statusLabel(filter)),
onChanged: (value) {
if (value == null) return;
_controller.updateStatusFilter(value);
_controller.fetch(page: 1);
},
options: GroupStatusFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_statusLabel(filter)),
),
)
.toList(),
),
),
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
if (showReset)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateDefaultFilter(
GroupDefaultFilter.all,
);
_controller.updateStatusFilter(
GroupStatusFilter.all,
);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
),
child: ShadCard(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('그룹 목록', style: theme.textTheme.h3),
Text('$totalCount건', style: theme.textTheme.muted),
],
),
footer: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'페이지 $currentPage / $totalPages',
style: theme.textTheme.small,
),
Row(
children: [
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || currentPage <= 1
? null
: () => _controller.fetch(page: currentPage - 1),
child: const Text('이전'),
),
const SizedBox(width: 8),
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || !hasNext
? null
: () => _controller.fetch(page: currentPage + 1),
child: const Text('다음'),
),
],
),
],
),
child: _controller.isLoading
? const Padding(
padding: EdgeInsets.all(48),
child: Center(child: CircularProgressIndicator()),
)
: groups.isEmpty
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
'조건에 맞는 그룹이 없습니다.',
style: theme.textTheme.muted,
),
)
: _GroupTable(
groups: groups,
dateFormat: _dateFormat,
onEdit: _controller.isSubmitting
? null
: (group) => _openGroupForm(context, group: group),
onDelete: _controller.isSubmitting
? null
: _confirmDelete,
onRestore: _controller.isSubmitting
? null
: _restoreGroup,
),
),
);
},
);
}
void _applyFilters() {
_controller.updateQuery(_searchController.text.trim());
_controller.fetch(page: 1);
}
String _defaultLabel(GroupDefaultFilter filter) {
switch (filter) {
case GroupDefaultFilter.all:
return '전체(기본/일반)';
case GroupDefaultFilter.defaultOnly:
return '기본 그룹만';
case GroupDefaultFilter.nonDefault:
return '일반 그룹만';
}
}
String _statusLabel(GroupStatusFilter filter) {
switch (filter) {
case GroupStatusFilter.all:
return '전체(사용/미사용)';
case GroupStatusFilter.activeOnly:
return '사용중';
case GroupStatusFilter.inactiveOnly:
return '미사용';
}
}
Future<void> _openGroupForm(BuildContext context, {Group? group}) async {
final existingGroup = group;
final isEdit = existingGroup != null;
final groupId = existingGroup?.id;
if (isEdit && groupId == null) {
_showSnack('ID 정보가 없어 수정할 수 없습니다.');
return;
}
final nameController = TextEditingController(
text: existingGroup?.groupName ?? '',
);
final descriptionController = TextEditingController(
text: existingGroup?.description ?? '',
);
final noteController = TextEditingController(
text: existingGroup?.note ?? '',
);
final isDefaultNotifier = ValueNotifier<bool>(
existingGroup?.isDefault ?? false,
);
final isActiveNotifier = ValueNotifier<bool>(
existingGroup?.isActive ?? true,
);
final saving = ValueNotifier<bool>(false);
final nameError = ValueNotifier<String?>(null);
await showDialog<bool>(
context: context,
builder: (dialogContext) {
final theme = ShadTheme.of(dialogContext);
final materialTheme = Theme.of(dialogContext);
final navigator = Navigator.of(dialogContext);
return Dialog(
insetPadding: const EdgeInsets.all(24),
clipBehavior: Clip.antiAlias,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 540),
child: ShadCard(
title: Text(
isEdit ? '그룹 수정' : '그룹 등록',
style: theme.textTheme.h3,
),
description: Text(
'그룹 정보를 ${isEdit ? '수정' : '입력'}하세요.',
style: theme.textTheme.muted,
),
footer: ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (_, isSaving, __) {
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ShadButton.ghost(
onPressed: isSaving ? null : () => navigator.pop(false),
child: const Text('취소'),
),
const SizedBox(width: 12),
ShadButton(
onPressed: isSaving
? null
: () async {
final name = nameController.text.trim();
final description = descriptionController.text
.trim();
final note = noteController.text.trim();
nameError.value = name.isEmpty
? '그룹명을 입력하세요.'
: null;
if (nameError.value != null) {
return;
}
saving.value = true;
final input = GroupInput(
groupName: name,
description: description.isEmpty
? null
: description,
isDefault: isDefaultNotifier.value,
isActive: isActiveNotifier.value,
note: note.isEmpty ? null : note,
);
final response = isEdit
? await _controller.update(groupId!, input)
: await _controller.create(input);
saving.value = false;
if (response != null) {
if (!navigator.mounted) {
return;
}
if (mounted) {
_showSnack(
isEdit ? '그룹을 수정했습니다.' : '그룹을 등록했습니다.',
);
}
navigator.pop(true);
}
},
child: Text(isEdit ? '저장' : '등록'),
),
],
);
},
),
child: SizedBox(
width: double.infinity,
child: SingleChildScrollView(
padding: const EdgeInsets.only(right: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
ValueListenableBuilder<String?>(
valueListenable: nameError,
builder: (_, errorText, __) {
return _FormField(
label: '그룹명',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ShadInput(
controller: nameController,
readOnly: isEdit,
onChanged: (_) {
if (nameController.text.trim().isNotEmpty) {
nameError.value = null;
}
},
),
if (errorText != null)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
errorText,
style: theme.textTheme.small.copyWith(
color: materialTheme.colorScheme.error,
),
),
),
],
),
);
},
),
const SizedBox(height: 16),
_FormField(
label: '설명',
child: ShadTextarea(controller: descriptionController),
),
const SizedBox(height: 16),
ValueListenableBuilder<bool>(
valueListenable: isDefaultNotifier,
builder: (_, value, __) {
return _FormField(
label: '기본여부',
child: Row(
children: [
ShadSwitch(
value: value,
onChanged: saving.value
? null
: (next) =>
isDefaultNotifier.value = next,
),
const SizedBox(width: 8),
Text(value ? '기본 그룹' : '일반 그룹'),
],
),
);
},
),
const SizedBox(height: 16),
ValueListenableBuilder<bool>(
valueListenable: isActiveNotifier,
builder: (_, value, __) {
return _FormField(
label: '사용여부',
child: Row(
children: [
ShadSwitch(
value: value,
onChanged: saving.value
? null
: (next) => isActiveNotifier.value = next,
),
const SizedBox(width: 8),
Text(value ? '사용' : '미사용'),
],
),
);
},
),
const SizedBox(height: 16),
_FormField(
label: '비고',
child: ShadTextarea(controller: noteController),
),
if (isEdit) ...[
const SizedBox(height: 20),
Text(
'생성일시: ${_formatDateTime(existingGroup.createdAt)}',
style: theme.textTheme.small,
),
const SizedBox(height: 4),
Text(
'수정일시: ${_formatDateTime(existingGroup.updatedAt)}',
style: theme.textTheme.small,
),
],
],
),
),
),
),
),
);
},
);
nameController.dispose();
descriptionController.dispose();
noteController.dispose();
isDefaultNotifier.dispose();
isActiveNotifier.dispose();
saving.dispose();
nameError.dispose();
}
Future<void> _confirmDelete(Group group) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: const Text('그룹 삭제'),
content: Text('"${group.groupName}" 그룹을 삭제하시겠습니까?'),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('취소'),
),
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('삭제'),
),
],
);
},
);
if (confirmed == true && group.id != null) {
final success = await _controller.delete(group.id!);
if (success && mounted) {
_showSnack('그룹을 삭제했습니다.');
}
}
}
Future<void> _restoreGroup(Group group) async {
if (group.id == null) return;
final restored = await _controller.restore(group.id!);
if (restored != null && mounted) {
_showSnack('그룹을 복구했습니다.');
}
}
void _showSnack(String message) {
if (!mounted) return;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(message)));
}
String _formatDateTime(DateTime? value) {
if (value == null) {
return '-';
}
return _dateFormat.format(value.toLocal());
}
}
class _GroupTable extends StatelessWidget {
const _GroupTable({
required this.groups,
required this.onEdit,
required this.onDelete,
required this.onRestore,
required this.dateFormat,
});
final List<Group> groups;
final void Function(Group group)? onEdit;
final void Function(Group group)? onDelete;
final void Function(Group group)? onRestore;
final DateFormat dateFormat;
@override
Widget build(BuildContext context) {
final header = [
'ID',
'그룹명',
'설명',
'기본',
'사용',
'삭제',
'비고',
'변경일시',
'동작',
].map((text) => ShadTableCell.header(child: Text(text))).toList();
final rows = groups.map((group) {
final cells = [
group.id?.toString() ?? '-',
group.groupName,
(group.description?.isEmpty ?? true) ? '-' : group.description!,
group.isDefault ? 'Y' : 'N',
group.isActive ? 'Y' : 'N',
group.isDeleted ? 'Y' : '-',
(group.note?.isEmpty ?? true) ? '-' : group.note!,
group.updatedAt == null
? '-'
: dateFormat.format(group.updatedAt!.toLocal()),
].map((text) => ShadTableCell(child: Text(text))).toList();
cells.add(
ShadTableCell(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onEdit == null ? null : () => onEdit!(group),
child: const Icon(LucideIcons.pencil, size: 16),
),
const SizedBox(width: 8),
group.isDeleted
? ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onRestore == null
? null
: () => onRestore!(group),
child: const Icon(LucideIcons.history, size: 16),
)
: ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onDelete == null
? null
: () => onDelete!(group),
child: const Icon(LucideIcons.trash2, size: 16),
),
],
),
),
);
return cells;
}).toList();
return SizedBox(
height: 56.0 * (groups.length + 1),
child: ShadTable.list(
header: header,
children: rows,
columnSpanExtent: (index) {
if (index == 8) {
return const FixedTableSpanExtent(160);
}
if (index == 2) {
return const FixedTableSpanExtent(220);
}
if (index == 6) {
return const FixedTableSpanExtent(200);
}
return const FixedTableSpanExtent(120);
},
),
);
}
}
class _FormField extends StatelessWidget {
const _FormField({required this.label, required this.child});
final String label;
final Widget child;
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: theme.textTheme.small),
const SizedBox(height: 6),
child,
],
);
}

View File

@@ -0,0 +1,127 @@
import 'package:superport_v2/core/common/models/paginated_result.dart';
import '../../domain/entities/group_permission.dart';
class GroupPermissionDto {
GroupPermissionDto({
this.id,
required this.group,
required this.menu,
this.canCreate = false,
this.canRead = true,
this.canUpdate = false,
this.canDelete = false,
this.isActive = true,
this.isDeleted = false,
this.note,
this.createdAt,
this.updatedAt,
});
final int? id;
final GroupPermissionGroupDto group;
final GroupPermissionMenuDto menu;
final bool canCreate;
final bool canRead;
final bool canUpdate;
final bool canDelete;
final bool isActive;
final bool isDeleted;
final String? note;
final DateTime? createdAt;
final DateTime? updatedAt;
factory GroupPermissionDto.fromJson(Map<String, dynamic> json) {
return GroupPermissionDto(
id: json['id'] as int?,
group: GroupPermissionGroupDto.fromJson(
(json['group'] as Map<String, dynamic>? ?? const {}),
),
menu: GroupPermissionMenuDto.fromJson(
(json['menu'] as Map<String, dynamic>? ?? const {}),
),
canCreate: (json['can_create'] as bool?) ?? false,
canRead: (json['can_read'] as bool?) ?? true,
canUpdate: (json['can_update'] as bool?) ?? false,
canDelete: (json['can_delete'] as bool?) ?? false,
isActive: (json['is_active'] as bool?) ?? true,
isDeleted: (json['is_deleted'] as bool?) ?? false,
note: json['note'] as String?,
createdAt: _parseDate(json['created_at']),
updatedAt: _parseDate(json['updated_at']),
);
}
GroupPermission toEntity() => GroupPermission(
id: id,
group: group.toEntity(),
menu: menu.toEntity(),
canCreate: canCreate,
canRead: canRead,
canUpdate: canUpdate,
canDelete: canDelete,
isActive: isActive,
isDeleted: isDeleted,
note: note,
createdAt: createdAt,
updatedAt: updatedAt,
);
static PaginatedResult<GroupPermission> parsePaginated(
Map<String, dynamic>? json,
) {
final items = (json?['items'] as List<dynamic>? ?? [])
.whereType<Map<String, dynamic>>()
.map(GroupPermissionDto.fromJson)
.map((dto) => dto.toEntity())
.toList();
return PaginatedResult<GroupPermission>(
items: items,
page: json?['page'] as int? ?? 1,
pageSize: json?['page_size'] as int? ?? items.length,
total: json?['total'] as int? ?? items.length,
);
}
}
class GroupPermissionGroupDto {
GroupPermissionGroupDto({required this.id, required this.groupName});
final int id;
final String groupName;
factory GroupPermissionGroupDto.fromJson(Map<String, dynamic> json) {
return GroupPermissionGroupDto(
id: json['id'] as int? ?? json['group_id'] as int,
groupName:
json['group_name'] as String? ?? json['name'] as String? ?? '-',
);
}
GroupPermissionGroup toEntity() =>
GroupPermissionGroup(id: id, groupName: groupName);
}
class GroupPermissionMenuDto {
GroupPermissionMenuDto({required this.id, required this.menuName});
final int id;
final String menuName;
factory GroupPermissionMenuDto.fromJson(Map<String, dynamic> json) {
return GroupPermissionMenuDto(
id: json['id'] as int? ?? json['menu_id'] as int,
menuName: json['menu_name'] as String? ?? json['name'] as String? ?? '-',
);
}
GroupPermissionMenu toEntity() =>
GroupPermissionMenu(id: id, menuName: menuName);
}
DateTime? _parseDate(Object? value) {
if (value == null) return null;
if (value is DateTime) return value;
if (value is String) return DateTime.tryParse(value);
return null;
}

View File

@@ -0,0 +1,78 @@
import 'package:dio/dio.dart';
import 'package:superport_v2/core/common/models/paginated_result.dart';
import 'package:superport_v2/core/network/api_client.dart';
import '../../domain/entities/group_permission.dart';
import '../../domain/repositories/group_permission_repository.dart';
import '../dtos/group_permission_dto.dart';
class GroupPermissionRepositoryRemote implements GroupPermissionRepository {
GroupPermissionRepositoryRemote({required ApiClient apiClient})
: _api = apiClient;
final ApiClient _api;
static const _basePath = '/group-menu-permissions';
@override
Future<PaginatedResult<GroupPermission>> list({
int page = 1,
int pageSize = 20,
int? groupId,
int? menuId,
bool? isActive,
bool includeDeleted = false,
}) async {
final response = await _api.get<Map<String, dynamic>>(
_basePath,
query: {
'page': page,
'page_size': pageSize,
if (groupId != null) 'group_id': groupId,
if (menuId != null) 'menu_id': menuId,
if (isActive != null) 'is_active': isActive,
if (includeDeleted) 'include_deleted': true,
'include': 'group,menu',
},
options: Options(responseType: ResponseType.json),
);
return GroupPermissionDto.parsePaginated(response.data ?? const {});
}
@override
Future<GroupPermission> create(GroupPermissionInput input) async {
final response = await _api.post<Map<String, dynamic>>(
_basePath,
data: input.toPayload(),
options: Options(responseType: ResponseType.json),
);
final data = (response.data?['data'] as Map<String, dynamic>?) ?? {};
return GroupPermissionDto.fromJson(data).toEntity();
}
@override
Future<GroupPermission> update(int id, GroupPermissionInput input) async {
final response = await _api.patch<Map<String, dynamic>>(
'$_basePath/$id',
data: input.toPayload(),
options: Options(responseType: ResponseType.json),
);
final data = (response.data?['data'] as Map<String, dynamic>?) ?? {};
return GroupPermissionDto.fromJson(data).toEntity();
}
@override
Future<void> delete(int id) async {
await _api.delete<void>('$_basePath/$id');
}
@override
Future<GroupPermission> restore(int id) async {
final response = await _api.post<Map<String, dynamic>>(
'$_basePath/$id/restore',
options: Options(responseType: ResponseType.json),
);
final data = (response.data?['data'] as Map<String, dynamic>?) ?? {};
return GroupPermissionDto.fromJson(data).toEntity();
}
}

View File

@@ -0,0 +1,113 @@
/// 그룹-메뉴 권한 엔티티
///
/// - 그룹과 메뉴별 CRUD 권한을 표현한다.
/// - presentation/data 레이어 세부 사항에 의존하지 않는다.
class GroupPermission {
GroupPermission({
this.id,
required this.group,
required this.menu,
this.canCreate = false,
this.canRead = true,
this.canUpdate = false,
this.canDelete = false,
this.isActive = true,
this.isDeleted = false,
this.note,
this.createdAt,
this.updatedAt,
});
final int? id;
final GroupPermissionGroup group;
final GroupPermissionMenu menu;
final bool canCreate;
final bool canRead;
final bool canUpdate;
final bool canDelete;
final bool isActive;
final bool isDeleted;
final String? note;
final DateTime? createdAt;
final DateTime? updatedAt;
GroupPermission copyWith({
int? id,
GroupPermissionGroup? group,
GroupPermissionMenu? menu,
bool? canCreate,
bool? canRead,
bool? canUpdate,
bool? canDelete,
bool? isActive,
bool? isDeleted,
String? note,
DateTime? createdAt,
DateTime? updatedAt,
}) {
return GroupPermission(
id: id ?? this.id,
group: group ?? this.group,
menu: menu ?? this.menu,
canCreate: canCreate ?? this.canCreate,
canRead: canRead ?? this.canRead,
canUpdate: canUpdate ?? this.canUpdate,
canDelete: canDelete ?? this.canDelete,
isActive: isActive ?? this.isActive,
isDeleted: isDeleted ?? this.isDeleted,
note: note ?? this.note,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt,
);
}
}
class GroupPermissionGroup {
GroupPermissionGroup({required this.id, required this.groupName});
final int id;
final String groupName;
}
class GroupPermissionMenu {
GroupPermissionMenu({required this.id, required this.menuName});
final int id;
final String menuName;
}
/// 그룹 권한 생성/수정 입력 모델
class GroupPermissionInput {
GroupPermissionInput({
required this.groupId,
required this.menuId,
this.canCreate = false,
this.canRead = true,
this.canUpdate = false,
this.canDelete = false,
this.isActive = true,
this.note,
});
final int groupId;
final int menuId;
final bool canCreate;
final bool canRead;
final bool canUpdate;
final bool canDelete;
final bool isActive;
final String? note;
Map<String, dynamic> toPayload() {
return {
'group_id': groupId,
'menu_id': menuId,
'can_create': canCreate,
'can_read': canRead,
'can_update': canUpdate,
'can_delete': canDelete,
'is_active': isActive,
'note': note,
};
}
}

View File

@@ -0,0 +1,22 @@
import 'package:superport_v2/core/common/models/paginated_result.dart';
import '../entities/group_permission.dart';
abstract class GroupPermissionRepository {
Future<PaginatedResult<GroupPermission>> list({
int page = 1,
int pageSize = 20,
int? groupId,
int? menuId,
bool? isActive,
bool includeDeleted = false,
});
Future<GroupPermission> create(GroupPermissionInput input);
Future<GroupPermission> update(int id, GroupPermissionInput input);
Future<void> delete(int id);
Future<GroupPermission> restore(int id);
}

View File

@@ -0,0 +1,208 @@
import 'package:flutter/foundation.dart';
import 'package:superport_v2/core/common/models/paginated_result.dart';
import '../../../group/domain/entities/group.dart';
import '../../../group/domain/repositories/group_repository.dart';
import '../../../menu/domain/entities/menu.dart';
import '../../../menu/domain/repositories/menu_repository.dart';
import '../../domain/entities/group_permission.dart';
import '../../domain/repositories/group_permission_repository.dart';
enum GroupPermissionStatusFilter { all, activeOnly, inactiveOnly }
/// 그룹-메뉴 권한 화면용 컨트롤러
///
/// - 목록/필터 상태를 관리하고, CRUD/복구 동작을 래핑한다.
/// - 그룹/메뉴 선택을 위해 참조 데이터를 로드한다.
class GroupPermissionController extends ChangeNotifier {
GroupPermissionController({
required GroupPermissionRepository permissionRepository,
required GroupRepository groupRepository,
required MenuRepository menuRepository,
}) : _permissionRepository = permissionRepository,
_groupRepository = groupRepository,
_menuRepository = menuRepository;
final GroupPermissionRepository _permissionRepository;
final GroupRepository _groupRepository;
final MenuRepository _menuRepository;
PaginatedResult<GroupPermission>? _result;
bool _isLoading = false;
bool _isSubmitting = false;
bool _isLoadingGroups = false;
bool _isLoadingMenus = false;
String? _errorMessage;
GroupPermissionStatusFilter _statusFilter = GroupPermissionStatusFilter.all;
int? _groupFilter;
int? _menuFilter;
bool _includeDeleted = false;
final List<Group> _groups = [];
final List<MenuItem> _menus = [];
PaginatedResult<GroupPermission>? get result => _result;
bool get isLoading => _isLoading;
bool get isSubmitting => _isSubmitting;
bool get isLoadingGroups => _isLoadingGroups;
bool get isLoadingMenus => _isLoadingMenus;
String? get errorMessage => _errorMessage;
GroupPermissionStatusFilter get statusFilter => _statusFilter;
int? get groupFilter => _groupFilter;
int? get menuFilter => _menuFilter;
bool get includeDeleted => _includeDeleted;
List<Group> get groups => List.unmodifiable(_groups);
List<MenuItem> get menus => List.unmodifiable(_menus);
Future<void> loadGroups() async {
_isLoadingGroups = true;
notifyListeners();
try {
final response = await _groupRepository.list(page: 1, pageSize: 200);
_groups
..clear()
..addAll(response.items);
} catch (e) {
_errorMessage = e.toString();
} finally {
_isLoadingGroups = false;
notifyListeners();
}
}
Future<void> loadMenus() async {
_isLoadingMenus = true;
notifyListeners();
try {
final response = await _menuRepository.list(
page: 1,
pageSize: 200,
includeDeleted: false,
);
_menus
..clear()
..addAll(response.items);
} catch (e) {
_errorMessage = e.toString();
} finally {
_isLoadingMenus = false;
notifyListeners();
}
}
Future<void> fetch({int page = 1}) async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
try {
final isActive = switch (_statusFilter) {
GroupPermissionStatusFilter.all => null,
GroupPermissionStatusFilter.activeOnly => true,
GroupPermissionStatusFilter.inactiveOnly => false,
};
final response = await _permissionRepository.list(
page: page,
pageSize: _result?.pageSize ?? 20,
groupId: _groupFilter,
menuId: _menuFilter,
isActive: isActive,
includeDeleted: _includeDeleted,
);
_result = response;
} catch (e) {
_errorMessage = e.toString();
} finally {
_isLoading = false;
notifyListeners();
}
}
void updateGroupFilter(int? groupId) {
_groupFilter = groupId;
notifyListeners();
}
void updateMenuFilter(int? menuId) {
_menuFilter = menuId;
notifyListeners();
}
void updateStatusFilter(GroupPermissionStatusFilter filter) {
_statusFilter = filter;
notifyListeners();
}
void updateIncludeDeleted(bool value) {
_includeDeleted = value;
notifyListeners();
}
Future<GroupPermission?> create(GroupPermissionInput input) async {
_setSubmitting(true);
try {
final created = await _permissionRepository.create(input);
await fetch(page: 1);
return created;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return null;
} finally {
_setSubmitting(false);
}
}
Future<GroupPermission?> update(int id, GroupPermissionInput input) async {
_setSubmitting(true);
try {
final updated = await _permissionRepository.update(id, input);
await fetch(page: _result?.page ?? 1);
return updated;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return null;
} finally {
_setSubmitting(false);
}
}
Future<bool> delete(int id) async {
_setSubmitting(true);
try {
await _permissionRepository.delete(id);
await fetch(page: _result?.page ?? 1);
return true;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return false;
} finally {
_setSubmitting(false);
}
}
Future<GroupPermission?> restore(int id) async {
_setSubmitting(true);
try {
final restored = await _permissionRepository.restore(id);
await fetch(page: _result?.page ?? 1);
return restored;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return null;
} finally {
_setSubmitting(false);
}
}
void clearError() {
_errorMessage = null;
notifyListeners();
}
void _setSubmitting(bool value) {
_isSubmitting = value;
notifyListeners();
}
}

View File

@@ -1,50 +1,966 @@
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:intl/intl.dart' as intl;
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport_v2/core/constants/app_sections.dart';
import 'package:superport_v2/widgets/app_layout.dart';
import 'package:superport_v2/widgets/components/filter_bar.dart';
import '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
import '../../../group/domain/entities/group.dart';
import '../../../group/domain/repositories/group_repository.dart';
import '../../../menu/domain/entities/menu.dart';
import '../../../menu/domain/repositories/menu_repository.dart';
import '../../domain/entities/group_permission.dart';
import '../../domain/repositories/group_permission_repository.dart';
import '../controllers/group_permission_controller.dart';
class GroupPermissionPage extends StatelessWidget {
const GroupPermissionPage({super.key});
@override
Widget build(BuildContext context) {
return const SpecPage(
title: '그룹 메뉴 권한 관리',
summary: '그룹별 메뉴 접근과 CRUD 권한을 설정합니다.',
sections: [
SpecSection(
title: '입력 폼',
items: [
'그룹 [Dropdown]',
'메뉴 [Dropdown]',
'생성권한 [Checkbox]',
'조회권한 [Checkbox]',
'수정권한 [Checkbox]',
'삭제권한 [Checkbox]',
'사용여부 [Switch]',
],
final enabled = Environment.flag('FEATURE_GROUP_PERMISSIONS_ENABLED');
if (!enabled) {
return SpecPage(
title: '그룹 권한 관리',
summary: '그룹과 메뉴별 CRUD 권한을 확인하고 수정합니다.',
trailing: ShadBadge(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
child: Row(
mainAxisSize: MainAxisSize.min,
children: const [
Icon(LucideIcons.info, size: 14),
SizedBox(width: 6),
Text('비활성화 (백엔드 준비 중)'),
],
),
),
),
SpecSection(title: '수정 폼', items: ['그룹 [ReadOnly]', '메뉴 [ReadOnly]']),
SpecSection(
title: '테이블 리스트',
description: '1행 예시',
table: SpecTable(
columns: [
'번호',
'그룹명',
'메뉴명',
'생성',
'조회',
'수정',
'삭제',
'사용여부',
'변경일시',
sections: const [
SpecSection(
title: '입력 폼',
items: [
'그룹 [Dropdown]',
'메뉴 [Dropdown]',
'생성권한 [Checkbox]',
'조회권한 [Checkbox]',
'수정권한 [Checkbox]',
'삭제권한 [Checkbox]',
'사용여부 [Switch]',
'비고 [Text]',
],
rows: [
['1', '관리자', '대시보드', 'Y', 'Y', 'Y', 'Y', 'Y', '2024-03-01 10:00'],
),
SpecSection(
title: '수정 폼',
items: ['그룹 [ReadOnly]', '메뉴 [ReadOnly]', '생성일시 [ReadOnly]'],
),
SpecSection(
title: '테이블 리스트',
description: '1행 예시',
table: SpecTable(
columns: [
'번호',
'그룹명',
'메뉴명',
'생성',
'조회',
'수정',
'삭제',
'사용여부',
'비고',
'변경일시',
],
rows: [
[
'1',
'관리자',
'대시보드',
'Y',
'Y',
'Y',
'Y',
'Y',
'-',
'2024-03-01 10:00',
],
],
),
),
],
);
}
return const _GroupPermissionEnabledPage();
}
}
class _GroupPermissionEnabledPage extends StatefulWidget {
const _GroupPermissionEnabledPage();
@override
State<_GroupPermissionEnabledPage> createState() =>
_GroupPermissionEnabledPageState();
}
class _GroupPermissionEnabledPageState
extends State<_GroupPermissionEnabledPage> {
late final GroupPermissionController _controller;
final TextEditingController _searchController = TextEditingController();
final FocusNode _searchFocus = FocusNode();
final intl.DateFormat _dateFormat = intl.DateFormat('yyyy-MM-dd HH:mm');
String? _lastError;
@override
void initState() {
super.initState();
_controller = GroupPermissionController(
permissionRepository: GetIt.I<GroupPermissionRepository>(),
groupRepository: GetIt.I<GroupRepository>(),
menuRepository: GetIt.I<MenuRepository>(),
)..addListener(_handleControllerUpdate);
WidgetsBinding.instance.addPostFrameCallback((_) async {
await _controller.loadGroups();
await _controller.loadMenus();
await _controller.fetch();
});
}
void _handleControllerUpdate() {
final error = _controller.errorMessage;
if (error != null && error != _lastError && mounted) {
_lastError = error;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(error)));
_controller.clearError();
}
}
@override
void dispose() {
_controller.removeListener(_handleControllerUpdate);
_controller.dispose();
_searchController.dispose();
_searchFocus.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
return AnimatedBuilder(
animation: _controller,
builder: (context, _) {
final result = _controller.result;
final permissions = result?.items ?? const <GroupPermission>[];
final totalCount = result?.total ?? 0;
final currentPage = result?.page ?? 1;
final totalPages = result == null || result.pageSize == 0
? 1
: (result.total / result.pageSize).ceil().clamp(1, 9999);
final hasNext = result == null
? false
: (result.page * result.pageSize) < result.total;
final showReset = _searchController.text.isNotEmpty ||
_controller.groupFilter != null ||
_controller.menuFilter != null ||
_controller.statusFilter != GroupPermissionStatusFilter.all ||
_controller.includeDeleted;
return AppLayout(
title: '그룹 권한 관리',
subtitle: '그룹별 메뉴 CRUD 권한을 체크박스로 관리합니다.',
breadcrumbs: const [
AppBreadcrumbItem(label: '대시보드', path: dashboardRoutePath),
AppBreadcrumbItem(label: '마스터', path: '/masters/group-permissions'),
AppBreadcrumbItem(label: '그룹 권한'),
],
actions: [
ShadButton(
leading: const Icon(LucideIcons.plus, size: 16),
onPressed: _controller.isSubmitting
? null
: () => _openPermissionForm(context),
child: const Text('신규 등록'),
),
],
toolbar: FilterBar(
children: [
SizedBox(
width: 260,
child: ShadInput(
controller: _searchController,
focusNode: _searchFocus,
placeholder: const Text('그룹/메뉴/비고 검색'),
leading: const Icon(LucideIcons.search, size: 16),
onSubmitted: (_) => _applyFilters(),
),
),
SizedBox(
width: 220,
child: ShadSelect<int?>(
key: ValueKey(_controller.groupFilter),
initialValue: _controller.groupFilter,
placeholder: Text(
_controller.groups.isEmpty
? '그룹 로딩중...'
: '그룹 전체',
),
selectedOptionBuilder: (context, value) {
if (value == null) {
return Text(
_controller.groups.isEmpty
? '그룹 로딩중...'
: '그룹 전체',
);
}
final group = _controller.groups.firstWhere(
(g) => g.id == value,
orElse: () => Group(id: value, groupName: ''),
);
return Text(group.groupName);
},
onChanged: (value) {
_controller.updateGroupFilter(value);
},
options: [
const ShadOption<int?>(
value: null,
child: Text('그룹 전체'),
),
..._controller.groups.map(
(group) => ShadOption<int?>(
value: group.id,
child: Text(group.groupName),
),
),
],
),
),
SizedBox(
width: 220,
child: ShadSelect<int?>(
key: ValueKey(_controller.menuFilter),
initialValue: _controller.menuFilter,
placeholder: Text(
_controller.menus.isEmpty
? '메뉴 로딩중...'
: '메뉴 전체',
),
selectedOptionBuilder: (context, value) {
if (value == null) {
return Text(
_controller.menus.isEmpty
? '메뉴 로딩중...'
: '메뉴 전체',
);
}
final menuItem = _controller.menus.firstWhere(
(m) => m.id == value,
orElse: () => MenuItem(
id: value,
menuCode: '',
menuName: '',
),
);
return Text(menuItem.menuName);
},
onChanged: (value) {
_controller.updateMenuFilter(value);
},
options: [
const ShadOption<int?>(
value: null,
child: Text('메뉴 전체'),
),
..._controller.menus.map(
(menuItem) => ShadOption<int?>(
value: menuItem.id,
child: Text(menuItem.menuName),
),
),
],
),
),
SizedBox(
width: 200,
child: ShadSelect<GroupPermissionStatusFilter>(
key: ValueKey(_controller.statusFilter),
initialValue: _controller.statusFilter,
selectedOptionBuilder: (context, filter) =>
Text(_statusLabel(filter)),
onChanged: (value) {
if (value == null) return;
_controller.updateStatusFilter(value);
},
options: GroupPermissionStatusFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_statusLabel(filter)),
),
)
.toList(),
),
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
ShadSwitch(
value: _controller.includeDeleted,
onChanged: (value) {
_controller.updateIncludeDeleted(value);
},
),
const SizedBox(width: 8),
const Text('삭제 포함'),
],
),
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
if (showReset)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateGroupFilter(null);
_controller.updateMenuFilter(null);
_controller.updateIncludeDeleted(false);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
),
child: ShadCard(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('그룹 권한 목록', style: theme.textTheme.h3),
Text('$totalCount건', style: theme.textTheme.muted),
],
),
footer: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'페이지 $currentPage / $totalPages',
style: theme.textTheme.small,
),
Row(
children: [
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || currentPage <= 1
? null
: () => _controller.fetch(page: currentPage - 1),
child: const Text('이전'),
),
const SizedBox(width: 8),
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || !hasNext
? null
: () => _controller.fetch(page: currentPage + 1),
child: const Text('다음'),
),
],
),
],
),
child: _controller.isLoading
? const Padding(
padding: EdgeInsets.all(48),
child: Center(child: CircularProgressIndicator()),
)
: permissions.isEmpty
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
'조건에 맞는 권한이 없습니다.',
style: theme.textTheme.muted,
),
)
: _PermissionTable(
permissions: permissions,
dateFormat: _dateFormat,
onEdit: _controller.isSubmitting
? null
: (permission) =>
_openPermissionForm(context, permission: permission),
onDelete: _controller.isSubmitting
? null
: _confirmDelete,
onRestore: _controller.isSubmitting
? null
: _restorePermission,
),
),
);
},
);
}
void _applyFilters() {
_controller.fetch(page: 1);
}
String _statusLabel(GroupPermissionStatusFilter filter) {
switch (filter) {
case GroupPermissionStatusFilter.all:
return '전체(사용/미사용)';
case GroupPermissionStatusFilter.activeOnly:
return '사용중';
case GroupPermissionStatusFilter.inactiveOnly:
return '미사용';
}
}
Future<void> _openPermissionForm(
BuildContext context, {
GroupPermission? permission,
}) async {
final isEdit = permission != null;
final permissionId = permission?.id;
if (isEdit && permissionId == null) {
_showSnack('ID 정보가 없어 수정할 수 없습니다.');
return;
}
final groupNotifier = ValueNotifier<int?>(permission?.group.id);
final menuNotifier = ValueNotifier<int?>(permission?.menu.id);
final createNotifier = ValueNotifier<bool>(permission?.canCreate ?? false);
final readNotifier = ValueNotifier<bool>(permission?.canRead ?? true);
final updateNotifier = ValueNotifier<bool>(permission?.canUpdate ?? false);
final deleteNotifier = ValueNotifier<bool>(permission?.canDelete ?? false);
final activeNotifier = ValueNotifier<bool>(permission?.isActive ?? true);
final noteController = TextEditingController(text: permission?.note ?? '');
final saving = ValueNotifier<bool>(false);
final groupError = ValueNotifier<String?>(null);
final menuError = ValueNotifier<String?>(null);
await showDialog<bool>(
context: context,
builder: (dialogContext) {
final theme = ShadTheme.of(dialogContext);
final materialTheme = Theme.of(dialogContext);
final navigator = Navigator.of(dialogContext);
return Dialog(
insetPadding: const EdgeInsets.all(24),
clipBehavior: Clip.antiAlias,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 600),
child: ShadCard(
title: Text(
isEdit ? '권한 수정' : '권한 등록',
style: theme.textTheme.h3,
),
description: Text(
'그룹과 메뉴의 권한을 ${isEdit ? '수정' : '등록'}하세요.',
style: theme.textTheme.muted,
),
footer: ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (_, isSaving, __) {
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ShadButton.ghost(
onPressed: isSaving ? null : () => navigator.pop(false),
child: const Text('취소'),
),
const SizedBox(width: 12),
ShadButton(
onPressed: isSaving
? null
: () async {
final groupId = groupNotifier.value;
final menuId = menuNotifier.value;
groupError.value = groupId == null
? '그룹을 선택하세요.'
: null;
menuError.value = menuId == null
? '메뉴를 선택하세요.'
: null;
if (groupError.value != null ||
menuError.value != null) {
return;
}
saving.value = true;
final input = GroupPermissionInput(
groupId: groupId!,
menuId: menuId!,
canCreate: createNotifier.value,
canRead: readNotifier.value,
canUpdate: updateNotifier.value,
canDelete: deleteNotifier.value,
isActive: activeNotifier.value,
note: noteController.text.trim().isEmpty
? null
: noteController.text.trim(),
);
final response = isEdit
? await _controller.update(
permissionId!,
input,
)
: await _controller.create(input);
saving.value = false;
if (response != null) {
if (!navigator.mounted) {
return;
}
if (mounted) {
_showSnack(
isEdit ? '권한을 수정했습니다.' : '권한을 등록했습니다.',
);
}
navigator.pop(true);
}
},
child: Text(isEdit ? '저장' : '등록'),
),
],
);
},
),
child: SizedBox(
width: double.infinity,
child: SingleChildScrollView(
padding: const EdgeInsets.only(right: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
ValueListenableBuilder<String?>(
valueListenable: groupError,
builder: (_, errorText, __) {
return _FormField(
label: '그룹',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ShadSelect<int?>(
initialValue: groupNotifier.value,
placeholder: const Text('그룹을 선택하세요'),
selectedOptionBuilder: (context, value) {
if (value == null) {
return const Text('그룹을 선택하세요');
}
final groupId = value;
final group = _controller.groups.firstWhere(
(g) => g.id == groupId,
orElse: () =>
Group(id: groupId, groupName: ''),
);
return Text(
group.groupName.isEmpty
? '그룹을 선택하세요'
: group.groupName,
);
},
onChanged: saving.value || isEdit
? null
: (value) {
groupNotifier.value = value;
if (value != null) {
groupError.value = null;
}
},
options: [
..._controller.groups.map(
(group) => ShadOption<int?>(
value: group.id,
child: Text(group.groupName),
),
),
],
),
if (errorText != null)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
errorText,
style: theme.textTheme.small.copyWith(
color: materialTheme.colorScheme.error,
),
),
),
],
),
);
},
),
const SizedBox(height: 16),
ValueListenableBuilder<String?>(
valueListenable: menuError,
builder: (_, errorText, __) {
return _FormField(
label: '메뉴',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ShadSelect<int?>(
initialValue: menuNotifier.value,
placeholder: const Text('메뉴를 선택하세요'),
selectedOptionBuilder: (context, value) {
if (value == null) {
return const Text('메뉴를 선택하세요');
}
final menuId = value;
final menu = _controller.menus.firstWhere(
(m) => m.id == menuId,
orElse: () => MenuItem(
id: menuId,
menuCode: '',
menuName: '',
),
);
return Text(
menu.menuName.isEmpty
? '메뉴를 선택하세요'
: menu.menuName,
);
},
onChanged: saving.value || isEdit
? null
: (value) {
menuNotifier.value = value;
if (value != null) {
menuError.value = null;
}
},
options: [
..._controller.menus.map(
(menu) => ShadOption<int?>(
value: menu.id,
child: Text(menu.menuName),
),
),
],
),
if (errorText != null)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
errorText,
style: theme.textTheme.small.copyWith(
color: materialTheme.colorScheme.error,
),
),
),
],
),
);
},
),
const SizedBox(height: 20),
_PermissionToggleRow(
label: '생성권한',
notifier: createNotifier,
enabled: !saving.value,
),
const SizedBox(height: 12),
_PermissionToggleRow(
label: '조회권한',
notifier: readNotifier,
enabled: !saving.value,
),
const SizedBox(height: 12),
_PermissionToggleRow(
label: '수정권한',
notifier: updateNotifier,
enabled: !saving.value,
),
const SizedBox(height: 12),
_PermissionToggleRow(
label: '삭제권한',
notifier: deleteNotifier,
enabled: !saving.value,
),
const SizedBox(height: 16),
ValueListenableBuilder<bool>(
valueListenable: activeNotifier,
builder: (_, value, __) {
return _FormField(
label: '사용여부',
child: Row(
children: [
ShadSwitch(
value: value,
onChanged: saving.value
? null
: (next) => activeNotifier.value = next,
),
const SizedBox(width: 8),
Text(value ? '사용' : '미사용'),
],
),
);
},
),
const SizedBox(height: 16),
_FormField(
label: '비고',
child: ShadTextarea(controller: noteController),
),
if (isEdit) ...[
const SizedBox(height: 20),
Text(
'생성일시: ${_formatDateTime(permission.createdAt)}',
style: theme.textTheme.small,
),
const SizedBox(height: 4),
Text(
'수정일시: ${_formatDateTime(permission.updatedAt)}',
style: theme.textTheme.small,
),
],
],
),
),
),
),
),
);
},
);
groupNotifier.dispose();
menuNotifier.dispose();
createNotifier.dispose();
readNotifier.dispose();
updateNotifier.dispose();
deleteNotifier.dispose();
activeNotifier.dispose();
noteController.dispose();
saving.dispose();
groupError.dispose();
menuError.dispose();
}
Future<void> _confirmDelete(GroupPermission permission) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: const Text('권한 삭제'),
content: Text(
'"${permission.group.groupName}" → "${permission.menu.menuName}" 권한을 삭제하시겠습니까?',
),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('취소'),
),
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('삭제'),
),
],
);
},
);
if (confirmed == true && permission.id != null) {
final success = await _controller.delete(permission.id!);
if (success && mounted) {
_showSnack('권한을 삭제했습니다.');
}
}
}
Future<void> _restorePermission(GroupPermission permission) async {
if (permission.id == null) return;
final restored = await _controller.restore(permission.id!);
if (restored != null && mounted) {
_showSnack('권한을 복구했습니다.');
}
}
void _showSnack(String message) {
if (!mounted) return;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(message)));
}
String _formatDateTime(DateTime? value) {
if (value == null) {
return '-';
}
return _dateFormat.format(value.toLocal());
}
}
class _PermissionTable extends StatelessWidget {
const _PermissionTable({
required this.permissions,
required this.dateFormat,
required this.onEdit,
required this.onDelete,
required this.onRestore,
});
final List<GroupPermission> permissions;
final intl.DateFormat dateFormat;
final void Function(GroupPermission permission)? onEdit;
final void Function(GroupPermission permission)? onDelete;
final void Function(GroupPermission permission)? onRestore;
@override
Widget build(BuildContext context) {
final header = [
'ID',
'그룹명',
'메뉴명',
'생성',
'조회',
'수정',
'삭제',
'사용',
'삭제',
'비고',
'변경일시',
'동작',
].map((text) => ShadTableCell.header(child: Text(text))).toList();
final rows = permissions.map((permission) {
final cells = [
permission.id?.toString() ?? '-',
permission.group.groupName,
permission.menu.menuName,
permission.canCreate ? 'Y' : '-',
permission.canRead ? 'Y' : '-',
permission.canUpdate ? 'Y' : '-',
permission.canDelete ? 'Y' : '-',
permission.isActive ? 'Y' : 'N',
permission.isDeleted ? 'Y' : '-',
permission.note?.isEmpty ?? true ? '-' : permission.note!,
permission.updatedAt == null
? '-'
: dateFormat.format(permission.updatedAt!.toLocal()),
].map((text) => ShadTableCell(child: Text(text))).toList();
cells.add(
ShadTableCell(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onEdit == null ? null : () => onEdit!(permission),
child: const Icon(LucideIcons.pencil, size: 16),
),
const SizedBox(width: 8),
permission.isDeleted
? ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onRestore == null
? null
: () => onRestore!(permission),
child: const Icon(LucideIcons.history, size: 16),
)
: ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onDelete == null
? null
: () => onDelete!(permission),
child: const Icon(LucideIcons.trash2, size: 16),
),
],
),
),
);
return cells;
}).toList();
return SizedBox(
height: 56.0 * (permissions.length + 1),
child: ShadTable.list(
header: header,
children: rows,
columnSpanExtent: (index) {
switch (index) {
case 1:
case 2:
return const FixedTableSpanExtent(180);
case 9:
return const FixedTableSpanExtent(220);
case 11:
return const FixedTableSpanExtent(160);
default:
return const FixedTableSpanExtent(110);
}
},
),
);
}
}
class _FormField extends StatelessWidget {
const _FormField({required this.label, required this.child});
final String label;
final Widget child;
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: theme.textTheme.small),
const SizedBox(height: 6),
child,
],
);
}
}
class _PermissionToggleRow extends StatelessWidget {
const _PermissionToggleRow({
required this.label,
required this.notifier,
required this.enabled,
});
final String label;
final ValueNotifier<bool> notifier;
final bool enabled;
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
return ValueListenableBuilder<bool>(
valueListenable: notifier,
builder: (_, value, __) {
return _FormField(
label: label,
child: Row(
children: [
ShadSwitch(
value: value,
onChanged: !enabled ? null : (next) => notifier.value = next,
),
const SizedBox(width: 8),
Text(value ? '허용' : '차단', style: theme.textTheme.small),
],
),
);
},
);
}
}

View File

@@ -0,0 +1,102 @@
import 'package:superport_v2/core/common/models/paginated_result.dart';
import '../../domain/entities/menu.dart';
class MenuDto {
MenuDto({
this.id,
required this.menuCode,
required this.menuName,
this.parent,
this.path,
this.displayOrder,
this.isActive = true,
this.isDeleted = false,
this.note,
this.createdAt,
this.updatedAt,
});
final int? id;
final String menuCode;
final String menuName;
final MenuSummaryDto? parent;
final String? path;
final int? displayOrder;
final bool isActive;
final bool isDeleted;
final String? note;
final DateTime? createdAt;
final DateTime? updatedAt;
factory MenuDto.fromJson(Map<String, dynamic> json) {
return MenuDto(
id: json['id'] as int?,
menuCode: json['menu_code'] as String,
menuName: json['menu_name'] as String,
parent: json['parent_menu'] is Map<String, dynamic>
? MenuSummaryDto.fromJson(json['parent_menu'] as Map<String, dynamic>)
: json['parent'] is Map<String, dynamic>
? MenuSummaryDto.fromJson(json['parent'] as Map<String, dynamic>)
: null,
path: json['path'] as String?,
displayOrder: json['display_order'] as int?,
isActive: (json['is_active'] as bool?) ?? true,
isDeleted: (json['is_deleted'] as bool?) ?? false,
note: json['note'] as String?,
createdAt: _parseDate(json['created_at']),
updatedAt: _parseDate(json['updated_at']),
);
}
MenuItem toEntity() => MenuItem(
id: id,
menuCode: menuCode,
menuName: menuName,
parent: parent?.toEntity(),
path: path,
displayOrder: displayOrder,
isActive: isActive,
isDeleted: isDeleted,
note: note,
createdAt: createdAt,
updatedAt: updatedAt,
);
static PaginatedResult<MenuItem> parsePaginated(Map<String, dynamic>? json) {
final items = (json?['items'] as List<dynamic>? ?? [])
.whereType<Map<String, dynamic>>()
.map(MenuDto.fromJson)
.map((dto) => dto.toEntity())
.toList();
return PaginatedResult<MenuItem>(
items: items,
page: json?['page'] as int? ?? 1,
pageSize: json?['page_size'] as int? ?? items.length,
total: json?['total'] as int? ?? items.length,
);
}
}
class MenuSummaryDto {
MenuSummaryDto({required this.id, required this.menuName});
final int id;
final String menuName;
factory MenuSummaryDto.fromJson(Map<String, dynamic> json) {
return MenuSummaryDto(
id: json['id'] as int,
menuName: json['menu_name'] as String,
);
}
MenuSummary toEntity() => MenuSummary(id: id, menuName: menuName);
}
DateTime? _parseDate(Object? value) {
if (value == null) return null;
if (value is DateTime) return value;
if (value is String) return DateTime.tryParse(value);
return null;
}

View File

@@ -0,0 +1,77 @@
import 'package:dio/dio.dart';
import 'package:superport_v2/core/common/models/paginated_result.dart';
import 'package:superport_v2/core/network/api_client.dart';
import '../../domain/entities/menu.dart';
import '../../domain/repositories/menu_repository.dart';
import '../dtos/menu_dto.dart';
class MenuRepositoryRemote implements MenuRepository {
MenuRepositoryRemote({required ApiClient apiClient}) : _api = apiClient;
final ApiClient _api;
static const _basePath = '/menus';
@override
Future<PaginatedResult<MenuItem>> list({
int page = 1,
int pageSize = 20,
String? query,
int? parentId,
bool? isActive,
bool includeDeleted = false,
}) async {
final response = await _api.get<Map<String, dynamic>>(
_basePath,
query: {
'page': page,
'page_size': pageSize,
if (query != null && query.isNotEmpty) 'q': query,
if (parentId != null) 'parent_id': parentId,
if (isActive != null) 'is_active': isActive,
if (includeDeleted) 'include_deleted': true,
'include': 'parent',
},
options: Options(responseType: ResponseType.json),
);
return MenuDto.parsePaginated(response.data ?? const {});
}
@override
Future<MenuItem> create(MenuInput input) async {
final response = await _api.post<Map<String, dynamic>>(
_basePath,
data: input.toPayload(),
options: Options(responseType: ResponseType.json),
);
final data = (response.data?['data'] as Map<String, dynamic>?) ?? {};
return MenuDto.fromJson(data).toEntity();
}
@override
Future<MenuItem> update(int id, MenuInput input) async {
final response = await _api.patch<Map<String, dynamic>>(
'$_basePath/$id',
data: input.toPayload(),
options: Options(responseType: ResponseType.json),
);
final data = (response.data?['data'] as Map<String, dynamic>?) ?? {};
return MenuDto.fromJson(data).toEntity();
}
@override
Future<void> delete(int id) async {
await _api.delete<void>('$_basePath/$id');
}
@override
Future<MenuItem> restore(int id) async {
final response = await _api.post<Map<String, dynamic>>(
'$_basePath/$id/restore',
options: Options(responseType: ResponseType.json),
);
final data = (response.data?['data'] as Map<String, dynamic>?) ?? {};
return MenuDto.fromJson(data).toEntity();
}
}

View File

@@ -0,0 +1,119 @@
/// 메뉴 엔티티
///
/// - 계층 구조를 표현하기 위해 상위 메뉴 정보를 포함한다.
/// - presentation/data 레이어 세부 구현에 의존하지 않는다.
class MenuItem {
MenuItem({
this.id,
required this.menuCode,
required this.menuName,
this.parent,
this.path,
this.displayOrder,
this.isActive = true,
this.isDeleted = false,
this.note,
this.createdAt,
this.updatedAt,
});
/// PK (null 이면 신규 생성)
final int? id;
/// 메뉴 코드 (고유)
final String menuCode;
/// 메뉴명
final String menuName;
/// 상위 메뉴 정보
final MenuSummary? parent;
/// 라우트 경로
final String? path;
/// 표시 순서
final int? displayOrder;
/// 사용 여부
final bool isActive;
/// 소프트 삭제 여부
final bool isDeleted;
/// 비고
final String? note;
/// 생성/수정 일시
final DateTime? createdAt;
final DateTime? updatedAt;
MenuItem copyWith({
int? id,
String? menuCode,
String? menuName,
MenuSummary? parent,
String? path,
int? displayOrder,
bool? isActive,
bool? isDeleted,
String? note,
DateTime? createdAt,
DateTime? updatedAt,
}) {
return MenuItem(
id: id ?? this.id,
menuCode: menuCode ?? this.menuCode,
menuName: menuName ?? this.menuName,
parent: parent ?? this.parent,
path: path ?? this.path,
displayOrder: displayOrder ?? this.displayOrder,
isActive: isActive ?? this.isActive,
isDeleted: isDeleted ?? this.isDeleted,
note: note ?? this.note,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt,
);
}
}
/// 상위 메뉴 요약 정보
class MenuSummary {
MenuSummary({required this.id, required this.menuName});
final int id;
final String menuName;
}
/// 메뉴 생성/수정 입력 모델
class MenuInput {
MenuInput({
required this.menuCode,
required this.menuName,
this.parentMenuId,
this.path,
this.displayOrder,
this.isActive = true,
this.note,
});
final String menuCode;
final String menuName;
final int? parentMenuId;
final String? path;
final int? displayOrder;
final bool isActive;
final String? note;
Map<String, dynamic> toPayload() {
return {
'menu_code': menuCode,
'menu_name': menuName,
'parent_menu_id': parentMenuId,
'path': path,
'display_order': displayOrder,
'is_active': isActive,
'note': note,
};
}
}

View File

@@ -0,0 +1,27 @@
import 'package:superport_v2/core/common/models/paginated_result.dart';
import '../entities/menu.dart';
abstract class MenuRepository {
/// 메뉴 목록 조회
Future<PaginatedResult<MenuItem>> list({
int page = 1,
int pageSize = 20,
String? query,
int? parentId,
bool? isActive,
bool includeDeleted = false,
});
/// 메뉴 신규 등록
Future<MenuItem> create(MenuInput input);
/// 메뉴 수정
Future<MenuItem> update(int id, MenuInput input);
/// 메뉴 삭제(소프트)
Future<void> delete(int id);
/// 메뉴 복구
Future<MenuItem> restore(int id);
}

View File

@@ -0,0 +1,179 @@
import 'package:flutter/foundation.dart';
import 'package:superport_v2/core/common/models/paginated_result.dart';
import '../../domain/entities/menu.dart';
import '../../domain/repositories/menu_repository.dart';
enum MenuStatusFilter { all, activeOnly, inactiveOnly }
/// 메뉴 마스터 상태 컨트롤러
///
/// - 목록, 필터, 페이지 상태를 관리한다.
/// - CRUD 및 복구 요청을 처리한다.
class MenuController extends ChangeNotifier {
MenuController({required MenuRepository repository})
: _repository = repository;
final MenuRepository _repository;
PaginatedResult<MenuItem>? _result;
bool _isLoading = false;
bool _isSubmitting = false;
bool _isLoadingParents = false;
String _query = '';
int? _parentFilter;
MenuStatusFilter _statusFilter = MenuStatusFilter.all;
bool _includeDeleted = false;
String? _errorMessage;
List<MenuItem> _parents = const [];
PaginatedResult<MenuItem>? get result => _result;
bool get isLoading => _isLoading;
bool get isSubmitting => _isSubmitting;
bool get isLoadingParents => _isLoadingParents;
String get query => _query;
int? get parentFilter => _parentFilter;
MenuStatusFilter get statusFilter => _statusFilter;
bool get includeDeleted => _includeDeleted;
String? get errorMessage => _errorMessage;
List<MenuItem> get parents => _parents;
Future<void> loadParents() async {
_isLoadingParents = true;
notifyListeners();
try {
final response = await _repository.list(
page: 1,
pageSize: 200,
includeDeleted: false,
);
_parents = response.items;
} catch (e) {
_errorMessage = e.toString();
} finally {
_isLoadingParents = false;
notifyListeners();
}
}
Future<void> fetch({int page = 1}) async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
try {
final isActive = switch (_statusFilter) {
MenuStatusFilter.all => null,
MenuStatusFilter.activeOnly => true,
MenuStatusFilter.inactiveOnly => false,
};
final response = await _repository.list(
page: page,
pageSize: _result?.pageSize ?? 20,
query: _query.isEmpty ? null : _query,
parentId: _parentFilter,
isActive: isActive,
includeDeleted: _includeDeleted,
);
_result = response;
} catch (e) {
_errorMessage = e.toString();
} finally {
_isLoading = false;
notifyListeners();
}
}
void updateQuery(String value) {
_query = value;
notifyListeners();
}
void updateParentFilter(int? parentId) {
_parentFilter = parentId;
notifyListeners();
}
void updateStatusFilter(MenuStatusFilter filter) {
_statusFilter = filter;
notifyListeners();
}
void updateIncludeDeleted(bool value) {
_includeDeleted = value;
notifyListeners();
}
Future<MenuItem?> create(MenuInput input) async {
_setSubmitting(true);
try {
final created = await _repository.create(input);
await fetch(page: 1);
await loadParents();
return created;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return null;
} finally {
_setSubmitting(false);
}
}
Future<MenuItem?> update(int id, MenuInput input) async {
_setSubmitting(true);
try {
final updated = await _repository.update(id, input);
await fetch(page: _result?.page ?? 1);
await loadParents();
return updated;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return null;
} finally {
_setSubmitting(false);
}
}
Future<bool> delete(int id) async {
_setSubmitting(true);
try {
await _repository.delete(id);
await fetch(page: _result?.page ?? 1);
await loadParents();
return true;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return false;
} finally {
_setSubmitting(false);
}
}
Future<MenuItem?> restore(int id) async {
_setSubmitting(true);
try {
final restored = await _repository.restore(id);
await fetch(page: _result?.page ?? 1);
await loadParents();
return restored;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return null;
} finally {
_setSubmitting(false);
}
}
void clearError() {
_errorMessage = null;
notifyListeners();
}
void _setSubmitting(bool value) {
_isSubmitting = value;
notifyListeners();
}
}

View File

@@ -1,51 +1,893 @@
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport_v2/core/constants/app_sections.dart';
import 'package:superport_v2/widgets/app_layout.dart';
import 'package:superport_v2/widgets/components/filter_bar.dart';
import '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
import '../../domain/entities/menu.dart';
import '../../domain/repositories/menu_repository.dart';
import '../controllers/menu_controller.dart' as menu;
class MenuPage extends StatelessWidget {
const MenuPage({super.key});
@override
Widget build(BuildContext context) {
return const SpecPage(
title: '메뉴 관리',
summary: '메뉴 계층, 경로, 노출 순서를 구성합니다.',
sections: [
SpecSection(
title: '입력 폼',
items: [
'메뉴코드 [Text]',
'메뉴명 [Text]',
'상위메뉴 [Dropdown]',
'경로 [Text]',
'표시순서 [Number]',
'사용여부 [Switch]',
'비고 [Text]',
],
),
SpecSection(
title: '수정 폼',
items: ['메뉴코드 [ReadOnly]', '생성일시 [ReadOnly]'],
),
SpecSection(
title: '테이블 리스트',
description: '1행 예시',
table: SpecTable(
columns: ['번호', '메뉴코드', '메뉴명', '상위메뉴', '경로', '사용여부', '비고', '변경일시'],
rows: [
[
'1',
'MN-001',
'대시보드',
'-',
'/dashboard',
'Y',
'-',
'2024-03-01 10:00',
final enabled = Environment.flag('FEATURE_MENUS_ENABLED');
if (!enabled) {
return SpecPage(
title: '메뉴 관리',
summary: '메뉴 코드, 트리 구조, 사용여부를 관리합니다.',
trailing: ShadBadge(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(LucideIcons.info, size: 14),
const SizedBox(width: 6),
const Text('비활성화 (백엔드 준비 중)'),
],
),
),
),
sections: const [
SpecSection(
title: '입력 폼',
items: [
'메뉴코드 [Text]',
'메뉴명 [Text]',
'상위메뉴 [Dropdown]',
'경로 [Text]',
'표시순서 [Number]',
'사용여부 [Switch]',
'비고 [Text]',
],
),
SpecSection(
title: '수정 폼',
items: ['메뉴코드 [ReadOnly]', '생성일시 [ReadOnly]'],
),
SpecSection(
title: '테이블 리스트',
description: '1행 예시',
table: SpecTable(
columns: [
'번호',
'메뉴코드',
'메뉴명',
'상위메뉴',
'경로',
'사용여부',
'비고',
'변경일시',
],
rows: [
[
'1',
'MENU001',
'대시보드',
'-',
'/dashboard',
'Y',
'-',
'2024-03-01 10:00',
],
],
),
),
],
);
}
return const _MenuEnabledPage();
}
}
class _MenuEnabledPage extends StatefulWidget {
const _MenuEnabledPage();
@override
State<_MenuEnabledPage> createState() => _MenuEnabledPageState();
}
class _MenuEnabledPageState extends State<_MenuEnabledPage> {
late final menu.MenuController _controller;
final TextEditingController _searchController = TextEditingController();
final FocusNode _searchFocus = FocusNode();
final DateFormat _dateFormat = DateFormat('yyyy-MM-dd HH:mm');
String? _lastError;
@override
void initState() {
super.initState();
_controller = menu.MenuController(repository: GetIt.I<MenuRepository>())
..addListener(_handleControllerUpdate);
WidgetsBinding.instance.addPostFrameCallback((_) async {
await _controller.loadParents();
await _controller.fetch();
});
}
void _handleControllerUpdate() {
final error = _controller.errorMessage;
if (error != null && error != _lastError && mounted) {
_lastError = error;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(error)));
_controller.clearError();
}
}
@override
void dispose() {
_controller.removeListener(_handleControllerUpdate);
_controller.dispose();
_searchController.dispose();
_searchFocus.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
return AnimatedBuilder(
animation: _controller,
builder: (context, _) {
final result = _controller.result;
final menus = result?.items ?? const <MenuItem>[];
final totalCount = result?.total ?? 0;
final currentPage = result?.page ?? 1;
final totalPages = result == null || result.pageSize == 0
? 1
: (result.total / result.pageSize).ceil().clamp(1, 9999);
final hasNext = result == null
? false
: (result.page * result.pageSize) < result.total;
final showReset = _searchController.text.isNotEmpty ||
_controller.parentFilter != null ||
_controller.statusFilter != menu.MenuStatusFilter.all ||
_controller.includeDeleted;
return AppLayout(
title: '메뉴 관리',
subtitle: '메뉴 트리와 경로, 사용 상태를 관리합니다.',
breadcrumbs: const [
AppBreadcrumbItem(label: '대시보드', path: dashboardRoutePath),
AppBreadcrumbItem(label: '마스터', path: '/masters/menus'),
AppBreadcrumbItem(label: '메뉴'),
],
actions: [
ShadButton(
leading: const Icon(LucideIcons.plus, size: 16),
onPressed:
_controller.isSubmitting ? null : () => _openMenuForm(context),
child: const Text('신규 등록'),
),
],
toolbar: FilterBar(
children: [
SizedBox(
width: 260,
child: ShadInput(
controller: _searchController,
focusNode: _searchFocus,
placeholder: const Text('메뉴코드, 메뉴명 검색'),
leading: const Icon(LucideIcons.search, size: 16),
onSubmitted: (_) => _applyFilters(),
),
),
SizedBox(
width: 220,
child: ShadSelect<int?>(
key: ValueKey(_controller.parentFilter),
initialValue: _controller.parentFilter,
placeholder: Text(
_controller.isLoadingParents ? '상위 로딩중...' : '상위 전체',
),
selectedOptionBuilder: (context, value) {
if (value == null) {
return Text(
_controller.isLoadingParents
? '상위 로딩중...'
: '상위 전체',
);
}
final target = _controller.parents.firstWhere(
(menuItem) => menuItem.id == value,
orElse: () => MenuItem(
id: value,
menuCode: '',
menuName: '',
),
);
final label = target.menuName.isEmpty
? '상위 전체'
: target.menuName;
return Text(label);
},
onChanged: _controller.isLoadingParents
? null
: (value) {
_controller.updateParentFilter(value);
_controller.fetch(page: 1);
},
options: [
const ShadOption<int?>(
value: null,
child: Text('상위 전체'),
),
..._controller.parents.map(
(menuItem) => ShadOption<int?>(
value: menuItem.id,
child: Text(menuItem.menuName),
),
),
],
),
),
SizedBox(
width: 200,
child: ShadSelect<menu.MenuStatusFilter>(
key: ValueKey(_controller.statusFilter),
initialValue: _controller.statusFilter,
selectedOptionBuilder: (context, filter) =>
Text(_statusLabel(filter)),
onChanged: (value) {
if (value == null) return;
_controller.updateStatusFilter(value);
_controller.fetch(page: 1);
},
options: menu.MenuStatusFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_statusLabel(filter)),
),
)
.toList(),
),
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
ShadSwitch(
value: _controller.includeDeleted,
onChanged: (value) {
_controller.updateIncludeDeleted(value);
_controller.fetch(page: 1);
},
),
const SizedBox(width: 8),
const Text('삭제 포함'),
],
),
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
if (showReset)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateParentFilter(null);
_controller.updateStatusFilter(
menu.MenuStatusFilter.all,
);
_controller.updateIncludeDeleted(false);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
),
child: ShadCard(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('메뉴 목록', style: theme.textTheme.h3),
Text('$totalCount건', style: theme.textTheme.muted),
],
),
footer: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'페이지 $currentPage / $totalPages',
style: theme.textTheme.small,
),
Row(
children: [
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || currentPage <= 1
? null
: () => _controller.fetch(page: currentPage - 1),
child: const Text('이전'),
),
const SizedBox(width: 8),
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || !hasNext
? null
: () => _controller.fetch(page: currentPage + 1),
child: const Text('다음'),
),
],
),
],
),
child: _controller.isLoading
? const Padding(
padding: EdgeInsets.all(48),
child: Center(child: CircularProgressIndicator()),
)
: menus.isEmpty
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
'조건에 맞는 메뉴가 없습니다.',
style: theme.textTheme.muted,
),
)
: _MenuTable(
menus: menus,
dateFormat: _dateFormat,
onEdit: _controller.isSubmitting
? null
: (menuItem) =>
_openMenuForm(context, menu: menuItem),
onDelete: _controller.isSubmitting
? null
: _confirmDelete,
onRestore: _controller.isSubmitting
? null
: _restoreMenu,
),
),
);
},
);
}
void _applyFilters() {
_controller.updateQuery(_searchController.text.trim());
_controller.fetch(page: 1);
}
String _statusLabel(menu.MenuStatusFilter filter) {
switch (filter) {
case menu.MenuStatusFilter.all:
return '전체(사용/미사용)';
case menu.MenuStatusFilter.activeOnly:
return '사용중';
case menu.MenuStatusFilter.inactiveOnly:
return '미사용';
}
}
Future<void> _openMenuForm(BuildContext context, {MenuItem? menu}) async {
final existingMenu = menu;
final isEdit = existingMenu != null;
final menuId = existingMenu?.id;
if (isEdit && menuId == null) {
_showSnack('ID 정보가 없어 수정할 수 없습니다.');
return;
}
final codeController = TextEditingController(
text: existingMenu?.menuCode ?? '',
);
final nameController = TextEditingController(
text: existingMenu?.menuName ?? '',
);
final pathController = TextEditingController(
text: existingMenu?.path ?? '',
);
final orderController = TextEditingController(
text: existingMenu?.displayOrder?.toString() ?? '',
);
final noteController = TextEditingController(
text: existingMenu?.note ?? '',
);
final parentNotifier = ValueNotifier<int?>(existingMenu?.parent?.id);
final isActiveNotifier = ValueNotifier<bool>(
existingMenu?.isActive ?? true,
);
final saving = ValueNotifier<bool>(false);
final codeError = ValueNotifier<String?>(null);
final nameError = ValueNotifier<String?>(null);
final orderError = ValueNotifier<String?>(null);
await showDialog<bool>(
context: context,
builder: (dialogContext) {
final theme = ShadTheme.of(dialogContext);
final materialTheme = Theme.of(dialogContext);
final navigator = Navigator.of(dialogContext);
return Dialog(
insetPadding: const EdgeInsets.all(24),
clipBehavior: Clip.antiAlias,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 560),
child: ShadCard(
title: Text(
isEdit ? '메뉴 수정' : '메뉴 등록',
style: theme.textTheme.h3,
),
description: Text(
'메뉴 정보를 ${isEdit ? '수정' : '입력'}하세요.',
style: theme.textTheme.muted,
),
footer: ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (_, isSaving, __) {
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ShadButton.ghost(
onPressed: isSaving ? null : () => navigator.pop(false),
child: const Text('취소'),
),
const SizedBox(width: 12),
ShadButton(
onPressed: isSaving
? null
: () async {
final code = codeController.text.trim();
final name = nameController.text.trim();
final path = pathController.text.trim();
final orderText = orderController.text.trim();
final note = noteController.text.trim();
codeError.value = code.isEmpty
? '메뉴코드를 입력하세요.'
: null;
nameError.value = name.isEmpty
? '메뉴명을 입력하세요.'
: null;
int? orderValue;
if (orderText.isNotEmpty) {
orderValue = int.tryParse(orderText);
if (orderValue == null) {
orderError.value = '표시순서는 숫자여야 합니다.';
} else {
orderError.value = null;
}
} else {
orderError.value = null;
}
if (codeError.value != null ||
nameError.value != null ||
orderError.value != null) {
return;
}
saving.value = true;
final input = MenuInput(
menuCode: code,
menuName: name,
parentMenuId: parentNotifier.value,
path: path.isEmpty ? null : path,
displayOrder: orderValue,
isActive: isActiveNotifier.value,
note: note.isEmpty ? null : note,
);
final response = isEdit
? await _controller.update(menuId!, input)
: await _controller.create(input);
saving.value = false;
if (response != null) {
if (!navigator.mounted) {
return;
}
if (mounted) {
_showSnack(
isEdit ? '메뉴를 수정했습니다.' : '메뉴를 등록했습니다.',
);
}
navigator.pop(true);
}
},
child: Text(isEdit ? '저장' : '등록'),
),
],
);
},
),
child: SizedBox(
width: double.infinity,
child: SingleChildScrollView(
padding: const EdgeInsets.only(right: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
ValueListenableBuilder<String?>(
valueListenable: codeError,
builder: (_, errorText, __) {
return _FormField(
label: '메뉴코드',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ShadInput(
controller: codeController,
readOnly: isEdit,
onChanged: (_) {
if (codeController.text.trim().isNotEmpty) {
codeError.value = null;
}
},
),
if (errorText != null)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
errorText,
style: theme.textTheme.small.copyWith(
color: materialTheme.colorScheme.error,
),
),
),
],
),
);
},
),
const SizedBox(height: 16),
ValueListenableBuilder<String?>(
valueListenable: nameError,
builder: (_, errorText, __) {
return _FormField(
label: '메뉴명',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ShadInput(
controller: nameController,
onChanged: (_) {
if (nameController.text.trim().isNotEmpty) {
nameError.value = null;
}
},
),
if (errorText != null)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
errorText,
style: theme.textTheme.small.copyWith(
color: materialTheme.colorScheme.error,
),
),
),
],
),
);
},
),
const SizedBox(height: 16),
ValueListenableBuilder<int?>(
valueListenable: parentNotifier,
builder: (_, value, __) {
return _FormField(
label: '상위메뉴',
child: ShadSelect<int?>(
initialValue: value,
placeholder: const Text('최상위'),
selectedOptionBuilder: (context, selected) {
if (selected == null) {
return const Text('최상위');
}
final target = _controller.parents.firstWhere(
(item) => item.id == selected,
orElse: () => MenuItem(
id: selected,
menuCode: '',
menuName: '',
),
);
final label = target.menuName.isEmpty
? '최상위'
: target.menuName;
return Text(label);
},
onChanged: saving.value
? null
: (next) => parentNotifier.value = next,
options: [
const ShadOption<int?>(
value: null,
child: Text('최상위'),
),
..._controller.parents
.where((item) => item.id != menuId)
.map(
(menuItem) => ShadOption<int?>(
value: menuItem.id,
child: Text(menuItem.menuName),
),
),
],
),
);
},
),
const SizedBox(height: 16),
_FormField(
label: '경로',
child: ShadInput(controller: pathController),
),
const SizedBox(height: 16),
ValueListenableBuilder<String?>(
valueListenable: orderError,
builder: (_, errorText, __) {
return _FormField(
label: '표시순서',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ShadInput(
controller: orderController,
keyboardType: TextInputType.number,
),
if (errorText != null)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
errorText,
style: theme.textTheme.small.copyWith(
color: materialTheme.colorScheme.error,
),
),
),
],
),
);
},
),
const SizedBox(height: 16),
ValueListenableBuilder<bool>(
valueListenable: isActiveNotifier,
builder: (_, value, __) {
return _FormField(
label: '사용여부',
child: Row(
children: [
ShadSwitch(
value: value,
onChanged: saving.value
? null
: (next) => isActiveNotifier.value = next,
),
const SizedBox(width: 8),
Text(value ? '사용' : '미사용'),
],
),
);
},
),
const SizedBox(height: 16),
_FormField(
label: '비고',
child: ShadTextarea(controller: noteController),
),
if (isEdit) ...[
const SizedBox(height: 20),
Text(
'생성일시: ${_formatDateTime(existingMenu.createdAt)}',
style: theme.textTheme.small,
),
const SizedBox(height: 4),
Text(
'수정일시: ${_formatDateTime(existingMenu.updatedAt)}',
style: theme.textTheme.small,
),
],
],
),
),
),
),
),
);
},
);
codeController.dispose();
nameController.dispose();
pathController.dispose();
orderController.dispose();
noteController.dispose();
parentNotifier.dispose();
isActiveNotifier.dispose();
saving.dispose();
codeError.dispose();
nameError.dispose();
orderError.dispose();
}
Future<void> _confirmDelete(MenuItem menu) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: const Text('메뉴 삭제'),
content: Text('"${menu.menuName}" 메뉴를 삭제하시겠습니까?'),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('취소'),
),
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('삭제'),
),
],
);
},
);
if (confirmed == true && menu.id != null) {
final success = await _controller.delete(menu.id!);
if (success && mounted) {
_showSnack('메뉴를 삭제했습니다.');
}
}
}
Future<void> _restoreMenu(MenuItem menu) async {
if (menu.id == null) return;
final restored = await _controller.restore(menu.id!);
if (restored != null && mounted) {
_showSnack('메뉴를 복구했습니다.');
}
}
void _showSnack(String message) {
if (!mounted) return;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(message)));
}
String _formatDateTime(DateTime? value) {
if (value == null) {
return '-';
}
return _dateFormat.format(value.toLocal());
}
}
class _MenuTable extends StatelessWidget {
const _MenuTable({
required this.menus,
required this.onEdit,
required this.onDelete,
required this.onRestore,
required this.dateFormat,
});
final List<MenuItem> menus;
final void Function(MenuItem menu)? onEdit;
final void Function(MenuItem menu)? onDelete;
final void Function(MenuItem menu)? onRestore;
final DateFormat dateFormat;
@override
Widget build(BuildContext context) {
final header = [
'ID',
'메뉴코드',
'메뉴명',
'상위메뉴',
'경로',
'사용',
'삭제',
'비고',
'변경일시',
'동작',
].map((text) => ShadTableCell.header(child: Text(text))).toList();
final rows = menus.map((item) {
final cells = [
item.id?.toString() ?? '-',
item.menuCode,
item.menuName,
item.parent?.menuName ?? '-',
item.path?.isEmpty ?? true ? '-' : item.path!,
item.isActive ? 'Y' : 'N',
item.isDeleted ? 'Y' : '-',
item.note?.isEmpty ?? true ? '-' : item.note!,
item.updatedAt == null
? '-'
: dateFormat.format(item.updatedAt!.toLocal()),
].map((text) => ShadTableCell(child: Text(text))).toList();
cells.add(
ShadTableCell(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onEdit == null ? null : () => onEdit!(item),
child: const Icon(LucideIcons.pencil, size: 16),
),
const SizedBox(width: 8),
item.isDeleted
? ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onRestore == null
? null
: () => onRestore!(item),
child: const Icon(LucideIcons.history, size: 16),
)
: ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onDelete == null
? null
: () => onDelete!(item),
child: const Icon(LucideIcons.trash2, size: 16),
),
],
),
),
);
return cells;
}).toList();
return SizedBox(
height: 56.0 * (menus.length + 1),
child: ShadTable.list(
header: header,
children: rows,
columnSpanExtent: (index) {
switch (index) {
case 4:
return const FixedTableSpanExtent(200);
case 7:
return const FixedTableSpanExtent(200);
case 9:
return const FixedTableSpanExtent(160);
default:
return const FixedTableSpanExtent(120);
}
},
),
);
}
}
class _FormField extends StatelessWidget {
const _FormField({required this.label, required this.child});
final String label;
final Widget child;
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: theme.textTheme.small),
const SizedBox(height: 6),
child,
],
);
}

View File

@@ -2,6 +2,10 @@ import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport_v2/core/constants/app_sections.dart';
import 'package:superport_v2/widgets/app_layout.dart';
import 'package:superport_v2/widgets/components/filter_bar.dart';
import '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
import '../../../uom/domain/entities/uom.dart';
@@ -134,223 +138,188 @@ class _ProductEnabledPageState extends State<_ProductEnabledPage> {
? false
: (result.page * result.pageSize) < result.total;
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
final showReset = _searchController.text.isNotEmpty ||
_controller.vendorFilter != null ||
_controller.uomFilter != null ||
_controller.statusFilter != ProductStatusFilter.all;
return AppLayout(
title: '장비 모델(제품) 관리',
subtitle: '제품코드, 제조사, 단위 정보를 관리합니다.',
breadcrumbs: const [
AppBreadcrumbItem(label: '대시보드', path: dashboardRoutePath),
AppBreadcrumbItem(label: '마스터', path: '/masters/products'),
AppBreadcrumbItem(label: '제품'),
],
actions: [
ShadButton(
leading: const Icon(LucideIcons.plus, size: 16),
onPressed: _controller.isSubmitting
? null
: () => _openProductForm(context),
child: const Text('신규 등록'),
),
],
toolbar: FilterBar(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('장비 모델(제품) 관리', style: theme.textTheme.h2),
const SizedBox(height: 6),
Text(
'제품코드, 제조사, 단위 정보를 관리합니다.',
style: theme.textTheme.muted,
),
],
),
),
const SizedBox(width: 16),
ShadButton(
leading: const Icon(LucideIcons.plus, size: 16),
onPressed: _controller.isSubmitting
? null
: () => _openProductForm(context),
child: const Text('신규 등록'),
),
],
SizedBox(
width: 260,
child: ShadInput(
controller: _searchController,
focusNode: _searchFocus,
placeholder: const Text('제품코드, 제품명 검색'),
leading: const Icon(LucideIcons.search, size: 16),
onSubmitted: (_) => _applyFilters(),
),
),
const SizedBox(height: 24),
ShadCard(
title: Text('검색 및 필터', style: theme.textTheme.h3),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
spacing: 16,
runSpacing: 16,
children: [
SizedBox(
width: 260,
child: ShadInput(
controller: _searchController,
focusNode: _searchFocus,
placeholder: const Text('제품코드, 제품명 검색'),
leading: const Icon(LucideIcons.search, size: 16),
onSubmitted: (_) => _applyFilters(),
),
),
SizedBox(
width: 220,
child: ShadSelect<int?>(
key: ValueKey(_controller.vendorFilter),
initialValue: _controller.vendorFilter,
placeholder: const Text('제조사 전체'),
selectedOptionBuilder: (context, value) {
if (value == null) {
return const Text('제조사 전체');
}
final vendor = _controller.vendorOptions
.firstWhere(
(v) => v.id == value,
orElse: () => Vendor(
id: value,
vendorCode: '',
vendorName: '',
),
);
return Text(vendor.vendorName);
},
onChanged: (value) {
_controller.updateVendorFilter(value);
},
options: [
const ShadOption<int?>(
value: null,
child: Text('제조사 전체'),
),
..._controller.vendorOptions.map(
(vendor) => ShadOption<int?>(
value: vendor.id,
child: Text(vendor.vendorName),
),
),
],
),
),
SizedBox(
width: 220,
child: ShadSelect<int?>(
key: ValueKey(_controller.uomFilter),
initialValue: _controller.uomFilter,
placeholder: const Text('단위 전체'),
selectedOptionBuilder: (context, value) {
if (value == null) {
return const Text('단위 전체');
}
final uom = _controller.uomOptions.firstWhere(
(u) => u.id == value,
orElse: () => Uom(id: value, uomName: ''),
);
return Text(uom.uomName);
},
onChanged: (value) {
_controller.updateUomFilter(value);
},
options: [
const ShadOption<int?>(
value: null,
child: Text('단위 전체'),
),
..._controller.uomOptions.map(
(uom) => ShadOption<int?>(
value: uom.id,
child: Text(uom.uomName),
),
),
],
),
),
SizedBox(
width: 200,
child: ShadSelect<ProductStatusFilter>(
key: ValueKey(_controller.statusFilter),
initialValue: _controller.statusFilter,
selectedOptionBuilder: (context, filter) =>
Text(_statusLabel(filter)),
onChanged: (value) {
if (value == null) return;
_controller.updateStatusFilter(value);
},
options: ProductStatusFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_statusLabel(filter)),
),
)
.toList(),
),
),
ShadButton.outline(
onPressed: _controller.isLoading
? null
: _applyFilters,
child: const Text('검색 적용'),
),
if (_searchController.text.isNotEmpty ||
_controller.vendorFilter != null ||
_controller.uomFilter != null ||
_controller.statusFilter != ProductStatusFilter.all)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateVendorFilter(null);
_controller.updateUomFilter(null);
_controller.updateStatusFilter(
ProductStatusFilter.all,
);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
SizedBox(
width: 220,
child: ShadSelect<int?>(
key: ValueKey(_controller.vendorFilter),
initialValue: _controller.vendorFilter,
placeholder: const Text('제조사 전체'),
selectedOptionBuilder: (context, value) {
if (value == null) {
return const Text('제조사 전체');
}
final vendor = _controller.vendorOptions.firstWhere(
(v) => v.id == value,
orElse: () => Vendor(id: value, vendorCode: '', vendorName: ''),
);
return Text(vendor.vendorName);
},
onChanged: (value) => _controller.updateVendorFilter(value),
options: [
const ShadOption<int?>(
value: null,
child: Text('제조사 전체'),
),
..._controller.vendorOptions.map(
(vendor) => ShadOption<int?>(
value: vendor.id,
child: Text(vendor.vendorName),
),
),
],
),
),
const SizedBox(height: 24),
ShadCard(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('제품 목록', style: theme.textTheme.h3),
Text('$totalCount건', style: theme.textTheme.muted),
],
),
footer: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'페이지 $currentPage / $totalPages',
style: theme.textTheme.small,
SizedBox(
width: 220,
child: ShadSelect<int?>(
key: ValueKey(_controller.uomFilter),
initialValue: _controller.uomFilter,
placeholder: const Text('단위 전체'),
selectedOptionBuilder: (context, value) {
if (value == null) {
return const Text('단위 전체');
}
final uom = _controller.uomOptions.firstWhere(
(u) => u.id == value,
orElse: () => Uom(id: value, uomName: ''),
);
return Text(uom.uomName);
},
onChanged: (value) => _controller.updateUomFilter(value),
options: [
const ShadOption<int?>(
value: null,
child: Text('단위 전체'),
),
Row(
children: [
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || currentPage <= 1
? null
: () => _controller.fetch(page: currentPage - 1),
child: const Text('이전'),
),
const SizedBox(width: 8),
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || !hasNext
? null
: () => _controller.fetch(page: currentPage + 1),
child: const Text('다음'),
),
],
..._controller.uomOptions.map(
(uom) => ShadOption<int?>(
value: uom.id,
child: Text(uom.uomName),
),
),
],
),
child: _controller.isLoading
? const Padding(
padding: EdgeInsets.all(48),
child: Center(child: CircularProgressIndicator()),
),
SizedBox(
width: 200,
child: ShadSelect<ProductStatusFilter>(
key: ValueKey(_controller.statusFilter),
initialValue: _controller.statusFilter,
selectedOptionBuilder: (context, filter) =>
Text(_statusLabel(filter)),
onChanged: (value) {
if (value == null) return;
_controller.updateStatusFilter(value);
},
options: ProductStatusFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_statusLabel(filter)),
),
)
: products.isEmpty
.toList(),
),
),
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
if (showReset)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateVendorFilter(null);
_controller.updateUomFilter(null);
_controller.updateStatusFilter(
ProductStatusFilter.all,
);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
),
child: ShadCard(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('제품 목록', style: theme.textTheme.h3),
Text('$totalCount건', style: theme.textTheme.muted),
],
),
footer: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'페이지 $currentPage / $totalPages',
style: theme.textTheme.small,
),
Row(
children: [
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || currentPage <= 1
? null
: () => _controller.fetch(page: currentPage - 1),
child: const Text('이전'),
),
const SizedBox(width: 8),
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || !hasNext
? null
: () => _controller.fetch(page: currentPage + 1),
child: const Text('다음'),
),
],
),
],
),
child: _controller.isLoading
? const Padding(
padding: EdgeInsets.all(48),
child: Center(child: CircularProgressIndicator()),
)
: products.isEmpty
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
@@ -372,8 +341,6 @@ class _ProductEnabledPageState extends State<_ProductEnabledPage> {
? null
: _restoreProduct,
),
),
],
),
);
},

View File

@@ -2,6 +2,10 @@ import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport_v2/core/constants/app_sections.dart';
import 'package:superport_v2/widgets/app_layout.dart';
import 'package:superport_v2/widgets/components/filter_bar.dart';
import '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
import '../../../group/domain/entities/group.dart';
@@ -143,188 +147,162 @@ class _UserEnabledPageState extends State<_UserEnabledPage> {
? false
: (result.page * result.pageSize) < result.total;
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
final showReset = _searchController.text.isNotEmpty ||
_controller.groupFilter != null ||
_controller.statusFilter != UserStatusFilter.all;
return AppLayout(
title: '사용자(사원) 관리',
subtitle: '사번 기반 계정과 그룹, 사용 상태를 관리합니다.',
breadcrumbs: const [
AppBreadcrumbItem(label: '대시보드', path: dashboardRoutePath),
AppBreadcrumbItem(label: '마스터', path: '/masters/users'),
AppBreadcrumbItem(label: '사용자'),
],
actions: [
ShadButton(
leading: const Icon(LucideIcons.plus, size: 16),
onPressed:
_controller.isSubmitting ? null : () => _openUserForm(context),
child: const Text('신규 등록'),
),
],
toolbar: FilterBar(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('사용자(사원) 관리', style: theme.textTheme.h2),
const SizedBox(height: 6),
Text(
'사번 기반 계정과 그룹, 사용 상태를 관리합니다.',
style: theme.textTheme.muted,
),
],
),
),
const SizedBox(width: 16),
ShadButton(
onPressed: _controller.isSubmitting
? null
: () => _openUserForm(context),
child: const Text('신규 등록'),
),
],
SizedBox(
width: 260,
child: ShadInput(
controller: _searchController,
focusNode: _searchFocus,
placeholder: const Text('사번, 성명, 이메일 검색'),
leading: const Icon(LucideIcons.search, size: 16),
onSubmitted: (_) => _applyFilters(),
),
),
const SizedBox(height: 24),
ShadCard(
title: Text('검색 및 필터', style: theme.textTheme.h3),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
spacing: 16,
runSpacing: 16,
children: [
SizedBox(
width: 260,
child: ShadInput(
controller: _searchController,
focusNode: _searchFocus,
placeholder: const Text('사번, 성명, 이메일 검색'),
leading: const Icon(LucideIcons.search, size: 16),
onSubmitted: (_) => _applyFilters(),
),
),
SizedBox(
width: 220,
child: ShadSelect<int?>(
key: ValueKey(_controller.groupFilter),
initialValue: _controller.groupFilter,
placeholder: Text(
_groupsLoaded ? '그룹 전체' : '그룹 로딩중...',
),
selectedOptionBuilder: (context, value) {
if (value == null) {
return Text(
_groupsLoaded ? '그룹 전체' : '그룹 로딩중...',
);
}
final group = _controller.groups.firstWhere(
(g) => g.id == value,
orElse: () => Group(id: value, groupName: ''),
);
return Text(group.groupName);
},
onChanged: _controller.isLoadingGroups
? null
: (value) {
_controller.updateGroupFilter(value);
},
options: [
const ShadOption<int?>(
value: null,
child: Text('그룹 전체'),
),
..._controller.groups.map(
(group) => ShadOption<int?>(
value: group.id,
child: Text(group.groupName),
),
),
],
),
),
SizedBox(
width: 200,
child: ShadSelect<UserStatusFilter>(
key: ValueKey(_controller.statusFilter),
initialValue: _controller.statusFilter,
selectedOptionBuilder: (context, filter) =>
Text(_statusLabel(filter)),
onChanged: (value) {
if (value == null) return;
_controller.updateStatusFilter(value);
},
options: UserStatusFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_statusLabel(filter)),
),
)
.toList(),
),
),
ShadButton.outline(
onPressed: _controller.isLoading
? null
: _applyFilters,
child: const Text('검색 적용'),
),
if (_searchController.text.isNotEmpty ||
_controller.groupFilter != null ||
_controller.statusFilter != UserStatusFilter.all)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateGroupFilter(null);
_controller.updateStatusFilter(
UserStatusFilter.all,
);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
SizedBox(
width: 220,
child: ShadSelect<int?>(
key: ValueKey(_controller.groupFilter),
initialValue: _controller.groupFilter,
placeholder: Text(
_groupsLoaded ? '그룹 전체' : '그룹 로딩중...',
),
selectedOptionBuilder: (context, value) {
if (value == null) {
return Text(
_groupsLoaded ? '그룹 전체' : '그룹 로딩중...',
);
}
final group = _controller.groups.firstWhere(
(g) => g.id == value,
orElse: () => Group(id: value, groupName: ''),
);
return Text(group.groupName);
},
onChanged: _controller.isLoadingGroups
? null
: (value) {
_controller.updateGroupFilter(value);
},
options: [
const ShadOption<int?>(
value: null,
child: Text('그룹 전체'),
),
..._controller.groups.map(
(group) => ShadOption<int?>(
value: group.id,
child: Text(group.groupName),
),
),
],
),
),
const SizedBox(height: 24),
ShadCard(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('사용자 목록', style: theme.textTheme.h3),
Text('$totalCount건', style: theme.textTheme.muted),
],
),
footer: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'페이지 $currentPage / $totalPages',
style: theme.textTheme.small,
),
Row(
children: [
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || currentPage <= 1
? null
: () => _controller.fetch(page: currentPage - 1),
child: const Text('이전'),
SizedBox(
width: 200,
child: ShadSelect<UserStatusFilter>(
key: ValueKey(_controller.statusFilter),
initialValue: _controller.statusFilter,
selectedOptionBuilder: (context, filter) =>
Text(_statusLabel(filter)),
onChanged: (value) {
if (value == null) return;
_controller.updateStatusFilter(value);
},
options: UserStatusFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_statusLabel(filter)),
),
const SizedBox(width: 8),
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || !hasNext
? null
: () => _controller.fetch(page: currentPage + 1),
child: const Text('다음'),
),
],
),
],
),
child: _controller.isLoading
? const Padding(
padding: EdgeInsets.all(48),
child: Center(child: CircularProgressIndicator()),
)
: users.isEmpty
.toList(),
),
),
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
if (showReset)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateGroupFilter(null);
_controller.updateStatusFilter(
UserStatusFilter.all,
);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
),
child: ShadCard(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('사용자 목록', style: theme.textTheme.h3),
Text('$totalCount건', style: theme.textTheme.muted),
],
),
footer: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'페이지 $currentPage / $totalPages',
style: theme.textTheme.small,
),
Row(
children: [
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || currentPage <= 1
? null
: () => _controller.fetch(page: currentPage - 1),
child: const Text('이전'),
),
const SizedBox(width: 8),
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || !hasNext
? null
: () => _controller.fetch(page: currentPage + 1),
child: const Text('다음'),
),
],
),
],
),
child: _controller.isLoading
? const Padding(
padding: EdgeInsets.all(48),
child: Center(child: CircularProgressIndicator()),
)
: users.isEmpty
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
@@ -344,8 +322,6 @@ class _UserEnabledPageState extends State<_UserEnabledPage> {
? null
: _restoreUser,
),
),
],
),
);
},

View File

@@ -2,6 +2,10 @@ import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport_v2/core/constants/app_sections.dart';
import 'package:superport_v2/widgets/app_layout.dart';
import 'package:superport_v2/widgets/components/filter_bar.dart';
import '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
import '../../../vendor/domain/entities/vendor.dart';
@@ -118,150 +122,122 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
? false
: (result.page * result.pageSize) < result.total;
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
return AppLayout(
title: '제조사(벤더) 관리',
subtitle: '벤더코드, 명칭, 사용여부, 삭제 상태를 관리합니다.',
breadcrumbs: const [
AppBreadcrumbItem(label: '대시보드', path: dashboardRoutePath),
AppBreadcrumbItem(label: '마스터', path: '/masters/vendors'),
AppBreadcrumbItem(label: '벤더'),
],
actions: [
ShadButton(
leading: const Icon(LucideIcons.plus, size: 16),
onPressed: _controller.isSubmitting
? null
: () => _openVendorForm(context),
child: const Text('신규 등록'),
),
],
toolbar: FilterBar(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('제조사(벤더) 관리', style: theme.textTheme.h2),
const SizedBox(height: 6),
Text(
'벤더코드, 명칭, 사용여부, 삭제 상태를 관리합니다.',
style: theme.textTheme.muted,
),
],
),
),
const SizedBox(width: 16),
ShadButton(
leading: const Icon(LucideIcons.plus, size: 16),
onPressed: _controller.isSubmitting
? null
: () => _openVendorForm(context),
child: const Text('신규 등록'),
),
],
),
const SizedBox(height: 24),
ShadCard(
title: Text('검색 및 필터', style: theme.textTheme.h3),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
spacing: 16,
runSpacing: 16,
children: [
SizedBox(
width: 280,
child: ShadInput(
controller: _searchController,
focusNode: _searchFocusNode,
placeholder: const Text('벤더코드, 벤더명 검색'),
leading: const Icon(LucideIcons.search, size: 16),
onSubmitted: (_) => _applyFilters(),
),
),
SizedBox(
width: 220,
child: ShadSelect<VendorStatusFilter>(
key: ValueKey(_controller.statusFilter),
initialValue: _controller.statusFilter,
selectedOptionBuilder: (context, value) =>
Text(_statusLabel(value)),
onChanged: (value) {
if (value != null) {
_controller.updateStatusFilter(value);
_controller.fetch(page: 1);
}
},
options: VendorStatusFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_statusLabel(filter)),
),
)
.toList(),
),
),
ShadButton.outline(
onPressed: _controller.isLoading
? null
: _applyFilters,
child: const Text('검색 적용'),
),
if (_searchController.text.isNotEmpty ||
_controller.statusFilter != VendorStatusFilter.all)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocusNode.requestFocus();
_controller.updateQuery('');
_controller.updateStatusFilter(
VendorStatusFilter.all,
);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
),
],
SizedBox(
width: 280,
child: ShadInput(
controller: _searchController,
focusNode: _searchFocusNode,
placeholder: const Text('벤더코드, 벤더명 검색'),
leading: const Icon(LucideIcons.search, size: 16),
onSubmitted: (_) => _applyFilters(),
),
),
const SizedBox(height: 24),
ShadCard(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('벤더 목록', style: theme.textTheme.h3),
Text('$totalCount건', style: theme.textTheme.muted),
],
),
footer: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'페이지 $currentPage / $totalPages',
style: theme.textTheme.small,
),
Row(
children: [
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || currentPage <= 1
? null
: () => _controller.fetch(page: currentPage - 1),
child: const Text('이전'),
SizedBox(
width: 220,
child: ShadSelect<VendorStatusFilter>(
key: ValueKey(_controller.statusFilter),
initialValue: _controller.statusFilter,
selectedOptionBuilder: (context, value) =>
Text(_statusLabel(value)),
onChanged: (value) {
if (value != null) {
_controller.updateStatusFilter(value);
_controller.fetch(page: 1);
}
},
options: VendorStatusFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_statusLabel(filter)),
),
const SizedBox(width: 8),
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || !hasNext
? null
: () => _controller.fetch(page: currentPage + 1),
child: const Text('다음'),
),
],
),
],
),
child: _controller.isLoading
? const Padding(
padding: EdgeInsets.all(48),
child: Center(child: CircularProgressIndicator()),
)
: vendors.isEmpty
.toList(),
),
),
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
if (_searchController.text.isNotEmpty ||
_controller.statusFilter != VendorStatusFilter.all)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocusNode.requestFocus();
_controller.updateQuery('');
_controller.updateStatusFilter(
VendorStatusFilter.all,
);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
),
child: ShadCard(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('벤더 목록', style: theme.textTheme.h3),
Text('$totalCount건', style: theme.textTheme.muted),
],
),
footer: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'페이지 $currentPage / $totalPages',
style: theme.textTheme.small,
),
Row(
children: [
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || currentPage <= 1
? null
: () => _controller.fetch(page: currentPage - 1),
child: const Text('이전'),
),
const SizedBox(width: 8),
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || !hasNext
? null
: () => _controller.fetch(page: currentPage + 1),
child: const Text('다음'),
),
],
),
],
),
child: _controller.isLoading
? const Padding(
padding: EdgeInsets.all(48),
child: Center(child: CircularProgressIndicator()),
)
: vendors.isEmpty
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
@@ -283,8 +259,6 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
: _restoreVendor,
dateFormat: _dateFormat,
),
),
],
),
);
},

View File

@@ -2,6 +2,10 @@ import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport_v2/core/constants/app_sections.dart';
import 'package:superport_v2/widgets/app_layout.dart';
import 'package:superport_v2/widgets/components/filter_bar.dart';
import '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
import '../../domain/entities/warehouse.dart';
@@ -133,149 +137,122 @@ class _WarehouseEnabledPageState extends State<_WarehouseEnabledPage> {
? false
: (result.page * result.pageSize) < result.total;
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
final showReset = _searchController.text.isNotEmpty ||
_controller.statusFilter != WarehouseStatusFilter.all;
return AppLayout(
title: '입고지(창고) 관리',
subtitle: '창고 코드, 주소, 사용여부를 관리합니다.',
breadcrumbs: const [
AppBreadcrumbItem(label: '대시보드', path: dashboardRoutePath),
AppBreadcrumbItem(label: '마스터', path: '/masters/warehouses'),
AppBreadcrumbItem(label: '창고'),
],
actions: [
ShadButton(
leading: const Icon(LucideIcons.plus, size: 16),
onPressed: _controller.isSubmitting
? null
: () => _openWarehouseForm(context),
child: const Text('신규 등록'),
),
],
toolbar: FilterBar(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('입고지(창고) 관리', style: theme.textTheme.h2),
const SizedBox(height: 6),
Text(
'창고 코드, 주소, 사용여부를 관리합니다.',
style: theme.textTheme.muted,
),
],
),
),
const SizedBox(width: 16),
ShadButton(
leading: const Icon(LucideIcons.plus, size: 16),
onPressed: _controller.isSubmitting
? null
: () => _openWarehouseForm(context),
child: const Text('신규 등록'),
),
],
),
const SizedBox(height: 24),
ShadCard(
title: Text('검색 및 필터', style: theme.textTheme.h3),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
spacing: 16,
runSpacing: 16,
children: [
SizedBox(
width: 260,
child: ShadInput(
controller: _searchController,
focusNode: _searchFocus,
placeholder: const Text('창고코드, 창고명 검색'),
leading: const Icon(LucideIcons.search, size: 16),
onSubmitted: (_) => _applyFilters(),
),
),
SizedBox(
width: 200,
child: ShadSelect<WarehouseStatusFilter>(
key: ValueKey(_controller.statusFilter),
initialValue: _controller.statusFilter,
selectedOptionBuilder: (context, filter) =>
Text(_statusLabel(filter)),
onChanged: (value) {
if (value == null) return;
_controller.updateStatusFilter(value);
},
options: WarehouseStatusFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_statusLabel(filter)),
),
)
.toList(),
),
),
ShadButton.outline(
onPressed: _controller.isLoading
? null
: _applyFilters,
child: const Text('검색 적용'),
),
if (_searchController.text.isNotEmpty ||
_controller.statusFilter !=
WarehouseStatusFilter.all)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateStatusFilter(
WarehouseStatusFilter.all,
);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
),
],
SizedBox(
width: 260,
child: ShadInput(
controller: _searchController,
focusNode: _searchFocus,
placeholder: const Text('창고코드, 창고명 검색'),
leading: const Icon(LucideIcons.search, size: 16),
onSubmitted: (_) => _applyFilters(),
),
),
const SizedBox(height: 24),
ShadCard(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('창고 목록', style: theme.textTheme.h3),
Text('$totalCount건', style: theme.textTheme.muted),
],
),
footer: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'페이지 $currentPage / $totalPages',
style: theme.textTheme.small,
),
Row(
children: [
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || currentPage <= 1
? null
: () => _controller.fetch(page: currentPage - 1),
child: const Text('이전'),
SizedBox(
width: 200,
child: ShadSelect<WarehouseStatusFilter>(
key: ValueKey(_controller.statusFilter),
initialValue: _controller.statusFilter,
selectedOptionBuilder: (context, filter) =>
Text(_statusLabel(filter)),
onChanged: (value) {
if (value == null) return;
_controller.updateStatusFilter(value);
},
options: WarehouseStatusFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_statusLabel(filter)),
),
const SizedBox(width: 8),
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || !hasNext
? null
: () => _controller.fetch(page: currentPage + 1),
child: const Text('다음'),
),
],
),
],
),
child: _controller.isLoading
? const Padding(
padding: EdgeInsets.all(48),
child: Center(child: CircularProgressIndicator()),
)
: warehouses.isEmpty
.toList(),
),
),
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
if (showReset)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateStatusFilter(
WarehouseStatusFilter.all,
);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
),
child: ShadCard(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('창고 목록', style: theme.textTheme.h3),
Text('$totalCount건', style: theme.textTheme.muted),
],
),
footer: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'페이지 $currentPage / $totalPages',
style: theme.textTheme.small,
),
Row(
children: [
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || currentPage <= 1
? null
: () => _controller.fetch(page: currentPage - 1),
child: const Text('이전'),
),
const SizedBox(width: 8),
ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || !hasNext
? null
: () => _controller.fetch(page: currentPage + 1),
child: const Text('다음'),
),
],
),
],
),
child: _controller.isLoading
? const Padding(
padding: EdgeInsets.all(48),
child: Center(child: CircularProgressIndicator()),
)
: warehouses.isEmpty
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
@@ -288,10 +265,8 @@ class _WarehouseEnabledPageState extends State<_WarehouseEnabledPage> {
dateFormat: _dateFormat,
onEdit: _controller.isSubmitting
? null
: (warehouse) => _openWarehouseForm(
context,
warehouse: warehouse,
),
: (warehouse) =>
_openWarehouseForm(context, warehouse: warehouse),
onDelete: _controller.isSubmitting
? null
: _confirmDelete,
@@ -299,8 +274,6 @@ class _WarehouseEnabledPageState extends State<_WarehouseEnabledPage> {
? null
: _restoreWarehouse,
),
),
],
),
);
},