This commit is contained in:
Marek Lenczewski
2026-03-31 18:09:15 +02:00
parent b6a4548732
commit b998940caa
48 changed files with 717 additions and 816 deletions

View File

@@ -2,8 +2,11 @@
namespace App\Controller\Api;
use App\DTO\Request\CreateTaskRequest;
use App\DTO\Request\UpdateTaskRequest;
use App\Entity\Task;
use App\Repository\TaskRepository;
use App\Service\TaskGenerator;
use App\Service\TaskManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
@@ -11,20 +14,42 @@ use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\Routing\Attribute\Route;
#[Route('/api/tasks', name: 'tasks.')]
#[Route('/api/tasks')]
class TaskController extends AbstractController
{
public function __construct(
private TaskManager $taskManager,
private TaskGenerator $taskGenerator,
private TaskRepository $taskRepository,
) {}
#[Route('/{id}', name: 'show', methods: ['GET'])]
#[Route('', name: 'tasks.index', methods: ['GET'])]
public function index(): JsonResponse
{
$today = new \DateTimeImmutable('today');
$end = $today->modify('+6 days');
$this->taskGenerator->generateForRange($today, $end);
$tasks = $this->taskRepository->findAllWithRelations();
return $this->json($tasks, context: ['groups' => ['task:read', 'category:read']]);
}
#[Route('/{id}', name: 'tasks.show', methods: ['GET'])]
public function show(Task $task): JsonResponse
{
return $this->json($task, context: ['groups' => ['task:read', 'category:read']]);
}
#[Route('/{id}', name: 'update', methods: ['PUT'])]
#[Route('', name: 'tasks.create', methods: ['POST'])]
public function create(#[MapRequestPayload] CreateTaskRequest $dto): JsonResponse
{
$task = $this->taskManager->createTask($dto);
return $this->json($task, Response::HTTP_CREATED, context: ['groups' => ['task:read', 'category:read']]);
}
#[Route('/{id}', name: 'tasks.update', methods: ['PUT'])]
public function update(#[MapRequestPayload] UpdateTaskRequest $dto, Task $task): JsonResponse
{
$task = $this->taskManager->updateTask($task, $dto);
@@ -32,11 +57,19 @@ class TaskController extends AbstractController
return $this->json($task, context: ['groups' => ['task:read', 'category:read']]);
}
#[Route('/{id}', name: 'delete', methods: ['DELETE'])]
#[Route('/{id}', name: 'tasks.delete', methods: ['DELETE'])]
public function delete(Task $task): JsonResponse
{
$this->taskManager->deleteTask($task);
return $this->json(null, Response::HTTP_NO_CONTENT);
}
#[Route('/{id}/toggle', name: 'tasks.toggle', methods: ['PATCH'])]
public function toggle(Task $task): JsonResponse
{
$task = $this->taskManager->toggleTask($task);
return $this->json($task, context: ['groups' => ['task:read', 'category:read']]);
}
}

View File

@@ -3,13 +3,10 @@
namespace App\Controller\Api;
use App\DTO\Request\CreateSchemaRequest;
use App\DTO\Request\ToggleRequest;
use App\DTO\Request\UpdateSchemaRequest;
use App\Entity\TaskSchema;
use App\Repository\TaskSchemaRepository;
use App\Service\TaskManager;
use App\Service\TaskSchemaManager;
use App\Service\TaskViewBuilder;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
@@ -23,41 +20,16 @@ class TaskSchemaController extends AbstractController
public function __construct(
private TaskSchemaRepository $schemaRepository,
private TaskSchemaManager $schemaManager,
private TaskManager $taskManager,
private TaskViewBuilder $taskViewBuilder,
) {}
#[Route('', name: 'schemas.index', methods: ['GET'])]
public function index(): JsonResponse
{
$schemas = $this->schemaRepository->findAll();
return $this->json($schemas, context: ['groups' => ['schema:read', 'category:read']]);
}
#[Route('/week', name: 'schemas.week', methods: ['GET'])]
public function week(Request $request): JsonResponse
{
$startParam = $request->query->get('start');
$start = $startParam ? new \DateTimeImmutable($startParam) : new \DateTimeImmutable('today');
return $this->json($this->taskViewBuilder->buildWeekView($start), context: ['groups' => ['task:read', 'category:read']]);
}
#[Route('/all', name: 'schemas.all', methods: ['GET'])]
public function allSchemas(): JsonResponse
{
$schemas = $this->schemaRepository->findBy([], ['createdAt' => 'DESC']);
return $this->json($schemas, context: ['groups' => ['schema:read', 'category:read']]);
}
#[Route('/all-tasks', name: 'schemas.allTasks', methods: ['GET'])]
public function allTasks(): JsonResponse
{
return $this->json($this->taskViewBuilder->buildAllTasksView(), context: ['groups' => ['task:read', 'category:read']]);
}
#[Route('/{id}', name: 'schemas.show', methods: ['GET'])]
public function show(TaskSchema $schema): JsonResponse
{
@@ -67,9 +39,13 @@ class TaskSchemaController extends AbstractController
#[Route('', name: 'schemas.create', methods: ['POST'])]
public function create(#[MapRequestPayload] CreateSchemaRequest $dto): JsonResponse
{
$schema = $this->schemaManager->createSchema($dto);
$result = $this->schemaManager->createSchema($dto);
return $this->json($schema, Response::HTTP_CREATED, context: ['groups' => ['schema:read', 'category:read']]);
if (is_array($result)) {
return $this->json($result, Response::HTTP_CREATED, context: ['groups' => ['task:read', 'category:read']]);
}
return $this->json($result, Response::HTTP_CREATED, context: ['groups' => ['schema:read', 'category:read']]);
}
#[Route('/{id}', name: 'schemas.update', methods: ['PUT'])]
@@ -81,18 +57,11 @@ class TaskSchemaController extends AbstractController
}
#[Route('/{id}', name: 'schemas.delete', methods: ['DELETE'])]
public function delete(TaskSchema $schema): JsonResponse
public function delete(TaskSchema $schema, Request $request): JsonResponse
{
$this->schemaManager->deleteSchema($schema);
$deleteTasks = (bool) $request->query->get('deleteTasks', false);
$this->schemaManager->deleteSchema($schema, $deleteTasks);
return $this->json(null, Response::HTTP_NO_CONTENT);
}
#[Route('/{id}/toggle', name: 'schemas.toggle', methods: ['PATCH'])]
public function toggle(TaskSchema $schema, #[MapRequestPayload] ToggleRequest $dto): JsonResponse
{
$result = $this->taskManager->toggleTaskStatus($schema, $dto);
return $this->json($result);
}
}

View File

@@ -14,11 +14,8 @@ class CreateSchemaRequest
public ?int $categoryId = null;
public ?string $status = null;
public ?string $taskType = null;
public ?string $deadline = null;
public ?string $type = null;
public ?string $startDate = null;
public ?string $endDate = null;
public ?array $weekdays = null;
public ?array $monthDays = null;
public ?array $yearDays = null;
public ?array $days = null;
}

View File

@@ -0,0 +1,15 @@
<?php
namespace App\DTO\Request;
use Symfony\Component\Validator\Constraints as Assert;
class CreateTaskRequest
{
#[Assert\NotBlank]
#[Assert\Length(max: 255)]
public ?string $name = null;
public ?int $categoryId = null;
public ?string $date = null;
}

View File

@@ -8,7 +8,7 @@ trait SchemaValidationTrait
{
public function validate(ExecutionContextInterface $context): void
{
if ($this->taskType !== null && $this->taskType !== 'einzel') {
if ($this->type !== null && $this->type !== 'single') {
if ($this->startDate !== null && $this->endDate !== null && $this->endDate < $this->startDate) {
$context->buildViolation('endDate muss >= startDate sein.')
->atPath('endDate')
@@ -16,26 +16,19 @@ trait SchemaValidationTrait
}
}
if ($this->taskType === 'woechentlich') {
if (empty($this->weekdays)) {
$context->buildViolation('weekdays darf nicht leer sein.')
->atPath('weekdays')
if ($this->type === 'single') {
$year = $this->days['year'] ?? null;
if (empty($year)) {
$context->buildViolation('Mindestens ein Datum muss ausgewählt werden.')
->atPath('days')
->addViolation();
}
}
if ($this->taskType === 'monatlich') {
if (empty($this->monthDays)) {
$context->buildViolation('monthDays darf nicht leer sein.')
->atPath('monthDays')
->addViolation();
}
}
if ($this->taskType === 'multi' || $this->taskType === 'jaehrlich') {
if (empty($this->yearDays)) {
$context->buildViolation('yearDays darf nicht leer sein.')
->atPath('yearDays')
if ($this->type === 'custom') {
if (empty($this->days)) {
$context->buildViolation('days darf nicht leer sein.')
->atPath('days')
->addViolation();
}
}

View File

@@ -1,8 +0,0 @@
<?php
namespace App\DTO\Request;
class ToggleRequest
{
public ?string $date = null;
}

View File

@@ -15,11 +15,8 @@ class UpdateSchemaRequest
public ?int $categoryId = null;
public bool $hasCategoryId = false;
public ?string $status = null;
public ?string $taskType = null;
public ?string $deadline = null;
public ?string $type = null;
public ?string $startDate = null;
public ?string $endDate = null;
public ?array $weekdays = null;
public ?array $monthDays = null;
public ?array $yearDays = null;
public ?array $days = null;
}

View File

@@ -1,16 +0,0 @@
<?php
namespace App\DTO\Response;
use Symfony\Component\Serializer\Attribute\Groups;
class DayResponse
{
public function __construct(
#[Groups(['task:read'])]
public readonly string $date,
/** @var \App\Entity\Task[] */
#[Groups(['task:read'])]
public readonly array $tasks,
) {}
}

View File

@@ -1,10 +0,0 @@
<?php
namespace App\DTO\Response;
class ToggleResponse
{
public function __construct(
public readonly bool $completed,
) {}
}

View File

@@ -1,17 +0,0 @@
<?php
namespace App\DTO\Response;
use Symfony\Component\Serializer\Attribute\Groups;
class WeekViewResponse
{
public function __construct(
/** @var \App\Entity\Task[] */
#[Groups(['task:read'])]
public readonly array $tasksWithoutDeadline,
/** @var DayResponse[] */
#[Groups(['task:read'])]
public readonly array $days,
) {}
}

View File

@@ -10,7 +10,6 @@ use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Serializer\Attribute\SerializedName;
#[ORM\Entity(repositoryClass: TaskRepository::class)]
#[ORM\UniqueConstraint(columns: ['task_id', 'date'])]
class Task
{
public function __construct()
@@ -21,30 +20,33 @@ class Task
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[Groups(['task:read'])]
private ?int $id = null;
#[ORM\ManyToOne]
#[ORM\JoinColumn(name: 'task_id', nullable: false, onDelete: 'CASCADE')]
private TaskSchema $schema;
#[ORM\JoinColumn(name: 'task_id', nullable: true, onDelete: 'SET NULL')]
private ?TaskSchema $schema = null;
#[ORM\Column(length: 255, nullable: true)]
#[Groups(['task:read'])]
private ?string $name = null;
#[ORM\ManyToOne]
#[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')]
#[Groups(['task:read'])]
private ?Category $category = null;
#[ORM\Column(type: Types::DATE_MUTABLE, nullable: true)]
#[Groups(['task:read'])]
private ?\DateTimeInterface $date = null;
#[ORM\Column(length: 20, enumType: TaskStatus::class)]
#[Groups(['task:read'])]
private TaskStatus $status = TaskStatus::Active;
#[ORM\Column(type: Types::DATETIME_MUTABLE)]
private \DateTimeInterface $createdAt;
#[Groups(['task:read'])]
#[SerializedName('taskId')]
public function getId(): ?int
{
return $this->id;
@@ -52,17 +54,17 @@ class Task
#[Groups(['task:read'])]
#[SerializedName('schemaId')]
public function getSchemaId(): int
public function getSchemaId(): ?int
{
return $this->schema->getId();
return $this->schema?->getId();
}
public function getSchema(): TaskSchema
public function getSchema(): ?TaskSchema
{
return $this->schema;
}
public function setSchema(TaskSchema $schema): static
public function setSchema(?TaskSchema $schema): static
{
$this->schema = $schema;
return $this;
@@ -79,7 +81,6 @@ class Task
return $this;
}
#[Groups(['task:read'])]
public function getCategory(): ?Category
{
return $this->category;
@@ -91,32 +92,17 @@ class Task
return $this;
}
#[Groups(['task:read'])]
#[SerializedName('name')]
public function getEffectiveName(): string
{
return $this->name ?? $this->schema->getName();
}
#[Groups(['task:read'])]
public function getDate(): ?\DateTimeInterface
{
return $this->date;
}
#[Groups(['task:read'])]
public function getDeadline(): ?\DateTimeInterface
{
return $this->date;
}
public function setDate(?\DateTimeInterface $date): static
{
$this->date = $date;
return $this;
}
#[Groups(['task:read'])]
public function getStatus(): TaskStatus
{
return $this->status;
@@ -128,13 +114,6 @@ class Task
return $this;
}
#[Groups(['task:read'])]
#[SerializedName('taskType')]
public function getTaskType(): string
{
return $this->schema->getTaskType()->value;
}
#[Groups(['task:read'])]
#[SerializedName('isPast')]
public function isPast(): bool

View File

@@ -8,6 +8,7 @@ use App\Repository\TaskSchemaRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Serializer\Attribute\SerializedName;
#[ORM\Entity(repositoryClass: TaskSchemaRepository::class)]
class TaskSchema
@@ -26,8 +27,9 @@ class TaskSchema
#[Groups(['schema:read', 'schema:write'])]
private TaskSchemaStatus $status = TaskSchemaStatus::Active;
#[ORM\Column(length: 20, enumType: TaskSchemaType::class)]
#[ORM\Column(name: 'task_type', length: 20, enumType: TaskSchemaType::class)]
#[Groups(['schema:read', 'schema:write'])]
#[SerializedName('type')]
private TaskSchemaType $taskType = TaskSchemaType::Single;
#[ORM\ManyToOne]
@@ -35,10 +37,6 @@ class TaskSchema
#[Groups(['schema:read'])]
private ?Category $category = null;
#[ORM\Column(type: Types::DATE_MUTABLE, nullable: true)]
#[Groups(['schema:read', 'schema:write'])]
private ?\DateTimeInterface $deadline = null;
#[ORM\Column(type: Types::DATE_MUTABLE, nullable: true)]
#[Groups(['schema:read', 'schema:write'])]
private ?\DateTimeInterface $startDate = null;
@@ -49,15 +47,7 @@ class TaskSchema
#[ORM\Column(type: Types::JSON, nullable: true)]
#[Groups(['schema:read', 'schema:write'])]
private ?array $weekdays = null;
#[ORM\Column(type: Types::JSON, nullable: true)]
#[Groups(['schema:read', 'schema:write'])]
private ?array $monthDays = null;
#[ORM\Column(type: Types::JSON, nullable: true)]
#[Groups(['schema:read', 'schema:write'])]
private ?array $yearDays = null;
private ?array $days = null;
#[ORM\Column(type: Types::DATETIME_MUTABLE)]
#[Groups(['schema:read'])]
@@ -117,17 +107,6 @@ class TaskSchema
return $this;
}
public function getDeadline(): ?\DateTimeInterface
{
return $this->deadline;
}
public function setDeadline(?\DateTimeInterface $deadline): static
{
$this->deadline = $deadline;
return $this;
}
public function getStartDate(): ?\DateTimeInterface
{
return $this->startDate;
@@ -150,36 +129,14 @@ class TaskSchema
return $this;
}
public function getWeekdays(): ?array
public function getDays(): ?array
{
return $this->weekdays;
return $this->days;
}
public function setWeekdays(?array $weekdays): static
public function setDays(?array $days): static
{
$this->weekdays = $weekdays;
return $this;
}
public function getMonthDays(): ?array
{
return $this->monthDays;
}
public function setMonthDays(?array $monthDays): static
{
$this->monthDays = $monthDays;
return $this;
}
public function getYearDays(): ?array
{
return $this->yearDays;
}
public function setYearDays(?array $yearDays): static
{
$this->yearDays = $yearDays;
$this->days = $days;
return $this;
}

View File

@@ -4,7 +4,6 @@ namespace App\Enum;
enum TaskSchemaStatus: string
{
case Active = 'aktiv';
case Completed = 'erledigt';
case Inactive = 'inaktiv';
case Active = 'active';
case Disabled = 'disabled';
}

View File

@@ -4,10 +4,7 @@ namespace App\Enum;
enum TaskSchemaType: string
{
case Single = 'einzel';
case Daily = 'taeglich';
case Multi = 'multi';
case Weekly = 'woechentlich';
case Monthly = 'monatlich';
case Yearly = 'jaehrlich';
case Single = 'single';
case Daily = 'daily';
case Custom = 'custom';
}

View File

@@ -4,6 +4,6 @@ namespace App\Enum;
enum TaskStatus: string
{
case Active = 'aktiv';
case Completed = 'erledigt';
case Active = 'active';
case Done = 'done';
}

View File

@@ -4,7 +4,6 @@ namespace App\Repository;
use App\Entity\Task;
use App\Entity\TaskSchema;
use App\Enum\TaskStatus;
use App\Enum\TaskSchemaStatus;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
@@ -19,6 +18,22 @@ class TaskRepository extends ServiceEntityRepository
parent::__construct($registry, Task::class);
}
/**
* @return Task[]
*/
public function findAllWithRelations(): array
{
return $this->createQueryBuilder('task')
->leftJoin('task.schema', 'schema')
->leftJoin('task.category', 'category')
->addSelect('schema', 'category')
->where('task.schema IS NULL OR schema.status != :disabled')
->setParameter('disabled', TaskSchemaStatus::Disabled)
->orderBy('task.date', 'ASC')
->getQuery()
->getResult();
}
public function findBySchemaAndDate(TaskSchema $schema, \DateTimeInterface $date): ?Task
{
return $this->createQueryBuilder('task')
@@ -36,15 +51,15 @@ class TaskRepository extends ServiceEntityRepository
public function findInRange(\DateTimeInterface $from, \DateTimeInterface $to): array
{
return $this->createQueryBuilder('task')
->join('task.schema', 'schema')
->leftJoin('task.schema', 'schema')
->leftJoin('task.category', 'category')
->addSelect('schema', 'category')
->where('task.date >= :from')
->andWhere('task.date <= :to')
->andWhere('schema.status != :excluded')
->andWhere('task.schema IS NULL OR schema.status != :disabled')
->setParameter('from', $from)
->setParameter('to', $to)
->setParameter('excluded', TaskSchemaStatus::Inactive)
->setParameter('disabled', TaskSchemaStatus::Disabled)
->orderBy('task.date', 'ASC')
->getQuery()
->getResult();
@@ -59,6 +74,7 @@ class TaskRepository extends ServiceEntityRepository
->select('IDENTITY(task.schema) AS schemaId', 'task.date')
->where('task.date >= :from')
->andWhere('task.date <= :to')
->andWhere('task.schema IS NOT NULL')
->setParameter('from', $from)
->setParameter('to', $to)
->getQuery()
@@ -88,62 +104,4 @@ class TaskRepository extends ServiceEntityRepository
->getQuery()
->getResult();
}
public function deleteFutureBySchema(TaskSchema $schema, \DateTimeInterface $fromDate): void
{
$this->createQueryBuilder('task')
->delete()
->where('task.schema = :schema')
->andWhere('task.date >= :from')
->setParameter('schema', $schema)
->setParameter('from', $fromDate)
->getQuery()
->execute();
}
public function deleteFutureActiveBySchema(TaskSchema $schema, \DateTimeInterface $fromDate): void
{
$this->createQueryBuilder('task')
->delete()
->where('task.schema = :schema')
->andWhere('task.date >= :from')
->andWhere('task.status = :status')
->setParameter('schema', $schema)
->setParameter('from', $fromDate)
->setParameter('status', TaskStatus::Active)
->getQuery()
->execute();
}
/**
* @return Task[]
*/
public function findAllSorted(): array
{
return $this->createQueryBuilder('task')
->join('task.schema', 'schema')
->leftJoin('task.category', 'category')
->addSelect('schema', 'category')
->where('task.date IS NOT NULL')
->orderBy('task.date', 'DESC')
->getQuery()
->getResult();
}
/**
* @return Task[]
*/
public function findWithoutDate(): array
{
return $this->createQueryBuilder('task')
->join('task.schema', 'schema')
->leftJoin('task.category', 'category')
->addSelect('schema', 'category')
->where('task.date IS NULL')
->andWhere('schema.status != :excluded')
->setParameter('excluded', TaskSchemaStatus::Inactive)
->orderBy('task.createdAt', 'DESC')
->getQuery()
->getResult();
}
}

View File

@@ -24,14 +24,12 @@ class TaskSchemaRepository extends ServiceEntityRepository
public function findActiveSchemasInRange(\DateTimeInterface $from, \DateTimeInterface $to): array
{
return $this->createQueryBuilder('t')
->where('t.status != :excluded')
->andWhere(
'(t.taskType = :einzel AND (t.deadline IS NULL OR (t.deadline >= :from AND t.deadline <= :to)))'
. ' OR '
. '(t.taskType != :einzel AND t.startDate <= :to AND (t.endDate IS NULL OR t.endDate >= :from))'
)
->setParameter('excluded', TaskSchemaStatus::Inactive)
->setParameter('einzel', TaskSchemaType::Single->value)
->where('t.status = :active')
->andWhere('t.taskType IN (:types)')
->andWhere('t.startDate <= :to')
->andWhere('t.endDate IS NULL OR t.endDate >= :from')
->setParameter('active', TaskSchemaStatus::Active)
->setParameter('types', [TaskSchemaType::Daily, TaskSchemaType::Custom])
->setParameter('from', $from)
->setParameter('to', $to)
->getQuery()

View File

@@ -11,22 +11,6 @@ class DeadlineCalculator
* @return \DateTimeInterface[]
*/
public function getDeadlinesForRange(TaskSchema $schema, \DateTimeInterface $from, \DateTimeInterface $to): array
{
if ($schema->getTaskType() === TaskSchemaType::Single) {
$deadline = $schema->getDeadline();
if ($deadline === null) {
return [];
}
return ($deadline >= $from && $deadline <= $to) ? [$deadline] : [];
}
return $this->getRecurringDeadlines($schema, $from, $to);
}
/**
* @return \DateTimeInterface[]
*/
private function getRecurringDeadlines(TaskSchema $schema, \DateTimeInterface $from, \DateTimeInterface $to): array
{
$startDate = $schema->getStartDate();
if ($startDate === null) {
@@ -59,21 +43,30 @@ class DeadlineCalculator
{
return match ($schema->getTaskType()) {
TaskSchemaType::Daily => true,
TaskSchemaType::Weekly => in_array((int) $date->format('N'), $schema->getWeekdays() ?? [], true),
TaskSchemaType::Monthly => in_array((int) $date->format('j'), $schema->getMonthDays() ?? [], true),
TaskSchemaType::Multi, TaskSchemaType::Yearly => $this->matchesYearDays($schema, $date),
TaskSchemaType::Custom => $this->matchesDays($schema, $date),
default => false,
};
}
private function matchesYearDays(TaskSchema $schema, \DateTimeImmutable $date): bool
private function matchesDays(TaskSchema $schema, \DateTimeImmutable $date): bool
{
$month = (int) $date->format('n');
$day = (int) $date->format('j');
$days = $schema->getDays() ?? [];
foreach ($schema->getYearDays() ?? [] as $yd) {
if (($yd['month'] ?? 0) === $month && ($yd['day'] ?? 0) === $day) {
return true;
if (!empty($days['week']) && in_array((int) $date->format('N'), $days['week'], true)) {
return true;
}
if (!empty($days['month']) && in_array((int) $date->format('j'), $days['month'], true)) {
return true;
}
if (!empty($days['year'])) {
$month = (int) $date->format('n');
$day = (int) $date->format('j');
foreach ($days['year'] as $yd) {
if (($yd['month'] ?? 0) === $month && ($yd['day'] ?? 0) === $day) {
return true;
}
}
}

View File

@@ -3,8 +3,6 @@
namespace App\Service;
use App\Entity\Task;
use App\Enum\TaskSchemaType;
use App\Enum\TaskSchemaStatus;
use App\Repository\TaskRepository;
use App\Repository\TaskSchemaRepository;
use Doctrine\ORM\EntityManagerInterface;
@@ -34,6 +32,7 @@ class TaskGenerator
$task = new Task();
$task->setSchema($schema);
$task->setDate(new \DateTime($deadline->format('Y-m-d')));
$task->setName($schema->getName());
$task->setCategory($schema->getCategory());
$this->em->persist($task);
@@ -47,31 +46,4 @@ class TaskGenerator
$this->em->flush();
}
}
public function generateForTasksWithoutDate(): void
{
$schemas = $this->schemaRepository->findBy([
'taskType' => TaskSchemaType::Single,
'deadline' => null,
'status' => TaskSchemaStatus::Active,
]);
$hasNew = false;
foreach ($schemas as $schema) {
$existing = $this->taskRepository->findOneBy(['schema' => $schema]);
if (!$existing) {
$task = new Task();
$task->setSchema($schema);
$task->setDate(null);
$task->setCategory($schema->getCategory());
$this->em->persist($task);
$hasNew = true;
}
}
if ($hasNew) {
$this->em->flush();
}
}
}

View File

@@ -2,26 +2,40 @@
namespace App\Service;
use App\DTO\Request\ToggleRequest;
use App\DTO\Request\CreateTaskRequest;
use App\DTO\Request\UpdateTaskRequest;
use App\DTO\Response\ToggleResponse;
use App\Entity\Task;
use App\Entity\TaskSchema;
use App\Enum\TaskSchemaStatus;
use App\Enum\TaskStatus;
use App\Repository\CategoryRepository;
use App\Repository\TaskRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;
class TaskManager
{
public function __construct(
private EntityManagerInterface $em,
private CategoryRepository $categoryRepository,
private TaskRepository $taskRepository,
) {}
public function createTask(CreateTaskRequest $request): Task
{
$task = new Task();
$task->setName($request->name);
if ($request->categoryId !== null) {
$category = $this->categoryRepository->find($request->categoryId);
$task->setCategory($category);
}
if ($request->date !== null) {
$task->setDate(new \DateTime($request->date));
}
$this->em->persist($task);
$this->em->flush();
return $task;
}
public function updateTask(Task $task, UpdateTaskRequest $request): Task
{
$task->setName($request->name);
@@ -43,27 +57,15 @@ class TaskManager
return $task;
}
public function toggleTaskStatus(TaskSchema $schema, ToggleRequest $request): ToggleResponse
public function toggleTask(Task $task): Task
{
if ($schema->getStatus() === TaskSchemaStatus::Inactive) {
throw new HttpException(422, 'Inaktive Aufgaben können nicht umgeschaltet werden.');
}
$task = $request->date !== null
? $this->taskRepository->findBySchemaAndDate($schema, new \DateTime($request->date))
: $this->taskRepository->findOneBy(['schema' => $schema, 'date' => null]);
if (!$task) {
throw new HttpException(404, 'Task nicht gefunden.');
}
$newStatus = $task->getStatus() === TaskStatus::Active
? TaskStatus::Completed
? TaskStatus::Done
: TaskStatus::Active;
$task->setStatus($newStatus);
$this->em->flush();
return new ToggleResponse(completed: $newStatus === TaskStatus::Completed);
return $task;
}
public function deleteTask(Task $task): void

View File

@@ -4,10 +4,12 @@ namespace App\Service;
use App\DTO\Request\CreateSchemaRequest;
use App\DTO\Request\UpdateSchemaRequest;
use App\Entity\Task;
use App\Entity\TaskSchema;
use App\Enum\TaskSchemaStatus;
use App\Enum\TaskSchemaType;
use App\Repository\CategoryRepository;
use App\Repository\TaskRepository;
use Doctrine\ORM\EntityManagerInterface;
class TaskSchemaManager
@@ -15,10 +17,11 @@ class TaskSchemaManager
public function __construct(
private EntityManagerInterface $em,
private CategoryRepository $categoryRepository,
private TaskRepository $taskRepository,
private TaskSynchronizer $taskSynchronizer,
) {}
public function createSchema(CreateSchemaRequest $request): TaskSchema
public function createSchema(CreateSchemaRequest $request): TaskSchema|array
{
$schema = new TaskSchema();
$schema->setName($request->name ?? '');
@@ -30,6 +33,14 @@ class TaskSchemaManager
$this->em->persist($schema);
$this->em->flush();
if ($schema->getTaskType() === TaskSchemaType::Single) {
$tasks = $this->createSingleTasks($schema);
$this->em->remove($schema);
$this->em->flush();
return $tasks;
}
return $schema;
}
@@ -50,6 +61,19 @@ class TaskSchemaManager
return $schema;
}
public function deleteSchema(TaskSchema $schema, bool $deleteTasks = false): void
{
if ($deleteTasks) {
$tasks = $this->taskRepository->findBy(['schema' => $schema]);
foreach ($tasks as $task) {
$this->em->remove($task);
}
}
$this->em->remove($schema);
$this->em->flush();
}
private function applyFields(TaskSchema $schema, CreateSchemaRequest|UpdateSchemaRequest $request): void
{
if ($request->status !== null) {
@@ -59,19 +83,16 @@ class TaskSchemaManager
}
}
if ($request->taskType !== null) {
$taskType = TaskSchemaType::tryFrom($request->taskType);
if ($request->type !== null) {
$taskType = TaskSchemaType::tryFrom($request->type);
if ($taskType !== null) {
$schema->setTaskType($taskType);
}
}
$schema->setDeadline($request->deadline !== null ? new \DateTime($request->deadline) : null);
$schema->setStartDate($request->startDate !== null ? new \DateTime($request->startDate) : null);
$schema->setEndDate($request->endDate !== null ? new \DateTime($request->endDate) : null);
$schema->setWeekdays($request->weekdays);
$schema->setMonthDays($request->monthDays);
$schema->setYearDays($request->yearDays);
$schema->setDays($request->days);
}
private function resolveCategory(TaskSchema $schema, UpdateSchemaRequest|CreateSchemaRequest $request): void
@@ -93,16 +114,37 @@ class TaskSchemaManager
}
}
public function deleteSchema(TaskSchema $schema): void
{
$this->em->remove($schema);
$this->em->flush();
}
private function applyDefaults(TaskSchema $schema): void
{
if ($schema->getTaskType() !== TaskSchemaType::Single && $schema->getStartDate() === null) {
$schema->setStartDate(new \DateTime('today'));
}
}
/**
* @return Task[]
*/
private function createSingleTasks(TaskSchema $schema): array
{
$days = $schema->getDays()['year'] ?? [];
$tasks = [];
foreach ($days as $yd) {
$month = $yd['month'] ?? 1;
$day = $yd['day'] ?? 1;
$date = new \DateTime(sprintf('%d-%02d-%02d', (int) date('Y'), $month, $day));
$task = new Task();
$task->setName($schema->getName());
$task->setCategory($schema->getCategory());
$task->setDate($date);
$this->em->persist($task);
$tasks[] = $task;
}
$this->em->flush();
return $tasks;
}
}

View File

@@ -4,7 +4,6 @@ namespace App\Service;
use App\Entity\Task;
use App\Entity\TaskSchema;
use App\Enum\TaskSchemaType;
use App\Repository\TaskRepository;
use Doctrine\ORM\EntityManagerInterface;
@@ -30,8 +29,7 @@ class TaskSynchronizer
$existingByDate = $this->loadExistingByDate($schema, $today);
$this->removeObsoleteTasks($existingByDate, $shouldExist);
$this->handleNullDateTasks($schema);
$this->resetFutureOverrides($existingByDate);
$this->resetFutureOverrides($schema, $existingByDate);
$this->createMissingTasks($schema, $deadlines, $existingByDate);
$this->em->flush();
@@ -75,30 +73,14 @@ class TaskSynchronizer
}
}
private function handleNullDateTasks(TaskSchema $schema): void
{
$nullDateTasks = $this->taskRepository->findBy(['schema' => $schema, 'date' => null]);
if ($schema->getTaskType() === TaskSchemaType::Single && $schema->getDeadline() === null) {
foreach ($nullDateTasks as $task) {
$task->setName(null);
$task->setCategory($schema->getCategory());
}
} else {
foreach ($nullDateTasks as $task) {
$this->em->remove($task);
}
}
}
/**
* @param array<string, Task> $existingByDate
*/
private function resetFutureOverrides(array $existingByDate): void
private function resetFutureOverrides(TaskSchema $schema, array $existingByDate): void
{
foreach ($existingByDate as $task) {
$task->setName(null);
$task->setCategory($task->getSchema()->getCategory());
$task->setName($schema->getName());
$task->setCategory($schema->getCategory());
}
}
@@ -114,6 +96,7 @@ class TaskSynchronizer
$task = new Task();
$task->setSchema($schema);
$task->setDate(new \DateTime($dateKey));
$task->setName($schema->getName());
$task->setCategory($schema->getCategory());
$this->em->persist($task);

View File

@@ -1,78 +0,0 @@
<?php
namespace App\Service;
use App\DTO\Response\DayResponse;
use App\DTO\Response\WeekViewResponse;
use App\Entity\Task;
use App\Repository\TaskRepository;
class TaskViewBuilder
{
public function __construct(
private TaskGenerator $taskGenerator,
private TaskRepository $taskRepository,
) {}
public function buildWeekView(?\DateTimeImmutable $start = null): WeekViewResponse
{
$start = $start ?? new \DateTimeImmutable('today');
$end = $start->modify('+6 days');
$this->taskGenerator->generateForRange($start, $end);
$this->taskGenerator->generateForTasksWithoutDate();
$tasks = $this->taskRepository->findInRange($start, $end);
$days = [];
$current = $start;
while ($current <= $end) {
$days[$current->format('Y-m-d')] = [];
$current = $current->modify('+1 day');
}
foreach ($tasks as $task) {
$dateKey = $task->getDate()->format('Y-m-d');
if (isset($days[$dateKey])) {
$days[$dateKey][] = $task;
}
}
$tasksWithoutDeadline = $this->taskRepository->findWithoutDate();
$dayResponses = [];
foreach ($days as $date => $dayTasks) {
usort($dayTasks, fn(Task $a, Task $b) => strcmp($a->getEffectiveName(), $b->getEffectiveName()));
$dayResponses[] = new DayResponse(
date: $date,
tasks: $dayTasks,
);
}
return new WeekViewResponse(
tasksWithoutDeadline: $tasksWithoutDeadline,
days: $dayResponses,
);
}
/**
* @return Task[]
*/
public function buildAllTasksView(): array
{
$this->taskGenerator->generateForTasksWithoutDate();
$result = [];
$noDate = $this->taskRepository->findWithoutDate();
foreach ($noDate as $task) {
$result[] = $task;
}
$tasks = $this->taskRepository->findAllSorted();
foreach ($tasks as $task) {
$result[] = $task;
}
return $result;
}
}