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.
30 use C4::Auth qw/:DEFAULT get_session/;
31 use C4::Dates qw/format_date/;
32 use C4::Branch; # GetBranches
33 use C4::Koha; # GetPrinter
42 use C4::Members::Attributes qw(GetBorrowerAttributes);
43 use Koha::Borrower::Debarments qw(GetDebarments IsDebarred);
53 use List::MoreUtils qw/uniq/;
61 my $sessionID = $query->cookie("CGISESSID") ;
62 my $session = get_session($sessionID);
64 # branch and printer are now defined by the userenv
65 # but first we have to check if someone has tried to change them
67 my $branch = $query->param('branch');
69 # update our session so the userenv is updated
70 $session->param('branch', $branch);
71 $session->param('branchname', GetBranchName($branch));
74 my $printer = $query->param('printer');
76 # update our session so the userenv is updated
77 $session->param('branchprinter', $printer);
80 if (!C4::Context->userenv && !$branch){
81 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
82 # no branch set we can't issue
83 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
88 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
90 template_name => 'circ/circulation.tmpl',
94 flagsrequired => { circulate => 'circulate_remaining_permissions' },
98 my $branches = GetBranches();
100 my $findborrower = $query->param('findborrower') || q{};
101 # FIXME dpavlin - FER
102 $findborrower =~ s/^.*%B601983\d\d(\d{10})\d&.*$/S$1/ && warn "JMBAG: $1";
103 $findborrower =~ s|,| |g;
104 my $borrowernumber = $query->param('borrowernumber');
106 $branch = C4::Context->userenv->{'branch'};
107 $printer = C4::Context->userenv->{'branchprinter'};
110 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
111 if (C4::Context->preference("AutoLocation") != 1) {
112 $template->param(ManualLocation => 1);
115 if (C4::Context->preference("DisplayClearScreenButton")) {
116 $template->param(DisplayClearScreenButton => 1);
119 my $barcode = $query->param('barcode') || q{};
120 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
122 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
123 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
124 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
125 my $issueconfirmed = $query->param('issueconfirmed');
126 my $cancelreserve = $query->param('cancelreserve');
127 my $print = $query->param('print') || q{};
128 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
129 my $charges = $query->param('charges') || q{};
131 # Check if stickyduedate is turned off
133 # was stickyduedate loaded from session?
134 if ( $stickyduedate && ! $query->param("stickyduedate") ) {
135 $session->clear( 'stickyduedate' );
136 $stickyduedate = $query->param('stickyduedate');
137 $duedatespec = $query->param('duedatespec');
141 my ($datedue,$invalidduedate);
143 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
144 if($duedatespec_allow){
146 if ($duedatespec =~ C4::Dates->regexp('syspref')) {
147 $datedue = dt_from_string($duedatespec);
150 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
155 our $todaysdate = C4::Dates->new->output('iso');
157 # check and see if we should print
158 if ( $barcode eq '' && $print eq 'maybe' ) {
162 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
163 if ( $barcode eq '' && $charges eq 'yes' ) {
166 borrowernumber => $borrowernumber
170 if ( $print eq 'yes' && $borrowernumber ne '' ) {
171 if ( C4::Context->boolean_preference('printcirculationslips') ) {
172 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
173 NetworkPrint($letter->{content});
175 $query->param( 'borrowernumber', '' );
176 $borrowernumber = '';
180 # STEP 2 : FIND BORROWER
181 # if there is a list of find borrowers....
186 my $borrowers = Search($findborrower, 'cardnumber') || [];
187 if (C4::Context->preference("AddPatronLists")) {
189 "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
191 if (C4::Context->preference("AddPatronLists")=~/code/){
192 my $categories = GetBorrowercategoryList;
193 $categories->[0]->{'first'} = 1;
194 $template->param(categories=>$categories);
197 if ( @$borrowers == 0 ) {
198 $query->param( 'findborrower', '' );
199 $message = "'$findborrower'";
201 elsif ( @$borrowers == 1 ) {
202 $borrowernumber = $borrowers->[0]->{'borrowernumber'};
203 $query->param( 'borrowernumber', $borrowernumber );
204 $query->param( 'barcode', '' );
207 $borrowerslist = $borrowers;
211 # get the borrower information.....
213 if ($borrowernumber) {
214 $borrower = GetMemberDetails( $borrowernumber, 0 );
215 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
217 # Warningdate is the date that the warning starts appearing
218 my ( $today_year, $today_month, $today_day) = Today();
219 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
220 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
221 # Renew day is calculated by adding the enrolment period to today
222 my ( $renew_year, $renew_month, $renew_day);
223 if ($enrol_year*$enrol_month*$enrol_day>0) {
224 ( $renew_year, $renew_month, $renew_day) =
225 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
226 0 , $borrower->{'enrolmentperiod'});
228 # if the expiry date is before today ie they have expired
229 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
230 || Date_to_Days($today_year, $today_month, $today_day )
231 > Date_to_Days($warning_year, $warning_month, $warning_day) )
233 #borrowercard expired, no issues
238 renewaldate => format_date("$renew_year-$renew_month-$renew_day")
241 # check for NotifyBorrowerDeparture
242 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
243 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
244 Date_to_Days( $today_year, $today_month, $today_day ) )
246 # borrower card soon to expire warn librarian
247 $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
249 if (C4::Context->preference('ReturnBeforeExpiry')){
250 $template->param("returnbeforeexpiry" => 1);
255 issuecount => $issue,
259 if ( IsDebarred($borrowernumber) ) {
261 'userdebarred' => $borrower->{debarred},
262 'debarredcomment' => $borrower->{debarredcomment},
265 if ( $borrower->{debarred} ne "9999-12-31" ) {
266 $template->param( 'userdebarreddate' =>
267 C4::Dates::format_date( $borrower->{debarred} ) );
278 # always check for blockers on issuing
279 my ( $error, $question, $alerts ) =
280 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
281 my $blocker = $invalidduedate ? 1 : 0;
283 $template->param( alert => $alerts );
285 # Get the item title for more information
286 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
288 authvalcode_notforloan => C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'}),
290 # Fix for bug 7494: optional checkout-time fallback search for a book
292 if ( $error->{'UNKNOWN_BARCODE'}
293 && C4::Context->preference("itemBarcodeFallbackSearch") )
295 $template->param( FALLBACK => 1 );
297 my $query = "kw=" . $barcode;
298 my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
300 # if multiple hits, offer options to librarian
301 if ( $total_hits > 0 ) {
303 foreach my $hit ( @{$results} ) {
305 TransformMarcToKoha( C4::Context->dbh,
306 C4::Search::new_record_from_zebra('biblioserver',$hit) );
308 # offer all barcodes individually
309 if ( $chosen->{barcode} ) {
310 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
311 my %chosen_single = %{$chosen};
312 $chosen_single{barcode} = $barcode;
313 push( @options, \%chosen_single );
317 $template->param( options => \@options );
321 delete $question->{'DEBT'} if ($debt_confirmed);
322 foreach my $impossible ( keys %$error ) {
324 $impossible => $$error{$impossible},
330 my $confirm_required = 0;
331 unless($issueconfirmed){
332 # Get the item title for more information
333 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
334 $template->{VARS}->{'additional_materials'} = $getmessageiteminfo->{'materials'};
335 $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
337 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
338 foreach my $needsconfirmation ( keys %$question ) {
340 $needsconfirmation => $$question{$needsconfirmation},
341 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
342 getBarcodeMessageIteminfo => $getmessageiteminfo->{'barcode'},
343 NEEDSCONFIRMATION => 1
345 $confirm_required = 1;
348 unless($confirm_required) {
349 AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
354 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
355 $template->param( issuecount => $issue );
358 # reload the borrower info for the sake of reseting the flags.....
359 if ($borrowernumber) {
360 $borrower = GetMemberDetails( $borrowernumber, 0 );
363 ##################################################################################
365 # show all reserves of this borrower, and the position of the reservation ....
366 if ($borrowernumber) {
368 holds_count => Koha::Database->new()->schema()->resultset('Reserve')
369 ->count( { borrowernumber => $borrowernumber } ) );
371 $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
376 my $CGIselectborrower;
377 if ($borrowerslist) {
379 sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
383 push @values, $_->{'borrowernumber'};
384 $labels{ $_->{'borrowernumber'} } =
385 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'} - $_->{'branchcode'}) ... $_->{'address'} ";
387 $CGIselectborrower = CGI::scrolling_list(
388 -name => 'borrowernumber',
390 -id => 'borrowernumber',
393 -ondblclick => 'document.forms[\'mainform\'].submit()',
401 my $flags = $borrower->{'flags'};
402 foreach my $flag ( sort keys %$flags ) {
403 $template->param( flagged=> 1);
404 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
405 if ( $flags->{$flag}->{'noissues'} ) {
409 if ( $flag eq 'GNA' ) {
410 $template->param( gna => 'true' );
412 elsif ( $flag eq 'LOST' ) {
413 $template->param( lost => 'true' );
415 elsif ( $flag eq 'DBARRED' ) {
416 $template->param( dbarred => 'true' );
418 elsif ( $flag eq 'CHARGES' ) {
421 chargesmsg => $flags->{'CHARGES'}->{'message'},
422 chargesamount => $flags->{'CHARGES'}->{'amount'},
423 charges_is_blocker => 1
426 elsif ( $flag eq 'CREDITS' ) {
429 creditsmsg => $flags->{'CREDITS'}->{'message'},
430 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
435 if ( $flag eq 'CHARGES' ) {
438 chargesmsg => $flags->{'CHARGES'}->{'message'},
439 chargesamount => $flags->{'CHARGES'}->{'amount'},
442 elsif ( $flag eq 'CREDITS' ) {
445 creditsmsg => $flags->{'CREDITS'}->{'message'},
446 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
449 elsif ( $flag eq 'ODUES' ) {
452 oduesmsg => $flags->{'ODUES'}->{'message'}
455 my $items = $flags->{$flag}->{'itemlist'};
456 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
457 $template->param( nonreturns => 'true' );
460 elsif ( $flag eq 'NOTES' ) {
463 notesmsg => $flags->{'NOTES'}->{'message'}
469 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
470 $amountold =~ s/^.*\$//; # remove upto the $, if any
472 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
474 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
475 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
476 my $cnt = scalar(@$catcodes);
477 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
478 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
481 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
482 if($lib_messages_loop){ $template->param(flagged => 1 ); }
484 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
485 if($bor_messages_loop){ $template->param(flagged => 1 ); }
487 # Computes full borrower address
489 push @fulladdress, $borrower->{'streetnumber'} if ( $borrower->{'streetnumber'} );
490 push @fulladdress, C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{'streettype'} ) if ( $borrower->{'streettype'} );
491 push @fulladdress, $borrower->{'address'} if ( $borrower->{'address'} );
493 my $fast_cataloging = 0;
494 if (defined getframeworkinfo('FA')) {
498 if (C4::Context->preference('ExtendedPatronAttributes')) {
499 my $attributes = GetBorrowerAttributes($borrowernumber);
501 ExtendedPatronAttributes => 1,
502 extendedattributes => $attributes
506 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
507 my $relatives_issues_count =
508 Koha::Database->new()->schema()->resultset('Issue')
509 ->count( { borrowernumber => \@relatives } );
512 lib_messages_loop => $lib_messages_loop,
513 bor_messages_loop => $bor_messages_loop,
514 all_messages_del => C4::Context->preference('AllowAllMessageDeletion'),
515 findborrower => $findborrower,
516 borrower => $borrower,
517 borrowernumber => $borrowernumber,
519 branchname => GetBranchName($borrower->{'branchcode'}),
521 printername => $printer,
522 firstname => $borrower->{'firstname'},
523 surname => $borrower->{'surname'},
524 showname => $borrower->{'showname'},
525 category_type => $borrower->{'category_type'},
526 was_renewed => $query->param('was_renewed') ? 1 : 0,
527 expiry => format_date($borrower->{'dateexpiry'}),
528 categorycode => $borrower->{'categorycode'},
529 categoryname => $borrower->{description},
530 address => join(' ', @fulladdress),
531 address2 => $borrower->{'address2'},
532 email => $borrower->{'email'},
533 emailpro => $borrower->{'emailpro'},
534 borrowernotes => $borrower->{'borrowernotes'},
535 city => $borrower->{'city'},
536 state => $borrower->{'state'},
537 zipcode => $borrower->{'zipcode'},
538 country => $borrower->{'country'},
539 phone => $borrower->{'phone'} || $borrower->{'mobile'},
540 cardnumber => $borrower->{'cardnumber'},
541 othernames => $borrower->{'othernames'},
542 amountold => $amountold,
544 stickyduedate => $stickyduedate,
545 duedatespec => $duedatespec,
547 CGIselectborrower => $CGIselectborrower,
548 totaldue => sprintf('%.2f', $total),
549 inprocess => $inprocess,
550 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
552 soundon => C4::Context->preference("SoundOn"),
553 fast_cataloging => $fast_cataloging,
554 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
555 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
556 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
557 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
558 RoutingSerials => C4::Context->preference('RoutingSerials'),
559 relatives_issues_count => $relatives_issues_count,
560 relatives_borrowernumbers => \@relatives,
563 # save stickyduedate to session
564 if ($stickyduedate) {
565 $session->param( 'stickyduedate', $duedatespec );
568 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
569 $template->param( picture => 1 ) if $picture;
571 # get authorised values with type of BOR_NOTES
573 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
576 debt_confirmed => $debt_confirmed,
577 SpecifyDueDate => $duedatespec_allow,
578 CircAutocompl => C4::Context->preference("CircAutocompl"),
579 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
580 export_remove_fields => C4::Context->preference("ExportRemoveFields"),
581 export_with_csv_profile => C4::Context->preference("ExportWithCsvProfile"),
582 canned_bor_notes_loop => $canned_notes,
583 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
586 output_html_with_http_headers $query, $cookie, $template->output;