#!/usr/bin/perl
use lib '/var/www/html/test-scb.impelsys.com/crons/affiliate_crons'; 
use AffiliateSystem;
use Class::Date;
use Date::Simple(':all');
use POSIX;
require 'db_config.pl';
require 'global_function_library.pl';
#####
#Author   : Arun V Yakkundi
#Date	   : 06th Nov 2009
#Desc	   : Purpose of this process is to create the order fact data 
###################

sub mailError
######
# Send mail only if any error is found
#
{
	my ($dbConn, $errorMsg) = @_;
	#$errorMsg = "processed for date range $ls_end_date";
	######
	# Send mail only if any error is found
	#
	if(length($errorMsg) gt 0) {
		$sqlTokens = "SELECT `key`, value FROM iplat_configurations WHERE category='iPublishCentral' AND configtype='REPORT_CRON_TOKEN'";
		$lhQuery = $dbConn->prepare($sqlTokens) or $errorMsg .= "Error:Preparing MYSQL query failed: $DBI::errstr $sqlTokens\n";
		$lhQuery->execute() or $errorMsg .= "Error:Preparing MYSQL query failed: $DBI::errstr\n";
		while (@results = $lhQuery->fetchrow_array()) {
		if($results[0] eq 'IPC_CRON_STATUS_MAIL_TO_IDS') {
		        @toMailIds = split(',' , $results[1]);
		        $mailToId = "";
		        $mailCcId = "";
		        foreach $mailId (@toMailIds) {
		        	if($mailToId eq "") {
		        		$mailToId = $mailId;
		        	}
			        else {
			        	if( $mailCcId eq "") {
			              		$mailCcId = $mailId;
            				}
				        	else {
				        		$mailCcId = $mailCcId . "," . $mailId;
				        	}
				}
		        } # end of for loop
      	}
      	elsif($results[0] eq 'IPC_CRON_ADMIN_MAIL_IDS') {
        	$mailFromId = $results[1];
      	}
      	elsif($results[0] eq 'IPC_CRON_MAIL_BODY_TEMPALTE') {
        	$mailBodyTemplate = $results[1];
      	}
      	elsif($results[0] eq 'IPC_CRON_MAIL_SUBJECT_TEMPALTE') {
        	$mailSubjectTemplate = $results[1];
                $codePath = $ENV{PWD};
                if($codePath =~ m/sites\/(.*?)\//) {
                        $mailSubjectTemplate .= ",SiteCode:".$1."";
                }
      	}
      	else {
      		# All tokens will begin with { and end with }, if token is not above matched case then it will be a token
		@arrCronTokens[$tokenIndex] = $results[0];
        	$tokenIndex++;
      	}
    	}

	$mailSubjectTemplate = parseToken($mailSubjectTemplate,$errorMsg, @arrCronTokens);
    	$mailBodyTemplate = parseToken($mailBodyTemplate,$errorMsg, @arrCronTokens);
    	my %arrMailCredentials = ();
    	$arrMailCredentials{"mailFrom"} = $mailFromId;
    	$arrMailCredentials{"mailTo"} = $mailToId;
    	$arrMailCredentials{"mailReply"} = $mailFromId;
    	$arrMailCredentials{"mailCc"} = $mailCcId;
    	$arrMailCredentials{"mailBcc"} = "";
    	$arrMailCredentials{"mailSubject"}= $mailSubjectTemplate;
    	$arrMailCredentials{"mailHtmlBody"} = $mailBodyTemplate;
    	$arrMailCredentials{"mailPlainBody"} = "";
    	$arrMailCredentials{"mailAttachment"} = "";
    	sendAlertMail(%arrMailCredentials);
  	}
	######
	return 1;	
}




# Variables used in the error handling & reporting by mail
	my $errorMsg = "";
	my $mailToId = "";
	my $mailCcId = "";
	my $mailFromId = "";
	my $mailSubjectTemplate = "";
	my $mailBodyTemplate = "";
	my @arrCronTokens = ();
	my $tokenIndex = 0;
	my $queryResult = 0;
	my $sqlDelete = "";
