Bug 643: Allow override of 'debarred' status
[koha.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 under the
13 # terms of the GNU General Public License as published by the Free Software
14 # Foundation; either version 2 of the License, or (at your option) any later
15 # version.
16 #
17 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
18 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License along
22 # with Koha; if not, write to the Free Software Foundation, Inc.,
23 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24
25 use strict;
26 use warnings;
27 use CGI;
28 use C4::Output;
29 use C4::Print;
30 use C4::Auth qw/:DEFAULT get_session/;
31 use C4::Dates qw/format_date/;
32 use C4::Branch; # GetBranches
33 use C4::Koha;   # GetPrinter
34 use C4::Circulation;
35 use C4::Members;
36 use C4::Biblio;
37 use C4::Search;
38 use MARC::Record;
39 use C4::Reserves;
40 use C4::Context;
41 use CGI::Session;
42 use C4::Members::Attributes qw(GetBorrowerAttributes);
43 use Koha::Borrower::Debarments qw(GetDebarments IsDebarred);
44 use Koha::DateUtils;
45 use Koha::Database;
46
47 use Date::Calc qw(
48   Today
49   Add_Delta_YM
50   Add_Delta_Days
51   Date_to_Days
52 );
53 use List::MoreUtils qw/uniq/;
54
55
56 #
57 # PARAMETERS READING
58 #
59 my $query = new CGI;
60
61 my $sessionID = $query->cookie("CGISESSID") ;
62 my $session = get_session($sessionID);
63
64 # branch and printer are now defined by the userenv
65 # but first we have to check if someone has tried to change them
66
67 my $branch = $query->param('branch');
68 if ($branch){
69     # update our session so the userenv is updated
70     $session->param('branch', $branch);
71     $session->param('branchname', GetBranchName($branch));
72 }
73
74 my $printer = $query->param('printer');
75 if ($printer){
76     # update our session so the userenv is updated
77     $session->param('branchprinter', $printer);
78 }
79
80 if (!C4::Context->userenv && !$branch){
81     if ($session->param('branch') eq 'NO_LIBRARY_SET'){
82         # no branch set we can't issue
83         print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
84         exit;
85     }
86 }
87
88 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
89     {
90         template_name   => 'circ/circulation.tt',
91         query           => $query,
92         type            => "intranet",
93         authnotrequired => 0,
94         flagsrequired   => { circulate => 'circulate_remaining_permissions' },
95     }
96 );
97
98 my $branches = GetBranches();
99
100 my $force_allow_issue = $query->param('forceallow') || 0;
101
102 my @failedrenews = $query->param('failedrenew');    # expected to be itemnumbers
103 our %renew_failed = ();
104 for (@failedrenews) { $renew_failed{$_} = 1; }
105
106 my @failedreturns = $query->param('failedreturn');
107 our %return_failed = ();
108 for (@failedreturns) { $return_failed{$_} = 1; }
109
110 my $findborrower = $query->param('findborrower') || q{};
111 $findborrower =~ s|,| |g;
112 my $borrowernumber = $query->param('borrowernumber');
113
114 $branch  = C4::Context->userenv->{'branch'};  
115 $printer = C4::Context->userenv->{'branchprinter'};
116
117
118 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
119 if (C4::Context->preference("AutoLocation") != 1) {
120     $template->param(ManualLocation => 1);
121 }
122
123 if (C4::Context->preference("DisplayClearScreenButton")) {
124     $template->param(DisplayClearScreenButton => 1);
125 }
126
127 my $barcode        = $query->param('barcode') || q{};
128 $barcode =~  s/^\s*|\s*$//g; # remove leading/trailing whitespace
129
130 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
131 my $stickyduedate  = $query->param('stickyduedate') || $session->param('stickyduedate');
132 my $duedatespec    = $query->param('duedatespec')   || $session->param('stickyduedate');
133 my $issueconfirmed = $query->param('issueconfirmed');
134 my $cancelreserve  = $query->param('cancelreserve');
135 my $print          = $query->param('print') || q{};
136 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
137 my $charges        = $query->param('charges') || q{};
138
139 # Check if stickyduedate is turned off
140 if ( $barcode ) {
141     # was stickyduedate loaded from session?
142     if ( $stickyduedate && ! $query->param("stickyduedate") ) {
143         $session->clear( 'stickyduedate' );
144         $stickyduedate  = $query->param('stickyduedate');
145         $duedatespec    = $query->param('duedatespec');
146     }
147     $session->param('auto_renew', $query->param('auto_renew'));
148 }
149 else {
150     $session->clear('auto_renew');
151 }
152
153 my ($datedue,$invalidduedate);
154
155 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
156 if($duedatespec_allow){
157     if ($duedatespec) {
158         if ($duedatespec =~ C4::Dates->regexp('syspref')) {
159                 $datedue = dt_from_string($duedatespec);
160         } else {
161             $invalidduedate = 1;
162             $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
163         }
164     }
165 }
166
167 our $todaysdate = C4::Dates->new->output('iso');
168
169 # check and see if we should print
170 if ( $barcode eq '' && $print eq 'maybe' ) {
171     $print = 'yes';
172 }
173
174 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
175 if ( $barcode eq '' && $charges eq 'yes' ) {
176     $template->param(
177         PAYCHARGES     => 'yes',
178         borrowernumber => $borrowernumber
179     );
180 }
181
182 if ( $print eq 'yes' && $borrowernumber ne '' ) {
183     if ( C4::Context->boolean_preference('printcirculationslips') ) {
184         my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
185         NetworkPrint($letter->{content});
186     }
187     $query->param( 'borrowernumber', '' );
188     $borrowernumber = '';
189 }
190
191 #
192 # STEP 2 : FIND BORROWER
193 # if there is a list of find borrowers....
194 #
195 my $borrowerslist;
196 my $message;
197 if ($findborrower) {
198     my $borrowers = Search($findborrower, 'cardnumber') || [];
199     if (C4::Context->preference("AddPatronLists")) {
200         $template->param(
201             "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
202         );
203         if (C4::Context->preference("AddPatronLists")=~/code/){
204             my $categories = GetBorrowercategoryList;
205             $categories->[0]->{'first'} = 1;
206             $template->param(categories=>$categories);
207         }
208     }
209     if ( @$borrowers == 0 ) {
210         $query->param( 'findborrower', '' );
211         $message = "'$findborrower'";
212     }
213     elsif ( @$borrowers == 1 ) {
214         $borrowernumber = $borrowers->[0]->{'borrowernumber'};
215         $query->param( 'borrowernumber', $borrowernumber );
216         $query->param( 'barcode',           '' );
217     }
218     else {
219         $borrowerslist = $borrowers;
220     }
221 }
222
223 # get the borrower information.....
224 my $borrower;
225 if ($borrowernumber) {
226     $borrower = GetMemberDetails( $borrowernumber, 0 );
227     my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
228
229     # Warningdate is the date that the warning starts appearing
230     my (  $today_year,   $today_month,   $today_day) = Today();
231     my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
232     my (  $enrol_year,   $enrol_month,   $enrol_day) = split /-/, $borrower->{'dateenrolled'};
233     # Renew day is calculated by adding the enrolment period to today
234     my (  $renew_year,   $renew_month,   $renew_day);
235     if ($enrol_year*$enrol_month*$enrol_day>0) {
236         (  $renew_year,   $renew_month,   $renew_day) =
237         Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
238             0 , $borrower->{'enrolmentperiod'});
239     }
240     # if the expiry date is before today ie they have expired
241     if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
242         || Date_to_Days($today_year,     $today_month, $today_day  ) 
243          > Date_to_Days($warning_year, $warning_month, $warning_day) )
244     {
245         #borrowercard expired, no issues
246         $template->param(
247             flagged  => "1",
248             noissues => ($force_allow_issue) ? 0 : "1",
249             forceallow => $force_allow_issue,
250             expired => "1",
251             renewaldate => format_date("$renew_year-$renew_month-$renew_day")
252         );
253     }
254     # check for NotifyBorrowerDeparture
255     elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
256             Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
257             Date_to_Days( $today_year, $today_month, $today_day ) ) 
258     {
259         # borrower card soon to expire warn librarian
260         $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
261         flagged       => "1",);
262         if (C4::Context->preference('ReturnBeforeExpiry')){
263             $template->param("returnbeforeexpiry" => 1);
264         }
265     }
266     $template->param(
267         overduecount => $od,
268         issuecount   => $issue,
269         finetotal    => $fines
270     );
271
272     if ( IsDebarred($borrowernumber) ) {
273         $template->param(
274             'userdebarred'    => $borrower->{debarred},
275             'debarredcomment' => $borrower->{debarredcomment},
276         );
277
278         if ( $borrower->{debarred} ne "9999-12-31" ) {
279             $template->param( 'userdebarreddate' =>
280                   C4::Dates::format_date( $borrower->{debarred} ) );
281         }
282     }
283
284 }
285
286 #
287 # STEP 3 : ISSUING
288 #
289 #
290 if ($barcode) {
291     # always check for blockers on issuing
292     my ( $error, $question, $alerts ) =
293     CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
294     my $blocker = $invalidduedate ? 1 : 0;
295
296     $template->param( alert => $alerts );
297
298     #  Get the item title for more information
299     my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
300     $template->param(
301         authvalcode_notforloan => C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'}),
302     );
303     # Fix for bug 7494: optional checkout-time fallback search for a book
304
305     if ( $error->{'UNKNOWN_BARCODE'}
306         && C4::Context->preference("itemBarcodeFallbackSearch") )
307     {
308      $template->param( FALLBACK => 1 );
309
310         my $query = "kw=" . $barcode;
311         my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
312
313         # if multiple hits, offer options to librarian
314         if ( $total_hits > 0 ) {
315             my @options = ();
316             foreach my $hit ( @{$results} ) {
317                 my $chosen =
318                   TransformMarcToKoha( C4::Context->dbh,
319                     C4::Search::new_record_from_zebra('biblioserver',$hit) );
320
321                 # offer all barcodes individually
322                 if ( $chosen->{barcode} ) {
323                     foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
324                         my %chosen_single = %{$chosen};
325                         $chosen_single{barcode} = $barcode;
326                         push( @options, \%chosen_single );
327                     }
328                 }
329             }
330             $template->param( options => \@options );
331         }
332     }
333
334     delete $question->{'DEBT'} if ($debt_confirmed);
335     foreach my $impossible ( keys %$error ) {
336         $template->param(
337             $impossible => $$error{$impossible},
338             IMPOSSIBLE  => 1
339         );
340         $blocker = 1;
341     }
342     if( !$blocker || $force_allow_issue ){
343         my $confirm_required = 0;
344         unless($issueconfirmed){
345             #  Get the item title for more information
346             my $getmessageiteminfo  = GetBiblioFromItemNumber(undef,$barcode);
347             $template->{VARS}->{'additional_materials'} = $getmessageiteminfo->{'materials'};
348             $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
349
350             # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
351             foreach my $needsconfirmation ( keys %$question ) {
352                 $template->param(
353                     $needsconfirmation => $$question{$needsconfirmation},
354                     getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
355                     getBarcodeMessageIteminfo => $getmessageiteminfo->{'barcode'},
356                     NEEDSCONFIRMATION  => 1
357                 );
358                 $confirm_required = 1;
359             }
360         }
361         unless($confirm_required) {
362             AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, $session->param('auto_renew') );
363             $session->clear('auto_renew');
364             $inprocess = 1;
365         }
366     }
367     
368     my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
369     $template->param( issuecount => $issue );
370 }
371
372 # reload the borrower info for the sake of reseting the flags.....
373 if ($borrowernumber) {
374     $borrower = GetMemberDetails( $borrowernumber, 0 );
375 }
376
377 ##################################################################################
378 # BUILD HTML
379 # show all reserves of this borrower, and the position of the reservation ....
380 if ($borrowernumber) {
381     $template->param(
382         holds_count => Koha::Database->new()->schema()->resultset('Reserve')
383           ->count( { borrowernumber => $borrowernumber } ) );
384
385     $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
386 }
387
388 my @values;
389 my %labels;
390 my $selectborrower;
391 if ($borrowerslist) {
392     foreach (
393         sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
394         } @$borrowerslist
395       )
396     {
397         push @values, $_->{'borrowernumber'};
398         $labels{ $_->{'borrowernumber'} } =
399 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'} - $_->{'branchcode'}) ...  $_->{'address'} ";
400     }
401     $selectborrower = {
402         values => \@values,
403         labels => \%labels,
404     };
405 }
406
407 #title
408 my $flags = $borrower->{'flags'};
409 foreach my $flag ( sort keys %$flags ) {
410     $template->param( flagged=> 1);
411     $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
412     if ( $flags->{$flag}->{'noissues'} ) {
413         $template->param(
414             noissues => ($force_allow_issue) ? 0 : 'true',
415             forceallow => $force_allow_issue,
416         );
417         if ( $flag eq 'GNA' ) {
418             $template->param( gna => 'true' );
419         }
420         elsif ( $flag eq 'LOST' ) {
421             $template->param( lost => 'true' );
422         }
423         elsif ( $flag eq 'DBARRED' ) {
424             $template->param( dbarred => 'true' );
425         }
426         elsif ( $flag eq 'CHARGES' ) {
427             $template->param(
428                 charges    => 'true',
429                 chargesmsg => $flags->{'CHARGES'}->{'message'},
430                 chargesamount => $flags->{'CHARGES'}->{'amount'},
431                 charges_is_blocker => 1
432             );
433         }
434         elsif ( $flag eq 'CREDITS' ) {
435             $template->param(
436                 credits    => 'true',
437                 creditsmsg => $flags->{'CREDITS'}->{'message'},
438                 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
439             );
440         }
441     }
442     else {
443         if ( $flag eq 'CHARGES' ) {
444             $template->param(
445                 charges    => 'true',
446                 chargesmsg => $flags->{'CHARGES'}->{'message'},
447                 chargesamount => $flags->{'CHARGES'}->{'amount'},
448             );
449         }
450         elsif ( $flag eq 'CREDITS' ) {
451             $template->param(
452                 credits    => 'true',
453                 creditsmsg => $flags->{'CREDITS'}->{'message'},
454                 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
455             );
456         }
457         elsif ( $flag eq 'ODUES' ) {
458             $template->param(
459                 odues    => 'true',
460                 oduesmsg => $flags->{'ODUES'}->{'message'}
461             );
462
463             my $items = $flags->{$flag}->{'itemlist'};
464             if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
465                 $template->param( nonreturns => 'true' );
466             }
467         }
468         elsif ( $flag eq 'NOTES' ) {
469             $template->param(
470                 notes    => 'true',
471                 notesmsg => $flags->{'NOTES'}->{'message'}
472             );
473         }
474     }
475 }
476
477 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
478 $amountold =~ s/^.*\$//;    # remove upto the $, if any
479
480 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
481
482 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
483     my  ( $catcodes, $labels ) =  GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
484     my $cnt = scalar(@$catcodes);
485     $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
486     $template->param( 'catcode' =>    $catcodes->[0])  if $cnt == 1;
487 }
488
489 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
490 if($lib_messages_loop){ $template->param(flagged => 1 ); }
491
492 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
493 if($bor_messages_loop){ $template->param(flagged => 1 ); }
494
495 # Computes full borrower address
496 my @fulladdress;
497 push @fulladdress, $borrower->{'streetnumber'} if ( $borrower->{'streetnumber'} );
498 push @fulladdress, C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{'streettype'} ) if ( $borrower->{'streettype'} );
499 push @fulladdress, $borrower->{'address'} if ( $borrower->{'address'} );
500
501 my $fast_cataloging = 0;
502 if (defined getframeworkinfo('FA')) {
503     $fast_cataloging = 1 
504 }
505
506 if (C4::Context->preference('ExtendedPatronAttributes')) {
507     my $attributes = GetBorrowerAttributes($borrowernumber);
508     $template->param(
509         ExtendedPatronAttributes => 1,
510         extendedattributes => $attributes
511     );
512 }
513
514 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
515 my $relatives_issues_count =
516   Koha::Database->new()->schema()->resultset('Issue')
517   ->count( { borrowernumber => \@relatives } );
518
519 $template->param(
520     lib_messages_loop => $lib_messages_loop,
521     bor_messages_loop => $bor_messages_loop,
522     all_messages_del  => C4::Context->preference('AllowAllMessageDeletion'),
523     findborrower      => $findborrower,
524     borrower          => $borrower,
525     borrowernumber    => $borrowernumber,
526     branch            => $branch,
527     branchname        => GetBranchName($borrower->{'branchcode'}),
528     printer           => $printer,
529     printername       => $printer,
530     firstname         => $borrower->{'firstname'},
531     surname           => $borrower->{'surname'},
532     showname          => $borrower->{'showname'},
533     category_type     => $borrower->{'category_type'},
534     was_renewed       => $query->param('was_renewed') ? 1 : 0,
535     expiry            => format_date($borrower->{'dateexpiry'}),
536     categorycode      => $borrower->{'categorycode'},
537     categoryname      => $borrower->{description},
538     address           => join(' ', @fulladdress),
539     address2          => $borrower->{'address2'},
540     email             => $borrower->{'email'},
541     emailpro          => $borrower->{'emailpro'},
542     borrowernotes     => $borrower->{'borrowernotes'},
543     city              => $borrower->{'city'},
544     state              => $borrower->{'state'},
545     zipcode           => $borrower->{'zipcode'},
546     country           => $borrower->{'country'},
547     phone             => $borrower->{'phone'},
548     mobile            => $borrower->{'mobile'},
549     phonepro          => $borrower->{'phonepro'},
550     cardnumber        => $borrower->{'cardnumber'},
551     othernames        => $borrower->{'othernames'},
552     amountold         => $amountold,
553     barcode           => $barcode,
554     stickyduedate     => $stickyduedate,
555     duedatespec       => $duedatespec,
556     message           => $message,
557     selectborrower    => $selectborrower,
558     totaldue          => sprintf('%.2f', $total),
559     inprocess         => $inprocess,
560     is_child          => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
561     circview => 1,
562     soundon           => C4::Context->preference("SoundOn"),
563     fast_cataloging   => $fast_cataloging,
564     CircAutoPrintQuickSlip   => C4::Context->preference("CircAutoPrintQuickSlip"),
565     activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
566     SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
567     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
568     RoutingSerials => C4::Context->preference('RoutingSerials'),
569     relatives_issues_count => $relatives_issues_count,
570     relatives_borrowernumbers => \@relatives,
571 );
572
573 # save stickyduedate to session
574 if ($stickyduedate) {
575     $session->param( 'stickyduedate', $duedatespec );
576 }
577
578 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
579 $template->param( picture => 1 ) if $picture;
580
581 # get authorised values with type of BOR_NOTES
582
583 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
584
585 $template->param(
586     debt_confirmed            => $debt_confirmed,
587     SpecifyDueDate            => $duedatespec_allow,
588     CircAutocompl             => C4::Context->preference("CircAutocompl"),
589     AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
590     export_remove_fields      => C4::Context->preference("ExportRemoveFields"),
591     export_with_csv_profile   => C4::Context->preference("ExportWithCsvProfile"),
592     canned_bor_notes_loop     => $canned_notes,
593     debarments                => GetDebarments({ borrowernumber => $borrowernumber }),
594 );
595
596 output_html_with_http_headers $query, $cookie, $template->output;