Bug 13298 - Holds ratios report ignores ordered items
[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 under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 use strict;
22 use warnings;
23
24 use CGI qw ( -utf8 );
25 use Date::Calc qw/Today Add_Delta_YM/;
26
27 use C4::Context;
28 use C4::Output;
29 use C4::Auth;
30 use C4::Dates qw/format_date format_date_in_iso/;
31 use C4::Debug;
32 use C4::Biblio qw/GetMarcBiblio GetRecordValue GetFrameworkCode/;
33 use C4::Acquisition qw/GetOrdersByBiblionumber/;
34
35 my $input = new CGI;
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
41 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
42     {
43         template_name   => "circ/reserveratios.tt",
44         query           => $input,
45         type            => "intranet",
46         authnotrequired => 0,
47         flagsrequired   => { circulate => "circulate_remaining_permissions" },
48         debug           => 1,
49     }
50 );
51
52 my $booksellerid = $input->param('booksellerid') // '';
53 my $basketno = $input->param('basketno') // '';
54 if ($booksellerid && $basketno) {
55      $template->param( booksellerid => $booksellerid, basketno => $basketno );
56 }
57
58 my ( $year, $month, $day ) = Today();
59 my $todaysdate     = sprintf("%-04.4d-%-02.2d-%02.2d", $year, $month, $day);
60 # Find yesterday for the default shelf pull start and end dates
61 #    A default of the prior years's holds is a reasonable way to pull holds 
62 my $datelastyear = sprintf("%-04.4d-%-02.2d-%02.2d", Add_Delta_YM($year, $month, $day, -1, 0));
63
64 #               Predefine the start and end dates if they are not already defined
65 #               Check if null, should string match, if so set start and end date to yesterday
66 if (!defined($startdate) or $startdate !~ s/^\s*(\S+)\s*$/$1/) {   # strip spaces, remove Taint
67         $startdate = format_date($datelastyear);
68 }
69 if (!defined($enddate)   or $enddate   !~ s/^\s*(\S+)\s*$/$1/) {   # strip spaces, remove Taint
70         $enddate   = format_date($todaysdate);
71 }
72 if (!defined($ratio)) {
73         $ratio = 3;
74 }
75 # Force to be a number
76 $ratio += 0;
77 if ($ratio <= 0) {
78     $ratio = 1; # prevent division by zero
79 }
80
81 my $dbh    = C4::Context->dbh;
82 my $sqldatewhere = "";
83 $debug and warn format_date_in_iso($startdate) . "\n" . format_date_in_iso($enddate);
84 my @query_params = ();
85 if ($startdate) {
86     $sqldatewhere .= " AND reservedate >= ?";
87     push @query_params, format_date_in_iso($startdate);
88 }
89 if ($enddate) {
90     $sqldatewhere .= " AND reservedate <= ?";
91     push @query_params, format_date_in_iso($enddate);
92 }
93
94 my $nfl_comparison = $include_ordered ? '<=' : '=';
95 my $strsth =
96 "SELECT reservedate,
97         reserves.borrowernumber as borrowernumber,
98         reserves.biblionumber,
99         reserves.branchcode as branch,
100         items.holdingbranch,
101         items.itemcallnumber,
102         items.itemnumber,
103         GROUP_CONCAT(DISTINCT items.itemcallnumber 
104                         ORDER BY items.itemnumber SEPARATOR '<br/>') as listcall,
105         GROUP_CONCAT(DISTINCT holdingbranch 
106                         ORDER BY items.itemnumber SEPARATOR '<br/>') as listbranch,
107         GROUP_CONCAT(DISTINCT items.location 
108                         ORDER BY items.itemnumber SEPARATOR '<br/>') as l_location,
109         GROUP_CONCAT(DISTINCT items.itype 
110                         ORDER BY items.itemnumber SEPARATOR '<br/>') as l_itype,
111
112         reserves.found,
113         biblio.title,
114         biblio.author,
115         count(DISTINCT reserves.borrowernumber) as reservecount, 
116         count(DISTINCT items.itemnumber) as itemcount 
117  FROM  reserves
118  LEFT JOIN items ON items.biblionumber=reserves.biblionumber 
119  LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber
120  WHERE
121  notforloan $nfl_comparison 0 AND damaged = 0 AND itemlost = 0 AND withdrawn = 0
122  $sqldatewhere
123 ";
124
125 if (C4::Context->preference('IndependentBranches')){
126     $strsth .= " AND items.holdingbranch=? ";
127     push @query_params, C4::Context->userenv->{'branch'};
128 }
129
130 $strsth .= " GROUP BY reserves.biblionumber ORDER BY reservecount DESC";
131
132 $template->param(sql => $strsth);
133 my $sth = $dbh->prepare($strsth);
134 $sth->execute(@query_params);
135
136 my $ratio_atleast1 = ($ratio >= 1) ? 1 : 0;
137 my @reservedata;
138 while ( my $data = $sth->fetchrow_hashref ) {
139     my $thisratio = $data->{reservecount} / $data->{itemcount};
140     my $ratiocalc = ($thisratio / $ratio);
141     ($thisratio / $ratio) >= 1 or next;  # TODO: tighter targeting -- get ratio limit into SQL using HAVING clause
142     my $record = GetMarcBiblio($data->{biblionumber});
143     $data->{subtitle} = GetRecordValue('subtitle', $record, GetFrameworkCode($data->{biblionumber}));
144     push(
145         @reservedata,
146         {
147             reservedate      => format_date( $data->{reservedate} ),
148             priority         => $data->{priority},
149             name             => $data->{borrower},
150             title            => $data->{title},
151             subtitle            => $data->{subtitle},
152             author           => $data->{author},
153             itemnum          => $data->{itemnumber},
154             biblionumber     => $data->{biblionumber},
155             holdingbranch    => $data->{holdingbranch},
156             listbranch       => $data->{listbranch},
157             branch           => $data->{branch},
158             itemcallnumber   => $data->{itemcallnumber},
159             location         => $data->{l_location},
160             itype            => $data->{l_itype},
161             reservecount     => $data->{reservecount},
162             itemcount        => $data->{itemcount},
163             ratiocalc        => sprintf("%.0d", $ratio_atleast1 ? ($thisratio / $ratio) : $thisratio),
164             thisratio        => sprintf("%.2f", $thisratio),
165             thisratio_atleast1 => ($thisratio >= 1) ? 1 : 0,
166             listcall         => $data->{listcall}    
167         }
168     );
169 }
170
171 for my $rd ( @reservedata ) {
172     next unless $rd->{biblionumber};
173     $rd->{pendingorders} = CountPendingOrdersByBiblionumber( $rd->{biblionumber} );
174 }
175
176 $template->param(
177     ratio_atleast1  => $ratio_atleast1,
178     todaysdate      => format_date($todaysdate),
179     from            => $startdate,
180     to              => $enddate,
181     ratio           => $ratio,
182     include_ordered => $include_ordered,
183     reserveloop     => \@reservedata,
184 );
185
186 output_html_with_http_headers $input, $cookie, $template->output;
187
188 sub CountPendingOrdersByBiblionumber {
189     my $biblionumber = shift;
190     my @orders = GetOrdersByBiblionumber( $biblionumber );
191     my $cnt = 0;
192     if (scalar(@orders)) {
193         for my $order ( @orders ) {
194             next if $order->{datecancellationprinted};
195             my $onum = $order->{quantity} // 0;
196             my $rnum = $order->{quantityreceived} // 0;
197             next if $rnum >= $onum;
198             $cnt += ($onum - $rnum);
199         }
200     }
201     return $cnt;
202 }