Bug 7947: Update MARC21 440/490 mapping and visibility in nb-NO installer
[koha.git] / circ / circulation.pl
blob81c3bcdf5614797ed3b7190b7afbc31c02c5882a
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 = new CGI;
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 authnotrequired => 0,
134 flagsrequired => { circulate => 'circulate_remaining_permissions' },
137 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
139 my $force_allow_issue = $query->param('forceallow') || 0;
140 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
141 $force_allow_issue = 0;
143 my $onsite_checkout = $query->param('onsite_checkout');
145 if (C4::Context->preference("OnSiteCheckoutAutoCheck") && $onsite_checkout eq "on") {
146 $template->param(onsite_checkout => $onsite_checkout);
149 my @failedrenews = $query->multi_param('failedrenew'); # expected to be itemnumbers
150 our %renew_failed = ();
151 for (@failedrenews) { $renew_failed{$_} = 1; }
153 my @failedreturns = $query->multi_param('failedreturn');
154 our %return_failed = ();
155 for (@failedreturns) { $return_failed{$_} = 1; }
157 my $searchtype = $query->param('searchtype') || q{contain};
159 my $branch = C4::Context->userenv->{'branch'};
161 if (C4::Context->preference("DisplayClearScreenButton")) {
162 $template->param(DisplayClearScreenButton => 1);
165 for my $barcode ( @$barcodes ) {
166 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
167 $barcode = barcodedecode($barcode)
168 if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
171 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
172 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
173 $duedatespec = eval { output_pref( { dt => dt_from_string( $duedatespec ), dateformat => 'iso' }); }
174 if ( $duedatespec );
175 my $restoreduedatespec = $query->param('restoreduedatespec') || $duedatespec || $session->param('stickyduedate');
176 if ( $restoreduedatespec && $restoreduedatespec eq "highholds_empty" ) {
177 undef $restoreduedatespec;
179 my $issueconfirmed = $query->param('issueconfirmed');
180 my $cancelreserve = $query->param('cancelreserve');
181 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
182 my $charges = $query->param('charges') || q{};
184 # Check if stickyduedate is turned off
185 if ( @$barcodes ) {
186 # was stickyduedate loaded from session?
187 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
188 $session->clear( 'stickyduedate' );
189 $stickyduedate = $query->param('stickyduedate');
190 $duedatespec = $query->param('duedatespec');
192 $session->param('auto_renew', scalar $query->param('auto_renew'));
194 else {
195 $session->clear('auto_renew');
198 $template->param( auto_renew => $session->param('auto_renew') );
200 my ($datedue,$invalidduedate);
202 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
203 if( $onsite_checkout && !$duedatespec_allow ) {
204 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
205 $datedue .= ' 23:59:00';
206 } elsif( $duedatespec_allow ) {
207 if ( $duedatespec ) {
208 $datedue = eval { dt_from_string( $duedatespec ) };
209 if (! $datedue ) {
210 $invalidduedate = 1;
211 $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec );
216 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
217 if ( @$barcodes == 0 && $charges eq 'yes' ) {
218 $template->param(
219 PAYCHARGES => 'yes',
220 borrowernumber => $borrowernumber
225 # STEP 2 : FIND BORROWER
226 # if there is a list of find borrowers....
228 my $message;
229 if ($findborrower) {
230 my $patron = Koha::Patrons->find( { cardnumber => $findborrower } );
231 if ( $patron ) {
232 $borrowernumber = $patron->borrowernumber;
233 } else {
234 my $dt_params = { iDisplayLength => -1 };
235 my $results = C4::Utils::DataTables::Members::search(
237 searchmember => $findborrower,
238 searchtype => $searchtype,
239 dt_params => $dt_params,
242 my $borrowers = $results->{patrons};
243 if ( scalar @$borrowers == 1 ) {
244 $borrowernumber = $borrowers->[0]->{borrowernumber};
245 $query->param( 'borrowernumber', $borrowernumber );
246 $query->param( 'barcode', '' );
247 } elsif ( @$borrowers ) {
248 $template->param( borrowers => $borrowers );
249 } else {
250 $query->param( 'findborrower', '' );
251 $message = "'$findborrower'";
256 # get the borrower information.....
257 my $balance = 0;
258 $patron ||= Koha::Patrons->find( $borrowernumber ) if $borrowernumber;
259 if ($patron) {
261 $template->param( borrowernumber => $patron->borrowernumber );
262 output_and_exit_if_error( $query, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
264 my $overdues = $patron->get_overdues;
265 my $issues = $patron->checkouts;
266 $balance = $patron->account->balance;
269 # if the expiry date is before today ie they have expired
270 if ( $patron->is_expired ) {
271 #borrowercard expired, no issues
272 $template->param(
273 noissues => ($force_allow_issue) ? 0 : "1",
274 forceallow => $force_allow_issue,
275 expired => "1",
278 # check for NotifyBorrowerDeparture
279 elsif ( $patron->is_going_to_expire ) {
280 # borrower card soon to expire warn librarian
281 $template->param( "warndeparture" => $patron->dateexpiry ,
283 if (C4::Context->preference('ReturnBeforeExpiry')){
284 $template->param("returnbeforeexpiry" => 1);
287 $template->param(
288 overduecount => $overdues->count,
289 issuecount => $issues->count,
290 finetotal => $balance,
293 if ( $patron and $patron->is_debarred ) {
294 $template->param(
295 'userdebarred' => $patron->debarred,
296 'debarredcomment' => $patron->debarredcomment,
299 if ( $patron->debarred ne "9999-12-31" ) {
300 $template->param( 'userdebarreddate' => $patron->debarred );
304 # Calculate and display patron's age
305 if ( !$patron->is_valid_age ) {
306 $template->param( age_limitations => 1 );
307 $template->param( age_low => $patron->category->dateofbirthrequired );
308 $template->param( age_high => $patron->category->upperagelimit );
314 # STEP 3 : ISSUING
317 if (@$barcodes) {
318 my $checkout_infos;
319 for my $barcode ( @$barcodes ) {
321 my $template_params = {
322 barcode => $barcode,
323 onsite_checkout => $onsite_checkout,
326 # always check for blockers on issuing
327 my ( $error, $question, $alerts, $messages ) = CanBookBeIssued(
328 $patron,
329 $barcode, $datedue,
330 $inprocess,
331 undef,
333 onsite_checkout => $onsite_checkout,
334 override_high_holds => $override_high_holds || $override_high_holds_tmp || 0,
338 my $blocker = $invalidduedate ? 1 : 0;
340 $template_params->{alert} = $alerts;
341 $template_params->{messages} = $messages;
343 my $item = Koha::Items->find({ barcode => $barcode });
345 my $biblio;
346 if ( $item ) {
347 $biblio = $item->biblio;
350 # Fix for bug 7494: optional checkout-time fallback search for a book
352 if ( $error->{'UNKNOWN_BARCODE'}
353 && C4::Context->preference("itemBarcodeFallbackSearch")
354 && not $batch
357 $template_params->{FALLBACK} = 1;
359 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
360 my $query = "kw=" . $barcode;
361 my ( $searcherror, $results, $total_hits ) = $searcher->simple_search_compat($query, 0, 10);
363 # if multiple hits, offer options to librarian
364 if ( $total_hits > 0 ) {
365 my @options = ();
366 foreach my $hit ( @{$results} ) {
367 my $chosen =
368 TransformMarcToKoha( C4::Search::new_record_from_zebra('biblioserver',$hit) );
370 # offer all barcodes individually
371 if ( $chosen->{barcode} ) {
372 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
373 my %chosen_single = %{$chosen};
374 $chosen_single{barcode} = $barcode;
375 push( @options, \%chosen_single );
379 $template_params->{options} = \@options;
383 if ( $error->{UNKNOWN_BARCODE} or not $onsite_checkout or not C4::Context->preference("OnSiteCheckoutsForce") ) {
384 delete $question->{'DEBT'} if ($debt_confirmed);
385 foreach my $impossible ( keys %$error ) {
386 $template_params->{$impossible} = $$error{$impossible};
387 $template_params->{IMPOSSIBLE} = 1;
388 $blocker = 1;
392 if( $item and ( !$blocker or $force_allow_issue ) ){
393 my $confirm_required = 0;
394 unless($issueconfirmed){
395 # Get the item title for more information
396 my $materials = $item->materials;
397 my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({ frameworkcode => $biblio->frameworkcode, kohafield => 'items.materials', authorised_value => $materials });
398 $materials = $descriptions->{lib} // $materials;
399 $template_params->{additional_materials} = $materials;
400 $template_params->{itemhomebranch} = $item->homebranch;
402 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
403 foreach my $needsconfirmation ( keys %$question ) {
404 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
405 $template_params->{getTitleMessageIteminfo} = $biblio->title;
406 $template_params->{getBarcodeMessageIteminfo} = $item->barcode;
407 $template_params->{NEEDSCONFIRMATION} = 1;
408 $confirm_required = 1;
411 unless($confirm_required) {
412 my $switch_onsite_checkout = exists $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED};
413 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, } );
414 $template_params->{issue} = $issue;
415 $session->clear('auto_renew');
416 $inprocess = 1;
420 if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
421 $template->param(
422 reserveborrowernumber => $question->{'resborrowernumber'}
427 # FIXME If the issue is confirmed, we launch another time checkouts->count, now display the issue count after issue
428 $patron = Koha::Patrons->find( $borrowernumber );
429 $template_params->{issuecount} = $patron->checkouts->count;
431 if ( $item ) {
432 $template_params->{item} = $item;
433 $template_params->{biblio} = $biblio;
434 $template_params->{itembiblionumber} = $biblio->biblionumber;
436 push @$checkout_infos, $template_params;
438 unless ( $batch ) {
439 $template->param( %{$checkout_infos->[0]} );
440 $template->param( barcode => $barcodes->[0] );
441 } else {
442 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
443 $template->param(
444 checkout_infos => $checkout_infos,
445 confirmation_needed => $confirmation_needed,
450 ##################################################################################
451 # BUILD HTML
452 # show all reserves of this borrower, and the position of the reservation ....
453 if ($patron) {
454 my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } ); # FIXME must be Koha::Patron->holds
455 my $waiting_holds = $holds->waiting;
456 $template->param(
457 holds_count => $holds->count(),
458 WaitingHolds => $waiting_holds,
462 if ( $patron ) {
463 my $noissues;
464 if ( $patron->gonenoaddress ) {
465 $template->param( gna => 1 );
466 $noissues = 1;
468 if ( $patron->lost ) {
469 $template->param( lost=> 1 );
470 $noissues = 1;
472 if ( $patron->is_debarred ) {
473 $template->param( dbarred=> 1 );
474 $noissues = 1;
476 my $account = $patron->account;
477 if( ( my $owing = $account->non_issues_charges ) > 0 ) {
478 my $noissuescharge = C4::Context->preference("noissuescharge") || 5; # FIXME If noissuescharge == 0 then 5, why??
479 $noissues ||= ( not C4::Context->preference("AllowFineOverride") and ( $owing > $noissuescharge ) );
480 $template->param(
481 charges => 1,
482 chargesamount => $owing,
484 } elsif ( $balance < 0 ) {
485 $template->param(
486 credits => 1,
487 creditsamount => -$balance,
491 my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
492 $no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
493 if ( defined $no_issues_charge_guarantees ) {
494 my $guarantees_non_issues_charges = 0;
495 my $guarantees = $patron->guarantee_relationships->guarantees;
496 while ( my $g = $guarantees->next ) {
497 $guarantees_non_issues_charges += $g->account->non_issues_charges;
499 if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
500 $template->param(
501 charges_guarantees => 1,
502 chargesamount_guarantees => $guarantees_non_issues_charges,
504 $noissues = 1 unless C4::Context->preference("allowfineoverride");
508 if ( $patron->has_overdues ) {
509 $template->param( odues => 1 );
512 if ( $patron->borrowernotes ) {
513 my $borrowernotes = $patron->borrowernotes;
514 $borrowernotes =~ s#\n#<br />#g;
515 $template->param(
516 notes =>1,
517 notesmsg => $borrowernotes,
521 if ( $noissues ) {
522 $template->param(
523 noissues => ($force_allow_issue) ? 0 : 'true',
524 forceallow => $force_allow_issue,
529 my $messages = Koha::Patron::Messages->search(
531 'me.borrowernumber' => $borrowernumber,
534 join => 'manager',
535 '+select' => ['manager.surname', 'manager.firstname' ],
536 '+as' => ['manager_surname', 'manager_firstname'],
540 my $fast_cataloging = 0;
541 if ( Koha::BiblioFrameworks->find('FA') ) {
542 $fast_cataloging = 1
545 my $view = $batch
546 ?'batch_checkout_view'
547 : 'circview';
549 my @relatives;
550 if ( $patron ) {
551 if ( my @guarantors = $patron->guarantor_relationships()->guarantors() ) {
552 push( @relatives, $_->id ) for @guarantors;
553 push( @relatives, $_->id ) for $patron->siblings();
554 } else {
555 push( @relatives, $_->id ) for $patron->guarantee_relationships()->guarantees();
558 my $relatives_issues_count =
559 Koha::Database->new()->schema()->resultset('Issue')
560 ->count( { borrowernumber => \@relatives } );
562 if ( $patron ) {
563 my $av = Koha::AuthorisedValues->search({ category => 'ROADTYPE', authorised_value => $patron->streettype });
564 my $roadtype = $av->count ? $av->next->lib : '';
565 $template->param(
566 roadtype => $roadtype,
567 patron => $patron,
568 categoryname => $patron->category->description,
569 expiry => $patron->dateexpiry,
573 # Restore date if changed by holds and/or save stickyduedate to session
574 if ($restoreduedatespec || $stickyduedate) {
575 $duedatespec = $restoreduedatespec || $duedatespec;
577 if ($stickyduedate) {
578 $session->param( 'stickyduedate', $duedatespec );
580 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
581 undef $duedatespec;
584 $template->param(
585 messages => $messages,
586 borrowernumber => $borrowernumber,
587 branch => $branch,
588 was_renewed => scalar $query->param('was_renewed') ? 1 : 0,
589 barcodes => $barcodes,
590 stickyduedate => $stickyduedate,
591 duedatespec => $duedatespec,
592 restoreduedatespec => $restoreduedatespec,
593 message => $message,
594 totaldue => sprintf('%.2f', $balance), # FIXME not used in template?
595 inprocess => $inprocess,
596 $view => 1,
597 batch_allowed => $batch_allowed,
598 batch => $batch,
599 AudioAlerts => C4::Context->preference("AudioAlerts"),
600 fast_cataloging => $fast_cataloging,
601 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
602 RoutingSerials => C4::Context->preference('RoutingSerials'),
603 relatives_issues_count => $relatives_issues_count,
604 relatives_borrowernumbers => \@relatives,
608 if ( C4::Context->preference("ExportCircHistory") ) {
609 $template->param(csv_profiles => [ Koha::CsvProfiles->search({ type => 'marc' }) ]);
612 my $has_modifications = Koha::Patron::Modifications->search( { borrowernumber => $borrowernumber } )->count;
613 $template->param(
614 debt_confirmed => $debt_confirmed,
615 SpecifyDueDate => $duedatespec_allow,
616 PatronAutoComplete => C4::Context->preference("PatronAutoComplete"),
617 debarments => scalar GetDebarments({ borrowernumber => $borrowernumber }),
618 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
619 has_modifications => $has_modifications,
620 override_high_holds => $override_high_holds,
621 nopermission => scalar $query->param('nopermission'),
622 autoswitched => $autoswitched,
623 logged_in_user => $logged_in_user,
626 output_html_with_http_headers $query, $cookie, $template->output;