마스터 고객/제품/창고 테스트 및 UI 구현

This commit is contained in:
JiWoong Sul
2025-09-22 20:30:08 +09:00
parent 5c9de2594a
commit 2d27d1bb5c
41 changed files with 6764 additions and 259 deletions

View File

@@ -0,0 +1,142 @@
import 'package:flutter/foundation.dart';
import 'package:superport_v2/core/common/models/paginated_result.dart';
import '../../domain/entities/vendor.dart';
import '../../domain/repositories/vendor_repository.dart';
enum VendorStatusFilter { all, activeOnly, inactiveOnly }
/// 벤더 화면 상태 컨트롤러
///
/// - 목록/검색/필터/페이지 상태를 관리한다.
/// - 생성/수정/삭제/복구 요청을 래핑하여 UI에 알린다.
class VendorController extends ChangeNotifier {
VendorController({required VendorRepository repository})
: _repository = repository;
final VendorRepository _repository;
PaginatedResult<Vendor>? _result;
bool _isLoading = false;
bool _isSubmitting = false;
String _query = '';
VendorStatusFilter _statusFilter = VendorStatusFilter.all;
String? _errorMessage;
PaginatedResult<Vendor>? get result => _result;
bool get isLoading => _isLoading;
bool get isSubmitting => _isSubmitting;
String get query => _query;
VendorStatusFilter get statusFilter => _statusFilter;
String? get errorMessage => _errorMessage;
/// 목록 갱신
Future<void> fetch({int page = 1}) async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
try {
final isActive = switch (_statusFilter) {
VendorStatusFilter.all => null,
VendorStatusFilter.activeOnly => true,
VendorStatusFilter.inactiveOnly => false,
};
final response = await _repository.list(
page: page,
pageSize: _result?.pageSize ?? 20,
query: _query.isEmpty ? null : _query,
isActive: isActive,
);
_result = response;
} catch (e) {
_errorMessage = e.toString();
} finally {
_isLoading = false;
notifyListeners();
}
}
void updateQuery(String value) {
_query = value;
notifyListeners();
}
void updateStatusFilter(VendorStatusFilter filter) {
_statusFilter = filter;
notifyListeners();
}
/// 신규 등록
Future<Vendor?> create(VendorInput input) async {
_setSubmitting(true);
try {
final vendor = await _repository.create(input);
await fetch(page: 1);
return vendor;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return null;
} finally {
_setSubmitting(false);
}
}
/// 수정
Future<Vendor?> update(int id, VendorInput input) async {
_setSubmitting(true);
try {
final vendor = await _repository.update(id, input);
await fetch(page: _result?.page ?? 1);
return vendor;
} 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<Vendor?> restore(int id) async {
_setSubmitting(true);
try {
final vendor = await _repository.restore(id);
await fetch(page: _result?.page ?? 1);
return vendor;
} 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

@@ -6,6 +6,7 @@ import '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
import '../../../vendor/domain/entities/vendor.dart';
import '../../../vendor/domain/repositories/vendor_repository.dart';
import '../controllers/vendor_controller.dart';
class VendorPage extends StatelessWidget {
const VendorPage({super.key});
@@ -65,111 +66,630 @@ class _VendorEnabledPage extends StatefulWidget {
}
class _VendorEnabledPageState extends State<_VendorEnabledPage> {
final _repo = GetIt.I<VendorRepository>();
final _loading = ValueNotifier(false);
final _vendors = ValueNotifier<List<Vendor>>([]);
late final VendorController _controller;
final TextEditingController _searchController = TextEditingController();
final FocusNode _searchFocusNode = FocusNode();
final DateFormat _dateFormat = DateFormat('yyyy-MM-dd HH:mm');
String? _lastError;
@override
void initState() {
super.initState();
_controller = VendorController(repository: GetIt.I<VendorRepository>());
_controller.addListener(_onControllerChanged);
WidgetsBinding.instance.addPostFrameCallback((_) => _controller.fetch());
}
@override
void dispose() {
_loading.dispose();
_vendors.dispose();
_controller.removeListener(_onControllerChanged);
_controller.dispose();
_searchController.dispose();
_searchFocusNode.dispose();
super.dispose();
}
Future<void> _load() async {
_loading.value = true;
try {
final list = await _repo.list(page: 1, pageSize: 50);
_vendors.value = list;
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('벤더 조회 실패: $e')),
);
}
} finally {
_loading.value = false;
void _onControllerChanged() {
final error = _controller.errorMessage;
if (error != null && error != _lastError && mounted) {
_lastError = error;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(error)));
_controller.clearError();
}
}
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
return AnimatedBuilder(
animation: _controller,
builder: (context, _) {
final result = _controller.result;
final vendors = result?.items ?? const <Vendor>[];
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;
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Column(
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('제조사(벤더) 관리', style: theme.textTheme.h2),
const SizedBox(height: 6),
Text('벤더코드, 명칭, 사용여부 관리', style: theme.textTheme.muted),
],
),
Row(
children: [
ValueListenableBuilder<bool>(
valueListenable: _loading,
builder: (_, loading, __) {
return ShadButton(
onPressed: loading ? null : _load,
child: Text(loading ? '로딩 중...' : '데이터 조회'),
);
},
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('초기화'),
),
],
),
],
),
),
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('이전'),
),
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(
'조건에 맞는 벤더가 없습니다.',
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,
),
),
],
),
const SizedBox(height: 16),
ShadCard(
title: Text('벤더 목록', style: theme.textTheme.h3),
child: ValueListenableBuilder<List<Vendor>>(
valueListenable: _vendors,
builder: (_, vendors, __) {
if (vendors.isEmpty) {
return Padding(
padding: const EdgeInsets.all(24),
child: Text('데이터가 없습니다. 상단의 "데이터 조회"를 눌러주세요.',
style: theme.textTheme.muted),
);
},
);
}
void _applyFilters() {
_controller.updateQuery(_searchController.text.trim());
_controller.fetch(page: 1);
}
String _statusLabel(VendorStatusFilter filter) {
switch (filter) {
case VendorStatusFilter.all:
return '전체(사용/미사용)';
case VendorStatusFilter.activeOnly:
return '사용중';
case VendorStatusFilter.inactiveOnly:
return '미사용';
}
}
Future<void> _openVendorForm(BuildContext context, {Vendor? vendor}) async {
final existingVendor = vendor;
final isEdit = existingVendor != null;
final vendorId = existingVendor?.id;
if (isEdit && vendorId == null) {
_showSnack('ID 정보가 없어 수정할 수 없습니다.');
return;
}
final codeController = TextEditingController(
text: existingVendor?.vendorCode ?? '',
);
final nameController = TextEditingController(
text: existingVendor?.vendorName ?? '',
);
final noteController = TextEditingController(
text: existingVendor?.note ?? '',
);
final isActiveNotifier = ValueNotifier<bool>(
existingVendor?.isActive ?? true,
);
final saving = ValueNotifier<bool>(false);
final codeError = ValueNotifier<String?>(null);
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: 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();
codeError.value = code.isEmpty
? '벤더코드를 입력하세요.'
: null;
nameError.value = name.isEmpty
? '벤더명을 입력하세요.'
: null;
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);
}
},
child: Text(isEdit ? '저장' : '등록'),
),
],
);
}
return SizedBox(
height: 56.0 * (vendors.length + 1),
child: ShadTable.list(
header: const [
'ID',
'벤더코드',
'벤더명',
'사용',
'비고',
'변경일시',
].map((h) => ShadTableCell.header(child: Text(h))).toList(),
children: vendors
.map(
(v) => [
'${v.id ?? '-'}',
v.vendorCode,
v.vendorName,
v.isActive ? 'Y' : 'N',
v.note ?? '-',
v.updatedAt?.toIso8601String() ?? '-',
].map((c) => ShadTableCell(child: Text(c))).toList(),
)
.toList(),
columnSpanExtent: (index) => const FixedTableSpanExtent(160),
),
);
},
},
),
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,
),
),
),
],
),
);
},
),
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),
_FormField(
label: '비고',
child: ShadTextarea(controller: noteController),
),
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();
nameController.dispose();
noteController.dispose();
isActiveNotifier.dispose();
saving.dispose();
codeError.dispose();
nameError.dispose();
}
Future<void> _confirmDelete(Vendor vendor) async {
final confirmed = await showDialog<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('삭제'),
),
],
);
},
);
if (confirmed == true && vendor.id != null) {
final success = await _controller.delete(vendor.id!);
if (success && mounted) {
_showSnack('벤더를 삭제했습니다.');
}
}
}
Future<void> _restoreVendor(Vendor vendor) async {
if (vendor.id == null) return;
final restored = await _controller.restore(vendor.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 _VendorTable extends StatelessWidget {
const _VendorTable({
required this.vendors,
required this.onEdit,
required this.onDelete,
required this.onRestore,
required this.dateFormat,
});
final List<Vendor> vendors;
final void Function(Vendor vendor)? onEdit;
final void Function(Vendor vendor)? onDelete;
final void Function(Vendor vendor)? onRestore;
final DateFormat dateFormat;
@override
Widget build(BuildContext context) {
final header = [
'ID',
'벤더코드',
'벤더명',
'사용',
'삭제',
'비고',
'변경일시',
'동작',
].map((text) => ShadTableCell.header(child: Text(text))).toList();
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(
ShadTableCell(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
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,
onPressed: onRestore == null
? null
: () => onRestore!(vendor),
child: const Icon(LucideIcons.history, size: 16),
)
: ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onDelete == null
? null
: () => onDelete!(vendor),
child: const Icon(LucideIcons.trash2, size: 16),
),
],
),
),
);
}).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),
),
);
}
}
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,
],
);
}
}