전역 구조 리팩터링 및 테스트 확장

This commit is contained in:
JiWoong Sul
2025-09-29 01:51:47 +09:00
parent c00c0c9ab2
commit fef7108479
70 changed files with 7709 additions and 3185 deletions

View File

@@ -211,19 +211,13 @@ class ApprovalStepActionInput {
/// 결재 단계를 일괄 등록/재배치하기 위한 입력 모델
class ApprovalStepAssignmentInput {
ApprovalStepAssignmentInput({
required this.approvalId,
required this.steps,
});
ApprovalStepAssignmentInput({required this.approvalId, required this.steps});
final int approvalId;
final List<ApprovalStepAssignmentItem> steps;
Map<String, dynamic> toPayload() {
return {
'id': approvalId,
'steps': steps.map((e) => e.toJson()).toList(),
};
return {'id': approvalId, 'steps': steps.map((e) => e.toJson()).toList()};
}
}

View File

@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:intl/intl.dart' as intl;
import 'package:lucide_icons_flutter/lucide_icons.dart' as lucide;
import 'package:shadcn_ui/shadcn_ui.dart';
@@ -7,6 +8,8 @@ import '../../../../../core/config/environment.dart';
import '../../../../../core/constants/app_sections.dart';
import '../../../../../widgets/app_layout.dart';
import '../../../../../widgets/components/filter_bar.dart';
import '../../../../../widgets/components/superport_date_picker.dart';
import '../../../../../widgets/components/superport_table.dart';
import '../../../../../widgets/spec_page.dart';
import '../../domain/entities/approval_history_record.dart';
import '../../domain/repositories/approval_history_repository.dart';
@@ -145,6 +148,19 @@ class _ApprovalHistoryEnabledPageState
),
],
toolbar: FilterBar(
actions: [
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
ShadButton.ghost(
onPressed:
_controller.isLoading || !_controller.hasActiveFilters
? null
: _resetFilters,
child: const Text('필터 초기화'),
),
],
children: [
SizedBox(
width: 240,
@@ -180,21 +196,24 @@ class _ApprovalHistoryEnabledPageState
),
SizedBox(
width: 220,
child: ShadButton.outline(
onPressed: _pickDateRange,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
const Icon(lucide.LucideIcons.calendar, size: 16),
const SizedBox(width: 8),
Text(
_dateRange == null
? '기간 선택'
: '${_formatDate(_dateRange!.start)} ~ ${_formatDate(_dateRange!.end)}',
child: SuperportDateRangePickerButton(
value: _dateRange,
dateFormat: intl.DateFormat('yyyy-MM-dd'),
enabled: !_controller.isLoading,
firstDate: DateTime(DateTime.now().year - 5),
lastDate: DateTime(DateTime.now().year + 1),
initialDateRange:
_dateRange ??
DateTimeRange(
start: DateTime.now().subtract(const Duration(days: 7)),
end: DateTime.now(),
),
],
),
onChanged: (range) {
if (range == null) return;
setState(() => _dateRange = range);
_controller.updateDateRange(range.start, range.end);
_controller.fetch(page: 1);
},
),
),
if (_dateRange != null)
@@ -202,17 +221,6 @@ class _ApprovalHistoryEnabledPageState
onPressed: _controller.isLoading ? null : _clearDateRange,
child: const Text('기간 초기화'),
),
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
ShadButton.ghost(
onPressed:
_controller.isLoading || !_controller.hasActiveFilters
? null
: _resetFilters,
child: const Text('필터 초기화'),
),
],
),
child: ShadCard(
@@ -283,27 +291,6 @@ class _ApprovalHistoryEnabledPageState
_controller.fetch(page: 1);
}
Future<void> _pickDateRange() async {
final now = DateTime.now();
final initial =
_dateRange ??
DateTimeRange(
start: DateTime(now.year, now.month, now.day - 7),
end: now,
);
final range = await showDateRangePicker(
context: context,
initialDateRange: initial,
firstDate: DateTime(now.year - 5),
lastDate: DateTime(now.year + 1),
);
if (range != null) {
setState(() => _dateRange = range);
_controller.updateDateRange(range.start, range.end);
_controller.fetch(page: 1);
}
}
void _clearDateRange() {
setState(() => _dateRange = null);
_controller.updateDateRange(null, null);
@@ -318,10 +305,6 @@ class _ApprovalHistoryEnabledPageState
_controller.fetch(page: 1);
}
String _formatDate(DateTime date) {
return DateFormat('yyyy-MM-dd').format(date.toLocal());
}
String _actionLabel(ApprovalHistoryActionFilter filter) {
switch (filter) {
case ApprovalHistoryActionFilter.all:
@@ -349,58 +332,60 @@ class _ApprovalHistoryTable extends StatelessWidget {
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
final normalizedQuery = query.trim().toLowerCase();
final header = [
'ID',
'결재번호',
'단계순서',
'승인자',
'행위',
'변경전 상태',
'변경 상태',
'작업일시',
'비고',
].map((label) => ShadTableCell.header(child: Text(label))).toList();
final columns = const [
Text('ID'),
Text('결재번호'),
Text('단계순서'),
Text('승인자'),
Text('행위'),
Text('변경 상태'),
Text('변경후 상태'),
Text('작업일시'),
Text('비고'),
];
final rows = histories.map((history) {
final isHighlighted =
normalizedQuery.isNotEmpty &&
history.approvalNo.toLowerCase().contains(normalizedQuery);
return [
ShadTableCell(child: Text(history.id.toString())),
ShadTableCell(
child: Text(
history.approvalNo,
style: isHighlighted
? ShadTheme.of(
context,
).textTheme.small.copyWith(fontWeight: FontWeight.w600)
: null,
),
),
ShadTableCell(
child: Text(
history.stepOrder == null ? '-' : history.stepOrder.toString(),
),
),
ShadTableCell(child: Text(history.approver.name)),
ShadTableCell(child: Text(history.action.name)),
ShadTableCell(child: Text(history.fromStatus?.name ?? '-')),
ShadTableCell(child: Text(history.toStatus.name)),
ShadTableCell(
child: Text(dateFormat.format(history.actionAt.toLocal())),
),
ShadTableCell(
child: Text(
history.note?.trim().isEmpty ?? true ? '-' : history.note!,
),
final highlightStyle = theme.textTheme.small.copyWith(
fontWeight: FontWeight.w600,
color: theme.colorScheme.foreground,
);
final noteText = history.note?.trim();
final noteContent = noteText?.isNotEmpty == true ? noteText : null;
final subLabelStyle = theme.textTheme.muted.copyWith(
fontSize: (theme.textTheme.muted.fontSize ?? 14) - 1,
);
return <Widget>[
Text(history.id.toString()),
Text(history.approvalNo, style: isHighlighted ? highlightStyle : null),
Text(history.stepOrder == null ? '-' : history.stepOrder.toString()),
Text(history.approver.name),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(history.action.name),
if (noteContent != null) Text(noteContent, style: subLabelStyle),
],
),
Text(history.fromStatus?.name ?? '-'),
Text(history.toStatus.name),
Text(dateFormat.format(history.actionAt.toLocal())),
Text(noteContent ?? '-'),
];
}).toList();
return ShadTable.list(
header: header,
children: rows,
return SuperportTable(
columns: columns,
rows: rows,
rowHeight: 64,
maxHeight: 520,
columnSpanExtent: (index) {
switch (index) {
case 1:

View File

@@ -7,6 +7,7 @@ import '../../../../../core/config/environment.dart';
import '../../../../../core/constants/app_sections.dart';
import '../../../../../widgets/app_layout.dart';
import '../../../../../widgets/components/filter_bar.dart';
import '../../../../../widgets/components/superport_dialog.dart';
import '../../../../../widgets/spec_page.dart';
import '../controllers/approval_step_controller.dart';
import '../../domain/entities/approval_step_input.dart';
@@ -528,73 +529,50 @@ class _ApprovalStepEnabledPageState extends State<_ApprovalStepEnabledPage> {
if (!mounted) return;
Navigator.of(context, rootNavigator: true).pop();
if (detail == null) return;
await showDialog<void>(
final step = detail.step;
await SuperportDialog.show<void>(
context: context,
builder: (dialogContext) {
final step = detail.step;
final theme = ShadTheme.of(dialogContext);
return Dialog(
insetPadding: const EdgeInsets.all(24),
clipBehavior: Clip.antiAlias,
child: ShadCard(
title: Text('결재 단계 상세', style: theme.textTheme.h3),
description: Text(
'결재번호 ${detail.approvalNo}',
style: theme.textTheme.muted,
dialog: SuperportDialog(
title: '결재 단계 상세',
description: '결재번호 ${detail.approvalNo}',
constraints: const BoxConstraints(maxWidth: 560),
contentPadding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 18,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
_DetailRow(label: '단계 순서', value: '${step.stepOrder}'),
_DetailRow(label: '승인자', value: step.approver.name),
_DetailRow(label: '상태', value: step.status.name),
_DetailRow(label: '배정일시', value: _formatDate(step.assignedAt)),
_DetailRow(
label: '결정일시',
value: step.decidedAt == null
? '-'
: _formatDate(step.decidedAt!),
),
footer: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ShadButton.ghost(
onPressed: () => Navigator.of(dialogContext).pop(),
child: const Text('닫기'),
),
],
_DetailRow(label: '템플릿', value: detail.templateName ?? '-'),
_DetailRow(label: '트랜잭션번호', value: detail.transactionNo ?? '-'),
const SizedBox(height: 12),
Text(
'비고',
style: ShadTheme.of(
context,
).textTheme.small.copyWith(fontWeight: FontWeight.w600),
),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_DetailRow(label: '단계 순서', value: '${step.stepOrder}'),
_DetailRow(label: '승인자', value: step.approver.name),
_DetailRow(label: '상태', value: step.status.name),
_DetailRow(
label: '배정일시',
value: _formatDate(step.assignedAt),
),
_DetailRow(
label: '결정일시',
value: step.decidedAt == null
? '-'
: _formatDate(step.decidedAt!),
),
_DetailRow(label: '템플릿', value: detail.templateName ?? '-'),
_DetailRow(
label: '트랜잭션번호',
value: detail.transactionNo ?? '-',
),
const SizedBox(height: 12),
Text(
'비고',
style: theme.textTheme.small.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 8),
ShadTextarea(
initialValue: step.note ?? '',
readOnly: true,
minHeight: 80,
maxHeight: 200,
),
],
),
const SizedBox(height: 8),
ShadTextarea(
initialValue: step.note ?? '',
readOnly: true,
minHeight: 80,
maxHeight: 200,
),
),
);
},
],
),
),
);
}
@@ -724,102 +702,93 @@ class _StepFormDialogState extends State<_StepFormDialog> {
final theme = ShadTheme.of(context);
final materialTheme = Theme.of(context);
return Dialog(
insetPadding: const EdgeInsets.all(24),
clipBehavior: Clip.antiAlias,
child: ShadCard(
title: Text(widget.title, style: theme.textTheme.h3),
footer: Row(
mainAxisAlignment: MainAxisAlignment.end,
return SuperportDialog(
title: widget.title,
constraints: const BoxConstraints(maxWidth: 560),
primaryAction: ShadButton(
key: const ValueKey('step_form_submit'),
onPressed: _handleSubmit,
child: Text(widget.submitLabel),
),
secondaryAction: ShadButton.ghost(
onPressed: () => Navigator.of(context).pop(),
child: const Text('취소'),
),
contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
ShadButton.ghost(
onPressed: () => Navigator.of(context).pop(),
child: const Text('취소'),
),
const SizedBox(width: 12),
ShadButton(
key: const ValueKey('step_form_submit'),
onPressed: _handleSubmit,
child: Text(widget.submitLabel),
),
],
),
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
if (!widget.isEditing)
_FormFieldBlock(
label: '결재 ID',
errorText: _errors['approvalId'],
child: ShadInput(
key: const ValueKey('step_form_approval_id'),
controller: _approvalIdController,
onChanged: (_) => _clearError('approvalId'),
),
)
else ...[
_FormFieldBlock(
label: '결재 ID',
child: ShadInput(
controller: _approvalIdController,
readOnly: true,
),
),
const SizedBox(height: 16),
_FormFieldBlock(
label: '결재번호',
child: ShadInput(
controller: _approvalNoController,
readOnly: true,
),
),
],
if (!widget.isEditing) const SizedBox(height: 16),
if (!widget.isEditing)
_FormFieldBlock(
label: '단계 순서',
errorText: _errors['stepOrder'],
label: '결재 ID',
errorText: _errors['approvalId'],
child: ShadInput(
key: const ValueKey('step_form_step_order'),
controller: _stepOrderController,
onChanged: (_) => _clearError('stepOrder'),
key: const ValueKey('step_form_approval_id'),
controller: _approvalIdController,
onChanged: (_) => _clearError('approvalId'),
),
)
else ...[
_FormFieldBlock(
label: '결재 ID',
child: ShadInput(
controller: _approvalIdController,
readOnly: true,
),
),
const SizedBox(height: 16),
_FormFieldBlock(
label: '승인자 ID',
errorText: _errors['approverId'],
label: '결재번호',
child: ShadInput(
key: const ValueKey('step_form_approver_id'),
controller: _approverIdController,
onChanged: (_) => _clearError('approverId'),
controller: _approvalNoController,
readOnly: true,
),
),
const SizedBox(height: 16),
_FormFieldBlock(
label: '비고',
helperText: '필요 시 단계에 대한 참고 내용을 남길 수 있습니다.',
child: ShadTextarea(
key: const ValueKey('step_form_note'),
controller: _noteController,
minHeight: 100,
maxHeight: 200,
),
),
if (_errors['form'] != null)
Padding(
padding: const EdgeInsets.only(top: 12),
child: Text(
_errors['form']!,
style: theme.textTheme.small.copyWith(
color: materialTheme.colorScheme.error,
),
),
),
],
),
if (!widget.isEditing) const SizedBox(height: 16),
_FormFieldBlock(
label: '단계 순서',
errorText: _errors['stepOrder'],
child: ShadInput(
key: const ValueKey('step_form_step_order'),
controller: _stepOrderController,
onChanged: (_) => _clearError('stepOrder'),
),
),
const SizedBox(height: 16),
_FormFieldBlock(
label: '승인자 ID',
errorText: _errors['approverId'],
child: ShadInput(
key: const ValueKey('step_form_approver_id'),
controller: _approverIdController,
onChanged: (_) => _clearError('approverId'),
),
),
const SizedBox(height: 16),
_FormFieldBlock(
label: '비고',
helperText: '필요 시 단계에 대한 참고 내용을 남길 수 있습니다.',
child: ShadTextarea(
key: const ValueKey('step_form_note'),
controller: _noteController,
minHeight: 100,
maxHeight: 200,
),
),
if (_errors['form'] != null)
Padding(
padding: const EdgeInsets.only(top: 12),
child: Text(
_errors['form']!,
style: theme.textTheme.small.copyWith(
color: materialTheme.colorScheme.error,
),
),
),
],
),
),
);

View File

@@ -7,6 +7,7 @@ import '../../../../../core/config/environment.dart';
import '../../../../../core/constants/app_sections.dart';
import '../../../../../widgets/app_layout.dart';
import '../../../../../widgets/components/filter_bar.dart';
import '../../../../../widgets/components/superport_table.dart';
import '../../../../../widgets/components/superport_dialog.dart';
import '../../../../../widgets/spec_page.dart';
import '../../../domain/entities/approval_template.dart';
@@ -151,6 +152,18 @@ class _ApprovalTemplateEnabledPageState
),
],
toolbar: FilterBar(
actions: [
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
ShadButton.ghost(
onPressed: !_controller.isLoading && showReset
? _resetFilters
: null,
child: const Text('필터 초기화'),
),
],
children: [
SizedBox(
width: 260,
@@ -183,16 +196,6 @@ class _ApprovalTemplateEnabledPageState
.toList(),
),
),
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
ShadButton.ghost(
onPressed: !_controller.isLoading && showReset
? _resetFilters
: null,
child: const Text('필터 초기화'),
),
],
),
child: ShadCard(
@@ -213,97 +216,95 @@ class _ApprovalTemplateEnabledPageState
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
height: 480,
child: ShadTable.list(
header:
['ID', '템플릿코드', '템플릿명', '설명', '사용', '변경일시', '동작']
.map(
(e) => ShadTableCell.header(child: Text(e)),
)
.toList(),
columnSpanExtent: (index) {
switch (index) {
case 2:
return const FixedTableSpanExtent(220);
case 3:
return const FixedTableSpanExtent(260);
case 4:
return const FixedTableSpanExtent(100);
case 5:
return const FixedTableSpanExtent(180);
case 6:
return const FixedTableSpanExtent(160);
default:
return const FixedTableSpanExtent(140);
}
},
children: templates.map((template) {
return [
ShadTableCell(child: Text('${template.id}')),
ShadTableCell(child: Text(template.code)),
ShadTableCell(child: Text(template.name)),
ShadTableCell(
child: Text(
template.description?.isNotEmpty == true
? template.description!
: '-',
),
SuperportTable.fromCells(
header: const [
ShadTableCell.header(child: Text('ID')),
ShadTableCell.header(child: Text('템플릿코드')),
ShadTableCell.header(child: Text('템플릿명')),
ShadTableCell.header(child: Text('설명')),
ShadTableCell.header(child: Text('사용')),
ShadTableCell.header(child: Text('변경일시')),
ShadTableCell.header(child: Text('동작')),
],
rows: templates.map((template) {
return [
ShadTableCell(child: Text('${template.id}')),
ShadTableCell(child: Text(template.code)),
ShadTableCell(child: Text(template.name)),
ShadTableCell(
child: Text(
template.description?.isNotEmpty == true
? template.description!
: '-',
),
ShadTableCell(
child: template.isActive
? const ShadBadge(child: Text('사용'))
: const ShadBadge.outline(
child: Text('미사용'),
),
ShadTableCell(
child: template.isActive
? const ShadBadge(child: Text('사용'))
: const ShadBadge.outline(child: Text('미사용')),
),
ShadTableCell(
child: Text(
template.updatedAt == null
? '-'
: _dateFormat.format(
template.updatedAt!.toLocal(),
),
),
ShadTableCell(
child: Text(
template.updatedAt == null
? '-'
: _dateFormat.format(
template.updatedAt!.toLocal(),
),
),
),
ShadTableCell(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ShadButton.ghost(
key: ValueKey(
'template_edit_${template.id}',
),
size: ShadButtonSize.sm,
onPressed: _controller.isSubmitting
? null
: () => _openEditTemplate(template),
child: const Text('수정'),
),
ShadTableCell(
alignment: Alignment.centerRight,
child: Wrap(
spacing: 8,
children: [
ShadButton.ghost(
key: ValueKey(
'template_edit_${template.id}',
),
const SizedBox(width: 8),
template.isActive
? ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isSubmitting
? null
: () =>
_confirmDelete(template),
child: const Text('삭제'),
)
: ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isSubmitting
? null
: () =>
_confirmRestore(template),
child: const Text('복구'),
),
],
),
size: ShadButtonSize.sm,
onPressed: _controller.isSubmitting
? null
: () => _openEditTemplate(template),
child: const Text('수정'),
),
template.isActive
? ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isSubmitting
? null
: () => _confirmDelete(template),
child: const Text('삭제'),
)
: ShadButton.outline(
size: ShadButtonSize.sm,
onPressed: _controller.isSubmitting
? null
: () => _confirmRestore(template),
child: const Text('복구'),
),
],
),
];
}).toList(),
),
),
];
}).toList(),
rowHeight: 56,
maxHeight: 480,
columnSpanExtent: (index) {
switch (index) {
case 2:
return const FixedTableSpanExtent(220);
case 3:
return const FixedTableSpanExtent(260);
case 4:
return const FixedTableSpanExtent(100);
case 5:
return const FixedTableSpanExtent(180);
case 6:
return const FixedTableSpanExtent(160);
default:
return const FixedTableSpanExtent(140);
}
},
),
const SizedBox(height: 16),
Row(
@@ -382,26 +383,23 @@ class _ApprovalTemplateEnabledPageState
}
Future<void> _confirmDelete(ApprovalTemplate template) async {
final confirmed = await showDialog<bool>(
final confirmed = await SuperportDialog.show<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: const Text('템플릿 삭제'),
content: Text(
dialog: SuperportDialog(
title: '템플릿 삭제',
description:
'"${template.name}" 템플릿을 삭제하시겠습니까?\n삭제 시 템플릿은 미사용 상태로 전환됩니다.',
actions: [
ShadButton.ghost(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('취소'),
),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('취소'),
),
FilledButton.tonal(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('삭제'),
),
],
);
},
ShadButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('삭제'),
),
],
),
);
if (confirmed != true) return;
final ok = await _controller.delete(template.id);
@@ -412,24 +410,22 @@ class _ApprovalTemplateEnabledPageState
}
Future<void> _confirmRestore(ApprovalTemplate template) async {
final confirmed = await showDialog<bool>(
final confirmed = await SuperportDialog.show<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: const Text('템플릿 복구'),
content: Text('"${template.name}" 템플릿을 복구하시겠습니까?'),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('취소'),
),
FilledButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('복구'),
),
],
);
},
dialog: SuperportDialog(
title: '템플릿 복구',
description: '"${template.name}" 템플릿 복구하시겠습니까?',
actions: [
ShadButton.ghost(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('취소'),
),
ShadButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('복구'),
),
],
),
);
if (confirmed != true) return;
final restored = await _controller.restore(template.id);
@@ -454,10 +450,74 @@ class _ApprovalTemplateEnabledPageState
String? errorText;
StateSetter? modalSetState;
Future<void> handleSubmit() async {
if (isSaving) return;
final codeValue = codeController.text.trim();
final nameValue = nameController.text.trim();
if (!isEdit && codeValue.isEmpty) {
modalSetState?.call(() => errorText = '템플릿 코드를 입력하세요.');
return;
}
if (nameValue.isEmpty) {
modalSetState?.call(() => errorText = '템플릿명을 입력하세요.');
return;
}
final validation = _validateSteps(steps);
if (validation != null) {
modalSetState?.call(() => errorText = validation);
return;
}
modalSetState?.call(() => errorText = null);
final stepInputs = steps
.map(
(field) => ApprovalTemplateStepInput(
id: field.id,
stepOrder: int.parse(field.orderController.text.trim()),
approverId: int.parse(field.approverController.text.trim()),
note: field.noteController.text.trim().isEmpty
? null
: field.noteController.text.trim(),
),
)
.toList();
final input = ApprovalTemplateInput(
code: isEdit ? existingTemplate?.code : codeValue,
name: nameValue,
description: descriptionController.text.trim().isEmpty
? null
: descriptionController.text.trim(),
note: noteController.text.trim().isEmpty
? null
: noteController.text.trim(),
isActive: statusNotifier.value,
);
if (isEdit && existingTemplate == null) {
modalSetState?.call(() => errorText = '템플릿 정보를 불러오지 못했습니다.');
modalSetState?.call(() => isSaving = false);
return;
}
modalSetState?.call(() => isSaving = true);
final success = isEdit && existingTemplate != null
? await _controller.update(
existingTemplate.id,
input,
stepInputs,
)
: await _controller.create(input, stepInputs);
if (success != null && mounted) {
Navigator.of(context).pop(true);
} else {
modalSetState?.call(() => isSaving = false);
}
}
final result = await showSuperportDialog<bool>(
context: context,
title: isEdit ? '템플릿 수정' : '템플릿 생성',
barrierDismissible: !isSaving,
onSubmit: handleSubmit,
body: StatefulBuilder(
builder: (dialogContext, setModalState) {
modalSetState = setModalState;
@@ -594,68 +654,7 @@ class _ApprovalTemplateEnabledPageState
child: const Text('취소'),
),
ShadButton(
onPressed: () async {
if (isSaving) return;
final codeValue = codeController.text.trim();
final nameValue = nameController.text.trim();
if (!isEdit && codeValue.isEmpty) {
modalSetState?.call(() => errorText = '템플릿 코드를 입력하세요.');
return;
}
if (nameValue.isEmpty) {
modalSetState?.call(() => errorText = '템플릿명을 입력하세요.');
return;
}
final validation = _validateSteps(steps);
if (validation != null) {
modalSetState?.call(() => errorText = validation);
return;
}
modalSetState?.call(() => errorText = null);
final stepInputs = steps
.map(
(field) => ApprovalTemplateStepInput(
id: field.id,
stepOrder: int.parse(field.orderController.text.trim()),
approverId: int.parse(field.approverController.text.trim()),
note: field.noteController.text.trim().isEmpty
? null
: field.noteController.text.trim(),
),
)
.toList();
final input = ApprovalTemplateInput(
code: isEdit ? existingTemplate?.code : codeValue,
name: nameValue,
description: descriptionController.text.trim().isEmpty
? null
: descriptionController.text.trim(),
note: noteController.text.trim().isEmpty
? null
: noteController.text.trim(),
isActive: statusNotifier.value,
);
if (isEdit && existingTemplate == null) {
modalSetState?.call(() => errorText = '템플릿 정보를 불러오지 못했습니다.');
modalSetState?.call(() => isSaving = false);
return;
}
modalSetState?.call(() => isSaving = true);
final success = isEdit && existingTemplate != null
? await _controller.update(
existingTemplate.id,
input,
stepInputs,
)
: await _controller.create(input, stepInputs);
if (success != null && mounted) {
Navigator.of(context).pop(true);
} else {
modalSetState?.call(() => isSaving = false);
}
},
onPressed: handleSubmit,
child: Text(isEdit ? '수정 완료' : '생성 완료'),
),
],

View File

@@ -1,24 +1,313 @@
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart' as lucide;
import 'package:shadcn_ui/shadcn_ui.dart';
import '../../../../widgets/spec_page.dart';
import 'package:superport_v2/widgets/app_layout.dart';
import 'package:superport_v2/widgets/components/empty_state.dart';
class DashboardPage extends StatelessWidget {
const DashboardPage({super.key});
static const _recentTransactions = [
('IN-20240312-003', '2024-03-12', '입고', '승인완료', '김담당'),
('OUT-20240311-005', '2024-03-11', '출고', '출고대기', '이물류'),
('RENT-20240310-001', '2024-03-10', '대여', '대여중', '박대여'),
('APP-20240309-004', '2024-03-09', '결재', '진행중', '최결재'),
];
static const _pendingApprovals = [
('APP-20240312-010', '설비 구매', '2/4 단계 진행 중'),
('APP-20240311-004', '창고 정기 점검', '승인 대기'),
('APP-20240309-002', '계약 연장', '반려 후 재상신'),
];
@override
Widget build(BuildContext context) {
return const SpecPage(
return AppLayout(
title: '대시보드',
summary: '오늘 입고/출고, 결재 대기, 최근 트랜잭션을 한 눈에 볼 수 있는 메인 화면 구성.',
sections: [
SpecSection(
title: '주요 위젯',
items: [
'오늘 입고/출고 건수, 대기 결재 수 KPI 카드',
'최근 트랜잭션 리스트: 번호 · 일자 · 유형 · 상태 · 작성자',
'내 결재 요청/대기 건 알림 패널',
subtitle: '입·출·대여 현황과 결재 대기를 한 눈에 확인합니다.',
breadcrumbs: const [AppBreadcrumbItem(label: '대시보드')],
child: SingleChildScrollView(
padding: const EdgeInsets.only(right: 12, bottom: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Wrap(
spacing: 16,
runSpacing: 16,
children: const [
_KpiCard(
icon: lucide.LucideIcons.packagePlus,
label: '오늘 입고',
value: '12건',
trend: '+3 vs 어제',
),
_KpiCard(
icon: lucide.LucideIcons.packageMinus,
label: '오늘 출고',
value: '9건',
trend: '-2 vs 어제',
),
_KpiCard(
icon: lucide.LucideIcons.messageSquareWarning,
label: '결재 대기',
value: '5건',
trend: '평균 12시간 지연',
),
_KpiCard(
icon: lucide.LucideIcons.users,
label: '고객사 문의',
value: '7건',
trend: '지원팀 확인 중',
),
],
),
const SizedBox(height: 24),
LayoutBuilder(
builder: (context, constraints) {
final showSidePanel = constraints.maxWidth > 920;
return Flex(
direction: showSidePanel ? Axis.horizontal : Axis.vertical,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
flex: 3,
child: _RecentTransactionsCard(
transactions: _recentTransactions,
),
),
if (showSidePanel)
const SizedBox(width: 16)
else
const SizedBox(height: 16),
Flexible(
flex: 2,
child: _PendingApprovalCard(approvals: _pendingApprovals),
),
],
);
},
),
const SizedBox(height: 24),
const _ReminderPanel(),
],
),
),
);
}
}
class _KpiCard extends StatelessWidget {
const _KpiCard({
required this.icon,
required this.label,
required this.value,
required this.trend,
});
final IconData icon;
final String label;
final String value;
final String trend;
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
return ConstrainedBox(
constraints: const BoxConstraints(minWidth: 220, maxWidth: 260),
child: ShadCard(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, size: 20, color: theme.colorScheme.primary),
const SizedBox(height: 12),
Text(label, style: theme.textTheme.small),
const SizedBox(height: 6),
Text(value, style: theme.textTheme.h3),
const SizedBox(height: 8),
Text(trend, style: theme.textTheme.muted),
],
),
),
);
}
}
class _RecentTransactionsCard extends StatelessWidget {
const _RecentTransactionsCard({required this.transactions});
final List<(String, String, String, String, String)> transactions;
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
return ShadCard(
title: Text('최근 트랜잭션', style: theme.textTheme.h3),
description: Text(
'최근 7일간의 입·출고 및 대여/결재 흐름입니다.',
style: theme.textTheme.muted,
),
child: SizedBox(
height: 320,
child: ShadTable.list(
header: const [
ShadTableCell.header(child: Text('번호')),
ShadTableCell.header(child: Text('일자')),
ShadTableCell.header(child: Text('유형')),
ShadTableCell.header(child: Text('상태')),
ShadTableCell.header(child: Text('작성자')),
],
children: [
for (final row in transactions)
[
ShadTableCell(child: Text(row.$1)),
ShadTableCell(child: Text(row.$2)),
ShadTableCell(child: Text(row.$3)),
ShadTableCell(child: Text(row.$4)),
ShadTableCell(child: Text(row.$5)),
],
],
columnSpanExtent: (index) => const FixedTableSpanExtent(140),
rowSpanExtent: (index) => const FixedTableSpanExtent(52),
),
),
);
}
}
class _PendingApprovalCard extends StatelessWidget {
const _PendingApprovalCard({required this.approvals});
final List<(String, String, String)> approvals;
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
if (approvals.isEmpty) {
return ShadCard(
title: Text('내 결재 대기', style: theme.textTheme.h3),
description: Text(
'현재 승인 대기 중인 결재 요청입니다.',
style: theme.textTheme.muted,
),
child: const SuperportEmptyState(
title: '대기 중인 결재가 없습니다',
description: '새로운 결재 요청이 등록되면 이곳에서 바로 확인할 수 있습니다.',
),
);
}
return ShadCard(
title: Text('내 결재 대기', style: theme.textTheme.h3),
description: Text('현재 승인 대기 중인 결재 요청입니다.', style: theme.textTheme.muted),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (final approval in approvals)
Padding(
padding: const EdgeInsets.symmetric(vertical: 12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(
lucide.LucideIcons.bell,
size: 18,
color: theme.colorScheme.primary,
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(approval.$1, style: theme.textTheme.small),
const SizedBox(height: 4),
Text(approval.$2, style: theme.textTheme.h4),
const SizedBox(height: 4),
Text(approval.$3, style: theme.textTheme.muted),
],
),
),
ShadButton.ghost(
size: ShadButtonSize.sm,
child: const Text('상세'),
onPressed: () {},
),
],
),
),
],
),
);
}
}
class _ReminderPanel extends StatelessWidget {
const _ReminderPanel();
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
return ShadCard(
title: Text('주의/알림', style: theme.textTheme.h3),
description: Text(
'지연된 결재나 시스템 점검 일정을 확인하세요.',
style: theme.textTheme.muted,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: const [
_ReminderItem(
icon: lucide.LucideIcons.clock,
label: '결재 지연',
message: '영업부 장비 구매 결재가 2일째 대기 중입니다.',
),
SizedBox(height: 12),
_ReminderItem(
icon: lucide.LucideIcons.triangleAlert,
label: '시스템 점검',
message: '2024-03-15 22:00 ~ 23:00 서버 점검이 예정되어 있습니다.',
),
SizedBox(height: 12),
_ReminderItem(
icon: lucide.LucideIcons.mail,
label: '고객 문의',
message: '3건의 신규 고객 문의가 접수되었습니다.',
),
],
),
);
}
}
class _ReminderItem extends StatelessWidget {
const _ReminderItem({
required this.icon,
required this.label,
required this.message,
});
final IconData icon;
final String label;
final String message;
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, size: 18, color: theme.colorScheme.secondary),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: theme.textTheme.small),
const SizedBox(height: 4),
Text(message, style: theme.textTheme.p),
],
),
),
],
);
}

