wp-e-commerce/WP-e-Commerce — pull request #620 by garyc40 (2013-08-26 14:40:11+00:00)
Title: Stats API for products and purchase logs

First pass at an API for products and purchase logs:

- I'm not writing a separate `WPSC_Stats` class. Since the only kind of object that we need to extract stats from are products, I think it might be cleaner to extend the product API (see below).

- `WPSC_Product` is a class I've already made for the new theme engine. I'm porting it over to WPEC core with some changes to accommodate stats API.

- `WPSC_Products` is a collection class, containing a bunch of `WPSC_Product` objects. Pass into it the same arguments as WP_Query. But note that this is not a query object.

- I only implemented `start` and `end` arguments for date time restriction of the collected stats. Any other more advanced and abstract date/time args can be translated back to `start` and `end` easily.

- The stats results are cached into each product's meta. If stats query include date ranges, these will be cached using WP Object Cache API (expire in 48 hours, can be changed by modifying a constant).

- Think of this pull request as a first pass, a draft, a proof of concept, or a blueprint. Please test thoroughly. I'm pretty sure there are little bugs, PHP warnings or notices. Make sure you test with products having variations as well. The stats should be a total of all child products' stats.

Here's how to use this stats API:

- Get overall stats of a product:

```php
$product = WPSC_Product::get_instance( $id );
echo 'Sales: ' . $product->sales . '. Earnings: ' . $product->earnings;
```

- Get overall stats of a collection of products (in this example, the whole store):

```php
$store = new WPSC_Products();
echo 'Sales: ' . $store->sales . '. Earnings: ' . $store->earnings;
```

- Get product stats from Jan 1st, 2013 to December 31st, 2013 (23:59:59), assuming UTC:

```php
$product = WPSC_Product::get_instance( $id );
$start = mktime( 0, 0, 0, 1, 1, 2013 ); // inclusive left bound
$end = mktime( 0, 0, 0, 1, 1, 2014 ); // exclusive right bound
$stats = $product->get_stats( array(
'start' => $start,
'end' => $end
);

echo 'Sales: ' . $stats['sales'] . '. Earnings: ' . $stats['earnings'];
```

- Get stats of a product collection during a date range: same as above, but use `WPSC_Products` instead.

The `get_stats()` functions let use specify "pagination" and "sort order". These are quite useless at the moment. I was intending to remove those arguments but then thought then might prove useful later when we reuse that code to fetch things like top 10 earnings products.

Again, this code is highly experimental. Needs moar testing! Comments and feedback are also welcome.