feat: 重构局域网数据同步与物理药瓶生命周期(Bottle Entity),实现开新瓶、软删除与多端精确余量核算
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
import 'dart:convert';
|
||||
|
||||
class Bottle {
|
||||
final String id; // 全局唯一 UUID (如: flix_b1_xxxx)
|
||||
final String canisterId; // 关联的药品ID (如: flixotide_primary / ventolin_primary)
|
||||
final String name; // 药品展示名称
|
||||
final int sequenceNumber; // 第几瓶 (1, 2, 3...)
|
||||
final int totalDoses; // 规格总喷数 (如 60, 200)
|
||||
final DateTime openedAt; // 严格 UTC 开封时间
|
||||
DateTime? finishedAt; // 严格 UTC 用尽/归档时间
|
||||
bool isActive; // 是否为当前正在使用的活跃药瓶
|
||||
final String openedByDevice; // 开瓶操作的设备名称
|
||||
DateTime updatedAt; // 严格 UTC 更新时间戳 (用于多端 LWW 冲突解决)
|
||||
|
||||
Bottle({
|
||||
required this.id,
|
||||
required this.canisterId,
|
||||
required this.name,
|
||||
this.sequenceNumber = 1,
|
||||
required this.totalDoses,
|
||||
required this.openedAt,
|
||||
this.finishedAt,
|
||||
this.isActive = true,
|
||||
this.openedByDevice = '本机',
|
||||
DateTime? updatedAt,
|
||||
}) : updatedAt = updatedAt ?? DateTime.now().toUtc();
|
||||
|
||||
Map<String, dynamic> toMap() {
|
||||
return {
|
||||
'id': id,
|
||||
'canisterId': canisterId,
|
||||
'name': name,
|
||||
'sequenceNumber': sequenceNumber,
|
||||
'totalDoses': totalDoses,
|
||||
'openedAt': openedAt.toUtc().toIso8601String(),
|
||||
'finishedAt': finishedAt?.toUtc().toIso8601String(),
|
||||
'isActive': isActive,
|
||||
'openedByDevice': openedByDevice,
|
||||
'updatedAt': updatedAt.toUtc().toIso8601String(),
|
||||
};
|
||||
}
|
||||
|
||||
factory Bottle.fromMap(Map<String, dynamic> map) {
|
||||
return Bottle(
|
||||
id: map['id'] as String,
|
||||
canisterId: map['canisterId'] as String? ?? (map['canister_id'] as String? ?? ''),
|
||||
name: map['name'] as String? ?? '',
|
||||
sequenceNumber: map['sequenceNumber'] as int? ?? (map['sequence_number'] as int? ?? 1),
|
||||
totalDoses: map['totalDoses'] as int? ?? (map['total_doses'] as int? ?? 60),
|
||||
openedAt: DateTime.parse(map['openedAt'] as String? ?? (map['opened_at'] as String? ?? DateTime.now().toUtc().toIso8601String())).toUtc(),
|
||||
finishedAt: map['finishedAt'] != null
|
||||
? DateTime.parse(map['finishedAt'] as String).toUtc()
|
||||
: (map['finished_at'] != null ? DateTime.parse(map['finished_at'] as String).toUtc() : null),
|
||||
isActive: map['isActive'] as bool? ?? ((map['is_active'] as int? ?? 1) == 1),
|
||||
openedByDevice: map['openedByDevice'] as String? ?? (map['opened_by_device'] as String? ?? '家庭设备'),
|
||||
updatedAt: map['updatedAt'] != null
|
||||
? DateTime.parse(map['updatedAt'] as String).toUtc()
|
||||
: (map['updated_at'] != null ? DateTime.parse(map['updated_at'] as String).toUtc() : DateTime.now().toUtc()),
|
||||
);
|
||||
}
|
||||
|
||||
String toJson() => json.encode(toMap());
|
||||
factory Bottle.fromJson(String source) =>
|
||||
Bottle.fromMap(json.decode(source) as Map<String, dynamic>);
|
||||
}
|
||||
@@ -39,7 +39,7 @@ class Canister {
|
||||
'name': name,
|
||||
'totalDoses': totalDoses,
|
||||
'remainingDoses': remainingDoses,
|
||||
'openedAt': openedAt.toIso8601String(),
|
||||
'openedAt': openedAt.toUtc().toIso8601String(),
|
||||
'isEnabled': isEnabled,
|
||||
'puffsPerSession': puffsPerSession,
|
||||
'inhalationSeconds': inhalationSeconds,
|
||||
@@ -55,7 +55,7 @@ class Canister {
|
||||
name: map['name'] as String,
|
||||
totalDoses: map['totalDoses'] as int,
|
||||
remainingDoses: map['remainingDoses'] as int,
|
||||
openedAt: DateTime.parse(map['openedAt'] as String),
|
||||
openedAt: DateTime.parse(map['openedAt'] as String).toUtc(),
|
||||
isEnabled: map['isEnabled'] as bool? ?? true,
|
||||
puffsPerSession: map['puffsPerSession'] as int? ?? 2,
|
||||
inhalationSeconds: map['inhalationSeconds'] as int? ?? 15,
|
||||
|
||||
+33
-15
@@ -4,12 +4,16 @@ class DoseRecord {
|
||||
final String id;
|
||||
final DateTime startTime;
|
||||
final DateTime endTime;
|
||||
final int flixotidePuffs; // 辅舒酮喷数
|
||||
final int ventolinPuffs; // 万托林喷数
|
||||
final bool rinsedMouth; // 是否漱口
|
||||
final bool washedFace; // 是否洗脸
|
||||
final bool isPrime; // 是否为试喷扣除
|
||||
final int flixotidePuffs; // 辅舒酮喷数
|
||||
final int ventolinPuffs; // 万托林喷数
|
||||
final String? flixotideBottleId; // 关联的辅舒酮药瓶 UUID
|
||||
final String? ventolinBottleId; // 关联的万托林药瓶 UUID
|
||||
final bool rinsedMouth; // 是否漱口
|
||||
final bool washedFace; // 是否洗脸
|
||||
final bool isPrime; // 是否为试喷扣除
|
||||
final bool isDeleted; // 软删除墓碑标记
|
||||
final String? note;
|
||||
final DateTime updatedAt; // UTC 更新时间
|
||||
|
||||
DoseRecord({
|
||||
required this.id,
|
||||
@@ -17,39 +21,53 @@ class DoseRecord {
|
||||
required this.endTime,
|
||||
this.flixotidePuffs = 0,
|
||||
this.ventolinPuffs = 0,
|
||||
this.flixotideBottleId,
|
||||
this.ventolinBottleId,
|
||||
this.rinsedMouth = true,
|
||||
this.washedFace = true,
|
||||
this.isPrime = false,
|
||||
this.isDeleted = false,
|
||||
this.note,
|
||||
});
|
||||
DateTime? updatedAt,
|
||||
}) : updatedAt = updatedAt ?? DateTime.now().toUtc();
|
||||
|
||||
Duration get duration => endTime.difference(startTime);
|
||||
|
||||
Map<String, dynamic> toMap() {
|
||||
return {
|
||||
'id': id,
|
||||
'startTime': startTime.toIso8601String(),
|
||||
'endTime': endTime.toIso8601String(),
|
||||
'startTime': startTime.toUtc().toIso8601String(),
|
||||
'endTime': endTime.toUtc().toIso8601String(),
|
||||
'flixotidePuffs': flixotidePuffs,
|
||||
'ventolinPuffs': ventolinPuffs,
|
||||
'flixotideBottleId': flixotideBottleId,
|
||||
'ventolinBottleId': ventolinBottleId,
|
||||
'rinsedMouth': rinsedMouth,
|
||||
'washedFace': washedFace,
|
||||
'isPrime': isPrime,
|
||||
'isDeleted': isDeleted,
|
||||
'note': note,
|
||||
'updatedAt': updatedAt.toUtc().toIso8601String(),
|
||||
};
|
||||
}
|
||||
|
||||
factory DoseRecord.fromMap(Map<String, dynamic> map) {
|
||||
return DoseRecord(
|
||||
id: map['id'] as String,
|
||||
startTime: DateTime.parse(map['startTime'] as String),
|
||||
endTime: DateTime.parse(map['endTime'] as String),
|
||||
flixotidePuffs: map['flixotidePuffs'] as int? ?? 0,
|
||||
ventolinPuffs: map['ventolinPuffs'] as int? ?? 0,
|
||||
rinsedMouth: map['rinsedMouth'] as bool? ?? true,
|
||||
washedFace: map['washedFace'] as bool? ?? true,
|
||||
isPrime: map['isPrime'] as bool? ?? false,
|
||||
startTime: DateTime.parse(map['startTime'] as String? ?? (map['start_time'] as String)).toUtc(),
|
||||
endTime: DateTime.parse(map['endTime'] as String? ?? (map['end_time'] as String)).toUtc(),
|
||||
flixotidePuffs: map['flixotidePuffs'] as int? ?? (map['flixotide_puffs'] as int? ?? 0),
|
||||
ventolinPuffs: map['ventolinPuffs'] as int? ?? (map['ventolin_puffs'] as int? ?? 0),
|
||||
flixotideBottleId: map['flixotideBottleId'] as String? ?? (map['flixotide_bottle_id'] as String?),
|
||||
ventolinBottleId: map['ventolinBottleId'] as String? ?? (map['ventolin_bottle_id'] as String?),
|
||||
rinsedMouth: map['rinsedMouth'] as bool? ?? ((map['rinsed_mouth'] as int? ?? 1) == 1),
|
||||
washedFace: map['washedFace'] as bool? ?? ((map['washed_face'] as int? ?? 1) == 1),
|
||||
isPrime: map['isPrime'] as bool? ?? ((map['is_prime'] as int? ?? 0) == 1),
|
||||
isDeleted: map['isDeleted'] as bool? ?? ((map['is_deleted'] as int? ?? 0) == 1),
|
||||
note: map['note'] as String?,
|
||||
updatedAt: map['updatedAt'] != null
|
||||
? DateTime.parse(map['updatedAt'] as String).toUtc()
|
||||
: (map['updated_at'] != null ? DateTime.parse(map['updated_at'] as String).toUtc() : DateTime.now().toUtc()),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../models/dose_record.dart';
|
||||
import '../services/storage_service.dart';
|
||||
import '../services/sync_service.dart';
|
||||
|
||||
class HistoryScreen extends StatefulWidget {
|
||||
final StorageService storageService;
|
||||
@@ -47,6 +48,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
if (confirmed == true) {
|
||||
await widget.storageService.deleteRecord(record.id);
|
||||
_loadRecords();
|
||||
SyncService(widget.storageService).syncSilently();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -136,7 +136,6 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
);
|
||||
|
||||
if (confirmed == true && _activeCanisters.isNotEmpty) {
|
||||
final now = DateTime.now();
|
||||
final Map<String, int> deductions = {};
|
||||
int flixotideDoses = 0;
|
||||
int ventolinDoses = 0;
|
||||
@@ -150,12 +149,19 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
final nowUtc = DateTime.now().toUtc();
|
||||
final activeFlix = widget.storageService.getActiveFlixotideBottle();
|
||||
final activeVent = widget.storageService.getActiveVentolinBottle();
|
||||
|
||||
final record = DoseRecord(
|
||||
id: const Uuid().v4(),
|
||||
startTime: now,
|
||||
endTime: now,
|
||||
startTime: nowUtc,
|
||||
endTime: nowUtc,
|
||||
flixotidePuffs: flixotideDoses,
|
||||
ventolinPuffs: ventolinDoses,
|
||||
flixotideBottleId: flixotideDoses > 0 ? activeFlix?.id : null,
|
||||
ventolinBottleId: ventolinDoses > 0 ? activeVent?.id : null,
|
||||
updatedAt: nowUtc,
|
||||
);
|
||||
|
||||
await widget.storageService.deductSessionDoses(deductions);
|
||||
@@ -185,15 +191,20 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
);
|
||||
|
||||
if (confirmed == true) {
|
||||
final now = DateTime.now();
|
||||
final nowUtc = DateTime.now().toUtc();
|
||||
final activeBottle = widget.storageService.getActiveBottle(canister.id);
|
||||
|
||||
final record = DoseRecord(
|
||||
id: const Uuid().v4(),
|
||||
startTime: now,
|
||||
endTime: now,
|
||||
startTime: nowUtc,
|
||||
endTime: nowUtc,
|
||||
flixotidePuffs: canister.isSteroid ? 1 : 0,
|
||||
ventolinPuffs: canister.isSteroid ? 0 : 1,
|
||||
flixotideBottleId: canister.isSteroid ? activeBottle?.id : null,
|
||||
ventolinBottleId: !canister.isSteroid ? activeBottle?.id : null,
|
||||
isPrime: true,
|
||||
note: '${canister.name.split(" ")[0]}试喷',
|
||||
updatedAt: nowUtc,
|
||||
);
|
||||
await widget.storageService.deductSessionDoses({canister.id: 1});
|
||||
await widget.storageService.addRecord(record);
|
||||
@@ -203,28 +214,36 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
}
|
||||
|
||||
Future<void> _resetCanister(Canister canister) async {
|
||||
final activeBottle = widget.storageService.getActiveBottle(canister.id);
|
||||
final currentSeq = activeBottle?.sequenceNumber ?? 1;
|
||||
final nextSeq = currentSeq + 1;
|
||||
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: Text('换新药瓶 - ${canister.name.split(" ")[0]}'),
|
||||
content: Text('确认启用新的一瓶【${canister.name}】,将其剩余次数重置为 ${canister.totalDoses} 喷吗?'),
|
||||
content: Text('当前正在使用第 $currentSeq 瓶。\n确认拆封启用【第 $nextSeq 瓶】,并将剩余次数重置为满瓶 (${canister.totalDoses} 喷) 吗?'),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('取消')),
|
||||
ElevatedButton(
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
child: Text('确认重置为 ${canister.totalDoses} 喷'),
|
||||
child: Text('确认启用第 $nextSeq 瓶'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmed == true) {
|
||||
await widget.storageService.resetCanisterDoses(canister.id, canister.totalDoses);
|
||||
final deviceName = await SyncService.getDeviceName();
|
||||
final newBottle = await widget.storageService.openNewBottle(canister.id, deviceName: deviceName);
|
||||
_loadData();
|
||||
SyncService(widget.storageService).syncSilently();
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('已成功将 ${canister.name.split(" ")[0]} 重置为满瓶!')),
|
||||
SnackBar(
|
||||
content: Text('已成功启用第 ${newBottle.sequenceNumber} 瓶【${canister.name.split(" ")[0]}】,剩余次数已更新为满瓶!'),
|
||||
backgroundColor: const Color(0xFF10B981),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -313,14 +313,20 @@ class ActiveSessionService extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
final activeFlix = storageService.getActiveFlixotideBottle();
|
||||
final activeVent = storageService.getActiveVentolinBottle();
|
||||
|
||||
final record = DoseRecord(
|
||||
id: const Uuid().v4(),
|
||||
startTime: _sessionStartTime ?? DateTime.now(),
|
||||
endTime: _sessionEndTime ?? DateTime.now(),
|
||||
startTime: (_sessionStartTime ?? DateTime.now()).toUtc(),
|
||||
endTime: (_sessionEndTime ?? DateTime.now()).toUtc(),
|
||||
flixotidePuffs: totalFlixotide,
|
||||
ventolinPuffs: totalVentolin,
|
||||
flixotideBottleId: totalFlixotide > 0 ? activeFlix?.id : null,
|
||||
ventolinBottleId: totalVentolin > 0 ? activeVent?.id : null,
|
||||
rinsedMouth: _rinsedMouth,
|
||||
washedFace: _washedFace,
|
||||
updatedAt: DateTime.now().toUtc(),
|
||||
);
|
||||
|
||||
await storageService.addRecord(record);
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import '../models/bottle.dart';
|
||||
import '../models/canister.dart';
|
||||
import '../models/dose_record.dart';
|
||||
import '../models/app_settings.dart';
|
||||
@@ -7,6 +9,7 @@ class StorageService {
|
||||
static const String _keySettings = 'aerotrack_settings';
|
||||
static const String _keyCanisters = 'aerotrack_canisters';
|
||||
static const String _keyRecords = 'aerotrack_records';
|
||||
static const String _keyBottles = 'aerotrack_bottles';
|
||||
|
||||
final SharedPreferences _prefs;
|
||||
|
||||
@@ -21,7 +24,7 @@ class StorageService {
|
||||
}
|
||||
|
||||
Future<void> _ensureInitialData() async {
|
||||
// 首次启动初始化默认药品 (使用早期占位时间,确保能完全继承云端开瓶时间与历史记录)
|
||||
// 1. 首次启动初始化默认药品方案配置
|
||||
if (!_prefs.containsKey(_keyCanisters)) {
|
||||
final defaultCanisters = [
|
||||
Canister(
|
||||
@@ -29,7 +32,7 @@ class StorageService {
|
||||
name: '万托林 (硫酸沙丁胺醇)',
|
||||
totalDoses: 200,
|
||||
remainingDoses: 200,
|
||||
openedAt: DateTime(2020, 1, 1),
|
||||
openedAt: DateTime(2020, 1, 1).toUtc(),
|
||||
isEnabled: true,
|
||||
puffsPerSession: 2,
|
||||
inhalationSeconds: 15,
|
||||
@@ -42,7 +45,7 @@ class StorageService {
|
||||
name: '辅舒酮 (丙酸氟替卡松)',
|
||||
totalDoses: 60,
|
||||
remainingDoses: 60,
|
||||
openedAt: DateTime(2020, 1, 1),
|
||||
openedAt: DateTime(2020, 1, 1).toUtc(),
|
||||
isEnabled: true,
|
||||
puffsPerSession: 2,
|
||||
inhalationSeconds: 15,
|
||||
@@ -53,6 +56,80 @@ class StorageService {
|
||||
];
|
||||
await saveCanisters(defaultCanisters);
|
||||
}
|
||||
|
||||
// 2. 物理药瓶生命周期实体初始化与历史流水平滑迁移
|
||||
final existingBottles = getBottles();
|
||||
if (existingBottles.isEmpty) {
|
||||
final initialFlixBottle = Bottle(
|
||||
id: 'flix_b1_initial',
|
||||
canisterId: 'flixotide_primary',
|
||||
name: '辅舒酮 (丙酸氟替卡松)',
|
||||
sequenceNumber: 1,
|
||||
totalDoses: 60,
|
||||
openedAt: DateTime(2020, 1, 1).toUtc(),
|
||||
isActive: true,
|
||||
openedByDevice: '系统初始化',
|
||||
updatedAt: DateTime.now().toUtc(),
|
||||
);
|
||||
|
||||
final initialVentBottle = Bottle(
|
||||
id: 'vent_b1_initial',
|
||||
canisterId: 'ventolin_primary',
|
||||
name: '万托林 (硫酸沙丁胺醇)',
|
||||
sequenceNumber: 1,
|
||||
totalDoses: 200,
|
||||
openedAt: DateTime(2020, 1, 1).toUtc(),
|
||||
isActive: true,
|
||||
openedByDevice: '系统初始化',
|
||||
updatedAt: DateTime.now().toUtc(),
|
||||
);
|
||||
|
||||
await saveBottles([initialFlixBottle, initialVentBottle]);
|
||||
|
||||
// 历史平滑过渡:若存在未绑定 bottle_id 的历史用药记录,全部归属到第 1 瓶
|
||||
final allRawRecords = getAllRecords(includeDeleted: true);
|
||||
bool recordsUpdated = false;
|
||||
final migratedRecords = <DoseRecord>[];
|
||||
|
||||
for (var r in allRawRecords) {
|
||||
String? fId = r.flixotideBottleId;
|
||||
String? vId = r.ventolinBottleId;
|
||||
|
||||
if (r.flixotidePuffs > 0 && fId == null) {
|
||||
fId = initialFlixBottle.id;
|
||||
recordsUpdated = true;
|
||||
}
|
||||
if (r.ventolinPuffs > 0 && vId == null) {
|
||||
vId = initialVentBottle.id;
|
||||
recordsUpdated = true;
|
||||
}
|
||||
|
||||
if (fId != r.flixotideBottleId || vId != r.ventolinBottleId) {
|
||||
migratedRecords.add(DoseRecord(
|
||||
id: r.id,
|
||||
startTime: r.startTime,
|
||||
endTime: r.endTime,
|
||||
flixotidePuffs: r.flixotidePuffs,
|
||||
ventolinPuffs: r.ventolinPuffs,
|
||||
flixotideBottleId: fId,
|
||||
ventolinBottleId: vId,
|
||||
rinsedMouth: r.rinsedMouth,
|
||||
washedFace: r.washedFace,
|
||||
isPrime: r.isPrime,
|
||||
isDeleted: r.isDeleted,
|
||||
note: r.note,
|
||||
updatedAt: r.updatedAt,
|
||||
));
|
||||
} else {
|
||||
migratedRecords.add(r);
|
||||
}
|
||||
}
|
||||
|
||||
if (recordsUpdated) {
|
||||
final list = migratedRecords.map((r) => r.toJson()).toList();
|
||||
await _prefs.setStringList(_keyRecords, list);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ========== AppSettings ==========
|
||||
@@ -70,6 +147,96 @@ class StorageService {
|
||||
await _prefs.setString(_keySettings, settings.toJson());
|
||||
}
|
||||
|
||||
// ========== Bottles (物理药瓶生命周期) ==========
|
||||
List<Bottle> getBottles() {
|
||||
final raw = _prefs.getStringList(_keyBottles);
|
||||
if (raw == null) return [];
|
||||
try {
|
||||
final list = raw.map((item) => Bottle.fromJson(item)).toList();
|
||||
list.sort((a, b) => a.sequenceNumber.compareTo(b.sequenceNumber));
|
||||
return list;
|
||||
} catch (_) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> saveBottles(List<Bottle> bottles) async {
|
||||
final list = bottles.map((b) => b.toJson()).toList();
|
||||
await _prefs.setStringList(_keyBottles, list);
|
||||
}
|
||||
|
||||
Bottle? getActiveBottle(String canisterId) {
|
||||
final bottles = getBottles();
|
||||
try {
|
||||
return bottles.firstWhere((b) => b.canisterId == canisterId && b.isActive);
|
||||
} catch (_) {
|
||||
final matched = bottles.where((b) => b.canisterId == canisterId).toList();
|
||||
return matched.isNotEmpty ? matched.last : null;
|
||||
}
|
||||
}
|
||||
|
||||
Bottle? getActiveFlixotideBottle() => getActiveBottle('flixotide_primary');
|
||||
Bottle? getActiveVentolinBottle() => getActiveBottle('ventolin_primary');
|
||||
|
||||
/// 开启新药瓶:归档旧瓶,激活带有全新 UUID 的新瓶实体
|
||||
Future<Bottle> openNewBottle(String canisterId, {required String deviceName}) async {
|
||||
final bottles = getBottles();
|
||||
final nowUtc = DateTime.now().toUtc();
|
||||
int nextSeq = 1;
|
||||
|
||||
for (var b in bottles) {
|
||||
if (b.canisterId == canisterId && b.isActive) {
|
||||
b.isActive = false;
|
||||
b.finishedAt = nowUtc;
|
||||
b.updatedAt = nowUtc;
|
||||
}
|
||||
if (b.canisterId == canisterId && b.sequenceNumber >= nextSeq) {
|
||||
nextSeq = b.sequenceNumber + 1;
|
||||
}
|
||||
}
|
||||
|
||||
final canisters = getCanisters();
|
||||
final config = canisters.firstWhere(
|
||||
(c) => c.id == canisterId,
|
||||
orElse: () => Canister(
|
||||
id: canisterId,
|
||||
name: canisterId.contains('flix') ? '辅舒酮 (丙酸氟替卡松)' : '万托林 (硫酸沙丁胺醇)',
|
||||
totalDoses: canisterId.contains('flix') ? 60 : 200,
|
||||
remainingDoses: canisterId.contains('flix') ? 60 : 200,
|
||||
openedAt: nowUtc,
|
||||
),
|
||||
);
|
||||
|
||||
final prefix = canisterId.contains('flix') ? 'flix' : 'vent';
|
||||
final randomSuffix = const Uuid().v4().substring(0, 8);
|
||||
final newBottle = Bottle(
|
||||
id: '${prefix}_b${nextSeq}_$randomSuffix',
|
||||
canisterId: canisterId,
|
||||
name: config.name,
|
||||
sequenceNumber: nextSeq,
|
||||
totalDoses: config.totalDoses,
|
||||
openedAt: nowUtc,
|
||||
isActive: true,
|
||||
openedByDevice: deviceName,
|
||||
updatedAt: nowUtc,
|
||||
);
|
||||
|
||||
bottles.add(newBottle);
|
||||
await saveBottles(bottles);
|
||||
|
||||
// 同步更新方案配置中的开瓶时间与初始满喷
|
||||
for (var c in canisters) {
|
||||
if (c.id == canisterId) {
|
||||
c.openedAt = nowUtc;
|
||||
c.remainingDoses = c.totalDoses;
|
||||
}
|
||||
}
|
||||
await saveCanisters(canisters);
|
||||
await recalculateCanisterDoses();
|
||||
|
||||
return newBottle;
|
||||
}
|
||||
|
||||
// ========== Canisters ==========
|
||||
List<Canister> getCanisters() {
|
||||
final raw = _prefs.getStringList(_keyCanisters);
|
||||
@@ -149,43 +316,60 @@ class StorageService {
|
||||
await saveCanisters(canisters);
|
||||
}
|
||||
|
||||
Future<void> resetCanisterDoses(String canisterId, int newTotal) async {
|
||||
final canisters = getCanisters();
|
||||
for (var c in canisters) {
|
||||
if (c.id == canisterId) {
|
||||
c.remainingDoses = newTotal;
|
||||
c.openedAt = DateTime.now(); // 启用新瓶时更新开封时间戳
|
||||
}
|
||||
}
|
||||
await saveCanisters(canisters);
|
||||
Future<void> resetCanisterDoses(String canisterId, int newTotal, {String deviceName = '本机'}) async {
|
||||
await openNewBottle(canisterId, deviceName: deviceName);
|
||||
}
|
||||
|
||||
/// 依据全部雾化流水历史记录,重新精准核算每个药瓶的真实剩余喷数
|
||||
/// 依据各药瓶 UUID 与真实流水账本,严格重算当前活跃药瓶的真实剩余喷数
|
||||
Future<void> recalculateCanisterDoses() async {
|
||||
final canisters = getCanisters();
|
||||
if (canisters.isEmpty) return;
|
||||
final records = getRecords();
|
||||
|
||||
final records = getAllRecords(includeDeleted: false);
|
||||
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)));
|
||||
});
|
||||
|
||||
final activeBottle = getActiveBottle(c.id);
|
||||
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 (activeBottle != null) {
|
||||
for (var r in records) {
|
||||
if (c.isSteroid) {
|
||||
// 优先依据明确绑定的 bottleId 核算
|
||||
if (r.flixotideBottleId == activeBottle.id) {
|
||||
consumedPuffs += r.flixotidePuffs;
|
||||
} else if (r.flixotideBottleId == null && !r.startTime.isBefore(activeBottle.openedAt)) {
|
||||
// 兼容早期未绑定 bottleId 的旧数据
|
||||
consumedPuffs += r.flixotidePuffs;
|
||||
}
|
||||
} else {
|
||||
if (r.ventolinBottleId == activeBottle.id) {
|
||||
consumedPuffs += r.ventolinPuffs;
|
||||
} else if (r.ventolinBottleId == null && !r.startTime.isBefore(activeBottle.openedAt)) {
|
||||
consumedPuffs += r.ventolinPuffs;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final correctRemaining = (activeBottle.totalDoses - consumedPuffs).clamp(0, activeBottle.totalDoses);
|
||||
if (c.remainingDoses != correctRemaining || c.openedAt != activeBottle.openedAt) {
|
||||
c.remainingDoses = correctRemaining;
|
||||
c.openedAt = activeBottle.openedAt;
|
||||
changed = true;
|
||||
}
|
||||
} else {
|
||||
// 无 activeBottle 时的保护逻辑
|
||||
for (var r in records) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,27 +379,64 @@ class StorageService {
|
||||
}
|
||||
|
||||
// ========== DoseRecords ==========
|
||||
List<DoseRecord> getRecords() {
|
||||
/// 获取对用户可见的有效流水记录(默认过滤掉软删除墓碑记录)
|
||||
List<DoseRecord> getRecords() => getAllRecords(includeDeleted: false);
|
||||
|
||||
/// 获取全量记录(可包含软删除墓碑,专供多端同步使用)
|
||||
List<DoseRecord> getAllRecords({bool includeDeleted = false}) {
|
||||
final raw = _prefs.getStringList(_keyRecords);
|
||||
if (raw == null) return [];
|
||||
final list = raw.map((item) => DoseRecord.fromJson(item)).toList();
|
||||
list.sort((a, b) => b.startTime.compareTo(a.startTime));
|
||||
return list;
|
||||
try {
|
||||
final list = raw.map((item) => DoseRecord.fromJson(item)).toList();
|
||||
final filtered = includeDeleted ? list : list.where((r) => !r.isDeleted).toList();
|
||||
filtered.sort((a, b) => b.startTime.compareTo(a.startTime));
|
||||
return filtered;
|
||||
} catch (_) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> addRecord(DoseRecord record) async {
|
||||
final records = getRecords();
|
||||
final records = getAllRecords(includeDeleted: true);
|
||||
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 {
|
||||
final records = getRecords();
|
||||
records.removeWhere((r) => r.id == id);
|
||||
final list = records.map((r) => r.toJson()).toList();
|
||||
await _prefs.setStringList(_keyRecords, list);
|
||||
await recalculateCanisterDoses();
|
||||
final records = getAllRecords(includeDeleted: true);
|
||||
final nowUtc = DateTime.now().toUtc();
|
||||
bool updated = false;
|
||||
|
||||
for (int i = 0; i < records.length; i++) {
|
||||
if (records[i].id == id) {
|
||||
final old = records[i];
|
||||
records[i] = DoseRecord(
|
||||
id: old.id,
|
||||
startTime: old.startTime,
|
||||
endTime: old.endTime,
|
||||
flixotidePuffs: old.flixotidePuffs,
|
||||
ventolinPuffs: old.ventolinPuffs,
|
||||
flixotideBottleId: old.flixotideBottleId,
|
||||
ventolinBottleId: old.ventolinBottleId,
|
||||
rinsedMouth: old.rinsedMouth,
|
||||
washedFace: old.washedFace,
|
||||
isPrime: old.isPrime,
|
||||
isDeleted: true,
|
||||
note: old.note,
|
||||
updatedAt: nowUtc,
|
||||
);
|
||||
updated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (updated) {
|
||||
final list = records.map((r) => r.toJson()).toList();
|
||||
await _prefs.setStringList(_keyRecords, list);
|
||||
await recalculateCanisterDoses();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter/foundation.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import '../models/bottle.dart';
|
||||
import '../models/canister.dart';
|
||||
import '../models/dose_record.dart';
|
||||
import 'storage_service.dart';
|
||||
@@ -116,15 +117,17 @@ class SyncService {
|
||||
|
||||
try {
|
||||
await storageService.recalculateCanisterDoses();
|
||||
final localRecords = storageService.getRecords();
|
||||
final localRecords = storageService.getAllRecords(includeDeleted: true);
|
||||
final localBottles = storageService.getBottles();
|
||||
final localCanisters = storageService.getCanisters();
|
||||
final lastSync = await getLastSyncTime();
|
||||
|
||||
final body = json.encode({
|
||||
'device_name': deviceName,
|
||||
'device_id': deviceId,
|
||||
'last_sync_time': lastSync?.toIso8601String(),
|
||||
'last_sync_time': lastSync?.toUtc().toIso8601String(),
|
||||
'records': localRecords.map((r) => r.toMap()).toList(),
|
||||
'bottles': localBottles.map((b) => b.toMap()).toList(),
|
||||
'canisters': localCanisters.map((c) => c.toMap()).toList(),
|
||||
});
|
||||
|
||||
@@ -138,33 +141,70 @@ class SyncService {
|
||||
if (res.statusCode == 200) {
|
||||
final data = json.decode(utf8.decode(res.bodyBytes)) as Map<String, dynamic>;
|
||||
|
||||
// 1. 合并远端记录到本地
|
||||
// 1. 合并远端药瓶生命周期实体 Bottles
|
||||
final remoteBottlesRaw = data['bottles'] as List<dynamic>? ?? [];
|
||||
final remoteBottles = remoteBottlesRaw
|
||||
.map((item) => Bottle.fromMap(item as Map<String, dynamic>))
|
||||
.toList();
|
||||
|
||||
if (remoteBottles.isNotEmpty) {
|
||||
final bottles = storageService.getBottles();
|
||||
final bottleMap = {for (var b in bottles) b.id: b};
|
||||
|
||||
for (var rb in remoteBottles) {
|
||||
final lb = bottleMap[rb.id];
|
||||
if (lb == null) {
|
||||
bottles.add(rb);
|
||||
} else {
|
||||
// LWW 依据 updatedAt 解决冲突
|
||||
if (rb.updatedAt.isAfter(lb.updatedAt) || (rb.isActive != lb.isActive && !rb.isActive)) {
|
||||
final idx = bottles.indexWhere((b) => b.id == rb.id);
|
||||
if (idx != -1) {
|
||||
bottles[idx] = rb;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
await storageService.saveBottles(bottles);
|
||||
}
|
||||
|
||||
// 2. 双向合并全量流水记录 (含软删除墓碑同步)
|
||||
final remoteRecordsRaw = data['records'] as List<dynamic>? ?? [];
|
||||
final remoteRecords = remoteRecordsRaw
|
||||
.map((item) => DoseRecord.fromMap(item as Map<String, dynamic>))
|
||||
.toList();
|
||||
|
||||
final existingIds = localRecords.map((r) => r.id).toSet();
|
||||
final allLocalRecords = storageService.getAllRecords(includeDeleted: true);
|
||||
final localRecordMap = {for (var r in allLocalRecords) r.id: r};
|
||||
int newCount = 0;
|
||||
final List<DoseRecord> newRecords = [];
|
||||
bool recordListChanged = false;
|
||||
|
||||
for (var r in remoteRecords) {
|
||||
if (!existingIds.contains(r.id)) {
|
||||
newRecords.add(r);
|
||||
newCount++;
|
||||
for (var rr in remoteRecords) {
|
||||
final lr = localRecordMap[rr.id];
|
||||
if (lr == null) {
|
||||
allLocalRecords.add(rr);
|
||||
if (!rr.isDeleted) newCount++;
|
||||
recordListChanged = true;
|
||||
} else {
|
||||
// 远端记录有状态变更(例如标记软删除或补充了 bottleId)
|
||||
if (rr.updatedAt.isAfter(lr.updatedAt) || (rr.isDeleted && !lr.isDeleted)) {
|
||||
final idx = allLocalRecords.indexWhere((r) => r.id == rr.id);
|
||||
if (idx != -1) {
|
||||
allLocalRecords[idx] = rr;
|
||||
recordListChanged = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
if (recordListChanged) {
|
||||
allLocalRecords.sort((a, b) => b.startTime.compareTo(a.startTime));
|
||||
final rawList = allLocalRecords.map((r) => r.toJson()).toList();
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setStringList('aerotrack_records', rawList);
|
||||
}
|
||||
|
||||
// 2. 合并远端药瓶状态到本地 (智能继承开封时间)
|
||||
// 3. 合并远端药瓶方案基础配置
|
||||
final remoteCanistersRaw = data['canisters'] as List<dynamic>? ?? [];
|
||||
final remoteCanisters = remoteCanistersRaw
|
||||
.map((item) => Canister.fromMap(item as Map<String, dynamic>))
|
||||
@@ -173,21 +213,10 @@ class SyncService {
|
||||
if (remoteCanisters.isNotEmpty) {
|
||||
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;
|
||||
@@ -201,12 +230,12 @@ class SyncService {
|
||||
await storageService.saveCanisters(currentCanisters);
|
||||
}
|
||||
|
||||
// 3. 核心核算:根据本地+云端汇总的全量流水,精准核算药瓶真实余量与使用次数
|
||||
// 4. 核心终极核算:严格由 active 药瓶 UUID 与全量流水确定性重算各药瓶喷数与开封时间
|
||||
await storageService.recalculateCanisterDoses();
|
||||
|
||||
// 4. 更新同步时间
|
||||
// 5. 更新同步时间戳
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyLastSync, DateTime.now().toIso8601String());
|
||||
await prefs.setString(_keyLastSync, DateTime.now().toUtc().toIso8601String());
|
||||
|
||||
return SyncResult(
|
||||
success: true,
|
||||
|
||||
+240
-109
@@ -2,9 +2,9 @@
|
||||
"""
|
||||
AeroTrack LAN Sync Server (AeroTrack 局域网多设备同步服务端)
|
||||
- 零第三方依赖,纯 Python 标准库 (Python 3.8+)
|
||||
- 自动管理 SQLite 数据库
|
||||
- 自动管理 SQLite 数据库,具备完整的物理药瓶生命周期 (Bottle Entity) 与事件账本溯源
|
||||
- 支持高并发多线程与完整 CORS
|
||||
- 提供局域网设备数据同步接口与 Web 状态看板
|
||||
- 一体化托管 Flutter Web 端应用与服务端监控看板
|
||||
"""
|
||||
|
||||
import sys
|
||||
@@ -33,7 +33,7 @@ def get_db():
|
||||
def init_db():
|
||||
conn = get_db()
|
||||
with conn:
|
||||
# 药瓶状态表
|
||||
# 1. 药品基础方案配置表
|
||||
conn.execute('''
|
||||
CREATE TABLE IF NOT EXISTS canisters (
|
||||
id TEXT PRIMARY KEY,
|
||||
@@ -51,7 +51,24 @@ def init_db():
|
||||
)
|
||||
''')
|
||||
|
||||
# 吸入流水日志表 (UUID 主键,天然支持并发防重)
|
||||
# 2. 物理药瓶全生命周期实体表 (支持换新瓶档案、多端独立计数)
|
||||
conn.execute('''
|
||||
CREATE TABLE IF NOT EXISTS bottles (
|
||||
id TEXT PRIMARY KEY,
|
||||
canister_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
sequence_number INTEGER DEFAULT 1,
|
||||
total_doses INTEGER NOT NULL,
|
||||
remaining_doses INTEGER NOT NULL,
|
||||
opened_at TEXT NOT NULL,
|
||||
finished_at TEXT,
|
||||
is_active INTEGER DEFAULT 1,
|
||||
opened_by_device TEXT,
|
||||
updated_at TEXT NOT NULL
|
||||
)
|
||||
''')
|
||||
|
||||
# 3. 吸入流水日志表 (UUID 主键,天然支持并发防重与软删除墓碑)
|
||||
conn.execute('''
|
||||
CREATE TABLE IF NOT EXISTS dose_records (
|
||||
id TEXT PRIMARY KEY,
|
||||
@@ -59,16 +76,32 @@ def init_db():
|
||||
end_time TEXT NOT NULL,
|
||||
flixotide_puffs INTEGER DEFAULT 0,
|
||||
ventolin_puffs INTEGER DEFAULT 0,
|
||||
flixotide_bottle_id TEXT,
|
||||
ventolin_bottle_id TEXT,
|
||||
rinsed_mouth INTEGER DEFAULT 1,
|
||||
washed_face INTEGER DEFAULT 1,
|
||||
is_prime INTEGER DEFAULT 0,
|
||||
is_deleted INTEGER DEFAULT 0,
|
||||
note TEXT,
|
||||
operator_name TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT
|
||||
)
|
||||
''')
|
||||
|
||||
# 局域网同步设备列表
|
||||
# 检查并平滑升级 dose_records 缺失的列
|
||||
cursor = conn.execute("PRAGMA table_info(dose_records)")
|
||||
existing_cols = {row['name'] for row in cursor.fetchall()}
|
||||
if 'flixotide_bottle_id' not in existing_cols:
|
||||
conn.execute('ALTER TABLE dose_records ADD COLUMN flixotide_bottle_id TEXT')
|
||||
if 'ventolin_bottle_id' not in existing_cols:
|
||||
conn.execute('ALTER TABLE dose_records ADD COLUMN ventolin_bottle_id TEXT')
|
||||
if 'is_deleted' not in existing_cols:
|
||||
conn.execute('ALTER TABLE dose_records ADD COLUMN is_deleted INTEGER DEFAULT 0')
|
||||
if 'updated_at' not in existing_cols:
|
||||
conn.execute('ALTER TABLE dose_records ADD COLUMN updated_at TEXT')
|
||||
|
||||
# 4. 局域网同步设备列表
|
||||
conn.execute('''
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
device_id TEXT PRIMARY KEY,
|
||||
@@ -77,6 +110,24 @@ def init_db():
|
||||
ip_address TEXT
|
||||
)
|
||||
''')
|
||||
|
||||
# 5. 若 bottles 为空,初始化默认第 1 瓶并平滑绑定历史流水
|
||||
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")
|
||||
conn.execute("UPDATE dose_records SET updated_at = ? WHERE updated_at IS NULL", (now_iso,))
|
||||
conn.close()
|
||||
|
||||
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
|
||||
@@ -118,21 +169,22 @@ class SyncHandler(SimpleHTTPRequestHandler):
|
||||
self.wfile.write(payload)
|
||||
|
||||
def do_GET(self):
|
||||
# 1. Ping / 延迟测试
|
||||
# 1. Ping / 连通性测试
|
||||
if self.path == '/api/v1/ping':
|
||||
self._send_json(200, {
|
||||
'status': 'ok',
|
||||
'service': 'AeroTrack LAN Sync Server',
|
||||
'timestamp': datetime.datetime.utcnow().isoformat() + 'Z'
|
||||
'timestamp': datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
})
|
||||
return
|
||||
|
||||
# 2. 状态查询
|
||||
if self.path == '/api/v1/sync/status':
|
||||
conn = get_db()
|
||||
total_records = conn.execute('SELECT COUNT(*) as c FROM dose_records').fetchone()['c']
|
||||
total_records = conn.execute('SELECT COUNT(*) as c FROM dose_records WHERE is_deleted = 0').fetchone()['c']
|
||||
devices = [dict(r) for r in conn.execute('SELECT * FROM devices ORDER BY last_seen DESC').fetchall()]
|
||||
canisters = [dict(r) for r in conn.execute('SELECT * FROM canisters ORDER BY sort_order ASC').fetchall()]
|
||||
bottles = [dict(r) for r in conn.execute('SELECT * FROM bottles ORDER BY sequence_number ASC').fetchall()]
|
||||
conn.close()
|
||||
|
||||
self._send_json(200, {
|
||||
@@ -140,11 +192,12 @@ class SyncHandler(SimpleHTTPRequestHandler):
|
||||
'total_records': total_records,
|
||||
'devices': devices,
|
||||
'canisters': canisters,
|
||||
'server_time': datetime.datetime.utcnow().isoformat() + 'Z'
|
||||
'bottles': bottles,
|
||||
'server_time': datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
})
|
||||
return
|
||||
|
||||
# 3. 监控面板
|
||||
# 3. 监控看板
|
||||
if self.path == '/dashboard' or self.path == '/dashboard/':
|
||||
self._render_dashboard()
|
||||
return
|
||||
@@ -180,11 +233,11 @@ class SyncHandler(SimpleHTTPRequestHandler):
|
||||
device_name = payload.get('device_name', '未知设备')
|
||||
device_id = payload.get('device_id', 'unknown')
|
||||
client_ip = self.client_address[0]
|
||||
now_str = datetime.datetime.utcnow().isoformat() + 'Z'
|
||||
now_str = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
|
||||
conn = get_db()
|
||||
with conn:
|
||||
# 记录设备心跳
|
||||
# 1. 记录设备心跳
|
||||
conn.execute('''
|
||||
INSERT INTO devices (device_id, device_name, last_seen, ip_address)
|
||||
VALUES (?, ?, ?, ?)
|
||||
@@ -194,125 +247,178 @@ class SyncHandler(SimpleHTTPRequestHandler):
|
||||
ip_address = excluded.ip_address
|
||||
''', (device_id, device_name, now_str, client_ip))
|
||||
|
||||
# 1. 接收客户端推上来的新用药记录 (以 UUID 防重幂等入库)
|
||||
# 2. 接收并合并药瓶实体列表 (Bottles)
|
||||
incoming_bottles = payload.get('bottles', [])
|
||||
for b in incoming_bottles:
|
||||
bid = b.get('id')
|
||||
if not bid:
|
||||
continue
|
||||
cid = b.get('canisterId') or b.get('canister_id', '')
|
||||
bname = b.get('name', '')
|
||||
seq = b.get('sequenceNumber') or b.get('sequence_number', 1)
|
||||
td = b.get('totalDoses') or b.get('total_doses', 60)
|
||||
op_at = b.get('openedAt') or b.get('opened_at', now_str)
|
||||
fin_at = b.get('finishedAt') or b.get('finished_at')
|
||||
is_act = 1 if (b.get('isActive') if b.get('isActive') is not None else b.get('is_active', 1)) else 0
|
||||
dev = b.get('openedByDevice') or b.get('opened_by_device', device_name)
|
||||
up_at = b.get('updatedAt') or b.get('updated_at', now_str)
|
||||
|
||||
existing_b = conn.execute('SELECT * FROM bottles WHERE id = ?', (bid,)).fetchone()
|
||||
if not existing_b:
|
||||
conn.execute('''
|
||||
INSERT INTO bottles (id, canister_id, name, sequence_number, total_doses, remaining_doses, opened_at, finished_at, is_active, opened_by_device, updated_at)
|
||||
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 ''):
|
||||
conn.execute('''
|
||||
UPDATE bottles SET
|
||||
finished_at = ?,
|
||||
is_active = ?,
|
||||
updated_at = ?
|
||||
WHERE id = ?
|
||||
''', (fin_at, is_act, up_at, bid))
|
||||
|
||||
# 3. 接收客户端推上来的用药记录 (UUID 幂等入库 + 软删除墓碑同步)
|
||||
incoming_records = payload.get('records', [])
|
||||
for r in incoming_records:
|
||||
rec_id = r.get('id')
|
||||
if not rec_id:
|
||||
continue
|
||||
conn.execute('''
|
||||
INSERT OR IGNORE INTO dose_records
|
||||
(id, start_time, end_time, flixotide_puffs, ventolin_puffs, rinsed_mouth, washed_face, is_prime, note, operator_name, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
''', (
|
||||
rec_id,
|
||||
r.get('startTime', now_str),
|
||||
r.get('endTime', now_str),
|
||||
r.get('flixotidePuffs', 0),
|
||||
r.get('ventolinPuffs', 0),
|
||||
1 if r.get('rinsedMouth', True) else 0,
|
||||
1 if r.get('washedFace', True) else 0,
|
||||
1 if r.get('isPrime', False) else 0,
|
||||
r.get('note', ''),
|
||||
device_name,
|
||||
now_str
|
||||
))
|
||||
is_del = 1 if r.get('isDeleted') or r.get('is_deleted') else 0
|
||||
up_at = r.get('updatedAt') or r.get('updated_at', now_str)
|
||||
fb_id = r.get('flixotideBottleId') or r.get('flixotide_bottle_id')
|
||||
vb_id = r.get('ventolinBottleId') or r.get('ventolin_bottle_id')
|
||||
|
||||
# 2. 接收客户端同步上来的药瓶设置或更新
|
||||
existing_r = conn.execute('SELECT * FROM dose_records WHERE id = ?', (rec_id,)).fetchone()
|
||||
if not existing_r:
|
||||
conn.execute('''
|
||||
INSERT INTO dose_records
|
||||
(id, start_time, end_time, flixotide_puffs, ventolin_puffs, flixotide_bottle_id, ventolin_bottle_id, rinsed_mouth, washed_face, is_prime, is_deleted, note, operator_name, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
''', (
|
||||
rec_id,
|
||||
r.get('startTime', now_str),
|
||||
r.get('endTime', now_str),
|
||||
r.get('flixotidePuffs', 0),
|
||||
r.get('ventolinPuffs', 0),
|
||||
fb_id,
|
||||
vb_id,
|
||||
1 if r.get('rinsedMouth', True) else 0,
|
||||
1 if r.get('washedFace', True) else 0,
|
||||
1 if r.get('isPrime', False) else 0,
|
||||
is_del,
|
||||
r.get('note', ''),
|
||||
device_name,
|
||||
now_str,
|
||||
up_at
|
||||
))
|
||||
else:
|
||||
if up_at >= (existing_r['updated_at'] or ''):
|
||||
conn.execute('''
|
||||
UPDATE dose_records SET
|
||||
is_deleted = ?,
|
||||
flixotide_bottle_id = COALESCE(?, flixotide_bottle_id),
|
||||
ventolin_bottle_id = COALESCE(?, ventolin_bottle_id),
|
||||
updated_at = ?
|
||||
WHERE id = ?
|
||||
''', (is_del, fb_id, vb_id, up_at, rec_id))
|
||||
|
||||
# 4. 接收客户端方案配置 (Canisters 元数据)
|
||||
incoming_canisters = payload.get('canisters', [])
|
||||
for c in incoming_canisters:
|
||||
cid = c.get('id')
|
||||
if not cid:
|
||||
continue
|
||||
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
|
||||
))
|
||||
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
|
||||
name = excluded.name,
|
||||
is_enabled = excluded.is_enabled,
|
||||
puffs_per_session = excluded.puffs_per_session,
|
||||
inhalation_seconds = excluded.inhalation_seconds,
|
||||
sort_order = excluded.sort_order,
|
||||
note = excluded.note,
|
||||
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
|
||||
))
|
||||
|
||||
# 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'
|
||||
# 5. 依据物理药瓶实体 (Bottle) 与流水绑定关系,严格确定性重新核算余量
|
||||
for b in conn.execute('SELECT * FROM bottles').fetchall():
|
||||
bid = b['id']
|
||||
cid = b['canister_id']
|
||||
td = b['total_doses']
|
||||
is_steroid = 1 if 'flix' in cid else 0
|
||||
|
||||
if is_steroid:
|
||||
res = conn.execute(
|
||||
'SELECT SUM(flixotide_puffs) as s FROM dose_records WHERE start_time >= ?',
|
||||
(opened,)
|
||||
).fetchone()
|
||||
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()
|
||||
else:
|
||||
res = conn.execute(
|
||||
'SELECT SUM(ventolin_puffs) as s FROM dose_records WHERE start_time >= ?',
|
||||
(opened,)
|
||||
).fetchone()
|
||||
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()
|
||||
|
||||
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))
|
||||
rem = max(0, td - consumed)
|
||||
conn.execute('UPDATE bottles SET remaining_doses = ? WHERE id = ?', (rem, bid))
|
||||
|
||||
# 4. 汇总拉取全量最新记录并返回给客户端
|
||||
# 若是当前在用活跃瓶,同步更新 canisters 方案余量
|
||||
if b['is_active']:
|
||||
conn.execute('UPDATE canisters SET remaining_doses = ?, opened_at = ? WHERE id = ?', (rem, b['opened_at'], cid))
|
||||
|
||||
# 6. 汇总全量数据响应客户端
|
||||
all_records = []
|
||||
for row in conn.execute('SELECT * FROM dose_records ORDER BY start_time DESC LIMIT 200'):
|
||||
for row in conn.execute('SELECT * FROM dose_records ORDER BY start_time DESC LIMIT 300'):
|
||||
all_records.append({
|
||||
'id': row['id'],
|
||||
'startTime': row['start_time'],
|
||||
'endTime': row['end_time'],
|
||||
'flixotidePuffs': row['flixotide_puffs'],
|
||||
'ventolinPuffs': row['ventolin_puffs'],
|
||||
'flixotideBottleId': row['flixotide_bottle_id'],
|
||||
'ventolinBottleId': row['ventolin_bottle_id'],
|
||||
'rinsedMouth': bool(row['rinsed_mouth']),
|
||||
'washedFace': bool(row['washed_face']),
|
||||
'isPrime': bool(row['is_prime']),
|
||||
'isDeleted': bool(row['is_deleted']),
|
||||
'note': row['note'],
|
||||
'operatorName': row['operator_name']
|
||||
'operatorName': row['operator_name'],
|
||||
'updatedAt': row['updated_at']
|
||||
})
|
||||
|
||||
all_bottles = []
|
||||
for row in conn.execute('SELECT * FROM bottles ORDER BY sequence_number ASC'):
|
||||
all_bottles.append({
|
||||
'id': row['id'],
|
||||
'canisterId': row['canister_id'],
|
||||
'name': row['name'],
|
||||
'sequenceNumber': row['sequence_number'],
|
||||
'totalDoses': row['total_doses'],
|
||||
'remainingDoses': row['remaining_doses'],
|
||||
'openedAt': row['opened_at'],
|
||||
'finishedAt': row['finished_at'],
|
||||
'isActive': bool(row['is_active']),
|
||||
'openedByDevice': row['opened_by_device'],
|
||||
'updatedAt': row['updated_at']
|
||||
})
|
||||
|
||||
# 4. 汇总各药瓶当前最新信息
|
||||
all_canisters = []
|
||||
for row in conn.execute('SELECT * FROM canisters ORDER BY sort_order ASC'):
|
||||
all_canisters.append({
|
||||
@@ -334,16 +440,18 @@ class SyncHandler(SimpleHTTPRequestHandler):
|
||||
self._send_json(200, {
|
||||
'success': True,
|
||||
'server_time': now_str,
|
||||
'bottles': all_bottles,
|
||||
'records': all_records,
|
||||
'canisters': all_canisters
|
||||
})
|
||||
|
||||
def _render_dashboard(self):
|
||||
conn = get_db()
|
||||
records = conn.execute('SELECT * FROM dose_records ORDER BY start_time DESC LIMIT 20').fetchall()
|
||||
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()
|
||||
total_count = conn.execute('SELECT COUNT(*) as c FROM dose_records').fetchone()['c']
|
||||
bottles = conn.execute('SELECT * FROM bottles ORDER BY sequence_number DESC').fetchall()
|
||||
total_count = conn.execute('SELECT COUNT(*) as c FROM dose_records WHERE is_deleted = 0').fetchone()['c']
|
||||
conn.close()
|
||||
|
||||
canister_list = []
|
||||
@@ -357,7 +465,23 @@ class SyncHandler(SimpleHTTPRequestHandler):
|
||||
f"<td style='padding:10px 14px;'>{status_badge}</td>"
|
||||
f"</tr>"
|
||||
)
|
||||
canister_rows = "".join(canister_list) or "<tr><td colspan='4' style='padding:12px;color:#94a3b8;'>暂无同步的药瓶数据</td></tr>"
|
||||
canister_rows = "".join(canister_list) or "<tr><td colspan='4' style='padding:12px;color:#94a3b8;'>暂无药瓶方案数据</td></tr>"
|
||||
|
||||
bottle_list = []
|
||||
for b in bottles:
|
||||
status_badge = '<span style="background:#dcfce7;color:#15803d;padding:2px 8px;border-radius:6px;font-size:11px;font-weight:bold;">在用活跃</span>' if b['is_active'] else '<span style="background:#f1f5f9;color:#64748b;padding:2px 8px;border-radius:6px;font-size:11px;">已归档</span>'
|
||||
fin_time = b['finished_at'][:16].replace('T', ' ') if b['finished_at'] else '使用中'
|
||||
bottle_list.append(
|
||||
f"<tr style='border-bottom:1px solid #e2e8f0;'>"
|
||||
f"<td style='padding:10px 14px;'><strong>第 {b['sequence_number']} 瓶</strong> ({b['name'].split(' ')[0]})</td>"
|
||||
f"<td style='padding:10px 14px;color:#2563eb;font-weight:bold;'>{b['remaining_doses']} / {b['total_doses']} 喷</td>"
|
||||
f"<td style='padding:10px 14px;color:#64748b;'>{b['opened_at'][:16].replace('T', ' ')}</td>"
|
||||
f"<td style='padding:10px 14px;color:#64748b;'>{fin_time}</td>"
|
||||
f"<td style='padding:10px 14px;'>{status_badge}</td>"
|
||||
f"<td style='padding:10px 14px;color:#64748b;font-size:12px;'>{b['opened_by_device']}</td>"
|
||||
f"</tr>"
|
||||
)
|
||||
bottle_rows = "".join(bottle_list) or "<tr><td colspan='6' style='padding:12px;color:#94a3b8;'>暂无药瓶实体数据</td></tr>"
|
||||
|
||||
device_list = []
|
||||
for d in devices:
|
||||
@@ -393,13 +517,12 @@ class SyncHandler(SimpleHTTPRequestHandler):
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<style>
|
||||
body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f8fafc; color: #1e293b; margin: 0; padding: 24px; }}
|
||||
.container {{ max-width: 900px; margin: 0 auto; }}
|
||||
.container {{ max-width: 960px; margin: 0 auto; }}
|
||||
.header {{ background: #2563eb; color: #fff; padding: 24px; border-radius: 16px; margin-bottom: 24px; display: flex; justify-content: space-between; align-items: center; }}
|
||||
.card {{ background: #fff; border-radius: 14px; border: 1px solid #e2e8f0; padding: 20px; margin-bottom: 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }}
|
||||
h2 {{ margin-top: 0; font-size: 16px; color: #0f172a; border-bottom: 2px solid #f1f5f9; padding-bottom: 10px; }}
|
||||
table {{ width: 100%; border-collapse: collapse; font-size: 13px; }}
|
||||
th {{ background: #f8fafc; text-align: left; padding: 10px 14px; font-weight: 600; color: #64748b; }}
|
||||
.tag {{ display: inline-block; padding: 2px 8px; border-radius: 6px; font-size: 11px; font-weight: bold; }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -407,7 +530,7 @@ class SyncHandler(SimpleHTTPRequestHandler):
|
||||
<div class="header">
|
||||
<div>
|
||||
<h1 style="margin:0;font-size:22px;">AeroTrack 局域网多设备同步服务器</h1>
|
||||
<p style="margin:4px 0 0;font-size:13px;opacity:0.85;">数据安全保存在局域网私有主机,已记录 {total_count} 条雾化流水</p>
|
||||
<p style="margin:4px 0 0;font-size:13px;opacity:0.85;">数据安全保存在局域网私有主机,已记录 {total_count} 条有效雾化流水</p>
|
||||
</div>
|
||||
<div style="display:flex;gap:10px;align-items:center;">
|
||||
<a href="/" style="background:#fff;color:#2563eb;text-decoration:none;padding:8px 16px;border-radius:12px;font-size:12px;font-weight:bold;">📱 打开舒雾记 Web 端</a>
|
||||
@@ -418,13 +541,21 @@ class SyncHandler(SimpleHTTPRequestHandler):
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>当前药瓶余量监控 (各设备统一账本)</h2>
|
||||
<h2>当前在用药瓶余量监控 (各设备统一权威真值)</h2>
|
||||
<table>
|
||||
<thead><tr><th>药名</th><th>当前剩余喷数</th><th>每次用量</th><th>方案状态</th></tr></thead>
|
||||
<tbody>{canister_rows}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>物理药瓶开封与换瓶档案 (Bottle Lifecycle 实体生命周期)</h2>
|
||||
<table>
|
||||
<thead><tr><th>瓶次 / 药品</th><th>剩余喷数</th><th>开瓶时间 (UTC)</th><th>用尽归档</th><th>状态</th><th>开瓶设备</th></tr></thead>
|
||||
<tbody>{bottle_rows}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>已连接局域网设备</h2>
|
||||
<table>
|
||||
@@ -434,7 +565,7 @@ class SyncHandler(SimpleHTTPRequestHandler):
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>最近雾化时间流水 (前20条)</h2>
|
||||
<h2>最近有效雾化时间流水 (前20条)</h2>
|
||||
<table>
|
||||
<thead><tr><th>时间</th><th>操作人</th><th>喷数明细</th><th>收尾防护</th></tr></thead>
|
||||
<tbody>{record_rows}</tbody>
|
||||
|
||||
Reference in New Issue
Block a user