Allow AddIssue to log SIP transactions distinct from others.
[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, $sipmode) = @_;
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         # TODO: for hourly circ, this will need to be a C4::Dates object
873         # and all calls to AddIssue including issuedate will need to pass a Dates object.
874     }
875         if ($borrower and $barcode and $barcodecheck ne '0'){
876                 # find which item we issue
877                 my $item = GetItem('', $barcode) or return undef;       # if we don't get an Item, abort.
878                 my $branch = (C4::Context->preference('CircControl') eq 'PickupLibrary') ? C4::Context->userenv->{'branch'} :
879                      (C4::Context->preference('CircControl') eq 'PatronLibrary') ? $borrower->{'branchcode'}        : 
880                      $item->{'homebranch'};     # fallback to item's homebranch
881                 
882                 # get actual issuing if there is one
883                 my $actualissue = GetItemIssue( $item->{itemnumber});
884                 
885                 # get biblioinformation for this item
886                 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
887                 
888                 #
889                 # check if we just renew the issue.
890                 #
891                 if ($actualissue->{borrowernumber} eq $borrower->{'borrowernumber'}) {
892                         $datedue = AddRenewal(
893                                 $borrower->{'borrowernumber'},
894                                 $item->{'itemnumber'},
895                                 $branch,
896                                 $datedue,
897                 $issuedate, # here interpreted as the renewal date
898                         );
899                 }
900                 else {
901         # it's NOT a renewal
902                         if ( $actualissue->{borrowernumber}) {
903                                 # This book is currently on loan, but not to the person
904                                 # who wants to borrow it now. mark it returned before issuing to the new borrower
905                                 AddReturn(
906                                         $item->{'barcode'},
907                                         C4::Context->userenv->{'branch'}
908                                 );
909                         }
910
911                         # See if the item is on reserve.
912                         my ( $restype, $res ) =
913                           C4::Reserves::CheckReserves( $item->{'itemnumber'} );
914                         if ($restype) {
915                                 my $resbor = $res->{'borrowernumber'};
916                                 if ( $resbor eq $borrower->{'borrowernumber'} ) {
917                                         # The item is reserved by the current patron
918                                         ModReserveFill($res);
919                                 }
920                                 elsif ( $restype eq "Waiting" ) {
921                                         # warn "Waiting";
922                                         # The item is on reserve and waiting, but has been
923                                         # reserved by some other patron.
924                                 }
925                                 elsif ( $restype eq "Reserved" ) {
926                                         # warn "Reserved";
927                                         # The item is reserved by someone else.
928                                         if ($cancelreserve) { # cancel reserves on this item
929                                                 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
930                                         }
931                                 }
932                                 if ($cancelreserve) {
933                                         CancelReserve($res->{'biblionumber'}, 0, $res->{'borrowernumber'});
934                                 }
935                                 else {
936                                         # set waiting reserve to first in reserve queue as book isn't waiting now
937                                         ModReserve(1,
938                                                 $res->{'biblionumber'},
939                                                 $res->{'borrowernumber'},
940                                                 $res->{'branchcode'}
941                                         );
942                                 }
943                         }
944
945                         # Starting process for transfer job (checking transfert and validate it if we have one)
946             my ($datesent) = GetTransfers($item->{'itemnumber'});
947             if ($datesent) {
948         #       updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for visibility of this case (maybe for stats ....)
949                 my $sth =
950                     $dbh->prepare(
951                     "UPDATE branchtransfers 
952                         SET datearrived = now(),
953                         tobranch = ?,
954                         comments = 'Forced branchtransfer'
955                     WHERE itemnumber= ? AND datearrived IS NULL"
956                     );
957                 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
958             }
959
960         # Record in the database the fact that the book was issued.
961         my $sth =
962           $dbh->prepare(
963                 "INSERT INTO issues 
964                     (borrowernumber, itemnumber,issuedate, date_due, branchcode)
965                 VALUES (?,?,?,?,?)"
966           );
967         unless ($datedue) {
968             my $itype = ( C4::Context->preference('item-level_itypes') ) ? $biblio->{'itype'} : $biblio->{'itemtype'};
969             my $loanlength = GetLoanLength( $borrower->{'categorycode'}, $itype, $branch );
970             $datedue = CalcDateDue( C4::Dates->new( $issuedate, 'iso' ), $loanlength, $branch );
971
972             # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
973             if ( C4::Context->preference('ReturnBeforeExpiry') && $datedue->output('iso') gt $borrower->{dateexpiry} ) {
974                 $datedue = C4::Dates->new( $borrower->{dateexpiry}, 'iso' );
975             }
976         }
977         $sth->execute(
978             $borrower->{'borrowernumber'},      # borrowernumber
979             $item->{'itemnumber'},              # itemnumber
980             $issuedate,                         # issuedate
981             $datedue->output('iso'),            # date_due
982             C4::Context->userenv->{'branch'}    # branchcode
983         );
984         $sth->finish;
985         $item->{'issues'}++;
986         ModItem({ issues           => $item->{'issues'},
987                   holdingbranch    => C4::Context->userenv->{'branch'},
988                   itemlost         => 0,
989                   datelastborrowed => C4::Dates->new()->output('iso'),
990                   onloan           => $datedue->output('iso'),
991                 }, $item->{'biblionumber'}, $item->{'itemnumber'});
992         ModDateLastSeen( $item->{'itemnumber'} );
993         
994         # If it costs to borrow this book, charge it to the patron's account.
995         my ( $charge, $itemtype ) = GetIssuingCharges(
996             $item->{'itemnumber'},
997             $borrower->{'borrowernumber'}
998         );
999         if ( $charge > 0 ) {
1000             AddIssuingCharge(
1001                 $item->{'itemnumber'},
1002                 $borrower->{'borrowernumber'}, $charge
1003             );
1004             $item->{'charge'} = $charge;
1005         }
1006
1007         # Record the fact that this book was issued.
1008         &UpdateStats(
1009             C4::Context->userenv->{'branch'},
1010             'issue', $charge,
1011             ($sipmode ? "SIP-$sipmode" : ''), $item->{'itemnumber'},
1012             $item->{'itype'}, $borrower->{'borrowernumber'}
1013         );
1014     }
1015     
1016     logaction("CIRCULATION", "ISSUE", $borrower->{'borrowernumber'}, $biblio->{'biblionumber'}) 
1017         if C4::Context->preference("IssueLog");
1018   }
1019   return ($datedue);    # not necessarily the same as when it came in!
1020 }
1021
1022 =head2 GetLoanLength
1023
1024 Get loan length for an itemtype, a borrower type and a branch
1025
1026 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1027
1028 =cut
1029
1030 sub GetLoanLength {
1031     my ( $borrowertype, $itemtype, $branchcode ) = @_;
1032     my $dbh = C4::Context->dbh;
1033     my $sth =
1034       $dbh->prepare(
1035 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1036       );
1037 # warn "in get loan lenght $borrowertype $itemtype $branchcode ";
1038 # try to find issuelength & return the 1st available.
1039 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1040     $sth->execute( $borrowertype, $itemtype, $branchcode );
1041     my $loanlength = $sth->fetchrow_hashref;
1042     return $loanlength->{issuelength}
1043       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1044
1045     $sth->execute( $borrowertype, "*", $branchcode );
1046     $loanlength = $sth->fetchrow_hashref;
1047     return $loanlength->{issuelength}
1048       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1049
1050     $sth->execute( "*", $itemtype, $branchcode );
1051     $loanlength = $sth->fetchrow_hashref;
1052     return $loanlength->{issuelength}
1053       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1054
1055     $sth->execute( "*", "*", $branchcode );
1056     $loanlength = $sth->fetchrow_hashref;
1057     return $loanlength->{issuelength}
1058       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1059
1060     $sth->execute( $borrowertype, $itemtype, "*" );
1061     $loanlength = $sth->fetchrow_hashref;
1062     return $loanlength->{issuelength}
1063       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1064
1065     $sth->execute( $borrowertype, "*", "*" );
1066     $loanlength = $sth->fetchrow_hashref;
1067     return $loanlength->{issuelength}
1068       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1069
1070     $sth->execute( "*", $itemtype, "*" );
1071     $loanlength = $sth->fetchrow_hashref;
1072     return $loanlength->{issuelength}
1073       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1074
1075     $sth->execute( "*", "*", "*" );
1076     $loanlength = $sth->fetchrow_hashref;
1077     return $loanlength->{issuelength}
1078       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1079
1080     # if no rule is set => 21 days (hardcoded)
1081     return 21;
1082 }
1083
1084 =head2 GetIssuingRule
1085
1086 FIXME - This is a copy-paste of GetLoanLength 
1087 as a stop-gap.  Do not wish to change API for GetLoanLength 
1088 this close to release, however, Overdues::GetIssuingRules is broken.
1089
1090 Get the issuing rule for an itemtype, a borrower type and a branch
1091 Returns a hashref from the issuingrules table.
1092
1093 my $irule = &GetIssuingRule($borrowertype,$itemtype,branchcode)
1094
1095 =cut
1096
1097 sub GetIssuingRule {
1098     my ( $borrowertype, $itemtype, $branchcode ) = @_;
1099     my $dbh = C4::Context->dbh;
1100     my $sth =  $dbh->prepare( "select * from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"  );
1101     my $irule;
1102
1103         $sth->execute( $borrowertype, $itemtype, $branchcode );
1104     $irule = $sth->fetchrow_hashref;
1105     return $irule if defined($irule) ;
1106
1107     $sth->execute( $borrowertype, "*", $branchcode );
1108     $irule = $sth->fetchrow_hashref;
1109     return $irule if defined($irule) ;
1110
1111     $sth->execute( "*", $itemtype, $branchcode );
1112     $irule = $sth->fetchrow_hashref;
1113     return $irule if defined($irule) ;
1114
1115     $sth->execute( "*", "*", $branchcode );
1116     $irule = $sth->fetchrow_hashref;
1117     return $irule if defined($irule) ;
1118
1119     $sth->execute( $borrowertype, $itemtype, "*" );
1120     $irule = $sth->fetchrow_hashref;
1121     return $irule if defined($irule) ;
1122
1123     $sth->execute( $borrowertype, "*", "*" );
1124     $irule = $sth->fetchrow_hashref;
1125     return $irule if defined($irule) ;
1126
1127     $sth->execute( "*", $itemtype, "*" );
1128     $irule = $sth->fetchrow_hashref;
1129     return $irule if defined($irule) ;
1130
1131     $sth->execute( "*", "*", "*" );
1132     $irule = $sth->fetchrow_hashref;
1133     return $irule if defined($irule) ;
1134
1135     # if no rule matches,
1136     return undef;
1137 }
1138
1139 =head2 GetBranchBorrowerCircRule
1140
1141 =over 4
1142
1143 my $branch_cat_rule = GetBranchBorrowerCircRule($branchcode, $categorycode);
1144
1145 =back
1146
1147 Retrieves circulation rule attributes that apply to the given
1148 branch and patron category, regardless of item type.  
1149 The return value is a hashref containing the following key:
1150
1151 maxissueqty - maximum number of loans that a
1152 patron of the given category can have at the given
1153 branch.  If the value is undef, no limit.
1154
1155 This will first check for a specific branch and
1156 category match from branch_borrower_circ_rules. 
1157
1158 If no rule is found, it will then check default_branch_circ_rules
1159 (same branch, default category).  If no rule is found,
1160 it will then check default_borrower_circ_rules (default 
1161 branch, same category), then failing that, default_circ_rules
1162 (default branch, default category).
1163
1164 If no rule has been found in the database, it will default to
1165 the buillt in rule:
1166
1167 maxissueqty - undef
1168
1169 C<$branchcode> and C<$categorycode> should contain the
1170 literal branch code and patron category code, respectively - no
1171 wildcards.
1172
1173 =cut
1174
1175 sub GetBranchBorrowerCircRule {
1176     my $branchcode = shift;
1177     my $categorycode = shift;
1178
1179     my $branch_cat_query = "SELECT maxissueqty
1180                             FROM branch_borrower_circ_rules
1181                             WHERE branchcode = ?
1182                             AND   categorycode = ?";
1183     my $dbh = C4::Context->dbh();
1184     my $sth = $dbh->prepare($branch_cat_query);
1185     $sth->execute($branchcode, $categorycode);
1186     my $result;
1187     if ($result = $sth->fetchrow_hashref()) {
1188         return $result;
1189     }
1190
1191     # try same branch, default borrower category
1192     my $branch_query = "SELECT maxissueqty
1193                         FROM default_branch_circ_rules
1194                         WHERE branchcode = ?";
1195     $sth = $dbh->prepare($branch_query);
1196     $sth->execute($branchcode);
1197     if ($result = $sth->fetchrow_hashref()) {
1198         return $result;
1199     }
1200
1201     # try default branch, same borrower category
1202     my $category_query = "SELECT maxissueqty
1203                           FROM default_borrower_circ_rules
1204                           WHERE categorycode = ?";
1205     $sth = $dbh->prepare($category_query);
1206     $sth->execute($categorycode);
1207     if ($result = $sth->fetchrow_hashref()) {
1208         return $result;
1209     }
1210   
1211     # try default branch, default borrower category
1212     my $default_query = "SELECT maxissueqty
1213                           FROM default_circ_rules";
1214     $sth = $dbh->prepare($default_query);
1215     $sth->execute();
1216     if ($result = $sth->fetchrow_hashref()) {
1217         return $result;
1218     }
1219     
1220     # built-in default circulation rule
1221     return {
1222         maxissueqty => undef,
1223     };
1224 }
1225
1226 =head2 AddReturn
1227
1228 ($doreturn, $messages, $iteminformation, $borrower) =
1229     &AddReturn($barcode, $branch, $exemptfine, $dropbox);
1230
1231 Returns a book.
1232
1233 =over 4
1234
1235 =item C<$barcode> is the bar code of the book being returned.
1236
1237 =item C<$branch> is the code of the branch where the book is being returned.
1238
1239 =item C<$exemptfine> indicates that overdue charges for the item will be
1240 removed.
1241
1242 =item C<$dropbox> indicates that the check-in date is assumed to be
1243 yesterday, or the last non-holiday as defined in C4::Calendar .  If
1244 overdue charges are applied and C<$dropbox> is true, the last charge
1245 will be removed.  This assumes that the fines accrual script has run
1246 for _today_.
1247
1248 =back
1249
1250 C<&AddReturn> returns a list of four items:
1251
1252 C<$doreturn> is true iff the return succeeded.
1253
1254 C<$messages> is a reference-to-hash giving the reason for failure:
1255
1256 =over 4
1257
1258 =item C<BadBarcode>
1259
1260 No item with this barcode exists. The value is C<$barcode>.
1261
1262 =item C<NotIssued>
1263
1264 The book is not currently on loan. The value is C<$barcode>.
1265
1266 =item C<IsPermanent>
1267
1268 The book's home branch is a permanent collection. If you have borrowed
1269 this book, you are not allowed to return it. The value is the code for
1270 the book's home branch.
1271
1272 =item C<wthdrawn>
1273
1274 This book has been withdrawn/cancelled. The value should be ignored.
1275
1276 =item C<ResFound>
1277
1278 The item was reserved. The value is a reference-to-hash whose keys are
1279 fields from the reserves table of the Koha database, and
1280 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1281 either C<Waiting>, C<Reserved>, or 0.
1282
1283 =back
1284
1285 C<$borrower> is a reference-to-hash, giving information about the
1286 patron who last borrowed the book.
1287
1288 =cut
1289
1290 sub AddReturn {
1291     my ( $barcode, $branch, $exemptfine, $dropbox ) = @_;
1292     my $dbh      = C4::Context->dbh;
1293     my $messages;
1294     my $doreturn = 1;
1295     my $borrower;
1296     my $validTransfert = 0;
1297     my $reserveDone = 0;
1298     
1299     # get information on item
1300     my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1301     my $biblio = GetBiblioItemData($iteminformation->{'biblioitemnumber'});
1302 #     use Data::Dumper;warn Data::Dumper::Dumper($iteminformation);  
1303     unless ($iteminformation->{'itemnumber'} ) {
1304         $messages->{'BadBarcode'} = $barcode;
1305         $doreturn = 0;
1306     } else {
1307         # find the borrower
1308         if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1309             $messages->{'NotIssued'} = $barcode;
1310             # even though item is not on loan, it may still
1311             # be transferred; therefore, get current branch information
1312             my $curr_iteminfo = GetItem($iteminformation->{'itemnumber'});
1313             $iteminformation->{'homebranch'} = $curr_iteminfo->{'homebranch'};
1314             $iteminformation->{'holdingbranch'} = $curr_iteminfo->{'holdingbranch'};
1315             $doreturn = 0;
1316         }
1317     
1318         # check if the book is in a permanent collection....
1319         my $hbr      = $iteminformation->{C4::Context->preference("HomeOrHoldingBranch")};
1320         my $branches = GetBranches();
1321                 # FIXME -- This 'PE' attribute is largely undocumented.  afaict, there's no user interface that reflects this functionality.
1322         if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1323             $messages->{'IsPermanent'} = $hbr;
1324         }
1325                 
1326                     # if independent branches are on and returning to different branch, refuse the return
1327         if ($hbr ne C4::Context->userenv->{'branch'} && C4::Context->preference("IndependantBranches")){
1328                           $messages->{'Wrongbranch'} = 1;
1329                           $doreturn=0;
1330                     }
1331                         
1332         # check that the book has been cancelled
1333         if ( $iteminformation->{'wthdrawn'} ) {
1334             $messages->{'wthdrawn'} = 1;
1335             $doreturn = 0;
1336         }
1337     
1338     #     new op dev : if the book returned in an other branch update the holding branch
1339     
1340     # update issues, thereby returning book (should push this out into another subroutine
1341         $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1342     
1343     # case of a return of document (deal with issues and holdingbranch)
1344     
1345         if ($doreturn) {
1346                         my $circControlBranch;
1347                         if($dropbox) {
1348                                 # don't allow dropbox mode to create an invalid entry in issues (issuedate > returndate) FIXME: actually checks eq, not gt
1349                                 undef($dropbox) if ( $iteminformation->{'issuedate'} eq C4::Dates->today('iso') );
1350                                 if (C4::Context->preference('CircControl') eq 'ItemHomeBranch' ) {
1351                                         $circControlBranch = $iteminformation->{homebranch};
1352                                 } elsif ( C4::Context->preference('CircControl') eq 'PatronLibrary') {
1353                                         $circControlBranch = $borrower->{branchcode};
1354                                 } else { # CircControl must be PickupLibrary.
1355                                         $circControlBranch = $iteminformation->{holdingbranch};
1356                                         # FIXME - is this right ? are we sure that the holdingbranch is still the pickup branch?
1357                                 }
1358                         }
1359             MarkIssueReturned($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'},$circControlBranch);
1360             $messages->{'WasReturned'} = 1;    # FIXME is the "= 1" right?
1361         }
1362     
1363     # continue to deal with returns cases, but not only if we have an issue
1364     
1365         # the holdingbranch is updated if the document is returned in an other location .
1366         if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} ) {
1367                         UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'}); 
1368                         #               reload iteminformation holdingbranch with the userenv value
1369                         $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1370         }
1371         ModDateLastSeen( $iteminformation->{'itemnumber'} );
1372         ModItem({ onloan => undef }, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'});
1373                     
1374                     if ($iteminformation->{borrowernumber}){
1375                           ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1376         }       
1377         # fix up the accounts.....
1378         if ( $iteminformation->{'itemlost'} ) {
1379             $messages->{'WasLost'} = 1;
1380         }
1381     
1382     # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1383     #     check if we have a transfer for this document
1384         my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1385     
1386     #     if we have a transfer to do, we update the line of transfers with the datearrived
1387         if ($datesent) {
1388             if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1389                     my $sth =
1390                     $dbh->prepare(
1391                             "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1392                     );
1393                     $sth->execute( $iteminformation->{'itemnumber'} );
1394                     $sth->finish;
1395     #         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'
1396             C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1397             }
1398         else {
1399             $messages->{'WrongTransfer'} = $tobranch;
1400             $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1401         }
1402         $validTransfert = 1;
1403         }
1404     
1405     # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
1406         # fix up the accounts.....
1407         if ($iteminformation->{'itemlost'}) {
1408                 FixAccountForLostAndReturned($iteminformation, $borrower);
1409                 $messages->{'WasLost'} = 1;
1410         }
1411         # fix up the overdues in accounts...
1412         FixOverduesOnReturn( $borrower->{'borrowernumber'},
1413             $iteminformation->{'itemnumber'}, $exemptfine, $dropbox );
1414     
1415     # find reserves.....
1416     #     if we don't have a reserve with the status W, we launch the Checkreserves routine
1417         my ( $resfound, $resrec ) =
1418         C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1419         if ($resfound) {
1420             $resrec->{'ResFound'}   = $resfound;
1421             $messages->{'ResFound'} = $resrec;
1422             $reserveDone = 1;
1423         }
1424     
1425         # update stats?
1426         # Record the fact that this book was returned.
1427         UpdateStats(
1428             $branch, 'return', '0', '',
1429             $iteminformation->{'itemnumber'},
1430             $biblio->{'itemtype'},
1431             $borrower->{'borrowernumber'}
1432         );
1433         
1434         logaction("CIRCULATION", "RETURN", $iteminformation->{borrowernumber}, $iteminformation->{'biblionumber'}) 
1435             if C4::Context->preference("ReturnLog");
1436         
1437         #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1438         #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1439         
1440         if ( ( $branch ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1441                         if (C4::Context->preference("AutomaticItemReturn") == 1) {
1442                                 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1443                                 $messages->{'WasTransfered'} = 1;
1444                         } elsif ( C4::Context->preference("UseBranchTransferLimits") == 1 
1445                                         && ! IsTransferAllowed( $branch, $iteminformation->{'homebranch'}, $iteminformation->{'itemtype'} )
1446                                 ) {
1447                                 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1448                                 $messages->{'WasTransfered'} = 1;
1449                         }
1450                         else {
1451                                 $messages->{'NeedsTransfer'} = 1;
1452                         }
1453         }
1454     }
1455     return ( $doreturn, $messages, $iteminformation, $borrower );
1456 }
1457
1458 =head2 MarkIssueReturned
1459
1460 =over 4
1461
1462 MarkIssueReturned($borrowernumber, $itemnumber, $dropbox_branch, $returndate);
1463
1464 =back
1465
1466 Unconditionally marks an issue as being returned by
1467 moving the C<issues> row to C<old_issues> and
1468 setting C<returndate> to the current date, or
1469 the last non-holiday date of the branccode specified in
1470 C<dropbox_branch> .  Assumes you've already checked that 
1471 it's safe to do this, i.e. last non-holiday > issuedate.
1472
1473 if C<$returndate> is specified (in iso format), it is used as the date
1474 of the return. It is ignored when a dropbox_branch is passed in.
1475
1476 Ideally, this function would be internal to C<C4::Circulation>,
1477 not exported, but it is currently needed by one 
1478 routine in C<C4::Accounts>.
1479
1480 =cut
1481
1482 sub MarkIssueReturned {
1483     my ( $borrowernumber, $itemnumber, $dropbox_branch, $returndate ) = @_;
1484     my $dbh   = C4::Context->dbh;
1485     my $query = "UPDATE issues SET returndate=";
1486     my @bind;
1487     if ($dropbox_branch) {
1488         my $calendar = C4::Calendar->new( branchcode => $dropbox_branch );
1489         my $dropboxdate = $calendar->addDate( C4::Dates->new(), -1 );
1490         $query .= " ? ";
1491         push @bind, $dropboxdate->output('iso');
1492     } elsif ($returndate) {
1493         $query .= " ? ";
1494         push @bind, $returndate;
1495     } else {
1496         $query .= " now() ";
1497     }
1498     $query .= " WHERE  borrowernumber = ?  AND itemnumber = ?";
1499     push @bind, $borrowernumber, $itemnumber;
1500     # FIXME transaction
1501     my $sth_upd  = $dbh->prepare($query);
1502     $sth_upd->execute(@bind);
1503     my $sth_copy = $dbh->prepare("INSERT INTO old_issues SELECT * FROM issues 
1504                                   WHERE borrowernumber = ?
1505                                   AND itemnumber = ?");
1506     $sth_copy->execute($borrowernumber, $itemnumber);
1507     my $sth_del  = $dbh->prepare("DELETE FROM issues
1508                                   WHERE borrowernumber = ?
1509                                   AND itemnumber = ?");
1510     $sth_del->execute($borrowernumber, $itemnumber);
1511 }
1512
1513 =head2 FixOverduesOnReturn
1514
1515     &FixOverduesOnReturn($brn,$itm, $exemptfine, $dropboxmode);
1516
1517 C<$brn> borrowernumber
1518
1519 C<$itm> itemnumber
1520
1521 C<$exemptfine> BOOL -- remove overdue charge associated with this issue. 
1522 C<$dropboxmode> BOOL -- remove lastincrement on overdue charge associated with this issue.
1523
1524 internal function, called only by AddReturn
1525
1526 =cut
1527
1528 sub FixOverduesOnReturn {
1529     my ( $borrowernumber, $item, $exemptfine, $dropbox ) = @_;
1530     my $dbh = C4::Context->dbh;
1531
1532     # check for overdue fine
1533     my $sth =
1534       $dbh->prepare(
1535 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1536       );
1537     $sth->execute( $borrowernumber, $item );
1538
1539     # alter fine to show that the book has been returned
1540    my $data; 
1541         if ($data = $sth->fetchrow_hashref) {
1542         my $uquery;
1543                 my @bind = ($borrowernumber,$item ,$data->{'accountno'});
1544                 if ($exemptfine) {
1545                         $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
1546                         if (C4::Context->preference("FinesLog")) {
1547                         &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
1548                         }
1549                 } elsif ($dropbox && $data->{lastincrement}) {
1550                         my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
1551                         my $amt = $data->{amount} - $data->{lastincrement} ;
1552                         if (C4::Context->preference("FinesLog")) {
1553                         &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
1554                         }
1555                          $uquery = "update accountlines set accounttype='F' ";
1556                          if($outstanding  >= 0 && $amt >=0) {
1557                                 $uquery .= ", amount = ? , amountoutstanding=? ";
1558                                 unshift @bind, ($amt, $outstanding) ;
1559                         }
1560                 } else {
1561                         $uquery = "update accountlines set accounttype='F' ";
1562                 }
1563                 $uquery .= " where (borrowernumber = ?) and (itemnumber = ?) and (accountno = ?)";
1564         my $usth = $dbh->prepare($uquery);
1565         $usth->execute(@bind);
1566         $usth->finish();
1567     }
1568
1569     $sth->finish();
1570     return;
1571 }
1572
1573 =head2 FixAccountForLostAndReturned
1574
1575         &FixAccountForLostAndReturned($iteminfo,$borrower);
1576
1577 Calculates the charge for a book lost and returned (Not exported & used only once)
1578
1579 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1580
1581 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1582
1583 Internal function, called by AddReturn
1584
1585 =cut
1586
1587 sub FixAccountForLostAndReturned {
1588         my ($iteminfo, $borrower) = @_;
1589         my $dbh = C4::Context->dbh;
1590         my $itm = $iteminfo->{'itemnumber'};
1591         # check for charge made for lost book
1592         my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1593         $sth->execute($itm);
1594         if (my $data = $sth->fetchrow_hashref) {
1595         # writeoff this amount
1596                 my $offset;
1597                 my $amount = $data->{'amount'};
1598                 my $acctno = $data->{'accountno'};
1599                 my $amountleft;
1600                 if ($data->{'amountoutstanding'} == $amount) {
1601                 $offset = $data->{'amount'};
1602                 $amountleft = 0;
1603                 } else {
1604                 $offset = $amount - $data->{'amountoutstanding'};
1605                 $amountleft = $data->{'amountoutstanding'} - $amount;
1606                 }
1607                 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1608                         WHERE (borrowernumber = ?)
1609                         AND (itemnumber = ?) AND (accountno = ?) ");
1610                 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1611                 $usth->finish;
1612         #check if any credit is left if so writeoff other accounts
1613                 my $nextaccntno = getnextacctno($data->{'borrowernumber'});
1614                 if ($amountleft < 0){
1615                 $amountleft*=-1;
1616                 }
1617                 if ($amountleft > 0){
1618                 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1619                                                         AND (amountoutstanding >0) ORDER BY date");
1620                 $msth->execute($data->{'borrowernumber'});
1621         # offset transactions
1622                 my $newamtos;
1623                 my $accdata;
1624                 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1625                         if ($accdata->{'amountoutstanding'} < $amountleft) {
1626                         $newamtos = 0;
1627                         $amountleft -= $accdata->{'amountoutstanding'};
1628                         }  else {
1629                         $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1630                         $amountleft = 0;
1631                         }
1632                         my $thisacct = $accdata->{'accountno'};
1633                         my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1634                                         WHERE (borrowernumber = ?)
1635                                         AND (accountno=?)");
1636                         $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1637                         $usth->finish;
1638                         $usth = $dbh->prepare("INSERT INTO accountoffsets
1639                                 (borrowernumber, accountno, offsetaccount,  offsetamount)
1640                                 VALUES
1641                                 (?,?,?,?)");
1642                         $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1643                         $usth->finish;
1644                 }
1645                 $msth->finish;
1646                 }
1647                 if ($amountleft > 0){
1648                         $amountleft*=-1;
1649                 }
1650                 my $desc="Item Returned ".$iteminfo->{'barcode'};
1651                 $usth = $dbh->prepare("INSERT INTO accountlines
1652                         (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1653                         VALUES (?,?,now(),?,?,'CR',?)");
1654                 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1655                 $usth->finish;
1656                 $usth = $dbh->prepare("INSERT INTO accountoffsets
1657                         (borrowernumber, accountno, offsetaccount,  offsetamount)
1658                         VALUES (?,?,?,?)");
1659                 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1660                 $usth->finish;
1661         ModItem({ paidfor => '' }, undef, $itm);
1662         }
1663         $sth->finish;
1664         return;
1665 }
1666
1667 =head2 GetItemIssue
1668
1669 $issues = &GetItemIssue($itemnumber);
1670
1671 Returns patrons currently having a book. nothing if item is not issued atm
1672
1673 C<$itemnumber> is the itemnumber
1674
1675 Returns an array of hashes
1676
1677 FIXME: Though the above says that this function returns nothing if the
1678 item is not issued, this actually returns a hasref that looks like
1679 this:
1680     {
1681       itemnumber => 1,
1682       overdue    => 1
1683     }
1684
1685
1686 =cut
1687
1688 sub GetItemIssue {
1689     my ( $itemnumber) = @_;
1690     return unless $itemnumber;
1691     my $dbh = C4::Context->dbh;
1692     my @GetItemIssues;
1693     
1694     # get today date
1695     my $today = POSIX::strftime("%Y%m%d", localtime);
1696
1697     my $sth = $dbh->prepare(
1698         "SELECT * FROM issues 
1699         LEFT JOIN items ON issues.itemnumber=items.itemnumber
1700     WHERE
1701     issues.itemnumber=?");
1702     $sth->execute($itemnumber);
1703     my $data = $sth->fetchrow_hashref;
1704     my $datedue = $data->{'date_due'};
1705     $datedue =~ s/-//g;
1706     if ( $datedue < $today ) {
1707         $data->{'overdue'} = 1;
1708     }
1709     $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1710     $sth->finish;
1711     return ($data);
1712 }
1713
1714 =head2 GetOpenIssue
1715
1716 $issue = GetOpenIssue( $itemnumber );
1717
1718 Returns the row from the issues table if the item is currently issued, undef if the item is not currently issued
1719
1720 C<$itemnumber> is the item's itemnumber
1721
1722 Returns a hashref
1723
1724 =cut
1725
1726 sub GetOpenIssue {
1727   my ( $itemnumber ) = @_;
1728
1729   my $dbh = C4::Context->dbh;  
1730   my $sth = $dbh->prepare( "SELECT * FROM issues WHERE itemnumber = ? AND returndate IS NULL" );
1731   $sth->execute( $itemnumber );
1732   my $issue = $sth->fetchrow_hashref();
1733   return $issue;
1734 }
1735
1736 =head2 GetItemIssues
1737
1738 $issues = &GetItemIssues($itemnumber, $history);
1739
1740 Returns patrons that have issued a book
1741
1742 C<$itemnumber> is the itemnumber
1743 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1744
1745 Returns an array of hashes
1746
1747 =cut
1748
1749 sub GetItemIssues {
1750     my ( $itemnumber,$history ) = @_;
1751     my $dbh = C4::Context->dbh;
1752     my @GetItemIssues;
1753     
1754     # get today date
1755     my $today = POSIX::strftime("%Y%m%d", localtime);
1756
1757     my $sql = "SELECT * FROM issues 
1758               JOIN borrowers USING (borrowernumber)
1759               JOIN items USING (itemnumber)
1760               WHERE issues.itemnumber = ? ";
1761     if ($history) {
1762         $sql .= "UNION ALL
1763                  SELECT * FROM old_issues 
1764                  LEFT JOIN borrowers USING (borrowernumber)
1765                  JOIN items USING (itemnumber)
1766                  WHERE old_issues.itemnumber = ? ";
1767     }
1768     $sql .= "ORDER BY date_due DESC";
1769     my $sth = $dbh->prepare($sql);
1770     if ($history) {
1771         $sth->execute($itemnumber, $itemnumber);
1772     } else {
1773         $sth->execute($itemnumber);
1774     }
1775     while ( my $data = $sth->fetchrow_hashref ) {
1776         my $datedue = $data->{'date_due'};
1777         $datedue =~ s/-//g;
1778         if ( $datedue < $today ) {
1779             $data->{'overdue'} = 1;
1780         }
1781         my $itemnumber = $data->{'itemnumber'};
1782         push @GetItemIssues, $data;
1783     }
1784     $sth->finish;
1785     return ( \@GetItemIssues );
1786 }
1787
1788 =head2 GetBiblioIssues
1789
1790 $issues = GetBiblioIssues($biblionumber);
1791
1792 this function get all issues from a biblionumber.
1793
1794 Return:
1795 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1796 tables issues and the firstname,surname & cardnumber from borrowers.
1797
1798 =cut
1799
1800 sub GetBiblioIssues {
1801     my $biblionumber = shift;
1802     return undef unless $biblionumber;
1803     my $dbh   = C4::Context->dbh;
1804     my $query = "
1805         SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1806         FROM issues
1807             LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1808             LEFT JOIN items ON issues.itemnumber = items.itemnumber
1809             LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1810             LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1811         WHERE biblio.biblionumber = ?
1812         UNION ALL
1813         SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1814         FROM old_issues
1815             LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
1816             LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
1817             LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1818             LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1819         WHERE biblio.biblionumber = ?
1820         ORDER BY timestamp
1821     ";
1822     my $sth = $dbh->prepare($query);
1823     $sth->execute($biblionumber, $biblionumber);
1824
1825     my @issues;
1826     while ( my $data = $sth->fetchrow_hashref ) {
1827         push @issues, $data;
1828     }
1829     return \@issues;
1830 }
1831
1832 =head2 GetUpcomingDueIssues
1833
1834 =over 4
1835  
1836 my $upcoming_dues = GetUpcomingDueIssues( { days_in_advance => 4 } );
1837
1838 =back
1839
1840 =cut
1841
1842 sub GetUpcomingDueIssues {
1843     my $params = shift;
1844
1845     $params->{'days_in_advance'} = 7 unless exists $params->{'days_in_advance'};
1846     my $dbh = C4::Context->dbh;
1847
1848     my $statement = <<END_SQL;
1849 SELECT issues.*, items.itype as itemtype, items.homebranch, TO_DAYS( date_due )-TO_DAYS( NOW() ) as days_until_due
1850 FROM issues 
1851 LEFT JOIN items USING (itemnumber)
1852 WhERE returndate is NULL
1853 AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ?
1854 END_SQL
1855
1856     my @bind_parameters = ( $params->{'days_in_advance'} );
1857     
1858     my $sth = $dbh->prepare( $statement );
1859     $sth->execute( @bind_parameters );
1860     my $upcoming_dues = $sth->fetchall_arrayref({});
1861     $sth->finish;
1862
1863     return $upcoming_dues;
1864 }
1865
1866 =head2 CanBookBeRenewed
1867
1868 ($ok,$error) = &CanBookBeRenewed($borrowernumber, $itemnumber[, $override_limit]);
1869
1870 Find out whether a borrowed item may be renewed.
1871
1872 C<$dbh> is a DBI handle to the Koha database.
1873
1874 C<$borrowernumber> is the borrower number of the patron who currently
1875 has the item on loan.
1876
1877 C<$itemnumber> is the number of the item to renew.
1878
1879 C<$override_limit>, if supplied with a true value, causes
1880 the limit on the number of times that the loan can be renewed
1881 (as controlled by the item type) to be ignored.
1882
1883 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1884 item must currently be on loan to the specified borrower; renewals
1885 must be allowed for the item's type; and the borrower must not have
1886 already renewed the loan. $error will contain the reason the renewal can not proceed
1887
1888 =cut
1889
1890 sub CanBookBeRenewed {
1891
1892     # check renewal status
1893     my ( $borrowernumber, $itemnumber, $override_limit ) = @_;
1894     my $dbh       = C4::Context->dbh;
1895     my $renews    = 1;
1896     my $renewokay = 0;
1897         my $error;
1898
1899     # Look in the issues table for this item, lent to this borrower,
1900     # and not yet returned.
1901
1902     # FIXME - I think this function could be redone to use only one SQL call.
1903     my $sth1 = $dbh->prepare(
1904         "SELECT * FROM issues
1905             WHERE borrowernumber = ?
1906             AND itemnumber = ?"
1907     );
1908     $sth1->execute( $borrowernumber, $itemnumber );
1909     if ( my $data1 = $sth1->fetchrow_hashref ) {
1910
1911         # Found a matching item
1912
1913         # See if this item may be renewed. This query is convoluted
1914         # because it's a bit messy: given the item number, we need to find
1915         # the biblioitem, which gives us the itemtype, which tells us
1916         # whether it may be renewed.
1917         my $query = "SELECT renewalsallowed FROM items ";
1918         $query .= (C4::Context->preference('item-level_itypes'))
1919                     ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1920                     : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1921                        LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1922         $query .= "WHERE items.itemnumber = ?";
1923         my $sth2 = $dbh->prepare($query);
1924         $sth2->execute($itemnumber);
1925         if ( my $data2 = $sth2->fetchrow_hashref ) {
1926             $renews = $data2->{'renewalsallowed'};
1927         }
1928         if ( ( $renews && $renews > $data1->{'renewals'} ) || $override_limit ) {
1929             $renewokay = 1;
1930         }
1931         else {
1932                         $error="too_many";
1933                 }
1934         $sth2->finish;
1935         my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1936         if ($resfound) {
1937             $renewokay = 0;
1938                         $error="on_reserve"
1939         }
1940
1941     }
1942     $sth1->finish;
1943     return ($renewokay,$error);
1944 }
1945
1946 =head2 AddRenewal
1947
1948 &AddRenewal($borrowernumber, $itemnumber, $branch, [$datedue], [$lastreneweddate]);
1949
1950 Renews a loan.
1951
1952 C<$borrowernumber> is the borrower number of the patron who currently
1953 has the item.
1954
1955 C<$itemnumber> is the number of the item to renew.
1956
1957 C<$branch> is the library branch.  Defaults to the homebranch of the ITEM.
1958
1959 C<$datedue> can be a C4::Dates object used to set the due date.
1960
1961 C<$lastreneweddate> is an optional ISO-formatted date used to set issues.lastreneweddate.  If
1962 this parameter is not supplied, lastreneweddate is set to the current date.
1963
1964 If C<$datedue> is the empty string, C<&AddRenewal> will calculate the due date automatically
1965 from the book's item type.
1966
1967 =cut
1968
1969 sub AddRenewal {
1970         my $borrowernumber = shift or return undef;
1971         my     $itemnumber = shift or return undef;
1972     my $item   = GetItem($itemnumber) or return undef;
1973     my $biblio = GetBiblioFromItemNumber($itemnumber) or return undef;
1974     my $branch  = (@_) ? shift : $item->{homebranch};   # opac-renew doesn't send branch
1975     my $datedue = shift;
1976     my $lastreneweddate = shift;
1977
1978     # If the due date wasn't specified, calculate it by adding the
1979     # book's loan length to today's date.
1980     unless ($datedue && $datedue->output('iso')) {
1981
1982         my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 ) or return undef;
1983         my $loanlength = GetLoanLength(
1984             $borrower->{'categorycode'},
1985              (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1986                         $item->{homebranch}                     # item's homebranch determines loanlength OR do we want the branch specified by the AddRenewal argument?
1987         );
1988                 #FIXME -- use circControl?
1989                 $datedue =  CalcDateDue(C4::Dates->new(),$loanlength,$branch);  # this branch is the transactional branch.
1990                                                                 # The question of whether to use item's homebranch calendar is open.
1991     }
1992
1993     # $lastreneweddate defaults to today.
1994     unless (defined $lastreneweddate) {
1995         $lastreneweddate = strftime( "%Y-%m-%d", localtime );
1996     }
1997
1998     my $dbh = C4::Context->dbh;
1999     # Find the issues record for this book
2000     my $sth =
2001       $dbh->prepare("SELECT * FROM issues
2002                         WHERE borrowernumber=? 
2003                         AND itemnumber=?"
2004       );
2005     $sth->execute( $borrowernumber, $itemnumber );
2006     my $issuedata = $sth->fetchrow_hashref;
2007     $sth->finish;
2008
2009     # Update the issues record to have the new due date, and a new count
2010     # of how many times it has been renewed.
2011     my $renews = $issuedata->{'renewals'} + 1;
2012     $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?, lastreneweddate = ?
2013                             WHERE borrowernumber=? 
2014                             AND itemnumber=?"
2015     );
2016     $sth->execute( $datedue->output('iso'), $renews, $lastreneweddate, $borrowernumber, $itemnumber );
2017     $sth->finish;
2018
2019     # Update the renewal count on the item, and tell zebra to reindex
2020     $renews = $biblio->{'renewals'} + 1;
2021     ModItem({ renewals => $renews }, $biblio->{'biblionumber'}, $itemnumber);
2022
2023     # Charge a new rental fee, if applicable?
2024     my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2025     if ( $charge > 0 ) {
2026         my $accountno = getnextacctno( $borrowernumber );
2027         my $item = GetBiblioFromItemNumber($itemnumber);
2028         $sth = $dbh->prepare(
2029                 "INSERT INTO accountlines
2030                     (date,
2031                                         borrowernumber, accountno, amount,
2032                     description,
2033                                         accounttype, amountoutstanding, itemnumber
2034                                         )
2035                     VALUES (now(),?,?,?,?,?,?,?)"
2036         );
2037         $sth->execute( $borrowernumber, $accountno, $charge,
2038             "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
2039             'Rent', $charge, $itemnumber );
2040         $sth->finish;
2041     }
2042     # Log the renewal
2043     UpdateStats( $branch, 'renew', $charge, '', $itemnumber, $item->{itype}, $borrowernumber);
2044         return $datedue;
2045 }
2046
2047 sub GetRenewCount {
2048     # check renewal status
2049     my ($bornum,$itemno)=@_;
2050     my $dbh = C4::Context->dbh;
2051     my $renewcount = 0;
2052         my $renewsallowed = 0;
2053         my $renewsleft = 0;
2054     # Look in the issues table for this item, lent to this borrower,
2055     # and not yet returned.
2056
2057     # FIXME - I think this function could be redone to use only one SQL call.
2058     my $sth = $dbh->prepare("select * from issues
2059                                 where (borrowernumber = ?)
2060                                 and (itemnumber = ?)");
2061     $sth->execute($bornum,$itemno);
2062     my $data = $sth->fetchrow_hashref;
2063     $renewcount = $data->{'renewals'} if $data->{'renewals'};
2064     $sth->finish;
2065     my $query = "SELECT renewalsallowed FROM items ";
2066     $query .= (C4::Context->preference('item-level_itypes'))
2067                 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2068                 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
2069                    LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2070     $query .= "WHERE items.itemnumber = ?";
2071     my $sth2 = $dbh->prepare($query);
2072     $sth2->execute($itemno);
2073     my $data2 = $sth2->fetchrow_hashref();
2074     $renewsallowed = $data2->{'renewalsallowed'};
2075     $renewsleft = $renewsallowed - $renewcount;
2076     return ($renewcount,$renewsallowed,$renewsleft);
2077 }
2078
2079 =head2 GetIssuingCharges
2080
2081 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
2082
2083 Calculate how much it would cost for a given patron to borrow a given
2084 item, including any applicable discounts.
2085
2086 C<$itemnumber> is the item number of item the patron wishes to borrow.
2087
2088 C<$borrowernumber> is the patron's borrower number.
2089
2090 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
2091 and C<$item_type> is the code for the item's item type (e.g., C<VID>
2092 if it's a video).
2093
2094 =cut
2095
2096 sub GetIssuingCharges {
2097
2098     # calculate charges due
2099     my ( $itemnumber, $borrowernumber ) = @_;
2100     my $charge = 0;
2101     my $dbh    = C4::Context->dbh;
2102     my $item_type;
2103
2104     # Get the book's item type and rental charge (via its biblioitem).
2105     my $qcharge =     "SELECT itemtypes.itemtype,rentalcharge FROM items
2106             LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
2107         $qcharge .= (C4::Context->preference('item-level_itypes'))
2108                 ? " LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2109                 : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2110         
2111     $qcharge .=      "WHERE items.itemnumber =?";
2112    
2113     my $sth1 = $dbh->prepare($qcharge);
2114     $sth1->execute($itemnumber);
2115     if ( my $data1 = $sth1->fetchrow_hashref ) {
2116         $item_type = $data1->{'itemtype'};
2117         $charge    = $data1->{'rentalcharge'};
2118         my $q2 = "SELECT rentaldiscount FROM borrowers
2119             LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
2120             WHERE borrowers.borrowernumber = ?
2121             AND issuingrules.itemtype = ?";
2122         my $sth2 = $dbh->prepare($q2);
2123         $sth2->execute( $borrowernumber, $item_type );
2124         if ( my $data2 = $sth2->fetchrow_hashref ) {
2125             my $discount = $data2->{'rentaldiscount'};
2126             if ( $discount eq 'NULL' ) {
2127                 $discount = 0;
2128             }
2129             $charge = ( $charge * ( 100 - $discount ) ) / 100;
2130         }
2131         $sth2->finish;
2132     }
2133
2134     $sth1->finish;
2135     return ( $charge, $item_type );
2136 }
2137
2138 =head2 AddIssuingCharge
2139
2140 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
2141
2142 =cut
2143
2144 sub AddIssuingCharge {
2145     my ( $itemnumber, $borrowernumber, $charge ) = @_;
2146     my $dbh = C4::Context->dbh;
2147     my $nextaccntno = getnextacctno( $borrowernumber );
2148     my $query ="
2149         INSERT INTO accountlines
2150             (borrowernumber, itemnumber, accountno,
2151             date, amount, description, accounttype,
2152             amountoutstanding)
2153         VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
2154     ";
2155     my $sth = $dbh->prepare($query);
2156     $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
2157     $sth->finish;
2158 }
2159
2160 =head2 GetTransfers
2161
2162 GetTransfers($itemnumber);
2163
2164 =cut
2165
2166 sub GetTransfers {
2167     my ($itemnumber) = @_;
2168
2169     my $dbh = C4::Context->dbh;
2170
2171     my $query = '
2172         SELECT datesent,
2173                frombranch,
2174                tobranch
2175         FROM branchtransfers
2176         WHERE itemnumber = ?
2177           AND datearrived IS NULL
2178         ';
2179     my $sth = $dbh->prepare($query);
2180     $sth->execute($itemnumber);
2181     my @row = $sth->fetchrow_array();
2182     $sth->finish;
2183     return @row;
2184 }
2185
2186
2187 =head2 GetTransfersFromTo
2188
2189 @results = GetTransfersFromTo($frombranch,$tobranch);
2190
2191 Returns the list of pending transfers between $from and $to branch
2192
2193 =cut
2194
2195 sub GetTransfersFromTo {
2196     my ( $frombranch, $tobranch ) = @_;
2197     return unless ( $frombranch && $tobranch );
2198     my $dbh   = C4::Context->dbh;
2199     my $query = "
2200         SELECT itemnumber,datesent,frombranch
2201         FROM   branchtransfers
2202         WHERE  frombranch=?
2203           AND  tobranch=?
2204           AND datearrived IS NULL
2205     ";
2206     my $sth = $dbh->prepare($query);
2207     $sth->execute( $frombranch, $tobranch );
2208     my @gettransfers;
2209
2210     while ( my $data = $sth->fetchrow_hashref ) {
2211         push @gettransfers, $data;
2212     }
2213     $sth->finish;
2214     return (@gettransfers);
2215 }
2216
2217 =head2 DeleteTransfer
2218
2219 &DeleteTransfer($itemnumber);
2220
2221 =cut
2222
2223 sub DeleteTransfer {
2224     my ($itemnumber) = @_;
2225     my $dbh          = C4::Context->dbh;
2226     my $sth          = $dbh->prepare(
2227         "DELETE FROM branchtransfers
2228          WHERE itemnumber=?
2229          AND datearrived IS NULL "
2230     );
2231     $sth->execute($itemnumber);
2232     $sth->finish;
2233 }
2234
2235 =head2 AnonymiseIssueHistory
2236
2237 $rows = AnonymiseIssueHistory($borrowernumber,$date)
2238
2239 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
2240 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
2241
2242 return the number of affected rows.
2243
2244 =cut
2245
2246 sub AnonymiseIssueHistory {
2247     my $date           = shift;
2248     my $borrowernumber = shift;
2249     my $dbh            = C4::Context->dbh;
2250     my $query          = "
2251         UPDATE old_issues
2252         SET    borrowernumber = NULL
2253         WHERE  returndate < '".$date."'
2254           AND borrowernumber IS NOT NULL
2255     ";
2256     $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
2257     my $rows_affected = $dbh->do($query);
2258     return $rows_affected;
2259 }
2260
2261 =head2 updateWrongTransfer
2262
2263 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
2264
2265 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 
2266
2267 =cut
2268
2269 sub updateWrongTransfer {
2270         my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
2271         my $dbh = C4::Context->dbh;     
2272 # first step validate the actual line of transfert .
2273         my $sth =
2274                 $dbh->prepare(
2275                         "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
2276                 );
2277                 $sth->execute($FromLibrary,$itemNumber);
2278                 $sth->finish;
2279
2280 # second step create a new line of branchtransfer to the right location .
2281         ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
2282
2283 #third step changing holdingbranch of item
2284         UpdateHoldingbranch($FromLibrary,$itemNumber);
2285 }
2286
2287 =head2 UpdateHoldingbranch
2288
2289 $items = UpdateHoldingbranch($branch,$itmenumber);
2290 Simple methode for updating hodlingbranch in items BDD line
2291
2292 =cut
2293
2294 sub UpdateHoldingbranch {
2295         my ( $branch,$itemnumber ) = @_;
2296     ModItem({ holdingbranch => $branch }, undef, $itemnumber);
2297 }
2298
2299 =head2 CalcDateDue
2300
2301 $newdatedue = CalcDateDue($startdate,$loanlength,$branchcode);
2302 this function calculates the due date given the loan length ,
2303 checking against the holidays calendar as per the 'useDaysMode' syspref.
2304 C<$startdate>   = C4::Dates object representing start date of loan period (assumed to be today)
2305 C<$branch>  = location whose calendar to use
2306 C<$loanlength>  = loan length prior to adjustment
2307 =cut
2308
2309 sub CalcDateDue { 
2310         my ($startdate,$loanlength,$branch) = @_;
2311         if(C4::Context->preference('useDaysMode') eq 'Days') {  # ignoring calendar
2312                 my $datedue = time + ($loanlength) * 86400;
2313         #FIXME - assumes now even though we take a startdate 
2314                 my @datearr  = localtime($datedue);
2315                 return C4::Dates->new( sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
2316         } else {
2317                 my $calendar = C4::Calendar->new(  branchcode => $branch );
2318                 my $datedue = $calendar->addDate($startdate, $loanlength);
2319                 return $datedue;
2320         }
2321 }
2322
2323 =head2 CheckValidDatedue
2324        This function does not account for holiday exceptions nor does it handle the 'useDaysMode' syspref .
2325        To be replaced by CalcDateDue() once C4::Calendar use is tested.
2326
2327 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
2328 this function validates the loan length against the holidays calendar, and adjusts the due date as per the 'useDaysMode' syspref.
2329 C<$date_due>   = returndate calculate with no day check
2330 C<$itemnumber>  = itemnumber
2331 C<$branchcode>  = location of issue (affected by 'CircControl' syspref)
2332 C<$loanlength>  = loan length prior to adjustment
2333 =cut
2334
2335 sub CheckValidDatedue {
2336 my ($date_due,$itemnumber,$branchcode)=@_;
2337 my @datedue=split('-',$date_due->output('iso'));
2338 my $years=$datedue[0];
2339 my $month=$datedue[1];
2340 my $day=$datedue[2];
2341 # die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
2342 my $dow;
2343 for (my $i=0;$i<2;$i++){
2344     $dow=Day_of_Week($years,$month,$day);
2345     ($dow=0) if ($dow>6);
2346     my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
2347     my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2348     my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2349         if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
2350         $i=0;
2351         (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
2352         }
2353     }
2354     my $newdatedue=C4::Dates->new(sprintf("%04d-%02d-%02d",$years,$month,$day),'iso');
2355 return $newdatedue;
2356 }
2357
2358
2359 =head2 CheckRepeatableHolidays
2360
2361 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
2362 this function checks if the date due is a repeatable holiday
2363 C<$date_due>   = returndate calculate with no day check
2364 C<$itemnumber>  = itemnumber
2365 C<$branchcode>  = localisation of issue 
2366
2367 =cut
2368
2369 sub CheckRepeatableHolidays{
2370 my($itemnumber,$week_day,$branchcode)=@_;
2371 my $dbh = C4::Context->dbh;
2372 my $query = qq|SELECT count(*)  
2373         FROM repeatable_holidays 
2374         WHERE branchcode=?
2375         AND weekday=?|;
2376 my $sth = $dbh->prepare($query);
2377 $sth->execute($branchcode,$week_day);
2378 my $result=$sth->fetchrow;
2379 $sth->finish;
2380 return $result;
2381 }
2382
2383
2384 =head2 CheckSpecialHolidays
2385
2386 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2387 this function check if the date is a special holiday
2388 C<$years>   = the years of datedue
2389 C<$month>   = the month of datedue
2390 C<$day>     = the day of datedue
2391 C<$itemnumber>  = itemnumber
2392 C<$branchcode>  = localisation of issue 
2393
2394 =cut
2395
2396 sub CheckSpecialHolidays{
2397 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
2398 my $dbh = C4::Context->dbh;
2399 my $query=qq|SELECT count(*) 
2400              FROM `special_holidays`
2401              WHERE year=?
2402              AND month=?
2403              AND day=?
2404              AND branchcode=?
2405             |;
2406 my $sth = $dbh->prepare($query);
2407 $sth->execute($years,$month,$day,$branchcode);
2408 my $countspecial=$sth->fetchrow ;
2409 $sth->finish;
2410 return $countspecial;
2411 }
2412
2413 =head2 CheckRepeatableSpecialHolidays
2414
2415 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2416 this function check if the date is a repeatble special holidays
2417 C<$month>   = the month of datedue
2418 C<$day>     = the day of datedue
2419 C<$itemnumber>  = itemnumber
2420 C<$branchcode>  = localisation of issue 
2421
2422 =cut
2423
2424 sub CheckRepeatableSpecialHolidays{
2425 my ($month,$day,$itemnumber,$branchcode) = @_;
2426 my $dbh = C4::Context->dbh;
2427 my $query=qq|SELECT count(*) 
2428              FROM `repeatable_holidays`
2429              WHERE month=?
2430              AND day=?
2431              AND branchcode=?
2432             |;
2433 my $sth = $dbh->prepare($query);
2434 $sth->execute($month,$day,$branchcode);
2435 my $countspecial=$sth->fetchrow ;
2436 $sth->finish;
2437 return $countspecial;
2438 }
2439
2440
2441
2442 sub CheckValidBarcode{
2443 my ($barcode) = @_;
2444 my $dbh = C4::Context->dbh;
2445 my $query=qq|SELECT count(*) 
2446              FROM items 
2447              WHERE barcode=?
2448             |;
2449 my $sth = $dbh->prepare($query);
2450 $sth->execute($barcode);
2451 my $exist=$sth->fetchrow ;
2452 $sth->finish;
2453 return $exist;
2454 }
2455
2456 =head2 IsBranchTransferAllowed
2457
2458 $allowed = IsBranchTransferAllowed( $toBranch, $fromBranch, $itemtype );
2459
2460 =cut
2461
2462 sub IsBranchTransferAllowed {
2463         my ( $toBranch, $fromBranch, $itemtype ) = @_;
2464     
2465         if ( $toBranch eq $fromBranch ) { return 1; } ## Short circuit for speed.
2466         
2467         my $dbh = C4::Context->dbh;
2468             
2469         my $sth = $dbh->prepare('SELECT * FROM branch_transfer_limits WHERE toBranch = ? AND fromBranch = ? AND itemtype = ?');
2470         $sth->execute( $toBranch, $fromBranch, $itemtype );
2471         my $limit = $sth->fetchrow_hashref();
2472                         
2473         ## If a row is found, then that combination is not allowed, if no matching row is found, then the combination *is allowed*
2474         if ( $limit->{'limitId'} ) {
2475                 return 0;
2476         } else {
2477                 return 1;
2478         }
2479 }                                                        
2480
2481 =head2 CreateBranchTransferLimit
2482
2483 CreateBranchTransferLimit( $toBranch, $fromBranch, $itemtype );
2484
2485 =cut
2486
2487 sub CreateBranchTransferLimit {
2488    my ( $toBranch, $fromBranch, $itemtype ) = @_;
2489    
2490    my $dbh = C4::Context->dbh;
2491    
2492    my $sth = $dbh->prepare("INSERT INTO branch_transfer_limits ( itemtype, toBranch, fromBranch ) VALUES ( ?, ?, ? )");
2493    $sth->execute( $itemtype, $toBranch, $fromBranch );
2494 }
2495
2496 =head2 DeleteBranchTransferLimits
2497
2498 DeleteBranchTransferLimits();
2499
2500 =cut
2501
2502 sub DeleteBranchTransferLimits {
2503    my $dbh = C4::Context->dbh;
2504    my $sth = $dbh->prepare("TRUNCATE TABLE branch_transfer_limits");
2505    $sth->execute();
2506 }
2507
2508
2509   1;
2510
2511 __END__
2512
2513 =head1 AUTHOR
2514
2515 Koha Developement team <info@koha.org>
2516
2517 =cut
2518