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
-
Copy or clone this repository into your Mautic installation as
docroot/plugins/PlanBundle. The folder name must bePlanBundle. -
Clear the cache and register the plugin:
php bin/console cache:clear php bin/console mautic:plugins:reload -
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. 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:
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 classConfig/config.php: metadata, routes, menu and integration service tagsConfig/services.php: autowires and autoconfigures every class in the bundleDependencyInjection/PlanExtension.php: loadsConfig/services.phpIntegration/PlanIntegration.php: the integration that is listed on the Plugins pageIntegration/Support/ConfigSupport.php: the configuration form for the integrationTranslations/en_US/messages.iniandvalidators.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'sAbstractStandardFormControllerResources/views/Plan/list.html.twig: the list. A plan's name opens its detail page.Resources/views/Plan/form.html.twiganddetails.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.phpandResources/views/Task/: the task list, and the create/edit form (Planning > Tasks).new?plan=IDpreselects 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 carryreturnTo=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 byMautic.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, keymautic.plan.tab.<plan id>). The detail page and the form both reopen it, so Edit and Save keep the current tab. Cancel goes to the plans list, as in core. - After a failed save, the first tab with an error opens instead, and every tab with an error gets a warning icon.
- Core reopens its own remembered tab on page load and after every Ajax request (
Mautic.rememberActiveTabs), in an order that varies.plan.jswraps 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 thehas-errorclass. Mautic's owncheckbox_rowtheme addshas-errorto every checkbox: it testserrors|length is not empty, and0isn't "empty" in Twig. Every objective's "Achieved" checkbox would otherwise put a warning icon on the Objectives tab, and opening that tab on load looked like a jump to Objectives. Security/Permissions/PlanPermissions.php: the permissions shown in Settings > Roles
The main menu has a top-level Planning entry, with Plans and Tasks as its items. Add future planning pages as more children of mautic.plan.menu.root in Config/config.php.
The Targets tab only shows an empty state for now.
| Route | URL | Purpose |
|---|---|---|
plan_index |
/s/plans/{page} |
Plan list, with search on name |
plan_action |
/s/plans/{objectAction}/{objectId} |
view, new, edit, delete, batchDelete |
plan_task_index |
/s/plan-tasks/{page} |
Task list, with search on name and description |
plan_task_action |
/s/plan-tasks/{objectAction}/{objectId} |
new (optional ?plan=ID), edit, delete, batchDelete |
The plan templates don't pass routeBase to core's button helpers (page_actions, list_actions) when a "close" button is involved: from routeBase, core builds mautic_<routeBase>_* route names, which don't exist in this plugin. The other buttons use the actionRoute (plan_action) that the controller passes to the template.
Permission keys:
plan:plans:*andplan: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 theplancategory type.
The Plan object
Entity/Plan.php: the entity (tableplans), with its Doctrine mapping and validation rulesEntity/PlanStatus.php: the status enum (draft,planned,active,paused,completed,archived)Entity/PlanRepository.php: the repositoryEntity/PlanObjective.phpandPlanObjectiveRepository.php: a plan's objectives (tableplan_objectives): title, description, position and an "achieved" flagModel/PlanModel.php: the model, available asmautic.plan.model.planor withgetModel('plan'). A new plan fromgetEntity()has the current user as owner.Entity/PlanDescriptionItem.phpandPlanDescriptionItemRepository.php: a plan's description items (tableplan_description_items): type, description and position. They make up the Description tab and replace the formerdescriptionfield.Form/Type/PlanType.php,PlanObjectiveType.phpandPlanDescriptionItemType.php: the create and edit form, with the objectives and the description items as collectionsValidator/Constraints/EndDateAfterStartDate.php: the end date must be on or after the start date, when both are set. Used by plans and tasks, throughEntity/DateRangeInterface.php.
Behaviour to know about:
- Setting the status to
completedfrom another status setscompletedAtto the current time. Moving a completed plan to any other status clearscompletedAt. owneris required by validation, but the column is nullable: if the user is deleted, the owner becomesNULL(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
plantype (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,EURby 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. versionis 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 CASCADEin the database too), and an objective removed from the form is deleted (orphanRemoval). They are always loaded ordered byposition. On save, the model renumbers positions to 0, 1, 2… in their current order. Description items follow the same rules. getObjectives()andgetDescriptionItems()return the rows sorted by position, as a new collection. The mapping'sorderByisn'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 onPlanTypepassing a mask array toCleanFormSubscriber. 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, tableplan_allocation_items) is a cost line: type (with its pictogram), name (optional), description, planned cost and real cost. Costs areDECIMAL(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
localeparameter) requires a name. Each type also has a pictogram. 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 theplan_description_item_typesandplan_allocation_item_typesparameters. Read them withService/ItemTypeProvider.php, passing the kind (descriptionorallocation). In templates, use the Twig functionsplan_item_type_name(kind, key),plan_item_type_description(kind, key)andplan_item_type_icon(kind, key), plusplan_currency()andplan_money(amount)(Twig/PlanExtension.php). - Every item type has 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 asiconin 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. The Allocation tab's cost lines list has the same Pictogram column, before Type. - 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, onCONFIG_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.phpandResources/views/FormTheme/Config/_config_planconfig_widget.html.twig. Adding and removing types is handled inAssets/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 (
publishStatusblock): 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.
isAchievedis toggled by hand on the form for now.
The Task object
Entity/Task.phpandTaskRepository.php: a task (tableplan_tasks): name, description, plan, optional parent task, optional start and end dates, and statusEntity/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 asVARCHAR(20), indexed.Model/TaskModel.php: the model, available asmautic.plan.model.taskor withgetModel('plan.task').getTaskTree($plan)returns a plan's tasks in tree order, with their depth.Form/Type/TaskType.php: the create and edit formValidator/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_idON DELETE CASCADE). - Deleting a task keeps its sub-tasks, which become top-level tasks (
parent_idON 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.*, plusmautic.plugin.plan.name - Permission keys:
plan:*