/**
  * Get the Export Data
  *
  * @access public
  * @since 2.5
  * @global object $wpdb Used to query the database using the WordPress
  *   Database API
  * @return array $data The data for the CSV file
  */
 public function get_data()
 {
     if ($this->step == 1) {
         $this->delete_data('edd_temp_recount_earnings');
     }
     $total = get_option('edd_temp_recount_earnings', false);
     if (false === $total) {
         $total = (double) 0;
         $this->store_data('edd_temp_recount_earnings', $total);
     }
     $accepted_statuses = apply_filters('edd_recount_accepted_statuses', array('publish', 'revoked'));
     $args = apply_filters('edd_recount_earnings_args', array('number' => $this->per_step, 'page' => $this->step, 'status' => $accepted_statuses, 'fields' => 'ids'));
     $payments = edd_get_payments($args);
     if (!empty($payments)) {
         foreach ($payments as $payment) {
             $total += edd_get_payment_amount($payment);
         }
         if ($total < 0) {
             $totals = 0;
         }
         $total = round($total, edd_currency_decimal_filter());
         $this->store_data('edd_temp_recount_earnings', $total);
         return true;
     }
     update_option('edd_earnings_total', $total);
     set_transient('edd_earnings_total', $total, 86400);
     return false;
 }
/**
 * Retrieve the Cart Content Details
 *
 * Includes prices, tax, etc of all items.
 *
 * @since 1.0
 * @return array $details Cart content details
 */
function edd_get_cart_content_details()
{
    global $edd_is_last_cart_item, $edd_flat_discount_total;
    $cart_items = edd_get_cart_contents();
    if (empty($cart_items)) {
        return false;
    }
    $details = array();
    $length = count($cart_items) - 1;
    foreach ($cart_items as $key => $item) {
        if ($key >= $length) {
            $edd_is_last_cart_item = true;
        }
        $item['quantity'] = edd_item_quantities_enabled() ? absint($item['quantity']) : 1;
        $price_id = isset($item['options']['price_id']) ? $item['options']['price_id'] : NULL;
        $item_price = edd_get_cart_item_price($item['id'], $item['options']);
        $discount = edd_get_cart_item_discount_amount($item);
        $discount = apply_filters('edd_get_cart_content_details_item_discount_amount', $discount, $item);
        $quantity = edd_get_cart_item_quantity($item['id'], $item['options']);
        $fees = edd_get_cart_fees('fee', $item['id'], $price_id);
        $subtotal = $item_price * $quantity;
        foreach ($fees as $fee) {
            if ($fee['amount'] < 0) {
                $subtotal += $fee['amount'];
            }
        }
        $tax = edd_get_cart_item_tax($item['id'], $item['options'], $subtotal - $discount);
        if (edd_prices_include_tax()) {
            $subtotal -= round($tax, edd_currency_decimal_filter());
        }
        $total = $subtotal - $discount + $tax;
        // Do not allow totals to go negative
        if ($total < 0) {
            $total = 0;
        }
        $details[$key] = array('name' => get_the_title($item['id']), 'id' => $item['id'], 'item_number' => $item, 'item_price' => round($item_price, edd_currency_decimal_filter()), 'quantity' => $quantity, 'discount' => round($discount, edd_currency_decimal_filter()), 'subtotal' => round($subtotal, edd_currency_decimal_filter()), 'tax' => round($tax, edd_currency_decimal_filter()), 'fees' => $fees, 'price' => round($total, edd_currency_decimal_filter()));
        if ($edd_is_last_cart_item) {
            $edd_is_last_cart_item = false;
            $edd_flat_discount_total = 0.0;
        }
    }
    return $details;
}
/**
 * Retrieve the Cart Content Details
 *
 * Includes prices, tax, etc of all items.
 *
 * @since 1.0
 * @return array $details Cart content details
 */
function edd_get_cart_content_details()
{
    $cart_items = edd_get_cart_contents();
    if (empty($cart_items)) {
        return false;
    }
    $details = array();
    foreach ($cart_items as $key => $item) {
        $item['quantity'] = edd_item_quantities_enabled() ? absint($item['quantity']) : 1;
        $item_price = edd_get_cart_item_price($item['id'], $item['options']);
        $discount = apply_filters('edd_get_cart_content_details_item_discount_amount', edd_get_cart_item_discount_amount($item), $item);
        $quantity = edd_get_cart_item_quantity($item['id'], $item['options']);
        $fees = edd_get_cart_fees('fee', $item['id']);
        $subtotal = $item_price * $quantity - $discount;
        $tax = edd_get_cart_item_tax($item['id'], $item['options'], $subtotal);
        if (edd_prices_include_tax()) {
            $subtotal -= $tax;
        }
        $total = round($subtotal + $tax, edd_currency_decimal_filter());
        $details[$key] = array('name' => get_the_title($item['id']), 'id' => $item['id'], 'item_number' => $item, 'item_price' => round($item_price, edd_currency_decimal_filter()), 'quantity' => $quantity, 'discount' => round($discount, edd_currency_decimal_filter()), 'subtotal' => round($subtotal, edd_currency_decimal_filter()), 'tax' => round($tax, edd_currency_decimal_filter()), 'fees' => $fees, 'price' => $total);
    }
    return $details;
}
/**
 * Get the discounted amount on a price
 *
 * @since 1.9
 * @param array $item Cart item array
 * @return float The discounted amount
 */
