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