diff --git a/lib/import/whoop_import.dart b/lib/import/whoop_import.dart index 8d273948f..962caeeb9 100644 --- a/lib/import/whoop_import.dart +++ b/lib/import/whoop_import.dart @@ -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; @@ -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 mergeWithPriorWhoopImport( + Map f, Map? 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 = { + '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 f, + Map fields, Set rawDays, ) async { // NEVER clobber a real derived day: a returning user with months of band @@ -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?; diff --git a/test/import_data_safety_test.dart b/test/import_data_safety_test.dart index 5014a1d40..3acd99c9c 100644 --- a/test/import_data_safety_test.dart +++ b/test/import_data_safety_test.dart @@ -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',