diff --git a/assets/app.js b/assets/app.js index a56af9e..5810e88 100644 --- a/assets/app.js +++ b/assets/app.js @@ -2,3 +2,24 @@ import './styles/app.scss'; import htmx from 'htmx.org'; window.htmx = htmx; + +document.addEventListener('click', (event) => { + const button = event.target.closest('[data-weather-location]'); + if (!button || !navigator.geolocation) return; + + navigator.geolocation.getCurrentPosition(async ({coords}) => { + const payload = new URLSearchParams({ + _token: button.dataset.locationToken, + latitude: String(coords.latitude), + longitude: String(coords.longitude), + }); + const response = await fetch(button.dataset.locationUrl, { + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + body: payload, + }); + if (response.ok) { + window.location.reload(); + } + }); +}); diff --git a/assets/styles/app.scss b/assets/styles/app.scss index 22b57f3..d5407d1 100644 --- a/assets/styles/app.scss +++ b/assets/styles/app.scss @@ -35,6 +35,36 @@ body { --container-max: 1440px; } + +.day-picker { + display: flex; + align-items: center; + justify-content: center; + gap: 1rem; + margin-bottom: 1.5rem; + color: #fff; + text-align: center; +} + +.day-picker a { + color: inherit; +} + +.day-picker > a { + display: grid; + place-items: center; + width: 2.5rem; + height: 2.5rem; + font-size: 2rem; + text-decoration: none; + border: 1px solid rgb(255 255 255 / .5); + border-radius: 50%; +} + +.day-picker strong, +.day-picker div a { + display: block; +} // dashboards/grids .container-flex--full { --container-max: none; @@ -156,6 +186,39 @@ body { } } +.task-composer__repeat { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: .5rem; +} + +.task-composer__repeat-input { + width: auto; + height: 1.25rem; + margin: 0; +} + +.task-composer__repeat-fields { + display: none; + flex-basis: 100%; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 1rem; + padding: .75rem; + background: #f2fbff; + border-radius: .5rem; +} + +.task-composer__repeat-input:checked ~ .task-composer__repeat-fields { + display: grid; +} + +@media (max-width: 640px) { + .task-composer__repeat-fields { + grid-template-columns: 1fr; + } +} + .task-list__item { display: flex; align-items: center; @@ -170,6 +233,13 @@ body { } } +.task-list__recurrence { + margin-left: auto; + color: #4f7280; + font-size: .8rem; + white-space: nowrap; +} + .task-list__completion-form { display: flex; flex: 1; diff --git a/composer.json b/composer.json index 92e6012..689d85c 100644 --- a/composer.json +++ b/composer.json @@ -15,6 +15,7 @@ "symfony/flex": "^2", "symfony/form": "8.1.*", "symfony/framework-bundle": "8.1.*", + "symfony/http-client": "8.1.*", "symfony/runtime": "8.1.*", "symfony/security-bundle": "8.1.*", "symfony/twig-bundle": "8.1.*", @@ -70,6 +71,7 @@ }, "extra": { "symfony": { + "symfony/phpunit-bridge": "^8.1", "allow-contrib": false, "require": "8.1.*" } diff --git a/composer.lock b/composer.lock index f4e21af..c977e31 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "7cb3f6fd0346d6768d6618db5e43671d", + "content-hash": "10ff9f83f3f6050f5acfb976e4ebe9e8", "packages": [ { "name": "doctrine/collections", @@ -2906,6 +2906,185 @@ ], "time": "2026-06-27T09:05:56+00:00" }, + { + "name": "symfony/http-client", + "version": "v8.1.4", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-client.git", + "reference": "f8d33e21c749e931a33c98b1f6a8ea378b29627a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-client/zipball/f8d33e21c749e931a33c98b1f6a8ea378b29627a", + "reference": "f8d33e21c749e931a33c98b1f6a8ea378b29627a", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "psr/log": "^1|^2|^3", + "symfony/deprecation-contracts": "^2.5|^3.0", + "symfony/http-client-contracts": "^3.7", + "symfony/service-contracts": "^2.5|^3" + }, + "conflict": { + "amphp/amp": "<3", + "php-http/discovery": "<1.15" + }, + "provide": { + "php-http/async-client-implementation": "*", + "php-http/client-implementation": "*", + "psr/http-client-implementation": "1.0", + "symfony/http-client-implementation": "3.0" + }, + "require-dev": { + "amphp/http-client": "^5.3.2", + "amphp/http-tunnel": "^2.0", + "guzzlehttp/guzzle": "^7.10|^8.0", + "nyholm/psr7": "^1.0", + "php-http/httplug": "^1.0|^2.0", + "psr/http-client": "^1.0", + "symfony/cache": "^7.4|^8.0", + "symfony/dependency-injection": "^7.4|^8.0", + "symfony/http-kernel": "^7.4|^8.0", + "symfony/messenger": "^7.4|^8.0", + "symfony/process": "^7.4|^8.0", + "symfony/rate-limiter": "^7.4|^8.0", + "symfony/stopwatch": "^7.4|^8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\HttpClient\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides powerful methods to fetch HTTP resources synchronously or asynchronously", + "homepage": "https://symfony.com", + "keywords": [ + "http" + ], + "support": { + "source": "https://github.com/symfony/http-client/tree/v8.1.4" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-08-06T21:11:24+00:00" + }, + { + "name": "symfony/http-client-contracts", + "version": "v3.7.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-client-contracts.git", + "reference": "41fc42d276aeff21192465331ebbab7d83a743c0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-client-contracts/zipball/41fc42d276aeff21192465331ebbab7d83a743c0", + "reference": "41fc42d276aeff21192465331ebbab7d83a743c0", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.7-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\HttpClient\\": "" + }, + "exclude-from-classmap": [ + "/Test/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to HTTP clients", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/http-client-contracts/tree/v3.7.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-06-05T06:23:12+00:00" + }, { "name": "symfony/http-foundation", "version": "v8.1.1", @@ -5831,7 +6010,7 @@ ], "aliases": [], "minimum-stability": "stable", - "stability-flags": {}, + "stability-flags": [], "prefer-stable": true, "prefer-lowest": false, "platform": { @@ -5839,6 +6018,6 @@ "ext-ctype": "*", "ext-iconv": "*" }, - "platform-dev": {}, - "plugin-api-version": "2.9.0" + "platform-dev": [], + "plugin-api-version": "2.6.0" } diff --git a/config/reference.php b/config/reference.php index 5785616..36b6d7f 100644 --- a/config/reference.php +++ b/config/reference.php @@ -471,7 +471,7 @@ use Symfony\Component\Config\Loader\ParamConfigurator as Param; * }, * disallow_search_engine_index?: bool|Param, // Enabled by default when debug is enabled. // Default: true * http_client?: bool|array{ // HTTP Client configuration - * enabled?: bool|Param, // Default: false + * enabled?: bool|Param, // Default: true * max_host_connections?: int|Param, // The maximum number of connections to a single host. * default_options?: array{ * headers?: array, diff --git a/migrations/Version20260811120000.php b/migrations/Version20260811120000.php new file mode 100644 index 0000000..843ae74 --- /dev/null +++ b/migrations/Version20260811120000.php @@ -0,0 +1,29 @@ +addSql('ALTER TABLE task ADD scheduled_for DATE DEFAULT NULL, ADD recurrence_interval INT DEFAULT NULL, ADD recurrence_unit VARCHAR(10) DEFAULT NULL'); + $this->addSql("UPDATE task SET recurrence_interval = 1, recurrence_unit = 'day' WHERE is_recurring = 1 AND (recurrence_interval IS NULL OR recurrence_unit IS NULL)"); + $this->addSql('UPDATE task SET scheduled_for = DATE(created_at) WHERE scheduled_for IS NULL'); + $this->addSql('ALTER TABLE task MODIFY scheduled_for DATE NOT NULL'); + } + + public function down(Schema $schema): void + { + $this->addSql('ALTER TABLE task DROP scheduled_for, DROP recurrence_interval, DROP recurrence_unit'); + } +} diff --git a/migrations/Version20260811150000.php b/migrations/Version20260811150000.php new file mode 100644 index 0000000..7f40d83 --- /dev/null +++ b/migrations/Version20260811150000.php @@ -0,0 +1,34 @@ +addSql('CREATE TABLE settings (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, latitude NUMERIC(10, 7) DEFAULT NULL, longitude NUMERIC(10, 7) DEFAULT NULL, location_updated_at DATETIME DEFAULT NULL, UNIQUE INDEX UNIQ_SETTINGS_USER (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4'); + $this->addSql('CREATE TABLE weather_forecast (id INT AUTO_INCREMENT NOT NULL, settings_id INT NOT NULL, forecast_date DATE NOT NULL, temperature_max DOUBLE PRECISION DEFAULT NULL, temperature_min DOUBLE PRECISION DEFAULT NULL, precipitation_sum DOUBLE PRECISION DEFAULT NULL, precipitation_probability_max INT DEFAULT NULL, rain_sum DOUBLE PRECISION DEFAULT NULL, weather_code INT DEFAULT NULL, fetched_at DATETIME NOT NULL, INDEX IDX_FORECAST_SETTINGS (settings_id), UNIQUE INDEX weather_forecast_settings_day (settings_id, forecast_date), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4'); + $this->addSql('ALTER TABLE settings ADD CONSTRAINT FK_SETTINGS_USER FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE'); + $this->addSql('ALTER TABLE weather_forecast ADD CONSTRAINT FK_FORECAST_SETTINGS FOREIGN KEY (settings_id) REFERENCES settings (id) ON DELETE CASCADE'); + $this->addSql("ALTER TABLE task ADD is_outdoor TINYINT(1) NOT NULL DEFAULT 0, ADD weather_profile VARCHAR(30) NOT NULL DEFAULT 'none'"); + } + + public function down(Schema $schema): void + { + $this->addSql('ALTER TABLE weather_forecast DROP FOREIGN KEY FK_FORECAST_SETTINGS'); + $this->addSql('ALTER TABLE settings DROP FOREIGN KEY FK_SETTINGS_USER'); + $this->addSql('DROP TABLE weather_forecast'); + $this->addSql('DROP TABLE settings'); + $this->addSql('ALTER TABLE task DROP is_outdoor, DROP weather_profile'); + } +} diff --git a/migrations/Version20260811164537.php b/migrations/Version20260811164537.php new file mode 100644 index 0000000..632af44 --- /dev/null +++ b/migrations/Version20260811164537.php @@ -0,0 +1,31 @@ +settings->findWithLocation() as $settings) { + $rows += $this->weather->refresh($settings); + } + + $output->writeln(sprintf('Refreshed %d daily weather forecasts.', $rows)); + + return Command::SUCCESS; + } +} diff --git a/src/Controller/LocationController.php b/src/Controller/LocationController.php new file mode 100644 index 0000000..f9f0d9d --- /dev/null +++ b/src/Controller/LocationController.php @@ -0,0 +1,42 @@ +isCsrfTokenValid('weather_location', $request->getPayload()->getString('_token'))) { + throw $this->createAccessDeniedException('Invalid CSRF token.'); + } + + $latitude = $request->getPayload()->get('latitude'); + $longitude = $request->getPayload()->get('longitude'); + if (!is_numeric($latitude) || !is_numeric($longitude) || abs((float) $latitude) > 90 || abs((float) $longitude) > 180) { + return $this->json(['saved' => false], Response::HTTP_UNPROCESSABLE_ENTITY); + } + + $user = $this->getUser(); + if (!$user instanceof User) { + throw $this->createAccessDeniedException(); + } + + $settings = $user->getSettings() ?? (new Settings())->setUser($user); + $user->setSettings($settings); + $settings->updateLocation((float) $latitude, (float) $longitude); + $entityManager->persist($settings); + $entityManager->flush(); + + return $this->json(['saved' => true]); + } +} diff --git a/src/Controller/TaskController.php b/src/Controller/TaskController.php index fdaf649..8a987af 100644 --- a/src/Controller/TaskController.php +++ b/src/Controller/TaskController.php @@ -1,11 +1,14 @@ normaliseBatteryLevel($request->getSession()->get('social_battery', 3)); + $selectedDate = $this->selectedDate($request); + $newTask = new Task(); + $newTask->setScheduledFor($selectedDate); + $settings = $this->currentSettings(); + return $this->render('task/index.html.twig', [ - 'tasks' => $taskRecommendationService->sort($taskRepository->findAll(), $batteryLevel), + 'tasks' => $taskRecommendationService->sort($taskRepository->findAll(), $batteryLevel, $selectedDate, $settings), 'battery_level' => $batteryLevel, 'battery_budget' => $taskRecommendationService->budgetFor($batteryLevel), - 'form' => $this->createForm(TaskType::class, new Task(), ['include_active' => false]), + 'selected_date' => $selectedDate, + 'form' => $this->createForm(TaskType::class, $newTask, ['include_active' => false]), + 'weather_forecast' => $selectedDate->format('Y-m-d') === (new \DateTimeImmutable('today'))->format('Y-m-d') ? $weatherService->cachedForecastFor($settings, $selectedDate) : null, + 'has_saved_location' => $settings?->hasLocation() ?? false, ]); } @@ -38,7 +49,7 @@ final class TaskController extends AbstractController $batteryLevel = $taskRecommendationService->normaliseBatteryLevel($request->getPayload()->getInt('social_battery')); $request->getSession()->set('social_battery', $batteryLevel); - return $this->renderTaskRecommendations($taskRepository, $taskRecommendationService, $batteryLevel); + return $this->renderTaskRecommendations($taskRepository, $taskRecommendationService, $batteryLevel, $this->selectedDate($request)); } #[Route('/new', name: 'app_task_new', methods: ['GET', 'POST'])] @@ -56,14 +67,17 @@ final class TaskController extends AbstractController if ($request->headers->has('HX-Request')) { $batteryLevel = $taskRecommendationService->normaliseBatteryLevel($request->getSession()->get('social_battery', 3)); + $selectedDate = $task->getScheduledFor() ?? new \DateTimeImmutable('today'); + $newTask = (new Task())->setScheduledFor($selectedDate); return $this->render('task/_task_composer_response.html.twig', [ - 'form' => $this->createForm(TaskType::class, new Task(), ['include_active' => false]), - 'tasks' => $taskRecommendationService->sort($taskRepository->findAll(), $batteryLevel), + 'form' => $this->createForm(TaskType::class, $newTask, ['include_active' => false]), + 'tasks' => $taskRecommendationService->sort($taskRepository->findAll(), $batteryLevel, $selectedDate), + 'selected_date' => $selectedDate, ]); } - return $this->redirectToRoute('app_task_index', [], Response::HTTP_SEE_OTHER); + return $this->redirectToRoute('app_task_index', ['date' => $task->getScheduledFor()?->format('Y-m-d')], Response::HTTP_SEE_OTHER); } return $this->render('task/new.html.twig', [ @@ -114,7 +128,7 @@ final class TaskController extends AbstractController $batteryLevel = $taskRecommendationService->normaliseBatteryLevel($request->getSession()->get('social_battery', 3)); - return $this->renderTaskList($taskRepository, $taskRecommendationService, $batteryLevel); + return $this->renderTaskList($taskRepository, $taskRecommendationService, $batteryLevel, $this->selectedDate($request)); } #[Route('/{id}', name: 'app_task_delete', methods: ['POST'])] @@ -132,19 +146,43 @@ final class TaskController extends AbstractController return $this->redirectToRoute('app_task_index', [], Response::HTTP_SEE_OTHER); } - private function renderTaskList(TaskRepository $taskRepository, TaskRecommendationService $taskRecommendationService, int $batteryLevel): Response + private function renderTaskList(TaskRepository $taskRepository, TaskRecommendationService $taskRecommendationService, int $batteryLevel, \DateTimeImmutable $selectedDate): Response { return $this->render('task/_task_list.html.twig', [ - 'tasks' => $taskRecommendationService->sort($taskRepository->findAll(), $batteryLevel), + 'tasks' => $taskRecommendationService->sort($taskRepository->findAll(), $batteryLevel, $selectedDate), + 'selected_date' => $selectedDate, ]); } - private function renderTaskRecommendations(TaskRepository $taskRepository, TaskRecommendationService $taskRecommendationService, int $batteryLevel): Response + private function renderTaskRecommendations(TaskRepository $taskRepository, TaskRecommendationService $taskRecommendationService, int $batteryLevel, \DateTimeImmutable $selectedDate): Response { return $this->render('task/_task_recommendations.html.twig', [ - 'tasks' => $taskRecommendationService->sort($taskRepository->findAll(), $batteryLevel), + 'tasks' => $taskRecommendationService->sort($taskRepository->findAll(), $batteryLevel, $selectedDate), 'battery_level' => $batteryLevel, 'battery_budget' => $taskRecommendationService->budgetFor($batteryLevel), + 'selected_date' => $selectedDate, ]); } -} + + private function selectedDate(Request $request): \DateTimeImmutable + { + $date = $request->getPayload()->getString('date'); + if ('' === $date) { + $date = $request->query->getString('date'); + } + + if ('' !== $date && false !== ($selectedDate = \DateTimeImmutable::createFromFormat('!Y-m-d', $date))) { + return $selectedDate; + } + + return new \DateTimeImmutable('today'); + } + private function currentSettings(): ?Settings + { + $user = $this->getUser(); + + return $user instanceof User ? $user->getSettings() : null; + } + + } + diff --git a/src/Entity/Settings.php b/src/Entity/Settings.php new file mode 100644 index 0000000..65d22f4 --- /dev/null +++ b/src/Entity/Settings.php @@ -0,0 +1,49 @@ +id; } + public function getUser(): ?User { return $this->user; } + public function setUser(User $user): static { $this->user = $user; return $this; } + public function getLatitude(): ?string { return $this->latitude; } + public function getLongitude(): ?string { return $this->longitude; } + public function getLocationUpdatedAt(): ?\DateTimeImmutable { return $this->locationUpdatedAt; } + + public function updateLocation(float $latitude, float $longitude): static + { + $this->latitude = number_format($latitude, 7, '.', ''); + $this->longitude = number_format($longitude, 7, '.', ''); + $this->locationUpdatedAt = new \DateTimeImmutable(); + + return $this; + } + + public function hasLocation(): bool + { + return null !== $this->latitude && null !== $this->longitude; + } +} diff --git a/src/Entity/Task.php b/src/Entity/Task.php index 10f2a53..d2defcc 100644 --- a/src/Entity/Task.php +++ b/src/Entity/Task.php @@ -35,9 +35,25 @@ class Task #[ORM\Column] private ?bool $isActive = null; + #[ORM\Column(type: Types::DATE_IMMUTABLE)] + private ?\DateTimeImmutable $scheduledFor = null; + + #[ORM\Column(nullable: true)] + private ?int $recurrenceInterval = null; + + #[ORM\Column(length: 10, nullable: true)] + private ?string $recurrenceUnit = null; + #[ORM\Column] private ?\DateTimeImmutable $createdAt = null; + #[ORM\Column] + private ?bool $isOutdoor = false; + + #[ORM\Column(length: 30)] + private ?string $weatherProfile = 'none'; + + #[ORM\Column] private ?\DateTimeImmutable $updatedAt = null; @@ -48,6 +64,9 @@ class Task $this->priority = 'medium'; $this->isRecurring = false; $this->isActive = true; + $this->recurrenceInterval = 1; + $this->recurrenceUnit = 'day'; + $this->scheduledFor = $now->setTime(0, 0); $this->createdAt = $now; $this->updatedAt = $now; } @@ -141,6 +160,67 @@ class Task return $this; } + public function getScheduledFor(): ?\DateTimeImmutable + { + return $this->scheduledFor; + } + + public function setScheduledFor(\DateTimeImmutable $scheduledFor): static + { + $this->scheduledFor = $scheduledFor->setTime(0, 0); + + return $this; + } + + public function getRecurrenceInterval(): ?int + { + return $this->recurrenceInterval; + } + + public function setRecurrenceInterval(?int $recurrenceInterval): static + { + $this->recurrenceInterval = $recurrenceInterval; + + return $this; + } + + public function getRecurrenceUnit(): ?string + { + return $this->recurrenceUnit; + } + + + public function isOutdoor(): ?bool + { + return $this->isOutdoor; + } + + public function setIsOutdoor(bool $isOutdoor): static + { + $this->isOutdoor = $isOutdoor; + + return $this; + } + + public function getWeatherProfile(): ?string + { + return $this->weatherProfile; + } + + public function setWeatherProfile(string $weatherProfile): static + { + $this->weatherProfile = $weatherProfile; + + return $this; + } + public function setRecurrenceUnit(?string $recurrenceUnit): static + { + $this->recurrenceUnit = $recurrenceUnit; + + return $this; + } + + public function getCreatedAt(): ?\DateTimeImmutable { return $this->createdAt; diff --git a/src/Entity/User.php b/src/Entity/User.php index 8fee99a..18c599e 100644 --- a/src/Entity/User.php +++ b/src/Entity/User.php @@ -32,6 +32,11 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface #[ORM\Column] private ?string $password = null; + #[ORM\OneToOne(mappedBy: 'user', cascade: ['persist', 'remove'])] + private ?Settings $settings = null; + + + public function getId(): ?int { return $this->id; @@ -81,12 +86,29 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface return $this; } - /** + + public function getSettings(): ?Settings + { + return $this->settings; + } + + public function setSettings(Settings $settings): static + { + $this->settings = $settings; + if ($settings->getUser() !== $this) { + $settings->setUser($this); + } + + return $this; + } + + /* * @see PasswordAuthenticatedUserInterface */ public function getPassword(): ?string { return $this->password; + } public function setPassword(string $password): static @@ -102,7 +124,7 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface public function __serialize(): array { $data = (array) $this; - $data["\0".self::class."\0password"] = hash('crc32c', $this->password); + $data["\0" . self::class . "\0password"] = hash('crc32c', $this->password); return $data; } diff --git a/src/Entity/WeatherForecast.php b/src/Entity/WeatherForecast.php new file mode 100644 index 0000000..f904064 --- /dev/null +++ b/src/Entity/WeatherForecast.php @@ -0,0 +1,65 @@ +id; } + public function getSettings(): ?Settings { return $this->settings; } + public function setSettings(Settings $settings): static { $this->settings = $settings; return $this; } + public function getForecastDate(): ?\DateTimeImmutable { return $this->forecastDate; } + public function setForecastDate(\DateTimeImmutable $date): static { $this->forecastDate = $date->setTime(0, 0); return $this; } + public function getTemperatureMax(): ?float { return $this->temperatureMax; } + public function setTemperatureMax(?float $value): static { $this->temperatureMax = $value; return $this; } + public function getTemperatureMin(): ?float { return $this->temperatureMin; } + public function setTemperatureMin(?float $value): static { $this->temperatureMin = $value; return $this; } + public function getPrecipitationSum(): ?float { return $this->precipitationSum; } + public function setPrecipitationSum(?float $value): static { $this->precipitationSum = $value; return $this; } + public function getPrecipitationProbabilityMax(): ?int { return $this->precipitationProbabilityMax; } + public function setPrecipitationProbabilityMax(?int $value): static { $this->precipitationProbabilityMax = $value; return $this; } + public function getRainSum(): ?float { return $this->rainSum; } + public function setRainSum(?float $value): static { $this->rainSum = $value; return $this; } + public function getWeatherCode(): ?int { return $this->weatherCode; } + public function setWeatherCode(?int $value): static { $this->weatherCode = $value; return $this; } + public function getFetchedAt(): ?\DateTimeImmutable { return $this->fetchedAt; } + public function setFetchedAt(\DateTimeImmutable $fetchedAt): static { $this->fetchedAt = $fetchedAt; return $this; } +} diff --git a/src/Form/TaskType.php b/src/Form/TaskType.php index 0291bf7..7682182 100644 --- a/src/Form/TaskType.php +++ b/src/Form/TaskType.php @@ -6,6 +6,7 @@ use App\Entity\Task; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; +use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; @@ -40,9 +41,41 @@ class TaskType extends AbstractType 'required' => false, 'attr' => ['placeholder' => 'e.g. Home'], ]) + ->add('isOutdoor', CheckboxType::class, [ + 'label' => 'Outdoor task', + 'required' => false, + ]) + ->add('weatherProfile', ChoiceType::class, [ + 'label' => 'Weather handling', + 'choices' => [ + 'No weather adjustment' => 'none', + 'Needs dry weather (e.g. sweeping)' => 'dry_weather', + 'Water plants' => 'water_plants', + ], + ]) ->add('isRecurring', CheckboxType::class, [ 'label' => 'Repeats', 'required' => false, + ]) + ->add('scheduledFor', DateType::class, [ + 'label' => 'First scheduled for', + 'widget' => 'single_text', + 'input' => 'datetime_immutable', + ]) + ->add('recurrenceInterval', IntegerType::class, [ + 'label' => 'Every', + 'required' => false, + 'attr' => ['min' => 1, 'placeholder' => '1'], + ]) + ->add('recurrenceUnit', ChoiceType::class, [ + 'label' => 'Repeat unit', + 'required' => false, + 'placeholder' => 'Choose a unit', + 'choices' => [ + 'Days' => 'day', + 'Weeks' => 'week', + 'Months' => 'month', + ], ]); if ($options['include_active']) { diff --git a/src/Repository/SettingsRepository.php b/src/Repository/SettingsRepository.php new file mode 100644 index 0000000..d417b62 --- /dev/null +++ b/src/Repository/SettingsRepository.php @@ -0,0 +1,22 @@ + */ +class SettingsRepository extends ServiceEntityRepository +{ + public function __construct(ManagerRegistry $registry) { parent::__construct($registry, Settings::class); } + + /** @return Settings[] */ + public function findWithLocation(): array + { + return $this->createQueryBuilder('s') + ->andWhere('s.latitude IS NOT NULL') + ->andWhere('s.longitude IS NOT NULL') + ->getQuery()->getResult(); + } +} diff --git a/src/Repository/WeatherForecastRepository.php b/src/Repository/WeatherForecastRepository.php new file mode 100644 index 0000000..599bcdf --- /dev/null +++ b/src/Repository/WeatherForecastRepository.php @@ -0,0 +1,19 @@ + */ +class WeatherForecastRepository extends ServiceEntityRepository +{ + public function __construct(ManagerRegistry $registry) { parent::__construct($registry, WeatherForecast::class); } + + public function findForDay(Settings $settings, \DateTimeImmutable $day): ?WeatherForecast + { + return $this->findOneBy(['settings' => $settings, 'forecastDate' => $day->setTime(0, 0)]); + } +} diff --git a/src/Service/TaskRecommendationService.php b/src/Service/TaskRecommendationService.php index a42b4ef..ae7841a 100644 --- a/src/Service/TaskRecommendationService.php +++ b/src/Service/TaskRecommendationService.php @@ -3,6 +3,9 @@ namespace App\Service; use App\Entity\Task; +use App\Entity\Settings; +use App\Entity\WeatherForecast; +use App\Repository\WeatherForecastRepository; /** * Central home for recommendation rules. Add future signals such as priority, @@ -19,6 +22,13 @@ final class TaskRecommendationService 5 => 180, ]; + public function __construct( + private WeatherEvaluator $weatherEvaluator, + private WeatherForecastRepository $weatherForecasts, + ) { + } + + public function normaliseBatteryLevel(int $batteryLevel): int { return max(1, min(5, $batteryLevel)); @@ -32,22 +42,65 @@ final class TaskRecommendationService /** * @param Task[] $tasks * - * @return Task[] Active tasks that fit the selected energy budget are first. + * @return Task[] Tasks scheduled for the selected day, ordered for the selected energy budget. */ - public function sort(array $tasks, int $batteryLevel): array + public function sort(array $tasks, int $batteryLevel, \DateTimeImmutable $selectedDate, ?Settings $settings = null): array { + $forecast = null === $settings ? null : $this->weatherForecasts->findForDay($settings, $selectedDate); + $previousForecast = null === $settings ? null : $this->weatherForecasts->findForDay($settings, $selectedDate->modify('-1 day')); + $batteryLevel = $this->normaliseBatteryLevel($batteryLevel); $budget = $this->budgetFor($batteryLevel); + $selectedDate = $selectedDate->setTime(0, 0); + $tasks = array_values(array_filter( + $tasks, + fn (Task $task): bool => $this->isScheduledFor($task, $selectedDate) + || $this->weatherEvaluator->shouldCarryForward($task, $selectedDate, $previousForecast, $forecast), + )); - usort($tasks, function (Task $left, Task $right) use ($batteryLevel, $budget): int { - return $this->sortKey($left, $batteryLevel, $budget) <=> $this->sortKey($right, $batteryLevel, $budget); + + usort($tasks, function (Task $left, Task $right) use ($batteryLevel, $budget, $forecast, $previousForecast): int { + return $this->sortKey($left, $batteryLevel, $budget, $forecast, $previousForecast) <=> $this->sortKey($right, $batteryLevel, $budget, $forecast, $previousForecast); }); return $tasks; } + public function isScheduledFor(Task $task, \DateTimeImmutable $selectedDate): bool + { + $scheduledFor = $task->getScheduledFor(); + if (null === $scheduledFor || $selectedDate < $scheduledFor) { + return false; + } + + if (!$task->isRecurring()) { + return $scheduledFor->format('Y-m-d') === $selectedDate->format('Y-m-d'); + } + + $interval = $task->getRecurrenceInterval(); + $unit = $task->getRecurrenceUnit(); + if (null === $interval || $interval < 1 || !in_array($unit, ['day', 'week', 'month'], true)) { + return false; + } + + return match ($unit) { + 'day' => 0 === $scheduledFor->diff($selectedDate)->days % $interval, + 'week' => 0 === $scheduledFor->diff($selectedDate)->days % (7 * $interval), + 'month' => $this->isMonthlyOccurrence($scheduledFor, $selectedDate, $interval), + }; + } + + private function isMonthlyOccurrence(\DateTimeImmutable $scheduledFor, \DateTimeImmutable $selectedDate, int $interval): bool + { + $monthsApart = ((int) $selectedDate->format('Y') - (int) $scheduledFor->format('Y')) * 12 + + (int) $selectedDate->format('n') - (int) $scheduledFor->format('n'); + + return 0 === $monthsApart % $interval + && $scheduledFor->format('d') === $selectedDate->format('d'); + } + /** @return array */ - private function sortKey(Task $task, int $batteryLevel, int $budget): array + private function sortKey(Task $task, int $batteryLevel, int $budget, ?WeatherForecast $forecast, ?WeatherForecast $previousForecast): array { $duration = $task->getEstimatedDurationMinutes(); $hasDuration = null !== $duration; @@ -59,7 +112,9 @@ final class TaskRecommendationService $durationScore = $batteryLevel <= 2 ? $duration : abs($budget - $duration); return [ + -$this->weatherEvaluator->scoreAdjustment($task, $forecast, $previousForecast), $task->isActive() ? 0 : 1, + $task->isRecurring() ? 0 : 1, $hasDuration ? 0 : 1, $fitsBudget ? 0 : 1, $durationScore, diff --git a/src/Service/WeatherEvaluator.php b/src/Service/WeatherEvaluator.php new file mode 100644 index 0000000..1256af4 --- /dev/null +++ b/src/Service/WeatherEvaluator.php @@ -0,0 +1,52 @@ +isOutdoor() || null === $forecast) { + return 0; + } + + if ('water_plants' === $task->getWeatherProfile()) { + if ($this->isWet($forecast) || $this->isWet($previousDay)) { + return -80; + } + + return ($forecast->getTemperatureMax() ?? 0) >= 25 ? 50 : 15; + } + + if ('dry_weather' === $task->getWeatherProfile()) { + return $this->isWet($forecast) ? -100 : 20; + } + + return $this->isWet($forecast) ? -45 : 0; + } + + public function isWet(?WeatherForecast $forecast): bool + { + return null !== $forecast + && (($forecast->getPrecipitationProbabilityMax() ?? 0) >= 50 + || ($forecast->getPrecipitationSum() ?? 0) >= 1.0 + || ($forecast->getRainSum() ?? 0) >= 1.0); + } + + public function isDryForecast(?WeatherForecast $forecast): bool + { + return null !== $forecast && !$this->isWet($forecast); + } + + public function shouldCarryForward(Task $task, \DateTimeImmutable $selectedDay, ?WeatherForecast $previousDay, ?WeatherForecast $currentDay): bool + { + return $task->isOutdoor() + && 'dry_weather' === $task->getWeatherProfile() + && $task->getScheduledFor()?->format('Y-m-d') === $selectedDay->modify('-1 day')->format('Y-m-d') + && $this->isWet($previousDay) + && $this->isDryForecast($currentDay); + } +} diff --git a/src/Service/WeatherService.php b/src/Service/WeatherService.php new file mode 100644 index 0000000..45e2255 --- /dev/null +++ b/src/Service/WeatherService.php @@ -0,0 +1,68 @@ +hasLocation() ? null : $this->forecasts->findForDay($settings, $day); + } + + public function refresh(Settings $settings): int + { + if (!$settings->hasLocation()) { + return 0; + } + + $response = $this->httpClient->request('GET', 'https://api.open-meteo.com/v1/forecast', [ + 'query' => [ + 'latitude' => $settings->getLatitude(), + 'longitude' => $settings->getLongitude(), + 'daily' => 'temperature_2m_max,temperature_2m_min,precipitation_sum,precipitation_probability_max,rain_sum,weather_code', + 'past_days' => 1, + 'forecast_days' => 8, + 'timezone' => 'auto', + ], + ])->toArray(); + + $daily = $response['daily'] ?? []; + $dates = $daily['time'] ?? []; + $count = 0; + foreach ($dates as $index => $date) { + $forecast = $this->forecasts->findForDay($settings, new \DateTimeImmutable($date)) ?? new WeatherForecast(); + $forecast + ->setSettings($settings) + ->setForecastDate(new \DateTimeImmutable($date)) + ->setTemperatureMax($this->floatValue($daily['temperature_2m_max'][$index] ?? null)) + ->setTemperatureMin($this->floatValue($daily['temperature_2m_min'][$index] ?? null)) + ->setPrecipitationSum($this->floatValue($daily['precipitation_sum'][$index] ?? null)) + ->setPrecipitationProbabilityMax($this->intValue($daily['precipitation_probability_max'][$index] ?? null)) + ->setRainSum($this->floatValue($daily['rain_sum'][$index] ?? null)) + ->setWeatherCode($this->intValue($daily['weather_code'][$index] ?? null)) + ->setFetchedAt(new \DateTimeImmutable()); + $this->entityManager->persist($forecast); + ++$count; + } + + $this->entityManager->flush(); + + return $count; + } + + private function floatValue(mixed $value): ?float { return null === $value ? null : (float) $value; } + private function intValue(mixed $value): ?int { return null === $value ? null : (int) $value; } +} diff --git a/templates/task/_task_composer.html.twig b/templates/task/_task_composer.html.twig index e6a10d3..fc99b81 100644 --- a/templates/task/_task_composer.html.twig +++ b/templates/task/_task_composer.html.twig @@ -23,7 +23,20 @@
{{ form_row(form.estimatedDurationMinutes) }}
{{ form_row(form.priority) }}
{{ form_row(form.category) }}
-
{{ form_row(form.isRecurring) }}
+
{{ form_row(form.scheduledFor) }}
+
{{ form_row(form.isOutdoor) }}
+
{{ form_row(form.weatherProfile) }}
+
{{ form_row(form.isOutdoor) }}
+
{{ form_row(form.weatherProfile) }}
+
+ {{ form_widget(form.isRecurring, {attr: {class: 'task-composer__repeat-input'}}) }} + {{ form_label(form.isRecurring) }} + {{ form_errors(form.isRecurring) }} +
+
{{ form_row(form.recurrenceInterval) }}
+
{{ form_row(form.recurrenceUnit) }}
+
+
Add a note diff --git a/templates/task/_task_composer_response.html.twig b/templates/task/_task_composer_response.html.twig index dea446e..a219e22 100644 --- a/templates/task/_task_composer_response.html.twig +++ b/templates/task/_task_composer_response.html.twig @@ -1,2 +1,2 @@ {{ include('task/_task_composer.html.twig', {form: form}) }} -{{ include('task/_task_list.html.twig', {tasks: tasks, out_of_band: true}) }} +{{ include('task/_task_list.html.twig', {tasks: tasks, selected_date: selected_date|default(null), out_of_band: true}) }} diff --git a/templates/task/_task_item.html.twig b/templates/task/_task_item.html.twig index 337a564..8b1fef5 100644 --- a/templates/task/_task_item.html.twig +++ b/templates/task/_task_item.html.twig @@ -1,5 +1,6 @@
  • + Mark {{ task.title }} as {{ task.isActive ? 'completed' : 'active' }} {{ task.title }} + {% if task.isRecurring %} + Every {{ task.recurrenceInterval }} {{ task.recurrenceUnit }}{{ task.recurrenceInterval != 1 ? 's' : '' }} + {% endif %}
    + + + +
  • diff --git a/templates/task/_task_list.html.twig b/templates/task/_task_list.html.twig index ddf819a..bff253a 100644 --- a/templates/task/_task_list.html.twig +++ b/templates/task/_task_list.html.twig @@ -1,6 +1,6 @@
      {% for task in tasks %} - {{ include('task/_task_item.html.twig', {task: task}) }} + {{ include('task/_task_item.html.twig', {task: task, selected_date: selected_date|default(null)}) }} {% else %}
    • No tasks yet.
    • {% endfor %} diff --git a/templates/task/_task_recommendations.html.twig b/templates/task/_task_recommendations.html.twig index c8a1e77..0fcbed4 100644 --- a/templates/task/_task_recommendations.html.twig +++ b/templates/task/_task_recommendations.html.twig @@ -9,10 +9,11 @@ diff --git a/templates/task/index.html.twig b/templates/task/index.html.twig index bac609b..6fd7115 100644 --- a/templates/task/index.html.twig +++ b/templates/task/index.html.twig @@ -6,14 +6,35 @@

      Tasks

      + +
      + + + + {% if weather_forecast %} + {{ include('task/_weather_forecast.html.twig', {forecast: weather_forecast}) }} {{ include('task/_task_composer.html.twig', {form: form}) }} + {% endif %} {{ include('task/_task_recommendations.html.twig', { tasks: tasks, battery_level: battery_level, - battery_budget: battery_budget + battery_budget: battery_budget, + selected_date: selected_date }) }}