Bug 27131: Add get_items_that_can_fill
[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;
29 use CGI qw ( -utf8 );
30 use C4::Auth;
31 use C4::Debug;
32 use C4::Items qw( ModItemTransfer );
33 use C4::Reserves qw( ModReserveCancelAll );
34 use Koha::Biblios;
35 use Koha::DateUtils;
36 use Koha::Holds;
37 use DateTime::Duration;
38
39 my $input = CGI->new;
40 my $startdate = $input->param('from');
41 my $enddate = $input->param('to');
42 my $theme = $input->param('theme');    # only used if allowthemeoverride is set
43 my $op         = $input->param('op') || '';
44 my $borrowernumber = $input->param('borrowernumber');
45 my $reserve_id = $input->param('reserve_id');
46
47 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
48     {
49         template_name   => "circ/pendingreserves.tt",
50         query           => $input,
51         type            => "intranet",
52         flagsrequired   => { circulate => "circulate_remaining_permissions" },
53         debug           => 1,
54     }
55 );
56
57 my @messages;
58 if ( $op eq 'cancel_reserve' and $reserve_id ) {
59     my $hold = Koha::Holds->find( $reserve_id );
60     if ( $hold ) {
61         my $cancellation_reason = $input->param('cancellation-reason');
62         $hold->cancel({ cancellation_reason => $cancellation_reason });
63         push @messages, { type => 'message', code => 'hold_cancelled' };
64     }
65 } elsif ( $op =~ m|^mark_as_lost| ) {
66     my $hold = Koha::Holds->find( $reserve_id );
67     die "wrong reserve_id" unless $hold; # This is a bit rude, but we are not supposed to get a wrong reserve_id
68     my $item = $hold->item;
69     if ( $item and C4::Context->preference('CanMarkHoldsToPullAsLost') =~ m|^allow| ) {
70         my $patron = $hold->borrower;
71         C4::Circulation::LostItem( $item->itemnumber, "pendingreserves" );
72         if ( $op eq 'mark_as_lost_and_notify' and C4::Context->preference('CanMarkHoldsToPullAsLost') eq 'allow_and_notify' ) {
73             my $library = $hold->branch;
74             my $letter = C4::Letters::GetPreparedLetter(
75                 module => 'reserves',
76                 letter_code => 'CANCEL_HOLD_ON_LOST',
77                 branchcode => $patron->branchcode,
78                 lang => $patron->lang,
79                 tables => {
80                     branches    => $library->branchcode,
81                     borrowers   => $patron->borrowernumber,
82                     items       => $item->itemnumber,
83                     biblio      => $hold->biblionumber,
84                     biblioitems => $hold->biblionumber,
85                     reserves    => $hold->unblessed,
86                 },
87             );
88             if ( $letter ) {
89                 my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
90
91                 C4::Letters::EnqueueLetter(
92                     {   letter                 => $letter,
93                         borrowernumber         => $patron->borrowernumber,
94                         message_transport_type => 'email',
95                         from_address           => $admin_email_address,
96                     }
97                 );
98                 unless ( $patron->notice_email_address ) {
99                     push @messages, {type => 'alert', code => 'no_email_address', };
100                 }
101                 push @messages, { type => 'message', code => 'letter_enqueued' };
102             } else {
103                 push @messages, { type => 'error', code => 'no_template_notice' };
104             }
105         }
106         $hold->cancel;
107         if ( $item->homebranch ne $item->holdingbranch ) {
108             C4::Items::ModItemTransfer( $item->itemnumber, $item->holdingbranch, $item->homebranch, 'LostReserve' );
109         }
110
111         if ( my $yaml = C4::Context->preference('UpdateItemWhenLostFromHoldList') ) {
112             $yaml = "$yaml\n\n";  # YAML is anal on ending \n. Surplus does not hurt
113             my $assignments;
114             eval { $assignments = YAML::XS::Load(Encode::encode_utf8($yaml)); };
115             if ($@) {
116                 warn "Unable to parse UpdateItemWhenLostFromHoldList syspref : $@" if $@;
117             }
118             else {
119                 eval {
120                     while ( my ( $f, $v ) = each( %$assignments ) ) {
121                         $item->$f($v);
122                     }
123                     $item->store;
124                 };
125                 warn "Unable to modify item itemnumber=" . $item->itemnumber . ": $@" if $@;
126             }
127         }
128
129     } elsif ( not $item ) {
130         push @messages, { type => 'alert', code => 'hold_placed_at_biblio_level'};
131     } # else the url parameters have been modified and the user is not allowed to continue
132 }
133
134
135 my $today = dt_from_string;
136
137 if ( $startdate ) {
138     $startdate =~ s/^\s+//;
139     $startdate =~ s/\s+$//;
140     $startdate = eval{dt_from_string( $startdate )};
141 }
142 unless ( $startdate ){
143     # changed from delivered range of 10 years-yesterday to 2 days ago-today
144     # Find two days ago for the default shelf pull start date, unless HoldsToPullStartDate sys pref is set.
145     $startdate = $today - DateTime::Duration->new( days => C4::Context->preference('HoldsToPullStartDate') || PULL_INTERVAL );
146 }
147
148 if ( $enddate ) {
149     $enddate =~ s/^\s+//;
150     $enddate =~ s/\s+$//;
151     $enddate = eval{dt_from_string( $enddate )};
152 }
153 unless ( $enddate ) {
154     #similarly: calculate end date with ConfirmFutureHolds (days)
155     $enddate = $today + DateTime::Duration->new( days => C4::Context->preference('ConfirmFutureHolds') || 0 );
156 }
157
158 # building query parameters
159 my %where = (
160     'reserve.found' => undef,
161     'reserve.priority' => 1,
162     'reserve.suspend' => 0,
163     'itembib.itemlost' => 0,
164     'itembib.withdrawn' => 0,
165     'itembib.notforloan' => 0,
166     'itembib.itemnumber' => { -not_in => \'SELECT itemnumber FROM branchtransfers WHERE datearrived IS NULL' }
167 );
168
169 # date boundaries
170 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
171 my $startdate_iso = $dtf->format_date($startdate);
172 my $enddate_iso   = $dtf->format_date($enddate);
173 if ( $startdate_iso && $enddate_iso ){
174     $where{'reserve.reservedate'} = [ -and => { '>=', $startdate_iso }, { '<=', $enddate_iso } ];
175 } elsif ( $startdate_iso ){
176     $where{'reserve.reservedate'} = { '>=', $startdate_iso };
177 } elsif ( $enddate_iso ){
178     $where{'reserve.reservedate'} = { '<=', $enddate_iso };
179 }
180
181 # Bug 21320
182 if ( !C4::Context->preference('AllowHoldsOnDamagedItems') ){
183     $where{'itembib.damaged'} = 0;
184 }
185
186 if ( C4::Context->preference('IndependentBranches') ){
187     $where{'itembib.holdingbranch'} = C4::Context->userenv->{'branch'};
188 }
189
190 # get all distinct unfulfilled reserves
191 my $holds = Koha::Holds->search(
192     { %where },
193     { join => 'itembib', alias => 'reserve', distinct  => 1, columns => qw[me.biblionumber] }
194 );
195 my @biblionumbers = $holds->get_column('biblionumber');
196
197 my $all_items;
198 foreach my $item ( $holds->get_items_that_can_fill ) {
199     push @{$all_items->{$item->biblionumber}}, $item;
200 }
201
202 # patrons count per biblio
203 my $patrons_count = {
204     map { $_->{biblionumber} => $_->{patrons_count} } @{ Koha::Holds->search(
205             {},
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                 alias   => 'reserve',
221                 select  => ['reserve.biblionumber', 'reserve.reserve_id'],
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' ],
232                 alias    => 'reserve',
233             }
234         )->as_list
235     }
236 };
237
238 # make final holds_info array and fill with info
239 my @holds_info;
240 foreach my $bibnum ( @biblionumbers ){
241
242     my $hold_info;
243     my $items = $all_items->{$bibnum};
244     my $items_count = defined $items ? scalar @$items : 0;
245     my $pull_count = $items_count <= $patrons_count->{$bibnum} ? $items_count : $patrons_count->{$bibnum};
246     if ( $pull_count == 0 ) {
247         next;
248     }
249
250     # get available item types for each biblio
251     my @res_itemtypes;
252     if ( C4::Context->preference('item-level_itypes') ){
253         @res_itemtypes = uniq map { defined $_->itype ? $_->itype : () } @$items;
254     } else {
255         @res_itemtypes = Koha::Biblioitems->search(
256             { biblionumber => $bibnum, itemtype => { '!=', undef }  },
257             { columns => 'itemtype',
258               distinct => 1,
259             }
260         )->get_column('itemtype');
261     }
262     $hold_info->{itemtypes} = \@res_itemtypes;
263
264     # get available values for each biblio
265     my $fields = {
266         locations       => 'location',
267         callnumbers     => 'itemcallnumber',
268         enumchrons      => 'enumchron',
269         copynumbers     => 'copynumber',
270         barcodes        => 'barcode',
271         holdingbranches => 'holdingbranch'
272     };
273
274     while (
275         my ( $key, $field ) = each %$fields )
276     {
277         $hold_info->{$key} =
278           [ uniq map { defined $_->$field ? $_->$field : () } @$items ];
279     }
280
281     # items available
282     $hold_info->{items_count} = $items_count;
283
284     # patrons with holds
285     $hold_info->{patrons_count} = $patrons_count->{$bibnum};
286
287     # number of items to pull
288     $hold_info->{pull_count} = $pull_count;
289
290     # get other relevant information
291     my $res_info = $all_holds->{$bibnum};
292     $hold_info->{patron} = $res_info->patron;
293     $hold_info->{item}   = $res_info->item;
294     $hold_info->{biblio} = $res_info->biblio;
295     $hold_info->{hold}   = $res_info;
296
297     push @holds_info, $hold_info;
298 }
299
300 $template->param(
301     todaysdate          => $today,
302     from                => $startdate,
303     to                  => $enddate,
304     holds_info          => \@holds_info,
305     "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
306     HoldsToPullStartDate => C4::Context->preference('HoldsToPullStartDate') || PULL_INTERVAL,
307     HoldsToPullEndDate  => C4::Context->preference('ConfirmFutureHolds') || 0,
308     messages            => \@messages,
309 );
310
311 output_html_with_http_headers $input, $cookie, $template->output;