fix(sync): 修复喷数重复扣减与重装恢复,支持余量校准

This commit is contained in:
shen
2026-11-25 03:43:24 -08:00
parent d322ae4d87
commit daccb4c04c
10 changed files with 576 additions and 123 deletions
+8
View File
@@ -10,6 +10,8 @@ class Bottle {
DateTime? finishedAt; // 严格 UTC 用尽/归档时间
bool isActive; // 是否为当前正在使用的活跃药瓶
final String openedByDevice; // 开瓶操作的设备名称
final int? calibratedRemainingDoses;
final DateTime? calibratedAt;
DateTime updatedAt; // 严格 UTC 更新时间戳 (用于多端 LWW 冲突解决)
Bottle({
@@ -20,6 +22,8 @@ class Bottle {
required this.totalDoses,
required this.openedAt,
this.finishedAt,
this.calibratedRemainingDoses,
this.calibratedAt,
this.isActive = true,
this.openedByDevice = '本机',
DateTime? updatedAt,
@@ -36,6 +40,8 @@ class Bottle {
'finishedAt': finishedAt?.toUtc().toIso8601String(),
'isActive': isActive,
'openedByDevice': openedByDevice,
'calibratedRemainingDoses': calibratedRemainingDoses,
'calibratedAt': calibratedAt?.toUtc().toIso8601String(),
'updatedAt': updatedAt.toUtc().toIso8601String(),
};
}
@@ -53,6 +59,8 @@ class Bottle {
: (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? ?? '家庭设备'),
calibratedRemainingDoses: map['calibratedRemainingDoses'] as int?,
calibratedAt: DateTime.tryParse(map['calibratedAt'] as String? ?? '')?.toUtc(),
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()),
-4
View File
@@ -227,12 +227,10 @@ class _HomeScreenState extends State<HomeScreen> {
);
if (confirmed == true && _activeCanisters.isNotEmpty) {
final Map<String, int> deductions = {};
int flixotideDoses = 0;
int ventolinDoses = 0;
for (var c in _activeCanisters) {
deductions[c.id] = c.puffsPerSession;
if (c.isSteroid) {
flixotideDoses += c.puffsPerSession;
} else {
@@ -255,7 +253,6 @@ class _HomeScreenState extends State<HomeScreen> {
updatedAt: nowUtc,
);
await widget.storageService.deductSessionDoses(deductions);
await widget.storageService.addRecord(record);
_loadData();
SyncService(widget.storageService).syncSilently();
@@ -297,7 +294,6 @@ class _HomeScreenState extends State<HomeScreen> {
note: '${canister.name.split(" ")[0]}试喷',
updatedAt: nowUtc,
);
await widget.storageService.deductSessionDoses({canister.id: 1});
await widget.storageService.addRecord(record);
_loadData();
SyncService(widget.storageService).syncSilently();
+17 -5
View File
@@ -78,9 +78,18 @@ class _SessionScreenState extends State<SessionScreen> {
}
Future<void> _saveAndExit() async {
await _sessionService.confirmAndSave(widget.storageService);
if (mounted) {
Navigator.of(context).pop(true);
if (_sessionService.isSaving) return;
try {
await _sessionService.confirmAndSave(widget.storageService);
if (mounted) {
Navigator.of(context).pop(true);
}
} catch (_) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('保存失败,请重试')),
);
}
}
}
@@ -640,14 +649,17 @@ class _SessionScreenState extends State<SessionScreen> {
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _saveAndExit,
onPressed: _sessionService.isSaving ? null : _saveAndExit,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF0F172A),
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
),
child: const Text('确认并保存记录', style: TextStyle(fontWeight: FontWeight.bold)),
child: Text(
_sessionService.isSaving ? '保存中…' : '确认并保存记录',
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
),
],
+30 -9
View File
@@ -59,10 +59,13 @@ class ActiveSessionService extends ChangeNotifier {
bool _washedFace = true;
AppSettings? _settings;
Future<void>? _saveFuture;
DoseRecord? _pendingRecord;
// Getters
bool get isActive => _isActive;
bool get isFinished => _isFinished;
bool get isSaving => _saveFuture != null;
bool get isWaitingForNextMed => _isWaitingForNextMed;
List<Canister> get activeMedications => _activeMedications;
List<SessionStep> get steps => _steps;
@@ -94,6 +97,8 @@ class ActiveSessionService extends ChangeNotifier {
required List<Canister> medications,
required AppSettings settings,
}) {
if (isSaving) return;
_pendingRecord = null;
// 强制临床顺序:万托林 (支气管舒张剂,非激素) 严格排在第一位,辅舒酮 (激素) 排在第二位
final sortedMeds = List<Canister>.from(medications);
sortedMeds.sort((a, b) {
@@ -299,13 +304,34 @@ class ActiveSessionService extends ChangeNotifier {
}
// 结算并保存记录
Future<void> confirmAndSave(StorageService storageService) async {
final Map<String, int> deductions = {};
Future<void> confirmAndSave(StorageService storageService) {
final saving = _saveFuture;
if (saving != null) return saving;
if (!_isActive || !_isFinished) return Future<void>.value();
final future = Future<void>.microtask(() => _saveRecord(storageService));
_saveFuture = future;
notifyListeners();
return future;
}
Future<void> _saveRecord(StorageService storageService) async {
try {
// 重试沿用同一记录,避免写入成功但后续失败时生成第二笔流水。
_pendingRecord ??= _buildRecord(storageService);
await storageService.addRecord(_pendingRecord!);
cancelSession();
} finally {
_saveFuture = null;
notifyListeners();
}
}
DoseRecord _buildRecord(StorageService storageService) {
int totalFlixotide = 0;
int totalVentolin = 0;
for (var med in _activeMedications) {
deductions[med.id] = med.puffsPerSession;
if (med.isSteroid) {
totalFlixotide += med.puffsPerSession;
} else {
@@ -316,7 +342,7 @@ class ActiveSessionService extends ChangeNotifier {
final activeFlix = storageService.getActiveFlixotideBottle();
final activeVent = storageService.getActiveVentolinBottle();
final record = DoseRecord(
return DoseRecord(
id: const Uuid().v4(),
startTime: (_sessionStartTime ?? DateTime.now()).toUtc(),
endTime: (_sessionEndTime ?? DateTime.now()).toUtc(),
@@ -328,10 +354,5 @@ class ActiveSessionService extends ChangeNotifier {
washedFace: _washedFace,
updatedAt: DateTime.now().toUtc(),
);
await storageService.addRecord(record);
await storageService.deductSessionDoses(deductions);
cancelSession();
}
}
+41 -34
View File
@@ -15,6 +15,7 @@ class StorageService {
static const String _keyMedicines = 'aerotrack_medicines';
final SharedPreferences _prefs;
Future<void> _recordWrite = Future<void>.value();
StorageService(this._prefs);
@@ -72,7 +73,7 @@ class StorageService {
openedAt: DateTime(2020, 1, 1).toUtc(),
isActive: true,
openedByDevice: '系统初始化',
updatedAt: DateTime.now().toUtc(),
updatedAt: DateTime.utc(2020),
);
final initialVentBottle = Bottle(
@@ -84,7 +85,7 @@ class StorageService {
openedAt: DateTime(2020, 1, 1).toUtc(),
isActive: true,
openedByDevice: '系统初始化',
updatedAt: DateTime.now().toUtc(),
updatedAt: DateTime.utc(2020),
);
await saveBottles([initialFlixBottle, initialVentBottle]);
@@ -207,7 +208,12 @@ class StorageService {
if (raw == null) return [];
try {
final list = raw.map((item) => Bottle.fromJson(item)).toList();
list.sort((a, b) => a.sequenceNumber.compareTo(b.sequenceNumber));
list.sort((a, b) {
final sequence = a.sequenceNumber.compareTo(b.sequenceNumber);
if (sequence != 0) return sequence;
final opening = a.openedAt.compareTo(b.openedAt);
return opening != 0 ? opening : a.id.compareTo(b.id);
});
return list;
} catch (_) {
return [];
@@ -222,7 +228,7 @@ class StorageService {
Bottle? getActiveBottle(String canisterId) {
final bottles = getBottles();
try {
return bottles.firstWhere((b) => b.canisterId == canisterId && b.isActive);
return bottles.lastWhere((b) => b.canisterId == canisterId && b.isActive);
} catch (_) {
final matched = bottles.where((b) => b.canisterId == canisterId).toList();
return matched.isNotEmpty ? matched.last : null;
@@ -347,29 +353,6 @@ class StorageService {
await saveCanisters(canisters);
}
Future<void> deductSessionDoses(Map<String, int> deductions) async {
final canisters = getCanisters();
for (var c in canisters) {
if (deductions.containsKey(c.id)) {
final used = deductions[c.id]!;
c.remainingDoses = (c.remainingDoses - used).clamp(0, c.totalDoses);
}
}
await saveCanisters(canisters);
}
Future<void> deductDoses({int flixotideDoses = 0, int ventolinDoses = 0}) async {
final canisters = getCanisters();
for (var c in canisters) {
if (c.isSteroid && flixotideDoses > 0) {
c.remainingDoses = (c.remainingDoses - flixotideDoses).clamp(0, c.totalDoses);
} else if (!c.isSteroid && ventolinDoses > 0) {
c.remainingDoses = (c.remainingDoses - ventolinDoses).clamp(0, c.totalDoses);
}
}
await saveCanisters(canisters);
}
Future<void> resetCanisterDoses(String canisterId, int newTotal, {String deviceName = '本机'}) async {
await openNewBottle(canisterId, deviceName: deviceName);
}
@@ -386,7 +369,17 @@ class StorageService {
int consumedPuffs = 0;
if (activeBottle != null) {
final isInitialBottle = activeBottle.id == 'flix_b1_initial' ||
activeBottle.id == 'vent_b1_initial';
final calibrationTime = activeBottle.calibratedAt;
for (var r in records) {
if (calibrationTime != null && !r.startTime.isAfter(calibrationTime)) {
continue;
}
// 旧版本可能已将换瓶前的记录绑定到固定的初始瓶 ID。
if (isInitialBottle && r.startTime.isBefore(activeBottle.openedAt)) {
continue;
}
if (c.isSteroid) {
// 优先依据明确绑定的 bottleId 核算
if (r.flixotideBottleId == activeBottle.id) {
@@ -404,7 +397,8 @@ class StorageService {
}
}
final correctRemaining = (activeBottle.totalDoses - consumedPuffs).clamp(0, activeBottle.totalDoses);
final baseline = activeBottle.calibratedRemainingDoses ?? activeBottle.totalDoses;
final correctRemaining = (baseline - consumedPuffs).clamp(0, activeBottle.totalDoses);
if (c.remainingDoses != correctRemaining || c.openedAt != activeBottle.openedAt) {
c.remainingDoses = correctRemaining;
c.openedAt = activeBottle.openedAt;
@@ -450,12 +444,25 @@ class StorageService {
}
}
Future<void> addRecord(DoseRecord record) async {
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> addRecord(DoseRecord record) {
final write = _recordWrite.then((_) async {
final records = getAllRecords(includeDeleted: true);
// 同一操作只入账一次,已删除的记录也不能被重试重新启用。
if (!records.any((existing) => existing.id == record.id)) {
records.insert(0, record);
final list = records.map((r) => r.toJson()).toList();
if (!await _prefs.setStringList(_keyRecords, list)) {
throw StateError('用药记录保存失败');
}
}
await recalculateCanisterDoses();
});
// 写入失败仍允许后续重试;调用方通过 write 接收原始错误。
_recordWrite = write.then<void>(
(_) {},
onError: (Object error, StackTrace stack) {},
);
return write;
}
/// 软删除记录(墓碑机制):全网标记废弃,喷数自动准确恢复
+33 -51
View File
@@ -108,15 +108,21 @@ class SyncService {
final deviceName = await getDeviceName();
final deviceId = await getDeviceId();
final pingMs = await pingServer(baseUrl);
if (pingMs == null) {
return SyncResult(
success: false,
message: '无法连接局域网服务器 ($baseUrl),请检查 Wi-Fi 或 IP 地址',
);
}
try {
final stopwatch = Stopwatch()..start();
final ping = await http
.get(Uri.parse('$baseUrl/api/v1/ping'))
.timeout(const Duration(seconds: 3));
final pingMs = stopwatch.elapsedMilliseconds;
if (ping.statusCode != 200) {
return SyncResult(success: false, message: '服务器连接检查失败');
}
final capabilities = jsonDecode(utf8.decode(ping.bodyBytes));
final syncVersion = capabilities is Map ? capabilities['sync_version'] : null;
if (syncVersion is! int || syncVersion < 2) {
return SyncResult(success: false, message: '同步服务器需要更新,才能恢复药瓶和完整用药记录');
}
await storageService.recalculateCanisterDoses();
final localRecords = storageService.getAllRecords(includeDeleted: true);
final localBottles = storageService.getBottles();
@@ -145,38 +151,26 @@ class SyncService {
final data = json.decode(utf8.decode(res.bodyBytes)) as Map<String, dynamic>;
// 1. 合并远端药瓶生命周期实体 Bottles
final remoteBottlesRaw = data['bottles'] as List<dynamic>? ?? [];
final remoteBottles = remoteBottlesRaw
final remoteBottles = (data['bottles'] as List<dynamic>)
.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
final remoteRecords = (data['records'] as List<dynamic>)
.map((item) => DoseRecord.fromMap(item as Map<String, dynamic>))
.toList();
final sentBottles = {for (final bottle in localBottles) bottle.id: bottle.toJson()};
final bottles = {for (final bottle in storageService.getBottles()) bottle.id: bottle};
for (final remote in remoteBottles) {
final local = bottles[remote.id];
// 服务器已合并这次提交。只保留请求发出后才发生的本地换瓶。
if (local == null || local.toJson() == sentBottles[remote.id]) {
bottles[remote.id] = remote;
}
}
await storageService.saveBottles(bottles.values.toList());
// 2. 双向合并全量流水记录 (含软删除墓碑同步)
final allLocalRecords = storageService.getAllRecords(includeDeleted: true);
final localRecordMap = {for (var r in allLocalRecords) r.id: r};
int newCount = 0;
@@ -214,23 +208,11 @@ class SyncService {
.toList();
if (remoteCanisters.isNotEmpty) {
final currentCanisters = storageService.getCanisters();
final localMap = {for (var c in currentCanisters) c.id: c};
for (var rc in remoteCanisters) {
final lc = localMap[rc.id];
if (lc != null) {
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);
final canisters = {
for (final local in storageService.getCanisters()) local.id: local,
for (final remote in remoteCanisters) remote.id: remote,
};
await storageService.saveCanisters(canisters.values.toList());
}
// 3.5. 合并远端家庭药箱药品数据 (Medicines)