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
+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();
}
}