__( 'Audience Builder', 'ai-eshop-optimizer' ),
'description' => __( 'Define reusable audiences over your customer intelligence in plain language or a visual rule builder — including behavioural-vector similarity (lookalikes, in-market intent) no scalar filter can express. Preview exact membership before you send.', 'ai-eshop-optimizer' ),
'bullets' => array(
__( 'Type a sentence → validated rule tree → live count + sample', 'ai-eshop-optimizer' ),
__( 'Behavioural predicates: lookalikes, instigator-state, taste similarity', 'ai-eshop-optimizer' ),
__( 'Save once, reuse across campaigns, coupons and the cascade', 'ai-eshop-optimizer' ),
),
);
}
public function register_hooks() {
add_action( 'wp_ajax_aieo_dmm_audience_generate', array( $this, 'ajax_generate' ) );
add_action( 'wp_ajax_aieo_dmm_audience_count', array( $this, 'ajax_count' ) );
add_action( 'wp_ajax_aieo_dmm_audience_save', array( $this, 'ajax_save' ) );
add_action( 'wp_ajax_aieo_dmm_audience_list', array( $this, 'ajax_list' ) );
add_action( 'wp_ajax_aieo_dmm_audience_delete', array( $this, 'ajax_delete' ) );
add_action( 'wp_ajax_aieo_dmm_audience_suggest', array( $this, 'ajax_suggest' ) );
}
public function render_subtab() {
if ( ! class_exists( 'AIEO_Audience_Rules' ) ) {
list( $aieo_ab_open, $aieo_ab_close ) = AIEO_DMM_UI::card( array( 'icon' => 'sparkles', 'title' => $this->get_label() ) );
echo $aieo_ab_open;
echo \Rooster\Admin\Ui::notice( esc_html__( 'Audience Rules engine is not loaded.', 'ai-eshop-optimizer' ), 'destructive', array( 'inline' => true ) );
echo $aieo_ab_close;
return;
}
$this->render_template( 'audience-builder.php', array(
'nonce' => wp_create_nonce( 'aieo_dmm_nonce' ),
'fields' => AIEO_Audience_Rules::field_catalog(),
'entries' => array(
'competition' => self::entry_choices( 'competition' ),
'form' => self::entry_choices( 'form' ),
),
'prefill' => self::prefill(),
) );
}
const ENTRY_ARG = 'aieo_ab_entry';
const ENTRY_ANCHOR = 'audience-builder-from-entries';
const ENTRY_POST_TYPES = array(
'competition' => 'aieo_competition',
'form' => 'aieo_form',
);
public static function entry_choices( $kind ) {
$type = self::ENTRY_POST_TYPES[ (string) $kind ] ?? '';
$out = array();
if ( '' === $type ) {
return $out;
}
$posts = get_posts( array(
'post_type' => $type,
'post_status' => array( 'publish', 'future', 'draft', 'pending', 'private' ),
'numberposts' => 200,
'orderby' => 'date',
'order' => 'DESC',
'suppress_filters' => true,
) );
foreach ( $posts as $post ) {
$title = trim( html_entity_decode( wp_strip_all_tags( (string) get_the_title( $post ) ), ENT_QUOTES, 'UTF-8' ) );
$id = (string) (int) $post->ID;
$out[ $id ] = '' !== $title ? $title : '#' . $id;
}
return $out;
}
public static function prefill( $raw = null ) {
if ( null === $raw ) {
$raw = isset( $_GET[ self::ENTRY_ARG ] ) && is_scalar( $_GET[ self::ENTRY_ARG ] ) ? sanitize_text_field( wp_unslash( (string) $_GET[ self::ENTRY_ARG ] ) ) : '';
}
if ( ! is_string( $raw ) || 1 !== preg_match( '/^(competition|form):([1-9]\d{0,18})$/', $raw, $m ) ) {
return array();
}
$post = get_post( (int) $m[2] );
if ( ! $post instanceof WP_Post || self::ENTRY_POST_TYPES[ $m[1] ] !== $post->post_type || in_array( $post->post_status, array( 'trash', 'auto-draft' ), true ) ) {
return array();
}
return array(
'kind' => $m[1],
'id' => (int) $post->ID,
);
}
public static function entry_url( $kind, $id ) {
return add_query_arg(
array(
'page' => AIEO_DMM::MENU_SLUG,
'dmm_tab' => 'audience_builder',
self::ENTRY_ARG => sanitize_key( (string) $kind ) . ':' . (int) $id,
),
admin_url( 'admin.php' )
) . '#aieo-card-' . self::ENTRY_ANCHOR;
}
public static function entrant_links( $kind, $id ) {
$id = (int) $id;
if ( $id <= 0 || ! isset( self::ENTRY_POST_TYPES[ $kind ] ) || in_array( get_post_status( $id ), array( false, 'auto-draft', 'trash' ), true )
|| ! current_user_can( defined( 'AIEO_CAPABILITY' ) ? AIEO_CAPABILITY : 'aieo_access' ) || ! class_exists( '\Rooster\Admin\Ui' ) ) {
return '';
}
$buttons = array();
if ( class_exists( 'AIEO_Audience_Rules' ) && self::is_aieo_pro_user() ) {
$buttons[] = \Rooster\Admin\Ui::button( __( 'Make an audience of its entrants', 'ai-eshop-optimizer' ), array( 'href' => self::entry_url( $kind, $id ), 'size' => 'sm' ) );
}
if ( class_exists( 'AIEO_DMM_Offers' ) && AIEO_DMM_Offers::wizard_on() && class_exists( 'AIEO_DMM_Offer_Wizard' ) ) {
$buttons[] = \Rooster\Admin\Ui::button( __( 'Make an offer for its entrants', 'ai-eshop-optimizer' ), array( 'href' => AIEO_DMM_Offer_Wizard::url( 0, '', 0, $kind . ':' . $id ), 'size' => 'sm' ) );
}
if ( ! $buttons ) {
return '';
}
if ( class_exists( '\Rooster\Admin\Library' ) ) {
\Rooster\Admin\Library::island_style();
}
return '
' . implode( '', $buttons ) . '
';
}
public function ajax_generate() {
AIEO_DMM::verify_ajax_request();
if ( ! self::is_aieo_pro_user() ) {
wp_send_json_error( array( 'message' => __( 'This feature requires the Pro version.', 'ai-eshop-optimizer' ) ) );
}
$text = isset( $_POST['text'] ) ? sanitize_textarea_field( wp_unslash( $_POST['text'] ) ) : '';
if ( '' === $text ) {
wp_send_json_error( array( 'message' => __( 'Describe the audience first.', 'ai-eshop-optimizer' ) ) );
}
$res = AIEO_Audience_Rules::from_nl( $text );
if ( empty( $res['ok'] ) ) {
wp_send_json_error( array( 'message' => (string) $res['error'] ) );
}
$rule = $res['rule'];
$cnt = AIEO_Audience_Rules::count( $rule );
wp_send_json_success( array(
'rule' => $rule,
'summary' => AIEO_Audience_Rules::describe_rule( $rule ),
'count' => $cnt,
'reach' => AIEO_Audience_Rules::reach( $rule ),
'sample' => AIEO_Audience_Rules::preview( $rule, 8 ),
) );
}
public function ajax_count() {
AIEO_DMM::verify_ajax_request();
$rule = self::posted_rule();
if ( null === $rule ) {
wp_send_json_error( array( 'message' => __( 'Invalid rule.', 'ai-eshop-optimizer' ) ) );
}
$refused = self::entry_refusal( $rule );
if ( '' !== $refused ) {
wp_send_json_error( array( 'message' => $refused ) );
}
$entry = method_exists( 'AIEO_Audience_Rules', 'entry_condition' ) ? AIEO_Audience_Rules::entry_condition( $rule ) : null;
wp_send_json_success( array(
'count' => AIEO_Audience_Rules::count( $rule ),
'summary' => AIEO_Audience_Rules::describe_rule( $rule ),
'reach' => AIEO_Audience_Rules::reach( $rule ),
'sample' => AIEO_Audience_Rules::preview( $rule, 8 ),
'name' => null !== $entry ? self::free_name( AIEO_Audience_Rules::entry_name( $entry['field'], $entry['ids'], $entry['days'] ) ) : '',
) );
}
public function ajax_save() {
AIEO_DMM::verify_ajax_request();
if ( ! self::is_aieo_pro_user() ) {
wp_send_json_error( array( 'message' => __( 'This feature requires the Pro version.', 'ai-eshop-optimizer' ) ) );
}
$name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
$rule = self::posted_rule();
if ( '' === $name || null === $rule ) {
wp_send_json_error( array( 'message' => __( 'Name and a valid rule are required.', 'ai-eshop-optimizer' ) ) );
}
$refused = self::entry_refusal( $rule );
if ( '' !== $refused ) {
wp_send_json_error( array( 'message' => $refused ) );
}
if ( self::wizard_holds( $name ) ) {
wp_send_json_error( array( 'message' => __( 'This name belongs to an audience the offer wizard made for an offer; choose another name.', 'ai-eshop-optimizer' ) ) );
}
if ( class_exists( 'AIEO_Audience_Rules' ) && defined( 'AIEO_Audience_Rules::MADE_BY_KEY' ) ) {
unset( $rule[ AIEO_Audience_Rules::MADE_BY_KEY ] );
}
$id = AIEO_Audience_Rules::save( $name, $rule );
wp_send_json_success( array( 'id' => $id, 'saved' => $id > 0 ) );
}
public function ajax_list() {
AIEO_DMM::verify_ajax_request();
$audiences = AIEO_Audience_Rules::list_saved();
wp_send_json_success( array(
'audiences' => $audiences,
'table' => self::saved_table( $audiences ),
) );
}
private static function saved_table( array $audiences ) {
if ( ! $audiences || ! class_exists( '\Rooster\Admin\Ui' ) || ! class_exists( '\Rooster\Admin\States' ) ) {
return '';
}
$rows = array();
foreach ( $audiences as $a ) {
$id = (string) (int) ( $a['id'] ?? 0 );
$name = (string) ( $a['name'] ?? '' );
$made = method_exists( 'AIEO_Audience_Rules', 'made_by_wizard' ) && AIEO_Audience_Rules::made_by_wizard( $a['rule'] ?? null );
$rows[] = array(
'_name' => $name,
'name' => $made ? array( 'html' => esc_html( $name ) . ' ' . \Rooster\Admin\Ui::badge( __( 'Made by the offer wizard', 'ai-eshop-optimizer' ), 'info', array( 'sm' => true ) ) ) : $name,
'count' => max( 0, (int) ( $a['count_cached'] ?? 0 ) ),
'actions' => array(
array(
'label' => __( 'Load', 'ai-eshop-optimizer' ),
'attrs' => array( 'data-aieo-ab-load' => $id ),
),
array(
'label' => __( 'Delete', 'ai-eshop-optimizer' ),
'destructive' => true,
'attrs' => array( 'data-aieo-ab-del' => $id ) + \Rooster\Admin\States::confirm_attrs( 'aieo-ab-delete-dialog' ),
),
),
);
}
return \Rooster\Admin\Ui::table(
array(
array( 'key' => 'name', 'label' => __( 'Audience', 'ai-eshop-optimizer' ), 'type' => 'text' ),
array( 'key' => 'count', 'label' => __( 'Customers', 'ai-eshop-optimizer' ), 'type' => 'num', 'priority' => 'low' ),
array( 'key' => 'actions', 'label' => __( 'Actions', 'ai-eshop-optimizer' ), 'type' => 'actions' ),
),
$rows,
array(
'id' => 'aieo-ab-saved-table',
'caption' => __( 'Saved audiences', 'ai-eshop-optimizer' ),
)
);
}
public function ajax_delete() {
AIEO_DMM::verify_ajax_request();
if ( ! self::is_aieo_pro_user() ) {
wp_send_json_error( array( 'message' => __( 'This feature requires the Pro version.', 'ai-eshop-optimizer' ) ) );
}
$id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0;
wp_send_json_success( array( 'deleted' => AIEO_Audience_Rules::delete( $id ) ) );
}
public function ajax_suggest() {
AIEO_DMM::verify_ajax_request();
wp_send_json_success( array( 'suggestions' => AIEO_Audience_Rules::suggestions() ) );
}
const ENTRY_FIELD_KINDS = array(
'competition_entered' => 'competition',
'form_submitted' => 'form',
);
public static function entry_refusal( array $rule ) {
$stack = array( $rule );
while ( $stack ) {
$node = array_pop( $stack );
if ( ! is_array( $node ) ) {
continue;
}
if ( isset( $node['conditions'] ) && is_array( $node['conditions'] ) ) {
foreach ( $node['conditions'] as $child ) {
$stack[] = $child;
}
continue;
}
$kind = self::ENTRY_FIELD_KINDS[ (string) ( $node['field'] ?? '' ) ] ?? '';
if ( '' === $kind ) {
continue;
}
foreach ( (array) ( $node['value'] ?? array() ) as $id ) {
if ( ! is_scalar( $id ) || ! ctype_digit( trim( (string) $id ) ) || (int) $id <= 0 || self::ENTRY_POST_TYPES[ $kind ] !== get_post_type( (int) $id ) ) {
return 'competition' === $kind
? __( 'Choose the competitions from the list: one of them is not a competition of this shop.', 'ai-eshop-optimizer' )
: __( 'Choose the forms from the list: one of them is not a form of this shop.', 'ai-eshop-optimizer' );
}
}
if ( array_key_exists( 'days', $node ) && ! self::valid_days( $node['days'] ) ) {
return __( 'Enter the days as a whole number from 1 to 3650, or leave them empty to count every entry.', 'ai-eshop-optimizer' );
}
}
return '';
}
private static function valid_days( $days ) {
if ( null === $days || '' === $days || 0 === $days || '0' === $days ) {
return true;
}
if ( is_int( $days ) ) {
return $days >= 1 && $days <= 3650;
}
return is_string( $days ) && 1 === preg_match( '/^\d{1,4}$/', trim( $days ) ) && (int) $days >= 1 && (int) $days <= 3650;
}
private static function named( $name ) {
global $wpdb;
if ( ! function_exists( 'aieo_audiences_table' ) ) {
return array();
}
$t = aieo_audiences_table();
if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) !== $t ) {
return array();
}
return (array) $wpdb->get_results( $wpdb->prepare( "SELECT id, rule_json FROM `{$t}` WHERE name = %s", sanitize_text_field( (string) $name ) ), ARRAY_A );
}
public static function wizard_holds( $name ) {
if ( ! method_exists( 'AIEO_Audience_Rules', 'made_by_wizard' ) ) {
return false;
}
foreach ( self::named( $name ) as $row ) {
if ( AIEO_Audience_Rules::made_by_wizard( json_decode( (string) $row['rule_json'], true ) ) ) {
return true;
}
}
return false;
}
public static function free_name( $name ) {
$name = (string) $name;
if ( '' === $name || ! self::named( $name ) ) {
return $name;
}
for ( $n = 2; $n < 100; $n++ ) {
$tail = ' (' . $n . ')';
$base = function_exists( 'mb_substr' ) ? mb_substr( $name, 0, 190 - strlen( $tail ) ) : substr( $name, 0, 190 - strlen( $tail ) );
if ( ! self::named( $base . $tail ) ) {
return $base . $tail;
}
}
return '';
}
private static function posted_rule() {
$raw = isset( $_POST['rule'] ) ? wp_unslash( $_POST['rule'] ) : '';
if ( is_string( $raw ) && '' !== $raw ) {
$d = json_decode( $raw, true );
return is_array( $d ) ? $d : null;
}
return null;
}
}