Bug 3186 - invalid or uninstalled SMSSendDriver (or bad number format) causes process...
[koha.git] / circ / circulation.pl
blob8f79f7196917a46d41a287972df4c1f0bde032ef
1 #!/usr/bin/perl
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
15 # version.
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.
25 use strict;
26 use warnings;
27 use CGI;
28 use C4::Output;
29 use C4::Print;
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
34 use C4::Circulation;
35 use C4::Members;
36 use C4::Biblio;
37 use C4::Search;
38 use MARC::Record;
39 use C4::Reserves;
40 use C4::Context;
41 use CGI::Session;
42 use C4::Members::Attributes qw(GetBorrowerAttributes);
43 use Koha::Borrower::Debarments qw(GetDebarments IsDebarred);
44 use Koha::DateUtils;
45 use Koha::Database;
47 use Date::Calc qw(
48 Today
49 Add_Delta_YM
50 Add_Delta_Days
51 Date_to_Days
53 use List::MoreUtils qw/uniq/;
57 # PARAMETERS READING
59 my $query = new CGI;
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');
68 if ($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');
75 if ($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");
84 exit;
88 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
90 template_name => 'circ/circulation.tt',
91 query => $query,
92 type => "intranet",
93 authnotrequired => 0,
94 flagsrequired => { circulate => 'circulate_remaining_permissions' },
98 my $branches = GetBranches();
100 my $findborrower = $query->param('findborrower') || q{};
101 $findborrower =~ s|,| |g;
102 my $borrowernumber = $query->param('borrowernumber');
104 $branch = C4::Context->userenv->{'branch'};
105 $printer = C4::Context->userenv->{'branchprinter'};
108 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
109 if (C4::Context->preference("AutoLocation") != 1) {
110 $template->param(ManualLocation => 1);
113 if (C4::Context->preference("DisplayClearScreenButton")) {
114 $template->param(DisplayClearScreenButton => 1);
117 my $barcode = $query->param('barcode') || q{};
118 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
120 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
121 my $stickyduedate = $query->param('stickyduedate') || $session->param('stickyduedate');
122 my $duedatespec = $query->param('duedatespec') || $session->param('stickyduedate');
123 my $issueconfirmed = $query->param('issueconfirmed');
124 my $cancelreserve = $query->param('cancelreserve');
125 my $print = $query->param('print') || q{};
126 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
127 my $charges = $query->param('charges') || q{};
129 # Check if stickyduedate is turned off
130 if ( $barcode ) {
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');
137 $session->param('auto_renew', $query->param('auto_renew'));
139 else {
140 $session->clear('auto_renew');
143 my ($datedue,$invalidduedate);
145 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
146 if($duedatespec_allow){
147 if ($duedatespec) {
148 if ($duedatespec =~ C4::Dates->regexp('syspref')) {
149 $datedue = dt_from_string($duedatespec);
150 } else {
151 $invalidduedate = 1;
152 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
157 our $todaysdate = C4::Dates->new->output('iso');
159 # check and see if we should print
160 if ( $barcode eq '' && $print eq 'maybe' ) {
161 $print = 'yes';
164 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
165 if ( $barcode eq '' && $charges eq 'yes' ) {
166 $template->param(
167 PAYCHARGES => 'yes',
168 borrowernumber => $borrowernumber
172 if ( $print eq 'yes' && $borrowernumber ne '' ) {
173 if ( C4::Context->boolean_preference('printcirculationslips') ) {
174 my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
175 NetworkPrint($letter->{content});
177 $query->param( 'borrowernumber', '' );
178 $borrowernumber = '';
182 # STEP 2 : FIND BORROWER
183 # if there is a list of find borrowers....
185 my $borrowerslist;
186 my $message;
187 if ($findborrower) {
188 my $borrowers = Search($findborrower, 'cardnumber') || [];
189 if (C4::Context->preference("AddPatronLists")) {
190 $template->param(
191 "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
193 if (C4::Context->preference("AddPatronLists")=~/code/){
194 my $categories = GetBorrowercategoryList;
195 $categories->[0]->{'first'} = 1;
196 $template->param(categories=>$categories);
199 if ( @$borrowers == 0 ) {
200 $query->param( 'findborrower', '' );
201 $message = "'$findborrower'";
203 elsif ( @$borrowers == 1 ) {
204 $borrowernumber = $borrowers->[0]->{'borrowernumber'};
205 $query->param( 'borrowernumber', $borrowernumber );
206 $query->param( 'barcode', '' );
208 else {
209 $borrowerslist = $borrowers;
213 # get the borrower information.....
214 my $borrower;
215 if ($borrowernumber) {
216 $borrower = GetMemberDetails( $borrowernumber, 0 );
217 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
219 # Warningdate is the date that the warning starts appearing
220 my ( $today_year, $today_month, $today_day) = Today();
221 my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
222 my ( $enrol_year, $enrol_month, $enrol_day) = split /-/, $borrower->{'dateenrolled'};
223 # Renew day is calculated by adding the enrolment period to today
224 my ( $renew_year, $renew_month, $renew_day);
225 if ($enrol_year*$enrol_month*$enrol_day>0) {
226 ( $renew_year, $renew_month, $renew_day) =
227 Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
228 0 , $borrower->{'enrolmentperiod'});
230 # if the expiry date is before today ie they have expired
231 if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
232 || Date_to_Days($today_year, $today_month, $today_day )
233 > Date_to_Days($warning_year, $warning_month, $warning_day) )
235 #borrowercard expired, no issues
236 $template->param(
237 flagged => "1",
238 noissues => "1",
239 expired => "1",
240 renewaldate => format_date("$renew_year-$renew_month-$renew_day")
243 # check for NotifyBorrowerDeparture
244 elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
245 Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
246 Date_to_Days( $today_year, $today_month, $today_day ) )
248 # borrower card soon to expire warn librarian
249 $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
250 flagged => "1",);
251 if (C4::Context->preference('ReturnBeforeExpiry')){
252 $template->param("returnbeforeexpiry" => 1);
255 $template->param(
256 overduecount => $od,
257 issuecount => $issue,
258 finetotal => $fines
261 if ( IsDebarred($borrowernumber) ) {
262 $template->param(
263 'userdebarred' => $borrower->{debarred},
264 'debarredcomment' => $borrower->{debarredcomment},
267 if ( $borrower->{debarred} ne "9999-12-31" ) {
268 $template->param( 'userdebarreddate' =>
269 C4::Dates::format_date( $borrower->{debarred} ) );
276 # STEP 3 : ISSUING
279 if ($barcode) {
280 # always check for blockers on issuing
281 my ( $error, $question, $alerts ) =
282 CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
283 my $blocker = $invalidduedate ? 1 : 0;
285 $template->param( alert => $alerts );
287 # Get the item title for more information
288 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
289 $template->param(
290 authvalcode_notforloan => C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'}),
292 # Fix for bug 7494: optional checkout-time fallback search for a book
294 if ( $error->{'UNKNOWN_BARCODE'}
295 && C4::Context->preference("itemBarcodeFallbackSearch") )
297 $template->param( FALLBACK => 1 );
299 my $query = "kw=" . $barcode;
300 my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
302 # if multiple hits, offer options to librarian
303 if ( $total_hits > 0 ) {
304 my @options = ();
305 foreach my $hit ( @{$results} ) {
306 my $chosen =
307 TransformMarcToKoha( C4::Context->dbh,
308 C4::Search::new_record_from_zebra('biblioserver',$hit) );
310 # offer all barcodes individually
311 if ( $chosen->{barcode} ) {
312 foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
313 my %chosen_single = %{$chosen};
314 $chosen_single{barcode} = $barcode;
315 push( @options, \%chosen_single );
319 $template->param( options => \@options );
323 delete $question->{'DEBT'} if ($debt_confirmed);
324 foreach my $impossible ( keys %$error ) {
325 $template->param(
326 $impossible => $$error{$impossible},
327 IMPOSSIBLE => 1
329 $blocker = 1;
331 if( !$blocker ){
332 my $confirm_required = 0;
333 unless($issueconfirmed){
334 # Get the item title for more information
335 my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
336 $template->{VARS}->{'additional_materials'} = $getmessageiteminfo->{'materials'};
337 $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
339 # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
340 foreach my $needsconfirmation ( keys %$question ) {
341 $template->param(
342 $needsconfirmation => $$question{$needsconfirmation},
343 getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
344 getBarcodeMessageIteminfo => $getmessageiteminfo->{'barcode'},
345 NEEDSCONFIRMATION => 1
347 $confirm_required = 1;
350 unless($confirm_required) {
351 AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, $session->param('auto_renew') );
352 $session->clear('auto_renew');
353 $inprocess = 1;
357 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
358 $template->param( issuecount => $issue );
361 # reload the borrower info for the sake of reseting the flags.....
362 if ($borrowernumber) {
363 $borrower = GetMemberDetails( $borrowernumber, 0 );
366 ##################################################################################
367 # BUILD HTML
368 # show all reserves of this borrower, and the position of the reservation ....
369 if ($borrowernumber) {
370 $template->param(
371 holds_count => Koha::Database->new()->schema()->resultset('Reserve')
372 ->count( { borrowernumber => $borrowernumber } ) );
374 $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
377 my @values;
378 my %labels;
379 my $selectborrower;
380 if ($borrowerslist) {
381 foreach (
382 sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
383 } @$borrowerslist
386 push @values, $_->{'borrowernumber'};
387 $labels{ $_->{'borrowernumber'} } =
388 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'} - $_->{'branchcode'}) ... $_->{'address'} ";
390 $selectborrower = {
391 values => \@values,
392 labels => \%labels,
396 #title
397 my $flags = $borrower->{'flags'};
398 foreach my $flag ( sort keys %$flags ) {
399 $template->param( flagged=> 1);
400 $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
401 if ( $flags->{$flag}->{'noissues'} ) {
402 $template->param(
403 noissues => 'true',
405 if ( $flag eq 'GNA' ) {
406 $template->param( gna => 'true' );
408 elsif ( $flag eq 'LOST' ) {
409 $template->param( lost => 'true' );
411 elsif ( $flag eq 'DBARRED' ) {
412 $template->param( dbarred => 'true' );
414 elsif ( $flag eq 'CHARGES' ) {
415 $template->param(
416 charges => 'true',
417 chargesmsg => $flags->{'CHARGES'}->{'message'},
418 chargesamount => $flags->{'CHARGES'}->{'amount'},
419 charges_is_blocker => 1
422 elsif ( $flag eq 'CREDITS' ) {
423 $template->param(
424 credits => 'true',
425 creditsmsg => $flags->{'CREDITS'}->{'message'},
426 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
430 else {
431 if ( $flag eq 'CHARGES' ) {
432 $template->param(
433 charges => 'true',
434 chargesmsg => $flags->{'CHARGES'}->{'message'},
435 chargesamount => $flags->{'CHARGES'}->{'amount'},
438 elsif ( $flag eq 'CREDITS' ) {
439 $template->param(
440 credits => 'true',
441 creditsmsg => $flags->{'CREDITS'}->{'message'},
442 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
445 elsif ( $flag eq 'ODUES' ) {
446 $template->param(
447 odues => 'true',
448 oduesmsg => $flags->{'ODUES'}->{'message'}
451 my $items = $flags->{$flag}->{'itemlist'};
452 if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
453 $template->param( nonreturns => 'true' );
456 elsif ( $flag eq 'NOTES' ) {
457 $template->param(
458 notes => 'true',
459 notesmsg => $flags->{'NOTES'}->{'message'}
465 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
466 $amountold =~ s/^.*\$//; # remove upto the $, if any
468 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
470 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
471 my ( $catcodes, $labels ) = GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
472 my $cnt = scalar(@$catcodes);
473 $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
474 $template->param( 'catcode' => $catcodes->[0]) if $cnt == 1;
477 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
478 if($lib_messages_loop){ $template->param(flagged => 1 ); }
480 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
481 if($bor_messages_loop){ $template->param(flagged => 1 ); }
483 # Computes full borrower address
484 my @fulladdress;
485 push @fulladdress, $borrower->{'streetnumber'} if ( $borrower->{'streetnumber'} );
486 push @fulladdress, C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{'streettype'} ) if ( $borrower->{'streettype'} );
487 push @fulladdress, $borrower->{'address'} if ( $borrower->{'address'} );
489 my $fast_cataloging = 0;
490 if (defined getframeworkinfo('FA')) {
491 $fast_cataloging = 1
494 if (C4::Context->preference('ExtendedPatronAttributes')) {
495 my $attributes = GetBorrowerAttributes($borrowernumber);
496 $template->param(
497 ExtendedPatronAttributes => 1,
498 extendedattributes => $attributes
502 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
503 my $relatives_issues_count =
504 Koha::Database->new()->schema()->resultset('Issue')
505 ->count( { borrowernumber => \@relatives } );
507 $template->param(
508 lib_messages_loop => $lib_messages_loop,
509 bor_messages_loop => $bor_messages_loop,
510 all_messages_del => C4::Context->preference('AllowAllMessageDeletion'),
511 findborrower => $findborrower,
512 borrower => $borrower,
513 borrowernumber => $borrowernumber,
514 branch => $branch,
515 branchname => GetBranchName($borrower->{'branchcode'}),
516 printer => $printer,
517 printername => $printer,
518 firstname => $borrower->{'firstname'},
519 surname => $borrower->{'surname'},
520 showname => $borrower->{'showname'},
521 category_type => $borrower->{'category_type'},
522 was_renewed => $query->param('was_renewed') ? 1 : 0,
523 expiry => format_date($borrower->{'dateexpiry'}),
524 categorycode => $borrower->{'categorycode'},
525 categoryname => $borrower->{description},
526 address => join(' ', @fulladdress),
527 address2 => $borrower->{'address2'},
528 email => $borrower->{'email'},
529 emailpro => $borrower->{'emailpro'},
530 borrowernotes => $borrower->{'borrowernotes'},
531 city => $borrower->{'city'},
532 state => $borrower->{'state'},
533 zipcode => $borrower->{'zipcode'},
534 country => $borrower->{'country'},
535 phone => $borrower->{'phone'},
536 mobile => $borrower->{'mobile'},
537 phonepro => $borrower->{'phonepro'},
538 cardnumber => $borrower->{'cardnumber'},
539 othernames => $borrower->{'othernames'},
540 amountold => $amountold,
541 barcode => $barcode,
542 stickyduedate => $stickyduedate,
543 duedatespec => $duedatespec,
544 message => $message,
545 selectborrower => $selectborrower,
546 totaldue => sprintf('%.2f', $total),
547 inprocess => $inprocess,
548 is_child => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
549 circview => 1,
550 soundon => C4::Context->preference("SoundOn"),
551 fast_cataloging => $fast_cataloging,
552 CircAutoPrintQuickSlip => C4::Context->preference("CircAutoPrintQuickSlip"),
553 activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
554 SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
555 AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
556 RoutingSerials => C4::Context->preference('RoutingSerials'),
557 relatives_issues_count => $relatives_issues_count,
558 relatives_borrowernumbers => \@relatives,
561 # save stickyduedate to session
562 if ($stickyduedate) {
563 $session->param( 'stickyduedate', $duedatespec );
566 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
567 $template->param( picture => 1 ) if $picture;
569 # get authorised values with type of BOR_NOTES
571 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
573 $template->param(
574 debt_confirmed => $debt_confirmed,
575 SpecifyDueDate => $duedatespec_allow,
576 CircAutocompl => C4::Context->preference("CircAutocompl"),
577 AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
578 export_remove_fields => C4::Context->preference("ExportRemoveFields"),
579 export_with_csv_profile => C4::Context->preference("ExportWithCsvProfile"),
580 canned_bor_notes_loop => $canned_notes,
581 debarments => GetDebarments({ borrowernumber => $borrowernumber }),
584 output_html_with_http_headers $query, $cookie, $template->output;