3 # script to execute issuing of books
5 # Copyright 2000-2002 Katipo Communications
6 # copyright 2010 BibLibre
7 # Copyright 2011 PTFS-Europe Ltd.
8 # Copyright 2012 software.coop and MJ Ray
10 # This file is part of Koha.
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
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.
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.
29 use DateTime::Duration;
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
44 use C4::Members::Attributes qw(GetBorrowerAttributes);
45 use Koha::Borrower::Debarments qw(GetDebarments IsDebarred);
55 use List::MoreUtils qw/uniq/;
63 my $sessionID = $query->cookie("CGISESSID") ;
64 my $session = get_session($sessionID);
66 # branch and printer are now defined by the userenv
67 # but first we have to check if someone has tried to change them
69 my $branch = $query->param('branch');
71 # update our session so the userenv is updated
72 $session->param('branch', $branch);
73 $session->param('branchname', GetBranchName($branch));
76 my $printer = $query->param('printer');
78 # update our session so the userenv is updated
79 $session->param('branchprinter', $printer);
82 if (!C4::Context->userenv && !$branch){
83 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
84 # no branch set we can't issue
85 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
90 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
92 template_name => 'circ/circulation.tt',
96 flagsrequired => { circulate => 'circulate_remaining_permissions' },
100 my $branches = GetBranches();
102 my $force_allow_issue = $query->param('forceallow') || 0;
103 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
104 $force_allow_issue = 0;
107 my @failedrenews = $query->param('failedrenew'); # expected to be itemnumbers
108 our %renew_failed = ();
109 for (@failedrenews) { $renew_failed{$_} = 1; }
111 my @failedreturns = $query->param('failedreturn');
112 our %return_failed = ();
113 for (@failedreturns) { $return_failed{$_} = 1; }
115 my $findborrower = $query->param('findborrower') || q{};
116 $findborrower =~ s|,| |g;
117 my $borrowernumber = $query->param('borrowernumber');
119 $branch = C4::Context->userenv->{'branch'};
120 $printer = C4::Context->userenv->{'branchprinter'};
123 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
124 if (C4::Context->preference("AutoLocation") != 1) {
125 $template->param(ManualLocation => 1);
128 if (C4::Context->preference("DisplayClearScreenButton")) {
129 $template->param(DisplayClearScreenButton => 1);
132 my $barcode = $query->param('barcode') || q{};
133 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
135 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
136 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
137 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
138 my $issueconfirmed = $query->param('issueconfirmed');
139 my $cancelreserve = $query->param('cancelreserve');
140 my $print = $query->param('print') || q{};
141 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
142 my $charges = $query->param('charges') || q{};
144 # Check if stickyduedate is turned off
146 # was stickyduedate loaded from session?
147 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
148 $session->clear( 'stickyduedate' );
149 $stickyduedate = $query->param('stickyduedate');
150 $duedatespec = $query->param('duedatespec');
152 $session->param('auto_renew', $query->param('auto_renew'));
155 $session->clear('auto_renew');
158 my ($datedue,$invalidduedate);
160 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
161 if($duedatespec_allow){
163 if ($duedatespec =~ C4::Dates->regexp('syspref')) {
164 $datedue = dt_from_string($duedatespec);
167 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
172 our $todaysdate = C4::Dates->new->output('iso');
174 # check and see if we should print
175 if ( $barcode eq '' && $print eq 'maybe' ) {
179 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
180 if ( $barcode eq '' && $charges eq 'yes' ) {
183 borrowernumber => $borrowernumber
187 if ( $print eq 'yes' && $borrowernumber ne '' ) {
188 if ( C4::Context->boolean_preference('printcirculationslips') ) {
189 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
190 NetworkPrint($letter->{content});
192 $query->param( 'borrowernumber', '' );
193 $borrowernumber = '';
197 # STEP 2 : FIND BORROWER
198 # if there is a list of find borrowers....
203 my $borrowers = Search($findborrower, 'cardnumber') || [];
204 if (C4::Context->preference("AddPatronLists")) {
206 "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
208 if (C4::Context->preference("AddPatronLists")=~/code/){
209 my $categories = GetBorrowercategoryList;
210 $categories->[0]->{'first'} = 1;
211 $template->param(categories=>$categories);
214 if ( @$borrowers == 0 ) {
215 $query->param( 'findborrower', '' );
216 $message = "'$findborrower'";
218 elsif ( @$borrowers == 1 ) {
219 $borrowernumber = $borrowers->[0]->{'borrowernumber'};
220 $query->param( 'borrowernumber', $borrowernumber );
221 $query->param( 'barcode', '' );
224 $borrowerslist = $borrowers;
228 # get the borrower information.....
230 if ($borrowernumber) {
231 $borrower = GetMemberDetails( $borrowernumber, 0 );
232 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
234 # Warningdate is the date that the warning starts appearing
235 my ( $today_year, $today_month, $today_day) = Today();
236 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
237 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
238 # Renew day is calculated by adding the enrolment period to today
239 my ( $renew_year, $renew_month, $renew_day);
240 if ($enrol_year*$enrol_month*$enrol_day>0) {
241 ( $renew_year, $renew_month, $renew_day) =
242 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
243 0 , $borrower->{'enrolmentperiod'});
245 # if the expiry date is before today ie they have expired
246 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
247 || Date_to_Days($today_year, $today_month, $today_day )
248 > Date_to_Days($warning_year, $warning_month, $warning_day) )
250 #borrowercard expired, no issues
253 noissues => ($force_allow_issue) ? 0 : "1",
254 forceallow => $force_allow_issue,
256 renewaldate => format_date("$renew_year-$renew_month-$renew_day")
259 # check for NotifyBorrowerDeparture
260 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
261 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
262 Date_to_Days( $today_year, $today_month, $today_day ) )
264 # borrower card soon to expire warn librarian
265 $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
267 if (C4::Context->preference('ReturnBeforeExpiry')){
268 $template->param("returnbeforeexpiry" => 1);
273 issuecount => $issue,
277 if ( IsDebarred($borrowernumber) ) {
279 'userdebarred' => $borrower->{debarred},
280 'debarredcomment' => $borrower->{debarredcomment},
283 if ( $borrower->{debarred} ne "9999-12-31" ) {
284 $template->param( 'userdebarreddate' =>
285 C4::Dates::format_date( $borrower->{debarred} ) );
296 # always check for blockers on issuing
297 my ( $error, $question, $alerts ) =
298 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
299 my $blocker = $invalidduedate ? 1 : 0;
301 $template->param( alert => $alerts );
303 # Get the item title for more information
304 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
306 authvalcode_notforloan => C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'}),
308 # Fix for bug 7494: optional checkout-time fallback search for a book
310 if ( $error->{'UNKNOWN_BARCODE'}
311 && C4::Context->preference("itemBarcodeFallbackSearch") )
313 $template->param( FALLBACK => 1 );
315 my $query = "kw=" . $barcode;
316 my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
318 # if multiple hits, offer options to librarian
319 if ( $total_hits > 0 ) {
321 foreach my $hit ( @{$results} ) {
323 TransformMarcToKoha( C4::Context->dbh,
324 C4::Search::new_record_from_zebra('biblioserver',$hit) );
326 # offer all barcodes individually
327 if ( $chosen->{barcode} ) {
328 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
329 my %chosen_single = %{$chosen};
330 $chosen_single{barcode} = $barcode;
331 push( @options, \%chosen_single );
335 $template->param( options => \@options );
339 unless( $query->param('inhouse_use') and C4::Context->preference("In-House Use Force") ) {
340 delete $question->{'DEBT'} if ($debt_confirmed);
341 foreach my $impossible ( keys %$error ) {
343 $impossible => $$error{$impossible},
349 if( !$blocker || $force_allow_issue ){
350 my $confirm_required = 0;
351 unless($issueconfirmed){
352 # Get the item title for more information
353 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
354 $template->{VARS}->{'additional_materials'} = $getmessageiteminfo->{'materials'};
355 $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
357 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
358 foreach my $needsconfirmation ( keys %$question ) {
360 $needsconfirmation => $$question{$needsconfirmation},
361 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
362 getBarcodeMessageIteminfo => $getmessageiteminfo->{'barcode'},
363 NEEDSCONFIRMATION => 1,
364 inhouse_use => $query->param('inhouse_use'),
366 $confirm_required = 1;
369 unless($confirm_required) {
370 my $inhouse_use = $query->param('inhouse_use');
371 AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, { inhouse_use => $inhouse_use, auto_renew => $session->param('auto_renew') } );
372 $session->clear('auto_renew');
377 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
378 $template->param( issuecount => $issue );
381 # reload the borrower info for the sake of reseting the flags.....
382 if ($borrowernumber) {
383 $borrower = GetMemberDetails( $borrowernumber, 0 );
386 ##################################################################################
388 # show all reserves of this borrower, and the position of the reservation ....
389 if ($borrowernumber) {
391 holds_count => Koha::Database->new()->schema()->resultset('Reserve')
392 ->count( { borrowernumber => $borrowernumber } ) );
394 $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
400 if ($borrowerslist) {
402 sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
406 push @values, $_->{'borrowernumber'};
407 $labels{ $_->{'borrowernumber'} } =
408 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'} - $_->{'branchcode'}) ... $_->{'address'} ";
417 my $flags = $borrower->{'flags'};
418 foreach my $flag ( sort keys %$flags ) {
419 $template->param( flagged=> 1);
420 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
421 if ( $flags->{$flag}->{'noissues'} ) {
423 noissues => ($force_allow_issue) ? 0 : 'true',
424 forceallow => $force_allow_issue,
426 if ( $flag eq 'GNA' ) {
427 $template->param( gna => 'true' );
429 elsif ( $flag eq 'LOST' ) {
430 $template->param( lost => 'true' );
432 elsif ( $flag eq 'DBARRED' ) {
433 $template->param( dbarred => 'true' );
435 elsif ( $flag eq 'CHARGES' ) {
438 chargesmsg => $flags->{'CHARGES'}->{'message'},
439 chargesamount => $flags->{'CHARGES'}->{'amount'},
440 charges_is_blocker => 1
443 elsif ( $flag eq 'CREDITS' ) {
446 creditsmsg => $flags->{'CREDITS'}->{'message'},
447 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
452 if ( $flag eq 'CHARGES' ) {
455 chargesmsg => $flags->{'CHARGES'}->{'message'},
456 chargesamount => $flags->{'CHARGES'}->{'amount'},
459 elsif ( $flag eq 'CREDITS' ) {
462 creditsmsg => $flags->{'CREDITS'}->{'message'},
463 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
466 elsif ( $flag eq 'ODUES' ) {
469 oduesmsg => $flags->{'ODUES'}->{'message'}
472 my $items = $flags->{$flag}->{'itemlist'};
473 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
474 $template->param( nonreturns => 'true' );
477 elsif ( $flag eq 'NOTES' ) {
480 notesmsg => $flags->{'NOTES'}->{'message'}
486 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
487 $amountold =~ s/^.*\$//; # remove upto the $, if any
489 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
491 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
492 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
493 my $cnt = scalar(@$catcodes);
494 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
495 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
498 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
499 if($lib_messages_loop){ $template->param(flagged => 1 ); }
501 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
502 if($bor_messages_loop){ $template->param(flagged => 1 ); }
504 # Computes full borrower address
506 push @fulladdress, $borrower->{'streetnumber'} if ( $borrower->{'streetnumber'} );
507 push @fulladdress, C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{'streettype'} ) if ( $borrower->{'streettype'} );
508 push @fulladdress, $borrower->{'address'} if ( $borrower->{'address'} );
510 my $fast_cataloging = 0;
511 if (defined getframeworkinfo('FA')) {
515 if (C4::Context->preference('ExtendedPatronAttributes')) {
516 my $attributes = GetBorrowerAttributes($borrowernumber);
518 ExtendedPatronAttributes => 1,
519 extendedattributes => $attributes
523 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
524 my $relatives_issues_count =
525 Koha::Database->new()->schema()->resultset('Issue')
526 ->count( { borrowernumber => \@relatives } );
529 lib_messages_loop => $lib_messages_loop,
530 bor_messages_loop => $bor_messages_loop,
531 all_messages_del => C4::Context->preference('AllowAllMessageDeletion'),
532 findborrower => $findborrower,
533 borrower => $borrower,
534 borrowernumber => $borrowernumber,
536 branchname => GetBranchName($borrower->{'branchcode'}),
538 printername => $printer,
539 firstname => $borrower->{'firstname'},
540 surname => $borrower->{'surname'},
541 showname => $borrower->{'showname'},
542 category_type => $borrower->{'category_type'},
543 was_renewed => $query->param('was_renewed') ? 1 : 0,
544 expiry => format_date($borrower->{'dateexpiry'}),
545 categorycode => $borrower->{'categorycode'},
546 categoryname => $borrower->{description},
547 address => join(' ', @fulladdress),
548 address2 => $borrower->{'address2'},
549 email => $borrower->{'email'},
550 emailpro => $borrower->{'emailpro'},
551 borrowernotes => $borrower->{'borrowernotes'},
552 city => $borrower->{'city'},
553 state => $borrower->{'state'},
554 zipcode => $borrower->{'zipcode'},
555 country => $borrower->{'country'},
556 phone => $borrower->{'phone'},
557 mobile => $borrower->{'mobile'},
558 phonepro => $borrower->{'phonepro'},
559 cardnumber => $borrower->{'cardnumber'},
560 othernames => $borrower->{'othernames'},
561 amountold => $amountold,
563 stickyduedate => $stickyduedate,
564 duedatespec => $duedatespec,
566 selectborrower => $selectborrower,
567 totaldue => sprintf('%.2f', $total),
568 inprocess => $inprocess,
569 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
571 soundon => C4::Context->preference("SoundOn"),
572 fast_cataloging => $fast_cataloging,
573 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
574 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
575 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
576 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
577 RoutingSerials => C4::Context->preference('RoutingSerials'),
578 relatives_issues_count => $relatives_issues_count,
579 relatives_borrowernumbers => \@relatives,
582 # save stickyduedate to session
583 if ($stickyduedate) {
584 $session->param( 'stickyduedate', $duedatespec );
587 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
588 $template->param( picture => 1 ) if $picture;
590 # get authorised values with type of BOR_NOTES
592 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
595 debt_confirmed => $debt_confirmed,
596 SpecifyDueDate => $duedatespec_allow,
597 CircAutocompl => C4::Context->preference("CircAutocompl"),
598 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
599 export_remove_fields => C4::Context->preference("ExportRemoveFields"),
600 export_with_csv_profile => C4::Context->preference("ExportWithCsvProfile"),
601 canned_bor_notes_loop => $canned_notes,
602 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
603 todaysdate => dt_from_string()->set(hour => 23)->set(minute => 59),
604 inhouse_use_feature => C4::Context->preference("In-House Use"),
605 inhouse_use_forced => C4::Context->preference("In-House Use Force"),
608 output_html_with_http_headers $query, $cookie, $template->output;