Bug 30477: Add new UNIMARC installer translation files
[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
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 qw( get_template_and_user );
20 use CGI;
21 use C4::Context;
22 use C4::Reports qw( GetDelimiterChoices );
23 use C4::Output qw( output_html_with_http_headers );
24 use DateTime;
25 use Koha::DateUtils qw( dt_from_string output_pref );
26 use Text::CSV::Encoded;
27 use List::Util qw( any );
28
29 use Koha::Account::CreditTypes;
30 use Koha::Account::DebitTypes;
31
32 my $input            = CGI->new;
33 my $dbh              = C4::Context->dbh;
34
35 my ($template, $borrowernumber, $cookie) = get_template_and_user({
36     template_name => "reports/cash_register_stats.tt",
37     query => $input,
38     type => "intranet",
39     flagsrequired => {reports => '*'},
40 });
41
42 my $do_it            = $input->param('do_it');
43 my $output           = $input->param("output");
44 my $basename         = $input->param("basename");
45 my $transaction_type = $input->param("transaction_type") || 'ACT';
46 my $manager_branchcode       = $input->param("branch") || C4::Context->userenv->{'branch'};
47
48 $template->param(
49     do_it => $do_it,
50     CGIsepChoice => GetDelimiterChoices,
51 );
52
53 #Initialize date pickers to today
54 my $fromDate = dt_from_string;
55 my $toDate   = dt_from_string;
56
57 my @debit_types =
58   Koha::Account::DebitTypes->search()->as_list;
59 my @credit_types =
60   Koha::Account::CreditTypes->search()->as_list;
61 my $registerid;
62
63 if ($do_it) {
64
65     $fromDate = output_pref({ dt => eval { dt_from_string(scalar $input->param("from")) } || dt_from_string,
66             dateformat => 'sql', dateonly => 1 }); #for sql query
67     $toDate   = output_pref({ dt => eval { dt_from_string(scalar $input->param("to")) } || dt_from_string,
68             dateformat => 'sql', dateonly => 1 }); #for sql query
69
70     my $whereTType = q{};
71     my @extra_params; # if we add conditions to the select we need extra params
72
73     if ($transaction_type eq 'ALL') { #All Transactons
74         $whereTType = q{};
75     } elsif ($transaction_type eq 'ACT') { #Active
76         $whereTType = q{ AND credit_type_code IN ('PAYMENT','CREDIT') };
77     } elsif ($transaction_type eq 'FORW') {
78         $whereTType = q{ AND credit_type_code IN ('FORGIVEN','WRITEOFF') };
79     } else {
80         if ( any { $transaction_type eq $_->code } @debit_types ) {
81             $whereTType = q{ AND debit_type_code = ? };
82             push @extra_params, $transaction_type;
83         } else {
84             $whereTType = q{ AND credit_type_code = ? };
85             push @extra_params, $transaction_type;
86         }
87     }
88
89     my $whereBranchCode = q{};
90     if ($manager_branchcode ne 'ALL') {
91         $whereBranchCode = q{ AND m.branchcode = ?};
92         push @extra_params, $manager_branchcode;
93     }
94
95     my $whereRegister = q{};
96     $registerid = $input->param("registerid");
97     if ($registerid) {
98         $whereRegister = q{ AND al.register_id = ?};
99         push @extra_params, $registerid;
100     }
101
102     my $query = "
103     SELECT round(amount,2) AS amount, al.description,
104         bo.surname AS bsurname, bo.firstname AS bfirstname, m.surname AS msurname, m.firstname AS mfirstname,
105         bo.cardnumber, br.branchname, bo.borrowernumber,
106         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,
107         bi.title, bi.biblionumber, i.barcode, i.itype
108         FROM accountlines al
109         LEFT JOIN borrowers bo ON (al.borrowernumber = bo.borrowernumber)
110         LEFT JOIN borrowers m ON (al.manager_id = m.borrowernumber)
111         LEFT JOIN branches br ON (br.branchcode = m.branchcode )
112         LEFT JOIN items i ON (i.itemnumber = al.itemnumber)
113         LEFT JOIN biblio bi ON (bi.biblionumber = i.biblionumber)
114         LEFT JOIN account_credit_types act ON (al.credit_type_code = act.code)
115         LEFT JOIN account_debit_types adt ON (al.debit_type_code = adt.code)
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->{type_description},
170                         $row->{note},
171                         $row->{amount},
172                         $row->{title},
173                         $row->{barcode},
174                         $row->{itype};
175                     push (@rows, \@rowValues) ;
176                 }
177                 my @total;
178                 for (1..7){push(@total,"")};
179                 push(@total, $grantotal);
180         print $input->header(
181             -type       => 'text/csv',
182             -encoding    => 'utf-8',
183             -attachment => $reportfilename,
184             -name       => $reportfilename
185          );
186         my $csvTemplate = C4::Templates::gettemplate('reports/csv/cash_register_stats.tt', 'intranet', $input);
187             $csvTemplate->param(sep => $delimiter, rows => \@rows, total => \@total );
188         print $csvTemplate->output;
189         exit;
190     }
191
192 }
193
194 $template->param(
195     beginDate        => $fromDate,
196     endDate          => $toDate,
197     transaction_type => $transaction_type,
198     branchloop       => Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed,
199     debit_types      => \@debit_types,
200     credit_types     => \@credit_types,
201     registerid       => $registerid,
202     CGIsepChoice => GetDelimiterChoices,
203 );
204
205 output_html_with_http_headers $input, $cookie, $template->output;
206
207 1;