Bug 14345: broken isbn logic prevents display of idreambooks image
[koha.git] / circ / circulation.pl
blob1071f4f330aedc84b3839da3d27a09e8e431e71c
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::Dates qw/format_date/;
34 use C4::Branch; # GetBranches
35 use C4::Koha; # GetPrinter
36 use C4::Circulation;
37 use C4::Utils::DataTables::Members;
38 use C4::Members;
39 use C4::Biblio;
40 use C4::Search;
41 use MARC::Record;
42 use C4::Reserves;
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/;
60 # PARAMETERS READING
62 my $query = new CGI;
64 my $sessionID = $query->cookie("CGISESSID") ;
65 my $session = get_session($sessionID);
67 # branch and printer are now defined by the userenv
68 # but first we have to check if someone has tried to change them
70 my $branch = $query->param('branch');
71 if ($branch){
72 # update our session so the userenv is updated
73 $session->param('branch', $branch);
74 $session->param('branchname', GetBranchName($branch));
77 my $printer = $query->param('printer');
78 if ($printer){
79 # update our session so the userenv is updated
80 $session->param('branchprinter', $printer);
83 if (!C4::Context->userenv && !$branch){
84 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
85 # no branch set we can't issue
86 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
87 exit;
91 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
93 template_name => 'circ/circulation.tt',
94 query => $query,
95 type => "intranet",
96 authnotrequired => 0,
97 flagsrequired => { circulate => 'circulate_remaining_permissions' },
101 my $branches = GetBranches();
103 my $force_allow_issue = $query->param('forceallow') || 0;
104 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
105 $force_allow_issue = 0;
108 my $onsite_checkout = $query->param('onsite_checkout');
110 my @failedrenews = $query->param('failedrenew'); # expected to be itemnumbers
111 our %renew_failed = ();
112 for (@failedrenews) { $renew_failed{$_} = 1; }
114 my @failedreturns = $query->param('failedreturn');
115 our %return_failed = ();
116 for (@failedreturns) { $return_failed{$_} = 1; }
118 my $findborrower = $query->param('findborrower') || q{};
119 $findborrower =~ s|,| |g;
120 my $borrowernumber = $query->param('borrowernumber');
122 $branch = C4::Context->userenv->{'branch'};
123 $printer = C4::Context->userenv->{'branchprinter'};
126 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
127 if (C4::Context->preference("AutoLocation") != 1) {
128 $template->param(ManualLocation => 1);
131 if (C4::Context->preference("DisplayClearScreenButton")) {
132 $template->param(DisplayClearScreenButton => 1);
135 my $barcode = $query->param('barcode') || q{};
136 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
138 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
139 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
140 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
141 my $issueconfirmed = $query->param('issueconfirmed');
142 my $cancelreserve = $query->param('cancelreserve');
143 my $print = $query->param('print') || q{};
144 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
145 my $charges = $query->param('charges') || q{};
147 # Check if stickyduedate is turned off
148 if ( $barcode ) {
149 # was stickyduedate loaded from session?
150 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
151 $session->clear( 'stickyduedate' );
152 $stickyduedate = $query->param('stickyduedate');
153 $duedatespec = $query->param('duedatespec');
155 $session->param('auto_renew', $query->param('auto_renew'));
157 else {
158 $session->clear('auto_renew');
161 my ($datedue,$invalidduedate);
163 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
164 if( $onsite_checkout && !$duedatespec_allow ) {
165 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
166 $datedue .= ' 23:59:00';
167 } elsif( $duedatespec_allow ) {
168 if ($duedatespec) {
169 if ($duedatespec =~ C4::Dates->regexp('syspref')) {
170 $datedue = dt_from_string($duedatespec);
171 } else {
172 $invalidduedate = 1;
173 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
178 our $todaysdate = C4::Dates->new->output('iso');
180 # check and see if we should print
181 if ( $barcode eq '' && $print eq 'maybe' ) {
182 $print = 'yes';
185 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
186 if ( $barcode eq '' && $charges eq 'yes' ) {
187 $template->param(
188 PAYCHARGES => 'yes',
189 borrowernumber => $borrowernumber
193 if ( $print eq 'yes' && $borrowernumber ne '' ) {
194 if ( C4::Context->boolean_preference('printcirculationslips') ) {
195 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
196 NetworkPrint($letter->{content});
198 $query->param( 'borrowernumber', '' );
199 $borrowernumber = '';
203 # STEP 2 : FIND BORROWER
204 # if there is a list of find borrowers....
206 my $message;
207 if ($findborrower) {
208 my $borrower = C4::Members::GetMember( cardnumber => $findborrower );
209 if ( $borrower ) {
210 $borrowernumber = $borrower->{borrowernumber};
211 } else {
212 my $dt_params = { iDisplayLength => -1 };
213 my $results = C4::Utils::DataTables::Members::search(
215 searchmember => $findborrower,
216 dt_params => $dt_params,
219 my $borrowers = $results->{patrons};
220 if ( scalar @$borrowers == 1 ) {
221 $borrowernumber = $borrowers->[0]->{borrowernumber};
222 $query->param( 'borrowernumber', $borrowernumber );
223 $query->param( 'barcode', '' );
224 } elsif ( @$borrowers ) {
225 $template->param( borrowers => $borrowers );
226 } else {
227 $query->param( 'findborrower', '' );
228 $message = "'$findborrower'";
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 my $issue = AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, { onsite_checkout => $onsite_checkout, auto_renew => $session->param('auto_renew') } );
376 $template->param( issue => $issue );
377 $session->clear('auto_renew');
378 $inprocess = 1;
382 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
383 $template->param( issuecount => $issue );
385 if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
386 $template->param(
387 reserveborrowernumber => $question->{'resborrowernumber'},
388 itembiblionumber => $getmessageiteminfo->{'biblionumber'}
393 # reload the borrower info for the sake of reseting the flags.....
394 if ($borrowernumber) {
395 $borrower = GetMemberDetails( $borrowernumber, 0 );
398 ##################################################################################
399 # BUILD HTML
400 # show all reserves of this borrower, and the position of the reservation ....
401 if ($borrowernumber) {
402 $template->param(
403 holds_count => Koha::Database->new()->schema()->resultset('Reserve')
404 ->count( { borrowernumber => $borrowernumber } ) );
405 my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber);
407 my @WaitingReserveLoop;
408 foreach my $num_res (@borrowerreserv) {
409 if ( $num_res->{'found'} && $num_res->{'found'} eq 'W' ) {
410 my $getiteminfo = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
411 my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
412 my %getWaitingReserveInfo;
413 $getWaitingReserveInfo{title} = $getiteminfo->{'title'};
414 $getWaitingReserveInfo{biblionumber} =
415 $getiteminfo->{'biblionumber'};
416 $getWaitingReserveInfo{itemtype} = $itemtypeinfo->{'description'};
417 $getWaitingReserveInfo{author} = $getiteminfo->{'author'};
418 $getWaitingReserveInfo{itemcallnumber} =
419 $getiteminfo->{'itemcallnumber'};
420 $getWaitingReserveInfo{reservedate} =
421 format_date( $num_res->{'reservedate'} );
422 $getWaitingReserveInfo{waitingat} =
423 GetBranchName( $num_res->{'branchcode'} );
424 $getWaitingReserveInfo{waitinghere} = 1
425 if $num_res->{'branchcode'} eq $branch;
426 push( @WaitingReserveLoop, \%getWaitingReserveInfo );
429 $template->param( WaitingReserveLoop => \@WaitingReserveLoop );
431 $template->param( adultborrower => 1 ) if ( $borrower->{category_type} eq 'A' || $borrower->{category_type} eq 'I' );
434 #title
435 my $flags = $borrower->{'flags'};
436 foreach my $flag ( sort keys %$flags ) {
437 $template->param( flagged=> 1);
438 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
439 if ( $flags->{$flag}->{'noissues'} ) {
440 $template->param(
441 noissues => ($force_allow_issue) ? 0 : 'true',
442 forceallow => $force_allow_issue,
444 if ( $flag eq 'GNA' ) {
445 $template->param( gna => 'true' );
447 elsif ( $flag eq 'LOST' ) {
448 $template->param( lost => 'true' );
450 elsif ( $flag eq 'DBARRED' ) {
451 $template->param( dbarred => 'true' );
453 elsif ( $flag eq 'CHARGES' ) {
454 $template->param(
455 charges => 'true',
456 chargesmsg => $flags->{'CHARGES'}->{'message'},
457 chargesamount => $flags->{'CHARGES'}->{'amount'},
458 charges_is_blocker => 1
461 elsif ( $flag eq 'CREDITS' ) {
462 $template->param(
463 credits => 'true',
464 creditsmsg => $flags->{'CREDITS'}->{'message'},
465 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
469 else {
470 if ( $flag eq 'CHARGES' ) {
471 $template->param(
472 charges => 'true',
473 chargesmsg => $flags->{'CHARGES'}->{'message'},
474 chargesamount => $flags->{'CHARGES'}->{'amount'},
477 elsif ( $flag eq 'CREDITS' ) {
478 $template->param(
479 credits => 'true',
480 creditsmsg => $flags->{'CREDITS'}->{'message'},
481 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
484 elsif ( $flag eq 'ODUES' ) {
485 $template->param(
486 odues => 'true',
487 oduesmsg => $flags->{'ODUES'}->{'message'}
490 my $items = $flags->{$flag}->{'itemlist'};
491 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
492 $template->param( nonreturns => 'true' );
495 elsif ( $flag eq 'NOTES' ) {
496 $template->param(
497 notes => 'true',
498 notesmsg => $flags->{'NOTES'}->{'message'}
504 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
505 $amountold =~ s/^.*\$//; # remove upto the $, if any
507 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
509 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
510 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
511 my $cnt = scalar(@$catcodes);
512 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
513 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
516 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
517 if($lib_messages_loop){ $template->param(flagged => 1 ); }
519 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
520 if($bor_messages_loop){ $template->param(flagged => 1 ); }
522 my $fast_cataloging = 0;
523 if (defined getframeworkinfo('FA')) {
524 $fast_cataloging = 1
527 if (C4::Context->preference('ExtendedPatronAttributes')) {
528 my $attributes = GetBorrowerAttributes($borrowernumber);
529 $template->param(
530 ExtendedPatronAttributes => 1,
531 extendedattributes => $attributes
535 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
536 my $relatives_issues_count =
537 Koha::Database->new()->schema()->resultset('Issue')
538 ->count( { borrowernumber => \@relatives } );
540 my $roadtype = C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{streettype} );
542 $template->param(%$borrower);
544 $template->param(
545 lib_messages_loop => $lib_messages_loop,
546 bor_messages_loop => $bor_messages_loop,
547 all_messages_del => C4::Context->preference('AllowAllMessageDeletion'),
548 findborrower => $findborrower,
549 borrower => $borrower,
550 borrowernumber => $borrowernumber,
551 branch => $branch,
552 branchname => GetBranchName($borrower->{'branchcode'}),
553 printer => $printer,
554 printername => $printer,
555 was_renewed => $query->param('was_renewed') ? 1 : 0,
556 expiry => format_date($borrower->{'dateexpiry'}),
557 roadtype => $roadtype,
558 amountold => $amountold,
559 barcode => $barcode,
560 stickyduedate => $stickyduedate,
561 duedatespec => $duedatespec,
562 message => $message,
563 totaldue => sprintf('%.2f', $total),
564 inprocess => $inprocess,
565 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
566 circview => 1,
567 soundon => C4::Context->preference("SoundOn"),
568 fast_cataloging => $fast_cataloging,
569 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
570 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
571 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
572 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
573 RoutingSerials => C4::Context->preference('RoutingSerials'),
574 relatives_issues_count => $relatives_issues_count,
575 relatives_borrowernumbers => \@relatives,
578 # save stickyduedate to session
579 if ($stickyduedate) {
580 $session->param( 'stickyduedate', $duedatespec );
583 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
584 $template->param( picture => 1 ) if $picture;
586 # get authorised values with type of BOR_NOTES
588 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
590 $template->param(
591 debt_confirmed => $debt_confirmed,
592 SpecifyDueDate => $duedatespec_allow,
593 CircAutocompl => C4::Context->preference("CircAutocompl"),
594 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
595 canned_bor_notes_loop => $canned_notes,
596 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
597 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
600 output_html_with_http_headers $query, $cookie, $template->output;