Updating database to version 3.18.07.001
[koha.git] / circ / circulation.pl
blob95ffa0b74c36b38a9582afaf3388531a5c63f3a7
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;
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 && !$duedatespec_allow ) {
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 if (C4::Context->preference("AddPatronLists")=~/code/){
211 my $categories = GetBorrowercategoryList;
212 $categories->[0]->{'first'} = 1;
213 $template->param(categories=>$categories);
216 if ( @$borrowers == 0 ) {
217 $query->param( 'findborrower', '' );
218 $message = "'$findborrower'";
220 elsif ( @$borrowers == 1 ) {
221 $borrowernumber = $borrowers->[0]->{'borrowernumber'};
222 $query->param( 'borrowernumber', $borrowernumber );
223 $query->param( 'barcode', '' );
225 else {
226 $borrowerslist = $borrowers;
230 # get the borrower information.....
231 my $borrower;
232 if ($borrowernumber) {
233 $borrower = GetMemberDetails( $borrowernumber, 0 );
234 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
236 # Warningdate is the date that the warning starts appearing
237 my ( $today_year, $today_month, $today_day) = Today();
238 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
239 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
240 # Renew day is calculated by adding the enrolment period to today
241 my ( $renew_year, $renew_month, $renew_day);
242 if ($enrol_year*$enrol_month*$enrol_day>0) {
243 ( $renew_year, $renew_month, $renew_day) =
244 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
245 0 , $borrower->{'enrolmentperiod'});
247 # if the expiry date is before today ie they have expired
248 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
249 || Date_to_Days($today_year, $today_month, $today_day )
250 > Date_to_Days($warning_year, $warning_month, $warning_day) )
252 #borrowercard expired, no issues
253 $template->param(
254 flagged => "1",
255 noissues => ($force_allow_issue) ? 0 : "1",
256 forceallow => $force_allow_issue,
257 expired => "1",
258 renewaldate => format_date("$renew_year-$renew_month-$renew_day")
261 # check for NotifyBorrowerDeparture
262 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
263 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
264 Date_to_Days( $today_year, $today_month, $today_day ) )
266 # borrower card soon to expire warn librarian
267 $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
268 flagged => "1",);
269 if (C4::Context->preference('ReturnBeforeExpiry')){
270 $template->param("returnbeforeexpiry" => 1);
273 $template->param(
274 overduecount => $od,
275 issuecount => $issue,
276 finetotal => $fines
279 if ( IsDebarred($borrowernumber) ) {
280 $template->param(
281 'userdebarred' => $borrower->{debarred},
282 'debarredcomment' => $borrower->{debarredcomment},
285 if ( $borrower->{debarred} ne "9999-12-31" ) {
286 $template->param( 'userdebarreddate' =>
287 C4::Dates::format_date( $borrower->{debarred} ) );
294 # STEP 3 : ISSUING
297 if ($barcode) {
298 # always check for blockers on issuing
299 my ( $error, $question, $alerts ) =
300 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
301 my $blocker = $invalidduedate ? 1 : 0;
303 $template->param( alert => $alerts );
305 # Get the item title for more information
306 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
307 $template->param(
308 authvalcode_notforloan => C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'}),
310 # Fix for bug 7494: optional checkout-time fallback search for a book
312 if ( $error->{'UNKNOWN_BARCODE'}
313 && C4::Context->preference("itemBarcodeFallbackSearch") )
315 $template->param( FALLBACK => 1 );
317 my $query = "kw=" . $barcode;
318 my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
320 # if multiple hits, offer options to librarian
321 if ( $total_hits > 0 ) {
322 my @options = ();
323 foreach my $hit ( @{$results} ) {
324 my $chosen =
325 TransformMarcToKoha( C4::Context->dbh,
326 C4::Search::new_record_from_zebra('biblioserver',$hit) );
328 # offer all barcodes individually
329 if ( $chosen->{barcode} ) {
330 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
331 my %chosen_single = %{$chosen};
332 $chosen_single{barcode} = $barcode;
333 push( @options, \%chosen_single );
337 $template->param( options => \@options );
341 unless( $onsite_checkout and C4::Context->preference("OnSiteCheckoutsForce") ) {
342 delete $question->{'DEBT'} if ($debt_confirmed);
343 foreach my $impossible ( keys %$error ) {
344 $template->param(
345 $impossible => $$error{$impossible},
346 IMPOSSIBLE => 1
348 $blocker = 1;
351 if( !$blocker || $force_allow_issue ){
352 my $confirm_required = 0;
353 unless($issueconfirmed){
354 # Get the item title for more information
355 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
356 $template->{VARS}->{'additional_materials'} = $getmessageiteminfo->{'materials'};
357 $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
359 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
360 foreach my $needsconfirmation ( keys %$question ) {
361 $template->param(
362 $needsconfirmation => $$question{$needsconfirmation},
363 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
364 getBarcodeMessageIteminfo => $getmessageiteminfo->{'barcode'},
365 NEEDSCONFIRMATION => 1,
366 onsite_checkout => $onsite_checkout,
368 $confirm_required = 1;
371 unless($confirm_required) {
372 my $issue = AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, { onsite_checkout => $onsite_checkout, auto_renew => $session->param('auto_renew') } );
373 $template->param( issue => $issue );
374 $session->clear('auto_renew');
375 $inprocess = 1;
379 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
380 $template->param( issuecount => $issue );
383 # reload the borrower info for the sake of reseting the flags.....
384 if ($borrowernumber) {
385 $borrower = GetMemberDetails( $borrowernumber, 0 );
388 ##################################################################################
389 # BUILD HTML
390 # show all reserves of this borrower, and the position of the reservation ....
391 if ($borrowernumber) {
392 $template->param(
393 holds_count => Koha::Database->new()->schema()->resultset('Reserve')
394 ->count( { borrowernumber => $borrowernumber } ) );
395 my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber);
397 my @WaitingReserveLoop;
398 foreach my $num_res (@borrowerreserv) {
399 if ( $num_res->{'found'} && $num_res->{'found'} eq 'W' ) {
400 my $getiteminfo = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
401 my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
402 my %getWaitingReserveInfo;
403 $getWaitingReserveInfo{title} = $getiteminfo->{'title'};
404 $getWaitingReserveInfo{biblionumber} =
405 $getiteminfo->{'biblionumber'};
406 $getWaitingReserveInfo{itemtype} = $itemtypeinfo->{'description'};
407 $getWaitingReserveInfo{author} = $getiteminfo->{'author'};
408 $getWaitingReserveInfo{itemcallnumber} =
409 $getiteminfo->{'itemcallnumber'};
410 $getWaitingReserveInfo{reservedate} =
411 format_date( $num_res->{'reservedate'} );
412 $getWaitingReserveInfo{waitingat} =
413 GetBranchName( $num_res->{'branchcode'} );
414 $getWaitingReserveInfo{waitinghere} = 1
415 if $num_res->{'branchcode'} eq $branch;
416 push( @WaitingReserveLoop, \%getWaitingReserveInfo );
419 $template->param( WaitingReserveLoop => \@WaitingReserveLoop );
420 $template->param( adultborrower => 1 )
421 if ( $borrower->{'category_type'} eq 'A' );
424 my @values;
425 my %labels;
426 my $selectborrower;
427 if ($borrowerslist) {
428 foreach (
429 sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
430 } @$borrowerslist
433 push @values, $_->{'borrowernumber'};
434 $labels{ $_->{'borrowernumber'} } =
435 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'} - $_->{'branchcode'}) ... $_->{'address'} ";
437 $selectborrower = {
438 values => \@values,
439 labels => \%labels,
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}->{'CHARGES'}->{'message'} || 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 # Computes full borrower address
532 my @fulladdress;
533 push @fulladdress, $borrower->{'streetnumber'} if ( $borrower->{'streetnumber'} );
534 push @fulladdress, C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{'streettype'} ) if ( $borrower->{'streettype'} );
535 push @fulladdress, $borrower->{'address'} if ( $borrower->{'address'} );
537 my $fast_cataloging = 0;
538 if (defined getframeworkinfo('FA')) {
539 $fast_cataloging = 1
542 if (C4::Context->preference('ExtendedPatronAttributes')) {
543 my $attributes = GetBorrowerAttributes($borrowernumber);
544 $template->param(
545 ExtendedPatronAttributes => 1,
546 extendedattributes => $attributes
550 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
551 my $relatives_issues_count =
552 Koha::Database->new()->schema()->resultset('Issue')
553 ->count( { borrowernumber => \@relatives } );
555 $template->param(
556 lib_messages_loop => $lib_messages_loop,
557 bor_messages_loop => $bor_messages_loop,
558 all_messages_del => C4::Context->preference('AllowAllMessageDeletion'),
559 findborrower => $findborrower,
560 borrower => $borrower,
561 borrowernumber => $borrowernumber,
562 branch => $branch,
563 branchname => GetBranchName($borrower->{'branchcode'}),
564 printer => $printer,
565 printername => $printer,
566 firstname => $borrower->{'firstname'},
567 surname => $borrower->{'surname'},
568 showname => $borrower->{'showname'},
569 category_type => $borrower->{'category_type'},
570 was_renewed => $query->param('was_renewed') ? 1 : 0,
571 expiry => format_date($borrower->{'dateexpiry'}),
572 categorycode => $borrower->{'categorycode'},
573 categoryname => $borrower->{description},
574 address => join(' ', @fulladdress),
575 address2 => $borrower->{'address2'},
576 email => $borrower->{'email'},
577 emailpro => $borrower->{'emailpro'},
578 borrowernotes => $borrower->{'borrowernotes'},
579 city => $borrower->{'city'},
580 state => $borrower->{'state'},
581 zipcode => $borrower->{'zipcode'},
582 country => $borrower->{'country'},
583 phone => $borrower->{'phone'},
584 mobile => $borrower->{'mobile'},
585 phonepro => $borrower->{'phonepro'},
586 cardnumber => $borrower->{'cardnumber'},
587 othernames => $borrower->{'othernames'},
588 amountold => $amountold,
589 barcode => $barcode,
590 stickyduedate => $stickyduedate,
591 duedatespec => $duedatespec,
592 message => $message,
593 selectborrower => $selectborrower,
594 totaldue => sprintf('%.2f', $total),
595 inprocess => $inprocess,
596 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
597 circview => 1,
598 soundon => C4::Context->preference("SoundOn"),
599 fast_cataloging => $fast_cataloging,
600 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
601 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
602 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
603 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
604 RoutingSerials => C4::Context->preference('RoutingSerials'),
605 relatives_issues_count => $relatives_issues_count,
606 relatives_borrowernumbers => \@relatives,
609 # save stickyduedate to session
610 if ($stickyduedate) {
611 $session->param( 'stickyduedate', $duedatespec );
614 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
615 $template->param( picture => 1 ) if $picture;
617 # get authorised values with type of BOR_NOTES
619 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
621 $template->param(
622 debt_confirmed => $debt_confirmed,
623 SpecifyDueDate => $duedatespec_allow,
624 CircAutocompl => C4::Context->preference("CircAutocompl"),
625 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
626 canned_bor_notes_loop => $canned_notes,
627 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
628 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
631 output_html_with_http_headers $query, $cookie, $template->output;