function edd_get_cart_item_discount_amount($item = array())
{
    global $edd_is_last_cart_item, $edd_flat_discount_total;
    // If we're not meeting the requirements of the $item array, return or set them
    if (empty($item) || empty($item['id'])) {
        return 0;
    }
    // Quantity is a requirement of the cart options array to determine the discounted price
    if (empty($item['quantity'])) {
        return 0;
    }
    if (!isset($item['options'])) {
        $item['options'] = array();
    }
    $amount = 0;
    $price = edd_get_cart_item_price($item['id'], $item['options']);
    $discounted_price = $price;
    // Retrieve all discounts applied to the cart
    $discounts = edd_get_cart_discounts();
    if ($discounts) {
        foreach ($discounts as $discount) {
            $code_id = edd_get_discount_id_by_code($discount);
            // Check discount exists
            if (!$code_id) {
                continue;
            }
            $reqs = edd_get_discount_product_reqs($code_id);
            $excluded_products = edd_get_discount_excluded_products($code_id);
            // Make sure requirements are set and that this discount shouldn't apply to the whole cart
            if (!empty($reqs) && edd_is_discount_not_global($code_id)) {
                // This is a product(s) specific discount
                foreach ($reqs as $download_id) {
                    if ($download_id == $item['id'] && !in_array($item['id'], $excluded_products)) {
                        $discounted_price -= $price - edd_get_discounted_amount($discount, $price);
                    }
                }
            } else {
                // This is a global cart discount
                if (!in_array($item['id'], $excluded_products)) {
                    if ('flat' === edd_get_discount_type($code_id)) {
                        /* *
                         * In order to correctly record individual item amounts, global flat rate discounts
                         * are distributed across all cart items. The discount amount is divided by the number
                         * of items in the cart and then a portion is evenly applied to each cart item
                         */
                        $items_subtotal = 0.0;
                        $cart_items = edd_get_cart_contents();
                        foreach ($cart_items as $cart_item) {
                            if (!in_array($cart_item['id'], $excluded_products)) {
                                $item_price = edd_get_cart_item_price($cart_item['id'], $cart_item['options']);
                                $items_subtotal += $item_price * $cart_item['quantity'];
                            }
                        }
                        $subtotal_percent = $price * $item['quantity'] / $items_subtotal;
                        $code_amount = edd_get_discount_amount($code_id);
                        $discounted_amount = $code_amount * $subtotal_percent;
                        $discounted_price -= $discounted_amount;
                        $edd_flat_discount_total += round($discounted_amount, edd_currency_decimal_filter());
                        if ($edd_is_last_cart_item && $edd_flat_discount_total < $code_amount) {
                            $adjustment = $code_amount - $edd_flat_discount_total;
                            $discounted_price -= $adjustment;
                        }
                    } else {
                        $discounted_price -= $price - edd_get_discounted_amount($discount, $price);
                    }
                }
            }
        }
        $amount = $price - apply_filters('edd_get_cart_item_discounted_amount', $discounted_price, $discounts, $item, $price);
        if ('flat' !== edd_get_discount_type($code_id)) {
            $amount = $amount * $item['quantity'];
        }
    }
    return $amount;
}
 /**
  * Retrieve earning stats
  *
  * @access public
  * @since 1.8
  * @param INT $download_id The download product to retrieve stats for. If false, gets stats for all products
  * @param string|bool $start_date The starting date for which we'd like to filter our sale stats. If false, we'll use the default start date of `this_month`
  * @param string|bool $end_date The end date for which we'd like to filter our sale stats. If false, we'll use the default end date of `this_month`
  * @param bool $include_taxes If taxes should be included in the earnings graphs
  * @return float|int Total amount of sales based on the passed arguments.
  */
 public function get_earnings($download_id = 0, $start_date = false, $end_date = false, $include_taxes = true)
 {
     global $wpdb;
     $this->setup_dates($start_date, $end_date);
     // Make sure start date is valid
     if (is_wp_error($this->start_date)) {
         return $this->start_date;
     }
     // Make sure end date is valid
     if (is_wp_error($this->end_date)) {
         return $this->end_date;
     }
     add_filter('posts_where', array($this, 'payments_where'));
     if (empty($download_id)) {
         // Global earning stats
         $args = array('post_type' => 'edd_payment', 'nopaging' => true, 'post_status' => array('publish', 'revoked'), 'fields' => 'ids', 'update_post_term_cache' => false, 'suppress_filters' => false, 'start_date' => $this->start_date, 'end_date' => $this->end_date, 'edd_transient_type' => 'edd_earnings', 'include_taxes' => $include_taxes);
         $args = apply_filters('edd_stats_earnings_args', $args);
         $cached = get_transient('edd_stats_earnings');
         $key = md5(json_encode($args));
         if (!isset($cached[$key])) {
             $sales = get_posts($args);
             $earnings = 0;
             if ($sales) {
                 $sales = implode(',', array_map('intval', $sales));
                 $total_earnings = $wpdb->get_var("SELECT SUM(meta_value) FROM {$wpdb->postmeta} WHERE meta_key = '_edd_payment_total' AND post_id IN ({$sales})");
                 $total_tax = 0;
                 if (!$include_taxes) {
                     $total_tax = $wpdb->get_var("SELECT SUM(meta_value) FROM {$wpdb->postmeta} WHERE meta_key = '_edd_payment_tax' AND post_id IN ({$sales})");
                 }
                 $total_earnings = apply_filters('edd_payment_stats_earnings_total', $total_earnings, $sales, $args);
                 $earnings += $total_earnings - $total_tax;
             }
             // Cache the results for one hour
             $cached[$key] = $earnings;
             set_transient('edd_stats_earnings', $cached, HOUR_IN_SECONDS);
         }
     } else {
         // Download specific earning stats
         global $edd_logs, $wpdb;
         $args = array('post_parent' => $download_id, 'nopaging' => true, 'log_type' => 'sale', 'fields' => 'ids', 'suppress_filters' => false, 'start_date' => $this->start_date, 'end_date' => $this->end_date, 'edd_transient_type' => 'edd_earnings', 'include_taxes' => $include_taxes);
         $args = apply_filters('edd_stats_earnings_args', $args);
         $cached = get_transient('edd_stats_earnings');
         $key = md5(json_encode($args));
         if (!isset($cached[$key])) {
             $this->timestamp = false;
             $log_ids = $edd_logs->get_connected_logs($args, 'sale');
             $earnings = 0;
             if ($log_ids) {
                 $log_ids = implode(',', array_map('intval', $log_ids));
                 $payment_ids = $wpdb->get_col("SELECT DISTINCT meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_edd_log_payment_id' AND post_id IN ({$log_ids});");
                 foreach ($payment_ids as $payment_id) {
                     $items = edd_get_payment_meta_cart_details($payment_id);
                     foreach ($items as $cart_key => $item) {
                         if ($item['id'] != $download_id) {
                             continue;
                         }
                         $earnings += $item['price'];
                         // Check if there are any item specific fees
                         if (!empty($item['fees'])) {
                             foreach ($item['fees'] as $key => $fee) {
                                 $earnings += $fee['amount'];
                             }
                         }
                         $earnings = apply_filters('edd_payment_stats_item_earnings', $earnings, $payment_id, $cart_key, $item);
                         if (!$include_taxes) {
                             $earnings -= edd_get_payment_item_tax($payment_id, $cart_key);
                         }
                     }
                 }
             }
             // Cache the results for one hour
             $cached[$key] = $earnings;
             set_transient('edd_stats_earnings', $cached, HOUR_IN_SECONDS);
         }
     }
     remove_filter('posts_where', array($this, 'payments_where'));
     $result = $cached[$key];
     return round($result, edd_currency_decimal_filter());
 }
 /**
  * Retrieve earning stats
  *
  * @access public
  * @since 1.8
  * @param $download_id INT The download product to retrieve stats for. If false, gets stats for all products
  * @param $start_date string|bool The starting date for which we'd like to filter our sale stats. If false, we'll use the default start date of `this_month`
  * @param $end_date string|bool The end date for which we'd like to filter our sale stats. If false, we'll use the default end date of `this_month`
  * @return float|int
  */
 public function get_earnings($download_id = 0, $start_date = false, $end_date = false)
 {
     global $wpdb;
     $this->setup_dates($start_date, $end_date);
     // Make sure start date is valid
     if (is_wp_error($this->start_date)) {
         return $this->start_date;
     }
     // Make sure end date is valid
     if (is_wp_error($this->end_date)) {
         return $this->end_date;
     }
     $earnings = 0;
     add_filter('posts_where', array($this, 'payments_where'));
     if (empty($download_id)) {
         // Global earning stats
         $args = array('post_type' => 'edd_payment', 'nopaging' => true, 'post_status' => array('publish', 'revoked'), 'fields' => 'ids', 'update_post_term_cache' => false, 'suppress_filters' => false, 'start_date' => $this->start_date, 'end_date' => $this->end_date, 'edd_transient_type' => 'edd_earnings');
         $args = apply_filters('edd_stats_earnings_args', $args);
         $key = md5(serialize($args));
         $earnings = get_transient($key);
         if (false === $earnings) {
             $sales = get_posts($args);
             $earnings = 0;
             if ($sales) {
                 $sales = implode(',', $sales);
                 $earnings += $wpdb->get_var("SELECT SUM(meta_value) FROM {$wpdb->postmeta} WHERE meta_key = '_edd_payment_total' AND post_id IN({$sales})");
             }
             // Cache the results for one hour
             set_transient($key, $earnings, 60 * 60);
         }
     } else {
         // Download specific earning stats
         global $edd_logs, $wpdb;
         $args = array('post_parent' => $download_id, 'nopaging' => true, 'log_type' => 'sale', 'fields' => 'ids', 'suppress_filters' => false, 'start_date' => $this->start_date, 'end_date' => $this->end_date, 'edd_transient_type' => 'edd_earnings');
         $args = apply_filters('edd_stats_earnings_args', $args);
         $key = md5(serialize($args));
         $earnings = get_transient($key);
         if (false === $earnings) {
             $log_ids = $edd_logs->get_connected_logs($args, 'sale');
             $earnings = 0;
             if ($log_ids) {
                 $log_ids = implode(',', $log_ids);
                 $payment_ids = $wpdb->get_col("SELECT meta_value FROM {$wpdb->postmeta} WHERE meta_key='_edd_log_payment_id' AND post_id IN ({$log_ids});");
                 foreach ($payment_ids as $payment_id) {
                     $items = edd_get_payment_meta_cart_details($payment_id);
                     foreach ($items as $item) {
                         if ($item['id'] != $download_id) {
                             continue;
                         }
                         $earnings += $item['price'];
                     }
                 }
             }
             // Cache the results for one hour
             set_transient($key, $earnings, 60 * 60);
         }
     }
     remove_filter('posts_where', array($this, 'payments_where'));
     return round($earnings, edd_currency_decimal_filter());
 }
/**
 * Get Total Earnings
 *
 * @since 1.2
 * @return float $total Total earnings
 */
function edd_get_total_earnings()
{
    $total = get_option('edd_earnings_total', 0);
    // If no total stored in DB, use old method of calculating total earnings
    if (!$total) {
        global $wpdb;
        $total = get_transient('edd_earnings_total');
        if (false === $total) {
            $total = (double) 0;
            $args = apply_filters('edd_get_total_earnings_args', array('offset' => 0, 'number' => -1, 'status' => array('publish', 'revoked'), 'fields' => 'ids'));
            $payments = edd_get_payments($args);
            if ($payments) {
                /*
                 * If performing a purchase, we need to skip the very last payment in the database, since it calls
                 * edd_increase_total_earnings() on completion, which results in duplicated earnings for the very
                 * first purchase
                 */
                if (did_action('edd_update_payment_status')) {
                    array_pop($payments);
                }
                if (!empty($payments)) {
                    $payments = implode(',', $payments);
                    $total += $wpdb->get_var("SELECT SUM(meta_value) FROM {$wpdb->postmeta} WHERE meta_key = '_edd_payment_total' AND post_id IN({$payments})");
                }
            }
            // Cache results for 1 day. This cache is cleared automatically when a payment is made
            set_transient('edd_earnings_total', $total, 86400);
            // Store the total for the first time
            update_option('edd_earnings_total', $total);
        }
    }
    if ($total < 0) {
        $total = 0;
        // Don't ever show negative earnings
    }
    return apply_filters('edd_total_earnings', round($total, edd_currency_decimal_filter()));
}
示例#8
0
/**
 * Load Admin Scripts
 *
 * Enqueues the required admin scripts.
 *
 * @since 1.0
 * @global $post
 * @param string $hook Page hook
 * @return void
 */
