Bug 24612: Make hold-transfer-slip take reserve_id
[koha.git] / circ / circulation.pl
1 #!/usr/bin/perl
2
3 # script to execute issuing of books
4
5 # Copyright 2000-2002 Katipo Communications
6 # copyright 2010 BibLibre
7 # Copyright 2011 PTFS-Europe Ltd.
8 # Copyright 2012 software.coop and MJ Ray
9 #
10 # This file is part of Koha.
11 #
12 # Koha is free software; you can redistribute it and/or modify it
13 # under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 3 of the License, or
15 # (at your option) any later version.
16 #
17 # Koha is distributed in the hope that it will be useful, but
18 # WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # GNU General Public License for more details.
21 #
22 # You should have received a copy of the GNU General Public License
23 # along with Koha; if not, see <http://www.gnu.org/licenses>.
24
25 # FIXME There are too many calls to Koha::Patrons->find in this script
26
27 use Modern::Perl;
28 use CGI qw ( -utf8 );
29 use DateTime;
30 use DateTime::Duration;
31 use Scalar::Util qw( looks_like_number );
32 use C4::Output;
33 use C4::Auth qw/:DEFAULT get_session haspermission/;
34 use C4::Koha;
35 use C4::Circulation;
36 use C4::Utils::DataTables::Members;
37 use C4::Members;
38 use C4::Biblio;
39 use C4::Search;
40 use MARC::Record;
41 use C4::Reserves;
42 use Koha::Holds;
43 use C4::Context;
44 use CGI::Session;
45 use Koha::AuthorisedValues;
46 use Koha::CsvProfiles;
47 use Koha::Patrons;
48 use Koha::Patron::Debarments qw(GetDebarments);
49 use Koha::DateUtils;
50 use Koha::Database;
51 use Koha::BiblioFrameworks;
52 use Koha::Items;
53 use Koha::Patron::Messages;
54 use Koha::SearchEngine;
55 use Koha::SearchEngine::Search;
56 use Koha::Patron::Modifications;
57
58 use Date::Calc qw(
59   Today
60   Add_Delta_Days
61   Date_to_Days
62 );
63 use List::MoreUtils qw/uniq/;
64
65 #
66 # PARAMETERS READING
67 #
68 my $query = new CGI;
69
70 my $override_high_holds     = $query->param('override_high_holds');
71 my $override_high_holds_tmp = $query->param('override_high_holds_tmp');
72
73 my $sessionID = $query->cookie("CGISESSID") ;
74 my $session = get_session($sessionID);
75
76 my $barcodes = [];
77 my $barcode =  $query->param('barcode');
78 my $findborrower;
79 my $autoswitched;
80 my $borrowernumber = $query->param('borrowernumber');
81
82 if (C4::Context->preference("AutoSwitchPatron") && $barcode) {
83     if (Koha::Patrons->search( { cardnumber => $barcode} )->count() > 0) {
84         $findborrower = $barcode;
85         undef $barcode;
86         undef $borrowernumber;
87         $autoswitched = 1;
88     }
89 }
90 $findborrower ||= $query->param('findborrower') || q{};
91 $findborrower =~ s|,| |g;
92
93 # Barcode given by user could be '0'
94 if ( $barcode || ( defined($barcode) && $barcode eq '0' ) ) {
95     $barcodes = [ $barcode ];
96 } else {
97     my $filefh = $query->upload('uploadfile');
98     if ( $filefh ) {
99         while ( my $content = <$filefh> ) {
100             $content =~ s/[\r\n]*$//g;
101             push @$barcodes, $content if $content;
102         }
103     } elsif ( my $list = $query->param('barcodelist') ) {
104         push @$barcodes, split( /\s\n/, $list );
105         $barcodes = [ map { $_ =~ /^\s*$/ ? () : $_ } @$barcodes ];
106     } else {
107         @$barcodes = $query->multi_param('barcodes');
108     }
109 }
110
111 $barcodes = [ uniq @$barcodes ];
112
113 my $template_name = q|circ/circulation.tt|;
114 my $patron = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : undef;
115 my $batch = $query->param('batch');
116 my $batch_allowed = 0;
117 if ( $batch && C4::Context->preference('BatchCheckouts') ) {
118     $template_name = q|circ/circulation_batch_checkouts.tt|;
119     my @batch_category_codes = split '\|', C4::Context->preference('BatchCheckoutsValidCategories');
120     my $categorycode = $patron->categorycode;
121     if ( $categorycode && grep { $_ eq $categorycode } @batch_category_codes ) {
122         $batch_allowed = 1;
123     } else {
124         $barcodes = [];
125     }
126 }
127
128 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
129     {
130         template_name   => $template_name,
131         query           => $query,
132         type            => "intranet",
133         authnotrequired => 0,
134         flagsrequired   => { circulate => 'circulate_remaining_permissions' },
135     }
136 );
137 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
138
139 my $force_allow_issue = $query->param('forceallow') || 0;
140 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
141     $force_allow_issue = 0;
142 }
143 my $onsite_checkout = $query->param('onsite_checkout');
144
145 if (C4::Context->preference("OnSiteCheckoutAutoCheck") && $onsite_checkout eq "on") {
146     $template->param(onsite_checkout => $onsite_checkout);
147 }
148
149 my @failedrenews = $query->multi_param('failedrenew');    # expected to be itemnumbers
150 our %renew_failed = ();
151 for (@failedrenews) { $renew_failed{$_} = 1; }
152
153 my @failedreturns = $query->multi_param('failedreturn');
154 our %return_failed = ();
155 for (@failedreturns) { $return_failed{$_} = 1; }
156
157 my $searchtype = $query->param('searchtype') || q{contain};
158
159 my $branch = C4::Context->userenv->{'branch'};
160
161 if (C4::Context->preference("DisplayClearScreenButton")) {
162     $template->param(DisplayClearScreenButton => 1);
163 }
164
165 for my $barcode ( @$barcodes ) {
166     $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
167     $barcode = barcodedecode($barcode)
168         if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
169 }
170
171 my $stickyduedate  = $query->param('stickyduedate') || $session->param('stickyduedate');
172 my $duedatespec    = $query->param('duedatespec')   || $session->param('stickyduedate');
173 $duedatespec = eval { output_pref( { dt => dt_from_string( $duedatespec ), dateformat => 'iso' }); }
174     if ( $duedatespec );
175 my $restoreduedatespec  = $query->param('restoreduedatespec') || $duedatespec || $session->param('stickyduedate');
176 if ( $restoreduedatespec && $restoreduedatespec eq "highholds_empty" ) {
177     undef $restoreduedatespec;
178 }
179 my $issueconfirmed = $query->param('issueconfirmed');
180 my $cancelreserve  = $query->param('cancelreserve');
181 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
182 my $charges        = $query->param('charges') || q{};
183
184 # Check if stickyduedate is turned off
185 if ( @$barcodes ) {
186     # was stickyduedate loaded from session?
187     if ( $stickyduedate && ! $query->param("stickyduedate") ) {
188         $session->clear( 'stickyduedate' );
189         $stickyduedate  = $query->param('stickyduedate');
190         $duedatespec    = $query->param('duedatespec');
191     }
192     $session->param('auto_renew', scalar $query->param('auto_renew'));
193 }
194 else {
195     $session->clear('auto_renew');
196 }
197
198 $template->param( auto_renew => $session->param('auto_renew') );
199
200 my ($datedue,$invalidduedate);
201
202 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
203 if( $onsite_checkout && !$duedatespec_allow ) {
204     $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
205     $datedue .= ' 23:59:00';
206 } elsif( $duedatespec_allow ) {
207     if ( $duedatespec ) {
208         $datedue = eval { dt_from_string( $duedatespec ) };
209         if (! $datedue ) {
210             $invalidduedate = 1;
211             $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec );
212         }
213     }
214 }
215
216 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
217 if ( @$barcodes == 0 && $charges eq 'yes' ) {
218     $template->param(
219         PAYCHARGES     => 'yes',
220         borrowernumber => $borrowernumber
221     );
222 }
223
224 #
225 # STEP 2 : FIND BORROWER
226 # if there is a list of find borrowers....
227 #
228 my $message;
229 if ($findborrower) {
230     my $patron = Koha::Patrons->find( { cardnumber => $findborrower } );
231     if ( $patron ) {
232         $borrowernumber = $patron->borrowernumber;
233     } else {
234         my $dt_params = { iDisplayLength => -1 };
235         my $results = C4::Utils::DataTables::Members::search(
236             {
237                 searchmember => $findborrower,
238                 searchtype   => $searchtype,
239                 dt_params    => $dt_params,
240             }
241         );
242         my $borrowers = $results->{patrons};
243         if ( scalar @$borrowers == 1 ) {
244             $borrowernumber = $borrowers->[0]->{borrowernumber};
245             $query->param( 'borrowernumber', $borrowernumber );
246             $query->param( 'barcode',           '' );
247         } elsif ( @$borrowers ) {
248             $template->param( borrowers => $borrowers );
249         } else {
250             $query->param( 'findborrower', '' );
251             $message = "'$findborrower'";
252         }
253     }
254 }
255
256 # get the borrower information.....
257 my $balance = 0;
258 $patron ||= Koha::Patrons->find( $borrowernumber ) if $borrowernumber;
259 if ($patron) {
260
261     $template->param( borrowernumber => $patron->borrowernumber );
262     output_and_exit_if_error( $query, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
263
264     my $overdues = $patron->get_overdues;
265     my $issues = $patron->checkouts;
266     $balance = $patron->account->balance;
267
268
269     # if the expiry date is before today ie they have expired
270     if ( $patron->is_expired ) {
271         #borrowercard expired, no issues
272         $template->param(
273             noissues => ($force_allow_issue) ? 0 : "1",
274             forceallow => $force_allow_issue,
275             expired => "1",
276         );
277     }
278     # check for NotifyBorrowerDeparture
279     elsif ( $patron->is_going_to_expire ) {
280         # borrower card soon to expire warn librarian
281         $template->param( "warndeparture" => $patron->dateexpiry ,
282                         );
283         if (C4::Context->preference('ReturnBeforeExpiry')){
284             $template->param("returnbeforeexpiry" => 1);
285         }
286     }
287     $template->param(
288         overduecount => $overdues->count,
289         issuecount   => $issues->count,
290         finetotal    => $balance,
291     );
292
293     if ( $patron and $patron->is_debarred ) {
294         $template->param(
295             'userdebarred'    => $patron->debarred,
296             'debarredcomment' => $patron->debarredcomment,
297         );
298
299         if ( $patron->debarred ne "9999-12-31" ) {
300             $template->param( 'userdebarreddate' => $patron->debarred );
301         }
302     }
303
304     # Calculate and display patron's age
305     if ( !$patron->is_valid_age ) {
306         $template->param( age_limitations => 1 );
307         $template->param( age_low => $patron->category->dateofbirthrequired );
308         $template->param( age_high => $patron->category->upperagelimit );
309     }
310
311 }
312
313 #
314 # STEP 3 : ISSUING
315 #
316 #
317 if (@$barcodes) {
318   my $checkout_infos;
319   for my $barcode ( @$barcodes ) {
320
321     my $template_params = {
322         barcode         => $barcode,
323         onsite_checkout => $onsite_checkout,
324     };
325
326     # always check for blockers on issuing
327     my ( $error, $question, $alerts, $messages ) = CanBookBeIssued(
328         $patron,
329         $barcode, $datedue,
330         $inprocess,
331         undef,
332         {
333             onsite_checkout     => $onsite_checkout,
334             override_high_holds => $override_high_holds || $override_high_holds_tmp || 0,
335         }
336     );
337
338     my $blocker = $invalidduedate ? 1 : 0;
339
340     $template_params->{alert} = $alerts;
341     $template_params->{messages} = $messages;
342
343     my $item = Koha::Items->find({ barcode => $barcode });
344
345     my $biblio;
346     if ( $item ) {
347         $biblio = $item->biblio;
348     }
349
350     # Fix for bug 7494: optional checkout-time fallback search for a book
351
352     if ( $error->{'UNKNOWN_BARCODE'}
353         && C4::Context->preference("itemBarcodeFallbackSearch")
354         && not $batch
355     )
356     {
357      $template_params->{FALLBACK} = 1;
358
359         my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
360         my $query = "kw=" . $barcode;
361         my ( $searcherror, $results, $total_hits ) = $searcher->simple_search_compat($query, 0, 10);
362
363         # if multiple hits, offer options to librarian
364         if ( $total_hits > 0 ) {
365             my @options = ();
366             foreach my $hit ( @{$results} ) {
367                 my $chosen =
368                   TransformMarcToKoha( C4::Search::new_record_from_zebra('biblioserver',$hit) );
369
370                 # offer all barcodes individually
371                 if ( $chosen->{barcode} ) {
372                     foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
373                         my %chosen_single = %{$chosen};
374                         $chosen_single{barcode} = $barcode;
375                         push( @options, \%chosen_single );
376                     }
377                 }
378             }
379             $template_params->{options} = \@options;
380         }
381     }
382
383     if ( $error->{UNKNOWN_BARCODE} or not $onsite_checkout or not C4::Context->preference("OnSiteCheckoutsForce") ) {
384         delete $question->{'DEBT'} if ($debt_confirmed);
385         foreach my $impossible ( keys %$error ) {
386             $template_params->{$impossible} = $$error{$impossible};
387             $template_params->{IMPOSSIBLE} = 1;
388             $blocker = 1;
389         }
390     }
391
392     if( $item and ( !$blocker or $force_allow_issue ) ){
393         my $confirm_required = 0;
394         unless($issueconfirmed){
395             #  Get the item title for more information
396             my $materials = $item->materials;
397             my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({ frameworkcode => $biblio->frameworkcode, kohafield => 'items.materials', authorised_value => $materials });
398             $materials = $descriptions->{lib} // $materials;
399             $template_params->{additional_materials} = $materials;
400             $template_params->{itemhomebranch} = $item->homebranch;
401
402             # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
403             foreach my $needsconfirmation ( keys %$question ) {
404                 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
405                 $template_params->{getTitleMessageIteminfo} = $biblio->title;
406                 $template_params->{getBarcodeMessageIteminfo} = $item->barcode;
407                 $template_params->{NEEDSCONFIRMATION} = 1;
408                 $confirm_required = 1;
409             }
410         }
411         unless($confirm_required) {
412             my $switch_onsite_checkout = exists $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED};
413             my $issue = AddIssue( $patron->unblessed, $barcode, $datedue, $cancelreserve, undef, undef, { onsite_checkout => $onsite_checkout, auto_renew => $session->param('auto_renew'), switch_onsite_checkout => $switch_onsite_checkout, } );
414             $template_params->{issue} = $issue;
415             $session->clear('auto_renew');
416             $inprocess = 1;
417         }
418     }
419
420     if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
421         $template->param(
422             reserveborrowernumber => $question->{'resborrowernumber'},
423             reserve_id => $question->{reserve_id},
424         );
425     }
426
427
428     # FIXME If the issue is confirmed, we launch another time checkouts->count, now display the issue count after issue
429     $patron = Koha::Patrons->find( $borrowernumber );
430     $template_params->{issuecount} = $patron->checkouts->count;
431
432     if ( $item ) {
433         $template_params->{item} = $item;
434         $template_params->{biblio} = $biblio;
435         $template_params->{itembiblionumber} = $biblio->biblionumber;
436     }
437     push @$checkout_infos, $template_params;
438   }
439   unless ( $batch ) {
440     $template->param( %{$checkout_infos->[0]} );
441     $template->param( barcode => $barcodes->[0] );
442   } else {
443     my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
444     $template->param(
445         checkout_infos => $checkout_infos,
446         confirmation_needed => $confirmation_needed,
447     );
448   }
449 }
450
451 ##################################################################################
452 # BUILD HTML
453 # show all reserves of this borrower, and the position of the reservation ....
454 if ($patron) {
455     my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } ); # FIXME must be Koha::Patron->holds
456     my $waiting_holds = $holds->waiting;
457     $template->param(
458         holds_count  => $holds->count(),
459         WaitingHolds => $waiting_holds,
460     );
461 }
462
463 if ( $patron ) {
464     my $noissues;
465     if ( $patron->gonenoaddress ) {
466         $template->param( gna => 1 );
467         $noissues = 1;
468     }
469     if ( $patron->lost ) {
470         $template->param( lost=> 1 );
471         $noissues = 1;
472     }
473     if ( $patron->is_debarred ) {
474         $template->param( dbarred=> 1 );
475         $noissues = 1;
476     }
477     my $account = $patron->account;
478     if( ( my $owing = $account->non_issues_charges ) > 0 ) {
479         my $noissuescharge = C4::Context->preference("noissuescharge") || 5; # FIXME If noissuescharge == 0 then 5, why??
480         $noissues ||= ( not C4::Context->preference("AllowFineOverride") and ( $owing > $noissuescharge ) );
481         $template->param(
482             charges => 1,
483             chargesamount => $owing,
484         )
485     } elsif ( $balance < 0 ) {
486         $template->param(
487             credits => 1,
488             creditsamount => -$balance,
489         );
490     }
491
492     my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
493     $no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
494     if ( defined $no_issues_charge_guarantees ) {
495         my $guarantees_non_issues_charges = 0;
496         my $guarantees = $patron->guarantee_relationships->guarantees;
497         while ( my $g = $guarantees->next ) {
498             $guarantees_non_issues_charges += $g->account->non_issues_charges;
499         }
500         if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
501             $template->param(
502                 charges_guarantees    => 1,
503                 chargesamount_guarantees => $guarantees_non_issues_charges,
504             );
505             $noissues = 1 unless C4::Context->preference("allowfineoverride");
506         }
507     }
508
509     if ( $patron->has_overdues ) {
510         $template->param( odues => 1 );
511     }
512
513     if ( $patron->borrowernotes ) {
514         my $borrowernotes = $patron->borrowernotes;
515         $borrowernotes =~ s#\n#<br />#g;
516         $template->param(
517             notes =>1,
518             notesmsg => $borrowernotes,
519         )
520     }
521
522     if ( $noissues ) {
523         $template->param(
524             noissues => ($force_allow_issue) ? 0 : 'true',
525             forceallow => $force_allow_issue,
526         );
527     }
528 }
529
530 my $messages = Koha::Patron::Messages->search(
531     {
532         'me.borrowernumber' => $borrowernumber,
533     },
534     {
535        join => 'manager',
536        '+select' => ['manager.surname', 'manager.firstname' ],
537        '+as' => ['manager_surname', 'manager_firstname'],
538     }
539 );
540
541 my $fast_cataloging = 0;
542 if ( Koha::BiblioFrameworks->find('FA') ) {
543     $fast_cataloging = 1 
544 }
545
546 my $view = $batch
547     ?'batch_checkout_view'
548     : 'circview';
549
550 my @relatives;
551 if ( $patron ) {
552     if ( my @guarantors = $patron->guarantor_relationships()->guarantors() ) {
553         push( @relatives, $_->id ) for @guarantors;
554         push( @relatives, $_->id ) for $patron->siblings();
555     } else {
556         push( @relatives, $_->id ) for $patron->guarantee_relationships()->guarantees();
557     }
558 }
559 my $relatives_issues_count =
560   Koha::Database->new()->schema()->resultset('Issue')
561   ->count( { borrowernumber => \@relatives } );
562
563 if ( $patron ) {
564     my $av = Koha::AuthorisedValues->search({ category => 'ROADTYPE', authorised_value => $patron->streettype });
565     my $roadtype = $av->count ? $av->next->lib : '';
566     $template->param(
567         roadtype          => $roadtype,
568         patron            => $patron,
569         categoryname      => $patron->category->description,
570         expiry            => $patron->dateexpiry,
571     );
572 }
573
574 # Restore date if changed by holds and/or save stickyduedate to session
575 if ($restoreduedatespec || $stickyduedate) {
576     $duedatespec = $restoreduedatespec || $duedatespec;
577
578     if ($stickyduedate) {
579         $session->param( 'stickyduedate', $duedatespec );
580     }
581 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
582     undef $duedatespec;
583 }
584
585 $template->param(
586     messages           => $messages,
587     borrowernumber    => $borrowernumber,
588     branch            => $branch,
589     was_renewed       => scalar $query->param('was_renewed') ? 1 : 0,
590     barcodes          => $barcodes,
591     stickyduedate     => $stickyduedate,
592     duedatespec       => $duedatespec,
593     restoreduedatespec => $restoreduedatespec,
594     message           => $message,
595     totaldue          => sprintf('%.2f', $balance), # FIXME not used in template?
596     inprocess         => $inprocess,
597     $view             => 1,
598     batch_allowed     => $batch_allowed,
599     batch             => $batch,
600     AudioAlerts           => C4::Context->preference("AudioAlerts"),
601     fast_cataloging   => $fast_cataloging,
602     CircAutoPrintQuickSlip   => C4::Context->preference("CircAutoPrintQuickSlip"),
603     RoutingSerials => C4::Context->preference('RoutingSerials'),
604     relatives_issues_count => $relatives_issues_count,
605     relatives_borrowernumbers => \@relatives,
606 );
607
608
609 if ( C4::Context->preference("ExportCircHistory") ) {
610     $template->param(csv_profiles => [ Koha::CsvProfiles->search({ type => 'marc' }) ]);
611 }
612
613 my $has_modifications = Koha::Patron::Modifications->search( { borrowernumber => $borrowernumber } )->count;
614 $template->param(
615     debt_confirmed            => $debt_confirmed,
616     SpecifyDueDate            => $duedatespec_allow,
617     PatronAutoComplete      => C4::Context->preference("PatronAutoComplete"),
618     debarments                => scalar GetDebarments({ borrowernumber => $borrowernumber }),
619     todaysdate                => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
620     has_modifications         => $has_modifications,
621     override_high_holds       => $override_high_holds,
622     nopermission              => scalar $query->param('nopermission'),
623     autoswitched              => $autoswitched,
624     logged_in_user            => $logged_in_user,
625 );
626
627 output_html_with_http_headers $query, $cookie, $template->output;