#------------------------------------------------------------
# Copyright (C) 2009 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package BookPub::DB::Item::POSSaleUnits;
use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::Assert;
use Common::Client;
use Common::DB::Item::OnixCode;
use base 'Common::DB::Item';

use constant kTable => 'pos_sale';
use constant kDB    => Common::DB::Item::kClientDB;

sub _GenerateClassConfig {
    my ($class) = @_;

    my $config = {};

    $config->{service_id} = { _readOnly => 1 };
    $config->{date}       = { _readOnly => 1 };
    $config->{units}      = { _readOnly => 1 };

    return $config;
}

sub ReportQuery {
    my ( $class, $productID, $serviceID, $dateStart, $dateEnd ) = @_;
    assert($productID);
    assert($serviceID);
    assert($dateStart);
    assert($dateEnd);

    # productID can be either a single id, or a reference to an array of ids.
    # We'll convert the single ID to an array of one
    #
    my @quotedProductIDs;
    if ( 'ARRAY' ne ref($productID) ) {
        push @quotedProductIDs, $class->quote($productID);
    } else {
        foreach my $id (@$productID) {
            push @quotedProductIDs, $class->quote($id);
        }
    }
    my $productIDString = join( ',', @quotedProductIDs );

    # JPK - Using 'date_end' as the cannonical date for sale...
    #
    my $sql =
        "SELECT pos_file.service_id AS service_id, pos_sale.date_end AS date, SUM(pos_sale.units) AS units"
      . " FROM pos_sale, pos_file"
      . " WHERE pos_sale.pos_file_id = pos_file.pos_file_id"
      . " AND product_id IN ( $productIDString )"
      . " AND pos_file.service_id=$serviceID"
      . " AND pos_sale.date_end >= "
      . $class->quote($dateStart)
      . " AND pos_sale.date_end <= "
      . $class->quote($dateEnd)
      . " GROUP BY 2 ORDER BY 2";

    return $class->GetAll($sql);
}

1;