function edd_load_admin_scripts($hook)
{
    if (!apply_filters('edd_load_admin_scripts', edd_is_admin_page(), $hook)) {
        return;
    }
    global $wp_version, $post;
    $js_dir = EDD_PLUGIN_URL . 'assets/js/';
    $css_dir = EDD_PLUGIN_URL . 'assets/css/';
    // Use minified libraries if SCRIPT_DEBUG is turned off
    $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min';
    // These have to be global
    wp_register_style('jquery-chosen', $css_dir . 'chosen' . $suffix . '.css', array(), EDD_VERSION);
    wp_enqueue_style('jquery-chosen');
    wp_register_script('jquery-chosen', $js_dir . 'chosen.jquery' . $suffix . '.js', array('jquery'), EDD_VERSION);
    wp_enqueue_script('jquery-chosen');
    wp_register_script('edd-admin-scripts', $js_dir . 'admin-scripts' . $suffix . '.js', array('jquery'), EDD_VERSION, false);
    wp_enqueue_script('edd-admin-scripts');
    wp_localize_script('edd-admin-scripts', 'edd_vars', array('post_id' => isset($post->ID) ? $post->ID : null, 'edd_version' => EDD_VERSION, 'add_new_download' => __('Add New Download', 'edd'), 'use_this_file' => __('Use This File', 'edd'), 'quick_edit_warning' => __('Sorry, not available for variable priced products.', 'edd'), 'delete_payment' => __('Are you sure you wish to delete this payment?', 'edd'), 'delete_payment_note' => __('Are you sure you wish to delete this note?', 'edd'), 'delete_tax_rate' => __('Are you sure you wish to delete this tax rate?', 'edd'), 'revoke_api_key' => __('Are you sure you wish to revoke this API key?', 'edd'), 'regenerate_api_key' => __('Are you sure you wish to regenerate this API key?', 'edd'), 'resend_receipt' => __('Are you sure you wish to resend the purchase receipt?', 'edd'), 'copy_download_link_text' => __('Copy these links to your clipboard and give them to your customer', 'edd'), 'delete_payment_download' => sprintf(__('Are you sure you wish to delete this %s?', 'edd'), edd_get_label_singular()), 'one_price_min' => __('You must have at least one price', 'edd'), 'one_field_min' => __('You must have at least one field', 'edd'), 'one_download_min' => __('Payments must contain at least one item', 'edd'), 'one_option' => sprintf(__('Choose a %s', 'edd'), edd_get_label_singular()), 'one_or_more_option' => sprintf(__('Choose one or more %s', 'edd'), edd_get_label_plural()), 'numeric_item_price' => __('Item price must be numeric', 'edd'), 'numeric_quantity' => __('Quantity must be numeric', 'edd'), 'currency' => edd_get_currency(), 'currency_sign' => edd_currency_filter(''), 'currency_pos' => edd_get_option('currency_position', 'before'), 'currency_decimals' => edd_currency_decimal_filter(), 'new_media_ui' => apply_filters('edd_use_35_media_ui', 1), 'remove_text' => __('Remove', 'edd'), 'type_to_search' => sprintf(__('Type to search %s', 'edd'), edd_get_label_plural()), 'quantities_enabled' => edd_item_quantities_enabled()));
    wp_enqueue_style('wp-color-picker');
    wp_enqueue_script('wp-color-picker');
    wp_register_style('colorbox', $css_dir . 'colorbox' . $suffix . '.css', array(), '1.3.20');
    wp_enqueue_style('colorbox');
    wp_register_script('colorbox', $js_dir . 'jquery.colorbox-min.js', array('jquery'), '1.3.20');
    wp_enqueue_script('colorbox');
    if (function_exists('wp_enqueue_media') && version_compare($wp_version, '3.5', '>=')) {
        //call for new media manager
        wp_enqueue_media();
    }
    wp_register_script('jquery-flot', $js_dir . 'jquery.flot' . $suffix . '.js');
    wp_enqueue_script('jquery-flot');
    wp_enqueue_script('jquery-ui-datepicker');
    wp_enqueue_script('jquery-ui-dialog');
    $ui_style = 'classic' == get_user_option('admin_color') ? 'classic' : 'fresh';
    wp_register_style('jquery-ui-css', $css_dir . 'jquery-ui-' . $ui_style . $suffix . '.css');
    wp_enqueue_style('jquery-ui-css');
    wp_enqueue_script('media-upload');
    wp_enqueue_script('thickbox');
    wp_enqueue_style('thickbox');
    wp_register_style('edd-admin', $css_dir . 'edd-admin' . $suffix . '.css', EDD_VERSION);
    wp_enqueue_style('edd-admin');
}
 /**
  * Remove a downoad from the payment
  *
  * @since  2.5
  * @param  int   $download_id The download ID to remove
  * @param  array $args        Arguements to pass to identify (quantity, amount, price_id)
  * @return bool               If the item was remvoed or not
  */
 public function remove_download($download_id, $args = array())
 {
     // Set some defaults
     $defaults = array('quantity' => 1, 'item_price' => false, 'price_id' => false, 'cart_index' => false);
     $args = wp_parse_args($args, $defaults);
     $download = new EDD_Download($download_id);
     // Bail if this post isn't a download
     if (!$download || $download->post_type !== 'download') {
         return false;
     }
     $total_reduced = 0;
     $tax_reduced = 0;
     foreach ($this->downloads as $key => $item) {
         if ($download_id != $item['id']) {
             continue;
         }
         if (false !== $args['price_id']) {
             if (isset($item['price_id']) && $args['price_id'] != $item['price_id']) {
                 continue;
             }
         }
         $item_quantity = $this->downloads[$key]['quantity'];
         if ($item_quantity > $args['quantity']) {
             $this->downloads[$key]['quantity'] -= $args['quantity'];
         } else {
             unset($this->downloads[$key]);
         }
     }
     $found_cart_key = false;
     if (false === $args['cart_index']) {
         foreach ($this->cart_details as $cart_key => $item) {
             if ($download_id != $item['id']) {
                 continue;
             }
             if (false !== $args['price_id']) {
                 if (isset($item['price_id']) && $args['price_id'] != $item['item_number']['options']['price_id']) {
                     continue;
                 }
             }
             $found_cart_key = $cart_key;
         }
     } else {
         $cart_index = absint($args['cart_index']);
         if (!array_key_exists($cart_index, $this->cart_details)) {
             return false;
             // Invalid cart index passed.
         }
         if ($this->cart_details[$cart_index]['id'] !== $download_id) {
             return false;
             // We still need the proper Download ID to be sure.
         }
         $found_cart_key = $cart_index;
     }
     $orig_quantity = $this->cart_details[$found_cart_key]['quantity'];
     if ($orig_quantity > $args['quantity']) {
         $this->cart_details[$found_cart_key]['quantity'] -= $args['quantity'];
         $item_price = $this->cart_details[$found_cart_key]['item_price'];
         $tax = $this->cart_details[$found_cart_key]['tax'];
         $discount = !empty($this->cart_details[$found_cart_key]['discount']) ? $this->cart_details[$found_cart_key]['discount'] : 0;
         // The total reduction quals the number removed * the item_price
         $total_reduced = round($item_price * $args['quantity'], edd_currency_decimal_filter());
         $tax_reduced = round($tax / $orig_quantity * $args['quantity'], edd_currency_decimal_filter());
         $new_quantity = $this->cart_details[$found_cart_key]['quantity'];
         $new_tax = $this->cart_details[$found_cart_key]['tax'] - $tax_reduced;
         $new_subtotal = $new_quantity * $item_price;
         $new_discount = 0;
         $new_total = 0;
         $this->cart_details[$found_cart_key]['subtotal'] = $new_subtotal;
         $this->cart_details[$found_cart_key]['discount'] = $new_discount;
         $this->cart_details[$found_cart_key]['tax'] = $new_tax;
         $this->cart_details[$found_cart_key]['price'] = $new_subtotal - $new_discount + $new_tax;
     } else {
         $total_reduced = $this->cart_details[$found_cart_key]['item_price'];
         $tax_reduced = $this->cart_details[$found_cart_key]['tax'];
         unset($this->cart_details[$found_cart_key]);
     }
     $pending_args = $args;
     $pending_args['id'] = $download_id;
     $pending_args['price_id'] = false !== $args['price_id'] ? $args['price_id'] : false;
     $pending_args['quantity'] = $args['quantity'];
     $pending_args['action'] = 'remove';
     $this->pending['downloads'][] = $pending_args;
     $this->decrease_subtotal($total_reduced);
     $this->decrease_tax($tax_reduced);
     return true;
 }
