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