Untitled

 avatar
unknown
plain_text
a month ago
6.9 kB
2
Indexable
/**
 * CONFIGURATION - EDIT THESE VALUES
 */

// Set to true to use rolling 3-month periods instead of calendar quarters
$b2bking_use_rolling_quarters = false; 

// Configure the group rules - Replace the IDs with your actual B2BKing group IDs
$b2bking_group_rules = array(
    // Elite Group
    'elite' => array(
        'id' => 123, // Replace with actual Elite group ID
        'threshold' => 25000, // Quarterly spending threshold in your currency
        'upgrade_to' => 'elite_plus',
        'downgrade_to' => 'elite_minus'
    ),
    // Elite+ Group
    'elite_plus' => array(
        'id' => 124, // Replace with actual Elite+ group ID
        'threshold' => 50000,
        'downgrade_to' => 'elite'
    ),
    // Elite- Group
    'elite_minus' => array(
        'id' => 125, // Replace with actual Elite- group ID
        'threshold' => 5000,
        'upgrade_to' => 'elite'
    )
);

/**
 * CODE BELOW - No need to edit unless you want to customize functionality
 */

// Schedule the quarterly check event
function b2bking_schedule_quarterly_checks() {
    // Schedule the event if it's not already scheduled
    if (!wp_next_scheduled('b2bking_quarterly_group_rules_check')) {
        // Set to run at midnight on the 1st day of each quarter
        $next_quarter_dates = array(
            mktime(0, 0, 0, 1, 1, date('Y')),   // January 1st
            mktime(0, 0, 0, 4, 1, date('Y')),   // April 1st
            mktime(0, 0, 0, 7, 1, date('Y')),   // July 1st
            mktime(0, 0, 0, 10, 1, date('Y')),  // October 1st
        );
        
        // Find the next upcoming quarter date
        $now = time();
        foreach ($next_quarter_dates as $date) {
            if ($date > $now) {
                wp_schedule_event($date, 'quarterly', 'b2bking_quarterly_group_rules_check');
                break;
            }
        }
        
        // If we've passed all quarter dates for this year, schedule for next year's January 1st
        if (!wp_next_scheduled('b2bking_quarterly_group_rules_check')) {
            wp_schedule_event(
                mktime(0, 0, 0, 1, 1, date('Y') + 1),
                'quarterly',
                'b2bking_quarterly_group_rules_check'
            );
        }
    }
}
add_action('init', 'b2bking_schedule_quarterly_checks');

// Register the quarterly interval for wp_schedule_event
function b2bking_add_quarterly_schedule($schedules) {
    $schedules['quarterly'] = array(
        'interval' => 7776000, // 90 days in seconds (approximate quarter)
        'display' => __('Quarterly')
    );
    return $schedules;
}
add_filter('cron_schedules', 'b2bking_add_quarterly_schedule');

// Function to process all users and check their quarterly order totals
function b2bking_process_quarterly_group_rules() {
    // Get all users with the customer role
    $customer_users = get_users(array('role' => 'customer'));
    
    // Loop through each customer
    foreach ($customer_users as $user) {
        b2bking_check_quarterly_rules($user->ID);
    }
}
add_action('b2bking_quarterly_group_rules_check', 'b2bking_process_quarterly_group_rules');

// Function to check if a user meets the quarterly order total criteria
function b2bking_check_quarterly_rules($user_id) {
    global $b2bking_use_rolling_quarters, $b2bking_group_rules;
    
    // Get current user group
    $current_group_id = get_user_meta($user_id, 'b2bking_customergroup', true);
    
    // Skip if user doesn't have a B2BKing group
    if (empty($current_group_id)) {
        return;
    }
    
    // Use the globally defined group rules
    $group_rules = $b2bking_group_rules;
    
    // Map ID to group key for easier lookups
    $group_id_map = array();
    foreach ($group_rules as $key => $group) {
        $group_id_map[$group['id']] = $key;
    }
    
    // If user is not in one of our defined groups, exit
    if (!isset($group_id_map[$current_group_id])) {
        return;
    }
    
    $current_group_key = $group_id_map[$current_group_id];
    
    // Set date range for the quarter
    if ($b2bking_use_rolling_quarters) {
        // Option 1: Last 3 months rolling window (for flexibility)
        $end_date = date('Y-m-d H:i:s');
        $start_date = date('Y-m-d H:i:s', strtotime('-3 months'));
    } else {
        // Option 2: Previous calendar quarter
        $current_month = date('n');
        $current_year = date('Y');
        
        // Determine which quarter we just completed
        if ($current_month >= 1 && $current_month <= 3) {
            // We're in Q1, so check Q4 of previous year
            $quarter_start_month = 10;
            $quarter_start_year = $current_year - 1;
        } else {
            // Check the previous quarter of current year
            $quarter_start_month = floor(($current_month - 1) / 3) * 3 - 2;
            $quarter_start_year = $current_year;
        }
        
        $quarter_end_month = $quarter_start_month + 2;
        $quarter_end_year = $quarter_start_year;
        
        $start_date = date('Y-m-d H:i:s', mktime(0, 0, 0, $quarter_start_month, 1, $quarter_start_year));
        $end_date = date('Y-m-d H:i:s', mktime(23, 59, 59, $quarter_end_month, date('t', mktime(0, 0, 0, $quarter_end_month, 1, $quarter_end_year)), $quarter_end_year));
    }
    
    // Calculate order total for the quarter
    $quarterly_total = b2bking_get_user_order_total($user_id, $start_date, $end_date);
    
    // Get current group rule
    $group_rule = $group_rules[$current_group_key];
    $threshold = $group_rule['threshold'];
    
    // Determine if group change is needed
    $new_group_key = null;
    
    if ($quarterly_total >= $threshold && isset($group_rule['upgrade_to'])) {
        $new_group_key = $group_rule['upgrade_to'];
    } elseif ($quarterly_total < $threshold && isset($group_rule['downgrade_to'])) {
        $new_group_key = $group_rule['downgrade_to'];
    }
    
    // If a group change is needed, update the user's group
    if ($new_group_key && isset($group_rules[$new_group_key]['id'])) {
        $new_group_id = $group_rules[$new_group_key]['id'];
        
        // Update the user's group
        update_user_meta($user_id, 'b2bking_customergroup', $new_group_id);
    }
}

// Function to calculate a user's order total for a specific date range
function b2bking_get_user_order_total($user_id, $start_date, $end_date) {
    // Get all orders for this user in the date range
    $args = array(
        'customer_id' => $user_id,
        'date_created' => $start_date . '...' . $end_date,
        'status' => array('wc-completed', 'wc-processing'), // Only count completed and processing orders
        'limit' => -1, // Get all orders
    );
    
    $orders = wc_get_orders($args);
    
    $total = 0;
    
    // Sum the order totals
    foreach ($orders as $order) {
        $total += $order->get_total();
    }
    
    return $total;
}
Editor is loading...
Leave a Comment