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