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