( function ( w, $ ) { 'use strict'; var config = w.wpbc_appointment_services_config || {}; var state = { storageReady: false, catalog_loading: true, selectedId: Number( config.selected_id || 0 ), requested_focus: String( config.focus_section || '' ), focus_handled: false, busy: false, status: 'all', services: [], providers: {}, providerCount: 0, editor_snapshot: '', editor_request_sequence: 0, initial_selection_pending: 0 < Number( config.selected_id || 0 ), inspector_focus_target: null, mutation_in_progress: false, operation_mode: '', operation_review: null, operation_request_sequence: 0, inline_editing: false, inline_drafts: {}, inline_schema: {}, inline_schema_loading: false, inline_request_sequence: 0, last_response: null, page: 1, page_size: Number( config.catalog && config.catalog.initial_request && config.catalog.initial_request.items_per_page ? config.catalog.initial_request.items_per_page : 10 ), total_items: 0, total_pages: 0, sort_by: String( config.catalog && config.catalog.initial_request && config.catalog.initial_request.sort_by ? config.catalog.initial_request.sort_by : 'service_id' ), sort_order: String( config.catalog && config.catalog.initial_request && config.catalog.initial_request.sort_order ? config.catalog.initial_request.sort_order : 'desc' ) }; var catalogController = false; var inlineWorkflowController = false; var inlineReviewWorkflowController = false; var deleteReviewWorkflowController = false; var inspectorWorkflowController = false; var searchTimer = 0; var weekdayKeys = [ 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun' ]; var pending_highlight_ids = []; /** Extract an API message while preserving a caller-provided fallback. */ function messageFrom( response, fallback ) { return response && response.data && response.data.message ? response.data.message : fallback; } /** Display a shared Booking Calendar administrator notice. */ function notify( message, type ) { if ( message && typeof w.wpbc_admin_show_message === 'function' ) { w.wpbc_admin_show_message( message, type || 'info', 5000, false ); } } /** * Return the shared signed-review presentation controller. * * @return {Object|false} Shared review controller or false when unavailable. */ function get_inline_review_workflow() { if ( inlineReviewWorkflowController ) { return inlineReviewWorkflowController; } if ( ! w.wpbc_ui_catalog || 'function' !== typeof w.wpbc_ui_catalog.create_inline_review_workflow ) { return false; } inlineReviewWorkflowController = w.wpbc_ui_catalog.create_inline_review_workflow( { apply_selector: '.wpbc_appointment_services__operation_apply', cancel_selector: '.wpbc_appointment_services__cancel', root: document } ); return inlineReviewWorkflowController; } /** * Return the shared permanent-deletion presentation controller. * * @return {Object|false} Shared deletion controller or false when unavailable. */ function get_delete_review_workflow() { if ( deleteReviewWorkflowController ) { return deleteReviewWorkflowController; } if ( ! w.wpbc_ui_catalog || 'function' !== typeof w.wpbc_ui_catalog.create_delete_review_workflow ) { return false; } deleteReviewWorkflowController = w.wpbc_ui_catalog.create_delete_review_workflow( { acknowledgement_selector: '[data-wpbc-ui-catalog-delete-acknowledgement]', apply_selector: '.wpbc_appointment_services__operation_apply', cancel_selector: '.wpbc_appointment_services__cancel', root: document } ); return deleteReviewWorkflowController; } /** * Show the native Booking Calendar Processing notice. * * The returned element identifies this specific request's notice so * overlapping requests cannot dismiss each other's feedback. * * @return {jQuery} Processing notice wrapper, or an empty collection. */ function show_processing_notice() { if ( 'function' !== typeof w.wpbc_admin_show_message_processing ) { return $(); } w.wpbc_admin_show_message_processing( '' ); return $( '#ajax_working .wpbc_processing.wpbc_spin' ).last().closest( '[id^="wpbc_notice_"]' ); } /** * Hide the Processing notice created for one completed request. * * @param {jQuery} $processing_notice Notice wrapper returned by show_processing_notice(). * @return {void} */ function hide_processing_notice( $processing_notice ) { if ( $processing_notice && $processing_notice.length ) { $processing_notice.stop( true, true ).hide(); } } /** * Send an authenticated Appointment Services AJAX request. * * Requests normally use the shared administrator Processing notice and remove * only their own notice after settling. Inspector-loading requests may opt out * because the shared inspector already exposes equivalent progress feedback. * * @param {string} action WordPress AJAX action name. * @param {Object} data Request-specific payload. * @param {boolean} use_processing_notice Whether to show the global notice. * @return {jqXHR} jQuery AJAX promise for the request. */ function request( action, data, use_processing_notice ) { var $processing_notice = false === use_processing_notice ? $() : show_processing_notice(); return $.ajax( { url: config.ajax_url, type: 'POST', dataType: 'json', data: $.extend( { action: action, nonce: config.nonce }, data || {} ) } ) .always( function () { hide_processing_notice( $processing_notice ); } ); } /** Activate the Settings or Help panel selected in the right sidebar. */ function switchRightPanel( $tab ) { var panelId = $tab.attr( 'aria-controls' ); var panel = panelId ? document.getElementById( panelId ) : null; var $tabs = $tab.closest( '.wpbc_appointment_services__rightbar_tabs' ).find( '[role="tab"]' ); var $panels = $( '.wpbc_appointment_services__rightbar [role="tabpanel"]' ); if ( ! panel ) { return; } $tabs.attr( 'aria-selected', 'false' ); $tab.attr( 'aria-selected', 'true' ); $panels.prop( 'hidden', true ).attr( 'aria-hidden', 'true' ); $( panel ).prop( 'hidden', false ).attr( 'aria-hidden', 'false' ); updateControls(); } /** * Tell the active Setup Wizard bar that the page workspace changed width. * * The delayed notification runs after the shared sidebar transition so the * setup bar can measure the final inspector boundary. * * @return {void} */ function notify_setup_wizard_layout_changed() { $( document ).trigger( 'wpbc_setup_wizard_layout_changed' ); w.setTimeout( function () { $( document ).trigger( 'wpbc_setup_wizard_layout_changed' ); }, 300 ); } /** * Expand the right sidebar and display the Service Settings inspector. * * @return {void} */ function expand_service_inspector() { var $settings_tab = $( '#wpbc_tab_service_settings' ); if ( 'function' === typeof w.wpbc_admin_ui__sidebar_right__do_max ) { w.wpbc_admin_ui__sidebar_right__do_max(); } if ( $settings_tab.length ) { switchRightPanel( $settings_tab ); } notify_setup_wizard_layout_changed(); } /** * Reveal, expand, highlight, and optionally focus one Service editor group. * * @param {string} fields_selector Group fields selector from the fixed editor markup. * @param {string} focus_selector Optional control selector to focus after scrolling. * @return {boolean} True when the requested inspector group was found. */ function open_service_inspector_group( fields_selector, focus_selector ) { var $group_fields = $( fields_selector ); var $group = $group_fields.closest( '.wpbc_ui__collapsible_group' ); var $group_header = $group.children( '.group__header' ); var group_element = $group.get( 0 ); var focus_element = focus_selector ? document.querySelector( focus_selector ) : null; expand_service_inspector(); if ( ! $group.length ) { return false; } $group.addClass( 'is-open' ); $group_header.attr( 'aria-expanded', 'true' ); $group_fields.prop( 'hidden', false ).attr( 'aria-hidden', 'false' ); $group.removeClass( 'wpbc_appointment_services__focus_pulse' ); if ( group_element ) { void group_element.offsetWidth; $group.addClass( 'wpbc_appointment_services__focus_pulse' ); try { group_element.scrollIntoView( { behavior: 'smooth', block: 'start', inline: 'nearest' } ); } catch ( error ) { group_element.scrollIntoView( true ); } w.setTimeout( function () { $group.removeClass( 'wpbc_appointment_services__focus_pulse' ); }, 900 ); } if ( focus_element && typeof focus_element.focus === 'function' ) { try { focus_element.focus( { preventScroll: true } ); } catch ( error ) { focus_element.focus(); } } return true; } /** * Open, reveal, and highlight the General Service editor section. * * @return {void} */ function open_add_service_inspector() { open_service_inspector_group( '#wpbc_service_general', '[data-service-field="title"]' ); } /** * Apply the one-time inspector focus requested by an administration link. * * @return {void} */ function focus_requested_service_section() { if ( state.focus_handled || 'booking_form' !== state.requested_focus ) { return; } if ( open_service_inspector_group( '#wpbc_service_form', '[data-service-field="booking_form_id"]' ) ) { state.focus_handled = true; if ( w.history && w.URL ) { var url = new w.URL( w.location.href ); url.searchParams.delete( 'wpbc_service_focus' ); w.history.replaceState( {}, '', url.toString() ); } } } /** Expand or collapse one inspector field group. */ function toggleInspectorGroup( $button ) { var $group = $button.closest( '.wpbc_ui__collapsible_group' ); var $fields = $group.find( '> .group__fields' ); var isOpen = $group.hasClass( 'is-open' ); $group.toggleClass( 'is-open', ! isOpen ); $button.attr( 'aria-expanded', isOpen ? 'false' : 'true' ); $fields.prop( 'hidden', isOpen ).attr( 'aria-hidden', isOpen ? 'true' : 'false' ); } /** Determine whether a Service is currently loaded into the editor. */ function editorIsOpen() { return ! $( '[data-service-field="title"]' ).prop( 'disabled' ); } /** * Synchronize one numeric Service field with its range control. * * Non-price sliders expand to represent an existing value above their normal * visual range. The price slider remains the product-defined 0-1000 control; * its number field can still preserve and submit a legacy value above 1000. * * @param {string} field_id Service field identifier. * @return {void} */ function sync_numeric_range( field_id ) { var $field = $( '[data-service-field="' + field_id + '"]' ); var $range = $( '[data-service-range-field="' + field_id + '"]' ); var value = Number( $field.val() ); var default_min = Number( $range.data( 'service-range-default-min' ) ); var default_max = Number( $range.data( 'service-range-default-max' ) ); var step = Number( $range.attr( 'step' ) || 1 ); var range_max; if ( ! $field.length || ! $range.length || ! isFinite( value ) ) { return; } default_min = isFinite( default_min ) ? default_min : 0; default_max = isFinite( default_max ) ? default_max : 100; step = isFinite( step ) && step > 0 ? step : 1; range_max = 'base_cost' === field_id || value <= default_max ? default_max : default_min + ( Math.ceil( ( value - default_min ) / step ) * step ); $range.attr( { min: default_min, max: range_max } ).val( value ); } /** * Synchronize every numeric Service field with its range control. * * @return {void} */ function sync_all_numeric_ranges() { $( '[data-service-range-field]' ).each( function () { sync_numeric_range( String( $( this ).data( 'service-range-field' ) || '' ) ); } ); } /** * Synchronize the visible Status radios with the stored Service status field. * * @return {void} */ function sync_status_radios() { var status = String( $( '[data-service-field="status"]' ).val() || 'active' ); $( '[data-service-status-choice]' ).each( function () { $( this ).prop( 'checked', String( $( this ).val() ) === status ); } ); } /** * Synchronize the Service image preview with the readonly URL field. * * @return {void} */ function updateMediaPreview() { var pictureUrl = String( $( '[data-service-field="picture_url"]' ).val() || '' ).trim(); var $image = $( '.wpbc_appointment_services__media_image' ); if ( pictureUrl ) { $image.attr( 'src', pictureUrl ); } else { $image.removeAttr( 'src' ); } $image.prop( 'hidden', ! pictureUrl ); $( '.wpbc_appointment_services__media_placeholder' ).prop( 'hidden', !! pictureUrl ); } /** Synchronize toolbar and inspector action states with the page state. */ function updateControls() { var open = state.storageReady && editorIsOpen(); var operation_open = !! state.operation_mode && 'loading' !== state.operation_mode; var operation_is_review = 'bulk_review' === state.operation_mode || 'inline_review' === state.operation_mode || 'delete_review' === state.operation_mode; var operation_is_delete_review = 'delete_review' === state.operation_mode; var hasPicture = !! String( $( '[data-service-field="picture_url"]' ).val() || '' ).trim(); var show_save = ( open || operation_open ) && 'true' === $( '#wpbc_tab_service_settings' ).attr( 'aria-selected' ); $( '.wpbc_appointment_services__add' ).prop( 'hidden', false ).prop( 'disabled', ! state.storageReady || state.busy ); $( '.wpbc_appointment_services__right_sidebar_footer, .wpbc_appointment_services__top_actions' ).prop( 'hidden', ! show_save ); $( '.wpbc_appointment_services__cancel' ).prop( 'hidden', ! show_save ).prop( 'disabled', ( ! open && ! operation_open ) || state.busy ); $( '.wpbc_appointment_services__save' ).prop( 'hidden', ! show_save || operation_open ).prop( 'disabled', ! open || state.busy ); $( '.wpbc_appointment_services__operation_review' ).prop( 'hidden', 'bulk_edit' !== state.operation_mode ).prop( 'disabled', 'bulk_edit' !== state.operation_mode || state.busy || ! collect_bulk_changes() ); $( '.wpbc_appointment_services__operation_apply' ).prop( 'hidden', ! operation_is_review ); if ( ! operation_is_delete_review ) { $( '.wpbc_appointment_services__operation_apply' ).prop( 'disabled', ! operation_is_review || state.busy || ! state.operation_review ); } $( '.wpbc_appointment_services__duplicate, .wpbc_appointment_services__archive' ).prop( 'disabled', ! open || ! state.selectedId || state.busy ); $( '.wpbc_appointment_services__media_preview, .wpbc_appointment_services__select_image' ).prop( 'disabled', ! open || state.busy ); $( '.wpbc_appointment_services__remove_image' ).prop( 'disabled', ! open || ! hasPicture || state.busy ); synchronize_inline_workflow(); } /** Synchronize the shared inline workflow from Service-owned state. */ function synchronize_inline_workflow() { var changed_count = get_inline_changed_count(); if ( ! inlineWorkflowController ) { return; } inlineWorkflowController.synchronize( { active: state.inline_editing, busy: state.busy, changed_count: changed_count, count_text: String( config.i18n.changed_rows || '%s changed rows' ).replace( '%s', changed_count ), has_items: 0 < state.services.length, lock_controls: state.inline_schema_loading || !! state.operation_mode, toggle_disabled: state.catalog_loading || ! state.storageReady || !! state.operation_mode, active_toggle_text: config.i18n.editing_rows, inactive_toggle_text: config.catalog && config.catalog.i18n ? config.catalog.i18n.edit_rows : '' } ); } /** * Stop page-changing catalog controls while a pending operation owns row state. * * Summary elements do not honor the disabled property, so this capture guard * complements the visual disabled state while Service inline or bulk editing is active. * * @param {Event} event Captured catalog event. * @return {void} */ function protect_inline_drafts_from_catalog_controls( event ) { var protected_control; if ( inlineWorkflowController && inlineWorkflowController.protect_event( event, state.inline_editing || state.inline_schema_loading || !! state.operation_mode ) ) { return; } if ( ( ! state.inline_editing && ! state.inline_schema_loading && ! state.operation_mode ) || ! event.target || ! event.target.closest ) { return; } protected_control = event.target.closest( '.wpbc_appointment_services__status_filter, #wpbc_service_provider_filter, .wpbc_appointment_services__add' ); if ( ! protected_control ) { return; } event.preventDefault(); event.stopImmediatePropagation(); } /** Mark the page busy during a mutating request and refresh controls. */ function setBusy( value ) { state.busy = value; $( '.wpbc_appointment_services_page' ).toggleClass( 'is-busy', value ); updateControls(); } /** Enable or disable all fields in the Service inspector. */ function setFieldsEnabled( enabled ) { $( '[data-service-field], [data-service-range-field], [data-service-status-choice]' ).prop( 'disabled', ! enabled ); updateControls(); } /** Return defaults for a new unsaved Service. */ function blankService() { return { service_id: 0, title: '', description: '', picture_url: '', status: 'active', duration_minutes: 30, buffer_before_minutes: 0, buffer_after_minutes: 0, base_cost: '0.00', booking_form_id: 0, resource_ids: ( config.default_provider_ids || [] ).slice() }; } /** * Render the Service-owned create or edit inspector header template. * * Existing Service fields remain in their native collapsible groups so the * template changes presentation without moving domain validation to shared code. * * @param {boolean} is_edit Whether an existing Service is being edited. * @return {void} */ function render_inspector_header( is_edit ) { var template_id = is_edit ? 'wpbc-appointment-service-inspector-edit' : 'wpbc-appointment-service-inspector-create'; var template = catalogTemplate( template_id ); var $header = $( '[data-wpbc-appointment-service-inspector-header]' ); var context = is_edit ? String( config.i18n.inspector_context_id || 'ID: %d' ).replace( '%d', String( state.selectedId ) ) : String( config.i18n.inspector_context_new || 'New' ); if ( ! template || ! $header.length ) { return; } $header.html( template( { title: is_edit ? config.i18n.edit_service_title : config.i18n.create_service_title, context: context, description: is_edit ? config.i18n.edit_service_description : config.i18n.create_service_description } ) ); } /** Populate the inspector from a normalized Service response. */ function fillEditor( service ) { service = $.extend( blankService(), service || {} ); state.selectedId = Number( service.service_id || 0 ); render_inspector_header( 0 < state.selectedId ); $.each( service, function ( key, value ) { $( '[data-service-field="' + key + '"]' ).val( value ); } ); sync_status_radios(); sync_all_numeric_ranges(); updateMediaPreview(); setFieldsEnabled( state.storageReady ); $( '.wpbc_appointment_services__item' ).removeClass( 'is-inspector-selected' ).attr( 'aria-current', 'false' ); $( '.wpbc_appointment_services__item[data-service-id="' + state.selectedId + '"]' ).addClass( 'is-inspector-selected' ).attr( 'aria-current', 'true' ); capture_editor_snapshot(); } /** Collect the current Service inspector values for saving. */ function collectEditor() { var service = { service_id: state.selectedId }; $( '[data-service-field]' ).each( function () { service[ $( this ).data( 'service-field' ) ] = $( this ).val(); } ); return service; } /** * Store the current editor values as the last loaded or saved state. * * @return {void} */ function capture_editor_snapshot() { state.editor_snapshot = JSON.stringify( collectEditor() ); } /** * Determine whether the open Service editor contains unsaved changes. * * @return {boolean} True when current fields differ from the captured state. */ function is_editor_dirty() { return editorIsOpen() && state.editor_snapshot !== JSON.stringify( collectEditor() ); } /** * Confirm before replacing an editor that contains unsaved Service changes. * * @return {boolean} True when replacing the current editor may continue. */ function can_replace_editor() { return ! is_editor_dirty() || w.confirm( config.i18n.confirm_discard || 'Discard unsaved Service changes?' ); } /** * Determine whether the current Service operation contains unapplied values. * * Inline drafts and signed review screens remain dirty until they are * explicitly applied or discarded. This prevents an outside click from * silently replacing a reviewed mutation. * * @return {boolean} True when closing would discard pending changes. */ function is_operation_dirty() { if ( 'bulk_edit' === state.operation_mode ) { return !! collect_bulk_changes(); } if ( 'inline_review' === state.operation_mode || 'bulk_review' === state.operation_mode || 'delete_review' === state.operation_mode ) { return !! state.operation_review; } return state.inline_editing && 0 < get_inline_changed_count(); } /** * Clear the Service editor after its native sidebar has been closed. * * Invalidating the request sequence prevents a late load response from * reopening an inspector that the user already dismissed. * * @return {void} */ function reset_service_editor() { var service = blankService(); state.editor_request_sequence += 1; state.selectedId = 0; state.requested_focus = ''; state.focus_handled = true; render_inspector_header( false ); $.each( service, function ( key, value ) { $( '[data-service-field="' + key + '"]' ).val( value ); } ); sync_status_radios(); sync_all_numeric_ranges(); updateMediaPreview(); setFieldsEnabled( false ); $( '.wpbc_appointment_services__item' ).removeClass( 'is-inspector-selected' ).attr( 'aria-current', 'false' ); capture_editor_snapshot(); updateUrl( 0 ); } /** * Clear a Service inline or bulk operation without changing selection. * * @param {boolean} restore_inline Whether inline rows should return to presentation mode. * @return {void} */ function reset_operation( restore_inline ) { state.operation_request_sequence += 1; state.operation_mode = ''; state.operation_review = null; $( '[data-wpbc-appointment-services-operation-host]' ).empty().prop( 'hidden', true ); $( '[data-wpbc-appointment-services-native-inspector]' ).prop( 'hidden', false ); $( '.wpbc_appointment_services__operation_apply' ) .removeClass( 'wpbc_ui_catalog_delete_review__apply button-secondary is-busy' ) .addClass( 'button-primary' ) .removeAttr( 'aria-busy form' ) .text( config.i18n.apply_changes || 'Apply changes' ); if ( restore_inline ) { state.inline_editing = false; state.inline_drafts = {}; state.inline_schema = {}; state.inline_schema_loading = false; state.inline_request_sequence += 1; $( '[data-wpbc-appointment-services-inline-bar-host]' ).empty(); if ( state.last_response ) { renderCatalogResponse( state.last_response ); } } setBusy( false ); } /** * Close the Service inspector using the Booking Resources lifecycle. * * @param {boolean} confirm_discard Whether to confirm unsaved changes. * @param {boolean} hide_sidebar Whether this function must hide the native sidebar. * @return {boolean} True when the inspector was closed. */ function close_service_inspector( confirm_discard, hide_sidebar ) { var focus_target = state.inspector_focus_target; if ( state.mutation_in_progress ) { return false; } if ( state.operation_mode ) { if ( confirm_discard && is_operation_dirty() && ! w.confirm( config.i18n.confirm_discard || 'Discard unsaved Service changes?' ) ) { return false; } reset_operation( true ); state.inspector_focus_target = null; if ( hide_sidebar && 'function' === typeof w.wpbc_admin_ui__sidebar_right__do_hide ) { w.wpbc_admin_ui__sidebar_right__do_hide(); } notify_setup_wizard_layout_changed(); if ( hide_sidebar && focus_target && document.documentElement.contains( focus_target ) && 'function' === typeof focus_target.focus ) { focus_target.focus(); } return true; } if ( confirm_discard && ! can_replace_editor() ) { return false; } reset_service_editor(); state.inspector_focus_target = null; if ( hide_sidebar && 'function' === typeof w.wpbc_admin_ui__sidebar_right__do_hide ) { w.wpbc_admin_ui__sidebar_right__do_hide(); } notify_setup_wizard_layout_changed(); if ( hide_sidebar && focus_target && document.documentElement.contains( focus_target ) && 'function' === typeof focus_target.focus ) { focus_target.focus(); } return true; } /** Reflect the selected Service in the admin URL without reloading. */ function updateUrl( serviceId ) { if ( ! w.history || ! w.URL ) { return; } var url = new w.URL( w.location.href ); if ( serviceId ) { url.searchParams.set( 'service_id', serviceId ); } else { url.searchParams.delete( 'service_id' ); } w.history.replaceState( {}, '', url.toString() ); } /** Index Provider presentation records by booking resource ID. */ function indexProviders( providers ) { state.providers = {}; $.each( providers || [], function ( index, provider ) { state.providers[ String( provider.id ) ] = provider; } ); } /** Update status and Provider counters above the Service table. */ function updateSummary( counts, providerCount ) { counts = $.extend( { all: 0, active: 0, inactive: 0, archived: 0 }, counts || {} ); state.providerCount = Number( providerCount || 0 ); $.each( counts, function ( status, count ) { $( '[data-service-count="' + status + '"]' ).text( Number( count || 0 ) ); } ); $( '[data-provider-count]' ).text( state.providerCount ); $( '.wpbc_appointment_services__provider_notice' ).prop( 'hidden', 0 !== state.providerCount ); } /** Format a normalized Service cost using the configured currency symbol. */ function formatCost( cost ) { var amount = Number( cost || 0 ); var symbol = config.currency_symbol || '$'; return symbol + amount.toFixed( 2 ); } /** Build compact Provider avatar nodes for one Service row. */ function providerNodes( service ) { var ids = $.map( service.resource_ids || [], function ( value ) { return Number( value || 0 ); } ); var $stack = $( '