66eebd3ce1635b831ad53c6ca585d7ebeeab3f45
[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
26 use C4::Context;
27 use C4::Output;
28 use C4::Auth;
29 use C4::Debug;
30 use C4::Acquisition qw/GetOrdersByBiblionumber/;
31 use Koha::DateUtils;
32 use Koha::Acquisition::Baskets;
33
34 my $input = new CGI;
35 my $startdate       = $input->param('from');
36 my $enddate         = $input->param('to');
37 my $ratio           = $input->param('ratio');
38 my $include_ordered = $input->param('include_ordered');
39
40 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
41     {
42         template_name   => "circ/reserveratios.tt",
43         query           => $input,
44         type            => "intranet",
45         authnotrequired => 0,
46         flagsrequired   => { circulate => "circulate_remaining_permissions" },
47         debug           => 1,
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 $strsth =
107 "SELECT reservedate,
108         reserves.borrowernumber as borrowernumber,
109         reserves.biblionumber,
110         reserves.branchcode as branch,
111         items.holdingbranch,
112         items.itemcallnumber,
113         items.itemnumber,
114         GROUP_CONCAT(DISTINCT items.itemcallnumber 
115             ORDER BY items.itemnumber SEPARATOR '|') as listcall,
116         GROUP_CONCAT(DISTINCT homebranch
117             ORDER BY items.itemnumber SEPARATOR '|') as homebranch_list,
118         GROUP_CONCAT(DISTINCT holdingbranch 
119             ORDER BY items.itemnumber SEPARATOR '|') as holdingbranch_list,
120         GROUP_CONCAT(DISTINCT items.location 
121             ORDER BY items.itemnumber SEPARATOR '|') as l_location,
122         GROUP_CONCAT(DISTINCT items.itype 
123             ORDER BY items.itemnumber SEPARATOR '|') as l_itype,
124
125         reserves.found,
126         biblio.title,
127         biblio.subtitle,
128         biblio.medium,
129         biblio.part_number,
130         biblio.part_name,
131         biblio.author,
132         count(DISTINCT reserves.borrowernumber) as reservecount, 
133         count(DISTINCT items.itemnumber) $include_aqorders_qty as itemcount
134  FROM  reserves
135  LEFT JOIN items ON items.biblionumber=reserves.biblionumber 
136  LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber
137  $include_aqorders_qty_join
138  WHERE
139  notforloan $nfl_comparison 0 AND damaged = 0 AND itemlost = 0 AND withdrawn = 0
140  $sqldatewhere
141 ";
142
143 if (C4::Context->preference('IndependentBranches')){
144     $strsth .= " AND items.holdingbranch=? ";
145     push @query_params, C4::Context->userenv->{'branch'};
146 }
147
148 $strsth .= " GROUP BY reserves.biblionumber ORDER BY reservecount DESC";
149
150 $template->param(sql => $strsth);
151 my $sth = $dbh->prepare($strsth);
152 $sth->execute(@query_params);
153
154 my $ratio_atleast1 = ($ratio >= 1) ? 1 : 0;
155 my @reservedata;
156 while ( my $data = $sth->fetchrow_hashref ) {
157     my $thisratio = $data->{reservecount} / $data->{itemcount};
158     my $ratiocalc = ($thisratio / $ratio);
159     ($thisratio / $ratio) >= 1 or next;  # TODO: tighter targeting -- get ratio limit into SQL using HAVING clause
160     push(
161         @reservedata,
162         {
163             reservedate        => $data->{reservedate},
164             priority           => $data->{priority},
165             name               => $data->{borrower},
166             title              => $data->{title},
167             subtitle           => C4::Biblio::SplitKohaField($data->{'subtitle'}),
168             author             => $data->{author},
169             itemnum            => $data->{itemnumber},
170             biblionumber       => $data->{biblionumber},
171             holdingbranch      => $data->{holdingbranch},
172             homebranch_list    => [split('\|', $data->{homebranch_list})],
173             holdingbranch_list => [split('\|', $data->{holdingbranch_list})],
174             branch             => $data->{branch},
175             itemcallnumber     => $data->{itemcallnumber},
176             location           => [split('\|', $data->{l_location})],
177             itype              => [split('\|', $data->{l_itype})],
178             reservecount       => $data->{reservecount},
179             itemcount          => $data->{itemcount},
180             ratiocalc          => sprintf( "%.0d", $ratio_atleast1 ? ( $thisratio / $ratio ) : $thisratio ),
181             thisratio => sprintf( "%.2f", $thisratio ),
182             thisratio_atleast1 => ( $thisratio >= 1 ) ? 1 : 0,
183             listcall           => [split('\|', $data->{listcall})]
184         }
185     );
186 }
187
188 for my $rd ( @reservedata ) {
189     next unless $rd->{biblionumber};
190     $rd->{pendingorders} = CountPendingOrdersByBiblionumber( $rd->{biblionumber} );
191 }
192
193 $template->param(
194     ratio_atleast1  => $ratio_atleast1,
195     todaysdate      => $todaysdate,
196     from            => $startdate,
197     to              => $enddate,
198     ratio           => $ratio,
199     include_ordered => $include_ordered,
200     reserveloop     => \@reservedata,
201 );
202
203 output_html_with_http_headers $input, $cookie, $template->output;
204
205 sub CountPendingOrdersByBiblionumber {
206     my $biblionumber = shift;
207     my @orders = GetOrdersByBiblionumber( $biblionumber );
208     my $cnt = 0;
209     if (scalar(@orders)) {
210         for my $order ( @orders ) {
211             next if $order->{datecancellationprinted};
212             my $onum = $order->{quantity} // 0;
213             my $rnum = $order->{quantityreceived} // 0;
214             next if $rnum >= $onum;
215             $cnt += ($onum - $rnum);
216         }
217     }
218     return $cnt;
219 }