示例#10
0
/**
 * Process the payment details edit
 *
 * @access      private
 * @since       1.9
 * @return      void
*/
function edd_update_payment_details($data)
{
    if (!current_user_can('edit_shop_payments', $data['edd_payment_id'])) {
        wp_die(__('You do not have permission to edit this payment record', 'easy-digital-downloads'), __('Error', 'easy-digital-downloads'), array('response' => 403));
    }
    check_admin_referer('edd_update_payment_details_nonce');
    // Retrieve the payment ID
    $payment_id = absint($data['edd_payment_id']);
    // Retrieve existing payment meta
    $meta = edd_get_payment_meta($payment_id);
    $user_info = edd_get_payment_meta_user_info($payment_id);
    $status = $data['edd-payment-status'];
    $unlimited = isset($data['edd-unlimited-downloads']) ? '1' : '';
    $date = sanitize_text_field($data['edd-payment-date']);
    $hour = sanitize_text_field($data['edd-payment-time-hour']);
    // Restrict to our high and low
    if ($hour > 23) {
        $hour = 23;
    } elseif ($hour < 0) {
        $hour = 00;
    }
    $minute = sanitize_text_field($data['edd-payment-time-min']);
    // Restrict to our high and low
    if ($minute > 59) {
        $minute = 59;
    } elseif ($minute < 0) {
        $minute = 00;
    }
    $address = array_map('trim', $data['edd-payment-address'][0]);
    $curr_total = edd_sanitize_amount(edd_get_payment_amount($payment_id));
    $new_total = edd_sanitize_amount($_POST['edd-payment-total']);
    $tax = isset($_POST['edd-payment-tax']) ? edd_sanitize_amount($_POST['edd-payment-tax']) : 0;
    $date = date('Y-m-d', strtotime($date)) . ' ' . $hour . ':' . $minute . ':00';
    $curr_customer_id = sanitize_text_field($data['edd-current-customer']);
    $new_customer_id = sanitize_text_field($data['customer-id']);
    // Setup purchased Downloads and price options
    $updated_downloads = isset($_POST['edd-payment-details-downloads']) ? $_POST['edd-payment-details-downloads'] : false;
    if ($updated_downloads && !empty($_POST['edd-payment-downloads-changed'])) {
        $downloads = array();
        $cart_details = array();
        $i = 0;
        foreach ($updated_downloads as $download) {
            if (empty($download['amount'])) {
                $download['amount'] = '0.00';
            }
            $item = array();
            $item['id'] = absint($download['id']);
            $item['quantity'] = absint($download['quantity']) > 0 ? absint($download['quantity']) : 1;
            $price_id = (int) $download['price_id'];
            $has_log = absint($download['has_log']);
            if ($price_id !== false && edd_has_variable_prices($item['id'])) {
                $item['options'] = array('price_id' => $price_id);
            }
            $downloads[] = $item;
            $cart_item = array();
            $cart_item['item_number'] = $item;
            $item_price = round($download['amount'] / $item['quantity'], edd_currency_decimal_filter());
            $cart_details[$i] = array('name' => get_the_title($download['id']), 'id' => $download['id'], 'item_number' => $item, 'price' => $download['amount'], 'item_price' => $item_price, 'subtotal' => $download['amount'], 'quantity' => $download['quantity'], 'discount' => 0, 'tax' => 0);
            // If this item doesn't have a log yet, add one for each quantity count
            if (empty($has_log)) {
                $log_date = date('Y-m-d G:i:s', current_time('timestamp', true));
                $price_id = $price_id !== false ? $price_id : 0;
                $y = 0;
                while ($y < $download['quantity']) {
                    edd_record_sale_in_log($download['id'], $payment_id, $price_id, $log_date);
                    $y++;
                }
                edd_increase_purchase_count($download['id'], $download['quantity']);
                edd_increase_earnings($download['id'], $download['amount']);
            }
            $i++;
        }
        $meta['downloads'] = $downloads;
        $meta['cart_details'] = $cart_details;
        $deleted_downloads = json_decode(stripcslashes($data['edd-payment-removed']), true);
        foreach ($deleted_downloads as $deleted_download) {
            $deleted_download = $deleted_download[0];
            if (empty($deleted_download['id'])) {
                continue;
            }
            $price_id = empty($deleted_download['price_id']) ? 0 : (int) $deleted_download['price_id'];
            $log_args = array('post_type' => 'edd_log', 'post_parent' => $deleted_download['id'], 'numberposts' => $deleted_download['quantity'], 'meta_query' => array(array('key' => '_edd_log_payment_id', 'value' => $payment_id, 'compare' => '='), array('key' => '_edd_log_price_id', 'value' => $price_id, 'compare' => '=')));
            $found_logs = get_posts($log_args);
            foreach ($found_logs as $log) {
                wp_delete_post($log->ID, true);
            }
            edd_decrease_purchase_count($deleted_download['id'], $deleted_download['quantity']);
            edd_decrease_earnings($deleted_download['id'], $deleted_download['amount']);
            do_action('edd_remove_download_from_payment', $payment_id, $deleted_download['id']);
        }
    }
    do_action('edd_update_edited_purchase', $payment_id);
    // Update main payment record
    $updated = wp_update_post(array('ID' => $payment_id, 'post_date' => $date));
    if (0 === $updated) {
        wp_die(__('Error Updating Payment', 'easy-digital-downloads'), __('Error', 'easy-digital-downloads'), array('response' => 400));
    }
    $customer_changed = false;
    if (isset($data['edd-new-customer']) && $data['edd-new-customer'] == '1') {
        $email = isset($data['edd-new-customer-email']) ? sanitize_text_field($data['edd-new-customer-email']) : '';
        $names = isset($data['edd-new-customer-name']) ? sanitize_text_field($data['edd-new-customer-name']) : '';
        if (empty($email) || empty($names)) {
            wp_die(__('New Customers require a name and email address', 'easy-digital-downloads'));
        }
        $customer = new EDD_Customer($email);
        if (empty($customer->id)) {
            $customer_data = array('name' => $names, 'email' => $email);
            $user_id = email_exists($email);
            if (false !== $user_id) {
                $customer_data['user_id'] = $user_id;
            }
            if (!$customer->create($customer_data)) {
                // Failed to crete the new customer, assume the previous customer
                $customer_changed = false;
                $customer = new EDD_Customer($curr_customer_id);
                edd_set_error('edd-payment-new-customer-fail', __('Error creating new customer', 'easy-digital-downloads'));
            }
        }
        $new_customer_id = $customer->id;
        $previous_customer = new EDD_Customer($curr_customer_id);
        $customer_changed = true;
    } elseif ($curr_customer_id !== $new_customer_id) {
        $customer = new EDD_Customer($new_customer_id);
        $email = $customer->email;
        $names = $customer->name;
        $previous_customer = new EDD_Customer($curr_customer_id);
        $customer_changed = true;
    } else {
        $customer = new EDD_Customer($curr_customer_id);
        $email = $customer->email;
        $names = $customer->name;
    }
    // Setup first and last name from input values
    $names = explode(' ', $names);
    $first_name = !empty($names[0]) ? $names[0] : '';
    $last_name = '';
    if (!empty($names[1])) {
        unset($names[0]);
        $last_name = implode(' ', $names);
    }
    if ($customer_changed) {
        // Remove the stats and payment from the previous customer and attach it to the new customer
        $previous_customer->remove_payment($payment_id, false);
        $customer->attach_payment($payment_id, false);
        // If purchase was completed and not ever refunded, adjust stats of customers
        if ('revoked' == $status || 'publish' == $status) {
            $previous_customer->decrease_purchase_count();
            $previous_customer->decrease_value($new_total);
            $customer->increase_purchase_count();
            $customer->increase_value($new_total);
        }
        update_post_meta($payment_id, '_edd_payment_customer_id', $customer->id);
    }
    // Set new meta values
    $user_info['id'] = $customer->user_id;
    $user_info['email'] = $customer->email;
    $user_info['first_name'] = $first_name;
    $user_info['last_name'] = $last_name;
    $user_info['address'] = $address;
    $meta['user_info'] = $user_info;
    $meta['tax'] = $tax;
    // Check for payment notes
    if (!empty($data['edd-payment-note'])) {
        $note = wp_kses($data['edd-payment-note'], array());
        edd_insert_payment_note($payment_id, $note);
    }
    // Set new status
    edd_update_payment_status($payment_id, $status);
    edd_update_payment_meta($payment_id, '_edd_payment_user_id', $customer->user_id);
    edd_update_payment_meta($payment_id, '_edd_payment_user_email', $customer->email);
    edd_update_payment_meta($payment_id, '_edd_payment_meta', $meta);
    edd_update_payment_meta($payment_id, '_edd_payment_total', $new_total);
    // Adjust total store earnings if the payment total has been changed
    if ($new_total !== $curr_total && ('publish' == $status || 'revoked' == $status)) {
        if ($new_total > $curr_total) {
            // Increase if our new total is higher
            $difference = $new_total - $curr_total;
            edd_increase_total_earnings($difference);
        } elseif ($curr_total > $new_total) {
            // Decrease if our new total is lower
            $difference = $curr_total - $new_total;
            edd_decrease_total_earnings($difference);
        }
    }
    edd_update_payment_meta($payment_id, '_edd_payment_downloads', $new_total);
    edd_update_payment_meta($payment_id, '_edd_payment_unlimited_downloads', $unlimited);
    do_action('edd_updated_edited_purchase', $payment_id);
    wp_safe_redirect(admin_url('edit.php?post_type=download&page=edd-payment-history&view=view-order-details&edd-message=payment-updated&id=' . $payment_id));
    exit;
}
示例#11
0
/**
 * Load Admin Scripts
 *
 * Enqueues the required admin scripts.
 *
 * @since 1.0
 * @global $post
 * @param string $hook Page hook
 * @return void
 */
