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