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