diff --git a/app/Models/Device.php b/app/Models/Device.php index 21f5c6c..d786d2e 100644 --- a/app/Models/Device.php +++ b/app/Models/Device.php @@ -218,12 +218,22 @@ class Device extends Model $to = $this->sleep_mode_to; // Handle overnight ranges (e.g. 22:00 to 06:00) - if ($this->sleep_mode_from < $to) { + if ($from < $to) { + // Normal range, same day return $now->between($from, $to) ? (int) $now->diffInSeconds($to, false) : null; + } else { + // Overnight range + if ($now->gte($from)) { + // After 'from', before midnight + return (int) $now->diffInSeconds($to->copy()->addDay(), false); + } elseif ($now->lt($to)) { + // After midnight, before 'to' + return (int) $now->diffInSeconds($to, false); + } else { + // Not in sleep window + return null; + } } - - return ($now->gte($from) || $now->lt($to)) ? (int) $now->diffInSeconds($to->addDay(), false) : null; - } public function isPauseActive(): bool diff --git a/tests/Feature/Devices/DeviceTest.php b/tests/Feature/Devices/DeviceTest.php index 6848bdd..e03a82a 100644 --- a/tests/Feature/Devices/DeviceTest.php +++ b/tests/Feature/Devices/DeviceTest.php @@ -1,6 +1,7 @@ toHaveKey('status') ->toHaveKey('timestamp'); }); + +test('getSleepModeEndsInSeconds returns correct value for overnight sleep window', function () { + // Set the current time to 12:13 + Carbon::setTestNow(Carbon::create(2024, 1, 1, 12, 13, 0)); + + $device = Device::factory()->create([ + 'sleep_mode_enabled' => true, + 'sleep_mode_from' => Carbon::create(2024, 1, 1, 22, 0, 0), // 22:00 + 'sleep_mode_to' => Carbon::create(2024, 1, 1, 13, 0, 0), // 13:00 + ]); + + $seconds = $device->getSleepModeEndsInSeconds(); + // 47 minutes = 2820 seconds + expect($seconds)->toBe(2820); + + Carbon::setTestNow(); // Clear test time +});