first commit

This commit is contained in:
2026-09-21 17:37:53 +08:00
commit 67d4dd5b7c
141 changed files with 8558 additions and 0 deletions
+247
View File
@@ -0,0 +1,247 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/network/api_exception.dart';
import '../../../providers/add_bill_provider.dart';
import '../../../providers/category_provider.dart';
import '../../../utils/amount_input_formatter.dart';
import '../../../utils/date_util.dart';
import '../../../utils/toast.dart';
import '../../../widgets/category_picker_grid.dart';
import '../../../widgets/state_views.dart';
/// 手动记账表单(复刻 uniApp add.vue 手动 Tab)
class ManualEntryTab extends ConsumerStatefulWidget {
const ManualEntryTab({super.key});
@override
ConsumerState<ManualEntryTab> createState() => _ManualEntryTabState();
}
class _ManualEntryTabState extends ConsumerState<ManualEntryTab> {
late final TextEditingController _descriptionController = TextEditingController();
late final TextEditingController _amountController = TextEditingController();
@override
void dispose() {
_descriptionController.dispose();
_amountController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final form = ref.watch(addBillFormProvider);
final notifier = ref.read(addBillFormProvider.notifier);
// OCR「选择此条」外部填充时,同步非受控输入框
ref.listen<int>(addBillFormProvider.select((s) => s.revision), (prev, next) {
if (prev == next) return;
final s = ref.read(addBillFormProvider);
_amountController.text = s.amount?.toStringAsFixed(2) ?? '';
_descriptionController.text = s.description;
});
return ListView(
padding: const EdgeInsets.all(16),
children: [
_sectionLabel('账单类型'),
_typeSelector(form, notifier),
const SizedBox(height: 16),
_sectionLabel('分类'),
_categoryGrid(form, notifier),
const SizedBox(height: 16),
_sectionLabel('金额'),
_amountField(form, notifier),
const SizedBox(height: 16),
_sectionLabel('日期'),
_dateField(context, form, notifier),
const SizedBox(height: 16),
_sectionLabel('备注'),
_descriptionField(form, notifier),
const SizedBox(height: 24),
_submitBtn(context, ref, form, notifier),
const SizedBox(height: 90), // 底部导航栏避让
],
);
}
Widget _sectionLabel(String text) => Padding(
padding: const EdgeInsets.only(bottom: 8, left: 4),
child: Text(
text,
style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xFF5D4037)),
),
);
// ---- 类型选择 ----
Widget _typeSelector(AddBillFormState form, AddBillFormNotifier notifier) {
return Row(
children: [
_typeCard('📤', '支出', 1, form, notifier),
const SizedBox(width: 10),
_typeCard('📥', '收入', 2, form, notifier),
],
);
}
Widget _typeCard(String icon, String label, int type, AddBillFormState form, AddBillFormNotifier notifier) {
final active = form.type == type;
return Expanded(
child: GestureDetector(
onTap: () => notifier.setType(type),
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
padding: const EdgeInsets.symmetric(vertical: 12),
decoration: BoxDecoration(
color: active ? Colors.white : Colors.white.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: active ? const Color(0xFFC8956E) : Colors.transparent,
width: 2,
),
boxShadow: active
? [BoxShadow(color: const Color(0x33C8956E), blurRadius: 8, offset: const Offset(0, 3))]
: null,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(icon, style: const TextStyle(fontSize: 20)),
const SizedBox(width: 8),
Text(
label,
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: active ? const Color(0xFF5D4037) : const Color(0xFF8D6E63),
),
),
],
),
),
),
);
}
// ---- 分类宫格 ----
Widget _categoryGrid(AddBillFormState form, AddBillFormNotifier notifier) {
return Consumer(builder: (context, ref, _) {
final categoriesAsync = ref.watch(categoriesProvider(form.type));
return categoriesAsync.when(
loading: () => const LoadingView(padding: EdgeInsets.all(20)),
error: (e, _) => ErrorView(
message: '分类加载失败:${asApiException(e).message}',
onRetry: () => ref.invalidate(categoriesProvider),
),
data: (categories) => CategoryPickerGrid(
categories: categories,
selectedId: form.categoryId,
onSelect: notifier.setCategory,
crossAxisCount: 5,
),
);
});
}
// ---- 金额 ----
Widget _amountField(AddBillFormState form, AddBillFormNotifier notifier) {
return TextField(
controller: _amountController,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
inputFormatters: [AmountInputFormatter()],
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF5D4037)),
decoration: InputDecoration(
hintText: '请输入金额',
prefixText: '¥ ',
prefixStyle: const TextStyle(fontSize: 18, color: Color(0xFFC8956E), fontWeight: FontWeight.bold),
filled: true,
fillColor: Colors.white,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(14), borderSide: BorderSide.none),
),
onChanged: (v) => notifier.setAmount(double.tryParse(v)),
);
}
// ---- 日期 ----
Widget _dateField(BuildContext context, AddBillFormState form, AddBillFormNotifier notifier) {
return GestureDetector(
onTap: () async {
final initial = DateTime.tryParse(form.billDate) ?? DateTime.now();
final picked = await showDatePicker(
context: context,
initialDate: initial,
firstDate: DateTime(2000),
lastDate: DateTime(2100),
);
if (picked != null) notifier.setDate(formatDate(picked));
},
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(14),
),
child: Row(
children: [
Text(form.billDate, style: const TextStyle(fontSize: 15, color: Color(0xFF5D4037))),
const Spacer(),
const Icon(Icons.chevron_right, color: Color(0xFF8D6E63)),
],
),
),
);
}
// ---- 备注 ----
Widget _descriptionField(AddBillFormState form, AddBillFormNotifier notifier) {
return TextField(
maxLines: 3,
maxLength: 200,
controller: _descriptionController,
style: const TextStyle(fontSize: 15, color: Color(0xFF5D4037)),
decoration: InputDecoration(
hintText: '请输入备注(可选)',
filled: true,
fillColor: Colors.white,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(14), borderSide: BorderSide.none),
),
onChanged: notifier.setDescription,
);
}
// ---- 保存 ----
Widget _submitBtn(BuildContext context, WidgetRef ref, AddBillFormState form, AddBillFormNotifier notifier) {
return SizedBox(
width: double.infinity,
height: 50,
child: FilledButton(
style: FilledButton.styleFrom(
backgroundColor: const Color(0xFFC8956E),
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
),
onPressed: form.submitting
? null
: () async {
try {
await notifier.submit();
_amountController.clear();
_descriptionController.clear();
if (context.mounted) showToast(context, '✅ 记账成功');
} on ApiException catch (e) {
if (context.mounted) showToast(context, e.message, error: true);
} catch (_) {
if (context.mounted) showToast(context, '保存失败,请重试', error: true);
}
},
child: form.submitting
? const SizedBox(
width: 22, height: 22,
child: CircularProgressIndicator(strokeWidth: 2.5, color: Colors.white),
)
: const Text('保 存', style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold, letterSpacing: 4)),
),
);
}
}
+139
View File
@@ -0,0 +1,139 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../providers/add_bill_provider.dart';
import '../../../providers/ocr_provider.dart';
import '../../../utils/date_util.dart';
import '../add_page.dart';
/// 单条 OCR 识别结果卡片:可折叠详情 + 「选择此条」填充手动表单
class OcrResultCard extends ConsumerWidget {
final int index;
final bool expanded;
final VoidCallback onToggle;
const OcrResultCard({
super.key,
required this.index,
required this.expanded,
required this.onToggle,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(ocrProvider);
if (index >= state.results.length) return const SizedBox.shrink();
final result = state.results[index];
final isExpense = result.isExpense;
return Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(14),
border: Border.all(color: const Color(0xFFE0C9A6)),
),
child: Column(
children: [
// 头部:序号 + 金额 + 置信度 + 展开
InkWell(
onTap: onToggle,
borderRadius: BorderRadius.circular(14),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
child: Row(
children: [
Text(
'#${index + 1}',
style: const TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: Color(0xFF8D6E63)),
),
const SizedBox(width: 12),
Expanded(
child: Text(
'¥${result.absAmount.toStringAsFixed(2)}',
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.bold,
color: isExpense ? const Color(0xFFEF5350) : const Color(0xFF66BB6A),
),
),
),
if (result.confidence != null)
Padding(
padding: const EdgeInsets.only(right: 8),
child: Text(
'置信度 ${(result.confidence! * 100).toStringAsFixed(1)}%',
style: const TextStyle(fontSize: 12, color: Color(0xFFBCAAA4)),
),
),
AnimatedRotation(
turns: expanded ? 0.5 : 0,
duration: const Duration(milliseconds: 200),
child: const Icon(Icons.expand_more, color: Color(0xFF8D6E63)),
),
],
),
),
),
// 详情
AnimatedCrossFade(
duration: const Duration(milliseconds: 200),
crossFadeState: expanded ? CrossFadeState.showSecond : CrossFadeState.showFirst,
firstChild: const SizedBox(width: double.infinity),
secondChild: Padding(
padding: const EdgeInsets.fromLTRB(14, 0, 14, 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Divider(height: 1, color: Color(0xFFF0E6D8)),
const SizedBox(height: 8),
_detailRow('类型', isExpense ? '支出' : '收入'),
if (result.merchant != null && result.merchant!.isNotEmpty)
_detailRow('商户', result.merchant!),
if (result.date != null && result.date!.isNotEmpty)
_detailRow('日期', parseBillDate(result.date)),
const SizedBox(height: 10),
SizedBox(
width: double.infinity,
height: 38,
child: OutlinedButton(
style: OutlinedButton.styleFrom(
foregroundColor: const Color(0xFFC8956E),
side: const BorderSide(color: Color(0xFFC8956E)),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(19)),
),
onPressed: () {
ref.read(addBillFormProvider.notifier).fillFromOcr(result);
// 切回手动记账 Tab 并清空 OCR 状态
ref.read(addTabProvider.notifier).set(0);
ref.read(ocrProvider.notifier).clearImage();
},
child: const Text('选择此条', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600)),
),
),
],
),
),
),
],
),
);
}
Widget _detailRow(String label, String value) {
return Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 42,
child: Text(label, style: const TextStyle(fontSize: 13, color: Color(0xFF8D6E63))),
),
Expanded(
child: Text(value, style: const TextStyle(fontSize: 13, color: Color(0xFF5D4037))),
),
],
),
);
}
}
+208
View File
@@ -0,0 +1,208 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:image_picker/image_picker.dart';
import '../../../core/network/api_exception.dart';
import '../../../providers/ocr_provider.dart';
import '../../../utils/toast.dart';
import 'ocr_result_card.dart';
/// OCR 识别 Tab:选图 → 识别 → 结果列表(复刻 uniApp add.vue OCR Tab)
class OcrTab extends ConsumerWidget {
const OcrTab({super.key});
Future<void> _chooseImage(BuildContext context, WidgetRef ref, ImageSource source) async {
final picker = ImagePicker();
final xfile = await picker.pickImage(source: source, imageQuality: 80, maxWidth: 1600);
if (xfile != null) {
ref.read(ocrProvider.notifier).setImagePath(xfile.path);
}
}
Future<void> _recognize(BuildContext context, WidgetRef ref) async {
try {
await ref.read(ocrProvider.notifier).recognize();
final count = ref.read(ocrProvider).results.length;
if (context.mounted) {
showToast(context, count > 0 ? '识别到 $count 条记录' : '未识别到账单信息', error: count == 0);
}
} on ApiException catch (e) {
if (context.mounted) showToast(context, e.message, error: true);
} catch (_) {
if (context.mounted) showToast(context, '识别失败,请重试', error: true);
}
}
Future<void> _saveDirectly(BuildContext context, WidgetRef ref) async {
try {
await ref.read(ocrProvider.notifier).saveDirectly();
if (context.mounted) showToast(context, '✅ 已保存识别的账单');
} on ApiException catch (e) {
if (context.mounted) showToast(context, e.message, error: true);
} catch (_) {
if (context.mounted) showToast(context, '保存失败,请重试', error: true);
}
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(ocrProvider);
final notifier = ref.read(ocrProvider.notifier);
return ListView(
padding: const EdgeInsets.all(16),
children: [
// 图片预览
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
),
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('图片预览', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xFF5D4037))),
const SizedBox(height: 10),
GestureDetector(
onTap: () => _showSourceSheet(context, ref),
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: state.imagePath != null
? SizedBox(
height: 220,
width: double.infinity,
child: Image.file(
File(state.imagePath!),
fit: BoxFit.contain,
),
)
: Container(
height: 140,
width: double.infinity,
color: const Color(0xFFF5F5F5),
child: const Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('📷', style: TextStyle(fontSize: 36)),
SizedBox(height: 6),
Text('点击选择图片', style: TextStyle(color: Color(0xFF8D6E63))),
],
),
),
),
),
if (state.imagePath != null)
Align(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: notifier.clearImage,
child: const Text('清除图片', style: TextStyle(color: Color(0xFF8D6E63))),
),
),
],
),
),
const SizedBox(height: 14),
// 识别按钮
if (state.imagePath != null && state.results.isEmpty)
SizedBox(
width: double.infinity,
height: 48,
child: FilledButton(
style: FilledButton.styleFrom(
backgroundColor: const Color(0xFFC8956E),
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
),
onPressed: state.recognizing ? null : () => _recognize(context, ref),
child: state.recognizing
? const SizedBox(
width: 22, height: 22,
child: CircularProgressIndicator(strokeWidth: 2.5, color: Colors.white),
)
: const Text('识别账单', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
),
),
// 识别结果
if (state.results.isNotEmpty) ...[
SizedBox(
width: double.infinity,
height: 44,
child: FilledButton.icon(
style: FilledButton.styleFrom(
backgroundColor: const Color(0xFF667eea),
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(22)),
),
onPressed: state.saving ? null : () => _saveDirectly(context, ref),
icon: state.saving
? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
: const Icon(Icons.save_outlined, size: 18),
label: const Text('直接存储', style: TextStyle(fontWeight: FontWeight.bold)),
),
),
const SizedBox(height: 12),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.9),
borderRadius: BorderRadius.circular(12),
),
child: Text(
'识别到 ${state.results.length} 条账单记录',
style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xFF5D4037)),
),
),
const SizedBox(height: 10),
for (var i = 0; i < state.results.length; i++)
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: OcrResultCard(
index: i,
expanded: state.expandedIndexes.contains(i),
onToggle: () => notifier.toggleExpanded(i),
),
),
],
const SizedBox(height: 90), // 底部导航栏避让
],
);
}
void _showSourceSheet(BuildContext context, WidgetRef ref) {
showModalBottomSheet(
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (sheetCtx) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: const Icon(Icons.camera_alt_outlined),
title: const Text('拍照'),
onTap: () {
Navigator.pop(sheetCtx);
_chooseImage(context, ref, ImageSource.camera);
},
),
ListTile(
leading: const Icon(Icons.photo_library_outlined),
title: const Text('从相册选择'),
onTap: () {
Navigator.pop(sheetCtx);
_chooseImage(context, ref, ImageSource.gallery);
},
),
],
),
),
);
}
}