Compare commits
42
Commits
05e348e9b7
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
46934e278c | ||
|
|
aebfc2ca9b | ||
|
|
3247df1171 | ||
|
|
6cfaaf1ba9 | ||
|
|
fd3d88209c | ||
|
|
21b00e3bd6 | ||
|
|
e517163c9a | ||
|
|
df564c30ae | ||
|
|
558e45fe5f | ||
|
|
c660bd68de | ||
|
|
55378b2bbc | ||
|
|
ac23baf625 | ||
|
|
a1645784fe | ||
|
|
3d94505e8d | ||
|
|
5942ecf340 | ||
|
|
0b0286787b | ||
|
|
2936d8947a | ||
|
|
0ff312c0c0 | ||
|
|
2b27b9809d | ||
|
|
980e378a7b | ||
|
|
77960fe81f | ||
|
|
9ce42de4c1 | ||
|
|
d50995a21c | ||
|
|
897a1ac7f9 | ||
|
|
2705401393 | ||
|
|
f5894a6bef | ||
|
|
e7df5ac03a | ||
|
|
c16f368293 | ||
|
|
d63fa10a56 | ||
|
|
e8fa71175d | ||
|
|
09610889f3 | ||
|
|
d8fe9a3875 | ||
|
|
e9766dbdce | ||
|
|
b047465339 | ||
|
|
a60bf68345 | ||
|
|
97c6330a9a | ||
|
|
ec36b61275 | ||
|
|
7c8dbeef48 | ||
|
|
e293bd3b1c | ||
|
|
a7b845751b | ||
|
|
234f3a0bd2 | ||
|
|
f794d882ca |
No files matched your search
@@ -19,6 +19,7 @@ composer_version: "2"
|
||||
web_environment: [ ]
|
||||
nodejs_version: "24"
|
||||
corepack_enable: false
|
||||
omit_containers: [ddev-ssh-agent]
|
||||
|
||||
# Key features of DDEV's config.yaml:
|
||||
|
||||
|
||||
@@ -44,6 +44,9 @@ MAILJET_API_KEY=
|
||||
MAILJET_API_SECRET=
|
||||
MAILJET_API_BASE_URL=https://api.mailjet.com/v3/REST
|
||||
MAILJET_DEFAULT_LIST_ID=
|
||||
# Sub-account for the travel mailing lists
|
||||
MAILJET_TRAVEL_MAILING_API_KEY=
|
||||
MAILJET_TRAVEL_MAILING_API_SECRET=
|
||||
# Development default for HTTP Basic Auth password; override in production secrets.
|
||||
MAILJET_WEBHOOK_BASIC_PASSWORD=secret
|
||||
APP_NEWSLETTER_CONFIRMATION_TTL_HOURS=1
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Controller } from '@hotwired/stimulus'
|
||||
|
||||
/*
|
||||
* The navigation (sidebar or header tabs) as a drawer on small screens: a modal <dialog> (target
|
||||
* "dialog"), so focus stays inside and Escape closes it. A click on the dimmed page beside it closes it
|
||||
* too, and so does widening the window until the navigation shows (lg).
|
||||
*/
|
||||
export default class extends Controller {
|
||||
static targets = ['dialog']
|
||||
|
||||
connect () {
|
||||
this.wide = window.matchMedia('(min-width: 64rem)')
|
||||
this.onWide = (event) => event.matches && this.close()
|
||||
this.wide.addEventListener('change', this.onWide)
|
||||
}
|
||||
|
||||
disconnect () {
|
||||
this.wide.removeEventListener('change', this.onWide)
|
||||
}
|
||||
|
||||
open () {
|
||||
this.dialogTarget.showModal()
|
||||
}
|
||||
|
||||
close () {
|
||||
this.dialogTarget.close()
|
||||
}
|
||||
|
||||
// a click on the dialog element itself, not on its content, is a click on the backdrop
|
||||
closeOnBackdrop (event) {
|
||||
if (event.target === this.dialogTarget) {
|
||||
this.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { Controller } from '@hotwired/stimulus'
|
||||
|
||||
/*
|
||||
* A small menu behind a "⋯" button: the button (menu#toggle) opens the panel (target "panel") below
|
||||
* itself. The panel is positioned fixed, so a scrolling container can't cut it off. Escape, a click
|
||||
* outside or a click on one of its items closes it; arrow keys move between the items. Scrolling or
|
||||
* resizing closes it too: a fixed panel would stay put while its row moves away (a table swiped
|
||||
* sideways on a phone).
|
||||
*/
|
||||
export default class extends Controller {
|
||||
static targets = ['button', 'panel']
|
||||
|
||||
connect () {
|
||||
this.onOutside = (event) => {
|
||||
if (!this.element.contains(event.target)) {
|
||||
this.close()
|
||||
}
|
||||
}
|
||||
this.onKey = (event) => this.key(event)
|
||||
this.onScroll = (event) => {
|
||||
if (!this.panelTarget.contains(event.target)) {
|
||||
this.close()
|
||||
}
|
||||
}
|
||||
this.onResize = () => this.close()
|
||||
}
|
||||
|
||||
disconnect () {
|
||||
this.close()
|
||||
}
|
||||
|
||||
toggle (event) {
|
||||
event.stopPropagation()
|
||||
this.panelTarget.hidden ? this.open() : this.close()
|
||||
}
|
||||
|
||||
open () {
|
||||
const box = this.buttonTarget.getBoundingClientRect()
|
||||
const panel = this.panelTarget
|
||||
panel.hidden = false
|
||||
// below the button, aligned to its right edge, and inside the window
|
||||
const left = Math.max(8, Math.min(box.right - panel.offsetWidth, window.innerWidth - panel.offsetWidth - 8))
|
||||
const below = box.bottom + 4 + panel.offsetHeight <= window.innerHeight
|
||||
panel.style.left = `${left}px`
|
||||
panel.style.top = `${below ? box.bottom + 4 : box.top - panel.offsetHeight - 4}px`
|
||||
this.buttonTarget.setAttribute('aria-expanded', 'true')
|
||||
document.addEventListener('click', this.onOutside, true)
|
||||
document.addEventListener('keydown', this.onKey)
|
||||
// capture: scroll events don't bubble, and the scrolling box may be any ancestor
|
||||
document.addEventListener('scroll', this.onScroll, true)
|
||||
window.addEventListener('resize', this.onResize)
|
||||
this.items()[0]?.focus({ preventScroll: true })
|
||||
}
|
||||
|
||||
close () {
|
||||
if (this.panelTarget.hidden) {
|
||||
return
|
||||
}
|
||||
this.panelTarget.hidden = true
|
||||
this.buttonTarget.setAttribute('aria-expanded', 'false')
|
||||
document.removeEventListener('click', this.onOutside, true)
|
||||
document.removeEventListener('keydown', this.onKey)
|
||||
document.removeEventListener('scroll', this.onScroll, true)
|
||||
window.removeEventListener('resize', this.onResize)
|
||||
}
|
||||
|
||||
// an item was chosen: it does its own work (htmx, link), the menu only closes
|
||||
choose () {
|
||||
this.close()
|
||||
}
|
||||
|
||||
key (event) {
|
||||
const items = this.items()
|
||||
const index = items.indexOf(document.activeElement)
|
||||
if (event.key === 'Escape') {
|
||||
event.stopPropagation()
|
||||
this.close()
|
||||
this.buttonTarget.focus()
|
||||
} else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
|
||||
event.preventDefault()
|
||||
const next = (index + (event.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length
|
||||
items[next]?.focus()
|
||||
}
|
||||
}
|
||||
|
||||
items () {
|
||||
return [...this.panelTarget.querySelectorAll('a, button:not([disabled])')]
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import { Controller } from '@hotwired/stimulus'
|
||||
|
||||
export default class extends Controller {
|
||||
static outlets = [ 'mobilenav' ]
|
||||
static classes = [ 'closed' ]
|
||||
|
||||
trigger({ params: { mode } }) {
|
||||
this.mobilenavOutlet.toggle(mode)
|
||||
}
|
||||
|
||||
toggle(mode) {
|
||||
// Add animation classes only now to avoid fouc
|
||||
this.element.classList.add('transition-transform', 'duration-300')
|
||||
this.element.classList.toggle(this.closedClass, 'close' === mode)
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import { Controller } from '@hotwired/stimulus'
|
||||
|
||||
export default class extends Controller {
|
||||
|
||||
static classes = ['closed', 'iconClosed', 'iconExpanded']
|
||||
static targets = ['submenu', 'button', 'icon']
|
||||
static values = { expanded: Boolean }
|
||||
|
||||
toggleSubmenu() {
|
||||
this.expandedValue = !this.expandedValue
|
||||
}
|
||||
|
||||
expandedValueChanged(expanded) {
|
||||
this.submenuTarget.classList.toggle(this.closedClass, false === expanded)
|
||||
if (false === this.hasButtonTarget) {
|
||||
return
|
||||
}
|
||||
this.buttonTarget.setAttribute('aria-expanded', expanded)
|
||||
if (false === this.hasIconTarget) {
|
||||
return
|
||||
}
|
||||
if (true === expanded) {
|
||||
this.iconTarget.classList.add(...this.iconExpandedClasses)
|
||||
this.iconTarget.classList.remove(...this.iconClosedClasses)
|
||||
} else {
|
||||
this.iconTarget.classList.add(...this.iconClosedClasses)
|
||||
this.iconTarget.classList.remove(...this.iconExpandedClasses)
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
<svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" viewBox="0 0 500 153" xmlns="http://www.w3.org/2000/svg"><g fill="#0084d4"><path d="m332.922 85.597c4.527 0 7.819 3.292 7.819 7.819 0 4.115-2.675 6.79-5.762 7.613l6.791 11.934h-3.704l-6.379-11.523h-7.613v11.523h-3.292v-27.366zm-8.642 12.963h8.642c2.469 0 4.527-2.058 4.527-5.144 0-3.293-2.264-5.144-5.35-5.144h-7.819z" fill-rule="nonzero"/><path d="m374.28 85.597v2.88h-15.432v9.877h13.374v2.881h-13.374v9.053h15.843v2.675h-19.135v-27.366z" fill-rule="nonzero"/><path d="m389.095 85.597h3.292v27.366h-3.292z"/><path d="m406.79 111.317.823-2.675c1.029.411 4.733 1.852 8.436 1.852 4.527 0 6.791-1.852 6.791-4.527 0-3.498-3.498-4.321-6.996-5.35-4.321-1.234-8.848-2.675-8.848-8.024 0-4.939 3.704-7.408 9.259-7.408 3.292 0 6.79 1.029 8.642 1.852l-.823 2.675s-4.115-1.646-7.613-1.646c-3.704 0-6.173 1.852-6.173 4.527 0 3.292 3.704 4.321 6.996 5.349 4.321 1.235 8.848 2.675 8.848 8.025 0 5.144-4.116 7.407-9.671 7.407-4.321 0-8.025-1.234-9.671-2.057z" fill-rule="nonzero"/><path d="m458.848 85.597v2.88h-15.432v9.877h13.374v2.881h-13.374v9.053h15.843v2.675h-19.136v-27.366z" fill-rule="nonzero"/><path d="m476.955 85.597 8.642 12.963 5.967 9.259-.206-9.259v-12.963h3.292v27.366h-3.498l-8.642-13.375-5.761-9.053.206 9.259v13.169h-3.292v-27.366z" fill-rule="nonzero"/><path d="m339.712 123.663v2.88h-15.432v9.877h13.374v2.88h-13.374v9.054h15.843v2.881h-19.135v-27.572z" fill-rule="nonzero"/><path d="m352.263 123.663 8.231 23.251 8.23-23.251h3.498l-9.876 27.366h-3.704l-9.877-27.366z" fill-rule="nonzero"/><path d="m401.44 123.663v2.88h-15.432v9.877h13.375v2.88h-13.375v9.054h15.844v2.881h-19.136v-27.572z" fill-rule="nonzero"/><path d="m416.872 123.663 8.642 12.963 5.967 9.259-.205-9.259v-12.963h3.292v27.366h-3.498l-8.642-13.375-5.761-9.053.205 9.259v13.169h-3.292v-27.366z" fill-rule="nonzero"/><path d="m466.872 123.457v3.086h-9.259v24.486h-3.292v-24.692h-9.259v-2.88z" fill-rule="nonzero"/><path d="m475.309 149.177.823-2.675c1.028.412 4.732 1.852 8.436 1.852 4.527 0 6.79-1.852 6.79-4.527 0-3.498-3.498-4.321-6.996-5.35-4.321-1.234-8.848-2.675-8.848-8.024 0-4.939 3.704-7.408 9.26-7.408 3.292 0 6.79 1.029 8.642 1.852l-.823 2.675s-4.116-1.646-7.614-1.646c-3.703 0-6.172 1.852-6.172 4.527 0 3.292 3.703 4.321 6.995 5.349 4.321 1.235 8.848 2.675 8.848 8.025 0 5.144-4.115 7.408-9.671 7.408-4.115 0-8.024-1.235-9.67-2.058z" fill-rule="nonzero"/><path d="m367.695 1.852v10.905h-33.333v17.078h28.395v11.112h-28.395v15.637h33.951v10.906h-47.12v-65.638z" fill-rule="nonzero"/><path d="m418.93 16.255c0 5.556-3.292 11.729-10.7 16.255l11.317 13.169s2.264-4.115 2.264-9.465h9.876c-.206 10.082-4.938 17.901-4.938 17.901l12.14 13.992h-14.609l-4.938-5.761c-4.527 3.909-10.494 6.173-17.284 6.173-12.346 0-23.457-7.202-23.457-20.782 0-8.848 5.761-14.404 11.728-18.519-3.292-4.321-5.761-7.202-5.761-12.963 0-11.317 9.465-15.638 16.872-15.638 7.408 0 17.49 4.321 17.49 15.638zm-28.189 31.276c0 6.173 4.526 10.082 11.728 10.082 3.704 0 6.996-1.029 9.671-3.292l-14.403-16.667c-4.116 2.264-6.996 5.35-6.996 9.877zm5.967-30.659c0 3.293 2.057 5.144 4.321 7.614 3.704-1.646 6.378-4.527 6.378-7.819 0-3.91-2.674-5.35-5.349-5.35-3.498 0-5.35 2.263-5.35 5.555z" fill-rule="nonzero"/><path d="m479.424 1.852c11.111 0 20.164 9.259 20.164 20.988 0 12.551-9.053 21.399-19.958 21.399h-15.844v23.456h-13.169v-65.843zm-15.638 31.276h13.169c6.173 0 9.671-4.527 9.671-10.288 0-7.202-5.556-9.877-10.7-9.877h-12.14z" fill-rule="nonzero"/><path d="m220.165.617c-74.898 11.317-167.902 39.301-167.902 78.601 0 36.42 86.009 27.161 86.009 27.161s-137.86 45.884-137.86-14.404c0-68.312 173.868-91.358 219.753-91.358z" fill-rule="nonzero"/></g><path d="m34.979 151.235c74.898-11.112 167.902-39.301 167.902-78.601 0-36.42-86.009-27.161-86.009-27.161s137.861-45.885 137.861 14.404c0 68.518-173.869 91.358-219.754 91.358z" fill="#f8c62f" fill-rule="nonzero"/><path d="m124.897 70.576-26.337 8.231 25.103 1.646-.823-4.939z" fill="#0084d4" fill-rule="nonzero"/><path d="m156.173 72.428-18.93 5.967-7.202 19.959-3.498-23.251 8.231-22.017 3.498 16.256z" fill="#f8c62f" fill-rule="nonzero"/></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1,64 @@
|
||||
/* Admin-only additions to ep-design.css, built on its tokens */
|
||||
@layer base {
|
||||
.htmx-indicator {
|
||||
@apply invisible;
|
||||
}
|
||||
|
||||
.htmx-request .htmx-indicator,
|
||||
.htmx-request.htmx-indicator {
|
||||
@apply visible;
|
||||
}
|
||||
|
||||
/* checked boxes and radios in the brand colour (@tailwindcss/forms fills them with currentColor) */
|
||||
[type="checkbox"],
|
||||
[type="radio"] {
|
||||
@apply text-brand;
|
||||
}
|
||||
|
||||
/* thin scrollbars without a track for inner scrolling areas, as in app.css */
|
||||
body * {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--color-line) transparent;
|
||||
}
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.badge {
|
||||
@apply inline-flex items-center px-1.5 py-0.5 text-xs font-bold whitespace-nowrap;
|
||||
}
|
||||
|
||||
.tippy-box {
|
||||
@apply bg-brand;
|
||||
}
|
||||
|
||||
.tippy-box[data-placement^='top'] > .tippy-arrow::before {
|
||||
border-top-color: var(--color-brand);
|
||||
}
|
||||
|
||||
.tippy-box[data-placement^='bottom'] > .tippy-arrow::before {
|
||||
border-bottom-color: var(--color-brand);
|
||||
}
|
||||
|
||||
.tippy-box[data-placement^='left'] > .tippy-arrow::before {
|
||||
border-left-color: var(--color-brand);
|
||||
}
|
||||
|
||||
.tippy-box[data-placement^='right'] > .tippy-arrow::before {
|
||||
border-right-color: var(--color-brand);
|
||||
}
|
||||
}
|
||||
|
||||
/* a list in a card, scrolling sideways when it is wider than the content column */
|
||||
@layer components {
|
||||
.data-table-wrapper {
|
||||
@apply mb-8 overflow-x-auto border border-line bg-white;
|
||||
}
|
||||
|
||||
.data-table-wrapper__inner {
|
||||
@apply min-w-full align-middle;
|
||||
}
|
||||
|
||||
.data-table tbody tr {
|
||||
@apply hover:bg-brand-light/50;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
@import "./components/autocomplete.css";
|
||||
@import "./components/badge.css";
|
||||
@import "./components/button.css";
|
||||
@import "./components/datatable.css";
|
||||
@import "./components/datepicker.css";
|
||||
@import "./components/forms.css";
|
||||
@import "./components/pagination.css";
|
||||
@import "./components/toast.css";
|
||||
@import "./components/tooltip.css";
|
||||
@import "./components/typography.css";
|
||||
+11
-3
@@ -1,4 +1,12 @@
|
||||
/* The admin in the E&P corporate design; shares nothing with app.css, so the frontend stays as it is */
|
||||
@import "tailwindcss" source(none);
|
||||
@import "./_theme.css";
|
||||
@import "./_base.css" layer(base);
|
||||
@import "./_components_admin.css" layer(components);
|
||||
@import "toastify-js/src/toastify.css" layer(base);
|
||||
@import "tippy.js/dist/tippy.css" layer(base);
|
||||
@import "./ep-design.css";
|
||||
@import "./_admin.css";
|
||||
|
||||
@source "../../templates";
|
||||
@source "../../src";
|
||||
@source "../../assets";
|
||||
|
||||
@plugin "@tailwindcss/forms";
|
||||
@@ -0,0 +1,377 @@
|
||||
/*
|
||||
* E&P corporate design for the internal Symfony tools, taken from the E&P apps template (Gitea EP/apps,
|
||||
* frontend/app/globals.css, frontend/components/): Lato, deep blue as the brand colour, magenta only
|
||||
* for the one main action of a page, square shapes, light blue page.
|
||||
* Status colours (green, red, amber) always come with text, never alone.
|
||||
*
|
||||
* Import after Tailwind: @import "tailwindcss"; @import "./ep-design.css"; @plugin "@tailwindcss/forms";
|
||||
* The toast styles expect toastify-js, imported into the base layer before this file:
|
||||
* @import "toastify-js/src/toastify.css" layer(base); unlayered (or through its own <link>), its
|
||||
* colours and gradient beat these layered styles whatever their specificity.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Lato (OFL) ships with the app, so browsers load nothing from Google: 400 (and italic), 700, 900. No 600:
|
||||
* font-semibold renders as 700, like font-bold; font-black is 900. The weights are not remapped.
|
||||
*/
|
||||
@font-face {
|
||||
font-family: "Lato";
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("../fonts/lato-400.woff2") format("woff2");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Lato";
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("../fonts/lato-400-italic.woff2") format("woff2");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Lato";
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url("../fonts/lato-700.woff2") format("woff2");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Lato";
|
||||
font-style: normal;
|
||||
font-weight: 900;
|
||||
font-display: swap;
|
||||
src: url("../fonts/lato-900.woff2") format("woff2");
|
||||
}
|
||||
|
||||
@theme {
|
||||
--font-sans: "Lato", ui-sans-serif, system-ui, sans-serif;
|
||||
|
||||
/* square everywhere; rounded-full stays round. Plain `rounded` reads --radius. */
|
||||
--radius: 0px;
|
||||
--radius-xs: 0px;
|
||||
--radius-sm: 0px;
|
||||
--radius-md: 0px;
|
||||
--radius-lg: 0px;
|
||||
--radius-xl: 0px;
|
||||
--radius-2xl: 0px;
|
||||
--radius-3xl: 0px;
|
||||
--radius-4xl: 0px;
|
||||
|
||||
--color-brand: #18527b; /* E&P deep blue, 8.5:1 on white */
|
||||
--color-brand-dark: #103c5b;
|
||||
--color-brand-mid: #165883;
|
||||
--color-brand-bright: #009fff; /* underlines and focus, never text */
|
||||
--color-brand-light: #e3eef8;
|
||||
|
||||
--color-page: #ebf3fa; /* page background */
|
||||
--color-line: #d8e3ed; /* borders */
|
||||
--color-ink: #27272a; /* text */
|
||||
--color-muted: #52525b; /* secondary text, 7.7:1 on white */
|
||||
|
||||
--color-accent: #c4097c; /* magenta of the main action */
|
||||
--color-accent-from: #960167;
|
||||
--color-accent-to: #fa1a8c;
|
||||
}
|
||||
|
||||
/*
|
||||
* Tailwind 3 defaults that Tailwind 4 changed: borders were a light gray instead of currentColor,
|
||||
* and buttons had a pointer cursor.
|
||||
*/
|
||||
@layer base {
|
||||
*,
|
||||
::after,
|
||||
::before,
|
||||
::backdrop,
|
||||
::file-selector-button {
|
||||
border-color: var(--color-line, currentcolor);
|
||||
}
|
||||
|
||||
button:not(:disabled),
|
||||
[role="button"]:not(:disabled) {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* text size of every E&P app: 14px; text-base (16px) and up only for headings */
|
||||
body {
|
||||
font-size: var(--text-sm);
|
||||
line-height: var(--text-sm--line-height);
|
||||
}
|
||||
|
||||
/* modals: centred (Preflight resets the browser's margin: auto), the page behind dimmed and blurred */
|
||||
dialog:modal {
|
||||
margin: auto;
|
||||
max-height: 85vh;
|
||||
}
|
||||
|
||||
dialog::backdrop {
|
||||
background: rgb(39 39 42 / 0.35);
|
||||
backdrop-filter: blur(3px);
|
||||
}
|
||||
|
||||
/* visible keyboard focus everywhere (WCAG 2.4.7) */
|
||||
:where(a, button, input, select, textarea, summary, [tabindex]):focus-visible {
|
||||
outline: 3px solid var(--color-brand-bright);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Components as in the apps template (frontend/components/ui.ts, Field.tsx, Alert.tsx). Magenta
|
||||
* only for the one main action of a page.
|
||||
*/
|
||||
@layer components {
|
||||
.btn,
|
||||
.btn-primary,
|
||||
.btn-secondary {
|
||||
@apply inline-flex items-center justify-center gap-2 px-4 py-2.5 text-xs font-bold uppercase tracking-wide no-underline transition-colors disabled:cursor-not-allowed;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
@apply text-white;
|
||||
background-image: linear-gradient(120deg, var(--color-accent-from), #9e036a 40%, var(--color-accent-to));
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background-image: linear-gradient(120deg, #7d0156, #8a035d 40%, #e3107c);
|
||||
}
|
||||
|
||||
.btn-primary:disabled {
|
||||
background-image: none;
|
||||
background-color: #64748b;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
@apply border border-brand bg-white text-brand hover:bg-brand hover:text-white;
|
||||
}
|
||||
|
||||
/* small actions in toolbars and on cards, next to the one main action */
|
||||
.btn-tool {
|
||||
@apply inline-flex items-center gap-1 rounded border border-line bg-white px-2 py-1 text-sm text-ink hover:border-brand hover:text-brand disabled:cursor-default disabled:border-line disabled:text-gray-400;
|
||||
}
|
||||
|
||||
/* the "⋯" behind which the actions of a card or row wait (menu_controller.js); finger-sized on touch screens */
|
||||
.btn-more {
|
||||
@apply inline-flex h-6 w-6 pointer-coarse:h-10 pointer-coarse:w-10 shrink-0 items-center justify-center rounded text-muted hover:bg-page hover:text-brand aria-expanded:bg-page aria-expanded:text-brand;
|
||||
}
|
||||
|
||||
.menu-panel {
|
||||
@apply fixed z-40 min-w-48 border border-line bg-white py-1 text-sm shadow-lg;
|
||||
}
|
||||
|
||||
.menu-item {
|
||||
@apply block w-full px-3 py-1.5 pointer-coarse:py-3 text-left text-ink no-underline hover:bg-page hover:text-brand focus:bg-page;
|
||||
}
|
||||
|
||||
.menu-item-danger {
|
||||
@apply block w-full px-3 py-1.5 pointer-coarse:py-3 text-left text-red-800 hover:bg-page hover:text-red-900 focus:bg-page;
|
||||
}
|
||||
|
||||
.input {
|
||||
@apply block w-full border border-slate-500 bg-white px-3 py-2 text-sm text-slate-900 placeholder:text-slate-500 focus:border-brand-bright aria-[invalid=true]:border-red-700 aria-[invalid=true]:ring-1 aria-[invalid=true]:ring-red-700 disabled:bg-slate-100 disabled:text-slate-600;
|
||||
}
|
||||
|
||||
.field-label {
|
||||
@apply block text-xs font-bold uppercase tracking-wide text-slate-700;
|
||||
}
|
||||
|
||||
/* white box on the light blue page */
|
||||
.card {
|
||||
@apply border border-line bg-white;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
@apply text-base font-bold uppercase tracking-wide text-brand;
|
||||
}
|
||||
|
||||
/* a row of tabs; the base line is an inset shadow, so a row that scrolls sideways doesn't scroll vertically too */
|
||||
.tabs {
|
||||
@apply flex overflow-x-auto shadow-[inset_0_-1px_0_var(--color-line)];
|
||||
}
|
||||
|
||||
.tab {
|
||||
@apply shrink-0 whitespace-nowrap border-b-4 border-transparent px-3 py-2 text-sm text-ink no-underline hover:text-brand;
|
||||
}
|
||||
|
||||
.tab[aria-current],
|
||||
.tab[aria-selected="true"] {
|
||||
@apply border-brand-bright font-bold text-brand;
|
||||
}
|
||||
|
||||
/* the main views as tabs in the header (_partials/_header.html.twig), for apps with few views */
|
||||
.header-tab {
|
||||
@apply flex items-center whitespace-nowrap border-b-4 border-transparent px-3 text-ink no-underline hover:text-brand;
|
||||
}
|
||||
|
||||
.header-tab[aria-current] {
|
||||
@apply border-brand-bright font-bold text-brand;
|
||||
}
|
||||
|
||||
/*
|
||||
* Sidebar navigation for apps with many views (_partials/_sidebar_menu.html.twig): on the light
|
||||
* blue page, the current item is a white box.
|
||||
*/
|
||||
.sidebar-heading {
|
||||
@apply px-2 pt-5 pb-1 text-[11px] font-bold uppercase tracking-wide text-muted;
|
||||
}
|
||||
|
||||
.sidebar-link {
|
||||
@apply flex w-full items-center gap-x-3 p-2 text-left text-sm leading-6 font-bold text-ink no-underline hover:bg-white/60 hover:text-brand;
|
||||
}
|
||||
|
||||
.sidebar-sublink {
|
||||
@apply block py-2 pr-2 pl-10 text-sm leading-6 text-ink no-underline hover:bg-white/60 hover:text-brand;
|
||||
}
|
||||
|
||||
:is(.sidebar-link, .sidebar-sublink)[aria-current],
|
||||
.sidebar-link--ancestor {
|
||||
@apply bg-white text-brand;
|
||||
}
|
||||
|
||||
.sidebar-group > summary {
|
||||
@apply list-none;
|
||||
}
|
||||
|
||||
.sidebar-group > summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* chevron of a group that opens in place */
|
||||
.sidebar-group > summary::after {
|
||||
@apply ml-auto size-2 shrink-0 rotate-45 border-r-2 border-b-2 border-current opacity-60 transition-transform content-[''];
|
||||
}
|
||||
|
||||
.sidebar-group[open] > summary::after {
|
||||
@apply -rotate-135;
|
||||
}
|
||||
|
||||
/* the navigation (sidebar or header tabs) as a drawer from the left on small screens (drawer_controller.js) */
|
||||
dialog.drawer {
|
||||
@apply m-0 h-dvh max-h-none w-80 max-w-[calc(100vw-4rem)] bg-page p-0;
|
||||
}
|
||||
|
||||
/*
|
||||
* a modal dialog doesn't stop the page behind it from scrolling: on touch screens the page took the
|
||||
* gesture first, and a long navigation in the drawer only scrolled once the page was at its end.
|
||||
* Only for the drawer: locking for every dialog:modal would hide the page's scrollbar under a
|
||||
* desktop modal and shift the layout sideways.
|
||||
*/
|
||||
html:has(dialog.drawer:modal) {
|
||||
@apply overflow-hidden;
|
||||
}
|
||||
|
||||
/* lists in a card: the outer cells line up with the card's padding */
|
||||
.data-table {
|
||||
@apply w-full;
|
||||
}
|
||||
|
||||
.data-table thead tr {
|
||||
@apply border-b-2 border-brand text-left text-[11px] font-bold uppercase tracking-wide text-brand;
|
||||
}
|
||||
|
||||
.data-table th {
|
||||
@apply px-2 py-2;
|
||||
}
|
||||
|
||||
.data-table td {
|
||||
@apply px-2 py-1.5;
|
||||
}
|
||||
|
||||
.data-table :is(th, td):first-child {
|
||||
@apply pl-5;
|
||||
}
|
||||
|
||||
.data-table :is(th, td):last-child {
|
||||
@apply pr-5;
|
||||
}
|
||||
|
||||
.data-table tbody tr {
|
||||
@apply border-b last:border-b-0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Lists of entries in a card, as on a dashboard (components/dashboard/): one line per entry, the
|
||||
* whole line is the link or button, its parts separated by a dot, the text cut off with "…".
|
||||
*/
|
||||
.entry-list {
|
||||
@apply divide-y divide-line;
|
||||
}
|
||||
|
||||
.entry-list > li {
|
||||
@apply py-2 first:pt-0 last:pb-0;
|
||||
}
|
||||
|
||||
/* a work queue that would otherwise grow the card without limit; keep it rare, it scrolls awkwardly on phones */
|
||||
.entry-list--scroll {
|
||||
@apply max-h-64 overflow-y-auto pr-3;
|
||||
}
|
||||
|
||||
.entry-link {
|
||||
@apply flex w-full min-w-0 items-center gap-1.5 text-left text-ink no-underline;
|
||||
}
|
||||
|
||||
:is(a, button).entry-link {
|
||||
@apply hover:text-brand;
|
||||
}
|
||||
|
||||
.entry-link > * {
|
||||
@apply shrink-0;
|
||||
}
|
||||
|
||||
/* the text after the icon: one line, cut off as a whole with "…" */
|
||||
.entry-text {
|
||||
@apply min-w-0 shrink truncate;
|
||||
}
|
||||
|
||||
/* icons and dots inside the text flow with it (Tailwind's preflight makes svg a block) */
|
||||
.entry-text :is(svg, img) {
|
||||
@apply inline-block align-middle;
|
||||
}
|
||||
|
||||
.entry-dot {
|
||||
@apply text-muted;
|
||||
}
|
||||
|
||||
/* notices (_partials/_alert.html.twig): light, with a coloured bar on the left */
|
||||
.notice {
|
||||
@apply border-l-4 px-4 py-2;
|
||||
}
|
||||
|
||||
/* toasts (toast_controller.js) in the colours of the notices */
|
||||
.toastify {
|
||||
@apply max-w-sm rounded-none border-l-4 bg-none px-4 py-3 text-sm shadow-lg;
|
||||
}
|
||||
|
||||
.toastify--success {
|
||||
@apply border-emerald-700 bg-emerald-50 text-emerald-950;
|
||||
}
|
||||
|
||||
.toastify--error {
|
||||
@apply border-red-700 bg-red-50 text-red-950;
|
||||
}
|
||||
|
||||
.toastify--warning {
|
||||
@apply border-amber-600 bg-amber-50 text-amber-950;
|
||||
}
|
||||
|
||||
.toastify--info {
|
||||
@apply border-brand bg-brand-light text-ink;
|
||||
}
|
||||
|
||||
.toastify .toast-close {
|
||||
@apply ml-3 text-current opacity-60 hover:opacity-100;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
Generated
+898
-632
File diff suppressed because it is too large.
Load diff
@@ -1,3 +1,3 @@
|
||||
knp_menu:
|
||||
twig:
|
||||
template: _partials/_menu.html.twig
|
||||
template: admin/_partials/_sidebar_menu.html.twig
|
||||
@@ -29,6 +29,10 @@ zenstruck_schedule:
|
||||
frequency: "45 1 * * *"
|
||||
description: "Removes expired pending newsletter double opt-in requests"
|
||||
|
||||
- task: app:cleanup:travel-mailing-lists
|
||||
frequency: "50 1 * * *"
|
||||
description: "Deletes Mailjet travel mailing lists and their orphaned contacts 30 days after the travel started"
|
||||
|
||||
- task: league:oauth2-server:clear-expired-tokens
|
||||
frequency: "0 * * * *"
|
||||
description: "Removes expired oauth2 tokens hourly"
|
||||
|
||||
@@ -426,6 +426,9 @@ services:
|
||||
App\BpnConnect\TravelsClient:
|
||||
parent: App\BpnConnect\AbstractApiClient
|
||||
|
||||
App\BpnConnect\RoomsClient:
|
||||
parent: App\BpnConnect\AbstractApiClient
|
||||
|
||||
App\ClickUp\ApiClient:
|
||||
arguments:
|
||||
$apiToken: '%env(default::CLICKUP_API_TOKEN)%'
|
||||
@@ -441,6 +444,20 @@ services:
|
||||
$defaultListId: '%env(default::MAILJET_DEFAULT_LIST_ID)%'
|
||||
$contactMetadataFields: '%mailjet_contact_metadata_fields%'
|
||||
|
||||
# Travel mailing lists live in a Mailjet sub-account, which has its own key pair and keeps
|
||||
# its contacts and lists apart from the newsletter on the main account.
|
||||
app.mailjet.travel_mailing_client:
|
||||
class: App\Mailjet\ApiClient
|
||||
arguments:
|
||||
$apiKey: '%env(default::MAILJET_TRAVEL_MAILING_API_KEY)%'
|
||||
$apiSecret: '%env(default::MAILJET_TRAVEL_MAILING_API_SECRET)%'
|
||||
$apiBaseUrl: '%env(default::MAILJET_API_BASE_URL)%'
|
||||
$contactMetadataFields: '%mailjet_contact_metadata_fields%'
|
||||
|
||||
App\Service\TravelMailingListManager:
|
||||
arguments:
|
||||
$mailjet: '@app.mailjet.travel_mailing_client'
|
||||
|
||||
App\EventListener\MaintenanceModeListener:
|
||||
arguments:
|
||||
$options:
|
||||
|
||||
@@ -268,6 +268,14 @@ page-consistency rule as `GET /api/exports/travels` above; only the rows differ.
|
||||
`Buchungsstop` rooms and services, rooms without a price and boarding points with id `0` are all emitted. Which of
|
||||
them a website shows, and how, is the client's rule, not this endpoint's.
|
||||
|
||||
**Which rooms can be booked.** Each room carries `bookable`, the one derived field: `true` exactly when the
|
||||
booking flow offers the room for a new booking. That is status `Frei` with `available` above 0. A room on request
|
||||
(`Anfrage`) is not bookable even with rooms left, because booking it would only produce an inquiry, unless its
|
||||
`code` ends in `Anf` (case-sensitive, e.g. `6erSDAnf`): the office sells such a room on request on purpose, it is
|
||||
`bookable`, and booking it makes the whole booking an inquiry. No room with `available` 0 or `null` is bookable. Show a room that is not bookable as sold out and do not count it towards places
|
||||
or the "ab" price. Read `bookable` rather than deriving it from `status` and `available`, so a change to the rule
|
||||
reaches you without a client change.
|
||||
|
||||
At current volumes the export is ~420 rows and ~3.8 MB of JSON (a row is 4–24 kB), so the default `perPage=500`
|
||||
returns it in one page.
|
||||
|
||||
@@ -313,6 +321,7 @@ returns it in one page.
|
||||
"price": 229,
|
||||
"available": 24,
|
||||
"status": "Frei",
|
||||
"bookable": true,
|
||||
"boardCode": "Lt. Auss.",
|
||||
"boardBusProId": 2
|
||||
}
|
||||
@@ -507,21 +516,74 @@ Errors: `400 {"error":"Hotel not found for hotelCode."}`, `400` with violations
|
||||
|
||||
`502 {"error":"Failed to fetch contingent data."}` is still returned — with the same body as before — but it now means **"no usable local snapshot for this hotel"** rather than "the upstream call failed": either the hotel has never synced successfully, or its last successful sync is more than 6 hours old. Treat it as before: the data is unavailable, not empty. This matters because the alternative would be a `200` reporting every day as `BLOCKED`, which is indistinguishable from a genuinely fully-booked hotel.
|
||||
|
||||
#### `GET /api/contingents/availability?hotelCode=…&dateFrom=…&dateTo=…` — scope `api`
|
||||
|
||||
The raw contingent snapshot per day, without prices. Built for the iCal feed that external booking portals import, which blocks only what the contingent itself reports as unavailable.
|
||||
|
||||
Parameters are the same as for `calendar`: `hotelCode` is required, `dateFrom` and `dateTo` are optional, `Y-m-d`, inclusive, and must be supplied together (at most 366 days). **Omit both to get every snapshot day from today to the end of the snapshot** (the 24-month sync horizon). Prices play no part in that span.
|
||||
|
||||
Each entry, ordered by date:
|
||||
|
||||
```json
|
||||
{"date": "2027-01-30", "status": "BLOCKED"}
|
||||
```
|
||||
|
||||
`status` is `OK`, `BLOCKED` or `ON_REQUEST`.
|
||||
|
||||
Two differences from `calendar`:
|
||||
|
||||
- **No price rule.** A day without a maintained price keeps the status the contingent reports; it is not forced to `BLOCKED`.
|
||||
- **Days the snapshot lacks are left out**, not returned as `BLOCKED`. The response is not contiguous: a day without an entry has no availability data, and the feed shows it as free, as it did when it read the upstream service directly.
|
||||
|
||||
- **Not limited to accommodations.** `hotelCode` may be any synced hotel code: an accommodation's calendar code, or the calendar hotel of a visible TYPO3 product (TYPO3's `/api/calendar-hotels`). Winter-only hotels without an accommodation are therefore served here, while `calendar` and `prices` still need an accommodation, since they need its prices.
|
||||
|
||||
Errors are the same as for `calendar`: `400 {"error":"Hotel not found for hotelCode."}` when the code is not synced, `400` with violations for invalid parameters, and `502 {"error":"Failed to fetch contingent data."}` when there is no usable snapshot. For this endpoint the `502` is the important one: an empty list would show every day as free, so a consumer should answer with an error and let the portals keep their last import.
|
||||
|
||||
#### `GET /api/contingents/status` — scope `api`
|
||||
|
||||
One row per synced hotel code, sorted by code, for an overview of which hotel supports which calendar:
|
||||
|
||||
```json
|
||||
{
|
||||
"hotelCode": "DGS",
|
||||
"name": "Sportclub Spinabad",
|
||||
"sources": ["accommodation", "typo3"],
|
||||
"accommodation": {"name": "Davos Glaris - Gruppenhaus Spinabad", "cmsCode": "DGSGRP"},
|
||||
"pricedFrom": "2027-06-01",
|
||||
"pricedTo": "2027-09-30",
|
||||
"syncedAt": "2026-10-29T10:15:00+01:00",
|
||||
"lastError": null,
|
||||
"failureCount": 0,
|
||||
"available": true
|
||||
}
|
||||
```
|
||||
|
||||
- `sources`: where the code comes from, `accommodation` and/or `typo3`.
|
||||
- `name`: the hotel's name in TYPO3's calendar hotel list, `null` for a code TYPO3 does not list.
|
||||
- `accommodation`: `null` without one; `cmsCode` is the code the accommodation is known by in TYPO3, which may differ from `hotelCode`.
|
||||
- `pricedFrom`/`pricedTo`: the span of the accommodation's prices, `null` without prices. `calendar` and `prices` work only for hotels that have them.
|
||||
- `syncedAt`, `lastError`, `failureCount`: the last successful sync (`null` if none) and the failures since.
|
||||
- `available`: whether `availability` currently serves the hotel, i.e. it has synced within the last 6 hours. `false` means that endpoint answers `502`.
|
||||
|
||||
---
|
||||
|
||||
### Operating the snapshot (deployment)
|
||||
|
||||
The snapshot is a new table populated by the scheduler, so it is **empty immediately after a deploy that runs the migration**. Until the first successful sync every hotel returns `502` — deliberately, so no consumer caches a fully-blocked calendar as if it were real availability.
|
||||
The snapshot is filled only by the scheduler, so on an empty database (a new environment, or after the snapshot tables were truncated) every hotel returns `502` until the first successful sync — deliberately, so no consumer caches a fully-blocked calendar as if it were real availability.
|
||||
|
||||
Rollout order:
|
||||
Bringing up an environment:
|
||||
|
||||
1. **Confirm `BPN_CONNECT_API_KEY` is valid for the target environment before deploying.** If it is rejected the sync cannot populate anything and the endpoint stays at `502`.
|
||||
2. Deploy; `database:migrate` creates the empty tables.
|
||||
3. Run `bin/console app:bpn:sync-contingents` on the host, promptly and ideally off-peak — a consumer that page-caches whatever it renders from a `502` may hold that for the length of its own cache period.
|
||||
4. Verify: `contingent_sync_state.synced_at` populated and `failure_count` at 0 for every hotel, then spot-check one calendar response.
|
||||
1. **Confirm `BPN_CONNECT_API_KEY` is valid for the environment.** If it is rejected the sync cannot populate anything and the endpoints stay at `502`.
|
||||
2. Deploy; `database:migrate` creates the tables.
|
||||
3. Run `bin/console app:bpn:sync-contingents -v` on the host promptly, ideally off-peak — a consumer that page-caches whatever it renders from a `502` may hold that for the length of its own cache period.
|
||||
4. Verify with `GET /api/contingents/status`: every row `available: true`, `failureCount` 0.
|
||||
|
||||
Thereafter the scheduler keeps it current; a sync failing for one hotel puts only that hotel into `502` and leaves the rest serving normally.
|
||||
|
||||
**Which hotels are synced.** Every accommodation's calendar code plus every code in TYPO3's `/api/calendar-hotels` (same `APP_CMS_API_KEY` as the other CMS calls). Each run fetches TYPO3's list first and stores it in `calendar_hotel`; when TYPO3 errors or answers with an empty list, the run logs a warning and uses the stored list, so TYPO3 being down never drops its hotels. `--hotel=<code>` accepts any code from either source. A full run deletes the snapshot of codes that are in neither source any more; they answer `400` from then on, and come back with the next run if they reappear.
|
||||
|
||||
**TYPO3's codes must be BusPro calendar codes.** The sync sends every code to bpn-connect as is. A TYPO3 hotel whose code is a CMS code rather than the BusPro hotel code (group houses often have both, e.g. calendar code `DKS`, CMS code `DKSGRP`) is answered with a `404` by bpn-connect: that code fails on every run, logs two errors each time, and shows up in `contingents/status` with `lastError` set and `available: false`. The task itself keeps succeeding, since only a total failure fails it. The fix belongs in TYPO3, by pointing the product at a hotel whose code is the BusPro code; MyE&P does not translate CMS codes. `contingents/status` is the place to spot such codes, and `accommodation.cmsCode` there shows both codes side by side for group houses.
|
||||
|
||||
### Freshness and propagation
|
||||
|
||||
There is deliberately **no change-notification endpoint**. Availability changes slowly, and the measured cost of simply refetching on a TTL is low enough that a polling/revision mechanism was not worth the extra moving parts on either side.
|
||||
|
||||
@@ -181,15 +181,37 @@ JOIN dbo.PartnerPreis pp ON pp.IDPartnerPreisKategorie_FS=pk.IDPartnerPreisKateg
|
||||
WHERE pk.IDAdresse_FS=@HotelAddressId AND pk.IDArtPartnerPreisCode_FS=@PriceCode
|
||||
AND pk.IDArtVerpflegung_FS=@BoardId AND pk.EK_VK='VK'
|
||||
AND pp.IDPartnerSaisonTafel_FS=@SaisonTafelId AND pp.Naechte=@Nights;
|
||||
-- room availability (flat, reproducible)
|
||||
-- room allotment (remaining = allotment − bookings, computed by BusPro; see below)
|
||||
SELECT IDZimmer_FS,Anzahl,BuchungsStatus FROM dbo.PartnerKontingent
|
||||
WHERE IDAdresse_FS=@HotelAddressId AND IDZimmer_FS=@ZimmerartId
|
||||
AND TerminVon<=@Abreise AND TerminBis>=@Anreise;
|
||||
```
|
||||
|
||||
- V: `EK_VK` = `EK` purchase / `VK` sale. **Always filter `VK`** for customer prices.
|
||||
- V: `PartnerKontingent.Anzahl` IS the available room count. Gate with `BuchungsStatus`
|
||||
(`''` bookable, `S` stop, `A` on request).
|
||||
- V 2026-11-11: `PartnerKontingent.Anzahl` is the room **allotment**, not what is left
|
||||
(hotel 163113, room type 2366: `Anzahl=6` while the export reported `verfuegbar="1"`).
|
||||
BusPro computes the remaining count; read it from the export, not from this table. Gate with
|
||||
`BuchungsStatus` (`''` bookable, `S` stop, `A` on request).
|
||||
- V 2026-11-11: **pooled room contingents.** `PartnerZimmer.IDPartnerZimmer_FS_KontiAus`
|
||||
points at the `PartnerZimmer` (same hotel) whose contingent a room type uses; `0` = own.
|
||||
Used for selling one room at several occupancies ("Unterbelegung"): at hotel 163113 room
|
||||
types 2367–2369 (7/6/5 pax) point at `PartnerZimmer` 8709 (2366, 8 pax). Only the parent
|
||||
has `PartnerKontingent` rows; the export reports the parent's remaining count on every room
|
||||
of the pool. The link is per hotel × room type (the same `Zimmerart` ids recur at other
|
||||
hotels), and room codes do not reveal it. `Zimmerart.Teilzimmer`/`TeilzimmerAus` were 0 for
|
||||
all four rooms and are not this link.
|
||||
|
||||
```sql
|
||||
-- room type → room type owning its contingent, one hotel
|
||||
SELECT pz.IDZimmerart_FS, COALESCE(m.IDZimmerart_FS, pz.IDZimmerart_FS) AS PoolZimmerart
|
||||
FROM dbo.PartnerZimmer pz
|
||||
LEFT JOIN dbo.PartnerZimmer m ON m.IDPartnerZimmer = pz.IDPartnerZimmer_FS_KontiAus
|
||||
WHERE pz.IDAdresse_FS = @HotelAddressId;
|
||||
```
|
||||
|
||||
- V 2026-11-11: BusPro's booking check does not sum a booking's rooms per pool. One booking with two room
|
||||
types of one pool is accepted against a remaining count of 1 and drives it to −1
|
||||
(2026-11-11, travel 1591, rooms 2366 + 2367).
|
||||
- A: `PartnerZimmer.PreisJeZimmer` flags per-room vs per-person. Observed booking
|
||||
responses returned the room price **per person** — check the flag before multiplying.
|
||||
- Service availability is a different, harder problem — see A10.
|
||||
@@ -326,6 +348,8 @@ guides · `Kalkulation*`/`VorplanungRaster*` costing and pre-planning.
|
||||
- `BuchungTNZuschlag` holds the departure surcharge. → `ArtZuschlag` has no such entry (A7).
|
||||
- `sys.objects.create_date` shows when a table was added. → Every object reported the same
|
||||
date: that of the last DB restore. Use `modify_date` after the restore instead.
|
||||
- `PartnerKontingent.Anzahl` is the remaining room count. → Hotel 163113, room type 2366:
|
||||
`Anzahl=6` against export `verfuegbar="1"` on the same day (A6). It is the allotment.
|
||||
|
||||
# A12. Maintenance
|
||||
|
||||
|
||||
@@ -261,15 +261,18 @@ WHERE pk.IDAdresse_FS = @HotelAddressId
|
||||
> customer price. `PartnerZimmer.PreisJeZimmer` flags per-room vs. per-person pricing.
|
||||
|
||||
```sql
|
||||
-- availability (XML 'verfuegbar') — VALIDATED: = PartnerKontingent.Anzahl for the
|
||||
-- (hotel, room-type, date-span). IDZimmer_FS = the XML idbuspro_zimmer (a Zimmerart).
|
||||
-- Sample: IDAdresse_FS=224923, IDZimmer_FS=1413, 2026-12-11 → Anzahl=25 = XML verfuegbar.
|
||||
-- allotment behind XML 'verfuegbar' for the (hotel, room-type, date-span).
|
||||
-- IDZimmer_FS = the XML idbuspro_zimmer (a Zimmerart). Anzahl is the allotment, NOT what is
|
||||
-- left: 2026-11-11, hotel 163113 / 2366 → Anzahl=6 against XML verfuegbar=1. The earlier
|
||||
-- sample 224923 / 1413 / 2026-12-11 (Anzahl=25 = verfuegbar) presumably had no bookings yet.
|
||||
SELECT IDZimmer_FS, Anzahl, BuchungsStatus FROM dbo.PartnerKontingent
|
||||
WHERE IDAdresse_FS = @HotelAddressId
|
||||
AND IDZimmer_FS = @ZimmerartId -- the room type (XML idbuspro_zimmer)
|
||||
AND TerminVon <= @Abreise AND TerminBis >= @Anreise;
|
||||
```
|
||||
> `verfuegbar` is a **flat column** (`PartnerKontingent.Anzahl`) — reproducible by SQL.
|
||||
> `verfuegbar` is **computed** by BusPro: allotment minus bookings (see
|
||||
> `live-api-queries.md`), and for a pooled room type the parent's figure
|
||||
> (`PartnerZimmer.IDPartnerZimmer_FS_KontiAus`, `buspro-database-reference.md` A6).
|
||||
> Gate it with `BuchungsStatus` (`''` bookable, `S` stop, `A` on-request).
|
||||
> `<abpreis>` (the headline "from" price) is still **computed** (cheapest valid room +
|
||||
> mandatory services) — recompute in the proxy from the per-room prices above.
|
||||
@@ -298,8 +301,9 @@ ORDER BY gs.Position, sg.Position;
|
||||
4. ~~**Partner room pricing**~~ — ✅ fully validated end-to-end: room `1413` (MBZ) →
|
||||
code `38` → category `9478` → season `15420` × `Naechte=2` × `VK` × schema `1` =
|
||||
**`269,00`**. (XML `abpreis 289,00` = room + mandatory services = computed.)
|
||||
5. ~~**`verfuegbar`**~~ — ✅ flat: `PartnerKontingent.Anzahl` for `(IDAdresse_FS, IDZimmer_FS,
|
||||
date-span)`; `1413 / 2026-12-11 → 25`. `<abpreis>` remains computed (recompute in proxy).
|
||||
5. **`verfuegbar`** — computed, not flat (corrected 2026-11-11): `PartnerKontingent.Anzahl`
|
||||
is the allotment; `1413 / 2026-12-11 → 25` presumably matched because nothing was booked
|
||||
yet. `<abpreis>` remains computed (recompute in proxy).
|
||||
6. ~~**Minimum-services filter**~~ — ✅ defined: "included services" =
|
||||
(A2a) `Leistung`s with sales price `0.00` (schema 1) **+** (A2b) selection items from
|
||||
the hardcoded "Leistungen" `Selektionsgruppenstamm` ids, merged into one plain list.
|
||||
+8
-3
@@ -79,9 +79,14 @@ Trip rules (`App\Chatbot\TripCatalog`):
|
||||
("NEU Sportclub Lederer Wochenenden und Kurztrips", "Vacanceole Résidence L'Edelweiss"), so a hotel is
|
||||
shown under its TYPO3 title, and under BusPro's name only when TYPO3 has no hotel for its code.
|
||||
`query` searches both. Trips have no name in BusPro's export, only a code; their names are TYPO3's.
|
||||
- A room is bookable unless its status is `Buchungsstop`. The baby row (room code `Baby`) is not a room.
|
||||
`available` counts rooms, so the places of a date at a hotel are `Σ available × maxPax` over its
|
||||
bookable rooms. The tools never output room counts, only `frei` or `auf Anfrage`.
|
||||
- A room is listed unless its status is `Buchungsstop`. The baby row (room code `Baby`) is not a room.
|
||||
A listed room is bookable when the booking flow offers it (the export's `bookable`): `Frei` with rooms
|
||||
left is `frei`; `Anfrage` with rooms left and a room code ending in `Anf` (sold on request on purpose,
|
||||
booking it produces an inquiry) is `auf Anfrage`. Any other room, including any other one on request, is
|
||||
sold out, as the website shows it. A date at a hotel is as available as its best room; dates with only
|
||||
sold-out rooms stay in `search_trips`, marked `ausgebucht`. `available` counts rooms, so the places of a
|
||||
date at a hotel are `Σ available × maxPax` over its bookable rooms, and the "ab" price is the cheapest
|
||||
bookable room's. The tools never output room counts, only `frei`, `auf Anfrage` or `ausgebucht`.
|
||||
- `search_trips` only offers products that TYPO3 lists in its own website search (`searchable`) and does
|
||||
not mark as unbookable. Closed group trips and staff trainings are `searchable: false`. `get_trip` still
|
||||
answers when someone names their code.
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
final class Version20261029120000 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Keys the contingent snapshot by hotel code instead of accommodation, and adds calendar_hotel for TYPO3\'s calendar hotel list.';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql('CREATE TABLE calendar_hotel (id INT AUTO_INCREMENT NOT NULL, code VARCHAR(16) NOT NULL, name VARCHAR(255) NOT NULL, UNIQUE INDEX UNIQ_6F075DB777153098 (code), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
|
||||
|
||||
// Backfill from the linked accommodation. accommodation_id stays, nullable and no longer
|
||||
// written, until a later migration drops it; that keeps this step reversible.
|
||||
$this->addSql('ALTER TABLE contingent_day ADD hotel_code VARCHAR(16) DEFAULT NULL, CHANGE accommodation_id accommodation_id INT DEFAULT NULL');
|
||||
$this->addSql('UPDATE contingent_day cd INNER JOIN accommodation a ON a.id = cd.accommodation_id SET cd.hotel_code = a.calendar_code');
|
||||
$this->addSql('DELETE FROM contingent_day WHERE hotel_code IS NULL OR hotel_code = \'\'');
|
||||
$this->addSql('ALTER TABLE contingent_day CHANGE hotel_code hotel_code VARCHAR(16) NOT NULL');
|
||||
$this->addSql('DROP INDEX uniq_contingent_day_accommodation_date ON contingent_day');
|
||||
$this->addSql('CREATE UNIQUE INDEX uniq_contingent_day_hotel_code_date ON contingent_day (hotel_code, date)');
|
||||
|
||||
$this->addSql('ALTER TABLE contingent_sync_state ADD hotel_code VARCHAR(16) DEFAULT NULL, CHANGE accommodation_id accommodation_id INT DEFAULT NULL');
|
||||
$this->addSql('UPDATE contingent_sync_state s INNER JOIN accommodation a ON a.id = s.accommodation_id SET s.hotel_code = a.calendar_code');
|
||||
$this->addSql('DELETE FROM contingent_sync_state WHERE hotel_code IS NULL OR hotel_code = \'\'');
|
||||
$this->addSql('ALTER TABLE contingent_sync_state CHANGE hotel_code hotel_code VARCHAR(16) NOT NULL');
|
||||
$this->addSql('CREATE UNIQUE INDEX UNIQ_737F167CC0D0E610 ON contingent_sync_state (hotel_code)');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
// Rows of hotel codes without an accommodation cannot be expressed in the old schema.
|
||||
// The snapshot is a cache, so the next sync of the old code rebuilds whatever is lost.
|
||||
$this->addSql('UPDATE contingent_day cd INNER JOIN accommodation a ON a.calendar_code = cd.hotel_code SET cd.accommodation_id = a.id');
|
||||
$this->addSql('DELETE cd FROM contingent_day cd LEFT JOIN accommodation a ON a.calendar_code = cd.hotel_code WHERE a.id IS NULL');
|
||||
$this->addSql('DROP INDEX uniq_contingent_day_hotel_code_date ON contingent_day');
|
||||
$this->addSql('ALTER TABLE contingent_day DROP hotel_code, CHANGE accommodation_id accommodation_id INT NOT NULL');
|
||||
$this->addSql('CREATE UNIQUE INDEX uniq_contingent_day_accommodation_date ON contingent_day (accommodation_id, date)');
|
||||
|
||||
$this->addSql('UPDATE contingent_sync_state s INNER JOIN accommodation a ON a.calendar_code = s.hotel_code SET s.accommodation_id = a.id');
|
||||
$this->addSql('DELETE s FROM contingent_sync_state s LEFT JOIN accommodation a ON a.calendar_code = s.hotel_code WHERE a.id IS NULL');
|
||||
$this->addSql('DROP INDEX UNIQ_737F167CC0D0E610 ON contingent_sync_state');
|
||||
$this->addSql('ALTER TABLE contingent_sync_state DROP hotel_code, CHANGE accommodation_id accommodation_id INT NOT NULL');
|
||||
|
||||
$this->addSql('DROP TABLE calendar_hotel');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
final class Version20261104142531 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Adds travel_mailing_list to track the Mailjet contact lists created per travel until their deletion.';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql('CREATE TABLE travel_mailing_list (id INT AUTO_INCREMENT NOT NULL, travel_code VARCHAR(32) NOT NULL, mailjet_list_id INT NOT NULL, delete_after DATETIME NOT NULL COMMENT \'(DC2Type:datetime_immutable)\', created_at DATETIME NOT NULL COMMENT \'(DC2Type:datetime_immutable)\', UNIQUE INDEX UNIQ_68DC6E28BC4DD335 (travel_code), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('DROP TABLE travel_mailing_list');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
final class Version20261109074654 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Allows a bus-only travel mailing list next to the full one: adds bus_leg and the list name, which replaces travel_code as the unique key.';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE travel_mailing_list ADD bus_leg VARCHAR(20) DEFAULT NULL, ADD name VARCHAR(64) DEFAULT NULL');
|
||||
// Every existing list holds all participants and is named by its travel code alone.
|
||||
$this->addSql('UPDATE travel_mailing_list SET name = travel_code');
|
||||
$this->addSql('ALTER TABLE travel_mailing_list MODIFY name VARCHAR(64) NOT NULL');
|
||||
$this->addSql('CREATE UNIQUE INDEX UNIQ_68DC6E285E237E06 ON travel_mailing_list (name)');
|
||||
$this->addSql('ALTER TABLE travel_mailing_list DROP INDEX UNIQ_68DC6E28BC4DD335, ADD INDEX IDX_68DC6E28BC4DD335 (travel_code)');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
// Fails while a travel has two lists; delete the bus-only one first.
|
||||
$this->addSql('ALTER TABLE travel_mailing_list DROP INDEX IDX_68DC6E28BC4DD335, ADD UNIQUE INDEX UNIQ_68DC6E28BC4DD335 (travel_code)');
|
||||
$this->addSql('DROP INDEX UNIQ_68DC6E285E237E06 ON travel_mailing_list');
|
||||
$this->addSql('ALTER TABLE travel_mailing_list DROP bus_leg, DROP name');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
final class Version20261113151744 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Adds the back-channel logout URL and secret to OAuth2 clients.';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE oauth2_client ADD logout_url VARCHAR(255) DEFAULT NULL, ADD logout_secret VARCHAR(128) DEFAULT NULL');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE oauth2_client DROP logout_url, DROP logout_secret');
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\BpnConnect\Model;
|
||||
|
||||
use App\Enum\BusLeg;
|
||||
|
||||
readonly class TravelMailingResponse
|
||||
{
|
||||
/**
|
||||
@@ -12,6 +14,7 @@ readonly class TravelMailingResponse
|
||||
public function __construct(
|
||||
public string $travelCode,
|
||||
public array $data,
|
||||
public ?BusLeg $busLeg = null,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\BpnConnect;
|
||||
|
||||
class RoomsClient extends AbstractApiClient
|
||||
{
|
||||
private const string CONTINGENT_POOLS_PATH = '/api/v1/rooms/contingent-pools';
|
||||
|
||||
/**
|
||||
* Which room type's contingent each room type of a hotel draws on.
|
||||
*
|
||||
* The office sells one room at several occupancies by pointing the extra room types at the
|
||||
* first one's contingent (`PartnerZimmer.IDPartnerZimmer_FS_KontiAus`). A room type with its
|
||||
* own contingent maps to itself.
|
||||
*
|
||||
* @param int $hotelId the hotel's BusPro address id (the export's `<hotel idbuspro>`)
|
||||
*
|
||||
* @return array<int, int> room type id => room type id owning its contingent
|
||||
*/
|
||||
public function getContingentPools(int $hotelId): array
|
||||
{
|
||||
$payload = $this->request(self::CONTINGENT_POOLS_PATH, ['hotelId' => $hotelId]);
|
||||
|
||||
$pools = [];
|
||||
foreach ($payload['data'] ?? [] as $item) {
|
||||
$pools[(int) $item['room_type_id']] = (int) $item['pool_room_type_id'];
|
||||
}
|
||||
|
||||
return $pools;
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,10 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\BpnConnect;
|
||||
|
||||
use App\BpnConnect\Exception\BpnConnectException;
|
||||
use App\BpnConnect\Model\TravelMailingRecipient;
|
||||
use App\BpnConnect\Model\TravelMailingResponse;
|
||||
use App\Enum\BusLeg;
|
||||
|
||||
class TravelsClient extends AbstractApiClient
|
||||
{
|
||||
@@ -14,12 +16,30 @@ class TravelsClient extends AbstractApiClient
|
||||
/**
|
||||
* An unknown travel code yields an empty list, not an error: bpn-connect cannot tell it
|
||||
* apart from a travel without confirmed participants.
|
||||
*
|
||||
* @param ?BusLeg $busLeg only participants who booked this bus leg, plus their bookings' applicants
|
||||
*/
|
||||
public function getMailingRecipients(string $travelCode): TravelMailingResponse
|
||||
public function getMailingRecipients(string $travelCode, ?BusLeg $busLeg = null): TravelMailingResponse
|
||||
{
|
||||
$payload = $this->request(self::MAILING_PATH, [
|
||||
'travelCode' => $travelCode,
|
||||
]);
|
||||
$query = ['travelCode' => $travelCode];
|
||||
if (null !== $busLeg) {
|
||||
$query['busLeg'] = $busLeg->value;
|
||||
}
|
||||
|
||||
$payload = $this->request(self::MAILING_PATH, $query);
|
||||
|
||||
// A bpn-connect that predates the filter ignores the parameter and returns everyone, which
|
||||
// must not end up on a list meant for bus passengers only.
|
||||
$appliedBusLeg = $payload['meta']['bus_leg'] ?? null;
|
||||
if ($appliedBusLeg !== $busLeg?->value) {
|
||||
$this->logger->error('BpnConnect ignored the travel mailing bus filter', [
|
||||
'travel_code' => $travelCode,
|
||||
'requested_bus_leg' => $busLeg?->value,
|
||||
'applied_bus_leg' => $appliedBusLeg,
|
||||
]);
|
||||
|
||||
throw new BpnConnectException('BpnConnect did not apply the requested bus leg filter.');
|
||||
}
|
||||
|
||||
$recipients = array_map(
|
||||
static fn (array $item) => new TravelMailingRecipient(
|
||||
@@ -30,6 +50,6 @@ class TravelsClient extends AbstractApiClient
|
||||
$payload['data'] ?? [],
|
||||
);
|
||||
|
||||
return new TravelMailingResponse($payload['meta']['travel_code'] ?? $travelCode, $recipients);
|
||||
return new TravelMailingResponse($payload['meta']['travel_code'] ?? $travelCode, $recipients, $busLeg);
|
||||
}
|
||||
}
|
||||
@@ -153,7 +153,6 @@ class BookingDataProcessor
|
||||
$roomSelection->price = $room->price;
|
||||
$roomSelection->quantity = $bookingRoom->totalCount; // Actual quantity from booking XML (anzahl)
|
||||
$roomSelection->capacity = $room->minPax ?? 1;
|
||||
$roomSelection->maxQuantity = $bookingRoom->totalCount + ($room->available ?? 0);
|
||||
$dto->roomSelections[] = $roomSelection;
|
||||
}
|
||||
}
|
||||
@@ -341,6 +340,7 @@ class BookingDataProcessor
|
||||
$this->serviceProcessor->processParticipantServices($participant, $bookingData, $travelData);
|
||||
}
|
||||
|
||||
$this->serviceProcessor->removeCanceledParticipantsFromRooms($bookingData);
|
||||
$this->serviceProcessor->removeUnusedServices($bookingData);
|
||||
$this->personalDataSynchronizer->updateParticipantPersonalData(
|
||||
$formData->participants,
|
||||
|
||||
@@ -14,8 +14,9 @@ use Psr\Log\LoggerInterface;
|
||||
* Processes participant service selections for booking updates.
|
||||
*
|
||||
* Handles the assignment and mapping of services (additional, transportation,
|
||||
* pickup, room, insurance) from participant DTOs to the booking model during
|
||||
* the update request workflow.
|
||||
* pickup, insurance) from participant DTOs to the booking model during the
|
||||
* update request workflow. Rooms are not taken from the DTOs: they cannot be
|
||||
* changed in edit mode, so the booking's own room assignments are sent back.
|
||||
*/
|
||||
class ParticipantServiceProcessor
|
||||
{
|
||||
@@ -28,7 +29,7 @@ class ParticipantServiceProcessor
|
||||
* Resets all existing participant-to-service mappings to start with a clean slate.
|
||||
*
|
||||
* This ensures that service assignments are rebuilt from scratch based on current form selections.
|
||||
* Includes resetting room mappings to allow room reassignments during edit.
|
||||
* Room mappings are left alone, see removeCanceledParticipantsFromRooms().
|
||||
*
|
||||
* @param Booking $bookingData The booking data object containing services to reset
|
||||
*/
|
||||
@@ -39,7 +40,6 @@ class ParticipantServiceProcessor
|
||||
...$bookingData->transportationServices,
|
||||
...$bookingData->pickups,
|
||||
...$bookingData->dropOffs,
|
||||
...$bookingData->rooms,
|
||||
...$bookingData->insurances,
|
||||
];
|
||||
|
||||
@@ -52,7 +52,7 @@ class ParticipantServiceProcessor
|
||||
* Processes all services for a single participant.
|
||||
*
|
||||
* This orchestrator method handles the complete service assignment workflow for one participant,
|
||||
* including additional services, transportation services, pickup locations, and room assignments.
|
||||
* including additional services, transportation services, pickup locations, and insurance.
|
||||
*
|
||||
* @param ParticipantDto $participant The participant data from the form
|
||||
* @param Booking $bookingData The booking data object to update
|
||||
@@ -68,7 +68,6 @@ class ParticipantServiceProcessor
|
||||
$this->processTransportationServices($participant, $bookingData, $travelData);
|
||||
$this->processPickupLocations($participant, $bookingData);
|
||||
$this->processDropOffLocations($participant, $bookingData);
|
||||
$this->processRoomAssignment($participant, $bookingData);
|
||||
$this->processInsurance($participant, $bookingData, $travelData);
|
||||
}
|
||||
|
||||
@@ -271,27 +270,23 @@ class ParticipantServiceProcessor
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes room assignment for a participant.
|
||||
* Removes canceled participants from the booking's room assignments.
|
||||
*
|
||||
* Maps the participant to their assigned room. Allows room reassignment during
|
||||
* booking edits while maintaining the constraint that participants can only be
|
||||
* assigned to room types that have already been booked.
|
||||
* Room assignments cannot be changed in edit mode, so they are sent back as BusPro reports
|
||||
* them on the booking reloaded at submit, together with its anzahl. Rebuilding them from the
|
||||
* session would undo any reassignment made in BusPro while the edit was open, and send a
|
||||
* zuordnung that no longer matches anzahl. Canceled participants are left out, as for every
|
||||
* other service.
|
||||
*
|
||||
* @param ParticipantDto $participant The participant data from the form
|
||||
* @param Booking $bookingData The booking data object to update
|
||||
* @param Booking $bookingData The booking data object to update
|
||||
*/
|
||||
private function processRoomAssignment(ParticipantDto $participant, Booking $bookingData): void
|
||||
public function removeCanceledParticipantsFromRooms(Booking $bookingData): void
|
||||
{
|
||||
if (null === $participant->assignedRoomId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Find the room in the existing booking by ID
|
||||
foreach ($bookingData->rooms as $room) {
|
||||
if ($room->id === $participant->assignedRoomId) {
|
||||
$room->mapping[] = $participant->index;
|
||||
break;
|
||||
}
|
||||
$room->mapping = array_values(array_filter(
|
||||
$room->mapping,
|
||||
fn (int $index) => 'S' !== ($bookingData->participantsStatus[$index] ?? null)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\BusProNet\Model;
|
||||
|
||||
use App\Validator\Constraints as AppAssert;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
|
||||
/**
|
||||
@@ -15,17 +16,47 @@ use Symfony\Component\Validator\Constraints as Assert;
|
||||
*/
|
||||
class Communication
|
||||
{
|
||||
#[Assert\When(
|
||||
expression: 'this.isPhoneNewlyEntered()',
|
||||
constraints: [new AppAssert\PhoneNumber()],
|
||||
groups: ['personal_data'],
|
||||
)]
|
||||
public ?string $phone = null;
|
||||
|
||||
#[Assert\NotBlank(message: 'Bitte angeben', groups: ['personal_data'])]
|
||||
#[Assert\When(
|
||||
expression: 'this.isMobileNewlyEntered()',
|
||||
constraints: [new AppAssert\PhoneNumber()],
|
||||
groups: ['personal_data'],
|
||||
)]
|
||||
public ?string $mobile = null;
|
||||
|
||||
// The numbers as loaded from BusPro, which go back unchanged and are exempt from PhoneNumber.
|
||||
public ?string $loadedPhone = null;
|
||||
public ?string $loadedMobile = null;
|
||||
|
||||
#[Assert\NotBlank(message: 'Bitte angeben', groups: ['personal_identity'])]
|
||||
#[Assert\Email(message: 'Bitte eine gültige Adresse angeben', mode: 'strict', groups: ['personal_identity'])]
|
||||
public ?string $email = null;
|
||||
|
||||
public bool $newsletter = false;
|
||||
|
||||
public function rememberLoadedNumbers(): void
|
||||
{
|
||||
$this->loadedPhone = $this->phone;
|
||||
$this->loadedMobile = $this->mobile;
|
||||
}
|
||||
|
||||
public function isPhoneNewlyEntered(): bool
|
||||
{
|
||||
return AppAssert\PhoneNumber::isNewlyEntered($this->phone, $this->loadedPhone);
|
||||
}
|
||||
|
||||
public function isMobileNewlyEntered(): bool
|
||||
{
|
||||
return AppAssert\PhoneNumber::isNewlyEntered($this->mobile, $this->loadedMobile);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the communication data to API payload format.
|
||||
*
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\BusProNet\Model;
|
||||
|
||||
use App\BusProNet\Constants;
|
||||
use Symfony\Component\Serializer\Attribute\Context;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
|
||||
@@ -20,6 +21,37 @@ class Room
|
||||
public const SELECTION_TYPE_BY_PAX = 'by_pax';
|
||||
public const SELECTION_TYPE_BY_ROOM = 'by_room';
|
||||
|
||||
/**
|
||||
* Room code suffix by which the office marks a room as deliberately sold on request.
|
||||
*/
|
||||
public const ON_REQUEST_CODE_SUFFIX = 'Anf';
|
||||
|
||||
/**
|
||||
* Whether a room with this status, availability and code is offered for new bookings.
|
||||
*
|
||||
* 'Frei' rooms with rooms left. A room on request ('Anfrage') would turn the booking into
|
||||
* an inquiry, so it is treated as sold out, unless isOnRequestByCode() says the office
|
||||
* sells it that way on purpose. Static and taking the raw values so the product export
|
||||
* and the chatbot, which hold rooms as arrays, apply the same rule.
|
||||
*/
|
||||
public static function isBookableState(?string $status, ?int $available, ?string $code): bool
|
||||
{
|
||||
if (($available ?? 0) <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Constants::STATUS_AVAILABLE === $status
|
||||
|| (Constants::STATUS_ON_REQUEST === $status && self::isOnRequestByCode($code));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the room code carries the on-request suffix (case-sensitive, e.g. `6erSDAnf`).
|
||||
*/
|
||||
public static function isOnRequestByCode(?string $code): bool
|
||||
{
|
||||
return null !== $code && str_ends_with($code, self::ON_REQUEST_CODE_SUFFIX);
|
||||
}
|
||||
|
||||
#[Groups(['api:list', 'api:single', 'snapshot'])]
|
||||
public ?int $id = null;
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\BusProNet\Model;
|
||||
|
||||
use App\BusProNet\Constants;
|
||||
use App\BusProNet\Traits\SortByPriceTrait;
|
||||
use Symfony\Component\Serializer\Attribute\Context;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
@@ -278,10 +277,10 @@ class Travel
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves all bookable rooms (both regular and inquiry).
|
||||
* Retrieves all bookable rooms.
|
||||
*
|
||||
* Returns rooms that have availability greater than zero and a bookable status
|
||||
* (either 'Frei' for regular booking or 'Anfrage' for inquiry booking).
|
||||
* Returns the rooms Room::isBookableState() accepts: status 'Frei' with rooms left, or rooms
|
||||
* the office sells on request on purpose, which turn the booking into an inquiry.
|
||||
*
|
||||
* @return array<int, Room> The filtered array of bookable rooms, indexed by room ID
|
||||
*/
|
||||
@@ -289,7 +288,7 @@ class Travel
|
||||
{
|
||||
$result = [];
|
||||
foreach ($this->rooms as $room) {
|
||||
if ($room->available > 0 && $this->isBookableRoomStatus($room->status)) {
|
||||
if (Room::isBookableState($room->status, $room->available, $room->code)) {
|
||||
$result[$room->id] = $room;
|
||||
}
|
||||
}
|
||||
@@ -307,40 +306,6 @@ class Travel
|
||||
return [] !== $this->getAvailableRooms();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if all bookable rooms require inquiry booking.
|
||||
*
|
||||
* Returns true if there are bookable rooms but none with 'Frei' status.
|
||||
* This indicates the booking must be submitted as an inquiry.
|
||||
*
|
||||
* @return bool True if only inquiry rooms are available
|
||||
*/
|
||||
public function requiresInquiryBooking(): bool
|
||||
{
|
||||
$bookableRooms = $this->getAvailableRooms();
|
||||
|
||||
if ([] === $bookableRooms) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($bookableRooms as $room) {
|
||||
if (Constants::STATUS_AVAILABLE === $room->status) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a room status allows booking.
|
||||
*/
|
||||
private function isBookableRoomStatus(?string $status): bool
|
||||
{
|
||||
return Constants::STATUS_AVAILABLE === $status
|
||||
|| Constants::STATUS_ON_REQUEST === $status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a room by its ID.
|
||||
*
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\BusProNet\Exception\ApiClientException;
|
||||
use App\BusProNet\Exception\ImmediateConnectionCloseException;
|
||||
use App\BusProNet\Exception\ResponseParserException;
|
||||
use App\BusProNet\MessageType;
|
||||
use App\BusProNet\Utility\XmlCharacterFilter;
|
||||
use App\BusProNet\XmlParser\ApiResponseParser;
|
||||
use App\Service\XmlDumpWriter;
|
||||
use Psr\Log\LoggerInterface;
|
||||
@@ -208,8 +209,18 @@ class XmlChannel
|
||||
*/
|
||||
private function parseResponse(MessageType $type, string $xml, array $parserArgs, string $requestId, bool $dumpOnFailure = true): mixed
|
||||
{
|
||||
// The dump keeps the raw response; only the parser sees the filtered one.
|
||||
$filtered = XmlCharacterFilter::strip($xml, $removed);
|
||||
if ($removed > 0) {
|
||||
$this->logger->warning('Removed characters not allowed in XML from API response', [
|
||||
'request_id' => $requestId,
|
||||
'type' => $type->value,
|
||||
'removed' => $removed,
|
||||
]);
|
||||
}
|
||||
|
||||
try {
|
||||
return $this->responseParser->parseXmlString($type, $xml, $parserArgs);
|
||||
return $this->responseParser->parseXmlString($type, $filtered, $parserArgs);
|
||||
} catch (ResponseParserException $e) {
|
||||
// Keep the evidence even outside debug mode: without the raw response a parse
|
||||
// failure is not diagnosable after the fact. app:cleanup:xml-dumps prunes it.
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\BusProNet\Utility;
|
||||
|
||||
/**
|
||||
* Removes characters XML 1.0 does not allow from a BusPro response before it is parsed.
|
||||
*
|
||||
* BusPro escapes whatever a field holds into a character reference without checking it,
|
||||
* so a NUL-padded value comes out as `�`. libxml rejects that as fatal and the whole
|
||||
* response fails to parse, not just the field. The same applies to the raw control bytes.
|
||||
*/
|
||||
final class XmlCharacterFilter
|
||||
{
|
||||
/**
|
||||
* @param-out int $count the number of characters removed
|
||||
*/
|
||||
public static function strip(string $xml, ?int &$count = null): string
|
||||
{
|
||||
$count = 0;
|
||||
|
||||
$xml = preg_replace_callback(
|
||||
'/&#(x[0-9a-f]+|[0-9]+);/i',
|
||||
static function (array $match) use (&$count): string {
|
||||
$reference = $match[1];
|
||||
$codePoint = 'x' === strtolower($reference[0]) ? hexdec(substr($reference, 1)) : (int) $reference;
|
||||
|
||||
if (self::isAllowed($codePoint)) {
|
||||
return $match[0];
|
||||
}
|
||||
|
||||
++$count;
|
||||
|
||||
return '';
|
||||
},
|
||||
$xml,
|
||||
);
|
||||
|
||||
// Control bytes never occur inside a UTF-8 multibyte sequence, so a byte-wise match is safe.
|
||||
$xml = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $xml, -1, $rawCount);
|
||||
|
||||
$count += $rawCount;
|
||||
|
||||
return $xml;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Char production of XML 1.0.
|
||||
*/
|
||||
private static function isAllowed(int|float $codePoint): bool
|
||||
{
|
||||
return 0x9 === $codePoint
|
||||
|| 0xA === $codePoint
|
||||
|| 0xD === $codePoint
|
||||
|| ($codePoint >= 0x20 && $codePoint <= 0xD7FF)
|
||||
|| ($codePoint >= 0xE000 && $codePoint <= 0xFFFD)
|
||||
|| ($codePoint >= 0x10000 && $codePoint <= 0x10FFFF);
|
||||
}
|
||||
}
|
||||
@@ -307,10 +307,10 @@ class TravelLoader extends AbstractLoader
|
||||
$availability = $serviceAvailabilities[$service->id];
|
||||
$service->available = $availability->available;
|
||||
|
||||
// The live status is the only signal that a contingent has run out: BusPro moves a
|
||||
// Leistung to 'Anfrage' without necessarily reporting frei="0". Only overwrite when the
|
||||
// response actually carries one, so a response that omits the attribute does not wipe
|
||||
// the value parsed from the XML export. Mirrors TravelSnapshotManager::applyExtendedToService().
|
||||
// The live status is fresher than the nightly export's. The parser has already mapped it
|
||||
// onto the export vocabulary. Only overwrite when the response actually carries one, so a
|
||||
// response that omits the attribute does not wipe the value parsed from the XML export.
|
||||
// Mirrors TravelSnapshotManager::applyExtendedToService().
|
||||
if (null !== $availability->status && '' !== trim($availability->status)) {
|
||||
$service->status = $availability->status;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\BusProNet\XmlParser;
|
||||
|
||||
use App\BusProNet\Constants;
|
||||
use App\BusProNet\Traits\TypeConversionTrait;
|
||||
use Symfony\Component\DomCrawler\Crawler;
|
||||
|
||||
@@ -9,6 +10,19 @@ abstract class AbstractParser
|
||||
{
|
||||
use TypeConversionTrait;
|
||||
|
||||
/**
|
||||
* Live availability wording for a Leistung, mapped onto the XML export's.
|
||||
*
|
||||
* The availability endpoints answer "buchbar" or "ausgebucht", while every availability rule
|
||||
* compares against the export's "Frei" / "Anfrage" / "Buchungsstop". "ausgebucht" also covers
|
||||
* a Leistung that would still take an inquiry (anfragemoeglich="J"); that is not offered
|
||||
* either, so it maps to the booking stop.
|
||||
*/
|
||||
private const LIVE_SERVICE_STATUS = [
|
||||
'buchbar' => Constants::STATUS_AVAILABLE,
|
||||
'ausgebucht' => Constants::STATUS_BLOCKED,
|
||||
];
|
||||
|
||||
protected function getStringOrNullValue(Crawler $node): ?string
|
||||
{
|
||||
return 0 < $node->count() ? $node->text() : null;
|
||||
@@ -87,4 +101,16 @@ abstract class AbstractParser
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates a live Leistung status into the export vocabulary; anything else passes through.
|
||||
*/
|
||||
protected function toServiceStatus(?string $liveStatus): ?string
|
||||
{
|
||||
if (null === $liveStatus) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return self::LIVE_SERVICE_STATUS[strtolower(trim($liveStatus))] ?? $liveStatus;
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ class AvailabilitiesParser extends AbstractParser
|
||||
->each(function (Crawler $node) use (&$availabilities) {
|
||||
$availability = new Availability();
|
||||
$availability->serviceId = (int) $node->attr('id');
|
||||
$availability->status = $node->attr('status');
|
||||
$availability->status = $this->toServiceStatus($node->attr('status'));
|
||||
$availability->available = (int) $node->attr('frei');
|
||||
$availability->price = $this->stringToFloat($node->attr('preis'));
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ class ExtendedAvailabilitiesParser extends AbstractParser
|
||||
|
||||
$availability = new ExtendedAvailability();
|
||||
$availability->serviceId = $serviceId;
|
||||
$availability->status = $node->attr('status');
|
||||
$availability->status = $this->toServiceStatus($node->attr('status'));
|
||||
$availability->available = (int) $node->attr('frei');
|
||||
$availability->price = $this->stringToFloat($node->attr('preis'));
|
||||
$availability->dateFrom = $this->stringToDate($node->attr('termin'));
|
||||
|
||||
@@ -50,6 +50,7 @@ class PersonalDataParser extends AbstractParser
|
||||
$communication->mobile = $this->getStringOrNullValue($contactDataNode->filterXPath('//telefonmobil'));
|
||||
$communication->email = $this->getStringOrNullValue($contactDataNode->filterXPath('//email'));
|
||||
$communication->newsletter = $this->getBoolValue($contactDataNode->filterXPath('//newsletter'));
|
||||
$communication->rememberLoadedNumbers();
|
||||
|
||||
$personalData->communication = $communication;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace App\BusProNet\XmlParser;
|
||||
|
||||
use App\BusProNet\Constants;
|
||||
use App\BusProNet\Model\Room;
|
||||
use Symfony\Component\DomCrawler\Crawler;
|
||||
|
||||
/**
|
||||
@@ -61,7 +62,8 @@ class ProductExportParser extends AbstractParser
|
||||
* The hotel's rooms, without the PDGS pseudo room.
|
||||
*
|
||||
* `available` is a count of rooms, not persons. Occupancy is read case-insensitively:
|
||||
* the travel export writes `MinPax`/`MaxPax`.
|
||||
* the travel export writes `MinPax`/`MaxPax`. `bookable` is the one derived field: whether
|
||||
* the booking flow offers the room, so a consumer need not re-derive that rule.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
@@ -76,6 +78,9 @@ class ProductExportParser extends AbstractParser
|
||||
return;
|
||||
}
|
||||
|
||||
$available = $this->getIntAttrOrNullValue($room, 'verfuegbar');
|
||||
$status = $this->getAttrOrNullValue($room, 'status');
|
||||
|
||||
$rooms[] = [
|
||||
'busProId' => $this->getIntAttrOrNullValue($room, 'idbuspro_zimmer'),
|
||||
'code' => $code,
|
||||
@@ -85,8 +90,9 @@ class ProductExportParser extends AbstractParser
|
||||
'maxPax' => $this->getIntAttrOrNullValue($room, 'maxpax'),
|
||||
'nights' => $this->getIntAttrOrNullValue($room, 'naechte'),
|
||||
'price' => $this->stringToFloat($this->getAttrOrNullValue($room, 'preis')),
|
||||
'available' => $this->getIntAttrOrNullValue($room, 'verfuegbar'),
|
||||
'status' => $this->getAttrOrNullValue($room, 'status'),
|
||||
'available' => $available,
|
||||
'status' => $status,
|
||||
'bookable' => Room::isBookableState($status, $available, $code),
|
||||
'boardCode' => $this->getAttrOrNullValue($room, 'vpcode'),
|
||||
'boardBusProId' => $this->getIntAttrOrNullValue($room, 'idbuspro_vp'),
|
||||
];
|
||||
|
||||
@@ -40,8 +40,6 @@ class TripCatalog
|
||||
/** The feed's only language for now; trips are joined in it. */
|
||||
public const LANGUAGE = 'de';
|
||||
|
||||
private const STATUS_FREE = 'Frei';
|
||||
|
||||
private const DATES_WITH_PICKUPS = 3;
|
||||
private const BODY_LIMIT = 20000;
|
||||
private const HOTEL_BODY_LIMIT = 8000;
|
||||
@@ -571,7 +569,7 @@ class TripCatalog
|
||||
*/
|
||||
private function matches(array $row, TravelDateFacts $facts, ?HotelType $hotelType, TripCriteria $criteria): bool
|
||||
{
|
||||
if (!$facts->isBookable()) {
|
||||
if (!$facts->isListed()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -696,7 +694,7 @@ class TripCatalog
|
||||
'board' => $room['boardCode'] ?? null,
|
||||
'nights' => $room['nights'] ?? null,
|
||||
'price' => $room['price'] ?? null,
|
||||
'availability' => self::STATUS_FREE === ($room['status'] ?? null) ? TravelDateFacts::AVAILABILITY_FREE : TravelDateFacts::AVAILABILITY_ON_REQUEST,
|
||||
'availability' => TravelDateFacts::roomAvailability($room),
|
||||
], static fn (mixed $value): bool => null !== $value);
|
||||
}
|
||||
|
||||
@@ -712,7 +710,7 @@ class TripCatalog
|
||||
'hotel' => $this->hotelName($catalog, $hotel, $row),
|
||||
'hotelCode' => $row['hotel']['code'],
|
||||
'rooms' => $rooms,
|
||||
'bookable' => [] !== $rooms,
|
||||
'bookable' => [] !== array_diff(array_column($rooms, 'availability'), [TravelDateFacts::AVAILABILITY_SOLD_OUT]),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,491 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Command;
|
||||
|
||||
use App\BusProNet\Client\BookingClient;
|
||||
use App\BusProNet\Client\TravelClient;
|
||||
use App\BusProNet\Constants;
|
||||
use App\BusProNet\DataProcessor\BookingDataProcessor;
|
||||
use App\BusProNet\Model\Booking;
|
||||
use App\BusProNet\Model\Notification;
|
||||
use App\BusProNet\Model\Service;
|
||||
use App\BusProNet\Model\Travel;
|
||||
use App\Entity\BookingEditDraft;
|
||||
use App\Entity\User;
|
||||
use App\Repository\BookingEditDraftRepository;
|
||||
use App\Security\Crypt;
|
||||
use App\Service\BookingChangeTracker;
|
||||
use App\Service\BookingEditDraftMerger;
|
||||
use App\Service\TravelDataProvider;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Console\Style\SymfonyStyle;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
|
||||
/**
|
||||
* Repairs a booking edit draft that BusPro keeps rejecting.
|
||||
*
|
||||
* A draft survives every failed submission and is replayed on each re-entry into the edit flow.
|
||||
* When one selection inside it has become unacceptable to BusPro - a Leistung whose status has
|
||||
* drifted to "Anfrage" because its contingent ran out, say - the whole change is refused, nothing
|
||||
* persists, and the customer is stuck in a loop they cannot edit their way out of. Booking 98787
|
||||
* accumulated 37 such failures over two months.
|
||||
*
|
||||
* The valuable half of that draft is the personal data: names, dates of birth, contact details,
|
||||
* addresses, room remarks. Re-entering it by hand for eighty participants is not a reasonable ask.
|
||||
* So this command rebuilds the draft on top of the booking as BusPro currently holds it, keeps
|
||||
* every field the customer typed, and reverts only the service selections that BusPro will not
|
||||
* accept - naming each one, so the office can tell the customer what to pick again.
|
||||
*
|
||||
* Dry run by default. --apply writes a JSON backup of the original form data first.
|
||||
*/
|
||||
#[AsCommand(
|
||||
name: 'app:booking:repair-draft',
|
||||
description: 'Rebuild a rejected booking edit draft, keeping typed data and reverting unacceptable service selections',
|
||||
)]
|
||||
class BookingRepairDraftCommand extends Command
|
||||
{
|
||||
/**
|
||||
* Draft `services` keys holding a single service id.
|
||||
*/
|
||||
/**
|
||||
* Date of birth the office writes into the empty slots of a template booking.
|
||||
*/
|
||||
private const PLACEHOLDER_DATE_OF_BIRTH = '2000-01-01';
|
||||
|
||||
private const SINGLE_SERVICE_KEYS = ['skiPass', 'veg', 'insurance', 'rentalInsurance'];
|
||||
|
||||
/**
|
||||
* Draft `services` keys holding a list of service ids.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
private const LIST_SERVICE_KEYS = ['courses', 'board', 'rentals', 'additionalServices'];
|
||||
|
||||
/**
|
||||
* Transport is reverted as a unit: a participant put back on their own arrival must lose the
|
||||
* pickup and drop-off that only make sense on a coach.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
private const TRANSPORT_KEYS = ['transportationOutbound', 'transportationInbound', 'pickup', 'dropOff'];
|
||||
|
||||
public function __construct(
|
||||
private readonly BookingEditDraftRepository $draftRepository,
|
||||
private readonly EntityManagerInterface $entityManager,
|
||||
private readonly BookingClient $bookingClient,
|
||||
private readonly TravelClient $travelClient,
|
||||
private readonly Crypt $crypt,
|
||||
private readonly TravelDataProvider $travelDataProvider,
|
||||
private readonly BookingDataProcessor $bookingDataProcessor,
|
||||
private readonly BookingEditDraftMerger $draftMerger,
|
||||
private readonly BookingChangeTracker $changeTracker,
|
||||
#[Autowire('%kernel.project_dir%')]
|
||||
private readonly string $projectDir,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
protected function configure(): void
|
||||
{
|
||||
$this
|
||||
->addOption('booking', 'b', InputOption::VALUE_REQUIRED, 'idbuchung whose draft should be repaired')
|
||||
->addOption('apply', null, InputOption::VALUE_NONE, 'Write the repaired draft. Without this the command only reports')
|
||||
->addOption('backup-dir', null, InputOption::VALUE_REQUIRED, 'Where to write the backup of the original form data', 'var/draft-backups')
|
||||
;
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$io = new SymfonyStyle($input, $output);
|
||||
|
||||
$bookingId = $input->getOption('booking');
|
||||
if (null === $bookingId) {
|
||||
$io->error('--booking is required.');
|
||||
|
||||
return Command::INVALID;
|
||||
}
|
||||
|
||||
$draft = $this->findSingleDraft($io, (int) $bookingId);
|
||||
if (null === $draft) {
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$user = $draft->getUser();
|
||||
$booking = $this->fetchLiveBooking($io, $user, (int) $bookingId);
|
||||
if (null === $booking) {
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$travel = $this->travelDataProvider->getTravelData((int) $booking->dateId, $booking->hotelId, true);
|
||||
if (null === $travel) {
|
||||
$io->error(sprintf('No travel data for date id %d.', (int) $booking->dateId));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$formData = $draft->getFormData();
|
||||
$draftParticipants = $formData['participants'] ?? [];
|
||||
|
||||
if (false === $this->assertAlignment($io, $booking, $draftParticipants)) {
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$blocked = $this->collectUnbookableServices($io, $travel);
|
||||
|
||||
// The booking as BusPro currently holds it is the only state known to be acceptable, so
|
||||
// it is the base everything is rebuilt on.
|
||||
$repairedDto = $this->bookingDataProcessor->createBookingDtoFromBooking(
|
||||
$booking,
|
||||
$travel,
|
||||
false,
|
||||
);
|
||||
|
||||
$liveSelections = $this->changeTracker->extractUserData($repairedDto)['participants'] ?? [];
|
||||
|
||||
$reverted = [];
|
||||
foreach ($draftParticipants as $index => $participantData) {
|
||||
if (false === isset($repairedDto->participants[$index])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$filtered = $this->filterServiceSelections(
|
||||
$participantData,
|
||||
$liveSelections[$index]['services'] ?? [],
|
||||
$blocked,
|
||||
$index,
|
||||
$reverted,
|
||||
);
|
||||
|
||||
$this->draftMerger->apply($repairedDto, $index, $repairedDto->participants[$index], $filtered, $travel);
|
||||
}
|
||||
|
||||
$repaired = $this->changeTracker->extractUserData($repairedDto);
|
||||
|
||||
$this->report($io, $formData, $repaired, $reverted, $blocked);
|
||||
|
||||
if (false === $input->getOption('apply')) {
|
||||
$io->note('Dry run. Re-run with --apply to write the repaired draft.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$backupPath = $this->writeBackup($draft, (string) $input->getOption('backup-dir'));
|
||||
$io->success(sprintf('Original form data backed up to %s', $backupPath));
|
||||
|
||||
$draft->setFormData($repaired);
|
||||
$this->entityManager->flush();
|
||||
|
||||
$io->success(sprintf('Draft %d repaired.', (int) $draft->getId()));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
private function findSingleDraft(SymfonyStyle $io, int $bookingId): ?BookingEditDraft
|
||||
{
|
||||
$drafts = $this->draftRepository->findBy(['bookingId' => $bookingId]);
|
||||
|
||||
if ([] === $drafts) {
|
||||
$io->error(sprintf('No draft found for booking %d.', $bookingId));
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if (count($drafts) > 1) {
|
||||
$io->error(sprintf('Booking %d has %d drafts; resolve by hand.', $bookingId, count($drafts)));
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$draft = $drafts[0];
|
||||
$io->definitionList(
|
||||
['Draft' => sprintf('%d (user %d)', (int) $draft->getId(), (int) $draft->getUser()->getId())],
|
||||
['Created' => $draft->getCreatedAt()->format('Y-m-d H:i')],
|
||||
['Last saved' => $draft->getUpdatedAt()->format('Y-m-d H:i')],
|
||||
['Participants' => (string) count($draft->getFormData()['participants'] ?? [])],
|
||||
);
|
||||
|
||||
return $draft;
|
||||
}
|
||||
|
||||
private function fetchLiveBooking(SymfonyStyle $io, User $user, int $bookingId): ?Booking
|
||||
{
|
||||
$result = $this->bookingClient->getBooking(
|
||||
(string) $user->getEmail(),
|
||||
$this->crypt->decrypt((string) $user->getPassword()),
|
||||
$bookingId,
|
||||
);
|
||||
|
||||
if ($result instanceof Notification) {
|
||||
$io->error(sprintf('Vorgang_Details failed: %d %s', (int) $result->code, (string) $result->message));
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses to repair a draft whose positions no longer line up with the live booking.
|
||||
*
|
||||
* Drafts are merged positionally, by array index, with no identity check. Empty template
|
||||
* slots are interchangeable, so they prove nothing; the participants BusPro already knows by
|
||||
* date of birth are the only anchors available. If one of those has moved, every later
|
||||
* position is suspect and rebuilding would quietly graft data onto the wrong people.
|
||||
*
|
||||
* @param array<int, array<string, mixed>> $draftParticipants
|
||||
*/
|
||||
private function assertAlignment(SymfonyStyle $io, Booking $booking, array $draftParticipants): bool
|
||||
{
|
||||
$liveCount = count($booking->participants);
|
||||
$draftCount = count($draftParticipants);
|
||||
|
||||
if ($liveCount !== $draftCount) {
|
||||
$io->warning(sprintf(
|
||||
'Live booking has %d participants, the draft has %d. Seats were added or removed since the draft was written.',
|
||||
$liveCount,
|
||||
$draftCount,
|
||||
));
|
||||
}
|
||||
|
||||
$anchors = 0;
|
||||
$mismatches = [];
|
||||
|
||||
foreach (array_values($booking->participants) as $index => $participant) {
|
||||
$liveDob = $participant->dateOfBirth?->format('Y-m-d');
|
||||
if (null === $liveDob || self::PLACEHOLDER_DATE_OF_BIRTH === $liveDob) {
|
||||
continue;
|
||||
}
|
||||
|
||||
++$anchors;
|
||||
$draftDob = $draftParticipants[$index]['personalData']['dateOfBirth'] ?? null;
|
||||
|
||||
if (null !== $draftDob && $draftDob !== $liveDob) {
|
||||
$mismatches[] = sprintf('position %d: live %s, draft %s', $index + 1, $liveDob, $draftDob);
|
||||
}
|
||||
}
|
||||
|
||||
if ([] !== $mismatches) {
|
||||
$io->error('Draft positions no longer match the live booking:');
|
||||
$io->listing($mismatches);
|
||||
$io->comment('Repairing would move typed data onto the wrong participants. Resolve by hand.');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$io->text(sprintf('Alignment verified against %d participant(s) BusPro already knows.', $anchors));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects the services BusPro will not accept as an addition.
|
||||
*
|
||||
* A Leistung only takes new participants while its own status is "Frei"; anything else is the
|
||||
* condition behind "Status der Leistung (A) ist unterschiedlich zum Status des Teilnehmers".
|
||||
* Live availability is preferred over the travel data, which lags behind it.
|
||||
*
|
||||
* @return array<int, string> service id => status
|
||||
*/
|
||||
private function collectUnbookableServices(SymfonyStyle $io, Travel $travel): array
|
||||
{
|
||||
$statuses = [];
|
||||
foreach ([...$travel->additionalServices, ...$travel->transportationServices] as $service) {
|
||||
if (null !== $service->id && null !== $service->status) {
|
||||
$statuses[$service->id] = $service->status;
|
||||
}
|
||||
}
|
||||
|
||||
$live = $this->travelClient->getAvailabilitiesExtended((int) $travel->id);
|
||||
if ($live instanceof Notification) {
|
||||
$io->warning(sprintf(
|
||||
'VERFUEGBARKEIT2 failed (%d %s); falling back to travel data, which may be stale.',
|
||||
(int) $live->code,
|
||||
(string) $live->message,
|
||||
));
|
||||
} else {
|
||||
foreach ($live->getServices() as $availability) {
|
||||
if (null !== $availability->serviceId && null !== $availability->status && '' !== trim($availability->status)) {
|
||||
$statuses[$availability->serviceId] = $availability->status;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$blocked = array_filter($statuses, static fn (string $status): bool => Constants::STATUS_AVAILABLE !== $status);
|
||||
|
||||
if ([] === $blocked) {
|
||||
$io->text('Every service on this travel is currently "Frei".');
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = [];
|
||||
foreach ($blocked as $serviceId => $status) {
|
||||
$service = $travel->additionalServices[$serviceId] ?? $travel->transportationServices[$serviceId] ?? null;
|
||||
$label = $service instanceof Service ? (string) $service->label : '?';
|
||||
$rows[] = [$serviceId, $label, $status];
|
||||
}
|
||||
|
||||
$io->section('Services that cannot take new participants');
|
||||
$io->table(['id', 'Leistung', 'status'], $rows);
|
||||
|
||||
return $blocked;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the draft's selections that would add a participant to a service BusPro has closed.
|
||||
*
|
||||
* Removing a key leaves the live booking's own value in place, because the merger applies
|
||||
* only the keys it is given. Selections BusPro still accepts - a different ski pass, a meal
|
||||
* preference - are kept, so the customer loses as little as possible.
|
||||
*
|
||||
* @param array<string, mixed> $participantData
|
||||
* @param array<string, mixed> $liveServices
|
||||
* @param array<int, string> $blocked
|
||||
* @param list<string> $reverted
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function filterServiceSelections(
|
||||
array $participantData,
|
||||
array $liveServices,
|
||||
array $blocked,
|
||||
int $index,
|
||||
array &$reverted,
|
||||
): array {
|
||||
if (false === isset($participantData['services']) || [] === $blocked) {
|
||||
return $participantData;
|
||||
}
|
||||
|
||||
$services = $participantData['services'];
|
||||
$position = $index + 1;
|
||||
|
||||
foreach (self::SINGLE_SERVICE_KEYS as $key) {
|
||||
$selected = $services[$key] ?? null;
|
||||
if (null !== $selected && isset($blocked[$selected]) && ($liveServices[$key] ?? null) !== $selected) {
|
||||
unset($services[$key]);
|
||||
$reverted[] = sprintf('participant %d: %s (service %d, %s)', $position, $key, $selected, $blocked[$selected]);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (self::LIST_SERVICE_KEYS as $key) {
|
||||
$selected = $services[$key] ?? null;
|
||||
if (false === is_array($selected)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$liveList = $liveServices[$key] ?? [];
|
||||
$kept = [];
|
||||
foreach ($selected as $serviceId) {
|
||||
if (isset($blocked[$serviceId]) && false === in_array($serviceId, $liveList, true)) {
|
||||
$reverted[] = sprintf('participant %d: %s (service %d, %s)', $position, $key, $serviceId, $blocked[$serviceId]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$kept[] = $serviceId;
|
||||
}
|
||||
|
||||
$services[$key] = $kept;
|
||||
}
|
||||
|
||||
foreach (['transportationOutbound', 'transportationInbound'] as $key) {
|
||||
$selected = $services[$key] ?? null;
|
||||
if (null === $selected || false === isset($blocked[$selected]) || ($liveServices[$key] ?? null) === $selected) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$reverted[] = sprintf('participant %d: %s (service %d, %s)', $position, $key, $selected, $blocked[$selected]);
|
||||
|
||||
// Transport reverts as a unit, pickup and drop-off included.
|
||||
foreach (self::TRANSPORT_KEYS as $transportKey) {
|
||||
unset($services[$transportKey]);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
$participantData['services'] = $services;
|
||||
|
||||
return $participantData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $original
|
||||
* @param array<string, mixed> $repaired
|
||||
* @param list<string> $reverted
|
||||
* @param array<int, string> $blocked
|
||||
*/
|
||||
private function report(SymfonyStyle $io, array $original, array $repaired, array $reverted, array $blocked): void
|
||||
{
|
||||
$io->section('Typed data preserved');
|
||||
|
||||
$fields = ['firstName', 'lastName', 'dateOfBirth', 'email', 'mobile'];
|
||||
$kept = 0;
|
||||
$lost = [];
|
||||
|
||||
foreach ($original['participants'] ?? [] as $index => $participantData) {
|
||||
foreach ($fields as $field) {
|
||||
$before = $participantData['personalData'][$field] ?? null;
|
||||
if (null === $before || '' === $before) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$after = $repaired['participants'][$index]['personalData'][$field] ?? null;
|
||||
if ($before === $after) {
|
||||
++$kept;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$lost[] = sprintf('participant %d: %s', $index + 1, $field);
|
||||
}
|
||||
}
|
||||
|
||||
$io->text(sprintf('<info>%d</info> personal-data field(s) carried over.', $kept));
|
||||
|
||||
if ([] !== $lost) {
|
||||
$io->warning(sprintf('%d field(s) could NOT be carried over:', count($lost)));
|
||||
$io->listing(array_slice($lost, 0, 25));
|
||||
}
|
||||
|
||||
$io->section('Service selections reverted');
|
||||
|
||||
if ([] === $reverted) {
|
||||
$io->text([] === $blocked
|
||||
? 'None - no service on this travel is closed.'
|
||||
: 'None - the draft selects no closed service.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$io->warning(sprintf('%d selection(s) reverted to the booked state. The customer must choose again:', count($reverted)));
|
||||
$io->listing($reverted);
|
||||
}
|
||||
|
||||
private function writeBackup(BookingEditDraft $draft, string $backupDir): string
|
||||
{
|
||||
$directory = $this->projectDir.'/'.trim($backupDir, '/');
|
||||
if (false === is_dir($directory)) {
|
||||
mkdir($directory, 0o775, true);
|
||||
}
|
||||
|
||||
$path = sprintf(
|
||||
'%s/draft-%d-booking-%d-%s.json',
|
||||
$directory,
|
||||
(int) $draft->getId(),
|
||||
$draft->getBookingId(),
|
||||
(new \DateTimeImmutable())->format('Ymd-His'),
|
||||
);
|
||||
|
||||
file_put_contents($path, json_encode($draft->getFormData(), \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE));
|
||||
|
||||
return $path;
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,9 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Command;
|
||||
|
||||
use App\Entity\Groups\Accommodation;
|
||||
use App\Repository\Groups\AccommodationRepository;
|
||||
use App\Repository\Groups\ContingentDayRepository;
|
||||
use App\Repository\Groups\ContingentSyncStateRepository;
|
||||
use App\Service\ContingentHotelDirectory;
|
||||
use App\Service\ContingentSnapshotManager;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Psr\Log\LoggerInterface;
|
||||
@@ -28,14 +27,18 @@ use Symfony\Component\Console\Style\SymfonyStyle;
|
||||
*
|
||||
* Scheduled over the full horizon throughout: every 15 minutes during peak hours, hourly
|
||||
* outside them. The options exist for ad-hoc runs — a narrower --horizon-months, or --hotel
|
||||
* to re-sync a single accommodation while debugging.
|
||||
* to re-sync a single hotel code while debugging.
|
||||
*
|
||||
* Syncs every code of {@see ContingentHotelDirectory}: the accommodations' calendar codes plus
|
||||
* TYPO3's calendar hotels. A full run also drops the snapshot of codes that have left both
|
||||
* sources, so the snapshot tables only ever describe hotels that are still synced.
|
||||
*/
|
||||
class BpnSyncContingentsCommand extends Command
|
||||
{
|
||||
use LockableTrait;
|
||||
|
||||
public function __construct(
|
||||
private readonly AccommodationRepository $accommodationRepository,
|
||||
private readonly ContingentHotelDirectory $hotelDirectory,
|
||||
private readonly ContingentSyncStateRepository $syncStateRepository,
|
||||
private readonly ContingentDayRepository $dayRepository,
|
||||
private readonly ContingentSnapshotManager $snapshotManager,
|
||||
@@ -51,8 +54,8 @@ class BpnSyncContingentsCommand extends Command
|
||||
{
|
||||
$this
|
||||
->addOption('horizon-months', null, InputOption::VALUE_REQUIRED, 'How many months ahead to sync (defaults to the full horizon)', '24')
|
||||
->addOption('hotel', null, InputOption::VALUE_REQUIRED, 'Restrict the run to a single calendarCode')
|
||||
->addOption('stale-after', null, InputOption::VALUE_REQUIRED, 'Minimum minutes since the last sync before an accommodation is eligible (ignored with --force)', '0')
|
||||
->addOption('hotel', null, InputOption::VALUE_REQUIRED, 'Restrict the run to a single hotel code')
|
||||
->addOption('stale-after', null, InputOption::VALUE_REQUIRED, 'Minimum minutes since the last sync before a hotel is eligible (ignored with --force)', '0')
|
||||
->addOption('force', 'f', InputOption::VALUE_NONE, 'Sync even if the snapshot was refreshed recently')
|
||||
;
|
||||
}
|
||||
@@ -79,10 +82,13 @@ class BpnSyncContingentsCommand extends Command
|
||||
$dateFrom = $today->toDateTimeImmutable();
|
||||
$dateTo = $today->addMonths($horizonMonths)->toDateTimeImmutable();
|
||||
|
||||
$accommodations = $this->resolveAccommodations(is_string($hotelCode) ? $hotelCode : null);
|
||||
$this->hotelDirectory->refresh();
|
||||
// array_keys() turns a numeric code into an int.
|
||||
$allHotelCodes = array_map('strval', array_keys($this->hotelDirectory->all()));
|
||||
$hotelCodes = is_string($hotelCode) ? array_values(array_intersect($allHotelCodes, [$hotelCode])) : $allHotelCodes;
|
||||
|
||||
if ([] === $accommodations) {
|
||||
$io->warning('No accommodation with a calendarCode matched.');
|
||||
if ([] === $hotelCodes) {
|
||||
$io->warning('No accommodation calendarCode or TYPO3 calendar hotel matched.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
@@ -92,19 +98,19 @@ class BpnSyncContingentsCommand extends Command
|
||||
$changed = 0;
|
||||
$failedCodes = [];
|
||||
|
||||
foreach ($accommodations as $accommodation) {
|
||||
if (!$force && $this->isFresh($accommodation, $staleAfterMinutes)) {
|
||||
foreach ($hotelCodes as $code) {
|
||||
if (!$force && $this->isFresh($code, $staleAfterMinutes)) {
|
||||
++$skipped;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$result = $this->snapshotManager->sync($accommodation, $dateFrom, $dateTo);
|
||||
$result = $this->snapshotManager->sync($code, $dateFrom, $dateTo);
|
||||
++$processed;
|
||||
|
||||
if (!$result->successful) {
|
||||
$failedCodes[] = (string) $accommodation->getCalendarCode();
|
||||
$io->warning(sprintf('%s: %s', (string) $accommodation->getCalendarCode(), (string) $result->error));
|
||||
$failedCodes[] = $code;
|
||||
$io->warning(sprintf('%s: %s', $code, (string) $result->error));
|
||||
|
||||
continue;
|
||||
}
|
||||
@@ -115,7 +121,7 @@ class BpnSyncContingentsCommand extends Command
|
||||
|
||||
$io->writeln(sprintf(
|
||||
'<info>%s</info>: %s (+%d ~%d -%d, %d beyond the previous horizon)',
|
||||
(string) $accommodation->getCalendarCode(),
|
||||
$code,
|
||||
$result->changed ? 'changed' : 'unchanged',
|
||||
$result->added,
|
||||
$result->updated,
|
||||
@@ -149,6 +155,21 @@ class BpnSyncContingentsCommand extends Command
|
||||
$deleted = $this->dayRepository->deleteBefore($today->subDay()->toDateTimeImmutable());
|
||||
$io->note(sprintf('Deleted %d outdated snapshot days.', $deleted));
|
||||
|
||||
// Only a full run knows the whole set. A code that left both sources is not served any
|
||||
// more (the availability endpoint answers 400 for it), so its snapshot is dead weight;
|
||||
// should it come back, the next run rebuilds it.
|
||||
if (!is_string($hotelCode)) {
|
||||
$orphanedDays = $this->dayRepository->deleteExceptHotelCodes($allHotelCodes);
|
||||
$orphanedStates = $this->syncStateRepository->deleteExceptHotelCodes($allHotelCodes);
|
||||
|
||||
if ($orphanedStates > 0) {
|
||||
$this->logger->info('Dropped the contingent snapshot of hotel codes that are no longer synced', [
|
||||
'hotels' => $orphanedStates,
|
||||
'days' => $orphanedDays,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// Only a *total* failure is worth failing the task over: that means upstream is down or
|
||||
// the API key is rejected, and the scheduler's failure mail is genuinely actionable.
|
||||
// A single hotel breaking must stay quiet — this task runs every 15 minutes during the
|
||||
@@ -158,27 +179,13 @@ class BpnSyncContingentsCommand extends Command
|
||||
return $processed > 0 && $failed === $processed ? Command::FAILURE : Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Accommodation[]
|
||||
*/
|
||||
private function resolveAccommodations(?string $hotelCode): array
|
||||
{
|
||||
if (null === $hotelCode) {
|
||||
return $this->accommodationRepository->findAllWithCalendarCode();
|
||||
}
|
||||
|
||||
$accommodation = $this->accommodationRepository->findOneByCalendarCode($hotelCode);
|
||||
|
||||
return null !== $accommodation ? [$accommodation] : [];
|
||||
}
|
||||
|
||||
private function isFresh(Accommodation $accommodation, int $staleAfterMinutes): bool
|
||||
private function isFresh(string $hotelCode, int $staleAfterMinutes): bool
|
||||
{
|
||||
if (0 === $staleAfterMinutes) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$syncedAt = $this->syncStateRepository->findOneByAccommodation($accommodation)?->getSyncedAt();
|
||||
$syncedAt = $this->syncStateRepository->findOneByHotelCode($hotelCode)?->getSyncedAt();
|
||||
|
||||
if (null === $syncedAt) {
|
||||
return false;
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Command;
|
||||
|
||||
use App\Entity\TravelMailingList;
|
||||
use App\Exception\NewsletterProviderException;
|
||||
use App\Repository\TravelMailingListRepository;
|
||||
use App\Service\TravelMailingListManager;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Console\Style\SymfonyStyle;
|
||||
|
||||
#[AsCommand(
|
||||
name: 'app:cleanup:travel-mailing-lists',
|
||||
description: 'Deletes travel mailing lists and their orphaned contacts from Mailjet 30 days after the travel started',
|
||||
)]
|
||||
class CleanupTravelMailingListsCommand extends Command
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TravelMailingListRepository $travelMailingListRepository,
|
||||
private readonly TravelMailingListManager $travelMailingListManager,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$io = new SymfonyStyle($input, $output);
|
||||
|
||||
$mailingLists = $this->travelMailingListRepository->findDueForDeletion(new \DateTimeImmutable());
|
||||
if ([] === $mailingLists) {
|
||||
$io->success('No travel mailing lists due for deletion.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// A travel's lists are deleted together (see TravelMailingListManager::delete()), including
|
||||
// one that is not due yet because the travel's start date moved after it was created.
|
||||
$travelCodes = array_unique(array_map(static fn (TravelMailingList $mailingList) => $mailingList->getTravelCode(), $mailingLists));
|
||||
|
||||
$failed = 0;
|
||||
$deletedLists = 0;
|
||||
foreach ($travelCodes as $travelCode) {
|
||||
$travelLists = $this->travelMailingListRepository->findByTravelCode($travelCode);
|
||||
$listIds = implode(', ', array_map(static fn (TravelMailingList $mailingList) => $mailingList->getMailjetListId(), $travelLists));
|
||||
|
||||
try {
|
||||
$deletedContacts = $this->travelMailingListManager->delete($travelLists);
|
||||
$deletedLists += count($travelLists);
|
||||
$io->writeln(sprintf('Deleted %s (lists %s) and %d orphaned contact(s).', $travelCode, $listIds, $deletedContacts));
|
||||
} catch (NewsletterProviderException $exception) {
|
||||
// The rows of lists not yet deleted stay, so the next run picks them up again.
|
||||
++$failed;
|
||||
$this->logger->error('Delete travel mailing lists failed', [
|
||||
'travel_code' => $travelCode,
|
||||
'mailjet_list_ids' => $listIds,
|
||||
'error' => $exception->getMessage(),
|
||||
]);
|
||||
$io->error(sprintf('%s (lists %s): %s', $travelCode, $listIds, $exception->getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
if ($failed > 0) {
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$io->success(sprintf('Deleted %d travel mailing list(s).', $deletedLists));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller\Admin\TravelMailing;
|
||||
|
||||
use App\BpnConnect\Exception\BpnConnectException;
|
||||
use App\BpnConnect\TravelsClient;
|
||||
use App\BusProNet\Utility\DateCodeUtility;
|
||||
use App\Entity\TravelMailingList;
|
||||
use App\Exception\NewsletterProviderException;
|
||||
use App\Form\Model\TravelMailingLookupDto;
|
||||
use App\Repository\TravelMailingListRepository;
|
||||
use App\Service\TravelDataProvider;
|
||||
use App\Service\TravelMailingListManager;
|
||||
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;
|
||||
|
||||
#[IsGranted('ROLE_CUSTOMER_EXPERT')]
|
||||
class CreateListController extends AbstractController
|
||||
{
|
||||
public const string CSRF_TOKEN_ID = 'create_travel_mailing_list';
|
||||
|
||||
public function __construct(
|
||||
private readonly TravelsClient $travelsClient,
|
||||
private readonly TravelDataProvider $travelDataProvider,
|
||||
private readonly TravelMailingListRepository $travelMailingListRepository,
|
||||
private readonly TravelMailingListManager $travelMailingListManager,
|
||||
private readonly LoggerInterface $adminLogger,
|
||||
) {
|
||||
}
|
||||
|
||||
#[Route('/admin/travel-mailing/list', name: 'app_admin_travelmailing_createlist', methods: ['POST'])]
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
if (!$this->isCsrfTokenValid(self::CSRF_TOKEN_ID, $request->request->getString('_token'))) {
|
||||
throw $this->createAccessDeniedException('Invalid CSRF token.');
|
||||
}
|
||||
|
||||
$lookup = new TravelMailingLookupDto();
|
||||
$lookup->travelCode = (new DateCodeUtility())->sanitize($request->request->getString('travelCode'));
|
||||
$lookup->busOnly = $request->request->getBoolean('busOnly');
|
||||
$travelCode = $lookup->travelCode;
|
||||
$busLeg = $lookup->getBusLeg();
|
||||
$returnUrl = $this->generateUrl('app_admin_travelmailing', array_filter([
|
||||
'travelCode' => $travelCode,
|
||||
'busOnly' => $lookup->busOnly ? 1 : null,
|
||||
]));
|
||||
|
||||
$name = TravelMailingList::nameFor($travelCode, $busLeg);
|
||||
if (null !== $this->travelMailingListRepository->findOneByName($name)) {
|
||||
$this->addFlash('error', sprintf('Die Mailjet-Liste %s gibt es bereits.', $name));
|
||||
|
||||
return $this->redirect($returnUrl);
|
||||
}
|
||||
|
||||
$travelStartsAt = $this->travelDataProvider->mapDateCodeToStartDate($travelCode);
|
||||
if (null === $travelStartsAt) {
|
||||
$this->addFlash('error', sprintf('Für %s ist kein Reisebeginn bekannt, die Liste könnte nicht automatisch gelöscht werden.', $travelCode));
|
||||
|
||||
return $this->redirect($returnUrl);
|
||||
}
|
||||
|
||||
// Fetched again rather than posted from the page, so the list holds what BusPro reports now.
|
||||
try {
|
||||
$recipients = $this->travelsClient->getMailingRecipients($travelCode, $busLeg)->data;
|
||||
} catch (BpnConnectException) {
|
||||
$this->addFlash('error', 'Die Teilnehmerliste konnte nicht von BusPro abgerufen werden. Bitte später erneut versuchen.');
|
||||
|
||||
return $this->redirect($returnUrl);
|
||||
}
|
||||
|
||||
if ([] === $recipients) {
|
||||
$this->addFlash('error', sprintf('Keine Empfänger für %s gefunden.', $travelCode));
|
||||
|
||||
return $this->redirect($returnUrl);
|
||||
}
|
||||
|
||||
try {
|
||||
$mailingList = $this->travelMailingListManager->create($travelCode, $recipients, $busLeg, $travelStartsAt);
|
||||
} catch (NewsletterProviderException $exception) {
|
||||
$this->adminLogger->error('Create travel mailing list failed', [
|
||||
'travel_code' => $travelCode,
|
||||
'error' => $exception->getMessage(),
|
||||
]);
|
||||
$this->addFlash('error', 'Die Mailjet-Liste konnte nicht angelegt werden: '.$exception->getMessage());
|
||||
|
||||
return $this->redirect($returnUrl);
|
||||
}
|
||||
|
||||
$this->adminLogger->info('Create travel mailing list', [
|
||||
'travel_code' => $travelCode,
|
||||
'mailjet_list_id' => $mailingList->getMailjetListId(),
|
||||
'bus_leg' => $busLeg?->value,
|
||||
'recipients' => count($recipients),
|
||||
]);
|
||||
$this->addFlash('success', sprintf('Die Mailjet-Liste %s wurde mit %d Empfängern angelegt.', $mailingList->getName(), count($recipients)));
|
||||
|
||||
return $this->redirect($returnUrl);
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,10 @@ namespace App\Controller\Admin\TravelMailing;
|
||||
use App\BpnConnect\Exception\BpnConnectException;
|
||||
use App\BpnConnect\TravelsClient;
|
||||
use App\BusProNet\Utility\DateCodeUtility;
|
||||
use App\Entity\TravelMailingList;
|
||||
use App\Form\Admin\TravelMailingLookupType;
|
||||
use App\Form\Model\TravelMailingLookupDto;
|
||||
use App\Repository\TravelMailingListRepository;
|
||||
use App\Service\TravelDataProvider;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
@@ -22,6 +24,7 @@ class IndexController extends AbstractController
|
||||
public function __construct(
|
||||
private readonly TravelsClient $travelsClient,
|
||||
private readonly TravelDataProvider $travelDataProvider,
|
||||
private readonly TravelMailingListRepository $travelMailingListRepository,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -36,6 +39,10 @@ class IndexController extends AbstractController
|
||||
|
||||
$result = null;
|
||||
$travelLabel = null;
|
||||
$travelStartsAt = null;
|
||||
$mailingLists = [];
|
||||
$mailingList = null;
|
||||
$listName = null;
|
||||
$failed = false;
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
// The local index matches codes exactly, so "lpjmp-281126" has to become "LPJMP281126"
|
||||
@@ -43,8 +50,17 @@ class IndexController extends AbstractController
|
||||
$travelCode = (new DateCodeUtility())->sanitize((string) $lookup->travelCode);
|
||||
|
||||
try {
|
||||
$result = $this->travelsClient->getMailingRecipients($travelCode);
|
||||
$result = $this->travelsClient->getMailingRecipients($travelCode, $lookup->getBusLeg());
|
||||
$travelLabel = $this->travelDataProvider->mapDateCodeToLabel($travelCode);
|
||||
$travelStartsAt = $this->travelDataProvider->mapDateCodeToStartDate($travelCode);
|
||||
$mailingLists = $this->travelMailingListRepository->findByTravelCode($travelCode);
|
||||
// The list matching the current filter, if one exists, replaces the create button.
|
||||
$listName = TravelMailingList::nameFor($travelCode, $lookup->getBusLeg());
|
||||
foreach ($mailingLists as $existing) {
|
||||
if ($listName === $existing->getName()) {
|
||||
$mailingList = $existing;
|
||||
}
|
||||
}
|
||||
} catch (BpnConnectException) {
|
||||
// The client has already logged the cause; the page only needs to say it failed.
|
||||
$failed = true;
|
||||
@@ -55,6 +71,10 @@ class IndexController extends AbstractController
|
||||
'form' => $form,
|
||||
'result' => $result,
|
||||
'travel_label' => $travelLabel,
|
||||
'travel_starts_at' => $travelStartsAt,
|
||||
'mailing_lists' => $mailingLists,
|
||||
'mailing_list' => $mailingList,
|
||||
'list_name' => $listName,
|
||||
'failed' => $failed,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@ use App\Model\ContingentCalendarQuery;
|
||||
use App\Model\ContingentPricesQuery;
|
||||
use App\Repository\Groups\AccommodationPriceRepository;
|
||||
use App\Repository\Groups\AccommodationRepository;
|
||||
use App\Repository\Groups\ContingentSyncStateRepository;
|
||||
use App\Service\AccommodationPriceCoverage;
|
||||
use App\Service\ContingentHotelDirectory;
|
||||
use App\Service\ContingentSnapshotReader;
|
||||
use App\Service\PriceTimelineBuilder;
|
||||
use Carbon\CarbonImmutable;
|
||||
@@ -33,6 +35,8 @@ class ContingentController extends AbstractController
|
||||
private readonly ContingentSnapshotReader $snapshotReader,
|
||||
private readonly PriceTimelineBuilder $priceTimelineBuilder,
|
||||
private readonly AccommodationPriceCoverage $priceCoverage,
|
||||
private readonly ContingentHotelDirectory $hotelDirectory,
|
||||
private readonly ContingentSyncStateRepository $syncStateRepository,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
}
|
||||
@@ -107,7 +111,7 @@ class ContingentController extends AbstractController
|
||||
// An empty or stale snapshot must not be served as though every day were blocked: that
|
||||
// is a plausible-looking 200 nobody can distinguish from real data. Fail the way this
|
||||
// endpoint always failed instead, so existing consumers need no change.
|
||||
$statuses = $this->snapshotReader->statusesFor($accommodation, $dateFrom, $dateTo);
|
||||
$statuses = $this->snapshotReader->statusesFor($query->hotelCode, $dateFrom, $dateTo);
|
||||
|
||||
if (null === $statuses) {
|
||||
return $this->json(['error' => 'Failed to fetch contingent data.'], Response::HTTP_BAD_GATEWAY);
|
||||
@@ -133,6 +137,86 @@ class ContingentController extends AbstractController
|
||||
return $this->json($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* The snapshot as it is, for the iCal feed: no price rule, and days the snapshot lacks are
|
||||
* left out rather than blocked, so a portal shows them as free like it did with the feed
|
||||
* that read bpn-connect directly.
|
||||
*
|
||||
* Serves every synced hotel code, including TYPO3's calendar hotels that have no
|
||||
* accommodation (winter-only hotels).
|
||||
*/
|
||||
#[Route(path: '/contingents/availability', name: 'api_contingents_availability', methods: ['GET'])]
|
||||
public function availability(
|
||||
#[MapQueryString(validationFailedStatusCode: Response::HTTP_BAD_REQUEST)]
|
||||
ContingentCalendarQuery $query,
|
||||
): JsonResponse {
|
||||
if (null === $this->hotelDirectory->find($query->hotelCode)) {
|
||||
$this->logger->error('Hotel not found for hotelcode '.$query->hotelCode);
|
||||
|
||||
return $this->json(['error' => 'Hotel not found for hotelCode.'], Response::HTTP_BAD_REQUEST);
|
||||
}
|
||||
|
||||
// Without a range: from today to wherever the snapshot ends.
|
||||
$dateFrom = $query->dateFromDate() ?? CarbonImmutable::now()->setTime(0, 0);
|
||||
$dateTo = $query->dateToDate();
|
||||
|
||||
// Same reasoning as calendar(): a missing or stale snapshot must not pass for real data.
|
||||
// Here it matters even more, since an empty feed would show every day as free.
|
||||
$statuses = $this->snapshotReader->statusesFor($query->hotelCode, $dateFrom, $dateTo);
|
||||
|
||||
if (null === $statuses) {
|
||||
return $this->json(['error' => 'Failed to fetch contingent data.'], Response::HTTP_BAD_GATEWAY);
|
||||
}
|
||||
|
||||
ksort($statuses);
|
||||
|
||||
$data = [];
|
||||
|
||||
foreach ($statuses as $date => $status) {
|
||||
$data[] = ['date' => (string) $date, 'status' => $status->value];
|
||||
}
|
||||
|
||||
return $this->json($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* One row per synced hotel code, for the overview of which hotel supports which calendar.
|
||||
*
|
||||
* `available` is whether `availability` currently serves the hotel; calendar and price table
|
||||
* additionally need an accommodation with prices, which `pricedFrom`/`pricedTo` show.
|
||||
*/
|
||||
#[Route(path: '/contingents/status', name: 'api_contingents_status', methods: ['GET'])]
|
||||
public function status(): JsonResponse
|
||||
{
|
||||
$states = $this->syncStateRepository->findAllIndexedByHotelCode();
|
||||
|
||||
$data = [];
|
||||
|
||||
foreach ($this->hotelDirectory->all() as $hotel) {
|
||||
$state = $states[$hotel->code] ?? null;
|
||||
$accommodation = $hotel->accommodation;
|
||||
$bounds = null !== $accommodation ? $this->priceRepository->findPricedDateBoundsByHotelCode($hotel->code) : null;
|
||||
|
||||
$data[] = [
|
||||
'hotelCode' => $hotel->code,
|
||||
'name' => $hotel->calendarHotel?->getName(),
|
||||
'sources' => array_map(static fn ($source) => $source->value, $hotel->sources()),
|
||||
'accommodation' => null !== $accommodation ? [
|
||||
'name' => $accommodation->getName(),
|
||||
'cmsCode' => $accommodation->getEffectiveCmsCode(),
|
||||
] : null,
|
||||
'pricedFrom' => null !== $bounds ? $bounds['from']->format('Y-m-d') : null,
|
||||
'pricedTo' => null !== $bounds ? $bounds['to']->format('Y-m-d') : null,
|
||||
'syncedAt' => $state?->getSyncedAt()?->format(\DateTimeInterface::ATOM),
|
||||
'lastError' => $state?->getLastError(),
|
||||
'failureCount' => $state?->getFailureCount() ?? 0,
|
||||
'available' => $this->snapshotReader->isCurrent($state),
|
||||
];
|
||||
}
|
||||
|
||||
return $this->json($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param AccommodationPrice[] $prices
|
||||
* @param array<string, true> $covered
|
||||
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace App\Controller\Booking\Create;
|
||||
|
||||
use App\BusProNet\XmlLoader\AgencyLoader;
|
||||
use App\Exception\BookingBackendUnavailableException;
|
||||
use App\Exception\HotelNotFoundException;
|
||||
use App\Exception\HotelNotInTravelException;
|
||||
use App\Exception\NoRoomsAvailableException;
|
||||
@@ -119,6 +120,10 @@ class IndexController extends AbstractController
|
||||
} catch (TravelNotFoundException|HotelNotFoundException|HotelNotInTravelException|NoRoomsAvailableException $e) {
|
||||
$this->addFlash('error', $e->getMessage());
|
||||
|
||||
return $this->htmxRedirect($request, $this->generateUrl('app_booking_create_error'));
|
||||
} catch (BookingBackendUnavailableException) {
|
||||
$this->addFlash('error', 'Unser Buchungssystem ist gerade nicht erreichbar. Bitte versuche es in ein paar Minuten erneut.');
|
||||
|
||||
return $this->htmxRedirect($request, $this->generateUrl('app_booking_create_error'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,6 @@ use App\Htmx\HxTrait;
|
||||
use App\Service\BookingConfigurator;
|
||||
use App\Service\BookingCreateContextFactory;
|
||||
use App\Service\BookingSessionManager;
|
||||
use App\Service\RoomPricingCalculator;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
@@ -66,7 +65,6 @@ class Step1Controller extends AbstractBookingCreateController
|
||||
$bookingCreateDto->resetParticipantAssignments();
|
||||
}
|
||||
|
||||
// Check if room selection forces inquiry mode
|
||||
$this->bookingService->updateBookingStatusFromRoomSelection($bookingCreateDto);
|
||||
|
||||
$bookingCreateDto->currentStep = 2;
|
||||
@@ -78,10 +76,7 @@ class Step1Controller extends AbstractBookingCreateController
|
||||
return $this->redirectToRoute('app_booking_create_step_2');
|
||||
}
|
||||
|
||||
$context = $this->createContextFactory->create(
|
||||
$bookingCreateDto,
|
||||
RoomPricingCalculator::PRICING_MODE_SELECTION
|
||||
);
|
||||
$context = $this->createContextFactory->createForRoomSelection($bookingCreateDto);
|
||||
|
||||
return $this->render('booking/create/step_1.html.twig', [
|
||||
'bookingCreateContext' => $context,
|
||||
@@ -108,10 +103,7 @@ class Step1Controller extends AbstractBookingCreateController
|
||||
]);
|
||||
$form->handleRequest($request);
|
||||
|
||||
$context = $this->createContextFactory->create(
|
||||
$bookingCreateDto,
|
||||
RoomPricingCalculator::PRICING_MODE_SELECTION
|
||||
);
|
||||
$context = $this->createContextFactory->createForRoomSelection($bookingCreateDto);
|
||||
|
||||
// The DTO is now updated with the latest selection.
|
||||
// We can now render the blocks with the fresh data.
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace App\Controller\Booking\Create;
|
||||
|
||||
use App\BusProNet\Model\Travel;
|
||||
use App\Entity\User;
|
||||
use App\Exception\BookingBackendUnavailableException;
|
||||
use App\Exception\BookingSessionNotFoundException;
|
||||
use App\Exception\HotelNotInTravelException;
|
||||
use App\Exception\TravelNotFoundException;
|
||||
@@ -67,8 +68,19 @@ class Step2Controller extends AbstractBookingCreateController
|
||||
return $redirect;
|
||||
}
|
||||
|
||||
// Enrich with fresh availability data
|
||||
$this->travelDataService->enrichWithFreshAvailabilities($bookingCreateDto->travel);
|
||||
// Enrich with fresh availability data. Opening the step is the last moment before the customer
|
||||
// types in participant data, so an unreachable BusPro stops them here rather than at the inquiry
|
||||
// in step 3. Submitting the step stays lenient: the data is entered by then, and step 3 says so.
|
||||
try {
|
||||
$this->travelDataService->enrichWithFreshAvailabilities(
|
||||
$bookingCreateDto->travel,
|
||||
requireReachable: false === $request->isMethod(Request::METHOD_POST),
|
||||
);
|
||||
} catch (BookingBackendUnavailableException) {
|
||||
$this->addFlash('error', 'Unser Buchungssystem ist gerade nicht erreichbar. Deine Zimmerauswahl bleibt gespeichert, bitte versuche es in ein paar Minuten erneut.');
|
||||
|
||||
return $this->redirectToRoute('app_booking_create_step_1');
|
||||
}
|
||||
|
||||
// Resync the room selections with the refreshed travel before any participant count is derived
|
||||
// from them, and send the customer back to step 1 when a room they picked is gone.
|
||||
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace App\Controller\Booking\Create;
|
||||
|
||||
use App\BusProNet\Client\BookingClient;
|
||||
use App\BusProNet\Exception\ApiClientException;
|
||||
use App\BusProNet\Exception\TimeoutException;
|
||||
use App\BusProNet\Model\BookingResponse;
|
||||
use App\BusProNet\Model\Notification;
|
||||
@@ -183,7 +184,17 @@ class Step3Controller extends AbstractBookingCreateController
|
||||
'exception' => $e->getMessage(),
|
||||
'trace' => $e->getTraceAsString(),
|
||||
],
|
||||
'Die Anfrage hat zu lange gedauert. Bitte versuche es erneut oder wende dich an den Kundenservice.',
|
||||
'Die Anfrage hat zu lange gedauert. Deine Angaben bleiben gespeichert, bitte versuche es in ein paar Minuten erneut oder wende dich an den Kundenservice.',
|
||||
);
|
||||
} catch (ApiClientException $e) {
|
||||
$this->handleApiError(
|
||||
$this->logger,
|
||||
'Booking inquiry failed to reach BusPro',
|
||||
[
|
||||
'exception' => $e->getMessage(),
|
||||
'trace' => $e->getTraceAsString(),
|
||||
],
|
||||
'Unser Buchungssystem ist gerade nicht erreichbar. Deine Angaben bleiben gespeichert, bitte versuche es in ein paar Minuten erneut.',
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
$this->handleApiError(
|
||||
|
||||
@@ -240,7 +240,7 @@ class Step1Controller extends AbstractController
|
||||
\DateTimeImmutable $dateTo,
|
||||
): array {
|
||||
$contingentStatus = null !== $accommodation
|
||||
? $this->snapshotReader->statusesFor($accommodation, $dateFrom, $dateTo) ?? []
|
||||
? $this->snapshotReader->statusesFor($hotelCode, $dateFrom, $dateTo) ?? []
|
||||
: [];
|
||||
|
||||
$prices = $this->priceRepository->findByHotelCodeAndDateRange($hotelCode, $dateFrom, $dateTo);
|
||||
|
||||
@@ -55,6 +55,14 @@ class Mailer
|
||||
->context($context)
|
||||
;
|
||||
|
||||
// Mailjet tracks per its account settings unless a message says otherwise: an open pixel
|
||||
// and links rewritten through its redirect domain. These headers only work over SMTP - the
|
||||
// Send API refuses them - and Symfony's SMTP transport passes them through untouched.
|
||||
$email->getHeaders()
|
||||
->addTextHeader('X-Mailjet-TrackOpen', '0')
|
||||
->addTextHeader('X-Mailjet-TrackClick', '0')
|
||||
;
|
||||
|
||||
foreach ($config['attachments'] as $attachment) {
|
||||
/* @var EmailAttachmentInterface $attachment */
|
||||
$attachment->attachTo($email);
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Entity\Groups;
|
||||
|
||||
use App\Repository\Groups\CalendarHotelRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
|
||||
/**
|
||||
* Local copy of the last calendar hotel list TYPO3 answered successfully.
|
||||
*
|
||||
* Kept so the contingent sync still covers TYPO3's hotels while TYPO3 is unreachable. Written
|
||||
* only by {@see \App\Service\ContingentHotelDirectory::refresh()}, never by hand: the list is
|
||||
* TYPO3's, this is not a third place to maintain hotel codes in.
|
||||
*/
|
||||
#[ORM\Entity(repositoryClass: CalendarHotelRepository::class)]
|
||||
#[ORM\Table(name: 'calendar_hotel')]
|
||||
class CalendarHotel
|
||||
{
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(length: 16, unique: true)]
|
||||
private ?string $code = null;
|
||||
|
||||
#[ORM\Column(length: 255)]
|
||||
private ?string $name = null;
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getCode(): ?string
|
||||
{
|
||||
return $this->code;
|
||||
}
|
||||
|
||||
public function setCode(string $code): self
|
||||
{
|
||||
$this->code = $code;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getName(): ?string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
public function setName(string $name): self
|
||||
{
|
||||
$this->name = $name;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -12,11 +12,14 @@ use Doctrine\ORM\Mapping as ORM;
|
||||
/**
|
||||
* Local snapshot of a single day of contingent availability as reported by bpn-connect.
|
||||
*
|
||||
* Keyed by hotel code, not by accommodation: the snapshot also covers TYPO3's calendar hotels,
|
||||
* which have no `Accommodation`.
|
||||
*
|
||||
* Written exclusively by the scheduled sync, never by a user, hence no Blameable/Timestampable.
|
||||
*/
|
||||
#[ORM\Entity(repositoryClass: ContingentDayRepository::class)]
|
||||
#[ORM\Table(name: 'contingent_day')]
|
||||
#[ORM\UniqueConstraint(name: 'uniq_contingent_day_accommodation_date', columns: ['accommodation_id', 'date'])]
|
||||
#[ORM\UniqueConstraint(name: 'uniq_contingent_day_hotel_code_date', columns: ['hotel_code', 'date'])]
|
||||
class ContingentDay
|
||||
{
|
||||
#[ORM\Id]
|
||||
@@ -24,8 +27,15 @@ class ContingentDay
|
||||
#[ORM\Column]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(length: 16)]
|
||||
private ?string $hotelCode = null;
|
||||
|
||||
/**
|
||||
* Superseded by $hotelCode and no longer written. Only rows from before the switch still
|
||||
* carry it; it stays mapped until the column is dropped, so the switch can be rolled back.
|
||||
*/
|
||||
#[ORM\ManyToOne]
|
||||
#[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
|
||||
#[ORM\JoinColumn(nullable: true, onDelete: 'CASCADE')]
|
||||
private ?Accommodation $accommodation = null;
|
||||
|
||||
#[ORM\Column(type: Types::DATE_IMMUTABLE)]
|
||||
@@ -39,6 +49,18 @@ class ContingentDay
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getHotelCode(): ?string
|
||||
{
|
||||
return $this->hotelCode;
|
||||
}
|
||||
|
||||
public function setHotelCode(string $hotelCode): self
|
||||
{
|
||||
$this->hotelCode = $hotelCode;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getAccommodation(): ?Accommodation
|
||||
{
|
||||
return $this->accommodation;
|
||||
|
||||
@@ -9,7 +9,7 @@ use Doctrine\DBAL\Types\Types;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
|
||||
/**
|
||||
* Bookkeeping for the scheduled contingent sync of a single accommodation.
|
||||
* Bookkeeping for the scheduled contingent sync of a single hotel code.
|
||||
*
|
||||
* `changedAt` records when the sync last saw a day appear, vanish or switch status within the
|
||||
* horizon it had already reached; `horizonTo` is how far that reach extends.
|
||||
@@ -23,8 +23,14 @@ class ContingentSyncState
|
||||
#[ORM\Column]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(length: 16, unique: true)]
|
||||
private ?string $hotelCode = null;
|
||||
|
||||
/**
|
||||
* Superseded by $hotelCode, see {@see ContingentDay::$accommodation}.
|
||||
*/
|
||||
#[ORM\OneToOne]
|
||||
#[ORM\JoinColumn(nullable: false, unique: true, onDelete: 'CASCADE')]
|
||||
#[ORM\JoinColumn(nullable: true, unique: true, onDelete: 'CASCADE')]
|
||||
private ?Accommodation $accommodation = null;
|
||||
|
||||
/**
|
||||
@@ -48,9 +54,9 @@ class ContingentSyncState
|
||||
#[ORM\Column]
|
||||
private int $failureCount = 0;
|
||||
|
||||
public function __construct(?Accommodation $accommodation = null)
|
||||
public function __construct(?string $hotelCode = null)
|
||||
{
|
||||
$this->accommodation = $accommodation;
|
||||
$this->hotelCode = $hotelCode;
|
||||
}
|
||||
|
||||
public function getId(): ?int
|
||||
@@ -58,6 +64,11 @@ class ContingentSyncState
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getHotelCode(): ?string
|
||||
{
|
||||
return $this->hotelCode;
|
||||
}
|
||||
|
||||
public function getAccommodation(): ?Accommodation
|
||||
{
|
||||
return $this->accommodation;
|
||||
|
||||
@@ -50,6 +50,21 @@ class OAuth2Client extends AbstractClient
|
||||
#[ORM\Column(type: 'json')]
|
||||
private array $requiredRoles = [];
|
||||
|
||||
/**
|
||||
* Where BackchannelLogoutListener tells this client that an account logged out of
|
||||
* MyE&P. Null for a client that has no back channel, which is then simply not told.
|
||||
*/
|
||||
#[ORM\Column(type: 'string', length: 255, nullable: true)]
|
||||
private ?string $logoutUrl = null;
|
||||
|
||||
/**
|
||||
* The bearer token sent with the back-channel logout call. Stored readable, unlike the
|
||||
* client secret, because MyE&P is the side that sends it rather than the side that
|
||||
* checks it.
|
||||
*/
|
||||
#[ORM\Column(type: 'string', length: 128, nullable: true)]
|
||||
private ?string $logoutSecret = null;
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
@@ -67,4 +82,28 @@ class OAuth2Client extends AbstractClient
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getLogoutUrl(): ?string
|
||||
{
|
||||
return $this->logoutUrl;
|
||||
}
|
||||
|
||||
public function setLogoutUrl(?string $logoutUrl): self
|
||||
{
|
||||
$this->logoutUrl = $logoutUrl;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getLogoutSecret(): ?string
|
||||
{
|
||||
return $this->logoutSecret;
|
||||
}
|
||||
|
||||
public function setLogoutSecret(?string $logoutSecret): self
|
||||
{
|
||||
$this->logoutSecret = $logoutSecret;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Entity;
|
||||
|
||||
use App\Enum\BusLeg;
|
||||
use App\Repository\TravelMailingListRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
|
||||
/**
|
||||
* A Mailjet contact list created for one travel's participants. The row exists so the list can
|
||||
* be deleted again once the travel is past; the list itself is never updated after creation.
|
||||
*
|
||||
* A travel can have two lists, one for all participants and one for bus passengers only, told
|
||||
* apart by their name.
|
||||
*/
|
||||
#[ORM\Entity(repositoryClass: TravelMailingListRepository::class)]
|
||||
#[ORM\Index(columns: ['travel_code'])]
|
||||
class TravelMailingList
|
||||
{
|
||||
private const string BUS_ONLY_SUFFIX = ' nur Bus';
|
||||
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 32)]
|
||||
private string $travelCode;
|
||||
|
||||
/** The Mailjet list name. */
|
||||
#[ORM\Column(type: 'string', length: 64, unique: true)]
|
||||
private string $name;
|
||||
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private int $mailjetListId;
|
||||
|
||||
/** The bus leg its participants were filtered by; null when it holds all participants. */
|
||||
#[ORM\Column(length: 20, nullable: true, enumType: BusLeg::class)]
|
||||
private ?BusLeg $busLeg;
|
||||
|
||||
#[ORM\Column(type: 'datetime_immutable')]
|
||||
private \DateTimeImmutable $deleteAfter;
|
||||
|
||||
#[ORM\Column(type: 'datetime_immutable')]
|
||||
private \DateTimeImmutable $createdAt;
|
||||
|
||||
public function __construct(string $travelCode, int $mailjetListId, ?BusLeg $busLeg, \DateTimeImmutable $deleteAfter)
|
||||
{
|
||||
$this->travelCode = $travelCode;
|
||||
$this->name = self::nameFor($travelCode, $busLeg);
|
||||
$this->mailjetListId = $mailjetListId;
|
||||
$this->busLeg = $busLeg;
|
||||
$this->deleteAfter = $deleteAfter;
|
||||
$this->createdAt = new \DateTimeImmutable();
|
||||
}
|
||||
|
||||
public static function nameFor(string $travelCode, ?BusLeg $busLeg): string
|
||||
{
|
||||
return null !== $busLeg ? $travelCode.self::BUS_ONLY_SUFFIX : $travelCode;
|
||||
}
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getTravelCode(): string
|
||||
{
|
||||
return $this->travelCode;
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
public function getMailjetListId(): int
|
||||
{
|
||||
return $this->mailjetListId;
|
||||
}
|
||||
|
||||
public function getBusLeg(): ?BusLeg
|
||||
{
|
||||
return $this->busLeg;
|
||||
}
|
||||
|
||||
public function getDeleteAfter(): \DateTimeImmutable
|
||||
{
|
||||
return $this->deleteAfter;
|
||||
}
|
||||
|
||||
public function getCreatedAt(): \DateTimeImmutable
|
||||
{
|
||||
return $this->createdAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Enum;
|
||||
|
||||
/**
|
||||
* Which bus leg a travel participant must have booked to be selected, as bpn-connect's travel
|
||||
* mailing endpoint takes it (`busLeg`).
|
||||
*/
|
||||
enum BusLeg: string
|
||||
{
|
||||
case Outbound = 'outbound';
|
||||
case Inbound = 'inbound';
|
||||
case Any = 'any';
|
||||
case Both = 'both';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Outbound => 'Busreisende (Hinfahrt)',
|
||||
self::Inbound => 'Busreisende (Rückfahrt)',
|
||||
self::Any => 'Busreisende (Hin- oder Rückfahrt)',
|
||||
self::Both => 'Busreisende (Hin- und Rückfahrt)',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Enum;
|
||||
|
||||
/**
|
||||
* Where a hotel code in the contingent snapshot comes from. A code can have both.
|
||||
*/
|
||||
enum ContingentHotelSource: string
|
||||
{
|
||||
/** The calendarCode of a group house (`Accommodation`). */
|
||||
case Accommodation = 'accommodation';
|
||||
|
||||
/** The calendar hotel of a visible TYPO3 product, from TYPO3's `/api/calendar-hotels`. */
|
||||
case Typo3 = 'typo3';
|
||||
}
|
||||
@@ -39,7 +39,7 @@ class AuthorizationCodeListener
|
||||
private readonly UrlGeneratorInterface $urlGenerator,
|
||||
private readonly RequestStack $requestStack,
|
||||
private readonly Security $security,
|
||||
private readonly LoggerInterface $authenticationLogger,
|
||||
private readonly LoggerInterface $authLogger,
|
||||
private readonly Environment $twig,
|
||||
) {
|
||||
}
|
||||
@@ -62,7 +62,7 @@ class AuthorizationCodeListener
|
||||
Response::HTTP_TEMPORARY_REDIRECT
|
||||
);
|
||||
$event->setResponse($response);
|
||||
$this->authenticationLogger->info('Authorization request without session');
|
||||
$this->authLogger->info('Authorization request without session');
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -126,7 +126,7 @@ class AuthorizationCodeListener
|
||||
array $required,
|
||||
string $reason,
|
||||
): void {
|
||||
$this->authenticationLogger->info('Authorization request denied', [
|
||||
$this->authLogger->info('Authorization request denied', [
|
||||
'client' => $client,
|
||||
'user_id' => $user->getId(),
|
||||
'required_roles' => $required,
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\EventListener;
|
||||
|
||||
use App\Entity\OAuth2Client;
|
||||
use App\Entity\User;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
|
||||
use Symfony\Component\Security\Http\Event\LogoutEvent;
|
||||
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
|
||||
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
|
||||
/**
|
||||
* Tells every client application with a back channel that an account logged out of MyE&P,
|
||||
* so the application can end that account's sessions as well.
|
||||
*
|
||||
* Each client gets a form-encoded POST of the account's `sub` — the uuid, exactly as
|
||||
* /api/userinfo exports it — authorized with the client's own logout secret. The call is
|
||||
* best effort: a client that is down, slow or misconfigured is logged and skipped, because
|
||||
* a failed call must never keep the user signed in to MyE&P.
|
||||
*
|
||||
* Only an explicit logout gets here. A session that merely expires dispatches nothing, so
|
||||
* the client applications are not told about it.
|
||||
*
|
||||
* Runs before SessionLogoutListener (priority 0), which invalidates the session the
|
||||
* `_oauth2` flag is read from.
|
||||
*/
|
||||
#[AsEventListener(event: LogoutEvent::class, priority: 64)]
|
||||
class BackchannelLogoutListener
|
||||
{
|
||||
public function __construct(
|
||||
private readonly EntityManagerInterface $entityManager,
|
||||
private readonly HttpClientInterface $httpClient,
|
||||
private readonly LoggerInterface $authLogger,
|
||||
) {
|
||||
}
|
||||
|
||||
public function __invoke(LogoutEvent $event): void
|
||||
{
|
||||
$user = $event->getToken()?->getUser();
|
||||
|
||||
if (false === $user instanceof User) {
|
||||
return;
|
||||
}
|
||||
|
||||
// AuthorizationCodeListener logs the user out of MyE&P straight after authorizing an
|
||||
// application that sent them here to sign in. Telling the applications about that
|
||||
// logout would sign the user out of the very application they just signed in to.
|
||||
if ($event->getRequest()->hasSession() && true === $event->getRequest()->getSession()->get('_oauth2', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// a handful of rows, so filtered here rather than in a query
|
||||
$clients = array_filter(
|
||||
$this->entityManager->getRepository(OAuth2Client::class)->findAll(),
|
||||
static fn (OAuth2Client $client): bool => null !== $client->getLogoutUrl(),
|
||||
);
|
||||
|
||||
// Requests first, responses second: HttpClient sends concurrently, so a slow client
|
||||
// costs its own timeout once rather than adding it to every other client's.
|
||||
$responses = [];
|
||||
foreach ($clients as $client) {
|
||||
try {
|
||||
$responses[] = [$client, $this->httpClient->request('POST', (string) $client->getLogoutUrl(), [
|
||||
'auth_bearer' => (string) $client->getLogoutSecret(),
|
||||
'body' => ['sub' => $user->getUuid()],
|
||||
'timeout' => 3,
|
||||
])];
|
||||
} catch (ExceptionInterface $e) {
|
||||
// a malformed URL is refused before anything is sent
|
||||
$this->warn($client, $user, ['error' => $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($responses as [$client, $response]) {
|
||||
try {
|
||||
$status = $response->getStatusCode();
|
||||
} catch (ExceptionInterface $e) {
|
||||
$this->warn($client, $user, ['error' => $e->getMessage()]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (200 !== $status) {
|
||||
$this->warn($client, $user, ['status' => $status]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $context
|
||||
*/
|
||||
private function warn(OAuth2Client $client, User $user, array $context): void
|
||||
{
|
||||
$this->authLogger->warning('Back-channel logout failed', [
|
||||
'client' => $client->getName(),
|
||||
'user_id' => $user->getId(),
|
||||
] + $context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Exception;
|
||||
|
||||
/**
|
||||
* Thrown when BusPro cannot be reached at a point where the booking flow must not continue without it.
|
||||
*
|
||||
* The flow can render most steps from XML export and snapshot data, but the inquiry in step 3 and the
|
||||
* booking itself always need BusPro. Failing before the customer types in participant data is kinder
|
||||
* than failing after.
|
||||
*/
|
||||
class BookingBackendUnavailableException extends \RuntimeException
|
||||
{
|
||||
}
|
||||
@@ -6,13 +6,14 @@ namespace App\Form\Admin;
|
||||
|
||||
use App\Form\Model\TravelMailingLookupDto;
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\TextType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
|
||||
/**
|
||||
* Submits as GET with an empty block prefix, so a lookup is the plain URL `?travelCode=…`
|
||||
* and can be bookmarked or shared.
|
||||
* (plus `&busOnly=1`) and can be bookmarked or shared.
|
||||
*
|
||||
* @extends AbstractType<TravelMailingLookupDto>
|
||||
*/
|
||||
@@ -26,6 +27,10 @@ class TravelMailingLookupType extends AbstractType
|
||||
'placeholder' => 'z. B. LPJMP281126',
|
||||
],
|
||||
]);
|
||||
$builder->add('busOnly', CheckboxType::class, [
|
||||
'label' => 'nur '.TravelMailingLookupDto::BUS_LEG->label(),
|
||||
'required' => false,
|
||||
]);
|
||||
}
|
||||
|
||||
public function configureOptions(OptionsResolver $resolver): void
|
||||
|
||||
@@ -4,11 +4,11 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Form;
|
||||
|
||||
use App\BusProNet\Form\CountryType;
|
||||
use App\Form\Model\ParticipantDto;
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\BirthdayType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\CountryType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\EmailType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\TextType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
@@ -53,6 +53,8 @@ class BookingApplicantType extends AbstractType
|
||||
->add('nationality', CountryType::class, [
|
||||
'label' => 'Nationalität',
|
||||
'required' => true,
|
||||
'property' => 'nationality',
|
||||
'placeholder' => 'Bitte auswählen...',
|
||||
'preferred_choices' => ['D', 'A', 'CH'],
|
||||
])
|
||||
->add('dateOfBirth', BirthdayType::class, [
|
||||
@@ -72,7 +74,6 @@ class BookingApplicantType extends AbstractType
|
||||
->add('mobile', TextType::class, [
|
||||
'label' => 'Telefon (mobil)',
|
||||
'required' => true,
|
||||
'sanitize_html' => true,
|
||||
'attr' => [
|
||||
'autocomplete' => 'leave-me-alone-chrome',
|
||||
],
|
||||
|
||||
@@ -3,14 +3,22 @@
|
||||
namespace App\Form;
|
||||
|
||||
use App\Form\Model\BookingDto;
|
||||
use App\Service\RoomContingentPoolResolver;
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\Form\FormInterface;
|
||||
use Symfony\Component\Form\FormView;
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
|
||||
/** @extends AbstractType<BookingDto> */
|
||||
class BookingCreateStep1Type extends AbstractType
|
||||
{
|
||||
public function __construct(
|
||||
private readonly RoomContingentPoolResolver $poolResolver,
|
||||
) {
|
||||
}
|
||||
|
||||
public function buildForm(FormBuilderInterface $builder, array $options): void
|
||||
{
|
||||
$builder
|
||||
@@ -28,6 +36,33 @@ class BookingCreateStep1Type extends AbstractType
|
||||
;
|
||||
}
|
||||
|
||||
/**
|
||||
* Caps the step buttons of rooms sharing a contingent at what the other rooms leave of it.
|
||||
*
|
||||
* Runs on every render, including the htmx refresh after each change, so selecting one room
|
||||
* of a pool locks the others once the pool is used up. Only the view changes: the choices
|
||||
* keep the room's own count, and RoomSelectionValidator stays the check on submit.
|
||||
*/
|
||||
public function finishView(FormView $view, FormInterface $form, array $options): void
|
||||
{
|
||||
$bookingDto = $form->getData();
|
||||
$selectionViews = $view['roomSelections'];
|
||||
|
||||
foreach ($this->poolResolver->findSharedPools($bookingDto->travel) as $pool) {
|
||||
$remaining = max(0, $pool->getAvailable() - $pool->getSelectedQuantity($bookingDto->roomSelections));
|
||||
|
||||
foreach (array_keys($pool->rooms) as $roomId) {
|
||||
if (!isset($selectionViews[$roomId]) || !isset($selectionViews[$roomId]['quantity'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$quantityView = $selectionViews[$roomId]['quantity'];
|
||||
$quantity = $bookingDto->roomSelections[$roomId]->quantity ?? 0;
|
||||
$quantityView->vars['max_value'] = min($quantityView->vars['max_value'], $quantity + $remaining);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function configureOptions(OptionsResolver $resolver): void
|
||||
{
|
||||
$resolver->setDefaults([
|
||||
|
||||
@@ -222,7 +222,6 @@ class BookingParticipantType extends AbstractType
|
||||
$form->add('mobile', TextType::class, $this->mergeFieldState([
|
||||
'label' => 'Telefon (mobil)',
|
||||
'required' => false,
|
||||
'sanitize_html' => true,
|
||||
'property_path' => 'participant.mobile',
|
||||
'attr' => [
|
||||
'autocomplete' => 'leave-me-alone-chrome',
|
||||
|
||||
@@ -4,6 +4,8 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Form\Model;
|
||||
|
||||
use App\Model\RoomContingentPool;
|
||||
|
||||
/**
|
||||
* Bundles the data needed to render the booking create flow.
|
||||
*/
|
||||
@@ -12,6 +14,7 @@ class BookingCreateContext
|
||||
/**
|
||||
* @param array<int, ParticipantCardDataDto>|null $cardsData
|
||||
* @param array<int, float>|null $participantPrices
|
||||
* @param array<int, RoomContingentPool> $roomContingentPools shared pools by member room id, step 1 only
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly BookingDto $bookingDto,
|
||||
@@ -21,6 +24,7 @@ class BookingCreateContext
|
||||
public readonly bool $isSubmitted = false,
|
||||
public readonly ?array $participantPrices = null,
|
||||
public readonly bool $familyInsuranceUpgradeAvailable = false,
|
||||
public readonly array $roomContingentPools = [],
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -60,8 +60,8 @@ class BookingDto
|
||||
|
||||
/**
|
||||
* Booking status the travel itself calls for when the booking starts, before any room is
|
||||
* selected and before the create-flow status rules run. Step 1 falls back to it whenever
|
||||
* no on-request room is selected, so the status can move back from 'A'.
|
||||
* selected and before the create-flow status rules run. Step 1 falls back to it, so an 'A'
|
||||
* from the Step 3 BusPro fallback is cleared when the rooms change.
|
||||
*
|
||||
* Null in sessions started before it was introduced.
|
||||
*/
|
||||
|
||||
@@ -93,8 +93,17 @@ class ParticipantDto
|
||||
)]
|
||||
public ?string $email = null;
|
||||
|
||||
#[Assert\When(
|
||||
expression: 'this.isMobileNewlyEntered()',
|
||||
constraints: [new AppAssert\PhoneNumber()],
|
||||
groups: ['booking_edit', 'booking_create'],
|
||||
)]
|
||||
public ?string $mobile = null;
|
||||
|
||||
// The number as loaded from BusPro, which goes back unchanged and is exempt from PhoneNumber.
|
||||
// Public so it survives the session round trip through __unserialize().
|
||||
public ?string $loadedMobile = null;
|
||||
|
||||
#[Assert\Valid(groups: ['booking_edit', 'booking_create'])]
|
||||
#[Assert\NotNull(message: 'Bitte Adresse angeben', groups: ['applicant_address'])]
|
||||
public ?Address $address = null;
|
||||
@@ -240,6 +249,7 @@ class ParticipantDto
|
||||
$instance->nationality = $personalData->nationality ?: 'D';
|
||||
$instance->email = $personalData->communication->email;
|
||||
$instance->mobile = $personalData->communication->mobile;
|
||||
$instance->loadedMobile = $personalData->communication->mobile;
|
||||
$instance->dateOfBirth = $personalData->dateOfBirth;
|
||||
$instance->height = $personalData->height;
|
||||
$instance->weight = $personalData->weight;
|
||||
@@ -254,6 +264,11 @@ class ParticipantDto
|
||||
return $instance;
|
||||
}
|
||||
|
||||
public function isMobileNewlyEntered(): bool
|
||||
{
|
||||
return AppAssert\PhoneNumber::isNewlyEntered($this->mobile, $this->loadedMobile);
|
||||
}
|
||||
|
||||
public function isApplicant(): bool
|
||||
{
|
||||
return 0 === $this->index;
|
||||
|
||||
@@ -4,10 +4,23 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Form\Model;
|
||||
|
||||
use App\Enum\BusLeg;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
|
||||
class TravelMailingLookupDto
|
||||
{
|
||||
/**
|
||||
* The leg "bus passengers only" stands for: whoever takes the bus out, whatever their return.
|
||||
*/
|
||||
public const BusLeg BUS_LEG = BusLeg::Outbound;
|
||||
|
||||
#[Assert\NotBlank(message: 'Bitte einen Reisecode angeben.')]
|
||||
public ?string $travelCode = null;
|
||||
|
||||
public bool $busOnly = false;
|
||||
|
||||
public function getBusLeg(): ?BusLeg
|
||||
{
|
||||
return $this->busOnly ? self::BUS_LEG : null;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use App\BusProNet\Model\Address;
|
||||
use App\BusProNet\Model\PersonalData;
|
||||
use App\BusProNet\Model\VoucherPaymentMethod;
|
||||
use App\BusProNet\Model\VoucherTemplate;
|
||||
use App\Validator\Constraints as AppAssert;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
|
||||
/**
|
||||
@@ -69,10 +70,24 @@ class VoucherPurchaseDto
|
||||
#[Assert\Valid]
|
||||
public Address $address;
|
||||
|
||||
#[Assert\When(
|
||||
expression: 'this.isPhoneNewlyEntered()',
|
||||
constraints: [new AppAssert\PhoneNumber()],
|
||||
groups: ['voucher_step_2'],
|
||||
)]
|
||||
public ?string $phone = null;
|
||||
|
||||
#[Assert\When(
|
||||
expression: 'this.isMobileNewlyEntered()',
|
||||
constraints: [new AppAssert\PhoneNumber()],
|
||||
groups: ['voucher_step_2'],
|
||||
)]
|
||||
public ?string $mobile = null;
|
||||
|
||||
// The numbers prefilled from BusPro, which are exempt from PhoneNumber.
|
||||
public ?string $loadedPhone = null;
|
||||
public ?string $loadedMobile = null;
|
||||
|
||||
#[Assert\NotBlank(message: 'Bitte angeben', groups: ['voucher_step_2'])]
|
||||
#[Assert\Email(message: 'Bitte eine gültige Adresse angeben', mode: 'strict', groups: ['voucher_step_2'])]
|
||||
public ?string $email = null;
|
||||
@@ -90,6 +105,16 @@ class VoucherPurchaseDto
|
||||
$this->address->country = 'D';
|
||||
}
|
||||
|
||||
public function isPhoneNewlyEntered(): bool
|
||||
{
|
||||
return AppAssert\PhoneNumber::isNewlyEntered($this->phone, $this->loadedPhone);
|
||||
}
|
||||
|
||||
public function isMobileNewlyEntered(): bool
|
||||
{
|
||||
return AppAssert\PhoneNumber::isNewlyEntered($this->mobile, $this->loadedMobile);
|
||||
}
|
||||
|
||||
public function getBuyerFullName(): string
|
||||
{
|
||||
return trim(sprintf('%s %s', $this->firstName ?? '', $this->lastName ?? ''));
|
||||
@@ -119,6 +144,8 @@ class VoucherPurchaseDto
|
||||
$this->address->country ??= 'D';
|
||||
$this->phone = $personalData->communication->phone;
|
||||
$this->mobile = $personalData->communication->mobile;
|
||||
$this->loadedPhone = $this->phone;
|
||||
$this->loadedMobile = $this->mobile;
|
||||
$this->email = $loginEmail;
|
||||
}
|
||||
}
|
||||
@@ -81,12 +81,10 @@ class PersonalDataType extends AbstractType
|
||||
'label' => 'Telefon',
|
||||
'required' => false,
|
||||
'property_path' => 'communication.phone',
|
||||
'sanitize_html' => true,
|
||||
])
|
||||
->add('mobile', TextType::class, [
|
||||
'label' => 'Mobil',
|
||||
'property_path' => 'communication.mobile',
|
||||
'sanitize_html' => true,
|
||||
])
|
||||
;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
namespace App\Form;
|
||||
|
||||
use App\BusProNet\Constants;
|
||||
use App\Form\Model\RoomSelectionDto;
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
|
||||
@@ -45,7 +44,6 @@ class RoomSelectType extends AbstractType
|
||||
|
||||
$view->vars['label_room'] = $data->label;
|
||||
$view->vars['label_price_amount'] = null;
|
||||
$view->vars['is_inquiry'] = Constants::STATUS_ON_REQUEST === $data->status;
|
||||
|
||||
if (null !== $data->price) {
|
||||
$view->vars['label_price_amount'] = (float) $data->price;
|
||||
|
||||
@@ -48,6 +48,17 @@ class ParticipantAssignedRoomFieldHandler extends AbstractParticipantFieldHandle
|
||||
return 'assignedRoomId';
|
||||
}
|
||||
|
||||
/**
|
||||
* Skips edit mode, where room assignments cannot be changed.
|
||||
*
|
||||
* The field is static text there, so a submitted value can only come from a replayed or
|
||||
* hand-crafted POST. The edit request sends the booking's own assignments anyway.
|
||||
*/
|
||||
public function shouldProcess(array $submittedData, string $mode, int $participantIndex): bool
|
||||
{
|
||||
return BookingDto::MODE_EDIT !== $mode && parent::shouldProcess($submittedData, $mode, $participantIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes the assignedRoomId field for a specific participant.
|
||||
*
|
||||
@@ -65,7 +76,7 @@ class ParticipantAssignedRoomFieldHandler extends AbstractParticipantFieldHandle
|
||||
* 6. Updates the participant's assignedRoomId property
|
||||
*
|
||||
* @param array<string, mixed> $submittedData The submitted participant form data
|
||||
* @param BookingDto $bookingDto The booking DTO to update (create or edit)
|
||||
* @param BookingDto $bookingDto The booking DTO to update
|
||||
* @param int $participantIndex The index of the participant being processed
|
||||
*/
|
||||
public function processField(array $submittedData, BookingDto $bookingDto, int $participantIndex): void
|
||||
@@ -122,15 +133,8 @@ class ParticipantAssignedRoomFieldHandler extends AbstractParticipantFieldHandle
|
||||
return false;
|
||||
}
|
||||
|
||||
// Calculate total capacity for this room type
|
||||
// In edit mode, use maxQuantity which includes available rooms beyond the booked count.
|
||||
// In create mode, use quantity which is the user's room selection from step 1.
|
||||
if (BookingDto::MODE_EDIT === $bookingDto->getMode()) {
|
||||
$effectiveQuantity = $roomSelection->maxQuantity;
|
||||
} else {
|
||||
$effectiveQuantity = $roomSelection->quantity ?? 0;
|
||||
}
|
||||
$totalCapacity = $effectiveQuantity * $roomSelection->capacity;
|
||||
// Calculate total capacity for this room type from the step 1 selection
|
||||
$totalCapacity = ($roomSelection->quantity ?? 0) * $roomSelection->capacity;
|
||||
|
||||
// Count current occupancy (excluding current participant)
|
||||
$occupancy = 0;
|
||||
@@ -182,12 +186,7 @@ class ParticipantAssignedRoomFieldHandler extends AbstractParticipantFieldHandle
|
||||
return; // Shouldn't happen
|
||||
}
|
||||
|
||||
if (BookingDto::MODE_EDIT === $bookingDto->getMode()) {
|
||||
$effectiveQuantity = $roomSelection->maxQuantity;
|
||||
} else {
|
||||
$effectiveQuantity = $roomSelection->quantity ?? 0;
|
||||
}
|
||||
$totalCapacity = $effectiveQuantity * $roomSelection->capacity;
|
||||
$totalCapacity = ($roomSelection->quantity ?? 0) * $roomSelection->capacity;
|
||||
$currentOccupancy = count($participantsWithRoom);
|
||||
$spacesNeeded = ($currentOccupancy + 1) - $totalCapacity;
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ use App\BusProNet\Constants;
|
||||
use App\BusProNet\Model\Booking;
|
||||
use App\BusProNet\Model\Insurance;
|
||||
use App\BusProNet\Model\Pickup;
|
||||
use App\BusProNet\Model\Room;
|
||||
use App\BusProNet\Model\Service;
|
||||
use App\BusProNet\Utility\DirectionMapper;
|
||||
use App\Form\Model\BookingDto;
|
||||
@@ -86,21 +85,18 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
|
||||
*/
|
||||
protected function registerFieldOptionProviders(): void
|
||||
{
|
||||
// Room assignment field provider (available for both create and edit workflows)
|
||||
// Room assignment field provider (create only: edit mode renders the room as static text)
|
||||
// Returns empty array when no room choices available
|
||||
$this->fieldOptionProviders['assignedRoomId'] = function (BookingDto $bookingDto, int $participantIndex, array $options = []): array {
|
||||
$choices = [];
|
||||
|
||||
if (BookingDto::MODE_CREATE === $bookingDto->getMode()) {
|
||||
// Create context: use selected rooms from step 1, filtered by participant age
|
||||
// Use selected rooms from step 1, filtered by participant age
|
||||
$choices = $this->filterRoomsByParticipantAge(
|
||||
$bookingDto->getSelectedRooms(),
|
||||
$bookingDto,
|
||||
$participantIndex
|
||||
);
|
||||
} elseif (BookingDto::MODE_EDIT === $bookingDto->getMode()) {
|
||||
// Edit context: convert booked rooms to RoomSelectionDto for consistent handling
|
||||
$choices = $this->convertBookedRoomsToSelectionDtos($bookingDto->booking->rooms);
|
||||
}
|
||||
|
||||
if (true === empty($choices)) {
|
||||
@@ -782,31 +778,6 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts booked Room objects to RoomSelectionDto for consistent form handling.
|
||||
*
|
||||
* In edit mode, we need to convert Room entities to RoomSelectionDto objects
|
||||
* so the form can use the same choice_value and choice_label configuration
|
||||
* as create mode, enabling consistent price display in the template.
|
||||
*
|
||||
* @param Room[] $bookedRooms Rooms from existing booking
|
||||
*
|
||||
* @return RoomSelectionDto[] Array of room selection DTOs
|
||||
*/
|
||||
private function convertBookedRoomsToSelectionDtos(array $bookedRooms): array
|
||||
{
|
||||
$selections = [];
|
||||
foreach ($bookedRooms as $room) {
|
||||
$selection = new RoomSelectionDto();
|
||||
$selection->id = $room->id;
|
||||
$selection->label = $room->label;
|
||||
$selection->price = $room->price;
|
||||
$selections[] = $selection;
|
||||
}
|
||||
|
||||
return $selections;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters rental services by selected skipass duration.
|
||||
*
|
||||
|
||||
@@ -55,12 +55,10 @@ class VoucherPurchaseStep2Type extends AbstractType
|
||||
->add('phone', TextType::class, [
|
||||
'label' => 'Telefon privat',
|
||||
'required' => false,
|
||||
'sanitize_html' => true,
|
||||
])
|
||||
->add('mobile', TextType::class, [
|
||||
'label' => 'Mobil',
|
||||
'required' => false,
|
||||
'sanitize_html' => true,
|
||||
])
|
||||
;
|
||||
}
|
||||
|
||||
+147
-1
@@ -12,6 +12,7 @@ class ApiClient
|
||||
{
|
||||
private const string DEFAULT_BASE_URL = 'https://api.mailjet.com/v3/REST';
|
||||
private const int NAME_MAX_LENGTH = 255;
|
||||
private const int PAGE_LIMIT = 1000;
|
||||
|
||||
/**
|
||||
* @param array{firstName?: string, lastName?: string} $contactMetadataFields
|
||||
@@ -141,6 +142,139 @@ class ApiClient
|
||||
]);
|
||||
}
|
||||
|
||||
public function createContactsList(string $name): int
|
||||
{
|
||||
$this->assertConfigured();
|
||||
|
||||
$response = $this->request('POST', 'contactslist', [
|
||||
'json' => [
|
||||
'Name' => $name,
|
||||
],
|
||||
]);
|
||||
|
||||
$listId = $response['Data'][0]['ID'] ?? null;
|
||||
if (null === $listId) {
|
||||
throw new NewsletterProviderException(sprintf('Mailjet did not return an id for the new contact list %s', $name));
|
||||
}
|
||||
|
||||
return (int) $listId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the contacts as subscribed, including any who unsubscribed from this list before.
|
||||
* Mailjet processes the request as an asynchronous job.
|
||||
*
|
||||
* @param list<array{email: string, firstName: ?string}> $contacts
|
||||
*
|
||||
* @return int|null the job id
|
||||
*/
|
||||
public function addContactsToList(int $listId, array $contacts): ?int
|
||||
{
|
||||
$this->assertConfigured();
|
||||
|
||||
$payload = [];
|
||||
foreach ($contacts as $contact) {
|
||||
$entry = ['Email' => $this->normalizeEmail($contact['email'])];
|
||||
|
||||
$firstName = $this->normalizeName($contact['firstName']);
|
||||
if (null !== $firstName && true === isset($this->contactMetadataFields['firstName'])) {
|
||||
$entry['Properties'] = [$this->contactMetadataFields['firstName'] => $firstName];
|
||||
}
|
||||
|
||||
$payload[] = $entry;
|
||||
}
|
||||
|
||||
$response = $this->request('POST', sprintf('contactslist/%d/managemanycontacts', $listId), [
|
||||
'json' => [
|
||||
'Action' => 'addforce',
|
||||
'Contacts' => $payload,
|
||||
],
|
||||
]);
|
||||
|
||||
$jobId = $response['Data'][0]['JobID'] ?? null;
|
||||
|
||||
return null !== $jobId ? (int) $jobId : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<int>
|
||||
*/
|
||||
public function getListContactIds(int $listId): array
|
||||
{
|
||||
$this->assertConfigured();
|
||||
|
||||
$contactIds = [];
|
||||
$offset = 0;
|
||||
do {
|
||||
$response = $this->request('GET', 'listrecipient', [
|
||||
'query' => [
|
||||
'ContactsList' => $listId,
|
||||
'Limit' => self::PAGE_LIMIT,
|
||||
'Offset' => $offset,
|
||||
],
|
||||
]);
|
||||
|
||||
$entries = true === is_array($response['Data'] ?? null) ? $response['Data'] : [];
|
||||
foreach ($entries as $entry) {
|
||||
if (true === is_array($entry) && true === isset($entry['ContactID'])) {
|
||||
$contactIds[] = (int) $entry['ContactID'];
|
||||
}
|
||||
}
|
||||
|
||||
$offset += self::PAGE_LIMIT;
|
||||
} while (self::PAGE_LIMIT === count($entries));
|
||||
|
||||
return array_values(array_unique($contactIds));
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the contact is on, subscribed or not. Mailjet includes lists deleted within the last 60 days.
|
||||
*
|
||||
* @return list<int>
|
||||
*/
|
||||
public function getContactListIds(int $contactId): array
|
||||
{
|
||||
$this->assertConfigured();
|
||||
|
||||
$response = $this->request('GET', sprintf('contact/%d/getcontactslists', $contactId), [
|
||||
'allow_404' => true,
|
||||
]);
|
||||
|
||||
$listIds = [];
|
||||
foreach ($response['Data'] ?? [] as $entry) {
|
||||
if (true === is_array($entry) && true === isset($entry['ListID'])) {
|
||||
$listIds[] = (int) $entry['ListID'];
|
||||
}
|
||||
}
|
||||
|
||||
return $listIds;
|
||||
}
|
||||
|
||||
public function deleteContactsList(int $listId): void
|
||||
{
|
||||
$this->assertConfigured();
|
||||
|
||||
$this->request('DELETE', sprintf('contactslist/%d', $listId), [
|
||||
'allow_404' => true,
|
||||
'allow_empty' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* GDPR deletion: Mailjet anonymises the contact immediately and purges it after 30 days.
|
||||
* This cannot be undone.
|
||||
*/
|
||||
public function deleteContact(int $contactId): void
|
||||
{
|
||||
$this->assertConfigured();
|
||||
|
||||
$this->request('DELETE', sprintf('contacts/%d', $contactId), [
|
||||
'allow_404' => true,
|
||||
'allow_empty' => true,
|
||||
'api_version' => 'v4',
|
||||
]);
|
||||
}
|
||||
|
||||
private function findOrCreateContactId(string $email): int
|
||||
{
|
||||
$contactId = $this->resolveContactId($email);
|
||||
@@ -246,15 +380,17 @@ class ApiClient
|
||||
{
|
||||
$allow404 = true === ($options['allow_404'] ?? false);
|
||||
$allowEmpty = true === ($options['allow_empty'] ?? false);
|
||||
$baseUrl = 'v4' === ($options['api_version'] ?? null) ? $this->getV4BaseUrl() : $this->getBaseUrl();
|
||||
unset($options['allow_404']);
|
||||
unset($options['allow_empty']);
|
||||
unset($options['api_version']);
|
||||
|
||||
$resourcePath = trim($resource, '/');
|
||||
|
||||
try {
|
||||
$response = $this->httpClient->request(
|
||||
$method,
|
||||
sprintf('%s/%s', $this->getBaseUrl(), $resourcePath),
|
||||
sprintf('%s/%s', $baseUrl, $resourcePath),
|
||||
array_merge($options, [
|
||||
'auth_basic' => sprintf('%s:%s', $this->apiKey, $this->apiSecret),
|
||||
])
|
||||
@@ -310,6 +446,16 @@ class ApiClient
|
||||
return rtrim($baseUrl, '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* The configured base URL points at v3 (`…/v3/REST`); the v4 API sits beside it on the same host.
|
||||
*/
|
||||
private function getV4BaseUrl(): string
|
||||
{
|
||||
$baseUrl = preg_replace('~/v3/REST$~i', '', $this->getBaseUrl());
|
||||
|
||||
return sprintf('%s/v4', $baseUrl);
|
||||
}
|
||||
|
||||
private function assertConfigured(): void
|
||||
{
|
||||
if (true === empty($this->apiKey) || true === empty($this->apiSecret)) {
|
||||
|
||||
@@ -103,32 +103,32 @@ class AdminMenuBuilder
|
||||
],
|
||||
]);
|
||||
|
||||
$this->addLogoutItem($menu);
|
||||
$this->addAccountGroup($menu);
|
||||
|
||||
return $menu;
|
||||
}
|
||||
|
||||
private function addLogoutItem(ItemInterface $menu): void
|
||||
/**
|
||||
* The account actions close the menu as one group without a route, so it opens in place in the
|
||||
* sidebar and the drawer alike; sub-items carry no icons.
|
||||
*/
|
||||
private function addAccountGroup(ItemInterface $menu): void
|
||||
{
|
||||
$this->addDivider($menu);
|
||||
|
||||
$menu->addChild('MyE&P', [
|
||||
$account = $menu->addChild('Mein Account', [
|
||||
'extras' => [
|
||||
'icon' => 'user',
|
||||
],
|
||||
]);
|
||||
$account->addChild('MyE&P', [
|
||||
'route' => 'app_account',
|
||||
'linkAttributes' => [
|
||||
'title' => 'zu MyE&P',
|
||||
],
|
||||
'extras' => [
|
||||
'icon' => 'logout',
|
||||
],
|
||||
]);
|
||||
$menu->addChild('Logout', [
|
||||
$account->addChild('Abmelden', [
|
||||
'route' => 'app_logout',
|
||||
'linkAttributes' => [
|
||||
'title' => 'Logout',
|
||||
],
|
||||
'extras' => [
|
||||
'icon' => 'logout',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,16 +4,21 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Model\Chatbot;
|
||||
|
||||
use App\BusProNet\Constants;
|
||||
use App\BusProNet\Model\Room;
|
||||
use App\Enum\RoomType;
|
||||
|
||||
/**
|
||||
* What the website's travel search knows about one travel date at one hotel, derived from
|
||||
* a product export row the way TYPO3's DateImportService derives it, with two deliberate
|
||||
* differences: rooms in `Buchungsstop` are not bookable, and neither is the baby row.
|
||||
* differences: rooms in `Buchungsstop` are not listed, and neither is the baby row. A listed
|
||||
* room is bookable when Room::isBookableState() says so, as the booking flow offers it;
|
||||
* the others are sold out, as the website shows them. A bookable room on request is reported
|
||||
* as such, because booking it only produces an inquiry.
|
||||
*
|
||||
* - places: Σ available × maxPax over the bookable rooms (`available` counts rooms);
|
||||
* - priceFrom ("ab" price): cheapest bookable room with places left, else cheapest bookable room;
|
||||
* - minPax: the smallest group a bookable room takes;
|
||||
* - priceFrom ("ab" price): cheapest bookable room, else cheapest listed room;
|
||||
* - minPax: the smallest group a listed room takes;
|
||||
* - inclusions from the selection groups (7 Skipass, 71 Verpflegung, 86 Programm, 87 Kurse,
|
||||
* 89 Events) and the outbound bus service (a price of 0 means included).
|
||||
*/
|
||||
@@ -21,9 +26,12 @@ final readonly class TravelDateFacts
|
||||
{
|
||||
public const AVAILABILITY_FREE = 'frei';
|
||||
public const AVAILABILITY_ON_REQUEST = 'auf Anfrage';
|
||||
public const AVAILABILITY_SOLD_OUT = 'ausgebucht';
|
||||
|
||||
/** Best first: a date is as available as its best room. */
|
||||
private const AVAILABILITY_RANK = [self::AVAILABILITY_FREE, self::AVAILABILITY_ON_REQUEST, self::AVAILABILITY_SOLD_OUT];
|
||||
|
||||
public const STATUS_BOOKING_STOP = 'Buchungsstop';
|
||||
private const STATUS_FREE = 'Frei';
|
||||
|
||||
private const GROUP_SKIPASS = 7;
|
||||
private const GROUP_BOARD = 71;
|
||||
@@ -32,7 +40,7 @@ final readonly class TravelDateFacts
|
||||
private const GROUP_EVENTS = 89;
|
||||
|
||||
/**
|
||||
* @param list<RoomType> $roomTypes distinct, of the bookable rooms
|
||||
* @param list<RoomType> $roomTypes distinct, of the listed rooms
|
||||
* @param list<string> $boards included board labels
|
||||
*/
|
||||
private function __construct(
|
||||
@@ -71,12 +79,13 @@ final readonly class TravelDateFacts
|
||||
continue;
|
||||
}
|
||||
|
||||
$available = (int) ($room['available'] ?? 0);
|
||||
$places += $available * (int) ($room['maxPax'] ?? 0);
|
||||
$roomAvailability = self::roomAvailability($room);
|
||||
$bookable = self::AVAILABILITY_SOLD_OUT !== $roomAvailability;
|
||||
if ($bookable) {
|
||||
$places += (int) $room['available'] * (int) ($room['maxPax'] ?? 0);
|
||||
}
|
||||
$roomTypes[$type->value] = $type;
|
||||
$availability = self::STATUS_FREE === ($room['status'] ?? null) || self::AVAILABILITY_FREE === $availability
|
||||
? self::AVAILABILITY_FREE
|
||||
: self::AVAILABILITY_ON_REQUEST;
|
||||
$availability = null === $availability ? $roomAvailability : self::better($availability, $roomAvailability);
|
||||
|
||||
if (is_int($room['minPax'] ?? null) && (null === $minPax || $room['minPax'] < $minPax)) {
|
||||
$minPax = $room['minPax'];
|
||||
@@ -86,7 +95,7 @@ final readonly class TravelDateFacts
|
||||
$price = (float) $room['price'];
|
||||
$priceFrom = null === $priceFrom ? $price : min($priceFrom, $price);
|
||||
|
||||
if ($available > 0) {
|
||||
if ($bookable) {
|
||||
$priceFromWithPlaces = null === $priceFromWithPlaces ? $price : min($priceFromWithPlaces, $price);
|
||||
}
|
||||
}
|
||||
@@ -131,11 +140,38 @@ final readonly class TravelDateFacts
|
||||
);
|
||||
}
|
||||
|
||||
public function isBookable(): bool
|
||||
/**
|
||||
* Whether the website search lists the date at all, sold out or not.
|
||||
*/
|
||||
public function isListed(): bool
|
||||
{
|
||||
return null !== $this->availability;
|
||||
}
|
||||
|
||||
/**
|
||||
* One of the AVAILABILITY_* constants.
|
||||
*
|
||||
* @param array<string, mixed> $room a room of a ProductExportBuilder row
|
||||
*/
|
||||
public static function roomAvailability(array $room): string
|
||||
{
|
||||
if (!Room::isBookableState($room['status'] ?? null, $room['available'] ?? null, $room['code'] ?? null)) {
|
||||
return self::AVAILABILITY_SOLD_OUT;
|
||||
}
|
||||
|
||||
return Constants::STATUS_ON_REQUEST === ($room['status'] ?? null)
|
||||
? self::AVAILABILITY_ON_REQUEST
|
||||
: self::AVAILABILITY_FREE;
|
||||
}
|
||||
|
||||
/**
|
||||
* The better of two AVAILABILITY_* values.
|
||||
*/
|
||||
private static function better(string $a, string $b): string
|
||||
{
|
||||
return array_search($a, self::AVAILABILITY_RANK, true) <= array_search($b, self::AVAILABILITY_RANK, true) ? $a : $b;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the price includes, as the website lists it on a result.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Model;
|
||||
|
||||
/**
|
||||
* One entry of TYPO3's `/api/calendar-hotels`: the calendar hotel of a visible product.
|
||||
*
|
||||
* TYPO3 also lists the products per hotel; only the code and the name are kept here.
|
||||
*/
|
||||
final readonly class CmsCalendarHotel
|
||||
{
|
||||
public function __construct(
|
||||
public string $code,
|
||||
public string $name,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ final readonly class ContingentCalendarQuery
|
||||
$hasFrom = null !== $from && '' !== $from;
|
||||
$hasTo = null !== $to && '' !== $to;
|
||||
|
||||
// Neither supplied: the caller wants the full priced span, which the persisted prices define.
|
||||
// Neither supplied: the caller wants the full span, which each endpoint defines for itself.
|
||||
if (!$hasFrom && !$hasTo) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Model;
|
||||
|
||||
use App\Entity\Groups\Accommodation;
|
||||
use App\Entity\Groups\CalendarHotel;
|
||||
use App\Enum\ContingentHotelSource;
|
||||
|
||||
/**
|
||||
* A hotel code the contingent snapshot is kept for, with whatever it is known as locally.
|
||||
*/
|
||||
final readonly class ContingentHotel
|
||||
{
|
||||
public function __construct(
|
||||
public string $code,
|
||||
public ?Accommodation $accommodation,
|
||||
public ?CalendarHotel $calendarHotel,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<ContingentHotelSource>
|
||||
*/
|
||||
public function sources(): array
|
||||
{
|
||||
$sources = [];
|
||||
|
||||
if (null !== $this->accommodation) {
|
||||
$sources[] = ContingentHotelSource::Accommodation;
|
||||
}
|
||||
|
||||
if (null !== $this->calendarHotel) {
|
||||
$sources[] = ContingentHotelSource::Typo3;
|
||||
}
|
||||
|
||||
return $sources;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Model;
|
||||
|
||||
use App\BusProNet\Model\Room;
|
||||
use App\Form\Model\RoomSelectionDto;
|
||||
|
||||
/**
|
||||
* Offered rooms of one travel that draw on the same BusPro contingent.
|
||||
*
|
||||
* BusPro reports the pool's remaining count on every member, and checks each room of a booking
|
||||
* against it separately, so a booking with two members can take more than is left. Only pools
|
||||
* with more than one offered member exist as objects; every other room is its own pool and is
|
||||
* already capped by its own count.
|
||||
*/
|
||||
final readonly class RoomContingentPool
|
||||
{
|
||||
/**
|
||||
* @param array<int, Room> $rooms the offered members, indexed by room id
|
||||
*/
|
||||
public function __construct(
|
||||
public array $rooms,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Rooms left in the pool. The members should all report the same figure; the lowest is the
|
||||
* safe reading if they ever disagree.
|
||||
*/
|
||||
public function getAvailable(): int
|
||||
{
|
||||
return min(array_map(static fn (Room $room): int => $room->available ?? 0, $this->rooms));
|
||||
}
|
||||
|
||||
/**
|
||||
* Rooms the given selections take from the pool.
|
||||
*
|
||||
* @param iterable<RoomSelectionDto> $roomSelections
|
||||
*/
|
||||
public function getSelectedQuantity(iterable $roomSelections): int
|
||||
{
|
||||
$quantity = 0;
|
||||
foreach ($roomSelections as $roomSelection) {
|
||||
if (null !== $roomSelection->id && $this->contains($roomSelection->id)) {
|
||||
$quantity += $roomSelection->quantity ?? 0;
|
||||
}
|
||||
}
|
||||
|
||||
return $quantity;
|
||||
}
|
||||
|
||||
public function contains(int $roomId): bool
|
||||
{
|
||||
return isset($this->rooms[$roomId]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public function getLabels(): array
|
||||
{
|
||||
return array_values(array_map(static fn (Room $room): string => (string) $room->label, $this->rooms));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Repository\Groups;
|
||||
|
||||
use App\Entity\Groups\CalendarHotel;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/**
|
||||
* @extends ServiceEntityRepository<CalendarHotel>
|
||||
*/
|
||||
class CalendarHotelRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, CalendarHotel::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, CalendarHotel>
|
||||
*/
|
||||
public function findAllIndexedByCode(): array
|
||||
{
|
||||
$indexed = [];
|
||||
|
||||
foreach ($this->findAll() as $hotel) {
|
||||
$indexed[(string) $hotel->getCode()] = $hotel;
|
||||
}
|
||||
|
||||
return $indexed;
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Repository\Groups;
|
||||
|
||||
use App\Entity\Groups\Accommodation;
|
||||
use App\Entity\Groups\ContingentDay;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
@@ -20,53 +19,30 @@ class ContingentDayRepository extends ServiceEntityRepository
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the snapshot days within [dateFrom, dateTo] for the accommodation
|
||||
* identified by the given hotel code, keyed by Y-m-d.
|
||||
* Returns the snapshot days of a hotel code within [dateFrom, dateTo], keyed by Y-m-d.
|
||||
* A null dateTo means everything from dateFrom to the end of the snapshot.
|
||||
*
|
||||
* @return array<string, ContingentDay>
|
||||
*/
|
||||
public function findByHotelCodeAndDateRange(
|
||||
string $hotelCode,
|
||||
\DateTimeImmutable $dateFrom,
|
||||
\DateTimeImmutable $dateTo,
|
||||
?\DateTimeImmutable $dateTo,
|
||||
): array {
|
||||
/** @var ContingentDay[] $days */
|
||||
$days = $this->createQueryBuilder('cd')
|
||||
->join('cd.accommodation', 'a')
|
||||
->where('a.calendarCode = :hotelCode')
|
||||
$qb = $this->createQueryBuilder('cd')
|
||||
->where('cd.hotelCode = :hotelCode')
|
||||
->andWhere('cd.date >= :dateFrom')
|
||||
->andWhere('cd.date <= :dateTo')
|
||||
->setParameter('hotelCode', $hotelCode)
|
||||
->setParameter('dateFrom', $dateFrom)
|
||||
->setParameter('dateTo', $dateTo)
|
||||
->orderBy('cd.date', 'ASC')
|
||||
->getQuery()
|
||||
->getResult();
|
||||
->orderBy('cd.date', 'ASC');
|
||||
|
||||
return $this->indexByDate($days);
|
||||
}
|
||||
if (null !== $dateTo) {
|
||||
$qb->andWhere('cd.date <= :dateTo')
|
||||
->setParameter('dateTo', $dateTo);
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as above but for a known accommodation; used by the sync to diff against.
|
||||
*
|
||||
* @return array<string, ContingentDay>
|
||||
*/
|
||||
public function findByAccommodationAndDateRange(
|
||||
Accommodation $accommodation,
|
||||
\DateTimeImmutable $dateFrom,
|
||||
\DateTimeImmutable $dateTo,
|
||||
): array {
|
||||
/** @var ContingentDay[] $days */
|
||||
$days = $this->createQueryBuilder('cd')
|
||||
->where('cd.accommodation = :accommodation')
|
||||
->andWhere('cd.date >= :dateFrom')
|
||||
->andWhere('cd.date <= :dateTo')
|
||||
->setParameter('accommodation', $accommodation)
|
||||
->setParameter('dateFrom', $dateFrom)
|
||||
->setParameter('dateTo', $dateTo)
|
||||
->orderBy('cd.date', 'ASC')
|
||||
->getQuery()
|
||||
->getResult();
|
||||
$days = $qb->getQuery()->getResult();
|
||||
|
||||
return $this->indexByDate($days);
|
||||
}
|
||||
@@ -84,6 +60,21 @@ class ContingentDayRepository extends ServiceEntityRepository
|
||||
->execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the days of every hotel code that is no longer synced.
|
||||
*
|
||||
* @param non-empty-list<string> $hotelCodes the codes that are still synced
|
||||
*/
|
||||
public function deleteExceptHotelCodes(array $hotelCodes): int
|
||||
{
|
||||
return (int) $this->createQueryBuilder('cd')
|
||||
->delete()
|
||||
->where('cd.hotelCode NOT IN (:hotelCodes)')
|
||||
->setParameter('hotelCodes', $hotelCodes)
|
||||
->getQuery()
|
||||
->execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ContingentDay[] $days
|
||||
*
|
||||
|
||||
@@ -4,7 +4,6 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Repository\Groups;
|
||||
|
||||
use App\Entity\Groups\Accommodation;
|
||||
use App\Entity\Groups\ContingentSyncState;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
@@ -19,30 +18,37 @@ class ContingentSyncStateRepository extends ServiceEntityRepository
|
||||
parent::__construct($registry, ContingentSyncState::class);
|
||||
}
|
||||
|
||||
public function findOneByAccommodation(Accommodation $accommodation): ?ContingentSyncState
|
||||
public function findOneByHotelCode(string $hotelCode): ?ContingentSyncState
|
||||
{
|
||||
return $this->findOneBy(['accommodation' => $accommodation]);
|
||||
return $this->findOneBy(['hotelCode' => $hotelCode]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns every sync state keyed by accommodation id, for the revisions endpoint.
|
||||
*
|
||||
* @return array<int, ContingentSyncState>
|
||||
* @return array<string, ContingentSyncState>
|
||||
*/
|
||||
public function findAllIndexedByAccommodationId(): array
|
||||
public function findAllIndexedByHotelCode(): array
|
||||
{
|
||||
$indexed = [];
|
||||
|
||||
foreach ($this->findAll() as $state) {
|
||||
$accommodation = $state->getAccommodation();
|
||||
|
||||
if (null === $accommodation || null === $accommodation->getId()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$indexed[$accommodation->getId()] = $state;
|
||||
$indexed[(string) $state->getHotelCode()] = $state;
|
||||
}
|
||||
|
||||
return $indexed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the sync state of every hotel code that is no longer synced.
|
||||
*
|
||||
* @param non-empty-list<string> $hotelCodes the codes that are still synced
|
||||
*/
|
||||
public function deleteExceptHotelCodes(array $hotelCodes): int
|
||||
{
|
||||
return (int) $this->createQueryBuilder('s')
|
||||
->delete()
|
||||
->where('s.hotelCode NOT IN (:hotelCodes)')
|
||||
->setParameter('hotelCodes', $hotelCodes)
|
||||
->getQuery()
|
||||
->execute();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Repository;
|
||||
|
||||
use App\Entity\TravelMailingList;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/**
|
||||
* @extends ServiceEntityRepository<TravelMailingList>
|
||||
*/
|
||||
class TravelMailingListRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, TravelMailingList::class);
|
||||
}
|
||||
|
||||
public function findOneByName(string $name): ?TravelMailingList
|
||||
{
|
||||
return $this->findOneBy(['name' => $name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<TravelMailingList>
|
||||
*/
|
||||
public function findByTravelCode(string $travelCode): array
|
||||
{
|
||||
return $this->findBy(['travelCode' => $travelCode], ['id' => 'ASC']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<TravelMailingList>
|
||||
*/
|
||||
public function findDueForDeletion(\DateTimeImmutable $now): array
|
||||
{
|
||||
return $this->createQueryBuilder('l')
|
||||
->where('l.deleteAfter <= :now')
|
||||
->setParameter('now', $now)
|
||||
->orderBy('l.deleteAfter', 'ASC')
|
||||
->getQuery()
|
||||
->getResult();
|
||||
}
|
||||
}
|
||||
@@ -10,11 +10,13 @@ use App\BusProNet\Model\Service;
|
||||
use App\BusProNet\Model\Travel;
|
||||
use App\BusProNet\Service\BookingStatusRuleRegistry;
|
||||
use App\BusProNet\XmlLoader\AgencyLoader;
|
||||
use App\Exception\BookingBackendUnavailableException;
|
||||
use App\Exception\NoRoomsAvailableException;
|
||||
use App\Form\Model\BookingDto;
|
||||
use App\Form\Model\ParticipantDto;
|
||||
use App\Form\Model\RoomSelectionDto;
|
||||
use App\Form\Service\ServiceAgeEvaluator;
|
||||
use App\Model\RoomContingentPool;
|
||||
use App\Model\RoomSelectionAdjustment;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
@@ -28,6 +30,7 @@ class BookingConfigurator
|
||||
private readonly ParticipantEligibilityChecker $participantEligibilityService,
|
||||
private readonly BookingStatusRuleRegistry $bookingStatusRuleRegistry,
|
||||
private readonly AgencyLoader $agencyLoader,
|
||||
private readonly RoomContingentPoolResolver $poolResolver,
|
||||
#[Autowire(param: 'default_booking_status')]
|
||||
private readonly string $defaultBookingStatus,
|
||||
) {
|
||||
@@ -44,6 +47,11 @@ class BookingConfigurator
|
||||
* - 'Frei': Regular booking with availability checks
|
||||
* - 'Option': Create-flow override from specific rules
|
||||
* - 'Anfrage': Inquiry booking, allows booking even with 0 availability
|
||||
*
|
||||
* The availability call doubles as the health check for the whole flow: if BusPro cannot be
|
||||
* reached now, the inquiry in step 3 would fail after the customer typed in every participant.
|
||||
*
|
||||
* @throws BookingBackendUnavailableException When BusPro cannot be reached
|
||||
*/
|
||||
public function startFreshBooking(Request $request, int $dateId, int $hotelId, ?int $agencyId = null): BookingDto
|
||||
{
|
||||
@@ -54,7 +62,7 @@ class BookingConfigurator
|
||||
|
||||
// Fetch and patch availability data (includes allowedBookingStatus from API)
|
||||
// Force refresh ensures fresh data at booking start, then populates cache for subsequent loads
|
||||
$availabilities = $this->travelDataService->getAvailabilityData($dateId, cached: true, forceRefresh: true);
|
||||
$availabilities = $this->travelDataService->getAvailabilityData($dateId, cached: true, forceRefresh: true, requireReachable: true);
|
||||
if (null !== $availabilities) {
|
||||
$this->travelDataService->patchAvailabilities($travelData, $availabilities);
|
||||
}
|
||||
@@ -102,16 +110,19 @@ class BookingConfigurator
|
||||
* exists; one that only loses part of its contingent leaves a quantity nothing else re-checks
|
||||
* before the booking is submitted; and one that becomes bookable again has no selection at all.
|
||||
* Rebuilding the selections from the current rooms, with the chosen quantities carried over and
|
||||
* capped at what is left, keeps both sides in step.
|
||||
* capped at what is left, keeps both sides in step. Rooms sharing a contingent are capped
|
||||
* together as well, in selection order, since BusPro reports the shared remainder on each.
|
||||
*
|
||||
* @return list<RoomSelectionAdjustment> The selections that had to give up quantity, in selection order
|
||||
*/
|
||||
public function reconcileRoomSelections(BookingDto $bookingDto): array
|
||||
{
|
||||
$availableRooms = $bookingDto->travel->getAvailableRooms();
|
||||
$pools = $this->poolResolver->findSharedPools($bookingDto->travel);
|
||||
|
||||
$adjustments = [];
|
||||
$quantitiesByRoomId = [];
|
||||
$poolRemainders = [];
|
||||
|
||||
foreach ($bookingDto->roomSelections as $roomSelection) {
|
||||
if (null === $roomSelection->id) {
|
||||
@@ -121,6 +132,13 @@ class BookingConfigurator
|
||||
$requestedQuantity = $roomSelection->quantity ?? 0;
|
||||
$bookableQuantity = min($requestedQuantity, $availableRooms[$roomSelection->id]->available ?? 0);
|
||||
|
||||
$poolIndex = $this->findPoolIndex($pools, $roomSelection->id);
|
||||
if (null !== $poolIndex) {
|
||||
$poolRemainders[$poolIndex] ??= $pools[$poolIndex]->getAvailable();
|
||||
$bookableQuantity = min($bookableQuantity, $poolRemainders[$poolIndex]);
|
||||
$poolRemainders[$poolIndex] -= $bookableQuantity;
|
||||
}
|
||||
|
||||
$quantitiesByRoomId[$roomSelection->id] = $bookableQuantity;
|
||||
|
||||
if (0 < $requestedQuantity && $bookableQuantity < $requestedQuantity) {
|
||||
@@ -141,6 +159,20 @@ class BookingConfigurator
|
||||
return $adjustments;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<RoomContingentPool> $pools
|
||||
*/
|
||||
private function findPoolIndex(array $pools, int $roomId): ?int
|
||||
{
|
||||
foreach ($pools as $index => $pool) {
|
||||
if ($pool->contains($roomId)) {
|
||||
return $index;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a room selection DTO from room data and quantities.
|
||||
*
|
||||
@@ -611,10 +643,6 @@ class BookingConfigurator
|
||||
/**
|
||||
* Determines the initial booking status based on travel configuration and API restrictions.
|
||||
*
|
||||
* This method implements a multi-stage check to determine the appropriate booking status:
|
||||
* 1. Checks API restrictions via buchungstatusmoeglich attribute
|
||||
* 2. Checks if only inquiry rooms are available (no Frei rooms with available > 0)
|
||||
*
|
||||
* When API provides allowed status restrictions, the method respects them by selecting
|
||||
* the best available status in order of preference: configured default → 'F' → 'O' → 'A'.
|
||||
*
|
||||
@@ -627,13 +655,7 @@ class BookingConfigurator
|
||||
*/
|
||||
private function determineInitialBookingStatus(Travel $travelData): string
|
||||
{
|
||||
// Check 1: Only inquiry rooms available (all rooms with available > 0 have status 'Anfrage')
|
||||
// This takes precedence as it's a business rule independent of API restrictions
|
||||
if ($travelData->requiresInquiryBooking()) {
|
||||
return Constants::BOOKING_STATUS_INQUIRY;
|
||||
}
|
||||
|
||||
// Check 2: If API provided allowed status restrictions, respect them
|
||||
// If API provided allowed status restrictions, respect them
|
||||
if ([] !== $travelData->allowedBookingStatus) {
|
||||
// Prefer configured default status if allowed
|
||||
if ($travelData->isBookingStatusAllowed($this->defaultBookingStatus)) {
|
||||
@@ -658,19 +680,19 @@ class BookingConfigurator
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates booking status based on selected room requirements.
|
||||
* Updates the booking status after the room selection in Step 1.
|
||||
*
|
||||
* If ANY selected room is only bookable on request, the whole booking becomes an inquiry.
|
||||
* If any selected room is on request, which Step 1 offers only for rooms the office sells
|
||||
* that way on purpose (Room::isBookableState()), the whole booking becomes an inquiry.
|
||||
* Otherwise the status returns to what the travel called for when the booking started,
|
||||
* and the create-flow rules run again, so a customer who swaps an on-request room for a
|
||||
* free one in Step 1 is no longer submitted as an inquiry. An 'A' from the Step 3 BusPro
|
||||
* fallback is cleared the same way; Step 3 validates again and re-applies it if needed.
|
||||
* and the create-flow rules run again. An 'A' from the Step 3 BusPro fallback is cleared
|
||||
* this way; Step 3 validates again with the new rooms and re-applies it if needed.
|
||||
*
|
||||
* @param BookingDto $bookingDto The booking DTO to update
|
||||
*/
|
||||
public function updateBookingStatusFromRoomSelection(BookingDto $bookingDto): void
|
||||
{
|
||||
if (true === $this->hasOnRequestRoomSelected($bookingDto)) {
|
||||
if ($this->hasOnRequestRoomSelected($bookingDto)) {
|
||||
$bookingDto->bookingStatus = Constants::BOOKING_STATUS_INQUIRY;
|
||||
|
||||
return;
|
||||
@@ -689,9 +711,7 @@ class BookingConfigurator
|
||||
{
|
||||
foreach ($bookingDto->getSelectedRooms() as $roomSelection) {
|
||||
$room = $bookingDto->travel->getRoomById($roomSelection->id);
|
||||
if (null !== $room
|
||||
&& Constants::STATUS_ON_REQUEST === $room->status
|
||||
&& $room->available > 0) {
|
||||
if (null !== $room && Constants::STATUS_ON_REQUEST === $room->status) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ class BookingCreateContextFactory
|
||||
private readonly BookingSummaryAssembler $summaryDataService,
|
||||
private readonly BookingPriceCalculator $priceCalculator,
|
||||
private readonly FamilyInsuranceAvailabilityChecker $familyInsuranceService,
|
||||
private readonly RoomContingentPoolResolver $poolResolver,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -37,6 +38,29 @@ class BookingCreateContextFactory
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The step 1 context, which also tells which offered rooms share a contingent.
|
||||
*/
|
||||
public function createForRoomSelection(BookingDto $bookingDto): BookingCreateContext
|
||||
{
|
||||
$baseContext = $this->buildBaseContext($bookingDto, RoomPricingCalculator::PRICING_MODE_SELECTION);
|
||||
|
||||
$poolsByRoomId = [];
|
||||
foreach ($this->poolResolver->findSharedPools($bookingDto->travel) as $pool) {
|
||||
foreach (array_keys($pool->rooms) as $roomId) {
|
||||
$poolsByRoomId[$roomId] = $pool;
|
||||
}
|
||||
}
|
||||
|
||||
return new BookingCreateContext(
|
||||
bookingDto: $bookingDto,
|
||||
summaryData: $baseContext['summaryData'],
|
||||
groupedRooms: $baseContext['groupedRooms'],
|
||||
familyInsuranceUpgradeAvailable: $baseContext['familyInsuranceUpgradeAvailable'],
|
||||
roomContingentPools: $poolsByRoomId,
|
||||
);
|
||||
}
|
||||
|
||||
public function createWithParticipantCards(BookingDto $bookingDto, bool $isSubmitted): BookingCreateContext
|
||||
{
|
||||
$baseContext = $this->buildBaseContext($bookingDto, RoomPricingCalculator::PRICING_MODE_SELECTION);
|
||||
|
||||
@@ -63,7 +63,7 @@ class BookingEditDraftMerger
|
||||
|
||||
// Room assignment
|
||||
if (true === isset($data['roomAssignment']) && true === is_array($data['roomAssignment'])) {
|
||||
$this->applyRoomAssignment($participant, $data['roomAssignment'], $travel);
|
||||
$this->applyRoomAssignment($participant, $data['roomAssignment']);
|
||||
}
|
||||
|
||||
// License plate
|
||||
@@ -177,26 +177,19 @@ class BookingEditDraftMerger
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the drafted room assignment to the participant.
|
||||
* Applies the drafted room remarks to the participant.
|
||||
*
|
||||
* The room id uses the same merge strategy as single-select services: it is only
|
||||
* applied when it resolves to a room of the current travel. A draft may therefore move
|
||||
* a participant to another room, but never unassign one. Edit mode renders the room as
|
||||
* static text and never submits assignedRoomId, so a null in the draft is only ever an
|
||||
* artefact of a snapshot taken before BusPro reported the assignment - replaying it
|
||||
* would drop the participant's room, both in the UI and in the outbound zuordnung.
|
||||
* The drafted assignedRoomId is ignored. Edit mode renders the room as static text and
|
||||
* never submits it, so the draft only holds what BusPro reported when it was saved, and
|
||||
* replaying it would undo a reassignment the office made since. The room always comes
|
||||
* from the booking as loaded.
|
||||
*
|
||||
* remarksRoom keeps overwrite semantics: it is free text the user can deliberately clear.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
private function applyRoomAssignment(ParticipantDto $participant, array $data, Travel $travel): void
|
||||
private function applyRoomAssignment(ParticipantDto $participant, array $data): void
|
||||
{
|
||||
$assignedRoomId = $data['assignedRoomId'] ?? null;
|
||||
if (null !== $assignedRoomId && null !== $travel->getRoomById((int) $assignedRoomId)) {
|
||||
$participant->assignedRoomId = (int) $assignedRoomId;
|
||||
}
|
||||
|
||||
if (true === array_key_exists('remarksRoom', $data)) {
|
||||
$participant->remarksRoom = $data['remarksRoom'];
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Model\CmsCalendarHotel;
|
||||
use App\Model\CmsHotelData;
|
||||
use App\Model\CmsRegionData;
|
||||
use Symfony\Contracts\Cache\CacheInterface;
|
||||
@@ -169,6 +170,40 @@ class CmsDataProvider
|
||||
return is_numeric($value) ? (float) $value : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The calendar hotels of TYPO3's visible products, or null when TYPO3 did not answer with a
|
||||
* usable list. Uncached: the only caller keeps its own copy of the last good answer.
|
||||
*
|
||||
* @return list<CmsCalendarHotel>|null
|
||||
*/
|
||||
public function fetchCalendarHotels(): ?array
|
||||
{
|
||||
try {
|
||||
$data = $this->httpClient->request('GET', 'api/calendar-hotels')->toArray();
|
||||
} catch (ExceptionInterface) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!array_is_list($data)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$hotels = [];
|
||||
|
||||
foreach ($data as $entry) {
|
||||
$code = $entry['code'] ?? null;
|
||||
|
||||
if (!is_string($code) || '' === $code) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = $entry['name'] ?? null;
|
||||
$hotels[] = new CmsCalendarHotel($code, is_string($name) && '' !== $name ? $name : $code);
|
||||
}
|
||||
|
||||
return $hotels;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function getProductDetails(string $productCode, ?string $hotelCode = null): array
|
||||
{
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Entity\Groups\CalendarHotel;
|
||||
use App\Model\ContingentHotel;
|
||||
use App\Repository\Groups\AccommodationRepository;
|
||||
use App\Repository\Groups\CalendarHotelRepository;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
/**
|
||||
* The hotel codes the contingent snapshot is kept for: every accommodation's calendarCode plus
|
||||
* the calendar hotels of TYPO3's visible products.
|
||||
*
|
||||
* Neither source is maintained here. Accommodations are the Groups admin's, the TYPO3 list is
|
||||
* TYPO3's; `calendar_hotel` only holds the last list TYPO3 answered with, so an unreachable
|
||||
* TYPO3 does not make its hotels drop out of the sync.
|
||||
*/
|
||||
class ContingentHotelDirectory
|
||||
{
|
||||
// Same rule as the hotelCode query parameter of the contingent API: a code nobody can ask
|
||||
// for is not worth syncing, and it would not fit the column either.
|
||||
private const string CODE_PATTERN = '/^[A-Za-z0-9_-]{1,16}$/';
|
||||
|
||||
public function __construct(
|
||||
private readonly CmsDataProvider $cmsDataProvider,
|
||||
private readonly AccommodationRepository $accommodationRepository,
|
||||
private readonly CalendarHotelRepository $calendarHotelRepository,
|
||||
private readonly EntityManagerInterface $entityManager,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the stored TYPO3 list with the one TYPO3 serves now.
|
||||
*
|
||||
* An error or an empty list keeps the stored one: TYPO3 without a single calendar hotel is
|
||||
* a fault on its side, not every winter hotel being withdrawn at once.
|
||||
*/
|
||||
public function refresh(): bool
|
||||
{
|
||||
$fetched = [];
|
||||
|
||||
foreach ($this->cmsDataProvider->fetchCalendarHotels() ?? [] as $hotel) {
|
||||
if (1 !== preg_match(self::CODE_PATTERN, $hotel->code)) {
|
||||
$this->logger->warning('Ignoring TYPO3 calendar hotel with an unusable code', ['hotelCode' => $hotel->code]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$fetched[$hotel->code] = $hotel;
|
||||
}
|
||||
|
||||
if ([] === $fetched) {
|
||||
$this->logger->warning('TYPO3 calendar hotels unavailable, keeping the stored list');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$stored = $this->calendarHotelRepository->findAllIndexedByCode();
|
||||
|
||||
foreach ($fetched as $code => $hotel) {
|
||||
$calendarHotel = $stored[$code] ?? null;
|
||||
|
||||
if (null === $calendarHotel) {
|
||||
$this->entityManager->persist((new CalendarHotel())->setCode($code)->setName($hotel->name));
|
||||
} elseif ($calendarHotel->getName() !== $hotel->name) {
|
||||
$calendarHotel->setName($hotel->name);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (array_diff_key($stored, $fetched) as $calendarHotel) {
|
||||
$this->entityManager->remove($calendarHotel);
|
||||
}
|
||||
|
||||
$this->entityManager->flush();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, ContingentHotel> keyed and sorted by hotel code
|
||||
*/
|
||||
public function all(): array
|
||||
{
|
||||
$accommodations = [];
|
||||
|
||||
foreach ($this->accommodationRepository->findAllWithCalendarCode() as $accommodation) {
|
||||
$accommodations[(string) $accommodation->getCalendarCode()] = $accommodation;
|
||||
}
|
||||
|
||||
$calendarHotels = $this->calendarHotelRepository->findAllIndexedByCode();
|
||||
|
||||
$hotels = [];
|
||||
|
||||
foreach (array_keys($accommodations + $calendarHotels) as $code) {
|
||||
$code = (string) $code;
|
||||
$hotels[$code] = new ContingentHotel($code, $accommodations[$code] ?? null, $calendarHotels[$code] ?? null);
|
||||
}
|
||||
|
||||
ksort($hotels, \SORT_STRING);
|
||||
|
||||
return $hotels;
|
||||
}
|
||||
|
||||
public function find(string $hotelCode): ?ContingentHotel
|
||||
{
|
||||
if ('' === $hotelCode) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$accommodation = $this->accommodationRepository->findOneByCalendarCode($hotelCode);
|
||||
$calendarHotel = $this->calendarHotelRepository->findOneBy(['code' => $hotelCode]);
|
||||
|
||||
if (null === $accommodation && null === $calendarHotel) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new ContingentHotel($hotelCode, $accommodation, $calendarHotel);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ namespace App\Service;
|
||||
|
||||
use App\BpnConnect\ContingentsClient;
|
||||
use App\BpnConnect\Exception\BpnConnectException;
|
||||
use App\Entity\Groups\Accommodation;
|
||||
use App\Entity\Groups\ContingentDay;
|
||||
use App\Entity\Groups\ContingentSyncState;
|
||||
use App\Model\ContingentSyncResult;
|
||||
@@ -34,24 +33,22 @@ class ContingentSnapshotManager
|
||||
}
|
||||
|
||||
/**
|
||||
* Refreshes [dateFrom, dateTo] for a single accommodation.
|
||||
* Refreshes [dateFrom, dateTo] for a single hotel code.
|
||||
*
|
||||
* Days are fetched, diffed against what is stored and then persisted; the snapshot outside
|
||||
* the requested window is left untouched, so a narrow ad-hoc run cannot truncate what a
|
||||
* full-horizon run already stored.
|
||||
*/
|
||||
public function sync(
|
||||
Accommodation $accommodation,
|
||||
string $hotelCode,
|
||||
\DateTimeImmutable $dateFrom,
|
||||
\DateTimeImmutable $dateTo,
|
||||
): ContingentSyncResult {
|
||||
$hotelCode = $accommodation->getCalendarCode();
|
||||
|
||||
if (null === $hotelCode || '' === $hotelCode) {
|
||||
return ContingentSyncResult::failed('Accommodation has no calendarCode.');
|
||||
if ('' === $hotelCode) {
|
||||
return ContingentSyncResult::failed('No hotel code given.');
|
||||
}
|
||||
|
||||
$state = $this->syncStateRepository->findOneByAccommodation($accommodation) ?? new ContingentSyncState($accommodation);
|
||||
$state = $this->syncStateRepository->findOneByHotelCode($hotelCode) ?? new ContingentSyncState($hotelCode);
|
||||
|
||||
// Read before recordSuccess() moves it: days beyond the horizon the previous run reached
|
||||
// are the window growing, not the contingent situation changing.
|
||||
@@ -67,7 +64,7 @@ class ContingentSnapshotManager
|
||||
return $this->recordFailure($state, $hotelCode, $e->getMessage());
|
||||
}
|
||||
|
||||
$existing = $this->dayRepository->findByAccommodationAndDateRange($accommodation, $dateFrom, $dateTo);
|
||||
$existing = $this->dayRepository->findByHotelCodeAndDateRange($hotelCode, $dateFrom, $dateTo);
|
||||
|
||||
// An empty upstream response would otherwise wipe the window and render the whole
|
||||
// period as BLOCKED. Treat it as an upstream problem and keep the last good snapshot.
|
||||
@@ -103,7 +100,7 @@ class ContingentSnapshotManager
|
||||
|
||||
if (null === $day) {
|
||||
$day = (new ContingentDay())
|
||||
->setAccommodation($accommodation)
|
||||
->setHotelCode($hotelCode)
|
||||
->setDate($date);
|
||||
|
||||
$this->entityManager->persist($day);
|
||||
|
||||
@@ -5,7 +5,7 @@ declare(strict_types=1);
|
||||
namespace App\Service;
|
||||
|
||||
use App\BpnConnect\Model\ContingentStatus;
|
||||
use App\Entity\Groups\Accommodation;
|
||||
use App\Entity\Groups\ContingentSyncState;
|
||||
use App\Repository\Groups\ContingentDayRepository;
|
||||
use App\Repository\Groups\ContingentSyncStateRepository;
|
||||
use Carbon\CarbonImmutable;
|
||||
@@ -41,22 +41,20 @@ class ContingentSnapshotReader
|
||||
* Per-day statuses keyed by Y-m-d, or null when there is no usable snapshot for this hotel.
|
||||
*
|
||||
* Days inside the range that the snapshot does not cover are simply absent from the map;
|
||||
* what that means is the caller's decision.
|
||||
* what that means is the caller's decision. A null dateTo reads to the end of the snapshot.
|
||||
*
|
||||
* @return array<string, ContingentStatus>|null
|
||||
*/
|
||||
public function statusesFor(
|
||||
Accommodation $accommodation,
|
||||
string $hotelCode,
|
||||
\DateTimeImmutable $dateFrom,
|
||||
\DateTimeImmutable $dateTo,
|
||||
?\DateTimeImmutable $dateTo,
|
||||
): ?array {
|
||||
$hotelCode = $accommodation->getCalendarCode();
|
||||
|
||||
if (null === $hotelCode || '' === $hotelCode) {
|
||||
if ('' === $hotelCode) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!$this->isUsable($accommodation, $hotelCode)) {
|
||||
if (!$this->isUsable($hotelCode)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -69,25 +67,36 @@ class ContingentSnapshotReader
|
||||
return $statuses;
|
||||
}
|
||||
|
||||
private function isUsable(Accommodation $accommodation, string $hotelCode): bool
|
||||
/**
|
||||
* Whether a hotel with this sync state gets statuses from {@see self::statusesFor()}, without
|
||||
* the logging: for overviews that ask about every hotel at once.
|
||||
*/
|
||||
public function isCurrent(?ContingentSyncState $state): bool
|
||||
{
|
||||
$syncedAt = $this->syncStateRepository->findOneByAccommodation($accommodation)?->getSyncedAt();
|
||||
$syncedAt = $state?->getSyncedAt();
|
||||
|
||||
return null !== $syncedAt && $syncedAt >= CarbonImmutable::now()->modify(self::MAX_SNAPSHOT_AGE);
|
||||
}
|
||||
|
||||
private function isUsable(string $hotelCode): bool
|
||||
{
|
||||
$state = $this->syncStateRepository->findOneByHotelCode($hotelCode);
|
||||
|
||||
if ($this->isCurrent($state)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$syncedAt = $state?->getSyncedAt();
|
||||
|
||||
if (null === $syncedAt) {
|
||||
$this->logger->error('No contingent snapshot has been synced yet', ['hotelCode' => $hotelCode]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($syncedAt < CarbonImmutable::now()->modify(self::MAX_SNAPSHOT_AGE)) {
|
||||
} else {
|
||||
$this->logger->error('Contingent snapshot is stale', [
|
||||
'hotelCode' => $hotelCode,
|
||||
'syncedAt' => $syncedAt->format(\DateTimeInterface::ATOM),
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -67,6 +67,7 @@ class ParticipantDataPrefiller
|
||||
$applicant->dateOfBirth = $prepopulated->dateOfBirth;
|
||||
$applicant->email = $prepopulated->email;
|
||||
$applicant->mobile = $prepopulated->mobile;
|
||||
$applicant->loadedMobile = $prepopulated->loadedMobile;
|
||||
$applicant->address = $prepopulated->address;
|
||||
$applicant->height = $prepopulated->height;
|
||||
$applicant->weight = $prepopulated->weight;
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\BpnConnect\Exception\BpnConnectException;
|
||||
use App\BpnConnect\RoomsClient;
|
||||
use App\BusProNet\Model\Travel;
|
||||
use App\Model\RoomContingentPool;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Contracts\Cache\CacheInterface;
|
||||
use Symfony\Contracts\Cache\ItemInterface;
|
||||
|
||||
/**
|
||||
* Groups a travel's offered rooms by the BusPro contingent they share.
|
||||
*
|
||||
* The link is hotel setup, not availability, so it is cached per hotel; the remaining count keeps
|
||||
* coming from the travel data. When bpn-connect cannot answer, every room counts as its own pool,
|
||||
* which is how bookings behaved before: bpn-connect and BusPro sit behind the same link, so a
|
||||
* booking is unlikely to get through while bpn-connect is unreachable anyway.
|
||||
*/
|
||||
class RoomContingentPoolResolver
|
||||
{
|
||||
private const int CACHE_TTL_SECONDS = 3600;
|
||||
|
||||
public function __construct(
|
||||
private readonly RoomsClient $roomsClient,
|
||||
private readonly CacheInterface $cache,
|
||||
#[Autowire(service: 'monolog.logger.bpn')]
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<RoomContingentPool> pools with more than one offered room, in room order
|
||||
*/
|
||||
public function findSharedPools(Travel $travel): array
|
||||
{
|
||||
if (null === $travel->hotelId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$poolIds = $this->getPoolIds($travel->hotelId);
|
||||
if ([] === $poolIds) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$roomsByPool = [];
|
||||
foreach ($travel->getAvailableRooms() as $roomId => $room) {
|
||||
$roomsByPool[$poolIds[$roomId] ?? $roomId][$roomId] = $room;
|
||||
}
|
||||
|
||||
$pools = [];
|
||||
foreach ($roomsByPool as $rooms) {
|
||||
if (1 < count($rooms)) {
|
||||
$pools[] = new RoomContingentPool($rooms);
|
||||
}
|
||||
}
|
||||
|
||||
return $pools;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, int> room type id => pool room type id, empty when unknown
|
||||
*/
|
||||
private function getPoolIds(int $hotelId): array
|
||||
{
|
||||
try {
|
||||
return $this->cache->get(
|
||||
sprintf('bpn_connect_room_contingent_pools_%d', $hotelId),
|
||||
function (ItemInterface $item) use ($hotelId): array {
|
||||
$item->expiresAfter(self::CACHE_TTL_SECONDS);
|
||||
|
||||
return $this->roomsClient->getContingentPools($hotelId);
|
||||
}
|
||||
);
|
||||
} catch (BpnConnectException $e) {
|
||||
// Thrown inside the callback, so nothing was cached and the next request asks again.
|
||||
$this->logger->error('Room contingent pools unavailable, rooms are checked one by one', [
|
||||
'hotel_id' => $hotelId,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 192 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user