first delivery

This commit is contained in:
Alexandre Gain committed 2026-11-07 19:31:49 +01:00
1 parent 793fbc0c91
commit f6684f3b2e
65 files changed
+5828

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
/**
* For repositories of typed plan items (description items, allocation items).
*/
trait CountsItemsByTypeTrait
{
/**
* Number of items per type key, for the types that are in use.
*
* @return array<string, int>
*/
public function countByType(): array
{
$alias = $this->getTableAlias();
$rows = $this->createQueryBuilder($alias)
->select($alias.'.type AS type, COUNT('.$alias.'.id) AS total')
->groupBy($alias.'.type')
->getQuery()
->getArrayResult();
$counts = [];
foreach ($rows as $row) {
$counts[(string) $row['type']] = (int) $row['total'];
}
return $counts;
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
/**
* An object with an optional start and end date. Checked by the EndDateAfterStartDate constraint.
*/
interface DateRangeInterface
{
public function getStartDate(): ?\DateTime;
public function getEndDate(): ?\DateTime;
}
+514
View File
@@ -0,0 +1,514 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata;
use Mautic\CategoryBundle\Entity\Category;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
use Mautic\CoreBundle\Entity\FormEntity;
use Mautic\UserBundle\Entity\User;
use MauticPlugin\PlanBundle\Validator\Constraints\EndDateAfterStartDate;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Constraints\Valid;
use Symfony\Component\Validator\Mapping\ClassMetadata;
class Plan extends FormEntity implements DateRangeInterface
{
public const TABLE_NAME = 'plans';
public const VERSION_MIN = 1;
public const VERSION_MAX = 99;
private ?int $id = null;
/**
* Plan version, 1 to 99. Edited by hand; not related to Doctrine optimistic locking.
*/
private ?int $version = self::VERSION_MIN;
/**
* @var Collection<int, PlanObjective>
*/
private Collection $objectives;
/**
* The content of the Description tab. Each item has a type set up by the admin in
* Settings > Configuration > Plan.
*
* @var Collection<int, PlanDescriptionItem>
*/
private Collection $descriptionItems;
/**
* The cost lines of the Allocation tab. Each item has a type set up by the admin in
* Settings > Configuration > Plan.
*
* @var Collection<int, PlanAllocationItem>
*/
private Collection $allocationItems;
/**
* Tasks are managed on their own pages (TaskController). Read-only from the plan: deleting a plan
* deletes its tasks through the database (ON DELETE CASCADE).
*
* @var Collection<int, Task>
*/
private Collection $tasks;
private ?string $name = null;
private PlanStatus $status = PlanStatus::Draft;
/**
* Required in the form. The column is nullable only so that deleting the user doesn't delete the plan (SET NULL).
*/
private ?User $owner = null;
private ?\DateTime $startDate = null;
private ?\DateTime $endDate = null;
private ?\DateTime $completedAt = null;
/**
* DECIMAL(12,2), in the general currency (CurrencyProvider). Doctrine returns decimals as strings to
* keep precision.
*/
private ?string $budgetPlanned = null;
private ?Category $category = null;
public function __construct()
{
$this->objectives = new ArrayCollection();
$this->descriptionItems = new ArrayCollection();
$this->allocationItems = new ArrayCollection();
$this->tasks = new ArrayCollection();
}
public function __clone()
{
$this->id = null;
$this->completedAt = null;
$this->tasks = new ArrayCollection();
// A clone gets its own copies of the objectives, description items and allocation items.
$objectives = $this->objectives;
$this->objectives = new ArrayCollection();
foreach ($objectives as $objective) {
$this->addObjective(clone $objective);
}
$descriptionItems = $this->descriptionItems;
$this->descriptionItems = new ArrayCollection();
foreach ($descriptionItems as $descriptionItem) {
$this->addDescriptionItem(clone $descriptionItem);
}
$allocationItems = $this->allocationItems;
$this->allocationItems = new ArrayCollection();
foreach ($allocationItems as $allocationItem) {
$this->addAllocationItem(clone $allocationItem);
}
parent::__clone();
}
public static function loadMetadata(OrmClassMetadata $metadata): void
{
$builder = new ClassMetadataBuilder($metadata);
$builder->setTable(self::TABLE_NAME)
->setCustomRepositoryClass(PlanRepository::class)
->addIndex(['status'], 'plan_status');
// id and name; no description column (replaced by description items).
$builder->addIdColumns('name', false);
// Mapped on the raw metadata: ClassMetadataBuilder::addField() forces every string to VARCHAR(191).
$metadata->mapField([
'fieldName' => 'status',
'type' => Types::STRING,
'length' => 20,
'enumType' => PlanStatus::class,
]);
$builder->createManyToOne('owner', User::class)
->addJoinColumn('owner_id', 'id', true, false, 'SET NULL')
->build();
$builder->addNamedField('startDate', Types::DATETIME_MUTABLE, 'start_date', true);
$builder->addNamedField('endDate', Types::DATETIME_MUTABLE, 'end_date', true);
$builder->addNamedField('completedAt', Types::DATETIME_MUTABLE, 'completed_at', true);
$builder->createField('budgetPlanned', Types::DECIMAL)
->columnName('budget_planned')
->precision(12)
->scale(2)
->nullable()
->build();
// ManyToOne Category, nullable, onDelete SET NULL.
$builder->addCategory();
$builder->createField('version', Types::SMALLINT)
->option('unsigned', true)
->option('default', self::VERSION_MIN)
->build();
$builder->createOneToMany('objectives', PlanObjective::class)
->mappedBy('plan')
->cascadePersist()
->cascadeRemove()
->orphanRemoval()
->setOrderBy(['position' => 'ASC'])
->fetchExtraLazy()
->build();
$builder->createOneToMany('descriptionItems', PlanDescriptionItem::class)
->mappedBy('plan')
->cascadePersist()
->cascadeRemove()
->orphanRemoval()
->setOrderBy(['position' => 'ASC'])
->fetchExtraLazy()
->build();
$builder->createOneToMany('allocationItems', PlanAllocationItem::class)
->mappedBy('plan')
->cascadePersist()
->cascadeRemove()
->orphanRemoval()
->setOrderBy(['position' => 'ASC'])
->fetchExtraLazy()
->build();
$builder->createOneToMany('tasks', Task::class)
->mappedBy('plan')
->setOrderBy(['name' => 'ASC'])
->fetchExtraLazy()
->build();
}
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('version', new NotNull(message: 'mautic.plan.version.range'));
$metadata->addPropertyConstraint('version', new Range(
notInRangeMessage: 'mautic.plan.version.range',
min: self::VERSION_MIN,
max: self::VERSION_MAX,
));
$metadata->addPropertyConstraint('objectives', new Valid());
$metadata->addPropertyConstraint('descriptionItems', new Valid());
$metadata->addPropertyConstraint('allocationItems', new Valid());
$metadata->addPropertyConstraint('name', new NotBlank(message: 'mautic.core.name.required'));
$metadata->addPropertyConstraint('owner', new NotBlank(message: 'mautic.plan.owner.required'));
$metadata->addConstraint(new EndDateAfterStartDate());
}
public function getId(): ?int
{
return $this->id;
}
public function getVersion(): ?int
{
return $this->version;
}
/**
* Accepts null so that an empty form field reaches validation (NotNull) instead of failing here.
*/
public function setVersion(?int $version): static
{
$this->isChanged('version', $version);
$this->version = $version;
return $this;
}
/**
* The objectives sorted by position, as a new collection (Doctrine itself reads the property).
*
* Sorted here, not only by the mapping's orderBy: after a reorder, positions change in memory while the
* loaded collection keeps its old order, and the page shown right after saving uses that collection.
*
* @return Collection<int, PlanObjective>
*/
public function getObjectives(): Collection
{
return self::sortedByPosition($this->objectives);
}
/**
* @return Collection<int, Task>
*/
public function getTasks(): Collection
{
return $this->tasks;
}
public function addObjective(PlanObjective $objective): static
{
if (!$this->objectives->contains($objective)) {
$objective->setPlan($this);
$this->objectives->add($objective);
}
return $this;
}
/**
* Removing an objective from the plan deletes it (orphanRemoval).
*/
public function removeObjective(PlanObjective $objective): static
{
$this->objectives->removeElement($objective);
return $this;
}
/**
* The description items sorted by position, as a new collection; see getObjectives().
*
* @return Collection<int, PlanDescriptionItem>
*/
public function getDescriptionItems(): Collection
{
return self::sortedByPosition($this->descriptionItems);
}
/**
* The allocation items sorted by position, as a new collection; see getObjectives().
*
* @return Collection<int, PlanAllocationItem>
*/
public function getAllocationItems(): Collection
{
return self::sortedByPosition($this->allocationItems);
}
public function addAllocationItem(PlanAllocationItem $allocationItem): static
{
if (!$this->allocationItems->contains($allocationItem)) {
$allocationItem->setPlan($this);
$this->allocationItems->add($allocationItem);
}
return $this;
}
/**
* Removing an allocation item from the plan deletes it (orphanRemoval).
*/
public function removeAllocationItem(PlanAllocationItem $allocationItem): static
{
$this->allocationItems->removeElement($allocationItem);
return $this;
}
/**
* Total planned and real costs of the allocation items, in the general currency. Each total is a
* string with 2 decimals, or null when no item has that cost.
*
* @return array{planned: ?string, real: ?string}
*/
public function getAllocationTotals(): array
{
// Summed in cents, as integers, to avoid floating-point drift.
$cents = ['planned' => null, 'real' => null];
foreach ($this->allocationItems as $item) {
foreach (['planned' => $item->getPlannedCost(), 'real' => $item->getRealCost()] as $kind => $cost) {
if (null === $cost || '' === $cost) {
continue;
}
$cents[$kind] = ($cents[$kind] ?? 0) + (int) round(((float) $cost) * 100);
}
}
return [
'planned' => null === $cents['planned'] ? null : number_format($cents['planned'] / 100, 2, '.', ''),
'real' => null === $cents['real'] ? null : number_format($cents['real'] / 100, 2, '.', ''),
];
}
/**
* @template T of PlanObjective|PlanDescriptionItem|PlanAllocationItem
*
* @param Collection<int, T> $collection
*
* @return Collection<int, T>
*/
private static function sortedByPosition(Collection $collection): Collection
{
$rows = $collection->toArray();
usort($rows, fn ($a, $b): int => $a->getPosition() <=> $b->getPosition());
return new ArrayCollection($rows);
}
public function addDescriptionItem(PlanDescriptionItem $descriptionItem): static
{
if (!$this->descriptionItems->contains($descriptionItem)) {
$descriptionItem->setPlan($this);
$this->descriptionItems->add($descriptionItem);
}
return $this;
}
/**
* Removing a description item from the plan deletes it (orphanRemoval).
*/
public function removeDescriptionItem(PlanDescriptionItem $descriptionItem): static
{
$this->descriptionItems->removeElement($descriptionItem);
return $this;
}
/**
* Renumbers objective, description item and allocation item positions 0..n-1 following their current positions,
* so that the order stays contiguous after rows are added, removed or moved.
*/
public function normalizePositions(): void
{
foreach ([$this->objectives, $this->descriptionItems, $this->allocationItems] as $collection) {
$rows = $collection->toArray();
usort($rows, fn ($a, $b): int => $a->getPosition() <=> $b->getPosition());
foreach ($rows as $index => $row) {
$row->setPosition($index);
}
}
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): static
{
$this->isChanged('name', $name);
$this->name = $name;
return $this;
}
public function getStatus(): PlanStatus
{
return $this->status;
}
/**
* Sets completedAt when the plan moves to "completed" from another status,
* and clears it when the plan leaves "completed".
*/
public function setStatus(PlanStatus $status): static
{
if ($status === $this->status) {
return $this;
}
// isChanged() can't log enums (they aren't stringable), so log the backing values.
$this->addChange('status', [$this->status->value, $status->value]);
if (PlanStatus::Completed === $status) {
$this->setCompletedAt(new \DateTime());
} elseif (PlanStatus::Completed === $this->status) {
$this->setCompletedAt(null);
}
$this->status = $status;
return $this;
}
public function getOwner(): ?User
{
return $this->owner;
}
public function setOwner(?User $owner): static
{
$this->isChanged('owner', $owner);
$this->owner = $owner;
return $this;
}
public function getStartDate(): ?\DateTime
{
return $this->startDate;
}
public function setStartDate(?\DateTime $startDate): static
{
$this->isChanged('startDate', $startDate);
$this->startDate = $startDate;
return $this;
}
public function getEndDate(): ?\DateTime
{
return $this->endDate;
}
public function setEndDate(?\DateTime $endDate): static
{
$this->isChanged('endDate', $endDate);
$this->endDate = $endDate;
return $this;
}
public function getCompletedAt(): ?\DateTime
{
return $this->completedAt;
}
public function setCompletedAt(?\DateTime $completedAt): static
{
$this->isChanged('completedAt', $completedAt);
$this->completedAt = $completedAt;
return $this;
}
public function getBudgetPlanned(): ?string
{
return $this->budgetPlanned;
}
public function setBudgetPlanned(?string $budgetPlanned): static
{
$this->isChanged('budgetPlanned', $budgetPlanned);
$this->budgetPlanned = $budgetPlanned;
return $this;
}
public function getCategory(): ?Category
{
return $this->category;
}
public function setCategory(?Category $category): static
{
$this->isChanged('category', $category);
$this->category = $category;
return $this;
}
}
+192
View File
@@ -0,0 +1,192 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* One item of a plan's Allocation tab: a typed cost line with a planned and a real cost, both in the
* general currency (CurrencyProvider). Plan::$allocationItems owns the lifecycle: items are saved and
* deleted with their plan, and are ordered by position.
*
* The type is the key of an allocation item type set up in Settings > Configuration > Plan Settings
* (parameter plan_allocation_item_types); see ItemTypeProvider.
*/
class PlanAllocationItem
{
public const TABLE_NAME = 'plan_allocation_items';
public const TYPE_MAX_LENGTH = 64;
private ?int $id = null;
private ?Plan $plan = null;
private ?string $type = null;
private ?string $name = null;
private ?string $description = null;
/**
* DECIMAL(12,2), as a string (Doctrine keeps decimals as strings for precision).
*/
private ?string $plannedCost = null;
private ?string $realCost = null;
/**
* Display order within the plan, from 0. Set by drag and drop in the form.
*/
private int $position = 0;
public function __clone()
{
$this->id = null;
$this->plan = null;
}
public static function loadMetadata(OrmClassMetadata $metadata): void
{
$builder = new ClassMetadataBuilder($metadata);
$builder->setTable(self::TABLE_NAME)
->setCustomRepositoryClass(PlanAllocationItemRepository::class);
$builder->addId();
$builder->createManyToOne('plan', Plan::class)
->inversedBy('allocationItems')
->addJoinColumn('plan_id', 'id', false, false, 'CASCADE')
->build();
$builder->createField('type', Types::STRING)
->length(self::TYPE_MAX_LENGTH)
->build();
$builder->createField('name', Types::STRING)
->length(255)
->nullable()
->build();
$builder->createField('description', Types::TEXT)
->nullable()
->build();
foreach (['planned', 'real'] as $kind) {
$builder->createField($kind.'Cost', Types::DECIMAL)
->columnName($kind.'_cost')
->precision(12)
->scale(2)
->nullable()
->build();
}
$builder->createField('position', Types::INTEGER)
->option('default', 0)
->build();
}
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('type', new NotBlank(message: 'mautic.plan.allocation_item.type.required'));
$metadata->addPropertyConstraint('type', new Length(max: self::TYPE_MAX_LENGTH));
$metadata->addPropertyConstraint('name', new Length(max: 255));
}
public function getId(): ?int
{
return $this->id;
}
public function getPlan(): ?Plan
{
return $this->plan;
}
public function setPlan(?Plan $plan): static
{
$this->plan = $plan;
return $this;
}
public function getType(): ?string
{
return $this->type;
}
public function setType(?string $type): static
{
$this->type = $type;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): static
{
$this->name = $name;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): static
{
$this->description = $description;
return $this;
}
public function getPlannedCost(): ?string
{
return $this->plannedCost;
}
public function setPlannedCost(?string $plannedCost): static
{
$this->plannedCost = $plannedCost;
return $this;
}
public function getRealCost(): ?string
{
return $this->realCost;
}
public function setRealCost(?string $realCost): static
{
$this->realCost = $realCost;
return $this;
}
public function getPosition(): int
{
return $this->position;
}
public function setPosition(?int $position): static
{
$this->position = $position ?? 0;
return $this;
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Mautic\CoreBundle\Entity\CommonRepository;
/**
* @extends CommonRepository<PlanAllocationItem>
*/
class PlanAllocationItemRepository extends CommonRepository
{
use CountsItemsByTypeTrait;
public function getTableAlias(): string
{
return 'pai';
}
}
+131
View File
@@ -0,0 +1,131 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* One item of a plan's Description tab. Plan::$descriptionItems owns the lifecycle: items are saved and
* deleted with their plan, and are ordered by position.
*
* The type is the key of a type set up in Settings > Configuration > Plan (parameter
* plan_description_item_types); see ItemTypeProvider (kind "description") for its name and description.
*/
class PlanDescriptionItem
{
public const TABLE_NAME = 'plan_description_items';
public const TYPE_MAX_LENGTH = 64;
private ?int $id = null;
private ?Plan $plan = null;
private ?string $type = null;
private ?string $description = null;
/**
* Display order within the plan, from 0. Set by drag and drop in the form.
*/
private int $position = 0;
public function __clone()
{
$this->id = null;
$this->plan = null;
}
public static function loadMetadata(OrmClassMetadata $metadata): void
{
$builder = new ClassMetadataBuilder($metadata);
$builder->setTable(self::TABLE_NAME)
->setCustomRepositoryClass(PlanDescriptionItemRepository::class);
$builder->addId();
$builder->createManyToOne('plan', Plan::class)
->inversedBy('descriptionItems')
->addJoinColumn('plan_id', 'id', false, false, 'CASCADE')
->build();
$builder->createField('type', Types::STRING)
->length(self::TYPE_MAX_LENGTH)
->build();
$builder->createField('description', Types::TEXT)
->nullable()
->build();
$builder->createField('position', Types::INTEGER)
->option('default', 0)
->build();
}
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('type', new NotBlank(message: 'mautic.plan.description_item.type.required'));
$metadata->addPropertyConstraint('type', new Length(max: self::TYPE_MAX_LENGTH));
}
public function getId(): ?int
{
return $this->id;
}
public function getPlan(): ?Plan
{
return $this->plan;
}
public function setPlan(?Plan $plan): static
{
$this->plan = $plan;
return $this;
}
public function getType(): ?string
{
return $this->type;
}
public function setType(?string $type): static
{
$this->type = $type;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): static
{
$this->description = $description;
return $this;
}
public function getPosition(): int
{
return $this->position;
}
public function setPosition(?int $position): static
{
$this->position = $position ?? 0;
return $this;
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Mautic\CoreBundle\Entity\CommonRepository;
/**
* @extends CommonRepository<PlanDescriptionItem>
*/
class PlanDescriptionItemRepository extends CommonRepository
{
use CountsItemsByTypeTrait;
public function getTableAlias(): string
{
return 'pdi';
}
}
+153
View File
@@ -0,0 +1,153 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* An objective of a plan. Plan::$objectives owns the lifecycle: objectives are saved and deleted with
* their plan, and are ordered by position.
*/
class PlanObjective
{
public const TABLE_NAME = 'plan_objectives';
private ?int $id = null;
private ?Plan $plan = null;
private ?string $title = null;
private ?string $description = null;
/**
* Display order within the plan, from 0. Set by drag and drop in the form.
*/
private int $position = 0;
/**
* Toggled by hand for now.
*/
private bool $isAchieved = false;
public function __clone()
{
$this->id = null;
$this->plan = null;
}
public static function loadMetadata(OrmClassMetadata $metadata): void
{
$builder = new ClassMetadataBuilder($metadata);
$builder->setTable(self::TABLE_NAME)
->setCustomRepositoryClass(PlanObjectiveRepository::class);
$builder->addId();
$builder->createManyToOne('plan', Plan::class)
->inversedBy('objectives')
->addJoinColumn('plan_id', 'id', false, false, 'CASCADE')
->build();
$builder->createField('title', Types::STRING)
->length(255)
->build();
$builder->createField('description', Types::TEXT)
->nullable()
->build();
$builder->createField('position', Types::INTEGER)
->option('default', 0)
->build();
$builder->createField('isAchieved', Types::BOOLEAN)
->columnName('is_achieved')
->option('default', false)
->build();
}
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('title', new NotBlank(message: 'mautic.plan.objective.title.required'));
$metadata->addPropertyConstraint('title', new Length(max: 255));
}
public function getId(): ?int
{
return $this->id;
}
public function getPlan(): ?Plan
{
return $this->plan;
}
public function setPlan(?Plan $plan): static
{
$this->plan = $plan;
return $this;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(?string $title): static
{
$this->title = $title;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): static
{
$this->description = $description;
return $this;
}
public function getPosition(): int
{
return $this->position;
}
public function setPosition(?int $position): static
{
$this->position = $position ?? 0;
return $this;
}
public function isAchieved(): bool
{
return $this->isAchieved;
}
public function getIsAchieved(): bool
{
return $this->isAchieved;
}
public function setIsAchieved(bool $isAchieved): static
{
$this->isAchieved = $isAchieved;
return $this;
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Mautic\CoreBundle\Entity\CommonRepository;
/**
* @extends CommonRepository<PlanObjective>
*/
class PlanObjectiveRepository extends CommonRepository
{
public function getTableAlias(): string
{
return 'po';
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Mautic\CoreBundle\Entity\CommonRepository;
/**
* @extends CommonRepository<Plan>
*/
class PlanRepository extends CommonRepository
{
public function getTableAlias(): string
{
return 'p';
}
/**
* Loads the owner and category with the plans, so that the list doesn't query them one by one.
*
* @param array<string, mixed> $args
*/
public function getEntities(array $args = [])
{
$alias = $this->getTableAlias();
$args['qb'] = $this->createQueryBuilder($alias)
->select($alias, 'o', 'c')
->leftJoin($alias.'.owner', 'o')
->leftJoin($alias.'.category', 'c');
return parent::getEntities($args);
}
/**
* The list's search box matches the name.
*
* @return array<int, mixed>
*/
protected function addCatchAllWhereClause($q, $filter): array
{
return $this->addStandardCatchAllWhereClause($q, $filter, [
$this->getTableAlias().'.name',
]);
}
/**
* @return array<array{0: string, 1: string}>
*/
protected function getDefaultOrder(): array
{
return [
[$this->getTableAlias().'.name', 'ASC'],
];
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
enum PlanStatus: string
{
case Draft = 'draft';
case Planned = 'planned';
case Active = 'active';
case Paused = 'paused';
case Completed = 'completed';
case Archived = 'archived';
public function getLabelKey(): string
{
return 'mautic.plan.status.'.$this->value;
}
}
+251
View File
@@ -0,0 +1,251 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
use Mautic\CoreBundle\Entity\FormEntity;
use MauticPlugin\PlanBundle\Validator\Constraints\EndDateAfterStartDate;
use MauticPlugin\PlanBundle\Validator\Constraints\ValidTaskParent;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* A task of a plan. Every task belongs to exactly one plan, and may have a parent task in the same plan.
*
* Database rules: deleting the plan deletes its tasks (ON DELETE CASCADE); deleting a task makes its
* sub-tasks top-level (parent ON DELETE SET NULL).
*/
class Task extends FormEntity implements DateRangeInterface
{
public const TABLE_NAME = 'plan_tasks';
private ?int $id = null;
private ?Plan $plan = null;
private ?string $name = null;
private ?string $description = null;
private ?Task $parent = null;
private ?\DateTime $startDate = null;
private ?\DateTime $endDate = null;
private TaskStatus $status = TaskStatus::New;
/**
* @var Collection<int, Task>
*/
private Collection $children;
public function __construct()
{
$this->children = new ArrayCollection();
}
public function __clone()
{
$this->id = null;
$this->children = new ArrayCollection();
parent::__clone();
}
public static function loadMetadata(OrmClassMetadata $metadata): void
{
$builder = new ClassMetadataBuilder($metadata);
$builder->setTable(self::TABLE_NAME)
->setCustomRepositoryClass(TaskRepository::class);
$builder->addId();
$builder->createManyToOne('plan', Plan::class)
->inversedBy('tasks')
->addJoinColumn('plan_id', 'id', false, false, 'CASCADE')
->build();
$builder->createField('name', Types::STRING)
->length(255)
->build();
$builder->createField('description', Types::TEXT)
->nullable()
->build();
$builder->createManyToOne('parent', self::class)
->inversedBy('children')
->addJoinColumn('parent_id', 'id', true, false, 'SET NULL')
->build();
$builder->createOneToMany('children', self::class)
->mappedBy('parent')
->setOrderBy(['name' => 'ASC'])
->fetchExtraLazy()
->build();
$builder->addNamedField('startDate', Types::DATETIME_MUTABLE, 'start_date', true);
$builder->addNamedField('endDate', Types::DATETIME_MUTABLE, 'end_date', true);
// Mapped on the raw metadata: ClassMetadataBuilder::addField() forces every string to VARCHAR(191).
$metadata->mapField([
'fieldName' => 'status',
'type' => Types::STRING,
'length' => 20,
'enumType' => TaskStatus::class,
'options' => ['default' => TaskStatus::New->value],
]);
$builder->addIndex(['status'], 'plan_task_status');
}
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('name', new NotBlank(message: 'mautic.core.name.required'));
$metadata->addPropertyConstraint('name', new Length(max: 255));
$metadata->addPropertyConstraint('plan', new NotBlank(message: 'mautic.plan.task.plan.required'));
$metadata->addConstraint(new ValidTaskParent());
$metadata->addConstraint(new EndDateAfterStartDate());
}
public function getId(): ?int
{
return $this->id;
}
public function getPlan(): ?Plan
{
return $this->plan;
}
public function setPlan(?Plan $plan): static
{
$this->isChanged('plan', $plan);
$this->plan = $plan;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): static
{
$this->isChanged('name', $name);
$this->name = $name;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): static
{
$this->isChanged('description', $description);
$this->description = $description;
return $this;
}
public function getParent(): ?Task
{
return $this->parent;
}
public function setParent(?Task $parent): static
{
$this->isChanged('parent', $parent);
$this->parent = $parent;
return $this;
}
public function getStartDate(): ?\DateTime
{
return $this->startDate;
}
public function setStartDate(?\DateTime $startDate): static
{
$this->isChanged('startDate', $startDate);
$this->startDate = $startDate;
return $this;
}
public function getEndDate(): ?\DateTime
{
return $this->endDate;
}
public function setEndDate(?\DateTime $endDate): static
{
$this->isChanged('endDate', $endDate);
$this->endDate = $endDate;
return $this;
}
public function getStatus(): TaskStatus
{
return $this->status;
}
public function setStatus(TaskStatus $status): static
{
if ($status !== $this->status) {
// isChanged() can't log enums (they aren't stringable), so log the backing values.
$this->addChange('status', [$this->status->value, $status->value]);
$this->status = $status;
}
return $this;
}
/**
* @return Collection<int, Task>
*/
public function getChildren(): Collection
{
return $this->children;
}
/**
* True when $task is this task or one of its ancestors.
*/
public function hasAncestorOrSelf(Task $task): bool
{
$seen = [];
$current = $this;
while (null !== $current) {
if ($current === $task || (null !== $task->getId() && $current->getId() === $task->getId())) {
return true;
}
// Guard against a cycle that is already stored.
$key = null !== $current->getId() ? 'id'.$current->getId() : spl_object_id($current);
if (isset($seen[$key])) {
return false;
}
$seen[$key] = true;
$current = $current->getParent();
}
return false;
}
}
+74
View File
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Mautic\CoreBundle\Entity\CommonRepository;
/**
* @extends CommonRepository<Task>
*/
class TaskRepository extends CommonRepository
{
public function getTableAlias(): string
{
return 't';
}
/**
* Loads the plan and the parent with the tasks, so that the list doesn't query them one by one.
*
* @param array<string, mixed> $args
*/
public function getEntities(array $args = [])
{
$alias = $this->getTableAlias();
$args['qb'] = $this->createQueryBuilder($alias)
->select($alias, 'pl', 'pa')
->leftJoin($alias.'.plan', 'pl')
->leftJoin($alias.'.parent', 'pa');
return parent::getEntities($args);
}
/**
* All tasks of a plan, ordered by name.
*
* @return Task[]
*/
public function findByPlan(Plan $plan): array
{
return $this->createQueryBuilder('t')
->where('t.plan = :plan')
->setParameter('plan', $plan)
->orderBy('t.name', 'ASC')
->addOrderBy('t.id', 'ASC')
->getQuery()
->getResult();
}
/**
* The list's search box matches the name and the description.
*
* @return array<int, mixed>
*/
protected function addCatchAllWhereClause($q, $filter): array
{
return $this->addStandardCatchAllWhereClause($q, $filter, [
$this->getTableAlias().'.name',
$this->getTableAlias().'.description',
]);
}
/**
* @return array<array{0: string, 1: string}>
*/
protected function getDefaultOrder(): array
{
return [
[$this->getTableAlias().'.name', 'ASC'],
];
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
/**
* Task status. The order of the cases is the order of the dropdown on the task form.
*/
enum TaskStatus: string
{
case New = 'new';
case Todo = 'todo';
case InProgress = 'in_progress';
case Done = 'done';
public function getLabelKey(): string
{
return 'mautic.plan.task.status.'.$this->value;
}
/**
* Bootstrap label class for the status badge in lists.
*/
public function getLabelClass(): string
{
return match ($this) {
self::New => 'label-default',
self::Todo => 'label-info',
self::InProgress => 'label-warning',
self::Done => 'label-success',
};
}
}