feat: 重构局域网数据同步与物理药瓶生命周期(Bottle Entity),实现开新瓶、软删除与多端精确余量核算
This commit is contained in:
@@ -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