Bug 12879: Remove unnecesary diags from Holds.t
[koha.git] / circ / circulation.pl
blobc766e88541c06af89f5df898649997e8cc124a2b
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 C4::Output;
29 use C4::Print;
30 use C4::Auth qw/:DEFAULT get_session/;
31 use C4::Dates qw/format_date/;
32 use C4::Branch; # GetBranches
33 use C4::Koha; # GetPrinter
34 use C4::Circulation;
35 use C4::Members;
36 use C4::Biblio;
37 use C4::Search;
38 use MARC::Record;
39 use C4::Reserves;
40 use C4::Context;
41 use CGI::Session;
42 use C4::Members::Attributes qw(GetBorrowerAttributes);
43 use Koha::Borrower::Debarments qw(GetDebarments IsDebarred);
44 use Koha::DateUtils;
45 use Koha::Database;
47 use Date::Calc qw(
48 Today
49 Add_Delta_YM
50 Add_Delta_Days
51 Date_to_Days
53 use List::MoreUtils qw/uniq/;
57 # PARAMETERS READING
59 my $query = new CGI;
61 my $sessionID = $query->cookie("CGISESSID") ;
62 my $session = get_session($sessionID);
64 # branch and printer are now defined by the userenv
65 # but first we have to check if someone has tried to change them
67 my $branch = $query->param('branch');
68 if ($branch){
69 # update our session so the userenv is updated
70 $session->param('branch', $branch);
71 $session->param('branchname', GetBranchName($branch));
74 my $printer = $query->param('printer');
75 if ($printer){
76 # update our session so the userenv is updated
77 $session->param('branchprinter', $printer);
80 if (!C4::Context->userenv && !$branch){
81 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
82 # no branch set we can't issue
83 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
84 exit;
88 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
90 template_name => 'circ/circulation.tt',
91 query => $query,
92 type => "intranet",
93 authnotrequired => 0,
94 flagsrequired => { circulate => 'circulate_remaining_permissions' },
98 my $branches = GetBranches();
100 my $findborrower = $query->param('findborrower') || q{};
101 $findborrower =~ s|,| |g;
102 my $borrowernumber = $query->param('borrowernumber');
104 $branch = C4::Context->userenv->{'branch'};
105 $printer = C4::Context->userenv->{'branchprinter'};
108 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
109 if (C4::Context->preference("AutoLocation") != 1) {
110 $template->param(ManualLocation => 1);
113 if (C4::Context->preference("DisplayClearScreenButton")) {
114 $template->param(DisplayClearScreenButton => 1);
117 my $barcode = $query->param('barcode') || q{};
118 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
120 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
121 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
122 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
123 my $issueconfirmed = $query->param('issueconfirmed');
124 my $cancelreserve = $query->param('cancelreserve');
125 my $print = $query->param('print') || q{};
126 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
127 my $charges = $query->param('charges') || q{};
129 # Check if stickyduedate is turned off
130 if ( $barcode ) {
131 # was stickyduedate loaded from session?
132 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
133 $session->clear( 'stickyduedate' );
134 $stickyduedate = $query->param('stickyduedate');
135 $duedatespec = $query->param('duedatespec');
139 my ($datedue,$invalidduedate);
141 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
142 if($duedatespec_allow){
143 if ($duedatespec) {
144 if ($duedatespec =~ C4::Dates->regexp('syspref')) {
145 $datedue = dt_from_string($duedatespec);
146 } else {
147 $invalidduedate = 1;
148 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
153 our $todaysdate = C4::Dates->new->output('iso');
155 # check and see if we should print
156 if ( $barcode eq '' && $print eq 'maybe' ) {
157 $print = 'yes';
160 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
161 if ( $barcode eq '' && $charges eq 'yes' ) {
162 $template->param(
163 PAYCHARGES => 'yes',
164 borrowernumber => $borrowernumber
168 if ( $print eq 'yes' && $borrowernumber ne '' ) {
169 if ( C4::Context->boolean_preference('printcirculationslips') ) {
170 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
171 NetworkPrint($letter->{content});
173 $query->param( 'borrowernumber', '' );
174 $borrowernumber = '';
178 # STEP 2 : FIND BORROWER
179 # if there is a list of find borrowers....
181 my $borrowerslist;
182 my $message;
183 if ($findborrower) {
184 my $borrowers = Search($findborrower, 'cardnumber') || [];
185 if (C4::Context->preference("AddPatronLists")) {
186 $template->param(
187 "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
189 if (C4::Context->preference("AddPatronLists")=~/code/){
190 my $categories = GetBorrowercategoryList;
191 $categories->[0]->{'first'} = 1;
192 $template->param(categories=>$categories);
195 if ( @$borrowers == 0 ) {
196 $query->param( 'findborrower', '' );
197 $message = "'$findborrower'";
199 elsif ( @$borrowers == 1 ) {
200 $borrowernumber = $borrowers->[0]->{'borrowernumber'};
201 $query->param( 'borrowernumber', $borrowernumber );
202 $query->param( 'barcode', '' );
204 else {
205 $borrowerslist = $borrowers;
209 # get the borrower information.....
210 my $borrower;
211 if ($borrowernumber) {
212 $borrower = GetMemberDetails( $borrowernumber, 0 );
213 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
215 # Warningdate is the date that the warning starts appearing
216 my ( $today_year, $today_month, $today_day) = Today();
217 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
218 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
219 # Renew day is calculated by adding the enrolment period to today
220 my ( $renew_year, $renew_month, $renew_day);
221 if ($enrol_year*$enrol_month*$enrol_day>0) {
222 ( $renew_year, $renew_month, $renew_day) =
223 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
224 0 , $borrower->{'enrolmentperiod'});
226 # if the expiry date is before today ie they have expired
227 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
228 || Date_to_Days($today_year, $today_month, $today_day )
229 > Date_to_Days($warning_year, $warning_month, $warning_day) )
231 #borrowercard expired, no issues
232 $template->param(
233 flagged => "1",
234 noissues => "1",
235 expired => "1",
236 renewaldate => format_date("$renew_year-$renew_month-$renew_day")
239 # check for NotifyBorrowerDeparture
240 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
241 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
242 Date_to_Days( $today_year, $today_month, $today_day ) )
244 # borrower card soon to expire warn librarian
245 $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
246 flagged => "1",);
247 if (C4::Context->preference('ReturnBeforeExpiry')){
248 $template->param("returnbeforeexpiry" => 1);
251 $template->param(
252 overduecount => $od,
253 issuecount => $issue,
254 finetotal => $fines
257 if ( IsDebarred($borrowernumber) ) {
258 $template->param(
259 'userdebarred' => $borrower->{debarred},
260 'debarredcomment' => $borrower->{debarredcomment},
263 if ( $borrower->{debarred} ne "9999-12-31" ) {
264 $template->param( 'userdebarreddate' =>
265 C4::Dates::format_date( $borrower->{debarred} ) );
272 # STEP 3 : ISSUING
275 if ($barcode) {
276 # always check for blockers on issuing
277 my ( $error, $question, $alerts ) =
278 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
279 my $blocker = $invalidduedate ? 1 : 0;
281 $template->param( alert => $alerts );
283 # Get the item title for more information
284 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
285 $template->param(
286 authvalcode_notforloan => C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'}),
288 # Fix for bug 7494: optional checkout-time fallback search for a book
290 if ( $error->{'UNKNOWN_BARCODE'}
291 && C4::Context->preference("itemBarcodeFallbackSearch") )
293 $template->param( FALLBACK => 1 );
295 my $query = "kw=" . $barcode;
296 my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
298 # if multiple hits, offer options to librarian
299 if ( $total_hits > 0 ) {
300 my @options = ();
301 foreach my $hit ( @{$results} ) {
302 my $chosen =
303 TransformMarcToKoha( C4::Context->dbh,
304 C4::Search::new_record_from_zebra('biblioserver',$hit) );
306 # offer all barcodes individually
307 if ( $chosen->{barcode} ) {
308 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
309 my %chosen_single = %{$chosen};
310 $chosen_single{barcode} = $barcode;
311 push( @options, \%chosen_single );
315 $template->param( options => \@options );
319 delete $question->{'DEBT'} if ($debt_confirmed);
320 foreach my $impossible ( keys %$error ) {
321 $template->param(
322 $impossible => $$error{$impossible},
323 IMPOSSIBLE => 1
325 $blocker = 1;
327 if( !$blocker ){
328 my $confirm_required = 0;
329 unless($issueconfirmed){
330 # Get the item title for more information
331 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
332 $template->{VARS}->{'additional_materials'} = $getmessageiteminfo->{'materials'};
333 $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
335 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
336 foreach my $needsconfirmation ( keys %$question ) {
337 $template->param(
338 $needsconfirmation => $$question{$needsconfirmation},
339 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
340 getBarcodeMessageIteminfo => $getmessageiteminfo->{'barcode'},
341 NEEDSCONFIRMATION => 1
343 $confirm_required = 1;
346 unless($confirm_required) {
347 AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
348 $inprocess = 1;
352 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
353 $template->param( issuecount => $issue );
356 # reload the borrower info for the sake of reseting the flags.....
357 if ($borrowernumber) {
358 $borrower = GetMemberDetails( $borrowernumber, 0 );
361 ##################################################################################
362 # BUILD HTML
363 # show all reserves of this borrower, and the position of the reservation ....
364 if ($borrowernumber) {
365 $template->param(
366 holds_count => Koha::Database->new()->schema()->resultset('Reserve')
367 ->count( { borrowernumber => $borrowernumber } ) );
369 $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
372 my @values;
373 my %labels;
374 my $selectborrower;
375 if ($borrowerslist) {
376 foreach (
377 sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
378 } @$borrowerslist
381 push @values, $_->{'borrowernumber'};
382 $labels{ $_->{'borrowernumber'} } =
383 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'} - $_->{'branchcode'}) ... $_->{'address'} ";
385 $selectborrower = {
386 values => \@values,
387 labels => \%labels,
391 #title
392 my $flags = $borrower->{'flags'};
393 foreach my $flag ( sort keys %$flags ) {
394 $template->param( flagged=> 1);
395 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
396 if ( $flags->{$flag}->{'noissues'} ) {
397 $template->param(
398 noissues => 'true',
400 if ( $flag eq 'GNA' ) {
401 $template->param( gna => 'true' );
403 elsif ( $flag eq 'LOST' ) {
404 $template->param( lost => 'true' );
406 elsif ( $flag eq 'DBARRED' ) {
407 $template->param( dbarred => 'true' );
409 elsif ( $flag eq 'CHARGES' ) {
410 $template->param(
411 charges => 'true',
412 chargesmsg => $flags->{'CHARGES'}->{'message'},
413 chargesamount => $flags->{'CHARGES'}->{'amount'},
414 charges_is_blocker => 1
417 elsif ( $flag eq 'CREDITS' ) {
418 $template->param(
419 credits => 'true',
420 creditsmsg => $flags->{'CREDITS'}->{'message'},
421 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
425 else {
426 if ( $flag eq 'CHARGES' ) {
427 $template->param(
428 charges => 'true',
429 chargesmsg => $flags->{'CHARGES'}->{'message'},
430 chargesamount => $flags->{'CHARGES'}->{'amount'},
433 elsif ( $flag eq 'CREDITS' ) {
434 $template->param(
435 credits => 'true',
436 creditsmsg => $flags->{'CREDITS'}->{'message'},
437 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
440 elsif ( $flag eq 'ODUES' ) {
441 $template->param(
442 odues => 'true',
443 oduesmsg => $flags->{'ODUES'}->{'message'}
446 my $items = $flags->{$flag}->{'itemlist'};
447 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
448 $template->param( nonreturns => 'true' );
451 elsif ( $flag eq 'NOTES' ) {
452 $template->param(
453 notes => 'true',
454 notesmsg => $flags->{'NOTES'}->{'message'}
460 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
461 $amountold =~ s/^.*\$//; # remove upto the $, if any
463 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
465 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
466 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
467 my $cnt = scalar(@$catcodes);
468 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
469 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
472 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
473 if($lib_messages_loop){ $template->param(flagged => 1 ); }
475 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
476 if($bor_messages_loop){ $template->param(flagged => 1 ); }
478 # Computes full borrower address
479 my @fulladdress;
480 push @fulladdress, $borrower->{'streetnumber'} if ( $borrower->{'streetnumber'} );
481 push @fulladdress, C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{'streettype'} ) if ( $borrower->{'streettype'} );
482 push @fulladdress, $borrower->{'address'} if ( $borrower->{'address'} );
484 my $fast_cataloging = 0;
485 if (defined getframeworkinfo('FA')) {
486 $fast_cataloging = 1
489 if (C4::Context->preference('ExtendedPatronAttributes')) {
490 my $attributes = GetBorrowerAttributes($borrowernumber);
491 $template->param(
492 ExtendedPatronAttributes => 1,
493 extendedattributes => $attributes
497 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
498 my $relatives_issues_count =
499 Koha::Database->new()->schema()->resultset('Issue')
500 ->count( { borrowernumber => \@relatives } );
502 $template->param(
503 lib_messages_loop => $lib_messages_loop,
504 bor_messages_loop => $bor_messages_loop,
505 all_messages_del => C4::Context->preference('AllowAllMessageDeletion'),
506 findborrower => $findborrower,
507 borrower => $borrower,
508 borrowernumber => $borrowernumber,
509 branch => $branch,
510 branchname => GetBranchName($borrower->{'branchcode'}),
511 printer => $printer,
512 printername => $printer,
513 firstname => $borrower->{'firstname'},
514 surname => $borrower->{'surname'},
515 showname => $borrower->{'showname'},
516 category_type => $borrower->{'category_type'},
517 was_renewed => $query->param('was_renewed') ? 1 : 0,
518 expiry => format_date($borrower->{'dateexpiry'}),
519 categorycode => $borrower->{'categorycode'},
520 categoryname => $borrower->{description},
521 address => join(' ', @fulladdress),
522 address2 => $borrower->{'address2'},
523 email => $borrower->{'email'},
524 emailpro => $borrower->{'emailpro'},
525 borrowernotes => $borrower->{'borrowernotes'},
526 city => $borrower->{'city'},
527 state => $borrower->{'state'},
528 zipcode => $borrower->{'zipcode'},
529 country => $borrower->{'country'},
530 phone => $borrower->{'phone'},
531 mobile => $borrower->{'mobile'},
532 phonepro => $borrower->{'phonepro'},
533 cardnumber => $borrower->{'cardnumber'},
534 othernames => $borrower->{'othernames'},
535 amountold => $amountold,
536 barcode => $barcode,
537 stickyduedate => $stickyduedate,
538 duedatespec => $duedatespec,
539 message => $message,
540 selectborrower => $selectborrower,
541 totaldue => sprintf('%.2f', $total),
542 inprocess => $inprocess,
543 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
544 circview => 1,
545 soundon => C4::Context->preference("SoundOn"),
546 fast_cataloging => $fast_cataloging,
547 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
548 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
549 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
550 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
551 RoutingSerials => C4::Context->preference('RoutingSerials'),
552 relatives_issues_count => $relatives_issues_count,
553 relatives_borrowernumbers => \@relatives,
556 # save stickyduedate to session
557 if ($stickyduedate) {
558 $session->param( 'stickyduedate', $duedatespec );
561 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
562 $template->param( picture => 1 ) if $picture;
564 # get authorised values with type of BOR_NOTES
566 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
568 $template->param(
569 debt_confirmed => $debt_confirmed,
570 SpecifyDueDate => $duedatespec_allow,
571 CircAutocompl => C4::Context->preference("CircAutocompl"),
572 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
573 export_remove_fields => C4::Context->preference("ExportRemoveFields"),
574 export_with_csv_profile => C4::Context->preference("ExportWithCsvProfile"),
575 canned_bor_notes_loop => $canned_notes,
576 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
579 output_html_with_http_headers $query, $cookie, $template->output;