function edd_load_admin_scripts($hook)
{
    if (!apply_filters('edd_load_admin_scripts', edd_is_admin_page(), $hook)) {
        return;
    }
    global $post;
    $js_dir = EDD_PLUGIN_URL . 'assets/js/';
    $css_dir = EDD_PLUGIN_URL . 'assets/css/';
    // Use minified libraries if SCRIPT_DEBUG is turned off
    $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min';
    // These have to be global
    wp_register_style('jquery-chosen', $css_dir . 'chosen' . $suffix . '.css', array(), EDD_VERSION);
    wp_enqueue_style('jquery-chosen');
    wp_register_script('jquery-chosen', $js_dir . 'chosen.jquery' . $suffix . '.js', array('jquery'), EDD_VERSION);
    wp_enqueue_script('jquery-chosen');
    wp_enqueue_script('jquery-form');
    $admin_deps = array();
    if (!edd_is_admin_page($hook, 'edit') && !edd_is_admin_page($hook, 'new')) {
        $admin_deps = array('jquery', 'jquery-form', 'inline-edit-post');
    } else {
        $admin_deps = array('jquery', 'jquery-form');
    }
    wp_register_script('edd-admin-scripts', $js_dir . 'admin-scripts' . $suffix . '.js', $admin_deps, EDD_VERSION, false);
    wp_enqueue_script('edd-admin-scripts');
    wp_localize_script('edd-admin-scripts', 'edd_vars', array('post_id' => isset($post->ID) ? $post->ID : null, 'edd_version' => EDD_VERSION, 'add_new_download' => __('Add New Download', 'easy-digital-downloads'), 'use_this_file' => __('Use This File', 'easy-digital-downloads'), 'quick_edit_warning' => __('Sorry, not available for variable priced products.', 'easy-digital-downloads'), 'delete_payment' => __('Are you sure you wish to delete this payment?', 'easy-digital-downloads'), 'delete_payment_note' => __('Are you sure you wish to delete this note?', 'easy-digital-downloads'), 'delete_tax_rate' => __('Are you sure you wish to delete this tax rate?', 'easy-digital-downloads'), 'revoke_api_key' => __('Are you sure you wish to revoke this API key?', 'easy-digital-downloads'), 'regenerate_api_key' => __('Are you sure you wish to regenerate this API key?', 'easy-digital-downloads'), 'resend_receipt' => __('Are you sure you wish to resend the purchase receipt?', 'easy-digital-downloads'), 'copy_download_link_text' => __('Copy these links to your clipboard and give them to your customer', 'easy-digital-downloads'), 'delete_payment_download' => sprintf(__('Are you sure you wish to delete this %s?', 'easy-digital-downloads'), edd_get_label_singular()), 'one_price_min' => __('You must have at least one price', 'easy-digital-downloads'), 'one_field_min' => __('You must have at least one field', 'easy-digital-downloads'), 'one_download_min' => __('Payments must contain at least one item', 'easy-digital-downloads'), 'one_option' => sprintf(__('Choose a %s', 'easy-digital-downloads'), edd_get_label_singular()), 'one_or_more_option' => sprintf(__('Choose one or more %s', 'easy-digital-downloads'), edd_get_label_plural()), 'numeric_item_price' => __('Item price must be numeric', 'easy-digital-downloads'), 'numeric_quantity' => __('Quantity must be numeric', 'easy-digital-downloads'), 'currency' => edd_get_currency(), 'currency_sign' => edd_currency_filter(''), 'currency_pos' => edd_get_option('currency_position', 'before'), 'currency_decimals' => edd_currency_decimal_filter(), 'new_media_ui' => apply_filters('edd_use_35_media_ui', 1), 'remove_text' => __('Remove', 'easy-digital-downloads'), 'type_to_search' => sprintf(__('Type to search %s', 'easy-digital-downloads'), edd_get_label_plural()), 'quantities_enabled' => edd_item_quantities_enabled(), 'batch_export_no_class' => __('You must choose a method.', 'easy-digital-downloads'), 'batch_export_no_reqs' => __('Required fields not completed.', 'easy-digital-downloads'), 'reset_stats_warn' => __('Are you sure you want to reset your store? This process is <strong><em>not reversible</em></strong>. Please be sure you have a recent backup.', 'easy-digital-downloads'), 'search_placeholder' => sprintf(__('Type to search all %s', 'easy-digital-downloads'), edd_get_label_plural()), 'search_placeholder_customer' => __('Type to search all Customers', 'easy-digital-downloads'), 'search_placeholder_country' => __('Type to search all Countries', 'easy-digital-downloads'), 'search_placeholder_state' => __('Type to search all States/Provinces', 'easy-digital-downloads'), 'unsupported_browser' => __('We are sorry but your browser is not compatible with this kind of file upload. Please upgrade your browser.', 'easy-digital-downloads')));
    wp_enqueue_style('wp-color-picker');
    wp_enqueue_script('wp-color-picker');
    wp_register_style('colorbox', $css_dir . 'colorbox' . $suffix . '.css', array(), '1.3.20');
    wp_enqueue_style('colorbox');
    wp_register_script('colorbox', $js_dir . 'jquery.colorbox-min.js', array('jquery'), '1.3.20');
    wp_enqueue_script('colorbox');
    //call for media manager
    wp_enqueue_media();
    wp_register_script('jquery-flot', $js_dir . 'jquery.flot' . $suffix . '.js');
    wp_enqueue_script('jquery-flot');
    wp_enqueue_script('jquery-ui-datepicker');
    wp_enqueue_script('jquery-ui-dialog');
    wp_enqueue_script('jquery-ui-tooltip');
    $ui_style = 'classic' == get_user_option('admin_color') ? 'classic' : 'fresh';
    wp_register_style('jquery-ui-css', $css_dir . 'jquery-ui-' . $ui_style . $suffix . '.css');
    wp_enqueue_style('jquery-ui-css');
    wp_enqueue_script('media-upload');
    wp_enqueue_script('thickbox');
    wp_enqueue_style('thickbox');
    wp_register_style('edd-admin', $css_dir . 'edd-admin' . $suffix . '.css', EDD_VERSION);
    wp_enqueue_style('edd-admin');
}
 /**
  * Build all the reports data
  *
  * @access public
  * @since  2.4
  * @return array $reports_data All the data for customer reports
  */
 public function reports_data()
 {
     $cached_reports = get_transient('edd_earnings_by_category_data');
     if (false !== $cached_reports) {
         $reports_data = $cached_reports;
     } else {
         $reports_data = array();
         $term_args = array('parent' => 0, 'hierarchical' => 0);
         $categories = get_terms('download_category', $term_args);
         foreach ($categories as $category_id => $category) {
             $category_slugs = array($category->slug);
             $child_args = array('parent' => $category->term_id, 'hierarchical' => 0);
             $child_terms = get_terms('download_category', $child_args);
             if (!empty($child_terms)) {
                 foreach ($child_terms as $child_term) {
                     $category_slugs[] = $child_term->slug;
                 }
             }
             $download_args = array('post_type' => 'download', 'posts_per_page' => -1, 'fields' => 'ids', 'tax_query' => array(array('taxonomy' => 'download_category', 'field' => 'slug', 'terms' => $category_slugs)));
             $downloads = get_posts($download_args);
             $sales = 0;
             $earnings = 0.0;
             $avg_sales = 0;
             $avg_earnings = 0.0;
             foreach ($downloads as $download) {
                 $sales += edd_get_download_sales_stats($download);
                 $earnings += edd_get_download_earnings_stats($download);
                 $avg_sales += edd_get_average_monthly_download_sales($download);
                 $avg_earnings += edd_get_average_monthly_download_earnings($download);
             }
             $avg_sales = round($avg_sales / count($downloads));
             $avg_earnings = round($avg_earnings / count($downloads), edd_currency_decimal_filter());
             $reports_data[] = array('ID' => $category->term_id, 'label' => $category->name, 'total_sales' => edd_format_amount($sales, false), 'total_sales_raw' => $sales, 'total_earnings' => edd_currency_filter(edd_format_amount($earnings)), 'total_earnings_raw' => $earnings, 'avg_sales' => edd_format_amount($avg_sales, false), 'avg_earnings' => edd_currency_filter(edd_format_amount($avg_earnings)), 'is_child' => false);
             if (!empty($child_terms)) {
                 foreach ($child_terms as $child_term) {
                     $child_args = array('post_type' => 'download', 'posts_per_page' => -1, 'fields' => 'ids', 'tax_query' => array(array('taxonomy' => 'download_category', 'field' => 'slug', 'terms' => $child_term->slug)));
                     $child_downloads = get_posts($child_args);
                     $child_sales = 0;
                     $child_earnings = 0.0;
                     $child_avg_sales = 0;
                     $child_avg_earnings = 0.0;
                     foreach ($child_downloads as $child_download) {
                         $child_sales += edd_get_download_sales_stats($child_download);
                         $child_earnings += edd_get_download_earnings_stats($child_download);
                         $child_avg_sales += edd_get_average_monthly_download_sales($child_download);
                         $child_avg_earnings += edd_get_average_monthly_download_earnings($child_download);
                     }
                     $child_avg_sales = round($child_avg_sales / count($child_downloads));
                     $child_avg_earnings = round($child_avg_earnings / count($child_downloads), edd_currency_decimal_filter());
                     $reports_data[] = array('ID' => $child_term->term_id, 'label' => '&#8212; ' . $child_term->name, 'total_sales' => edd_format_amount($child_sales, false), 'total_sales_raw' => $child_sales, 'total_earnings' => edd_currency_filter(edd_format_amount($child_earnings)), 'total_earnings_raw' => $child_earnings, 'avg_sales' => edd_format_amount($child_avg_sales, false), 'avg_earnings' => edd_currency_filter(edd_format_amount($child_avg_earnings)), 'is_child' => true);
                 }
             }
         }
         set_transient('edd_earnings_by_category_data', $reports_data, HOUR_IN_SECONDS / 4);
     }
     return $reports_data;
 }
 /**
  * Build all the reports data
  *
  * @access public
  * @since  2.4
  * @return array $reports_data All the data for customer reports
  */
 public function reports_data()
 {
     /*
      * Date filtering
      */
     $dates = edd_get_report_dates();
     if (!empty($dates['year'])) {
         $date = new DateTime();
         $date->setDate($dates['year'], $dates['m_start'], $dates['day']);
         $start_date = $date->format('Y-m-d');
         $date->setDate($dates['year_end'], $dates['m_end'], $dates['day_end']);
         $end_date = $date->format('Y-m-d');
         $cached_report_key = 'edd_earnings_by_category_data' . $start_date . '_' . $end_date;
     } else {
         $start_date = false;
         $end_date = false;
         $cached_report_key = 'edd_earnings_by_category_data';
     }
     $cached_reports = get_transient($cached_report_key);
     if (false !== $cached_reports) {
         $reports_data = $cached_reports;
     } else {
         $reports_data = array();
         $term_args = array('parent' => 0, 'hierarchical' => 0);
         $categories = get_terms('download_category', $term_args);
         foreach ($categories as $category_id => $category) {
             $category_slugs = array($category->slug);
             $child_args = array('parent' => $category->term_id, 'hierarchical' => 0);
             $child_terms = get_terms('download_category', $child_args);
             if (!empty($child_terms)) {
                 foreach ($child_terms as $child_term) {
                     $category_slugs[] = $child_term->slug;
                 }
             }
             $download_args = array('post_type' => 'download', 'posts_per_page' => -1, 'fields' => 'ids', 'tax_query' => array(array('taxonomy' => 'download_category', 'field' => 'slug', 'terms' => $category_slugs)));
             $downloads = get_posts($download_args);
             $sales = 0;
             $earnings = 0.0;
             $avg_sales = 0;
             $avg_earnings = 0.0;
             $payment_stats = new EDD_Payment_Stats();
             foreach ($downloads as $download) {
                 $current_average_sales = $current_sales = $payment_stats->get_sales($download, $start_date, $end_date);
                 $current_average_earnings = $current_earnings = $payment_stats->get_earnings($download, $start_date, $end_date);
                 $release_date = get_post_field('post_date', $download);
                 $diff = abs(current_time('timestamp') - strtotime($release_date));
                 $months = floor($diff / (30 * 60 * 60 * 24));
                 // Number of months since publication
                 if ($months > 0) {
                     $current_average_sales = $current_sales / $months;
                     $current_average_earnings = $current_earnings / $months;
                 }
                 $sales += $current_sales;
                 $earnings += $current_earnings;
                 $avg_sales += $current_average_sales;
                 $avg_earnings += $current_average_earnings;
             }
             $avg_sales = round($avg_sales / count($downloads));
             $avg_earnings = round($avg_earnings / count($downloads), edd_currency_decimal_filter());
             $reports_data[] = array('ID' => $category->term_id, 'label' => $category->name, 'total_sales' => edd_format_amount($sales, false), 'total_sales_raw' => $sales, 'total_earnings' => edd_currency_filter(edd_format_amount($earnings)), 'total_earnings_raw' => $earnings, 'avg_sales' => edd_format_amount($avg_sales, false), 'avg_earnings' => edd_currency_filter(edd_format_amount($avg_earnings)), 'is_child' => false);
             if (!empty($child_terms)) {
                 foreach ($child_terms as $child_term) {
                     $child_args = array('post_type' => 'download', 'posts_per_page' => -1, 'fields' => 'ids', 'tax_query' => array(array('taxonomy' => 'download_category', 'field' => 'slug', 'terms' => $child_term->slug)));
                     $child_downloads = get_posts($child_args);
                     $child_sales = 0;
                     $child_earnings = 0.0;
                     $child_avg_sales = 0;
                     $child_avg_earnings = 0.0;
                     foreach ($child_downloads as $child_download) {
                         $current_average_sales = $current_sales = $payment_stats->get_sales($child_download, $start_date, $end_date);
                         $current_average_earnings = $current_earnings = $payment_stats->get_earnings($child_download, $start_date, $end_date);
                         $release_date = get_post_field('post_date', $child_download);
                         $diff = abs(current_time('timestamp') - strtotime($release_date));
                         $months = floor($diff / (30 * 60 * 60 * 24));
                         // Number of months since publication
                         if ($months > 0) {
                             $current_average_sales = $current_sales / $months;
                             $current_average_earnings = $current_earnings / $months;
                         }
                         $child_sales += $current_sales;
                         $child_earnings += $current_earnings;
                         $child_avg_sales += $current_average_sales;
                         $child_avg_earnings += $current_average_earnings;
                     }
                     $child_avg_sales = round($child_avg_sales / count($child_downloads));
                     $child_avg_earnings = round($child_avg_earnings / count($child_downloads), edd_currency_decimal_filter());
                     $reports_data[] = array('ID' => $child_term->term_id, 'label' => '&#8212; ' . $child_term->name, 'total_sales' => edd_format_amount($child_sales, false), 'total_sales_raw' => $child_sales, 'total_earnings' => edd_currency_filter(edd_format_amount($child_earnings)), 'total_earnings_raw' => $child_earnings, 'avg_sales' => edd_format_amount($child_avg_sales, false), 'avg_earnings' => edd_currency_filter(edd_format_amount($child_avg_earnings)), 'is_child' => true);
                 }
             }
         }
     }
     return $reports_data;
 }
    public static function payment_creation_form()
    {
        // Determine our float accuracy for the steps and rounding
        $decimals = edd_currency_decimal_filter();
        if (empty($decimals)) {
            $step = 1;
        } else {
            $i = 1;
            $step = '0.';
            while ($i < $decimals) {
                $step .= '0';
                $i++;
            }
            $step .= '1';
            $step = (double) $step;
        }
        $tax_included = 'false';
        if (edd_use_taxes() && edd_prices_include_tax()) {
            $tax_included = 'true';
        }
        $columns = 4;
        ?>
		<div class="wrap">
			<h2><?php 
        _e('Create New Payment', 'edd-manual-purchases');
        ?>
</h2>
			<script type="text/javascript">
				jQuery(document).ready(function($) {

					$(document.body).on('input', '.edd-mp-amount,.edd-mp-tax,.edd-mp-quantity', function() {
						eddmp_update_total();
					});

					// check for variable prices
					$('#edd_mp_create_payment').on('change', '.mp-downloads', function() {
						var $this = $(this);
						var selected_download = $('option:selected', this).val();
						$this.parent().parent().find('.download-price-option-wrap').html('');
						if( parseInt( selected_download ) != 0) {
							var edd_mp_nonce = $('#edd_create_payment_nonce').val();
							var key = $this.parent().parent().data('key');
							$.ajax({
								type: "POST",
								url: ajaxurl,
								data: {
									action: 'edd_mp_check_for_variations',
									download_id: selected_download,
									key: key,
									nonce: edd_mp_nonce
								},
								dataType: "json",
								success: function(response) {
									$this.parent().parent().find('.download-price-option-wrap').html( response.html );
									$this.parent().parent().find('input[name="downloads['+ key +'][amount]"]').val( response.amount );
									eddmp_update_total();
								}
							}).fail(function (data) {
								if ( window.console && window.console.log ) {
									console.log( data );
								}
							});
						} else {
							$this.parent().parent().find('.download-price-option-wrap').html('N/A');
						}
					});

					// Update the price when a variation changes
					$('#edd_mp_create_payment').on('change', '.edd-mp-price-select', function() {
						var $this        = $(this);
						var price_id     = $('option:selected', this).val();
						var edd_mp_nonce = $('#edd_create_payment_nonce').val();
						var key          = $this.parent().parent().data('key');
						var download_id  = $('select[name="downloads[' + key + '][id]"]').val();

						$.ajax({
							type: "POST",
							url: ajaxurl,
							data: {
								action: 'edd_mp_variation_change',
								download_id: download_id,
								price_id: price_id,
								key: key,
								nonce: edd_mp_nonce
							},
							dataType: "json",
							success: function(response) {
								$this.parent().parent().find('input[name="downloads['+ key +'][amount]"]').val( response.amount );
								eddmp_update_total();
							}
						}).fail(function (data) {
							if ( window.console && window.console.log ) {
								console.log( data );
							}
						});

					});

					$('.edd_add_repeatable').click(function() {
						setTimeout( function() {
							$('.edd_repeatable_row:last').find('.download-price-option-wrap').html('');
							$('.edd_repeatable_row:last').find('.edd-mp-quantity').val('1');
						}, 300 );
					});

					$(document.body).on('click', '.edd_remove_repeatable', function() {
						setTimeout( function() {
							var row_count = $('.edd_repeatable_row').length;
							if ( 1 === row_count ) {
								var current_quantity = $('.edd_repeatable_row:first').find('.edd-mp-quantity').val();
								if ( '' === current_quantity ) {
									$('.edd_repeatable_row:first').find('.edd-mp-quantity').val('1');
								}
							}

							eddmp_update_total();
						}, 100 );
					});

					if ($('.form-table .edd_datepicker').length > 0) {
						var dateFormat = 'mm/dd/yy';
						$('.edd_datepicker').datepicker({
							dateFormat: dateFormat
						});
					}

					function eddmp_update_total() {
						// Setup some place holder vars for each row
						var item_amount   = 0;
						var item_tax      = 0;
						var item_quantity = 1;
						var item_total    = 0;

						// Our final total to show to the customer
						var total      = 0;

						var prices_include_tax = <?php 
        echo $tax_included;
        ?>
;

						// Iterate over each line item and add amount + tax * quantity to get the total
						$('.edd_repeatable_row').each(function() {
							var row = $(this);

							item_amount   = parseFloat( row.find('.edd-mp-amount').val() );

							if (row.find('.edd-mp-tax').length) {
								item_tax      = parseFloat(row.find('.edd-mp-tax').val() );

								if (! isNaN(item_tax) && ! prices_include_tax) {
									item_amount = item_amount + item_tax;
								}
							}

							if (row.find('.edd-mp-quantity').length) {
								item_quantity = parseFloat(row.find('.edd-mp-quantity').val() );
							}

							item_total  = item_amount * item_quantity;

							total += item_total;
						});

						if ( isNaN( total ) ){
							total = 0;
						}

						$('#edd-mp-total-amount').html(total.toFixed(<?php 
        echo $decimals;
        ?>
));
					}
				});
			</script>

			<form id="edd_mp_create_payment" method="post">
				<table class="form-table" id="edd-customer-details">
					<tbody id="edd-mp-table-body">
						<tr class="form-field edd-mp-download-wrap">
							<th scope="row" valign="top">
								<label><?php 
        echo edd_get_label_plural();
        ?>
</label>
							</th>
							<td class="edd-mp-downloads">
								<div id="edd_file_fields" class="edd_meta_table_wrap">
									<table class="widefat edd_repeatable_table" style="width: auto;" cellpadding="0" cellspacing="0">
										<thead>
											<tr>
												<th style="padding: 10px;"><?php 
        echo edd_get_label_plural();
        ?>
</th>
												<th style="padding: 10px;"><?php 
        _e('Price Option', 'edd-manual-purchases');
        ?>
</th>
												<th style="padding: 10px; width: 150px;"><?php 
        _e('Amount', 'edd-manual-purchases');
        ?>
</th>
												<?php 
        if (edd_use_taxes()) {
            ?>
													<th style="padding: 10px; width: 150px;"><?php 
            _e('Tax', 'edd-manual-purchases');
            ?>
</th>
													<?php 
            $columns++;
            ?>
												<?php 
        }
        if (edd_item_quantities_enabled()) {
            ?>
													<th style="padding: 10px; width: 50px;"><?php 
            _e('Quantity', 'edd-manual-purchases');
            ?>
</th>
													<?php 
            $columns++;
            ?>
												<?php 
        }
        ?>
												<th style="padding: 10px; width: 5px;"
											</tr>
										</thead>
										<tbody>
											<tr class="edd_repeatable_product_wrapper edd_repeatable_row" data-key="1">
												<td>
													<?php 
        echo EDD()->html->product_dropdown(array('name' => 'downloads[1][id]', 'id' => 'downloads', 'class' => 'mp-downloads', 'multiple' => false, 'chosen' => true));
        ?>
												</td>
												<td class="download-price-option-wrap"><?php 
        _e('N/A', 'edd-manual-purchases');
        ?>
</td>
												<td>
													<input type="number" step="<?php 
        echo $step;
        ?>
" class="edd-mp-amount" name="downloads[1][amount]" value="" min="0" placeholder="<?php 
        esc_attr_e('Item price', 'edd-manual-purchases');
        ?>
"/>
												</td>
												<?php 
        if (edd_use_taxes()) {
            ?>
													<td>
														<?php 
            if (!edd_prices_include_tax()) {
                ?>
														&nbsp;&plus;&nbsp;
														<?php 
            }
            ?>
														<input type="number" style="width: 65%" step="<?php 
            echo $step;
            ?>
" class="edd-mp-tax" name="downloads[1][tax]" value="" min="0" placeholder="<?php 
            esc_attr_e('Item Tax', 'edd-manual-purchases');
            ?>
"/>
													</td>
												<?php 
        }
        ?>
												<?php 
        if (edd_item_quantities_enabled()) {
            ?>
													<td>
														&nbsp;&times;&nbsp;<input type="number" step="1" class="edd-mp-quantity" style="width: 65%" name="downloads[1][quantity]" value="1" min="1" placeholder="<?php 
            esc_attr_e('Enter quantity', 'edd-manual-purchases');
            ?>
"/>
													</td>
												<?php 
        }
        ?>
												<td>
													<a href="#" class="edd_remove_repeatable" data-type="file" style="background: url(<?php 
        echo admin_url('/images/xit.gif');
        ?>
) no-repeat;">&times;</a>
												</td>
											</tr>
											<tr>
												<td class="submit" colspan="<?php 
        echo $columns;
        ?>
