feat: 增加全家庭智能药箱功能,支持扫码识别(追溯码/GS1/条形码)、出厂有效期与开封保质期双轨追踪及局域网多设备同步

This commit is contained in:
shen
2026-10-27 23:56:47 -07:00
parent ba32e29682
commit 113794fa4b
15 changed files with 2934 additions and 9 deletions
+215 -6
View File
@@ -141,6 +141,29 @@ def init_db():
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 ('flixotide_primary', '辅舒酮 (丙酸氟替卡松)', 60, 60, '2020-01-01T00:00:00Z', 1, 2, 15, 1, 2, '糖皮质激素', ?)
''', (now_iso,))
# 7. 家庭智能药箱全量管理表
conn.execute('''
CREATE TABLE IF NOT EXISTS medicines (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
category TEXT NOT NULL,
spec TEXT,
storage_location TEXT,
target_user TEXT,
barcode TEXT,
batch_number TEXT,
production_date TEXT,
expiry_date TEXT NOT NULL,
shelf_life_days_after_opening INTEGER,
is_opened INTEGER DEFAULT 0,
opened_at TEXT,
opened_by_device TEXT,
notes TEXT,
is_deleted INTEGER DEFAULT 0,
updated_at TEXT NOT NULL
)
''')
conn.close()
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
@@ -210,17 +233,25 @@ class SyncHandler(SimpleHTTPRequestHandler):
})
return
# 3. 监控看板
# 3. 药品条码/追溯码信息查询接口
if self.path.startswith('/api/v1/medicine/lookup'):
from urllib.parse import urlparse, parse_qs
query = parse_qs(urlparse(self.path).query)
code = query.get('code', [''])[0].strip()
self._handle_medicine_lookup(code)
return
# 4. 监控看板
if self.path == '/dashboard' or self.path == '/dashboard/':
self._render_dashboard()
return
# 4. 静态 Web 端(Flutter Web 产物)
# 5. 静态 Web 端(Flutter Web 产物)
if os.path.isdir(WEB_DIR):
super().do_GET()
return
# 5. 若未编译 Flutter Web,则默认展示监控面板
# 6. 若未编译 Flutter Web,则默认展示监控面板
if self.path == '/' or self.path == '/index.html':
self._render_dashboard()
return
@@ -283,10 +314,10 @@ 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 ''):
if up_at >= (existing_b['updated_at'] or '') or (not is_act and existing_b['is_active']):
conn.execute('''
UPDATE bottles SET
finished_at = ?,
finished_at = COALESCE(?, finished_at),
is_active = ?,
updated_at = ?
WHERE id = ?
@@ -370,6 +401,82 @@ class SyncHandler(SimpleHTTPRequestHandler):
now_str
))
# 4.5. 接收客户端家庭药箱数据 (Medicines)
incoming_medicines = payload.get('medicines', [])
for m in incoming_medicines:
mid = m.get('id')
if not mid:
continue
up_at = m.get('updatedAt', now_str)
is_del = 1 if m.get('isDeleted', False) else 0
is_open = 1 if m.get('isOpened', False) else 0
existing_m = conn.execute('SELECT * FROM medicines WHERE id = ?', (mid,)).fetchone()
if not existing_m:
conn.execute('''
INSERT INTO medicines
(id, name, category, spec, storage_location, target_user, barcode, batch_number, production_date, expiry_date, shelf_life_days_after_opening, is_opened, opened_at, opened_by_device, notes, is_deleted, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
mid,
m.get('name', '未命名药品'),
m.get('category', 'other'),
m.get('spec', ''),
m.get('storageLocation', '常温药箱'),
m.get('targetUser', '全家'),
m.get('barcode'),
m.get('batchNumber'),
m.get('productionDate'),
m.get('expiryDate', now_str),
m.get('shelfLifeDaysAfterOpening'),
is_open,
m.get('openedAt'),
m.get('openedByDevice'),
m.get('notes', ''),
is_del,
up_at
))
else:
if up_at >= (existing_m['updated_at'] or ''):
conn.execute('''
UPDATE medicines SET
name = ?,
category = ?,
spec = ?,
storage_location = ?,
target_user = ?,
barcode = ?,
batch_number = ?,
production_date = ?,
expiry_date = ?,
shelf_life_days_after_opening = ?,
is_opened = ?,
opened_at = ?,
opened_by_device = ?,
notes = ?,
is_deleted = ?,
updated_at = ?
WHERE id = ?
''', (
m.get('name', existing_m['name']),
m.get('category', existing_m['category']),
m.get('spec', existing_m['spec']),
m.get('storageLocation', existing_m['storage_location']),
m.get('targetUser', existing_m['target_user']),
m.get('barcode', existing_m['barcode']),
m.get('batchNumber', existing_m['batch_number']),
m.get('productionDate', existing_m['production_date']),
m.get('expiryDate', existing_m['expiry_date']),
m.get('shelfLifeDaysAfterOpening', existing_m['shelf_life_days_after_opening']),
is_open,
m.get('openedAt', existing_m['opened_at']),
m.get('openedByDevice', existing_m['opened_by_device']),
m.get('notes', existing_m['notes']),
is_del,
up_at,
mid
))
# 5. 依据物理药瓶实体 (Bottle) 与流水绑定关系,严格确定性重新核算余量
for b in conn.execute('SELECT * FROM bottles').fetchall():
bid = b['id']
@@ -452,6 +559,28 @@ class SyncHandler(SimpleHTTPRequestHandler):
'note': row['note']
})
all_medicines = []
for row in conn.execute('SELECT * FROM medicines ORDER BY expiry_date ASC').fetchall():
all_medicines.append({
'id': row['id'],
'name': row['name'],
'category': row['category'],
'spec': row['spec'] or '',
'storageLocation': row['storage_location'] or '常温药箱',
'targetUser': row['target_user'] or '全家',
'barcode': row['barcode'],
'batchNumber': row['batch_number'],
'productionDate': row['production_date'],
'expiryDate': row['expiry_date'],
'shelfLifeDaysAfterOpening': row['shelf_life_days_after_opening'],
'isOpened': bool(row['is_opened']),
'openedAt': row['opened_at'],
'openedByDevice': row['opened_by_device'],
'notes': row['notes'] or '',
'isDeleted': bool(row['is_deleted']),
'updatedAt': row['updated_at']
})
conn.close()
self._send_json(200, {
@@ -459,18 +588,90 @@ class SyncHandler(SimpleHTTPRequestHandler):
'server_time': now_str,
'bottles': all_bottles,
'records': all_records,
'canisters': all_canisters
'canisters': all_canisters,
'medicines': all_medicines
})
def _handle_medicine_lookup(self, code):
catalog = {
'6921147600010': {'name': '辅舒酮 (丙酸氟替卡松吸入气雾剂)', 'spec': '50μg/喷 × 60喷', 'notes': '吸入用糖皮质激素'},
'6921147600027': {'name': '万托林 (硫酸沙丁胺醇吸入气雾剂)', 'spec': '100μg/喷 × 200喷', 'notes': '支气管舒张剂'},
'6925567800018': {'name': '美林 (布洛芬混悬液)', 'spec': '100ml:2g', 'notes': '退热抗炎镇痛'},
'6925567800025': {'name': '泰诺林 (对乙酰氨基酚混悬滴剂)', 'spec': '15ml:1.5g', 'notes': '儿童退热滴剂'},
'6936577800015': {'name': '托百士 (妥布霉素滴眼液)', 'spec': '5ml:15mg', 'notes': '抗生素眼药水,开封4周内使用'},
'6914567800012': {'name': '可乐必妥 (左氧氟沙星滴眼液)', 'spec': '5ml:24.45mg', 'notes': '抗菌滴眼液'},
'6901234560019': {'name': '百多邦 (莫匹罗星软膏)', 'spec': '5g:0.1g', 'notes': '外用抗菌软膏'},
}
if code in catalog:
item = catalog[code]
self._send_json(200, {
'status': 'ok',
'data': {
'barcode': code,
'name': item['name'],
'spec': item['spec'],
'notes': item['notes']
}
})
return
if len(code) == 20 and code.isdigit():
self._send_json(200, {
'status': 'ok',
'data': {
'barcode': code,
'name': f'追溯码药品 ({code[:6]}...)',
'notes': '由国家药品电子监管码录入'
}
})
return
self._send_json(200, {'status': 'not_found', 'message': '未在本地知识库匹配到该药品条码'})
def _render_dashboard(self):
conn = get_db()
records = conn.execute('SELECT * FROM dose_records WHERE is_deleted = 0 ORDER BY start_time DESC LIMIT 20').fetchall()
devices = conn.execute('SELECT * FROM devices ORDER BY last_seen DESC').fetchall()
canisters = conn.execute('SELECT * FROM canisters ORDER BY sort_order ASC').fetchall()
bottles = conn.execute('SELECT * FROM bottles ORDER BY sequence_number DESC').fetchall()
medicines = conn.execute('SELECT * FROM medicines WHERE is_deleted = 0 ORDER BY expiry_date ASC').fetchall()
total_count = conn.execute('SELECT COUNT(*) as c FROM dose_records WHERE is_deleted = 0').fetchone()['c']
conn.close()
med_list = []
now_dt = datetime.datetime.now(datetime.timezone.utc)
for m in medicines:
exp_str = m['expiry_date'] or ''
try:
exp_clean = exp_str.replace('Z', '+00:00')
exp_dt = datetime.datetime.fromisoformat(exp_clean)
days_left = (exp_dt.date() - now_dt.date()).days
except Exception:
days_left = 999
if days_left < 0:
badge = '<span style="background:#fee2e2;color:#b91c1c;padding:2px 8px;border-radius:6px;font-size:11px;font-weight:bold;">已过期</span>'
elif days_left <= 30:
badge = f'<span style="background:#fef3c7;color:#b45309;padding:2px 8px;border-radius:6px;font-size:11px;font-weight:bold;">临期 ({days_left}天)</span>'
elif m['is_opened']:
badge = '<span style="background:#dbeafe;color:#1d4ed8;padding:2px 8px;border-radius:6px;font-size:11px;font-weight:bold;">已开封使用</span>'
else:
badge = '<span style="background:#dcfce7;color:#15803d;padding:2px 8px;border-radius:6px;font-size:11px;font-weight:bold;">未开封正常</span>'
open_info = f"已开封 ({m['opened_at'][:10]})" if m['is_opened'] and m['opened_at'] else "未开封"
loc = m['storage_location'] or '常温药箱'
spec = f" <span style='color:#64748b;font-size:11px;'>({m['spec']})</span>" if m['spec'] else ""
med_list.append(
f"<tr style='border-bottom:1px solid #e2e8f0;'>"
f"<td style='padding:10px 14px;'><strong>{m['name']}</strong>{spec}</td>"
f"<td style='padding:10px 14px;'>{loc}</td>"
f"<td style='padding:10px 14px;color:#2563eb;'>{exp_str[:10]}</td>"
f"<td style='padding:10px 14px;'>{open_info}</td>"
f"<td style='padding:10px 14px;'>{badge}</td>"
f"</tr>"
)
med_rows = "".join(med_list) or "<tr><td colspan='5' style='padding:12px;color:#94a3b8;'>暂无家庭药箱数据,可在 App 内扫码或手动添加</td></tr>"
canister_list = []
for c in canisters:
status_badge = '<span style="color:#059669;font-weight:bold;">启用</span>' if c['is_enabled'] else '<span style="color:#94a3b8;">未启用</span>'
@@ -557,6 +758,14 @@ class SyncHandler(SimpleHTTPRequestHandler):
</div>
</div>
<div class="card">
<h2>🏠 家庭智能药箱健康与保质期监控 (全家药品有效期与开封管理)</h2>
<table>
<thead><tr><th>药品名称</th><th>存放位置</th><th>出厂有效期</th><th>开封追踪</th><th>健康状态</th></tr></thead>
<tbody>{med_rows}</tbody>
</table>
</div>
<div class="card">
<h2>当前在用药瓶余量监控 (各设备统一权威真值)</h2>
<table>