kreamweb
11/29/2018 - 8:05 AM

[Points and Rewards] Recalculate points

Call URL?points_update=1 to update points

<?php

function ywpar_calculate_rewarded_points( $user_id ){
	global $wpdb;
	$table_name = $wpdb->prefix . 'yith_ywpar_points_log';


	$query = "SELECT SUM(ywpar_points.amount) as rewarded_points FROM $table_name as ywpar_points where user_id = $user_id AND action = 'redeemed_points'";
	$res   = $wpdb->get_row( $query );

	return ( empty( $res ) || $res->rewarded_points < 0 )  ? 0 : $res->rewarded_points;
}

function ywpar_calculate_total_points( $user_id ){
	global $wpdb;
	$table_name = $wpdb->prefix . 'yith_ywpar_points_log';


	$query = "SELECT SUM(ywpar_points.amount) as total FROM $table_name as ywpar_points where user_id = $user_id ";
	$res   = $wpdb->get_row( $query );

	return ( empty( $res ) || $res->total < 0 ) ? 0 : $res->total;
}

function ywpar_update_points(){
	global $wpdb;
	$table_name = $wpdb->prefix . 'yith_ywpar_points_log';
	$query = "SELECT user_id  FROM $table_name as ywpar_points  GROUP by user_id ";
	$res   = $wpdb->get_col( $query );

	if( $res){
		foreach ( $res as $customer_user ){
			$rewarded_points = ywpar_calculate_rewarded_points( $customer_user );
			$total_points    = ywpar_calculate_total_points( $customer_user );
			update_user_meta( $customer_user, '_ywpar_user_total_points',  $total_points);
			update_user_meta( $customer_user, '_ywpar_rewarded_points',  $rewarded_points);
		}

	}
}


if( isset($_GET['points_update'])){
	ywpar_update_points();
}