" style="float: none; clear:both; background: #fff;">
													<a class="button-secondary edd_add_repeatable" style="margin: 6px 0 10px;"><?php 
        _e('Add New', 'edd-manual-purchases');
        ?>
</a>
													<span style="line-height: 38px;">
														Total: <?php 
        echo edd_currency_symbol();
        ?>
<span id="edd-mp-total-amount">0.00</span>
														<?php 
        if (edd_use_taxes()) {
            ?>
															<sup>&dagger;</sup>
														<?php 
        }
        ?>
													</span>
												</td>
											</tr>
										</tbody>
									</table>
								</div>
								<span>
									<small>
									<?php 
        if (edd_use_taxes()) {
            ?>
<sup>&dagger;</sup>
										<?php 
            if (!edd_prices_include_tax()) {
                ?>
											<em><?php 
                _e('Total is based on prices exclusive of tax.', 'edd-manual-purchases');
                ?>
</em>
										<?php 
            } else {
                ?>
											<em><?php 
                _e('Total is based on prices inclusive of tax.', 'edd-manual-purchases');
                ?>
</em>
										<?php 
            }
            ?>
									<?php 
        }
        ?>
									</small>
								</span>
							</td>
						</tr>
						<tr class="form-field">
							<th scope="row" valign="top">
								<label for="edd-mp-user"><?php 
        _e('Customer', 'edd-manual-purchases');
        ?>
