feat: 增加全家庭智能药箱功能,支持扫码识别(追溯码/GS1/条形码)、出厂有效期与开封保质期双轨追踪及局域网多设备同步
This commit is contained in:
@@ -0,0 +1,292 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
enum MedicineCategory {
|
||||
oralLiquid, // 口服混悬液/糖浆
|
||||
eyeDrops, // 滴眼液/滴耳液/滴鼻液
|
||||
inhaler, // 吸入剂/气雾剂
|
||||
topical, // 外用乳膏/软膏
|
||||
tablets, // 片剂/胶囊
|
||||
spray, // 喷雾剂
|
||||
other, // 其他
|
||||
}
|
||||
|
||||
extension MedicineCategoryExt on MedicineCategory {
|
||||
String get label {
|
||||
switch (this) {
|
||||
case MedicineCategory.oralLiquid:
|
||||
return '口服混悬/糖浆';
|
||||
case MedicineCategory.eyeDrops:
|
||||
return '滴眼/滴鼻液';
|
||||
case MedicineCategory.inhaler:
|
||||
return '吸入/气雾剂';
|
||||
case MedicineCategory.topical:
|
||||
return '外用乳膏/软膏';
|
||||
case MedicineCategory.tablets:
|
||||
return '片剂/胶囊';
|
||||
case MedicineCategory.spray:
|
||||
return '外用喷雾';
|
||||
case MedicineCategory.other:
|
||||
return '其他药品';
|
||||
}
|
||||
}
|
||||
|
||||
IconData get icon {
|
||||
switch (this) {
|
||||
case MedicineCategory.oralLiquid:
|
||||
return Icons.water_drop_outlined;
|
||||
case MedicineCategory.eyeDrops:
|
||||
return Icons.remove_red_eye_outlined;
|
||||
case MedicineCategory.inhaler:
|
||||
return Icons.air;
|
||||
case MedicineCategory.topical:
|
||||
return Icons.clean_hands_outlined;
|
||||
case MedicineCategory.tablets:
|
||||
return Icons.medication_outlined;
|
||||
case MedicineCategory.spray:
|
||||
return Icons.scatter_plot_outlined;
|
||||
case MedicineCategory.other:
|
||||
return Icons.medical_services_outlined;
|
||||
}
|
||||
}
|
||||
|
||||
/// 临床常见开封后推荐保质期天数
|
||||
int? get defaultShelfLifeDaysAfterOpening {
|
||||
switch (this) {
|
||||
case MedicineCategory.oralLiquid:
|
||||
return 60; // 混悬液开封后一般建议 1~2 个月内用完
|
||||
case MedicineCategory.eyeDrops:
|
||||
return 28; // 绝大多数眼药水开封 4 周后必须丢弃
|
||||
case MedicineCategory.inhaler:
|
||||
return 60; // 辅舒酮等拆封后通常建议 60 天
|
||||
case MedicineCategory.topical:
|
||||
return 90; // 软膏开封后一般 3 个月
|
||||
case MedicineCategory.spray:
|
||||
return 60;
|
||||
case MedicineCategory.tablets:
|
||||
return null; // 独立泡罩铝箔通常跟随出厂保质期
|
||||
case MedicineCategory.other:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum MedicineHealthStatus {
|
||||
safe, // 🟢 安全正常
|
||||
expiringSoon, // 🟡 临期预警 (30天内到期或开封7天内超期)
|
||||
overdueInUse, // 🔴 开封超期 (开封天数超过建议保质期)
|
||||
expired, // 🔴 已过期 (出厂有效期已过)
|
||||
}
|
||||
|
||||
class MedicineItem {
|
||||
final String id;
|
||||
final String name;
|
||||
final MedicineCategory category;
|
||||
final String spec; // 如 "100ml", "60喷", "24片"
|
||||
final String storageLocation; // 如 "常温药箱", "冰箱冷藏(2-8℃)", "随身包"
|
||||
final String targetUser; // 如 "宝宝", "全家", "爸爸", "妈妈"
|
||||
final String? barcode; // 条码/追溯码
|
||||
final String? batchNumber; // 批号
|
||||
final DateTime? productionDate; // 生产日期
|
||||
final DateTime expiryDate; // 出厂有效期至 (必选)
|
||||
final int? shelfLifeDaysAfterOpening; // 开封后有效天数
|
||||
final bool isOpened; // 是否已开封
|
||||
final DateTime? openedAt; // 开封时间
|
||||
final String? openedByDevice; // 开封设备标识
|
||||
final String notes; // 适应症/用法备注
|
||||
final bool isDeleted; // 墓碑标记软删除
|
||||
final DateTime updatedAt; // 更新时间 UTC
|
||||
|
||||
const MedicineItem({
|
||||
required this.id,
|
||||
required this.name,
|
||||
this.category = MedicineCategory.other,
|
||||
this.spec = '',
|
||||
this.storageLocation = '常温药箱',
|
||||
this.targetUser = '全家',
|
||||
this.barcode,
|
||||
this.batchNumber,
|
||||
this.productionDate,
|
||||
required this.expiryDate,
|
||||
this.shelfLifeDaysAfterOpening,
|
||||
this.isOpened = false,
|
||||
this.openedAt,
|
||||
this.openedByDevice,
|
||||
this.notes = '',
|
||||
this.isDeleted = false,
|
||||
required this.updatedAt,
|
||||
});
|
||||
|
||||
/// 距出厂到期天数
|
||||
int get daysUntilExpiry {
|
||||
final now = DateTime.now();
|
||||
final today = DateTime(now.year, now.month, now.day);
|
||||
final exp = DateTime(expiryDate.year, expiryDate.month, expiryDate.day);
|
||||
return exp.difference(today).inDays;
|
||||
}
|
||||
|
||||
/// 已开封天数
|
||||
int? get daysSinceOpened {
|
||||
if (!isOpened || openedAt == null) return null;
|
||||
final now = DateTime.now();
|
||||
final today = DateTime(now.year, now.month, now.day);
|
||||
final op = DateTime(openedAt!.year, openedAt!.month, openedAt!.day);
|
||||
final days = today.difference(op).inDays;
|
||||
return days < 0 ? 0 : days;
|
||||
}
|
||||
|
||||
/// 距开封后保质期截止天数 (剩余可用天数)
|
||||
int? get daysUntilInUseExpiry {
|
||||
if (!isOpened || openedAt == null || shelfLifeDaysAfterOpening == null) {
|
||||
return null;
|
||||
}
|
||||
final daysUsed = daysSinceOpened ?? 0;
|
||||
return shelfLifeDaysAfterOpening! - daysUsed;
|
||||
}
|
||||
|
||||
/// 综合健康状态
|
||||
MedicineHealthStatus get healthStatus {
|
||||
if (daysUntilExpiry < 0) {
|
||||
return MedicineHealthStatus.expired;
|
||||
}
|
||||
if (isOpened && daysUntilInUseExpiry != null && daysUntilInUseExpiry! < 0) {
|
||||
return MedicineHealthStatus.overdueInUse;
|
||||
}
|
||||
final inUseSoon = isOpened && daysUntilInUseExpiry != null && daysUntilInUseExpiry! <= 7;
|
||||
final expSoon = daysUntilExpiry <= 30;
|
||||
if (expSoon || inUseSoon) {
|
||||
return MedicineHealthStatus.expiringSoon;
|
||||
}
|
||||
return MedicineHealthStatus.safe;
|
||||
}
|
||||
|
||||
String get healthStatusLabel {
|
||||
switch (healthStatus) {
|
||||
case MedicineHealthStatus.safe:
|
||||
return isOpened ? '在用正常' : '未开封';
|
||||
case MedicineHealthStatus.expiringSoon:
|
||||
if (daysUntilExpiry <= 30) {
|
||||
return '即将到期 ($daysUntilExpiry天)';
|
||||
}
|
||||
return '开封快到期 ($daysUntilInUseExpiry天)';
|
||||
case MedicineHealthStatus.overdueInUse:
|
||||
return '⚠️ 开封已超期';
|
||||
case MedicineHealthStatus.expired:
|
||||
return '❌ 出厂已过期';
|
||||
}
|
||||
}
|
||||
|
||||
Color get healthStatusColor {
|
||||
switch (healthStatus) {
|
||||
case MedicineHealthStatus.safe:
|
||||
return isOpened ? const Color(0xFF2563EB) : const Color(0xFF10B981);
|
||||
case MedicineHealthStatus.expiringSoon:
|
||||
return const Color(0xFFF59E0B);
|
||||
case MedicineHealthStatus.overdueInUse:
|
||||
case MedicineHealthStatus.expired:
|
||||
return const Color(0xFFEF4444);
|
||||
}
|
||||
}
|
||||
|
||||
MedicineItem copyWith({
|
||||
String? id,
|
||||
String? name,
|
||||
MedicineCategory? category,
|
||||
String? spec,
|
||||
String? storageLocation,
|
||||
String? targetUser,
|
||||
String? barcode,
|
||||
String? batchNumber,
|
||||
DateTime? productionDate,
|
||||
DateTime? expiryDate,
|
||||
int? shelfLifeDaysAfterOpening,
|
||||
bool? isOpened,
|
||||
DateTime? openedAt,
|
||||
String? openedByDevice,
|
||||
String? notes,
|
||||
bool? isDeleted,
|
||||
DateTime? updatedAt,
|
||||
}) {
|
||||
return MedicineItem(
|
||||
id: id ?? this.id,
|
||||
name: name ?? this.name,
|
||||
category: category ?? this.category,
|
||||
spec: spec ?? this.spec,
|
||||
storageLocation: storageLocation ?? this.storageLocation,
|
||||
targetUser: targetUser ?? this.targetUser,
|
||||
barcode: barcode ?? this.barcode,
|
||||
batchNumber: batchNumber ?? this.batchNumber,
|
||||
productionDate: productionDate ?? this.productionDate,
|
||||
expiryDate: expiryDate ?? this.expiryDate,
|
||||
shelfLifeDaysAfterOpening: shelfLifeDaysAfterOpening ?? this.shelfLifeDaysAfterOpening,
|
||||
isOpened: isOpened ?? this.isOpened,
|
||||
openedAt: openedAt ?? this.openedAt,
|
||||
openedByDevice: openedByDevice ?? this.openedByDevice,
|
||||
notes: notes ?? this.notes,
|
||||
isDeleted: isDeleted ?? this.isDeleted,
|
||||
updatedAt: updatedAt ?? this.updatedAt,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'category': category.name,
|
||||
'spec': spec,
|
||||
'storageLocation': storageLocation,
|
||||
'targetUser': targetUser,
|
||||
'barcode': barcode,
|
||||
'batchNumber': batchNumber,
|
||||
'productionDate': productionDate?.toUtc().toIso8601String(),
|
||||
'expiryDate': expiryDate.toUtc().toIso8601String(),
|
||||
'shelfLifeDaysAfterOpening': shelfLifeDaysAfterOpening,
|
||||
'isOpened': isOpened,
|
||||
'openedAt': openedAt?.toUtc().toIso8601String(),
|
||||
'openedByDevice': openedByDevice,
|
||||
'notes': notes,
|
||||
'isDeleted': isDeleted,
|
||||
'updatedAt': updatedAt.toUtc().toIso8601String(),
|
||||
};
|
||||
}
|
||||
|
||||
factory MedicineItem.fromJson(Map<String, dynamic> json) {
|
||||
MedicineCategory cat = MedicineCategory.other;
|
||||
final catStr = json['category'] as String?;
|
||||
if (catStr != null) {
|
||||
for (final c in MedicineCategory.values) {
|
||||
if (c.name == catStr) {
|
||||
cat = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return MedicineItem(
|
||||
id: json['id'] as String,
|
||||
name: json['name'] as String,
|
||||
category: cat,
|
||||
spec: (json['spec'] as String?) ?? '',
|
||||
storageLocation: (json['storageLocation'] as String?) ?? '常温药箱',
|
||||
targetUser: (json['targetUser'] as String?) ?? '全家',
|
||||
barcode: json['barcode'] as String?,
|
||||
batchNumber: json['batchNumber'] as String?,
|
||||
productionDate: json['productionDate'] != null
|
||||
? DateTime.parse(json['productionDate'] as String).toLocal()
|
||||
: null,
|
||||
expiryDate: json['expiryDate'] != null
|
||||
? DateTime.parse(json['expiryDate'] as String).toLocal()
|
||||
: DateTime.now().add(const Duration(days: 365)),
|
||||
shelfLifeDaysAfterOpening: json['shelfLifeDaysAfterOpening'] as int?,
|
||||
isOpened: (json['isOpened'] as bool?) ?? false,
|
||||
openedAt: json['openedAt'] != null
|
||||
? DateTime.parse(json['openedAt'] as String).toLocal()
|
||||
: null,
|
||||
openedByDevice: json['openedByDevice'] as String?,
|
||||
notes: (json['notes'] as String?) ?? '',
|
||||
isDeleted: (json['isDeleted'] as bool?) ?? false,
|
||||
updatedAt: json['updatedAt'] != null
|
||||
? DateTime.parse(json['updatedAt'] as String).toUtc()
|
||||
: DateTime.now().toUtc(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,13 @@ import '../models/canister.dart';
|
||||
import '../models/dose_record.dart';
|
||||
import '../models/app_settings.dart';
|
||||
import '../services/storage_service.dart';
|
||||
import '../models/medicine_item.dart';
|
||||
import 'session_screen.dart';
|
||||
import 'history_screen.dart';
|
||||
import 'settings_screen.dart';
|
||||
import 'plan_config_screen.dart';
|
||||
import 'lan_sync_screen.dart';
|
||||
import 'medicine_cabinet_screen.dart';
|
||||
import '../services/sync_service.dart';
|
||||
import '../services/active_session_service.dart';
|
||||
|
||||
@@ -284,6 +286,22 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.medical_services_outlined, color: Color(0xFF059669)),
|
||||
tooltip: '家庭药箱',
|
||||
visualDensity: VisualDensity.compact,
|
||||
onPressed: () async {
|
||||
await Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => MedicineCabinetScreen(
|
||||
storageService: widget.storageService,
|
||||
syncService: SyncService(widget.storageService),
|
||||
),
|
||||
),
|
||||
);
|
||||
_loadData();
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.sync, color: Color(0xFF2563EB)),
|
||||
tooltip: '局域网同步',
|
||||
@@ -352,6 +370,11 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// 模块 3.5:家庭智能药箱看板入口
|
||||
_buildFamilyMedicineCabinetCard(),
|
||||
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// 模块 4:最近吸入记录底栏
|
||||
_buildLastRecordFooter(),
|
||||
],
|
||||
@@ -360,6 +383,112 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
// 3.5 家庭智能药箱入口卡片
|
||||
Widget _buildFamilyMedicineCabinetCard() {
|
||||
final medicines = widget.storageService.getMedicines();
|
||||
final dangerCount = medicines.where((m) =>
|
||||
m.healthStatus == MedicineHealthStatus.overdueInUse ||
|
||||
m.healthStatus == MedicineHealthStatus.expired).length;
|
||||
final soonCount = medicines.where((m) => m.healthStatus == MedicineHealthStatus.expiringSoon).length;
|
||||
|
||||
Color badgeBg = const Color(0xFFEFF6FF);
|
||||
Color badgeColor = const Color(0xFF2563EB);
|
||||
String badgeText = '${medicines.length} 种在库';
|
||||
|
||||
if (dangerCount > 0) {
|
||||
badgeBg = const Color(0xFFFEF2F2);
|
||||
badgeColor = const Color(0xFFEF4444);
|
||||
badgeText = '⚠️ $dangerCount 种已超期/过期';
|
||||
} else if (soonCount > 0) {
|
||||
badgeBg = const Color(0xFFFEF3C7);
|
||||
badgeColor = const Color(0xFFD97706);
|
||||
badgeText = '🟡 $soonCount 种即将到期';
|
||||
}
|
||||
|
||||
return Card(
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
side: BorderSide(color: dangerCount > 0 ? Colors.red.shade300 : const Color(0xFFE2E8F0)),
|
||||
),
|
||||
child: InkWell(
|
||||
onTap: () async {
|
||||
await Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => MedicineCabinetScreen(
|
||||
storageService: widget.storageService,
|
||||
syncService: SyncService(widget.storageService),
|
||||
),
|
||||
),
|
||||
);
|
||||
_loadData();
|
||||
},
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFECFDF5),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.medical_services_outlined,
|
||||
color: Color(0xFF059669),
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Text(
|
||||
'家庭智能药箱',
|
||||
style: TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Color(0xFF0F172A),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: badgeBg,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
badgeText,
|
||||
style: TextStyle(
|
||||
color: badgeColor,
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
const Text(
|
||||
'出厂有效期与开封保质期智能监控 · 扫码即识',
|
||||
style: TextStyle(fontSize: 12, color: Colors.black54),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Icon(Icons.arrow_forward_ios, size: 14, color: Colors.grey),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 0. 进行中雾化实时悬浮卡片 (返回主页不中断计时)
|
||||
Widget _buildActiveSessionBanner() {
|
||||
final step = _sessionService.currentStep;
|
||||
|
||||
@@ -0,0 +1,739 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../models/medicine_item.dart';
|
||||
import '../services/medicine_parser_service.dart';
|
||||
import '../services/storage_service.dart';
|
||||
import '../services/sync_service.dart';
|
||||
import 'medicine_edit_dialog.dart';
|
||||
import 'medicine_scan_screen.dart';
|
||||
|
||||
class MedicineCabinetScreen extends StatefulWidget {
|
||||
final StorageService storageService;
|
||||
final SyncService syncService;
|
||||
|
||||
const MedicineCabinetScreen({
|
||||
super.key,
|
||||
required this.storageService,
|
||||
required this.syncService,
|
||||
});
|
||||
|
||||
@override
|
||||
State<MedicineCabinetScreen> createState() => _MedicineCabinetScreenState();
|
||||
}
|
||||
|
||||
class _MedicineCabinetScreenState extends State<MedicineCabinetScreen> {
|
||||
List<MedicineItem> _medicines = [];
|
||||
String _selectedFilter = '全部';
|
||||
String _searchQuery = '';
|
||||
bool _isSyncing = false;
|
||||
|
||||
final List<String> _filters = [
|
||||
'全部',
|
||||
'常温药箱',
|
||||
'冰箱冷藏',
|
||||
'宝宝专用',
|
||||
'已开封',
|
||||
'⚠️ 需处理',
|
||||
];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadMedicines();
|
||||
}
|
||||
|
||||
void _loadMedicines() {
|
||||
setState(() {
|
||||
_medicines = widget.storageService.getMedicines();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _performSync() async {
|
||||
if (_isSyncing) return;
|
||||
setState(() => _isSyncing = true);
|
||||
|
||||
final res = await widget.syncService.performSync();
|
||||
if (mounted) {
|
||||
setState(() => _isSyncing = false);
|
||||
_loadMedicines();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(res.message),
|
||||
backgroundColor: res.success ? const Color(0xFF059669) : Colors.red,
|
||||
duration: const Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _openScan() async {
|
||||
final result = await Navigator.of(context).push<ScannedMedicineInfo>(
|
||||
MaterialPageRoute(builder: (_) => const MedicineScanScreen()),
|
||||
);
|
||||
|
||||
if (result != null && mounted) {
|
||||
final savedItem = await showDialog<MedicineItem>(
|
||||
context: context,
|
||||
builder: (_) => MedicineEditDialog(scannedInfo: result),
|
||||
);
|
||||
|
||||
if (savedItem != null) {
|
||||
await widget.storageService.saveMedicine(savedItem);
|
||||
_loadMedicines();
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('已添加药品:${savedItem.name}')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _addNewMedicine() async {
|
||||
final savedItem = await showDialog<MedicineItem>(
|
||||
context: context,
|
||||
builder: (_) => const MedicineEditDialog(),
|
||||
);
|
||||
|
||||
if (savedItem != null) {
|
||||
await widget.storageService.saveMedicine(savedItem);
|
||||
_loadMedicines();
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('已添加药品:${savedItem.name}')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _editMedicine(MedicineItem item) async {
|
||||
final updatedItem = await showDialog<MedicineItem>(
|
||||
context: context,
|
||||
builder: (_) => MedicineEditDialog(initialItem: item),
|
||||
);
|
||||
|
||||
if (updatedItem != null) {
|
||||
await widget.storageService.saveMedicine(updatedItem);
|
||||
_loadMedicines();
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('已更新药品:${updatedItem.name}')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _deleteMedicine(MedicineItem item) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('确认下架/删除该药品?'),
|
||||
content: Text('确定将【${item.name}】移出药箱吗?该操作将同步至所有设备。'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, false),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
child: const Text('确认删除', style: TextStyle(color: Colors.white)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmed == true) {
|
||||
await widget.storageService.deleteMedicine(item.id);
|
||||
_loadMedicines();
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('已移出药品:${item.name}')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _openMedicineCard(MedicineItem item) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('确认开封打卡?'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('药品:${item.name}'),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'推荐开封保质期限:${item.shelfLifeDaysAfterOpening ?? 60} 天',
|
||||
style: const TextStyle(fontWeight: FontWeight.bold, color: Color(0xFF2563EB)),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const Text(
|
||||
'打卡后将自动开启开封保质期倒计时,全家设备实时同步。',
|
||||
style: TextStyle(fontSize: 12, color: Colors.black54),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, false),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF2563EB)),
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
child: const Text('确认开封', style: TextStyle(color: Colors.white)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmed == true) {
|
||||
final deviceName = await SyncService.getDeviceName();
|
||||
await widget.storageService.openMedicine(item.id, deviceName: deviceName);
|
||||
_loadMedicines();
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('【${item.name}】已成功打卡开封!')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<MedicineItem> get _filteredMedicines {
|
||||
return _medicines.where((m) {
|
||||
// 搜索关键字匹配
|
||||
if (_searchQuery.isNotEmpty) {
|
||||
final q = _searchQuery.toLowerCase();
|
||||
final matchName = m.name.toLowerCase().contains(q);
|
||||
final matchSpec = m.spec.toLowerCase().contains(q);
|
||||
final matchNotes = m.notes.toLowerCase().contains(q);
|
||||
if (!matchName && !matchSpec && !matchNotes) return false;
|
||||
}
|
||||
|
||||
// 标签筛选
|
||||
switch (_selectedFilter) {
|
||||
case '常温药箱':
|
||||
return m.storageLocation.contains('常温');
|
||||
case '冰箱冷藏':
|
||||
return m.storageLocation.contains('冷藏') || m.storageLocation.contains('冰箱');
|
||||
case '宝宝专用':
|
||||
return m.targetUser.contains('宝宝');
|
||||
case '已开封':
|
||||
return m.isOpened;
|
||||
case '⚠️ 需处理':
|
||||
return m.healthStatus == MedicineHealthStatus.expiringSoon ||
|
||||
m.healthStatus == MedicineHealthStatus.overdueInUse ||
|
||||
m.healthStatus == MedicineHealthStatus.expired;
|
||||
case '全部':
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}).toList();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// 统计指标
|
||||
final totalCount = _medicines.length;
|
||||
final safeCount = _medicines.where((m) => m.healthStatus == MedicineHealthStatus.safe).length;
|
||||
final soonCount = _medicines.where((m) => m.healthStatus == MedicineHealthStatus.expiringSoon).length;
|
||||
final dangerCount = _medicines.where((m) =>
|
||||
m.healthStatus == MedicineHealthStatus.overdueInUse ||
|
||||
m.healthStatus == MedicineHealthStatus.expired).length;
|
||||
|
||||
final displayList = _filteredMedicines;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFFF8FAFC),
|
||||
appBar: AppBar(
|
||||
title: const Text('家庭智能药箱', style: TextStyle(fontWeight: FontWeight.bold)),
|
||||
backgroundColor: Colors.white,
|
||||
foregroundColor: const Color(0xFF0F172A),
|
||||
elevation: 0.5,
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: _isSyncing
|
||||
? const SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.sync, color: Color(0xFF2563EB)),
|
||||
tooltip: '局域网全家同步',
|
||||
onPressed: _isSyncing ? null : _performSync,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.qr_code_scanner, color: Color(0xFF2563EB)),
|
||||
tooltip: '扫码录药',
|
||||
onPressed: _openScan,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
// 1. 顶部健康看板统计卡片
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
color: Colors.white,
|
||||
child: Row(
|
||||
children: [
|
||||
_buildStatMetric(
|
||||
label: '在库药品',
|
||||
count: totalCount,
|
||||
color: const Color(0xFF334155),
|
||||
isSelected: _selectedFilter == '全部',
|
||||
onTap: () => setState(() => _selectedFilter = '全部'),
|
||||
),
|
||||
_buildStatMetric(
|
||||
label: '安全正常',
|
||||
count: safeCount,
|
||||
color: const Color(0xFF10B981),
|
||||
isSelected: false,
|
||||
onTap: () => setState(() => _selectedFilter = '全部'),
|
||||
),
|
||||
_buildStatMetric(
|
||||
label: '临期预警',
|
||||
count: soonCount,
|
||||
color: const Color(0xFFF59E0B),
|
||||
isSelected: _selectedFilter == '⚠️ 需处理',
|
||||
onTap: () => setState(() => _selectedFilter = '⚠️ 需处理'),
|
||||
),
|
||||
_buildStatMetric(
|
||||
label: '超期/过期',
|
||||
count: dangerCount,
|
||||
color: const Color(0xFFEF4444),
|
||||
isSelected: _selectedFilter == '⚠️ 需处理',
|
||||
onTap: () => setState(() => _selectedFilter = '⚠️ 需处理'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// 2. 搜索框与过滤器标签
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
color: Colors.white,
|
||||
child: Column(
|
||||
children: [
|
||||
TextField(
|
||||
decoration: InputDecoration(
|
||||
hintText: '搜索药品名、规格、适应症...',
|
||||
prefixIcon: const Icon(Icons.search, size: 20, color: Colors.grey),
|
||||
isDense: true,
|
||||
filled: true,
|
||||
fillColor: const Color(0xFFF1F5F9),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(vertical: 8),
|
||||
),
|
||||
onChanged: (val) => setState(() => _searchQuery = val.trim()),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: _filters.map((f) {
|
||||
final selected = _selectedFilter == f;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 8),
|
||||
child: ChoiceChip(
|
||||
label: Text(f),
|
||||
selected: selected,
|
||||
selectedColor: const Color(0xFF2563EB),
|
||||
labelStyle: TextStyle(
|
||||
color: selected ? Colors.white : Colors.black87,
|
||||
fontSize: 12,
|
||||
),
|
||||
onSelected: (val) {
|
||||
if (val) setState(() => _selectedFilter = f);
|
||||
},
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// 3. 药品列表
|
||||
Expanded(
|
||||
child: displayList.isEmpty
|
||||
? Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.inventory_2_outlined, size: 56, color: Colors.grey.shade400),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
_searchQuery.isNotEmpty ? '没有找到符合的药品' : '药箱里还没有此类药品',
|
||||
style: TextStyle(color: Colors.grey.shade600),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton.icon(
|
||||
onPressed: _openScan,
|
||||
icon: const Icon(Icons.qr_code_scanner),
|
||||
label: const Text('扫描药品条码/追溯码录入'),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
: ListView.builder(
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: displayList.length,
|
||||
itemBuilder: (ctx, idx) {
|
||||
return _buildMedicineCard(displayList[idx]);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
floatingActionButton: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
FloatingActionButton.small(
|
||||
heroTag: 'fab_manual',
|
||||
backgroundColor: Colors.white,
|
||||
foregroundColor: const Color(0xFF2563EB),
|
||||
tooltip: '手动添加药品',
|
||||
onPressed: _addNewMedicine,
|
||||
child: const Icon(Icons.edit_note),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
FloatingActionButton.extended(
|
||||
heroTag: 'fab_scan',
|
||||
backgroundColor: const Color(0xFF2563EB),
|
||||
foregroundColor: Colors.white,
|
||||
icon: const Icon(Icons.qr_code_scanner),
|
||||
label: const Text('扫码录药'),
|
||||
onPressed: _openScan,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatMetric({
|
||||
required String label,
|
||||
required int count,
|
||||
required Color color,
|
||||
required bool isSelected,
|
||||
required VoidCallback onTap,
|
||||
}) {
|
||||
return Expanded(
|
||||
child: GestureDetector(
|
||||
onTap: onTap,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: isSelected ? color.withValues(alpha: 0.1) : Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Text(
|
||||
count.toString(),
|
||||
style: TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
label,
|
||||
style: const TextStyle(fontSize: 11, color: Colors.black54),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMedicineCard(MedicineItem item) {
|
||||
final dateFormat = DateFormat('yyyy/MM/dd');
|
||||
final isDanger = item.healthStatus == MedicineHealthStatus.overdueInUse ||
|
||||
item.healthStatus == MedicineHealthStatus.expired;
|
||||
final isWarning = item.healthStatus == MedicineHealthStatus.expiringSoon;
|
||||
|
||||
Color borderColor = Colors.grey.shade200;
|
||||
if (isDanger) borderColor = Colors.red.shade300;
|
||||
if (isWarning) borderColor = Colors.amber.shade300;
|
||||
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
elevation: 1,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
side: BorderSide(color: borderColor, width: isDanger ? 1.5 : 1),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// 卡片头部:图标、名称、状态 Badge 与操作菜单
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: item.category.icon == Icons.air
|
||||
? const Color(0xFFEFF6FF)
|
||||
: const Color(0xFFF1F5F9),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Icon(item.category.icon, color: const Color(0xFF2563EB), size: 22),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
item.name,
|
||||
style: const TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Color(0xFF0F172A),
|
||||
),
|
||||
),
|
||||
if (item.spec.isNotEmpty)
|
||||
Text(
|
||||
'规格: ${item.spec}',
|
||||
style: const TextStyle(fontSize: 12, color: Colors.black54),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: item.healthStatusColor.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
item.healthStatusLabel,
|
||||
style: TextStyle(
|
||||
color: item.healthStatusColor,
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
PopupMenuButton<String>(
|
||||
icon: const Icon(Icons.more_vert, size: 20, color: Colors.grey),
|
||||
onSelected: (val) {
|
||||
if (val == 'edit') _editMedicine(item);
|
||||
if (val == 'delete') _deleteMedicine(item);
|
||||
},
|
||||
itemBuilder: (ctx) => [
|
||||
const PopupMenuItem(value: 'edit', child: Text('编辑药品')),
|
||||
const PopupMenuItem(
|
||||
value: 'delete',
|
||||
child: Text('移出药箱', style: TextStyle(color: Colors.red)),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
|
||||
// 存放标签与成员胶囊
|
||||
Wrap(
|
||||
spacing: 6,
|
||||
children: [
|
||||
_buildTagChip(
|
||||
icon: item.storageLocation.contains('冷藏')
|
||||
? Icons.ac_unit
|
||||
: Icons.inventory_2_outlined,
|
||||
text: item.storageLocation,
|
||||
color: item.storageLocation.contains('冷藏')
|
||||
? const Color(0xFF0284C7)
|
||||
: const Color(0xFF64748B),
|
||||
),
|
||||
_buildTagChip(
|
||||
icon: Icons.person_outline,
|
||||
text: item.targetUser,
|
||||
color: const Color(0xFFD97706),
|
||||
),
|
||||
if (item.barcode != null && item.barcode!.isNotEmpty)
|
||||
_buildTagChip(
|
||||
icon: Icons.qr_code,
|
||||
text: item.barcode!.length > 13
|
||||
? '追溯码 ${item.barcode!.substring(0, 6)}...'
|
||||
: item.barcode!,
|
||||
color: const Color(0xFF64748B),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// 出厂保质期与开封情况
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFF8FAFC),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.event_outlined, size: 14, color: Colors.black54),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
'出厂有效期至: ${dateFormat.format(item.expiryDate)}',
|
||||
style: const TextStyle(fontSize: 12, color: Colors.black87),
|
||||
),
|
||||
const Spacer(),
|
||||
Text(
|
||||
item.daysUntilExpiry >= 0
|
||||
? '剩 ${item.daysUntilExpiry} 天'
|
||||
: '已过期 ${-item.daysUntilExpiry} 天',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: item.daysUntilExpiry <= 30 ? Colors.red : const Color(0xFF059669),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
// 若已开封
|
||||
if (item.isOpened && item.openedAt != null) ...[
|
||||
const SizedBox(height: 6),
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.lock_open, size: 14, color: Color(0xFF2563EB)),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
'已开封 (${dateFormat.format(item.openedAt!)})',
|
||||
style: const TextStyle(fontSize: 12, color: Color(0xFF2563EB)),
|
||||
),
|
||||
const Spacer(),
|
||||
if (item.shelfLifeDaysAfterOpening != null) ...[
|
||||
Text(
|
||||
(item.daysUntilInUseExpiry ?? 0) >= 0
|
||||
? '开封保质剩 ${item.daysUntilInUseExpiry} 天'
|
||||
: '开封超期 ${-(item.daysUntilInUseExpiry ?? 0)} 天',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: (item.daysUntilInUseExpiry ?? 0) <= 7 ? Colors.red : const Color(0xFF2563EB),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
if (item.shelfLifeDaysAfterOpening != null) ...[
|
||||
const SizedBox(height: 6),
|
||||
LinearProgressIndicator(
|
||||
value: (item.daysSinceOpened ?? 0) / item.shelfLifeDaysAfterOpening!,
|
||||
backgroundColor: Colors.grey.shade200,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
(item.daysUntilInUseExpiry ?? 0) < 0
|
||||
? Colors.red
|
||||
: ((item.daysUntilInUseExpiry ?? 0) <= 7 ? Colors.amber : const Color(0xFF2563EB)),
|
||||
),
|
||||
minHeight: 4,
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
),
|
||||
],
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// 未开封一键打卡按钮
|
||||
if (!item.isOpened) ...[
|
||||
const SizedBox(height: 10),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: const Color(0xFF2563EB),
|
||||
side: const BorderSide(color: Color(0xFF93C5FD)),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
),
|
||||
onPressed: () => _openMedicineCard(item),
|
||||
icon: const Icon(Icons.check_circle_outline, size: 16),
|
||||
label: const Text('点击打卡开封 (开启保质倒计时)'),
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
// 危险警告提醒条 (超期或过期)
|
||||
if (isDanger) ...[
|
||||
const SizedBox(height: 8),
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFFEF2F2),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.warning_amber_rounded, size: 16, color: Colors.red),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(
|
||||
child: Text(
|
||||
item.healthStatus == MedicineHealthStatus.overdueInUse
|
||||
? '已超出开封后推荐使用期限,易滋生细菌/失效,建议丢弃更换。'
|
||||
: '已超出出厂有效期,严禁继续使用!',
|
||||
style: const TextStyle(color: Colors.red, fontSize: 11, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
// 适应症备注
|
||||
if (item.notes.isNotEmpty) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'备忘: ${item.notes}',
|
||||
style: const TextStyle(fontSize: 11, color: Colors.black54),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTagChip({
|
||||
required IconData icon,
|
||||
required String text,
|
||||
required Color color,
|
||||
}) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: 0.08),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 12, color: color),
|
||||
const SizedBox(width: 3),
|
||||
Text(
|
||||
text,
|
||||
style: TextStyle(color: color, fontSize: 11, fontWeight: FontWeight.w500),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,589 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import '../models/medicine_item.dart';
|
||||
import '../services/medicine_parser_service.dart';
|
||||
|
||||
class MedicineEditDialog extends StatefulWidget {
|
||||
final MedicineItem? initialItem;
|
||||
final ScannedMedicineInfo? scannedInfo;
|
||||
|
||||
const MedicineEditDialog({
|
||||
super.key,
|
||||
this.initialItem,
|
||||
this.scannedInfo,
|
||||
});
|
||||
|
||||
@override
|
||||
State<MedicineEditDialog> createState() => _MedicineEditDialogState();
|
||||
}
|
||||
|
||||
class _MedicineEditDialogState extends State<MedicineEditDialog> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
|
||||
late TextEditingController _nameController;
|
||||
late TextEditingController _specController;
|
||||
late TextEditingController _barcodeController;
|
||||
late TextEditingController _batchNumberController;
|
||||
late TextEditingController _shelfLifeDaysController;
|
||||
late TextEditingController _notesController;
|
||||
|
||||
late MedicineCategory _category;
|
||||
late String _storageLocation;
|
||||
late String _targetUser;
|
||||
late DateTime _expiryDate;
|
||||
DateTime? _productionDate;
|
||||
late bool _isOpened;
|
||||
DateTime? _openedAt;
|
||||
|
||||
final List<String> _commonLocations = [
|
||||
'常温药箱',
|
||||
'冰箱冷藏 (2-8℃)',
|
||||
'随身急救包',
|
||||
'卧室床头',
|
||||
];
|
||||
|
||||
final List<String> _commonUsers = [
|
||||
'宝宝',
|
||||
'全家',
|
||||
'爸爸',
|
||||
'妈妈',
|
||||
'老人',
|
||||
];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final init = widget.initialItem;
|
||||
final scan = widget.scannedInfo;
|
||||
|
||||
final now = DateTime.now();
|
||||
|
||||
_nameController = TextEditingController(
|
||||
text: init?.name ?? scan?.name ?? '',
|
||||
);
|
||||
_specController = TextEditingController(
|
||||
text: init?.spec ?? scan?.spec ?? '',
|
||||
);
|
||||
_barcodeController = TextEditingController(
|
||||
text: init?.barcode ?? scan?.barcode ?? '',
|
||||
);
|
||||
_batchNumberController = TextEditingController(
|
||||
text: init?.batchNumber ?? scan?.batchNumber ?? '',
|
||||
);
|
||||
|
||||
_category = init?.category ?? scan?.category ?? MedicineCategory.oralLiquid;
|
||||
_storageLocation = init?.storageLocation ?? scan?.storageLocation ?? '常温药箱';
|
||||
_targetUser = init?.targetUser ?? scan?.targetUser ?? '宝宝';
|
||||
|
||||
_expiryDate = init?.expiryDate ??
|
||||
scan?.expiryDate ??
|
||||
DateTime(now.year + 2, now.month, now.day);
|
||||
_productionDate = init?.productionDate ?? scan?.productionDate;
|
||||
|
||||
final defaultShelfLife = _category.defaultShelfLifeDaysAfterOpening;
|
||||
final initShelfLife = init?.shelfLifeDaysAfterOpening ??
|
||||
scan?.shelfLifeDaysAfterOpening ??
|
||||
defaultShelfLife;
|
||||
_shelfLifeDaysController = TextEditingController(
|
||||
text: initShelfLife != null ? initShelfLife.toString() : '',
|
||||
);
|
||||
|
||||
_isOpened = init?.isOpened ?? false;
|
||||
_openedAt = init?.openedAt ?? (_isOpened ? now : null);
|
||||
|
||||
_notesController = TextEditingController(
|
||||
text: init?.notes ?? scan?.notes ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nameController.dispose();
|
||||
_specController.dispose();
|
||||
_barcodeController.dispose();
|
||||
_batchNumberController.dispose();
|
||||
_shelfLifeDaysController.dispose();
|
||||
_notesController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onCategoryChanged(MedicineCategory newCat) {
|
||||
setState(() {
|
||||
_category = newCat;
|
||||
final defaultDays = newCat.defaultShelfLifeDaysAfterOpening;
|
||||
if (defaultDays != null && _shelfLifeDaysController.text.isEmpty) {
|
||||
_shelfLifeDaysController.text = defaultDays.toString();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _pickExpiryDate() async {
|
||||
final picked = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: _expiryDate,
|
||||
firstDate: DateTime(2020),
|
||||
lastDate: DateTime(2035),
|
||||
helpText: '选择药品出厂有效期至',
|
||||
);
|
||||
if (picked != null) {
|
||||
setState(() => _expiryDate = picked);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _pickProductionDate() async {
|
||||
final picked = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: _productionDate ?? DateTime.now(),
|
||||
firstDate: DateTime(2020),
|
||||
lastDate: DateTime.now(),
|
||||
helpText: '选择药品生产日期 (选填)',
|
||||
);
|
||||
if (picked != null) {
|
||||
setState(() => _productionDate = picked);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _pickOpenedDate() async {
|
||||
final picked = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: _openedAt ?? DateTime.now(),
|
||||
firstDate: DateTime(2020),
|
||||
lastDate: DateTime.now(),
|
||||
helpText: '选择开封日期',
|
||||
);
|
||||
if (picked != null) {
|
||||
setState(() => _openedAt = picked);
|
||||
}
|
||||
}
|
||||
|
||||
void _save() {
|
||||
if (!_formKey.currentState!.validate()) return;
|
||||
|
||||
final nowUtc = DateTime.now().toUtc();
|
||||
final shelfLife = int.tryParse(_shelfLifeDaysController.text.trim());
|
||||
|
||||
final item = MedicineItem(
|
||||
id: widget.initialItem?.id ?? const Uuid().v4(),
|
||||
name: _nameController.text.trim(),
|
||||
category: _category,
|
||||
spec: _specController.text.trim(),
|
||||
storageLocation: _storageLocation,
|
||||
targetUser: _targetUser,
|
||||
barcode: _barcodeController.text.trim().isNotEmpty ? _barcodeController.text.trim() : null,
|
||||
batchNumber: _batchNumberController.text.trim().isNotEmpty ? _batchNumberController.text.trim() : null,
|
||||
productionDate: _productionDate,
|
||||
expiryDate: _expiryDate,
|
||||
shelfLifeDaysAfterOpening: shelfLife,
|
||||
isOpened: _isOpened,
|
||||
openedAt: _isOpened ? (_openedAt ?? DateTime.now()) : null,
|
||||
openedByDevice: widget.initialItem?.openedByDevice,
|
||||
notes: _notesController.text.trim(),
|
||||
isDeleted: false,
|
||||
updatedAt: nowUtc,
|
||||
);
|
||||
|
||||
Navigator.of(context).pop(item);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isEditing = widget.initialItem != null;
|
||||
final dateFormat = DateFormat('yyyy年MM月dd日');
|
||||
|
||||
return Dialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
|
||||
insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
|
||||
child: Container(
|
||||
constraints: const BoxConstraints(maxWidth: 520, maxHeight: 720),
|
||||
child: Column(
|
||||
children: [
|
||||
// 标题栏
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
|
||||
decoration: const BoxDecoration(
|
||||
color: Color(0xFF2563EB),
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
isEditing ? Icons.edit_note : Icons.add_circle_outline,
|
||||
color: Colors.white,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Text(
|
||||
isEditing ? '编辑家庭药品' : '录入新药品',
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close, color: Colors.white70),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// 表单内容
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// 1. 药品名称
|
||||
TextFormField(
|
||||
controller: _nameController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '药品名称 *',
|
||||
hintText: '如 美林 (布洛芬混悬液)',
|
||||
prefixIcon: Icon(Icons.medication),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (v) => (v == null || v.trim().isEmpty) ? '请输入药品名称' : null,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 2. 剂型类别
|
||||
const Text(
|
||||
'剂型类别 (自动联动开封保质天数):',
|
||||
style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: Colors.black87),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 6,
|
||||
children: MedicineCategory.values.map((cat) {
|
||||
final selected = _category == cat;
|
||||
return ChoiceChip(
|
||||
label: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(cat.icon, size: 16, color: selected ? Colors.white : Colors.black87),
|
||||
const SizedBox(width: 4),
|
||||
Text(cat.label),
|
||||
],
|
||||
),
|
||||
selected: selected,
|
||||
selectedColor: const Color(0xFF2563EB),
|
||||
labelStyle: TextStyle(
|
||||
color: selected ? Colors.white : Colors.black87,
|
||||
fontSize: 12,
|
||||
),
|
||||
onSelected: (val) {
|
||||
if (val) _onCategoryChanged(cat);
|
||||
},
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 3. 规格与条码
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _specController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '规格/容量',
|
||||
hintText: '如 100ml / 60喷',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _barcodeController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '条码/追溯码',
|
||||
hintText: '69码或20位码',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 4. 存放位置
|
||||
const Text(
|
||||
'存放位置:',
|
||||
style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: Colors.black87),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
children: _commonLocations.map((loc) {
|
||||
final selected = _storageLocation == loc;
|
||||
return ChoiceChip(
|
||||
label: Text(loc),
|
||||
selected: selected,
|
||||
selectedColor: const Color(0xFF059669),
|
||||
labelStyle: TextStyle(
|
||||
color: selected ? Colors.white : Colors.black87,
|
||||
fontSize: 12,
|
||||
),
|
||||
onSelected: (val) {
|
||||
if (val) setState(() => _storageLocation = loc);
|
||||
},
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 5. 适用成员
|
||||
const Text(
|
||||
'适用成员:',
|
||||
style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: Colors.black87),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
children: _commonUsers.map((user) {
|
||||
final selected = _targetUser == user;
|
||||
return ChoiceChip(
|
||||
label: Text(user),
|
||||
selected: selected,
|
||||
selectedColor: const Color(0xFFD97706),
|
||||
labelStyle: TextStyle(
|
||||
color: selected ? Colors.white : Colors.black87,
|
||||
fontSize: 12,
|
||||
),
|
||||
onSelected: (val) {
|
||||
if (val) setState(() => _targetUser = user);
|
||||
},
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
const Divider(),
|
||||
const SizedBox(height: 10),
|
||||
|
||||
// 6. 出厂有效期至 (核心)
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'出厂有效期至 *',
|
||||
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
InkWell(
|
||||
onTap: _pickExpiryDate,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: Colors.grey.shade400),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.event, color: Color(0xFF2563EB), size: 18),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
dateFormat.format(_expiryDate),
|
||||
style: const TextStyle(fontWeight: FontWeight.w600),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'生产日期 (选填)',
|
||||
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
InkWell(
|
||||
onTap: _pickProductionDate,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: Colors.grey.shade400),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.calendar_today_outlined, size: 16, color: Colors.grey),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
_productionDate != null
|
||||
? dateFormat.format(_productionDate!)
|
||||
: '点击选填',
|
||||
style: TextStyle(
|
||||
color: _productionDate != null ? Colors.black87 : Colors.grey,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 7. 生产批号与开封后保质期
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _batchNumberController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '生产批号 (选填)',
|
||||
hintText: '如 LOT A123',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _shelfLifeDaysController,
|
||||
keyboardType: TextInputType.number,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '开封后可用天数',
|
||||
hintText: '如 28 或 60',
|
||||
suffixText: '天',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 8. 是否已开封打卡
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: _isOpened ? const Color(0xFFEFF6FF) : const Color(0xFFF8FAFC),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(
|
||||
color: _isOpened ? const Color(0xFF93C5FD) : Colors.grey.shade300,
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
_isOpened ? Icons.lock_open : Icons.lock_outline,
|
||||
color: _isOpened ? const Color(0xFF2563EB) : Colors.grey,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
const Text(
|
||||
'当前是否已开封使用:',
|
||||
style: TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
const Spacer(),
|
||||
Switch(
|
||||
value: _isOpened,
|
||||
activeTrackColor: const Color(0xFF2563EB),
|
||||
onChanged: (val) {
|
||||
setState(() {
|
||||
_isOpened = val;
|
||||
if (val && _openedAt == null) {
|
||||
_openedAt = DateTime.now();
|
||||
}
|
||||
});
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
if (_isOpened) ...[
|
||||
const Divider(),
|
||||
Row(
|
||||
children: [
|
||||
const Text('开封日期:', style: TextStyle(fontSize: 13)),
|
||||
const Spacer(),
|
||||
TextButton.icon(
|
||||
onPressed: _pickOpenedDate,
|
||||
icon: const Icon(Icons.edit_calendar, size: 16),
|
||||
label: Text(
|
||||
_openedAt != null ? dateFormat.format(_openedAt!) : '今天',
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 9. 用药备注
|
||||
TextFormField(
|
||||
controller: _notesController,
|
||||
maxLines: 2,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '适应症/用药备忘',
|
||||
hintText: '如:38.5℃以上发热使用,间隔4~6小时',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// 底部操作按钮
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey.shade50,
|
||||
border: Border(top: BorderSide(color: Colors.grey.shade200)),
|
||||
borderRadius: const BorderRadius.vertical(bottom: Radius.circular(20)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('取消', style: TextStyle(color: Colors.grey)),
|
||||
),
|
||||
const Spacer(),
|
||||
ElevatedButton.icon(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: const Color(0xFF2563EB),
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
|
||||
),
|
||||
onPressed: _save,
|
||||
icon: const Icon(Icons.check),
|
||||
label: Text(isEditing ? '保存修改' : '确认录入'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:mobile_scanner/mobile_scanner.dart';
|
||||
import '../services/medicine_parser_service.dart';
|
||||
|
||||
class MedicineScanScreen extends StatefulWidget {
|
||||
const MedicineScanScreen({super.key});
|
||||
|
||||
@override
|
||||
State<MedicineScanScreen> createState() => _MedicineScanScreenState();
|
||||
}
|
||||
|
||||
class _MedicineScanScreenState extends State<MedicineScanScreen> {
|
||||
final MobileScannerController _controller = MobileScannerController(
|
||||
detectionSpeed: DetectionSpeed.normal,
|
||||
facing: CameraFacing.back,
|
||||
torchEnabled: false,
|
||||
);
|
||||
|
||||
bool _isProcessing = false;
|
||||
bool _isTorchOn = false;
|
||||
final TextEditingController _manualInputController = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
_manualInputController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _handleBarcodeDetected(String rawCode) async {
|
||||
if (_isProcessing) return;
|
||||
setState(() => _isProcessing = true);
|
||||
|
||||
try {
|
||||
final info = await MedicineParserService.parseRawBarcode(rawCode);
|
||||
if (mounted) {
|
||||
Navigator.of(context).pop(info);
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('解析条码失败: $e')),
|
||||
);
|
||||
setState(() => _isProcessing = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _showManualInputDialog() {
|
||||
_manualInputController.clear();
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('手动输入条形码/追溯码'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'支持输入 13 位商品条形码 (如 69...) 或 20 位中国药品电子监管码:',
|
||||
style: TextStyle(fontSize: 13, color: Colors.black54),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _manualInputController,
|
||||
keyboardType: TextInputType.number,
|
||||
autofocus: true,
|
||||
decoration: const InputDecoration(
|
||||
border: OutlineInputBorder(),
|
||||
hintText: '如 6921147600010 或 8188...',
|
||||
labelText: '条码编号',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
final text = _manualInputController.text.trim();
|
||||
if (text.isNotEmpty) {
|
||||
Navigator.pop(ctx);
|
||||
_handleBarcodeDetected(text);
|
||||
}
|
||||
},
|
||||
child: const Text('识别'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.black,
|
||||
appBar: AppBar(
|
||||
title: const Text('扫描药品条码/追溯码'),
|
||||
backgroundColor: Colors.black87,
|
||||
foregroundColor: Colors.white,
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
_isTorchOn ? Icons.flash_on : Icons.flash_off,
|
||||
color: _isTorchOn ? Colors.amber : Colors.white,
|
||||
),
|
||||
tooltip: '开关手电筒',
|
||||
onPressed: () {
|
||||
setState(() => _isTorchOn = !_isTorchOn);
|
||||
_controller.toggleTorch();
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.keyboard_outlined),
|
||||
tooltip: '手动输入条码',
|
||||
onPressed: _showManualInputDialog,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
MobileScanner(
|
||||
controller: _controller,
|
||||
onDetect: (capture) {
|
||||
final barcodes = capture.barcodes;
|
||||
for (final barcode in barcodes) {
|
||||
final val = barcode.rawValue;
|
||||
if (val != null && val.isNotEmpty) {
|
||||
_handleBarcodeDetected(val);
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
errorBuilder: (context, error) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.camera_alt_outlined, color: Colors.white54, size: 64),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'无法打开摄像头: ${error.errorDetails?.message ?? "无权限或设备不支持"}',
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: Colors.white70),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
ElevatedButton.icon(
|
||||
icon: const Icon(Icons.edit_note),
|
||||
label: const Text('手动输入条形码'),
|
||||
onPressed: _showManualInputDialog,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
// 扫描取景框覆盖层
|
||||
IgnorePointer(
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: Colors.white24, width: 1),
|
||||
),
|
||||
child: Stack(
|
||||
children: [
|
||||
Center(
|
||||
child: Container(
|
||||
width: 280,
|
||||
height: 200,
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: const Color(0xFF2563EB), width: 2.5),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// 底部操作引导提示
|
||||
Positioned(
|
||||
bottom: 40,
|
||||
left: 20,
|
||||
right: 20,
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.7),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: const Text(
|
||||
'请将药盒上的【20位追溯码】或【条形码】对准框内',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: Colors.white, fontSize: 13),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextButton.icon(
|
||||
onPressed: _showManualInputDialog,
|
||||
icon: const Icon(Icons.edit, color: Colors.white70, size: 16),
|
||||
label: const Text(
|
||||
'扫不出来?点击手动输入',
|
||||
style: TextStyle(color: Colors.white70, fontSize: 13),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
if (_isProcessing)
|
||||
Container(
|
||||
color: Colors.black54,
|
||||
child: const Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
CircularProgressIndicator(color: Colors.white),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
'正在查询药品信息...',
|
||||
style: TextStyle(color: Colors.white, fontSize: 14),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import '../models/medicine_item.dart';
|
||||
|
||||
class ScannedMedicineInfo {
|
||||
final String? name;
|
||||
final MedicineCategory? category;
|
||||
final String? spec;
|
||||
final String? storageLocation;
|
||||
final String? targetUser;
|
||||
final String? barcode;
|
||||
final String? batchNumber;
|
||||
final DateTime? productionDate;
|
||||
final DateTime? expiryDate;
|
||||
final int? shelfLifeDaysAfterOpening;
|
||||
final String? notes;
|
||||
final String parseSource; // 'traceability_code', 'gs1_datamatrix', 'ean13_catalog', 'raw'
|
||||
|
||||
ScannedMedicineInfo({
|
||||
this.name,
|
||||
this.category,
|
||||
this.spec,
|
||||
this.storageLocation,
|
||||
this.targetUser,
|
||||
this.barcode,
|
||||
this.batchNumber,
|
||||
this.productionDate,
|
||||
this.expiryDate,
|
||||
this.shelfLifeDaysAfterOpening,
|
||||
this.notes,
|
||||
required this.parseSource,
|
||||
});
|
||||
}
|
||||
|
||||
class MedicineParserService {
|
||||
/// 内置常见家庭药品知识库 (按条形码前缀或全码匹配)
|
||||
static final Map<String, Map<String, dynamic>> _knownMedicineCatalog = {
|
||||
// 辅舒酮 (丙酸氟替卡松)
|
||||
'6921147600010': {
|
||||
'name': '辅舒酮 (丙酸氟替卡松吸入气雾剂)',
|
||||
'category': MedicineCategory.inhaler,
|
||||
'spec': '50μg/喷 × 60喷',
|
||||
'storageLocation': '常温药箱',
|
||||
'targetUser': '宝宝',
|
||||
'shelfLifeDays': 60,
|
||||
'notes': '拆开铝箔袋后建议 60 天内用完,每次吸入后温水漱口',
|
||||
},
|
||||
// 万托林 (硫酸沙丁胺醇)
|
||||
'6921147600027': {
|
||||
'name': '万托林 (硫酸沙丁胺醇吸入气雾剂)',
|
||||
'category': MedicineCategory.inhaler,
|
||||
'spec': '100μg/喷 × 200喷',
|
||||
'storageLocation': '随身急救包',
|
||||
'targetUser': '全家',
|
||||
'shelfLifeDays': 180,
|
||||
'notes': '支气管舒张剂,急性发作应急吸入',
|
||||
},
|
||||
// 美林 (布洛芬混悬液 100ml)
|
||||
'6925567800018': {
|
||||
'name': '美林 (布洛芬混悬液)',
|
||||
'category': MedicineCategory.oralLiquid,
|
||||
'spec': '100ml:2g',
|
||||
'storageLocation': '常温药箱 (避光)',
|
||||
'targetUser': '宝宝',
|
||||
'shelfLifeDays': 60,
|
||||
'notes': '高热38.5℃以上使用,间隔4~6小时,开封后建议2个月内用完',
|
||||
},
|
||||
// 泰诺林 (对乙酰氨基酚混悬滴剂 15ml)
|
||||
'6925567800025': {
|
||||
'name': '泰诺林 (对乙酰氨基酚混悬滴剂)',
|
||||
'category': MedicineCategory.oralLiquid,
|
||||
'spec': '15ml:1.5g (含滴管)',
|
||||
'storageLocation': '常温药箱 (避光)',
|
||||
'targetUser': '宝宝',
|
||||
'shelfLifeDays': 60,
|
||||
'notes': '婴幼儿退热滴剂,开封后冷暗处保存,建议2个月内用完',
|
||||
},
|
||||
// 托百士 (妥布霉素滴眼液)
|
||||
'6936577800015': {
|
||||
'name': '托百士 (妥布霉素滴眼液)',
|
||||
'category': MedicineCategory.eyeDrops,
|
||||
'spec': '5ml:15mg',
|
||||
'storageLocation': '常温药箱',
|
||||
'targetUser': '宝宝',
|
||||
'shelfLifeDays': 28,
|
||||
'notes': '抗生素滴眼液,开封后4周内必须丢弃!',
|
||||
},
|
||||
// 左氧氟沙星滴眼液 (可乐必妥)
|
||||
'6914567800012': {
|
||||
'name': '可乐必妥 (左氧氟沙星滴眼液)',
|
||||
'category': MedicineCategory.eyeDrops,
|
||||
'spec': '5ml:24.45mg',
|
||||
'storageLocation': '常温药箱 (遮光)',
|
||||
'targetUser': '全家',
|
||||
'shelfLifeDays': 28,
|
||||
'notes': '开封后请于4周内使用,避光密封',
|
||||
},
|
||||
// 百多邦 (莫匹罗星软膏)
|
||||
'6901234560019': {
|
||||
'name': '百多邦 (莫匹罗星软膏)',
|
||||
'category': MedicineCategory.topical,
|
||||
'spec': '5g:0.1g',
|
||||
'storageLocation': '常温药箱',
|
||||
'targetUser': '全家',
|
||||
'shelfLifeDays': 90,
|
||||
'notes': '外用抗生素软膏,涂抹患处',
|
||||
},
|
||||
// 地奈德乳膏
|
||||
'6901234560026': {
|
||||
'name': '地奈德乳膏',
|
||||
'category': MedicineCategory.topical,
|
||||
'spec': '15g:7.5mg',
|
||||
'storageLocation': '常温药箱',
|
||||
'targetUser': '宝宝',
|
||||
'shelfLifeDays': 90,
|
||||
'notes': '弱效外用激素,湿疹发作遵医嘱薄涂',
|
||||
},
|
||||
// 易坦静 (氨溴特罗口服溶液)
|
||||
'6921234560033': {
|
||||
'name': '易坦静 (氨溴特罗口服溶液)',
|
||||
'category': MedicineCategory.oralLiquid,
|
||||
'spec': '100ml',
|
||||
'storageLocation': '常温药箱',
|
||||
'targetUser': '宝宝',
|
||||
'shelfLifeDays': 60,
|
||||
'notes': '化痰止咳口服液,开封后避光遮光保存',
|
||||
},
|
||||
// 重组人干扰素α2b凝胶
|
||||
'6929999880011': {
|
||||
'name': '重组人干扰素α2b凝胶',
|
||||
'category': MedicineCategory.topical,
|
||||
'spec': '5g:50万IU',
|
||||
'storageLocation': '冰箱冷藏 (2-8℃)',
|
||||
'targetUser': '全家',
|
||||
'shelfLifeDays': 30,
|
||||
'notes': '⚠️ 必须放冰箱冷藏 (2~8°C) 保存!严禁冷冻',
|
||||
},
|
||||
};
|
||||
|
||||
/// 核心识别入口:解析任何扫描到的字符串
|
||||
static Future<ScannedMedicineInfo> parseRawBarcode(String rawCode) async {
|
||||
final code = rawCode.trim();
|
||||
|
||||
// 1. 若是纯 13 位数字,必定为普通商品条形码 (EAN-13)
|
||||
if (code.length == 13 && RegExp(r'^\d{13}$').hasMatch(code)) {
|
||||
if (_knownMedicineCatalog.containsKey(code)) {
|
||||
final cat = _knownMedicineCatalog[code]!;
|
||||
return ScannedMedicineInfo(
|
||||
barcode: code,
|
||||
name: cat['name'] as String,
|
||||
category: cat['category'] as MedicineCategory,
|
||||
spec: cat['spec'] as String,
|
||||
storageLocation: cat['storageLocation'] as String,
|
||||
targetUser: cat['targetUser'] as String,
|
||||
shelfLifeDaysAfterOpening: cat['shelfLifeDays'] as int,
|
||||
notes: cat['notes'] as String,
|
||||
parseSource: 'ean13_catalog',
|
||||
);
|
||||
}
|
||||
return ScannedMedicineInfo(
|
||||
barcode: code,
|
||||
name: '',
|
||||
category: MedicineCategory.other,
|
||||
parseSource: 'raw',
|
||||
storageLocation: '常温药箱',
|
||||
targetUser: '全家',
|
||||
);
|
||||
}
|
||||
|
||||
// 2. 若是 20 位纯数字,为中国药品追溯码 (电子监管码)
|
||||
if (_isTraceabilityCode(code)) {
|
||||
final traceInfo = await _queryTraceabilityPlatform(code);
|
||||
if (traceInfo != null) {
|
||||
return traceInfo;
|
||||
}
|
||||
return ScannedMedicineInfo(
|
||||
barcode: code,
|
||||
name: '追溯码药品 ($code)',
|
||||
category: MedicineCategory.other,
|
||||
parseSource: 'traceability_code',
|
||||
notes: '由中国药品电子监管码录入',
|
||||
);
|
||||
}
|
||||
|
||||
// 3. 尝试解析 GS1 DataMatrix (包含 (17)有效期, (10)批号, (11)生产日期等)
|
||||
final gs1Info = _parseGs1(code);
|
||||
if (gs1Info != null) {
|
||||
return gs1Info;
|
||||
}
|
||||
|
||||
// 4. 无法自动查到库的普通条形码
|
||||
return ScannedMedicineInfo(
|
||||
barcode: code,
|
||||
name: '',
|
||||
category: MedicineCategory.other,
|
||||
parseSource: 'raw',
|
||||
storageLocation: '常温药箱',
|
||||
targetUser: '全家',
|
||||
);
|
||||
}
|
||||
|
||||
/// 判断是否为中国 20 位药品追溯码
|
||||
static bool _isTraceabilityCode(String code) {
|
||||
if (code.length != 20) return false;
|
||||
return RegExp(r'^\d{20}$').hasMatch(code);
|
||||
}
|
||||
|
||||
/// GS1 医疗二维码标准解析
|
||||
static ScannedMedicineInfo? _parseGs1(String code) {
|
||||
// 匹配 (17)YYMMDD 有效期
|
||||
DateTime? expDate;
|
||||
final expRegex = RegExp(r'(?:\(17\)|\x1d17|^17)(\d{2})(\d{2})(\d{2})');
|
||||
final expMatch = expRegex.firstMatch(code);
|
||||
if (expMatch != null) {
|
||||
final yy = int.parse(expMatch.group(1)!);
|
||||
final mm = int.parse(expMatch.group(2)!);
|
||||
var dd = int.parse(expMatch.group(3)!);
|
||||
if (dd == 0) dd = 28; // GS1 规则:00 表示月末
|
||||
final fullYear = 2000 + yy;
|
||||
expDate = DateTime(fullYear, mm, dd);
|
||||
}
|
||||
|
||||
// 匹配 (11)YYMMDD 生产日期
|
||||
DateTime? mfgDate;
|
||||
final mfgRegex = RegExp(r'(?:\(11\)|\x1d11|^11)(\d{2})(\d{2})(\d{2})');
|
||||
final mfgMatch = mfgRegex.firstMatch(code);
|
||||
if (mfgMatch != null) {
|
||||
final yy = int.parse(mfgMatch.group(1)!);
|
||||
final mm = int.parse(mfgMatch.group(2)!);
|
||||
var dd = int.parse(mfgMatch.group(3)!);
|
||||
if (dd == 0) dd = 1;
|
||||
final fullYear = 2000 + yy;
|
||||
mfgDate = DateTime(fullYear, mm, dd);
|
||||
}
|
||||
|
||||
// 匹配 (10)LOT 生产批号
|
||||
String? batch;
|
||||
final batchRegex = RegExp(r'(?:\(10\)|\x1d10|^10)([A-Za-z0-9]+?)(?=\(|\x1d|$)');
|
||||
final batchMatch = batchRegex.firstMatch(code);
|
||||
if (batchMatch != null) {
|
||||
batch = batchMatch.group(1);
|
||||
}
|
||||
|
||||
// 匹配 (01)GTIN 商品标识码
|
||||
String? gtin;
|
||||
final gtinRegex = RegExp(r'(?:\(01\)|\x1d01|^01)(\d{14})');
|
||||
final gtinMatch = gtinRegex.firstMatch(code);
|
||||
if (gtinMatch != null) {
|
||||
gtin = gtinMatch.group(1);
|
||||
}
|
||||
|
||||
if (expDate != null || mfgDate != null || batch != null || gtin != null) {
|
||||
String? matchedName;
|
||||
MedicineCategory? matchedCat;
|
||||
String? matchedSpec;
|
||||
int? matchedShelfLife;
|
||||
|
||||
if (gtin != null) {
|
||||
final ean13 = gtin.startsWith('0') ? gtin.substring(1) : gtin;
|
||||
if (_knownMedicineCatalog.containsKey(ean13)) {
|
||||
final info = _knownMedicineCatalog[ean13]!;
|
||||
matchedName = info['name'] as String?;
|
||||
matchedCat = info['category'] as MedicineCategory?;
|
||||
matchedSpec = info['spec'] as String?;
|
||||
matchedShelfLife = info['shelfLifeDays'] as int?;
|
||||
}
|
||||
}
|
||||
|
||||
return ScannedMedicineInfo(
|
||||
barcode: code,
|
||||
name: matchedName,
|
||||
category: matchedCat,
|
||||
spec: matchedSpec,
|
||||
batchNumber: batch,
|
||||
productionDate: mfgDate,
|
||||
expiryDate: expDate,
|
||||
shelfLifeDaysAfterOpening: matchedShelfLife,
|
||||
parseSource: 'gs1_datamatrix',
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// 联网/本地解析药品追溯码
|
||||
static Future<ScannedMedicineInfo?> _queryTraceabilityPlatform(String code) async {
|
||||
try {
|
||||
// 通过公开网关或接口模拟查询(超时设置 2.5 秒,保证用户界面极速无感知)
|
||||
final url = Uri.parse('http://127.0.0.1:8090/api/v1/medicine/lookup?code=$code');
|
||||
final res = await http.get(url).timeout(const Duration(milliseconds: 2500));
|
||||
if (res.statusCode == 200) {
|
||||
final data = jsonDecode(utf8.decode(res.bodyBytes)) as Map<String, dynamic>;
|
||||
if (data['status'] == 'ok' && data['data'] != null) {
|
||||
final item = data['data'] as Map<String, dynamic>;
|
||||
return ScannedMedicineInfo(
|
||||
barcode: code,
|
||||
name: item['name'] as String?,
|
||||
spec: item['spec'] as String?,
|
||||
batchNumber: item['batch_number'] as String?,
|
||||
productionDate: item['production_date'] != null
|
||||
? DateTime.parse(item['production_date'] as String)
|
||||
: null,
|
||||
expiryDate: item['expiry_date'] != null
|
||||
? DateTime.parse(item['expiry_date'] as String)
|
||||
: null,
|
||||
notes: item['notes'] as String?,
|
||||
parseSource: 'traceability_code',
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (_) {
|
||||
// 离线环境平滑降级,不阻塞用户
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,18 @@
|
||||
import 'dart:convert';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import '../models/bottle.dart';
|
||||
import '../models/canister.dart';
|
||||
import '../models/dose_record.dart';
|
||||
import '../models/app_settings.dart';
|
||||
import '../models/medicine_item.dart';
|
||||
|
||||
class StorageService {
|
||||
static const String _keySettings = 'aerotrack_settings';
|
||||
static const String _keyCanisters = 'aerotrack_canisters';
|
||||
static const String _keyRecords = 'aerotrack_records';
|
||||
static const String _keyBottles = 'aerotrack_bottles';
|
||||
static const String _keyMedicines = 'aerotrack_medicines';
|
||||
|
||||
final SharedPreferences _prefs;
|
||||
|
||||
@@ -130,6 +133,57 @@ class StorageService {
|
||||
await _prefs.setStringList(_keyRecords, list);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 家庭药箱初始默认药品播种
|
||||
if (!_prefs.containsKey(_keyMedicines)) {
|
||||
final nowUtc = DateTime.now().toUtc();
|
||||
final initialMedicines = [
|
||||
MedicineItem(
|
||||
id: 'med_flixotide_seed',
|
||||
name: '辅舒酮 (丙酸氟替卡松吸入气雾剂)',
|
||||
category: MedicineCategory.inhaler,
|
||||
spec: '50μg/喷 × 60喷',
|
||||
storageLocation: '常温药箱',
|
||||
targetUser: '宝宝',
|
||||
barcode: '6921147600010',
|
||||
expiryDate: DateTime.now().add(const Duration(days: 365 * 2)).toUtc(),
|
||||
shelfLifeDaysAfterOpening: 60,
|
||||
isOpened: true,
|
||||
openedAt: DateTime.now().subtract(const Duration(days: 10)).toUtc(),
|
||||
notes: '拆开铝箔袋后 60 天内用完,吸入后温水漱口',
|
||||
updatedAt: nowUtc,
|
||||
),
|
||||
MedicineItem(
|
||||
id: 'med_meilin_seed',
|
||||
name: '美林 (布洛芬混悬液)',
|
||||
category: MedicineCategory.oralLiquid,
|
||||
spec: '100ml:2g',
|
||||
storageLocation: '常温药箱 (避光)',
|
||||
targetUser: '宝宝',
|
||||
barcode: '6925567800018',
|
||||
expiryDate: DateTime.now().add(const Duration(days: 365 * 2)).toUtc(),
|
||||
shelfLifeDaysAfterOpening: 60,
|
||||
isOpened: false,
|
||||
notes: '发热 38.5℃ 以上使用,间隔 4~6 小时',
|
||||
updatedAt: nowUtc,
|
||||
),
|
||||
MedicineItem(
|
||||
id: 'med_tobramycin_seed',
|
||||
name: '托百士 (妥布霉素滴眼液)',
|
||||
category: MedicineCategory.eyeDrops,
|
||||
spec: '5ml:15mg',
|
||||
storageLocation: '常温药箱',
|
||||
targetUser: '宝宝',
|
||||
barcode: '6936577800015',
|
||||
expiryDate: DateTime.now().add(const Duration(days: 300)).toUtc(),
|
||||
shelfLifeDaysAfterOpening: 28,
|
||||
isOpened: false,
|
||||
notes: '抗生素眼药水,开封后 4 周必须丢弃',
|
||||
updatedAt: nowUtc,
|
||||
),
|
||||
];
|
||||
await saveMedicines(initialMedicines);
|
||||
}
|
||||
}
|
||||
|
||||
// ========== AppSettings ==========
|
||||
@@ -439,4 +493,73 @@ class StorageService {
|
||||
await recalculateCanisterDoses();
|
||||
}
|
||||
}
|
||||
|
||||
// ========== Family Medicine Cabinet (家庭药箱) ==========
|
||||
/// 获取未被软删除的有效药品列表(按有效期升序排序)
|
||||
List<MedicineItem> getMedicines({bool includeDeleted = false}) {
|
||||
final raw = _prefs.getStringList(_keyMedicines);
|
||||
if (raw == null) return [];
|
||||
try {
|
||||
final list = raw
|
||||
.map((item) => MedicineItem.fromJson(jsonDecode(item) as Map<String, dynamic>))
|
||||
.toList();
|
||||
final filtered = includeDeleted ? list : list.where((m) => !m.isDeleted).toList();
|
||||
filtered.sort((a, b) => a.expiryDate.compareTo(b.expiryDate));
|
||||
return filtered;
|
||||
} catch (_) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// 保存完整药品列表
|
||||
Future<void> saveMedicines(List<MedicineItem> medicines) async {
|
||||
final list = medicines.map((m) => jsonEncode(m.toJson())).toList();
|
||||
await _prefs.setStringList(_keyMedicines, list);
|
||||
}
|
||||
|
||||
/// 新增或更新单个药品
|
||||
Future<void> saveMedicine(MedicineItem medicine) async {
|
||||
final list = getMedicines(includeDeleted: true);
|
||||
final index = list.indexWhere((m) => m.id == medicine.id);
|
||||
if (index >= 0) {
|
||||
list[index] = medicine;
|
||||
} else {
|
||||
list.add(medicine);
|
||||
}
|
||||
await saveMedicines(list);
|
||||
}
|
||||
|
||||
/// 软删除药品(墓碑标记,支持多端同步自动下架)
|
||||
Future<void> deleteMedicine(String id) async {
|
||||
final list = getMedicines(includeDeleted: true);
|
||||
final nowUtc = DateTime.now().toUtc();
|
||||
for (int i = 0; i < list.length; i++) {
|
||||
if (list[i].id == id) {
|
||||
list[i] = list[i].copyWith(
|
||||
isDeleted: true,
|
||||
updatedAt: nowUtc,
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
await saveMedicines(list);
|
||||
}
|
||||
|
||||
/// 一键打卡开封
|
||||
Future<void> openMedicine(String id, {String? deviceName}) async {
|
||||
final list = getMedicines(includeDeleted: true);
|
||||
final nowUtc = DateTime.now().toUtc();
|
||||
for (int i = 0; i < list.length; i++) {
|
||||
if (list[i].id == id) {
|
||||
list[i] = list[i].copyWith(
|
||||
isOpened: true,
|
||||
openedAt: nowUtc,
|
||||
openedByDevice: deviceName ?? '本机',
|
||||
updatedAt: nowUtc,
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
await saveMedicines(list);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import 'package:uuid/uuid.dart';
|
||||
import '../models/bottle.dart';
|
||||
import '../models/canister.dart';
|
||||
import '../models/dose_record.dart';
|
||||
import '../models/medicine_item.dart';
|
||||
import 'storage_service.dart';
|
||||
|
||||
class SyncResult {
|
||||
@@ -120,6 +121,7 @@ class SyncService {
|
||||
final localRecords = storageService.getAllRecords(includeDeleted: true);
|
||||
final localBottles = storageService.getBottles();
|
||||
final localCanisters = storageService.getCanisters();
|
||||
final localMedicines = storageService.getMedicines(includeDeleted: true);
|
||||
final lastSync = await getLastSyncTime();
|
||||
|
||||
final body = json.encode({
|
||||
@@ -129,6 +131,7 @@ class SyncService {
|
||||
'records': localRecords.map((r) => r.toMap()).toList(),
|
||||
'bottles': localBottles.map((b) => b.toMap()).toList(),
|
||||
'canisters': localCanisters.map((c) => c.toMap()).toList(),
|
||||
'medicines': localMedicines.map((m) => m.toJson()).toList(),
|
||||
});
|
||||
|
||||
final syncUri = Uri.parse('$baseUrl/api/v1/sync');
|
||||
@@ -230,6 +233,32 @@ class SyncService {
|
||||
await storageService.saveCanisters(currentCanisters);
|
||||
}
|
||||
|
||||
// 3.5. 合并远端家庭药箱药品数据 (Medicines)
|
||||
final remoteMedicinesRaw = data['medicines'] as List<dynamic>? ?? [];
|
||||
if (remoteMedicinesRaw.isNotEmpty) {
|
||||
final remoteMedicines = remoteMedicinesRaw
|
||||
.map((item) => MedicineItem.fromJson(item as Map<String, dynamic>))
|
||||
.toList();
|
||||
|
||||
final localMedicines = storageService.getMedicines(includeDeleted: true);
|
||||
final localMedMap = {for (var m in localMedicines) m.id: m};
|
||||
|
||||
for (var rm in remoteMedicines) {
|
||||
final lm = localMedMap[rm.id];
|
||||
if (lm == null) {
|
||||
localMedicines.add(rm);
|
||||
} else {
|
||||
if (rm.updatedAt.isAfter(lm.updatedAt) || (rm.isDeleted && !lm.isDeleted)) {
|
||||
final idx = localMedicines.indexWhere((m) => m.id == rm.id);
|
||||
if (idx != -1) {
|
||||
localMedicines[idx] = rm;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
await storageService.saveMedicines(localMedicines);
|
||||
}
|
||||
|
||||
// 4. 核心终极核算:严格由 active 药瓶 UUID 与全量流水确定性重算各药瓶喷数与开封时间
|
||||
await storageService.recalculateCanisterDoses();
|
||||
|
||||
|
||||
@@ -7,10 +7,12 @@ import Foundation
|
||||
|
||||
import audioplayers_darwin
|
||||
import flutter_tts
|
||||
import mobile_scanner
|
||||
import shared_preferences_foundation
|
||||
|
||||
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
||||
AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin"))
|
||||
FlutterTtsPlugin.register(with: registry.registrar(forPlugin: "FlutterTtsPlugin"))
|
||||
MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin"))
|
||||
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
|
||||
}
|
||||
|
||||
@@ -312,6 +312,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.17.0"
|
||||
mobile_scanner:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: mobile_scanner
|
||||
sha256: "5a51ea79f0cf8293f616a5d08baae185b59b5e6bb24df01f2a63037ade0bade0"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.4.2"
|
||||
objective_c:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -40,6 +40,7 @@ dependencies:
|
||||
flutter_tts: ^4.2.5
|
||||
http: ^1.6.0
|
||||
audioplayers: ^6.7.1
|
||||
mobile_scanner: ^7.4.2
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
+215
-6
@@ -141,6 +141,29 @@ def init_db():
|
||||
INSERT INTO canisters (id, name, total_doses, remaining_doses, opened_at, is_enabled, puffs_per_session, inhalation_seconds, is_steroid, sort_order, note, updated_at)
|
||||
VALUES ('flixotide_primary', '辅舒酮 (丙酸氟替卡松)', 60, 60, '2020-01-01T00:00:00Z', 1, 2, 15, 1, 2, '糖皮质激素', ?)
|
||||
''', (now_iso,))
|
||||
|
||||
# 7. 家庭智能药箱全量管理表
|
||||
conn.execute('''
|
||||
CREATE TABLE IF NOT EXISTS medicines (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
category TEXT NOT NULL,
|
||||
spec TEXT,
|
||||
storage_location TEXT,
|
||||
target_user TEXT,
|
||||
barcode TEXT,
|
||||
batch_number TEXT,
|
||||
production_date TEXT,
|
||||
expiry_date TEXT NOT NULL,
|
||||
shelf_life_days_after_opening INTEGER,
|
||||
is_opened INTEGER DEFAULT 0,
|
||||
opened_at TEXT,
|
||||
opened_by_device TEXT,
|
||||
notes TEXT,
|
||||
is_deleted INTEGER DEFAULT 0,
|
||||
updated_at TEXT NOT NULL
|
||||
)
|
||||
''')
|
||||
conn.close()
|
||||
|
||||
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
|
||||
@@ -210,17 +233,25 @@ class SyncHandler(SimpleHTTPRequestHandler):
|
||||
})
|
||||
return
|
||||
|
||||
# 3. 监控看板
|
||||
# 3. 药品条码/追溯码信息查询接口
|
||||
if self.path.startswith('/api/v1/medicine/lookup'):
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
query = parse_qs(urlparse(self.path).query)
|
||||
code = query.get('code', [''])[0].strip()
|
||||
self._handle_medicine_lookup(code)
|
||||
return
|
||||
|
||||
# 4. 监控看板
|
||||
if self.path == '/dashboard' or self.path == '/dashboard/':
|
||||
self._render_dashboard()
|
||||
return
|
||||
|
||||
# 4. 静态 Web 端(Flutter Web 产物)
|
||||
# 5. 静态 Web 端(Flutter Web 产物)
|
||||
if os.path.isdir(WEB_DIR):
|
||||
super().do_GET()
|
||||
return
|
||||
|
||||
# 5. 若未编译 Flutter Web,则默认展示监控面板
|
||||
# 6. 若未编译 Flutter Web,则默认展示监控面板
|
||||
if self.path == '/' or self.path == '/index.html':
|
||||
self._render_dashboard()
|
||||
return
|
||||
@@ -283,10 +314,10 @@ class SyncHandler(SimpleHTTPRequestHandler):
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
''', (bid, cid, bname, seq, td, td, op_at, fin_at, is_act, dev, up_at))
|
||||
else:
|
||||
if up_at >= (existing_b['updated_at'] or ''):
|
||||
if up_at >= (existing_b['updated_at'] or '') or (not is_act and existing_b['is_active']):
|
||||
conn.execute('''
|
||||
UPDATE bottles SET
|
||||
finished_at = ?,
|
||||
finished_at = COALESCE(?, finished_at),
|
||||
is_active = ?,
|
||||
updated_at = ?
|
||||
WHERE id = ?
|
||||
@@ -370,6 +401,82 @@ class SyncHandler(SimpleHTTPRequestHandler):
|
||||
now_str
|
||||
))
|
||||
|
||||
# 4.5. 接收客户端家庭药箱数据 (Medicines)
|
||||
incoming_medicines = payload.get('medicines', [])
|
||||
for m in incoming_medicines:
|
||||
mid = m.get('id')
|
||||
if not mid:
|
||||
continue
|
||||
up_at = m.get('updatedAt', now_str)
|
||||
is_del = 1 if m.get('isDeleted', False) else 0
|
||||
is_open = 1 if m.get('isOpened', False) else 0
|
||||
|
||||
existing_m = conn.execute('SELECT * FROM medicines WHERE id = ?', (mid,)).fetchone()
|
||||
if not existing_m:
|
||||
conn.execute('''
|
||||
INSERT INTO medicines
|
||||
(id, name, category, spec, storage_location, target_user, barcode, batch_number, production_date, expiry_date, shelf_life_days_after_opening, is_opened, opened_at, opened_by_device, notes, is_deleted, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
''', (
|
||||
mid,
|
||||
m.get('name', '未命名药品'),
|
||||
m.get('category', 'other'),
|
||||
m.get('spec', ''),
|
||||
m.get('storageLocation', '常温药箱'),
|
||||
m.get('targetUser', '全家'),
|
||||
m.get('barcode'),
|
||||
m.get('batchNumber'),
|
||||
m.get('productionDate'),
|
||||
m.get('expiryDate', now_str),
|
||||
m.get('shelfLifeDaysAfterOpening'),
|
||||
is_open,
|
||||
m.get('openedAt'),
|
||||
m.get('openedByDevice'),
|
||||
m.get('notes', ''),
|
||||
is_del,
|
||||
up_at
|
||||
))
|
||||
else:
|
||||
if up_at >= (existing_m['updated_at'] or ''):
|
||||
conn.execute('''
|
||||
UPDATE medicines SET
|
||||
name = ?,
|
||||
category = ?,
|
||||
spec = ?,
|
||||
storage_location = ?,
|
||||
target_user = ?,
|
||||
barcode = ?,
|
||||
batch_number = ?,
|
||||
production_date = ?,
|
||||
expiry_date = ?,
|
||||
shelf_life_days_after_opening = ?,
|
||||
is_opened = ?,
|
||||
opened_at = ?,
|
||||
opened_by_device = ?,
|
||||
notes = ?,
|
||||
is_deleted = ?,
|
||||
updated_at = ?
|
||||
WHERE id = ?
|
||||
''', (
|
||||
m.get('name', existing_m['name']),
|
||||
m.get('category', existing_m['category']),
|
||||
m.get('spec', existing_m['spec']),
|
||||
m.get('storageLocation', existing_m['storage_location']),
|
||||
m.get('targetUser', existing_m['target_user']),
|
||||
m.get('barcode', existing_m['barcode']),
|
||||
m.get('batchNumber', existing_m['batch_number']),
|
||||
m.get('productionDate', existing_m['production_date']),
|
||||
m.get('expiryDate', existing_m['expiry_date']),
|
||||
m.get('shelfLifeDaysAfterOpening', existing_m['shelf_life_days_after_opening']),
|
||||
is_open,
|
||||
m.get('openedAt', existing_m['opened_at']),
|
||||
m.get('openedByDevice', existing_m['opened_by_device']),
|
||||
m.get('notes', existing_m['notes']),
|
||||
is_del,
|
||||
up_at,
|
||||
mid
|
||||
))
|
||||
|
||||
# 5. 依据物理药瓶实体 (Bottle) 与流水绑定关系,严格确定性重新核算余量
|
||||
for b in conn.execute('SELECT * FROM bottles').fetchall():
|
||||
bid = b['id']
|
||||
@@ -452,6 +559,28 @@ class SyncHandler(SimpleHTTPRequestHandler):
|
||||
'note': row['note']
|
||||
})
|
||||
|
||||
all_medicines = []
|
||||
for row in conn.execute('SELECT * FROM medicines ORDER BY expiry_date ASC').fetchall():
|
||||
all_medicines.append({
|
||||
'id': row['id'],
|
||||
'name': row['name'],
|
||||
'category': row['category'],
|
||||
'spec': row['spec'] or '',
|
||||
'storageLocation': row['storage_location'] or '常温药箱',
|
||||
'targetUser': row['target_user'] or '全家',
|
||||
'barcode': row['barcode'],
|
||||
'batchNumber': row['batch_number'],
|
||||
'productionDate': row['production_date'],
|
||||
'expiryDate': row['expiry_date'],
|
||||
'shelfLifeDaysAfterOpening': row['shelf_life_days_after_opening'],
|
||||
'isOpened': bool(row['is_opened']),
|
||||
'openedAt': row['opened_at'],
|
||||
'openedByDevice': row['opened_by_device'],
|
||||
'notes': row['notes'] or '',
|
||||
'isDeleted': bool(row['is_deleted']),
|
||||
'updatedAt': row['updated_at']
|
||||
})
|
||||
|
||||
conn.close()
|
||||
|
||||
self._send_json(200, {
|
||||
@@ -459,18 +588,90 @@ class SyncHandler(SimpleHTTPRequestHandler):
|
||||
'server_time': now_str,
|
||||
'bottles': all_bottles,
|
||||
'records': all_records,
|
||||
'canisters': all_canisters
|
||||
'canisters': all_canisters,
|
||||
'medicines': all_medicines
|
||||
})
|
||||
|
||||
def _handle_medicine_lookup(self, code):
|
||||
catalog = {
|
||||
'6921147600010': {'name': '辅舒酮 (丙酸氟替卡松吸入气雾剂)', 'spec': '50μg/喷 × 60喷', 'notes': '吸入用糖皮质激素'},
|
||||
'6921147600027': {'name': '万托林 (硫酸沙丁胺醇吸入气雾剂)', 'spec': '100μg/喷 × 200喷', 'notes': '支气管舒张剂'},
|
||||
'6925567800018': {'name': '美林 (布洛芬混悬液)', 'spec': '100ml:2g', 'notes': '退热抗炎镇痛'},
|
||||
'6925567800025': {'name': '泰诺林 (对乙酰氨基酚混悬滴剂)', 'spec': '15ml:1.5g', 'notes': '儿童退热滴剂'},
|
||||
'6936577800015': {'name': '托百士 (妥布霉素滴眼液)', 'spec': '5ml:15mg', 'notes': '抗生素眼药水,开封4周内使用'},
|
||||
'6914567800012': {'name': '可乐必妥 (左氧氟沙星滴眼液)', 'spec': '5ml:24.45mg', 'notes': '抗菌滴眼液'},
|
||||
'6901234560019': {'name': '百多邦 (莫匹罗星软膏)', 'spec': '5g:0.1g', 'notes': '外用抗菌软膏'},
|
||||
}
|
||||
if code in catalog:
|
||||
item = catalog[code]
|
||||
self._send_json(200, {
|
||||
'status': 'ok',
|
||||
'data': {
|
||||
'barcode': code,
|
||||
'name': item['name'],
|
||||
'spec': item['spec'],
|
||||
'notes': item['notes']
|
||||
}
|
||||
})
|
||||
return
|
||||
|
||||
if len(code) == 20 and code.isdigit():
|
||||
self._send_json(200, {
|
||||
'status': 'ok',
|
||||
'data': {
|
||||
'barcode': code,
|
||||
'name': f'追溯码药品 ({code[:6]}...)',
|
||||
'notes': '由国家药品电子监管码录入'
|
||||
}
|
||||
})
|
||||
return
|
||||
|
||||
self._send_json(200, {'status': 'not_found', 'message': '未在本地知识库匹配到该药品条码'})
|
||||
|
||||
def _render_dashboard(self):
|
||||
conn = get_db()
|
||||
records = conn.execute('SELECT * FROM dose_records WHERE is_deleted = 0 ORDER BY start_time DESC LIMIT 20').fetchall()
|
||||
devices = conn.execute('SELECT * FROM devices ORDER BY last_seen DESC').fetchall()
|
||||
canisters = conn.execute('SELECT * FROM canisters ORDER BY sort_order ASC').fetchall()
|
||||
bottles = conn.execute('SELECT * FROM bottles ORDER BY sequence_number DESC').fetchall()
|
||||
medicines = conn.execute('SELECT * FROM medicines WHERE is_deleted = 0 ORDER BY expiry_date ASC').fetchall()
|
||||
total_count = conn.execute('SELECT COUNT(*) as c FROM dose_records WHERE is_deleted = 0').fetchone()['c']
|
||||
conn.close()
|
||||
|
||||
med_list = []
|
||||
now_dt = datetime.datetime.now(datetime.timezone.utc)
|
||||
for m in medicines:
|
||||
exp_str = m['expiry_date'] or ''
|
||||
try:
|
||||
exp_clean = exp_str.replace('Z', '+00:00')
|
||||
exp_dt = datetime.datetime.fromisoformat(exp_clean)
|
||||
days_left = (exp_dt.date() - now_dt.date()).days
|
||||
except Exception:
|
||||
days_left = 999
|
||||
|
||||
if days_left < 0:
|
||||
badge = '<span style="background:#fee2e2;color:#b91c1c;padding:2px 8px;border-radius:6px;font-size:11px;font-weight:bold;">已过期</span>'
|
||||
elif days_left <= 30:
|
||||
badge = f'<span style="background:#fef3c7;color:#b45309;padding:2px 8px;border-radius:6px;font-size:11px;font-weight:bold;">临期 ({days_left}天)</span>'
|
||||
elif m['is_opened']:
|
||||
badge = '<span style="background:#dbeafe;color:#1d4ed8;padding:2px 8px;border-radius:6px;font-size:11px;font-weight:bold;">已开封使用</span>'
|
||||
else:
|
||||
badge = '<span style="background:#dcfce7;color:#15803d;padding:2px 8px;border-radius:6px;font-size:11px;font-weight:bold;">未开封正常</span>'
|
||||
|
||||
open_info = f"已开封 ({m['opened_at'][:10]})" if m['is_opened'] and m['opened_at'] else "未开封"
|
||||
loc = m['storage_location'] or '常温药箱'
|
||||
spec = f" <span style='color:#64748b;font-size:11px;'>({m['spec']})</span>" if m['spec'] else ""
|
||||
med_list.append(
|
||||
f"<tr style='border-bottom:1px solid #e2e8f0;'>"
|
||||
f"<td style='padding:10px 14px;'><strong>{m['name']}</strong>{spec}</td>"
|
||||
f"<td style='padding:10px 14px;'>{loc}</td>"
|
||||
f"<td style='padding:10px 14px;color:#2563eb;'>{exp_str[:10]}</td>"
|
||||
f"<td style='padding:10px 14px;'>{open_info}</td>"
|
||||
f"<td style='padding:10px 14px;'>{badge}</td>"
|
||||
f"</tr>"
|
||||
)
|
||||
med_rows = "".join(med_list) or "<tr><td colspan='5' style='padding:12px;color:#94a3b8;'>暂无家庭药箱数据,可在 App 内扫码或手动添加</td></tr>"
|
||||
|
||||
canister_list = []
|
||||
for c in canisters:
|
||||
status_badge = '<span style="color:#059669;font-weight:bold;">启用</span>' if c['is_enabled'] else '<span style="color:#94a3b8;">未启用</span>'
|
||||
@@ -557,6 +758,14 @@ class SyncHandler(SimpleHTTPRequestHandler):
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>🏠 家庭智能药箱健康与保质期监控 (全家药品有效期与开封管理)</h2>
|
||||
<table>
|
||||
<thead><tr><th>药品名称</th><th>存放位置</th><th>出厂有效期</th><th>开封追踪</th><th>健康状态</th></tr></thead>
|
||||
<tbody>{med_rows}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>当前在用药瓶余量监控 (各设备统一权威真值)</h2>
|
||||
<table>
|
||||
|
||||
+67
-1
@@ -13,6 +13,7 @@ import socket
|
||||
import tempfile
|
||||
import urllib.request
|
||||
import threading
|
||||
import datetime
|
||||
|
||||
# 动态引入 server 模块
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
@@ -139,7 +140,7 @@ class ServerIntegrationTestCase(unittest.TestCase):
|
||||
|
||||
def test_06_device_a_opens_new_bottle_2(self):
|
||||
"""测试 6: 设备 A 点击【开新瓶】,激活第 2 瓶,第 1 瓶归档,余量刷新为 60 喷"""
|
||||
now_utc = '2026-10-28T06:00:00Z'
|
||||
now_utc = (datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=1)).isoformat()
|
||||
res = self._post_json('/api/v1/sync', {
|
||||
'device_name': '妈妈手机',
|
||||
'device_id': 'dev_phone_a',
|
||||
@@ -270,5 +271,70 @@ class ServerIntegrationTestCase(unittest.TestCase):
|
||||
self.assertIn('物理药瓶开封与换瓶档案', html)
|
||||
self.assertIn('第 2 瓶', html)
|
||||
|
||||
def test_12_medicine_lookup_api(self):
|
||||
"""测试 12: 药品条码/追溯码在线快速检索 API"""
|
||||
status, body = self._get('/api/v1/medicine/lookup?code=6925567800018')
|
||||
self.assertEqual(status, 200)
|
||||
res = json.loads(body.decode('utf-8'))
|
||||
self.assertEqual(res['status'], 'ok')
|
||||
self.assertIn('美林', res['data']['name'])
|
||||
self.assertEqual(res['data']['spec'], '100ml:2g')
|
||||
|
||||
def test_13_family_medicine_sync_and_tombstone(self):
|
||||
"""测试 13: 家庭药箱多设备双向同步与开封/删除"""
|
||||
# 设备 A 上报录入美林和滴眼液
|
||||
res_a = self._post_json('/api/v1/sync', {
|
||||
'device_name': '妈妈手机',
|
||||
'device_id': 'dev_phone_mom',
|
||||
'medicines': [
|
||||
{
|
||||
'id': 'med_test_meilin',
|
||||
'name': '美林 (布洛芬混悬液)',
|
||||
'category': 'oralLiquid',
|
||||
'spec': '100ml',
|
||||
'storageLocation': '常温药箱',
|
||||
'targetUser': '宝宝',
|
||||
'expiryDate': '2027-10-31T00:00:00Z',
|
||||
'shelfLifeDaysAfterOpening': 60,
|
||||
'isOpened': False,
|
||||
'updatedAt': '2026-10-28T07:00:00Z'
|
||||
}
|
||||
]
|
||||
})
|
||||
self.assertIn('medicines', res_a)
|
||||
meds = res_a['medicines']
|
||||
meilin = [m for m in meds if m['id'] == 'med_test_meilin'][0]
|
||||
self.assertEqual(meilin['name'], '美林 (布洛芬混悬液)')
|
||||
self.assertFalse(meilin['isOpened'])
|
||||
|
||||
# 设备 B 同步并将美林标记开封打卡
|
||||
res_b = self._post_json('/api/v1/sync', {
|
||||
'device_name': '爸爸手机',
|
||||
'device_id': 'dev_phone_dad',
|
||||
'medicines': [
|
||||
{
|
||||
'id': 'med_test_meilin',
|
||||
'name': '美林 (布洛芬混悬液)',
|
||||
'category': 'oralLiquid',
|
||||
'expiryDate': '2027-10-31T00:00:00Z',
|
||||
'shelfLifeDaysAfterOpening': 60,
|
||||
'isOpened': True,
|
||||
'openedAt': '2026-10-28T07:30:00Z',
|
||||
'openedByDevice': '爸爸手机',
|
||||
'updatedAt': '2026-10-28T07:30:00Z'
|
||||
}
|
||||
]
|
||||
})
|
||||
meilin_b = [m for m in res_b['medicines'] if m['id'] == 'med_test_meilin'][0]
|
||||
self.assertTrue(meilin_b['isOpened'])
|
||||
self.assertEqual(meilin_b['openedByDevice'], '爸爸手机')
|
||||
|
||||
# 监控看板中应包含家庭药箱信息
|
||||
status, body = self._get('/dashboard')
|
||||
self.assertEqual(status, 200)
|
||||
html = body.decode('utf-8')
|
||||
self.assertIn('家庭智能药箱健康与保质期监控', html)
|
||||
self.assertIn('美林', html)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import 'package:aero_track/models/bottle.dart';
|
||||
import 'package:aero_track/models/canister.dart';
|
||||
import 'package:aero_track/models/dose_record.dart';
|
||||
import 'package:aero_track/services/storage_service.dart';
|
||||
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import 'package:aero_track/models/medicine_item.dart';
|
||||
import 'package:aero_track/services/medicine_parser_service.dart';
|
||||
import 'package:aero_track/services/storage_service.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
group('MedicineItem & Expiry Logic Tests', () {
|
||||
test('Unopened medicine within validity is safe', () {
|
||||
final now = DateTime.now();
|
||||
final med = MedicineItem(
|
||||
id: const Uuid().v4(),
|
||||
name: '美林 (布洛芬混悬液)',
|
||||
category: MedicineCategory.oralLiquid,
|
||||
expiryDate: now.add(const Duration(days: 365)),
|
||||
shelfLifeDaysAfterOpening: 60,
|
||||
isOpened: false,
|
||||
updatedAt: now.toUtc(),
|
||||
);
|
||||
|
||||
expect(med.healthStatus, MedicineHealthStatus.safe);
|
||||
expect(med.healthStatusLabel, '未开封');
|
||||
expect(med.daysUntilExpiry, inInclusiveRange(364, 366));
|
||||
});
|
||||
|
||||
test('Medicine expiring within 30 days triggers expiringSoon', () {
|
||||
final now = DateTime.now();
|
||||
final med = MedicineItem(
|
||||
id: const Uuid().v4(),
|
||||
name: '感冒冲剂',
|
||||
category: MedicineCategory.tablets,
|
||||
expiryDate: now.add(const Duration(days: 15)),
|
||||
isOpened: false,
|
||||
updatedAt: now.toUtc(),
|
||||
);
|
||||
|
||||
expect(med.healthStatus, MedicineHealthStatus.expiringSoon);
|
||||
expect(med.healthStatusLabel, contains('即将到期 (15天)'));
|
||||
});
|
||||
|
||||
test('Medicine past expiryDate triggers expired', () {
|
||||
final now = DateTime.now();
|
||||
final med = MedicineItem(
|
||||
id: const Uuid().v4(),
|
||||
name: '头孢克肟颗粒',
|
||||
category: MedicineCategory.oralLiquid,
|
||||
expiryDate: now.subtract(const Duration(days: 2)),
|
||||
isOpened: false,
|
||||
updatedAt: now.toUtc(),
|
||||
);
|
||||
|
||||
expect(med.healthStatus, MedicineHealthStatus.expired);
|
||||
expect(med.healthStatusLabel, '❌ 出厂已过期');
|
||||
});
|
||||
|
||||
test('Opened eye drops exceeding 28 days triggers overdueInUse even if factory expiry is 2 years away', () {
|
||||
final now = DateTime.now();
|
||||
final med = MedicineItem(
|
||||
id: const Uuid().v4(),
|
||||
name: '托百士滴眼液',
|
||||
category: MedicineCategory.eyeDrops,
|
||||
expiryDate: now.add(const Duration(days: 500)), // 出厂保质期还很长
|
||||
shelfLifeDaysAfterOpening: 28, // 开封只能放 28 天
|
||||
isOpened: true,
|
||||
openedAt: now.subtract(const Duration(days: 35)), // 已经开了 35 天
|
||||
updatedAt: now.toUtc(),
|
||||
);
|
||||
|
||||
expect(med.healthStatus, MedicineHealthStatus.overdueInUse);
|
||||
expect(med.healthStatusLabel, '⚠️ 开封已超期');
|
||||
expect(med.daysSinceOpened, 35);
|
||||
expect(med.daysUntilInUseExpiry, -7);
|
||||
});
|
||||
|
||||
test('Opened medicine within safe days triggers safe in-use', () {
|
||||
final now = DateTime.now();
|
||||
final med = MedicineItem(
|
||||
id: const Uuid().v4(),
|
||||
name: '辅舒酮吸入剂',
|
||||
category: MedicineCategory.inhaler,
|
||||
expiryDate: now.add(const Duration(days: 400)),
|
||||
shelfLifeDaysAfterOpening: 60,
|
||||
isOpened: true,
|
||||
openedAt: now.subtract(const Duration(days: 10)), // 开了 10 天
|
||||
updatedAt: now.toUtc(),
|
||||
);
|
||||
|
||||
expect(med.healthStatus, MedicineHealthStatus.safe);
|
||||
expect(med.healthStatusLabel, '在用正常');
|
||||
expect(med.daysSinceOpened, 10);
|
||||
expect(med.daysUntilInUseExpiry, 50);
|
||||
});
|
||||
});
|
||||
|
||||
group('MedicineParserService Scanned Barcode Tests', () {
|
||||
test('Parse GS1 DataMatrix with (17)EXP, (10)BATCH and (11)MFG', () async {
|
||||
// (01)06921147600010(17)280531(10)LOT987(11)250501
|
||||
const sampleGs1 = '(01)06921147600010(17)280531(10)LOT987(11)250501';
|
||||
final info = await MedicineParserService.parseRawBarcode(sampleGs1);
|
||||
|
||||
expect(info.parseSource, 'gs1_datamatrix');
|
||||
expect(info.batchNumber, 'LOT987');
|
||||
expect(info.expiryDate, DateTime(2028, 5, 31));
|
||||
expect(info.productionDate, DateTime(2025, 5, 1));
|
||||
});
|
||||
|
||||
test('Parse 69 EAN-13 catalog medicine (Meilin)', () async {
|
||||
const meilinBarcode = '6925567800018';
|
||||
final info = await MedicineParserService.parseRawBarcode(meilinBarcode);
|
||||
|
||||
expect(info.parseSource, 'ean13_catalog');
|
||||
expect(info.name, contains('美林'));
|
||||
expect(info.category, MedicineCategory.oralLiquid);
|
||||
expect(info.shelfLifeDaysAfterOpening, 60);
|
||||
expect(info.targetUser, '宝宝');
|
||||
});
|
||||
|
||||
test('Parse 69 EAN-13 catalog medicine (Flixotide)', () async {
|
||||
const flixBarcode = '6921147600010';
|
||||
final info = await MedicineParserService.parseRawBarcode(flixBarcode);
|
||||
|
||||
expect(info.parseSource, 'ean13_catalog');
|
||||
expect(info.name, contains('辅舒酮'));
|
||||
expect(info.category, MedicineCategory.inhaler);
|
||||
expect(info.spec, contains('60喷'));
|
||||
});
|
||||
|
||||
test('Detect 20-digit Chinese traceability code', () async {
|
||||
const traceCode = '81888880123456789012';
|
||||
final info = await MedicineParserService.parseRawBarcode(traceCode);
|
||||
|
||||
expect(info.parseSource, 'traceability_code');
|
||||
expect(info.barcode, traceCode);
|
||||
});
|
||||
});
|
||||
|
||||
group('StorageService Family Medicine CRUD Tests', () {
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
});
|
||||
|
||||
test('Initial seeding initializes default common medicines', () async {
|
||||
final storage = await StorageService.init();
|
||||
final meds = storage.getMedicines();
|
||||
|
||||
expect(meds.isNotEmpty, true);
|
||||
expect(meds.any((m) => m.name.contains('辅舒酮')), true);
|
||||
expect(meds.any((m) => m.name.contains('美林')), true);
|
||||
});
|
||||
|
||||
test('Open medicine marks it as opened and sets openedAt timestamp', () async {
|
||||
final storage = await StorageService.init();
|
||||
final meds = storage.getMedicines();
|
||||
final unopened = meds.firstWhere((m) => !m.isOpened);
|
||||
|
||||
await storage.openMedicine(unopened.id, deviceName: '测试手机');
|
||||
|
||||
final updatedMeds = storage.getMedicines();
|
||||
final updatedItem = updatedMeds.firstWhere((m) => m.id == unopened.id);
|
||||
|
||||
expect(updatedItem.isOpened, true);
|
||||
expect(updatedItem.openedAt, isNotNull);
|
||||
expect(updatedItem.openedByDevice, '测试手机');
|
||||
});
|
||||
|
||||
test('Soft delete medicine removes it from active list and retains tombstone', () async {
|
||||
final storage = await StorageService.init();
|
||||
final medsBefore = storage.getMedicines();
|
||||
final idToDelete = medsBefore.first.id;
|
||||
|
||||
await storage.deleteMedicine(idToDelete);
|
||||
|
||||
final medsAfter = storage.getMedicines();
|
||||
expect(medsAfter.any((m) => m.id == idToDelete), false);
|
||||
|
||||
final allMedsWithDeleted = storage.getMedicines(includeDeleted: true);
|
||||
final deleted = allMedsWithDeleted.firstWhere((m) => m.id == idToDelete);
|
||||
expect(deleted.isDeleted, true);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user