__( 'Campaigns', 'ai-eshop-optimizer' ), 'description' => __( 'Build automated multi-step campaigns (the AutomateWoo-familiar Trigger → Audience → Steps builder) with push-first / email-fallback delivery, native coupons, and behavioural product recommendations — paused-by-default so you can watch a campaign run end to end before a single message sends.', 'ai-eshop-optimizer' ), 'bullets' => array( __( 'Triggers: abandoned cart, birthday, welcome, back-in-stock, win-back, scheduled', 'ai-eshop-optimizer' ), __( 'Push-first cascade with email fallback and frequency caps', 'ai-eshop-optimizer' ), __( 'Per-recipient native coupons + one-click apply links', 'ai-eshop-optimizer' ), ), ); } public function register_hooks() { add_action( 'wp_ajax_aieo_dmm_wf_list', array( $this, 'ajax_list' ) ); add_action( 'wp_ajax_aieo_dmm_wf_get', array( $this, 'ajax_get' ) ); add_action( 'wp_ajax_aieo_dmm_wf_save', array( $this, 'ajax_save' ) ); add_action( 'wp_ajax_aieo_dmm_wf_delete', array( $this, 'ajax_delete' ) ); add_action( 'wp_ajax_aieo_dmm_wf_status', array( $this, 'ajax_status' ) ); add_action( 'wp_ajax_aieo_dmm_wf_run', array( $this, 'ajax_run' ) ); add_action( 'wp_ajax_aieo_dmm_wf_preview', array( $this, 'ajax_preview' ) ); add_action( 'wp_ajax_aieo_dmm_wf_test', array( $this, 'ajax_test' ) ); add_action( 'wp_ajax_aieo_wf_search_products', array( $this, 'ajax_search_products' ) ); add_action( 'wp_ajax_aieo_wf_search_terms', array( $this, 'ajax_search_terms' ) ); add_action( 'wp_ajax_aieo_dmm_wf_engine', array( $this, 'ajax_engine' ) ); add_action( 'wp_ajax_aieo_dmm_wf_testers', array( $this, 'ajax_testers' ) ); add_action( 'wp_ajax_aieo_dmm_wf_tester_run', array( $this, 'ajax_tester_run' ) ); add_action( 'wp_ajax_aieo_dmm_wf_test_coupons', array( $this, 'ajax_test_coupons' ) ); add_action( 'wp_ajax_aieo_wf_search_users', array( $this, 'ajax_search_users' ) ); } public function enqueue_admin_assets() { $css = 'assets/css/aieo-workflows-admin.css'; $js = 'assets/js/aieo-workflows-admin.js'; wp_enqueue_style( 'aieo-workflows-admin', plugins_url( $css, AIEO_FILE ), array(), file_exists( AIEO_DIR . $css ) ? (string) filemtime( AIEO_DIR . $css ) : '1' ); wp_enqueue_script( 'aieo-workflows-admin', plugins_url( $js, AIEO_FILE ), array(), file_exists( AIEO_DIR . $js ) ? (string) filemtime( AIEO_DIR . $js ) : '1', true ); } public function render_subtab() { if ( ! class_exists( 'AIEO_Workflows' ) ) { list( $open, $close ) = AIEO_DMM_UI::card( array( 'anchor' => 'workflows-campaigns-workflows', 'icon' => 'workflow', 'title' => __( 'Workflows', 'ai-eshop-optimizer' ), ) ); echo $open; echo \Rooster\Admin\Ui::notice( esc_html__( 'Workflow engine is not loaded.', 'ai-eshop-optimizer' ), 'destructive', array( 'inline' => true ) ); echo $close; return; } $audiences = array(); if ( class_exists( 'AIEO_Audience_Rules' ) ) { foreach ( AIEO_Audience_Rules::list_saved() as $a ) { $audiences[] = array( 'id' => $a['id'], 'name' => $a['name'], 'count' => $a['count_cached'] ); } } $email_live = class_exists( 'AIEO_Email_Engine' ) && AIEO_Email_Engine::is_live(); $push_live = class_exists( 'AIEO_DMM_Web_Push' ) && method_exists( 'AIEO_DMM_Web_Push', 'is_engine_live' ) && AIEO_DMM_Web_Push::is_engine_live(); $order_rule_fields = array(); $brand_tax = 'product_brand'; if ( class_exists( 'AIEO_Order_Rules' ) ) { foreach ( AIEO_Order_Rules::field_catalog() as $key => $def ) { $order_rule_fields[ $key ] = array( 'label' => $def['label'], 'type' => $def['type'], 'ops' => $def['ops'] ); } $brand_tax = AIEO_Order_Rules::brand_tax(); } $roles = array(); foreach ( wp_roles()->get_names() as $rk => $rname ) { $roles[ (string) $rk ] = translate_user_role( $rname ); } $vp = AIEO_DIR . 'assets/js/aieo-value-picker.js'; if ( is_readable( $vp ) ) { wp_enqueue_script( 'aieo-value-picker', plugins_url( 'assets/js/aieo-value-picker.js', AIEO_FILE ), array(), (string) filemtime( $vp ), true ); } $this->render_template( 'workflows.php', array( 'nonce' => wp_create_nonce( 'aieo_dmm_nonce' ), 'triggers' => AIEO_Workflows::trigger_catalog(), 'steps' => AIEO_Workflows::step_catalog(), 'audiences' => $audiences, 'engines' => array( 'email' => $email_live, 'push' => $push_live ), 'order_rule_fields' => $order_rule_fields, 'brand_tax' => $brand_tax, 'tag_tax' => (string) apply_filters( 'aieo_purchases_tag_taxonomy', 'product_tag' ), 'need_tax' => (string) apply_filters( 'aieo_purchases_needs_taxonomy', 'pa_need' ), 'roles' => $roles, ) ); } public function ajax_search_products() { AIEO_DMM::verify_ajax_request(); $this->require_pro(); $q = isset( $_GET['q'] ) ? sanitize_text_field( wp_unslash( $_GET['q'] ) ) : ''; $results = array(); if ( function_exists( 'wc_get_products' ) ) { $args = array( 'limit' => 20, 'status' => 'publish', 'orderby' => 'title', 'order' => 'ASC', 'return' => 'objects' ); if ( '' !== $q ) { if ( ctype_digit( $q ) ) { $args['include'] = array( (int) $q ); } else { $args['s'] = $q; } } foreach ( (array) wc_get_products( $args ) as $p ) { $sku = $p->get_sku(); $results[] = array( 'value' => (string) $p->get_id(), 'label' => $p->get_name() . ( $sku ? ' [' . $sku . ']' : '' ) . ' #' . $p->get_id(), ); } } wp_send_json( array( 'results' => $results ) ); } public function ajax_search_terms() { AIEO_DMM::verify_ajax_request(); $this->require_pro(); $q = isset( $_GET['q'] ) ? sanitize_text_field( wp_unslash( $_GET['q'] ) ) : ''; $tax = isset( $_GET['tax'] ) ? sanitize_key( wp_unslash( $_GET['tax'] ) ) : 'product_cat'; $brand = class_exists( 'AIEO_Order_Rules' ) ? AIEO_Order_Rules::brand_tax() : 'product_brand'; $tagtax = (string) apply_filters( 'aieo_purchases_tag_taxonomy', 'product_tag' ); $needtax = (string) apply_filters( 'aieo_purchases_needs_taxonomy', 'pa_need' ); $allowed = array( 'product_cat', $brand, $tagtax, $needtax ); if ( ! in_array( $tax, $allowed, true ) || ! taxonomy_exists( $tax ) ) { $tax = 'product_cat'; } $results = array(); $terms = get_terms( array( 'taxonomy' => $tax, 'hide_empty' => false, 'number' => 25, 'orderby' => 'name', 'search' => $q, ) ); if ( ! is_wp_error( $terms ) ) { foreach ( (array) $terms as $term ) { $results[] = array( 'value' => (string) $term->term_id, 'label' => $term->name . ' #' . $term->term_id ); } } wp_send_json( array( 'results' => $results ) ); } public function ajax_list() { AIEO_DMM::verify_ajax_request(); $workflows = AIEO_Workflows::list_all(); $stats = array(); if ( class_exists( 'AIEO_Workflow_Stats' ) ) { AIEO_Workflow_Stats::maybe_refresh(); $stats = AIEO_Workflow_Stats::get_all(); } foreach ( $workflows as &$w ) { $s = isset( $stats[ (int) $w['id'] ] ) ? $stats[ (int) $w['id'] ] : null; $w['stats'] = $s ? array( 'sent' => (int) $s['sent'], 'opens' => (int) ( $s['opens'] ?? 0 ), 'open_rate' => (float) ( $s['open_rate'] ?? 0 ), 'clicks' => (int) $s['clicks'], 'redeemed' => (int) $s['coupons_redeemed'], 'revenue' => round( (float) ( $s['attributed_revenue'] ?? 0 ), 2 ), 'ctr' => (float) $s['ctr'], 'last_send_at' => $s['last_send_at'], ) : null; } unset( $w ); $currency = function_exists( 'get_woocommerce_currency_symbol' ) ? html_entity_decode( get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8' ) : ''; $table = self::list_table( is_array( $workflows ) ? $workflows : array(), $currency ); wp_send_json_success( array( 'workflows' => $workflows, 'currency' => $currency, 'table' => $table, 'icons' => '' !== $table ? \Rooster\Admin\Ui::icons_of( $table ) : '', ) ); } public static function list_table( array $workflows, $currency = '' ) { if ( ! function_exists( 'rooster_admin_builders' ) || ! rooster_admin_builders() ) { return ''; } $catalog = class_exists( 'AIEO_Workflows' ) ? AIEO_Workflows::trigger_catalog() : array(); $words = array( 'active' => __( 'active', 'ai-eshop-optimizer' ), 'paused' => __( 'paused', 'ai-eshop-optimizer' ), 'draft' => __( 'draft', 'ai-eshop-optimizer' ), ); $tones = array( 'active' => 'success', 'paused' => 'warning', 'draft' => 'mono' ); $nf = static function ( $n ) { return (string) preg_replace( '/\B(?=(\d{3})+(?!\d))/', ',', (string) $n ); }; $rows = array(); foreach ( $workflows as $w ) { $id = (int) $w['id']; $status = (string) ( $w['status'] ?? 'draft' ); $type = (string) ( $w['trigger_type'] ?? '' ); $trigger = isset( $catalog[ $type ]['label'] ) ? (string) $catalog[ $type ]['label'] : $type; $s = is_array( $w['stats'] ?? null ) ? $w['stats'] : null; $perf = '—'; if ( $s && ! empty( $s['sent'] ) ) { $sep = ' › '; $perf = '' . esc_html( $nf( $s['sent'] ) ) . ' ' . esc_html__( 'sent', 'ai-eshop-optimizer' ) . ( ! empty( $s['opens'] ) ? $sep . esc_html( $nf( $s['opens'] ) ) . ' ' . esc_html__( 'opn', 'ai-eshop-optimizer' ) . ( ! empty( $s['open_rate'] ) ? ' (' . esc_html( (string) $s['open_rate'] ) . '%)' : '' ) : '' ) . $sep . esc_html( $nf( $s['clicks'] ) ) . ' ' . esc_html__( 'clk', 'ai-eshop-optimizer' ) . ( ! empty( $s['ctr'] ) ? ' (' . esc_html( (string) $s['ctr'] ) . '%)' : '' ) . $sep . esc_html( $nf( $s['redeemed'] ) ) . ' ' . esc_html__( 'red', 'ai-eshop-optimizer' ) . ( ! empty( $s['revenue'] ) ? ' · ' . esc_html( $currency . $nf( $s['revenue'] ) ) . '' : '' ) . ''; } $hook = static function ( $act, $extra = array() ) use ( $id ) { return array( 'data-aieo-wf' => $act, 'data-id' => $id ) + $extra; }; $rows[] = array( '_id' => (string) $id, '_name' => (string) $w['name'], '_attrs' => array( 'data-ra-s' => array( 'name' => (string) $w['name'], 'trigger' => $trigger, 'runs' => (int) ( $w['runs_count'] ?? 0 ), '_id' => $id ), 'data-ra-text' => (string) $w['name'], ), 'name' => array( 'html' => '' . esc_html( (string) $w['name'] ) . '' ), 'trigger' => $trigger, 'status' => array( 'label' => $words[ $status ] ?? $status, 'tone' => $tones[ $status ] ?? 'mono' ), 'runs' => (string) (int) ( $w['runs_count'] ?? 0 ), 'performance' => $s && ! empty( $s['sent'] ) ? array( 'html' => $perf, 'tip' => __( 'Sent → email opens (rate) → clicks (CTR) → coupons redeemed · revenue from the orders that used the coupon or came last through the message\'s link, each order once', 'ai-eshop-optimizer' ) ) : array( 'html' => $perf ), 'act' => array_values( array_filter( array( array( 'label' => __( 'Edit', 'ai-eshop-optimizer' ), 'attrs' => $hook( 'edit' ) ), 'active' === $status ? array( 'label' => __( 'Pause', 'ai-eshop-optimizer' ), 'attrs' => $hook( 'pause' ) ) : array( 'label' => __( 'Activate', 'ai-eshop-optimizer' ), 'attrs' => $hook( 'activate' ) ), array( 'label' => __( 'Preview', 'ai-eshop-optimizer' ), 'attrs' => $hook( 'preview' ) ), array( 'label' => __( 'Send test', 'ai-eshop-optimizer' ), 'attrs' => $hook( 'test' ) ), array( 'label' => __( 'Run now', 'ai-eshop-optimizer' ), 'attrs' => $hook( 'run' ) ), ( class_exists( 'AIEO_Automation_Test_Mode' ) && AIEO_Automation_Test_Mode::any_test() ) ? array( 'label' => __( 'Run for a tester', 'ai-eshop-optimizer' ), 'attrs' => $hook( 'tester', array( 'aria-haspopup' => 'dialog', 'data-name' => (string) $w['name'] ) ) ) : null, array( 'label' => __( 'Delete', 'ai-eshop-optimizer' ), 'destructive' => true, 'attrs' => $hook( 'delete', array( 'data-ra-confirm' => 'aieo-wf-delete-dialog', 'aria-haspopup' => 'dialog', 'data-name' => (string) $w['name'] ) ), ), ) ) ), ); } $id = 'aieo-wf-table'; $sort = static function ( $key, $type ) { return array( 'sort' => 'none', 'sort_type' => $type, 'sort_url' => '#wf_orderby=' . $key ); }; return \Rooster\Admin\Ui::table( array( array( 'key' => 'name', 'label' => __( 'Name', 'ai-eshop-optimizer' ), 'type' => 'text' ) + $sort( 'name', 'text' ), array( 'key' => 'trigger', 'label' => __( 'Trigger', 'ai-eshop-optimizer' ), 'type' => 'text' ) + $sort( 'trigger', 'text' ), array( 'key' => 'status', 'label' => __( 'Status', 'ai-eshop-optimizer' ), 'type' => 'status' ), array( 'key' => 'runs', 'label' => __( 'People reached', 'ai-eshop-optimizer' ), 'type' => 'num', 'tip' => __( 'One for each time this automation delivered at least one message to a customer. A customer it ran for twice counts twice; a run that sent nothing does not count.', 'ai-eshop-optimizer' ), ) + $sort( 'runs', 'number' ), array( 'key' => 'performance', 'label' => __( 'Performance', 'ai-eshop-optimizer' ), 'type' => 'html' ), array( 'key' => 'act', 'label' => __( 'Actions', 'ai-eshop-optimizer' ), 'type' => 'actions' ), ), $rows, array( 'id' => $id, 'caption' => __( 'Workflows', 'ai-eshop-optimizer' ), 'local' => array( 'size' => 25, 'sizes' => array( 25, 50, 100 ), 'words' => true, 'prefix' => 'wf_' ), 'toolbar' => \Rooster\Admin\Filters::bar( $id, array(), array(), array( 'prefix' => 'wf_', 'search' => array( 'label' => __( 'Search', 'ai-eshop-optimizer' ), 'placeholder' => __( 'Workflow names', 'ai-eshop-optimizer' ) ), 'keys' => array( 's' => 'wf_s' ), ) ), 'empty' => \Rooster\Admin\States::state( 'first-use', array( 'compact' => true, 'title' => __( 'No workflows yet. Create one above.', 'ai-eshop-optimizer' ) ) ), ) ); } public function ajax_get() { AIEO_DMM::verify_ajax_request(); $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; $wf = AIEO_Workflows::get( $id ); wp_send_json_success( array( 'workflow' => $wf, 'orf_labels' => is_array( $wf ) ? $this->resolve_orf_labels( $wf ) : (object) array(), ) ); } private function resolve_orf_labels( $wf ) { $out = array(); if ( ! in_array( (string) ( $wf['trigger_type'] ?? '' ), array( 'order_completed', 'abandoned_checkout' ), true ) ) { return (object) $out; } $rules = ( isset( $wf['trigger_config']['order_rules'] ) && is_array( $wf['trigger_config']['order_rules'] ) ) ? $wf['trigger_config']['order_rules'] : array(); $products = array(); $terms = array(); $walk = function ( $node ) use ( &$walk, &$products, &$terms ) { if ( ! is_array( $node ) ) { return; } if ( isset( $node['conditions'] ) && is_array( $node['conditions'] ) ) { foreach ( $node['conditions'] as $c ) { $walk( $c ); } return; } $field = (string) ( $node['field'] ?? '' ); $vals = is_array( $node['value'] ?? null ) ? $node['value'] : array( $node['value'] ?? '' ); foreach ( $vals as $v ) { $id = (int) $v; if ( $id <= 0 ) { continue; } if ( 'order_items' === $field ) { $products[ $id ] = true; } elseif ( in_array( $field, array( 'order_categories', 'order_brands', 'order_tags', 'order_needs' ), true ) ) { $terms[ $id ] = true; } } }; $walk( $rules ); foreach ( array_keys( $products ) as $pid ) { if ( function_exists( 'wc_get_product' ) ) { $p = wc_get_product( $pid ); if ( $p ) { $sku = $p->get_sku(); $out[ (string) $pid ] = $p->get_name() . ( $sku ? ' [' . $sku . ']' : '' ) . ' #' . $pid; } } } foreach ( array_keys( $terms ) as $tid ) { $term = get_term( $tid ); if ( $term && ! is_wp_error( $term ) ) { $out[ (string) $tid ] = $term->name . ' #' . $tid; } } return empty( $out ) ? (object) array() : $out; } private function require_pro() { if ( ! self::is_aieo_pro_user() ) { wp_send_json_error( array( 'message' => __( 'This feature requires the Pro version.', 'ai-eshop-optimizer' ) ) ); } } public function ajax_save() { AIEO_DMM::verify_ajax_request(); $this->require_pro(); $raw = isset( $_POST['workflow'] ) ? wp_unslash( $_POST['workflow'] ) : ''; $data = is_string( $raw ) ? json_decode( $raw, true ) : null; if ( ! is_array( $data ) || '' === trim( (string) ( $data['name'] ?? '' ) ) ) { wp_send_json_error( array( 'message' => __( 'A name and trigger are required.', 'ai-eshop-optimizer' ) ) ); } if ( 'active' === (string) ( $data['status'] ?? '' ) && self::broadcast_without_audience( $data ) ) { wp_send_json_error( array( 'message' => self::audience_needed() ) ); } $id = AIEO_Workflows::save( $data ); wp_send_json_success( array( 'id' => $id ) ); } private static function broadcast_without_audience( array $wf ) { return in_array( (string) ( $wf['trigger_type'] ?? '' ), array( 'scheduled', 'manual' ), true ) && (int) ( $wf['audience_id'] ?? 0 ) <= 0; } private static function audience_needed() { return __( 'Choose an audience: a broadcast goes to the customers of a saved audience, never to every customer.', 'ai-eshop-optimizer' ); } public function ajax_delete() { AIEO_DMM::verify_ajax_request(); $this->require_pro(); wp_send_json_success( array( 'deleted' => AIEO_Workflows::delete( isset( $_POST['id'] ) ? (int) $_POST['id'] : 0 ) ) ); } public function ajax_status() { AIEO_DMM::verify_ajax_request(); $this->require_pro(); $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; $status = isset( $_POST['status'] ) ? sanitize_key( wp_unslash( $_POST['status'] ) ) : 'draft'; $wf = 'active' === $status ? AIEO_Workflows::get( $id ) : null; if ( is_array( $wf ) && self::broadcast_without_audience( $wf ) ) { wp_send_json_error( array( 'message' => self::audience_needed() ) ); } wp_send_json_success( array( 'ok' => AIEO_Workflows::set_status( $id, $status ) ) ); } public function ajax_run() { AIEO_DMM::verify_ajax_request(); $this->require_pro(); if ( ! class_exists( 'AIEO_Workflow_Runtime' ) ) { wp_send_json_error( array( 'message' => 'runtime unavailable' ) ); } $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; $n = AIEO_Workflow_Runtime::run_manual( $id ); $out = array( 'enqueued' => (int) $n ); if ( $n <= 0 && method_exists( 'AIEO_Workflow_Runtime', 'manual_refusal' ) ) { $out['message'] = AIEO_Workflow_Runtime::manual_refusal( $id ); } wp_send_json_success( $out ); } public function ajax_preview() { AIEO_DMM::verify_ajax_request(); $this->require_pro(); $r = $this->render_preview(); if ( is_wp_error( $r ) ) { wp_send_json_error( array( 'message' => $r->get_error_message() ) ); } wp_send_json_success( $r ); } public function ajax_test() { AIEO_DMM::verify_ajax_request(); $this->require_pro(); $to = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( (string) $_POST['email'] ) ) : ''; if ( '' === $to || ! is_email( $to ) ) { wp_send_json_error( array( 'message' => __( 'Enter a valid test email address.', 'ai-eshop-optimizer' ) ) ); } $r = $this->render_preview( $to ); if ( is_wp_error( $r ) ) { wp_send_json_error( array( 'message' => $r->get_error_message() ) ); } $subject = '[TEST] ' . $r['subject']; $ct = static function () { return 'text/html'; }; add_filter( 'wp_mail_content_type', $ct ); $ok = wp_mail( $to, trim( wp_strip_all_tags( $subject ) ), (string) $r['html'], array( 'Content-Type: text/html; charset=UTF-8' ) ); remove_filter( 'wp_mail_content_type', $ct ); if ( ! $ok ) { wp_send_json_error( array( 'message' => __( 'wp_mail() refused the message — check the site mailer/SMTP.', 'ai-eshop-optimizer' ) ) ); } wp_send_json_success( array( 'sent' => true, 'to' => $to ) ); } private function render_preview( $to = '' ) { if ( ! class_exists( 'AIEO_Workflow_Runtime' ) || ! class_exists( 'AIEO_Workflows' ) || ! method_exists( 'AIEO_Workflow_Runtime', 'preview_send' ) ) { return new \WP_Error( 'runtime', __( 'Workflow engine unavailable.', 'ai-eshop-optimizer' ) ); } $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; $wf = AIEO_Workflows::get( $id ); if ( ! $wf ) { return new \WP_Error( 'nowf', __( 'Workflow not found — save it first, then preview.', 'ai-eshop-optimizer' ) ); } $steps = ( isset( $wf['steps'] ) && is_array( $wf['steps'] ) ) ? $wf['steps'] : array(); $idx = isset( $_POST['step_index'] ) ? (int) $_POST['step_index'] : -1; $step = null; if ( $idx >= 0 && isset( $steps[ $idx ] ) && 'send' === (string) ( $steps[ $idx ]['type'] ?? '' ) ) { $step = $steps[ $idx ]; } else { foreach ( $steps as $s ) { if ( 'send' === (string) ( $s['type'] ?? '' ) ) { $step = $s; break; } } } if ( ! is_array( $step ) ) { return new \WP_Error( 'nostep', __( 'This workflow has no “Send message” step to preview.', 'ai-eshop-optimizer' ) ); } if ( '' === $to ) { $u = wp_get_current_user(); $to = ( $u && ! empty( $u->user_email ) ) ? (string) $u->user_email : ''; } $target = isset( $_POST['target_user'] ) ? (int) $_POST['target_user'] : 0; $r = AIEO_Workflow_Runtime::preview_send( $wf, $step, $to, $target ); $r['steps'] = array(); foreach ( $steps as $i => $s ) { if ( 'send' === (string) ( $s['type'] ?? '' ) ) { $r['steps'][] = array( 'index' => (int) $i, 'label' => (string) ( $s['subject'] ?? '' ) ); } } $r['step_index'] = ( $idx >= 0 && isset( $steps[ $idx ] ) ) ? $idx : (int) ( $r['steps'][0]['index'] ?? 0 ); $r['channel'] = (string) ( $step['channel'] ?? 'email' ); return $r; } public static function sending_body() { $words = array( 'paused' => _x( 'Paused', 'an engine state: nothing is sent', 'ai-eshop-optimizer' ), 'test' => _x( 'Test', 'an engine state: sends to the testers only', 'ai-eshop-optimizer' ), 'live' => _x( 'Live', 'an engine state: sends to every customer', 'ai-eshop-optimizer' ), ); $help = array( 'paused' => __( 'Nothing is sent.', 'ai-eshop-optimizer' ), 'test' => __( 'Real messages and coupons, to the testers only.', 'ai-eshop-optimizer' ), 'live' => __( 'Every customer the automations reach.', 'ai-eshop-optimizer' ), ); $rows = ''; $data = ''; foreach ( array( 'email' => __( 'E-mail', 'ai-eshop-optimizer' ), 'push' => _x( 'Push', 'the push notification channel', 'ai-eshop-optimizer' ) ) as $ch => $label ) { $state = AIEO_Automation_Test_Mode::state( $ch ); $held = 'live' === $state ? array( 'count' => 0, 'oldest' => '', 'recent' => 0 ) : AIEO_Automation_Test_Mode::held_runs( $ch ); $says = ''; if ( $held['count'] > 0 ) { $says = sprintf( _n( '%1$s run has waited since the engine was paused, the oldest from %2$s. Going live cancels it, unless you keep the last 7 days\' (%3$s).', '%1$s runs have waited since the engine was paused, the oldest from %2$s. Going live cancels them, unless you keep the last 7 days\' (%3$s).', $held['count'], 'ai-eshop-optimizer' ), number_format_i18n( $held['count'] ), '' !== $held['oldest'] ? wp_date( get_option( 'date_format' ), strtotime( $held['oldest'] . ' UTC' ) ) : '', number_format_i18n( $held['recent'] ) ); } $rows .= \Rooster\Admin\Ui::field_row( array( 'id' => 'aieo-wf-engine-' . $ch, 'label' => $label, 'group' => true, 'control' => \Rooster\Admin\Ui::checks( 'aieo_wf_engine_' . $ch, $words, array( $state ), array( 'type' => 'radio', 'inline' => true ) ), 'help' => trim( $help[ $state ] . ' ' . $says ), ) ); $data .= ' data-held-' . $ch . '="' . (int) $held['count'] . '" data-recent-' . $ch . '="' . (int) $held['recent'] . '" data-golive-' . $ch . '="' . esc_attr( $says ) . '"'; } return '
' . $rows . '
'; } public static function testers_body() { $t = AIEO_Automation_Test_Mode::testers(); $items = array(); $list = array(); foreach ( $t['users'] as $uid ) { $u = get_userdata( $uid ); if ( $u ) { $label = $u->display_name . ' <' . $u->user_email . '>'; $items[] = array( 'value' => (string) $uid, 'label' => $label ); $list[] = array( 'key' => 'u:' . $uid, 'label' => $label ); } } foreach ( $t['emails'] as $e ) { $list[] = array( 'key' => 'e:' . $e, 'label' => $e ); } $picker = '' . '' . '' . ''; $rows = \Rooster\Admin\Ui::field_row( array( 'id' => 'aieo-wf-testers-users', 'label' => __( 'Tester accounts', 'ai-eshop-optimizer' ), 'group' => true, 'control' => $picker, 'help' => __( 'Accounts of the shop. In Test, only they get runs, and they receive every channel they can.', 'ai-eshop-optimizer' ), ) ) . \Rooster\Admin\Ui::field_row( array( 'id' => 'aieo-wf-testers-emails', 'label' => __( 'Staff e-mail addresses', 'ai-eshop-optimizer' ), 'control' => \Rooster\Admin\Ui::textarea( 'aieo_wf_testers_emails', implode( "\n", $t['emails'] ), array( 'id' => 'aieo-wf-testers-emails', 'rows' => 3 ) ), 'help' => __( 'One per line, optional: addresses with no account, tested as guests.', 'ai-eshop-optimizer' ), ) ); $skips = '

' . esc_html__( 'Testers get every message: their consent, the opt-out list, the quiet hours, the frequency caps and the dedup are not applied to them.', 'ai-eshop-optimizer' ) . '

'; return '
' . $skips . '
' . $rows . '
'; } public static function would_do_sentence( array $e, array $catalog ) { $type = (string) ( $e['type'] ?? '' ); $what = (string) ( $e['what'] ?? '' ); $oid = (int) ( $e['order'] ?? 0 ); $order = ( $oid > 0 && function_exists( 'wc_get_order' ) ) ? wc_get_order( $oid ) : null; $num = $order ? (string) $order->get_order_number() : (string) $oid; switch ( $type ) { case 'change_order_status': if ( $oid > 0 && '' !== $what ) { return sprintf( __( 'Would set order #%1$s to %2$s', 'ai-eshop-optimizer' ), $num, function_exists( 'wc_get_order_status_name' ) ? wc_get_order_status_name( $what ) : $what ); } break; case 'order_add_note': if ( $oid > 0 ) { return sprintf( __( 'Would add a note to order #%s', 'ai-eshop-optimizer' ), $num ); } break; case 'order_update_meta': if ( $oid > 0 && '' !== $what ) { return sprintf( __( 'Would set the field %1$s on order #%2$s', 'ai-eshop-optimizer' ), $what, $num ); } break; case 'customer_update_meta': if ( '' !== $what ) { return sprintf( __( 'Would set the field %s on the customer\'s account', 'ai-eshop-optimizer' ), $what ); } break; case 'customer_change_role': if ( '' !== $what ) { $names = function_exists( 'wp_roles' ) ? wp_roles()->get_names() : array(); $role = isset( $names[ $what ] ) ? translate_user_role( $names[ $what ] ) : $what; if ( 'remove' === ( $e['mode'] ?? '' ) ) { return sprintf( __( 'Would take the role %s from the customer', 'ai-eshop-optimizer' ), $role ); } if ( 'add' === ( $e['mode'] ?? '' ) ) { return sprintf( __( 'Would give the customer the role %s', 'ai-eshop-optimizer' ), $role ); } return sprintf( __( 'Would change the customer\'s role to %s', 'ai-eshop-optimizer' ), $role ); } break; case 'custom_function': if ( '' !== $what ) { return sprintf( __( 'Would run the developer action %s', 'ai-eshop-optimizer' ), $what ); } break; } return (string) ( $catalog[ $type ]['label'] ?? $type ); } public static function test_log_body() { $state_words = array( 'pending' => __( 'Waiting', 'ai-eshop-optimizer' ), 'running' => __( 'Running', 'ai-eshop-optimizer' ), 'done' => __( 'Done', 'ai-eshop-optimizer' ), 'cancelled' => __( 'Cancelled', 'ai-eshop-optimizer' ), ); $tones = array( 'pending' => 'info', 'running' => 'info', 'done' => 'success', 'cancelled' => 'mono' ); $catalog = AIEO_Workflows::step_catalog(); $runs = array(); foreach ( AIEO_Automation_Test_Mode::test_runs( 50 ) as $r ) { $ctx = json_decode( (string) $r['context_json'], true ); $ctx = is_array( $ctx ) ? $ctx : array(); $u = (int) $r['wp_user_id'] > 0 ? get_userdata( (int) $r['wp_user_id'] ) : null; $who = $u ? $u->user_email : (string) ( $ctx['guest_email'] ?? '' ); $skipped = array(); foreach ( (array) ( $ctx['_test_skipped'] ?? array() ) as $e ) { $skipped[] = self::would_do_sentence( is_array( $e ) ? $e : array(), $catalog ); } $runs[] = array( '_id' => (string) $r['id'], 'workflow' => '' !== (string) $r['name'] ? (string) $r['name'] : '#' . (int) $r['workflow_id'], 'tester' => $who, 'state' => array( 'label' => $state_words[ $r['state'] ] ?? (string) $r['state'], 'tone' => $tones[ $r['state'] ] ?? 'mono' ), 'sent' => ! empty( $ctx['_delivered'] ) ? __( 'Yes', 'ai-eshop-optimizer' ) : __( 'No', 'ai-eshop-optimizer' ), 'skipped' => implode( ' · ', array_unique( array_filter( $skipped ) ) ), 'audience' => array_key_exists( '_test_audience', $ctx ) ? ( empty( $ctx['_test_audience'] ) ? __( 'No', 'ai-eshop-optimizer' ) : __( 'Yes', 'ai-eshop-optimizer' ) ) : '', 'started' => (string) $r['created'], 'next' => 'pending' === (string) $r['state'] ? (string) $r['run_at'] : '', ); } $html = \Rooster\Admin\Ui::table( array( array( 'key' => 'workflow', 'label' => __( 'Workflow', 'ai-eshop-optimizer' ), 'type' => 'text' ), array( 'key' => 'tester', 'label' => __( 'Tester', 'ai-eshop-optimizer' ), 'type' => 'text' ), array( 'key' => 'state', 'label' => __( 'Status', 'ai-eshop-optimizer' ), 'type' => 'status' ), array( 'key' => 'sent', 'label' => __( 'Delivered', 'ai-eshop-optimizer' ), 'type' => 'text' ), array( 'key' => 'skipped', 'label' => __( 'Not done in Test', 'ai-eshop-optimizer' ), 'type' => 'text', 'tip' => __( 'A tester\'s run changes no order, account or data: these steps were left out.', 'ai-eshop-optimizer' ) ), array( 'key' => 'audience', 'label' => __( 'In the audience', 'ai-eshop-optimizer' ), 'type' => 'text', 'tip' => __( 'In Test a broadcast reaches every tester: whether this tester is in its audience.', 'ai-eshop-optimizer' ) ), array( 'key' => 'started', 'label' => __( 'Started', 'ai-eshop-optimizer' ), 'type' => 'relative', 'format' => array( 'tz' => 'utc' ) ), array( 'key' => 'next', 'label' => __( 'Next step', 'ai-eshop-optimizer' ), 'type' => 'relative', 'format' => array( 'tz' => 'utc' ) ), ), $runs, array( 'id' => 'aieo-wf-test-runs', 'caption' => __( 'Test runs', 'ai-eshop-optimizer' ), 'empty' => __( 'No test run yet. Put a channel in Test, add testers, then run a workflow for a tester.', 'ai-eshop-optimizer' ), ) ); $coupons = array(); foreach ( AIEO_Automation_Test_Mode::test_coupons() as $g ) { $wid = (int) preg_replace( '/^wf_(\d+)_test$/', '$1', (string) $g['source'] ); $wf = $wid > 0 ? AIEO_Workflows::get( $wid ) : null; $coupons[] = array( '_id' => (string) $g['id'], 'code' => strtoupper( (string) $g['code'] ), 'workflow' => $wf ? (string) $wf['name'] : '#' . $wid, 'email' => (string) $g['email'], 'offer' => class_exists( 'AIEO_Coupon_Minter' ) ? AIEO_Coupon_Minter::label( (string) $g['offer_type'], (float) $g['offer_value'] ) : (string) $g['offer_value'], 'status' => (string) $g['status'], 'expires' => (string) $g['expires_at'], ); } $html .= rooster_admin_card_section_html( __( 'Test coupons', 'ai-eshop-optimizer' ) ) . \Rooster\Admin\Ui::table( array( array( 'key' => 'code', 'label' => __( 'Code', 'ai-eshop-optimizer' ), 'type' => 'code' ), array( 'key' => 'workflow', 'label' => __( 'Workflow', 'ai-eshop-optimizer' ), 'type' => 'text' ), array( 'key' => 'email', 'label' => __( 'Locked to', 'ai-eshop-optimizer' ), 'type' => 'text' ), array( 'key' => 'offer', 'label' => __( 'Offer', 'ai-eshop-optimizer' ), 'type' => 'text' ), array( 'key' => 'status', 'label' => __( 'Status', 'ai-eshop-optimizer' ), 'type' => 'text' ), array( 'key' => 'expires', 'label' => __( 'Expires', 'ai-eshop-optimizer' ), 'type' => 'relative', 'format' => array( 'tz' => 'utc' ) ), ), $coupons, array( 'id' => 'aieo-wf-test-coupons', 'caption' => __( 'Test coupons', 'ai-eshop-optimizer' ), 'empty' => __( 'No test coupon. A tester\'s run mints one when its message carries an offer.', 'ai-eshop-optimizer' ), ) ); return '
' . $html . '
'; } private static function test_mode_bodies() { return array( 'sending' => self::sending_body(), 'testers' => self::testers_body(), 'log' => self::test_log_body(), ); } public function ajax_engine() { AIEO_DMM::verify_ajax_request(); $this->require_pro(); $channel = isset( $_POST['channel'] ) && 'push' === $_POST['channel'] ? 'push' : 'email'; $state = isset( $_POST['state'] ) ? sanitize_key( wp_unslash( $_POST['state'] ) ) : 'paused'; $keep = ! empty( $_POST['keep_recent'] ); $r = AIEO_Automation_Test_Mode::switch_channel( $channel, $state, $keep ); $label = 'push' === $channel ? _x( 'Push', 'the push notification channel', 'ai-eshop-optimizer' ) : __( 'E-mail', 'ai-eshop-optimizer' ); $says = array( 'live' => __( '%s: live, to every customer the workflows reach.', 'ai-eshop-optimizer' ), 'test' => __( '%s: in Test, to the testers only.', 'ai-eshop-optimizer' ), 'paused' => __( '%s: paused, nothing is sent.', 'ai-eshop-optimizer' ), ); $msg = sprintf( $says[ $r['state'] ] ?? $says['paused'], $label ); if ( $r['cancelled'] > 0 ) { $msg .= ' ' . sprintf( _n( '%s waiting run cancelled.', '%s waiting runs cancelled.', $r['cancelled'], 'ai-eshop-optimizer' ), number_format_i18n( $r['cancelled'] ) ); } wp_send_json_success( array( 'state' => $r['state'], 'cancelled' => $r['cancelled'], 'message' => $msg, 'bodies' => self::test_mode_bodies() ) ); } public function ajax_testers() { AIEO_DMM::verify_ajax_request(); $this->require_pro(); $users = isset( $_POST['users'] ) ? array_map( 'intval', explode( ',', sanitize_text_field( wp_unslash( (string) $_POST['users'] ) ) ) ) : array(); $emails = isset( $_POST['emails'] ) ? preg_split( '/[\s,;]+/', sanitize_textarea_field( wp_unslash( (string) $_POST['emails'] ) ), -1, PREG_SPLIT_NO_EMPTY ) : array(); $saved = AIEO_Automation_Test_Mode::set_testers( $users, (array) $emails ); $out = array_values( array_filter( (array) $emails, static function ( $e ) use ( $saved ) { return ! in_array( strtolower( sanitize_email( (string) $e ) ), $saved['emails'], true ); } ) ); $msg = $out ? sprintf( __( 'Testers saved. Not e-mail addresses, so left out: %s', 'ai-eshop-optimizer' ), implode( ', ', $out ) ) : __( 'Testers saved.', 'ai-eshop-optimizer' ); wp_send_json_success( array( 'message' => $msg, 'bodies' => self::test_mode_bodies() ) ); } public function ajax_tester_run() { AIEO_DMM::verify_ajax_request(); $this->require_pro(); $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; $tester = isset( $_POST['tester'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['tester'] ) ) : ''; $uid = 0 === strpos( $tester, 'u:' ) ? (int) substr( $tester, 2 ) : 0; $email = 0 === strpos( $tester, 'e:' ) ? sanitize_email( substr( $tester, 2 ) ) : ''; $r = AIEO_Workflow_Runtime::run_for_tester( $id, $uid, $email ); if ( is_wp_error( $r ) ) { wp_send_json_error( array( 'message' => $r->get_error_message() ) ); } $msg = $r['delivered'] ? __( 'The tester\'s run started and its first message was sent.', 'ai-eshop-optimizer' ) : ( 'pending' === $r['state'] ? __( 'The tester\'s run started and waits for its next step.', 'ai-eshop-optimizer' ) : __( 'The tester\'s run ended without a message. Its row in Test runs says how far it went.', 'ai-eshop-optimizer' ) ); wp_send_json_success( array( 'message' => $msg, 'run' => $r, 'bodies' => self::test_mode_bodies() ) ); } public function ajax_test_coupons() { AIEO_DMM::verify_ajax_request(); $this->require_pro(); $n = AIEO_Automation_Test_Mode::remove_test_coupons(); wp_send_json_success( array( 'message' => sprintf( _n( '%s test coupon removed.', '%s test coupons removed.', $n, 'ai-eshop-optimizer' ), number_format_i18n( $n ) ), 'bodies' => self::test_mode_bodies() ) ); } public function ajax_search_users() { AIEO_DMM::verify_ajax_request(); $q = isset( $_GET['q'] ) ? sanitize_text_field( wp_unslash( $_GET['q'] ) ) : ''; $args = array( 'number' => 20, 'orderby' => 'display_name', 'fields' => array( 'ID', 'display_name', 'user_email' ) ); if ( '' !== $q ) { $args['search'] = '*' . $q . '*'; $args['search_columns'] = array( 'user_login', 'user_email', 'display_name' ); } $results = array(); foreach ( get_users( $args ) as $u ) { $results[] = array( 'value' => (string) $u->ID, 'label' => $u->display_name . ' <' . $u->user_email . '>' ); } wp_send_json( array( 'results' => $results ) ); } }