View File

@@ -0,0 +1,232 @@
import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
/// 인벤토리 폼에서 공유하는 제품 카탈로그 항목.
class InventoryProductCatalogItem {
const InventoryProductCatalogItem({
required this.code,
required this.name,
required this.manufacturer,
required this.unit,
});
final String code;
final String name;
final String manufacturer;
final String unit;
}
String _normalizeText(String value) {
return value.toLowerCase().replaceAll(RegExp(r'[^a-z0-9가-힣]'), '');
}
/// 제품 카탈로그 유틸리티.
class InventoryProductCatalog {
static final List<InventoryProductCatalogItem> items = List.unmodifiable([
const InventoryProductCatalogItem(
code: 'P-100',
name: 'XR-5000',
manufacturer: '슈퍼벤더',
unit: 'EA',
),
const InventoryProductCatalogItem(
code: 'P-101',
name: 'XR-5001',
manufacturer: '슈퍼벤더',
unit: 'EA',
),
const InventoryProductCatalogItem(
code: 'P-102',
name: 'Eco-200',
manufacturer: '그린텍',
unit: 'EA',
),
const InventoryProductCatalogItem(
code: 'P-201',
name: 'Delta-One',
manufacturer: '델타',
unit: 'SET',
),
const InventoryProductCatalogItem(
code: 'P-210',
name: 'SmartGauge A1',
manufacturer: '슈퍼벤더',
unit: 'EA',
),
const InventoryProductCatalogItem(
code: 'P-305',
name: 'PowerPack Mini',
manufacturer: '에이치솔루션',
unit: 'EA',
),
const InventoryProductCatalogItem(
code: 'P-320',
name: 'Hydra-Flow 2',
manufacturer: '블루하이드',
unit: 'EA',
),
const InventoryProductCatalogItem(
code: 'P-401',
name: 'SolarEdge Pro',
manufacturer: '그린텍',
unit: 'EA',
),
const InventoryProductCatalogItem(
code: 'P-430',
name: 'Alpha-Kit 12',
manufacturer: '테크솔루션',
unit: 'SET',
),
const InventoryProductCatalogItem(
code: 'P-501',
name: 'LogiSense 5',
manufacturer: '슈퍼벤더',
unit: 'EA',
),
]);
static final Map<String, InventoryProductCatalogItem> _byKey = {
for (final item in items) _normalizeText(item.name): item,
};
static InventoryProductCatalogItem? match(String value) {
if (value.isEmpty) return null;
return _byKey[_normalizeText(value)];
}
static List<InventoryProductCatalogItem> filter(String query) {
final normalized = _normalizeText(query.trim());
if (normalized.isEmpty) {
return items.take(12).toList();
}
final lower = query.trim().toLowerCase();
return [
for (final item in items)
if (_normalizeText(item.name).contains(normalized) ||
item.code.toLowerCase().contains(lower))
item,
];
}
}
/// 고객 카탈로그 항목.
class InventoryCustomerCatalogItem {
const InventoryCustomerCatalogItem({
required this.code,
required this.name,
required this.industry,
required this.region,
});
final String code;
final String name;
final String industry;
final String region;
}
/// 고객 카탈로그 유틸리티.
class InventoryCustomerCatalog {
static final List<InventoryCustomerCatalogItem> items = List.unmodifiable([
const InventoryCustomerCatalogItem(
code: 'C-1001',
name: '슈퍼포트 파트너',
industry: '물류',
region: '서울',
),
const InventoryCustomerCatalogItem(
code: 'C-1002',
name: '그린에너지',
industry: '에너지',
region: '대전',
),
const InventoryCustomerCatalogItem(
code: 'C-1003',
name: '테크솔루션',
industry: 'IT 서비스',
region: '부산',
),
const InventoryCustomerCatalogItem(
code: 'C-1004',
name: '에이치솔루션',
industry: '제조',
region: '인천',
),
const InventoryCustomerCatalogItem(
code: 'C-1005',
name: '블루하이드',
industry: '해양장비',
region: '울산',
),
const InventoryCustomerCatalogItem(
code: 'C-1010',
name: '넥스트파워',
industry: '발전설비',
region: '광주',
),
const InventoryCustomerCatalogItem(
code: 'C-1011',
name: '씨에스테크',
industry: '반도체',
region: '수원',
),
const InventoryCustomerCatalogItem(
code: 'C-1012',
name: '알파시스템',
industry: '장비임대',
region: '대구',
),
const InventoryCustomerCatalogItem(
code: 'C-1013',
name: '스타트랩',
industry: '연구개발',
region: '세종',
),
const InventoryCustomerCatalogItem(
code: 'C-1014',
name: '메가스틸',
industry: '철강',
region: '포항',
),
]);
static final Map<String, InventoryCustomerCatalogItem> _byName = {
for (final item in items) item.name: item,
};
static InventoryCustomerCatalogItem? byName(String name) => _byName[name];
static List<InventoryCustomerCatalogItem> filter(String query) {
final normalized = _normalizeText(query.trim());
if (normalized.isEmpty) {
return items;
}
final lower = query.trim().toLowerCase();
return [
for (final item in items)
if (_normalizeText(item.name).contains(normalized) ||
item.code.toLowerCase().contains(lower) ||
_normalizeText(item.industry).contains(normalized) ||
_normalizeText(item.region).contains(normalized))
item,
];
}
static String displayLabel(String name) {
final item = byName(name);
if (item == null) {
return name;
}
return '${item.name} (${item.code})';
}
}
/// 검색 결과가 없을 때 노출할 기본 위젯.
Widget buildEmptySearchResult(
ShadTextTheme textTheme, {
String message = '검색 결과가 없습니다.',
}) {
return Padding(
padding: const EdgeInsets.all(12),
child: Text(message, style: textTheme.muted),
);
}

