Bug 31051: Fix test
[koha-ffzg.git] / reports / cash_register_stats.pl
index bd9aa0f..c2b22f9 100755 (executable)
@@ -2,52 +2,48 @@
 #
 # This file is part of Koha.
 #
-# Koha is free software; you can redistribute it and/or modify it under the
-# terms of the GNU General Public License as published by the Free Software
-# Foundation;
+# Koha is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
 #
-# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
-# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+# Koha is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
 #
-# You should have received a copy of the GNU General Public License along
-# with Koha; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# You should have received a copy of the GNU General Public License
+# along with Koha; if not, see <http://www.gnu.org/licenses>.
 
 use Modern::Perl;
-use C4::Auth;
+use C4::Auth qw( get_template_and_user );
 use CGI;
 use C4::Context;
-use C4::Reports;
-use C4::Output;
-use C4::Koha;
-use C4::Circulation;
+use C4::Reports qw( GetDelimiterChoices );
+use C4::Output qw( output_html_with_http_headers );
 use DateTime;
-use Koha::DateUtils;
-use C4::Budgets qw/GetCurrency GetCurrencies/;
-#use Data::Dumper;
-#use Smart::Comments;
+use Koha::DateUtils qw( dt_from_string );
+use Text::CSV::Encoded;
+use List::Util qw( any );
 
-my $input            = new CGI;
+use Koha::Account::CreditTypes;
+use Koha::Account::DebitTypes;
+
+my $input            = CGI->new;
 my $dbh              = C4::Context->dbh;
-my $fullreportname   = "reports/cash_register_stats.tt";
 
 my ($template, $borrowernumber, $cookie) = get_template_and_user({
-    template_name => $fullreportname,
+    template_name => "reports/cash_register_stats.tt",
     query => $input,
     type => "intranet",
-    authnotrequired => 0,
     flagsrequired => {reports => '*'},
-    debug => 1,
 });
 
 my $do_it            = $input->param('do_it');
 my $output           = $input->param("output");
 my $basename         = $input->param("basename");
 my $transaction_type = $input->param("transaction_type") || 'ACT';
