마스터 고객/제품/창고 테스트 및 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,3 +1,5 @@
import 'package:superport_v2/core/common/models/paginated_result.dart';
import '../../domain/entities/vendor.dart';
/// 벤더 DTO (JSON 직렬화/역직렬화)
@@ -49,26 +51,40 @@ class VendorDto {
}
Vendor toEntity() => Vendor(
id: id,
vendorCode: vendorCode,
vendorName: vendorName,
isActive: isActive,
isDeleted: isDeleted,
note: note,
createdAt: createdAt,
updatedAt: updatedAt,
);
id: id,
vendorCode: vendorCode,
vendorName: vendorName,
isActive: isActive,
isDeleted: isDeleted,
note: note,
createdAt: createdAt,
updatedAt: updatedAt,
);
static VendorDto fromEntity(Vendor entity) => VendorDto(
id: entity.id,
vendorCode: entity.vendorCode,
vendorName: entity.vendorName,
isActive: entity.isActive,
isDeleted: entity.isDeleted,
note: entity.note,
createdAt: entity.createdAt,
updatedAt: entity.updatedAt,
);
id: entity.id,
vendorCode: entity.vendorCode,
vendorName: entity.vendorName,
isActive: entity.isActive,
isDeleted: entity.isDeleted,
note: entity.note,
createdAt: entity.createdAt,
updatedAt: entity.updatedAt,
);
static PaginatedResult<Vendor> parsePaginated(Map<String, dynamic>? json) {
final items = (json?['items'] as List<dynamic>? ?? [])
.whereType<Map<String, dynamic>>()
.map(VendorDto.fromJson)
.map((dto) => dto.toEntity())
.toList();
return PaginatedResult<Vendor>(
items: items,
page: json?['page'] as int? ?? 1,
pageSize: json?['page_size'] as int? ?? items.length,
total: json?['total'] as int? ?? items.length,
);
}
}
DateTime? _parseDate(Object? value) {
@@ -78,3 +94,8 @@ DateTime? _parseDate(Object? value) {
return null;
}
Map<String, dynamic> vendorInputToJson(VendorInput input) {
final map = input.toPayload();
map.removeWhere((key, value) => value == null);
return map;
}

View File

@@ -1,9 +1,11 @@
import 'package:dio/dio.dart';
import 'package:superport_v2/core/common/models/paginated_result.dart';
import 'package:superport_v2/core/network/api_client.dart';
import '../../domain/entities/vendor.dart';
import '../../domain/repositories/vendor_repository.dart';
import '../dtos/vendor_dto.dart';
import '../../../../../core/network/api_client.dart';
/// 원격 구현체: 공통 ApiClient(Dio) 사용
class VendorRepositoryRemote implements VendorRepository {
@@ -14,57 +16,60 @@ class VendorRepositoryRemote implements VendorRepository {
static const _basePath = '/vendors'; // TODO: 백엔드 경로 확정 시 수정
@override
Future<List<Vendor>> list({
Future<PaginatedResult<Vendor>> list({
int page = 1,
int pageSize = 20,
String? query,
bool includeInactive = true,
bool? isActive,
}) async {
final response = await _api.get<List<dynamic>>(
final response = await _api.get<Map<String, dynamic>>(
_basePath,
query: {
'page': page,
'page_size': pageSize,
if (query != null && query.isNotEmpty) 'q': query,
if (includeInactive) 'include': 'inactive',
if (isActive != null) 'is_active': isActive,
},
options: Options(responseType: ResponseType.json),
);
final data = response.data ?? [];
return data
.whereType<Map<String, dynamic>>()
.map((e) => VendorDto.fromJson(e).toEntity())
.toList();
final map = response.data ?? const <String, dynamic>{};
return VendorDto.parsePaginated(map);
}
@override
Future<Vendor> create(Vendor vendor) async {
final dto = VendorDto.fromEntity(vendor);
Future<Vendor> create(VendorInput input) async {
final response = await _api.post<Map<String, dynamic>>(
_basePath,
data: dto.toJson(),
data: vendorInputToJson(input),
options: Options(responseType: ResponseType.json),
);
return VendorDto.fromJson(response.data ?? {}).toEntity();
final data = (response.data?['data'] as Map<String, dynamic>?) ?? {};
return VendorDto.fromJson(data).toEntity();
}
@override
Future<Vendor> update(Vendor vendor) async {
if (vendor.id == null) {
throw ArgumentError('id가 없는 엔티티는 수정할 수 없습니다.');
}
final dto = VendorDto.fromEntity(vendor);
Future<Vendor> update(int id, VendorInput input) async {
final response = await _api.patch<Map<String, dynamic>>(
'$_basePath/${vendor.id}',
data: dto.toJson(),
'$_basePath/$id',
data: vendorInputToJson(input),
options: Options(responseType: ResponseType.json),
);
return VendorDto.fromJson(response.data ?? {}).toEntity();
final data = (response.data?['data'] as Map<String, dynamic>?) ?? {};
return VendorDto.fromJson(data).toEntity();
}
@override
Future<void> delete(int id) async {
await _api.delete<void>('$_basePath/$id');
}
}
@override
Future<Vendor> 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 VendorDto.fromJson(data).toEntity();
}
}

View File

@@ -59,3 +59,28 @@ class Vendor {
}
}
/// 벤더 신규/수정 입력 모델
///
/// - code는 생성 시 필수, 수정 시 읽기 전용이지만 API 전송을 위해 포함
class VendorInput {
VendorInput({
required this.vendorCode,
required this.vendorName,
this.isActive = true,
this.note,
});
final String vendorCode;
final String vendorName;
final bool isActive;
final String? note;
Map<String, dynamic> toPayload() {
return {
'vendor_code': vendorCode,
'vendor_name': vendorName,
'is_active': isActive,
'note': note,
};
}
}

View File

@@ -1,3 +1,5 @@
import 'package:superport_v2/core/common/models/paginated_result.dart';
import '../entities/vendor.dart';
/// 벤더 리포지토리 인터페이스
@@ -8,20 +10,22 @@ abstract class VendorRepository {
/// 벤더 목록 조회
///
/// - 표준 쿼리 파라미터: page, page_size, q, include
Future<List<Vendor>> list({
Future<PaginatedResult<Vendor>> list({
int page = 1,
int pageSize = 20,
String? query,
bool includeInactive = true,
bool? isActive,
});
/// 벤더 생성
Future<Vendor> create(Vendor vendor);
Future<Vendor> create(VendorInput input);
/// 벤더 수정 (부분 업데이트 포함)
Future<Vendor> update(Vendor vendor);
Future<Vendor> update(int id, VendorInput input);
/// 벤더 소프트 삭제
Future<void> delete(int id);
}
/// 벤더 복구 (소프트 삭제 해제)
Future<Vendor> restore(int id);
}

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