Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 59 additions & 2 deletions lib/import/whoop_import.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import '../compute/derivation_engine.dart' show kAlgoVersion, DerivationEngine;
import '../compute/profile.dart';
import '../compute/substrate.dart' show localDateLabel;
import '../data/db.dart';
import '../data/series_codec.dart';
import '../health/health_export.dart';
import 'import_container.dart';
import 'journal_csv_import.dart' show parseCsv;
Expand Down Expand Up @@ -320,9 +321,59 @@ class WhoopImporter {
});
}

static const _sleepKeys = [
'asleepMin', 'inBedMin', 'lightMin', 'deepMin', 'remMin', 'awakeMin',
'effPct',
];

/// [f] with its nulls filled from a prior WHOOP import's day_result row.
/// Sleep fields carry over only as a group, and only when [f] has no sleep
/// of its own, so two files' stage numbers never mix into one night.
@visibleForTesting
static Map<String, dynamic> mergeWithPriorWhoopImport(
Map<String, dynamic> f, Map<String, dynamic>? existing) {
final p = SeriesCodec.decodePayloadJson(existing?['payload_json']);
if (p == null || p['source'] != 'whoop_export') return f;
Map m(Object? v) => v is Map ? v : const {};
final s = m(p['scalars']);
final acct = m(m(m(p['sleep'])['accounting'])['value']);
final win = m(m(m(p['sleep'])['window'])['value']);
num? div(Object? v, int by) => v is num ? v / by : null;
int? sec(Object? ms) => ms is num ? ms.toInt() ~/ 1000 : null;
final onset = sec(win['onset_ms']), wake = sec(win['offset_ms']);
// a row with only a matching onset/wake (cycles csv) still gets the group
final sameWindow = (f['sleepOnset'] == null || f['sleepOnset'] == onset) &&
(f['sleepWake'] == null || f['sleepWake'] == wake);
final prior = <String, Object?>{
'recovery': s['readiness'],
'rhr': s['rhr'],
'rmssd': s['rmssd'],
'strain': s['strain'],
'caloriesTotal': s['calories_total'],
'resp': s['resp_rate'],
'spo2': s['spo2'],
if (sameWindow && !_sleepKeys.any((k) => f[k] != null)) ...{
'asleepMin': s['tst_min'],
'inBedMin': div(acct['in_bed_sec'], 60),
'lightMin': s['light_min'],
'deepMin': s['deep_min'],
'remMin': s['rem_min'],
'awakeMin': div(acct['wake_sec'], 60),
'effPct': s['efficiency'],
'sleepOnset': onset,
'sleepWake': wake,
},
};
return {
...f,
for (final e in prior.entries)
if (f[e.key] == null && e.value is num) e.key: e.value,
};
}

static Future<_DayWrite> _buildAndWriteDay(
String date,
Map<String, dynamic> f,
Map<String, dynamic> fields,
Set<String> rawDays,
) async {
// NEVER clobber a real derived day: a returning user with months of band
Expand All @@ -331,7 +382,13 @@ class WhoopImporter {
// `finalized: true` then locked the day so DerivationEngine could never
// rebuild it from raw. The guard now lives in LocalDb so the other three
// import paths share it rather than each forgetting it.
if (await LocalDb.isMeasuredDay(date)) return _DayWrite.keptExisting;
final existing = await LocalDb.dayResult(date);
if (LocalDb.isMeasuredDayRow(existing)) return _DayWrite.keptExisting;
// Importing sleeps.csv on its own after physiological_cycles.csv (or the
// reverse) brings none of the other file's columns, and the write below
// REPLACEs the day, so the earlier import's numbers went null. Fill the
// gaps from that earlier import; a new non-null value still wins.
final f = mergeWithPriorWhoopImport(fields, existing);

final recovery = f['recovery'] as num?;
final rhr = f['rhr'] as num?;
Expand Down
22 changes: 22 additions & 0 deletions test/import_data_safety_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,28 @@ void main() {
expect(res.days, 1);
await assertMerged(day);
});

test('importing the two files separately keeps both files\' fields',
() async {
const wake = '2026-06-03 07:00:00';
final day =
localDateLabel(DateTime.parse(wake).millisecondsSinceEpoch ~/ 1000);
expect((await WhoopImporter.importFiles([cyclesCsv(tmp, wake)])).days, 1);
expect((await WhoopImporter.importFiles([sleepsCsv(tmp, wake)])).days, 1);
await assertMerged(day);
expect(await _metric(day, 'readiness'), 66.0);
expect(await _metric(day, 'rmssd'), 80.0);
});

test('sleep file then cycles file separately keeps the night', () async {
const wake = '2026-06-04 07:00:00';
final day =
localDateLabel(DateTime.parse(wake).millisecondsSinceEpoch ~/ 1000);
expect((await WhoopImporter.importFiles([sleepsCsv(tmp, wake)])).days, 1);
expect((await WhoopImporter.importFiles([cyclesCsv(tmp, wake)])).days, 1);
await assertMerged(day);
expect(await _metric(day, 'light_min'), 250.0);
});
});

test('WhoopImporter: a nap row never replaces that date\'s night',
Expand Down
Loading