Bug 26782: Compiled CSS
[koha.git] / circ / circulation.pl
blobee3878ca1349a97259615fcd38219c23efc5e882
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 Modern::Perl;
28 use CGI qw ( -utf8 );
29 use DateTime;
30 use DateTime::Duration;
31 use Scalar::Util qw( looks_like_number );
32 use C4::Output;
33 use C4::Auth qw/:DEFAULT get_session haspermission/;
34 use C4::Koha;
35 use C4::Circulation;
36 use C4::Utils::DataTables::Members;
37 use C4::Members;
38 use C4::Biblio;
39 use C4::Search;
40 use MARC::Record;
41 use C4::Reserves;
42 use Koha::Holds;
43 use C4::Context;
44 use CGI::Session;
45 use Koha::AuthorisedValues;
46 use Koha::CsvProfiles;
47 use Koha::Patrons;
48 use Koha::Patron::Debarments qw(GetDebarments);
49 use Koha::DateUtils;
50 use Koha::Database;
51 use Koha::BiblioFrameworks;
52 use Koha::Items;
53 use Koha::Patron::Messages;
54 use Koha::SearchEngine;
55 use Koha::SearchEngine::Search;
56 use Koha::Patron::Modifications;
58 use Date::Calc qw(
59 Today
60 Add_Delta_Days
61 Date_to_Days
63 use List::MoreUtils qw/uniq/;
66 # PARAMETERS READING
68 my $query = CGI->new;
70 my $override_high_holds = $query->param('override_high_holds');
71 my $override_high_holds_tmp = $query->param('override_high_holds_tmp');
73 my $sessionID = $query->cookie("CGISESSID") ;
74 my $session = get_session($sessionID);
76 my $barcodes = [];
77 my $barcode = $query->param('barcode');
78 my $findborrower;
79 my $autoswitched;
80 my $borrowernumber = $query->param('borrowernumber');
82 if (C4::Context->preference("AutoSwitchPatron") && $barcode) {
83 if (Koha::Patrons->search( { cardnumber => $barcode} )->count() > 0) {
84 $findborrower = $barcode;
85 undef $barcode;
86 undef $borrowernumber;
87 $autoswitched = 1;
90 $findborrower ||= $query->param('findborrower') || q{};
91 $findborrower =~ s|,| |g;
93 # Barcode given by user could be '0'
94 if ( $barcode || ( defined($barcode) && $barcode eq '0' ) ) {
95 $barcodes = [ $barcode ];
96 } else {
97 my $filefh = $query->upload('uploadfile');
98 if ( $filefh ) {
99 while ( my $content = <$filefh> ) {
100 $content =~ s/[\r\n]*$//g;
101 push @$barcodes, $content if $content;
103 } elsif ( my $list = $query->param('barcodelist') ) {
104 push @$barcodes, split( /\s\n/, $list );
105 $barcodes = [ map { $_ =~ /^\s*$/ ? () : $_ } @$barcodes ];
106 } else {
107 @$barcodes = $query->multi_param('barcodes');
111 $barcodes = [ uniq @$barcodes ];
113 my $template_name = q|circ/circulation.tt|;
114 my $patron = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : undef;
115 my $batch = $query->param('batch');
116 my $batch_allowed = 0;
117 if ( $batch && C4::Context->preference('BatchCheckouts') ) {
118 $template_name = q|circ/circulation_batch_checkouts.tt|;
119 my @batch_category_codes = split '\|', C4::Context->preference('BatchCheckoutsValidCategories');
120 my $categorycode = $patron->categorycode;
121 if ( $categorycode && grep { $_ eq $categorycode } @batch_category_codes ) {
122 $batch_allowed = 1;
123 } else {
124 $barcodes = [];
128 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
130 template_name => $template_name,
131 query => $query,
132 type => "intranet",
133 flagsrequired => { circulate => 'circulate_remaining_permissions' },
136 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
138 my $force_allow_issue = $query->param('forceallow') || 0;
139 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
140 $force_allow_issue = 0;
142 my $onsite_checkout = $query->param('onsite_checkout');
144 if (C4::Context->preference("OnSiteCheckoutAutoCheck") && $onsite_checkout eq "on") {
145 $template->param(onsite_checkout => $onsite_checkout);
148 my @failedrenews = $query->multi_param('failedrenew'); # expected to be itemnumbers
149 our %renew_failed = ();
150 for (@failedrenews) { $renew_failed{$_} = 1; }
152 my @failedreturns = $query->multi_param('failedreturn');
153 our %return_failed = ();
154 for (@failedreturns) { $return_failed{$_} = 1; }
156 my $searchtype = $query->param('searchtype') || q{contain};
158 my $branch = C4::Context->userenv->{'branch'};
160 if (C4::Context->preference("DisplayClearScreenButton")) {
161 $template->param(DisplayClearScreenButton => 1);
164 for my $barcode ( @$barcodes ) {
165 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
166 $barcode = barcodedecode($barcode)
167 if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
170 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
171 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
172 $duedatespec = eval { output_pref( { dt => dt_from_string( $duedatespec ), dateformat => 'iso' }); }
173 if ( $duedatespec );
174 my $restoreduedatespec = $query->param('restoreduedatespec') || $duedatespec || $session->param('stickyduedate');
175 if ( $restoreduedatespec && $restoreduedatespec eq "highholds_empty" ) {
176 undef $restoreduedatespec;
178 my $issueconfirmed = $query->param('issueconfirmed');
179 my $cancelreserve = $query->param('cancelreserve');
180 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
181 my $charges = $query->param('charges') || q{};
183 # Check if stickyduedate is turned off
184 if ( @$barcodes ) {
185 # was stickyduedate loaded from session?
186 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
187 $session->clear( 'stickyduedate' );
188 $stickyduedate = $query->param('stickyduedate');
189 $duedatespec = $query->param('duedatespec');
191 $session->param('auto_renew', scalar $query->param('auto_renew'));
193 else {
194 $session->clear('auto_renew');
197 $template->param( auto_renew => $session->param('auto_renew') );
199 my ($datedue,$invalidduedate);
201 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
202 if( $onsite_checkout && !$duedatespec_allow ) {
203 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
204 $datedue .= ' 23:59:00';
205 } elsif( $duedatespec_allow ) {
206 if ( $duedatespec ) {
207 $datedue = eval { dt_from_string( $duedatespec ) };
208 if (! $datedue ) {
209 $invalidduedate = 1;
210 $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec );
215 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
216 if ( @$barcodes == 0 && $charges eq 'yes' ) {
217 $template->param(
218 PAYCHARGES => 'yes',
219 borrowernumber => $borrowernumber
224 # STEP 2 : FIND BORROWER
225 # if there is a list of find borrowers....
227 my $message;
228 if ($findborrower) {
229 my $patron = Koha::Patrons->find( { cardnumber => $findborrower } );
230 if ( $patron ) {
231 $borrowernumber = $patron->borrowernumber;
232 } else {
233 my $dt_params = { iDisplayLength => -1 };
234 my $results = C4::Utils::DataTables::Members::search(
236 searchmember => $findborrower,
237 searchtype => $searchtype,
238 dt_params => $dt_params,
241 my $borrowers = $results->{patrons};
242 if ( scalar @$borrowers == 1 ) {
243 $borrowernumber = $borrowers->[0]->{borrowernumber};
244 $query->param( 'borrowernumber', $borrowernumber );
245 $query->param( 'barcode', '' );
246 } elsif ( @$borrowers ) {
247 $template->param( borrowers => $borrowers );
248 } else {
249 $query->param( 'findborrower', '' );
250 $message = "'$findborrower'";
255 # get the borrower information.....
256 my $balance = 0;
257 $patron ||= Koha::Patrons->find( $borrowernumber ) if $borrowernumber;
258 if ($patron) {
260 $template->param( borrowernumber => $patron->borrowernumber );
261 output_and_exit_if_error( $query, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
263 my $overdues = $patron->get_overdues;
264 my $issues = $patron->checkouts;
265 $balance = $patron->account->balance;
268 # if the expiry date is before today ie they have expired
269 if ( $patron->is_expired ) {
270 #borrowercard expired, no issues
271 $template->param(
272 noissues => ($force_allow_issue) ? 0 : "1",
273 forceallow => $force_allow_issue,
274 expired => "1",
277 # check for NotifyBorrowerDeparture
278 elsif ( $patron->is_going_to_expire ) {
279 # borrower card soon to expire warn librarian
280 $template->param( "warndeparture" => $patron->dateexpiry ,
282 if (C4::Context->preference('ReturnBeforeExpiry')){
283 $template->param("returnbeforeexpiry" => 1);
286 $template->param(
287 overduecount => $overdues->count,
288 issuecount => $issues->count,
289 finetotal => $balance,
292 if ( $patron and $patron->is_debarred ) {
293 $template->param(
294 'userdebarred' => $patron->debarred,
295 'debarredcomment' => $patron->debarredcomment,
298 if ( $patron->debarred ne "9999-12-31" ) {
299 $template->param( 'userdebarreddate' => $patron->debarred );
303 # Calculate and display patron's age
304 if ( !$patron->is_valid_age ) {
305 $template->param( age_limitations => 1 );
306 $template->param( age_low => $patron->category->dateofbirthrequired );
307 $template->param( age_high => $patron->category->upperagelimit );
313 # STEP 3 : ISSUING
316 if (@$barcodes) {
317 my $checkout_infos;
318 for my $barcode ( @$barcodes ) {
320 my $template_params = {
321 barcode => $barcode,
322 onsite_checkout => $onsite_checkout,
325 # always check for blockers on issuing
326 my ( $error, $question, $alerts, $messages ) = CanBookBeIssued(
327 $patron,
328 $barcode, $datedue,
329 $inprocess,
330 undef,
332 onsite_checkout => $onsite_checkout,
333 override_high_holds => $override_high_holds || $override_high_holds_tmp || 0,
337 my $blocker = $invalidduedate ? 1 : 0;
339 $template_params->{alert} = $alerts;
340 $template_params->{messages} = $messages;
342 my $item = Koha::Items->find({ barcode => $barcode });
344 my $biblio;
345 if ( $item ) {
346 $biblio = $item->biblio;
349 # Fix for bug 7494: optional checkout-time fallback search for a book
351 if ( $error->{'UNKNOWN_BARCODE'}
352 && C4::Context->preference("itemBarcodeFallbackSearch")
353 && not $batch
356 $template_params->{FALLBACK} = 1;
358 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
359 my $query = "kw=" . $barcode;
360 my ( $searcherror, $results, $total_hits ) = $searcher->simple_search_compat($query, 0, 10);
362 # if multiple hits, offer options to librarian
363 if ( $total_hits > 0 ) {
364 my @options = ();
365 foreach my $hit ( @{$results} ) {
366 my $chosen =
367 TransformMarcToKoha( C4::Search::new_record_from_zebra('biblioserver',$hit) );
369 # offer all barcodes individually
370 if ( $chosen->{barcode} ) {
371 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
372 my %chosen_single = %{$chosen};
373 $chosen_single{barcode} = $barcode;
374 push( @options, \%chosen_single );
378 $template_params->{options} = \@options;
382 if ( $error->{DEBT_GUARANTORS} ) {
383 $template_params->{DEBT_GUARANTORS} = $error->{DEBT_GUARANTORS};
384 $template_params->{IMPOSSIBLE} = 1;
385 $blocker = 1;
388 if ( $error->{UNKNOWN_BARCODE} or not $onsite_checkout or not C4::Context->preference("OnSiteCheckoutsForce") ) {
389 delete $question->{'DEBT'} if ($debt_confirmed);
390 foreach my $impossible ( keys %$error ) {
391 $template_params->{$impossible} = $$error{$impossible};
392 $template_params->{IMPOSSIBLE} = 1;
393 $blocker = 1;
397 if( $item and ( !$blocker or $force_allow_issue ) ){
398 my $confirm_required = 0;
399 unless($issueconfirmed){
400 # Get the item title for more information
401 my $materials = $item->materials;
402 my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({ frameworkcode => $biblio->frameworkcode, kohafield => 'items.materials', authorised_value => $materials });
403 $materials = $descriptions->{lib} // $materials;
404 $template_params->{ADDITIONAL_MATERIALS} = $materials;
405 $template_params->{itemhomebranch} = $item->homebranch;
407 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
408 foreach my $needsconfirmation ( keys %$question ) {
409 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
410 $template_params->{getTitleMessageIteminfo} = $biblio->title;
411 $template_params->{getBarcodeMessageIteminfo} = $item->barcode;
412 $template_params->{NEEDSCONFIRMATION} = 1;
413 $confirm_required = 1;
416 unless($confirm_required) {
417 my $switch_onsite_checkout = exists $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED};
418 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, } );
419 $template_params->{issue} = $issue;
420 $session->clear('auto_renew');
421 $inprocess = 1;
425 if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
426 $template->param(
427 reserveborrowernumber => $question->{'resborrowernumber'},
428 reserve_id => $question->{reserve_id},
433 # FIXME If the issue is confirmed, we launch another time checkouts->count, now display the issue count after issue
434 $patron = Koha::Patrons->find( $borrowernumber );
435 $template_params->{issuecount} = $patron->checkouts->count;
437 if ( $item ) {
438 $template_params->{item} = $item;
439 $template_params->{biblio} = $biblio;
440 $template_params->{itembiblionumber} = $biblio->biblionumber;
442 push @$checkout_infos, $template_params;
444 unless ( $batch ) {
445 $template->param( %{$checkout_infos->[0]} );
446 $template->param( barcode => $barcodes->[0] );
447 } else {
448 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
449 $template->param(
450 checkout_infos => $checkout_infos,
451 confirmation_needed => $confirmation_needed,
456 ##################################################################################
457 # BUILD HTML
458 # show all reserves of this borrower, and the position of the reservation ....
459 if ($patron) {
460 my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } ); # FIXME must be Koha::Patron->holds
461 my $waiting_holds = $holds->waiting;
462 $template->param(
463 holds_count => $holds->count(),
464 WaitingHolds => $waiting_holds,
468 if ( $patron ) {
469 my $noissues;
470 if ( $patron->gonenoaddress ) {
471 $template->param( gna => 1 );
472 $noissues = 1;
474 if ( $patron->lost ) {
475 $template->param( lost=> 1 );
476 $noissues = 1;
478 if ( $patron->is_debarred ) {
479 $template->param( dbarred=> 1 );
480 $noissues = 1;
482 my $account = $patron->account;
483 if( ( my $owing = $account->non_issues_charges ) > 0 ) {
484 my $noissuescharge = C4::Context->preference("noissuescharge") || 5; # FIXME If noissuescharge == 0 then 5, why??
485 $noissues ||= ( not C4::Context->preference("AllowFineOverride") and ( $owing > $noissuescharge ) );
486 $template->param(
487 charges => 1,
488 chargesamount => $owing,
490 } elsif ( $balance < 0 ) {
491 $template->param(
492 credits => 1,
493 creditsamount => -$balance,
497 # Check the debt of this patrons guarantors *and* the guarantees of those guarantors
498 my $no_issues_charge_guarantors = C4::Context->preference("NoIssuesChargeGuarantorsWithGuarantees");
499 if ( $no_issues_charge_guarantors ) {
500 my $guarantors_non_issues_charges += $patron->relationships_debt({ include_guarantors => 1, only_this_guarantor => 0, include_this_patron => 1 });
502 if ( $guarantors_non_issues_charges > $no_issues_charge_guarantors ) {
503 $template->param(
504 charges_guarantors_guarantees => $guarantors_non_issues_charges
506 $noissues = 1 unless C4::Context->preference("allowfineoverride");
510 my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
511 $no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
512 if ( defined $no_issues_charge_guarantees ) {
513 my $guarantees_non_issues_charges = 0;
514 my $guarantees = $patron->guarantee_relationships->guarantees;
515 while ( my $g = $guarantees->next ) {
516 $guarantees_non_issues_charges += $g->account->non_issues_charges;
518 if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
519 $template->param(
520 charges_guarantees => 1,
521 chargesamount_guarantees => $guarantees_non_issues_charges,
523 $noissues = 1 unless C4::Context->preference("allowfineoverride");
527 if ( $patron->has_overdues ) {
528 $template->param( odues => 1 );
531 if ( $patron->borrowernotes ) {
532 my $borrowernotes = $patron->borrowernotes;
533 $borrowernotes =~ s#\n#<br />#g;
534 $template->param(
535 notes =>1,
536 notesmsg => $borrowernotes,
540 if ( $noissues ) {
541 $template->param(
542 noissues => ($force_allow_issue) ? 0 : 'true',
543 forceallow => $force_allow_issue,
548 my $messages = Koha::Patron::Messages->search(
550 'me.borrowernumber' => $borrowernumber,
553 join => 'manager',
554 '+select' => ['manager.surname', 'manager.firstname' ],
555 '+as' => ['manager_surname', 'manager_firstname'],
559 my $fast_cataloging = 0;
560 if ( Koha::BiblioFrameworks->find('FA') ) {
561 $fast_cataloging = 1
564 my $view = $batch
565 ?'batch_checkout_view'
566 : 'circview';
568 my @relatives;
569 if ( $patron ) {
570 if ( my @guarantors = $patron->guarantor_relationships()->guarantors() ) {
571 push( @relatives, $_->id ) for @guarantors;
572 push( @relatives, $_->id ) for $patron->siblings();
573 } else {
574 push( @relatives, $_->id ) for $patron->guarantee_relationships()->guarantees();
577 my $relatives_issues_count =
578 Koha::Database->new()->schema()->resultset('Issue')
579 ->count( { borrowernumber => \@relatives } );
581 if ( $patron ) {
582 my $av = Koha::AuthorisedValues->search({ category => 'ROADTYPE', authorised_value => $patron->streettype });
583 my $roadtype = $av->count ? $av->next->lib : '';
584 $template->param(
585 roadtype => $roadtype,
586 patron => $patron,
587 categoryname => $patron->category->description,
588 expiry => $patron->dateexpiry,
592 # Restore date if changed by holds and/or save stickyduedate to session
593 if ($restoreduedatespec || $stickyduedate) {
594 $duedatespec = $restoreduedatespec || $duedatespec;
596 if ($stickyduedate) {
597 $session->param( 'stickyduedate', $duedatespec );
599 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
600 undef $duedatespec;
603 $template->param(
604 messages => $messages,
605 borrowernumber => $borrowernumber,
606 branch => $branch,
607 was_renewed => scalar $query->param('was_renewed') ? 1 : 0,
608 barcodes => $barcodes,
609 stickyduedate => $stickyduedate,
610 duedatespec => $duedatespec,
611 restoreduedatespec => $restoreduedatespec,
612 message => $message,
613 totaldue => sprintf('%.2f', $balance), # FIXME not used in template?
614 inprocess => $inprocess,
615 $view => 1,
616 batch_allowed => $batch_allowed,
617 batch => $batch,
618 AudioAlerts => C4::Context->preference("AudioAlerts"),
619 fast_cataloging => $fast_cataloging,
620 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
621 RoutingSerials => C4::Context->preference('RoutingSerials'),
622 relatives_issues_count => $relatives_issues_count,
623 relatives_borrowernumbers => \@relatives,
627 if ( C4::Context->preference("ExportCircHistory") ) {
628 $template->param(csv_profiles => [ Koha::CsvProfiles->search({ type => 'marc' }) ]);
631 my $has_modifications = Koha::Patron::Modifications->search( { borrowernumber => $borrowernumber } )->count;
632 $template->param(
633 debt_confirmed => $debt_confirmed,
634 SpecifyDueDate => $duedatespec_allow,
635 PatronAutoComplete => C4::Context->preference("PatronAutoComplete"),
636 debarments => scalar GetDebarments({ borrowernumber => $borrowernumber }),
637 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
638 has_modifications => $has_modifications,
639 override_high_holds => $override_high_holds,
640 nopermission => scalar $query->param('nopermission'),
641 autoswitched => $autoswitched,
642 logged_in_user => $logged_in_user,
645 output_html_with_http_headers $query, $cookie, $template->output;