'no_such_report' ); } $query = new AIEO_Report_Query( $def, $request ); $envelope = $query->run(); if ( isset( $envelope['error'] ) ) { return $envelope; } $series = self::chart_series( $def, $envelope ); if ( ! empty( $series ) ) { $envelope['series'] = $series; } $envelope['html'] = self::html( $def, $envelope, $request, $overrides ); return $envelope; } private static function chart_series( $def, $envelope ) { $chart = (array) $def->get( 'chart', array() ); if ( empty( $chart['x'] ) || empty( $chart['y'] ) ) { return array(); } $rows = isset( $envelope['rows_assoc'] ) ? (array) $envelope['rows_assoc'] : array(); if ( empty( $rows ) ) { return array(); } $x = (string) $chart['x']; $ys = array_values( array_filter( array_map( 'strval', (array) $chart['y'] ) ) ); $limit = max( 1, min( 50, (int) ( isset( $chart['limit'] ) ? $chart['limit'] : 12 ) ) ); $slice = array_slice( $rows, 0, $limit ); $by_key = array(); foreach ( (array) $def->get( 'columns', array() ) as $col ) { if ( isset( $col['key'] ) ) { $by_key[ (string) $col['key'] ] = $col; } } $categories = array(); foreach ( $slice as $row ) { $categories[] = (string) ( isset( $row[ $x ] ) ? $row[ $x ] : '' ); } $series = array(); foreach ( $ys as $y ) { $col = isset( $by_key[ $y ] ) ? $by_key[ $y ] : array(); $data = array(); foreach ( $slice as $row ) { $data[] = isset( $row[ $y ] ) ? (float) $row[ $y ] : 0.0; } $series[] = array( 'name' => self::translate( (string) ( isset( $col['label'] ) ? $col['label'] : $y ) ), 'key' => $y, 'data' => $data, 'money' => isset( $col['type'] ) && 'money' === (string) $col['type'], ); } $type = isset( $chart['type'] ) ? (string) $chart['type'] : 'bar'; return array( 'type' => in_array( $type, array( 'bar', 'line', 'area' ), true ) ? $type : 'bar', 'categories' => $categories, 'series' => $series, ); } private static function chart_html( $def, $envelope ) { if ( empty( $envelope['series'] ) ) { return ''; } $base = trailingslashit( AIEO_URI ) . 'assets/js/vendor/apexcharts/'; $dir = trailingslashit( AIEO_DIR ) . 'assets/js/vendor/apexcharts/'; wp_enqueue_style( 'aieo-apexcharts', $base . 'apexcharts.css', array(), file_exists( $dir . 'apexcharts.css' ) ? (string) filemtime( $dir . 'apexcharts.css' ) : AIEO_VERSION ); wp_enqueue_script( 'aieo-apexcharts', $base . 'apexcharts.min.js', array(), file_exists( $dir . 'apexcharts.min.js' ) ? (string) filemtime( $dir . 'apexcharts.min.js' ) : AIEO_VERSION, true ); $adapter = trailingslashit( AIEO_DIR ) . 'assets/js/aieo-report-chart.js'; wp_enqueue_script( 'aieo-report-chart', trailingslashit( AIEO_URI ) . 'assets/js/aieo-report-chart.js', array( 'aieo-apexcharts' ), file_exists( $adapter ) ? (string) filemtime( $adapter ) : AIEO_VERSION, true ); return '
"; } public static function html( $def, $envelope, $request = array(), $overrides = array() ) { $overrides = (array) $overrides; $exports = ! array_key_exists( 'library_exports', $overrides ) || ! empty( $overrides['library_exports'] ); unset( $overrides['library_exports'] ); $config = self::table_config( $def, $envelope, $request, $overrides ); if ( '' !== (string) $config['report'] && 'storefront' !== (string) ( $config['context'] ?? 'admin' ) && self::library_on( $def ) ) { $config = self::library_config( $def, $config, $request, $exports ); } return self::chart_html( $def, $envelope ) . AIEO_Table::get_html( $config ); } public static function answer( $report_id, $request ) { $def = AIEO_Report_Registry::get( $report_id ); if ( ! $def ) { return array( 'error' => 'no_such_report' ); } $envelope = ( new AIEO_Report_Query( $def, $request ) )->run(); if ( isset( $envelope['error'] ) ) { return $envelope; } $series = self::chart_series( $def, $envelope ); $config = self::table_config( $def, $envelope, $request, array() ); if ( isset( $config['meta']['sort'] ) ) { $config['meta']['sort'] = $def->column_for_sort( (string) $config['meta']['sort'] ); } $config['edit'] = self::edit_route( $def ); $config['answer_extra'] = $series ? array( 'series' => $series ) : null; if ( function_exists( 'rooster_admin_builders' ) ) { rooster_admin_builders(); } return AIEO_Table::remote_answer( $config ); } private static function table_config( $def, $envelope, $request, $overrides ) { $req = AIEO_Report_Query::normalise_request( $request, $def ); return array_merge( array( 'report' => $def->id(), 'meta' => isset( $envelope['meta'] ) ? $envelope['meta'] : array(), 'columns' => self::table_columns( $def ), 'filter_columns' => self::filter_columns( $def ), 'rows' => self::table_rows( $envelope ), 'row_key' => $def->row_key(), 'row_type' => (string) $def->get( 'row_type', '' ), 'group_by' => (string) $def->get( 'group_by', '' ), 'actions' => self::gated_actions( $def ), 'bulk' => self::gated_bulk_actions( $def ), 'page_id' => $def->id(), 'totals' => isset( $envelope['totals'] ) ? $envelope['totals'] : array(), 'totals_at' => 'foot', 'totals_label' => __( 'All matching rows', 'ai-eshop-optimizer' ), 'empty' => self::empty_text( $def ), 'search' => $req['search'], 'params' => $req['params'], ), (array) $overrides ); } const FILTER_CONTROLS = array( 'cancellations_hotspots' => 'top_reason_slug:select last_cancelled_at:presets total_orders:buckets total_cancellations:buckets cancellation_rate:slider', 'cancellations_risk_users' => 'risk_band:select top_reason_slug:select last_cancelled_at:presets total_orders:buckets total_cancellations:buckets cancellation_rate:slider', 'erp_landed_cost_margin' => 'supplier:combo last_bought:presets net_spend:inputs margin_pct:slider', 'erp_purchases_by_supplier' => 'currency:select last_doc:presets net_purchases:inputs', 'erp_supplier_price_drift' => 'supplier:combo currency:select last_seen:presets drift_pct:slider', 'erp_vat_reconciliation' => 'month:combo vat_rate:select currency:select', 'google_reviews_history' => 'rating:select match_method:segmented is_visible:segmented location_label:chips review_time:calendar seen_at:presets', 'insights_basket_position' => 'cart_position:segmented product_state:segmented menu_category:chips head_category:chips sub_category:chips frequency:buckets stock:inputs', 'insights_cart_products' => 'payment_method:select quantity:chips brand:chips menu_category:chips head_category:chips sub_category:chips prof_discount:select date_created_gmt:calendar order_items:inputs order_sequence:inputs', 'insights_customer_order_averages' => 'BuyersPayrol:select BuyersDay:select BuyersTime:select OrderSpend:inputs NumberOfItemsPerOrder:buckets AveSpendOfUserPerItemPerOrder:inputs AveSpendOfUserPerOrder:inputs AveItemsOfUserPerOrder:buckets TotalNumberofOrders:buckets', 'insights_invoice_match' => 'order_status:chips match_status:chips invoice_branch:chips month_slot:combo report_month:combo shippingtype:chips order_datetime:calendar woo_total:inputs woo_net_total:inputs invoice_total:inputs invoice_date:calendar date_diff_days:inputs overlap_pct_vs_order:slider overlap_pct_vs_invoice:slider price_diff_pct:slider', 'insights_order_patterns' => 'ordersource:select orderstatus:select paymenttype:select orderdatetime:calendar', 'insights_out_of_stock' => 'best_match_estimator:segmented cost_known:segmented brand:chips menu_category:chips head_category:chips sub_category:chips current_stock:inputs out_of_stock_days:buckets out_of_stock_repetitions:buckets optimistic_cost:inputs average_cost:inputs pessimistic_cost:inputs reorder_quantity:inputs price:inputs price_adjustment_percentage:slider product_age:inputs product_creation_date:dates product_first_sale_date:calendar product_latest_sale_date:presets', 'insights_product_needs' => 'has_needs:segmented brand:combo menu_category:combo head_category:combo needs_count:buckets', 'insights_reorder_summary' => 'branch:combo status:select supplier:combo created_at:calendar', 'insights_stock_check' => 'stock_state:segmented brand:chips menu_category:chips head_category:chips sub_category:chips stock:inputs', 'insights_survey_results' => 'f18_is_pro:segmented f18_shipping_concern:segmented submitted_at:calendar f18_nps:inputs f18_satisfaction:inputs f18_site_ux_avg:inputs', 'insights_unit_sales' => 'brand:combo total_30d:inputs total_60d:inputs trend_of_total:slider eshop_30d:inputs', 'insights_variations_stock' => 'brand:combo menu_category:combo sub_category:combo latest_sale_gmt:presets out_of_stock_variations:inputs pct_out_of_stock:slider', 'landing_income_pages' => 's:buckets rev:inputs', 'landing_income_zeroes' => 's:buckets', 'missing_hot_sellers_priority' => 'branches:combo status:segmented needs_image:segmented needs_desc:segmented needs_cats:segmented needs_brand:segmented first_created:calendar phys_units:inputs phys_turnover:inputs', 'preorder_audit_log' => 'source:segmented branch:combo from_status:select to_status:select user_name:combo created_at:calendar', 'preorder_order_batches' => 'supplier:combo ordered_at:calendar', 'preorder_receive_reconcile' => 'branch:combo supplier:combo received_at:calendar short_qty:inputs', 'price_history_changes' => 'first_at:calendar changes:buckets last_at:presets', 'questionnaire_results' => 'kind:select', 'questionnaire_answers' => 'question:combo', 'questionnaire_responses' => 'wrote:segmented surface:select when:calendar', 'seo_linking_suggestions' => 'match_type:segmented status:segmented present:select score:slider', 'seo_meta_batch_catalogue' => 'post_type:select has_description:segmented ai_state:segmented demand:buckets striking:buckets', 'seo_opportunities_grid' => 'quadrant:segmented is_pillar:segmented object_type:select traffic_score:slider conversion_score:slider cornerstone_score:slider priority:slider focus_keyphrase:text', 'seo_redirects_rules' => 'is_regex:segmented status_code:select source:select last_hit:presets hits:buckets created_at:calendar', 'seo_gsc_terms' => 'object_type:select clicks:buckets impressions:buckets position:inputs', 'supplier_preorders_queue' => 'branch:combo status:select brand:combo supplier:combo created_at:calendar', 'preorder_worksheet_*' => 'has_request:segmented brand:combo supplier:combo menu_category:combo sales_30d:buckets', ); public static function library_on( $def ) { return $def && class_exists( 'AIEO_Table' ) && AIEO_Table::remote_ready(); } public static function prefix( $report_id ) { $words = array_values( array_filter( explode( '_', strtolower( (string) preg_replace( '/[^A-Za-z0-9_]/', '', (string) $report_id ) ) ), 'strlen' ) ); if ( ! $words ) { return 'r_'; } $last = array_pop( $words ); $head = ''; foreach ( $words as $word ) { $head .= $word[0]; } return ( '' !== $head ? $head . '_' : '' ) . substr( $last, 0, 8 ) . '_'; } private static function controls_for( $report_id ) { $line = self::FILTER_CONTROLS[ $report_id ] ?? ( 0 === strpos( (string) $report_id, 'preorder_worksheet_' ) ? self::FILTER_CONTROLS['preorder_worksheet_*'] : '' ); $out = array(); foreach ( preg_split( '/\s+/', trim( $line ) ) as $pair ) { if ( false !== strpos( $pair, ':' ) ) { list( $key, $control ) = explode( ':', $pair, 2 ); $out[ $key ] = $control; } } return $out; } private static function filter_decls( $def, $params = array(), $with_options = true, $search = '' ) { $controls = self::controls_for( $def->id() ); $scope = array_keys( (array) $def->get( 'params', array() ) ); $search = (array) $def->searchable_keys(); $out = array(); foreach ( $def->columns() as $col ) { $kind = (string) ( $col['filter'] ?? '' ); $key = (string) ( $col['key'] ?? '' ); if ( '' === $kind || in_array( $key, $scope, true ) || 1 !== preg_match( '/^[A-Za-z][A-Za-z0-9_-]*$/', $key ) ) { continue; } $want = $controls[ $key ] ?? ''; $type = (string) ( $col['type'] ?? '' ); $format = isset( $col['format'] ) && is_array( $col['format'] ) ? $col['format'] : array(); $d = array( 'key' => $key, 'label' => self::translate( (string) ( $col['label'] ?? $key ) ), ); switch ( $kind ) { case 'text': case 'number': if ( in_array( $key, $search, true ) ) { continue 2; } $d += array( 'kind' => 'text', 'control' => 'text', ); break; case 'number_range': $control = in_array( $want, array( 'inputs', 'slider', 'buckets' ), true ) ? $want : 'inputs'; $d += array( 'kind' => 'range', 'control' => $control, ); if ( 'slider' === $control ) { $d += self::slider_bounds( $col ); } elseif ( 'buckets' === $control ) { $own = $def->get( 'filter_bar', array() )['buckets'][ $key ] ?? null; $d['options'] = is_array( $own ) && $own ? array_values( array_map( 'strval', $own ) ) : array( '0', '1-10', '11-50', '51+' ); } elseif ( 'money' === $type && function_exists( 'get_woocommerce_currency_symbol' ) ) { $d['unit'] = html_entity_decode( (string) get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8' ); } elseif ( 'integer' === $type ) { $d['step'] = 1; } break; case 'date_range': $d += array( 'kind' => 'range', 'control' => in_array( $want, array( 'calendar', 'presets', 'dates' ), true ) ? $want : 'calendar', ); break; default: $labels = array(); foreach ( (array) ( $format['labels'] ?? array() ) as $value => $words ) { $labels[ (string) $value ] = is_string( $words ) ? self::translate( $words ) : (string) $value; } if ( 'boolean' === $type ) { $d += array( 'kind' => 'boolean', 'control' => 'segmented', ); break; } $control = 'multiselect' === $kind ? 'chips' : ( in_array( $want, array( 'select', 'combo', 'segmented' ), true ) ? $want : 'combo' ); $d += array( 'kind' => 'values', 'control' => $control, ); $chosen = $params[ $key ] ?? ''; $chosen = array_values( array_filter( array_map( 'strval', is_array( $chosen ) ? $chosen : array( $chosen ) ), 'strlen' ) ); $printed = in_array( $control, array( 'chips', 'segmented' ), true ); $options = $labels; if ( $printed && ! $options && $with_options ) { $found = ( new AIEO_Report_Query( $def, array( 'params' => $params ) ) )->filter_options( $key ); foreach ( (array) ( $found['options'] ?? array() ) as $value ) { $options[ (string) $value ] = (string) $value; } } foreach ( $chosen as $value ) { if ( ! isset( $options[ $value ] ) ) { $options[ $value ] = $value; } } $d['options'] = $options; if ( $with_options && ! empty( $col['counts'] ) ) { $d['counts'] = self::choice_counts( $def, $key, $params, $search ); } break; } $out[ $key ] = $d; } return self::arranged( $def, $out ); } private static function arranged( $def, array $decls ) { $levels = array_intersect_key( array( 'menu_category' => __( 'Menu', 'ai-eshop-optimizer' ), 'head_category' => __( 'Head', 'ai-eshop-optimizer' ), 'sub_category' => __( 'Sub', 'ai-eshop-optimizer' ), ), $decls ); if ( count( $levels ) > 1 ) { $out = array(); foreach ( $decls as $key => $d ) { if ( ! isset( $levels[ $key ] ) ) { $out[ $key ] = $d; continue; } foreach ( $levels as $level => $words ) { if ( ! isset( $out[ $level ] ) ) { $out[ $level ] = array_merge( $decls[ $level ], array( 'label' => $words, 'group' => __( 'Category', 'ai-eshop-optimizer' ), ) ); } } } $decls = $out; } $first = array_values( array_intersect( array_map( 'strval', (array) ( $def->get( 'filter_bar', array() )['first'] ?? array() ) ), array_keys( $decls ) ) ); if ( array() === $first ) { return $decls; } $out = array(); foreach ( $first as $key ) { $out[ $key ] = $decls[ $key ]; } foreach ( $decls as $key => $d ) { if ( ! isset( $out[ $key ] ) ) { $out[ $key ] = $d + array( 'more' => true ); } } return $out; } public static function choice_counts( $def, $key, $params, $search = '' ) { $others = (array) $params; unset( $others[ $key ] ); $found = ( new AIEO_Report_Query( $def, array( 'params' => $others ) ) )->filter_options( $key ); $multi = 'multiselect' === (string) ( $def->filterable()[ $key ] ?? '' ); $out = array(); foreach ( (array) ( $found['options'] ?? array() ) as $value ) { $value = (string) $value; $one = $others + array( $key => $multi ? array( $value ) : $value ); $out[ $value ] = ( new AIEO_Report_Query( $def, array( 'params' => $one, 'search' => (string) $search ) ) )->count_filtered(); } return $out; } public static function counts_choices( $def, $key ) { foreach ( $def->columns() as $col ) { if ( (string) ( $col['key'] ?? '' ) === (string) $key ) { return ! empty( $col['counts'] ); } } return false; } public static function lazy_filters( $def ) { $out = array(); foreach ( self::filter_decls( $def, array(), false ) as $key => $d ) { if ( 'values' === $d['kind'] && in_array( $d['control'], array( 'select', 'combo' ), true ) ) { $out[ $key ] = (array) ( $d['options'] ?? array() ); } } return $out; } private static function slider_bounds( $col ) { $type = (string) ( $col['type'] ?? '' ); $format = isset( $col['format'] ) && is_array( $col['format'] ) ? $col['format'] : array(); if ( 'percent' === $type ) { return array( 'min' => 0, 'max' => 100, 'step' => 1, 'unit' => '%' ); } if ( 'bar' === $type && is_numeric( $format['max'] ?? null ) ) { return array( 'min' => 0, 'max' => 0 + $format['max'], 'step' => 1 ); } if ( 'decimal' === $type ) { return array( 'min' => 0, 'max' => 1, 'step' => 0.01 ); } return array( 'min' => 0, 'max' => 100, 'step' => 1 ); } private static function ratio_keys( $def ) { $controls = self::controls_for( $def->id() ); $out = array(); foreach ( $def->columns() as $col ) { if ( 'percent' === ( $col['type'] ?? '' ) && 'number_range' === ( $col['filter'] ?? '' ) && 'ratio' === ( $col['format']['of'] ?? '' ) && 'slider' === ( $controls[ (string) $col['key'] ] ?? '' ) ) { $out[] = (string) $col['key']; } } return $out; } public static function query_params( $def, $params ) { $ratio = self::ratio_keys( $def ); $out = array(); foreach ( (array) $params as $key => $value ) { if ( is_array( $value ) && ( array_key_exists( 'from', $value ) || array_key_exists( 'to', $value ) ) ) { $value = array_filter( array( 'from' => (string) ( $value['from'] ?? '' ), 'to' => (string) ( $value['to'] ?? '' ), ), 'strlen' ); if ( in_array( (string) $key, $ratio, true ) ) { $value = array_map( static function ( $n ) { return is_numeric( $n ) ? (string) ( $n / 100 ) : $n; }, $value ); } if ( ! $value ) { continue; } } elseif ( is_array( $value ) ) { $value = array_values( array_filter( array_map( 'strval', $value ), 'strlen' ) ); if ( ! $value ) { continue; } } elseif ( '' === (string) $value ) { continue; } $out[ $key ] = $value; } return $out; } private static function view_values( $def, $params, $decls ) { $ratio = self::ratio_keys( $def ); $out = array(); foreach ( $decls as $key => $d ) { $value = $params[ $key ] ?? null; if ( 'range' === $d['kind'] ) { $value = array( 'from' => is_array( $value ) ? (string) ( $value['from'] ?? '' ) : '', 'to' => is_array( $value ) ? (string) ( $value['to'] ?? '' ) : '', ); if ( in_array( $key, $ratio, true ) ) { $value = array_map( static function ( $n ) { return is_numeric( $n ) ? (string) round( $n * 100, 4 ) : $n; }, $value ); } } elseif ( 'chips' === ( $d['control'] ?? '' ) ) { $value = array_values( array_map( 'strval', is_array( $value ) ? $value : ( null === $value || '' === $value ? array() : array( $value ) ) ) ); } else { $value = is_scalar( $value ) ? (string) $value : ''; } $out[ $key ] = $value; } return $out; } public static function view_request( $def, $request, $signed = true ) { $p = self::prefix( $def->id() ); $r = (array) $request; $get = static function ( $name ) use ( $signed ) { return $signed ? \Rooster\Admin\Request::text( $name ) : self::address_text( $name ); }; if ( null !== $get( $p . 's' ) ) { $r['search'] = $get( $p . 's' ); } if ( null !== $get( $p . 'orderby' ) ) { $r['sort'] = (string) preg_replace( '/[^a-zA-Z0-9_]/', '', $get( $p . 'orderby' ) ); $r['dir'] = 'desc' === strtolower( (string) $get( $p . 'order' ) ) ? 'desc' : 'asc'; } if ( null !== $get( $p . 'paged' ) ) { $r['page'] = max( 1, absint( $get( $p . 'paged' ) ) ); } if ( null !== $get( $p . 'per_page' ) ) { $r['per_page'] = absint( $get( $p . 'per_page' ) ); } $decls = self::filter_decls( $def, array(), false ); $names = array(); foreach ( array_keys( $decls ) as $key ) { $names[] = $p . $key; } $source = $signed ? \Rooster\Admin\Request::values( $names ) : self::address_values( $names ); if ( array() !== $source && class_exists( '\Rooster\Admin\Filters' ) ) { $scope = array_intersect_key( (array) ( $r['params'] ?? array() ), (array) $def->get( 'params', array() ) ); $r['params'] = $scope + self::query_params( $def, \Rooster\Admin\Filters::values( array_values( $decls ), $p, $signed ? null : wp_slash( $source ) ) ); } return $r; } public static function address_text( $name ) { return isset( $_GET[ $name ] ) && is_scalar( $_GET[ $name ] ) ? sanitize_text_field( wp_unslash( (string) $_GET[ $name ] ) ) : null; } public static function address_values( array $names ) { $out = array(); foreach ( $names as $name ) { $name = (string) $name; if ( ! isset( $_GET[ $name ] ) ) { continue; } $value = wp_unslash( $_GET[ $name ] ); if ( is_array( $value ) ) { $inner = array(); foreach ( $value as $k => $v ) { if ( is_scalar( $v ) ) { $inner[ preg_replace( '/[^a-zA-Z0-9_]/', '', (string) $k ) ] = sanitize_text_field( (string) $v ); } } $out[ $name ] = $inner; } elseif ( is_scalar( $value ) ) { $out[ $name ] = sanitize_text_field( (string) $value ); } } return $out; } private static function edit_route( $def ) { $editable = false; foreach ( $def->columns() as $col ) { $editable = $editable || ! empty( $col['editable'] ); } if ( ! $editable || ! $def->user_can( 'edit' ) ) { return array(); } $nonce = wp_create_nonce( AIEO_DMM::NONCE_ACTION ); return array( 'url' => add_query_arg( array( 'action' => AIEO_Report_Ajax::ACTION_SAVE, 'report' => $def->id(), 'nonce' => $nonce, ), admin_url( 'admin-ajax.php' ) ), 'nonce' => $nonce, ); } private static function library_config( $def, $config, $request, $exports ) { $req = AIEO_Report_Query::normalise_request( $request, $def ); $p = self::prefix( $def->id() ); $nonce = wp_create_nonce( AIEO_DMM::NONCE_ACTION ); $ajax = admin_url( 'admin-ajax.php' ); $scope = array_intersect_key( (array) $req['params'], (array) $def->get( 'params', array() ) ); $decls = self::filter_decls( $def, (array) $req['params'], true, (string) $req['search'] ); $wide = array( 'report' => $def->id() ); foreach ( $scope as $key => $value ) { if ( is_scalar( $value ) ) { $wide[ 'params[' . $key . ']' ] = (string) $value; } } $lazy = false; foreach ( $decls as $d ) { $lazy = $lazy || ( 'values' === $d['kind'] && in_array( $d['control'], array( 'select', 'combo' ), true ) ); } $sort = $def->default_sort(); $config['remote'] = array( 'url' => add_query_arg( 'action', AIEO_Report_Ajax::ACTION_FETCH, $ajax ), 'nonce' => $nonce, 'scope' => $wide, 'scope_params' => $scope, 'options' => $lazy ? add_query_arg( 'action', AIEO_Report_Ajax::ACTION_OPTIONS, $ajax ) : '', 'prefix' => $p, 'sort' => $sort ? array( 'key' => $def->column_for_sort( $sort[0] ), 'dir' => strtolower( $sort[1] ) ) : null, ); if ( isset( $config['meta']['sort'] ) ) { $config['meta']['sort'] = $def->column_for_sort( (string) $config['meta']['sort'] ); } $config['nonce'] = $nonce; $config['filters'] = array_values( $decls ); $config['filter_values'] = self::view_values( $def, (array) $req['params'], $decls ); $config['edit'] = self::edit_route( $def ); $config['caption'] = '' !== (string) ( $config['caption'] ?? '' ) ? $config['caption'] : self::translate( (string) $def->get( 'label', '' ) ); $shown = array_values( array_map( 'strval', (array) $def->get( 'columns_shown', array() ) ) ); if ( $shown ) { $config['chooser'] = array( 'shown' => $shown ); $config['text_size'] = true; } if ( $exports ) { $config['export'] = self::export_pair( $def, $req, $decls, $config['filter_values'] ); } return $config; } private static function export_pair( $def, $req, $decls, $values ) { if ( ! self::may_export( $def ) ) { return array(); } $p = self::prefix( $def->id() ); $base = array( 'action' => AIEO_Report_Ajax::ACTION_EXPORT, 'report' => $def->id(), 'nonce' => wp_create_nonce( AIEO_DMM::NONCE_ACTION ), ); $scope = array_intersect_key( (array) $req['params'], (array) $def->get( 'params', array() ) ); if ( $scope ) { $base['params'] = $scope; } if ( '' !== (string) $req['search'] ) { $base[ $p . 's' ] = (string) $req['search']; } $sort = $def->default_sort(); if ( '' !== (string) $req['sort'] && ( ! $sort || $sort[0] !== $req['sort'] || $sort[1] !== $req['dir'] ) ) { $base[ $p . 'orderby' ] = (string) $req['sort']; $base[ $p . 'order' ] = strtolower( (string) $req['dir'] ); } foreach ( $values as $key => $value ) { if ( is_array( $value ) && isset( $decls[ $key ] ) && 'range' === $decls[ $key ]['kind'] ) { $value = array_filter( $value, 'strlen' ); if ( $value ) { $base[ $p . $key ] = $value; } } elseif ( is_array( $value ) ) { if ( $value ) { $base[ $p . $key ] = implode( ',', $value ); } } elseif ( '' !== (string) $value ) { $base[ $p . $key ] = (string) $value; } } $urls = array(); foreach ( array( 'csv', 'xlsx' ) as $format ) { $urls[ $format ] = add_query_arg( array_merge( $base, array( 'format' => $format ) ), admin_url( 'admin-post.php' ) ); } return array( 'csv' => $urls['csv'], 'xlsx' => $urls['xlsx'], 'scope' => __( 'Exports every row that matches the current search and filters, not only this page.', 'ai-eshop-optimizer' ), 'id' => 'aieo-t-export-' . sanitize_html_class( $def->id() ), 'columns' => 'visible', ); } private static function may_export( $def ) { if ( ! $def || ! class_exists( 'AIEO_Report_Export' ) || ! class_exists( 'AIEO_Table_Registry' ) ) { return false; } $rid = (string) $def->get( 'registry_id', '' ); $row = $rid ? AIEO_Table_Registry::get( $rid ) : null; return $row && ! empty( $row['caps']['export'] ) && AIEO_Report_Export::may_export( $def, AIEO_Report_Export::policy( $def ) ); } public static function export_request( $def, $request, $source ) { $p = self::prefix( $def->id() ); $clean = static function ( $name ) use ( $source ) { return isset( $source[ $name ] ) && is_scalar( $source[ $name ] ) ? sanitize_text_field( wp_unslash( (string) $source[ $name ] ) ) : null; }; $r = (array) $request; if ( null !== $clean( $p . 's' ) ) { $r['search'] = $clean( $p . 's' ); } if ( null !== $clean( $p . 'orderby' ) ) { $r['sort'] = (string) preg_replace( '/[^a-zA-Z0-9_]/', '', $clean( $p . 'orderby' ) ); $r['dir'] = 'desc' === strtolower( (string) $clean( $p . 'order' ) ) ? 'desc' : 'asc'; } if ( ! class_exists( '\Rooster\Admin\Filters' ) && function_exists( 'rooster_admin_builders' ) ) { rooster_admin_builders(); } if ( class_exists( '\Rooster\Admin\Filters' ) ) { $r['params'] = self::query_params( $def, \Rooster\Admin\Filters::values( array_values( self::filter_decls( $def, array(), false ) ), $p, (array) $source ) ) + (array) ( $r['params'] ?? array() ); } return $r; } public static function card( $report_id, $card = array(), $request = null ) { $c = array_merge( array( 'anchor' => '', 'icon' => '', 'title' => '', 'heading' => 'h3', 'description' => '', 'footnote' => '', 'footnote_role' => 'essential', 'exports' => true, 'wrap' => true, 'overrides' => array(), ), (array) $card ); $def = AIEO_Report_Registry::get( $report_id ); if ( $c['wrap'] || '' !== (string) $c['title'] ) { $shell = AIEO_Table::card_shell( array_merge( array_intersect_key( $c, array_flip( array( 'col', 'span', 'min', 'movable', 'essential', 'meta' ) ) ), array( 'anchor' => $c['anchor'], 'icon' => $c['icon'], 'title' => $c['title'], 'level' => 'h2' === $c['heading'] && $c['wrap'] ? 2 : 3, 'description' => $c['description'], 'footnote' => $c['footnote'], 'flush' => true, ) ) ); } elseif ( class_exists( '\Rooster\Admin\Guidance' ) ) { $shell = array( '' !== (string) $c['description'] ? \Rooster\Admin\Guidance::text( (string) $c['description'] ) : '', '' !== (string) $c['footnote'] ? \Rooster\Admin\Guidance::text( (string) $c['footnote'], 'guidance' === $c['footnote_role'] ? 'guidance' : 'essential' ) : '', ); } else { $shell = array( '' !== (string) $c['description'] ? '' . esc_html( $c['description'] ) . '
' : '', '' !== (string) $c['footnote'] ? '' . esc_html( $c['footnote'] ) . '
' : '', ); } $open = $shell[0]; if ( ! $def ) { echo $open . self::failed_html( __( 'This table could not be built. Its definition is missing.', 'ai-eshop-optimizer' ) ) . $shell[1]; return; } if ( ! $def->user_can( 'view' ) ) { return; } $req = ( null === $request ) ? self::request_from_url( $report_id ) : (array) $request; $library = self::library_on( $def ); if ( $library ) { $req = self::view_request( $def, $req ); $c['overrides'] = (array) $c['overrides']; $c['overrides']['library_exports'] = ! empty( $c['exports'] ); $c['exports'] = false; } $envelope = self::run( $report_id, $req, (array) $c['overrides'] ); if ( isset( $envelope['error'] ) ) { echo $open . self::failed_html( __( 'This table could not be built. Its definition may be invalid.', 'ai-eshop-optimizer' ) ) . $shell[1]; return; } echo $open; if ( $c['exports'] ) { echo self::export_bar( $report_id, $req ); } echo $envelope['html']; echo $shell[1]; } public static function failed_html( $text ) { if ( class_exists( '\Rooster\Admin\States' ) ) { return \Rooster\Admin\States::state( 'failed', array( 'text' => (string) $text ) ); } return '' . esc_html( (string) $text ) . '
' . $html . '
'; } $shell = AIEO_Table::card_shell( array( 'anchor' => $anchor, 'icon' => 'chart-column', 'title' => __( 'Summary', 'ai-eshop-optimizer' ), ) ); return $shell[0] . '' . \Rooster\Admin\Guidance::export( array( 'csv' => $urls['csv'], 'xlsx' => $urls['xlsx'], 'scope' => __( 'Exports every row that matches the current search and filters, not only this page.', 'ai-eshop-optimizer' ), 'id' => 'aieo-t-export-' . sanitize_html_class( (string) $report_id ), ) ) . '
'; } $out = ''; foreach ( $urls as $format => $url ) { $out .= '' . esc_html( sprintf( __( 'Export %s', 'ai-eshop-optimizer' ), strtoupper( $format ) ) ) . ' '; } return $out . '
'; } public static function request_from_url( $report_id = '' ) { $target = isset( $_GET['rt'] ) ? sanitize_key( wp_unslash( $_GET['rt'] ) ) : ''; if ( '' !== $target && '' !== (string) $report_id && $target !== (string) $report_id ) { return array( 'page' => 1, 'sort' => '', 'dir' => '', 'search' => '', 'params' => array() ); } $params = array(); if ( isset( $_GET['rp'] ) && is_array( $_GET['rp'] ) ) { foreach ( wp_unslash( $_GET['rp'] ) as $key => $value ) { $key = preg_replace( '/[^a-zA-Z0-9_]/', '', (string) $key ); if ( '' === $key || is_array( $value ) ) { continue; } $params[ $key ] = sanitize_text_field( (string) $value ); } } $request = array( 'page' => isset( $_GET['rpage'] ) ? absint( $_GET['rpage'] ) : 1, 'sort' => isset( $_GET['rsort'] ) ? preg_replace( '/[^a-zA-Z0-9_]/', '', (string) wp_unslash( $_GET['rsort'] ) ) : '', 'dir' => isset( $_GET['rdir'] ) ? sanitize_key( wp_unslash( $_GET['rdir'] ) ) : '', 'search' => isset( $_GET['rq'] ) ? sanitize_text_field( wp_unslash( $_GET['rq'] ) ) : '', 'params' => $params, ); return $request; } private static function gated_actions( $def ) { $fallback = $def->capability_for( 'execute' ); $out = array(); foreach ( $def->actions() as $action ) { if ( empty( $action['capability'] ) && '' !== $fallback ) { $action['capability'] = $fallback; } foreach ( array( 'label', 'confirm', 'confirm_noun', 'confirm_body' ) as $key ) { if ( ! empty( $action[ $key ] ) && is_string( $action[ $key ] ) ) { $action[ $key ] = self::translate( $action[ $key ] ); } } if ( ! empty( $action['ask']['label'] ) && is_string( $action['ask']['label'] ) ) { $action['ask']['label'] = self::translate( $action['ask']['label'] ); } $out[] = $action; } return $out; } private static function gated_bulk_actions( $def ) { $fallback = $def->capability_for( 'execute' ); $edit_cap = $def->capability_for( 'edit' ); $labels = array(); foreach ( $def->columns() as $col ) { $labels[ (string) $col['key'] ] = (string) $col['label']; } $out = array(); foreach ( $def->bulk_actions() as $action ) { if ( ! empty( $action['set_column'] ) ) { $col_key = (string) $action['set_column']; $col_label = self::translate( isset( $labels[ $col_key ] ) ? $labels[ $col_key ] : $col_key ); if ( '' === (string) $action['label'] ) { $action['label'] = sprintf( __( 'Set %s on selected', 'ai-eshop-optimizer' ), $col_label ); } if ( '' === (string) $action['confirm'] ) { $action['confirm'] = str_replace( '%3$s', $col_label, __( 'Set %3$s to %2$s on %1$s selected rows?', 'ai-eshop-optimizer' ) ); } if ( empty( $action['capability'] ) && '' !== $edit_cap ) { $action['capability'] = $edit_cap; } } elseif ( empty( $action['capability'] ) && '' !== $fallback ) { $action['capability'] = $fallback; } foreach ( array( 'label', 'confirm' ) as $key ) { if ( ! empty( $action[ $key ] ) && is_string( $action[ $key ] ) && empty( $action['set_column'] ) ) { $action[ $key ] = self::translate( $action[ $key ] ); } } if ( ! empty( $action['param'] ) && is_array( $action['param'] ) ) { if ( ! empty( $action['param']['label'] ) && is_string( $action['param']['label'] ) ) { $action['param']['label'] = self::translate( $action['param']['label'] ); } if ( ! empty( $action['param']['options'] ) && is_array( $action['param']['options'] ) ) { foreach ( $action['param']['options'] as $ok => $ov ) { if ( is_string( $ov ) && '' !== $ov ) { $action['param']['options'][ $ok ] = self::translate( $ov ); } } } } $out[] = $action; } return $out; } private static function filter_columns( $def ) { return array_values( array_filter( self::table_columns( $def, true ), static function ( $col ) { return ! empty( $col['filter'] ); } ) ); } private static function table_columns( $def, $with_hidden = false ) { $out = array(); foreach ( $def->columns() as $col ) { if ( ! $with_hidden && ! empty( $col['hidden'] ) ) { continue; } unset( $col['select'] ); $col['label'] = self::translate( (string) $col['label'] ); if ( isset( $col['format']['text'] ) && is_string( $col['format']['text'] ) && '' !== $col['format']['text'] ) { $col['format']['text'] = self::translate( $col['format']['text'] ); } if ( '' !== (string) $col['header_tip'] ) { $col['header_tip'] = self::translate( (string) $col['header_tip'] ); } if ( '' !== (string) ( $col['sr_label'] ?? '' ) ) { $col['sr_label'] = self::translate( (string) $col['sr_label'] ); } if ( ! empty( $col['format']['labels'] ) && is_array( $col['format']['labels'] ) ) { foreach ( $col['format']['labels'] as $value => $label ) { if ( is_string( $label ) && '' !== $label ) { $col['format']['labels'][ $value ] = self::translate( $label ); } } } $out[] = $col; } return $out; } private static function table_rows( $envelope ) { return isset( $envelope['rows_assoc'] ) ? (array) $envelope['rows_assoc'] : array(); } private static function translate( $text ) { if ( '' === $text ) { return ''; } return __( $text, 'ai-eshop-optimizer' ); } }