Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5141673bcd | ||
|
|
b530679658 | ||
|
|
d5f4b12f0a | ||
|
|
aa728ddc99 | ||
|
|
19364df2db | ||
|
|
cb2d64f2cd | ||
|
|
f073a2014d | ||
|
|
30ad5e8488 |
No files matched your search
@@ -1,4 +1,3 @@
|
||||
name: myep-team
|
||||
type: php
|
||||
docroot: public
|
||||
php_version: "8.4"
|
||||
|
||||
@@ -47,12 +47,12 @@ MAILER_DSN=null://null
|
||||
MAILING_MAILER_DSN=null://null
|
||||
###< symfony/mailer ###
|
||||
|
||||
APP_BASE_URI=https://myep-team.ddev.site
|
||||
APP_BASE_URI=https://epteam.ddev.site
|
||||
|
||||
# Regex matched against the Host header; requests for any other host are refused. The
|
||||
# OAuth2 redirect_uri is generated from the request, so this is what pins it. Production
|
||||
# sets its own value outside the repository, like APP_BASE_URI above.
|
||||
APP_TRUSTED_HOSTS=^myep-team\.ddev\.site$
|
||||
APP_TRUSTED_HOSTS=^epteam\.ddev\.site$
|
||||
|
||||
APP_BPN_USER=
|
||||
APP_BPN_PASSWORD=
|
||||
@@ -82,6 +82,12 @@ MYEP_OAUTH2_URL_AUTHORIZE=https://my.ep-reisen.de/authorize
|
||||
MYEP_OAUTH2_URL_ACCESS_TOKEN=https://my.ep-reisen.de/token
|
||||
MYEP_OAUTH2_URL_RESOURCE_OWNER_DETAILS=https://my.ep-reisen.de/api/userinfo
|
||||
MYEP_OAUTH2_SCOPES=email,id,roles,profile
|
||||
# Shared key the sibling websites send in the X-Api-Key header. Empty here: set it per stage.
|
||||
APPLICATION_FORM_API_KEY=
|
||||
# Booking link for the Team-Infocall, substituted for {bookingUrl} in the application form
|
||||
# receipt mail. Empty here: set it per stage. While it is empty that mail is not sent at all -
|
||||
# an invitation with a dead booking link is worse than none.
|
||||
APPLICATION_FORM_BOOKING_URL=
|
||||
|
||||
###> symfony/mailjet-mailer ###
|
||||
# Bulk teamer mailings only, everything else goes out over MAILER_DSN. Set the real
|
||||
|
||||
@@ -6,3 +6,9 @@ PANTHER_APP_ENV=panther
|
||||
PANTHER_ERROR_SCREENSHOT_DIR=./var/error-screenshots
|
||||
# the test client requests http://localhost/
|
||||
APP_TRUSTED_HOSTS='^localhost$'
|
||||
# The api firewall rejects every request while no key is configured, and .env.local is not
|
||||
# loaded in the test environment - so the throwaway key the tests send belongs here.
|
||||
# Keep it in sync with ApplicationFormControllerTest::KEY.
|
||||
APPLICATION_FORM_API_KEY=test-application-form-api-key
|
||||
# The receipt mail refuses to render without it, and several tests send that mail.
|
||||
APPLICATION_FORM_BOOKING_URL=https://bookings.example.com/team-infocall
|
||||
@@ -0,0 +1,57 @@
|
||||
### Full submission, as the TYPO3 ApplicationApiFinisher sends it.
|
||||
### The key is APPLICATION_FORM_API_KEY of the stage being called; keep the real values in
|
||||
### http-client.private.env.json, which is not in the repository.
|
||||
POST https://myep-team.ddev.site/api/application-forms
|
||||
Content-Type: application/json
|
||||
X-Api-Key: {{applicationFormApiKey}}
|
||||
|
||||
{
|
||||
"form": "applicationform",
|
||||
"formLabel": "Bewerbungsformular",
|
||||
"submittedAt": "2026-09-22T12:30:00+02:00",
|
||||
"pageUid": 1421,
|
||||
"pageUrl": "https://www.ep-reisen.de/jobs/bewerbung",
|
||||
"firstName": "Anna",
|
||||
"lastName": "Muster",
|
||||
"email": "[email protected]",
|
||||
"phone": "+49 30 1234567",
|
||||
"mobile": "+49 170 1234567",
|
||||
"birthDate": "01.01.1990",
|
||||
"street": "Musterstraße 1",
|
||||
"zipCode": "10115",
|
||||
"city": "Berlin",
|
||||
"details": {
|
||||
"Nationalität": "deutsch",
|
||||
"Führerschein": "ja",
|
||||
"Ausbildung/Studium": "Tourismusmanagement",
|
||||
"Bewerbung als": ["Reiseleitung", "Skilehrer"],
|
||||
"Ich fahre": ["Ski", "Snowboard"],
|
||||
"Wie gut fahre ich Ski": "fortgeschritten",
|
||||
"Skifahrer seit": "2004",
|
||||
"Einsatz datum": "ab 20.12.2026"
|
||||
}
|
||||
}
|
||||
|
||||
### A form that maps nothing but the basics - valid, everything else is absent, not empty.
|
||||
POST https://myep-team.ddev.site/api/application-forms
|
||||
Content-Type: application/json
|
||||
X-Api-Key: {{applicationFormApiKey}}
|
||||
|
||||
{
|
||||
"form": "contactform",
|
||||
"formLabel": "Kontaktformular",
|
||||
"submittedAt": "2026-09-22T12:30:00+02:00",
|
||||
"details": {}
|
||||
}
|
||||
|
||||
### Wrong key: 401, and the submission is dropped on the TYPO3 side without a retry.
|
||||
POST https://myep-team.ddev.site/api/application-forms
|
||||
Content-Type: application/json
|
||||
X-Api-Key: definitely-not-the-key
|
||||
|
||||
{
|
||||
"form": "applicationform",
|
||||
"formLabel": "Bewerbungsformular",
|
||||
"submittedAt": "2026-09-22T12:30:00+02:00",
|
||||
"details": {}
|
||||
}
|
||||
@@ -51,6 +51,74 @@ texts:
|
||||
|
||||
Bitte wende dich bei Rückfragen an [email protected].
|
||||
|
||||
application_form_received:
|
||||
label: 'Eingegangenes Formular - Eingangsbestätigung'
|
||||
# Only bookingUrl, which is not caller-supplied like the others: it comes from
|
||||
# APPLICATION_FORM_BOOKING_URL and is substituted into the Markdown before it is parsed,
|
||||
# which is what lets it be a link target (see App\Email\EmailTextRenderer). The mailer
|
||||
# also passes firstName, lastName and formLabel, so an admin who adds one of those tokens
|
||||
# by hand still gets it substituted - they are just not advertised, because the wording
|
||||
# greets from Köln rather than by name and EmailTextCatalogTest insists every declared
|
||||
# placeholder appears in the default text.
|
||||
placeholders: ['bookingUrl', 'season']
|
||||
subject: 'Einladung zum Team-Infocall'
|
||||
headline: 'Hallo aus Köln,'
|
||||
body: |-
|
||||
vielen Dank für deine Bewerbung für die kommende Wintersaison {season}!
|
||||
|
||||
Die Teamplanung der Wintersaison läuft wieder an und um herauszufinden, wie du zu E&P Reisen passt, laden wir dich hiermit zum Team-Infocall ein.
|
||||
|
||||
Beim Team-Infocall erhältst du allgemeine Infos über E&P Reisen, welche Reisekonzepte und Destinationen wir anbieten und welche Jobs es dort gibt. Natürlich hast du auch die Gelegenheit offene Fragen zu stellen.
|
||||
|
||||
Der Termin wird ca. eine Stunde in Anspruch nehmen und mit mehreren Teilnehmenden als Videocall über Teams stattfinden. Nach der Buchung des Termins erhältst du alle Infos, um an dem Call teilzunehmen, das geht auch als Gast über einen Webbrowser.
|
||||
|
||||
Bitte buche dir einen passenden Termin unter [diesem Buchungslink]({bookingUrl}). Bis zu Beginn der Saison werden noch weitere Termine für eine Teilnahme online gestellt.
|
||||
|
||||
Folge uns doch gerne schon auf Instagram unter team_ep_reisen für kurzfristige Einsätze, relevante News und coolen Ski- und Boardcontent.
|
||||
|
||||
Vielleicht hast du auch Lust im Sommer schon für uns zu arbeiten? Schreibe uns gerne in einer separaten Mail 🙂
|
||||
|
||||
Wir freuen uns darauf, dich kennenzulernen und hoffen, dich bald in unserem Team begrüßen zu können!
|
||||
|
||||
application_form_follow_up:
|
||||
label: 'Eingegangenes Formular - Nachfassen'
|
||||
# No placeholders, same as the receipt: the wording greets from Köln, not by name, and
|
||||
# EmailTextCatalogTest insists every declared placeholder appears in the default text.
|
||||
#
|
||||
# This wording goes stale by design - it names concrete call dates and a Bookings outage.
|
||||
# It is the fallback for a fresh database only: the moment somebody edits the mail under
|
||||
# /admin/system/email-text, that override wins and this block stops being sent. Maintain
|
||||
# it there, not here.
|
||||
placeholders: []
|
||||
subject: 'Termine für die Wochenteam-Calls'
|
||||
headline: 'Hallo aus Köln,'
|
||||
body: |-
|
||||
schön, dass du bei unserem Digitalen Infotreffen dabei warst! Ich hoffe wir konnten bereits einige deiner Fragen beantworten. Aufgrund der Fülle an Informationen habe ich ein kleines [Handout](https://PLATZHALTER-HANDOUT) zusammengestellt, damit du die wichtigsten Infos nochmal auf einen Blick hast.
|
||||
|
||||
Nun geht es für dich in die 2. Runde! Wir wollen dich besser kennenlernen.
|
||||
|
||||
## Wochenteam
|
||||
|
||||
Leider gibt es aktuell technische Probleme mit Bookings, sodass ihr momentan keine Termine für die Wochenteam-Calls einsehen oder buchen könnt. Deshalb organisieren wir die Anmeldung vorübergehend manuell. Hier findest du alle Termine für die Wochenteam-Calls. Wenn du an einem der Termine teilnehmen möchtest, antworte bitte einfach auf diese E-Mail und teile uns deinen Wunschtermin mit. Wir melden dich dann manuell an und senden dir rechtzeitig die Zugangsdaten für den entsprechenden Call zu. **Wichtig:** Sobald das Wochenteam-Seminar vollständig besetzt ist, werden keine weiteren Wochenteam-Calls mehr angeboten.
|
||||
|
||||
Folgende Termine sind möglich:
|
||||
|
||||
- Mi 30.9 14:30-15:15Uhr
|
||||
- Fr 9.10 9:30-10:15Uhr
|
||||
- Fr 16.10 14:30-15:15Uhr
|
||||
- Mi 21.10 14:30-15:15Uhr
|
||||
- Fr 30.10 11-11:45Uhr
|
||||
|
||||
## Saisonpersonal
|
||||
|
||||
Interessierst du dich dafür als Saisonmitarbeiter\*in (die ganze Saison) in den Bergen mitzuarbeiten? Wir haben unser Saisonpersonal für diesen Winter bereits vollständig besetzt. Bei Interesse kannst du uns gerne eine E-Mail mit deinem Interesse und dem gewünschten Zeitraum schicken – falls es durch kurzfristige Änderungen, wie z. B. Verletzungen, zu einer Ausnahme kommt, würden wir darauf zurückkommen. Um dir sicherer noch in diesem Winter einen Platz in unserem Team und in den Bergen zu ermöglichen, empfehlen wir dir, Teil unseres Wochenteams zu werden.
|
||||
|
||||
Wenn du in der Zwischenzeit eine Frage hast, dann kannst du dich gerne per E-Mail oder telefonisch melden! Wir freuen uns darauf, dich besser kennenzulernen. 😊
|
||||
|
||||
Schöne Grüße aus Köln
|
||||
|
||||
Eure Personalabteilung
|
||||
|
||||
application_rejected:
|
||||
label: 'Bewerbung abgelehnt'
|
||||
placeholders: ['destination']
|
||||
@@ -147,6 +215,11 @@ texts:
|
||||
# Descriptions shown next to the form fields. They describe the placeholder itself rather
|
||||
# than any one mail, so they are shared: a name means the same thing wherever it appears.
|
||||
placeholders:
|
||||
bookingUrl: 'Buchungslink für den Team-Infocall, kommt aus der Konfiguration (APPLICATION_FORM_BOOKING_URL)'
|
||||
season: 'Kommende Saison in Kurzform, z. B. "26/27" - wird automatisch eingesetzt'
|
||||
firstName: 'Vorname der Person, die das Formular abgeschickt hat'
|
||||
lastName: 'Nachname der Person, die das Formular abgeschickt hat'
|
||||
formLabel: 'Name des Formulars, z. B. "Bewerbungsformular"'
|
||||
destination: 'Einsatz, z. B. "12.01.25 - 19.01.25 Skireise"'
|
||||
specialAgreements: 'Zusätzliche Absprachen zum Einsatz'
|
||||
contractUploadDeadlineDays: 'Frist zum Hochladen des Honorarvertrags in Tagen'
|
||||
|
||||
@@ -3,6 +3,7 @@ monolog:
|
||||
- deprecation
|
||||
- bpn
|
||||
- audit
|
||||
- api
|
||||
|
||||
handlers:
|
||||
main:
|
||||
@@ -11,7 +12,7 @@ monolog:
|
||||
handler: exceptions
|
||||
excluded_http_codes: [404, 405]
|
||||
buffer_size: 50
|
||||
channels: ["!bpn", "!audit"]
|
||||
channels: ["!bpn", "!audit", "!api"]
|
||||
exceptions:
|
||||
type: rotating_file
|
||||
path: "%kernel.logs_dir%/framework.%kernel.environment%.log"
|
||||
@@ -29,6 +30,14 @@ monolog:
|
||||
path: '%kernel.logs_dir%/audit.%kernel.environment%.log'
|
||||
max_files: 5
|
||||
level: info
|
||||
# Form submissions posted by the sibling websites. Own file because it is machine
|
||||
# traffic nobody watches between incidents, and it must stay out of the audit table.
|
||||
api:
|
||||
channels: [ "api" ]
|
||||
type: rotating_file
|
||||
path: '%kernel.logs_dir%/api.%kernel.environment%.log'
|
||||
max_files: 30
|
||||
level: info
|
||||
database:
|
||||
channels: ["audit"]
|
||||
type: service
|
||||
@@ -36,7 +45,7 @@ monolog:
|
||||
console:
|
||||
type: console
|
||||
process_psr_3_messages: false
|
||||
channels: ["!event", "!bpn", "!doctrine", "!console"]
|
||||
channels: ["!event", "!bpn", "!api", "!doctrine", "!console"]
|
||||
|
||||
when@dev:
|
||||
monolog:
|
||||
@@ -73,7 +82,7 @@ when@prod:
|
||||
handler: exceptions
|
||||
excluded_http_codes: [404, 405]
|
||||
buffer_size: 50
|
||||
channels: ["!bpn", "!audit"]
|
||||
channels: ["!bpn", "!audit", "!api"]
|
||||
exceptions:
|
||||
type: rotating_file
|
||||
path: "%kernel.logs_dir%/framework.%kernel.environment%.log"
|
||||
@@ -91,6 +100,12 @@ when@prod:
|
||||
path: '%kernel.logs_dir%/audit.%kernel.environment%.log'
|
||||
max_files: 5
|
||||
level: info
|
||||
api:
|
||||
channels: [ "api" ]
|
||||
type: rotating_file
|
||||
path: '%kernel.logs_dir%/api.%kernel.environment%.log'
|
||||
max_files: 30
|
||||
level: info
|
||||
database:
|
||||
channels: ["audit"]
|
||||
type: service
|
||||
@@ -98,4 +113,4 @@ when@prod:
|
||||
console:
|
||||
type: console
|
||||
process_psr_3_messages: false
|
||||
channels: ["!event", "!doctrine", "!bpn", "!audit"]
|
||||
channels: ["!event", "!doctrine", "!bpn", "!audit", "!api"]
|
||||
@@ -7,6 +7,12 @@ security:
|
||||
entity:
|
||||
class: App\Entity\User
|
||||
property: email
|
||||
# The sibling websites post as this one; it exists in configuration only. An API caller
|
||||
# must never be a row in the user table, where it would be a login to the UI as well.
|
||||
api_user_provider:
|
||||
memory:
|
||||
users:
|
||||
api: { roles: [ ROLE_API ] }
|
||||
|
||||
role_hierarchy:
|
||||
ROLE_TEAM_ADMIN: [ ROLE_ADMINISTRATIVE ]
|
||||
@@ -16,6 +22,17 @@ security:
|
||||
dev:
|
||||
pattern: ^/(_(profiler|wdt)|css|images|js)/
|
||||
security: false
|
||||
# Stateless and key-authenticated: a machine posts here inside a visitor's form
|
||||
# submission on another site, so there is no session, no login form and no redirect.
|
||||
# Must stay above "main", whose pattern is ^/.
|
||||
api:
|
||||
pattern: ^/api
|
||||
stateless: true
|
||||
provider: api_user_provider
|
||||
access_token:
|
||||
token_handler: App\Security\AccessToken\ApiKeyTokenHandler
|
||||
token_extractors:
|
||||
- App\Security\AccessToken\ApiKeyExtractor
|
||||
main:
|
||||
lazy: true
|
||||
provider: bpn_user_provider
|
||||
@@ -29,6 +46,8 @@ security:
|
||||
path: app_security_logout
|
||||
target: app_security_login
|
||||
access_control:
|
||||
# The firewall authenticates, the controller requires ROLE_API
|
||||
- { path: '^/api', roles: PUBLIC_ACCESS, requires_channel: https }
|
||||
- { path: '^/_uploader', roles: ROLE_USER, requires_channel: https }
|
||||
- { path: '^/', roles: PUBLIC_ACCESS, requires_channel: https }
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Enabled for #[MapRequestPayload] on the api controllers - nothing else in this application
|
||||
# serializes. ALLOW_EXTRA_ATTRIBUTES stays at its default (true) on purpose: the TYPO3 form
|
||||
# payload grows keys without a release here, and rejecting an unknown one would turn every
|
||||
# later mapping change into a 400 (see .ddev/plans/application-form-endpoint.md).
|
||||
framework:
|
||||
serializer:
|
||||
name_converter: ~
|
||||
@@ -35,6 +35,16 @@ parameters:
|
||||
1461: 'SHM'
|
||||
1462: 'AGR'
|
||||
|
||||
# Shared key the sibling websites authenticate their form submissions with. Empty here on
|
||||
# purpose - the real value belongs in the environment of each stage, and an empty key
|
||||
# rejects every request instead of letting them through.
|
||||
application_form_api_key: '%env(string:APPLICATION_FORM_API_KEY)%'
|
||||
|
||||
# Booking link the application form receipt mail invites the applicant to. A deployment
|
||||
# value rather than part of the wording, so a new booking system does not need an edit in
|
||||
# every stage's mail text.
|
||||
application_form_booking_url: '%env(string:APPLICATION_FORM_BOOKING_URL)%'
|
||||
|
||||
default_email_from: '%env(APP_DEFAULT_EMAIL_FROM)%'
|
||||
default_email_to: '%env(APP_DEFAULT_EMAIL_TO)%'
|
||||
|
||||
@@ -159,6 +169,13 @@ services:
|
||||
bpn_api_port: '%env(APP_BPN_PORT)%'
|
||||
debug: '%env(bool:APP_BPN_DEBUG)%'
|
||||
|
||||
App\Service\Teamer\TeamerProvisioner:
|
||||
arguments:
|
||||
$logger: '@monolog.logger.bpn'
|
||||
# The same selection the login reads a teamer's role from - this is the one place that
|
||||
# writes it, so it must be the same id.
|
||||
$teamerSelectionId: '%bpn_crm_id_teamer%'
|
||||
|
||||
App\BusProNet\ResponseParser:
|
||||
arguments:
|
||||
$options:
|
||||
@@ -318,6 +335,22 @@ services:
|
||||
from: '%default_email_from%'
|
||||
to: '%default_email_to%'
|
||||
|
||||
# Its own log channel, not the audit one bound by default: the audit channel writes a row
|
||||
# to the log table through App\Logging\DatabaseHandler, which records what staff did here.
|
||||
App\Email\EmailTextRenderer:
|
||||
arguments:
|
||||
$bookingUrl: '%application_form_booking_url%'
|
||||
|
||||
App\Security\AccessToken\ApiKeyTokenHandler:
|
||||
arguments:
|
||||
$apiKey: '%application_form_api_key%'
|
||||
$logger: '@monolog.logger.api'
|
||||
|
||||
App\Controller\Api\ApplicationFormController:
|
||||
arguments:
|
||||
$logger: '@monolog.logger.api'
|
||||
tags: [ 'controller.service_arguments' ]
|
||||
|
||||
App\Security\OAuth2\MyEpClient:
|
||||
arguments:
|
||||
$options:
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* Form submissions posted by the sibling websites (TYPO3 ApplicationApiFinisher).
|
||||
*
|
||||
* Generated with doctrine:migrations:diff and reduced to these two statements: the diff also
|
||||
* swept in the long-standing dev drift in the datetime and json column declarations, plus
|
||||
* tables that only exist on another branch.
|
||||
*/
|
||||
final class Version20260923062331 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Add application_form_submission for form submissions posted by the websites';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql('CREATE TABLE application_form_submission (id INT AUTO_INCREMENT NOT NULL, uuid VARCHAR(36) NOT NULL, form VARCHAR(64) NOT NULL, form_label VARCHAR(255) NOT NULL, submitted_at DATETIME NOT NULL, page_uid INT DEFAULT NULL, page_url VARCHAR(2048) DEFAULT NULL, first_name VARCHAR(255) DEFAULT NULL, last_name VARCHAR(255) DEFAULT NULL, email VARCHAR(255) DEFAULT NULL, phone VARCHAR(64) DEFAULT NULL, mobile VARCHAR(64) DEFAULT NULL, birth_date VARCHAR(64) DEFAULT NULL, street VARCHAR(255) DEFAULT NULL, zip_code VARCHAR(32) DEFAULT NULL, city VARCHAR(255) DEFAULT NULL, details JSON NOT NULL, payload JSON NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME DEFAULT NULL, UNIQUE INDEX UNIQ_F47CE995D17F50A6 (uuid), INDEX IDX_F47CE995B5265E72 (form, submitted_at), PRIMARY KEY (id)) DEFAULT CHARACTER SET utf8mb4');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('DROP TABLE application_form_submission');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* The follow-up a reviewer works through on a received form submission: two mails and two calls.
|
||||
*
|
||||
* Hand-written rather than generated: doctrine:migrations:diff also sweeps in the long-standing
|
||||
* dev drift in the datetime and json column declarations and tables from other branches. These
|
||||
* are the only statements this change needs.
|
||||
*/
|
||||
final class Version20260924090000 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Add the follow-up mail and call dates to application_form_submission';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE application_form_submission ADD first_mail_sent_at DATETIME DEFAULT NULL, ADD second_mail_sent_at DATETIME DEFAULT NULL, ADD first_call_held_at DATE DEFAULT NULL, ADD second_call_held_at DATE DEFAULT NULL');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE application_form_submission DROP first_mail_sent_at, DROP second_mail_sent_at, DROP first_call_held_at, DROP second_call_held_at');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* The one payload field a rule depends on: whether the form reported an EU (incl. Switzerland)
|
||||
* nationality. Nullable with three meanings - true, false, and "this form does not ask" - because
|
||||
* only true earns the automatic receipt mail.
|
||||
*
|
||||
* Hand-written rather than generated, like the other two: doctrine:migrations:diff also sweeps in
|
||||
* the long-standing dev drift and tables from other branches.
|
||||
*/
|
||||
final class Version20260924120000 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Add the eu eligibility flag to application_form_submission';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE application_form_submission ADD eu TINYINT DEFAULT NULL');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE application_form_submission DROP eu');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* A slot marker on the document library, so a feature can look a file up by what it is for
|
||||
* instead of by id (App\Config\UploadToken). Unique: one document per slot.
|
||||
*
|
||||
* Reduced to these two statements by hand - the generated diff also wanted to drop another
|
||||
* branch's upload columns and restate the long-standing datetime drift on this table.
|
||||
*/
|
||||
final class Version20260924140000 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Add the token slot marker to upload';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE upload ADD token VARCHAR(64) DEFAULT NULL');
|
||||
$this->addSql('CREATE UNIQUE INDEX UNIQ_17BDE61F5F37A13B ON upload (token)');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('DROP INDEX UNIQ_17BDE61F5F37A13B ON upload');
|
||||
$this->addSql('ALTER TABLE upload DROP token');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* What it takes to provision a teamer from a received application: the applicant's gender, and the
|
||||
* outcome of each of the three provisioning writes
|
||||
* (.ddev/plans/application-form-teamer-provisioning.md).
|
||||
*
|
||||
* Emptying the table first is deliberate. gender is NOT NULL because BusPro refuses an address
|
||||
* without one and Teamer::$gender is not nullable either, and the existing rows predate the
|
||||
* tightened endpoint contract, so none of them carries a value. They are test submissions in dev -
|
||||
* the feature has never shipped, and nothing in production is affected. Doing it here rather than
|
||||
* by hand keeps it reviewable and keeps the migration replayable.
|
||||
*
|
||||
* Reduced to these statements by hand: the generated diff also wanted to restate the long-standing
|
||||
* datetime comment drift and another branch's tables.
|
||||
*/
|
||||
final class Version20260925120000 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Add gender and the provisioning state to application_form_submission';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql('DELETE FROM application_form_submission');
|
||||
$this->addSql('ALTER TABLE application_form_submission ADD gender VARCHAR(1) NOT NULL, ADD bus_pro_address_id INT DEFAULT NULL, ADD bus_pro_person_id INT DEFAULT NULL, ADD teamer_created_at DATETIME DEFAULT NULL, ADD user_id INT DEFAULT NULL');
|
||||
$this->addSql('ALTER TABLE application_form_submission ADD CONSTRAINT FK_F47CE995A76ED395 FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE SET NULL');
|
||||
$this->addSql('CREATE INDEX IDX_F47CE995A76ED395 ON application_form_submission (user_id)');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE application_form_submission DROP FOREIGN KEY FK_F47CE995A76ED395');
|
||||
$this->addSql('DROP INDEX IDX_F47CE995A76ED395 ON application_form_submission');
|
||||
$this->addSql('ALTER TABLE application_form_submission DROP gender, DROP bus_pro_address_id, DROP bus_pro_person_id, DROP teamer_created_at, DROP user_id');
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ use App\BusProNet\Model\CrmAttributesResponse;
|
||||
use App\BusProNet\Model\NotificationResponse;
|
||||
use App\BusProNet\Model\ProfileResponse;
|
||||
use App\BusProNet\Model\ProfileUpdateResponse;
|
||||
use App\BusProNet\Model\RegistrationResponse;
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use App\Entity\User;
|
||||
use League\Flysystem\FilesystemException;
|
||||
use League\Flysystem\FilesystemOperator;
|
||||
@@ -83,6 +85,86 @@ class ApiClient
|
||||
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the applicant's address in the CRM, which is what makes them a person BusPro knows.
|
||||
*
|
||||
* BusPro answers with the ids of an address it already held when it recognises the person
|
||||
* ("neuanlage" False), so this never produces a duplicate and needs no pre-flight lookup -
|
||||
* reading an address would require the customer's password, which provisioning deliberately
|
||||
* does not have.
|
||||
*
|
||||
* "ohnemailversand" suppresses BusPro's own mail about the new record: the applicant is asked
|
||||
* to set a password by resetPassword() at the end of provisioning instead, so that a failure
|
||||
* in between never mails somebody who has not been provisioned.
|
||||
*
|
||||
* @throws ApiClientException
|
||||
* @throws ResponseParserException
|
||||
*/
|
||||
public function createAddress(ApplicationFormSubmission $submission): NotificationResponse|RegistrationResponse
|
||||
{
|
||||
$data = [
|
||||
'anfrage' => [
|
||||
'user' => $this->config['bpn_username'],
|
||||
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_CUSTOMER_DATA),
|
||||
'satz' => ['@typ' => static::TYPE_CUSTOMER_DATA],
|
||||
'art' => 'Adresse_Neu',
|
||||
'adressdaten' => $submission->toPayload(),
|
||||
'ohnemailversand' => 'True',
|
||||
],
|
||||
];
|
||||
|
||||
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets or clears one CRM selection on a person - the one write to the CRM this application
|
||||
* makes. Everything else about selections is read-only here: roles and hotel codes are synced
|
||||
* from BusPro on every login and an admin may approve a claim, never grant one.
|
||||
*
|
||||
* "login" switches the password check off, which only works when the request identifies the
|
||||
* person by id: both ids are required, and the person id is "idadresseperson" on the way in
|
||||
* although the response calls it "idperson". The element order and the single-selection
|
||||
* payload are what BusPro was verified to accept - the art is undocumented, see
|
||||
* .ddev/plans/buspro-crm-selection-write.md before changing the shape.
|
||||
*
|
||||
* Idempotent: setting a selection that is already set answers änderung=True and changes
|
||||
* nothing, so a caller may write unconditionally and take isUpdated() as the success check.
|
||||
*
|
||||
* The write only goes through where the selection is marked changeable in the BusPro
|
||||
* settings, and that flag is per environment - 1070 is writable in production only.
|
||||
*
|
||||
* @throws ApiClientException
|
||||
* @throws ResponseParserException
|
||||
*/
|
||||
public function updateCrmAttribute(
|
||||
string $email,
|
||||
int $addressId,
|
||||
int $personId,
|
||||
int $selectionId,
|
||||
bool $selected,
|
||||
): NotificationResponse|ProfileUpdateResponse {
|
||||
$data = [
|
||||
'anfrage' => [
|
||||
'user' => $this->config['bpn_username'],
|
||||
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], static::TYPE_CUSTOMER_DATA),
|
||||
'satz' => ['@typ' => static::TYPE_CUSTOMER_DATA],
|
||||
'art' => 'SelektionCRM_Ändern',
|
||||
'login' => 'J',
|
||||
'email' => $email,
|
||||
'idadresse' => $addressId,
|
||||
'idadresseperson' => $personId,
|
||||
'selektionsmerkmale' => [
|
||||
'selektion' => [
|
||||
// Capitalised as in the read response, which is what the write accepts.
|
||||
['@id' => $selectionId, '@auswahl' => true === $selected ? 'True' : 'False'],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ApiClientException
|
||||
* @throws ResponseParserException
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\BusProNet\Model;
|
||||
|
||||
/**
|
||||
* The answer to "Adresse_Neu": the ids of the address the CRM now holds for this person, and
|
||||
* whether it had to create it.
|
||||
*
|
||||
* isNewRecord() is BusPro's own duplicate check ("neuanlage"): False means it matched an address
|
||||
* that already existed and answered with that one's ids, so a caller never has to look for
|
||||
* duplicates itself - which it could not anyway, as reading an address needs the customer's
|
||||
* password. It says nothing about which CRM selections that address carries.
|
||||
*/
|
||||
class RegistrationResponse
|
||||
{
|
||||
public function __construct(
|
||||
private readonly int $addressId,
|
||||
private readonly int $personId,
|
||||
private readonly bool $isNewRecord,
|
||||
) {
|
||||
}
|
||||
|
||||
public function getAddressId(): int
|
||||
{
|
||||
return $this->addressId;
|
||||
}
|
||||
|
||||
public function getPersonId(): int
|
||||
{
|
||||
return $this->personId;
|
||||
}
|
||||
|
||||
public function isNewRecord(): bool
|
||||
{
|
||||
return $this->isNewRecord;
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ use App\BusProNet\Model\NotificationResponse;
|
||||
use App\BusProNet\Model\Pickup;
|
||||
use App\BusProNet\Model\ProfileResponse;
|
||||
use App\BusProNet\Model\ProfileUpdateResponse;
|
||||
use App\BusProNet\Model\RegistrationResponse;
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
|
||||
class ResponseParser
|
||||
@@ -50,8 +51,17 @@ class ResponseParser
|
||||
case 'Adressdaten_Ändern':
|
||||
return $this->createProfileUpdateResponse($xml);
|
||||
case 'SelektionCRM':
|
||||
case 'SelektionCRM_Ändern':
|
||||
return $this->createCrmAttributesResponse($xml);
|
||||
case 'SelektionCRM_Ändern':
|
||||
// Not a CRM attribute tree: the write answers idadresse + idperson +
|
||||
// änderung, exactly the shape createProfileUpdateResponse() reads. It used
|
||||
// to be routed to createCrmAttributesResponse(), which walks a
|
||||
// "selektionsmerkmale" node that is absent here and would have returned an
|
||||
// empty response with every role flag false - dead code until something
|
||||
// sent the art (.ddev/plans/buspro-crm-selection-write.md).
|
||||
return $this->createProfileUpdateResponse($xml);
|
||||
case 'Adresse_Neu':
|
||||
return $this->createRegistrationResponse($xml);
|
||||
}
|
||||
break;
|
||||
case ApiClient::TYPE_BASE_DATA_COUNTRIES:
|
||||
@@ -166,6 +176,34 @@ class ResponseParser
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ResponseParserException
|
||||
*/
|
||||
public function createRegistrationResponse(\SimpleXMLElement $xml): RegistrationResponse
|
||||
{
|
||||
$addressIdXml = $xml->xpath('idadresse') ?: [];
|
||||
$personIdXml = $xml->xpath('idperson') ?: [];
|
||||
|
||||
// Without both ids there is nothing to carry on with: the CRM selection is set by id, and
|
||||
// a local account without them cannot be matched again on the next login. Better a parse
|
||||
// error naming the response than a half-provisioned applicant.
|
||||
if (0 === count($addressIdXml) || 0 === count($personIdXml)) {
|
||||
throw new ResponseParserException('Missing idadresse or idperson in the Adresse_Neu response');
|
||||
}
|
||||
|
||||
$isNewRecord = false;
|
||||
$isNewRecordXml = $xml->xpath('neuanlage') ?: [];
|
||||
if (0 < count($isNewRecordXml)) {
|
||||
$isNewRecord = 'true' === strtolower((string) $isNewRecordXml[0]);
|
||||
}
|
||||
|
||||
return new RegistrationResponse(
|
||||
(int) $addressIdXml[0],
|
||||
(int) $personIdXml[0],
|
||||
$isNewRecord,
|
||||
);
|
||||
}
|
||||
|
||||
public function createCrmAttributesResponse(\SimpleXMLElement $xml): CrmAttributesResponse
|
||||
{
|
||||
$groups = [];
|
||||
|
||||
@@ -12,6 +12,8 @@ enum EmailTextKey: string
|
||||
{
|
||||
case APPLICATION_ACCEPTED = 'application_accepted';
|
||||
case APPLICATION_ACCEPTED_NO_CONTRACT = 'application_accepted_no_contract';
|
||||
case APPLICATION_FORM_FOLLOW_UP = 'application_form_follow_up';
|
||||
case APPLICATION_FORM_RECEIVED = 'application_form_received';
|
||||
case APPLICATION_REJECTED = 'application_rejected';
|
||||
case ASSIGNMENT_CALLED_OFF = 'assignment_called_off';
|
||||
case DISPOSITION_CALLED_OFF = 'disposition_called_off';
|
||||
|
||||
@@ -56,6 +56,35 @@ final class SeasonCalendar
|
||||
return $day >= $start && $day <= $end ? $year : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The season a mail written now would call "die kommende Saison": the one currently running,
|
||||
* or - between two seasons - the next one to start. Never null, unlike seasonYearFor(): a
|
||||
* recruiting mail sent in September is outside every season window but is unmistakably about
|
||||
* the winter ahead.
|
||||
*/
|
||||
public function currentOrUpcomingSeasonYear(\DateTimeInterface $date): int
|
||||
{
|
||||
if (null !== $seasonYear = $this->seasonYearFor($date)) {
|
||||
return $seasonYear;
|
||||
}
|
||||
|
||||
$day = CarbonImmutable::instance($date)->startOfDay();
|
||||
$year = (int) $day->format('Y');
|
||||
|
||||
// Outside any window, so the next start is this year's unless it has already passed,
|
||||
// which for a wrapping window can only mean the season already began - handled above.
|
||||
return $day <= $this->boundaryFor($this->seasonStart, $year) ? $year : $year + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 2026 -> "26/27". The short form the mails to applicants use, where "Saison 2026/27" would
|
||||
* read like a heading in the middle of a sentence.
|
||||
*/
|
||||
public function shortLabel(int $seasonYear): string
|
||||
{
|
||||
return sprintf('%02d/%02d', $seasonYear % 100, ($seasonYear + 1) % 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* null -> "außerhalb der Saison"; 2024 -> "Saison 2024/25".
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Config;
|
||||
|
||||
/**
|
||||
* The slots in the staff-wide document library (Upload::TYPE_DOCUMENT) that code looks a file up
|
||||
* by, rather than by id or name.
|
||||
*
|
||||
* A fixed list and not free text on purpose: something in the application has to consume a slot
|
||||
* for it to mean anything, so inventing one without a release would only produce a token nothing
|
||||
* reads - and a typo would look exactly the same as a document nobody has assigned yet, while
|
||||
* silently dropping an attachment.
|
||||
*
|
||||
* A case's value is what ends up in upload.token, so renaming one orphans the assignment and the
|
||||
* mail quietly loses its attachment. The column is unique: one document per slot.
|
||||
*/
|
||||
enum UploadToken: string
|
||||
{
|
||||
case APPLICATION_FORM_HANDOUT = 'application_form_handout';
|
||||
|
||||
/**
|
||||
* What the document library offers in its dropdown.
|
||||
*/
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::APPLICATION_FORM_HANDOUT => 'Handout für die 2. Mail an Bewerber:innen',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controller\Admin\ApplicationFormSubmission;
|
||||
|
||||
use App\Controller\Traits\ReturnUrlTrait;
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use App\Form\ApplicationFormSubmissionCallsType;
|
||||
use App\Model\ApplicationFormSubmissionCallsDto;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
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;
|
||||
|
||||
/**
|
||||
* Saves the two "call held" checkboxes of the detail view. Rendered by DetailController, which
|
||||
* builds the same form - this one only takes the submission.
|
||||
*/
|
||||
class CallsController extends AbstractController
|
||||
{
|
||||
use ReturnUrlTrait;
|
||||
|
||||
public function __construct(
|
||||
private readonly EntityManagerInterface $entityManager,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
}
|
||||
|
||||
#[Route('/admin/application-form-submission/calls/{uuid}', name: 'app_admin_application_form_submission_calls', methods: ['POST'])]
|
||||
#[IsGranted('ROLE_TEAM_ADMIN')]
|
||||
public function index(ApplicationFormSubmission $submission, Request $request): Response
|
||||
{
|
||||
$callsDto = new ApplicationFormSubmissionCallsDto($submission);
|
||||
$form = $this->createForm(ApplicationFormSubmissionCallsType::class, $callsDto);
|
||||
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
$callsDto->applyToSubmission();
|
||||
$this->entityManager->flush();
|
||||
|
||||
$this->logger->info('Update application form submission calls', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
'firstCallHeldAt' => $submission->getFirstCallHeldAt()?->format('Y-m-d'),
|
||||
'secondCallHeldAt' => $submission->getSecondCallHeldAt()?->format('Y-m-d'),
|
||||
]);
|
||||
|
||||
$this->addFlash('success', 'Die Calls wurden gespeichert');
|
||||
}
|
||||
|
||||
return $this->redirect($this->detailUrl($submission, $request));
|
||||
}
|
||||
|
||||
private function detailUrl(ApplicationFormSubmission $submission, Request $request): string
|
||||
{
|
||||
return $this->generateUrl('app_admin_application_form_submission_detail', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
'r' => $request->query->get('r'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controller\Admin\ApplicationFormSubmission;
|
||||
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use App\Htmx\HxRedirectResponse;
|
||||
use App\Model\TeamerProvisioningResult;
|
||||
use App\Service\Teamer\TeamerProvisioner;
|
||||
use App\Service\Teamer\TeamerProvisioningException;
|
||||
use Psr\Log\LoggerInterface;
|
||||
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;
|
||||
|
||||
/**
|
||||
* Makes a teamer out of an applicant who passed the interview: one click, because the submission
|
||||
* carries everything the CRM needs and there is nothing left for the reviewer to type.
|
||||
*
|
||||
* The click writes to the CRM for real - three writes, none of them undoable from here - so what
|
||||
* goes to BusPro is shown in the confirmation before it goes, and TeamerProvisioner refuses a
|
||||
* submission it cannot provision before sending anything.
|
||||
*/
|
||||
class CreateTeamerController extends AbstractController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TeamerProvisioner $provisioner,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
}
|
||||
|
||||
#[Route('/admin/application-form-submission/create-teamer/{uuid}', name: 'app_admin_application_form_submission_create_teamer')]
|
||||
#[IsGranted('ROLE_TEAM_ADMIN')]
|
||||
public function index(ApplicationFormSubmission $submission, Request $request): Response
|
||||
{
|
||||
if (false === $request->isMethod(Request::METHOD_POST)) {
|
||||
return $this->render('admin/application_form_submission/modal_create_teamer.html.twig', [
|
||||
'submission' => $submission,
|
||||
]);
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $this->provisioner->provision($submission);
|
||||
$this->addFlash('success', $this->describe($result));
|
||||
$this->log($submission, $result);
|
||||
} catch (TeamerProvisioningException $e) {
|
||||
// Deliberately the exception's own wording: it usually carries BusPro's complaint, and
|
||||
// a reviewer can act on a named mandatory field but not on "something went wrong".
|
||||
$this->addFlash('error', $e->getMessage());
|
||||
$this->logger->error('Unable to provision a teamer from an application form submission', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
'error_message' => $e->getMessage(),
|
||||
...$e->getContext(),
|
||||
]);
|
||||
}
|
||||
|
||||
return new HxRedirectResponse($this->generateUrl('app_admin_application_form_submission_detail', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
'r' => $request->query->get('r'),
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Names what happened rather than "erledigt": whether BusPro recognised the applicant, whether
|
||||
* an account already existed and - the one thing that needs a human afterwards - whether the
|
||||
* password mail went out.
|
||||
*/
|
||||
private function describe(TeamerProvisioningResult $result): string
|
||||
{
|
||||
if (true === $result->isAlreadyProvisioned()) {
|
||||
return 'Diese Bewerbung wurde bereits übernommen, es wurde nichts erneut angelegt';
|
||||
}
|
||||
|
||||
$message = true === $result->isUserCreated()
|
||||
? sprintf('%s wurde als Teamer:in angelegt', (string) $result->getUser()->getTeamer())
|
||||
: sprintf('%s hat schon ein Konto und ist jetzt Teamer:in', $result->getUser()->getFullName());
|
||||
|
||||
if (false === $result->isAddressCreated()) {
|
||||
$message .= '. In BusPro gab es die Adresse schon, sie wurde übernommen';
|
||||
}
|
||||
|
||||
$message .= true === $result->isPasswordMailSent()
|
||||
? '. BusPro hat die Passwort-Mail versendet'
|
||||
: '. Die Passwort-Mail von BusPro ist nicht rausgegangen - bitte erneut anstoßen';
|
||||
|
||||
return $message;
|
||||
}
|
||||
|
||||
private function log(ApplicationFormSubmission $submission, TeamerProvisioningResult $result): void
|
||||
{
|
||||
$this->logger->info('Provision a teamer from an application form submission', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
'user_id' => $result->getUser()->getId(),
|
||||
'user_email' => $result->getUser()->getEmail(),
|
||||
'bus_pro_address_id' => $submission->getBusProAddressId(),
|
||||
'bus_pro_person_id' => $submission->getBusProPersonId(),
|
||||
'address_created' => $result->isAddressCreated(),
|
||||
'user_created' => $result->isUserCreated(),
|
||||
'already_teamer' => $result->isAlreadyTeamer(),
|
||||
'already_provisioned' => $result->isAlreadyProvisioned(),
|
||||
'password_mail_sent' => $result->isPasswordMailSent(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controller\Admin\ApplicationFormSubmission;
|
||||
|
||||
use App\Controller\Traits\ReturnUrlTrait;
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use App\Htmx\HxRedirectResponse;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
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;
|
||||
|
||||
/**
|
||||
* A real DELETE, not setDeleted(): the retention rule for job applications asks for the row to
|
||||
* be gone, and "details" and "payload" go with it. The audit log keeps the uuid and who deleted
|
||||
* it, deliberately without the applicant's data.
|
||||
*/
|
||||
class DeleteController extends AbstractController
|
||||
{
|
||||
use ReturnUrlTrait;
|
||||
|
||||
public function __construct(
|
||||
private readonly EntityManagerInterface $entityManager,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
}
|
||||
|
||||
#[Route('/admin/application-form-submission/delete/{uuid}', name: 'app_admin_application_form_submission_delete')]
|
||||
#[IsGranted('ROLE_TEAM_ADMIN')]
|
||||
public function index(ApplicationFormSubmission $submission, Request $request): Response
|
||||
{
|
||||
if (true === $request->isMethod(Request::METHOD_POST)) {
|
||||
$uuid = $submission->getUuid();
|
||||
|
||||
$this->entityManager->remove($submission);
|
||||
$this->entityManager->flush();
|
||||
|
||||
$this->logger->info('Delete application form submission', [
|
||||
'uuid' => $uuid,
|
||||
'form' => $submission->getForm(),
|
||||
'submittedAt' => $submission->getSubmittedAt()->format(\DateTimeInterface::ATOM),
|
||||
]);
|
||||
|
||||
$this->addFlash('success', 'Das eingegangene Formular wurde gelöscht');
|
||||
|
||||
return new HxRedirectResponse(
|
||||
$this->getReturnUrl($request, 'app_admin_application_form_submission_index')
|
||||
);
|
||||
}
|
||||
|
||||
return $this->render('admin/application_form_submission/modal_delete.html.twig', [
|
||||
'submission' => $submission,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controller\Admin\ApplicationFormSubmission;
|
||||
|
||||
use App\Controller\Traits\ReturnUrlTrait;
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use App\Form\ApplicationFormSubmissionCallsType;
|
||||
use App\Model\ApplicationFormSubmissionCallsDto;
|
||||
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;
|
||||
|
||||
class DetailController extends AbstractController
|
||||
{
|
||||
use ReturnUrlTrait;
|
||||
|
||||
#[Route('/admin/application-form-submission/detail/{uuid}', name: 'app_admin_application_form_submission_detail')]
|
||||
#[IsGranted('ROLE_TEAM_ADMIN')]
|
||||
public function index(ApplicationFormSubmission $submission, Request $request): Response
|
||||
{
|
||||
// Rendered here, taken by CallsController - the form has no validation to fail, so it
|
||||
// never has to come back to this page with errors.
|
||||
$callsForm = $this->createForm(
|
||||
ApplicationFormSubmissionCallsType::class,
|
||||
new ApplicationFormSubmissionCallsDto($submission),
|
||||
['action' => $this->generateUrl('app_admin_application_form_submission_calls', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
'r' => $request->query->get('r'),
|
||||
])]
|
||||
);
|
||||
|
||||
return $this->render('admin/application_form_submission/detail.html.twig', [
|
||||
'submission' => $submission,
|
||||
'callsForm' => $callsForm->createView(),
|
||||
'returnUrl' => $this->getReturnUrl($request, 'app_admin_application_form_submission_index'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controller\Admin\ApplicationFormSubmission;
|
||||
|
||||
use App\Repository\ApplicationFormSubmissionRepository;
|
||||
use App\Service\Common\ApplicationFormSubmissionFilterHandler;
|
||||
use Knp\Component\Pager\PaginatorInterface;
|
||||
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;
|
||||
|
||||
/**
|
||||
* The forms the public websites posted here, newest first. Read-only apart from the follow-up
|
||||
* dates and the deletion the retention rule asks for - nothing in this application creates a
|
||||
* submission.
|
||||
*/
|
||||
class IndexController extends AbstractController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ApplicationFormSubmissionRepository $submissionRepository,
|
||||
private readonly PaginatorInterface $paginator,
|
||||
private readonly ApplicationFormSubmissionFilterHandler $filterHandler,
|
||||
) {
|
||||
}
|
||||
|
||||
#[Route('/admin/application-form-submission', name: 'app_admin_application_form_submission_index')]
|
||||
#[IsGranted('ROLE_TEAM_ADMIN')]
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$filterDto = $this->filterHandler->getFilterSettings();
|
||||
|
||||
$pagination = $this->paginator->paginate(
|
||||
$this->submissionRepository->getListQuery($filterDto),
|
||||
$request->query->getInt('page', 1),
|
||||
$request->query->getInt('limit', 50),
|
||||
[
|
||||
'defaultSortFieldName' => 'submission.submittedAt',
|
||||
'defaultSortDirection' => 'desc',
|
||||
]
|
||||
);
|
||||
|
||||
return $this->render('admin/application_form_submission/index.html.twig', [
|
||||
'pagination' => $pagination,
|
||||
'filterDto' => $filterDto,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controller\Admin\ApplicationFormSubmission;
|
||||
|
||||
use App\Email\ApplicationFormSubmissionMailer;
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use App\Htmx\HxRedirectResponse;
|
||||
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;
|
||||
|
||||
/**
|
||||
* Sends the follow-up mail. Never automatic: a reviewer decides when a submission has waited long
|
||||
* enough, and may send it again after a bounce or a wording fix - the stamp is overwritten.
|
||||
*
|
||||
* Unlike the receipt this one is allowed to fail loudly: somebody is watching the response.
|
||||
*/
|
||||
class SendFollowUpMailController extends AbstractController
|
||||
{
|
||||
public function __construct(private readonly ApplicationFormSubmissionMailer $mailer)
|
||||
{
|
||||
}
|
||||
|
||||
#[Route('/admin/application-form-submission/send-follow-up/{uuid}', name: 'app_admin_application_form_submission_send_follow_up')]
|
||||
#[IsGranted('ROLE_TEAM_ADMIN')]
|
||||
public function index(ApplicationFormSubmission $submission, Request $request): Response
|
||||
{
|
||||
if (true === $request->isMethod(Request::METHOD_POST)) {
|
||||
$this->mailer->sendFollowUp($submission);
|
||||
|
||||
$this->addFlash('success', 'Die zweite E-Mail wurde versendet');
|
||||
|
||||
return new HxRedirectResponse($this->generateUrl('app_admin_application_form_submission_detail', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
'r' => $request->query->get('r'),
|
||||
]));
|
||||
}
|
||||
|
||||
return $this->render('admin/application_form_submission/modal_send_follow_up.html.twig', [
|
||||
'submission' => $submission,
|
||||
// Named in the confirmation so a reviewer sees whether the handout the wording
|
||||
// promises is actually going out.
|
||||
'handout' => $this->mailer->findHandout(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controller\Admin\ApplicationFormSubmission;
|
||||
|
||||
use App\Email\ApplicationFormSubmissionMailer;
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use App\Htmx\HxRedirectResponse;
|
||||
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;
|
||||
|
||||
/**
|
||||
* Sends the receipt again by hand. The endpoint sends it by itself when a submission arrives, so
|
||||
* this is for the cases where that did not work: an address that was missing or wrong, or wording
|
||||
* that was fixed afterwards.
|
||||
*/
|
||||
class SendReceiptMailController extends AbstractController
|
||||
{
|
||||
public function __construct(private readonly ApplicationFormSubmissionMailer $mailer)
|
||||
{
|
||||
}
|
||||
|
||||
#[Route('/admin/application-form-submission/send-receipt/{uuid}', name: 'app_admin_application_form_submission_send_receipt')]
|
||||
#[IsGranted('ROLE_TEAM_ADMIN')]
|
||||
public function index(ApplicationFormSubmission $submission, Request $request): Response
|
||||
{
|
||||
if (true === $request->isMethod(Request::METHOD_POST)) {
|
||||
$this->mailer->sendReceipt($submission);
|
||||
|
||||
$this->addFlash('success', 'Die Eingangsbestätigung wurde erneut versendet');
|
||||
|
||||
return new HxRedirectResponse($this->generateUrl('app_admin_application_form_submission_detail', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
'r' => $request->query->get('r'),
|
||||
]));
|
||||
}
|
||||
|
||||
return $this->render('admin/application_form_submission/modal_send_receipt.html.twig', [
|
||||
'submission' => $submission,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,14 @@
|
||||
|
||||
namespace App\Controller\Administrative\System\Document;
|
||||
|
||||
use App\Config\UploadToken;
|
||||
use App\Entity\Upload;
|
||||
use App\Htmx\HxRedirectResponse;
|
||||
use App\Repository\UploadRepository;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\Form\Extension\Core\Type\EnumType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\TextType;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
@@ -18,6 +21,7 @@ class EditController extends AbstractController
|
||||
public function __construct(
|
||||
private readonly EntityManagerInterface $entityManager,
|
||||
private readonly LoggerInterface $logger,
|
||||
private readonly UploadRepository $uploadRepository,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -26,6 +30,7 @@ class EditController extends AbstractController
|
||||
public function index(Upload $upload, Request $request): Response
|
||||
{
|
||||
$nameBefore = $upload->getDisplayName();
|
||||
$tokenBefore = $upload->getToken();
|
||||
|
||||
$form = $this
|
||||
->createFormBuilder($upload)
|
||||
@@ -35,19 +40,37 @@ class EditController extends AbstractController
|
||||
'placeholder' => $upload->getOriginalFilename(),
|
||||
],
|
||||
])
|
||||
->add('token', EnumType::class, [
|
||||
'label' => 'Verwendung',
|
||||
'class' => UploadToken::class,
|
||||
'required' => false,
|
||||
'placeholder' => 'keine besondere Verwendung',
|
||||
'choice_label' => fn (UploadToken $token) => $token->label(),
|
||||
'help' => 'Eine Verwendung gehört immer zu genau einem Dokument. Wird sie hier gesetzt, verliert das bisherige Dokument sie.',
|
||||
])
|
||||
->getForm()
|
||||
;
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
$this->entityManager->flush();
|
||||
$this->addFlash('success', 'Das Dokument wurden umbenannt');
|
||||
// The column is unique, so taking a slot has to free it first - otherwise the flush
|
||||
// dies on the index. Moving rather than refusing is what staff mean by assigning it:
|
||||
// "this is the handout now".
|
||||
$previousHolderId = null === $upload->getToken()
|
||||
? null
|
||||
: $this->uploadRepository->releaseToken($upload->getToken(), $upload);
|
||||
|
||||
$this->logger->info('Rename document', [
|
||||
$this->entityManager->flush();
|
||||
$this->addFlash('success', 'Das Dokument wurde aktualisiert');
|
||||
|
||||
$this->logger->info('Edit document', [
|
||||
'document_id' => $upload->getId(),
|
||||
'document_filename' => $upload->getOriginalFilename(),
|
||||
'document_name_before' => $nameBefore,
|
||||
'document_name_after' => $upload->getDisplayName(),
|
||||
'document_token_before' => $tokenBefore?->value,
|
||||
'document_token_after' => $upload->getToken()?->value,
|
||||
'document_token_taken_from' => $previousHolderId,
|
||||
]);
|
||||
|
||||
return new HxRedirectResponse($this->generateUrl('app_administrative_system_document_index'));
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controller\Api;
|
||||
|
||||
use App\Email\ApplicationFormSubmissionMailer;
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use App\Model\ApplicationFormSubmissionDto;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
||||
|
||||
/**
|
||||
* Receives a form submitted on one of the public websites, posted by the TYPO3
|
||||
* ApplicationApiFinisher. Authenticated by the API key of the stateless "api" firewall.
|
||||
*
|
||||
* The visitor waits for this response inside their own form submission and TYPO3 gives up after
|
||||
* a few seconds without retrying, so this stores the row and answers - notification mail and any
|
||||
* matching against known people belong in a worker, not here
|
||||
* (.ddev/plans/MYEP-APPLICATION-ENDPOINT.md §6).
|
||||
*/
|
||||
class ApplicationFormController extends AbstractController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly EntityManagerInterface $entityManager,
|
||||
private readonly LoggerInterface $logger,
|
||||
private readonly ApplicationFormSubmissionMailer $mailer,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* A failed mapping or validation answers 400 rather than the resolver's default 422: the
|
||||
* contract names 400 for an unusable payload, and the TYPO3 side logs the response body.
|
||||
* Errors are English - the only caller is a machine.
|
||||
*/
|
||||
#[Route('/api/application-forms', name: 'app_api_application_form_submit', methods: ['POST'])]
|
||||
#[IsGranted('ROLE_API')]
|
||||
public function submit(
|
||||
Request $request,
|
||||
#[MapRequestPayload(validationFailedStatusCode: Response::HTTP_BAD_REQUEST)]
|
||||
ApplicationFormSubmissionDto $dto,
|
||||
): JsonResponse {
|
||||
$submission = $this->store($dto, $request);
|
||||
|
||||
// After the store and unable to throw: the row is safe by now, and a mail problem must
|
||||
// not answer an error to a submission this application has accepted. A payload without
|
||||
// an email address is normal - not every form asks for one - and is logged, not failed.
|
||||
$receiptSent = $this->mailer->sendAutomaticReceipt($submission);
|
||||
|
||||
$this->logger->info('Application form submission received', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
'form' => $submission->getForm(),
|
||||
'formLabel' => $submission->getFormLabel(),
|
||||
'pageUid' => $submission->getPageUid(),
|
||||
'submittedAt' => $submission->getSubmittedAt()->format(\DateTimeInterface::ATOM),
|
||||
// the labels and the answers are personal data (§7), their number is not
|
||||
'detailCount' => count($submission->getDetails()),
|
||||
'receiptSent' => $receiptSent,
|
||||
]);
|
||||
|
||||
return new JsonResponse(
|
||||
['status' => 'accepted', 'uuid' => $submission->getUuid()],
|
||||
Response::HTTP_ACCEPTED
|
||||
);
|
||||
}
|
||||
|
||||
private function store(ApplicationFormSubmissionDto $dto, Request $request): ApplicationFormSubmission
|
||||
{
|
||||
$submission = ApplicationFormSubmission::fromDto($dto, $this->decodePayload($request));
|
||||
|
||||
$this->entityManager->persist($submission);
|
||||
$this->entityManager->flush();
|
||||
|
||||
return $submission;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function decodePayload(Request $request): array
|
||||
{
|
||||
$payload = json_decode($request->getContent(), true);
|
||||
|
||||
return is_array($payload) ? $payload : [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controller\Common;
|
||||
|
||||
use App\Form\ApplicationFormSubmissionFilterType;
|
||||
use App\Htmx\HxRedirectResponse;
|
||||
use App\Service\Common\ApplicationFormSubmissionFilterHandler;
|
||||
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;
|
||||
|
||||
class ApplicationFormSubmissionFilterController extends AbstractController
|
||||
{
|
||||
public function __construct(private readonly ApplicationFormSubmissionFilterHandler $filterHandler)
|
||||
{
|
||||
}
|
||||
|
||||
#[Route('/common/application-form-submission/filter', name: 'app_common_application_form_submission_filter')]
|
||||
#[IsGranted('ROLE_TEAM_ADMIN')]
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$formData = $this->filterHandler->getFilterSettings();
|
||||
$form = $this->createForm(ApplicationFormSubmissionFilterType::class, $formData);
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
$this->filterHandler->handleRequest($form);
|
||||
|
||||
return new HxRedirectResponse(
|
||||
$this->generateUrl('app_admin_application_form_submission_index')
|
||||
);
|
||||
}
|
||||
|
||||
return $this->render('common/modal_application_form_submission_filter.html.twig', [
|
||||
'filterForm' => $form->createView(),
|
||||
'filterDto' => $form->getData(),
|
||||
]);
|
||||
}
|
||||
|
||||
#[Route('/common/application-form-submission/filter/reset', name: 'app_common_application_form_submission_filter_reset')]
|
||||
#[IsGranted('ROLE_TEAM_ADMIN')]
|
||||
public function reset(): Response
|
||||
{
|
||||
$this->filterHandler->resetFilterSettings();
|
||||
|
||||
return $this->redirectToRoute('app_admin_application_form_submission_index');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
<?php
|
||||
|
||||
namespace App\Email;
|
||||
|
||||
use App\Config\EmailTextKey;
|
||||
use App\Config\SeasonCalendar;
|
||||
use App\Config\UploadToken;
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use App\Entity\Upload;
|
||||
use App\Model\EmailPathAttachmentDto;
|
||||
use App\Repository\UploadRepository;
|
||||
use App\Service\Upload\UploadHandler;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
/**
|
||||
* The two mails a received form submission gets: the receipt sent when it arrives, and the
|
||||
* follow-up a reviewer triggers by hand. Both are admin-editable (App\Config\EmailTextKey) and
|
||||
* both stamp the date they went out, which is what the reviewer's list shows.
|
||||
*
|
||||
* "Sent" means handed to the mailer. Symfony routes SendEmailMessage to the async transport in
|
||||
* production, so the SMTP delivery happens in a worker afterwards - deliberately, because this
|
||||
* is called inside the visitor's own form submission on another website. A delivery
|
||||
* confirmation would need machinery nothing else here has.
|
||||
*
|
||||
* Goes over MAILER_DSN like every transactional mail; MAILING_MAILER_DSN is for the bulk teamer
|
||||
* mailing only.
|
||||
*/
|
||||
class ApplicationFormSubmissionMailer
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Mailer $mailer,
|
||||
private readonly EntityManagerInterface $entityManager,
|
||||
private readonly LoggerInterface $logger,
|
||||
private readonly SeasonCalendar $seasonCalendar,
|
||||
private readonly UploadRepository $uploadRepository,
|
||||
private readonly UploadHandler $uploadHandler,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The document library file the follow-up mail attaches, or null while no document carries the
|
||||
* slot. Public so the confirmation modal can name it - a reviewer should see whether the
|
||||
* handout the wording promises is actually going out before clicking send.
|
||||
*/
|
||||
public function findHandout(): ?Upload
|
||||
{
|
||||
return $this->uploadRepository->findOneBy(['token' => UploadToken::APPLICATION_FORM_HANDOUT]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The receipt as the endpoint sends it: only for an applicant the form reported as holding an
|
||||
* EU (incl. Switzerland) nationality, and never throwing. The submission is stored and
|
||||
* answered by the time this runs, so a template or transport problem must not turn that into
|
||||
* a 500 - TYPO3 would drop a submission this application already has.
|
||||
*/
|
||||
public function sendAutomaticReceipt(ApplicationFormSubmission $submission): bool
|
||||
{
|
||||
// Strictly true: false is "asked and not EU", null is "this form does not ask at all",
|
||||
// and neither is a yes. A form that wants the receipt has to map the "eu" field.
|
||||
if (true !== $submission->isEu()) {
|
||||
$this->logger->info('Application form receipt mail skipped, not eligible', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
// The value, not the applicant's nationality: a flag the form set (§7).
|
||||
'euFieldPresent' => null !== $submission->isEu(),
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return $this->sendReceipt($submission);
|
||||
} catch (\Throwable $e) {
|
||||
$this->logger->error('Application form receipt mail failed', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
'exception' => $e,
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The receipt sent by hand from the detail view. No eligibility check: a reviewer looking at
|
||||
* the submission has decided, and that decision outranks what the form reported.
|
||||
*/
|
||||
public function sendReceipt(ApplicationFormSubmission $submission): bool
|
||||
{
|
||||
return $this->send($submission, EmailTextKey::APPLICATION_FORM_RECEIVED);
|
||||
}
|
||||
|
||||
/**
|
||||
* The follow-up, triggered from the detail view. Unlike the receipt this one is allowed to
|
||||
* throw: a reviewer who clicked the button has to learn that nothing went out.
|
||||
*/
|
||||
public function sendFollowUp(ApplicationFormSubmission $submission): bool
|
||||
{
|
||||
return $this->send($submission, EmailTextKey::APPLICATION_FORM_FOLLOW_UP);
|
||||
}
|
||||
|
||||
/**
|
||||
* Both mails may be sent again - a bounced address that got corrected, or wording that was
|
||||
* fixed after the fact - so the stamp is overwritten rather than guarded.
|
||||
*/
|
||||
/**
|
||||
* The follow-up mail's wording promises a handout. A missing one is a warning and not a
|
||||
* refusal: the send is a reviewer's deliberate action, the confirmation modal has already told
|
||||
* them whether the attachment exists, and blocking them on something only an admin can fix
|
||||
* would be worse than a mail without it.
|
||||
*
|
||||
* @return list<EmailPathAttachmentDto>
|
||||
*/
|
||||
private function attachmentsFor(EmailTextKey $key): array
|
||||
{
|
||||
if (EmailTextKey::APPLICATION_FORM_FOLLOW_UP !== $key) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$handout = $this->findHandout();
|
||||
|
||||
if (null === $handout) {
|
||||
$this->logger->warning('Application form follow-up mail sent without its handout', [
|
||||
'token' => UploadToken::APPLICATION_FORM_HANDOUT->value,
|
||||
]);
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
return [new EmailPathAttachmentDto(
|
||||
// Resolved, not raw: outside production this hands back UPLOAD_REPLACEMENT_FILE when
|
||||
// one is configured, so a staging test does not mail the real document.
|
||||
$this->uploadHandler->getResolvedUploadFilepath($handout),
|
||||
$handout->getDisplayName() ?: $handout->getOriginalFilename(),
|
||||
$handout->getMimeType(),
|
||||
)];
|
||||
}
|
||||
|
||||
private function send(ApplicationFormSubmission $submission, EmailTextKey $key): bool
|
||||
{
|
||||
$email = $submission->getEmail();
|
||||
|
||||
if (null === $email) {
|
||||
$this->logger->warning('Application form mail skipped, no email address', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
'mail' => $key->value,
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->mailer->createAndSendText($key, [
|
||||
'firstName' => $submission->getFirstName(),
|
||||
'lastName' => $submission->getLastName(),
|
||||
'formLabel' => $submission->getFormLabel(),
|
||||
// The season the applicant applied for, not the one that happens to be current when a
|
||||
// reviewer re-sends months later - hence the submission's own date.
|
||||
'season' => $this->seasonCalendar->shortLabel(
|
||||
$this->seasonCalendar->currentOrUpcomingSeasonYear($submission->getSubmittedAt())
|
||||
),
|
||||
], [
|
||||
'to' => $email,
|
||||
// Without the layout's "Zum Portal" button - the recipient has no account here.
|
||||
'template' => 'email/generic_no_button.html.twig',
|
||||
'attachments' => $this->attachmentsFor($key),
|
||||
]);
|
||||
|
||||
$sentAt = new \DateTimeImmutable();
|
||||
|
||||
match ($key) {
|
||||
EmailTextKey::APPLICATION_FORM_RECEIVED => $submission->setFirstMailSentAt($sentAt),
|
||||
EmailTextKey::APPLICATION_FORM_FOLLOW_UP => $submission->setSecondMailSentAt($sentAt),
|
||||
default => throw new \LogicException(sprintf('%s is not one of the form submission mails.', $key->value)),
|
||||
};
|
||||
|
||||
$this->entityManager->flush();
|
||||
|
||||
$this->logger->info('Application form mail sent', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
'mail' => $key->value,
|
||||
'sentAt' => $sentAt->format(\DateTimeInterface::ATOM),
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -29,10 +29,24 @@ class EmailTextRenderer
|
||||
*/
|
||||
private const ESCAPE_FLAGS = ENT_COMPAT | ENT_SUBSTITUTE;
|
||||
|
||||
/**
|
||||
* The token for the booking link, and why it is not handled like the other placeholders:
|
||||
* a placeholder value is substituted into the *rendered HTML* and escaped there, which is
|
||||
* what makes a teamer's own words harmless - but it also means such a value can never be a
|
||||
* link target, because CommonMark has already percent-encoded the braces by then
|
||||
* ("%7BbookingUrl%7D"). This one is substituted into the Markdown *before* parsing instead,
|
||||
* so the admin can write it as a proper link and CommonMark still gets to vet the URL
|
||||
* through allow_unsafe_links. That is only defensible because the value comes from the
|
||||
* deployment's own environment, exactly like the wording it is substituted into - never
|
||||
* from a teamer or an applicant. Do not extend this to anything a user can influence.
|
||||
*/
|
||||
private const BOOKING_URL_TOKEN = '{bookingUrl}';
|
||||
|
||||
public function __construct(
|
||||
private readonly EmailTextCatalog $catalog,
|
||||
private readonly EmailTextRepository $emailTextRepository,
|
||||
private readonly MailBodyRenderer $mailBodyRenderer,
|
||||
private readonly string $bookingUrl = '',
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -86,10 +100,29 @@ class EmailTextRenderer
|
||||
return new RenderedEmailTextDto(
|
||||
strtr($subject ?? '', $rawTokens),
|
||||
$this->renderHeadline($headline ?? '', $htmlTokens),
|
||||
$this->mailBodyRenderer->render($body ?? '', $rawTokens),
|
||||
$this->mailBodyRenderer->render($this->insertBookingUrl($body ?? ''), $rawTokens),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses rather than sending a broken link: an unconfigured APPLICATION_FORM_BOOKING_URL
|
||||
* would otherwise render as <a href=""> and invite an applicant to book a call they cannot
|
||||
* reach. The caller decides what that means - the endpoint logs it and answers the
|
||||
* submission anyway, a reviewer sending by hand gets to see it.
|
||||
*/
|
||||
private function insertBookingUrl(string $body): string
|
||||
{
|
||||
if (false === str_contains($body, self::BOOKING_URL_TOKEN)) {
|
||||
return $body;
|
||||
}
|
||||
|
||||
if ('' === trim($this->bookingUrl)) {
|
||||
throw new \RuntimeException('The mail wording uses {bookingUrl}, but APPLICATION_FORM_BOOKING_URL is not configured.');
|
||||
}
|
||||
|
||||
return str_replace(self::BOOKING_URL_TOKEN, trim($this->bookingUrl), $body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
@@ -0,0 +1,624 @@
|
||||
<?php
|
||||
|
||||
namespace App\Entity;
|
||||
|
||||
use App\Entity\Traits\TimestampableEntity;
|
||||
use App\Model\ApplicationFormSubmissionDto;
|
||||
use App\Repository\ApplicationFormSubmissionRepository;
|
||||
use Doctrine\DBAL\Types\Types;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
/**
|
||||
* A job application submitted on one of the public websites and posted here by TYPO3. Unrelated
|
||||
* to App\Entity\Application, which is a teamer applying for an assignment.
|
||||
*
|
||||
* The endpoint only ever receives application forms, so every row carries the nine fields it takes
|
||||
* to provision a teamer from it - see ApplicationFormSubmissionDto, where that contract is enforced.
|
||||
* gender is in the constructor because Teamer::$gender is NOT NULL as well; the postal address is
|
||||
* required of a payload but its columns stay nullable, because the address it ends up in
|
||||
* (Embeddable\Address) is nullable throughout - a stricter column here than on the entity it feeds
|
||||
* would be a promise this application does not otherwise keep. What guards provisioning is
|
||||
* TeamerProvisioner's pre-flight check, which refuses a row that predates the contract before
|
||||
* anything is written.
|
||||
*
|
||||
* Deliberately neither Blameable nor SoftDeletable. Nothing here creates a row - TYPO3 does -
|
||||
* and the only thing staff write are the four follow-up dates, where the interesting fact is
|
||||
* that the mail went out or the call happened, not who ticked it off; who did is in the audit
|
||||
* log the mutating controllers write. No SoftDeletable because the retention rule for job
|
||||
* applications asks for real deletion, so this is the one entity here that gets an actual
|
||||
* DELETE. A purge has to cover "details" and "payload" as well - a json column is exactly what
|
||||
* a deletion job forgets.
|
||||
*
|
||||
* The typed columns are the mapped core agreed with the TYPO3 side. "details" is everything
|
||||
* else the visitor filled in, keyed by the German field label in the order the form asked -
|
||||
* display only, never a schema, never queried on (see
|
||||
* .ddev/plans/MYEP-APPLICATION-ENDPOINT.md §3.3).
|
||||
*/
|
||||
#[ORM\Entity(repositoryClass: ApplicationFormSubmissionRepository::class)]
|
||||
// What a list and a dedupe check ask for: the submissions of one form, newest first.
|
||||
#[ORM\Index(name: 'IDX_F47CE995B5265E72', columns: ['form', 'submitted_at'])]
|
||||
class ApplicationFormSubmission implements TimestampableEntityInterface
|
||||
{
|
||||
use TimestampableEntity;
|
||||
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 36, unique: true)]
|
||||
private string $uuid;
|
||||
|
||||
#[ORM\Column(length: 64)]
|
||||
private string $form;
|
||||
|
||||
#[ORM\Column(length: 255)]
|
||||
private string $formLabel;
|
||||
|
||||
#[ORM\Column]
|
||||
private \DateTimeImmutable $submittedAt;
|
||||
|
||||
/**
|
||||
* F, M or D - the application's own vocabulary, as on Teamer. Not null, because BusPro
|
||||
* refuses an address without a gender (error 887) and Teamer::$gender is not nullable
|
||||
* either: a submission that could not be provisioned is not worth storing.
|
||||
*/
|
||||
#[ORM\Column(length: 1)]
|
||||
private string $gender;
|
||||
|
||||
#[ORM\Column(nullable: true)]
|
||||
private ?int $pageUid = null;
|
||||
|
||||
#[ORM\Column(length: 2048, nullable: true)]
|
||||
private ?string $pageUrl = null;
|
||||
|
||||
#[ORM\Column(length: 255, nullable: true)]
|
||||
private ?string $firstName = null;
|
||||
|
||||
#[ORM\Column(length: 255, nullable: true)]
|
||||
private ?string $lastName = null;
|
||||
|
||||
#[ORM\Column(length: 255, nullable: true)]
|
||||
private ?string $email = null;
|
||||
|
||||
#[ORM\Column(length: 64, nullable: true)]
|
||||
private ?string $phone = null;
|
||||
|
||||
#[ORM\Column(length: 64, nullable: true)]
|
||||
private ?string $mobile = null;
|
||||
|
||||
/**
|
||||
* A string, not a date column: the forms use a text field rather than a date picker, so the
|
||||
* value arrives as text and is stored as it arrived. The contract does pin the format -
|
||||
* YYYY-MM-DD, enforced by the DTO - so getDateOfBirth() can parse it strictly. A date column
|
||||
* would only mean migrating the rows that predate the contract, for no gain.
|
||||
*/
|
||||
#[ORM\Column(length: 64, nullable: true)]
|
||||
private ?string $birthDate = null;
|
||||
|
||||
/**
|
||||
* Required of every payload, though nullable here: BusPro refuses to create an address without a
|
||||
* street and a postcode (errors 891 and 890), and a town is expected with them.
|
||||
*/
|
||||
#[ORM\Column(length: 255, nullable: true)]
|
||||
private ?string $street = null;
|
||||
|
||||
#[ORM\Column(length: 32, nullable: true)]
|
||||
private ?string $zipCode = null;
|
||||
|
||||
#[ORM\Column(length: 255, nullable: true)]
|
||||
private ?string $city = null;
|
||||
|
||||
/**
|
||||
* Whether the form said the applicant holds an EU (incl. Switzerland) nationality. Three
|
||||
* states on purpose: true, false, and null for a form that does not ask - only true gets the
|
||||
* automatic receipt mail, so an unmapped or unanswered field is silence, never a yes.
|
||||
*
|
||||
* Mapped rather than left in $details precisely because a rule depends on it. The keys in
|
||||
* $details are staff-written German labels that change on a reword, so nothing may key a
|
||||
* decision off them; the payload key "eu" is the contract with the TYPO3 side instead, and
|
||||
* the German wording of the question stays free to change.
|
||||
*/
|
||||
#[ORM\Column(nullable: true)]
|
||||
private ?bool $eu = null;
|
||||
|
||||
/**
|
||||
* The follow-up a reviewer works through after a submission arrived: two mails and two
|
||||
* phone calls, each stamped when it happened and null until it has. Staff state, never part
|
||||
* of the payload - fromDto() must not touch them.
|
||||
*
|
||||
* The mails carry a time because a send time is a machine fact and stays one once the
|
||||
* notification mail of §6 is automated. A held call does not: the reviewer records it
|
||||
* afterwards and knows the day, so storing an invented time would only look precise.
|
||||
*/
|
||||
#[ORM\Column(type: Types::DATETIME_IMMUTABLE, nullable: true)]
|
||||
private ?\DateTimeImmutable $firstMailSentAt = null;
|
||||
|
||||
#[ORM\Column(type: Types::DATETIME_IMMUTABLE, nullable: true)]
|
||||
private ?\DateTimeImmutable $secondMailSentAt = null;
|
||||
|
||||
#[ORM\Column(type: Types::DATE_IMMUTABLE, nullable: true)]
|
||||
private ?\DateTimeImmutable $firstCallHeldAt = null;
|
||||
|
||||
#[ORM\Column(type: Types::DATE_IMMUTABLE, nullable: true)]
|
||||
private ?\DateTimeImmutable $secondCallHeldAt = null;
|
||||
|
||||
/**
|
||||
* What provisioning got done, step by step (App\Service\Teamer\TeamerProvisioner). The three
|
||||
* writes are not a transaction and each one can fail with the earlier ones done, so a retry
|
||||
* has to resume rather than restart: with these ids set, a second run never creates a second
|
||||
* BusPro address.
|
||||
*
|
||||
* There is deliberately no stamp for the CRM selection in between. That write is idempotent -
|
||||
* setting a selection that is already set answers "änderung=True" and changes nothing - so a
|
||||
* resume simply sends it again, and a column nobody reads would only pretend to be evidence.
|
||||
*/
|
||||
#[ORM\Column(nullable: true)]
|
||||
private ?int $busProAddressId = null;
|
||||
|
||||
#[ORM\Column(nullable: true)]
|
||||
private ?int $busProPersonId = null;
|
||||
|
||||
#[ORM\Column(type: Types::DATETIME_IMMUTABLE, nullable: true)]
|
||||
private ?\DateTimeImmutable $teamerCreatedAt = null;
|
||||
|
||||
/**
|
||||
* The account provisioning created, or the one it found for this applicant. Unowned and
|
||||
* without any cascade on purpose: this entity gets a real DELETE (above), and a purged
|
||||
* application must never take a teamer's account with it.
|
||||
*/
|
||||
#[ORM\ManyToOne]
|
||||
#[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')]
|
||||
private ?User $user = null;
|
||||
|
||||
/**
|
||||
* Everything the visitor filled in beyond the mapped core, keyed by the German field label.
|
||||
* Display only: the labels are staff-written and change on a reword, so nothing may query
|
||||
* this, build a column from it or migrate old rows to a new spelling (§3.3).
|
||||
*
|
||||
* The key order is whatever the engine hands back and is not part of what this carries: on
|
||||
* MariaDB (dev and production) JSON is an alias for LONGTEXT and the document survives
|
||||
* verbatim, on MySQL 8 an object is normalised and its keys come back sorted by length.
|
||||
* Render it in whatever order suits the reviewer rather than relying on either.
|
||||
*
|
||||
* @var array<string, string|bool|list<string>>
|
||||
*/
|
||||
#[ORM\Column(type: Types::JSON)]
|
||||
private array $details = [];
|
||||
|
||||
/**
|
||||
* The request body as received. Mapped keys this application does not know yet are ignored
|
||||
* on the way in (§3.2) and the TYPO3 side widens a form's mapping without a release here,
|
||||
* so without this copy those answers would be lost for good instead of backfillable.
|
||||
*
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
#[ORM\Column(type: Types::JSON)]
|
||||
private array $payload = [];
|
||||
|
||||
public function __construct(string $form, string $formLabel, \DateTimeImmutable $submittedAt, string $gender)
|
||||
{
|
||||
$this->uuid = Uuid::v4();
|
||||
$this->form = $form;
|
||||
$this->formLabel = $formLabel;
|
||||
$this->submittedAt = $submittedAt;
|
||||
$this->gender = $gender;
|
||||
}
|
||||
|
||||
/**
|
||||
* The validated payload as a row. Called with a DTO that passed validation - submittedAt is
|
||||
* parseable and gender is one of F/M/D by then, which is why the constructor can insist on
|
||||
* both.
|
||||
*
|
||||
* The raw payload is passed in separately because the DTO no longer has it: the resolver
|
||||
* drops every key the DTO has no property for, and those are the mapped fields the TYPO3
|
||||
* side has added and this application does not know yet (§3.2). Keeping the body is what
|
||||
* makes them backfillable instead of lost.
|
||||
*
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public static function fromDto(ApplicationFormSubmissionDto $dto, array $payload = []): self
|
||||
{
|
||||
$submission = new self($dto->form, $dto->formLabel, $dto->getSubmittedAt(), (string) $dto->gender);
|
||||
|
||||
return $submission
|
||||
->setPageUid($dto->getPageUid())
|
||||
->setPageUrl($dto->pageUrl)
|
||||
->setFirstName($dto->firstName)
|
||||
->setLastName($dto->lastName)
|
||||
->setEmail($dto->email)
|
||||
->setPhone($dto->phone)
|
||||
->setMobile($dto->mobile)
|
||||
->setBirthDate($dto->birthDate)
|
||||
->setStreet($dto->street)
|
||||
->setZipCode($dto->zipCode)
|
||||
->setCity($dto->city)
|
||||
->setEu($dto->isEu())
|
||||
->setDetails($dto->getNormalizedDetails())
|
||||
->setPayload($payload)
|
||||
;
|
||||
}
|
||||
|
||||
/**
|
||||
* The applicant as BusPro's "Adresse_Neu" wants them: the German keys of Teamer::toPayload(),
|
||||
* Embeddable\Address::toPayload() and Embeddable\Communication::toPayload(), which is what
|
||||
* the CRM has always been sent from this application.
|
||||
*
|
||||
* The gender mapping is Teamer::toPayload()'s: F becomes W, everything else goes out as it
|
||||
* came. What BusPro makes of "D" is unverified - it is passed through rather than guessed at.
|
||||
*
|
||||
* The street and the postcode are BusPro's own mandatory fields here, which is why the contract
|
||||
* requires the postal address as a whole. The country is not asked on the forms and is not
|
||||
* guessed either: BusPro fills its own default in, and a wrong country on the record would be
|
||||
* worse than none.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toPayload(): array
|
||||
{
|
||||
$gender = strtoupper($this->gender);
|
||||
|
||||
return [
|
||||
'geburtsdatum' => $this->getDateOfBirth()?->format('d.m.Y'),
|
||||
'geschlecht' => 'F' === $gender ? 'W' : $gender,
|
||||
'vorname' => $this->firstName,
|
||||
'name' => $this->lastName,
|
||||
'anschrift' => [
|
||||
'strasse' => $this->street,
|
||||
'plz' => $this->zipCode,
|
||||
'ort' => $this->city,
|
||||
],
|
||||
'kommunikation' => [
|
||||
'email' => $this->email,
|
||||
'telefonmobil' => $this->mobile,
|
||||
'telefonprivat' => $this->phone,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The birthday as a date, parsed strictly: the contract guarantees YYYY-MM-DD, and anything
|
||||
* else is null rather than a date \DateTimeImmutable would have invented from it - rows that
|
||||
* predate the contract are exactly that case. Zeroed time of day, so the same row never yields
|
||||
* two different dates.
|
||||
*/
|
||||
public function getDateOfBirth(): ?\DateTimeImmutable
|
||||
{
|
||||
if (null === $this->birthDate || '' === $this->birthDate) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$dateOfBirth = \DateTimeImmutable::createFromFormat('!Y-m-d', $this->birthDate);
|
||||
|
||||
// createFromFormat() happily rolls a 31st of February over into March, which would put a
|
||||
// date of birth on the record the applicant never gave. The round trip is what catches it.
|
||||
if (false === $dateOfBirth || $dateOfBirth->format('Y-m-d') !== $this->birthDate) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $dateOfBirth;
|
||||
}
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getUuid(): string
|
||||
{
|
||||
return $this->uuid;
|
||||
}
|
||||
|
||||
public function getForm(): string
|
||||
{
|
||||
return $this->form;
|
||||
}
|
||||
|
||||
public function getFormLabel(): string
|
||||
{
|
||||
return $this->formLabel;
|
||||
}
|
||||
|
||||
public function getSubmittedAt(): \DateTimeImmutable
|
||||
{
|
||||
return $this->submittedAt;
|
||||
}
|
||||
|
||||
public function getGender(): string
|
||||
{
|
||||
return $this->gender;
|
||||
}
|
||||
|
||||
public function getPageUid(): ?int
|
||||
{
|
||||
return $this->pageUid;
|
||||
}
|
||||
|
||||
public function setPageUid(?int $pageUid): static
|
||||
{
|
||||
$this->pageUid = $pageUid;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPageUrl(): ?string
|
||||
{
|
||||
return $this->pageUrl;
|
||||
}
|
||||
|
||||
public function setPageUrl(?string $pageUrl): static
|
||||
{
|
||||
$this->pageUrl = $pageUrl;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getFirstName(): ?string
|
||||
{
|
||||
return $this->firstName;
|
||||
}
|
||||
|
||||
public function setFirstName(?string $firstName): static
|
||||
{
|
||||
$this->firstName = $firstName;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getLastName(): ?string
|
||||
{
|
||||
return $this->lastName;
|
||||
}
|
||||
|
||||
public function setLastName(?string $lastName): static
|
||||
{
|
||||
$this->lastName = $lastName;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getEmail(): ?string
|
||||
{
|
||||
return $this->email;
|
||||
}
|
||||
|
||||
public function setEmail(?string $email): static
|
||||
{
|
||||
// Same normalization as Contact and Embeddable\Communication: a later match against
|
||||
// existing people has to compare like with like.
|
||||
$this->email = null === $email ? null : mb_strtolower(trim($email));
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPhone(): ?string
|
||||
{
|
||||
return $this->phone;
|
||||
}
|
||||
|
||||
public function setPhone(?string $phone): static
|
||||
{
|
||||
$this->phone = $phone;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getMobile(): ?string
|
||||
{
|
||||
return $this->mobile;
|
||||
}
|
||||
|
||||
public function setMobile(?string $mobile): static
|
||||
{
|
||||
$this->mobile = $mobile;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getBirthDate(): ?string
|
||||
{
|
||||
return $this->birthDate;
|
||||
}
|
||||
|
||||
public function setBirthDate(?string $birthDate): static
|
||||
{
|
||||
$this->birthDate = $birthDate;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getStreet(): ?string
|
||||
{
|
||||
return $this->street;
|
||||
}
|
||||
|
||||
public function setStreet(?string $street): static
|
||||
{
|
||||
$this->street = $street;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getZipCode(): ?string
|
||||
{
|
||||
return $this->zipCode;
|
||||
}
|
||||
|
||||
public function setZipCode(?string $zipCode): static
|
||||
{
|
||||
$this->zipCode = $zipCode;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getCity(): ?string
|
||||
{
|
||||
return $this->city;
|
||||
}
|
||||
|
||||
public function setCity(?string $city): static
|
||||
{
|
||||
$this->city = $city;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function isEu(): ?bool
|
||||
{
|
||||
return $this->eu;
|
||||
}
|
||||
|
||||
public function setEu(?bool $eu): static
|
||||
{
|
||||
$this->eu = $eu;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getFirstMailSentAt(): ?\DateTimeImmutable
|
||||
{
|
||||
return $this->firstMailSentAt;
|
||||
}
|
||||
|
||||
public function setFirstMailSentAt(?\DateTimeImmutable $firstMailSentAt): static
|
||||
{
|
||||
$this->firstMailSentAt = $firstMailSentAt;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getSecondMailSentAt(): ?\DateTimeImmutable
|
||||
{
|
||||
return $this->secondMailSentAt;
|
||||
}
|
||||
|
||||
public function setSecondMailSentAt(?\DateTimeImmutable $secondMailSentAt): static
|
||||
{
|
||||
$this->secondMailSentAt = $secondMailSentAt;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getFirstCallHeldAt(): ?\DateTimeImmutable
|
||||
{
|
||||
return $this->firstCallHeldAt;
|
||||
}
|
||||
|
||||
public function setFirstCallHeldAt(?\DateTimeImmutable $firstCallHeldAt): static
|
||||
{
|
||||
$this->firstCallHeldAt = $firstCallHeldAt;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getSecondCallHeldAt(): ?\DateTimeImmutable
|
||||
{
|
||||
return $this->secondCallHeldAt;
|
||||
}
|
||||
|
||||
public function setSecondCallHeldAt(?\DateTimeImmutable $secondCallHeldAt): static
|
||||
{
|
||||
$this->secondCallHeldAt = $secondCallHeldAt;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getBusProAddressId(): ?int
|
||||
{
|
||||
return $this->busProAddressId;
|
||||
}
|
||||
|
||||
public function setBusProAddressId(?int $busProAddressId): static
|
||||
{
|
||||
$this->busProAddressId = $busProAddressId;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getBusProPersonId(): ?int
|
||||
{
|
||||
return $this->busProPersonId;
|
||||
}
|
||||
|
||||
public function setBusProPersonId(?int $busProPersonId): static
|
||||
{
|
||||
$this->busProPersonId = $busProPersonId;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getTeamerCreatedAt(): ?\DateTimeImmutable
|
||||
{
|
||||
return $this->teamerCreatedAt;
|
||||
}
|
||||
|
||||
public function setTeamerCreatedAt(?\DateTimeImmutable $teamerCreatedAt): static
|
||||
{
|
||||
$this->teamerCreatedAt = $teamerCreatedAt;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getUser(): ?User
|
||||
{
|
||||
return $this->user;
|
||||
}
|
||||
|
||||
public function setUser(?User $user): static
|
||||
{
|
||||
$this->user = $user;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the BusPro address behind this submission is known - the one thing a retry must
|
||||
* not do twice.
|
||||
*/
|
||||
public function hasBusProAddress(): bool
|
||||
{
|
||||
return null !== $this->busProAddressId && null !== $this->busProPersonId;
|
||||
}
|
||||
|
||||
public function isProvisioned(): bool
|
||||
{
|
||||
return null !== $this->teamerCreatedAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string|bool|list<string>>
|
||||
*/
|
||||
public function getDetails(): array
|
||||
{
|
||||
return $this->details;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string|bool|list<string>> $details
|
||||
*/
|
||||
public function setDetails(array $details): static
|
||||
{
|
||||
$this->details = $details;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function getPayload(): array
|
||||
{
|
||||
return $this->payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function setPayload(array $payload): static
|
||||
{
|
||||
$this->payload = $payload;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Entity;
|
||||
|
||||
use App\Config\UploadToken;
|
||||
use App\Entity\Traits\BlameableEntity;
|
||||
use App\Entity\Traits\TimestampableEntity;
|
||||
use App\Model\UploadDto;
|
||||
@@ -53,6 +54,14 @@ class Upload implements BlameableEntityInterface, TimestampableEntityInterface
|
||||
#[ORM\Column(length: 255, nullable: true)]
|
||||
private ?string $displayName = null;
|
||||
|
||||
/**
|
||||
* Marks this document as the one a specific feature looks up - the handout a mail attaches,
|
||||
* and whatever else earns a slot later. Unique, so assigning a token that another document
|
||||
* holds moves it rather than duplicating it (see the document library's edit action).
|
||||
*/
|
||||
#[ORM\Column(length: 64, nullable: true, unique: true, enumType: UploadToken::class)]
|
||||
private ?UploadToken $token = null;
|
||||
|
||||
#[ORM\Column]
|
||||
private ?int $size = null;
|
||||
|
||||
@@ -163,6 +172,18 @@ class Upload implements BlameableEntityInterface, TimestampableEntityInterface
|
||||
return static::STATUS_REJECTED === $this->getStatus();
|
||||
}
|
||||
|
||||
public function getToken(): ?UploadToken
|
||||
{
|
||||
return $this->token;
|
||||
}
|
||||
|
||||
public function setToken(?UploadToken $token): static
|
||||
{
|
||||
$this->token = $token;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getFilename(): ?string
|
||||
{
|
||||
return $this->filename;
|
||||
|
||||
@@ -36,6 +36,13 @@ class AccessDeniedListener
|
||||
return;
|
||||
}
|
||||
|
||||
// The api firewall is stateless and answers machines: a redirect to a login page would
|
||||
// be read as success there, and the flash message below needs a session this request
|
||||
// has none of.
|
||||
if (str_starts_with($request->getPathInfo(), '/api/')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->logger->warning('Access denied', [
|
||||
'uri' => $request->getRequestUri(),
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
<?php
|
||||
|
||||
namespace App\EventListener;
|
||||
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
use Symfony\Component\HttpKernel\KernelEvents;
|
||||
use Symfony\Component\Validator\ConstraintViolationInterface;
|
||||
use Symfony\Component\Validator\Exception\ValidationFailedException;
|
||||
|
||||
/**
|
||||
* Answers every failure under the api firewall as JSON.
|
||||
*
|
||||
* Without this, a rejected payload leaves through Symfony's error renderer, which picks its format
|
||||
* from the request: the callers send "Content-Type: application/json" but no "Accept" header, so the
|
||||
* format is html and the body is an error page. The violation messages then survive only in dev,
|
||||
* inside an HTML comment and a <title>; in production the error template carries no message at all.
|
||||
* The TYPO3 finisher logs that body verbatim, which is how a missing field became "some HTML" in the
|
||||
* log of the one system that could act on it.
|
||||
*
|
||||
* So the field names are put where the caller can read them - and into this application's own log as
|
||||
* well, because "submissions stopped arriving" is diagnosed here as often as there.
|
||||
*
|
||||
* Scoped by path, like AccessDeniedListener, and deliberately the same pattern the api firewall uses
|
||||
* (security.yaml, "^/api"): the UI must keep its HTML error pages.
|
||||
*
|
||||
* **The priority is load-bearing.** ExceptionEvent::setResponse() stops propagation, so whoever
|
||||
* answers first is the only one who answers. This has to sit below security's own firewall listener
|
||||
* (priority 1), which turns an AuthenticationException or an AccessDeniedException into the 401 the
|
||||
* caller needs - at a higher priority this listener answered those as a bare 500 - and below
|
||||
* Symfony's ErrorListener::logKernelException (priority 0), so a crash is still logged with its
|
||||
* stack trace. Everything left over is ours, well before the error page is rendered at -128.
|
||||
*/
|
||||
#[AsEventListener(event: KernelEvents::EXCEPTION, method: 'onKernelException', priority: -8)]
|
||||
class ApiExceptionListener
|
||||
{
|
||||
public function __construct(private readonly LoggerInterface $logger)
|
||||
{
|
||||
}
|
||||
|
||||
public function onKernelException(ExceptionEvent $event): void
|
||||
{
|
||||
$request = $event->getRequest();
|
||||
|
||||
if (false === $this->isApiRequest($request)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$exception = $event->getThrowable();
|
||||
$statusCode = $exception instanceof HttpExceptionInterface
|
||||
? $exception->getStatusCode()
|
||||
: Response::HTTP_INTERNAL_SERVER_ERROR;
|
||||
|
||||
$violations = $this->collectViolations($exception, $request);
|
||||
|
||||
$event->setResponse(new JsonResponse(
|
||||
[
|
||||
'status' => 'error',
|
||||
'message' => $this->describe($exception, $statusCode, $violations),
|
||||
'errors' => $violations,
|
||||
],
|
||||
$statusCode,
|
||||
// Keeps what the status needs to mean anything, WWW-Authenticate on a 401 above all.
|
||||
$exception instanceof HttpExceptionInterface ? $exception->getHeaders() : [],
|
||||
));
|
||||
|
||||
$this->log($request, $exception, $statusCode, $violations);
|
||||
}
|
||||
|
||||
/**
|
||||
* The failed payload fields, as "field", the message the constraint produced, and the shape of
|
||||
* what actually arrived. A violation without a property path keeps the field null rather than
|
||||
* inventing one - a class-level constraint belongs to the payload as a whole.
|
||||
*
|
||||
* @return list<array{field: string|null, message: string, received: string}>
|
||||
*/
|
||||
private function collectViolations(\Throwable $exception, Request $request): array
|
||||
{
|
||||
// RequestPayloadValueResolver wraps the ValidationFailedException in an HttpException whose
|
||||
// status code the endpoint chooses (400 here, not the resolver's default 422).
|
||||
$validationFailed = $exception instanceof ValidationFailedException
|
||||
? $exception
|
||||
: $exception->getPrevious();
|
||||
|
||||
if (false === $validationFailed instanceof ValidationFailedException) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$payload = $this->decodePayload($request);
|
||||
$violations = [];
|
||||
|
||||
foreach ($validationFailed->getViolations() as $violation) {
|
||||
$field = $violation->getPropertyPath();
|
||||
$violations[] = [
|
||||
'field' => '' === $field ? null : $field,
|
||||
'message' => $this->untranslate($violation),
|
||||
'received' => $this->describeReceived($payload, $field),
|
||||
];
|
||||
}
|
||||
|
||||
return $violations;
|
||||
}
|
||||
|
||||
/**
|
||||
* The violation message in English, rebuilt from its own template.
|
||||
*
|
||||
* ConstraintViolation::getMessage() is translated - the application's locale is German, so a
|
||||
* constraint whose message this application does not phrase itself reaches the caller as
|
||||
* "Dieser Wert sollte vom Typ null|string sein.", in a payload the contract promises is English.
|
||||
* The template and its parameters are untouched by that, and substituting them is exactly what
|
||||
* Symfony does when no translator is configured.
|
||||
*
|
||||
* "{{ value }}" is deliberately not substituted: it would put the rejected value into the
|
||||
* response and into the log, and a rejected payload is still personal data. Which field and what
|
||||
* shape it had is what a caller needs; describeReceived() covers the shape.
|
||||
*/
|
||||
private function untranslate(ConstraintViolationInterface $violation): string
|
||||
{
|
||||
$replacements = ['{{ value }}' => '(omitted)'];
|
||||
|
||||
foreach ($violation->getParameters() as $placeholder => $value) {
|
||||
// Only real placeholders: the parameters may carry extra keys (the serializer's "hint"),
|
||||
// and strtr() would replace those as plain substrings anywhere in the template.
|
||||
if (false === str_starts_with((string) $placeholder, '{{')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (true === is_scalar($value) || null === $value) {
|
||||
$replacements[(string) $placeholder] = (string) $value;
|
||||
}
|
||||
}
|
||||
|
||||
return strtr($violation->getMessageTemplate(), $replacements);
|
||||
}
|
||||
|
||||
/**
|
||||
* The shape of the value that was rejected - never the value itself.
|
||||
*
|
||||
* This is the part the framework does not tell anybody: "This value should be of type
|
||||
* null|string." names what was expected and leaves the caller to guess what they sent. A form
|
||||
* engine that hands a date element straight to json_encode sends an object, and seeing its keys
|
||||
* is the difference between a five-minute fix and a guessing game.
|
||||
*
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
private function describeReceived(array $payload, string $propertyPath): string
|
||||
{
|
||||
// Top-level key only: a path like "details[Nationalität]" is described by its own bucket,
|
||||
// which is as deep as this endpoint's payload goes.
|
||||
$field = explode('[', explode('.', $propertyPath)[0])[0];
|
||||
|
||||
if ('' === $field || false === array_key_exists($field, $payload)) {
|
||||
return 'missing';
|
||||
}
|
||||
|
||||
return $this->describeShape($payload[$field]);
|
||||
}
|
||||
|
||||
private function describeShape(mixed $value): string
|
||||
{
|
||||
if (true === is_string($value)) {
|
||||
return '' === $value ? 'empty string' : sprintf('string (%d characters)', mb_strlen($value));
|
||||
}
|
||||
|
||||
if (false === is_array($value)) {
|
||||
return get_debug_type($value);
|
||||
}
|
||||
|
||||
if ([] === $value) {
|
||||
return 'empty array';
|
||||
}
|
||||
|
||||
if (true === array_is_list($value)) {
|
||||
return sprintf('list of %d', count($value));
|
||||
}
|
||||
|
||||
// The keys of an object are not personal data, and they are what identifies the sender's
|
||||
// shape - a serialized date arrives as date/timezone_type/timezone, for instance.
|
||||
$keys = array_map(
|
||||
static fn (string|int $key): string => mb_substr((string) $key, 0, 32),
|
||||
array_slice(array_keys($value), 0, 10),
|
||||
);
|
||||
|
||||
return sprintf('object with keys: %s', implode(', ', $keys));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function decodePayload(Request $request): array
|
||||
{
|
||||
$payload = json_decode($request->getContent(), true);
|
||||
|
||||
return is_array($payload) ? $payload : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* One line naming what is wrong, for a caller that logs the body and reads no further.
|
||||
*
|
||||
* A server error is described generically: its message is an internal detail, and the log entry
|
||||
* below is where it belongs. Everything else may say what it says - the 4xx messages here are
|
||||
* the endpoint's own contract ("birthDate must be a date in the format YYYY-MM-DD."), written
|
||||
* for exactly this reader.
|
||||
*
|
||||
* @param list<array{field: string|null, message: string}> $violations
|
||||
*/
|
||||
private function describe(\Throwable $exception, int $statusCode, array $violations): string
|
||||
{
|
||||
if ($statusCode >= Response::HTTP_INTERNAL_SERVER_ERROR) {
|
||||
return 'Internal server error.';
|
||||
}
|
||||
|
||||
if ([] !== $violations) {
|
||||
return implode(' ', array_column($violations, 'message'));
|
||||
}
|
||||
|
||||
// Not translated either - an HttpException message from the resolver ("Request payload
|
||||
// contains invalid \"json\" data.") is English already, unlike a constraint violation.
|
||||
|
||||
$message = trim($exception->getMessage());
|
||||
|
||||
return '' === $message ? 'Request rejected.' : $message;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{field: string|null, message: string}> $violations
|
||||
*/
|
||||
private function log(Request $request, \Throwable $exception, int $statusCode, array $violations): void
|
||||
{
|
||||
$context = [
|
||||
'method' => $request->getMethod(),
|
||||
'uri' => $request->getRequestUri(),
|
||||
'status' => $statusCode,
|
||||
// The field names and the shape of what arrived, never the values: a rejected payload is
|
||||
// still personal data.
|
||||
'fields' => array_values(array_filter(array_column($violations, 'field'))),
|
||||
'rejected' => $this->summarise($violations),
|
||||
'error_message' => $exception->getMessage(),
|
||||
];
|
||||
|
||||
if ($statusCode >= Response::HTTP_INTERNAL_SERVER_ERROR) {
|
||||
// The trace comes from Symfony's own logging at priority 0; this entry is the one that
|
||||
// says which request it was.
|
||||
$this->logger->error('API request failed', $context);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->logger->warning('API request rejected', $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* One readable line per violation for the log, so this application's own log answers the same
|
||||
* question the response does.
|
||||
*
|
||||
* @param list<array{field: string|null, message: string, received: string}> $violations
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private function summarise(array $violations): array
|
||||
{
|
||||
return array_map(
|
||||
static fn (array $violation): string => sprintf(
|
||||
'%s: %s (received %s)',
|
||||
$violation['field'] ?? 'payload',
|
||||
$violation['message'],
|
||||
$violation['received'],
|
||||
),
|
||||
$violations,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The api firewall's own pattern. "/api" alone is matched as well, so a request to the prefix
|
||||
* itself does not slip out as HTML.
|
||||
*/
|
||||
private function isApiRequest(Request $request): bool
|
||||
{
|
||||
$path = $request->getPathInfo();
|
||||
|
||||
return '/api' === $path || str_starts_with($path, '/api/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Form;
|
||||
|
||||
use App\Model\ApplicationFormSubmissionCallsDto;
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
|
||||
class ApplicationFormSubmissionCallsType extends AbstractType
|
||||
{
|
||||
public function buildForm(FormBuilderInterface $builder, array $options): void
|
||||
{
|
||||
$builder
|
||||
->add('firstCallHeld', CheckboxType::class, [
|
||||
'label' => '1. Call geführt',
|
||||
'required' => false,
|
||||
])
|
||||
->add('secondCallHeld', CheckboxType::class, [
|
||||
'label' => '2. Call geführt',
|
||||
'required' => false,
|
||||
])
|
||||
->add('save', SubmitType::class, [
|
||||
'label' => 'speichern',
|
||||
])
|
||||
;
|
||||
}
|
||||
|
||||
public function configureOptions(OptionsResolver $resolver): void
|
||||
{
|
||||
$resolver
|
||||
->setDefaults([
|
||||
'data_class' => ApplicationFormSubmissionCallsDto::class,
|
||||
// The DTO is built from the submission and has no no-arg constructor.
|
||||
'empty_data' => null,
|
||||
])
|
||||
;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Form;
|
||||
|
||||
use App\Model\ApplicationFormSubmissionFilterDto;
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\TextType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
|
||||
class ApplicationFormSubmissionFilterType extends AbstractType
|
||||
{
|
||||
public function buildForm(FormBuilderInterface $builder, array $options): void
|
||||
{
|
||||
$builder
|
||||
->add('name', TextType::class, [
|
||||
'label' => 'Name',
|
||||
'required' => false,
|
||||
'help' => 'Vor- oder Nachname, Teil genügt',
|
||||
])
|
||||
->add('dateFrom', DatepickerType::class, [
|
||||
'label' => 'eingegangen von',
|
||||
'required' => false,
|
||||
])
|
||||
->add('dateTo', DatepickerType::class, [
|
||||
'label' => 'eingegangen bis',
|
||||
'required' => false,
|
||||
])
|
||||
->add('apply', SubmitType::class, [
|
||||
'label' => 'filtern',
|
||||
])
|
||||
->add('reset', SubmitType::class, [
|
||||
'label' => 'reset',
|
||||
])
|
||||
;
|
||||
}
|
||||
|
||||
public function configureOptions(OptionsResolver $resolver): void
|
||||
{
|
||||
$resolver
|
||||
->setDefaults([
|
||||
'data_class' => ApplicationFormSubmissionFilterDto::class,
|
||||
])
|
||||
;
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,15 @@ use Symfony\Bundle\SecurityBundle\Security;
|
||||
|
||||
class InjectUserProcessor
|
||||
{
|
||||
public function __construct(private readonly Security $security)
|
||||
{
|
||||
/**
|
||||
* The SAPI is injected rather than read from PHP_SAPI inside the processor so a test can
|
||||
* exercise the web path: under PHPUnit php_sapi_name() is always "cli", which made the
|
||||
* branch below unreachable from every functional test.
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly Security $security,
|
||||
private readonly string $sapi = \PHP_SAPI,
|
||||
) {
|
||||
}
|
||||
|
||||
public function __invoke(LogRecord $record): LogRecord
|
||||
@@ -18,10 +25,9 @@ class InjectUserProcessor
|
||||
return $record;
|
||||
}
|
||||
|
||||
/** @var User $user */
|
||||
$user = $this->security->getUser();
|
||||
|
||||
if (null === $user || 'cli' === php_sapi_name()) {
|
||||
if (null === $user || 'cli' === $this->sapi) {
|
||||
$record->extra['user'] = [
|
||||
'id' => null,
|
||||
'username' => 'system',
|
||||
@@ -31,6 +37,20 @@ class InjectUserProcessor
|
||||
return $record;
|
||||
}
|
||||
|
||||
// Not every firewall authenticates a row in the user table: the stateless "api" firewall
|
||||
// resolves its shared key to an in-memory user, which has an identifier and roles and
|
||||
// nothing else. Reaching for getId() or getEmail() there is a 500 on a request that had
|
||||
// already stored its data.
|
||||
if (false === $user instanceof User) {
|
||||
$record->extra['user'] = [
|
||||
'id' => null,
|
||||
'username' => $user->getUserIdentifier(),
|
||||
'roles' => $user->getRoles(),
|
||||
];
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
$record->extra['user'] = [
|
||||
'id' => $user->getId(),
|
||||
'email' => $user->getEmail(),
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace App\Logging;
|
||||
|
||||
use App\Entity\Core\User;
|
||||
use App\Entity\User;
|
||||
use Monolog\Attribute\AsMonologProcessor;
|
||||
use Monolog\LogRecord;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
@@ -11,8 +11,15 @@ use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
|
||||
#[AsMonologProcessor]
|
||||
class UserDataProcessor
|
||||
{
|
||||
public function __construct(private readonly Security $security)
|
||||
{
|
||||
/**
|
||||
* The SAPI is injected rather than read from PHP_SAPI inside the processor so a test can
|
||||
* exercise the web path: under PHPUnit php_sapi_name() is always "cli", which made
|
||||
* everything below the check unreachable from every functional test.
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly Security $security,
|
||||
private readonly string $sapi = \PHP_SAPI,
|
||||
) {
|
||||
}
|
||||
|
||||
public function __invoke(LogRecord $record): LogRecord
|
||||
@@ -21,7 +28,7 @@ class UserDataProcessor
|
||||
return $record;
|
||||
}
|
||||
|
||||
if ('cli' === php_sapi_name()) {
|
||||
if ('cli' === $this->sapi) {
|
||||
$record->extra['user'] = [
|
||||
'id' => null,
|
||||
'username' => 'SYSTEM',
|
||||
@@ -31,7 +38,6 @@ class UserDataProcessor
|
||||
return $record;
|
||||
}
|
||||
|
||||
/** @var User $user */
|
||||
$user = $this->security->getUser();
|
||||
|
||||
if (null === $user) {
|
||||
@@ -57,7 +63,10 @@ class UserDataProcessor
|
||||
$username = $user->getUserIdentifier();
|
||||
}
|
||||
$record->extra['user'] = [
|
||||
'id' => $user->getId(),
|
||||
// Only a user table row has an id: the stateless "api" firewall resolves its shared
|
||||
// key to an in-memory user, and calling getId() on that is a 500 on a request that
|
||||
// had already stored its data.
|
||||
'id' => $user instanceof User ? $user->getId() : null,
|
||||
'username' => $username,
|
||||
'roles' => $user->getRoles(),
|
||||
];
|
||||
|
||||
@@ -50,6 +50,18 @@ class AdminMenuBuilder extends AbstractMenuBuilder
|
||||
'icon' => 'mail',
|
||||
],
|
||||
]);
|
||||
$menu->addChild('Eingegangene Bewerbungen', [
|
||||
'route' => 'app_admin_application_form_submission_index',
|
||||
'linkAttributes' => [
|
||||
'title' => 'Eingegangene Bewerbungen',
|
||||
],
|
||||
'extras' => [
|
||||
'icon' => 'file',
|
||||
'routes' => [
|
||||
['pattern' => '/^app_admin_application_form_submission_/'],
|
||||
],
|
||||
],
|
||||
]);
|
||||
$documentMenu = $menu->addChild('Dokumente', [
|
||||
'extras' => [
|
||||
'icon' => 'document',
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model;
|
||||
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
|
||||
/**
|
||||
* The two "call held" checkboxes of the detail view. The entity stores the day each call
|
||||
* happened, the reviewer only ticks a box - this is the translation between the two.
|
||||
*
|
||||
* Unticking clears the date. Ticking a box whose date is already set leaves that date alone, so
|
||||
* saving the form again does not silently move a call from the day it happened to today.
|
||||
*/
|
||||
class ApplicationFormSubmissionCallsDto
|
||||
{
|
||||
private bool $firstCallHeld;
|
||||
|
||||
private bool $secondCallHeld;
|
||||
|
||||
public function __construct(private readonly ApplicationFormSubmission $submission)
|
||||
{
|
||||
$this->firstCallHeld = null !== $submission->getFirstCallHeldAt();
|
||||
$this->secondCallHeld = null !== $submission->getSecondCallHeldAt();
|
||||
}
|
||||
|
||||
public function isFirstCallHeld(): bool
|
||||
{
|
||||
return $this->firstCallHeld;
|
||||
}
|
||||
|
||||
public function setFirstCallHeld(bool $firstCallHeld): static
|
||||
{
|
||||
$this->firstCallHeld = $firstCallHeld;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function isSecondCallHeld(): bool
|
||||
{
|
||||
return $this->secondCallHeld;
|
||||
}
|
||||
|
||||
public function setSecondCallHeld(bool $secondCallHeld): static
|
||||
{
|
||||
$this->secondCallHeld = $secondCallHeld;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function applyToSubmission(): void
|
||||
{
|
||||
$this->submission
|
||||
->setFirstCallHeldAt($this->resolve($this->firstCallHeld, $this->submission->getFirstCallHeldAt()))
|
||||
->setSecondCallHeldAt($this->resolve($this->secondCallHeld, $this->submission->getSecondCallHeldAt()))
|
||||
;
|
||||
}
|
||||
|
||||
private function resolve(bool $held, ?\DateTimeImmutable $current): ?\DateTimeImmutable
|
||||
{
|
||||
if (false === $held) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $current ?? new \DateTimeImmutable('today');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model;
|
||||
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
|
||||
/**
|
||||
* One submitted TYPO3 form, mapped from the request body by #[MapRequestPayload].
|
||||
*
|
||||
* Two rules from the contract (.ddev/plans/MYEP-APPLICATION-ENDPOINT.md §3.2, §3.3) shape this
|
||||
* class and must survive any rewrite:
|
||||
*
|
||||
* - **Unknown keys are ignored, never rejected.** The mapped vocabulary grows on the TYPO3
|
||||
* side without a release here, so nothing may switch the serializer's ALLOW_EXTRA_ATTRIBUTES
|
||||
* off: it would turn every later mapping change into a 400, silent because the finisher only
|
||||
* logs it.
|
||||
* - **Nine fields are required of every payload**: lastName, firstName, birthDate, email, gender,
|
||||
* eu, street, zipCode and city. They are what it takes to provision a teamer from a submission,
|
||||
* and BusPro's own mandatory fields for creating an address are among them (errors 885-891: Name,
|
||||
* Vorname, Geschlecht, EMail, PLZ, Straße) - a payload without those cannot become a teamer at
|
||||
* all, and asking a reviewer to retype them from the answers would be worse than refusing the
|
||||
* payload. The endpoint only ever receives application forms, so this holds for every payload and
|
||||
* there is no form-type discriminator
|
||||
* (.ddev/plans/application-form-teamer-provisioning.md).
|
||||
*
|
||||
* Everything beyond the nine - phone, mobile, nationality, bank details - stays optional and is
|
||||
* filled in by the teamer themselves afterwards, so an absent key there still means "not part of
|
||||
* this form", never "empty".
|
||||
*
|
||||
* A 400 costs a whole application, and the visitor sees their form submit normally either way.
|
||||
* That is accepted deliberately: the same people control the TYPO3 forms and this endpoint, the
|
||||
* response body names the offending field and the finisher logs it.
|
||||
*
|
||||
* The lengths are the storage limits of ApplicationFormSubmission, not an opinion about what a
|
||||
* visitor may type: they exist so an oversized value is a 400 the TYPO3 side logs, and not a
|
||||
* database error after the response has been promised.
|
||||
*/
|
||||
class ApplicationFormSubmissionDto
|
||||
{
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
public const GENDERS = ['F', 'M', 'D'];
|
||||
|
||||
public const MAX_DETAIL_LABEL_LENGTH = 255;
|
||||
|
||||
public const MAX_DETAIL_VALUE_LENGTH = 65535;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $details
|
||||
*/
|
||||
public function __construct(
|
||||
#[Assert\NotBlank(message: 'form must not be empty.')]
|
||||
#[Assert\Length(max: 64, maxMessage: 'form must not exceed {{ limit }} characters.')]
|
||||
public readonly ?string $form = null,
|
||||
#[Assert\NotBlank(message: 'formLabel must not be empty.')]
|
||||
#[Assert\Length(max: 255, maxMessage: 'formLabel must not exceed {{ limit }} characters.')]
|
||||
public readonly ?string $formLabel = null,
|
||||
#[Assert\NotBlank(message: 'submittedAt must not be empty.')]
|
||||
public readonly ?string $submittedAt = null,
|
||||
// int|string because a page id is unmistakable as "1421": rejecting the quoted form
|
||||
// would cost a whole submission over a distinction nobody can see in a form editor.
|
||||
// Read it back through getPageUid().
|
||||
public readonly int|string|null $pageUid = null,
|
||||
#[Assert\Length(max: 2048, maxMessage: 'pageUrl must not exceed {{ limit }} characters.')]
|
||||
public readonly ?string $pageUrl = null,
|
||||
#[Assert\NotBlank(message: 'firstName must not be empty.')]
|
||||
#[Assert\Length(max: 255)]
|
||||
public readonly ?string $firstName = null,
|
||||
#[Assert\NotBlank(message: 'lastName must not be empty.')]
|
||||
#[Assert\Length(max: 255)]
|
||||
public readonly ?string $lastName = null,
|
||||
#[Assert\NotBlank(message: 'email must not be empty.')]
|
||||
#[Assert\Email(message: 'email is not a valid email address.')]
|
||||
#[Assert\Length(max: 255)]
|
||||
public readonly ?string $email = null,
|
||||
#[Assert\Length(max: 64)]
|
||||
public readonly ?string $phone = null,
|
||||
#[Assert\Length(max: 64)]
|
||||
public readonly ?string $mobile = null,
|
||||
// The one field whose format is nailed down rather than stored as typed: provisioning
|
||||
// parses it as a date, and a free-text birthday would only fail later, in front of a
|
||||
// reviewer who cannot fix it.
|
||||
#[Assert\NotBlank(message: 'birthDate must not be empty.')]
|
||||
#[Assert\Date(message: 'birthDate must be a date in the format YYYY-MM-DD.')]
|
||||
public readonly ?string $birthDate = null,
|
||||
// The application's own vocabulary, not BusPro's: ApplicationFormSubmission::toPayload()
|
||||
// maps F to W on the way out, exactly as Teamer::toPayload() does.
|
||||
#[Assert\NotBlank(message: 'gender must not be empty.')]
|
||||
#[Assert\Choice(choices: self::GENDERS, message: 'gender must be one of F, M or D.')]
|
||||
public readonly ?string $gender = null,
|
||||
// The whole postal address, required together. Street and postcode are BusPro's own
|
||||
// Pflichtfelder for a new address (errors 891 and 890), so a submission without them is one
|
||||
// no teamer can be provisioned from; the town is not on that list, but an address carrying a
|
||||
// street and a postcode without one is not an address worth writing to the CRM either.
|
||||
#[Assert\NotBlank(message: 'street must not be empty.')]
|
||||
#[Assert\Length(max: 255)]
|
||||
public readonly ?string $street = null,
|
||||
#[Assert\NotBlank(message: 'zipCode must not be empty.')]
|
||||
#[Assert\Length(max: 32)]
|
||||
public readonly ?string $zipCode = null,
|
||||
#[Assert\NotBlank(message: 'city must not be empty.')]
|
||||
#[Assert\Length(max: 255)]
|
||||
public readonly ?string $city = null,
|
||||
// Whether the applicant holds an EU (incl. Switzerland) nationality - the one payload
|
||||
// field a rule depends on, hence mapped rather than left in $details. bool|string|int
|
||||
// for the same reason as pageUid: a form posts "1" or "" as readily as a JSON boolean,
|
||||
// and losing a whole application over the spelling would be absurd. Read it back
|
||||
// through isEu(). Required, because the receipt mail depends on it - but required as a
|
||||
// value, not as a truth: NotNull rather than NotBlank, or a lawful "no" would be a 400.
|
||||
#[Assert\NotNull(message: 'eu must not be omitted.')]
|
||||
public readonly bool|string|int|null $eu = null,
|
||||
public readonly array $details = [],
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The value is generated with \DateTimeInterface::ATOM on the TYPO3 side, but it is still
|
||||
* outside input: it is validated here rather than trusted, and read back through
|
||||
* getSubmittedAt() so the endpoint never stores a date it could not parse.
|
||||
*/
|
||||
#[Assert\Callback]
|
||||
public function validateSubmittedAt(ExecutionContextInterface $executionContext): void
|
||||
{
|
||||
if (null === $this->submittedAt || '' === $this->submittedAt) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (null === $this->getSubmittedAt()) {
|
||||
$executionContext
|
||||
->buildViolation('submittedAt is not a valid ISO 8601 date and time.')
|
||||
->atPath('submittedAt')
|
||||
->addViolation()
|
||||
;
|
||||
}
|
||||
}
|
||||
|
||||
#[Assert\Callback]
|
||||
public function validatePageUid(ExecutionContextInterface $executionContext): void
|
||||
{
|
||||
if (null === $this->pageUid || '' === $this->pageUid) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (null === $this->getPageUid()) {
|
||||
$executionContext
|
||||
->buildViolation('pageUid must be a positive integer.')
|
||||
->atPath('pageUid')
|
||||
->addViolation()
|
||||
;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* details is the only half with no schema: the keys are staff-written German field labels,
|
||||
* so anything a person can type is a legal key - dots, slashes, umlauts and typos included.
|
||||
* Only the shape is checked, because that is all the json column and the display can carry:
|
||||
* a label with content, and a scalar or a flat list as the answer.
|
||||
*/
|
||||
/**
|
||||
* A value that is neither a boolean nor one of the spellings a form posts is a 400 rather
|
||||
* than a silent null: null means "this form does not ask", and a misconfigured mapping that
|
||||
* quietly stopped every receipt mail would be the worst of both worlds. The same reasoning
|
||||
* as validatePageUid().
|
||||
*/
|
||||
#[Assert\Callback]
|
||||
public function validateEu(ExecutionContextInterface $executionContext): void
|
||||
{
|
||||
if (null === $this->eu) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (null === $this->isEu()) {
|
||||
$executionContext
|
||||
->buildViolation('eu must be a boolean.')
|
||||
->atPath('eu')
|
||||
->addViolation()
|
||||
;
|
||||
}
|
||||
}
|
||||
|
||||
#[Assert\Callback]
|
||||
public function validateDetails(ExecutionContextInterface $executionContext): void
|
||||
{
|
||||
foreach ($this->details as $label => $value) {
|
||||
$label = (string) $label;
|
||||
|
||||
if ('' === trim($label) || mb_strlen($label) > self::MAX_DETAIL_LABEL_LENGTH) {
|
||||
$this->violate(
|
||||
$executionContext,
|
||||
sprintf('details contains an empty or overlong label ("%s").', mb_substr($label, 0, 32))
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_array($value) && false === array_is_list($value)) {
|
||||
$this->violate($executionContext, sprintf('The value of "%s" must be a flat list.', $label));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (is_array($value) ? $value : [$value] as $single) {
|
||||
if (null === $single || is_scalar($single)) {
|
||||
if (is_string($single) && mb_strlen($single) > self::MAX_DETAIL_VALUE_LENGTH) {
|
||||
$this->violate(
|
||||
$executionContext,
|
||||
sprintf('The value of "%s" exceeds %d characters.', $label, self::MAX_DETAIL_VALUE_LENGTH)
|
||||
);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->violate(
|
||||
$executionContext,
|
||||
sprintf('The value of "%s" must be a string, a boolean or a list of strings.', $label)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* null for "the form does not ask" as well as for a value that made no sense - the caller
|
||||
* treats both as "no automatic mail", and validateEu() has already turned the second into a
|
||||
* 400 by the time anything reads this.
|
||||
*/
|
||||
public function isEu(): ?bool
|
||||
{
|
||||
if (is_bool($this->eu)) {
|
||||
return $this->eu;
|
||||
}
|
||||
|
||||
return match (is_string($this->eu) ? mb_strtolower(trim($this->eu)) : $this->eu) {
|
||||
null => null,
|
||||
1, '1', 'true' => true,
|
||||
0, '0', 'false', '' => false,
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
public function getPageUid(): ?int
|
||||
{
|
||||
if (null === $this->pageUid) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_string($this->pageUid) && 1 !== preg_match('/^\d+$/', $this->pageUid)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$pageUid = (int) $this->pageUid;
|
||||
|
||||
return $pageUid > 0 ? $pageUid : null;
|
||||
}
|
||||
|
||||
public function getSubmittedAt(): ?\DateTimeImmutable
|
||||
{
|
||||
if (null === $this->submittedAt || '' === $this->submittedAt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Anchored on a date: \DateTimeImmutable happily reads "now" or "monday", and a
|
||||
// submission timestamped by a relative expression is not a submission time at all.
|
||||
if (1 !== preg_match('/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/', $this->submittedAt)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return new \DateTimeImmutable($this->submittedAt);
|
||||
} catch (\Exception) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The blob as it is stored: numbers arrive as strings from the form editor but nothing stops
|
||||
* a mapping from sending one unquoted, and an empty answer is dropped rather than kept -
|
||||
* TYPO3 strips those before sending (§3.3), so a label present in the blob always has
|
||||
* content. The received order is the form's order and is never touched.
|
||||
*
|
||||
* @return array<string, string|bool|list<string>>
|
||||
*/
|
||||
public function getNormalizedDetails(): array
|
||||
{
|
||||
$normalized = [];
|
||||
|
||||
foreach ($this->details as $label => $value) {
|
||||
if (null === $value || '' === $value || [] === $value) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$normalized[(string) $label] = is_array($value)
|
||||
? array_values(array_map($this->normalizeListValue(...), $value))
|
||||
: $this->normalizeValue($value);
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
private function violate(ExecutionContextInterface $executionContext, string $message): void
|
||||
{
|
||||
$executionContext
|
||||
->buildViolation($message)
|
||||
->atPath('details')
|
||||
->addViolation()
|
||||
;
|
||||
}
|
||||
|
||||
private function normalizeValue(mixed $value): string|bool
|
||||
{
|
||||
return is_bool($value) ? $value : (string) $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* A multi-select answer is a list of the labels the visitor picked, never a list of
|
||||
* true/false: casting keeps the blob readable as what was chosen.
|
||||
*/
|
||||
private function normalizeListValue(mixed $value): string
|
||||
{
|
||||
if (is_bool($value)) {
|
||||
return $value ? 'true' : 'false';
|
||||
}
|
||||
|
||||
return (string) $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model;
|
||||
|
||||
class ApplicationFormSubmissionFilterDto extends AbstractFilterDto
|
||||
{
|
||||
protected ?string $name = null;
|
||||
|
||||
/**
|
||||
* A range over the arrival time, not over the follow-up dates: "what came in that week" is
|
||||
* the question a reviewer asks of this list. The datepicker hands over midnight, so the
|
||||
* repository has to stretch dateTo to the end of its day - submittedAt carries a time.
|
||||
*/
|
||||
protected ?\DateTimeImmutable $dateFrom = null;
|
||||
|
||||
protected ?\DateTimeImmutable $dateTo = null;
|
||||
|
||||
public function getName(): ?string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
public function setName(?string $name): static
|
||||
{
|
||||
$this->name = $name;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getDateFrom(): ?\DateTimeImmutable
|
||||
{
|
||||
return $this->dateFrom;
|
||||
}
|
||||
|
||||
public function setDateFrom(?\DateTimeImmutable $dateFrom): static
|
||||
{
|
||||
$this->dateFrom = $dateFrom;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getDateTo(): ?\DateTimeImmutable
|
||||
{
|
||||
return $this->dateTo;
|
||||
}
|
||||
|
||||
public function setDateTo(?\DateTimeImmutable $dateTo): static
|
||||
{
|
||||
$this->dateTo = $dateTo;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace App\Model;
|
||||
|
||||
use App\Entity\User;
|
||||
|
||||
/**
|
||||
* What provisioning actually did, so the controller can phrase the flash and the log entry
|
||||
* without re-deriving any of it (App\Service\Teamer\TeamerProvisioner).
|
||||
*
|
||||
* Every flag is a fact the reviewer wants to know: whether BusPro created the address or
|
||||
* recognised the applicant, whether an account already existed, and whether the password mail
|
||||
* went out - the last is not fatal, but without it the teamer cannot log in until somebody sends
|
||||
* it again.
|
||||
*/
|
||||
class TeamerProvisioningResult
|
||||
{
|
||||
public function __construct(
|
||||
private readonly User $user,
|
||||
private readonly bool $addressCreated,
|
||||
private readonly bool $userCreated,
|
||||
private readonly bool $alreadyTeamer,
|
||||
private readonly bool $passwordMailSent,
|
||||
private readonly bool $alreadyProvisioned = false,
|
||||
) {
|
||||
}
|
||||
|
||||
public function getUser(): User
|
||||
{
|
||||
return $this->user;
|
||||
}
|
||||
|
||||
/**
|
||||
* False means BusPro matched an address it already held and answered with its ids - not a
|
||||
* failure, and not a duplicate either.
|
||||
*/
|
||||
public function isAddressCreated(): bool
|
||||
{
|
||||
return $this->addressCreated;
|
||||
}
|
||||
|
||||
public function isUserCreated(): bool
|
||||
{
|
||||
return $this->userCreated;
|
||||
}
|
||||
|
||||
public function isAlreadyTeamer(): bool
|
||||
{
|
||||
return $this->alreadyTeamer;
|
||||
}
|
||||
|
||||
public function isPasswordMailSent(): bool
|
||||
{
|
||||
return $this->passwordMailSent;
|
||||
}
|
||||
|
||||
/**
|
||||
* The submission had been provisioned before and nothing was sent to BusPro at all.
|
||||
*/
|
||||
public function isAlreadyProvisioned(): bool
|
||||
{
|
||||
return $this->alreadyProvisioned;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Repository;
|
||||
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use App\Model\ApplicationFormSubmissionFilterDto;
|
||||
use App\Repository\Traits\QueryHelperTrait;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\ORM\Query;
|
||||
use Doctrine\ORM\QueryBuilder;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/**
|
||||
* @extends ServiceEntityRepository<ApplicationFormSubmission>
|
||||
*
|
||||
* @method ApplicationFormSubmission|null find($id, $lockMode = null, $lockVersion = null)
|
||||
* @method ApplicationFormSubmission|null findOneBy(array $criteria, array $orderBy = null)
|
||||
* @method ApplicationFormSubmission[] findAll()
|
||||
* @method ApplicationFormSubmission[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
|
||||
*/
|
||||
class ApplicationFormSubmissionRepository extends ServiceEntityRepository
|
||||
{
|
||||
use QueryHelperTrait;
|
||||
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, ApplicationFormSubmission::class);
|
||||
}
|
||||
|
||||
public function getListQuery(ApplicationFormSubmissionFilterDto $filterDto): Query
|
||||
{
|
||||
$qb = $this->createQueryBuilder('submission');
|
||||
|
||||
$this->applyFilterCriteria($qb, $filterDto);
|
||||
|
||||
return $qb->getQuery();
|
||||
}
|
||||
|
||||
private function applyFilterCriteria(QueryBuilder $qb, ApplicationFormSubmissionFilterDto $filterDto): void
|
||||
{
|
||||
if (null !== $name = $filterDto->getName()) {
|
||||
$qb
|
||||
->andWhere($qb->expr()->orX(
|
||||
$qb->expr()->like('submission.firstName', ':name'),
|
||||
$qb->expr()->like('submission.lastName', ':name')
|
||||
))
|
||||
->setParameter('name', '%'.$this->escapeLikeWildcards($name).'%')
|
||||
;
|
||||
}
|
||||
|
||||
if (null !== $dateFrom = $filterDto->getDateFrom()) {
|
||||
$qb
|
||||
->andWhere($qb->expr()->gte('submission.submittedAt', ':dateFrom'))
|
||||
->setParameter('dateFrom', $dateFrom)
|
||||
;
|
||||
}
|
||||
|
||||
if (null !== $dateTo = $filterDto->getDateTo()) {
|
||||
// The datepicker hands over midnight and submittedAt carries a time, so a plain
|
||||
// lte would drop everything that arrived during the last day of the range.
|
||||
$qb
|
||||
->andWhere($qb->expr()->lte('submission.submittedAt', ':dateTo'))
|
||||
->setParameter('dateTo', $dateTo->setTime(23, 59, 59))
|
||||
;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Repository;
|
||||
|
||||
use App\Config\UploadToken;
|
||||
use App\Entity\Upload;
|
||||
use App\Model\DocumentFilterDto;
|
||||
use App\Repository\Traits\QueryHelperTrait;
|
||||
@@ -231,4 +232,38 @@ class UploadRepository extends ServiceEntityRepository
|
||||
->getSingleScalarResult()
|
||||
;
|
||||
}
|
||||
|
||||
public function findByToken(UploadToken $token): ?Upload
|
||||
{
|
||||
return $this->findOneBy(['token' => $token]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees a token slot, so the document taking it can be flushed without tripping the unique
|
||||
* index. The update runs immediately rather than through the unit of work on purpose: both
|
||||
* rows are Uploads, and nothing guarantees Doctrine writes the release before it writes the
|
||||
* row that takes the token.
|
||||
*
|
||||
* Returns the id of the document that lost the slot, for the log.
|
||||
*/
|
||||
public function releaseToken(UploadToken $token, Upload $takenBy): ?int
|
||||
{
|
||||
$holder = $this->findByToken($token);
|
||||
|
||||
if (null === $holder || $holder === $takenBy) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$this
|
||||
->getEntityManager()
|
||||
->createQuery('UPDATE App\Entity\Upload u SET u.token = NULL WHERE u.id = :id')
|
||||
->setParameter('id', $holder->getId())
|
||||
->execute()
|
||||
;
|
||||
|
||||
// Keeps the loaded entity in step with the row that was just written.
|
||||
$holder->setToken(null);
|
||||
|
||||
return $holder->getId();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Security\AccessToken;
|
||||
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\Security\Http\AccessToken\AccessTokenExtractorInterface;
|
||||
|
||||
/**
|
||||
* Reads the API key of the stateless "api" firewall from its own header. The built-in header
|
||||
* extractor expects "Authorization: Bearer", which would claim a shared secret is an OAuth
|
||||
* access token - this application is the client of a real OAuth provider (MYEP_OAUTH2_*), and
|
||||
* the two must not look alike in a request.
|
||||
*/
|
||||
class ApiKeyExtractor implements AccessTokenExtractorInterface
|
||||
{
|
||||
public const HEADER = 'X-Api-Key';
|
||||
|
||||
public function extractAccessToken(Request $request): ?string
|
||||
{
|
||||
$key = trim((string) $request->headers->get(self::HEADER, ''));
|
||||
|
||||
return '' === $key ? null : $key;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Security\AccessToken;
|
||||
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
|
||||
use Symfony\Component\Security\Http\AccessToken\AccessTokenHandlerInterface;
|
||||
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
|
||||
|
||||
/**
|
||||
* Validates the shared key a sibling website posts with. There is no person to log in and no
|
||||
* account to look up: the key is the identity, and the user it resolves to is the in-memory
|
||||
* "api" user of the api_user_provider - nothing about it may reach the user table, where a row
|
||||
* would be a login to this application's UI.
|
||||
*/
|
||||
class ApiKeyTokenHandler implements AccessTokenHandlerInterface
|
||||
{
|
||||
public const USER_IDENTIFIER = 'api';
|
||||
|
||||
public function __construct(
|
||||
private readonly string $apiKey,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
}
|
||||
|
||||
public function getUserBadgeFrom(string $accessToken): UserBadge
|
||||
{
|
||||
// An unconfigured key locks the endpoint instead of opening it: hash_equals('', '')
|
||||
// is true, so without this check a deployment that forgot the secret would accept
|
||||
// an empty key from anyone.
|
||||
if ('' === $this->apiKey) {
|
||||
$this->logger->error('API key authentication attempted while no key is configured');
|
||||
|
||||
throw new BadCredentialsException('No API key configured.');
|
||||
}
|
||||
|
||||
if (false === hash_equals($this->apiKey, $accessToken)) {
|
||||
$this->logger->warning('API key authentication failed');
|
||||
|
||||
throw new BadCredentialsException('Invalid API key.');
|
||||
}
|
||||
|
||||
return new UserBadge(self::USER_IDENTIFIER);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service\Common;
|
||||
|
||||
use App\Model\AbstractFilterDto;
|
||||
use App\Model\ApplicationFormSubmissionFilterDto;
|
||||
|
||||
class ApplicationFormSubmissionFilterHandler extends AbstractFilterHandler
|
||||
{
|
||||
protected string $namespace = 'filter:application_form_submission';
|
||||
protected string $modelClass = ApplicationFormSubmissionFilterDto::class;
|
||||
|
||||
public function getFilterSettings(): ApplicationFormSubmissionFilterDto
|
||||
{
|
||||
$filterDto = new $this->modelClass();
|
||||
|
||||
if (null === $data = $this->getSession()->get($this->namespace)) {
|
||||
return $filterDto;
|
||||
}
|
||||
|
||||
if (isset($data['name'])) {
|
||||
$filterDto->setName($data['name']);
|
||||
}
|
||||
if (isset($data['date_from'])) {
|
||||
$filterDto->setDateFrom($data['date_from']);
|
||||
}
|
||||
if (isset($data['date_to'])) {
|
||||
$filterDto->setDateTo($data['date_to']);
|
||||
}
|
||||
|
||||
return $filterDto;
|
||||
}
|
||||
|
||||
protected function saveFilterSettings(AbstractFilterDto $filterDto): void
|
||||
{
|
||||
/* @var ApplicationFormSubmissionFilterDto $filterDto */
|
||||
$this->getSession()->set($this->namespace, [
|
||||
'name' => $filterDto->getName(),
|
||||
'date_from' => $filterDto->getDateFrom(),
|
||||
'date_to' => $filterDto->getDateTo(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service\Teamer;
|
||||
|
||||
use App\BusProNet\ApiClient;
|
||||
use App\BusProNet\ApiClientException;
|
||||
use App\BusProNet\Model\Address;
|
||||
use App\BusProNet\Model\Communication;
|
||||
use App\BusProNet\Model\NotificationResponse;
|
||||
use App\BusProNet\Model\ProfileResponse;
|
||||
use App\BusProNet\Model\RegistrationResponse;
|
||||
use App\BusProNet\ResponseParserException;
|
||||
use App\BusProNet\UserDataHandler;
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use App\Entity\Teamer;
|
||||
use App\Entity\User;
|
||||
use App\Model\TeamerProvisioningResult;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
/**
|
||||
* Turns an applicant who passed the interview into a teamer.
|
||||
*
|
||||
* Three writes, two of them in BusPro, which is the source of truth for who is a teamer:
|
||||
*
|
||||
* 1. create the applicant's address in the CRM (or learn that it already exists),
|
||||
* 2. set the general teamer selection on it,
|
||||
* 3. create the local User and Teamer - only once 2 succeeded.
|
||||
*
|
||||
* A password mail follows as step 4, so the applicant can log in here.
|
||||
*
|
||||
* **They are not a transaction.** Each step can fail with the earlier ones done, and there is no
|
||||
* undo for an address in BusPro. What makes that survivable is that every outcome is persisted on
|
||||
* the submission as it happens, so a retry resumes instead of restarting: with the ids stored, the
|
||||
* address is never created twice, and the selection write is idempotent by design.
|
||||
*
|
||||
* Nothing here reads the applicant's profile back from BusPro. Adressdaten needs the customer's
|
||||
* password, which provisioning deliberately never has (see
|
||||
* .ddev/plans/application-form-teamer-provisioning.md), so the local records are built from the
|
||||
* data that was sent plus the ids that came back.
|
||||
*
|
||||
* This is also the one place in the application that grants a teamer their CRM marker rather than
|
||||
* reading it. Everything else stays read-only: roles and hotel codes are synced from BusPro on
|
||||
* every login, and an admin may approve a claim, never grant one.
|
||||
*/
|
||||
class TeamerProvisioner
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ApiClient $apiClient,
|
||||
private readonly UserDataHandler $userDataHandler,
|
||||
private readonly EntityManagerInterface $entityManager,
|
||||
private readonly LoggerInterface $logger,
|
||||
private readonly int $teamerSelectionId,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws TeamerProvisioningException
|
||||
*/
|
||||
public function provision(ApplicationFormSubmission $submission): TeamerProvisioningResult
|
||||
{
|
||||
// A second click must not create a second anything. The button is gone once a submission
|
||||
// is provisioned, but a resubmitted form or a stale page would still arrive here.
|
||||
if (true === $submission->isProvisioned() && null !== $user = $submission->getUser()) {
|
||||
return new TeamerProvisioningResult(
|
||||
user: $user,
|
||||
addressCreated: false,
|
||||
userCreated: false,
|
||||
alreadyTeamer: true,
|
||||
passwordMailSent: false,
|
||||
alreadyProvisioned: true,
|
||||
);
|
||||
}
|
||||
|
||||
$this->assertProvisionable($submission);
|
||||
|
||||
$addressCreated = $this->createAddress($submission);
|
||||
$this->setTeamerSelection($submission);
|
||||
|
||||
$user = $this->createUser($submission);
|
||||
|
||||
return new TeamerProvisioningResult(
|
||||
user: $user['user'],
|
||||
addressCreated: $addressCreated,
|
||||
userCreated: $user['created'],
|
||||
alreadyTeamer: $user['alreadyTeamer'],
|
||||
// Last, so that a failure in any earlier step never asks somebody to set a password
|
||||
// for an account that does not exist.
|
||||
passwordMailSent: $this->requestPassword($user['user']),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The fields the contract guarantees, checked once before anything is written: a payload that
|
||||
* predates the contract would otherwise fail halfway, and BusPro's own complaint about a
|
||||
* missing field arrives after the address attempt, not before it.
|
||||
*
|
||||
* @throws TeamerProvisioningException
|
||||
*/
|
||||
private function assertProvisionable(ApplicationFormSubmission $submission): void
|
||||
{
|
||||
$missing = [];
|
||||
|
||||
if (true === empty($submission->getFirstName())) {
|
||||
$missing[] = 'Vorname';
|
||||
}
|
||||
if (true === empty($submission->getLastName())) {
|
||||
$missing[] = 'Nachname';
|
||||
}
|
||||
if (true === empty($submission->getEmail())) {
|
||||
$missing[] = 'E-Mail-Adresse';
|
||||
}
|
||||
if (null === $submission->getDateOfBirth()) {
|
||||
$missing[] = 'Geburtsdatum';
|
||||
}
|
||||
// BusPro's own Pflichtfelder for a new address, and the reason the contract requires them:
|
||||
// without a street and a postcode the request fails at step 1 (errors 891 and 890).
|
||||
if (true === empty($submission->getStreet())) {
|
||||
$missing[] = 'Straße';
|
||||
}
|
||||
if (true === empty($submission->getZipCode())) {
|
||||
$missing[] = 'Postleitzahl';
|
||||
}
|
||||
if (true === empty($submission->getCity())) {
|
||||
$missing[] = 'Ort';
|
||||
}
|
||||
|
||||
if ([] === $missing) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new TeamerProvisioningException(sprintf('Die Bewerbung ist unvollständig, es fehlt: %s', implode(', ', $missing)), ['uuid' => $submission->getUuid(), 'missing' => $missing]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 1. Returns whether BusPro created the address, or recognised the person and answered
|
||||
* with the ids of the one it already held.
|
||||
*
|
||||
* @throws TeamerProvisioningException
|
||||
*/
|
||||
private function createAddress(ApplicationFormSubmission $submission): bool
|
||||
{
|
||||
// Resume: the address of this submission exists, and asking for it again would create a
|
||||
// second one.
|
||||
if (true === $submission->hasBusProAddress()) {
|
||||
$this->logger->info('Skip BusPro address creation, the submission already has one', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
'bus_pro_address_id' => $submission->getBusProAddressId(),
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $this->apiClient->createAddress($submission);
|
||||
} catch (ApiClientException|ResponseParserException $e) {
|
||||
throw new TeamerProvisioningException('Die Adresse konnte in BusPro nicht angelegt werden, BusPro hat nicht geantwortet', ['uuid' => $submission->getUuid()], $e);
|
||||
}
|
||||
|
||||
if (false === $response instanceof RegistrationResponse) {
|
||||
throw new TeamerProvisioningException(sprintf('Die Adresse konnte in BusPro nicht angelegt werden: %s', $this->describe($response)), ['uuid' => $submission->getUuid(), 'bpn_code' => $response->getCode()]);
|
||||
}
|
||||
|
||||
$submission
|
||||
->setBusProAddressId($response->getAddressId())
|
||||
->setBusProPersonId($response->getPersonId())
|
||||
;
|
||||
|
||||
// Immediately, and on its own: from here on a retry must resume rather than create a
|
||||
// second address, whatever the next step does.
|
||||
$this->entityManager->flush();
|
||||
|
||||
$this->logger->info('Create BusPro address for application form submission', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
'bus_pro_address_id' => $response->getAddressId(),
|
||||
'bus_pro_person_id' => $response->getPersonId(),
|
||||
'new_record' => $response->isNewRecord(),
|
||||
]);
|
||||
|
||||
return $response->isNewRecord();
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 2. Sets the teamer selection unconditionally: the write is idempotent, and whether the
|
||||
* address already carried it is not knowable here - Adresse_Neu answers no selections, and
|
||||
* reading them would need the customer's password.
|
||||
*
|
||||
* @throws TeamerProvisioningException
|
||||
*/
|
||||
private function setTeamerSelection(ApplicationFormSubmission $submission): void
|
||||
{
|
||||
$email = (string) $submission->getEmail();
|
||||
$addressId = (int) $submission->getBusProAddressId();
|
||||
$personId = (int) $submission->getBusProPersonId();
|
||||
|
||||
try {
|
||||
$response = $this->apiClient->updateCrmAttribute(
|
||||
$email,
|
||||
$addressId,
|
||||
$personId,
|
||||
$this->teamerSelectionId,
|
||||
true,
|
||||
);
|
||||
} catch (ApiClientException|ResponseParserException $e) {
|
||||
throw new TeamerProvisioningException('Das Teamer-Merkmal konnte in BusPro nicht gesetzt werden, BusPro hat nicht geantwortet', ['uuid' => $submission->getUuid()], $e);
|
||||
}
|
||||
|
||||
if ($response instanceof NotificationResponse) {
|
||||
throw new TeamerProvisioningException(sprintf('Das Teamer-Merkmal konnte in BusPro nicht gesetzt werden: %s', $this->describe($response)), ['uuid' => $submission->getUuid(), 'bpn_code' => $response->getCode()]);
|
||||
}
|
||||
|
||||
if (false === $response->isUpdated()) {
|
||||
throw new TeamerProvisioningException('BusPro hat das Teamer-Merkmal nicht übernommen. Die Adresse wurde angelegt, der Teamer nicht.', ['uuid' => $submission->getUuid(), 'bus_pro_address_id' => $addressId]);
|
||||
}
|
||||
|
||||
$this->logger->info('Set teamer CRM selection', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
'bus_pro_address_id' => $addressId,
|
||||
'bus_pro_person_id' => $personId,
|
||||
'selection_id' => $this->teamerSelectionId,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 3. The local account, built from what was sent plus the ids that came back.
|
||||
*
|
||||
* @return array{user: User, created: bool, alreadyTeamer: bool}
|
||||
*
|
||||
* @throws TeamerProvisioningException
|
||||
*/
|
||||
private function createUser(ApplicationFormSubmission $submission): array
|
||||
{
|
||||
$profileResponse = $this->toProfileResponse($submission);
|
||||
$user = $this->userDataHandler->findLocalUser($profileResponse);
|
||||
|
||||
if (null === $user) {
|
||||
// ROLE_TEAMER needs no approval, which is why it may be granted here at all - see
|
||||
// UserDataHandler for the policy every identity source shares.
|
||||
$user = $this->userDataHandler->createLocalUser($profileResponse, ['ROLE_TEAMER'], isTeamer: true);
|
||||
$this->markProvisioned($submission, $user);
|
||||
|
||||
return ['user' => $user, 'created' => true, 'alreadyTeamer' => false];
|
||||
}
|
||||
|
||||
// A deleted account matched by email: granting it a role would resurrect somebody who
|
||||
// asked to be gone, under their old row. That is a decision for a human, not for a
|
||||
// provisioning click.
|
||||
if (true === $user->isDeleted()) {
|
||||
throw new TeamerProvisioningException('Zu dieser E-Mail-Adresse gehört ein gelöschtes Konto. Der Teamer muss von Hand angelegt werden.', ['uuid' => $submission->getUuid(), 'user_id' => $user->getId()]);
|
||||
}
|
||||
|
||||
$alreadyTeamer = true === $user->hasRole('ROLE_TEAMER') && null !== $user->getTeamer();
|
||||
|
||||
if (false === $alreadyTeamer) {
|
||||
if (null === $user->getTeamer()) {
|
||||
$user->setTeamer(Teamer::fromApiResponse($profileResponse));
|
||||
}
|
||||
|
||||
$this->userDataHandler->grantTeamerRole($user);
|
||||
}
|
||||
|
||||
$this->markProvisioned($submission, $user);
|
||||
|
||||
$this->logger->info('Provision existing local user as teamer', [
|
||||
'uuid' => $submission->getUuid(),
|
||||
'user_id' => $user->getId(),
|
||||
'user_email' => $user->getEmail(),
|
||||
'already_teamer' => $alreadyTeamer,
|
||||
]);
|
||||
|
||||
return ['user' => $user, 'created' => false, 'alreadyTeamer' => $alreadyTeamer];
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 4. BusPro mails the applicant a password, which is what lets them log in here at all -
|
||||
* this application never sets one for a CRM account.
|
||||
*
|
||||
* A failure is reported, not thrown: by now the teamer exists, and the mail can be sent again
|
||||
* from the user's own page. Undoing the three writes over an unsent mail would be worse.
|
||||
*/
|
||||
private function requestPassword(User $user): bool
|
||||
{
|
||||
try {
|
||||
$response = $this->apiClient->resetPassword((string) $user->getEmail());
|
||||
} catch (ApiClientException|ResponseParserException $e) {
|
||||
$this->logger->error('Unable to request the BusPro password mail for a new teamer', [
|
||||
'user_id' => $user->getId(),
|
||||
'user_email' => $user->getEmail(),
|
||||
'error_message' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (false === $response->isSuccessful()) {
|
||||
$this->logger->error('BusPro refused the password mail for a new teamer', [
|
||||
'user_id' => $user->getId(),
|
||||
'user_email' => $user->getEmail(),
|
||||
'bpn_code' => $response->getCode(),
|
||||
'bpn_message' => $response->getMessage(),
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function markProvisioned(ApplicationFormSubmission $submission, User $user): void
|
||||
{
|
||||
$submission
|
||||
->setUser($user)
|
||||
->setTeamerCreatedAt(new \DateTimeImmutable())
|
||||
;
|
||||
|
||||
$this->entityManager->flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* The submission as a profile response, which is the shape UserDataHandler and
|
||||
* Teamer::fromApiResponse() read. Not read back from BusPro on purpose: Adressdaten would
|
||||
* need the customer's password.
|
||||
*
|
||||
* The gender goes in as it is stored - F/M/D is this application's own vocabulary, and the
|
||||
* mapping to BusPro's W happens on the way out, not here.
|
||||
*/
|
||||
private function toProfileResponse(ApplicationFormSubmission $submission): ProfileResponse
|
||||
{
|
||||
$address = new Address();
|
||||
$address
|
||||
->setStreet($submission->getStreet())
|
||||
->setPostCode($submission->getZipCode())
|
||||
->setCity($submission->getCity())
|
||||
;
|
||||
|
||||
$communication = new Communication();
|
||||
$communication
|
||||
->setEmail($submission->getEmail())
|
||||
->setPhone($submission->getPhone())
|
||||
->setMobile($submission->getMobile())
|
||||
;
|
||||
|
||||
$profileResponse = new ProfileResponse();
|
||||
|
||||
return $profileResponse
|
||||
->setAddressId($submission->getBusProAddressId())
|
||||
->setPersonId($submission->getBusProPersonId())
|
||||
->setFirstName($submission->getFirstName())
|
||||
->setName($submission->getLastName())
|
||||
->setGender($submission->getGender())
|
||||
->setDateOfBirth($submission->getDateOfBirth())
|
||||
->setAddress($address)
|
||||
->setCommunication($communication)
|
||||
;
|
||||
}
|
||||
|
||||
private function describe(NotificationResponse $response): string
|
||||
{
|
||||
$message = trim((string) $response->getMessage());
|
||||
|
||||
if ('' === $message) {
|
||||
return sprintf('BusPro hat mit dem Code %s geantwortet', (string) $response->getCode());
|
||||
}
|
||||
|
||||
return sprintf('%s (%s)', $message, (string) $response->getCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service\Teamer;
|
||||
|
||||
/**
|
||||
* Provisioning stopped, with whatever the earlier steps had already done left in place.
|
||||
*
|
||||
* The message is shown to the reviewer as it is, which is why it is one of the few strings in this
|
||||
* application written for a human rather than a log: they are the only audience, and the useful part
|
||||
* is usually BusPro's own complaint about a mandatory field, which no rewording here would improve.
|
||||
* The technical detail goes to the log through getContext().
|
||||
*/
|
||||
class TeamerProvisioningException extends \Exception
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $context
|
||||
*/
|
||||
public function __construct(
|
||||
string $message,
|
||||
private readonly array $context = [],
|
||||
?\Throwable $previous = null,
|
||||
) {
|
||||
parent::__construct($message, 0, $previous);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function getContext(): array
|
||||
{
|
||||
return $this->context;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
{% extends 'admin/layout.html.twig' %}
|
||||
|
||||
{% block title %}Eingegangenes Formular{% endblock %}
|
||||
|
||||
{% macro row(label, value) %}
|
||||
<div class="py-6 first:pt-0 last:pb-0 sm:grid sm:grid-cols-4 sm:gap-4">
|
||||
<dt class="text-sm font-bold leading-6 text-gray-900">
|
||||
{{ label }}
|
||||
</dt>
|
||||
<dd class="mt-1 text-sm leading-6 text-gray-700 sm:col-span-3 sm:mt-0">
|
||||
{% if value is same as(true) %}
|
||||
ja
|
||||
{% elseif value is same as(false) %}
|
||||
nein
|
||||
{% elseif value is empty %}
|
||||
-
|
||||
{% else %}
|
||||
{{ value|nl2br }}
|
||||
{% endif %}
|
||||
</dd>
|
||||
</div>
|
||||
{% endmacro %}
|
||||
|
||||
{% block content %}
|
||||
<div class="flex items-start justify-between pb-8">
|
||||
<h1 class="text-2xl font-bold">
|
||||
{{ submission.formLabel }}
|
||||
{% if submission.lastName or submission.firstName %}
|
||||
- {{ [submission.firstName, submission.lastName]|filter(part => part is not empty)|join(' ') }}
|
||||
{% endif %}
|
||||
</h1>
|
||||
<a href="{{ returnUrl }}" class="btn btn--small btn--secondary">
|
||||
zurück
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="grid lg:grid-cols-2 gap-x-8 gap-y-4 pb-8">
|
||||
<dl class="divide-y divide-gray-100">
|
||||
{{ _self.row('eingegangen am', submission.submittedAt|date('d.m.Y, H:i')) }}
|
||||
{{ _self.row('Name', [submission.firstName, submission.lastName]|filter(part => part is not empty)|join(' ')) }}
|
||||
{{ _self.row('Geburtsdatum', submission.dateOfBirth ? submission.dateOfBirth|date('d.m.Y') : submission.birthDate) }}
|
||||
{{ _self.row('Geschlecht', submission.gender) }}
|
||||
{# Three states: the form said yes, said no, or never asked - and only the first one
|
||||
earns the automatic receipt mail, so "-" is not the same as "nein" here. #}
|
||||
{{ _self.row('EU (inkl. Schweiz)', submission.eu) }}
|
||||
{{ _self.row('E-Mail', submission.email) }}
|
||||
{{ _self.row('Telefon', submission.phone) }}
|
||||
{{ _self.row('Mobil', submission.mobile) }}
|
||||
{{ _self.row('Adresse', [submission.street, [submission.zipCode, submission.city]|filter(part => part is not empty)|join(' ')]|filter(part => part is not empty)|join(', ')) }}
|
||||
</dl>
|
||||
<dl class="divide-y divide-gray-100">
|
||||
{{ _self.row('Formularkennung', submission.form) }}
|
||||
{{ _self.row('Quelle', submission.pageUrl) }}
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
<h2 class="font-bold text-lg pb-4">
|
||||
Bearbeitung
|
||||
</h2>
|
||||
<div class="grid lg:grid-cols-2 gap-x-8 gap-y-8 pb-8">
|
||||
<div>
|
||||
<dl class="divide-y divide-gray-100">
|
||||
{{ _self.row('1. Mail versendet', submission.firstMailSentAt ? submission.firstMailSentAt|date('d.m.Y, H:i') : null) }}
|
||||
{{ _self.row('2. Mail versendet', submission.secondMailSentAt ? submission.secondMailSentAt|date('d.m.Y, H:i') : null) }}
|
||||
</dl>
|
||||
{% if submission.email %}
|
||||
<div class="flex flex-wrap items-center gap-2 pt-4">
|
||||
<button type="button"
|
||||
class="btn btn--small btn--secondary"
|
||||
hx-get="{{ path('app_admin_application_form_submission_send_receipt', { 'uuid': submission.uuid, 'r': forwarded_return_url() }) }}"
|
||||
hx-target="body"
|
||||
hx-swap="beforeend">
|
||||
Eingangsbestätigung erneut senden
|
||||
</button>
|
||||
<button type="button"
|
||||
class="btn btn--small"
|
||||
hx-get="{{ path('app_admin_application_form_submission_send_follow_up', { 'uuid': submission.uuid, 'r': forwarded_return_url() }) }}"
|
||||
hx-target="body"
|
||||
hx-swap="beforeend">
|
||||
{% if submission.secondMailSentAt %}
|
||||
2. Mail erneut senden
|
||||
{% else %}
|
||||
2. Mail senden
|
||||
{% endif %}
|
||||
</button>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="pt-4 text-sm">
|
||||
Dieses Formular enthält keine E-Mail-Adresse - es kann keine Mail versendet werden.
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div>
|
||||
{{ form_start(callsForm) }}
|
||||
<div class="flex flex-col space-y-2 pb-4">
|
||||
{{ form_row(callsForm.firstCallHeld) }}
|
||||
{% if submission.firstCallHeldAt %}
|
||||
<div class="text-sm">geführt am {{ submission.firstCallHeldAt|date('d.m.Y') }}</div>
|
||||
{% endif %}
|
||||
{{ form_row(callsForm.secondCallHeld) }}
|
||||
{% if submission.secondCallHeldAt %}
|
||||
<div class="text-sm">geführt am {{ submission.secondCallHeldAt|date('d.m.Y') }}</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{{ form_widget(callsForm.save, { 'attr': { 'class': 'btn btn--small' } }) }}
|
||||
{{ form_rest(callsForm) }}
|
||||
{{ form_end(callsForm) }}
|
||||
</div>
|
||||
<div>
|
||||
<dl class="divide-y divide-gray-100">
|
||||
{{ _self.row('übernommen am', submission.teamerCreatedAt ? submission.teamerCreatedAt|date('d.m.Y, H:i') : null) }}
|
||||
</dl>
|
||||
<div class="pt-4">
|
||||
{% if submission.user and submission.user.teamer %}
|
||||
<a href="{{ path('app_administrative_teamer_profile', { 'uuid': submission.user.teamer.uuid, 'r': forwarded_return_url() }) }}"
|
||||
class="btn btn--small btn--secondary">
|
||||
Teamer:innenprofil öffnen
|
||||
</a>
|
||||
{% elseif submission.email %}
|
||||
<button type="button"
|
||||
class="btn btn--small"
|
||||
hx-get="{{ path('app_admin_application_form_submission_create_teamer', { 'uuid': submission.uuid, 'r': forwarded_return_url() }) }}"
|
||||
hx-target="body"
|
||||
hx-swap="beforeend">
|
||||
Teamer:in anlegen
|
||||
</button>
|
||||
{% if submission.busProAddressId %}
|
||||
{# Step 1 is done and the rest is not: naming it here is what makes a
|
||||
retry a resume rather than a guess. #}
|
||||
<div class="pt-2 text-sm">
|
||||
Die BusPro-Adresse {{ submission.busProAddressId }} wurde schon angelegt,
|
||||
die Übernahme wurde aber nicht abgeschlossen.
|
||||
</div>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
<div class="text-sm">
|
||||
Ohne E-Mail-Adresse kann kein Teamer:innenkonto angelegt werden.
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2 class="font-bold text-lg pb-4">
|
||||
Angaben aus dem Formular
|
||||
</h2>
|
||||
{% if submission.details is empty %}
|
||||
<p>Das Formular hat über die Stammdaten hinaus nichts erfasst.</p>
|
||||
{% else %}
|
||||
<dl class="divide-y divide-gray-100">
|
||||
{% for label, answer in submission.details %}
|
||||
{{ _self.row(label, answer is iterable ? answer|join(', ') : answer) }}
|
||||
{% endfor %}
|
||||
</dl>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,133 @@
|
||||
{% extends 'admin/layout.html.twig' %}
|
||||
|
||||
{% block title %}Eingegangene Formulare{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="flex items-start justify-between pb-4">
|
||||
<h1 class="text-2xl font-bold">
|
||||
Eingegangene Formulare
|
||||
</h1>
|
||||
<div class="flex flex-col items-end space-y-2 md:flex-row md:items-center md:space-x-2 md:space-y-0">
|
||||
<button type="button"
|
||||
class="{{ html_classes('btn btn--small', { 'btn--secondary': filterDto.active }) }}"
|
||||
title="Filter"
|
||||
hx-get="{{ path('app_common_application_form_submission_filter', { 'r': return_url() }) }}"
|
||||
hx-target="body"
|
||||
hx-swap="beforeend">
|
||||
{{ icon('filter', 'w-4 h-4 shrink-0') }}
|
||||
{% if filterDto.active %}
|
||||
<span class="whitespace-nowrap">{{ filterDto.activeFiltersCount }} Filter aktiv</span>
|
||||
{% else %}
|
||||
<span>Filter</span>
|
||||
{% endif %}
|
||||
</button>
|
||||
{% if filterDto.active %}
|
||||
<a href="{{ path('app_common_application_form_submission_filter_reset') }}"
|
||||
class="btn btn--small btn--secondary">
|
||||
Reset
|
||||
</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="data-table-wrapper">
|
||||
<div class="data-table-wrapper__inner">
|
||||
<table class="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>
|
||||
{{ knp_pagination_sortable(pagination, 'Name', 'submission.lastName') }}
|
||||
</th>
|
||||
<th>
|
||||
{{ knp_pagination_sortable(pagination, 'E-Mail', 'submission.email') }}
|
||||
</th>
|
||||
<th>
|
||||
{{ knp_pagination_sortable(pagination, 'Formular', 'submission.formLabel') }}
|
||||
</th>
|
||||
<th>
|
||||
{{ knp_pagination_sortable(pagination, 'eingegangen', 'submission.submittedAt') }}
|
||||
</th>
|
||||
<th>
|
||||
{{ knp_pagination_sortable(pagination, '1. Mail', 'submission.firstMailSentAt') }}
|
||||
</th>
|
||||
<th>
|
||||
{{ knp_pagination_sortable(pagination, '2. Mail', 'submission.secondMailSentAt') }}
|
||||
</th>
|
||||
<th>
|
||||
{{ knp_pagination_sortable(pagination, '1. Call', 'submission.firstCallHeldAt') }}
|
||||
</th>
|
||||
<th>
|
||||
{{ knp_pagination_sortable(pagination, '2. Call', 'submission.secondCallHeldAt') }}
|
||||
</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for submission in pagination %}
|
||||
<tr>
|
||||
<td>
|
||||
<a href="{{ path('app_admin_application_form_submission_detail', { 'uuid': submission.uuid, 'r': return_url() }) }}">
|
||||
{% if submission.lastName or submission.firstName %}
|
||||
{{ [submission.lastName, submission.firstName]|filter(part => part is not empty)|join(', ') }}
|
||||
{% else %}
|
||||
ohne Namen
|
||||
{% endif %}
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
{% if submission.email %}
|
||||
<a href="mailto:{{ submission.email }}">{{ submission.email }}</a>
|
||||
{% else %}
|
||||
-
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
{{ submission.formLabel }}
|
||||
</td>
|
||||
<td class="whitespace-nowrap">
|
||||
{{ submission.submittedAt|date('d.m.Y, H:i') }}
|
||||
</td>
|
||||
<td class="whitespace-nowrap">
|
||||
{{ submission.firstMailSentAt ? submission.firstMailSentAt|date('d.m.Y, H:i') : '-' }}
|
||||
</td>
|
||||
<td class="whitespace-nowrap">
|
||||
{{ submission.secondMailSentAt ? submission.secondMailSentAt|date('d.m.Y, H:i') : '-' }}
|
||||
</td>
|
||||
<td class="whitespace-nowrap">
|
||||
{{ submission.firstCallHeldAt ? submission.firstCallHeldAt|date('d.m.Y') : '-' }}
|
||||
</td>
|
||||
<td class="whitespace-nowrap">
|
||||
{{ submission.secondCallHeldAt ? submission.secondCallHeldAt|date('d.m.Y') : '-' }}
|
||||
</td>
|
||||
<td>
|
||||
<twig:DropDown>
|
||||
<a href="{{ path('app_admin_application_form_submission_detail', { 'uuid': submission.uuid, 'r': return_url() }) }}"
|
||||
class="text-gray-700 hover:text-primary block px-4 py-2 text-sm"
|
||||
role="menuitem"
|
||||
tabindex="-1">
|
||||
Details
|
||||
</a>
|
||||
<button type="button"
|
||||
class="text-red-500 hover:text-primary block px-4 py-2 text-sm w-full text-left"
|
||||
role="menuitem"
|
||||
tabindex="-1"
|
||||
hx-get="{{ path('app_admin_application_form_submission_delete', { 'uuid': submission.uuid, 'r': return_url() }) }}"
|
||||
hx-target="body"
|
||||
hx-swap="beforeend">
|
||||
löschen
|
||||
</button>
|
||||
</twig:DropDown>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="9">
|
||||
Keine Daten...
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{{ knp_pagination_render(pagination) }}
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,49 @@
|
||||
{% extends 'htmx_confirmation_modal.html.twig' %}
|
||||
|
||||
{% block title %}Teamer:in anlegen{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<em>{{ [submission.firstName, submission.lastName]|filter(part => part is not empty)|join(' ') }}</em>
|
||||
als Teamer:in übernehmen?
|
||||
<div class="pt-2 text-sm">
|
||||
Dabei wird in BusPro eine Adresse angelegt und das Teamer-Merkmal gesetzt. Kennt BusPro
|
||||
die Person schon, wird die vorhandene Adresse verwendet. Anschließend entsteht hier das
|
||||
Teamer:innenkonto, und BusPro schickt eine Mail zum Setzen des Passworts.
|
||||
</div>
|
||||
{# The three writes cannot be undone from here, so what goes to BusPro is shown before it
|
||||
goes, not afterwards in a log entry nobody reads. #}
|
||||
<dl class="pt-4 text-sm grid grid-cols-3 gap-y-1">
|
||||
<dt class="font-bold">Geburtsdatum</dt>
|
||||
<dd class="col-span-2">
|
||||
{% if submission.dateOfBirth %}
|
||||
{{ submission.dateOfBirth|date('d.m.Y') }}
|
||||
{% else %}
|
||||
<strong>fehlt</strong> - ohne Geburtsdatum kann keine Adresse angelegt werden
|
||||
{% endif %}
|
||||
</dd>
|
||||
<dt class="font-bold">Geschlecht</dt>
|
||||
<dd class="col-span-2">{{ submission.gender }}</dd>
|
||||
<dt class="font-bold">E-Mail</dt>
|
||||
<dd class="col-span-2">{{ submission.email ?: 'fehlt' }}</dd>
|
||||
<dt class="font-bold">Adresse</dt>
|
||||
<dd class="col-span-2">
|
||||
{# Street and postcode are mandatory in BusPro, so step 1 fails without them. Said
|
||||
here, before the write, rather than only in the error message afterwards. #}
|
||||
{% if submission.street is empty or submission.zipCode is empty or submission.city is empty %}
|
||||
<strong>unvollständig</strong> - ohne Straße, PLZ und Ort kann BusPro keine Adresse anlegen
|
||||
{% else %}
|
||||
{{ [submission.street, [submission.zipCode, submission.city]|filter(part => part is not empty)|join(' ')]|filter(part => part is not empty)|join(', ') }}
|
||||
{% endif %}
|
||||
</dd>
|
||||
</dl>
|
||||
{% if submission.busProAddressId %}
|
||||
<div class="pt-4 text-sm">
|
||||
In BusPro besteht für diese Bewerbung schon die Adresse
|
||||
{{ submission.busProAddressId }} - sie wird nicht erneut angelegt.
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block button_confirm %}Anlegen{% endblock %}
|
||||
@@ -0,0 +1,14 @@
|
||||
{% extends 'htmx_confirmation_modal.html.twig' %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
Möchtest du das Formular <em>{{ submission.formLabel }}</em>
|
||||
{% if submission.lastName or submission.firstName %}
|
||||
von <em>{{ [submission.firstName, submission.lastName]|filter(part => part is not empty)|join(' ') }}</em>
|
||||
{% endif %}
|
||||
vom {{ submission.submittedAt|date('d.m.Y, H:i') }} wirklich löschen?
|
||||
<div class="pt-2 text-sm">
|
||||
Die Daten werden endgültig entfernt und können nicht wiederhergestellt werden.
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,21 @@
|
||||
{% extends 'htmx_confirmation_modal.html.twig' %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
Zweite E-Mail an <em>{{ submission.email }}</em> versenden?
|
||||
<div class="pt-2 text-sm">
|
||||
{% if handout %}
|
||||
Anhang: {{ handout.displayName ?: handout.originalFilename }}
|
||||
{% else %}
|
||||
{# The wording promises a handout, so its absence has to be visible before sending. #}
|
||||
<strong>Kein Handout hinterlegt</strong> - die Mail geht ohne Anhang raus.
|
||||
Ein Dokument erhält die Verwendung in der Dokumentenverwaltung.
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if submission.secondMailSentAt %}
|
||||
<div class="pt-2 text-sm">
|
||||
Zuletzt versendet am {{ submission.secondMailSentAt|date('d.m.Y, H:i') }} - das Datum wird überschrieben.
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,12 @@
|
||||
{% extends 'htmx_confirmation_modal.html.twig' %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
Eingangsbestätigung erneut an <em>{{ submission.email }}</em> versenden?
|
||||
{% if submission.firstMailSentAt %}
|
||||
<div class="pt-2 text-sm">
|
||||
Zuletzt versendet am {{ submission.firstMailSentAt|date('d.m.Y, H:i') }} - das Datum wird überschrieben.
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -14,6 +14,9 @@
|
||||
<th>
|
||||
{{ knp_pagination_sortable(pagination, 'Dateiname', 'upload.originalFilename') }}
|
||||
</th>
|
||||
<th>
|
||||
Verwendung
|
||||
</th>
|
||||
<th>
|
||||
Dateigröße
|
||||
</th>
|
||||
@@ -32,6 +35,11 @@
|
||||
<td>
|
||||
{{ document.displayName ? document.displayName : document.originalFilename }}
|
||||
</td>
|
||||
<td>
|
||||
{# A slot belongs to exactly one document, so this is what tells staff
|
||||
which file a feature actually picks up. #}
|
||||
{{ document.token ? document.token.label() : '-' }}
|
||||
</td>
|
||||
<td>
|
||||
{{ document.size|file_size }}
|
||||
</td>
|
||||
@@ -71,7 +79,7 @@
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="5">
|
||||
<td colspan="6">
|
||||
Keine Daten...
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
{% extends 'htmx_modal.html.twig' %}
|
||||
|
||||
{% block title %}Dokument umbenennen{% endblock %}
|
||||
{% block title %}Dokument bearbeiten{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{{ form_start(form, { 'attr': { 'hx-post': app.request.uri, 'hx-target': '#htmx-modal', 'hx-swap': 'outerHTML' } }) }}
|
||||
<div class="pb-4">
|
||||
<div class="flex flex-col space-y-2 pb-4">
|
||||
{{ form_row(form.displayName) }}
|
||||
{{ form_row(form.token) }}
|
||||
</div>
|
||||
<button type="submit" class="btn">
|
||||
aktualisieren
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
{% extends 'htmx_modal.html.twig' %}
|
||||
|
||||
{% block title %}Eingegangene Formulare filtern{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{{ form_start(filterForm, { 'attr': { 'hx-post': app.request.uri, 'hx-target': '#htmx-modal', 'hx-swap': 'outerHTML' } }) }}
|
||||
<div class="flex flex-col space-y-2 pb-4">
|
||||
{{ form_row(filterForm.name) }}
|
||||
{{ form_row(filterForm.dateFrom) }}
|
||||
{{ form_row(filterForm.dateTo) }}
|
||||
</div>
|
||||
<div class="flex items-center space-x-2">
|
||||
{{ form_widget(filterForm.apply, { 'attr': { 'class': 'btn' } }) }}
|
||||
{{ form_widget(filterForm.reset, { 'attr': { 'class': 'btn btn--secondary' } }) }}
|
||||
</div>
|
||||
{{ form_rest(filterForm) }}
|
||||
{{ form_end(filterForm) }}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,7 @@
|
||||
{# Like generic.html.twig, but without the layout's closing "Zum Portal" button: these mails go
|
||||
to someone who filled in a form on one of the public websites and has no account here, so a
|
||||
link to a login they cannot pass is worse than no link at all. Same block-emptying trick as
|
||||
email/datev_invoice.html.twig. #}
|
||||
{% extends 'email/generic.html.twig' %}
|
||||
|
||||
{% block button %}{% endblock %}
|
||||
@@ -9,6 +9,7 @@ use App\BusProNet\Model\Hotel;
|
||||
use App\BusProNet\Model\Pickup;
|
||||
use App\BusProNet\Model\ProfileResponse;
|
||||
use App\BusProNet\Model\ProfileUpdateResponse;
|
||||
use App\BusProNet\Model\RegistrationResponse;
|
||||
use App\BusProNet\ResponseParser;
|
||||
use App\BusProNet\ResponseParserException;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
@@ -238,6 +239,63 @@ class ResponseParserTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The write answers idadresse + idperson + änderung, not a selection tree - the shape
|
||||
* createProfileUpdateResponse() reads. It used to be routed to the CRM attribute parser, which
|
||||
* would have returned an empty response with every role flag false
|
||||
* (.ddev/plans/buspro-crm-selection-write.md).
|
||||
*/
|
||||
public function testParseCrmSelectionWriteResponse(): void
|
||||
{
|
||||
$content = '<?xml version="1.0" encoding="utf-8"?><ergebnis><satz typ="KUNDENKONTO"></satz><art>SelektionCRM_Ändern</art><idadresse>141747</idadresse><idperson>224526</idperson><änderung>True</änderung></ergebnis>';
|
||||
|
||||
$response = $this->getParserInstance()->parseXmlString(ApiClient::TYPE_CUSTOMER_DATA, $content);
|
||||
|
||||
$this->assertInstanceOf(ProfileUpdateResponse::class, $response);
|
||||
$this->assertSame(141747, $response->getAddressId());
|
||||
$this->assertSame(224526, $response->getPersonId());
|
||||
$this->assertTrue($response->isUpdated());
|
||||
}
|
||||
|
||||
public function testParseNewAddressResponse(): void
|
||||
{
|
||||
$content = '<?xml version="1.0" encoding="utf-8"?><ergebnis><satz typ="KUNDENKONTO"></satz><art>Adresse_Neu</art><idadresse>141747</idadresse><idperson>224526</idperson><neuanlage>True</neuanlage></ergebnis>';
|
||||
|
||||
$response = $this->getParserInstance()->parseXmlString(ApiClient::TYPE_CUSTOMER_DATA, $content);
|
||||
|
||||
$this->assertInstanceOf(RegistrationResponse::class, $response);
|
||||
$this->assertSame(141747, $response->getAddressId());
|
||||
$this->assertSame(224526, $response->getPersonId());
|
||||
$this->assertTrue($response->isNewRecord());
|
||||
}
|
||||
|
||||
/**
|
||||
* BusPro recognised the person and answered with the ids of the address it already held. Not a
|
||||
* failure and not a duplicate - provisioning carries on with those ids.
|
||||
*/
|
||||
public function testParseNewAddressResponseForAnExistingPerson(): void
|
||||
{
|
||||
$content = '<?xml version="1.0" encoding="utf-8"?><ergebnis><satz typ="KUNDENKONTO"></satz><art>Adresse_Neu</art><idadresse>141747</idadresse><idperson>224526</idperson><neuanlage>False</neuanlage></ergebnis>';
|
||||
|
||||
$response = $this->getParserInstance()->parseXmlString(ApiClient::TYPE_CUSTOMER_DATA, $content);
|
||||
|
||||
$this->assertInstanceOf(RegistrationResponse::class, $response);
|
||||
$this->assertFalse($response->isNewRecord());
|
||||
}
|
||||
|
||||
/**
|
||||
* Without both ids there is nothing to provision with, and a silent 0 would be stored on the
|
||||
* account and never match again.
|
||||
*/
|
||||
public function testParseNewAddressResponseWithoutIdsFails(): void
|
||||
{
|
||||
$content = '<?xml version="1.0" encoding="utf-8"?><ergebnis><satz typ="KUNDENKONTO"></satz><art>Adresse_Neu</art><neuanlage>True</neuanlage></ergebnis>';
|
||||
|
||||
$this->expectException(ResponseParserException::class);
|
||||
|
||||
$this->getParserInstance()->parseXmlString(ApiClient::TYPE_CUSTOMER_DATA, $content);
|
||||
}
|
||||
|
||||
private function loadFixture(string $filename): string
|
||||
{
|
||||
return file_get_contents(__DIR__.'/../Resources/'.$filename);
|
||||
|
||||
@@ -70,4 +70,35 @@ class SeasonCalendarTest extends TestCase
|
||||
|
||||
(new SeasonCalendar('xx-yy', '04-01'))->seasonYearFor(new \DateTimeImmutable('2025-01-01'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider provideUpcomingSeasonDates
|
||||
*/
|
||||
public function testTheCurrentOrUpcomingSeasonYear(string $date, int $expected): void
|
||||
{
|
||||
$calendar = new SeasonCalendar('11-01', '04-01');
|
||||
|
||||
$this->assertSame($expected, $calendar->currentOrUpcomingSeasonYear(new \DateTimeImmutable($date)));
|
||||
}
|
||||
|
||||
public static function provideUpcomingSeasonDates(): iterable
|
||||
{
|
||||
// Between two seasons: the winter ahead, which is what a recruiting mail means.
|
||||
yield 'September, before the season starts' => ['2026-09-24', 2026];
|
||||
yield 'the day the season starts' => ['2026-11-01', 2026];
|
||||
// Inside a season: that season, not the next one.
|
||||
yield 'December, mid season' => ['2026-12-15', 2026];
|
||||
yield 'the last day of the season' => ['2027-04-01', 2026];
|
||||
// After a season ended, so the next one to start.
|
||||
yield 'May, after the season ended' => ['2027-05-02', 2027];
|
||||
}
|
||||
|
||||
public function testTheShortLabelIsTheTwoDigitSpan(): void
|
||||
{
|
||||
$calendar = new SeasonCalendar('11-01', '04-01');
|
||||
|
||||
$this->assertSame('26/27', $calendar->shortLabel(2026));
|
||||
// The turn of the century has to stay two digits on both ends.
|
||||
$this->assertSame('99/00', $calendar->shortLabel(1999));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Controller\Admin\ApplicationFormSubmission;
|
||||
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use App\Entity\User;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
|
||||
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Everything around the provisioning click that can be exercised without writing to BusPro.
|
||||
*
|
||||
* The write itself cannot: the teamer CRM selection is only changeable in the production database
|
||||
* (.ddev/plans/buspro-crm-selection-write.md), and a POST that gets as far as the api client would
|
||||
* open a socket to it from a test. TeamerProvisionerTest covers the flow against a mocked client;
|
||||
* what is left here is the route, the confirmation and the one POST that is safe to make - a
|
||||
* submission TeamerProvisioner refuses before it sends anything.
|
||||
*/
|
||||
class CreateTeamerControllerTest extends WebTestCase
|
||||
{
|
||||
private KernelBrowser $client;
|
||||
|
||||
private EntityManagerInterface $entityManager;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->client = static::createClient(server: ['HTTPS' => true]);
|
||||
$this->entityManager = self::getContainer()->get(EntityManagerInterface::class);
|
||||
|
||||
$this->entityManager->createQuery(sprintf('DELETE FROM %s', ApplicationFormSubmission::class))->execute();
|
||||
$this->entityManager->createQuery(sprintf('DELETE FROM %s', User::class))->execute();
|
||||
|
||||
$this->client->loginUser($this->reviewer());
|
||||
}
|
||||
|
||||
public function testTheDetailPageOffersTheProvisioningButton(): void
|
||||
{
|
||||
$submission = $this->submission();
|
||||
|
||||
$crawler = $this->client->request(
|
||||
'GET',
|
||||
sprintf('/admin/application-form-submission/detail/%s', $submission->getUuid()),
|
||||
['r' => rawurlencode('/admin/application-form-submission')]
|
||||
);
|
||||
|
||||
$this->assertSame(Response::HTTP_OK, $this->client->getResponse()->getStatusCode());
|
||||
|
||||
$button = $crawler->filter('button[hx-get*="create-teamer"]');
|
||||
|
||||
$this->assertCount(1, $button);
|
||||
// Like every other action on that page: it hands on the return url it was given, so "zurück"
|
||||
// keeps pointing at the list.
|
||||
$this->assertStringContainsString('r='.rawurlencode('/admin/application-form-submission'), (string) $button->attr('hx-get'));
|
||||
}
|
||||
|
||||
/**
|
||||
* The three writes cannot be undone from here, so the confirmation names what goes to BusPro
|
||||
* rather than asking "are you sure".
|
||||
*/
|
||||
public function testTheConfirmationNamesWhatGoesToBusPro(): void
|
||||
{
|
||||
$crawler = $this->client->request('GET', $this->url($this->submission()));
|
||||
|
||||
$this->assertSame(Response::HTTP_OK, $this->client->getResponse()->getStatusCode());
|
||||
|
||||
$modal = $crawler->filter('#htmx-confirmation-modal')->text();
|
||||
|
||||
$this->assertStringContainsString('Anna Muster', $modal);
|
||||
$this->assertStringContainsString('01.01.1990', $modal);
|
||||
$this->assertStringContainsString('Musterstraße 1, 10115 Berlin', $modal);
|
||||
}
|
||||
|
||||
/**
|
||||
* A row from before the tightened endpoint contract. The confirmation says so before the
|
||||
* reviewer clicks, because BusPro would answer the same thing only after the attempt.
|
||||
*/
|
||||
public function testTheConfirmationFlagsAnIncompleteSubmission(): void
|
||||
{
|
||||
$crawler = $this->client->request('GET', $this->url($this->incompleteSubmission()));
|
||||
|
||||
$modal = $crawler->filter('#htmx-confirmation-modal')->text();
|
||||
|
||||
$this->assertStringContainsString('ohne Geburtsdatum', $modal);
|
||||
$this->assertStringContainsString('ohne Straße, PLZ und Ort', $modal);
|
||||
}
|
||||
|
||||
/**
|
||||
* The only POST a test may make: TeamerProvisioner refuses an unprovisionable submission before
|
||||
* it touches the api client, so nothing here reaches BusPro. It covers what the reviewer
|
||||
* actually sees when provisioning fails - the refusal's own wording, not "es ist ein Fehler
|
||||
* aufgetreten".
|
||||
*/
|
||||
public function testAnUnprovisionableSubmissionFailsWithoutWritingAnything(): void
|
||||
{
|
||||
$submission = $this->incompleteSubmission();
|
||||
|
||||
$this->client->request('POST', $this->url($submission));
|
||||
|
||||
$response = $this->client->getResponse();
|
||||
|
||||
$this->assertSame(Response::HTTP_OK, $response->getStatusCode());
|
||||
$this->assertStringContainsString('detail', (string) $response->headers->get('HX-Redirect'));
|
||||
|
||||
$flashes = $this->client->getRequest()->getSession()->getFlashBag()->peekAll();
|
||||
|
||||
$this->assertArrayHasKey('error', $flashes);
|
||||
$this->assertStringContainsString('Geburtsdatum', $flashes['error'][0]);
|
||||
|
||||
$this->entityManager->clear();
|
||||
$stored = $this->entityManager->getRepository(ApplicationFormSubmission::class)->find($submission->getId());
|
||||
|
||||
$this->assertNotNull($stored);
|
||||
$this->assertFalse($stored->isProvisioned());
|
||||
$this->assertNull($stored->getBusProAddressId());
|
||||
$this->assertNull($stored->getUser());
|
||||
}
|
||||
|
||||
private function url(ApplicationFormSubmission $submission): string
|
||||
{
|
||||
return sprintf('/admin/application-form-submission/create-teamer/%s', $submission->getUuid());
|
||||
}
|
||||
|
||||
private function submission(): ApplicationFormSubmission
|
||||
{
|
||||
return $this->persist(
|
||||
$this->newSubmission()
|
||||
->setBirthDate('1990-01-01')
|
||||
->setStreet('Musterstraße 1')
|
||||
->setZipCode('10115')
|
||||
->setCity('Berlin')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything the contract now requires, missing - which only a row stored before it can be.
|
||||
*/
|
||||
private function incompleteSubmission(): ApplicationFormSubmission
|
||||
{
|
||||
return $this->persist($this->newSubmission()->setBirthDate('01.01.1990'));
|
||||
}
|
||||
|
||||
private function newSubmission(): ApplicationFormSubmission
|
||||
{
|
||||
return (new ApplicationFormSubmission(
|
||||
'applicationform',
|
||||
'Bewerbungsformular',
|
||||
new \DateTimeImmutable('2026-09-22T12:30:00+02:00'),
|
||||
'F'
|
||||
))
|
||||
->setFirstName('Anna')
|
||||
->setLastName('Muster')
|
||||
->setEmail('[email protected]')
|
||||
;
|
||||
}
|
||||
|
||||
private function persist(ApplicationFormSubmission $submission): ApplicationFormSubmission
|
||||
{
|
||||
$this->entityManager->persist($submission);
|
||||
$this->entityManager->flush();
|
||||
|
||||
return $submission;
|
||||
}
|
||||
|
||||
private function reviewer(): User
|
||||
{
|
||||
$user = (new User())
|
||||
->setFirstName('Rita')
|
||||
->setLastName('Reviewer')
|
||||
->setEmail('[email protected]')
|
||||
->setRoles(['ROLE_TEAM_ADMIN'])
|
||||
->setBusProAddressId(1)
|
||||
->setBusProPersonId(1)
|
||||
;
|
||||
|
||||
$this->entityManager->persist($user);
|
||||
$this->entityManager->flush();
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Controller\Admin\ApplicationFormSubmission;
|
||||
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use App\Entity\User;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
|
||||
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* The return url of a detail page's own actions.
|
||||
*
|
||||
* Every action on this page has to hand on the "r" it was given, not the url of the page it sits
|
||||
* on: return_url() encodes the current request, so a send button would send the reviewer back to
|
||||
* the detail page they are already looking at - and because the send controller redirects with
|
||||
* that same "r", "zurück" then points at the detail page itself and appears to do nothing, one
|
||||
* nesting level deeper per click. forwarded_return_url() is what keeps pointing at the list.
|
||||
*/
|
||||
class DetailControllerTest extends WebTestCase
|
||||
{
|
||||
private const LIST_URL = '/admin/application-form-submission';
|
||||
|
||||
private KernelBrowser $client;
|
||||
|
||||
private EntityManagerInterface $entityManager;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->client = static::createClient(server: ['HTTPS' => true]);
|
||||
$this->entityManager = self::getContainer()->get(EntityManagerInterface::class);
|
||||
|
||||
$this->entityManager->createQuery(sprintf('DELETE FROM %s', ApplicationFormSubmission::class))->execute();
|
||||
$this->entityManager->createQuery(sprintf('DELETE FROM %s', User::class))->execute();
|
||||
|
||||
$this->client->loginUser($this->reviewer());
|
||||
}
|
||||
|
||||
public function testTheActionsCarryTheReturnUrlTheyWereGivenOn(): void
|
||||
{
|
||||
$submission = $this->submission();
|
||||
$crawler = $this->client->request(
|
||||
'GET',
|
||||
sprintf('/admin/application-form-submission/detail/%s', $submission->getUuid()),
|
||||
['r' => rawurlencode(self::LIST_URL)]
|
||||
);
|
||||
|
||||
$this->assertSame(Response::HTTP_OK, $this->client->getResponse()->getStatusCode());
|
||||
|
||||
// "zurück" goes where the reviewer came from.
|
||||
$this->assertSame(self::LIST_URL, $crawler->filter('a.btn')->first()->attr('href'));
|
||||
|
||||
foreach (['send-receipt', 'send-follow-up'] as $action) {
|
||||
$button = $crawler->filter(sprintf('button[hx-get*="%s"]', $action));
|
||||
|
||||
$this->assertCount(1, $button, sprintf('The %s button is missing', $action));
|
||||
|
||||
$url = $button->attr('hx-get');
|
||||
|
||||
$this->assertStringContainsString('r='.rawurlencode(self::LIST_URL), $url);
|
||||
// The bug: the detail url itself as the return url, which "zurück" then loops on.
|
||||
$this->assertStringNotContainsString('detail', urldecode(substr($url, (int) strpos($url, 'r='))));
|
||||
}
|
||||
}
|
||||
|
||||
public function testWithoutAReturnUrlTheActionsCarryNone(): void
|
||||
{
|
||||
$submission = $this->submission();
|
||||
$crawler = $this->client->request(
|
||||
'GET',
|
||||
sprintf('/admin/application-form-submission/detail/%s', $submission->getUuid())
|
||||
);
|
||||
|
||||
$this->assertSame(Response::HTTP_OK, $this->client->getResponse()->getStatusCode());
|
||||
// Dropped rather than emitted empty, so the controllers fall back to the list route.
|
||||
$this->assertStringNotContainsString('r=', $crawler->filter('button[hx-get*="send-receipt"]')->attr('hx-get'));
|
||||
$this->assertSame(self::LIST_URL, $crawler->filter('a.btn')->first()->attr('href'));
|
||||
}
|
||||
|
||||
private function submission(): ApplicationFormSubmission
|
||||
{
|
||||
$submission = (new ApplicationFormSubmission(
|
||||
'applicationform',
|
||||
'Bewerbungsformular',
|
||||
new \DateTimeImmutable('2026-09-22T12:30:00+02:00'),
|
||||
'F'
|
||||
))->setEmail('[email protected]');
|
||||
|
||||
$this->entityManager->persist($submission);
|
||||
$this->entityManager->flush();
|
||||
|
||||
return $submission;
|
||||
}
|
||||
|
||||
private function reviewer(): User
|
||||
{
|
||||
$user = (new User())
|
||||
->setFirstName('Rita')
|
||||
->setLastName('Reviewer')
|
||||
->setEmail('[email protected]')
|
||||
->setRoles(['ROLE_TEAM_ADMIN'])
|
||||
->setBusProAddressId(1)
|
||||
->setBusProPersonId(1)
|
||||
;
|
||||
|
||||
$this->entityManager->persist($user);
|
||||
$this->entityManager->flush();
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,655 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Controller\Api;
|
||||
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use App\Repository\ApplicationFormSubmissionRepository;
|
||||
use App\Security\AccessToken\ApiKeyExtractor;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
|
||||
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* The cases here are the ones the TYPO3 side actually produces
|
||||
* (.ddev/plans/MYEP-APPLICATION-ENDPOINT.md §8): labels with slashes and umlauts, a long textarea
|
||||
* answer, a duplicate label, and a mapped key this application does not know - which must not be a
|
||||
* 400, or a later mapping change on the website silently stops every submission of that form.
|
||||
*
|
||||
* The other half is the required nine of the contract: every payload carries lastName, firstName,
|
||||
* birthDate, email, gender, eu, street, zipCode and city, and every one of them is a 400 when it is
|
||||
* missing. That is
|
||||
* deliberately harsh - a 400 costs a whole application - and each rejection case is pinned here
|
||||
* one field at a time, because these are the fields a teamer cannot be provisioned without
|
||||
* (.ddev/plans/application-form-teamer-provisioning.md).
|
||||
*/
|
||||
class ApplicationFormControllerTest extends WebTestCase
|
||||
{
|
||||
private const URL = '/api/application-forms';
|
||||
|
||||
private const KEY = 'test-application-form-api-key';
|
||||
|
||||
private KernelBrowser $client;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
// access_control requires https for every path, so an http request is a 301 here
|
||||
$this->client = static::createClient(server: ['HTTPS' => true]);
|
||||
|
||||
$this->entityManager()->createQuery(
|
||||
sprintf('DELETE FROM %s', ApplicationFormSubmission::class)
|
||||
)->execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* The endpoint promises JSON out, and on the error path that is not decoration: the TYPO3
|
||||
* finisher logs the response body, and Symfony's error renderer would answer an HTML error page
|
||||
* here - one that names the offending field only in dev, inside an HTML comment, and not at all
|
||||
* in production. See ApiExceptionListener.
|
||||
*/
|
||||
public function testARejectionIsJsonNamingTheField(): void
|
||||
{
|
||||
$payload = $this->payload();
|
||||
unset($payload['birthDate']);
|
||||
|
||||
$this->post($payload);
|
||||
|
||||
$response = $this->client->getResponse();
|
||||
|
||||
$this->assertSame(Response::HTTP_BAD_REQUEST, $response->getStatusCode());
|
||||
$this->assertStringContainsString('application/json', (string) $response->headers->get('Content-Type'));
|
||||
$this->assertStringNotContainsString('<html', (string) $response->getContent());
|
||||
|
||||
$body = $this->decode();
|
||||
|
||||
$this->assertSame('error', $body['status']);
|
||||
$this->assertSame(
|
||||
[['field' => 'birthDate', 'message' => 'birthDate must not be empty.', 'received' => 'missing']],
|
||||
$body['errors']
|
||||
);
|
||||
// One line for a caller that logs the message alone.
|
||||
$this->assertSame('birthDate must not be empty.', $body['message']);
|
||||
}
|
||||
|
||||
/**
|
||||
* The shape of what arrived, which the framework never says: "This value should be of type
|
||||
* null|string." names the expectation and leaves the sender guessing. A form engine that hands a
|
||||
* date element straight to json_encode sends an object, and its keys are the whole diagnosis.
|
||||
*
|
||||
* Never the value itself - a rejected payload is still personal data.
|
||||
*
|
||||
* @dataProvider unusableBirthDateTypes
|
||||
*/
|
||||
public function testARejectionNamesTheShapeThatArrived(mixed $birthDate, string $received): void
|
||||
{
|
||||
$this->post(['birthDate' => $birthDate] + $this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_BAD_REQUEST, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame(
|
||||
[['field' => 'birthDate', 'message' => 'This value should be of type null|string.', 'received' => $received]],
|
||||
$this->decode()['errors']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return iterable<string, array{mixed, string}>
|
||||
*/
|
||||
public static function unusableBirthDateTypes(): iterable
|
||||
{
|
||||
yield 'a serialized date object' => [
|
||||
['date' => '1990-01-01 00:00:00.000000', 'timezone_type' => 3, 'timezone' => 'Europe/Berlin'],
|
||||
'object with keys: date, timezone_type, timezone',
|
||||
];
|
||||
yield 'a list' => [['1990-01-01'], 'list of 1'];
|
||||
yield 'a number' => [19900101, 'int'];
|
||||
yield 'a boolean' => [true, 'bool'];
|
||||
}
|
||||
|
||||
/**
|
||||
* The endpoint's errors are English (the only caller is a machine), but a constraint message this
|
||||
* application does not phrase itself is translated by the validator - and this application's
|
||||
* locale is German. The message is therefore rebuilt from its own template rather than read off
|
||||
* the violation.
|
||||
*/
|
||||
public function testAFrameworkMessageIsNotTranslated(): void
|
||||
{
|
||||
$this->post(['birthDate' => 19900101] + $this->payload());
|
||||
|
||||
$content = (string) $this->client->getResponse()->getContent();
|
||||
|
||||
$this->assertStringContainsString('This value should be of type null|string.', $content);
|
||||
$this->assertStringNotContainsString('Dieser Wert', $content);
|
||||
}
|
||||
|
||||
public function testAnEmptyValueIsDistinguishedFromAnAbsentOne(): void
|
||||
{
|
||||
$this->post(['city' => ''] + $this->payload());
|
||||
|
||||
$this->assertSame('empty string', $this->decode()['errors'][0]['received']);
|
||||
}
|
||||
|
||||
public function testEveryOffendingFieldIsNamed(): void
|
||||
{
|
||||
$payload = $this->payload();
|
||||
unset($payload['street'], $payload['zipCode'], $payload['city']);
|
||||
|
||||
$this->post($payload);
|
||||
|
||||
$this->assertEqualsCanonicalizing(['street', 'zipCode', 'city'], $this->rejectedFields());
|
||||
}
|
||||
|
||||
/**
|
||||
* A malformed body has no field to name, so the resolver's own explanation is passed on rather
|
||||
* than swallowed - still JSON, still readable in a log.
|
||||
*/
|
||||
public function testABrokenBodyIsRejectedAsJson(): void
|
||||
{
|
||||
$this->client->request(
|
||||
'POST',
|
||||
self::URL,
|
||||
server: ['CONTENT_TYPE' => 'application/json', 'HTTP_'.strtoupper(str_replace('-', '_', ApiKeyExtractor::HEADER)) => self::KEY],
|
||||
content: '{"form": "applicationform",'
|
||||
);
|
||||
|
||||
$body = $this->decode();
|
||||
|
||||
$this->assertSame(Response::HTTP_BAD_REQUEST, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame([], $body['errors']);
|
||||
$this->assertNotSame('', $body['message']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Not only the validation path: a wrong method comes from the router and used to leave as HTML
|
||||
* too.
|
||||
*/
|
||||
public function testAWrongMethodIsJsonToo(): void
|
||||
{
|
||||
$this->client->request('GET', self::URL, server: [
|
||||
'HTTP_'.strtoupper(str_replace('-', '_', ApiKeyExtractor::HEADER)) => self::KEY,
|
||||
]);
|
||||
|
||||
$this->assertSame(Response::HTTP_METHOD_NOT_ALLOWED, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame('error', $this->decode()['status']);
|
||||
}
|
||||
|
||||
public function testAKeylessRequestIsRejected(): void
|
||||
{
|
||||
$this->post(['form' => 'applicationform'], key: null);
|
||||
|
||||
$this->assertSame(Response::HTTP_UNAUTHORIZED, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame(0, $this->countSubmissions());
|
||||
$this->assertSame('error', $this->decode()['status']);
|
||||
}
|
||||
|
||||
/**
|
||||
* A wrong key is answered by the firewall's entry point, which stops the exception before
|
||||
* ApiExceptionListener sees it: the body stays empty. Pinned because "empty" is the thing to
|
||||
* recognise in a caller's log - it is not the HTML error page a rejected payload used to get,
|
||||
* and it is not something this application can phrase without an entry point of its own.
|
||||
*/
|
||||
public function testAWrongKeyIsRejected(): void
|
||||
{
|
||||
$this->post(['form' => 'applicationform'], key: 'not-the-key');
|
||||
|
||||
$response = $this->client->getResponse();
|
||||
|
||||
$this->assertSame(Response::HTTP_UNAUTHORIZED, $response->getStatusCode());
|
||||
$this->assertStringNotContainsString('<html', (string) $response->getContent());
|
||||
}
|
||||
|
||||
public function testAFullSubmissionIsStored(): void
|
||||
{
|
||||
$this->post([
|
||||
'form' => 'applicationform',
|
||||
'formLabel' => 'Bewerbungsformular',
|
||||
'submittedAt' => '2026-09-22T12:30:00+02:00',
|
||||
'pageUid' => 1421,
|
||||
'pageUrl' => 'https://www.ep-reisen.de/jobs/bewerbung',
|
||||
'firstName' => 'Anna',
|
||||
'lastName' => 'Muster',
|
||||
'email' => '[email protected]',
|
||||
'phone' => '+49 30 1234567',
|
||||
'mobile' => '+49 170 1234567',
|
||||
'birthDate' => '1990-01-01',
|
||||
'gender' => 'F',
|
||||
'eu' => true,
|
||||
'street' => 'Musterstraße 1',
|
||||
'zipCode' => '10115',
|
||||
'city' => 'Berlin',
|
||||
'details' => [
|
||||
'Nationalität' => 'deutsch',
|
||||
'Ausbildung/Studium' => 'Tourismusmanagement',
|
||||
'Bewerbung als' => ['Reiseleitung', 'Skilehrer'],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertSame(Response::HTTP_ACCEPTED, $this->client->getResponse()->getStatusCode());
|
||||
|
||||
$submission = $this->lastSubmission();
|
||||
|
||||
$this->assertSame('applicationform', $submission->getForm());
|
||||
$this->assertSame('Bewerbungsformular', $submission->getFormLabel());
|
||||
$this->assertSame('2026-09-22T12:30:00+02:00', $submission->getSubmittedAt()->format(\DateTimeInterface::ATOM));
|
||||
$this->assertSame(1421, $submission->getPageUid());
|
||||
$this->assertSame('1990-01-01', $submission->getBirthDate());
|
||||
$this->assertSame('1990-01-01', $submission->getDateOfBirth()?->format('Y-m-d'));
|
||||
$this->assertSame('F', $submission->getGender());
|
||||
$this->assertSame('[email protected]', $submission->getEmail(), 'the address is normalized like everywhere else');
|
||||
$this->assertSame(['Reiseleitung', 'Skilehrer'], $submission->getDetails()['Bewerbung als']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Beyond the required nine everything stays optional: a form is configured without a mobile
|
||||
* number as often as with it, and the teamer fills those in themselves afterwards. An absent
|
||||
* optional key means the form has no such field - never an empty value that failed validation.
|
||||
*/
|
||||
public function testTheRequiredFieldsAloneAreEnough(): void
|
||||
{
|
||||
$this->post($this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_ACCEPTED, $this->client->getResponse()->getStatusCode());
|
||||
|
||||
$submission = $this->lastSubmission();
|
||||
|
||||
$this->assertNull($submission->getPhone());
|
||||
$this->assertNull($submission->getMobile());
|
||||
$this->assertSame([], $submission->getDetails());
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider requiredFields
|
||||
*/
|
||||
public function testAPayloadMissingARequiredFieldIsRejected(string $field): void
|
||||
{
|
||||
$payload = $this->payload();
|
||||
unset($payload[$field]);
|
||||
|
||||
$this->post($payload);
|
||||
|
||||
$this->assertSame(Response::HTTP_BAD_REQUEST, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame(0, $this->countSubmissions());
|
||||
// The whole point of the rejection: the caller logs this body and has to see the field.
|
||||
$this->assertContains($field, $this->rejectedFields());
|
||||
}
|
||||
|
||||
/**
|
||||
* An empty string is the shape a form posts for a field the visitor left blank, and it is as
|
||||
* unusable as an absent key - except for eu, where "" is a lawful no and has its own case.
|
||||
*
|
||||
* @dataProvider requiredFields
|
||||
*/
|
||||
public function testAPayloadWithAnEmptyRequiredFieldIsRejected(string $field): void
|
||||
{
|
||||
if ('eu' === $field) {
|
||||
$this->markTestSkipped('An empty eu is a no, not a missing answer - see its own test');
|
||||
}
|
||||
|
||||
$this->post([$field => ''] + $this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_BAD_REQUEST, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame(0, $this->countSubmissions());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return iterable<string, array{string}>
|
||||
*/
|
||||
public static function requiredFields(): iterable
|
||||
{
|
||||
yield 'form' => ['form'];
|
||||
yield 'formLabel' => ['formLabel'];
|
||||
yield 'submittedAt' => ['submittedAt'];
|
||||
yield 'firstName' => ['firstName'];
|
||||
yield 'lastName' => ['lastName'];
|
||||
yield 'email' => ['email'];
|
||||
yield 'birthDate' => ['birthDate'];
|
||||
yield 'gender' => ['gender'];
|
||||
yield 'eu' => ['eu'];
|
||||
yield 'street' => ['street'];
|
||||
yield 'zipCode' => ['zipCode'];
|
||||
yield 'city' => ['city'];
|
||||
}
|
||||
|
||||
/**
|
||||
* The one field whose format is nailed down: provisioning parses it as a date, so the day the
|
||||
* TYPO3 side switches a form back to a free-text birthday has to be a 400 here rather than a
|
||||
* failure in front of a reviewer weeks later.
|
||||
*
|
||||
* @dataProvider unusableBirthDates
|
||||
*/
|
||||
public function testAnUnusableBirthDateIsRejected(string $birthDate): void
|
||||
{
|
||||
$this->post(['birthDate' => $birthDate] + $this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_BAD_REQUEST, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame(0, $this->countSubmissions());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return iterable<string, array{string}>
|
||||
*/
|
||||
public static function unusableBirthDates(): iterable
|
||||
{
|
||||
yield 'the German spelling the forms used before the contract' => ['01.01.1990'];
|
||||
yield 'free text' => ['irgendwann 1990'];
|
||||
yield 'a day that does not exist' => ['1990-02-31'];
|
||||
yield 'a year alone' => ['1990'];
|
||||
}
|
||||
|
||||
public function testAnUnknownGenderIsRejected(): void
|
||||
{
|
||||
$this->post(['gender' => 'weiblich'] + $this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_BAD_REQUEST, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame(0, $this->countSubmissions());
|
||||
}
|
||||
|
||||
/**
|
||||
* D is passed through to BusPro as it is - what BusPro makes of it is unverified, and guessing
|
||||
* a replacement here would be worse than finding out.
|
||||
*/
|
||||
public function testEveryGenderTheApplicationKnowsIsAccepted(): void
|
||||
{
|
||||
foreach (['F', 'M', 'D'] as $gender) {
|
||||
$this->post(['gender' => $gender] + $this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_ACCEPTED, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame($gender, $this->lastSubmission()->getGender());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The mapped vocabulary grows on the website side without a release here. An unknown key is
|
||||
* ignored, and kept in the raw payload so it can be mapped later without losing the answers
|
||||
* that arrived in the meantime.
|
||||
*/
|
||||
public function testAnUnknownMappedKeyIsIgnoredAndKept(): void
|
||||
{
|
||||
$this->post(['nationality' => 'deutsch'] + $this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_ACCEPTED, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame('deutsch', $this->lastSubmission()->getPayload()['nationality']);
|
||||
}
|
||||
|
||||
/**
|
||||
* A duplicate label is disambiguated by the identifier on the TYPO3 side, so both answers
|
||||
* survive as separate keys (§3.3). The order is MySQL's, not the form's - a json column
|
||||
* sorts an object's keys by length - so only the set of labels is pinned here.
|
||||
*/
|
||||
public function testEveryLabelSurvivesIncludingADisambiguatedDuplicate(): void
|
||||
{
|
||||
$details = [
|
||||
'Nationalität' => 'deutsch',
|
||||
'Führerschein' => 'ja',
|
||||
'Einsatz datum' => 'ab 20.12.2026',
|
||||
'Geburtsdatum' => '01.01.1990',
|
||||
'Geburtsdatum (text-10)' => '02.02.1992',
|
||||
];
|
||||
|
||||
$this->post(['details' => $details] + $this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_ACCEPTED, $this->client->getResponse()->getStatusCode());
|
||||
|
||||
$stored = $this->lastSubmission()->getDetails();
|
||||
|
||||
$this->assertEqualsCanonicalizing(array_keys($details), array_keys($stored));
|
||||
$this->assertSame('01.01.1990', $stored['Geburtsdatum']);
|
||||
$this->assertSame('02.02.1992', $stored['Geburtsdatum (text-10)']);
|
||||
}
|
||||
|
||||
public function testALongAnswerIsStored(): void
|
||||
{
|
||||
$answer = str_repeat('ä', 3000);
|
||||
|
||||
$this->post(['details' => ['Warum ich' => $answer]] + $this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_ACCEPTED, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame($answer, $this->lastSubmission()->getDetails()['Warum ich']);
|
||||
}
|
||||
|
||||
public function testAPayloadWithoutPageInformationIsAccepted(): void
|
||||
{
|
||||
$this->post(['details' => ['Nationalität' => 'deutsch']] + $this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_ACCEPTED, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertNull($this->lastSubmission()->getPageUid());
|
||||
$this->assertNull($this->lastSubmission()->getPageUrl());
|
||||
}
|
||||
|
||||
/**
|
||||
* pageUid arrives as a JSON number today. A numeric string is pinned here because the
|
||||
* distinction is invisible in a form editor and nobody would notice it becoming a 400.
|
||||
*/
|
||||
public function testANumericStringPageUidIsAccepted(): void
|
||||
{
|
||||
$this->post(['pageUid' => '1421'] + $this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_ACCEPTED, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame(1421, $this->lastSubmission()->getPageUid());
|
||||
}
|
||||
|
||||
public function testABodyWithoutAJsonContentTypeIsRejected(): void
|
||||
{
|
||||
$this->client->request(
|
||||
'POST',
|
||||
self::URL,
|
||||
server: ['HTTP_'.strtoupper(str_replace('-', '_', ApiKeyExtractor::HEADER)) => self::KEY],
|
||||
content: json_encode($this->payload(), JSON_THROW_ON_ERROR)
|
||||
);
|
||||
|
||||
$this->assertSame(0, $this->countSubmissions());
|
||||
// Pinned because it is what the TYPO3 side has to be told: the resolver needs the
|
||||
// header to read the body as JSON at all, and answers 400 without it.
|
||||
$this->assertSame(Response::HTTP_BAD_REQUEST, $this->client->getResponse()->getStatusCode());
|
||||
}
|
||||
|
||||
public function testABrokenBodyIsRejected(): void
|
||||
{
|
||||
$this->client->request(
|
||||
'POST',
|
||||
self::URL,
|
||||
server: ['CONTENT_TYPE' => 'application/json', 'HTTP_'.strtoupper(str_replace('-', '_', ApiKeyExtractor::HEADER)) => self::KEY],
|
||||
content: '{"form": "applicationform",'
|
||||
);
|
||||
|
||||
$this->assertSame(Response::HTTP_BAD_REQUEST, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame(0, $this->countSubmissions());
|
||||
}
|
||||
|
||||
public function testAnUnparseableSubmissionTimeIsRejected(): void
|
||||
{
|
||||
$this->post(['submittedAt' => 'gestern'] + $this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_BAD_REQUEST, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame(0, $this->countSubmissions());
|
||||
}
|
||||
|
||||
public function testAnInvalidEmailAddressIsRejected(): void
|
||||
{
|
||||
$this->post(['email' => 'not-an-address'] + $this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_BAD_REQUEST, $this->client->getResponse()->getStatusCode());
|
||||
}
|
||||
|
||||
public function testANestedDetailValueIsRejected(): void
|
||||
{
|
||||
$this->post(['details' => ['Bewerbung als' => ['erste' => ['Reiseleitung']]]] + $this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_BAD_REQUEST, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame(0, $this->countSubmissions());
|
||||
}
|
||||
|
||||
public function testTheEndpointOnlyAnswersPost(): void
|
||||
{
|
||||
$this->client->request('GET', self::URL, server: [
|
||||
'HTTP_'.strtoupper(str_replace('-', '_', ApiKeyExtractor::HEADER)) => self::KEY,
|
||||
]);
|
||||
|
||||
$this->assertSame(Response::HTTP_METHOD_NOT_ALLOWED, $this->client->getResponse()->getStatusCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* §5.1 is not implemented yet: a double-clicked submit button stores two rows for now, and
|
||||
* this pins that it is a known state rather than an accident.
|
||||
*/
|
||||
public function testTheSamePayloadTwiceIsStoredTwiceForNow(): void
|
||||
{
|
||||
$payload = $this->payload();
|
||||
|
||||
$this->post($payload);
|
||||
$this->post($payload);
|
||||
|
||||
$this->assertSame(Response::HTTP_ACCEPTED, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame(2, $this->countSubmissions());
|
||||
}
|
||||
|
||||
/**
|
||||
* The receipt mail only goes out for an applicant the form reported as EU (incl. Switzerland).
|
||||
* Everything else - "no", and a form that never asks - is silence, so an unmapped field can
|
||||
* never mail someone by accident.
|
||||
*/
|
||||
public function testTheReceiptGoesOutForAnEuApplicant(): void
|
||||
{
|
||||
$this->post($this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_ACCEPTED, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertEmailCount(1);
|
||||
$this->assertNotNull($this->lastSubmission()->getFirstMailSentAt());
|
||||
$this->assertTrue($this->lastSubmission()->isEu());
|
||||
}
|
||||
|
||||
public function testNoReceiptForANonEuApplicant(): void
|
||||
{
|
||||
$this->post(['eu' => false] + $this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_ACCEPTED, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertEmailCount(0);
|
||||
$this->assertNull($this->lastSubmission()->getFirstMailSentAt());
|
||||
$this->assertFalse($this->lastSubmission()->isEu());
|
||||
}
|
||||
|
||||
/**
|
||||
* A form posts "1" as readily as a JSON true, and dropping an application over the spelling
|
||||
* would be absurd - the same tolerance pageUid has.
|
||||
*/
|
||||
public function testAQuotedEuFlagStillEarnsTheReceipt(): void
|
||||
{
|
||||
$this->post(['eu' => '1'] + $this->payload());
|
||||
|
||||
$this->assertEmailCount(1);
|
||||
$this->assertTrue($this->lastSubmission()->isEu());
|
||||
}
|
||||
|
||||
public function testAnEmptyEuFlagIsNotAYes(): void
|
||||
{
|
||||
$this->post(['eu' => ''] + $this->payload());
|
||||
|
||||
$this->assertEmailCount(0);
|
||||
$this->assertFalse($this->lastSubmission()->isEu());
|
||||
}
|
||||
|
||||
/**
|
||||
* Not a silent null: a mapping that quietly stopped every receipt mail is worse than a 400
|
||||
* the TYPO3 side logs.
|
||||
*/
|
||||
public function testAnUnparseableEuFlagIsRejected(): void
|
||||
{
|
||||
$this->post(['eu' => 'vielleicht'] + $this->payload());
|
||||
|
||||
$this->assertSame(Response::HTTP_BAD_REQUEST, $this->client->getResponse()->getStatusCode());
|
||||
$this->assertSame(0, $this->countSubmissions());
|
||||
$this->assertEmailCount(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* A payload with nothing but the required six, which is the smallest thing the endpoint
|
||||
* accepts. Spread an override in front of it - ['gender' => 'X'] + $this->payload() - rather
|
||||
* than rebuilding it, so a field added to the contract reaches every case at once.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function payload(): array
|
||||
{
|
||||
return [
|
||||
'form' => 'applicationform',
|
||||
'formLabel' => 'Bewerbungsformular',
|
||||
'submittedAt' => '2026-09-22T12:30:00+02:00',
|
||||
'firstName' => 'Anna',
|
||||
'lastName' => 'Muster',
|
||||
'email' => '[email protected]',
|
||||
'birthDate' => '1990-01-01',
|
||||
'gender' => 'F',
|
||||
'eu' => true,
|
||||
// The postal address, required as a whole: street and postcode are BusPro's own
|
||||
// mandatory fields for a new address.
|
||||
'street' => 'Musterstraße 1',
|
||||
'zipCode' => '10115',
|
||||
'city' => 'Berlin',
|
||||
'details' => [],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The fields the endpoint named as the reason for a rejection.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private function rejectedFields(): array
|
||||
{
|
||||
return array_values(array_filter(array_column($this->decode()['errors'], 'field')));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function decode(): array
|
||||
{
|
||||
$body = json_decode((string) $this->client->getResponse()->getContent(), true);
|
||||
|
||||
$this->assertIsArray($body, 'The endpoint has to answer JSON, on the error path as well');
|
||||
|
||||
return $body;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
private function post(array $payload, ?string $key = self::KEY): void
|
||||
{
|
||||
$server = ['CONTENT_TYPE' => 'application/json'];
|
||||
|
||||
if (null !== $key) {
|
||||
$server['HTTP_'.strtoupper(str_replace('-', '_', ApiKeyExtractor::HEADER))] = $key;
|
||||
}
|
||||
|
||||
$this->client->request('POST', self::URL, server: $server, content: json_encode($payload, JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
private function lastSubmission(): ApplicationFormSubmission
|
||||
{
|
||||
$this->entityManager()->clear();
|
||||
|
||||
/** @var ApplicationFormSubmissionRepository $repository */
|
||||
$repository = $this->entityManager()->getRepository(ApplicationFormSubmission::class);
|
||||
|
||||
$submission = $repository->findOneBy([], ['id' => 'DESC']);
|
||||
|
||||
$this->assertInstanceOf(ApplicationFormSubmission::class, $submission);
|
||||
|
||||
return $submission;
|
||||
}
|
||||
|
||||
private function countSubmissions(): int
|
||||
{
|
||||
return (int) $this->entityManager()
|
||||
->createQuery(sprintf('SELECT COUNT(s.id) FROM %s s', ApplicationFormSubmission::class))
|
||||
->getSingleScalarResult()
|
||||
;
|
||||
}
|
||||
|
||||
private function entityManager(): EntityManagerInterface
|
||||
{
|
||||
return static::getContainer()->get(EntityManagerInterface::class);
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,29 @@ use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
|
||||
*/
|
||||
class EmailTextMailRenderingTest extends KernelTestCase
|
||||
{
|
||||
/**
|
||||
* The mails that go to someone without an account here, and are therefore sent through the
|
||||
* template that empties the layout's closing "Zum Portal" button. Kept next to the assertion
|
||||
* that every other mail *has* that button, so adding a third such mail is a decision rather
|
||||
* than an accident.
|
||||
*
|
||||
* @var list<EmailTextKey>
|
||||
*/
|
||||
/**
|
||||
* Stands in for APPLICATION_FORM_BOOKING_URL. Unlike the other placeholders this one is not
|
||||
* caller-supplied - it reaches the body from configuration, before the Markdown is parsed -
|
||||
* so the assertions below look for the URL itself rather than a "[name]" marker.
|
||||
*/
|
||||
private const BOOKING_URL = 'https://bookings.example.test/team-infocall';
|
||||
|
||||
/**
|
||||
* @var list<EmailTextKey>
|
||||
*/
|
||||
private const NO_PORTAL_BUTTON = [
|
||||
EmailTextKey::APPLICATION_FORM_RECEIVED,
|
||||
EmailTextKey::APPLICATION_FORM_FOLLOW_UP,
|
||||
];
|
||||
|
||||
/**
|
||||
* @dataProvider provideKeys
|
||||
*/
|
||||
@@ -43,15 +66,22 @@ class EmailTextMailRenderingTest extends KernelTestCase
|
||||
$repository = $this->createMock(EmailTextRepository::class);
|
||||
$repository->method('findByKey')->willReturn(null);
|
||||
|
||||
$text = (new EmailTextRenderer($catalog, $repository, $container->get(MailBodyRenderer::class)))
|
||||
->render($key, $placeholders)
|
||||
;
|
||||
$text = (new EmailTextRenderer(
|
||||
$catalog,
|
||||
$repository,
|
||||
$container->get(MailBodyRenderer::class),
|
||||
self::BOOKING_URL
|
||||
))->render($key, $placeholders);
|
||||
|
||||
$withoutButton = in_array($key, self::NO_PORTAL_BUTTON, true);
|
||||
|
||||
$email = $container->get(Mailer::class)->create(['text' => $text], [
|
||||
'from' => '[email protected]',
|
||||
'to' => '[email protected]',
|
||||
'subject' => $text->subject,
|
||||
'template' => 'email/generic.html.twig',
|
||||
'template' => $withoutButton
|
||||
? 'email/generic_no_button.html.twig'
|
||||
: 'email/generic.html.twig',
|
||||
'subject_parameters' => [],
|
||||
'attachments' => [],
|
||||
'transport' => null,
|
||||
@@ -62,15 +92,30 @@ class EmailTextMailRenderingTest extends KernelTestCase
|
||||
|
||||
$this->assertNotEmpty($html);
|
||||
$this->assertStringContainsString($text->headline, $html);
|
||||
// The layout closes every mail with the same button, pointing at the site root
|
||||
// rather than a deep link so that a client's link preview cannot trip the
|
||||
// unauthorized-access logging.
|
||||
$this->assertStringContainsString('class="button">Zum Portal</a>', $html);
|
||||
if (true === $withoutButton) {
|
||||
// The recipient filled in a form on a public website and has no account here, so a
|
||||
// link to a login they cannot pass would be worse than no link.
|
||||
$this->assertStringNotContainsString('Zum Portal', $html);
|
||||
} else {
|
||||
// The layout closes every mail with the same button, pointing at the site root
|
||||
// rather than a deep link so that a client's link preview cannot trip the
|
||||
// unauthorized-access logging.
|
||||
$this->assertStringContainsString('class="button">Zum Portal</a>', $html);
|
||||
}
|
||||
|
||||
$this->assertStringNotContainsString('/teamer/disposition/detail', $html);
|
||||
|
||||
// Every placeholder the mail declares has to reach the rendered body, or the
|
||||
// wording lost a detail somewhere between catalogue and template.
|
||||
foreach ($definition->getPlaceholderNames() as $name) {
|
||||
if ('bookingUrl' === $name) {
|
||||
// Configured, not passed in, and substituted before parsing - so it has to have
|
||||
// become a real link target rather than a percent-encoded token.
|
||||
$this->assertStringContainsString('href="'.self::BOOKING_URL.'"', $html);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->assertStringContainsString(
|
||||
'['.$name.']',
|
||||
$html.$email->getSubject(),
|
||||
@@ -79,6 +124,68 @@ class EmailTextMailRenderingTest extends KernelTestCase
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The follow-up mail is the one piece of delivered wording that leans on Markdown escaping:
|
||||
* "Saisonmitarbeiter\*in" has a single asterisk, which CommonMark reads as emphasis unless it
|
||||
* is escaped. Getting that wrong does not fail anything - it silently italicises a stretch of
|
||||
* the mail - so it is pinned here.
|
||||
*/
|
||||
public function testTheFollowUpSurvivesItsMarkdown(): void
|
||||
{
|
||||
$html = $this->renderBody(EmailTextKey::APPLICATION_FORM_FOLLOW_UP);
|
||||
|
||||
$this->assertStringContainsString('Saisonmitarbeiter*in', $html);
|
||||
$this->assertStringNotContainsString('<em>in', $html);
|
||||
// The call dates are written as a list and the two parts as headings.
|
||||
$this->assertStringContainsString('<ul>', $html);
|
||||
$this->assertStringContainsString('Wochenteam', $html);
|
||||
$this->assertStringContainsString('Saisonpersonal', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* An unconfigured booking URL must stop the mail, not render <a href=""> and invite an
|
||||
* applicant to book a call they cannot reach. The endpoint turns this into a logged error and
|
||||
* still answers the submission; a reviewer sending by hand sees it.
|
||||
*/
|
||||
public function testAnUnconfiguredBookingUrlRefusesToRender(): void
|
||||
{
|
||||
self::bootKernel();
|
||||
|
||||
$container = self::getContainer();
|
||||
$repository = $this->createMock(EmailTextRepository::class);
|
||||
$repository->method('findByKey')->willReturn(null);
|
||||
|
||||
$renderer = new EmailTextRenderer(
|
||||
$container->get(EmailTextCatalog::class),
|
||||
$repository,
|
||||
$container->get(MailBodyRenderer::class),
|
||||
''
|
||||
);
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessage('APPLICATION_FORM_BOOKING_URL is not configured');
|
||||
|
||||
$renderer->render(EmailTextKey::APPLICATION_FORM_RECEIVED, []);
|
||||
}
|
||||
|
||||
private function renderBody(EmailTextKey $key): string
|
||||
{
|
||||
self::bootKernel();
|
||||
|
||||
$container = self::getContainer();
|
||||
$repository = $this->createMock(EmailTextRepository::class);
|
||||
$repository->method('findByKey')->willReturn(null);
|
||||
|
||||
$text = (new EmailTextRenderer(
|
||||
$container->get(EmailTextCatalog::class),
|
||||
$repository,
|
||||
$container->get(MailBodyRenderer::class),
|
||||
self::BOOKING_URL
|
||||
))->render($key, []);
|
||||
|
||||
return $text->bodyHtml;
|
||||
}
|
||||
|
||||
public static function provideKeys(): iterable
|
||||
{
|
||||
foreach (EmailTextKey::cases() as $key) {
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Entity;
|
||||
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* The payload a submission goes to BusPro as, asserted directly - in the spirit of
|
||||
* AssignmentTypeTest pinning a form type's choice list. It is the one part of provisioning that
|
||||
* cannot be rehearsed against the test database at all (the teamer selection is only changeable in
|
||||
* production), so the keys and the gender mapping are pinned here rather than discovered live.
|
||||
*/
|
||||
class ApplicationFormSubmissionTest extends TestCase
|
||||
{
|
||||
public function testThePayloadCarriesTheGermanKeysBusProExpects(): void
|
||||
{
|
||||
$payload = $this->submission()->toPayload();
|
||||
|
||||
$this->assertSame([
|
||||
'geburtsdatum' => '01.01.1990',
|
||||
'geschlecht' => 'W',
|
||||
'vorname' => 'Anna',
|
||||
'name' => 'Muster',
|
||||
'anschrift' => [
|
||||
'strasse' => 'Musterstraße 1',
|
||||
'plz' => '10115',
|
||||
'ort' => 'Berlin',
|
||||
],
|
||||
'kommunikation' => [
|
||||
'email' => '[email protected]',
|
||||
'telefonmobil' => '+49 170 1234567',
|
||||
'telefonprivat' => '+49 30 1234567',
|
||||
],
|
||||
], $payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* F becomes W, exactly as in Teamer::toPayload(). What BusPro makes of "D" is unverified, so it
|
||||
* is passed through rather than guessed at - the mapping must not invent a value here.
|
||||
*/
|
||||
public function testTheGenderMappingIsTheOneTeamerUses(): void
|
||||
{
|
||||
$this->assertSame('W', $this->submission('F')->toPayload()['geschlecht']);
|
||||
$this->assertSame('M', $this->submission('M')->toPayload()['geschlecht']);
|
||||
$this->assertSame('D', $this->submission('D')->toPayload()['geschlecht']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Only a row that predates the contract gets here - street and postcode are required of every
|
||||
* payload now. The keys still go out empty rather than absent, because BusPro is told what it
|
||||
* asked for and answers with its own Pflichtfeld error rather than a parse failure.
|
||||
*/
|
||||
public function testAnAbsentAddressLeavesTheKeysEmptyRatherThanAbsent(): void
|
||||
{
|
||||
$payload = (new ApplicationFormSubmission(
|
||||
'applicationform',
|
||||
'Bewerbungsformular',
|
||||
new \DateTimeImmutable('2026-09-22T12:30:00+02:00'),
|
||||
'M',
|
||||
))->toPayload();
|
||||
|
||||
$this->assertSame(['strasse' => null, 'plz' => null, 'ort' => null], $payload['anschrift']);
|
||||
}
|
||||
|
||||
public function testTheBirthDateIsParsedStrictly(): void
|
||||
{
|
||||
$this->assertSame('1990-01-01', $this->submission()->getDateOfBirth()?->format('Y-m-d'));
|
||||
// What a row from before the contract looks like: stored, displayed, but not a date.
|
||||
$this->assertNull($this->submission(birthDate: '01.01.1990')->getDateOfBirth());
|
||||
$this->assertNull($this->submission(birthDate: 'irgendwann')->getDateOfBirth());
|
||||
$this->assertNull($this->submission(birthDate: '1990-02-31')->getDateOfBirth());
|
||||
$this->assertNull($this->submission(birthDate: null)->getDateOfBirth());
|
||||
}
|
||||
|
||||
/**
|
||||
* The time of day is zeroed rather than "now", or two runs of the same submission would produce
|
||||
* two different dates of birth.
|
||||
*/
|
||||
public function testTheBirthDateHasNoTimeOfDay(): void
|
||||
{
|
||||
$this->assertSame('00:00:00', $this->submission()->getDateOfBirth()?->format('H:i:s'));
|
||||
}
|
||||
|
||||
public function testProvisioningStateStartsEmpty(): void
|
||||
{
|
||||
$submission = $this->submission();
|
||||
|
||||
$this->assertFalse($submission->hasBusProAddress());
|
||||
$this->assertFalse($submission->isProvisioned());
|
||||
|
||||
$submission->setBusProAddressId(141747);
|
||||
|
||||
// Both ids or nothing: the selection write needs the person id as well.
|
||||
$this->assertFalse($submission->hasBusProAddress());
|
||||
|
||||
$submission->setBusProPersonId(224526);
|
||||
|
||||
$this->assertTrue($submission->hasBusProAddress());
|
||||
}
|
||||
|
||||
private function submission(string $gender = 'F', ?string $birthDate = '1990-01-01'): ApplicationFormSubmission
|
||||
{
|
||||
return (new ApplicationFormSubmission(
|
||||
'applicationform',
|
||||
'Bewerbungsformular',
|
||||
new \DateTimeImmutable('2026-09-22T12:30:00+02:00'),
|
||||
$gender,
|
||||
))
|
||||
->setFirstName('Anna')
|
||||
->setLastName('Muster')
|
||||
->setEmail('[email protected]')
|
||||
->setPhone('+49 30 1234567')
|
||||
->setMobile('+49 170 1234567')
|
||||
->setBirthDate($birthDate)
|
||||
->setStreet('Musterstraße 1')
|
||||
->setZipCode('10115')
|
||||
->setCity('Berlin')
|
||||
;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Logging;
|
||||
|
||||
use App\Logging\InjectUserProcessor;
|
||||
use Monolog\Level;
|
||||
use Monolog\LogRecord;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
use Symfony\Component\Security\Core\User\InMemoryUser;
|
||||
|
||||
/**
|
||||
* The processor runs on every channel, so it sees whatever user the firewall of the request
|
||||
* authenticated - including the in-memory user the stateless "api" firewall resolves its shared
|
||||
* key to, which has no getId() and no getEmail(). That cost a stored submission a 500 once.
|
||||
*
|
||||
* Every case here passes a web SAPI: with "cli" the processor returns the system record before
|
||||
* reaching any of this, which is exactly why no functional test caught the bug.
|
||||
*/
|
||||
class InjectUserProcessorTest extends TestCase
|
||||
{
|
||||
public function testAnApiFirewallUserIsLoggedByItsIdentifier(): void
|
||||
{
|
||||
$record = $this->process(new InMemoryUser('api', null, ['ROLE_API']));
|
||||
|
||||
$this->assertSame(
|
||||
['id' => null, 'username' => 'api', 'roles' => ['ROLE_API']],
|
||||
$record->extra['user']
|
||||
);
|
||||
}
|
||||
|
||||
public function testAnAnonymousRequestIsLoggedAsSystem(): void
|
||||
{
|
||||
$record = $this->process(null);
|
||||
|
||||
$this->assertSame('system', $record->extra['user']['username']);
|
||||
}
|
||||
|
||||
public function testTheConsoleIsLoggedAsSystemEvenWithAUser(): void
|
||||
{
|
||||
$record = $this->process(new InMemoryUser('api', null, ['ROLE_API']), sapi: 'cli');
|
||||
|
||||
$this->assertSame('system', $record->extra['user']['username']);
|
||||
}
|
||||
|
||||
public function testAnAlreadyResolvedUserIsLeftAlone(): void
|
||||
{
|
||||
$security = $this->createMock(Security::class);
|
||||
$security->expects($this->never())->method('getUser');
|
||||
|
||||
$processor = new InjectUserProcessor($security, 'fpm-fcgi');
|
||||
$record = $processor(self::record(['user' => ['username' => 'kept']]));
|
||||
|
||||
$this->assertSame(['username' => 'kept'], $record->extra['user']);
|
||||
}
|
||||
|
||||
private function process(?InMemoryUser $user, string $sapi = 'fpm-fcgi'): LogRecord
|
||||
{
|
||||
$security = $this->createMock(Security::class);
|
||||
$security->method('getUser')->willReturn($user);
|
||||
|
||||
$processor = new InjectUserProcessor($security, $sapi);
|
||||
|
||||
return $processor(self::record());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $extra
|
||||
*/
|
||||
private static function record(array $extra = []): LogRecord
|
||||
{
|
||||
return new LogRecord(
|
||||
new \DateTimeImmutable(),
|
||||
'api',
|
||||
Level::Info,
|
||||
'Application form submission received',
|
||||
[],
|
||||
$extra
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Logging;
|
||||
|
||||
use App\Logging\UserDataProcessor;
|
||||
use Monolog\Level;
|
||||
use Monolog\LogRecord;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
use Symfony\Component\Security\Core\User\InMemoryUser;
|
||||
|
||||
/**
|
||||
* Same hazard as InjectUserProcessorTest: this one feeds the log table through
|
||||
* App\Logging\DatabaseHandler, and it is registered globally with #[AsMonologProcessor], so a
|
||||
* request on the stateless "api" firewall reaches it with an in-memory user that has no getId().
|
||||
*/
|
||||
class UserDataProcessorTest extends TestCase
|
||||
{
|
||||
public function testAnApiFirewallUserGetsNoIdInsteadOfAnError(): void
|
||||
{
|
||||
$security = $this->createMock(Security::class);
|
||||
$security->method('getUser')->willReturn(new InMemoryUser('api', null, ['ROLE_API']));
|
||||
$security->method('getToken')->willReturn(null);
|
||||
|
||||
$processor = new UserDataProcessor($security, 'fpm-fcgi');
|
||||
|
||||
$record = $processor(new LogRecord(
|
||||
new \DateTimeImmutable(),
|
||||
'api',
|
||||
Level::Info,
|
||||
'Application form submission received'
|
||||
));
|
||||
|
||||
$this->assertSame(
|
||||
['id' => null, 'username' => 'api', 'roles' => ['ROLE_API']],
|
||||
$record->extra['user']
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Model;
|
||||
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use App\Model\ApplicationFormSubmissionCallsDto;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class ApplicationFormSubmissionCallsDtoTest extends TestCase
|
||||
{
|
||||
public function testTickingABoxStampsToday(): void
|
||||
{
|
||||
$submission = $this->submission();
|
||||
|
||||
$dto = new ApplicationFormSubmissionCallsDto($submission);
|
||||
$dto->setFirstCallHeld(true)->applyToSubmission();
|
||||
|
||||
$this->assertSame(
|
||||
(new \DateTimeImmutable('today'))->format('Y-m-d'),
|
||||
$submission->getFirstCallHeldAt()?->format('Y-m-d')
|
||||
);
|
||||
$this->assertNull($submission->getSecondCallHeldAt());
|
||||
}
|
||||
|
||||
/**
|
||||
* The reason the DTO exists: saving the form again must not move a call from the day it
|
||||
* happened to today.
|
||||
*/
|
||||
public function testAnAlreadyHeldCallKeepsItsDate(): void
|
||||
{
|
||||
$held = new \DateTimeImmutable('2026-09-01');
|
||||
$submission = $this->submission()->setFirstCallHeldAt($held);
|
||||
|
||||
$dto = new ApplicationFormSubmissionCallsDto($submission);
|
||||
$this->assertTrue($dto->isFirstCallHeld());
|
||||
|
||||
$dto->applyToSubmission();
|
||||
|
||||
$this->assertSame($held, $submission->getFirstCallHeldAt());
|
||||
}
|
||||
|
||||
public function testUntickingClearsTheDate(): void
|
||||
{
|
||||
$submission = $this->submission()->setSecondCallHeldAt(new \DateTimeImmutable('2026-09-01'));
|
||||
|
||||
$dto = new ApplicationFormSubmissionCallsDto($submission);
|
||||
$dto->setSecondCallHeld(false)->applyToSubmission();
|
||||
|
||||
$this->assertNull($submission->getSecondCallHeldAt());
|
||||
}
|
||||
|
||||
private function submission(): ApplicationFormSubmission
|
||||
{
|
||||
return new ApplicationFormSubmission(
|
||||
'applicationform',
|
||||
'Bewerbungsformular',
|
||||
new \DateTimeImmutable('2026-09-22T12:30:00+02:00'),
|
||||
'F'
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Model;
|
||||
|
||||
use App\Model\ApplicationFormSubmissionDto;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* The normalization the json column relies on: no empty answers, numbers as strings, booleans
|
||||
* kept, and a multi-select as a flat list of what was picked.
|
||||
*/
|
||||
class ApplicationFormSubmissionDtoTest extends TestCase
|
||||
{
|
||||
public function testEmptyAnswersAreDropped(): void
|
||||
{
|
||||
$dto = $this->dto(['Nationalität' => 'deutsch', 'Führerschein' => '', 'Sprachen' => [], 'Sport' => null]);
|
||||
|
||||
$this->assertSame(['Nationalität' => 'deutsch'], $dto->getNormalizedDetails());
|
||||
}
|
||||
|
||||
public function testNumbersBecomeStringsAndBooleansStay(): void
|
||||
{
|
||||
$dto = $this->dto(['Skifahrer seit' => 2004, 'Datenschutz' => true]);
|
||||
|
||||
$this->assertSame(['Skifahrer seit' => '2004', 'Datenschutz' => true], $dto->getNormalizedDetails());
|
||||
}
|
||||
|
||||
public function testAMultiSelectStaysAFlatListOfLabels(): void
|
||||
{
|
||||
$dto = $this->dto(['Ich fahre' => ['Ski', 'Snowboard']]);
|
||||
|
||||
$this->assertSame(['Ich fahre' => ['Ski', 'Snowboard']], $dto->getNormalizedDetails());
|
||||
}
|
||||
|
||||
public function testARelativeSubmissionTimeIsNotADate(): void
|
||||
{
|
||||
$this->assertNull((new ApplicationFormSubmissionDto(submittedAt: 'now'))->getSubmittedAt());
|
||||
$this->assertNull((new ApplicationFormSubmissionDto(submittedAt: '2026-09-22'))->getSubmittedAt());
|
||||
$this->assertNotNull((new ApplicationFormSubmissionDto(submittedAt: '2026-09-22T12:30:00+02:00'))->getSubmittedAt());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $details
|
||||
*/
|
||||
private function dto(array $details): ApplicationFormSubmissionDto
|
||||
{
|
||||
return new ApplicationFormSubmissionDto(
|
||||
form: 'applicationform',
|
||||
formLabel: 'Bewerbungsformular',
|
||||
submittedAt: '2026-09-22T12:30:00+02:00',
|
||||
details: $details,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Repository;
|
||||
|
||||
use App\Config\UploadToken;
|
||||
use App\Entity\Upload;
|
||||
use App\Repository\UploadRepository;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
|
||||
|
||||
/**
|
||||
* The token column is unique, so taking a slot from another document has to free it first - and
|
||||
* both rows are Uploads, which means nothing guarantees Doctrine writes the release before the
|
||||
* row that takes it. A single flush would trip the index; these tests pin that it does not.
|
||||
*/
|
||||
class UploadRepositoryTokenTest extends KernelTestCase
|
||||
{
|
||||
private EntityManagerInterface $entityManager;
|
||||
|
||||
private UploadRepository $repository;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
self::bootKernel();
|
||||
|
||||
$this->entityManager = self::getContainer()->get(EntityManagerInterface::class);
|
||||
$this->repository = self::getContainer()->get(UploadRepository::class);
|
||||
|
||||
$this->entityManager->createQuery(sprintf('DELETE FROM %s', Upload::class))->execute();
|
||||
}
|
||||
|
||||
public function testADocumentIsFoundByItsToken(): void
|
||||
{
|
||||
$document = $this->document('handout.pdf')->setToken(UploadToken::APPLICATION_FORM_HANDOUT);
|
||||
$this->entityManager->flush();
|
||||
|
||||
$this->assertSame($document, $this->repository->findByToken(UploadToken::APPLICATION_FORM_HANDOUT));
|
||||
}
|
||||
|
||||
public function testNothingIsFoundWhileNoDocumentHoldsTheToken(): void
|
||||
{
|
||||
$this->document('handout.pdf');
|
||||
$this->entityManager->flush();
|
||||
|
||||
$this->assertNull($this->repository->findByToken(UploadToken::APPLICATION_FORM_HANDOUT));
|
||||
}
|
||||
|
||||
public function testTakingTheTokenMovesItOffThePreviousDocument(): void
|
||||
{
|
||||
$old = $this->document('handout-2025.pdf')->setToken(UploadToken::APPLICATION_FORM_HANDOUT);
|
||||
$this->entityManager->flush();
|
||||
|
||||
$new = $this->document('handout-2026.pdf')->setToken(UploadToken::APPLICATION_FORM_HANDOUT);
|
||||
$releasedFrom = $this->repository->releaseToken(UploadToken::APPLICATION_FORM_HANDOUT, $new);
|
||||
$this->entityManager->flush();
|
||||
|
||||
$this->assertSame($old->getId(), $releasedFrom);
|
||||
$this->assertNull($old->getToken());
|
||||
$this->assertSame($new, $this->repository->findByToken(UploadToken::APPLICATION_FORM_HANDOUT));
|
||||
}
|
||||
|
||||
public function testReleasingForTheDocumentThatAlreadyHoldsItChangesNothing(): void
|
||||
{
|
||||
$document = $this->document('handout.pdf')->setToken(UploadToken::APPLICATION_FORM_HANDOUT);
|
||||
$this->entityManager->flush();
|
||||
|
||||
$this->assertNull($this->repository->releaseToken(UploadToken::APPLICATION_FORM_HANDOUT, $document));
|
||||
|
||||
$this->entityManager->flush();
|
||||
|
||||
$this->assertSame($document, $this->repository->findByToken(UploadToken::APPLICATION_FORM_HANDOUT));
|
||||
}
|
||||
|
||||
private function document(string $filename): Upload
|
||||
{
|
||||
$upload = (new Upload())
|
||||
->setType(Upload::TYPE_DOCUMENT)
|
||||
->setFilename($filename)
|
||||
->setOriginalFilename($filename)
|
||||
->setMimeType('application/pdf')
|
||||
->setSize(1024)
|
||||
;
|
||||
|
||||
$this->entityManager->persist($upload);
|
||||
|
||||
return $upload;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Service\Teamer;
|
||||
|
||||
use App\BusProNet\ApiClient;
|
||||
use App\BusProNet\ApiClientException;
|
||||
use App\BusProNet\Model\NotificationResponse;
|
||||
use App\BusProNet\Model\ProfileResponse;
|
||||
use App\BusProNet\Model\ProfileUpdateResponse;
|
||||
use App\BusProNet\Model\RegistrationResponse;
|
||||
use App\BusProNet\UserDataHandler;
|
||||
use App\Entity\ApplicationFormSubmission;
|
||||
use App\Entity\Teamer;
|
||||
use App\Entity\User;
|
||||
use App\Service\Teamer\TeamerProvisioner;
|
||||
use App\Service\Teamer\TeamerProvisioningException;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use PHPUnit\Framework\MockObject\MockObject;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Log\NullLogger;
|
||||
|
||||
/**
|
||||
* The three provisioning writes are not a transaction and only the first and the third can be
|
||||
* rehearsed against BusPro's test database - the teamer selection is changeable in production only
|
||||
* (.ddev/plans/buspro-crm-selection-write.md). So the orchestration is pinned here against a mocked
|
||||
* client: what runs, in which order, what is persisted before the next step, and what a retry does
|
||||
* after a failure halfway.
|
||||
*/
|
||||
class TeamerProvisionerTest extends TestCase
|
||||
{
|
||||
private const SELECTION_ID = 1070;
|
||||
|
||||
private const ADDRESS_ID = 141747;
|
||||
|
||||
private const PERSON_ID = 224526;
|
||||
|
||||
private ApiClient&MockObject $apiClient;
|
||||
|
||||
private UserDataHandler&MockObject $userDataHandler;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->apiClient = $this->createMock(ApiClient::class);
|
||||
$this->userDataHandler = $this->createMock(UserDataHandler::class);
|
||||
}
|
||||
|
||||
public function testANewApplicantBecomesATeamer(): void
|
||||
{
|
||||
$submission = $this->submission();
|
||||
|
||||
$this->apiClient
|
||||
->expects($this->once())
|
||||
->method('createAddress')
|
||||
->with($submission)
|
||||
->willReturn(new RegistrationResponse(self::ADDRESS_ID, self::PERSON_ID, true))
|
||||
;
|
||||
$this->expectSelectionWrite();
|
||||
$this->apiClient
|
||||
->expects($this->once())
|
||||
->method('resetPassword')
|
||||
->with('[email protected]')
|
||||
->willReturn(new NotificationResponse())
|
||||
;
|
||||
|
||||
$this->userDataHandler->method('findLocalUser')->willReturn(null);
|
||||
$this->userDataHandler
|
||||
->expects($this->once())
|
||||
->method('createLocalUser')
|
||||
// ROLE_TEAMER needs no approval, which is the only reason it may be granted here.
|
||||
->with($this->isInstanceOf(ProfileResponse::class), ['ROLE_TEAMER'], true)
|
||||
->willReturn($this->user())
|
||||
;
|
||||
|
||||
$result = $this->provisioner()->provision($submission);
|
||||
|
||||
$this->assertTrue($result->isAddressCreated());
|
||||
$this->assertTrue($result->isUserCreated());
|
||||
$this->assertFalse($result->isAlreadyTeamer());
|
||||
$this->assertTrue($result->isPasswordMailSent());
|
||||
$this->assertSame(self::ADDRESS_ID, $submission->getBusProAddressId());
|
||||
$this->assertSame(self::PERSON_ID, $submission->getBusProPersonId());
|
||||
$this->assertTrue($submission->isProvisioned());
|
||||
}
|
||||
|
||||
/**
|
||||
* BusPro recognised the person and answered with the ids of the address it already held. The
|
||||
* selection is set on that record and the reviewer is told - it is not a failure, and a
|
||||
* duplicate is what it prevents.
|
||||
*/
|
||||
public function testAnApplicantBusProAlreadyKnowsUsesTheExistingAddress(): void
|
||||
{
|
||||
$submission = $this->submission();
|
||||
|
||||
$this->apiClient
|
||||
->method('createAddress')
|
||||
->willReturn(new RegistrationResponse(self::ADDRESS_ID, self::PERSON_ID, false))
|
||||
;
|
||||
$this->expectSelectionWrite();
|
||||
$this->apiClient->method('resetPassword')->willReturn(new NotificationResponse());
|
||||
$this->userDataHandler->method('findLocalUser')->willReturn(null);
|
||||
$this->userDataHandler->method('createLocalUser')->willReturn($this->user());
|
||||
|
||||
$result = $this->provisioner()->provision($submission);
|
||||
|
||||
$this->assertFalse($result->isAddressCreated());
|
||||
$this->assertTrue($result->isUserCreated());
|
||||
$this->assertSame(self::ADDRESS_ID, $submission->getBusProAddressId());
|
||||
}
|
||||
|
||||
/**
|
||||
* The step that cannot be rehearsed outside production. When BusPro refuses it, the address is
|
||||
* already there - so the ids have to be persisted and no local teamer may appear.
|
||||
*/
|
||||
public function testARefusedSelectionLeavesTheAddressRecordedAndNoTeamer(): void
|
||||
{
|
||||
$submission = $this->submission();
|
||||
|
||||
$this->apiClient
|
||||
->method('createAddress')
|
||||
->willReturn(new RegistrationResponse(self::ADDRESS_ID, self::PERSON_ID, true))
|
||||
;
|
||||
$this->apiClient
|
||||
->method('updateCrmAttribute')
|
||||
->willReturn(new NotificationResponse(853, 'ID, EMail oder Passwort falsch'))
|
||||
;
|
||||
$this->apiClient->expects($this->never())->method('resetPassword');
|
||||
$this->userDataHandler->expects($this->never())->method('createLocalUser');
|
||||
|
||||
try {
|
||||
$this->provisioner()->provision($submission);
|
||||
$this->fail('Provisioning was expected to fail');
|
||||
} catch (TeamerProvisioningException $e) {
|
||||
$this->assertStringContainsString('853', $e->getMessage());
|
||||
}
|
||||
|
||||
$this->assertSame(self::ADDRESS_ID, $submission->getBusProAddressId());
|
||||
$this->assertFalse($submission->isProvisioned());
|
||||
$this->assertNull($submission->getUser());
|
||||
}
|
||||
|
||||
/**
|
||||
* änderung=False is BusPro saying it did not apply the change - the selection is not
|
||||
* changeable in this environment, which is exactly the state of the test database.
|
||||
*/
|
||||
public function testAnUnappliedSelectionIsAFailure(): void
|
||||
{
|
||||
$submission = $this->submission();
|
||||
|
||||
$this->apiClient
|
||||
->method('createAddress')
|
||||
->willReturn(new RegistrationResponse(self::ADDRESS_ID, self::PERSON_ID, true))
|
||||
;
|
||||
$this->apiClient
|
||||
->method('updateCrmAttribute')
|
||||
->willReturn((new ProfileUpdateResponse())->setUpdated(false))
|
||||
;
|
||||
$this->userDataHandler->expects($this->never())->method('createLocalUser');
|
||||
|
||||
$this->expectException(TeamerProvisioningException::class);
|
||||
|
||||
$this->provisioner()->provision($submission);
|
||||
}
|
||||
|
||||
/**
|
||||
* The retry after the failure above: the address exists and must not be created a second time.
|
||||
* The selection is written again instead, which is safe because that write is idempotent.
|
||||
*/
|
||||
public function testARetryResumesInsteadOfCreatingASecondAddress(): void
|
||||
{
|
||||
$submission = $this->submission()
|
||||
->setBusProAddressId(self::ADDRESS_ID)
|
||||
->setBusProPersonId(self::PERSON_ID)
|
||||
;
|
||||
|
||||
$this->apiClient->expects($this->never())->method('createAddress');
|
||||
$this->expectSelectionWrite();
|
||||
$this->apiClient->method('resetPassword')->willReturn(new NotificationResponse());
|
||||
$this->userDataHandler->method('findLocalUser')->willReturn(null);
|
||||
$this->userDataHandler->method('createLocalUser')->willReturn($this->user());
|
||||
|
||||
$result = $this->provisioner()->provision($submission);
|
||||
|
||||
$this->assertFalse($result->isAddressCreated());
|
||||
$this->assertTrue($submission->isProvisioned());
|
||||
}
|
||||
|
||||
/**
|
||||
* Somebody who already has an account - an existing customer, or a teamer from an earlier
|
||||
* season. No second account, and the reviewer is told rather than left wondering why nothing
|
||||
* appeared.
|
||||
*/
|
||||
public function testAnApplicantWhoAlreadyHasATeamerAccountIsNotCreatedTwice(): void
|
||||
{
|
||||
$submission = $this->submission();
|
||||
$user = $this->user(teamer: true, roles: ['ROLE_TEAMER']);
|
||||
|
||||
$this->apiClient
|
||||
->method('createAddress')
|
||||
->willReturn(new RegistrationResponse(self::ADDRESS_ID, self::PERSON_ID, false))
|
||||
;
|
||||
$this->expectSelectionWrite();
|
||||
$this->apiClient->method('resetPassword')->willReturn(new NotificationResponse());
|
||||
$this->userDataHandler->method('findLocalUser')->willReturn($user);
|
||||
$this->userDataHandler->expects($this->never())->method('createLocalUser');
|
||||
$this->userDataHandler->expects($this->never())->method('grantTeamerRole');
|
||||
|
||||
$result = $this->provisioner()->provision($submission);
|
||||
|
||||
$this->assertFalse($result->isUserCreated());
|
||||
$this->assertTrue($result->isAlreadyTeamer());
|
||||
$this->assertSame($user, $result->getUser());
|
||||
$this->assertSame($user, $submission->getUser());
|
||||
}
|
||||
|
||||
/**
|
||||
* An account without the teamer half - an office user, or a customer who once booked a trip.
|
||||
* They get the role and a teamer record, not a second account.
|
||||
*/
|
||||
public function testAnAccountWithoutATeamerGetsOne(): void
|
||||
{
|
||||
$submission = $this->submission();
|
||||
$user = $this->user();
|
||||
|
||||
$this->apiClient
|
||||
->method('createAddress')
|
||||
->willReturn(new RegistrationResponse(self::ADDRESS_ID, self::PERSON_ID, false))
|
||||
;
|
||||
$this->expectSelectionWrite();
|
||||
$this->apiClient->method('resetPassword')->willReturn(new NotificationResponse());
|
||||
$this->userDataHandler->method('findLocalUser')->willReturn($user);
|
||||
$this->userDataHandler->expects($this->once())->method('grantTeamerRole')->with($user);
|
||||
|
||||
$result = $this->provisioner()->provision($submission);
|
||||
|
||||
$this->assertFalse($result->isUserCreated());
|
||||
$this->assertFalse($result->isAlreadyTeamer());
|
||||
$this->assertInstanceOf(Teamer::class, $user->getTeamer());
|
||||
$this->assertSame('Anna', $user->getTeamer()->getFirstName());
|
||||
// F/M/D is this application's own vocabulary and is stored as it came; the mapping to
|
||||
// BusPro's W happens on the way out only.
|
||||
$this->assertSame('F', $user->getTeamer()->getGender());
|
||||
$this->assertSame('1990-01-01', $user->getTeamer()->getDateOfBirth()?->format('Y-m-d'));
|
||||
}
|
||||
|
||||
/**
|
||||
* A deleted account matched by email. Granting it a role would resurrect somebody who asked to
|
||||
* be gone, under their old row - a decision for a human, not for a provisioning click.
|
||||
*/
|
||||
public function testADeletedAccountStopsProvisioning(): void
|
||||
{
|
||||
$submission = $this->submission();
|
||||
|
||||
$this->apiClient
|
||||
->method('createAddress')
|
||||
->willReturn(new RegistrationResponse(self::ADDRESS_ID, self::PERSON_ID, false))
|
||||
;
|
||||
$this->expectSelectionWrite();
|
||||
$this->userDataHandler->method('findLocalUser')->willReturn($this->user(deleted: true));
|
||||
$this->userDataHandler->expects($this->never())->method('createLocalUser');
|
||||
$this->apiClient->expects($this->never())->method('resetPassword');
|
||||
|
||||
$this->expectException(TeamerProvisioningException::class);
|
||||
|
||||
$this->provisioner()->provision($submission);
|
||||
}
|
||||
|
||||
/**
|
||||
* The password mail is the last step and its failure is reported, not thrown: the teamer exists
|
||||
* by then, and undoing three writes over an unsent mail would be worse than saying so.
|
||||
*/
|
||||
public function testAFailedPasswordMailStillLeavesAProvisionedTeamer(): void
|
||||
{
|
||||
$submission = $this->submission();
|
||||
|
||||
$this->apiClient
|
||||
->method('createAddress')
|
||||
->willReturn(new RegistrationResponse(self::ADDRESS_ID, self::PERSON_ID, true))
|
||||
;
|
||||
$this->expectSelectionWrite();
|
||||
$this->apiClient->method('resetPassword')->willThrowException(new ApiClientException('timeout'));
|
||||
$this->userDataHandler->method('findLocalUser')->willReturn(null);
|
||||
$this->userDataHandler->method('createLocalUser')->willReturn($this->user());
|
||||
|
||||
$result = $this->provisioner()->provision($submission);
|
||||
|
||||
$this->assertFalse($result->isPasswordMailSent());
|
||||
$this->assertTrue($submission->isProvisioned());
|
||||
}
|
||||
|
||||
/**
|
||||
* A second click, or a stale page: nothing is sent to BusPro at all.
|
||||
*/
|
||||
public function testAProvisionedSubmissionIsNotProvisionedAgain(): void
|
||||
{
|
||||
$user = $this->user();
|
||||
$submission = $this->submission()
|
||||
->setBusProAddressId(self::ADDRESS_ID)
|
||||
->setBusProPersonId(self::PERSON_ID)
|
||||
->setUser($user)
|
||||
->setTeamerCreatedAt(new \DateTimeImmutable())
|
||||
;
|
||||
|
||||
$this->apiClient->expects($this->never())->method('createAddress');
|
||||
$this->apiClient->expects($this->never())->method('updateCrmAttribute');
|
||||
$this->apiClient->expects($this->never())->method('resetPassword');
|
||||
|
||||
$result = $this->provisioner()->provision($submission);
|
||||
|
||||
$this->assertTrue($result->isAlreadyProvisioned());
|
||||
$this->assertSame($user, $result->getUser());
|
||||
}
|
||||
|
||||
/**
|
||||
* A row from before the tightened endpoint contract. It is refused before anything is written,
|
||||
* because BusPro's own complaint would only arrive after the address attempt.
|
||||
*/
|
||||
public function testAnIncompleteSubmissionIsRefusedBeforeAnythingIsWritten(): void
|
||||
{
|
||||
$submission = $this->submission()->setBirthDate('01.01.1990');
|
||||
|
||||
$this->apiClient->expects($this->never())->method('createAddress');
|
||||
|
||||
try {
|
||||
$this->provisioner()->provision($submission);
|
||||
$this->fail('Provisioning was expected to fail');
|
||||
} catch (TeamerProvisioningException $e) {
|
||||
$this->assertStringContainsString('Geburtsdatum', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The postal address is required of every payload - street and postcode because BusPro treats
|
||||
* them as mandatory for a new address - so a row without it is refused here rather than at step
|
||||
* 1, where the reviewer would get BusPro's complaint only after the attempt.
|
||||
*/
|
||||
public function testASubmissionWithoutAnAddressIsRefusedBeforeAnythingIsWritten(): void
|
||||
{
|
||||
$submission = $this->submission()->setStreet(null)->setZipCode(null)->setCity(null);
|
||||
|
||||
$this->apiClient->expects($this->never())->method('createAddress');
|
||||
|
||||
try {
|
||||
$this->provisioner()->provision($submission);
|
||||
$this->fail('Provisioning was expected to fail');
|
||||
} catch (TeamerProvisioningException $e) {
|
||||
$this->assertStringContainsString('Straße', $e->getMessage());
|
||||
$this->assertStringContainsString('Postleitzahl', $e->getMessage());
|
||||
$this->assertStringContainsString('Ort', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private function expectSelectionWrite(): void
|
||||
{
|
||||
$this->apiClient
|
||||
->expects($this->once())
|
||||
->method('updateCrmAttribute')
|
||||
->with('[email protected]', self::ADDRESS_ID, self::PERSON_ID, self::SELECTION_ID, true)
|
||||
->willReturn((new ProfileUpdateResponse())->setUpdated(true))
|
||||
;
|
||||
}
|
||||
|
||||
private function provisioner(): TeamerProvisioner
|
||||
{
|
||||
return new TeamerProvisioner(
|
||||
$this->apiClient,
|
||||
$this->userDataHandler,
|
||||
$this->createMock(EntityManagerInterface::class),
|
||||
new NullLogger(),
|
||||
self::SELECTION_ID,
|
||||
);
|
||||
}
|
||||
|
||||
private function submission(): ApplicationFormSubmission
|
||||
{
|
||||
return (new ApplicationFormSubmission(
|
||||
'applicationform',
|
||||
'Bewerbungsformular',
|
||||
new \DateTimeImmutable('2026-09-22T12:30:00+02:00'),
|
||||
'F',
|
||||
))
|
||||
->setFirstName('Anna')
|
||||
->setLastName('Muster')
|
||||
->setEmail('[email protected]')
|
||||
->setBirthDate('1990-01-01')
|
||||
->setStreet('Musterstraße 1')
|
||||
->setZipCode('10115')
|
||||
->setCity('Berlin')
|
||||
->setEu(true)
|
||||
;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string[] $roles
|
||||
*/
|
||||
private function user(bool $teamer = false, array $roles = [], bool $deleted = false): User
|
||||
{
|
||||
$user = (new User())
|
||||
->setFirstName('Anna')
|
||||
->setLastName('Muster')
|
||||
->setEmail('[email protected]')
|
||||
->setRoles($roles)
|
||||
;
|
||||
|
||||
if (true === $teamer) {
|
||||
$user->setTeamer((new Teamer())->setFirstName('Anna')->setLastName('Muster')->setGender('F'));
|
||||
}
|
||||
|
||||
if (true === $deleted) {
|
||||
$user->setDeletedAt(new \DateTimeImmutable());
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user