View File

@@ -0,0 +1,213 @@
import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import '../catalogs.dart';
/// 제품명 입력 시 카탈로그 자동완성을 제공하는 필드.
class InventoryProductAutocompleteField extends StatefulWidget {
const InventoryProductAutocompleteField({
super.key,
required this.productController,
required this.productFocusNode,
required this.manufacturerController,
required this.unitController,
required this.onCatalogMatched,
this.onChanged,
});
final TextEditingController productController;
final FocusNode productFocusNode;
final TextEditingController manufacturerController;
final TextEditingController unitController;
final ValueChanged<InventoryProductCatalogItem?> onCatalogMatched;
final VoidCallback? onChanged;
@override
State<InventoryProductAutocompleteField> createState() =>
_InventoryProductAutocompleteFieldState();
}
class _InventoryProductAutocompleteFieldState
extends State<InventoryProductAutocompleteField> {
InventoryProductCatalogItem? _catalogMatch;
@override
void initState() {
super.initState();
_catalogMatch = InventoryProductCatalog.match(
widget.productController.text.trim(),
);
if (_catalogMatch != null) {
_applyCatalog(_catalogMatch!, updateProduct: false);
}
widget.productController.addListener(_handleTextChanged);
}
@override
void didUpdateWidget(covariant InventoryProductAutocompleteField oldWidget) {
super.didUpdateWidget(oldWidget);
if (!identical(oldWidget.productController, widget.productController)) {
oldWidget.productController.removeListener(_handleTextChanged);
widget.productController.addListener(_handleTextChanged);
_catalogMatch = InventoryProductCatalog.match(
widget.productController.text.trim(),
);
if (_catalogMatch != null) {
_applyCatalog(_catalogMatch!, updateProduct: false);
}
}
}
void _handleTextChanged() {
final text = widget.productController.text.trim();
final match = InventoryProductCatalog.match(text);
if (match != null) {
_applyCatalog(match);
return;
}
if (_catalogMatch != null) {
setState(() {
_catalogMatch = null;
});
widget.onCatalogMatched(null);
if (widget.manufacturerController.text.isNotEmpty) {
widget.manufacturerController.clear();
}
if (widget.unitController.text.isNotEmpty) {
widget.unitController.clear();
}
}
widget.onChanged?.call();
}
void _applyCatalog(
InventoryProductCatalogItem match, {
bool updateProduct = true,
}) {
setState(() {
_catalogMatch = match;
});
widget.onCatalogMatched(match);
if (updateProduct && widget.productController.text != match.name) {
widget.productController.text = match.name;
widget.productController.selection = TextSelection.collapsed(
offset: widget.productController.text.length,
);
}
if (widget.manufacturerController.text != match.manufacturer) {
widget.manufacturerController.text = match.manufacturer;
}
if (widget.unitController.text != match.unit) {
widget.unitController.text = match.unit;
}
widget.onChanged?.call();
}
Iterable<InventoryProductCatalogItem> _options(String query) {
return InventoryProductCatalog.filter(query);
}
@override
void dispose() {
widget.productController.removeListener(_handleTextChanged);
super.dispose();
}
@override
Widget build(BuildContext context) {
final theme = ShadTheme.of(context);
return LayoutBuilder(
builder: (context, constraints) {
return RawAutocomplete<InventoryProductCatalogItem>(
textEditingController: widget.productController,
focusNode: widget.productFocusNode,
optionsBuilder: (textEditingValue) {
return _options(textEditingValue.text);
},
displayStringForOption: (option) => option.name,
onSelected: (option) {
_applyCatalog(option);
},
fieldViewBuilder:
(context, textEditingController, focusNode, onFieldSubmitted) {
return ShadInput(
controller: textEditingController,
focusNode: focusNode,
placeholder: const Text('제품명'),
onChanged: (_) => widget.onChanged?.call(),
onSubmitted: (_) => onFieldSubmitted(),
);
},
optionsViewBuilder: (context, onSelected, options) {
if (options.isEmpty) {
return Align(
alignment: AlignmentDirectional.topStart,
child: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: constraints.maxWidth,
maxHeight: 240,
),
child: Material(
elevation: 6,
color: theme.colorScheme.background,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: BorderSide(color: theme.colorScheme.border),
),
child: buildEmptySearchResult(theme.textTheme),
),
),
);
}
return Align(
alignment: AlignmentDirectional.topStart,
child: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: constraints.maxWidth,
maxHeight: 260,
),
child: Material(
elevation: 6,
color: theme.colorScheme.background,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: BorderSide(color: theme.colorScheme.border),
),
child: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 6),
itemCount: options.length,
itemBuilder: (context, index) {
final option = options.elementAt(index);
return InkWell(
onTap: () => onSelected(option),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 10,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(option.name, style: theme.textTheme.p),
const SizedBox(height: 4),
Text(
'${option.code} · ${option.manufacturer} · ${option.unit}',
style: theme.textTheme.muted.copyWith(
fontSize: 12,
),
),
],
),
),
);
},
),
),
),
);
},
);
},
);
}
}

View File

@@ -0,0 +1,274 @@
import 'package:superport_v2/core/common/models/paginated_result.dart';
import 'package:superport_v2/core/common/utils/json_utils.dart';
import '../../domain/entities/stock_transaction.dart';
/// 재고 트랜잭션 DTO
///
/// - API 응답(JSON)을 도메인 엔티티로 변환하고, 요청 페이로드를 구성한다.
class StockTransactionDto {
StockTransactionDto({
this.id,
required this.transactionNo,
required this.transactionDate,
required this.type,
required this.status,
required this.warehouse,
required this.createdBy,
this.note,
this.isActive = true,
this.createdAt,
this.updatedAt,
this.lines = const [],
this.customers = const [],
this.approval,
this.expectedReturnDate,
});
final int? id;
final String transactionNo;
final DateTime transactionDate;
final StockTransactionType type;
final StockTransactionStatus status;
final StockTransactionWarehouse warehouse;
final StockTransactionEmployee createdBy;
final String? note;
final bool isActive;
final DateTime? createdAt;
final DateTime? updatedAt;
final List<StockTransactionLine> lines;
final List<StockTransactionCustomer> customers;
final StockTransactionApprovalSummary? approval;
final DateTime? expectedReturnDate;
/// JSON 객체를 DTO로 변환한다.
factory StockTransactionDto.fromJson(Map<String, dynamic> json) {
final typeJson = json['transaction_type'] as Map<String, dynamic>?;
final statusJson = json['transaction_status'] as Map<String, dynamic>?;
final warehouseJson = json['warehouse'] as Map<String, dynamic>?;
final createdByJson = json['created_by'] as Map<String, dynamic>?;
return StockTransactionDto(
id: json['id'] as int?,
transactionNo: json['transaction_no'] as String? ?? '',
transactionDate: _parseDate(json['transaction_date']) ?? DateTime.now(),
type: _parseType(typeJson),
status: _parseStatus(statusJson),
warehouse: _parseWarehouse(warehouseJson),
createdBy: _parseEmployee(createdByJson),
note: json['note'] as String?,
isActive: (json['is_active'] as bool?) ?? true,
createdAt: _parseDateTime(json['created_at']),
updatedAt: _parseDateTime(json['updated_at']),
lines: _parseLines(json),
customers: _parseCustomers(json),
approval: _parseApproval(json['approval']),
expectedReturnDate:
_parseDate(json['expected_return_date']) ??
_parseDate(json['planned_return_date']) ??
_parseDate(json['return_due_date']),
);
}
/// 도메인 엔티티로 변환한다.
StockTransaction toEntity() {
return StockTransaction(
id: id,
transactionNo: transactionNo,
transactionDate: transactionDate,
type: type,
status: status,
warehouse: warehouse,
createdBy: createdBy,
note: note,
isActive: isActive,
createdAt: createdAt,
updatedAt: updatedAt,
lines: lines,
customers: customers,
approval: approval,
expectedReturnDate: expectedReturnDate,
);
}
/// 페이지네이션 응답을 파싱한다.
static PaginatedResult<StockTransaction> parsePaginated(dynamic json) {
final raw = JsonUtils.extractList(json, keys: const ['items']);
final items = raw
.map(StockTransactionDto.fromJson)
.map((dto) => dto.toEntity())
.toList(growable: false);
final map = json is Map<String, dynamic> ? json : <String, dynamic>{};
return PaginatedResult<StockTransaction>(
items: items,
page: JsonUtils.readInt(map, 'page', fallback: 1),
pageSize: JsonUtils.readInt(map, 'page_size', fallback: items.length),
total: JsonUtils.readInt(map, 'total', fallback: items.length),
);
}
/// 단건 응답을 파싱한다.
static StockTransaction? parseSingle(dynamic json) {
final map = JsonUtils.extractMap(json, keys: const ['data']);
if (map.isEmpty) {
return null;
}
return StockTransactionDto.fromJson(map).toEntity();
}
}
StockTransactionType _parseType(Map<String, dynamic>? json) {
return StockTransactionType(
id: json?['id'] as int? ?? 0,
name: json?['type_name'] as String? ?? '',
);
}
StockTransactionStatus _parseStatus(Map<String, dynamic>? json) {
return StockTransactionStatus(
id: json?['id'] as int? ?? 0,
name: json?['status_name'] as String? ?? '',
);
}
StockTransactionWarehouse _parseWarehouse(Map<String, dynamic>? json) {
final zipcode = json?['zipcode'] as Map<String, dynamic>?;
return StockTransactionWarehouse(
id: json?['id'] as int? ?? 0,
code: json?['warehouse_code'] as String? ?? '',
name: json?['warehouse_name'] as String? ?? '',
zipcode: zipcode?['zipcode'] as String?,
addressLine: zipcode?['road_name'] as String?,
);
}
StockTransactionEmployee _parseEmployee(Map<String, dynamic>? json) {
return StockTransactionEmployee(
id: json?['id'] as int? ?? 0,
employeeNo: json?['employee_no'] as String? ?? '',
name: json?['employee_name'] as String? ?? '',
);
}
List<StockTransactionLine> _parseLines(Map<String, dynamic> json) {
final raw = JsonUtils.extractList(json, keys: const ['lines']);
return [
for (final item in raw)
StockTransactionLine(
id: item['id'] as int?,
lineNo: JsonUtils.readInt(item, 'line_no', fallback: 1),
product: _parseProduct(item['product'] as Map<String, dynamic>?),
quantity: JsonUtils.readInt(item, 'quantity', fallback: 0),
unitPrice: _readDouble(item['unit_price']),
note: item['note'] as String?,
),
];
}
StockTransactionProduct _parseProduct(Map<String, dynamic>? json) {
final vendorJson = json?['vendor'] as Map<String, dynamic>?;
final uomJson = json?['uom'] as Map<String, dynamic>?;
return StockTransactionProduct(
id: json?['id'] as int? ?? 0,
code: json?['product_code'] as String? ?? json?['code'] as String? ?? '',
name: json?['product_name'] as String? ?? json?['name'] as String? ?? '',
vendor: vendorJson == null
? null
: StockTransactionVendorSummary(
id: vendorJson['id'] as int? ?? 0,
name:
vendorJson['vendor_name'] as String? ??
vendorJson['name'] as String? ??
'',
),
uom: uomJson == null
? null
: StockTransactionUomSummary(
id: uomJson['id'] as int? ?? 0,
name:
uomJson['uom_name'] as String? ??
uomJson['name'] as String? ??
'',
),
);
}
List<StockTransactionCustomer> _parseCustomers(Map<String, dynamic> json) {
final raw = JsonUtils.extractList(json, keys: const ['customers']);
return [
for (final item in raw)
StockTransactionCustomer(
id: item['id'] as int?,
customer: _parseCustomer(item['customer'] as Map<String, dynamic>?),
note: item['note'] as String?,
),
];
}
StockTransactionCustomerSummary _parseCustomer(Map<String, dynamic>? json) {
return StockTransactionCustomerSummary(
id: json?['id'] as int? ?? 0,
code: json?['customer_code'] as String? ?? json?['code'] as String? ?? '',
name: json?['customer_name'] as String? ?? json?['name'] as String? ?? '',
);
}
StockTransactionApprovalSummary? _parseApproval(dynamic raw) {
if (raw is! Map<String, dynamic>) {
return null;
}
final status = raw['approval_status'] as Map<String, dynamic>?;
return StockTransactionApprovalSummary(
id: raw['id'] as int? ?? 0,
approvalNo: raw['approval_no'] as String? ?? '',
status: status == null
? null
: StockTransactionApprovalStatusSummary(
id: status['id'] as int? ?? 0,
name:
status['status_name'] as String? ??
status['name'] as String? ??
'',
isBlocking: status['is_blocking_next'] as bool?,
),
);
}
DateTime? _parseDate(Object? value) {
if (value == null) {
return null;
}
if (value is DateTime) {
return value;
}
if (value is String && value.isNotEmpty) {
return DateTime.tryParse(value);
}
return null;
}
DateTime? _parseDateTime(Object? value) {
if (value == null) {
return null;
}
if (value is DateTime) {
return value;
}
if (value is String && value.isNotEmpty) {
return DateTime.tryParse(value);
}
return null;
}
double _readDouble(Object? value) {
if (value is double) {
return value;
}
if (value is int) {
return value.toDouble();
}
if (value is String) {
return double.tryParse(value) ?? 0;
}
return 0;
}

View File

