Bug 24593: Rewrite marc21_default_matching_rules to YAML
[koha.git] / circ / circulation.pl
blob1572a080e52744fd7b6c92f27aaccbc88fb27a3f
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::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 Koha::AuthorisedValues;
47 use Koha::CsvProfiles;
48 use Koha::Patrons;
49 use Koha::Patron::Debarments qw(GetDebarments);
50 use Koha::DateUtils;
51 use Koha::Database;
52 use Koha::BiblioFrameworks;
53 use Koha::Items;
54 use Koha::Patron::Messages;
55 use Koha::SearchEngine;
56 use Koha::SearchEngine::Search;
57 use Koha::Patron::Modifications;
59 use Date::Calc qw(
60 Today
61 Add_Delta_Days
62 Date_to_Days
64 use List::MoreUtils qw/uniq/;
67 # PARAMETERS READING
69 my $query = new CGI;
71 my $override_high_holds = $query->param('override_high_holds');
72 my $override_high_holds_tmp = $query->param('override_high_holds_tmp');
74 my $sessionID = $query->cookie("CGISESSID") ;
75 my $session = get_session($sessionID);
77 my $barcodes = [];
78 my $barcode = $query->param('barcode');
79 my $findborrower;
80 my $autoswitched;
81 my $borrowernumber = $query->param('borrowernumber');
83 if (C4::Context->preference("AutoSwitchPatron") && $barcode) {
84 if (Koha::Patrons->search( { cardnumber => $barcode} )->count() > 0) {
85 $findborrower = $barcode;
86 undef $barcode;
87 undef $borrowernumber;
88 $autoswitched = 1;
91 $findborrower ||= $query->param('findborrower') || q{};
92 $findborrower =~ s|,| |g;
94 # Barcode given by user could be '0'
95 if ( $barcode || ( defined($barcode) && $barcode eq '0' ) ) {
96 $barcodes = [ $barcode ];
97 } else {
98 my $filefh = $query->upload('uploadfile');
99 if ( $filefh ) {
100 while ( my $content = <$filefh> ) {
101 $content =~ s/[\r\n]*$//g;
102 push @$barcodes, $content if $content;
104 } elsif ( my $list = $query->param('barcodelist') ) {
105 push @$barcodes, split( /\s\n/, $list );
106 $barcodes = [ map { $_ =~ /^\s*$/ ? () : $_ } @$barcodes ];
107 } else {
108 @$barcodes = $query->multi_param('barcodes');
112 $barcodes = [ uniq @$barcodes ];
114 my $template_name = q|circ/circulation.tt|;
115 my $patron = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : undef;
116 my $batch = $query->param('batch');
117 my $batch_allowed = 0;
118 if ( $batch && C4::Context->preference('BatchCheckouts') ) {
119 $template_name = q|circ/circulation_batch_checkouts.tt|;
120 my @batch_category_codes = split '\|', C4::Context->preference('BatchCheckoutsValidCategories');
121 my $categorycode = $patron->categorycode;
122 if ( $categorycode && grep { $_ eq $categorycode } @batch_category_codes ) {
123 $batch_allowed = 1;
124 } else {
125 $barcodes = [];
129 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
131 template_name => $template_name,
132 query => $query,
133 type => "intranet",
134 authnotrequired => 0,
135 flagsrequired => { circulate => 'circulate_remaining_permissions' },
138 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
140 my $force_allow_issue = $query->param('forceallow') || 0;
141 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
142 $force_allow_issue = 0;
144 my $onsite_checkout = $query->param('onsite_checkout');
146 if (C4::Context->preference("OnSiteCheckoutAutoCheck") && $onsite_checkout eq "on") {
147 $template->param(onsite_checkout => $onsite_checkout);
150 my @failedrenews = $query->multi_param('failedrenew'); # expected to be itemnumbers
151 our %renew_failed = ();
152 for (@failedrenews) { $renew_failed{$_} = 1; }
154 my @failedreturns = $query->multi_param('failedreturn');
155 our %return_failed = ();
156 for (@failedreturns) { $return_failed{$_} = 1; }
158 my $searchtype = $query->param('searchtype') || q{contain};
160 my $branch = C4::Context->userenv->{'branch'};
162 if (C4::Context->preference("DisplayClearScreenButton")) {
163 $template->param(DisplayClearScreenButton => 1);
166 for my $barcode ( @$barcodes ) {
167 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
168 $barcode = barcodedecode($barcode)
169 if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
172 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
173 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
174 $duedatespec = eval { output_pref( { dt => dt_from_string( $duedatespec ), dateformat => 'iso', timeformat => '24hr' }); }
175 if ( $duedatespec );
176 my $restoreduedatespec = $query->param('restoreduedatespec') || $duedatespec || $session->param('stickyduedate');
177 if ( $restoreduedatespec && $restoreduedatespec eq "highholds_empty" ) {
178 undef $restoreduedatespec;
180 my $issueconfirmed = $query->param('issueconfirmed');
181 my $cancelreserve = $query->param('cancelreserve');
182 my $print = $query->param('print') || q{};
183 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
184 my $charges = $query->param('charges') || q{};
186 # Check if stickyduedate is turned off
187 if ( @$barcodes ) {
188 # was stickyduedate loaded from session?
189 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
190 $session->clear( 'stickyduedate' );
191 $stickyduedate = $query->param('stickyduedate');
192 $duedatespec = $query->param('duedatespec');
194 $session->param('auto_renew', scalar $query->param('auto_renew'));
196 else {
197 $session->clear('auto_renew');
200 $template->param( auto_renew => $session->param('auto_renew') );
202 my ($datedue,$invalidduedate);
204 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
205 if( $onsite_checkout && !$duedatespec_allow ) {
206 $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
207 $datedue .= ' 23:59:00';
208 } elsif( $duedatespec_allow ) {
209 if ( $duedatespec ) {
210 $datedue = eval { dt_from_string( $duedatespec ) };
211 if (! $datedue ) {
212 $invalidduedate = 1;
213 $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec );
218 # check and see if we should print
219 if ( @$barcodes == 0 && $print eq 'maybe' ) {
220 $print = 'yes';
223 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
224 if ( @$barcodes == 0 && $charges eq 'yes' ) {
225 $template->param(
226 PAYCHARGES => 'yes',
227 borrowernumber => $borrowernumber
231 if ( $print eq 'yes' && $borrowernumber ne '' ) {
232 if ( C4::Context->boolean_preference('printcirculationslips') ) {
233 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
234 NetworkPrint($letter->{content});
236 $query->param( 'borrowernumber', '' );
237 $borrowernumber = '';
238 undef $patron;
242 # STEP 2 : FIND BORROWER
243 # if there is a list of find borrowers....
245 my $message;
246 if ($findborrower) {
247 my $patron = Koha::Patrons->find( { cardnumber => $findborrower } );
248 if ( $patron ) {
249 $borrowernumber = $patron->borrowernumber;
250 } else {
251 my $dt_params = { iDisplayLength => -1 };
252 my $results = C4::Utils::DataTables::Members::search(
254 searchmember => $findborrower,
255 searchtype => $searchtype,
256 dt_params => $dt_params,
259 my $borrowers = $results->{patrons};
260 if ( scalar @$borrowers == 1 ) {
261 $borrowernumber = $borrowers->[0]->{borrowernumber};
262 $query->param( 'borrowernumber', $borrowernumber );
263 $query->param( 'barcode', '' );
264 } elsif ( @$borrowers ) {
265 $template->param( borrowers => $borrowers );
266 } else {
267 $query->param( 'findborrower', '' );
268 $message = "'$findborrower'";
273 # get the borrower information.....
274 my $balance = 0;
275 $patron ||= Koha::Patrons->find( $borrowernumber ) if $borrowernumber;
276 if ($patron) {
278 $template->param( borrowernumber => $patron->borrowernumber );
279 output_and_exit_if_error( $query, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
281 my $overdues = $patron->get_overdues;
282 my $issues = $patron->checkouts;
283 $balance = $patron->account->balance;
286 # if the expiry date is before today ie they have expired
287 if ( $patron->is_expired ) {
288 #borrowercard expired, no issues
289 $template->param(
290 noissues => ($force_allow_issue) ? 0 : "1",
291 forceallow => $force_allow_issue,
292 expired => "1",
295 # check for NotifyBorrowerDeparture
296 elsif ( $patron->is_going_to_expire ) {
297 # borrower card soon to expire warn librarian
298 $template->param( "warndeparture" => $patron->dateexpiry ,
300 if (C4::Context->preference('ReturnBeforeExpiry')){
301 $template->param("returnbeforeexpiry" => 1);
304 $template->param(
305 overduecount => $overdues->count,
306 issuecount => $issues->count,
307 finetotal => $balance,
310 if ( $patron and $patron->is_debarred ) {
311 $template->param(
312 'userdebarred' => $patron->debarred,
313 'debarredcomment' => $patron->debarredcomment,
316 if ( $patron->debarred ne "9999-12-31" ) {
317 $template->param( 'userdebarreddate' => $patron->debarred );
321 # Calculate and display patron's age
322 if ( !$patron->is_valid_age ) {
323 $template->param( age_limitations => 1 );
324 $template->param( age_low => $patron->category->dateofbirthrequired );
325 $template->param( age_high => $patron->category->upperagelimit );
331 # STEP 3 : ISSUING
334 if (@$barcodes) {
335 my $checkout_infos;
336 for my $barcode ( @$barcodes ) {
338 my $template_params = {
339 barcode => $barcode,
340 onsite_checkout => $onsite_checkout,
343 # always check for blockers on issuing
344 my ( $error, $question, $alerts, $messages ) = CanBookBeIssued(
345 $patron,
346 $barcode, $datedue,
347 $inprocess,
348 undef,
350 onsite_checkout => $onsite_checkout,
351 override_high_holds => $override_high_holds || $override_high_holds_tmp || 0,
355 my $blocker = $invalidduedate ? 1 : 0;
357 $template_params->{alert} = $alerts;
358 $template_params->{messages} = $messages;
360 my $item = Koha::Items->find({ barcode => $barcode });
362 my $biblio;
363 if ( $item ) {
364 $biblio = $item->biblio;
367 # Fix for bug 7494: optional checkout-time fallback search for a book
369 if ( $error->{'UNKNOWN_BARCODE'}
370 && C4::Context->preference("itemBarcodeFallbackSearch")
371 && not $batch
374 $template_params->{FALLBACK} = 1;
376 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
377 my $query = "kw=" . $barcode;
378 my ( $searcherror, $results, $total_hits ) = $searcher->simple_search_compat($query, 0, 10);
380 # if multiple hits, offer options to librarian
381 if ( $total_hits > 0 ) {
382 my @options = ();
383 foreach my $hit ( @{$results} ) {
384 my $chosen =
385 TransformMarcToKoha( C4::Search::new_record_from_zebra('biblioserver',$hit) );
387 # offer all barcodes individually
388 if ( $chosen->{barcode} ) {
389 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
390 my %chosen_single = %{$chosen};
391 $chosen_single{barcode} = $barcode;
392 push( @options, \%chosen_single );
396 $template_params->{options} = \@options;
400 if ( $error->{UNKNOWN_BARCODE} or not $onsite_checkout or not C4::Context->preference("OnSiteCheckoutsForce") ) {
401 delete $question->{'DEBT'} if ($debt_confirmed);
402 foreach my $impossible ( keys %$error ) {
403 $template_params->{$impossible} = $$error{$impossible};
404 $template_params->{IMPOSSIBLE} = 1;
405 $blocker = 1;
409 if( $item and ( !$blocker or $force_allow_issue ) ){
410 my $confirm_required = 0;
411 unless($issueconfirmed){
412 # Get the item title for more information
413 my $materials = $item->materials;
414 my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({ frameworkcode => $biblio->frameworkcode, kohafield => 'items.materials', authorised_value => $materials });
415 $materials = $descriptions->{lib} // $materials;
416 $template_params->{additional_materials} = $materials;
417 $template_params->{itemhomebranch} = $item->homebranch;
419 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
420 foreach my $needsconfirmation ( keys %$question ) {
421 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
422 $template_params->{getTitleMessageIteminfo} = $biblio->title;
423 $template_params->{getBarcodeMessageIteminfo} = $item->barcode;
424 $template_params->{NEEDSCONFIRMATION} = 1;
425 $confirm_required = 1;
428 unless($confirm_required) {
429 my $switch_onsite_checkout = exists $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED};
430 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, } );
431 $template_params->{issue} = $issue;
432 $session->clear('auto_renew');
433 $inprocess = 1;
437 if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
438 $template->param(
439 reserveborrowernumber => $question->{'resborrowernumber'}
444 # FIXME If the issue is confirmed, we launch another time checkouts->count, now display the issue count after issue
445 $patron = Koha::Patrons->find( $borrowernumber );
446 $template_params->{issuecount} = $patron->checkouts->count;
448 if ( $item ) {
449 $template_params->{item} = $item;
450 $template_params->{biblio} = $biblio;
451 $template_params->{itembiblionumber} = $biblio->biblionumber;
453 push @$checkout_infos, $template_params;
455 unless ( $batch ) {
456 $template->param( %{$checkout_infos->[0]} );
457 $template->param( barcode => $barcodes->[0] );
458 } else {
459 my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
460 $template->param(
461 checkout_infos => $checkout_infos,
462 confirmation_needed => $confirmation_needed,
467 ##################################################################################
468 # BUILD HTML
469 # show all reserves of this borrower, and the position of the reservation ....
470 if ($patron) {
471 my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } ); # FIXME must be Koha::Patron->holds
472 my $waiting_holds = $holds->waiting;
473 $template->param(
474 holds_count => $holds->count(),
475 WaitingHolds => $waiting_holds,
479 if ( $patron ) {
480 my $noissues;
481 if ( $patron->gonenoaddress ) {
482 $template->param( gna => 1 );
483 $noissues = 1;
485 if ( $patron->lost ) {
486 $template->param( lost=> 1 );
487 $noissues = 1;
489 if ( $patron->is_debarred ) {
490 $template->param( dbarred=> 1 );
491 $noissues = 1;
493 my $account = $patron->account;
494 if( ( my $owing = $account->non_issues_charges ) > 0 ) {
495 my $noissuescharge = C4::Context->preference("noissuescharge") || 5; # FIXME If noissuescharge == 0 then 5, why??
496 $noissues ||= ( not C4::Context->preference("AllowFineOverride") and ( $owing > $noissuescharge ) );
497 $template->param(
498 charges => 1,
499 chargesamount => $owing,
501 } elsif ( $balance < 0 ) {
502 $template->param(
503 credits => 1,
504 creditsamount => -$balance,
508 my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
509 $no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
510 if ( defined $no_issues_charge_guarantees ) {
511 my $guarantees_non_issues_charges = 0;
512 my $guarantees = $patron->guarantee_relationships->guarantees;
513 while ( my $g = $guarantees->next ) {
514 $guarantees_non_issues_charges += $g->account->non_issues_charges;
516 if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
517 $template->param(
518 charges_guarantees => 1,
519 chargesamount_guarantees => $guarantees_non_issues_charges,
521 $noissues = 1 unless C4::Context->preference("allowfineoverride");
525 if ( $patron->has_overdues ) {
526 $template->param( odues => 1 );
529 if ( $patron->borrowernotes ) {
530 my $borrowernotes = $patron->borrowernotes;
531 $borrowernotes =~ s#\n#<br />#g;
532 $template->param(
533 notes =>1,
534 notesmsg => $borrowernotes,
538 if ( $noissues ) {
539 $template->param(
540 noissues => ($force_allow_issue) ? 0 : 'true',
541 forceallow => $force_allow_issue,
546 my $messages = Koha::Patron::Messages->search(
548 'me.borrowernumber' => $borrowernumber,
551 join => 'manager',
552 '+select' => ['manager.surname', 'manager.firstname' ],
553 '+as' => ['manager_surname', 'manager_firstname'],
557 my $fast_cataloging = 0;
558 if ( Koha::BiblioFrameworks->find('FA') ) {
559 $fast_cataloging = 1
562 my $view = $batch
563 ?'batch_checkout_view'
564 : 'circview';
566 my @relatives;
567 if ( $patron ) {
568 if ( my @guarantors = $patron->guarantor_relationships()->guarantors() ) {
569 push( @relatives, $_->id ) for @guarantors;
570 push( @relatives, $_->id ) for $patron->siblings();
571 } else {
572 push( @relatives, $_->id ) for $patron->guarantee_relationships()->guarantees();
575 my $relatives_issues_count =
576 Koha::Database->new()->schema()->resultset('Issue')
577 ->count( { borrowernumber => \@relatives } );
579 if ( $patron ) {
580 my $av = Koha::AuthorisedValues->search({ category => 'ROADTYPE', authorised_value => $patron->streettype });
581 my $roadtype = $av->count ? $av->next->lib : '';
582 $template->param(
583 roadtype => $roadtype,
584 patron => $patron,
585 categoryname => $patron->category->description,
586 expiry => $patron->dateexpiry,
590 # Restore date if changed by holds and/or save stickyduedate to session
591 if ($restoreduedatespec || $stickyduedate) {
592 $duedatespec = $restoreduedatespec || $duedatespec;
594 if ($stickyduedate) {
595 $session->param( 'stickyduedate', $duedatespec );
597 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
598 undef $duedatespec;
601 $template->param(
602 messages => $messages,
603 borrowernumber => $borrowernumber,
604 branch => $branch,
605 was_renewed => scalar $query->param('was_renewed') ? 1 : 0,
606 barcodes => $barcodes,
607 stickyduedate => $stickyduedate,
608 duedatespec => $duedatespec,
609 restoreduedatespec => $restoreduedatespec,
610 message => $message,
611 totaldue => sprintf('%.2f', $balance), # FIXME not used in template?
612 inprocess => $inprocess,
613 $view => 1,
614 batch_allowed => $batch_allowed,
615 batch => $batch,
616 AudioAlerts => C4::Context->preference("AudioAlerts"),
617 fast_cataloging => $fast_cataloging,
618 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
619 RoutingSerials => C4::Context->preference('RoutingSerials'),
620 relatives_issues_count => $relatives_issues_count,
621 relatives_borrowernumbers => \@relatives,
625 if ( C4::Context->preference("ExportCircHistory") ) {
626 $template->param(csv_profiles => [ Koha::CsvProfiles->search({ type => 'marc' }) ]);
629 my $has_modifications = Koha::Patron::Modifications->search( { borrowernumber => $borrowernumber } )->count;
630 $template->param(
631 debt_confirmed => $debt_confirmed,
632 SpecifyDueDate => $duedatespec_allow,
633 PatronAutoComplete => C4::Context->preference("PatronAutoComplete"),
634 debarments => scalar GetDebarments({ borrowernumber => $borrowernumber }),
635 todaysdate => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
636 has_modifications => $has_modifications,
637 override_high_holds => $override_high_holds,
638 nopermission => scalar $query->param('nopermission'),
639 autoswitched => $autoswitched,
640 logged_in_user => $logged_in_user,
643 output_html_with_http_headers $query, $cookie, $template->output;