From 5455973dba6df70bdfabe5f1f74c34163d3c745a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Fromme?= Date: Mon, 16 Nov 2026 17:18:00 +0100 Subject: [PATCH] feat: Kalender-Code replaces the product's calendar hotel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every hotel field now has one job. The hotel's code and aliases are import codes only (dates, lookups); a new Kalender-Code (calendar_code) decides the availability a record shows and may be shared by a house's summer and winter records. The product's "Unterkunft für Belegungskalender" is replaced by the checkbox "Kalender anzeigen" (show_calendar): a product page shows the calendar of the hotel it displays, the season still decides which one. - Price calendar, price tables, Belegungskalender, iCal feeds and /api/calendar-hotels read the Kalender-Code. A feed without one answers 404 instead of an empty calendar. - The upgrade wizard epProductsCalendarCode fills both fields from calendar_hotel, preserving today's calendars; the deploy runs it between the schema update and the switch. calendar_hotel stays in the database, so the previous release keeps working. ep:calendar-codes lists the product pages whose calendar differs from it. - HotelCodeResolver is the one lookup of import codes (date import, /api/hotel, Travelinfo); a code on several records resolves to the record whose own code it is, then the lowest uid, with a warning. Saving a code that is already another visible record's import code is refused with a message naming that record. - /api/product without hotel attaches the product's only visible Unterkunft (422 otherwise) and adds board_description, additional_services and calendar_hotel_code. Co-Authored-By: Claude Opus 5.5 --- deploy.php | 10 + docs/calendars.md | 53 ++-- docs/cms-api.md | 40 ++- .../Classes/Command/CalendarCodesCommand.php | 47 +++ .../Controller/AjaxCalendarController.php | 6 +- .../Classes/Controller/IcalController.php | 11 + .../Classes/Controller/ProductController.php | 1 + .../Controller/TravelinfoController.php | 5 +- .../Classes/Domain/Model/Hotel.php | 16 + .../Classes/Domain/Model/Product.php | 25 ++ .../Domain/Repository/HotelRepository.php | 13 - .../Classes/Hooks/ImportCodeCheck.php | 70 +++++ .../Classes/Middleware/ApiMiddleware.php | 157 ++++++++-- .../Classes/Service/CalendarCodeMigration.php | 274 ++++++++++++++++++ .../Classes/Service/DateImportService.php | 30 +- .../Classes/Service/HotelCodeResolver.php | 110 +++++++ .../Classes/Service/IcalService.php | 17 +- .../Classes/Upgrades/CalendarCodeUpdate.php | 62 ++++ .../ep_products/Configuration/Services.yaml | 2 + .../TCA/tx_epproducts_domain_model_hotel.php | 21 +- .../tx_epproducts_domain_model_product.php | 12 +- packages/ep_products/ext_localconf.php | 3 + packages/ep_products/ext_tables.sql | 2 + .../Partials/Product/PriceCalendar.html | 8 +- .../Private/Templates/Product/Detail.html | 12 +- 25 files changed, 880 insertions(+), 127 deletions(-) create mode 100644 packages/ep_products/Classes/Command/CalendarCodesCommand.php create mode 100644 packages/ep_products/Classes/Hooks/ImportCodeCheck.php create mode 100644 packages/ep_products/Classes/Service/CalendarCodeMigration.php create mode 100644 packages/ep_products/Classes/Service/HotelCodeResolver.php create mode 100644 packages/ep_products/Classes/Upgrades/CalendarCodeUpdate.php diff --git a/deploy.php b/deploy.php index b4e5041..e2962c6 100644 --- a/deploy.php +++ b/deploy.php @@ -112,6 +112,15 @@ task('deploy:check:site-settings', function () { } }); +// Data migrations that the new release needs, named one by one: a wizard already done is skipped, +// and pending core or third-party wizards are not run unattended +set('upgrade_wizards', ['epProductsCalendarCode']); +task('typo3:upgrade:run', function () { + foreach (get('upgrade_wizards') as $wizard) { + run("{{bin/php}} {{release_path}}/{{bin/typo3}} upgrade:run $wizard --no-interaction"); + } +}); + // current_path instead of the recipe's release_path, so it also works after a rollback task('typo3:cache:flush', function () { run('{{bin/php}} {{current_path}}/{{bin/typo3}} cache:flush'); @@ -131,6 +140,7 @@ task('deploy', [ 'deploy:writable', // The schema has to exist before the new code starts serving traffic. 'typo3:extension:setup', + 'typo3:upgrade:run', // deploy:publish == deploy:symlink, deploy:unlock, deploy:cleanup, deploy:success 'deploy:publish', ]); diff --git a/docs/calendars.md b/docs/calendars.md index 4e57f57..3c3d691 100644 --- a/docs/calendars.md +++ b/docs/calendars.md @@ -6,32 +6,35 @@ group house prices. | What | Where | Shown for | MyE&P endpoint | |---|---|---|---| -| **Price calendar** + price tables | product detail, tab "Termine/Preise" | products with a calendar hotel and season **summer** (`s`) | `contingents/calendar`, `contingents/prices` | -| **Belegungskalender** (availability calendar) | product detail, sidebar | products with a calendar hotel and season **not summer** | `contingents/availability` (+ `contingents/calendar` for the months to leave out) | -| **iCal feed** for booking portals | `https://www.ep-reisen.de/contingents/.ical` | every hotel | `contingents/availability` | +| **Price calendar** + price tables | product detail, tab "Termine/Preise" | products with a calendar and season **summer** (`s`) | `contingents/calendar`, `contingents/prices` | +| **Belegungskalender** (availability calendar) | product detail, sidebar | products with a calendar and season **not summer** | `contingents/availability` (+ `contingents/calendar` for the months to leave out) | +| **iCal feed** for booking portals | `https://www.ep-reisen.de/contingents/.ical` | every hotel with a Kalender-Code | `contingents/availability` | -So every product with a calendar hotel shows exactly one calendar. The MyE&P side is documented in +So every product with a calendar shows exactly one. The MyE&P side is documented in its `docs/api-consumer-guide.md` (`EP/myep`). -## The calendar hotel field +## Hotel codes -A product's **calendar hotel** (`calendar_hotel`) decides whose availability and prices it shows. -TYPO3 sends that hotel's **code** to MyE&P, which only understands **BusPro calendar codes** (the -codes bpn-connect knows, e.g. `DGS`, `LPJ`, `DKS`). +Every field has one job: -Most hotel records carry the BusPro code. Group houses also have **content records** of their own -(`DKSGRP`, `LPJGRP`, `SERASCSO`, …) whose code is the **CMS code** MyE&P uses to fetch content via -`/api/hotel`. These must **not** be used as calendar hotel: MyE&P and bpn-connect do not know -them, and the calendar shows its error message. This broke three example trips until 2026-10-29. - -| Use as calendar hotel | Not | +| Field | Job | |---|---| -| `DKS` Sportclub Schweizerhaus (uid 193) | `DKSGRP` Davos Klosters - Gruppenhaus Schweizerhaus | -| `LPJ` Sportclub Jenatsch (uid 37) | `LPJGRP` Lenzerheide - Gruppenhaus Jenatsch | +| Hotel › **Import-Code** (`code`) and **Weitere Import-Codes** (matchcode aliases) | The BusPro codes whose imported dates land on this record, and by which `/api/hotel`, `/api/product?hotel=` and the Travelinfo page find it (`HotelCodeResolver`). A code belongs to one visible record; saving it on a second one is refused. Nothing to do with the calendars. | +| Hotel › **Kalender-Code** (`calendar_code`) | The BusPro code whose contingent this record shows: calendars, price tables, iCal feed. Empty = no calendar, the feed answers `404`. Records may share it: a house's summer record (`…GRP`) and its winter record both carry the house's code. | +| Product › **Kalender anzeigen** (`show_calendar`) | Whether the product page shows a calendar at all. | +| Product › **Saison** (`season`) | Which one: `s` the price calendar, anything else the Belegungskalender. | -`/api/calendar-hotels` lists all calendar hotels in use; every code in it should be a BusPro code. -A hidden hotel record counts as no calendar hotel: the product shows no calendar and the code is -not in the list (e.g. `ASB` Sportclub Bader). +**The calendar on a product page is the Kalender-Code of the hotel that page shows**: the hotel +pinned in the Produktdetail element, else the product's only Unterkunft, else the one picked in +its hotel list (`Product::getCalendarHotelFor()`). + +MyE&P only understands **BusPro codes** that it syncs (e.g. `DGS`, `LPJ`, `DKS`). When BusPro has +several entries for a house (Mitterlengau: nine), only one carries the house's contingent; the +office says which one, and that is the Kalender-Code. + +The product's old "Unterkunft für Belegungskalender" (`calendar_hotel`) is no longer read. The +upgrade wizard `epProductsCalendarCode` filled the new fields from it; `vendor/bin/typo3 +ep:calendar-codes` lists the product pages whose calendar differs from it, until it is removed. ## Price calendar (summer) @@ -62,7 +65,7 @@ not in the list (e.g. `ASB` Sportclub Bader). - `IcalController::contingentsAction`, `IcalService`; route `/contingents/{hotel}.ical` on the `ep-reisen` site (`config/sites/ep-reisen/config.yaml`, page 9, type 1710), `{hotel}` is the - hotel's path segment. + hotel's path segment. The feed shows the record's Kalender-Code; without one it answers `404`. - One `Unavailable` event per run of `BLOCKED` or `ON_REQUEST` days with the same status, as on TYPO3 10. - Never cached. When MyE&P has no availability it answers `503` with `Retry-After: 900` instead of @@ -72,8 +75,9 @@ not in the list (e.g. `ASB` Sportclub Bader). MyE&P syncs its snapshot from bpn-connect every 15 minutes during the day and hourly at night, for the calendar codes of its accommodations **plus** every code in TYPO3's `/api/calendar-hotels` -(see [cms-api.md](cms-api.md)). So a hotel offered only in winter needs nothing in MyE&P: setting -it as calendar hotel of a visible product is enough; it is synced with the next run. +(see [cms-api.md](cms-api.md)), which lists the Kalender-Code of every visible hotel record. So a +hotel offered only in winter needs nothing in MyE&P: giving the record a Kalender-Code is enough; +it is synced with the next run. `contingents/availability` answers: - `400` for a code that is not synced (not an accommodation, not in TYPO3's list), @@ -106,8 +110,9 @@ The message is "Der Kalender konnte aktuell nicht geladen werden."; the iCal fee | Cause | How to tell | Fix | |---|---|---| -| Calendar hotel has a CMS code (`…GRP`, `…SO`) | code not BusPro; MyE&P `400`, bpn-connect `404` | set the hotel record with the BusPro code as calendar hotel | -| Code not synced by MyE&P | not in `contingents/status`; MyE&P `400` | check that the product and its calendar hotel are visible (then it is in `/api/calendar-hotels`) | +| No calendar at all | product's "Kalender anzeigen" off, or the shown hotel has no Kalender-Code | tick it / set the Kalender-Code of the hotel the page shows | +| Kalender-Code is not a BusPro code (`…GRP`, `…SO`) | MyE&P `400`, bpn-connect `404` | set the house's BusPro code as Kalender-Code | +| Code not synced by MyE&P | not in `contingents/status`; MyE&P `400` | check that the hotel record is visible (then its code is in `/api/calendar-hotels`) | | Sync failing for the hotel | `contingents/status`: `available: false`, `lastError` | MyE&P / bpn-connect | | MyE&P unreachable or its OAuth failing | all hotels fail; TYPO3 log `EP.EpProducts.MyEP.ApiClient` | MyE&P | | Price calendar only: no accommodation or no prices | MyE&P `400` / empty | prices are maintained in MyE&P's Groups admin | diff --git a/docs/cms-api.md b/docs/cms-api.md index 67bbfb4..5522c07 100644 --- a/docs/cms-api.md +++ b/docs/cms-api.md @@ -23,8 +23,9 @@ changed together. Content of one hotel, for MyE&P's group house pages and booking flow. -- `hotel`: the TYPO3 hotel code or one of its matchcode aliases. In MyE&P this is the - accommodation's **CMS code** (e.g. `DGSGRP`), which can differ from its calendar code. +- `hotel`: an import code of the record: its "Import-Code" or one of its "Weitere Import-Codes" + (matchcode aliases), resolved by `HotelCodeResolver`. In MyE&P this is the accommodation's + **CMS code** (e.g. `DGSGRP`), which can differ from its calendar code. - `400` without `hotel`, `404 {"message": "Hotel not found"}` for an unknown code. ```json @@ -42,15 +43,23 @@ Content of one hotel, for MyE&P's group house pages and booking flow. ## `GET /api/product?product=[&hotel=]` -Content of one product, optionally with a hotel. +Content of one product with a hotel. -- `product`: the product code. `400` without it, `404 {"message": "Product not found"}` for an - unknown code. -- `hotel` (optional): adds `hotel` with the same content as `/api/hotel`. +- `product`: the product code (default language). `400` without it, `404 {"message": "Product + not found"}` for an unknown code. +- Without `hotel` (MyE&P's group houses, linked by product code): the product's only visible + Unterkunft. Any other number of visible Unterkünfte answers `422 {"message": "Product + links hotels, expected exactly 1", "hotel_count": }`. +- With `hotel` (MyE&P's booking flow): the record of that import code, as in `/api/hotel`; an + unknown code gives `"hotel": []`. +- `board_description`, `additional_services`: raw RTE values, `""` when empty. +- `calendar_hotel_code`: the Kalender-Code of the hotel when "Kalender anzeigen" is on, else + `null`. MyE&P compares it with its accommodation's calendar code. ```json { - "product": {"name": "…", "code": "…", "images": {…}}, + "product": {"name": "…", "code": "…", "images": {…}, "board_description": "…", + "additional_services": "…", "calendar_hotel_code": "SST"}, "country": {"name": "…"}, "region": {…}, "city": {"name": "…"}, @@ -60,12 +69,14 @@ Content of one product, optionally with a hotel. ## `GET /api/calendar-hotels` -The calendar hotel of every visible product: the hotel codes whose availability TYPO3 shows -(iCal feed, availability calendar, price calendar). MyE&P syncs its contingent snapshot for -these codes in addition to its accommodations, so hotels offered only in winter, which have no -accommodation in MyE&P, have availability too. See [calendars.md](calendars.md). +The Kalender-Codes of all visible hotel records: the codes whose availability TYPO3 shows (iCal +feeds, availability calendar, price calendar). MyE&P syncs its contingent snapshot for these codes +in addition to its accommodations, so hotels offered only in winter, which have no accommodation in +MyE&P, have availability too. See [calendars.md](calendars.md). -- Only products and hotels that are not hidden or deleted; hotels without a code are left out. +- One entry per code; `name` of the record whose import code it is, else of the first record. +- `products`: visible products with "Kalender anzeigen" that link a record with the code under + Unterkünfte. - Sorted by code; products by uid. Names have line breaks collapsed. - `season`: `"s"` (summer), `"w"` (winter) or `null`. @@ -78,9 +89,8 @@ accommodation in MyE&P, have availability too. See [calendars.md](calendars.md). ] ``` -Every code in this list should be a **BusPro calendar code**. A group house's content record -(`…GRP`, `…SO`) set as a product's calendar hotel puts its CMS code in here, which bpn-connect does -not know (see [calendars.md](calendars.md#the-calendar-hotel-field)). +Every code in this list should be a **BusPro code** with a contingent (see +[calendars.md](calendars.md#hotel-codes)). ## `GET /api/content/manifest` and `GET /api/content/records?type=&uids=` diff --git a/packages/ep_products/Classes/Command/CalendarCodesCommand.php b/packages/ep_products/Classes/Command/CalendarCodesCommand.php new file mode 100644 index 0000000..1d2e073 --- /dev/null +++ b/packages/ep_products/Classes/Command/CalendarCodesCommand.php @@ -0,0 +1,47 @@ +calendarCodeMigration->findDifferences(); + if ([] === $differences) { + $io->success('Every product page shows the same calendar as with "Unterkunft für Belegungskalender".'); + return Command::SUCCESS; + } + + $io->table( + ['Produkt', 'Saison', 'Unterkunft', 'bisher', 'jetzt'], + array_map(static fn(array $row): array => [ + sprintf('%d %s', $row['product'], $row['name']), + $row['season'], + 0 === $row['hotel'] ? $row['hotelName'] : sprintf('%d %s', $row['hotel'], $row['hotelName']), + '' !== $row['before'] ? $row['before'] : '–', + '' !== $row['after'] ? $row['after'] : '–', + ], $differences) + ); + $io->writeln('bisher: Code der "Unterkunft für Belegungskalender"; jetzt: Kalender-Code der angezeigten Unterkunft, wenn "Kalender anzeigen" an ist.'); + + return Command::SUCCESS; + } +} diff --git a/packages/ep_products/Classes/Controller/AjaxCalendarController.php b/packages/ep_products/Classes/Controller/AjaxCalendarController.php index 15da4e6..58a83b9 100644 --- a/packages/ep_products/Classes/Controller/AjaxCalendarController.php +++ b/packages/ep_products/Classes/Controller/AjaxCalendarController.php @@ -19,7 +19,7 @@ class AjaxCalendarController extends ActionController public function priceCalendarAction(Hotel $hotel, int $months = 12): ResponseInterface { - $hotelCode = trim($hotel->getCode() ?? ''); + $hotelCode = trim($hotel->getCalendarCode()); $this->tagPageCacheForHotel($hotelCode); $dateRange = DateUtility::getDateRange(null, null, $months); @@ -120,7 +120,7 @@ class AjaxCalendarController extends ActionController */ public function availabilityAction(Hotel $hotel, int $months = 12): ResponseInterface { - $hotelCode = trim($hotel->getCode() ?? ''); + $hotelCode = trim($hotel->getCalendarCode()); $this->tagPageCacheForHotel($hotelCode); $period = DateUtility::getDateRange(null, null, $months)['period']; @@ -206,7 +206,7 @@ class AjaxCalendarController extends ActionController public function priceTableAction(Hotel $hotel, ?string $year = null): ResponseInterface { $year ??= new \DateTimeImmutable()->format('Y'); - $hotelCode = trim($hotel->getCode() ?? ''); + $hotelCode = trim($hotel->getCalendarCode()); $this->tagPageCacheForHotel($hotelCode); $priceTable = [ diff --git a/packages/ep_products/Classes/Controller/IcalController.php b/packages/ep_products/Classes/Controller/IcalController.php index 62a27ef..74fd23d 100644 --- a/packages/ep_products/Classes/Controller/IcalController.php +++ b/packages/ep_products/Classes/Controller/IcalController.php @@ -21,6 +21,17 @@ class IcalController extends ActionController */ public function contingentsAction(Hotel $hotel): ResponseInterface { + // Without a Kalender-Code the hotel has no availability; an empty calendar would read as free + if ('' === trim($hotel->getCalendarCode())) { + throw new PropagateResponseException( + $this->responseFactory->createResponse(404) + ->withHeader('Content-Type', 'text/plain; charset=utf-8') + ->withHeader('Cache-Control', 'private, no-store') + ->withBody($this->streamFactory->createStream('No availability for this hotel')), + 1763309100 + ); + } + $calendar = $this->icalService->createContingentsFeed($hotel); // An empty calendar would show the portals every day as free; an error keeps their last import diff --git a/packages/ep_products/Classes/Controller/ProductController.php b/packages/ep_products/Classes/Controller/ProductController.php index 4aaa102..0eb910a 100644 --- a/packages/ep_products/Classes/Controller/ProductController.php +++ b/packages/ep_products/Classes/Controller/ProductController.php @@ -94,6 +94,7 @@ class ProductController extends ActionController $this->view->assignMultiple([ 'hotel' => $hotel, 'product' => $product, + 'calendarHotel' => $product->getCalendarHotelFor($hotel), // Daytrip availability came from the contingent import, which is not ported 'enabledDates' => [], 'isProductWithExcludedConcept' => $isProductWithExcludedConcept, diff --git a/packages/ep_products/Classes/Controller/TravelinfoController.php b/packages/ep_products/Classes/Controller/TravelinfoController.php index 2bf953f..8529793 100644 --- a/packages/ep_products/Classes/Controller/TravelinfoController.php +++ b/packages/ep_products/Classes/Controller/TravelinfoController.php @@ -6,6 +6,7 @@ use Psr\Http\Message\ResponseInterface; use EP\EpProducts\Domain\Model\Hotel; use EP\EpProducts\Domain\Model\Travelinfo; use EP\EpProducts\Domain\Repository\HotelRepository; +use EP\EpProducts\Service\HotelCodeResolver; use EP\EpProducts\Domain\Repository\TravelinfoRepository; use EP\EpProducts\MyEP\ApiClient; use EP\EpProducts\MyEP\ApiException; @@ -22,6 +23,7 @@ class TravelinfoController extends ActionController private readonly ApiClient $apiClient, private readonly TravelinfoRepository $travelinfoRepository, private readonly HotelRepository $hotelRepository, + private readonly HotelCodeResolver $hotelCodeResolver, ) { } @@ -101,7 +103,8 @@ class TravelinfoController extends ActionController $hotel = null; $hotelCode = $travelData['hotel']['code'] ?? null; if (null !== $hotelCode && '' !== $hotelCode) { - $hotel = $this->hotelRepository->findOneByCodeOrAdditionalCode($hotelCode); + $hotelUid = $this->hotelCodeResolver->findUid($hotelCode); + $hotel = null !== $hotelUid ? $this->hotelRepository->findByUid($hotelUid) : null; } $hotelAddress = $hotel instanceof Hotel ? trim((string)$hotel->getAddress()) : ''; diff --git a/packages/ep_products/Classes/Domain/Model/Hotel.php b/packages/ep_products/Classes/Domain/Model/Hotel.php index 0325d76..83decb4 100644 --- a/packages/ep_products/Classes/Domain/Model/Hotel.php +++ b/packages/ep_products/Classes/Domain/Model/Hotel.php @@ -171,6 +171,12 @@ class Hotel extends AbstractEntity implements TeaserInterface */ protected $code = ''; + /** + * BusPro code of the house whose availability this record shows, shared by its summer and + * winter records; empty = no calendar + */ + protected string $calendarCode = ''; + /** * @var ObjectStorage */ @@ -765,6 +771,16 @@ class Hotel extends AbstractEntity implements TeaserInterface $this->code = $code; } + public function getCalendarCode(): string + { + return $this->calendarCode; + } + + public function setCalendarCode(string $calendarCode): void + { + $this->calendarCode = $calendarCode; + } + public function addAdditionalCode(MatchCode $code): void { $this->additionalCodes->attach($code); diff --git a/packages/ep_products/Classes/Domain/Model/Product.php b/packages/ep_products/Classes/Domain/Model/Product.php index bde2968..7c1a28d 100644 --- a/packages/ep_products/Classes/Domain/Model/Product.php +++ b/packages/ep_products/Classes/Domain/Model/Product.php @@ -239,6 +239,8 @@ class Product extends AbstractEntity implements TeaserInterface */ protected $calendarHotel; + protected bool $showCalendar = false; + /** * @var Product */ @@ -1024,6 +1026,29 @@ class Product extends AbstractEntity implements TeaserInterface $this->calendarHotel = $calendarHotel; } + public function getShowCalendar(): bool + { + return $this->showCalendar; + } + + public function setShowCalendar(bool $showCalendar): void + { + $this->showCalendar = $showCalendar; + } + + /** + * The hotel whose calendar this product's page shows: the hotel the page shows, when + * "Kalender anzeigen" is on and that hotel has a Kalender-Code + */ + public function getCalendarHotelFor(?Hotel $hotel): ?Hotel + { + if (!$this->showCalendar || null === $hotel || '' === trim($hotel->getCalendarCode())) { + return null; + } + + return $hotel; + } + /** * @return Product */ diff --git a/packages/ep_products/Classes/Domain/Repository/HotelRepository.php b/packages/ep_products/Classes/Domain/Repository/HotelRepository.php index 9e1683f..f9ed82a 100644 --- a/packages/ep_products/Classes/Domain/Repository/HotelRepository.php +++ b/packages/ep_products/Classes/Domain/Repository/HotelRepository.php @@ -243,17 +243,4 @@ class HotelRepository extends AbstractRepository return $query->execute(); } - public function findOneByCodeOrAdditionalCode(string $code): ?Hotel - { - $query = $this->createQuery(); - $query->matching( - $query->logicalOr( - $query->equals('code', $code), - $query->equals('additionalCodes.code', $code) - ) - ); - - return $query->execute()->getFirst(); - } - } diff --git a/packages/ep_products/Classes/Hooks/ImportCodeCheck.php b/packages/ep_products/Classes/Hooks/ImportCodeCheck.php new file mode 100644 index 0000000..eae1db6 --- /dev/null +++ b/packages/ep_products/Classes/Hooks/ImportCodeCheck.php @@ -0,0 +1,70 @@ +recordInfo($table, (int)$id)['code'] ?? ''))) === strtoupper(trim((string)$fieldArray['code']))) { + return; + } + + if (self::HOTEL_TABLE === $table) { + $ownHotelUids = [(int)$id]; + } elseif (self::ALIAS_TABLE === $table && 'hotel' === ($fieldArray['entity_type'] ?? $dataHandler->recordInfo($table, (int)$id)['entity_type'] ?? 'hotel')) { + // A new alias gets its hotel only after this hook; every hotel saved with it may own the code + $ownHotelUids = array_map(intval(...), array_keys($dataHandler->datamap[self::HOTEL_TABLE] ?? [])); + $entity = $fieldArray['entity'] ?? (is_numeric($id) ? ($dataHandler->recordInfo($table, (int)$id)['entity'] ?? 0) : 0); + $ownHotelUids[] = (int)$entity; + } else { + return; + } + + $otherHotelUids = array_diff($this->hotelCodeResolver->findHotelUids((string)$fieldArray['code']), $ownHotelUids); + if ([] === $otherHotelUids) { + return; + } + + $otherHotelUid = (int)reset($otherHotelUids); + $otherHotel = $dataHandler->recordInfo(self::HOTEL_TABLE, $otherHotelUid) ?? []; + $dataHandler->log( + $table, + is_numeric($id) ? (int)$id : 0, + DatabaseAction::UPDATE, + null, + SystemLogErrorClassification::USER_ERROR, + sprintf( + 'Der Code "%s" wurde nicht gespeichert: er ist schon Import-Code von "%s" [%d]. Jeder BusPro-Code darf nur an einem Datensatz stehen; für den Kalender gibt es den Kalender-Code.', + trim((string)$fieldArray['code']), + trim((string)preg_replace('/\s+/', ' ', (string)($otherHotel['name'] ?? ''))), + $otherHotelUid + ) + ); + unset($fieldArray['code']); + } +} diff --git a/packages/ep_products/Classes/Middleware/ApiMiddleware.php b/packages/ep_products/Classes/Middleware/ApiMiddleware.php index aa8453f..69ffd91 100644 --- a/packages/ep_products/Classes/Middleware/ApiMiddleware.php +++ b/packages/ep_products/Classes/Middleware/ApiMiddleware.php @@ -7,6 +7,7 @@ use TYPO3\CMS\Core\Database\Connection; use EP\EpProducts\ContentFeed\ContentFeedApi; use EP\EpProducts\Http\ApiKeyAuthenticator; use EP\EpProducts\JsonLd\JsonLdApi; +use EP\EpProducts\Service\HotelCodeResolver; use EP\EpProducts\Service\MyEpImageService; use EP\EpProducts\Utility\HotelIconUtility; use Psr\Http\Message\ResponseInterface; @@ -30,6 +31,7 @@ class ApiMiddleware implements MiddlewareInterface private readonly ContentFeedApi $contentFeedApi, private readonly ApiKeyAuthenticator $authenticator, private readonly JsonLdApi $jsonLdApi, + private readonly HotelCodeResolver $hotelCodeResolver, ) { } @@ -100,17 +102,84 @@ class ApiMiddleware implements MiddlewareInterface return new JsonResponse(['message' => 'Product not found'], 404); } - if (null !== $hotelCode) { - $data['hotel'] = $this->fetchHotelData($hotelCode); + $productUid = $data['productUid']; + $showCalendar = $data['showCalendar']; + unset($data['productUid'], $data['showCalendar']); + + // Without a hotel code (MyE&P's group houses), the product's only Unterkunft is its hotel + if (null === $hotelCode) { + $hotelUids = $this->fetchVisibleHotelUids($productUid); + if (1 !== count($hotelUids)) { + return new JsonResponse([ + 'message' => sprintf('Product %s links %d hotels, expected exactly 1', $productCode, count($hotelUids)), + 'hotel_count' => count($hotelUids), + ], 422); + } + $hotelUid = $hotelUids[0]; + } else { + $hotelUid = $this->hotelCodeResolver->findUid($hotelCode); + } + + $calendarCode = $showCalendar && null !== $hotelUid ? $this->fetchCalendarCode($hotelUid) : ''; + $data['product']['calendar_hotel_code'] = '' !== $calendarCode ? $calendarCode : null; + + if (null !== $hotelUid) { + $data['hotel'] = $this->fetchHotelDataByUid($hotelUid); + } elseif (null !== $hotelCode) { + $data['hotel'] = []; } return new JsonResponse($data); } /** - * The calendar hotels of all visible products, for the contingent sync of MyE&P: their - * availability is needed for the iCal feed and the availability calendar, whether or not - * MyE&P has an accommodation with prices for them. + * Uids from the MM table, then selected from the hotel table, so its restrictions apply + * + * @return list + */ + private function fetchVisibleHotelUids(int $productUid): array + { + $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class); + + $queryBuilder = $connectionPool->getQueryBuilderForTable('tx_epproducts_product_hotel_mm'); + $linkedUids = $queryBuilder + ->select('uid_foreign') + ->from('tx_epproducts_product_hotel_mm') + ->where($queryBuilder->expr()->eq('uid_local', $queryBuilder->createNamedParameter($productUid, Connection::PARAM_INT))) + ->executeQuery() + ->fetchFirstColumn(); + + if ([] === $linkedUids) { + return []; + } + + $queryBuilder = $connectionPool->getQueryBuilderForTable('tx_epproducts_domain_model_hotel'); + + return array_map(intval(...), $queryBuilder + ->select('uid') + ->from('tx_epproducts_domain_model_hotel') + ->where($queryBuilder->expr()->in('uid', $queryBuilder->createNamedParameter(array_map(intval(...), $linkedUids), Connection::PARAM_INT_ARRAY))) + ->executeQuery() + ->fetchFirstColumn()); + } + + private function fetchCalendarCode(int $hotelUid): string + { + $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class) + ->getQueryBuilderForTable('tx_epproducts_domain_model_hotel'); + + return trim((string)$queryBuilder + ->select('calendar_code') + ->from('tx_epproducts_domain_model_hotel') + ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($hotelUid, Connection::PARAM_INT))) + ->executeQuery() + ->fetchOne()); + } + + /** + * The Kalender-Codes of all visible hotels, for the contingent sync of MyE&P: their availability + * is needed for the iCal feeds and the calendars, whether or not MyE&P has an accommodation with + * prices for them. Per code the visible products with "Kalender anzeigen" showing a hotel with it. */ private function handleCalendarHotelsRequest(ServerRequestInterface $request): ResponseInterface { @@ -118,31 +187,50 @@ class ApiMiddleware implements MiddlewareInterface return new JsonResponse(['message' => 'Invalid or missing api key'], 403); } - $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class) - ->getQueryBuilderForTable('tx_epproducts_domain_model_product'); + $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class); - $rows = $queryBuilder - ->select('hotel.code', 'hotel.name AS hotelName', 'product.uid', 'product.name', 'product.season') - ->from('tx_epproducts_domain_model_product', 'product') - ->join('product', 'tx_epproducts_domain_model_hotel', 'hotel', 'hotel.uid = product.calendar_hotel') - ->where( - $queryBuilder->expr()->eq('product.sys_language_uid', 0), - $queryBuilder->expr()->neq('hotel.code', $queryBuilder->createNamedParameter('')), - ) - ->orderBy('hotel.code') - ->addOrderBy('product.uid') + $queryBuilder = $connectionPool->getQueryBuilderForTable('tx_epproducts_domain_model_hotel'); + $hotelRows = $queryBuilder + ->select('calendar_code', 'code', 'name') + ->from('tx_epproducts_domain_model_hotel') + ->where($queryBuilder->expr()->neq('calendar_code', $queryBuilder->createNamedParameter(''))) + ->orderBy('uid') ->executeQuery() ->fetchAllAssociative(); $hotels = []; - foreach ($rows as $row) { - $code = trim((string)$row['code']); - $hotels[$code] ??= [ + foreach ($hotelRows as $row) { + $code = trim((string)$row['calendar_code']); + // Named after the record whose import code it is, else the first one + if (isset($hotels[$code]) && $code !== trim((string)$row['code'])) { + continue; + } + $hotels[$code] = [ 'code' => $code, - 'name' => trim((string)preg_replace('/\s+/', ' ', (string)$row['hotelName'])), + 'name' => trim((string)preg_replace('/\s+/', ' ', (string)$row['name'])), 'products' => [], ]; - $hotels[$code]['products'][] = [ + } + ksort($hotels); + + $queryBuilder = $connectionPool->getQueryBuilderForTable('tx_epproducts_domain_model_product'); + $productRows = $queryBuilder + ->select('hotel.calendar_code', 'product.uid', 'product.name', 'product.season') + ->from('tx_epproducts_domain_model_product', 'product') + ->join('product', 'tx_epproducts_product_hotel_mm', 'mm', 'mm.uid_local = product.uid') + ->join('mm', 'tx_epproducts_domain_model_hotel', 'hotel', 'hotel.uid = mm.uid_foreign') + ->where( + $queryBuilder->expr()->eq('product.sys_language_uid', 0), + $queryBuilder->expr()->eq('product.show_calendar', 1), + $queryBuilder->expr()->neq('hotel.calendar_code', $queryBuilder->createNamedParameter('')), + ) + ->groupBy('hotel.calendar_code', 'product.uid', 'product.name', 'product.season') + ->orderBy('product.uid') + ->executeQuery() + ->fetchAllAssociative(); + + foreach ($productRows as $row) { + $hotels[trim((string)$row['calendar_code'])]['products'][] = [ 'uid' => (int)$row['uid'], 'name' => trim((string)preg_replace('/\s+/', ' ', (string)$row['name'])), 'season' => '' !== (string)$row['season'] ? (string)$row['season'] : null, @@ -163,13 +251,19 @@ class ApiMiddleware implements MiddlewareInterface 'product.name as productName', 'product.code as productCode', 'product.region as regionUid', + 'product.board_description as boardDescription', + 'product.additional_services as additionalServices', + 'product.show_calendar as showCalendar', 'country.name as countryName', 'city.name as cityName', ) ->from('tx_epproducts_domain_model_product', 'product') ->leftJoin('product', 'tx_epproducts_domain_model_country', 'country', 'product.country = country.uid') ->leftJoin('product', 'tx_epproducts_domain_model_city', 'city', 'product.city = city.uid') - ->where($queryBuilder->expr()->eq('product.code', $queryBuilder->createNamedParameter($productCode))) + ->where( + $queryBuilder->expr()->eq('product.code', $queryBuilder->createNamedParameter($productCode)), + $queryBuilder->expr()->in('product.sys_language_uid', [0, -1]), + ) ->orderBy('product.uid') ->setMaxResults(1)->executeQuery() ->fetchAssociative() @@ -182,10 +276,14 @@ class ApiMiddleware implements MiddlewareInterface $images = $this->serializeImages($this->productImageService->getImages((int) $data['productUid'])); return [ + 'productUid' => (int) $data['productUid'], + 'showCalendar' => (bool) $data['showCalendar'], 'product' => [ 'name' => $data['productName'], 'code' => $data['productCode'], 'images' => $images, + 'board_description' => (string) $data['boardDescription'], + 'additional_services' => (string) $data['additionalServices'], ], 'country' => [ 'name' => $data['countryName'], @@ -198,6 +296,13 @@ class ApiMiddleware implements MiddlewareInterface } private function fetchHotelData(string $hotelCode): array + { + $hotelUid = $this->hotelCodeResolver->findUid($hotelCode); + + return null !== $hotelUid ? $this->fetchHotelDataByUid($hotelUid) : []; + } + + private function fetchHotelDataByUid(int $hotelUid): array { $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class) ->getQueryBuilderForTable('tx_epproducts_domain_model_hotel'); @@ -225,10 +330,8 @@ class ApiMiddleware implements MiddlewareInterface 'hotel.region', ) ->from('tx_epproducts_domain_model_hotel', 'hotel') - ->leftJoin('hotel', 'tx_epproducts_domain_model_matchcode', 'alias', 'hotel.uid = alias.entity AND alias.entity_type="hotel"') - ->where( - $queryBuilder->expr()->or($queryBuilder->expr()->eq('hotel.code', $queryBuilder->createNamedParameter($hotelCode)), $queryBuilder->expr()->eq('alias.code', $queryBuilder->createNamedParameter($hotelCode))) - )->setMaxResults(1)->executeQuery() + ->where($queryBuilder->expr()->eq('hotel.uid', $queryBuilder->createNamedParameter($hotelUid, Connection::PARAM_INT))) + ->executeQuery() ->fetchAssociative() ; diff --git a/packages/ep_products/Classes/Service/CalendarCodeMigration.php b/packages/ep_products/Classes/Service/CalendarCodeMigration.php new file mode 100644 index 0000000..2319061 --- /dev/null +++ b/packages/ep_products/Classes/Service/CalendarCodeMigration.php @@ -0,0 +1,274 @@ +getLegacyCalendarCodes() as $productUid => $code) { + if (!($this->getProducts()[$productUid]['show_calendar'] ?? false)) { + return true; + } + } + + return false; + } + + /** + * Additive: sets show_calendar and fills empty Kalender-Codes, never clears or overwrites one + * + * @return list what the fill could not decide + */ + public function fill(): array + { + $legacyCodes = $this->getLegacyCalendarCodes(); + $hotels = $this->getVisibleHotels(); + $pinnedHotels = $this->getPinnedHotels(); + $accommodations = $this->getVisibleAccommodations(); + $notes = []; + + // Today's behaviour: a calendar where the calendar hotel is visible and has a code + foreach (array_keys($legacyCodes) as $productUid) { + $this->connectionPool->getConnectionForTable(self::PRODUCT_TABLE) + ->update(self::PRODUCT_TABLE, ['show_calendar' => 1], ['uid' => $productUid]); + } + + // Who gets which code, by priority: 0 a calendar hotel its own code, 1 the hotel a product page + // shows (pinned in the Produktdetail element, else the single Unterkunft), 2 the other + // Unterkünfte, only when they have no code of their own (another house's record keeps none) + $candidates = []; + foreach ($legacyCodes as $productUid => $code) { + $candidates[$this->getProducts()[$productUid]['calendar_hotel']][0][$code][] = 0; + $productAccommodations = $accommodations[$productUid] ?? []; + $shownHotelUids = $pinnedHotels[$productUid] ?? (1 === count($productAccommodations) ? $productAccommodations : []); + foreach ($shownHotelUids as $hotelUid) { + $candidates[$hotelUid][1][$code][] = $productUid; + } + foreach (array_diff($productAccommodations, $shownHotelUids) as $hotelUid) { + if ('' === ($hotels[$hotelUid]['code'] ?? '')) { + $candidates[$hotelUid][2][$code][] = $productUid; + } + } + } + + // Within a priority, the most frequent code wins, then the one of the lowest product uid + $hotelConnection = $this->connectionPool->getConnectionForTable(self::HOTEL_TABLE); + foreach ($candidates as $hotelUid => $codesByPriority) { + if (!isset($hotels[$hotelUid]) || '' !== $hotels[$hotelUid]['calendar_code']) { + continue; + } + ksort($codesByPriority); + $codes = reset($codesByPriority); + uasort($codes, static fn(array $a, array $b): int => count($b) <=> count($a) ?: min($a) <=> min($b)); + $chosen = (string)array_key_first($codes); + $others = array_diff_key($codes, [$chosen => true]); + if ([] !== $others) { + $notes[] = sprintf( + 'Hotel %d (%s) got %s; also wanted: %s', + $hotelUid, + $hotels[$hotelUid]['name'], + $chosen, + implode(', ', array_map( + static fn(string $code, array $productUids): string => sprintf('%s by products %s', $code, implode(', ', $productUids)), + array_keys($others), + $others + )) + ); + } + $hotelConnection->update(self::HOTEL_TABLE, ['calendar_code' => $chosen], ['uid' => $hotelUid]); + } + + return $notes; + } + + /** + * Product pages whose calendar differs between calendar_hotel and the Kalender-Code model, as long + * as calendar_hotel is still filled + * + * @return list + */ + public function findDifferences(): array + { + $legacyCodes = $this->getLegacyCalendarCodes(); + $hotels = $this->getVisibleHotels(); + $pinnedHotels = $this->getPinnedHotels(); + $accommodations = $this->getVisibleAccommodations(); + + $differences = []; + foreach ($this->getProducts() as $productUid => $product) { + if ($product['hidden']) { + continue; + } + $shownHotelUids = array_unique(array_merge($pinnedHotels[$productUid] ?? [], $accommodations[$productUid] ?? [])); + $before = $legacyCodes[$productUid] ?? ''; + if ([] === $shownHotelUids && '' !== $before) { + $differences[] = ['product' => $productUid, 'name' => $product['name'], 'season' => $product['season'], 'hotel' => 0, 'hotelName' => '(keine sichtbare Unterkunft)', 'before' => $before, 'after' => '']; + } + foreach ($shownHotelUids as $hotelUid) { + $after = $product['show_calendar'] ? ($hotels[$hotelUid]['calendar_code'] ?? '') : ''; + if ($before !== $after) { + $differences[] = ['product' => $productUid, 'name' => $product['name'], 'season' => $product['season'], 'hotel' => $hotelUid, 'hotelName' => $hotels[$hotelUid]['name'] ?? '', 'before' => $before, 'after' => $after]; + } + } + } + + return $differences; + } + + /** + * @return array product uid => code of its calendar hotel, where that hotel is visible and has a code + */ + private function getLegacyCalendarCodes(): array + { + $hotels = $this->getVisibleHotels(); + $codes = []; + foreach ($this->getProducts() as $productUid => $product) { + $code = $hotels[$product['calendar_hotel']]['code'] ?? ''; + if ('' !== $code) { + $codes[$productUid] = $code; + } + } + + return $codes; + } + + /** + * Hidden products too: their calendar is there when they are shown again + * + * @return array + */ + private function getProducts(): array + { + if (null !== $this->products) { + return $this->products; + } + + $queryBuilder = $this->connectionPool->getQueryBuilderForTable(self::PRODUCT_TABLE); + $queryBuilder->getRestrictions()->removeByType(HiddenRestriction::class); + $rows = $queryBuilder + ->select('uid', 'name', 'season', 'hidden', 'calendar_hotel', 'show_calendar') + ->from(self::PRODUCT_TABLE) + ->where($queryBuilder->expr()->eq('sys_language_uid', 0)) + ->orderBy('uid') + ->executeQuery() + ->fetchAllAssociative(); + + $this->products = []; + foreach ($rows as $row) { + $this->products[(int)$row['uid']] = [ + 'name' => trim((string)preg_replace('/\s+/', ' ', (string)$row['name'])), + 'season' => (string)$row['season'], + 'hidden' => (bool)$row['hidden'], + 'calendar_hotel' => (int)$row['calendar_hotel'], + 'show_calendar' => (bool)$row['show_calendar'], + ]; + } + + return $this->products; + } + + /** + * @return array + */ + private function getVisibleHotels(): array + { + $queryBuilder = $this->connectionPool->getQueryBuilderForTable(self::HOTEL_TABLE); + $rows = $queryBuilder + ->select('uid', 'name', 'code', 'calendar_code') + ->from(self::HOTEL_TABLE) + ->executeQuery() + ->fetchAllAssociative(); + + $hotels = []; + foreach ($rows as $row) { + $hotels[(int)$row['uid']] = [ + 'name' => trim((string)preg_replace('/\s+/', ' ', (string)$row['name'])), + 'code' => strtoupper(trim((string)$row['code'])), + 'calendar_code' => trim((string)$row['calendar_code']), + ]; + } + + return $hotels; + } + + /** + * @return array> product uid => its visible Unterkünfte + */ + private function getVisibleAccommodations(): array + { + $queryBuilder = $this->connectionPool->getQueryBuilderForTable(self::HOTEL_TABLE); + $rows = $queryBuilder + ->select('mm.uid_local', 'mm.uid_foreign') + ->from(self::HOTEL_TABLE, 'hotel') + ->join('hotel', 'tx_epproducts_product_hotel_mm', 'mm', 'mm.uid_foreign = hotel.uid') + ->orderBy('mm.uid_local') + ->addOrderBy('mm.sorting') + ->executeQuery() + ->fetchAllAssociative(); + + $accommodations = []; + foreach ($rows as $row) { + $accommodations[(int)$row['uid_local']][] = (int)$row['uid_foreign']; + } + + return $accommodations; + } + + /** + * A hidden pinned hotel is left out: the page falls back to the Unterkünfte + * + * @return array> product uid => visible hotels pinned in visible Produktdetail elements + */ + private function getPinnedHotels(): array + { + $hotels = $this->getVisibleHotels(); + $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content'); + $rows = $queryBuilder + ->select('content.pi_flexform') + ->from('tt_content', 'content') + ->join('content', 'pages', 'page', 'page.uid = content.pid') + ->where($queryBuilder->expr()->eq('content.CType', $queryBuilder->createNamedParameter('epproducts_product_detail', Connection::PARAM_STR))) + ->executeQuery() + ->fetchAllAssociative(); + + $pinned = []; + foreach ($rows as $row) { + $flexform = GeneralUtility::xml2array((string)$row['pi_flexform']); + $fields = is_array($flexform) ? ($flexform['data']['sDEF']['lDEF'] ?? []) : []; + $productUid = (int)($fields['settings.productUid']['vDEF'] ?? 0); + $hotelUid = (int)($fields['settings.hotelUid']['vDEF'] ?? 0); + if (0 < $productUid && isset($hotels[$hotelUid]) && !in_array($hotelUid, $pinned[$productUid] ?? [], true)) { + $pinned[$productUid][] = $hotelUid; + } + } + + return $pinned; + } +} diff --git a/packages/ep_products/Classes/Service/DateImportService.php b/packages/ep_products/Classes/Service/DateImportService.php index 496c3c5..4e4d47e 100644 --- a/packages/ep_products/Classes/Service/DateImportService.php +++ b/packages/ep_products/Classes/Service/DateImportService.php @@ -72,7 +72,8 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface ExtensionConfiguration $extensionConfiguration, private CacheService $cacheService, private ProductImportSource $importSource, - private RoomTypeResolver $roomTypeResolver + private RoomTypeResolver $roomTypeResolver, + private HotelCodeResolver $hotelCodeResolver ) { // Extension configuration rather than TypoScript: the import runs on the CLI, where // TYPO3 13 has no frontend TypoScript (plugin.tx_epproducts.persistence.storagePid) @@ -426,13 +427,14 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface $code = $row['hotel']['code']; $busProId = (int) $row['hotel']['busProId']; - if (!array_key_exists((string) $code, $this->hotelMappings)) { + $hotelUid = $this->hotelCodeResolver->findUid((string) $code); + if (null === $hotelUid || !isset($this->hotelMappings[$hotelUid])) { $this->logger->warning('hotel not found', ['code' => $code]); return false; } - $hotel = $this->hotelMappings[$code]; + $hotel = ['code' => $code] + $this->hotelMappings[$hotelUid]; $hotel['fact'] = $this->getTopFactForRecord('tx_epproducts_hotel_fact_mm', $hotel['uid']); $services = []; @@ -751,31 +753,23 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface return (float) str_replace(['.', ','], ['', '.'], $price); } + /** + * The visible hotel records by uid; which record a code belongs to says HotelCodeResolver + */ private function getHotelMappings(): void { $sql = ' - SELECT u.code code, u.uid uid, h.name name, h.type type, + SELECT h.uid uid, h.name name, h.type type, h.earlybird earlybird, h.new new, h.low_contingent low_contingent, h.keywords keywords, h.header_title header_title, h.category category, h.teaser teaser, h.detail_page detail_page - FROM ( - SELECT hotel.code code, hotel.uid uid - FROM tx_epproducts_domain_model_hotel hotel - WHERE hotel.code != "" AND hotel.deleted = 0 AND hotel.hidden = 0 - UNION SELECT matchcode.code code, matchcode.entity uid - FROM tx_epproducts_domain_model_matchcode matchcode - INNER JOIN tx_epproducts_domain_model_hotel matchcode_hotel ON matchcode.entity = matchcode_hotel.uid - WHERE matchcode.deleted = 0 AND matchcode.hidden = 0 - AND matchcode_hotel.deleted = 0 AND matchcode_hotel.hidden = 0 - ORDER BY code - ) u - LEFT JOIN tx_epproducts_domain_model_hotel h ON u.uid = h.uid + FROM tx_epproducts_domain_model_hotel h + WHERE h.deleted = 0 AND h.hidden = 0 '; $rows = $this->db->fetchAllAssociative($sql); foreach ($rows as $row) { - $this->hotelMappings[$row['code']] = [ + $this->hotelMappings[(int) $row['uid']] = [ 'uid' => $row['uid'], - 'code' => $row['code'], 'type' => $row['type'], 'name' => $row['name'], 'earlybird' => $row['earlybird'], diff --git a/packages/ep_products/Classes/Service/HotelCodeResolver.php b/packages/ep_products/Classes/Service/HotelCodeResolver.php new file mode 100644 index 0000000..5be397a --- /dev/null +++ b/packages/ep_products/Classes/Service/HotelCodeResolver.php @@ -0,0 +1,110 @@ +|null + */ + private ?array $map = null; + + public function __construct( + private readonly ConnectionPool $connectionPool, + ) { + } + + public function findUid(string $code): ?int + { + return $this->map()[strtoupper(trim($code))] ?? null; + } + + /** + * Read fresh, not from the map: for the check on save + * + * @return list the visible hotel records that have this import code + */ + public function findHotelUids(string $code): array + { + $code = strtoupper(trim($code)); + $uids = []; + foreach ($this->findImportCodes() as $row) { + if ($code === strtoupper(trim((string)$row['code']))) { + $uids[] = (int)$row['uid']; + } + } + + return array_values(array_unique($uids)); + } + + /** + * @return array import code (upper case) => hotel uid + */ + public function map(): array + { + if (null !== $this->map) { + return $this->map; + } + + $owners = []; + foreach ($this->findImportCodes() as $row) { + $owners[strtoupper(trim((string)$row['code']))][(int)$row['uid']] ??= (bool)$row['own']; + } + + $this->map = []; + foreach ($owners as $code => $hotels) { + uksort($hotels, static fn(int $a, int $b): int => $hotels[$b] <=> $hotels[$a] ?: $a <=> $b); + $this->map[$code] = (int)array_key_first($hotels); + if (1 < count($hotels)) { + $this->logger?->warning(sprintf('Import code %s is on several hotel records (%s), using %d', $code, implode(', ', array_keys($hotels)), $this->map[$code])); + } + } + + return $this->map; + } + + /** + * @return list + */ + private function findImportCodes(): array + { + $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tx_epproducts_domain_model_hotel'); + $codes = $queryBuilder + ->select('code', 'uid') + ->addSelectLiteral('1 AS own') + ->from('tx_epproducts_domain_model_hotel') + ->where($queryBuilder->expr()->neq('code', $queryBuilder->createNamedParameter(''))) + ->executeQuery() + ->fetchAllAssociative(); + + $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tx_epproducts_domain_model_matchcode'); + $aliases = $queryBuilder + ->select('alias.code', 'hotel.uid') + ->addSelectLiteral('0 AS own') + ->from('tx_epproducts_domain_model_matchcode', 'alias') + ->join('alias', 'tx_epproducts_domain_model_hotel', 'hotel', 'hotel.uid = alias.entity') + ->where( + $queryBuilder->expr()->eq('alias.entity_type', $queryBuilder->createNamedParameter('hotel')), + $queryBuilder->expr()->neq('alias.code', $queryBuilder->createNamedParameter('')), + ) + ->executeQuery() + ->fetchAllAssociative(); + + return array_merge($codes, $aliases); + } +} diff --git a/packages/ep_products/Classes/Service/IcalService.php b/packages/ep_products/Classes/Service/IcalService.php index cafbef8..eb0a23c 100644 --- a/packages/ep_products/Classes/Service/IcalService.php +++ b/packages/ep_products/Classes/Service/IcalService.php @@ -10,7 +10,7 @@ use Psr\Log\LoggerAwareInterface; use Psr\Log\LoggerAwareTrait; /** - * Contingent feed of a hotel for the booking portals + * Contingent feed of a hotel for the booking portals, for its Kalender-Code * * The availability comes from MyE&P (contingents/availability, the bpn-connect snapshot without the * price rule of contingents/calendar). Like the sidebar calendar, it has three levels: every run of @@ -36,16 +36,13 @@ class IcalService implements LoggerAwareInterface */ public function createContingentsFeed(Hotel $hotel): ?string { - $calendarRows = []; - $hotelCode = trim((string)$hotel->getCode()); + $hotelCode = trim($hotel->getCalendarCode()); - if ('' !== $hotelCode) { - try { - $calendarRows = $this->apiClient->getContingentAvailability($hotelCode); - } catch (ApiException $e) { - $this->logger?->error(sprintf('iCal: no availability for hotel %s', $hotelCode), ['exception' => $e]); - return null; - } + try { + $calendarRows = $this->apiClient->getContingentAvailability($hotelCode); + } catch (ApiException $e) { + $this->logger?->error(sprintf('iCal: no availability for hotel %s', $hotelCode), ['exception' => $e]); + return null; } $vcalendar = Vcalendar::factory([Vcalendar::UNIQUE_ID => 'www.ep-reisen.de']); diff --git a/packages/ep_products/Classes/Upgrades/CalendarCodeUpdate.php b/packages/ep_products/Classes/Upgrades/CalendarCodeUpdate.php new file mode 100644 index 0000000..f46859e --- /dev/null +++ b/packages/ep_products/Classes/Upgrades/CalendarCodeUpdate.php @@ -0,0 +1,62 @@ +output = $output; + } + + public function getTitle(): string + { + return 'E&P Produkte: Kalender-Codes aus den Kalender-Unterkünften'; + } + + public function getDescription(): string + { + return 'Sets "Kalender anzeigen" on products with a calendar hotel and fills the Kalender-Code of the hotels their pages show. Check the result with ep:calendar-codes.'; + } + + public function updateNecessary(): bool + { + return $this->calendarCodeMigration->isFillNecessary(); + } + + public function executeUpdate(): bool + { + foreach ($this->calendarCodeMigration->fill() as $note) { + $this->output?->writeln($note); + } + + return true; + } + + public function getPrerequisites(): array + { + return [DatabaseUpdatedPrerequisite::class]; + } +} diff --git a/packages/ep_products/Configuration/Services.yaml b/packages/ep_products/Configuration/Services.yaml index 7330ad4..e1880ac 100644 --- a/packages/ep_products/Configuration/Services.yaml +++ b/packages/ep_products/Configuration/Services.yaml @@ -30,6 +30,8 @@ services: public: true EP\EpProducts\Service\SearchResultService: public: true + EP\EpProducts\Hooks\ImportCodeCheck: + public: true cache.ep_cache: class: TYPO3\CMS\Core\Cache\Frontend\FrontendInterface diff --git a/packages/ep_products/Configuration/TCA/tx_epproducts_domain_model_hotel.php b/packages/ep_products/Configuration/TCA/tx_epproducts_domain_model_hotel.php index faee0d8..131f531 100644 --- a/packages/ep_products/Configuration/TCA/tx_epproducts_domain_model_hotel.php +++ b/packages/ep_products/Configuration/TCA/tx_epproducts_domain_model_hotel.php @@ -27,7 +27,7 @@ return [ 'endtime' => 'endtime', ], 'searchFields' => 'name,headline,teaser,description,features,room_types,additional_information,teaser_images, - header_images,images,reseller_images,code,type,category,country,region,city,teamer,products,external_link', + header_images,images,reseller_images,code,calendar_code,type,category,country,region,city,teamer,products,external_link', 'iconfile' => 'EXT:ep_theme/Resources/Public/images/icon_ce.svg', ], 'types' => [ @@ -43,7 +43,7 @@ return [ ], 'palettes' => [ 'top' => ['showitem' => 'hidden,earlybird,new,--linebreak--,low_contingent,show_as_teaser, - --linebreak--,code,detail_page,--linebreak--,external_link,path_segment'], + --linebreak--,code,calendar_code,--linebreak--,detail_page,--linebreak--,external_link,path_segment'], 'geolocation' => ['showitem' => 'address, longitude, latitude'], 'destinations' => ['showitem' => 'country,region,city'], 'name' => ['showitem' => 'name,short_name,--linebreak--,header_title,header_subtitle,--linebreak--,headline'], @@ -425,13 +425,25 @@ return [ ], 'code' => [ 'exclude' => 0, - 'label' => 'Code', + 'label' => 'Import-Code', + 'description' => 'BusPro-Code, dessen Termine diesem Datensatz zugeordnet werden. Jeder Code darf nur an einem Datensatz stehen. Für den Kalender ohne Bedeutung.', 'config' => [ 'type' => 'input', 'size' => 30, 'eval' => 'trim' ], ], + 'calendar_code' => [ + 'exclude' => 0, + 'label' => 'Kalender-Code', + 'description' => 'BusPro-Code des Hauses, dessen Belegung Belegungskalender, Preiskalender, Preistabelle und iCal-Feed zeigen. Leer = kein Kalender.', + 'config' => [ + 'type' => 'input', + 'size' => 16, + 'max' => 16, + 'eval' => 'trim,upper', + ], + ], 'external_link' => [ 'exclude' => 0, 'label' => 'Externer Link (Google MyBusiness)', @@ -569,7 +581,8 @@ return [ ], 'additional_codes' => [ 'exclude' => 0, - 'label' => 'Zusätzliche Codes', + 'label' => 'Weitere Import-Codes', + 'description' => 'BusPro-Codes, deren Termine diesem Datensatz zugeordnet werden. Jeder Code darf nur an einem Datensatz stehen. Für den Kalender ohne Bedeutung.', 'config' => [ 'type' => 'inline', 'foreign_table' => 'tx_epproducts_domain_model_matchcode', diff --git a/packages/ep_products/Configuration/TCA/tx_epproducts_domain_model_product.php b/packages/ep_products/Configuration/TCA/tx_epproducts_domain_model_product.php index b0cb13b..764e267 100644 --- a/packages/ep_products/Configuration/TCA/tx_epproducts_domain_model_product.php +++ b/packages/ep_products/Configuration/TCA/tx_epproducts_domain_model_product.php @@ -55,7 +55,7 @@ return [ 'alternative' => ['showitem' => 'alt_product, alt_label'], 'header' => ['showitem' => 'headline, subline, --linebreak--, header_title, header_subtitle'], 'rating' => ['showitem' => 'rating_average, rating_votes_count'], - 'records' => ['showitem' => 'journey, concept, calendar_hotel, --linebreak--, officetip, badge'], + 'records' => ['showitem' => 'journey, concept, show_calendar, --linebreak--, officetip, badge'], 'misc' => ['showitem' => 'feature,keywords'], ], 'columns' => [ @@ -735,9 +735,17 @@ return [ 'multiple' => 0, ], ], + 'show_calendar' => [ + 'exclude' => 0, + 'label' => 'Kalender anzeigen', + 'description' => 'Zeigt den Kalender der Unterkunft, die auf der Produktseite angezeigt wird (deren Kalender-Code)', + 'config' => [ + 'type' => 'check', + ], + ], 'calendar_hotel' => [ 'exclude' => 0, - 'label' => 'Unterkunft für Belegungskalender', + 'label' => 'Unterkunft für Belegungskalender (alt, nicht mehr verwendet)', 'config' => [ 'type' => 'select', 'default' => 0, diff --git a/packages/ep_products/ext_localconf.php b/packages/ep_products/ext_localconf.php index c0ee5d1..3d60774 100644 --- a/packages/ep_products/ext_localconf.php +++ b/packages/ep_products/ext_localconf.php @@ -26,6 +26,7 @@ use EP\EpProducts\Controller\AjaxWatchlistController; use EP\EpProducts\Controller\AjaxCalendarController; use EP\EpProducts\Controller\AjaxTeaserPopupController; use EP\EpProducts\Routing\Aspect\PassthroughMapper; +use EP\EpProducts\Hooks\ImportCodeCheck; use TYPO3\CMS\Core\Log\LogLevel; use EP\EpProducts\Log\Writer; @@ -45,6 +46,8 @@ $boot = function (): void { // Client-side callers pass these parameters in POST bodies, which cHash never inspects. $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['requireCacheHashPresenceParameters'][] = '^tx_epproducts_ajax'; + $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass']['ep_products_import_code'] = ImportCodeCheck::class; + $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][TableGarbageCollectionTask::class]['options']['tables']['tx_epproducts_log'] = [ 'dateField' => 'time_micro', 'expirePeriod' => 180, diff --git a/packages/ep_products/ext_tables.sql b/packages/ep_products/ext_tables.sql index 426ae2f..cde0cfa 100644 --- a/packages/ep_products/ext_tables.sql +++ b/packages/ep_products/ext_tables.sql @@ -56,6 +56,7 @@ CREATE TABLE tx_epproducts_domain_model_product dates int(11) unsigned DEFAULT '0' NOT NULL, hotels int(11) unsigned DEFAULT '0' NOT NULL, calendar_hotel int(11) unsigned DEFAULT '0' NOT NULL, + show_calendar tinyint(4) unsigned DEFAULT '0' NOT NULL, faqs int(11) unsigned DEFAULT '0' NOT NULL, officetip int(11) unsigned DEFAULT '0' NOT NULL, alt_product int(11) unsigned DEFAULT '0' NOT NULL, @@ -238,6 +239,7 @@ CREATE TABLE tx_epproducts_domain_model_hotel images int(11) unsigned NOT NULL default '0', reseller_images int(11) unsigned NOT NULL default '0', code varchar(255) DEFAULT '' NOT NULL, + calendar_code varchar(16) DEFAULT '' NOT NULL, external_link varchar(255) DEFAULT '' NOT NULL, path_segment varchar(255) DEFAULT '' NOT NULL, type varchar(255) DEFAULT '' NOT NULL, diff --git a/packages/ep_theme/Resources/Private/Partials/Product/PriceCalendar.html b/packages/ep_theme/Resources/Private/Partials/Product/PriceCalendar.html index d9add91..237b02b 100644 --- a/packages/ep_theme/Resources/Private/Partials/Product/PriceCalendar.html +++ b/packages/ep_theme/Resources/Private/Partials/Product/PriceCalendar.html @@ -4,18 +4,18 @@ xmlns:ep="http://typo3.org/ns/EP/EpTheme/ViewHelpers">
+ id="pc-loading-{calendarHotel.uid}"> Preiskalender wird geladen …
+ hx-indicator="#pc-loading-{calendarHotel.uid}">
diff --git a/packages/ep_theme/Resources/Private/Templates/Product/Detail.html b/packages/ep_theme/Resources/Private/Templates/Product/Detail.html index b2138a4..05e7b5c 100644 --- a/packages/ep_theme/Resources/Private/Templates/Product/Detail.html +++ b/packages/ep_theme/Resources/Private/Templates/Product/Detail.html @@ -76,15 +76,15 @@
- + - + - + @@ -171,7 +171,7 @@ - + @@ -360,7 +360,7 @@ paint that compete with the price calendar for PHP workers. The tables sit below the fold, so fetch them when they actually come into view. --> -
@@ -371,7 +371,7 @@ Belegungskalender -