#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package BookPub::Price::Command::ApproveAll;
use strict;
use warnings;

use lib '/app/tools/bookpub/lib';
use lib '/app/tools/common/lib';
use RSApache::Response::XSLT;
use Common::Preference;
use Common::Assert;

use BookPub::DB::Item::File;
use BookPub::DB::Item::SalePriceException;
use BookPub::Price::SalePriceExceptionRule;

use base 'BookPub::Command';

sub cmd      { return 'approve_all'; }
sub area     { return 'price'; }
sub pageName { return 'Approve All Price Exceptions'; }

use constant kTemplate => "/app/tools/bookpub/templates/price/exceptions.xsl";

sub execute {
    my ($self) = @_;

    # Give any inherited methods the first crack at this.
    # (This checks for login and basic access permissions).
    #
    my $response = $self->SUPER::execute();
    return $response if $response;

    my $fileID    = $self->getParam('File');
    my $serviceID = $self->getParam('Service');
    die "Error - Missing file or service parameter" unless ( $fileID || $serviceID );

    my $trackerPageParam = $self->getParam('trackerPage');
    my $pageParam        = $self->getParam('Page');

    # Let's approve all the exceptions, update the counts in the file table,
    # and then redirect back to the page we came from.

    my $exceptions;

    if ($fileID) {
        $exceptions = BookPub::DB::Item::SalePriceException->GetUnapprovedByFileID($fileID);
    } else {
        $exceptions = BookPub::DB::Item::SalePriceException->GetUnapprovedByServiceID($serviceID);
    }

    # Okay, start approving these exceptions.
    while ( my $exception = $exceptions->next() ) {
        $exception->approved(1);
        $exception->save();

        my $obj = BookPub::Price::SalePriceExceptionRule->new( saleID => $exception->sale_id );
        $obj->save() if ($obj);
    }

    # Now update the counts in the file table.
    if ($fileID) {
        BookPub::DB::Item::File->updatePriceValidationCounts( file_id => $fileID );
    } else {
        BookPub::DB::Item::File->updatePriceValidationCounts( service_id => $serviceID );
    }

    # Back to where we came from.
    return RSApache::Response::Redirect->new( "/bookpub/"
          . $self->area()
          . "?File="
          . $fileID
          . "&Service="
          . $serviceID
          . "&Page="
          . $pageParam
          . "&trackerPage=$trackerPageParam&ExceptionsApproved=ALL" );

}

1;
