Bug 28772: (QA follow-up) Apply change to other dbrev too [STABLE]
[koha.git] / reports / cash_register_stats.pl
1 #!/usr/bin/perl
2 #
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation;
8 #
9 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
10 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
11 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with Koha; if not, write to the Free Software Foundation, Inc.,
15 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
16
17 use Modern::Perl;
18 use C4::Auth;
19 use CGI;
20 use C4::Context;
21 use C4::Reports;
22 use C4::Output;
23 use C4::Koha;
24 use C4::Circulation;
25 use DateTime;
26 use Koha::DateUtils;
27 use Text::CSV::Encoded;
28 use List::Util qw/any/;
29
30 use Koha::Account::CreditTypes;
31 use Koha::Account::DebitTypes;
32
33 my $input            = new CGI;
34 my $dbh              = C4::Context->dbh;
35
36 my ($template, $borrowernumber, $cookie) = get_template_and_user({
37     template_name => "reports/cash_register_stats.tt",
38     query => $input,
39     type => "intranet",
40     flagsrequired => {reports => '*'},
41     debug => 1,
42 });
43
44 my $do_it            = $input->param('do_it');
45 my $output           = $input->param("output");
46 my $basename         = $input->param("basename");
47 my $transaction_type = $input->param("transaction_type") || 'ACT';
48 my $manager_branchcode       = $input->param("branch") || C4::Context->userenv->{'branch'};
49
50 $template->param(
51     do_it => $do_it,
52     CGIsepChoice => GetDelimiterChoices,
53 );
54
55 #Initialize date pickers to today
56 my $fromDate = dt_from_string;
57 my $toDate   = dt_from_string;
58
59 my @debit_types =
60   Koha::Account::DebitTypes->search()->as_list;
61 my @credit_types =
62   Koha::Account::CreditTypes->search()->as_list;
63
64 if ($do_it) {
65
66     $fromDate = output_pref({ dt => eval { dt_from_string(scalar $input->param("from")) } || dt_from_string,
67             dateformat => 'sql', dateonly => 1 }); #for sql query
68     $toDate   = output_pref({ dt => eval { dt_from_string(scalar $input->param("to")) } || dt_from_string,
69             dateformat => 'sql', dateonly => 1 }); #for sql query
70
71     my $whereTType = q{};
72     my @extra_params; # if we add conditions to the select we need extra params
73
74     if ($transaction_type eq 'ALL') { #All Transactons
75         $whereTType = q{};
76     } elsif ($transaction_type eq 'ACT') { #Active
77         $whereTType = q{ AND credit_type_code IN ('PAYMENT','CREDIT') };
78     } elsif ($transaction_type eq 'FORW') {
79         $whereTType = q{ AND credit_type_code IN ('FORGIVEN','WRITEOFF') };
80     } else {
81         if ( any { $transaction_type eq $_->code } @debit_types ) {
82             $whereTType = q{ AND debit_type_code = ? };
83             push @extra_params, $transaction_type;
84         } else {
85             $whereTType = q{ AND credit_type_code = ? };
86             push @extra_params, $transaction_type;
87         }
88     }
89
90     my $whereBranchCode = q{};
91     if ($manager_branchcode ne 'ALL') {
92         $whereBranchCode = q{ AND m.branchcode = ?};
93         push @extra_params, $manager_branchcode;
94     }
95
96
97     my $query = "
98     SELECT round(amount,2) AS amount, description,
99         bo.surname AS bsurname, bo.firstname AS bfirstname, m.surname AS msurname, m.firstname AS mfirstname,
100         bo.cardnumber, br.branchname, bo.borrowernumber,
101         al.borrowernumber, DATE(al.date) as date, al.credit_type_code, al.debit_type_code, al.amountoutstanding, al.note,
102         bi.title, bi.biblionumber, i.barcode, i.itype
103         FROM accountlines al
104         LEFT JOIN borrowers bo ON (al.borrowernumber = bo.borrowernumber)
105         LEFT JOIN borrowers m ON (al.manager_id = m.borrowernumber)
106         LEFT JOIN branches br ON (br.branchcode = m.branchcode )
107         LEFT JOIN items i ON (i.itemnumber = al.itemnumber)
108         LEFT JOIN biblio bi ON (bi.biblionumber = i.biblionumber)
109         WHERE CAST(al.date AS DATE) BETWEEN ? AND ?
110         $whereTType
111         $whereBranchCode
112         ORDER BY al.date
113     ";
114     my $sth_stats = $dbh->prepare($query) or die "Unable to prepare query " . $dbh->errstr;
115     $sth_stats->execute($fromDate, $toDate, @extra_params) or die "Unable to execute query " . $sth_stats->errstr;
116
117     my @loopresult;
118     my $grantotal = 0;
119     while ( my $row = $sth_stats->fetchrow_hashref()) {
120         $row->{amountoutstanding} = 0 if (!$row->{amountoutstanding});
121         #if ((abs($row->{amount}) - $row->{amountoutstanding}) > 0) {
122             $row->{amount} = sprintf("%.2f", abs ($row->{amount}));
123             $row->{date} = dt_from_string($row->{date}, 'sql');
124
125             push (@loopresult, $row);
126             if($transaction_type eq 'ACT' && ($row->{credit_type_code} !~ /^CREDIT$|^PAYMENT$/)){
127                 pop @loopresult;
128                 next;
129             }
130             if($row->{credit_type_code} =~ /^CREDIT$/){
131                 $grantotal -= abs($row->{amount});
132                 $row->{amount} = '-' . $row->{amount};
133             }elsif($row->{credit_type_code} eq 'FORGIVEN' || $row->{credit_type_code} eq 'WRITEOFF'){
134             }else{
135                 $grantotal += abs($row->{amount});
136             }
137         #}
138     }
139
140     $grantotal = sprintf("%.2f", $grantotal);
141
142     if($output eq 'screen'){
143         $template->param(
144             loopresult => \@loopresult,
145             total => $grantotal,
146         );
147     } else{
148         my $format = 'csv';
149         my $reportname = $input->param('basename');
150         my $reportfilename = $reportname ? "$reportname.$format" : "reportresults.$format" ;
151         my $delimiter = C4::Context->preference('delimiter') || ',';
152             my @rows;
153             foreach my $row (@loopresult) {
154                 my @rowValues;
155                 push @rowValues, $row->{mfirstname}. ' ' . $row->{msurname},
156                         $row->{cardnumber},
157                         $row->{bfirstname} . ' ' . $row->{bsurname},
158                         $row->{branchname},
159                         $row->{date},
160                         $row->{credit_type},
161                         $row->{debit_type},
162                         $row->{note},
163                         $row->{amount},
164                         $row->{title},
165                         $row->{barcode},
166                         $row->{itype};
167                     push (@rows, \@rowValues) ;
168                 }
169                 my @total;
170                 for (1..6){push(@total,"")};
171                 push(@total, $grantotal);
172         print $input->header(
173             -type       => 'text/csv',
174             -encoding    => 'utf-8',
175             -attachment => $reportfilename,
176             -name       => $reportfilename
177          );
178         my $csvTemplate = C4::Templates::gettemplate('reports/csv/cash_register_stats.tt', 'intranet', $input);
179             $csvTemplate->param(sep => $delimiter, rows => \@rows, total => \@total );
180         print $csvTemplate->output;
181         exit;
182     }
183
184 }
185
186 $template->param(
187     beginDate        => $fromDate,
188     endDate          => $toDate,
189     transaction_type => $transaction_type,
190     branchloop       => Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed,
191     debit_types      => \@debit_types,
192     credit_types     => \@credit_types,
193     CGIsepChoice => GetDelimiterChoices,
194 );
195
196 output_html_with_http_headers $input, $cookie, $template->output;
197
198 1;