Files
alexandre_gain_mt3s 4fb36eebfc feat(call-script): add the Call Script component (0.19.0)
A new Mautic component, listed under Components > Call Scripts (/s/call-scripts),
built like the other domains on AbstractStandardFormController/FormModel.

- CallScript (mt3s_call_scripts): name, description, category, owner, status,
the publish window shown as start/end date and time, the HTML script with
dynamic tokens kept as typed (html cleaning mask), the calling window
(weekdays, hours, sentinel in the contact's or a fixed timezone) and the retry
policy (max attempts, delay, backoff: none/linear/exponential)
- CallScriptOutcome (mt3s_call_script_outcomes, ON DELETE CASCADE): label,
data type (checkbox/radio/free text/dropdown), options JSON ({value,label})
and position; nested collections reuse the program-collection JS
- validators: ValidCallingWindow, ValidCallScriptOutcomeOptions, and an atPath
option on EndDateAfterStartDate so its violation lands on publishDown
- config: routes, the Components menu item (parent mautic.core.components),
call_script category type, model alias, call_scripts permissions, version 0.19.0
- migration Version_0_19_0 creates both tables and their FKs immediately
(users/categories SET NULL, outcomes CASCADE), idempotent
- translations en_US/fr_FR, unit tests, readme/AGENTS documentation
2026-11-21 20:58:25 +01:00

545 lines
16 KiB
PHP

<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\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\MT3SMarketingProgramBundle\Validator\Constraints\EndDateAfterStartDate;
use MauticPlugin\MT3SMarketingProgramBundle\Validator\Constraints\ValidCallingWindow;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Constraints\Valid;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* A call script: an HTML script with dynamic tokens like {contact.first_name}, the outcomes an agent
* can record, its calling window and its retry policy.
*
* It is a Mautic component (like an email or a landing page): its pages are linked from the
* Components menu. The script itself is stored as typed; resolving the tokens for a contact is the
* job of the call execution, which is not part of this entity.
*/
class CallScript extends FormEntity implements DateRangeInterface
{
public const TABLE_NAME = 'mt3s_call_scripts';
public const NAME_MAX_LENGTH = 191;
public const TIMEZONE_MAX_LENGTH = 64;
public const RETRY_ATTEMPTS_MIN = 1;
public const RETRY_ATTEMPTS_MAX = 20;
/**
* One week, in minutes.
*/
public const RETRY_DELAY_MAX = 10080;
public const RETRY_MAX_ATTEMPTS_DEFAULT = 3;
public const RETRY_DELAY_DEFAULT = 30;
/**
* The weekdays of the calling window, in display order.
*/
public const WEEKDAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
private ?int $id = null;
/**
* @var Collection<int, CallScriptOutcome>
*/
private Collection $outcomes;
private ?string $name = null;
private ?string $description = null;
/**
* The script's validity window: the "start" date and time.
*/
private ?\DateTime $publishUp = null;
/**
* The script's validity window: the "end" date and time.
*/
private ?\DateTime $publishDown = null;
/**
* Required in the form. The column is nullable only so that deleting the user doesn't delete the
* script (ON DELETE SET NULL).
*/
private ?User $owner = null;
private ?Category $category = null;
/**
* HTML with dynamic tokens like {contact.first_name}, kept as typed.
*/
private ?string $script = null;
/**
* The weekdays the calls may happen on, as ISO short names (mon..sun). Empty means every day.
*
* @var list<string>
*/
private array $callingDays = [];
/**
* The calling window's hours, as times of day in the window's timezone.
*/
private ?\DateTime $callingFrom = null;
private ?\DateTime $callingTo = null;
private CallScriptTimezoneMode $callingTimezoneMode = CallScriptTimezoneMode::Contact;
/**
* The fixed timezone of the calling window, when its mode is "fixed".
*/
private ?string $callingTimezone = null;
private int $retryMaxAttempts = self::RETRY_MAX_ATTEMPTS_DEFAULT;
private int $retryDelayMinutes = self::RETRY_DELAY_DEFAULT;
private CallScriptRetryBackoff $retryBackoff = CallScriptRetryBackoff::None;
public function __construct()
{
$this->outcomes = new ArrayCollection();
}
public static function loadMetadata(OrmClassMetadata $metadata): void
{
$builder = new ClassMetadataBuilder($metadata);
$builder->setTable(self::TABLE_NAME)
->setCustomRepositoryClass(CallScriptRepository::class);
$builder->addId();
$builder->createField('name', Types::STRING)
->length(self::NAME_MAX_LENGTH)
->build();
$builder->createField('description', Types::TEXT)
->nullable()
->build();
// The script's validity window: the "start" and "end" date and time in the form.
$builder->addPublishDates();
$builder->createManyToOne('owner', User::class)
->addJoinColumn('owner_id', 'id', true, false, 'SET NULL')
->build();
$builder->addCategory();
// Types::TEXT is LONGTEXT on MySQL: the script keeps all its HTML.
$builder->createField('script', Types::TEXT)
->nullable()
->build();
// Mapped on the raw metadata, like the Smart Links arrays: ClassMetadataBuilder forces
// VARCHAR(191) on strings and doesn't accept JSON or enum types.
$metadata->mapField([
'fieldName' => 'callingDays',
'columnName' => 'calling_days',
'type' => Types::JSON,
]);
$metadata->mapField([
'fieldName' => 'callingFrom',
'columnName' => 'calling_from',
'type' => Types::TIME_MUTABLE,
'nullable' => true,
]);
$metadata->mapField([
'fieldName' => 'callingTo',
'columnName' => 'calling_to',
'type' => Types::TIME_MUTABLE,
'nullable' => true,
]);
$metadata->mapField([
'fieldName' => 'callingTimezoneMode',
'columnName' => 'calling_timezone_mode',
'type' => Types::STRING,
'length' => 10,
'enumType' => CallScriptTimezoneMode::class,
'options' => ['default' => CallScriptTimezoneMode::Contact->value],
]);
$builder->createField('callingTimezone', Types::STRING)
->columnName('calling_timezone')
->length(self::TIMEZONE_MAX_LENGTH)
->nullable()
->build();
$builder->createField('retryMaxAttempts', Types::INTEGER)
->columnName('retry_max_attempts')
->option('default', self::RETRY_MAX_ATTEMPTS_DEFAULT)
->option('unsigned', true)
->build();
$builder->createField('retryDelayMinutes', Types::INTEGER)
->columnName('retry_delay_minutes')
->option('default', self::RETRY_DELAY_DEFAULT)
->option('unsigned', true)
->build();
$metadata->mapField([
'fieldName' => 'retryBackoff',
'columnName' => 'retry_backoff',
'type' => Types::STRING,
'length' => 20,
'enumType' => CallScriptRetryBackoff::class,
'options' => ['default' => CallScriptRetryBackoff::None->value],
]);
$builder->createOneToMany('outcomes', CallScriptOutcome::class)
->mappedBy('callScript')
->setOrderBy(['position' => 'ASC'])
->cascadePersist()
->cascadeRemove()
->orphanRemoval()
->build();
}
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('name', new NotBlank(message: 'mautic.core.name.required'));
$metadata->addPropertyConstraint('name', new Length(max: self::NAME_MAX_LENGTH));
$metadata->addPropertyConstraint('owner', new NotBlank(message: 'mt3s.marketing_program.owner.required'));
$metadata->addPropertyConstraint('outcomes', new Valid());
$metadata->addPropertyConstraint('retryMaxAttempts', new Range(
notInRangeMessage: 'mt3s.call_script.retry_attempts.range',
min: self::RETRY_ATTEMPTS_MIN,
max: self::RETRY_ATTEMPTS_MAX,
));
$metadata->addPropertyConstraint('retryDelayMinutes', new Range(
notInRangeMessage: 'mt3s.call_script.retry_delay.range',
min: 0,
max: self::RETRY_DELAY_MAX,
));
// The validity window: the end must be on or after the start (the form's "end" field is publishDown).
$metadata->addConstraint(new EndDateAfterStartDate(atPath: 'publishDown'));
$metadata->addConstraint(new ValidCallingWindow());
}
public function getId(): ?int
{
return $this->id;
}
/**
* The outcomes sorted by position, as a new collection (see Program::getObjectives()).
*
* @return Collection<int, CallScriptOutcome>
*/
public function getOutcomes(): Collection
{
$rows = $this->outcomes->toArray();
usort($rows, fn (CallScriptOutcome $a, CallScriptOutcome $b): int => $a->getPosition() <=> $b->getPosition());
return new ArrayCollection($rows);
}
public function addOutcome(CallScriptOutcome $outcome): static
{
if (!$this->outcomes->contains($outcome)) {
$outcome->setCallScript($this);
$this->outcomes->add($outcome);
}
return $this;
}
public function removeOutcome(CallScriptOutcome $outcome): static
{
$this->outcomes->removeElement($outcome);
return $this;
}
/**
* Keeps the outcome positions contiguous (0..n-1) in their current order, before saving.
*/
public function normalizePositions(): void
{
$rows = $this->outcomes->toArray();
usort($rows, fn (CallScriptOutcome $a, CallScriptOutcome $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 getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): static
{
$this->isChanged('description', $description);
$this->description = $description;
return $this;
}
public function getPublishUp(): ?\DateTime
{
return $this->publishUp;
}
public function setPublishUp(?\DateTime $publishUp): static
{
$this->isChanged('publishUp', $publishUp);
$this->publishUp = $publishUp;
return $this;
}
public function getPublishDown(): ?\DateTime
{
return $this->publishDown;
}
public function setPublishDown(?\DateTime $publishDown): static
{
$this->isChanged('publishDown', $publishDown);
$this->publishDown = $publishDown;
return $this;
}
/**
* DateRangeInterface: the script's validity window, for EndDateAfterStartDate.
*/
public function getStartDate(): ?\DateTime
{
return $this->publishUp;
}
public function getEndDate(): ?\DateTime
{
return $this->publishDown;
}
public function getOwner(): ?User
{
return $this->owner;
}
public function setOwner(?User $owner): static
{
$this->isChanged('owner', $owner);
$this->owner = $owner;
return $this;
}
public function getCategory(): ?Category
{
return $this->category;
}
public function setCategory(?Category $category): static
{
$this->isChanged('category', $category);
$this->category = $category;
return $this;
}
public function getScript(): ?string
{
return $this->script;
}
public function setScript(?string $script): static
{
$this->isChanged('script', $script);
$this->script = $script;
return $this;
}
/**
* @return list<string>
*/
public function getCallingDays(): array
{
return $this->callingDays;
}
/**
* @param list<string>|null $callingDays
*/
public function setCallingDays(?array $callingDays): static
{
$days = [];
foreach ($callingDays ?? [] as $day) {
$day = (string) $day;
if (in_array($day, self::WEEKDAYS, true) && !in_array($day, $days, true)) {
$days[] = $day;
}
}
$this->isChanged('callingDays', $days);
$this->callingDays = $days;
return $this;
}
public function getCallingFrom(): ?\DateTime
{
return $this->callingFrom;
}
public function setCallingFrom(?\DateTime $callingFrom): static
{
$this->isChanged('callingFrom', $callingFrom);
$this->callingFrom = $callingFrom;
return $this;
}
public function getCallingTo(): ?\DateTime
{
return $this->callingTo;
}
public function setCallingTo(?\DateTime $callingTo): static
{
$this->isChanged('callingTo', $callingTo);
$this->callingTo = $callingTo;
return $this;
}
public function getCallingTimezoneMode(): CallScriptTimezoneMode
{
return $this->callingTimezoneMode;
}
/**
* Null (a mode field missing from the submitted form) keeps the current mode, like the task kind.
*/
public function setCallingTimezoneMode(?CallScriptTimezoneMode $callingTimezoneMode): static
{
if (null === $callingTimezoneMode || $callingTimezoneMode === $this->callingTimezoneMode) {
return $this;
}
// isChanged() can't log enums (they aren't stringable), so log the backing values.
$this->addChange('callingTimezoneMode', [$this->callingTimezoneMode->value, $callingTimezoneMode->value]);
$this->callingTimezoneMode = $callingTimezoneMode;
return $this;
}
public function getCallingTimezone(): ?string
{
return $this->callingTimezone;
}
public function setCallingTimezone(?string $callingTimezone): static
{
if (null !== $callingTimezone && '' === trim($callingTimezone)) {
$callingTimezone = null;
}
$this->isChanged('callingTimezone', $callingTimezone);
$this->callingTimezone = $callingTimezone;
return $this;
}
public function getRetryMaxAttempts(): int
{
return $this->retryMaxAttempts;
}
/**
* Null (an attempts field missing from the submitted form) keeps the current value.
*/
public function setRetryMaxAttempts(?int $retryMaxAttempts): static
{
if (null === $retryMaxAttempts || $retryMaxAttempts === $this->retryMaxAttempts) {
return $this;
}
$this->isChanged('retryMaxAttempts', $retryMaxAttempts);
$this->retryMaxAttempts = $retryMaxAttempts;
return $this;
}
public function getRetryDelayMinutes(): int
{
return $this->retryDelayMinutes;
}
/**
* Null (a delay field missing from the submitted form) keeps the current value.
*/
public function setRetryDelayMinutes(?int $retryDelayMinutes): static
{
if (null === $retryDelayMinutes || $retryDelayMinutes === $this->retryDelayMinutes) {
return $this;
}
$this->isChanged('retryDelayMinutes', $retryDelayMinutes);
$this->retryDelayMinutes = $retryDelayMinutes;
return $this;
}
public function getRetryBackoff(): CallScriptRetryBackoff
{
return $this->retryBackoff;
}
/**
* Null (a backoff field missing from the submitted form) keeps the current policy.
*/
public function setRetryBackoff(?CallScriptRetryBackoff $retryBackoff): static
{
if (null === $retryBackoff || $retryBackoff === $this->retryBackoff) {
return $this;
}
// isChanged() can't log enums (they aren't stringable), so log the backing values.
$this->addChange('retryBackoff', [$this->retryBackoff->value, $retryBackoff->value]);
$this->retryBackoff = $retryBackoff;
return $this;
}
}