Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0ad5374e9 | ||
|
|
96d49fc488 | ||
|
|
2a554bb7bf | ||
|
|
c16e4bf53f |
No files matched your search
@@ -1,7 +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).
|
||||
# later mapping change into a 400.
|
||||
framework:
|
||||
serializer:
|
||||
name_converter: ~
|
||||
@@ -1,354 +0,0 @@
|
||||
# API Consumer Guide
|
||||
|
||||
This document describes the public JSON API exposed under `/api`, written for developers implementing a **client** in another application. It is self-contained: no access to this codebase is required to use it.
|
||||
|
||||
## Overview
|
||||
|
||||
A Symfony application exposing a read-mostly JSON API under the `/api` prefix. All `/api/*` requests are stateless and authenticated via OAuth2 Bearer tokens (League OAuth2 Server, JWT access tokens). Responses are `application/json`. HTTPS is enforced on all routes.
|
||||
|
||||
## Authentication
|
||||
|
||||
- Token endpoint: `POST /token` (unauthenticated).
|
||||
- Enabled grants: **client_credentials**, **authorization_code** (PKCE required for public clients), **refresh_token**. Password and implicit grants are disabled.
|
||||
- Access token TTL: **10 minutes** — clients must refresh/re-request frequently.
|
||||
- Available scopes: `email`, `id`, `profile`, `roles`, `api`. Default scope if none requested: `email`.
|
||||
- Each granted scope maps to a role `ROLE_OAUTH2_<SCOPE_UPPERCASE>` (e.g. scope `api` → `ROLE_OAUTH2_API`).
|
||||
- Send the token as `Authorization: Bearer <access_token>`.
|
||||
|
||||
Scope required per endpoint:
|
||||
|
||||
| Scope needed | Endpoints |
|
||||
|---|---|
|
||||
| `api` | everything except the two below |
|
||||
| `profile` | `GET /api/crm-attributes` |
|
||||
| `email` | `GET /api/userinfo` (optional extra scopes `id`, `profile`, `roles` widen the response) |
|
||||
|
||||
`/api/userinfo` and `/api/crm-attributes` act on the **authenticated end user**, so they require an authorization_code token issued for a user. All other endpoints are machine-to-machine and work with client_credentials.
|
||||
|
||||
### Machine-to-machine example
|
||||
|
||||
```
|
||||
POST /token
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
grant_type=client_credentials&client_id=...&client_secret=...&scope=api
|
||||
```
|
||||
|
||||
```
|
||||
GET /api/hotels
|
||||
Authorization: Bearer eyJ0eXAi...
|
||||
```
|
||||
|
||||
## Error conventions
|
||||
|
||||
There is no single error envelope; three shapes occur:
|
||||
|
||||
- `{"message": "..."}` — commonly with 404 / 400.
|
||||
- `{"error": "...", "type": "api_error"}` — upstream failures on some endpoints. **Caution:** on `/api/products` and `/api/travels/{dateId}/{hotelId}/{dateTo}/availability` this shape is returned with HTTP **200**, so clients must check for the presence of an `error` key, not only the status code.
|
||||
- `{"success": false, "message": "..."}` — the write endpoints (contact form, newsletter).
|
||||
|
||||
Validation failures on endpoints using mapped query strings / payloads (`/api/contingents/*`, `/api/newsletter-subscriptions`) return **400** with Symfony's constraint-violation body. Missing/invalid token yields **401**; insufficient scope yields **403**.
|
||||
|
||||
The HTTP methods listed below are the intended ones. Several read routes do not restrict methods server-side; clients should still use `GET` for them.
|
||||
|
||||
---
|
||||
|
||||
## Endpoints
|
||||
|
||||
### Reference data (BusProNet master data)
|
||||
|
||||
#### `GET /api/hotels` — scope `api`
|
||||
|
||||
List of hotels. Array of objects: `id` (int), `code` (string), `name`, `city`, `street`, `phone`, `country`.
|
||||
|
||||
#### `GET /api/hotels/{id}` — scope `api`
|
||||
|
||||
Single hotel by numeric id, same field set as the list. `404 {"message":"Not found"}` if unknown.
|
||||
|
||||
#### `GET /api/countries` — scope `api`
|
||||
|
||||
Array of `{id, name, token, nationality}`.
|
||||
|
||||
#### `GET /api/products` — scope `api`
|
||||
|
||||
Product master data from the upstream BusProNet system, cached server-side for 1 hour. On upstream failure returns `{"error": "...", "type": "api_error"}` **with status 200**.
|
||||
|
||||
#### `GET /api/last-update` — scope `api`
|
||||
|
||||
Timestamp of the last upstream data export: `{"timestamp": "YYYY-MM-DD HH:MM:SS"}`. Note: if no export marker file exists the current implementation errors (500) rather than returning null — treat a non-JSON/500 response as "unknown".
|
||||
|
||||
---
|
||||
|
||||
### Pickups (bus boarding points)
|
||||
|
||||
#### `GET /api/pickups` — scope `api`
|
||||
|
||||
Array of `{id, code, city, postalCode, street}`.
|
||||
|
||||
#### `GET /api/pickups/{id}` — scope `api`
|
||||
|
||||
Single pickup by numeric id, same fields as the list.
|
||||
|
||||
#### `GET /api/pickups-planning/{travelCode}` — scope `api`
|
||||
|
||||
Planned outbound (HIN) boarding stops for one travel code. Returns an array, chronologically sorted:
|
||||
|
||||
```json
|
||||
[{"city": "...", "location": "...", "datetime": "YYYY-MM-DD HH:MM", "busNumber": "..."}]
|
||||
```
|
||||
|
||||
`404 {"error":"Planning data not available"}` if no planning has been uploaded yet, `404 {"error":"Travel code not found"}` for an unknown code, `500 {"error":"Failed to read planning data"}` on storage errors.
|
||||
|
||||
#### `POST /api/pickups-planning` — scope `api`
|
||||
|
||||
Bulk-replaces the planning dataset. Body: a JSON **array** of raw planning rows using the upstream German keys:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"PlanungsArt": "HIN",
|
||||
"Reisecode": "ABC123",
|
||||
"Zustieg/Ausstieg Ort": "Köln",
|
||||
"Zustieg/Ausstieg Strasse": "Hauptbahnhof",
|
||||
"Zeit": "24.12.2026 07:30",
|
||||
"BusNummer": "1"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
Rows without `PlanungsArt === "HIN"` or without `Reisecode` are dropped; duplicates (same city + location + datetime + bus) are de-duplicated; results are grouped by `Reisecode` and sorted by time. Response `{"status":"ok"}` (200). `400 {"error":"Invalid JSON payload"}`, `500 {"error":"Failed to write pickups planning data"}`.
|
||||
|
||||
This is a full overwrite, not a merge.
|
||||
|
||||
---
|
||||
|
||||
### Travels
|
||||
|
||||
#### `GET /api/travels` — scope `api`
|
||||
|
||||
Index/mapping of all known travel dates. Object keyed by numeric travel id, each value `{id, code, label, dateFrom, dateTo, hotels: [...]}`.
|
||||
|
||||
#### `GET /api/travels/{dateId}/{hotelId}` — scope `api`
|
||||
|
||||
Single travel by **numeric** ids (`hotelId` optional). Route matches only when both segments are digits.
|
||||
|
||||
#### `GET /api/travels/{dateCode}/{hotelCode}` — scope `api`
|
||||
|
||||
Same, addressed by **string** codes (`hotelCode` optional). The date code is sanitized (separators stripped) before lookup. `404 {"message":"Not found"}` if the date code is unknown, `404 {"message":"Travel not found"}` if no data exists.
|
||||
|
||||
Both variants accept optional query parameters:
|
||||
|
||||
- `source=local` — force the local XML/snapshot data.
|
||||
- `source=remote` — force a live upstream call.
|
||||
- `prefer_remote=1` — used only when `source` is absent; prefers upstream with local fallback.
|
||||
|
||||
Response fields: `id`, `code`, `productCode`, `productId`, `label`, `hotelId`, `hotel` (hotel object), `dateFrom`, `dateTo`, `type`, `status`, `allowedBookingStatus[]`, `priceFrom`, `selectionGroups[]`, `additionalServices[]`, `transportationServices[]`, `pickups[]`, `dropOffs[]`, `rooms[]`, `guide`, `insurances[]`.
|
||||
|
||||
#### `GET /api/travels/{dateId}/{hotelId}/{dateTo}/availability` — scope `api`
|
||||
|
||||
Live hotel availability from the upstream system. `dateTo` must be `Y-m-d`. On upstream failure returns `{"error":"...","type":"api_error"}` **with status 200**.
|
||||
|
||||
---
|
||||
|
||||
### Contingents & accommodation prices
|
||||
|
||||
#### `GET /api/contingents/prices?hotelCode=…&year=…` — scope `api`
|
||||
|
||||
Price timeline for one accommodation and calendar year, collapsed into contiguous segments (adjacent days with the same effective price are merged into one row). The timeline never starts before today; if the requested year is entirely in the past the response is `[]`.
|
||||
|
||||
- `hotelCode`: required, max 16 chars, `[A-Za-z0-9_-]+` (matches the accommodation's calendar code).
|
||||
- `year`: required int, 1000–9999.
|
||||
|
||||
Each row:
|
||||
|
||||
```json
|
||||
{
|
||||
"dateFrom": "2026-06-01",
|
||||
"dateTo": "2026-06-14",
|
||||
"season": "high|low|...|null",
|
||||
"includedPax": 2,
|
||||
"pricePerNight": 89.5,
|
||||
"priceAdditionalPerson": 25.0,
|
||||
"defaultPricePerNight": 99.0,
|
||||
"defaultPriceAdditionalPerson": 30.0,
|
||||
"currency": "EUR",
|
||||
"type": "discount|null"
|
||||
}
|
||||
```
|
||||
|
||||
Prices are **decimal major units** (converted from integer minor units server-side). `default*` fields are non-null only when the winning price is a discount, and then carry the undiscounted price. `400 {"error":"Hotel not found for hotelCode."}` for an unknown code; `400` with violations for invalid parameters.
|
||||
|
||||
#### `GET /api/contingents/calendar?hotelCode=…&dateFrom=…&dateTo=…` — scope `api`
|
||||
|
||||
Per-day availability enriched with prices. Both dates are `Y-m-d` and **inclusive** (`dateTo` is the last night, not the checkout day); the range may not exceed 366 days and `dateTo` must not precede `dateFrom`. Upstream contingent data is cached 1 hour per (hotelCode, dateFrom, dateTo).
|
||||
|
||||
Each entry:
|
||||
|
||||
```json
|
||||
{
|
||||
"date": "2026-06-01",
|
||||
"status": "Free|Blocked|...",
|
||||
"type": "discount|null",
|
||||
"pricePerNight": 89.5,
|
||||
"defaultPricePerNight": 99.0,
|
||||
"priceAdditionalPerson": 25.0,
|
||||
"defaultPriceAdditionalPerson": 30.0,
|
||||
"currency": "EUR",
|
||||
"includedPax": 2,
|
||||
"minNights": 2
|
||||
}
|
||||
```
|
||||
|
||||
Important rule: **a day with no maintained price is forced to `Blocked`** regardless of what the upstream contingent says. Price fields may be `null` in that case.
|
||||
|
||||
Errors: `400 {"error":"Hotel not found for hotelCode."}`, `502 {"error":"Failed to fetch contingent data."}` when the upstream contingent service fails, `400` with violations for invalid parameters.
|
||||
|
||||
---
|
||||
|
||||
### Accommodation bookings (group bookings)
|
||||
|
||||
#### `GET /api/accommodation-bookings/{uuid}` — scope `api`
|
||||
|
||||
Single booking by UUID. `404 {"message":"Not found"}` if unknown.
|
||||
|
||||
```json
|
||||
{
|
||||
"uuid": "...",
|
||||
"status": "...",
|
||||
"type": "...",
|
||||
"dateFrom": "2026-06-01",
|
||||
"dateTo": "2026-06-08",
|
||||
"nights": 7,
|
||||
"paxCount": 40,
|
||||
"minorsCount": 12,
|
||||
"childrenCount": 3,
|
||||
"groupName": "...",
|
||||
"acceptedAt": "2026-05-01T10:00:00+00:00",
|
||||
"personalData": {},
|
||||
"accommodation": {},
|
||||
"boardService": {},
|
||||
"additionalServices": [],
|
||||
"accommodationDiscount": null,
|
||||
"boardServiceDiscount": null,
|
||||
"additionalServicesDiscount": null,
|
||||
"totalPrice": 123456,
|
||||
"pricingCurrency": "EUR",
|
||||
"pricingVersion": 3,
|
||||
"priceBreakdown": {}
|
||||
}
|
||||
```
|
||||
|
||||
`totalPrice` and the `*Discount` fields are integer **minor units** (cents) — unlike the contingent endpoints. `dateFrom`/`dateTo` are `Y-m-d`; `acceptedAt` is a full ISO-8601 datetime and is `null` until accepted. `priceBreakdown` is a computed nested structure.
|
||||
|
||||
#### `POST /api/accommodation-bookings/{uuid}/accept` — scope `api`
|
||||
|
||||
Marks the booking as accepted (server-side side effects: status change, `acceptedAt`, notifications). No request body. Returns the same booking representation as the GET. `404` if unknown. Not idempotent in terms of side effects — call once.
|
||||
|
||||
---
|
||||
|
||||
### Contact form
|
||||
|
||||
#### `POST /api/contactform` — scope `api`
|
||||
|
||||
Creates or matches an address record in the upstream CRM.
|
||||
|
||||
Request body (all fields optional strings; the upstream system decides what is required):
|
||||
|
||||
```json
|
||||
{
|
||||
"lastName": "...", "firstName": "...", "gender": "...",
|
||||
"street": "...", "zipCode": "...", "city": "...",
|
||||
"email": "...", "phone": "..."
|
||||
}
|
||||
```
|
||||
|
||||
- `201` — `{"success": true, "addressId": 123, "personId": 456, "isNewRecord": true}`
|
||||
- `409` — `{"success": false, "message": "<upstream notification>"}` (upstream rejected/conflicted)
|
||||
- `400` — `{"success": false, "message": "<error>"}` (upstream call failed)
|
||||
- `422` — malformed payload
|
||||
|
||||
---
|
||||
|
||||
### Newsletter
|
||||
|
||||
#### `GET /api/newsletters` — scope `api`
|
||||
|
||||
The configured newsletter lists as an array of `{id, name, ...}` mapping objects. Use the returned `id` values as `listIds` below.
|
||||
|
||||
#### `POST /api/newsletter-subscriptions` — scope `api`
|
||||
|
||||
Request:
|
||||
|
||||
```json
|
||||
{
|
||||
"email": "[email protected]",
|
||||
"firstName": "Ada",
|
||||
"lastName": "Lovelace",
|
||||
"listIds": [1, 2]
|
||||
}
|
||||
```
|
||||
|
||||
- `email`: required, strict email validation.
|
||||
- `firstName` / `lastName`: optional, max 255 chars.
|
||||
- `listIds`: required, at least one positive integer; every id must be one of the configured lists.
|
||||
|
||||
Responses:
|
||||
|
||||
- `200` — subscription completed, `state: "subscribed"`.
|
||||
- `202` — a double-opt-in confirmation mail was requested, `state: "confirmation_requested"`.
|
||||
- Body in both cases:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"email": "[email protected]",
|
||||
"lists": [{"id": 1, "name": "...", "state": "success|pending|already_registered"}],
|
||||
"state": "subscribed|pending_confirmation|confirmation_requested",
|
||||
"confirmationRequested": true
|
||||
}
|
||||
```
|
||||
|
||||
- `400` — unknown or disallowed list ids: `{"success": false, "message": "...", "listIds": [...], "unknownListIds": [...]}`, or validation violations.
|
||||
- `503` — `{"success": false, "email": "...", "listIds": [...], "message": "Newsletter subscription request could not be processed."}` when the newsletter provider is unavailable. Safe to retry.
|
||||
|
||||
---
|
||||
|
||||
### End-user endpoints (require a user-bound token)
|
||||
|
||||
#### `GET /api/userinfo` — scope `email` (+ optional `id`, `profile`, `roles`)
|
||||
|
||||
OIDC-style claims for the authenticated user. The response contains only the claims covered by the granted scopes:
|
||||
|
||||
- always: `email`
|
||||
- scope `id`: `person_id`, `address_id`
|
||||
- scope `roles`: `roles` (array; the implicit baseline role is stripped, only explicitly assigned roles are exported)
|
||||
- scope `profile`: `profile` object:
|
||||
|
||||
```json
|
||||
{
|
||||
"first_name": "...", "last_name": "...", "title": "...", "salutation": "...",
|
||||
"gender": "...", "date_of_birth": "1990-01-01", "nationality": "...",
|
||||
"address": {"street": "...", "postcode": "...", "city": "...", "district": "...", "country": "..."},
|
||||
"communication": {"email": "...", "mobile": "...", "phone": "...", "newsletter": true},
|
||||
"hotel_codes": ["..."], "height": null, "weight": null, "shoe_size": null, "remarks": "..."
|
||||
}
|
||||
```
|
||||
|
||||
Note: `profile.communication.email` comes from the CRM address record and is **not necessarily** the login email — a single address can hold several contacts. Use the top-level `email` claim for identity.
|
||||
|
||||
`400 {"message": "...", "code": "..."}` when the upstream lookup fails or rejects the credentials.
|
||||
|
||||
#### `GET /api/crm-attributes` — scope `profile`
|
||||
|
||||
CRM selection attributes/segments for the authenticated user. `400 {"message": "...", "code": "..."}` on upstream failure.
|
||||
|
||||
---
|
||||
|
||||
## Client implementation notes
|
||||
|
||||
1. **Token lifetime is 10 minutes** — implement refresh/re-fetch with a safety margin and retry once on 401.
|
||||
2. **Check for an `error` key even on 200 responses** for `/api/products` and the travel availability endpoint.
|
||||
3. **Money units are inconsistent across endpoints**: contingent endpoints return decimal major units; accommodation-booking fields return integer cents. Normalize at the client boundary.
|
||||
4. **Dates**: `Y-m-d` everywhere except `acceptedAt` (ISO-8601 datetime) and pickup planning (`Y-m-d H:i`). Contingent `dateFrom`/`dateTo` are inclusive night boundaries.
|
||||
5. **Server-side caching** (1 h on products and the contingent calendar) means upstream changes may not be visible immediately.
|
||||
6. **Route ambiguity**: `/api/travels/{a}/{b}` resolves to the id-based route when both segments are numeric, otherwise to the code-based route. Non-numeric codes are safe; purely numeric *codes* will hit the id route.
|
||||
@@ -9,8 +9,7 @@ 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).
|
||||
* outcome of each of the three provisioning writes.
|
||||
*
|
||||
* 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
|
||||
|
||||
@@ -68,15 +68,28 @@ class ApiClient
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the teamer's profile to their BusPro address without their password.
|
||||
*
|
||||
* "login" switches the password check off, so the two ids are the whole authorisation of
|
||||
* this write: an address can hold several persons, and only "idadresseperson" names the
|
||||
* person, while "email" is ignored. The ids must therefore only ever come from a verified
|
||||
* source - MyE&P userinfo or a BusPro answer - never from a form or a request parameter.
|
||||
* Verified on the BusPro test system (2026-10-16): BusPro accepts "login" on KUNDENKONTO
|
||||
* requests made with our API credentials.
|
||||
*
|
||||
* @throws ApiClientException
|
||||
* @throws ResponseParserException
|
||||
*/
|
||||
public function updateProfile(User $user, string $password): NotificationResponse|ProfileUpdateResponse
|
||||
public function updateProfile(User $user): NotificationResponse|ProfileUpdateResponse
|
||||
{
|
||||
if (null === $teamer = $user->getTeamer()) {
|
||||
throw new ApiClientException('Invalid argument');
|
||||
}
|
||||
|
||||
if (null === $user->getBusProAddressId() || null === $user->getBusProPersonId()) {
|
||||
throw new ApiClientException('User has no BusPro address and person id');
|
||||
}
|
||||
|
||||
$data = [
|
||||
'anfrage' => [
|
||||
'user' => $this->config['bpn_username'],
|
||||
@@ -84,8 +97,9 @@ class ApiClient
|
||||
'satz' => ['@typ' => static::TYPE_CUSTOMER_DATA],
|
||||
'art' => 'Adressdaten_Ändern',
|
||||
'email' => $user->getEmail(),
|
||||
'passwort' => $password,
|
||||
'login' => 'J',
|
||||
'idadresse' => $user->getBusProAddressId(),
|
||||
'idadresseperson' => $user->getBusProPersonId(),
|
||||
'adressdaten' => $teamer->toPayload(),
|
||||
],
|
||||
];
|
||||
@@ -132,8 +146,9 @@ class ApiClient
|
||||
* "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.
|
||||
* payload are what BusPro accepted when verified against production (2026-09-25, selection
|
||||
* 1070 toggled off and back on) - the art is undocumented, so re-verify 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.
|
||||
|
||||
@@ -54,7 +54,7 @@ class ResponseParser
|
||||
// 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).
|
||||
// sent the art.
|
||||
return $this->createProfileUpdateResponse($xml);
|
||||
case 'Adresse_Neu':
|
||||
return $this->createRegistrationResponse($xml);
|
||||
|
||||
@@ -21,8 +21,7 @@ use Symfony\Component\Security\Http\Attribute\IsGranted;
|
||||
*
|
||||
* 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).
|
||||
* matching against known people belong in a worker, not here.
|
||||
*/
|
||||
class ApplicationFormController extends AbstractController
|
||||
{
|
||||
@@ -58,7 +57,7 @@ class ApplicationFormController extends AbstractController
|
||||
'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
|
||||
// the labels and the answers are personal data, their number is not
|
||||
'detailCount' => count($submission->getDetails()),
|
||||
'receiptSent' => $receiptSent,
|
||||
]);
|
||||
|
||||
@@ -4,6 +4,9 @@ namespace App\Controller\Teamer\Profile;
|
||||
|
||||
use App\BusProNet\ApiClient;
|
||||
use App\BusProNet\ApiClientException;
|
||||
use App\BusProNet\Model\NotificationResponse;
|
||||
use App\BusProNet\Model\ProfileUpdateResponse;
|
||||
use App\BusProNet\ResponseParserException;
|
||||
use App\Entity\Teamer;
|
||||
use App\Entity\Upload;
|
||||
use App\Entity\User;
|
||||
@@ -59,12 +62,7 @@ class IndexController extends AbstractController
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
try {
|
||||
$bpnPassword = $request->getSession()->get('bpn_password');
|
||||
$this->apiClient->updateProfile($user, $bpnPassword);
|
||||
$this->entityManager->flush();
|
||||
} catch (ApiClientException $e) {
|
||||
}
|
||||
$this->updateBusProProfile($user);
|
||||
|
||||
// Saving the full profile form is a stronger statement than ticking the
|
||||
// confirmation box, so it clears the verification check too.
|
||||
@@ -88,6 +86,44 @@ class IndexController extends AbstractController
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The local save does not depend on BusPro: a failed write is logged, and the teamer's data
|
||||
* is kept here either way.
|
||||
*/
|
||||
private function updateBusProProfile(User $user): void
|
||||
{
|
||||
$context = [
|
||||
'user_id' => $user->getId(),
|
||||
'bus_pro_address_id' => $user->getBusProAddressId(),
|
||||
'bus_pro_person_id' => $user->getBusProPersonId(),
|
||||
];
|
||||
|
||||
if (null === $user->getBusProAddressId() || null === $user->getBusProPersonId()) {
|
||||
$this->logger->warning('Skip BusPro profile update: user has no BusPro IDs', $context);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $this->apiClient->updateProfile($user);
|
||||
} catch (ApiClientException|ResponseParserException $e) {
|
||||
$this->logger->error('BusPro profile update failed', $context + [
|
||||
'error_message' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($response instanceof NotificationResponse && false === $response->isSuccessful()) {
|
||||
$this->logger->error('BusPro rejected profile update', $context + [
|
||||
'bpn_code' => $response->getCode(),
|
||||
'bpn_message' => $response->getMessage(),
|
||||
]);
|
||||
} elseif ($response instanceof ProfileUpdateResponse && false === $response->isUpdated()) {
|
||||
$this->logger->error('BusPro did not update profile', $context);
|
||||
}
|
||||
}
|
||||
|
||||
private function updatePhoto(User $user, UploadSessionDto $uploadSession): void
|
||||
{
|
||||
$teamer = $user->getTeamer();
|
||||
|
||||
@@ -61,7 +61,7 @@ class ApplicationFormSubmissionMailer
|
||||
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).
|
||||
// The value, not the applicant's nationality: a flag the form set.
|
||||
'euFieldPresent' => null !== $submission->isEu(),
|
||||
]);
|
||||
|
||||
|
||||
@@ -32,8 +32,7 @@ use Symfony\Component\Uid\Uuid;
|
||||
*
|
||||
* 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).
|
||||
* display only, never a schema, never queried on.
|
||||
*/
|
||||
#[ORM\Entity(repositoryClass: ApplicationFormSubmissionRepository::class)]
|
||||
// What a list and a dedupe check ask for: the submissions of one form, newest first.
|
||||
@@ -129,7 +128,7 @@ class ApplicationFormSubmission implements TimestampableEntityInterface
|
||||
* 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
|
||||
* notification mail 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)]
|
||||
@@ -175,7 +174,7 @@ class ApplicationFormSubmission implements TimestampableEntityInterface
|
||||
/**
|
||||
* 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).
|
||||
* this, build a column from it or migrate old rows to a new spelling.
|
||||
*
|
||||
* 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
|
||||
@@ -189,7 +188,7 @@ class ApplicationFormSubmission implements TimestampableEntityInterface
|
||||
|
||||
/**
|
||||
* 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,
|
||||
* on the way in 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>
|
||||
@@ -214,7 +213,7 @@ class ApplicationFormSubmission implements TimestampableEntityInterface
|
||||
*
|
||||
* 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
|
||||
* side has added and this application does not know yet. Keeping the body is what
|
||||
* makes them backfillable instead of lost.
|
||||
*
|
||||
* @param array<string, mixed> $payload
|
||||
|
||||
@@ -8,8 +8,8 @@ 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:
|
||||
* Two rules from the contract with the TYPO3 side 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
|
||||
@@ -21,8 +21,7 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
* 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).
|
||||
* there is no form-type discriminator.
|
||||
*
|
||||
* 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
|
||||
@@ -334,7 +333,7 @@ class ApplicationFormSubmissionDto
|
||||
/**
|
||||
* 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
|
||||
* TYPO3 strips those before sending, 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>>
|
||||
|
||||
@@ -73,7 +73,7 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
|
||||
$csrfToken = $request->request->getString('_csrf_token');
|
||||
|
||||
return new SelfValidatingPassport(
|
||||
new UserBadge($email, function () use ($email, $password, $request) {
|
||||
new UserBadge($email, function () use ($email, $password) {
|
||||
try {
|
||||
$response = $this->apiClient->getProfile($email, $password);
|
||||
} catch (ApiClientException $e) {
|
||||
@@ -91,9 +91,6 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
|
||||
return null;
|
||||
}
|
||||
|
||||
// Store BPN password in session for later use
|
||||
$request->getSession()->set('bpn_password', $password);
|
||||
|
||||
return $user;
|
||||
}),
|
||||
[
|
||||
|
||||
@@ -12,7 +12,7 @@ use App\Service\Common\PickupOptions;
|
||||
/**
|
||||
* Turns a staffing matrix row into the draft assignments for one travel date.
|
||||
*
|
||||
* The rules, agreed 2026-10-15 (see .ddev/plans/teamer-auto-assignments-plan.md):
|
||||
* The rules, agreed with the stakeholders on 2026-10-15:
|
||||
* - one assignment per role, the role's head count as its places;
|
||||
* - without split, each ski level is a Kursleitung of its own, one place;
|
||||
* - with split, a Reiseleitung takes over each level through the combined profile, one place
|
||||
|
||||
@@ -35,9 +35,8 @@ use Psr\Log\LoggerInterface;
|
||||
* 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.
|
||||
* password, which provisioning deliberately never has, 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
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\BusProNet;
|
||||
|
||||
use App\BusProNet\ApiClient;
|
||||
use App\BusProNet\ApiClientException;
|
||||
use App\BusProNet\ResponseParser;
|
||||
use App\Entity\Embeddable\Address;
|
||||
use App\Entity\Embeddable\Communication;
|
||||
use App\Entity\Teamer;
|
||||
use App\Entity\User;
|
||||
use League\Flysystem\FilesystemOperator;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Log\NullLogger;
|
||||
use Symfony\Component\Serializer\SerializerInterface;
|
||||
|
||||
/**
|
||||
* Pins the request payloads. The serializer is the last step before the socket, so the payload is
|
||||
* captured there and the request aborted - no connection is ever opened.
|
||||
*/
|
||||
class ApiClientTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* Without the password: "login" switches BusPro's password check off and the two ids identify
|
||||
* the person. The element order is the one verified on the BusPro test system.
|
||||
*/
|
||||
public function testUpdateProfileIdentifiesThePersonByIdInsteadOfPassword(): void
|
||||
{
|
||||
$payload = $this->capturePayload(fn (ApiClient $client) => $client->updateProfile($this->user(addressId: 141747, personId: 224526)));
|
||||
|
||||
$this->assertSame('Adressdaten_Ändern', $payload['art']);
|
||||
$this->assertSame('J', $payload['login']);
|
||||
$this->assertSame(141747, $payload['idadresse']);
|
||||
$this->assertSame(224526, $payload['idadresseperson']);
|
||||
$this->assertArrayNotHasKey('passwort', $payload);
|
||||
$this->assertSame(
|
||||
['user', 'key', 'satz', 'art', 'email', 'login', 'idadresse', 'idadresseperson', 'adressdaten'],
|
||||
array_keys($payload),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ids are the whole authorisation of the write, so a user missing one is refused before
|
||||
* anything is sent.
|
||||
*/
|
||||
public function testUpdateProfileRefusesAUserWithoutBothIds(): void
|
||||
{
|
||||
$serializer = $this->createMock(SerializerInterface::class);
|
||||
$serializer->expects($this->never())->method('serialize');
|
||||
|
||||
$this->expectException(ApiClientException::class);
|
||||
|
||||
$this->client($serializer)->updateProfile($this->user(addressId: 141747, personId: null));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable(ApiClient): mixed $request
|
||||
*/
|
||||
private function capturePayload(callable $request): array
|
||||
{
|
||||
$captured = null;
|
||||
|
||||
$serializer = $this->createMock(SerializerInterface::class);
|
||||
$serializer
|
||||
->expects($this->once())
|
||||
->method('serialize')
|
||||
->willReturnCallback(function (mixed $data) use (&$captured): never {
|
||||
$captured = $data;
|
||||
|
||||
throw new \LogicException('Request captured');
|
||||
})
|
||||
;
|
||||
|
||||
try {
|
||||
$request($this->client($serializer));
|
||||
} catch (\LogicException) {
|
||||
}
|
||||
|
||||
$this->assertIsArray($captured);
|
||||
|
||||
return $captured['anfrage'];
|
||||
}
|
||||
|
||||
private function client(SerializerInterface $serializer): ApiClient
|
||||
{
|
||||
return new ApiClient(
|
||||
$serializer,
|
||||
$this->createStub(ResponseParser::class),
|
||||
new NullLogger(),
|
||||
$this->createStub(FilesystemOperator::class),
|
||||
[
|
||||
'bpn_username' => 'api',
|
||||
'bpn_password' => 'secret',
|
||||
'bpn_api_ip' => '127.0.0.1',
|
||||
'bpn_api_port' => 1,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
private function user(?int $addressId, ?int $personId): User
|
||||
{
|
||||
$teamer = new Teamer();
|
||||
$teamer
|
||||
->setFirstName('Anna')
|
||||
->setLastName('Muster')
|
||||
->setGender('F')
|
||||
->setAddress(new Address())
|
||||
->setCommunication(new Communication())
|
||||
;
|
||||
|
||||
$user = new User();
|
||||
$user
|
||||
->setEmail('[email protected]')
|
||||
->setTeamer($teamer)
|
||||
;
|
||||
|
||||
if (null !== $addressId) {
|
||||
$user->setBusProAddressId($addressId);
|
||||
}
|
||||
|
||||
if (null !== $personId) {
|
||||
$user->setBusProPersonId($personId);
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
@@ -194,8 +194,7 @@ 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).
|
||||
* would have returned an empty response with every role flag false.
|
||||
*/
|
||||
public function testParseCrmSelectionWriteResponse(): void
|
||||
{
|
||||
|
||||
@@ -14,8 +14,8 @@ 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
|
||||
* The write itself cannot: the teamer CRM selection is only changeable in the production database,
|
||||
* 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.
|
||||
|
||||
@@ -13,8 +13,8 @@ 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
|
||||
* The cases here are the ones the TYPO3 side actually produces:
|
||||
* 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.
|
||||
*
|
||||
@@ -22,8 +22,7 @@ use Symfony\Component\HttpFoundation\Response;
|
||||
* 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).
|
||||
* one field at a time, because these are the fields a teamer cannot be provisioned without.
|
||||
*/
|
||||
class ApplicationFormControllerTest extends WebTestCase
|
||||
{
|
||||
@@ -412,7 +411,7 @@ class ApplicationFormControllerTest extends WebTestCase
|
||||
|
||||
/**
|
||||
* 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
|
||||
* survive as separate keys. 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
|
||||
@@ -528,7 +527,7 @@ class ApplicationFormControllerTest extends WebTestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* §5.1 is not implemented yet: a double-clicked submit button stores two rows for now, and
|
||||
* Dedupe 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
|
||||
|
||||
@@ -13,7 +13,7 @@ use App\Service\Assignment\AssignmentPlanner;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* One test per row of the planner table in .ddev/plans/teamer-auto-assignments-plan.md.
|
||||
* Pins the rules listed on AssignmentPlanner, one test per case.
|
||||
*/
|
||||
class AssignmentPlannerTest extends TestCase
|
||||
{
|
||||
|
||||
@@ -24,10 +24,9 @@ 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.
|
||||
* rehearsed against BusPro's test database - the teamer selection is changeable in production only.
|
||||
* 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.
|
||||
*/
|
||||
#[AllowMockObjectsWithoutExpectations]
|
||||
class TeamerProvisionerTest extends TestCase
|
||||
|
||||
Reference in new issue
Block a user