####  
	my $sql;
	my $rowsAffected;
	my $today = "";
	my $objAffiliate;

	($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
	my $startTime  = time();

	$rowsAffected = 0;
	$sql = "";
       	$isArchivedData = 1;
   	$codePath = $ENV{PWD};
	$sideCode = "";
	if($codePath =~ m/sites\/(.*?)\//) {
		$siteCode = $1;
	}


        if(!defined($ARGV[0])){
          $parseStartDate = today();
          $parseStartDate = $parseStartDate-1;
          $parseEndDate = $parseStartDate;
        }else{
          if($#ARGV == 0){
            $parseStartDate = Date::Simple->new($ARGV[0]);
            # if invalid date halt
            if(!defined($parseStartDate)){
            die "\nPlease input vaild dates in specified format\nusage: perl <program.pl> YYYY-MM-DD YYYY-MM-DD\n";
            }
            $parseEndDate = $parseStartDate;
           }

          if($#ARGV == 1){
            $parseStartDate = Date::Simple->new($ARGV[0]);
            $parseEndDate   = Date::Simple->new($ARGV[1]);
            # if invalid date halt
            if(!defined($parseStartDate)){
                die "\nPlease input vaild dates in specified format\nusage: perl <program.pl> YYYY-MM-DD YYYY-MM-DD\n";
            }
            # if invalid date halt
            if(!defined($parseEndDate)){
                die "\nPlease input vaild dates in specified format\nusage: perl <program.pl> YYYY-MM-DD YYYY-MM-DD\n";
            }

            if($parseStartDate > $parseEndDate){
                $tmpDate        = $parseStartDate;
                $parseStartDate = $parseEndDate;
                $parseEndDate   = $tmpDate;
            }
        }#if($#ARGV == 1)
 
     } #else close




       printf "\nStarted the ETL for Affiliate Reports (%4d-%02d-%02d %02d:%02d:%02d)\n",$year+1900,$mon+1,$mday,$hour,$min,$sec;

     $parseStartDate = Date::Simple->new('2010-03-15');
     $parseEndDate   = Date::Simple->new('2010-03-15');


	$objAffiliate = new AffiliateSystem($eupConnection, $sideCode, $parseStartDate, $parseEndDate);

	$errorMsg = $objAffiliate->generateDimensionCurrency();
        if(length($errorMsg) gt 0) {
                mailError($eupConnection,$errorMsg);
               die();
        }
        $errorMsg = $objAffiliate->generateDimensionSite();
        if(length($errorMsg) gt 0) {
                mailError($eupConnection,$errorMsg);
               die();
        }
        $errorMsg = $objAffiliate->generateDimensionPublisher();
        if(length($errorMsg) gt 0) {
                mailError($eupConnection,$errorMsg);
               die();
        }

  	 $errorMsg = $objAffiliate->generateDimensionAccessDate($parseStartDate, $parseEndDate);
        if(length($errorMsg) gt 0) {
                mailError($eupConnection,$errorMsg);
		die();
        }

        $errorMsg = $objAffiliate->generateDimensionAffProgramAction($ipcConnection);
        if(length($errorMsg) gt 0) {
                mailError($eupConnection,$errorMsg);
               die();
        }

        $errorMsg = $objAffiliate->generateDimensionAffProgram();
        if(length($errorMsg) gt 0) {
                mailError($eupConnection,$errorMsg);
               die();
        }

        $errorMsg = $objAffiliate->generateDimensionAffProgramLink();
        if(length($errorMsg) gt 0) {
                mailError($eupConnection,$errorMsg);
               die();
        }

        $errorMsg = $objAffiliate->generateDimensionAffProfile($affConnection);
        if(length($errorMsg) gt 0) {
                mailError($eupConnection,$errorMsg);
		die();
        }

	$errorMsg = $objAffiliate->generateDimensionAffVisitor();
        if(length($errorMsg) gt 0) {
                mailError($eupConnection,$errorMsg);
		die();
        }
      
        $errorMsg = $objAffiliate->generateDimensionAffCampaigns();
        if(length($errorMsg) gt 0) {
                mailError($eupConnection,$errorMsg);
               die();
        }

     

       ########
	# Affiliate Click reports process
	########
        $errorMsg = $objAffiliate->generateVisitorFact($parseStartDate,$parseEndDate);
        if(length($errorMsg) gt 0) {
             mailError($eupConnection,$errorMsg);
             die();
        }      


       $errorMsg = $objAffiliate->calculateAffCommission();
       if(length($errorMsg) gt 0) {
            mailError($eupConnection,$errorMsg);
            die();
       }
    
       $errorMsg = $objAffiliate->generateDimensionCommDeclineReason();
       if(length($errorMsg) gt 0) {
            mailError($eupConnection,$errorMsg);
            die();
       }

	$errorMsg = $objAffiliate->processAffiliateOrders($parseStartDate, $parseEndDate);
	if(length($errorMsg) gt 0) {
		mailError($eupConnection,$errorMsg);
                die();
	}


       


        $errorMsg = $objAffiliate->WhSummaryAffProgOrderDate($parseStartDate, $parseEndDate,$isArchivedData);
        if(length($errorMsg) gt 0) {
                mailError($eupConnection,$errorMsg);
                die();
        }



        $errorMsg = $objAffiliate->WhSummaryAffProgDate($parseStartDate, $parseEndDate,$isArchivedData);
        if(length($errorMsg) gt 0) {
                mailError($eupConnection,$errorMsg);
                die();
        }

       
        $errorMsg = $objAffiliate->WhSummaryAffCampDate($parseStartDate, $parseEndDate,$isArchivedData);
        if(length($errorMsg) gt 0) {
                mailError($eupConnection,$errorMsg);
                die();
        }

        $errorMsg = $objAffiliate->WhSummaryAffDate($parseStartDate, $parseEndDate,$isArchivedData);
        if(length($errorMsg) gt 0) {
                mailError($eupConnection,$errorMsg);
                die();
        }

     

        $errorMsg = $objAffiliate->WhSummaryAffProgMonth($parseStartDate, $parseEndDate,$isArchivedData);
        if(length($errorMsg) gt 0) {
                mailError($eupConnection,$errorMsg);
                die();
        }

      

        $errorMsg = $objAffiliate->WhSummaryAffCampMonth($parseStartDate, $parseEndDate,$isArchivedData);
        if(length($errorMsg) gt 0) {
             mailError($eupConnection,$errorMsg);
             die();
        }



	

	#######
	# Pushing the summary data to affiliate db
	#######
        $dateOfRun =  today()-1;
   
        $errorMsg = $objAffiliate->pushwhSummaryAffCampaignDate($affConnection,$dateOfRun);
        if(length($errorMsg) gt 0) {
             mailError($eupConnection,$errorMsg);
             die();
        }

        $errorMsg = $objAffiliate->pushwhSummaryAffProgmDate($affConnection,$dateOfRun);
        if(length($errorMsg) gt 0) {
             mailError($eupConnection,$errorMsg);
             die();
        }

        $errorMsg = $objAffiliate->pushwhSummaryAffCampaignMonth($affConnection,$dateOfRun);
        if(length($errorMsg) gt 0) {
            mailError($eupConnection,$errorMsg);
            die();
        }

        $errorMsg = $objAffiliate->pushwhSummaryAffProgmMonth($affConnection,$dateOfRun);
        if(length($errorMsg) gt 0) {
            mailError($eupConnection,$errorMsg);
            die();
        }




       

    ######
    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
    my $timeDiff = time() - $startTime ;
    my $difMin = int($timeDiff / 60);
    my $diffSec = sprintf("%02d", $timeDiff - 60 * $difMin);
    printf "\nEnd of ETL for warehousing of orders End Time:%4d-%02d-%02d %02d:%02d:%02d [%2d\:%02d]\n",$year+1900,$mon+1,$mday,$hour,$min,$sec,$difMin,$diffSec;
    $eupConnection->disconnect();
    $eupConnection->disconnect();
    $eupConnection->disconnect();
