마스터 고객/제품/창고 테스트 및 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,160 @@
import 'package:superport_v2/core/common/models/paginated_result.dart';
import '../../domain/entities/customer.dart';
class CustomerDto {
CustomerDto({
this.id,
required this.customerCode,
required this.customerName,
this.isPartner = false,
this.isGeneral = true,
this.email,
this.mobileNo,
this.zipcode,
this.addressDetail,
this.isActive = true,
this.isDeleted = false,
this.note,
this.createdAt,
this.updatedAt,
});
final int? id;
final String customerCode;
final String customerName;
final bool isPartner;
final bool isGeneral;
final String? email;
final String? mobileNo;
final CustomerZipcodeDto? zipcode;
final String? addressDetail;
final bool isActive;
final bool isDeleted;
final String? note;
final DateTime? createdAt;
final DateTime? updatedAt;
factory CustomerDto.fromJson(Map<String, dynamic> json) {
return CustomerDto(
id: json['id'] as int?,
customerCode: json['customer_code'] as String,
customerName: json['customer_name'] as String,
isPartner: (json['is_partner'] as bool?) ?? false,
isGeneral: (json['is_general'] as bool?) ?? true,
email: json['email'] as String?,
mobileNo: json['mobile_no'] as String?,
zipcode: json['zipcode'] is Map<String, dynamic>
? CustomerZipcodeDto.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,
'customer_code': customerCode,
'customer_name': customerName,
'is_partner': isPartner,
'is_general': isGeneral,
'email': email,
'mobile_no': mobileNo,
'zipcode': zipcode?.toJson(),
'address_detail': addressDetail,
'is_active': isActive,
'is_deleted': isDeleted,
'note': note,
'created_at': createdAt?.toIso8601String(),
'updated_at': updatedAt?.toIso8601String(),
};
}
Customer toEntity() => Customer(
id: id,
customerCode: customerCode,
customerName: customerName,
isPartner: isPartner,
isGeneral: isGeneral,
email: email,
mobileNo: mobileNo,
zipcode: zipcode?.toEntity(),
addressDetail: addressDetail,
isActive: isActive,
isDeleted: isDeleted,
note: note,
createdAt: createdAt,
updatedAt: updatedAt,
);
static PaginatedResult<Customer> parsePaginated(Map<String, dynamic>? json) {
final items = (json?['items'] as List<dynamic>? ?? [])
.whereType<Map<String, dynamic>>()
.map(CustomerDto.fromJson)
.map((dto) => dto.toEntity())
.toList();
return PaginatedResult<Customer>(
items: items,
page: json?['page'] as int? ?? 1,
pageSize: json?['page_size'] as int? ?? items.length,
total: json?['total'] as int? ?? items.length,
);
}
}
class CustomerZipcodeDto {
CustomerZipcodeDto({
required this.zipcode,
this.sido,
this.sigungu,
this.roadName,
});
final String zipcode;
final String? sido;
final String? sigungu;
final String? roadName;
factory CustomerZipcodeDto.fromJson(Map<String, dynamic> json) {
return CustomerZipcodeDto(
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,
};
}
CustomerZipcode toEntity() => CustomerZipcode(
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> customerInputToJson(CustomerInput input) {
final map = input.toPayload();
map.removeWhere((key, value) => value == null);
return map;
}

View File

@@ -0,0 +1,76 @@
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/customer.dart';
import '../../domain/repositories/customer_repository.dart';
import '../dtos/customer_dto.dart';
class CustomerRepositoryRemote implements CustomerRepository {
CustomerRepositoryRemote({required ApiClient apiClient}) : _api = apiClient;
final ApiClient _api;
static const _basePath = '/customers';
@override
Future<PaginatedResult<Customer>> list({
int page = 1,
int pageSize = 20,
String? query,
bool? isPartner,
bool? isGeneral,
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 (isPartner != null) 'is_partner': isPartner,
if (isGeneral != null) 'is_general': isGeneral,
if (isActive != null) 'is_active': isActive,
},
options: Options(responseType: ResponseType.json),
);
return CustomerDto.parsePaginated(response.data ?? const {});
}
@override
Future<Customer> create(CustomerInput input) async {
final response = await _api.post<Map<String, dynamic>>(
_basePath,
data: customerInputToJson(input),
options: Options(responseType: ResponseType.json),
);
final data = (response.data?['data'] as Map<String, dynamic>?) ?? {};
return CustomerDto.fromJson(data).toEntity();
}
@override
Future<Customer> update(int id, CustomerInput input) async {
final response = await _api.patch<Map<String, dynamic>>(
'$_basePath/$id',
data: customerInputToJson(input),
options: Options(responseType: ResponseType.json),
);
final data = (response.data?['data'] as Map<String, dynamic>?) ?? {};
return CustomerDto.fromJson(data).toEntity();
}
@override
Future<void> delete(int id) async {
await _api.delete<void>('$_basePath/$id');
}
@override
Future<Customer> 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 CustomerDto.fromJson(data).toEntity();
}
}

