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