fix(sync): 修复多设备同步后药瓶使用次数与余量未扣减的问题,改由全量流水动态精准核算

This commit is contained in:
shen
2026-10-27 20:40:03 -07:00
parent 4d9df89a59
commit 065e219a83
3 changed files with 158 additions and 32 deletions
+41 -3
View File
@@ -16,11 +16,12 @@ class StorageService {
final prefs = await SharedPreferences.getInstance();
final service = StorageService(prefs);
await service._ensureInitialData();
await service.recalculateCanisterDoses();
return service;
}
Future<void> _ensureInitialData() async {
// 首次启动初始化默认药品
// 首次启动初始化默认药品 (使用早期占位时间,确保能完全继承云端开瓶时间与历史记录)
if (!_prefs.containsKey(_keyCanisters)) {
final defaultCanisters = [
Canister(
@@ -28,7 +29,7 @@ class StorageService {
name: '万托林 (硫酸沙丁胺醇)',
totalDoses: 200,
remainingDoses: 200,
openedAt: DateTime.now(),
openedAt: DateTime(2020, 1, 1),
isEnabled: true,
puffsPerSession: 2,
inhalationSeconds: 15,
@@ -41,7 +42,7 @@ class StorageService {
name: '辅舒酮 (丙酸氟替卡松)',
totalDoses: 60,
remainingDoses: 60,
openedAt: DateTime.now(),
openedAt: DateTime(2020, 1, 1),
isEnabled: true,
puffsPerSession: 2,
inhalationSeconds: 15,
@@ -153,11 +154,46 @@ class StorageService {
for (var c in canisters) {
if (c.id == canisterId) {
c.remainingDoses = newTotal;
c.openedAt = DateTime.now(); // 启用新瓶时更新开封时间戳
}
}
await saveCanisters(canisters);
}
/// 依据全部雾化流水历史记录,重新精准核算每个药瓶的真实剩余喷数
Future<void> recalculateCanisterDoses() async {
final canisters = getCanisters();
if (canisters.isEmpty) return;
final records = getRecords();
bool changed = false;
for (var c in canisters) {
// 统计自开封时间点以来的全部消耗喷数(留 1 分钟时钟误差裕量)
final validRecords = records.where((r) {
return !r.startTime.isBefore(c.openedAt.subtract(const Duration(minutes: 1)));
});
int consumedPuffs = 0;
for (var r in validRecords) {
if (c.isSteroid) {
consumedPuffs += r.flixotidePuffs;
} else {
consumedPuffs += r.ventolinPuffs;
}
}
final correctRemaining = (c.totalDoses - consumedPuffs).clamp(0, c.totalDoses);
if (c.remainingDoses != correctRemaining) {
c.remainingDoses = correctRemaining;
changed = true;
}
}
if (changed) {
await saveCanisters(canisters);
}
}
// ========== DoseRecords ==========
List<DoseRecord> getRecords() {
final raw = _prefs.getStringList(_keyRecords);
@@ -172,6 +208,7 @@ class StorageService {
records.insert(0, record);
final list = records.map((r) => r.toJson()).toList();
await _prefs.setStringList(_keyRecords, list);
await recalculateCanisterDoses();
}
Future<void> deleteRecord(String id) async {
@@ -179,5 +216,6 @@ class StorageService {
records.removeWhere((r) => r.id == id);
final list = records.map((r) => r.toJson()).toList();
await _prefs.setStringList(_keyRecords, list);
await recalculateCanisterDoses();
}
}
+45 -4
View File
@@ -115,6 +115,7 @@ class SyncService {
}
try {
await storageService.recalculateCanisterDoses();
final localRecords = storageService.getRecords();
final localCanisters = storageService.getCanisters();
final lastSync = await getLastSyncTime();
@@ -145,25 +146,65 @@ class SyncService {
final existingIds = localRecords.map((r) => r.id).toSet();
int newCount = 0;
final List<DoseRecord> newRecords = [];
for (var r in remoteRecords) {
if (!existingIds.contains(r.id)) {
await storageService.addRecord(r);
newRecords.add(r);
newCount++;
}
}
// 2. 合并远端药瓶状态到本地
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();
final prefs = await SharedPreferences.getInstance();
await prefs.setStringList('aerotrack_records', rawList);
}
// 2. 合并远端药瓶状态到本地 (智能继承开封时间)
final remoteCanistersRaw = data['canisters'] as List<dynamic>? ?? [];
final remoteCanisters = remoteCanistersRaw
.map((item) => Canister.fromMap(item as Map<String, dynamic>))
.toList();
if (remoteCanisters.isNotEmpty) {
await storageService.saveCanisters(remoteCanisters);
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;
lc.inhalationSeconds = rc.inhalationSeconds;
lc.sortOrder = rc.sortOrder;
lc.note = rc.note;
} else {
currentCanisters.add(rc);
}
}
await storageService.saveCanisters(currentCanisters);
}
// 3. 更新同步时间
// 3. 核心核算:根据本地+云端汇总的全量流水,精准核算药瓶真实余量与使用次数
await storageService.recalculateCanisterDoses();
// 4. 更新同步时间
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_keyLastSync, DateTime.now().toIso8601String());
+72 -25
View File
@@ -224,32 +224,79 @@ class SyncHandler(SimpleHTTPRequestHandler):
cid = c.get('id')
if not cid:
continue
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
remaining_doses = excluded.remaining_doses,
is_enabled = excluded.is_enabled,
puffs_per_session = excluded.puffs_per_session,
inhalation_seconds = excluded.inhalation_seconds,
updated_at = excluded.updated_at
''', (
cid,
c.get('name', ''),
c.get('totalDoses', 60),
c.get('remainingDoses', 60),
c.get('openedAt', now_str),
1 if c.get('isEnabled', True) else 0,
c.get('puffsPerSession', 2),
c.get('inhalationSeconds', 15),
1 if c.get('isSteroid', True) else 0,
c.get('sortOrder', 1),
c.get('note', ''),
now_str
))
incoming_opened_at = c.get('openedAt', now_str)
existing = conn.execute('SELECT * FROM canisters WHERE id = ?', (cid,)).fetchone()
if not existing:
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
cid,
c.get('name', ''),
c.get('totalDoses', 60),
c.get('remainingDoses', 60),
incoming_opened_at,
1 if c.get('isEnabled', True) else 0,
c.get('puffsPerSession', 2),
c.get('inhalationSeconds', 15),
1 if c.get('isSteroid', True) else 0,
c.get('sortOrder', 1),
c.get('note', ''),
now_str
))
else:
# 如果客户端开瓶时间更新(换了新药瓶),则更新开封时间戳
server_opened = existing['opened_at'] or ''
target_opened = incoming_opened_at if incoming_opened_at > server_opened else server_opened
conn.execute('''
UPDATE canisters SET
name = ?,
total_doses = ?,
opened_at = ?,
is_enabled = ?,
puffs_per_session = ?,
inhalation_seconds = ?,
sort_order = ?,
note = ?,
updated_at = ?
WHERE id = ?
''', (
c.get('name', existing['name']),
c.get('totalDoses', existing['total_doses']),
target_opened,
1 if c.get('isEnabled', existing['is_enabled']) else 0,
c.get('puffsPerSession', existing['puffs_per_session']),
c.get('inhalationSeconds', existing['inhalation_seconds']),
c.get('sortOrder', existing['sort_order']),
c.get('note', existing['note']),
now_str,
cid
))
# 3. 汇总拉取全量最新记录并返回给客户端
# 3. 依据全量真实流水账本,严格重新核算药瓶剩余喷数(彻底避免不同设备同步导致余量被旧缓存覆盖)
for can in conn.execute('SELECT * FROM canisters').fetchall():
cid = can['id']
is_steroid = can['is_steroid']
total_d = can['total_doses']
opened = can['opened_at'] or '1970-01-01'
if is_steroid:
res = conn.execute(
'SELECT SUM(flixotide_puffs) as s FROM dose_records WHERE start_time >= ?',
(opened,)
).fetchone()
else:
res = conn.execute(
'SELECT SUM(ventolin_puffs) as s FROM dose_records WHERE start_time >= ?',
(opened,)
).fetchone()
consumed = (res['s'] or 0) if res else 0
rem = max(0, total_d - consumed)
conn.execute('UPDATE canisters SET remaining_doses = ? WHERE id = ?', (rem, cid))
# 4. 汇总拉取全量最新记录并返回给客户端
all_records = []
for row in conn.execute('SELECT * FROM dose_records ORDER BY start_time DESC LIMIT 200'):
all_records.append({