전역 구조 리팩터링 및 테스트 확장

This commit is contained in:
JiWoong Sul
2025-09-29 01:51:47 +09:00
parent c00c0c9ab2
commit fef7108479
70 changed files with 7709 additions and 3185 deletions

View File

@@ -11,6 +11,8 @@ enum VendorStatusFilter { all, activeOnly, inactiveOnly }
/// - 목록/검색/필터/페이지 상태를 관리한다.
/// - 생성/수정/삭제/복구 요청을 래핑하여 UI에 알린다.
class VendorController extends ChangeNotifier {
static const int defaultPageSize = 20;
VendorController({required VendorRepository repository})
: _repository = repository;
@@ -21,6 +23,7 @@ class VendorController extends ChangeNotifier {
bool _isSubmitting = false;
String _query = '';
VendorStatusFilter _statusFilter = VendorStatusFilter.all;
int _pageSize = defaultPageSize;
String? _errorMessage;
PaginatedResult<Vendor>? get result => _result;
@@ -28,6 +31,7 @@ class VendorController extends ChangeNotifier {
bool get isSubmitting => _isSubmitting;
String get query => _query;
VendorStatusFilter get statusFilter => _statusFilter;
int get pageSize => _pageSize;
String? get errorMessage => _errorMessage;
/// 목록 갱신
@@ -43,11 +47,14 @@ class VendorController extends ChangeNotifier {
};
final response = await _repository.list(
page: page,
pageSize: _result?.pageSize ?? 20,
pageSize: _pageSize,
query: _query.isEmpty ? null : _query,
isActive: isActive,
);
_result = response;
if (response.pageSize > 0 && response.pageSize != _pageSize) {
_pageSize = response.pageSize;
}
} catch (e) {
_errorMessage = e.toString();
} finally {
@@ -57,15 +64,29 @@ class VendorController extends ChangeNotifier {
}
void updateQuery(String value) {
if (_query == value) {
return;
}
_query = value;
notifyListeners();
}
void updateStatusFilter(VendorStatusFilter filter) {
if (_statusFilter == filter) {
return;
}
_statusFilter = filter;
notifyListeners();
}
void updatePageSize(int size) {
if (size <= 0 || _pageSize == size) {
return;
}
_pageSize = size;
notifyListeners();
}
/// 신규 등록
Future<Vendor?> create(VendorInput input) async {
_setSubmitting(true);

View File

@@ -1,10 +1,13 @@
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:go_router/go_router.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 'package:superport_v2/widgets/components/superport_dialog.dart';
import 'package:superport_v2/widgets/components/superport_table.dart';
import '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
@@ -13,7 +16,9 @@ import '../../../vendor/domain/repositories/vendor_repository.dart';
import '../controllers/vendor_controller.dart';
class VendorPage extends StatelessWidget {
const VendorPage({super.key});
const VendorPage({super.key, required this.routeUri});
final Uri routeUri;
@override
Widget build(BuildContext context) {
@@ -58,12 +63,14 @@ class VendorPage extends StatelessWidget {
);
}
return const _VendorEnabledPage();
return _VendorEnabledPage(routeUri: routeUri);
}
}
class _VendorEnabledPage extends StatefulWidget {
const _VendorEnabledPage();
const _VendorEnabledPage({required this.routeUri});
final Uri routeUri;
@override
State<_VendorEnabledPage> createState() => _VendorEnabledPageState();
@@ -75,13 +82,22 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
final FocusNode _searchFocusNode = FocusNode();
final DateFormat _dateFormat = DateFormat('yyyy-MM-dd HH:mm');
String? _lastError;
bool _routeApplied = false;
@override
void initState() {
super.initState();
_controller = VendorController(repository: GetIt.I<VendorRepository>());
_controller.addListener(_onControllerChanged);
WidgetsBinding.instance.addPostFrameCallback((_) => _controller.fetch());
_controller = VendorController(repository: GetIt.I<VendorRepository>())
..addListener(_onControllerChanged);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (!_routeApplied) {
_routeApplied = true;
_applyRouteParameters();
}
}
@override
@@ -140,6 +156,32 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
),
],
toolbar: FilterBar(
actions: [
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,
);
_updateRoute(
page: 1,
queryOverride: '',
statusOverride: VendorStatusFilter.all,
);
},
child: const Text('초기화'),
),
],
children: [
SizedBox(
width: 280,
@@ -159,10 +201,9 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
selectedOptionBuilder: (context, value) =>
Text(_statusLabel(value)),
onChanged: (value) {
if (value != null) {
_controller.updateStatusFilter(value);
_controller.fetch(page: 1);
}
if (value == null) return;
_controller.updateStatusFilter(value);
_updateRoute(page: 1, statusOverride: value);
},
options: VendorStatusFilter.values
.map(
@@ -174,26 +215,6 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
.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(
@@ -217,7 +238,7 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || currentPage <= 1
? null
: () => _controller.fetch(page: currentPage - 1),
: () => _goToPage(currentPage - 1),
child: const Text('이전'),
),
const SizedBox(width: 8),
@@ -225,7 +246,7 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || !hasNext
? null
: () => _controller.fetch(page: currentPage + 1),
: () => _goToPage(currentPage + 1),
child: const Text('다음'),
),
],
@@ -238,27 +259,22 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
child: Center(child: CircularProgressIndicator()),
)
: vendors.isEmpty
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
'조건에 맞는 벤더가 없습니다.',
style: theme.textTheme.muted,
),
)
: _VendorTable(
vendors: vendors,
onEdit: _controller.isSubmitting
? null
: (vendor) =>
_openVendorForm(context, vendor: vendor),
onDelete: _controller.isSubmitting
? null
: _confirmDelete,
onRestore: _controller.isSubmitting
? null
: _restoreVendor,
dateFormat: _dateFormat,
),
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
'조건에 맞는 벤더가 없습니다.',
style: theme.textTheme.muted,
),
)
: _VendorTable(
vendors: vendors,
onEdit: _controller.isSubmitting
? null
: (vendor) => _openVendorForm(context, vendor: vendor),
onDelete: _controller.isSubmitting ? null : _confirmDelete,
onRestore: _controller.isSubmitting ? null : _restoreVendor,
dateFormat: _dateFormat,
),
),
);
},
@@ -266,8 +282,9 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
}
void _applyFilters() {
_controller.updateQuery(_searchController.text.trim());
_controller.fetch(page: 1);
final keyword = _searchController.text.trim();
_controller.updateQuery(keyword);
_updateRoute(page: 1, queryOverride: keyword);
}
String _statusLabel(VendorStatusFilter filter) {
@@ -281,6 +298,90 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
}
}
void _applyRouteParameters() {
final params = widget.routeUri.queryParameters;
final query = params['q'] ?? '';
final status = _statusFromParam(params['status']);
final pageSizeParam = int.tryParse(params['page_size'] ?? '');
final pageParam = int.tryParse(params['page'] ?? '');
_searchController.text = query;
_controller.updateQuery(query);
_controller.updateStatusFilter(status);
if (pageSizeParam != null && pageSizeParam > 0) {
_controller.updatePageSize(pageSizeParam);
}
final page = pageParam != null && pageParam > 0 ? pageParam : 1;
_controller.fetch(page: page);
}
void _goToPage(int page) {
if (page < 1) {
page = 1;
}
_updateRoute(page: page);
}
void _updateRoute({
required int page,
String? queryOverride,
VendorStatusFilter? statusOverride,
int? pageSizeOverride,
}) {
final query = queryOverride ?? _controller.query;
final status = statusOverride ?? _controller.statusFilter;
final pageSize = pageSizeOverride ?? _controller.pageSize;
final params = <String, String>{};
if (query.isNotEmpty) {
params['q'] = query;
}
final statusParam = _encodeStatus(status);
if (statusParam != null) {
params['status'] = statusParam;
}
if (page > 1) {
params['page'] = page.toString();
}
if (pageSize > 0 && pageSize != VendorController.defaultPageSize) {
params['page_size'] = pageSize.toString();
}
final uri = Uri(
path: widget.routeUri.path,
queryParameters: params.isEmpty ? null : params,
);
final newLocation = uri.toString();
if (widget.routeUri.toString() == newLocation) {
_controller.fetch(page: page);
return;
}
GoRouter.of(context).go(newLocation);
}
VendorStatusFilter _statusFromParam(String? value) {
switch (value) {
case 'active':
return VendorStatusFilter.activeOnly;
case 'inactive':
return VendorStatusFilter.inactiveOnly;
default:
return VendorStatusFilter.all;
}
}
String? _encodeStatus(VendorStatusFilter filter) {
switch (filter) {
case VendorStatusFilter.all:
return null;
case VendorStatusFilter.activeOnly:
return 'active';
case VendorStatusFilter.inactiveOnly:
return 'inactive';
}
}
Future<void> _openVendorForm(BuildContext context, {Vendor? vendor}) async {
final existingVendor = vendor;
final isEdit = existingVendor != null;
@@ -306,201 +407,183 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
final codeError = ValueNotifier<String?>(null);
final nameError = ValueNotifier<String?>(null);
await showDialog<bool>(
await SuperportDialog.show<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: 520),
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 note = noteController.text.trim();
dialog: SuperportDialog(
title: isEdit ? '벤더 수정' : '벤더 등록',
description: '벤더 기본 정보를 ${isEdit ? '수정' : '입력'}하세요.',
constraints: const BoxConstraints(maxWidth: 520),
primaryAction: ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (context, isSaving, _) {
return ShadButton(
onPressed: isSaving
? null
: () async {
final code = codeController.text.trim();
final name = nameController.text.trim();
final note = noteController.text.trim();
codeError.value = code.isEmpty
? '벤더코드를 입력하세요.'
: null;
nameError.value = name.isEmpty
? '벤더명을 입력하세요.'
: null;
codeError.value = code.isEmpty ? '벤더코드를 입력하세요.' : null;
nameError.value = name.isEmpty ? '벤더명을 입력하세요.' : null;
if (codeError.value != null ||
nameError.value != null) {
return;
}
if (codeError.value != null || nameError.value != null) {
return;
}
saving.value = true;
final input = VendorInput(
vendorCode: code,
vendorName: name,
isActive: isActiveNotifier.value,
note: note.isEmpty ? null : note,
);
final response = isEdit
? await _controller.update(vendorId!, input)
: await _controller.create(input);
saving.value = false;
if (response != null) {
if (!navigator.mounted) {
return;
}
if (mounted) {
_showSnack(
isEdit ? '벤더를 수정했습니다.' : '벤더를 등록했습니다.',
);
}
navigator.pop(true);
saving.value = true;
final input = VendorInput(
vendorCode: code,
vendorName: name,
isActive: isActiveNotifier.value,
note: note.isEmpty ? null : note,
);
final navigator = Navigator.of(context);
final response = isEdit
? await _controller.update(vendorId!, input)
: await _controller.create(input);
saving.value = false;
if (response != null && mounted) {
if (!navigator.mounted) {
return;
}
_showSnack(isEdit ? '벤더를 수정했습니다.' : '벤더를 등록했습니다.');
navigator.pop(true);
}
},
child: Text(isEdit ? '저장' : '등록'),
);
},
),
secondaryAction: ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (context, isSaving, _) {
return ShadButton.ghost(
onPressed: isSaving
? null
: () => Navigator.of(context).pop(false),
child: const Text('취소'),
);
},
),
child: Builder(
builder: (dialogContext) {
final theme = ShadTheme.of(dialogContext);
final materialTheme = Theme.of(dialogContext);
return Padding(
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;
}
},
child: Text(isEdit ? '저장' : '등록'),
),
],
);
},
),
child: Padding(
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,
),
),
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<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<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),
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(existingVendor.createdAt)}',
style: theme.textTheme.small,
),
const SizedBox(height: 16),
_FormField(
label: '비고',
child: ShadTextarea(controller: noteController),
const SizedBox(height: 4),
Text(
'수정일시: ${_formatDateTime(existingVendor.updatedAt)}',
style: theme.textTheme.small,
),
if (isEdit) ...[
const SizedBox(height: 20),
Text(
'생성일시: ${_formatDateTime(existingVendor.createdAt)}',
style: theme.textTheme.small,
),
const SizedBox(height: 4),
Text(
'수정일시: ${_formatDateTime(existingVendor.updatedAt)}',
style: theme.textTheme.small,
),
],
],
),
],
),
),
),
);
},
);
},
),
),
);
codeController.dispose();
@@ -513,24 +596,22 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
}
Future<void> _confirmDelete(Vendor vendor) async {
final confirmed = await showDialog<bool>(
final confirmed = await SuperportDialog.show<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: const Text('벤더 삭제'),
content: Text('"${vendor.vendorName}" 벤더를 삭제하시겠습니까?'),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('취소'),
),
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('삭제'),
),
],
);
},
dialog: SuperportDialog(
title: '벤더 삭제',
description: '"${vendor.vendorName}" 벤더 삭제하시겠습니까?',
actions: [
ShadButton.ghost(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('취소'),
),
ShadButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('삭제'),
),
],
),
);
if (confirmed == true && vendor.id != null) {
@@ -581,39 +662,43 @@ class _VendorTable extends StatelessWidget {
@override
Widget build(BuildContext context) {
final header = [
'ID',
'벤더코드',
'벤더명',
'사용',
'삭제',
'비고',
'변경일시',
'동작',
].map((text) => ShadTableCell.header(child: Text(text))).toList();
final columns = const [
Text('ID'),
Text('벤더코드'),
Text('벤더명'),
Text('사용'),
Text('삭제'),
Text('비고'),
Text('변경일시'),
Text('동작'),
];
final rows = vendors.map((vendor) {
return [
vendor.id?.toString() ?? '-',
vendor.vendorCode,
vendor.vendorName,
vendor.isActive ? 'Y' : 'N',
vendor.isDeleted ? 'Y' : '-',
vendor.note?.isEmpty ?? true ? '-' : vendor.note!,
vendor.updatedAt == null
? '-'
: dateFormat.format(vendor.updatedAt!.toLocal()),
].map((text) => ShadTableCell(child: Text(text))).toList()..add(
final cells = <Widget>[
Text(vendor.id?.toString() ?? '-'),
Text(vendor.vendorCode),
Text(vendor.vendorName),
Text(vendor.isActive ? 'Y' : 'N'),
Text(vendor.isDeleted ? 'Y' : '-'),
Text(vendor.note?.isEmpty ?? true ? '-' : vendor.note!),
Text(
vendor.updatedAt == null
? '-'
: dateFormat.format(vendor.updatedAt!.toLocal()),
),
];
cells.add(
ShadTableCell(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
alignment: Alignment.centerRight,
child: Wrap(
spacing: 8,
children: [
ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onEdit == null ? null : () => onEdit!(vendor),
child: const Icon(LucideIcons.pencil, size: 16),
),
const SizedBox(width: 8),
vendor.isDeleted
? ShadButton.ghost(
size: ShadButtonSize.sm,
@@ -633,17 +718,18 @@ class _VendorTable extends StatelessWidget {
),
),
);
return cells;
}).toList();
return SizedBox(
height: 56.0 * (vendors.length + 1),
child: ShadTable.list(
header: header,
children: rows,
columnSpanExtent: (index) => index == 7
? const FixedTableSpanExtent(160)
: const FixedTableSpanExtent(140),
),
return SuperportTable(
columns: columns,
rows: rows,
rowHeight: 56,
maxHeight: 520,
columnSpanExtent: (index) => index == 7
? const FixedTableSpanExtent(160)
: const FixedTableSpanExtent(140),
);
}
}