Untitled

mail@pastecode.io avatar
unknown
plain_text
16 days ago
2.6 kB
0
Indexable
Never

add_action('woocommerce_checkout_order_processed', function($order_id){
	$order = wc_get_order($order_id);
	$user_id = $order->get_customer_id();
	$order_total = $order->get_total();
	$amount = $order_total / 100; // 1% credit


	$note = esc_html__('Credit for order ','b2bkingcredit').'#'.$order_id;
	// get user history
	$user_credit_history = sanitize_text_field(get_user_meta($user_id,'b2bking_user_credit_history', true));

	// create reimbursed transaction
	$date = date_i18n( 'Y/m/d', time()+(get_option('gmt_offset')*3600) ); 
	$operation = 'reimburse';
	$consumed_balance = get_user_meta($user_id,'b2bking_user_credit_consumed_balance', true);
	$new_consumed_balance = floatval($consumed_balance) - floatval($amount);		
	$transaction_new = $date.':'.$operation.':'.$amount.':'.$new_consumed_balance.':'.$note;

	// update credit history
	update_user_meta($user_id,'b2bking_user_credit_history',$user_credit_history.';'.$transaction_new);
	// update user consumed balance
	update_user_meta($user_id,'b2bking_user_credit_consumed_balance',$new_consumed_balance);

	$order->update_meta_data('added_extra_credit', $amount);
	$order->save();
}, 10, 1);

add_action( 'woocommerce_order_status_changed', 'custom_order_status_change_action', 10, 4 );
function custom_order_status_change_action( $order_id, $old_status, $new_status, $order ) {
    if ( in_array( $new_status, array( 'cancelled', 'failed', 'refunded' ) ) ) {
    	$customer_id = $order->get_customer_id();
    	$credit = floatval($order->get_meta('added_extra_credit'));
    	if ($credit > 0){
    		$total = $credit;
    		// remove credit from order
    		$note = esc_html__('Cancelled credit for order','b2bkingcredit').' #'.$order_id;

    		// get user history
    		$user_credit_history = sanitize_text_field(get_user_meta($customer_id,'b2bking_user_credit_history', true));

    		// create transaction
    		$date = date_i18n( 'Y/m/d', time()+(get_option('gmt_offset')*3600) ); 
    		$operation = 'purchase';
    		$consumed_balance = get_user_meta($customer_id,'b2bking_user_credit_consumed_balance', true);
    		$new_consumed_balance = floatval($consumed_balance) + floatval($total);		
    		$transaction_new = $date.':'.$operation.':'.$total.':'.$new_consumed_balance.':'.$note;

    		// update credit history
    		update_user_meta($customer_id,'b2bking_user_credit_history',$user_credit_history.';'.$transaction_new);
    		// update user consumed balance
    		update_user_meta($customer_id,'b2bking_user_credit_consumed_balance',$new_consumed_balance);


    		$order->update_meta_data('added_extra_credit', 0);
    		$order->save();

    	}
    }
}
Leave a Comment