Bug 24488: Show correct first patron details on Holds to pull
[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
24 use C4::Context;
25 use C4::Output;
26 use CGI qw ( -utf8 );
27 use C4::Auth;
28 use C4::Debug;
29 use C4::Items qw( ModItemTransfer );
30 use C4::Reserves qw( ModReserveCancelAll );
31 use Koha::Biblios;
32 use Koha::DateUtils;
33 use Koha::Holds;
34 use DateTime::Duration;
35
36 my $input = CGI->new;
37 my $startdate = $input->param('from');
38 my $enddate = $input->param('to');
39 my $theme = $input->param('theme');    # only used if allowthemeoverride is set
40 my $op         = $input->param('op') || '';
41 my $borrowernumber = $input->param('borrowernumber');
42 my $reserve_id = $input->param('reserve_id');
43
44 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
45     {
46         template_name   => "circ/pendingreserves.tt",
47         query           => $input,
48         type            => "intranet",
49         flagsrequired   => { circulate => "circulate_remaining_permissions" },
50         debug           => 1,
51     }
52 );
53
54 my @messages;
55 if ( $op eq 'cancel_reserve' and $reserve_id ) {
56     my $hold = Koha::Holds->find( $reserve_id );
57     if ( $hold ) {
58         my $cancellation_reason = $input->param('cancellation-reason');
59         $hold->cancel({ cancellation_reason => $cancellation_reason });
60         push @messages, { type => 'message', code => 'hold_cancelled' };
61     }
62 } elsif ( $op =~ m|^mark_as_lost| ) {
63     my $hold = Koha::Holds->find( $reserve_id );
64     die "wrong reserve_id" unless $hold; # This is a bit rude, but we are not supposed to get a wrong reserve_id
65     my $item = $hold->item;
66     if ( $item and C4::Context->preference('CanMarkHoldsToPullAsLost') =~ m|^allow| ) {
67         my $patron = $hold->borrower;
68         C4::Circulation::LostItem( $item->itemnumber, "pendingreserves" );
69         if ( $op eq 'mark_as_lost_and_notify' and C4::Context->preference('CanMarkHoldsToPullAsLost') eq 'allow_and_notify' ) {
70             my $library = $hold->branch;
71             my $letter = C4::Letters::GetPreparedLetter(
72                 module => 'reserves',
73                 letter_code => 'CANCEL_HOLD_ON_LOST',
74                 branchcode => $patron->branchcode,
75                 lang => $patron->lang,
76                 tables => {
77                     branches    => $library->branchcode,
78                     borrowers   => $patron->borrowernumber,
79                     items       => $item->itemnumber,
80                     biblio      => $hold->biblionumber,
81                     biblioitems => $hold->biblionumber,
82                     reserves    => $hold->unblessed,
83                 },
84             );
85             if ( $letter ) {
86                 my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
87
88                 C4::Letters::EnqueueLetter(
89                     {   letter                 => $letter,
90                         borrowernumber         => $patron->borrowernumber,
91                         message_transport_type => 'email',
92                         from_address           => $admin_email_address,
93                     }
94                 );
95                 unless ( $patron->notice_email_address ) {
96                     push @messages, {type => 'alert', code => 'no_email_address', };
97                 }
98                 push @messages, { type => 'message', code => 'letter_enqueued' };
99             } else {
100                 push @messages, { type => 'error', code => 'no_template_notice' };
101             }
102         }
103         $hold->cancel;
104         if ( $item->homebranch ne $item->holdingbranch ) {
105             C4::Items::ModItemTransfer( $item->itemnumber, $item->holdingbranch, $item->homebranch, 'LostReserve' );
106         }
107
108         if ( my $yaml = C4::Context->preference('UpdateItemWhenLostFromHoldList') ) {
109             $yaml = "$yaml\n\n";  # YAML is anal on ending \n. Surplus does not hurt
110             my $assignments;
111             eval { $assignments = YAML::Load($yaml); };
112             if ($@) {
113                 warn "Unable to parse UpdateItemWhenLostFromHoldList syspref : $@" if $@;
114             }
115             else {
116                 eval {
117                     while ( my ( $f, $v ) = each( %$assignments ) ) {
118                         $item->$f($v);
119                     }
120                     $item->store;
121                 };
122                 warn "Unable to modify item itemnumber=" . $item->itemnumber . ": $@" if $@;
123             }
124         }
125
126     } elsif ( not $item ) {
127         push @messages, { type => 'alert', code => 'hold_placed_at_biblio_level'};
128     } # else the url parameters have been modified and the user is not allowed to continue
129 }
130
131
132 my $today = dt_from_string;
133
134 if ( $startdate ) {
135     $startdate =~ s/^\s+//;
136     $startdate =~ s/\s+$//;
137     $startdate = eval{dt_from_string( $startdate )};
138 }
139 unless ( $startdate ){
140     # changed from delivered range of 10 years-yesterday to 2 days ago-today
141     # Find two days ago for the default shelf pull start date, unless HoldsToPullStartDate sys pref is set.
142     $startdate = $today - DateTime::Duration->new( days => C4::Context->preference('HoldsToPullStartDate') || PULL_INTERVAL );
143 }
144
145 if ( $enddate ) {
146     $enddate =~ s/^\s+//;
147     $enddate =~ s/\s+$//;
148     $enddate = eval{dt_from_string( $enddate )};
149 }
150 unless ( $enddate ) {
151     #similarly: calculate end date with ConfirmFutureHolds (days)
152     $enddate = $today + DateTime::Duration->new( days => C4::Context->preference('ConfirmFutureHolds') || 0 );
153 }
154
155 # building query parameters
156 my %where = (
157     'reserve.found' => undef,
158     'reserve.suspend' => 0,
159     'itembib.itemlost' => 0,
160     'itembib.withdrawn' => 0,
161     'itembib.notforloan' => 0,
162     'itembib.itemnumber' => { -not_in => \'SELECT itemnumber FROM branchtransfers WHERE datearrived IS NULL' }
163 );
164
165 # date boundaries
166 my $startdate_iso = output_pref({ dt => $startdate, dateformat => 'iso', dateonly => 1 });
167 my $enddate_iso   = output_pref({ dt => $enddate, dateformat => 'iso', dateonly => 1 });
168 if ( $startdate_iso && $enddate_iso ){
169     $where{'reserve.reservedate'} = [ -and => { '>=', $startdate_iso }, { '<=', $enddate_iso } ];
170 } elsif ( $startdate_iso ){
171     $where{'reserve.reservedate'} = { '>=', $startdate_iso };
172 } elsif ( $enddate_iso ){
173     $where{'reserve.reservedate'} = { '<=', $enddate_iso };
174 }
175
176 # Bug 21320
177 if ( !C4::Context->preference('AllowHoldsOnDamagedItems') ){
178     $where{'itembib.damaged'} = 0;
179 }
180
181 if ( C4::Context->preference('IndependentBranches') ){
182     $where{'itembib.holdingbranch'} = C4::Context->userenv->{'branch'};
183 }
184
185 # get all distinct unfulfilled reserves
186 my @distinct_holds = Koha::Holds->search(
187     { %where },
188     { join => 'itembib', group_by => 'reserve.biblionumber', alias => 'reserve' }
189 );
190
191 # make final reserves hash and fill with info
192 my $reserves;
193 foreach my $dh ( @distinct_holds ){
194
195     my $bibnum = $dh->biblionumber;
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;