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