Files
mautic-marketing-program-bu…/Entity/Plan.php
T
2026-11-07 19:31:49 +01:00

515 lines
15 KiB
PHP

<?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;
}
}