Bug 28591: Don't pass debug to get_template_and_user
[koha.git] / circ / reserveratios.pl
1 #!/usr/bin/perl
2
3
4 # Copyright 2000-2002 Katipo Communications
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 use Modern::Perl;
22
23 use CGI qw ( -utf8 );
24 use Date::Calc qw/Today Add_Delta_YM/;
25 use POSIX qw( ceil );
26
27 use C4::Context;
28 use C4::Output;
29 use C4::Auth;
30 use C4::Debug;
31 use C4::Acquisition qw/GetOrdersByBiblionumber/;
32 use Koha::DateUtils;
33 use Koha::Acquisition::Baskets;
34
35 my $input = CGI->new;
36 my $startdate       = $input->param('from');
37 my $enddate         = $input->param('to');
38 my $ratio           = $input->param('ratio');
39 my $include_ordered = $input->param('include_ordered');
40 my $include_suspended = $input->param('include_suspended');
41
42 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
43     {
44         template_name   => "circ/reserveratios.tt",
45         query           => $input,
46         type            => "intranet",
47         flagsrequired   => { circulate => "circulate_remaining_permissions" },
48     }
49 );
50
51 my $booksellerid = $input->param('booksellerid') // '';
52 my $basketno = $input->param('basketno') // '';
53 if ($booksellerid && $basketno) {
54      $template->param( booksellerid => $booksellerid, basketno => $basketno );
55 }
56
57 my $effective_create_items = q{};
58 if ( $basketno ){
59     my $basket = Koha::Acquisition::Baskets->find( $basketno );
60     if ($basket){
61         $effective_create_items = $basket->effective_create_items;
62     } else {
63         $effective_create_items = C4::Context->preference('AcqCreateItem');
64     }
65 }
66
67 $startdate = eval { dt_from_string( $startdate ) } if $startdate;
68 $enddate = eval { dt_from_string( $enddate ) } if $enddate;
69
70 my $todaysdate = dt_from_string;
71
72 #    A default of the prior years's holds is a reasonable way to pull holds
73 $enddate = $todaysdate unless $enddate;
74 $startdate = $todaysdate->clone->subtract( years => 1 ) unless $startdate;
75
76 if (!defined($ratio)) {
77     $ratio = 3;
78 }
79 # Force to be a number
80 $ratio += 0;
81 if ($ratio <= 0) {
82     $ratio = 1; # prevent division by zero
83 }
84
85 my $dbh    = C4::Context->dbh;
86 my $sqldatewhere = "";
87 $debug and warn output_pref({ dt => $startdate, dateformat => 'iso', dateonly => 1 }) . "\n" . output_pref({ dt => $enddate, dateformat => 'iso', dateonly => 1 });
88 my @query_params = ();
89
90 $sqldatewhere .= " AND reservedate >= ?";
91 push @query_params, output_pref({ dt => $startdate, dateformat => 'iso' }) ;
92 $sqldatewhere .= " AND reservedate <= ?";
93 push @query_params, output_pref({ dt => $enddate, dateformat => 'iso' });
94
95 my $include_aqorders_qty =
96   $effective_create_items eq 'receiving'
97   ? '+ COALESCE(aqorders.quantity, 0) - COALESCE(aqorders.quantityreceived, 0)'
98   : q{};
99
100 my $include_aqorders_qty_join =
101   $effective_create_items eq 'receiving'
102   ? 'LEFT JOIN aqorders ON reserves.biblionumber=aqorders.biblionumber'
103   : q{};
104
105 my $nfl_comparison = $include_ordered ? '<=' : '=';
106 my $sus_comparison = $include_suspended ? '<=' : '<';
107 my $strsth =
108 "SELECT reservedate,
109         reserves.borrowernumber as borrowernumber,
110         reserves.biblionumber,
111         reserves.branchcode as branch,
112         items.holdingbranch,
113         items.itemcallnumber,
114         items.itemnumber,
115         GROUP_CONCAT(DISTINCT items.itemcallnumber 
116             ORDER BY items.itemnumber SEPARATOR '|') as listcall,
117         GROUP_CONCAT(DISTINCT homebranch
118             ORDER BY items.itemnumber SEPARATOR '|') as homebranch_list,
119         GROUP_CONCAT(DISTINCT holdingbranch 
120             ORDER BY items.itemnumber SEPARATOR '|') as holdingbranch_list,
121         GROUP_CONCAT(DISTINCT items.location 
122             ORDER BY items.itemnumber SEPARATOR '|') as l_location,
123         GROUP_CONCAT(DISTINCT items.itype 
124             ORDER BY items.itemnumber SEPARATOR '|') as l_itype,
125
126         reserves.found,
127         biblio.title,
128         biblio.subtitle,
129         biblio.medium,
130         biblio.part_number,
131         biblio.part_name,
132         biblio.author,
133         count(DISTINCT reserves.borrowernumber) as reservecount, 
134         count(DISTINCT items.itemnumber) $include_aqorders_qty as itemcount
135  FROM  reserves
136  LEFT JOIN items ON items.biblionumber=reserves.biblionumber 
137  LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber
138  $include_aqorders_qty_join
139  WHERE
140  notforloan $nfl_comparison 0 AND damaged = 0 AND itemlost = 0 AND withdrawn = 0
141  AND suspend $sus_comparison 1
142  $sqldatewhere
143 ";
144
145 if (C4::Context->preference('IndependentBranches')){
146     $strsth .= " AND items.holdingbranch=? ";
147     push @query_params, C4::Context->userenv->{'branch'};
148 }
149
150 $strsth .= " GROUP BY reserves.biblionumber ORDER BY reservecount DESC";
151
152 $template->param(sql => $strsth);
153 my $sth = $dbh->prepare($strsth);
154 $sth->execute(@query_params);
155
156 my @reservedata;
157 while ( my $data = $sth->fetchrow_hashref ) {
158     my $thisratio = $data->{reservecount} / $data->{itemcount};
159     my $copies_to_buy = ceil($data->{reservecount}/$ratio - $data->{itemcount});
160     $thisratio >= $ratio or next;  # TODO: tighter targeting -- get ratio limit into SQL using HAVING clause
161     push(
162         @reservedata,
163         {
164             reservedate        => $data->{reservedate},
165             priority           => $data->{priority},
166             name               => $data->{borrower},
167             title              => $data->{title},
168             subtitle           => $data->{subtitle},
169             medium             => $data->{medium},
170             part_number        => $data->{part_number},
171             part_name          => $data->{part_name},
172             author             => $data->{author},
173             itemnum            => $data->{itemnumber},
174             biblionumber       => $data->{biblionumber},
175             holdingbranch      => $data->{holdingbranch},
176             homebranch_list    => [split('\|', $data->{homebranch_list})],
177             holdingbranch_list => [split('\|', $data->{holdingbranch_list})],
178             branch             => $data->{branch},
179             itemcallnumber     => $data->{itemcallnumber},
180             location           => [split('\|', $data->{l_location})],
181             itype              => [split('\|', $data->{l_itype})],
182             reservecount       => $data->{reservecount},
183             itemcount          => $data->{itemcount},
184             copies_to_buy      => sprintf( "%d", $copies_to_buy ),
185             thisratio => sprintf( "%.2f", $thisratio ),
186             thisratio_atleast1 => ( $thisratio >= 1 ) ? 1 : 0,
187             listcall           => [split('\|', $data->{listcall})]
188         }
189     );
190 }
191
192 for my $rd ( @reservedata ) {
193     next unless $rd->{biblionumber};
194     $rd->{pendingorders} = CountPendingOrdersByBiblionumber( $rd->{biblionumber} );
195 }
196
197 $template->param(
198     todaysdate      => $todaysdate,
199     from            => $startdate,
200     to              => $enddate,
201     ratio           => $ratio,
202     include_ordered => $include_ordered,
203     include_suspended => $include_suspended,
204     reserveloop     => \@reservedata,
205 );
206
207 output_html_with_http_headers $input, $cookie, $template->output;
208
209 sub CountPendingOrdersByBiblionumber {
210     my $biblionumber = shift;
211     my @orders = GetOrdersByBiblionumber( $biblionumber );
212     my $cnt = 0;
213     if (scalar(@orders)) {
214         for my $order ( @orders ) {
215             next if $order->{datecancellationprinted};
216             my $onum = $order->{quantity} // 0;
217             my $rnum = $order->{quantityreceived} // 0;
218             next if $rnum >= $onum;
219             $cnt += ($onum - $rnum);
220         }
221     }
222     return $cnt;
223 }