WIP: weather integration
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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]);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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']) {
|
||||
|
||||
@@ -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)]);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
Reference in New Issue
Block a user