Plugin Directory

Changeset 3816012


Ignore:
Timestamp:
11/22/2026 01:40:27 AM (2 hours ago)
Author:
sturmbusinesssolutions
Message:

Release 1.0.3 – frei konfigurierbare Terminkategorien

Location:
sbs-kalender-assistent
Files:
12 added
4 edited

Legend:

Unmodified
Added
Removed
  • sbs-kalender-assistent/trunk/public-calendar.js

    r3813890 r3816012  
    2424        const today = root.querySelector('.sbs-cal-today');
    2525        let selected, refreshId = 0, booking = false;
     26
     27        function updateReminder() {
     28            const checkbox = form.elements.reminder_opt_in;
     29            const email = form.elements.reminder_email;
     30            const available = selected && selected.start * 1000 > Date.now() + Number(root.dataset.reminderHours) * 3600000;
     31            checkbox.disabled = !available;
     32            if (!available) checkbox.checked = false;
     33            form.querySelector('.sbs-cal-reminder-choice').hidden = !available;
     34            form.querySelector('.sbs-cal-reminder-unavailable').hidden = !selected || Boolean(available);
     35            const requested = Boolean(available && checkbox.checked);
     36            email.disabled = !requested;
     37            email.required = requested;
     38            form.querySelector('.sbs-cal-reminder-email').hidden = !requested;
     39            if (!requested) email.value = '';
     40        }
    2641
    2742        function updateContact() {
    … …  
    4257            field.querySelector('span').textContent = type === 'video' ? 'E-Mail-Adresse' : whatsapp ? 'WhatsApp-Nummer mit Ländervorwahl' : 'Telefonnummer';
    4358            form.querySelector('.sbs-cal-onsite').hidden = type !== 'onsite';
    44             form.querySelector('[type="submit"]').textContent = type === 'onsite' ? 'Vor-Ort-Termin anfragen' : 'Termin verbindlich buchen';
     59            updateReminder();
     60            form.querySelector('[type="submit"]').textContent = type === 'onsite' && root.dataset.onsiteFixed !== '1' ? 'Vor-Ort-Termin anfragen' : 'Termin verbindlich buchen';
    4561        }
    4662
    … …  
    7894            const offer = hex.replace(/^(........)(....)(....)(....)(............)$/, '$1-$2-$3-$4-$5');
    7995            selected = {start: slot.start, duration: length, offer, department: department.value, employee: employee.value};
     96            updateContact();
    8097            form.querySelector('.sbs-cal-selected').textContent = label;
    8198            form.hidden = false;
    … …  
    228245        });
    229246        if (form) {
     247            form.elements.reminder_opt_in.addEventListener('change', () => {
     248                updateReminder();
     249                if (form.elements.reminder_opt_in.checked && form.elements.appointment_type.value === 'video') {
     250                    form.elements.reminder_email.value = form.elements.contact.value;
     251                }
     252            });
    230253            form.elements.appointment_type.addEventListener('change', () => {
    231254                form.elements.contact.value = '';
    … …  
    239262                booking = true;
    240263                const controls = [date, duration, department, employee, view, today, ...form.elements];
    241                 const body = {...selected, name: form.elements.visitor.value, reason: form.elements.reason.value, appointment_type: form.elements.appointment_type.value, contact: form.elements.contact.value, whatsapp_consent: form.elements.whatsapp_consent.checked};
     264                const body = {...selected, name: form.elements.visitor.value, reason: form.elements.reason.value, appointment_type: form.elements.appointment_type.value, contact: form.elements.contact.value, whatsapp_consent: form.elements.whatsapp_consent.checked, reminder_opt_in: form.elements.reminder_opt_in.checked, reminder_email: form.elements.reminder_email.value, reminder_hours: Number(root.dataset.reminderHours)};
    242265                controls.forEach(control => { control.disabled = true; });
    243266                try {
  • sbs-kalender-assistent/trunk/public-calendar.php

    r3813890 r3816012  
    7373        if ($choice) {
    7474            $choice['offer'] = $offer;
    75             $status = SBSKAAS_Kalender::book($choice, $name, $reason, $type, $contact);
     75            $status = SBSKAAS_Kalender::book($choice, $name, $reason, $type, $contact, [
     76                'opt_in'=>$request->get_param('reminder_opt_in') === true,
     77                'email'=>sanitize_text_field($request->get_param('reminder_email') ?? ''),
     78                'hours'=>$request->get_param('reminder_hours') ?? SBSKAAS_Reminders::hours(),
     79            ]);
    7680            if ($status === 'ok') return ['message'=>SBSKAAS_Kalender::confirmation($type, SBSKAAS_Kalender::label($start))];
     81            if ($status === 'reminder_invalid') return new WP_Error('calendar_reminder', 'Bitte prüfen Sie die E-Mail-Adresse für Ihre Erinnerung. Der Erinnerungszeitpunkt muss noch in der Zukunft liegen. Sie können auch ohne Erinnerung buchen.', ['status'=>400]);
    7782            if ($status === 'limited') return new WP_Error('calendar_limit', SBSKAAS_Kalender::BOOKING_LIMIT_MESSAGE, ['status'=>429]);
    7883            if ($status === 'retry') return new WP_Error('calendar_retry', 'Buchung derzeit nicht möglich. Bitte versuchen Sie es erneut.', ['status'=>503]);
    … …  
    8287
    8388    static function shortcode() {
    84         wp_enqueue_script('sbs-kalender-assistent-public', plugin_dir_url(__FILE__) . 'public-calendar.js', [], '0.2.18', true);
    85         wp_enqueue_style('sbs-kalender-assistent-public', plugin_dir_url(__FILE__) . 'public-calendar.css', [], '0.2.18');
     89        wp_enqueue_script('sbs-kalender-assistent-public', plugin_dir_url(__FILE__) . 'public-calendar.js', [], '1.0.3', true);
     90        wp_enqueue_style('sbs-kalender-assistent-public', plugin_dir_url(__FILE__) . 'public-calendar.css', [], '1.0.3');
    8691        $today = new DateTimeImmutable('today', wp_timezone());
    8792        $privacy = get_privacy_policy_url();
    8893        ob_start();
    8994        ?>
    90         <section class="sbs-kalender" data-calendar-source="standalone" aria-label="SBS Kalender Assistent"
     95        <section class="sbs-kalender" data-calendar-source="standalone" data-reminder-hours="<?php echo esc_attr(SBSKAAS_Reminders::hours()); ?>" data-onsite-fixed="<?php echo SBSKAAS_Kalender::onsite_location() ? '1' : '0'; ?>" aria-label="SBS Kalender Assistent"
    9196            data-slots="<?php echo esc_url(rest_url(self::ROUTE . '/slots')); ?>"
    9297            data-book="<?php echo esc_url(rest_url(self::ROUTE . '/book')); ?>">
    … …  
    122127                    <p><label>Name <input name="visitor" autocomplete="name" required minlength="2" maxlength="120"></label></p>
    123128                    <p><label>Termingrund <select name="reason" required><option value="">Bitte auswählen</option>
    124                     <?php foreach (SBSKAAS_Kalender::REASONS as $reason) : ?>
     129                    <?php foreach (SBSKAAS_Kalender::reasons() as $reason) : ?>
    125130                        <option><?php echo esc_html($reason); ?></option>
    126131                    <?php endforeach; ?>
    127132                    </select></label></p>
    128133                    <p><label>Terminart <select name="appointment_type" required><option value="">Bitte auswählen</option>
    129                     <?php foreach (SBSKAAS_Kalender::TYPES as $type=>$label) : ?>
     134                    <?php foreach (SBSKAAS_Kalender::appointment_types() as $type=>$label) : ?>
    130135                        <option value="<?php echo esc_attr($type); ?>"><?php echo esc_html($label); ?></option>
    131136                    <?php endforeach; ?>
    … …  
    133138                    <p class="sbs-cal-contact" hidden><label><span></span> <input name="contact" disabled maxlength="190"></label></p>
    134139                    <p class="sbs-cal-whatsapp-consent" hidden><label><input type="checkbox" name="whatsapp_consent" disabled> Ich stimme der Kontaktaufnahme über WhatsApp ausschließlich für diesen Termin zu.</label></p>
    135                     <p class="sbs-cal-onsite" hidden>Wir rufen Sie zurück, um Ort und Details persönlich zu vereinbaren.</p>
     140                    <p class="sbs-cal-onsite" hidden><?php
     141                        echo nl2br(esc_html(SBSKAAS_Kalender::onsite_location()
     142                            ? 'Standort: ' . SBSKAAS_Kalender::onsite_location()
     143                            : 'Wir rufen Sie zurück, um Ort und Details persönlich zu vereinbaren.'));
     144                    ?></p>
     145                    <p class="sbs-cal-reminder-choice"><label><input type="checkbox" name="reminder_opt_in"> <?php echo esc_html(SBSKAAS_Reminders::label()); ?></label></p>
     146                    <p class="sbs-cal-reminder-email" hidden><label>E-Mail-Adresse für die Erinnerung <input type="email" name="reminder_email" autocomplete="email" maxlength="190" disabled></label></p>
     147                    <p class="sbs-cal-reminder-unavailable" hidden>Für diese kurzfristige Buchung ist der Erinnerungszeitpunkt bereits verstrichen. Sie können den Termin ohne Erinnerung buchen.</p>
    136148                    <button type="submit">Termin verbindlich buchen</button>
    137149                    <button type="button" class="sbs-cal-cancel">Abbrechen</button>
  • sbs-kalender-assistent/trunk/readme.txt

    r3813890 r3816012  
    55Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 0.2.18
     7Stable tag: 1.0.3
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    1818* Bookings with configurable appointment lengths.
    1919* Booking hours, configurable departments, staff assignments, and staff absences.
    20 * Phone calls, video calls, WhatsApp voice or video calls, and in-person requests.
     20* Define your own appointment categories, with one entry per line and your own wording.
     21* Select which appointment types visitors can book and customize their labels.
     22* Set a provider location, full address, and optional directions for in-person appointments.
     23* Phone calls, video calls, WhatsApp voice or video calls, and in-person appointments.
    2124* Email notifications to assigned staff with a configured email address.
    2225* A booking attempt limit per IP address.
     26* Optional customer email reminders with an unchecked opt-in checkbox and configurable timing.
    2327* Optional chat booking with the separately available SBS KI Business Assistant.
    2428
     29Reminder emails are sent only when a visitor explicitly requests them during booking. The default timing is 24 hours before the appointment and can be set from 1 to 168 hours in the dashboard. An email address is required for an opted-in reminder. Short-notice appointments can still be booked without a reminder. Existing bookings are not enrolled automatically.
     30
    2531Booking details are stored in your WordPress database. The public calendar displays availability only. The scheduled cleanup removes records after 30 days from the appointment end or cancellation.
     32
     33Suitable for appointment scheduling in massage studios, hair salons, therapy practices, medical practices, trades, and other small businesses.
    2634
    2735== Installation ==
    … …  
    30382. Select a published privacy policy under Settings > Privacy.
    31393. Open SBS Kalender to add staff and business hours, then enable bookable hours. With a compatible Business Assistant active, find the calendar under Business Assistant > Terminkalender.
    32 4. Add the shortcode [sbskaas_calendar] to your booking page.
    33 5. Make a test booking and verify staff email delivery.
     404. Under Appointment types and location, select the offered types and enter the provider address for in-person appointments.
     415. Add the shortcode [sbskaas_calendar] to your booking page.
     426. Set the optional reminder lead time in the calendar dashboard.
     437. Make a test booking and verify staff and opted-in customer reminder email delivery.
    3444
    3545== Frequently Asked Questions ==
    … …  
    4757The plugin uses the WordPress mail function. Delivery depends on your site's mail configuration.
    4858
     59= Can I offer only in-person appointments? =
     60
     61Yes. Enable only the in-person appointment type in the calendar dashboard. You can customize its label and enter the provider name, address, and optional directions. Visitors see the location during booking and in the on-screen confirmation. Assigned staff receive the location in their notification email. Without a provider address, in-person requests keep the callback workflow to arrange the location.
     62
     63= How do optional email reminders work? =
     64
     65Visitors must actively select the unchecked reminder checkbox or explicitly agree in calendar chat. Only then are their reminder email address, consent time, scheduled reminder time, and sending status saved. Cancellation removes the reminder address and stops pending reminders. Reminder data is deleted with the booking according to the 30-day retention period.
     66
     67The reminder worker checks due reminders every five minutes through WP-Cron. WordPress normally triggers WP-Cron on page visits. Configure a regular server cron invocation for timely reminders on low-traffic sites. Emails use wp_mail(), so delivery depends on the site's mail configuration. Failed mail submissions are retried up to three times, 15 minutes apart, while the appointment is still in the future. A sending operation interrupted with unknown delivery status is not retried automatically, to avoid duplicates. Its status is shown in the dashboard.
     68
    4969== Changelog ==
     70
     71= 1.0.3 =
     72* Admin-defined appointment categories are used in both the public booking form and chat booking.
     73* Existing bookings retain their original category; default categories remain until customized.
     74
     75= 1.0.2 =
     76* Sanitize submitted appointment settings recursively while preserving address line breaks.
     77* Remove internal staff-permissions notes from the production package.
     78
     79= 1.0.1 =
     80* Prepare the booking table identifier in the staff booking overview with the %i placeholder.
     81
     82= 1.0.0 =
     83* Add voluntary email reminders with explicit per-booking opt-in in the public form and calendar chat.
     84* Configure reminder timing from 1 to 168 hours before the appointment (default: 24 hours).
     85* Track reminder status, prevent duplicate processing, and clear reminder data on cancellation.
     86* Preserve existing booking data and settings during the reminder schema upgrade.
     87
     88
     89= 0.2.20 =
     90* Configure enabled appointment types and their display labels.
     91* Add a provider location and directions for in-person bookings.
     92* Apply enabled types to the booking form, chat prompts, and booking validation.
     93
     94= 0.2.19 =
     95* Add staff permissions for viewing and managing calendar bookings.
     96
    5097
    5198= 0.2.18 =
  • sbs-kalender-assistent/trunk/sbs-termin-kalender.php

    r3813890 r3816012  
    88 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
    99 * Text Domain: sbs-kalender-assistent
    10  * Version: 0.2.18
     10 * Version: 1.0.3
    1111 * Requires at least: 6.4
    1212 * Requires PHP: 7.4
    1313 */
    1414if (!defined('ABSPATH')) exit;
     15require_once __DIR__.'/sbs-staff-access.php';
     16SBS_Staff_Access::register('calendar',array('sbs_calendar_view', 'sbs_calendar_manage'),array('sbs_calendar_view'));
    1517
    1618final class SBSKAAS_Kalender {
    … …  
    5860        wp_safe_redirect(self::url());
    5961        exit;
     62    }
     63
     64    static function appointment_options() {
     65        $defaults = [
     66            'types'=>self::TYPES,
     67            'location_name'=>'',
     68            'location_address'=>'',
     69            'location_directions'=>'',
     70        ];
     71        return array_replace($defaults, (array)get_option('sbskaas_appointment_options', []));
     72    }
     73
     74    static function appointment_types() {
     75        return array_intersect_key((array)self::appointment_options()['types'], self::TYPES);
     76    }
     77
     78    static function type_label($type) {
     79        return self::appointment_types()[$type] ?? self::TYPES[$type] ?? '';
     80    }
     81
     82    static function onsite_location() {
     83        $options = self::appointment_options();
     84        if ($options['location_address'] === '') return '';
     85        return implode("\n", array_filter([
     86            $options['location_name'], $options['location_address'], $options['location_directions'],
     87        ], static function ($value) { return $value !== ''; }));
     88    }
     89
     90    static function type_prompt() {
     91        $choices = [];
     92        $number = 1;
     93        foreach (self::appointment_types() as $label) {
     94            $choices[] = $number++ . ') ' . $label;
     95        }
     96        return 'Wie möchten Sie den Termin wahrnehmen? ' . implode(', ', $choices) . '.';
     97    }
     98
     99    static function save_appointment_options() {
     100        if (!current_user_can('manage_options')) wp_die('Nicht berechtigt.');
     101        check_admin_referer('sbskaas_appointment_options');
     102        $input = map_deep(wp_unslash($_POST['appointment_options'] ?? []), 'sanitize_textarea_field');
     103        if (!is_array($input)) wp_die('Bitte prüfen Sie die Termineinstellungen.');
     104        $types = [];
     105        foreach (self::TYPES as $type=>$default) {
     106            if (empty($input['enabled'][$type])) continue;
     107            $label = sanitize_text_field($input['labels'][$type] ?? $default);
     108            if ($label === '' || mb_strlen($label) > 80) wp_die('Bitte geben Sie eine Terminart mit höchstens 80 Zeichen ein.');
     109            $types[$type] = $label;
     110        }
     111        if (!$types) wp_die('Bitte aktivieren Sie mindestens eine Terminart.');
     112        $normalized = array_map('mb_strtolower', array_values($types));
     113        if (count(array_unique($normalized)) !== count($normalized)) wp_die('Bitte verwenden Sie eindeutige Bezeichnungen für die Terminarten.');
     114        update_option('sbskaas_appointment_options', [
     115            'types'=>$types,
     116            'location_name'=>sanitize_text_field($input['location_name'] ?? ''),
     117            'location_address'=>sanitize_textarea_field($input['location_address'] ?? ''),
     118            'location_directions'=>sanitize_textarea_field($input['location_directions'] ?? ''),
     119        ], false);
     120        wp_safe_redirect(self::url());
     121        exit;
     122    }
     123
     124    static function appointment_fields() {
     125        $options = self::appointment_options();
     126        $enabled = self::appointment_types();
     127        echo '<h2>Terminarten und Standort</h2><form method="post" action="' . esc_url(admin_url('admin-post.php')) . '">';
     128        echo '<input type="hidden" name="action" value="sbskaas_appointment_options">';
     129        wp_nonce_field('sbskaas_appointment_options');
     130        echo '<p>Wählen Sie die angebotenen Terminarten. Die Bezeichnungen können Sie an Ihren Betrieb anpassen.</p>';
     131        foreach (self::TYPES as $type=>$default) {
     132            echo '<p><label><input type="checkbox" name="appointment_options[enabled][' . esc_attr($type) . ']" value="1" '
     133                . checked(isset($enabled[$type]), true, false) . '> ' . esc_html($default) . '</label> ';
     134            echo '<label>Bezeichnung <input maxlength="80" name="appointment_options[labels][' . esc_attr($type) . ']" value="'
     135                . esc_attr($enabled[$type] ?? $default) . '"></label></p>';
     136        }
     137        echo '<h3>Standort für Vor-Ort-Termine</h3>';
     138        echo '<p>Mit hinterlegter Adresse werden Vor-Ort-Termine direkt an diesem Standort gebucht. Ohne Adresse wird wie bisher ein Rückruf zur Ortsvereinbarung angefragt.</p>';
     139        echo '<p><label>Standortbezeichnung, z. B. Praxis oder Salon<br><input class="regular-text" name="appointment_options[location_name]" value="' . esc_attr($options['location_name']) . '"></label></p>';
     140        echo '<p><label>Vollständige Anbieteradresse<br><textarea class="large-text" rows="3" name="appointment_options[location_address]">' . esc_textarea($options['location_address']) . '</textarea></label></p>';
     141        echo '<p><label>Anfahrtshinweis (optional)<br><textarea class="large-text" rows="2" name="appointment_options[location_directions]">' . esc_textarea($options['location_directions']) . '</textarea></label></p>';
     142        submit_button('Terminarten und Standort speichern');
     143        echo '</form>';
    60144    }
    61145
    … …  
    117201            cancelled tinyint NOT NULL DEFAULT 0,
    118202            cancelled_at bigint unsigned NOT NULL DEFAULT 0,
     203            reminder_email varchar(190) NOT NULL DEFAULT '',
     204            reminder_consent_at bigint unsigned NOT NULL DEFAULT 0,
     205            reminder_at bigint unsigned NOT NULL DEFAULT 0,
     206            reminder_status varchar(12) NOT NULL DEFAULT '',
     207            reminder_attempts tinyint unsigned NOT NULL DEFAULT 0,
     208            reminder_retry_at bigint unsigned NOT NULL DEFAULT 0,
     209            reminder_sent_at bigint unsigned NOT NULL DEFAULT 0,
     210            reminder_location text,
    119211            PRIMARY KEY  (id),
    120212            UNIQUE KEY offer (offer),
    121             KEY staff_time (staff,starts)
     213            KEY staff_time (staff,starts),
     214            KEY reminder_due (reminder_status,reminder_at)
    122215        ) $charset;");
    123         if ($wpdb->get_var($wpdb->prepare("SHOW COLUMNS FROM %i LIKE %s", $table, "reason")) !== 'reason'
    124             || $wpdb->get_var($wpdb->prepare("SHOW COLUMNS FROM %i LIKE %s", $table, "appointment_type")) !== 'appointment_type'
    125             || $wpdb->get_var($wpdb->prepare("SHOW COLUMNS FROM %i LIKE %s", $table, "contact")) !== 'contact'
    126             || $wpdb->get_var($wpdb->prepare("SHOW COLUMNS FROM %i LIKE %s", $table, "cancelled_at")) !== 'cancelled_at') return;
     216        foreach (['reason', 'appointment_type', 'contact', 'cancelled_at', 'reminder_email', 'reminder_consent_at',
     217            'reminder_at', 'reminder_status', 'reminder_attempts', 'reminder_retry_at', 'reminder_sent_at', 'reminder_location'] as $column) {
     218            if ($wpdb->get_var($wpdb->prepare("SHOW COLUMNS FROM %i LIKE %s", $table, $column)) !== $column) return;
     219        }
    127220        // Earlier versions removed visitor details at cancellation but kept no cancellation timestamp.
    128221        $updated = $wpdb->query($wpdb->prepare(
    … …  
    130223        ));
    131224        if ($updated === false) return;
    132         update_option('sbskaas_schema', '4', false);
     225        update_option('sbskaas_schema', '5', false);
    133226        self::schedule_cleanup();
    134227    }
    135228
    136229    static function upgrade() {
    137         if (get_option('sbskaas_schema') !== '4') self::install();
     230        if (get_option('sbskaas_schema') !== '5') self::install();
    138231        else self::schedule_cleanup();
    139232        wp_add_privacy_policy_content('SBS Kalender Assistent',
    140233            '<p>Die Online-Terminbuchung verarbeitet den angegebenen Namen, Terminzeit, Dauer, Terminkategorie, Terminart, je nach Terminart E-Mail-Adresse, Telefonnummer oder WhatsApp-Nummer und die Zuordnung zum zuständigen Mitarbeiter. Die Angaben werden in dieser WordPress-Installation gespeichert. Bei Auswahl eines WhatsApp-Anrufs wird die ausdrückliche Zustimmung zur Kontaktaufnahme über WhatsApp für den gewählten Termin erfasst. Bei einer Buchung im Chat werden die Buchungsschritte lokal verarbeitet. Buchungen und Termingründe sind im Administrationsbereich sichtbar.</p>'
     234            . '<p>Nur auf ausdrücklichen Wunsch bei der Buchung wird eine E-Mail-Erinnerung versendet. Dafür werden die angegebene E-Mail-Adresse, der Zeitpunkt der Zustimmung, der gewählte Erinnerungszeitpunkt und der Versandstatus gespeichert. Bei einer Stornierung werden die Erinnerungsadresse und die Zustimmung entfernt. Bereits bestehende Buchungen erhalten keine automatische Erinnerung.</p>'
    141235            . '<p>Die Kalendereinträge werden beim täglichen Löschlauf gelöscht, sobald seit dem Terminende oder der Stornierung 30 Tage vergangen sind. Bei einer Stornierung werden Name, Terminkategorie und Kontaktdaten bereits unmittelbar aus dem Kalendereintrag entfernt. Ergänzen Sie für Ihre Website die Rechtsgrundlage, Empfänger und gegebenenfalls zusätzliche Datenflüsse.</p>');
    142236    }
    143237
    144238    static function schedule_cleanup() {
     239        SBSKAAS_Reminders::schedule();
    145240        if (!wp_next_scheduled(self::CLEANUP)) wp_schedule_event(time(), 'daily', self::CLEANUP);
    146241    }
    … …  
    148243    static function deactivate() {
    149244        wp_clear_scheduled_hook(self::CLEANUP);
     245        wp_clear_scheduled_hook(SBSKAAS_Reminders::HOOK);
    150246    }
    151247
    152248    static function delete_expired_bookings() {
    153         if (get_option('sbskaas_schema') !== '4') return;
     249        if (get_option('sbskaas_schema') !== '5') return;
    154250        global $wpdb;
    155251        $table = self::table();
    … …  
    288384    }
    289385
    290     static function book($choice, $name, $reason, $type, $contact) {
     386    static function book($choice, $name, $reason, $type, $contact, $reminder = []) {
    291387        global $wpdb;
    292388        $table = self::table();
    … …  
    294390        $start = $choice['start'];
    295391        $duration = $choice['duration'] ?? 30;
    296         if (!in_array($duration, self::durations(), true)) return 'unavailable';
     392        if (!isset(self::appointment_types()[$type]) || !in_array($duration, self::durations(), true)) return 'unavailable';
    297393        $lock = 'sbskaas_' . sha1(DB_NAME . ':' . $table . ':' . $staff);
    298394        if ((string) $wpdb->get_var($wpdb->prepare('SELECT GET_LOCK(%s, 3)', $lock)) !== '1') return 'retry';
    … …  
    301397            if ($wpdb->last_error) return 'retry';
    302398            if ($existing !== null) return (int) $existing ? 'unavailable' : 'ok';
     399            $reminderData = SBSKAAS_Reminders::prepare($reminder, $start);
     400            if ($reminderData === false) return 'reminder_invalid';
    303401            $attempt = self::reserve_booking_attempt();
    304402            if ($attempt !== 'ok') return $attempt;
    … …  
    307405            if ($wpdb->last_error) return 'retry';
    308406            $person = self::staff()[$staff] ?? [];
    309             $saved = $wpdb->insert($table, [
     407            $saved = $wpdb->insert($table, array_merge([
    310408                'offer'=>$choice['offer'], 'staff'=>$staff, 'staff_name'=>$person['name'] ?? '',
    311409                'starts'=>$start, 'ends'=>$start + $duration * 60, 'visitor'=>$name, 'reason'=>$reason, 'appointment_type'=>$type, 'contact'=>$contact,
    312             ], ['%s','%s','%s','%d','%d','%s','%s','%s','%s']);
     410            ], $reminderData), ['%s','%s','%s','%d','%d','%s','%s','%s','%s','%s','%d','%d','%s','%s']);
    313411        } finally {
    314412            $wpdb->get_var($wpdb->prepare('SELECT RELEASE_LOCK(%s)', $lock));
    … …  
    321419    static function notify_staff($email, $start, $duration, $type) {
    322420        if (!is_email($email)) return;
    323         $subject = $type === 'onsite' ? 'Neue Vor-Ort-Terminanfrage' : 'Neue Terminbuchung';
     421        $subject = $type === 'onsite' && !self::onsite_location() ? 'Neue Vor-Ort-Terminanfrage' : 'Neue Terminbuchung';
    324422        $lines = [
    325423            $subject . ' im SBS Kalender Assistenten.',
    … …  
    327425            'Zeitpunkt: ' . self::label($start),
    328426            'Dauer: ' . $duration . ' Minuten',
    329             'Terminart: ' . self::TYPES[$type],
     427            'Terminart: ' . self::type_label($type),
    330428        ];
    331         if ($type === 'onsite') $lines[] = 'Bitte rufen Sie zurück, um Ort und Details zu vereinbaren.';
     429        if ($type === 'onsite') $lines[] = self::onsite_location() ?: 'Bitte rufen Sie zurück, um Ort und Details zu vereinbaren.';
    332430        $lines[] = '';
    333431        $lines[] = 'Termindetails im WordPress-Dashboard: ' . self::url();
    … …  
    365463            return self::begin($row, $message, $key, $choice);
    366464        }
    367         if ($state && in_array($messageLower, ['abbrechen','nein'], true)) {
     465        if ($state && ($messageLower === 'abbrechen' || ($messageLower === 'nein' && !(isset($state['contact']) && empty($state['reminder_done']))))) {
    368466            delete_transient($key);
    369467            return self::reply($row, $message, 'Der Buchungsvorgang wurde beendet.');
    370468        }
     469        if ($state && isset($state['contact']) && empty($state['reminder_done'])) {
     470            return self::reply($row, $message, SBSKAAS_Reminders::chat_step($key, $state, $message));
     471        }
    371472        if ($state && isset($state['contact']) && self::is_whatsapp($state['type']) && $messageLower !== 'whatsapp bestätigen') {
    372473            return self::reply($row, $message, self::WHATSAPP_PROMPT);
    … …  
    374475        if ($state && isset($state['contact']) && $messageLower === (self::is_whatsapp($state['type']) ? 'whatsapp bestätigen' : 'bestätigen')) {
    375476            if (!get_privacy_policy_url()) return self::reply($row, $message, 'Die Online-Buchung ist derzeit nicht freigeschaltet.');
    376             $status = self::book($state['choice'], $state['name'], $state['reason'], $state['type'], $state['contact']);
     477            $status = self::book($state['choice'], $state['name'], $state['reason'], $state['type'], $state['contact'], $state['reminder'] ?? []);
     478            if ($status === 'reminder_invalid') {
     479                $state['reminder'] = [];
     480                set_transient($key, $state, 15 * MINUTE_IN_SECONDS);
     481                return self::reply($row, $message, 'Der Erinnerungszeitpunkt ist inzwischen verstrichen. Sie können den Termin ohne Erinnerung buchen. ' . self::confirmation_prompt($state));
     482            }
    377483            if ($status === 'limited') return self::reply($row, $message, self::BOOKING_LIMIT_MESSAGE);
    378484            if ($status === 'retry') return self::reply($row, $message, 'Der Kalender konnte die Buchung gerade nicht prüfen. Bitte versuchen Sie es erneut mit „Bestätigen“.');
    … …  
    387493            $state['reason'] = $reason;
    388494            set_transient($key, $state, 15 * MINUTE_IN_SECONDS);
    389             return self::reply($row, $message, self::TYPE_PROMPT);
     495            return self::reply($row, $message, self::type_prompt());
    390496        }
    391497        if ($state && isset($state['reason']) && !isset($state['type'])) {
    392498            $type = self::appointment_type($message);
    393             if (!$type) return self::reply($row, $message, self::TYPE_PROMPT);
     499            if (!$type) return self::reply($row, $message, self::type_prompt());
    394500            $state['type'] = $type;
    395501            set_transient($key, $state, 15 * MINUTE_IN_SECONDS);
    … …  
    401507            $state['contact'] = $contact;
    402508            set_transient($key, $state, 15 * MINUTE_IN_SECONDS);
    403             $choice = $state['choice'];
    404             return self::reply($row, $message, self::TYPES[$state['type']] . ' am ' . self::label($choice['start']) . ' (' . ($choice['duration'] ?? 30) . ' Minuten). ' . (self::is_whatsapp($state['type']) ? self::WHATSAPP_PROMPT : ($state['type'] === 'onsite' ? 'Schreiben Sie „Bestätigen“, um den Vor-Ort-Termin anzufragen, oder „Abbrechen“.' : 'Schreiben Sie „Bestätigen“, um verbindlich zu buchen, oder „Abbrechen“.')));
     509            return self::reply($row, $message, SBSKAAS_Reminders::chat_start($key, $state));
    405510        }
    406511        if ($state && isset($state['choice']) && !isset($state['name']) && preg_match('/^Name:\s*(.{2,120})$/ui', $message, $match)) {
    … …  
    497602    }
    498603
     604    static function confirmation_prompt($state) {
     605        $choice = $state['choice'];
     606        $text = self::type_label($state['type']) . ' am ' . self::label($choice['start']) . ' (' . ($choice['duration'] ?? 30) . ' Minuten). ';
     607        if ($state['type'] === 'onsite' && self::onsite_location()) $text .= self::onsite_location() . "\n";
     608        if (!empty($state['reminder']['opt_in'])) $text .= 'Gewünschte E-Mail-Erinnerung an ' . $state['reminder']['email'] . '. ';
     609        if (self::is_whatsapp($state['type'])) return $text . self::WHATSAPP_PROMPT;
     610        return $text . ($state['type'] === 'onsite' && !self::onsite_location()
     611            ? 'Schreiben Sie „Bestätigen“, um den Vor-Ort-Termin anzufragen, oder „Abbrechen“.'
     612            : 'Schreiben Sie „Bestätigen“, um verbindlich zu buchen, oder „Abbrechen“.');
     613    }
     614
    499615    const TYPES = ['video'=>'Videocall', 'phone'=>'Telefonisch', 'onsite'=>'Vor Ort', 'wa_voice'=>'WhatsApp-Sprachanruf', 'wa_video'=>'WhatsApp-Videoanruf'];
    500616    const TYPE_PROMPT = 'Wie möchten Sie den Termin wahrnehmen? 1) Videocall, 2) telefonisch, 3) vor Ort, 4) WhatsApp-Sprachanruf oder 5) WhatsApp-Videoanruf.';
    … …  
    508624    static function appointment_type($value) {
    509625        $value = mb_strtolower(trim($value));
    510         $numbered = ['1'=>'video', '2'=>'phone', '3'=>'onsite', '4'=>'wa_voice', '5'=>'wa_video', 'telefon'=>'phone', 'vor-ort-termin'=>'onsite'];
     626        $types = self::appointment_types();
     627        if (!$types) return '';
     628        $numbered = array_combine(array_map('strval', range(1, count($types))), array_keys($types));
     629        $aliases = ['telefon'=>'phone', 'vor-ort-termin'=>'onsite'];
    511630        if (isset($numbered[$value])) return $numbered[$value];
    512         foreach (self::TYPES as $key=>$label) {
    513             if ($value === $key || $value === mb_strtolower($label)) return $key;
     631        if (isset($aliases[$value], $types[$aliases[$value]])) return $aliases[$value];
     632        foreach ($types as $key=>$label) {
     633            if ($value === $key || $value === mb_strtolower($label) || $value === mb_strtolower(self::TYPES[$key])) return $key;
    514634        }
    515635        return '';
    … …  
    527647        if (self::is_whatsapp($type)) return 'Bitte geben Sie Ihre WhatsApp-Nummer mit Ländervorwahl an.';
    528648        if ($type === 'video') return 'Bitte geben Sie Ihre E-Mail-Adresse für die Einladung zum Videocall ein.';
    529         if ($type === 'onsite') return 'Bitte geben Sie Ihre Telefonnummer an. Wir rufen Sie zurück, um Ort und Details persönlich zu vereinbaren.';
     649        if ($type === 'onsite') return self::onsite_location() ? 'Der Termin findet hier statt: ' . self::onsite_location() . "\nBitte geben Sie Ihre Telefonnummer für Rückfragen an." : 'Bitte geben Sie Ihre Telefonnummer an. Wir rufen Sie zurück, um Ort und Details persönlich zu vereinbaren.';
    530650        return 'Bitte geben Sie die Telefonnummer an, unter der wir Sie zum Termin erreichen.';
    531651    }
    532652
    533653    static function confirmation($type, $label) {
     654        if ($type === 'onsite' && self::onsite_location()) return self::type_label($type) . ' am ' . $label . ' ist verbindlich gebucht.' . "\nStandort: " . self::onsite_location();
    534655        if ($type === 'onsite') return 'Ihre Anfrage für einen Vor-Ort-Termin am ' . $label . ' wurde erfasst. Wir rufen Sie zurück, um Ort und Details zu vereinbaren.';
    535         return self::TYPES[$type] . ' am ' . $label . ' ist verbindlich gebucht.';
     656        return self::type_label($type) . ' am ' . $label . ' ist verbindlich gebucht.';
    536657    }
    537658
    538659    const REASONS = ['Erstgespräch', 'Beratung', 'Support', 'Sonstiges'];
    539660
     661    static function reasons() {
     662        return (array)get_option('sbskaas_reasons', self::REASONS);
     663    }
     664
     665    static function parse_reasons($input) {
     666        if (!is_string($input)) return null;
     667        $reasons = [];
     668        $seen = [];
     669        foreach (preg_split('/\R/u', $input) as $line) {
     670            $label = sanitize_text_field($line);
     671            if ($label === '') continue;
     672            $key = mb_strtolower($label);
     673            if (mb_strlen($label) > 190 || isset($seen[$key])) return null;
     674            $seen[$key] = true;
     675            $reasons[] = $label;
     676        }
     677        return $reasons ?: null;
     678    }
     679
     680    static function save_reasons() {
     681        if (!current_user_can('manage_options')) wp_die('Nicht berechtigt.');
     682        check_admin_referer('sbskaas_reasons');
     683        $input = sanitize_textarea_field(wp_unslash($_POST['reasons'] ?? ''));
     684        $reasons = self::parse_reasons($input);
     685        if ($reasons === null) wp_die('Bitte geben Sie mindestens eine eindeutige Terminkategorie ein, mit höchstens 190 Zeichen je Kategorie.');
     686        update_option('sbskaas_reasons', $reasons, false);
     687        wp_safe_redirect(self::url());
     688        exit;
     689    }
     690
     691    static function reason_fields() {
     692        echo '<h2>Terminkategorien</h2><form method="post" action="' . esc_url(admin_url('admin-post.php')) . '">';
     693        echo '<input type="hidden" name="action" value="sbskaas_reasons">';
     694        wp_nonce_field('sbskaas_reasons');
     695        echo '<p>Geben Sie eine Kategorie pro Zeile ein, zum Beispiel Massage, Haarschnitt oder Erstuntersuchung. Anzahl und Texte bestimmen Sie selbst. Mindestens eine Kategorie ist erforderlich; jede Bezeichnung darf höchstens 190 Zeichen enthalten. Die Reihenfolge gilt auch für die nummerierte Auswahl im Chat.</p>';
     696        echo '<p><label>Terminkategorien<br><textarea class="large-text" rows="6" name="reasons" required>' . esc_textarea(implode("\n", self::reasons())) . '</textarea></label></p>';
     697        submit_button('Terminkategorien speichern');
     698        echo '</form>';
     699    }
     700
    540701    static function reason($value) {
    541         foreach (self::REASONS as $index=>$reason) {
     702        // Match labels first so a numeric label remains selectable in the form.
     703        foreach (self::reasons() as $reason) {
     704            if (mb_strtolower(trim($value)) === mb_strtolower($reason)) return $reason;
     705        }
     706        foreach (self::reasons() as $index=>$reason) {
    542707            if (mb_strtolower(trim($value)) === mb_strtolower($reason) || trim($value) === (string)($index + 1)) return $reason;
    543708        }
    … …  
    546711
    547712    static function reason_prompt() {
    548         return 'Worum geht es bei Ihrem Termin? 1) Erstgespräch, 2) Beratung, 3) Support, 4) Sonstiges. Bitte nennen Sie nur die Kategorie.';
     713        $choices = [];
     714        foreach (self::reasons() as $index=>$label) {
     715            $choices[] = ($index + 1) . ') ' . $label;
     716        }
     717        return 'Worum geht es bei Ihrem Termin? ' . implode(', ', $choices) . '. Bitte nennen Sie nur die Kategorie.';
    549718    }
    550719
    … …  
    576745
    577746    static function menu() {
     747 if(!current_user_can('manage_options') && SBS_Staff_Access::can('sbs_calendar_view')) {add_menu_page('SBS Termine','SBS Termine','sbs_calendar_view',self::menu_slug(),array(__CLASS__,'page'),'dashicons-calendar');return;}
     748
    578749        if (!self::connected()) {
    579750            add_menu_page('SBS Kalender Assistent', 'SBS Kalender', 'manage_options', self::menu_slug(), [__CLASS__, 'page'], 'dashicons-calendar-alt');
    … …  
    624795
    625796    static function cancel() {
    626         if (!current_user_can('manage_options')) wp_die('Nicht berechtigt.');
     797        if (!SBS_Staff_Access::can('sbs_calendar_manage')) wp_die('Nicht berechtigt.');
    627798        check_admin_referer('sbskaas_cancel');
    628799        global $wpdb;
    629         $wpdb->update(self::table(), ['cancelled'=>1, 'cancelled_at'=>time(), 'visitor'=>'', 'reason'=>'', 'contact'=>''], ['id'=>absint($_POST['id'] ?? 0), 'cancelled'=>0], ['%d','%d','%s','%s','%s'], ['%d','%d']);
     800        $id = absint($_POST['id'] ?? 0);
     801        $lock = SBSKAAS_Reminders::lock($id);
     802        if ((string)$wpdb->get_var($wpdb->prepare('SELECT GET_LOCK(%s, 3)', $lock)) !== '1') wp_die('Bitte versuchen Sie die Stornierung erneut.');
     803        try {
     804            $cancelled = $wpdb->update(self::table(), ['cancelled'=>1, 'cancelled_at'=>time(), 'visitor'=>'', 'reason'=>'', 'contact'=>'',
     805                'reminder_email'=>'', 'reminder_consent_at'=>0, 'reminder_at'=>0, 'reminder_status'=>'', 'reminder_location'=>''],
     806                ['id'=>$id, 'cancelled'=>0], ['%d','%d','%s','%s','%s','%s','%d','%d','%s','%s'], ['%d','%d']);
     807            if ($cancelled === false) wp_die('Die Stornierung konnte nicht gespeichert werden. Bitte versuchen Sie es erneut.');
     808        } finally {
     809            $wpdb->get_var($wpdb->prepare('SELECT RELEASE_LOCK(%s)', $lock));
     810        }
    630811        wp_safe_redirect(self::url());
    631812        exit;
    632813    }
    633814
     815    static function staff_bookings_page() {
     816        SBS_Staff_Access::require_cap('sbs_calendar_view'); global $wpdb;
     817        $table = self::table();
     818        $rows = $wpdb->get_results($wpdb->prepare(
     819            'SELECT * FROM %i WHERE cancelled=0 AND ends>%d ORDER BY starts',
     820            $table, time()
     821        ));
     822        echo '<div class="wrap"><h1>SBS Termine</h1><table class="widefat striped"><tr><th>Termin</th><th>Mitarbeiter</th><th>Besucher</th><th>Grund</th><th>Kontakt</th><th>Aktion</th></tr>';
     823        foreach($rows as $r) {echo '<tr><td>'.esc_html(wp_date('d.m.Y H:i',(int)$r->starts)).'</td><td>'.esc_html($r->staff_name).'</td><td>'.esc_html($r->visitor).'</td><td>'.esc_html($r->reason??'').'</td><td>'.esc_html($r->contact??'').'</td><td>';
     824        if(SBS_Staff_Access::can('sbs_calendar_manage')) { echo '<form method="post" action="'.esc_url(admin_url('admin-post.php')).'"><input type="hidden" name="action" value="sbskaas_cancel"><input type="hidden" name="id" value="'.(int)$r->id.'">';wp_nonce_field('sbskaas_cancel');echo '<button class="button">Termin absagen</button></form>'; }
     825        echo '</td></tr>'; }echo '</table></div>';
     826    }
    634827    static function page() {
    635         if (!current_user_can('manage_options')) return;
     828 if(!current_user_can('manage_options')) {self::staff_bookings_page();return;}
     829        if (!SBS_Staff_Access::can('sbs_calendar_view')) return;
    636830        global $wpdb;
    637831        $settings = self::settings();
    … …  
    640834        echo '<div class="wrap"><h1>Terminkalender</h1>';
    641835        echo '<p>Der SBS Kalender Assistent ist kostenlos und ohne SBS-Konto nutzbar. Eine Entwicklung von <a href="https://sturm-business-solutions.at/">Sturm Business Solutions</a>.</p>';
     836        self::reason_fields();
     837        self::appointment_fields();
     838        SBSKAAS_Reminders::fields();
    642839        echo '<h2>Termindauer und Abteilungen</h2><form method="post" action="' . esc_url(admin_url('admin-post.php')) . '">';
    643840        echo '<input type="hidden" name="action" value="sbskaas_booking_options">';
    … …  
    675872        echo '</tbody></table>';
    676873        submit_button('Buchbare Zeiten speichern');
    677         echo '</form><h2>Anstehende Termine</h2><table class="widefat striped"><thead><tr><th>Termin</th><th>Mitarbeiter</th><th>Dauer</th><th>Gebucht für</th><th>Termingrund</th><th>Terminart</th><th>Kontakt</th><th>Aktion</th></tr></thead><tbody>';
     874        echo '</form><h2>Anstehende Termine</h2><table class="widefat striped"><thead><tr><th>Termin</th><th>Mitarbeiter</th><th>Dauer</th><th>Gebucht für</th><th>Termingrund</th><th>Terminart</th><th>Kontakt</th><th>Erinnerung</th><th>Aktion</th></tr></thead><tbody>';
    678875        foreach ($bookings ?: [] as $booking) {
    679             echo '<tr><td>' . esc_html(self::label((int)$booking->starts)) . '</td><td>' . esc_html($booking->staff_name) . '</td><td>' . (int)(($booking->ends - $booking->starts) / 60) . ' Min.</td><td>' . esc_html($booking->visitor) . '</td><td>' . esc_html($booking->reason ?? '') . '</td><td>' . esc_html(self::TYPES[$booking->appointment_type ?? ''] ?? '–') . '</td><td>' . esc_html($booking->contact ?? '') . '</td><td><form method="post" action="' . esc_url(admin_url('admin-post.php')) . '"><input type="hidden" name="action" value="sbskaas_cancel"><input type="hidden" name="id" value="' . esc_attr($booking->id) . '">';
     876            echo '<tr><td>' . esc_html(self::label((int)$booking->starts)) . '</td><td>' . esc_html($booking->staff_name) . '</td><td>' . (int)(($booking->ends - $booking->starts) / 60) . ' Min.</td><td>' . esc_html($booking->visitor) . '</td><td>' . esc_html($booking->reason ?? '') . '</td><td>' . esc_html(self::type_label($booking->appointment_type ?? '') ?: '–') . '</td><td>' . esc_html($booking->contact ?? '') . '</td><td>' . esc_html(SBSKAAS_Reminders::status($booking)) . '</td><td><form method="post" action="' . esc_url(admin_url('admin-post.php')) . '"><input type="hidden" name="action" value="sbskaas_cancel"><input type="hidden" name="id" value="' . esc_attr($booking->id) . '">';
    680877            wp_nonce_field('sbskaas_cancel');
    681878            echo '<button class="button" type="submit">Termin stornieren</button></form></td></tr>';
    682879        }
    683         if (!$bookings) echo '<tr><td colspan="8">Keine anstehenden Termine.</td></tr>';
     880        if (!$bookings) echo '<tr><td colspan="9">Keine anstehenden Termine.</td></tr>';
    684881        echo '</tbody></table></div>';
    685882    }
    … …  
    690887add_action(SBSKAAS_Kalender::CLEANUP, ['SBSKAAS_Kalender', 'delete_expired_bookings']);
    691888add_action('admin_menu', ['SBSKAAS_Kalender', 'menu'], 30);
     889add_action('admin_post_sbskaas_appointment_options', ['SBSKAAS_Kalender', 'save_appointment_options']);
     890add_action('admin_post_sbskaas_reasons', ['SBSKAAS_Kalender', 'save_reasons']);
    692891add_action('admin_post_sbskaas_booking_options', ['SBSKAAS_Kalender', 'save_booking_options']);
    693892add_action('admin_post_sbskaas_save', ['SBSKAAS_Kalender', 'save']);
    … …  
    696895add_filter('sbs_ba_calendar_chat', ['SBSKAAS_Kalender', 'chat'], 10, 3);
    697896
     897require_once __DIR__ . '/reminders.php';
    698898require_once __DIR__ . '/standalone.php';
    699899require_once __DIR__ . '/public-calendar.php';
Note: See TracChangeset for help on using the changeset viewer.