Bug 24488: Simplify searches
[koha.git] / circ / pendingreserves.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use constant PULL_INTERVAL => 2;
23 use List::MoreUtils qw( uniq );
24
25 use C4::Context;
26 use C4::Output;
27 use CGI qw ( -utf8 );
28 use C4::Auth;
29 use C4::Debug;
30 use C4::Items qw( ModItemTransfer );
31 use C4::Reserves qw( ModReserveCancelAll );
32 use Koha::Biblios;
33 use Koha::DateUtils;
34 use Koha::Holds;
35 use DateTime::Duration;
36
37 my $input = CGI->new;
38 my $startdate = $input->param('from');
39 my $enddate = $input->param('to');
40 my $theme = $input->param('theme');    # only used if allowthemeoverride is set
41 my $op         = $input->param('op') || '';
42 my $borrowernumber = $input->param('borrowernumber');
43 my $reserve_id = $input->param('reserve_id');
44
45 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
46     {
47         template_name   => "circ/pendingreserves.tt",
48         query           => $input,
49         type            => "intranet",
50         flagsrequired   => { circulate => "circulate_remaining_permissions" },
51         debug           => 1,
52     }
53 );
54
55 my @messages;
56 if ( $op eq 'cancel_reserve' and $reserve_id ) {
57     my $hold = Koha::Holds->find( $reserve_id );
58     if ( $hold ) {
59         my $cancellation_reason = $input->param('cancellation-reason');
60         $hold->cancel({ cancellation_reason => $cancellation_reason });
61         push @messages, { type => 'message', code => 'hold_cancelled' };
62     }
63 } elsif ( $op =~ m|^mark_as_lost| ) {
64     my $hold = Koha::Holds->find( $reserve_id );
65     die "wrong reserve_id" unless $hold; # This is a bit rude, but we are not supposed to get a wrong reserve_id
66     my $item = $hold->item;
67     if ( $item and C4::Context->preference('CanMarkHoldsToPullAsLost') =~ m|^allow| ) {
68         my $patron = $hold->borrower;
69         C4::Circulation::LostItem( $item->itemnumber, "pendingreserves" );
70         if ( $op eq 'mark_as_lost_and_notify' and C4::Context->preference('CanMarkHoldsToPullAsLost') eq 'allow_and_notify' ) {
71             my $library = $hold->branch;
72             my $letter = C4::Letters::GetPreparedLetter(
73                 module => 'reserves',
74                 letter_code => 'CANCEL_HOLD_ON_LOST',
75                 branchcode => $patron->branchcode,
76                 lang => $patron->lang,
77                 tables => {
78                     branches    => $library->branchcode,
79                     borrowers   => $patron->borrowernumber,
80                     items       => $item->itemnumber,
81                     biblio      => $hold->biblionumber,
82                     biblioitems => $hold->biblionumber,
83                     reserves    => $hold->unblessed,
84                 },
85             );
86             if ( $letter ) {
87                 my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
88
89                 C4::Letters::EnqueueLetter(
90                     {   letter                 => $letter,
91                         borrowernumber         => $patron->borrowernumber,
92                         message_transport_type => 'email',
93                         from_address           => $admin_email_address,
94                     }
95                 );
96                 unless ( $patron->notice_email_address ) {
97                     push @messages, {type => 'alert', code => 'no_email_address', };
98                 }
99                 push @messages, { type => 'message', code => 'letter_enqueued' };
100             } else {
101                 push @messages, { type => 'error', code => 'no_template_notice' };
102             }
103         }
104         $hold->cancel;
105         if ( $item->homebranch ne $item->holdingbranch ) {
106             C4::Items::ModItemTransfer( $item->itemnumber, $item->holdingbranch, $item->homebranch, 'LostReserve' );
107         }
108
109         if ( my $yaml = C4::Context->preference('UpdateItemWhenLostFromHoldList') ) {
110             $yaml = "$yaml\n\n";  # YAML is anal on ending \n. Surplus does not hurt
111             my $assignments;
112             eval { $assignments = YAML::Load($yaml); };
113             if ($@) {
114                 warn "Unable to parse UpdateItemWhenLostFromHoldList syspref : $@" if $@;
115             }
116             else {
117                 eval {
118                     while ( my ( $f, $v ) = each( %$assignments ) ) {
119                         $item->$f($v);
120                     }
121                     $item->store;
122                 };
123                 warn "Unable to modify item itemnumber=" . $item->itemnumber . ": $@" if $@;
124             }
125         }
126
127     } elsif ( not $item ) {
128         push @messages, { type => 'alert', code => 'hold_placed_at_biblio_level'};
129     } # else the url parameters have been modified and the user is not allowed to continue
130 }
131
132
133 my $today = dt_from_string;
134
135 if ( $startdate ) {
136     $startdate =~ s/^\s+//;
137     $startdate =~ s/\s+$//;
138     $startdate = eval{dt_from_string( $startdate )};
139 }
140 unless ( $startdate ){
141     # changed from delivered range of 10 years-yesterday to 2 days ago-today
142     # Find two days ago for the default shelf pull start date, unless HoldsToPullStartDate sys pref is set.
143     $startdate = $today - DateTime::Duration->new( days => C4::Context->preference('HoldsToPullStartDate') || PULL_INTERVAL );
144 }
145
146 if ( $enddate ) {
147     $enddate =~ s/^\s+//;
148     $enddate =~ s/\s+$//;
149     $enddate = eval{dt_from_string( $enddate )};
150 }
151 unless ( $enddate ) {
152     #similarly: calculate end date with ConfirmFutureHolds (days)
153     $enddate = $today + DateTime::Duration->new( days => C4::Context->preference('ConfirmFutureHolds') || 0 );
154 }
155
156 # building query parameters
157 my %where = (
158     'reserve.found' => undef,
159     'reserve.suspend' => 0,
160     'itembib.itemlost' => 0,
161     'itembib.withdrawn' => 0,
162     'itembib.notforloan' => 0,
163     'itembib.itemnumber' => { -not_in => \'SELECT itemnumber FROM branchtransfers WHERE datearrived IS NULL' }
164 );
165
166 # date boundaries
167 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
168 my $startdate_iso = $dtf->format_date($startdate);
169 my $enddate_iso   = $dtf->format_date($enddate);
170 if ( $startdate_iso && $enddate_iso ){
171     $where{'reserve.reservedate'} = [ -and => { '>=', $startdate_iso }, { '<=', $enddate_iso } ];
172 } elsif ( $startdate_iso ){
173     $where{'reserve.reservedate'} = { '>=', $startdate_iso };
174 } elsif ( $enddate_iso ){
175     $where{'reserve.reservedate'} = { '<=', $enddate_iso };
176 }
177
178 # Bug 21320
179 if ( !C4::Context->preference('AllowHoldsOnDamagedItems') ){
180     $where{'itembib.damaged'} = 0;
181 }
182
183 if ( C4::Context->preference('IndependentBranches') ){
184     $where{'itembib.holdingbranch'} = C4::Context->userenv->{'branch'};
185 }
186
187 # get all distinct unfulfilled reserves
188 my $distinct_holds = Koha::Holds->search(
189     { %where },
190     { join => 'itembib', alias => 'reserve' }
191 );
192 my @biblionumbers = uniq $distinct_holds->get_column('biblionumber');
193
194 # make final reserves hash and fill with info
195 my $reserves;
196 foreach my $bibnum ( @biblionumbers ){
197
198     my @items = Koha::Items->search({ biblionumber => $bibnum });
199     foreach my $i ( @items ){
200         if ( $i->checkout ){
201             next;
202         }
203     }
204
205     my @branchtransfers = map { $_->itemnumber } Koha::Item::Transfers->search({ datearrived => undef }, { columns => [ 'itemnumber' ], collapse => 1 });
206     my @issues = map { $_->itemnumber } Koha::Checkouts->search({}, { columns => [ 'itemnumber' ], collapse => 1 });
207
208     my $items = Koha::Items->search(
209         {
210             biblionumber => $bibnum,
211             itemlost     => 0,
212             withdrawn    => 0,
213             notforloan   => 0,
214             itemnumber   => { -not_in => [ @branchtransfers, @issues ] },
215         }
216     );
217
218     # get available item types for each biblio
219     my $res_itemtypes;
220     if ( C4::Context->preference('item-level_itypes') ){
221         $res_itemtypes = $items->search(
222             {
223                 itype => { '!=', undef },
224             },
225             {
226                 columns  => 'itype',
227                 distinct => 1,
228             }
229         );
230     } else {
231         my $res_itemtypes = Koha::Biblioitems->search(
232             { biblionumber => $bibnum, itemtype => { '!=', undef }  },
233             { columns => 'itemtype',
234               distinct => 1,
235             }
236         );
237     }
238     $reserves->{$bibnum}->{itemtypes} = $res_itemtypes;
239
240     # get available locations for each biblio
241     my $res_locations = $items->search(
242         {
243             location => { '!=', undef },
244         },
245         {
246             columns  => 'location',
247             distinct => 1,
248         }
249     );
250     $reserves->{$bibnum}->{locations} = $res_locations;
251
252     # get available callnumbers for each biblio
253     my $res_callnumbers = $items->search(
254         {
255             itemcallnumber => { '!=', undef },
256         },
257         {
258             columns  => 'itemcallnumber',
259             distinct => 1,
260         }
261     );
262     $reserves->{$bibnum}->{callnumbers} = $res_callnumbers;
263
264     # get available enumchrons for each biblio
265     my $res_enumchrons = $items->search(
266         {
267             enumchron => { '!=', undef },
268         },
269         {
270             columns  => 'enumchron',
271             distinct => 1,
272         }
273     );
274     $reserves->{$bibnum}->{enumchrons} = $res_enumchrons;
275
276     # get available copynumbers for each biblio
277     my $res_copynumbers = $items->search(
278         {
279             copynumber => { '!=', undef },
280         },
281         {
282             columns  => 'copynumber',
283             distinct => 1,
284         }
285     );
286     $reserves->{$bibnum}->{copynumbers} = $res_copynumbers;
287
288     # get available barcodes for each biblio
289     my $res_barcodes = $items->search(
290         {
291             barcode => { '!=', undef },
292         },
293         {
294             columns  => 'barcode',
295             distinct => 1,
296         }
297     );
298     $reserves->{$bibnum}->{barcodes} = $res_barcodes;
299
300     # get available holding branches for each biblio
301     my $res_holdingbranches = $items->search(
302         {
303             holdingbranch => { '!=', undef },
304         },
305         {
306             columns  => 'holdingbranch',
307             distinct => 1,
308         }
309     );
310     $reserves->{$bibnum}->{holdingbranches} = $res_holdingbranches;
311
312     # items available
313     my $items_count = $items->count;
314     $reserves->{$bibnum}->{items_count} = $items_count;
315
316     # patrons with holds
317     my $patrons_count = Koha::Holds->search(
318         { biblionumber => $bibnum },
319         { select => [ { distinct => 'borrowernumber' } ] }
320     )->count;
321     $reserves->{$bibnum}->{patrons_count} = $patrons_count;
322
323     my $pull_count = $items_count <= $patrons_count ? $items_count : $patrons_count;
324     if ( $pull_count == 0 ) {
325         delete($reserves->{$bibnum});
326         next;
327     }
328     $reserves->{$bibnum}->{pull_count} = $pull_count;
329
330     # get other relevant information
331     my $res_info = Koha::Holds->search(
332         { 'reserve.biblionumber' => $bibnum, %where },
333         { prefetch => [ 'borrowernumber', 'itembib', 'biblio' ],
334           order_by => 'priority',
335           alias => 'reserve'
336         }
337     )->next; # get first item in results
338     $reserves->{$bibnum}->{borrower} = $res_info->borrower;
339     $reserves->{$bibnum}->{item} = $res_info->item;
340     $reserves->{$bibnum}->{biblio} = $res_info->biblio;
341     $reserves->{$bibnum}->{reserve} = $res_info;
342 }
343
344 $template->param(
345     todaysdate          => $today,
346     from                => $startdate,
347     to                  => $enddate,
348     reserves            => $reserves,
349     "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
350     HoldsToPullStartDate => C4::Context->preference('HoldsToPullStartDate') || PULL_INTERVAL,
351     HoldsToPullEndDate  => C4::Context->preference('ConfirmFutureHolds') || 0,
352     messages            => \@messages,
353 );
354
355 output_html_with_http_headers $input, $cookie, $template->output;