Compare commits

...
5 Commits
45 changed files with 2162 additions and 380 deletions

No files matched your search

+33 -2
View File
@@ -19,7 +19,15 @@
font-size: 20px;
line-height: 24px;
margin-bottom: 0;
padding-bottom: 0;
/* Was 0 while an h2 only ever preceded a p, which brings its own spacing. */
padding-bottom: 8px;
}
h3 {
font-weight: bold;
font-size: 17px;
line-height: 22px;
margin-bottom: 0;
padding-bottom: 4px;
}
p {
font-size: 16px;
@@ -48,6 +56,18 @@
strong {
font-weight: bold;
}
em {
font-style: italic;
}
ul, ol {
/* Margin, not padding: Outlook on Windows renders list padding unreliably. */
margin: 0 0 16px 24px;
padding: 0;
font-size: 16px;
}
li {
padding-bottom: 4px;
}
</mj-style>
</mj-head>
<mj-body background-color="#666666">
@@ -70,8 +90,19 @@
</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto culpa delectus dolores
<strong>earum eius fugiat in nesciunt quas quidem vitae</strong>?
<strong>earum eius fugiat in nesciunt quas quidem vitae</strong>, <em>eius fugiat</em>?
</p>
<ul>
<li>Lorem ipsum dolor</li>
<li>Consectetur adipisicing elit</li>
</ul>
<h3>
Lorem ipsum
</h3>
<ol>
<li>Lorem ipsum dolor</li>
<li>Consectetur adipisicing elit</li>
</ol>
<p>
<a href="#" class="button">
Button
+1
View File
@@ -6,3 +6,4 @@
@import "components/toast.css";
@import "components/tooltip.css";
@import "components/timeline.css";
@import "components/mail-body.css";
+41
View File
@@ -0,0 +1,41 @@
/*
* Mirrors the rules the mail layout carries in assets/mjml/layout.mjml, so both admin
* previews show what the rendered mail will look like. Kept out of Tailwind's typography
* plugin on purpose: prose brings its own type scale, and the point here is to match the
* mail rather than to look good on its own.
*/
.mail-body > p {
@apply pb-4;
}
.mail-body h2 {
@apply text-xl pb-2;
}
.mail-body h3 {
@apply text-lg font-bold pb-1;
}
.mail-body strong {
@apply font-bold;
}
.mail-body em {
@apply italic;
}
.mail-body ul {
@apply list-disc ml-6 pb-4;
}
.mail-body ol {
@apply list-decimal ml-6 pb-4;
}
.mail-body li {
@apply pb-1;
}
.mail-body a {
@apply underline;
}
+1
View File
@@ -22,6 +22,7 @@
"flagception/flagception-bundle": "^6.0",
"knplabs/knp-menu-bundle": "^3.2",
"knplabs/knp-paginator-bundle": "^6.2",
"league/commonmark": "^2.10",
"league/flysystem-bundle": "^3.4",
"league/flysystem-sftp-v3": "^3.29",
"league/oauth2-client": "^2.9",
Generated
+437 -16
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "b6c422d9533a5a1589f72c500a66cf90",
"content-hash": "8e7c82ac9ab513690dab33c12c4fa2c2",
"packages": [
{
"name": "beberlei/doctrineextensions",
@@ -209,6 +209,81 @@
],
"time": "2026-07-18T12:35:13+00:00"
},
{
"name": "dflydev/dot-access-data",
"version": "v3.0.3",
"source": {
"type": "git",
"url": "https://github.com/dflydev/dflydev-dot-access-data.git",
"reference": "a23a2bf4f31d3518f3ecb38660c95715dfead60f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/dflydev/dflydev-dot-access-data/zipball/a23a2bf4f31d3518f3ecb38660c95715dfead60f",
"reference": "a23a2bf4f31d3518f3ecb38660c95715dfead60f",
"shasum": ""
},
"require": {
"php": "^7.1 || ^8.0"
},
"require-dev": {
"phpstan/phpstan": "^0.12.42",
"phpunit/phpunit": "^7.5 || ^8.5 || ^9.3",
"scrutinizer/ocular": "1.6.0",
"squizlabs/php_codesniffer": "^3.5",
"vimeo/psalm": "^4.0.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "3.x-dev"
}
},
"autoload": {
"psr-4": {
"Dflydev\\DotAccessData\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Dragonfly Development Inc.",
"email": "[email protected]",
"homepage": "http://dflydev.com"
},
{
"name": "Beau Simensen",
"email": "[email protected]",
"homepage": "http://beausimensen.com"
},
{
"name": "Carlos Frutos",
"email": "[email protected]",
"homepage": "https://github.com/cfrutos"
},
{
"name": "Colin O'Dell",
"email": "[email protected]",
"homepage": "https://www.colinodell.com"
}
],
"description": "Given a deep data structure, access data by dot notation.",
"homepage": "https://github.com/dflydev/dflydev-dot-access-data",
"keywords": [
"access",
"data",
"dot",
"notation"
],
"support": {
"issues": "https://github.com/dflydev/dflydev-dot-access-data/issues",
"source": "https://github.com/dflydev/dflydev-dot-access-data/tree/v3.0.3"
},
"time": "2024-07-08T12:26:09+00:00"
},
{
"name": "doctrine/cache",
"version": "2.2.0",
@@ -2496,6 +2571,195 @@
},
"time": "2025-11-29T09:14:09+00:00"
},
{
"name": "league/commonmark",
"version": "2.10.0",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/commonmark.git",
"reference": "d2d1aa8b35e072966c89bc0c66cf926e56767dc4"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/commonmark/zipball/d2d1aa8b35e072966c89bc0c66cf926e56767dc4",
"reference": "d2d1aa8b35e072966c89bc0c66cf926e56767dc4",
"shasum": ""
},
"require": {
"ext-mbstring": "*",
"league/config": "^1.1.1",
"php": "^7.4 || ^8.0",
"psr/event-dispatcher": "^1.0",
"symfony/deprecation-contracts": "^2.1 || ^3.0",
"symfony/polyfill-php80": "^1.16"
},
"require-dev": {
"cebe/markdown": "^1.0",
"commonmark/cmark": "0.31.1",
"commonmark/commonmark.js": "0.31.1",
"composer/package-versions-deprecated": "^1.8",
"embed/embed": "^4.4",
"erusev/parsedown": "^1.0",
"ext-json": "*",
"github/gfm": "0.29.0",
"michelf/php-markdown": "^1.4 || ^2.0",
"nyholm/psr7": "^1.5",
"phpstan/phpstan": "^2.0.0",
"phpunit/phpunit": "^9.5.21 || ^10.5.9 || ^11.0.0 || ^12.0.0 || ^13.0.0",
"scrutinizer/ocular": "^1.8.1",
"symfony/finder": "^5.3 | ^6.0 | ^7.0 || ^8.0",
"symfony/process": "^5.4 | ^6.0 | ^7.0 || ^8.0",
"symfony/yaml": "^2.3 | ^3.0 | ^4.0 | ^5.0 | ^6.0 | ^7.0 || ^8.0",
"unleashedtech/php-coding-standard": "^3.1.1",
"vimeo/psalm": "^4.24.0 || ^5.0.0 || ^6.0.0"
},
"suggest": {
"symfony/yaml": "v2.3+ required if using the Front Matter extension"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "2.11-dev"
}
},
"autoload": {
"psr-4": {
"League\\CommonMark\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Colin O'Dell",
"email": "[email protected]",
"homepage": "https://www.colinodell.com",
"role": "Lead Developer"
}
],
"description": "Highly-extensible PHP Markdown parser which fully supports the CommonMark spec and GitHub-Flavored Markdown (GFM)",
"homepage": "https://commonmark.thephpleague.com",
"keywords": [
"commonmark",
"flavored",
"gfm",
"github",
"github-flavored",
"markdown",
"md",
"parser"
],
"support": {
"docs": "https://commonmark.thephpleague.com/",
"forum": "https://github.com/thephpleague/commonmark/discussions",
"issues": "https://github.com/thephpleague/commonmark/issues",
"rss": "https://github.com/thephpleague/commonmark/releases.atom",
"source": "https://github.com/thephpleague/commonmark"
},
"funding": [
{
"url": "https://www.colinodell.com/sponsor",
"type": "custom"
},
{
"url": "https://www.paypal.me/colinpodell/10.00",
"type": "custom"
},
{
"url": "https://github.com/colinodell",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/league/commonmark",
"type": "tidelift"
}
],
"time": "2026-08-11T16:06:25+00:00"
},
{
"name": "league/config",
"version": "v1.2.0",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/config.git",
"reference": "754b3604fb2984c71f4af4a9cbe7b57f346ec1f3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/config/zipball/754b3604fb2984c71f4af4a9cbe7b57f346ec1f3",
"reference": "754b3604fb2984c71f4af4a9cbe7b57f346ec1f3",
"shasum": ""
},
"require": {
"dflydev/dot-access-data": "^3.0.1",
"nette/schema": "^1.2",
"php": "^7.4 || ^8.0"
},
"require-dev": {
"phpstan/phpstan": "^1.8.2",
"phpunit/phpunit": "^9.5.5",
"scrutinizer/ocular": "^1.8.1",
"unleashedtech/php-coding-standard": "^3.1",
"vimeo/psalm": "^4.7.3"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "1.2-dev"
}
},
"autoload": {
"psr-4": {
"League\\Config\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Colin O'Dell",
"email": "[email protected]",
"homepage": "https://www.colinodell.com",
"role": "Lead Developer"
}
],
"description": "Define configuration arrays with strict schemas and access values with dot notation",
"homepage": "https://config.thephpleague.com",
"keywords": [
"array",
"config",
"configuration",
"dot",
"dot-access",
"nested",
"schema"
],
"support": {
"docs": "https://config.thephpleague.com/",
"issues": "https://github.com/thephpleague/config/issues",
"rss": "https://github.com/thephpleague/config/releases.atom",
"source": "https://github.com/thephpleague/config"
},
"funding": [
{
"url": "https://www.colinodell.com/sponsor",
"type": "custom"
},
{
"url": "https://www.paypal.me/colinpodell/10.00",
"type": "custom"
},
{
"url": "https://github.com/colinodell",
"type": "github"
}
],
"time": "2022-12-11T20:36:23+00:00"
},
{
"name": "league/flysystem",
"version": "3.35.2",
@@ -3338,6 +3602,164 @@
],
"time": "2025-01-08T20:10:23+00:00"
},
{
"name": "nette/schema",
"version": "v1.3.6",
"source": {
"type": "git",
"url": "https://github.com/nette/schema.git",
"reference": "c54350438cd6914616f790a49cb424605f421562"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/nette/schema/zipball/c54350438cd6914616f790a49cb424605f421562",
"reference": "c54350438cd6914616f790a49cb424605f421562",
"shasum": ""
},
"require": {
"nette/utils": "^4.0",
"php": "8.1 - 8.5"
},
"require-dev": {
"nette/phpstan-rules": "^1.0",
"nette/tester": "^2.6",
"phpstan/extension-installer": "^1.4@stable",
"phpstan/phpstan": "^2.1.39@stable",
"tracy/tracy": "^2.8"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.3-dev"
}
},
"autoload": {
"psr-4": {
"Nette\\": "src"
},
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause",
"GPL-2.0-only",
"GPL-3.0-only"
],
"authors": [
{
"name": "David Grudl",
"homepage": "https://davidgrudl.com"
},
{
"name": "Nette Community",
"homepage": "https://nette.org/contributors"
}
],
"description": "📐 Nette Schema: validating data structures against a given Schema.",
"homepage": "https://nette.org",
"keywords": [
"config",
"nette"
],
"support": {
"issues": "https://github.com/nette/schema/issues",
"source": "https://github.com/nette/schema/tree/v1.3.6"
},
"time": "2026-08-16T21:58:41+00:00"
},
{
"name": "nette/utils",
"version": "v4.1.5",
"source": {
"type": "git",
"url": "https://github.com/nette/utils.git",
"reference": "b043439dbdf954e6c28b5ea7e34b0100f83165e0"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/nette/utils/zipball/b043439dbdf954e6c28b5ea7e34b0100f83165e0",
"reference": "b043439dbdf954e6c28b5ea7e34b0100f83165e0",
"shasum": ""
},
"require": {
"php": "8.2 - 8.5"
},
"conflict": {
"nette/finder": "<3",
"nette/schema": "<1.2.2"
},
"require-dev": {
"jetbrains/phpstorm-attributes": "^1.2",
"nette/phpstan-rules": "^1.0",
"nette/tester": "^2.5",
"phpstan/extension-installer": "^1.4@stable",
"phpstan/phpstan": "^2.1@stable",
"tracy/tracy": "^2.9"
},
"suggest": {
"ext-gd": "to use Image",
"ext-iconv": "to use Strings::chr(), ord() and reverse()",
"ext-intl": "to use Strings::webalize(), toAscii(), normalize() and compare()",
"ext-json": "to use Nette\\Utils\\Json",
"ext-mbstring": "to use Strings::lower() etc...",
"ext-tokenizer": "to use Nette\\Utils\\Reflection::getUseStatements()"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "4.1-dev"
}
},
"autoload": {
"psr-4": {
"Nette\\": "src"
},
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause",
"GPL-2.0-only",
"GPL-3.0-only"
],
"authors": [
{
"name": "David Grudl",
"homepage": "https://davidgrudl.com"
},
{
"name": "Nette Community",
"homepage": "https://nette.org/contributors"
}
],
"description": "🛠 Nette Utils: lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.",
"homepage": "https://nette.org",
"keywords": [
"array",
"core",
"datetime",
"images",
"json",
"nette",
"paginator",
"password",
"slugify",
"string",
"unicode",
"utf-8",
"utility",
"validation"
],
"support": {
"issues": "https://github.com/nette/utils/issues",
"source": "https://github.com/nette/utils/tree/v4.1.5"
},
"time": "2026-07-17T23:02:45+00:00"
},
{
"name": "oneup/uploader-bundle",
"version": "4.0.1",
@@ -11965,16 +12387,16 @@
},
{
"name": "friendsofphp/php-cs-fixer",
"version": "v3.95.18",
"version": "v3.95.20",
"source": {
"type": "git",
"url": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer.git",
"reference": "a8b4e4216faabf67f4e96110ee99a48c96e4e683"
"reference": "4d6c9886a77dbc1db3b9eaca6472cedf9eb1fab7"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/zipball/a8b4e4216faabf67f4e96110ee99a48c96e4e683",
"reference": "a8b4e4216faabf67f4e96110ee99a48c96e4e683",
"url": "https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/zipball/4d6c9886a77dbc1db3b9eaca6472cedf9eb1fab7",
"reference": "4d6c9886a77dbc1db3b9eaca6472cedf9eb1fab7",
"shasum": ""
},
"require": {
@@ -12010,7 +12432,6 @@
"infection/infection": "^0.32.7",
"justinrainbow/json-schema": "^6.10.0",
"keradus/cli-executor": "^2.3",
"mikey179/vfsstream": "^1.6.12",
"php-coveralls/php-coveralls": "^2.9.1",
"php-cs-fixer/phpunit-constraint-isidenticalstring": "^1.8",
"php-cs-fixer/phpunit-constraint-xmlmatchesxsd": "^1.8",
@@ -12058,7 +12479,7 @@
],
"support": {
"issues": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues",
"source": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/tree/v3.95.18"
"source": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/tree/v3.95.20"
},
"funding": [
{
@@ -12066,7 +12487,7 @@
"type": "github"
}
],
"time": "2026-07-30T15:46:02+00:00"
"time": "2026-08-19T16:28:14+00:00"
},
{
"name": "marcocesarato/php-conventional-changelog",
@@ -12148,24 +12569,24 @@
},
{
"name": "masterminds/html5",
"version": "2.10.1",
"version": "2.11.0",
"source": {
"type": "git",
"url": "https://github.com/Masterminds/html5-php.git",
"reference": "fd5018f6815fff903946d0564977b44ce8010e29"
"reference": "a1e7a2f88ee13635d86fc61cfbdf2306a76ddfc7"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Masterminds/html5-php/zipball/fd5018f6815fff903946d0564977b44ce8010e29",
"reference": "fd5018f6815fff903946d0564977b44ce8010e29",
"url": "https://api.github.com/repos/Masterminds/html5-php/zipball/a1e7a2f88ee13635d86fc61cfbdf2306a76ddfc7",
"reference": "a1e7a2f88ee13635d86fc61cfbdf2306a76ddfc7",
"shasum": ""
},
"require": {
"ext-dom": "*",
"php": ">=5.3.0"
"php": ">=7.4"
},
"require-dev": {
"phpunit/phpunit": "^4.8.35 || ^5.7.21 || ^6 || ^7 || ^8 || ^9 || ^10"
"phpunit/phpunit": "^6 || ^7 || ^8 || ^9 || ^10"
},
"type": "library",
"extra": {
@@ -12209,9 +12630,9 @@
],
"support": {
"issues": "https://github.com/Masterminds/html5-php/issues",
"source": "https://github.com/Masterminds/html5-php/tree/2.10.1"
"source": "https://github.com/Masterminds/html5-php/tree/2.11.0"
},
"time": "2026-06-23T18:43:15+00:00"
"time": "2026-08-18T06:18:41+00:00"
},
{
"name": "myclabs/deep-copy",
+11 -9
View File
@@ -5,10 +5,12 @@
# Parsed on demand by App\Config\EmailTextCatalog. This file is NOT loaded by the
# container, which is why it does not live in config/packages/.
#
# The text is plain text, never markup: {platzhalter} tokens are substituted by
# App\Email\EmailTextRenderer after escaping, *Sternchen* make text bold (write \* for a
# literal one), a blank line starts a new paragraph, and bare URLs and mail addresses
# become links by themselves. A placeholder without a value prints "-".
# The body is Markdown, never markup: **fett**, *kursiv*, "## Ueberschrift", "- Liste"
# and "1. Nummerierung" (write \* for a literal asterisk), a blank line starts a new
# paragraph, a single newline stays a line break, and bare URLs and mail addresses become
# links by themselves. Rendered by App\Email\MailBodyRenderer. The headline is plain text
# and takes no Markdown. {platzhalter} tokens are substituted after rendering, escaped, so
# what a teamer wrote can never become markup. A placeholder without a value prints "-".
#
# Every mail closes with the same "Zum Portal" button, rendered by email/layout.html.twig.
@@ -19,7 +21,7 @@ texts:
subject: 'Dein Einsatz wurde angenommen'
headline: 'Herzlichen Glückwunsch!'
body: |-
*Dein Einsatz {destination} wurde angenommen!*
**Dein Einsatz {destination} wurde angenommen!**
Zusätzliche Absprachen: {specialAgreements}
@@ -86,7 +88,7 @@ texts:
body: |-
bitte denke daran, deinen ausgefüllten Honorarvertrag für folgenden Einsatz hochzuladen. Vorher können wir nicht fest mit dir planen und behalten uns vor den Einsatz anderweitig zu vergeben.
*{destination}*
**{destination}**
reminder_invoice_upload:
label: 'Erinnerung: Honorarnote hochladen'
@@ -105,7 +107,7 @@ texts:
body: |-
für deinen Einsatz {destination} liegt uns noch immer keine Honorarnote vor.
Heute endet die Frist von {invoiceUploadDeadlineDays} Tagen nach deinem Einsatz. *Bitte lade deine Honorarnote noch heute hoch* - danach können wir sie eventuell nicht mehr annehmen.
Heute endet die Frist von {invoiceUploadDeadlineDays} Tagen nach deinem Einsatz. **Bitte lade deine Honorarnote noch heute hoch** - danach können wir sie eventuell nicht mehr annehmen.
Bei Fragen melde dich gerne unter [email protected]
@@ -115,11 +117,11 @@ texts:
subject: 'Reminder: Dein Einsatz {destination}'
headline: 'Hallo aus Köln,'
body: |-
dein Einsatz als {jobProfile}, {product} vom {dateFrom} bis {dateTo} beginnt *in {diffInDays} Tagen*.
dein Einsatz als {jobProfile}, {product} vom {dateFrom} bis {dateTo} beginnt **in {diffInDays} Tagen**.
Wir hoffen, dass du ich schon freust und wünschen dir viel Spaß und Erfolg! Finale Infos erhältst du, falls noch nicht geschehen, ein paar Tage vor deinem Einsatz von deinen zuständigen Haus- oder Reisemanager:innen.
Bitte denk daran, deine *ausgefüllte Honorarnote bis zu {invoiceUploadDeadlineDays} Tage nach deinem Einsatz* in My E&P Team hochzuladen.
Bitte denk daran, deine **ausgefüllte Honorarnote bis zu {invoiceUploadDeadlineDays} Tage nach deinem Einsatz** in My E&P Team hochzuladen.
Liebe Grüße,
dein Team Personalabteilung
+31
View File
@@ -4,6 +4,36 @@ parameters:
bpn_crm_id_teamer: '%env(int:APP_BPN_CRM_ID_TEAMER)%'
bpn_default_hotel_code: '%env(default::APP_BPN_DEFAULT_HOTEL_CODE)%'
# BusPro CRM selection id => hotel code. A person holding a selected attribute from this
# list is a house manager for that house. Matched by id and not by the "Hausleitung XXX"
# label, so renaming a selection in BusPro cannot silently grant or revoke a house.
# The commented entries are BusPro selections whose code is not a house in the "houses"
# parameter below: granting them would let someone in who then sees no assignments and
# no dispositions at all. Uncomment one once its house exists. The reverse gap is fine -
# not every house has a selection.
bpn_crm_house_manager_ids:
1299: 'SSL'
1300: 'SST'
1301: 'MVK'
# 1302: 'ASB'
1303: 'LPJ'
1304: 'DKS'
1305: 'DGS'
1306: 'DPW'
1307: 'DKI'
1308: 'DWW'
1309: 'PMV'
# 1352: 'ASG'
1371: 'ASC'
1373: 'PCJ'
1374: 'SBW'
# 1375: 'UCH'
# 1376: 'SZO'
1377: 'KHH'
1459: 'SVS'
1461: 'SHM'
1462: 'AGR'
default_email_from: '%env(APP_DEFAULT_EMAIL_FROM)%'
default_email_to: '%env(APP_DEFAULT_EMAIL_TO)%'
@@ -118,6 +148,7 @@ services:
bpn_crm_id_admin: '%bpn_crm_id_admin%'
bpn_crm_id_manager: '%bpn_crm_id_manager%'
bpn_crm_id_teamer: '%bpn_crm_id_teamer%'
bpn_crm_house_manager_ids: '%bpn_crm_house_manager_ids%'
bpn_default_hotel_code: '%bpn_default_hotel_code%'
App\Twig\AppRuntime:
+100 -39
View File
@@ -3,11 +3,23 @@
Reference for how a user account comes into existence, how it gains and loses roles, and
how it gets blocked. Describes the behaviour as implemented — not a plan.
The governing rule, from which most of the rest follows:
The governing rules, from which the rest follows:
> **The BusPro CRM may nominate, but never grant, an administrative role.** Only a super
> admin turns a nomination into a privilege. The CRM's word alone is enough to *take away*
> access, never to hand it out.
> **BusPro is the source of truth for roles and hotel codes.** Both are synced on every
> login, so anything it no longer reports is withdrawn.
>
> **The CRM may nominate, but never grant, an administrative role.** Only a super admin
> turns a nomination into a privilege. The CRM's word alone is enough to take away access,
> never to hand it out - and an administrator's word alone is enough for neither.
Two corollaries that surprise people:
- **A role cannot be handed out by hand.** The edit form approves what BusPro claims; it
cannot add a role BusPro is silent about, nor remove one it reports. Same for hotel codes,
which are display-only there.
- **Every role stands on its own.** `ROLE_TEAMER` is not a base role others build on, and a
Reisemanager is not a superset of a Hausleitung - somebody claiming both is nominated for
both, and approved for each separately.
---
@@ -16,12 +28,12 @@ The governing rule, from which most of the rest follows:
Defined in `User::ROLES` (`src/Entity/User.php`), these four are the only roles a human can
assign:
| Role | Label | Granted by | Hierarchy |
|------|-------|-----------|-----------|
| `ROLE_ADMIN` | Admin | super admin, manually | ⇒ `ROLE_ADMINISTRATIVE` |
| `ROLE_MANAGER` | Reisemanager | super admin, manually | ⇒ `ROLE_ADMINISTRATIVE` |
| `ROLE_HOUSE_MANAGER` | Hausleitung | super admin, manually | — |
| `ROLE_TEAMER` | Teamer | the CRM, automatically | — |
| Role | Label | Granted by | Revoked by | Hierarchy |
|------|-------|-----------|------------|-----------|
| `ROLE_ADMIN` | Admin | super admin, approving a CRM claim | the CRM, automatically | ⇒ `ROLE_ADMINISTRATIVE` |
| `ROLE_MANAGER` | Reisemanager | super admin, approving a CRM claim | the CRM, automatically | ⇒ `ROLE_ADMINISTRATIVE` |
| `ROLE_HOUSE_MANAGER` | Hausleitung | super admin, approving a CRM claim | the CRM, automatically | — |
| `ROLE_TEAMER` | Teamer | the CRM, automatically | the CRM, automatically | — |
`User::PENDING_ROLES` holds a marker for each of the three administrative roles, keyed by
the role it stands for:
@@ -40,7 +52,9 @@ put the user on the approval list). `ROLE_TEAMER` has no marker: it needs no app
Two further roles are synthesized by `User::getRoles()` and never stored: `ROLE_USER` for
everybody, and `ROLE_SUPER_ADMIN` when the separate `superAdmin` boolean column is set. A
validation callback (`User::validateSuperAdmin()`) refuses `superAdmin` without
`ROLE_ADMIN` alongside it — super admin is an elevation, never a standalone grant.
`ROLE_ADMIN` alongside it — super admin is an elevation, never a standalone grant. The sync
enforces the same rule from the other side: revoking `ROLE_ADMIN` clears the flag, or the one
role that outranks every check in the application would outlive the role it depends on.
### Storage and accessors
@@ -50,8 +64,9 @@ slice it, and picking the right one matters:
| Accessor | Returns |
|----------|---------|
| `getRoles()` | the column **plus** synthesized `ROLE_USER` / `ROLE_SUPER_ADMIN` — what Symfony authorises against |
| `getAssignedRoles()` | only the four real roles from the column — what the edit form binds to |
| `getAssignedRoles()` | only the four real roles from the column — what the sync works on |
| `getPendingRoles()` | only the markers |
| `getNominatedRoles()` | the roles behind those markers, as `role => label` — what an approver acts on |
---
@@ -65,11 +80,17 @@ slice it, and picking the right one matters:
| admin | attribute id `%bpn_crm_id_admin%`, selected | `isAdmin` |
| Reisemanager | attribute id `%bpn_crm_id_manager%`, selected | `isManager` |
| teamer | attribute id `%bpn_crm_id_teamer%`, selected | `isTeamer` |
| Hausleitung | label matching `/^Hausleitung ([A-Z0-9]+)$/`, selected | `isHouseManager` + one hotel code per match |
| Hausleitung | attribute id listed in `%bpn_crm_house_manager_ids%`, selected | `isHouseManager` + the hotel code that id maps to |
`UserDataHandler::collectPendingRoles()` turns those into markers — `isManager` wins over
`isHouseManager`, they are never both claimed, though the hotel codes of a Hausleitung are
imported eitherway. `collectRoles()` is that set plus a real `ROLE_TEAMER` when `isTeamer`.
`bpn_crm_house_manager_ids` (`config/services.yaml`) maps a BusPro selection id to a hotel
code. Entries whose code is not a house in the `houses` parameter are kept commented out:
such a house manager could log in but would see no assignments and no dispositions at all.
`UserDataHandler::collectClaimedRoles()` turns those four booleans into plain role names -
what the CRM says. Two things are made of that list: `toPendingRoles()` produces one marker
per claimed administrative role (the roles are independent, so a Reisemanager who is also a
Hausleitung gets both), and `collectRoles()` produces the markers plus a real `ROLE_TEAMER`,
which is what a brand new account starts with.
### The shape of a BusPro response (important)
@@ -96,6 +117,14 @@ roles were revoked.
>
> Matching is by id and never by label, so `Preisrechner Admin` does not trip the admin flag.
>
> `bpn_crm_house_manager_ids` (`config/services.yaml`) is deployment-critical for the same
> reason, and more sharply so: since roles are synced, an id missing from that map does not
> merely fail to nominate a Hausleitung, it **revokes** the role from everyone holding it, one
> login at a time, with re-approval manual per user. Entries whose hotel code is not a house
> in the `houses` parameter are deliberately commented out there — a person holding only such
> a Hausleitung claims nothing at all and is blocked (see 4) rather than left with a role that
> shows them no data.
>
> `APP_BPN_DEFAULT_HOTEL_CODE` is a testing affordance: when set, **every** admin also
> becomes a house manager for that hotel. It must stay empty outside local development.
@@ -103,7 +132,7 @@ roles were revoked.
## Lifecycle
### 1. First login — the only automatic grant of anything
### 1. First login
`BpnAuthenticator::getOrCreateLocalUser()` → `UserDataHandler::createLocalUser()` writes
`collectRoles()` verbatim, together with the hotel codes from the Hausleitung attributes.
@@ -112,40 +141,70 @@ A CRM admin who is not also a teamer therefore starts with `['ROLE_ADMIN_PENDING
privileges at all: they can authenticate, but `UserChecker` refuses the session until a
super admin approves them.
### 2. Every subsequent login
### 2. Every subsequent login — the sync
`UserDataHandler::updateLocalUser()` refreshes name, email and the teamer record, and then:
`UserDataHandler::updateLocalUser()` refreshes name, email and the teamer record, and hands
the roles to **`syncRoles()`**, which is the whole policy in four steps:
- **`refreshPendingRoles()`** recomputes the marker set from the current CRM claims. A
marker whose real role is already granted is dropped — an approved role is never marked
again. Granted roles are kept untouched.
- **`grantTeamerRole()`** adds `ROLE_TEAMER` if the CRM reports a teamer and the user does
not have it yet. This is deliberately *grant-only*: the role is never withdrawn here,
because it may have been handed out manually and must survive a login. Losing the CRM
teamer attribute while holding no other role blocks the account anyway (see 4).
1. **revoke** every granted role the CRM no longer claims. This is what makes BusPro the
source of truth, and it applies to `ROLE_TEAMER` as much as to the administrative roles.
2. **clear the super admin flag** when `ROLE_ADMIN` was among them — `ROLE_SUPER_ADMIN` is
synthesized from a separate column and would otherwise survive its own precondition.
3. **`refreshPendingRoles()`** recomputes the marker set from the current claims. A marker
whose real role is already granted is dropped — an approved role is never marked again.
It runs *after* the revocation, so a role just revoked is not immediately marked again.
4. **`grantTeamerRole()`** adds `ROLE_TEAMER` when the CRM claims it. Grant-only in itself;
withdrawing it is step 1's business.
Administrative roles and hotel codes are imported at creation and are managed by hand
afterwards. Nothing on this path can raise a privilege.
**`syncHotelCodes()`** then replaces the hotel codes with the ones the CRM reports, so a
Hausleitung who moves house is not left seeing the old one.
Nothing on this path can raise a privilege: step 3 only ever produces markers.
The same two methods run on the MyE&P SSO path (`MyEpAuthenticator`), against the eligible
roles it reports — one policy, two identity sources.
### 3. Approval — turning a marker into a role
`/admin/system/user/edit/{id}`, `UserType`, gated by `UserVoter::EDIT`: super admin only,
never yourself, never while impersonating.
The `roles` field binds to `assignedRoles`, whose setter **replaces the whole column**.
Consequences to be aware of:
The page keeps three things apart, because they follow three different rules:
- Approving is "tick the real role and save". The marker disappears because the column is
rewritten from the ticked choices.
- Saving the form drops *every* marker, including ones you did not act on.
- A denial is not recorded anywhere. As long as the CRM keeps claiming the role, the marker
returns on that user's next login.
| Block | What it is |
|-------|-----------|
| **Aus BusPro** | information, not a form: granted roles, houses, last login. Synced on every login and editable nowhere in this application |
| **Freischaltung** | one action per nomination — a button, a confirmation dialog, its own route (`ApproveRoleController`). Only shown when the user carries a marker |
| **Account** | the actual form (`UserType`): super admin, block, block reasons |
### 4. Revocation — demotion by the CRM
None of this is a disabled form field. Roles and hotel codes are simply not fields, so there
is nothing to submit and nothing that looks editable but is not.
**Approval is its own act**, deliberately not a checkbox on the form: it grants a privilege,
so it is confirmed on its own, logged on its own, and cannot happen as a side effect of
saving an unrelated setting. `UserDataHandler::approveRole()` refuses any role the user has
no marker for, so a hand-crafted URL cannot grant one the CRM never claimed, and the check
runs again on submit to catch a sync that revoked the claim while the dialog was open.
A denial is not recorded anywhere: as long as the CRM keeps claiming the role, the
nomination is back on the next login.
**Super admin** is only offered to somebody who already holds `ROLE_ADMIN` — approve first,
elevate afterwards. The one exception is a flag that outlived its role, which stays editable
so the account can be saved at all while `User::validateSuperAdmin()` is violated; the sync
clears it (see 2), so it should never occur in practice.
The user list marks nominations with their own badge — it is the only place an approver would
look for them.
### 4. Losing everything — the block
Revocation of an *individual* role is step 1 of the sync above. This section is the stronger
case: the CRM claims **nothing at all**, which is not a demotion but an exit.
Evaluated on every login, in `BpnAuthenticator::getOrCreateLocalUser()`, before the local
user is even loaded. If `collectRoles()` is empty, the CRM grants this person nothing in
this application, so they are not a user of it:
user is even loaded. If `collectClaimedRoles()` is empty, the CRM grants this person nothing
in this application, so they are not a user of it:
| Situation | Outcome |
|-----------|---------|
@@ -159,7 +218,9 @@ pending markers — they no longer reflect the CRM. **Granted roles are kept**,
stays reviewable.
Two preconditions guard this branch, because "no roles" is otherwise indistinguishable from
"the CRM told us nothing":
"the CRM told us nothing". They now protect the sync as well: a degraded response that got
past them would not merely block one account, it would strip the roles of every user logging
in.
1. the response must be a `CrmAttributesResponse` — BusPro answers with a notification
record on its own errors;
+64
View File
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Admin-edited mail bodies used to be plain text in which a single *asterisk* made a word
* bold. They are Markdown now (App\Email\MailBodyRenderer), where that is italic and bold
* is written **twice**, so every saved body is rewritten once.
*
* Only `body` is touched: `subject` never took markers, and `headline` is plain text under
* the new renderer, so a marker left in one is meant to stay the character it is.
*/
final class Version20260820000000 extends AbstractMigration
{
/**
* A single asterisk pair on one line. The lookarounds keep three things out: an already
* doubled **bold**, an escaped \* an admin wrote to get a literal asterisk, and a marker
* with whitespace next to it - "a * b * c" and "5 * 3" are arithmetic, not emphasis.
* That last rule is CommonMark's own, and slightly stricter than the renderer this
* replaces: a text that leant on the old, laxer matching loses its bold here rather
* than turning into something nobody wrote.
*/
private const SINGLE_EMPHASIS = '/(?<![\\\\*])\*(?!\*)(?!\s)([^*\n]+?)(?<![\s\\\\*])\*(?!\*)/u';
private const DOUBLE_EMPHASIS = '/(?<![\\\\*])\*\*(?!\*)(?!\s)([^*\n]+?)(?<![\s\\\\*])\*\*(?!\*)/u';
public function getDescription(): string
{
return 'Rewrite *bold* to **bold** in saved email texts, which are Markdown now';
}
public function up(Schema $schema): void
{
$this->rewriteBodies(self::SINGLE_EMPHASIS, '**$1**');
}
public function down(Schema $schema): void
{
$this->rewriteBodies(self::DOUBLE_EMPHASIS, '*$1*');
}
/**
* The rewrite happens in PHP, one row at a time: MySQL's REGEXP_REPLACE has no
* lookbehind, and getting this wrong would quietly mangle wording that goes out to
* every teamer. Only the read is done here and now - the writes go through addSql, so
* they are logged and rolled back like any other migration statement.
*/
private function rewriteBodies(string $pattern, string $replacement): void
{
foreach ($this->connection->fetchAllAssociative('SELECT id, body FROM email_text') as $row) {
$body = preg_replace($pattern, $replacement, (string) $row['body']);
if (null === $body || $body === $row['body']) {
continue;
}
$this->addSql('UPDATE email_text SET body = ? WHERE id = ?', [$body, $row['id']]);
}
}
}
+7 -3
View File
@@ -185,9 +185,12 @@ class ResponseParser
;
$attributes[] = $attribute;
if (1 === preg_match('/^Hausleitung ([A-Z0-9]+)$/', $attributeLabel, $matches) && true === $attribute->isSelected()) {
// Matched by id, like every other role: the "Hausleitung XXX" label is BusPro
// wording and must not decide who gets access to which house.
$houseManagerCode = $this->config['bpn_crm_house_manager_ids'][$attribute->getId()] ?? null;
if (null !== $houseManagerCode && true === $attribute->isSelected()) {
$isHouseManager = true;
$hotelCodes[] = $matches[1];
$hotelCodes[] = $houseManagerCode;
}
if ($this->config['bpn_crm_id_admin'] === $attribute->getId() && true === $attribute->isSelected()) {
$isAdmin = true;
@@ -294,13 +297,14 @@ class ResponseParser
private function resolveOptions(array $options): array
{
$optionsResolver = new OptionsResolver();
$optionsResolver->setRequired(['bpn_crm_id_admin', 'bpn_crm_id_manager', 'bpn_crm_id_teamer']);
$optionsResolver->setRequired(['bpn_crm_id_admin', 'bpn_crm_id_manager', 'bpn_crm_id_teamer', 'bpn_crm_house_manager_ids']);
$optionsResolver->setDefaults([
'bpn_default_hotel_code' => null,
]);
$optionsResolver->setAllowedTypes('bpn_crm_id_admin', 'int');
$optionsResolver->setAllowedTypes('bpn_crm_id_manager', 'int');
$optionsResolver->setAllowedTypes('bpn_crm_id_teamer', 'int');
$optionsResolver->setAllowedTypes('bpn_crm_house_manager_ids', 'array');
$optionsResolver->setAllowedTypes('bpn_default_hotel_code', ['string', 'null']);
return $optionsResolver->resolve($options);
+192 -27
View File
@@ -14,9 +14,17 @@ use Psr\Log\LoggerInterface;
/**
* Owns the role policy for local user accounts, whatever identity source reports them.
* The importing of BusPro profile data is specific to the CRM, but the role rules -
* toPendingRoles(), refreshPendingRoles() and grantTeamerRole() - are deliberately
* shared with the MyE&P SSO login (see App\Security\MyEpAuthenticator), so that no
* identity source can grant an administrative role this application would not.
* toPendingRoles() and everything syncRoles() composes - are deliberately shared with
* the MyE&P SSO login (see App\Security\MyEpAuthenticator), so that no identity source
* can grant an administrative role this application would not.
*
* The policy in one paragraph: the identity source leads. Every role it no longer claims
* is revoked on the next login, and the hotel codes are re-imported with them. What it
* claims is not granted, though: an administrative role arrives as a privilege-free
* marker and only a super admin turns it into the real role. ROLE_TEAMER is the exception
* that needs no approval - it carries no privileges of its own - and is granted outright.
* Nobody can therefore escalate through the CRM, and nobody keeps an access the CRM has
* taken away.
*/
class UserDataHandler
{
@@ -27,7 +35,7 @@ class UserDataHandler
}
/**
* Collects the roles to grant on initial user creation.
* Collects the roles to store on initial user creation.
*
* Administrative roles are deliberately not importable: they may only be granted
* manually by a super admin, so that nobody can escalate their own privileges via
@@ -48,9 +56,15 @@ class UserDataHandler
}
/**
* Collects the pending markers for the administrative roles claimed in the CRM.
* The roles the CRM claims for this person, as plain role names.
*
* This is what the CRM says, not what the application grants for it - see syncRoles()
* for that. Named after MyEpAuthenticator::collectClaimedRoles(), which produces the
* same shape from the SSO claims, so that one policy can serve both identity sources.
*
* @return string[]
*/
public function collectPendingRoles(CrmAttributesResponse $crmAttributes): array
public function collectClaimedRoles(CrmAttributesResponse $crmAttributes): array
{
$claimedRoles = [];
@@ -66,7 +80,19 @@ class UserDataHandler
$claimedRoles[] = 'ROLE_HOUSE_MANAGER';
}
return $this->toPendingRoles($claimedRoles);
if ($crmAttributes->isTeamer()) {
$claimedRoles[] = 'ROLE_TEAMER';
}
return $claimedRoles;
}
/**
* Collects the pending markers for the administrative roles claimed in the CRM.
*/
public function collectPendingRoles(CrmAttributesResponse $crmAttributes): array
{
return $this->toPendingRoles($this->collectClaimedRoles($crmAttributes));
}
/**
@@ -75,6 +101,10 @@ class UserDataHandler
* attributes, expressed over plain role names so that any identity source can use
* it. ROLE_TEAMER has no marker and is dropped here: it needs no approval.
*
* Every claimed role gets its own marker. The roles stand on their own - a manager is
* not a super-set of a house manager - so somebody claiming both is approved for both,
* one decision at a time.
*
* @param string[] $claimedRoles
*
* @return string[]
@@ -83,15 +113,10 @@ class UserDataHandler
{
$roles = [];
if (true === in_array('ROLE_ADMIN', $claimedRoles, true)) {
$roles[] = User::PENDING_ROLES['ROLE_ADMIN'];
}
// a manager outranks a house manager, so only the higher marker is kept
if (true === in_array('ROLE_MANAGER', $claimedRoles, true)) {
$roles[] = User::PENDING_ROLES['ROLE_MANAGER'];
} elseif (true === in_array('ROLE_HOUSE_MANAGER', $claimedRoles, true)) {
$roles[] = User::PENDING_ROLES['ROLE_HOUSE_MANAGER'];
foreach (User::PENDING_ROLES as $role => $pendingRole) {
if (true === in_array($role, $claimedRoles, true)) {
$roles[] = $pendingRole;
}
}
return $roles;
@@ -209,13 +234,11 @@ class UserDataHandler
/**
* Updates an existing user from BusPro data.
*
* Administrative roles and hotel codes are imported once on user creation only and are
* managed manually afterwards, so they are intentionally left untouched here. The
* exceptions are the privilege-free pending markers, which keep tracking the
* administrative roles claimed in the CRM, and ROLE_TEAMER, which needs no approval
* and is granted to whoever the CRM reports as a teamer.
* The CRM leads: roles and hotel codes are re-synced on every login, so a role or a
* house it no longer reports is gone. Granting still needs approval - see syncRoles().
*
* @param string[] $claimedRoles pending markers as returned by collectPendingRoles()
* @param string[] $claimedRoles plain role names as returned by collectClaimedRoles()
* @param string[] $hotelCodes the houses the CRM reports for this person
*/
public function updateLocalUser(
User $user,
@@ -223,6 +246,7 @@ class UserDataHandler
bool $isTeamer = false,
array $crmSelections = [],
array $claimedRoles = [],
array $hotelCodes = [],
): void {
$user
->setFirstName($profileResponse->getFirstName())
@@ -230,11 +254,10 @@ class UserDataHandler
->setEmail($profileResponse->getCommunication()->getEmail())
;
$this->refreshPendingRoles($user, $claimedRoles);
$this->syncRoles($user, $claimedRoles);
$this->syncHotelCodes($user, $hotelCodes);
if (true === $isTeamer) {
$this->grantTeamerRole($user);
$address = Address::fromApiResponse($profileResponse);
$communication = Communication::fromApiResponse($profileResponse);
if (null === $user->getTeamer()) {
@@ -306,6 +329,148 @@ class UserDataHandler
]);
}
/**
* Turns a nomination into the real role - the one role decision left to a human.
*
* Only a role the identity source currently claims can be approved, and the marker is
* what says so: no marker, nothing to approve, whoever asked for it. Everything else
* the user holds is left exactly as it is, markers for other roles included.
*
* Returns false when there is nothing to approve, so the caller can refuse the request
* rather than silently granting a role off a hand-crafted URL.
*/
public function approveRole(User $user, string $role): bool
{
$pendingRole = User::PENDING_ROLES[$role] ?? null;
if (null === $pendingRole || false === in_array($pendingRole, $user->getPendingRoles(), true)) {
return false;
}
$user->setRoles([
...$user->getAssignedRoles(),
$role,
...array_values(array_diff($user->getPendingRoles(), [$pendingRole])),
]);
$this->entityManager->flush();
$this->logger->info('Approve role', [
'user_id' => $user->getId(),
'user_email' => $user->getEmail(),
'role' => $role,
]);
return true;
}
/**
* Brings a user's roles in line with what the identity source claims for them.
*
* The whole policy, in the order it has to run:
*
* 1. revoke what is no longer claimed - the identity source leads;
* 2. drop the super admin flag along with ROLE_ADMIN, or the highest privilege in the
* application would outlive the role it depends on;
* 3. refresh the pending markers, after the revocation so that a role just revoked is
* not immediately marked again - it is unclaimed in both steps;
* 4. grant ROLE_TEAMER, the one role that needs no approval.
*
* Nothing here grants an administrative role: step 3 only ever produces markers, and
* turning one into the real role is a super admin's decision.
*
* Does not flush; the caller decides when to.
*
* @param string[] $claimedRoles plain role names, e.g. from collectClaimedRoles()
*/
public function syncRoles(User $user, array $claimedRoles): void
{
$this->revokeUnclaimedRoles($user, $claimedRoles);
$this->refreshPendingRoles($user, $this->toPendingRoles($claimedRoles));
if (true === in_array('ROLE_TEAMER', $claimedRoles, true)) {
$this->grantTeamerRole($user);
}
}
/**
* Replaces the houses a user is responsible for with the ones the identity source
* reports. They are led by the CRM just like the roles are, so a house manager who
* moves house is not left seeing their old one.
*
* Does not flush; the caller decides when to.
*
* @param string[] $hotelCodes
*/
public function syncHotelCodes(User $user, array $hotelCodes): void
{
$hotelCodes = array_values($hotelCodes);
if ($hotelCodes === $user->getHotelCodes()) {
return;
}
$user->setHotelCodes($hotelCodes);
$this->logger->info('Sync hotel codes', [
'user_id' => $user->getId(),
'user_email' => $user->getEmail(),
'hotel_codes' => $hotelCodes,
]);
}
/**
* Withdraws every granted role the identity source no longer claims.
*
* Only the roles of User::ROLES are touched: getAssignedRoles() excludes the pending
* markers as well as the implicit ROLE_USER, and the markers are dealt with by
* refreshPendingRoles(). ROLE_SUPER_ADMIN is not a stored role at all but a flag, so
* it is handled separately below.
*
* @param string[] $claimedRoles
*/
private function revokeUnclaimedRoles(User $user, array $claimedRoles): void
{
$grantedRoles = $user->getAssignedRoles();
$keptRoles = array_values(array_intersect($grantedRoles, $claimedRoles));
if ($keptRoles === $grantedRoles) {
return;
}
$user->setRoles([...$keptRoles, ...$user->getPendingRoles()]);
$this->logger->info('Revoke roles no longer claimed', [
'user_id' => $user->getId(),
'user_email' => $user->getEmail(),
'revoked_roles' => array_values(array_diff($grantedRoles, $keptRoles)),
]);
$this->revokeSuperAdminWithoutRoleAdmin($user);
}
/**
* Takes the super admin flag down with ROLE_ADMIN.
*
* The flag is stored on its own and getRoles() turns it into ROLE_SUPER_ADMIN whatever
* else the user holds, so without this a person the CRM no longer calls an admin would
* keep the one role that outranks every check in the application. User::validateSuperAdmin()
* enforces the same rule on the edit form, but only there.
*/
private function revokeSuperAdminWithoutRoleAdmin(User $user): void
{
if (false === $user->isSuperAdmin() || true === $user->hasRole('ROLE_ADMIN')) {
return;
}
$user->setSuperAdmin(false);
$this->logger->info('Revoke super admin flag along with ROLE_ADMIN', [
'user_id' => $user->getId(),
'user_email' => $user->getEmail(),
]);
}
/**
* Grants ROLE_TEAMER to a user the CRM reports as a teamer.
*
@@ -314,8 +479,8 @@ class UserDataHandler
* area, and a teamer without it would be left with a teamer record they cannot reach,
* or locked out entirely for holding no assignable role at all.
*
* It is never withdrawn here. Losing the CRM attribute while holding no other role
* blocks the account anyway, and a role handed out manually must survive a login.
* Grant-only in itself - withdrawing it is revokeUnclaimedRoles()' business, which
* syncRoles() runs first.
*
* Does not flush; the caller decides when to.
*/
@@ -35,8 +35,8 @@ class IndexController extends AbstractController
$request->query->getInt('page', 1),
$request->query->getInt('limit', 50),
[
'defaultSortFieldName' => 'destination.dateFrom',
'defaultSortDirection' => 'asc',
'defaultSortFieldName' => 'application.createdAt',
'defaultSortDirection' => 'desc',
]
);
@@ -0,0 +1,55 @@
<?php
namespace App\Controller\Admin\System\User;
use App\BusProNet\UserDataHandler;
use App\Entity\User;
use App\Htmx\HxRedirectResponse;
use App\Security\Voter\UserVoter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* Granting a privilege is its own act, deliberately not a checkbox on the user edit form:
* it is confirmed on its own, logged on its own, and cannot happen as a side effect of
* saving an unrelated setting. It is also the only way a role is ever granted at all -
* everything else about roles is synced from BusPro (see docs/user-roles.md).
*/
class ApproveRoleController extends AbstractController
{
public function __construct(private readonly UserDataHandler $userDataHandler)
{
}
#[Route('/admin/system/user/approve-role/{id}/{role}', name: 'app_admin_system_user_approve_role')]
#[IsGranted(UserVoter::EDIT, subject: 'user')]
public function index(User $user, string $role, Request $request): Response
{
// nothing but a role this user is actually nominated for, so a hand-crafted URL
// cannot grant one BusPro never claimed
$pendingRole = User::PENDING_ROLES[$role] ?? null;
if (null === $pendingRole || false === in_array($pendingRole, $user->getPendingRoles(), true)) {
throw $this->createNotFoundException('Für diese Rolle liegt keine Freischaltung vor');
}
if (true === $request->isMethod(Request::METHOD_POST)) {
// checked again by the handler, which is what catches a sync revoking the claim
// between opening the dialog and confirming it
if (false === $this->userDataHandler->approveRole($user, $role)) {
throw $this->createNotFoundException('Für diese Rolle liegt keine Freischaltung vor');
}
$this->addFlash('success', sprintf('Die Rolle %s wurde freigeschaltet', User::ROLES[$role]));
return new HxRedirectResponse($this->generateUrl('app_admin_system_user_edit', ['id' => $user->getId()]));
}
return $this->render('admin/system/user/modal_approve_role.html.twig', [
'user' => $user,
'roleLabel' => User::ROLES[$role],
]);
}
}
@@ -2,6 +2,7 @@
namespace App\Controller\Admin\System\User;
use App\Config\HouseCatalog;
use App\Entity\User;
use App\Form\UserType;
use App\Security\Voter\UserVoter;
@@ -18,6 +19,7 @@ class EditController extends AbstractController
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly LoggerInterface $logger,
private readonly HouseCatalog $houseCatalog,
) {
}
@@ -44,9 +46,21 @@ class EditController extends AbstractController
return $this->redirectToRoute('app_admin_system_user_index');
}
// a code with no house behind it stays visible under its own name rather than
// vanishing from the page - it is what the user is actually restricted to
$houses = [];
foreach ($user->getHotelCodes() as $code) {
$houses[$code] = $this->houseCatalog->getName($code) ?? $code;
}
return $this->render('admin/system/user/edit.html.twig', [
'form' => $form,
'user' => $user,
'grantedRoles' => array_map(
static fn (string $role): string => User::ROLES[$role],
$user->getAssignedRoles(),
),
'houses' => $houses,
]);
}
}
@@ -3,9 +3,11 @@
namespace App\Controller\Admin\Teamer;
use App\Controller\Traits\ReturnUrlTrait;
use App\Email\MailBodyRenderer;
use App\Form\TeamerMailingType;
use App\Htmx\HxRedirectResponse;
use App\Message\SendTeamerMailing;
use App\Model\TeamerMailingDto;
use App\Service\Common\TeamerFilterHandler;
use App\Service\Teamer\TeamerMailingDraftHandler;
use App\Service\Teamer\TeamerMailingService;
@@ -25,6 +27,7 @@ class MailingController extends AbstractController
private readonly TeamerFilterHandler $filterHandler,
private readonly TeamerMailingService $mailingService,
private readonly TeamerMailingDraftHandler $draftHandler,
private readonly MailBodyRenderer $mailBodyRenderer,
private readonly MessageBusInterface $messageBus,
) {
}
@@ -54,9 +57,12 @@ class MailingController extends AbstractController
$filterDto = $this->filterHandler->getFilterSettings();
// no redirect after the preview, the composed mail has to survive it
// No redirect after the preview mail, the composed mail has to survive it. The
// preview pane is rendered here so the page arrives complete; from then on the
// draft route above keeps it up to date.
return $this->render('admin/teamer/mailing.html.twig', [
'form' => $form->createView(),
'preview' => $this->renderPreview($form->getData()),
'filterDto' => $filterDto,
'recipients' => $this->mailingService->resolveRecipients($filterDto),
'placeholders' => TeamerMailingService::PLACEHOLDERS,
@@ -66,16 +72,22 @@ class MailingController extends AbstractController
}
/**
* Park what has been typed so far, so that a trip to the filter and back does not
* throw the composed mail away. Answers nothing, the page stays as it is.
* Park what has been typed so far, so that a trip to the filter and back does not throw
* the composed mail away, and answer with the preview of that very draft.
*
* Both hang off the same form content, so they are deliberately one request rather than
* two routes on the same keystroke: the preview can never show wording other than the
* one that was parked.
*/
#[Route('/admin/teamer/mailing/draft', name: 'app_admin_teamer_mailing_draft', methods: ['POST'])]
#[IsGranted('ROLE_ADMIN')]
public function draft(Request $request): Response
{
$this->draftHandler->saveDraft($this->createMailingForm($request)->getData());
$mailingDto = $this->createMailingForm($request)->getData();
return new Response(null, Response::HTTP_NO_CONTENT);
$this->draftHandler->saveDraft($mailingDto);
return $this->render('admin/teamer/_mailing_preview.html.twig', $this->renderPreview($mailingDto));
}
#[Route('/admin/teamer/mailing/discard', name: 'app_admin_teamer_mailing_discard')]
@@ -140,6 +152,26 @@ class MailingController extends AbstractController
return new HxRedirectResponse($this->generateUrl('app_administrative_teamer_index'));
}
/**
* What the composing admin would receive. The placeholders are filled from their own
* record, the same way sendPreview() fills the test mail, so the pane and the mail that
* lands in their inbox show the same name.
*
* Deliberately rendered whether or not the form validates: a mail that is still missing
* its subject is exactly the one an admin is looking at while writing it.
*
* @return array{subject: string, bodyHtml: string}
*/
private function renderPreview(TeamerMailingDto $mailingDto): array
{
$values = $this->mailingService->placeholderValuesForUser($this->getUser());
return [
'subject' => $this->mailingService->render($mailingDto->getSubject(), $values),
'bodyHtml' => $this->mailBodyRenderer->render($mailingDto->getMessage(), $values),
];
}
/**
* A GET starts from the parked draft, a POST always carries the current one itself.
*/
+22 -85
View File
@@ -8,12 +8,12 @@ use App\Model\RenderedEmailTextDto;
use App\Repository\EmailTextRepository;
/**
* Turns the plain text an admin wrote into the HTML of a transactional mail.
* Turns the text an admin wrote into the HTML of a transactional mail.
*
* Admins write plain text with {placeholder} tokens and *bold* markers - never markup,
* never Twig. Everything an admin or a teamer typed is escaped here before any tag is
* introduced, which is the only reason email/generic.html.twig may print the result with
* |raw. The order of operations below is load-bearing; see the comments on each step.
* Admins write Markdown with {placeholder} tokens - never markup, never Twig. The body is
* handed to App\Email\MailBodyRenderer, which is where the escaping that makes
* email/generic.html.twig's |raw safe happens; subject and headline are plain text and
* are dealt with here.
*/
class EmailTextRenderer
{
@@ -32,6 +32,7 @@ class EmailTextRenderer
public function __construct(
private readonly EmailTextCatalog $catalog,
private readonly EmailTextRepository $emailTextRepository,
private readonly MailBodyRenderer $mailBodyRenderer,
) {
}
@@ -68,103 +69,39 @@ class EmailTextRenderer
): RenderedEmailTextDto {
$definition = $this->catalog->get($key);
// Two token maps from the same values: the subject of a mail is plain text, the
// body is HTML. Escaping happens here, before substitution, so that neither the
// admin's copy nor a teamer's own words (reason, comment, specialAgreements) can
// introduce a tag.
$plainTokens = [];
// Three token maps from the same values, because the three parts of a mail are not
// the same kind of text: the subject is a plain header, the headline is escaped
// plain text, and the body is Markdown the renderer escapes for us.
$rawTokens = [];
$htmlTokens = [];
foreach ($definition->getPlaceholderNames() as $name) {
$value = (string) ($placeholders[$name] ?? '');
$value = '' === trim($value) ? self::EMPTY_VALUE : $value;
$plainTokens['{'.$name.'}'] = $value;
$rawTokens['{'.$name.'}'] = $value;
$htmlTokens['{'.$name.'}'] = htmlspecialchars($value, self::ESCAPE_FLAGS, 'UTF-8');
}
return new RenderedEmailTextDto(
strtr($subject ?? '', $plainTokens),
$this->prepare($headline ?? '', $htmlTokens),
$this->renderBody($body ?? '', $htmlTokens),
strtr($subject ?? '', $rawTokens),
$this->renderHeadline($headline ?? '', $htmlTokens),
$this->mailBodyRenderer->render($body ?? '', $rawTokens),
);
}
/**
* The headline is set as the mail's own <h1>, so it deliberately takes no Markdown:
* emphasis inside an already bold heading says nothing, and a stray "-" or "#" at the
* start of one should stay the character it is.
*
* @param array<string, string> $tokens
*/
private function renderBody(string $body, array $tokens): string
private function renderHeadline(string $headline, array $tokens): string
{
$body = $this->prepare($body, $tokens);
// Blank lines separate paragraphs, single newlines are soft breaks. The mail
// layout styles <p> with its own margins, so keeping real paragraphs preserves
// the spacing the hand-written templates had - a single <p> full of <br> would
// collapse it. nl2br then handles the breaks inside a block, which is what
// multi-line values such as a rejection comment need.
$paragraphs = [];
foreach (preg_split('/\R{2,}/', $body) as $block) {
$block = trim($block);
if ('' === $block) {
continue;
}
$paragraphs[] = '<p>'.nl2br($block).'</p>';
}
return $this->linkify(implode("\n", $paragraphs));
}
/**
* @param array<string, string> $tokens
*/
private function prepare(string $text, array $tokens): string
{
$text = $this->emphasise(htmlspecialchars(trim($text), self::ESCAPE_FLAGS, 'UTF-8'));
// Substituting last means asterisks and URLs inside a value stay literal: only
// what an admin wrote can turn into a tag.
return strtr($text, $tokens);
}
/**
* Markdown-style *bold*. Runs on the already escaped string, so the only tag it can
* ever produce is <strong>. A literal asterisk is written \*.
*/
private function emphasise(string $text): string
{
$text = preg_replace(
'/(?<!\\\\)\*([^*\n]+)(?<!\\\\)\*/',
'<strong>$1</strong>',
$text
);
return str_replace('\*', '*', $text);
}
/**
* Makes bare URLs and mail addresses clickable, so dropping the inline links the
* hand-written templates had does not cost the reader anything. One pass over an
* alternation, so a match is never linked twice.
*/
private function linkify(string $html): string
{
return preg_replace_callback(
'~(?<url>https?://[^\s<]+)|(?<email>[\w.+-]+@[\w-]+(?:\.[\w-]+)+)~',
static function (array $match): string {
if ('' !== ($match['url'] ?? '')) {
// Sentence punctuation is not part of the address.
$url = rtrim($match['url'], '.,;:!?)');
$trailing = substr($match['url'], strlen($url));
return sprintf('<a href="%s">%s</a>%s', $url, $url, $trailing);
}
return sprintf('<a href="mailto:%1$s">%1$s</a>', $match['email']);
},
$html
return strtr(
htmlspecialchars(trim($headline), self::ESCAPE_FLAGS, 'UTF-8'),
$tokens
);
}
}
+138
View File
@@ -0,0 +1,138 @@
<?php
namespace App\Email;
use League\CommonMark\Environment\Environment;
use League\CommonMark\Event\DocumentParsedEvent;
use League\CommonMark\Extension\Autolink\AutolinkExtension;
use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension;
use League\CommonMark\Extension\CommonMark\Node\Block\Heading;
use League\CommonMark\Extension\CommonMark\Node\Inline\Image;
use League\CommonMark\MarkdownConverter;
use League\CommonMark\Node\Inline\Text;
use League\CommonMark\Node\Node;
/**
* Turns the Markdown an admin wrote into the HTML body of a mail.
*
* Admins write Markdown with {platzhalter} tokens - never markup, never Twig. Two rules
* carry the whole safety argument, and both are load-bearing:
*
* 1. Only what an admin typed goes through the parser. Everything that is substituted for
* a token afterwards is escaped, so a teamer's own words (a rejection comment, their
* name) can never introduce a tag, a heading or a list - no matter what they contain.
* 2. Markup an admin types is stripped rather than passed through, so even the admin side
* cannot smuggle a <script> in.
*
* That is what lets email/generic.html.twig and email/teamer_mailing.html.twig print the
* result with |raw. Do not pass anything into those templates that did not come out of here.
*/
class MailBodyRenderer
{
/**
* Substituted text only ever lands in element content, never in an attribute, so
* single quotes stay readable instead of turning into &#039; mid-sentence.
*/
private const ESCAPE_FLAGS = ENT_COMPAT | ENT_SUBSTITUTE;
/**
* The mail layout puts its own <h1> above the body (the headline field), and styles
* nothing below <h3>. An admin's "#" must not outrank the one, "####" must not fall
* out of the other, so every heading is folded into that range.
*/
private const MIN_HEADING_LEVEL = 2;
private const MAX_HEADING_LEVEL = 3;
private readonly MarkdownConverter $converter;
public function __construct()
{
$environment = new Environment([
// Markup an admin types is dropped instead of passed through.
'html_input' => 'strip',
'allow_unsafe_links' => false,
'renderer' => [
// CommonMark would turn a single newline into a bare "\n", which a mail
// client does not show. The hand-written texts predate Markdown and use
// single newlines as real line breaks, so they stay visible.
'soft_break' => "<br />\n",
],
]);
$environment->addExtension(new CommonMarkCoreExtension());
// Replaces the hand-rolled linkify(): bare URLs and mail addresses become links.
$environment->addExtension(new AutolinkExtension());
$environment->addEventListener(DocumentParsedEvent::class, $this->constrainDocument(...));
$this->converter = new MarkdownConverter($environment);
}
/**
* @param array<string, string> $tokenValues keyed by the whole token as it appears in
* the text, "{destination}" or "{{vorname}}"
*/
public function render(?string $markdown, array $tokenValues): string
{
// Trimmed on both ends: the converter closes with a newline, which is nothing but
// noise in a mail body and makes the rendered HTML awkward to assert against.
$html = trim($this->converter->convert(trim((string) $markdown))->getContent());
// Substituting last is the point: braces mean nothing to CommonMark, so the tokens
// survive the parser untouched and only the admin's own text has become markup by
// the time any value is put in.
return strtr($html, array_map($this->escapeValue(...), $tokenValues));
}
/**
* Values are escaped but keep their line breaks - a multi-line rejection comment must
* not run together into one line. Blank lines inside a value do not start a new
* paragraph: the structure of a mail is the admin's to decide, not the teamer's.
*/
private function escapeValue(string $value): string
{
return nl2br(htmlspecialchars($value, self::ESCAPE_FLAGS, 'UTF-8'));
}
/**
* Trims the parsed document down to what a mail can actually show. Runs once over the
* tree after parsing, which is cheaper and far more reliable than trying to forbid the
* syntax on the way in.
*/
private function constrainDocument(DocumentParsedEvent $event): void
{
$nodes = [];
foreach ($event->getDocument()->iterator() as $node) {
$nodes[] = $node;
}
// Collected first, changed after: replacing a node while the iterator is walking
// the very same tree would skip its neighbours.
foreach ($nodes as $node) {
if ($node instanceof Heading) {
$node->setLevel(max(self::MIN_HEADING_LEVEL, min(self::MAX_HEADING_LEVEL, $node->getLevel())));
continue;
}
// An image in a mailing would be an external image loaded from an address
// nobody reviewed, so only its alt text survives.
if ($node instanceof Image) {
$node->replaceWith(new Text($this->textOf($node)));
}
}
}
private function textOf(Node $node): string
{
$text = '';
foreach ($node->iterator() as $child) {
if ($child instanceof Text) {
$text .= $child->getLiteral();
}
}
return $text;
}
}
+21
View File
@@ -231,6 +231,27 @@ class User implements UserInterface, TimestampableEntityInterface, SoftDeletable
return array_values(array_intersect($this->roles, array_keys(self::ROLES)));
}
/**
* The roles this user is nominated for but does not hold, as role => label.
*
* The markers are storage; this is what an approver acts on, so it is keyed by the real
* role rather than by the marker standing in for it.
*
* @return array<string, string>
*/
public function getNominatedRoles(): array
{
$roles = [];
foreach (self::PENDING_ROLES as $role => $pendingRole) {
if (true === in_array($pendingRole, $this->roles, true)) {
$roles[$role] = self::ROLES[$role];
}
}
return $roles;
}
/**
* The pending markers currently held by the user.
*/
+24 -29
View File
@@ -2,7 +2,6 @@
namespace App\Form;
use App\Config\HouseCatalog;
use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
@@ -12,27 +11,20 @@ use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* The account settings of an administrative user - and nothing else.
*
* Roles and hotel codes are synced from BusPro on every login and are not editable here or
* anywhere else, so they are not fields: the edit page renders them as information. The one
* role decision left to a human, approving a nomination, is its own action with its own
* confirmation (see App\Controller\Admin\System\User\ApproveRoleController). Keeping all
* three apart is deliberate - a form field that cannot be submitted only looks broken.
*/
class UserType extends AbstractType
{
public function __construct(private readonly HouseCatalog $houseCatalog)
{
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('roles', MultiselectType::class, [
'label' => 'Rollen',
'required' => false,
'property_path' => 'assignedRoles',
'choices' => array_flip(User::ROLES),
'empty_label' => 'keine Rolle',
])
->add('superAdmin', CheckboxType::class, [
'label' => 'Superadmin',
'required' => false,
'help' => 'Setzt die Rolle Admin voraus.',
])
->add('disabled', CheckboxType::class, [
'label' => 'Account gesperrt',
'required' => false,
@@ -74,23 +66,26 @@ class UserType extends AbstractType
;
});
// hotel codes already assigned to the user may predate the catalog, so they are
// added as choices to keep them selectable instead of failing
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event): void {
// Super admin is an elevation of an existing role, never a grant of its own, so the
// field exists only for somebody who already holds ROLE_ADMIN - offering it to
// anyone else would only produce the violation from User::validateSuperAdmin().
// A flag already set without the role is the exception: it has to stay editable, or
// that user could not be saved at all until BusPro claims them an admin again.
$builder->addEventListener(FormEvents::PRE_SET_DATA, static function (FormEvent $event): void {
$user = $event->getData();
$choices = $this->houseCatalog->getCodeChoices();
foreach ($user instanceof User ? $user->getHotelCodes() : [] as $code) {
if (false === in_array($code, $choices, true)) {
$choices[$code] = $code;
}
if (false === $user instanceof User) {
return;
}
$event->getForm()->add('hotelCodes', MultiselectType::class, [
'label' => 'Häuser',
if (false === in_array('ROLE_ADMIN', $user->getAssignedRoles(), true) && false === $user->isSuperAdmin()) {
return;
}
$event->getForm()->add('superAdmin', CheckboxType::class, [
'label' => 'Superadmin',
'required' => false,
'choices' => $choices,
'empty_label' => 'keine Häuser',
'help' => 'Darf Rollen freischalten und Accounts verwalten.',
]);
});
}
+13 -5
View File
@@ -128,8 +128,15 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
// Determine teamer status from CRM attributes
$isTeamer = $crmAttributes->isTeamer();
// Everything the CRM grants this person here: pending markers plus ROLE_TEAMER
// What the CRM claims, as plain role names, and what this application makes of it:
// pending markers plus ROLE_TEAMER. The first drives the sync, the second is what
// a new account starts with.
$claimedRoles = $this
->userDataHandler
->collectClaimedRoles($crmAttributes)
;
$grantedRoles = $this
->userDataHandler
->collectRoles($crmAttributes)
;
@@ -180,8 +187,8 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
return $user;
}
// Update existing user's teamer data and return it, leaving roles and hotel
// codes alone: they are imported once on creation and managed manually after
// Update the existing user, re-syncing roles and hotel codes from the CRM: it
// leads, so a role or a house it no longer reports is withdrawn here
if (null !== $user) {
$this
->userDataHandler
@@ -190,7 +197,8 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
$profileResponse,
$isTeamer,
$crmSelections,
$this->userDataHandler->collectPendingRoles($crmAttributes),
$claimedRoles,
$crmAttributes->getHotelCodes(),
)
;
@@ -202,7 +210,7 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
->userDataHandler
->createLocalUser(
$profileResponse,
$claimedRoles,
$grantedRoles,
$isTeamer,
$crmSelections,
$crmAttributes->getHotelCodes(),
+22 -11
View File
@@ -161,6 +161,7 @@ class MyEpAuthenticator extends AbstractAuthenticator
$isTeamer = in_array('ROLE_TEAMER', $claimedRoles, true);
$pendingRoles = $this->userDataHandler->toPendingRoles($claimedRoles);
$hotelCodes = $this->collectHotelCodes($userinfo);
$user = $this->findLocalUser($userinfo);
@@ -177,23 +178,20 @@ class MyEpAuthenticator extends AbstractAuthenticator
return $user;
}
// Update existing user, leaving granted roles and hotel codes alone: they are
// imported once on creation and managed manually afterwards. Only the
// privilege-free markers and ROLE_TEAMER track MyE&P on every login.
// Update existing user. MyE&P leads here exactly as BusPro does on the other login
// path - the shared policy in UserDataHandler withdraws what is no longer claimed
// and marks administrative claims for approval rather than granting them.
if (null !== $user) {
$this->refreshBusProIds($user, $userinfo);
$this->userDataHandler->refreshPendingRoles($user, $pendingRoles);
if (true === $isTeamer) {
$this->userDataHandler->grantTeamerRole($user);
}
$this->userDataHandler->syncRoles($user, $claimedRoles);
$this->userDataHandler->syncHotelCodes($user, $hotelCodes);
$this->entityManager->flush();
return $user;
}
return $this->createLocalUser($userinfo, $pendingRoles, $isTeamer);
return $this->createLocalUser($userinfo, $pendingRoles, $isTeamer, $hotelCodes);
}
/**
@@ -233,6 +231,19 @@ class MyEpAuthenticator extends AbstractAuthenticator
return $claimedRoles;
}
/**
* The houses MyE&P reports for this person. Read on both the create and the update
* path, since they are led by the identity provider just like the roles are.
*
* @return string[]
*/
private function collectHotelCodes(array $userinfo): array
{
$profile = is_array($userinfo['profile'] ?? null) ? $userinfo['profile'] : [];
return is_array($profile['hotel_codes'] ?? null) ? array_values($profile['hotel_codes']) : [];
}
/**
* Matches the local account on the BusPro ids first and falls back to the email, the
* same precedence UserDataHandler::findLocalUser() applies to a BusPro login, so that
@@ -300,8 +311,9 @@ class MyEpAuthenticator extends AbstractAuthenticator
/**
* @param string[] $pendingRoles
* @param string[] $hotelCodes
*/
private function createLocalUser(array $userinfo, array $pendingRoles, bool $isTeamer): ?User
private function createLocalUser(array $userinfo, array $pendingRoles, bool $isTeamer, array $hotelCodes): ?User
{
$addressId = $userinfo['address_id'] ?? null;
$personId = $userinfo['person_id'] ?? null;
@@ -318,7 +330,6 @@ class MyEpAuthenticator extends AbstractAuthenticator
}
$profile = is_array($userinfo['profile'] ?? null) ? $userinfo['profile'] : [];
$hotelCodes = is_array($profile['hotel_codes'] ?? null) ? $profile['hotel_codes'] : [];
$user = new User();
$user
+12 -6
View File
@@ -2,6 +2,7 @@
namespace App\Service\Teamer;
use App\Email\MailBodyRenderer;
use App\Email\Mailer;
use App\Entity\User;
use App\Message\SendTeamerMailing;
@@ -37,6 +38,7 @@ class TeamerMailingService
public function __construct(
private readonly TeamerRepository $teamerRepository,
private readonly Mailer $mailer,
private readonly MailBodyRenderer $mailBodyRenderer,
private readonly LoggerInterface $logger,
// messenger transport, "mailing" in production and "sync" in dev and test,
// see the parameter of the same name in services.yaml
@@ -98,7 +100,7 @@ class TeamerMailingService
$this->sendTo(
$recipient['email'],
$this->render($mailing->getSubject(), $values),
$this->render($mailing->getMessage(), $values),
$this->mailBodyRenderer->render($mailing->getMessage(), $values),
self::TRANSPORT,
$this->mailingBusTransport
);
@@ -121,7 +123,7 @@ class TeamerMailingService
$this->sendTo(
$admin->getUserIdentifier(),
self::PREVIEW_SUBJECT_PREFIX.$this->render($mailingDto->getSubject(), $values),
$this->render($mailingDto->getMessage(), $values)
$this->mailBodyRenderer->render($mailingDto->getMessage(), $values)
);
$this->logger->info('Send teamer mailing preview', [
@@ -131,8 +133,10 @@ class TeamerMailingService
}
/**
* Replace the known placeholders. Anything that merely looks like a placeholder is
* left alone - a typo should not silently blank out part of the mail.
* Replace the known placeholders in a subject line. Anything that merely looks like a
* placeholder is left alone - a typo should not silently blank out part of the mail.
* The message body does not come through here: it is Markdown, and
* App\Email\MailBodyRenderer has to escape the values before it puts them in.
*/
public function render(?string $text, array $values): string
{
@@ -195,12 +199,14 @@ class TeamerMailingService
private function sendTo(
string $email,
string $subject,
string $message,
string $bodyHtml,
?string $transport = null,
?string $busTransport = null,
): void {
// $bodyHtml is already rendered and escaped mail HTML, see MailBodyRenderer -
// email/teamer_mailing.html.twig prints it with |raw.
$this->mailer->createAndSendEmail([
'message' => $message,
'bodyHtml' => $bodyHtml,
], [
'to' => $email,
'subject' => $subject,
@@ -0,0 +1,24 @@
{# Shown under both mail editors, so an admin meets the same syntax in each of them. #}
<div class="text-sm text-gray-500">
<div class="pb-2">
Formatierung der Nachricht:
</div>
<div class="flex flex-wrap gap-2">
{% for example, label in {
'**fett**': 'fett',
'*kursiv*': 'kursiv',
'## Überschrift': 'Überschrift',
'- Punkt': 'Aufzählung',
'1. Punkt': 'Nummerierung',
} %}
<span class="inline-flex items-center space-x-1 py-1 px-2 bg-gray-50 border border-gray-200 rounded">
<code>{{ example }}</code>
<span>{{ label }}</span>
</span>
{% endfor %}
</div>
<div class="pt-2">
Eine Leerzeile beginnt einen neuen Absatz, Links und E-Mail-Adressen werden
automatisch verlinkt.
</div>
</div>
+7 -1
View File
@@ -49,6 +49,9 @@
<th>
{{ knp_pagination_sortable(pagination, 'Bus', 'destination.pickup') }}
</th>
<th>
{{ knp_pagination_sortable(pagination, 'erstellt am', 'application.createdAt') }}
</th>
<th>
{{ knp_pagination_sortable(pagination, 'Bewerber:in', 'teamer.lastName') }}
</th>
@@ -96,6 +99,9 @@
-
{% endif %}
</td>
<td>
{{ application.createdAt | date('d.m.Y, H:i') }}
</td>
<td>
<a href="{{ path('app_administrative_assignment_detail', { 'uuid': assignment.uuid, 'r': return_url() }) }}">
{{ application.teamer }}
@@ -137,4 +143,4 @@
{{ knp_pagination_render(pagination) }}
</div>
</div>
{% endblock %}
{% endblock %}
@@ -4,6 +4,8 @@
{{ form_row(form.headline) }}
{{ form_row(form.body) }}
{{ include('_partials/_markdown_hint.html.twig') }}
<div class="bg-gray-100 rounded-md p-4 text-sm">
<div class="font-bold pb-2">
Verfügbare Platzhalter
@@ -6,9 +6,9 @@
{% if text.headline is not empty %}
<h1 class="text-xl font-bold pb-2">{{ text.headline | raw }}</h1>
{% endif %}
{# The paragraphs come from the mail body, where email/layout.html.twig styles every
<p> with padding-bottom:16px - pb-4 is the same spacing, so the preview matches. #}
<div class="[&>p]:pb-4 [&_a]:underline">
{# .mail-body carries the spacing and list styling of email/layout.html.twig, so this
pane and the mailing pane both show what the mail will look like. #}
<div class="mail-body">
{{ text.bodyHtml | raw }}
</div>
<p>
+4 -3
View File
@@ -1,8 +1,9 @@
{{ form_start(form) }}
<div class="flex flex-col space-y-4 pb-8">
{{ form_row(form.roles) }}
{{ form_row(form.superAdmin) }}
{{ form_row(form.hotelCodes) }}
{# only present for somebody who already holds ROLE_ADMIN, see UserType #}
{% if form.superAdmin is defined %}
{{ form_row(form.superAdmin) }}
{% endif %}
{{ form_row(form.disabled) }}
{{ form_row(form.disabledReason) }}
{{ form_row(form.disabledReasonInternal) }}
@@ -7,6 +7,85 @@
<h1 class="text-2xl font-bold pb-8">
{{ user.fullName }} bearbeiten
</h1>
<div class="pb-10">
<h2 class="text-lg font-bold pb-1">
Aus BusPro
</h2>
<p class="text-sm text-gray-500 pb-2">
Wird bei jeder Anmeldung übernommen und kann hier nicht geändert werden.
</p>
<dl class="divide-y divide-gray-100 border-t border-gray-100">
<div class="py-4 sm:grid sm:grid-cols-3 sm:gap-4">
<dt class="text-sm font-bold leading-6 text-gray-900">
Zugewiesene Rollen
</dt>
<dd class="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0">
{{ grantedRoles|join(', ')|default('keine Rolle') }}
{% if user.superAdmin %}
<div class="text-gray-500">
Superadmin
</div>
{% endif %}
</dd>
</div>
<div class="py-4 sm:grid sm:grid-cols-3 sm:gap-4">
<dt class="text-sm font-bold leading-6 text-gray-900">
Zugewiesene Häuser
</dt>
<dd class="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0">
{% for code, name in houses %}
<div>
{{ name }} <span class="text-gray-500">({{ code }})</span>
</div>
{% else %}
-
{% endfor %}
</dd>
</div>
<div class="py-4 sm:grid sm:grid-cols-3 sm:gap-4">
<dt class="text-sm font-bold leading-6 text-gray-900">
Letzter Login
</dt>
<dd class="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0">
{{ user.lastLoginAt ? user.lastLoginAt|date('d.m.Y, H:i') : '-' }}
</dd>
</div>
</dl>
</div>
{# Its own act, with its own confirmation: granting a privilege must not happen as a
side effect of saving something else on this page. #}
{% if user.nominatedRoles is not empty %}
<div class="pb-10">
<h2 class="text-lg font-bold pb-1">
Freischaltung
</h2>
<p class="text-sm text-gray-500 pb-2">
In BusPro beansprucht, aber noch nicht freigeschaltet.
</p>
<ul class="divide-y divide-gray-100 border-t border-gray-100">
{% for role, label in user.nominatedRoles %}
<li class="py-3 flex items-center justify-between">
<span class="text-sm">
{{ label }}
</span>
<button type="button"
class="btn btn--secondary"
hx-get="{{ path('app_admin_system_user_approve_role', { 'id': user.id, 'role': role }) }}"
hx-target="body"
hx-swap="beforeend">
Freischalten
</button>
</li>
{% endfor %}
</ul>
</div>
{% endif %}
<h2 class="text-lg font-bold pb-2">
Account
</h2>
{% include 'admin/system/user/_form.html.twig' %}
</div>
{% endblock %}
+8 -2
View File
@@ -48,7 +48,13 @@
{{ user.email }}
</td>
<td>
{{ user.rolesLabels|join(', ') }}
{% set grantedRoles = user.assignedRoles|map(role => constant('App\\Entity\\User::ROLES')[role]) %}
{{ grantedRoles is empty ? '-' : grantedRoles|join(', ') }}
{% for label in user.nominatedRoles %}
<span class="inline-block mt-1 py-1 px-2 text-xs bg-amber-500 text-gray-700 rounded-md">
{{ label }} angefordert
</span>
{% endfor %}
</td>
<td class="text-center">
{% if user.superAdmin %}
@@ -91,4 +97,4 @@
</table>
</div>
</div>
{% endblock %}
{% endblock %}
@@ -0,0 +1,12 @@
{% extends 'htmx_confirmation_modal.html.twig' %}
{% block content %}
<div class="pb-4">
Möchtest du die Rolle <em>{{ roleLabel }}</em> für <em>{{ user.fullName }}</em> wirklich freischalten?
</div>
<div>
Die Rolle wird damit sofort wirksam. Sie wird automatisch wieder entzogen, sobald sie in BusPro nicht mehr beansprucht wird.
</div>
{% endblock %}
{% block button_confirm %}Freischalten{% endblock %}
@@ -0,0 +1,15 @@
<div class="pb-4">
<span class="font-bold">Betreff:</span> {{ subject }}
</div>
{# App\Email\MailBodyRenderer escaped everything before it introduced a tag, which is what
makes |raw safe here - see the contract on that class. #}
<div class="mail-body border border-gray-200 rounded-md p-4">
{{ bodyHtml | raw }}
<p>
<span class="btn inline-block">Zum Portal</span>
</p>
</div>
<div class="pt-4 text-sm text-gray-500">
Platzhalter sind mit deinem eigenen Namen gefüllt, beim Versand steht dort der Name der
jeweiligen Person. Logo und Fußzeile der E-Mail sind hier nicht abgebildet.
</div>
+56 -21
View File
@@ -27,29 +27,64 @@
{% endif %}
</div>
{# the draft is parked on every keystroke so that a trip to the filter and back keeps it,
hx-trigger replaces htmx' default submit trigger, the preview button still posts natively #}
{{ form_start(form, { 'attr': {
'hx-post': path('app_admin_teamer_mailing_draft'),
'hx-trigger': 'input changed delay:500ms',
'hx-swap': 'none',
} }) }}
<div class="flex flex-col space-y-4 pb-4 max-w-3xl">
{{ form_row(form.subject) }}
{{ form_row(form.message) }}
</div>
{# One request per keystroke parks the draft - so that a trip to the filter and back
keeps it - and answers with the preview, which is why the response is swapped into
the pane instead of being thrown away. hx-trigger replaces htmx' default submit
trigger, the "Vorschau an mich senden" button still posts natively.
<div class="pb-8 max-w-3xl text-sm text-gray-500">
<div class="pb-2">
Platzhalter für Betreff und Nachricht, sie werden beim Senden pro Person ersetzt:
Deliberately without htmx' "changed" modifier: it compares the listening element's
.value between events, and a <form> has none, so every event compares undefined to
undefined and the request is never sent. The 500ms delay is what keeps the typing
from flooding the route. #}
{{ form_start(form, { 'attr': {
'id': 'mailing-form',
'hx-post': path('app_admin_teamer_mailing_draft'),
'hx-trigger': 'input delay:500ms',
'hx-target': '#mailing-preview',
'hx-swap': 'innerHTML',
'hx-indicator': '#mailing-preview-indicator',
} }) }}
<div class="grid lg:grid-cols-2 gap-8 items-start">
<div>
<div class="flex flex-col space-y-4 pb-4">
{{ form_row(form.subject) }}
{{ form_row(form.message) }}
</div>
<div class="pb-6">
{{ include('_partials/_markdown_hint.html.twig') }}
</div>
<div class="pb-8 text-sm text-gray-500">
<div class="pb-2">
Platzhalter für Betreff und Nachricht, sie werden beim Senden pro Person ersetzt:
</div>
<div class="flex flex-wrap gap-2">
{% for placeholder, label in placeholders %}
<span class="inline-flex items-center space-x-1 py-1 px-2 bg-gray-50 border border-gray-200 rounded">
<code>{{ placeholder }}</code>
<span>{{ label }}</span>
</span>
{% endfor %}
</div>
</div>
</div>
<div class="flex flex-wrap gap-2">
{% for placeholder, label in placeholders %}
<span class="inline-flex items-center space-x-1 py-1 px-2 bg-gray-50 border border-gray-200 rounded">
<code>{{ placeholder }}</code>
<span>{{ label }}</span>
</span>
{% endfor %}
<div class="lg:sticky lg:top-4">
<div class="font-bold pb-2">
Vorschau
</div>
<div class="relative">
<div id="mailing-preview">
{{ include('admin/teamer/_mailing_preview.html.twig', preview) }}
</div>
{# Deliberately a sibling of the swap target, not a child: hx-swap replaces
the target's contents, which would carry the indicator away with them. #}
<div class="htmx-indicator absolute inset-0 bg-white/75 flex items-center justify-center"
id="mailing-preview-indicator">
{{ include('_partials/_spinner.html.twig', { 'class': 'w-8 h-8' }) }}
</div>
</div>
</div>
</div>
+41 -10
View File
@@ -1,5 +1,5 @@
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<html lang="und" dir="auto" xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<title>MyE&amp;P Team</title>
@@ -116,7 +116,16 @@
font-size: 20px;
line-height: 24px;
margin-bottom: 0;
padding-bottom: 0;
/* Was 0 while an h2 only ever preceded a p, which brings its own spacing. */
padding-bottom: 8px;
}
h3 {
font-weight: bold;
font-size: 17px;
line-height: 22px;
margin-bottom: 0;
padding-bottom: 4px;
}
p {
@@ -152,12 +161,28 @@
font-weight: bold;
}
em {
font-style: italic;
}
ul,
ol {
/* Margin, not padding: Outlook on Windows renders list padding unreliably. */
margin: 0 0 16px 24px;
padding: 0;
font-size: 16px;
}
li {
padding-bottom: 4px;
}
</style>
</head>
<body style="word-spacing:normal;background-color:#666666;">
<div style="display:none;font-size:1px;color:#ffffff;line-height:1px;max-height:0px;max-width:0px;opacity:0;overflow:hidden;">MyE&amp;P Team</div>
<div style="background-color:#666666;">
<div aria-label="MyE&amp;P Team" aria-roledescription="email" style="background-color:#666666;" role="article" lang="und" dir="auto">
<!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:600px;" width="600" ><tr><td style="line-height:0;font-size:0;mso-line-height-rule:exactly;"><v:image style="border:0;mso-position-horizontal:center;position:absolute;top:0;width:600px;z-index:-3;" xmlns:v="urn:schemas-microsoft-com:vml" /><![endif]-->
<div style="margin:0 auto;max-width:600px;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
@@ -215,16 +240,22 @@
<div style="font-family:Lato, Verdana, Arial, 'Helvetica neue', sans-serif;font-size:16px;line-height:24px;text-align:left;color:#666666;">{% block body %} <h1> Lorem ipsum dolor sit amet </h1>
<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto culpa delectus dolores earum eius fugiat in nesciunt quas quidem vitae? </p>
<h2> Lorem ipsum dolor </h2>
<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto culpa delectus dolores <strong>earum eius fugiat in nesciunt quas quidem vitae</strong>? </p>
<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto culpa delectus dolores <strong>earum eius fugiat in nesciunt quas quidem vitae</strong>, <em>eius fugiat</em>? </p>
<ul>
<li>Lorem ipsum dolor</li>
<li>Consectetur adipisicing elit</li>
</ul>
<h3> Lorem ipsum </h3>
<ol>
<li>Lorem ipsum dolor</li>
<li>Consectetur adipisicing elit</li>
</ol>
<p>
<a href="#" class="button"> Button </a>
</p>
<p class="small"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Doloribus, eveniet! </p> {% endblock %}
{% block button %}
<p>
<a href="{{ url('app_index') }}" class="button">Zum Portal</a>
</p>
{% endblock %}
<p class="small"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Doloribus, eveniet! </p> {% endblock %} {% block button %} <p>
<a href="{{ url('app_index') }}" class="button">Zum Portal</a>
</p> {% endblock %}
</div>
</td>
</tr>
+4 -3
View File
@@ -1,7 +1,8 @@
{% extends 'email/layout.html.twig' %}
{# Everything on `bodyHtml` was escaped by App\Email\MailBodyRenderer before any tag was
introduced, which is what makes |raw safe here - same contract as email/generic.html.twig.
Do not pass anything into this template that did not come out of that renderer. #}
{% block body %}
<p>
{{ message | nl2br }}
</p>
{{ bodyHtml | raw }}
{% endblock %}
+27
View File
@@ -86,6 +86,25 @@ class ResponseParserTest extends TestCase
$this->assertCount(3, $response->getAttributeGroups());
}
/**
* The house of a "Hausleitung" selection comes from the configured id map, never from the
* label: an id that is not mapped grants nothing. That is also what keeps the houses
* commented out in bpn_crm_house_manager_ids from letting someone in who would then see
* no assignments and no dispositions at all.
*/
public function testParseCrmAttributesIgnoresAnUnmappedHouseManagerSelection(): void
{
$content = '<?xml version="1.0" encoding="utf-8"?><ergebnis><satz typ="KUNDENKONTO"></satz><art>SelektionCRM</art><idadresse>141747</idadresse><idperson>224526</idperson><selektionsmerkmale><selektionsgruppe id="10" bezeichnung="TEAM"><selektion id="1070" bezeichnung="E&amp;P Teamer - allg. Merkmal" aenderbar="False" auswahl="True"></selektion><selektion id="9999" bezeichnung="Hausleitung XYZ" aenderbar="False" auswahl="True"></selektion></selektionsgruppe></selektionsmerkmale></ergebnis>';
$parser = $this->getParserInstance();
$response = $parser->parseXmlString(ApiClient::TYPE_CUSTOMER_DATA, $content);
$this->assertInstanceOf(CrmAttributesResponse::class, $response);
$this->assertTrue($response->isTeamer());
$this->assertFalse($response->isHouseManager());
$this->assertSame([], $response->getHotelCodes());
}
public function testParseCrmAttributesOfAnEmptyResponse(): void
{
$content = '<?xml version="1.0" encoding="utf-8"?><ergebnis><satz typ="KUNDENKONTO"></satz><art>SelektionCRM</art><idadresse>141747</idadresse><idperson>224526</idperson><selektionsmerkmale></selektionsmerkmale></ergebnis>';
@@ -170,6 +189,14 @@ class ResponseParserTest extends TestCase
'bpn_crm_id_admin' => 1292,
'bpn_crm_id_manager' => 1293,
'bpn_crm_id_teamer' => 1070,
// Deliberately a small excerpt of the configured map: the fixtures only carry
// these three houses, and 1301 is here to be a mapped id no fixture selects.
'bpn_crm_house_manager_ids' => [
1299 => 'SSL',
1301 => 'MVK',
1304 => 'DKS',
1305 => 'DGS',
],
]);
}
}
+152 -20
View File
@@ -72,9 +72,9 @@ class UserDataHandlerTest extends TestCase
[User::PENDING_ROLES['ROLE_ADMIN'], User::PENDING_ROLES['ROLE_MANAGER']],
];
yield 'manager takes precedence over house manager' => [
yield 'manager and house manager yield both markers, the roles stand on their own' => [
(new CrmAttributesResponse())->setManager(true)->setHouseManager(true),
[User::PENDING_ROLES['ROLE_MANAGER']],
[User::PENDING_ROLES['ROLE_MANAGER'], User::PENDING_ROLES['ROLE_HOUSE_MANAGER']],
];
yield 'house manager and teamer' => [
@@ -105,10 +105,10 @@ class UserDataHandlerTest extends TestCase
[User::PENDING_ROLES['ROLE_ADMIN']],
];
yield 'manager takes precedence over house manager' => [
yield 'manager and house manager are marked independently' => [
['ROLE_HOUSE_MANAGER', 'ROLE_MANAGER'],
(new CrmAttributesResponse())->setManager(true)->setHouseManager(true),
[User::PENDING_ROLES['ROLE_MANAGER']],
[User::PENDING_ROLES['ROLE_MANAGER'], User::PENDING_ROLES['ROLE_HOUSE_MANAGER']],
];
yield 'house manager' => [
@@ -172,14 +172,16 @@ class UserDataHandlerTest extends TestCase
$profileResponse,
true,
['team' => ['selected' => true]],
['ROLE_ADMIN', 'ROLE_TEAMER'],
['DKS'],
);
$this->assertSame('New', $user->getFirstName());
$this->assertSame('Lastname', $user->getLastName());
$this->assertSame('[email protected]', $user->getEmail());
// roles and hotel codes are imported on creation only and stay under manual control
$this->assertSame(['XYZ'], $user->getHotelCodes());
// the CRM leads: the still claimed role survives, the houses are replaced by its own
$this->assertSame(['DKS'], $user->getHotelCodes());
$this->assertTrue($user->hasRole('ROLE_ADMIN'));
$this->assertSame('New', $teamer->getFirstName());
@@ -225,44 +227,51 @@ class UserDataHandlerTest extends TestCase
{
yield 'marker is added when the CRM claims a manager' => [
['ROLE_TEAMER'],
[User::PENDING_ROLES['ROLE_MANAGER']],
['ROLE_MANAGER', 'ROLE_TEAMER'],
['ROLE_TEAMER'],
[User::PENDING_ROLES['ROLE_MANAGER']],
];
yield 'marker is dropped when the CRM attribute is gone' => [
[User::PENDING_ROLES['ROLE_HOUSE_MANAGER'], 'ROLE_TEAMER'],
[],
['ROLE_TEAMER'],
['ROLE_TEAMER'],
[],
];
yield 'an approved role is never marked again' => [
['ROLE_MANAGER'],
[User::PENDING_ROLES['ROLE_MANAGER']],
['ROLE_MANAGER'],
['ROLE_MANAGER'],
[],
];
yield 'a claim beyond the approved role stays pending' => [
['ROLE_MANAGER'],
[User::PENDING_ROLES['ROLE_ADMIN'], User::PENDING_ROLES['ROLE_MANAGER']],
['ROLE_ADMIN', 'ROLE_MANAGER'],
['ROLE_MANAGER'],
[User::PENDING_ROLES['ROLE_ADMIN']],
];
yield 'the claimed role changes' => [
[User::PENDING_ROLES['ROLE_HOUSE_MANAGER']],
[User::PENDING_ROLES['ROLE_MANAGER']],
['ROLE_MANAGER'],
[],
[User::PENDING_ROLES['ROLE_MANAGER']],
];
yield 'granted roles are untouched without any claim' => [
['ROLE_ADMIN'],
yield 'a granted role is revoked once the CRM stops claiming it' => [
['ROLE_ADMIN', 'ROLE_TEAMER'],
['ROLE_TEAMER'],
['ROLE_TEAMER'],
[],
['ROLE_ADMIN'],
];
yield 'a manager who is also a house manager is marked for both' => [
[],
['ROLE_MANAGER', 'ROLE_HOUSE_MANAGER'],
[],
[User::PENDING_ROLES['ROLE_MANAGER'], User::PENDING_ROLES['ROLE_HOUSE_MANAGER']],
];
}
@@ -277,15 +286,18 @@ class UserDataHandlerTest extends TestCase
;
$handler = new UserDataHandler($this->entityManager, $this->logger);
$handler->updateLocalUser($user, $this->createProfileResponse(), true, [], [User::PENDING_ROLES['ROLE_ADMIN']]);
$handler->updateLocalUser($user, $this->createProfileResponse(), true, [], ['ROLE_ADMIN', 'ROLE_TEAMER']);
$this->assertSame(['ROLE_TEAMER'], $user->getAssignedRoles());
$this->assertSame([User::PENDING_ROLES['ROLE_ADMIN']], $user->getPendingRoles());
}
public function testUpdateLocalUserKeepsTheTeamerRoleOfSomebodyTheCrmNoLongerReportsAsTeamer(): void
/**
* ROLE_TEAMER needs no approval, but it is not exempt from the sync either: the CRM
* leads, so the role goes when the attribute does.
*/
public function testUpdateLocalUserWithdrawsTheTeamerRoleOfSomebodyTheCrmNoLongerReportsAsTeamer(): void
{
// the role may have been granted manually and must survive a login
$user = (new User())
->setFirstName('First')
->setLastName('Last')
@@ -294,9 +306,9 @@ class UserDataHandlerTest extends TestCase
;
$handler = new UserDataHandler($this->entityManager, $this->logger);
$handler->updateLocalUser($user, $this->createProfileResponse(), false, [], []);
$handler->updateLocalUser($user, $this->createProfileResponse(), false, [], ['ROLE_ADMIN']);
$this->assertSame(['ROLE_ADMIN', 'ROLE_TEAMER'], $user->getAssignedRoles());
$this->assertSame(['ROLE_ADMIN'], $user->getAssignedRoles());
}
public function testUpdateLocalUserGrantsTheTeamerRoleOnlyOnce(): void
@@ -309,11 +321,131 @@ class UserDataHandlerTest extends TestCase
;
$handler = new UserDataHandler($this->entityManager, $this->logger);
$handler->updateLocalUser($user, $this->createProfileResponse(), true, [], []);
$handler->updateLocalUser($user, $this->createProfileResponse(), true, [], ['ROLE_TEAMER']);
$this->assertSame(['ROLE_TEAMER'], $user->getAssignedRoles());
}
/**
* ROLE_SUPER_ADMIN is not a stored role but a flag getRoles() turns into one, so
* revoking ROLE_ADMIN has to take it down explicitly - otherwise the highest privilege
* in the application would outlive the role it depends on.
*/
public function testUpdateLocalUserTakesTheSuperAdminFlagDownWithRoleAdmin(): void
{
$user = (new User())
->setFirstName('First')
->setLastName('Last')
->setEmail('[email protected]')
->setRoles(['ROLE_ADMIN', 'ROLE_TEAMER'])
->setSuperAdmin(true)
;
$handler = new UserDataHandler($this->entityManager, $this->logger);
$handler->updateLocalUser($user, $this->createProfileResponse(), true, [], ['ROLE_TEAMER']);
$this->assertSame(['ROLE_TEAMER'], $user->getAssignedRoles());
$this->assertFalse($user->isSuperAdmin());
$this->assertFalse($user->hasRole('ROLE_SUPER_ADMIN'));
}
public function testUpdateLocalUserKeepsTheSuperAdminFlagOfAStillClaimedAdmin(): void
{
$user = (new User())
->setFirstName('First')
->setLastName('Last')
->setEmail('[email protected]')
->setRoles(['ROLE_ADMIN', 'ROLE_TEAMER'])
->setSuperAdmin(true)
;
$handler = new UserDataHandler($this->entityManager, $this->logger);
$handler->updateLocalUser($user, $this->createProfileResponse(), false, [], ['ROLE_ADMIN']);
$this->assertTrue($user->isSuperAdmin());
$this->assertTrue($user->hasRole('ROLE_SUPER_ADMIN'));
}
public function testUpdateLocalUserReplacesTheHotelCodesWithTheOnesTheCrmReports(): void
{
$user = (new User())
->setFirstName('First')
->setLastName('Last')
->setEmail('[email protected]')
->setRoles(['ROLE_HOUSE_MANAGER'])
->setHotelCodes(['SSL'])
;
$handler = new UserDataHandler($this->entityManager, $this->logger);
$handler->updateLocalUser($user, $this->createProfileResponse(), false, [], ['ROLE_HOUSE_MANAGER'], ['DKS']);
$this->assertSame(['DKS'], $user->getHotelCodes());
}
/**
* Approval is the one place a role is granted at all, and it can only ever grant a role
* the CRM already claims - the marker is what says so.
*/
public function testApproveRoleGrantsTheRoleAndClearsItsMarker(): void
{
$user = (new User())
->setFirstName('First')
->setLastName('Last')
->setEmail('[email protected]')
->setRoles([
'ROLE_TEAMER',
User::PENDING_ROLES['ROLE_ADMIN'],
User::PENDING_ROLES['ROLE_HOUSE_MANAGER'],
])
;
$this->entityManager->expects($this->once())->method('flush');
$handler = new UserDataHandler($this->entityManager, $this->logger);
$this->assertTrue($handler->approveRole($user, 'ROLE_ADMIN'));
$this->assertSame(['ROLE_TEAMER', 'ROLE_ADMIN'], $user->getAssignedRoles());
// the other nomination is untouched: one decision at a time
$this->assertSame([User::PENDING_ROLES['ROLE_HOUSE_MANAGER']], $user->getPendingRoles());
}
/**
* @dataProvider unapprovableRoleProvider
*/
public function testApproveRoleRefusesARoleWithoutANomination(array $roles, string $role): void
{
$user = (new User())
->setFirstName('First')
->setLastName('Last')
->setEmail('[email protected]')
->setRoles($roles)
;
$this->entityManager->expects($this->never())->method('flush');
$handler = new UserDataHandler($this->entityManager, $this->logger);
$this->assertFalse($handler->approveRole($user, $role));
$this->assertEqualsCanonicalizing(
$roles,
[...$user->getAssignedRoles(), ...$user->getPendingRoles()],
);
}
public static function unapprovableRoleProvider(): iterable
{
yield 'the CRM never claimed it' => [['ROLE_TEAMER'], 'ROLE_MANAGER'];
yield 'a different role is nominated' => [[User::PENDING_ROLES['ROLE_MANAGER']], 'ROLE_ADMIN'];
yield 'already granted, so there is no marker left' => [['ROLE_ADMIN'], 'ROLE_ADMIN'];
yield 'teamer has no nomination to approve' => [['ROLE_TEAMER'], 'ROLE_TEAMER'];
yield 'not a role at all' => [[User::PENDING_ROLES['ROLE_ADMIN']], 'ROLE_SUPER_ADMIN'];
}
public function testDisableForRevokedCrmRolesBlocksTheUserAndDropsThePendingMarkers(): void
{
$user = (new User())
+2 -1
View File
@@ -7,6 +7,7 @@ namespace App\Tests\Email;
use App\Config\EmailTextCatalog;
use App\Config\EmailTextKey;
use App\Email\EmailTextRenderer;
use App\Email\MailBodyRenderer;
use App\Email\Mailer;
use App\Repository\EmailTextRepository;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
@@ -42,7 +43,7 @@ class EmailTextMailRenderingTest extends KernelTestCase
$repository = $this->createMock(EmailTextRepository::class);
$repository->method('findByKey')->willReturn(null);
$text = (new EmailTextRenderer($catalog, $repository))
$text = (new EmailTextRenderer($catalog, $repository, $container->get(MailBodyRenderer::class)))
->render($key, $placeholders)
;
+55 -10
View File
@@ -7,6 +7,7 @@ namespace App\Tests\Email;
use App\Config\EmailTextCatalog;
use App\Config\EmailTextKey;
use App\Email\EmailTextRenderer;
use App\Email\MailBodyRenderer;
use App\Entity\EmailText;
use App\Repository\EmailTextRepository;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
@@ -41,7 +42,11 @@ class EmailTextRendererTest extends KernelTestCase
$this->assertStringContainsString('Skireise', $rendered->bodyHtml);
}
public function testMarkupTypedByAnAdminIsEscaped(): void
/**
* Admins write Markdown, so markup they type is dropped rather than shown back to them
* as entities - a mail full of &lt;script&gt; would be nobody's intention either.
*/
public function testMarkupTypedByAnAdminIsStripped(): void
{
$rendered = $this->render(
$this->emailText(body: 'Hallo <script>alert(1)</script>'),
@@ -49,7 +54,7 @@ class EmailTextRendererTest extends KernelTestCase
);
$this->assertStringNotContainsString('<script>', $rendered->bodyHtml);
$this->assertStringContainsString('&lt;script&gt;', $rendered->bodyHtml);
$this->assertStringNotContainsString('&lt;script&gt;', $rendered->bodyHtml);
}
/**
@@ -66,16 +71,53 @@ class EmailTextRendererTest extends KernelTestCase
$this->assertStringContainsString('&lt;img', $rendered->bodyHtml);
}
public function testAsterisksMakeTextBold(): void
public function testDoubleAsterisksMakeTextBold(): void
{
$rendered = $this->render(
$this->emailText(body: 'Das ist *wichtig* und das nicht'),
$this->emailText(body: 'Das ist **wichtig** und das nicht'),
['destination' => 'Skireise']
);
$this->assertSame('<p>Das ist <strong>wichtig</strong> und das nicht</p>', $rendered->bodyHtml);
}
public function testSingleAsterisksMakeTextItalic(): void
{
$rendered = $this->render(
$this->emailText(body: 'Das ist *anders* gemeint'),
['destination' => 'Skireise']
);
$this->assertSame('<p>Das ist <em>anders</em> gemeint</p>', $rendered->bodyHtml);
}
public function testDashesAndNumbersBecomeLists(): void
{
$rendered = $this->render(
$this->emailText(body: "- Ausweis\n- Bankverbindung"),
['destination' => 'Skireise']
);
$this->assertSame(
"<ul>\n<li>Ausweis</li>\n<li>Bankverbindung</li>\n</ul>",
$rendered->bodyHtml
);
}
/**
* The mail sets its own h1 above the body and styles nothing below h3, so an admin's
* heading is folded into what is left.
*/
public function testHeadingsAreFoldedIntoTheLevelsTheMailStyles(): void
{
$rendered = $this->render(
$this->emailText(body: "# Ganz gross\n\n#### Ganz klein"),
['destination' => 'Skireise']
);
$this->assertSame("<h2>Ganz gross</h2>\n<h3>Ganz klein</h3>", $rendered->bodyHtml);
}
public function testAnEscapedAsteriskStaysLiteral(): void
{
$rendered = $this->render(
@@ -94,11 +136,11 @@ class EmailTextRendererTest extends KernelTestCase
{
$rendered = $this->render(
$this->emailText(body: 'Einsatz {destination}'),
['destination' => '*nicht fett*']
['destination' => '**nicht fett**']
);
$this->assertStringNotContainsString('<strong>', $rendered->bodyHtml);
$this->assertStringContainsString('*nicht fett*', $rendered->bodyHtml);
$this->assertStringContainsString('**nicht fett**', $rendered->bodyHtml);
}
public function testAnEmptyPlaceholderFallsBackToADash(): void
@@ -196,14 +238,15 @@ class EmailTextRendererTest extends KernelTestCase
$renderer = new EmailTextRenderer(
self::getContainer()->get(EmailTextCatalog::class),
$repository
$repository,
self::getContainer()->get(MailBodyRenderer::class)
);
$rendered = $renderer->renderValues(
EmailTextKey::APPLICATION_REJECTED,
'Entwurf {destination}',
'Überschrift',
'Entwurfstext *fett*',
'Entwurfstext **fett**',
['destination' => 'Skireise']
);
@@ -221,7 +264,8 @@ class EmailTextRendererTest extends KernelTestCase
$renderer = new EmailTextRenderer(
self::getContainer()->get(EmailTextCatalog::class),
$this->createMock(EmailTextRepository::class)
$this->createMock(EmailTextRepository::class),
self::getContainer()->get(MailBodyRenderer::class)
);
$rendered = $renderer->renderValues(
@@ -252,7 +296,8 @@ class EmailTextRendererTest extends KernelTestCase
$renderer = new EmailTextRenderer(
self::getContainer()->get(EmailTextCatalog::class),
$repository
$repository,
self::getContainer()->get(MailBodyRenderer::class)
);
return $renderer->render(EmailTextKey::APPLICATION_REJECTED, $placeholders);
+174
View File
@@ -0,0 +1,174 @@
<?php
declare(strict_types=1);
namespace App\Tests\Email;
use App\Email\MailBodyRenderer;
use PHPUnit\Framework\TestCase;
/**
* The renderer is the only thing standing between what an admin typed and the HTML of a
* mail, and between what a teamer typed and that same HTML. Most of what is asserted here
* is where that line runs: admin text may become markup, a substituted value may not.
*/
class MailBodyRendererTest extends TestCase
{
private MailBodyRenderer $renderer;
protected function setUp(): void
{
$this->renderer = new MailBodyRenderer();
}
public function testDoubleAsterisksMakeTextBoldAndSingleOnesItalic(): void
{
$this->assertSame(
'<p><strong>fett</strong> und <em>kursiv</em></p>',
$this->renderer->render('**fett** und *kursiv*', [])
);
}
public function testDashesBecomeABulletList(): void
{
$this->assertSame(
"<ul>\n<li>Ausweis</li>\n<li>Bankverbindung</li>\n</ul>",
$this->renderer->render("- Ausweis\n- Bankverbindung", [])
);
}
public function testNumbersBecomeANumberedList(): void
{
$this->assertSame(
"<ol>\n<li>Erstens</li>\n<li>Zweitens</li>\n</ol>",
$this->renderer->render("1. Erstens\n2. Zweitens", [])
);
}
/**
* The mail layout sets its own h1 above the body and styles nothing below h3, so every
* heading is folded into that range rather than producing a tag nobody styled.
*/
public function testHeadingsAreFoldedIntoTheLevelsTheMailStyles(): void
{
$this->assertSame(
"<h2>Gross</h2>\n<h2>Mittel</h2>\n<h3>Klein</h3>\n<h3>Winzig</h3>",
$this->renderer->render("# Gross\n\n## Mittel\n\n### Klein\n\n###### Winzig", [])
);
}
public function testBlankLinesBecomeParagraphsAndSingleBreaksStay(): void
{
$this->assertSame(
"<p>Erste Zeile<br />\nZweite Zeile</p>\n<p>Neuer Absatz</p>",
$this->renderer->render("Erste Zeile\nZweite Zeile\n\nNeuer Absatz", [])
);
}
public function testBareUrlsAndMailAddressesBecomeLinks(): void
{
$html = $this->renderer->render('Schreib an [email protected] oder https://ep-reisen.de/team.', []);
$this->assertStringContainsString('<a href="mailto:[email protected]">[email protected]</a>', $html);
// The full stop ends the sentence, it is not part of the address.
$this->assertStringContainsString('<a href="https://ep-reisen.de/team">https://ep-reisen.de/team</a>.', $html);
}
public function testAnEscapedAsteriskStaysLiteral(): void
{
$this->assertSame('<p>Ein Sternchen: *</p>', $this->renderer->render('Ein Sternchen: \*', []));
}
/**
* Admins write Markdown, so markup they type is dropped rather than passed through.
*/
public function testMarkupTypedByAnAdminIsStripped(): void
{
$html = $this->renderer->render('Hallo <b>alle</b> <script>alert(1)</script>', []);
$this->assertStringNotContainsString('<b>', $html);
$this->assertStringNotContainsString('<script', $html);
}
/**
* An image in a mailing would be loaded from an address nobody reviewed, so only the
* alt text survives.
*/
public function testAnImageIsReducedToItsAltText(): void
{
$html = $this->renderer->render('![Ein Bild](https://example.org/pixel.png)', []);
$this->assertStringNotContainsString('<img', $html);
$this->assertStringContainsString('Ein Bild', $html);
}
public function testAnUnsafeLinkLosesItsTarget(): void
{
$html = $this->renderer->render('[klick](javascript:alert(1))', []);
$this->assertStringNotContainsString('javascript:', $html);
$this->assertStringContainsString('klick', $html);
}
public function testPlaceholdersAreSubstituted(): void
{
$this->assertSame(
'<p>Hallo Anna, dein Einsatz Skireise</p>',
$this->renderer->render(
'Hallo {{vorname}}, dein Einsatz {destination}',
['{{vorname}}' => 'Anna', '{destination}' => 'Skireise']
)
);
}
/**
* The load-bearing case. A teamer's own words go in after the parser has run, so
* nothing in them can become a tag, a heading, a list or emphasis - whatever they
* happen to contain.
*/
public function testNothingInAPlaceholderValueBecomesMarkup(): void
{
$html = $this->renderer->render('Kommentar: {kommentar}', [
'{kommentar}' => "**nicht fett**\n- keine Liste\n# keine Überschrift <b>x</b>",
]);
$this->assertStringNotContainsString('<strong>', $html);
$this->assertStringNotContainsString('<ul>', $html);
$this->assertStringNotContainsString('<h1', $html);
$this->assertStringNotContainsString('<h2', $html);
$this->assertStringNotContainsString('<b>', $html);
$this->assertStringContainsString('**nicht fett**', $html);
$this->assertStringContainsString('- keine Liste', $html);
$this->assertStringContainsString('&lt;b&gt;x&lt;/b&gt;', $html);
}
/**
* A rejection comment arrives as one multi-line value inside a single paragraph.
*/
public function testLineBreaksInsideAPlaceholderValueSurvive(): void
{
$this->assertSame(
"<p>Erste Zeile<br />\nZweite Zeile</p>",
$this->renderer->render('{kommentar}', ['{kommentar}' => "Erste Zeile\nZweite Zeile"])
);
}
/**
* Documented rather than desired: substitution runs over the finished HTML, so a token
* an admin put in backticks is replaced like any other. Harmless, but surprising enough
* to pin down.
*/
public function testATokenInACodeSpanIsStillSubstituted(): void
{
$this->assertSame(
'<p><code>Skireise</code></p>',
$this->renderer->render('`{destination}`', ['{destination}' => 'Skireise'])
);
}
public function testAnEmptyBodyRendersAsNothing(): void
{
$this->assertSame('', $this->renderer->render('', []));
$this->assertSame('', $this->renderer->render(null, []));
}
}
+21
View File
@@ -165,4 +165,25 @@ class UserTest extends TestCase
->validate($user)
;
}
public function testNominatedRolesAreKeyedByTheRoleAndNotByItsMarker(): void
{
$user = (new User())->setRoles([
'ROLE_TEAMER',
User::PENDING_ROLES['ROLE_ADMIN'],
User::PENDING_ROLES['ROLE_HOUSE_MANAGER'],
]);
$this->assertSame(
['ROLE_ADMIN' => 'Admin', 'ROLE_HOUSE_MANAGER' => 'Hausleitung'],
$user->getNominatedRoles(),
);
}
public function testAGrantedRoleIsNotNominated(): void
{
$user = (new User())->setRoles(['ROLE_ADMIN']);
$this->assertSame([], $user->getNominatedRoles());
}
}
+59 -53
View File
@@ -11,88 +11,98 @@ use Symfony\Component\Form\FormFactoryInterface;
class UserTypeTest extends KernelTestCase
{
public function testRendersRolesWithoutSynthesizedRoles(): void
/**
* The form is the account settings and nothing else. Roles and hotel codes are synced
* from BusPro and editable nowhere, so they are not fields at all - a disabled field
* that cannot be submitted only reads as broken.
*/
public function testRolesAndHotelCodesAreNotFields(): void
{
$user = (new User())
->setRoles(['ROLE_ADMIN'])
->setHotelCodes(['DKS'])
;
$form = $this->createForm($user);
$this->assertFalse($form->has('roles'));
$this->assertFalse($form->has('hotelCodes'));
$this->assertFalse($form->has('approvedRoles'));
}
public function testNeitherRolesNorHotelCodesCanBeSubmitted(): void
{
$user = (new User())
->setRoles(['ROLE_TEAMER'])
->setHotelCodes(['SSL'])
;
$form = $this->createForm($user);
$form->submit([
'roles' => ['ROLE_ADMIN'],
'hotelCodes' => ['DKS'],
'disabled' => null,
]);
$this->assertSame(['ROLE_TEAMER'], $user->getAssignedRoles());
$this->assertSame(['SSL'], $user->getHotelCodes());
}
/**
* Super admin is an elevation of ROLE_ADMIN, so it is not on offer for anybody else -
* offering it would only ever produce the violation from User::validateSuperAdmin().
*/
public function testSuperAdminIsOnlyOfferedToAnAdmin(): void
{
$this->assertTrue($this->createForm((new User())->setRoles(['ROLE_ADMIN']))->has('superAdmin'));
$this->assertFalse($this->createForm((new User())->setRoles(['ROLE_MANAGER']))->has('superAdmin'));
$this->assertFalse($this->createForm((new User())->setRoles([User::PENDING_ROLES['ROLE_ADMIN']]))->has('superAdmin'));
}
/**
* The exception: a flag left over from before its role was revoked has to stay editable,
* or that account could not be saved at all while the violation stands.
*/
public function testSuperAdminStaysEditableWhenTheFlagOutlivedTheRole(): void
{
$user = (new User())
->setRoles(['ROLE_MANAGER'])
->setSuperAdmin(true)
;
$view = $this->createForm($user)->createView();
// ROLE_USER and ROLE_SUPER_ADMIN are synthesized by getRoles() and must not leak in
$this->assertSame(['ROLE_ADMIN'], $view->children['roles']->vars['data']);
}
public function testApprovingAPendingRoleClearsTheMarker(): void
{
$user = (new User())->setRoles([User::PENDING_ROLES['ROLE_ADMIN']]);
$form = $this->createForm($user);
// the marker is not an assignable choice and must not reach the field
$this->assertSame([], $form->createView()->children['roles']->vars['data']);
$this->assertTrue($form->has('superAdmin'));
$form->submit([
'roles' => ['ROLE_ADMIN'],
'superAdmin' => null,
'hotelCodes' => [],
'disabled' => null,
]);
$this->assertTrue($form->isValid());
$this->assertSame(['ROLE_ADMIN'], $user->getAssignedRoles());
$this->assertSame([], $user->getPendingRoles());
$this->assertFalse($user->isSuperAdmin());
}
public function testRendersHotelCodesNotCoveredByTheConfiguredMap(): void
public function testSuperAdminIsAppointed(): void
{
$user = (new User())->setHotelCodes(['XYZ']);
$view = $this->createForm($user)->createView();
$this->assertSame(['XYZ'], $view->children['hotelCodes']->vars['data']);
}
public function testSubmitStoresAssignedRolesOnly(): void
{
$user = (new User())->setRoles(['ROLE_TEAMER']);
$user = (new User())->setRoles(['ROLE_ADMIN']);
$form = $this->createForm($user);
$form->submit([
'roles' => ['ROLE_ADMIN'],
'superAdmin' => '1',
'hotelCodes' => [],
'disabled' => null,
]);
$this->assertTrue($form->isValid());
$this->assertSame(['ROLE_ADMIN'], $user->getAssignedRoles());
$this->assertTrue($user->isSuperAdmin());
}
public function testSubmitRejectsSuperAdminWithoutRoleAdmin(): void
{
$user = new User();
$form = $this->createForm($user);
$form->submit([
'roles' => ['ROLE_MANAGER'],
'superAdmin' => '1',
'hotelCodes' => [],
]);
$this->assertFalse($form->isValid());
$this->assertCount(1, $form->get('superAdmin')->getErrors());
}
public function testSubmitBlocksTheAccountWithAReason(): void
{
$user = (new User())->setRoles(['ROLE_ADMIN']);
$form = $this->createForm($user);
$form->submit([
'roles' => ['ROLE_ADMIN'],
'superAdmin' => null,
'hotelCodes' => [],
'disabled' => '1',
'disabledReason' => 'Wegen Fehlverhaltens gesperrt.',
'disabledReasonInternal' => 'Siehe Vorgang 4711.',
@@ -115,9 +125,7 @@ class UserTypeTest extends KernelTestCase
$form = $this->createForm($user);
$form->submit([
'roles' => ['ROLE_ADMIN'],
'superAdmin' => null,
'hotelCodes' => [],
'disabled' => null,
'disabledReason' => null,
'disabledReasonInternal' => null,
@@ -143,9 +151,7 @@ class UserTypeTest extends KernelTestCase
// the textareas are prefilled, so unchecking the box alone submits the old reasons
$form->submit([
'roles' => ['ROLE_ADMIN'],
'superAdmin' => null,
'hotelCodes' => [],
'disabled' => null,
'disabledReason' => 'Für deinen Account liegt in BusPro keine Berechtigung mehr vor.',
'disabledReasonInternal' => 'Automatisch gesperrt: keine Rollen in BusPro.',
+84
View File
@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace App\Tests\Migrations;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Yaml\Yaml;
/**
* Version20260820000000 rewrites the wording of mails that go out to every teamer, and it
* runs exactly once with nobody watching, so the patterns it does that with are pinned
* here. The migration is not autoloaded (only src/ and tests/ are), hence the require.
*/
class EmphasisRewriteTest extends TestCase
{
private string $single;
private string $double;
protected function setUp(): void
{
require_once __DIR__.'/../../migrations/Version20260820000000.php';
$reflection = new \ReflectionClass(\DoctrineMigrations\Version20260820000000::class);
$this->single = $reflection->getConstant('SINGLE_EMPHASIS');
$this->double = $reflection->getConstant('DOUBLE_EMPHASIS');
}
/**
* @dataProvider upCases
*/
public function testTheUpwardRewrite(string $before, string $after): void
{
$this->assertSame($after, preg_replace($this->single, '**$1**', $before));
}
/**
* @return iterable<string, array{string, string}>
*/
public static function upCases(): iterable
{
yield 'one word' => ['Das ist *wichtig*', 'Das ist **wichtig**'];
yield 'several words' => ['*Dein Einsatz wurde angenommen!*', '**Dein Einsatz wurde angenommen!**'];
yield 'around a placeholder' => ['*{destination}*', '**{destination}**'];
yield 'already bold' => ['Das ist **wichtig**', 'Das ist **wichtig**'];
yield 'escaped asterisk' => ['Ein Sternchen: \*', 'Ein Sternchen: \*'];
// Whitespace next to a marker means it is not emphasis - CommonMark's own rule, and
// the reason arithmetic and stray asterisks come through untouched.
yield 'multiplication' => ['5 * 3 = 15', '5 * 3 = 15'];
yield 'spaced asterisks' => ['a * b * c', 'a * b * c'];
yield 'bullet at line start' => ["* Ausweis\n* Bankverbindung", "* Ausweis\n* Bankverbindung"];
yield 'not across lines' => ["*offen\ngeblieben*", "*offen\ngeblieben*"];
}
public function testTheRewriteIsReversible(): void
{
$before = 'Das ist *wichtig* und *{destination}* auch';
$up = preg_replace($this->single, '**$1**', $before);
$this->assertSame($before, preg_replace($this->double, '*$1*', $up));
}
/**
* The delivered defaults were rewritten by hand in the same commit, so nothing should
* be left in them for the migration to find. Read through the parser rather than off
* the raw file: the header comment documents *kursiv* on purpose.
*/
public function testTheDeliveredDefaultsAreAlreadyMigrated(): void
{
$texts = Yaml::parseFile(__DIR__.'/../../config/email_texts.yaml')['texts'];
foreach ($texts as $key => $text) {
$body = (string) ($text['body'] ?? '');
$this->assertSame(
$body,
preg_replace($this->single, '**$1**', $body),
sprintf('Default wording of "%s" still carries single-asterisk emphasis', $key)
);
}
}
}
+17 -7
View File
@@ -38,7 +38,7 @@ class BpnAuthenticatorTest extends TestCase
{
$this->stubApiClient($this->createCrmAttributes());
$this->userDataHandler->method('collectRoles')->willReturn([]);
$this->userDataHandler->method('collectClaimedRoles')->willReturn([]);
$this->userDataHandler->method('findLocalUser')->willReturn(null);
$this->userDataHandler->expects($this->never())->method('createLocalUser');
@@ -55,7 +55,7 @@ class BpnAuthenticatorTest extends TestCase
$this->stubApiClient($this->createCrmAttributes());
$this->userDataHandler->method('collectRoles')->willReturn([]);
$this->userDataHandler->method('collectClaimedRoles')->willReturn([]);
$this->userDataHandler->method('findLocalUser')->willReturn($user);
$this->userDataHandler->expects($this->never())->method('updateLocalUser');
@@ -69,6 +69,11 @@ class BpnAuthenticatorTest extends TestCase
$this->assertSame($user, $this->loadUser());
}
/**
* This guard is what stands between a degraded response and a mass revocation: with the
* roles led by the CRM, a login that reached updateLocalUser() on an empty payload would
* strip every role of every user logging in, one at a time.
*/
public function testResponseWithoutAttributeGroupsRefusesTheLoginWithoutBlocking(): void
{
$user = (new User())->setRoles(['ROLE_ADMIN']);
@@ -76,14 +81,19 @@ class BpnAuthenticatorTest extends TestCase
// an empty payload carries no roles either and must not read as a revocation
$this->stubApiClient(new CrmAttributesResponse());
$this->userDataHandler->method('collectRoles')->willReturn([]);
$this->userDataHandler->method('collectClaimedRoles')->willReturn([]);
$this->userDataHandler->method('findLocalUser')->willReturn($user);
$this->userDataHandler->expects($this->never())->method('disableForRevokedCrmRoles');
$this->userDataHandler->expects($this->never())->method('updateLocalUser');
$this->expectException(UserNotFoundException::class);
try {
$this->loadUser();
$this->fail('Expected the login to be refused');
} catch (UserNotFoundException) {
}
$this->loadUser();
$this->assertSame(['ROLE_ADMIN'], $user->getAssignedRoles());
}
/**
@@ -97,7 +107,7 @@ class BpnAuthenticatorTest extends TestCase
$this->stubApiClient($this->createCrmAttributes());
$this->userDataHandler->method('collectRoles')->willReturn(['ROLE_TEAMER']);
$this->userDataHandler->method('collectClaimedRoles')->willReturn(['ROLE_TEAMER']);
$this->userDataHandler->method('findLocalUser')->willReturn($user);
$this->userDataHandler->expects($this->never())->method('updateLocalUser');
@@ -115,7 +125,7 @@ class BpnAuthenticatorTest extends TestCase
$this->stubApiClient($this->createCrmAttributes());
$this->userDataHandler->method('collectRoles')->willReturn([]);
$this->userDataHandler->method('collectClaimedRoles')->willReturn([]);
$this->userDataHandler->method('findLocalUser')->willReturn($user);
$this->userDataHandler->expects($this->never())->method('disableForRevokedCrmRoles');
+30 -3
View File
@@ -110,9 +110,10 @@ class MyEpAuthenticatorTest extends TestCase
}
/**
* A super admin's manual demotion has to survive the user's next SSO login.
* A claimed administrative role is marked for approval, never granted - not even when
* the identity provider reports it outright.
*/
public function testExistingGrantedRolesAreNeverOverwritten(): void
public function testClaimedAdministrativeRolesAreNeverGrantedOnLogin(): void
{
$user = (new User())->setEmail('[email protected]')->setRoles(['ROLE_TEAMER']);
$this->repository->method('findOneBy')->willReturn($user);
@@ -130,7 +131,7 @@ class MyEpAuthenticatorTest extends TestCase
/**
* An already approved role must not be demoted back to a marker on the next login.
*/
public function testAnAlreadyGrantedAdministrativeRoleIsKept(): void
public function testAnAlreadyGrantedAdministrativeRoleIsKeptWhileStillClaimed(): void
{
$user = (new User())->setEmail('[email protected]')->setRoles(['ROLE_ADMIN', 'ROLE_TEAMER']);
$this->repository->method('findOneBy')->willReturn($user);
@@ -141,6 +142,32 @@ class MyEpAuthenticatorTest extends TestCase
$this->assertSame([], $user->getPendingRoles());
}
/**
* MyE&P leads exactly as BusPro does: a role it stops reporting is withdrawn on the
* next login, and the hotel codes are re-imported with it.
*/
public function testGrantedRolesNoLongerClaimedAreRevoked(): void
{
$user = (new User())
->setEmail('[email protected]')
->setRoles(['ROLE_ADMIN', 'ROLE_TEAMER'])
->setSuperAdmin(true)
->setHotelCodes(['SSL'])
;
$this->repository->method('findOneBy')->willReturn($user);
$this->loadUser($this->createUserinfo(['ROLE_TEAMER']));
$this->assertSame(['ROLE_TEAMER'], $user->getAssignedRoles());
$this->assertSame([], $user->getPendingRoles());
// the flag would otherwise outlive the role it depends on
$this->assertFalse($user->isSuperAdmin());
$this->assertNotContains('ROLE_SUPER_ADMIN', $user->getRoles());
$this->assertSame(['HOTEL'], $user->getHotelCodes());
}
public function testTeamerRoleIsGrantedToAnExistingUser(): void
{
$user = (new User())->setEmail('[email protected]')->setRoles([User::PENDING_ROLES['ROLE_MANAGER']]);
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Tests\Service\Teamer;
use App\Email\MailBodyRenderer;
use App\Email\Mailer;
use App\Entity\Teamer;
use App\Entity\User;
@@ -30,9 +31,12 @@ class TeamerMailingServiceTest extends TestCase
$this->teamerRepository = $this->createMock(TeamerRepository::class);
$this->mailer = $this->createMock(Mailer::class);
// The real renderer, not a mock: what the mailing puts in front of a teamer is
// Markdown turned into HTML, and getting that wrong is the whole risk here.
$this->service = new TeamerMailingService(
$this->teamerRepository,
$this->mailer,
new MailBodyRenderer(),
$this->createMock(LoggerInterface::class),
'mailing',
);
@@ -111,7 +115,7 @@ class TeamerMailingServiceTest extends TestCase
->expects($this->exactly(2))
->method('createAndSendEmail')
->willReturnCallback(function (array $context, array $options) use (&$sent): void {
$sent[] = [$options['to'], $options['subject'], $context['message']];
$sent[] = [$options['to'], $options['subject'], $context['bodyHtml']];
})
;
@@ -123,8 +127,8 @@ class TeamerMailingServiceTest extends TestCase
));
$this->assertSame([
['[email protected]', 'Hallo Anna', 'Servus Anna Berg'],
['[email protected]', 'Hallo Bea', 'Servus Bea Ohm'],
['[email protected]', 'Hallo Anna', '<p>Servus Anna Berg</p>'],
['[email protected]', 'Hallo Bea', '<p>Servus Bea Ohm</p>'],
], $sent);
}
@@ -210,7 +214,7 @@ class TeamerMailingServiceTest extends TestCase
->expects($this->once())
->method('createAndSendEmail')
->with(
['message' => 'Servus Rita Kern'],
['bodyHtml' => '<p>Servus Rita Kern</p>'],
$this->callback(function (array $options): bool {
$this->assertSame('[email protected]', $options['to']);
$this->assertSame('[Vorschau] Hallo Rita', $options['subject']);