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