fix(sync): 修复多设备同步后药瓶使用次数与余量未扣减的问题,改由全量流水动态精准核算

This commit is contained in:
shen
2026-10-27 20:40:03 -07:00
parent 4d9df89a59
commit 065e219a83
3 changed files with 158 additions and 32 deletions
+45 -4
View File
@@ -115,6 +115,7 @@ class SyncService {
}
try {
await storageService.recalculateCanisterDoses();
final localRecords = storageService.getRecords();
final localCanisters = storageService.getCanisters();
final lastSync = await getLastSyncTime();
@@ -145,25 +146,65 @@ class SyncService {
final existingIds = localRecords.map((r) => r.id).toSet();
int newCount = 0;
final List<DoseRecord> newRecords = [];
for (var r in remoteRecords) {
if (!existingIds.contains(r.id)) {
await storageService.addRecord(r);
newRecords.add(r);
newCount++;
}
}
// 2. 合并远端药瓶状态到本地
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();
final prefs = await SharedPreferences.getInstance();
await prefs.setStringList('aerotrack_records', rawList);
}
// 2. 合并远端药瓶状态到本地 (智能继承开封时间)
final remoteCanistersRaw = data['canisters'] as List<dynamic>? ?? [];
final remoteCanisters = remoteCanistersRaw
.map((item) => Canister.fromMap(item as Map<String, dynamic>))
.toList();
if (remoteCanisters.isNotEmpty) {
await storageService.saveCanisters(remoteCanisters);
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;
lc.inhalationSeconds = rc.inhalationSeconds;
lc.sortOrder = rc.sortOrder;
lc.note = rc.note;
} else {
currentCanisters.add(rc);
}
}
await storageService.saveCanisters(currentCanisters);
}
// 3. 更新同步时间
// 3. 核心核算:根据本地+云端汇总的全量流水,精准核算药瓶真实余量与使用次数
await storageService.recalculateCanisterDoses();
// 4. 更新同步时间
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_keyLastSync, DateTime.now().toIso8601String());