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