3 # script to execute issuing of books
5 # Copyright 2000-2002 Katipo Communications
6 # copyright 2010 BibLibre
8 # This file is part of Koha.
10 # Koha is free software; you can redistribute it and/or modify it under the
11 # terms of the GNU General Public License as published by the Free Software
12 # Foundation; either version 2 of the License, or (at your option) any later
15 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
16 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License along
20 # with Koha; if not, write to the Free Software Foundation, Inc.,
21 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #use warnings; FIXME - Bug 2505
28 use C4::Auth qw/:DEFAULT get_session/;
29 use C4::Dates qw/format_date/;
30 use C4::Branch; # GetBranches
31 use C4::Koha; # GetPrinter
52 my $sessionID = $query->cookie("CGISESSID") ;
53 my $session = get_session($sessionID);
55 # branch and printer are now defined by the userenv
56 # but first we have to check if someone has tried to change them
58 my $branch = $query->param('branch');
60 # update our session so the userenv is updated
61 $session->param('branch', $branch);
62 $session->param('branchname', GetBranchName($branch));
65 my $printer = $query->param('printer');
67 # update our session so the userenv is updated
68 $session->param('branchprinter', $printer);
71 if (!C4::Context->userenv && !$branch){
72 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
73 # no branch set we can't issue
74 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
79 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
81 template_name => 'circ/circulation.tmpl',
85 flagsrequired => { circulate => 'circulate_remaining_permissions' },
89 my $branches = GetBranches();
91 my @failedrenews = $query->param('failedrenew'); # expected to be itemnumbers
93 for (@failedrenews) { $renew_failed{$_} = 1; }
95 my $findborrower = $query->param('findborrower');
96 $findborrower =~ s|,| |g;
97 my $borrowernumber = $query->param('borrowernumber');
99 $branch = C4::Context->userenv->{'branch'};
100 $printer = C4::Context->userenv->{'branchprinter'};
103 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
104 if (C4::Context->preference("AutoLocation") != 1) {
105 $template->param(ManualLocation => 1);
108 if (C4::Context->preference("DisplayClearScreenButton")) {
109 $template->param(DisplayClearScreenButton => 1);
112 if (C4::Context->preference("UseTablesortForCirc")) {
113 $template->param(UseTablesortForCirc => 1);
116 my $barcode = $query->param('barcode') || '';
117 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
119 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
120 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
121 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
122 my $issueconfirmed = $query->param('issueconfirmed');
123 my $cancelreserve = $query->param('cancelreserve');
124 my $organisation = $query->param('organisations');
125 my $print = $query->param('print');
126 my $newexpiry = $query->param('dateexpiry');
127 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
129 # Check if stickyduedate is turned off
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');
139 my ($datedue,$invalidduedate);
141 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
142 if($duedatespec_allow){
144 if ($duedatespec =~ C4::Dates->regexp('syspref')) {
145 my $tempdate = C4::Dates->new($duedatespec);
146 # if ($tempdate and $tempdate->output('iso') gt C4::Dates->new()->output('iso')) {
147 # # i.e., it has to be later than today/now
148 $datedue = $tempdate;
150 # $invalidduedate = 1;
151 # $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
155 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
160 my $todaysdate = C4::Dates->new->output('iso');
162 # check and see if we should print
163 if ( $barcode eq '' && $print eq 'maybe' ) {
167 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
168 if ( $barcode eq '' && $query->param('charges') eq 'yes' ) {
171 borrowernumber => $borrowernumber
175 if ( $print eq 'yes' && $borrowernumber ne '' ) {
176 printslip( $borrowernumber );
177 $query->param( 'borrowernumber', '' );
178 $borrowernumber = '';
182 # STEP 2 : FIND BORROWER
183 # if there is a list of find borrowers....
188 my ($count, $borrowers) = SearchMember($findborrower, 'cardnumber', 'web');
189 my @borrowers = @$borrowers;
190 if (C4::Context->preference("AddPatronLists")) {
192 "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
194 if (C4::Context->preference("AddPatronLists")=~/code/){
195 my $categories = GetBorrowercategoryList;
196 $categories->[0]->{'first'} = 1;
197 $template->param(categories=>$categories);
200 if ( $#borrowers == -1 ) {
201 $query->param( 'findborrower', '' );
202 $message = "'$findborrower'";
204 elsif ( $#borrowers == 0 ) {
205 $query->param( 'borrowernumber', $borrowers[0]->{'borrowernumber'} );
206 $query->param( 'barcode', '' );
207 $borrowernumber = $borrowers[0]->{'borrowernumber'};
210 $borrowerslist = \@borrowers;
214 # get the borrower information.....
216 if ($borrowernumber) {
217 $borrower = GetMemberDetails( $borrowernumber, 0 );
218 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
220 # Warningdate is the date that the warning starts appearing
221 my ( $today_year, $today_month, $today_day) = Today();
222 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
223 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
224 # Renew day is calculated by adding the enrolment period to today
225 my ( $renew_year, $renew_month, $renew_day);
226 if ($enrol_year*$enrol_month*$enrol_day>0) {
227 ( $renew_year, $renew_month, $renew_day) =
228 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
229 0 , $borrower->{'enrolmentperiod'});
231 # if the expiry date is before today ie they have expired
232 if ( $warning_year*$warning_month*$warning_day==0
233 || Date_to_Days($today_year, $today_month, $today_day )
234 > Date_to_Days($warning_year, $warning_month, $warning_day) )
236 #borrowercard expired, no issues
240 expired => format_date($borrower->{dateexpiry}),
241 renewaldate => format_date("$renew_year-$renew_month-$renew_day")
244 # check for NotifyBorrowerDeparture
245 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
246 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
247 Date_to_Days( $today_year, $today_month, $today_day ) )
249 # borrower card soon to expire warn librarian
250 $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
252 if (C4::Context->preference('ReturnBeforeExpiry')){
253 $template->param("returnbeforeexpiry" => 1);
258 issuecount => $issue,
268 # always check for blockers on issuing
269 my ( $error, $question ) =
270 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
271 my $blocker = $invalidduedate ? 1 : 0;
273 delete $question->{'DEBT'} if ($debt_confirmed);
274 foreach my $impossible ( keys %$error ) {
276 $impossible => $$error{$impossible},
282 my $confirm_required = 0;
283 unless($issueconfirmed){
284 # Get the item title for more information
285 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
286 $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
288 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
289 foreach my $needsconfirmation ( keys %$question ) {
291 $needsconfirmation => $$question{$needsconfirmation},
292 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
293 getBarcodeMessageIteminfo => $getmessageiteminfo->{'barcode'},
294 NEEDSCONFIRMATION => 1
296 $confirm_required = 1;
299 unless($confirm_required) {
300 AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
305 # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue
306 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
307 $template->param( issuecount => $issue );
310 # reload the borrower info for the sake of reseting the flags.....
311 if ($borrowernumber) {
312 $borrower = GetMemberDetails( $borrowernumber, 0 );
315 ##################################################################################
317 # show all reserves of this borrower, and the position of the reservation ....
318 if ($borrowernumber) {
321 # now we show the status of the borrower's reservations
322 my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
324 my @WaitingReserveLoop;
326 foreach my $num_res (@borrowerreserv) {
328 my %getWaitingReserveInfo;
329 my $getiteminfo = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
330 my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
331 my ( $transfertwhen, $transfertfrom, $transfertto ) =
332 GetTransfers( $num_res->{'itemnumber'} );
334 $getreserv{waiting} = 0;
335 $getreserv{transfered} = 0;
336 $getreserv{nottransfered} = 0;
338 $getreserv{reservedate} = format_date( $num_res->{'reservedate'} );
339 $getreserv{reservenumber} = $num_res->{'reservenumber'};
340 $getreserv{title} = $getiteminfo->{'title'};
341 $getreserv{itemtype} = $itemtypeinfo->{'description'};
342 $getreserv{author} = $getiteminfo->{'author'};
343 $getreserv{barcodereserv} = $getiteminfo->{'barcode'};
344 $getreserv{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
345 $getreserv{biblionumber} = $getiteminfo->{'biblionumber'};
346 $getreserv{waitingat} = GetBranchName( $num_res->{'branchcode'} );
347 # check if we have a waiting status for reservations
348 if ( $num_res->{'found'} eq 'W' ) {
349 $getreserv{color} = 'reserved';
350 $getreserv{waiting} = 1;
351 # genarate information displaying only waiting reserves
352 $getWaitingReserveInfo{title} = $getiteminfo->{'title'};
353 $getWaitingReserveInfo{biblionumber} = $getiteminfo->{'biblionumber'};
354 $getWaitingReserveInfo{itemtype} = $itemtypeinfo->{'description'};
355 $getWaitingReserveInfo{author} = $getiteminfo->{'author'};
356 $getWaitingReserveInfo{reservedate} = format_date( $num_res->{'reservedate'} );
357 $getWaitingReserveInfo{waitingat} = GetBranchName( $num_res->{'branchcode'} );
358 $getWaitingReserveInfo{waitinghere} = 1 if $num_res->{'branchcode'} eq $branch;
360 # check transfers with the itemnumber foud in th reservation loop
361 if ($transfertwhen) {
362 $getreserv{color} = 'transfered';
363 $getreserv{transfered} = 1;
364 $getreserv{datesent} = format_date($transfertwhen);
365 $getreserv{frombranch} = GetBranchName($transfertfrom);
366 } elsif ($getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'}) {
367 $getreserv{nottransfered} = 1;
368 $getreserv{nottransferedby} = GetBranchName( $getiteminfo->{'holdingbranch'} );
371 # if we don't have a reserv on item, we put the biblio infos and the waiting position
372 if ( $getiteminfo->{'title'} eq '' ) {
373 my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
375 $getreserv{color} = 'inwait';
376 $getreserv{title} = $getbibinfo->{'title'};
377 $getreserv{nottransfered} = 0;
378 $getreserv{itemtype} = $itemtypeinfo->{'description'};
379 $getreserv{author} = $getbibinfo->{'author'};
380 $getreserv{biblionumber} = $num_res->{'biblionumber'};
382 $getreserv{waitingposition} = $num_res->{'priority'};
383 push( @reservloop, \%getreserv );
385 # if we have a reserve waiting, initiate waitingreserveloop
386 if ($getreserv{waiting} == 1) {
387 push (@WaitingReserveLoop, \%getWaitingReserveInfo)
392 # return result to the template
394 countreserv => scalar @reservloop,
395 reservloop => \@reservloop ,
396 WaitingReserveLoop => \@WaitingReserveLoop,
398 $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
401 # make the issued books table.
402 my $todaysissues = '';
410 # get each issue of the borrower & separate them in todayissues & previous issues
411 my ($issueslist) = GetPendingIssues($borrower->{'borrowernumber'});
412 # split in 2 arrays for today & previous
413 foreach my $it ( @$issueslist ) {
414 my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $it->{'itype'} : $it->{'itemtype'} );
415 # set itemtype per item-level_itype syspref - FIXME this is an ugly hack
416 $it->{'itemtype'} = ( C4::Context->preference( 'item-level_itypes' ) ) ? $it->{'itype'} : $it->{'itemtype'};
418 ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
419 $it->{'itemnumber'}, $borrower->{'borrowernumber'}
421 $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
422 my ($can_renew, $can_renew_error) = CanBookBeRenewed(
423 $borrower->{'borrowernumber'},$it->{'itemnumber'}
425 $it->{"renew_error_${can_renew_error}"} = 1 if defined $can_renew_error;
426 my ( $restype, $reserves ) = CheckReserves( $it->{'itemnumber'} );
427 $it->{'can_renew'} = $can_renew;
428 $it->{'can_confirm'} = !$can_renew && !$restype;
429 $it->{'renew_error'} = $restype;
430 $it->{'checkoutdate'} = C4::Dates->new($it->{'issuedate'},'iso')->output('syspref');
432 $totalprice += $it->{'replacementprice'};
433 $it->{'itemtype'} = $itemtypeinfo->{'description'};
434 $it->{'itemtype_image'} = $itemtypeinfo->{'imageurl'};
435 $it->{'dd'} = format_date($it->{'date_due'});
436 $it->{'displaydate'} = format_date($it->{'issuedate'});
437 $it->{'od'} = ( $it->{'date_due'} lt $todaysdate ) ? 1 : 0 ;
438 ($it->{'author'} eq '') and $it->{'author'} = ' ';
439 $it->{'renew_failed'} = $renew_failed{$it->{'itemnumber'}};
441 if ( $todaysdate eq $it->{'issuedate'} or $todaysdate eq $it->{'lastreneweddate'} ) {
442 push @todaysissues, $it;
444 push @previousissues, $it;
447 if ( C4::Context->preference( "todaysIssuesDefaultSortOrder" ) eq 'asc' ) {
448 @todaysissues = sort { $a->{'timestamp'} cmp $b->{'timestamp'} } @todaysissues;
451 @todaysissues = sort { $b->{'timestamp'} cmp $a->{'timestamp'} } @todaysissues;
453 if ( C4::Context->preference( "previousIssuesDefaultSortOrder" ) eq 'asc' ){
454 @previousissues = sort { $a->{'date_due'} cmp $b->{'date_due'} } @previousissues;
457 @previousissues = sort { $b->{'date_due'} cmp $a->{'date_due'} } @previousissues;
464 my $CGIselectborrower;
465 if ($borrowerslist) {
467 sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
471 push @values, $_->{'borrowernumber'};
472 $labels{ $_->{'borrowernumber'} } =
473 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'}) ... $_->{'address'} ";
475 $CGIselectborrower = CGI::scrolling_list(
476 -name => 'borrowernumber',
478 -id => 'borrowernumber',
481 -ondblclick => 'document.forms[\'mainform\'].submit()',
489 my $flags = $borrower->{'flags'};
490 foreach my $flag ( sort keys %$flags ) {
491 $template->param( flagged=> 1);
492 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
493 if ( $flags->{$flag}->{'noissues'} ) {
498 if ( $flag eq 'GNA' ) {
499 $template->param( gna => 'true' );
501 elsif ( $flag eq 'LOST' ) {
502 $template->param( lost => 'true' );
504 elsif ( $flag eq 'DBARRED' ) {
505 $template->param( dbarred => 'true' );
507 elsif ( $flag eq 'CHARGES' ) {
510 chargesmsg => $flags->{'CHARGES'}->{'message'},
511 chargesamount => $flags->{'CHARGES'}->{'amount'},
512 charges_is_blocker => 1
515 elsif ( $flag eq 'CREDITS' ) {
518 creditsmsg => $flags->{'CREDITS'}->{'message'},
519 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
524 if ( $flag eq 'CHARGES' ) {
528 chargesmsg => $flags->{'CHARGES'}->{'message'},
529 chargesamount => $flags->{'CHARGES'}->{'amount'},
532 elsif ( $flag eq 'CREDITS' ) {
535 creditsmsg => $flags->{'CREDITS'}->{'message'},
536 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
539 elsif ( $flag eq 'ODUES' ) {
543 oduesmsg => $flags->{'ODUES'}->{'message'}
546 my $items = $flags->{$flag}->{'itemlist'};
547 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
548 $template->param( nonreturns => 'true' );
551 elsif ( $flag eq 'NOTES' ) {
555 notesmsg => $flags->{'NOTES'}->{'message'}
561 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
562 $amountold =~ s/^.*\$//; # remove upto the $, if any
564 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
566 if ( $borrower->{'category_type'} eq 'C') {
567 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
568 my $cnt = scalar(@$catcodes);
569 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
570 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
573 my $CGIorganisations;
574 my $member_of_institution;
575 if ( C4::Context->preference("memberofinstitution") ) {
576 my $organisations = get_institutions();
579 foreach my $organisation ( keys %$organisations ) {
580 push @orgs, $organisation;
581 $org_labels{$organisation} = $organisations->{$organisation}->{'surname'};
583 $member_of_institution = 1;
584 $CGIorganisations = CGI::popup_menu(
585 -id => 'organisations',
586 -name => 'organisations',
587 -labels => \%org_labels,
592 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
593 if($lib_messages_loop){ $template->param(flagged => 1 ); }
595 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
596 if($bor_messages_loop){ $template->param(flagged => 1 ); }
598 # Computes full borrower address
599 my (undef, $roadttype_hashref) = &GetRoadTypes();
600 my $address = $borrower->{'streetnumber'}.' '.$roadttype_hashref->{$borrower->{'streettype'}}.' '.$borrower->{'address'};
602 my $fast_cataloging = 0;
603 if (defined getframeworkinfo('FA')) {
608 lib_messages_loop => $lib_messages_loop,
609 bor_messages_loop => $bor_messages_loop,
610 all_messages_del => C4::Context->preference('AllowAllMessageDeletion'),
611 findborrower => $findborrower,
612 borrower => $borrower,
613 borrowernumber => $borrowernumber,
615 branchname => GetBranchName($borrower->{'branchcode'}),
617 printername => $printer,
618 firstname => $borrower->{'firstname'},
619 surname => $borrower->{'surname'},
620 dateexpiry => format_date($newexpiry),
621 expiry => format_date($borrower->{'dateexpiry'}),
622 categorycode => $borrower->{'categorycode'},
623 categoryname => $borrower->{description},
625 address2 => $borrower->{'address2'},
626 email => $borrower->{'email'},
627 emailpro => $borrower->{'emailpro'},
628 borrowernotes => $borrower->{'borrowernotes'},
629 city => $borrower->{'city'},
630 zipcode => $borrower->{'zipcode'},
631 country => $borrower->{'country'},
632 phone => $borrower->{'phone'} || $borrower->{'mobile'},
633 cardnumber => $borrower->{'cardnumber'},
634 amountold => $amountold,
636 stickyduedate => $stickyduedate,
637 duedatespec => $duedatespec,
639 CGIselectborrower => $CGIselectborrower,
640 totalprice => sprintf('%.2f', $totalprice),
641 totaldue => sprintf('%.2f', $total),
642 todayissues => \@todaysissues,
643 previssues => \@previousissues,
644 inprocess => $inprocess,
645 memberofinstution => $member_of_institution,
646 CGIorganisations => $CGIorganisations,
647 is_child => ($borrower->{'category_type'} eq 'C'),
649 soundon => C4::Context->preference("SoundOn"),
650 fast_cataloging => $fast_cataloging,
653 # save stickyduedate to session
654 if ($stickyduedate) {
655 $session->param( 'stickyduedate', $duedatespec );
658 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
659 $template->param( picture => 1 ) if $picture;
661 # get authorised values with type of BOR_NOTES
663 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
666 debt_confirmed => $debt_confirmed,
667 SpecifyDueDate => $duedatespec_allow,
668 CircAutocompl => C4::Context->preference("CircAutocompl"),
669 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
670 dateformat => C4::Context->preference("dateformat"),
671 DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
672 canned_bor_notes_loop => $canned_notes,
674 output_html_with_http_headers $query, $cookie, $template->output;