마스터 고객/제품/창고 테스트 및 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,183 @@
import 'package:flutter/foundation.dart';
import 'package:superport_v2/core/common/models/paginated_result.dart';
import '../../../vendor/domain/entities/vendor.dart';
import '../../../vendor/domain/repositories/vendor_repository.dart';
import '../../../uom/domain/entities/uom.dart';
import '../../../uom/domain/repositories/uom_repository.dart';
import '../../domain/entities/product.dart';
import '../../domain/repositories/product_repository.dart';
enum ProductStatusFilter { all, activeOnly, inactiveOnly }
class ProductController extends ChangeNotifier {
ProductController({
required ProductRepository productRepository,
required VendorRepository vendorRepository,
required UomRepository uomRepository,
}) : _productRepository = productRepository,
_vendorRepository = vendorRepository,
_uomRepository = uomRepository;
final ProductRepository _productRepository;
final VendorRepository _vendorRepository;
final UomRepository _uomRepository;
PaginatedResult<Product>? _result;
bool _isLoading = false;
bool _isSubmitting = false;
bool _isLoadingLookups = false;
String _query = '';
int? _vendorFilter;
int? _uomFilter;
ProductStatusFilter _statusFilter = ProductStatusFilter.all;
String? _errorMessage;
List<Vendor> _vendorOptions = const [];
List<Uom> _uomOptions = const [];
PaginatedResult<Product>? get result => _result;
bool get isLoading => _isLoading;
bool get isSubmitting => _isSubmitting;
bool get isLoadingLookups => _isLoadingLookups;
String get query => _query;
int? get vendorFilter => _vendorFilter;
int? get uomFilter => _uomFilter;
ProductStatusFilter get statusFilter => _statusFilter;
String? get errorMessage => _errorMessage;
List<Vendor> get vendorOptions => _vendorOptions;
List<Uom> get uomOptions => _uomOptions;
Future<void> fetch({int page = 1}) async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
try {
final isActive = switch (_statusFilter) {
ProductStatusFilter.all => null,
ProductStatusFilter.activeOnly => true,
ProductStatusFilter.inactiveOnly => false,
};
final response = await _productRepository.list(
page: page,
pageSize: _result?.pageSize ?? 20,
query: _query.isEmpty ? null : _query,
vendorId: _vendorFilter,
uomId: _uomFilter,
isActive: isActive,
);
_result = response;
} catch (e) {
_errorMessage = e.toString();
} finally {
_isLoading = false;
notifyListeners();
}
}
Future<void> loadLookups() async {
_isLoadingLookups = true;
notifyListeners();
try {
final vendorResult = await _vendorRepository.list(page: 1, pageSize: 100);
final uomResult = await _uomRepository.list(page: 1, pageSize: 100);
_vendorOptions = vendorResult.items;
_uomOptions = uomResult.items;
} catch (e) {
_errorMessage = e.toString();
} finally {
_isLoadingLookups = false;
notifyListeners();
}
}
void updateQuery(String value) {
_query = value;
notifyListeners();
}
void updateVendorFilter(int? vendorId) {
_vendorFilter = vendorId;
notifyListeners();
}
void updateUomFilter(int? uomId) {
_uomFilter = uomId;
notifyListeners();
}
void updateStatusFilter(ProductStatusFilter filter) {
_statusFilter = filter;
notifyListeners();
}
Future<Product?> create(ProductInput input) async {
_setSubmitting(true);
try {
final created = await _productRepository.create(input);
await fetch(page: 1);
return created;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return null;
} finally {
_setSubmitting(false);
}
}
Future<Product?> update(int id, ProductInput input) async {
_setSubmitting(true);
try {
final updated = await _productRepository.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 _productRepository.delete(id);
await fetch(page: _result?.page ?? 1);
return true;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return false;
} finally {
_setSubmitting(false);
}
}
Future<Product?> restore(int id) async {
_setSubmitting(true);
try {
final restored = await _productRepository.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,937 @@
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 '../../../uom/domain/entities/uom.dart';
import '../../../uom/domain/repositories/uom_repository.dart';
import '../../../vendor/domain/entities/vendor.dart';
import '../../../vendor/domain/repositories/vendor_repository.dart';
import '../../domain/entities/product.dart';
import '../../domain/repositories/product_repository.dart';
import '../controllers/product_controller.dart';
class ProductPage extends StatelessWidget {
const ProductPage({super.key});
@override
Widget build(BuildContext context) {
return const SpecPage(
title: '장비 모델(제품) 관리',
summary: '제품 코드, 제조사, 단위 정보를 유지하여 재고 라인과 연계합니다.',
sections: [
SpecSection(
title: '입력 폼',
items: [
'제품코드 [Text]',
'제품명 [Text]',
'조사 [Dropdown]',
'단위 [Dropdown]',
'사용여부 [Switch]',
'비고 [Text]',
],
),
SpecSection(
title: '수정 폼',
items: ['제품코드 [ReadOnly]', '생성일시 [ReadOnly]'],
),
SpecSection(
title: '테이블 리스트',
description: '1행 예시',
table: SpecTable(
columns: ['번호', '제품코드', '제품명', '제조사', '단위', '사용여부', '비고', '변경일'],
rows: [
[
'1',
'P-100',
'XR-5000',
'슈퍼벤더',
'EA',
'Y',
'-',
'2024-03-01 10:00',
final enabled = Environment.flag('FEATURE_PRODUCTS_ENABLED');
if (!enabled) {
return const SpecPage(
title: '장비 모델(제품) 관리',
summary: '제품 코드, 제조사, 단위 정보를 유지하여 재고 라인과 연계합니다.',
sections: [
SpecSection(
title: '입력 폼',
items: [
'품코드 [Text]',
'제품명 [Text]',
'제조사 [Dropdown]',
'단위 [Dropdown]',
'사용여부 [Switch]',
'비고 [Text]',
],
),
SpecSection(
title: '수정 폼',
items: ['제품코드 [ReadOnly]', '생성일시 [ReadOnly]'],
),
SpecSection(
title: '테이블 리스트',
description: '1행 예',
table: SpecTable(
columns: ['번호', '제품코드', '제품명', '제조사', '단위', '사용여부', '비고', '변경일시'],
rows: [
[
'1',
'P-100',
'XR-5000',
'슈퍼벤더',
'EA',
'Y',
'-',
'2024-03-01 10:00',
],
],
),
),
],
);
}
return const _ProductEnabledPage();
}
}
class _ProductEnabledPage extends StatefulWidget {
const _ProductEnabledPage();
@override
State<_ProductEnabledPage> createState() => _ProductEnabledPageState();
}
class _ProductEnabledPageState extends State<_ProductEnabledPage> {
late final ProductController _controller;
final TextEditingController _searchController = TextEditingController();
final FocusNode _searchFocus = FocusNode();
final DateFormat _dateFormat = DateFormat('yyyy-MM-dd HH:mm');
bool _lookupsLoaded = false;
String? _lastError;
@override
void initState() {
super.initState();
_controller = ProductController(
productRepository: GetIt.I<ProductRepository>(),
vendorRepository: GetIt.I<VendorRepository>(),
uomRepository: GetIt.I<UomRepository>(),
)..addListener(_handleControllerUpdate);
WidgetsBinding.instance.addPostFrameCallback((_) async {
await Future.wait([_controller.loadLookups(), _controller.fetch()]);
setState(() {
_lookupsLoaded = true;
});
});
}
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 products = result?.items ?? const <Product>[];
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
: () => _openProductForm(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: 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('초기화'),
),
],
),
],
),
),
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()),
)
: products.isEmpty
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
'조건에 맞는 제품이 없습니다.',
style: theme.textTheme.muted,
),
)
: _ProductTable(
products: products,
dateFormat: _dateFormat,
onEdit: _controller.isSubmitting
? null
: (product) =>
_openProductForm(context, product: product),
onDelete: _controller.isSubmitting
? null
: _confirmDelete,
onRestore: _controller.isSubmitting
? null
: _restoreProduct,
),
),
],
),
);
},
);
}
void _applyFilters() {
_controller.updateQuery(_searchController.text.trim());
_controller.fetch(page: 1);
}
String _statusLabel(ProductStatusFilter filter) {
switch (filter) {
case ProductStatusFilter.all:
return '전체(사용/미사용)';
case ProductStatusFilter.activeOnly:
return '사용중';
case ProductStatusFilter.inactiveOnly:
return '미사용';
}
}
Future<void> _openProductForm(
BuildContext context, {
Product? product,
}) async {
final existing = product;
final isEdit = existing != null;
final productId = existing?.id;
if (isEdit && productId == null) {
_showSnack('ID 정보가 없어 수정할 수 없습니다.');
return;
}
if (!_lookupsLoaded) {
_showSnack('선택 목록을 불러오는 중입니다. 잠시 후 다시 시도하세요.');
return;
}
final parentContext = context;
final codeController = TextEditingController(
text: existing?.productCode ?? '',
);
final nameController = TextEditingController(
text: existing?.productName ?? '',
);
final noteController = TextEditingController(text: existing?.note ?? '');
final vendorNotifier = ValueNotifier<int?>(existing?.vendor?.id);
final uomNotifier = ValueNotifier<int?>(existing?.uom?.id);
final isActiveNotifier = ValueNotifier<bool>(existing?.isActive ?? true);
final saving = ValueNotifier<bool>(false);
final codeError = ValueNotifier<String?>(null);
final nameError = ValueNotifier<String?>(null);
final vendorError = ValueNotifier<String?>(null);
final uomError = ValueNotifier<String?>(null);
await showDialog<bool>(
context: parentContext,
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 note = noteController.text.trim();
final vendorId = vendorNotifier.value;
final uomId = uomNotifier.value;
codeError.value = code.isEmpty
? '제품코드를 입력하세요.'
: null;
nameError.value = name.isEmpty
? '제품명을 입력하세요.'
: null;
vendorError.value = vendorId == null
? '제조사를 선택하세요.'
: null;
uomError.value = uomId == null
? '단위를 선택하세요.'
: null;
if (codeError.value != null ||
nameError.value != null ||
vendorError.value != null ||
uomError.value != null) {
return;
}
saving.value = true;
final input = ProductInput(
productCode: code,
productName: name,
vendorId: vendorId!,
uomId: uomId!,
isActive: isActiveNotifier.value,
note: note.isEmpty ? null : note,
);
final response = isEdit
? await _controller.update(
productId!,
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),
ValueListenableBuilder<int?>(
valueListenable: vendorNotifier,
builder: (_, value, __) {
return ValueListenableBuilder<String?>(
valueListenable: vendorError,
builder: (_, errorText, __) {
return _FormField(
label: '제조사',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ShadSelect<int?>(
initialValue: value,
onChanged: saving.value
? null
: (next) {
vendorNotifier.value = next;
vendorError.value = null;
},
options: _controller.vendorOptions
.map(
(vendor) => ShadOption<int?>(
value: vendor.id,
child: Text(vendor.vendorName),
),
)
.toList(),
placeholder: const Text('제조사를 선택하세요'),
selectedOptionBuilder: (context, selected) {
if (selected == null) {
return const Text('제조사를 선택하세요');
}
final vendor = _controller.vendorOptions
.firstWhere(
(v) => v.id == selected,
orElse: () => Vendor(
id: selected,
vendorCode: '',
vendorName: '',
),
);
return Text(vendor.vendorName);
},
),
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: uomNotifier,
builder: (_, value, __) {
return ValueListenableBuilder<String?>(
valueListenable: uomError,
builder: (_, errorText, __) {
return _FormField(
label: '단위',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ShadSelect<int?>(
initialValue: value,
onChanged: saving.value
? null
: (next) {
uomNotifier.value = next;
uomError.value = null;
},
options: _controller.uomOptions
.map(
(uom) => ShadOption<int?>(
value: uom.id,
child: Text(uom.uomName),
),
)
.toList(),
placeholder: const Text('단위를 선택하세요'),
selectedOptionBuilder: (context, selected) {
if (selected == null) {
return const Text('단위를 선택하세요');
}
final uom = _controller.uomOptions
.firstWhere(
(u) => u.id == selected,
orElse: () =>
Uom(id: selected, uomName: ''),
);
return Text(uom.uomName);
},
),
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(existing.createdAt)}',
style: theme.textTheme.small,
),
const SizedBox(height: 4),
Text(
'수정일시: ${_formatDateTime(existing.updatedAt)}',
style: theme.textTheme.small,
),
],
],
),
),
),
),
);
},
);
codeController.dispose();
nameController.dispose();
noteController.dispose();
vendorNotifier.dispose();
uomNotifier.dispose();
isActiveNotifier.dispose();
saving.dispose();
codeError.dispose();
nameError.dispose();
vendorError.dispose();
uomError.dispose();
}
Future<void> _confirmDelete(Product product) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: const Text('제품 삭제'),
content: Text('"${product.productName}" 제품을 삭제하시겠습니까?'),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('취소'),
),
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('삭제'),
),
],
);
},
);
if (confirmed == true && product.id != null) {
final success = await _controller.delete(product.id!);
if (success && mounted) {
_showSnack('제품을 삭제했습니다.');
}
}
}
Future<void> _restoreProduct(Product product) async {
if (product.id == null) return;
final restored = await _controller.restore(product.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 _ProductTable extends StatelessWidget {
const _ProductTable({
required this.products,
required this.dateFormat,
required this.onEdit,
required this.onDelete,
required this.onRestore,
});
final List<Product> products;
final DateFormat dateFormat;
final void Function(Product product)? onEdit;
final void Function(Product product)? onDelete;
final void Function(Product product)? onRestore;
@override
Widget build(BuildContext context) {
final header = [
'ID',
'제품코드',
'제품명',
'제조사',
'단위',
'사용',
'삭제',
'비고',
'변경일시',
'동작',
].map((text) => ShadTableCell.header(child: Text(text))).toList();
final rows = products.map((product) {
return [
product.id?.toString() ?? '-',
product.productCode,
product.productName,
product.vendor?.vendorName ?? '-',
product.uom?.uomName ?? '-',
product.isActive ? 'Y' : 'N',
product.isDeleted ? 'Y' : '-',
product.note?.isEmpty ?? true ? '-' : product.note!,
product.updatedAt == null
? '-'
: dateFormat.format(product.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!(product),
child: const Icon(LucideIcons.pencil, size: 16),
),
const SizedBox(width: 8),
product.isDeleted
? ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onRestore == null
? null
: () => onRestore!(product),
child: const Icon(LucideIcons.history, size: 16),
)
: ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onDelete == null
? null
: () => onDelete!(product),
child: const Icon(LucideIcons.trash2, size: 16),
),
],
),
),
);
}).toList();
return SizedBox(
height: 56.0 * (products.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,
],
);
}