Translation updates for Koha 23.05.00
[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 );
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 = $input->param("from") || dt_from_string;
55 my $toDate   = $input->param("to")   || 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
66     my $whereTType = q{};
67     my @extra_params; # if we add conditions to the select we need extra params
68
69     if ($transaction_type eq 'ALL') { #All Transactons
70         $whereTType = q{};
71     } elsif ($transaction_type eq 'ACT') { #Active
72         $whereTType = q{ AND credit_type_code IN ('PAYMENT','CREDIT') };
73     } elsif ($transaction_type eq 'FORW') {
74         $whereTType = q{ AND credit_type_code IN ('FORGIVEN','WRITEOFF') };
75     } else {
76         if ( any { $transaction_type eq $_->code } @debit_types ) {
77             $whereTType = q{ AND debit_type_code = ? };
78             push @extra_params, $transaction_type;
79         } else {
80             $whereTType = q{ AND credit_type_code = ? };
81             push @extra_params, $transaction_type;
82         }
83     }
84
85     my $whereBranchCode = q{};
86     if ($manager_branchcode ne 'ALL') {
87         $whereBranchCode = q{ AND m.branchcode = ?};
88         push @extra_params, $manager_branchcode;
89     }
90
91     my $whereRegister = q{};
92     $registerid = $input->param("registerid");
93     if ($registerid) {
94         $whereRegister = q{ AND al.register_id = ?};
95         push @extra_params, $registerid;
96     }
97
98     my $query = "
99     SELECT round(amount,2) AS amount, al.description,
100         bo.surname AS bsurname, bo.firstname AS bfirstname, m.surname AS msurname, m.firstname AS mfirstname,
101         bo.cardnumber, br.branchname, bo.borrowernumber,
102         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,
103         bi.title, bi.biblionumber, i.barcode, i.itype
104         FROM accountlines al
105         LEFT JOIN borrowers bo ON (al.borrowernumber = bo.borrowernumber)
106         LEFT JOIN borrowers m ON (al.manager_id = m.borrowernumber)
107         LEFT JOIN cash_registers cr ON (al.register_id = cr.id)
108         LEFT JOIN branches br ON (br.branchcode = cr.branch)
109         LEFT JOIN items i ON (i.itemnumber = al.itemnumber)
110         LEFT JOIN biblio bi ON (bi.biblionumber = i.biblionumber)
111         LEFT JOIN account_credit_types act ON (al.credit_type_code = act.code)
112         LEFT JOIN account_debit_types adt ON (al.debit_type_code = adt.code)
113         WHERE CAST(al.date AS DATE) BETWEEN ? AND ?
114         $whereTType
115         $whereBranchCode
116         $whereRegister
117         ORDER BY al.date
118     ";
119     my $sth_stats = $dbh->prepare($query) or die "Unable to prepare query " . $dbh->errstr;
120     $sth_stats->execute($fromDate, $toDate, @extra_params) or die "Unable to execute query " . $sth_stats->errstr;
121
122     my @loopresult;
123     my $grantotal = 0;
124     while ( my $row = $sth_stats->fetchrow_hashref()) {
125         $row->{amountoutstanding} = 0 if (!$row->{amountoutstanding});
126         #if ((abs($row->{amount}) - $row->{amountoutstanding}) > 0) {
127             $row->{amount} = sprintf("%.2f", abs ($row->{amount}));
128             $row->{date} = dt_from_string($row->{date}, 'sql');
129
130             push (@loopresult, $row);
131             if($transaction_type eq 'ACT' && ($row->{credit_type_code} !~ /^CREDIT$|^PAYMENT$/)){
132                 pop @loopresult;
133                 next;
134             }
135             if($row->{credit_type_code} =~ /^CREDIT$/){
136                 $grantotal -= abs($row->{amount});
137                 $row->{amount} = '-' . $row->{amount};
138             }elsif($row->{credit_type_code} eq 'FORGIVEN' || $row->{credit_type_code} eq 'WRITEOFF'){
139             }else{
140                 $grantotal += abs($row->{amount});
141             }
142         #}
143     }
144
145     $grantotal = sprintf("%.2f", $grantotal);
146
147     if($output eq 'screen'){
148         $template->param(
149             loopresult => \@loopresult,
150             total => $grantotal,
151         );
152     } else{
153         my $format = 'csv';
154         my $reportname = $input->param('basename');
155         my $reportfilename = $reportname ? "$reportname.$format" : "reportresults.$format" ;
156         my $delimiter = C4::Context->csv_delimiter;
157             my @rows;
158             foreach my $row (@loopresult) {
159                 my @rowValues;
160                 push @rowValues, $row->{mfirstname}. ' ' . $row->{msurname},
161                         $row->{cardnumber},
162                         $row->{bfirstname} . ' ' . $row->{bsurname},
163                         $row->{branchname},
164                         $row->{date},
165                         $row->{timestamp},
166                         $row->{type_description},
167                         $row->{note},
168                         $row->{amount},
169                         $row->{title},
170                         $row->{barcode},
171                         $row->{itype};
172                     push (@rows, \@rowValues) ;
173                 }
174                 my @total;
175                 for (1..7){push(@total,"")};
176                 push(@total, $grantotal);
177         print $input->header(
178             -type       => 'text/csv',
179             -encoding    => 'utf-8',
180             -attachment => $reportfilename,
181             -name       => $reportfilename
182          );
183         my $csvTemplate = C4::Templates::gettemplate('reports/csv/cash_register_stats.tt', 'intranet', $input);
184             $csvTemplate->param(sep => $delimiter, rows => \@rows, total => \@total );
185         print $csvTemplate->output;
186         exit;
187     }
188
189 }
190
191 $template->param(
192     beginDate        => $fromDate,
193     endDate          => $toDate,
194     transaction_type => $transaction_type,
195     branchloop       => Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed,
196     debit_types      => \@debit_types,
197     credit_types     => \@credit_types,
198     registerid       => $registerid,
199     CGIsepChoice => GetDelimiterChoices,
200 );
201
202 output_html_with_http_headers $input, $cookie, $template->output;
203
204 1;