Bug 11559: Supporting changes for Rancor
[koha.git] / C4 / Circulation.pm
1 package C4::Circulation;
2
3 # Copyright 2000-2002 Katipo Communications
4 # copyright 2010 BibLibre
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21
22 use strict;
23 #use warnings; FIXME - Bug 2505
24 use DateTime;
25 use C4::Context;
26 use C4::Stats;
27 use C4::Reserves;
28 use C4::Biblio;
29 use C4::Items;
30 use C4::Members;
31 use C4::Dates;
32 use C4::Dates qw(format_date);
33 use C4::Accounts;
34 use C4::ItemCirculationAlertPreference;
35 use C4::Message;
36 use C4::Debug;
37 use C4::Branch; # GetBranches
38 use C4::Log; # logaction
39 use C4::Koha qw(
40     GetAuthorisedValueByCode
41     GetAuthValCode
42     GetKohaAuthorisedValueLib
43 );
44 use C4::Overdues qw(CalcFine UpdateFine get_chargeable_units);
45 use C4::RotatingCollections qw(GetCollectionItemBranches);
46 use Algorithm::CheckDigits;
47
48 use Data::Dumper;
49 use Koha::DateUtils;
50 use Koha::Calendar;
51 use Koha::Borrower::Debarments;
52 use Koha::Database;
53 use Carp;
54 use List::MoreUtils qw( uniq );
55 use Date::Calc qw(
56   Today
57   Today_and_Now
58   Add_Delta_YM
59   Add_Delta_DHMS
60   Date_to_Days
61   Day_of_Week
62   Add_Delta_Days
63 );
64 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
65
66 BEGIN {
67         require Exporter;
68     $VERSION = 3.07.00.049;     # for version checking
69         @ISA    = qw(Exporter);
70
71         # FIXME subs that should probably be elsewhere
72         push @EXPORT, qw(
73                 &barcodedecode
74         &LostItem
75         &ReturnLostItem
76         &GetPendingOnSiteCheckouts
77         );
78
79         # subs to deal with issuing a book
80         push @EXPORT, qw(
81                 &CanBookBeIssued
82                 &CanBookBeRenewed
83                 &AddIssue
84                 &AddRenewal
85                 &GetRenewCount
86         &GetSoonestRenewDate
87                 &GetItemIssue
88                 &GetItemIssues
89                 &GetIssuingCharges
90                 &GetIssuingRule
91         &GetBranchBorrowerCircRule
92         &GetBranchItemRule
93                 &GetBiblioIssues
94                 &GetOpenIssue
95                 &AnonymiseIssueHistory
96         &CheckIfIssuedToPatron
97         &IsItemIssued
98         GetTopIssues
99         );
100
101         # subs to deal with returns
102         push @EXPORT, qw(
103                 &AddReturn
104         &MarkIssueReturned
105         );
106
107         # subs to deal with transfers
108         push @EXPORT, qw(
109                 &transferbook
110                 &GetTransfers
111                 &GetTransfersFromTo
112                 &updateWrongTransfer
113                 &DeleteTransfer
114                 &IsBranchTransferAllowed
115                 &CreateBranchTransferLimit
116                 &DeleteBranchTransferLimits
117         &TransferSlip
118         );
119
120     # subs to deal with offline circulation
121     push @EXPORT, qw(
122       &GetOfflineOperations
123       &GetOfflineOperation
124       &AddOfflineOperation
125       &DeleteOfflineOperation
126       &ProcessOfflineOperation
127     );
128 }
129
130 =head1 NAME
131
132 C4::Circulation - Koha circulation module
133
134 =head1 SYNOPSIS
135
136 use C4::Circulation;
137
138 =head1 DESCRIPTION
139
140 The functions in this module deal with circulation, issues, and
141 returns, as well as general information about the library.
142 Also deals with stocktaking.
143
144 =head1 FUNCTIONS
145
146 =head2 barcodedecode
147
148   $str = &barcodedecode($barcode, [$filter]);
149
150 Generic filter function for barcode string.
151 Called on every circ if the System Pref itemBarcodeInputFilter is set.
152 Will do some manipulation of the barcode for systems that deliver a barcode
153 to circulation.pl that differs from the barcode stored for the item.
154 For proper functioning of this filter, calling the function on the 
155 correct barcode string (items.barcode) should return an unaltered barcode.
156
157 The optional $filter argument is to allow for testing or explicit 
158 behavior that ignores the System Pref.  Valid values are the same as the 
159 System Pref options.
160
161 =cut
162
163 # FIXME -- the &decode fcn below should be wrapped into this one.
164 # FIXME -- these plugins should be moved out of Circulation.pm
165 #
166 sub barcodedecode {
167     my ($barcode, $filter) = @_;
168     my $branch = C4::Branch::mybranch();
169     $filter = C4::Context->preference('itemBarcodeInputFilter') unless $filter;
170     $filter or return $barcode;     # ensure filter is defined, else return untouched barcode
171         if ($filter eq 'whitespace') {
172                 $barcode =~ s/\s//g;
173         } elsif ($filter eq 'cuecat') {
174                 chomp($barcode);
175             my @fields = split( /\./, $barcode );
176             my @results = map( decode($_), @fields[ 1 .. $#fields ] );
177             ($#results == 2) and return $results[2];
178         } elsif ($filter eq 'T-prefix') {
179                 if ($barcode =~ /^[Tt](\d)/) {
180                         (defined($1) and $1 eq '0') and return $barcode;
181             $barcode = substr($barcode, 2) + 0;     # FIXME: probably should be substr($barcode, 1)
182                 }
183         return sprintf("T%07d", $barcode);
184         # FIXME: $barcode could be "T1", causing warning: substr outside of string
185         # Why drop the nonzero digit after the T?
186         # Why pass non-digits (or empty string) to "T%07d"?
187         } elsif ($filter eq 'libsuite8') {
188                 unless($barcode =~ m/^($branch)-/i){    #if barcode starts with branch code its in Koha style. Skip it.
189                         if($barcode =~ m/^(\d)/i){      #Some barcodes even start with 0's & numbers and are assumed to have b as the item type in the libsuite8 software
190                                 $barcode =~ s/^[0]*(\d+)$/$branch-b-$1/i;
191                         }else{
192                                 $barcode =~ s/^(\D+)[0]*(\d+)$/$branch-$1-$2/i;
193                         }
194                 }
195     } elsif ($filter eq 'EAN13') {
196         my $ean = CheckDigits('ean');
197         if ( $ean->is_valid($barcode) ) {
198             #$barcode = sprintf('%013d',$barcode); # this doesn't work on 32-bit systems
199             $barcode = '0' x ( 13 - length($barcode) ) . $barcode;
200         } else {
201             warn "# [$barcode] not valid EAN-13/UPC-A\n";
202         }
203         }
204     return $barcode;    # return barcode, modified or not
205 }
206
207 =head2 decode
208
209   $str = &decode($chunk);
210
211 Decodes a segment of a string emitted by a CueCat barcode scanner and
212 returns it.
213
214 FIXME: Should be replaced with Barcode::Cuecat from CPAN
215 or Javascript based decoding on the client side.
216
217 =cut
218
219 sub decode {
220     my ($encoded) = @_;
221     my $seq =
222       'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
223     my @s = map { index( $seq, $_ ); } split( //, $encoded );
224     my $l = ( $#s + 1 ) % 4;
225     if ($l) {
226         if ( $l == 1 ) {
227             # warn "Error: Cuecat decode parsing failed!";
228             return;
229         }
230         $l = 4 - $l;
231         $#s += $l;
232     }
233     my $r = '';
234     while ( $#s >= 0 ) {
235         my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
236         $r .=
237             chr( ( $n >> 16 ) ^ 67 )
238          .chr( ( $n >> 8 & 255 ) ^ 67 )
239          .chr( ( $n & 255 ) ^ 67 );
240         @s = @s[ 4 .. $#s ];
241     }
242     $r = substr( $r, 0, length($r) - $l );
243     return $r;
244 }
245
246 =head2 transferbook
247
248   ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, 
249                                             $barcode, $ignore_reserves);
250
251 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
252
253 C<$newbranch> is the code for the branch to which the item should be transferred.
254
255 C<$barcode> is the barcode of the item to be transferred.
256
257 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
258 Otherwise, if an item is reserved, the transfer fails.
259
260 Returns three values:
261
262 =over
263
264 =item $dotransfer 
265
266 is true if the transfer was successful.
267
268 =item $messages
269
270 is a reference-to-hash which may have any of the following keys:
271
272 =over
273
274 =item C<BadBarcode>
275
276 There is no item in the catalog with the given barcode. The value is C<$barcode>.
277
278 =item C<IsPermanent>
279
280 The item's home branch is permanent. This doesn't prevent the item from being transferred, though. The value is the code of the item's home branch.
281
282 =item C<DestinationEqualsHolding>
283
284 The item is already at the branch to which it is being transferred. The transfer is nonetheless considered to have failed. The value should be ignored.
285
286 =item C<WasReturned>
287
288 The item was on loan, and C<&transferbook> automatically returned it before transferring it. The value is the borrower number of the patron who had the item.
289
290 =item C<ResFound>
291
292 The item was reserved. The value is a reference-to-hash whose keys are fields from the reserves table of the Koha database, and C<biblioitemnumber>. It also has the key C<ResFound>, whose value is either C<Waiting> or C<Reserved>.
293
294 =item C<WasTransferred>
295
296 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
297
298 =back
299
300 =back
301
302 =cut
303
304 sub transferbook {
305     my ( $tbr, $barcode, $ignoreRs ) = @_;
306     my $messages;
307     my $dotransfer      = 1;
308     my $branches        = GetBranches();
309     my $itemnumber = GetItemnumberFromBarcode( $barcode );
310     my $issue      = GetItemIssue($itemnumber);
311     my $biblio = GetBiblioFromItemNumber($itemnumber);
312
313     # bad barcode..
314     if ( not $itemnumber ) {
315         $messages->{'BadBarcode'} = $barcode;
316         $dotransfer = 0;
317     }
318
319     # get branches of book...
320     my $hbr = $biblio->{'homebranch'};
321     my $fbr = $biblio->{'holdingbranch'};
322
323     # if using Branch Transfer Limits
324     if ( C4::Context->preference("UseBranchTransferLimits") == 1 ) {
325         if ( C4::Context->preference("item-level_itypes") && C4::Context->preference("BranchTransferLimitsType") eq 'itemtype' ) {
326             if ( ! IsBranchTransferAllowed( $tbr, $fbr, $biblio->{'itype'} ) ) {
327                 $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{'itype'};
328                 $dotransfer = 0;
329             }
330         } elsif ( ! IsBranchTransferAllowed( $tbr, $fbr, $biblio->{ C4::Context->preference("BranchTransferLimitsType") } ) ) {
331             $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{ C4::Context->preference("BranchTransferLimitsType") };
332             $dotransfer = 0;
333         }
334     }
335
336     # if is permanent...
337     if ( $hbr && $branches->{$hbr}->{'PE'} ) {
338         $messages->{'IsPermanent'} = $hbr;
339         $dotransfer = 0;
340     }
341
342     # can't transfer book if is already there....
343     if ( $fbr eq $tbr ) {
344         $messages->{'DestinationEqualsHolding'} = 1;
345         $dotransfer = 0;
346     }
347
348     # check if it is still issued to someone, return it...
349     if ($issue->{borrowernumber}) {
350         AddReturn( $barcode, $fbr );
351         $messages->{'WasReturned'} = $issue->{borrowernumber};
352     }
353
354     # find reserves.....
355     # That'll save a database query.
356     my ( $resfound, $resrec, undef ) =
357       CheckReserves( $itemnumber );
358     if ( $resfound and not $ignoreRs ) {
359         $resrec->{'ResFound'} = $resfound;
360
361         #         $messages->{'ResFound'} = $resrec;
362         $dotransfer = 1;
363     }
364
365     #actually do the transfer....
366     if ($dotransfer) {
367         ModItemTransfer( $itemnumber, $fbr, $tbr );
368
369         # don't need to update MARC anymore, we do it in batch now
370         $messages->{'WasTransfered'} = 1;
371
372     }
373     ModDateLastSeen( $itemnumber );
374     return ( $dotransfer, $messages, $biblio );
375 }
376
377
378 sub TooMany {
379     my $borrower        = shift;
380     my $biblionumber = shift;
381         my $item                = shift;
382     my $params = shift;
383     my $onsite_checkout = $params->{onsite_checkout} || 0;
384     my $cat_borrower    = $borrower->{'categorycode'};
385     my $dbh             = C4::Context->dbh;
386         my $branch;
387         # Get which branchcode we need
388         $branch = _GetCircControlBranch($item,$borrower);
389         my $type = (C4::Context->preference('item-level_itypes')) 
390                         ? $item->{'itype'}         # item-level
391                         : $item->{'itemtype'};     # biblio-level
392  
393     # given branch, patron category, and item type, determine
394     # applicable issuing rule
395     my $issuing_rule = GetIssuingRule($cat_borrower, $type, $branch);
396
397     # if a rule is found and has a loan limit set, count
398     # how many loans the patron already has that meet that
399     # rule
400     if (defined($issuing_rule) and defined($issuing_rule->{'maxissueqty'})) {
401         my @bind_params;
402         my $count_query = q|
403             SELECT COUNT(*) AS total, COALESCE(SUM(onsite_checkout), 0) AS onsite_checkouts
404             FROM issues
405             JOIN items USING (itemnumber)
406         |;
407
408         my $rule_itemtype = $issuing_rule->{itemtype};
409         if ($rule_itemtype eq "*") {
410             # matching rule has the default item type, so count only
411             # those existing loans that don't fall under a more
412             # specific rule
413             if (C4::Context->preference('item-level_itypes')) {
414                 $count_query .= " WHERE items.itype NOT IN (
415                                     SELECT itemtype FROM issuingrules
416                                     WHERE branchcode = ?
417                                     AND   (categorycode = ? OR categorycode = ?)
418                                     AND   itemtype <> '*'
419                                   ) ";
420             } else { 
421                 $count_query .= " JOIN  biblioitems USING (biblionumber) 
422                                   WHERE biblioitems.itemtype NOT IN (
423                                     SELECT itemtype FROM issuingrules
424                                     WHERE branchcode = ?
425                                     AND   (categorycode = ? OR categorycode = ?)
426                                     AND   itemtype <> '*'
427                                   ) ";
428             }
429             push @bind_params, $issuing_rule->{branchcode};
430             push @bind_params, $issuing_rule->{categorycode};
431             push @bind_params, $cat_borrower;
432         } else {
433             # rule has specific item type, so count loans of that
434             # specific item type
435             if (C4::Context->preference('item-level_itypes')) {
436                 $count_query .= " WHERE items.itype = ? ";
437             } else { 
438                 $count_query .= " JOIN  biblioitems USING (biblionumber) 
439                                   WHERE biblioitems.itemtype= ? ";
440             }
441             push @bind_params, $type;
442         }
443
444         $count_query .= " AND borrowernumber = ? ";
445         push @bind_params, $borrower->{'borrowernumber'};
446         my $rule_branch = $issuing_rule->{branchcode};
447         if ($rule_branch ne "*") {
448             if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
449                 $count_query .= " AND issues.branchcode = ? ";
450                 push @bind_params, $branch;
451             } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
452                 ; # if branch is the patron's home branch, then count all loans by patron
453             } else {
454                 $count_query .= " AND items.homebranch = ? ";
455                 push @bind_params, $branch;
456             }
457         }
458
459         my ( $checkout_count, $onsite_checkout_count ) = $dbh->selectrow_array( $count_query, {}, @bind_params );
460
461         my $max_checkouts_allowed = $issuing_rule->{maxissueqty};
462         my $max_onsite_checkouts_allowed = $issuing_rule->{maxonsiteissueqty};
463
464         if ( $onsite_checkout ) {
465             if ( $onsite_checkout_count >= $max_onsite_checkouts_allowed )  {
466                 return {
467                     reason => 'TOO_MANY_ONSITE_CHECKOUTS',
468                     count => $onsite_checkout_count,
469                     max_allowed => $max_onsite_checkouts_allowed,
470                 }
471             }
472         }
473         if ( C4::Context->preference('ConsiderOnSiteCheckoutsAsNormalCheckouts') ) {
474             if ( $checkout_count >= $max_checkouts_allowed ) {
475                 return {
476                     reason => 'TOO_MANY_CHECKOUTS',
477                     count => $checkout_count,
478                     max_allowed => $max_checkouts_allowed,
479                 };
480             }
481         } elsif ( not $onsite_checkout ) {
482             if ( $checkout_count - $onsite_checkout_count >= $max_checkouts_allowed )  {
483                 return {
484                     reason => 'TOO_MANY_CHECKOUTS',
485                     count => $checkout_count - $onsite_checkout_count,
486                     max_allowed => $max_checkouts_allowed,
487                 };
488             }
489         }
490     }
491
492     # Now count total loans against the limit for the branch
493     my $branch_borrower_circ_rule = GetBranchBorrowerCircRule($branch, $cat_borrower);
494     if (defined($branch_borrower_circ_rule->{maxissueqty})) {
495         my @bind_params = ();
496         my $branch_count_query = q|
497             SELECT COUNT(*) AS total, COALESCE(SUM(onsite_checkout), 0) AS onsite_checkouts
498             FROM issues
499             JOIN items USING (itemnumber)
500             WHERE borrowernumber = ?
501         |;
502         push @bind_params, $borrower->{borrowernumber};
503
504         if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
505             $branch_count_query .= " AND issues.branchcode = ? ";
506             push @bind_params, $branch;
507         } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
508             ; # if branch is the patron's home branch, then count all loans by patron
509         } else {
510             $branch_count_query .= " AND items.homebranch = ? ";
511             push @bind_params, $branch;
512         }
513         my ( $checkout_count, $onsite_checkout_count ) = $dbh->selectrow_array( $branch_count_query, {}, @bind_params );
514         my $max_checkouts_allowed = $branch_borrower_circ_rule->{maxissueqty};
515         my $max_onsite_checkouts_allowed = $branch_borrower_circ_rule->{maxonsiteissueqty};
516
517         if ( $onsite_checkout ) {
518             if ( $onsite_checkout_count >= $max_onsite_checkouts_allowed )  {
519                 return {
520                     reason => 'TOO_MANY_ONSITE_CHECKOUTS',
521                     count => $onsite_checkout_count,
522                     max_allowed => $max_onsite_checkouts_allowed,
523                 }
524             }
525         }
526         if ( C4::Context->preference('ConsiderOnSiteCheckoutsAsNormalCheckouts') ) {
527             if ( $checkout_count >= $max_checkouts_allowed ) {
528                 return {
529                     reason => 'TOO_MANY_CHECKOUTS',
530                     count => $checkout_count,
531                     max_allowed => $max_checkouts_allowed,
532                 };
533             }
534         } elsif ( not $onsite_checkout ) {
535             if ( $checkout_count - $onsite_checkout_count >= $max_checkouts_allowed )  {
536                 return {
537                     reason => 'TOO_MANY_CHECKOUTS',
538                     count => $checkout_count - $onsite_checkout_count,
539                     max_allowed => $max_checkouts_allowed,
540                 };
541             }
542         }
543     }
544
545     # OK, the patron can issue !!!
546     return;
547 }
548
549 =head2 itemissues
550
551   @issues = &itemissues($biblioitemnumber, $biblio);
552
553 Looks up information about who has borrowed the bookZ<>(s) with the
554 given biblioitemnumber.
555
556 C<$biblio> is ignored.
557
558 C<&itemissues> returns an array of references-to-hash. The keys
559 include the fields from the C<items> table in the Koha database.
560 Additional keys include:
561
562 =over 4
563
564 =item C<date_due>
565
566 If the item is currently on loan, this gives the due date.
567
568 If the item is not on loan, then this is either "Available" or
569 "Cancelled", if the item has been withdrawn.
570
571 =item C<card>
572
573 If the item is currently on loan, this gives the card number of the
574 patron who currently has the item.
575
576 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
577
578 These give the timestamp for the last three times the item was
579 borrowed.
580
581 =item C<card0>, C<card1>, C<card2>
582
583 The card number of the last three patrons who borrowed this item.
584
585 =item C<borrower0>, C<borrower1>, C<borrower2>
586
587 The borrower number of the last three patrons who borrowed this item.
588
589 =back
590
591 =cut
592
593 #'
594 sub itemissues {
595     my ( $bibitem, $biblio ) = @_;
596     my $dbh = C4::Context->dbh;
597     my $sth =
598       $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
599       || die $dbh->errstr;
600     my $i = 0;
601     my @results;
602
603     $sth->execute($bibitem) || die $sth->errstr;
604
605     while ( my $data = $sth->fetchrow_hashref ) {
606
607         # Find out who currently has this item.
608         # FIXME - Wouldn't it be better to do this as a left join of
609         # some sort? Currently, this code assumes that if
610         # fetchrow_hashref() fails, then the book is on the shelf.
611         # fetchrow_hashref() can fail for any number of reasons (e.g.,
612         # database server crash), not just because no items match the
613         # search criteria.
614         my $sth2 = $dbh->prepare(
615             "SELECT * FROM issues
616                 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
617                 WHERE itemnumber = ?
618             "
619         );
620
621         $sth2->execute( $data->{'itemnumber'} );
622         if ( my $data2 = $sth2->fetchrow_hashref ) {
623             $data->{'date_due'} = $data2->{'date_due'};
624             $data->{'card'}     = $data2->{'cardnumber'};
625             $data->{'borrower'} = $data2->{'borrowernumber'};
626         }
627         else {
628             $data->{'date_due'} = ($data->{'withdrawn'} eq '1') ? 'Cancelled' : 'Available';
629         }
630
631
632         # Find the last 3 people who borrowed this item.
633         $sth2 = $dbh->prepare(
634             "SELECT * FROM old_issues
635                 LEFT JOIN borrowers ON  issues.borrowernumber = borrowers.borrowernumber
636                 WHERE itemnumber = ?
637                 ORDER BY returndate DESC,timestamp DESC"
638         );
639
640         $sth2->execute( $data->{'itemnumber'} );
641         for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
642         {    # FIXME : error if there is less than 3 pple borrowing this item
643             if ( my $data2 = $sth2->fetchrow_hashref ) {
644                 $data->{"timestamp$i2"} = $data2->{'timestamp'};
645                 $data->{"card$i2"}      = $data2->{'cardnumber'};
646                 $data->{"borrower$i2"}  = $data2->{'borrowernumber'};
647             }    # if
648         }    # for
649
650         $results[$i] = $data;
651         $i++;
652     }
653
654     return (@results);
655 }
656
657 =head2 CanBookBeIssued
658
659   ( $issuingimpossible, $needsconfirmation ) =  CanBookBeIssued( $borrower, 
660                       $barcode, $duedatespec, $inprocess, $ignore_reserves );
661
662 Check if a book can be issued.
663
664 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
665
666 =over 4
667
668 =item C<$borrower> hash with borrower informations (from GetMember or GetMemberDetails)
669
670 =item C<$barcode> is the bar code of the book being issued.
671
672 =item C<$duedatespec> is a C4::Dates object.
673
674 =item C<$inprocess> boolean switch
675 =item C<$ignore_reserves> boolean switch
676
677 =back
678
679 Returns :
680
681 =over 4
682
683 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
684 Possible values are :
685
686 =back
687
688 =head3 INVALID_DATE 
689
690 sticky due date is invalid
691
692 =head3 GNA
693
694 borrower gone with no address
695
696 =head3 CARD_LOST
697
698 borrower declared it's card lost
699
700 =head3 DEBARRED
701
702 borrower debarred
703
704 =head3 UNKNOWN_BARCODE
705
706 barcode unknown
707
708 =head3 NOT_FOR_LOAN
709
710 item is not for loan
711
712 =head3 WTHDRAWN
713
714 item withdrawn.
715
716 =head3 RESTRICTED
717
718 item is restricted (set by ??)
719
720 C<$needsconfirmation> a reference to a hash. It contains reasons why the loan 
721 could be prevented, but ones that can be overriden by the operator.
722
723 Possible values are :
724
725 =head3 DEBT
726
727 borrower has debts.
728
729 =head3 RENEW_ISSUE
730
731 renewing, not issuing
732
733 =head3 ISSUED_TO_ANOTHER
734
735 issued to someone else.
736
737 =head3 RESERVED
738
739 reserved for someone else.
740
741 =head3 INVALID_DATE
742
743 sticky due date is invalid or due date in the past
744
745 =head3 TOO_MANY
746
747 if the borrower borrows to much things
748
749 =cut
750
751 sub CanBookBeIssued {
752     my ( $borrower, $barcode, $duedate, $inprocess, $ignore_reserves, $params ) = @_;
753     my %needsconfirmation;    # filled with problems that needs confirmations
754     my %issuingimpossible;    # filled with problems that causes the issue to be IMPOSSIBLE
755     my %alerts;               # filled with messages that shouldn't stop issuing, but the librarian should be aware of.
756
757     my $onsite_checkout = $params->{onsite_checkout} || 0;
758
759     my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
760     my $issue = GetItemIssue($item->{itemnumber});
761         my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
762         $item->{'itemtype'}=$item->{'itype'}; 
763     my $dbh             = C4::Context->dbh;
764
765     # MANDATORY CHECKS - unless item exists, nothing else matters
766     unless ( $item->{barcode} ) {
767         $issuingimpossible{UNKNOWN_BARCODE} = 1;
768     }
769         return ( \%issuingimpossible, \%needsconfirmation ) if %issuingimpossible;
770
771     #
772     # DUE DATE is OK ? -- should already have checked.
773     #
774     if ($duedate && ref $duedate ne 'DateTime') {
775         $duedate = dt_from_string($duedate);
776     }
777     my $now = DateTime->now( time_zone => C4::Context->tz() );
778     unless ( $duedate ) {
779         my $issuedate = $now->clone();
780
781         my $branch = _GetCircControlBranch($item,$borrower);
782         my $itype = ( C4::Context->preference('item-level_itypes') ) ? $item->{'itype'} : $biblioitem->{'itemtype'};
783         $duedate = CalcDateDue( $issuedate, $itype, $branch, $borrower );
784
785         # Offline circ calls AddIssue directly, doesn't run through here
786         #  So issuingimpossible should be ok.
787     }
788     if ($duedate) {
789         my $today = $now->clone();
790         $today->truncate( to => 'minute');
791         if (DateTime->compare($duedate,$today) == -1 ) { # duedate cannot be before now
792             $needsconfirmation{INVALID_DATE} = output_pref($duedate);
793         }
794     } else {
795             $issuingimpossible{INVALID_DATE} = output_pref($duedate);
796     }
797
798     #
799     # BORROWER STATUS
800     #
801     if ( $borrower->{'category_type'} eq 'X' && (  $item->{barcode}  )) { 
802         # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1  .
803         &UpdateStats({
804                      branch => C4::Context->userenv->{'branch'},
805                      type => 'localuse',
806                      itemnumber => $item->{'itemnumber'},
807                      itemtype => $item->{'itemtype'},
808                      borrowernumber => $borrower->{'borrowernumber'},
809                      ccode => $item->{'ccode'}}
810                     );
811         ModDateLastSeen( $item->{'itemnumber'} );
812         return( { STATS => 1 }, {});
813     }
814     if ( $borrower->{flags}->{GNA} ) {
815         $issuingimpossible{GNA} = 1;
816     }
817     if ( $borrower->{flags}->{'LOST'} ) {
818         $issuingimpossible{CARD_LOST} = 1;
819     }
820     if ( $borrower->{flags}->{'DBARRED'} ) {
821         $issuingimpossible{DEBARRED} = 1;
822     }
823     if ( !defined $borrower->{dateexpiry} || $borrower->{'dateexpiry'} eq '0000-00-00') {
824         $issuingimpossible{EXPIRED} = 1;
825     } else {
826         my $expiry_dt = dt_from_string( $borrower->{dateexpiry}, 'sql', 'floating' );
827         $expiry_dt->truncate( to => 'day');
828         my $today = $now->clone()->truncate(to => 'day');
829         $today->set_time_zone( 'floating' );
830         if ( DateTime->compare($today, $expiry_dt) == 1 ) {
831             $issuingimpossible{EXPIRED} = 1;
832         }
833     }
834
835     #
836     # BORROWER STATUS
837     #
838
839     # DEBTS
840     my ($balance, $non_issue_charges, $other_charges) =
841       C4::Members::GetMemberAccountBalance( $borrower->{'borrowernumber'} );
842     my $amountlimit = C4::Context->preference("noissuescharge");
843     my $allowfineoverride = C4::Context->preference("AllowFineOverride");
844     my $allfinesneedoverride = C4::Context->preference("AllFinesNeedOverride");
845     if ( C4::Context->preference("IssuingInProcess") ) {
846         if ( $non_issue_charges > $amountlimit && !$inprocess && !$allowfineoverride) {
847             $issuingimpossible{DEBT} = sprintf( "%.2f", $non_issue_charges );
848         } elsif ( $non_issue_charges > $amountlimit && !$inprocess && $allowfineoverride) {
849             $needsconfirmation{DEBT} = sprintf( "%.2f", $non_issue_charges );
850         } elsif ( $allfinesneedoverride && $non_issue_charges > 0 && $non_issue_charges <= $amountlimit && !$inprocess ) {
851             $needsconfirmation{DEBT} = sprintf( "%.2f", $non_issue_charges );
852         }
853     }
854     else {
855         if ( $non_issue_charges > $amountlimit && $allowfineoverride ) {
856             $needsconfirmation{DEBT} = sprintf( "%.2f", $non_issue_charges );
857         } elsif ( $non_issue_charges > $amountlimit && !$allowfineoverride) {
858             $issuingimpossible{DEBT} = sprintf( "%.2f", $non_issue_charges );
859         } elsif ( $non_issue_charges > 0 && $allfinesneedoverride ) {
860             $needsconfirmation{DEBT} = sprintf( "%.2f", $non_issue_charges );
861         }
862     }
863     if ($balance > 0 && $other_charges > 0) {
864         $alerts{OTHER_CHARGES} = sprintf( "%.2f", $other_charges );
865     }
866
867     my ($blocktype, $count) = C4::Members::IsMemberBlocked($borrower->{'borrowernumber'});
868     if ($blocktype == -1) {
869         ## patron has outstanding overdue loans
870             if ( C4::Context->preference("OverduesBlockCirc") eq 'block'){
871                 $issuingimpossible{USERBLOCKEDOVERDUE} = $count;
872             }
873             elsif ( C4::Context->preference("OverduesBlockCirc") eq 'confirmation'){
874                 $needsconfirmation{USERBLOCKEDOVERDUE} = $count;
875             }
876     } elsif($blocktype == 1) {
877         # patron has accrued fine days or has a restriction. $count is a date
878         if ($count eq '9999-12-31') {
879             $issuingimpossible{USERBLOCKEDNOENDDATE} = $count;
880         }
881         else {
882             $issuingimpossible{USERBLOCKEDWITHENDDATE} = $count;
883         }
884     }
885
886 #
887     # JB34 CHECKS IF BORROWERS DON'T HAVE ISSUE TOO MANY BOOKS
888     #
889     my $toomany = TooMany( $borrower, $item->{biblionumber}, $item, { onsite_checkout => $onsite_checkout } );
890     # if TooMany max_allowed returns 0 the user doesn't have permission to check out this book
891     if ( $toomany ) {
892         if ( $toomany->{max_allowed} == 0 ) {
893             $needsconfirmation{PATRON_CANT} = 1;
894         }
895         if ( C4::Context->preference("AllowTooManyOverride") ) {
896             $needsconfirmation{TOO_MANY} = $toomany->{reason};
897             $needsconfirmation{current_loan_count} = $toomany->{count};
898             $needsconfirmation{max_loans_allowed} = $toomany->{max_allowed};
899         } else {
900             $needsconfirmation{TOO_MANY} = $toomany->{reason};
901             $issuingimpossible{current_loan_count} = $toomany->{count};
902             $issuingimpossible{max_loans_allowed} = $toomany->{max_allowed};
903         }
904     }
905
906     #
907     # ITEM CHECKING
908     #
909     if ( $item->{'notforloan'} )
910     {
911         if(!C4::Context->preference("AllowNotForLoanOverride")){
912             $issuingimpossible{NOT_FOR_LOAN} = 1;
913             $issuingimpossible{item_notforloan} = $item->{'notforloan'};
914         }else{
915             $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
916             $needsconfirmation{item_notforloan} = $item->{'notforloan'};
917         }
918     }
919     else {
920         # we have to check itemtypes.notforloan also
921         if (C4::Context->preference('item-level_itypes')){
922             # this should probably be a subroutine
923             my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
924             $sth->execute($item->{'itemtype'});
925             my $notforloan=$sth->fetchrow_hashref();
926             if ($notforloan->{'notforloan'}) {
927                 if (!C4::Context->preference("AllowNotForLoanOverride")) {
928                     $issuingimpossible{NOT_FOR_LOAN} = 1;
929                     $issuingimpossible{itemtype_notforloan} = $item->{'itype'};
930                 } else {
931                     $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
932                     $needsconfirmation{itemtype_notforloan} = $item->{'itype'};
933                 }
934             }
935         }
936         elsif ($biblioitem->{'notforloan'} == 1){
937             if (!C4::Context->preference("AllowNotForLoanOverride")) {
938                 $issuingimpossible{NOT_FOR_LOAN} = 1;
939                 $issuingimpossible{itemtype_notforloan} = $biblioitem->{'itemtype'};
940             } else {
941                 $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
942                 $needsconfirmation{itemtype_notforloan} = $biblioitem->{'itemtype'};
943             }
944         }
945     }
946     if ( $item->{'withdrawn'} && $item->{'withdrawn'} > 0 )
947     {
948         $issuingimpossible{WTHDRAWN} = 1;
949     }
950     if (   $item->{'restricted'}
951         && $item->{'restricted'} == 1 )
952     {
953         $issuingimpossible{RESTRICTED} = 1;
954     }
955     if ( $item->{'itemlost'} && C4::Context->preference("IssueLostItem") ne 'nothing' ) {
956         my $code = GetAuthorisedValueByCode( 'LOST', $item->{'itemlost'} );
957         $needsconfirmation{ITEM_LOST} = $code if ( C4::Context->preference("IssueLostItem") eq 'confirm' );
958         $alerts{ITEM_LOST} = $code if ( C4::Context->preference("IssueLostItem") eq 'alert' );
959     }
960     if ( C4::Context->preference("IndependentBranches") ) {
961         my $userenv = C4::Context->userenv;
962         unless ( C4::Context->IsSuperLibrarian() ) {
963             if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} ){
964                 $issuingimpossible{ITEMNOTSAMEBRANCH} = 1;
965                 $issuingimpossible{'itemhomebranch'} = $item->{C4::Context->preference("HomeOrHoldingBranch")};
966             }
967             $needsconfirmation{BORRNOTSAMEBRANCH} = GetBranchName( $borrower->{'branchcode'} )
968               if ( $borrower->{'branchcode'} ne $userenv->{branch} );
969         }
970     }
971     #
972     # CHECK IF THERE IS RENTAL CHARGES. RENTAL MUST BE CONFIRMED BY THE BORROWER
973     #
974     my $rentalConfirmation = C4::Context->preference("RentalFeesCheckoutConfirmation");
975
976     if ( $rentalConfirmation ){
977         my ($rentalCharge) = GetIssuingCharges( $item->{'itemnumber'}, $borrower->{'borrowernumber'} );
978         if ( $rentalCharge > 0 ){
979             $rentalCharge = sprintf("%.02f", $rentalCharge);
980             $needsconfirmation{RENTALCHARGE} = $rentalCharge;
981         }
982     }
983
984     #
985     # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
986     #
987     if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} ){
988
989         # Already issued to current borrower. Ask whether the loan should
990         # be renewed.
991         my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed(
992             $borrower->{'borrowernumber'},
993             $item->{'itemnumber'}
994         );
995         if ( $CanBookBeRenewed == 0 ) {    # no more renewals allowed
996             if ( $renewerror eq 'onsite_checkout' ) {
997                 $issuingimpossible{NO_RENEWAL_FOR_ONSITE_CHECKOUTS} = 1;
998             }
999             else {
1000                 $issuingimpossible{NO_MORE_RENEWALS} = 1;
1001             }
1002         }
1003         else {
1004             $needsconfirmation{RENEW_ISSUE} = 1;
1005         }
1006     }
1007     elsif ($issue->{borrowernumber}) {
1008
1009         # issued to someone else
1010         my $currborinfo =    C4::Members::GetMember( borrowernumber => $issue->{borrowernumber} );
1011
1012 #        warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
1013         $needsconfirmation{ISSUED_TO_ANOTHER} = 1;
1014         $needsconfirmation{issued_firstname} = $currborinfo->{'firstname'};
1015         $needsconfirmation{issued_surname} = $currborinfo->{'surname'};
1016         $needsconfirmation{issued_cardnumber} = $currborinfo->{'cardnumber'};
1017         $needsconfirmation{issued_borrowernumber} = $currborinfo->{'borrowernumber'};
1018     }
1019
1020     unless ( $ignore_reserves ) {
1021         # See if the item is on reserve.
1022         my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
1023         if ($restype) {
1024             my $resbor = $res->{'borrowernumber'};
1025             if ( $resbor ne $borrower->{'borrowernumber'} ) {
1026                 my ( $resborrower ) = C4::Members::GetMember( borrowernumber => $resbor );
1027                 my $branchname = GetBranchName( $res->{'branchcode'} );
1028                 if ( $restype eq "Waiting" )
1029                 {
1030                     # The item is on reserve and waiting, but has been
1031                     # reserved by some other patron.
1032                     $needsconfirmation{RESERVE_WAITING} = 1;
1033                     $needsconfirmation{'resfirstname'} = $resborrower->{'firstname'};
1034                     $needsconfirmation{'ressurname'} = $resborrower->{'surname'};
1035                     $needsconfirmation{'rescardnumber'} = $resborrower->{'cardnumber'};
1036                     $needsconfirmation{'resborrowernumber'} = $resborrower->{'borrowernumber'};
1037                     $needsconfirmation{'resbranchname'} = $branchname;
1038                     $needsconfirmation{'reswaitingdate'} = format_date($res->{'waitingdate'});
1039                 }
1040                 elsif ( $restype eq "Reserved" ) {
1041                     # The item is on reserve for someone else.
1042                     $needsconfirmation{RESERVED} = 1;
1043                     $needsconfirmation{'resfirstname'} = $resborrower->{'firstname'};
1044                     $needsconfirmation{'ressurname'} = $resborrower->{'surname'};
1045                     $needsconfirmation{'rescardnumber'} = $resborrower->{'cardnumber'};
1046                     $needsconfirmation{'resborrowernumber'} = $resborrower->{'borrowernumber'};
1047                     $needsconfirmation{'resbranchname'} = $branchname;
1048                     $needsconfirmation{'resreservedate'} = format_date($res->{'reservedate'});
1049                 }
1050             }
1051         }
1052     }
1053
1054     ## CHECK AGE RESTRICTION
1055     my $agerestriction  = $biblioitem->{'agerestriction'};
1056     my ($restriction_age, $daysToAgeRestriction) = GetAgeRestriction( $agerestriction, $borrower );
1057     if ( $daysToAgeRestriction && $daysToAgeRestriction > 0 ) {
1058         if ( C4::Context->preference('AgeRestrictionOverride') ) {
1059             $needsconfirmation{AGE_RESTRICTION} = "$agerestriction";
1060         }
1061         else {
1062             $issuingimpossible{AGE_RESTRICTION} = "$agerestriction";
1063         }
1064     }
1065
1066     ## check for high holds decreasing loan period
1067     my $decrease_loan = C4::Context->preference('decreaseLoanHighHolds');
1068     if ( $decrease_loan && $decrease_loan == 1 ) {
1069         my ( $reserved, $num, $duration, $returndate ) =
1070           checkHighHolds( $item, $borrower );
1071
1072         if ( $num >= C4::Context->preference('decreaseLoanHighHoldsValue') ) {
1073             $needsconfirmation{HIGHHOLDS} = {
1074                 num_holds  => $num,
1075                 duration   => $duration,
1076                 returndate => output_pref($returndate),
1077             };
1078         }
1079     }
1080
1081     if (
1082         !C4::Context->preference('AllowMultipleIssuesOnABiblio') &&
1083         # don't do the multiple loans per bib check if we've
1084         # already determined that we've got a loan on the same item
1085         !$issuingimpossible{NO_MORE_RENEWALS} &&
1086         !$needsconfirmation{RENEW_ISSUE}
1087     ) {
1088         # Check if borrower has already issued an item from the same biblio
1089         # Only if it's not a subscription
1090         my $biblionumber = $item->{biblionumber};
1091         require C4::Serials;
1092         my $is_a_subscription = C4::Serials::CountSubscriptionFromBiblionumber($biblionumber);
1093         unless ($is_a_subscription) {
1094             my $issues = GetIssues( {
1095                 borrowernumber => $borrower->{borrowernumber},
1096                 biblionumber   => $biblionumber,
1097             } );
1098             my @issues = $issues ? @$issues : ();
1099             # if we get here, we don't already have a loan on this item,
1100             # so if there are any loans on this bib, ask for confirmation
1101             if (scalar @issues > 0) {
1102                 $needsconfirmation{BIBLIO_ALREADY_ISSUED} = 1;
1103             }
1104         }
1105     }
1106
1107     return ( \%issuingimpossible, \%needsconfirmation, \%alerts );
1108 }
1109
1110 =head2 CanBookBeReturned
1111
1112   ($returnallowed, $message) = CanBookBeReturned($item, $branch)
1113
1114 Check whether the item can be returned to the provided branch
1115
1116 =over 4
1117
1118 =item C<$item> is a hash of item information as returned from GetItem
1119
1120 =item C<$branch> is the branchcode where the return is taking place
1121
1122 =back
1123
1124 Returns:
1125
1126 =over 4
1127
1128 =item C<$returnallowed> is 0 or 1, corresponding to whether the return is allowed (1) or not (0)
1129
1130 =item C<$message> is the branchcode where the item SHOULD be returned, if the return is not allowed
1131
1132 =back
1133
1134 =cut
1135
1136 sub CanBookBeReturned {
1137   my ($item, $branch) = @_;
1138   my $allowreturntobranch = C4::Context->preference("AllowReturnToBranch") || 'anywhere';
1139
1140   # assume return is allowed to start
1141   my $allowed = 1;
1142   my $message;
1143
1144   # identify all cases where return is forbidden
1145   if ($allowreturntobranch eq 'homebranch' && $branch ne $item->{'homebranch'}) {
1146      $allowed = 0;
1147      $message = $item->{'homebranch'};
1148   } elsif ($allowreturntobranch eq 'holdingbranch' && $branch ne $item->{'holdingbranch'}) {
1149      $allowed = 0;
1150      $message = $item->{'holdingbranch'};
1151   } elsif ($allowreturntobranch eq 'homeorholdingbranch' && $branch ne $item->{'homebranch'} && $branch ne $item->{'holdingbranch'}) {
1152      $allowed = 0;
1153      $message = $item->{'homebranch'}; # FIXME: choice of homebranch is arbitrary
1154   }
1155
1156   return ($allowed, $message);
1157 }
1158
1159 =head2 CheckHighHolds
1160
1161     used when syspref decreaseLoanHighHolds is active. Returns 1 or 0 to define whether the minimum value held in
1162     decreaseLoanHighHoldsValue is exceeded, the total number of outstanding holds, the number of days the loan
1163     has been decreased to (held in syspref decreaseLoanHighHoldsValue), and the new due date
1164
1165 =cut
1166
1167 sub checkHighHolds {
1168     my ( $item, $borrower ) = @_;
1169     my $biblio = GetBiblioFromItemNumber( $item->{itemnumber} );
1170     my $branch = _GetCircControlBranch( $item, $borrower );
1171     my $dbh    = C4::Context->dbh;
1172     my $sth    = $dbh->prepare(
1173 'select count(borrowernumber) as num_holds from reserves where biblionumber=?'
1174     );
1175     $sth->execute( $item->{'biblionumber'} );
1176     my ($holds) = $sth->fetchrow_array;
1177     if ($holds) {
1178         my $issuedate = DateTime->now( time_zone => C4::Context->tz() );
1179
1180         my $calendar = Koha::Calendar->new( branchcode => $branch );
1181
1182         my $itype =
1183           ( C4::Context->preference('item-level_itypes') )
1184           ? $biblio->{'itype'}
1185           : $biblio->{'itemtype'};
1186         my $orig_due =
1187           C4::Circulation::CalcDateDue( $issuedate, $itype, $branch,
1188             $borrower );
1189
1190         my $reduced_datedue =
1191           $calendar->addDate( $issuedate,
1192             C4::Context->preference('decreaseLoanHighHoldsDuration') );
1193
1194         if ( DateTime->compare( $reduced_datedue, $orig_due ) == -1 ) {
1195             return ( 1, $holds,
1196                 C4::Context->preference('decreaseLoanHighHoldsDuration'),
1197                 $reduced_datedue );
1198         }
1199     }
1200     return ( 0, 0, 0, undef );
1201 }
1202
1203 =head2 AddIssue
1204
1205   &AddIssue($borrower, $barcode, [$datedue], [$cancelreserve], [$issuedate])
1206
1207 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
1208
1209 =over 4
1210
1211 =item C<$borrower> is a hash with borrower informations (from GetMember or GetMemberDetails).
1212
1213 =item C<$barcode> is the barcode of the item being issued.
1214
1215 =item C<$datedue> is a C4::Dates object for the max date of return, i.e. the date due (optional).
1216 Calculated if empty.
1217
1218 =item C<$cancelreserve> is 1 to override and cancel any pending reserves for the item (optional).
1219
1220 =item C<$issuedate> is the date to issue the item in iso (YYYY-MM-DD) format (optional).
1221 Defaults to today.  Unlike C<$datedue>, NOT a C4::Dates object, unfortunately.
1222
1223 AddIssue does the following things :
1224
1225   - step 01: check that there is a borrowernumber & a barcode provided
1226   - check for RENEWAL (book issued & being issued to the same patron)
1227       - renewal YES = Calculate Charge & renew
1228       - renewal NO  =
1229           * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
1230           * RESERVE PLACED ?
1231               - fill reserve if reserve to this patron
1232               - cancel reserve or not, otherwise
1233           * TRANSFERT PENDING ?
1234               - complete the transfert
1235           * ISSUE THE BOOK
1236
1237 =back
1238
1239 =cut
1240
1241 sub AddIssue {
1242     my ( $borrower, $barcode, $datedue, $cancelreserve, $issuedate, $sipmode, $params ) = @_;
1243     my $onsite_checkout = $params && $params->{onsite_checkout} ? 1 : 0;
1244     my $auto_renew = $params && $params->{auto_renew};
1245     my $dbh = C4::Context->dbh;
1246     my $barcodecheck=CheckValidBarcode($barcode);
1247
1248     my $issue;
1249
1250     if ($datedue && ref $datedue ne 'DateTime') {
1251         $datedue = dt_from_string($datedue);
1252     }
1253     # $issuedate defaults to today.
1254     if ( ! defined $issuedate ) {
1255         $issuedate = DateTime->now(time_zone => C4::Context->tz());
1256     }
1257     else {
1258         if ( ref $issuedate ne 'DateTime') {
1259             $issuedate = dt_from_string($issuedate);
1260
1261         }
1262     }
1263         if ($borrower and $barcode and $barcodecheck ne '0'){#??? wtf
1264                 # find which item we issue
1265                 my $item = GetItem('', $barcode) or return;     # if we don't get an Item, abort.
1266                 my $branch = _GetCircControlBranch($item,$borrower);
1267                 
1268                 # get actual issuing if there is one
1269                 my $actualissue = GetItemIssue( $item->{itemnumber});
1270                 
1271                 # get biblioinformation for this item
1272                 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
1273                 
1274                 #
1275                 # check if we just renew the issue.
1276                 #
1277                 if ($actualissue->{borrowernumber} eq $borrower->{'borrowernumber'}) {
1278                     $datedue = AddRenewal(
1279                         $borrower->{'borrowernumber'},
1280                         $item->{'itemnumber'},
1281                         $branch,
1282                         $datedue,
1283                         $issuedate, # here interpreted as the renewal date
1284                         );
1285                 }
1286                 else {
1287         # it's NOT a renewal
1288                         if ( $actualissue->{borrowernumber}) {
1289                                 # This book is currently on loan, but not to the person
1290                                 # who wants to borrow it now. mark it returned before issuing to the new borrower
1291                                 AddReturn(
1292                                         $item->{'barcode'},
1293                                         C4::Context->userenv->{'branch'}
1294                                 );
1295                         }
1296
1297             MoveReserve( $item->{'itemnumber'}, $borrower->{'borrowernumber'}, $cancelreserve );
1298                         # Starting process for transfer job (checking transfert and validate it if we have one)
1299             my ($datesent) = GetTransfers($item->{'itemnumber'});
1300             if ($datesent) {
1301         #       updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for visibility of this case (maybe for stats ....)
1302                 my $sth =
1303                     $dbh->prepare(
1304                     "UPDATE branchtransfers 
1305                         SET datearrived = now(),
1306                         tobranch = ?,
1307                         comments = 'Forced branchtransfer'
1308                     WHERE itemnumber= ? AND datearrived IS NULL"
1309                     );
1310                 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
1311             }
1312
1313         # If automatic renewal wasn't selected while issuing, set the value according to the issuing rule.
1314         unless ($auto_renew) {
1315             my $issuingrule = GetIssuingRule($borrower->{categorycode}, $item->{itype}, $branch);
1316             $auto_renew = $issuingrule->{auto_renew};
1317         }
1318
1319         # Record in the database the fact that the book was issued.
1320         unless ($datedue) {
1321             my $itype = ( C4::Context->preference('item-level_itypes') ) ? $biblio->{'itype'} : $biblio->{'itemtype'};
1322             $datedue = CalcDateDue( $issuedate, $itype, $branch, $borrower );
1323
1324         }
1325         $datedue->truncate( to => 'minute');
1326
1327         $issue = Koha::Database->new()->schema()->resultset('Issue')->create(
1328             {
1329                 borrowernumber  => $borrower->{'borrowernumber'},
1330                 itemnumber      => $item->{'itemnumber'},
1331                 issuedate       => $issuedate->strftime('%Y-%m-%d %H:%M:%S'),
1332                 date_due        => $datedue->strftime('%Y-%m-%d %H:%M:%S'),
1333                 branchcode      => C4::Context->userenv->{'branch'},
1334                 onsite_checkout => $onsite_checkout,
1335                 auto_renew      => $auto_renew ? 1 : 0
1336             }
1337         );
1338
1339         if ( C4::Context->preference('ReturnToShelvingCart') ) { ## ReturnToShelvingCart is on, anything issued should be taken off the cart.
1340           CartToShelf( $item->{'itemnumber'} );
1341         }
1342         $item->{'issues'}++;
1343         if ( C4::Context->preference('UpdateTotalIssuesOnCirc') ) {
1344             UpdateTotalIssues($item->{'biblionumber'}, 1);
1345         }
1346
1347         ## If item was lost, it has now been found, reverse any list item charges if necessary.
1348         if ( $item->{'itemlost'} ) {
1349             if ( C4::Context->preference('RefundLostItemFeeOnReturn' ) ) {
1350                 _FixAccountForLostAndReturned( $item->{'itemnumber'}, undef, $item->{'barcode'} );
1351             }
1352         }
1353
1354         ModItem({ issues           => $item->{'issues'},
1355                   holdingbranch    => C4::Context->userenv->{'branch'},
1356                   itemlost         => 0,
1357                   datelastborrowed => DateTime->now(time_zone => C4::Context->tz())->ymd(),
1358                   onloan           => $datedue->ymd(),
1359                 }, $item->{'biblionumber'}, $item->{'itemnumber'});
1360         ModDateLastSeen( $item->{'itemnumber'} );
1361
1362         # If it costs to borrow this book, charge it to the patron's account.
1363         my ( $charge, $itemtype ) = GetIssuingCharges(
1364             $item->{'itemnumber'},
1365             $borrower->{'borrowernumber'}
1366         );
1367         if ( $charge > 0 ) {
1368             AddIssuingCharge(
1369                 $item->{'itemnumber'},
1370                 $borrower->{'borrowernumber'}, $charge
1371             );
1372             $item->{'charge'} = $charge;
1373         }
1374
1375         # Record the fact that this book was issued.
1376         &UpdateStats({
1377                       branch => C4::Context->userenv->{'branch'},
1378                       type => ( $onsite_checkout ? 'onsite_checkout' : 'issue' ),
1379                       amount => $charge,
1380                       other => ($sipmode ? "SIP-$sipmode" : ''),
1381                       itemnumber => $item->{'itemnumber'},
1382                       itemtype => $item->{'itype'},
1383                       borrowernumber => $borrower->{'borrowernumber'},
1384                       ccode => $item->{'ccode'}}
1385         );
1386
1387         # Send a checkout slip.
1388         my $circulation_alert = 'C4::ItemCirculationAlertPreference';
1389         my %conditions = (
1390             branchcode   => $branch,
1391             categorycode => $borrower->{categorycode},
1392             item_type    => $item->{itype},
1393             notification => 'CHECKOUT',
1394         );
1395         if ($circulation_alert->is_enabled_for(\%conditions)) {
1396             SendCirculationAlert({
1397                 type     => 'CHECKOUT',
1398                 item     => $item,
1399                 borrower => $borrower,
1400                 branch   => $branch,
1401             });
1402         }
1403     }
1404
1405     logaction("CIRCULATION", "ISSUE", $borrower->{'borrowernumber'}, $biblio->{'itemnumber'})
1406         if C4::Context->preference("IssueLog");
1407   }
1408   return $issue;
1409 }
1410
1411 =head2 GetLoanLength
1412
1413   my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1414
1415 Get loan length for an itemtype, a borrower type and a branch
1416
1417 =cut
1418
1419 sub GetLoanLength {
1420     my ( $borrowertype, $itemtype, $branchcode ) = @_;
1421     my $dbh = C4::Context->dbh;
1422     my $sth = $dbh->prepare(qq{
1423         SELECT issuelength, lengthunit, renewalperiod
1424         FROM issuingrules
1425         WHERE   categorycode=?
1426             AND itemtype=?
1427             AND branchcode=?
1428             AND issuelength IS NOT NULL
1429     });
1430
1431     # try to find issuelength & return the 1st available.
1432     # check with borrowertype, itemtype and branchcode, then without one of those parameters
1433     $sth->execute( $borrowertype, $itemtype, $branchcode );
1434     my $loanlength = $sth->fetchrow_hashref;
1435
1436     return $loanlength
1437       if defined($loanlength) && $loanlength->{issuelength};
1438
1439     $sth->execute( $borrowertype, '*', $branchcode );
1440     $loanlength = $sth->fetchrow_hashref;
1441     return $loanlength
1442       if defined($loanlength) && $loanlength->{issuelength};
1443
1444     $sth->execute( '*', $itemtype, $branchcode );
1445     $loanlength = $sth->fetchrow_hashref;
1446     return $loanlength
1447       if defined($loanlength) && $loanlength->{issuelength};
1448
1449     $sth->execute( '*', '*', $branchcode );
1450     $loanlength = $sth->fetchrow_hashref;
1451     return $loanlength
1452       if defined($loanlength) && $loanlength->{issuelength};
1453
1454     $sth->execute( $borrowertype, $itemtype, '*' );
1455     $loanlength = $sth->fetchrow_hashref;
1456     return $loanlength
1457       if defined($loanlength) && $loanlength->{issuelength};
1458
1459     $sth->execute( $borrowertype, '*', '*' );
1460     $loanlength = $sth->fetchrow_hashref;
1461     return $loanlength
1462       if defined($loanlength) && $loanlength->{issuelength};
1463
1464     $sth->execute( '*', $itemtype, '*' );
1465     $loanlength = $sth->fetchrow_hashref;
1466     return $loanlength
1467       if defined($loanlength) && $loanlength->{issuelength};
1468
1469     $sth->execute( '*', '*', '*' );
1470     $loanlength = $sth->fetchrow_hashref;
1471     return $loanlength
1472       if defined($loanlength) && $loanlength->{issuelength};
1473
1474     # if no rule is set => 21 days (hardcoded)
1475     return {
1476         issuelength => 21,
1477         renewalperiod => 21,
1478         lengthunit => 'days',
1479     };
1480
1481 }
1482
1483
1484 =head2 GetHardDueDate
1485
1486   my ($hardduedate,$hardduedatecompare) = &GetHardDueDate($borrowertype,$itemtype,branchcode)
1487
1488 Get the Hard Due Date and it's comparison for an itemtype, a borrower type and a branch
1489
1490 =cut
1491
1492 sub GetHardDueDate {
1493     my ( $borrowertype, $itemtype, $branchcode ) = @_;
1494
1495     my $rule = GetIssuingRule( $borrowertype, $itemtype, $branchcode );
1496
1497     if ( defined( $rule ) ) {
1498         if ( $rule->{hardduedate} ) {
1499             return (dt_from_string($rule->{hardduedate}, 'iso'),$rule->{hardduedatecompare});
1500         } else {
1501             return (undef, undef);
1502         }
1503     }
1504 }
1505
1506 =head2 GetIssuingRule
1507
1508   my $irule = &GetIssuingRule($borrowertype,$itemtype,branchcode)
1509
1510 FIXME - This is a copy-paste of GetLoanLength
1511 as a stop-gap.  Do not wish to change API for GetLoanLength 
1512 this close to release.
1513
1514 Get the issuing rule for an itemtype, a borrower type and a branch
1515 Returns a hashref from the issuingrules table.
1516
1517 =cut
1518
1519 sub GetIssuingRule {
1520     my ( $borrowertype, $itemtype, $branchcode ) = @_;
1521     my $dbh = C4::Context->dbh;
1522     my $sth =  $dbh->prepare( "select * from issuingrules where categorycode=? and itemtype=? and branchcode=?"  );
1523     my $irule;
1524
1525     $sth->execute( $borrowertype, $itemtype, $branchcode );
1526     $irule = $sth->fetchrow_hashref;
1527     return $irule if defined($irule) ;
1528
1529     $sth->execute( $borrowertype, "*", $branchcode );
1530     $irule = $sth->fetchrow_hashref;
1531     return $irule if defined($irule) ;
1532
1533     $sth->execute( "*", $itemtype, $branchcode );
1534     $irule = $sth->fetchrow_hashref;
1535     return $irule if defined($irule) ;
1536
1537     $sth->execute( "*", "*", $branchcode );
1538     $irule = $sth->fetchrow_hashref;
1539     return $irule if defined($irule) ;
1540
1541     $sth->execute( $borrowertype, $itemtype, "*" );
1542     $irule = $sth->fetchrow_hashref;
1543     return $irule if defined($irule) ;
1544
1545     $sth->execute( $borrowertype, "*", "*" );
1546     $irule = $sth->fetchrow_hashref;
1547     return $irule if defined($irule) ;
1548
1549     $sth->execute( "*", $itemtype, "*" );
1550     $irule = $sth->fetchrow_hashref;
1551     return $irule if defined($irule) ;
1552
1553     $sth->execute( "*", "*", "*" );
1554     $irule = $sth->fetchrow_hashref;
1555     return $irule if defined($irule) ;
1556
1557     # if no rule matches,
1558     return;
1559 }
1560
1561 =head2 GetBranchBorrowerCircRule
1562
1563   my $branch_cat_rule = GetBranchBorrowerCircRule($branchcode, $categorycode);
1564
1565 Retrieves circulation rule attributes that apply to the given
1566 branch and patron category, regardless of item type.  
1567 The return value is a hashref containing the following key:
1568
1569 maxissueqty - maximum number of loans that a
1570 patron of the given category can have at the given
1571 branch.  If the value is undef, no limit.
1572
1573 maxonsiteissueqty - maximum of on-site checkouts that a
1574 patron of the given category can have at the given
1575 branch.  If the value is undef, no limit.
1576
1577 This will first check for a specific branch and
1578 category match from branch_borrower_circ_rules. 
1579
1580 If no rule is found, it will then check default_branch_circ_rules
1581 (same branch, default category).  If no rule is found,
1582 it will then check default_borrower_circ_rules (default 
1583 branch, same category), then failing that, default_circ_rules
1584 (default branch, default category).
1585
1586 If no rule has been found in the database, it will default to
1587 the buillt in rule:
1588
1589 maxissueqty - undef
1590 maxonsiteissueqty - undef
1591
1592 C<$branchcode> and C<$categorycode> should contain the
1593 literal branch code and patron category code, respectively - no
1594 wildcards.
1595
1596 =cut
1597
1598 sub GetBranchBorrowerCircRule {
1599     my ( $branchcode, $categorycode ) = @_;
1600
1601     my $rules;
1602     my $dbh = C4::Context->dbh();
1603     $rules = $dbh->selectrow_hashref( q|
1604         SELECT maxissueqty, maxonsiteissueqty
1605         FROM branch_borrower_circ_rules
1606         WHERE branchcode = ?
1607         AND   categorycode = ?
1608     |, {}, $branchcode, $categorycode ) ;
1609     return $rules if $rules;
1610
1611     # try same branch, default borrower category
1612     $rules = $dbh->selectrow_hashref( q|
1613         SELECT maxissueqty, maxonsiteissueqty
1614         FROM default_branch_circ_rules
1615         WHERE branchcode = ?
1616     |, {}, $branchcode ) ;
1617     return $rules if $rules;
1618
1619     # try default branch, same borrower category
1620     $rules = $dbh->selectrow_hashref( q|
1621         SELECT maxissueqty, maxonsiteissueqty
1622         FROM default_borrower_circ_rules
1623         WHERE categorycode = ?
1624     |, {}, $categorycode ) ;
1625     return $rules if $rules;
1626
1627     # try default branch, default borrower category
1628     $rules = $dbh->selectrow_hashref( q|
1629         SELECT maxissueqty, maxonsiteissueqty
1630         FROM default_circ_rules
1631     |, {} );
1632     return $rules if $rules;
1633
1634     # built-in default circulation rule
1635     return {
1636         maxissueqty => undef,
1637         maxonsiteissueqty => undef,
1638     };
1639 }
1640
1641 =head2 GetBranchItemRule
1642
1643   my $branch_item_rule = GetBranchItemRule($branchcode, $itemtype);
1644
1645 Retrieves circulation rule attributes that apply to the given
1646 branch and item type, regardless of patron category.
1647
1648 The return value is a hashref containing the following keys:
1649
1650 holdallowed => Hold policy for this branch and itemtype. Possible values:
1651   0: No holds allowed.
1652   1: Holds allowed only by patrons that have the same homebranch as the item.
1653   2: Holds allowed from any patron.
1654
1655 returnbranch => branch to which to return item.  Possible values:
1656   noreturn: do not return, let item remain where checked in (floating collections)
1657   homebranch: return to item's home branch
1658   holdingbranch: return to issuer branch
1659
1660 This searches branchitemrules in the following order:
1661
1662   * Same branchcode and itemtype
1663   * Same branchcode, itemtype '*'
1664   * branchcode '*', same itemtype
1665   * branchcode and itemtype '*'
1666
1667 Neither C<$branchcode> nor C<$itemtype> should be '*'.
1668
1669 =cut
1670
1671 sub GetBranchItemRule {
1672     my ( $branchcode, $itemtype ) = @_;
1673     my $dbh = C4::Context->dbh();
1674     my $result = {};
1675
1676     my @attempts = (
1677         ['SELECT holdallowed, returnbranch
1678             FROM branch_item_rules
1679             WHERE branchcode = ?
1680               AND itemtype = ?', $branchcode, $itemtype],
1681         ['SELECT holdallowed, returnbranch
1682             FROM default_branch_circ_rules
1683             WHERE branchcode = ?', $branchcode],
1684         ['SELECT holdallowed, returnbranch
1685             FROM default_branch_item_rules
1686             WHERE itemtype = ?', $itemtype],
1687         ['SELECT holdallowed, returnbranch
1688             FROM default_circ_rules'],
1689     );
1690
1691     foreach my $attempt (@attempts) {
1692         my ($query, @bind_params) = @{$attempt};
1693         my $search_result = $dbh->selectrow_hashref ( $query , {}, @bind_params )
1694           or next;
1695
1696         # Since branch/category and branch/itemtype use the same per-branch
1697         # defaults tables, we have to check that the key we want is set, not
1698         # just that a row was returned
1699         $result->{'holdallowed'}  = $search_result->{'holdallowed'}  unless ( defined $result->{'holdallowed'} );
1700         $result->{'returnbranch'} = $search_result->{'returnbranch'} unless ( defined $result->{'returnbranch'} );
1701     }
1702     
1703     # built-in default circulation rule
1704     $result->{'holdallowed'} = 2 unless ( defined $result->{'holdallowed'} );
1705     $result->{'returnbranch'} = 'homebranch' unless ( defined $result->{'returnbranch'} );
1706
1707     return $result;
1708 }
1709
1710 =head2 AddReturn
1711
1712   ($doreturn, $messages, $iteminformation, $borrower) =
1713       &AddReturn( $barcode, $branch [,$exemptfine] [,$dropbox] [,$returndate] );
1714
1715 Returns a book.
1716
1717 =over 4
1718
1719 =item C<$barcode> is the bar code of the book being returned.
1720
1721 =item C<$branch> is the code of the branch where the book is being returned.
1722
1723 =item C<$exemptfine> indicates that overdue charges for the item will be
1724 removed. Optional.
1725
1726 =item C<$dropbox> indicates that the check-in date is assumed to be
1727 yesterday, or the last non-holiday as defined in C4::Calendar .  If
1728 overdue charges are applied and C<$dropbox> is true, the last charge
1729 will be removed.  This assumes that the fines accrual script has run
1730 for _today_. Optional.
1731
1732 =item C<$return_date> allows the default return date to be overridden
1733 by the given return date. Optional.
1734
1735 =back
1736
1737 C<&AddReturn> returns a list of four items:
1738
1739 C<$doreturn> is true iff the return succeeded.
1740
1741 C<$messages> is a reference-to-hash giving feedback on the operation.
1742 The keys of the hash are:
1743
1744 =over 4
1745
1746 =item C<BadBarcode>
1747
1748 No item with this barcode exists. The value is C<$barcode>.
1749
1750 =item C<NotIssued>
1751
1752 The book is not currently on loan. The value is C<$barcode>.
1753
1754 =item C<IsPermanent>
1755
1756 The book's home branch is a permanent collection. If you have borrowed
1757 this book, you are not allowed to return it. The value is the code for
1758 the book's home branch.
1759
1760 =item C<withdrawn>
1761
1762 This book has been withdrawn/cancelled. The value should be ignored.
1763
1764 =item C<Wrongbranch>
1765
1766 This book has was returned to the wrong branch.  The value is a hashref
1767 so that C<$messages->{Wrongbranch}->{Wrongbranch}> and C<$messages->{Wrongbranch}->{Rightbranch}>
1768 contain the branchcode of the incorrect and correct return library, respectively.
1769
1770 =item C<ResFound>
1771
1772 The item was reserved. The value is a reference-to-hash whose keys are
1773 fields from the reserves table of the Koha database, and
1774 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1775 either C<Waiting>, C<Reserved>, or 0.
1776
1777 =item C<WasReturned>
1778
1779 Value 1 if return is successful.
1780
1781 =item C<NeedsTransfer>
1782
1783 If AutomaticItemReturn is disabled, return branch is given as value of NeedsTransfer.
1784
1785 =back
1786
1787 C<$iteminformation> is a reference-to-hash, giving information about the
1788 returned item from the issues table.
1789
1790 C<$borrower> is a reference-to-hash, giving information about the
1791 patron who last borrowed the book.
1792
1793 =cut
1794
1795 sub AddReturn {
1796     my ( $barcode, $branch, $exemptfine, $dropbox, $return_date, $dropboxdate ) = @_;
1797
1798     if ($branch and not GetBranchDetail($branch)) {
1799         warn "AddReturn error: branch '$branch' not found.  Reverting to " . C4::Context->userenv->{'branch'};
1800         undef $branch;
1801     }
1802     $branch = C4::Context->userenv->{'branch'} unless $branch;  # we trust userenv to be a safe fallback/default
1803     my $messages;
1804     my $borrower;
1805     my $biblio;
1806     my $doreturn       = 1;
1807     my $validTransfert = 0;
1808     my $stat_type = 'return';
1809
1810     # get information on item
1811     my $itemnumber = GetItemnumberFromBarcode( $barcode );
1812     unless ($itemnumber) {
1813         return (0, { BadBarcode => $barcode }); # no barcode means no item or borrower.  bail out.
1814     }
1815     my $issue  = GetItemIssue($itemnumber);
1816     if ($issue and $issue->{borrowernumber}) {
1817         $borrower = C4::Members::GetMemberDetails($issue->{borrowernumber})
1818             or die "Data inconsistency: barcode $barcode (itemnumber:$itemnumber) claims to be issued to non-existent borrowernumber '$issue->{borrowernumber}'\n"
1819                 . Dumper($issue) . "\n";
1820     } else {
1821         $messages->{'NotIssued'} = $barcode;
1822         # even though item is not on loan, it may still be transferred;  therefore, get current branch info
1823         $doreturn = 0;
1824         # No issue, no borrowernumber.  ONLY if $doreturn, *might* you have a $borrower later.
1825         # Record this as a local use, instead of a return, if the RecordLocalUseOnReturn is on
1826         if (C4::Context->preference("RecordLocalUseOnReturn")) {
1827            $messages->{'LocalUse'} = 1;
1828            $stat_type = 'localuse';
1829         }
1830     }
1831
1832     my $item = GetItem($itemnumber) or die "GetItem($itemnumber) failed";
1833
1834     if ( $item->{'location'} eq 'PROC' ) {
1835         if ( C4::Context->preference("InProcessingToShelvingCart") ) {
1836             $item->{'location'} = 'CART';
1837         }
1838         else {
1839             $item->{location} = $item->{permanent_location};
1840         }
1841
1842         ModItem( $item, $item->{'biblionumber'}, $item->{'itemnumber'} );
1843     }
1844
1845         # full item data, but no borrowernumber or checkout info (no issue)
1846         # we know GetItem should work because GetItemnumberFromBarcode worked
1847     my $hbr = GetBranchItemRule($item->{'homebranch'}, $item->{'itype'})->{'returnbranch'} || "homebranch";
1848         # get the proper branch to which to return the item
1849     my $returnbranch = $item->{$hbr} || $branch ;
1850         # if $hbr was "noreturn" or any other non-item table value, then it should 'float' (i.e. stay at this branch)
1851
1852     my $borrowernumber = $borrower->{'borrowernumber'} || undef;    # we don't know if we had a borrower or not
1853
1854     my $yaml = C4::Context->preference('UpdateNotForLoanStatusOnCheckin');
1855     if ($yaml) {
1856         $yaml = "$yaml\n\n";  # YAML is anal on ending \n. Surplus does not hurt
1857         my $rules;
1858         eval { $rules = YAML::Load($yaml); };
1859         if ($@) {
1860             warn "Unable to parse UpdateNotForLoanStatusOnCheckin syspref : $@";
1861         }
1862         else {
1863             foreach my $key ( keys %$rules ) {
1864                 if ( $item->{notforloan} eq $key ) {
1865                     $messages->{'NotForLoanStatusUpdated'} = { from => $item->{notforloan}, to => $rules->{$key} };
1866                     ModItem( { notforloan => $rules->{$key} }, undef, $itemnumber );
1867                     last;
1868                 }
1869             }
1870         }
1871     }
1872
1873
1874     # check if the book is in a permanent collection....
1875     # FIXME -- This 'PE' attribute is largely undocumented.  afaict, there's no user interface that reflects this functionality.
1876     if ( $returnbranch ) {
1877         my $branches = GetBranches();    # a potentially expensive call for a non-feature.
1878         $branches->{$returnbranch}->{PE} and $messages->{'IsPermanent'} = $returnbranch;
1879     }
1880
1881     # check if the return is allowed at this branch
1882     my ($returnallowed, $message) = CanBookBeReturned($item, $branch);
1883     unless ($returnallowed){
1884         $messages->{'Wrongbranch'} = {
1885             Wrongbranch => $branch,
1886             Rightbranch => $message
1887         };
1888         $doreturn = 0;
1889         return ( $doreturn, $messages, $issue, $borrower );
1890     }
1891
1892     if ( $item->{'withdrawn'} ) { # book has been cancelled
1893         $messages->{'withdrawn'} = 1;
1894         $doreturn = 0 if C4::Context->preference("BlockReturnOfWithdrawnItems");
1895     }
1896
1897     # case of a return of document (deal with issues and holdingbranch)
1898     my $today = DateTime->now( time_zone => C4::Context->tz() );
1899
1900     if ($doreturn) {
1901         my $datedue = $issue->{date_due};
1902         $borrower or warn "AddReturn without current borrower";
1903                 my $circControlBranch;
1904         if ($dropbox) {
1905             # define circControlBranch only if dropbox mode is set
1906             # don't allow dropbox mode to create an invalid entry in issues (issuedate > today)
1907             # FIXME: check issuedate > returndate, factoring in holidays
1908             #$circControlBranch = _GetCircControlBranch($item,$borrower) unless ( $item->{'issuedate'} eq C4::Dates->today('iso') );;
1909             $circControlBranch = _GetCircControlBranch($item,$borrower);
1910             $issue->{'overdue'} = DateTime->compare($issue->{'date_due'}, $dropboxdate ) == -1 ? 1 : 0;
1911         }
1912
1913         if ($borrowernumber) {
1914             if ( ( C4::Context->preference('CalculateFinesOnReturn') && $issue->{'overdue'} ) || $return_date ) {
1915                 # we only need to calculate and change the fines if we want to do that on return
1916                 # Should be on for hourly loans
1917                 my $control = C4::Context->preference('CircControl');
1918                 my $control_branchcode =
1919                     ( $control eq 'ItemHomeLibrary' ) ? $item->{homebranch}
1920                   : ( $control eq 'PatronLibrary' )   ? $borrower->{branchcode}
1921                   :                                     $issue->{branchcode};
1922
1923                 my $date_returned =
1924                   $return_date ? dt_from_string($return_date) : $today;
1925
1926                 my ( $amount, $type, $unitcounttotal ) =
1927                   C4::Overdues::CalcFine( $item, $borrower->{categorycode},
1928                     $control_branchcode, $datedue, $date_returned );
1929
1930                 $type ||= q{};
1931
1932                 if ( C4::Context->preference('finesMode') eq 'production' ) {
1933                     if ( $amount > 0 ) {
1934                         C4::Overdues::UpdateFine( $issue->{itemnumber},
1935                             $issue->{borrowernumber},
1936                             $amount, $type, output_pref($datedue) );
1937                     }
1938                     elsif ($return_date) {
1939
1940                        # Backdated returns may have fines that shouldn't exist,
1941                        # so in this case, we need to drop those fines to 0
1942
1943                         C4::Overdues::UpdateFine( $issue->{itemnumber},
1944                             $issue->{borrowernumber},
1945                             0, $type, output_pref($datedue) );
1946                     }
1947                 }
1948             }
1949
1950             eval {
1951                 MarkIssueReturned( $borrowernumber, $item->{'itemnumber'},
1952                     $circControlBranch, $return_date, $borrower->{'privacy'} );
1953             };
1954             if ( $@ ) {
1955                 $messages->{'Wrongbranch'} = {
1956                     Wrongbranch => $branch,
1957                     Rightbranch => $message
1958                 };
1959                 carp $@;
1960                 return ( 0, { WasReturned => 0 }, $issue, $borrower );
1961             }
1962
1963             # FIXME is the "= 1" right?  This could be the borrower hash.
1964             $messages->{'WasReturned'} = 1;
1965
1966         }
1967
1968         ModItem({ onloan => undef }, $issue->{'biblionumber'}, $item->{'itemnumber'});
1969     }
1970
1971     # the holdingbranch is updated if the document is returned to another location.
1972     # this is always done regardless of whether the item was on loan or not
1973     if ($item->{'holdingbranch'} ne $branch) {
1974         UpdateHoldingbranch($branch, $item->{'itemnumber'});
1975         $item->{'holdingbranch'} = $branch; # update item data holdingbranch too
1976     }
1977     ModDateLastSeen( $item->{'itemnumber'} );
1978
1979     # check if we have a transfer for this document
1980     my ($datesent,$frombranch,$tobranch) = GetTransfers( $item->{'itemnumber'} );
1981
1982     # if we have a transfer to do, we update the line of transfers with the datearrived
1983     my $is_in_rotating_collection = C4::RotatingCollections::isItemInAnyCollection( $item->{'itemnumber'} );
1984     if ($datesent) {
1985         if ( $tobranch eq $branch ) {
1986             my $sth = C4::Context->dbh->prepare(
1987                 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1988             );
1989             $sth->execute( $item->{'itemnumber'} );
1990             # if we have a reservation with valid transfer, we can set it's status to 'W'
1991             ShelfToCart( $item->{'itemnumber'} ) if ( C4::Context->preference("ReturnToShelvingCart") );
1992             C4::Reserves::ModReserveStatus($item->{'itemnumber'}, 'W');
1993         } else {
1994             $messages->{'WrongTransfer'}     = $tobranch;
1995             $messages->{'WrongTransferItem'} = $item->{'itemnumber'};
1996         }
1997         $validTransfert = 1;
1998     } else {
1999         ShelfToCart( $item->{'itemnumber'} ) if ( C4::Context->preference("ReturnToShelvingCart") );
2000     }
2001
2002     # fix up the accounts.....
2003     if ( $item->{'itemlost'} ) {
2004         $messages->{'WasLost'} = 1;
2005
2006         if ( C4::Context->preference('RefundLostItemFeeOnReturn' ) ) {
2007             _FixAccountForLostAndReturned($item->{'itemnumber'}, $borrowernumber, $barcode);    # can tolerate undef $borrowernumber
2008             $messages->{'LostItemFeeRefunded'} = 1;
2009         }
2010     }
2011
2012     # fix up the overdues in accounts...
2013     if ($borrowernumber) {
2014         my $fix = _FixOverduesOnReturn($borrowernumber, $item->{itemnumber}, $exemptfine, $dropbox);
2015         defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $item->{itemnumber}...) failed!";  # zero is OK, check defined
2016         
2017         if ( $issue->{overdue} && $issue->{date_due} ) {
2018         # fix fine days
2019             $today = $dropboxdate if $dropbox;
2020             my ($debardate,$reminder) = _debar_user_on_return( $borrower, $item, $issue->{date_due}, $today );
2021             if ($reminder){
2022                 $messages->{'PrevDebarred'} = $debardate;
2023             } else {
2024                 $messages->{'Debarred'} = $debardate if $debardate;
2025             }
2026         # there's no overdue on the item but borrower had been previously debarred
2027         } elsif ( $issue->{date_due} and $borrower->{'debarred'} ) {
2028              if ( $borrower->{debarred} eq "9999-12-31") {
2029                 $messages->{'ForeverDebarred'} = $borrower->{'debarred'};
2030              } else {
2031                   my $borrower_debar_dt = dt_from_string( $borrower->{debarred} );
2032                   $borrower_debar_dt->truncate(to => 'day');
2033                   my $today_dt = $today->clone()->truncate(to => 'day');
2034                   if ( DateTime->compare( $borrower_debar_dt, $today_dt ) != -1 ) {
2035                       $messages->{'PrevDebarred'} = $borrower->{'debarred'};
2036                   }
2037              }
2038         }
2039     }
2040
2041     # find reserves.....
2042     # if we don't have a reserve with the status W, we launch the Checkreserves routine
2043     my ($resfound, $resrec);
2044     my $lookahead= C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
2045     ($resfound, $resrec, undef) = C4::Reserves::CheckReserves( $item->{'itemnumber'}, undef, $lookahead ) unless ( $item->{'withdrawn'} );
2046     if ($resfound) {
2047           $resrec->{'ResFound'} = $resfound;
2048         $messages->{'ResFound'} = $resrec;
2049     }
2050
2051     # Record the fact that this book was returned.
2052     # FIXME itemtype should record item level type, not bibliolevel type
2053     UpdateStats({
2054                 branch => $branch,
2055                 type => $stat_type,
2056                 itemnumber => $item->{'itemnumber'},
2057                 itemtype => $biblio->{'itemtype'},
2058                 borrowernumber => $borrowernumber,
2059                 ccode => $item->{'ccode'}}
2060     );
2061
2062     # Send a check-in slip. # NOTE: borrower may be undef.  probably shouldn't try to send messages then.
2063     my $circulation_alert = 'C4::ItemCirculationAlertPreference';
2064     my %conditions = (
2065         branchcode   => $branch,
2066         categorycode => $borrower->{categorycode},
2067         item_type    => $item->{itype},
2068         notification => 'CHECKIN',
2069     );
2070     if ($doreturn && $circulation_alert->is_enabled_for(\%conditions)) {
2071         SendCirculationAlert({
2072             type     => 'CHECKIN',
2073             item     => $item,
2074             borrower => $borrower,
2075             branch   => $branch,
2076         });
2077     }
2078     
2079     logaction("CIRCULATION", "RETURN", $borrowernumber, $item->{'itemnumber'})
2080         if C4::Context->preference("ReturnLog");
2081     
2082     # Remove any OVERDUES related debarment if the borrower has no overdues
2083     if ( $borrowernumber
2084       && $borrower->{'debarred'}
2085       && C4::Context->preference('AutoRemoveOverduesRestrictions')
2086       && !C4::Members::HasOverdues( $borrowernumber )
2087       && @{ GetDebarments({ borrowernumber => $borrowernumber, type => 'OVERDUES' }) }
2088     ) {
2089         DelUniqueDebarment({ borrowernumber => $borrowernumber, type => 'OVERDUES' });
2090     }
2091
2092     # Transfer to returnbranch if Automatic transfer set or append message NeedsTransfer
2093     if (!$is_in_rotating_collection && ($doreturn or $messages->{'NotIssued'}) and !$resfound and ($branch ne $returnbranch) and not $messages->{'WrongTransfer'}){
2094         if  (C4::Context->preference("AutomaticItemReturn"    ) or
2095             (C4::Context->preference("UseBranchTransferLimits") and
2096              ! IsBranchTransferAllowed($branch, $returnbranch, $item->{C4::Context->preference("BranchTransferLimitsType")} )
2097            )) {
2098             $debug and warn sprintf "about to call ModItemTransfer(%s, %s, %s)", $item->{'itemnumber'},$branch, $returnbranch;
2099             $debug and warn "item: " . Dumper($item);
2100             ModItemTransfer($item->{'itemnumber'}, $branch, $returnbranch);
2101             $messages->{'WasTransfered'} = 1;
2102         } else {
2103             $messages->{'NeedsTransfer'} = $returnbranch;
2104         }
2105     }
2106
2107     return ( $doreturn, $messages, $issue, $borrower );
2108 }
2109
2110 =head2 MarkIssueReturned
2111
2112   MarkIssueReturned($borrowernumber, $itemnumber, $dropbox_branch, $returndate, $privacy);
2113
2114 Unconditionally marks an issue as being returned by
2115 moving the C<issues> row to C<old_issues> and
2116 setting C<returndate> to the current date, or
2117 the last non-holiday date of the branccode specified in
2118 C<dropbox_branch> .  Assumes you've already checked that 
2119 it's safe to do this, i.e. last non-holiday > issuedate.
2120
2121 if C<$returndate> is specified (in iso format), it is used as the date
2122 of the return. It is ignored when a dropbox_branch is passed in.
2123
2124 C<$privacy> contains the privacy parameter. If the patron has set privacy to 2,
2125 the old_issue is immediately anonymised
2126
2127 Ideally, this function would be internal to C<C4::Circulation>,
2128 not exported, but it is currently needed by one 
2129 routine in C<C4::Accounts>.
2130
2131 =cut
2132
2133 sub MarkIssueReturned {
2134     my ( $borrowernumber, $itemnumber, $dropbox_branch, $returndate, $privacy ) = @_;
2135
2136     my $anonymouspatron;
2137     if ( $privacy == 2 ) {
2138         # The default of 0 will not work due to foreign key constraints
2139         # The anonymisation will fail if AnonymousPatron is not a valid entry
2140         # We need to check if the anonymous patron exist, Koha will fail loudly if it does not
2141         # Note that a warning should appear on the about page (System information tab).
2142         $anonymouspatron = C4::Context->preference('AnonymousPatron');
2143         die "Fatal error: the patron ($borrowernumber) has requested their circulation history be anonymized on check-in, but the AnonymousPatron system preference is empty or not set correctly."
2144             unless C4::Members::GetMember( borrowernumber => $anonymouspatron );
2145     }
2146     my $dbh   = C4::Context->dbh;
2147     my $query = 'UPDATE issues SET returndate=';
2148     my @bind;
2149     if ($dropbox_branch) {
2150         my $calendar = Koha::Calendar->new( branchcode => $dropbox_branch );
2151         my $dropboxdate = $calendar->addDate( DateTime->now( time_zone => C4::Context->tz), -1 );
2152         $query .= ' ? ';
2153         push @bind, $dropboxdate->strftime('%Y-%m-%d %H:%M');
2154     } elsif ($returndate) {
2155         $query .= ' ? ';
2156         push @bind, $returndate;
2157     } else {
2158         $query .= ' now() ';
2159     }
2160     $query .= ' WHERE  borrowernumber = ?  AND itemnumber = ?';
2161     push @bind, $borrowernumber, $itemnumber;
2162     # FIXME transaction
2163     my $sth_upd  = $dbh->prepare($query);
2164     $sth_upd->execute(@bind);
2165     my $sth_copy = $dbh->prepare('INSERT INTO old_issues SELECT * FROM issues
2166                                   WHERE borrowernumber = ?
2167                                   AND itemnumber = ?');
2168     $sth_copy->execute($borrowernumber, $itemnumber);
2169     # anonymise patron checkout immediately if $privacy set to 2 and AnonymousPatron is set to a valid borrowernumber
2170     if ( $privacy == 2) {
2171         my $sth_ano = $dbh->prepare("UPDATE old_issues SET borrowernumber=?
2172                                   WHERE borrowernumber = ?
2173                                   AND itemnumber = ?");
2174        $sth_ano->execute($anonymouspatron, $borrowernumber, $itemnumber);
2175     }
2176     my $sth_del  = $dbh->prepare("DELETE FROM issues
2177                                   WHERE borrowernumber = ?
2178                                   AND itemnumber = ?");
2179     $sth_del->execute($borrowernumber, $itemnumber);
2180
2181     ModItem( { 'onloan' => undef }, undef, $itemnumber );
2182 }
2183
2184 =head2 _debar_user_on_return
2185
2186     _debar_user_on_return($borrower, $item, $datedue, today);
2187
2188 C<$borrower> borrower hashref
2189
2190 C<$item> item hashref
2191
2192 C<$datedue> date due DateTime object
2193
2194 C<$today> DateTime object representing the return time
2195
2196 Internal function, called only by AddReturn that calculates and updates
2197  the user fine days, and debars him if necessary.
2198
2199 Should only be called for overdue returns
2200
2201 =cut
2202
2203 sub _debar_user_on_return {
2204     my ( $borrower, $item, $dt_due, $dt_today ) = @_;
2205
2206     my $branchcode = _GetCircControlBranch( $item, $borrower );
2207
2208     my $circcontrol = C4::Context->preference('CircControl');
2209     my $issuingrule =
2210       GetIssuingRule( $borrower->{categorycode}, $item->{itype}, $branchcode );
2211     my $finedays = $issuingrule->{finedays};
2212     my $unit     = $issuingrule->{lengthunit};
2213     my $chargeable_units = C4::Overdues::get_chargeable_units($unit, $dt_due, $dt_today, $branchcode);
2214
2215     if ($finedays) {
2216
2217         # finedays is in days, so hourly loans must multiply by 24
2218         # thus 1 hour late equals 1 day suspension * finedays rate
2219         $finedays = $finedays * 24 if ( $unit eq 'hours' );
2220
2221         # grace period is measured in the same units as the loan
2222         my $grace =
2223           DateTime::Duration->new( $unit => $issuingrule->{firstremind} );
2224
2225         my $deltadays = DateTime::Duration->new(
2226             days => $chargeable_units
2227         );
2228         if ( $deltadays->subtract($grace)->is_positive() ) {
2229             my $suspension_days = $deltadays * $finedays;
2230
2231             # If the max suspension days is < than the suspension days
2232             # the suspension days is limited to this maximum period.
2233             my $max_sd = $issuingrule->{maxsuspensiondays};
2234             if ( defined $max_sd ) {
2235                 $max_sd = DateTime::Duration->new( days => $max_sd );
2236                 $suspension_days = $max_sd
2237                   if DateTime::Duration->compare( $max_sd, $suspension_days ) < 0;
2238             }
2239
2240             my $new_debar_dt =
2241               $dt_today->clone()->add_duration( $suspension_days );
2242
2243             Koha::Borrower::Debarments::AddUniqueDebarment({
2244                 borrowernumber => $borrower->{borrowernumber},
2245                 expiration     => $new_debar_dt->ymd(),
2246                 type           => 'SUSPENSION',
2247             });
2248             # if borrower was already debarred but does not get an extra debarment
2249             if ( $borrower->{debarred} eq Koha::Borrower::Debarments::IsDebarred($borrower->{borrowernumber}) ) {
2250                     return ($borrower->{debarred},1);
2251             }
2252             return $new_debar_dt->ymd();
2253         }
2254     }
2255     return;
2256 }
2257
2258 =head2 _FixOverduesOnReturn
2259
2260    &_FixOverduesOnReturn($brn,$itm, $exemptfine, $dropboxmode);
2261
2262 C<$brn> borrowernumber
2263
2264 C<$itm> itemnumber
2265
2266 C<$exemptfine> BOOL -- remove overdue charge associated with this issue. 
2267 C<$dropboxmode> BOOL -- remove lastincrement on overdue charge associated with this issue.
2268
2269 Internal function, called only by AddReturn
2270
2271 =cut
2272
2273 sub _FixOverduesOnReturn {
2274     my ($borrowernumber, $item);
2275     unless ($borrowernumber = shift) {
2276         warn "_FixOverduesOnReturn() not supplied valid borrowernumber";
2277         return;
2278     }
2279     unless ($item = shift) {
2280         warn "_FixOverduesOnReturn() not supplied valid itemnumber";
2281         return;
2282     }
2283     my ($exemptfine, $dropbox) = @_;
2284     my $dbh = C4::Context->dbh;
2285
2286     # check for overdue fine
2287     my $sth = $dbh->prepare(
2288 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
2289     );
2290     $sth->execute( $borrowernumber, $item );
2291
2292     # alter fine to show that the book has been returned
2293     my $data = $sth->fetchrow_hashref;
2294     return 0 unless $data;    # no warning, there's just nothing to fix
2295
2296     my $uquery;
2297     my @bind = ($data->{'accountlines_id'});
2298     if ($exemptfine) {
2299         $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
2300         if (C4::Context->preference("FinesLog")) {
2301             &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
2302         }
2303     } elsif ($dropbox && $data->{lastincrement}) {
2304         my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
2305         my $amt = $data->{amount} - $data->{lastincrement} ;
2306         if (C4::Context->preference("FinesLog")) {
2307             &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
2308         }
2309          $uquery = "update accountlines set accounttype='F' ";
2310          if($outstanding  >= 0 && $amt >=0) {
2311             $uquery .= ", amount = ? , amountoutstanding=? ";
2312             unshift @bind, ($amt, $outstanding) ;
2313         }
2314     } else {
2315         $uquery = "update accountlines set accounttype='F' ";
2316     }
2317     $uquery .= " where (accountlines_id = ?)";
2318     my $usth = $dbh->prepare($uquery);
2319     return $usth->execute(@bind);
2320 }
2321
2322 =head2 _FixAccountForLostAndReturned
2323
2324   &_FixAccountForLostAndReturned($itemnumber, [$borrowernumber, $barcode]);
2325
2326 Calculates the charge for a book lost and returned.
2327
2328 Internal function, not exported, called only by AddReturn.
2329
2330 FIXME: This function reflects how inscrutable fines logic is.  Fix both.
2331 FIXME: Give a positive return value on success.  It might be the $borrowernumber who received credit, or the amount forgiven.
2332
2333 =cut
2334
2335 sub _FixAccountForLostAndReturned {
2336     my $itemnumber     = shift or return;
2337     my $borrowernumber = @_ ? shift : undef;
2338     my $item_id        = @_ ? shift : $itemnumber;  # Send the barcode if you want that logged in the description
2339     my $dbh = C4::Context->dbh;
2340     # check for charge made for lost book
2341     my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE itemnumber = ? AND accounttype IN ('L', 'Rep', 'W') ORDER BY date DESC, accountno DESC");
2342     $sth->execute($itemnumber);
2343     my $data = $sth->fetchrow_hashref;
2344     $data or return;    # bail if there is nothing to do
2345     $data->{accounttype} eq 'W' and return;    # Written off
2346
2347     # writeoff this amount
2348     my $offset;
2349     my $amount = $data->{'amount'};
2350     my $acctno = $data->{'accountno'};
2351     my $amountleft;                                             # Starts off undef/zero.
2352     if ($data->{'amountoutstanding'} == $amount) {
2353         $offset     = $data->{'amount'};
2354         $amountleft = 0;                                        # Hey, it's zero here, too.
2355     } else {
2356         $offset     = $amount - $data->{'amountoutstanding'};   # Um, isn't this the same as ZERO?  We just tested those two things are ==
2357         $amountleft = $data->{'amountoutstanding'} - $amount;   # Um, isn't this the same as ZERO?  We just tested those two things are ==
2358     }
2359     my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
2360         WHERE (accountlines_id = ?)");
2361     $usth->execute($data->{'accountlines_id'});      # We might be adjusting an account for some OTHER borrowernumber now.  Not the one we passed in.
2362     #check if any credit is left if so writeoff other accounts
2363     my $nextaccntno = getnextacctno($data->{'borrowernumber'});
2364     $amountleft *= -1 if ($amountleft < 0);
2365     if ($amountleft > 0) {
2366         my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
2367                             AND (amountoutstanding >0) ORDER BY date");     # might want to order by amountoustanding ASC (pay smallest first)
2368         $msth->execute($data->{'borrowernumber'});
2369         # offset transactions
2370         my $newamtos;
2371         my $accdata;
2372         while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
2373             if ($accdata->{'amountoutstanding'} < $amountleft) {
2374                 $newamtos = 0;
2375                 $amountleft -= $accdata->{'amountoutstanding'};
2376             }  else {
2377                 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
2378                 $amountleft = 0;
2379             }
2380             my $thisacct = $accdata->{'accountlines_id'};
2381             # FIXME: move prepares outside while loop!
2382             my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
2383                     WHERE (accountlines_id = ?)");
2384             $usth->execute($newamtos,$thisacct);
2385             $usth = $dbh->prepare("INSERT INTO accountoffsets
2386                 (borrowernumber, accountno, offsetaccount,  offsetamount)
2387                 VALUES
2388                 (?,?,?,?)");
2389             $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
2390         }
2391     }
2392     $amountleft *= -1 if ($amountleft > 0);
2393     my $desc = "Item Returned " . $item_id;
2394     $usth = $dbh->prepare("INSERT INTO accountlines
2395         (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
2396         VALUES (?,?,now(),?,?,'CR',?)");
2397     $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
2398     if ($borrowernumber) {
2399         # FIXME: same as query above.  use 1 sth for both
2400         $usth = $dbh->prepare("INSERT INTO accountoffsets
2401             (borrowernumber, accountno, offsetaccount,  offsetamount)
2402             VALUES (?,?,?,?)");
2403         $usth->execute($borrowernumber, $data->{'accountno'}, $nextaccntno, $offset);
2404     }
2405     ModItem({ paidfor => '' }, undef, $itemnumber);
2406     return;
2407 }
2408
2409 =head2 _GetCircControlBranch
2410
2411    my $circ_control_branch = _GetCircControlBranch($iteminfos, $borrower);
2412
2413 Internal function : 
2414
2415 Return the library code to be used to determine which circulation
2416 policy applies to a transaction.  Looks up the CircControl and
2417 HomeOrHoldingBranch system preferences.
2418
2419 C<$iteminfos> is a hashref to iteminfo. Only {homebranch or holdingbranch} is used.
2420
2421 C<$borrower> is a hashref to borrower. Only {branchcode} is used.
2422
2423 =cut
2424
2425 sub _GetCircControlBranch {
2426     my ($item, $borrower) = @_;
2427     my $circcontrol = C4::Context->preference('CircControl');
2428     my $branch;
2429
2430     if ($circcontrol eq 'PickupLibrary' and (C4::Context->userenv and C4::Context->userenv->{'branch'}) ) {
2431         $branch= C4::Context->userenv->{'branch'};
2432     } elsif ($circcontrol eq 'PatronLibrary') {
2433         $branch=$borrower->{branchcode};
2434     } else {
2435         my $branchfield = C4::Context->preference('HomeOrHoldingBranch') || 'homebranch';
2436         $branch = $item->{$branchfield};
2437         # default to item home branch if holdingbranch is used
2438         # and is not defined
2439         if (!defined($branch) && $branchfield eq 'holdingbranch') {
2440             $branch = $item->{homebranch};
2441         }
2442     }
2443     return $branch;
2444 }
2445
2446
2447
2448
2449
2450
2451 =head2 GetItemIssue
2452
2453   $issue = &GetItemIssue($itemnumber);
2454
2455 Returns patron currently having a book, or undef if not checked out.
2456
2457 C<$itemnumber> is the itemnumber.
2458
2459 C<$issue> is a hashref of the row from the issues table.
2460
2461 =cut
2462
2463 sub GetItemIssue {
2464     my ($itemnumber) = @_;
2465     return unless $itemnumber;
2466     my $sth = C4::Context->dbh->prepare(
2467         "SELECT items.*, issues.*
2468         FROM issues
2469         LEFT JOIN items ON issues.itemnumber=items.itemnumber
2470         WHERE issues.itemnumber=?");
2471     $sth->execute($itemnumber);
2472     my $data = $sth->fetchrow_hashref;
2473     return unless $data;
2474     $data->{issuedate_sql} = $data->{issuedate};
2475     $data->{date_due_sql} = $data->{date_due};
2476     $data->{issuedate} = dt_from_string($data->{issuedate}, 'sql');
2477     $data->{issuedate}->truncate(to => 'minute');
2478     $data->{date_due} = dt_from_string($data->{date_due}, 'sql');
2479     $data->{date_due}->truncate(to => 'minute');
2480     my $dt = DateTime->now( time_zone => C4::Context->tz)->truncate( to => 'minute');
2481     $data->{'overdue'} = DateTime->compare($data->{'date_due'}, $dt ) == -1 ? 1 : 0;
2482     return $data;
2483 }
2484
2485 =head2 GetOpenIssue
2486
2487   $issue = GetOpenIssue( $itemnumber );
2488
2489 Returns the row from the issues table if the item is currently issued, undef if the item is not currently issued
2490
2491 C<$itemnumber> is the item's itemnumber
2492
2493 Returns a hashref
2494
2495 =cut
2496
2497 sub GetOpenIssue {
2498   my ( $itemnumber ) = @_;
2499   return unless $itemnumber;
2500   my $dbh = C4::Context->dbh;  
2501   my $sth = $dbh->prepare( "SELECT * FROM issues WHERE itemnumber = ? AND returndate IS NULL" );
2502   $sth->execute( $itemnumber );
2503   return $sth->fetchrow_hashref();
2504
2505 }
2506
2507 =head2 GetIssues
2508
2509     $issues = GetIssues({});    # return all issues!
2510     $issues = GetIssues({ borrowernumber => $borrowernumber, biblionumber => $biblionumber });
2511
2512 Returns all pending issues that match given criteria.
2513 Returns a arrayref or undef if an error occurs.
2514
2515 Allowed criteria are:
2516
2517 =over 2
2518
2519 =item * borrowernumber
2520
2521 =item * biblionumber
2522
2523 =item * itemnumber
2524
2525 =back
2526
2527 =cut
2528
2529 sub GetIssues {
2530     my ($criteria) = @_;
2531
2532     # Build filters
2533     my @filters;
2534     my @allowed = qw(borrowernumber biblionumber itemnumber);
2535     foreach (@allowed) {
2536         if (defined $criteria->{$_}) {
2537             push @filters, {
2538                 field => $_,
2539                 value => $criteria->{$_},
2540             };
2541         }
2542     }
2543
2544     # Do we need to join other tables ?
2545     my %join;
2546     if (defined $criteria->{biblionumber}) {
2547         $join{items} = 1;
2548     }
2549
2550     # Build SQL query
2551     my $where = '';
2552     if (@filters) {
2553         $where = "WHERE " . join(' AND ', map { "$_->{field} = ?" } @filters);
2554     }
2555     my $query = q{
2556         SELECT issues.*
2557         FROM issues
2558     };
2559     if (defined $join{items}) {
2560         $query .= q{
2561             LEFT JOIN items ON (issues.itemnumber = items.itemnumber)
2562         };
2563     }
2564     $query .= $where;
2565
2566     # Execute SQL query
2567     my $dbh = C4::Context->dbh;
2568     my $sth = $dbh->prepare($query);
2569     my $rv = $sth->execute(map { $_->{value} } @filters);
2570
2571     return $rv ? $sth->fetchall_arrayref({}) : undef;
2572 }
2573
2574 =head2 GetItemIssues
2575
2576   $issues = &GetItemIssues($itemnumber, $history);
2577
2578 Returns patrons that have issued a book
2579
2580 C<$itemnumber> is the itemnumber
2581 C<$history> is false if you just want the current "issuer" (if any)
2582 and true if you want issues history from old_issues also.
2583
2584 Returns reference to an array of hashes
2585
2586 =cut
2587
2588 sub GetItemIssues {
2589     my ( $itemnumber, $history ) = @_;
2590     
2591     my $today = DateTime->now( time_zome => C4::Context->tz);  # get today date
2592     $today->truncate( to => 'minute' );
2593     my $sql = "SELECT * FROM issues
2594               JOIN borrowers USING (borrowernumber)
2595               JOIN items     USING (itemnumber)
2596               WHERE issues.itemnumber = ? ";
2597     if ($history) {
2598         $sql .= "UNION ALL
2599                  SELECT * FROM old_issues
2600                  LEFT JOIN borrowers USING (borrowernumber)
2601                  JOIN items USING (itemnumber)
2602                  WHERE old_issues.itemnumber = ? ";
2603     }
2604     $sql .= "ORDER BY date_due DESC";
2605     my $sth = C4::Context->dbh->prepare($sql);
2606     if ($history) {
2607         $sth->execute($itemnumber, $itemnumber);
2608     } else {
2609         $sth->execute($itemnumber);
2610     }
2611     my $results = $sth->fetchall_arrayref({});
2612     foreach (@$results) {
2613         my $date_due = dt_from_string($_->{date_due},'sql');
2614         $date_due->truncate( to => 'minute' );
2615
2616         $_->{overdue} = (DateTime->compare($date_due, $today) == -1) ? 1 : 0;
2617     }
2618     return $results;
2619 }
2620
2621 =head2 GetBiblioIssues
2622
2623   $issues = GetBiblioIssues($biblionumber);
2624
2625 this function get all issues from a biblionumber.
2626
2627 Return:
2628 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
2629 tables issues and the firstname,surname & cardnumber from borrowers.
2630
2631 =cut
2632
2633 sub GetBiblioIssues {
2634     my $biblionumber = shift;
2635     return unless $biblionumber;
2636     my $dbh   = C4::Context->dbh;
2637     my $query = "
2638         SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
2639         FROM issues
2640             LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
2641             LEFT JOIN items ON issues.itemnumber = items.itemnumber
2642             LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
2643             LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
2644         WHERE biblio.biblionumber = ?
2645         UNION ALL
2646         SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
2647         FROM old_issues
2648             LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
2649             LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
2650             LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
2651             LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
2652         WHERE biblio.biblionumber = ?
2653         ORDER BY timestamp
2654     ";
2655     my $sth = $dbh->prepare($query);
2656     $sth->execute($biblionumber, $biblionumber);
2657
2658     my @issues;
2659     while ( my $data = $sth->fetchrow_hashref ) {
2660         push @issues, $data;
2661     }
2662     return \@issues;
2663 }
2664
2665 =head2 GetUpcomingDueIssues
2666
2667   my $upcoming_dues = GetUpcomingDueIssues( { days_in_advance => 4 } );
2668
2669 =cut
2670
2671 sub GetUpcomingDueIssues {
2672     my $params = shift;
2673
2674     $params->{'days_in_advance'} = 7 unless exists $params->{'days_in_advance'};
2675     my $dbh = C4::Context->dbh;
2676
2677     my $statement = <<END_SQL;
2678 SELECT issues.*, items.itype as itemtype, items.homebranch, TO_DAYS( date_due )-TO_DAYS( NOW() ) as days_until_due, branches.branchemail
2679 FROM issues 
2680 LEFT JOIN items USING (itemnumber)
2681 LEFT OUTER JOIN branches USING (branchcode)
2682 WHERE returndate is NULL
2683 HAVING days_until_due >= 0 AND days_until_due <= ?
2684 END_SQL
2685
2686     my @bind_parameters = ( $params->{'days_in_advance'} );
2687     
2688     my $sth = $dbh->prepare( $statement );
2689     $sth->execute( @bind_parameters );
2690     my $upcoming_dues = $sth->fetchall_arrayref({});
2691
2692     return $upcoming_dues;
2693 }
2694
2695 =head2 CanBookBeRenewed
2696
2697   ($ok,$error) = &CanBookBeRenewed($borrowernumber, $itemnumber[, $override_limit]);
2698
2699 Find out whether a borrowed item may be renewed.
2700
2701 C<$borrowernumber> is the borrower number of the patron who currently
2702 has the item on loan.
2703
2704 C<$itemnumber> is the number of the item to renew.
2705
2706 C<$override_limit>, if supplied with a true value, causes
2707 the limit on the number of times that the loan can be renewed
2708 (as controlled by the item type) to be ignored. Overriding also allows
2709 to renew sooner than "No renewal before" and to manually renew loans
2710 that are automatically renewed.
2711
2712 C<$CanBookBeRenewed> returns a true value if the item may be renewed. The
2713 item must currently be on loan to the specified borrower; renewals
2714 must be allowed for the item's type; and the borrower must not have
2715 already renewed the loan. $error will contain the reason the renewal can not proceed
2716
2717 =cut
2718
2719 sub CanBookBeRenewed {
2720     my ( $borrowernumber, $itemnumber, $override_limit ) = @_;
2721
2722     my $dbh    = C4::Context->dbh;
2723     my $renews = 1;
2724
2725     my $item      = GetItem($itemnumber)      or return ( 0, 'no_item' );
2726     my $itemissue = GetItemIssue($itemnumber) or return ( 0, 'no_checkout' );
2727     return ( 0, 'onsite_checkout' ) if $itemissue->{onsite_checkout};
2728
2729     $borrowernumber ||= $itemissue->{borrowernumber};
2730     my $borrower = C4::Members::GetMember( borrowernumber => $borrowernumber )
2731       or return;
2732
2733     my ( $resfound, $resrec, undef ) = C4::Reserves::CheckReserves($itemnumber);
2734
2735     # This item can fill one or more unfilled reserve, can those unfilled reserves
2736     # all be filled by other available items?
2737     if ( $resfound
2738         && C4::Context->preference('AllowRenewalIfOtherItemsAvailable') )
2739     {
2740         my $schema = Koha::Database->new()->schema();
2741
2742         my $item_holds = $schema->resultset('Reserve')->search( { itemnumber => $itemnumber, found => undef } )->count();
2743         if ($item_holds) {
2744             # There is an item level hold on this item, no other item can fill the hold
2745             $resfound = 1;
2746         }
2747         else {
2748
2749             # Get all other items that could possibly fill reserves
2750             my @itemnumbers = $schema->resultset('Item')->search(
2751                 {
2752                     biblionumber => $resrec->{biblionumber},
2753                     onloan       => undef,
2754                     notforloan   => 0,
2755                     -not         => { itemnumber => $itemnumber }
2756                 },
2757                 { columns => 'itemnumber' }
2758             )->get_column('itemnumber')->all();
2759
2760             # Get all other reserves that could have been filled by this item
2761             my @borrowernumbers;
2762             while (1) {
2763                 my ( $reserve_found, $reserve, undef ) =
2764                   C4::Reserves::CheckReserves( $itemnumber, undef, undef, \@borrowernumbers );
2765
2766                 if ($reserve_found) {
2767                     push( @borrowernumbers, $reserve->{borrowernumber} );
2768                 }
2769                 else {
2770                     last;
2771                 }
2772             }
2773
2774             # If the count of the union of the lists of reservable items for each borrower
2775             # is equal or greater than the number of borrowers, we know that all reserves
2776             # can be filled with available items. We can get the union of the sets simply
2777             # by pushing all the elements onto an array and removing the duplicates.
2778             my @reservable;
2779             foreach my $b (@borrowernumbers) {
2780                 my ($borr) = C4::Members::GetMemberDetails($b);
2781                 foreach my $i (@itemnumbers) {
2782                     my $item = GetItem($i);
2783                     if (   IsAvailableForItemLevelRequest( $item, $borr )
2784                         && CanItemBeReserved( $b, $i )
2785                         && !IsItemOnHoldAndFound($i) )
2786                     {
2787                         push( @reservable, $i );
2788                     }
2789                 }
2790             }
2791
2792             @reservable = uniq(@reservable);
2793
2794             if ( @reservable >= @borrowernumbers ) {
2795                 $resfound = 0;
2796             }
2797         }
2798     }
2799     return ( 0, "on_reserve" ) if $resfound;    # '' when no hold was found
2800
2801     return ( 1, undef ) if $override_limit;
2802
2803     my $branchcode = _GetCircControlBranch( $item, $borrower );
2804     my $issuingrule =
2805       GetIssuingRule( $borrower->{categorycode}, $item->{itype}, $branchcode );
2806
2807     return ( 0, "too_many" )
2808       if $issuingrule->{renewalsallowed} <= $itemissue->{renewals};
2809
2810     my $overduesblockrenewing = C4::Context->preference('OverduesBlockRenewing');
2811     my $restrictionblockrenewing = C4::Context->preference('RestrictionBlockRenewing');
2812     my $restricted = Koha::Borrower::Debarments::IsDebarred($borrowernumber);
2813     my $hasoverdues = C4::Members::HasOverdues($borrowernumber);
2814
2815     if ( $restricted and $restrictionblockrenewing ) {
2816         return ( 0, 'restriction');
2817     } elsif ( ($hasoverdues and $overduesblockrenewing eq 'block') || ($itemissue->{overdue} and $overduesblockrenewing eq 'blockitem') ) {
2818         return ( 0, 'overdue');
2819     }
2820
2821     if ( $issuingrule->{norenewalbefore} ) {
2822
2823         # Get current time and add norenewalbefore.
2824         # If this is smaller than date_due, it's too soon for renewal.
2825         if (
2826             DateTime->now( time_zone => C4::Context->tz() )->add(
2827                 $issuingrule->{lengthunit} => $issuingrule->{norenewalbefore}
2828             ) < $itemissue->{date_due}
2829           )
2830         {
2831             return ( 0, "auto_too_soon" ) if $itemissue->{auto_renew};
2832             return ( 0, "too_soon" );
2833         }
2834     }
2835
2836     return ( 0, "auto_renew" ) if $itemissue->{auto_renew};
2837     return ( 1, undef );
2838 }
2839
2840 =head2 AddRenewal
2841
2842   &AddRenewal($borrowernumber, $itemnumber, $branch, [$datedue], [$lastreneweddate]);
2843
2844 Renews a loan.
2845
2846 C<$borrowernumber> is the borrower number of the patron who currently
2847 has the item.
2848
2849 C<$itemnumber> is the number of the item to renew.
2850
2851 C<$branch> is the library where the renewal took place (if any).
2852            The library that controls the circ policies for the renewal is retrieved from the issues record.
2853
2854 C<$datedue> can be a C4::Dates object used to set the due date.
2855
2856 C<$lastreneweddate> is an optional ISO-formatted date used to set issues.lastreneweddate.  If
2857 this parameter is not supplied, lastreneweddate is set to the current date.
2858
2859 If C<$datedue> is the empty string, C<&AddRenewal> will calculate the due date automatically
2860 from the book's item type.
2861
2862 =cut
2863
2864 sub AddRenewal {
2865     my $borrowernumber  = shift;
2866     my $itemnumber      = shift or return;
2867     my $branch          = shift;
2868     my $datedue         = shift;
2869     my $lastreneweddate = shift || DateTime->now(time_zone => C4::Context->tz)->ymd();
2870
2871     my $item   = GetItem($itemnumber) or return;
2872     my $biblio = GetBiblioFromItemNumber($itemnumber) or return;
2873
2874     my $dbh = C4::Context->dbh;
2875
2876     # Find the issues record for this book
2877     my $sth =
2878       $dbh->prepare("SELECT * FROM issues WHERE itemnumber = ?");
2879     $sth->execute( $itemnumber );
2880     my $issuedata = $sth->fetchrow_hashref;
2881
2882     return unless ( $issuedata );
2883
2884     $borrowernumber ||= $issuedata->{borrowernumber};
2885
2886     if ( defined $datedue && ref $datedue ne 'DateTime' ) {
2887         carp 'Invalid date passed to AddRenewal.';
2888         return;
2889     }
2890
2891     # If the due date wasn't specified, calculate it by adding the
2892     # book's loan length to today's date or the current due date
2893     # based on the value of the RenewalPeriodBase syspref.
2894     unless ($datedue) {
2895
2896         my $borrower = C4::Members::GetMember( borrowernumber => $borrowernumber ) or return;
2897         my $itemtype = (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'};
2898
2899         $datedue = (C4::Context->preference('RenewalPeriodBase') eq 'date_due') ?
2900                                         dt_from_string( $issuedata->{date_due} ) :
2901                                         DateTime->now( time_zone => C4::Context->tz());
2902         $datedue =  CalcDateDue($datedue, $itemtype, $issuedata->{'branchcode'}, $borrower, 'is a renewal');
2903     }
2904
2905     # Update the issues record to have the new due date, and a new count
2906     # of how many times it has been renewed.
2907     my $renews = $issuedata->{'renewals'} + 1;
2908     $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?, lastreneweddate = ?
2909                             WHERE borrowernumber=? 
2910                             AND itemnumber=?"
2911     );
2912
2913     $sth->execute( $datedue->strftime('%Y-%m-%d %H:%M'), $renews, $lastreneweddate, $borrowernumber, $itemnumber );
2914
2915     # Update the renewal count on the item, and tell zebra to reindex
2916     $renews = $biblio->{'renewals'} + 1;
2917     ModItem({ renewals => $renews, onloan => $datedue->strftime('%Y-%m-%d %H:%M')}, $biblio->{'biblionumber'}, $itemnumber);
2918
2919     # Charge a new rental fee, if applicable?
2920     my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2921     if ( $charge > 0 ) {
2922         my $accountno = getnextacctno( $borrowernumber );
2923         my $item = GetBiblioFromItemNumber($itemnumber);
2924         my $manager_id = 0;
2925         $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv; 
2926         $sth = $dbh->prepare(
2927                 "INSERT INTO accountlines
2928                     (date, borrowernumber, accountno, amount, manager_id,
2929                     description,accounttype, amountoutstanding, itemnumber)
2930                     VALUES (now(),?,?,?,?,?,?,?,?)"
2931         );
2932         $sth->execute( $borrowernumber, $accountno, $charge, $manager_id,
2933             "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
2934             'Rent', $charge, $itemnumber );
2935     }
2936
2937     # Send a renewal slip according to checkout alert preferencei
2938     if ( C4::Context->preference('RenewalSendNotice') eq '1') {
2939         my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 );
2940         my $circulation_alert = 'C4::ItemCirculationAlertPreference';
2941         my %conditions = (
2942                 branchcode   => $branch,
2943                 categorycode => $borrower->{categorycode},
2944                 item_type    => $item->{itype},
2945                 notification => 'CHECKOUT',
2946         );
2947         if ($circulation_alert->is_enabled_for(\%conditions)) {
2948                 SendCirculationAlert({
2949                         type     => 'RENEWAL',
2950                         item     => $item,
2951                 borrower => $borrower,
2952                 branch   => $branch,
2953                 });
2954         }
2955     }
2956
2957     # Remove any OVERDUES related debarment if the borrower has no overdues
2958     my $borrower = C4::Members::GetMember( borrowernumber => $borrowernumber );
2959     if ( $borrowernumber
2960       && $borrower->{'debarred'}
2961       && !C4::Members::HasOverdues( $borrowernumber )
2962       && @{ GetDebarments({ borrowernumber => $borrowernumber, type => 'OVERDUES' }) }
2963     ) {
2964         DelUniqueDebarment({ borrowernumber => $borrowernumber, type => 'OVERDUES' });
2965     }
2966
2967     # Log the renewal
2968     UpdateStats({branch => $branch,
2969                 type => 'renew',
2970                 amount => $charge,
2971                 itemnumber => $itemnumber,
2972                 itemtype => $item->{itype},
2973                 borrowernumber => $borrowernumber,
2974                 ccode => $item->{'ccode'}}
2975                 );
2976         return $datedue;
2977 }
2978
2979 sub GetRenewCount {
2980     # check renewal status
2981     my ( $bornum, $itemno ) = @_;
2982     my $dbh           = C4::Context->dbh;
2983     my $renewcount    = 0;
2984     my $renewsallowed = 0;
2985     my $renewsleft    = 0;
2986
2987     my $borrower = C4::Members::GetMember( borrowernumber => $bornum);
2988     my $item     = GetItem($itemno); 
2989
2990     # Look in the issues table for this item, lent to this borrower,
2991     # and not yet returned.
2992
2993     # FIXME - I think this function could be redone to use only one SQL call.
2994     my $sth = $dbh->prepare(
2995         "select * from issues
2996                                 where (borrowernumber = ?)
2997                                 and (itemnumber = ?)"
2998     );
2999     $sth->execute( $bornum, $itemno );
3000     my $data = $sth->fetchrow_hashref;
3001     $renewcount = $data->{'renewals'} if $data->{'renewals'};
3002     # $item and $borrower should be calculated
3003     my $branchcode = _GetCircControlBranch($item, $borrower);
3004     
3005     my $issuingrule = GetIssuingRule($borrower->{categorycode}, $item->{itype}, $branchcode);
3006     
3007     $renewsallowed = $issuingrule->{'renewalsallowed'};
3008     $renewsleft    = $renewsallowed - $renewcount;
3009     if($renewsleft < 0){ $renewsleft = 0; }
3010     return ( $renewcount, $renewsallowed, $renewsleft );
3011 }
3012
3013 =head2 GetSoonestRenewDate
3014
3015   $NoRenewalBeforeThisDate = &GetSoonestRenewDate($borrowernumber, $itemnumber);
3016
3017 Find out the soonest possible renew date of a borrowed item.
3018
3019 C<$borrowernumber> is the borrower number of the patron who currently
3020 has the item on loan.
3021
3022 C<$itemnumber> is the number of the item to renew.
3023
3024 C<$GetSoonestRenewDate> returns the DateTime of the soonest possible
3025 renew date, based on the value "No renewal before" of the applicable
3026 issuing rule. Returns the current date if the item can already be
3027 renewed, and returns undefined if the borrower, loan, or item
3028 cannot be found.
3029
3030 =cut
3031
3032 sub GetSoonestRenewDate {
3033     my ( $borrowernumber, $itemnumber ) = @_;
3034
3035     my $dbh = C4::Context->dbh;
3036
3037     my $item      = GetItem($itemnumber)      or return;
3038     my $itemissue = GetItemIssue($itemnumber) or return;
3039
3040     $borrowernumber ||= $itemissue->{borrowernumber};
3041     my $borrower = C4::Members::GetMemberDetails($borrowernumber)
3042       or return;
3043
3044     my $branchcode = _GetCircControlBranch( $item, $borrower );
3045     my $issuingrule =
3046       GetIssuingRule( $borrower->{categorycode}, $item->{itype}, $branchcode );
3047
3048     my $now = DateTime->now( time_zone => C4::Context->tz() );
3049
3050     if ( $issuingrule->{norenewalbefore} ) {
3051         my $soonestrenewal =
3052           $itemissue->{date_due}->subtract(
3053             $issuingrule->{lengthunit} => $issuingrule->{norenewalbefore} );
3054
3055         $soonestrenewal = $now > $soonestrenewal ? $now : $soonestrenewal;
3056         return $soonestrenewal;
3057     }
3058     return $now;
3059 }
3060
3061 =head2 GetIssuingCharges
3062
3063   ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
3064
3065 Calculate how much it would cost for a given patron to borrow a given
3066 item, including any applicable discounts.
3067
3068 C<$itemnumber> is the item number of item the patron wishes to borrow.
3069
3070 C<$borrowernumber> is the patron's borrower number.
3071
3072 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
3073 and C<$item_type> is the code for the item's item type (e.g., C<VID>
3074 if it's a video).
3075
3076 =cut
3077
3078 sub GetIssuingCharges {
3079
3080     # calculate charges due
3081     my ( $itemnumber, $borrowernumber ) = @_;
3082     my $charge = 0;
3083     my $dbh    = C4::Context->dbh;
3084     my $item_type;
3085
3086     # Get the book's item type and rental charge (via its biblioitem).
3087     my $charge_query = 'SELECT itemtypes.itemtype,rentalcharge FROM items
3088         LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber';
3089     $charge_query .= (C4::Context->preference('item-level_itypes'))
3090         ? ' LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype'
3091         : ' LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype';
3092
3093     $charge_query .= ' WHERE items.itemnumber =?';
3094
3095     my $sth = $dbh->prepare($charge_query);
3096     $sth->execute($itemnumber);
3097     if ( my $item_data = $sth->fetchrow_hashref ) {
3098         $item_type = $item_data->{itemtype};
3099         $charge    = $item_data->{rentalcharge};
3100         my $branch = C4::Branch::mybranch();
3101         my $discount_query = q|SELECT rentaldiscount,
3102             issuingrules.itemtype, issuingrules.branchcode
3103             FROM borrowers
3104             LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
3105             WHERE borrowers.borrowernumber = ?
3106             AND (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
3107             AND (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')|;
3108         my $discount_sth = $dbh->prepare($discount_query);
3109         $discount_sth->execute( $borrowernumber, $item_type, $branch );
3110         my $discount_rules = $discount_sth->fetchall_arrayref({});
3111         if (@{$discount_rules}) {
3112             # We may have multiple rules so get the most specific
3113             my $discount = _get_discount_from_rule($discount_rules, $branch, $item_type);
3114             $charge = ( $charge * ( 100 - $discount ) ) / 100;
3115         }
3116     }
3117
3118     return ( $charge, $item_type );
3119 }
3120
3121 # Select most appropriate discount rule from those returned
3122 sub _get_discount_from_rule {
3123     my ($rules_ref, $branch, $itemtype) = @_;
3124     my $discount;
3125
3126     if (@{$rules_ref} == 1) { # only 1 applicable rule use it
3127         $discount = $rules_ref->[0]->{rentaldiscount};
3128         return (defined $discount) ? $discount : 0;
3129     }
3130     # could have up to 4 does one match $branch and $itemtype
3131     my @d = grep { $_->{branchcode} eq $branch && $_->{itemtype} eq $itemtype } @{$rules_ref};
3132     if (@d) {
3133         $discount = $d[0]->{rentaldiscount};
3134         return (defined $discount) ? $discount : 0;
3135     }
3136     # do we have item type + all branches
3137     @d = grep { $_->{branchcode} eq q{*} && $_->{itemtype} eq $itemtype } @{$rules_ref};
3138     if (@d) {
3139         $discount = $d[0]->{rentaldiscount};
3140         return (defined $discount) ? $discount : 0;
3141     }
3142     # do we all item types + this branch
3143     @d = grep { $_->{branchcode} eq $branch && $_->{itemtype} eq q{*} } @{$rules_ref};
3144     if (@d) {
3145         $discount = $d[0]->{rentaldiscount};
3146         return (defined $discount) ? $discount : 0;
3147     }
3148     # so all and all (surely we wont get here)
3149     @d = grep { $_->{branchcode} eq q{*} && $_->{itemtype} eq q{*} } @{$rules_ref};
3150     if (@d) {
3151         $discount = $d[0]->{rentaldiscount};
3152         return (defined $discount) ? $discount : 0;
3153     }
3154     # none of the above
3155     return 0;
3156 }
3157
3158 =head2 AddIssuingCharge
3159
3160   &AddIssuingCharge( $itemno, $borrowernumber, $charge )
3161
3162 =cut
3163
3164 sub AddIssuingCharge {
3165     my ( $itemnumber, $borrowernumber, $charge ) = @_;
3166     my $dbh = C4::Context->dbh;
3167     my $nextaccntno = getnextacctno( $borrowernumber );
3168     my $manager_id = 0;
3169     $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
3170     my $query ="
3171         INSERT INTO accountlines
3172             (borrowernumber, itemnumber, accountno,
3173             date, amount, description, accounttype,
3174             amountoutstanding, manager_id)
3175         VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?,?)
3176     ";
3177     my $sth = $dbh->prepare($query);
3178     $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge, $manager_id );
3179 }
3180
3181 =head2 GetTransfers
3182
3183   GetTransfers($itemnumber);
3184
3185 =cut
3186
3187 sub GetTransfers {
3188     my ($itemnumber) = @_;
3189
3190     my $dbh = C4::Context->dbh;
3191
3192     my $query = '
3193         SELECT datesent,
3194                frombranch,
3195                tobranch
3196         FROM branchtransfers
3197         WHERE itemnumber = ?
3198           AND datearrived IS NULL
3199         ';
3200     my $sth = $dbh->prepare($query);
3201     $sth->execute($itemnumber);
3202     my @row = $sth->fetchrow_array();
3203     return @row;
3204 }
3205
3206 =head2 GetTransfersFromTo
3207
3208   @results = GetTransfersFromTo($frombranch,$tobranch);
3209
3210 Returns the list of pending transfers between $from and $to branch
3211
3212 =cut
3213
3214 sub GetTransfersFromTo {
3215     my ( $frombranch, $tobranch ) = @_;
3216     return unless ( $frombranch && $tobranch );
3217     my $dbh   = C4::Context->dbh;
3218     my $query = "
3219         SELECT itemnumber,datesent,frombranch
3220         FROM   branchtransfers
3221         WHERE  frombranch=?
3222           AND  tobranch=?
3223           AND datearrived IS NULL
3224     ";
3225     my $sth = $dbh->prepare($query);
3226     $sth->execute( $frombranch, $tobranch );
3227     my @gettransfers;
3228
3229     while ( my $data = $sth->fetchrow_hashref ) {
3230         push @gettransfers, $data;
3231     }
3232     return (@gettransfers);
3233 }
3234
3235 =head2 DeleteTransfer
3236
3237   &DeleteTransfer($itemnumber);
3238
3239 =cut
3240
3241 sub DeleteTransfer {
3242     my ($itemnumber) = @_;
3243     return unless $itemnumber;
3244     my $dbh          = C4::Context->dbh;
3245     my $sth          = $dbh->prepare(
3246         "DELETE FROM branchtransfers
3247          WHERE itemnumber=?
3248          AND datearrived IS NULL "
3249     );
3250     return $sth->execute($itemnumber);
3251 }
3252
3253 =head2 AnonymiseIssueHistory
3254
3255   ($rows,$err_history_not_deleted) = AnonymiseIssueHistory($date,$borrowernumber)
3256
3257 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
3258 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
3259
3260 If c<$borrowernumber> is set, it will delete issue history for only that borrower, regardless of their opac privacy
3261 setting (force delete).
3262
3263 return the number of affected rows and a value that evaluates to true if an error occurred deleting the history.
3264
3265 =cut
3266
3267 sub AnonymiseIssueHistory {
3268     my $date           = shift;
3269     my $borrowernumber = shift;
3270     my $dbh            = C4::Context->dbh;
3271     my $query          = "
3272         UPDATE old_issues
3273         SET    borrowernumber = ?
3274         WHERE  returndate < ?
3275           AND borrowernumber IS NOT NULL
3276     ";
3277
3278     # The default of 0 does not work due to foreign key constraints
3279     # The anonymisation should not fail quietly if AnonymousPatron is not a valid entry
3280     # Set it to undef (NULL)
3281     my $anonymouspatron = C4::Context->preference('AnonymousPatron') || undef;
3282     my @bind_params = ($anonymouspatron, $date);
3283     if (defined $borrowernumber) {
3284        $query .= " AND borrowernumber = ?";
3285        push @bind_params, $borrowernumber;
3286     } else {
3287        $query .= " AND (SELECT privacy FROM borrowers WHERE borrowers.borrowernumber=old_issues.borrowernumber) <> 0";
3288     }
3289     my $sth = $dbh->prepare($query);
3290     $sth->execute(@bind_params);
3291     my $anonymisation_err = $dbh->err;
3292     my $rows_affected = $sth->rows;  ### doublecheck row count return function
3293     return ($rows_affected, $anonymisation_err);
3294 }
3295
3296 =head2 SendCirculationAlert
3297
3298 Send out a C<check-in> or C<checkout> alert using the messaging system.
3299
3300 B<Parameters>:
3301
3302 =over 4
3303
3304 =item type
3305
3306 Valid values for this parameter are: C<CHECKIN> and C<CHECKOUT>.
3307
3308 =item item
3309
3310 Hashref of information about the item being checked in or out.
3311
3312 =item borrower
3313
3314 Hashref of information about the borrower of the item.
3315
3316 =item branch
3317
3318 The branchcode from where the checkout or check-in took place.
3319
3320 =back
3321
3322 B<Example>:
3323
3324     SendCirculationAlert({
3325         type     => 'CHECKOUT',
3326         item     => $item,
3327         borrower => $borrower,
3328         branch   => $branch,
3329     });
3330
3331 =cut
3332
3333 sub SendCirculationAlert {
3334     my ($opts) = @_;
3335     my ($type, $item, $borrower, $branch) =
3336         ($opts->{type}, $opts->{item}, $opts->{borrower}, $opts->{branch});
3337     my %message_name = (
3338         CHECKIN  => 'Item_Check_in',
3339         CHECKOUT => 'Item_Checkout',
3340         RENEWAL  => 'Item_Checkout',
3341     );
3342     my $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences({
3343         borrowernumber => $borrower->{borrowernumber},
3344         message_name   => $message_name{$type},
3345     });
3346     my $issues_table = ( $type eq 'CHECKOUT' || $type eq 'RENEWAL' ) ? 'issues' : 'old_issues';
3347
3348     my @transports = keys %{ $borrower_preferences->{transports} };
3349     # warn "no transports" unless @transports;
3350     for (@transports) {
3351         # warn "transport: $_";
3352         my $message = C4::Message->find_last_message($borrower, $type, $_);
3353         if (!$message) {
3354             #warn "create new message";
3355             my $letter =  C4::Letters::GetPreparedLetter (
3356                 module => 'circulation',
3357                 letter_code => $type,
3358                 branchcode => $branch,
3359                 message_transport_type => $_,
3360                 tables => {
3361                     $issues_table => $item->{itemnumber},
3362                     'items'       => $item->{itemnumber},
3363                     'biblio'      => $item->{biblionumber},
3364                     'biblioitems' => $item->{biblionumber},
3365                     'borrowers'   => $borrower,
3366                     'branches'    => $branch,
3367                 }
3368             ) or next;
3369             C4::Message->enqueue($letter, $borrower, $_);
3370         } else {
3371             #warn "append to old message";
3372             my $letter =  C4::Letters::GetPreparedLetter (
3373                 module => 'circulation',
3374                 letter_code => $type,
3375                 branchcode => $branch,
3376                 message_transport_type => $_,
3377                 tables => {
3378                     $issues_table => $item->{itemnumber},
3379                     'items'       => $item->{itemnumber},
3380                     'biblio'      => $item->{biblionumber},
3381                     'biblioitems' => $item->{biblionumber},
3382                     'borrowers'   => $borrower,
3383                     'branches'    => $branch,
3384                 }
3385             ) or next;
3386             $message->append($letter);
3387             $message->update;
3388         }
3389     }
3390
3391     return;
3392 }
3393
3394 =head2 updateWrongTransfer
3395
3396   $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
3397
3398 This function validate the line of brachtransfer but with the wrong destination (mistake from a librarian ...), and create a new line in branchtransfer from the actual library to the original library of reservation 
3399
3400 =cut
3401
3402 sub updateWrongTransfer {
3403         my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
3404         my $dbh = C4::Context->dbh;     
3405 # first step validate the actual line of transfert .
3406         my $sth =
3407                 $dbh->prepare(
3408                         "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
3409                 );
3410                 $sth->execute($FromLibrary,$itemNumber);
3411
3412 # second step create a new line of branchtransfer to the right location .
3413         ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
3414
3415 #third step changing holdingbranch of item
3416         UpdateHoldingbranch($FromLibrary,$itemNumber);
3417 }
3418
3419 =head2 UpdateHoldingbranch
3420
3421   $items = UpdateHoldingbranch($branch,$itmenumber);
3422
3423 Simple methode for updating hodlingbranch in items BDD line
3424
3425 =cut
3426
3427 sub UpdateHoldingbranch {
3428         my ( $branch,$itemnumber ) = @_;
3429     ModItem({ holdingbranch => $branch }, undef, $itemnumber);
3430 }
3431
3432 =head2 CalcDateDue
3433
3434 $newdatedue = CalcDateDue($startdate,$itemtype,$branchcode,$borrower);
3435
3436 this function calculates the due date given the start date and configured circulation rules,
3437 checking against the holidays calendar as per the 'useDaysMode' syspref.
3438 C<$startdate>   = C4::Dates object representing start date of loan period (assumed to be today)
3439 C<$itemtype>  = itemtype code of item in question
3440 C<$branch>  = location whose calendar to use
3441 C<$borrower> = Borrower object
3442 C<$isrenewal> = Boolean: is true if we want to calculate the date due for a renewal. Else is false.
3443
3444 =cut
3445
3446 sub CalcDateDue {
3447     my ( $startdate, $itemtype, $branch, $borrower, $isrenewal ) = @_;
3448
3449     $isrenewal ||= 0;
3450
3451     # loanlength now a href
3452     my $loanlength =
3453             GetLoanLength( $borrower->{'categorycode'}, $itemtype, $branch );
3454
3455     my $length_key = ( $isrenewal and defined $loanlength->{renewalperiod} )
3456             ? qq{renewalperiod}
3457             : qq{issuelength};
3458
3459     my $datedue;
3460     if ( $startdate ) {
3461         if (ref $startdate ne 'DateTime' ) {
3462             $datedue = dt_from_string($datedue);
3463         } else {
3464             $datedue = $startdate->clone;
3465         }
3466     } else {
3467         $datedue =
3468           DateTime->now( time_zone => C4::Context->tz() )
3469           ->truncate( to => 'minute' );
3470     }
3471
3472
3473     # calculate the datedue as normal
3474     if ( C4::Context->preference('useDaysMode') eq 'Days' )
3475     {    # ignoring calendar
3476         if ( $loanlength->{lengthunit} eq 'hours' ) {
3477             $datedue->add( hours => $loanlength->{$length_key} );
3478         } else {    # days
3479             $datedue->add( days => $loanlength->{$length_key} );
3480             $datedue->set_hour(23);
3481             $datedue->set_minute(59);
3482         }
3483     } else {
3484         my $dur;
3485         if ($loanlength->{lengthunit} eq 'hours') {
3486             $dur = DateTime::Duration->new( hours => $loanlength->{$length_key});
3487         }
3488         else { # days
3489             $dur = DateTime::Duration->new( days => $loanlength->{$length_key});
3490         }
3491         my $calendar = Koha::Calendar->new( branchcode => $branch );
3492         $datedue = $calendar->addDate( $datedue, $dur, $loanlength->{lengthunit} );
3493         if ($loanlength->{lengthunit} eq 'days') {
3494             $datedue->set_hour(23);
3495             $datedue->set_minute(59);
3496         }
3497     }
3498
3499     # if Hard Due Dates are used, retrieve them and apply as necessary
3500     my ( $hardduedate, $hardduedatecompare ) =
3501       GetHardDueDate( $borrower->{'categorycode'}, $itemtype, $branch );
3502     if ($hardduedate) {    # hardduedates are currently dates
3503         $hardduedate->truncate( to => 'minute' );
3504         $hardduedate->set_hour(23);
3505         $hardduedate->set_minute(59);
3506         my $cmp = DateTime->compare( $hardduedate, $datedue );
3507
3508 # if the calculated due date is after the 'before' Hard Due Date (ceiling), override
3509 # if the calculated date is before the 'after' Hard Due Date (floor), override
3510 # if the hard due date is set to 'exactly', overrride
3511         if ( $hardduedatecompare == 0 || $hardduedatecompare == $cmp ) {
3512             $datedue = $hardduedate->clone;
3513         }
3514
3515         # in all other cases, keep the date due as it is
3516
3517     }
3518
3519     # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
3520     if ( C4::Context->preference('ReturnBeforeExpiry') ) {
3521         my $expiry_dt = dt_from_string( $borrower->{dateexpiry}, 'iso', 'floating');
3522         if( $expiry_dt ) { #skip empty expiry date..
3523             $expiry_dt->set( hour => 23, minute => 59);
3524             my $d1= $datedue->clone->set_time_zone('floating');
3525             if ( DateTime->compare( $d1, $expiry_dt ) == 1 ) {
3526                 $datedue = $expiry_dt->clone->set_time_zone( C4::Context->tz );
3527             }
3528         }
3529     }
3530
3531     return $datedue;
3532 }
3533
3534
3535 =head2 CheckRepeatableHolidays
3536
3537   $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
3538
3539 This function checks if the date due is a repeatable holiday
3540
3541 C<$date_due>   = returndate calculate with no day check
3542 C<$itemnumber>  = itemnumber
3543 C<$branchcode>  = localisation of issue 
3544
3545 =cut
3546
3547 sub CheckRepeatableHolidays{
3548 my($itemnumber,$week_day,$branchcode)=@_;
3549 my $dbh = C4::Context->dbh;
3550 my $query = qq|SELECT count(*)  
3551         FROM repeatable_holidays 
3552         WHERE branchcode=?
3553         AND weekday=?|;
3554 my $sth = $dbh->prepare($query);
3555 $sth->execute($branchcode,$week_day);
3556 my $result=$sth->fetchrow;
3557 return $result;
3558 }
3559
3560
3561 =head2 CheckSpecialHolidays
3562
3563   $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
3564
3565 This function check if the date is a special holiday
3566
3567 C<$years>   = the years of datedue
3568 C<$month>   = the month of datedue
3569 C<$day>     = the day of datedue
3570 C<$itemnumber>  = itemnumber
3571 C<$branchcode>  = localisation of issue 
3572
3573 =cut
3574
3575 sub CheckSpecialHolidays{
3576 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
3577 my $dbh = C4::Context->dbh;
3578 my $query=qq|SELECT count(*) 
3579              FROM `special_holidays`
3580              WHERE year=?
3581              AND month=?
3582              AND day=?
3583              AND branchcode=?
3584             |;
3585 my $sth = $dbh->prepare($query);
3586 $sth->execute($years,$month,$day,$branchcode);
3587 my $countspecial=$sth->fetchrow ;
3588 return $countspecial;
3589 }
3590
3591 =head2 CheckRepeatableSpecialHolidays
3592
3593   $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
3594
3595 This function check if the date is a repeatble special holidays
3596
3597 C<$month>   = the month of datedue
3598 C<$day>     = the day of datedue
3599 C<$itemnumber>  = itemnumber
3600 C<$branchcode>  = localisation of issue 
3601
3602 =cut
3603
3604 sub CheckRepeatableSpecialHolidays{
3605 my ($month,$day,$itemnumber,$branchcode) = @_;
3606 my $dbh = C4::Context->dbh;
3607 my $query=qq|SELECT count(*) 
3608              FROM `repeatable_holidays`
3609              WHERE month=?
3610              AND day=?
3611              AND branchcode=?
3612             |;
3613 my $sth = $dbh->prepare($query);
3614 $sth->execute($month,$day,$branchcode);
3615 my $countspecial=$sth->fetchrow ;
3616 return $countspecial;
3617 }
3618
3619
3620
3621 sub CheckValidBarcode{
3622 my ($barcode) = @_;
3623 my $dbh = C4::Context->dbh;
3624 my $query=qq|SELECT count(*) 
3625              FROM items 
3626              WHERE barcode=?
3627             |;
3628 my $sth = $dbh->prepare($query);
3629 $sth->execute($barcode);
3630 my $exist=$sth->fetchrow ;
3631 return $exist;
3632 }
3633
3634 =head2 IsBranchTransferAllowed
3635
3636   $allowed = IsBranchTransferAllowed( $toBranch, $fromBranch, $code );
3637
3638 Code is either an itemtype or collection doe depending on the pref BranchTransferLimitsType
3639
3640 =cut
3641
3642 sub IsBranchTransferAllowed {
3643         my ( $toBranch, $fromBranch, $code ) = @_;
3644
3645         if ( $toBranch eq $fromBranch ) { return 1; } ## Short circuit for speed.
3646         
3647         my $limitType = C4::Context->preference("BranchTransferLimitsType");   
3648         my $dbh = C4::Context->dbh;
3649             
3650         my $sth = $dbh->prepare("SELECT * FROM branch_transfer_limits WHERE toBranch = ? AND fromBranch = ? AND $limitType = ?");
3651         $sth->execute( $toBranch, $fromBranch, $code );
3652         my $limit = $sth->fetchrow_hashref();
3653                         
3654         ## If a row is found, then that combination is not allowed, if no matching row is found, then the combination *is allowed*
3655         if ( $limit->{'limitId'} ) {
3656                 return 0;
3657         } else {
3658                 return 1;
3659         }
3660 }                                                        
3661
3662 =head2 CreateBranchTransferLimit
3663
3664   CreateBranchTransferLimit( $toBranch, $fromBranch, $code );
3665
3666 $code is either itemtype or collection code depending on what the pref BranchTransferLimitsType is set to.
3667
3668 =cut
3669
3670 sub CreateBranchTransferLimit {
3671    my ( $toBranch, $fromBranch, $code ) = @_;
3672    return unless defined($toBranch) && defined($fromBranch);
3673    my $limitType = C4::Context->preference("BranchTransferLimitsType");
3674    
3675    my $dbh = C4::Context->dbh;
3676    
3677    my $sth = $dbh->prepare("INSERT INTO branch_transfer_limits ( $limitType, toBranch, fromBranch ) VALUES ( ?, ?, ? )");
3678    return $sth->execute( $code, $toBranch, $fromBranch );
3679 }
3680
3681 =head2 DeleteBranchTransferLimits
3682
3683     my $result = DeleteBranchTransferLimits($frombranch);
3684
3685 Deletes all the library transfer limits for one library.  Returns the
3686 number of limits deleted, 0e0 if no limits were deleted, or undef if
3687 no arguments are supplied.
3688
3689 =cut
3690
3691 sub DeleteBranchTransferLimits {
3692     my $branch = shift;
3693     return unless defined $branch;
3694     my $dbh    = C4::Context->dbh;
3695     my $sth    = $dbh->prepare("DELETE FROM branch_transfer_limits WHERE fromBranch = ?");
3696     return $sth->execute($branch);
3697 }
3698
3699 sub ReturnLostItem{
3700     my ( $borrowernumber, $itemnum ) = @_;
3701
3702     MarkIssueReturned( $borrowernumber, $itemnum );
3703     my $borrower = C4::Members::GetMember( 'borrowernumber'=>$borrowernumber );
3704     my $item = C4::Items::GetItem( $itemnum );
3705     my $old_note = ($item->{'paidfor'} && ($item->{'paidfor'} ne q{})) ? $item->{'paidfor'}.' / ' : q{};
3706     my @datearr = localtime(time);
3707     my $date = ( 1900 + $datearr[5] ) . "-" . ( $datearr[4] + 1 ) . "-" . $datearr[3];
3708     my $bor = "$borrower->{'firstname'} $borrower->{'surname'} $borrower->{'cardnumber'}";
3709     ModItem({ paidfor =>  $old_note."Paid for by $bor $date" }, undef, $itemnum);
3710 }
3711
3712
3713 sub LostItem{
3714     my ($itemnumber, $mark_returned) = @_;
3715
3716     my $dbh = C4::Context->dbh();
3717     my $sth=$dbh->prepare("SELECT issues.*,items.*,biblio.title 
3718                            FROM issues 
3719                            JOIN items USING (itemnumber) 
3720                            JOIN biblio USING (biblionumber)
3721                            WHERE issues.itemnumber=?");
3722     $sth->execute($itemnumber);
3723     my $issues=$sth->fetchrow_hashref();
3724
3725     # If a borrower lost the item, add a replacement cost to the their record
3726     if ( my $borrowernumber = $issues->{borrowernumber} ){
3727         my $borrower = C4::Members::GetMemberDetails( $borrowernumber );
3728
3729         if (C4::Context->preference('WhenLostForgiveFine')){
3730             my $fix = _FixOverduesOnReturn($borrowernumber, $itemnumber, 1, 0); # 1, 0 = exemptfine, no-dropbox
3731             defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $itemnumber...) failed!";  # zero is OK, check defined
3732         }
3733         if (C4::Context->preference('WhenLostChargeReplacementFee')){
3734             C4::Accounts::chargelostitem($borrowernumber, $itemnumber, $issues->{'replacementprice'}, "Lost Item $issues->{'title'} $issues->{'barcode'}");
3735             #FIXME : Should probably have a way to distinguish this from an item that really was returned.
3736             #warn " $issues->{'borrowernumber'}  /  $itemnumber ";
3737         }
3738
3739         MarkIssueReturned($borrowernumber,$itemnumber,undef,undef,$borrower->{'privacy'}) if $mark_returned;
3740     }
3741 }
3742
3743 sub GetOfflineOperations {
3744     my $dbh = C4::Context->dbh;
3745     my $sth = $dbh->prepare("SELECT * FROM pending_offline_operations WHERE branchcode=? ORDER BY timestamp");
3746     $sth->execute(C4::Context->userenv->{'branch'});
3747     my $results = $sth->fetchall_arrayref({});
3748     return $results;
3749 }
3750
3751 sub GetOfflineOperation {
3752     my $operationid = shift;
3753     return unless $operationid;
3754     my $dbh = C4::Context->dbh;
3755     my $sth = $dbh->prepare("SELECT * FROM pending_offline_operations WHERE operationid=?");
3756     $sth->execute( $operationid );
3757     return $sth->fetchrow_hashref;
3758 }
3759
3760 sub AddOfflineOperation {
3761     my ( $userid, $branchcode, $timestamp, $action, $barcode, $cardnumber, $amount ) = @_;
3762     my $dbh = C4::Context->dbh;
3763     my $sth = $dbh->prepare("INSERT INTO pending_offline_operations (userid, branchcode, timestamp, action, barcode, cardnumber, amount) VALUES(?,?,?,?,?,?,?)");
3764     $sth->execute( $userid, $branchcode, $timestamp, $action, $barcode, $cardnumber, $amount );
3765     return "Added.";
3766 }
3767
3768 sub DeleteOfflineOperation {
3769     my $dbh = C4::Context->dbh;
3770     my $sth = $dbh->prepare("DELETE FROM pending_offline_operations WHERE operationid=?");
3771     $sth->execute( shift );
3772     return "Deleted.";
3773 }
3774
3775 sub ProcessOfflineOperation {
3776     my $operation = shift;
3777
3778     my $report;
3779     if ( $operation->{action} eq 'return' ) {
3780         $report = ProcessOfflineReturn( $operation );
3781     } elsif ( $operation->{action} eq 'issue' ) {
3782         $report = ProcessOfflineIssue( $operation );
3783     } elsif ( $operation->{action} eq 'payment' ) {
3784         $report = ProcessOfflinePayment( $operation );
3785     }
3786
3787     DeleteOfflineOperation( $operation->{operationid} ) if $operation->{operationid};
3788
3789     return $report;
3790 }
3791
3792 sub ProcessOfflineReturn {
3793     my $operation = shift;
3794
3795     my $itemnumber = C4::Items::GetItemnumberFromBarcode( $operation->{barcode} );
3796
3797     if ( $itemnumber ) {
3798         my $issue = GetOpenIssue( $itemnumber );
3799         if ( $issue ) {
3800             MarkIssueReturned(
3801                 $issue->{borrowernumber},
3802                 $itemnumber,
3803                 undef,
3804                 $operation->{timestamp},
3805             );
3806             ModItem(
3807                 { renewals => 0, onloan => undef },
3808                 $issue->{'biblionumber'},
3809                 $itemnumber
3810             );
3811             return "Success.";
3812         } else {
3813             return "Item not issued.";
3814         }
3815     } else {
3816         return "Item not found.";
3817     }
3818 }
3819
3820 sub ProcessOfflineIssue {
3821     my $operation = shift;
3822
3823     my $borrower = C4::Members::GetMemberDetails( undef, $operation->{cardnumber} ); # Get borrower from operation cardnumber
3824
3825     if ( $borrower->{borrowernumber} ) {
3826         my $itemnumber = C4::Items::GetItemnumberFromBarcode( $operation->{barcode} );
3827         unless ($itemnumber) {
3828             return "Barcode not found.";
3829         }
3830         my $issue = GetOpenIssue( $itemnumber );
3831
3832         if ( $issue and ( $issue->{borrowernumber} ne $borrower->{borrowernumber} ) ) { # Item already issued to another borrower, mark it returned
3833             MarkIssueReturned(
3834                 $issue->{borrowernumber},
3835                 $itemnumber,
3836                 undef,
3837                 $operation->{timestamp},
3838             );
3839         }
3840         AddIssue(
3841             $borrower,
3842             $operation->{'barcode'},
3843             undef,
3844             1,
3845             $operation->{timestamp},
3846             undef,
3847         );
3848         return "Success.";
3849     } else {
3850         return "Borrower not found.";
3851     }
3852 }
3853
3854 sub ProcessOfflinePayment {
3855     my $operation = shift;
3856
3857     my $borrower = C4::Members::GetMemberDetails( undef, $operation->{cardnumber} ); # Get borrower from operation cardnumber
3858     my $amount = $operation->{amount};
3859
3860     recordpayment( $borrower->{borrowernumber}, $amount );
3861
3862     return "Success."
3863 }
3864
3865
3866 =head2 TransferSlip
3867
3868   TransferSlip($user_branch, $itemnumber, $barcode, $to_branch)
3869
3870   Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
3871
3872 =cut
3873
3874 sub TransferSlip {
3875     my ($branch, $itemnumber, $barcode, $to_branch) = @_;
3876
3877     my $item =  GetItem( $itemnumber, $barcode )
3878       or return;
3879
3880     my $pulldate = C4::Dates->new();
3881
3882     return C4::Letters::GetPreparedLetter (
3883         module => 'circulation',
3884         letter_code => 'TRANSFERSLIP',
3885         branchcode => $branch,
3886         tables => {
3887             'branches'    => $to_branch,
3888             'biblio'      => $item->{biblionumber},
3889             'items'       => $item,
3890         },
3891     );
3892 }
3893
3894 =head2 CheckIfIssuedToPatron
3895
3896   CheckIfIssuedToPatron($borrowernumber, $biblionumber)
3897
3898   Return 1 if any record item is issued to patron, otherwise return 0
3899
3900 =cut
3901
3902 sub CheckIfIssuedToPatron {
3903     my ($borrowernumber, $biblionumber) = @_;
3904
3905     my $dbh = C4::Context->dbh;
3906     my $query = q|
3907         SELECT COUNT(*) FROM issues
3908         LEFT JOIN items ON items.itemnumber = issues.itemnumber
3909         WHERE items.biblionumber = ?
3910         AND issues.borrowernumber = ?
3911     |;
3912     my $is_issued = $dbh->selectrow_array($query, {}, $biblionumber, $borrowernumber );
3913     return 1 if $is_issued;
3914     return;
3915 }
3916
3917 =head2 IsItemIssued
3918
3919   IsItemIssued( $itemnumber )
3920
3921   Return 1 if the item is on loan, otherwise return 0
3922
3923 =cut
3924
3925 sub IsItemIssued {
3926     my $itemnumber = shift;
3927     my $dbh = C4::Context->dbh;
3928     my $sth = $dbh->prepare(q{
3929         SELECT COUNT(*)
3930         FROM issues
3931         WHERE itemnumber = ?
3932     });
3933     $sth->execute($itemnumber);
3934     return $sth->fetchrow;
3935 }
3936
3937 =head2 GetAgeRestriction
3938
3939   my ($ageRestriction, $daysToAgeRestriction) = GetAgeRestriction($record_restrictions, $borrower);
3940   my ($ageRestriction, $daysToAgeRestriction) = GetAgeRestriction($record_restrictions);
3941
3942   if($daysToAgeRestriction <= 0) { #Borrower is allowed to access this material, as he is older or as old as the agerestriction }
3943   if($daysToAgeRestriction > 0) { #Borrower is this many days from meeting the agerestriction }
3944
3945 @PARAM1 the koha.biblioitems.agerestriction value, like K18, PEGI 13, ...
3946 @PARAM2 a borrower-object with koha.borrowers.dateofbirth. (OPTIONAL)
3947 @RETURNS The age restriction age in years and the days to fulfill the age restriction for the given borrower.
3948          Negative days mean the borrower has gone past the age restriction age.
3949
3950 =cut
3951
3952 sub GetAgeRestriction {
3953     my ($record_restrictions, $borrower) = @_;
3954     my $markers = C4::Context->preference('AgeRestrictionMarker');
3955
3956     # Split $record_restrictions to something like FSK 16 or PEGI 6
3957     my @values = split ' ', uc($record_restrictions);
3958     return unless @values;
3959
3960     # Search first occurrence of one of the markers
3961     my @markers = split /\|/, uc($markers);
3962     return unless @markers;
3963
3964     my $index            = 0;
3965     my $restriction_year = 0;
3966     for my $value (@values) {
3967         $index++;
3968         for my $marker (@markers) {
3969             $marker =~ s/^\s+//;    #remove leading spaces
3970             $marker =~ s/\s+$//;    #remove trailing spaces
3971             if ( $marker eq $value ) {
3972                 if ( $index <= $#values ) {
3973                     $restriction_year += $values[$index];
3974                 }
3975                 last;
3976             }
3977             elsif ( $value =~ /^\Q$marker\E(\d+)$/ ) {
3978
3979                 # Perhaps it is something like "K16" (as in Finland)
3980                 $restriction_year += $1;
3981                 last;
3982             }
3983         }
3984         last if ( $restriction_year > 0 );
3985     }
3986
3987     #Check if the borrower is age restricted for this material and for how long.
3988     if ($restriction_year && $borrower) {
3989         if ( $borrower->{'dateofbirth'} ) {
3990             my @alloweddate = split /-/, $borrower->{'dateofbirth'};
3991             $alloweddate[0] += $restriction_year;
3992
3993             #Prevent runime eror on leap year (invalid date)
3994             if ( ( $alloweddate[1] == 2 ) && ( $alloweddate[2] == 29 ) ) {
3995                 $alloweddate[2] = 28;
3996             }
3997
3998             #Get how many days the borrower has to reach the age restriction
3999             my $daysToAgeRestriction = Date_to_Days(@alloweddate) - Date_to_Days(Today);
4000             #Negative days means the borrower went past the age restriction age
4001             return ($restriction_year, $daysToAgeRestriction);
4002         }
4003     }
4004
4005     return ($restriction_year);
4006 }
4007
4008 1;
4009
4010 =head2 GetPendingOnSiteCheckouts
4011
4012 =cut
4013
4014 sub GetPendingOnSiteCheckouts {
4015     my $dbh = C4::Context->dbh;
4016     return $dbh->selectall_arrayref(q|
4017         SELECT
4018           items.barcode,
4019           items.biblionumber,
4020           items.itemnumber,
4021           items.itemnotes,
4022           items.itemcallnumber,
4023           items.location,
4024           issues.date_due,
4025           issues.branchcode,
4026           issues.date_due < NOW() AS is_overdue,
4027           biblio.author,
4028           biblio.title,
4029           borrowers.firstname,
4030           borrowers.surname,
4031           borrowers.cardnumber,
4032           borrowers.borrowernumber
4033         FROM items
4034         LEFT JOIN issues ON items.itemnumber = issues.itemnumber
4035         LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
4036         LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
4037         WHERE issues.onsite_checkout = 1
4038     |, { Slice => {} } );
4039 }
4040
4041 sub GetTopIssues {
4042     my ($params) = @_;
4043
4044     my ($count, $branch, $itemtype, $ccode, $newness)
4045         = @$params{qw(count branch itemtype ccode newness)};
4046
4047     my $dbh = C4::Context->dbh;
4048     my $query = q{
4049         SELECT b.biblionumber, b.title, b.author, bi.itemtype, bi.publishercode,
4050           bi.place, bi.publicationyear, b.copyrightdate, bi.pages, bi.size,
4051           i.ccode, SUM(i.issues) AS count
4052         FROM biblio b
4053         LEFT JOIN items i ON (i.biblionumber = b.biblionumber)
4054         LEFT JOIN biblioitems bi ON (bi.biblionumber = b.biblionumber)
4055     };
4056
4057     my (@where_strs, @where_args);
4058
4059     if ($branch) {
4060         push @where_strs, 'i.homebranch = ?';
4061         push @where_args, $branch;
4062     }
4063     if ($itemtype) {
4064         if (C4::Context->preference('item-level_itypes')){
4065             push @where_strs, 'i.itype = ?';
4066             push @where_args, $itemtype;
4067         } else {
4068             push @where_strs, 'bi.itemtype = ?';
4069             push @where_args, $itemtype;
4070         }
4071     }
4072     if ($ccode) {
4073         push @where_strs, 'i.ccode = ?';
4074         push @where_args, $ccode;
4075     }
4076     if ($newness) {
4077         push @where_strs, 'TO_DAYS(NOW()) - TO_DAYS(b.datecreated) <= ?';
4078         push @where_args, $newness;
4079     }
4080
4081     if (@where_strs) {
4082         $query .= 'WHERE ' . join(' AND ', @where_strs);
4083     }
4084
4085     $query .= q{
4086         GROUP BY b.biblionumber
4087         HAVING count > 0
4088         ORDER BY count DESC
4089     };
4090
4091     $count = int($count);
4092     if ($count > 0) {
4093         $query .= "LIMIT $count";
4094     }
4095
4096     my $rows = $dbh->selectall_arrayref($query, { Slice => {} }, @where_args);
4097
4098     return @$rows;
4099 }
4100
4101 __END__
4102
4103 =head1 AUTHOR
4104
4105 Koha Development Team <http://koha-community.org/>
4106
4107 =cut
4108