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