diff --git a/Assets/js/mt3s-mp-program.js b/Assets/js/mt3s-mp-program.js index 561e8f9..21dc198 100644 --- a/Assets/js/mt3s-mp-program.js +++ b/Assets/js/mt3s-mp-program.js @@ -400,6 +400,14 @@ Mautic.mt3sMpProgramInitCollection = function ($editor) { var $row = mQuery($editor.attr('data-prototype').replace(prototypeName, nextIndex++)); $list.append($row); refresh(); + // A new row may contain nested collections (a call script outcome's options): give them + // their own add/remove/drag handler. + $row.find('.program-collection').each(function () { + Mautic.mt3sMpProgramInitCollection(mQuery(this)); + }); + if (typeof Mautic.mt3sMpCallScriptInitOutcomeTypes === 'function') { + Mautic.mt3sMpCallScriptInitOutcomeTypes($row); + } $row.find('select, input[type="text"], textarea').first().trigger('focus'); }); @@ -430,6 +438,40 @@ Mautic.mt3sMpProgramInitCollection = function ($editor) { refresh(); }; +/** + * Call Script form: show the options of an outcome only for the choice types (checkbox, radio, + * dropdown); a free text outcome has none. + */ +Mautic.mt3sMpCallScriptInitOutcomeTypes = function ($container) { + mQuery($container).find('select.program-outcome-type').each(function () { + var $select = mQuery(this); + + if ($select.data('mt3sMpCallScriptTypeInitialized')) { + return; + } + $select.data('mt3sMpCallScriptTypeInitialized', true); + + var toggle = function () { + var $row = $select.closest('.program-collection-row'); + $row.find('.program-outcome-options').first().toggleClass('hide', 'free_text' === $select.val()); + }; + + $select.on('change', toggle); + toggle(); + }); +}; + +/** + * The Call Script form (Components > Call Scripts): its outcomes and their nested options use the + * program collections, and the options block follows the chosen data type. + */ +Mautic.mt3sMpCallScriptOnLoad = function (container) { + mQuery(container).find('.program-collection').each(function () { + Mautic.mt3sMpProgramInitCollection(mQuery(this)); + }); + Mautic.mt3sMpCallScriptInitOutcomeTypes(mQuery(container)); +}; + /** * Settings > Configuration > Plan: add and remove item types (description and allocation). */ diff --git a/Config/config.php b/Config/config.php index 15bd785..e9023e2 100644 --- a/Config/config.php +++ b/Config/config.php @@ -5,7 +5,7 @@ declare(strict_types=1); return [ 'name' => 'MT3S Marketing Program', 'description' => 'MT3S Marketing: programs, tasks, audiences, and smart links with their UTM taxonomies.', - 'version' => '0.18.2', + 'version' => '0.19.0', 'author' => 'Experiential', 'routes' => [ @@ -46,6 +46,16 @@ return [ 'path' => '/marketing-program-audiences/{objectAction}/{objectId}', 'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\AudienceController::executeAction', ], + // Call Scripts component (Components > Call Scripts): the list and its object actions. + 'mt3s_call_script_index' => [ + 'path' => '/call-scripts/{page}', + 'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\CallScriptController::indexAction', + ], + // objectAction: new, edit, delete, batchDelete. + 'mt3s_call_script_action' => [ + 'path' => '/call-scripts/{objectAction}/{objectId}', + 'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\CallScriptController::executeAction', + ], // Smart Links domain: the list and its object actions. 'mt3s_smart_links_index' => [ 'path' => '/smart-links/{page}', @@ -139,6 +149,16 @@ return [ ], ], ], + + // The Call Script component: a flat item attached to core's Components menu. The + // "parent" key hands it to Mautic's orphan mechanism, which places it in that group; + // the key itself is the translation key of the label. + 'mt3s.call_script.menu.index' => [ + 'route' => 'mt3s_call_script_index', + 'access' => ['mt3smarketingprogram:call_scripts:viewown', 'mt3smarketingprogram:call_scripts:viewother'], + 'parent' => 'mautic.core.components', + 'priority' => 80, + ], ], ], @@ -173,12 +193,17 @@ return [ ], ], - // Registers "program" as a category type (Settings > Categories), used by Program::$category. + // Registers "program" as a category type (Settings > Categories), used by Program::$category, + // and "call_script" for the Call Script component. 'categories' => [ 'program' => [ 'class' => MauticPlugin\MT3SMarketingProgramBundle\Entity\Program::class, 'label' => 'mt3s.marketing_program.category.type', ], + 'call_script' => [ + 'class' => MauticPlugin\MT3SMarketingProgramBundle\Entity\CallScript::class, + 'label' => 'mt3s.call_script.category.type', + ], ], 'parameters' => [ diff --git a/Config/services.php b/Config/services.php index 16c86c5..e1f647e 100644 --- a/Config/services.php +++ b/Config/services.php @@ -29,6 +29,7 @@ return function (ContainerConfigurator $configurator): void { // exactly one alias per model, under the bundle's canonical prefix. $services->alias('mautic.mt3smarketingprogram.model.program', MauticPlugin\MT3SMarketingProgramBundle\Model\ProgramModel::class); $services->alias('mautic.mt3smarketingprogram.model.task', MauticPlugin\MT3SMarketingProgramBundle\Model\TaskModel::class); + $services->alias('mautic.mt3smarketingprogram.model.call_script', MauticPlugin\MT3SMarketingProgramBundle\Model\CallScriptModel::class); $services->alias('mautic.mt3smarketingprogram.model.stakeholder', MauticPlugin\MT3SMarketingProgramBundle\Model\StakeholderModel::class); $services->alias('mautic.mt3smarketingprogram.model.audience', MauticPlugin\MT3SMarketingProgramBundle\Model\AudienceModel::class); // Smart Links domain: getModel('mt3smarketingprogram.smart_link') / getModel('mt3smarketingprogram.utm_taxonomy'). diff --git a/Controller/CallScriptController.php b/Controller/CallScriptController.php new file mode 100644 index 0000000..cab54f7 --- /dev/null +++ b/Controller/CallScriptController.php @@ -0,0 +1,118 @@ + Call Scripts), using core's standard CRUD flow. + * + * Model mt3smarketingprogram.call_script (mautic.mt3smarketingprogram.model.call_script), permission base + * mt3smarketingprogram:call_scripts, translation base mt3s.call_script. + * + * Call scripts have no detail page: after Save or Cancel the user goes back to the list. They are + * never cloned (the outcomes are part of the script). + */ +class CallScriptController extends AbstractStandardFormController +{ + public const ROUTE_INDEX = 'mt3s_call_script_index'; + public const ROUTE_ACTION = 'mt3s_call_script_action'; + + protected function getModelName(): string + { + return 'mt3smarketingprogram.call_script'; + } + + protected function getTemplateBase(): string + { + return '@MT3SMarketingProgram/CallScript'; + } + + protected function getIndexRoute(): string + { + return self::ROUTE_INDEX; + } + + protected function getActionRoute(): string + { + return self::ROUTE_ACTION; + } + + /** + * The OnLoad JS prefix: core dispatches Mautic[getJsLoadMethodPrefix() + "OnLoad"]() + * (Mautic.mt3sMpCallScriptOnLoad in Assets/js/mt3s-mp-program.js). Without this override, + * core falls back to the model name, which nothing listens to. + */ + protected function getJsLoadMethodPrefix(): string + { + return 'mt3sMpCallScript'; + } + + /** + * Core would build mautic.mt3smarketingprogram.call_script; every key of the feature lives + * under mt3s.call_script. + */ + protected function getTranslationBase(): string + { + return 'mt3s.call_script'; + } + + /** + * @param int $page + */ + public function indexAction(Request $request, $page = 1): Response + { + return $this->indexStandard($request, $page); + } + + public function newAction(Request $request): Response + { + return $this->newStandard($request); + } + + /** + * @param int $objectId + * @param bool $ignorePost + */ + public function editAction(Request $request, $objectId, $ignorePost = false): Response + { + return $this->editStandard($request, $objectId, $ignorePost); + } + + /** + * @param int $objectId + */ + public function deleteAction(Request $request, $objectId): Response + { + return $this->deleteStandard($request, $objectId); + } + + public function batchDeleteAction(Request $request): Response + { + return $this->batchDeleteStandard($request); + } + + /** + * Call scripts don't have a detail page; after Save or Cancel go back to the list. + * + * @param string $action + */ + protected function getPostActionControllerAction($action): string + { + return 'index'; + } + + /** + * A saved call script is never cloned: its outcomes are part of it. + * + * @param int|null $objectId + */ + public function cloneAction(Request $request, $objectId): Response + { + $this->throwAccessDenied(); + } +} diff --git a/Entity/CallScript.php b/Entity/CallScript.php new file mode 100644 index 0000000..7e207a6 --- /dev/null +++ b/Entity/CallScript.php @@ -0,0 +1,544 @@ + + */ + 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 + */ + 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 + */ + 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 + */ + public function getCallingDays(): array + { + return $this->callingDays; + } + + /** + * @param list|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; + } +} diff --git a/Entity/CallScriptOutcome.php b/Entity/CallScriptOutcome.php new file mode 100644 index 0000000..3e9521a --- /dev/null +++ b/Entity/CallScriptOutcome.php @@ -0,0 +1,200 @@ + + */ + private array $options = []; + + /** + * Display order within the script, from 0. Set by drag and drop in the form. + */ + private int $position = 0; + + public static function loadMetadata(OrmClassMetadata $metadata): void + { + $builder = new ClassMetadataBuilder($metadata); + + $builder->setTable(self::TABLE_NAME); + + $builder->addId(); + + $builder->createManyToOne('callScript', CallScript::class) + ->inversedBy('outcomes') + ->addJoinColumn('call_script_id', 'id', false, false, 'CASCADE') + ->build(); + + $builder->createField('label', Types::STRING) + ->length(self::LABEL_MAX_LENGTH) + ->build(); + + // Mapped on the raw metadata: ClassMetadataBuilder forces VARCHAR(191) on strings and + // doesn't accept enum or JSON types. + $metadata->mapField([ + 'fieldName' => 'inputType', + 'columnName' => 'input_type', + 'type' => Types::STRING, + 'length' => 20, + 'enumType' => CallScriptOutcomeInputType::class, + 'options' => ['default' => CallScriptOutcomeInputType::FreeText->value], + ]); + + $metadata->mapField([ + 'fieldName' => 'options', + 'columnName' => 'options', + 'type' => Types::JSON, + ]); + + $builder->createField('position', Types::INTEGER) + ->option('default', 0) + ->build(); + } + + public static function loadValidatorMetadata(ClassMetadata $metadata): void + { + $metadata->addPropertyConstraint('label', new NotBlank(message: 'mt3s.call_script.outcome.label.required')); + $metadata->addPropertyConstraint('label', new Length(max: self::LABEL_MAX_LENGTH)); + $metadata->addConstraint(new ValidCallScriptOutcomeOptions()); + } + + public function getId(): ?int + { + return $this->id; + } + + public function getCallScript(): ?CallScript + { + return $this->callScript; + } + + public function setCallScript(?CallScript $callScript): static + { + $this->callScript = $callScript; + + return $this; + } + + public function getLabel(): ?string + { + return $this->label; + } + + public function setLabel(?string $label): static + { + $this->label = $label; + + return $this; + } + + public function getInputType(): CallScriptOutcomeInputType + { + return $this->inputType; + } + + /** + * Null (a type field missing from the submitted form) keeps the current type. + */ + public function setInputType(?CallScriptOutcomeInputType $inputType): static + { + if (null !== $inputType) { + $this->inputType = $inputType; + } + + return $this; + } + + public function hasOptions(): bool + { + return $this->inputType->hasOptions(); + } + + /** + * @return list + */ + public function getOptions(): array + { + return $this->options; + } + + /** + * Keeps the {value, label} rows of the submitted options, dropping the empty ones and + * defaulting an empty label to the value. + * + * @param list|array|null $options + */ + public function setOptions(?array $options): static + { + $clean = []; + foreach (array_slice($options ?? [], 0, self::OPTIONS_MAX) as $option) { + if (!is_array($option)) { + continue; + } + + $value = trim((string) ($option['value'] ?? '')); + $label = trim((string) ($option['label'] ?? '')); + + if ('' === $value && '' === $label) { + continue; + } + + $clean[] = ['value' => $value, 'label' => '' !== $label ? $label : $value]; + } + + $this->options = $clean; + + return $this; + } + + public function getPosition(): int + { + return $this->position; + } + + public function setPosition(?int $position): static + { + $this->position = $position ?? 0; + + return $this; + } +} diff --git a/Entity/CallScriptOutcomeInputType.php b/Entity/CallScriptOutcomeInputType.php new file mode 100644 index 0000000..8a7fe2e --- /dev/null +++ b/Entity/CallScriptOutcomeInputType.php @@ -0,0 +1,30 @@ +value; + } + + /** + * True when the user records the outcome by choosing among configured options. + */ + public function hasOptions(): bool + { + return self::FreeText !== $this; + } +} diff --git a/Entity/CallScriptRepository.php b/Entity/CallScriptRepository.php new file mode 100644 index 0000000..51b3f05 --- /dev/null +++ b/Entity/CallScriptRepository.php @@ -0,0 +1,57 @@ + + */ +class CallScriptRepository extends CommonRepository +{ + public function getTableAlias(): string + { + return 'cs'; + } + + /** + * Loads the owner and category with the scripts, so that the list doesn't query them one by one. + * + * @param array $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 + */ + protected function addCatchAllWhereClause($q, $filter): array + { + return $this->addStandardCatchAllWhereClause($q, $filter, [ + $this->getTableAlias().'.name', + ]); + } + + /** + * @return array + */ + protected function getDefaultOrder(): array + { + return [ + [$this->getTableAlias().'.name', 'ASC'], + ]; + } +} diff --git a/Entity/CallScriptRetryBackoff.php b/Entity/CallScriptRetryBackoff.php new file mode 100644 index 0000000..9240191 --- /dev/null +++ b/Entity/CallScriptRetryBackoff.php @@ -0,0 +1,24 @@ +value; + } +} diff --git a/Entity/CallScriptTimezoneMode.php b/Entity/CallScriptTimezoneMode.php new file mode 100644 index 0000000..342cafa --- /dev/null +++ b/Entity/CallScriptTimezoneMode.php @@ -0,0 +1,24 @@ +value; + } + + public function isFixed(): bool + { + return self::Fixed === $this; + } +} diff --git a/Form/Type/CallScriptOutcomeOptionType.php b/Form/Type/CallScriptOutcomeOptionType.php new file mode 100644 index 0000000..d17c6c8 --- /dev/null +++ b/Form/Type/CallScriptOutcomeOptionType.php @@ -0,0 +1,45 @@ +add('value', TextType::class, [ + 'label' => 'mt3s.call_script.outcome_option.field.value', + 'label_attr' => ['class' => 'control-label'], + 'attr' => ['class' => 'form-control', 'maxlength' => 191], + ]); + + $builder->add('label', TextType::class, [ + 'label' => 'mt3s.call_script.outcome_option.field.label', + 'label_attr' => ['class' => 'control-label'], + 'attr' => ['class' => 'form-control', 'maxlength' => 191], + 'required' => false, + ]); + } + + public function configureOptions(OptionsResolver $resolver): void + { + $resolver->setDefaults([ + 'data_class' => null, + ]); + } + + public function getBlockPrefix(): string + { + return 'mt3s_call_script_outcome_option'; + } +} diff --git a/Form/Type/CallScriptOutcomeType.php b/Form/Type/CallScriptOutcomeType.php new file mode 100644 index 0000000..6344a70 --- /dev/null +++ b/Form/Type/CallScriptOutcomeType.php @@ -0,0 +1,69 @@ +add('label', TextType::class, [ + 'label' => 'mt3s.call_script.outcome.field.label', + 'label_attr' => ['class' => 'control-label'], + 'attr' => ['class' => 'form-control', 'maxlength' => CallScriptOutcome::LABEL_MAX_LENGTH], + ]); + + $builder->add('inputType', EnumType::class, [ + 'label' => 'mt3s.call_script.outcome.field.type', + 'label_attr' => ['class' => 'control-label'], + 'attr' => ['class' => 'form-control program-outcome-type'], + 'class' => CallScriptOutcomeInputType::class, + 'choice_label' => fn (CallScriptOutcomeInputType $type): string => $type->getLabelKey(), + ]); + + // The choices of a checkbox, radio or dropdown outcome; hidden by the JS for free text. + $builder->add('options', CollectionType::class, [ + 'label' => false, + 'entry_type' => CallScriptOutcomeOptionType::class, + 'allow_add' => true, + 'allow_delete' => true, + 'by_reference' => false, + 'prototype' => true, + 'prototype_name' => '__option__', + 'required' => false, + ]); + + // The row's order in the collection, rewritten by mt3s-mp-program.js after each change. + $builder->add('position', HiddenType::class, [ + 'attr' => ['class' => 'program-row-position'], + ]); + } + + public function configureOptions(OptionsResolver $resolver): void + { + $resolver->setDefaults([ + 'data_class' => CallScriptOutcome::class, + ]); + } + + public function getBlockPrefix(): string + { + return 'mt3s_call_script_outcome'; + } +} diff --git a/Form/Type/CallScriptType.php b/Form/Type/CallScriptType.php new file mode 100644 index 0000000..e836052 --- /dev/null +++ b/Form/Type/CallScriptType.php @@ -0,0 +1,229 @@ + Call Scripts). + * + * The script keeps the HTML typed in it (the "html" cleaning mask), including the dynamic tokens like + * {contact.first_name}. The outcomes are edited as a sortable collection (see Assets/js/mt3s-mp-program.js); + * the options of an outcome are shown only for the checkbox, radio and dropdown types. + */ +class CallScriptType extends AbstractType +{ + public function __construct( + private EntityManagerInterface $em, + ) { + } + + public function buildForm(FormBuilderInterface $builder, array $options): void + { + // Pass a mask array, never nothing: without one, core applies its "clean" mask (HTML-encodes &, <, >, + // quotes). "html" keeps the script markup; "clean" strips the rest of the fields. + $builder->addEventSubscriber(new CleanFormSubscriber([ + 'name' => 'clean', + 'description' => 'clean', + 'script' => 'html', + ])); + + $builder->add('name', TextType::class, [ + 'label' => 'mt3s.call_script.field.name', + 'label_attr' => ['class' => 'control-label'], + 'attr' => ['class' => 'form-control', 'maxlength' => CallScript::NAME_MAX_LENGTH], + ]); + + $builder->add('description', TextareaType::class, [ + 'label' => 'mt3s.call_script.field.description', + 'label_attr' => ['class' => 'control-label'], + 'attr' => ['class' => 'form-control', 'rows' => 2], + 'required' => false, + ]); + + $builder->add('script', TextareaType::class, [ + 'label' => 'mt3s.call_script.field.script', + 'label_attr' => ['class' => 'control-label'], + 'attr' => [ + 'class' => 'form-control', + 'rows' => 14, + 'style' => 'font-family: monospace;', + 'tooltip' => 'mt3s.call_script.field.script.help', + ], + 'required' => false, + ]); + + // Required here; the column is nullable only because of onDelete SET NULL. + $builder->add( + $builder->create('owner', UserListType::class, [ + 'label' => 'mt3s.call_script.field.owner', + 'label_attr' => ['class' => 'control-label'], + 'attr' => ['class' => 'form-control'], + 'required' => true, + 'multiple' => false, + ])->addModelTransformer(new IdToEntityModelTransformer($this->em, User::class)) + ); + + $builder->add('category', CategoryListType::class, [ + 'bundle' => 'call_script', + 'label' => 'mt3s.call_script.field.category', + ]); + + $builder->add('isPublished', YesNoButtonGroupType::class, [ + 'label' => 'mautic.core.form.available', + ]); + + // The validity window: "start" and "end" date and time. + $builder->add('publishUp', PublishUpDateType::class, [ + 'label' => 'mt3s.call_script.field.start', + ]); + + $builder->add('publishDown', PublishDownDateType::class, [ + 'label' => 'mt3s.call_script.field.end', + ]); + + // Calling window: the weekdays, the hours and the timezone the hours are read in. + $builder->add('callingDays', ChoiceType::class, [ + 'label' => 'mt3s.call_script.field.calling_days', + 'label_attr' => ['class' => 'control-label'], + 'choices' => $this->weekdayChoices(), + 'choice_translation_domain' => true, + 'multiple' => true, + 'expanded' => true, + 'required' => false, + ]); + + $builder->add('callingFrom', TimeType::class, [ + 'label' => 'mt3s.call_script.field.calling_from', + 'label_attr' => ['class' => 'control-label'], + 'widget' => 'single_text', + 'with_seconds' => false, + 'attr' => ['class' => 'form-control'], + 'required' => false, + ]); + + $builder->add('callingTo', TimeType::class, [ + 'label' => 'mt3s.call_script.field.calling_to', + 'label_attr' => ['class' => 'control-label'], + 'widget' => 'single_text', + 'with_seconds' => false, + 'attr' => ['class' => 'form-control'], + 'required' => false, + ]); + + $builder->add('callingTimezoneMode', EnumType::class, [ + 'label' => 'mt3s.call_script.field.calling_timezone_mode', + 'label_attr' => ['class' => 'control-label'], + 'attr' => ['class' => 'form-control'], + 'class' => CallScriptTimezoneMode::class, + 'choice_label' => fn (CallScriptTimezoneMode $mode): string => $mode->getLabelKey(), + ]); + + $builder->add('callingTimezone', TimezoneType::class, [ + 'label' => 'mt3s.call_script.field.calling_timezone', + 'placeholder' => '', + 'required' => false, + ]); + + // Retry policy: how many times, how long between attempts, and how the delay grows. + $builder->add('retryMaxAttempts', IntegerType::class, [ + 'label' => 'mt3s.call_script.field.retry_max_attempts', + 'label_attr' => ['class' => 'control-label'], + 'attr' => [ + 'class' => 'form-control', + 'min' => CallScript::RETRY_ATTEMPTS_MIN, + 'max' => CallScript::RETRY_ATTEMPTS_MAX, + 'step' => 1, + ], + ]); + + $builder->add('retryDelayMinutes', IntegerType::class, [ + 'label' => 'mt3s.call_script.field.retry_delay_minutes', + 'label_attr' => ['class' => 'control-label'], + 'attr' => [ + 'class' => 'form-control', + 'min' => 0, + 'max' => CallScript::RETRY_DELAY_MAX, + 'step' => 1, + ], + ]); + + $builder->add('retryBackoff', EnumType::class, [ + 'label' => 'mt3s.call_script.field.retry_backoff', + 'label_attr' => ['class' => 'control-label'], + 'attr' => ['class' => 'form-control'], + 'class' => CallScriptRetryBackoff::class, + 'choice_label' => fn (CallScriptRetryBackoff $backoff): string => $backoff->getLabelKey(), + ]); + + // Outcomes: the list of things the agent can record, each with its data type and options. + $builder->add('outcomes', CollectionType::class, [ + 'label' => false, + 'entry_type' => CallScriptOutcomeType::class, + 'allow_add' => true, + 'allow_delete' => true, + 'by_reference' => false, + 'prototype' => true, + 'prototype_name' => '__outcome__', + 'required' => false, + ]); + + $builder->add('buttons', FormButtonsType::class); + + if (!empty($options['action'])) { + $builder->setAction($options['action']); + } + } + + /** + * The weekdays of the calling window: translation key => ISO short name. + * + * @return array + */ + private function weekdayChoices(): array + { + $choices = []; + foreach (CallScript::WEEKDAYS as $day) { + $choices['mt3s.call_script.day.'.$day] = $day; + } + + return $choices; + } + + public function configureOptions(OptionsResolver $resolver): void + { + $resolver->setDefaults([ + 'data_class' => CallScript::class, + ]); + } + + public function getBlockPrefix(): string + { + return 'mt3s_call_script'; + } +} diff --git a/Migrations/Version_0_19_0.php b/Migrations/Version_0_19_0.php new file mode 100644 index 0000000..3c29531 --- /dev/null +++ b/Migrations/Version_0_19_0.php @@ -0,0 +1,136 @@ + local column, referenced table, ON DELETE clause. + */ + private const FOREIGN_KEYS = [ + ['mt3s_call_scripts', 'owner_id', 'users', 'ON DELETE SET NULL'], + ['mt3s_call_scripts', 'category_id', 'categories', 'ON DELETE SET NULL'], + ['mt3s_call_script_outcomes', 'call_script_id', 'mt3s_call_scripts', 'ON DELETE CASCADE'], + ]; + + protected function isApplicable(Schema $schema): bool + { + return null !== $this->getCreateTableSql($schema) + || [] !== $this->getMissingForeignKeys($schema); + } + + protected function up(): void + { + $connection = $this->entityManager->getConnection(); + $schema = $this->introspectSchema(); + + if (!$schema->hasTable($this->concatPrefix(CallScript::TABLE_NAME))) { + $connection->executeStatement($this->buildCreateTableSql(CallScript::class, CallScript::TABLE_NAME)); + $schema = $this->introspectSchema(); + } + + if (!$schema->hasTable($this->concatPrefix(CallScriptOutcome::TABLE_NAME))) { + $connection->executeStatement($this->buildCreateTableSql(CallScriptOutcome::class, CallScriptOutcome::TABLE_NAME)); + $schema = $this->introspectSchema(); + } + + foreach ($this->getMissingForeignKeys($schema) as [$table, $column, $referenceTable, $onDelete]) { + $connection->executeStatement($this->generateAlterTableForeignKeyStatement( + $table, + [$column], + $referenceTable, + ['id'], + $onDelete + )); + } + } + + /** + * The missing CREATE TABLE statement, or null when both tables already exist. + */ + private function getCreateTableSql(Schema $schema): ?string + { + if (!$schema->hasTable($this->concatPrefix(CallScript::TABLE_NAME))) { + return 'mt3s_call_scripts'; + } + + if (!$schema->hasTable($this->concatPrefix(CallScriptOutcome::TABLE_NAME))) { + return 'mt3s_call_script_outcomes'; + } + + return null; + } + + /** + * @return list + */ + private function getMissingForeignKeys(Schema $schema): array + { + $missing = []; + + foreach (self::FOREIGN_KEYS as $foreignKey) { + [$table, $column] = $foreignKey; + $prefixed = $this->concatPrefix($table); + + // The tables may not exist yet; up() adds their keys after creating them. + if (!$schema->hasTable($prefixed)) { + continue; + } + + $found = false; + foreach ($schema->getTable($prefixed)->getForeignKeys() as $existing) { + if (in_array($column, $existing->getLocalColumns(), true)) { + $found = true; + break; + } + } + + if (!$found) { + $missing[] = $foreignKey; + } + } + + return $missing; + } + + /** + * @param class-string $entityClass + */ + private function buildCreateTableSql(string $entityClass, string $table): string + { + $schemaTool = new SchemaTool($this->entityManager); + $prefix = 'CREATE TABLE '.$this->concatPrefix($table).' '; + + foreach ($schemaTool->getCreateSchemaSql([$this->entityManager->getClassMetadata($entityClass)]) as $sql) { + if (str_starts_with($sql, $prefix)) { + return $sql; + } + } + + throw new \RuntimeException('SchemaTool returned no CREATE TABLE statement for '.$table.'.'); + } + + private function introspectSchema(): Schema + { + return $this->entityManager->getConnection()->createSchemaManager()->introspectSchema(); + } +} diff --git a/Model/CallScriptModel.php b/Model/CallScriptModel.php new file mode 100644 index 0000000..34c9d74 --- /dev/null +++ b/Model/CallScriptModel.php @@ -0,0 +1,80 @@ + + */ +class CallScriptModel extends FormModel +{ + public function getRepository(): CallScriptRepository + { + $repository = $this->em->getRepository(CallScript::class); + \assert($repository instanceof CallScriptRepository); + + return $repository; + } + + public function getPermissionBase(): string + { + return 'mt3smarketingprogram:call_scripts'; + } + + /** + * With no ID, returns a new script with the current user as owner. + */ + public function getEntity($id = null): ?CallScript + { + if (null === $id) { + $callScript = new CallScript(); + $callScript->setOwner($this->userHelper->getUser(true)); + + return $callScript; + } + + $callScript = parent::getEntity($id); + + return $callScript instanceof CallScript ? $callScript : null; + } + + /** + * Keeps the outcome positions contiguous (0..n-1) before saving. + */ + public function saveEntity($entity, $unlock = true): void + { + if ($entity instanceof CallScript) { + $entity->normalizePositions(); + } + + parent::saveEntity($entity, $unlock); + } + + /** + * @param array $options + */ + public function createForm($entity, FormFactoryInterface $formFactory, $action = null, $options = []): FormInterface + { + if (!$entity instanceof CallScript) { + throw new MethodNotAllowedHttpException(['CallScript']); + } + + if (!empty($action)) { + $options['action'] = $action; + } + + return $formFactory->create(CallScriptType::class, $entity, $options); + } +} diff --git a/Resources/views/CallScript/form.html.twig b/Resources/views/CallScript/form.html.twig new file mode 100644 index 0000000..86cf9e4 --- /dev/null +++ b/Resources/views/CallScript/form.html.twig @@ -0,0 +1,129 @@ +{% extends '@MauticCore/Default/content.html.twig' %} + +{% block mauticContent %}mt3sMpCallScript{% endblock %} + +{% block headerTitle %} + {% if form.vars.data.id %} + {{ 'mt3s.call_script.header.edit'|trans({'%name%': form.vars.data.name}) }} + {% else %} + {{ 'mt3s.call_script.header.new'|trans }} + {% endif %} +{% endblock %} + +{# One {value, label} option of an outcome's choices. #} +{% macro option_row(option) %} +
  • +
    +
    {{ form_row(option.value) }}
    +
    {{ form_row(option.label) }}
    +
    + +
    +
    +
  • +{% endmacro %} + +{# One outcome: its label, the data type the agent records it with, and the options of the choice types. + Adding, removing and reordering is handled by Assets/js/mt3s-mp-program.js through the + program-collection-* classes (the options are a nested collection of the same kind). #} +{% macro outcome_row(outcome) %} +
  • +
    +
    + + + +
    +
    +
    +
    {{ form_row(outcome.label) }}
    +
    {{ form_row(outcome.inputType) }}
    +
    +
    +
    {{ 'mt3s.call_script.outcome.options'|trans }}
    +
    +

    + {{ 'mt3s.call_script.outcome.options.empty'|trans }} +

    +
      + {% for option in outcome.options %} + {{ _self.option_row(option) }} + {% endfor %} +
    + +
    +
    + {{ form_widget(outcome.position) }} +
    +
    + +
    +
    +
  • +{% endmacro %} + +{% block content %} + {{ form_start(form) }} +
    +
    +
    + {{ form_row(form.name) }} + {{ form_row(form.description) }} + {{ form_row(form.script) }} +
    +
    +

    {{ 'mt3s.call_script.outcome.list'|trans }}

    +
    + {{ form_errors(form.outcomes) }} +

    + {{ 'mt3s.call_script.outcome.empty'|trans }} +

    +
      + {% for outcome in form.outcomes %} + {{ _self.outcome_row(outcome) }} + {% endfor %} +
    + +
    + {% do form.outcomes.setRendered %} +
    +
    +
    +
    + {{ form_row(form.owner) }} + {{ form_row(form.category) }} + {{ form_row(form.isPublished) }} + {{ form_row(form.publishUp) }} + {{ form_row(form.publishDown) }} + +

    {{ 'mt3s.call_script.section.calling_window'|trans }}

    + {{ form_row(form.callingDays) }} + {{ form_row(form.callingFrom) }} + {{ form_row(form.callingTo) }} + {{ form_row(form.callingTimezoneMode) }} + {{ form_row(form.callingTimezone) }} + +

    {{ 'mt3s.call_script.section.retry_policy'|trans }}

    + {{ form_row(form.retryMaxAttempts) }} + {{ form_row(form.retryDelayMinutes) }} + {{ form_row(form.retryBackoff) }} +
    +
    +
    + {{ form_row(form.buttons) }} + {# render_rest is false, so the hidden CSRF token must be rendered explicitly. #} + {{ form_widget(form._token) }} + {{ form_end(form, {'render_rest': false}) }} +{% endblock %} diff --git a/Resources/views/CallScript/list.html.twig b/Resources/views/CallScript/list.html.twig new file mode 100644 index 0000000..b36e947 --- /dev/null +++ b/Resources/views/CallScript/list.html.twig @@ -0,0 +1,133 @@ +{% set isIndex = 'index' == tmpl|default('index') ? true : false %} +{% set tmpl = 'list' %} +{% extends isIndex ? '@MauticCore/Default/content.html.twig' : '@MauticCore/Default/raw_output.html.twig' %} + +{% block mauticContent %}mt3sMpCallScript{% endblock %} + +{% block headerTitle %}{{ 'mt3s.call_script.header.index'|trans }}{% endblock %} + +{% block content %} +
    + {# The toolbar belongs to the full page only: ajax reloads (sort, filter, pagination) + replace the contents of .page-list, so including it here again would duplicate it. #} + {% if isIndex %} + {{- include('@MauticCore/Helper/list_toolbar.html.twig', { + 'searchValue': searchValue, + 'action': currentRoute, + 'page_actions': { + 'templateButtons': { + 'new': permissions[permissionBase ~ ':create'], + }, + 'langVar': 'mt3smarketingprogram.call_scripts', + 'routeBase': 'call_scripts', + }, + 'bulk_actions': { + 'langVar': 'mt3smarketingprogram.call_scripts', + 'templateButtons': { + 'delete': permissions[permissionBase ~ ':deleteown'] or permissions[permissionBase ~ ':deleteother'], + }, + }, + }) -}} + {% endif %} +
    + {% if items is defined and items is not empty %} +
    + + + + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'checkall': 'true', + 'target': '#callScriptTable', + }) }} + {# Columns: Name, Category, Status, Owner, Modified. #} + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'sessionVar': sessionVar, + 'orderBy': tablePrefix ~ '.name', + 'text': 'mt3s.call_script.field.name', + 'class': 'col-call-script-name', + 'default': true, + }) }} + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'sessionVar': sessionVar, + 'text': 'mt3s.call_script.list.category', + 'class': 'visible-md visible-lg col-call-script-category', + }) }} + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'sessionVar': sessionVar, + 'orderBy': tablePrefix ~ '.isPublished', + 'text': 'mt3s.call_script.list.status', + 'class': 'col-call-script-status', + }) }} + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'sessionVar': sessionVar, + 'text': 'mt3s.call_script.list.owner', + 'class': 'visible-md visible-lg col-call-script-owner', + }) }} + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'sessionVar': sessionVar, + 'orderBy': tablePrefix ~ '.dateModified', + 'text': 'mt3s.call_script.list.modified', + 'class': 'visible-md visible-lg col-call-script-date', + }) }} + + + + {% for item in items %} + {% set canEdit = securityHasEntityAccess(permissions[permissionBase ~ ':editown'], permissions[permissionBase ~ ':editother'], item.createdBy) %} + + + + + + + + + {% endfor %} + +
    + {{- include('@MauticCore/Helper/list_actions.html.twig', { + 'item': item, + 'templateButtons': { + 'edit': canEdit, + 'delete': securityHasEntityAccess(permissions[permissionBase ~ ':deleteown'], permissions[permissionBase ~ ':deleteother'], item.createdBy), + }, + 'langVar': 'mt3smarketingprogram.call_scripts', + 'routeBase': 'call_scripts', + }) -}} + + {% if canEdit %} + {{ item.name }} + {% else %} + {{ item.name }} + {% endif %} + {{ item.category.name|default('—') }} + {% if item.isPublished %} + {{ 'mt3s.call_script.list.published'|trans }} + {% else %} + {{ 'mt3s.call_script.list.unpublished'|trans }} + {% endif %} + {{ item.owner.name|default('—') }}{{ item.dateModified ? dateToFull(item.dateModified) : '—' }}
    + +
    + {% elseif searchValue is not empty %} + {{ include('@MauticCore/Helper/noresults.html.twig') }} + {% else %} +
    + {{ include('@MauticCore/Components/content-block.html.twig', { + 'heading': 'mt3s.call_script.onboarding.heading', + 'subheading': 'mt3s.call_script.onboarding.subheading', + 'copy': 'mt3s.call_script.onboarding.copy', + }) }} +
    + {% endif %} +
    +
    +{% endblock %} diff --git a/Security/Permissions/MT3SMarketingProgramPermissions.php b/Security/Permissions/MT3SMarketingProgramPermissions.php index d40de66..1510580 100644 --- a/Security/Permissions/MT3SMarketingProgramPermissions.php +++ b/Security/Permissions/MT3SMarketingProgramPermissions.php @@ -31,6 +31,7 @@ class MT3SMarketingProgramPermissions extends AbstractPermissions $this->addExtendedPermissions(['audiences']); $this->addExtendedPermissions(['smart_links']); $this->addExtendedPermissions(['taxonomies']); + $this->addExtendedPermissions(['call_scripts']); $this->addStandardPermissions(['itemtypes']); } @@ -52,6 +53,7 @@ class MT3SMarketingProgramPermissions extends AbstractPermissions $this->addExtendedFormFields('mt3smarketingprogram', 'audiences', $builder, $data); $this->addExtendedFormFields('mt3smarketingprogram', 'smart_links', $builder, $data); $this->addExtendedFormFields('mt3smarketingprogram', 'taxonomies', $builder, $data); + $this->addExtendedFormFields('mt3smarketingprogram', 'call_scripts', $builder, $data); $this->addStandardFormFields('mt3smarketingprogram', 'itemtypes', $builder, $data); } } diff --git a/Tests/Unit/Entity/CallScriptTest.php b/Tests/Unit/Entity/CallScriptTest.php new file mode 100644 index 0000000..d854d1e --- /dev/null +++ b/Tests/Unit/Entity/CallScriptTest.php @@ -0,0 +1,104 @@ +getCallingTimezoneMode()); + self::assertSame(3, $script->getRetryMaxAttempts()); + self::assertSame(30, $script->getRetryDelayMinutes()); + self::assertSame(CallScriptRetryBackoff::None, $script->getRetryBackoff()); + self::assertSame([], $script->getCallingDays()); + self::assertCount(0, $script->getOutcomes()); + } + + public function testCallingDaysAreFilteredAndDeduplicated(): void + { + $script = new CallScript(); + + $script->setCallingDays(['mon', 'mon', 'xxx', 'fri']); + + self::assertSame(['mon', 'fri'], $script->getCallingDays()); + } + + public function testNormalizePositionsRenumbersTheOutcomes(): void + { + $script = new CallScript(); + $first = (new CallScriptOutcome())->setLabel('First')->setPosition(7); + $second = (new CallScriptOutcome())->setLabel('Second')->setPosition(2); + $script->addOutcome($first); + $script->addOutcome($second); + + $script->normalizePositions(); + + self::assertSame(0, $second->getPosition()); + self::assertSame(1, $first->getPosition()); + self::assertSame(['Second', 'First'], array_map(fn (CallScriptOutcome $o): ?string => $o->getLabel(), $script->getOutcomes()->toArray())); + } + + public function testOutcomeOptionsAreSanitized(): void + { + $outcome = new CallScriptOutcome(); + + $outcome->setOptions([ + ['value' => 'yes', 'label' => 'Yes'], + ['value' => '', 'label' => ''], + ['value' => 'maybe', 'label' => ''], + ]); + + self::assertSame([ + ['value' => 'yes', 'label' => 'Yes'], + ['value' => 'maybe', 'label' => 'maybe'], + ], $outcome->getOptions()); + } + + public function testNullEnumsAndNumbersKeepTheCurrentValues(): void + { + $script = new CallScript(); + $script->setCallingTimezoneMode(CallScriptTimezoneMode::Fixed); + $script->setRetryBackoff(CallScriptRetryBackoff::Exponential); + $script->setRetryMaxAttempts(5); + + $script->setCallingTimezoneMode(null); + $script->setRetryBackoff(null); + $script->setRetryMaxAttempts(null); + + self::assertSame(CallScriptTimezoneMode::Fixed, $script->getCallingTimezoneMode()); + self::assertSame(CallScriptRetryBackoff::Exponential, $script->getRetryBackoff()); + self::assertSame(5, $script->getRetryMaxAttempts()); + } + + public function testDateRangeInterfaceMapsTheValidityWindow(): void + { + $script = new CallScript(); + $start = new \DateTime('2026-01-10 09:00:00'); + $end = new \DateTime('2026-01-12 18:00:00'); + + $script->setPublishUp($start); + $script->setPublishDown($end); + + self::assertSame($start, $script->getStartDate()); + self::assertSame($end, $script->getEndDate()); + } + + public function testOutcomeInputTypesDeclareWhetherTheyHaveOptions(): void + { + self::assertFalse(CallScriptOutcomeInputType::FreeText->hasOptions()); + self::assertTrue(CallScriptOutcomeInputType::Checkbox->hasOptions()); + self::assertTrue(CallScriptOutcomeInputType::Radio->hasOptions()); + self::assertTrue(CallScriptOutcomeInputType::Dropdown->hasOptions()); + } +} diff --git a/Tests/Unit/Validator/ValidCallScriptOutcomeOptionsValidatorTest.php b/Tests/Unit/Validator/ValidCallScriptOutcomeOptionsValidatorTest.php new file mode 100644 index 0000000..4bff5de --- /dev/null +++ b/Tests/Unit/Validator/ValidCallScriptOutcomeOptionsValidatorTest.php @@ -0,0 +1,96 @@ +setInputType(CallScriptOutcomeInputType::FreeText); + + $this->validate($outcome, []); + } + + public function testAChoiceOutcomeWithOptionsIsValid(): void + { + $outcome = (new CallScriptOutcome()) + ->setInputType(CallScriptOutcomeInputType::Dropdown) + ->setOptions([['value' => 'yes', 'label' => 'Yes']]); + + $this->validate($outcome, []); + } + + public function testAChoiceOutcomeWithoutOptionsIsRefused(): void + { + $outcome = (new CallScriptOutcome())->setInputType(CallScriptOutcomeInputType::Radio); + + $this->validate($outcome, ['mt3s.call_script.outcome.options.required']); + } + + public function testAFreeTextOutcomeWithOptionsIsRefused(): void + { + $outcome = (new CallScriptOutcome()) + ->setInputType(CallScriptOutcomeInputType::FreeText) + ->setOptions([['value' => 'yes', 'label' => 'Yes']]); + + $this->validate($outcome, ['mt3s.call_script.outcome.options.free_text_forbidden']); + } + + public function testOptionsNeedAValue(): void + { + $outcome = (new CallScriptOutcome()) + ->setInputType(CallScriptOutcomeInputType::Radio) + ->setOptions([['value' => '', 'label' => 'No value']]); + + $this->validate($outcome, ['mt3s.call_script.outcome.options.value_required']); + } + + public function testOptionValuesMustBeUnique(): void + { + $outcome = (new CallScriptOutcome()) + ->setInputType(CallScriptOutcomeInputType::Checkbox) + ->setOptions([ + ['value' => 'yes', 'label' => 'Yes'], + ['value' => 'yes', 'label' => 'Again'], + ]); + + $this->validate($outcome, ['mt3s.call_script.outcome.options.duplicate_value']); + } + + /** + * @param list $expectedMessages + */ + private function validate(CallScriptOutcome $outcome, array $expectedMessages): void + { + $violations = []; + $builder = $this->createMock(ConstraintViolationBuilderInterface::class); + $builder->method('atPath')->willReturnSelf(); + $builder->method('addViolation')->willReturnCallback(function () use (&$violations, $builder): void { + $violations[] = $builder; + }); + + $context = $this->createMock(ExecutionContextInterface::class); + $context->method('buildViolation')->willReturnCallback(function (string $message) use (&$violations, $builder): ConstraintViolationBuilderInterface { + $violations[] = $message; + + return $builder; + }); + + $validator = new ValidCallScriptOutcomeOptionsValidator(); + $validator->initialize($context); + $validator->validate($outcome, new ValidCallScriptOutcomeOptions()); + + $messages = array_values(array_filter($violations, fn ($violation): bool => is_string($violation))); + self::assertSame($expectedMessages, $messages); + } +} diff --git a/Tests/Unit/Validator/ValidCallingWindowValidatorTest.php b/Tests/Unit/Validator/ValidCallingWindowValidatorTest.php new file mode 100644 index 0000000..a55abd0 --- /dev/null +++ b/Tests/Unit/Validator/ValidCallingWindowValidatorTest.php @@ -0,0 +1,85 @@ +setCallingFrom(new \DateTime('09:00')); + $script->setCallingTo(new \DateTime('18:00')); + + $this->validate($script, null); + } + + public function testAnEmptyWindowIsValid(): void + { + $this->validate(new CallScript(), null); + } + + public function testPartialHoursAreRefused(): void + { + $script = new CallScript(); + $script->setCallingFrom(new \DateTime('09:00')); + + $this->validate($script, 'mt3s.call_script.calling_window.partial_hours'); + } + + public function testTheEndMustBeAfterTheStart(): void + { + $script = new CallScript(); + $script->setCallingFrom(new \DateTime('18:00')); + $script->setCallingTo(new \DateTime('09:00')); + + $this->validate($script, 'mt3s.call_script.calling_window.to_before_from'); + } + + public function testAFixedModeNeedsATimezone(): void + { + $script = new CallScript(); + $script->setCallingTimezoneMode(CallScriptTimezoneMode::Fixed); + + $this->validate($script, 'mt3s.call_script.calling_window.timezone_required'); + } + + public function testAFixedModeWithATimezoneIsValid(): void + { + $script = new CallScript(); + $script->setCallingTimezoneMode(CallScriptTimezoneMode::Fixed); + $script->setCallingTimezone('Europe/Paris'); + + $this->validate($script, null); + } + + private function validate(CallScript $script, ?string $expectedMessage): void + { + $violation = $this->createMock(ConstraintViolationBuilderInterface::class); + $violation->method('atPath')->willReturnSelf(); + + $context = $this->createMock(ExecutionContextInterface::class); + if (null === $expectedMessage) { + $context->expects(self::never())->method('buildViolation'); + } else { + $context->expects(self::once()) + ->method('buildViolation') + ->with($expectedMessage) + ->willReturn($violation); + $violation->expects(self::once())->method('addViolation'); + } + + $validator = new ValidCallingWindowValidator(); + $validator->initialize($context); + $validator->validate($script, new ValidCallingWindow()); + } +} diff --git a/Translations/en_US/messages.ini b/Translations/en_US/messages.ini index 2dc8276..6f1c314 100644 --- a/Translations/en_US/messages.ini +++ b/Translations/en_US/messages.ini @@ -531,3 +531,70 @@ mt3s.smart_links.taxonomies.unpublished_choice="%name% (no longer published)" mt3s.smart_links.taxonomies.free_values.tooltip="The allowed values of this parameter for the links using this taxonomy. One value per line, optionally value;Label for a display label." mt3s.smart_links.taxonomies.free_values.placeholder="one value per line" mt3s.smart_links.taxonomies.no_values.tooltip="No values are configured for this parameter in Smart Links Settings yet: ask the admin to configure some." + +; Call Scripts (Components > Call Scripts). Translation base mt3s.call_script. +mt3s.call_script.menu.index="Call Scripts" +mt3s.call_script.category.type="Call Script" +mt3s.call_script.header.index="Call Scripts" +mt3s.call_script.header.new="New Call Script" +mt3s.call_script.header.edit="Call Script - %name%" +mt3s.call_script.error.notfound="No call script with the ID %id% was found." +mt3s.call_script.form.confirmdelete="Delete the call script %name%? Its outcomes are deleted too." +mt3s.call_script.form.confirmbatchdelete="Delete the selected call scripts? Their outcomes are deleted too." +mt3s.call_script.onboarding.heading="No call scripts yet" +mt3s.call_script.onboarding.subheading="Call scripts guide your agents through a call and record what happens." +mt3s.call_script.onboarding.copy="Use the New button above to add a call script. Define its script, its outcomes, its calling window and its retry policy." +mt3s.call_script.field.name="Name" +mt3s.call_script.field.description="Description" +mt3s.call_script.field.script="Script" +mt3s.call_script.field.script.help="HTML is allowed. Use dynamic tokens like {contact.first_name}; they are kept as typed." +mt3s.call_script.field.owner="Owner" +mt3s.call_script.field.category="Category" +mt3s.call_script.field.start="Start date and time" +mt3s.call_script.field.end="End date and time" +mt3s.call_script.field.calling_days="Calling days" +mt3s.call_script.field.calling_from="From" +mt3s.call_script.field.calling_to="To" +mt3s.call_script.field.calling_timezone_mode="Timezone mode" +mt3s.call_script.field.calling_timezone="Fixed timezone" +mt3s.call_script.field.retry_max_attempts="Maximum attempts" +mt3s.call_script.field.retry_delay_minutes="Delay between attempts (minutes)" +mt3s.call_script.field.retry_backoff="Backoff" +mt3s.call_script.list.published="Published" +mt3s.call_script.list.unpublished="Unpublished" +mt3s.call_script.list.owner="Owner" +mt3s.call_script.list.category="Category" +mt3s.call_script.list.status="Status" +mt3s.call_script.list.modified="Modified" +mt3s.call_script.day.mon="Monday" +mt3s.call_script.day.tue="Tuesday" +mt3s.call_script.day.wed="Wednesday" +mt3s.call_script.day.thu="Thursday" +mt3s.call_script.day.fri="Friday" +mt3s.call_script.day.sat="Saturday" +mt3s.call_script.day.sun="Sunday" +mt3s.call_script.timezone_mode.contact="Contact's timezone" +mt3s.call_script.timezone_mode.fixed="Fixed timezone" +mt3s.call_script.retry_backoff.none="No backoff (constant delay)" +mt3s.call_script.retry_backoff.linear="Linear (delay multiplied by the attempt number)" +mt3s.call_script.retry_backoff.exponential="Exponential (delay doubled at every attempt)" +mt3s.call_script.outcome.list="Outcomes" +mt3s.call_script.outcome.empty="No outcomes yet." +mt3s.call_script.outcome.add="Add outcome" +mt3s.call_script.outcome.remove="Remove this outcome" +mt3s.call_script.outcome.drag="Drag to reorder" +mt3s.call_script.outcome.field.label="Outcome" +mt3s.call_script.outcome.field.type="Data type" +mt3s.call_script.outcome.options="Options" +mt3s.call_script.outcome.options.empty="No options yet." +mt3s.call_script.outcome.options.add="Add option" +mt3s.call_script.outcome.options.remove="Remove this option" +mt3s.call_script.outcome_type.checkbox="Checkboxes" +mt3s.call_script.outcome_type.radio="Radio buttons" +mt3s.call_script.outcome_type.free_text="Free text" +mt3s.call_script.outcome_type.dropdown="Drop-down" +mt3s.call_script.outcome_option.field.value="Value" +mt3s.call_script.outcome_option.field.label="Label" + +mt3s.call_script.section.calling_window="Calling window" +mt3s.call_script.section.retry_policy="Retry policy" diff --git a/Translations/en_US/validators.ini b/Translations/en_US/validators.ini index aa95ce6..68388e8 100644 --- a/Translations/en_US/validators.ini +++ b/Translations/en_US/validators.ini @@ -59,3 +59,13 @@ mt3s.smart_links.taxonomies.error.name_characters="The name cannot contain the c mt3s.smart_links.taxonomies.error.value_invalid="The value %value% is invalid. Use only lowercase letters, digits, hyphens, underscores and dots." mt3s.smart_links.smart_links.error.taxonomy_required="Choose a UTM Taxonomy." mt3s.smart_links.smart_links.error.taxonomy_parameter_unknown="The parameter %key% is not part of the taxonomy %name%." +mt3s.call_script.retry_attempts.range="The maximum attempts must be a whole number from 1 to 20." +mt3s.call_script.retry_delay.range="The delay must be a whole number of minutes, 0 or more." +mt3s.call_script.calling_window.partial_hours="Set both the from and the to time of the calling window." +mt3s.call_script.calling_window.to_before_from="The calling window must end after it starts." +mt3s.call_script.calling_window.timezone_required="Choose the fixed timezone of the calling window." +mt3s.call_script.outcome.label.required="An outcome needs a label." +mt3s.call_script.outcome.options.required="This outcome type needs at least one option." +mt3s.call_script.outcome.options.free_text_forbidden="A free text outcome takes no options." +mt3s.call_script.outcome.options.value_required="Every option needs a value." +mt3s.call_script.outcome.options.duplicate_value="The option values must be unique." diff --git a/Translations/fr_FR/messages.ini b/Translations/fr_FR/messages.ini index 76c4e9b..95fbcdf 100644 --- a/Translations/fr_FR/messages.ini +++ b/Translations/fr_FR/messages.ini @@ -206,3 +206,70 @@ mt3s.smart_links.taxonomies.unpublished_choice="%name% (plus publiée)" mt3s.smart_links.taxonomies.free_values.tooltip="Les valeurs autorisées de ce paramètre pour les liens utilisant cette taxonomie. Une valeur par ligne, éventuellement valeur;Libellé." mt3s.smart_links.taxonomies.free_values.placeholder="une valeur par ligne" mt3s.smart_links.taxonomies.no_values.tooltip="Aucune valeur n’est encore configurée pour ce paramètre dans Paramètres Smart Links : demandez à l’administrateur d’en configurer." + +; Scripts d'appel (Composants > Scripts d'appel). Base de traduction mt3s.call_script. +mt3s.call_script.menu.index="Scripts d'appel" +mt3s.call_script.category.type="Script d'appel" +mt3s.call_script.header.index="Scripts d'appel" +mt3s.call_script.header.new="Nouveau script d'appel" +mt3s.call_script.header.edit="Script d'appel - %name%" +mt3s.call_script.error.notfound="Aucun script d'appel avec l'ID %id% n'a été trouvé." +mt3s.call_script.form.confirmdelete="Supprimer le script d'appel %name% ? Ses résultats sont supprimés aussi." +mt3s.call_script.form.confirmbatchdelete="Supprimer les scripts d'appel sélectionnés ? Leurs résultats sont supprimés aussi." +mt3s.call_script.onboarding.heading="Aucun script d'appel pour le moment" +mt3s.call_script.onboarding.subheading="Les scripts d'appel guident vos agents pendant un appel et enregistrent son résultat." +mt3s.call_script.onboarding.copy="Utilisez le bouton Nouveau ci-dessus pour ajouter un script d'appel. Définissez son script, ses résultats, sa plage d'appel et sa politique de réessai." +mt3s.call_script.field.name="Nom" +mt3s.call_script.field.description="Description" +mt3s.call_script.field.script="Script" +mt3s.call_script.field.script.help="Le HTML est accepté. Utilisez les jetons dynamiques comme {contact.first_name} ; ils sont conservés tels quels." +mt3s.call_script.field.owner="Propriétaire" +mt3s.call_script.field.category="Catégorie" +mt3s.call_script.field.start="Date et heure de début" +mt3s.call_script.field.end="Date et heure de fin" +mt3s.call_script.field.calling_days="Jours d'appel" +mt3s.call_script.field.calling_from="De" +mt3s.call_script.field.calling_to="À" +mt3s.call_script.field.calling_timezone_mode="Mode de fuseau horaire" +mt3s.call_script.field.calling_timezone="Fuseau horaire fixe" +mt3s.call_script.field.retry_max_attempts="Nombre maximal de tentatives" +mt3s.call_script.field.retry_delay_minutes="Délai entre les tentatives (minutes)" +mt3s.call_script.field.retry_backoff="Espacement" +mt3s.call_script.list.published="Publié" +mt3s.call_script.list.unpublished="Non publié" +mt3s.call_script.list.owner="Propriétaire" +mt3s.call_script.list.category="Catégorie" +mt3s.call_script.list.status="Statut" +mt3s.call_script.list.modified="Modifié" +mt3s.call_script.day.mon="Lundi" +mt3s.call_script.day.tue="Mardi" +mt3s.call_script.day.wed="Mercredi" +mt3s.call_script.day.thu="Jeudi" +mt3s.call_script.day.fri="Vendredi" +mt3s.call_script.day.sat="Samedi" +mt3s.call_script.day.sun="Dimanche" +mt3s.call_script.timezone_mode.contact="Fuseau horaire du contact" +mt3s.call_script.timezone_mode.fixed="Fuseau horaire fixe" +mt3s.call_script.retry_backoff.none="Aucun espacement (délai constant)" +mt3s.call_script.retry_backoff.linear="Linéaire (délai multiplié par le numéro de tentative)" +mt3s.call_script.retry_backoff.exponential="Exponentiel (délai doublé à chaque tentative)" +mt3s.call_script.outcome.list="Résultats" +mt3s.call_script.outcome.empty="Aucun résultat pour le moment." +mt3s.call_script.outcome.add="Ajouter un résultat" +mt3s.call_script.outcome.remove="Supprimer ce résultat" +mt3s.call_script.outcome.drag="Glisser pour réordonner" +mt3s.call_script.outcome.field.label="Résultat" +mt3s.call_script.outcome.field.type="Type de données" +mt3s.call_script.outcome.options="Options" +mt3s.call_script.outcome.options.empty="Aucune option pour le moment." +mt3s.call_script.outcome.options.add="Ajouter une option" +mt3s.call_script.outcome.options.remove="Supprimer cette option" +mt3s.call_script.outcome_type.checkbox="Cases à cocher" +mt3s.call_script.outcome_type.radio="Boutons radio" +mt3s.call_script.outcome_type.free_text="Texte libre" +mt3s.call_script.outcome_type.dropdown="Liste déroulante" +mt3s.call_script.outcome_option.field.value="Valeur" +mt3s.call_script.outcome_option.field.label="Libellé" + +mt3s.call_script.section.calling_window="Plage d'appel" +mt3s.call_script.section.retry_policy="Politique de réessai" diff --git a/Translations/fr_FR/validators.ini b/Translations/fr_FR/validators.ini index f27f8c7..ed27c1a 100644 --- a/Translations/fr_FR/validators.ini +++ b/Translations/fr_FR/validators.ini @@ -38,3 +38,13 @@ mt3s.smart_links.taxonomies.error.name_characters="Le nom ne peut pas contenir l mt3s.smart_links.taxonomies.error.value_invalid="La valeur %value% est invalide. Utilisez uniquement des lettres minuscules, des chiffres, des tirets, des tirets bas et des points." mt3s.smart_links.smart_links.error.taxonomy_required="Choisissez une taxonomie UTM." mt3s.smart_links.smart_links.error.taxonomy_parameter_unknown="Le paramètre %key% ne fait pas partie de la taxonomie %name%." +mt3s.call_script.retry_attempts.range="Le nombre maximal de tentatives doit être un nombre entier de 1 à 20." +mt3s.call_script.retry_delay.range="Le délai doit être un nombre entier de minutes, 0 ou plus." +mt3s.call_script.calling_window.partial_hours="Renseignez à la fois le début et la fin de la plage d'appel." +mt3s.call_script.calling_window.to_before_from="La plage d'appel doit se terminer après son début." +mt3s.call_script.calling_window.timezone_required="Choisissez le fuseau horaire fixe de la plage d'appel." +mt3s.call_script.outcome.label.required="Un résultat a besoin d'un libellé." +mt3s.call_script.outcome.options.required="Ce type de résultat a besoin d'au moins une option." +mt3s.call_script.outcome.options.free_text_forbidden="Un résultat en texte libre ne prend pas d'option." +mt3s.call_script.outcome.options.value_required="Chaque valeur d'option est requise." +mt3s.call_script.outcome.options.duplicate_value="Les valeurs des options doivent être uniques." diff --git a/Validator/Constraints/EndDateAfterStartDate.php b/Validator/Constraints/EndDateAfterStartDate.php index d6f6b7f..9d1e38a 100644 --- a/Validator/Constraints/EndDateAfterStartDate.php +++ b/Validator/Constraints/EndDateAfterStartDate.php @@ -7,12 +7,27 @@ namespace MauticPlugin\MT3SMarketingProgramBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; /** - * Class constraint for any DateRangeInterface (Plan, Task): when both dates are set, endDate must be - * on or after startDate. + * Class constraint for any DateRangeInterface (Plan, Task, CallScript): when both dates are set, endDate + * must be on or after startDate. */ class EndDateAfterStartDate extends Constraint { - public string $message = 'mt3s.marketing_program.end_date.before_start_date'; + /** + * @param string|null $message the violation message + * @param string|null $atPath the form field the violation is attached to; entities whose end + * date is not named "endDate" (like the CallScript's publishDown) override it + */ + public function __construct( + public ?string $message = null, + public ?string $atPath = null, + ?array $groups = null, + mixed $payload = null, + ) { + parent::__construct(null, $groups, $payload); + + $this->message = $message ?? 'mt3s.marketing_program.end_date.before_start_date'; + $this->atPath = $atPath ?? 'endDate'; + } public function getTargets(): string { diff --git a/Validator/Constraints/EndDateAfterStartDateValidator.php b/Validator/Constraints/EndDateAfterStartDateValidator.php index 74d7615..858ad98 100644 --- a/Validator/Constraints/EndDateAfterStartDateValidator.php +++ b/Validator/Constraints/EndDateAfterStartDateValidator.php @@ -34,7 +34,7 @@ class EndDateAfterStartDateValidator extends ConstraintValidator } $this->context->buildViolation($constraint->message) - ->atPath('endDate') + ->atPath($constraint->atPath) ->addViolation(); } } diff --git a/Validator/Constraints/ValidCallScriptOutcomeOptions.php b/Validator/Constraints/ValidCallScriptOutcomeOptions.php new file mode 100644 index 0000000..a6a0fe2 --- /dev/null +++ b/Validator/Constraints/ValidCallScriptOutcomeOptions.php @@ -0,0 +1,27 @@ +getOptions(); + + if (!$value->hasOptions()) { + if ([] !== $options) { + $this->context->buildViolation($constraint->freeTextForbidden) + ->atPath('options') + ->addViolation(); + } + + return; + } + + if ([] === $options) { + $this->context->buildViolation($constraint->required) + ->atPath('options') + ->addViolation(); + + return; + } + + $seen = []; + foreach ($options as $index => $option) { + if ('' === $option['value']) { + $this->context->buildViolation($constraint->valueRequired) + ->atPath('options['.$index.'][value]') + ->addViolation(); + + continue; + } + + if (isset($seen[$option['value']])) { + $this->context->buildViolation($constraint->duplicateValue) + ->atPath('options['.$index.'][value]') + ->addViolation(); + + continue; + } + + $seen[$option['value']] = true; + } + } +} diff --git a/Validator/Constraints/ValidCallingWindow.php b/Validator/Constraints/ValidCallingWindow.php new file mode 100644 index 0000000..b39fe51 --- /dev/null +++ b/Validator/Constraints/ValidCallingWindow.php @@ -0,0 +1,25 @@ +getCallingFrom(); + $to = $value->getCallingTo(); + + if ((null === $from) !== (null === $to)) { + $this->context->buildViolation($constraint->partialHours) + ->atPath('callingFrom') + ->addViolation(); + + return; + } + + if (null !== $from && null !== $to && $to <= $from) { + $this->context->buildViolation($constraint->toBeforeFrom) + ->atPath('callingTo') + ->addViolation(); + } + + if ($value->getCallingTimezoneMode()->isFixed() && null === $value->getCallingTimezone()) { + $this->context->buildViolation($constraint->timezoneRequired) + ->atPath('callingTimezone') + ->addViolation(); + } + } +} diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 7c0a4e6..e7e0548 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -6,6 +6,18 @@ parameters: count: 1 path: Entity/Audience.php + - + message: '#^Property MauticPlugin\\MT3SMarketingProgramBundle\\Entity\\CallScript\:\:\$id \(int\|null\) is never assigned int so it can be removed from the property type\.$#' + identifier: property.unusedType + count: 1 + path: Entity/CallScript.php + + - + message: '#^Property MauticPlugin\\MT3SMarketingProgramBundle\\Entity\\CallScriptOutcome\:\:\$id \(int\|null\) is never assigned int so it can be removed from the property type\.$#' + identifier: property.unusedType + count: 1 + path: Entity/CallScriptOutcome.php + - message: '#^Property MauticPlugin\\MT3SMarketingProgramBundle\\Entity\\Program\:\:\$id \(int\|null\) is never assigned int so it can be removed from the property type\.$#' identifier: property.unusedType diff --git a/readme.md b/readme.md index 7fddc54..d6815ac 100644 --- a/readme.md +++ b/readme.md @@ -67,6 +67,19 @@ In short: configure (it stays a normal Mautic page on any other domain), records a hit per click — date, IP, referer, user agent — and never lets a statistics failure block the redirect. +### Call Scripts + +- **Call Scripts**, in the **Components** menu: the scripts your agents read when they call a + contact. +- A script is HTML with dynamic tokens like `{contact.first_name}`, kept as typed, and carries a + name, a description, a category, an owner, a status and a start and end date and time. +- Each script defines its **outcomes** — the list of things the agent records after the call. Each + outcome has a data type: checkboxes, radio buttons or a drop-down (with their options), or free + text. +- A **calling window** (weekdays and hours, read in the contact's timezone or in a fixed one) and a + **retry policy** (maximum attempts, delay between attempts, and whether the delay stays + constant, grows linearly or doubles) travel with the script. + ## Configuration - **Settings > Configuration > Marketing Program Settings**: the general settings — the