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: