결재 템플릿 단계 적용 구현

- 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

@@ -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,
],
);
}