first delivery

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

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
/vendor/
/composer.lock
.idea/
*.log
.vscode/
.claude/
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="12" fill="#2e7d6b"/><text x="32" y="40" font-family="Arial,sans-serif" font-size="18" font-weight="bold" fill="#fff" text-anchor="middle">PLAN</text></svg>

After

Width:  |  Height:  |  Size: 249 B

+216
View File
@@ -0,0 +1,216 @@
/**
* Plan plugin scripts.
*
* - Plan form: editable, sortable rows (objectives, description items, allocation items), the selected
* item type's description, and tab error markers. Started by Mautic.planOnLoad(), which Mautic calls after
* it loads any page whose mauticContent is "plan", including pages loaded through Ajax.
* - Settings > Configuration > Plan: adding and removing item types (delegated handlers,
* because that page isn't a "plan" page).
*/
Mautic.planOnLoad = function (container) {
mQuery(container).find('.plan-collection').each(function () {
Mautic.planInitCollection(mQuery(this));
});
mQuery(container).find('.plan-tabs').each(function () {
Mautic.planInitTabs(mQuery(this), mQuery(container));
});
};
/**
* Plan tabs (detail page and form):
* - the tab last used for a plan is remembered for the browser session, and reopened when the plan's
* detail page or form loads, so that Edit, Save and Cancel keep the same tab;
* - after a failed save, the tabs whose pane has an error get an icon, and the first of them is
* opened instead.
*
* Core also reopens the last tab used on a page (Mautic.rememberActiveTabs in 12.tabs.js), on document
* ready and after every Ajax request, so the order with this code varies (full page load or Ajax). The
* chosen tab is therefore applied twice: in a deferred call, and right after core's restore (see the
* wrapper below). It stays pending for a second only, so that a later background request can't switch
* the tab under the user. The plan's tab panes have no "fade" class: with fade, two tab('show') calls
* within the 150 ms transition left two panes visible.
*/
Mautic.planInitTabs = function ($tabs, $container) {
var planId = $tabs.attr('data-plan-id');
var storageKey = planId ? 'mautic.plan.tab.' + planId : null;
var $target = null;
$tabs.find('a[data-toggle="tab"]').each(function () {
var $link = mQuery(this);
var hasError = Mautic.planPaneHasError($container.find($link.attr('href')));
$link.toggleClass('text-danger', hasError);
$link.find('.plan-tab-error').remove();
if (hasError) {
$link.append(' <i class="ri-error-warning-line text-danger plan-tab-error"></i>');
if ($target === null) {
$target = $link;
}
}
});
if ($target === null && storageKey) {
try {
var remembered = window.sessionStorage.getItem(storageKey);
if (remembered) {
var $remembered = $tabs.find('a[data-toggle="tab"][href="' + remembered + '"]');
$target = $remembered.length ? $remembered : null;
}
} catch (e) {
// sessionStorage unavailable: keep the default tab.
}
}
if (storageKey) {
$tabs.find('a[data-toggle="tab"]').on('shown.bs.tab', function (event) {
try {
window.sessionStorage.setItem(storageKey, mQuery(event.target).attr('href'));
} catch (e) {
// sessionStorage unavailable: nothing to remember.
}
});
}
if ($target !== null) {
Mautic.planPendingTab = $target;
setTimeout(Mautic.planApplyPendingTab, 0);
setTimeout(function () {
if (Mautic.planPendingTab === $target) {
Mautic.planPendingTab = null;
}
}, 1000);
}
};
Mautic.planPendingTab = null;
Mautic.planApplyPendingTab = function () {
var $target = Mautic.planPendingTab;
if ($target && mQuery.contains(document, $target[0])) {
$target.tab('show');
}
};
// Run after core's tab restore, so that the plan's choice wins (see Mautic.planInitTabs).
if (typeof Mautic.rememberActiveTabs === 'function' && !Mautic.rememberActiveTabs.planWrapped) {
(function (coreRememberActiveTabs) {
Mautic.rememberActiveTabs = function () {
var result = coreRememberActiveTabs.apply(this, arguments);
Mautic.planApplyPendingTab();
return result;
};
Mautic.rememberActiveTabs.planWrapped = true;
})(Mautic.rememberActiveTabs);
}
/**
* True when a tab pane holds a real validation error, that is an error message as rendered by Mautic's
* form_errors block: div.help-block > .alert-danger (one error) or li.alert-danger (several).
*
* The "has-error" class isn't used: Mautic's checkbox_row theme adds it to every checkbox (it tests
* "errors|length is not empty", and 0 isn't empty in Twig), so each objective's "Achieved" checkbox
* would mark the Objectives tab.
*/
Mautic.planPaneHasError = function ($pane) {
return $pane.find('.help-block .alert-danger').filter(function () {
return mQuery.trim(mQuery(this).text()) !== '';
}).length > 0;
};
/**
* An editable list of rows built from a Symfony collection:
* .plan-collection[data-prototype][data-prototype-name]
* .plan-collection-empty, .plan-collection-list > .plan-collection-row, .plan-collection-add
* in each row: .plan-collection-handle (drag), .plan-collection-remove, input.plan-row-position
*
* The hidden position of every row is rewritten to its display index after each change, so the saved
* order is the displayed order.
*/
Mautic.planInitCollection = function ($editor) {
if ($editor.data('planInitialized')) {
return;
}
$editor.data('planInitialized', true);
var $list = $editor.find('.plan-collection-list').first();
var prototypeName = new RegExp($editor.attr('data-prototype-name'), 'g');
// New rows get indexes that were never used on this page, so they can't collide with existing ones.
var nextIndex = $list.children('.plan-collection-row').length;
var refresh = function () {
var $rows = $list.children('.plan-collection-row');
$rows.each(function (index) {
mQuery(this).find('input.plan-row-position').val(index);
});
$editor.find('.plan-collection-empty').first().toggleClass('hide', $rows.length > 0);
};
$editor.on('click', '.plan-collection-add', function (event) {
event.preventDefault();
var $row = mQuery($editor.attr('data-prototype').replace(prototypeName, nextIndex++));
$list.append($row);
refresh();
$row.find('select, input[type="text"], textarea').first().trigger('focus');
});
$editor.on('click', '.plan-collection-remove', function (event) {
event.preventDefault();
mQuery(this).closest('.plan-collection-row').remove();
refresh();
});
// Typed items (description, allocation): show the selected type's description under the dropdown, and
// for description items its pictogram next to it.
$editor.on('change', 'select.plan-item-type', function () {
var $option = mQuery(this).find('option:selected');
var $row = mQuery(this).closest('.plan-collection-row');
$row.find('.plan-item-type-help').first().text($option.attr('data-description') || '');
$row.find('.plan-item-type-icon').first().attr('class', 'plan-item-type-icon ' + ($option.attr('data-icon') || ''));
});
if (typeof $list.sortable === 'function') {
$list.sortable({
items: '> .plan-collection-row',
handle: '.plan-collection-handle',
axis: 'y',
update: refresh
});
}
refresh();
};
/**
* Settings > Configuration > Plan: add and remove item types (description and allocation).
*/
(function () {
var refreshTypes = function ($editor) {
var count = $editor.find('.plan-config-type').length;
$editor.find('.plan-config-types-empty').toggleClass('hide', count > 0);
};
mQuery(document).on('click', '.plan-config-types .plan-config-type-add', function (event) {
event.preventDefault();
var $editor = mQuery(this).closest('.plan-config-types');
// Never reuse an index: count every index ever added on this page.
var index = ($editor.data('planNextIndex') || $editor.find('.plan-config-type').length + 1000);
$editor.data('planNextIndex', index + 1);
var $row = mQuery($editor.attr('data-prototype').replace(/__type__/g, index));
$editor.find('.plan-config-types-list').append($row);
refreshTypes($editor);
$row.find('input[type="text"]').first().trigger('focus');
});
// Pictogram of a description item type: preview the chosen icon.
mQuery(document).on('change', '.plan-config-types select.plan-type-icon-select', function () {
var icon = mQuery(this).find('option:selected').attr('data-icon') || '';
mQuery(this).closest('.plan-config-type').find('.plan-type-icon-preview').first().attr('class', 'plan-type-icon-preview ' + icon);
});
mQuery(document).on('click', '.plan-config-types .plan-config-type-remove', function (event) {
event.preventDefault();
var $editor = mQuery(this).closest('.plan-config-types');
mQuery(this).closest('.plan-config-type').remove();
refreshTypes($editor);
});
})();
+97
View File
@@ -0,0 +1,97 @@
<?php
declare(strict_types=1);
return [
'name' => 'Plan',
'description' => 'Plan plugin for Mautic.',
'version' => '0.8.0',
'author' => 'Experiential',
'routes' => [
'main' => [
'plan_index' => [
'path' => '/plans/{page}',
'controller' => 'MauticPlugin\PlanBundle\Controller\PlanController::indexAction',
],
// objectAction: view, new, edit, delete, batchDelete.
'plan_action' => [
'path' => '/plans/{objectAction}/{objectId}',
'controller' => 'MauticPlugin\PlanBundle\Controller\PlanController::executeAction',
],
'plan_task_index' => [
'path' => '/plan-tasks/{page}',
'controller' => 'MauticPlugin\PlanBundle\Controller\TaskController::indexAction',
],
// objectAction: new (optional ?plan=ID), edit, delete, batchDelete.
'plan_task_action' => [
'path' => '/plan-tasks/{objectAction}/{objectId}',
'controller' => 'MauticPlugin\PlanBundle\Controller\TaskController::executeAction',
],
],
],
// Top-level "Planning" menu. Future planning objects go in its children, after Plans.
'menu' => [
'main' => [
'mautic.plan.menu.root' => [
'id' => 'plan_root',
'iconClass' => 'ri-calendar-line',
'access' => ['plan:plans:viewown', 'plan:plans:viewother', 'plan:tasks:viewown', 'plan:tasks:viewother'],
'priority' => 5,
'children' => [
'mautic.plan.menu.index' => [
'id' => 'plan_index',
'route' => 'plan_index',
'access' => ['plan:plans:viewown', 'plan:plans:viewother'],
'priority' => 100,
],
'mautic.plan.task.menu.index' => [
'id' => 'plan_task_index',
'route' => 'plan_task_index',
'access' => ['plan:tasks:viewown', 'plan:tasks:viewother'],
'priority' => 90,
],
],
],
],
],
'services' => [
'integrations' => [
'mautic.plan.integration' => [
'class' => MauticPlugin\PlanBundle\Integration\PlanIntegration::class,
'tags' => [
'mautic.integration',
'mautic.basic_integration',
],
],
'mautic.plan.integration.configuration' => [
'class' => MauticPlugin\PlanBundle\Integration\Support\ConfigSupport::class,
'tags' => [
'mautic.config_integration',
],
],
],
],
// Registers "plan" as a category type (Settings > Categories), used by Plan::$category.
'categories' => [
'plan' => [
'class' => MauticPlugin\PlanBundle\Entity\Plan::class,
'label' => 'mautic.plan.category.type',
],
],
'parameters' => [
// The currency of every amount in the plugin (ISO 4217), edited in Settings > Configuration >
// Plan Settings. Read it through CurrencyProvider.
'plan_currency' => 'EUR',
// Item types, edited in Settings > Configuration > Plan Settings. Read them through ItemTypeProvider.
// Each is a list of ['key' => …, 'names' => [locale => …], 'descriptions' => [locale => …]],
// plus 'icon' => a Remix Icon class for description item types.
'plan_description_item_types' => [],
'plan_allocation_item_types' => [],
],
];
+30
View File
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
use Mautic\CoreBundle\DependencyInjection\MauticCoreExtension;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return function (ContainerConfigurator $configurator): void {
$services = $configurator->services()
->defaults()
->autowire()
->autoconfigure()
->public();
$excludes = [
'Tests',
];
$services->load('MauticPlugin\\PlanBundle\\', '../')
->exclude('../{'.implode(',', array_merge(MauticCoreExtension::DEFAULT_EXCLUDES, $excludes)).'}');
// Entity/ is excluded above; repositories must still be services for Doctrine to build them.
$services->load('MauticPlugin\\PlanBundle\\Entity\\', '../Entity/*Repository.php')
->tag(Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG);
// Lets core resolve the model with getModel('plan') / getModel('plan.plan').
$services->alias('mautic.plan.model.plan', MauticPlugin\PlanBundle\Model\PlanModel::class);
// getModel('plan.task').
$services->alias('mautic.plan.model.task', MauticPlugin\PlanBundle\Model\TaskModel::class);
};
+173
View File
@@ -0,0 +1,173 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Controller;
use Mautic\CoreBundle\Controller\AbstractStandardFormController;
use MauticPlugin\PlanBundle\Entity\Plan;
use MauticPlugin\PlanBundle\Model\TaskModel;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* List, view, create, edit and delete plans, using core's standard CRUD flow.
*
* Core derives most names from the model name "plan": model mautic.plan.model.plan, permission base
* plan:plans (from PlanModel), translation base mautic.plan, session base mautic.plan.
*/
class PlanController extends AbstractStandardFormController
{
public const ROUTE_INDEX = 'plan_index';
public const ROUTE_ACTION = 'plan_action';
protected function getModelName(): string
{
return 'plan';
}
protected function getTemplateBase(): string
{
return '@Plan/Plan';
}
/**
* Core would build mautic_plan_index; the plugin's routes use the plan_ prefix.
*/
protected function getIndexRoute(): string
{
return self::ROUTE_INDEX;
}
protected function getActionRoute(): string
{
return self::ROUTE_ACTION;
}
/**
* @param int $page
*/
public function indexAction(Request $request, $page = 1): Response
{
return $this->indexStandard($request, $page);
}
/**
* The plan detail page (tabs: Details, Description, Objectives, Allocation, Targets, Tasks).
*
* Core's viewStandard() isn't used: for users who aren't administrators it checks an
* "<entity>:export:enable" permission, which plans don't have.
*
* @param int $objectId
*/
public function viewAction(Request $request, $objectId): Response
{
$plan = $this->getModel($this->getModelName())->getEntity((int) $objectId);
if (!$plan instanceof Plan) {
return $this->notFound('mautic.plan.error.notfound');
}
if (!$this->checkActionPermission('view', $plan)) {
return $this->accessDenied();
}
$base = $this->getPermissionBase();
$permissions = $this->security->isGranted(
[
$base.':create',
$base.':editown',
$base.':editother',
$base.':deleteown',
$base.':deleteother',
],
'RETURN_ARRAY',
null,
true
);
$taskPermissions = $this->security->isGranted(
[
'plan:tasks:create',
'plan:tasks:editown',
'plan:tasks:editother',
],
'RETURN_ARRAY',
null,
true
);
return $this->delegateView([
'viewParameters' => [
'item' => $plan,
'permissions' => $permissions,
'taskTree' => $this->getTaskModel()->getTaskTree($plan),
'taskPermissions' => $taskPermissions,
// Core's page_actions helper would otherwise build mautic_plan_* route names.
'indexRoute' => self::ROUTE_INDEX,
'actionRoute' => self::ROUTE_ACTION,
'tmpl' => $request->isXmlHttpRequest() ? $request->get('tmpl', 'details') : 'details',
],
'contentTemplate' => $this->getTemplateName('details.html.twig'),
'passthroughVars' => [
'activeLink' => '#plan_index',
'mauticContent' => $this->getJsLoadMethodPrefix(),
'route' => $this->generateUrl(self::ROUTE_ACTION, ['objectAction' => 'view', 'objectId' => $plan->getId()]),
],
]);
}
/**
* Adds the plan's task tree to the form, for the read-only Tasks tab.
*
* @param array<string, mixed> $args
* @param string $action
*
* @return array<string, mixed>
*/
protected function getViewArguments(array $args, $action): array
{
$plan = $args['viewParameters']['entity'] ?? null;
if (in_array($action, ['new', 'edit'], true) && $plan instanceof Plan && null !== $plan->getId()) {
$args['viewParameters']['taskTree'] = $this->getTaskModel()->getTaskTree($plan);
}
return parent::getViewArguments($args, $action);
}
private function getTaskModel(): TaskModel
{
$model = $this->getModel('plan.task');
\assert($model instanceof TaskModel);
return $model;
}
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);
}
}
+186
View File
@@ -0,0 +1,186 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Controller;
use Mautic\CoreBundle\Controller\AbstractStandardFormController;
use MauticPlugin\PlanBundle\Entity\Plan;
use MauticPlugin\PlanBundle\Entity\Task;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* List, create, edit and delete tasks (Planning > Tasks), using core's standard CRUD flow.
*
* Model plan.task (mautic.plan.model.task), permission base plan:tasks, translation base mautic.plan.task.
*
* Where the user lands after Save or Cancel depends on where the task form was opened from:
* - from Planning > Tasks: back to the task list (core's default);
* - from a plan's Tasks tab (links with ?returnTo=plan): back to that plan.
* The origin is kept in the session when the form is opened, because the form posts to a URL
* without the query string.
*/
class TaskController extends AbstractStandardFormController
{
public const ROUTE_INDEX = 'plan_task_index';
public const ROUTE_ACTION = 'plan_task_action';
/**
* Value of the returnTo query parameter that sends the user back to the plan.
*/
public const RETURN_TO_PLAN = 'plan';
private const SESSION_RETURN_PLAN = 'mautic.plan.task.return_plan.';
/**
* Plan to preselect on a new task (from ?plan=ID, used by the plan's "Add task" button).
*/
private ?int $preselectedPlanId = null;
/**
* The task saved during this request, if any.
*/
private ?Task $savedTask = null;
/**
* Plan to go back to after Save or Cancel, or null for the task list.
*/
private ?int $returnPlanId = null;
protected function getModelName(): string
{
return 'plan.task';
}
protected function getTemplateBase(): string
{
return '@Plan/Task';
}
protected function getIndexRoute(): string
{
return self::ROUTE_INDEX;
}
protected function getActionRoute(): string
{
return self::ROUTE_ACTION;
}
protected function getJsLoadMethodPrefix(): string
{
return 'planTask';
}
/**
* @param int $page
*/
public function indexAction(Request $request, $page = 1): Response
{
return $this->indexStandard($request, $page);
}
public function newAction(Request $request): Response
{
$planId = $request->query->getInt('plan');
$this->preselectedPlanId = $planId > 0 ? $planId : null;
$this->returnPlanId = $this->resolveReturnPlan($request, 'new', $this->preselectedPlanId);
return $this->newStandard($request);
}
/**
* @param int $objectId
* @param bool $ignorePost
*/
public function editAction(Request $request, $objectId, $ignorePost = false): Response
{
$task = $this->getModel($this->getModelName())->getEntity((int) $objectId);
$planId = $task instanceof Task ? $task->getPlan()?->getId() : null;
$this->returnPlanId = $this->resolveReturnPlan($request, (string) (int) $objectId, $planId);
return $this->editStandard($request, $objectId, $ignorePost);
}
/**
* When the form is opened (GET), records whether it came from a plan (?returnTo=plan); when it is
* submitted (POST), reads that record back. Opening the same form from the task list clears it.
*/
private function resolveReturnPlan(Request $request, string $formKey, ?int $planId): ?int
{
$session = $request->getSession();
$key = self::SESSION_RETURN_PLAN.$formKey;
if (!$request->isMethod('POST')) {
$fromPlan = self::RETURN_TO_PLAN === $request->query->get('returnTo') && null !== $planId;
$session->set($key, $fromPlan ? $planId : null);
}
$value = $session->get($key);
return is_int($value) ? $value : null;
}
/**
* @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);
}
/**
* @return object|null
*/
protected function getFormEntity($action, &$objectId = null, &$isClone = false)
{
$entity = parent::getFormEntity($action, $objectId, $isClone);
if ('new' === $action && $entity instanceof Task && null === $entity->getPlan() && null !== $this->preselectedPlanId) {
$plan = $this->getModel('plan')->getEntity($this->preselectedPlanId);
if ($plan instanceof Plan) {
$entity->setPlan($plan);
}
}
return $entity;
}
protected function afterEntitySave($entity, Form $form, $action, $pass = null)
{
if ($entity instanceof Task) {
$this->savedTask = $entity;
}
return parent::afterEntitySave($entity, $form, $action, $pass);
}
/**
* After Save or Cancel (not Apply) on a form opened from a plan, go back to that plan. If the task
* was moved to another plan, go to its new plan. Otherwise keep core's default: the task list.
*
* @param array<string, mixed> $args
*
* @return array<string, mixed>
*/
protected function getPostActionRedirectArguments(array $args, $action): array
{
if (in_array($action, ['new', 'edit'], true) && null !== $this->returnPlanId) {
$planId = $this->savedTask?->getPlan()?->getId() ?? $this->returnPlanId;
$args['returnUrl'] = $this->generateUrl(PlanController::ROUTE_ACTION, ['objectAction' => 'view', 'objectId' => $planId]);
$args['contentTemplate'] = PlanController::class.'::viewAction';
$args['viewParameters'] = ['objectId' => $planId];
$args['passthroughVars'] = array_merge($args['passthroughVars'] ?? [], ['mauticContent' => 'plan']);
}
return parent::getPostActionRedirectArguments($args, $action);
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
/**
* Loads Config/services.php (Symfony finds this class by naming convention).
*/
final class PlanExtension extends Extension
{
/**
* @param mixed[] $configs
*/
public function load(array $configs, ContainerBuilder $container): void
{
$loader = new PhpFileLoader($container, new FileLocator(__DIR__.'/../Config'));
$loader->load('services.php');
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
/**
* For repositories of typed plan items (description items, allocation items).
*/
trait CountsItemsByTypeTrait
{
/**
* Number of items per type key, for the types that are in use.
*
* @return array<string, int>
*/
public function countByType(): array
{
$alias = $this->getTableAlias();
$rows = $this->createQueryBuilder($alias)
->select($alias.'.type AS type, COUNT('.$alias.'.id) AS total')
->groupBy($alias.'.type')
->getQuery()
->getArrayResult();
$counts = [];
foreach ($rows as $row) {
$counts[(string) $row['type']] = (int) $row['total'];
}
return $counts;
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
/**
* An object with an optional start and end date. Checked by the EndDateAfterStartDate constraint.
*/
interface DateRangeInterface
{
public function getStartDate(): ?\DateTime;
public function getEndDate(): ?\DateTime;
}
+514
View File
@@ -0,0 +1,514 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata;
use Mautic\CategoryBundle\Entity\Category;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
use Mautic\CoreBundle\Entity\FormEntity;
use Mautic\UserBundle\Entity\User;
use MauticPlugin\PlanBundle\Validator\Constraints\EndDateAfterStartDate;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Constraints\Valid;
use Symfony\Component\Validator\Mapping\ClassMetadata;
class Plan extends FormEntity implements DateRangeInterface
{
public const TABLE_NAME = 'plans';
public const VERSION_MIN = 1;
public const VERSION_MAX = 99;
private ?int $id = null;
/**
* Plan version, 1 to 99. Edited by hand; not related to Doctrine optimistic locking.
*/
private ?int $version = self::VERSION_MIN;
/**
* @var Collection<int, PlanObjective>
*/
private Collection $objectives;
/**
* The content of the Description tab. Each item has a type set up by the admin in
* Settings > Configuration > Plan.
*
* @var Collection<int, PlanDescriptionItem>
*/
private Collection $descriptionItems;
/**
* The cost lines of the Allocation tab. Each item has a type set up by the admin in
* Settings > Configuration > Plan.
*
* @var Collection<int, PlanAllocationItem>
*/
private Collection $allocationItems;
/**
* Tasks are managed on their own pages (TaskController). Read-only from the plan: deleting a plan
* deletes its tasks through the database (ON DELETE CASCADE).
*
* @var Collection<int, Task>
*/
private Collection $tasks;
private ?string $name = null;
private PlanStatus $status = PlanStatus::Draft;
/**
* Required in the form. The column is nullable only so that deleting the user doesn't delete the plan (SET NULL).
*/
private ?User $owner = null;
private ?\DateTime $startDate = null;
private ?\DateTime $endDate = null;
private ?\DateTime $completedAt = null;
/**
* DECIMAL(12,2), in the general currency (CurrencyProvider). Doctrine returns decimals as strings to
* keep precision.
*/
private ?string $budgetPlanned = null;
private ?Category $category = null;
public function __construct()
{
$this->objectives = new ArrayCollection();
$this->descriptionItems = new ArrayCollection();
$this->allocationItems = new ArrayCollection();
$this->tasks = new ArrayCollection();
}
public function __clone()
{
$this->id = null;
$this->completedAt = null;
$this->tasks = new ArrayCollection();
// A clone gets its own copies of the objectives, description items and allocation items.
$objectives = $this->objectives;
$this->objectives = new ArrayCollection();
foreach ($objectives as $objective) {
$this->addObjective(clone $objective);
}
$descriptionItems = $this->descriptionItems;
$this->descriptionItems = new ArrayCollection();
foreach ($descriptionItems as $descriptionItem) {
$this->addDescriptionItem(clone $descriptionItem);
}
$allocationItems = $this->allocationItems;
$this->allocationItems = new ArrayCollection();
foreach ($allocationItems as $allocationItem) {
$this->addAllocationItem(clone $allocationItem);
}
parent::__clone();
}
public static function loadMetadata(OrmClassMetadata $metadata): void
{
$builder = new ClassMetadataBuilder($metadata);
$builder->setTable(self::TABLE_NAME)
->setCustomRepositoryClass(PlanRepository::class)
->addIndex(['status'], 'plan_status');
// id and name; no description column (replaced by description items).
$builder->addIdColumns('name', false);
// Mapped on the raw metadata: ClassMetadataBuilder::addField() forces every string to VARCHAR(191).
$metadata->mapField([
'fieldName' => 'status',
'type' => Types::STRING,
'length' => 20,
'enumType' => PlanStatus::class,
]);
$builder->createManyToOne('owner', User::class)
->addJoinColumn('owner_id', 'id', true, false, 'SET NULL')
->build();
$builder->addNamedField('startDate', Types::DATETIME_MUTABLE, 'start_date', true);
$builder->addNamedField('endDate', Types::DATETIME_MUTABLE, 'end_date', true);
$builder->addNamedField('completedAt', Types::DATETIME_MUTABLE, 'completed_at', true);
$builder->createField('budgetPlanned', Types::DECIMAL)
->columnName('budget_planned')
->precision(12)
->scale(2)
->nullable()
->build();
// ManyToOne Category, nullable, onDelete SET NULL.
$builder->addCategory();
$builder->createField('version', Types::SMALLINT)
->option('unsigned', true)
->option('default', self::VERSION_MIN)
->build();
$builder->createOneToMany('objectives', PlanObjective::class)
->mappedBy('plan')
->cascadePersist()
->cascadeRemove()
->orphanRemoval()
->setOrderBy(['position' => 'ASC'])
->fetchExtraLazy()
->build();
$builder->createOneToMany('descriptionItems', PlanDescriptionItem::class)
->mappedBy('plan')
->cascadePersist()
->cascadeRemove()
->orphanRemoval()
->setOrderBy(['position' => 'ASC'])
->fetchExtraLazy()
->build();
$builder->createOneToMany('allocationItems', PlanAllocationItem::class)
->mappedBy('plan')
->cascadePersist()
->cascadeRemove()
->orphanRemoval()
->setOrderBy(['position' => 'ASC'])
->fetchExtraLazy()
->build();
$builder->createOneToMany('tasks', Task::class)
->mappedBy('plan')
->setOrderBy(['name' => 'ASC'])
->fetchExtraLazy()
->build();
}
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('version', new NotNull(message: 'mautic.plan.version.range'));
$metadata->addPropertyConstraint('version', new Range(
notInRangeMessage: 'mautic.plan.version.range',
min: self::VERSION_MIN,
max: self::VERSION_MAX,
));
$metadata->addPropertyConstraint('objectives', new Valid());
$metadata->addPropertyConstraint('descriptionItems', new Valid());
$metadata->addPropertyConstraint('allocationItems', new Valid());
$metadata->addPropertyConstraint('name', new NotBlank(message: 'mautic.core.name.required'));
$metadata->addPropertyConstraint('owner', new NotBlank(message: 'mautic.plan.owner.required'));
$metadata->addConstraint(new EndDateAfterStartDate());
}
public function getId(): ?int
{
return $this->id;
}
public function getVersion(): ?int
{
return $this->version;
}
/**
* Accepts null so that an empty form field reaches validation (NotNull) instead of failing here.
*/
public function setVersion(?int $version): static
{
$this->isChanged('version', $version);
$this->version = $version;
return $this;
}
/**
* The objectives sorted by position, as a new collection (Doctrine itself reads the property).
*
* Sorted here, not only by the mapping's orderBy: after a reorder, positions change in memory while the
* loaded collection keeps its old order, and the page shown right after saving uses that collection.
*
* @return Collection<int, PlanObjective>
*/
public function getObjectives(): Collection
{
return self::sortedByPosition($this->objectives);
}
/**
* @return Collection<int, Task>
*/
public function getTasks(): Collection
{
return $this->tasks;
}
public function addObjective(PlanObjective $objective): static
{
if (!$this->objectives->contains($objective)) {
$objective->setPlan($this);
$this->objectives->add($objective);
}
return $this;
}
/**
* Removing an objective from the plan deletes it (orphanRemoval).
*/
public function removeObjective(PlanObjective $objective): static
{
$this->objectives->removeElement($objective);
return $this;
}
/**
* The description items sorted by position, as a new collection; see getObjectives().
*
* @return Collection<int, PlanDescriptionItem>
*/
public function getDescriptionItems(): Collection
{
return self::sortedByPosition($this->descriptionItems);
}
/**
* The allocation items sorted by position, as a new collection; see getObjectives().
*
* @return Collection<int, PlanAllocationItem>
*/
public function getAllocationItems(): Collection
{
return self::sortedByPosition($this->allocationItems);
}
public function addAllocationItem(PlanAllocationItem $allocationItem): static
{
if (!$this->allocationItems->contains($allocationItem)) {
$allocationItem->setPlan($this);
$this->allocationItems->add($allocationItem);
}
return $this;
}
/**
* Removing an allocation item from the plan deletes it (orphanRemoval).
*/
public function removeAllocationItem(PlanAllocationItem $allocationItem): static
{
$this->allocationItems->removeElement($allocationItem);
return $this;
}
/**
* Total planned and real costs of the allocation items, in the general currency. Each total is a
* string with 2 decimals, or null when no item has that cost.
*
* @return array{planned: ?string, real: ?string}
*/
public function getAllocationTotals(): array
{
// Summed in cents, as integers, to avoid floating-point drift.
$cents = ['planned' => null, 'real' => null];
foreach ($this->allocationItems as $item) {
foreach (['planned' => $item->getPlannedCost(), 'real' => $item->getRealCost()] as $kind => $cost) {
if (null === $cost || '' === $cost) {
continue;
}
$cents[$kind] = ($cents[$kind] ?? 0) + (int) round(((float) $cost) * 100);
}
}
return [
'planned' => null === $cents['planned'] ? null : number_format($cents['planned'] / 100, 2, '.', ''),
'real' => null === $cents['real'] ? null : number_format($cents['real'] / 100, 2, '.', ''),
];
}
/**
* @template T of PlanObjective|PlanDescriptionItem|PlanAllocationItem
*
* @param Collection<int, T> $collection
*
* @return Collection<int, T>
*/
private static function sortedByPosition(Collection $collection): Collection
{
$rows = $collection->toArray();
usort($rows, fn ($a, $b): int => $a->getPosition() <=> $b->getPosition());
return new ArrayCollection($rows);
}
public function addDescriptionItem(PlanDescriptionItem $descriptionItem): static
{
if (!$this->descriptionItems->contains($descriptionItem)) {
$descriptionItem->setPlan($this);
$this->descriptionItems->add($descriptionItem);
}
return $this;
}
/**
* Removing a description item from the plan deletes it (orphanRemoval).
*/
public function removeDescriptionItem(PlanDescriptionItem $descriptionItem): static
{
$this->descriptionItems->removeElement($descriptionItem);
return $this;
}
/**
* Renumbers objective, description item and allocation item positions 0..n-1 following their current positions,
* so that the order stays contiguous after rows are added, removed or moved.
*/
public function normalizePositions(): void
{
foreach ([$this->objectives, $this->descriptionItems, $this->allocationItems] as $collection) {
$rows = $collection->toArray();
usort($rows, fn ($a, $b): int => $a->getPosition() <=> $b->getPosition());
foreach ($rows as $index => $row) {
$row->setPosition($index);
}
}
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): static
{
$this->isChanged('name', $name);
$this->name = $name;
return $this;
}
public function getStatus(): PlanStatus
{
return $this->status;
}
/**
* Sets completedAt when the plan moves to "completed" from another status,
* and clears it when the plan leaves "completed".
*/
public function setStatus(PlanStatus $status): static
{
if ($status === $this->status) {
return $this;
}
// isChanged() can't log enums (they aren't stringable), so log the backing values.
$this->addChange('status', [$this->status->value, $status->value]);
if (PlanStatus::Completed === $status) {
$this->setCompletedAt(new \DateTime());
} elseif (PlanStatus::Completed === $this->status) {
$this->setCompletedAt(null);
}
$this->status = $status;
return $this;
}
public function getOwner(): ?User
{
return $this->owner;
}
public function setOwner(?User $owner): static
{
$this->isChanged('owner', $owner);
$this->owner = $owner;
return $this;
}
public function getStartDate(): ?\DateTime
{
return $this->startDate;
}
public function setStartDate(?\DateTime $startDate): static
{
$this->isChanged('startDate', $startDate);
$this->startDate = $startDate;
return $this;
}
public function getEndDate(): ?\DateTime
{
return $this->endDate;
}
public function setEndDate(?\DateTime $endDate): static
{
$this->isChanged('endDate', $endDate);
$this->endDate = $endDate;
return $this;
}
public function getCompletedAt(): ?\DateTime
{
return $this->completedAt;
}
public function setCompletedAt(?\DateTime $completedAt): static
{
$this->isChanged('completedAt', $completedAt);
$this->completedAt = $completedAt;
return $this;
}
public function getBudgetPlanned(): ?string
{
return $this->budgetPlanned;
}
public function setBudgetPlanned(?string $budgetPlanned): static
{
$this->isChanged('budgetPlanned', $budgetPlanned);
$this->budgetPlanned = $budgetPlanned;
return $this;
}
public function getCategory(): ?Category
{
return $this->category;
}
public function setCategory(?Category $category): static
{
$this->isChanged('category', $category);
$this->category = $category;
return $this;
}
}
+192
View File
@@ -0,0 +1,192 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* One item of a plan's Allocation tab: a typed cost line with a planned and a real cost, both in the
* general currency (CurrencyProvider). Plan::$allocationItems owns the lifecycle: items are saved and
* deleted with their plan, and are ordered by position.
*
* The type is the key of an allocation item type set up in Settings > Configuration > Plan Settings
* (parameter plan_allocation_item_types); see ItemTypeProvider.
*/
class PlanAllocationItem
{
public const TABLE_NAME = 'plan_allocation_items';
public const TYPE_MAX_LENGTH = 64;
private ?int $id = null;
private ?Plan $plan = null;
private ?string $type = null;
private ?string $name = null;
private ?string $description = null;
/**
* DECIMAL(12,2), as a string (Doctrine keeps decimals as strings for precision).
*/
private ?string $plannedCost = null;
private ?string $realCost = null;
/**
* Display order within the plan, from 0. Set by drag and drop in the form.
*/
private int $position = 0;
public function __clone()
{
$this->id = null;
$this->plan = null;
}
public static function loadMetadata(OrmClassMetadata $metadata): void
{
$builder = new ClassMetadataBuilder($metadata);
$builder->setTable(self::TABLE_NAME)
->setCustomRepositoryClass(PlanAllocationItemRepository::class);
$builder->addId();
$builder->createManyToOne('plan', Plan::class)
->inversedBy('allocationItems')
->addJoinColumn('plan_id', 'id', false, false, 'CASCADE')
->build();
$builder->createField('type', Types::STRING)
->length(self::TYPE_MAX_LENGTH)
->build();
$builder->createField('name', Types::STRING)
->length(255)
->nullable()
->build();
$builder->createField('description', Types::TEXT)
->nullable()
->build();
foreach (['planned', 'real'] as $kind) {
$builder->createField($kind.'Cost', Types::DECIMAL)
->columnName($kind.'_cost')
->precision(12)
->scale(2)
->nullable()
->build();
}
$builder->createField('position', Types::INTEGER)
->option('default', 0)
->build();
}
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('type', new NotBlank(message: 'mautic.plan.allocation_item.type.required'));
$metadata->addPropertyConstraint('type', new Length(max: self::TYPE_MAX_LENGTH));
$metadata->addPropertyConstraint('name', new Length(max: 255));
}
public function getId(): ?int
{
return $this->id;
}
public function getPlan(): ?Plan
{
return $this->plan;
}
public function setPlan(?Plan $plan): static
{
$this->plan = $plan;
return $this;
}
public function getType(): ?string
{
return $this->type;
}
public function setType(?string $type): static
{
$this->type = $type;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): static
{
$this->name = $name;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): static
{
$this->description = $description;
return $this;
}
public function getPlannedCost(): ?string
{
return $this->plannedCost;
}
public function setPlannedCost(?string $plannedCost): static
{
$this->plannedCost = $plannedCost;
return $this;
}
public function getRealCost(): ?string
{
return $this->realCost;
}
public function setRealCost(?string $realCost): static
{
$this->realCost = $realCost;
return $this;
}
public function getPosition(): int
{
return $this->position;
}
public function setPosition(?int $position): static
{
$this->position = $position ?? 0;
return $this;
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Mautic\CoreBundle\Entity\CommonRepository;
/**
* @extends CommonRepository<PlanAllocationItem>
*/
class PlanAllocationItemRepository extends CommonRepository
{
use CountsItemsByTypeTrait;
public function getTableAlias(): string
{
return 'pai';
}
}
+131
View File
@@ -0,0 +1,131 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* One item of a plan's Description tab. Plan::$descriptionItems owns the lifecycle: items are saved and
* deleted with their plan, and are ordered by position.
*
* The type is the key of a type set up in Settings > Configuration > Plan (parameter
* plan_description_item_types); see ItemTypeProvider (kind "description") for its name and description.
*/
class PlanDescriptionItem
{
public const TABLE_NAME = 'plan_description_items';
public const TYPE_MAX_LENGTH = 64;
private ?int $id = null;
private ?Plan $plan = null;
private ?string $type = null;
private ?string $description = null;
/**
* Display order within the plan, from 0. Set by drag and drop in the form.
*/
private int $position = 0;
public function __clone()
{
$this->id = null;
$this->plan = null;
}
public static function loadMetadata(OrmClassMetadata $metadata): void
{
$builder = new ClassMetadataBuilder($metadata);
$builder->setTable(self::TABLE_NAME)
->setCustomRepositoryClass(PlanDescriptionItemRepository::class);
$builder->addId();
$builder->createManyToOne('plan', Plan::class)
->inversedBy('descriptionItems')
->addJoinColumn('plan_id', 'id', false, false, 'CASCADE')
->build();
$builder->createField('type', Types::STRING)
->length(self::TYPE_MAX_LENGTH)
->build();
$builder->createField('description', Types::TEXT)
->nullable()
->build();
$builder->createField('position', Types::INTEGER)
->option('default', 0)
->build();
}
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('type', new NotBlank(message: 'mautic.plan.description_item.type.required'));
$metadata->addPropertyConstraint('type', new Length(max: self::TYPE_MAX_LENGTH));
}
public function getId(): ?int
{
return $this->id;
}
public function getPlan(): ?Plan
{
return $this->plan;
}
public function setPlan(?Plan $plan): static
{
$this->plan = $plan;
return $this;
}
public function getType(): ?string
{
return $this->type;
}
public function setType(?string $type): static
{
$this->type = $type;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): static
{
$this->description = $description;
return $this;
}
public function getPosition(): int
{
return $this->position;
}
public function setPosition(?int $position): static
{
$this->position = $position ?? 0;
return $this;
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Mautic\CoreBundle\Entity\CommonRepository;
/**
* @extends CommonRepository<PlanDescriptionItem>
*/
class PlanDescriptionItemRepository extends CommonRepository
{
use CountsItemsByTypeTrait;
public function getTableAlias(): string
{
return 'pdi';
}
}
+153
View File
@@ -0,0 +1,153 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* An objective of a plan. Plan::$objectives owns the lifecycle: objectives are saved and deleted with
* their plan, and are ordered by position.
*/
class PlanObjective
{
public const TABLE_NAME = 'plan_objectives';
private ?int $id = null;
private ?Plan $plan = null;
private ?string $title = null;
private ?string $description = null;
/**
* Display order within the plan, from 0. Set by drag and drop in the form.
*/
private int $position = 0;
/**
* Toggled by hand for now.
*/
private bool $isAchieved = false;
public function __clone()
{
$this->id = null;
$this->plan = null;
}
public static function loadMetadata(OrmClassMetadata $metadata): void
{
$builder = new ClassMetadataBuilder($metadata);
$builder->setTable(self::TABLE_NAME)
->setCustomRepositoryClass(PlanObjectiveRepository::class);
$builder->addId();
$builder->createManyToOne('plan', Plan::class)
->inversedBy('objectives')
->addJoinColumn('plan_id', 'id', false, false, 'CASCADE')
->build();
$builder->createField('title', Types::STRING)
->length(255)
->build();
$builder->createField('description', Types::TEXT)
->nullable()
->build();
$builder->createField('position', Types::INTEGER)
->option('default', 0)
->build();
$builder->createField('isAchieved', Types::BOOLEAN)
->columnName('is_achieved')
->option('default', false)
->build();
}
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('title', new NotBlank(message: 'mautic.plan.objective.title.required'));
$metadata->addPropertyConstraint('title', new Length(max: 255));
}
public function getId(): ?int
{
return $this->id;
}
public function getPlan(): ?Plan
{
return $this->plan;
}
public function setPlan(?Plan $plan): static
{
$this->plan = $plan;
return $this;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(?string $title): static
{
$this->title = $title;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): static
{
$this->description = $description;
return $this;
}
public function getPosition(): int
{
return $this->position;
}
public function setPosition(?int $position): static
{
$this->position = $position ?? 0;
return $this;
}
public function isAchieved(): bool
{
return $this->isAchieved;
}
public function getIsAchieved(): bool
{
return $this->isAchieved;
}
public function setIsAchieved(bool $isAchieved): static
{
$this->isAchieved = $isAchieved;
return $this;
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Mautic\CoreBundle\Entity\CommonRepository;
/**
* @extends CommonRepository<PlanObjective>
*/
class PlanObjectiveRepository extends CommonRepository
{
public function getTableAlias(): string
{
return 'po';
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Mautic\CoreBundle\Entity\CommonRepository;
/**
* @extends CommonRepository<Plan>
*/
class PlanRepository extends CommonRepository
{
public function getTableAlias(): string
{
return 'p';
}
/**
* Loads the owner and category with the plans, so that the list doesn't query them one by one.
*
* @param array<string, mixed> $args
*/
public function getEntities(array $args = [])
{
$alias = $this->getTableAlias();
$args['qb'] = $this->createQueryBuilder($alias)
->select($alias, 'o', 'c')
->leftJoin($alias.'.owner', 'o')
->leftJoin($alias.'.category', 'c');
return parent::getEntities($args);
}
/**
* The list's search box matches the name.
*
* @return array<int, mixed>
*/
protected function addCatchAllWhereClause($q, $filter): array
{
return $this->addStandardCatchAllWhereClause($q, $filter, [
$this->getTableAlias().'.name',
]);
}
/**
* @return array<array{0: string, 1: string}>
*/
protected function getDefaultOrder(): array
{
return [
[$this->getTableAlias().'.name', 'ASC'],
];
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
enum PlanStatus: string
{
case Draft = 'draft';
case Planned = 'planned';
case Active = 'active';
case Paused = 'paused';
case Completed = 'completed';
case Archived = 'archived';
public function getLabelKey(): string
{
return 'mautic.plan.status.'.$this->value;
}
}
+251
View File
@@ -0,0 +1,251 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
use Mautic\CoreBundle\Entity\FormEntity;
use MauticPlugin\PlanBundle\Validator\Constraints\EndDateAfterStartDate;
use MauticPlugin\PlanBundle\Validator\Constraints\ValidTaskParent;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* A task of a plan. Every task belongs to exactly one plan, and may have a parent task in the same plan.
*
* Database rules: deleting the plan deletes its tasks (ON DELETE CASCADE); deleting a task makes its
* sub-tasks top-level (parent ON DELETE SET NULL).
*/
class Task extends FormEntity implements DateRangeInterface
{
public const TABLE_NAME = 'plan_tasks';
private ?int $id = null;
private ?Plan $plan = null;
private ?string $name = null;
private ?string $description = null;
private ?Task $parent = null;
private ?\DateTime $startDate = null;
private ?\DateTime $endDate = null;
private TaskStatus $status = TaskStatus::New;
/**
* @var Collection<int, Task>
*/
private Collection $children;
public function __construct()
{
$this->children = new ArrayCollection();
}
public function __clone()
{
$this->id = null;
$this->children = new ArrayCollection();
parent::__clone();
}
public static function loadMetadata(OrmClassMetadata $metadata): void
{
$builder = new ClassMetadataBuilder($metadata);
$builder->setTable(self::TABLE_NAME)
->setCustomRepositoryClass(TaskRepository::class);
$builder->addId();
$builder->createManyToOne('plan', Plan::class)
->inversedBy('tasks')
->addJoinColumn('plan_id', 'id', false, false, 'CASCADE')
->build();
$builder->createField('name', Types::STRING)
->length(255)
->build();
$builder->createField('description', Types::TEXT)
->nullable()
->build();
$builder->createManyToOne('parent', self::class)
->inversedBy('children')
->addJoinColumn('parent_id', 'id', true, false, 'SET NULL')
->build();
$builder->createOneToMany('children', self::class)
->mappedBy('parent')
->setOrderBy(['name' => 'ASC'])
->fetchExtraLazy()
->build();
$builder->addNamedField('startDate', Types::DATETIME_MUTABLE, 'start_date', true);
$builder->addNamedField('endDate', Types::DATETIME_MUTABLE, 'end_date', true);
// Mapped on the raw metadata: ClassMetadataBuilder::addField() forces every string to VARCHAR(191).
$metadata->mapField([
'fieldName' => 'status',
'type' => Types::STRING,
'length' => 20,
'enumType' => TaskStatus::class,
'options' => ['default' => TaskStatus::New->value],
]);
$builder->addIndex(['status'], 'plan_task_status');
}
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('name', new NotBlank(message: 'mautic.core.name.required'));
$metadata->addPropertyConstraint('name', new Length(max: 255));
$metadata->addPropertyConstraint('plan', new NotBlank(message: 'mautic.plan.task.plan.required'));
$metadata->addConstraint(new ValidTaskParent());
$metadata->addConstraint(new EndDateAfterStartDate());
}
public function getId(): ?int
{
return $this->id;
}
public function getPlan(): ?Plan
{
return $this->plan;
}
public function setPlan(?Plan $plan): static
{
$this->isChanged('plan', $plan);
$this->plan = $plan;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): static
{
$this->isChanged('name', $name);
$this->name = $name;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): static
{
$this->isChanged('description', $description);
$this->description = $description;
return $this;
}
public function getParent(): ?Task
{
return $this->parent;
}
public function setParent(?Task $parent): static
{
$this->isChanged('parent', $parent);
$this->parent = $parent;
return $this;
}
public function getStartDate(): ?\DateTime
{
return $this->startDate;
}
public function setStartDate(?\DateTime $startDate): static
{
$this->isChanged('startDate', $startDate);
$this->startDate = $startDate;
return $this;
}
public function getEndDate(): ?\DateTime
{
return $this->endDate;
}
public function setEndDate(?\DateTime $endDate): static
{
$this->isChanged('endDate', $endDate);
$this->endDate = $endDate;
return $this;
}
public function getStatus(): TaskStatus
{
return $this->status;
}
public function setStatus(TaskStatus $status): static
{
if ($status !== $this->status) {
// isChanged() can't log enums (they aren't stringable), so log the backing values.
$this->addChange('status', [$this->status->value, $status->value]);
$this->status = $status;
}
return $this;
}
/**
* @return Collection<int, Task>
*/
public function getChildren(): Collection
{
return $this->children;
}
/**
* True when $task is this task or one of its ancestors.
*/
public function hasAncestorOrSelf(Task $task): bool
{
$seen = [];
$current = $this;
while (null !== $current) {
if ($current === $task || (null !== $task->getId() && $current->getId() === $task->getId())) {
return true;
}
// Guard against a cycle that is already stored.
$key = null !== $current->getId() ? 'id'.$current->getId() : spl_object_id($current);
if (isset($seen[$key])) {
return false;
}
$seen[$key] = true;
$current = $current->getParent();
}
return false;
}
}
+74
View File
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
use Mautic\CoreBundle\Entity\CommonRepository;
/**
* @extends CommonRepository<Task>
*/
class TaskRepository extends CommonRepository
{
public function getTableAlias(): string
{
return 't';
}
/**
* Loads the plan and the parent with the tasks, so that the list doesn't query them one by one.
*
* @param array<string, mixed> $args
*/
public function getEntities(array $args = [])
{
$alias = $this->getTableAlias();
$args['qb'] = $this->createQueryBuilder($alias)
->select($alias, 'pl', 'pa')
->leftJoin($alias.'.plan', 'pl')
->leftJoin($alias.'.parent', 'pa');
return parent::getEntities($args);
}
/**
* All tasks of a plan, ordered by name.
*
* @return Task[]
*/
public function findByPlan(Plan $plan): array
{
return $this->createQueryBuilder('t')
->where('t.plan = :plan')
->setParameter('plan', $plan)
->orderBy('t.name', 'ASC')
->addOrderBy('t.id', 'ASC')
->getQuery()
->getResult();
}
/**
* The list's search box matches the name and the description.
*
* @return array<int, mixed>
*/
protected function addCatchAllWhereClause($q, $filter): array
{
return $this->addStandardCatchAllWhereClause($q, $filter, [
$this->getTableAlias().'.name',
$this->getTableAlias().'.description',
]);
}
/**
* @return array<array{0: string, 1: string}>
*/
protected function getDefaultOrder(): array
{
return [
[$this->getTableAlias().'.name', 'ASC'],
];
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Entity;
/**
* Task status. The order of the cases is the order of the dropdown on the task form.
*/
enum TaskStatus: string
{
case New = 'new';
case Todo = 'todo';
case InProgress = 'in_progress';
case Done = 'done';
public function getLabelKey(): string
{
return 'mautic.plan.task.status.'.$this->value;
}
/**
* Bootstrap label class for the status badge in lists.
*/
public function getLabelClass(): string
{
return match ($this) {
self::New => 'label-default',
self::Todo => 'label-info',
self::InProgress => 'label-warning',
self::Done => 'label-success',
};
}
}
+90
View File
@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\EventListener;
use Mautic\ConfigBundle\ConfigEvents;
use Mautic\ConfigBundle\Event\ConfigBuilderEvent;
use Mautic\ConfigBundle\Event\ConfigEvent;
use MauticPlugin\PlanBundle\Entity\PlanAllocationItemRepository;
use MauticPlugin\PlanBundle\Entity\PlanDescriptionItemRepository;
use MauticPlugin\PlanBundle\Form\Type\ConfigType;
use MauticPlugin\PlanBundle\Service\ItemTypeProvider;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Adds the "Plan" tab to Settings > Configuration (description and allocation item types), and refuses
* to save it when a type that items still use has been removed.
*/
class ConfigSubscriber implements EventSubscriberInterface
{
public function __construct(
private PlanDescriptionItemRepository $descriptionItemRepository,
private PlanAllocationItemRepository $allocationItemRepository,
private ItemTypeProvider $typeProvider,
) {
}
public static function getSubscribedEvents(): array
{
return [
ConfigEvents::CONFIG_ON_GENERATE => ['onConfigGenerate', 0],
ConfigEvents::CONFIG_PRE_SAVE => ['onConfigPreSave', 0],
];
}
public function onConfigGenerate(ConfigBuilderEvent $event): void
{
$event->addForm([
'bundle' => 'PlanBundle',
'formAlias' => ConfigType::FORM_ALIAS,
'formType' => ConfigType::class,
'formTheme' => '@Plan/FormTheme/Config/_config_planconfig_widget.html.twig',
'parameters' => $event->getParametersFromConfig('PlanBundle'),
]);
}
public function onConfigPreSave(ConfigEvent $event): void
{
$config = $event->getConfig(ConfigType::FORM_ALIAS);
if (!is_array($config)) {
return;
}
$usage = [
ItemTypeProvider::KIND_DESCRIPTION => $this->descriptionItemRepository->countByType(),
ItemTypeProvider::KIND_ALLOCATION => $this->allocationItemRepository->countByType(),
];
foreach ($usage as $kind => $counts) {
$parameter = ItemTypeProvider::getParameter($kind);
if (!array_key_exists($parameter, $config)) {
continue;
}
$submitted = [];
foreach (ItemTypeProvider::normalize((array) $config[$parameter]) as $type) {
$submitted[$type['key']] = true;
}
$removedInUse = [];
foreach ($counts as $key => $count) {
if (!isset($submitted[$key])) {
$removedInUse[] = sprintf('%s (%d)', $this->typeProvider->getName($kind, $key) ?? $key, $count);
}
}
if ([] !== $removedInUse) {
$event->setError(
'mautic.plan.config.type.in_use',
['%types%' => implode(', ', $removedInUse)],
ConfigType::FORM_ALIAS,
$parameter
);
}
}
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\EventListener;
use Mautic\PluginBundle\Bundle\PluginDatabase;
use Mautic\PluginBundle\Event\PluginInstallEvent;
use Mautic\PluginBundle\PluginEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Core runs plugin migrations only on update. This also runs them right after install, once core has
* created the tables, so that a fresh install gets the foreign keys (see Migrations/Version_0_2_0.php).
*/
class PluginInstallSubscriber implements EventSubscriberInterface
{
private const BUNDLE = 'PlanBundle';
public function __construct(
private PluginDatabase $pluginDatabase,
) {
}
public static function getSubscribedEvents(): array
{
return [
// Lower priority than core's PluginSubscriber (0), which creates the schema.
PluginEvents::ON_PLUGIN_INSTALL => ['onPluginInstall', -10],
];
}
public function onPluginInstall(PluginInstallEvent $event): void
{
$plugin = $event->getPlugin();
if (self::BUNDLE !== $plugin->getBundle()) {
return;
}
$this->pluginDatabase->onPluginUpdate($plugin);
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Form\Type;
use MauticPlugin\PlanBundle\Service\CurrencyProvider;
use MauticPlugin\PlanBundle\Service\ItemTypeProvider;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\NotBlank;
/**
* The "Plan Settings" tab of Settings > Configuration. Each child is a local.php parameter:
* - plan_currency: the currency of every amount in the plugin (general setting);
* - one list of item types per kind (description items, with a pictogram; allocation items).
*
* @extends AbstractType<array<string, mixed>>
*/
class ConfigType extends AbstractType
{
public const FORM_ALIAS = 'planconfig';
public function __construct(
private CurrencyProvider $currencyProvider,
) {
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add(CurrencyProvider::CONFIG_PARAMETER, ChoiceType::class, [
'label' => 'mautic.plan.config.currency',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control', 'tooltip' => 'mautic.plan.config.currency.tooltip'],
'choices' => $this->currencyProvider->getChoices(),
'placeholder' => false,
'required' => true,
'constraints' => [new NotBlank()],
'empty_data' => CurrencyProvider::DEFAULT_CURRENCY,
]);
foreach (ItemTypeProvider::PARAMETERS as $kind => $parameter) {
$builder->add($parameter, CollectionType::class, [
'label' => false,
'entry_type' => ItemTypeConfigType::class,
'entry_options' => ['label' => false, 'with_icon' => ItemTypeProvider::KIND_DESCRIPTION === $kind],
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'prototype_name' => '__type__',
'required' => false,
'error_bubbling' => false,
]);
// Stored as a clean list (0..n-1, empty texts dropped), in the order shown on the page.
$builder->get($parameter)->addModelTransformer(new CallbackTransformer(
fn ($types): array => ItemTypeProvider::normalize(is_array($types) ? $types : []),
fn ($types): array => ItemTypeProvider::normalize(is_array($types) ? $types : []),
));
}
}
public function getBlockPrefix(): string
{
return self::FORM_ALIAS;
}
}
+109
View File
@@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Form\Type;
use MauticPlugin\PlanBundle\Service\ItemTypeProvider;
use MauticPlugin\PlanBundle\Service\Pictograms;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
/**
* One item type (description or allocation) in Settings > Configuration > Plan Settings: a name and a
* description per language, and for description item types a pictogram.
*
* The key is hidden. It is generated when the type is created and never changes, so that renaming a
* type doesn't affect the items that use it.
*
* @extends AbstractType<array<string, mixed>>
*/
class ItemTypeConfigType extends AbstractType
{
public function __construct(
private ItemTypeProvider $typeProvider,
) {
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$default = $this->typeProvider->getDefaultLocale();
$builder->add('key', HiddenType::class, [
'attr' => ['class' => 'plan-type-key'],
]);
$names = $builder->create('names', FormType::class, ['label' => false]);
$descriptions = $builder->create('descriptions', FormType::class, ['label' => false]);
foreach ($this->typeProvider->getLanguages() as $locale => $language) {
$isDefault = $locale === $default;
$names->add($locale, TextType::class, [
'label' => 'mautic.plan.config.type.name',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control', 'maxlength' => 191, 'data-locale' => $locale, 'data-language' => $language],
'required' => $isDefault,
'constraints' => $isDefault
? [new NotBlank(message: 'mautic.plan.config.type.name.required'), new Length(max: 191)]
: [new Length(max: 191)],
]);
$descriptions->add($locale, TextareaType::class, [
'label' => 'mautic.plan.config.type.description',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control', 'rows' => 2, 'data-locale' => $locale],
'required' => false,
]);
}
$builder->add($names);
$builder->add($descriptions);
// Description item types have a pictogram; the preview next to the dropdown is updated by plan.js.
if ($options['with_icon']) {
$builder->add('icon', ChoiceType::class, [
'label' => 'mautic.plan.config.type.icon',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control plan-type-icon-select'],
'choices' => Pictograms::getChoices(),
'choice_attr' => fn (?string $icon): array => ['data-icon' => (string) $icon],
'placeholder' => 'mautic.plan.config.type.icon.none',
'required' => false,
]);
}
// New types get a key once, here; existing types keep theirs.
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event): void {
$data = $event->getData();
if (is_array($data) && (!isset($data['key']) || '' === trim((string) $data['key']))) {
$data['key'] = 'type_'.bin2hex(random_bytes(4));
$event->setData($data);
}
});
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
// True for description item types: adds the pictogram field.
'with_icon' => false,
]);
$resolver->setAllowedTypes('with_icon', 'bool');
}
public function getBlockPrefix(): string
{
return 'plan_item_type_config';
}
}
+90
View File
@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Form\Type;
use MauticPlugin\PlanBundle\Entity\PlanAllocationItem;
use MauticPlugin\PlanBundle\Service\CurrencyProvider;
use MauticPlugin\PlanBundle\Service\ItemTypeProvider;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* One row of the allocation items collection in PlanType: type, name, description, planned cost and
* real cost (both in the general currency). Works like PlanDescriptionItemType (type description shown under the
* dropdown, hidden position kept in display order by Assets/js/plan.js).
*
* @extends AbstractType<PlanAllocationItem>
*/
class PlanAllocationItemType extends AbstractType
{
public function __construct(
private ItemTypeProvider $typeProvider,
private CurrencyProvider $currencyProvider,
) {
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$kind = ItemTypeProvider::KIND_ALLOCATION;
$builder->add('type', ChoiceType::class, [
'label' => 'mautic.plan.allocation_item.field.type',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control plan-item-type'],
'choices' => $this->typeProvider->getChoices($kind),
'choice_attr' => fn (?string $key): array => ['data-description' => (string) $this->typeProvider->getDescription($kind, $key)],
'placeholder' => 'mautic.core.form.chooseone',
'required' => true,
]);
$builder->add('name', TextType::class, [
'label' => 'mautic.plan.allocation_item.field.name',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control', 'maxlength' => 255],
'required' => false,
]);
$builder->add('description', TextareaType::class, [
'label' => 'mautic.plan.allocation_item.field.description',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control', 'rows' => 3],
'required' => false,
]);
// Costs are in the general currency (Settings > Configuration > Plan Settings), shown next to the field.
foreach (['planned', 'real'] as $cost) {
$builder->add($cost.'Cost', NumberType::class, [
'label' => 'mautic.plan.allocation_item.field.'.$cost.'_cost',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control', 'postaddon_text' => $this->currencyProvider->getCurrency()],
'input' => 'string',
'scale' => 2,
'required' => false,
]);
}
$builder->add('position', HiddenType::class, [
'attr' => ['class' => 'plan-row-position'],
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => PlanAllocationItem::class,
]);
}
public function getBlockPrefix(): string
{
return 'plan_allocation_item';
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Form\Type;
use MauticPlugin\PlanBundle\Entity\PlanDescriptionItem;
use MauticPlugin\PlanBundle\Service\ItemTypeProvider;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* One row of the description items collection in PlanType. The type dropdown lists the description item
* types set up in Settings > Configuration > Plan; each option carries the type's description, which
* Assets/js/plan.js shows under the dropdown. The position field is hidden and kept in display order by
* plan.js.
*
* @extends AbstractType<PlanDescriptionItem>
*/
class PlanDescriptionItemType extends AbstractType
{
public function __construct(
private ItemTypeProvider $typeProvider,
) {
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$kind = ItemTypeProvider::KIND_DESCRIPTION;
$builder->add('type', ChoiceType::class, [
'label' => 'mautic.plan.description_item.field.type',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control plan-item-type'],
'choices' => $this->typeProvider->getChoices($kind),
// The type's description and pictogram, shown next to the dropdown by plan.js.
'choice_attr' => fn (?string $key): array => [
'data-description' => (string) $this->typeProvider->getDescription($kind, $key),
'data-icon' => (string) $this->typeProvider->getIcon($kind, $key),
],
'placeholder' => 'mautic.core.form.chooseone',
'required' => true,
]);
$builder->add('description', TextareaType::class, [
'label' => 'mautic.plan.description_item.field.description',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control', 'rows' => 5],
'required' => false,
]);
$builder->add('position', HiddenType::class, [
'attr' => ['class' => 'plan-row-position'],
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => PlanDescriptionItem::class,
]);
}
public function getBlockPrefix(): string
{
return 'plan_description_item';
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Form\Type;
use MauticPlugin\PlanBundle\Entity\PlanObjective;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* One row of the objectives collection in PlanType. The position field is hidden and kept in
* display order by Assets/js/plan.js.
*
* @extends AbstractType<PlanObjective>
*/
class PlanObjectiveType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('title', TextType::class, [
'label' => 'mautic.plan.objective.field.title',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control', 'maxlength' => 255],
]);
$builder->add('description', TextareaType::class, [
'label' => 'mautic.plan.objective.field.description',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control', 'rows' => 2],
'required' => false,
]);
$builder->add('position', HiddenType::class, [
'attr' => ['class' => 'plan-row-position'],
]);
$builder->add('isAchieved', CheckboxType::class, [
'label' => 'mautic.plan.objective.field.is_achieved',
'required' => false,
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => PlanObjective::class,
]);
}
public function getBlockPrefix(): string
{
return 'plan_objective';
}
}
+167
View File
@@ -0,0 +1,167 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Form\Type;
use Doctrine\ORM\EntityManagerInterface;
use Mautic\CategoryBundle\Form\Type\CategoryListType;
use Mautic\CoreBundle\Form\DataTransformer\IdToEntityModelTransformer;
use Mautic\CoreBundle\Form\EventListener\CleanFormSubscriber;
use Mautic\CoreBundle\Form\Type\DatePickerType;
use Mautic\CoreBundle\Form\Type\FormButtonsType;
use Mautic\CoreBundle\Form\Type\YesNoButtonGroupType;
use Mautic\UserBundle\Entity\User;
use Mautic\UserBundle\Form\Type\UserListType;
use MauticPlugin\PlanBundle\Entity\Plan;
use MauticPlugin\PlanBundle\Entity\PlanStatus;
use MauticPlugin\PlanBundle\Service\CurrencyProvider;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\EnumType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* @extends AbstractType<Plan>
*/
class PlanType extends AbstractType
{
public function __construct(
private CurrencyProvider $currencyProvider,
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 and line breaks, again on every save). With an array, every field not listed, nested
// objectives and description items included, goes through core's "filter": plain text is kept as
// typed (line breaks, &, quotes) and HTML tags are removed.
$builder->addEventSubscriber(new CleanFormSubscriber(['name' => 'filter']));
$builder->add('name', TextType::class, [
'label' => 'mautic.plan.field.name',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control'],
]);
// The Description tab. by_reference false: Symfony calls Plan::addDescriptionItem()/removeDescriptionItem().
$builder->add('descriptionItems', CollectionType::class, [
'label' => 'mautic.plan.field.description_items',
'entry_type' => PlanDescriptionItemType::class,
'entry_options' => ['label' => false],
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
'prototype' => true,
'prototype_name' => '__descitem__',
'required' => false,
]);
// The Allocation tab's cost lines, in the general currency.
$builder->add('allocationItems', CollectionType::class, [
'label' => 'mautic.plan.field.allocation_items',
'entry_type' => PlanAllocationItemType::class,
'entry_options' => ['label' => false],
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
'prototype' => true,
'prototype_name' => '__allocitem__',
'required' => false,
]);
$builder->add('version', IntegerType::class, [
'label' => 'mautic.plan.field.version',
'label_attr' => ['class' => 'control-label'],
'invalid_message' => 'mautic.plan.version.range',
'attr' => [
'class' => 'form-control',
'min' => Plan::VERSION_MIN,
'max' => Plan::VERSION_MAX,
'step' => 1,
],
]);
// by_reference false: Symfony calls Plan::addObjective()/removeObjective(), which keep both sides in sync.
$builder->add('objectives', CollectionType::class, [
'label' => 'mautic.plan.field.objectives',
'entry_type' => PlanObjectiveType::class,
'entry_options' => ['label' => false],
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
'prototype' => true,
'prototype_name' => '__objective__',
'required' => false,
]);
$builder->add('status', EnumType::class, [
'class' => PlanStatus::class,
'choice_label' => fn (PlanStatus $status): string => $status->getLabelKey(),
'label' => 'mautic.plan.field.status',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control'],
]);
// Required here; the column is nullable only because of onDelete SET NULL.
$builder->add(
$builder->create('owner', UserListType::class, [
'label' => 'mautic.plan.field.owner',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control'],
'required' => true,
'multiple' => false,
])->addModelTransformer(new IdToEntityModelTransformer($this->em, User::class))
);
$builder->add('startDate', DatePickerType::class, [
'label' => 'mautic.plan.field.start_date',
]);
$builder->add('endDate', DatePickerType::class, [
'label' => 'mautic.plan.field.end_date',
]);
// In the general currency (Settings > Configuration > Plan Settings), shown next to the field.
$builder->add('budgetPlanned', NumberType::class, [
'label' => 'mautic.plan.field.budget_planned',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control', 'postaddon_text' => $this->currencyProvider->getCurrency()],
'input' => 'string',
'scale' => 2,
'required' => false,
]);
$builder->add('category', CategoryListType::class, [
'bundle' => 'plan',
]);
$builder->add('isPublished', YesNoButtonGroupType::class, [
'label' => 'mautic.core.form.available',
]);
$builder->add('buttons', FormButtonsType::class);
if (!empty($options['action'])) {
$builder->setAction($options['action']);
}
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Plan::class,
]);
}
public function getBlockPrefix(): string
{
return 'plan';
}
}
+124
View File
@@ -0,0 +1,124 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Form\Type;
use Doctrine\ORM\EntityRepository;
use Mautic\CoreBundle\Form\EventListener\CleanFormSubscriber;
use Mautic\CoreBundle\Form\Type\DatePickerType;
use Mautic\CoreBundle\Form\Type\FormButtonsType;
use MauticPlugin\PlanBundle\Entity\Plan;
use MauticPlugin\PlanBundle\Entity\Task;
use MauticPlugin\PlanBundle\Entity\TaskStatus;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EnumType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* @extends AbstractType<Task>
*/
class TaskType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->addEventSubscriber(new CleanFormSubscriber(['description' => 'strict_html']));
/** @var Task $task */
$task = $options['data'];
$plan = $task->getPlan();
$builder->add('name', TextType::class, [
'label' => 'mautic.plan.task.field.name',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control', 'maxlength' => 255],
]);
$builder->add('description', TextareaType::class, [
'label' => 'mautic.plan.task.field.description',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control', 'rows' => 6],
'required' => false,
]);
$builder->add('plan', EntityType::class, [
'label' => 'mautic.plan.task.field.plan',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control'],
'class' => Plan::class,
'choice_label' => 'name',
'query_builder' => fn (EntityRepository $er) => $er->createQueryBuilder('p')->orderBy('p.name', 'ASC'),
'placeholder' => 'mautic.core.form.chooseone',
'required' => true,
]);
// Offers the tasks of the task's plan when it is known, otherwise all tasks grouped by plan.
// ValidTaskParent rejects a parent from another plan, and loops.
$builder->add('parent', EntityType::class, [
'label' => 'mautic.plan.task.field.parent',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control'],
'class' => Task::class,
'choice_label' => 'name',
'group_by' => null === $plan ? fn (Task $t): string => (string) $t->getPlan()?->getName() : null,
'query_builder' => function (EntityRepository $er) use ($task, $plan) {
$qb = $er->createQueryBuilder('t')
->leftJoin('t.plan', 'p')
->addSelect('p')
->orderBy('p.name', 'ASC')
->addOrderBy('t.name', 'ASC');
if (null !== $plan) {
$qb->andWhere('t.plan = :plan')->setParameter('plan', $plan);
}
if (null !== $task->getId()) {
$qb->andWhere('t.id != :self')->setParameter('self', $task->getId());
}
return $qb;
},
'placeholder' => 'mautic.plan.task.parent.none',
'required' => false,
]);
// Dropdown in the order of the TaskStatus cases: New, To do, In progress, Done.
$builder->add('status', EnumType::class, [
'label' => 'mautic.plan.task.field.status',
'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control'],
'class' => TaskStatus::class,
'choice_label' => fn (TaskStatus $status): string => $status->getLabelKey(),
]);
$builder->add('startDate', DatePickerType::class, [
'label' => 'mautic.plan.task.field.start_date',
]);
$builder->add('endDate', DatePickerType::class, [
'label' => 'mautic.plan.task.field.end_date',
]);
$builder->add('buttons', FormButtonsType::class);
if (!empty($options['action'])) {
$builder->setAction($options['action']);
}
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Task::class,
]);
}
public function getBlockPrefix(): string
{
return 'plan_task';
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Integration;
use Mautic\IntegrationsBundle\Integration\BasicIntegration;
use Mautic\IntegrationsBundle\Integration\ConfigurationTrait;
use Mautic\IntegrationsBundle\Integration\Interfaces\BasicInterface;
class PlanIntegration extends BasicIntegration implements BasicInterface
{
use ConfigurationTrait;
public const NAME = 'Plan';
public const DISPLAY_NAME = 'Plan';
public function getName(): string
{
return self::NAME;
}
public function getDisplayName(): string
{
return self::DISPLAY_NAME;
}
public function getIcon(): string
{
return 'plugins/PlanBundle/Assets/img/icon.svg';
}
}
+14
View File
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Integration\Support;
use Mautic\IntegrationsBundle\Integration\DefaultConfigFormTrait;
use Mautic\IntegrationsBundle\Integration\Interfaces\ConfigFormInterface;
use MauticPlugin\PlanBundle\Integration\PlanIntegration;
class ConfigSupport extends PlanIntegration implements ConfigFormInterface
{
use DefaultConfigFormTrait;
}
+98
View File
@@ -0,0 +1,98 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Table;
use Mautic\IntegrationsBundle\Migration\AbstractMigration;
use MauticPlugin\PlanBundle\Entity\Plan;
/**
* Brings the plans table in line with the entity mapping.
*
* The plugin installer only runs SchemaTool on the plugin's own entities, so it drops the foreign keys
* to core tables (users, categories). This migration adds them with ON DELETE SET NULL, and shrinks the
* status column to VARCHAR(20). It is idempotent: it runs on plugin update (by the core migration
* engine) and right after install (by PluginInstallSubscriber).
*/
class Version_0_2_0 extends AbstractMigration
{
private const STATUS_LENGTH = 20;
/**
* Local column => referenced core table.
*/
private const FOREIGN_KEYS = [
'owner_id' => 'users',
'category_id' => 'categories',
];
protected function isApplicable(Schema $schema): bool
{
$table = $this->getTable($schema);
if (null === $table) {
return false;
}
return [] !== $this->getMissingForeignKeys($table) || $this->statusNeedsResize($table);
}
protected function up(): void
{
$schema = $this->entityManager->getConnection()->createSchemaManager()->introspectSchema();
$table = $this->getTable($schema);
if (null === $table) {
return;
}
if ($this->statusNeedsResize($table)) {
$this->addSql(sprintf(
'ALTER TABLE %s MODIFY status VARCHAR(%d) NOT NULL',
$this->concatPrefix(Plan::TABLE_NAME),
self::STATUS_LENGTH
));
}
foreach ($this->getMissingForeignKeys($table) as $column => $referenceTable) {
$this->addSql($this->generateAlterTableForeignKeyStatement(
Plan::TABLE_NAME,
[$column],
$referenceTable,
['id'],
'ON DELETE SET NULL'
));
}
}
private function getTable(Schema $schema): ?Table
{
$name = $this->concatPrefix(Plan::TABLE_NAME);
return $schema->hasTable($name) ? $schema->getTable($name) : null;
}
/**
* @return array<string, string>
*/
private function getMissingForeignKeys(Table $table): array
{
$missing = self::FOREIGN_KEYS;
foreach ($table->getForeignKeys() as $foreignKey) {
foreach ($foreignKey->getLocalColumns() as $column) {
unset($missing[$column]);
}
}
return $missing;
}
private function statusNeedsResize(Table $table): bool
{
return $table->hasColumn('status') && self::STATUS_LENGTH !== $table->getColumn('status')->getLength();
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Mautic\IntegrationsBundle\Migration\AbstractMigration;
use MauticPlugin\PlanBundle\Entity\Plan;
use MauticPlugin\PlanBundle\Entity\PlanObjective;
/**
* Adds plans.version and the plan_objectives table to installs created before 0.3.0.
*
* Fresh installs get both from the entity mapping, so this migration then finds nothing to do.
*/
class Version_0_3_0 extends AbstractMigration
{
protected function isApplicable(Schema $schema): bool
{
$plans = $this->concatPrefix(Plan::TABLE_NAME);
if (!$schema->hasTable($plans)) {
return false;
}
return !$schema->getTable($plans)->hasColumn('version')
|| !$schema->hasTable($this->concatPrefix(PlanObjective::TABLE_NAME));
}
protected function up(): void
{
$schema = $this->entityManager->getConnection()->createSchemaManager()->introspectSchema();
$plans = $this->concatPrefix(Plan::TABLE_NAME);
$objectives = $this->concatPrefix(PlanObjective::TABLE_NAME);
if (!$schema->getTable($plans)->hasColumn('version')) {
$this->addSql("ALTER TABLE {$plans} ADD version SMALLINT UNSIGNED DEFAULT 1 NOT NULL");
}
if (!$schema->hasTable($objectives)) {
$index = $this->generatePropertyName(PlanObjective::TABLE_NAME, 'idx', ['plan_id']);
$foreignKey = $this->generatePropertyName(PlanObjective::TABLE_NAME, 'fk', ['plan_id']);
$this->addSql("CREATE TABLE {$objectives} (
id INT UNSIGNED AUTO_INCREMENT NOT NULL,
plan_id INT UNSIGNED NOT NULL,
title VARCHAR(255) NOT NULL,
description LONGTEXT DEFAULT NULL,
position INT DEFAULT 0 NOT NULL,
is_achieved TINYINT(1) DEFAULT 0 NOT NULL,
INDEX {$index} (plan_id),
PRIMARY KEY(id),
CONSTRAINT {$foreignKey} FOREIGN KEY (plan_id) REFERENCES {$plans} (id) ON DELETE CASCADE
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB ROW_FORMAT = DYNAMIC");
}
}
}
+98
View File
@@ -0,0 +1,98 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Table;
use Doctrine\ORM\Tools\SchemaTool;
use Mautic\IntegrationsBundle\Migration\AbstractMigration;
use MauticPlugin\PlanBundle\Entity\Plan;
use MauticPlugin\PlanBundle\Entity\Task;
/**
* Adds the plan_tasks table and its foreign keys to installs created before 0.4.0.
*
* The CREATE TABLE comes from the Task mapping, so it can't drift from the entity. Only that statement
* is kept: SchemaTool's output also contains statements for other tables (for example Symfony
* Messenger's messenger_messages), which would fail on an existing install.
*
* The foreign keys are added one by one when missing, so the migration also repairs a plan_tasks table
* that exists without them. Fresh installs get everything from the entity mapping, so this migration
* then finds nothing to do.
*/
class Version_0_4_0 extends AbstractMigration
{
/**
* Local column => [referenced table, ON DELETE action].
*/
private const FOREIGN_KEYS = [
'plan_id' => [Plan::TABLE_NAME, 'CASCADE'],
'parent_id' => [Task::TABLE_NAME, 'SET NULL'],
];
protected function isApplicable(Schema $schema): bool
{
if (!$schema->hasTable($this->concatPrefix(Plan::TABLE_NAME))) {
return false;
}
$tasks = $this->concatPrefix(Task::TABLE_NAME);
return !$schema->hasTable($tasks) || [] !== $this->getMissingForeignKeys($schema->getTable($tasks));
}
protected function up(): void
{
$schema = $this->entityManager->getConnection()->createSchemaManager()->introspectSchema();
$tasks = $this->concatPrefix(Task::TABLE_NAME);
$missingFk = self::FOREIGN_KEYS;
if (!$schema->hasTable($tasks)) {
$this->addSql($this->getCreateTableSql());
} else {
$missingFk = $this->getMissingForeignKeys($schema->getTable($tasks));
}
foreach ($missingFk as $column => [$referenceTable, $onDelete]) {
$this->addSql($this->generateAlterTableForeignKeyStatement(
Task::TABLE_NAME,
[$column],
$referenceTable,
['id'],
'ON DELETE '.$onDelete
));
}
}
private function getCreateTableSql(): string
{
$schemaTool = new SchemaTool($this->entityManager);
$prefix = 'CREATE TABLE '.$this->concatPrefix(Task::TABLE_NAME).' ';
foreach ($schemaTool->getCreateSchemaSql([$this->entityManager->getClassMetadata(Task::class)]) as $sql) {
if (str_starts_with($sql, $prefix)) {
return $sql;
}
}
throw new \RuntimeException('SchemaTool returned no CREATE TABLE statement for '.Task::TABLE_NAME.'.');
}
/**
* @return array<string, array{0: string, 1: string}>
*/
private function getMissingForeignKeys(Table $table): array
{
$missing = self::FOREIGN_KEYS;
foreach ($table->getForeignKeys() as $foreignKey) {
foreach ($foreignKey->getLocalColumns() as $column) {
unset($missing[$column]);
}
}
return $missing;
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Mautic\IntegrationsBundle\Migration\AbstractMigration;
use MauticPlugin\PlanBundle\Entity\Task;
use MauticPlugin\PlanBundle\Entity\TaskStatus;
/**
* Adds start_date, end_date and status (default "new", indexed) to plan_tasks, for installs created
* before 0.5.0. Existing tasks get the status "new". Each column is added only if missing.
*/
class Version_0_5_0 extends AbstractMigration
{
private const STATUS_INDEX = 'plan_task_status';
protected function isApplicable(Schema $schema): bool
{
$tasks = $this->concatPrefix(Task::TABLE_NAME);
if (!$schema->hasTable($tasks)) {
return false;
}
$table = $schema->getTable($tasks);
return !$table->hasColumn('start_date')
|| !$table->hasColumn('end_date')
|| !$table->hasColumn('status')
|| !$table->hasIndex(self::STATUS_INDEX);
}
protected function up(): void
{
$tasks = $this->concatPrefix(Task::TABLE_NAME);
$table = $this->entityManager->getConnection()->createSchemaManager()->introspectTable($tasks);
if (!$table->hasColumn('start_date')) {
$this->addSql("ALTER TABLE {$tasks} ADD start_date DATETIME DEFAULT NULL");
}
if (!$table->hasColumn('end_date')) {
$this->addSql("ALTER TABLE {$tasks} ADD end_date DATETIME DEFAULT NULL");
}
if (!$table->hasColumn('status')) {
$this->addSql(sprintf(
"ALTER TABLE %s ADD status VARCHAR(20) DEFAULT '%s' NOT NULL",
$tasks,
TaskStatus::New->value
));
}
if (!$table->hasIndex(self::STATUS_INDEX)) {
// Same name as in the Task mapping (index names aren't prefixed).
$this->addSql('CREATE INDEX '.self::STATUS_INDEX." ON {$tasks} (status)");
}
}
}
+94
View File
@@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\ORM\Tools\SchemaTool;
use Mautic\IntegrationsBundle\Migration\AbstractMigration;
use MauticPlugin\PlanBundle\Entity\Plan;
use MauticPlugin\PlanBundle\Entity\PlanDescriptionItem;
/**
* For installs created before 0.6.0:
* - creates plan_description_items (and its foreign key to plans, ON DELETE CASCADE);
* - drops plans.description, which description items replace. Its content is deleted, as decided
* when description items were introduced.
*
* Each step runs only if needed. As in Version_0_4_0, only the CREATE TABLE statement for this table is
* kept from SchemaTool's output.
*/
class Version_0_6_0 extends AbstractMigration
{
protected function isApplicable(Schema $schema): bool
{
$plans = $this->concatPrefix(Plan::TABLE_NAME);
if (!$schema->hasTable($plans)) {
return false;
}
$items = $this->concatPrefix(PlanDescriptionItem::TABLE_NAME);
return !$schema->hasTable($items)
|| !$this->hasPlanForeignKey($schema)
|| $schema->getTable($plans)->hasColumn('description');
}
protected function up(): void
{
$schema = $this->entityManager->getConnection()->createSchemaManager()->introspectSchema();
$plans = $this->concatPrefix(Plan::TABLE_NAME);
$items = $this->concatPrefix(PlanDescriptionItem::TABLE_NAME);
if (!$schema->hasTable($items)) {
$this->addSql($this->getCreateTableSql());
}
if (!$schema->hasTable($items) || !$this->hasPlanForeignKey($schema)) {
$this->addSql($this->generateAlterTableForeignKeyStatement(
PlanDescriptionItem::TABLE_NAME,
['plan_id'],
Plan::TABLE_NAME,
['id'],
'ON DELETE CASCADE'
));
}
if ($schema->getTable($plans)->hasColumn('description')) {
$this->addSql("ALTER TABLE {$plans} DROP COLUMN description");
}
}
private function hasPlanForeignKey(Schema $schema): bool
{
$items = $this->concatPrefix(PlanDescriptionItem::TABLE_NAME);
if (!$schema->hasTable($items)) {
return false;
}
foreach ($schema->getTable($items)->getForeignKeys() as $foreignKey) {
if (in_array('plan_id', $foreignKey->getLocalColumns(), true)) {
return true;
}
}
return false;
}
private function getCreateTableSql(): string
{
$schemaTool = new SchemaTool($this->entityManager);
$prefix = 'CREATE TABLE '.$this->concatPrefix(PlanDescriptionItem::TABLE_NAME).' ';
foreach ($schemaTool->getCreateSchemaSql([$this->entityManager->getClassMetadata(PlanDescriptionItem::class)]) as $sql) {
if (str_starts_with($sql, $prefix)) {
return $sql;
}
}
throw new \RuntimeException('SchemaTool returned no CREATE TABLE statement for '.PlanDescriptionItem::TABLE_NAME.'.');
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\ORM\Tools\SchemaTool;
use Mautic\IntegrationsBundle\Migration\AbstractMigration;
use MauticPlugin\PlanBundle\Entity\Plan;
use MauticPlugin\PlanBundle\Entity\PlanAllocationItem;
/**
* Creates plan_allocation_items (and its foreign key to plans, ON DELETE CASCADE) for installs created
* before 0.7.0. Each step runs only if needed. As in Version_0_4_0, only the CREATE TABLE statement for
* this table is kept from SchemaTool's output.
*/
class Version_0_7_0 extends AbstractMigration
{
protected function isApplicable(Schema $schema): bool
{
if (!$schema->hasTable($this->concatPrefix(Plan::TABLE_NAME))) {
return false;
}
return !$schema->hasTable($this->concatPrefix(PlanAllocationItem::TABLE_NAME)) || !$this->hasPlanForeignKey($schema);
}
protected function up(): void
{
$schema = $this->entityManager->getConnection()->createSchemaManager()->introspectSchema();
$items = $this->concatPrefix(PlanAllocationItem::TABLE_NAME);
if (!$schema->hasTable($items)) {
$this->addSql($this->getCreateTableSql());
}
if (!$this->hasPlanForeignKey($schema)) {
$this->addSql($this->generateAlterTableForeignKeyStatement(
PlanAllocationItem::TABLE_NAME,
['plan_id'],
Plan::TABLE_NAME,
['id'],
'ON DELETE CASCADE'
));
}
}
private function hasPlanForeignKey(Schema $schema): bool
{
$items = $this->concatPrefix(PlanAllocationItem::TABLE_NAME);
if (!$schema->hasTable($items)) {
return false;
}
foreach ($schema->getTable($items)->getForeignKeys() as $foreignKey) {
if (in_array('plan_id', $foreignKey->getLocalColumns(), true)) {
return true;
}
}
return false;
}
private function getCreateTableSql(): string
{
$schemaTool = new SchemaTool($this->entityManager);
$prefix = 'CREATE TABLE '.$this->concatPrefix(PlanAllocationItem::TABLE_NAME).' ';
foreach ($schemaTool->getCreateSchemaSql([$this->entityManager->getClassMetadata(PlanAllocationItem::class)]) as $sql) {
if (str_starts_with($sql, $prefix)) {
return $sql;
}
}
throw new \RuntimeException('SchemaTool returned no CREATE TABLE statement for '.PlanAllocationItem::TABLE_NAME.'.');
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Mautic\IntegrationsBundle\Migration\AbstractMigration;
use MauticPlugin\PlanBundle\Entity\Plan;
use MauticPlugin\PlanBundle\Entity\PlanAllocationItem;
/**
* Since 0.8.0 every amount is in one general currency (Settings > Configuration > Plan Settings, parameter
* plan_currency), so the per-record currency columns are dropped: plans.currency,
* plan_allocation_items.planned_currency and plan_allocation_items.real_currency. Amounts are kept as they
* are. Each column is dropped only if it exists.
*/
class Version_0_8_0 extends AbstractMigration
{
/**
* Table => columns to drop.
*/
private const COLUMNS = [
Plan::TABLE_NAME => ['currency'],
PlanAllocationItem::TABLE_NAME => ['planned_currency', 'real_currency'],
];
protected function isApplicable(Schema $schema): bool
{
return [] !== $this->getColumnsToDrop($schema);
}
protected function up(): void
{
$schema = $this->entityManager->getConnection()->createSchemaManager()->introspectSchema();
foreach ($this->getColumnsToDrop($schema) as $table => $columns) {
foreach ($columns as $column) {
$this->addSql("ALTER TABLE {$table} DROP COLUMN {$column}");
}
}
}
/**
* @return array<string, string[]> prefixed table => existing columns to drop
*/
private function getColumnsToDrop(Schema $schema): array
{
$drop = [];
foreach (self::COLUMNS as $table => $columns) {
$table = $this->concatPrefix($table);
if (!$schema->hasTable($table)) {
continue;
}
$existing = array_values(array_filter($columns, fn (string $column): bool => $schema->getTable($table)->hasColumn($column)));
if ([] !== $existing) {
$drop[$table] = $existing;
}
}
return $drop;
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Model;
use Mautic\CoreBundle\Model\FormModel;
use MauticPlugin\PlanBundle\Entity\Plan;
use MauticPlugin\PlanBundle\Entity\PlanRepository;
use MauticPlugin\PlanBundle\Form\Type\PlanType;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
/**
* @extends FormModel<Plan>
*/
class PlanModel extends FormModel
{
public function getRepository(): PlanRepository
{
$repository = $this->em->getRepository(Plan::class);
\assert($repository instanceof PlanRepository);
return $repository;
}
public function getPermissionBase(): string
{
return 'plan:plans';
}
/**
* With no ID, returns a new plan with the current user as owner.
*/
public function getEntity($id = null): ?Plan
{
if (null === $id) {
$plan = new Plan();
$plan->setOwner($this->userHelper->getUser(true));
return $plan;
}
$plan = parent::getEntity($id);
return $plan instanceof Plan ? $plan : null;
}
/**
* Keeps objective and description item positions contiguous (0..n-1) before saving.
*/
public function saveEntity($entity, $unlock = true): void
{
if ($entity instanceof Plan) {
$entity->normalizePositions();
}
parent::saveEntity($entity, $unlock);
}
/**
* @param array<string, mixed> $options
*/
public function createForm($entity, FormFactoryInterface $formFactory, $action = null, $options = []): FormInterface
{
if (!$entity instanceof Plan) {
throw new MethodNotAllowedHttpException(['Plan']);
}
if (!empty($action)) {
$options['action'] = $action;
}
return $formFactory->create(PlanType::class, $entity, $options);
}
}
+91
View File
@@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Model;
use Mautic\CoreBundle\Model\FormModel;
use MauticPlugin\PlanBundle\Entity\Plan;
use MauticPlugin\PlanBundle\Entity\Task;
use MauticPlugin\PlanBundle\Entity\TaskRepository;
use MauticPlugin\PlanBundle\Form\Type\TaskType;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
/**
* Available as mautic.plan.model.task, or getModel('plan.task').
*
* @extends FormModel<Task>
*/
class TaskModel extends FormModel
{
public function getRepository(): TaskRepository
{
$repository = $this->em->getRepository(Task::class);
\assert($repository instanceof TaskRepository);
return $repository;
}
public function getPermissionBase(): string
{
return 'plan:tasks';
}
public function getEntity($id = null): ?Task
{
if (null === $id) {
return new Task();
}
$task = parent::getEntity($id);
return $task instanceof Task ? $task : null;
}
/**
* The plan's tasks as a tree: top-level tasks first, each with its sub-tasks, ordered by name.
*
* @return array<int, array{task: Task, depth: int}>
*/
public function getTaskTree(Plan $plan): array
{
$byParent = [];
foreach ($this->getRepository()->findByPlan($plan) as $task) {
$byParent[$task->getParent()?->getId() ?? 0][] = $task;
}
$rows = [];
$seen = [];
$walk = function (int $parentId, int $depth) use (&$walk, &$rows, &$seen, $byParent): void {
foreach ($byParent[$parentId] ?? [] as $task) {
if (isset($seen[$task->getId()])) {
continue;
}
$seen[$task->getId()] = true;
$rows[] = ['task' => $task, 'depth' => $depth];
$walk((int) $task->getId(), $depth + 1);
}
};
$walk(0, 0);
return $rows;
}
/**
* @param array<string, mixed> $options
*/
public function createForm($entity, FormFactoryInterface $formFactory, $action = null, $options = []): FormInterface
{
if (!$entity instanceof Task) {
throw new MethodNotAllowedHttpException(['Task']);
}
if (!empty($action)) {
$options['action'] = $action;
}
return $formFactory->create(TaskType::class, $entity, $options);
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle;
use Mautic\IntegrationsBundle\Bundle\AbstractPluginBundle;
class PlanBundle extends AbstractPluginBundle
{
}
@@ -0,0 +1,96 @@
{#
# Settings > Configuration > Plan Settings: the general currency, the description item types (with a
# pictogram) and the allocation item types. Adding and removing types, and the pictogram preview, are
# handled by Assets/js/plan.js (delegated handlers on .plan-config-types).
#}
{% macro type_row(type) %}
<div class="panel panel-default plan-config-type">
<div class="panel-body">
{{ form_widget(type.children.key) }}
{{ form_errors(type) }}
{% if type.children.icon is defined %}
{% set icon = type.children.icon.vars.value %}
<div class="row mb-sm">
<div class="col-xs-1 text-center pt-lg">
<i class="plan-type-icon-preview {{ icon }}" style="font-size: 28px;" aria-hidden="true"></i>
</div>
<div class="col-xs-5">{{ form_row(type.children.icon) }}</div>
</div>
{% endif %}
<table class="table table-condensed mb-0">
<thead>
<tr>
<th class="col-xs-2">{{ 'mautic.plan.config.type.language'|trans }}</th>
<th class="col-xs-4">{{ 'mautic.plan.config.type.name'|trans }}</th>
<th class="col-xs-6">{{ 'mautic.plan.config.type.description'|trans }}</th>
</tr>
</thead>
<tbody>
{% for locale, name in type.children.names.children %}
<tr>
<td class="text-muted" title="{{ name.vars.attr['data-locale'] }}">
{{ name.vars.attr['data-language'] }}
{% if name.vars.required %}<span class="required">*</span>{% endif %}
</td>
<td>
{{ form_widget(name) }}
{{ form_errors(name) }}
</td>
<td>
{{ form_widget(type.children.descriptions.children[locale]) }}
{{ form_errors(type.children.descriptions.children[locale]) }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="text-right mt-xs">
<button type="button" class="btn btn-ghost btn-sm plan-config-type-remove">
<i class="ri-delete-bin-line"></i> {{ 'mautic.plan.config.type.remove'|trans }}
</button>
</div>
</div>
</div>
{% endmacro %}
{# One editable list of types (one per kind of plan item). #}
{% macro type_section(types, titleKey, helpKey) %}
{% import _self as plan %}
<h4 class="fw-sb mt-lg mb-xs">{{ titleKey|trans }}</h4>
<p class="text-muted small">{{ helpKey|trans }}</p>
{{ form_errors(types) }}
<div class="plan-config-types" data-prototype="{{ plan.type_row(types.vars.prototype)|e('html_attr') }}">
<p class="text-muted plan-config-types-empty{% if types|length > 0 %} hide{% endif %}">
{{ 'mautic.plan.config.types.empty'|trans }}
</p>
<div class="plan-config-types-list">
{% for type in types %}
{{ plan.type_row(type) }}
{% endfor %}
</div>
<button type="button" class="btn btn-ghost plan-config-type-add">
<i class="ri-add-line"></i> {{ 'mautic.plan.config.type.add'|trans }}
</button>
</div>
{% do types.setRendered %}
{% endmacro %}
{% block _config_planconfig_widget %}
{% import _self as plan %}
<div class="text-muted small pb-md">{{ 'mautic.plan.config.description'|trans }}</div>
<h4 class="fw-sb mb-xs">{{ 'mautic.plan.config.section.general'|trans }}</h4>
<div class="row">
<div class="col-md-6">{{ form_row(form.children.plan_currency) }}</div>
</div>
<p class="text-muted small">{{ 'mautic.plan.config.currency.help'|trans }}</p>
{{ plan.type_section(form.children.plan_description_item_types,
'mautic.plan.config.section.description_item_types',
'mautic.plan.config.section.description_item_types.help') }}
{{ plan.type_section(form.children.plan_allocation_item_types,
'mautic.plan.config.section.allocation_item_types',
'mautic.plan.config.section.allocation_item_types.help') }}
{% endblock %}
+31
View File
@@ -0,0 +1,31 @@
{#
# Tab bar shared by the plan form and the plan detail page.
#
# Parameters:
# planId: the plan's id (null for a new plan)
# counts (optional): tab id => number shown next to the tab name
#
# The tab panes use the ids plan-tab-<id>. Assets/js/plan.js reopens the tab last used for this plan
# (so Edit, Save and Cancel keep the same tab), and on the form marks the tabs whose pane contains a
# validation error and opens the first of them.
#}
{% set planTabs = {
'details': 'mautic.plan.tab.details',
'description': 'mautic.plan.tab.description',
'objectives': 'mautic.plan.tab.objectives',
'allocation': 'mautic.plan.tab.allocation',
'targets': 'mautic.plan.tab.targets',
'tasks': 'mautic.plan.tab.tasks',
} %}
<ul class="nav nav-tabs nav-tabs-contained tabs-horizontal plan-tabs" role="tablist" data-plan-id="{{ planId|default('') }}">
{% for id, label in planTabs %}
<li class="{{ loop.first ? 'active' : '' }}" data-tab-id="plan-tab-{{ id }}">
<a href="#plan-tab-{{ id }}" role="tab" data-toggle="tab">
<span>{{ label|trans }}</span>
{% if counts is defined and counts[id] is defined %}
<span class="badge">{{ counts[id] }}</span>
{% endif %}
</a>
</li>
{% endfor %}
</ul>
@@ -0,0 +1,78 @@
{#
# The plan's tasks, for the Tasks tab of the plan detail page and form. Same columns as the task list
# (Planning > Tasks): ID, Name, Description, Start date, End date, Status. Rows are in tree order:
# each task is followed by its sub-tasks, indented under it.
#
# Parameters:
# plan: the Plan
# taskTree: rows from TaskModel::getTaskTree(): {task, depth}, in display order
# readOnly: true on the plan form: no links, so that following one can't drop unsaved changes
# taskPermissions: plan:tasks:* permissions (create, editown, editother), when not read-only
#
# Links carry returnTo=plan, so that Save and Cancel on the task form come back to this plan
# (see TaskController). Opened from Planning > Tasks, the task form goes back to the task list.
#}
{% set readOnly = readOnly|default(false) %}
{% set taskPermissions = taskPermissions|default({}) %}
{% set canCreate = not readOnly and plan.id and taskPermissions['plan:tasks:create']|default(false) %}
{% if canCreate %}
<div class="mb-md">
<a class="btn btn-ghost plan-task-add" href="{{ path('plan_task_action', {'objectAction': 'new', 'plan': plan.id, 'returnTo': 'plan'}) }}" data-toggle="ajax">
<i class="ri-add-line"></i> {{ 'mautic.plan.task.add'|trans }}
</a>
</div>
{% endif %}
{% if not plan.id %}
<p class="text-muted">{{ 'mautic.plan.task.save_plan_first'|trans }}</p>
{% elseif taskTree is empty %}
<p class="text-muted">{{ 'mautic.plan.task.empty'|trans }}</p>
{% else %}
<div class="table-responsive">
<table class="table table-hover plan-task-table">
<thead>
<tr>
<th class="col-plan-task-id">{{ 'mautic.core.id'|trans }}</th>
<th class="col-plan-task-name">{{ 'mautic.plan.task.field.name'|trans }}</th>
<th class="visible-md visible-lg col-plan-task-description">{{ 'mautic.plan.task.field.description'|trans }}</th>
<th class="col-plan-task-start">{{ 'mautic.plan.task.field.start_date'|trans }}</th>
<th class="col-plan-task-end">{{ 'mautic.plan.task.field.end_date'|trans }}</th>
<th class="col-plan-task-status">{{ 'mautic.plan.task.field.status'|trans }}</th>
</tr>
</thead>
<tbody>
{% for row in taskTree %}
{% set task = row.task %}
{% set canEdit = not readOnly and securityHasEntityAccess(taskPermissions['plan:tasks:editown']|default(false), taskPermissions['plan:tasks:editother']|default(false), task.createdBy) %}
{% set childCount = taskTree|filter(r => r.task.parent and r.task.parent.id == task.id)|length %}
<tr class="plan-task" data-task-id="{{ task.id }}" data-depth="{{ row.depth }}">
<td>{{ task.id }}</td>
<td>
<span style="display: inline-block; padding-left: {{ row.depth * 24 }}px;">
{% if row.depth > 0 %}
<i class="ri-corner-down-right-line text-muted" title="{{ 'mautic.plan.task.subtask_of'|trans({'%parent%': task.parent.name}) }}"></i>
{% endif %}
{% if canEdit %}
<a href="{{ path('plan_task_action', {'objectAction': 'edit', 'objectId': task.id, 'returnTo': 'plan'}) }}" data-toggle="ajax">{{ task.name }}</a>
{% else %}
{{ task.name }}
{% endif %}
{% if childCount > 0 %}
<span class="text-muted small" title="{{ 'mautic.plan.task.subtasks'|trans }}">({{ childCount }})</span>
{% endif %}
</span>
</td>
<td class="visible-md visible-lg text-muted">
{% set description = task.description|default('')|striptags|trim %}
{{ description|length > 120 ? description|slice(0, 120) ~ '…' : description }}
</td>
<td>{{ task.startDate ? dateToFull(task.startDate) : '' }}</td>
<td>{{ task.endDate ? dateToFull(task.endDate) : '' }}</td>
<td><span class="label {{ task.status.labelClass }}">{{ task.status.labelKey|trans }}</span></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
+294
View File
@@ -0,0 +1,294 @@
{% extends '@MauticCore/Default/content.html.twig' %}
{% block mauticContent %}plan{% endblock %}
{#
# No routeBase on the page_actions includes: core would turn it into mautic_plan_* route names.
# The buttons use actionRoute (plan_action) from the controller, and the close button gets its URL here.
#}
{% block preHeader %}
{{- include('@MauticCore/Helper/page_actions.html.twig', {
'item': item,
'templateButtons': {
'close': true,
},
'closeUrl': path('plan_index'),
'targetLabel': 'mautic.plan.header.index'|trans,
}) -}}
{# Core's helper renders an empty pill when there is no category. #}
{% if item.category %}
{{ include('@MauticCore/Modules/category--inline.html.twig', {'category': item.category}) }}
{% endif %}
{% endblock %}
{% block headerTitle %}{{ item.name }}{% endblock %}
{#
# Under the title, as on an email's page: the plan status, then the total planned and real costs of the
# allocation items, in the general currency. A real total above the planned total is red, otherwise green.
#}
{% block publishStatus %}
{% set statusColors = {
'draft': 'warm-gray', 'planned': 'blue', 'active': 'green',
'paused': 'warning', 'completed': 'teal', 'archived': 'cool-gray',
} %}
{% include '@MauticCore/Helper/_tag.html.twig' with { tags: [{
color: statusColors[item.status.value]|default('gray'),
label: item.status.labelKey,
icon: 'ri-flag-line',
attributes: {'class': 'plan-status-tag'},
}] } %}
{% set totals = item.allocationTotals %}
{% if totals.planned is not null or totals.real is not null %}
<div class="label__divider"></div>
{% set totalTags = [] %}
{% if totals.planned is not null %}
{% set totalTags = totalTags|merge([{
color: 'high-contrast',
icon: 'ri-wallet-3-line',
label: 'mautic.plan.header.total_planned'|trans({'%amount%': plan_money(totals.planned), '%currency%': plan_currency()}),
attributes: {'class': 'plan-total-planned', 'title': 'mautic.plan.header.total_planned.tooltip'|trans, 'data-toggle': 'tooltip'},
}]) %}
{% endif %}
{% if totals.real is not null %}
{% set overPlan = totals.planned is not null and (totals.real + 0) > (totals.planned + 0) %}
{% set totalTags = totalTags|merge([{
color: overPlan ? 'red' : 'green',
icon: overPlan ? 'ri-error-warning-line' : 'ri-checkbox-circle-line',
label: 'mautic.plan.header.total_real'|trans({'%amount%': plan_money(totals.real), '%currency%': plan_currency()}),
attributes: {'class': 'plan-total-real', 'title': (overPlan ? 'mautic.plan.header.total_real.over' : 'mautic.plan.header.total_real.tooltip')|trans, 'data-toggle': 'tooltip'},
}]) %}
{% endif %}
{% include '@MauticCore/Helper/_tag.html.twig' with { tags: totalTags } %}
{% endif %}
{% endblock %}
{% block actions %}
{{- include('@MauticCore/Helper/page_actions.html.twig', {
'item': item,
'templateButtons': {
'edit': securityHasEntityAccess(permissions['plan:plans:editown'], permissions['plan:plans:editother'], item.createdBy),
'delete': securityHasEntityAccess(permissions['plan:plans:deleteown'], permissions['plan:plans:deleteother'], item.createdBy),
},
'langVar': 'plan',
}) -}}
{% endblock %}
{% block content %}
{% set objectives = item.objectives %}
{% set achievedCount = objectives|filter(o => o.achieved)|length %}
{% set descriptionItems = item.descriptionItems %}
{% set allocationItems = item.allocationItems %}
{% set allocationTotals = item.allocationTotals %}
{{ include('@Plan/Plan/_tabs.html.twig', {'planId': item.id, 'counts': {
'description': descriptionItems|length,
'objectives': objectives|length,
'allocation': allocationItems|length,
'tasks': taskTree|length,
}}) }}
<div class="tab-content pa-md">
{# Details #}
<div class="tab-pane active bdr-w-0" id="plan-tab-details" role="tabpanel">
<table class="table table-hover mb-0 plan-details">
<tbody>
<tr>
<td class="col-md-3 text-muted">{{ 'mautic.plan.field.status'|trans }}</td>
<td>{{ item.status.labelKey|trans }}</td>
</tr>
{% if item.completedAt %}
<tr>
<td class="text-muted">{{ 'mautic.plan.field.completed_at'|trans }}</td>
<td>{{ dateToFull(item.completedAt) }}</td>
</tr>
{% endif %}
<tr>
<td class="text-muted">{{ 'mautic.plan.field.version'|trans }}</td>
<td>{{ item.version }}</td>
</tr>
<tr>
<td class="text-muted">{{ 'mautic.plan.field.owner'|trans }}</td>
<td>{{ item.owner ? item.owner.name : 'mautic.plan.owner.none'|trans }}</td>
</tr>
<tr>
<td class="text-muted">{{ 'mautic.plan.field.start_date'|trans }}</td>
<td>{{ item.startDate ? dateToFull(item.startDate) : 'mautic.plan.value.none'|trans }}</td>
</tr>
<tr>
<td class="text-muted">{{ 'mautic.plan.field.end_date'|trans }}</td>
<td>{{ item.endDate ? dateToFull(item.endDate) : 'mautic.plan.value.none'|trans }}</td>
</tr>
<tr>
<td class="text-muted">{{ 'mautic.core.category'|trans }}</td>
<td>{{ item.category ? item.category.title : 'mautic.plan.value.none'|trans }}</td>
</tr>
<tr>
<td class="text-muted">{{ 'mautic.core.form.available'|trans }}</td>
<td>{{ (item.isPublished ? 'mautic.core.form.yes' : 'mautic.core.form.no')|trans }}</td>
</tr>
<tr>
<td class="text-muted">{{ 'mautic.core.created'|trans }}</td>
<td>{{ item.dateAdded ? dateToFull(item.dateAdded) : '' }}{% if item.createdByUser %} ({{ item.createdByUser }}){% endif %}</td>
</tr>
{% if item.dateModified %}
<tr>
<td class="text-muted">{{ 'mautic.core.modified'|trans }}</td>
<td>{{ dateToFull(item.dateModified) }}{% if item.modifiedByUser %} ({{ item.modifiedByUser }}){% endif %}</td>
</tr>
{% endif %}
<tr>
<td class="text-muted">{{ 'mautic.core.id'|trans }}</td>
<td>{{ item.id }}</td>
</tr>
</tbody>
</table>
</div>
{# Description #}
<div class="tab-pane bdr-w-0" id="plan-tab-description" role="tabpanel">
{% if descriptionItems is empty %}
<p class="text-muted">{{ 'mautic.plan.description_item.empty'|trans }}</p>
{% else %}
{# Three columns: the type's pictogram, the type, the description. #}
<div class="table-responsive">
<table class="table table-hover plan-description-items-view">
<thead>
<tr>
<th class="text-center" style="width: 1%;">{{ 'mautic.plan.description_item.field.pictogram'|trans }}</th>
<th class="col-md-3">{{ 'mautic.plan.description_item.field.type'|trans }}</th>
<th>{{ 'mautic.plan.description_item.field.description'|trans }}</th>
</tr>
</thead>
<tbody>
{% for descriptionItem in descriptionItems %}
{% set typeName = plan_item_type_name('description', descriptionItem.type) %}
{% set typeDescription = plan_item_type_description('description', descriptionItem.type) %}
{% set typeIcon = plan_item_type_icon('description', descriptionItem.type) %}
<tr>
<td class="text-center">
{% if typeIcon %}<i class="{{ typeIcon }} plan-item-type-icon" style="font-size: 24px;" aria-hidden="true"></i>{% endif %}
</td>
<td>
<strong{% if typeDescription %} title="{{ typeDescription }}" data-toggle="tooltip"{% endif %}>
{{ typeName ?? 'mautic.plan.description_item.type.unknown'|trans({'%key%': descriptionItem.type}) }}
</strong>
</td>
<td style="white-space: pre-wrap;">{{ descriptionItem.description }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
</div>
{# Objectives #}
<div class="tab-pane bdr-w-0" id="plan-tab-objectives" role="tabpanel">
{% if objectives is empty %}
<p class="text-muted">{{ 'mautic.plan.objective.empty'|trans }}</p>
{% else %}
<p class="text-muted plan-objectives-progress">
{{ 'mautic.plan.objective.progress'|trans({'%achieved%': achievedCount, '%total%': objectives|length}) }}
</p>
<ol class="list-group plan-objectives-view">
{% for objective in objectives %}
<li class="list-group-item">
{% if objective.achieved %}
<i class="ri-checkbox-circle-fill text-success" title="{{ 'mautic.plan.objective.achieved'|trans }}"></i>
{% else %}
<i class="ri-checkbox-blank-circle-line text-muted" title="{{ 'mautic.plan.objective.not_achieved'|trans }}"></i>
{% endif %}
<strong>{{ objective.title }}</strong>
{% if objective.description is not empty %}
<div class="text-muted mt-xs" style="white-space: pre-wrap;">{{ objective.description }}</div>
{% endif %}
</li>
{% endfor %}
</ol>
{% endif %}
</div>
{# Allocation: the plan's budget, then the allocation items (cost lines) with their totals. #}
<div class="tab-pane bdr-w-0" id="plan-tab-allocation" role="tabpanel">
<table class="table table-hover mb-md plan-allocation">
<tbody>
<tr>
<td class="col-md-3 text-muted">{{ 'mautic.plan.field.budget_planned'|trans }}</td>
<td>
{% if item.budgetPlanned is not null %}
{{ plan_money(item.budgetPlanned) }} {{ plan_currency() }}
{% else %}
{{ 'mautic.plan.value.none'|trans }}
{% endif %}
</td>
</tr>
</tbody>
</table>
<h4 class="mb-sm">{{ 'mautic.plan.field.allocation_items'|trans }}</h4>
{% if allocationItems is empty %}
<p class="text-muted">{{ 'mautic.plan.allocation_item.empty'|trans }}</p>
{% else %}
<div class="table-responsive">
<table class="table table-hover plan-allocation-items-view">
<thead>
<tr>
<th>{{ 'mautic.plan.allocation_item.field.type'|trans }}</th>
<th>{{ 'mautic.plan.allocation_item.field.name'|trans }}</th>
<th class="visible-md visible-lg">{{ 'mautic.plan.allocation_item.field.description'|trans }}</th>
<th class="text-right">{{ 'mautic.plan.allocation_item.field.planned_cost'|trans }}</th>
<th class="text-right">{{ 'mautic.plan.allocation_item.field.real_cost'|trans }}</th>
</tr>
</thead>
<tbody>
{% for allocationItem in allocationItems %}
{% set typeName = plan_item_type_name('allocation', allocationItem.type) %}
{% set typeDescription = plan_item_type_description('allocation', allocationItem.type) %}
<tr>
<td{% if typeDescription %} title="{{ typeDescription }}"{% endif %}>
{{ typeName ?? 'mautic.plan.description_item.type.unknown'|trans({'%key%': allocationItem.type}) }}
</td>
<td>{{ allocationItem.name }}</td>
<td class="visible-md visible-lg text-muted" style="white-space: pre-wrap;">{{ allocationItem.description }}</td>
<td class="text-right text-nowrap">
{% if allocationItem.plannedCost is not null %}{{ plan_money(allocationItem.plannedCost) }} {{ plan_currency() }}{% endif %}
</td>
<td class="text-right text-nowrap">
{% if allocationItem.realCost is not null %}{{ plan_money(allocationItem.realCost) }} {{ plan_currency() }}{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr class="plan-allocation-total">
<th colspan="3">{{ 'mautic.plan.allocation.total'|trans }}</th>
<th class="text-right text-nowrap">
{% if allocationTotals.planned is not null %}{{ plan_money(allocationTotals.planned) }} {{ plan_currency() }}{% endif %}
</th>
<th class="text-right text-nowrap">
{% if allocationTotals.real is not null %}{{ plan_money(allocationTotals.real) }} {{ plan_currency() }}{% endif %}
</th>
</tr>
</tfoot>
</table>
</div>
{% endif %}
</div>
{# Targets #}
<div class="tab-pane bdr-w-0" id="plan-tab-targets" role="tabpanel">
<p class="text-muted">{{ 'mautic.plan.target.empty'|trans }}</p>
</div>
{# Tasks: same columns as Planning > Tasks, in tree order. #}
<div class="tab-pane bdr-w-0" id="plan-tab-tasks" role="tabpanel">
{{ include('@Plan/Plan/_task_table.html.twig', {
'plan': item,
'taskTree': taskTree,
'taskPermissions': taskPermissions,
}) }}
</div>
</div>
{% endblock %}
+216
View File
@@ -0,0 +1,216 @@
{% extends '@MauticCore/Default/content.html.twig' %}
{% block mauticContent %}plan{% endblock %}
{% block headerTitle %}
{% if entity.id %}
{{ 'mautic.plan.header.edit'|trans({'%name%': entity.name}) }}
{% else %}
{{ 'mautic.plan.header.new'|trans }}
{% endif %}
{% endblock %}
{#
# Editable, sortable rows (objectives, description items). Each macro renders one row, for existing
# rows and, through data-prototype, for new ones. Adding, removing and reordering rows is handled by
# Assets/js/plan.js, through the plan-collection-* classes.
#}
{% macro row_start(dragLabel) %}
<li class="plan-collection-row list-group-item">
<div class="row">
<div class="col-xs-1 text-center">
<span class="plan-collection-handle text-muted" title="{{ dragLabel|trans }}" style="cursor: move;">
<i class="ri-draggable ri-lg"></i>
</span>
</div>
<div class="col-xs-10">
{% endmacro %}
{% macro row_end(removeLabel) %}
</div>
<div class="col-xs-1 text-right">
<button type="button" class="btn btn-ghost btn-sm plan-collection-remove" title="{{ removeLabel|trans }}">
<i class="ri-delete-bin-line"></i>
</button>
</div>
</div>
</li>
{% endmacro %}
{% macro objective_row(objective) %}
{{ _self.row_start('mautic.plan.objective.drag') }}
{{ form_row(objective.title) }}
{{ form_row(objective.description) }}
{{ form_row(objective.isAchieved) }}
{{ form_widget(objective.position) }}
{{ _self.row_end('mautic.plan.objective.remove') }}
{% endmacro %}
{% macro description_item_row(item) %}
{{ _self.row_start('mautic.plan.description_item.drag') }}
<div class="row">
{# The selected type's pictogram; updated by plan.js when the type changes. #}
<div class="col-xs-1 text-center pt-lg">
<i class="plan-item-type-icon {{ plan_item_type_icon('description', item.type.vars.value) }}" style="font-size: 28px;" aria-hidden="true"></i>
</div>
<div class="col-xs-11">
{{ form_row(item.type) }}
{# Filled with the selected type's description by plan.js. #}
<p class="help-block plan-item-type-help">{{ plan_item_type_description('description', item.type.vars.value) }}</p>
</div>
</div>
{{ form_row(item.description) }}
{{ form_widget(item.position) }}
{{ _self.row_end('mautic.plan.description_item.remove') }}
{% endmacro %}
{% macro allocation_item_row(item) %}
{{ _self.row_start('mautic.plan.allocation_item.drag') }}
<div class="row">
<div class="col-md-6">
{{ form_row(item.type) }}
{# Filled with the selected type's description by plan.js. #}
<p class="help-block plan-item-type-help">{{ plan_item_type_description('allocation', item.type.vars.value) }}</p>
</div>
<div class="col-md-6">{{ form_row(item.name) }}</div>
</div>
{{ form_row(item.description) }}
<div class="row">
<div class="col-md-6">{{ form_row(item.plannedCost) }}</div>
<div class="col-md-6">{{ form_row(item.realCost) }}</div>
</div>
{{ form_widget(item.position) }}
{{ _self.row_end('mautic.plan.allocation_item.remove') }}
{% endmacro %}
{% block content %}
{{ form_start(form) }}
<div class="pa-md pb-0">
{{ form_row(form.name) }}
</div>
{{ include('@Plan/Plan/_tabs.html.twig', {'planId': entity.id}) }}
<div class="tab-content pa-md">
{# Details #}
<div class="tab-pane active bdr-w-0" id="plan-tab-details" role="tabpanel">
<div class="row">
<div class="col-md-4">{{ form_row(form.status) }}</div>
<div class="col-md-4">{{ form_row(form.version) }}</div>
<div class="col-md-4">{{ form_row(form.owner) }}</div>
</div>
{% if entity.completedAt %}
<div class="form-group">
<label class="control-label">{{ 'mautic.plan.field.completed_at'|trans }}</label>
<p class="form-control-static">{{ dateToFull(entity.completedAt) }}</p>
</div>
{% endif %}
<div class="row">
<div class="col-md-6">{{ form_row(form.startDate) }}</div>
<div class="col-md-6">{{ form_row(form.endDate) }}</div>
</div>
<div class="row">
<div class="col-md-6">{{ form_row(form.category) }}</div>
<div class="col-md-6">{{ form_row(form.isPublished) }}</div>
</div>
</div>
{# Description: description items. #}
<div class="tab-pane bdr-w-0" id="plan-tab-description" role="tabpanel">
{% set hasTypes = form.descriptionItems.vars.prototype.type.vars.choices is not empty %}
<div class="plan-collection plan-description-items"
data-prototype="{{ _self.description_item_row(form.descriptionItems.vars.prototype)|e('html_attr') }}"
data-prototype-name="__descitem__">
{{ form_errors(form.descriptionItems) }}
{% if not hasTypes %}
<div class="alert alert-info">{{ 'mautic.plan.description_item.no_types'|trans }}</div>
{% endif %}
<p class="text-muted plan-collection-empty{% if form.descriptionItems|length > 0 %} hide{% endif %}">
{{ 'mautic.plan.description_item.empty'|trans }}
</p>
<ul class="list-group plan-collection-list">
{% for item in form.descriptionItems %}
{{ _self.description_item_row(item) }}
{% endfor %}
</ul>
{% if hasTypes %}
<button type="button" class="btn btn-ghost plan-collection-add">
<i class="ri-add-line"></i> {{ 'mautic.plan.description_item.add'|trans }}
</button>
{% endif %}
</div>
{% do form.descriptionItems.setRendered %}
</div>
{# Objectives #}
<div class="tab-pane bdr-w-0" id="plan-tab-objectives" role="tabpanel">
<div class="plan-collection plan-objectives"
data-prototype="{{ _self.objective_row(form.objectives.vars.prototype)|e('html_attr') }}"
data-prototype-name="__objective__">
{{ form_errors(form.objectives) }}
<p class="text-muted plan-collection-empty{% if form.objectives|length > 0 %} hide{% endif %}">
{{ 'mautic.plan.objective.empty'|trans }}
</p>
<ul class="list-group plan-collection-list">
{% for objective in form.objectives %}
{{ _self.objective_row(objective) }}
{% endfor %}
</ul>
<button type="button" class="btn btn-ghost plan-collection-add">
<i class="ri-add-line"></i> {{ 'mautic.plan.objective.add'|trans }}
</button>
</div>
{% do form.objectives.setRendered %}
</div>
{# Allocation: the plan's budget, then the allocation items (cost lines). #}
<div class="tab-pane bdr-w-0" id="plan-tab-allocation" role="tabpanel">
<div class="row">
<div class="col-md-6">{{ form_row(form.budgetPlanned) }}</div>
</div>
{% set hasAllocationTypes = form.allocationItems.vars.prototype.type.vars.choices is not empty %}
<div class="plan-collection plan-allocation-items"
data-prototype="{{ _self.allocation_item_row(form.allocationItems.vars.prototype)|e('html_attr') }}"
data-prototype-name="__allocitem__">
<h4 class="mt-lg mb-sm">{{ 'mautic.plan.field.allocation_items'|trans }}</h4>
{{ form_errors(form.allocationItems) }}
{% if not hasAllocationTypes %}
<div class="alert alert-info">{{ 'mautic.plan.allocation_item.no_types'|trans }}</div>
{% endif %}
<p class="text-muted plan-collection-empty{% if form.allocationItems|length > 0 %} hide{% endif %}">
{{ 'mautic.plan.allocation_item.empty'|trans }}
</p>
<ul class="list-group plan-collection-list">
{% for item in form.allocationItems %}
{{ _self.allocation_item_row(item) }}
{% endfor %}
</ul>
{% if hasAllocationTypes %}
<button type="button" class="btn btn-ghost plan-collection-add">
<i class="ri-add-line"></i> {{ 'mautic.plan.allocation_item.add'|trans }}
</button>
{% endif %}
</div>
{% do form.allocationItems.setRendered %}
</div>
{# Targets #}
<div class="tab-pane bdr-w-0" id="plan-tab-targets" role="tabpanel">
<p class="text-muted">{{ 'mautic.plan.target.empty'|trans }}</p>
</div>
{# Tasks: read-only here, so that following a link doesn't drop unsaved changes to the plan. #}
<div class="tab-pane bdr-w-0" id="plan-tab-tasks" role="tabpanel">
{% if entity.id %}
<p class="text-muted small">{{ 'mautic.plan.task.manage_from_plan_page'|trans }}</p>
{% endif %}
{{ include('@Plan/Plan/_task_table.html.twig', {
'plan': entity,
'taskTree': taskTree|default([]),
'readOnly': true,
}) }}
</div>
</div>
{{ form_end(form) }}
{% endblock %}
+151
View File
@@ -0,0 +1,151 @@
{% set isIndex = 'index' == tmpl ? true : false %}
{% set tmpl = 'list' %}
{% extends isIndex ? '@MauticCore/Default/content.html.twig' : '@MauticCore/Default/raw_output.html.twig' %}
{% block mauticContent %}plan{% endblock %}
{% block headerTitle %}{{ 'mautic.plan.header.index'|trans }}{% endblock %}
{% block content %}
<div id="page-list-wrapper" class="{% if items|length > 0 or searchValue is not empty %}panel {% endif %}panel-default">
{{- include('@MauticCore/Helper/list_toolbar.html.twig', {
'searchValue': searchValue,
'action': currentRoute,
'page_actions': {
'templateButtons': {
'new': permissions['plan:plans:create'],
},
'routeBase': 'plan',
'langVar': 'plan',
},
'bulk_actions': {
'langVar': 'plan',
'routeBase': 'plan',
'templateButtons': {
'delete': permissions['plan:plans:deleteown'] or permissions['plan:plans:deleteother'],
},
},
}) -}}
<div class="page-list">
{% if items is defined and items is not empty %}
<div class="table-responsive">
<table class="table table-hover" id="planTable">
<thead>
<tr>
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'checkall': 'true',
'target': '#planTable',
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': 'plan',
'orderBy': 'p.name',
'text': 'mautic.plan.field.name',
'class': 'col-plan-name',
'default': true,
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': 'plan',
'orderBy': 'p.status',
'text': 'mautic.plan.field.status',
'class': 'col-plan-status',
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': 'plan',
'text': 'mautic.plan.field.owner',
'class': 'visible-md visible-lg col-plan-owner',
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': 'plan',
'orderBy': 'p.startDate',
'text': 'mautic.plan.field.start_date',
'class': 'visible-md visible-lg col-plan-start',
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': 'plan',
'orderBy': 'p.endDate',
'text': 'mautic.plan.field.end_date',
'class': 'visible-md visible-lg col-plan-end',
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': 'plan',
'orderBy': 'p.budgetPlanned',
'text': 'mautic.plan.field.budget_planned',
'class': 'visible-md visible-lg col-plan-budget text-right',
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': 'plan',
'orderBy': 'p.id',
'text': 'mautic.core.id',
'class': 'visible-md visible-lg col-plan-id',
}) }}
</tr>
</thead>
<tbody>
{% for item in items %}
{% set canEdit = securityHasEntityAccess(permissions['plan:plans:editown'], permissions['plan:plans:editother'], item.createdBy) %}
<tr>
<td>
{{- include('@MauticCore/Helper/list_actions.html.twig', {
'item': item,
'templateButtons': {
'edit': canEdit,
'delete': securityHasEntityAccess(permissions['plan:plans:deleteown'], permissions['plan:plans:deleteother'], item.createdBy),
},
'routeBase': 'plan',
'langVar': 'plan',
}) -}}
</td>
<td>
<div>
{{- include('@MauticCore/Helper/publishstatus_icon.html.twig', {
'item': item,
'model': 'plan',
}) -}}
<a href="{{ path('plan_action', {'objectAction': 'view', 'objectId': item.id}) }}" data-toggle="ajax">
{{ item.name }}
</a>
{% if item.category %}
<span class="label label-default">{{ item.category.title }}</span>
{% endif %}
</div>
</td>
<td>{{ item.status.labelKey|trans }}</td>
<td class="visible-md visible-lg">
{{ item.owner ? item.owner.name : 'mautic.plan.owner.none'|trans }}
</td>
<td class="visible-md visible-lg">{{ item.startDate ? dateToDate(item.startDate) : '' }}</td>
<td class="visible-md visible-lg">{{ item.endDate ? dateToDate(item.endDate) : '' }}</td>
<td class="visible-md visible-lg text-right">
{% if item.budgetPlanned is not null %}
{{ plan_money(item.budgetPlanned) }} {{ plan_currency() }}
{% endif %}
</td>
<td class="visible-md visible-lg">{{ item.id }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="panel-footer">
{{- include('@MauticCore/Helper/pagination.html.twig', {
'totalItems': totalItems,
'page': page,
'limit': limit,
'baseUrl': path('plan_index'),
'sessionVar': 'plan',
}) -}}
</div>
</div>
{% elseif searchValue is not empty %}
{{ include('@MauticCore/Helper/noresults.html.twig') }}
{% else %}
<div class="mt-80 col-md-offset-2 col-lg-offset-3 col-md-8 col-lg-5 height-auto">
{{ include('@MauticCore/Components/content-block.html.twig', {
'heading': 'mautic.plan.onboarding.heading',
'subheading': 'mautic.plan.onboarding.subheading',
'copy': 'mautic.plan.onboarding.copy',
}) }}
</div>
{% endif %}
</div>
</div>
{% endblock %}
+34
View File
@@ -0,0 +1,34 @@
{% extends '@MauticCore/Default/content.html.twig' %}
{% block mauticContent %}planTask{% endblock %}
{% block headerTitle %}
{% if entity.id %}
{{ 'mautic.plan.task.header.edit'|trans({'%name%': entity.name}) }}
{% else %}
{{ 'mautic.plan.task.header.new'|trans }}
{% endif %}
{% endblock %}
{% block content %}
{{ form_start(form) }}
<div class="box-layout">
<div class="col-md-9 height-auto bdr-r">
<div class="pa-md">
{{ form_row(form.name) }}
{{ form_row(form.description) }}
</div>
</div>
<div class="col-md-3 height-auto">
<div class="pr-lg pl-lg pt-md pb-md">
{{ form_row(form.status) }}
{{ form_row(form.startDate) }}
{{ form_row(form.endDate) }}
{{ form_row(form.plan) }}
{{ form_row(form.parent) }}
<p class="text-muted small">{{ 'mautic.plan.task.parent.help'|trans }}</p>
</div>
</div>
</div>
{{ form_end(form) }}
{% endblock %}
+132
View File
@@ -0,0 +1,132 @@
{% set isIndex = 'index' == tmpl ? true : false %}
{% set tmpl = 'list' %}
{% extends isIndex ? '@MauticCore/Default/content.html.twig' : '@MauticCore/Default/raw_output.html.twig' %}
{% block mauticContent %}planTask{% endblock %}
{% block headerTitle %}{{ 'mautic.plan.task.header.index'|trans }}{% endblock %}
{% block content %}
<div id="page-list-wrapper" class="{% if items|length > 0 or searchValue is not empty %}panel {% endif %}panel-default">
{{- include('@MauticCore/Helper/list_toolbar.html.twig', {
'searchValue': searchValue,
'action': currentRoute,
'page_actions': {
'templateButtons': {
'new': permissions['plan:tasks:create'],
},
'langVar': 'plan.task',
},
'bulk_actions': {
'langVar': 'plan.task',
'templateButtons': {
'delete': permissions['plan:tasks:deleteown'] or permissions['plan:tasks:deleteother'],
},
},
}) -}}
<div class="page-list">
{% if items is defined and items is not empty %}
<div class="table-responsive">
<table class="table table-hover" id="planTaskTable">
<thead>
<tr>
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'checkall': 'true',
'target': '#planTaskTable',
}) }}
{# Columns: ID, Name, Description, Start date, End date, Status. #}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': 'plan.task',
'orderBy': 't.id',
'text': 'mautic.core.id',
'class': 'col-plan-task-id',
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': 'plan.task',
'orderBy': 't.name',
'text': 'mautic.plan.task.field.name',
'class': 'col-plan-task-name',
'default': true,
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': 'plan.task',
'text': 'mautic.plan.task.field.description',
'class': 'visible-md visible-lg col-plan-task-description',
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': 'plan.task',
'orderBy': 't.startDate',
'text': 'mautic.plan.task.field.start_date',
'class': 'col-plan-task-start',
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': 'plan.task',
'orderBy': 't.endDate',
'text': 'mautic.plan.task.field.end_date',
'class': 'col-plan-task-end',
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': 'plan.task',
'orderBy': 't.status',
'text': 'mautic.plan.task.field.status',
'class': 'col-plan-task-status',
}) }}
</tr>
</thead>
<tbody>
{% for item in items %}
{% set canEdit = securityHasEntityAccess(permissions['plan:tasks:editown'], permissions['plan:tasks:editother'], item.createdBy) %}
<tr>
<td>
{{- include('@MauticCore/Helper/list_actions.html.twig', {
'item': item,
'templateButtons': {
'edit': canEdit,
'delete': securityHasEntityAccess(permissions['plan:tasks:deleteown'], permissions['plan:tasks:deleteother'], item.createdBy),
},
'langVar': 'plan.task',
}) -}}
</td>
<td>{{ item.id }}</td>
<td>
{% if canEdit %}
<a href="{{ path('plan_task_action', {'objectAction': 'edit', 'objectId': item.id}) }}" data-toggle="ajax">{{ item.name }}</a>
{% else %}
{{ item.name }}
{% endif %}
</td>
<td class="visible-md visible-lg text-muted">
{% set description = item.description|default('')|striptags|trim %}
{{ description|length > 120 ? description|slice(0, 120) ~ '…' : description }}
</td>
<td>{{ item.startDate ? dateToFull(item.startDate) : '' }}</td>
<td>{{ item.endDate ? dateToFull(item.endDate) : '' }}</td>
<td><span class="label {{ item.status.labelClass }}">{{ item.status.labelKey|trans }}</span></td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="panel-footer">
{{- include('@MauticCore/Helper/pagination.html.twig', {
'totalItems': totalItems,
'page': page,
'limit': limit,
'baseUrl': path('plan_task_index'),
'sessionVar': 'plan.task',
}) -}}
</div>
</div>
{% elseif searchValue is not empty %}
{{ include('@MauticCore/Helper/noresults.html.twig') }}
{% else %}
<div class="mt-80 col-md-offset-2 col-lg-offset-3 col-md-8 col-lg-5 height-auto">
{{ include('@MauticCore/Components/content-block.html.twig', {
'heading': 'mautic.plan.task.onboarding.heading',
'subheading': 'mautic.plan.task.onboarding.subheading',
'copy': 'mautic.plan.task.onboarding.copy',
}) }}
</div>
{% endif %}
</div>
</div>
{% endblock %}
+45
View File
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Security\Permissions;
use Mautic\CoreBundle\Security\Permissions\AbstractPermissions;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Permission keys: plan:plans:* and plan:tasks:* (view/edit/delete/publish own and other, create, full),
* and plan:categories:* (managing the "plan" category type).
*
* Shown under Settings > Roles. Core discovers this class from Security/Permissions/.
*/
class PlanPermissions extends AbstractPermissions
{
/**
* @param mixed[] $params
*/
public function __construct(array $params)
{
parent::__construct($params);
$this->addStandardPermissions('categories');
$this->addExtendedPermissions('plans');
$this->addExtendedPermissions('tasks');
}
public function getName(): string
{
return 'plan';
}
/**
* @param array<string, mixed> $options
* @param array<string, mixed> $data
*/
public function buildForm(FormBuilderInterface &$builder, array $options, array $data): void
{
$this->addStandardFormFields('plan', 'categories', $builder, $data);
$this->addExtendedFormFields('plan', 'plans', $builder, $data);
$this->addExtendedFormFields('plan', 'tasks', $builder, $data);
}
}
+71
View File
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Service;
use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Symfony\Component\Intl\Currencies;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* The currency of all amounts in the plugin (plan budgets, allocation costs and totals).
*
* It is a general setting, chosen by an administrator in Settings > Configuration > Plan Settings and
* stored in the local.php parameter plan_currency; users don't pick a currency. Amounts aren't converted
* when it changes: they are simply shown with the new currency.
*/
class CurrencyProvider
{
public const CONFIG_PARAMETER = 'plan_currency';
public const DEFAULT_CURRENCY = 'EUR';
/**
* The main world currencies offered in the settings (ISO 4217), most traded first.
*/
public const MAIN_CURRENCIES = [
'USD', 'EUR', 'JPY', 'GBP', 'CNY', 'AUD', 'CAD', 'CHF', 'HKD', 'SGD',
'SEK', 'NOK', 'DKK', 'NZD', 'KRW', 'INR', 'BRL', 'MXN', 'ZAR', 'PLN',
'CZK', 'HUF', 'RON', 'TRY', 'AED', 'SAR', 'ILS', 'THB', 'MYR', 'IDR',
'PHP', 'TWD', 'RUB', 'MAD', 'EGP', 'NGN', 'CLP', 'COP', 'ARS', 'PEN',
];
public function __construct(
private CoreParametersHelper $coreParametersHelper,
private TranslatorInterface $translator,
) {
}
/**
* The general currency code, e.g. "EUR".
*/
public function getCurrency(): string
{
$currency = $this->coreParametersHelper->get(self::CONFIG_PARAMETER);
return is_string($currency) && in_array($currency, self::MAIN_CURRENCIES, true) ? $currency : self::DEFAULT_CURRENCY;
}
/**
* Dropdown choices: "EUR - Euro" => "EUR", names in the user's language.
*
* @return array<string, string>
*/
public function getChoices(): array
{
$locale = $this->translator->getLocale();
$choices = [];
foreach (self::MAIN_CURRENCIES as $code) {
try {
$name = Currencies::getName($code, $locale);
} catch (\Throwable) {
$name = Currencies::exists($code) ? Currencies::getName($code) : $code;
}
$choices[$code.' - '.$name] = $code;
}
return $choices;
}
}
+214
View File
@@ -0,0 +1,214 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Service;
use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Mautic\CoreBundle\Helper\LanguageHelper;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Reads the item types set up in Settings > Configuration > Plan. There is one list of types per kind of
* plan item:
* - KIND_DESCRIPTION: types of description items (Description tab), parameter plan_description_item_types;
* - KIND_ALLOCATION: types of allocation items (Allocation tab), parameter plan_allocation_item_types.
*
* Each list is stored in local.php, in display order:
*
* [
* ['key' => 'type_1a2b3c4d', 'names' => ['en_US' => 'Context', 'fr' => 'Contexte'],
* 'descriptions' => ['en_US' => 'Why this plan exists', 'fr' => '…'], 'icon' => 'ri-lightbulb-line'],
* …
* ]
*
* Names and descriptions fall back from the user's language to the default language (the "locale"
* parameter), then to the first one filled in. The key is what items store; it never changes once the
* type is created.
*/
class ItemTypeProvider
{
public const KIND_DESCRIPTION = 'description';
public const KIND_ALLOCATION = 'allocation';
/**
* Kind => local.php parameter.
*/
public const PARAMETERS = [
self::KIND_DESCRIPTION => 'plan_description_item_types',
self::KIND_ALLOCATION => 'plan_allocation_item_types',
];
public function __construct(
private CoreParametersHelper $coreParametersHelper,
private LanguageHelper $languageHelper,
private TranslatorInterface $translator,
) {
}
public static function getParameter(string $kind): string
{
return self::PARAMETERS[$kind] ?? throw new \InvalidArgumentException('Unknown item kind: '.$kind);
}
/**
* The types as stored, cleaned up: only entries with a key, names/descriptions as locale => text.
*
* @return array<int, array{key: string, names: array<string, string>, descriptions: array<string, string>, icon?: string}>
*/
public function getTypes(string $kind): array
{
$types = $this->coreParametersHelper->get(self::getParameter($kind));
return self::normalize(is_array($types) ? $types : []);
}
/**
* Dropdown choices for an item form: localized name => key, in configured order.
*
* @return array<string, string>
*/
public function getChoices(string $kind, ?string $locale = null): array
{
$choices = [];
foreach ($this->getTypes($kind) as $type) {
$name = $this->pick($type['names'], $locale) ?: $type['key'];
// Two types with the same name would collide as choice labels; tell them apart.
$label = isset($choices[$name]) ? $name.' ('.$type['key'].')' : $name;
$choices[$label] = $type['key'];
}
return $choices;
}
/**
* Localized name of a type, or null when the key isn't a configured type of this kind.
*/
public function getName(string $kind, ?string $key, ?string $locale = null): ?string
{
$type = $this->find($kind, $key);
return null === $type ? null : ($this->pick($type['names'], $locale) ?: $type['key']);
}
/**
* Localized description of a type ('' when none), or null when the key isn't a configured type.
*/
public function getDescription(string $kind, ?string $key, ?string $locale = null): ?string
{
$type = $this->find($kind, $key);
return null === $type ? null : $this->pick($type['descriptions'], $locale, '');
}
/**
* Pictogram of a type (a Remix Icon class such as "ri-lightbulb-line"), or null when it has none or
* the key isn't a configured type. Only description item types have pictograms.
*/
public function getIcon(string $kind, ?string $key): ?string
{
return $this->find($kind, $key)['icon'] ?? null;
}
/**
* Languages the admin can fill in: the languages installed in Mautic, default language first.
*
* @return array<string, string> locale => language name
*/
public function getLanguages(): array
{
$languages = $this->languageHelper->getSupportedLanguages();
$default = $this->getDefaultLocale();
if (isset($languages[$default])) {
$languages = [$default => $languages[$default]] + $languages;
}
return $languages;
}
public function getDefaultLocale(): string
{
$locale = $this->coreParametersHelper->get('locale');
return is_string($locale) && '' !== $locale ? $locale : 'en_US';
}
/**
* @param array<mixed> $types
*
* @return array<int, array{key: string, names: array<string, string>, descriptions: array<string, string>, icon?: string}>
*/
public static function normalize(array $types): array
{
$clean = [];
foreach ($types as $type) {
if (!is_array($type) || !isset($type['key']) || !is_string($type['key']) || '' === trim($type['key'])) {
continue;
}
$entry = [
'key' => trim($type['key']),
'names' => self::texts($type['names'] ?? []),
'descriptions' => self::texts($type['descriptions'] ?? []),
];
// Pictogram (description item types only); kept only when it's one of the offered icons.
if (isset($type['icon']) && is_string($type['icon']) && Pictograms::isValid($type['icon'])) {
$entry['icon'] = $type['icon'];
}
$clean[] = $entry;
}
return $clean;
}
/**
* @param mixed $texts
*
* @return array<string, string>
*/
private static function texts($texts): array
{
if (!is_array($texts)) {
return [];
}
$clean = [];
foreach ($texts as $locale => $text) {
if (is_string($locale) && is_string($text) && '' !== trim($text)) {
$clean[$locale] = trim($text);
}
}
return $clean;
}
/**
* @return array{key: string, names: array<string, string>, descriptions: array<string, string>, icon?: string}|null
*/
private function find(string $kind, ?string $key): ?array
{
foreach ($this->getTypes($kind) as $type) {
if ($type['key'] === $key) {
return $type;
}
}
return null;
}
/**
* @param array<string, string> $texts
*/
private function pick(array $texts, ?string $locale, ?string $empty = null): string
{
$locale ??= $this->translator->getLocale();
return $texts[$locale]
?? $texts[$this->getDefaultLocale()]
?? (reset($texts) ?: ($empty ?? ''));
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Service;
/**
* Pictograms an administrator can give to a description item type (Settings > Configuration > Plan
* Settings). They are icons of the Remix Icon set that Mautic ships ("ri-*" classes); each one was
* checked against Mautic 7's icon stylesheet.
*/
final class Pictograms
{
public const ICONS = [
// Ideas, goals, guidance
'ri-lightbulb-line', 'ri-focus-3-line', 'ri-compass-3-line', 'ri-route-line', 'ri-flag-line',
'ri-rocket-line', 'ri-trophy-line', 'ri-award-line', 'ri-medal-line', 'ri-star-line',
'ri-sparkling-line', 'ri-magic-line', 'ri-key-2-line',
// Creative, style, tone
'ri-palette-line', 'ri-brush-line', 'ri-quill-pen-line', 'ri-pencil-line', 'ri-emotion-line',
'ri-emotion-happy-line', 'ri-heart-line', 'ri-thumb-up-line', 'ri-image-line', 'ri-camera-line',
'ri-video-line', 'ri-mic-line', 'ri-music-line', 'ri-layout-line', 'ri-pages-line',
'ri-presentation-line', 'ri-slideshow-line',
// Messages, content
'ri-chat-quote-line', 'ri-chat-3-line', 'ri-volume-up-line', 'ri-megaphone-line', 'ri-mail-line',
'ri-newspaper-line', 'ri-article-line', 'ri-file-text-line', 'ri-file-list-3-line',
'ri-book-open-line', 'ri-bookmark-line', 'ri-links-line',
// People, market
'ri-team-line', 'ri-group-line', 'ri-user-line', 'ri-user-heart-line', 'ri-customer-service-2-line',
'ri-hand-heart-line', 'ri-building-line', 'ri-briefcase-line', 'ri-store-2-line',
'ri-shopping-cart-line', 'ri-price-tag-3-line', 'ri-gift-line', 'ri-truck-line',
'ri-global-line', 'ri-earth-line', 'ri-map-pin-line',
// Figures, time
'ri-money-euro-circle-line', 'ri-wallet-3-line', 'ri-bar-chart-line', 'ri-pie-chart-line',
'ri-line-chart-line', 'ri-calendar-line', 'ri-time-line', 'ri-timer-line',
// Rules, status, structure
'ri-information-line', 'ri-question-line', 'ri-error-warning-line', 'ri-shield-check-line',
'ri-scales-3-line', 'ri-lock-line', 'ri-checkbox-circle-line', 'ri-list-check', 'ri-search-line',
'ri-eye-line', 'ri-tools-line', 'ri-settings-3-line', 'ri-stack-line', 'ri-node-tree', 'ri-leaf-line',
];
public static function isValid(?string $icon): bool
{
return null !== $icon && in_array($icon, self::ICONS, true);
}
/**
* Dropdown choices: readable name => icon class, e.g. "Lightbulb" => "ri-lightbulb-line".
*
* @return array<string, string>
*/
public static function getChoices(): array
{
$choices = [];
foreach (self::ICONS as $icon) {
$name = preg_replace(['/^ri-/', '/-line$/'], '', $icon);
$name = ucfirst(str_replace('-', ' ', (string) $name));
$choices[$name] = $icon;
}
return $choices;
}
}
+151
View File
@@ -0,0 +1,151 @@
mautic.plugin.plan.name="Plan"
mautic.plan.menu.root="Planning"
mautic.plan.menu.index="Plans"
mautic.plan.tab.details="Details"
mautic.plan.tab.description="Description"
mautic.plan.tab.objectives="Objectives"
mautic.plan.tab.allocation="Allocation"
mautic.plan.tab.targets="Targets"
mautic.plan.tab.tasks="Tasks"
mautic.plan.value.none="None"
mautic.plan.target.empty="No targets yet."
mautic.plan.task.empty="No tasks yet."
mautic.plan.header.index="Plans"
mautic.plan.header.new="New plan"
mautic.plan.header.edit="Edit plan - %name%"
mautic.plan.onboarding.heading="No plans yet"
mautic.plan.onboarding.subheading="Create your first plan to get started."
mautic.plan.onboarding.copy="Use the New button above to create a plan, then track its status, dates and budget here."
; Used by core's standard CRUD controller and buttons (translation base mautic.plan).
mautic.plan.error.notfound="No plan with the ID %id% was found."
mautic.plan.form.confirmdelete="Delete the plan, %name%? Its objectives and tasks are deleted too."
mautic.plan.form.confirmbatchdelete="Delete the selected plans? Their objectives and tasks are deleted too."
; Category type label (Settings > Categories).
mautic.plan.category.type="Plan"
; Settings > Roles.
mautic.plan.permissions.header="Plan Permissions"
mautic.plan.permissions.plans="Plans - User has access to"
mautic.plan.permissions.tasks="Tasks - User has access to"
; Tasks (Planning > Tasks). Translation base mautic.plan.task.
mautic.plan.task.menu.index="Tasks"
mautic.plan.task.header.index="Tasks"
mautic.plan.task.header.new="New task"
mautic.plan.task.header.edit="Edit task - %name%"
mautic.plan.task.error.notfound="No task with the ID %id% was found."
mautic.plan.task.form.confirmdelete="Delete the task, %name%? Its sub-tasks are kept and become top-level tasks."
mautic.plan.task.form.confirmbatchdelete="Delete the selected tasks? Their sub-tasks are kept and become top-level tasks."
mautic.plan.task.onboarding.heading="No tasks yet"
mautic.plan.task.onboarding.subheading="Tasks break a plan down into work to do."
mautic.plan.task.onboarding.copy="Use the New button above, or Add task on a plan's Tasks tab. A task belongs to one plan and can be a sub-task of another task in the same plan."
mautic.plan.task.field.name="Name"
mautic.plan.task.field.description="Description"
mautic.plan.task.field.plan="Plan"
mautic.plan.task.field.parent="Parent task"
mautic.plan.task.field.start_date="Start date"
mautic.plan.task.field.end_date="End date"
mautic.plan.task.field.status="Status"
mautic.plan.task.status.new="New"
mautic.plan.task.status.todo="To do"
mautic.plan.task.status.in_progress="In progress"
mautic.plan.task.status.done="Done"
mautic.plan.task.parent.none="None (top-level task)"
mautic.plan.task.parent.help="A parent task must be in the same plan."
mautic.plan.task.add="Add task"
mautic.plan.task.save_plan_first="Save the plan first, then add tasks from its page."
mautic.plan.task.manage_from_plan_page="Add and edit tasks from the plan's page, after saving."
mautic.plan.field.name="Name"
mautic.plan.field.status="Status"
mautic.plan.field.owner="Owner"
mautic.plan.field.start_date="Start date"
mautic.plan.field.end_date="End date"
mautic.plan.field.completed_at="Completed at"
mautic.plan.field.budget_planned="Planned budget"
mautic.plan.field.version="Version"
mautic.plan.field.objectives="Objectives"
mautic.plan.field.description_items="Description items"
mautic.plan.field.allocation_items="Allocation items"
mautic.plan.objective.field.title="Title"
mautic.plan.objective.field.description="Description"
mautic.plan.objective.field.is_achieved="Achieved"
mautic.plan.objective.add="Add objective"
mautic.plan.objective.remove="Remove objective"
mautic.plan.objective.drag="Drag to reorder"
mautic.plan.objective.empty="No objectives yet."
mautic.plan.objective.progress="%achieved% of %total% achieved"
mautic.plan.objective.achieved="Achieved"
mautic.plan.objective.not_achieved="Not achieved"
mautic.plan.owner.none="No owner"
mautic.plan.status.draft="Draft"
mautic.plan.status.planned="Planned"
mautic.plan.status.active="Active"
mautic.plan.status.paused="Paused"
mautic.plan.status.completed="Completed"
mautic.plan.status.archived="Archived"
; Description items (the plan's Description tab).
mautic.plan.description_item.field.type="Type"
mautic.plan.description_item.field.description="Description"
mautic.plan.description_item.add="Add description item"
mautic.plan.description_item.remove="Remove description item"
mautic.plan.description_item.drag="Drag to reorder"
mautic.plan.description_item.empty="No description items yet."
mautic.plan.description_item.no_types="No description item types are set up yet. An administrator can add them in Settings > Configuration > Plan Settings."
mautic.plan.description_item.type.unknown="Unknown type (%key%)"
; Settings > Configuration > Plan. Core builds the tab title key from the form alias.
mautic.config.tab.planconfig="Plan Settings"
mautic.plan.config.description="Settings of the Plan plugin."
mautic.plan.config.section.description_item_types="Description item types"
mautic.plan.config.section.description_item_types.help="The types offered for the items of a plan's Description tab, in this order. Give each type a name and a description in each language; the default language is required. Users see their own language, or the default language when it's empty."
mautic.plan.config.types.empty="No types yet."
mautic.plan.config.type.add="Add type"
mautic.plan.config.type.remove="Remove type"
mautic.plan.config.type.language="Language"
mautic.plan.config.type.name="Name"
mautic.plan.config.type.description="Description"
; Allocation items (the plan's Allocation tab).
mautic.plan.allocation_item.field.type="Type"
mautic.plan.allocation_item.field.name="Name"
mautic.plan.allocation_item.field.description="Description"
mautic.plan.allocation_item.field.planned_cost="Planned cost"
mautic.plan.allocation_item.field.real_cost="Real cost"
mautic.plan.allocation_item.add="Add allocation item"
mautic.plan.allocation_item.remove="Remove allocation item"
mautic.plan.allocation_item.drag="Drag to reorder"
mautic.plan.allocation_item.empty="No allocation items yet."
mautic.plan.allocation_item.no_types="No allocation item types are set up yet. An administrator can add them in Settings > Configuration > Plan Settings."
mautic.plan.allocation.total="Total"
; Plan page header: total costs of the allocation items, in the general currency.
mautic.plan.header.total_planned="Planned: %amount% %currency%"
mautic.plan.header.total_planned.tooltip="Total planned cost of the allocation items"
mautic.plan.header.total_real="Real: %amount% %currency%"
mautic.plan.header.total_real.tooltip="Total real cost of the allocation items, within the planned cost"
mautic.plan.header.total_real.over="Total real cost of the allocation items, above the planned cost"
mautic.plan.task.subtask_of="Sub-task of %parent%"
mautic.plan.task.subtasks="Number of sub-tasks"
mautic.plan.config.section.allocation_item_types="Allocation item types"
mautic.plan.config.section.allocation_item_types.help="The types offered for the cost lines of a plan's Allocation tab, in this order. Give each type a name and a description in each language; the default language is required. Users see their own language, or the default language when it's empty."
mautic.plan.description_item.field.pictogram="Pictogram"
mautic.plan.config.section.general="General"
mautic.plan.config.currency="Currency"
mautic.plan.config.currency.tooltip="The currency of every amount in plans: budgets, costs and totals."
mautic.plan.config.currency.help="Users don't choose a currency: every budget, cost and total is in this currency. Changing it doesn't convert existing amounts."
mautic.plan.config.type.icon="Pictogram"
mautic.plan.config.type.icon.none="No pictogram"
+11
View File
@@ -0,0 +1,11 @@
mautic.plan.owner.required="An owner is required."
mautic.plan.end_date.before_start_date="The end date must be on or after the start date."
mautic.plan.version.range="The version must be a whole number from 1 to 99."
mautic.plan.objective.title.required="An objective needs a title."
mautic.plan.task.plan.required="A task must be assigned to a plan."
mautic.plan.task.parent.other_plan="The parent task must be in the same plan."
mautic.plan.task.parent.loop="A task can't be its own parent, or a sub-task of one of its sub-tasks."
mautic.plan.description_item.type.required="Choose a type."
mautic.plan.config.type.name.required="A type needs a name in the default language."
mautic.plan.config.type.in_use="These types are used by description items and can't be removed: %types%. Change those items to another type first."
mautic.plan.allocation_item.type.required="Choose a type."
+38
View File
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Twig;
use MauticPlugin\PlanBundle\Service\CurrencyProvider;
use MauticPlugin\PlanBundle\Service\ItemTypeProvider;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* Twig functions for the plan templates (kind: "description" or "allocation"):
* plan_item_type_name(kind, key) localized type name, or null for an unknown key
* plan_item_type_description(kind, key) localized type description ('' when none)
* plan_item_type_icon(kind, key) the type's pictogram (Remix Icon class), or null
* plan_currency() the general currency code, e.g. EUR
* plan_money(amount) an amount with 2 decimals, e.g. 12,500.00
*/
class PlanExtension extends AbstractExtension
{
public function __construct(
private ItemTypeProvider $typeProvider,
private CurrencyProvider $currencyProvider,
) {
}
public function getFunctions(): array
{
return [
new TwigFunction('plan_item_type_name', fn (string $kind, ?string $key): ?string => $this->typeProvider->getName($kind, $key)),
new TwigFunction('plan_item_type_description', fn (string $kind, ?string $key): ?string => $this->typeProvider->getDescription($kind, $key)),
new TwigFunction('plan_item_type_icon', fn (string $kind, ?string $key): ?string => $this->typeProvider->getIcon($kind, $key)),
new TwigFunction('plan_currency', fn (): string => $this->currencyProvider->getCurrency()),
new TwigFunction('plan_money', fn ($amount): string => number_format((float) $amount, 2)),
];
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\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 EndDateAfterStartDate extends Constraint
{
public string $message = 'mautic.plan.end_date.before_start_date';
public function getTargets(): string
{
return self::CLASS_CONSTRAINT;
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Validator\Constraints;
use MauticPlugin\PlanBundle\Entity\DateRangeInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
class EndDateAfterStartDateValidator extends ConstraintValidator
{
public function validate(mixed $value, Constraint $constraint): void
{
if (!$constraint instanceof EndDateAfterStartDate) {
throw new UnexpectedTypeException($constraint, EndDateAfterStartDate::class);
}
if (null === $value) {
return;
}
if (!$value instanceof DateRangeInterface) {
throw new UnexpectedValueException($value, DateRangeInterface::class);
}
$start = $value->getStartDate();
$end = $value->getEndDate();
if (null === $start || null === $end || $end >= $start) {
return;
}
$this->context->buildViolation($constraint->message)
->atPath('endDate')
->addViolation();
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* Class constraint on Task: the parent task must be in the same plan, and must not be the task itself
* or one of its sub-tasks (which would create a loop).
*/
class ValidTaskParent extends Constraint
{
public string $otherPlanMessage = 'mautic.plan.task.parent.other_plan';
public string $loopMessage = 'mautic.plan.task.parent.loop';
public function getTargets(): string
{
return self::CLASS_CONSTRAINT;
}
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\PlanBundle\Validator\Constraints;
use MauticPlugin\PlanBundle\Entity\Task;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
class ValidTaskParentValidator extends ConstraintValidator
{
public function validate(mixed $value, Constraint $constraint): void
{
if (!$constraint instanceof ValidTaskParent) {
throw new UnexpectedTypeException($constraint, ValidTaskParent::class);
}
if (null === $value) {
return;
}
if (!$value instanceof Task) {
throw new UnexpectedValueException($value, Task::class);
}
$parent = $value->getParent();
if (null === $parent) {
return;
}
// The parent's ancestors include the task itself: the task is its own parent or a sub-task's child.
if ($parent->hasAncestorOrSelf($value)) {
$this->context->buildViolation($constraint->loopMessage)
->atPath('parent')
->addViolation();
return;
}
$plan = $value->getPlan();
$parentPlan = $parent->getPlan();
if (null !== $plan && null !== $parentPlan && $plan->getId() !== $parentPlan->getId()) {
$this->context->buildViolation($constraint->otherPlanMessage)
->atPath('parent')
->addViolation();
}
}
}
+19
View File
@@ -0,0 +1,19 @@
{
"name": "experiential/mautic-plan-bundle",
"description": "Plan plugin for Mautic",
"type": "mautic-plugin",
"license": "GPL-3.0-or-later",
"keywords": ["mautic", "plugin", "plan"],
"require": {
"php": ">=8.2",
"mautic/core-lib": "^7.0"
},
"autoload": {
"psr-4": {
"MauticPlugin\\PlanBundle\\": ""
}
},
"extra": {
"install-directory-name": "PlanBundle"
}
}
+176
View File
@@ -0,0 +1,176 @@
# Mautic Plan plugin
A custom Mautic 7 plugin (`PlanBundle`) for managing plans: a name, status, owner, dates, budget and category.
This repository holds only the plugin source. The bundle files are at the repository root, and Mautic loads them from `docroot/plugins/PlanBundle`.
## Installation
1. Copy or clone this repository into your Mautic installation as `docroot/plugins/PlanBundle`. The folder name must be `PlanBundle`.
2. Clear the cache and register the plugin:
```bash
php bin/console cache:clear
php bin/console mautic:plugins:reload
```
3. In Mautic, go to **Settings > Plugins**, open **Plan** and publish it.
Plans are listed under **Planning > Plans** in the main menu (URL `/s/plans`), and tasks under **Planning > Tasks** (URL `/s/plan-tasks`). Users who aren't administrators need a role with the **Plan Permissions** set in **Settings > Roles**.
Before using the items of a plan's **Description** and **Allocation** tabs, an administrator sets up their types in **Settings > Configuration > Plan Settings**.
## Development
Run the plugin in the shared Docker environment, [mautic-dev-env](https://git.mt3.solutions/MT3S/mautic-dev-env). Clone both repositories side by side:
```
~/projects/
mautic-plugin-plan/
```
In the dev environment's `.env`, point it at this plugin:
```
PLUGIN_PLAN_PATH=../mautic-plugin-plan
```
Run all commands from the `mautic-dev-env` folder:
```bash
cd ../mautic-dev-env
./dev.sh up # start the stack
./dev.sh install # first time only: install Mautic and register the plugin
./dev.sh reload # after changing Config/config.php, services or entities
```
For the complete list of commands, see the dev environment's README.
## Plugin structure
The plugin uses the IntegrationsBundle conventions:
- `PlanBundle.php`: the bundle class
- `Config/config.php`: metadata, routes, menu and integration service tags
- `Config/services.php`: autowires and autoconfigures every class in the bundle
- `DependencyInjection/PlanExtension.php`: loads `Config/services.php`
- `Integration/PlanIntegration.php`: the integration that is listed on the Plugins page
- `Integration/Support/ConfigSupport.php`: the configuration form for the integration
- `Translations/en_US/messages.ini` and `validators.ini`: UI strings and validation messages
### Pages and permissions
- `Controller/PlanController.php`: list, detail page, create, edit and delete (single and batch), built on core's `AbstractStandardFormController`
- `Resources/views/Plan/list.html.twig`: the list. A plan's name opens its detail page.
- `Resources/views/Plan/form.html.twig` and `details.html.twig`: the create/edit form and the detail page. Both have the same six tabs, from `_tabs.html.twig`: **Details**, **Description** (description items), **Objectives**, **Allocation** (planned budget, currency and allocation items), **Targets** and **Tasks**.
- `Resources/views/Plan/_task_table.html.twig`: the plan's tasks in the Tasks tab. It has the same columns as **Planning > Tasks** (ID, Name, Description, Start date, End date, Status), in tree order: each task is followed by its sub-tasks, indented, and a task's name shows its number of sub-tasks. On the detail page it has an **Add task** button and links to each task. On the plan form it is read-only, so that following a link doesn't drop unsaved changes.
- `Controller/TaskController.php` and `Resources/views/Task/`: the task list, and the create/edit form (**Planning > Tasks**). `new?plan=ID` preselects the plan. After Save or Cancel, the user goes back to where the form was opened from. Opened from **Planning > Tasks**, that's the task list. Opened from a plan's Tasks tab, whose links carry `returnTo=plan`, that's the plan (its new plan, if the task was moved). The origin is stored in the session when the form is opened, because the form posts without the query string.
- `Assets/js/plan.js`: on the form, the objectives editor (add, remove, drag-and-drop ordering), and after a failed save, marking the tabs that contain errors with an icon and opening the first one. Started by `Mautic.planOnLoad()`.
The plan's tab panes deliberately have no Bootstrap `fade` class. Core reopens the last tab used on a page (`12.tabs.js`), and the plugin opens the tab with an error after a failed save. With `fade`, those two `tab('show')` calls overlapped within the 150 ms transition and left two panes visible at once, so the Tasks tab also showed the objectives.
Which tab opens on a plan's detail page and form (`Mautic.planInitTabs`):
- The tab last used for a plan is remembered for the browser session (`sessionStorage`, key `mautic.plan.tab.<plan id>`). The detail page and the form both reopen it, so Edit and Save keep the current tab. Cancel goes to the plans list, as in core.
- After a failed save, the first tab with an error opens instead, and every tab with an error gets a warning icon.
- Core reopens its own remembered tab on page load and after every Ajax request (`Mautic.rememberActiveTabs`), in an order that varies. `plan.js` wraps that function, so the plan's choice is applied right after core's restore, and only during the page load.
- A tab counts as having an error only if it shows an error message (`.help-block .alert-danger`), not just because an element has the `has-error` class. Mautic's own `checkbox_row` theme adds `has-error` to every checkbox: it tests `errors|length is not empty`, and `0` isn't "empty" in Twig. Every objective's "Achieved" checkbox would otherwise put a warning icon on the Objectives tab, and opening that tab on load looked like a jump to Objectives.
- `Security/Permissions/PlanPermissions.php`: the permissions shown in **Settings > Roles**
The main menu has a top-level **Planning** entry, with **Plans** and **Tasks** as its items. Add future planning pages as more children of `mautic.plan.menu.root` in `Config/config.php`.
The **Targets** tab only shows an empty state for now.
| Route | URL | Purpose |
| --- | --- | --- |
| `plan_index` | `/s/plans/{page}` | Plan list, with search on name |
| `plan_action` | `/s/plans/{objectAction}/{objectId}` | `view`, `new`, `edit`, `delete`, `batchDelete` |
| `plan_task_index` | `/s/plan-tasks/{page}` | Task list, with search on name and description |
| `plan_task_action` | `/s/plan-tasks/{objectAction}/{objectId}` | `new` (optional `?plan=ID`), `edit`, `delete`, `batchDelete` |
The plan templates don't pass `routeBase` to core's button helpers (`page_actions`, `list_actions`) when a "close" button is involved: from `routeBase`, core builds `mautic_<routeBase>_*` route names, which don't exist in this plugin. The other buttons use the `actionRoute` (`plan_action`) that the controller passes to the template.
Permission keys:
- `plan:plans:*` and `plan:tasks:*`: `viewown`, `viewother`, `editown`, `editother`, `create`, `deleteown`, `deleteother`, `publishown`, `publishother`, `full`. "Own" means items the user created (`createdBy`), as in core objects.
- `plan:categories:*`: managing the `plan` category type.
### The Plan object
- `Entity/Plan.php`: the entity (table `plans`), with its Doctrine mapping and validation rules
- `Entity/PlanStatus.php`: the status enum (`draft`, `planned`, `active`, `paused`, `completed`, `archived`)
- `Entity/PlanRepository.php`: the repository
- `Entity/PlanObjective.php` and `PlanObjectiveRepository.php`: a plan's objectives (table `plan_objectives`): title, description, position and an "achieved" flag
- `Model/PlanModel.php`: the model, available as `mautic.plan.model.plan` or with `getModel('plan')`. A new plan from `getEntity()` has the current user as owner.
- `Entity/PlanDescriptionItem.php` and `PlanDescriptionItemRepository.php`: a plan's description items (table `plan_description_items`): type, description and position. They make up the Description tab and replace the former `description` field.
- `Form/Type/PlanType.php`, `PlanObjectiveType.php` and `PlanDescriptionItemType.php`: the create and edit form, with the objectives and the description items as collections
- `Validator/Constraints/EndDateAfterStartDate.php`: the end date must be on or after the start date, when both are set. Used by plans and tasks, through `Entity/DateRangeInterface.php`.
Behaviour to know about:
- Setting the status to `completed` from another status sets `completedAt` to the current time. Moving a completed plan to any other status clears `completedAt`.
- `owner` is required by validation, but the column is nullable: if the user is deleted, the owner becomes `NULL` (`ON DELETE SET NULL`), and the plan must be given a new owner before it can be saved again.
- Categories use the core CategoryBundle with the `plan` type (**Settings > Categories**).
- There is one currency for every amount: plan budgets, allocation costs and totals. It's a general setting, the **Currency** dropdown in **Settings > Configuration > Plan Settings** (parameter `plan_currency`, `EUR` by default), offering 40 main world currencies (`Service/CurrencyProvider.php`). Users never choose a currency, and amount fields show it next to the input. Changing it doesn't convert existing amounts: they're simply shown with the new currency.
- `version` is a whole number from 1 to 99, and new plans start at 1. It is edited by hand and isn't related to Doctrine's optimistic locking.
- Objectives belong to their plan: they are saved with it, deleted with it (`ON DELETE CASCADE` in the database too), and an objective removed from the form is deleted (`orphanRemoval`). They are always loaded ordered by `position`. On save, the model renumbers positions to 0, 1, 2… in their current order. Description items follow the same rules.
- `getObjectives()` and `getDescriptionItems()` return the rows sorted by position, as a new collection. The mapping's `orderBy` isn't enough: after a reorder, the page shown right after saving uses the collection already loaded, in its old order.
- Text typed in the plan form, including in objectives and description items, is kept as typed: line breaks, `&` and quotes are preserved, and HTML tags are removed. This depends on `PlanType` passing a mask array to `CleanFormSubscriber`. Without one, core HTML-encodes every value, again on each save.
### Typed items: description items and allocation items
- A **description item** (Description tab, `Entity/PlanDescriptionItem.php`) has a type and a description. More fields are planned.
- An **allocation item** (Allocation tab, `Entity/PlanAllocationItem.php`, table `plan_allocation_items`) is a cost line: type, name (optional), description, planned cost and real cost. Costs are `DECIMAL(12,2)`, in the general currency.
- Both kinds are edited inside the plan form, like objectives: add, remove, drag to reorder. They're saved and deleted with the plan.
- An administrator sets up each kind's types in **Settings > Configuration > Plan Settings**, in two sections. Each type has a name and a description for each language installed in Mautic, and the default language (the `locale` parameter) requires a name. Users see their own language, or the default language when theirs is empty. The order of the types is the order of the dropdown.
- The types are stored in `config/local.php`, in the `plan_description_item_types` and `plan_allocation_item_types` parameters. Read them with `Service/ItemTypeProvider.php`, passing the kind (`description` or `allocation`). In templates, use the Twig functions `plan_item_type_name(kind, key)`, `plan_item_type_description(kind, key)` and `plan_item_type_icon(kind, key)`, plus `plan_currency()` and `plan_money(amount)` (`Twig/PlanExtension.php`).
- **Description item types have a pictogram**, chosen by the administrator from a list of Remix Icons that Mautic ships (`Service/Pictograms.php`, each checked against Mautic 7's icon stylesheet), with a live preview. It's stored as `icon` in the type. On the plan form it appears next to the type dropdown when a type is chosen. On the detail page, the Description tab is a table with three columns: Pictogram, Type, Description. Allocation item types have no pictogram.
- Each type has a hidden key, generated when it's created and never changed. Items store that key, so renaming a type renames it everywhere.
- A type that items use can't be removed: the configuration isn't saved, and the error lists the types and how many items use them (`EventListener/ConfigSubscriber.php`, on `CONFIG_PRE_SAVE`).
- On the plan form, the selected type's description is shown under the type dropdown. When no types are set up, the tab says where to set them up.
- Files: `Form/Type/ConfigType.php`, `ItemTypeConfigType.php`, `PlanDescriptionItemType.php`, `PlanAllocationItemType.php` and `Resources/views/FormTheme/Config/_config_planconfig_widget.html.twig`. Adding and removing types is handled in `Assets/js/plan.js`.
### Cost totals
- `Plan::getAllocationTotals()` adds up the allocation items' planned and real costs, in the general currency. The sums are done in cents, as integers.
- The plan detail page shows them under the title, after the plan status, as on an email's page (`publishStatus` block): a "Planned" tag and a "Real" tag. A real total above the planned total is red, otherwise green.
- The Allocation tab of the detail page lists the cost lines, followed by a total row.
- `isAchieved` is toggled by hand on the form for now.
### The Task object
- `Entity/Task.php` and `TaskRepository.php`: a task (table `plan_tasks`): name, description, plan, optional parent task, optional start and end dates, and status
- `Entity/TaskStatus.php`: the status enum. The order of its cases is the order of the dropdown: `new` (New, the default), `todo` (To do), `in_progress` (In progress), `done` (Done). Stored as `VARCHAR(20)`, indexed.
- `Model/TaskModel.php`: the model, available as `mautic.plan.model.task` or with `getModel('plan.task')`. `getTaskTree($plan)` returns a plan's tasks in tree order, with their depth.
- `Form/Type/TaskType.php`: the create and edit form
- `Validator/Constraints/ValidTaskParent.php`: the parent task must be in the same plan, and must not be the task itself or one of its sub-tasks
Behaviour to know about:
- A task must belong to a plan. A plan can have any number of tasks, including none.
- A task's end date must be on or after its start date, when both are set.
- The task list (**Planning > Tasks**) shows these columns, in this order: ID, Name, Description (first 120 characters), Start date, End date, Status. Every column except Description can be sorted.
- Deleting a plan deletes its tasks (`plan_id` `ON DELETE CASCADE`).
- Deleting a task keeps its sub-tasks, which become top-level tasks (`parent_id` `ON DELETE SET NULL`).
- Tasks are edited on their own pages, not inside the plan form: a task can only be picked as a parent once it exists.
After you change `Assets/js/plan.js`, run `php bin/console mautic:assets:generate` (in the dev environment, `./dev.sh console mautic:assets:generate`), because production mode bundles plugin scripts into `app.js`.
### Database schema
Mautic creates the `plans` table from the entity mapping when it installs the plugin. However, the installer drops foreign keys that point to core tables (`users`, `categories`). `Migrations/Version_0_2_0.php` adds them and only runs when they are missing. Core runs plugin migrations when the plugin version changes, and `EventListener/PluginInstallSubscriber.php` also runs them right after a fresh install.
`Migrations/Version_0_3_0.php` adds `plans.version` and the `plan_objectives` table to installs created before 0.3.0. `Migrations/Version_0_4_0.php` adds the `plan_tasks` table and its two foreign keys, and adds the foreign keys to an existing `plan_tasks` table that lacks them. `Migrations/Version_0_5_0.php` adds the tasks' `start_date`, `end_date` and `status` columns, and existing tasks get the status `new`. `Migrations/Version_0_6_0.php` creates `plan_description_items` with its foreign key to `plans` (`ON DELETE CASCADE`), and drops `plans.description`, deleting its content. `Migrations/Version_0_7_0.php` creates `plan_allocation_items` with its foreign key to `plans` (`ON DELETE CASCADE`). `Migrations/Version_0_8_0.php` drops the currency columns (`plans.currency`, `plan_allocation_items.planned_currency` and `real_currency`), since every amount is now in the general currency. Every migration checks the schema first, so it's safe to run again.
If a migration builds its `CREATE TABLE` with Doctrine's `SchemaTool`, keep only the statement for its own table. `SchemaTool` also returns statements for other tables, such as Symfony Messenger's `messenger_messages`. Those fail on an existing install, and the migration engine then reports "There is no active transaction" instead of the real error.
When you change the schema, add a migration in `Migrations/` and increase `version` in `Config/config.php`, then run `./dev.sh reload`.
## Naming conventions
To avoid collisions with other plugins, such as UTM Manager, every identifier in this bundle is prefixed with `plan`:
- Service IDs: `mautic.plan.*`
- Route names: `plan_*`
- Translation keys: `mautic.plan.*`, plus `mautic.plugin.plan.name`
- Permission keys: `plan:*`
View File
Whitespace-only changes.