From f6684f3b2e733439ea9dd3a6dec94bddb28a3ab6 Mon Sep 17 00:00:00 2001 From: Alexandre Gain <270117159+alexandregain-xprl@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:31:49 +0100 Subject: [PATCH] first delivery --- .gitignore | 6 + Assets/img/icon.svg | 1 + Assets/js/plan.js | 216 ++++++++ Config/config.php | 97 ++++ Config/services.php | 30 + Controller/PlanController.php | 173 ++++++ Controller/TaskController.php | 186 +++++++ DependencyInjection/PlanExtension.php | 25 + Entity/CountsItemsByTypeTrait.php | 33 ++ Entity/DateRangeInterface.php | 15 + Entity/Plan.php | 514 ++++++++++++++++++ Entity/PlanAllocationItem.php | 192 +++++++ Entity/PlanAllocationItemRepository.php | 20 + Entity/PlanDescriptionItem.php | 131 +++++ Entity/PlanDescriptionItemRepository.php | 20 + Entity/PlanObjective.php | 153 ++++++ Entity/PlanObjectiveRepository.php | 18 + Entity/PlanRepository.php | 57 ++ Entity/PlanStatus.php | 20 + Entity/Task.php | 251 +++++++++ Entity/TaskRepository.php | 74 +++ Entity/TaskStatus.php | 34 ++ EventListener/ConfigSubscriber.php | 90 +++ EventListener/PluginInstallSubscriber.php | 43 ++ Form/Type/ConfigType.php | 70 +++ Form/Type/ItemTypeConfigType.php | 109 ++++ Form/Type/PlanAllocationItemType.php | 90 +++ Form/Type/PlanDescriptionItemType.php | 72 +++ Form/Type/PlanObjectiveType.php | 60 ++ Form/Type/PlanType.php | 167 ++++++ Form/Type/TaskType.php | 124 +++++ Integration/PlanIntegration.php | 32 ++ Integration/Support/ConfigSupport.php | 14 + Migrations/Version_0_2_0.php | 98 ++++ Migrations/Version_0_3_0.php | 58 ++ Migrations/Version_0_4_0.php | 98 ++++ Migrations/Version_0_5_0.php | 62 +++ Migrations/Version_0_6_0.php | 94 ++++ Migrations/Version_0_7_0.php | 79 +++ Migrations/Version_0_8_0.php | 65 +++ Model/PlanModel.php | 77 +++ Model/TaskModel.php | 91 ++++ PlanBundle.php | 11 + .../_config_planconfig_widget.html.twig | 96 ++++ Resources/views/Plan/_tabs.html.twig | 31 ++ Resources/views/Plan/_task_table.html.twig | 78 +++ Resources/views/Plan/details.html.twig | 294 ++++++++++ Resources/views/Plan/form.html.twig | 216 ++++++++ Resources/views/Plan/list.html.twig | 151 +++++ Resources/views/Task/form.html.twig | 34 ++ Resources/views/Task/list.html.twig | 132 +++++ Security/Permissions/PlanPermissions.php | 45 ++ Service/CurrencyProvider.php | 71 +++ Service/ItemTypeProvider.php | 214 ++++++++ Service/Pictograms.php | 64 +++ Translations/en_US/messages.ini | 151 +++++ Translations/en_US/validators.ini | 11 + Twig/PlanExtension.php | 38 ++ .../Constraints/EndDateAfterStartDate.php | 21 + .../EndDateAfterStartDateValidator.php | 40 ++ Validator/Constraints/ValidTaskParent.php | 23 + .../Constraints/ValidTaskParentValidator.php | 53 ++ composer.json | 19 + readme.md | 176 ++++++ test.fr | 0 65 files changed, 5828 insertions(+) create mode 100644 .gitignore create mode 100644 Assets/img/icon.svg create mode 100644 Assets/js/plan.js create mode 100644 Config/config.php create mode 100644 Config/services.php create mode 100644 Controller/PlanController.php create mode 100644 Controller/TaskController.php create mode 100644 DependencyInjection/PlanExtension.php create mode 100644 Entity/CountsItemsByTypeTrait.php create mode 100644 Entity/DateRangeInterface.php create mode 100644 Entity/Plan.php create mode 100644 Entity/PlanAllocationItem.php create mode 100644 Entity/PlanAllocationItemRepository.php create mode 100644 Entity/PlanDescriptionItem.php create mode 100644 Entity/PlanDescriptionItemRepository.php create mode 100644 Entity/PlanObjective.php create mode 100644 Entity/PlanObjectiveRepository.php create mode 100644 Entity/PlanRepository.php create mode 100644 Entity/PlanStatus.php create mode 100644 Entity/Task.php create mode 100644 Entity/TaskRepository.php create mode 100644 Entity/TaskStatus.php create mode 100644 EventListener/ConfigSubscriber.php create mode 100644 EventListener/PluginInstallSubscriber.php create mode 100644 Form/Type/ConfigType.php create mode 100644 Form/Type/ItemTypeConfigType.php create mode 100644 Form/Type/PlanAllocationItemType.php create mode 100644 Form/Type/PlanDescriptionItemType.php create mode 100644 Form/Type/PlanObjectiveType.php create mode 100644 Form/Type/PlanType.php create mode 100644 Form/Type/TaskType.php create mode 100644 Integration/PlanIntegration.php create mode 100644 Integration/Support/ConfigSupport.php create mode 100644 Migrations/Version_0_2_0.php create mode 100644 Migrations/Version_0_3_0.php create mode 100644 Migrations/Version_0_4_0.php create mode 100644 Migrations/Version_0_5_0.php create mode 100644 Migrations/Version_0_6_0.php create mode 100644 Migrations/Version_0_7_0.php create mode 100644 Migrations/Version_0_8_0.php create mode 100644 Model/PlanModel.php create mode 100644 Model/TaskModel.php create mode 100644 PlanBundle.php create mode 100644 Resources/views/FormTheme/Config/_config_planconfig_widget.html.twig create mode 100644 Resources/views/Plan/_tabs.html.twig create mode 100644 Resources/views/Plan/_task_table.html.twig create mode 100644 Resources/views/Plan/details.html.twig create mode 100644 Resources/views/Plan/form.html.twig create mode 100644 Resources/views/Plan/list.html.twig create mode 100644 Resources/views/Task/form.html.twig create mode 100644 Resources/views/Task/list.html.twig create mode 100644 Security/Permissions/PlanPermissions.php create mode 100644 Service/CurrencyProvider.php create mode 100644 Service/ItemTypeProvider.php create mode 100644 Service/Pictograms.php create mode 100644 Translations/en_US/messages.ini create mode 100644 Translations/en_US/validators.ini create mode 100644 Twig/PlanExtension.php create mode 100644 Validator/Constraints/EndDateAfterStartDate.php create mode 100644 Validator/Constraints/EndDateAfterStartDateValidator.php create mode 100644 Validator/Constraints/ValidTaskParent.php create mode 100644 Validator/Constraints/ValidTaskParentValidator.php create mode 100644 composer.json create mode 100644 readme.md delete mode 100644 test.fr diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1f5bb70 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/vendor/ +/composer.lock +.idea/ +*.log +.vscode/ +.claude/ \ No newline at end of file diff --git a/Assets/img/icon.svg b/Assets/img/icon.svg new file mode 100644 index 0000000..253af1c --- /dev/null +++ b/Assets/img/icon.svg @@ -0,0 +1 @@ +PLAN diff --git a/Assets/js/plan.js b/Assets/js/plan.js new file mode 100644 index 0000000..b0f3db8 --- /dev/null +++ b/Assets/js/plan.js @@ -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(' '); + 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); + }); +})(); diff --git a/Config/config.php b/Config/config.php new file mode 100644 index 0000000..df7b130 --- /dev/null +++ b/Config/config.php @@ -0,0 +1,97 @@ + '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' => [], + ], +]; diff --git a/Config/services.php b/Config/services.php new file mode 100644 index 0000000..b4a754e --- /dev/null +++ b/Config/services.php @@ -0,0 +1,30 @@ +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); +}; diff --git a/Controller/PlanController.php b/Controller/PlanController.php new file mode 100644 index 0000000..733f98a --- /dev/null +++ b/Controller/PlanController.php @@ -0,0 +1,173 @@ +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 + * ":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 $args + * @param string $action + * + * @return array + */ + 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); + } +} diff --git a/Controller/TaskController.php b/Controller/TaskController.php new file mode 100644 index 0000000..bcc8bac --- /dev/null +++ b/Controller/TaskController.php @@ -0,0 +1,186 @@ + 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 $args + * + * @return array + */ + 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); + } +} diff --git a/DependencyInjection/PlanExtension.php b/DependencyInjection/PlanExtension.php new file mode 100644 index 0000000..03acc13 --- /dev/null +++ b/DependencyInjection/PlanExtension.php @@ -0,0 +1,25 @@ +load('services.php'); + } +} diff --git a/Entity/CountsItemsByTypeTrait.php b/Entity/CountsItemsByTypeTrait.php new file mode 100644 index 0000000..8fd919b --- /dev/null +++ b/Entity/CountsItemsByTypeTrait.php @@ -0,0 +1,33 @@ + + */ + 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; + } +} diff --git a/Entity/DateRangeInterface.php b/Entity/DateRangeInterface.php new file mode 100644 index 0000000..d716293 --- /dev/null +++ b/Entity/DateRangeInterface.php @@ -0,0 +1,15 @@ + + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + public function getObjectives(): Collection + { + return self::sortedByPosition($this->objectives); + } + + /** + * @return Collection + */ + 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 + */ + public function getDescriptionItems(): Collection + { + return self::sortedByPosition($this->descriptionItems); + } + + /** + * The allocation items sorted by position, as a new collection; see getObjectives(). + * + * @return Collection + */ + 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 $collection + * + * @return Collection + */ + 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; + } +} diff --git a/Entity/PlanAllocationItem.php b/Entity/PlanAllocationItem.php new file mode 100644 index 0000000..deb540b --- /dev/null +++ b/Entity/PlanAllocationItem.php @@ -0,0 +1,192 @@ + 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; + } +} diff --git a/Entity/PlanAllocationItemRepository.php b/Entity/PlanAllocationItemRepository.php new file mode 100644 index 0000000..2a05470 --- /dev/null +++ b/Entity/PlanAllocationItemRepository.php @@ -0,0 +1,20 @@ + + */ +class PlanAllocationItemRepository extends CommonRepository +{ + use CountsItemsByTypeTrait; + + public function getTableAlias(): string + { + return 'pai'; + } +} diff --git a/Entity/PlanDescriptionItem.php b/Entity/PlanDescriptionItem.php new file mode 100644 index 0000000..6ac8e56 --- /dev/null +++ b/Entity/PlanDescriptionItem.php @@ -0,0 +1,131 @@ + 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; + } +} diff --git a/Entity/PlanDescriptionItemRepository.php b/Entity/PlanDescriptionItemRepository.php new file mode 100644 index 0000000..a1941eb --- /dev/null +++ b/Entity/PlanDescriptionItemRepository.php @@ -0,0 +1,20 @@ + + */ +class PlanDescriptionItemRepository extends CommonRepository +{ + use CountsItemsByTypeTrait; + + public function getTableAlias(): string + { + return 'pdi'; + } +} diff --git a/Entity/PlanObjective.php b/Entity/PlanObjective.php new file mode 100644 index 0000000..2f09d80 --- /dev/null +++ b/Entity/PlanObjective.php @@ -0,0 +1,153 @@ +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; + } +} diff --git a/Entity/PlanObjectiveRepository.php b/Entity/PlanObjectiveRepository.php new file mode 100644 index 0000000..76001ba --- /dev/null +++ b/Entity/PlanObjectiveRepository.php @@ -0,0 +1,18 @@ + + */ +class PlanObjectiveRepository extends CommonRepository +{ + public function getTableAlias(): string + { + return 'po'; + } +} diff --git a/Entity/PlanRepository.php b/Entity/PlanRepository.php new file mode 100644 index 0000000..3abf133 --- /dev/null +++ b/Entity/PlanRepository.php @@ -0,0 +1,57 @@ + + */ +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 $args + */ + public function getEntities(array $args = []) + { + $alias = $this->getTableAlias(); + + $args['qb'] = $this->createQueryBuilder($alias) + ->select($alias, 'o', 'c') + ->leftJoin($alias.'.owner', 'o') + ->leftJoin($alias.'.category', 'c'); + + return parent::getEntities($args); + } + + /** + * The list's search box matches the name. + * + * @return array + */ + protected function addCatchAllWhereClause($q, $filter): array + { + return $this->addStandardCatchAllWhereClause($q, $filter, [ + $this->getTableAlias().'.name', + ]); + } + + /** + * @return array + */ + protected function getDefaultOrder(): array + { + return [ + [$this->getTableAlias().'.name', 'ASC'], + ]; + } +} diff --git a/Entity/PlanStatus.php b/Entity/PlanStatus.php new file mode 100644 index 0000000..6dea618 --- /dev/null +++ b/Entity/PlanStatus.php @@ -0,0 +1,20 @@ +value; + } +} diff --git a/Entity/Task.php b/Entity/Task.php new file mode 100644 index 0000000..e9bb92e --- /dev/null +++ b/Entity/Task.php @@ -0,0 +1,251 @@ + + */ + 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 + */ + 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; + } +} diff --git a/Entity/TaskRepository.php b/Entity/TaskRepository.php new file mode 100644 index 0000000..5cb2dbf --- /dev/null +++ b/Entity/TaskRepository.php @@ -0,0 +1,74 @@ + + */ +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 $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 + */ + protected function addCatchAllWhereClause($q, $filter): array + { + return $this->addStandardCatchAllWhereClause($q, $filter, [ + $this->getTableAlias().'.name', + $this->getTableAlias().'.description', + ]); + } + + /** + * @return array + */ + protected function getDefaultOrder(): array + { + return [ + [$this->getTableAlias().'.name', 'ASC'], + ]; + } +} diff --git a/Entity/TaskStatus.php b/Entity/TaskStatus.php new file mode 100644 index 0000000..62396a0 --- /dev/null +++ b/Entity/TaskStatus.php @@ -0,0 +1,34 @@ +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', + }; + } +} diff --git a/EventListener/ConfigSubscriber.php b/EventListener/ConfigSubscriber.php new file mode 100644 index 0000000..df3eb7c --- /dev/null +++ b/EventListener/ConfigSubscriber.php @@ -0,0 +1,90 @@ + 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 + ); + } + } + } +} diff --git a/EventListener/PluginInstallSubscriber.php b/EventListener/PluginInstallSubscriber.php new file mode 100644 index 0000000..6f2798e --- /dev/null +++ b/EventListener/PluginInstallSubscriber.php @@ -0,0 +1,43 @@ + ['onPluginInstall', -10], + ]; + } + + public function onPluginInstall(PluginInstallEvent $event): void + { + $plugin = $event->getPlugin(); + + if (self::BUNDLE !== $plugin->getBundle()) { + return; + } + + $this->pluginDatabase->onPluginUpdate($plugin); + } +} diff --git a/Form/Type/ConfigType.php b/Form/Type/ConfigType.php new file mode 100644 index 0000000..1664ef6 --- /dev/null +++ b/Form/Type/ConfigType.php @@ -0,0 +1,70 @@ + 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> + */ +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; + } +} diff --git a/Form/Type/ItemTypeConfigType.php b/Form/Type/ItemTypeConfigType.php new file mode 100644 index 0000000..d4d1a0a --- /dev/null +++ b/Form/Type/ItemTypeConfigType.php @@ -0,0 +1,109 @@ + 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> + */ +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'; + } +} diff --git a/Form/Type/PlanAllocationItemType.php b/Form/Type/PlanAllocationItemType.php new file mode 100644 index 0000000..bcdeb0b --- /dev/null +++ b/Form/Type/PlanAllocationItemType.php @@ -0,0 +1,90 @@ + + */ +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'; + } +} diff --git a/Form/Type/PlanDescriptionItemType.php b/Form/Type/PlanDescriptionItemType.php new file mode 100644 index 0000000..40c9176 --- /dev/null +++ b/Form/Type/PlanDescriptionItemType.php @@ -0,0 +1,72 @@ + 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 + */ +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'; + } +} diff --git a/Form/Type/PlanObjectiveType.php b/Form/Type/PlanObjectiveType.php new file mode 100644 index 0000000..39c3354 --- /dev/null +++ b/Form/Type/PlanObjectiveType.php @@ -0,0 +1,60 @@ + + */ +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'; + } +} diff --git a/Form/Type/PlanType.php b/Form/Type/PlanType.php new file mode 100644 index 0000000..d6369fc --- /dev/null +++ b/Form/Type/PlanType.php @@ -0,0 +1,167 @@ + + */ +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'; + } +} diff --git a/Form/Type/TaskType.php b/Form/Type/TaskType.php new file mode 100644 index 0000000..f726ebc --- /dev/null +++ b/Form/Type/TaskType.php @@ -0,0 +1,124 @@ + + */ +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'; + } +} diff --git a/Integration/PlanIntegration.php b/Integration/PlanIntegration.php new file mode 100644 index 0000000..0ab36ce --- /dev/null +++ b/Integration/PlanIntegration.php @@ -0,0 +1,32 @@ + 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 + */ + 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(); + } +} diff --git a/Migrations/Version_0_3_0.php b/Migrations/Version_0_3_0.php new file mode 100644 index 0000000..cafa4a0 --- /dev/null +++ b/Migrations/Version_0_3_0.php @@ -0,0 +1,58 @@ +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"); + } + } +} diff --git a/Migrations/Version_0_4_0.php b/Migrations/Version_0_4_0.php new file mode 100644 index 0000000..6cb21f8 --- /dev/null +++ b/Migrations/Version_0_4_0.php @@ -0,0 +1,98 @@ + [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 + */ + 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; + } +} diff --git a/Migrations/Version_0_5_0.php b/Migrations/Version_0_5_0.php new file mode 100644 index 0000000..9378ede --- /dev/null +++ b/Migrations/Version_0_5_0.php @@ -0,0 +1,62 @@ +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)"); + } + } +} diff --git a/Migrations/Version_0_6_0.php b/Migrations/Version_0_6_0.php new file mode 100644 index 0000000..72db35e --- /dev/null +++ b/Migrations/Version_0_6_0.php @@ -0,0 +1,94 @@ +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.'.'); + } +} diff --git a/Migrations/Version_0_7_0.php b/Migrations/Version_0_7_0.php new file mode 100644 index 0000000..5ee3ed6 --- /dev/null +++ b/Migrations/Version_0_7_0.php @@ -0,0 +1,79 @@ +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.'.'); + } +} diff --git a/Migrations/Version_0_8_0.php b/Migrations/Version_0_8_0.php new file mode 100644 index 0000000..01a3dec --- /dev/null +++ b/Migrations/Version_0_8_0.php @@ -0,0 +1,65 @@ + 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 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; + } +} diff --git a/Model/PlanModel.php b/Model/PlanModel.php new file mode 100644 index 0000000..79b8c1e --- /dev/null +++ b/Model/PlanModel.php @@ -0,0 +1,77 @@ + + */ +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 $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); + } +} diff --git a/Model/TaskModel.php b/Model/TaskModel.php new file mode 100644 index 0000000..9e1460c --- /dev/null +++ b/Model/TaskModel.php @@ -0,0 +1,91 @@ + + */ +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 + */ + 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 $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); + } +} diff --git a/PlanBundle.php b/PlanBundle.php new file mode 100644 index 0000000..210fded --- /dev/null +++ b/PlanBundle.php @@ -0,0 +1,11 @@ + 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) %} +
+
+ {{ form_widget(type.children.key) }} + {{ form_errors(type) }} + {% if type.children.icon is defined %} + {% set icon = type.children.icon.vars.value %} +
+
+ +
+
{{ form_row(type.children.icon) }}
+
+ {% endif %} + + + + + + + + + + {% for locale, name in type.children.names.children %} + + + + + + {% endfor %} + +
{{ 'mautic.plan.config.type.language'|trans }}{{ 'mautic.plan.config.type.name'|trans }}{{ 'mautic.plan.config.type.description'|trans }}
+ {{ name.vars.attr['data-language'] }} + {% if name.vars.required %}*{% endif %} + + {{ form_widget(name) }} + {{ form_errors(name) }} + + {{ form_widget(type.children.descriptions.children[locale]) }} + {{ form_errors(type.children.descriptions.children[locale]) }} +
+
+ +
+
+
+{% endmacro %} + +{# One editable list of types (one per kind of plan item). #} +{% macro type_section(types, titleKey, helpKey) %} + {% import _self as plan %} +

{{ titleKey|trans }}

+

{{ helpKey|trans }}

+ {{ form_errors(types) }} +
+

+ {{ 'mautic.plan.config.types.empty'|trans }} +

+
+ {% for type in types %} + {{ plan.type_row(type) }} + {% endfor %} +
+ +
+ {% do types.setRendered %} +{% endmacro %} + +{% block _config_planconfig_widget %} +{% import _self as plan %} +
{{ 'mautic.plan.config.description'|trans }}
+ +

{{ 'mautic.plan.config.section.general'|trans }}

+
+
{{ form_row(form.children.plan_currency) }}
+
+

{{ 'mautic.plan.config.currency.help'|trans }}

+ +{{ 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 %} diff --git a/Resources/views/Plan/_tabs.html.twig b/Resources/views/Plan/_tabs.html.twig new file mode 100644 index 0000000..f5f0f09 --- /dev/null +++ b/Resources/views/Plan/_tabs.html.twig @@ -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-. 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', +} %} + diff --git a/Resources/views/Plan/_task_table.html.twig b/Resources/views/Plan/_task_table.html.twig new file mode 100644 index 0000000..b420c90 --- /dev/null +++ b/Resources/views/Plan/_task_table.html.twig @@ -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 %} + +{% endif %} + +{% if not plan.id %} +

{{ 'mautic.plan.task.save_plan_first'|trans }}

+{% elseif taskTree is empty %} +

{{ 'mautic.plan.task.empty'|trans }}

+{% else %} +
+ + + + + + + + + + + + + {% 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 %} + + + + + + + + + {% endfor %} + +
{{ 'mautic.core.id'|trans }}{{ 'mautic.plan.task.field.name'|trans }}{{ 'mautic.plan.task.field.description'|trans }}{{ 'mautic.plan.task.field.start_date'|trans }}{{ 'mautic.plan.task.field.end_date'|trans }}{{ 'mautic.plan.task.field.status'|trans }}
{{ task.id }} + + {% if row.depth > 0 %} + + {% endif %} + {% if canEdit %} + {{ task.name }} + {% else %} + {{ task.name }} + {% endif %} + {% if childCount > 0 %} + ({{ childCount }}) + {% endif %} + + + {% set description = task.description|default('')|striptags|trim %} + {{ description|length > 120 ? description|slice(0, 120) ~ '…' : description }} + {{ task.startDate ? dateToFull(task.startDate) : '' }}{{ task.endDate ? dateToFull(task.endDate) : '' }}{{ task.status.labelKey|trans }}
+
+{% endif %} diff --git a/Resources/views/Plan/details.html.twig b/Resources/views/Plan/details.html.twig new file mode 100644 index 0000000..41bbe12 --- /dev/null +++ b/Resources/views/Plan/details.html.twig @@ -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 %} +
+ {% 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, + }}) }} + +
+ {# Details #} +
+ + + + + + + {% if item.completedAt %} + + + + + {% endif %} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {% if item.dateModified %} + + + + + {% endif %} + + + + + +
{{ 'mautic.plan.field.status'|trans }}{{ item.status.labelKey|trans }}
{{ 'mautic.plan.field.completed_at'|trans }}{{ dateToFull(item.completedAt) }}
{{ 'mautic.plan.field.version'|trans }}{{ item.version }}
{{ 'mautic.plan.field.owner'|trans }}{{ item.owner ? item.owner.name : 'mautic.plan.owner.none'|trans }}
{{ 'mautic.plan.field.start_date'|trans }}{{ item.startDate ? dateToFull(item.startDate) : 'mautic.plan.value.none'|trans }}
{{ 'mautic.plan.field.end_date'|trans }}{{ item.endDate ? dateToFull(item.endDate) : 'mautic.plan.value.none'|trans }}
{{ 'mautic.core.category'|trans }}{{ item.category ? item.category.title : 'mautic.plan.value.none'|trans }}
{{ 'mautic.core.form.available'|trans }}{{ (item.isPublished ? 'mautic.core.form.yes' : 'mautic.core.form.no')|trans }}
{{ 'mautic.core.created'|trans }}{{ item.dateAdded ? dateToFull(item.dateAdded) : '' }}{% if item.createdByUser %} ({{ item.createdByUser }}){% endif %}
{{ 'mautic.core.modified'|trans }}{{ dateToFull(item.dateModified) }}{% if item.modifiedByUser %} ({{ item.modifiedByUser }}){% endif %}
{{ 'mautic.core.id'|trans }}{{ item.id }}
+
+ + {# Description #} +
+ {% if descriptionItems is empty %} +

{{ 'mautic.plan.description_item.empty'|trans }}

+ {% else %} + {# Three columns: the type's pictogram, the type, the description. #} +
+ + + + + + + + + + {% 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) %} + + + + + + {% endfor %} + +
{{ 'mautic.plan.description_item.field.pictogram'|trans }}{{ 'mautic.plan.description_item.field.type'|trans }}{{ 'mautic.plan.description_item.field.description'|trans }}
+ {% if typeIcon %}{% endif %} + + + {{ typeName ?? 'mautic.plan.description_item.type.unknown'|trans({'%key%': descriptionItem.type}) }} + + {{ descriptionItem.description }}
+
+ {% endif %} +
+ + {# Objectives #} +
+ {% if objectives is empty %} +

{{ 'mautic.plan.objective.empty'|trans }}

+ {% else %} +

+ {{ 'mautic.plan.objective.progress'|trans({'%achieved%': achievedCount, '%total%': objectives|length}) }} +

+
    + {% for objective in objectives %} +
  1. + {% if objective.achieved %} + + {% else %} + + {% endif %} + {{ objective.title }} + {% if objective.description is not empty %} +
    {{ objective.description }}
    + {% endif %} +
  2. + {% endfor %} +
+ {% endif %} +
+ + {# Allocation: the plan's budget, then the allocation items (cost lines) with their totals. #} +
+ + + + + + + +
{{ 'mautic.plan.field.budget_planned'|trans }} + {% if item.budgetPlanned is not null %} + {{ plan_money(item.budgetPlanned) }} {{ plan_currency() }} + {% else %} + {{ 'mautic.plan.value.none'|trans }} + {% endif %} +
+ +

{{ 'mautic.plan.field.allocation_items'|trans }}

+ {% if allocationItems is empty %} +

{{ 'mautic.plan.allocation_item.empty'|trans }}

+ {% else %} +
+ + + + + + + + + + + + {% for allocationItem in allocationItems %} + {% set typeName = plan_item_type_name('allocation', allocationItem.type) %} + {% set typeDescription = plan_item_type_description('allocation', allocationItem.type) %} + + + {{ typeName ?? 'mautic.plan.description_item.type.unknown'|trans({'%key%': allocationItem.type}) }} + + + + + + + {% endfor %} + + + + + + + + +
{{ 'mautic.plan.allocation_item.field.type'|trans }}{{ 'mautic.plan.allocation_item.field.name'|trans }}{{ 'mautic.plan.allocation_item.field.description'|trans }}{{ 'mautic.plan.allocation_item.field.planned_cost'|trans }}{{ 'mautic.plan.allocation_item.field.real_cost'|trans }}
{{ allocationItem.name }}{{ allocationItem.description }} + {% if allocationItem.plannedCost is not null %}{{ plan_money(allocationItem.plannedCost) }} {{ plan_currency() }}{% endif %} + + {% if allocationItem.realCost is not null %}{{ plan_money(allocationItem.realCost) }} {{ plan_currency() }}{% endif %} +
{{ 'mautic.plan.allocation.total'|trans }} + {% if allocationTotals.planned is not null %}{{ plan_money(allocationTotals.planned) }} {{ plan_currency() }}{% endif %} + + {% if allocationTotals.real is not null %}{{ plan_money(allocationTotals.real) }} {{ plan_currency() }}{% endif %} +
+
+ {% endif %} +
+ + {# Targets #} +
+

{{ 'mautic.plan.target.empty'|trans }}

+
+ + {# Tasks: same columns as Planning > Tasks, in tree order. #} +
+ {{ include('@Plan/Plan/_task_table.html.twig', { + 'plan': item, + 'taskTree': taskTree, + 'taskPermissions': taskPermissions, + }) }} +
+
+{% endblock %} diff --git a/Resources/views/Plan/form.html.twig b/Resources/views/Plan/form.html.twig new file mode 100644 index 0000000..c1de2b7 --- /dev/null +++ b/Resources/views/Plan/form.html.twig @@ -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) %} +
  • +
    +
    + + + +
    +
    +{% endmacro %} + +{% macro row_end(removeLabel) %} +
    +
    + +
    +
    +
  • +{% 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') }} +
    + {# The selected type's pictogram; updated by plan.js when the type changes. #} +
    + +
    +
    + {{ form_row(item.type) }} + {# Filled with the selected type's description by plan.js. #} +

    {{ plan_item_type_description('description', item.type.vars.value) }}

    +
    +
    + {{ 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') }} +
    +
    + {{ form_row(item.type) }} + {# Filled with the selected type's description by plan.js. #} +

    {{ plan_item_type_description('allocation', item.type.vars.value) }}

    +
    +
    {{ form_row(item.name) }}
    +
    + {{ form_row(item.description) }} +
    +
    {{ form_row(item.plannedCost) }}
    +
    {{ form_row(item.realCost) }}
    +
    + {{ form_widget(item.position) }} + {{ _self.row_end('mautic.plan.allocation_item.remove') }} +{% endmacro %} + +{% block content %} + {{ form_start(form) }} +
    + {{ form_row(form.name) }} +
    + + {{ include('@Plan/Plan/_tabs.html.twig', {'planId': entity.id}) }} + +
    + {# Details #} +
    +
    +
    {{ form_row(form.status) }}
    +
    {{ form_row(form.version) }}
    +
    {{ form_row(form.owner) }}
    +
    + {% if entity.completedAt %} +
    + +

    {{ dateToFull(entity.completedAt) }}

    +
    + {% endif %} +
    +
    {{ form_row(form.startDate) }}
    +
    {{ form_row(form.endDate) }}
    +
    +
    +
    {{ form_row(form.category) }}
    +
    {{ form_row(form.isPublished) }}
    +
    +
    + + {# Description: description items. #} +
    + {% set hasTypes = form.descriptionItems.vars.prototype.type.vars.choices is not empty %} +
    + {{ form_errors(form.descriptionItems) }} + {% if not hasTypes %} +
    {{ 'mautic.plan.description_item.no_types'|trans }}
    + {% endif %} +

    + {{ 'mautic.plan.description_item.empty'|trans }} +

    +
      + {% for item in form.descriptionItems %} + {{ _self.description_item_row(item) }} + {% endfor %} +
    + {% if hasTypes %} + + {% endif %} +
    + {% do form.descriptionItems.setRendered %} +
    + + {# Objectives #} +
    +
    + {{ form_errors(form.objectives) }} +

    + {{ 'mautic.plan.objective.empty'|trans }} +

    +
      + {% for objective in form.objectives %} + {{ _self.objective_row(objective) }} + {% endfor %} +
    + +
    + {% do form.objectives.setRendered %} +
    + + {# Allocation: the plan's budget, then the allocation items (cost lines). #} +
    +
    +
    {{ form_row(form.budgetPlanned) }}
    +
    + + {% set hasAllocationTypes = form.allocationItems.vars.prototype.type.vars.choices is not empty %} +
    +

    {{ 'mautic.plan.field.allocation_items'|trans }}

    + {{ form_errors(form.allocationItems) }} + {% if not hasAllocationTypes %} +
    {{ 'mautic.plan.allocation_item.no_types'|trans }}
    + {% endif %} +

    + {{ 'mautic.plan.allocation_item.empty'|trans }} +

    +
      + {% for item in form.allocationItems %} + {{ _self.allocation_item_row(item) }} + {% endfor %} +
    + {% if hasAllocationTypes %} + + {% endif %} +
    + {% do form.allocationItems.setRendered %} +
    + + {# Targets #} +
    +

    {{ 'mautic.plan.target.empty'|trans }}

    +
    + + {# Tasks: read-only here, so that following a link doesn't drop unsaved changes to the plan. #} +
    + {% if entity.id %} +

    {{ 'mautic.plan.task.manage_from_plan_page'|trans }}

    + {% endif %} + {{ include('@Plan/Plan/_task_table.html.twig', { + 'plan': entity, + 'taskTree': taskTree|default([]), + 'readOnly': true, + }) }} +
    +
    + {{ form_end(form) }} +{% endblock %} diff --git a/Resources/views/Plan/list.html.twig b/Resources/views/Plan/list.html.twig new file mode 100644 index 0000000..053279d --- /dev/null +++ b/Resources/views/Plan/list.html.twig @@ -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 %} +
    + {{- 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'], + }, + }, + }) -}} +
    + {% if items is defined and items is not empty %} +
    + + + + {{ 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', + }) }} + + + + {% for item in items %} + {% set canEdit = securityHasEntityAccess(permissions['plan:plans:editown'], permissions['plan:plans:editother'], item.createdBy) %} + + + + + + + + + + + {% endfor %} + +
    + {{- 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', + }) -}} + +
    + {{- include('@MauticCore/Helper/publishstatus_icon.html.twig', { + 'item': item, + 'model': 'plan', + }) -}} + + {{ item.name }} + + {% if item.category %} + {{ item.category.title }} + {% endif %} +
    +
    {{ item.status.labelKey|trans }} + {{ item.owner ? item.owner.name : 'mautic.plan.owner.none'|trans }} + {{ item.startDate ? dateToDate(item.startDate) : '' }}{{ item.endDate ? dateToDate(item.endDate) : '' }} + {% if item.budgetPlanned is not null %} + {{ plan_money(item.budgetPlanned) }} {{ plan_currency() }} + {% endif %} + {{ item.id }}
    + +
    + {% elseif searchValue is not empty %} + {{ include('@MauticCore/Helper/noresults.html.twig') }} + {% else %} +
    + {{ include('@MauticCore/Components/content-block.html.twig', { + 'heading': 'mautic.plan.onboarding.heading', + 'subheading': 'mautic.plan.onboarding.subheading', + 'copy': 'mautic.plan.onboarding.copy', + }) }} +
    + {% endif %} +
    +
    +{% endblock %} diff --git a/Resources/views/Task/form.html.twig b/Resources/views/Task/form.html.twig new file mode 100644 index 0000000..d39f74e --- /dev/null +++ b/Resources/views/Task/form.html.twig @@ -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) }} +
    +
    +
    + {{ form_row(form.name) }} + {{ form_row(form.description) }} +
    +
    +
    +
    + {{ form_row(form.status) }} + {{ form_row(form.startDate) }} + {{ form_row(form.endDate) }} + {{ form_row(form.plan) }} + {{ form_row(form.parent) }} +

    {{ 'mautic.plan.task.parent.help'|trans }}

    +
    +
    +
    + {{ form_end(form) }} +{% endblock %} diff --git a/Resources/views/Task/list.html.twig b/Resources/views/Task/list.html.twig new file mode 100644 index 0000000..592bd37 --- /dev/null +++ b/Resources/views/Task/list.html.twig @@ -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 %} +
    + {{- 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'], + }, + }, + }) -}} +
    + {% if items is defined and items is not empty %} +
    + + + + {{ 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', + }) }} + + + + {% for item in items %} + {% set canEdit = securityHasEntityAccess(permissions['plan:tasks:editown'], permissions['plan:tasks:editother'], item.createdBy) %} + + + + + + + + + + {% endfor %} + +
    + {{- 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', + }) -}} + {{ item.id }} + {% if canEdit %} + {{ item.name }} + {% else %} + {{ item.name }} + {% endif %} + + {% set description = item.description|default('')|striptags|trim %} + {{ description|length > 120 ? description|slice(0, 120) ~ '…' : description }} + {{ item.startDate ? dateToFull(item.startDate) : '' }}{{ item.endDate ? dateToFull(item.endDate) : '' }}{{ item.status.labelKey|trans }}
    + +
    + {% elseif searchValue is not empty %} + {{ include('@MauticCore/Helper/noresults.html.twig') }} + {% else %} +
    + {{ 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', + }) }} +
    + {% endif %} +
    +
    +{% endblock %} diff --git a/Security/Permissions/PlanPermissions.php b/Security/Permissions/PlanPermissions.php new file mode 100644 index 0000000..315a303 --- /dev/null +++ b/Security/Permissions/PlanPermissions.php @@ -0,0 +1,45 @@ + 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 $options + * @param array $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); + } +} diff --git a/Service/CurrencyProvider.php b/Service/CurrencyProvider.php new file mode 100644 index 0000000..4416c47 --- /dev/null +++ b/Service/CurrencyProvider.php @@ -0,0 +1,71 @@ + 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 + */ + 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; + } +} diff --git a/Service/ItemTypeProvider.php b/Service/ItemTypeProvider.php new file mode 100644 index 0000000..4e766c3 --- /dev/null +++ b/Service/ItemTypeProvider.php @@ -0,0 +1,214 @@ + 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, descriptions: array, 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 + */ + 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 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 $types + * + * @return array, descriptions: array, 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 + */ + 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, descriptions: array, 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 $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 ?? '')); + } +} diff --git a/Service/Pictograms.php b/Service/Pictograms.php new file mode 100644 index 0000000..d38c38d --- /dev/null +++ b/Service/Pictograms.php @@ -0,0 +1,64 @@ + 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 + */ + 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; + } +} diff --git a/Translations/en_US/messages.ini b/Translations/en_US/messages.ini new file mode 100644 index 0000000..fd5d64e --- /dev/null +++ b/Translations/en_US/messages.ini @@ -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" diff --git a/Translations/en_US/validators.ini b/Translations/en_US/validators.ini new file mode 100644 index 0000000..ae2483a --- /dev/null +++ b/Translations/en_US/validators.ini @@ -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." diff --git a/Twig/PlanExtension.php b/Twig/PlanExtension.php new file mode 100644 index 0000000..d06a2f3 --- /dev/null +++ b/Twig/PlanExtension.php @@ -0,0 +1,38 @@ + $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)), + ]; + } +} diff --git a/Validator/Constraints/EndDateAfterStartDate.php b/Validator/Constraints/EndDateAfterStartDate.php new file mode 100644 index 0000000..cf7a112 --- /dev/null +++ b/Validator/Constraints/EndDateAfterStartDate.php @@ -0,0 +1,21 @@ +getStartDate(); + $end = $value->getEndDate(); + + if (null === $start || null === $end || $end >= $start) { + return; + } + + $this->context->buildViolation($constraint->message) + ->atPath('endDate') + ->addViolation(); + } +} diff --git a/Validator/Constraints/ValidTaskParent.php b/Validator/Constraints/ValidTaskParent.php new file mode 100644 index 0000000..a904d84 --- /dev/null +++ b/Validator/Constraints/ValidTaskParent.php @@ -0,0 +1,23 @@ +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(); + } + } +} diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..0ce63a7 --- /dev/null +++ b/composer.json @@ -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" + } +} diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..b0f0889 --- /dev/null +++ b/readme.md @@ -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.`). 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__*` 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:*` diff --git a/test.fr b/test.fr deleted file mode 100644 index e69de29..0000000