@@ -0,0 +1,233 @@
/// 재고 트랜잭션 도메인 엔티티
///
/// - 입고/출고/대여 공통으로 사용되는 헤더와 라인, 고객 연결 정보를 포함한다.
class StockTransaction {
StockTransaction({
this.id,
required this.transactionNo,
required this.transactionDate,
required this.type,
required this.status,
required this.warehouse,
required this.createdBy,
this.note,
this.isActive = true,
this.createdAt,
this.updatedAt,
this.lines = const [],
this.customers = const [],
this.approval,
this.expectedReturnDate,
});
final int? id;
final String transactionNo;
final DateTime transactionDate;
final StockTransactionType type;
final StockTransactionStatus status;
final StockTransactionWarehouse warehouse;
final StockTransactionEmployee createdBy;
final String? note;
final bool isActive;
final DateTime? createdAt;
final DateTime? updatedAt;
final List<StockTransactionLine> lines;
final List<StockTransactionCustomer> customers;
final StockTransactionApprovalSummary? approval;
final DateTime? expectedReturnDate;
int get itemCount => lines.length;
int get totalQuantity => lines.fold<int>(
0,
(previousValue, line) => previousValue + line.quantity,
);
StockTransaction copyWith({
int? id,
String? transactionNo,
DateTime? transactionDate,
StockTransactionType? type,
StockTransactionStatus? status,
StockTransactionWarehouse? warehouse,
StockTransactionEmployee? createdBy,
String? note,
bool? isActive,
DateTime? createdAt,
DateTime? updatedAt,
List<StockTransactionLine>? lines,
List<StockTransactionCustomer>? customers,
StockTransactionApprovalSummary? approval,
DateTime? expectedReturnDate,
}) {
return StockTransaction(
id: id ?? this.id,
transactionNo: transactionNo ?? this.transactionNo,
transactionDate: transactionDate ?? this.transactionDate,
type: type ?? this.type,
status: status ?? this.status,
warehouse: warehouse ?? this.warehouse,
createdBy: createdBy ?? this.createdBy,
note: note ?? this.note,
isActive: isActive ?? this.isActive,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt,
lines: lines ?? this.lines,
customers: customers ?? this.customers,
approval: approval ?? this.approval,
expectedReturnDate: expectedReturnDate ?? this.expectedReturnDate,
);
}
}
/// 재고 트랜잭션 유형 요약 정보
class StockTransactionType {
StockTransactionType({required this.id, required this.name});
final int id;
final String name;
}
/// 재고 트랜잭션 상태 요약 정보
class StockTransactionStatus {
StockTransactionStatus({required this.id, required this.name});
final int id;
final String name;
}
/// 재고 트랜잭션 작성자 정보
class StockTransactionEmployee {
StockTransactionEmployee({
required this.id,
required this.employeeNo,
required this.name,
});
final int id;
final String employeeNo;
final String name;
}
/// 재고 트랜잭션 창고 정보 요약
class StockTransactionWarehouse {
StockTransactionWarehouse({
required this.id,
required this.code,
required this.name,
this.zipcode,
this.addressLine,
});
final int id;
final String code;
final String name;
final String? zipcode;
final String? addressLine;
}
/// 재고 트랜잭션 품목(라인)
class StockTransactionLine {
StockTransactionLine({
this.id,
required this.lineNo,
required this.product,
required this.quantity,
required this.unitPrice,
this.note,
});
final int? id;
final int lineNo;
final StockTransactionProduct product;
final int quantity;
final double unitPrice;
final String? note;
}
/// 재고 트랜잭션 품목의 제품 정보 요약
class StockTransactionProduct {
StockTransactionProduct({
required this.id,
required this.code,
required this.name,
this.vendor,
this.uom,
});
final int id;
final String code;
final String name;
final StockTransactionVendorSummary? vendor;
final StockTransactionUomSummary? uom;
}
/// 재고 트랜잭션에 연결된 고객 정보
class StockTransactionCustomer {
StockTransactionCustomer({this.id, required this.customer, this.note});
final int? id;
final StockTransactionCustomerSummary customer;
final String? note;
}
/// 고객 요약 정보
class StockTransactionCustomerSummary {
StockTransactionCustomerSummary({
required this.id,
required this.code,
required this.name,
});
final int id;
final String code;
final String name;
}
/// 제품의 공급사 요약 정보
class StockTransactionVendorSummary {
StockTransactionVendorSummary({required this.id, required this.name});
final int id;
final String name;
}
/// 제품 단위 요약 정보
class StockTransactionUomSummary {
StockTransactionUomSummary({required this.id, required this.name});
final int id;
final String name;
}
/// 결재 요약 정보
class StockTransactionApprovalSummary {
StockTransactionApprovalSummary({
required this.id,
required this.approvalNo,
this.status,
});
final int id;
final String approvalNo;
final StockTransactionApprovalStatusSummary? status;
}
/// 결재 상태 요약 정보
class StockTransactionApprovalStatusSummary {
StockTransactionApprovalStatusSummary({
required this.id,
required this.name,
this.isBlocking,
});
final int id;
final String name;
final bool? isBlocking;
}
extension StockTransactionLineX on List<StockTransactionLine> {
/// 라인 품목 가격 총액을 계산한다.
double get totalAmount =>
fold<double>(0, (sum, line) => sum + (line.quantity * line.unitPrice));
}

View File

@@ -15,6 +15,8 @@ class _LoginPageState extends State<LoginPage> {
final idController = TextEditingController();
final passwordController = TextEditingController();
bool rememberMe = false;
bool isLoading = false;
String? errorMessage;
@override
void dispose() {
@@ -23,7 +25,35 @@ class _LoginPageState extends State<LoginPage> {
super.dispose();
}
void _handleSubmit() {
Future<void> _handleSubmit() async {
if (isLoading) return;
setState(() {
errorMessage = null;
isLoading = true;
});
final id = idController.text.trim();
final password = passwordController.text.trim();
await Future<void>.delayed(const Duration(milliseconds: 600));
if (id.isEmpty || password.isEmpty) {
setState(() {
errorMessage = '아이디와 비밀번호를 모두 입력하세요.';
isLoading = false;
});
return;
}
if (password.length < 6) {
setState(() {
errorMessage = '비밀번호는 6자 이상이어야 합니다.';
isLoading = false;
});
return;
}
if (!mounted) return;
context.go(dashboardRoutePath);
}
@@ -73,9 +103,33 @@ class _LoginPageState extends State<LoginPage> {
],
),
const SizedBox(height: 24),
if (errorMessage != null)
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Text(
errorMessage!,
style: theme.textTheme.small.copyWith(
color: theme.colorScheme.destructive,
),
),
),
ShadButton(
onPressed: _handleSubmit,
child: const Text('로그인'),
onPressed: isLoading ? null : _handleSubmit,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
if (isLoading) ...[
const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
),
const SizedBox(width: 8),
],
const Text('로그인'),
],
),
),
],
),

View File

@@ -6,6 +6,7 @@ import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport_v2/core/constants/app_sections.dart';
import 'package:superport_v2/widgets/app_layout.dart';
import 'package:superport_v2/widgets/components/filter_bar.dart';
import 'package:superport_v2/widgets/components/superport_dialog.dart';
import 'package:superport_v2/features/util/postal_search/presentation/models/postal_search_result.dart';
import 'package:superport_v2/features/util/postal_search/presentation/widgets/postal_search_dialog.dart';
@@ -198,6 +199,33 @@ class _CustomerEnabledPageState extends State<_CustomerEnabledPage> {
),
],
toolbar: FilterBar(
actions: [
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
if (showReset)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateTypeFilter(CustomerTypeFilter.all);
_controller.updateStatusFilter(
CustomerStatusFilter.all,
);
_updateRoute(
page: 1,
queryOverride: '',
typeOverride: CustomerTypeFilter.all,
statusOverride: CustomerStatusFilter.all,
);
},
child: const Text('초기화'),
),
],
children: [
SizedBox(
width: 260,
@@ -251,31 +279,6 @@ class _CustomerEnabledPageState extends State<_CustomerEnabledPage> {
.toList(),
),
),
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
if (showReset)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateTypeFilter(CustomerTypeFilter.all);
_controller.updateStatusFilter(
CustomerStatusFilter.all,
);
_updateRoute(
page: 1,
queryOverride: '',
typeOverride: CustomerTypeFilter.all,
statusOverride: CustomerStatusFilter.all,
);
},
child: const Text('초기화'),
),
],
),
child: ShadCard(
@@ -515,395 +518,427 @@ class _CustomerEnabledPageState extends State<_CustomerEnabledPage> {
final codeError = ValueNotifier<String?>(null);
final nameError = ValueNotifier<String?>(null);
final typeError = ValueNotifier<String?>(null);
final zipcodeError = 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);
Future<void> openPostalSearch() async {
final keyword = zipcodeController.text.trim();
final result = await showPostalSearchDialog(
dialogContext,
initialKeyword: keyword.isEmpty ? null : keyword,
);
if (result == null) {
return;
}
zipcodeController
..text = result.zipcode
..selection = TextSelection.collapsed(
offset: result.zipcode.length,
);
selectedPostalNotifier.value = result;
if (result.fullAddress.isNotEmpty) {
addressController
..text = result.fullAddress
..selection = TextSelection.collapsed(
offset: addressController.text.length,
);
}
var isApplyingPostalSelection = false;
void handleZipcodeChange() {
if (isApplyingPostalSelection) {
return;
}
final text = zipcodeController.text.trim();
final selection = selectedPostalNotifier.value;
if (text.isEmpty) {
if (selection != null) {
selectedPostalNotifier.value = null;
}
zipcodeError.value = null;
return;
}
if (selection != null && selection.zipcode != text) {
selectedPostalNotifier.value = null;
}
if (zipcodeError.value != null) {
zipcodeError.value = null;
}
}
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;
void handlePostalSelectionChange() {
if (selectedPostalNotifier.value != null) {
zipcodeError.value = null;
}
}
codeError.value = code.isEmpty
? '고객사코드를 입력하세요.'
: null;
nameError.value = name.isEmpty
? '고객사명을 입력하세요.'
: null;
zipcodeController.addListener(handleZipcodeChange);
selectedPostalNotifier.addListener(handlePostalSelectionChange);
if (!partner && !general) {
general = true;
generalNotifier.value = true;
}
Future<void> openPostalSearch(BuildContext dialogContext) async {
final keyword = zipcodeController.text.trim();
final result = await showPostalSearchDialog(
dialogContext,
initialKeyword: keyword.isEmpty ? null : keyword,
);
if (result == null) {
return;
}
isApplyingPostalSelection = true;
zipcodeController
..text = result.zipcode
..selection = TextSelection.collapsed(offset: result.zipcode.length);
isApplyingPostalSelection = false;
selectedPostalNotifier.value = result;
if (result.fullAddress.isNotEmpty) {
addressController
..text = result.fullAddress
..selection = TextSelection.collapsed(
offset: addressController.text.length,
);
}
}
typeError.value = (!partner && !general)
? '파트너/일반 중 하나 이상 선택하세요.'
: null;
await SuperportDialog.show<bool>(
context: parentContext,
dialog: SuperportDialog(
title: isEdit ? '고객사 수정' : '고객사 등록',
description: '고객사 기본 정보를 ${isEdit ? '수정' : '입력'}하세요.',
primaryAction: ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (context, isSaving, _) {
return 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;
final selectedPostal = selectedPostalNotifier.value;
if (codeError.value != null ||
nameError.value != null ||
typeError.value != null) {
return;
}
codeError.value = code.isEmpty ? '고객사코드를 입력하세요.' : null;
nameError.value = name.isEmpty ? '고객사명을 입력하세요.' : null;
zipcodeError.value =
zipcode.isNotEmpty && selectedPostal == null
? '우편번호 검색으로 주소를 선택하세요.'
: null;
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);
if (!partner && !general) {
general = true;
generalNotifier.value = true;
}
typeError.value = (!partner && !general)
? '파트너/일반 중 하나 이상 선택하세요.'
: null;
if (codeError.value != null ||
nameError.value != null ||
zipcodeError.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 navigator = Navigator.of(context);
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 ? '저장' : '등록'),
);
},
),
secondaryAction: ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (context, isSaving, _) {
return ShadButton.ghost(
onPressed: isSaving
? null
: () => Navigator.of(context).pop(false),
child: const Text('취소'),
);
},
),
child: ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (context, isSaving, _) {
final theme = ShadTheme.of(context);
final materialTheme = Theme.of(context);
return 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;
}
},
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,
),
),
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<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),
ValueListenableBuilder<bool>(
valueListenable: partnerNotifier,
builder: (_, partner, __) {
return ValueListenableBuilder<bool>(
valueListenable: generalNotifier,
builder: (_, general, __) {
return ValueListenableBuilder<String?>(
valueListenable: typeError,
builder: (_, errorText, __) {
final onChanged = isSaving
? null
: (bool? value) {
if (value == null) return;
partnerNotifier.value = value;
if (!value && !generalNotifier.value) {
typeError.value =
'파트너/일반 중 하나 이상 선택하세요.';
} else {
typeError.value = null;
}
};
final onChangedGeneral = isSaving
? 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: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: ShadInput(
controller: zipcodeController,
placeholder: const Text('예: 06000'),
keyboardType: TextInputType.number,
),
],
),
),
const SizedBox(width: 8),
ShadButton.outline(
onPressed: saving.value
? null
: openPostalSearch,
child: const Text('검색'),
),
],
),
const SizedBox(height: 8),
ValueListenableBuilder<PostalSearchResult?>(
valueListenable: selectedPostalNotifier,
builder: (_, selection, __) {
if (selection == null) {
return Text(
'검색 버튼을 눌러 주소를 선택하세요.',
style: theme.textTheme.small.copyWith(
color: theme.colorScheme.mutedForeground,
),
);
}
final fullAddress = selection.fullAddress;
return Text(
fullAddress.isEmpty
? '선택한 우편번호에 주소 정보가 없습니다.'
: fullAddress,
style: theme.textTheme.small,
);
},
),
],
),
);
},
);
},
),
const SizedBox(height: 16),
_FormField(
label: '이메일',
child: ShadInput(
controller: emailController,
keyboardType: TextInputType.emailAddress,
),
const SizedBox(height: 16),
_FormField(
label: '상세주소',
child: ShadInput(
controller: addressController,
placeholder: const Text('상세주소 입력'),
),
),
const SizedBox(height: 16),
_FormField(
label: '연락처',
child: ShadInput(
controller: mobileController,
keyboardType: TextInputType.phone,
),
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(height: 16),
ValueListenableBuilder<String?>(
valueListenable: zipcodeError,
builder: (_, zipcodeErrorText, __) {
return _FormField(
label: '우편번호',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: ShadInput(
controller: zipcodeController,
placeholder: const Text('예: 06000'),
keyboardType: TextInputType.number,
),
),
const SizedBox(width: 8),
ShadButton.outline(
onPressed: isSaving
? null
: () => openPostalSearch(context),
child: const Text('검색'),
),
],
),
const SizedBox(height: 8),
ValueListenableBuilder<PostalSearchResult?>(
valueListenable: selectedPostalNotifier,
builder: (_, selection, __) {
if (selection == null) {
return Text(
'검색 버튼을 눌러 주소를 선택하세요.',
style: theme.textTheme.small.copyWith(
color: theme.colorScheme.mutedForeground,
),
);
}
final fullAddress = selection.fullAddress;
return Text(
fullAddress.isEmpty
? '선택한 우편번호에 주소 정보가 없습니다.'
: fullAddress,
style: theme.textTheme.small,
);
},
),
if (zipcodeErrorText != null)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
zipcodeErrorText,
style: theme.textTheme.small.copyWith(
color: materialTheme.colorScheme.error,
),
),
),
const SizedBox(width: 8),
Text(value ? '사용' : '미사용'),
],
),
);
},
],
),
);
},
),
const SizedBox(height: 16),
_FormField(
label: '상세주소',
child: ShadInput(
controller: addressController,
placeholder: const Text('상세주소 입력'),
),
const SizedBox(height: 16),
_FormField(
label: '비고',
child: ShadTextarea(controller: noteController),
),
if (existing != null) ..._buildAuditInfo(existing, theme),
],
),
),
const SizedBox(height: 16),
ValueListenableBuilder<bool>(
valueListenable: isActiveNotifier,
builder: (_, value, __) {
return _FormField(
label: '사용여부',
child: Row(
children: [
ShadSwitch(
value: value,
onChanged: isSaving
? 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),
],
),
),
),
);
},
);
},
),
),
);
zipcodeController.removeListener(handleZipcodeChange);
selectedPostalNotifier.removeListener(handlePostalSelectionChange);
codeController.dispose();
nameController.dispose();
@@ -920,27 +955,26 @@ class _CustomerEnabledPageState extends State<_CustomerEnabledPage> {
codeError.dispose();
nameError.dispose();
typeError.dispose();
zipcodeError.dispose();
}
Future<void> _confirmDelete(Customer customer) async {
final confirmed = await showDialog<bool>(
final confirmed = await SuperportDialog.show<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('삭제'),
),
],
);
},
dialog: SuperportDialog(
title: '고객사 삭제',
description: '"${customer.customerName}" 고객사 삭제하시겠습니까?',
actions: [
ShadButton.ghost(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('취소'),
),
ShadButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('삭제'),
),
],
),
);
if (confirmed == true && customer.id != null) {

View File

@@ -5,6 +5,7 @@ import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport_v2/core/constants/app_sections.dart';
import 'package:superport_v2/widgets/app_layout.dart';
import 'package:superport_v2/widgets/components/filter_bar.dart';
import 'package:superport_v2/widgets/components/superport_dialog.dart';
import '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
@@ -130,7 +131,8 @@ class _GroupEnabledPageState extends State<_GroupEnabledPage> {
? false
: (result.page * result.pageSize) < result.total;
final showReset = _searchController.text.isNotEmpty ||
final showReset =
_searchController.text.isNotEmpty ||
_controller.defaultFilter != GroupDefaultFilter.all ||
_controller.statusFilter != GroupStatusFilter.all;
@@ -145,12 +147,35 @@ class _GroupEnabledPageState extends State<_GroupEnabledPage> {
actions: [
ShadButton(
leading: const Icon(LucideIcons.plus, size: 16),
onPressed:
_controller.isSubmitting ? null : () => _openGroupForm(context),
onPressed: _controller.isSubmitting
? null
: () => _openGroupForm(context),
child: const Text('신규 등록'),
),
],
toolbar: FilterBar(
actions: [
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
if (showReset)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateDefaultFilter(
GroupDefaultFilter.all,
);
_controller.updateStatusFilter(GroupStatusFilter.all);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
children: [
SizedBox(
width: 260,
@@ -206,28 +231,6 @@ class _GroupEnabledPageState extends State<_GroupEnabledPage> {
.toList(),
),
),
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
if (showReset)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateDefaultFilter(
GroupDefaultFilter.all,
);
_controller.updateStatusFilter(
GroupStatusFilter.all,
);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
),
child: ShadCard(
@@ -272,26 +275,22 @@ class _GroupEnabledPageState extends State<_GroupEnabledPage> {
child: Center(child: CircularProgressIndicator()),
)
: groups.isEmpty
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
'조건에 맞는 그룹이 없습니다.',
style: theme.textTheme.muted,
),
)
: _GroupTable(
groups: groups,
dateFormat: _dateFormat,
onEdit: _controller.isSubmitting
? null
: (group) => _openGroupForm(context, group: group),
onDelete: _controller.isSubmitting
? null
: _confirmDelete,
onRestore: _controller.isSubmitting
? null
: _restoreGroup,
),
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
'조건에 맞는 그룹이 없습니다.',
style: theme.textTheme.muted,
),
)
: _GroupTable(
groups: groups,
dateFormat: _dateFormat,
onEdit: _controller.isSubmitting
? null
: (group) => _openGroupForm(context, group: group),
onDelete: _controller.isSubmitting ? null : _confirmDelete,
onRestore: _controller.isSubmitting ? null : _restoreGroup,
),
),
);
},
@@ -352,199 +351,185 @@ class _GroupEnabledPageState extends State<_GroupEnabledPage> {
final saving = ValueNotifier<bool>(false);
final nameError = ValueNotifier<String?>(null);
await showDialog<bool>(
await SuperportDialog.show<void>(
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 name = nameController.text.trim();
final description = descriptionController.text
.trim();
final note = noteController.text.trim();
dialog: SuperportDialog(
title: isEdit ? '그룹 수정' : '그룹 등록',
description: '그룹 정보를 ${isEdit ? '수정' : '입력'}하세요.',
constraints: const BoxConstraints(maxWidth: 540),
actions: [
ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (dialogContext, isSaving, __) {
return ShadButton.ghost(
onPressed: isSaving
? null
: () => Navigator.of(dialogContext).pop(),
child: const Text('취소'),
);
},
),
ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (dialogContext, isSaving, __) {
return ShadButton(
onPressed: isSaving
? null
: () async {
final name = nameController.text.trim();
final description = descriptionController.text.trim();
final note = noteController.text.trim();
nameError.value = name.isEmpty
? '그룹명을 입력하세요.'
: null;
nameError.value = name.isEmpty ? '그룹명을 입력하세요.' : null;
if (nameError.value != null) {
return;
}
if (nameError.value != null) {
return;
}
saving.value = true;
final input = GroupInput(
groupName: name,
description: description.isEmpty
? null
: description,
isDefault: isDefaultNotifier.value,
isActive: isActiveNotifier.value,
note: note.isEmpty ? null : note,
);
final response = isEdit
? await _controller.update(groupId!, input)
: await _controller.create(input);
saving.value = false;
if (response != null) {
if (!navigator.mounted) {
return;
saving.value = true;
final input = GroupInput(
groupName: name,
description: description.isEmpty ? null : description,
isDefault: isDefaultNotifier.value,
isActive: isActiveNotifier.value,
note: note.isEmpty ? null : note,
);
final navigator = Navigator.of(dialogContext);
final response = isEdit
? await _controller.update(groupId!, input)
: await _controller.create(input);
saving.value = false;
if (response != null) {
if (!navigator.mounted) {
return;
}
if (mounted) {
_showSnack(isEdit ? '그룹을 수정했습니다.' : '그룹을 등록했습니다.');
}
navigator.pop();
}
},
child: Text(isEdit ? '저장' : '등록'),
);
},
),
],
child: StatefulBuilder(
builder: (dialogContext, _) {
final theme = ShadTheme.of(dialogContext);
final materialTheme = Theme.of(dialogContext);
return SizedBox(
width: double.infinity,
child: SingleChildScrollView(
padding: const EdgeInsets.only(right: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
ValueListenableBuilder<String?>(
valueListenable: nameError,
builder: (_, errorText, __) {
return _FormField(
label: '그룹명',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ShadInput(
controller: nameController,
readOnly: isEdit,
onChanged: (_) {
if (nameController.text.trim().isNotEmpty) {
nameError.value = null;
}
if (mounted) {
_showSnack(
isEdit ? '그룹을 수정했습니다.' : '그룹을 등록했습니다.',
);
}
navigator.pop(true);
}
},
child: Text(isEdit ? '저장' : '등록'),
),
],
);
},
),
child: SizedBox(
width: double.infinity,
child: SingleChildScrollView(
padding: const EdgeInsets.only(right: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
ValueListenableBuilder<String?>(
valueListenable: nameError,
builder: (_, errorText, __) {
return _FormField(
label: '그룹명',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ShadInput(
controller: nameController,
readOnly: isEdit,
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,
),
},
),
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: ShadTextarea(controller: descriptionController),
),
const SizedBox(height: 16),
ValueListenableBuilder<bool>(
valueListenable: isDefaultNotifier,
builder: (_, value, __) {
return _FormField(
label: '기본여부',
child: Row(
children: [
ShadSwitch(
value: value,
onChanged: saving.value
? null
: (next) =>
isDefaultNotifier.value = next,
),
const SizedBox(width: 8),
Text(value ? '기본 그룹' : '일반 그룹'),
],
),
);
},
],
),
);
},
),
const SizedBox(height: 16),
_FormField(
label: '설명',
child: ShadTextarea(controller: descriptionController),
),
const SizedBox(height: 16),
ValueListenableBuilder<bool>(
valueListenable: isDefaultNotifier,
builder: (_, value, __) {
return _FormField(
label: '기본여부',
child: Row(
children: [
ShadSwitch(
value: value,
onChanged: saving.value
? null
: (next) => isDefaultNotifier.value = next,
),
const SizedBox(width: 8),
Text(value ? '기본 그룹' : '일반 그룹'),
],
),
);
},
),
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 (existingGroup != null) ...[
const SizedBox(height: 20),
Text(
'생성일시: ${_formatDateTime(existingGroup.createdAt)}',
style: theme.textTheme.small,
),
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: 4),
Text(
'수정일시: ${_formatDateTime(existingGroup.updatedAt)}',
style: theme.textTheme.small,
),
const SizedBox(height: 16),
_FormField(
label: '비고',
child: ShadTextarea(controller: noteController),
),
if (isEdit) ...[
const SizedBox(height: 20),
Text(
'생성일시: ${_formatDateTime(existingGroup.createdAt)}',
style: theme.textTheme.small,
),
const SizedBox(height: 4),
Text(
'수정일시: ${_formatDateTime(existingGroup.updatedAt)}',
style: theme.textTheme.small,
),
],
],
),
],
),
),
),
),
);
},
);
},
),
),
);
nameController.dispose();

