812f9e4e34477242d0acde069706a25b136ac75d
[srvgit] / 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::Acquisition qw/GetOrdersByBiblionumber/;
31 use Koha::DateUtils;
32 use Koha::Acquisition::Baskets;
33
34 my $input = CGI->new;
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 my $include_suspended = $input->param('include_suspended');
40
41 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
42     {
43         template_name   => "circ/reserveratios.tt",
44         query           => $input,
45         type            => "intranet",
46         flagsrequired   => { circulate => "circulate_remaining_permissions" },
47     }
48 );
49
50 my $booksellerid = $input->param('booksellerid') // '';
51 my $basketno = $input->param('basketno') // '';
52 if ($booksellerid && $basketno) {
53      $template->param( booksellerid => $booksellerid, basketno => $basketno );
54 }
55
56 my $effective_create_items = q{};
57 if ( $basketno ){
58     my $basket = Koha::Acquisition::Baskets->find( $basketno );
59     if ($basket){
60         $effective_create_items = $basket->effective_create_items;
61     } else {
62         $effective_create_items = C4::Context->preference('AcqCreateItem');
63     }
64 }
65
66 $startdate = eval { dt_from_string( $startdate ) } if $startdate;
67 $enddate = eval { dt_from_string( $enddate ) } if $enddate;
68
69 my $todaysdate = dt_from_string;
70
71 #    A default of the prior years's holds is a reasonable way to pull holds
72 $enddate = $todaysdate unless $enddate;
73 $startdate = $todaysdate->clone->subtract( years => 1 ) unless $startdate;
74
75 if (!defined($ratio)) {
76     $ratio = 3;
77 }
78 # Force to be a number
79 $ratio += 0;
80 if ($ratio <= 0) {
81     $ratio = 1; # prevent division by zero
82 }
83
84 my $dbh    = C4::Context->dbh;
85 my $sqldatewhere = "";
86 my @query_params = ();
87
88 $sqldatewhere .= " AND reservedate >= ?";
89 push @query_params, output_pref({ dt => $startdate, dateformat => 'iso' }) ;
90 $sqldatewhere .= " AND reservedate <= ?";
91 push @query_params, output_pref({ dt => $enddate, dateformat => 'iso' });
92
93 my $include_aqorders_qty =
94   $effective_create_items eq 'receiving'
95   ? '+ COALESCE(aqorders.quantity, 0) - COALESCE(aqorders.quantityreceived, 0)'
96   : q{};
97
98 my $include_aqorders_qty_join =
99   $effective_create_items eq 'receiving'
100   ? 'LEFT JOIN aqorders ON reserves.biblionumber=aqorders.biblionumber'
101   : q{};
102
103 my $nfl_comparison = $include_ordered ? '<=' : '=';
104 my $sus_comparison = $include_suspended ? '<=' : '<';
105 my $strsth =
106 "SELECT reservedate,
107         reserves.borrowernumber as borrowernumber,
108         reserves.biblionumber,
109         reserves.branchcode as branch,
110         items.holdingbranch,
111         items.itemcallnumber,
112         items.itemnumber,
113         GROUP_CONCAT(DISTINCT items.itemcallnumber 
114             ORDER BY items.itemnumber SEPARATOR '|') as listcall,
115         GROUP_CONCAT(DISTINCT homebranch
116             ORDER BY items.itemnumber SEPARATOR '|') as homebranch_list,
117         GROUP_CONCAT(DISTINCT holdingbranch 
118             ORDER BY items.itemnumber SEPARATOR '|') as holdingbranch_list,
119         GROUP_CONCAT(DISTINCT items.location 
120             ORDER BY items.itemnumber SEPARATOR '|') as l_location,
121         GROUP_CONCAT(DISTINCT items.itype 
122             ORDER BY items.itemnumber SEPARATOR '|') as l_itype,
123
124         reserves.found,
125         biblio.title,
126         biblio.subtitle,
127         biblio.medium,
128         biblio.part_number,
129         biblio.part_name,
130         biblio.author,
131         count(DISTINCT reserves.borrowernumber) as reservecount, 
132         count(DISTINCT items.itemnumber) $include_aqorders_qty as itemcount
133  FROM  reserves
134  LEFT JOIN items ON items.biblionumber=reserves.biblionumber 
135  LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber
136  $include_aqorders_qty_join
137  WHERE
138  notforloan $nfl_comparison 0 AND damaged = 0 AND itemlost = 0 AND withdrawn = 0
139  AND suspend $sus_comparison 1
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 @reservedata;
155 while ( my $data = $sth->fetchrow_hashref ) {
156     my $thisratio = $data->{reservecount} / $data->{itemcount};
157     my $copies_to_buy = ceil($data->{reservecount}/$ratio - $data->{itemcount});
158     $thisratio >= $ratio or next;  # TODO: tighter targeting -- get ratio limit into SQL using HAVING clause
159     push(
160         @reservedata,
161         {
162             reservedate        => $data->{reservedate},
163             priority           => $data->{priority},
164             name               => $data->{borrower},
165             title              => $data->{title},
166             subtitle           => $data->{subtitle},
167             medium             => $data->{medium},
168             part_number        => $data->{part_number},
169             part_name          => $data->{part_name},
170             author             => $data->{author},
171             itemnum            => $data->{itemnumber},
172             biblionumber       => $data->{biblionumber},
173             holdingbranch      => $data->{holdingbranch},
174             homebranch_list    => [split('\|', $data->{homebranch_list})],
175             holdingbranch_list => [split('\|', $data->{holdingbranch_list})],
176             branch             => $data->{branch},
177             itemcallnumber     => $data->{itemcallnumber},
178             location           => [split('\|', $data->{l_location})],
179             itype              => [split('\|', $data->{l_itype})],
180             reservecount       => $data->{reservecount},
181             itemcount          => $data->{itemcount},
182             copies_to_buy      => sprintf( "%d", $copies_to_buy ),
183             thisratio => sprintf( "%.2f", $thisratio ),
184             thisratio_atleast1 => ( $thisratio >= 1 ) ? 1 : 0,
185             listcall           => [split('\|', $data->{listcall})]
186         }
187     );
188 }
189
190 for my $rd ( @reservedata ) {
191     next unless $rd->{biblionumber};
192     $rd->{pendingorders} = CountPendingOrdersByBiblionumber( $rd->{biblionumber} );
193 }
194
195 $template->param(
196     todaysdate      => $todaysdate,
197     from            => $startdate,
198     to              => $enddate,
199     ratio           => $ratio,
200     include_ordered => $include_ordered,
201     include_suspended => $include_suspended,
202     reserveloop     => \@reservedata,
203 );
204
205 output_html_with_http_headers $input, $cookie, $template->output;
206
207 sub CountPendingOrdersByBiblionumber {
208     my $biblionumber = shift;
209     my @orders = GetOrdersByBiblionumber( $biblionumber );
210     my $cnt = 0;
211     if (scalar(@orders)) {
212         for my $order ( @orders ) {
213             next if $order->{datecancellationprinted};
214             my $onum = $order->{quantity} // 0;
215             my $rnum = $order->{quantityreceived} // 0;
216             next if $rnum >= $onum;
217             $cnt += ($onum - $rnum);
218         }
219     }
220     return $cnt;
221 }