Fix use of non-existent variable $borrower
[koha.git] / circ / circulation.pl
blobb94b088839ef10dbf869ca58f640d8b5a25846e7
1 #!/usr/bin/perl
3 # script to execute issuing of books
5 # Copyright 2000-2002 Katipo Communications
6 # copyright 2010 BibLibre
7 # Copyright 2011 PTFS-Europe Ltd.
8 # Copyright 2012 software.coop and MJ Ray
10 # This file is part of Koha.
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.
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.
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>.
25 use strict;
26 use warnings;
27 use CGI qw ( -utf8 );
28 use DateTime;
29 use DateTime::Duration;
30 use C4::Output;
31 use C4::Print;
32 use C4::Auth qw/:DEFAULT get_session haspermission/;
33 use C4::Branch; # GetBranches
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::Borrower::Debarments qw(GetDebarments IsDebarred);
47 use Koha::DateUtils;
48 use Koha::Database;
49 use Koha::Borrower::Modifications;
51 use Date::Calc qw(
52 Today
53 Add_Delta_Days
54 Date_to_Days
56 use List::MoreUtils qw/uniq/;
59 # PARAMETERS READING
61 my $query = new CGI;
63 my $sessionID = $query->cookie("CGISESSID") ;
64 my $session = get_session($sessionID);
65 if (!C4::Context->userenv){
66 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
67 # no branch set we can't issue
68 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
69 exit;
73 my $barcodes = [];
74 my $barcode = $query->param('barcode');
75 # Barcode given by user could be '0'
76 if ( $barcode || ( defined($barcode) && $barcode eq '0' ) ) {
77 $barcodes = [ $barcode ];
78 } else {
79 my $filefh = $query->upload('uploadfile');
80 if ( $filefh ) {
81 while ( my $content = <$filefh> ) {
82 $content =~ s/[\r\n]*$//g;
83 push @$barcodes, $content if $content;
85 } elsif ( my $list = $query->param('barcodelist') ) {
86 push @$barcodes, split( /\s\n/, $list );
87 $barcodes = [ map { $_ =~ /^\s*$/ ? () : $_ } @$barcodes ];
88 } else {
89 @$barcodes = $query->multi_param('barcodes');
93 $barcodes = [ uniq @$barcodes ];
95 my $template_name = q|circ/circulation.tt|;
96 my $borrowernumber = $query->param('borrowernumber');
97 my $borrower = $borrowernumber ? GetMember( borrowernumber => $borrowernumber ) : undef;
98 my $batch = $query->param('batch');
99 my $batch_allowed = 0;
100 if ( $batch && C4::Context->preference('BatchCheckouts') ) {
101 $template_name = q|circ/circulation_batch_checkouts.tt|;
102 my @batch_category_codes = split '\|', C4::Context->preference('BatchCheckoutsValidCategories');
103 if ( grep {/^$borrower->{categorycode}$/} @batch_category_codes ) {
104 $batch_allowed = 1;
105 } else {
106 $barcodes = [];
110 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
112 template_name => $template_name,
113 query => $query,
114 type => "intranet",
115 authnotrequired => 0,
116 flagsrequired => { circulate => 'circulate_remaining_permissions' },
120 my $force_allow_issue = $query->param('forceallow') || 0;
121 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
122 $force_allow_issue = 0;
125 my $onsite_checkout = $query->param('onsite_checkout');
127 my @failedrenews = $query->multi_param('failedrenew'); # expected to be itemnumbers
128 our %renew_failed = ();
129 for (@failedrenews) { $renew_failed{$_} = 1; }
131 my @failedreturns = $query->multi_param('failedreturn');
132 our %return_failed = ();
133 for (@failedreturns) { $return_failed{$_} = 1; }
135 my $findborrower = $query->param('findborrower') || q{};
136 $findborrower =~ s|,| |g;
138 my $branch = C4::Context->userenv->{'branch'};
140 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
141 if (C4::Context->preference("AutoLocation") != 1) {
142 $template->param(ManualLocation => 1);
145 if (C4::Context->preference("DisplayClearScreenButton")) {
146 $template->param(DisplayClearScreenButton => 1);
149 for my $barcode ( @$barcodes ) {
150 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
151 $barcode = barcodedecode($barcode)
152 if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
155 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
156 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
157 $duedatespec = eval { output_pref( { dt => dt_from_string( $duedatespec ), dateformat => 'iso', timeformat => '24hr' }); }
158 if ( $duedatespec );
159 my $restoreduedatespec = $query->param('restoreduedatespec') || $duedatespec || $session->param('stickyduedate');
160 if ( $restoreduedatespec && $restoreduedatespec eq "highholds_empty" ) {
161 undef $restoreduedatespec;
163 my $issueconfirmed = $query->param('issueconfirmed');
164 my $cancelreserve = $query->param('cancelreserve');
165 my $print = $query->param('print') || q{};
166 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
167 my $charges = $query->param('charges') || q{};
169 # Check if stickyduedate is turned off
170 if ( @$barcodes ) {
171 # was stickyduedate loaded from session?
172 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
173 $session->clear( 'stickyduedate' );
174 $stickyduedate = $query->param('stickyduedate');
175 $duedatespec = $query->param('duedatespec');
177 $session->param('auto_renew', scalar $query->param('auto_renew'));
179 else {
180 $session->clear('auto_renew');
183 my ($datedue,$invalidduedate);
185 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
186 if( $onsite_checkout && !$duedatespec_allow ) {
187 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
188 $datedue .= ' 23:59:00';
189 } elsif( $duedatespec_allow ) {
190 if ( $duedatespec ) {
191 $datedue = eval { dt_from_string( $duedatespec ) };
192 if (! $datedue ) {
193 $invalidduedate = 1;
194 $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec );
199 # check and see if we should print
200 if ( @$barcodes == 0 && $print eq 'maybe' ) {
201 $print = 'yes';
204 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
205 if ( @$barcodes == 0 && $charges eq 'yes' ) {
206 $template->param(
207 PAYCHARGES => 'yes',
208 borrowernumber => $borrowernumber
212 if ( $print eq 'yes' && $borrowernumber ne '' ) {
213 if ( C4::Context->boolean_preference('printcirculationslips') ) {
214 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
215 NetworkPrint($letter->{content});
217 $query->param( 'borrowernumber', '' );
218 $borrowernumber = '';
222 # STEP 2 : FIND BORROWER
223 # if there is a list of find borrowers....
225 my $message;
226 if ($findborrower) {
227 my $borrower = C4::Members::GetMember( cardnumber => $findborrower );
228 if ( $borrower ) {
229 $borrowernumber = $borrower->{borrowernumber};
230 } else {
231 my $dt_params = { iDisplayLength => -1 };
232 my $results = C4::Utils::DataTables::Members::search(
234 searchmember => $findborrower,
235 searchtype => 'contain',
236 dt_params => $dt_params,
239 my $borrowers = $results->{patrons};
240 if ( scalar @$borrowers == 1 ) {
241 $borrowernumber = $borrowers->[0]->{borrowernumber};
242 $query->param( 'borrowernumber', $borrowernumber );
243 $query->param( 'barcode', '' );
244 } elsif ( @$borrowers ) {
245 $template->param( borrowers => $borrowers );
246 } else {
247 $query->param( 'findborrower', '' );
248 $message = "'$findborrower'";
253 # get the borrower information.....
254 if ($borrowernumber) {
255 $borrower = GetMemberDetails( $borrowernumber, 0 );
256 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
258 # Warningdate is the date that the warning starts appearing
259 my ( $today_year, $today_month, $today_day) = Today();
260 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
261 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
262 # if the expiry date is before today ie they have expired
263 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
264 || Date_to_Days($today_year, $today_month, $today_day )
265 > Date_to_Days($warning_year, $warning_month, $warning_day) )
267 #borrowercard expired, no issues
268 $template->param(
269 flagged => "1",
270 noissues => ($force_allow_issue) ? 0 : "1",
271 forceallow => $force_allow_issue,
272 expired => "1",
275 # check for NotifyBorrowerDeparture
276 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
277 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
278 Date_to_Days( $today_year, $today_month, $today_day ) )
280 # borrower card soon to expire warn librarian
281 $template->param( "warndeparture" => $borrower->{dateexpiry} ,
282 flagged => "1"
284 if (C4::Context->preference('ReturnBeforeExpiry')){
285 $template->param("returnbeforeexpiry" => 1);
288 $template->param(
289 overduecount => $od,
290 issuecount => $issue,
291 finetotal => $fines
294 if ( IsDebarred($borrowernumber) ) {
295 $template->param(
296 'userdebarred' => $borrower->{debarred},
297 'debarredcomment' => $borrower->{debarredcomment},
300 if ( $borrower->{debarred} ne "9999-12-31" ) {
301 $template->param( 'userdebarreddate' => $borrower->{debarred} );
308 # STEP 3 : ISSUING
311 if (@$barcodes) {
312 my $checkout_infos;
313 for my $barcode ( @$barcodes ) {
314 my $template_params = { barcode => $barcode };
315 # always check for blockers on issuing
316 my ( $error, $question, $alerts ) =
317 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess, undef, { onsite_checkout => $onsite_checkout } );
318 my $blocker = $invalidduedate ? 1 : 0;
320 $template_params->{alert} = $alerts;
322 # Get the item title for more information
323 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
324 $template_params->{authvalcode_notforloan} =
325 C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'});
327 # Fix for bug 7494: optional checkout-time fallback search for a book
329 if ( $error->{'UNKNOWN_BARCODE'}
330 && C4::Context->preference("itemBarcodeFallbackSearch")
331 && not $batch
334 $template_params->{FALLBACK} = 1;
336 my $query = "kw=" . $barcode;
337 my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
339 # if multiple hits, offer options to librarian
340 if ( $total_hits > 0 ) {
341 my @options = ();
342 foreach my $hit ( @{$results} ) {
343 my $chosen =
344 TransformMarcToKoha( C4::Context->dbh,
345 C4::Search::new_record_from_zebra('biblioserver',$hit) );
347 # offer all barcodes individually
348 if ( $chosen->{barcode} ) {
349 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
350 my %chosen_single = %{$chosen};
351 $chosen_single{barcode} = $barcode;
352 push( @options, \%chosen_single );
356 $template_params->{options} = \@options;
360 unless( $onsite_checkout and C4::Context->preference("OnSiteCheckoutsForce") ) {
361 delete $question->{'DEBT'} if ($debt_confirmed);
362 foreach my $impossible ( keys %$error ) {
363 $template_params->{$impossible} = $$error{$impossible};
364 $template_params->{IMPOSSIBLE} = 1;
365 $blocker = 1;
368 my $iteminfo = GetBiblioFromItemNumber(undef, $barcode);
369 if( !$blocker || $force_allow_issue ){
370 my $confirm_required = 0;
371 unless($issueconfirmed){
372 # Get the item title for more information
373 $template_params->{additional_materials} = $iteminfo->{'materials'};
374 $template_params->{itemhomebranch} = $iteminfo->{'homebranch'};
376 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
377 foreach my $needsconfirmation ( keys %$question ) {
378 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
379 $template_params->{getTitleMessageIteminfo} = $iteminfo->{'title'};
380 $template_params->{getBarcodeMessageIteminfo} = $iteminfo->{'barcode'};
381 $template_params->{NEEDSCONFIRMATION} = 1;
382 $template_params->{onsite_checkout} = $onsite_checkout;
383 $confirm_required = 1;
386 unless($confirm_required) {
387 my $issue = AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, { onsite_checkout => $onsite_checkout, auto_renew => $session->param('auto_renew') } );
388 $template_params->{issue} = $issue;
389 $session->clear('auto_renew');
390 $inprocess = 1;
394 # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue
395 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
397 if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
398 $template->param(
399 reserveborrowernumber => $question->{'resborrowernumber'},
400 itembiblionumber => $getmessageiteminfo->{'biblionumber'}
404 $template_params->{issuecount} = $issue;
406 if ( $iteminfo ) {
407 $iteminfo->{subtitle} = GetRecordValue('subtitle', GetMarcBiblio($iteminfo->{biblionumber}), GetFrameworkCode($iteminfo->{biblionumber}));
408 $template_params->{item} = $iteminfo;
410 push @$checkout_infos, $template_params;
412 unless ( $batch ) {
413 $template->param( %{$checkout_infos->[0]} );
414 $template->param( barcode => $barcodes->[0] );
415 } else {
416 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
417 $template->param(
418 checkout_infos => $checkout_infos,
419 confirmation_needed => $confirmation_needed,
424 # reload the borrower info for the sake of reseting the flags.....
425 if ($borrowernumber) {
426 $borrower = GetMemberDetails( $borrowernumber, 0 );
429 ##################################################################################
430 # BUILD HTML
431 # show all reserves of this borrower, and the position of the reservation ....
432 if ($borrowernumber) {
433 my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } );
434 my $waiting_holds = $holds->waiting;
435 $template->param(
436 holds_count => $holds->count(),
437 WaitingHolds => $waiting_holds,
440 $template->param( adultborrower => 1 ) if ( $borrower->{category_type} eq 'A' || $borrower->{category_type} eq 'I' );
443 #title
444 my $flags = $borrower->{'flags'};
445 foreach my $flag ( sort keys %$flags ) {
446 $template->param( flagged=> 1);
447 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
448 if ( $flags->{$flag}->{'noissues'} ) {
449 $template->param(
450 noissues => ($force_allow_issue) ? 0 : 'true',
451 forceallow => $force_allow_issue,
453 if ( $flag eq 'GNA' ) {
454 $template->param( gna => 'true' );
456 elsif ( $flag eq 'LOST' ) {
457 $template->param( lost => 'true' );
459 elsif ( $flag eq 'DBARRED' ) {
460 $template->param( dbarred => 'true' );
462 elsif ( $flag eq 'CHARGES' ) {
463 $template->param(
464 charges => 'true',
465 chargesmsg => $flags->{'CHARGES'}->{'message'},
466 chargesamount => $flags->{'CHARGES'}->{'amount'},
467 charges_is_blocker => 1
470 elsif ( $flag eq 'CREDITS' ) {
471 $template->param(
472 credits => 'true',
473 creditsmsg => $flags->{'CREDITS'}->{'message'},
474 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
478 else {
479 if ( $flag eq 'CHARGES' ) {
480 $template->param(
481 charges => 'true',
482 chargesmsg => $flags->{'CHARGES'}->{'message'},
483 chargesamount => $flags->{'CHARGES'}->{'amount'},
486 elsif ( $flag eq 'CREDITS' ) {
487 $template->param(
488 credits => 'true',
489 creditsmsg => $flags->{'CREDITS'}->{'message'},
490 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
493 elsif ( $flag eq 'ODUES' ) {
494 $template->param(
495 odues => 'true',
496 oduesmsg => $flags->{'ODUES'}->{'message'}
499 my $items = $flags->{$flag}->{'itemlist'};
500 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
501 $template->param( nonreturns => 'true' );
504 elsif ( $flag eq 'NOTES' ) {
505 $template->param(
506 notes => 'true',
507 notesmsg => $flags->{'NOTES'}->{'message'}
513 my $amountold = $borrower->{flags} ? $borrower->{flags}->{'CHARGES'}->{'message'} || 0 : 0;
514 $amountold =~ s/^.*\$//; # remove upto the $, if any
516 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
518 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
519 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
520 my $cnt = scalar(@$catcodes);
521 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
522 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
525 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
526 if($lib_messages_loop){ $template->param(flagged => 1 ); }
528 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
529 if($bor_messages_loop){ $template->param(flagged => 1 ); }
531 my $fast_cataloging = 0;
532 if (defined getframeworkinfo('FA')) {
533 $fast_cataloging = 1
536 if (C4::Context->preference('ExtendedPatronAttributes')) {
537 my $attributes = GetBorrowerAttributes($borrowernumber);
538 $template->param(
539 ExtendedPatronAttributes => 1,
540 extendedattributes => $attributes
543 my $view = $batch
544 ?'batch_checkout_view'
545 : 'circview';
547 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
548 my $relatives_issues_count =
549 Koha::Database->new()->schema()->resultset('Issue')
550 ->count( { borrowernumber => \@relatives } );
552 my $roadtype = C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{streettype} );
554 $template->param(%$borrower);
556 # Restore date if changed by holds and/or save stickyduedate to session
557 if ($restoreduedatespec || $stickyduedate) {
558 $duedatespec = $restoreduedatespec || $duedatespec;
560 if ($stickyduedate) {
561 $session->param( 'stickyduedate', $duedatespec );
563 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
564 undef $duedatespec;
567 $template->param(
568 lib_messages_loop => $lib_messages_loop,
569 bor_messages_loop => $bor_messages_loop,
570 all_messages_del => C4::Context->preference('AllowAllMessageDeletion'),
571 findborrower => $findborrower,
572 borrower => $borrower,
573 borrowernumber => $borrowernumber,
574 categoryname => $borrower->{'description'},
575 branch => $branch,
576 branchname => GetBranchName($borrower->{'branchcode'}),
577 was_renewed => scalar $query->param('was_renewed') ? 1 : 0,
578 expiry => $borrower->{'dateexpiry'},
579 roadtype => $roadtype,
580 amountold => $amountold,
581 barcodes => $barcodes,
582 stickyduedate => $stickyduedate,
583 duedatespec => $duedatespec,
584 restoreduedatespec => $restoreduedatespec,
585 message => $message,
586 totaldue => sprintf('%.2f', $total),
587 inprocess => $inprocess,
588 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
589 $view => 1,
590 batch_allowed => $batch_allowed,
591 AudioAlerts => C4::Context->preference("AudioAlerts"),
592 fast_cataloging => $fast_cataloging,
593 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
594 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
595 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
596 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
597 RoutingSerials => C4::Context->preference('RoutingSerials'),
598 relatives_issues_count => $relatives_issues_count,
599 relatives_borrowernumbers => \@relatives,
602 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
603 $template->param( picture => 1 ) if $picture;
605 # get authorised values with type of BOR_NOTES
607 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
609 $template->param(
610 debt_confirmed => $debt_confirmed,
611 SpecifyDueDate => $duedatespec_allow,
612 CircAutocompl => C4::Context->preference("CircAutocompl"),
613 canned_bor_notes_loop => $canned_notes,
614 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
615 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
616 nopermission => scalar $query->param('nopermission'),
617 modifications => Koha::Borrower::Modifications->GetModifications({ borrowernumber => $borrowernumber }),
620 output_html_with_http_headers $query, $cookie, $template->output;