View File

@@ -0,0 +1,122 @@
class Customer {
Customer({
this.id,
required this.customerCode,
required this.customerName,
this.isPartner = false,
this.isGeneral = true,
this.email,
this.mobileNo,
this.zipcode,
this.addressDetail,
this.isActive = true,
this.isDeleted = false,
this.note,
this.createdAt,
this.updatedAt,
});
final int? id;
final String customerCode;
final String customerName;
final bool isPartner;
final bool isGeneral;
final String? email;
final String? mobileNo;
final CustomerZipcode? zipcode;
final String? addressDetail;
final bool isActive;
final bool isDeleted;
final String? note;
final DateTime? createdAt;
final DateTime? updatedAt;
Customer copyWith({
int? id,
String? customerCode,
String? customerName,
bool? isPartner,
bool? isGeneral,
String? email,
String? mobileNo,
CustomerZipcode? zipcode,
String? addressDetail,
bool? isActive,
bool? isDeleted,
String? note,
DateTime? createdAt,
DateTime? updatedAt,
}) {
return Customer(
id: id ?? this.id,
customerCode: customerCode ?? this.customerCode,
customerName: customerName ?? this.customerName,
isPartner: isPartner ?? this.isPartner,
isGeneral: isGeneral ?? this.isGeneral,
email: email ?? this.email,
mobileNo: mobileNo ?? this.mobileNo,
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 CustomerZipcode {
CustomerZipcode({
required this.zipcode,
this.sido,
this.sigungu,
this.roadName,
});
final String zipcode;
final String? sido;
final String? sigungu;
final String? roadName;
}
class CustomerInput {
CustomerInput({
required this.customerCode,
required this.customerName,
required this.isPartner,
required this.isGeneral,
this.email,
this.mobileNo,
this.zipcode,
this.addressDetail,
this.isActive = true,
this.note,
});
final String customerCode;
final String customerName;
final bool isPartner;
final bool isGeneral;
final String? email;
final String? mobileNo;
final String? zipcode;
final String? addressDetail;
final bool isActive;
final String? note;
Map<String, dynamic> toPayload() {
return {
'customer_code': customerCode,
'customer_name': customerName,
'is_partner': isPartner,
'is_general': isGeneral,
'email': email,
'mobile_no': mobileNo,
'zipcode': zipcode,
'address_detail': addressDetail,
'is_active': isActive,
'note': note,
};
}
}

View File

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

View File

@@ -0,0 +1,162 @@
import 'package:flutter/foundation.dart';
import 'package:superport_v2/core/common/models/paginated_result.dart';
import '../../domain/entities/customer.dart';
import '../../domain/repositories/customer_repository.dart';
enum CustomerTypeFilter { all, partner, general }
enum CustomerStatusFilter { all, activeOnly, inactiveOnly }
class CustomerController extends ChangeNotifier {
CustomerController({required CustomerRepository repository})
: _repository = repository;
final CustomerRepository _repository;
PaginatedResult<Customer>? _result;
bool _isLoading = false;
bool _isSubmitting = false;
String _query = '';
CustomerTypeFilter _typeFilter = CustomerTypeFilter.all;
CustomerStatusFilter _statusFilter = CustomerStatusFilter.all;
String? _errorMessage;
PaginatedResult<Customer>? get result => _result;
bool get isLoading => _isLoading;
bool get isSubmitting => _isSubmitting;
String get query => _query;
CustomerTypeFilter get typeFilter => _typeFilter;
CustomerStatusFilter get statusFilter => _statusFilter;
String? get errorMessage => _errorMessage;
Future<void> fetch({int page = 1}) async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
try {
bool? isPartner;
bool? isGeneral;
switch (_typeFilter) {
case CustomerTypeFilter.all:
isPartner = null;
isGeneral = null;
break;
case CustomerTypeFilter.partner:
isPartner = true;
isGeneral = null;
break;
case CustomerTypeFilter.general:
isPartner = null;
isGeneral = true;
break;
}
final isActive = switch (_statusFilter) {
CustomerStatusFilter.all => null,
CustomerStatusFilter.activeOnly => true,
CustomerStatusFilter.inactiveOnly => false,
};
final response = await _repository.list(
page: page,
pageSize: _result?.pageSize ?? 20,
query: _query.isEmpty ? null : _query,
isPartner: isPartner,
isGeneral: isGeneral,
isActive: isActive,
);
_result = response;
} catch (e) {
_errorMessage = e.toString();
} finally {
_isLoading = false;
notifyListeners();
}
}
void updateQuery(String value) {
_query = value;
notifyListeners();
}
void updateTypeFilter(CustomerTypeFilter filter) {
_typeFilter = filter;
notifyListeners();
}
void updateStatusFilter(CustomerStatusFilter filter) {
_statusFilter = filter;
notifyListeners();
}
Future<Customer?> create(CustomerInput 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<Customer?> update(int id, CustomerInput 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<Customer?> 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,65 +1,927 @@
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/customer.dart';
import '../../domain/repositories/customer_repository.dart';
import '../controllers/customer_controller.dart';
class CustomerPage extends StatelessWidget {
const CustomerPage({super.key});
@override
Widget build(BuildContext context) {
return const SpecPage(
title: '회사(고객사) 관리',
summary: '고객사 기본 정보와 연락처, 주소를 관리합니다.',
sections: [
SpecSection(
title: '입력 폼',
items: [
'고객사코드 [Text]',
'고객사명 [Text]',
'유형 (파트너/일반) [Dropdown]',
'이메일 [Text]',
'연락처 [Text]',
'우편번호 [검색 연동], 상세주소 [Text]',
'사용여부 [Switch]',
'비고 [Text]',
],
),
SpecSection(
title: '수정 폼',
items: ['고객사코드 [ReadOnly]', '생성일시 [ReadOnly]'],
),
SpecSection(
title: '테이블 리스트',
description: '1행 예시',
table: SpecTable(
columns: [
'번호',
'고객사코드',
'고객사명',
'유형',
'이메일',
'연락처',
'우편번호',
'상세주소',
'사용여부',
'비고',
final enabled = Environment.flag('FEATURE_CUSTOMERS_ENABLED');
if (!enabled) {
return const SpecPage(
title: '회사(고객사) 관리',
summary: '고객사 기본 정보와 연락처, 주소를 관리합니다.',
sections: [
SpecSection(
title: '입력 폼',
items: [
'고객사코드 [Text]',
'고객사명 [Text]',
'유형 (파트너/일반) [Dropdown]',
'이메일 [Text]',
'연락처 [Text]',
'우편번호 [검색 연동], 상세주소 [Text]',
'사용여부 [Switch]',
'비고 [Text]',
],
rows: [
[
'1',
'C-001',
'슈퍼포트 파트너',
'파트너',
'partner@superport.com',
'02-1234-5678',
'04532',
'서울시 중구 을지로 100',
'Y',
'-',
),
SpecSection(
title: '수정 폼',
items: ['고객사코드 [ReadOnly]', '생성일시 [ReadOnly]'],
),
SpecSection(
title: '테이블 리스트',
description: '1행 예시',
table: SpecTable(
columns: [
'번호',
'고객사코드',
'고객사명',
'유형',
'이메일',
'연락처',
'우편번호',
'상세주소',
'사용여부',
'비고',
],
rows: [
[
'1',
'C-001',
'슈퍼포트 파트너',
'파트너',
'partner@superport.com',
'02-1234-5678',
'04532',
'서울시 중구 을지로 100',
'Y',
'-',
],
],
),
),
],
);
}
return const _CustomerEnabledPage();
}
}
class _CustomerEnabledPage extends StatefulWidget {
const _CustomerEnabledPage();
@override
State<_CustomerEnabledPage> createState() => _CustomerEnabledPageState();
}
class _CustomerEnabledPageState extends State<_CustomerEnabledPage> {
late final CustomerController _controller;
final TextEditingController _searchController = TextEditingController();
final FocusNode _searchFocus = FocusNode();
String? _lastError;
@override
void initState() {
super.initState();
_controller = CustomerController(repository: GetIt.I<CustomerRepository>())
..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 customers = result?.items ?? const <Customer>[];
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(
onPressed: _controller.isSubmitting
? null
: () => _openCustomerForm(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<CustomerTypeFilter>(
key: ValueKey(_controller.typeFilter),
initialValue: _controller.typeFilter,
selectedOptionBuilder: (context, value) =>
Text(_typeLabel(value)),
onChanged: (value) {
if (value == null) return;
_controller.updateTypeFilter(value);
},
options: CustomerTypeFilter.values
.map(
(filter) => ShadOption(
value: filter,
child: Text(_typeLabel(filter)),
),
)
.toList(),
),
),
SizedBox(
width: 200,
child: ShadSelect<CustomerStatusFilter>(
key: ValueKey(_controller.statusFilter),
initialValue: _controller.statusFilter,
selectedOptionBuilder: (context, value) =>
Text(_statusLabel(value)),
onChanged: (value) {
if (value == null) return;
_controller.updateStatusFilter(value);
},
options: CustomerStatusFilter.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.typeFilter != CustomerTypeFilter.all ||
_controller.statusFilter !=
CustomerStatusFilter.all)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateTypeFilter(
CustomerTypeFilter.all,
);
_controller.updateStatusFilter(
CustomerStatusFilter.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()),
)
: customers.isEmpty
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
'조건에 맞는 고객사가 없습니다.',
style: theme.textTheme.muted,
),
)
: _CustomerTable(
customers: customers,
onEdit: _controller.isSubmitting
? null
: (customer) => _openCustomerForm(
context,
customer: customer,
),
onDelete: _controller.isSubmitting
? null
: _confirmDelete,
onRestore: _controller.isSubmitting
? null
: _restoreCustomer,
),
),
],
),
);
},
);
}
void _applyFilters() {
_controller.updateQuery(_searchController.text.trim());
_controller.fetch(page: 1);
}
String _typeLabel(CustomerTypeFilter filter) {
switch (filter) {
case CustomerTypeFilter.all:
return '전체(파트너/일반)';
case CustomerTypeFilter.partner:
return '파트너';
case CustomerTypeFilter.general:
return '일반';
}
}
String _statusLabel(CustomerStatusFilter filter) {
switch (filter) {
case CustomerStatusFilter.all:
return '전체(사용/미사용)';
case CustomerStatusFilter.activeOnly:
return '사용중';
case CustomerStatusFilter.inactiveOnly:
return '미사용';
}
}
Future<void> _openCustomerForm(
BuildContext context, {
Customer? customer,
}) async {
final existing = customer;
final isEdit = existing != null;
final customerId = existing?.id;
if (isEdit && customerId == null) {
_showSnack('ID 정보가 없어 수정할 수 없습니다.');
return;
}
final parentContext = context;
final codeController = TextEditingController(
text: existing?.customerCode ?? '',
);
final nameController = TextEditingController(
text: existing?.customerName ?? '',
);
final emailController = TextEditingController(text: existing?.email ?? '');
final mobileController = TextEditingController(
text: existing?.mobileNo ?? '',
);
final zipcodeController = TextEditingController(
text: existing?.zipcode?.zipcode ?? '',
);
final addressController = TextEditingController(
text: existing?.addressDetail ?? '',
);
final noteController = TextEditingController(text: existing?.note ?? '');
final partnerNotifier = ValueNotifier<bool>(existing?.isPartner ?? false);
final generalNotifier = ValueNotifier<bool>(existing?.isGeneral ?? true);
final isActiveNotifier = ValueNotifier<bool>(existing?.isActive ?? true);
final saving = ValueNotifier<bool>(false);
final codeError = ValueNotifier<String?>(null);
final nameError = ValueNotifier<String?>(null);
final typeError = 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 email = emailController.text.trim();
final mobile = mobileController.text.trim();
final zipcode = zipcodeController.text.trim();
final address = addressController.text.trim();
final note = noteController.text.trim();
final partner = partnerNotifier.value;
var general = generalNotifier.value;
codeError.value = code.isEmpty
? '고객사코드를 입력하세요.'
: null;
nameError.value = name.isEmpty
? '고객사명을 입력하세요.'
: null;
if (!partner && !general) {
general = true;
generalNotifier.value = true;
}
typeError.value = (!partner && !general)
? '파트너/일반 중 하나 이상 선택하세요.'
: null;
if (codeError.value != null ||
nameError.value != null ||
typeError.value != null) {
return;
}
saving.value = true;
final input = CustomerInput(
customerCode: code,
customerName: name,
isPartner: partner,
isGeneral: general,
email: email.isEmpty ? null : email,
mobileNo: mobile.isEmpty ? null : mobile,
zipcode: zipcode.isEmpty ? null : zipcode,
addressDetail: address.isEmpty
? null
: address,
isActive: isActiveNotifier.value,
note: note.isEmpty ? null : note,
);
final response = isEdit
? await _controller.update(
customerId!,
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,
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: partnerNotifier,
builder: (_, partner, __) {
return ValueListenableBuilder<bool>(
valueListenable: generalNotifier,
builder: (_, general, __) {
return ValueListenableBuilder<String?>(
valueListenable: typeError,
builder: (_, errorText, __) {
final onChanged = saving.value
? null
: (bool? value) {
if (value == null) return;
partnerNotifier.value = value;
if (!value && !generalNotifier.value) {
typeError.value =
'파트너/일반 중 하나 이상 선택하세요.';
} else {
typeError.value = null;
}
};
final onChangedGeneral = saving.value
? null
: (bool? value) {
if (value == null) return;
generalNotifier.value = value;
if (!value && !partnerNotifier.value) {
typeError.value =
'파트너/일반 중 하나 이상 선택하세요.';
} else {
typeError.value = null;
}
};
return _FormField(
label: '유형',
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Row(
children: [
ShadCheckbox(
value: partner,
onChanged: onChanged,
),
const SizedBox(width: 8),
const Text('파트너'),
const SizedBox(width: 24),
ShadCheckbox(
value: general,
onChanged: onChangedGeneral,
),
const SizedBox(width: 8),
const Text('일반'),
],
),
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: emailController,
keyboardType: TextInputType.emailAddress,
),
),
const SizedBox(height: 16),
_FormField(
label: '연락처',
child: ShadInput(
controller: mobileController,
keyboardType: TextInputType.phone,
),
),
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 (existing != null)
..._buildAuditInfo(
existing,
theme,
),
],
),
),
),
),
);
},
);
codeController.dispose();
nameController.dispose();
emailController.dispose();
mobileController.dispose();
zipcodeController.dispose();
addressController.dispose();
noteController.dispose();
partnerNotifier.dispose();
generalNotifier.dispose();
isActiveNotifier.dispose();
saving.dispose();
codeError.dispose();
nameError.dispose();
typeError.dispose();
}
Future<void> _confirmDelete(Customer customer) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: const Text('고객사 삭제'),
content: Text('"${customer.customerName}" 고객사를 삭제하시겠습니까?'),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('취소'),
),
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('삭제'),
),
],
);
},
);
if (confirmed == true && customer.id != null) {
final success = await _controller.delete(customer.id!);
if (success && mounted) {
_showSnack('고객사를 삭제했습니다.');
}
}
}
Future<void> _restoreCustomer(Customer customer) async {
if (customer.id == null) return;
final restored = await _controller.restore(customer.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 value.toLocal().toIso8601String();
}
List<Widget> _buildAuditInfo(Customer customer, ShadThemeData theme) {
return [
const SizedBox(height: 20),
Text(
'생성일시: ${_formatDateTime(customer.createdAt)}',
style: theme.textTheme.small,
),
const SizedBox(height: 4),
Text(
'수정일시: ${_formatDateTime(customer.updatedAt)}',
style: theme.textTheme.small,
),
];
}
}
class _CustomerTable extends StatelessWidget {
const _CustomerTable({
required this.customers,
required this.onEdit,
required this.onDelete,
required this.onRestore,
});
final List<Customer> customers;
final void Function(Customer customer)? onEdit;
final void Function(Customer customer)? onDelete;
final void Function(Customer customer)? onRestore;
@override
Widget build(BuildContext context) {
final header = [
'ID',
'고객사코드',
'고객사명',
'유형',
'이메일',
'연락처',
'우편번호',
'상세주소',
'사용',
'삭제',
'비고',
'동작',
].map((text) => ShadTableCell.header(child: Text(text))).toList();
String resolveType(Customer customer) {
if (customer.isPartner && customer.isGeneral) {
return '파트너/일반';
}
if (customer.isPartner) return '파트너';
if (customer.isGeneral) return '일반';
return '-';
}
final rows = customers.map((customer) {
return [
customer.id?.toString() ?? '-',
customer.customerCode,
customer.customerName,
resolveType(customer),
customer.email?.isEmpty ?? true ? '-' : customer.email!,
customer.mobileNo?.isEmpty ?? true ? '-' : customer.mobileNo!,
customer.zipcode?.zipcode ?? '-',
customer.addressDetail?.isEmpty ?? true ? '-' : customer.addressDetail!,
customer.isActive ? 'Y' : 'N',
customer.isDeleted ? 'Y' : '-',
customer.note?.isEmpty ?? true ? '-' : customer.note!,
].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!(customer),
child: const Icon(LucideIcons.pencil, size: 16),
),
const SizedBox(width: 8),
customer.isDeleted
? ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onRestore == null
? null
: () => onRestore!(customer),
child: const Icon(LucideIcons.history, size: 16),
)
: ShadButton.ghost(
size: ShadButtonSize.sm,
onPressed: onDelete == null
? null
: () => onDelete!(customer),
child: const Icon(LucideIcons.trash2, size: 16),
),
],
),
),
);
}).toList();
return SizedBox(
height: 56.0 * (customers.length + 1),
child: ShadTable.list(
header: header,
children: rows,
columnSpanExtent: (index) => index == 11
? 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,
],
);
}