Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0fc0addf47 | |||
| 3225ff1e10 | |||
| 7d7f748f7a | |||
| f4d3972d07 |
+4
-1
@@ -1,4 +1,7 @@
|
||||
{
|
||||
"$schema": "/phpactor.schema.json",
|
||||
"language_server_psalm.enabled": true
|
||||
"language_server_psalm.enabled": true,
|
||||
"indexer.stub_paths": [
|
||||
"%project_root%/vendor/php-stubs/wordpress-stubs"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
# Forms
|
||||
|
||||
The reservation is mostly created by filling in a form. For that reason this plugin has it's own _form definition_ feature.
|
||||
|
||||
The form definition is an array of element it contains. Each element has a *type*, for example: `input-text`, `input-reservation`, etc.
|
||||
|
||||
Keep the form structure and content separate -> when working with the form, take time to figure, if you are working with structure, or existence of something within.
|
||||
|
||||
## Submitting
|
||||
|
||||
When user submits the form, the `RsvFormSubmitter.js` is called. It collects the values, which we describe in more detail, and then sends it using `fetch` as POST to `reservations/forms/{form_id}`.
|
||||
|
||||
### Collecting
|
||||
|
||||
The *collecting* is a process with `<form>` DOM subtree as an _input_ and valid input JSON for the defined form at `form_id` as _output_.
|
||||
|
||||
We decided to only consider *linearized* form, therefore an single-dimension array of fields. We find little to no value to define JSON structure in the form itself, but rather define linear array of inputs, where each input value is a JSON itself. We explaing why that is beneficial.
|
||||
|
||||
1. Even atomic values like `"hello"` or `69` are valid JSON format. This means the collector can assume every value is a JSON and use `JSON.parse(input.value)`.
|
||||
2. We can change the form structure, but the output remains the same. The use-case is for example, grouping fields for First and Last name into one row, but still keep them separate attributes in final JSON. On the other hand, the country code and telephone number are two fields on the same row, but should be one attribute in the final JSON. Both cases reflect only in the DOM structure.
|
||||
|
||||
### Contract
|
||||
|
||||
For element to be collected, it has to comply to a contract. Namely, it must have a `rsv-form-field` class and have a `value` attribute. The tagging with `rsv-form-field` class allows that by default, no custom defined component is collected. Therefore you can compose new elements from existing ones and only tag the outer-most as `rsv-form-field`. For example:
|
||||
|
||||
```
|
||||
<rsv-reservation-collector class="rsv-form-field">
|
||||
<rsv-calendar/>
|
||||
|
||||
<rsv-time-slot-selector/>
|
||||
</rsv-reservation-collector>
|
||||
```
|
||||
|
||||
If the collector would collect exact elements, like `<input>`, it would:
|
||||
a) require a register
|
||||
b) be unpredictable
|
||||
c) require some form of filtering
|
||||
|
||||
## Element handlers
|
||||
|
||||
Element handler is a PHP class extending `RsvFormElementHandler` class. The parent class has two abstract methods: `draw` & `submit`. The `draw` method is called when the form is being rendered on the backend for the user. The caller is the `RsvFormRenderer` that does not try hard to catch all errors, so be careful with putting logic to `draw`.
|
||||
|
||||
The other method `submit` is called by the `RsvFormProcessor`. It definitely should validate the value, but it can also do other things. For example, the element for reservation saves the reservation to the database.
|
||||
|
||||
You might have noticed in a reservation example one major flaw. What happens, when any of the next elements fail and cause the whole form _unworthy of submission_? The error handling itself and propagating back to the user is described later. For now let's focus on handling the error correctly.
|
||||
|
||||
We thought of two approaches: separate validation & submission steps and rollback. The first approach will not actually solve the issue. It might eliminate some cases, but sometimes error slips through and cause exception in the submission step. For example suppose creating reservation. The validation step can decide it is okay and the time block is available. But right after that another request creates the reservation in the same time block.
|
||||
|
||||
We could either do same validation in the submission step, but then, what is the point of the validation step. Another solution is to create a token for the time block. The second solution requires one important thing, the element must know it is an element, to implement the safety gates correctly.
|
||||
|
||||
The second approach is using a rollback, that does so when any of the next elements fail and cause the whole form _unworthy of submission_. This way only the element handler has to implement the safe gate.
|
||||
|
||||
TODO: generalize it using a property the element submission must have
|
||||
|
||||
## Register
|
||||
|
||||
Register is a string to object mapping, that maps element IDs to instantiated objects of the handlers. This allows to customize the handler by changing it's state. For example, there is a handler for input text. The constructor can have a predicate lambda that does the validation and allow simple implementation of email, telephone number or any other validation. Or it can be wrapped with regular expression.
|
||||
|
||||
## Error handling
|
||||
|
||||
When an error occurs, the backend should send back an error response, so that user knowns what he did wrong. The response should contain element's ID, that detected the issue and error ID. The reason why not use a message is for internationalization. The form processor does not know and must not know the user's culture. The internationalization is a separate concern and should be done mapping error ID to a particular message.
|
||||
|
||||
Last thing inspired by Problem Details RFC are extensions. The response can contain a dictionary mapping strings to strings that contains structured data about the error. For example, only one time slot of multiple can be occupied. The extensions could contain value of the occupied time slot and the response handler could use it to provide a more detailed error message.
|
||||
|
||||
## Success handling
|
||||
|
||||
Even success must be handled. The user must know that the submission is successfully finished. What is shown is a templated HTML code that is defined by user. It can contain custom elements, like `<reservation-summary>`.
|
||||
@@ -0,0 +1,181 @@
|
||||
# Implementation Brief: Live form preview in the form editor
|
||||
|
||||
## Goal
|
||||
Add a real-time form preview pane beside the elements editor on the form **edit** page. Reuse the existing PHP renderer (`RsvFormHtmlRenderer`) via a new admin REST endpoint — do **not** build a JS renderer.
|
||||
|
||||
## Context you need (don't re-derive)
|
||||
- **Editor**: `includes/Views/RsvFormsPage.php`. `show_edit()` renders the edit page; `elements_table_script()` emits the inline `<script>` that drives the elements table. Elements live in an in-memory JS object `rsv_elements_source`; `rsv_elements_source.get_all()` returns the elements array (without internal `id`). Nothing is persisted until the form is saved (PUT).
|
||||
- **Renderer**: `includes/Services/Forms/RsvFormHtmlRenderer.php`. `draw(RsvFormDefinition $form): bool` **echoes** the real `<form>` HTML; returns `false` and echoes nothing when the form has no elements. This is the same renderer the frontend uses (`src/render.php`).
|
||||
- **Definition object**: `new RsvFormDefinition(string $id, array $definition)` where `$definition` has keys `elements` (array), `email_key`, `success_message`.
|
||||
- **Assets**: admin already enqueues the `rsv-client` bundle (`rsv_enqueue_admin_assets` in `includes/RsvAssetsDefinition.php`). It defines the custom elements (`<rsv-reservation-selector>`, `<rsv-reservation-summary>`) and bundles the form CSS (`RsvFormStyles.css` -> confirmed in `build/client.css`). **So form HTML injected via `innerHTML` into the admin page is styled and auto-upgrades its custom elements — no extra assets needed.**
|
||||
- `ReservairServiceAPI.nonce` and `ReservairServiceAPI.restUrl` are available globally in admin (localized onto `rsv-client`).
|
||||
- The registries `$rsv_form_registry` / `$rsv_template_registry` are populated on `plugins_loaded` (`rsv_bootstrap`), which runs for REST requests too.
|
||||
- REST errors are handled globally by the `rest_dispatch_request` filter in `includes/RsvRestApiDefinition.php` (any `Throwable` -> 500 JSON `{error}`), so the endpoint needs no try/catch.
|
||||
- `RsvColumnLayout::split('3:2')->column(fn)->column(fn)->output()` (`modules/Layout/RsvColumnLayout.php`) renders side-by-side columns; each callable just echoes. CSS for `.rsv-cols`/`.rsv-col` already exists (used on the list page).
|
||||
|
||||
## The plan is JS-inline only — no webpack rebuild
|
||||
All new editor JS goes inside the existing inline `<script>` in `elements_table_script()`. Do **not** add CSS to `assets/css/*` (that would require a webpack rebuild); use inline `style=""`/a `<style>` block in the PHP if you want the sticky preview.
|
||||
|
||||
---
|
||||
|
||||
## Task 1 — Preview endpoint
|
||||
**File:** `includes/Controllers/RsvFormDefinitionController.php`
|
||||
|
||||
In `register_routes()`, add a standalone route (the `\d+` id route won't match the non-numeric `preview`, so order is safe):
|
||||
|
||||
```php
|
||||
register_rest_route($this->namespace, '/' . $this->resource_name . '/preview', [
|
||||
'methods' => 'POST',
|
||||
'callback' => [$this, 'preview'],
|
||||
'permission_callback' => [RsvRestPolicy::class, 'admin'],
|
||||
]);
|
||||
```
|
||||
|
||||
Add the method:
|
||||
|
||||
```php
|
||||
/** Renders an unsaved definition to HTML for the editor's live preview. */
|
||||
function preview(WP_REST_Request $request): WP_REST_Response {
|
||||
$definition = $request->get_json_params()['definition'] ?? [];
|
||||
if (!is_array($definition)) {
|
||||
$definition = [];
|
||||
}
|
||||
|
||||
ob_start();
|
||||
(new RsvFormHtmlRenderer())->draw(new RsvFormDefinition('preview', $definition));
|
||||
$html = ob_get_clean();
|
||||
|
||||
return new WP_REST_Response(['html' => $html], 200);
|
||||
}
|
||||
```
|
||||
|
||||
Notes: no-elements case -> `$html` is `''` (handled client-side). A malformed element payload would throw, but the global filter turns it into a 500 the client catch handles gracefully.
|
||||
|
||||
---
|
||||
|
||||
## Task 2 — Editor layout (two columns + preview pane)
|
||||
**File:** `includes/Views/RsvFormsPage.php`, `show_edit()`.
|
||||
|
||||
Replace the current Form Elements block (the `<h2>Form Elements</h2>` heading, `#form_elements_table`, the add button, and the submit button — currently around lines 133–142) with a split layout. **Keep the existing IDs `form_elements_table` and `rsv_add_element_btn`.** `RsvColumnLayout` is already imported at the top of the file.
|
||||
|
||||
```php
|
||||
<hr>
|
||||
<h2>Form Elements</h2>
|
||||
<p>Define the fields that will appear in this form.</p>
|
||||
<?php
|
||||
RsvColumnLayout::split('3:2')
|
||||
->column(function (): void { ?>
|
||||
<div id="form_elements_table"></div>
|
||||
<p>
|
||||
<button type="button" class="button" id="rsv_add_element_btn">+ Add Element</button>
|
||||
</p>
|
||||
<p class="submit">
|
||||
<button type="submit" form="edit_form_definition" class="button button-primary">Update Form Definition</button>
|
||||
</p>
|
||||
<?php })
|
||||
->column(function (): void { ?>
|
||||
<h3>Live preview</h3>
|
||||
<div id="rsv_form_preview" class="rsv-form-preview" style="position: sticky; top: 40px;"></div>
|
||||
<?php })
|
||||
->output();
|
||||
?>
|
||||
```
|
||||
|
||||
The container is `rsv-form-preview` (a plain wrapper) — **not** `reservair-form`; the injected HTML brings its own `<form class="reservair-form ...">`.
|
||||
|
||||
---
|
||||
|
||||
## Task 3 — Editor wiring (inline JS in `elements_table_script()`)
|
||||
|
||||
### 3a. Shared definition collector + preview functions
|
||||
Add at the top level of the script (right after the `rsv_elements_source` IIFE). `<?= $form_id ?>` is the meta form's id (`edit_form_definition` on the edit page):
|
||||
|
||||
```js
|
||||
function rsv_collect_definition() {
|
||||
const form = document.getElementById('<?= $form_id ?>');
|
||||
const get = (n) => form?.querySelector(`[name="${n}"]`)?.value ?? '';
|
||||
return {
|
||||
name: get('name'),
|
||||
definition: {
|
||||
email_key: get('definition.email_key'),
|
||||
success_message: get('definition.success_message'),
|
||||
elements: rsv_elements_source.get_all(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const rsv_preview_el = document.getElementById('rsv_form_preview');
|
||||
let rsv_preview_timer = null;
|
||||
|
||||
function rsv_schedule_preview() {
|
||||
if (!rsv_preview_el) return;
|
||||
clearTimeout(rsv_preview_timer);
|
||||
rsv_preview_timer = setTimeout(rsv_render_preview, 300);
|
||||
}
|
||||
|
||||
function rsv_render_preview() {
|
||||
if (!rsv_preview_el) return;
|
||||
fetch('<?= get_rest_url(null, 'reservations/v1/form-definition/preview') ?>', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
'X-WP-Nonce': ReservairServiceAPI.nonce,
|
||||
},
|
||||
body: JSON.stringify(rsv_collect_definition()),
|
||||
})
|
||||
.then(r => r.ok ? r.json() : r.json().then(e => { throw new Error(e.error || 'Preview failed'); }))
|
||||
.then(data => {
|
||||
rsv_preview_el.innerHTML = data.html || '<p class="rsv-preview-empty">No fields to preview yet.</p>';
|
||||
})
|
||||
.catch(() => { rsv_preview_el.innerHTML = '<p class="rsv-preview-empty">Preview unavailable.</p>'; });
|
||||
}
|
||||
|
||||
// The preview form is inert: block submission (capture so it works after re-render).
|
||||
rsv_preview_el?.addEventListener('submit', (e) => e.preventDefault(), true);
|
||||
```
|
||||
|
||||
### 3b. Trigger preview on every mutation
|
||||
- **Inline edit** (`rsv_render_element_inline_form`, the `builder.build({...})` options): change the two callbacks to also schedule a preview:
|
||||
```js
|
||||
on_success: () => { elements_dt.refresh(); rsv_schedule_preview(); },
|
||||
on_cancel: () => { elements_dt.refresh(); rsv_schedule_preview(); },
|
||||
```
|
||||
- **Move Up / Move Down / Remove** `func_action`s and the **`rsv_add_element_btn` onclick**: add `rsv_schedule_preview();` right after each `dt.refresh()` / `elements_dt.refresh()`.
|
||||
- **Meta fields**: after the existing `rsv_email_key_select` block, add:
|
||||
```js
|
||||
const rsv_meta_form = document.getElementById('<?= $form_id ?>');
|
||||
['name', 'definition.email_key', 'definition.success_message'].forEach((n) => {
|
||||
const el = rsv_meta_form?.querySelector(`[name="${n}"]`);
|
||||
el?.addEventListener('input', rsv_schedule_preview);
|
||||
el?.addEventListener('change', rsv_schedule_preview);
|
||||
});
|
||||
```
|
||||
|
||||
### 3c. Reuse the collector for saving
|
||||
Simplify the existing `RsvAdminForm.bind(...)` `transform` to reuse the collector (keeps preview == saved shape):
|
||||
```js
|
||||
transform: () => rsv_collect_definition(),
|
||||
```
|
||||
|
||||
### 3d. Initial render
|
||||
At the end of the script add:
|
||||
```js
|
||||
rsv_render_preview();
|
||||
```
|
||||
(`rsv_render_preview` no-ops when `#rsv_form_preview` is absent, e.g. the create page, so the shared script stays safe there.)
|
||||
|
||||
---
|
||||
|
||||
## Edge cases / constraints
|
||||
- A freshly-added element defaults to `type: 'text'`, which has no registered handler -> silently skipped in the preview until a real type is chosen. Expected.
|
||||
- The `<rsv-reservation-selector>` in the preview will fetch availability read-only by `timetable-id` — fine, makes the preview realistic.
|
||||
- Use form id `'preview'` (already in the endpoint) so it never collides with a real numeric form id.
|
||||
- Don't touch `RsvFormHtmlRenderer` — submission is neutralized client-side.
|
||||
|
||||
## Verification
|
||||
- `php -l includes/Controllers/RsvFormDefinitionController.php includes/Views/RsvFormsPage.php`
|
||||
- `composer lint` (runs phpcs, phpstan, psalm) — must pass.
|
||||
- No JS build needed (all editor JS is inline).
|
||||
- Manual: open a form's edit page -> edit/add/reorder elements and change the meta fields -> preview updates within ~300 ms and matches the frontend form.
|
||||
@@ -1,7 +1,7 @@
|
||||
/* ─── Two-column admin layout (Forms page) ──────────────────────────────── */
|
||||
/* ─── Column layouts (RsvColumnLayout) ──────────────────────────────────── */
|
||||
|
||||
/*#col-left { width: 30%; }
|
||||
#col-right { width: 70%; }*/
|
||||
.rsv-cols { display: flex; flex-wrap: wrap; gap: 1.5rem; align-items: flex-start; }
|
||||
.rsv-cols > .rsv-col { flex: var(--rsv-col-grow, 1) 1 0; min-width: 18rem; }
|
||||
|
||||
/* ─── Inline detail expand row (Reservations page) ──────────────────────── */
|
||||
|
||||
|
||||
@@ -1,19 +1,30 @@
|
||||
.rsv-form-btn {
|
||||
border-radius: 1.375rem;
|
||||
border: 1.5px solid #e0e0e0;
|
||||
color: #555;
|
||||
padding: 0 calc(1.25rem + 4px);
|
||||
height: 3.5rem;
|
||||
background-color: white;
|
||||
|
||||
line-height: 140%;
|
||||
font-size: 1rem;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
font-family: inherit;
|
||||
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.rsv-form-btn:hover {
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
/* Primary CTA (submit / confirm) */
|
||||
.rsv-form-btn-primary {
|
||||
background: #2563eb;
|
||||
color: #fff;
|
||||
|
||||
border-radius: 1.375rem;
|
||||
font-size: 1rem;
|
||||
padding: 0 calc(1.25rem + 4px);
|
||||
line-height: 140%;
|
||||
height: 3.5rem;
|
||||
|
||||
|
||||
border: none;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
width: 100%;
|
||||
transition: background .12s;
|
||||
@@ -43,12 +54,6 @@
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
/*.reservair-form button {
|
||||
padding: var(--s-3) !important;
|
||||
font-weight: 400 !important;
|
||||
}*/
|
||||
|
||||
/*.reservair-form button,*/
|
||||
.rsv-form-input {
|
||||
border: 1px solid var(--color-gray-300);
|
||||
outline: none;
|
||||
@@ -103,10 +108,10 @@
|
||||
border-color: var(--color-blue-500);
|
||||
}
|
||||
|
||||
.rsv-form-input input:user-invalid {
|
||||
/*.rsv-form-input input:user-invalid {
|
||||
border-color: var(--color-red-500);
|
||||
box-shadow: 0 0 0 4px color-mix(in oklab,var(--color-red-500)25%,transparent);
|
||||
}
|
||||
}*/
|
||||
|
||||
.rsv-form-section {
|
||||
margin-bottom: var(--s-5);
|
||||
@@ -159,52 +164,50 @@
|
||||
padding-left: 5pt;
|
||||
}
|
||||
|
||||
.rsv-form-input:user-invalid,
|
||||
.rsv-invalid {
|
||||
border-color: var(--color-red-500) !important;
|
||||
box-shadow: 0 0 0 4px color-mix(in oklab, var(--color-red-500) 25%, transparent) !important;
|
||||
}
|
||||
|
||||
.rsv-success-message {
|
||||
.rsv-success-msg {
|
||||
text-align: center;
|
||||
padding: var(--s-5);
|
||||
color: var(--color-green-700);
|
||||
width: 320px;
|
||||
}
|
||||
|
||||
.rsv-success-message p {
|
||||
.rsv-success-msg p {
|
||||
margin-top: 0;
|
||||
font-size: 1.125rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
|
||||
.mesg {
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
line-height: 1rem;
|
||||
margin-top: var(--s-5);
|
||||
margin-bottom: var(--s-5);
|
||||
padding: var(--s-4) 0;
|
||||
.rsv-success-msg h1,
|
||||
.rsv-success-msg h2,
|
||||
.rsv-success-msg h3,
|
||||
.rsv-success-msg h4,
|
||||
.rsv-success-msg h5,
|
||||
.rsv-success-msg h6
|
||||
{
|
||||
margin-top: 0;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.success-mesg-icon {
|
||||
.rsv-summary {
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.mesg-icon svg {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
padding: var(--s-2);
|
||||
.rsv-success-icon {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
border-radius: 50%;
|
||||
color: #00000094;
|
||||
background: #dcfce7;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.error-mesg svg {
|
||||
background-color: var(--color-red-200);
|
||||
}
|
||||
|
||||
.success-mesg svg {
|
||||
background-color: rgba(0, 201, 80, 0.36);
|
||||
}
|
||||
/* FORM END */
|
||||
|
||||
.rsv-timetable-selector {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
|
||||
@@ -77,7 +77,7 @@ label.rsv-slots-slot-time>input:checked + .content>.capacity {
|
||||
margin-top: 0.375rem;
|
||||
border: 1.5px solid #e8e8e8;
|
||||
border-radius: 10px;
|
||||
padding: 9px 12px;
|
||||
padding: 0.25rem;
|
||||
cursor: pointer;
|
||||
transition: border-color .12s, background .12s, color .12s;
|
||||
display: flex;
|
||||
@@ -87,7 +87,7 @@ label.rsv-slots-slot-time>input:checked + .content>.capacity {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.rsv-slots-slot:hover:not(.rsv-slots-slot-full):not(.rsv-slots-slot-selected) {
|
||||
.rsv-slots-slot:hover:not(.rsv-slots-slot-full):not(.rsv-slots-slot-too-soon):not(.rsv-slots-slot-selected) {
|
||||
border-color: #2563eb;
|
||||
background: #f5f8ff;
|
||||
}
|
||||
@@ -115,6 +115,12 @@ label.rsv-slots-slot-time>input:checked + .content>.capacity {
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* Within minimum lead time — available but not yet bookable */
|
||||
.rsv-slots-slot-too-soon {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* Selected */
|
||||
.rsv-slots-slot-selected {
|
||||
background: #2563eb;
|
||||
|
||||
@@ -179,6 +179,14 @@ export const RsvCalendarPicker = (() => {
|
||||
new InputEvent('change', { bubbles: true, cancelable: true, composed: true })
|
||||
);
|
||||
},
|
||||
|
||||
// Re-check the radio for the current date. The date lives in JS state, so
|
||||
// this restores the visual selection after a native form.reset() clears it.
|
||||
reselect() {
|
||||
if (this.date === null) return;
|
||||
const radio = this.body.querySelector(`input[id="${this.date.toISOString()}"]`);
|
||||
if (radio) radio.checked = true;
|
||||
},
|
||||
};
|
||||
|
||||
container.classList.add('rsv-calendar');
|
||||
|
||||
@@ -37,6 +37,16 @@ class RsvReservationSelector extends HTMLElement {
|
||||
this.querySelectorAll('.rsv-slots-slot-selected').forEach(s => s.classList.remove('rsv-slots-slot-selected'));
|
||||
this._slots = [];
|
||||
this._commit();
|
||||
// _commit clears only the slots; keep the picked date selected, re-asserting
|
||||
// it in case a surrounding form.reset() just unchecked the calendar radio.
|
||||
this._calendar?.reselect();
|
||||
}
|
||||
|
||||
// Reset for a new reservation: drop the local selection (keeping the date) and
|
||||
// reload availability so slots booked by the previous submission show as full.
|
||||
reset() {
|
||||
this.clear();
|
||||
this.querySelector('rsv-timeline')?.refresh();
|
||||
}
|
||||
|
||||
// ---- Private ------------------------------------------------------------
|
||||
|
||||
@@ -25,6 +25,31 @@ class RsvReservationSummary extends HTMLElement {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Public API ---------------------------------------------------------
|
||||
|
||||
// Detached, static copy of the current selection for the success message.
|
||||
// Mirrors the live layout minus the interactive "clear all" control.
|
||||
snapshot() {
|
||||
const s = ReservairStrings.summary;
|
||||
const list = this.querySelector('.rsv-summary-list');
|
||||
const count = this.querySelector('.rsv-summary-count');
|
||||
const price = this.querySelector('.rsv-summary-price');
|
||||
|
||||
const node = document.createElement('div');
|
||||
node.className = 'rsv-summary rsv-summary-snapshot';
|
||||
node.innerHTML = `
|
||||
<div class="rsv-summary-header">
|
||||
<span class="rsv-summary-title">${s.title}</span>
|
||||
</div>
|
||||
<ul class="rsv-summary-list">${list ? list.innerHTML : ''}</ul>
|
||||
<div class="rsv-summary-footer">
|
||||
<span class="rsv-summary-count">${count ? count.textContent : ''}</span>
|
||||
<div class="rsv-summary-price">${price ? price.textContent : ''}</div>
|
||||
</div>
|
||||
`;
|
||||
return node;
|
||||
}
|
||||
|
||||
// ---- Private ------------------------------------------------------------
|
||||
|
||||
_build() {
|
||||
@@ -51,7 +76,6 @@ class RsvReservationSummary extends HTMLElement {
|
||||
const all_slots = [...this._all_slots.values()].flatMap(({ slots, price_per_block }) =>
|
||||
slots.map(s => ({ ...s, price_per_block }))
|
||||
);
|
||||
console.log(all_slots);
|
||||
|
||||
const n = all_slots.length;
|
||||
const list = this.querySelector('.rsv-summary-list');
|
||||
|
||||
@@ -35,11 +35,19 @@ class RsvTimeline extends HTMLElement {
|
||||
this._render();
|
||||
}
|
||||
|
||||
// ---- Public API ---------------------------------------------------------
|
||||
|
||||
// Re-fetch availability for the current date, e.g. after a booking occupied
|
||||
// some slots. The date is unchanged, so attributeChangedCallback won't fire.
|
||||
refresh() {
|
||||
this._render();
|
||||
}
|
||||
|
||||
// ---- Private ------------------------------------------------------------
|
||||
|
||||
_on_click(event) {
|
||||
const slot = event.target.closest('.rsv-slots-slot');
|
||||
if (slot && !slot.classList.contains('rsv-slots-slot-full')) {
|
||||
if (slot && !slot.classList.contains('rsv-slots-slot-full') && !slot.classList.contains('rsv-slots-slot-too-soon')) {
|
||||
slot.classList.toggle('rsv-slots-slot-selected');
|
||||
slot.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}
|
||||
@@ -59,10 +67,6 @@ class RsvTimeline extends HTMLElement {
|
||||
const occupancy = await RsvTimetableService.get_availability_for_date(this.timetableId, this.date);
|
||||
if (v !== this._version) return;
|
||||
|
||||
if(occupancy.length === 0) {
|
||||
this.replaceChildren(this._notice(s.no_blocks));
|
||||
return;
|
||||
}
|
||||
|
||||
const header = document.createElement('div');
|
||||
header.classList.add('rsv-slots-label');
|
||||
@@ -70,9 +74,14 @@ class RsvTimeline extends HTMLElement {
|
||||
weekday: 'long', day: 'numeric', month: 'long',
|
||||
}).replace(',', '');
|
||||
|
||||
if(occupancy.length === 0) {
|
||||
this.replaceChildren(header, this._notice(s.no_blocks));
|
||||
return;
|
||||
}
|
||||
|
||||
const blocks = [];
|
||||
|
||||
for (const { from_minutes, to_minutes, block_size_in_minutes, occupancy: block_occ } of occupancy) {
|
||||
for (const { from_minutes, to_minutes, block_size_in_minutes, occupancy: block_occ, lead_time_minutes } of occupancy) {
|
||||
if (from_minutes === to_minutes || block_occ.length === 0) {
|
||||
continue;
|
||||
}
|
||||
@@ -80,7 +89,7 @@ class RsvTimeline extends HTMLElement {
|
||||
const from_block = parseInt(from_minutes) / block_size_in_minutes;
|
||||
|
||||
const time_slots = block_occ.map((occ, i) =>
|
||||
this._block(this.date, occ, block_size_in_minutes, from_block + i)
|
||||
this._block(this.date, occ, block_size_in_minutes, from_block + i, lead_time_minutes?.[i] ?? 0)
|
||||
);
|
||||
|
||||
const time_slot_group = document.createElement('div');
|
||||
@@ -96,7 +105,7 @@ class RsvTimeline extends HTMLElement {
|
||||
}
|
||||
}
|
||||
|
||||
_block(date, left, block_size, idx) {
|
||||
_block(date, left, block_size, idx, min_lead_time_minutes = 0) {
|
||||
const from = new Date(date);
|
||||
from.setHours(0, idx * block_size, 0, 0);
|
||||
|
||||
@@ -107,7 +116,8 @@ class RsvTimeline extends HTMLElement {
|
||||
cell.classList.add('rsv-slots-slot', 'rsv-slots-slot-available');
|
||||
cell.dataset.start_utc = from.toISOString();
|
||||
cell.dataset.end_utc = to.toISOString();
|
||||
if (left === 0) cell.classList.add('rsv-slots-slot-full');
|
||||
if (left <= 0) cell.classList.add('rsv-slots-slot-full');
|
||||
else if (from < new Date(Date.now() + min_lead_time_minutes * 60_000)) cell.classList.add('rsv-slots-slot-too-soon');
|
||||
|
||||
const time_el = document.createElement('span');
|
||||
time_el.classList.add('rsv-slots-slot-time');
|
||||
|
||||
@@ -56,24 +56,14 @@ export const RsvFormSender = {
|
||||
svg.appendChild(path);
|
||||
|
||||
const icon = document.createElement('div');
|
||||
icon.className = 'success-icon';
|
||||
icon.className = 'rsv-success-icon';
|
||||
icon.appendChild(svg);
|
||||
|
||||
const title = document.createElement('div');
|
||||
title.className = 'success-title';
|
||||
title.textContent = s.success_title;
|
||||
|
||||
const subtitle = document.createElement('p');
|
||||
subtitle.className = 'success-msg';
|
||||
subtitle.textContent = s.success_subtitle;
|
||||
|
||||
const reset_btn = document.createElement('button');
|
||||
reset_btn.className = 'reset-btn';
|
||||
reset_btn.textContent = s.new_reservation;
|
||||
const body = this.build_success_body(form, s);
|
||||
|
||||
const state = document.createElement('div');
|
||||
state.className = 'success-state';
|
||||
state.append(icon, title, subtitle, reset_btn);
|
||||
state.className = 'rsv-success-state';
|
||||
state.append(icon, body);
|
||||
|
||||
const msg = document.createElement('div');
|
||||
msg.appendChild(state);
|
||||
@@ -81,12 +71,50 @@ export const RsvFormSender = {
|
||||
existing.forEach(child => child.style.display = 'none');
|
||||
wrapper.appendChild(msg);
|
||||
|
||||
reset_btn.addEventListener('click', () => {
|
||||
// The form catches every data-rsv-reset button in the card and links it to
|
||||
// its cleanup — so new buttons just need the marker, no wiring here.
|
||||
const reset = () => {
|
||||
msg.remove();
|
||||
form.reset();
|
||||
// Native reset leaves custom controls untouched; reset the reservation
|
||||
// selectors so their slots, hidden inputs and the summary clear, the date
|
||||
// stays selected and availability reloads with the just-booked slots.
|
||||
form.querySelectorAll('rsv-reservation-selector').forEach(sel => sel.reset());
|
||||
this.clear_feedback(form);
|
||||
existing.forEach(child => child.style.display = '');
|
||||
});
|
||||
};
|
||||
state.querySelectorAll('[data-rsv-reset]').forEach(btn => btn.addEventListener('click', reset));
|
||||
},
|
||||
|
||||
// Body of the success card. Uses the admin-configured template when the form
|
||||
// ships one, filling the .rsv-success-summary placeholder (expanded server-side
|
||||
// from <reservation-summary>) with a snapshot of the selected slots; otherwise
|
||||
// falls back to the default text.
|
||||
build_success_body(form, strings) {
|
||||
const tpl = form.parentElement?.querySelector('template.rsv-form-success');
|
||||
|
||||
if (!tpl) {
|
||||
const subtitle = document.createElement('p');
|
||||
subtitle.className = 'rsv-success-msg';
|
||||
subtitle.textContent = strings.success_subtitle;
|
||||
return subtitle;
|
||||
}
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'rsv-success-msg';
|
||||
body.appendChild(tpl.content.cloneNode(true));
|
||||
|
||||
const placeholder = body.querySelector('.rsv-success-summary');
|
||||
if (placeholder) {
|
||||
const summary = form.querySelector('rsv-reservation-summary');
|
||||
if (summary && typeof summary.snapshot === 'function') {
|
||||
placeholder.replaceWith(summary.snapshot());
|
||||
} else {
|
||||
placeholder.remove();
|
||||
}
|
||||
}
|
||||
|
||||
return body;
|
||||
},
|
||||
|
||||
set_loading(form, is_loading) {
|
||||
|
||||
+3
-6
@@ -12,17 +12,14 @@
|
||||
"files": [
|
||||
"includes/RsvAdminMenuDefinition.php",
|
||||
"includes/RsvAssetsDefinition.php",
|
||||
"includes/RsvRestApiDefinition.php",
|
||||
"includes/Views/RsvFormsPage.php",
|
||||
"includes/Views/RsvReservationsPage.php",
|
||||
"includes/Views/RsvTimetablePage.php",
|
||||
"includes/Views/RsvGoogleCalendarSettingsPage.php"
|
||||
"includes/RsvRestApiDefinition.php"
|
||||
]
|
||||
},
|
||||
"require-dev": {
|
||||
"johnpbloch/wordpress-core": "^6.9",
|
||||
"vimeo/psalm": "^6.16",
|
||||
"humanmade/psalm-plugin-wordpress": "^3.1"
|
||||
"humanmade/psalm-plugin-wordpress": "^3.1",
|
||||
"php-stubs/wordpress-stubs": "^6.9"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": ["phpcs", "phpstan analyse", "psalm --find-dead-code"]
|
||||
|
||||
Generated
+1
-1
@@ -4,7 +4,7 @@
|
||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"content-hash": "c4e0cf49edc636becbde269300f26001",
|
||||
"content-hash": "b4f5229f78cd0eed0c7166614bf05110",
|
||||
"packages": [
|
||||
{
|
||||
"name": "chillerlan/php-qrcode",
|
||||
|
||||
@@ -19,6 +19,7 @@ class RsvFormDefinitionController {
|
||||
'required' => false,
|
||||
'properties' => [
|
||||
'email_key' => ['type' => 'string', 'required' => false],
|
||||
'success_message' => ['type' => 'string', 'required' => false],
|
||||
'elements' => ['type' => 'array', 'default' => []],
|
||||
],
|
||||
],
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<?php
|
||||
|
||||
use Reservair\Logger\Logger;
|
||||
use Reservair\Templating\RsvTemplateEngine;
|
||||
|
||||
/**
|
||||
* Handles all outgoing email for the reservation module.
|
||||
@@ -22,11 +23,7 @@ class RsvEmailListener {
|
||||
<p>Rezervace č. {{reservation_id}} čeká na vaše schválení.</p>
|
||||
<p><strong>Datum:</strong> {{date}}</p>
|
||||
<p><strong>Čas:</strong> {{start}} – {{end}}</p>
|
||||
<p>
|
||||
<a href='{{accept_url}}'>Přijmout</a>
|
||||
|
|
||||
<a href='{{refuse_url}}'>Odmítnout</a>
|
||||
</p>
|
||||
<p><reservation-actions></reservation-actions></p>
|
||||
";
|
||||
|
||||
private const string DEFAULT_ACCEPTED_SUBJECT = 'Rezervace přijata';
|
||||
@@ -48,17 +45,20 @@ class RsvEmailListener {
|
||||
|
||||
public static function on_pending(RsvTimetableReservationPendingEvent $event): void {
|
||||
try {
|
||||
global $rsv_template_registry;
|
||||
$engine = new RsvTemplateEngine(registry: $rsv_template_registry);
|
||||
|
||||
$tz = wp_timezone();
|
||||
$start_dt = (clone $event->reservation->start_utc)->setTimezone($tz);
|
||||
$end_dt = (clone $event->reservation->end_utc)->setTimezone($tz);
|
||||
|
||||
$body = (new RsvEmailTemplater())->render(self::DEFAULT_PENDING_BODY, [
|
||||
$body = $engine->render(self::DEFAULT_PENDING_BODY, [
|
||||
'reservation_id' => (string) $event->reservation_id,
|
||||
'date' => esc_html($start_dt->format('Y-m-d')),
|
||||
'start' => esc_html($start_dt->format('H:i')),
|
||||
'end' => esc_html($end_dt->format('H:i')),
|
||||
'accept_url' => esc_url(get_rest_url(null, 'reservations/v1/timetable-reservation/accept/' . $event->code)),
|
||||
'refuse_url' => esc_url(get_rest_url(null, 'reservations/v1/timetable-reservation/refuse/' . $event->code)),
|
||||
'date' => $start_dt->format('Y-m-d'),
|
||||
'start' => $start_dt->format('H:i'),
|
||||
'end' => $end_dt->format('H:i'),
|
||||
'accept_url' => get_rest_url(null, 'reservations/v1/timetable-reservation/accept/' . $event->code),
|
||||
'refuse_url' => get_rest_url(null, 'reservations/v1/timetable-reservation/refuse/' . $event->code),
|
||||
]);
|
||||
|
||||
(new RsvEmailSender())->send($event->maintainer_email, self::DEFAULT_PENDING_SUBJECT, $body);
|
||||
@@ -67,22 +67,6 @@ class RsvEmailListener {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* HTML-escape scalar form values for safe interpolation into an HTML email
|
||||
* body. Non-scalar values (e.g. nested arrays) are dropped to an empty
|
||||
* string since the templater only substitutes plain placeholders.
|
||||
*
|
||||
* @param array<string,mixed> $values
|
||||
* @return array<string,string>
|
||||
*/
|
||||
private static function escape_values(array $values): array {
|
||||
$escaped = [];
|
||||
foreach ($values as $key => $value) {
|
||||
$escaped[$key] = is_scalar($value) ? esc_html((string) $value) : '';
|
||||
}
|
||||
return $escaped;
|
||||
}
|
||||
|
||||
public static function on_form_submit_closed(RsvFormSubmitClosedEvent $event): void {
|
||||
try {
|
||||
$form_submit = (new RsvFormSubmitRepository())->get($event->form_submit_id);
|
||||
@@ -136,15 +120,14 @@ class RsvEmailListener {
|
||||
$subject_tpl = trim((string) ($tpl['subject'] ?? '')) !== '' ? $tpl['subject'] : $default_subject;
|
||||
$body_tpl = trim((string) ($tpl['body'] ?? '')) !== '' ? $tpl['body'] : $default_body;
|
||||
|
||||
$templater = new RsvEmailTemplater();
|
||||
global $rsv_template_registry;
|
||||
$engine = new RsvTemplateEngine(registry: $rsv_template_registry);
|
||||
|
||||
// Subject is plain text: render with raw values, then strip any tags
|
||||
// or newlines to avoid header issues.
|
||||
$subject = sanitize_text_field($templater->render($subject_tpl, $form_values));
|
||||
// Subject is plain text: render without HTML-escaping, then strip tags/newlines.
|
||||
$subject = sanitize_text_field($engine->render_plain($subject_tpl, $form_values));
|
||||
|
||||
// Body is HTML: escape the user-submitted values before interpolation
|
||||
// so they can't inject markup into the message.
|
||||
$body = $templater->render($body_tpl, self::escape_values($form_values));
|
||||
// Body is HTML: the engine HTML-escapes all interpolated values.
|
||||
$body = $engine->render($body_tpl, $form_values);
|
||||
|
||||
(new RsvEmailSender())->send($user_email, $subject, $body);
|
||||
} catch (\Throwable $e) {
|
||||
|
||||
@@ -6,16 +6,19 @@
|
||||
class RsvTimetableAvailability {
|
||||
/**
|
||||
* @param array<int,int> $occupancy Number of available seats for each time block
|
||||
* @param array<int,int> $lead_time_minutes Minimum lead time in minutes required for each block
|
||||
*/
|
||||
public function __construct(
|
||||
public int $from_minutes,
|
||||
public int $to_minutes,
|
||||
public int $block_size_in_minutes,
|
||||
public array $occupancy
|
||||
public array $occupancy,
|
||||
public array $lead_time_minutes = []
|
||||
) { }
|
||||
|
||||
public function push_block(int $capacity) {
|
||||
public function push_block(int $capacity, int $min_lead_time_minutes = 0) {
|
||||
$this->occupancy[] = $capacity;
|
||||
$this->lead_time_minutes[] = $min_lead_time_minutes;
|
||||
$this->to_minutes += $this->block_size_in_minutes;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,7 +34,8 @@ class RsvTimetableReservationRepository {
|
||||
WHERE timetable_id = %d
|
||||
AND `start_utc` < %s
|
||||
AND `end_utc` > %s",
|
||||
[$timetable_id, $end_utc, $start_utc]
|
||||
[$timetable_id, $end_utc->format('Y-m-d H:i:s'), $start_utc->format('Y-m-d H:i:s')],
|
||||
ARRAY_A
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,12 +4,17 @@
|
||||
* Contains definitions of the admin menus
|
||||
*/
|
||||
function rsv_admin_menu_definition() {
|
||||
$reservations = new RsvReservationsPage();
|
||||
$forms = new RsvFormsPage();
|
||||
$timetable = new RsvTimetablePage();
|
||||
$google_cal = new RsvGoogleCalendarSettingsPage();
|
||||
|
||||
add_menu_page(
|
||||
'Reservations Settings', // Page title
|
||||
'Reservations', // Menu title
|
||||
RsvCapabilities::MANAGE, // Capability
|
||||
'reservations-settings', // Menu slug
|
||||
'rsv_reservations_page', // Callback
|
||||
[$reservations, 'render'], // Callback
|
||||
'dashicons-calendar', // Icon
|
||||
20 // Position
|
||||
);
|
||||
@@ -20,7 +25,7 @@ function rsv_admin_menu_definition() {
|
||||
'Forms',
|
||||
RsvCapabilities::MANAGE,
|
||||
'forms-settings',
|
||||
'rsv_forms_page'
|
||||
[$forms, 'render']
|
||||
);
|
||||
|
||||
add_submenu_page(
|
||||
@@ -29,7 +34,7 @@ function rsv_admin_menu_definition() {
|
||||
'Timetables',
|
||||
RsvCapabilities::MANAGE,
|
||||
'timetable-settings',
|
||||
'rsv_timetable_page'
|
||||
[$timetable, 'render']
|
||||
);
|
||||
|
||||
add_submenu_page(
|
||||
@@ -38,6 +43,6 @@ function rsv_admin_menu_definition() {
|
||||
'Google Calendar',
|
||||
RsvCapabilities::MANAGE,
|
||||
'rsv-google-calendar',
|
||||
'rsv_google_calendar_settings_page'
|
||||
[$google_cal, 'render']
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
abstract class RsvAdminPage {
|
||||
|
||||
final public function render(): void {
|
||||
if (!current_user_can(RsvCapabilities::MANAGE)) {
|
||||
return;
|
||||
}
|
||||
echo '<div class="wrap">';
|
||||
$this->render_content();
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
abstract protected function render_content(): void;
|
||||
}
|
||||
@@ -52,8 +52,15 @@ function rsv_enqueue_assets(): void {
|
||||
}
|
||||
|
||||
function rsv_enqueue_admin_assets(): void {
|
||||
wp_enqueue_script('rsv-admin', rsv_build_url('admin.js'), [], filemtime(rsv_build_file('admin.js')));
|
||||
wp_enqueue_style('rsv-admin', rsv_build_url('admin.css'), [], filemtime(rsv_build_file('admin.css')));
|
||||
// The client bundle defines the custom elements shared by both front-end and
|
||||
// admin. enqueue_block_assets already enqueues `rsv-client` in the editor, so
|
||||
// re-using the same handle here keeps it loaded exactly once (WP dedupes by
|
||||
// handle) instead of bundling a second copy into admin.js.
|
||||
wp_enqueue_script('rsv-client', rsv_build_url('client.js'), [], filemtime(rsv_build_file('client.js')));
|
||||
wp_enqueue_style('rsv-client', rsv_build_url('client.css'), [], filemtime(rsv_build_file('client.css')));
|
||||
|
||||
rsv_localize_api('rsv-admin');
|
||||
wp_enqueue_script('rsv-admin', rsv_build_url('admin.js'), ['rsv-client'], filemtime(rsv_build_file('admin.js')));
|
||||
wp_enqueue_style('rsv-admin', rsv_build_url('admin.css'), ['rsv-client'], filemtime(rsv_build_file('admin.css')));
|
||||
|
||||
rsv_localize_api('rsv-client');
|
||||
}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
<?php
|
||||
|
||||
class RsvEmailTemplater {
|
||||
public function render(string $template, array $data) : string {
|
||||
return preg_replace_callback('/{{\s*(\w+)\s*}}/', function($matches) use ($data) {
|
||||
return $data[$matches[1]] ?? '';
|
||||
}, $template);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ class RsvButtonElementHandler implements RsvFormElementHandler {
|
||||
public function draw(RsvFormElementDefinition $element): void {
|
||||
?>
|
||||
<div class="rsv-form-input-group rsv-form-input-short">
|
||||
<button class="rsv-form-btn-primary"><?= $element->getLabel() ?></button>
|
||||
<button class="rsv-form-btn rsv-form-btn-primary"><?= $element->getLabel() ?></button>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
<?php
|
||||
|
||||
|
||||
interface RsvFormElementHandler {
|
||||
function draw(RsvFormElementDefinition $def) : void;
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ class RsvFormReservationElementHandler implements RsvFormElementHandler {
|
||||
$name = $element->getName();
|
||||
?>
|
||||
<div class="rsv-form-input-group">
|
||||
<label><?= esc_html($element->getLabel()) ?></label>
|
||||
<label class="rsv-form-label"><?= esc_html($element->getLabel()) ?></label>
|
||||
<rsv-reservation-selector
|
||||
timetable-id="<?= $timetable_id ?>"
|
||||
name="<?= esc_attr($name) ?>"
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
|
||||
class RsvOutputTextElementHandler implements RsvFormElementHandler {
|
||||
|
||||
private const ALLOWED_TAGS = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
|
||||
|
||||
public function draw(RsvFormElementDefinition $def): void {
|
||||
$raw = $def->getAttr('tag', 'p');
|
||||
$tag = in_array($raw, self::ALLOWED_TAGS, true) ? $raw : 'p';
|
||||
echo '<' . $tag . ' class="rsv-form-output-text">' . esc_html($def->getLabel()) . '</' . $tag . '>';
|
||||
}
|
||||
|
||||
public function submit(RsvFormElementDefinition $def, int $submit_id, array $data, RsvFormSubmitResult $result): bool {
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rollback(RsvFormElementDefinition $def, int $submit_id, array $data, RsvFormSubmitResult $result): void {
|
||||
// No side effects to undo.
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,10 @@ class RsvFormDefinition {
|
||||
|
||||
public string $email_key = "";
|
||||
|
||||
public string $success_message = "";
|
||||
|
||||
/**
|
||||
* @param array<int,mixed> $definition Full definition array including 'elements' and 'email_key'.
|
||||
* @param array<int,mixed> $definition Full definition array including 'elements', 'email_key' and 'success_message'.
|
||||
*/
|
||||
public function __construct(string $id, array $definition) {
|
||||
$this->_elements = [];
|
||||
@@ -21,6 +23,7 @@ class RsvFormDefinition {
|
||||
|
||||
$this->_id = $id;
|
||||
$this->email_key = $definition['email_key'] ?? '';
|
||||
$this->success_message = $definition['success_message'] ?? '';
|
||||
}
|
||||
|
||||
public function getId(): string {
|
||||
@@ -31,6 +34,11 @@ class RsvFormDefinition {
|
||||
return $this->email_key;
|
||||
}
|
||||
|
||||
/** Template shown to the visitor after a successful submission. */
|
||||
public function getSuccessMessage(): string {
|
||||
return $this->success_message;
|
||||
}
|
||||
|
||||
|
||||
public function hasElements() : bool {
|
||||
return count($this->_elements) > 0;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?php
|
||||
|
||||
use Reservair\Templating\RsvTemplateEngine;
|
||||
|
||||
class RsvFormHtmlRenderer {
|
||||
public function draw(RsvFormDefinition $form): bool {
|
||||
@@ -20,12 +21,37 @@ class RsvFormHtmlRenderer {
|
||||
<?php endforeach; ?>
|
||||
|
||||
</form>
|
||||
<?php $this->draw_success_template($form); ?>
|
||||
</div>
|
||||
<?php
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Emits the admin-configured success message as an inert <template> that the
|
||||
* client clones once the form is submitted. A <reservation-summary> element
|
||||
* expands to a placeholder div that RsvFormSender fills with the visitor's
|
||||
* selected slots.
|
||||
*/
|
||||
private function draw_success_template(RsvFormDefinition $form): void {
|
||||
$message = trim($form->getSuccessMessage());
|
||||
if ($message === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
global $rsv_template_registry;
|
||||
$engine = new RsvTemplateEngine(registry: $rsv_template_registry);
|
||||
|
||||
// Sanitize admin HTML before rendering, allowing the registered template
|
||||
// custom elements through so the engine can expand them.
|
||||
$allowed = $rsv_template_registry->kses_allowed(wp_kses_allowed_html('post'));
|
||||
$html = $engine->render(wp_kses($message, $allowed));
|
||||
?>
|
||||
<template class="rsv-form-success"><?= $html ?></template>
|
||||
<?php
|
||||
}
|
||||
|
||||
public function draw_element(RsvFormElementDefinition $data): void {
|
||||
global $rsv_form_registry;
|
||||
|
||||
|
||||
@@ -35,6 +35,15 @@ class RsvTimetableReservationService {
|
||||
->get_overlapping_capacity($timetable_id, $start_utc, $end_utc);
|
||||
|
||||
if (count($overlapping_capacity) === 0) {
|
||||
Logger::error("No available capacity for timetable_id: $timetable_id, start_utc: " . $start_utc->format('Y-m-d H:i:s') . ", end_utc: " . $end_utc->format('Y-m-d H:i:s'));
|
||||
return false;
|
||||
}
|
||||
|
||||
$max_lead_time = max(array_map(fn($c) => (int) $c->min_lead_time_minutes, $overlapping_capacity));
|
||||
$earliest_allowed = new DateTime('now', new DateTimeZone('UTC'));
|
||||
$earliest_allowed->modify("+{$max_lead_time} minutes");
|
||||
if ($start_utc < $earliest_allowed) {
|
||||
Logger::error("Reservation rejected: minimum lead time of {$max_lead_time} minutes not met for timetable_id: $timetable_id");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -42,6 +51,7 @@ class RsvTimetableReservationService {
|
||||
$end_min = $this->time_of_day_minutes($end_utc);
|
||||
|
||||
if ((int) $overlapping_capacity[0]->start_time > $start_min) {
|
||||
Logger::error("Overlapping capacity start_time: " . (int) $overlapping_capacity[0]->start_time . " is after the reservation start_time: $start_min");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -59,6 +69,7 @@ class RsvTimetableReservationService {
|
||||
|
||||
$capacity = (int) $overlapping_capacity[0]->capacity;
|
||||
$reservations = $this->repo->get_overlapping($timetable_id, $start_utc, $end_utc);
|
||||
error_log('reservations: ' . json_encode($reservations));
|
||||
|
||||
return count($reservations) < $capacity;
|
||||
}
|
||||
|
||||
@@ -98,7 +98,8 @@ class RsvTimetableService {
|
||||
$availabilities[] = new RsvTimetableAvailability($i * $block_length, ($i + 1) * $block_length, $block_length, []);
|
||||
}
|
||||
|
||||
$availabilities[$availability_idx]->push_block($total_capacity - count($reservation_stack));
|
||||
$max_lead_time = empty($capacity_stack) ? 0 : max(array_map(fn($x) => $x->min_lead_time_minutes, $capacity_stack));
|
||||
$availabilities[$availability_idx]->push_block($total_capacity - count($reservation_stack), $max_lead_time);
|
||||
} else if($total_capacity === 0 && count($availabilities) !== $availability_idx) {
|
||||
$availability_idx++;
|
||||
}
|
||||
|
||||
+180
-158
@@ -1,11 +1,151 @@
|
||||
<?php
|
||||
|
||||
use Reservair\Forms\RsvFormBuilder;
|
||||
use Reservair\Layout\RsvColumnLayout;
|
||||
|
||||
// Shared inline script for the elements data grid.
|
||||
// $elements_with_ids: array of element objects already carrying an 'id' key.
|
||||
// $next_id: the first integer not yet used as an id.
|
||||
function rsv_elements_table_script(array $elements_with_ids, int $next_id, string $form_id, array $element_types, array $timetables = []): void {
|
||||
class RsvFormsPage extends RsvAdminPage {
|
||||
|
||||
protected function render_content(): void {
|
||||
if (isset($_GET['action']) && $_GET['action'] === 'edit' && isset($_GET['id'])) {
|
||||
$this->show_edit(intval($_GET['id']));
|
||||
return;
|
||||
}
|
||||
$this->show_list();
|
||||
}
|
||||
|
||||
private function show_list(): void {
|
||||
global $rsv_form_registry;
|
||||
$element_types = array_keys($rsv_form_registry->handlers);
|
||||
$elements_with_ids = [];
|
||||
$next_id = 1;
|
||||
$timetables = (new RsvTimetableService())->get_all();
|
||||
?>
|
||||
<h1>Formuláře</h1>
|
||||
<hr>
|
||||
<?php
|
||||
RsvColumnLayout::split('1:2')
|
||||
->column(function () {
|
||||
echo RsvFormBuilder::create('add_form_definition', get_rest_url(null, 'reservations/v1/form-definition'), 'POST', 'Form definition created.')
|
||||
->heading('Přidat formulář')
|
||||
->nonce('my_action', 'my_nonce')
|
||||
->text('name', 'Název')
|
||||
->render();
|
||||
?>
|
||||
<hr>
|
||||
<p class="submit">
|
||||
<button type="submit" form="add_form_definition" class="button button-primary">Add Form Definition</button>
|
||||
</p>
|
||||
<?php })
|
||||
->column(function () { ?>
|
||||
<div id="forms_table"></div>
|
||||
<script>
|
||||
var forms_dt = RsvDataGrid.create_data_grid(forms_table,
|
||||
RsvFormDefinitionResource(), {
|
||||
'form_id': RsvDataGrid.column('ID', false, 30),
|
||||
'name': RsvDataGrid.action_column('Název', false, {
|
||||
'Edit': RsvDataGrid.link_action((data) =>
|
||||
`<?= menu_page_url('forms-settings', false) ?>&id=${data.form_id}&action=edit`
|
||||
),
|
||||
'Trash': RsvDataGrid.func_action(function(dt, row, data) {
|
||||
if (!confirm('Delete this form? This cannot be undone.')) return;
|
||||
dt.resource.delete(data.form_id).then(() => forms_dt.refresh()).catch(err => alert(err.message));
|
||||
}),
|
||||
'Clone': RsvDataGrid.func_action(function(dt, row, data) {
|
||||
const base_url = `<?= get_rest_url(null, 'reservations/v1/form-definition') ?>`;
|
||||
fetch(`${base_url}/${data.form_id}`, {
|
||||
headers: { 'Accept': 'application/json' },
|
||||
})
|
||||
.then(r => {
|
||||
if (!r.ok) return r.json().then(err => { throw new Error(err.error || 'Fetch failed'); });
|
||||
return r.json();
|
||||
})
|
||||
.then(form_def => fetch(base_url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'Copy of ' + form_def.name,
|
||||
definition: form_def.definition,
|
||||
}),
|
||||
}))
|
||||
.then(r => {
|
||||
if (!r.ok) return r.json().then(err => { throw new Error(err.error || 'Clone failed'); });
|
||||
forms_dt.refresh();
|
||||
})
|
||||
.catch(err => alert(err.message));
|
||||
}),
|
||||
}),
|
||||
});
|
||||
forms_dt.refresh();
|
||||
</script>
|
||||
<?php })
|
||||
->output();
|
||||
?>
|
||||
|
||||
<?php $this->elements_table_script($elements_with_ids, $next_id, 'add_form_definition', $element_types, $timetables); ?>
|
||||
<?php
|
||||
}
|
||||
|
||||
private function show_edit(int $id): void {
|
||||
global $rsv_form_registry;
|
||||
$element_types = array_keys($rsv_form_registry->handlers);
|
||||
|
||||
$repo = new RsvFormDefinitionRepository();
|
||||
$form_def = $repo->get($id);
|
||||
|
||||
if ($form_def === null) {
|
||||
echo '<div class="notice notice-error"><p>Form definition not found.</p></div>';
|
||||
return;
|
||||
}
|
||||
|
||||
$definition = $form_def['definition'] ?? [];
|
||||
$raw_elements = array_values($definition['elements'] ?? []);
|
||||
|
||||
$elements_with_ids = array_map(function (array $el, int $idx): array {
|
||||
return array_merge($el, ['id' => $idx + 1]);
|
||||
}, $raw_elements, array_keys($raw_elements));
|
||||
|
||||
$next_id = count($elements_with_ids) + 1;
|
||||
$timetables = (new RsvTimetableService())->get_all();
|
||||
|
||||
$email_key_options = ['' => '— select field —'];
|
||||
foreach ($raw_elements as $el) {
|
||||
$el_name = $el['name'] ?? '';
|
||||
if ($el_name === '') {
|
||||
continue;
|
||||
}
|
||||
$el_label = $el['label'] ?? '';
|
||||
$email_key_options[$el_name] = $el_label !== '' ? "$el_label ($el_name)" : $el_name;
|
||||
}
|
||||
|
||||
?>
|
||||
<h1>Edit Form: <?= esc_html($form_def['name']) ?></h1>
|
||||
<a href="<?= menu_page_url('forms-settings', false) ?>">← Back to Forms</a>
|
||||
<hr>
|
||||
|
||||
<?php
|
||||
echo RsvFormBuilder::create('edit_form_definition', get_rest_url(null, 'reservations/v1/form-definition/' . $id), 'PUT', 'Form definition updated.')
|
||||
->text('name', 'Name', '', true, $form_def['name'])
|
||||
->select('definition.email_key', 'Email Key', $email_key_options, "Form field that holds the submitter's email address.", true, $definition['email_key'] ?? '')
|
||||
->textarea('definition.success_message', 'Success message', 'Shown to the visitor after a successful submission. HTML is allowed. Use <reservation-summary></reservation-summary> to display the selected reservations. Leave blank for the default message.', false, $definition['success_message'] ?? '')
|
||||
->render();
|
||||
?>
|
||||
|
||||
<hr>
|
||||
<h2>Form Elements</h2>
|
||||
<p>Define the fields that will appear in this form.</p>
|
||||
<div id="form_elements_table"></div>
|
||||
<p>
|
||||
<button type="button" class="button" id="rsv_add_element_btn">+ Add Element</button>
|
||||
</p>
|
||||
<p class="submit">
|
||||
<button type="submit" form="edit_form_definition" class="button button-primary">Update Form Definition</button>
|
||||
</p>
|
||||
|
||||
<?php $this->elements_table_script($elements_with_ids, $next_id, 'edit_form_definition', $element_types, $timetables); ?>
|
||||
<?php
|
||||
}
|
||||
|
||||
private function elements_table_script(array $elements_with_ids, int $next_id, string $form_id, array $element_types, array $timetables = []): void {
|
||||
$elements_json = json_encode($elements_with_ids);
|
||||
$types_json = json_encode(array_values($element_types));
|
||||
$timetables_json = json_encode(array_values($timetables));
|
||||
@@ -36,7 +176,7 @@ function rsv_elements_table_script(array $elements_with_ids, int $next_id, strin
|
||||
if (idx === -1) return Promise.reject(new Error('Element not found'));
|
||||
// Destructure reservation-specific fields so they don't bleed into extra_attrs.
|
||||
const { id: _id, name: _n, label: _l, type: _t, desc: _d, required: _r,
|
||||
price_per_block: _p, email_templates: _et, timetable_id: _ti, ...extra_attrs } = items[idx];
|
||||
price_per_block: _p, email_templates: _et, timetable_id: _ti, tag: _tag, ...extra_attrs } = items[idx];
|
||||
items[idx] = {
|
||||
...extra_attrs,
|
||||
id,
|
||||
@@ -50,6 +190,9 @@ function rsv_elements_table_script(array $elements_with_ids, int $next_id, strin
|
||||
pattern: data.pattern ?? '',
|
||||
pattern_message: data.pattern_message ?? '',
|
||||
} : {}),
|
||||
...(data.type === 'output-text' ? {
|
||||
tag: data.tag ?? 'p',
|
||||
} : {}),
|
||||
...(data.type === 'reservation' ? {
|
||||
timetable_id: data.timetable_id ? parseInt(data.timetable_id) : null,
|
||||
price_per_block: parseFloat(data.price_per_block ?? '0') || 0,
|
||||
@@ -122,6 +265,19 @@ function rsv_elements_table_script(array $elements_with_ids, int $next_id, strin
|
||||
.input_textarea('email_refused_body', 'Body', refused.body ?? RSV_EMAIL_DEFAULTS.refused_body);
|
||||
}
|
||||
|
||||
if ((data?.type ?? rsv_element_types[0]) === 'output-text') {
|
||||
builder
|
||||
.input_select('tag', 'Tag', [
|
||||
{ value: 'p', label: 'Paragraph (p)' },
|
||||
{ value: 'h1', label: 'Heading 1 (h1)' },
|
||||
{ value: 'h2', label: 'Heading 2 (h2)' },
|
||||
{ value: 'h3', label: 'Heading 3 (h3)' },
|
||||
{ value: 'h4', label: 'Heading 4 (h4)' },
|
||||
{ value: 'h5', label: 'Heading 5 (h5)' },
|
||||
{ value: 'h6', label: 'Heading 6 (h6)' },
|
||||
], data?.tag ?? 'p');
|
||||
}
|
||||
|
||||
if ((data?.type ?? rsv_element_types[0]) === 'input-text') {
|
||||
builder
|
||||
.input_select('validation', 'Validation', [
|
||||
@@ -139,7 +295,7 @@ function rsv_elements_table_script(array $elements_with_ids, int $next_id, strin
|
||||
|
||||
const node = builder.build({
|
||||
id: data?.id,
|
||||
colspan: 5,
|
||||
colspan: 6,
|
||||
save_label: 'Save',
|
||||
on_success: () => elements_dt.refresh(),
|
||||
on_cancel: () => elements_dt.refresh(),
|
||||
@@ -229,11 +385,29 @@ function rsv_elements_table_script(array $elements_with_ids, int $next_id, strin
|
||||
};
|
||||
}
|
||||
|
||||
// The Email Key select offers the form's fields. Elements are edited in
|
||||
// the grid above and only persisted on save, so refresh the options from
|
||||
// the live source each time the select is opened.
|
||||
const rsv_email_key_select = document.querySelector('#edit_form_definition select[name="definition.email_key"]');
|
||||
function rsv_sync_email_key_options() {
|
||||
if (!rsv_email_key_select) return;
|
||||
const selected = rsv_email_key_select.value;
|
||||
const options = [new Option('— select field —', '')];
|
||||
for (const el of rsv_elements_source.get_all()) {
|
||||
if (!el.name) continue;
|
||||
options.push(new Option(el.label ? `${el.label} (${el.name})` : el.name, el.name));
|
||||
}
|
||||
rsv_email_key_select.replaceChildren(...options);
|
||||
rsv_email_key_select.value = selected;
|
||||
}
|
||||
rsv_email_key_select?.addEventListener('focus', rsv_sync_email_key_options);
|
||||
|
||||
RsvAdminForm.bind(document.getElementById('<?= $form_id ?>'), {
|
||||
transform: (body) => ({
|
||||
name: body.name,
|
||||
definition: {
|
||||
email_key: body.definition?.email_key ?? '',
|
||||
success_message: body.definition?.success_message ?? '',
|
||||
elements: rsv_elements_source.get_all(),
|
||||
},
|
||||
}),
|
||||
@@ -241,157 +415,5 @@ function rsv_elements_table_script(array $elements_with_ids, int $next_id, strin
|
||||
});
|
||||
</script>
|
||||
<?php
|
||||
}
|
||||
|
||||
function rsv_form_info_page(): void {
|
||||
global $rsv_form_registry;
|
||||
$element_types = array_keys($rsv_form_registry->handlers);
|
||||
$elements_with_ids = [];
|
||||
$next_id = 1;
|
||||
$timetables = (new RsvTimetableService())->get_all();
|
||||
?>
|
||||
|
||||
<h1>Formuláře</h1>
|
||||
<hr>
|
||||
<div id="col-container" class="wp-clearfix">
|
||||
<div id="col-left">
|
||||
<div class="col-wrap">
|
||||
<div class="form-wrap">
|
||||
<h2>Přidat formulář</h2>
|
||||
|
||||
<form id="add_form_definition"
|
||||
method="post"
|
||||
data-method="POST"
|
||||
data-success-msg="Form definition created."
|
||||
action="<?= get_rest_url(null, 'reservations/v1/form-definition'); ?>">
|
||||
<?php wp_nonce_field('my_action', 'my_nonce'); ?>
|
||||
|
||||
<?php echo RsvFormBuilder::create('add_form_definition')->text('name', 'Název')->render(); ?>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<hr>
|
||||
<p class="submit">
|
||||
<button type="submit" form="add_form_definition" class="button button-primary">Add Form Definition</button>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="col-right">
|
||||
<div class="col-wrap">
|
||||
<div id="forms_table"></div>
|
||||
<script>
|
||||
var forms_dt = RsvDataGrid.create_data_grid(forms_table,
|
||||
RsvFormDefinitionResource(), {
|
||||
'form_id': RsvDataGrid.column('ID', false, 30),
|
||||
'name': RsvDataGrid.action_column('Název', false, {
|
||||
'Edit': RsvDataGrid.link_action((data) =>
|
||||
`<?= menu_page_url('forms-settings', false) ?>&id=${data.form_id}&action=edit`
|
||||
),
|
||||
'Trash': RsvDataGrid.func_action(function(dt, row, data) {
|
||||
dt.resource.delete(data.form_id).then(() => forms_dt.refresh()).catch(err => alert(err.message));
|
||||
}),
|
||||
'Clone': RsvDataGrid.func_action(function(dt, row, data) {
|
||||
const base_url = `<?= get_rest_url(null, 'reservations/v1/form-definition') ?>`;
|
||||
fetch(`${base_url}/${data.form_id}`, {
|
||||
headers: { 'Accept': 'application/json' },
|
||||
})
|
||||
.then(r => {
|
||||
if (!r.ok) return r.json().then(err => { throw new Error(err.error || 'Fetch failed'); });
|
||||
return r.json();
|
||||
})
|
||||
.then(form_def => fetch(base_url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'Copy of ' + form_def.name,
|
||||
definition: form_def.definition,
|
||||
}),
|
||||
}))
|
||||
.then(r => {
|
||||
if (!r.ok) return r.json().then(err => { throw new Error(err.error || 'Clone failed'); });
|
||||
forms_dt.refresh();
|
||||
})
|
||||
.catch(err => alert(err.message));
|
||||
}),
|
||||
}),
|
||||
});
|
||||
forms_dt.refresh();
|
||||
</script>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<?php rsv_elements_table_script($elements_with_ids, $next_id, 'add_form_definition', $element_types, $timetables); ?>
|
||||
|
||||
<?php
|
||||
}
|
||||
|
||||
function rsv_form_definition_edit_page(int $id): void {
|
||||
global $rsv_form_registry;
|
||||
$element_types = array_keys($rsv_form_registry->handlers);
|
||||
|
||||
$repo = new RsvFormDefinitionRepository();
|
||||
$form_def = $repo->get($id);
|
||||
|
||||
if ($form_def === null) {
|
||||
echo '<div class="notice notice-error"><p>Form definition not found.</p></div>';
|
||||
return;
|
||||
}
|
||||
|
||||
$definition = $form_def['definition'] ?? [];
|
||||
$raw_elements = array_values($definition['elements'] ?? []);
|
||||
|
||||
$elements_with_ids = array_map(function (array $el, int $idx): array {
|
||||
return array_merge($el, ['id' => $idx + 1]);
|
||||
}, $raw_elements, array_keys($raw_elements));
|
||||
|
||||
$next_id = count($elements_with_ids) + 1;
|
||||
$timetables = (new RsvTimetableService())->get_all();
|
||||
|
||||
?>
|
||||
<h1>Edit Form: <?= esc_html($form_def['name']) ?></h1>
|
||||
<a href="<?= menu_page_url('forms-settings', false) ?>">← Back to Forms</a>
|
||||
<hr>
|
||||
|
||||
<form id="edit_form_definition"
|
||||
method="post"
|
||||
data-method="PUT"
|
||||
data-success-msg="Form definition updated."
|
||||
action="<?= get_rest_url(null, 'reservations/v1/form-definition/' . $id); ?>">
|
||||
|
||||
<?php
|
||||
echo RsvFormBuilder::create('edit_form_definition')
|
||||
->text('name', 'Name', '', true, $form_def['name'])
|
||||
->text('definition.email_key', 'Email Key', "Name of the form field that holds the submitter's email address.", true, $definition['email_key'] ?? '')
|
||||
->render();
|
||||
?>
|
||||
</form>
|
||||
|
||||
<hr>
|
||||
<h2>Form Elements</h2>
|
||||
<p>Define the fields that will appear in this form.</p>
|
||||
<div id="form_elements_table"></div>
|
||||
<p>
|
||||
<button type="button" class="button" id="rsv_add_element_btn">+ Add Element</button>
|
||||
</p>
|
||||
<p class="submit">
|
||||
<button type="submit" form="edit_form_definition" class="button button-primary">Update Form Definition</button>
|
||||
</p>
|
||||
|
||||
<?php rsv_elements_table_script($elements_with_ids, $next_id, 'edit_form_definition', $element_types, $timetables); ?>
|
||||
|
||||
<?php
|
||||
}
|
||||
|
||||
function rsv_forms_page(): void {
|
||||
if (isset($_GET['action'])) {
|
||||
if ($_GET['action'] === 'edit' && isset($_GET['id'])) {
|
||||
rsv_form_definition_edit_page(intval($_GET['id']));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
rsv_form_info_page();
|
||||
}
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
<?php
|
||||
|
||||
|
||||
function rsv_google_calendar_settings_page(): void {
|
||||
if (!current_user_can(RsvCapabilities::MANAGE)) {
|
||||
return;
|
||||
}
|
||||
class RsvGoogleCalendarSettingsPage extends RsvAdminPage {
|
||||
|
||||
protected function render_content(): void {
|
||||
$service = new RsvGoogleCalendarService();
|
||||
$notice = null;
|
||||
|
||||
@@ -50,7 +48,6 @@ function rsv_google_calendar_settings_page(): void {
|
||||
$cal_id = esc_attr(get_option('rsv_google_calendar_id', 'primary'));
|
||||
$oauth_url = esc_url($service->get_oauth_url());
|
||||
?>
|
||||
<div class="wrap">
|
||||
<h1>Google Calendar</h1>
|
||||
|
||||
<?php if ($notice): ?>
|
||||
@@ -127,6 +124,6 @@ function rsv_google_calendar_settings_page(): void {
|
||||
<?php endif; ?>
|
||||
<?php endif; ?>
|
||||
</form>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
<?php
|
||||
|
||||
function rsv_reservations_page(): void {
|
||||
class RsvReservationsPage extends RsvAdminPage {
|
||||
|
||||
protected function render_content(): void {
|
||||
?>
|
||||
<h1>Form Submissions</h1>
|
||||
|
||||
@@ -216,4 +218,5 @@ function rsv_reservations_page(): void {
|
||||
reservations_dt.refresh();
|
||||
</script>
|
||||
<?php
|
||||
}
|
||||
}
|
||||
|
||||
+134
-194
@@ -1,53 +1,46 @@
|
||||
<?php
|
||||
|
||||
use Reservair\Forms\RsvFormBuilder;
|
||||
use Reservair\Layout\RsvColumnLayout;
|
||||
|
||||
class RsvTimetablePage extends RsvAdminPage {
|
||||
|
||||
function rsv_timetable_list_page() {
|
||||
protected function render_content(): void {
|
||||
if (isset($_GET['action'])) {
|
||||
if ($_GET['action'] === 'view' && isset($_GET['id'])) {
|
||||
$this->show_view(intval($_GET['id']));
|
||||
return;
|
||||
} elseif ($_GET['action'] === 'edit' && isset($_GET['id'])) {
|
||||
$this->show_capacity(intval($_GET['id']));
|
||||
return;
|
||||
}
|
||||
// Deletion is intentionally not handled here: a state-changing GET is
|
||||
// CSRF-prone. Timetables are deleted via the nonce-authenticated REST
|
||||
// DELETE /timetable/{id} (see the "Trash" action in the list grid).
|
||||
}
|
||||
|
||||
$this->show_list();
|
||||
}
|
||||
|
||||
private function show_list(): void {
|
||||
?>
|
||||
<style>
|
||||
/*#col-left {
|
||||
width: 30%;
|
||||
}*/
|
||||
|
||||
/*#col-right {
|
||||
width: 70%;
|
||||
}*/
|
||||
</style>
|
||||
<h1>Timetables</h1>
|
||||
<hr>
|
||||
<div id="col-container" class="wp-clearfix">
|
||||
<div id="col-left">
|
||||
<div class="col-wrap">
|
||||
<div class="form-wrap">
|
||||
<h2>Add timetable</h2>
|
||||
|
||||
<?php
|
||||
$timetable_service = new RsvTimetableService();
|
||||
$existing_emails = $timetable_service->get_all_maintainer_emails();
|
||||
$existing_emails_json = json_encode($existing_emails);
|
||||
?>
|
||||
<datalist id="maintainer_email_suggestions">
|
||||
<?php foreach ($existing_emails as $email): ?>
|
||||
<option value="<?= esc_attr($email) ?>">
|
||||
<?php endforeach; ?>
|
||||
</datalist>
|
||||
|
||||
<form id="add_timetable_form"
|
||||
method="post"
|
||||
data-method="POST"
|
||||
data-success-msg="Timetable created."
|
||||
action="<?= get_rest_url(null, 'reservations/v1/timetable'); ?>">
|
||||
|
||||
<?php
|
||||
echo RsvFormBuilder::create('add_timetable_form')
|
||||
RsvColumnLayout::split('1:2')
|
||||
->column(function () use ($existing_emails) {
|
||||
echo RsvFormBuilder::create('add_timetable_form', get_rest_url(null, 'reservations/v1/timetable'), 'POST', 'Timetable created.')
|
||||
->heading('Add timetable')
|
||||
->datalist('maintainer_email_suggestions', $existing_emails)
|
||||
->text('name', 'Name', 'Name of the timetable that can be reserved.', true)
|
||||
->number('block_size', 'Block length (minutes)', 'Duration of one reservable time block in minutes.', true, '', 1)
|
||||
->email('maintainer_email', 'Maintainer Email', 'Email address to notify when a reservation requires confirmation.', false, '', 'maintainer_email_suggestions')
|
||||
->submit('Add Timetable')
|
||||
->render();
|
||||
?>
|
||||
</form>
|
||||
<script>
|
||||
RsvAdminForm.bind(add_timetable_form, {
|
||||
transform: (body) => ({
|
||||
@@ -58,14 +51,9 @@ function rsv_timetable_list_page() {
|
||||
refresh: () => availability_dt.refresh(),
|
||||
});
|
||||
</script>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="col-right">
|
||||
<div class="col-wrap">
|
||||
<div id="availability_table">
|
||||
|
||||
</div>
|
||||
<?php })
|
||||
->column(function () { ?>
|
||||
<div id="availability_table"></div>
|
||||
<script>
|
||||
var availability_dt = RsvDataGrid.create_data_grid(availability_table,
|
||||
RsvTimetableResource(), {
|
||||
@@ -83,71 +71,67 @@ function rsv_timetable_list_page() {
|
||||
});
|
||||
availability_dt.refresh();
|
||||
</script>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
function rsv_create_capacity_form($timetable_id) {
|
||||
$form = RsvFormBuilder::create("create_capacity_form", get_rest_url(null, 'reservations/v1/timetable/' . $timetable_id . '/capacity'));
|
||||
$form->date('date', 'First Date', 'Od kterého datumu platí tato kapacita.', true, new DateTime()->format('Y-m-d'));
|
||||
$form->group('Availability Range', fn($g) => $g
|
||||
->time('start_time', 'Start')
|
||||
->time('end_time', 'End')
|
||||
);
|
||||
$form->number('capacity', 'Capacity', 'How many reservations can overlap on the same time.', true, 1, 1);
|
||||
$form->number('min_lead_time_minutes', 'Minimum lead time (minutes)', 'How many minutes in advance must be the reservation created. This is useful if it takes some time to prepare the reservation.', true);
|
||||
$form->checkbox('requires_confirmation', 'Requires Confirmation?', 'If checked, all the reservations that overlap this capacity will require confirmation from maintainer. The maintainer will receive an email asking for the confirmation.', true);
|
||||
$form->custom('Is Repeating Event', function() {
|
||||
return '
|
||||
<input id="is_repeating" class="regular-text" type="checkbox" name="is_repeating" checked="true">
|
||||
<p>If the capacity is available repeatingly. For example: repeat each monday every week.</p>
|
||||
';
|
||||
});
|
||||
$form->number('repeat_period_in_days', 'Repeat Period (days)', 'How many days between each repetition.', true);
|
||||
$form->custom('Apply to Days', function() {
|
||||
return '
|
||||
<table class="option-table">
|
||||
<tbody>
|
||||
<tr class="form-day-names">
|
||||
<td>Monday</td>
|
||||
<td>Tuesday</td>
|
||||
<td>Wednesday</td>
|
||||
<td>Thursday</td>
|
||||
<td>Friday</td>
|
||||
<td>Saturday</td>
|
||||
<td>Sunday</td>
|
||||
</tr>
|
||||
<tr class="form-days">
|
||||
<td><input class="is-repeating-input" type="checkbox" name="monday"></td>
|
||||
<td><input class="is-repeating-input" type="checkbox" name="tuesday"></td>
|
||||
<td><input class="is-repeating-input" type="checkbox" name="wednesday"></td>
|
||||
<td><input class="is-repeating-input" type="checkbox" name="thursday"></td>
|
||||
<td><input class="is-repeating-input" type="checkbox" name="friday"></td>
|
||||
<td><input class="is-repeating-input" type="checkbox" name="saturday"></td>
|
||||
<td><input class="is-repeating-input" type="checkbox" name="sunday"></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>';
|
||||
});
|
||||
$form->submit('Create Capacity', 'button-primary', 'submit');
|
||||
|
||||
<?php })
|
||||
->output();
|
||||
?>
|
||||
<form
|
||||
id="create_capacity_form"
|
||||
data-method="POST"
|
||||
data-success-msg="Capacity created."
|
||||
action="<?= get_rest_url(null, 'reservations/v1/timetable/' . $timetable_id . '/capacity'); ?>" >
|
||||
<?php
|
||||
$form->output();
|
||||
}
|
||||
|
||||
private function show_view(int $id): void {
|
||||
$timetable = (new RsvTimetableService())->get($id);
|
||||
if ($timetable === null) {
|
||||
echo '<div class="notice notice-error"><p>Timetable not found.</p></div>';
|
||||
return;
|
||||
}
|
||||
?>
|
||||
</form>
|
||||
<?php
|
||||
}
|
||||
<h1><?= esc_html($timetable->name) ?></h1>
|
||||
<a href="<?= esc_url(menu_page_url('timetable-settings', false)) ?>">← Back to Timetables</a>
|
||||
<hr>
|
||||
|
||||
function rsv_timetable_capacity_view($id) {
|
||||
<table class="form-table">
|
||||
<tr><th>Name</th><td><?= esc_html($timetable->name) ?></td></tr>
|
||||
<tr><th>Block size</th><td><?= esc_html($timetable->block_size) ?> minutes</td></tr>
|
||||
<?php if ($timetable->maintainer_email): ?>
|
||||
<tr><th>Maintainer email</th><td><?= esc_html($timetable->maintainer_email) ?></td></tr>
|
||||
<?php endif; ?>
|
||||
</table>
|
||||
|
||||
<h2>Reservations</h2>
|
||||
<div id="timetable_reservations_table"></div>
|
||||
<script>
|
||||
RsvDataGrid.create_data_grid(
|
||||
timetable_reservations_table,
|
||||
RsvTimetableReservationResource(<?= $id ?>),
|
||||
{
|
||||
'id': RsvDataGrid.column('ID', false),
|
||||
'reservation_id': RsvDataGrid.action_column('Reservation', false, {
|
||||
'Accept': RsvDataGrid.func_action(
|
||||
(dt, row, data) => RsvReservationClient.accept(data.reservation_id).then(() => dt.refresh()),
|
||||
(item) => item.pending_confirmation_id !== null
|
||||
),
|
||||
'Refuse': RsvDataGrid.func_action(
|
||||
(dt, row, data) => RsvReservationClient.refuse(data.reservation_id).then(() => dt.refresh()),
|
||||
(item) => item.pending_confirmation_id !== null
|
||||
),
|
||||
}),
|
||||
'start_utc': RsvDataGrid.column('Start', false),
|
||||
'end_utc': RsvDataGrid.column('End', false),
|
||||
'is_confirmed': RsvDataGrid.column('Status', false),
|
||||
}
|
||||
)
|
||||
.map_column('is_confirmed', (dt, row, data) => {
|
||||
const td = document.createElement('td');
|
||||
td.textContent = data.pending_confirmation_id !== null ? 'Pending'
|
||||
: data.is_confirmed == 1 ? 'Confirmed'
|
||||
: 'Refused';
|
||||
return td;
|
||||
})
|
||||
.refresh();
|
||||
</script>
|
||||
<?php
|
||||
}
|
||||
|
||||
private function show_capacity(int $id): void {
|
||||
$timetable_service = new RsvTimetableService();
|
||||
$timetable = $timetable_service->get($id);
|
||||
$gcal_service = new RsvGoogleCalendarService();
|
||||
@@ -156,21 +140,10 @@ function rsv_timetable_capacity_view($id) {
|
||||
$existing_emails = $timetable_service->get_all_maintainer_emails();
|
||||
?>
|
||||
|
||||
<h2>Settings</h2>
|
||||
|
||||
<datalist id="maintainer_email_list">
|
||||
<?php foreach ($existing_emails as $email): ?>
|
||||
<option value="<?= esc_attr($email) ?>">
|
||||
<?php endforeach; ?>
|
||||
</datalist>
|
||||
|
||||
<form id="timetable_settings_form"
|
||||
action="<?= esc_url(get_rest_url(null, 'reservations/v1/timetable/' . $id)) ?>"
|
||||
data-method="PATCH"
|
||||
data-success-msg="Settings saved.">
|
||||
|
||||
<?php
|
||||
RsvFormBuilder::create("timetable_settings_form")
|
||||
RsvFormBuilder::create('timetable_settings_form', get_rest_url(null, 'reservations/v1/timetable/' . $id), 'PATCH', 'Settings saved.')
|
||||
->heading('Settings')
|
||||
->datalist('maintainer_email_suggestions', $existing_emails)
|
||||
->text('name', 'Name', 'Name of the timetable that can be reserved.', true, $timetable->name)
|
||||
->number('block_size', 'Block length (minutes)', 'Duration of one reservable time block in minutes.', true, $timetable->block_size, 1)
|
||||
->email('maintainer_email', 'Maintainer Email', 'Email address to notify when a reservation requires confirmation.', false, $timetable->maintainer_email ?? '', 'maintainer_email_suggestions')
|
||||
@@ -189,7 +162,6 @@ function rsv_timetable_capacity_view($id) {
|
||||
->submit('Save Settings', 'button-primary', 'submit')
|
||||
->output();
|
||||
?>
|
||||
</form>
|
||||
|
||||
<script>
|
||||
(function() {
|
||||
@@ -225,11 +197,8 @@ function rsv_timetable_capacity_view($id) {
|
||||
|
||||
<p>Define capacities for timetable.</p>
|
||||
|
||||
<?php
|
||||
<?php $this->create_capacity_form($id); ?>
|
||||
|
||||
rsv_create_capacity_form($id);
|
||||
|
||||
?>
|
||||
<script>
|
||||
(function() {
|
||||
const DAY_DOW = { monday: 1, tuesday: 2, wednesday: 3, thursday: 4, friday: 5, saturday: 6, sunday: 0 };
|
||||
@@ -353,82 +322,53 @@ function rsv_timetable_capacity_view($id) {
|
||||
|
||||
capacity_dt.refresh();
|
||||
</script>
|
||||
|
||||
<?php
|
||||
}
|
||||
|
||||
function rsv_timetable_view_page(int $id): void {
|
||||
$timetable = (new RsvTimetableService())->get($id);
|
||||
if ($timetable === null) {
|
||||
echo '<div class="notice notice-error"><p>Timetable not found.</p></div>';
|
||||
return;
|
||||
}
|
||||
?>
|
||||
<h1><?= esc_html($timetable->name) ?></h1>
|
||||
<a href="<?= esc_url(menu_page_url('timetable-settings', false)) ?>">← Back to Timetables</a>
|
||||
<hr>
|
||||
|
||||
<table class="form-table">
|
||||
<tr><th>Name</th><td><?= esc_html($timetable->name) ?></td></tr>
|
||||
<tr><th>Block size</th><td><?= esc_html($timetable->block_size) ?> minutes</td></tr>
|
||||
<?php if ($timetable->maintainer_email): ?>
|
||||
<tr><th>Maintainer email</th><td><?= esc_html($timetable->maintainer_email) ?></td></tr>
|
||||
<?php endif; ?>
|
||||
</table>
|
||||
|
||||
<h2>Reservations</h2>
|
||||
<div id="timetable_reservations_table"></div>
|
||||
<script>
|
||||
RsvDataGrid.create_data_grid(
|
||||
timetable_reservations_table,
|
||||
RsvTimetableReservationResource(<?= $id ?>),
|
||||
{
|
||||
'id': RsvDataGrid.column('ID', false),
|
||||
'reservation_id': RsvDataGrid.action_column('Reservation', false, {
|
||||
'Accept': RsvDataGrid.func_action(
|
||||
(dt, row, data) => RsvReservationClient.accept(data.reservation_id).then(() => dt.refresh()),
|
||||
(item) => item.pending_confirmation_id !== null
|
||||
),
|
||||
'Refuse': RsvDataGrid.func_action(
|
||||
(dt, row, data) => RsvReservationClient.refuse(data.reservation_id).then(() => dt.refresh()),
|
||||
(item) => item.pending_confirmation_id !== null
|
||||
),
|
||||
}),
|
||||
'start_utc': RsvDataGrid.column('Start', false),
|
||||
'end_utc': RsvDataGrid.column('End', false),
|
||||
'is_confirmed': RsvDataGrid.column('Status', false),
|
||||
}
|
||||
)
|
||||
.map_column('is_confirmed', (dt, row, data) => {
|
||||
const td = document.createElement('td');
|
||||
td.textContent = data.pending_confirmation_id !== null ? 'Pending'
|
||||
: data.is_confirmed == 1 ? 'Confirmed'
|
||||
: 'Refused';
|
||||
return td;
|
||||
})
|
||||
.refresh();
|
||||
</script>
|
||||
<?php
|
||||
}
|
||||
|
||||
function rsv_timetable_edit_page($id) {
|
||||
rsv_timetable_capacity_view($id);
|
||||
}
|
||||
|
||||
|
||||
function rsv_timetable_page() {
|
||||
if (isset($_GET['action'])) {
|
||||
if ($_GET['action'] === 'view' && isset($_GET['id'])) {
|
||||
rsv_timetable_view_page(intval($_GET['id']));
|
||||
return;
|
||||
} else if($_GET['action'] === 'edit' && isset($_GET['id'])) {
|
||||
rsv_timetable_edit_page(intval($_GET['id']));
|
||||
return;
|
||||
}
|
||||
// Deletion is intentionally not handled here: a state-changing GET is
|
||||
// CSRF-prone. Timetables are deleted via the nonce-authenticated REST
|
||||
// DELETE /timetable/{id} (see the "Trash" action in the list grid).
|
||||
}
|
||||
|
||||
rsv_timetable_list_page();
|
||||
private function create_capacity_form(int $timetable_id): void {
|
||||
$form = RsvFormBuilder::create('create_capacity_form', get_rest_url(null, 'reservations/v1/timetable/' . $timetable_id . '/capacity'), 'POST', 'Capacity created.');
|
||||
$form->date('date', 'First Date', 'Od kterého datumu platí tato kapacita.', true, new DateTime()->format('Y-m-d'));
|
||||
$form->group('Availability Range', fn($g) => $g
|
||||
->time('start_time', 'Start')
|
||||
->time('end_time', 'End')
|
||||
);
|
||||
$form->number('capacity', 'Capacity', 'How many reservations can overlap on the same time.', true, 1, 1);
|
||||
$form->number('min_lead_time_minutes', 'Minimum lead time (minutes)', 'How many minutes in advance must be the reservation created. This is useful if it takes some time to prepare the reservation.', true);
|
||||
$form->checkbox('requires_confirmation', 'Requires Confirmation?', 'If checked, all the reservations that overlap this capacity will require confirmation from maintainer. The maintainer will receive an email asking for the confirmation.', true);
|
||||
$form->custom('Is Repeating Event', function() {
|
||||
return '
|
||||
<input id="is_repeating" class="regular-text" type="checkbox" name="is_repeating" checked="true">
|
||||
<p>If the capacity is available repeatingly. For example: repeat each monday every week.</p>
|
||||
';
|
||||
});
|
||||
$form->number('repeat_period_in_days', 'Repeat Period (days)', 'How many days between each repetition.', true);
|
||||
$form->custom('Apply to Days', function() {
|
||||
return '
|
||||
<table class="option-table">
|
||||
<tbody>
|
||||
<tr class="form-day-names">
|
||||
<td>Monday</td>
|
||||
<td>Tuesday</td>
|
||||
<td>Wednesday</td>
|
||||
<td>Thursday</td>
|
||||
<td>Friday</td>
|
||||
<td>Saturday</td>
|
||||
<td>Sunday</td>
|
||||
</tr>
|
||||
<tr class="form-days">
|
||||
<td><input class="is-repeating-input" type="checkbox" name="monday"></td>
|
||||
<td><input class="is-repeating-input" type="checkbox" name="tuesday"></td>
|
||||
<td><input class="is-repeating-input" type="checkbox" name="wednesday"></td>
|
||||
<td><input class="is-repeating-input" type="checkbox" name="thursday"></td>
|
||||
<td><input class="is-repeating-input" type="checkbox" name="friday"></td>
|
||||
<td><input class="is-repeating-input" type="checkbox" name="saturday"></td>
|
||||
<td><input class="is-repeating-input" type="checkbox" name="sunday"></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>';
|
||||
});
|
||||
$form->submit('Create Capacity', 'button-primary', 'submit');
|
||||
|
||||
$form->output();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,9 @@ class Db {
|
||||
|
||||
public static function get_results(string $sql, array $params = [], string $output = OBJECT): array {
|
||||
global $wpdb;
|
||||
$rows = $wpdb->get_results(empty($params) ? $sql : $wpdb->prepare($sql, $params), $output);
|
||||
$query = empty($params) ? $sql : $wpdb->prepare($sql, $params);
|
||||
error_log($query);
|
||||
$rows = $wpdb->get_results($query, $output);
|
||||
self::throw_if_error();
|
||||
return $rows ?? [];
|
||||
}
|
||||
|
||||
@@ -5,24 +5,34 @@ namespace Reservair\Forms;
|
||||
/**
|
||||
* Fluent builder for WordPress admin settings forms.
|
||||
*
|
||||
* Renders a <table class="form-table"> with one row per field.
|
||||
* Hidden inputs and datalist elements are emitted before the table;
|
||||
* notices before, submit button after.
|
||||
* Renders a self-contained "form-wrap" card: an optional heading and a <form>
|
||||
* wrapping a <table class="form-table"> with one row per field. Hidden inputs
|
||||
* and datalist elements are emitted before the table; notices before the card,
|
||||
* submit button after the fields.
|
||||
*
|
||||
* Usage:
|
||||
* echo RsvFormBuilder::create()
|
||||
* echo RsvFormBuilder::create('settings', $action, 'PATCH', 'Saved.')
|
||||
* ->heading('Settings')
|
||||
* ->text('name', 'Name', required: true)
|
||||
* ->email('email', 'Email')
|
||||
* ->submit('Save');
|
||||
*/
|
||||
class RsvFormBuilder
|
||||
{
|
||||
private string $form_id = "";
|
||||
private string $form_id;
|
||||
|
||||
/** Where the form submits, and how RsvAdminForm should send it. */
|
||||
private string $action;
|
||||
private string $rest_method;
|
||||
private string $success_msg;
|
||||
|
||||
/** Optional heading shown inside the card. */
|
||||
private string $heading = '';
|
||||
|
||||
/** @var string[] Rendered before the table (hidden inputs, datalists). */
|
||||
private array $before = [];
|
||||
|
||||
/** @var string[] WP admin notice banners rendered before the table. */
|
||||
/** @var string[] WP admin notice banners rendered before the card. */
|
||||
private array $notices = [];
|
||||
|
||||
/** @var string[] <tr> elements inside the table. */
|
||||
@@ -33,9 +43,29 @@ class RsvFormBuilder
|
||||
|
||||
private function __construct() {}
|
||||
|
||||
public static function create(string $id): static
|
||||
/**
|
||||
* @param string $rest_method Verb sent via data-method (POST, PUT, PATCH…).
|
||||
* @param string $success_msg Message RsvAdminForm shows on success.
|
||||
*/
|
||||
public static function create(
|
||||
string $id,
|
||||
string $action,
|
||||
string $rest_method = 'POST',
|
||||
string $success_msg = ''
|
||||
): static {
|
||||
$builder = new static();
|
||||
$builder->form_id = $id;
|
||||
$builder->action = $action;
|
||||
$builder->rest_method = $rest_method;
|
||||
$builder->success_msg = $success_msg;
|
||||
return $builder;
|
||||
}
|
||||
|
||||
/** Heading shown inside the card, above the fields. */
|
||||
public function heading(string $text): static
|
||||
{
|
||||
return new static();
|
||||
$this->heading = $text;
|
||||
return $this;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
@@ -206,6 +236,13 @@ class RsvFormBuilder
|
||||
return $this;
|
||||
}
|
||||
|
||||
/** WordPress nonce field, emitted inside the form before the table. */
|
||||
public function nonce(string $action, string $name): static
|
||||
{
|
||||
$this->before[] = wp_nonce_field($action, $name, true, false);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <datalist> element for email/text suggestions — emitted before the table.
|
||||
*
|
||||
@@ -257,15 +294,27 @@ class RsvFormBuilder
|
||||
|
||||
public function render(): string
|
||||
{
|
||||
$html = implode('', $this->notices);
|
||||
$html .= implode('', $this->before);
|
||||
$inner = implode('', $this->before);
|
||||
|
||||
if (!empty($this->rows)) {
|
||||
$html .= '<table class="form-table"><tbody>' . implode('', $this->rows) . '</tbody></table>';
|
||||
$inner .= '<table class="form-table"><tbody>' . implode('', $this->rows) . '</tbody></table>';
|
||||
}
|
||||
|
||||
$html .= implode('', $this->after);
|
||||
return $html;
|
||||
$inner .= implode('', $this->after);
|
||||
|
||||
$success = $this->success_msg !== '' ? ' data-success-msg="' . esc_attr($this->success_msg) . '"' : '';
|
||||
$form = '<form id="' . esc_attr($this->form_id) . '"'
|
||||
. ' action="' . esc_url($this->action) . '"'
|
||||
. ' method="post"'
|
||||
. ' data-method="' . esc_attr($this->rest_method) . '"'
|
||||
. $success . '>'
|
||||
. $inner
|
||||
. '</form>';
|
||||
|
||||
$heading = $this->heading !== '' ? '<h2>' . esc_html($this->heading) . '</h2>' : '';
|
||||
|
||||
return implode('', $this->notices)
|
||||
. '<div class="form-wrap">' . $heading . $form . '</div>';
|
||||
}
|
||||
|
||||
public function output(): void
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace Reservair\Layout;
|
||||
|
||||
/**
|
||||
* Fluent builder for multi-column admin page layouts.
|
||||
*
|
||||
* Lets a page declare the shape it wants (e.g. a two-column split) without
|
||||
* committing to any markup or styling. Each column's content is supplied as a
|
||||
* callable that echoes — inline HTML and <script> blocks work as usual.
|
||||
*
|
||||
* Usage:
|
||||
* RsvColumnLayout::split('1:2')
|
||||
* ->column(function () { ?>
|
||||
* <h2>Add timetable</h2>
|
||||
* ...
|
||||
* <?php })
|
||||
* ->column(function () { ?>
|
||||
* <div id="availability_table"></div>
|
||||
* ...
|
||||
* <?php })
|
||||
* ->output();
|
||||
*/
|
||||
class RsvColumnLayout
|
||||
{
|
||||
/** @var list<callable():void> Column content, in left-to-right order. */
|
||||
private array $columns = [];
|
||||
|
||||
/** @var list<int> Relative column weights, parsed from the ratio. */
|
||||
private array $weights;
|
||||
|
||||
private function __construct(string $ratio)
|
||||
{
|
||||
$this->weights = array_map('intval', explode(':', $ratio));
|
||||
}
|
||||
|
||||
/**
|
||||
* Side-by-side columns that stack on narrow screens.
|
||||
*
|
||||
* @param string $ratio Relative column widths, e.g. '1:1', '1:2'.
|
||||
*/
|
||||
public static function split(string $ratio = '1:1'): static
|
||||
{
|
||||
return new static($ratio);
|
||||
}
|
||||
|
||||
/** Adds the next column. $render echoes the column's content. */
|
||||
public function column(callable $render): static
|
||||
{
|
||||
$this->columns[] = $render;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function render(): string
|
||||
{
|
||||
$cols = '';
|
||||
foreach ($this->columns as $i => $render) {
|
||||
$grow = $this->weights[$i] ?? end($this->weights) ?: 1;
|
||||
$cols .= '<div class="rsv-col" style="--rsv-col-grow:' . (int) $grow . '">'
|
||||
. $this->capture($render)
|
||||
. '</div>';
|
||||
}
|
||||
return '<div class="rsv-cols">' . $cols . '</div>';
|
||||
}
|
||||
|
||||
public function output(): void
|
||||
{
|
||||
echo $this->render();
|
||||
}
|
||||
|
||||
/** Runs an echoing callable and returns what it printed. */
|
||||
private function capture(callable $render): string
|
||||
{
|
||||
ob_start();
|
||||
$render();
|
||||
return ob_get_clean();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace Reservair\Templating\Elements;
|
||||
|
||||
use Reservair\Templating\RsvTemplateElement;
|
||||
use Reservair\Templating\RsvTemplateSymbols;
|
||||
|
||||
/**
|
||||
* Renders accept / refuse action buttons for a reservation, for the maintainer
|
||||
* approval email. The links come from the template's accept_url and refuse_url
|
||||
* symbols; the button labels can be overridden with the accept-label and
|
||||
* refuse-label attributes.
|
||||
*/
|
||||
class RsvReservationActionsElement implements RsvTemplateElement {
|
||||
|
||||
/** Inline styles, since email clients ignore stylesheets. */
|
||||
private const string ACCEPT_STYLE = 'display:inline-block;padding:10px 18px;margin-right:8px;background:#2e7d32;color:#ffffff;text-decoration:none;border-radius:4px;font-weight:bold;';
|
||||
private const string REFUSE_STYLE = 'display:inline-block;padding:10px 18px;background:#c62828;color:#ffffff;text-decoration:none;border-radius:4px;font-weight:bold;';
|
||||
|
||||
public function render(RsvTemplateSymbols $symbols): string {
|
||||
$accept_url = (string) $symbols->get('accept_url', '');
|
||||
$refuse_url = (string) $symbols->get('refuse_url', '');
|
||||
if ($accept_url === '' && $refuse_url === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$accept_label = (string) $symbols->get('accept-label', 'Přijmout');
|
||||
$refuse_label = (string) $symbols->get('refuse-label', 'Odmítnout');
|
||||
|
||||
return '<a href="' . esc_url($accept_url) . '" style="' . self::ACCEPT_STYLE . '">' . esc_html($accept_label) . '</a>'
|
||||
. '<a href="' . esc_url($refuse_url) . '" style="' . self::REFUSE_STYLE . '">' . esc_html($refuse_label) . '</a>';
|
||||
}
|
||||
|
||||
public function symbols(): array {
|
||||
return ['accept-label', 'refuse-label'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace Reservair\Templating\Elements;
|
||||
|
||||
use Reservair\Templating\RsvTemplateElement;
|
||||
use Reservair\Templating\RsvTemplateSymbols;
|
||||
|
||||
/**
|
||||
* Emits the client-side summary placeholder. The browser-side RsvFormSender
|
||||
* locates this div after form submission and fills it with the visitor's
|
||||
* selected time slots.
|
||||
*/
|
||||
class RsvReservationSummaryElement implements RsvTemplateElement {
|
||||
|
||||
public function render(RsvTemplateSymbols $symbols): string {
|
||||
return '<div class="rsv-success-summary"></div>';
|
||||
}
|
||||
|
||||
public function symbols(): array {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace Reservair\Templating\Elements;
|
||||
|
||||
use Reservair\Templating\RsvTemplateElement;
|
||||
use Reservair\Templating\RsvTemplateSymbols;
|
||||
|
||||
/**
|
||||
* Renders a button that asks the form to clear itself. It only carries the
|
||||
* data-rsv-reset marker; RsvFormSender finds marked buttons in the success card
|
||||
* and links them to the form's cleanup. The label can be overridden with the
|
||||
* label attribute.
|
||||
*/
|
||||
class RsvResetFormButtonElement implements RsvTemplateElement {
|
||||
|
||||
public function render(RsvTemplateSymbols $symbols): string {
|
||||
$label = (string) $symbols->get('label', 'Odeslat znova');
|
||||
return '<button type="button" class="rsv-form-btn" data-rsv-reset>'
|
||||
. esc_html($label)
|
||||
. '</button>';
|
||||
}
|
||||
|
||||
public function symbols(): array {
|
||||
return ['label'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
# Templating
|
||||
|
||||
Templates allow to replace place values of symbols in text written in one language. Templating itself requires a language. Therefore the process combines two languages.
|
||||
|
||||
This plugin uses templates for success messages of forms & emails. The usage might expand in the future. That is one of the quality attributes of this requirement.
|
||||
|
||||
## Language
|
||||
|
||||
As both use cases are using HTML (one is an email and another a webpage), the templates in this plugin also uses HTML. The frontend for HTML is `RsvHtmlTemplateParser`, that transforms it into an internal structure. The input language can be changed by writing a new frontend for the compiler in the future.
|
||||
|
||||
The main advantage of HTML is that it can be easily extended with custom elements. But we do note that traditional custom elements using JS cannot be used, because JS would not work like that in emails for example.
|
||||
|
||||
Extensions and the plugin itself can register custom elements to templates, for example `<reservation-summary>` that auto-expands onto a nice summary of the selected time slots.
|
||||
|
||||
Atomic values and strings can be retrieved from submitted data using JSON Path RFC using this syntax: `{{ path }}`. The reason for JSON Path is the simplicity of implementation. We are careful not to overcomplicate the templating language, for a price of being less powerful. Helm language being the example of what not to do.
|
||||
|
||||
The language can be easily validated for symbols existence and validity.
|
||||
|
||||
## Custom elements
|
||||
|
||||
The Templating module calls `rsv-template-register-custom-elements` to register custom elements to templates. Plugins can subscribe to it and in the handler register their own custom elements.
|
||||
|
||||
Custom element has a symbol table with values in the input and outputs string. If the custom element has attributes, like `<custom-element attr="test">`, the symbol `attr` with value `test` will also be added to the symbol table.
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace Reservair\Templating;
|
||||
|
||||
/** A registered handler for a hyphenated custom element tag. */
|
||||
interface RsvTemplateElement {
|
||||
/** Renders the element to a trusted HTML string given the resolved symbol table. */
|
||||
public function render(RsvTemplateSymbols $symbols): string;
|
||||
|
||||
/**
|
||||
* Returns the symbol names this element understands — used by validation to
|
||||
* report missing or extra attributes.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function symbols(): array;
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
<?php
|
||||
|
||||
namespace Reservair\Templating;
|
||||
|
||||
use Reservair\Logger\Logger;
|
||||
|
||||
/**
|
||||
* Renders templates in two phases: first it substitutes {{ path }} interpolations
|
||||
* with values from the data, then it walks the HTML and expands the registered
|
||||
* custom elements. The public entry point for the module.
|
||||
*/
|
||||
class RsvTemplateEngine {
|
||||
|
||||
public readonly RsvTemplateRegistry $registry;
|
||||
|
||||
public function __construct(?RsvTemplateRegistry $registry = null) {
|
||||
$this->registry = $registry ?? new RsvTemplateRegistry();
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders $source as HTML. Interpolated scalar values are HTML-escaped;
|
||||
* custom elements emit their own trusted markup.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public function render(string $source, array $data = []): string {
|
||||
try {
|
||||
return $this->expand_elements(
|
||||
$this->interpolate($source, $data, escape: true),
|
||||
$data,
|
||||
);
|
||||
} catch (RsvTemplateException $e) {
|
||||
throw $e;
|
||||
} catch (\Throwable $e) {
|
||||
Logger::error($e);
|
||||
throw new RsvTemplateException('Template render failed: ' . $e->getMessage(), 0, $e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders $source for a plain-text context such as an email subject: values
|
||||
* are substituted without HTML-escaping and all tags are stripped.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public function render_plain(string $source, array $data = []): string {
|
||||
return trim(wp_strip_all_tags($this->interpolate($source, $data, escape: false)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists a template's problems without rendering it (empty = valid): empty
|
||||
* interpolations, unregistered custom elements, and attributes an element
|
||||
* does not declare.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function validate(string $source): array {
|
||||
$errors = [];
|
||||
|
||||
if (preg_match_all('/{{\s*([^}]*?)\s*}}/', $source, $matches)) {
|
||||
foreach ($matches[1] as $path) {
|
||||
if (trim($path) === '') {
|
||||
$errors[] = 'Empty interpolation: {{ }}';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($this->custom_elements($this->load($source)) as $element) {
|
||||
$handler = $this->registry->get($element->tagName);
|
||||
if ($handler === null) {
|
||||
$errors[] = "Unregistered custom element: <{$element->tagName}>";
|
||||
continue;
|
||||
}
|
||||
$allowed = $handler->symbols();
|
||||
foreach ($this->attributes($element) as $name => $value) {
|
||||
if (!in_array($name, $allowed, true)) {
|
||||
$errors[] = "Unknown attribute \"{$name}\" on <{$element->tagName}>";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Phase 1 — interpolation
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/** @param array<string, mixed> $data */
|
||||
private function interpolate(string $source, array $data, bool $escape): string {
|
||||
return preg_replace_callback('/{{\s*([^}]+?)\s*}}/', function (array $match) use ($data, $escape): string {
|
||||
$value = $this->resolve($match[1], $data);
|
||||
if (!is_scalar($value)) {
|
||||
return ''; // null and non-scalar (arrays/objects) render empty
|
||||
}
|
||||
$string = (string) $value;
|
||||
return $escape ? esc_html($string) : $string;
|
||||
}, $source) ?? $source;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Phase 2 — custom element expansion
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Replaces each registered custom element with its handler's output. The
|
||||
* element is swapped for a unique comment marker, the document is serialised,
|
||||
* and the markers are substituted for the (trusted) handler strings — so the
|
||||
* output is never re-escaped by the serialiser.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
private function expand_elements(string $html, array $data): string {
|
||||
// Skip the DOM round-trip unless a hyphenated tag could match a handler.
|
||||
if ($this->registry->all() === [] || !preg_match('/<[a-z][a-z0-9]*-/i', $html)) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
$dom = $this->load($html);
|
||||
$nonce = 'rsv-' . bin2hex(random_bytes(6));
|
||||
$replacements = [];
|
||||
|
||||
foreach ($this->custom_elements($dom) as $i => $element) {
|
||||
$handler = $this->registry->get($element->tagName);
|
||||
if ($handler === null) {
|
||||
continue; // leave unknown custom elements in place
|
||||
}
|
||||
$token = "{$nonce}-{$i}";
|
||||
$replacements["<!--{$token}-->"] = $handler->render(
|
||||
new RsvTemplateSymbols(array_merge($data, $this->attributes($element)))
|
||||
);
|
||||
$element->parentNode?->replaceChild($dom->createComment($token), $element);
|
||||
}
|
||||
|
||||
return strtr($this->serialize($dom), $replacements);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// JSON Path resolver
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Resolves a minimal JSON Path expression against $data.
|
||||
*
|
||||
* Supported forms: bare key, $.key, $.a.b, $.items[0], $['key'].
|
||||
* Returns null for a missing path; the renderer emits an empty string for null.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
private function resolve(string $path, array $data): mixed {
|
||||
$tokens = preg_split('/[\.\[\]]+/', $path, -1, PREG_SPLIT_NO_EMPTY) ?: [];
|
||||
$current = $data;
|
||||
|
||||
foreach ($tokens as $token) {
|
||||
if ($token === '$') {
|
||||
continue; // root sigil
|
||||
}
|
||||
$token = trim($token, "'\""); // strip bracket-notation quotes
|
||||
if (!is_array($current) || !array_key_exists($token, $current)) {
|
||||
return null;
|
||||
}
|
||||
$current = $current[$token];
|
||||
}
|
||||
|
||||
return $current;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// DOM helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private function load(string $html): \DOMDocument {
|
||||
$dom = new \DOMDocument();
|
||||
$prev = libxml_use_internal_errors(true);
|
||||
// The XML encoding hint forces UTF-8; NOIMPLIED/NODEFDTD keep the fragment
|
||||
// free of the synthetic <html>/<body>/doctype wrappers libxml adds.
|
||||
$dom->loadHTML(
|
||||
'<?xml encoding="UTF-8">' . $html,
|
||||
LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD,
|
||||
);
|
||||
libxml_clear_errors();
|
||||
libxml_use_internal_errors($prev);
|
||||
|
||||
// Drop the encoding hint, which libxml leaves behind as a stray node.
|
||||
foreach (iterator_to_array($dom->childNodes) as $node) {
|
||||
if ($node instanceof \DOMProcessingInstruction
|
||||
|| ($node instanceof \DOMComment && str_contains((string) $node->nodeValue, 'xml encoding'))) {
|
||||
$dom->removeChild($node);
|
||||
}
|
||||
}
|
||||
|
||||
return $dom;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every hyphenated element in document order — registered or not.
|
||||
*
|
||||
* @return list<\DOMElement>
|
||||
*/
|
||||
private function custom_elements(\DOMDocument $dom): array {
|
||||
$elements = [];
|
||||
foreach ((new \DOMXPath($dom))->query('//*[contains(local-name(), "-")]') as $node) {
|
||||
if ($node instanceof \DOMElement) {
|
||||
$elements[] = $node;
|
||||
}
|
||||
}
|
||||
return $elements;
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
private function attributes(\DOMElement $element): array {
|
||||
$attributes = [];
|
||||
if ($element->hasAttributes()) {
|
||||
foreach ($element->attributes as $attribute) {
|
||||
$attributes[$attribute->name] = $attribute->value;
|
||||
}
|
||||
}
|
||||
return $attributes;
|
||||
}
|
||||
|
||||
private function serialize(\DOMDocument $dom): string {
|
||||
$html = '';
|
||||
foreach ($dom->childNodes as $child) {
|
||||
$html .= $dom->saveHTML($child);
|
||||
}
|
||||
return $html;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Reservair\Templating;
|
||||
|
||||
class RsvTemplateException extends \RuntimeException {}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace Reservair\Templating;
|
||||
|
||||
/** Holds the mapping from custom element tag names to their handlers. */
|
||||
class RsvTemplateRegistry {
|
||||
/** @var array<string, RsvTemplateElement> */
|
||||
private array $elements = [];
|
||||
|
||||
public function register(string $tag, RsvTemplateElement $element): void {
|
||||
$this->elements[$tag] = $element;
|
||||
}
|
||||
|
||||
public function get(string $tag): ?RsvTemplateElement {
|
||||
return $this->elements[$tag] ?? null;
|
||||
}
|
||||
|
||||
/** @return array<string, RsvTemplateElement> */
|
||||
public function all(): array {
|
||||
return $this->elements;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extends a wp_kses allowlist so the registered custom elements survive
|
||||
* sanitization of admin HTML. Each element contributes its tag and the
|
||||
* attributes it declares via symbols().
|
||||
*
|
||||
* @param array<string, mixed> $base A wp_kses allowed-html map to extend.
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function kses_allowed(array $base = []): array {
|
||||
foreach ($this->elements as $tag => $element) {
|
||||
$attributes = [];
|
||||
foreach ($element->symbols() as $name) {
|
||||
$attributes[$name] = true;
|
||||
}
|
||||
$base[$tag] = $attributes;
|
||||
}
|
||||
return $base;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Reservair\Templating;
|
||||
|
||||
/** Immutable symbol table passed to custom-element handlers. */
|
||||
class RsvTemplateSymbols {
|
||||
/** @param array<string, mixed> $data */
|
||||
public function __construct(private readonly array $data) {}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function all(): array {
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
public function get(string $name, mixed $default = null): mixed {
|
||||
return $this->data[$name] ?? $default;
|
||||
}
|
||||
}
|
||||
+15
-1
@@ -1,4 +1,8 @@
|
||||
<?php
|
||||
|
||||
use Reservair\Templating\Elements\RsvReservationSummaryElement;
|
||||
use Reservair\Templating\Elements\RsvReservationActionsElement;
|
||||
use Reservair\Templating\Elements\RsvResetFormButtonElement;
|
||||
/**
|
||||
* Plugin Name: Reservair
|
||||
* Description: A reservation and booking system for WordPress. Site visitors browse available time slots and submit reservation requests via a Gutenberg block; administrators manage timetables, services, forms, and reservations from the WordPress admin panel.
|
||||
@@ -29,7 +33,7 @@ register_activation_hook( __FILE__, [ 'RsvInstaller', 'install' ] );
|
||||
* plugins we might interact with) is fully loaded.
|
||||
*/
|
||||
function rsv_bootstrap(): void {
|
||||
global $rsv_form_registry;
|
||||
global $rsv_form_registry, $rsv_template_registry;
|
||||
|
||||
// Re-grant the custom capability after a plugin *update* (the activation hook
|
||||
// only runs on activate). No-op once the stored version matches.
|
||||
@@ -47,6 +51,16 @@ function rsv_bootstrap(): void {
|
||||
$rsv_form_registry->register( 'button', new RsvButtonElementHandler() );
|
||||
$rsv_form_registry->register( 'reservation', new RsvFormReservationElementHandler() );
|
||||
$rsv_form_registry->register( 'output-reservation-summary', new RsvReservationSummaryElementHandler() );
|
||||
$rsv_form_registry->register( 'output-text', new RsvOutputTextElementHandler() );
|
||||
|
||||
// Template custom-element registry. Extensions register via the action.
|
||||
add_action( 'rsv-template-register-custom-elements', function ( \Reservair\Templating\RsvTemplateRegistry $reg ): void {
|
||||
$reg->register( 'reservation-summary', new RsvReservationSummaryElement() );
|
||||
$reg->register( 'reservation-actions', new RsvReservationActionsElement() );
|
||||
$reg->register( 'reset-form-button', new RsvResetFormButtonElement() );
|
||||
} );
|
||||
$rsv_template_registry = new \Reservair\Templating\RsvTemplateRegistry();
|
||||
do_action( 'rsv-template-register-custom-elements', $rsv_template_registry );
|
||||
}
|
||||
|
||||
add_action( 'plugins_loaded', 'rsv_bootstrap' );
|
||||
|
||||
+5
-2
@@ -1,5 +1,6 @@
|
||||
import './client.js';
|
||||
|
||||
// The client bundle (custom elements, form sender, client styles) is loaded
|
||||
// separately under the shared `rsv-client` handle — see rsv_enqueue_admin_assets.
|
||||
// Bundling it here too would run customElements.define() twice in the editor.
|
||||
import '../assets/css/RsvAdminStyle.css';
|
||||
|
||||
import { RsvDataGrid } from '../assets/js/elements/RsvDatagrid.js';
|
||||
@@ -7,6 +8,7 @@ import { RsvInlineFormBuilder } from '../assets/js/forms/RsvInlineFormBuilder.js
|
||||
import './components/admin.js';
|
||||
import { RsvAdminForm } from '../assets/js/forms/RsvAdminForm.js';
|
||||
import { RsvReservationResource } from '../assets/js/datasource/RsvReservationResource.js';
|
||||
import { RsvFormDefinitionResource } from '../assets/js/datasource/RsvFormDefinitionResource.js';
|
||||
import { RsvTimetableResource } from '../assets/js/datasource/RsvTimetableResource.js';
|
||||
import { RsvTimetableCapacityResource } from '../assets/js/datasource/RsvTimetableCapacityResource.js';
|
||||
import { RsvTimetableReservationResource } from '../assets/js/datasource/RsvTimetableReservationResource.js';
|
||||
@@ -16,6 +18,7 @@ window.RsvDataGrid = RsvDataGrid;
|
||||
window.RsvInlineFormBuilder = RsvInlineFormBuilder;
|
||||
window.RsvAdminForm = RsvAdminForm;
|
||||
window.RsvReservationResource = RsvReservationResource;
|
||||
window.RsvFormDefinitionResource = RsvFormDefinitionResource;
|
||||
window.RsvTimetableResource = RsvTimetableResource;
|
||||
window.RsvTimetableCapacityResource = RsvTimetableCapacityResource;
|
||||
window.RsvTimetableReservationResource = RsvTimetableReservationResource;
|
||||
|
||||
@@ -1,99 +1,3 @@
|
||||
import { get_rest_url } from '../../assets/js/RsvApi.js';
|
||||
|
||||
async function fetch_reservations_to_confirm(object_id) {
|
||||
const url = `/wordpress/wp-json/reservations/v1/object/${object_id}/timetable/reservation/unconfirmed`;
|
||||
return await fetch(url, {
|
||||
method: 'GET'
|
||||
}).then(x => x.json());
|
||||
}
|
||||
|
||||
async function confirm_reservation(confirmation_code) {
|
||||
const url = `/wordpress/wp-json/reservations/v1/accept/${confirmation_code}`;
|
||||
const x = await fetch(url, {
|
||||
method: 'GET'
|
||||
});
|
||||
}
|
||||
|
||||
async function refuse_reservation(confirmation_code) {
|
||||
const url = `/wordpress/wp-json/reservations/v1/refuse/${confirmation_code}`;
|
||||
const x = await fetch(url, {
|
||||
method: 'GET'
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
async function render_unconfirmed_reservations_table(self) {
|
||||
const reservations = await fetch_reservations_to_confirm(self.object_id);
|
||||
const rows = reservations.map(reservation => {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td>${reservation.date}</td>
|
||||
<td>${get_format_time(new Date(`${reservation.date}T${reservation.start}`))}</td>
|
||||
<td>${get_format_time(add_minutes(new Date(`${reservation.date}T${reservation.start}`), parseInt(reservation.num_minutes)))}</td>
|
||||
<td>${reservation.num_minutes} min</td>
|
||||
<td>${reservation.email}</td>
|
||||
`;
|
||||
|
||||
let td = document.createElement('td');
|
||||
let confirm_button = document.createElement('button');
|
||||
confirm_button.classList.add('button');
|
||||
confirm_button.classList.add('button-primary');
|
||||
confirm_button.onclick = function() {
|
||||
confirm_reservation(reservation.confirmation_code)
|
||||
.then(x => self.refresh());
|
||||
};
|
||||
confirm_button.innerText = "Confirm";
|
||||
td.appendChild(confirm_button);
|
||||
|
||||
let refuse_button = document.createElement('button');
|
||||
refuse_button.classList.add('button');
|
||||
refuse_button.classList.add('button-secondary');
|
||||
refuse_button.onclick = function() {
|
||||
confirm_reservation(reservation.confirmation_code)
|
||||
.then(x => self.refresh());
|
||||
};
|
||||
refuse_button.innerText = "Refuse";
|
||||
td.appendChild(refuse_button);
|
||||
row.appendChild(td);
|
||||
|
||||
return row;
|
||||
});
|
||||
self.body.replaceChildren(...rows);
|
||||
}
|
||||
|
||||
function create_unconfirmed_reservations(object_id, container) {
|
||||
let table = document.createElement('table');
|
||||
table.classList.add('widefat');
|
||||
|
||||
let header = document.createElement('thead');
|
||||
header.innerHTML = `
|
||||
<tr>
|
||||
<th>Date</th>
|
||||
<th>From</th>
|
||||
<th>To</th>
|
||||
<th>Length</th>
|
||||
<th>Email</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
`;
|
||||
|
||||
table.appendChild(header);
|
||||
let body = document.createElement('tbody');
|
||||
|
||||
table.appendChild(body);
|
||||
|
||||
container.appendChild(table);
|
||||
|
||||
return {
|
||||
object_id: object_id,
|
||||
container: container,
|
||||
body: body,
|
||||
refresh() {
|
||||
render_unconfirmed_reservations_table(this);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function create_notice(id, type, mesg) {
|
||||
let container = document.createElement('div');
|
||||
container.id = id;
|
||||
@@ -107,45 +11,3 @@ export function show_notice(target, type, mesg) {
|
||||
const notice = create_notice('test', type, mesg);
|
||||
target.prepend(notice);
|
||||
}
|
||||
|
||||
async function error_handler(error) {
|
||||
if(error.body != null && error.body.message != null) {
|
||||
show_notice(error.target, 'error', error.body.message);
|
||||
}
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
|
||||
async function delete_action(id) {
|
||||
return await fetch(get_rest_url(`action/${id}`), {
|
||||
method: 'DELETE'
|
||||
});
|
||||
}
|
||||
|
||||
function collect_selected_actions(target) {
|
||||
return Array.from(target.querySelectorAll('input[type="checkbox"].action-selector:checked')).map(x =>
|
||||
x.value
|
||||
);
|
||||
}
|
||||
|
||||
async function delete_object(id) {
|
||||
return await fetch(get_rest_url(`object/${id}`), {
|
||||
method: 'DELETE'
|
||||
});
|
||||
}
|
||||
|
||||
async function set_object_actions(id, actions) {
|
||||
return await fetch(get_rest_url(`object/${id}/action`), {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(actions)
|
||||
});
|
||||
}
|
||||
|
||||
function inline_edit_row() {
|
||||
let row = document.createElement('tr');
|
||||
row.classList.add('iedit author-self level-0 post-1 type-post status-publish format-standard hentry category-uncategorized');
|
||||
return row;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user