Bug 15752: (follow-up) Search for patrons only if param barcode is defined
[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 C4::Output;
32 use C4::Print;
33 use C4::Auth qw/:DEFAULT get_session haspermission/;
34 use C4::Koha;   # GetPrinter
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 C4::Members::Attributes qw(GetBorrowerAttributes);
46 use Koha::AuthorisedValues;
47 use Koha::CsvProfiles;
48 use Koha::Patrons;
49 use Koha::Patron::Debarments qw(GetDebarments);
50 use Koha::DateUtils;
51 use Koha::Database;
52 use Koha::BiblioFrameworks;
53 use Koha::Items;
54 use Koha::Patron::Messages;
55 use Koha::SearchEngine;
56 use Koha::SearchEngine::Search;
57 use Koha::Patron::Modifications;
58
59 use Date::Calc qw(
60   Today
61   Add_Delta_Days
62   Date_to_Days
63 );
64 use List::MoreUtils qw/uniq/;
65
66 #
67 # PARAMETERS READING
68 #
69 my $query = new CGI;
70
71 my $override_high_holds     = $query->param('override_high_holds');
72 my $override_high_holds_tmp = $query->param('override_high_holds_tmp');
73
74 my $sessionID = $query->cookie("CGISESSID") ;
75 my $session = get_session($sessionID);
76 if (!C4::Context->userenv){
77     if ($session->param('branch') eq 'NO_LIBRARY_SET'){
78         # no branch set we can't issue
79         print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
80         exit;
81     }
82 }
83
84 my $barcodes = [];
85 my $barcode =  $query->param('barcode');
86
87 if (C4::Context->preference("AutoSwitchPatron") && $barcode) {
88     if (Koha::Patrons->search( { cardnumber => $barcode} )->count() > 0) {
89         print $query->redirect("/cgi-bin/koha/circ/circulation.pl?findborrower=".$barcode);
90     }
91 }
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 $borrowernumber = $query->param('borrowernumber');
115 my $patron = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : undef;
116 my $batch = $query->param('batch');
117 my $batch_allowed = 0;
118 if ( $batch && C4::Context->preference('BatchCheckouts') ) {
119     $template_name = q|circ/circulation_batch_checkouts.tt|;
120     my @batch_category_codes = split '\|', C4::Context->preference('BatchCheckoutsValidCategories');
121     my $categorycode = $patron->categorycode;
122     if ( $categorycode && grep {/^$categorycode$/} @batch_category_codes ) {
123         $batch_allowed = 1;
124     } else {
125         $barcodes = [];
126     }
127 }
128
129 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
130     {
131         template_name   => $template_name,
132         query           => $query,
133         type            => "intranet",
134         authnotrequired => 0,
135         flagsrequired   => { circulate => 'circulate_remaining_permissions' },
136     }
137 );
138 my $logged_in_user = Koha::Patrons->find( $loggedinuser ) or die "Not logged in";
139
140 my $force_allow_issue = $query->param('forceallow') || 0;
141 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
142     $force_allow_issue = 0;
143 }
144
145 my $onsite_checkout = $query->param('onsite_checkout');
146
147 my @failedrenews = $query->multi_param('failedrenew');    # expected to be itemnumbers
148 our %renew_failed = ();
149 for (@failedrenews) { $renew_failed{$_} = 1; }
150
151 my @failedreturns = $query->multi_param('failedreturn');
152 our %return_failed = ();
153 for (@failedreturns) { $return_failed{$_} = 1; }
154
155 my $searchtype = $query->param('searchtype') || q{contain};
156
157 my $findborrower = $query->param('findborrower') || q{};
158 $findborrower =~ s|,| |g;
159
160 my $branch = C4::Context->userenv->{'branch'};
161
162 if (C4::Context->preference("DisplayClearScreenButton")) {
163     $template->param(DisplayClearScreenButton => 1);
164 }
165
166 for my $barcode ( @$barcodes ) {
167     $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
168     $barcode = barcodedecode($barcode)
169         if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
170 }
171
172 my $stickyduedate  = $query->param('stickyduedate') || $session->param('stickyduedate');
173 my $duedatespec    = $query->param('duedatespec')   || $session->param('stickyduedate');
174 $duedatespec = eval { output_pref( { dt => dt_from_string( $duedatespec ), dateformat => 'iso', timeformat => '24hr' }); }
175     if ( $duedatespec );
176 my $restoreduedatespec  = $query->param('restoreduedatespec') || $duedatespec || $session->param('stickyduedate');
177 if ( $restoreduedatespec && $restoreduedatespec eq "highholds_empty" ) {
178     undef $restoreduedatespec;
179 }
180 my $issueconfirmed = $query->param('issueconfirmed');
181 my $cancelreserve  = $query->param('cancelreserve');
182 my $print          = $query->param('print') || q{};
183 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
184 my $charges        = $query->param('charges') || q{};
185
186 # Check if stickyduedate is turned off
187 if ( @$barcodes ) {
188     # was stickyduedate loaded from session?
189     if ( $stickyduedate && ! $query->param("stickyduedate") ) {
190         $session->clear( 'stickyduedate' );
191         $stickyduedate  = $query->param('stickyduedate');
192         $duedatespec    = $query->param('duedatespec');
193     }
194     $session->param('auto_renew', scalar $query->param('auto_renew'));
195 }
196 else {
197     $session->clear('auto_renew');
198 }
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 # check and see if we should print
217 if ( @$barcodes == 0 && $print eq 'maybe' ) {
218     $print = 'yes';
219 }
220
221 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
222 if ( @$barcodes == 0 && $charges eq 'yes' ) {
223     $template->param(
224         PAYCHARGES     => 'yes',
225         borrowernumber => $borrowernumber
226     );
227 }
228
229 if ( $print eq 'yes' && $borrowernumber ne '' ) {
230     if ( C4::Context->boolean_preference('printcirculationslips') ) {
231         my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
232         NetworkPrint($letter->{content});
233     }
234     $query->param( 'borrowernumber', '' );
235     $borrowernumber = '';
236 }
237
238 #
239 # STEP 2 : FIND BORROWER
240 # if there is a list of find borrowers....
241 #
242 my $message;
243 if ($findborrower) {
244     my $patron = Koha::Patrons->find( { cardnumber => $findborrower } );
245     if ( $patron ) {
246         $borrowernumber = $patron->borrowernumber;
247     } else {
248         my $dt_params = { iDisplayLength => -1 };
249         my $results = C4::Utils::DataTables::Members::search(
250             {
251                 searchmember => $findborrower,
252                 searchtype   => $searchtype,
253                 dt_params    => $dt_params,
254             }
255         );
256         my $borrowers = $results->{patrons};
257         if ( scalar @$borrowers == 1 ) {
258             $borrowernumber = $borrowers->[0]->{borrowernumber};
259             $query->param( 'borrowernumber', $borrowernumber );
260             $query->param( 'barcode',           '' );
261         } elsif ( @$borrowers ) {
262             $template->param( borrowers => $borrowers );
263         } else {
264             $query->param( 'findborrower', '' );
265             $message = "'$findborrower'";
266         }
267     }
268 }
269
270 # get the borrower information.....
271 $patron ||= Koha::Patrons->find( $borrowernumber ) if $borrowernumber;
272 if ($patron) {
273
274     $template->param( borrowernumber => $patron->borrowernumber );
275     output_and_exit_if_error( $query, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
276
277     my $overdues = $patron->get_overdues;
278     my $issues = $patron->checkouts;
279     my $balance = $patron->account->balance;
280
281
282     # if the expiry date is before today ie they have expired
283     if ( $patron->is_expired ) {
284         #borrowercard expired, no issues
285         $template->param(
286             noissues => ($force_allow_issue) ? 0 : "1",
287             forceallow => $force_allow_issue,
288             expired => "1",
289         );
290     }
291     # check for NotifyBorrowerDeparture
292     elsif ( $patron->is_going_to_expire ) {
293         # borrower card soon to expire warn librarian
294         $template->param( "warndeparture" => $patron->dateexpiry ,
295                         );
296         if (C4::Context->preference('ReturnBeforeExpiry')){
297             $template->param("returnbeforeexpiry" => 1);
298         }
299     }
300     $template->param(
301         overduecount => $overdues->count,
302         issuecount   => $issues->count,
303         finetotal    => $balance,
304     );
305
306     if ( $patron and $patron->is_debarred ) {
307         $template->param(
308             'userdebarred'    => $patron->debarred,
309             'debarredcomment' => $patron->debarredcomment,
310         );
311
312         if ( $patron->debarred ne "9999-12-31" ) {
313             $template->param( 'userdebarreddate' => $patron->debarred );
314         }
315     }
316
317 }
318
319 #
320 # STEP 3 : ISSUING
321 #
322 #
323 if (@$barcodes) {
324   my $checkout_infos;
325   for my $barcode ( @$barcodes ) {
326     my $template_params = { barcode => $barcode };
327     # always check for blockers on issuing
328     my ( $error, $question, $alerts, $messages ) = CanBookBeIssued(
329         $patron,
330         $barcode, $datedue,
331         $inprocess,
332         undef,
333         {
334             onsite_checkout     => $onsite_checkout,
335             override_high_holds => $override_high_holds || $override_high_holds_tmp || 0,
336         }
337     );
338
339     my $blocker = $invalidduedate ? 1 : 0;
340
341     $template_params->{alert} = $alerts;
342     $template_params->{messages} = $messages;
343
344     my $item = Koha::Items->find({ barcode => $barcode });
345     my ( $biblio, $mss );
346
347     if ( $item ) {
348         $biblio = $item->biblio;
349         my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $biblio->frameworkcode, kohafield => 'items.notforloan', authorised_value => { not => undef } });
350         $template_params->{authvalcode_notforloan} = $mss->count ? $mss->next->authorised_value : undef;
351     }
352
353     # Fix for bug 7494: optional checkout-time fallback search for a book
354
355     if ( $error->{'UNKNOWN_BARCODE'}
356         && C4::Context->preference("itemBarcodeFallbackSearch")
357         && not $batch
358     )
359     {
360      $template_params->{FALLBACK} = 1;
361
362         my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
363         my $query = "kw=" . $barcode;
364         my ( $searcherror, $results, $total_hits ) = $searcher->simple_search_compat($query, 0, 10);
365
366         # if multiple hits, offer options to librarian
367         if ( $total_hits > 0 ) {
368             my @options = ();
369             foreach my $hit ( @{$results} ) {
370                 my $chosen =
371                   TransformMarcToKoha( C4::Search::new_record_from_zebra('biblioserver',$hit) );
372
373                 # offer all barcodes individually
374                 if ( $chosen->{barcode} ) {
375                     foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
376                         my %chosen_single = %{$chosen};
377                         $chosen_single{barcode} = $barcode;
378                         push( @options, \%chosen_single );
379                     }
380                 }
381             }
382             $template_params->{options} = \@options;
383         }
384     }
385
386     if ( $error->{UNKNOWN_BARCODE} or not $onsite_checkout or not C4::Context->preference("OnSiteCheckoutsForce") ) {
387         delete $question->{'DEBT'} if ($debt_confirmed);
388         foreach my $impossible ( keys %$error ) {
389             $template_params->{$impossible} = $$error{$impossible};
390             $template_params->{IMPOSSIBLE} = 1;
391             $blocker = 1;
392         }
393     }
394
395     if( $item and ( !$blocker or $force_allow_issue ) ){
396         my $confirm_required = 0;
397         unless($issueconfirmed){
398             #  Get the item title for more information
399             my $materials = $item->materials;
400             my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({ frameworkcode => $biblio->frameworkcode, kohafield => 'items.materials', authorised_value => $materials });
401             $materials = $descriptions->{lib} // $materials;
402             $template_params->{additional_materials} = $materials;
403             $template_params->{itemhomebranch} = $item->homebranch;
404
405             # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
406             foreach my $needsconfirmation ( keys %$question ) {
407                 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
408                 $template_params->{getTitleMessageIteminfo} = $biblio->title;
409                 $template_params->{getBarcodeMessageIteminfo} = $item->barcode;
410                 $template_params->{NEEDSCONFIRMATION} = 1;
411                 $template_params->{onsite_checkout} = $onsite_checkout;
412                 $template_params->{auto_renew} = $session->param('auto_renew');
413                 $confirm_required = 1;
414             }
415         }
416         unless($confirm_required) {
417             my $switch_onsite_checkout = exists $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED};
418             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, } );
419             $template_params->{issue} = $issue;
420             $session->clear('auto_renew');
421             $inprocess = 1;
422         }
423     }
424
425     if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
426         $template->param(
427             reserveborrowernumber => $question->{'resborrowernumber'}
428         );
429     }
430
431
432     # FIXME If the issue is confirmed, we launch another time checkouts->count, now display the issue count after issue
433     $patron = Koha::Patrons->find( $borrowernumber );
434     $template_params->{issuecount} = $patron->checkouts->count;
435
436     if ( $item ) {
437         $template_params->{item} = $item;
438         $template_params->{biblio} = $biblio;
439         $template_params->{itembiblionumber} = $biblio->biblionumber;
440     }
441     push @$checkout_infos, $template_params;
442   }
443   unless ( $batch ) {
444     $template->param( %{$checkout_infos->[0]} );
445     $template->param( barcode => $barcodes->[0] );
446   } else {
447     my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
448     $template->param(
449         checkout_infos => $checkout_infos,
450         confirmation_needed => $confirmation_needed,
451     );
452   }
453 }
454
455 ##################################################################################
456 # BUILD HTML
457 # show all reserves of this borrower, and the position of the reservation ....
458 if ($patron) {
459     my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } ); # FIXME must be Koha::Patron->holds
460     my $waiting_holds = $holds->waiting;
461     $template->param(
462         holds_count  => $holds->count(),
463         WaitingHolds => $waiting_holds,
464     );
465
466     my $category_type = $patron->category->category_type;
467     $template->param( adultborrower => 1 ) if ( $category_type eq 'A' || $category_type eq 'I' );
468 }
469
470 #title
471 my $flags = $patron ? C4::Members::patronflags( $patron->unblessed ) : {};
472 foreach my $flag ( sort keys %$flags ) {
473     $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
474     if ( $flags->{$flag}->{'noissues'} ) {
475         $template->param(
476             noissues => ($force_allow_issue) ? 0 : 'true',
477             forceallow => $force_allow_issue,
478         );
479         if ( $flag eq 'GNA' ) {
480             $template->param( gna => 'true' );
481         }
482         elsif ( $flag eq 'LOST' ) {
483             $template->param( lost => 'true' );
484         }
485         elsif ( $flag eq 'DBARRED' ) {
486             $template->param( dbarred => 'true' );
487         }
488         elsif ( $flag eq 'CHARGES' ) {
489             $template->param(
490                 charges    => 'true',
491                 chargesmsg => $flags->{'CHARGES'}->{'message'},
492                 chargesamount => $flags->{'CHARGES'}->{'amount'},
493                 charges_is_blocker => 1
494             );
495         }
496         elsif ( $flag eq 'CHARGES_GUARANTEES' ) {
497             $template->param(
498                 charges_guarantees    => 'true',
499                 chargesmsg_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'message'},
500                 chargesamount_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'amount'},
501                 charges_guarantees_is_blocker => 1
502             );
503         }
504         elsif ( $flag eq 'CREDITS' ) {
505             $template->param(
506                 credits    => 'true',
507                 creditsmsg => $flags->{'CREDITS'}->{'message'},
508                 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
509             );
510         }
511     }
512     else {
513         if ( $flag eq 'CHARGES' ) {
514             $template->param(
515                 charges    => 'true',
516                 chargesmsg => $flags->{'CHARGES'}->{'message'},
517                 chargesamount => $flags->{'CHARGES'}->{'amount'},
518             );
519         }
520         elsif ( $flag eq 'CHARGES_GUARANTEES' ) {
521             $template->param(
522                 charges_guarantees    => 'true',
523                 chargesmsg_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'message'},
524                 chargesamount_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'amount'},
525             );
526         }
527         elsif ( $flag eq 'CREDITS' ) {
528             $template->param(
529                 credits    => 'true',
530                 creditsmsg => $flags->{'CREDITS'}->{'message'},
531                 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
532             );
533         }
534         elsif ( $flag eq 'ODUES' ) {
535             $template->param(
536                 odues    => 'true',
537                 oduesmsg => $flags->{'ODUES'}->{'message'}
538             );
539
540             my $items = $flags->{$flag}->{'itemlist'};
541             if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
542                 $template->param( nonreturns => 'true' );
543             }
544         }
545         elsif ( $flag eq 'NOTES' ) {
546             $template->param(
547                 notes    => 'true',
548                 notesmsg => $flags->{'NOTES'}->{'message'}
549             );
550         }
551     }
552 }
553
554 my $amountold = $flags ? $flags->{'CHARGES'}->{'message'} || 0 : 0;
555 $amountold =~ s/^.*\$//;    # remove upto the $, if any
556
557 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
558
559 if ( $patron && $patron->category->category_type eq 'C') {
560     my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => 'A' }, {order_by => ['categorycode']});
561     $template->param( 'CATCODE_MULTI' => 1) if $patron_categories->count > 1;
562     $template->param( 'catcode' => $patron_categories->next->categorycode )  if $patron_categories->count == 1;
563 }
564
565 my $messages = Koha::Patron::Messages->search(
566     {
567         'me.borrowernumber' => $borrowernumber,
568     },
569     {
570        join => 'manager',
571        '+select' => ['manager.surname', 'manager.firstname' ],
572        '+as' => ['manager_surname', 'manager_firstname'],
573     }
574 );
575
576 my $fast_cataloging = 0;
577 if ( Koha::BiblioFrameworks->find('FA') ) {
578     $fast_cataloging = 1 
579 }
580
581 if (C4::Context->preference('ExtendedPatronAttributes')) {
582     my $attributes = GetBorrowerAttributes($borrowernumber);
583     $template->param(
584         ExtendedPatronAttributes => 1,
585         extendedattributes => $attributes
586     );
587 }
588 my $view = $batch
589     ?'batch_checkout_view'
590     : 'circview';
591
592 my @relatives;
593 if ( $borrowernumber ) {
594     if ( $patron ) {
595         if ( my $guarantor = $patron->guarantor ) {
596             push @relatives, $guarantor->borrowernumber;
597             push @relatives, $_->borrowernumber for $patron->siblings;
598         } else {
599             push @relatives, $_->borrowernumber for $patron->guarantees;
600         }
601     }
602 }
603 my $relatives_issues_count =
604   Koha::Database->new()->schema()->resultset('Issue')
605   ->count( { borrowernumber => \@relatives } );
606
607 if ( $patron ) {
608     my $av = Koha::AuthorisedValues->search({ category => 'ROADTYPE', authorised_value => $patron->streettype });
609     my $roadtype = $av->count ? $av->next->lib : '';
610     $template->param(
611         %{ $patron->unblessed },
612         borrower => $patron->unblessed,
613         roadtype          => $roadtype,
614         patron            => $patron,
615         categoryname      => $patron->category->description,
616         expiry            => $patron->dateexpiry,
617         is_child          => ( $patron->category->category_type eq 'C' ),
618         picture           => ( $patron->image ? 1 : 0 ),
619     );
620 }
621
622 # Restore date if changed by holds and/or save stickyduedate to session
623 if ($restoreduedatespec || $stickyduedate) {
624     $duedatespec = $restoreduedatespec || $duedatespec;
625
626     if ($stickyduedate) {
627         $session->param( 'stickyduedate', $duedatespec );
628     }
629 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
630     undef $duedatespec;
631 }
632
633 $template->param(
634     messages           => $messages,
635     borrowernumber    => $borrowernumber,
636     branch            => $branch,
637     was_renewed       => scalar $query->param('was_renewed') ? 1 : 0,
638     amountold         => $amountold,
639     barcodes          => $barcodes,
640     stickyduedate     => $stickyduedate,
641     duedatespec       => $duedatespec,
642     restoreduedatespec => $restoreduedatespec,
643     message           => $message,
644     totaldue          => sprintf('%.2f', $total),
645     inprocess         => $inprocess,
646     $view             => 1,
647     batch_allowed     => $batch_allowed,
648     batch             => $batch,
649     AudioAlerts           => C4::Context->preference("AudioAlerts"),
650     fast_cataloging   => $fast_cataloging,
651     CircAutoPrintQuickSlip   => C4::Context->preference("CircAutoPrintQuickSlip"),
652     RoutingSerials => C4::Context->preference('RoutingSerials'),
653     relatives_issues_count => $relatives_issues_count,
654     relatives_borrowernumbers => \@relatives,
655 );
656
657
658 if ( C4::Context->preference("ExportCircHistory") ) {
659     $template->param(csv_profiles => [ Koha::CsvProfiles->search({ type => 'marc' }) ]);
660 }
661
662 my $has_modifications = Koha::Patron::Modifications->search( { borrowernumber => $borrowernumber } )->count;
663 $template->param(
664     debt_confirmed            => $debt_confirmed,
665     SpecifyDueDate            => $duedatespec_allow,
666     CircAutocompl             => C4::Context->preference("CircAutocompl"),
667     debarments                => scalar GetDebarments({ borrowernumber => $borrowernumber }),
668     todaysdate                => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
669     has_modifications         => $has_modifications,
670     override_high_holds       => $override_high_holds,
671     nopermission              => scalar $query->param('nopermission'),
672 );
673
674 output_html_with_http_headers $query, $cookie, $template->output;