View File

@@ -6,6 +6,7 @@ import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport_v2/core/constants/app_sections.dart';
import 'package:superport_v2/widgets/app_layout.dart';
import 'package:superport_v2/widgets/components/filter_bar.dart';
import 'package:superport_v2/widgets/components/superport_dialog.dart';
import '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
@@ -167,7 +168,8 @@ class _GroupPermissionEnabledPageState
? false
: (result.page * result.pageSize) < result.total;
final showReset = _searchController.text.isNotEmpty ||
final showReset =
_searchController.text.isNotEmpty ||
_controller.groupFilter != null ||
_controller.menuFilter != null ||
_controller.statusFilter != GroupPermissionStatusFilter.all ||
@@ -191,6 +193,29 @@ class _GroupPermissionEnabledPageState
),
],
toolbar: FilterBar(
actions: [
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
if (showReset)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateGroupFilter(null);
_controller.updateMenuFilter(null);
_controller.updateIncludeDeleted(false);
_controller.updateStatusFilter(
GroupPermissionStatusFilter.all,
);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
children: [
SizedBox(
width: 260,
@@ -208,16 +233,12 @@ class _GroupPermissionEnabledPageState
key: ValueKey(_controller.groupFilter),
initialValue: _controller.groupFilter,
placeholder: Text(
_controller.groups.isEmpty
? '그룹 로딩중...'
: '그룹 전체',
_controller.groups.isEmpty ? '그룹 로딩중...' : '그룹 전체',
),
selectedOptionBuilder: (context, value) {
if (value == null) {
return Text(
_controller.groups.isEmpty
? '그룹 로딩중...'
: '그룹 전체',
_controller.groups.isEmpty ? '그룹 로딩중...' : '그룹 전체',
);
}
final group = _controller.groups.firstWhere(
@@ -230,10 +251,7 @@ class _GroupPermissionEnabledPageState
_controller.updateGroupFilter(value);
},
options: [
const ShadOption<int?>(
value: null,
child: Text('그룹 전체'),
),
const ShadOption<int?>(value: null, child: Text('그룹 전체')),
..._controller.groups.map(
(group) => ShadOption<int?>(
value: group.id,
@@ -249,25 +267,18 @@ class _GroupPermissionEnabledPageState
key: ValueKey(_controller.menuFilter),
initialValue: _controller.menuFilter,
placeholder: Text(
_controller.menus.isEmpty
? '메뉴 로딩중...'
: '메뉴 전체',
_controller.menus.isEmpty ? '메뉴 로딩중...' : '메뉴 전체',
),
selectedOptionBuilder: (context, value) {
if (value == null) {
return Text(
_controller.menus.isEmpty
? '메뉴 로딩중...'
: '메뉴 전체',
_controller.menus.isEmpty ? '메뉴 로딩중...' : '메뉴 전체',
);
}
final menuItem = _controller.menus.firstWhere(
(m) => m.id == value,
orElse: () => MenuItem(
id: value,
menuCode: '',
menuName: '',
),
orElse: () =>
MenuItem(id: value, menuCode: '', menuName: ''),
);
return Text(menuItem.menuName);
},
@@ -275,10 +286,7 @@ class _GroupPermissionEnabledPageState
_controller.updateMenuFilter(value);
},
options: [
const ShadOption<int?>(
value: null,
child: Text('메뉴 전체'),
),
const ShadOption<int?>(value: null, child: Text('메뉴 전체')),
..._controller.menus.map(
(menuItem) => ShadOption<int?>(
value: menuItem.id,
@@ -322,24 +330,6 @@ class _GroupPermissionEnabledPageState
const Text('삭제 포함'),
],
),
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
if (showReset)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateGroupFilter(null);
_controller.updateMenuFilter(null);
_controller.updateIncludeDeleted(false);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
),
child: ShadCard(
@@ -384,27 +374,27 @@ class _GroupPermissionEnabledPageState
child: Center(child: CircularProgressIndicator()),
)
: permissions.isEmpty
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
'조건에 맞는 권한이 없습니다.',
style: theme.textTheme.muted,
),
)
: _PermissionTable(
permissions: permissions,
dateFormat: _dateFormat,
onEdit: _controller.isSubmitting
? null
: (permission) =>
_openPermissionForm(context, permission: permission),
onDelete: _controller.isSubmitting
? null
: _confirmDelete,
onRestore: _controller.isSubmitting
? null
: _restorePermission,
),
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
'조건에 맞는 권한이 없습니다.',
style: theme.textTheme.muted,
),
)
: _PermissionTable(
permissions: permissions,
dateFormat: _dateFormat,
onEdit: _controller.isSubmitting
? null
: (permission) => _openPermissionForm(
context,
permission: permission,
),
onDelete: _controller.isSubmitting ? null : _confirmDelete,
onRestore: _controller.isSubmitting
? null
: _restorePermission,
),
),
);
},
@@ -430,311 +420,302 @@ class _GroupPermissionEnabledPageState
BuildContext context, {
GroupPermission? permission,
}) async {
final isEdit = permission != null;
final permissionId = permission?.id;
final existingPermission = permission;
final isEdit = existingPermission != null;
final permissionId = existingPermission?.id;
if (isEdit && permissionId == null) {
_showSnack('ID 정보가 없어 수정할 수 없습니다.');
return;
}
final groupNotifier = ValueNotifier<int?>(permission?.group.id);
final menuNotifier = ValueNotifier<int?>(permission?.menu.id);
final createNotifier = ValueNotifier<bool>(permission?.canCreate ?? false);
final readNotifier = ValueNotifier<bool>(permission?.canRead ?? true);
final updateNotifier = ValueNotifier<bool>(permission?.canUpdate ?? false);
final deleteNotifier = ValueNotifier<bool>(permission?.canDelete ?? false);
final activeNotifier = ValueNotifier<bool>(permission?.isActive ?? true);
final noteController = TextEditingController(text: permission?.note ?? '');
final groupNotifier = ValueNotifier<int?>(existingPermission?.group.id);
final menuNotifier = ValueNotifier<int?>(existingPermission?.menu.id);
final createNotifier = ValueNotifier<bool>(
existingPermission?.canCreate ?? false,
);
final readNotifier = ValueNotifier<bool>(
existingPermission?.canRead ?? true,
);
final updateNotifier = ValueNotifier<bool>(
existingPermission?.canUpdate ?? false,
);
final deleteNotifier = ValueNotifier<bool>(
existingPermission?.canDelete ?? false,
);
final activeNotifier = ValueNotifier<bool>(
existingPermission?.isActive ?? true,
);
final noteController = TextEditingController(
text: existingPermission?.note ?? '',
);
final saving = ValueNotifier<bool>(false);
final groupError = ValueNotifier<String?>(null);
final menuError = ValueNotifier<String?>(null);
await showDialog<bool>(
await SuperportDialog.show<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: 600),
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 groupId = groupNotifier.value;
final menuId = menuNotifier.value;
groupError.value = groupId == null
? '그룹을 선택하세요.'
: null;
menuError.value = menuId == null
? '메뉴를 선택하세요.'
: null;
if (groupError.value != null ||
menuError.value != null) {
return;
}
dialog: SuperportDialog(
title: isEdit ? '권한 수정' : '권한 등록',
description: '그룹과 메뉴의 권한을 ${isEdit ? '수정' : '등록'}하세요.',
constraints: const BoxConstraints(maxWidth: 600),
secondaryAction: ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (dialogContext, isSaving, __) {
return ShadButton.ghost(
onPressed: isSaving
? null
: () => Navigator.of(dialogContext).pop(false),
child: const Text('취소'),
);
},
),
primaryAction: ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (dialogContext, isSaving, __) {
return ShadButton(
onPressed: isSaving
? null
: () async {
final groupId = groupNotifier.value;
final menuId = menuNotifier.value;
groupError.value = groupId == null ? '그룹을 선택하세요.' : null;
menuError.value = menuId == null ? '메뉴를 선택하세요.' : null;
if (groupError.value != null || menuError.value != null) {
return;
}
saving.value = true;
final input = GroupPermissionInput(
groupId: groupId!,
menuId: menuId!,
canCreate: createNotifier.value,
canRead: readNotifier.value,
canUpdate: updateNotifier.value,
canDelete: deleteNotifier.value,
isActive: activeNotifier.value,
note: noteController.text.trim().isEmpty
? null
: noteController.text.trim(),
);
final response = isEdit
? await _controller.update(
permissionId!,
input,
)
: await _controller.create(input);
saving.value = false;
if (response != null) {
if (!navigator.mounted) {
return;
}
if (mounted) {
_showSnack(
isEdit ? '권한을 수정했습니다.' : '권한을 등록했습니다.',
);
}
navigator.pop(true);
saving.value = true;
final trimmedNote = noteController.text.trim();
final input = GroupPermissionInput(
groupId: groupId!,
menuId: menuId!,
canCreate: createNotifier.value,
canRead: readNotifier.value,
canUpdate: updateNotifier.value,
canDelete: deleteNotifier.value,
isActive: activeNotifier.value,
note: trimmedNote.isEmpty ? null : trimmedNote,
);
final navigator = Navigator.of(dialogContext);
final response = isEdit
? await _controller.update(permissionId!, 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: ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (dialogContext, isSaving, __) {
final theme = ShadTheme.of(dialogContext);
final materialTheme = Theme.of(dialogContext);
return SingleChildScrollView(
padding: const EdgeInsets.only(right: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
ValueListenableBuilder<String?>(
valueListenable: groupError,
builder: (_, errorText, __) {
return _FormField(
label: '그룹',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ShadSelect<int?>(
initialValue: groupNotifier.value,
placeholder: const Text('그룹을 선택하세요'),
selectedOptionBuilder: (context, value) {
if (value == null) {
return const Text('그룹을 선택하세요');
}
final groupId = value;
final group = _controller.groups.firstWhere(
(g) => g.id == groupId,
orElse: () =>
Group(id: groupId, groupName: ''),
);
return Text(
group.groupName.isEmpty
? '그룹을 선택하세요'
: group.groupName,
);
},
child: Text(isEdit ? '저장' : '등록'),
),
],
);
},
),
child: SizedBox(
width: double.infinity,
child: SingleChildScrollView(
padding: const EdgeInsets.only(right: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
ValueListenableBuilder<String?>(
valueListenable: groupError,
builder: (_, errorText, __) {
return _FormField(
label: '그룹',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ShadSelect<int?>(
initialValue: groupNotifier.value,
placeholder: const Text('그룹을 선택하세요'),
selectedOptionBuilder: (context, value) {
if (value == null) {
return const Text('그룹을 선택하세요');
}
final groupId = value;
final group = _controller.groups.firstWhere(
(g) => g.id == groupId,
orElse: () =>
Group(id: groupId, groupName: ''),
);
return Text(
group.groupName.isEmpty
? '그룹을 선택하세요'
: group.groupName,
);
},
onChanged: saving.value || isEdit
? null
: (value) {
groupNotifier.value = value;
if (value != null) {
groupError.value = null;
}
},
options: [
..._controller.groups.map(
(group) => ShadOption<int?>(
value: group.id,
child: Text(group.groupName),
),
),
],
),
if (errorText != null)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
errorText,
style: theme.textTheme.small.copyWith(
color: materialTheme.colorScheme.error,
),
),
onChanged: isSaving || isEdit
? null
: (value) {
groupNotifier.value = value;
if (value != null) {
groupError.value = null;
}
},
options: [
..._controller.groups.map(
(group) => ShadOption<int?>(
value: group.id,
child: Text(group.groupName),
),
),
],
),
);
},
),
const SizedBox(height: 16),
ValueListenableBuilder<String?>(
valueListenable: menuError,
builder: (_, errorText, __) {
return _FormField(
label: '메뉴',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ShadSelect<int?>(
initialValue: menuNotifier.value,
placeholder: const Text('메뉴를 선택하세요'),
selectedOptionBuilder: (context, value) {
if (value == null) {
return const Text('메뉴를 선택하세요');
}
final menuId = value;
final menu = _controller.menus.firstWhere(
(m) => m.id == menuId,
orElse: () => MenuItem(
id: menuId,
menuCode: '',
menuName: '',
),
);
return Text(
menu.menuName.isEmpty
? '메뉴를 선택하세요'
: menu.menuName,
);
},
onChanged: saving.value || isEdit
? null
: (value) {
menuNotifier.value = value;
if (value != null) {
menuError.value = null;
}
},
options: [
..._controller.menus.map(
(menu) => ShadOption<int?>(
value: menu.id,
child: Text(menu.menuName),
),
),
],
),
if (errorText != null)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
errorText,
style: theme.textTheme.small.copyWith(
color: materialTheme.colorScheme.error,
),
),
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: 20),
_PermissionToggleRow(
label: '생성권한',
notifier: createNotifier,
enabled: !saving.value,
),
const SizedBox(height: 12),
_PermissionToggleRow(
label: '조회권한',
notifier: readNotifier,
enabled: !saving.value,
),
const SizedBox(height: 12),
_PermissionToggleRow(
label: '수정권한',
notifier: updateNotifier,
enabled: !saving.value,
),
const SizedBox(height: 12),
_PermissionToggleRow(
label: '삭제권한',
notifier: deleteNotifier,
enabled: !saving.value,
),
const SizedBox(height: 16),
ValueListenableBuilder<bool>(
valueListenable: activeNotifier,
builder: (_, value, __) {
return _FormField(
label: '사용여부',
child: Row(
children: [
ShadSwitch(
value: value,
onChanged: saving.value
? null
: (next) => activeNotifier.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(permission.createdAt)}',
style: theme.textTheme.small,
),
],
),
const SizedBox(height: 4),
Text(
'수정일시: ${_formatDateTime(permission.updatedAt)}',
style: theme.textTheme.small,
),
],
],
);
},
),
),
const SizedBox(height: 16),
ValueListenableBuilder<String?>(
valueListenable: menuError,
builder: (_, errorText, __) {
return _FormField(
label: '메뉴',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ShadSelect<int?>(
initialValue: menuNotifier.value,
placeholder: const Text('메뉴를 선택하세요'),
selectedOptionBuilder: (context, value) {
if (value == null) {
return const Text('메뉴를 선택하세요');
}
final menuId = value;
final menu = _controller.menus.firstWhere(
(m) => m.id == menuId,
orElse: () => MenuItem(
id: menuId,
menuCode: '',
menuName: '',
),
);
return Text(
menu.menuName.isEmpty
? '메뉴를 선택하세요'
: menu.menuName,
);
},
onChanged: isSaving || isEdit
? null
: (value) {
menuNotifier.value = value;
if (value != null) {
menuError.value = null;
}
},
options: [
..._controller.menus.map(
(menu) => ShadOption<int?>(
value: menu.id,
child: Text(menu.menuName),
),
),
],
),
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: 20),
_PermissionToggleRow(
label: '생성권한',
notifier: createNotifier,
enabled: !isSaving,
),
const SizedBox(height: 12),
_PermissionToggleRow(
label: '조회권한',
notifier: readNotifier,
enabled: !isSaving,
),
const SizedBox(height: 12),
_PermissionToggleRow(
label: '수정권한',
notifier: updateNotifier,
enabled: !isSaving,
),
const SizedBox(height: 12),
_PermissionToggleRow(
label: '삭제권한',
notifier: deleteNotifier,
enabled: !isSaving,
),
const SizedBox(height: 16),
ValueListenableBuilder<bool>(
valueListenable: activeNotifier,
builder: (_, value, __) {
return _FormField(
label: '사용여부',
child: Row(
children: [
ShadSwitch(
value: value,
onChanged: isSaving
? null
: (next) => activeNotifier.value = next,
),
const SizedBox(width: 8),
Text(value ? '사용' : '미사용'),
],
),
);
},
),
const SizedBox(height: 16),
_FormField(
label: '비고',
child: ShadTextarea(controller: noteController),
),
if (existingPermission != null) ...[
const SizedBox(height: 20),
Text(
'생성일시: ${_formatDateTime(existingPermission.createdAt)}',
style: theme.textTheme.small,
),
const SizedBox(height: 4),
Text(
'수정일시: ${_formatDateTime(existingPermission.updatedAt)}',
style: theme.textTheme.small,
),
],
],
),
),
),
);
},
);
},
),
),
);
groupNotifier.dispose();
@@ -751,26 +732,29 @@ class _GroupPermissionEnabledPageState
}
Future<void> _confirmDelete(GroupPermission permission) async {
final confirmed = await showDialog<bool>(
final confirmed = await SuperportDialog.show<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: const Text('권한 삭제'),
content: Text(
dialog: SuperportDialog(
title: '권한 삭제',
description:
'"${permission.group.groupName}" → "${permission.menu.menuName}" 권한을 삭제하시겠습니까?',
),
actions: [
TextButton(
secondaryAction: Builder(
builder: (dialogContext) {
return ShadButton.ghost(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('취소'),
),
TextButton(
);
},
),
primaryAction: Builder(
builder: (dialogContext) {
return ShadButton.destructive(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('삭제'),
),
],
);
},
);
},
),
),
);
if (confirmed == true && permission.id != null) {

View File

@@ -5,6 +5,7 @@ import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport_v2/core/constants/app_sections.dart';
import 'package:superport_v2/widgets/app_layout.dart';
import 'package:superport_v2/widgets/components/filter_bar.dart';
import 'package:superport_v2/widgets/components/superport_dialog.dart';
import '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
@@ -151,7 +152,8 @@ class _MenuEnabledPageState extends State<_MenuEnabledPage> {
? false
: (result.page * result.pageSize) < result.total;
final showReset = _searchController.text.isNotEmpty ||
final showReset =
_searchController.text.isNotEmpty ||
_controller.parentFilter != null ||
_controller.statusFilter != menu.MenuStatusFilter.all ||
_controller.includeDeleted;
@@ -167,12 +169,36 @@ class _MenuEnabledPageState extends State<_MenuEnabledPage> {
actions: [
ShadButton(
leading: const Icon(LucideIcons.plus, size: 16),
onPressed:
_controller.isSubmitting ? null : () => _openMenuForm(context),
onPressed: _controller.isSubmitting
? null
: () => _openMenuForm(context),
child: const Text('신규 등록'),
),
],
toolbar: FilterBar(
actions: [
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
if (showReset)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateParentFilter(null);
_controller.updateStatusFilter(
menu.MenuStatusFilter.all,
);
_controller.updateIncludeDeleted(false);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
children: [
SizedBox(
width: 260,
@@ -195,18 +221,13 @@ class _MenuEnabledPageState extends State<_MenuEnabledPage> {
selectedOptionBuilder: (context, value) {
if (value == null) {
return Text(
_controller.isLoadingParents
? '상위 로딩중...'
: '상위 전체',
_controller.isLoadingParents ? '상위 로딩중...' : '상위 전체',
);
}
final target = _controller.parents.firstWhere(
(menuItem) => menuItem.id == value,
orElse: () => MenuItem(
id: value,
menuCode: '',
menuName: '',
),
orElse: () =>
MenuItem(id: value, menuCode: '', menuName: ''),
);
final label = target.menuName.isEmpty
? '상위 전체'
@@ -220,10 +241,7 @@ class _MenuEnabledPageState extends State<_MenuEnabledPage> {
_controller.fetch(page: 1);
},
options: [
const ShadOption<int?>(
value: null,
child: Text('상위 전체'),
),
const ShadOption<int?>(value: null, child: Text('상위 전체')),
..._controller.parents.map(
(menuItem) => ShadOption<int?>(
value: menuItem.id,
@@ -269,27 +287,6 @@ class _MenuEnabledPageState extends State<_MenuEnabledPage> {
const Text('삭제 포함'),
],
),
ShadButton.outline(
onPressed: _controller.isLoading ? null : _applyFilters,
child: const Text('검색 적용'),
),
if (showReset)
ShadButton.ghost(
onPressed: _controller.isLoading
? null
: () {
_searchController.clear();
_searchFocus.requestFocus();
_controller.updateQuery('');
_controller.updateParentFilter(null);
_controller.updateStatusFilter(
menu.MenuStatusFilter.all,
);
_controller.updateIncludeDeleted(false);
_controller.fetch(page: 1);
},
child: const Text('초기화'),
),
],
),
child: ShadCard(
@@ -334,27 +331,22 @@ class _MenuEnabledPageState extends State<_MenuEnabledPage> {
child: Center(child: CircularProgressIndicator()),
)
: menus.isEmpty
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
'조건에 맞는 메뉴가 없습니다.',
style: theme.textTheme.muted,
),
)
: _MenuTable(
menus: menus,
dateFormat: _dateFormat,
onEdit: _controller.isSubmitting
? null
: (menuItem) =>
_openMenuForm(context, menu: menuItem),
onDelete: _controller.isSubmitting
? null
: _confirmDelete,
onRestore: _controller.isSubmitting
? null
: _restoreMenu,
),
? Padding(
padding: const EdgeInsets.all(32),
child: Text(
'조건에 맞는 메뉴가 없습니다.',
style: theme.textTheme.muted,
),
)
: _MenuTable(
menus: menus,
dateFormat: _dateFormat,
onEdit: _controller.isSubmitting
? null
: (menuItem) => _openMenuForm(context, menu: menuItem),
onDelete: _controller.isSubmitting ? null : _confirmDelete,
onRestore: _controller.isSubmitting ? null : _restoreMenu,
),
),
);
},
@@ -410,302 +402,283 @@ class _MenuEnabledPageState extends State<_MenuEnabledPage> {
final nameError = ValueNotifier<String?>(null);
final orderError = ValueNotifier<String?>(null);
await showDialog<bool>(
await SuperportDialog.show<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: 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 path = pathController.text.trim();
final orderText = orderController.text.trim();
final note = noteController.text.trim();
dialog: SuperportDialog(
title: isEdit ? '메뉴 수정' : '메뉴 등록',
description: '메뉴 정보를 ${isEdit ? '수정' : '입력'}하세요.',
constraints: const BoxConstraints(maxWidth: 560),
secondaryAction: ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (dialogContext, isSaving, __) {
return ShadButton.ghost(
onPressed: isSaving
? null
: () => Navigator.of(dialogContext).pop(false),
child: const Text('취소'),
);
},
),
primaryAction: ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (dialogContext, isSaving, __) {
return ShadButton(
onPressed: isSaving
? null
: () async {
final code = codeController.text.trim();
final name = nameController.text.trim();
final path = pathController.text.trim();
final orderText = orderController.text.trim();
final note = noteController.text.trim();
codeError.value = code.isEmpty
? '메뉴코드를 입력하세요.'
: null;
nameError.value = name.isEmpty
? '메뉴명을 입력하세요.'
: null;
codeError.value = code.isEmpty ? '메뉴코드를 입력하세요.' : null;
nameError.value = name.isEmpty ? '메뉴명을 입력하세요.' : null;
int? orderValue;
if (orderText.isNotEmpty) {
orderValue = int.tryParse(orderText);
if (orderValue == null) {
orderError.value = '표시순서는 숫자여야 합니다.';
} else {
orderError.value = null;
}
} else {
orderError.value = null;
}
int? orderValue;
if (orderText.isNotEmpty) {
orderValue = int.tryParse(orderText);
orderError.value = orderValue == null
? '표시순서는 숫자여야 합니다.'
: null;
} else {
orderError.value = null;
}
if (codeError.value != null ||
nameError.value != null ||
orderError.value != null) {
return;
}
if (codeError.value != null ||
nameError.value != null ||
orderError.value != null) {
return;
}
saving.value = true;
final input = MenuInput(
menuCode: code,
menuName: name,
parentMenuId: parentNotifier.value,
path: path.isEmpty ? null : path,
displayOrder: orderValue,
isActive: isActiveNotifier.value,
note: note.isEmpty ? null : note,
);
final response = isEdit
? await _controller.update(menuId!, input)
: await _controller.create(input);
saving.value = false;
if (response != null) {
if (!navigator.mounted) {
return;
}
if (mounted) {
_showSnack(
isEdit ? '메뉴를 수정했습니다.' : '메뉴를 등록했습니다.',
);
}
navigator.pop(true);
saving.value = true;
final input = MenuInput(
menuCode: code,
menuName: name,
parentMenuId: parentNotifier.value,
path: path.isEmpty ? null : path,
displayOrder: orderValue,
isActive: isActiveNotifier.value,
note: note.isEmpty ? null : note,
);
final navigator = Navigator.of(dialogContext);
final response = isEdit
? await _controller.update(menuId!, 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: ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (dialogContext, isSaving, __) {
final theme = ShadTheme.of(dialogContext);
final materialTheme = Theme.of(dialogContext);
return 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;
}
},
child: Text(isEdit ? '저장' : '등록'),
),
],
);
},
),
child: SizedBox(
width: double.infinity,
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,
),
),
),
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: parentNotifier,
builder: (_, value, __) {
return _FormField(
label: '상위메뉴',
child: ShadSelect<int?>(
initialValue: value,
placeholder: const Text('최상위'),
selectedOptionBuilder: (context, selected) {
if (selected == null) {
return const Text('최상위');
}
final target = _controller.parents.firstWhere(
(item) => item.id == selected,
orElse: () => MenuItem(
id: selected,
menuCode: '',
menuName: '',
),
);
final label = target.menuName.isEmpty
? '최상위'
: target.menuName;
return Text(label);
},
onChanged: saving.value
? null
: (next) => parentNotifier.value = next,
options: [
const ShadOption<int?>(
value: null,
child: Text('최상위'),
),
..._controller.parents
.where((item) => item.id != menuId)
.map(
(menuItem) => ShadOption<int?>(
value: menuItem.id,
child: Text(menuItem.menuName),
),
),
],
),
);
},
),
const SizedBox(height: 16),
_FormField(
label: '경로',
child: ShadInput(controller: pathController),
),
const SizedBox(height: 16),
ValueListenableBuilder<String?>(
valueListenable: orderError,
builder: (_, errorText, __) {
return _FormField(
label: '표시순서',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ShadInput(
controller: orderController,
keyboardType: TextInputType.number,
),
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(existingMenu.createdAt)}',
style: theme.textTheme.small,
),
],
),
const SizedBox(height: 4),
Text(
'수정일시: ${_formatDateTime(existingMenu.updatedAt)}',
style: theme.textTheme.small,
),
],
],
);
},
),
),
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: parentNotifier,
builder: (_, value, __) {
return _FormField(
label: '상위메뉴',
child: ShadSelect<int?>(
initialValue: value,
placeholder: const Text('최상위'),
selectedOptionBuilder: (context, selected) {
if (selected == null) {
return const Text('최상위');
}
final target = _controller.parents.firstWhere(
(item) => item.id == selected,
orElse: () => MenuItem(
id: selected,
menuCode: '',
menuName: '',
),
);
final label = target.menuName.isEmpty
? '최상위'
: target.menuName;
return Text(label);
},
onChanged: isSaving
? null
: (next) => parentNotifier.value = next,
options: [
const ShadOption<int?>(
value: null,
child: Text('최상위'),
),
..._controller.parents
.where((item) => item.id != menuId)
.map(
(menuItem) => ShadOption<int?>(
value: menuItem.id,
child: Text(menuItem.menuName),
),
),
],
),
);
},
),
const SizedBox(height: 16),
_FormField(
label: '경로',
child: ShadInput(controller: pathController),
),
const SizedBox(height: 16),
ValueListenableBuilder<String?>(
valueListenable: orderError,
builder: (_, errorText, __) {
return _FormField(
label: '표시순서',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ShadInput(
controller: orderController,
keyboardType: TextInputType.number,
),
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: isSaving
? null
: (next) => isActiveNotifier.value = next,
),
const SizedBox(width: 8),
Text(value ? '사용' : '미사용'),
],
),
);
},
),
const SizedBox(height: 16),
_FormField(
label: '비고',
child: ShadTextarea(controller: noteController),
),
if (existingMenu != null) ...[
const SizedBox(height: 20),
Text(
'생성일시: ${_formatDateTime(existingMenu.createdAt)}',
style: theme.textTheme.small,
),
const SizedBox(height: 4),
Text(
'수정일시: ${_formatDateTime(existingMenu.updatedAt)}',
style: theme.textTheme.small,
),
],
],
),
),
),
);
},
);
},
),
),
);
codeController.dispose();
@@ -722,24 +695,28 @@ class _MenuEnabledPageState extends State<_MenuEnabledPage> {
}
Future<void> _confirmDelete(MenuItem menu) async {
final confirmed = await showDialog<bool>(
final confirmed = await SuperportDialog.show<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: const Text('메뉴 삭제'),
content: Text('"${menu.menuName}" 메뉴를 삭제하시겠습니까?'),
actions: [
TextButton(
dialog: SuperportDialog(
title: '메뉴 삭제',
description: '"${menu.menuName}" 메뉴 삭제하시겠습니까?',
secondaryAction: Builder(
builder: (dialogContext) {
return ShadButton.ghost(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('취소'),
),
TextButton(
);
},
),
primaryAction: Builder(
builder: (dialogContext) {
return ShadButton.destructive(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: const Text('삭제'),
),
],
);
},
);
},
),
),
);
if (confirmed == true && menu.id != null) {

View File

@@ -11,6 +11,8 @@ import '../../domain/repositories/product_repository.dart';
enum ProductStatusFilter { all, activeOnly, inactiveOnly }
class ProductController extends ChangeNotifier {
static const int defaultPageSize = 20;
ProductController({
required ProductRepository productRepository,
required VendorRepository vendorRepository,
@@ -31,6 +33,7 @@ class ProductController extends ChangeNotifier {
int? _vendorFilter;
int? _uomFilter;
ProductStatusFilter _statusFilter = ProductStatusFilter.all;
int _pageSize = defaultPageSize;
String? _errorMessage;
List<Vendor> _vendorOptions = const [];
@@ -44,6 +47,7 @@ class ProductController extends ChangeNotifier {
int? get vendorFilter => _vendorFilter;
int? get uomFilter => _uomFilter;
ProductStatusFilter get statusFilter => _statusFilter;
int get pageSize => _pageSize;
String? get errorMessage => _errorMessage;
List<Vendor> get vendorOptions => _vendorOptions;
List<Uom> get uomOptions => _uomOptions;
@@ -60,13 +64,16 @@ class ProductController extends ChangeNotifier {
};
final response = await _productRepository.list(
page: page,
pageSize: _result?.pageSize ?? 20,
pageSize: _pageSize,
query: _query.isEmpty ? null : _query,
vendorId: _vendorFilter,
uomId: _uomFilter,
isActive: isActive,
);
_result = response;
if (response.pageSize > 0 && response.pageSize != _pageSize) {
_pageSize = response.pageSize;
}
} catch (e) {
_errorMessage = e.toString();
} finally {
@@ -92,25 +99,45 @@ class ProductController extends ChangeNotifier {
}
void updateQuery(String value) {
if (_query == value) {
return;
}
_query = value;
notifyListeners();
}
void updateVendorFilter(int? vendorId) {
if (_vendorFilter == vendorId) {
return;
}
_vendorFilter = vendorId;
notifyListeners();
}
void updateUomFilter(int? uomId) {
if (_uomFilter == uomId) {
return;
}
_uomFilter = uomId;
notifyListeners();
}
void updateStatusFilter(ProductStatusFilter filter) {
if (_statusFilter == filter) {
return;
}
_statusFilter = filter;
notifyListeners();
}
void updatePageSize(int size) {
if (size <= 0 || _pageSize == size) {
return;
}
_pageSize = size;
notifyListeners();
}
Future<Product?> create(ProductInput input) async {
_setSubmitting(true);
try {

View File

@@ -11,6 +11,8 @@ enum VendorStatusFilter { all, activeOnly, inactiveOnly }
/// - 목록/검색/필터/페이지 상태를 관리한다.
/// - 생성/수정/삭제/복구 요청을 래핑하여 UI에 알린다.
class VendorController extends ChangeNotifier {
static const int defaultPageSize = 20;
VendorController({required VendorRepository repository})
: _repository = repository;
@@ -21,6 +23,7 @@ class VendorController extends ChangeNotifier {
bool _isSubmitting = false;
String _query = '';
VendorStatusFilter _statusFilter = VendorStatusFilter.all;
int _pageSize = defaultPageSize;
String? _errorMessage;
PaginatedResult<Vendor>? get result => _result;
@@ -28,6 +31,7 @@ class VendorController extends ChangeNotifier {
bool get isSubmitting => _isSubmitting;
String get query => _query;
VendorStatusFilter get statusFilter => _statusFilter;
int get pageSize => _pageSize;
String? get errorMessage => _errorMessage;
/// 목록 갱신
@@ -43,11 +47,14 @@ class VendorController extends ChangeNotifier {
};
final response = await _repository.list(
page: page,
pageSize: _result?.pageSize ?? 20,
pageSize: _pageSize,
query: _query.isEmpty ? null : _query,
isActive: isActive,
);
_result = response;
if (response.pageSize > 0 && response.pageSize != _pageSize) {
_pageSize = response.pageSize;
}
} catch (e) {
_errorMessage = e.toString();
} finally {
@@ -57,15 +64,29 @@ class VendorController extends ChangeNotifier {
}
void updateQuery(String value) {
if (_query == value) {
return;
}
_query = value;
notifyListeners();
}
void updateStatusFilter(VendorStatusFilter filter) {
if (_statusFilter == filter) {
return;
}
_statusFilter = filter;
notifyListeners();
}
void updatePageSize(int size) {
if (size <= 0 || _pageSize == size) {
return;
}
_pageSize = size;
notifyListeners();
}
/// 신규 등록
Future<Vendor?> create(VendorInput input) async {
_setSubmitting(true);

View File

@@ -1,10 +1,13 @@
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:go_router/go_router.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport_v2/core/constants/app_sections.dart';
import 'package:superport_v2/widgets/app_layout.dart';
import 'package:superport_v2/widgets/components/filter_bar.dart';
import 'package:superport_v2/widgets/components/superport_dialog.dart';
import 'package:superport_v2/widgets/components/superport_table.dart';
import '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
@@ -13,7 +16,9 @@ import '../../../vendor/domain/repositories/vendor_repository.dart';
import '../controllers/vendor_controller.dart';
class VendorPage extends StatelessWidget {
const VendorPage({super.key});
const VendorPage({super.key, required this.routeUri});
final Uri routeUri;
@override
Widget build(BuildContext context) {
@@ -58,12 +63,14 @@ class VendorPage extends StatelessWidget {
);
}
return const _VendorEnabledPage();
return _VendorEnabledPage(routeUri: routeUri);
}
}
class _VendorEnabledPage extends StatefulWidget {
const _VendorEnabledPage();
const _VendorEnabledPage({required this.routeUri});
final Uri routeUri;
@override
State<_VendorEnabledPage> createState() => _VendorEnabledPageState();
@@ -75,13 +82,22 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
final FocusNode _searchFocusNode = FocusNode();
final DateFormat _dateFormat = DateFormat('yyyy-MM-dd HH:mm');
String? _lastError;
bool _routeApplied = false;
@override
void initState() {
super.initState();
_controller = VendorController(repository: GetIt.I<VendorRepository>());
_controller.addListener(_onControllerChanged);
WidgetsBinding.instance.addPostFrameCallback((_) => _controller.fetch());
_controller = VendorController(repository: GetIt.I<VendorRepository>())
..addListener(_onControllerChanged);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (!_routeApplied) {
_routeApplied = true;
_applyRouteParameters();
}
}
@override
@@ -140,6 +156,32 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
),
],
toolbar: FilterBar(
actions: [
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,
);
_updateRoute(
page: 1,
queryOverride: '',
statusOverride: VendorStatusFilter.all,
);
},
child: const Text('초기화'),
),
],
children: [
SizedBox(
width: 280,
@@ -159,10 +201,9 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
selectedOptionBuilder: (context, value) =>
Text(_statusLabel(value)),
onChanged: (value) {
if (value != null) {
_controller.updateStatusFilter(value);
_controller.fetch(page: 1);
}
if (value == null) return;
_controller.updateStatusFilter(value);
_updateRoute(page: 1, statusOverride: value);
},
options: VendorStatusFilter.values
.map(
@@ -174,26 +215,6 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
.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('초기화'),
),
],
),
child: ShadCard(
@@ -217,7 +238,7 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || currentPage <= 1
? null
: () => _controller.fetch(page: currentPage - 1),
: () => _goToPage(currentPage - 1),
child: const Text('이전'),
),
const SizedBox(width: 8),
@@ -225,7 +246,7 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
size: ShadButtonSize.sm,
onPressed: _controller.isLoading || !hasNext
? null
: () => _controller.fetch(page: currentPage + 1),
: () => _goToPage(currentPage + 1),
child: const Text('다음'),
),
],
@@ -238,27 +259,22 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
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,
),
? 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,
),
),
);
},
@@ -266,8 +282,9 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
}
void _applyFilters() {
_controller.updateQuery(_searchController.text.trim());
_controller.fetch(page: 1);
final keyword = _searchController.text.trim();
_controller.updateQuery(keyword);
_updateRoute(page: 1, queryOverride: keyword);
}
String _statusLabel(VendorStatusFilter filter) {
@@ -281,6 +298,90 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
}
}
void _applyRouteParameters() {
final params = widget.routeUri.queryParameters;
final query = params['q'] ?? '';
final status = _statusFromParam(params['status']);
final pageSizeParam = int.tryParse(params['page_size'] ?? '');
final pageParam = int.tryParse(params['page'] ?? '');
_searchController.text = query;
_controller.updateQuery(query);
_controller.updateStatusFilter(status);
if (pageSizeParam != null && pageSizeParam > 0) {
_controller.updatePageSize(pageSizeParam);
}
final page = pageParam != null && pageParam > 0 ? pageParam : 1;
_controller.fetch(page: page);
}
void _goToPage(int page) {
if (page < 1) {
page = 1;
}
_updateRoute(page: page);
}
void _updateRoute({
required int page,
String? queryOverride,
VendorStatusFilter? statusOverride,
int? pageSizeOverride,
}) {
final query = queryOverride ?? _controller.query;
final status = statusOverride ?? _controller.statusFilter;
final pageSize = pageSizeOverride ?? _controller.pageSize;
final params = <String, String>{};
if (query.isNotEmpty) {
params['q'] = query;
}
final statusParam = _encodeStatus(status);
if (statusParam != null) {
params['status'] = statusParam;
}
if (page > 1) {
params['page'] = page.toString();
}
if (pageSize > 0 && pageSize != VendorController.defaultPageSize) {
params['page_size'] = pageSize.toString();
}
final uri = Uri(
path: widget.routeUri.path,
queryParameters: params.isEmpty ? null : params,
);
final newLocation = uri.toString();
if (widget.routeUri.toString() == newLocation) {
_controller.fetch(page: page);
return;
}
GoRouter.of(context).go(newLocation);
}
VendorStatusFilter _statusFromParam(String? value) {
switch (value) {
case 'active':
return VendorStatusFilter.activeOnly;
case 'inactive':
return VendorStatusFilter.inactiveOnly;
default:
return VendorStatusFilter.all;
}
}
String? _encodeStatus(VendorStatusFilter filter) {
switch (filter) {
case VendorStatusFilter.all:
return null;
case VendorStatusFilter.activeOnly:
return 'active';
case VendorStatusFilter.inactiveOnly:
return 'inactive';
}
}
Future<void> _openVendorForm(BuildContext context, {Vendor? vendor}) async {
final existingVendor = vendor;
final isEdit = existingVendor != null;
@@ -306,201 +407,183 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
final codeError = ValueNotifier<String?>(null);
final nameError = ValueNotifier<String?>(null);
await showDialog<bool>(
await SuperportDialog.show<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();
dialog: SuperportDialog(
title: isEdit ? '벤더 수정' : '벤더 등록',
description: '벤더 기본 정보를 ${isEdit ? '수정' : '입력'}하세요.',
constraints: const BoxConstraints(maxWidth: 520),
primaryAction: ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (context, isSaving, _) {
return 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;
codeError.value = code.isEmpty ? '벤더코드를 입력하세요.' : null;
nameError.value = name.isEmpty ? '벤더명을 입력하세요.' : null;
if (codeError.value != null ||
nameError.value != null) {
return;
}
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);
saving.value = true;
final input = VendorInput(
vendorCode: code,
vendorName: name,
isActive: isActiveNotifier.value,
note: note.isEmpty ? null : note,
);
final navigator = Navigator.of(context);
final response = isEdit
? await _controller.update(vendorId!, input)
: await _controller.create(input);
saving.value = false;
if (response != null && mounted) {
if (!navigator.mounted) {
return;
}
_showSnack(isEdit ? '벤더를 수정했습니다.' : '벤더를 등록했습니다.');
navigator.pop(true);
}
},
child: Text(isEdit ? '저장' : '등록'),
);
},
),
secondaryAction: ValueListenableBuilder<bool>(
valueListenable: saving,
builder: (context, isSaving, _) {
return ShadButton.ghost(
onPressed: isSaving
? null
: () => Navigator.of(context).pop(false),
child: const Text('취소'),
);
},
),
child: Builder(
builder: (dialogContext) {
final theme = ShadTheme.of(dialogContext);
final materialTheme = Theme.of(dialogContext);
return 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;
}
},
child: Text(isEdit ? '저장' : '등록'),
),
],
);
},
),
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,
),
),
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<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),
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: 16),
_FormField(
label: '비고',
child: ShadTextarea(controller: noteController),
const SizedBox(height: 4),
Text(
'수정일시: ${_formatDateTime(existingVendor.updatedAt)}',
style: theme.textTheme.small,
),
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();
@@ -513,24 +596,22 @@ class _VendorEnabledPageState extends State<_VendorEnabledPage> {
}
Future<void> _confirmDelete(Vendor vendor) async {
final confirmed = await showDialog<bool>(
final confirmed = await SuperportDialog.show<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('삭제'),
),
],
);
},
dialog: SuperportDialog(
title: '벤더 삭제',
description: '"${vendor.vendorName}" 벤더 삭제하시겠습니까?',
actions: [
ShadButton.ghost(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('취소'),
),
ShadButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('삭제'),
),
],
),
);
if (confirmed == true && vendor.id != null) {
@@ -581,39 +662,43 @@ class _VendorTable extends StatelessWidget {
@override
Widget build(BuildContext context) {
final header = [
'ID',
'벤더코드',
'벤더명',
'사용',
'삭제',
'비고',
'변경일시',
'동작',
].map((text) => ShadTableCell.header(child: Text(text))).toList();
final columns = const [
Text('ID'),
Text('벤더코드'),
Text('벤더명'),
Text('사용'),
Text('삭제'),
Text('비고'),
Text('변경일시'),
Text('동작'),
];
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(
final cells = <Widget>[
Text(vendor.id?.toString() ?? '-'),
Text(vendor.vendorCode),
Text(vendor.vendorName),
Text(vendor.isActive ? 'Y' : 'N'),
Text(vendor.isDeleted ? 'Y' : '-'),
Text(vendor.note?.isEmpty ?? true ? '-' : vendor.note!),
Text(
vendor.updatedAt == null
? '-'
: dateFormat.format(vendor.updatedAt!.toLocal()),
),
];
cells.add(
ShadTableCell(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
alignment: Alignment.centerRight,
child: Wrap(
spacing: 8,
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,
@@ -633,17 +718,18 @@ class _VendorTable extends StatelessWidget {
),
),
);
return cells;
}).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),
),
return SuperportTable(
columns: columns,
rows: rows,
rowHeight: 56,
maxHeight: 520,
columnSpanExtent: (index) => index == 7
? const FixedTableSpanExtent(160)
: const FixedTableSpanExtent(140),
);
}
}

