Bug 15049: (Signed off) Hide currency but preserv alert
[koha.git] / circ / circulation.pl
blobab2b088cc72e5aeb8421bc79b4362e144e282ce1
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;
50 use Date::Calc qw(
51 Today
52 Add_Delta_YM
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);
66 # branch and printer are now defined by the userenv
67 # but first we have to check if someone has tried to change them
69 my $branch = $query->param('branch');
70 if ($branch){
71 # update our session so the userenv is updated
72 $session->param('branch', $branch);
73 $session->param('branchname', GetBranchName($branch));
76 my $printer = $query->param('printer');
77 if ($printer){
78 # update our session so the userenv is updated
79 $session->param('branchprinter', $printer);
82 if (!C4::Context->userenv && !$branch){
83 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
84 # no branch set we can't issue
85 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
86 exit;
90 my $barcodes = [];
91 if ( my $barcode = $query->param('barcode') ) {
92 $barcodes = [ $barcode ];
93 } else {
94 my $filefh = $query->upload('uploadfile');
95 if ( $filefh ) {
96 while ( my $content = <$filefh> ) {
97 $content =~ s/[\r\n]*$//g;
98 push @$barcodes, $content if $content;
100 } elsif ( my $list = $query->param('barcodelist') ) {
101 push @$barcodes, split( /\s\n/, $list );
102 $barcodes = [ map { $_ =~ /^\s*$/ ? () : $_ } @$barcodes ];
103 } else {
104 @$barcodes = $query->param('barcodes');
108 $barcodes = [ uniq @$barcodes ];
110 my $template_name = q|circ/circulation.tt|;
111 my $borrowernumber = $query->param('borrowernumber');
112 my $borrower = $borrowernumber ? GetMember( borrowernumber => $borrowernumber ) : undef;
113 my $batch = $query->param('batch');
114 my $batch_allowed = 0;
115 if ( $batch && C4::Context->preference('BatchCheckouts') ) {
116 $template_name = q|circ/circulation_batch_checkouts.tt|;
117 my @batch_category_codes = split '\|', C4::Context->preference('BatchCheckoutsValidCategories');
118 if ( grep {/^$borrower->{categorycode}$/} @batch_category_codes ) {
119 $batch_allowed = 1;
120 } else {
121 $barcodes = [];
125 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
127 template_name => $template_name,
128 query => $query,
129 type => "intranet",
130 authnotrequired => 0,
131 flagsrequired => { circulate => 'circulate_remaining_permissions' },
135 my $branches = GetBranches();
137 my $force_allow_issue = $query->param('forceallow') || 0;
138 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
139 $force_allow_issue = 0;
142 my $onsite_checkout = $query->param('onsite_checkout');
144 my @failedrenews = $query->param('failedrenew'); # expected to be itemnumbers
145 our %renew_failed = ();
146 for (@failedrenews) { $renew_failed{$_} = 1; }
148 my @failedreturns = $query->param('failedreturn');
149 our %return_failed = ();
150 for (@failedreturns) { $return_failed{$_} = 1; }
152 my $findborrower = $query->param('findborrower') || q{};
153 $findborrower =~ s|,| |g;
155 $branch = C4::Context->userenv->{'branch'};
156 $printer = C4::Context->userenv->{'branchprinter'};
158 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
159 if (C4::Context->preference("AutoLocation") != 1) {
160 $template->param(ManualLocation => 1);
163 if (C4::Context->preference("DisplayClearScreenButton")) {
164 $template->param(DisplayClearScreenButton => 1);
167 for my $barcode ( @$barcodes ) {
168 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
169 $barcode = barcodedecode($barcode)
170 if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
173 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
174 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
175 $duedatespec = eval { output_pref( { dt => dt_from_string( $duedatespec ), dateformat => 'iso' }); }
176 if ( $duedatespec );
177 my $restoreduedatespec = $query->param('restoreduedatespec') || $session->param('stickyduedate') || $duedatespec;
178 if ($restoreduedatespec eq "highholds_empty") {
179 undef $restoreduedatespec;
181 my $issueconfirmed = $query->param('issueconfirmed');
182 my $cancelreserve = $query->param('cancelreserve');
183 my $print = $query->param('print') || q{};
184 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
185 my $charges = $query->param('charges') || q{};
187 # Check if stickyduedate is turned off
188 if ( @$barcodes ) {
189 # was stickyduedate loaded from session?
190 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
191 $session->clear( 'stickyduedate' );
192 $stickyduedate = $query->param('stickyduedate');
193 $duedatespec = $query->param('duedatespec');
195 $session->param('auto_renew', $query->param('auto_renew'));
197 else {
198 $session->clear('auto_renew');
201 my ($datedue,$invalidduedate);
203 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
204 if( $onsite_checkout && !$duedatespec_allow ) {
205 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
206 $datedue .= ' 23:59:00';
207 } elsif( $duedatespec_allow ) {
208 if ( $duedatespec ) {
209 $datedue = eval { dt_from_string( $duedatespec ) };
210 if (! $datedue ) {
211 $invalidduedate = 1;
212 $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec );
217 # check and see if we should print
218 if ( @$barcodes == 0 && $print eq 'maybe' ) {
219 $print = 'yes';
222 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
223 if ( @$barcodes == 0 && $charges eq 'yes' ) {
224 $template->param(
225 PAYCHARGES => 'yes',
226 borrowernumber => $borrowernumber
230 if ( $print eq 'yes' && $borrowernumber ne '' ) {
231 if ( C4::Context->boolean_preference('printcirculationslips') ) {
232 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
233 NetworkPrint($letter->{content});
235 $query->param( 'borrowernumber', '' );
236 $borrowernumber = '';
240 # STEP 2 : FIND BORROWER
241 # if there is a list of find borrowers....
243 my $message;
244 if ($findborrower) {
245 my $borrower = C4::Members::GetMember( cardnumber => $findborrower );
246 if ( $borrower ) {
247 $borrowernumber = $borrower->{borrowernumber};
248 } else {
249 my $dt_params = { iDisplayLength => -1 };
250 my $results = C4::Utils::DataTables::Members::search(
252 searchmember => $findborrower,
253 searchtype => 'contain',
254 dt_params => $dt_params,
257 my $borrowers = $results->{patrons};
258 if ( scalar @$borrowers == 1 ) {
259 $borrowernumber = $borrowers->[0]->{borrowernumber};
260 $query->param( 'borrowernumber', $borrowernumber );
261 $query->param( 'barcode', '' );
262 } elsif ( @$borrowers ) {
263 $template->param( borrowers => $borrowers );
264 } else {
265 $query->param( 'findborrower', '' );
266 $message = "'$findborrower'";
271 # get the borrower information.....
272 if ($borrowernumber) {
273 $borrower = C4::Members::GetMember( borrowernumber => $borrowernumber );
274 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
276 # Warningdate is the date that the warning starts appearing
277 my ( $today_year, $today_month, $today_day) = Today();
278 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
279 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
280 # Renew day is calculated by adding the enrolment period to today
281 my ( $renew_year, $renew_month, $renew_day);
282 if ($enrol_year*$enrol_month*$enrol_day>0) {
283 ( $renew_year, $renew_month, $renew_day) =
284 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
285 0 , $borrower->{'enrolmentperiod'});
287 # if the expiry date is before today ie they have expired
288 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
289 || Date_to_Days($today_year, $today_month, $today_day )
290 > Date_to_Days($warning_year, $warning_month, $warning_day) )
292 #borrowercard expired, no issues
293 $template->param(
294 flagged => "1",
295 noissues => ($force_allow_issue) ? 0 : "1",
296 forceallow => $force_allow_issue,
297 expired => "1",
298 renewaldate => "$renew_year-$renew_month-$renew_day",
301 # check for NotifyBorrowerDeparture
302 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
303 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
304 Date_to_Days( $today_year, $today_month, $today_day ) )
306 # borrower card soon to expire warn librarian
307 $template->param( "warndeparture" => $borrower->{dateexpiry} ,
308 flagged => "1"
310 if (C4::Context->preference('ReturnBeforeExpiry')){
311 $template->param("returnbeforeexpiry" => 1);
314 $template->param(
315 overduecount => $od,
316 issuecount => $issue,
317 finetotal => $fines
320 if ( IsDebarred($borrowernumber) ) {
321 $template->param(
322 'userdebarred' => $borrower->{debarred},
323 'debarredcomment' => $borrower->{debarredcomment},
326 if ( $borrower->{debarred} ne "9999-12-31" ) {
327 $template->param( 'userdebarreddate' => $borrower->{debarred} );
334 # STEP 3 : ISSUING
337 if (@$barcodes) {
338 my $checkout_infos;
339 for my $barcode ( @$barcodes ) {
340 my $template_params = { barcode => $barcode };
341 # always check for blockers on issuing
342 my ( $error, $question, $alerts ) =
343 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess, undef, { onsite_checkout => $onsite_checkout } );
344 my $blocker = $invalidduedate ? 1 : 0;
346 $template_params->{alert} = $alerts;
348 # Get the item title for more information
349 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
350 $template_params->{authvalcode_notforloan} =
351 C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'});
353 # Fix for bug 7494: optional checkout-time fallback search for a book
355 if ( $error->{'UNKNOWN_BARCODE'}
356 && C4::Context->preference("itemBarcodeFallbackSearch")
357 && not $batch
360 $template_params->{FALLBACK} = 1;
362 my $query = "kw=" . $barcode;
363 my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
365 # if multiple hits, offer options to librarian
366 if ( $total_hits > 0 ) {
367 my @options = ();
368 foreach my $hit ( @{$results} ) {
369 my $chosen =
370 TransformMarcToKoha( C4::Context->dbh,
371 C4::Search::new_record_from_zebra('biblioserver',$hit) );
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 );
382 $template_params->{options} = \@options;
386 unless( $onsite_checkout and 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;
394 my $iteminfo = GetBiblioFromItemNumber(undef, $barcode);
395 if( !$blocker || $force_allow_issue ){
396 my $confirm_required = 0;
397 unless($issueconfirmed){
398 # Get the item title for more information
399 $template_params->{additional_materials} = $iteminfo->{'materials'};
400 $template_params->{itemhomebranch} = $iteminfo->{'homebranch'};
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} = $iteminfo->{'title'};
406 $template_params->{getBarcodeMessageIteminfo} = $iteminfo->{'barcode'};
407 $template_params->{NEEDSCONFIRMATION} = 1;
408 $template_params->{onsite_checkout} = $onsite_checkout;
409 $confirm_required = 1;
412 unless($confirm_required) {
413 my $issue = AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, { onsite_checkout => $onsite_checkout, auto_renew => $session->param('auto_renew') } );
414 $template->param( issue => $issue );
415 $session->clear('auto_renew');
416 $inprocess = 1;
420 # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue
421 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
423 if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
424 $template->param(
425 reserveborrowernumber => $question->{'resborrowernumber'},
426 itembiblionumber => $getmessageiteminfo->{'biblionumber'}
430 $template_params->{issuecount} = $issue;
432 if ( $iteminfo ) {
433 $iteminfo->{subtitle} = GetRecordValue('subtitle', GetMarcBiblio($iteminfo->{biblionumber}), GetFrameworkCode($iteminfo->{biblionumber}));
434 $template_params->{item} = $iteminfo;
436 push @$checkout_infos, $template_params;
438 unless ( $batch ) {
439 $template->param( %{$checkout_infos->[0]} );
440 $template->param( barcode => $barcodes->[0] );
441 } else {
442 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
443 $template->param(
444 checkout_infos => $checkout_infos,
445 confirmation_needed => $confirmation_needed,
450 # reload the borrower info for the sake of reseting the flags.....
451 if ($borrowernumber) {
452 $borrower = GetMemberDetails( $borrowernumber, 0 );
455 ##################################################################################
456 # BUILD HTML
457 # show all reserves of this borrower, and the position of the reservation ....
458 if ($borrowernumber) {
459 my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } );
460 my $waiting_holds = $holds->waiting;
461 $template->param(
462 holds_count => $holds->count(),
463 WaitingHolds => $waiting_holds,
466 $template->param( adultborrower => 1 ) if ( $borrower->{category_type} eq 'A' || $borrower->{category_type} eq 'I' );
469 #title
470 my $flags = $borrower->{'flags'};
471 foreach my $flag ( sort keys %$flags ) {
472 $template->param( flagged=> 1);
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,
479 if ( $flag eq 'GNA' ) {
480 $template->param( gna => 'true' );
482 elsif ( $flag eq 'LOST' ) {
483 $template->param( lost => 'true' );
485 elsif ( $flag eq 'DBARRED' ) {
486 $template->param( dbarred => 'true' );
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
496 elsif ( $flag eq 'CREDITS' ) {
497 $template->param(
498 credits => 'true',
499 creditsmsg => $flags->{'CREDITS'}->{'message'},
500 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
504 else {
505 if ( $flag eq 'CHARGES' ) {
506 $template->param(
507 charges => 'true',
508 chargesmsg => $flags->{'CHARGES'}->{'message'},
509 chargesamount => $flags->{'CHARGES'}->{'amount'},
512 elsif ( $flag eq 'CREDITS' ) {
513 $template->param(
514 credits => 'true',
515 creditsmsg => $flags->{'CREDITS'}->{'message'},
516 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
519 elsif ( $flag eq 'ODUES' ) {
520 $template->param(
521 odues => 'true',
522 oduesmsg => $flags->{'ODUES'}->{'message'}
525 my $items = $flags->{$flag}->{'itemlist'};
526 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
527 $template->param( nonreturns => 'true' );
530 elsif ( $flag eq 'NOTES' ) {
531 $template->param(
532 notes => 'true',
533 notesmsg => $flags->{'NOTES'}->{'message'}
539 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
540 $amountold =~ s/^.*\$//; # remove upto the $, if any
542 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
544 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
545 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
546 my $cnt = scalar(@$catcodes);
547 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
548 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
551 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
552 if($lib_messages_loop){ $template->param(flagged => 1 ); }
554 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
555 if($bor_messages_loop){ $template->param(flagged => 1 ); }
557 my $fast_cataloging = 0;
558 if (defined getframeworkinfo('FA')) {
559 $fast_cataloging = 1
562 if (C4::Context->preference('ExtendedPatronAttributes')) {
563 my $attributes = GetBorrowerAttributes($borrowernumber);
564 $template->param(
565 ExtendedPatronAttributes => 1,
566 extendedattributes => $attributes
569 my $view = $batch
570 ?'batch_checkout_view'
571 : 'circview';
573 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
574 my $relatives_issues_count =
575 Koha::Database->new()->schema()->resultset('Issue')
576 ->count( { borrowernumber => \@relatives } );
578 my $roadtype = C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{streettype} );
580 $template->param(%$borrower);
582 # Restore date if changed by holds and/or save stickyduedate to session
583 if ($restoreduedatespec || $stickyduedate) {
584 $duedatespec = $restoreduedatespec || $duedatespec;
586 if ($stickyduedate) {
587 $session->param( 'stickyduedate', $duedatespec );
589 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
590 undef $duedatespec;
593 $template->param(
594 lib_messages_loop => $lib_messages_loop,
595 bor_messages_loop => $bor_messages_loop,
596 all_messages_del => C4::Context->preference('AllowAllMessageDeletion'),
597 findborrower => $findborrower,
598 borrower => $borrower,
599 borrowernumber => $borrowernumber,
600 categoryname => $borrower->{'description'},
601 branch => $branch,
602 branchname => GetBranchName($borrower->{'branchcode'}),
603 printer => $printer,
604 printername => $printer,
605 was_renewed => $query->param('was_renewed') ? 1 : 0,
606 expiry => $borrower->{'dateexpiry'},
607 roadtype => $roadtype,
608 amountold => $amountold,
609 barcodes => $barcodes,
610 stickyduedate => $stickyduedate,
611 duedatespec => $duedatespec,
612 restoreduedatespec => $restoreduedatespec,
613 message => $message,
614 totaldue => sprintf('%.2f', $total),
615 inprocess => $inprocess,
616 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
617 $view => 1,
618 batch_allowed => $batch_allowed,
619 AudioAlerts => C4::Context->preference("AudioAlerts"),
620 fast_cataloging => $fast_cataloging,
621 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
622 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
623 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
624 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
625 RoutingSerials => C4::Context->preference('RoutingSerials'),
626 relatives_issues_count => $relatives_issues_count,
627 relatives_borrowernumbers => \@relatives,
630 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
631 $template->param( picture => 1 ) if $picture;
633 # get authorised values with type of BOR_NOTES
635 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
637 $template->param(
638 debt_confirmed => $debt_confirmed,
639 SpecifyDueDate => $duedatespec_allow,
640 CircAutocompl => C4::Context->preference("CircAutocompl"),
641 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
642 canned_bor_notes_loop => $canned_notes,
643 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
644 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
647 output_html_with_http_headers $query, $cookie, $template->output;