</label>
							</th>
							<td class="edd-mp-email">
								<div class="customer-info">
									<?php 
        echo EDD()->html->customer_dropdown(array('name' => 'customer'));
        ?>
								</div>
								<div class="description customer-info">
									<a href="#new" class="edd-payment-new-customer" title="<?php 
        _e('New Customer', 'edd-manual-purchases');
        ?>
"><?php 
        _e('Create new customer', 'edd-manual-purchases');
        ?>
</a>
								</div>
								<div class="description new-customer" style="display: none">
									<a href="#cancel" class="edd-payment-new-customer-cancel" title="<?php 
        _e('Existing Customer', 'edd-manual-purchases');
        ?>
"><?php 
        _e('Select existing customer', 'edd-manual-purchases');
        ?>
</a>
								</div>
							</td>
						</tr>
						<tr class="form-field new-customer" style="display: none">
							<th scope="row" valign="top">
								<label for="edd-mp-user"><?php 
        _e('Customer Email', 'edd-manual-purchases');
        ?>
</label>
							</th>
							<td class="edd-mp-email">
								<input type="text" class="small-text" id="edd-mp-email" name="email" style="width: 180px;"/>
								<div class="description"><?php 
        _e('Enter the email address of the customer.', 'edd-manual-purchases');
        ?>
</div>
							</td>
						</tr>
						<tr class="form-field new-customer" style="display: none">
							<th scope="row" valign="top">
								<label for="edd-mp-last"><?php 
        _e('Customer First Name', 'edd-manual-purchases');
        ?>
</label>
							</th>
							<td class="edd-mp-last">
								<input type="text" class="small-text" id="edd-mp-last" name="first" style="width: 180px;"/>
								<div class="description"><?php 
        _e('Enter the first name of the customer (optional).', 'edd-manual-purchases');
        ?>
</div>
							</td>
						</tr>
						<tr class="form-field new-customer" style="display: none">
							<th scope="row" valign="top">
								<label for="edd-mp-last"><?php 
        _e('Customer Last Name', 'edd-manual-purchases');
        ?>
</label>
							</th>
							<td class="edd-mp-last">
								<input type="text" class="small-text" id="edd-mp-last" name="last" style="width: 180px;"/>
								<div class="description"><?php 
        _e('Enter the last name of the customer (optional).', 'edd-manual-purchases');
        ?>
</div>
							</td>
						</tr>
						<tr class="form-field">
							<th scope="row" valign="top">
								<label for="edd-mp-amount"><?php 
        _e('Amount', 'edd-manual-purchases');
        ?>
</label>
							</th>
							<td class="edd-mp-downloads">
								<input type="text" class="small-text" id="edd-mp-amount" name="amount" style="width: 180px;"/>
								<?php 
        if (edd_item_quantities_enabled()) {
            ?>
									<div class="description"><?php 
            _e('Enter the total purchase amount, or leave blank to auto calculate price based on the selected items and quantities above. Use 0.00 for 0.', 'edd-manual-purchases');
            ?>
</div>
								<?php 
        } else {
            ?>
									<div class="description"><?php 
            _e('Enter the total purchase amount, or leave blank to auto calculate price based on the selected items above. Use 0.00 for 0.', 'edd-manual-purchases');
            ?>
</div>
								<?php 
        }
        ?>
							</td>
						</tr>
						<tr class="form-field">
							<th scope="row" valign="top">
								<?php 
        _e('Payment status', 'edd-manual-purchases');
        ?>
							</th>
							<td class="edd-mp-status">
								<?php 
        echo EDD()->html->select(array('name' => 'status', 'options' => edd_get_payment_statuses(), 'selected' => 'publish', 'show_option_all' => false, 'show_option_none' => false));
        ?>
								<label for="edd-mp-status" class="description"><?php 
        _e('Select the status of this payment.', 'edd-manual-purchases');
        ?>
</label>
							</td>
						</tr>
						<tr class="form-field">
							<th scope="row" valign="top">
								<label for="edd-mp-payment-method"><?php 
        _e('Payment Method', 'edd-manual-purchases');
        ?>
</label>
							</th>
							<td class="edd-mp-gateways">
								<select name="gateway" id="edd-mp-payment-method">
									<option value="manual_purchases"><?php 
        esc_html_e('Manual Payment', 'edd-manual-purchases');
        ?>
</option>
									<?php 
        foreach (edd_get_payment_gateways() as $gateway_id => $gateway) {
            ?>
										<option value="<?php 
            echo esc_attr($gateway_id);
            ?>
"><?php 
            echo esc_html($gateway['admin_label']);
            ?>
</option>
									<?php 
        }
        ?>
								</select>
								<div class="description"><?php 
        _e('Select the payment method used.', 'edd-manual-purchases');
        ?>
</div>
							</td>
						</tr>
						<tr class="form-field">
							<th scope="row" valign="top">
								<label for="edd-mp-transaction-id"><?php 
        _e('Transaction ID', 'edd-manual-purchases');
        ?>
</label>
							</th>
							<td class="edd-mp-downloads">
								<input type="text" class="small-text" id="edd-mp-transaction-id" name="transaction_id" style="width: 180px;"/>
								<div class="description"><?php 
        _e('Enter the transaction ID, if any.', 'edd-manual-purchases');
        ?>
</div>
							</td>
						</tr>
						<tr class="form-field">
							<th scope="row" valign="top">
								<label for="edd-mp-date"><?php 
        _e('Date', 'edd-manual-purchases');
        ?>
</label>
							</th>
							<td class="edd-mp-downloads">
								<input type="text" class="small-text edd_datepicker" id="edd-mp-date" name="date" style="width: 180px;"/>
								<div class="description"><?php 
        _e('Enter the purchase date, or leave blank for today\'s date.', 'edd-manual-purchases');
        ?>
</div>
							</td>
						</tr>
						<?php 
        if (function_exists('eddc_record_commission')) {
            ?>
						<tr class="form-field">
							<th scope="row" valign="top">
								<?php 
            _e('Commission', 'edd-manual-purchases');
            ?>
							</th>
							<td class="edd-mp-downloads">
								<label for="edd-mp-commission">
									<input type="checkbox" id="edd-mp-commission" name="commission" style="width: auto;"/>
									<?php 
            _e('Record commissions (if any) for this manual purchase?', 'edd-manual-purchases');
            ?>
								</label>
							</td>
						</tr>
						<?php 
        }
        ?>
						<?php 
        if (class_exists('EDD_Simple_Shipping')) {
            ?>
						<tr class="form-field">
							<th scope="row" valign="top">
								<label for="edd-mp-shipped"><?php 
            _e('Shipped', 'edd-manual-purchases');
            ?>
</label>
							</th>
							<td class="edd-mp-shipped">
								<label for="edd-mp-shipped">
									<input type="checkbox" id="edd-mp-shipped" name="shipped" style="width: auto;"/>
									<?php 
            _e('Mark order as shipped?', 'edd-manual-purchases');
            ?>
								</label>
							</td>
						</tr>
						<?php 
        }
        ?>
						<?php 
        if (class_exists('EDD_Wallet')) {
            ?>
						<tr class="form-field">
							<th scope="row" valign="top">
								<label for="edd-mp-wallet"><?php 
            _e('Pay From Wallet', 'edd-manual-purchases');
            ?>
</label>
							</th>
							<td class="edd-mp-wallet">
								<label for="edd-mp-wallet">
									<input type="checkbox" id="edd-mp-wallet" name="wallet" style="width: auto;"/>
									<?php 
            _e('Use funds from the customers\' wallet to pay for this payment.', 'edd-manual-purchases');
            ?>
								</label>
							</td>
						</tr>
						<?php 
        }
        ?>
						<tr class="form-field">
							<th scope="row" valign="top">
								<?php 
        _e('Send Receipt', 'edd-manual-purchases');
        ?>
							</th>
							<td class="edd-mp-receipt">
								<label for="edd-mp-receipt">
									<input type="checkbox" id="edd-mp-receipt" name="receipt" style="width: auto;" checked="1" value="1"/>
									<?php 
        _e('Send the purchase receipt to the buyer?', 'edd-manual-purchases');
        ?>
								</label>
							</td>
						</tr>
					</tbody>
				</table>
				<?php 
        wp_nonce_field('edd_create_payment_nonce', 'edd_create_payment_nonce');
        ?>
				<input type="hidden" name="edd-gateway" value="manual_purchases"/>
				<input type="hidden" name="edd-action" value="create_payment" />
				<?php 
        submit_button(__('Create Payment', 'edd-manual-purchases'));
        ?>
			</form>
		</div>
		<?php 
    }
