render_template('loyalty-classes.php', array( 'classes' => $this->fetch_classes(), 'assignments_sample' => $this->fetch_recent_assignments(25), )); } public function fetch_classes() { global $wpdb; $table = $wpdb->prefix . 'aieo_dmm_loyalty_classes'; if (!aieo_dmm_table_exists($table)) { return array(); } $rows = $wpdb->get_results("SELECT * FROM {$table} ORDER BY enabled DESC, label ASC", ARRAY_A); return is_array($rows) ? $rows : array(); } public function fetch_recent_assignments($limit = 25) { global $wpdb; $table = $wpdb->prefix . 'aieo_dmm_loyalty_assignments'; $defs = $wpdb->prefix . 'aieo_dmm_loyalty_classes'; if (!aieo_dmm_table_exists($table) || !aieo_dmm_table_exists($defs)) { return array(); } $rows = $wpdb->get_results($wpdb->prepare( "SELECT a.user_id, a.class_id, a.assigned_at, d.slug, d.label, d.extra_percent FROM {$table} a INNER JOIN {$defs} d ON d.id = a.class_id ORDER BY a.assigned_at DESC LIMIT %d", (int) $limit ), ARRAY_A); if (!is_array($rows)) { return array(); } foreach ($rows as &$row) { $user = get_userdata((int) $row['user_id']); $row['user_label'] = $user ? ($user->display_name . ' <' . $user->user_email . '>') : ('#' . $row['user_id']); } return $rows; } public function ajax_save_class() { AIEO_DMM::verify_ajax_request(); global $wpdb; $table = $wpdb->prefix . 'aieo_dmm_loyalty_classes'; if (!aieo_dmm_table_exists($table)) { wp_send_json_error(array('message' => __('Table missing.', 'ai-eshop-optimizer'))); } $id = isset($_POST['id']) ? absint(wp_unslash($_POST['id'])) : 0; $slug = isset($_POST['slug']) ? sanitize_key(wp_unslash($_POST['slug'])) : ''; $label = isset($_POST['label']) ? sanitize_text_field(wp_unslash($_POST['label'])) : ''; $pct = isset($_POST['extra_percent']) ? (float) $_POST['extra_percent'] : 0.0; $ppc = isset($_POST['points_per_currency']) ? (float) $_POST['points_per_currency'] : 0.0; $enabled = !empty($_POST['enabled']) ? 1 : 0; $desc = isset($_POST['description']) ? sanitize_textarea_field(wp_unslash($_POST['description'])) : ''; if ($slug === '' || $label === '') { wp_send_json_error(array('message' => __('Slug and label are required.', 'ai-eshop-optimizer'))); } if ($pct < 0 || $pct >= 100) { wp_send_json_error(array('message' => __('Percent must be between 0 and 100.', 'ai-eshop-optimizer'))); } if ($ppc < 0) { wp_send_json_error(array('message' => __('Points per currency cannot be negative.', 'ai-eshop-optimizer'))); } $date_from_raw = isset($_POST['date_from']) ? sanitize_text_field(wp_unslash($_POST['date_from'])) : ''; $date_to_raw = isset($_POST['date_to']) ? sanitize_text_field(wp_unslash($_POST['date_to'])) : ''; $window_error = AIEO_DMM_Schedule::window_error($date_from_raw, $date_to_raw); if ('' !== $window_error) { wp_send_json_error(array('message' => $window_error)); } $date_from = AIEO_DMM_Schedule::clean_date($date_from_raw); $date_to = AIEO_DMM_Schedule::clean_date($date_to_raw); $has_window = AIEO_DMM_Loyalty_Window::ready(); if (!$has_window && ('' !== $date_from || '' !== $date_to)) { wp_send_json_error(array('message' => __('The schedule cannot be saved yet: the database update has not finished. Reload the page and try again.', 'ai-eshop-optimizer'))); } $data = array( 'slug' => $slug, 'label' => $label, 'extra_percent' => $pct, 'points_per_currency' => $ppc, 'enabled' => $enabled, 'description' => $desc, ); $formats = array('%s', '%s', '%f', '%f', '%d', '%s'); if ($has_window) { $data['date_from'] = '' !== $date_from ? $date_from : null; $data['date_to'] = '' !== $date_to ? $date_to : null; $formats[] = '%s'; $formats[] = '%s'; } $counts_now = 1 === $enabled && AIEO_DMM_Schedule::in_window($date_from, $date_to); $counted = false; require_once dirname(__DIR__) . '/services/class-aieo-dmm-offer-forms.php'; if ($id > 0) { $stored = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE id = %d", $id), ARRAY_A); if (!is_array($stored)) { wp_send_json_error(array('message' => __('Not found.', 'ai-eshop-optimizer'))); } $counted = !empty($stored['enabled']) && AIEO_DMM_Schedule::in_window($stored['date_from'] ?? '', $stored['date_to'] ?? ''); unset($data['slug']); array_shift($formats); if (AIEO_DMM_Offer_Forms::previewing()) { AIEO_DMM_Offer_Forms::answer_preview('aieo_dmm_loyalty_classes', array(array('id' => $id) + $data + $stored)); } if (false === $wpdb->update($table, $data, array('id' => $id), $formats, array('%d'))) { wp_send_json_error(array('message' => __('That could not be saved.', 'ai-eshop-optimizer'))); } } else { $existing = $wpdb->get_var($wpdb->prepare( "SELECT id FROM {$table} WHERE slug = %s", $slug )); if ($existing) { wp_send_json_error(array('message' => __('A class with that slug already exists.', 'ai-eshop-optimizer'))); } if (AIEO_DMM_Offer_Forms::previewing()) { $next = (int) $wpdb->get_var("SELECT COALESCE(MAX(id), 0) + 1 FROM {$table}"); AIEO_DMM_Offer_Forms::answer_preview('aieo_dmm_loyalty_classes', array(array('id' => $next) + $data)); } if (false === $wpdb->insert($table, $data, $formats)) { wp_send_json_error(array('message' => __('That could not be saved.', 'ai-eshop-optimizer'))); } $id = (int) $wpdb->insert_id; } if (!$this->write_class_offer($id)) { AIEO_DMM_Cache::bump_version('loyalty'); } if ($counted !== $counts_now && class_exists('AIEO_DMM_Schedule_Boundary')) { AIEO_DMM_Schedule_Boundary::refresh_class_customers(array($id)); } wp_send_json_success(array('id' => $id, 'message' => __('Class saved.', 'ai-eshop-optimizer'))); } private function write_class_offer($class_id) { global $wpdb; require_once dirname(__DIR__) . '/services/class-aieo-dmm-offer-forms.php'; $through = AIEO_DMM_Offer_Forms::through_the_writer(); if ($through || null !== AIEO_DMM_Offer_Forms::posted_exclusive()) { $class = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}aieo_dmm_loyalty_classes WHERE id = %d", (int) $class_id), ARRAY_A); $suppress = $through ? null : $wpdb->suppress_errors(true); $saved = is_array($class) ? AIEO_DMM_Offer_Forms::save_old_row('aieo_dmm_loyalty_classes', $class, 'the customer discounts form') : new WP_Error('not_found', 'The class is not in its table.'); if (null !== $suppress) { $wpdb->suppress_errors($suppress); } if (!is_wp_error($saved)) { return true; } if ($through) { AIEO_DMM_Offer_Forms::refuse($saved); } } AIEO_DMM_Offer_Forms::copy('aieo_dmm_loyalty_classes', (int) $class_id); return false; } public function edit_payload(array $row) { return array( 'id' => (int) ($row['id'] ?? 0), 'slug' => (string) ($row['slug'] ?? ''), 'label' => (string) ($row['label'] ?? ''), 'extra_percent' => (float) ($row['extra_percent'] ?? 0), 'points_per_currency' => (float) ($row['points_per_currency'] ?? 0), 'enabled' => !empty($row['enabled']), 'description' => (string) ($row['description'] ?? ''), 'date_from' => AIEO_DMM_Schedule::clean_date($row['date_from'] ?? ''), 'date_to' => AIEO_DMM_Schedule::clean_date($row['date_to'] ?? ''), ); } public function ajax_delete_class() { AIEO_DMM::verify_ajax_request(); $id = isset($_POST['id']) ? absint(wp_unslash($_POST['id'])) : 0; if ($id <= 0) { wp_send_json_error(array('message' => __('Invalid id.', 'ai-eshop-optimizer'))); } global $wpdb; $wpdb->delete($wpdb->prefix . 'aieo_dmm_loyalty_classes', array('id' => $id), array('%d')); $wpdb->delete($wpdb->prefix . 'aieo_dmm_loyalty_assignments', array('class_id' => $id), array('%d')); require_once dirname(__DIR__) . '/services/class-aieo-dmm-offer-forms.php'; if (!AIEO_DMM_Offer_Forms::archive_old_row('aieo_dmm_loyalty_classes', $id, 'deleted in the customer discounts form')) { AIEO_DMM_Offer_Forms::copy('aieo_dmm_loyalty_classes', $id); AIEO_DMM_Cache::bump_version('loyalty'); } wp_send_json_success(); } public function ajax_assign_user() { AIEO_DMM::verify_ajax_request(); $user_id = isset($_POST['user_id']) ? absint(wp_unslash($_POST['user_id'])) : 0; $class_id = isset($_POST['class_id']) ? absint(wp_unslash($_POST['class_id'])) : 0; if ($user_id <= 0 || $class_id <= 0) { wp_send_json_error(array('message' => __('Pick a user and class.', 'ai-eshop-optimizer'))); } if (!get_userdata($user_id)) { wp_send_json_error(array('message' => __('User not found.', 'ai-eshop-optimizer'))); } global $wpdb; $table = $wpdb->prefix . 'aieo_dmm_loyalty_assignments'; $wpdb->query($wpdb->prepare( "INSERT IGNORE INTO {$table} (user_id, class_id) VALUES (%d, %d)", $user_id, $class_id )); AIEO_DMM_Cache::bump_version('loyalty'); do_action('aieo_dmm_loyalty_assignment_saved', $user_id, $class_id); wp_send_json_success(); } public function ajax_unassign_user() { AIEO_DMM::verify_ajax_request(); $user_id = isset($_POST['user_id']) ? absint(wp_unslash($_POST['user_id'])) : 0; $class_id = isset($_POST['class_id']) ? absint(wp_unslash($_POST['class_id'])) : 0; if ($user_id <= 0 || $class_id <= 0) { wp_send_json_error(array('message' => __('Invalid input.', 'ai-eshop-optimizer'))); } global $wpdb; $wpdb->delete($wpdb->prefix . 'aieo_dmm_loyalty_assignments', array( 'user_id' => $user_id, 'class_id' => $class_id, ), array('%d', '%d')); AIEO_DMM_Cache::bump_version('loyalty'); do_action('aieo_dmm_loyalty_assignment_deleted', $user_id, $class_id); wp_send_json_success(); } public function ajax_bulk_upload() { AIEO_DMM::verify_ajax_request(); if (empty($_FILES['csv_file']['tmp_name']) || !is_uploaded_file($_FILES['csv_file']['tmp_name'])) { wp_send_json_error(array('message' => __('No file uploaded.', 'ai-eshop-optimizer'))); } $handle = fopen($_FILES['csv_file']['tmp_name'], 'r'); if (!$handle) { wp_send_json_error(array('message' => __('Cannot read file.', 'ai-eshop-optimizer'))); } $header = fgetcsv($handle, 0, ',', '"', ''); if (!$header) { fclose($handle); wp_send_json_error(array('message' => __('Empty CSV.', 'ai-eshop-optimizer'))); } $map = array(); foreach ($header as $i => $c) { $map[strtolower(trim((string) $c))] = $i; } if (!isset($map['class_slug']) || !(isset($map['user_email']) || isset($map['user_login']) || isset($map['user_id']))) { fclose($handle); wp_send_json_error(array('message' => __('CSV must contain class_slug and one of user_email/user_login/user_id.', 'ai-eshop-optimizer'))); } $rows = array(); while (($row = fgetcsv($handle, 0, ',', '"', '')) !== false) { $rows[] = $row; } fclose($handle); if (empty($rows)) { wp_send_json_error(array('message' => __('No rows in CSV.', 'ai-eshop-optimizer'))); } $job_id = wp_generate_password(16, false, false); $this->create_job($job_id, 'loyalty_bulk_assign', count($rows), array( 'map' => $map, 'rows' => $rows, )); wp_send_json_success(array('job_id' => $job_id, 'total' => count($rows))); } public function ajax_bulk_process() { AIEO_DMM::verify_ajax_request(); $job_id = isset($_POST['job_id']) ? sanitize_text_field(wp_unslash($_POST['job_id'])) : ''; $job = $this->load_job($job_id); if (!$job || $job['type'] !== 'loyalty_bulk_assign') { wp_send_json_error(array('message' => __('Invalid job.', 'ai-eshop-optimizer'))); } $params = json_decode($job['params'], true); if (!is_array($params)) { wp_send_json_error(array('message' => __('Corrupted job.', 'ai-eshop-optimizer'))); } $batch_size = 100; $offset = (int) $job['processed']; $slice = array_slice($params['rows'], $offset, $batch_size); global $wpdb; $defs = $wpdb->prefix . 'aieo_dmm_loyalty_classes'; $assign = $wpdb->prefix . 'aieo_dmm_loyalty_assignments'; $errors = array(); foreach ($slice as $row) { $slug = isset($params['map']['class_slug']) && isset($row[$params['map']['class_slug']]) ? sanitize_key($row[$params['map']['class_slug']]) : ''; if ($slug === '') { $errors[] = __('Missing class_slug on a row.', 'ai-eshop-optimizer'); continue; } $class_id = (int) $wpdb->get_var($wpdb->prepare( "SELECT id FROM {$defs} WHERE slug = %s", $slug )); if ($class_id <= 0) { $errors[] = sprintf( __('Class %s not found.', 'ai-eshop-optimizer'), $slug); continue; } $user = $this->resolve_user_from_row($row, $params['map']); if (!$user) { $errors[] = __('User not found for a row.', 'ai-eshop-optimizer'); continue; } $wpdb->query($wpdb->prepare( "INSERT IGNORE INTO {$assign} (user_id, class_id) VALUES (%d, %d)", $user->ID, $class_id )); } $new_processed = $offset + count($slice); $complete = $new_processed >= (int) $job['total']; $this->update_job($job_id, array( 'processed' => $new_processed, 'status' => $complete ? 'complete' : 'running', )); if ($complete) { AIEO_DMM_Cache::bump_version('loyalty'); } wp_send_json_success(array( 'processed' => $new_processed, 'total' => (int) $job['total'], 'complete' => $complete, 'percentage'=> (int) $job['total'] > 0 ? (int) floor(($new_processed / (int) $job['total']) * 100) : 100, 'errors' => array_slice($errors, 0, 20), )); } private function resolve_user_from_row(array $row, array $map) { if (isset($map['user_id']) && !empty($row[$map['user_id']])) { $u = get_user_by('id', (int) $row[$map['user_id']]); if ($u) return $u; } if (isset($map['user_email']) && !empty($row[$map['user_email']])) { $u = get_user_by('email', sanitize_email($row[$map['user_email']])); if ($u) return $u; } if (isset($map['user_login']) && !empty($row[$map['user_login']])) { $u = get_user_by('login', sanitize_user($row[$map['user_login']], true)); if ($u) return $u; } return null; } public function ajax_search_users() { AIEO_DMM::verify_ajax_request(); $q = isset($_GET['q']) ? sanitize_text_field(wp_unslash($_GET['q'])) : ''; $users = get_users(array( 'search' => '*' . $q . '*', 'search_columns' => array('user_login', 'user_email', 'display_name'), 'number' => 25, 'orderby' => 'display_name', )); $out = array(); foreach ($users as $u) { $out[] = array( 'id' => (int) $u->ID, 'text' => $u->display_name . ' <' . $u->user_email . '> (#' . $u->ID . ')', ); } wp_send_json(array('results' => $out)); } public function render_user_profile_field($user) { if (!current_user_can(AIEO_CAPABILITY)) { return; } $classes = $this->fetch_classes(); if (empty($classes)) { return; } $assigned = $this->get_class_ids_for_user((int) $user->ID); $balance = self::get_balance((int) $user->ID); echo '
| ' . esc_html__('Classes', 'ai-eshop-optimizer') . ' | '; foreach ($classes as $class) { $checked = in_array((int) $class['id'], $assigned, true) ? 'checked' : ''; printf( '', (int) $class['id'], esc_attr($checked), esc_html($class['label']), esc_html((float) $class['extra_percent']), esc_html(number_format((float) (isset($class['points_per_currency']) ? $class['points_per_currency'] : 0), 4)) ); } echo ' |
|---|---|
| ' . esc_html__('Points balance', 'ai-eshop-optimizer') . ' | ' . esc_html(number_format($balance, 2)) . ' |