Bug 23064: Use Koha::Subscription in ModSubscription
[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
29 my $input            = new CGI;
30 my $dbh              = C4::Context->dbh;
31
32 my ($template, $borrowernumber, $cookie) = get_template_and_user({
33     template_name => "reports/cash_register_stats.tt",
34     query => $input,
35     type => "intranet",
36     authnotrequired => 0,
37     flagsrequired => {reports => '*'},
38     debug => 1,
39 });
40
41 my $do_it            = $input->param('do_it');
42 my $output           = $input->param("output");
43 my $basename         = $input->param("basename");
44 my $transaction_type = $input->param("transaction_type") || 'ACT';
45 my $manager_branchcode       = $input->param("branch") || C4::Context->userenv->{'branch'};
46
47 $template->param(
48     do_it => $do_it,
49     CGIsepChoice => GetDelimiterChoices,
50 );
51
52 #Initialize date pickers to today
53 my $fromDate = dt_from_string;
54 my $toDate   = dt_from_string;
55
56 my $query_manualinv = "SELECT id, authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'";
57 my $sth_manualinv = $dbh->prepare($query_manualinv) or die "Unable to prepare query" . $dbh->errstr;
58 $sth_manualinv->execute() or die "Unable to execute query " . $sth_manualinv->errstr;
59 my $manualinv_types = $sth_manualinv->fetchall_arrayref({});
60
61
62 if ($do_it) {
63
64     $fromDate = output_pref({ dt => eval { dt_from_string($input->param("from")) } || dt_from_string,
65             dateformat => 'sql', dateonly => 1 }); #for sql query
66     $toDate   = output_pref({ dt => eval { dt_from_string($input->param("to")) } || dt_from_string,
67             dateformat => 'sql', dateonly => 1 }); #for sql query
68
69     my $whereTType = q{};
70     my @extra_params; # if we add conditions to the select we need extra params
71
72     if ($transaction_type eq 'ALL') { #All Transactons
73         $whereTType = q{};
74     } elsif ($transaction_type eq 'ACT') { #Active
75         $whereTType = q{ AND accounttype IN ('Pay','C') };
76     } else { #Single transac type
77         if ($transaction_type eq 'FORW') {
78             $whereTType = q{ AND accounttype IN ('FOR','W') };
79         } elsif ( $transaction_type eq 'OVERDUEA' ) {
80             $whereTType = q{ AND accounttype = 'OVERDUE' AND status = 'UNRETURNED' };
81         } elsif ( $transaction_type eq 'OVERDUE' ) {
82             $whereTType = q{ AND accounttype = 'OVERDUE' AND status != 'UNRETURNED' };
83         } else {
84             $whereTType = q{ AND accounttype = ? };
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
96     my $query = "
97     SELECT round(amount,2) AS amount, description,
98         bo.surname AS bsurname, bo.firstname AS bfirstname, m.surname AS msurname, m.firstname AS mfirstname,
99         bo.cardnumber, br.branchname, bo.borrowernumber,
100         al.borrowernumber, DATE(al.date) as date, al.accounttype, al.amountoutstanding, al.note,
101         bi.title, bi.biblionumber, i.barcode, i.itype
102         FROM accountlines al
103         LEFT JOIN borrowers bo ON (al.borrowernumber = bo.borrowernumber)
104         LEFT JOIN borrowers m ON (al.manager_id = m.borrowernumber)
105         LEFT JOIN branches br ON (br.branchcode = m.branchcode )
106         LEFT JOIN items i ON (i.itemnumber = al.itemnumber)
107         LEFT JOIN biblio bi ON (bi.biblionumber = i.biblionumber)
108         WHERE CAST(al.date AS DATE) BETWEEN ? AND ?
109         $whereTType
110         $whereBranchCode
111         ORDER BY al.date
112     ";
113     my $sth_stats = $dbh->prepare($query) or die "Unable to prepare query " . $dbh->errstr;
114     $sth_stats->execute($fromDate, $toDate, @extra_params) or die "Unable to execute query " . $sth_stats->errstr;
115
116     my @loopresult;
117     my $grantotal = 0;
118     while ( my $row = $sth_stats->fetchrow_hashref()) {
119         $row->{amountoutstanding} = 0 if (!$row->{amountoutstanding});
120         #if ((abs($row->{amount}) - $row->{amountoutstanding}) > 0) {
121             $row->{amount} = sprintf("%.2f", abs ($row->{amount}));
122             $row->{date} = dt_from_string($row->{date}, 'sql');
123
124             push (@loopresult, $row);
125             if($transaction_type eq 'ACT' && ($row->{accounttype} !~ /^C$|^CR$|^LR$|^Pay$/)){
126                 pop @loopresult;
127                 next;
128             }
129             if($row->{accounttype} =~ /^C$|^CR$|^LR$/){
130                 $grantotal -= abs($row->{amount});
131                 $row->{amount} = '-' . $row->{amount};
132             }elsif($row->{accounttype} eq 'FORW' || $row->{accounttype} eq 'W'){
133             }else{
134                 $grantotal += abs($row->{amount});
135             }
136         #}
137     }
138
139     $grantotal = sprintf("%.2f", $grantotal);
140
141     if($output eq 'screen'){
142         $template->param(
143             loopresult => \@loopresult,
144             total => $grantotal,
145         );
146     } else{
147         my $format = 'csv';
148         my $reportname = $input->param('basename');
149         my $reportfilename = $reportname ? "$reportname.$format" : "reportresults.$format" ;
150         my $delimiter = C4::Context->preference('delimiter') || ',';
151             my @rows;
152             foreach my $row (@loopresult) {
153                 my @rowValues;
154                 push @rowValues, $row->{mfirstname}. ' ' . $row->{msurname},
155                         $row->{cardnumber},
156                         $row->{bfirstname} . ' ' . $row->{bsurname},
157                         $row->{branchname},
158                         $row->{date},
159                         $row->{accounttype},
160                         $row->{note},
161                         $row->{amount},
162                         $row->{title},
163                         $row->{barcode},
164                         $row->{itype};
165                     push (@rows, \@rowValues) ;
166                 }
167                 my @total;
168                 for (1..6){push(@total,"")};
169                 push(@total, $grantotal);
170         print $input->header(
171             -type       => 'text/csv',
172             -encoding    => 'utf-8',
173             -attachment => $reportfilename,
174             -name       => $reportfilename
175          );
176         my $csvTemplate = C4::Templates::gettemplate('reports/csv/cash_register_stats.tt', 'intranet', $input);
177             $csvTemplate->param(sep => $delimiter, rows => \@rows, total => \@total );
178         print $csvTemplate->output;
179         exit;
180     }
181
182 }
183
184 $template->param(
185     beginDate        => $fromDate,
186     endDate          => $toDate,
187     transaction_type => $transaction_type,
188     branchloop       => Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed,
189     manualinv_types  => $manualinv_types,
190     CGIsepChoice => GetDelimiterChoices,
191 );
192
193 output_html_with_http_headers $input, $cookie, $template->output;
194
195 1;