#!/usr/bin/perl 
#

# We created a new column in the file table to hold the unaggragated count of price exceptions.
# Now we need to populate the value for all of the files in the current period.
#

use strict;

UpdateRemainingPriceExceptions->start();

package UpdateRemainingPriceExceptions;

use lib '/app/tools/common/lib';
use lib '/app/tools/bookpub/lib';
use BookPub::DB::Item::Sale;
use BookPub::DB::Item::File;

use base 'BookPub::CronScript';

sub _process {
    my $self = shift;

    my $collection = BookPub::DB::Item::File->GetByPeriodID(0);
    while ( my $row = $collection->next ) {
        if ( $row->price_exceptions_unapproved > 0 ) {
            $self->_updateSQL($row);
        }
    }
}

sub _updateSQL {
    my $self = shift;
    my $file = shift;

    my $fileID = $file->file_id;
    my $count  = 0;

    my $sql =
"SELECT COUNT(*) as count FROM sale_price_exception LEFT JOIN sale USING (sale_id) WHERE sale.file_id = $fileID AND sale_price_exception.approved = 0";
    my $dbo = Common::RSApp::GetClientDB();

    my $sth = $dbo->DoCmd($sql);

    if ( defined $sth && $sth->rows > 0 ) {
        my $href = $sth->fetchrow_hashref();
        $count = $href->{count};
    }

    my $dbo = Common::RSApp::GetClientDB();
    my $sql = "UPDATE file SET remaining_price_exceptions = $count" . " WHERE file_id = $fileID";

    $dbo->DoCmd($sql);
}

1;