示例#15
0
/**
 * Given a user id, display a graph of commissions
 *
 * @since  3.2
 * @param  integer $user_id The user id to display commissions graph for
 * @return string           HTML markup of the commissions graph for the user
 */
function eddc_user_commissions_graph($user_id = 0)
{
    $user_id = empty($user_id) ? get_current_user_id() : $user_id;
    // If still empty, exit
    if (empty($user_id)) {
        return;
    }
    $graph = '';
    if (eddc_user_has_commissions($user_id)) {
        include_once EDD_PLUGIN_DIR . 'includes/admin/reporting/class-edd-graph.php';
        global $post;
        $month = !isset($_GET['month']) ? date('n') : absint($_GET['month']);
        $year = !isset($_GET['year']) ? date('Y') : absint($_GET['year']);
        $num_of_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
        ob_start();
        ?>
		<script>
		if ( typeof( edd_vars ) === 'undefined' ) {
			edd_vars = {
				"currency": "<?php 
        echo edd_get_currency();
        ?>
",
				"currency_sign": "<?php 
        echo edd_currency_filter("");
        ?>
",
				"currency_pos": "<?php 
        echo edd_get_option('currency_position', 'before');
        ?>
",
				"currency_decimals": "<?php 
        echo edd_currency_decimal_filter();
        ?>
",
			};
		}
		</script>
		<style>
		.tickLabel {
			width: 30px;
		}
		.legend > table {
			width: auto;
		}
		</style>
		<div id="eddc-dashboard-graphs">

			<h4><?php 
        _e('Commission Stats', 'eddc');
        ?>
</h4>
			<form id="edd-graphs-filter" method="get" action="<?php 
        echo get_the_permalink($post->ID);
        ?>
#eddc-dashboard-graphs">
				<div class="tablenav top">
					<div class="actions">
						<?php 
        echo EDD()->html->month_dropdown('month', $month);
        ?>
						<?php 
        echo EDD()->html->year_dropdown('year', $year);
        ?>

						<input type="hidden" name="edd_action" value="filter_reports" />
						<input type="submit" class="button-secondary" value="<?php 
        _e('Filter', 'eddc');
        ?>
"/>
					</div>
				</div>
			</form>
			<?php 
        $args = array('user_id' => $user_id, 'number' => -1, 'query_args' => array('date_query' => array('after' => array('year' => $year, 'month' => $month, 'day' => 1), 'before' => array('year' => $year, 'month' => $month, 'day' => $num_of_days), 'inclusive' => true)));
        $commissions = eddc_get_commissions($args);
        $grouped_data = array();
        if (!empty($commissions)) {
            foreach ($commissions as $commission) {
                $key = date('njY', strtotime($commission->post_date));
                $commission_meta = get_post_meta($commission->ID, '_edd_commission_info', true);
                if (!isset($grouped_data[$key])) {
                    $grouped_data[$key] = array();
                    $grouped_data[$key]['earnings'] = (double) $commission_meta['amount'];
                    $grouped_data[$key]['sales'] = 1;
                } else {
                    $grouped_data[$key]['earnings'] += (double) $commission_meta['amount'];
                    $grouped_data[$key]['sales']++;
                }
            }
        }
        $d = 1;
        while ($d <= $num_of_days) {
            $key = $month . $d . $year;
            $date = mktime(0, 0, 0, $month, $d, $year) * 1000;
            $sales = isset($grouped_data[$key]['sales']) ? $grouped_data[$key]['sales'] : 0;
            $earnings = isset($grouped_data[$key]['earnings']) ? round($grouped_data[$key]['earnings'], edd_currency_decimal_filter()) : 0;
            $sales_data[] = array($date, $sales);
            $earnings_data[] = array($date, $earnings);
            $d++;
        }
        $data = array(__('Earnings', 'edd') => $earnings_data, __('Sales', 'edd') => $sales_data);
        ?>

			<div class="inside">
				<?php 
        $graph = new EDD_Graph($data);
        $graph->set('x_mode', 'time');
        $graph->set('multiple_y_axes', true);
        $graph->display();
        ?>
			</div>

		</div>
		<?php 
        $graph = apply_filters('edd_user_commissions_graph_display', ob_get_clean());
    }
    return $graph;
}
示例#16
0
/**
 * Process the payment details edit
 *
 * @access      private
 * @since       1.9
 * @return      void
*/
function edd_update_payment_details($data)
{
    if (!current_user_can('edit_shop_payment', $data['edd_payment_id'])) {
        wp_die(__('You do not have permission to edit this payment record', 'edd'), __('Error', 'edd'));
    }
    check_admin_referer('edd_update_payment_details_nonce');
    // Retrieve the payment ID
    $payment_id = absint($data['edd_payment_id']);
    // Retrieve existing payment meta
    $meta = edd_get_payment_meta($payment_id);
    $user_info = edd_get_payment_meta_user_info($payment_id);
    $status = $data['edd-payment-status'];
    $unlimited = isset($data['edd-unlimited-downloads']) ? '1' : '';
    $user_id = intval($data['edd-payment-user-id']);
    $date = sanitize_text_field($data['edd-payment-date']);
    $hour = sanitize_text_field($data['edd-payment-time-hour']);
    $minute = sanitize_text_field($data['edd-payment-time-min']);
    $email = sanitize_text_field($data['edd-payment-user-email']);
    $names = sanitize_text_field($data['edd-payment-user-name']);
    $address = array_map('trim', $data['edd-payment-address'][0]);
    $total = edd_sanitize_amount($_POST['edd-payment-total']);
    $tax = isset($_POST['edd-payment-tax']) ? edd_sanitize_amount($_POST['edd-payment-tax']) : 0;
    // Setup date from input values
    $date = date('Y-m-d', strtotime($date)) . ' ' . $hour . ':' . $minute . ':00';
    // Setup first and last name from input values
    $names = explode(' ', $names);
    $first_name = !empty($names[0]) ? $names[0] : '';
    $last_name = '';
    if (!empty($names[1])) {
        unset($names[0]);
        $last_name = implode(' ', $names);
    }
    // Setup purchased Downloads and price options
    $updated_downloads = isset($_POST['edd-payment-details-downloads']) ? $_POST['edd-payment-details-downloads'] : false;
    if ($updated_downloads && !empty($_POST['edd-payment-downloads-changed'])) {
        $downloads = array();
        $cart_details = array();
        $i = 0;
        foreach ($updated_downloads as $download) {
            if (empty($download['amount'])) {
                $download['amount'] = '0.00';
            }
            $item = array();
            $item['id'] = absint($download['id']);
            $item['quantity'] = absint($download['quantity']) > 0 ? absint($download['quantity']) : 1;
            $price_id = (int) $download['price_id'];
            if ($price_id !== false && edd_has_variable_prices($item['id'])) {
                $item['options'] = array('price_id' => $price_id);
            }
            $downloads[] = $item;
            $cart_item = array();
            $cart_item['item_number'] = $item;
            $item_price = round($download['amount'] / $item['quantity'], edd_currency_decimal_filter());
            $cart_details[$i] = array('name' => get_the_title($download['id']), 'id' => $download['id'], 'item_number' => $item, 'price' => $download['amount'], 'item_price' => $item_price, 'quantity' => $download['quantity'], 'discount' => 0, 'tax' => 0);
            $i++;
        }
        $meta['downloads'] = $downloads;
        $meta['cart_details'] = $cart_details;
    }
    if ($user_id !== $user_info['id'] || $email !== $user_info['email']) {
        $user = get_user_by('id', $user_id);
        if (!empty($user) && strtolower($user->data->user_email) !== strtolower($email)) {
            // protect a purcahse from being assigned to a customer with a user ID and Email that belong to different users
            wp_die('User ID and User Email do not match.');
            exit;
        }
        // Remove the stats and payment from the previous customer
        $previous_customer = EDD()->customers->get_by('email', $user_info['email']);
        EDD()->customers->remove_payment($previous_customer->id, $payment_id);
        // Attribute the payment to the new customer and update the payment post meta
        $new_customer_id = EDD()->customers->get_column_by('id', 'email', $email);
        if (!$new_customer) {
            // No customer exists for the given email so create one
            $new_customer_id = EDD()->customers->add(array('email' => $email, 'name' => $first_name . ' ' . $last_name));
        }
        EDD()->customers->attach_payment($new_customer_id, $payment_id);
        // If purchase was completed and not ever refunded, adjust stats of customers
        if ('revoked' == $status || 'publish' == $status) {
            EDD()->customers->decrement_stats($previous_customer->id, $total);
            EDD()->customers->increment_stats($new_customer_id, $total);
        }
        update_post_meta($payment_id, '_edd_payment_customer_id', $new_customer_id);
    }
    // Set new meta values
    $user_info['id'] = $user_id;
    $user_info['email'] = $email;
    $user_info['first_name'] = $first_name;
    $user_info['last_name'] = $last_name;
    $user_info['address'] = $address;
    $meta['user_info'] = $user_info;
    $meta['tax'] = $tax;
    // Check for payment notes
    if (!empty($data['edd-payment-note'])) {
        $note = wp_kses($data['edd-payment-note'], array());
        edd_insert_payment_note($payment_id, $note);
    }
    do_action('edd_update_edited_purchase', $payment_id);
    // Update main payment record
    wp_update_post(array('ID' => $payment_id, 'post_date' => $date));
    // Set new status
    edd_update_payment_status($payment_id, $status);
    edd_update_payment_meta($payment_id, '_edd_payment_user_id', $user_id);
    edd_update_payment_meta($payment_id, '_edd_payment_user_email', $email);
    edd_update_payment_meta($payment_id, '_edd_payment_meta', $meta);
    edd_update_payment_meta($payment_id, '_edd_payment_total', $total);
    edd_update_payment_meta($payment_id, '_edd_payment_downloads', $total);
    edd_update_payment_meta($payment_id, '_edd_payment_unlimited_downloads', $unlimited);
    do_action('edd_updated_edited_purchase', $payment_id);
    wp_safe_redirect(admin_url('edit.php?post_type=download&page=edd-payment-history&view=view-order-details&edd-message=payment-updated&id=' . $payment_id));
    exit;
}