View File

@@ -7,6 +7,8 @@ import '../../domain/repositories/warehouse_repository.dart';
enum WarehouseStatusFilter { all, activeOnly, inactiveOnly }
class WarehouseController extends ChangeNotifier {
static const int defaultPageSize = 20;
WarehouseController({required WarehouseRepository repository})
: _repository = repository;
@@ -17,6 +19,7 @@ class WarehouseController extends ChangeNotifier {
bool _isSubmitting = false;
String _query = '';
WarehouseStatusFilter _statusFilter = WarehouseStatusFilter.all;
int _pageSize = defaultPageSize;
String? _errorMessage;
PaginatedResult<Warehouse>? get result => _result;
@@ -24,6 +27,7 @@ class WarehouseController extends ChangeNotifier {
bool get isSubmitting => _isSubmitting;
String get query => _query;
WarehouseStatusFilter get statusFilter => _statusFilter;
int get pageSize => _pageSize;
String? get errorMessage => _errorMessage;
Future<void> fetch({int page = 1}) async {
@@ -38,11 +42,14 @@ class WarehouseController extends ChangeNotifier {
};
final response = await _repository.list(
page: page,
pageSize: _result?.pageSize ?? 20,
pageSize: _pageSize,
query: _query.isEmpty ? null : _query,
isActive: isActive,
);
_result = response;
if (response.pageSize > 0 && response.pageSize != _pageSize) {
_pageSize = response.pageSize;
}
} catch (e) {
_errorMessage = e.toString();
} finally {
@@ -52,15 +59,29 @@ class WarehouseController extends ChangeNotifier {
}
void updateQuery(String value) {
if (_query == value) {
return;
}
_query = value;
notifyListeners();
}
void updateStatusFilter(WarehouseStatusFilter filter) {
if (_statusFilter == filter) {
return;
}
_statusFilter = filter;
notifyListeners();
}
void updatePageSize(int size) {
if (size <= 0 || _pageSize == size) {
return;
}
_pageSize = size;
notifyListeners();
}
Future<Warehouse?> create(WarehouseInput input) async {
_setSubmitting(true);
try {

View File

@@ -1,5 +1,7 @@
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:intl/intl.dart' as intl;
import 'package:lucide_icons_flutter/lucide_icons.dart' as lucide;
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport_v2/core/constants/app_sections.dart';
@@ -7,7 +9,9 @@ import 'package:superport_v2/features/masters/warehouse/domain/entities/warehous
import 'package:superport_v2/features/masters/warehouse/domain/repositories/warehouse_repository.dart';
import 'package:superport_v2/widgets/app_layout.dart';
import 'package:superport_v2/widgets/components/empty_state.dart';
import 'package:superport_v2/widgets/components/feedback.dart';
import 'package:superport_v2/widgets/components/filter_bar.dart';
import 'package:superport_v2/widgets/components/superport_date_picker.dart';
class ReportingPage extends StatefulWidget {
const ReportingPage({super.key});
@@ -18,12 +22,16 @@ class ReportingPage extends StatefulWidget {
class _ReportingPageState extends State<ReportingPage> {
late final WarehouseRepository _warehouseRepository;
final DateFormat _dateFormat = DateFormat('yyyy.MM.dd');
final intl.DateFormat _dateFormat = intl.DateFormat('yyyy.MM.dd');
DateTimeRange? _dateRange;
ReportTypeFilter _selectedType = ReportTypeFilter.all;
ReportStatusFilter _selectedStatus = ReportStatusFilter.all;
WarehouseFilterOption _selectedWarehouse = WarehouseFilterOption.all;
DateTimeRange? _appliedDateRange;
DateTimeRange? _pendingDateRange;
ReportTypeFilter _appliedType = ReportTypeFilter.all;
ReportTypeFilter _pendingType = ReportTypeFilter.all;
ReportStatusFilter _appliedStatus = ReportStatusFilter.all;
ReportStatusFilter _pendingStatus = ReportStatusFilter.all;
WarehouseFilterOption _appliedWarehouse = WarehouseFilterOption.all;
WarehouseFilterOption _pendingWarehouse = WarehouseFilterOption.all;
List<WarehouseFilterOption> _warehouseOptions = const [
WarehouseFilterOption.all,
@@ -63,14 +71,14 @@ class _ReportingPageState extends State<ReportingPage> {
if (mounted) {
setState(() {
_warehouseOptions = options;
WarehouseFilterOption nextSelected = WarehouseFilterOption.all;
for (final option in options) {
if (option == _selectedWarehouse) {
nextSelected = option;
break;
}
}
_selectedWarehouse = nextSelected;
_appliedWarehouse = _resolveWarehouseOption(
_appliedWarehouse,
options,
);
_pendingWarehouse = _resolveWarehouseOption(
_pendingWarehouse,
options,
);
});
}
} catch (error) {
@@ -78,7 +86,8 @@ class _ReportingPageState extends State<ReportingPage> {
setState(() {
_warehouseError = '창고 목록을 불러오지 못했습니다. 잠시 후 다시 시도하세요.';
_warehouseOptions = const [WarehouseFilterOption.all];
_selectedWarehouse = WarehouseFilterOption.all;
_appliedWarehouse = WarehouseFilterOption.all;
_pendingWarehouse = WarehouseFilterOption.all;
});
}
} finally {
@@ -90,57 +99,70 @@ class _ReportingPageState extends State<ReportingPage> {
}
}
Future<void> _pickDateRange() async {
final now = DateTime.now();
final initialRange =
_dateRange ??
DateTimeRange(
start: DateTime(
now.year,
now.month,
now.day,
).subtract(const Duration(days: 6)),
end: DateTime(now.year, now.month, now.day),
);
final picked = await showDateRangePicker(
context: context,
initialDateRange: initialRange,
firstDate: DateTime(now.year - 5),
lastDate: DateTime(now.year + 2),
helpText: '기간 선택',
saveText: '적용',
currentDate: now,
locale: Localizations.localeOf(context),
);
if (picked != null && mounted) {
setState(() {
_dateRange = picked;
});
}
}
void _resetFilters() {
setState(() {
_dateRange = null;
_selectedType = ReportTypeFilter.all;
_selectedStatus = ReportStatusFilter.all;
_selectedWarehouse = WarehouseFilterOption.all;
_appliedDateRange = null;
_pendingDateRange = null;
_appliedType = ReportTypeFilter.all;
_pendingType = ReportTypeFilter.all;
_appliedStatus = ReportStatusFilter.all;
_pendingStatus = ReportStatusFilter.all;
_appliedWarehouse = WarehouseFilterOption.all;
_pendingWarehouse = WarehouseFilterOption.all;
});
}
void _applyFilters() {
setState(() {
_appliedDateRange = _pendingDateRange;
_appliedType = _pendingType;
_appliedStatus = _pendingStatus;
_appliedWarehouse = _pendingWarehouse;
});
}
bool get _canExport {
return _dateRange != null && _selectedType != ReportTypeFilter.all;
return _appliedDateRange != null && _appliedType != ReportTypeFilter.all;
}
bool get _hasCustomFilters {
return _dateRange != null ||
_selectedType != ReportTypeFilter.all ||
_selectedStatus != ReportStatusFilter.all ||
_selectedWarehouse != WarehouseFilterOption.all;
return _appliedDateRange != null ||
_appliedType != ReportTypeFilter.all ||
_appliedStatus != ReportStatusFilter.all ||
_appliedWarehouse != WarehouseFilterOption.all;
}
String get _dateRangeLabel {
final range = _dateRange;
bool get _hasAppliedFilters => _hasCustomFilters;
bool get _hasDirtyFilters =>
!_isSameRange(_pendingDateRange, _appliedDateRange) ||
_pendingType != _appliedType ||
_pendingStatus != _appliedStatus ||
_pendingWarehouse != _appliedWarehouse;
bool _isSameRange(DateTimeRange? a, DateTimeRange? b) {
if (identical(a, b)) {
return true;
}
if (a == null || b == null) {
return a == b;
}
return a.start == b.start && a.end == b.end;
}
WarehouseFilterOption _resolveWarehouseOption(
WarehouseFilterOption target,
List<WarehouseFilterOption> options,
) {
for (final option in options) {
if (option == target) {
return option;
}
}
return options.first;
}
String _dateRangeLabel(DateTimeRange? range) {
if (range == null) {
return '기간 선택';
}
@@ -150,11 +172,7 @@ class _ReportingPageState extends State<ReportingPage> {
String _formatDate(DateTime value) => _dateFormat.format(value);
void _handleExport(ReportExportFormat format) {
final messenger = ScaffoldMessenger.of(context);
messenger.clearSnackBars();
messenger.showSnackBar(
SnackBar(content: Text('${format.label} 다운로드 연동은 준비 중입니다.')),
);
SuperportToast.info(context, '${format.label} 다운로드 연동은 준비 중입니다.');
}
@override
@@ -174,34 +192,56 @@ class _ReportingPageState extends State<ReportingPage> {
onPressed: _canExport
? () => _handleExport(ReportExportFormat.xlsx)
: null,
leading: const Icon(LucideIcons.fileDown, size: 16),
leading: const Icon(lucide.LucideIcons.fileDown, size: 16),
child: const Text('XLSX 다운로드'),
),
ShadButton.outline(
onPressed: _canExport
? () => _handleExport(ReportExportFormat.pdf)
: null,
leading: const Icon(LucideIcons.fileText, size: 16),
leading: const Icon(lucide.LucideIcons.fileText, size: 16),
child: const Text('PDF 다운로드'),
),
],
toolbar: FilterBar(
actionConfig: FilterBarActionConfig(
onApply: _applyFilters,
onReset: _resetFilters,
hasPendingChanges: _hasDirtyFilters,
hasActiveFilters: _hasAppliedFilters,
),
children: [
ShadButton.outline(
onPressed: _pickDateRange,
leading: const Icon(LucideIcons.calendar, size: 16),
child: Text(_dateRangeLabel),
SizedBox(
width: 220,
child: SuperportDateRangePickerButton(
value: _pendingDateRange ?? _appliedDateRange,
dateFormat: _dateFormat,
firstDate: DateTime(DateTime.now().year - 5),
lastDate: DateTime(DateTime.now().year + 2),
initialDateRange:
_pendingDateRange ??
_appliedDateRange ??
DateTimeRange(
start: DateTime.now().subtract(const Duration(days: 6)),
end: DateTime.now(),
),
onChanged: (range) {
setState(() {
_pendingDateRange = range;
});
},
),
),
SizedBox(
width: 200,
child: ShadSelect<ReportTypeFilter>(
key: ValueKey(_selectedType),
initialValue: _selectedType,
key: ValueKey(_pendingType),
initialValue: _pendingType,
selectedOptionBuilder: (_, value) => Text(value.label),
onChanged: (value) {
if (value == null) return;
setState(() {
_selectedType = value;
_pendingType = value;
});
},
options: [
@@ -214,14 +254,14 @@ class _ReportingPageState extends State<ReportingPage> {
width: 220,
child: ShadSelect<WarehouseFilterOption>(
key: ValueKey(
'${_selectedWarehouse.cacheKey}-${_warehouseOptions.length}',
'${_pendingWarehouse.cacheKey}-${_warehouseOptions.length}',
),
initialValue: _selectedWarehouse,
initialValue: _pendingWarehouse,
selectedOptionBuilder: (_, value) => Text(value.label),
onChanged: (value) {
if (value == null) return;
setState(() {
_selectedWarehouse = value;
_pendingWarehouse = value;
});
},
options: [
@@ -233,13 +273,13 @@ class _ReportingPageState extends State<ReportingPage> {
SizedBox(
width: 200,
child: ShadSelect<ReportStatusFilter>(
key: ValueKey(_selectedStatus),
initialValue: _selectedStatus,
key: ValueKey(_pendingStatus),
initialValue: _pendingStatus,
selectedOptionBuilder: (_, value) => Text(value.label),
onChanged: (value) {
if (value == null) return;
setState(() {
_selectedStatus = value;
_pendingStatus = value;
});
},
options: [
@@ -248,11 +288,6 @@ class _ReportingPageState extends State<ReportingPage> {
],
),
),
ShadButton.ghost(
onPressed: _hasCustomFilters ? _resetFilters : null,
leading: const Icon(LucideIcons.rotateCcw, size: 16),
child: const Text('초기화'),
),
],
),
child: Column(
@@ -264,7 +299,7 @@ class _ReportingPageState extends State<ReportingPage> {
child: Row(
children: [
Icon(
LucideIcons.circleAlert,
lucide.LucideIcons.circleAlert,
size: 16,
color: theme.colorScheme.destructive,
),
@@ -280,7 +315,7 @@ class _ReportingPageState extends State<ReportingPage> {
const SizedBox(width: 8),
ShadButton.ghost(
onPressed: _isLoadingWarehouses ? null : _loadWarehouses,
leading: const Icon(LucideIcons.refreshCw, size: 16),
leading: const Icon(lucide.LucideIcons.refreshCw, size: 16),
child: const Text('재시도'),
),
],
@@ -290,14 +325,12 @@ class _ReportingPageState extends State<ReportingPage> {
Padding(
padding: const EdgeInsets.only(bottom: 16),
child: Row(
children: [
const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
),
const SizedBox(width: 8),
Text('창고 목록을 불러오는 중입니다...', style: theme.textTheme.small),
children: const [
SuperportSkeleton(width: 180, height: 20),
SizedBox(width: 12),
SuperportSkeleton(width: 140, height: 20),
SizedBox(width: 12),
SuperportSkeleton(width: 120, height: 20),
],
),
),
@@ -312,11 +345,13 @@ class _ReportingPageState extends State<ReportingPage> {
children: [
_SummaryRow(
label: '기간',
value: _dateRange == null ? '기간을 선택하세요.' : _dateRangeLabel,
value: _appliedDateRange == null
? '기간을 선택하세요.'
: _dateRangeLabel(_appliedDateRange),
),
_SummaryRow(label: '유형', value: _selectedType.label),
_SummaryRow(label: '창고', value: _selectedWarehouse.label),
_SummaryRow(label: '상태', value: _selectedStatus.label),
_SummaryRow(label: '유형', value: _appliedType.label),
_SummaryRow(label: '창고', value: _appliedWarehouse.label),
_SummaryRow(label: '상태', value: _appliedStatus.label),
if (!_canExport)
Padding(
padding: const EdgeInsets.only(top: 12),
@@ -339,9 +374,10 @@ class _ReportingPageState extends State<ReportingPage> {
),
child: SizedBox(
height: 240,
child: EmptyState(
icon: LucideIcons.chartBar,
message: '필터를 선택하고 다운로드하면 결과 미리보기가 제공됩니다.',
child: SuperportEmptyState(
icon: lucide.LucideIcons.chartBar,
title: '미리보기 데이터가 없습니다.',
description: '필터를 적용하거나 보고서를 다운로드하면 이 영역에 요약이 표시됩니다.',
),
),
),

View File

@@ -1,25 +1,113 @@
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import '../../../../../widgets/spec_page.dart';
import '../../../../../core/constants/app_sections.dart';
import '../../../../../widgets/app_layout.dart';
import '../models/postal_search_result.dart';
import '../widgets/postal_search_dialog.dart';
class PostalSearchPage extends StatelessWidget {
class PostalSearchPage extends StatefulWidget {
const PostalSearchPage({super.key});
@override
State<PostalSearchPage> createState() => _PostalSearchPageState();
}
class _PostalSearchPageState extends State<PostalSearchPage> {
PostalSearchResult? _lastSelection;
@override
Widget build(BuildContext context) {
return const SpecPage(
final theme = ShadTheme.of(context);
return AppLayout(
title: '우편번호 검색',
summary: '모달 기반 우편번호 검색 UI 구성을 정의합니다.',
sections: [
SpecSection(
title: '모달 구성',
items: [
'검색어 [Text] 입력 필드',
'결과 리스트: 우편번호 | 시도 | 시군구 | 도로명 | 건물번호',
'선택 시 호출 화면에 우편번호/주소 전달',
],
),
subtitle: '창고/고객사 등 주소 입력 폼에서 재사용되는 검색 모달입니다.',
breadcrumbs: const [
AppBreadcrumbItem(label: '대시보드', path: dashboardRoutePath),
AppBreadcrumbItem(label: '유틸리티', path: '/utilities/postal-search'),
AppBreadcrumbItem(label: '우편번호 검색'),
],
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 520),
child: ShadCard(
title: Text('우편번호 검색 모달 미리보기', style: theme.textTheme.h3),
description: Text(
'검색 버튼을 눌러 모달 UI를 확인하세요. 검색 API 연동은 이후 단계에서 진행됩니다.',
style: theme.textTheme.muted,
),
footer: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ShadButton(
leading: const Icon(LucideIcons.search, size: 16),
onPressed: () async {
final result = await showPostalSearchDialog(context);
if (result != null && mounted) {
setState(() {
_lastSelection = result;
});
}
},
child: const Text('모달 열기'),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'우편번호를 검색한 뒤 결과 행을 클릭하면 선택한 주소가 폼에 채워집니다.',
style: theme.textTheme.p,
),
const SizedBox(height: 16),
if (_lastSelection == null)
Text('선택한 주소가 없습니다.', style: theme.textTheme.muted)
else
Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
border: Border.all(color: theme.colorScheme.border),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'선택된 우편번호',
style: theme.textTheme.small.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 4),
Text(
_lastSelection!.zipcode,
style: theme.textTheme.h4,
),
const SizedBox(height: 12),
Text(
'주소 구성요소',
style: theme.textTheme.small.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 4),
Text(
_lastSelection!.fullAddress.isEmpty
? '주소 정보가 제공되지 않았습니다.'
: _lastSelection!.fullAddress,
style: theme.textTheme.p,
),
],
),
),
],
),
),
),
),
);
}
}

View File

@@ -255,7 +255,14 @@ class _PostalSearchDialogState extends State<_PostalSearchDialog> {
],
],
onRowTap: (index) {
navigator.pop(_results[index]);
if (_results.isEmpty) {
return;
}
final adjustedIndex = (index - 1).clamp(
0,
_results.length - 1,
);
navigator.pop(_results[adjustedIndex]);
},
emptyLabel: '검색 결과가 없습니다.',
),