feat: 重构局域网数据同步与物理药瓶生命周期(Bottle Entity),实现开新瓶、软删除与多端精确余量核算

This commit is contained in:
shen
2026-10-27 22:42:44 -07:00
parent 065e219a83
commit 89ab13ecf5
9 changed files with 699 additions and 208 deletions
+8 -2
View File
@@ -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);
+262 -41
View File
@@ -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();
}
}
}
+58 -29
View File
@@ -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,