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>.
29 use DateTime
::Duration
;
32 use C4
::Auth qw
/:DEFAULT get_session haspermission/;
33 use C4
::Branch
; # GetBranches
34 use C4
::Koha
; # GetPrinter
36 use C4
::Utils
::DataTables
::Members
;
45 use C4
::Members
::Attributes
qw(GetBorrowerAttributes);
47 use Koha
::Patron
::Debarments
qw(GetDebarments IsDebarred);
50 use Koha
::Patron
::Messages
;
51 use Koha
::Patron
::Images
;
52 use Koha
::SearchEngine
;
53 use Koha
::SearchEngine
::Search
;
54 use Koha
::Patron
::Modifications
;
61 use List
::MoreUtils qw
/uniq/;
68 my $sessionID = $query->cookie("CGISESSID") ;
69 my $session = get_session
($sessionID);
71 my $override_high_holds = $query->param('override_high_holds');
72 my $override_high_holds_tmp = $query->param('override_high_holds_tmp');
74 # branch and printer are now defined by the userenv
75 # but first we have to check if someone has tried to change them
77 my $branch = $query->param('branch');
79 # update our session so the userenv is updated
80 $session->param('branch', $branch);
81 $session->param('branchname', GetBranchName
($branch));
84 my $printer = $query->param('printer');
86 # update our session so the userenv is updated
87 $session->param('branchprinter', $printer);
90 if (!C4
::Context
->userenv && !$branch){
91 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
92 # no branch set we can't issue
93 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
99 my $barcode = $query->param('barcode');
100 # Barcode given by user could be '0'
101 if ( $barcode || $barcode eq '0' ) {
102 $barcodes = [ $barcode ];
104 my $filefh = $query->upload('uploadfile');
106 while ( my $content = <$filefh> ) {
107 $content =~ s/[\r\n]*$//g;
108 push @
$barcodes, $content if $content;
110 } elsif ( my $list = $query->param('barcodelist') ) {
111 push @
$barcodes, split( /\s\n/, $list );
112 $barcodes = [ map { $_ =~ /^\s*$/ ?
() : $_ } @
$barcodes ];
114 @
$barcodes = $query->multi_param('barcodes');
118 $barcodes = [ uniq @
$barcodes ];
120 my $template_name = q
|circ
/circulation
.tt
|;
121 my $borrowernumber = $query->param('borrowernumber');
122 my $borrower = $borrowernumber ? GetMember
( borrowernumber
=> $borrowernumber ) : undef;
123 my $batch = $query->param('batch');
124 my $batch_allowed = 0;
125 if ( $batch && C4
::Context
->preference('BatchCheckouts') ) {
126 $template_name = q
|circ
/circulation_batch_checkouts
.tt
|;
127 my @batch_category_codes = split '\|', C4
::Context
->preference('BatchCheckoutsValidCategories');
128 if ( grep {/^$borrower->{categorycode}$/} @batch_category_codes ) {
135 my ( $template, $loggedinuser, $cookie ) = get_template_and_user
(
137 template_name
=> $template_name,
140 authnotrequired
=> 0,
141 flagsrequired
=> { circulate
=> 'circulate_remaining_permissions' },
145 my $branches = GetBranches
();
147 my $force_allow_issue = $query->param('forceallow') || 0;
148 if (!C4
::Auth
::haspermission
( C4
::Context
->userenv->{id
} , { circulate
=> 'force_checkout' } )) {
149 $force_allow_issue = 0;
152 my $onsite_checkout = $query->param('onsite_checkout');
154 my @failedrenews = $query->multi_param('failedrenew'); # expected to be itemnumbers
155 our %renew_failed = ();
156 for (@failedrenews) { $renew_failed{$_} = 1; }
158 my @failedreturns = $query->multi_param('failedreturn');
159 our %return_failed = ();
160 for (@failedreturns) { $return_failed{$_} = 1; }
162 my $findborrower = $query->param('findborrower') || q{};
163 $findborrower =~ s
|,| |g
;
165 $branch = C4
::Context
->userenv->{'branch'};
166 $printer = C4
::Context
->userenv->{'branchprinter'};
168 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
169 if (C4
::Context
->preference("AutoLocation") != 1) {
170 $template->param(ManualLocation
=> 1);
173 if (C4
::Context
->preference("DisplayClearScreenButton")) {
174 $template->param(DisplayClearScreenButton
=> 1);
177 for my $barcode ( @
$barcodes ) {
178 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
179 $barcode = barcodedecode
($barcode)
180 if( $barcode && C4
::Context
->preference('itemBarcodeInputFilter'));
183 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
184 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
185 $duedatespec = eval { output_pref
( { dt
=> dt_from_string
( $duedatespec ), dateformat
=> 'iso' }); }
187 my $restoreduedatespec = $query->param('restoreduedatespec') || $session->param('stickyduedate') || $duedatespec;
188 if ($restoreduedatespec eq "highholds_empty") {
189 undef $restoreduedatespec;
191 my $issueconfirmed = $query->param('issueconfirmed');
192 my $cancelreserve = $query->param('cancelreserve');
193 my $print = $query->param('print') || q{};
194 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
195 my $charges = $query->param('charges') || q{};
197 # Check if stickyduedate is turned off
199 # was stickyduedate loaded from session?
200 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
201 $session->clear( 'stickyduedate' );
202 $stickyduedate = $query->param('stickyduedate');
203 $duedatespec = $query->param('duedatespec');
205 $session->param('auto_renew', $query->param('auto_renew'));
208 $session->clear('auto_renew');
211 my ($datedue,$invalidduedate);
213 my $duedatespec_allow = C4
::Context
->preference('SpecifyDueDate');
214 if( $onsite_checkout && !$duedatespec_allow ) {
215 $datedue = output_pref
({ dt
=> dt_from_string
, dateonly
=> 1, dateformat
=> 'iso' });
216 $datedue .= ' 23:59:00';
217 } elsif( $duedatespec_allow ) {
218 if ( $duedatespec ) {
219 $datedue = eval { dt_from_string
( $duedatespec ) };
222 $template->param( IMPOSSIBLE
=>1, INVALID_DATE
=>$duedatespec );
227 # check and see if we should print
228 if ( @
$barcodes == 0 && $print eq 'maybe' ) {
232 my $inprocess = (@
$barcodes == 0) ?
'' : $query->param('inprocess');
233 if ( @
$barcodes == 0 && $charges eq 'yes' ) {
236 borrowernumber
=> $borrowernumber
240 if ( $print eq 'yes' && $borrowernumber ne '' ) {
241 if ( C4
::Context
->boolean_preference('printcirculationslips') ) {
242 my $letter = IssueSlip
($branch, $borrowernumber, "QUICK");
243 NetworkPrint
($letter->{content
});
245 $query->param( 'borrowernumber', '' );
246 $borrowernumber = '';
250 # STEP 2 : FIND BORROWER
251 # if there is a list of find borrowers....
255 my $borrower = C4
::Members
::GetMember
( cardnumber
=> $findborrower );
257 $borrowernumber = $borrower->{borrowernumber
};
259 my $dt_params = { iDisplayLength
=> -1 };
260 my $results = C4
::Utils
::DataTables
::Members
::search
(
262 searchmember
=> $findborrower,
263 searchtype
=> 'contain',
264 dt_params
=> $dt_params,
267 my $borrowers = $results->{patrons
};
268 if ( scalar @
$borrowers == 1 ) {
269 $borrowernumber = $borrowers->[0]->{borrowernumber
};
270 $query->param( 'borrowernumber', $borrowernumber );
271 $query->param( 'barcode', '' );
272 } elsif ( @
$borrowers ) {
273 $template->param( borrowers
=> $borrowers );
275 $query->param( 'findborrower', '' );
276 $message = "'$findborrower'";
281 # get the borrower information.....
282 if ($borrowernumber) {
283 $borrower = GetMemberDetails
( $borrowernumber, 0 );
284 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines
( $borrowernumber );
286 # Warningdate is the date that the warning starts appearing
287 my ( $today_year, $today_month, $today_day) = Today
();
288 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
289 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
290 # if the expiry date is before today ie they have expired
291 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
292 || Date_to_Days
($today_year, $today_month, $today_day )
293 > Date_to_Days
($warning_year, $warning_month, $warning_day) )
295 #borrowercard expired, no issues
297 noissues
=> ($force_allow_issue) ?
0 : "1",
298 forceallow
=> $force_allow_issue,
302 # check for NotifyBorrowerDeparture
303 elsif ( C4
::Context
->preference('NotifyBorrowerDeparture') &&
304 Date_to_Days
(Add_Delta_Days
($warning_year,$warning_month,$warning_day,- C4
::Context
->preference('NotifyBorrowerDeparture'))) <
305 Date_to_Days
( $today_year, $today_month, $today_day ) )
307 # borrower card soon to expire warn librarian
308 $template->param( "warndeparture" => $borrower->{dateexpiry
} ,
310 if (C4
::Context
->preference('ReturnBeforeExpiry')){
311 $template->param("returnbeforeexpiry" => 1);
316 issuecount
=> $issue,
320 if ( IsDebarred
($borrowernumber) ) {
322 'userdebarred' => $borrower->{debarred
},
323 'debarredcomment' => $borrower->{debarredcomment
},
326 if ( $borrower->{debarred
} ne "9999-12-31" ) {
327 $template->param( 'userdebarreddate' => $borrower->{debarred
} );
339 for my $barcode ( @
$barcodes ) {
340 my $template_params = { barcode
=> $barcode };
341 # always check for blockers on issuing
342 my ( $error, $question, $alerts ) = CanBookBeIssued
(
348 onsite_checkout
=> $onsite_checkout,
349 override_high_holds
=> $override_high_holds || $override_high_holds_tmp || 0,
353 my $blocker = $invalidduedate ?
1 : 0;
355 $template_params->{alert
} = $alerts;
357 # Get the item title for more information
358 my $getmessageiteminfo = GetBiblioFromItemNumber
(undef,$barcode);
359 $template_params->{authvalcode_notforloan
} =
360 C4
::Koha
::GetAuthValCode
('items.notforloan', $getmessageiteminfo->{'frameworkcode'});
362 # Fix for bug 7494: optional checkout-time fallback search for a book
364 if ( $error->{'UNKNOWN_BARCODE'}
365 && C4
::Context
->preference("itemBarcodeFallbackSearch")
369 $template_params->{FALLBACK
} = 1;
371 my $searcher = Koha
::SearchEngine
::Search
->new({index => $Koha::SearchEngine
::BIBLIOS_INDEX
});
372 my $query = "kw=" . $barcode;
373 my ( $searcherror, $results, $total_hits ) = $searcher->simple_search_compat($query, 0, 10);
375 # if multiple hits, offer options to librarian
376 if ( $total_hits > 0 ) {
378 foreach my $hit ( @
{$results} ) {
380 TransformMarcToKoha
( C4
::Search
::new_record_from_zebra
('biblioserver',$hit) );
382 # offer all barcodes individually
383 if ( $chosen->{barcode
} ) {
384 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode
}) ) {
385 my %chosen_single = %{$chosen};
386 $chosen_single{barcode
} = $barcode;
387 push( @options, \
%chosen_single );
391 $template_params->{options
} = \
@options;
395 unless( $onsite_checkout and C4
::Context
->preference("OnSiteCheckoutsForce") ) {
396 delete $question->{'DEBT'} if ($debt_confirmed);
397 foreach my $impossible ( keys %$error ) {
398 $template_params->{$impossible} = $$error{$impossible};
399 $template_params->{IMPOSSIBLE
} = 1;
403 my $iteminfo = GetBiblioFromItemNumber
(undef, $barcode);
404 if( !$blocker || $force_allow_issue ){
405 my $confirm_required = 0;
406 unless($issueconfirmed){
407 # Get the item title for more information
408 my $materials = $iteminfo->{'materials'};
409 my $avcode = GetAuthValCode
('items.materials');
411 $materials = GetKohaAuthorisedValueLib
($avcode, $materials);
413 $template_params->{additional_materials
} = $materials;
414 $template_params->{itemhomebranch
} = $iteminfo->{'homebranch'};
416 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
417 foreach my $needsconfirmation ( keys %$question ) {
418 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
419 $template_params->{getTitleMessageIteminfo
} = $iteminfo->{'title'};
420 $template_params->{getBarcodeMessageIteminfo
} = $iteminfo->{'barcode'};
421 $template_params->{NEEDSCONFIRMATION
} = 1;
422 $template_params->{onsite_checkout
} = $onsite_checkout;
423 $confirm_required = 1;
426 unless($confirm_required) {
427 my $issue = AddIssue
( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, { onsite_checkout
=> $onsite_checkout, auto_renew
=> $session->param('auto_renew') } );
428 $template->param( issue
=> $issue );
429 $session->clear('auto_renew');
434 # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue
435 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines
($borrowernumber);
437 if ($question->{RESERVE_WAITING
} or $question->{RESERVED
}){
439 reserveborrowernumber
=> $question->{'resborrowernumber'}
444 itembiblionumber
=> $getmessageiteminfo->{'biblionumber'}
449 $template_params->{issuecount
} = $issue;
452 $iteminfo->{subtitle
} = GetRecordValue
('subtitle', GetMarcBiblio
($iteminfo->{biblionumber
}), GetFrameworkCode
($iteminfo->{biblionumber
}));
453 $template_params->{item
} = $iteminfo;
455 push @
$checkout_infos, $template_params;
458 $template->param( %{$checkout_infos->[0]} );
459 $template->param( barcode
=> $barcodes->[0] );
461 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION
} } @
$checkout_infos;
463 checkout_infos
=> $checkout_infos,
464 confirmation_needed
=> $confirmation_needed,
469 # reload the borrower info for the sake of reseting the flags.....
470 if ($borrowernumber) {
471 $borrower = GetMemberDetails
( $borrowernumber, 0 );
474 ##################################################################################
476 # show all reserves of this borrower, and the position of the reservation ....
477 if ($borrowernumber) {
478 my $holds = Koha
::Holds
->search( { borrowernumber
=> $borrowernumber } );
479 my $waiting_holds = $holds->waiting;
481 holds_count
=> $holds->count(),
482 WaitingHolds
=> $waiting_holds,
485 $template->param( adultborrower
=> 1 ) if ( $borrower->{category_type
} eq 'A' || $borrower->{category_type
} eq 'I' );
489 my $flags = $borrower->{'flags'};
490 foreach my $flag ( sort keys %$flags ) {
491 $flags->{$flag}->{'message'} =~ s
#\n#<br />#g;
492 if ( $flags->{$flag}->{'noissues'} ) {
494 noissues
=> ($force_allow_issue) ?
0 : 'true',
495 forceallow
=> $force_allow_issue,
497 if ( $flag eq 'GNA' ) {
498 $template->param( gna
=> 'true' );
500 elsif ( $flag eq 'LOST' ) {
501 $template->param( lost
=> 'true' );
503 elsif ( $flag eq 'DBARRED' ) {
504 $template->param( dbarred
=> 'true' );
506 elsif ( $flag eq 'CHARGES' ) {
509 chargesmsg
=> $flags->{'CHARGES'}->{'message'},
510 chargesamount
=> $flags->{'CHARGES'}->{'amount'},
511 charges_is_blocker
=> 1
514 elsif ( $flag eq 'CHARGES_GUARANTEES' ) {
516 charges_guarantees
=> 'true',
517 chargesmsg_guarantees
=> $flags->{'CHARGES_GUARANTEES'}->{'message'},
518 chargesamount_guarantees
=> $flags->{'CHARGES_GUARANTEES'}->{'amount'},
519 charges_guarantees_is_blocker
=> 1
522 elsif ( $flag eq 'CREDITS' ) {
525 creditsmsg
=> $flags->{'CREDITS'}->{'message'},
526 creditsamount
=> sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
531 if ( $flag eq 'CHARGES' ) {
534 chargesmsg
=> $flags->{'CHARGES'}->{'message'},
535 chargesamount
=> $flags->{'CHARGES'}->{'amount'},
538 elsif ( $flag eq 'CHARGES_GUARANTEES' ) {
540 charges_guarantees
=> 'true',
541 chargesmsg_guarantees
=> $flags->{'CHARGES_GUARANTEES'}->{'message'},
542 chargesamount_guarantees
=> $flags->{'CHARGES_GUARANTEES'}->{'amount'},
545 elsif ( $flag eq 'CREDITS' ) {
548 creditsmsg
=> $flags->{'CREDITS'}->{'message'},
549 creditsamount
=> sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
552 elsif ( $flag eq 'ODUES' ) {
555 oduesmsg
=> $flags->{'ODUES'}->{'message'}
558 my $items = $flags->{$flag}->{'itemlist'};
559 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
560 $template->param( nonreturns
=> 'true' );
563 elsif ( $flag eq 'NOTES' ) {
566 notesmsg
=> $flags->{'NOTES'}->{'message'}
572 my $amountold = $borrower->{flags
} ?
$borrower->{flags
}->{'CHARGES'}->{'message'} || 0 : 0;
573 $amountold =~ s/^.*\$//; # remove upto the $, if any
575 my ( $total, $accts, $numaccts) = GetMemberAccountRecords
( $borrowernumber );
577 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
578 my ( $catcodes, $labels ) = GetborCatFromCatType
( 'A', 'WHERE category_type = ?' );
579 my $cnt = scalar(@
$catcodes);
580 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
581 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
584 my $librarian_messages = Koha
::Patron
::Messages
->search(
586 borrowernumber
=> $borrowernumber,
591 my $patron_messages = Koha
::Patron
::Messages
->search(
593 borrowernumber
=> $borrowernumber,
598 my $fast_cataloging = 0;
599 if (defined getframeworkinfo
('FA')) {
603 if (C4
::Context
->preference('ExtendedPatronAttributes')) {
604 my $attributes = GetBorrowerAttributes
($borrowernumber);
606 ExtendedPatronAttributes
=> 1,
607 extendedattributes
=> $attributes
611 ?
'batch_checkout_view'
615 if ( $borrowernumber ) {
616 if ( my $patron = Koha
::Patrons
->find( $borrower->{borrowernumber
} ) ) {
617 if ( my $guarantor = $patron->guarantor ) {
618 push @relatives, $guarantor->borrowernumber;
619 push @relatives, $_->borrowernumber for $patron->siblings;
621 push @relatives, $_->borrowernumber for $patron->guarantees;
625 my $relatives_issues_count =
626 Koha
::Database
->new()->schema()->resultset('Issue')
627 ->count( { borrowernumber
=> \
@relatives } );
629 my $roadtype = C4
::Koha
::GetAuthorisedValueByCode
( 'ROADTYPE', $borrower->{streettype
} );
631 $template->param(%$borrower);
633 # Restore date if changed by holds and/or save stickyduedate to session
634 if ($restoreduedatespec || $stickyduedate) {
635 $duedatespec = $restoreduedatespec || $duedatespec;
637 if ($stickyduedate) {
638 $session->param( 'stickyduedate', $duedatespec );
640 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
645 librarian_messages
=> $librarian_messages,
646 patron_messages
=> $patron_messages,
647 findborrower
=> $findborrower,
648 borrower
=> $borrower,
649 borrowernumber
=> $borrowernumber,
650 categoryname
=> $borrower->{'description'},
652 branchname
=> GetBranchName
($borrower->{'branchcode'}),
654 printername
=> $printer,
655 was_renewed
=> scalar $query->param('was_renewed') ?
1 : 0,
656 expiry
=> $borrower->{'dateexpiry'},
657 roadtype
=> $roadtype,
658 amountold
=> $amountold,
659 barcodes
=> $barcodes,
660 stickyduedate
=> $stickyduedate,
661 duedatespec
=> $duedatespec,
662 restoreduedatespec
=> $restoreduedatespec,
664 totaldue
=> sprintf('%.2f', $total),
665 inprocess
=> $inprocess,
666 is_child
=> ($borrowernumber && $borrower->{'category_type'} eq 'C'),
668 batch_allowed
=> $batch_allowed,
669 AudioAlerts
=> C4
::Context
->preference("AudioAlerts"),
670 fast_cataloging
=> $fast_cataloging,
671 CircAutoPrintQuickSlip
=> C4
::Context
->preference("CircAutoPrintQuickSlip"),
672 activeBorrowerRelationship
=> (C4
::Context
->preference('borrowerRelationship') ne ''),
673 SuspendHoldsIntranet
=> C4
::Context
->preference('SuspendHoldsIntranet'),
674 AutoResumeSuspendedHolds
=> C4
::Context
->preference('AutoResumeSuspendedHolds'),
675 RoutingSerials
=> C4
::Context
->preference('RoutingSerials'),
676 relatives_issues_count
=> $relatives_issues_count,
677 relatives_borrowernumbers
=> \
@relatives,
680 my $patron_image = Koha
::Patron
::Images
->find($borrower->{borrowernumber
});
681 $template->param( picture
=> 1 ) if $patron_image;
683 # get authorised values with type of BOR_NOTES
685 my $canned_notes = GetAuthorisedValues
("BOR_NOTES");
688 debt_confirmed
=> $debt_confirmed,
689 SpecifyDueDate
=> $duedatespec_allow,
690 CircAutocompl
=> C4
::Context
->preference("CircAutocompl"),
691 canned_bor_notes_loop
=> $canned_notes,
692 debarments
=> GetDebarments
({ borrowernumber
=> $borrowernumber }),
693 todaysdate
=> output_pref
( { dt
=> dt_from_string
()->set(hour
=> 23)->set(minute
=> 59), dateformat
=> 'sql' } ),
694 modifications
=> Koha
::Patron
::Modifications
->GetModifications({ borrowernumber
=> $borrowernumber }),
695 override_high_holds
=> $override_high_holds,
698 output_html_with_http_headers
$query, $cookie, $template->output;