Bug 30650: Add circulation page view
[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 C4::Reserves qw( ModReserveCancelAll );
33 use Koha::Biblios;
34 use Koha::DateUtils qw( dt_from_string );
35 use Koha::Holds;
36 use DateTime::Duration;
37
38 my $input = CGI->new;
39 my $startdate = $input->param('from');
40 my $enddate = $input->param('to');
41 my $theme = $input->param('theme');    # only used if allowthemeoverride is set
42 my $op         = $input->param('op') || '';
43 my $borrowernumber = $input->param('borrowernumber');
44 my $reserve_id = $input->param('reserve_id');
45
46 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
47     {
48         template_name   => "circ/pendingreserves.tt",
49         query           => $input,
50         type            => "intranet",
51         flagsrequired   => { circulate => "circulate_remaining_permissions" },
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 $from_address = $library->from_email_address;
88
89                 C4::Letters::EnqueueLetter(
90                     {   letter                 => $letter,
91                         borrowernumber         => $patron->borrowernumber,
92                         message_transport_type => 'email',
93                         from_address           => $from_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::XS::Load(Encode::encode_utf8($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     'me.found' => undef,
159     'me.priority' => { '!=' => 0 },
160     'me.suspend' => 0,
161     'itembib.itemlost' => 0,
162     'itembib.withdrawn' => 0,
163     'itembib.notforloan' => 0,
164     'itembib.itemnumber' => { -not_in => \'SELECT itemnumber FROM branchtransfers WHERE datearrived IS NULL AND datecancelled IS NULL' }
165 );
166
167 # date boundaries
168 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
169 my $startdate_iso = $dtf->format_date($startdate);
170 my $enddate_iso   = $dtf->format_date($enddate);
171 if ( $startdate_iso && $enddate_iso ){
172     $where{'me.reservedate'} = [ -and => { '>=', $startdate_iso }, { '<=', $enddate_iso } ];
173 } elsif ( $startdate_iso ){
174     $where{'me.reservedate'} = { '>=', $startdate_iso };
175 } elsif ( $enddate_iso ){
176     $where{'me.reservedate'} = { '<=', $enddate_iso };
177 }
178
179 # Bug 21320
180 if ( !C4::Context->preference('AllowHoldsOnDamagedItems') ){
181     $where{'itembib.damaged'} = 0;
182 }
183
184 if ( C4::Context->preference('IndependentBranches') ){
185     $where{'itembib.holdingbranch'} = C4::Context->userenv->{'branch'};
186 }
187
188 # get all distinct unfulfilled reserves
189 my $holds = Koha::Holds->search(
190     { %where },
191     { join => 'itembib', distinct => 1, columns => qw[me.biblionumber] }
192 );
193
194 my @biblionumbers = $holds->get_column('biblionumber');
195
196 my $all_items;
197 if ( $holds->count ) {
198     foreach my $item ( $holds->get_items_that_can_fill->as_list ) {
199         push @{ $all_items->{ $item->biblionumber } }, $item;
200     }
201 }
202
203 # patrons count per biblio
204 my $patrons_count = {
205     map { $_->{biblionumber} => $_->{patrons_count} } @{ Koha::Holds->search(
206             { 'suspend' => 0 },
207             {
208                 select   => [ 'biblionumber', { count => { distinct => 'borrowernumber' } } ],
209                 as       => [qw( biblionumber patrons_count )],
210                 group_by => [qw( biblionumber )]
211             },
212         )->unblessed
213     }
214 };
215
216 my $holds_biblios_map = {
217     map { $_->{biblionumber} => $_->{reserve_id} } @{ Koha::Holds->search(
218             {%where},
219             {
220                 join    => ['itembib', 'biblio'],
221                 select  => ['me.biblionumber', 'me.reserve_id'],
222                 order_by => { -desc => 'priority' }
223             }
224         )->unblessed
225     }
226 };
227
228 my $all_holds = {
229     map { $_->biblionumber => $_ } @{ Koha::Holds->search(
230             { reserve_id => [ values %$holds_biblios_map ]},
231             {
232                 prefetch => [ 'borrowernumber', 'itembib', 'biblio' ],
233             }
234         )->as_list
235     }
236 };
237
238 # make final holds_info array and fill with info
239 my @holds_info;
240 my $seen = {};
241 foreach my $bibnum ( @biblionumbers ){
242     # Skip this record if it's already been handled
243     next if $seen->{$bibnum};
244     $seen->{$bibnum} = 1;
245
246     my $hold_info;
247     my $items = $all_items->{$bibnum};
248     my $items_count = defined $items ? scalar @$items : 0;
249     my $pull_count = $items_count <= $patrons_count->{$bibnum} ? $items_count : $patrons_count->{$bibnum};
250     if ( $pull_count == 0 ) {
251         next;
252     }
253
254     # get available item types for each biblio
255     my @res_itemtypes;
256     if ( C4::Context->preference('item-level_itypes') ){
257         @res_itemtypes = uniq map { defined $_->itype ? $_->itype : () } @$items;
258     } else {
259         @res_itemtypes = Koha::Biblioitems->search(
260             { biblionumber => $bibnum, itemtype => { '!=', undef }  },
261             { columns => 'itemtype',
262               distinct => 1,
263             }
264         )->get_column('itemtype');
265     }
266     $hold_info->{itemtypes} = \@res_itemtypes;
267
268     # get available values for each biblio
269     my $fields = {
270         locations       => 'location',
271         callnumbers     => 'itemcallnumber',
272         enumchrons      => 'enumchron',
273         copynumbers     => 'copynumber',
274         barcodes        => 'barcode',
275         holdingbranches => 'holdingbranch'
276     };
277
278     while (
279         my ( $key, $field ) = each %$fields )
280     {
281         $hold_info->{$key} =
282           [ uniq map { defined $_->$field ? $_->$field : () } @$items ];
283     }
284
285     # items available
286     $hold_info->{items_count} = $items_count;
287
288     # patrons with holds
289     $hold_info->{patrons_count} = $patrons_count->{$bibnum};
290
291     # number of items to pull
292     $hold_info->{pull_count} = $pull_count;
293
294     # get other relevant information
295     my $res_info = $all_holds->{$bibnum};
296     $hold_info->{patron} = $res_info->patron;
297     $hold_info->{item}   = $res_info->item;
298     $hold_info->{biblio} = $res_info->biblio;
299     $hold_info->{hold}   = $res_info;
300
301     push @holds_info, $hold_info;
302 }
303
304 $template->param(
305     todaysdate          => $today,
306     from                => $startdate,
307     to                  => $enddate,
308     holds_info          => \@holds_info,
309     HoldsToPullStartDate => C4::Context->preference('HoldsToPullStartDate') || PULL_INTERVAL,
310     HoldsToPullEndDate  => C4::Context->preference('ConfirmFutureHolds') || 0,
311     messages            => \@messages,
312 );
313
314 output_html_with_http_headers $input, $cookie, $template->output;