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