Untitled

 avatar
webwizards
plain_text
3 days ago
2.7 kB
0
Indexable
function b2bking_check_quarterly_updates() {
    // Configuration
    $basic_group_id = 123; // change this with the group ID of this group
    $premium_group_id = 234; // change this with the group ID of this group
    $quarterly_threshold = 3750;
    
    // Check if today is first day of quarter (Jan 1, Apr 1, Jul 1, Oct 1)
    $month = (int) date('n');
    $day = (int) date('j');
    
    if ($day !== 1 || !in_array($month, [1, 4, 7, 10])) {
        return;
    }
    
    // Prevent running multiple times on same day
    $last_run = get_option('b2bking_last_quarterly_update', '');
    $today = date('Y-m-d');
    
    if ($last_run === $today) {
        return;
    }
    
    // Update all customers
    $customers = get_users(['role' => 'customer', 'fields' => 'ID']);
    
    foreach ($customers as $customer_id) {
        $previous_quarter_sales = b2bking_get_previous_quarter_sales($customer_id);
        $new_group_id = ($previous_quarter_sales >= $quarterly_threshold) 
            ? $premium_group_id 
            : $basic_group_id;
        
        if (b2bking()->get_user_group($customer_id) != $new_group_id) {
            b2bking()->update_user_group($customer_id, $new_group_id);
        }
    }
    
    update_option('b2bking_last_quarterly_update', $today);
}
add_action('wp_loaded', 'b2bking_check_quarterly_updates');

/**
 * Get customer's previous quarter sales total
 */
function b2bking_get_previous_quarter_sales($customer_id) {
    $dates = b2bking_get_previous_quarter_dates();
    
    $orders = wc_get_orders([
        'customer_id' => $customer_id,
        'status' => 'wc-completed', // Fixed: added 'wc-' prefix
        'date_created' => $dates['start'] . '...' . $dates['end'],
        'limit' => -1
    ]);
    
    return array_sum(array_map(function($order) {
        return $order->get_total();
    }, $orders));
}

/**
 * Get previous quarter date range
 */
function b2bking_get_previous_quarter_dates() {
    $year = date('Y');
    $current_quarter = ceil(date('n') / 3);
    
    // Quarter start months and previous quarter logic
    $quarters = [
        1 => ['01-01', '03-31'],
        2 => ['04-01', '06-30'], 
        3 => ['07-01', '09-30'],
        4 => ['10-01', '12-31']
    ];
    
    if ($current_quarter === 1) {
        // Previous quarter is Q4 of last year
        $prev_year = $year - 1;
        $prev_quarter = 4;
    } else {
        $prev_year = $year;
        $prev_quarter = $current_quarter - 1;
    }
    
    return [
        'start' => $prev_year . '-' . $quarters[$prev_quarter][0] . ' 00:00:00',
        'end' => $prev_year . '-' . $quarters[$prev_quarter][1] . ' 23:59:59'
    ];
}
Editor is loading...
Leave a Comment