Bug 13416: Typo in marc21_leader.pl position 5 (record status)
[koha.git] / circ / circulation.pl
blob6e9f449292d0df58dabad505c67e1dca9b702bba
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 under the
13 # terms of the GNU General Public License as published by the Free Software
14 # Foundation; either version 2 of the License, or (at your option) any later
15 # version.
17 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
18 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
21 # You should have received a copy of the GNU General Public License along
22 # with Koha; if not, write to the Free Software Foundation, Inc.,
23 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 use strict;
26 use warnings;
27 use CGI;
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::Dates qw/format_date/;
34 use C4::Branch; # GetBranches
35 use C4::Koha; # GetPrinter
36 use C4::Circulation;
37 use C4::Members;
38 use C4::Biblio;
39 use C4::Search;
40 use MARC::Record;
41 use C4::Reserves;
42 use C4::Context;
43 use CGI::Session;
44 use C4::Members::Attributes qw(GetBorrowerAttributes);
45 use Koha::Borrower::Debarments qw(GetDebarments IsDebarred);
46 use Koha::DateUtils;
47 use Koha::Database;
49 use Date::Calc qw(
50 Today
51 Add_Delta_YM
52 Add_Delta_Days
53 Date_to_Days
55 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 ( $template, $loggedinuser, $cookie ) = get_template_and_user (
92 template_name => 'circ/circulation.tt',
93 query => $query,
94 type => "intranet",
95 authnotrequired => 0,
96 flagsrequired => { circulate => 'circulate_remaining_permissions' },
100 my $branches = GetBranches();
102 my $force_allow_issue = $query->param('forceallow') || 0;
103 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
104 $force_allow_issue = 0;
107 my $onsite_checkout = $query->param('onsite_checkout');
109 my @failedrenews = $query->param('failedrenew'); # expected to be itemnumbers
110 our %renew_failed = ();
111 for (@failedrenews) { $renew_failed{$_} = 1; }
113 my @failedreturns = $query->param('failedreturn');
114 our %return_failed = ();
115 for (@failedreturns) { $return_failed{$_} = 1; }
117 my $findborrower = $query->param('findborrower') || q{};
118 $findborrower =~ s|,| |g;
119 my $borrowernumber = $query->param('borrowernumber');
121 $branch = C4::Context->userenv->{'branch'};
122 $printer = C4::Context->userenv->{'branchprinter'};
125 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
126 if (C4::Context->preference("AutoLocation") != 1) {
127 $template->param(ManualLocation => 1);
130 if (C4::Context->preference("DisplayClearScreenButton")) {
131 $template->param(DisplayClearScreenButton => 1);
134 my $barcode = $query->param('barcode') || q{};
135 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
137 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
138 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
139 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
140 my $issueconfirmed = $query->param('issueconfirmed');
141 my $cancelreserve = $query->param('cancelreserve');
142 my $print = $query->param('print') || q{};
143 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
144 my $charges = $query->param('charges') || q{};
146 # Check if stickyduedate is turned off
147 if ( $barcode ) {
148 # was stickyduedate loaded from session?
149 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
150 $session->clear( 'stickyduedate' );
151 $stickyduedate = $query->param('stickyduedate');
152 $duedatespec = $query->param('duedatespec');
154 $session->param('auto_renew', $query->param('auto_renew'));
156 else {
157 $session->clear('auto_renew');
160 my ($datedue,$invalidduedate);
162 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
163 if( $onsite_checkout ) {
164 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
165 $datedue .= ' 23:59:00';
166 } elsif( $duedatespec_allow ) {
167 if ($duedatespec) {
168 if ($duedatespec =~ C4::Dates->regexp('syspref')) {
169 $datedue = dt_from_string($duedatespec);
170 } else {
171 $invalidduedate = 1;
172 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
177 our $todaysdate = C4::Dates->new->output('iso');
179 # check and see if we should print
180 if ( $barcode eq '' && $print eq 'maybe' ) {
181 $print = 'yes';
184 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
185 if ( $barcode eq '' && $charges eq 'yes' ) {
186 $template->param(
187 PAYCHARGES => 'yes',
188 borrowernumber => $borrowernumber
192 if ( $print eq 'yes' && $borrowernumber ne '' ) {
193 if ( C4::Context->boolean_preference('printcirculationslips') ) {
194 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
195 NetworkPrint($letter->{content});
197 $query->param( 'borrowernumber', '' );
198 $borrowernumber = '';
202 # STEP 2 : FIND BORROWER
203 # if there is a list of find borrowers....
205 my $borrowerslist;
206 my $message;
207 if ($findborrower) {
208 my $borrowers = Search($findborrower, 'cardnumber') || [];
209 if (C4::Context->preference("AddPatronLists")) {
210 $template->param(
211 "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
213 if (C4::Context->preference("AddPatronLists")=~/code/){
214 my $categories = GetBorrowercategoryList;
215 $categories->[0]->{'first'} = 1;
216 $template->param(categories=>$categories);
219 if ( @$borrowers == 0 ) {
220 $query->param( 'findborrower', '' );
221 $message = "'$findborrower'";
223 elsif ( @$borrowers == 1 ) {
224 $borrowernumber = $borrowers->[0]->{'borrowernumber'};
225 $query->param( 'borrowernumber', $borrowernumber );
226 $query->param( 'barcode', '' );
228 else {
229 $borrowerslist = $borrowers;
233 # get the borrower information.....
234 my $borrower;
235 if ($borrowernumber) {
236 $borrower = GetMemberDetails( $borrowernumber, 0 );
237 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
239 # Warningdate is the date that the warning starts appearing
240 my ( $today_year, $today_month, $today_day) = Today();
241 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
242 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
243 # Renew day is calculated by adding the enrolment period to today
244 my ( $renew_year, $renew_month, $renew_day);
245 if ($enrol_year*$enrol_month*$enrol_day>0) {
246 ( $renew_year, $renew_month, $renew_day) =
247 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
248 0 , $borrower->{'enrolmentperiod'});
250 # if the expiry date is before today ie they have expired
251 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
252 || Date_to_Days($today_year, $today_month, $today_day )
253 > Date_to_Days($warning_year, $warning_month, $warning_day) )
255 #borrowercard expired, no issues
256 $template->param(
257 flagged => "1",
258 noissues => ($force_allow_issue) ? 0 : "1",
259 forceallow => $force_allow_issue,
260 expired => "1",
261 renewaldate => format_date("$renew_year-$renew_month-$renew_day")
264 # check for NotifyBorrowerDeparture
265 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
266 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
267 Date_to_Days( $today_year, $today_month, $today_day ) )
269 # borrower card soon to expire warn librarian
270 $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
271 flagged => "1",);
272 if (C4::Context->preference('ReturnBeforeExpiry')){
273 $template->param("returnbeforeexpiry" => 1);
276 $template->param(
277 overduecount => $od,
278 issuecount => $issue,
279 finetotal => $fines
282 if ( IsDebarred($borrowernumber) ) {
283 $template->param(
284 'userdebarred' => $borrower->{debarred},
285 'debarredcomment' => $borrower->{debarredcomment},
288 if ( $borrower->{debarred} ne "9999-12-31" ) {
289 $template->param( 'userdebarreddate' =>
290 C4::Dates::format_date( $borrower->{debarred} ) );
297 # STEP 3 : ISSUING
300 if ($barcode) {
301 # always check for blockers on issuing
302 my ( $error, $question, $alerts ) =
303 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
304 my $blocker = $invalidduedate ? 1 : 0;
306 $template->param( alert => $alerts );
308 # Get the item title for more information
309 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
310 $template->param(
311 authvalcode_notforloan => C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'}),
313 # Fix for bug 7494: optional checkout-time fallback search for a book
315 if ( $error->{'UNKNOWN_BARCODE'}
316 && C4::Context->preference("itemBarcodeFallbackSearch") )
318 $template->param( FALLBACK => 1 );
320 my $query = "kw=" . $barcode;
321 my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
323 # if multiple hits, offer options to librarian
324 if ( $total_hits > 0 ) {
325 my @options = ();
326 foreach my $hit ( @{$results} ) {
327 my $chosen =
328 TransformMarcToKoha( C4::Context->dbh,
329 C4::Search::new_record_from_zebra('biblioserver',$hit) );
331 # offer all barcodes individually
332 if ( $chosen->{barcode} ) {
333 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
334 my %chosen_single = %{$chosen};
335 $chosen_single{barcode} = $barcode;
336 push( @options, \%chosen_single );
340 $template->param( options => \@options );
344 unless( $onsite_checkout and C4::Context->preference("OnSiteCheckoutsForce") ) {
345 delete $question->{'DEBT'} if ($debt_confirmed);
346 foreach my $impossible ( keys %$error ) {
347 $template->param(
348 $impossible => $$error{$impossible},
349 IMPOSSIBLE => 1
351 $blocker = 1;
354 if( !$blocker || $force_allow_issue ){
355 my $confirm_required = 0;
356 unless($issueconfirmed){
357 # Get the item title for more information
358 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
359 $template->{VARS}->{'additional_materials'} = $getmessageiteminfo->{'materials'};
360 $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
362 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
363 foreach my $needsconfirmation ( keys %$question ) {
364 $template->param(
365 $needsconfirmation => $$question{$needsconfirmation},
366 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
367 getBarcodeMessageIteminfo => $getmessageiteminfo->{'barcode'},
368 NEEDSCONFIRMATION => 1,
369 onsite_checkout => $onsite_checkout,
371 $confirm_required = 1;
374 unless($confirm_required) {
375 AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, { onsite_checkout => $onsite_checkout, auto_renew => $session->param('auto_renew') } );
376 $session->clear('auto_renew');
377 $inprocess = 1;
381 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
382 $template->param( issuecount => $issue );
385 # reload the borrower info for the sake of reseting the flags.....
386 if ($borrowernumber) {
387 $borrower = GetMemberDetails( $borrowernumber, 0 );
390 ##################################################################################
391 # BUILD HTML
392 # show all reserves of this borrower, and the position of the reservation ....
393 if ($borrowernumber) {
394 $template->param(
395 holds_count => Koha::Database->new()->schema()->resultset('Reserve')
396 ->count( { borrowernumber => $borrowernumber } ) );
397 my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber);
399 my @WaitingReserveLoop;
400 foreach my $num_res (@borrowerreserv) {
401 if ( $num_res->{'found'} && $num_res->{'found'} eq 'W' ) {
402 my $getiteminfo = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
403 my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
404 my %getWaitingReserveInfo;
405 $getWaitingReserveInfo{title} = $getiteminfo->{'title'};
406 $getWaitingReserveInfo{biblionumber} =
407 $getiteminfo->{'biblionumber'};
408 $getWaitingReserveInfo{itemtype} = $itemtypeinfo->{'description'};
409 $getWaitingReserveInfo{author} = $getiteminfo->{'author'};
410 $getWaitingReserveInfo{itemcallnumber} =
411 $getiteminfo->{'itemcallnumber'};
412 $getWaitingReserveInfo{reservedate} =
413 format_date( $num_res->{'reservedate'} );
414 $getWaitingReserveInfo{waitingat} =
415 GetBranchName( $num_res->{'branchcode'} );
416 $getWaitingReserveInfo{waitinghere} = 1
417 if $num_res->{'branchcode'} eq $branch;
418 push( @WaitingReserveLoop, \%getWaitingReserveInfo );
421 $template->param( WaitingReserveLoop => \@WaitingReserveLoop );
422 $template->param( adultborrower => 1 )
423 if ( $borrower->{'category_type'} eq 'A' );
426 my @values;
427 my %labels;
428 my $selectborrower;
429 if ($borrowerslist) {
430 foreach (
431 sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
432 } @$borrowerslist
435 push @values, $_->{'borrowernumber'};
436 $labels{ $_->{'borrowernumber'} } =
437 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'} - $_->{'branchcode'}) ... $_->{'address'} ";
439 $selectborrower = {
440 values => \@values,
441 labels => \%labels,
445 #title
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'} ) {
451 $template->param(
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' ) {
465 $template->param(
466 charges => 'true',
467 chargesmsg => $flags->{'CHARGES'}->{'message'},
468 chargesamount => $flags->{'CHARGES'}->{'amount'},
469 charges_is_blocker => 1
472 elsif ( $flag eq 'CREDITS' ) {
473 $template->param(
474 credits => 'true',
475 creditsmsg => $flags->{'CREDITS'}->{'message'},
476 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
480 else {
481 if ( $flag eq 'CHARGES' ) {
482 $template->param(
483 charges => 'true',
484 chargesmsg => $flags->{'CHARGES'}->{'message'},
485 chargesamount => $flags->{'CHARGES'}->{'amount'},
488 elsif ( $flag eq 'CREDITS' ) {
489 $template->param(
490 credits => 'true',
491 creditsmsg => $flags->{'CREDITS'}->{'message'},
492 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
495 elsif ( $flag eq 'ODUES' ) {
496 $template->param(
497 odues => 'true',
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' ) {
507 $template->param(
508 notes => 'true',
509 notesmsg => $flags->{'NOTES'}->{'message'}
515 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 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 # Computes full borrower address
534 my @fulladdress;
535 push @fulladdress, $borrower->{'streetnumber'} if ( $borrower->{'streetnumber'} );
536 push @fulladdress, C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{'streettype'} ) if ( $borrower->{'streettype'} );
537 push @fulladdress, $borrower->{'address'} if ( $borrower->{'address'} );
539 my $fast_cataloging = 0;
540 if (defined getframeworkinfo('FA')) {
541 $fast_cataloging = 1
544 if (C4::Context->preference('ExtendedPatronAttributes')) {
545 my $attributes = GetBorrowerAttributes($borrowernumber);
546 $template->param(
547 ExtendedPatronAttributes => 1,
548 extendedattributes => $attributes
552 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
553 my $relatives_issues_count =
554 Koha::Database->new()->schema()->resultset('Issue')
555 ->count( { borrowernumber => \@relatives } );
557 $template->param(
558 lib_messages_loop => $lib_messages_loop,
559 bor_messages_loop => $bor_messages_loop,
560 all_messages_del => C4::Context->preference('AllowAllMessageDeletion'),
561 findborrower => $findborrower,
562 borrower => $borrower,
563 borrowernumber => $borrowernumber,
564 branch => $branch,
565 branchname => GetBranchName($borrower->{'branchcode'}),
566 printer => $printer,
567 printername => $printer,
568 firstname => $borrower->{'firstname'},
569 surname => $borrower->{'surname'},
570 showname => $borrower->{'showname'},
571 category_type => $borrower->{'category_type'},
572 was_renewed => $query->param('was_renewed') ? 1 : 0,
573 expiry => format_date($borrower->{'dateexpiry'}),
574 categorycode => $borrower->{'categorycode'},
575 categoryname => $borrower->{description},
576 address => join(' ', @fulladdress),
577 address2 => $borrower->{'address2'},
578 email => $borrower->{'email'},
579 emailpro => $borrower->{'emailpro'},
580 borrowernotes => $borrower->{'borrowernotes'},
581 city => $borrower->{'city'},
582 state => $borrower->{'state'},
583 zipcode => $borrower->{'zipcode'},
584 country => $borrower->{'country'},
585 phone => $borrower->{'phone'},
586 mobile => $borrower->{'mobile'},
587 phonepro => $borrower->{'phonepro'},
588 cardnumber => $borrower->{'cardnumber'},
589 othernames => $borrower->{'othernames'},
590 amountold => $amountold,
591 barcode => $barcode,
592 stickyduedate => $stickyduedate,
593 duedatespec => $duedatespec,
594 message => $message,
595 selectborrower => $selectborrower,
596 totaldue => sprintf('%.2f', $total),
597 inprocess => $inprocess,
598 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
599 circview => 1,
600 soundon => C4::Context->preference("SoundOn"),
601 fast_cataloging => $fast_cataloging,
602 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
603 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
604 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
605 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
606 RoutingSerials => C4::Context->preference('RoutingSerials'),
607 relatives_issues_count => $relatives_issues_count,
608 relatives_borrowernumbers => \@relatives,
611 # save stickyduedate to session
612 if ($stickyduedate) {
613 $session->param( 'stickyduedate', $duedatespec );
616 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
617 $template->param( picture => 1 ) if $picture;
619 # get authorised values with type of BOR_NOTES
621 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
623 $template->param(
624 debt_confirmed => $debt_confirmed,
625 SpecifyDueDate => $duedatespec_allow,
626 CircAutocompl => C4::Context->preference("CircAutocompl"),
627 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
628 canned_bor_notes_loop => $canned_notes,
629 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
630 todaysdate => dt_from_string()->set(hour => 23)->set(minute => 59),
633 output_html_with_http_headers $query, $cookie, $template->output;