Bug 23158: Make the assignment statement more readable
[koha-equinox.git] / circ / circulation.pl
1 #!/usr/bin/perl
2
3 # script to execute issuing of books
4
5 # Copyright 2000-2002 Katipo Communications
6 # copyright 2010 BibLibre
7 # Copyright 2011 PTFS-Europe Ltd.
8 # Copyright 2012 software.coop and MJ Ray
9 #
10 # This file is part of Koha.
11 #
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.
16 #
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.
21 #
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>.
24
25 # FIXME There are too many calls to Koha::Patrons->find in this script
26
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;
58
59 use Date::Calc qw(
60   Today
61   Add_Delta_Days
62   Date_to_Days
63 );
64 use List::MoreUtils qw/uniq/;
65
66 #
67 # PARAMETERS READING
68 #
69 my $query = new CGI;
70
71 my $override_high_holds     = $query->param('override_high_holds');
72 my $override_high_holds_tmp = $query->param('override_high_holds_tmp');
73
74 my $sessionID = $query->cookie("CGISESSID") ;
75 my $session = get_session($sessionID);
76 if (!C4::Context->userenv){
77     if ($session->param('branch') eq 'NO_LIBRARY_SET'){
78         # no branch set we can't issue
79         print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
80         exit;
81     }
82 }
83
84 my $barcodes = [];
85 my $barcode =  $query->param('barcode');
86 my $findborrower;
87 my $autoswitched;
88 my $borrowernumber = $query->param('borrowernumber');
89
90 if (C4::Context->preference("AutoSwitchPatron") && $barcode) {
91     if (Koha::Patrons->search( { cardnumber => $barcode} )->count() > 0) {
92         $findborrower = $barcode;
93         undef $barcode;
94         undef $borrowernumber;
95         $autoswitched = 1;
96     }
97 }
98 $findborrower ||= $query->param('findborrower') || q{};
99 $findborrower =~ s|,| |g;
100
101 # Barcode given by user could be '0'
102 if ( $barcode || ( defined($barcode) && $barcode eq '0' ) ) {
103     $barcodes = [ $barcode ];
104 } else {
105     my $filefh = $query->upload('uploadfile');
106     if ( $filefh ) {
107         while ( my $content = <$filefh> ) {
108             $content =~ s/[\r\n]*$//g;
109             push @$barcodes, $content if $content;
110         }
111     } elsif ( my $list = $query->param('barcodelist') ) {
112         push @$barcodes, split( /\s\n/, $list );
113         $barcodes = [ map { $_ =~ /^\s*$/ ? () : $_ } @$barcodes ];
114     } else {
115         @$barcodes = $query->multi_param('barcodes');
116     }
117 }
118
119 $barcodes = [ uniq @$barcodes ];
120
121 my $template_name = q|circ/circulation.tt|;
122 my $patron = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : undef;
123 my $batch = $query->param('batch');
124 my $batch_allowed = 0;
125 if ( $batch && C4::Context->preference('BatchCheckouts') ) {
126     $template_name = q|circ/circulation_batch_checkouts.tt|;
127     my @batch_category_codes = split '\|', C4::Context->preference('BatchCheckoutsValidCategories');
128     my $categorycode = $patron->categorycode;
129     if ( $categorycode && grep {/^$categorycode$/} @batch_category_codes ) {
130         $batch_allowed = 1;
131     } else {
132         $barcodes = [];
133     }
134 }
135
136 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
137     {
138         template_name   => $template_name,
139         query           => $query,
140         type            => "intranet",
141         authnotrequired => 0,
142         flagsrequired   => { circulate => 'circulate_remaining_permissions' },
143     }
144 );
145 my $logged_in_user = Koha::Patrons->find( $loggedinuser ) or die "Not logged in";
146
147 my $force_allow_issue = $query->param('forceallow') || 0;
148 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
149     $force_allow_issue = 0;
150 }
151
152 my $onsite_checkout = $query->param('onsite_checkout');
153
154 my @failedrenews = $query->multi_param('failedrenew');    # expected to be itemnumbers
155 our %renew_failed = ();
156 for (@failedrenews) { $renew_failed{$_} = 1; }
157
158 my @failedreturns = $query->multi_param('failedreturn');
159 our %return_failed = ();
160 for (@failedreturns) { $return_failed{$_} = 1; }
161
162 my $searchtype = $query->param('searchtype') || q{contain};
163
164 my $branch = C4::Context->userenv->{'branch'};
165
166 if (C4::Context->preference("DisplayClearScreenButton")) {
167     $template->param(DisplayClearScreenButton => 1);
168 }
169
170 for my $barcode ( @$barcodes ) {
171     $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
172     $barcode = barcodedecode($barcode)
173         if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
174 }
175
176 my $stickyduedate  = $query->param('stickyduedate') || $session->param('stickyduedate');
177 my $duedatespec    = $query->param('duedatespec')   || $session->param('stickyduedate');
178 $duedatespec = eval { output_pref( { dt => dt_from_string( $duedatespec ), dateformat => 'iso', timeformat => '24hr' }); }
179     if ( $duedatespec );
180 my $restoreduedatespec  = $query->param('restoreduedatespec') || $duedatespec || $session->param('stickyduedate');
181 if ( $restoreduedatespec && $restoreduedatespec eq "highholds_empty" ) {
182     undef $restoreduedatespec;
183 }
184 my $issueconfirmed = $query->param('issueconfirmed');
185 my $cancelreserve  = $query->param('cancelreserve');
186 my $print          = $query->param('print') || q{};
187 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
188 my $charges        = $query->param('charges') || q{};
189
190 # Check if stickyduedate is turned off
191 if ( @$barcodes ) {
192     # was stickyduedate loaded from session?
193     if ( $stickyduedate && ! $query->param("stickyduedate") ) {
194         $session->clear( 'stickyduedate' );
195         $stickyduedate  = $query->param('stickyduedate');
196         $duedatespec    = $query->param('duedatespec');
197     }
198     $session->param('auto_renew', scalar $query->param('auto_renew'));
199 }
200 else {
201     $session->clear('auto_renew');
202 }
203
204 my ($datedue,$invalidduedate);
205
206 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
207 if( $onsite_checkout && !$duedatespec_allow ) {
208     $datedue = output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
209     $datedue .= ' 23:59:00';
210 } elsif( $duedatespec_allow ) {
211     if ( $duedatespec ) {
212         $datedue = eval { dt_from_string( $duedatespec ) };
213         if (! $datedue ) {
214             $invalidduedate = 1;
215             $template->param( IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec );
216         }
217     }
218 }
219
220 # check and see if we should print
221 if ( @$barcodes == 0 && $print eq 'maybe' ) {
222     $print = 'yes';
223 }
224
225 my $inprocess = (@$barcodes == 0) ? '' : $query->param('inprocess');
226 if ( @$barcodes == 0 && $charges eq 'yes' ) {
227     $template->param(
228         PAYCHARGES     => 'yes',
229         borrowernumber => $borrowernumber
230     );
231 }
232
233 if ( $print eq 'yes' && $borrowernumber ne '' ) {
234     if ( C4::Context->boolean_preference('printcirculationslips') ) {
235         my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
236         NetworkPrint($letter->{content});
237     }
238     $query->param( 'borrowernumber', '' );
239     $borrowernumber = '';
240     undef $patron;
241 }
242
243 #
244 # STEP 2 : FIND BORROWER
245 # if there is a list of find borrowers....
246 #
247 my $message;
248 if ($findborrower) {
249     my $patron = Koha::Patrons->find( { cardnumber => $findborrower } );
250     if ( $patron ) {
251         $borrowernumber = $patron->borrowernumber;
252     } else {
253         my $dt_params = { iDisplayLength => -1 };
254         my $results = C4::Utils::DataTables::Members::search(
255             {
256                 searchmember => $findborrower,
257                 searchtype   => $searchtype,
258                 dt_params    => $dt_params,
259             }
260         );
261         my $borrowers = $results->{patrons};
262         if ( scalar @$borrowers == 1 ) {
263             $borrowernumber = $borrowers->[0]->{borrowernumber};
264             $query->param( 'borrowernumber', $borrowernumber );
265             $query->param( 'barcode',           '' );
266         } elsif ( @$borrowers ) {
267             $template->param( borrowers => $borrowers );
268         } else {
269             $query->param( 'findborrower', '' );
270             $message = "'$findborrower'";
271         }
272     }
273 }
274
275 # get the borrower information.....
276 my $balance = 0;
277 $patron ||= Koha::Patrons->find( $borrowernumber ) if $borrowernumber;
278 if ($patron) {
279
280     $template->param( borrowernumber => $patron->borrowernumber );
281     output_and_exit_if_error( $query, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
282
283     my $overdues = $patron->get_overdues;
284     my $issues = $patron->checkouts;
285     $balance = $patron->account->balance;
286
287
288     # if the expiry date is before today ie they have expired
289     if ( $patron->is_expired ) {
290         #borrowercard expired, no issues
291         $template->param(
292             noissues => ($force_allow_issue) ? 0 : "1",
293             forceallow => $force_allow_issue,
294             expired => "1",
295         );
296     }
297     # check for NotifyBorrowerDeparture
298     elsif ( $patron->is_going_to_expire ) {
299         # borrower card soon to expire warn librarian
300         $template->param( "warndeparture" => $patron->dateexpiry ,
301                         );
302         if (C4::Context->preference('ReturnBeforeExpiry')){
303             $template->param("returnbeforeexpiry" => 1);
304         }
305     }
306     $template->param(
307         overduecount => $overdues->count,
308         issuecount   => $issues->count,
309         finetotal    => $balance,
310     );
311
312     if ( $patron and $patron->is_debarred ) {
313         $template->param(
314             'userdebarred'    => $patron->debarred,
315             'debarredcomment' => $patron->debarredcomment,
316         );
317
318         if ( $patron->debarred ne "9999-12-31" ) {
319             $template->param( 'userdebarreddate' => $patron->debarred );
320         }
321     }
322
323 }
324
325 #
326 # STEP 3 : ISSUING
327 #
328 #
329 if (@$barcodes) {
330   my $checkout_infos;
331   for my $barcode ( @$barcodes ) {
332
333     my $template_params = {
334         barcode         => $barcode,
335         onsite_checkout => $onsite_checkout,
336     };
337
338     # always check for blockers on issuing
339     my ( $error, $question, $alerts, $messages ) = CanBookBeIssued(
340         $patron,
341         $barcode, $datedue,
342         $inprocess,
343         undef,
344         {
345             onsite_checkout     => $onsite_checkout,
346             override_high_holds => $override_high_holds || $override_high_holds_tmp || 0,
347         }
348     );
349
350     my $blocker = $invalidduedate ? 1 : 0;
351
352     $template_params->{alert} = $alerts;
353     $template_params->{messages} = $messages;
354
355     my $item = Koha::Items->find({ barcode => $barcode });
356
357     my $biblio;
358     if ( $item ) {
359         $biblio = $item->biblio;
360     }
361
362     # Fix for bug 7494: optional checkout-time fallback search for a book
363
364     if ( $error->{'UNKNOWN_BARCODE'}
365         && C4::Context->preference("itemBarcodeFallbackSearch")
366         && not $batch
367     )
368     {
369      $template_params->{FALLBACK} = 1;
370
371         my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
372         my $query = "kw=" . $barcode;
373         my ( $searcherror, $results, $total_hits ) = $searcher->simple_search_compat($query, 0, 10);
374
375         # if multiple hits, offer options to librarian
376         if ( $total_hits > 0 ) {
377             my @options = ();
378             foreach my $hit ( @{$results} ) {
379                 my $chosen =
380                   TransformMarcToKoha( C4::Search::new_record_from_zebra('biblioserver',$hit) );
381
382                 # offer all barcodes individually
383                 if ( $chosen->{barcode} ) {
384                     foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
385                         my %chosen_single = %{$chosen};
386                         $chosen_single{barcode} = $barcode;
387                         push( @options, \%chosen_single );
388                     }
389                 }
390             }
391             $template_params->{options} = \@options;
392         }
393     }
394
395     if ( $error->{UNKNOWN_BARCODE} or not $onsite_checkout or not C4::Context->preference("OnSiteCheckoutsForce") ) {
396         delete $question->{'DEBT'} if ($debt_confirmed);
397         foreach my $impossible ( keys %$error ) {
398             $template_params->{$impossible} = $$error{$impossible};
399             $template_params->{IMPOSSIBLE} = 1;
400             $blocker = 1;
401         }
402     }
403
404     if( $item and ( !$blocker or $force_allow_issue ) ){
405         my $confirm_required = 0;
406         unless($issueconfirmed){
407             #  Get the item title for more information
408             my $materials = $item->materials;
409             my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({ frameworkcode => $biblio->frameworkcode, kohafield => 'items.materials', authorised_value => $materials });
410             $materials = $descriptions->{lib} // $materials;
411             $template_params->{additional_materials} = $materials;
412             $template_params->{itemhomebranch} = $item->homebranch;
413
414             # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
415             foreach my $needsconfirmation ( keys %$question ) {
416                 $template_params->{$needsconfirmation} = $$question{$needsconfirmation};
417                 $template_params->{getTitleMessageIteminfo} = $biblio->title;
418                 $template_params->{getBarcodeMessageIteminfo} = $item->barcode;
419                 $template_params->{NEEDSCONFIRMATION} = 1;
420                 $template_params->{auto_renew} = $session->param('auto_renew');
421                 $confirm_required = 1;
422             }
423         }
424         unless($confirm_required) {
425             my $switch_onsite_checkout = exists $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED};
426             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, } );
427             $template_params->{issue} = $issue;
428             $session->clear('auto_renew');
429             $inprocess = 1;
430         }
431     }
432
433     if ($question->{RESERVE_WAITING} or $question->{RESERVED}){
434         $template->param(
435             reserveborrowernumber => $question->{'resborrowernumber'}
436         );
437     }
438
439
440     # FIXME If the issue is confirmed, we launch another time checkouts->count, now display the issue count after issue
441     $patron = Koha::Patrons->find( $borrowernumber );
442     $template_params->{issuecount} = $patron->checkouts->count;
443
444     if ( $item ) {
445         $template_params->{item} = $item;
446         $template_params->{biblio} = $biblio;
447         $template_params->{itembiblionumber} = $biblio->biblionumber;
448     }
449     push @$checkout_infos, $template_params;
450   }
451   unless ( $batch ) {
452     $template->param( %{$checkout_infos->[0]} );
453     $template->param( barcode => $barcodes->[0] );
454   } else {
455     my $confirmation_needed = grep { $_->{NEEDSCONFIRMATION} } @$checkout_infos;
456     $template->param(
457         checkout_infos => $checkout_infos,
458         confirmation_needed => $confirmation_needed,
459     );
460   }
461 }
462
463 ##################################################################################
464 # BUILD HTML
465 # show all reserves of this borrower, and the position of the reservation ....
466 if ($patron) {
467     my $holds = Koha::Holds->search( { borrowernumber => $borrowernumber } ); # FIXME must be Koha::Patron->holds
468     my $waiting_holds = $holds->waiting;
469     $template->param(
470         holds_count  => $holds->count(),
471         WaitingHolds => $waiting_holds,
472     );
473 }
474
475 if ( $patron ) {
476     my $noissues;
477     if ( $patron->gonenoaddress ) {
478         $template->param( gna => 1 );
479         $noissues = 1;
480     }
481     if ( $patron->lost ) {
482         $template->param( lost=> 1 );
483         $noissues = 1;
484     }
485     if ( $patron->is_debarred ) {
486         $template->param( dbarred=> 1 );
487         $noissues = 1;
488     }
489     my $account = $patron->account;
490     if( ( my $owing = $account->non_issues_charges ) > 0 ) {
491         my $noissuescharge = C4::Context->preference("noissuescharge") || 5; # FIXME If noissuescharge == 0 then 5, why??
492         $noissues ||= ( not C4::Context->preference("AllowFineOverride") and ( $owing > $noissuescharge ) );
493         $template->param(
494             charges => 1,
495             chargesamount => $owing,
496         )
497     } elsif ( $balance < 0 ) {
498         $template->param(
499             credits => 1,
500             creditsamount => -$balance,
501         );
502     }
503
504     my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
505     $no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
506     if ( defined $no_issues_charge_guarantees ) {
507         my $guarantees_non_issues_charges = 0;
508         my $guarantees = $patron->guarantees;
509         while ( my $g = $guarantees->next ) {
510             $guarantees_non_issues_charges += $g->account->non_issues_charges;
511         }
512         if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
513             $template->param(
514                 charges_guarantees    => 1,
515                 chargesamount_guarantees => $guarantees_non_issues_charges,
516             );
517             $noissues = 1 unless C4::Context->preference("allowfineoverride");
518         }
519     }
520
521     if ( $patron->has_overdues ) {
522         $template->param( odues => 1 );
523     }
524
525     if ( $patron->borrowernotes ) {
526         my $borrowernotes = $patron->borrowernotes;
527         $borrowernotes =~ s#\n#<br />#g;
528         $template->param(
529             notes =>1,
530             notesmsg => $borrowernotes,
531         )
532     }
533
534     if ( $noissues ) {
535         $template->param(
536             noissues => ($force_allow_issue) ? 0 : 'true',
537             forceallow => $force_allow_issue,
538         );
539     }
540 }
541
542 my $messages = Koha::Patron::Messages->search(
543     {
544         'me.borrowernumber' => $borrowernumber,
545     },
546     {
547        join => 'manager',
548        '+select' => ['manager.surname', 'manager.firstname' ],
549        '+as' => ['manager_surname', 'manager_firstname'],
550     }
551 );
552
553 my $fast_cataloging = 0;
554 if ( Koha::BiblioFrameworks->find('FA') ) {
555     $fast_cataloging = 1 
556 }
557
558 my $view = $batch
559     ?'batch_checkout_view'
560     : 'circview';
561
562 my @relatives;
563 if ( $borrowernumber ) {
564     if ( $patron ) {
565         if ( my $guarantor = $patron->guarantor ) {
566             push @relatives, $guarantor->borrowernumber;
567             push @relatives, $_->borrowernumber for $patron->siblings;
568         } else {
569             push @relatives, $_->borrowernumber for $patron->guarantees;
570         }
571     }
572 }
573 my $relatives_issues_count =
574   Koha::Database->new()->schema()->resultset('Issue')
575   ->count( { borrowernumber => \@relatives } );
576
577 if ( $patron ) {
578     my $av = Koha::AuthorisedValues->search({ category => 'ROADTYPE', authorised_value => $patron->streettype });
579     my $roadtype = $av->count ? $av->next->lib : '';
580     $template->param(
581         roadtype          => $roadtype,
582         patron            => $patron,
583         categoryname      => $patron->category->description,
584         expiry            => $patron->dateexpiry,
585     );
586 }
587
588 # Restore date if changed by holds and/or save stickyduedate to session
589 if ($restoreduedatespec || $stickyduedate) {
590     $duedatespec = $restoreduedatespec || $duedatespec;
591
592     if ($stickyduedate) {
593         $session->param( 'stickyduedate', $duedatespec );
594     }
595 } elsif (defined($duedatespec) && !defined($restoreduedatespec)) {
596     undef $duedatespec;
597 }
598
599 $template->param(
600     messages           => $messages,
601     borrowernumber    => $borrowernumber,
602     branch            => $branch,
603     was_renewed       => scalar $query->param('was_renewed') ? 1 : 0,
604     barcodes          => $barcodes,
605     stickyduedate     => $stickyduedate,
606     duedatespec       => $duedatespec,
607     restoreduedatespec => $restoreduedatespec,
608     message           => $message,
609     totaldue          => sprintf('%.2f', $balance), # FIXME not used in template?
610     inprocess         => $inprocess,
611     $view             => 1,
612     batch_allowed     => $batch_allowed,
613     batch             => $batch,
614     AudioAlerts           => C4::Context->preference("AudioAlerts"),
615     fast_cataloging   => $fast_cataloging,
616     CircAutoPrintQuickSlip   => C4::Context->preference("CircAutoPrintQuickSlip"),
617     RoutingSerials => C4::Context->preference('RoutingSerials'),
618     relatives_issues_count => $relatives_issues_count,
619     relatives_borrowernumbers => \@relatives,
620 );
621
622
623 if ( C4::Context->preference("ExportCircHistory") ) {
624     $template->param(csv_profiles => [ Koha::CsvProfiles->search({ type => 'marc' }) ]);
625 }
626
627 my $has_modifications = Koha::Patron::Modifications->search( { borrowernumber => $borrowernumber } )->count;
628 $template->param(
629     debt_confirmed            => $debt_confirmed,
630     SpecifyDueDate            => $duedatespec_allow,
631     CircAutocompl             => C4::Context->preference("CircAutocompl"),
632     debarments                => scalar GetDebarments({ borrowernumber => $borrowernumber }),
633     todaysdate                => output_pref( { dt => dt_from_string()->set(hour => 23)->set(minute => 59), dateformat => 'sql' } ),
634     has_modifications         => $has_modifications,
635     override_high_holds       => $override_high_holds,
636     nopermission              => scalar $query->param('nopermission'),
637     autoswitched              => $autoswitched,
638 );
639
640 output_html_with_http_headers $query, $cookie, $template->output;