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
+136
View File
@@ -0,0 +1,136 @@
import 'dart:convert';
import 'package:aero_track/models/dose_record.dart';
import 'package:aero_track/services/storage_service.dart';
import 'package:aero_track/services/sync_service.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() => SharedPreferences.setMockInitialValues({}));
Future<SyncResult> syncAgainst(
StorageService storage, {
required Map<String, dynamic> ping,
required Map<String, dynamic> Function() sync,
}) {
return http.runWithClient(
() => SyncService(storage).performSync(customUrl: 'http://test.local'),
() => MockClient((request) async {
final data = request.url.path == '/api/v1/ping' ? ping : sync();
return http.Response.bytes(utf8.encode(jsonEncode(data)), 200);
}),
);
}
test('恢复时以服务器实际药瓶为准并完整计算已用喷数', () async {
final storage = await StorageService.init();
final flix = storage.getActiveFlixotideBottle()!;
final opened = DateTime.utc(2026, 10, 29);
final result = await syncAgainst(
storage,
ping: {'sync_version': 2},
sync: () => {
'bottles': [
{
...flix.toMap(),
'openedAt': opened.toIso8601String(),
'updatedAt': '2020-01-01T00:00:00Z',
},
],
'canisters': storage
.getCanisters()
.map((item) => item.toMap())
.toList(),
'records': [
DoseRecord(
id: 'prior-bottle',
startTime: opened.subtract(const Duration(days: 1)),
endTime: opened.subtract(const Duration(days: 1)),
flixotidePuffs: 12,
flixotideBottleId: flix.id,
).toMap(),
DoseRecord(
id: 'current-bottle',
startTime: opened,
endTime: opened,
flixotidePuffs: 4,
flixotideBottleId: flix.id,
).toMap(),
],
},
);
expect(result.success, isTrue, reason: result.message);
expect(storage.getRecords(), hasLength(2));
expect(storage.getActiveFlixotideBottle()!.openedAt, opened);
expect(storage.getPrimaryFlixotide()!.remainingDoses, 56);
final reopened = await StorageService.init();
expect(reopened.getPrimaryFlixotide()!.remainingDoses, 56);
});
test('校准保留历史,只扣减校准后的用量', () async {
final storage = await StorageService.init();
final flix = storage.getActiveFlixotideBottle()!;
final cutoff = DateTime.utc(2026, 11, 25);
final result = await syncAgainst(
storage,
ping: {'sync_version': 2},
sync: () => {
'bottles': [
{
...flix.toMap(),
'calibratedAt': cutoff.toIso8601String(),
'calibratedRemainingDoses': 11,
},
],
'records': [
DoseRecord(
id: 'old',
startTime: cutoff.subtract(const Duration(minutes: 1)),
endTime: cutoff,
flixotidePuffs: 60,
flixotideBottleId: flix.id,
).toMap(),
],
},
);
expect(result.success, isTrue, reason: result.message);
expect(storage.getPrimaryFlixotide()!.remainingDoses, 11);
final after = cutoff.add(const Duration(minutes: 1));
await storage.addRecord(
DoseRecord(
id: 'new',
startTime: after,
endTime: after,
flixotidePuffs: 1,
flixotideBottleId: flix.id,
),
);
final reopened = await StorageService.init();
expect(reopened.getRecords(), hasLength(2));
expect(reopened.getPrimaryFlixotide()!.remainingDoses, 10);
});
test('旧服务器提示升级且不上传本地初始化数据', () async {
final storage = await StorageService.init();
var syncRequests = 0;
final result = await syncAgainst(
storage,
ping: {'status': 'ok'},
sync: () {
syncRequests++;
return {};
},
);
expect(result.success, isFalse);
expect(result.message, contains('服务器需要更新'));
expect(syncRequests, 0);
expect(await SyncService.getLastSyncTime(), isNull);
});
}
+137
View File
@@ -0,0 +1,137 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:aero_track/models/app_settings.dart';
import 'package:aero_track/models/dose_record.dart';
import 'package:aero_track/services/active_session_service.dart';
import 'package:aero_track/services/storage_service.dart';
// 模拟记录已写入,但后续步骤失败的可重试保存。
class FailAfterWriteStorage extends StorageService {
FailAfterWriteStorage(super.prefs);
bool failNext = true;
@override
Future<void> recalculateCanisterDoses() async {
await super.recalculateCanisterDoses();
if (failNext) {
failNext = false;
throw StateError('Simulated failure after persistence');
}
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final session = ActiveSessionService();
setUp(() {
session.cancelSession();
SharedPreferences.setMockInitialValues({});
});
tearDown(() => session.cancelSession());
void finishSession(StorageService storage) {
session.startNewSession(
medications: storage.getActiveCanisters(),
settings: AppSettings(
enableSound: false,
enableVibration: false,
enableVoicePrompt: false,
),
);
while (!session.isFinished) {
if (session.isWaitingForNextMed) {
session.startNextMedication();
} else {
session.completeCurrentStep();
}
}
}
DoseRecord record(StorageService storage, String id) {
final now = DateTime.now().toUtc();
return DoseRecord(
id: id,
startTime: now,
endTime: now,
flixotidePuffs: 2,
flixotideBottleId: storage.getActiveFlixotideBottle()!.id,
);
}
test('完成雾化保存后立即只扣一次,重算和重启均保持一致', () async {
final storage = await StorageService.init();
finishSession(storage);
await session.confirmAndSave(storage);
expect(storage.getRecords(), hasLength(1));
expect(storage.getPrimaryFlixotide()!.remainingDoses, 58);
expect(storage.getPrimaryVentolin()!.remainingDoses, 198);
await storage.recalculateCanisterDoses();
final reopened = await StorageService.init();
expect(reopened.getPrimaryFlixotide()!.remainingDoses, 58);
expect(reopened.getPrimaryVentolin()!.remainingDoses, 198);
});
test('并发和保存完成后的重复确认均只生成一条记录', () async {
final storage = await StorageService.init();
finishSession(storage);
final first = session.confirmAndSave(storage);
expect(session.isSaving, isTrue);
final second = session.confirmAndSave(storage);
expect(identical(first, second), isTrue);
await Future.wait([first, second]);
await session.confirmAndSave(storage);
expect(session.isSaving, isFalse);
expect(storage.getRecords(), hasLength(1));
expect(storage.getPrimaryFlixotide()!.remainingDoses, 58);
});
test('写入后失败重试仍使用同一记录,下一次会话使用新记录', () async {
await StorageService.init();
final storage = FailAfterWriteStorage(await SharedPreferences.getInstance());
finishSession(storage);
await expectLater(session.confirmAndSave(storage), throwsStateError);
final firstId = storage.getRecords().single.id;
expect(session.isSaving, isFalse);
expect(session.isActive, isTrue);
await session.confirmAndSave(storage);
expect(storage.getRecords().single.id, firstId);
expect(storage.getPrimaryFlixotide()!.remainingDoses, 58);
finishSession(storage);
await session.confirmAndSave(storage);
expect(storage.getRecords(), hasLength(2));
expect(storage.getPrimaryFlixotide()!.remainingDoses, 56);
});
test('相同记录 ID 顺序或并发提交均只入账一次', () async {
final storage = await StorageService.init();
final dose = record(storage, 'same-operation');
await Future.wait([storage.addRecord(dose), storage.addRecord(dose)]);
await storage.addRecord(dose);
expect(storage.getRecords(), hasLength(1));
expect(storage.getPrimaryFlixotide()!.remainingDoses, 58);
});
test('重试不能重新启用已删除的记录', () async {
final storage = await StorageService.init();
final dose = record(storage, 'deleted-operation');
await storage.addRecord(dose);
await storage.deleteRecord(dose.id);
await storage.addRecord(dose);
expect(storage.getRecords(), isEmpty);
expect(storage.getAllRecords(includeDeleted: true), hasLength(1));
expect(storage.getPrimaryFlixotide()!.remainingDoses, 60);
});
test('并发保存不同记录不会覆盖或丢失用量', () async {
final storage = await StorageService.init();
await Future.wait([
storage.addRecord(record(storage, 'operation-1')),
storage.addRecord(record(storage, 'operation-2')),
]);
expect(storage.getRecords(), hasLength(2));
expect(storage.getPrimaryFlixotide()!.remainingDoses, 56);
});
}