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);
46 use Koha::Borrower::Debarments qw(GetDebarments IsDebarred);
49 use Koha::Borrower::Modifications;
56 use List::MoreUtils qw/uniq/;
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");
74 my $barcode = $query->param('barcode');
75 # Barcode given by user could be '0'
76 if ( $barcode or defined $barcode and $barcode eq '0' ) {
77 $barcodes = [ $barcode ];
79 my $filefh = $query->upload('uploadfile');
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 ];
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 ) {
110 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
112 template_name => $template_name,
115 authnotrequired => 0,
116 flagsrequired => { circulate => 'circulate_remaining_permissions' },
120 my $branches = GetBranches();
122 my $force_allow_issue = $query->param('forceallow') || 0;
123 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
124 $force_allow_issue = 0;
127 my $onsite_checkout = $query->param('onsite_checkout');
129 my @failedrenews = $query->multi_param('failedrenew'); # expected to be itemnumbers
130 our %renew_failed = ();
131 for (@failedrenews) { $renew_failed{$_} = 1; }
133 my @failedreturns = $query->multi_param('failedreturn');
134 our %return_failed = ();
135 for (@failedreturns) { $return_failed{$_} = 1; }
137 my $findborrower = $query->param('findborrower') || q{};
138 $findborrower =~ s|,| |g;
140 my $branch = C4::Context->userenv->{'branch'};
142 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
143 if (C4::Context->preference("AutoLocation") != 1) {
144 $template->param(ManualLocation => 1);
147 if (C4::Context->preference("DisplayClearScreenButton")) {
148 $template->param(DisplayClearScreenButton => 1);
151 for my $barcode ( @$barcodes ) {
152 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
153 $barcode = barcodedecode($barcode)
154 if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
157 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
158 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
159 $duedatespec = eval { output_pref( { dt => dt_from_string( $duedatespec ), dateformat => 'iso' }); }
161 my $restoreduedatespec = $query->param('restoreduedatespec') || $session->param('stickyduedate') || $duedatespec;
162 if ($restoreduedatespec and $restoreduedatespec eq "highholds_empty") {
163 undef $restoreduedatespec;
165 my $issueconfirmed = $query->param('issueconfirmed');
166 my $cancelreserve = $query->param('cancelreserve');
167 my $print = $query->param('print') || q{};
168 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
169 my $charges = $query->param('charges') || q{};
171 # Check if stickyduedate is turned off
173 # was stickyduedate loaded from session?
174 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
175 $session->clear( 'stickyduedate' );
176 $stickyduedate = $query->param('stickyduedate');
177 $duedatespec = $query->param('duedatespec');
179 $session->param('auto_renew', scalar $query->param('auto_renew'));
182 $session->clear('auto_renew');
185 my ($datedue,$invalidduedate);
187 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
188 if( $onsite_checkout && !$duedatespec_allow ) {
189 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
190 $datedue .= ' 23:59:00';
191 } elsif( $duedatespec_allow ) {
192 if ( $duedatespec ) {
193 $datedue = eval { dt_from_string( $duedatespec ) };
196 $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec );
201 # check and see if we should print
202 if ( @$barcodes == 0 && $print eq 'maybe' ) {
206 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
207 if ( @$barcodes == 0 && $charges eq 'yes' ) {
210 borrowernumber => $borrowernumber
214 if ( $print eq 'yes' && $borrowernumber ne '' ) {
215 if ( C4::Context->boolean_preference('printcirculationslips') ) {
216 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
217 NetworkPrint($letter->{content});
219 $query->param( 'borrowernumber', '' );
220 $borrowernumber = '';
224 # STEP 2 : FIND BORROWER
225 # if there is a list of find borrowers....
229 my $borrower = C4::Members::GetMember( cardnumber => $findborrower );
231 $borrowernumber = $borrower->{borrowernumber};
233 my $dt_params = { iDisplayLength => -1 };
234 my $results = C4::Utils::DataTables::Members::search(
236 searchmember => $findborrower,
237 searchtype => 'contain',
238 dt_params => $dt_params,
241 my $borrowers = $results->{patrons};
242 if ( scalar @$borrowers == 1 ) {
243 $borrowernumber = $borrowers->[0]->{borrowernumber};
244 $query->param( 'borrowernumber', $borrowernumber );
245 $query->param( 'barcode', '' );
246 } elsif ( @$borrowers ) {
247 $template->param( borrowers => $borrowers );
249 $query->param( 'findborrower', '' );
250 $message = "'$findborrower'";
255 # get the borrower information.....
256 if ($borrowernumber) {
257 $borrower = GetMemberDetails( $borrowernumber, 0 );
258 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
260 # Warningdate is the date that the warning starts appearing
261 my ( $today_year, $today_month, $today_day) = Today();
262 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
263 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
264 # if the expiry date is before today ie they have expired
265 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
266 || Date_to_Days($today_year, $today_month, $today_day )
267 > Date_to_Days($warning_year, $warning_month, $warning_day) )
269 #borrowercard expired, no issues
272 noissues => ($force_allow_issue) ? 0 : "1",
273 forceallow => $force_allow_issue,
277 # check for NotifyBorrowerDeparture
278 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
279 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
280 Date_to_Days( $today_year, $today_month, $today_day ) )
282 # borrower card soon to expire warn librarian
283 $template->param( "warndeparture" => $borrower->{dateexpiry} ,
286 if (C4::Context->preference('ReturnBeforeExpiry')){
287 $template->param("returnbeforeexpiry" => 1);
292 issuecount => $issue,
296 if ( IsDebarred($borrowernumber) ) {
298 'userdebarred' => $borrower->{debarred},
299 'debarredcomment' => $borrower->{debarredcomment},
302 if ( $borrower->{debarred} ne "9999-12-31" ) {
303 $template->param( 'userdebarreddate' => $borrower->{debarred} );
315 for my $barcode ( @$barcodes ) {
316 my $template_params = { barcode => $barcode };
317 # always check for blockers on issuing
318 my ( $error, $question, $alerts ) =
319 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess, undef, { onsite_checkout => $onsite_checkout } );
320 my $blocker = $invalidduedate ? 1 : 0;
322 $template_params->{alert} = $alerts;
324 # Get the item title for more information
325 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
326 $template_params->{authvalcode_notforloan} =
327 C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'});
329 # Fix for bug 7494: optional checkout-time fallback search for a book
331 if ( $error->{'UNKNOWN_BARCODE'}
332 && C4::Context->preference("itemBarcodeFallbackSearch")
336 $template_params->{FALLBACK} = 1;
338 my $query = "kw=" . $barcode;
339 my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
341 # if multiple hits, offer options to librarian
342 if ( $total_hits > 0 ) {
344 foreach my $hit ( @{$results} ) {
346 TransformMarcToKoha( C4::Context->dbh,
347 C4::Search::new_record_from_zebra('biblioserver',$hit) );
349 # offer all barcodes individually
350 if ( $chosen->{barcode} ) {
351 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
352 my %chosen_single = %{$chosen};
353 $chosen_single{barcode} = $barcode;
354 push( @options, \%chosen_single );
358 $template_params->{options} = \@options;
362 unless( $onsite_checkout and C4::Context->preference("OnSiteCheckoutsForce") ) {
363 delete $question->{'DEBT'} if ($debt_confirmed);
364 foreach my $impossible ( keys %$error ) {
365 $template_params->{$impossible} = $$error{$impossible};
366 $template_params->{IMPOSSIBLE} = 1;
370 my $iteminfo = GetBiblioFromItemNumber(undef, $barcode);
371 if( !$blocker || $force_allow_issue ){
372 my $confirm_required = 0;
373 unless($issueconfirmed){
374 # Get the item title for more information
375 $template_params->{additional_materials} = $iteminfo->{'materials'};
376 $template_params->{itemhomebranch} = $iteminfo->{'homebranch'};
378 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
379 foreach my $needsconfirmation ( keys %$question ) {
380 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
381 $template_params->{getTitleMessageIteminfo} = $iteminfo->{'title'};
382 $template_params->{getBarcodeMessageIteminfo} = $iteminfo->{'barcode'};
383 $template_params->{NEEDSCONFIRMATION} = 1;
384 $template_params->{onsite_checkout} = $onsite_checkout;
385 $confirm_required = 1;
388 unless($confirm_required) {
389 my $issue = AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, { onsite_checkout => $onsite_checkout, auto_renew => $session->param('auto_renew') } );
390 $template_params->{issue} = $issue;
391 $session->clear('auto_renew');
396 # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue
397 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
399 if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
401 reserveborrowernumber => $question->{'resborrowernumber'},
402 itembiblionumber => $getmessageiteminfo->{'biblionumber'}
406 $template_params->{issuecount} = $issue;
409 $iteminfo->{subtitle} = GetRecordValue('subtitle', GetMarcBiblio($iteminfo->{biblionumber}), GetFrameworkCode($iteminfo->{biblionumber}));
410 $template_params->{item} = $iteminfo;
412 push @$checkout_infos, $template_params;
415 $template->param( %{$checkout_infos->[0]} );
416 $template->param( barcode => $barcodes->[0] );
418 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
420 checkout_infos => $checkout_infos,
421 confirmation_needed => $confirmation_needed,
426 # reload the borrower info for the sake of reseting the flags.....
427 if ($borrowernumber) {
428 $borrower = GetMemberDetails( $borrowernumber, 0 );
431 ##################################################################################
433 # show all reserves of this borrower, and the position of the reservation ....
434 if ($borrowernumber) {
435 my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } );
436 my $waiting_holds = $holds->waiting;
438 holds_count => $holds->count(),
439 WaitingHolds => $waiting_holds,
442 $template->param( adultborrower => 1 ) if ( $borrower->{category_type} eq 'A' || $borrower->{category_type} eq 'I' );
446 my $flags = $borrower->{'flags'};
447 foreach my $flag ( sort keys %$flags ) {
448 $template->param( flagged=> 1);
449 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
450 if ( $flags->{$flag}->{'noissues'} ) {
452 noissues => ($force_allow_issue) ? 0 : 'true',
453 forceallow => $force_allow_issue,
455 if ( $flag eq 'GNA' ) {
456 $template->param( gna => 'true' );
458 elsif ( $flag eq 'LOST' ) {
459 $template->param( lost => 'true' );
461 elsif ( $flag eq 'DBARRED' ) {
462 $template->param( dbarred => 'true' );
464 elsif ( $flag eq 'CHARGES' ) {
467 chargesmsg => $flags->{'CHARGES'}->{'message'},
468 chargesamount => $flags->{'CHARGES'}->{'amount'},
469 charges_is_blocker => 1
472 elsif ( $flag eq 'CREDITS' ) {
475 creditsmsg => $flags->{'CREDITS'}->{'message'},
476 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
481 if ( $flag eq 'CHARGES' ) {
484 chargesmsg => $flags->{'CHARGES'}->{'message'},
485 chargesamount => $flags->{'CHARGES'}->{'amount'},
488 elsif ( $flag eq 'CREDITS' ) {
491 creditsmsg => $flags->{'CREDITS'}->{'message'},
492 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
495 elsif ( $flag eq 'ODUES' ) {
498 oduesmsg => $flags->{'ODUES'}->{'message'}
501 my $items = $flags->{$flag}->{'itemlist'};
502 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
503 $template->param( nonreturns => 'true' );
506 elsif ( $flag eq 'NOTES' ) {
509 notesmsg => $flags->{'NOTES'}->{'message'}
515 my $amountold = $borrower->{flags} ? $borrower->{flags}->{'CHARGES'}->{'message'} || 0 : 0;
516 $amountold =~ s/^.*\$//; # remove upto the $, if any
518 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
520 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
521 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
522 my $cnt = scalar(@$catcodes);
523 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
524 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
527 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
528 if($lib_messages_loop){ $template->param(flagged => 1 ); }
530 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
531 if($bor_messages_loop){ $template->param(flagged => 1 ); }
533 my $fast_cataloging = 0;
534 if (defined getframeworkinfo('FA')) {
538 if (C4::Context->preference('ExtendedPatronAttributes')) {
539 my $attributes = GetBorrowerAttributes($borrowernumber);
541 ExtendedPatronAttributes => 1,
542 extendedattributes => $attributes
546 ?'batch_checkout_view'
549 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
550 my $relatives_issues_count =
551 Koha::Database->new()->schema()->resultset('Issue')
552 ->count( { borrowernumber => \@relatives } );
554 my $roadtype = C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{streettype} );
556 $template->param(%$borrower);
558 # Restore date if changed by holds and/or save stickyduedate to session
559 if ($restoreduedatespec || $stickyduedate) {
560 $duedatespec = $restoreduedatespec || $duedatespec;
562 if ($stickyduedate) {
563 $session->param( 'stickyduedate', $duedatespec );
565 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
570 lib_messages_loop => $lib_messages_loop,
571 bor_messages_loop => $bor_messages_loop,
572 all_messages_del => C4::Context->preference('AllowAllMessageDeletion'),
573 findborrower => $findborrower,
574 borrower => $borrower,
575 borrowernumber => $borrowernumber,
576 categoryname => $borrower->{'description'},
578 branchname => GetBranchName($borrower->{'branchcode'}),
579 was_renewed => scalar $query->param('was_renewed') ? 1 : 0,
580 expiry => $borrower->{'dateexpiry'},
581 roadtype => $roadtype,
582 amountold => $amountold,
583 barcodes => $barcodes,
584 stickyduedate => $stickyduedate,
585 duedatespec => $duedatespec,
586 restoreduedatespec => $restoreduedatespec,
588 totaldue => sprintf('%.2f', $total),
589 inprocess => $inprocess,
590 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
592 batch_allowed => $batch_allowed,
593 AudioAlerts => C4::Context->preference("AudioAlerts"),
594 fast_cataloging => $fast_cataloging,
595 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
596 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
597 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
598 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
599 RoutingSerials => C4::Context->preference('RoutingSerials'),
600 relatives_issues_count => $relatives_issues_count,
601 relatives_borrowernumbers => \@relatives,
604 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
605 $template->param( picture => 1 ) if $picture;
607 # get authorised values with type of BOR_NOTES
609 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
612 debt_confirmed => $debt_confirmed,
613 SpecifyDueDate => $duedatespec_allow,
614 CircAutocompl => C4::Context->preference("CircAutocompl"),
615 canned_bor_notes_loop => $canned_notes,
616 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
617 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
618 nopermission => $query->param('nopermission'),
619 modifications => Koha::Borrower::Modifications->GetModifications({ borrowernumber => $borrowernumber }),
622 output_html_with_http_headers $query, $cookie, $template->output;