Bug 12692 - Markup improvements to holds awaiting pickup report
[koha.git] / circ / circulation.pl
blobbd7f821395e06bed5654c2e092f47042dd1f7755
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 @failedrenews = $query->param('failedrenew'); # expected to be itemnumbers
108 our %renew_failed = ();
109 for (@failedrenews) { $renew_failed{$_} = 1; }
111 my @failedreturns = $query->param('failedreturn');
112 our %return_failed = ();
113 for (@failedreturns) { $return_failed{$_} = 1; }
115 my $findborrower = $query->param('findborrower') || q{};
116 $findborrower =~ s|,| |g;
117 my $borrowernumber = $query->param('borrowernumber');
119 $branch = C4::Context->userenv->{'branch'};
120 $printer = C4::Context->userenv->{'branchprinter'};
123 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
124 if (C4::Context->preference("AutoLocation") != 1) {
125 $template->param(ManualLocation => 1);
128 if (C4::Context->preference("DisplayClearScreenButton")) {
129 $template->param(DisplayClearScreenButton => 1);
132 my $barcode = $query->param('barcode') || q{};
133 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
135 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
136 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
137 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
138 my $issueconfirmed = $query->param('issueconfirmed');
139 my $cancelreserve = $query->param('cancelreserve');
140 my $print = $query->param('print') || q{};
141 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
142 my $charges = $query->param('charges') || q{};
144 # Check if stickyduedate is turned off
145 if ( $barcode ) {
146 # was stickyduedate loaded from session?
147 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
148 $session->clear( 'stickyduedate' );
149 $stickyduedate = $query->param('stickyduedate');
150 $duedatespec = $query->param('duedatespec');
152 $session->param('auto_renew', $query->param('auto_renew'));
154 else {
155 $session->clear('auto_renew');
158 my ($datedue,$invalidduedate);
160 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
161 if($duedatespec_allow){
162 if ($duedatespec) {
163 if ($duedatespec =~ C4::Dates->regexp('syspref')) {
164 $datedue = dt_from_string($duedatespec);
165 } else {
166 $invalidduedate = 1;
167 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
172 our $todaysdate = C4::Dates->new->output('iso');
174 # check and see if we should print
175 if ( $barcode eq '' && $print eq 'maybe' ) {
176 $print = 'yes';
179 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
180 if ( $barcode eq '' && $charges eq 'yes' ) {
181 $template->param(
182 PAYCHARGES => 'yes',
183 borrowernumber => $borrowernumber
187 if ( $print eq 'yes' && $borrowernumber ne '' ) {
188 if ( C4::Context->boolean_preference('printcirculationslips') ) {
189 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
190 NetworkPrint($letter->{content});
192 $query->param( 'borrowernumber', '' );
193 $borrowernumber = '';
197 # STEP 2 : FIND BORROWER
198 # if there is a list of find borrowers....
200 my $borrowerslist;
201 my $message;
202 if ($findborrower) {
203 my $borrowers = Search($findborrower, 'cardnumber') || [];
204 if (C4::Context->preference("AddPatronLists")) {
205 $template->param(
206 "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
208 if (C4::Context->preference("AddPatronLists")=~/code/){
209 my $categories = GetBorrowercategoryList;
210 $categories->[0]->{'first'} = 1;
211 $template->param(categories=>$categories);
214 if ( @$borrowers == 0 ) {
215 $query->param( 'findborrower', '' );
216 $message = "'$findborrower'";
218 elsif ( @$borrowers == 1 ) {
219 $borrowernumber = $borrowers->[0]->{'borrowernumber'};
220 $query->param( 'borrowernumber', $borrowernumber );
221 $query->param( 'barcode', '' );
223 else {
224 $borrowerslist = $borrowers;
228 # get the borrower information.....
229 my $borrower;
230 if ($borrowernumber) {
231 $borrower = GetMemberDetails( $borrowernumber, 0 );
232 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
234 # Warningdate is the date that the warning starts appearing
235 my ( $today_year, $today_month, $today_day) = Today();
236 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
237 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
238 # Renew day is calculated by adding the enrolment period to today
239 my ( $renew_year, $renew_month, $renew_day);
240 if ($enrol_year*$enrol_month*$enrol_day>0) {
241 ( $renew_year, $renew_month, $renew_day) =
242 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
243 0 , $borrower->{'enrolmentperiod'});
245 # if the expiry date is before today ie they have expired
246 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
247 || Date_to_Days($today_year, $today_month, $today_day )
248 > Date_to_Days($warning_year, $warning_month, $warning_day) )
250 #borrowercard expired, no issues
251 $template->param(
252 flagged => "1",
253 noissues => ($force_allow_issue) ? 0 : "1",
254 forceallow => $force_allow_issue,
255 expired => "1",
256 renewaldate => format_date("$renew_year-$renew_month-$renew_day")
259 # check for NotifyBorrowerDeparture
260 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
261 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
262 Date_to_Days( $today_year, $today_month, $today_day ) )
264 # borrower card soon to expire warn librarian
265 $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
266 flagged => "1",);
267 if (C4::Context->preference('ReturnBeforeExpiry')){
268 $template->param("returnbeforeexpiry" => 1);
271 $template->param(
272 overduecount => $od,
273 issuecount => $issue,
274 finetotal => $fines
277 if ( IsDebarred($borrowernumber) ) {
278 $template->param(
279 'userdebarred' => $borrower->{debarred},
280 'debarredcomment' => $borrower->{debarredcomment},
283 if ( $borrower->{debarred} ne "9999-12-31" ) {
284 $template->param( 'userdebarreddate' =>
285 C4::Dates::format_date( $borrower->{debarred} ) );
292 # STEP 3 : ISSUING
295 if ($barcode) {
296 # always check for blockers on issuing
297 my ( $error, $question, $alerts ) =
298 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
299 my $blocker = $invalidduedate ? 1 : 0;
301 $template->param( alert => $alerts );
303 # Get the item title for more information
304 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
305 $template->param(
306 authvalcode_notforloan => C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'}),
308 # Fix for bug 7494: optional checkout-time fallback search for a book
310 if ( $error->{'UNKNOWN_BARCODE'}
311 && C4::Context->preference("itemBarcodeFallbackSearch") )
313 $template->param( FALLBACK => 1 );
315 my $query = "kw=" . $barcode;
316 my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
318 # if multiple hits, offer options to librarian
319 if ( $total_hits > 0 ) {
320 my @options = ();
321 foreach my $hit ( @{$results} ) {
322 my $chosen =
323 TransformMarcToKoha( C4::Context->dbh,
324 C4::Search::new_record_from_zebra('biblioserver',$hit) );
326 # offer all barcodes individually
327 if ( $chosen->{barcode} ) {
328 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
329 my %chosen_single = %{$chosen};
330 $chosen_single{barcode} = $barcode;
331 push( @options, \%chosen_single );
335 $template->param( options => \@options );
339 unless( $query->param('onsite_checkout') and C4::Context->preference("OnSiteCheckoutsForce") ) {
340 delete $question->{'DEBT'} if ($debt_confirmed);
341 foreach my $impossible ( keys %$error ) {
342 $template->param(
343 $impossible => $$error{$impossible},
344 IMPOSSIBLE => 1
346 $blocker = 1;
349 if( !$blocker || $force_allow_issue ){
350 my $confirm_required = 0;
351 unless($issueconfirmed){
352 # Get the item title for more information
353 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
354 $template->{VARS}->{'additional_materials'} = $getmessageiteminfo->{'materials'};
355 $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
357 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
358 foreach my $needsconfirmation ( keys %$question ) {
359 $template->param(
360 $needsconfirmation => $$question{$needsconfirmation},
361 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
362 getBarcodeMessageIteminfo => $getmessageiteminfo->{'barcode'},
363 NEEDSCONFIRMATION => 1,
364 onsite_checkout => $query->param('onsite_checkout'),
366 $confirm_required = 1;
369 unless($confirm_required) {
370 my $onsite_checkout = $query->param('onsite_checkout');
371 AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, { onsite_checkout => $onsite_checkout, auto_renew => $session->param('auto_renew') } );
372 $session->clear('auto_renew');
373 $inprocess = 1;
377 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
378 $template->param( issuecount => $issue );
381 # reload the borrower info for the sake of reseting the flags.....
382 if ($borrowernumber) {
383 $borrower = GetMemberDetails( $borrowernumber, 0 );
386 ##################################################################################
387 # BUILD HTML
388 # show all reserves of this borrower, and the position of the reservation ....
389 if ($borrowernumber) {
390 $template->param(
391 holds_count => Koha::Database->new()->schema()->resultset('Reserve')
392 ->count( { borrowernumber => $borrowernumber } ) );
393 my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber);
395 my @WaitingReserveLoop;
396 foreach my $num_res (@borrowerreserv) {
397 if ( $num_res->{'found'} && $num_res->{'found'} eq 'W' ) {
398 my $getiteminfo = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
399 my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
400 my %getWaitingReserveInfo;
401 $getWaitingReserveInfo{title} = $getiteminfo->{'title'};
402 $getWaitingReserveInfo{biblionumber} =
403 $getiteminfo->{'biblionumber'};
404 $getWaitingReserveInfo{itemtype} = $itemtypeinfo->{'description'};
405 $getWaitingReserveInfo{author} = $getiteminfo->{'author'};
406 $getWaitingReserveInfo{itemcallnumber} =
407 $getiteminfo->{'itemcallnumber'};
408 $getWaitingReserveInfo{reservedate} =
409 format_date( $num_res->{'reservedate'} );
410 $getWaitingReserveInfo{waitingat} =
411 GetBranchName( $num_res->{'branchcode'} );
412 $getWaitingReserveInfo{waitinghere} = 1
413 if $num_res->{'branchcode'} eq $branch;
414 push( @WaitingReserveLoop, \%getWaitingReserveInfo );
417 $template->param( WaitingReserveLoop => \@WaitingReserveLoop );
418 $template->param( adultborrower => 1 )
419 if ( $borrower->{'category_type'} eq 'A' );
422 my @values;
423 my %labels;
424 my $selectborrower;
425 if ($borrowerslist) {
426 foreach (
427 sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
428 } @$borrowerslist
431 push @values, $_->{'borrowernumber'};
432 $labels{ $_->{'borrowernumber'} } =
433 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'} - $_->{'branchcode'}) ... $_->{'address'} ";
435 $selectborrower = {
436 values => \@values,
437 labels => \%labels,
441 #title
442 my $flags = $borrower->{'flags'};
443 foreach my $flag ( sort keys %$flags ) {
444 $template->param( flagged=> 1);
445 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
446 if ( $flags->{$flag}->{'noissues'} ) {
447 $template->param(
448 noissues => ($force_allow_issue) ? 0 : 'true',
449 forceallow => $force_allow_issue,
451 if ( $flag eq 'GNA' ) {
452 $template->param( gna => 'true' );
454 elsif ( $flag eq 'LOST' ) {
455 $template->param( lost => 'true' );
457 elsif ( $flag eq 'DBARRED' ) {
458 $template->param( dbarred => 'true' );
460 elsif ( $flag eq 'CHARGES' ) {
461 $template->param(
462 charges => 'true',
463 chargesmsg => $flags->{'CHARGES'}->{'message'},
464 chargesamount => $flags->{'CHARGES'}->{'amount'},
465 charges_is_blocker => 1
468 elsif ( $flag eq 'CREDITS' ) {
469 $template->param(
470 credits => 'true',
471 creditsmsg => $flags->{'CREDITS'}->{'message'},
472 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
476 else {
477 if ( $flag eq 'CHARGES' ) {
478 $template->param(
479 charges => 'true',
480 chargesmsg => $flags->{'CHARGES'}->{'message'},
481 chargesamount => $flags->{'CHARGES'}->{'amount'},
484 elsif ( $flag eq 'CREDITS' ) {
485 $template->param(
486 credits => 'true',
487 creditsmsg => $flags->{'CREDITS'}->{'message'},
488 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
491 elsif ( $flag eq 'ODUES' ) {
492 $template->param(
493 odues => 'true',
494 oduesmsg => $flags->{'ODUES'}->{'message'}
497 my $items = $flags->{$flag}->{'itemlist'};
498 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
499 $template->param( nonreturns => 'true' );
502 elsif ( $flag eq 'NOTES' ) {
503 $template->param(
504 notes => 'true',
505 notesmsg => $flags->{'NOTES'}->{'message'}
511 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
512 $amountold =~ s/^.*\$//; # remove upto the $, if any
514 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
516 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
517 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
518 my $cnt = scalar(@$catcodes);
519 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
520 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
523 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
524 if($lib_messages_loop){ $template->param(flagged => 1 ); }
526 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
527 if($bor_messages_loop){ $template->param(flagged => 1 ); }
529 # Computes full borrower address
530 my @fulladdress;
531 push @fulladdress, $borrower->{'streetnumber'} if ( $borrower->{'streetnumber'} );
532 push @fulladdress, C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{'streettype'} ) if ( $borrower->{'streettype'} );
533 push @fulladdress, $borrower->{'address'} if ( $borrower->{'address'} );
535 my $fast_cataloging = 0;
536 if (defined getframeworkinfo('FA')) {
537 $fast_cataloging = 1
540 if (C4::Context->preference('ExtendedPatronAttributes')) {
541 my $attributes = GetBorrowerAttributes($borrowernumber);
542 $template->param(
543 ExtendedPatronAttributes => 1,
544 extendedattributes => $attributes
548 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
549 my $relatives_issues_count =
550 Koha::Database->new()->schema()->resultset('Issue')
551 ->count( { borrowernumber => \@relatives } );
553 $template->param(
554 lib_messages_loop => $lib_messages_loop,
555 bor_messages_loop => $bor_messages_loop,
556 all_messages_del => C4::Context->preference('AllowAllMessageDeletion'),
557 findborrower => $findborrower,
558 borrower => $borrower,
559 borrowernumber => $borrowernumber,
560 branch => $branch,
561 branchname => GetBranchName($borrower->{'branchcode'}),
562 printer => $printer,
563 printername => $printer,
564 firstname => $borrower->{'firstname'},
565 surname => $borrower->{'surname'},
566 showname => $borrower->{'showname'},
567 category_type => $borrower->{'category_type'},
568 was_renewed => $query->param('was_renewed') ? 1 : 0,
569 expiry => format_date($borrower->{'dateexpiry'}),
570 categorycode => $borrower->{'categorycode'},
571 categoryname => $borrower->{description},
572 address => join(' ', @fulladdress),
573 address2 => $borrower->{'address2'},
574 email => $borrower->{'email'},
575 emailpro => $borrower->{'emailpro'},
576 borrowernotes => $borrower->{'borrowernotes'},
577 city => $borrower->{'city'},
578 state => $borrower->{'state'},
579 zipcode => $borrower->{'zipcode'},
580 country => $borrower->{'country'},
581 phone => $borrower->{'phone'},
582 mobile => $borrower->{'mobile'},
583 phonepro => $borrower->{'phonepro'},
584 cardnumber => $borrower->{'cardnumber'},
585 othernames => $borrower->{'othernames'},
586 amountold => $amountold,
587 barcode => $barcode,
588 stickyduedate => $stickyduedate,
589 duedatespec => $duedatespec,
590 message => $message,
591 selectborrower => $selectborrower,
592 totaldue => sprintf('%.2f', $total),
593 inprocess => $inprocess,
594 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
595 circview => 1,
596 soundon => C4::Context->preference("SoundOn"),
597 fast_cataloging => $fast_cataloging,
598 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
599 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
600 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
601 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
602 RoutingSerials => C4::Context->preference('RoutingSerials'),
603 relatives_issues_count => $relatives_issues_count,
604 relatives_borrowernumbers => \@relatives,
607 # save stickyduedate to session
608 if ($stickyduedate) {
609 $session->param( 'stickyduedate', $duedatespec );
612 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
613 $template->param( picture => 1 ) if $picture;
615 # get authorised values with type of BOR_NOTES
617 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
619 $template->param(
620 debt_confirmed => $debt_confirmed,
621 SpecifyDueDate => $duedatespec_allow,
622 CircAutocompl => C4::Context->preference("CircAutocompl"),
623 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
624 canned_bor_notes_loop => $canned_notes,
625 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
626 todaysdate => dt_from_string()->set(hour => 23)->set(minute => 59),
629 output_html_with_http_headers $query, $cookie, $template->output;