WIP: weather integration

This commit is contained in:
Joren de Graaf
2026-08-11 21:11:31 +02:00
parent f63134d00f
commit 6a20cb80ca
30 changed files with 1054 additions and 31 deletions
+21
View File
@@ -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();
}
});
});
+70
View File
@@ -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;
+2
View File
@@ -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.*"
}
Generated
+183 -4
View File
@@ -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"
}
+1 -1
View File
@@ -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<string, mixed>,
+29
View File
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260811120000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add task scheduling and recurrence fields.';
}
public function up(Schema $schema): void
{
$this->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');
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260811150000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add user weather settings, cached daily forecasts, and task weather metadata.';
}
public function up(Schema $schema): void
{
$this->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');
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20260811164537 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20260811191017 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
}
}
+1 -1
View File
@@ -17,4 +17,4 @@
"sass": "^1.102.0",
"sass-loader": "^17.0.0"
}
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Command;
use App\Repository\SettingsRepository;
use App\Service\WeatherService;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(name: 'app:weather:refresh', description: 'Refresh cached Open-Meteo forecasts for saved locations.')]
final class RefreshWeatherCommand extends Command
{
public function __construct(private SettingsRepository $settings, private WeatherService $weather)
{
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$rows = 0;
foreach ($this->settings->findWithLocation() as $settings) {
$rows += $this->weather->refresh($settings);
}
$output->writeln(sprintf('Refreshed %d daily weather forecasts.', $rows));
return Command::SUCCESS;
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Controller;
use App\Entity\Settings;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
final class LocationController extends AbstractController
{
#[Route('/task/location', name: 'app_task_location', methods: ['POST'])]
public function save(Request $request, EntityManagerInterface $entityManager): JsonResponse
{
if (!$this->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]);
}
}
+51 -13
View File
@@ -1,11 +1,14 @@
<?php
namespace App\Controller;
use App\Entity\Settings;
use App\Entity\User;
use App\Entity\Task;
use App\Form\TaskType;
use App\Repository\TaskRepository;
use App\Service\TaskRecommendationService;
use App\Service\WeatherService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
@@ -16,15 +19,23 @@ use Symfony\Component\Routing\Attribute\Route;
final class TaskController extends AbstractController
{
#[Route(name: 'app_task_index', methods: ['GET'])]
public function index(Request $request, TaskRepository $taskRepository, TaskRecommendationService $taskRecommendationService): Response
public function index(Request $request, TaskRepository $taskRepository, TaskRecommendationService $taskRecommendationService, WeatherService $weatherService): Response
{
$batteryLevel = $taskRecommendationService->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;
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace App\Entity;
use App\Repository\SettingsRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: SettingsRepository::class)]
class Settings
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\OneToOne(inversedBy: 'settings', cascade: ['persist', 'remove'])]
#[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
private ?User $user = null;
#[ORM\Column(nullable: true, precision: 10, scale: 7)]
private ?string $latitude = null;
#[ORM\Column(nullable: true, precision: 10, scale: 7)]
private ?string $longitude = null;
#[ORM\Column(nullable: true)]
private ?\DateTimeImmutable $locationUpdatedAt = null;
public function getId(): ?int { return $this->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;
}
}
+80
View File
@@ -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;
+24 -2
View File
@@ -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;
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Entity;
use App\Repository\WeatherForecastRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: WeatherForecastRepository::class)]
#[ORM\UniqueConstraint(name: 'weather_forecast_settings_day', fields: ['settings', 'forecastDate'])]
class WeatherForecast
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\ManyToOne]
#[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
private ?Settings $settings = null;
#[ORM\Column(type: Types::DATE_IMMUTABLE)]
private ?\DateTimeImmutable $forecastDate = null;
#[ORM\Column(nullable: true)]
private ?float $temperatureMax = null;
#[ORM\Column(nullable: true)]
private ?float $temperatureMin = null;
#[ORM\Column(nullable: true)]
private ?float $precipitationSum = null;
#[ORM\Column(nullable: true)]
private ?int $precipitationProbabilityMax = null;
#[ORM\Column(nullable: true)]
private ?float $rainSum = null;
#[ORM\Column(nullable: true)]
private ?int $weatherCode = null;
#[ORM\Column]
private ?\DateTimeImmutable $fetchedAt = null;
public function getId(): ?int { return $this->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; }
}
+33
View File
@@ -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']) {
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Repository;
use App\Entity\Settings;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/** @extends ServiceEntityRepository<Settings> */
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();
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Repository;
use App\Entity\Settings;
use App\Entity\WeatherForecast;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/** @extends ServiceEntityRepository<WeatherForecast> */
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)]);
}
}
+60 -5
View File
@@ -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<int, int|string> */
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,
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace App\Service;
use App\Entity\Task;
use App\Entity\WeatherForecast;
final class WeatherEvaluator
{
public function scoreAdjustment(Task $task, ?WeatherForecast $forecast, ?WeatherForecast $previousDay = null): int
{
if (!$task->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);
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
namespace App\Service;
use App\Entity\Settings;
use App\Entity\WeatherForecast;
use App\Repository\WeatherForecastRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
final class WeatherService
{
public function __construct(
private HttpClientInterface $httpClient,
private EntityManagerInterface $entityManager,
private WeatherForecastRepository $forecasts,
) {
}
public function cachedForecastFor(?Settings $settings, \DateTimeImmutable $day): ?WeatherForecast
{
return null === $settings || !$settings->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; }
}
+14 -1
View File
@@ -23,7 +23,20 @@
<div>{{ form_row(form.estimatedDurationMinutes) }}</div>
<div>{{ form_row(form.priority) }}</div>
<div>{{ form_row(form.category) }}</div>
<div class="task-composer__checks">{{ form_row(form.isRecurring) }}</div>
<div>{{ form_row(form.scheduledFor) }}</div>
<div>{{ form_row(form.isOutdoor) }}</div>
<div>{{ form_row(form.weatherProfile) }}</div>
<div>{{ form_row(form.isOutdoor) }}</div>
<div>{{ form_row(form.weatherProfile) }}</div>
<div class="task-composer__repeat">
{{ form_widget(form.isRecurring, {attr: {class: 'task-composer__repeat-input'}}) }}
{{ form_label(form.isRecurring) }}
{{ form_errors(form.isRecurring) }}
<div class="task-composer__repeat-fields">
<div>{{ form_row(form.recurrenceInterval) }}</div>
<div>{{ form_row(form.recurrenceUnit) }}</div>
</div>
</div>
</div>
<details class="task-composer__notes">
<summary>Add a note</summary>
@@ -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}) }}
+8
View File
@@ -1,5 +1,6 @@
<li class="task-list__item{{ not task.isActive ? ' task-list__item--completed' : '' }}">
<form class="task-list__completion-form">
<input type="hidden" name="date" value="{{ selected_date|default('now')|date('Y-m-d') }}">
<input type="hidden" name="_token" value="{{ csrf_token('completion' ~ task.id) }}">
<input
id="task-completion-{{ task.id }}"
@@ -20,6 +21,9 @@
<span class="visually-hidden">Mark {{ task.title }} as {{ task.isActive ? 'completed' : 'active' }}</span>
</label>
<a class="task-list__title" href="{{ path('app_task_edit', {'id': task.id}) }}">{{ task.title }}</a>
{% if task.isRecurring %}
<span class="task-list__recurrence">Every {{ task.recurrenceInterval }} {{ task.recurrenceUnit }}{{ task.recurrenceInterval != 1 ? 's' : '' }}</span>
{% endif %}
</form>
<form
class="task-list__remove-form"
@@ -33,4 +37,8 @@
<span class="material-symbols-outlined" aria-hidden="true">delete</span>
</button>
</form>
<a class="task-list__title" href="{{ path('app_task_edit', {'id': task.id}) }}">
<span class="material-symbols-outlined" aria-hidden="true">edit</span>
</a>
</li>
+1 -1
View File
@@ -1,6 +1,6 @@
<ul id="task-list" class="task-list" aria-label="Tasks"{% if out_of_band|default(false) %} hx-swap-oob="outerHTML"{% endif %}>
{% 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 %}
<li class="task-list__empty">No tasks yet.</li>
{% endfor %}
@@ -9,10 +9,11 @@
<section class="social-battery" aria-labelledby="social-battery-title">
<div>
<h2 id="social-battery-title">Social battery</h2>
<p>Choose today’s energy. We’ll put tasks that fit your {{ battery_budget }}-minute budget first.</p>
<p>Choose your energy. We’ll put tasks that fit your {{ battery_budget }}-minute budget first.</p>
</div>
<form class="social-battery__levels">
<input type="hidden" name="_token" value="{{ csrf_token('social_battery') }}">
<input type="hidden" name="date" value="{{ selected_date|default('now')|date('Y-m-d') }}">
{% for level, option in battery_levels %}
<input
id="social-battery-{{ level }}"
@@ -0,0 +1,7 @@
<section class="weather-forecast" aria-label="Today’s weather forecast">
<span class="material-symbols-outlined" aria-hidden="true">{{ forecast.weatherCode in [0, 1] ? 'sunny' : (forecast.weatherCode in [2, 3] ? 'cloud' : 'rainy') }}</span>
<div>
<strong>{{ forecast.temperatureMax|round }}°C</strong>
<span>{{ forecast.weatherCode in [0, 1] ? 'Clear' : (forecast.weatherCode in [2, 3] ? 'Cloudy' : 'Rain possible') }}</span>
</div>
</section>
+22 -1
View File
@@ -6,14 +6,35 @@
<div class="container">
<div class="task-list-header">
<h1>Tasks</h1>
<nav class="day-picker" aria-label="Choose task day">
<a href="{{ path('app_task_index', {date: selected_date|date_modify('-1 day')|date('Y-m-d')}) }}" aria-label="Previous day">‹</a>
<div>
<strong>{{ selected_date|date('l, j F') }}</strong>
{% if selected_date|date('Y-m-d') != 'now'|date('Y-m-d') %}
<a href="{{ path('app_task_index') }}">Today</a>
{% endif %}
</div>
<a href="{{ path('app_task_index', {date: selected_date|date_modify('+1 day')|date('Y-m-d')}) }}" aria-label="Next day">›</a>
</nav>
</div>
<button class="weather-location" type="button" data-weather-location data-location-url="{{ path('app_task_location') }}" data-location-token="{{ csrf_token('weather_location') }}">
<span class="material-symbols-outlined" aria-hidden="true">my_location</span>
{{ has_saved_location ? 'Update weather location' : 'Use my location for weather' }}
</button>
{% 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
}) }}
</div>