마스터 고객/제품/창고 테스트 및 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

@@ -1,59 +1,759 @@
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 '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
import '../../domain/entities/warehouse.dart';
import '../../domain/repositories/warehouse_repository.dart';
import '../controllers/warehouse_controller.dart';
class WarehousePage extends StatelessWidget {
const WarehousePage({super.key});
@override
Widget build(BuildContext context) {
return const SpecPage(
title: '입고지(창고) 관리',
summary: '창고 주소와 사용 여부를 구성합니다.',
sections: [
SpecSection(
title: '입력 폼',
items: [
'창고코드 [Text]',
'창고명 [Text]',
'우편번호 [검색 연동]',
'상세주소 [Text]',
'사용여부 [Switch]',
'비고 [Text]',
],
),
SpecSection(
title: '수정 폼',
items: ['창고코드 [ReadOnly]', '생성일시 [ReadOnly]'],
),
SpecSection(
title: '테이블 리스트',
description: '1행 예시',
table: SpecTable(
columns: [
'번호',
'창고코드',
'창고명',
'우편번호',
'상세주소',
'사용여부',
'비고',
'변경일시',
final enabled = Environment.flag('FEATURE_WAREHOUSES_ENABLED');
if (!enabled) {
return const SpecPage(
title: '입고지(창고) 관리',
summary: '창고 코드, 주소, 사용여부를 관리합니다.',
sections: [
SpecSection(
title: '입력 폼',
items: [
'창고코드 [Text]',
'창고명 [Text]',
'우편번호 [Text+검색]',
'상세주소 [Text]',
'사용여부 [Switch]',
'비고 [Text]',
],
rows: [
[
'1',
'WH-01',
'서울 1창고',
'04532',
'서울시 중구 을지로 100',
'Y',
'-',
'2024-03-01 10:00',
),
SpecSection(
title: '수정 폼',
items: ['창고코드 [ReadOnly]', '생성일시 [ReadOnly]'],
),
SpecSection(
title: '테이블 리스트',
description: '1행 예시',
table: SpecTable(
columns: [
'번호',
'창고코드',
'창고명',
'우편번호',
'상세주소',
'사용여부',
'비고',
'변경일시',
],
rows: [
[
'1',
'WH-001',
'서울 1창고',
'06000',
'강남대로 123',
'Y',
'-',
'2024-03-01 10:00',
],
],
),
),
],
);
}
return const _WarehouseEnabledPage();
}
}
class _WarehouseEnabledPage extends StatefulWidget {
const _WarehouseEnabledPage();
@override
State<_WarehouseEnabledPage> createState() => _WarehouseEnabledPageState();
}
class _WarehouseEnabledPageState extends State<_WarehouseEnabledPage> {
late final WarehouseController _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 = WarehouseController(
repository: GetIt.I<WarehouseRepository>(),
)..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 warehouses = result?.items ?? const <Warehouse>[];
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: [
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('초기화'),
),
],
),
],
),
),
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()),
)
: warehouses.isEmpty
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
'조건에 맞는 창고가 없습니다.',
style: theme.textTheme.muted,
),
)
: _WarehouseTable(
warehouses: warehouses,
dateFormat: _dateFormat,
onEdit: _controller.isSubmitting
? null
: (warehouse) => _openWarehouseForm(
context,
warehouse: warehouse,
),
onDelete: _controller.isSubmitting
? null
: _confirmDelete,
onRestore: _controller.isSubmitting
? null
: _restoreWarehouse,
),
),
],
),
);
},
);
}
void _applyFilters() {
_controller.updateQuery(_searchController.text.trim());
_controller.fetch(page: 1);
}
String _statusLabel(WarehouseStatusFilter filter) {
switch (filter) {
case WarehouseStatusFilter.all:
return '전체(사용/미사용)';
case WarehouseStatusFilter.activeOnly:
return '사용중';
case WarehouseStatusFilter.inactiveOnly:
return '미사용';
}
}
Future<void> _openWarehouseForm(
BuildContext context, {
Warehouse? warehouse,
}) async {
final existing = warehouse;
final isEdit = existing != null;
final warehouseId = existing?.id;
if (isEdit && warehouseId == null) {
_showSnack('ID 정보가 없어 수정할 수 없습니다.');
return;
}
final codeController = TextEditingController(
text: existing?.warehouseCode ?? '',
);
final nameController = TextEditingController(
text: existing?.warehouseName ?? '',
);
final zipcodeController = TextEditingController(
text: existing?.zipcode?.zipcode ?? '',
);
final addressController = TextEditingController(
text: existing?.addressDetail ?? '',
);
final noteController = TextEditingController(text: existing?.note ?? '');
final isActiveNotifier = ValueNotifier<bool>(existing?.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: 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 code = codeController.text.trim();
final name = nameController.text.trim();
final zipcode = zipcodeController.text.trim();
final address = addressController.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 = WarehouseInput(
warehouseCode: code,
warehouseName: name,
zipcode: zipcode.isEmpty ? null : zipcode,
addressDetail: address.isEmpty
? null
: address,
isActive: isActiveNotifier.value,
note: note.isEmpty ? null : note,
);
final response = isEdit
? await _controller.update(
warehouseId!,
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: 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),
_FormField(
label: '우편번호',
child: ShadInput(
controller: zipcodeController,
placeholder: const Text('예: 06000'),
),
),
const SizedBox(height: 16),
_FormField(
label: '상세주소',
child: ShadInput(
controller: addressController,
placeholder: const Text('상세주소 입력'),
),
),
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(existing.createdAt)}',
style: theme.textTheme.small,
),
const SizedBox(height: 4),
Text(
'수정일시: ${_formatDateTime(existing.updatedAt)}',
style: theme.textTheme.small,
),
],
],
),
),
),
),
);
},
);
if (!mounted) {
codeController.dispose();
nameController.dispose();
zipcodeController.dispose();
addressController.dispose();
noteController.dispose();
isActiveNotifier.dispose();
saving.dispose();
codeError.dispose();
nameError.dispose();
return;
}
codeController.dispose();
nameController.dispose();
zipcodeController.dispose();
addressController.dispose();
noteController.dispose();
isActiveNotifier.dispose();
saving.dispose();
codeError.dispose();
nameError.dispose();
}
Future<void> _confirmDelete(Warehouse warehouse) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: const Text('창고 삭제'),
content: Text('"${warehouse.warehouseName}" 창고를 삭제하시겠습니까?'),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('취소'),
),
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('삭제'),
),
],
);
},
);
if (confirmed == true && warehouse.id != null) {
final success = await _controller.delete(warehouse.id!);
if (success && mounted) {
_showSnack('창고를 삭제했습니다.');
}
}
}
Future<void> _restoreWarehouse(Warehouse warehouse) async {
if (warehouse.id == null) return;
final restored = await _controller.restore(warehouse.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 _WarehouseTable extends StatelessWidget {
const _WarehouseTable({
required this.warehouses,
required this.dateFormat,
required this.onEdit,
required this.onDelete,
required this.onRestore,
});
final List<Warehouse> warehouses;
final DateFormat dateFormat;
final void Function(Warehouse warehouse)? onEdit;
final void Function(Warehouse warehouse)? onDelete;
final void Function(Warehouse warehouse)? onRestore;
@override
Widget build(BuildContext context) {
final header = [
'ID',
'창고코드',
'창고명',
'우편번호',
'상세주소',
'사용',
'삭제',
'비고',
'변경일시',
'동작',
].map((text) => ShadTableCell.header(child: Text(text))).toList();
final rows = warehouses.map((warehouse) {
return [
warehouse.id?.toString() ?? '-',
warehouse.warehouseCode,
warehouse.warehouseName,
warehouse.zipcode?.zipcode ?? '-',
warehouse.addressDetail?.isEmpty ?? true
? '-'
: warehouse.addressDetail!,
warehouse.isActive ? 'Y' : 'N',
warehouse.isDeleted ? 'Y' : '-',
warehouse.note?.isEmpty ?? true ? '-' : warehouse.note!,
warehouse.updatedAt == null
? '-'
: dateFormat.format(warehouse.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!(warehouse),
child: const Icon(LucideIcons.pencil, size: 16),
),
const SizedBox(width: 8),
warehouse.isDeleted
? ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onRestore == null
? null
: () => onRestore!(warehouse),
child: const Icon(LucideIcons.history, size: 16),
)
: ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onDelete == null
? null
: () => onDelete!(warehouse),
child: const Icon(LucideIcons.trash2, size: 16),
),
],
),
),
);
}).toList();
return SizedBox(
height: 56.0 * (warehouses.length + 1),
child: ShadTable.list(
header: header,
children: rows,
columnSpanExtent: (index) => index == 9
? 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,
],
);
}