Bug 24488: Fix reserve.reserve_id' isn't in GROUP BY
[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 $startdate_iso = output_pref({ dt => $startdate, dateformat => 'iso', dateonly => 1 });
168 my $enddate_iso   = output_pref({ dt => $enddate, dateformat => 'iso', dateonly => 1 });
169 if ( $startdate_iso && $enddate_iso ){
170     $where{'reserve.reservedate'} = [ -and => { '>=', $startdate_iso }, { '<=', $enddate_iso } ];
171 } elsif ( $startdate_iso ){
172     $where{'reserve.reservedate'} = { '>=', $startdate_iso };
173 } elsif ( $enddate_iso ){
174     $where{'reserve.reservedate'} = { '<=', $enddate_iso };
175 }
176
177 # Bug 21320
178 if ( !C4::Context->preference('AllowHoldsOnDamagedItems') ){
179     $where{'itembib.damaged'} = 0;
180 }
181
182 if ( C4::Context->preference('IndependentBranches') ){
183     $where{'itembib.holdingbranch'} = C4::Context->userenv->{'branch'};
184 }
185
186 # get all distinct unfulfilled reserves
187 my $distinct_holds = Koha::Holds->search(
188     { %where },
189     { join => 'itembib', alias => 'reserve' }
190 );
191 my @biblionumbers = uniq $distinct_holds->get_column('biblionumber');
192
193 # make final reserves hash and fill with info
194 my $reserves;
195 foreach my $bibnum ( @biblionumbers ){
196
197     my @items = Koha::Items->search({ biblionumber => $bibnum });
198     foreach my $i ( @items ){
199         if ( $i->checkout ){
200             next;
201         }
202     }
203
204     my @branchtransfers = map { $_->itemnumber } Koha::Item::Transfers->search({ datearrived => undef }, { columns => [ 'itemnumber' ], collapse => 1 });
205     my @issues = map { $_->itemnumber } Koha::Checkouts->search({}, { columns => [ 'itemnumber' ], collapse => 1 });
206
207     # get available item types for each biblio
208     my $res_itemtypes;
209     if ( C4::Context->preference('item-level_itypes') ){
210         $res_itemtypes = Koha::Items->search(
211             { biblionumber => $bibnum,
212               itype => { '!=', undef },
213               itemlost => 0,
214               withdrawn => 0,
215               notforloan => 0,
216               itemnumber => { -not_in => [ @branchtransfers, @issues ] },
217             },
218             { columns => 'itype',
219               distinct => 1,
220             }
221         );
222     } else {
223         my $res_itemtypes = Koha::Biblioitems->search(
224             { biblionumber => $bibnum, itemtype => { '!=', undef }  },
225             { columns => 'itemtype',
226               distinct => 1,
227             }
228         );
229     }
230     $reserves->{$bibnum}->{itemtypes} = $res_itemtypes;
231
232     # get available locations for each biblio
233     my $res_locations = Koha::Items->search(
234         { biblionumber => $bibnum,
235           location => { '!=', undef },
236           itemlost => 0,
237           withdrawn => 0,
238           notforloan => 0,
239           itemnumber => { -not_in => [ @branchtransfers, @issues ] },
240         },
241         { columns => 'location',
242           distinct => 1,
243         }
244     );
245     $reserves->{$bibnum}->{locations} = $res_locations;
246
247     # get available callnumbers for each biblio
248     my $res_callnumbers = Koha::Items->search(
249         { biblionumber => $bibnum,
250           itemcallnumber => { '!=', undef },
251           itemlost => 0,
252           withdrawn => 0,
253           notforloan => 0,
254           itemnumber => { -not_in => [ @branchtransfers, @issues ] },
255         },
256         { columns => 'itemcallnumber',
257           distinct => 1,
258         }
259     );
260     $reserves->{$bibnum}->{callnumbers} = $res_callnumbers;
261
262     # get available enumchrons for each biblio
263     my $res_enumchrons = Koha::Items->search(
264         { biblionumber => $bibnum,
265           enumchron => { '!=', undef },
266           itemlost => 0,
267           withdrawn => 0,
268           notforloan => 0,
269           itemnumber => { -not_in => [ @branchtransfers, @issues ] },
270         },
271         { columns => 'enumchron',
272           distinct => 1,
273         }
274     );
275     $reserves->{$bibnum}->{enumchrons} = $res_enumchrons;
276
277     # get available copynumbers for each biblio
278     my $res_copynumbers = Koha::Items->search(
279         { biblionumber => $bibnum,
280           copynumber => { '!=', undef },
281           itemlost => 0,
282           withdrawn => 0,
283           notforloan => 0,
284           itemnumber => { -not_in => [ @branchtransfers, @issues ] },
285         },
286         { columns => 'copynumber',
287           distinct => 1,
288         }
289     );
290     $reserves->{$bibnum}->{copynumbers} = $res_copynumbers;
291
292     # get available barcodes for each biblio
293     my $res_barcodes = Koha::Items->search(
294         { biblionumber => $bibnum,
295           barcode => { '!=', undef },
296           itemlost => 0,
297           withdrawn => 0,
298           notforloan => 0,
299           itemnumber => { -not_in => [ @branchtransfers, @issues ] },
300         },
301         { columns => 'barcode',
302           distinct => 1,
303         }
304     );
305     $reserves->{$bibnum}->{barcodes} = $res_barcodes;
306
307     # get available holding branches for each biblio
308     my $res_holdingbranches = Koha::Items->search(
309         { biblionumber => $bibnum,
310           holdingbranch => { '!=', undef },
311           itemlost => 0,
312           withdrawn => 0,
313           notforloan => 0,
314           itemnumber => { -not_in => [ @branchtransfers, @issues ] },
315         },
316         { columns => 'holdingbranch',
317           distinct => 1,
318         }
319     );
320     $reserves->{$bibnum}->{holdingbranches} = $res_holdingbranches;
321
322     # items available
323     my $items_count = Koha::Items->search(
324         { biblionumber => $bibnum,
325           itemlost => 0,
326           withdrawn => 0,
327           notforloan => 0,
328           itemnumber => { -not_in => [ @branchtransfers, @issues ] },
329         },
330         { select => [ { distinct => 'itemnumber' } ] }
331     )->count;
332     $reserves->{$bibnum}->{items_count} = $items_count;
333
334     # patrons with holds
335     my $patrons_count = Koha::Holds->search(
336         { biblionumber => $bibnum },
337         { select => [ { distinct => 'borrowernumber' } ] }
338     )->count;
339     $reserves->{$bibnum}->{patrons_count} = $patrons_count;
340
341     my $pull_count = $items_count <= $patrons_count ? $items_count : $patrons_count;
342     if ( $pull_count == 0 ) {
343         delete($reserves->{$bibnum});
344         next;
345     }
346     $reserves->{$bibnum}->{pull_count} = $pull_count;
347
348     # get other relevant information
349     my $res_info = Koha::Holds->search(
350         { 'reserve.biblionumber' => $bibnum, %where },
351         { prefetch => [ 'borrowernumber', 'itembib', 'biblio' ],
352           order_by => 'reserve.reservedate',
353           alias => 'reserve'
354         }
355     )->next; # get first item in results
356     $reserves->{$bibnum}->{borrower} = $res_info->borrower;
357     $reserves->{$bibnum}->{item} = $res_info->item;
358     $reserves->{$bibnum}->{biblio} = $res_info->biblio;
359     $reserves->{$bibnum}->{reserve} = $res_info;
360 }
361
362 $template->param(
363     todaysdate          => $today,
364     from                => $startdate,
365     to                  => $enddate,
366     reserves            => $reserves,
367     "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
368     HoldsToPullStartDate => C4::Context->preference('HoldsToPullStartDate') || PULL_INTERVAL,
369     HoldsToPullEndDate  => C4::Context->preference('ConfirmFutureHolds') || 0,
370     messages            => \@messages,
371 );
372
373 output_html_with_http_headers $input, $cookie, $template->output;