마스터 고객/제품/창고 테스트 및 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:superport_v2/core/common/models/paginated_result.dart';
import '../../domain/entities/warehouse.dart';
class WarehouseDto {
WarehouseDto({
this.id,
required this.warehouseCode,
required this.warehouseName,
this.zipcode,
this.addressDetail,
this.isActive = true,
this.isDeleted = false,
this.note,
this.createdAt,
this.updatedAt,
});
final int? id;
final String warehouseCode;
final String warehouseName;
final WarehouseZipcodeDto? zipcode;
final String? addressDetail;
final bool isActive;
final bool isDeleted;
final String? note;
final DateTime? createdAt;
final DateTime? updatedAt;
factory WarehouseDto.fromJson(Map<String, dynamic> json) {
return WarehouseDto(
id: json['id'] as int?,
warehouseCode: json['warehouse_code'] as String,
warehouseName: json['warehouse_name'] as String,
zipcode: json['zipcode'] is Map<String, dynamic>
? WarehouseZipcodeDto.fromJson(
json['zipcode'] as Map<String, dynamic>,
)
: null,
addressDetail: json['address_detail'] as String?,
isActive: (json['is_active'] as bool?) ?? true,
isDeleted: (json['is_deleted'] as bool?) ?? false,
note: json['note'] as String?,
createdAt: _parseDate(json['created_at']),
updatedAt: _parseDate(json['updated_at']),
);
}
Map<String, dynamic> toJson() {
return {
if (id != null) 'id': id,
'warehouse_code': warehouseCode,
'warehouse_name': warehouseName,
'zipcode': zipcode?.toJson(),
'address_detail': addressDetail,
'is_active': isActive,
'is_deleted': isDeleted,
'note': note,
'created_at': createdAt?.toIso8601String(),
'updated_at': updatedAt?.toIso8601String(),
};
}
Warehouse toEntity() => Warehouse(
id: id,
warehouseCode: warehouseCode,
warehouseName: warehouseName,
zipcode: zipcode?.toEntity(),
addressDetail: addressDetail,
isActive: isActive,
isDeleted: isDeleted,
note: note,
createdAt: createdAt,
updatedAt: updatedAt,
);
static PaginatedResult<Warehouse> parsePaginated(Map<String, dynamic>? json) {
final items = (json?['items'] as List<dynamic>? ?? [])
.whereType<Map<String, dynamic>>()
.map(WarehouseDto.fromJson)
.map((dto) => dto.toEntity())
.toList();
return PaginatedResult<Warehouse>(
items: items,
page: json?['page'] as int? ?? 1,
pageSize: json?['page_size'] as int? ?? items.length,
total: json?['total'] as int? ?? items.length,
);
}
}
class WarehouseZipcodeDto {
WarehouseZipcodeDto({
required this.zipcode,
this.sido,
this.sigungu,
this.roadName,
});
final String zipcode;
final String? sido;
final String? sigungu;
final String? roadName;
factory WarehouseZipcodeDto.fromJson(Map<String, dynamic> json) {
return WarehouseZipcodeDto(
zipcode: json['zipcode'] as String,
sido: json['sido'] as String?,
sigungu: json['sigungu'] as String?,
roadName: json['road_name'] as String?,
);
}
Map<String, dynamic> toJson() {
return {
'zipcode': zipcode,
'sido': sido,
'sigungu': sigungu,
'road_name': roadName,
};
}
WarehouseZipcode toEntity() => WarehouseZipcode(
zipcode: zipcode,
sido: sido,
sigungu: sigungu,
roadName: roadName,
);
}
DateTime? _parseDate(Object? value) {
if (value == null) return null;
if (value is DateTime) return value;
if (value is String) return DateTime.tryParse(value);
return null;
}
Map<String, dynamic> warehouseInputToJson(WarehouseInput input) {
final map = input.toPayload();
map.removeWhere((key, value) => value == null);
return map;
}

View File

@@ -0,0 +1,72 @@
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/warehouse.dart';
import '../../domain/repositories/warehouse_repository.dart';
import '../dtos/warehouse_dto.dart';
class WarehouseRepositoryRemote implements WarehouseRepository {
WarehouseRepositoryRemote({required ApiClient apiClient}) : _api = apiClient;
final ApiClient _api;
static const _basePath = '/warehouses';
@override
Future<PaginatedResult<Warehouse>> list({
int page = 1,
int pageSize = 20,
String? query,
bool? isActive,
}) async {
final response = await _api.get<Map<String, dynamic>>(
_basePath,
query: {
'page': page,
'page_size': pageSize,
if (query != null && query.isNotEmpty) 'q': query,
if (isActive != null) 'is_active': isActive,
},
options: Options(responseType: ResponseType.json),
);
return WarehouseDto.parsePaginated(response.data ?? const {});
}
@override
Future<Warehouse> create(WarehouseInput input) async {
final response = await _api.post<Map<String, dynamic>>(
_basePath,
data: warehouseInputToJson(input),
options: Options(responseType: ResponseType.json),
);
final data = (response.data?['data'] as Map<String, dynamic>?) ?? {};
return WarehouseDto.fromJson(data).toEntity();
}
@override
Future<Warehouse> update(int id, WarehouseInput input) async {
final response = await _api.patch<Map<String, dynamic>>(
'$_basePath/$id',
data: warehouseInputToJson(input),
options: Options(responseType: ResponseType.json),
);
final data = (response.data?['data'] as Map<String, dynamic>?) ?? {};
return WarehouseDto.fromJson(data).toEntity();
}
@override
Future<void> delete(int id) async {
await _api.delete<void>('$_basePath/$id');
}
@override
Future<Warehouse> 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 WarehouseDto.fromJson(data).toEntity();
}
}

