Added 'Branch Transfer Limits' Feature requested by Geauga County Library System.
[koha.git] / C4 / Circulation.pm
1 package C4::Circulation;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20
21 use strict;
22 #use warnings;  # soon!
23 use C4::Context;
24 use C4::Stats;
25 use C4::Reserves;
26 use C4::Koha;
27 use C4::Biblio;
28 use C4::Items;
29 use C4::Members;
30 use C4::Dates;
31 use C4::Calendar;
32 use C4::Accounts;
33 use Date::Calc qw(
34   Today
35   Today_and_Now
36   Add_Delta_YM
37   Add_Delta_DHMS
38   Date_to_Days
39   Day_of_Week
40   Add_Delta_Days        
41 );
42 use POSIX qw(strftime);
43 use C4::Branch; # GetBranches
44 use C4::Log; # logaction
45
46 use Data::Dumper;
47
48 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
49
50 BEGIN {
51         require Exporter;
52         $VERSION = 3.02;        # for version checking
53         @ISA    = qw(Exporter);
54
55         # FIXME subs that should probably be elsewhere
56         push @EXPORT, qw(
57                 &FixOverduesOnReturn
58                 &barcodedecode
59         );
60
61         # subs to deal with issuing a book
62         push @EXPORT, qw(
63                 &CanBookBeIssued
64                 &CanBookBeRenewed
65                 &AddIssue
66                 &AddRenewal
67                 &GetRenewCount
68                 &GetItemIssue
69                 &GetOpenIssue
70                 &GetItemIssues
71                 &GetBorrowerIssues
72                 &GetIssuingCharges
73                 &GetIssuingRule
74         &GetBranchBorrowerCircRule
75                 &GetBiblioIssues
76                 &AnonymiseIssueHistory
77         );
78
79         # subs to deal with returns
80         push @EXPORT, qw(
81                 &AddReturn
82         &MarkIssueReturned
83         );
84
85         # subs to deal with transfers
86         push @EXPORT, qw(
87                 &transferbook
88                 &GetTransfers
89                 &GetTransfersFromTo
90                 &updateWrongTransfer
91                 &DeleteTransfer
92                 &IsBranchTransferAllowed
93                 &CreateBranchTransferLimit
94                 &DeleteBranchTransferLimits
95         );
96 }
97
98 =head1 NAME
99
100 C4::Circulation - Koha circulation module
101
102 =head1 SYNOPSIS
103
104 use C4::Circulation;
105
106 =head1 DESCRIPTION
107
108 The functions in this module deal with circulation, issues, and
109 returns, as well as general information about the library.
110 Also deals with stocktaking.
111
112 =head1 FUNCTIONS
113
114 =head2 barcodedecode
115
116 =head3 $str = &barcodedecode($barcode);
117
118 =over 4
119
120 =item Generic filter function for barcode string.
121 Called on every circ if the System Pref itemBarcodeInputFilter is set.
122 Will do some manipulation of the barcode for systems that deliver a barcode
123 to circulation.pl that differs from the barcode stored for the item.
124 For proper functioning of this filter, calling the function on the 
125 correct barcode string (items.barcode) should return an unaltered barcode.
126
127 =back
128
129 =cut
130
131 # FIXME -- the &decode fcn below should be wrapped into this one.
132 # FIXME -- these plugins should be moved out of Circulation.pm
133 #
134 sub barcodedecode {
135     my ($barcode) = @_;
136     my $filter = C4::Context->preference('itemBarcodeInputFilter');
137         if($filter eq 'whitespace') {
138                 $barcode =~ s/\s//g;
139                 return $barcode;
140         } elsif($filter eq 'cuecat') {
141                 chomp($barcode);
142             my @fields = split( /\./, $barcode );
143             my @results = map( decode($_), @fields[ 1 .. $#fields ] );
144             if ( $#results == 2 ) {
145                 return $results[2];
146             }
147             else {
148                 return $barcode;
149             }
150         } elsif($filter eq 'T-prefix') {
151                 if ( $barcode =~ /^[Tt]/) {
152                         if (substr($barcode,1,1) eq '0') {
153                                 return $barcode;
154                         } else {
155                                 $barcode = substr($barcode,2) + 0 ;
156                         }
157                 }
158                 return sprintf( "T%07d",$barcode);
159         }
160 }
161
162 =head2 decode
163
164 =head3 $str = &decode($chunk);
165
166 =over 4
167
168 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
169 returns it.
170
171 =back
172
173 =cut
174
175 sub decode {
176     my ($encoded) = @_;
177     my $seq =
178       'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
179     my @s = map { index( $seq, $_ ); } split( //, $encoded );
180     my $l = ( $#s + 1 ) % 4;
181     if ($l) {
182         if ( $l == 1 ) {
183             warn "Error!";
184             return;
185         }
186         $l = 4 - $l;
187         $#s += $l;
188     }
189     my $r = '';
190     while ( $#s >= 0 ) {
191         my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
192         $r .=
193             chr( ( $n >> 16 ) ^ 67 )
194          .chr( ( $n >> 8 & 255 ) ^ 67 )
195          .chr( ( $n & 255 ) ^ 67 );
196         @s = @s[ 4 .. $#s ];
197     }
198     $r = substr( $r, 0, length($r) - $l );
199     return $r;
200 }
201
202 =head2 transferbook
203
204 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
205
206 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
207
208 C<$newbranch> is the code for the branch to which the item should be transferred.
209
210 C<$barcode> is the barcode of the item to be transferred.
211
212 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
213 Otherwise, if an item is reserved, the transfer fails.
214
215 Returns three values:
216
217 =head3 $dotransfer 
218
219 is true if the transfer was successful.
220
221 =head3 $messages
222
223 is a reference-to-hash which may have any of the following keys:
224
225 =over 4
226
227 =item C<BadBarcode>
228
229 There is no item in the catalog with the given barcode. The value is C<$barcode>.
230
231 =item C<IsPermanent>
232
233 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.
234
235 =item C<DestinationEqualsHolding>
236
237 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.
238
239 =item C<WasReturned>
240
241 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.
242
243 =item C<ResFound>
244
245 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>.
246
247 =item C<WasTransferred>
248
249 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
250
251 =back
252
253 =cut
254
255 sub transferbook {
256     my ( $tbr, $barcode, $ignoreRs ) = @_;
257     my $messages;
258     my $dotransfer      = 1;
259     my $branches        = GetBranches();
260     my $itemnumber = GetItemnumberFromBarcode( $barcode );
261     my $issue      = GetItemIssue($itemnumber);
262     my $biblio = GetBiblioFromItemNumber($itemnumber);
263
264     # bad barcode..
265     if ( not $itemnumber ) {
266         $messages->{'BadBarcode'} = $barcode;
267         $dotransfer = 0;
268     }
269
270     # get branches of book...
271     my $hbr = $biblio->{'homebranch'};
272     my $fbr = $biblio->{'holdingbranch'};
273
274     # if using Branch Transfer Limits
275     if ( C4::Context->preference("UseBranchTransferLimits") == 1 ) {
276         if ( C4::Context->preference("item-level_itypes") ) {
277             if ( ! IsBranchTransferAllowed( $tbr, $fbr, $biblio->{'itype'} ) ) {
278                 $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{'itype'};
279                 $dotransfer = 0;
280             }
281         } elsif ( ! IsBranchTransferAllowed( $tbr, $fbr, $biblio->{'itemtype'} ) ) {
282             $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{'itemtype'};
283             $dotransfer = 0;
284         }
285     }
286
287     # if is permanent...
288     if ( $hbr && $branches->{$hbr}->{'PE'} ) {
289         $messages->{'IsPermanent'} = $hbr;
290         $dotransfer = 0;
291     }
292
293     # can't transfer book if is already there....
294     if ( $fbr eq $tbr ) {
295         $messages->{'DestinationEqualsHolding'} = 1;
296         $dotransfer = 0;
297     }
298
299     # check if it is still issued to someone, return it...
300     if ($issue->{borrowernumber}) {
301         AddReturn( $barcode, $fbr );
302         $messages->{'WasReturned'} = $issue->{borrowernumber};
303     }
304
305     # find reserves.....
306     # That'll save a database query.
307     my ( $resfound, $resrec ) =
308       CheckReserves( $itemnumber );
309     if ( $resfound and not $ignoreRs ) {
310         $resrec->{'ResFound'} = $resfound;
311
312         #         $messages->{'ResFound'} = $resrec;
313         $dotransfer = 1;
314     }
315
316     #actually do the transfer....
317     if ($dotransfer) {
318         ModItemTransfer( $itemnumber, $fbr, $tbr );
319
320         # don't need to update MARC anymore, we do it in batch now
321         $messages->{'WasTransfered'} = 1;
322                 ModDateLastSeen( $itemnumber );
323     }
324     return ( $dotransfer, $messages, $biblio );
325 }
326
327
328 sub TooMany {
329     my $borrower        = shift;
330     my $biblionumber = shift;
331         my $item                = shift;
332     my $cat_borrower    = $borrower->{'categorycode'};
333     my $dbh             = C4::Context->dbh;
334         my $branch;
335         # Get which branchcode we need
336         if (C4::Context->preference('CircControl') eq 'PickupLibrary'){
337                 $branch = C4::Context->userenv->{'branch'}; 
338         }
339         elsif (C4::Context->preference('CircControl') eq 'PatronLibrary'){
340         $branch = $borrower->{'branchcode'}; 
341         }
342         else {
343                 # items home library
344                 $branch = $item->{'homebranch'};
345         }
346         my $type = (C4::Context->preference('item-level_itypes')) 
347                         ? $item->{'itype'}         # item-level
348                         : $item->{'itemtype'};     # biblio-level
349  
350     # given branch, patron category, and item type, determine
351     # applicable issuing rule
352     my $issuing_rule = GetIssuingRule($cat_borrower, $type, $branch);
353
354     # if a rule is found and has a loan limit set, count
355     # how many loans the patron already has that meet that
356     # rule
357     if (defined($issuing_rule) and defined($issuing_rule->{'maxissueqty'})) {
358         my @bind_params;
359         my $count_query = "SELECT COUNT(*) FROM issues
360                            JOIN items USING (itemnumber) ";
361
362         my $rule_itemtype = $issuing_rule->{itemtype};
363         if ($rule_itemtype eq "*") {
364             # matching rule has the default item type, so count only
365             # those existing loans that don't fall under a more
366             # specific rule
367             if (C4::Context->preference('item-level_itypes')) {
368                 $count_query .= " WHERE items.itype NOT IN (
369                                     SELECT itemtype FROM issuingrules
370                                     WHERE branchcode = ?
371                                     AND   (categorycode = ? OR categorycode = ?)
372                                     AND   itemtype <> '*'
373                                   ) ";
374             } else { 
375                 $count_query .= " JOIN  biblioitems USING (biblionumber) 
376                                   WHERE biblioitems.itemtype NOT IN (
377                                     SELECT itemtype FROM issuingrules
378                                     WHERE branchcode = ?
379                                     AND   (categorycode = ? OR categorycode = ?)
380                                     AND   itemtype <> '*'
381                                   ) ";
382             }
383             push @bind_params, $issuing_rule->{branchcode};
384             push @bind_params, $issuing_rule->{categorycode};
385             push @bind_params, $cat_borrower;
386         } else {
387             # rule has specific item type, so count loans of that
388             # specific item type
389             if (C4::Context->preference('item-level_itypes')) {
390                 $count_query .= " WHERE items.itype = ? ";
391             } else { 
392                 $count_query .= " JOIN  biblioitems USING (biblionumber) 
393                                   WHERE biblioitems.itemtype= ? ";
394             }
395             push @bind_params, $type;
396         }
397
398         $count_query .= " AND borrowernumber = ? ";
399         push @bind_params, $borrower->{'borrowernumber'};
400         my $rule_branch = $issuing_rule->{branchcode};
401         if ($rule_branch ne "*") {
402             if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
403                 $count_query .= " AND issues.branchcode = ? ";
404                 push @bind_params, $branch;
405             } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
406                 ; # if branch is the patron's home branch, then count all loans by patron
407             } else {
408                 $count_query .= " AND items.homebranch = ? ";
409                 push @bind_params, $branch;
410             }
411         }
412
413         my $count_sth = $dbh->prepare($count_query);
414         $count_sth->execute(@bind_params);
415         my ($current_loan_count) = $count_sth->fetchrow_array;
416
417         my $max_loans_allowed = $issuing_rule->{'maxissueqty'};
418         if ($current_loan_count >= $max_loans_allowed) {
419             return "$current_loan_count / $max_loans_allowed";
420         }
421     }
422
423     # Now count total loans against the limit for the branch
424     my $branch_borrower_circ_rule = GetBranchBorrowerCircRule($branch, $cat_borrower);
425     if (defined($branch_borrower_circ_rule->{maxissueqty})) {
426         my @bind_params = ();
427         my $branch_count_query = "SELECT COUNT(*) FROM issues 
428                                   JOIN items USING (itemnumber)
429                                   WHERE borrowernumber = ? ";
430         push @bind_params, $borrower->{borrowernumber};
431
432         if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
433             $branch_count_query .= " AND issues.branchcode = ? ";
434             push @bind_params, $branch;
435         } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
436             ; # if branch is the patron's home branch, then count all loans by patron
437         } else {
438             $branch_count_query .= " AND items.homebranch = ? ";
439             push @bind_params, $branch;
440         }
441         my $branch_count_sth = $dbh->prepare($branch_count_query);
442         $branch_count_sth->execute(@bind_params);
443         my ($current_loan_count) = $branch_count_sth->fetchrow_array;
444
445         my $max_loans_allowed = $branch_borrower_circ_rule->{maxissueqty};
446         if ($current_loan_count >= $max_loans_allowed) {
447             return "$current_loan_count / $max_loans_allowed";
448         }
449     }
450
451     # OK, the patron can issue !!!
452     return;
453 }
454
455 =head2 itemissues
456
457   @issues = &itemissues($biblioitemnumber, $biblio);
458
459 Looks up information about who has borrowed the bookZ<>(s) with the
460 given biblioitemnumber.
461
462 C<$biblio> is ignored.
463
464 C<&itemissues> returns an array of references-to-hash. The keys
465 include the fields from the C<items> table in the Koha database.
466 Additional keys include:
467
468 =over 4
469
470 =item C<date_due>
471
472 If the item is currently on loan, this gives the due date.
473
474 If the item is not on loan, then this is either "Available" or
475 "Cancelled", if the item has been withdrawn.
476
477 =item C<card>
478
479 If the item is currently on loan, this gives the card number of the
480 patron who currently has the item.
481
482 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
483
484 These give the timestamp for the last three times the item was
485 borrowed.
486
487 =item C<card0>, C<card1>, C<card2>
488
489 The card number of the last three patrons who borrowed this item.
490
491 =item C<borrower0>, C<borrower1>, C<borrower2>
492
493 The borrower number of the last three patrons who borrowed this item.
494
495 =back
496
497 =cut
498
499 #'
500 sub itemissues {
501     my ( $bibitem, $biblio ) = @_;
502     my $dbh = C4::Context->dbh;
503     my $sth =
504       $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
505       || die $dbh->errstr;
506     my $i = 0;
507     my @results;
508
509     $sth->execute($bibitem) || die $sth->errstr;
510
511     while ( my $data = $sth->fetchrow_hashref ) {
512
513         # Find out who currently has this item.
514         # FIXME - Wouldn't it be better to do this as a left join of
515         # some sort? Currently, this code assumes that if
516         # fetchrow_hashref() fails, then the book is on the shelf.
517         # fetchrow_hashref() can fail for any number of reasons (e.g.,
518         # database server crash), not just because no items match the
519         # search criteria.
520         my $sth2 = $dbh->prepare(
521             "SELECT * FROM issues
522                 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
523                 WHERE itemnumber = ?
524             "
525         );
526
527         $sth2->execute( $data->{'itemnumber'} );
528         if ( my $data2 = $sth2->fetchrow_hashref ) {
529             $data->{'date_due'} = $data2->{'date_due'};
530             $data->{'card'}     = $data2->{'cardnumber'};
531             $data->{'borrower'} = $data2->{'borrowernumber'};
532         }
533         else {
534             $data->{'date_due'} = ($data->{'wthdrawn'} eq '1') ? 'Cancelled' : 'Available';
535         }
536
537         $sth2->finish;
538
539         # Find the last 3 people who borrowed this item.
540         $sth2 = $dbh->prepare(
541             "SELECT * FROM old_issues
542                 LEFT JOIN borrowers ON  issues.borrowernumber = borrowers.borrowernumber
543                 WHERE itemnumber = ?
544                 ORDER BY returndate DESC,timestamp DESC"
545         );
546
547         $sth2->execute( $data->{'itemnumber'} );
548         for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
549         {    # FIXME : error if there is less than 3 pple borrowing this item
550             if ( my $data2 = $sth2->fetchrow_hashref ) {
551                 $data->{"timestamp$i2"} = $data2->{'timestamp'};
552                 $data->{"card$i2"}      = $data2->{'cardnumber'};
553                 $data->{"borrower$i2"}  = $data2->{'borrowernumber'};
554             }    # if
555         }    # for
556
557         $sth2->finish;
558         $results[$i] = $data;
559         $i++;
560     }
561
562     $sth->finish;
563     return (@results);
564 }
565
566 =head2 CanBookBeIssued
567
568 Check if a book can be issued.
569
570 ( $issuingimpossible, $needsconfirmation ) =  CanBookBeIssued( $borrower, $barcode, $duedatespec, $inprocess );
571
572 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
573
574 =over 4
575
576 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
577
578 =item C<$barcode> is the bar code of the book being issued.
579
580 =item C<$duedatespec> is a C4::Dates object.
581
582 =item C<$inprocess>
583
584 =back
585
586 Returns :
587
588 =over 4
589
590 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
591 Possible values are :
592
593 =back
594
595 =head3 INVALID_DATE 
596
597 sticky due date is invalid
598
599 =head3 GNA
600
601 borrower gone with no address
602
603 =head3 CARD_LOST
604
605 borrower declared it's card lost
606
607 =head3 DEBARRED
608
609 borrower debarred
610
611 =head3 UNKNOWN_BARCODE
612
613 barcode unknown
614
615 =head3 NOT_FOR_LOAN
616
617 item is not for loan
618
619 =head3 WTHDRAWN
620
621 item withdrawn.
622
623 =head3 RESTRICTED
624
625 item is restricted (set by ??)
626
627 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
628 Possible values are :
629
630 =head3 DEBT
631
632 borrower has debts.
633
634 =head3 RENEW_ISSUE
635
636 renewing, not issuing
637
638 =head3 ISSUED_TO_ANOTHER
639
640 issued to someone else.
641
642 =head3 RESERVED
643
644 reserved for someone else.
645
646 =head3 INVALID_DATE
647
648 sticky due date is invalid
649
650 =head3 TOO_MANY
651
652 if the borrower borrows to much things
653
654 =cut
655
656 sub CanBookBeIssued {
657     my ( $borrower, $barcode, $duedate, $inprocess ) = @_;
658     my %needsconfirmation;    # filled with problems that needs confirmations
659     my %issuingimpossible;    # filled with problems that causes the issue to be IMPOSSIBLE
660     my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
661     my $issue = GetItemIssue($item->{itemnumber});
662         my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
663         $item->{'itemtype'}=$item->{'itype'}; 
664     my $dbh             = C4::Context->dbh;
665
666     #
667     # DUE DATE is OK ? -- should already have checked.
668     #
669     #$issuingimpossible{INVALID_DATE} = 1 unless ($duedate);
670
671     #
672     # BORROWER STATUS
673     #
674     if ( $borrower->{'category_type'} eq 'X' && (  $item->{barcode}  )) { 
675         # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1  .
676         &UpdateStats(C4::Context->userenv->{'branch'},'localuse','','',$item->{'itemnumber'},$item->{'itemtype'},$borrower->{'borrowernumber'});
677         return( { STATS => 1 }, {});
678     }
679     if ( $borrower->{flags}->{GNA} ) {
680         $issuingimpossible{GNA} = 1;
681     }
682     if ( $borrower->{flags}->{'LOST'} ) {
683         $issuingimpossible{CARD_LOST} = 1;
684     }
685     if ( $borrower->{flags}->{'DBARRED'} ) {
686         $issuingimpossible{DEBARRED} = 1;
687     }
688     if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
689         $issuingimpossible{EXPIRED} = 1;
690     } else {
691         my @expirydate=  split /-/,$borrower->{'dateexpiry'};
692         if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
693             Date_to_Days(Today) > Date_to_Days( @expirydate )) {
694             $issuingimpossible{EXPIRED} = 1;                                   
695         }
696     }
697     #
698     # BORROWER STATUS
699     #
700
701     # DEBTS
702     my ($amount) =
703       C4::Members::GetMemberAccountRecords( $borrower->{'borrowernumber'}, '' && $duedate->output('iso') );
704     if ( C4::Context->preference("IssuingInProcess") ) {
705         my $amountlimit = C4::Context->preference("noissuescharge");
706         if ( $amount > $amountlimit && !$inprocess ) {
707             $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
708         }
709         elsif ( $amount > 0 && $amount <= $amountlimit && !$inprocess ) {
710             $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
711         }
712     }
713     else {
714         if ( $amount > 0 ) {
715             $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
716         }
717     }
718
719     #
720     # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
721     #
722         my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
723     $needsconfirmation{TOO_MANY} = $toomany if $toomany;
724
725     #
726     # ITEM CHECKING
727     #
728     unless ( $item->{barcode} ) {
729         $issuingimpossible{UNKNOWN_BARCODE} = 1;
730     }
731     if (   $item->{'notforloan'}
732         && $item->{'notforloan'} > 0 )
733     {
734         $issuingimpossible{NOT_FOR_LOAN} = 1;
735     }
736         elsif ( !$item->{'notforloan'} ){
737                 # we have to check itemtypes.notforloan also
738                 if (C4::Context->preference('item-level_itypes')){
739                         # this should probably be a subroutine
740                         my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
741                         $sth->execute($item->{'itemtype'});
742                         my $notforloan=$sth->fetchrow_hashref();
743                         $sth->finish();
744                         if ($notforloan->{'notforloan'} == 1){
745                                 $issuingimpossible{NOT_FOR_LOAN} = 1;                           
746                         }
747                 }
748                 elsif ($biblioitem->{'notforloan'} == 1){
749                         $issuingimpossible{NOT_FOR_LOAN} = 1;
750                 }
751         }
752     if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
753     {
754         $issuingimpossible{WTHDRAWN} = 1;
755     }
756     if (   $item->{'restricted'}
757         && $item->{'restricted'} == 1 )
758     {
759         $issuingimpossible{RESTRICTED} = 1;
760     }
761     if ( C4::Context->preference("IndependantBranches") ) {
762         my $userenv = C4::Context->userenv;
763         if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
764             $issuingimpossible{NOTSAMEBRANCH} = 1
765               if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} );
766         }
767     }
768
769     #
770     # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
771     #
772     if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
773     {
774
775         # Already issued to current borrower. Ask whether the loan should
776         # be renewed.
777         my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed(
778             $borrower->{'borrowernumber'},
779             $item->{'itemnumber'}
780         );
781         if ( $CanBookBeRenewed == 0 ) {    # no more renewals allowed
782             $issuingimpossible{NO_MORE_RENEWALS} = 1;
783         }
784         else {
785             $needsconfirmation{RENEW_ISSUE} = 1;
786         }
787     }
788     elsif ($issue->{borrowernumber}) {
789
790         # issued to someone else
791         my $currborinfo = GetMemberDetails( $issue->{borrowernumber} );
792
793 #        warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
794         $needsconfirmation{ISSUED_TO_ANOTHER} =
795 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
796     }
797
798     # See if the item is on reserve.
799     my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
800     if ($restype) {
801                 my $resbor = $res->{'borrowernumber'};
802                 my ( $resborrower ) = C4::Members::GetMemberDetails( $resbor, 0 );
803                 my $branches  = GetBranches();
804                 my $branchname = $branches->{ $res->{'branchcode'} }->{'branchname'};
805         if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
806         {
807             # The item is on reserve and waiting, but has been
808             # reserved by some other patron.
809             $needsconfirmation{RESERVE_WAITING} =
810 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
811         }
812         elsif ( $restype eq "Reserved" ) {
813             # The item is on reserve for someone else.
814             $needsconfirmation{RESERVED} =
815 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
816         }
817     }
818     if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" ) {
819         if ( $borrower->{'categorycode'} eq 'W' ) {
820             my %emptyhash;
821             return ( \%emptyhash, \%needsconfirmation );
822         }
823         }
824         return ( \%issuingimpossible, \%needsconfirmation );
825 }
826
827 =head2 AddIssue
828
829 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
830
831 &AddIssue($borrower, $barcode, [$datedue], [$cancelreserve], [$issuedate])
832
833 =over 4
834
835 =item C<$borrower> is a hash with borrower informations (from GetMemberDetails).
836
837 =item C<$barcode> is the barcode of the item being issued.
838
839 =item C<$datedue> is a C4::Dates object for the max date of return, i.e. the date due (optional).
840 Calculated if empty.
841
842 =item C<$cancelreserve> is 1 to override and cancel any pending reserves for the item (optional).
843
844 =item C<$issuedate> is the date to issue the item in iso (YYYY-MM-DD) format (optional).
845 Defaults to today.  Unlike C<$datedue>, NOT a C4::Dates object, unfortunately.
846
847 AddIssue does the following things :
848 - step 01: check that there is a borrowernumber & a barcode provided
849 - check for RENEWAL (book issued & being issued to the same patron)
850     - renewal YES = Calculate Charge & renew
851     - renewal NO  = 
852         * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
853         * RESERVE PLACED ?
854             - fill reserve if reserve to this patron
855             - cancel reserve or not, otherwise
856         * TRANSFERT PENDING ?
857             - complete the transfert
858         * ISSUE THE BOOK
859
860 =back
861
862 =cut
863
864 sub AddIssue {
865     my ( $borrower, $barcode, $datedue, $cancelreserve, $issuedate ) = @_;
866     my $dbh = C4::Context->dbh;
867         my $barcodecheck=CheckValidBarcode($barcode);
868
869     # $issuedate defaults to today.
870     if ( ! defined $issuedate ) {
871         $issuedate = strftime( "%Y-%m-%d", localtime );
872     }
873         if ($borrower and $barcode and $barcodecheck ne '0'){
874                 # find which item we issue
875                 my $item = GetItem('', $barcode) or return undef;       # if we don't get an Item, abort.
876                 my $branch;
877                 # Get which branchcode we need
878                 if (C4::Context->preference('CircControl') eq 'PickupLibrary'){
879                         $branch = C4::Context->userenv->{'branch'}; 
880                 }
881                 elsif (C4::Context->preference('CircControl') eq 'PatronLibrary'){
882                         $branch = $borrower->{'branchcode'}; 
883                 }
884                 else {
885                         # items home library
886                         $branch = $item->{'homebranch'};
887                 }
888                 
889                 # get actual issuing if there is one
890                 my $actualissue = GetItemIssue( $item->{itemnumber});
891                 
892                 # get biblioinformation for this item
893                 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
894                 
895                 #
896                 # check if we just renew the issue.
897                 #
898                 if ($actualissue->{borrowernumber} eq $borrower->{'borrowernumber'}) {
899                         $datedue = AddRenewal(
900                                 $borrower->{'borrowernumber'},
901                                 $item->{'itemnumber'},
902                                 $branch,
903                                 $datedue,
904                 $issuedate, # here interpreted as the renewal date
905                         );
906                 }
907                 else {
908         # it's NOT a renewal
909                         if ( $actualissue->{borrowernumber}) {
910                                 # This book is currently on loan, but not to the person
911                                 # who wants to borrow it now. mark it returned before issuing to the new borrower
912                                 AddReturn(
913                                         $item->{'barcode'},
914                                         C4::Context->userenv->{'branch'}
915                                 );
916                         }
917
918                         # See if the item is on reserve.
919                         my ( $restype, $res ) =
920                           C4::Reserves::CheckReserves( $item->{'itemnumber'} );
921                         if ($restype) {
922                                 my $resbor = $res->{'borrowernumber'};
923                                 if ( $resbor eq $borrower->{'borrowernumber'} ) {
924
925                                         # The item is reserved by the current patron
926                                         ModReserveFill($res);
927                                 }
928                                 elsif ( $restype eq "Waiting" ) {
929
930                                         # warn "Waiting";
931                                         # The item is on reserve and waiting, but has been
932                                         # reserved by some other patron.
933                                 }
934                                 elsif ( $restype eq "Reserved" ) {
935
936                                         # warn "Reserved";
937                                         # The item is reserved by someone else.
938                                         if ($cancelreserve) { # cancel reserves on this item
939                                                 CancelReserve( 0, $res->{'itemnumber'},
940                                                         $res->{'borrowernumber'} );
941                                         }
942                                 }
943                                 if ($cancelreserve) {
944                                         CancelReserve( $res->{'biblionumber'}, 0,
945                     $res->{'borrowernumber'} );
946                                 }
947                                 else {
948                                         # set waiting reserve to first in reserve queue as book isn't waiting now
949                                         ModReserve(1,
950                                                 $res->{'biblionumber'},
951                                                 $res->{'borrowernumber'},
952                                                 $res->{'branchcode'}
953                                         );
954                                 }
955                         }
956
957                         # Starting process for transfer job (checking transfert and validate it if we have one)
958             my ($datesent) = GetTransfers($item->{'itemnumber'});
959             if ($datesent) {
960         #       updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for lisibility of this case (maybe for stats ....)
961             my $sth =
962                     $dbh->prepare(
963                     "UPDATE branchtransfers 
964                         SET datearrived = now(),
965                         tobranch = ?,
966                         comments = 'Forced branchtransfer'
967                     WHERE itemnumber= ? AND datearrived IS NULL"
968                     );
969                     $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
970                     $sth->finish;
971             }
972
973         # Record in the database the fact that the book was issued.
974         my $sth =
975           $dbh->prepare(
976                 "INSERT INTO issues 
977                     (borrowernumber, itemnumber,issuedate, date_due, branchcode)
978                 VALUES (?,?,?,?,?)"
979           );
980         unless ($datedue) {
981             my $itype = ( C4::Context->preference('item-level_itypes') ) ? $biblio->{'itype'} : $biblio->{'itemtype'};
982             my $loanlength = GetLoanLength( $borrower->{'categorycode'}, $itype, $branch );
983             $datedue = CalcDateDue( C4::Dates->new( $issuedate, 'iso' ), $loanlength, $branch );
984
985             # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
986             if ( C4::Context->preference('ReturnBeforeExpiry') && $datedue->output('iso') gt $borrower->{dateexpiry} ) {
987                 $datedue = C4::Dates->new( $borrower->{dateexpiry}, 'iso' );
988             }
989         }
990         $sth->execute(
991             $borrower->{'borrowernumber'},      # borrowernumber
992             $item->{'itemnumber'},              # itemnumber
993             $issuedate,                         # issuedate
994             $datedue->output('iso'),            # date_due
995             C4::Context->userenv->{'branch'}    # branchcode
996         );
997         $sth->finish;
998         $item->{'issues'}++;
999         ModItem({ issues           => $item->{'issues'},
1000                   holdingbranch    => C4::Context->userenv->{'branch'},
1001                   itemlost         => 0,
1002                   datelastborrowed => C4::Dates->new()->output('iso'),
1003                   onloan           => $datedue->output('iso'),
1004                 }, $item->{'biblionumber'}, $item->{'itemnumber'});
1005         ModDateLastSeen( $item->{'itemnumber'} );
1006         
1007         # If it costs to borrow this book, charge it to the patron's account.
1008         my ( $charge, $itemtype ) = GetIssuingCharges(
1009             $item->{'itemnumber'},
1010             $borrower->{'borrowernumber'}
1011         );
1012         if ( $charge > 0 ) {
1013             AddIssuingCharge(
1014                 $item->{'itemnumber'},
1015                 $borrower->{'borrowernumber'}, $charge
1016             );
1017             $item->{'charge'} = $charge;
1018         }
1019
1020         # Record the fact that this book was issued.
1021         &UpdateStats(
1022             C4::Context->userenv->{'branch'},
1023             'issue',                        $charge,
1024             '',                             $item->{'itemnumber'},
1025             $item->{'itype'}, $borrower->{'borrowernumber'}
1026         );
1027     }
1028     
1029     logaction("CIRCULATION", "ISSUE", $borrower->{'borrowernumber'}, $biblio->{'biblionumber'}) 
1030         if C4::Context->preference("IssueLog");
1031   }
1032   return ($datedue);    # not necessarily the same as when it came in!
1033 }
1034
1035 =head2 GetLoanLength
1036
1037 Get loan length for an itemtype, a borrower type and a branch
1038
1039 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1040
1041 =cut
1042
1043 sub GetLoanLength {
1044     my ( $borrowertype, $itemtype, $branchcode ) = @_;
1045     my $dbh = C4::Context->dbh;
1046     my $sth =
1047       $dbh->prepare(
1048 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1049       );
1050 # warn "in get loan lenght $borrowertype $itemtype $branchcode ";
1051 # try to find issuelength & return the 1st available.
1052 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1053     $sth->execute( $borrowertype, $itemtype, $branchcode );
1054     my $loanlength = $sth->fetchrow_hashref;
1055     return $loanlength->{issuelength}
1056       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1057
1058     $sth->execute( $borrowertype, "*", $branchcode );
1059     $loanlength = $sth->fetchrow_hashref;
1060     return $loanlength->{issuelength}
1061       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1062
1063     $sth->execute( "*", $itemtype, $branchcode );
1064     $loanlength = $sth->fetchrow_hashref;
1065     return $loanlength->{issuelength}
1066       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1067
1068     $sth->execute( "*", "*", $branchcode );
1069     $loanlength = $sth->fetchrow_hashref;
1070     return $loanlength->{issuelength}
1071       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1072
1073     $sth->execute( $borrowertype, $itemtype, "*" );
1074     $loanlength = $sth->fetchrow_hashref;
1075     return $loanlength->{issuelength}
1076       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1077
1078     $sth->execute( $borrowertype, "*", "*" );
1079     $loanlength = $sth->fetchrow_hashref;
1080     return $loanlength->{issuelength}
1081       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1082
1083     $sth->execute( "*", $itemtype, "*" );
1084     $loanlength = $sth->fetchrow_hashref;
1085     return $loanlength->{issuelength}
1086       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1087
1088     $sth->execute( "*", "*", "*" );
1089     $loanlength = $sth->fetchrow_hashref;
1090     return $loanlength->{issuelength}
1091       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1092
1093     # if no rule is set => 21 days (hardcoded)
1094     return 21;
1095 }
1096
1097 =head2 GetIssuingRule
1098
1099 FIXME - This is a copy-paste of GetLoanLength 
1100 as a stop-gap.  Do not wish to change API for GetLoanLength 
1101 this close to release, however, Overdues::GetIssuingRules is broken.
1102
1103 Get the issuing rule for an itemtype, a borrower type and a branch
1104 Returns a hashref from the issuingrules table.
1105
1106 my $irule = &GetIssuingRule($borrowertype,$itemtype,branchcode)
1107
1108 =cut
1109
1110 sub GetIssuingRule {
1111     my ( $borrowertype, $itemtype, $branchcode ) = @_;
1112     my $dbh = C4::Context->dbh;
1113     my $sth =  $dbh->prepare( "select * from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"  );
1114     my $irule;
1115
1116         $sth->execute( $borrowertype, $itemtype, $branchcode );
1117     $irule = $sth->fetchrow_hashref;
1118     return $irule if defined($irule) ;
1119
1120     $sth->execute( $borrowertype, "*", $branchcode );
1121     $irule = $sth->fetchrow_hashref;
1122     return $irule if defined($irule) ;
1123
1124     $sth->execute( "*", $itemtype, $branchcode );
1125     $irule = $sth->fetchrow_hashref;
1126     return $irule if defined($irule) ;
1127
1128     $sth->execute( "*", "*", $branchcode );
1129     $irule = $sth->fetchrow_hashref;
1130     return $irule if defined($irule) ;
1131
1132     $sth->execute( $borrowertype, $itemtype, "*" );
1133     $irule = $sth->fetchrow_hashref;
1134     return $irule if defined($irule) ;
1135
1136     $sth->execute( $borrowertype, "*", "*" );
1137     $irule = $sth->fetchrow_hashref;
1138     return $irule if defined($irule) ;
1139
1140     $sth->execute( "*", $itemtype, "*" );
1141     $irule = $sth->fetchrow_hashref;
1142     return $irule if defined($irule) ;
1143
1144     $sth->execute( "*", "*", "*" );
1145     $irule = $sth->fetchrow_hashref;
1146     return $irule if defined($irule) ;
1147
1148     # if no rule matches,
1149     return undef;
1150 }
1151
1152 =head2 GetBranchBorrowerCircRule
1153
1154 =over 4
1155
1156 my $branch_cat_rule = GetBranchBorrowerCircRule($branchcode, $categorycode);
1157
1158 =back
1159
1160 Retrieves circulation rule attributes that apply to the given
1161 branch and patron category, regardless of item type.  
1162 The return value is a hashref containing the following key:
1163
1164 maxissueqty - maximum number of loans that a
1165 patron of the given category can have at the given
1166 branch.  If the value is undef, no limit.
1167
1168 This will first check for a specific branch and
1169 category match from branch_borrower_circ_rules. 
1170
1171 If no rule is found, it will then check default_branch_circ_rules
1172 (same branch, default category).  If no rule is found,
1173 it will then check default_borrower_circ_rules (default 
1174 branch, same category), then failing that, default_circ_rules
1175 (default branch, default category).
1176
1177 If no rule has been found in the database, it will default to
1178 the buillt in rule:
1179
1180 maxissueqty - undef
1181
1182 C<$branchcode> and C<$categorycode> should contain the
1183 literal branch code and patron category code, respectively - no
1184 wildcards.
1185
1186 =cut
1187
1188 sub GetBranchBorrowerCircRule {
1189     my $branchcode = shift;
1190     my $categorycode = shift;
1191
1192     my $branch_cat_query = "SELECT maxissueqty
1193                             FROM branch_borrower_circ_rules
1194                             WHERE branchcode = ?
1195                             AND   categorycode = ?";
1196     my $dbh = C4::Context->dbh();
1197     my $sth = $dbh->prepare($branch_cat_query);
1198     $sth->execute($branchcode, $categorycode);
1199     my $result;
1200     if ($result = $sth->fetchrow_hashref()) {
1201         return $result;
1202     }
1203
1204     # try same branch, default borrower category
1205     my $branch_query = "SELECT maxissueqty
1206                         FROM default_branch_circ_rules
1207                         WHERE branchcode = ?";
1208     $sth = $dbh->prepare($branch_query);
1209     $sth->execute($branchcode);
1210     if ($result = $sth->fetchrow_hashref()) {
1211         return $result;
1212     }
1213
1214     # try default branch, same borrower category
1215     my $category_query = "SELECT maxissueqty
1216                           FROM default_borrower_circ_rules
1217                           WHERE categorycode = ?";
1218     $sth = $dbh->prepare($category_query);
1219     $sth->execute($categorycode);
1220     if ($result = $sth->fetchrow_hashref()) {
1221         return $result;
1222     }
1223   
1224     # try default branch, default borrower category
1225     my $default_query = "SELECT maxissueqty
1226                           FROM default_circ_rules";
1227     $sth = $dbh->prepare($default_query);
1228     $sth->execute();
1229     if ($result = $sth->fetchrow_hashref()) {
1230         return $result;
1231     }
1232     
1233     # built-in default circulation rule
1234     return {
1235         maxissueqty => undef,
1236     };
1237 }
1238
1239 =head2 AddReturn
1240
1241 ($doreturn, $messages, $iteminformation, $borrower) =
1242     &AddReturn($barcode, $branch, $exemptfine, $dropbox);
1243
1244 Returns a book.
1245
1246 =over 4
1247
1248 =item C<$barcode> is the bar code of the book being returned.
1249
1250 =item C<$branch> is the code of the branch where the book is being returned.
1251
1252 =item C<$exemptfine> indicates that overdue charges for the item will be
1253 removed.
1254
1255 =item C<$dropbox> indicates that the check-in date is assumed to be
1256 yesterday, or the last non-holiday as defined in C4::Calendar .  If
1257 overdue charges are applied and C<$dropbox> is true, the last charge
1258 will be removed.  This assumes that the fines accrual script has run
1259 for _today_.
1260
1261 =back
1262
1263 C<&AddReturn> returns a list of four items:
1264
1265 C<$doreturn> is true iff the return succeeded.
1266
1267 C<$messages> is a reference-to-hash giving the reason for failure:
1268
1269 =over 4
1270
1271 =item C<BadBarcode>
1272
1273 No item with this barcode exists. The value is C<$barcode>.
1274
1275 =item C<NotIssued>
1276
1277 The book is not currently on loan. The value is C<$barcode>.
1278
1279 =item C<IsPermanent>
1280
1281 The book's home branch is a permanent collection. If you have borrowed
1282 this book, you are not allowed to return it. The value is the code for
1283 the book's home branch.
1284
1285 =item C<wthdrawn>
1286
1287 This book has been withdrawn/cancelled. The value should be ignored.
1288
1289 =item C<ResFound>
1290
1291 The item was reserved. The value is a reference-to-hash whose keys are
1292 fields from the reserves table of the Koha database, and
1293 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1294 either C<Waiting>, C<Reserved>, or 0.
1295
1296 =back
1297
1298 C<$borrower> is a reference-to-hash, giving information about the
1299 patron who last borrowed the book.
1300
1301 =cut
1302
1303 sub AddReturn {
1304     my ( $barcode, $branch, $exemptfine, $dropbox ) = @_;
1305     my $dbh      = C4::Context->dbh;
1306     my $messages;
1307     my $doreturn = 1;
1308     my $borrower;
1309     my $validTransfert = 0;
1310     my $reserveDone = 0;
1311     
1312     # get information on item
1313     my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1314     my $biblio = GetBiblioItemData($iteminformation->{'biblioitemnumber'});
1315 #     use Data::Dumper;warn Data::Dumper::Dumper($iteminformation);  
1316     unless ($iteminformation->{'itemnumber'} ) {
1317         $messages->{'BadBarcode'} = $barcode;
1318         $doreturn = 0;
1319     } else {
1320         # find the borrower
1321         if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1322             $messages->{'NotIssued'} = $barcode;
1323             # even though item is not on loan, it may still
1324             # be transferred; therefore, get current branch information
1325             my $curr_iteminfo = GetItem($iteminformation->{'itemnumber'});
1326             $iteminformation->{'homebranch'} = $curr_iteminfo->{'homebranch'};
1327             $iteminformation->{'holdingbranch'} = $curr_iteminfo->{'holdingbranch'};
1328             $doreturn = 0;
1329         }
1330     
1331         # check if the book is in a permanent collection....
1332         my $hbr      = $iteminformation->{C4::Context->preference("HomeOrHoldingBranch")};
1333         my $branches = GetBranches();
1334                 # FIXME -- This 'PE' attribute is largely undocumented.  afaict, there's no user interface that reflects this functionality.
1335         if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1336             $messages->{'IsPermanent'} = $hbr;
1337         }
1338                 
1339                     # if independent branches are on and returning to different branch, refuse the return
1340         if ($hbr ne C4::Context->userenv->{'branch'} && C4::Context->preference("IndependantBranches")){
1341                           $messages->{'Wrongbranch'} = 1;
1342                           $doreturn=0;
1343                     }
1344                         
1345         # check that the book has been cancelled
1346         if ( $iteminformation->{'wthdrawn'} ) {
1347             $messages->{'wthdrawn'} = 1;
1348             $doreturn = 0;
1349         }
1350     
1351     #     new op dev : if the book returned in an other branch update the holding branch
1352     
1353     # update issues, thereby returning book (should push this out into another subroutine
1354         $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1355     
1356     # case of a return of document (deal with issues and holdingbranch)
1357     
1358         if ($doreturn) {
1359                         my $circControlBranch;
1360                         if($dropbox) {
1361                                 # don't allow dropbox mode to create an invalid entry in issues (issuedate > returndate) FIXME: actually checks eq, not gt
1362                                 undef($dropbox) if ( $iteminformation->{'issuedate'} eq C4::Dates->today('iso') );
1363                                 if (C4::Context->preference('CircControl') eq 'ItemHomeBranch' ) {
1364                                         $circControlBranch = $iteminformation->{homebranch};
1365                                 } elsif ( C4::Context->preference('CircControl') eq 'PatronLibrary') {
1366                                         $circControlBranch = $borrower->{branchcode};
1367                                 } else { # CircControl must be PickupLibrary.
1368                                         $circControlBranch = $iteminformation->{holdingbranch};
1369                                         # FIXME - is this right ? are we sure that the holdingbranch is still the pickup branch?
1370                                 }
1371                         }
1372             MarkIssueReturned($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'},$circControlBranch);
1373             $messages->{'WasReturned'} = 1;    # FIXME is the "= 1" right?
1374         }
1375     
1376     # continue to deal with returns cases, but not only if we have an issue
1377     
1378         # the holdingbranch is updated if the document is returned in an other location .
1379         if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} ) {
1380                         UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'}); 
1381                         #               reload iteminformation holdingbranch with the userenv value
1382                         $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1383         }
1384         ModDateLastSeen( $iteminformation->{'itemnumber'} );
1385         ModItem({ onloan => undef }, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'});
1386                     
1387                     if ($iteminformation->{borrowernumber}){
1388                           ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1389         }       
1390         # fix up the accounts.....
1391         if ( $iteminformation->{'itemlost'} ) {
1392             $messages->{'WasLost'} = 1;
1393         }
1394     
1395     # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1396     #     check if we have a transfer for this document
1397         my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1398     
1399     #     if we have a transfer to do, we update the line of transfers with the datearrived
1400         if ($datesent) {
1401             if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1402                     my $sth =
1403                     $dbh->prepare(
1404                             "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1405                     );
1406                     $sth->execute( $iteminformation->{'itemnumber'} );
1407                     $sth->finish;
1408     #         now we check if there is a reservation with the validate of transfer if we have one, we can         set it with the status 'W'
1409             C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1410             }
1411         else {
1412             $messages->{'WrongTransfer'} = $tobranch;
1413             $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1414         }
1415         $validTransfert = 1;
1416         }
1417     
1418     # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
1419         # fix up the accounts.....
1420         if ($iteminformation->{'itemlost'}) {
1421                 FixAccountForLostAndReturned($iteminformation, $borrower);
1422                 $messages->{'WasLost'} = 1;
1423         }
1424         # fix up the overdues in accounts...
1425         FixOverduesOnReturn( $borrower->{'borrowernumber'},
1426             $iteminformation->{'itemnumber'}, $exemptfine, $dropbox );
1427     
1428     # find reserves.....
1429     #     if we don't have a reserve with the status W, we launch the Checkreserves routine
1430         my ( $resfound, $resrec ) =
1431         C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1432         if ($resfound) {
1433             $resrec->{'ResFound'}   = $resfound;
1434             $messages->{'ResFound'} = $resrec;
1435             $reserveDone = 1;
1436         }
1437     
1438         # update stats?
1439         # Record the fact that this book was returned.
1440         UpdateStats(
1441             $branch, 'return', '0', '',
1442             $iteminformation->{'itemnumber'},
1443             $biblio->{'itemtype'},
1444             $borrower->{'borrowernumber'}
1445         );
1446         
1447         logaction("CIRCULATION", "RETURN", $iteminformation->{borrowernumber}, $iteminformation->{'biblionumber'}) 
1448             if C4::Context->preference("ReturnLog");
1449         
1450         #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1451         #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1452         
1453         if ( ( $branch ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1454                         if (C4::Context->preference("AutomaticItemReturn") == 1) {
1455                                 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1456                                 $messages->{'WasTransfered'} = 1;
1457                         } elsif ( C4::Context->preference("UseBranchTransferLimits") == 1 
1458                                         && ! IsTransferAllowed( $branch, $iteminformation->{'homebranch'}, $iteminformation->{'itemtype'} )
1459                                 ) {
1460                                 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1461                                 $messages->{'WasTransfered'} = 1;
1462                         }
1463                         else {
1464                                 $messages->{'NeedsTransfer'} = 1;
1465                         }
1466         }
1467     }
1468     return ( $doreturn, $messages, $iteminformation, $borrower );
1469 }
1470
1471 =head2 MarkIssueReturned
1472
1473 =over 4
1474
1475 MarkIssueReturned($borrowernumber, $itemnumber, $dropbox_branch, $returndate);
1476
1477 =back
1478
1479 Unconditionally marks an issue as being returned by
1480 moving the C<issues> row to C<old_issues> and
1481 setting C<returndate> to the current date, or
1482 the last non-holiday date of the branccode specified in
1483 C<dropbox_branch> .  Assumes you've already checked that 
1484 it's safe to do this, i.e. last non-holiday > issuedate.
1485
1486 if C<$returndate> is specified (in iso format), it is used as the date
1487 of the return. It is ignored when a dropbox_branch is passed in.
1488
1489 Ideally, this function would be internal to C<C4::Circulation>,
1490 not exported, but it is currently needed by one 
1491 routine in C<C4::Accounts>.
1492
1493 =cut
1494
1495 sub MarkIssueReturned {
1496     my ( $borrowernumber, $itemnumber, $dropbox_branch, $returndate ) = @_;
1497     my $dbh   = C4::Context->dbh;
1498     my $query = "UPDATE issues SET returndate=";
1499     my @bind;
1500     if ($dropbox_branch) {
1501         my $calendar = C4::Calendar->new( branchcode => $dropbox_branch );
1502         my $dropboxdate = $calendar->addDate( C4::Dates->new(), -1 );
1503         $query .= " ? ";
1504         push @bind, $dropboxdate->output('iso');
1505     } elsif ($returndate) {
1506         $query .= " ? ";
1507         push @bind, $returndate;
1508     } else {
1509         $query .= " now() ";
1510     }
1511     $query .= " WHERE  borrowernumber = ?  AND itemnumber = ?";
1512     push @bind, $borrowernumber, $itemnumber;
1513     # FIXME transaction
1514     my $sth_upd  = $dbh->prepare($query);
1515     $sth_upd->execute(@bind);
1516     my $sth_copy = $dbh->prepare("INSERT INTO old_issues SELECT * FROM issues 
1517                                   WHERE borrowernumber = ?
1518                                   AND itemnumber = ?");
1519     $sth_copy->execute($borrowernumber, $itemnumber);
1520     my $sth_del  = $dbh->prepare("DELETE FROM issues
1521                                   WHERE borrowernumber = ?
1522                                   AND itemnumber = ?");
1523     $sth_del->execute($borrowernumber, $itemnumber);
1524 }
1525
1526 =head2 FixOverduesOnReturn
1527
1528     &FixOverduesOnReturn($brn,$itm, $exemptfine, $dropboxmode);
1529
1530 C<$brn> borrowernumber
1531
1532 C<$itm> itemnumber
1533
1534 C<$exemptfine> BOOL -- remove overdue charge associated with this issue. 
1535 C<$dropboxmode> BOOL -- remove lastincrement on overdue charge associated with this issue.
1536
1537 internal function, called only by AddReturn
1538
1539 =cut
1540
1541 sub FixOverduesOnReturn {
1542     my ( $borrowernumber, $item, $exemptfine, $dropbox ) = @_;
1543     my $dbh = C4::Context->dbh;
1544
1545     # check for overdue fine
1546     my $sth =
1547       $dbh->prepare(
1548 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1549       );
1550     $sth->execute( $borrowernumber, $item );
1551
1552     # alter fine to show that the book has been returned
1553    my $data; 
1554         if ($data = $sth->fetchrow_hashref) {
1555         my $uquery;
1556                 my @bind = ($borrowernumber,$item ,$data->{'accountno'});
1557                 if ($exemptfine) {
1558                         $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
1559                         if (C4::Context->preference("FinesLog")) {
1560                         &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
1561                         }
1562                 } elsif ($dropbox && $data->{lastincrement}) {
1563                         my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
1564                         my $amt = $data->{amount} - $data->{lastincrement} ;
1565                         if (C4::Context->preference("FinesLog")) {
1566                         &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
1567                         }
1568                          $uquery = "update accountlines set accounttype='F' ";
1569                          if($outstanding  >= 0 && $amt >=0) {
1570                                 $uquery .= ", amount = ? , amountoutstanding=? ";
1571                                 unshift @bind, ($amt, $outstanding) ;
1572                         }
1573                 } else {
1574                         $uquery = "update accountlines set accounttype='F' ";
1575                 }
1576                 $uquery .= " where (borrowernumber = ?) and (itemnumber = ?) and (accountno = ?)";
1577         my $usth = $dbh->prepare($uquery);
1578         $usth->execute(@bind);
1579         $usth->finish();
1580     }
1581
1582     $sth->finish();
1583     return;
1584 }
1585
1586 =head2 FixAccountForLostAndReturned
1587
1588         &FixAccountForLostAndReturned($iteminfo,$borrower);
1589
1590 Calculates the charge for a book lost and returned (Not exported & used only once)
1591
1592 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1593
1594 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1595
1596 Internal function, called by AddReturn
1597
1598 =cut
1599
1600 sub FixAccountForLostAndReturned {
1601         my ($iteminfo, $borrower) = @_;
1602         my $dbh = C4::Context->dbh;
1603         my $itm = $iteminfo->{'itemnumber'};
1604         # check for charge made for lost book
1605         my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1606         $sth->execute($itm);
1607         if (my $data = $sth->fetchrow_hashref) {
1608         # writeoff this amount
1609                 my $offset;
1610                 my $amount = $data->{'amount'};
1611                 my $acctno = $data->{'accountno'};
1612                 my $amountleft;
1613                 if ($data->{'amountoutstanding'} == $amount) {
1614                 $offset = $data->{'amount'};
1615                 $amountleft = 0;
1616                 } else {
1617                 $offset = $amount - $data->{'amountoutstanding'};
1618                 $amountleft = $data->{'amountoutstanding'} - $amount;
1619                 }
1620                 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1621                         WHERE (borrowernumber = ?)
1622                         AND (itemnumber = ?) AND (accountno = ?) ");
1623                 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1624                 $usth->finish;
1625         #check if any credit is left if so writeoff other accounts
1626                 my $nextaccntno = getnextacctno($data->{'borrowernumber'});
1627                 if ($amountleft < 0){
1628                 $amountleft*=-1;
1629                 }
1630                 if ($amountleft > 0){
1631                 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1632                                                         AND (amountoutstanding >0) ORDER BY date");
1633                 $msth->execute($data->{'borrowernumber'});
1634         # offset transactions
1635                 my $newamtos;
1636                 my $accdata;
1637                 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1638                         if ($accdata->{'amountoutstanding'} < $amountleft) {
1639                         $newamtos = 0;
1640                         $amountleft -= $accdata->{'amountoutstanding'};
1641                         }  else {
1642                         $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1643                         $amountleft = 0;
1644                         }
1645                         my $thisacct = $accdata->{'accountno'};
1646                         my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1647                                         WHERE (borrowernumber = ?)
1648                                         AND (accountno=?)");
1649                         $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1650                         $usth->finish;
1651                         $usth = $dbh->prepare("INSERT INTO accountoffsets
1652                                 (borrowernumber, accountno, offsetaccount,  offsetamount)
1653                                 VALUES
1654                                 (?,?,?,?)");
1655                         $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1656                         $usth->finish;
1657                 }
1658                 $msth->finish;
1659                 }
1660                 if ($amountleft > 0){
1661                         $amountleft*=-1;
1662                 }
1663                 my $desc="Item Returned ".$iteminfo->{'barcode'};
1664                 $usth = $dbh->prepare("INSERT INTO accountlines
1665                         (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1666                         VALUES (?,?,now(),?,?,'CR',?)");
1667                 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1668                 $usth->finish;
1669                 $usth = $dbh->prepare("INSERT INTO accountoffsets
1670                         (borrowernumber, accountno, offsetaccount,  offsetamount)
1671                         VALUES (?,?,?,?)");
1672                 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1673                 $usth->finish;
1674         ModItem({ paidfor => '' }, undef, $itm);
1675         }
1676         $sth->finish;
1677         return;
1678 }
1679
1680 =head2 GetItemIssue
1681
1682 $issues = &GetItemIssue($itemnumber);
1683
1684 Returns patrons currently having a book. nothing if item is not issued atm
1685
1686 C<$itemnumber> is the itemnumber
1687
1688 Returns an array of hashes
1689
1690 FIXME: Though the above says that this function returns nothing if the
1691 item is not issued, this actually returns a hasref that looks like
1692 this:
1693     {
1694       itemnumber => 1,
1695       overdue    => 1
1696     }
1697
1698
1699 =cut
1700
1701 sub GetItemIssue {
1702     my ( $itemnumber) = @_;
1703     return unless $itemnumber;
1704     my $dbh = C4::Context->dbh;
1705     my @GetItemIssues;
1706     
1707     # get today date
1708     my $today = POSIX::strftime("%Y%m%d", localtime);
1709
1710     my $sth = $dbh->prepare(
1711         "SELECT * FROM issues 
1712         LEFT JOIN items ON issues.itemnumber=items.itemnumber
1713     WHERE
1714     issues.itemnumber=?");
1715     $sth->execute($itemnumber);
1716     my $data = $sth->fetchrow_hashref;
1717     my $datedue = $data->{'date_due'};
1718     $datedue =~ s/-//g;
1719     if ( $datedue < $today ) {
1720         $data->{'overdue'} = 1;
1721     }
1722     $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1723     $sth->finish;
1724     return ($data);
1725 }
1726
1727 =head2 GetOpenIssue
1728
1729 $issue = GetOpenIssue( $itemnumber );
1730
1731 Returns the row from the issues table if the item is currently issued, undef if the item is not currently issued
1732
1733 C<$itemnumber> is the item's itemnumber
1734
1735 Returns a hashref
1736
1737 =cut
1738
1739 sub GetOpenIssue {
1740   my ( $itemnumber ) = @_;
1741
1742   my $dbh = C4::Context->dbh;  
1743   my $sth = $dbh->prepare( "SELECT * FROM issues WHERE itemnumber = ? AND returndate IS NULL" );
1744   $sth->execute( $itemnumber );
1745   my $issue = $sth->fetchrow_hashref();
1746   return $issue;
1747 }
1748
1749 =head2 GetItemIssues
1750
1751 $issues = &GetItemIssues($itemnumber, $history);
1752
1753 Returns patrons that have issued a book
1754
1755 C<$itemnumber> is the itemnumber
1756 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1757
1758 Returns an array of hashes
1759
1760 =cut
1761
1762 sub GetItemIssues {
1763     my ( $itemnumber,$history ) = @_;
1764     my $dbh = C4::Context->dbh;
1765     my @GetItemIssues;
1766     
1767     # get today date
1768     my $today = POSIX::strftime("%Y%m%d", localtime);
1769
1770     my $sql = "SELECT * FROM issues 
1771               JOIN borrowers USING (borrowernumber)
1772               JOIN items USING (itemnumber)
1773               WHERE issues.itemnumber = ? ";
1774     if ($history) {
1775         $sql .= "UNION ALL
1776                  SELECT * FROM old_issues 
1777                  LEFT JOIN borrowers USING (borrowernumber)
1778                  JOIN items USING (itemnumber)
1779                  WHERE old_issues.itemnumber = ? ";
1780     }
1781     $sql .= "ORDER BY date_due DESC";
1782     my $sth = $dbh->prepare($sql);
1783     if ($history) {
1784         $sth->execute($itemnumber, $itemnumber);
1785     } else {
1786         $sth->execute($itemnumber);
1787     }
1788     while ( my $data = $sth->fetchrow_hashref ) {
1789         my $datedue = $data->{'date_due'};
1790         $datedue =~ s/-//g;
1791         if ( $datedue < $today ) {
1792             $data->{'overdue'} = 1;
1793         }
1794         my $itemnumber = $data->{'itemnumber'};
1795         push @GetItemIssues, $data;
1796     }
1797     $sth->finish;
1798     return ( \@GetItemIssues );
1799 }
1800
1801 =head2 GetBiblioIssues
1802
1803 $issues = GetBiblioIssues($biblionumber);
1804
1805 this function get all issues from a biblionumber.
1806
1807 Return:
1808 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1809 tables issues and the firstname,surname & cardnumber from borrowers.
1810
1811 =cut
1812
1813 sub GetBiblioIssues {
1814     my $biblionumber = shift;
1815     return undef unless $biblionumber;
1816     my $dbh   = C4::Context->dbh;
1817     my $query = "
1818         SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1819         FROM issues
1820             LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1821             LEFT JOIN items ON issues.itemnumber = items.itemnumber
1822             LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1823             LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1824         WHERE biblio.biblionumber = ?
1825         UNION ALL
1826         SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1827         FROM old_issues
1828             LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
1829             LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
1830             LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1831             LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1832         WHERE biblio.biblionumber = ?
1833         ORDER BY timestamp
1834     ";
1835     my $sth = $dbh->prepare($query);
1836     $sth->execute($biblionumber, $biblionumber);
1837
1838     my @issues;
1839     while ( my $data = $sth->fetchrow_hashref ) {
1840         push @issues, $data;
1841     }
1842     return \@issues;
1843 }
1844
1845 =head2 GetUpcomingDueIssues
1846
1847 =over 4
1848  
1849 my $upcoming_dues = GetUpcomingDueIssues( { days_in_advance => 4 } );
1850
1851 =back
1852
1853 =cut
1854
1855 sub GetUpcomingDueIssues {
1856     my $params = shift;
1857
1858     $params->{'days_in_advance'} = 7 unless exists $params->{'days_in_advance'};
1859     my $dbh = C4::Context->dbh;
1860
1861     my $statement = <<END_SQL;
1862 SELECT issues.*, items.itype as itemtype, items.homebranch, TO_DAYS( date_due )-TO_DAYS( NOW() ) as days_until_due
1863 FROM issues 
1864 LEFT JOIN items USING (itemnumber)
1865 WhERE returndate is NULL
1866 AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ?
1867 END_SQL
1868
1869     my @bind_parameters = ( $params->{'days_in_advance'} );
1870     
1871     my $sth = $dbh->prepare( $statement );
1872     $sth->execute( @bind_parameters );
1873     my $upcoming_dues = $sth->fetchall_arrayref({});
1874     $sth->finish;
1875
1876     return $upcoming_dues;
1877 }
1878
1879 =head2 CanBookBeRenewed
1880
1881 ($ok,$error) = &CanBookBeRenewed($borrowernumber, $itemnumber[, $override_limit]);
1882
1883 Find out whether a borrowed item may be renewed.
1884
1885 C<$dbh> is a DBI handle to the Koha database.
1886
1887 C<$borrowernumber> is the borrower number of the patron who currently
1888 has the item on loan.
1889
1890 C<$itemnumber> is the number of the item to renew.
1891
1892 C<$override_limit>, if supplied with a true value, causes
1893 the limit on the number of times that the loan can be renewed
1894 (as controlled by the item type) to be ignored.
1895
1896 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1897 item must currently be on loan to the specified borrower; renewals
1898 must be allowed for the item's type; and the borrower must not have
1899 already renewed the loan. $error will contain the reason the renewal can not proceed
1900
1901 =cut
1902
1903 sub CanBookBeRenewed {
1904
1905     # check renewal status
1906     my ( $borrowernumber, $itemnumber, $override_limit ) = @_;
1907     my $dbh       = C4::Context->dbh;
1908     my $renews    = 1;
1909     my $renewokay = 0;
1910         my $error;
1911
1912     # Look in the issues table for this item, lent to this borrower,
1913     # and not yet returned.
1914
1915     # FIXME - I think this function could be redone to use only one SQL call.
1916     my $sth1 = $dbh->prepare(
1917         "SELECT * FROM issues
1918             WHERE borrowernumber = ?
1919             AND itemnumber = ?"
1920     );
1921     $sth1->execute( $borrowernumber, $itemnumber );
1922     if ( my $data1 = $sth1->fetchrow_hashref ) {
1923
1924         # Found a matching item
1925
1926         # See if this item may be renewed. This query is convoluted
1927         # because it's a bit messy: given the item number, we need to find
1928         # the biblioitem, which gives us the itemtype, which tells us
1929         # whether it may be renewed.
1930         my $query = "SELECT renewalsallowed FROM items ";
1931         $query .= (C4::Context->preference('item-level_itypes'))
1932                     ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1933                     : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1934                        LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1935         $query .= "WHERE items.itemnumber = ?";
1936         my $sth2 = $dbh->prepare($query);
1937         $sth2->execute($itemnumber);
1938         if ( my $data2 = $sth2->fetchrow_hashref ) {
1939             $renews = $data2->{'renewalsallowed'};
1940         }
1941         if ( ( $renews && $renews > $data1->{'renewals'} ) || $override_limit ) {
1942             $renewokay = 1;
1943         }
1944         else {
1945                         $error="too_many";
1946                 }
1947         $sth2->finish;
1948         my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1949         if ($resfound) {
1950             $renewokay = 0;
1951                         $error="on_reserve"
1952         }
1953
1954     }
1955     $sth1->finish;
1956     return ($renewokay,$error);
1957 }
1958
1959 =head2 AddRenewal
1960
1961 &AddRenewal($borrowernumber, $itemnumber, $branch, [$datedue], [$lastreneweddate]);
1962
1963 Renews a loan.
1964
1965 C<$borrowernumber> is the borrower number of the patron who currently
1966 has the item.
1967
1968 C<$itemnumber> is the number of the item to renew.
1969
1970 C<$branch> is the library branch.  Defaults to the homebranch of the ITEM.
1971
1972 C<$datedue> can be a C4::Dates object used to set the due date.
1973
1974 C<$lastreneweddate> is an optional ISO-formatted date used to set issues.lastreneweddate.  If
1975 this parameter is not supplied, lastreneweddate is set to the current date.
1976
1977 If C<$datedue> is the empty string, C<&AddRenewal> will calculate the due date automatically
1978 from the book's item type.
1979
1980 =cut
1981
1982 sub AddRenewal {
1983         my $borrowernumber = shift or return undef;
1984         my     $itemnumber = shift or return undef;
1985     my $item   = GetItem($itemnumber) or return undef;
1986     my $biblio = GetBiblioFromItemNumber($itemnumber) or return undef;
1987     my $branch  = (@_) ? shift : $item->{homebranch};   # opac-renew doesn't send branch
1988     my $datedue = shift;
1989     my $lastreneweddate = shift;
1990
1991     # If the due date wasn't specified, calculate it by adding the
1992     # book's loan length to today's date.
1993     unless ($datedue && $datedue->output('iso')) {
1994
1995         my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 ) or return undef;
1996         my $loanlength = GetLoanLength(
1997             $borrower->{'categorycode'},
1998              (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1999                         $item->{homebranch}                     # item's homebranch determines loanlength OR do we want the branch specified by the AddRenewal argument?
2000         );
2001                 #FIXME -- use circControl?
2002                 $datedue =  CalcDateDue(C4::Dates->new(),$loanlength,$branch);  # this branch is the transactional branch.
2003                                                                 # The question of whether to use item's homebranch calendar is open.
2004     }
2005
2006     # $lastreneweddate defaults to today.
2007     unless (defined $lastreneweddate) {
2008         $lastreneweddate = strftime( "%Y-%m-%d", localtime );
2009     }
2010
2011     my $dbh = C4::Context->dbh;
2012     # Find the issues record for this book
2013     my $sth =
2014       $dbh->prepare("SELECT * FROM issues
2015                         WHERE borrowernumber=? 
2016                         AND itemnumber=?"
2017       );
2018     $sth->execute( $borrowernumber, $itemnumber );
2019     my $issuedata = $sth->fetchrow_hashref;
2020     $sth->finish;
2021
2022     # Update the issues record to have the new due date, and a new count
2023     # of how many times it has been renewed.
2024     my $renews = $issuedata->{'renewals'} + 1;
2025     $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?, lastreneweddate = ?
2026                             WHERE borrowernumber=? 
2027                             AND itemnumber=?"
2028     );
2029     $sth->execute( $datedue->output('iso'), $renews, $lastreneweddate, $borrowernumber, $itemnumber );
2030     $sth->finish;
2031
2032     # Update the renewal count on the item, and tell zebra to reindex
2033     $renews = $biblio->{'renewals'} + 1;
2034     ModItem({ renewals => $renews }, $biblio->{'biblionumber'}, $itemnumber);
2035
2036     # Charge a new rental fee, if applicable?
2037     my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2038     if ( $charge > 0 ) {
2039         my $accountno = getnextacctno( $borrowernumber );
2040         my $item = GetBiblioFromItemNumber($itemnumber);
2041         $sth = $dbh->prepare(
2042                 "INSERT INTO accountlines
2043                     (date,
2044                                         borrowernumber, accountno, amount,
2045                     description,
2046                                         accounttype, amountoutstanding, itemnumber
2047                                         )
2048                     VALUES (now(),?,?,?,?,?,?,?)"
2049         );
2050         $sth->execute( $borrowernumber, $accountno, $charge,
2051             "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
2052             'Rent', $charge, $itemnumber );
2053         $sth->finish;
2054     }
2055     # Log the renewal
2056     UpdateStats( $branch, 'renew', $charge, '', $itemnumber, $item->{itype}, $borrowernumber);
2057         return $datedue;
2058 }
2059
2060 sub GetRenewCount {
2061     # check renewal status
2062     my ($bornum,$itemno)=@_;
2063     my $dbh = C4::Context->dbh;
2064     my $renewcount = 0;
2065         my $renewsallowed = 0;
2066         my $renewsleft = 0;
2067     # Look in the issues table for this item, lent to this borrower,
2068     # and not yet returned.
2069
2070     # FIXME - I think this function could be redone to use only one SQL call.
2071     my $sth = $dbh->prepare("select * from issues
2072                                 where (borrowernumber = ?)
2073                                 and (itemnumber = ?)");
2074     $sth->execute($bornum,$itemno);
2075     my $data = $sth->fetchrow_hashref;
2076     $renewcount = $data->{'renewals'} if $data->{'renewals'};
2077     $sth->finish;
2078     my $query = "SELECT renewalsallowed FROM items ";
2079     $query .= (C4::Context->preference('item-level_itypes'))
2080                 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2081                 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
2082                    LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2083     $query .= "WHERE items.itemnumber = ?";
2084     my $sth2 = $dbh->prepare($query);
2085     $sth2->execute($itemno);
2086     my $data2 = $sth2->fetchrow_hashref();
2087     $renewsallowed = $data2->{'renewalsallowed'};
2088     $renewsleft = $renewsallowed - $renewcount;
2089     return ($renewcount,$renewsallowed,$renewsleft);
2090 }
2091
2092 =head2 GetIssuingCharges
2093
2094 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
2095
2096 Calculate how much it would cost for a given patron to borrow a given
2097 item, including any applicable discounts.
2098
2099 C<$itemnumber> is the item number of item the patron wishes to borrow.
2100
2101 C<$borrowernumber> is the patron's borrower number.
2102
2103 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
2104 and C<$item_type> is the code for the item's item type (e.g., C<VID>
2105 if it's a video).
2106
2107 =cut
2108
2109 sub GetIssuingCharges {
2110
2111     # calculate charges due
2112     my ( $itemnumber, $borrowernumber ) = @_;
2113     my $charge = 0;
2114     my $dbh    = C4::Context->dbh;
2115     my $item_type;
2116
2117     # Get the book's item type and rental charge (via its biblioitem).
2118     my $qcharge =     "SELECT itemtypes.itemtype,rentalcharge FROM items
2119             LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
2120         $qcharge .= (C4::Context->preference('item-level_itypes'))
2121                 ? " LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2122                 : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2123         
2124     $qcharge .=      "WHERE items.itemnumber =?";
2125    
2126     my $sth1 = $dbh->prepare($qcharge);
2127     $sth1->execute($itemnumber);
2128     if ( my $data1 = $sth1->fetchrow_hashref ) {
2129         $item_type = $data1->{'itemtype'};
2130         $charge    = $data1->{'rentalcharge'};
2131         my $q2 = "SELECT rentaldiscount FROM borrowers
2132             LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
2133             WHERE borrowers.borrowernumber = ?
2134             AND issuingrules.itemtype = ?";
2135         my $sth2 = $dbh->prepare($q2);
2136         $sth2->execute( $borrowernumber, $item_type );
2137         if ( my $data2 = $sth2->fetchrow_hashref ) {
2138             my $discount = $data2->{'rentaldiscount'};
2139             if ( $discount eq 'NULL' ) {
2140                 $discount = 0;
2141             }
2142             $charge = ( $charge * ( 100 - $discount ) ) / 100;
2143         }
2144         $sth2->finish;
2145     }
2146
2147     $sth1->finish;
2148     return ( $charge, $item_type );
2149 }
2150
2151 =head2 AddIssuingCharge
2152
2153 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
2154
2155 =cut
2156
2157 sub AddIssuingCharge {
2158     my ( $itemnumber, $borrowernumber, $charge ) = @_;
2159     my $dbh = C4::Context->dbh;
2160     my $nextaccntno = getnextacctno( $borrowernumber );
2161     my $query ="
2162         INSERT INTO accountlines
2163             (borrowernumber, itemnumber, accountno,
2164             date, amount, description, accounttype,
2165             amountoutstanding)
2166         VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
2167     ";
2168     my $sth = $dbh->prepare($query);
2169     $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
2170     $sth->finish;
2171 }
2172
2173 =head2 GetTransfers
2174
2175 GetTransfers($itemnumber);
2176
2177 =cut
2178
2179 sub GetTransfers {
2180     my ($itemnumber) = @_;
2181
2182     my $dbh = C4::Context->dbh;
2183
2184     my $query = '
2185         SELECT datesent,
2186                frombranch,
2187                tobranch
2188         FROM branchtransfers
2189         WHERE itemnumber = ?
2190           AND datearrived IS NULL
2191         ';
2192     my $sth = $dbh->prepare($query);
2193     $sth->execute($itemnumber);
2194     my @row = $sth->fetchrow_array();
2195     $sth->finish;
2196     return @row;
2197 }
2198
2199
2200 =head2 GetTransfersFromTo
2201
2202 @results = GetTransfersFromTo($frombranch,$tobranch);
2203
2204 Returns the list of pending transfers between $from and $to branch
2205
2206 =cut
2207
2208 sub GetTransfersFromTo {
2209     my ( $frombranch, $tobranch ) = @_;
2210     return unless ( $frombranch && $tobranch );
2211     my $dbh   = C4::Context->dbh;
2212     my $query = "
2213         SELECT itemnumber,datesent,frombranch
2214         FROM   branchtransfers
2215         WHERE  frombranch=?
2216           AND  tobranch=?
2217           AND datearrived IS NULL
2218     ";
2219     my $sth = $dbh->prepare($query);
2220     $sth->execute( $frombranch, $tobranch );
2221     my @gettransfers;
2222
2223     while ( my $data = $sth->fetchrow_hashref ) {
2224         push @gettransfers, $data;
2225     }
2226     $sth->finish;
2227     return (@gettransfers);
2228 }
2229
2230 =head2 DeleteTransfer
2231
2232 &DeleteTransfer($itemnumber);
2233
2234 =cut
2235
2236 sub DeleteTransfer {
2237     my ($itemnumber) = @_;
2238     my $dbh          = C4::Context->dbh;
2239     my $sth          = $dbh->prepare(
2240         "DELETE FROM branchtransfers
2241          WHERE itemnumber=?
2242          AND datearrived IS NULL "
2243     );
2244     $sth->execute($itemnumber);
2245     $sth->finish;
2246 }
2247
2248 =head2 AnonymiseIssueHistory
2249
2250 $rows = AnonymiseIssueHistory($borrowernumber,$date)
2251
2252 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
2253 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
2254
2255 return the number of affected rows.
2256
2257 =cut
2258
2259 sub AnonymiseIssueHistory {
2260     my $date           = shift;
2261     my $borrowernumber = shift;
2262     my $dbh            = C4::Context->dbh;
2263     my $query          = "
2264         UPDATE old_issues
2265         SET    borrowernumber = NULL
2266         WHERE  returndate < '".$date."'
2267           AND borrowernumber IS NOT NULL
2268     ";
2269     $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
2270     my $rows_affected = $dbh->do($query);
2271     return $rows_affected;
2272 }
2273
2274 =head2 updateWrongTransfer
2275
2276 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
2277
2278 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 
2279
2280 =cut
2281
2282 sub updateWrongTransfer {
2283         my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
2284         my $dbh = C4::Context->dbh;     
2285 # first step validate the actual line of transfert .
2286         my $sth =
2287                 $dbh->prepare(
2288                         "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
2289                 );
2290                 $sth->execute($FromLibrary,$itemNumber);
2291                 $sth->finish;
2292
2293 # second step create a new line of branchtransfer to the right location .
2294         ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
2295
2296 #third step changing holdingbranch of item
2297         UpdateHoldingbranch($FromLibrary,$itemNumber);
2298 }
2299
2300 =head2 UpdateHoldingbranch
2301
2302 $items = UpdateHoldingbranch($branch,$itmenumber);
2303 Simple methode for updating hodlingbranch in items BDD line
2304
2305 =cut
2306
2307 sub UpdateHoldingbranch {
2308         my ( $branch,$itemnumber ) = @_;
2309     ModItem({ holdingbranch => $branch }, undef, $itemnumber);
2310 }
2311
2312 =head2 CalcDateDue
2313
2314 $newdatedue = CalcDateDue($startdate,$loanlength,$branchcode);
2315 this function calculates the due date given the loan length ,
2316 checking against the holidays calendar as per the 'useDaysMode' syspref.
2317 C<$startdate>   = C4::Dates object representing start date of loan period (assumed to be today)
2318 C<$branch>  = location whose calendar to use
2319 C<$loanlength>  = loan length prior to adjustment
2320 =cut
2321
2322 sub CalcDateDue { 
2323         my ($startdate,$loanlength,$branch) = @_;
2324         if(C4::Context->preference('useDaysMode') eq 'Days') {  # ignoring calendar
2325                 my $datedue = time + ($loanlength) * 86400;
2326         #FIXME - assumes now even though we take a startdate 
2327                 my @datearr  = localtime($datedue);
2328                 return C4::Dates->new( sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
2329         } else {
2330                 my $calendar = C4::Calendar->new(  branchcode => $branch );
2331                 my $datedue = $calendar->addDate($startdate, $loanlength);
2332                 return $datedue;
2333         }
2334 }
2335
2336 =head2 CheckValidDatedue
2337        This function does not account for holiday exceptions nor does it handle the 'useDaysMode' syspref .
2338        To be replaced by CalcDateDue() once C4::Calendar use is tested.
2339
2340 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
2341 this function validates the loan length against the holidays calendar, and adjusts the due date as per the 'useDaysMode' syspref.
2342 C<$date_due>   = returndate calculate with no day check
2343 C<$itemnumber>  = itemnumber
2344 C<$branchcode>  = location of issue (affected by 'CircControl' syspref)
2345 C<$loanlength>  = loan length prior to adjustment
2346 =cut
2347
2348 sub CheckValidDatedue {
2349 my ($date_due,$itemnumber,$branchcode)=@_;
2350 my @datedue=split('-',$date_due->output('iso'));
2351 my $years=$datedue[0];
2352 my $month=$datedue[1];
2353 my $day=$datedue[2];
2354 # die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
2355 my $dow;
2356 for (my $i=0;$i<2;$i++){
2357     $dow=Day_of_Week($years,$month,$day);
2358     ($dow=0) if ($dow>6);
2359     my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
2360     my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2361     my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2362         if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
2363         $i=0;
2364         (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
2365         }
2366     }
2367     my $newdatedue=C4::Dates->new(sprintf("%04d-%02d-%02d",$years,$month,$day),'iso');
2368 return $newdatedue;
2369 }
2370
2371
2372 =head2 CheckRepeatableHolidays
2373
2374 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
2375 this function checks if the date due is a repeatable holiday
2376 C<$date_due>   = returndate calculate with no day check
2377 C<$itemnumber>  = itemnumber
2378 C<$branchcode>  = localisation of issue 
2379
2380 =cut
2381
2382 sub CheckRepeatableHolidays{
2383 my($itemnumber,$week_day,$branchcode)=@_;
2384 my $dbh = C4::Context->dbh;
2385 my $query = qq|SELECT count(*)  
2386         FROM repeatable_holidays 
2387         WHERE branchcode=?
2388         AND weekday=?|;
2389 my $sth = $dbh->prepare($query);
2390 $sth->execute($branchcode,$week_day);
2391 my $result=$sth->fetchrow;
2392 $sth->finish;
2393 return $result;
2394 }
2395
2396
2397 =head2 CheckSpecialHolidays
2398
2399 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2400 this function check if the date is a special holiday
2401 C<$years>   = the years of datedue
2402 C<$month>   = the month of datedue
2403 C<$day>     = the day of datedue
2404 C<$itemnumber>  = itemnumber
2405 C<$branchcode>  = localisation of issue 
2406
2407 =cut
2408
2409 sub CheckSpecialHolidays{
2410 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
2411 my $dbh = C4::Context->dbh;
2412 my $query=qq|SELECT count(*) 
2413              FROM `special_holidays`
2414              WHERE year=?
2415              AND month=?
2416              AND day=?
2417              AND branchcode=?
2418             |;
2419 my $sth = $dbh->prepare($query);
2420 $sth->execute($years,$month,$day,$branchcode);
2421 my $countspecial=$sth->fetchrow ;
2422 $sth->finish;
2423 return $countspecial;
2424 }
2425
2426 =head2 CheckRepeatableSpecialHolidays
2427
2428 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2429 this function check if the date is a repeatble special holidays
2430 C<$month>   = the month of datedue
2431 C<$day>     = the day of datedue
2432 C<$itemnumber>  = itemnumber
2433 C<$branchcode>  = localisation of issue 
2434
2435 =cut
2436
2437 sub CheckRepeatableSpecialHolidays{
2438 my ($month,$day,$itemnumber,$branchcode) = @_;
2439 my $dbh = C4::Context->dbh;
2440 my $query=qq|SELECT count(*) 
2441              FROM `repeatable_holidays`
2442              WHERE month=?
2443              AND day=?
2444              AND branchcode=?
2445             |;
2446 my $sth = $dbh->prepare($query);
2447 $sth->execute($month,$day,$branchcode);
2448 my $countspecial=$sth->fetchrow ;
2449 $sth->finish;
2450 return $countspecial;
2451 }
2452
2453
2454
2455 sub CheckValidBarcode{
2456 my ($barcode) = @_;
2457 my $dbh = C4::Context->dbh;
2458 my $query=qq|SELECT count(*) 
2459              FROM items 
2460              WHERE barcode=?
2461             |;
2462 my $sth = $dbh->prepare($query);
2463 $sth->execute($barcode);
2464 my $exist=$sth->fetchrow ;
2465 $sth->finish;
2466 return $exist;
2467 }
2468
2469 =head2 IsBranchTransferAllowed
2470
2471 $allowed = IsBranchTransferAllowed( $toBranch, $fromBranch, $itemtype );
2472
2473 =cut
2474
2475 sub IsBranchTransferAllowed {
2476         my ( $toBranch, $fromBranch, $itemtype ) = @_;
2477     
2478         if ( $toBranch eq $fromBranch ) { return 1; } ## Short circuit for speed.
2479         
2480         my $dbh = C4::Context->dbh;
2481             
2482         my $sth = $dbh->prepare('SELECT * FROM branch_transfer_limits WHERE toBranch = ? AND fromBranch = ? AND itemtype = ?');
2483         $sth->execute( $toBranch, $fromBranch, $itemtype );
2484         my $limit = $sth->fetchrow_hashref();
2485                         
2486         ## If a row is found, then that combination is not allowed, if no matching row is found, then the combination *is allowed*
2487         if ( $limit->{'limitId'} ) {
2488                 return 0;
2489         } else {
2490                 return 1;
2491         }
2492 }                                                        
2493
2494 =head2 CreateBranchTransferLimit
2495
2496 CreateBranchTransferLimit( $toBranch, $fromBranch, $itemtype );
2497
2498 =cut
2499
2500 sub CreateBranchTransferLimit {
2501    my ( $toBranch, $fromBranch, $itemtype ) = @_;
2502    
2503    my $dbh = C4::Context->dbh;
2504    
2505    my $sth = $dbh->prepare("INSERT INTO branch_transfer_limits ( itemtype, toBranch, fromBranch ) VALUES ( ?, ?, ? )");
2506    $sth->execute( $itemtype, $toBranch, $fromBranch );
2507 }
2508
2509 =head2 DeleteBranchTransferLimits
2510
2511 DeleteBranchTransferLimits();
2512
2513 =cut
2514
2515 sub DeleteBranchTransferLimits {
2516    my $dbh = C4::Context->dbh;
2517    my $sth = $dbh->prepare("TRUNCATE TABLE branch_transfer_limits");
2518    $sth->execute();
2519 }
2520
2521
2522   1;
2523
2524 __END__
2525
2526 =head1 AUTHOR
2527
2528 Koha Developement team <info@koha.org>
2529
2530 =cut
2531