-my $branchcode       = $input->param("branch") || C4::Context->userenv->{'branch'};
-our $sep = $input->param("sep") // ',';
-$sep = "\t" if ($sep eq 'tabulation');
+my $manager_branchcode       = $input->param("branch") || C4::Context->userenv->{'branch'};
 
 $template->param(
     do_it => $do_it,
@@ -55,64 +51,73 @@ $template->param(
 );
 
 #Initialize date pickers to today
-my $fromDate = dt_from_string;
-my $toDate   = dt_from_string;
-### fromdate today: $fromDate
-
-my $query_manualinv = "SELECT id, authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'";
-my $sth_manualinv = $dbh->prepare($query_manualinv) or die "Unable to prepare query" . $dbh->errstr;
-$sth_manualinv->execute() or die "Unable to execute query " . $sth_manualinv->errstr;
-my $manualinv_types = $sth_manualinv->fetchall_arrayref({});
+my $fromDate = $input->param("from") || dt_from_string;
+my $toDate   = $input->param("to")   || dt_from_string;
 
-### $manualinv_types
+my @debit_types =
+  Koha::Account::DebitTypes->search()->as_list;
+my @credit_types =
+  Koha::Account::CreditTypes->search()->as_list;
+my $registerid;
 
 if ($do_it) {
 
-    $fromDate = output_pref({ dt => eval { dt_from_string($input->param("filter_date_begin")) } || dt_from_string,
-            dateformat => 'sql', dateonly => 1 }); #for sql query
-    $toDate   = output_pref({ dt => eval { dt_from_string($input->param("filter_date_end")) } || dt_from_string,
-            dateformat => 'sql', dateonly => 1 }); #for sql query
 
-    my $whereTType = '';
+    my $whereTType = q{};
+    my @extra_params; # if we add conditions to the select we need extra params
 
     if ($transaction_type eq 'ALL') { #All Transactons
-        $whereTType = '';
+        $whereTType = q{};
     } elsif ($transaction_type eq 'ACT') { #Active
-        $whereTType = " accounttype NOT IN ('F', 'FU', 'FOR', 'M', 'L') AND ";
-    } else { #Single transac type
-        if ($transaction_type eq 'FORW') {
-            $whereTType = " accounttype = 'FOR' OR accounttype = 'W' AND ";
+        $whereTType = q{ AND credit_type_code IN ('PAYMENT','CREDIT') };
+    } elsif ($transaction_type eq 'FORW') {
+        $whereTType = q{ AND credit_type_code IN ('FORGIVEN','WRITEOFF') };
+    } else {
+        if ( any { $transaction_type eq $_->code } @debit_types ) {
+            $whereTType = q{ AND debit_type_code = ? };
+            push @extra_params, $transaction_type;
         } else {
-            $whereTType = " accounttype = '$transaction_type' AND ";
+            $whereTType = q{ AND credit_type_code = ? };
+            push @extra_params, $transaction_type;
         }
     }
 
-    my $whereBranchCode = '';
-    if ($branchcode ne 'ALL') {
-        $whereBranchCode = "AND bo.branchcode = '$branchcode'";
+    my $whereBranchCode = q{};
+    if ($manager_branchcode ne 'ALL') {
+        $whereBranchCode = q{ AND m.branchcode = ?};
+        push @extra_params, $manager_branchcode;
     }
 
-    ### $transaction_type;
+    my $whereRegister = q{};
+    $registerid = $input->param("registerid");
+    if ($registerid) {
+        $whereRegister = q{ AND al.register_id = ?};
+        push @extra_params, $registerid;
+    }
 
     my $query = "
-    SELECT round(amount,2) AS amount, description,
+    SELECT round(amount,2) AS amount, al.description,
         bo.surname AS bsurname, bo.firstname AS bfirstname, m.surname AS msurname, m.firstname AS mfirstname,
         bo.cardnumber, br.branchname, bo.borrowernumber,
-        al.borrowernumber, DATE(al.date) as date, al.accounttype, al.amountoutstanding,
+        al.borrowernumber, DATE(al.date) as date, al.credit_type_code, al.debit_type_code, COALESCE(act.description,al.credit_type_code,adt.description,al.debit_type_code) AS type_description, al.amountoutstanding, al.note, al.timestamp,
         bi.title, bi.biblionumber, i.barcode, i.itype
         FROM accountlines al
         LEFT JOIN borrowers bo ON (al.borrowernumber = bo.borrowernumber)
         LEFT JOIN borrowers m ON (al.manager_id = m.borrowernumber)
-        LEFT JOIN branches br ON (br.branchcode = m.branchcode )
+        LEFT JOIN cash_registers cr ON (al.register_id = cr.id)
+        LEFT JOIN branches br ON (br.branchcode = cr.branch)
         LEFT JOIN items i ON (i.itemnumber = al.itemnumber)
         LEFT JOIN biblio bi ON (bi.biblionumber = i.biblionumber)
-        WHERE $whereTType
-        CAST(al.date AS DATE) BETWEEN ? AND ?
+        LEFT JOIN account_credit_types act ON (al.credit_type_code = act.code)
+        LEFT JOIN account_debit_types adt ON (al.debit_type_code = adt.code)
+        WHERE CAST(al.date AS DATE) BETWEEN ? AND ?
+        $whereTType
         $whereBranchCode
+        $whereRegister
         ORDER BY al.date
     ";
-    my $sth_stats = $dbh->prepare($query) or die "Unable to prepare query" . $dbh->errstr;
-    $sth_stats->execute($fromDate, $toDate) or die "Unable to execute query " . $sth_stats->errstr;
+    my $sth_stats = $dbh->prepare($query) or die "Unable to prepare query " . $dbh->errstr;
+    $sth_stats->execute($fromDate, $toDate, @extra_params) or die "Unable to execute query " . $sth_stats->errstr;
 
     my @loopresult;
     my $grantotal = 0;
@@ -121,14 +126,22 @@ if ($do_it) {
         #if ((abs($row->{amount}) - $row->{amountoutstanding}) > 0) {
             $row->{amount} = sprintf("%.2f", abs ($row->{amount}));
             $row->{date} = dt_from_string($row->{date}, 'sql');
-            ### date : $row->{date}
 
             push (@loopresult, $row);
-            $grantotal += abs($row->{amount});
+            if($transaction_type eq 'ACT' && ($row->{credit_type_code} !~ /^CREDIT$|^PAYMENT$/)){
+                pop @loopresult;
+                next;
+            }
+            if($row->{credit_type_code} =~ /^CREDIT$/){
+                $grantotal -= abs($row->{amount});
+                $row->{amount} = '-' . $row->{amount};
+            }elsif($row->{credit_type_code} eq 'FORGIVEN' || $row->{credit_type_code} eq 'WRITEOFF'){
+            }else{
+                $grantotal += abs($row->{amount});
+            }
         #}
     }
 
-    my @currency = GetCurrency();
     $grantotal = sprintf("%.2f", $grantotal);
 
     if($output eq 'screen'){
@@ -137,53 +150,52 @@ if ($do_it) {
             total => $grantotal,
         );
     } else{
-        binmode STDOUT, ':encoding(UTF-8)';
+        my $format = 'csv';
+        my $reportname = $input->param('basename');
+        my $reportfilename = $reportname ? "$reportname.$format" : "reportresults.$format" ;
+        my $delimiter = C4::Context->csv_delimiter;
+            my @rows;
+            foreach my $row (@loopresult) {
+                my @rowValues;
+                push @rowValues, $row->{mfirstname}. ' ' . $row->{msurname},
+                        $row->{cardnumber},
+                        $row->{bfirstname} . ' ' . $row->{bsurname},
+                        $row->{branchname},
+                        $row->{date},
+                        $row->{timestamp},
+                        $row->{type_description},
+                        $row->{note},
+                        $row->{amount},
+                        $row->{title},
+                        $row->{barcode},
+                        $row->{itype};
+                    push (@rows, \@rowValues) ;
+                }
+                my @total;
+                for (1..7){push(@total,"")};
+                push(@total, $grantotal);
         print $input->header(
-            -type => 'application/vnd.sun.xml.calc',
-            -encoding => 'utf-8',
-            -name => "$basename.csv",
-            -attachment => "$basename.csv"
-        );
-
-        print "Manager name".$sep;
-        print "Borrower cardnumber".$sep;
-        print "Borrower name".$sep;
-        print "Branch".$sep;
-        print "Transaction date".$sep;
-        print "Transaction type".$sep;
-        print "Amount".$sep;
-        print "Biblio title".$sep;
-        print "Barcode".$sep;
-        print "Document type"."\n";
-
-        foreach my $item (@loopresult){
-            print $item->{mfirstname}. ' ' . $item->{msurname} . $sep;
-            print $item->{cardnumber}.$sep;
-            print $item->{bfirstname}. ' ' . $item->{bsurname} . $sep;
-            print $item->{branchname}.$sep;
-            print $item->{date}.$sep;
-            print $item->{accounttype}.$sep;
-            print $item->{amount}.$sep;
-            print $item->{title}.$sep;
-            print $item->{barcode}.$sep;
-            print $item->{itype}."\n";
-        }
-
-        print $sep x 6;
-        print $grantotal."\n";
-        exit(1);
+            -type       => 'text/csv',
+            -encoding    => 'utf-8',
+            -attachment => $reportfilename,
+            -name       => $reportfilename
+         );
+        my $csvTemplate = C4::Templates::gettemplate('reports/csv/cash_register_stats.tt', 'intranet', $input);
+            $csvTemplate->param(sep => $delimiter, rows => \@rows, total => \@total );
+        print $csvTemplate->output;
+        exit;
     }
 
 }
 
-### fromdate final: $fromDate
-### toDate final: $toDate
 $template->param(
-    beginDate        => dt_from_string($fromDate),
-    endDate          => dt_from_string($toDate),
+    beginDate        => $fromDate,
+    endDate          => $toDate,
     transaction_type => $transaction_type,
-    branchloop       => C4::Branch::GetBranchesLoop($branchcode),
-    manualinv_types  => $manualinv_types,
+    branchloop       => Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed,
+    debit_types      => \@debit_types,
+    credit_types     => \@credit_types,
+    registerid       => $registerid,
     CGIsepChoice => GetDelimiterChoices,
 );