feat: 重构局域网数据同步与物理药瓶生命周期(Bottle Entity),实现开新瓶、软删除与多端精确余量核算
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
import 'dart:convert';
|
||||
|
||||
class Bottle {
|
||||
final String id; // 全局唯一 UUID (如: flix_b1_xxxx)
|
||||
final String canisterId; // 关联的药品ID (如: flixotide_primary / ventolin_primary)
|
||||
final String name; // 药品展示名称
|
||||
final int sequenceNumber; // 第几瓶 (1, 2, 3...)
|
||||
final int totalDoses; // 规格总喷数 (如 60, 200)
|
||||
final DateTime openedAt; // 严格 UTC 开封时间
|
||||
DateTime? finishedAt; // 严格 UTC 用尽/归档时间
|
||||
bool isActive; // 是否为当前正在使用的活跃药瓶
|
||||
final String openedByDevice; // 开瓶操作的设备名称
|
||||
DateTime updatedAt; // 严格 UTC 更新时间戳 (用于多端 LWW 冲突解决)
|
||||
|
||||
Bottle({
|
||||
required this.id,
|
||||
required this.canisterId,
|
||||
required this.name,
|
||||
this.sequenceNumber = 1,
|
||||
required this.totalDoses,
|
||||
required this.openedAt,
|
||||
this.finishedAt,
|
||||
this.isActive = true,
|
||||
this.openedByDevice = '本机',
|
||||
DateTime? updatedAt,
|
||||
}) : updatedAt = updatedAt ?? DateTime.now().toUtc();
|
||||
|
||||
Map<String, dynamic> toMap() {
|
||||
return {
|
||||
'id': id,
|
||||
'canisterId': canisterId,
|
||||
'name': name,
|
||||
'sequenceNumber': sequenceNumber,
|
||||
'totalDoses': totalDoses,
|
||||
'openedAt': openedAt.toUtc().toIso8601String(),
|
||||
'finishedAt': finishedAt?.toUtc().toIso8601String(),
|
||||
'isActive': isActive,
|
||||
'openedByDevice': openedByDevice,
|
||||
'updatedAt': updatedAt.toUtc().toIso8601String(),
|
||||
};
|
||||
}
|
||||
|
||||
factory Bottle.fromMap(Map<String, dynamic> map) {
|
||||
return Bottle(
|
||||
id: map['id'] as String,
|
||||
canisterId: map['canisterId'] as String? ?? (map['canister_id'] as String? ?? ''),
|
||||
name: map['name'] as String? ?? '',
|
||||
sequenceNumber: map['sequenceNumber'] as int? ?? (map['sequence_number'] as int? ?? 1),
|
||||
totalDoses: map['totalDoses'] as int? ?? (map['total_doses'] as int? ?? 60),
|
||||
openedAt: DateTime.parse(map['openedAt'] as String? ?? (map['opened_at'] as String? ?? DateTime.now().toUtc().toIso8601String())).toUtc(),
|
||||
finishedAt: map['finishedAt'] != null
|
||||
? DateTime.parse(map['finishedAt'] as String).toUtc()
|
||||
: (map['finished_at'] != null ? DateTime.parse(map['finished_at'] as String).toUtc() : null),
|
||||
isActive: map['isActive'] as bool? ?? ((map['is_active'] as int? ?? 1) == 1),
|
||||
openedByDevice: map['openedByDevice'] as String? ?? (map['opened_by_device'] as String? ?? '家庭设备'),
|
||||
updatedAt: map['updatedAt'] != null
|
||||
? DateTime.parse(map['updatedAt'] as String).toUtc()
|
||||
: (map['updated_at'] != null ? DateTime.parse(map['updated_at'] as String).toUtc() : DateTime.now().toUtc()),
|
||||
);
|
||||
}
|
||||
|
||||
String toJson() => json.encode(toMap());
|
||||
factory Bottle.fromJson(String source) =>
|
||||
Bottle.fromMap(json.decode(source) as Map<String, dynamic>);
|
||||
}
|
||||
@@ -39,7 +39,7 @@ class Canister {
|
||||
'name': name,
|
||||
'totalDoses': totalDoses,
|
||||
'remainingDoses': remainingDoses,
|
||||
'openedAt': openedAt.toIso8601String(),
|
||||
'openedAt': openedAt.toUtc().toIso8601String(),
|
||||
'isEnabled': isEnabled,
|
||||
'puffsPerSession': puffsPerSession,
|
||||
'inhalationSeconds': inhalationSeconds,
|
||||
@@ -55,7 +55,7 @@ class Canister {
|
||||
name: map['name'] as String,
|
||||
totalDoses: map['totalDoses'] as int,
|
||||
remainingDoses: map['remainingDoses'] as int,
|
||||
openedAt: DateTime.parse(map['openedAt'] as String),
|
||||
openedAt: DateTime.parse(map['openedAt'] as String).toUtc(),
|
||||
isEnabled: map['isEnabled'] as bool? ?? true,
|
||||
puffsPerSession: map['puffsPerSession'] as int? ?? 2,
|
||||
inhalationSeconds: map['inhalationSeconds'] as int? ?? 15,
|
||||
|
||||
+33
-15
@@ -4,12 +4,16 @@ class DoseRecord {
|
||||
final String id;
|
||||
final DateTime startTime;
|
||||
final DateTime endTime;
|
||||
final int flixotidePuffs; // 辅舒酮喷数
|
||||
final int ventolinPuffs; // 万托林喷数
|
||||
final bool rinsedMouth; // 是否漱口
|
||||
final bool washedFace; // 是否洗脸
|
||||
final bool isPrime; // 是否为试喷扣除
|
||||
final int flixotidePuffs; // 辅舒酮喷数
|
||||
final int ventolinPuffs; // 万托林喷数
|
||||
final String? flixotideBottleId; // 关联的辅舒酮药瓶 UUID
|
||||
final String? ventolinBottleId; // 关联的万托林药瓶 UUID
|
||||
final bool rinsedMouth; // 是否漱口
|
||||
final bool washedFace; // 是否洗脸
|
||||
final bool isPrime; // 是否为试喷扣除
|
||||
final bool isDeleted; // 软删除墓碑标记
|
||||
final String? note;
|
||||
final DateTime updatedAt; // UTC 更新时间
|
||||
|
||||
DoseRecord({
|
||||
required this.id,
|
||||
@@ -17,39 +21,53 @@ class DoseRecord {
|
||||
required this.endTime,
|
||||
this.flixotidePuffs = 0,
|
||||
this.ventolinPuffs = 0,
|
||||
this.flixotideBottleId,
|
||||
this.ventolinBottleId,
|
||||
this.rinsedMouth = true,
|
||||
this.washedFace = true,
|
||||
this.isPrime = false,
|
||||
this.isDeleted = false,
|
||||
this.note,
|
||||
});
|
||||
DateTime? updatedAt,
|
||||
}) : updatedAt = updatedAt ?? DateTime.now().toUtc();
|
||||
|
||||
Duration get duration => endTime.difference(startTime);
|
||||
|
||||
Map<String, dynamic> toMap() {
|
||||
return {
|
||||
'id': id,
|
||||
'startTime': startTime.toIso8601String(),
|
||||
'endTime': endTime.toIso8601String(),
|
||||
'startTime': startTime.toUtc().toIso8601String(),
|
||||
'endTime': endTime.toUtc().toIso8601String(),
|
||||
'flixotidePuffs': flixotidePuffs,
|
||||
'ventolinPuffs': ventolinPuffs,
|
||||
'flixotideBottleId': flixotideBottleId,
|
||||
'ventolinBottleId': ventolinBottleId,
|
||||
'rinsedMouth': rinsedMouth,
|
||||
'washedFace': washedFace,
|
||||
'isPrime': isPrime,
|
||||
'isDeleted': isDeleted,
|
||||
'note': note,
|
||||
'updatedAt': updatedAt.toUtc().toIso8601String(),
|
||||
};
|
||||
}
|
||||
|
||||
factory DoseRecord.fromMap(Map<String, dynamic> map) {
|
||||
return DoseRecord(
|
||||
id: map['id'] as String,
|
||||
startTime: DateTime.parse(map['startTime'] as String),
|
||||
endTime: DateTime.parse(map['endTime'] as String),
|
||||
flixotidePuffs: map['flixotidePuffs'] as int? ?? 0,
|
||||
ventolinPuffs: map['ventolinPuffs'] as int? ?? 0,
|
||||
rinsedMouth: map['rinsedMouth'] as bool? ?? true,
|
||||
washedFace: map['washedFace'] as bool? ?? true,
|
||||
isPrime: map['isPrime'] as bool? ?? false,
|
||||
startTime: DateTime.parse(map['startTime'] as String? ?? (map['start_time'] as String)).toUtc(),
|
||||
endTime: DateTime.parse(map['endTime'] as String? ?? (map['end_time'] as String)).toUtc(),
|
||||
flixotidePuffs: map['flixotidePuffs'] as int? ?? (map['flixotide_puffs'] as int? ?? 0),
|
||||
ventolinPuffs: map['ventolinPuffs'] as int? ?? (map['ventolin_puffs'] as int? ?? 0),
|
||||
flixotideBottleId: map['flixotideBottleId'] as String? ?? (map['flixotide_bottle_id'] as String?),
|
||||
ventolinBottleId: map['ventolinBottleId'] as String? ?? (map['ventolin_bottle_id'] as String?),
|
||||
rinsedMouth: map['rinsedMouth'] as bool? ?? ((map['rinsed_mouth'] as int? ?? 1) == 1),
|
||||
washedFace: map['washedFace'] as bool? ?? ((map['washed_face'] as int? ?? 1) == 1),
|
||||
isPrime: map['isPrime'] as bool? ?? ((map['is_prime'] as int? ?? 0) == 1),
|
||||
isDeleted: map['isDeleted'] as bool? ?? ((map['is_deleted'] as int? ?? 0) == 1),
|
||||
note: map['note'] as String?,
|
||||
updatedAt: map['updatedAt'] != null
|
||||
? DateTime.parse(map['updatedAt'] as String).toUtc()
|
||||
: (map['updated_at'] != null ? DateTime.parse(map['updated_at'] as String).toUtc() : DateTime.now().toUtc()),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../models/dose_record.dart';
|
||||
import '../services/storage_service.dart';
|
||||
import '../services/sync_service.dart';
|
||||
|
||||
class HistoryScreen extends StatefulWidget {
|
||||
final StorageService storageService;
|
||||
@@ -47,6 +48,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
if (confirmed == true) {
|
||||
await widget.storageService.deleteRecord(record.id);
|
||||
_loadRecords();
|
||||
SyncService(widget.storageService).syncSilently();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -136,7 +136,6 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
);
|
||||
|
||||
if (confirmed == true && _activeCanisters.isNotEmpty) {
|
||||
final now = DateTime.now();
|
||||
final Map<String, int> deductions = {};
|
||||
int flixotideDoses = 0;
|
||||
int ventolinDoses = 0;
|
||||
@@ -150,12 +149,19 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
final nowUtc = DateTime.now().toUtc();
|
||||
final activeFlix = widget.storageService.getActiveFlixotideBottle();
|
||||
final activeVent = widget.storageService.getActiveVentolinBottle();
|
||||
|
||||
final record = DoseRecord(
|
||||
id: const Uuid().v4(),
|
||||
startTime: now,
|
||||
endTime: now,
|
||||
startTime: nowUtc,
|
||||
endTime: nowUtc,
|
||||
flixotidePuffs: flixotideDoses,
|
||||
ventolinPuffs: ventolinDoses,
|
||||
flixotideBottleId: flixotideDoses > 0 ? activeFlix?.id : null,
|
||||
ventolinBottleId: ventolinDoses > 0 ? activeVent?.id : null,
|
||||
updatedAt: nowUtc,
|
||||
);
|
||||
|
||||
await widget.storageService.deductSessionDoses(deductions);
|
||||
@@ -185,15 +191,20 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
);
|
||||
|
||||
if (confirmed == true) {
|
||||
final now = DateTime.now();
|
||||
final nowUtc = DateTime.now().toUtc();
|
||||
final activeBottle = widget.storageService.getActiveBottle(canister.id);
|
||||
|
||||
final record = DoseRecord(
|
||||
id: const Uuid().v4(),
|
||||
startTime: now,
|
||||
endTime: now,
|
||||
startTime: nowUtc,
|
||||
endTime: nowUtc,
|
||||
flixotidePuffs: canister.isSteroid ? 1 : 0,
|
||||
ventolinPuffs: canister.isSteroid ? 0 : 1,
|
||||
flixotideBottleId: canister.isSteroid ? activeBottle?.id : null,
|
||||
ventolinBottleId: !canister.isSteroid ? activeBottle?.id : null,
|
||||
isPrime: true,
|
||||
note: '${canister.name.split(" ")[0]}试喷',
|
||||
updatedAt: nowUtc,
|
||||
);
|
||||
await widget.storageService.deductSessionDoses({canister.id: 1});
|
||||
await widget.storageService.addRecord(record);
|
||||
@@ -203,28 +214,36 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
}
|
||||
|
||||
Future<void> _resetCanister(Canister canister) async {
|
||||
final activeBottle = widget.storageService.getActiveBottle(canister.id);
|
||||
final currentSeq = activeBottle?.sequenceNumber ?? 1;
|
||||
final nextSeq = currentSeq + 1;
|
||||
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: Text('换新药瓶 - ${canister.name.split(" ")[0]}'),
|
||||
content: Text('确认启用新的一瓶【${canister.name}】,将其剩余次数重置为 ${canister.totalDoses} 喷吗?'),
|
||||
content: Text('当前正在使用第 $currentSeq 瓶。\n确认拆封启用【第 $nextSeq 瓶】,并将剩余次数重置为满瓶 (${canister.totalDoses} 喷) 吗?'),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('取消')),
|
||||
ElevatedButton(
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
child: Text('确认重置为 ${canister.totalDoses} 喷'),
|
||||
child: Text('确认启用第 $nextSeq 瓶'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmed == true) {
|
||||
await widget.storageService.resetCanisterDoses(canister.id, canister.totalDoses);
|
||||
final deviceName = await SyncService.getDeviceName();
|
||||
final newBottle = await widget.storageService.openNewBottle(canister.id, deviceName: deviceName);
|
||||
_loadData();
|
||||
SyncService(widget.storageService).syncSilently();
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('已成功将 ${canister.name.split(" ")[0]} 重置为满瓶!')),
|
||||
SnackBar(
|
||||
content: Text('已成功启用第 ${newBottle.sequenceNumber} 瓶【${canister.name.split(" ")[0]}】,剩余次数已更新为满瓶!'),
|
||||
backgroundColor: const Color(0xFF10B981),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -313,14 +313,20 @@ class ActiveSessionService extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
final activeFlix = storageService.getActiveFlixotideBottle();
|
||||
final activeVent = storageService.getActiveVentolinBottle();
|
||||
|
||||
final record = DoseRecord(
|
||||
id: const Uuid().v4(),
|
||||
startTime: _sessionStartTime ?? DateTime.now(),
|
||||
endTime: _sessionEndTime ?? DateTime.now(),
|
||||
startTime: (_sessionStartTime ?? DateTime.now()).toUtc(),
|
||||
endTime: (_sessionEndTime ?? DateTime.now()).toUtc(),
|
||||
flixotidePuffs: totalFlixotide,
|
||||
ventolinPuffs: totalVentolin,
|
||||
flixotideBottleId: totalFlixotide > 0 ? activeFlix?.id : null,
|
||||
ventolinBottleId: totalVentolin > 0 ? activeVent?.id : null,
|
||||
rinsedMouth: _rinsedMouth,
|
||||
washedFace: _washedFace,
|
||||
updatedAt: DateTime.now().toUtc(),
|
||||
);
|
||||
|
||||
await storageService.addRecord(record);
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
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';
|
||||
@@ -7,6 +9,7 @@ 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';
|
||||
|
||||
final SharedPreferences _prefs;
|
||||
|
||||
@@ -21,7 +24,7 @@ class StorageService {
|
||||
}
|
||||
|
||||
Future<void> _ensureInitialData() async {
|
||||
// 首次启动初始化默认药品 (使用早期占位时间,确保能完全继承云端开瓶时间与历史记录)
|
||||
// 1. 首次启动初始化默认药品方案配置
|
||||
if (!_prefs.containsKey(_keyCanisters)) {
|
||||
final defaultCanisters = [
|
||||
Canister(
|
||||
@@ -29,7 +32,7 @@ class StorageService {
|
||||
name: '万托林 (硫酸沙丁胺醇)',
|
||||
totalDoses: 200,
|
||||
remainingDoses: 200,
|
||||
openedAt: DateTime(2020, 1, 1),
|
||||
openedAt: DateTime(2020, 1, 1).toUtc(),
|
||||
isEnabled: true,
|
||||
puffsPerSession: 2,
|
||||
inhalationSeconds: 15,
|
||||
@@ -42,7 +45,7 @@ class StorageService {
|
||||
name: '辅舒酮 (丙酸氟替卡松)',
|
||||
totalDoses: 60,
|
||||
remainingDoses: 60,
|
||||
openedAt: DateTime(2020, 1, 1),
|
||||
openedAt: DateTime(2020, 1, 1).toUtc(),
|
||||
isEnabled: true,
|
||||
puffsPerSession: 2,
|
||||
inhalationSeconds: 15,
|
||||
@@ -53,6 +56,80 @@ class StorageService {
|
||||
];
|
||||
await saveCanisters(defaultCanisters);
|
||||
}
|
||||
|
||||
// 2. 物理药瓶生命周期实体初始化与历史流水平滑迁移
|
||||
final existingBottles = getBottles();
|
||||
if (existingBottles.isEmpty) {
|
||||
final initialFlixBottle = Bottle(
|
||||
id: 'flix_b1_initial',
|
||||
canisterId: 'flixotide_primary',
|
||||
name: '辅舒酮 (丙酸氟替卡松)',
|
||||
sequenceNumber: 1,
|
||||
totalDoses: 60,
|
||||
openedAt: DateTime(2020, 1, 1).toUtc(),
|
||||
isActive: true,
|
||||
openedByDevice: '系统初始化',
|
||||
updatedAt: DateTime.now().toUtc(),
|
||||
);
|
||||
|
||||
final initialVentBottle = Bottle(
|
||||
id: 'vent_b1_initial',
|
||||
canisterId: 'ventolin_primary',
|
||||
name: '万托林 (硫酸沙丁胺醇)',
|
||||
sequenceNumber: 1,
|
||||
totalDoses: 200,
|
||||
openedAt: DateTime(2020, 1, 1).toUtc(),
|
||||
isActive: true,
|
||||
openedByDevice: '系统初始化',
|
||||
updatedAt: DateTime.now().toUtc(),
|
||||
);
|
||||
|
||||
await saveBottles([initialFlixBottle, initialVentBottle]);
|
||||
|
||||
// 历史平滑过渡:若存在未绑定 bottle_id 的历史用药记录,全部归属到第 1 瓶
|
||||
final allRawRecords = getAllRecords(includeDeleted: true);
|
||||
bool recordsUpdated = false;
|
||||
final migratedRecords = <DoseRecord>[];
|
||||
|
||||
for (var r in allRawRecords) {
|
||||
String? fId = r.flixotideBottleId;
|
||||
String? vId = r.ventolinBottleId;
|
||||
|
||||
if (r.flixotidePuffs > 0 && fId == null) {
|
||||
fId = initialFlixBottle.id;
|
||||
recordsUpdated = true;
|
||||
}
|
||||
if (r.ventolinPuffs > 0 && vId == null) {
|
||||
vId = initialVentBottle.id;
|
||||
recordsUpdated = true;
|
||||
}
|
||||
|
||||
if (fId != r.flixotideBottleId || vId != r.ventolinBottleId) {
|
||||
migratedRecords.add(DoseRecord(
|
||||
id: r.id,
|
||||
startTime: r.startTime,
|
||||
endTime: r.endTime,
|
||||
flixotidePuffs: r.flixotidePuffs,
|
||||
ventolinPuffs: r.ventolinPuffs,
|
||||
flixotideBottleId: fId,
|
||||
ventolinBottleId: vId,
|
||||
rinsedMouth: r.rinsedMouth,
|
||||
washedFace: r.washedFace,
|
||||
isPrime: r.isPrime,
|
||||
isDeleted: r.isDeleted,
|
||||
note: r.note,
|
||||
updatedAt: r.updatedAt,
|
||||
));
|
||||
} else {
|
||||
migratedRecords.add(r);
|
||||
}
|
||||
}
|
||||
|
||||
if (recordsUpdated) {
|
||||
final list = migratedRecords.map((r) => r.toJson()).toList();
|
||||
await _prefs.setStringList(_keyRecords, list);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ========== AppSettings ==========
|
||||
@@ -70,6 +147,96 @@ class StorageService {
|
||||
await _prefs.setString(_keySettings, settings.toJson());
|
||||
}
|
||||
|
||||
// ========== Bottles (物理药瓶生命周期) ==========
|
||||
List<Bottle> getBottles() {
|
||||
final raw = _prefs.getStringList(_keyBottles);
|
||||
if (raw == null) return [];
|
||||
try {
|
||||
final list = raw.map((item) => Bottle.fromJson(item)).toList();
|
||||
list.sort((a, b) => a.sequenceNumber.compareTo(b.sequenceNumber));
|
||||
return list;
|
||||
} catch (_) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> saveBottles(List<Bottle> bottles) async {
|
||||
final list = bottles.map((b) => b.toJson()).toList();
|
||||
await _prefs.setStringList(_keyBottles, list);
|
||||
}
|
||||
|
||||
Bottle? getActiveBottle(String canisterId) {
|
||||
final bottles = getBottles();
|
||||
try {
|
||||
return bottles.firstWhere((b) => b.canisterId == canisterId && b.isActive);
|
||||
} catch (_) {
|
||||
final matched = bottles.where((b) => b.canisterId == canisterId).toList();
|
||||
return matched.isNotEmpty ? matched.last : null;
|
||||
}
|
||||
}
|
||||
|
||||
Bottle? getActiveFlixotideBottle() => getActiveBottle('flixotide_primary');
|
||||
Bottle? getActiveVentolinBottle() => getActiveBottle('ventolin_primary');
|
||||
|
||||
/// 开启新药瓶:归档旧瓶,激活带有全新 UUID 的新瓶实体
|
||||
Future<Bottle> openNewBottle(String canisterId, {required String deviceName}) async {
|
||||
final bottles = getBottles();
|
||||
final nowUtc = DateTime.now().toUtc();
|
||||
int nextSeq = 1;
|
||||
|
||||
for (var b in bottles) {
|
||||
if (b.canisterId == canisterId && b.isActive) {
|
||||
b.isActive = false;
|
||||
b.finishedAt = nowUtc;
|
||||
b.updatedAt = nowUtc;
|
||||
}
|
||||
if (b.canisterId == canisterId && b.sequenceNumber >= nextSeq) {
|
||||
nextSeq = b.sequenceNumber + 1;
|
||||
}
|
||||
}
|
||||
|
||||
final canisters = getCanisters();
|
||||
final config = canisters.firstWhere(
|
||||
(c) => c.id == canisterId,
|
||||
orElse: () => Canister(
|
||||
id: canisterId,
|
||||
name: canisterId.contains('flix') ? '辅舒酮 (丙酸氟替卡松)' : '万托林 (硫酸沙丁胺醇)',
|
||||
totalDoses: canisterId.contains('flix') ? 60 : 200,
|
||||
remainingDoses: canisterId.contains('flix') ? 60 : 200,
|
||||
openedAt: nowUtc,
|
||||
),
|
||||
);
|
||||
|
||||
final prefix = canisterId.contains('flix') ? 'flix' : 'vent';
|
||||
final randomSuffix = const Uuid().v4().substring(0, 8);
|
||||
final newBottle = Bottle(
|
||||
id: '${prefix}_b${nextSeq}_$randomSuffix',
|
||||
canisterId: canisterId,
|
||||
name: config.name,
|
||||
sequenceNumber: nextSeq,
|
||||
totalDoses: config.totalDoses,
|
||||
openedAt: nowUtc,
|
||||
isActive: true,
|
||||
openedByDevice: deviceName,
|
||||
updatedAt: nowUtc,
|
||||
);
|
||||
|
||||
bottles.add(newBottle);
|
||||
await saveBottles(bottles);
|
||||
|
||||
// 同步更新方案配置中的开瓶时间与初始满喷
|
||||
for (var c in canisters) {
|
||||
if (c.id == canisterId) {
|
||||
c.openedAt = nowUtc;
|
||||
c.remainingDoses = c.totalDoses;
|
||||
}
|
||||
}
|
||||
await saveCanisters(canisters);
|
||||
await recalculateCanisterDoses();
|
||||
|
||||
return newBottle;
|
||||
}
|
||||
|
||||
// ========== Canisters ==========
|
||||
List<Canister> getCanisters() {
|
||||
final raw = _prefs.getStringList(_keyCanisters);
|
||||
@@ -149,43 +316,60 @@ class StorageService {
|
||||
await saveCanisters(canisters);
|
||||
}
|
||||
|
||||
Future<void> resetCanisterDoses(String canisterId, int newTotal) async {
|
||||
final canisters = getCanisters();
|
||||
for (var c in canisters) {
|
||||
if (c.id == canisterId) {
|
||||
c.remainingDoses = newTotal;
|
||||
c.openedAt = DateTime.now(); // 启用新瓶时更新开封时间戳
|
||||
}
|
||||
}
|
||||
await saveCanisters(canisters);
|
||||
Future<void> resetCanisterDoses(String canisterId, int newTotal, {String deviceName = '本机'}) async {
|
||||
await openNewBottle(canisterId, deviceName: deviceName);
|
||||
}
|
||||
|
||||
/// 依据全部雾化流水历史记录,重新精准核算每个药瓶的真实剩余喷数
|
||||
/// 依据各药瓶 UUID 与真实流水账本,严格重算当前活跃药瓶的真实剩余喷数
|
||||
Future<void> recalculateCanisterDoses() async {
|
||||
final canisters = getCanisters();
|
||||
if (canisters.isEmpty) return;
|
||||
final records = getRecords();
|
||||
|
||||
final records = getAllRecords(includeDeleted: false);
|
||||
bool changed = false;
|
||||
|
||||
for (var c in canisters) {
|
||||
// 统计自开封时间点以来的全部消耗喷数(留 1 分钟时钟误差裕量)
|
||||
final validRecords = records.where((r) {
|
||||
return !r.startTime.isBefore(c.openedAt.subtract(const Duration(minutes: 1)));
|
||||
});
|
||||
|
||||
final activeBottle = getActiveBottle(c.id);
|
||||
int consumedPuffs = 0;
|
||||
for (var r in validRecords) {
|
||||
if (c.isSteroid) {
|
||||
consumedPuffs += r.flixotidePuffs;
|
||||
} else {
|
||||
consumedPuffs += r.ventolinPuffs;
|
||||
}
|
||||
}
|
||||
|
||||
final correctRemaining = (c.totalDoses - consumedPuffs).clamp(0, c.totalDoses);
|
||||
if (c.remainingDoses != correctRemaining) {
|
||||
c.remainingDoses = correctRemaining;
|
||||
changed = true;
|
||||
if (activeBottle != null) {
|
||||
for (var r in records) {
|
||||
if (c.isSteroid) {
|
||||
// 优先依据明确绑定的 bottleId 核算
|
||||
if (r.flixotideBottleId == activeBottle.id) {
|
||||
consumedPuffs += r.flixotidePuffs;
|
||||
} else if (r.flixotideBottleId == null && !r.startTime.isBefore(activeBottle.openedAt)) {
|
||||
// 兼容早期未绑定 bottleId 的旧数据
|
||||
consumedPuffs += r.flixotidePuffs;
|
||||
}
|
||||
} else {
|
||||
if (r.ventolinBottleId == activeBottle.id) {
|
||||
consumedPuffs += r.ventolinPuffs;
|
||||
} else if (r.ventolinBottleId == null && !r.startTime.isBefore(activeBottle.openedAt)) {
|
||||
consumedPuffs += r.ventolinPuffs;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final correctRemaining = (activeBottle.totalDoses - consumedPuffs).clamp(0, activeBottle.totalDoses);
|
||||
if (c.remainingDoses != correctRemaining || c.openedAt != activeBottle.openedAt) {
|
||||
c.remainingDoses = correctRemaining;
|
||||
c.openedAt = activeBottle.openedAt;
|
||||
changed = true;
|
||||
}
|
||||
} else {
|
||||
// 无 activeBottle 时的保护逻辑
|
||||
for (var r in records) {
|
||||
if (c.isSteroid) {
|
||||
consumedPuffs += r.flixotidePuffs;
|
||||
} else {
|
||||
consumedPuffs += r.ventolinPuffs;
|
||||
}
|
||||
}
|
||||
final correctRemaining = (c.totalDoses - consumedPuffs).clamp(0, c.totalDoses);
|
||||
if (c.remainingDoses != correctRemaining) {
|
||||
c.remainingDoses = correctRemaining;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,27 +379,64 @@ class StorageService {
|
||||
}
|
||||
|
||||
// ========== DoseRecords ==========
|
||||
List<DoseRecord> getRecords() {
|
||||
/// 获取对用户可见的有效流水记录(默认过滤掉软删除墓碑记录)
|
||||
List<DoseRecord> getRecords() => getAllRecords(includeDeleted: false);
|
||||
|
||||
/// 获取全量记录(可包含软删除墓碑,专供多端同步使用)
|
||||
List<DoseRecord> getAllRecords({bool includeDeleted = false}) {
|
||||
final raw = _prefs.getStringList(_keyRecords);
|
||||
if (raw == null) return [];
|
||||
final list = raw.map((item) => DoseRecord.fromJson(item)).toList();
|
||||
list.sort((a, b) => b.startTime.compareTo(a.startTime));
|
||||
return list;
|
||||
try {
|
||||
final list = raw.map((item) => DoseRecord.fromJson(item)).toList();
|
||||
final filtered = includeDeleted ? list : list.where((r) => !r.isDeleted).toList();
|
||||
filtered.sort((a, b) => b.startTime.compareTo(a.startTime));
|
||||
return filtered;
|
||||
} catch (_) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> addRecord(DoseRecord record) async {
|
||||
final records = getRecords();
|
||||
final records = getAllRecords(includeDeleted: true);
|
||||
records.insert(0, record);
|
||||
final list = records.map((r) => r.toJson()).toList();
|
||||
await _prefs.setStringList(_keyRecords, list);
|
||||
await recalculateCanisterDoses();
|
||||
}
|
||||
|
||||
/// 软删除记录(墓碑机制):全网标记废弃,喷数自动准确恢复
|
||||
Future<void> deleteRecord(String id) async {
|
||||
final records = getRecords();
|
||||
records.removeWhere((r) => r.id == id);
|
||||
final list = records.map((r) => r.toJson()).toList();
|
||||
await _prefs.setStringList(_keyRecords, list);
|
||||
await recalculateCanisterDoses();
|
||||
final records = getAllRecords(includeDeleted: true);
|
||||
final nowUtc = DateTime.now().toUtc();
|
||||
bool updated = false;
|
||||
|
||||
for (int i = 0; i < records.length; i++) {
|
||||
if (records[i].id == id) {
|
||||
final old = records[i];
|
||||
records[i] = DoseRecord(
|
||||
id: old.id,
|
||||
startTime: old.startTime,
|
||||
endTime: old.endTime,
|
||||
flixotidePuffs: old.flixotidePuffs,
|
||||
ventolinPuffs: old.ventolinPuffs,
|
||||
flixotideBottleId: old.flixotideBottleId,
|
||||
ventolinBottleId: old.ventolinBottleId,
|
||||
rinsedMouth: old.rinsedMouth,
|
||||
washedFace: old.washedFace,
|
||||
isPrime: old.isPrime,
|
||||
isDeleted: true,
|
||||
note: old.note,
|
||||
updatedAt: nowUtc,
|
||||
);
|
||||
updated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (updated) {
|
||||
final list = records.map((r) => r.toJson()).toList();
|
||||
await _prefs.setStringList(_keyRecords, list);
|
||||
await recalculateCanisterDoses();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter/foundation.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
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 'storage_service.dart';
|
||||
@@ -116,15 +117,17 @@ class SyncService {
|
||||
|
||||
try {
|
||||
await storageService.recalculateCanisterDoses();
|
||||
final localRecords = storageService.getRecords();
|
||||
final localRecords = storageService.getAllRecords(includeDeleted: true);
|
||||
final localBottles = storageService.getBottles();
|
||||
final localCanisters = storageService.getCanisters();
|
||||
final lastSync = await getLastSyncTime();
|
||||
|
||||
final body = json.encode({
|
||||
'device_name': deviceName,
|
||||
'device_id': deviceId,
|
||||
'last_sync_time': lastSync?.toIso8601String(),
|
||||
'last_sync_time': lastSync?.toUtc().toIso8601String(),
|
||||
'records': localRecords.map((r) => r.toMap()).toList(),
|
||||
'bottles': localBottles.map((b) => b.toMap()).toList(),
|
||||
'canisters': localCanisters.map((c) => c.toMap()).toList(),
|
||||
});
|
||||
|
||||
@@ -138,33 +141,70 @@ class SyncService {
|
||||
if (res.statusCode == 200) {
|
||||
final data = json.decode(utf8.decode(res.bodyBytes)) as Map<String, dynamic>;
|
||||
|
||||
// 1. 合并远端记录到本地
|
||||
// 1. 合并远端药瓶生命周期实体 Bottles
|
||||
final remoteBottlesRaw = data['bottles'] as List<dynamic>? ?? [];
|
||||
final remoteBottles = remoteBottlesRaw
|
||||
.map((item) => Bottle.fromMap(item as Map<String, dynamic>))
|
||||
.toList();
|
||||
|
||||
if (remoteBottles.isNotEmpty) {
|
||||
final bottles = storageService.getBottles();
|
||||
final bottleMap = {for (var b in bottles) b.id: b};
|
||||
|
||||
for (var rb in remoteBottles) {
|
||||
final lb = bottleMap[rb.id];
|
||||
if (lb == null) {
|
||||
bottles.add(rb);
|
||||
} else {
|
||||
// LWW 依据 updatedAt 解决冲突
|
||||
if (rb.updatedAt.isAfter(lb.updatedAt) || (rb.isActive != lb.isActive && !rb.isActive)) {
|
||||
final idx = bottles.indexWhere((b) => b.id == rb.id);
|
||||
if (idx != -1) {
|
||||
bottles[idx] = rb;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
await storageService.saveBottles(bottles);
|
||||
}
|
||||
|
||||
// 2. 双向合并全量流水记录 (含软删除墓碑同步)
|
||||
final remoteRecordsRaw = data['records'] as List<dynamic>? ?? [];
|
||||
final remoteRecords = remoteRecordsRaw
|
||||
.map((item) => DoseRecord.fromMap(item as Map<String, dynamic>))
|
||||
.toList();
|
||||
|
||||
final existingIds = localRecords.map((r) => r.id).toSet();
|
||||
final allLocalRecords = storageService.getAllRecords(includeDeleted: true);
|
||||
final localRecordMap = {for (var r in allLocalRecords) r.id: r};
|
||||
int newCount = 0;
|
||||
final List<DoseRecord> newRecords = [];
|
||||
bool recordListChanged = false;
|
||||
|
||||
for (var r in remoteRecords) {
|
||||
if (!existingIds.contains(r.id)) {
|
||||
newRecords.add(r);
|
||||
newCount++;
|
||||
for (var rr in remoteRecords) {
|
||||
final lr = localRecordMap[rr.id];
|
||||
if (lr == null) {
|
||||
allLocalRecords.add(rr);
|
||||
if (!rr.isDeleted) newCount++;
|
||||
recordListChanged = true;
|
||||
} else {
|
||||
// 远端记录有状态变更(例如标记软删除或补充了 bottleId)
|
||||
if (rr.updatedAt.isAfter(lr.updatedAt) || (rr.isDeleted && !lr.isDeleted)) {
|
||||
final idx = allLocalRecords.indexWhere((r) => r.id == rr.id);
|
||||
if (idx != -1) {
|
||||
allLocalRecords[idx] = rr;
|
||||
recordListChanged = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (newRecords.isNotEmpty) {
|
||||
final allRecords = storageService.getRecords();
|
||||
allRecords.insertAll(0, newRecords);
|
||||
allRecords.sort((a, b) => b.startTime.compareTo(a.startTime));
|
||||
final rawList = allRecords.map((r) => r.toJson()).toList();
|
||||
if (recordListChanged) {
|
||||
allLocalRecords.sort((a, b) => b.startTime.compareTo(a.startTime));
|
||||
final rawList = allLocalRecords.map((r) => r.toJson()).toList();
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setStringList('aerotrack_records', rawList);
|
||||
}
|
||||
|
||||
// 2. 合并远端药瓶状态到本地 (智能继承开封时间)
|
||||
// 3. 合并远端药瓶方案基础配置
|
||||
final remoteCanistersRaw = data['canisters'] as List<dynamic>? ?? [];
|
||||
final remoteCanisters = remoteCanistersRaw
|
||||
.map((item) => Canister.fromMap(item as Map<String, dynamic>))
|
||||
@@ -173,21 +213,10 @@ class SyncService {
|
||||
if (remoteCanisters.isNotEmpty) {
|
||||
final currentCanisters = storageService.getCanisters();
|
||||
final localMap = {for (var c in currentCanisters) c.id: c};
|
||||
final allCurrentRecords = storageService.getRecords();
|
||||
|
||||
for (var rc in remoteCanisters) {
|
||||
final lc = localMap[rc.id];
|
||||
if (lc != null) {
|
||||
// 判断是否采纳远端的开瓶时间:
|
||||
// 情况 A: 远端 openedAt 比本地新(其他设备换了新瓶)
|
||||
// 情况 B: 本地 openedAt 比远端新,但本地是在这些用药记录产生后初始化的占位时间
|
||||
final bool hasRecordsBetween = allCurrentRecords.any(
|
||||
(r) => r.startTime.isAfter(rc.openedAt) && r.startTime.isBefore(lc.openedAt),
|
||||
);
|
||||
if (rc.openedAt.isAfter(lc.openedAt) || hasRecordsBetween) {
|
||||
lc.openedAt = rc.openedAt;
|
||||
}
|
||||
|
||||
lc.name = rc.name;
|
||||
lc.isEnabled = rc.isEnabled;
|
||||
lc.puffsPerSession = rc.puffsPerSession;
|
||||
@@ -201,12 +230,12 @@ class SyncService {
|
||||
await storageService.saveCanisters(currentCanisters);
|
||||
}
|
||||
|
||||
// 3. 核心核算:根据本地+云端汇总的全量流水,精准核算药瓶真实余量与使用次数
|
||||
// 4. 核心终极核算:严格由 active 药瓶 UUID 与全量流水确定性重算各药瓶喷数与开封时间
|
||||
await storageService.recalculateCanisterDoses();
|
||||
|
||||
// 4. 更新同步时间
|
||||
// 5. 更新同步时间戳
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyLastSync, DateTime.now().toIso8601String());
|
||||
await prefs.setString(_keyLastSync, DateTime.now().toUtc().toIso8601String());
|
||||
|
||||
return SyncResult(
|
||||
success: true,
|
||||
|
||||
Reference in New Issue
Block a user