Bug 19726: Move admin templates JavaScript to the footer: Preferences
[koha.git] / circ / circulation.pl
blobe46ced16380dbc03c7d0fafd5e402ae54cda851c
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 # FIXME There are too many calls to Koha::Patrons->find in this script
27 use strict;
28 use warnings;
29 use CGI qw ( -utf8 );
30 use DateTime;
31 use DateTime::Duration;
32 use C4::Output;
33 use C4::Print;
34 use C4::Auth qw/:DEFAULT get_session haspermission/;
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 Koha::Holds;
44 use C4::Context;
45 use CGI::Session;
46 use C4::Members::Attributes qw(GetBorrowerAttributes);
47 use Koha::AuthorisedValues;
48 use Koha::CsvProfiles;
49 use Koha::Patrons;
50 use Koha::Patron::Debarments qw(GetDebarments);
51 use Koha::DateUtils;
52 use Koha::Database;
53 use Koha::BiblioFrameworks;
54 use Koha::Items;
55 use Koha::Patron::Messages;
56 use Koha::SearchEngine;
57 use Koha::SearchEngine::Search;
58 use Koha::Patron::Modifications;
60 use Date::Calc qw(
61 Today
62 Add_Delta_Days
63 Date_to_Days
65 use List::MoreUtils qw/uniq/;
68 # PARAMETERS READING
70 my $query = new CGI;
72 my $override_high_holds = $query->param('override_high_holds');
73 my $override_high_holds_tmp = $query->param('override_high_holds_tmp');
75 my $sessionID = $query->cookie("CGISESSID") ;
76 my $session = get_session($sessionID);
77 if (!C4::Context->userenv){
78 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
79 # no branch set we can't issue
80 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
81 exit;
85 my $barcodes = [];
86 my $barcode = $query->param('barcode');
87 # Barcode given by user could be '0'
88 if ( $barcode || ( defined($barcode) && $barcode eq '0' ) ) {
89 $barcodes = [ $barcode ];
90 } else {
91 my $filefh = $query->upload('uploadfile');
92 if ( $filefh ) {
93 while ( my $content = <$filefh> ) {
94 $content =~ s/[\r\n]*$//g;
95 push @$barcodes, $content if $content;
97 } elsif ( my $list = $query->param('barcodelist') ) {
98 push @$barcodes, split( /\s\n/, $list );
99 $barcodes = [ map { $_ =~ /^\s*$/ ? () : $_ } @$barcodes ];
100 } else {
101 @$barcodes = $query->multi_param('barcodes');
105 $barcodes = [ uniq @$barcodes ];
107 my $template_name = q|circ/circulation.tt|;
108 my $borrowernumber = $query->param('borrowernumber');
109 my $patron = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : undef;
110 my $batch = $query->param('batch');
111 my $batch_allowed = 0;
112 if ( $batch && C4::Context->preference('BatchCheckouts') ) {
113 $template_name = q|circ/circulation_batch_checkouts.tt|;
114 my @batch_category_codes = split '\|', C4::Context->preference('BatchCheckoutsValidCategories');
115 my $categorycode = $patron->categorycode;
116 if ( $categorycode && grep {/^$categorycode$/} @batch_category_codes ) {
117 $batch_allowed = 1;
118 } else {
119 $barcodes = [];
123 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
125 template_name => $template_name,
126 query => $query,
127 type => "intranet",
128 authnotrequired => 0,
129 flagsrequired => { circulate => 'circulate_remaining_permissions' },
133 my $force_allow_issue = $query->param('forceallow') || 0;
134 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
135 $force_allow_issue = 0;
138 my $onsite_checkout = $query->param('onsite_checkout');
140 my @failedrenews = $query->multi_param('failedrenew'); # expected to be itemnumbers
141 our %renew_failed = ();
142 for (@failedrenews) { $renew_failed{$_} = 1; }
144 my @failedreturns = $query->multi_param('failedreturn');
145 our %return_failed = ();
146 for (@failedreturns) { $return_failed{$_} = 1; }
148 my $searchtype = $query->param('searchtype') || q{contain};
150 my $findborrower = $query->param('findborrower') || q{};
151 $findborrower =~ s|,| |g;
153 my $branch = C4::Context->userenv->{'branch'};
155 if (C4::Context->preference("DisplayClearScreenButton")) {
156 $template->param(DisplayClearScreenButton => 1);
159 for my $barcode ( @$barcodes ) {
160 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
161 $barcode = barcodedecode($barcode)
162 if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
165 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
166 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
167 $duedatespec = eval { output_pref( { dt => dt_from_string( $duedatespec ), dateformat => 'iso', timeformat => '24hr' }); }
168 if ( $duedatespec );
169 my $restoreduedatespec = $query->param('restoreduedatespec') || $duedatespec || $session->param('stickyduedate');
170 if ( $restoreduedatespec && $restoreduedatespec eq "highholds_empty" ) {
171 undef $restoreduedatespec;
173 my $issueconfirmed = $query->param('issueconfirmed');
174 my $cancelreserve = $query->param('cancelreserve');
175 my $print = $query->param('print') || q{};
176 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
177 my $charges = $query->param('charges') || q{};
179 # Check if stickyduedate is turned off
180 if ( @$barcodes ) {
181 # was stickyduedate loaded from session?
182 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
183 $session->clear( 'stickyduedate' );
184 $stickyduedate = $query->param('stickyduedate');
185 $duedatespec = $query->param('duedatespec');
187 $session->param('auto_renew', scalar $query->param('auto_renew'));
189 else {
190 $session->clear('auto_renew');
193 my ($datedue,$invalidduedate);
195 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
196 if( $onsite_checkout && !$duedatespec_allow ) {
197 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
198 $datedue .= ' 23:59:00';
199 } elsif( $duedatespec_allow ) {
200 if ( $duedatespec ) {
201 $datedue = eval { dt_from_string( $duedatespec ) };
202 if (! $datedue ) {
203 $invalidduedate = 1;
204 $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec );
209 # check and see if we should print
210 if ( @$barcodes == 0 && $print eq 'maybe' ) {
211 $print = 'yes';
214 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
215 if ( @$barcodes == 0 && $charges eq 'yes' ) {
216 $template->param(
217 PAYCHARGES => 'yes',
218 borrowernumber => $borrowernumber
222 if ( $print eq 'yes' && $borrowernumber ne '' ) {
223 if ( C4::Context->boolean_preference('printcirculationslips') ) {
224 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
225 NetworkPrint($letter->{content});
227 $query->param( 'borrowernumber', '' );
228 $borrowernumber = '';
232 # STEP 2 : FIND BORROWER
233 # if there is a list of find borrowers....
235 my $message;
236 if ($findborrower) {
237 my $patron = Koha::Patrons->find( { cardnumber => $findborrower } );
238 if ( $patron ) {
239 $borrowernumber = $patron->borrowernumber;
240 } else {
241 my $dt_params = { iDisplayLength => -1 };
242 my $results = C4::Utils::DataTables::Members::search(
244 searchmember => $findborrower,
245 searchtype => $searchtype,
246 dt_params => $dt_params,
249 my $borrowers = $results->{patrons};
250 if ( scalar @$borrowers == 1 ) {
251 $borrowernumber = $borrowers->[0]->{borrowernumber};
252 $query->param( 'borrowernumber', $borrowernumber );
253 $query->param( 'barcode', '' );
254 } elsif ( @$borrowers ) {
255 $template->param( borrowers => $borrowers );
256 } else {
257 $query->param( 'findborrower', '' );
258 $message = "'$findborrower'";
263 # get the borrower information.....
264 $patron ||= Koha::Patrons->find( $borrowernumber ) if $borrowernumber;
265 if ($patron) {
266 my $overdues = $patron->get_overdues;
267 my $issues = $patron->checkouts;
268 my $balance = $patron->account->balance;
271 # if the expiry date is before today ie they have expired
272 if ( $patron->is_expired ) {
273 #borrowercard expired, no issues
274 $template->param(
275 noissues => ($force_allow_issue) ? 0 : "1",
276 forceallow => $force_allow_issue,
277 expired => "1",
280 # check for NotifyBorrowerDeparture
281 elsif ( $patron->is_going_to_expire ) {
282 # borrower card soon to expire warn librarian
283 $template->param( "warndeparture" => $patron->dateexpiry ,
285 if (C4::Context->preference('ReturnBeforeExpiry')){
286 $template->param("returnbeforeexpiry" => 1);
289 $template->param(
290 overduecount => $overdues->count,
291 issuecount => $issues->count,
292 finetotal => $balance,
295 if ( $patron and $patron->is_debarred ) {
296 $template->param(
297 'userdebarred' => $patron->debarred,
298 'debarredcomment' => $patron->debarredcomment,
301 if ( $patron->debarred ne "9999-12-31" ) {
302 $template->param( 'userdebarreddate' => $patron->debarred );
309 # STEP 3 : ISSUING
312 if (@$barcodes) {
313 my $checkout_infos;
314 for my $barcode ( @$barcodes ) {
315 my $template_params = { barcode => $barcode };
316 # always check for blockers on issuing
317 my ( $error, $question, $alerts, $messages ) = CanBookBeIssued(
318 $patron->unblessed,
319 $barcode, $datedue,
320 $inprocess,
321 undef,
323 onsite_checkout => $onsite_checkout,
324 override_high_holds => $override_high_holds || $override_high_holds_tmp || 0,
328 my $blocker = $invalidduedate ? 1 : 0;
330 $template_params->{alert} = $alerts;
331 $template_params->{messages} = $messages;
333 my $item = Koha::Items->find({ barcode => $barcode });
334 my ( $biblio, $mss );
336 if ( $item ) {
337 $biblio = $item->biblio;
338 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $biblio->frameworkcode, kohafield => 'items.notforloan', authorised_value => { not => undef } });
339 $template_params->{authvalcode_notforloan} = $mss->count ? $mss->next->authorised_value : undef;
342 # Fix for bug 7494: optional checkout-time fallback search for a book
344 if ( $error->{'UNKNOWN_BARCODE'}
345 && C4::Context->preference("itemBarcodeFallbackSearch")
346 && not $batch
349 $template_params->{FALLBACK} = 1;
351 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
352 my $query = "kw=" . $barcode;
353 my ( $searcherror, $results, $total_hits ) = $searcher->simple_search_compat($query, 0, 10);
355 # if multiple hits, offer options to librarian
356 if ( $total_hits > 0 ) {
357 my @options = ();
358 foreach my $hit ( @{$results} ) {
359 my $chosen =
360 TransformMarcToKoha( C4::Search::new_record_from_zebra('biblioserver',$hit) );
362 # offer all barcodes individually
363 if ( $chosen->{barcode} ) {
364 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
365 my %chosen_single = %{$chosen};
366 $chosen_single{barcode} = $barcode;
367 push( @options, \%chosen_single );
371 $template_params->{options} = \@options;
375 if ( $error->{UNKNOWN_BARCODE} or not $onsite_checkout or not C4::Context->preference("OnSiteCheckoutsForce") ) {
376 delete $question->{'DEBT'} if ($debt_confirmed);
377 foreach my $impossible ( keys %$error ) {
378 $template_params->{$impossible} = $$error{$impossible};
379 $template_params->{IMPOSSIBLE} = 1;
380 $blocker = 1;
384 if( $item and ( !$blocker or $force_allow_issue ) ){
385 my $confirm_required = 0;
386 unless($issueconfirmed){
387 # Get the item title for more information
388 my $materials = $item->materials;
389 my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({ frameworkcode => $biblio->frameworkcode, kohafield => 'items.materials', authorised_value => $materials });
390 $materials = $descriptions->{lib} // $materials;
391 $template_params->{additional_materials} = $materials;
392 $template_params->{itemhomebranch} = $item->homebranch;
394 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
395 foreach my $needsconfirmation ( keys %$question ) {
396 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
397 $template_params->{getTitleMessageIteminfo} = $biblio->title;
398 $template_params->{getBarcodeMessageIteminfo} = $item->barcode;
399 $template_params->{NEEDSCONFIRMATION} = 1;
400 $template_params->{onsite_checkout} = $onsite_checkout;
401 $template_params->{auto_renew} = $session->param('auto_renew');
402 $confirm_required = 1;
405 unless($confirm_required) {
406 my $switch_onsite_checkout = exists $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED};
407 my $issue = AddIssue( $patron->unblessed, $barcode, $datedue, $cancelreserve, undef, undef, { onsite_checkout => $onsite_checkout, auto_renew => $session->param('auto_renew'), switch_onsite_checkout => $switch_onsite_checkout, } );
408 $template_params->{issue} = $issue;
409 $session->clear('auto_renew');
410 $inprocess = 1;
414 if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
415 $template->param(
416 reserveborrowernumber => $question->{'resborrowernumber'}
421 # FIXME If the issue is confirmed, we launch another time checkouts->count, now display the issue count after issue
422 $patron = Koha::Patrons->find( $borrowernumber );
423 $template_params->{issuecount} = $patron->checkouts->count;
425 if ( $item ) {
426 $template_params->{item} = $item;
427 $template_params->{biblio} = $biblio;
428 $template_params->{itembiblionumber} = $biblio->biblionumber;
430 push @$checkout_infos, $template_params;
432 unless ( $batch ) {
433 $template->param( %{$checkout_infos->[0]} );
434 $template->param( barcode => $barcodes->[0] );
435 } else {
436 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
437 $template->param(
438 checkout_infos => $checkout_infos,
439 confirmation_needed => $confirmation_needed,
444 ##################################################################################
445 # BUILD HTML
446 # show all reserves of this borrower, and the position of the reservation ....
447 if ($patron) {
448 my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } ); # FIXME must be Koha::Patron->holds
449 my $waiting_holds = $holds->waiting;
450 $template->param(
451 holds_count => $holds->count(),
452 WaitingHolds => $waiting_holds,
455 my $category_type = $patron->category->category_type;
456 $template->param( adultborrower => 1 ) if ( $category_type eq 'A' || $category_type eq 'I' );
459 #title
460 my $flags = $patron ? C4::Members::patronflags( $patron->unblessed ) : {};
461 foreach my $flag ( sort keys %$flags ) {
462 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
463 if ( $flags->{$flag}->{'noissues'} ) {
464 $template->param(
465 noissues => ($force_allow_issue) ? 0 : 'true',
466 forceallow => $force_allow_issue,
468 if ( $flag eq 'GNA' ) {
469 $template->param( gna => 'true' );
471 elsif ( $flag eq 'LOST' ) {
472 $template->param( lost => 'true' );
474 elsif ( $flag eq 'DBARRED' ) {
475 $template->param( dbarred => 'true' );
477 elsif ( $flag eq 'CHARGES' ) {
478 $template->param(
479 charges => 'true',
480 chargesmsg => $flags->{'CHARGES'}->{'message'},
481 chargesamount => $flags->{'CHARGES'}->{'amount'},
482 charges_is_blocker => 1
485 elsif ( $flag eq 'CHARGES_GUARANTEES' ) {
486 $template->param(
487 charges_guarantees => 'true',
488 chargesmsg_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'message'},
489 chargesamount_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'amount'},
490 charges_guarantees_is_blocker => 1
493 elsif ( $flag eq 'CREDITS' ) {
494 $template->param(
495 credits => 'true',
496 creditsmsg => $flags->{'CREDITS'}->{'message'},
497 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
501 else {
502 if ( $flag eq 'CHARGES' ) {
503 $template->param(
504 charges => 'true',
505 chargesmsg => $flags->{'CHARGES'}->{'message'},
506 chargesamount => $flags->{'CHARGES'}->{'amount'},
509 elsif ( $flag eq 'CHARGES_GUARANTEES' ) {
510 $template->param(
511 charges_guarantees => 'true',
512 chargesmsg_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'message'},
513 chargesamount_guarantees => $flags->{'CHARGES_GUARANTEES'}->{'amount'},
516 elsif ( $flag eq 'CREDITS' ) {
517 $template->param(
518 credits => 'true',
519 creditsmsg => $flags->{'CREDITS'}->{'message'},
520 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
523 elsif ( $flag eq 'ODUES' ) {
524 $template->param(
525 odues => 'true',
526 oduesmsg => $flags->{'ODUES'}->{'message'}
529 my $items = $flags->{$flag}->{'itemlist'};
530 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
531 $template->param( nonreturns => 'true' );
534 elsif ( $flag eq 'NOTES' ) {
535 $template->param(
536 notes => 'true',
537 notesmsg => $flags->{'NOTES'}->{'message'}
543 my $amountold = $flags ? $flags->{'CHARGES'}->{'message'} || 0 : 0;
544 $amountold =~ s/^.*\$//; # remove upto the $, if any
546 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
548 if ( $patron && $patron->category->category_type eq 'C') {
549 my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => 'A' }, {order_by => ['categorycode']});
550 $template->param( 'CATCODE_MULTI' => 1) if $patron_categories->count > 1;
551 $template->param( 'catcode' => $patron_categories->next ) if $patron_categories->count == 1;
554 my $messages = Koha::Patron::Messages->search(
556 'me.borrowernumber' => $borrowernumber,
559 join => 'manager',
560 '+select' => ['manager.surname', 'manager.firstname' ],
561 '+as' => ['manager_surname', 'manager_firstname'],
565 my $fast_cataloging = 0;
566 if ( Koha::BiblioFrameworks->find('FA') ) {
567 $fast_cataloging = 1
570 if (C4::Context->preference('ExtendedPatronAttributes')) {
571 my $attributes = GetBorrowerAttributes($borrowernumber);
572 $template->param(
573 ExtendedPatronAttributes => 1,
574 extendedattributes => $attributes
577 my $view = $batch
578 ?'batch_checkout_view'
579 : 'circview';
581 my @relatives;
582 if ( $borrowernumber ) {
583 if ( $patron ) {
584 if ( my $guarantor = $patron->guarantor ) {
585 push @relatives, $guarantor->borrowernumber;
586 push @relatives, $_->borrowernumber for $patron->siblings;
587 } else {
588 push @relatives, $_->borrowernumber for $patron->guarantees;
592 my $relatives_issues_count =
593 Koha::Database->new()->schema()->resultset('Issue')
594 ->count( { borrowernumber => \@relatives } );
596 if ( $patron ) {
597 my $av = Koha::AuthorisedValues->search({ category => 'ROADTYPE', authorised_value => $patron->streettype });
598 my $roadtype = $av->count ? $av->next->lib : '';
599 $template->param(
600 %{ $patron->unblessed },
601 borrower => $patron->unblessed,
602 roadtype => $roadtype,
603 patron => $patron,
604 categoryname => $patron->category->description,
605 expiry => $patron->dateexpiry,
606 is_child => ( $patron->category->category_type eq 'C' ),
607 picture => ( $patron->image ? 1 : 0 ),
611 # Restore date if changed by holds and/or save stickyduedate to session
612 if ($restoreduedatespec || $stickyduedate) {
613 $duedatespec = $restoreduedatespec || $duedatespec;
615 if ($stickyduedate) {
616 $session->param( 'stickyduedate', $duedatespec );
618 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
619 undef $duedatespec;
622 $template->param(
623 messages => $messages,
624 borrowernumber => $borrowernumber,
625 branch => $branch,
626 was_renewed => scalar $query->param('was_renewed') ? 1 : 0,
627 amountold => $amountold,
628 barcodes => $barcodes,
629 stickyduedate => $stickyduedate,
630 duedatespec => $duedatespec,
631 restoreduedatespec => $restoreduedatespec,
632 message => $message,
633 totaldue => sprintf('%.2f', $total),
634 inprocess => $inprocess,
635 $view => 1,
636 batch_allowed => $batch_allowed,
637 batch => $batch,
638 AudioAlerts => C4::Context->preference("AudioAlerts"),
639 fast_cataloging => $fast_cataloging,
640 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
641 RoutingSerials => C4::Context->preference('RoutingSerials'),
642 relatives_issues_count => $relatives_issues_count,
643 relatives_borrowernumbers => \@relatives,
647 if ( C4::Context->preference("ExportCircHistory") ) {
648 $template->param(csv_profiles => [ Koha::CsvProfiles->search({ type => 'marc' }) ]);
651 my $has_modifications = Koha::Patron::Modifications->search( { borrowernumber => $borrowernumber } )->count;
652 $template->param(
653 debt_confirmed => $debt_confirmed,
654 SpecifyDueDate => $duedatespec_allow,
655 CircAutocompl => C4::Context->preference("CircAutocompl"),
656 debarments => scalar GetDebarments({ borrowernumber => $borrowernumber }),
657 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
658 has_modifications => $has_modifications,
659 override_high_holds => $override_high_holds,
660 nopermission => scalar $query->param('nopermission'),
663 output_html_with_http_headers $query, $cookie, $template->output;