View File

@@ -0,0 +1,94 @@
class Warehouse {
Warehouse({
this.id,
required this.warehouseCode,
required this.warehouseName,
this.zipcode,
this.addressDetail,
this.isActive = true,
this.isDeleted = false,
this.note,
this.createdAt,
this.updatedAt,
});
final int? id;
final String warehouseCode;
final String warehouseName;
final WarehouseZipcode? zipcode;
final String? addressDetail;
final bool isActive;
final bool isDeleted;
final String? note;
final DateTime? createdAt;
final DateTime? updatedAt;
Warehouse copyWith({
int? id,
String? warehouseCode,
String? warehouseName,
WarehouseZipcode? zipcode,
String? addressDetail,
bool? isActive,
bool? isDeleted,
String? note,
DateTime? createdAt,
DateTime? updatedAt,
}) {
return Warehouse(
id: id ?? this.id,
warehouseCode: warehouseCode ?? this.warehouseCode,
warehouseName: warehouseName ?? this.warehouseName,
zipcode: zipcode ?? this.zipcode,
addressDetail: addressDetail ?? this.addressDetail,
isActive: isActive ?? this.isActive,
isDeleted: isDeleted ?? this.isDeleted,
note: note ?? this.note,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt,
);
}
}
class WarehouseZipcode {
WarehouseZipcode({
required this.zipcode,
this.sido,
this.sigungu,
this.roadName,
});
final String zipcode;
final String? sido;
final String? sigungu;
final String? roadName;
}
class WarehouseInput {
WarehouseInput({
required this.warehouseCode,
required this.warehouseName,
this.zipcode,
this.addressDetail,
this.isActive = true,
this.note,
});
final String warehouseCode;
final String warehouseName;
final String? zipcode;
final String? addressDetail;
final bool isActive;
final String? note;
Map<String, dynamic> toPayload() {
return {
'warehouse_code': warehouseCode,
'warehouse_name': warehouseName,
'zipcode': zipcode,
'address_detail': addressDetail,
'is_active': isActive,
'note': note,
};
}
}

View File

@@ -0,0 +1,20 @@
import 'package:superport_v2/core/common/models/paginated_result.dart';
import '../entities/warehouse.dart';
abstract class WarehouseRepository {
Future<PaginatedResult<Warehouse>> list({
int page = 1,
int pageSize = 20,
String? query,
bool? isActive,
});
Future<Warehouse> create(WarehouseInput input);
Future<Warehouse> update(int id, WarehouseInput input);
Future<void> delete(int id);
Future<Warehouse> restore(int id);
}

View File

@@ -0,0 +1,133 @@
import 'package:flutter/foundation.dart';
import 'package:superport_v2/core/common/models/paginated_result.dart';
import '../../domain/entities/warehouse.dart';
import '../../domain/repositories/warehouse_repository.dart';
enum WarehouseStatusFilter { all, activeOnly, inactiveOnly }
class WarehouseController extends ChangeNotifier {
WarehouseController({required WarehouseRepository repository})
: _repository = repository;
final WarehouseRepository _repository;
PaginatedResult<Warehouse>? _result;
bool _isLoading = false;
bool _isSubmitting = false;
String _query = '';
WarehouseStatusFilter _statusFilter = WarehouseStatusFilter.all;
String? _errorMessage;
PaginatedResult<Warehouse>? get result => _result;
bool get isLoading => _isLoading;
bool get isSubmitting => _isSubmitting;
String get query => _query;
WarehouseStatusFilter get statusFilter => _statusFilter;
String? get errorMessage => _errorMessage;
Future<void> fetch({int page = 1}) async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
try {
final isActive = switch (_statusFilter) {
WarehouseStatusFilter.all => null,
WarehouseStatusFilter.activeOnly => true,
WarehouseStatusFilter.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(WarehouseStatusFilter filter) {
_statusFilter = filter;
notifyListeners();
}
Future<Warehouse?> create(WarehouseInput input) async {
_setSubmitting(true);
try {
final created = await _repository.create(input);
await fetch(page: 1);
return created;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return null;
} finally {
_setSubmitting(false);
}
}
Future<Warehouse?> update(int id, WarehouseInput input) async {
_setSubmitting(true);
try {
final updated = await _repository.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 _repository.delete(id);
await fetch(page: _result?.page ?? 1);
return true;
} catch (e) {
_errorMessage = e.toString();
notifyListeners();
return false;
} finally {
_setSubmitting(false);
}
}
Future<Warehouse?> restore(int id) async {
_setSubmitting(true);
try {
final restored = await _repository.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,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,
],
);
}