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)
+89 -20
View File
@@ -68,6 +68,12 @@ def init_db():
)
''')
bottle_cols = {row['name'] for row in conn.execute("PRAGMA table_info(bottles)")}
if 'calibrated_remaining_doses' not in bottle_cols:
conn.execute('ALTER TABLE bottles ADD COLUMN calibrated_remaining_doses INTEGER')
if 'calibrated_at' not in bottle_cols:
conn.execute('ALTER TABLE bottles ADD COLUMN calibrated_at TEXT')
# 3. 吸入流水日志表 (UUID 主键,天然支持并发防重与软删除墓碑)
conn.execute('''
CREATE TABLE IF NOT EXISTS dose_records (
@@ -115,18 +121,27 @@ def init_db():
bottle_count = conn.execute('SELECT COUNT(*) as c FROM bottles').fetchone()['c']
if bottle_count == 0:
now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()
earliest_time = '2020-01-01T00:00:00Z'
conn.execute('''
INSERT INTO bottles (id, canister_id, name, sequence_number, total_doses, remaining_doses, opened_at, is_active, opened_by_device, updated_at)
VALUES ('flix_b1_initial', 'flixotide_primary', '辅舒酮 (丙酸氟替卡松)', 1, 60, 60, ?, 1, '系统初始化', ?)
''', (earliest_time, now_iso))
conn.execute('''
INSERT INTO bottles (id, canister_id, name, sequence_number, total_doses, remaining_doses, opened_at, is_active, opened_by_device, updated_at)
VALUES ('vent_b1_initial', 'ventolin_primary', '万托林 (硫酸沙丁胺醇)', 1, 200, 200, ?, 1, '系统初始化', ?)
''', (earliest_time, now_iso))
conn.execute("UPDATE dose_records SET flixotide_bottle_id = 'flix_b1_initial' WHERE flixotide_puffs > 0 AND flixotide_bottle_id IS NULL")
conn.execute("UPDATE dose_records SET ventolin_bottle_id = 'vent_b1_initial' WHERE ventolin_puffs > 0 AND ventolin_bottle_id IS NULL")
for bottle_id, canister_id, column, name, capacity in (
('flix_b1_initial', 'flixotide_primary', 'flixotide', '辅舒酮 (丙酸氟替卡松)', 60),
('vent_b1_initial', 'ventolin_primary', 'ventolin', '万托林 (硫酸沙丁胺醇)', 200),
):
legacy = conn.execute('SELECT * FROM canisters WHERE id = ?', (canister_id,)).fetchone()
opened_at = (legacy['opened_at'] if legacy else None) or '2020-01-01T00:00:00Z'
if legacy:
capacity = legacy['total_doses']
name = legacy['name']
conn.execute("""
INSERT INTO bottles (id, canister_id, name, sequence_number, total_doses,
remaining_doses, opened_at, is_active, opened_by_device, updated_at)
VALUES (?, ?, ?, 1, ?, ?, ?, 1, '系统初始化', ?)
""", (bottle_id, canister_id, name, capacity,
legacy['remaining_doses'] if legacy else capacity, opened_at, now_iso))
# 旧版只保存当前瓶的开瓶时间。更早的流水保留为历史,不能扣到当前瓶。
conn.execute(f"""
UPDATE dose_records SET {column}_bottle_id = ?
WHERE {column}_puffs > 0 AND {column}_bottle_id IS NULL
AND julianday(start_time) >= julianday(?)
""", (bottle_id, opened_at))
conn.execute("UPDATE dose_records SET updated_at = ? WHERE updated_at IS NULL", (now_iso,))
# 6. 若 canisters 为空,初始化基础配置
@@ -210,6 +225,7 @@ class SyncHandler(SimpleHTTPRequestHandler):
self._send_json(200, {
'status': 'ok',
'service': 'AeroTrack LAN Sync Server',
'sync_version': 2,
'timestamp': datetime.datetime.now(datetime.timezone.utc).isoformat()
})
return
@@ -314,7 +330,8 @@ class SyncHandler(SimpleHTTPRequestHandler):
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (bid, cid, bname, seq, td, td, op_at, fin_at, is_act, dev, up_at))
else:
if up_at >= (existing_b['updated_at'] or '') or (not is_act and existing_b['is_active']):
# 归档是单向操作,重装客户端不能用初始化数据重新激活旧瓶。
if not is_act and (existing_b['is_active'] or up_at >= (existing_b['updated_at'] or '')):
conn.execute('''
UPDATE bottles SET
finished_at = COALESCE(?, finished_at),
@@ -323,6 +340,19 @@ class SyncHandler(SimpleHTTPRequestHandler):
WHERE id = ?
''', (fin_at, is_act, up_at, bid))
# 修复已出现的多活跃瓶,同一药品保留最新的一瓶。
active_by_canister = {}
for bottle in conn.execute("""
SELECT * FROM bottles WHERE is_active = 1
ORDER BY canister_id, sequence_number DESC, julianday(opened_at) DESC, id DESC
""").fetchall():
current = active_by_canister.setdefault(bottle['canister_id'], bottle)
if current['id'] != bottle['id']:
conn.execute("""
UPDATE bottles SET is_active = 0, finished_at = COALESCE(finished_at, ?),
updated_at = ? WHERE id = ?
""", (current['opened_at'], now_str, bottle['id']))
# 3. 接收客户端推上来的用药记录 (UUID 幂等入库 + 软删除墓碑同步)
incoming_records = payload.get('records', [])
for r in incoming_records:
@@ -483,20 +513,34 @@ class SyncHandler(SimpleHTTPRequestHandler):
cid = b['canister_id']
td = b['total_doses']
is_steroid = 1 if 'flix' in cid else 0
initial = bid in ('flix_b1_initial', 'vent_b1_initial')
baseline = b['calibrated_remaining_doses']
cutoff = b['calibrated_at']
if is_steroid:
res = conn.execute('''
SELECT SUM(flixotide_puffs) as s FROM dose_records
WHERE is_deleted = 0 AND (flixotide_bottle_id = ? OR (flixotide_bottle_id IS NULL AND start_time >= ?))
''', (bid, b['opened_at'])).fetchone()
WHERE is_deleted = 0
AND (? IS NULL OR julianday(start_time) > julianday(?)) AND ((flixotide_bottle_id = ?
AND (? = 0 OR julianday(start_time) >= julianday(?)))
OR (flixotide_bottle_id IS NULL
AND julianday(start_time) >= julianday(?)
AND (? IS NULL OR julianday(start_time) < julianday(?))))
''', (cutoff, cutoff, bid, initial, b['opened_at'], b['opened_at'], b['finished_at'], b['finished_at'])).fetchone()
else:
res = conn.execute('''
SELECT SUM(ventolin_puffs) as s FROM dose_records
WHERE is_deleted = 0 AND (ventolin_bottle_id = ? OR (ventolin_bottle_id IS NULL AND start_time >= ?))
''', (bid, b['opened_at'])).fetchone()
WHERE is_deleted = 0
AND (? IS NULL OR julianday(start_time) > julianday(?)) AND ((ventolin_bottle_id = ?
AND (? = 0 OR julianday(start_time) >= julianday(?)))
OR (ventolin_bottle_id IS NULL
AND julianday(start_time) >= julianday(?)
AND (? IS NULL OR julianday(start_time) < julianday(?))))
''', (cutoff, cutoff, bid, initial, b['opened_at'], b['opened_at'], b['finished_at'], b['finished_at'])).fetchone()
consumed = (res['s'] or 0) if res else 0
rem = max(0, td - consumed)
rem = max(0, (td if baseline is None else baseline) - consumed)
conn.execute('UPDATE bottles SET remaining_doses = ? WHERE id = ?', (rem, bid))
# 若是当前在用活跃瓶,同步确保并更新 canisters 方案余量
@@ -504,12 +548,13 @@ class SyncHandler(SimpleHTTPRequestHandler):
conn.execute('''
INSERT INTO canisters (id, name, total_doses, remaining_doses, opened_at, is_enabled, puffs_per_session, inhalation_seconds, is_steroid, sort_order, note, updated_at)
VALUES (?, ?, ?, ?, ?, 1, 2, 15, ?, 1, '', ?)
ON CONFLICT(id) DO UPDATE SET remaining_doses = excluded.remaining_doses, opened_at = excluded.opened_at
ON CONFLICT(id) DO UPDATE SET total_doses = excluded.total_doses,
remaining_doses = excluded.remaining_doses, opened_at = excluded.opened_at
''', (cid, b['name'], td, rem, b['opened_at'], is_steroid, now_str))
# 6. 汇总全量数据响应客户端
all_records = []
for row in conn.execute('SELECT * FROM dose_records ORDER BY start_time DESC LIMIT 300'):
for row in conn.execute('SELECT * FROM dose_records ORDER BY start_time DESC, id'):
all_records.append({
'id': row['id'],
'startTime': row['start_time'],
@@ -538,6 +583,8 @@ class SyncHandler(SimpleHTTPRequestHandler):
'remainingDoses': row['remaining_doses'],
'openedAt': row['opened_at'],
'finishedAt': row['finished_at'],
'calibratedRemainingDoses': row['calibrated_remaining_doses'],
'calibratedAt': row['calibrated_at'],
'isActive': bool(row['is_active']),
'openedByDevice': row['opened_by_device'],
'updatedAt': row['updated_at']
@@ -807,7 +854,29 @@ class SyncHandler(SimpleHTTPRequestHandler):
self.end_headers()
self.wfile.write(encoded)
def calibrate_bottle(bottle_id, remaining):
"""Record a physical count without changing any usage records."""
with get_db() as conn:
conn.execute('BEGIN IMMEDIATE')
bottle = conn.execute('SELECT * FROM bottles WHERE id = ? AND is_active = 1',
(bottle_id,)).fetchone()
if bottle is None or not 0 <= remaining <= bottle['total_doses']:
raise ValueError('Expected an active bottle and a valid remaining dose count')
now = datetime.datetime.now(datetime.timezone.utc).isoformat()
conn.execute("""
UPDATE bottles SET calibrated_at = ?, calibrated_remaining_doses = ?,
remaining_doses = ?, updated_at = ? WHERE id = ?
""", (now, remaining, remaining, now, bottle_id))
conn.execute('UPDATE canisters SET remaining_doses = ? WHERE id = ?',
(remaining, bottle['canister_id']))
return now
def main():
if len(sys.argv) == 4 and sys.argv[1] == '--calibrate-bottle':
timestamp = calibrate_bottle(sys.argv[2], int(sys.argv[3]))
print(f'Calibrated {sys.argv[2]} to {sys.argv[3]} at {timestamp}')
return
port = int(os.environ.get('PORT', 8090))
if len(sys.argv) > 1:
try:
+85
View File
@@ -336,5 +336,90 @@ class ServerIntegrationTestCase(unittest.TestCase):
self.assertIn('家庭智能药箱健康与保质期监控', html)
self.assertIn('美林', html)
class RestoreRegressionTests(unittest.TestCase):
def setUp(self):
temp_dir = tempfile.TemporaryDirectory()
self.addCleanup(temp_dir.cleanup)
self.addCleanup(setattr, server, 'DB_FILE', server.DB_FILE)
server.DB_FILE = os.path.join(temp_dir.name, 'restore.db')
server.init_db()
def sync(self, **payload):
handler = object.__new__(server.SyncHandler)
handler.client_address = ('127.0.0.1', 0)
result = {}
handler._send_json = lambda status, data: result.update(data)
handler._handle_sync(payload)
return result
def test_restore_preserves_archived_bottle_and_repairs_multiple_active_bottles(self):
opened = '2026-10-29T00:00:00Z'
initial = dict(id='flix_b1_initial', canisterId='flixotide_primary',
isActive=True, updatedAt='2099-01-01T00:00:00Z')
current = dict(id='flix_b2_restore', canisterId='flixotide_primary', sequenceNumber=2,
totalDoses=60, openedAt=opened, updatedAt=opened)
self.sync(bottles=[current], records=[
dict(id='used', startTime=opened, endTime=opened, flixotidePuffs=4,
flixotideBottleId=current['id'])
])
result = self.sync(bottles=[initial])
flix = [b for b in result['bottles'] if b['canisterId'] == 'flixotide_primary']
self.assertEqual([b['id'] for b in flix if b['isActive']], [current['id']])
self.assertEqual(flix[1]['remainingDoses'], 56)
def test_calibration_keeps_history_and_only_deducts_later_records(self):
self.sync(records=[dict(id='old', startTime='2026-10-29T00:00:00Z',
flixotidePuffs=60, flixotideBottleId='flix_b1_initial')])
cutoff = datetime.datetime.fromisoformat(server.calibrate_bottle('flix_b1_initial', 11))
result = self.sync()
self.assertEqual(len(result['records']), 1)
bottle = next(b for b in result['bottles'] if b['id'] == 'flix_b1_initial')
self.assertEqual(bottle['remainingDoses'], 11)
self.assertEqual(bottle['calibratedRemainingDoses'], 11)
when = (cutoff + datetime.timedelta(minutes=1)).isoformat()
result = self.sync(records=[dict(id='new', startTime=when, flixotidePuffs=1,
flixotideBottleId='flix_b1_initial')])
bottle = next(b for b in result['bottles'] if b['id'] == 'flix_b1_initial')
self.assertEqual(bottle['remainingDoses'], 10)
self.assertEqual(len(result['records']), 2)
def test_restore_returns_records_beyond_previous_limit(self):
date = datetime.datetime(2026, 10, 29, tzinfo=datetime.timezone.utc)
records = []
for i in range(301):
when = (date + datetime.timedelta(minutes=i)).isoformat()
records.append(dict(id=f'r-{i}', startTime=when, endTime=when,
ventolinPuffs=2 if i == 0 else 0))
self.sync(records=records)
result = self.sync()
self.assertEqual(len(result['records']), 301)
self.assertEqual(sum(r['ventolinPuffs'] for r in result['records']), 2)
def test_legacy_migration_uses_actual_opening_and_retains_old_history(self):
conn = server.get_db()
with conn:
conn.execute('DROP TABLE bottles')
conn.execute("""
UPDATE canisters SET opened_at = '2026-10-29T08:00:00', remaining_doses = 58
WHERE id = 'flixotide_primary'
""")
for rec_id, when in [('previous', '2026-10-28T09:00:00'),
('current', '2026-10-29T09:00:00')]:
conn.execute("""
INSERT INTO dose_records (id, start_time, end_time, flixotide_puffs, created_at)
VALUES (?, ?, ?, 2, ?)
""", (rec_id, when, when, when))
conn.close()
server.init_db()
result = self.sync()
bottle = next(b for b in result['bottles'] if b['id'] == 'flix_b1_initial')
self.assertEqual(bottle['openedAt'], '2026-10-29T08:00:00')
self.assertEqual(bottle['remainingDoses'], 58)
records = {r['id']: r for r in result['records']}
self.assertIsNone(records['previous']['flixotideBottleId'])
self.assertEqual(records['current']['flixotideBottleId'], bottle['id'])
if __name__ == '__main__':
unittest.main()
+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);
});
}