Bug 8461: Display information on withdrawn item when checked in
[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 use YAML::XS;
25 use Encode;
26
27 use C4::Context;
28 use C4::Output qw( output_html_with_http_headers );
29 use CGI qw ( -utf8 );
30 use C4::Auth qw( get_template_and_user );
31 use C4::Items;
32 use Koha::Biblios;
33 use Koha::DateUtils qw( dt_from_string );
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     }
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 $from_address = $library->from_email_address;
87
88                 C4::Letters::EnqueueLetter(
89                     {   letter                 => $letter,
90                         borrowernumber         => $patron->borrowernumber,
91                         message_transport_type => 'email',
92                         from_address           => $from_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::XS::Load(Encode::encode_utf8($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     'me.found' => undef,
158     'me.priority' => { '!=' => 0 },
159     'me.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 AND datecancelled 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{'me.reservedate'} = [ -and => { '>=', $startdate_iso }, { '<=', $enddate_iso } ];
172 } elsif ( $startdate_iso ){
173     $where{'me.reservedate'} = { '>=', $startdate_iso };
174 } elsif ( $enddate_iso ){
175     $where{'me.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->only_my_library() ){
184     $where{'me.branchcode'} = C4::Context->userenv->{'branch'};
185 }
186
187 # get all distinct unfulfilled reserves
188 my $holds = Koha::Holds->search(
189     { %where },
190     { join => 'itembib', distinct => 1, columns => qw[me.biblionumber] }
191 );
192
193 my @biblionumbers = $holds->get_column('biblionumber');
194
195 my $all_items;
196 if ( $holds->count ) {
197     foreach my $item ( $holds->get_items_that_can_fill->as_list ) {
198         push @{ $all_items->{ $item->biblionumber } }, $item;
199     }
200 }
201
202 # patrons count per biblio
203 my $patrons_count = {
204     map { $_->{biblionumber} => $_->{patrons_count} } @{ Koha::Holds->search(
205             { 'suspend' => 0 },
206             {
207                 select   => [ 'biblionumber', { count => { distinct => 'borrowernumber' } } ],
208                 as       => [qw( biblionumber patrons_count )],
209                 group_by => [qw( biblionumber )]
210             },
211         )->unblessed
212     }
213 };
214
215 my $holds_biblios_map = {
216     map { $_->{biblionumber} => $_->{reserve_id} } @{ Koha::Holds->search(
217             {%where},
218             {
219                 join    => ['itembib', 'biblio'],
220                 select  => ['me.biblionumber', 'me.reserve_id'],
221                 order_by => { -desc => 'priority' }
222             }
223         )->unblessed
224     }
225 };
226
227 my $all_holds = {
228     map { $_->biblionumber => $_ } @{ Koha::Holds->search(
229             { reserve_id => [ values %$holds_biblios_map ]},
230             {
231                 prefetch => [ 'borrowernumber', 'itembib', 'biblio', 'item_group' ],
232             }
233         )->as_list
234     }
235 };
236
237 # make final holds_info array and fill with info
238 my @holds_info;
239 my $seen = {};
240 foreach my $bibnum ( @biblionumbers ){
241     # Skip this record if it's already been handled
242     next if $seen->{$bibnum};
243     $seen->{$bibnum} = 1;
244
245     my $hold_info;
246     my $items = $all_items->{$bibnum};
247     my $items_count = defined $items ? scalar @$items : 0;
248     my $pull_count = $items_count <= $patrons_count->{$bibnum} ? $items_count : $patrons_count->{$bibnum};
249     if ( $pull_count == 0 ) {
250         next;
251     }
252
253     # get available item types for each biblio
254     my @res_itemtypes;
255     if ( C4::Context->preference('item-level_itypes') ){
256         @res_itemtypes = uniq map { defined $_->itype ? $_->itype : () } @$items;
257     } else {
258         @res_itemtypes = Koha::Biblioitems->search(
259             { biblionumber => $bibnum, itemtype => { '!=', undef }  },
260             { columns => 'itemtype',
261               distinct => 1,
262             }
263         )->get_column('itemtype');
264     }
265     $hold_info->{itemtypes} = \@res_itemtypes;
266
267     my $res_info = $all_holds->{$bibnum};
268
269     # get available values for each biblio
270     my $fields = {
271         collections     => 'ccode',
272         locations       => 'location',
273         callnumbers     => 'itemcallnumber',
274         enumchrons      => 'enumchron',
275         copynumbers     => 'copynumber',
276         barcodes        => 'barcode',
277         holdingbranches => 'holdingbranch'
278     };
279
280     while (
281         my ( $key, $field ) = each %$fields )
282     {
283         $hold_info->{$key} =
284           [ uniq map { defined $_->$field ? $_->$field : () } @$items ];
285     }
286
287     if ( $res_info->item_group ) {
288        $hold_info->{barcodes} = [ uniq map { defined $_->barcode && $_->item_group && ( $_->item_group->id == $res_info->item_group_id )  ? $_->barcode : () } @$items ];
289     }
290
291     # items available
292     $hold_info->{items_count} = $items_count;
293
294     # patrons with holds
295     $hold_info->{patrons_count} = $patrons_count->{$bibnum};
296
297     # number of items to pull
298     $hold_info->{pull_count} = $pull_count;
299
300     # get other relevant information
301     $hold_info->{patron} = $res_info->patron;
302     $hold_info->{item}   = $res_info->item;
303     $hold_info->{biblio} = $res_info->biblio;
304     $hold_info->{hold}   = $res_info;
305     $hold_info->{item_group} = $res_info->item_group;
306
307     push @holds_info, $hold_info;
308 }
309
310 $template->param(
311     todaysdate          => $today,
312     from                => $startdate,
313     to                  => $enddate,
314     holds_info          => \@holds_info,
315     HoldsToPullStartDate => C4::Context->preference('HoldsToPullStartDate') || PULL_INTERVAL,
316     HoldsToPullEndDate  => C4::Context->preference('ConfirmFutureHolds') || 0,
317     messages            => \@messages,
318 );
319
320 output_html_with_http_headers $input, $cookie, $template->output;