new file: 0001-applied-various-perltidy-styles-to-Circ.pm.patch
[koha-perltidy/.git] / 0001-applied-various-perltidy-styles-to-Circ.pm.patch
1 From eb5d6e635320f6a185f5d767b1451eb30d044c10 Mon Sep 17 00:00:00 2001
2 From: Mason James <mtj@kohaaloha.com>
3 Date: Sat, 1 Oct 2011 20:45:41 +1300
4 Subject: [PATCH] applied various perltidy styles to Circ.pm
5 Content-Type: text/plain; charset="utf-8"
6
7  perltidy -gnu ./Circulation.pm.gnu-style
8  perltidy -pbp ./Circulation.pm.pbp-style
9  perltidy -nopro ./Circulation.pm.perlstyle-style
10  perltidy --profile='./koha-master/xt/perltidyrc' ./Circulation.pm.koha-style
11 ---
12  Circulation.pm.gnu-style       | 1730 +++++++++++++++++-----------------
13  Circulation.pm.koha-style      | 1673 +++++++++++++++++----------------
14  Circulation.pm.pbp-style       | 2037 +++++++++++++++++++++++-----------------
15  Circulation.pm.perlstyle-style | 2045 +++++++++++++++++++++++-----------------
16  4 files changed, 4063 insertions(+), 3422 deletions(-)
17
18 diff --git a/Circulation.pm.gnu-style b/Circulation.pm.gnu-style
19 index 520c116..aad5632 100644
20 --- a/Circulation.pm.gnu-style
21 +++ b/Circulation.pm.gnu-style
22 @@ -18,8 +18,8 @@ package C4::Circulation;
23  # with Koha; if not, write to the Free Software Foundation, Inc.,
24  # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25  
26 -
27  use strict;
28 +
29  #use warnings; FIXME - Bug 2505
30  use C4::Context;
31  use C4::Stats;
32 @@ -42,63 +42,63 @@ use Date::Calc qw(
33    Add_Delta_DHMS
34    Date_to_Days
35    Day_of_Week
36 -  Add_Delta_Days       
37 -);
38 +  Add_Delta_Days
39 +  );
40  use POSIX qw(strftime);
41 -use C4::Branch; # GetBranches
42 -use C4::Log; # logaction
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 -               &GetItemIssues
70 -               &GetBorrowerIssues
71 -               &GetIssuingCharges
72 -               &GetIssuingRule
73 -        &GetBranchBorrowerCircRule
74 -        &GetBranchItemRule
75 -               &GetBiblioIssues
76 -               &GetOpenIssue
77 -               &AnonymiseIssueHistory
78 -       );
79 -
80 -       # subs to deal with returns
81 -       push @EXPORT, qw(
82 -               &AddReturn
83 -        &MarkIssueReturned
84 -       );
85 -
86 -       # subs to deal with transfers
87 -       push @EXPORT, qw(
88 -               &transferbook
89 -               &GetTransfers
90 -               &GetTransfersFromTo
91 -               &updateWrongTransfer
92 -               &DeleteTransfer
93 -                &IsBranchTransferAllowed
94 -                &CreateBranchTransferLimit
95 -                &DeleteBranchTransferLimits
96 -       );
97 +    require Exporter;
98 +    $VERSION = 3.02;           # for version checking
99 +    @ISA     = qw(Exporter);
100 +
101 +    # FIXME subs that should probably be elsewhere
102 +    push @EXPORT, qw(
103 +      &FixOverduesOnReturn
104 +      &barcodedecode
105 +      );
106 +
107 +    # subs to deal with issuing a book
108 +    push @EXPORT, qw(
109 +      &CanBookBeIssued
110 +      &CanBookBeRenewed
111 +      &AddIssue
112 +      &AddRenewal
113 +      &GetRenewCount
114 +      &GetItemIssue
115 +      &GetItemIssues
116 +      &GetBorrowerIssues
117 +      &GetIssuingCharges
118 +      &GetIssuingRule
119 +      &GetBranchBorrowerCircRule
120 +      &GetBranchItemRule
121 +      &GetBiblioIssues
122 +      &GetOpenIssue
123 +      &AnonymiseIssueHistory
124 +      );
125 +
126 +    # subs to deal with returns
127 +    push @EXPORT, qw(
128 +      &AddReturn
129 +      &MarkIssueReturned
130 +      );
131 +
132 +    # subs to deal with transfers
133 +    push @EXPORT, qw(
134 +      &transferbook
135 +      &GetTransfers
136 +      &GetTransfersFromTo
137 +      &updateWrongTransfer
138 +      &DeleteTransfer
139 +      &IsBranchTransferAllowed
140 +      &CreateBranchTransferLimit
141 +      &DeleteBranchTransferLimits
142 +      );
143  }
144  
145  =head1 NAME
146 @@ -141,33 +141,34 @@ sub barcodedecode {
147      my ($barcode, $filter) = @_;
148      my $branch = C4::Branch::mybranch();
149      $filter = C4::Context->preference('itemBarcodeInputFilter') unless $filter;
150 -    $filter or return $barcode;     # ensure filter is defined, else return untouched barcode
151 -       if ($filter eq 'whitespace') {
152 -               $barcode =~ s/\s//g;
153 -       } elsif ($filter eq 'cuecat') {
154 -               chomp($barcode);
155 -           my @fields = split( /\./, $barcode );
156 -           my @results = map( decode($_), @fields[ 1 .. $#fields ] );
157 -           ($#results == 2) and return $results[2];
158 -       } elsif ($filter eq 'T-prefix') {
159 -               if ($barcode =~ /^[Tt](\d)/) {
160 -                       (defined($1) and $1 eq '0') and return $barcode;
161 -            $barcode = substr($barcode, 2) + 0;     # FIXME: probably should be substr($barcode, 1)
162 -               }
163 +    $filter or return $barcode;    # ensure filter is defined, else return untouched barcode
164 +    if ($filter eq 'whitespace') {
165 +        $barcode =~ s/\s//g;
166 +    } elsif ($filter eq 'cuecat') {
167 +        chomp($barcode);
168 +        my @fields = split(/\./, $barcode);
169 +        my @results = map(decode($_), @fields[1 .. $#fields]);
170 +        ($#results == 2) and return $results[2];
171 +    } elsif ($filter eq 'T-prefix') {
172 +        if ($barcode =~ /^[Tt](\d)/) {
173 +            (defined($1) and $1 eq '0') and return $barcode;
174 +            $barcode = substr($barcode, 2) + 0;    # FIXME: probably should be substr($barcode, 1)
175 +        }
176          return sprintf("T%07d", $barcode);
177 +
178          # FIXME: $barcode could be "T1", causing warning: substr outside of string
179          # Why drop the nonzero digit after the T?
180          # Why pass non-digits (or empty string) to "T%07d"?
181 -       } elsif ($filter eq 'libsuite8') {
182 -               unless($barcode =~ m/^($branch)-/i){    #if barcode starts with branch code its in Koha style. Skip it.
183 -                       if($barcode =~ m/^(\d)/i){      #Some barcodes even start with 0's & numbers and are assumed to have b as the item type in the libsuite8 software
184 -                                $barcode =~ s/^[0]*(\d+)$/$branch-b-$1/i;
185 -                        }else{
186 -                               $barcode =~ s/^(\D+)[0]*(\d+)$/$branch-$1-$2/i;
187 -                       }
188 -               }
189 -       }
190 -    return $barcode;    # return barcode, modified or not
191 +    } elsif ($filter eq 'libsuite8') {
192 +        unless ($barcode =~ m/^($branch)-/i) {     #if barcode starts with branch code its in Koha style. Skip it.
193 +            if ($barcode =~ m/^(\d)/i) {           #Some barcodes even start with 0's & numbers and are assumed to have b as the item type in the libsuite8 software
194 +                $barcode =~ s/^[0]*(\d+)$/$branch-b-$1/i;
195 +            } else {
196 +                $barcode =~ s/^(\D+)[0]*(\d+)$/$branch-$1-$2/i;
197 +            }
198 +        }
199 +    }
200 +    return $barcode;                               # return barcode, modified or not
201  }
202  
203  =head2 decode
204 @@ -184,12 +185,12 @@ or Javascript based decoding on the client side.
205  
206  sub decode {
207      my ($encoded) = @_;
208 -    my $seq =
209 -      'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
210 -    my @s = map { index( $seq, $_ ); } split( //, $encoded );
211 -    my $l = ( $#s + 1 ) % 4;
212 +    my $seq = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
213 +    my @s = map { index($seq, $_); } split(//, $encoded);
214 +    my $l = ($#s + 1) % 4;
215      if ($l) {
216 -        if ( $l == 1 ) {
217 +        if ($l == 1) {
218 +
219              # warn "Error: Cuecat decode parsing failed!";
220              return;
221          }
222 @@ -197,15 +198,12 @@ sub decode {
223          $#s += $l;
224      }
225      my $r = '';
226 -    while ( $#s >= 0 ) {
227 -        my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
228 -        $r .=
229 -            chr( ( $n >> 16 ) ^ 67 )
230 -         .chr( ( $n >> 8 & 255 ) ^ 67 )
231 -         .chr( ( $n & 255 ) ^ 67 );
232 -        @s = @s[ 4 .. $#s ];
233 -    }
234 -    $r = substr( $r, 0, length($r) - $l );
235 +    while ($#s >= 0) {
236 +        my $n = (($s[0] << 6 | $s[1]) << 6 | $s[2]) << 6 | $s[3];
237 +        $r .= chr(($n >> 16) ^ 67) . chr(($n >> 8 & 255) ^ 67) . chr(($n & 255) ^ 67);
238 +        @s = @s[4 .. $#s];
239 +    }
240 +    $r = substr($r, 0, length($r) - $l);
241      return $r;
242  }
243  
244 @@ -268,16 +266,16 @@ The item was eligible to be transferred. Barring problems communicating with the
245  =cut
246  
247  sub transferbook {
248 -    my ( $tbr, $barcode, $ignoreRs ) = @_;
249 +    my ($tbr, $barcode, $ignoreRs) = @_;
250      my $messages;
251 -    my $dotransfer      = 1;
252 -    my $branches        = GetBranches();
253 -    my $itemnumber = GetItemnumberFromBarcode( $barcode );
254 +    my $dotransfer = 1;
255 +    my $branches   = GetBranches();
256 +    my $itemnumber = GetItemnumberFromBarcode($barcode);
257      my $issue      = GetItemIssue($itemnumber);
258 -    my $biblio = GetBiblioFromItemNumber($itemnumber);
259 +    my $biblio     = GetBiblioFromItemNumber($itemnumber);
260  
261      # bad barcode..
262 -    if ( not $itemnumber ) {
263 +    if (not $itemnumber) {
264          $messages->{'BadBarcode'} = $barcode;
265          $dotransfer = 0;
266      }
267 @@ -287,41 +285,40 @@ sub transferbook {
268      my $fbr = $biblio->{'holdingbranch'};
269  
270      # if using Branch Transfer Limits
271 -    if ( C4::Context->preference("UseBranchTransferLimits") == 1 ) {
272 -        if ( C4::Context->preference("item-level_itypes") && C4::Context->preference("BranchTransferLimitsType") eq 'itemtype' ) {
273 -            if ( ! IsBranchTransferAllowed( $tbr, $fbr, $biblio->{'itype'} ) ) {
274 +    if (C4::Context->preference("UseBranchTransferLimits") == 1) {
275 +        if (C4::Context->preference("item-level_itypes") && C4::Context->preference("BranchTransferLimitsType") eq 'itemtype') {
276 +            if (!IsBranchTransferAllowed($tbr, $fbr, $biblio->{'itype'})) {
277                  $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{'itype'};
278                  $dotransfer = 0;
279              }
280 -        } elsif ( ! IsBranchTransferAllowed( $tbr, $fbr, $biblio->{ C4::Context->preference("BranchTransferLimitsType") } ) ) {
281 -            $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{ C4::Context->preference("BranchTransferLimitsType") };
282 +        } elsif (!IsBranchTransferAllowed($tbr, $fbr, $biblio->{C4::Context->preference("BranchTransferLimitsType")})) {
283 +            $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{C4::Context->preference("BranchTransferLimitsType")};
284              $dotransfer = 0;
285 -       }
286 +        }
287      }
288  
289      # if is permanent...
290 -    if ( $hbr && $branches->{$hbr}->{'PE'} ) {
291 +    if ($hbr && $branches->{$hbr}->{'PE'}) {
292          $messages->{'IsPermanent'} = $hbr;
293          $dotransfer = 0;
294      }
295  
296      # can't transfer book if is already there....
297 -    if ( $fbr eq $tbr ) {
298 +    if ($fbr eq $tbr) {
299          $messages->{'DestinationEqualsHolding'} = 1;
300          $dotransfer = 0;
301      }
302  
303      # check if it is still issued to someone, return it...
304      if ($issue->{borrowernumber}) {
305 -        AddReturn( $barcode, $fbr );
306 +        AddReturn($barcode, $fbr);
307          $messages->{'WasReturned'} = $issue->{borrowernumber};
308      }
309  
310      # find reserves.....
311      # That'll save a database query.
312 -    my ( $resfound, $resrec ) =
313 -      CheckReserves( $itemnumber );
314 -    if ( $resfound and not $ignoreRs ) {
315 +    my ($resfound, $resrec) = CheckReserves($itemnumber);
316 +    if ($resfound and not $ignoreRs) {
317          $resrec->{'ResFound'} = $resfound;
318  
319          #         $messages->{'ResFound'} = $resrec;
320 @@ -330,30 +327,30 @@ sub transferbook {
321  
322      #actually do the transfer....
323      if ($dotransfer) {
324 -        ModItemTransfer( $itemnumber, $fbr, $tbr );
325 +        ModItemTransfer($itemnumber, $fbr, $tbr);
326  
327          # don't need to update MARC anymore, we do it in batch now
328          $messages->{'WasTransfered'} = 1;
329  
330      }
331 -    ModDateLastSeen( $itemnumber );
332 -    return ( $dotransfer, $messages, $biblio );
333 +    ModDateLastSeen($itemnumber);
334 +    return ($dotransfer, $messages, $biblio);
335  }
336  
337 -
338  sub TooMany {
339 -    my $borrower        = shift;
340 +    my $borrower     = shift;
341      my $biblionumber = shift;
342 -       my $item                = shift;
343 -    my $cat_borrower    = $borrower->{'categorycode'};
344 -    my $dbh             = C4::Context->dbh;
345 -       my $branch;
346 -       # Get which branchcode we need
347 -       $branch = _GetCircControlBranch($item,$borrower);
348 -       my $type = (C4::Context->preference('item-level_itypes')) 
349 -                       ? $item->{'itype'}         # item-level
350 -                       : $item->{'itemtype'};     # biblio-level
351
352 +    my $item         = shift;
353 +    my $cat_borrower = $borrower->{'categorycode'};
354 +    my $dbh          = C4::Context->dbh;
355 +    my $branch;
356 +
357 +    # Get which branchcode we need
358 +    $branch = _GetCircControlBranch($item, $borrower);
359 +    my $type = (C4::Context->preference('item-level_itypes'))
360 +      ? $item->{'itype'}        # item-level
361 +      : $item->{'itemtype'};    # biblio-level
362 +
363      # given branch, patron category, and item type, determine
364      # applicable issuing rule
365      my $issuing_rule = GetIssuingRule($cat_borrower, $type, $branch);
366 @@ -368,6 +365,7 @@ sub TooMany {
367  
368          my $rule_itemtype = $issuing_rule->{itemtype};
369          if ($rule_itemtype eq "*") {
370 +
371              # matching rule has the default item type, so count only
372              # those existing loans that don't fall under a more
373              # specific rule
374 @@ -378,7 +376,7 @@ sub TooMany {
375                                      AND   (categorycode = ? OR categorycode = ?)
376                                      AND   itemtype <> '*'
377                                    ) ";
378 -            } else { 
379 +            } else {
380                  $count_query .= " JOIN  biblioitems USING (biblionumber) 
381                                    WHERE biblioitems.itemtype NOT IN (
382                                      SELECT itemtype FROM issuingrules
383 @@ -391,11 +389,12 @@ sub TooMany {
384              push @bind_params, $issuing_rule->{categorycode};
385              push @bind_params, $cat_borrower;
386          } else {
387 +
388              # rule has specific item type, so count loans of that
389              # specific item type
390              if (C4::Context->preference('item-level_itypes')) {
391                  $count_query .= " WHERE items.itype = ? ";
392 -            } else { 
393 +            } else {
394                  $count_query .= " JOIN  biblioitems USING (biblionumber) 
395                                    WHERE biblioitems.itemtype= ? ";
396              }
397 @@ -410,7 +409,7 @@ sub TooMany {
398                  $count_query .= " AND issues.branchcode = ? ";
399                  push @bind_params, $branch;
400              } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
401 -                ; # if branch is the patron's home branch, then count all loans by patron
402 +                ;    # if branch is the patron's home branch, then count all loans by patron
403              } else {
404                  $count_query .= " AND items.homebranch = ? ";
405                  push @bind_params, $branch;
406 @@ -430,7 +429,7 @@ sub TooMany {
407      # Now count total loans against the limit for the branch
408      my $branch_borrower_circ_rule = GetBranchBorrowerCircRule($branch, $cat_borrower);
409      if (defined($branch_borrower_circ_rule->{maxissueqty})) {
410 -        my @bind_params = ();
411 +        my @bind_params        = ();
412          my $branch_count_query = "SELECT COUNT(*) FROM issues 
413                                    JOIN items USING (itemnumber)
414                                    WHERE borrowernumber = ? ";
415 @@ -440,7 +439,7 @@ sub TooMany {
416              $branch_count_query .= " AND issues.branchcode = ? ";
417              push @bind_params, $branch;
418          } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
419 -            ; # if branch is the patron's home branch, then count all loans by patron
420 +            ;    # if branch is the patron's home branch, then count all loans by patron
421          } else {
422              $branch_count_query .= " AND items.homebranch = ? ";
423              push @bind_params, $branch;
424 @@ -505,17 +504,16 @@ The borrower number of the last three patrons who borrowed this item.
425  
426  #'
427  sub itemissues {
428 -    my ( $bibitem, $biblio ) = @_;
429 +    my ($bibitem, $biblio) = @_;
430      my $dbh = C4::Context->dbh;
431 -    my $sth =
432 -      $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
433 +    my $sth = $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
434        || die $dbh->errstr;
435      my $i = 0;
436      my @results;
437  
438      $sth->execute($bibitem) || die $sth->errstr;
439  
440 -    while ( my $data = $sth->fetchrow_hashref ) {
441 +    while (my $data = $sth->fetchrow_hashref) {
442  
443          # Find out who currently has this item.
444          # FIXME - Wouldn't it be better to do this as a left join of
445 @@ -529,35 +527,32 @@ sub itemissues {
446                  LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
447                  WHERE itemnumber = ?
448              "
449 -        );
450 +                                );
451  
452 -        $sth2->execute( $data->{'itemnumber'} );
453 -        if ( my $data2 = $sth2->fetchrow_hashref ) {
454 +        $sth2->execute($data->{'itemnumber'});
455 +        if (my $data2 = $sth2->fetchrow_hashref) {
456              $data->{'date_due'} = $data2->{'date_due'};
457              $data->{'card'}     = $data2->{'cardnumber'};
458              $data->{'borrower'} = $data2->{'borrowernumber'};
459 -        }
460 -        else {
461 +        } else {
462              $data->{'date_due'} = ($data->{'wthdrawn'} eq '1') ? 'Cancelled' : 'Available';
463          }
464  
465 -
466          # Find the last 3 people who borrowed this item.
467          $sth2 = $dbh->prepare(
468              "SELECT * FROM old_issues
469                  LEFT JOIN borrowers ON  issues.borrowernumber = borrowers.borrowernumber
470                  WHERE itemnumber = ?
471                  ORDER BY returndate DESC,timestamp DESC"
472 -        );
473 +                             );
474  
475 -        $sth2->execute( $data->{'itemnumber'} );
476 -        for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
477 -        {    # FIXME : error if there is less than 3 pple borrowing this item
478 -            if ( my $data2 = $sth2->fetchrow_hashref ) {
479 +        $sth2->execute($data->{'itemnumber'});
480 +        for (my $i2 = 0 ; $i2 < 2 ; $i2++) {    # FIXME : error if there is less than 3 pple borrowing this item
481 +            if (my $data2 = $sth2->fetchrow_hashref) {
482                  $data->{"timestamp$i2"} = $data2->{'timestamp'};
483                  $data->{"card$i2"}      = $data2->{'cardnumber'};
484                  $data->{"borrower$i2"}  = $data2->{'borrowernumber'};
485 -            }    # if
486 +            }                                   # if
487          }    # for
488  
489          $results[$i] = $data;
490 @@ -661,30 +656,30 @@ if the borrower borrows to much things
491  =cut
492  
493  sub CanBookBeIssued {
494 -    my ( $borrower, $barcode, $duedate, $inprocess ) = @_;
495 +    my ($borrower, $barcode, $duedate, $inprocess) = @_;
496      my %needsconfirmation;    # filled with problems that needs confirmations
497      my %issuingimpossible;    # filled with problems that causes the issue to be IMPOSSIBLE
498 -    my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
499 -    my $issue = GetItemIssue($item->{itemnumber});
500 -       my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
501 -       $item->{'itemtype'}=$item->{'itype'}; 
502 -    my $dbh             = C4::Context->dbh;
503 +    my $item       = GetItem(GetItemnumberFromBarcode($barcode));
504 +    my $issue      = GetItemIssue($item->{itemnumber});
505 +    my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
506 +    $item->{'itemtype'} = $item->{'itype'};
507 +    my $dbh = C4::Context->dbh;
508  
509      # MANDATORY CHECKS - unless item exists, nothing else matters
510 -    unless ( $item->{barcode} ) {
511 +    unless ($item->{barcode}) {
512          $issuingimpossible{UNKNOWN_BARCODE} = 1;
513      }
514 -       return ( \%issuingimpossible, \%needsconfirmation ) if %issuingimpossible;
515 +    return (\%issuingimpossible, \%needsconfirmation) if %issuingimpossible;
516  
517      #
518      # DUE DATE is OK ? -- should already have checked.
519      #
520 -    unless ( $duedate ) {
521 -        my $issuedate = strftime( "%Y-%m-%d", localtime );
522 +    unless ($duedate) {
523 +        my $issuedate = strftime("%Y-%m-%d", localtime);
524  
525 -        my $branch = _GetCircControlBranch($item,$borrower);
526 -        my $itype = ( C4::Context->preference('item-level_itypes') ) ? $item->{'itype'} : $biblioitem->{'itemtype'};
527 -        $duedate = CalcDateDue( C4::Dates->new( $issuedate, 'iso' ), $itype, $branch, $borrower );
528 +        my $branch = _GetCircControlBranch($item, $borrower);
529 +        my $itype = (C4::Context->preference('item-level_itypes')) ? $item->{'itype'} : $biblioitem->{'itemtype'};
530 +        $duedate = CalcDateDue(C4::Dates->new($issuedate, 'iso'), $itype, $branch, $borrower);
531  
532          # Offline circ calls AddIssue directly, doesn't run through here
533          #  So issuingimpossible should be ok.
534 @@ -699,85 +694,88 @@ sub CanBookBeIssued {
535      #
536      # BORROWER STATUS
537      #
538 -    if ( $borrower->{'category_type'} eq 'X' && (  $item->{barcode}  )) { 
539 -       # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1  .
540 -        &UpdateStats(C4::Context->userenv->{'branch'},'localuse','','',$item->{'itemnumber'},$item->{'itemtype'},$borrower->{'borrowernumber'});
541 -        ModDateLastSeen( $item->{'itemnumber'} );
542 -        return( { STATS => 1 }, {});
543 +    if ($borrower->{'category_type'} eq 'X' && ($item->{barcode})) {
544 +
545 +        # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1  .
546 +        &UpdateStats(C4::Context->userenv->{'branch'}, 'localuse', '', '', $item->{'itemnumber'}, $item->{'itemtype'}, $borrower->{'borrowernumber'});
547 +        ModDateLastSeen($item->{'itemnumber'});
548 +        return ({STATS => 1}, {});
549      }
550 -    if ( $borrower->{flags}->{GNA} ) {
551 +    if ($borrower->{flags}->{GNA}) {
552          $issuingimpossible{GNA} = 1;
553      }
554 -    if ( $borrower->{flags}->{'LOST'} ) {
555 +    if ($borrower->{flags}->{'LOST'}) {
556          $issuingimpossible{CARD_LOST} = 1;
557      }
558 -    if ( $borrower->{flags}->{'DBARRED'} ) {
559 +    if ($borrower->{flags}->{'DBARRED'}) {
560          $issuingimpossible{DEBARRED} = 1;
561      }
562 -    if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
563 +    if ($borrower->{'dateexpiry'} eq '0000-00-00') {
564          $issuingimpossible{EXPIRED} = 1;
565      } else {
566 -        my @expirydate=  split /-/,$borrower->{'dateexpiry'};
567 -        if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
568 -            Date_to_Days(Today) > Date_to_Days( @expirydate )) {
569 -            $issuingimpossible{EXPIRED} = 1;                                   
570 +        my @expirydate = split /-/, $borrower->{'dateexpiry'};
571 +        if (   $expirydate[0] == 0
572 +            || $expirydate[1] == 0
573 +            || $expirydate[2] == 0
574 +            || Date_to_Days(Today) > Date_to_Days(@expirydate)) {
575 +            $issuingimpossible{EXPIRED} = 1;
576          }
577      }
578 +
579      #
580      # BORROWER STATUS
581      #
582  
583      # DEBTS
584 -    my ($amount) =
585 -      C4::Members::GetMemberAccountRecords( $borrower->{'borrowernumber'}, '' && $duedate->output('iso') );
586 -    my $amountlimit = C4::Context->preference("noissuescharge");
587 -    my $allowfineoverride = C4::Context->preference("AllowFineOverride");
588 +    my ($amount) = C4::Members::GetMemberAccountRecords($borrower->{'borrowernumber'}, '' && $duedate->output('iso'));
589 +    my $amountlimit          = C4::Context->preference("noissuescharge");
590 +    my $allowfineoverride    = C4::Context->preference("AllowFineOverride");
591      my $allfinesneedoverride = C4::Context->preference("AllFinesNeedOverride");
592 -    if ( C4::Context->preference("IssuingInProcess") ) {
593 -        if ( $amount > $amountlimit && !$inprocess && !$allowfineoverride) {
594 -            $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
595 -        } elsif ( $amount > $amountlimit && !$inprocess && $allowfineoverride) {
596 -            $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
597 -        } elsif ( $allfinesneedoverride && $amount > 0 && $amount <= $amountlimit && !$inprocess ) {
598 -            $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
599 +    if (C4::Context->preference("IssuingInProcess")) {
600 +        if ($amount > $amountlimit && !$inprocess && !$allowfineoverride) {
601 +            $issuingimpossible{DEBT} = sprintf("%.2f", $amount);
602 +        } elsif ($amount > $amountlimit && !$inprocess && $allowfineoverride) {
603 +            $needsconfirmation{DEBT} = sprintf("%.2f", $amount);
604 +        } elsif ($allfinesneedoverride && $amount > 0 && $amount <= $amountlimit && !$inprocess) {
605 +            $needsconfirmation{DEBT} = sprintf("%.2f", $amount);
606          }
607 -    }
608 -    else {
609 -        if ( $amount > $amountlimit && $allowfineoverride ) {
610 -            $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
611 -        } elsif ( $amount > $amountlimit && !$allowfineoverride) {
612 -            $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
613 -        } elsif ( $amount > 0 && $allfinesneedoverride ) {
614 -            $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
615 +    } else {
616 +        if ($amount > $amountlimit && $allowfineoverride) {
617 +            $needsconfirmation{DEBT} = sprintf("%.2f", $amount);
618 +        } elsif ($amount > $amountlimit && !$allowfineoverride) {
619 +            $issuingimpossible{DEBT} = sprintf("%.2f", $amount);
620 +        } elsif ($amount > 0 && $allfinesneedoverride) {
621 +            $needsconfirmation{DEBT} = sprintf("%.2f", $amount);
622          }
623      }
624  
625      my ($blocktype, $count) = C4::Members::IsMemberBlocked($borrower->{'borrowernumber'});
626      if ($blocktype == -1) {
627          ## patron has outstanding overdue loans
628 -           if ( C4::Context->preference("OverduesBlockCirc") eq 'block'){
629 -               $issuingimpossible{USERBLOCKEDOVERDUE} = $count;
630 -           }
631 -           elsif ( C4::Context->preference("OverduesBlockCirc") eq 'confirmation'){
632 -               $needsconfirmation{USERBLOCKEDOVERDUE} = $count;
633 -           }
634 -    } elsif($blocktype == 1) {
635 +        if (C4::Context->preference("OverduesBlockCirc") eq 'block') {
636 +            $issuingimpossible{USERBLOCKEDOVERDUE} = $count;
637 +        } elsif (C4::Context->preference("OverduesBlockCirc") eq 'confirmation') {
638 +            $needsconfirmation{USERBLOCKEDOVERDUE} = $count;
639 +        }
640 +    } elsif ($blocktype == 1) {
641 +
642          # patron has accrued fine days
643          $issuingimpossible{USERBLOCKEDREMAINING} = $count;
644      }
645  
646 -#
647 +    #
648      # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
649      #
650 -       my ($current_loan_count, $max_loans_allowed) = TooMany( $borrower, $item->{biblionumber}, $item );
651 +    my ($current_loan_count, $max_loans_allowed) = TooMany($borrower, $item->{biblionumber}, $item);
652 +
653      # if TooMany max_loans_allowed returns 0 the user doesn't have permission to check out this book
654      if ($max_loans_allowed eq 0) {
655          $needsconfirmation{PATRON_CANT} = 1;
656      } else {
657 -        if($max_loans_allowed){
658 -            $needsconfirmation{TOO_MANY} = 1;
659 +        if ($max_loans_allowed) {
660 +            $needsconfirmation{TOO_MANY}           = 1;
661              $needsconfirmation{current_loan_count} = $current_loan_count;
662 -            $needsconfirmation{max_loans_allowed} = $max_loans_allowed;
663 +            $needsconfirmation{max_loans_allowed}  = $max_loans_allowed;
664          }
665      }
666  
667 @@ -785,21 +783,21 @@ sub CanBookBeIssued {
668      # ITEM CHECKING
669      #
670      if (   $item->{'notforloan'}
671 -        && $item->{'notforloan'} > 0 )
672 -    {
673 -        if(!C4::Context->preference("AllowNotForLoanOverride")){
674 +        && $item->{'notforloan'} > 0) {
675 +        if (!C4::Context->preference("AllowNotForLoanOverride")) {
676              $issuingimpossible{NOT_FOR_LOAN} = 1;
677 -        }else{
678 +        } else {
679              $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
680          }
681 -    }
682 -    elsif ( !$item->{'notforloan'} ){
683 +    } elsif (!$item->{'notforloan'}) {
684 +
685          # we have to check itemtypes.notforloan also
686 -        if (C4::Context->preference('item-level_itypes')){
687 +        if (C4::Context->preference('item-level_itypes')) {
688 +
689              # this should probably be a subroutine
690              my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
691              $sth->execute($item->{'itemtype'});
692 -            my $notforloan=$sth->fetchrow_hashref();
693 +            my $notforloan = $sth->fetchrow_hashref();
694              $sth->finish();
695              if ($notforloan->{'notforloan'}) {
696                  if (!C4::Context->preference("AllowNotForLoanOverride")) {
697 @@ -808,8 +806,7 @@ sub CanBookBeIssued {
698                      $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
699                  }
700              }
701 -        }
702 -        elsif ($biblioitem->{'notforloan'} == 1){
703 +        } elsif ($biblioitem->{'notforloan'} == 1) {
704              if (!C4::Context->preference("AllowNotForLoanOverride")) {
705                  $issuingimpossible{NOT_FOR_LOAN} = 1;
706              } else {
707 @@ -817,88 +814,80 @@ sub CanBookBeIssued {
708              }
709          }
710      }
711 -    if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} > 0 )
712 -    {
713 +    if ($item->{'wthdrawn'} && $item->{'wthdrawn'} > 0) {
714          $issuingimpossible{WTHDRAWN} = 1;
715      }
716      if (   $item->{'restricted'}
717 -        && $item->{'restricted'} == 1 )
718 -    {
719 +        && $item->{'restricted'} == 1) {
720          $issuingimpossible{RESTRICTED} = 1;
721      }
722 -    if ( C4::Context->preference("IndependantBranches") ) {
723 +    if (C4::Context->preference("IndependantBranches")) {
724          my $userenv = C4::Context->userenv;
725 -        if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
726 +        if (($userenv) && ($userenv->{flags} % 2 != 1)) {
727              $issuingimpossible{ITEMNOTSAMEBRANCH} = 1
728 -              if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} );
729 -            $needsconfirmation{BORRNOTSAMEBRANCH} = GetBranchName( $borrower->{'branchcode'} )
730 -              if ( $borrower->{'branchcode'} ne $userenv->{branch} );
731 +              if ($item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch});
732 +            $needsconfirmation{BORRNOTSAMEBRANCH} = GetBranchName($borrower->{'branchcode'})
733 +              if ($borrower->{'branchcode'} ne $userenv->{branch});
734          }
735      }
736  
737      #
738      # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
739      #
740 -    if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
741 -    {
742 +    if ($issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'}) {
743  
744          # Already issued to current borrower. Ask whether the loan should
745          # be renewed.
746 -        my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed(
747 -            $borrower->{'borrowernumber'},
748 -            $item->{'itemnumber'}
749 -        );
750 -        if ( $CanBookBeRenewed == 0 ) {    # no more renewals allowed
751 +        my ($CanBookBeRenewed, $renewerror) = CanBookBeRenewed($borrower->{'borrowernumber'}, $item->{'itemnumber'});
752 +        if ($CanBookBeRenewed == 0) {    # no more renewals allowed
753              $issuingimpossible{NO_MORE_RENEWALS} = 1;
754 -        }
755 -        else {
756 +        } else {
757              $needsconfirmation{RENEW_ISSUE} = 1;
758          }
759 -    }
760 -    elsif ($issue->{borrowernumber}) {
761 +    } elsif ($issue->{borrowernumber}) {
762  
763          # issued to someone else
764 -        my $currborinfo =    C4::Members::GetMemberDetails( $issue->{borrowernumber} );
765 +        my $currborinfo = C4::Members::GetMemberDetails($issue->{borrowernumber});
766  
767 -#        warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
768 -        $needsconfirmation{ISSUED_TO_ANOTHER} = 1;
769 -        $needsconfirmation{issued_firstname} = $currborinfo->{'firstname'};
770 -        $needsconfirmation{issued_surname} = $currborinfo->{'surname'};
771 -        $needsconfirmation{issued_cardnumber} = $currborinfo->{'cardnumber'};
772 +        #        warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
773 +        $needsconfirmation{ISSUED_TO_ANOTHER}     = 1;
774 +        $needsconfirmation{issued_firstname}      = $currborinfo->{'firstname'};
775 +        $needsconfirmation{issued_surname}        = $currborinfo->{'surname'};
776 +        $needsconfirmation{issued_cardnumber}     = $currborinfo->{'cardnumber'};
777          $needsconfirmation{issued_borrowernumber} = $currborinfo->{'borrowernumber'};
778      }
779  
780      # See if the item is on reserve.
781 -    my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
782 +    my ($restype, $res) = C4::Reserves::CheckReserves($item->{'itemnumber'});
783      if ($restype) {
784 -               my $resbor = $res->{'borrowernumber'};
785 -               my ( $resborrower ) = C4::Members::GetMemberDetails( $resbor, 0 );
786 -               my $branches  = GetBranches();
787 -               my $branchname = $branches->{ $res->{'branchcode'} }->{'branchname'};
788 -        if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
789 -        {
790 +        my $resbor = $res->{'borrowernumber'};
791 +        my ($resborrower) = C4::Members::GetMemberDetails($resbor, 0);
792 +        my $branches      = GetBranches();
793 +        my $branchname    = $branches->{$res->{'branchcode'}}->{'branchname'};
794 +        if ($resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting") {
795 +
796              # The item is on reserve and waiting, but has been
797              # reserved by some other patron.
798 -            $needsconfirmation{RESERVE_WAITING} = 1;
799 -            $needsconfirmation{'resfirstname'} = $resborrower->{'firstname'};
800 -            $needsconfirmation{'ressurname'} = $resborrower->{'surname'};
801 -            $needsconfirmation{'rescardnumber'} = $resborrower->{'cardnumber'};
802 +            $needsconfirmation{RESERVE_WAITING}     = 1;
803 +            $needsconfirmation{'resfirstname'}      = $resborrower->{'firstname'};
804 +            $needsconfirmation{'ressurname'}        = $resborrower->{'surname'};
805 +            $needsconfirmation{'rescardnumber'}     = $resborrower->{'cardnumber'};
806              $needsconfirmation{'resborrowernumber'} = $resborrower->{'borrowernumber'};
807 -            $needsconfirmation{'resbranchname'} = $branchname;
808 -            $needsconfirmation{'reswaitingdate'} = format_date($res->{'waitingdate'});
809 -        }
810 -        elsif ( $restype eq "Reserved" ) {
811 +            $needsconfirmation{'resbranchname'}     = $branchname;
812 +            $needsconfirmation{'reswaitingdate'}    = format_date($res->{'waitingdate'});
813 +        } elsif ($restype eq "Reserved") {
814 +
815              # The item is on reserve for someone else.
816 -            $needsconfirmation{RESERVED} = 1;
817 -            $needsconfirmation{'resfirstname'} = $resborrower->{'firstname'};
818 -            $needsconfirmation{'ressurname'} = $resborrower->{'surname'};
819 -            $needsconfirmation{'rescardnumber'} = $resborrower->{'cardnumber'};
820 +            $needsconfirmation{RESERVED}            = 1;
821 +            $needsconfirmation{'resfirstname'}      = $resborrower->{'firstname'};
822 +            $needsconfirmation{'ressurname'}        = $resborrower->{'surname'};
823 +            $needsconfirmation{'rescardnumber'}     = $resborrower->{'cardnumber'};
824              $needsconfirmation{'resborrowernumber'} = $resborrower->{'borrowernumber'};
825 -            $needsconfirmation{'resbranchname'} = $branchname;
826 -            $needsconfirmation{'resreservedate'} = format_date($res->{'reservedate'});
827 +            $needsconfirmation{'resbranchname'}     = $branchname;
828 +            $needsconfirmation{'resreservedate'}    = format_date($res->{'reservedate'});
829          }
830      }
831 -       return ( \%issuingimpossible, \%needsconfirmation );
832 +    return (\%issuingimpossible, \%needsconfirmation);
833  }
834  
835  =head2 AddIssue
836 @@ -940,173 +929,162 @@ AddIssue does the following things :
837  =cut
838  
839  sub AddIssue {
840 -    my ( $borrower, $barcode, $datedue, $cancelreserve, $issuedate, $sipmode) = @_;
841 -    my $dbh = C4::Context->dbh;
842 -       my $barcodecheck=CheckValidBarcode($barcode);
843 +    my ($borrower, $barcode, $datedue, $cancelreserve, $issuedate, $sipmode) = @_;
844 +    my $dbh          = C4::Context->dbh;
845 +    my $barcodecheck = CheckValidBarcode($barcode);
846 +
847      # $issuedate defaults to today.
848 -    if ( ! defined $issuedate ) {
849 -        $issuedate = strftime( "%Y-%m-%d", localtime );
850 +    if (!defined $issuedate) {
851 +        $issuedate = strftime("%Y-%m-%d", localtime);
852 +
853          # TODO: for hourly circ, this will need to be a C4::Dates object
854          # and all calls to AddIssue including issuedate will need to pass a Dates object.
855      }
856 -       if ($borrower and $barcode and $barcodecheck ne '0'){
857 -               # find which item we issue
858 -               my $item = GetItem('', $barcode) or return undef;       # if we don't get an Item, abort.
859 -               my $branch = _GetCircControlBranch($item,$borrower);
860 -               
861 -               # get actual issuing if there is one
862 -               my $actualissue = GetItemIssue( $item->{itemnumber});
863 -               
864 -               # get biblioinformation for this item
865 -               my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
866 -               
867 -               #
868 -               # check if we just renew the issue.
869 -               #
870 -               if ($actualissue->{borrowernumber} eq $borrower->{'borrowernumber'}) {
871 -                       $datedue = AddRenewal(
872 -                               $borrower->{'borrowernumber'},
873 -                               $item->{'itemnumber'},
874 -                               $branch,
875 -                               $datedue,
876 -                $issuedate, # here interpreted as the renewal date
877 -                       );
878 -               }
879 -               else {
880 -        # it's NOT a renewal
881 -                       if ( $actualissue->{borrowernumber}) {
882 -                               # This book is currently on loan, but not to the person
883 -                               # who wants to borrow it now. mark it returned before issuing to the new borrower
884 -                               AddReturn(
885 -                                       $item->{'barcode'},
886 -                                       C4::Context->userenv->{'branch'}
887 -                               );
888 -                       }
889 -
890 -                       # See if the item is on reserve.
891 -                       my ( $restype, $res ) =
892 -                         C4::Reserves::CheckReserves( $item->{'itemnumber'} );
893 -                       if ($restype) {
894 -                               my $resbor = $res->{'borrowernumber'};
895 -                               if ( $resbor eq $borrower->{'borrowernumber'} ) {
896 -                                       # The item is reserved by the current patron
897 -                                       ModReserveFill($res);
898 -                               }
899 -                               elsif ( $restype eq "Waiting" ) {
900 -                                       # warn "Waiting";
901 -                                       # The item is on reserve and waiting, but has been
902 -                                       # reserved by some other patron.
903 -                               }
904 -                               elsif ( $restype eq "Reserved" ) {
905 -                                       # warn "Reserved";
906 -                                       # The item is reserved by someone else.
907 -                                       if ($cancelreserve) { # cancel reserves on this item
908 -                                               CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
909 -                                       }
910 -                               }
911 -                               if ($cancelreserve) {
912 -                                       CancelReserve($res->{'biblionumber'}, 0, $res->{'borrowernumber'});
913 -                               }
914 -                               else {
915 -                                       # set waiting reserve to first in reserve queue as book isn't waiting now
916 -                                       ModReserve(1,
917 -                                               $res->{'biblionumber'},
918 -                                               $res->{'borrowernumber'},
919 -                                               $res->{'branchcode'}
920 -                                       );
921 -                               }
922 -                       }
923 -
924 -                       # Starting process for transfer job (checking transfert and validate it if we have one)
925 +    if ($borrower and $barcode and $barcodecheck ne '0') {
926 +
927 +        # find which item we issue
928 +        my $item = GetItem('', $barcode) or return undef;    # if we don't get an Item, abort.
929 +        my $branch = _GetCircControlBranch($item, $borrower);
930 +
931 +        # get actual issuing if there is one
932 +        my $actualissue = GetItemIssue($item->{itemnumber});
933 +
934 +        # get biblioinformation for this item
935 +        my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
936 +
937 +        #
938 +        # check if we just renew the issue.
939 +        #
940 +        if ($actualissue->{borrowernumber} eq $borrower->{'borrowernumber'}) {
941 +            $datedue = AddRenewal($borrower->{'borrowernumber'},
942 +                                  $item->{'itemnumber'},
943 +                                  $branch,
944 +                                  $datedue,
945 +                                  $issuedate,                      # here interpreted as the renewal date
946 +                                 );
947 +        } else {
948 +
949 +            # it's NOT a renewal
950 +            if ($actualissue->{borrowernumber}) {
951 +
952 +                # This book is currently on loan, but not to the person
953 +                # who wants to borrow it now. mark it returned before issuing to the new borrower
954 +                AddReturn($item->{'barcode'}, C4::Context->userenv->{'branch'});
955 +            }
956 +
957 +            # See if the item is on reserve.
958 +            my ($restype, $res) = C4::Reserves::CheckReserves($item->{'itemnumber'});
959 +            if ($restype) {
960 +                my $resbor = $res->{'borrowernumber'};
961 +                if ($resbor eq $borrower->{'borrowernumber'}) {
962 +
963 +                    # The item is reserved by the current patron
964 +                    ModReserveFill($res);
965 +                } elsif ($restype eq "Waiting") {
966 +
967 +                    # warn "Waiting";
968 +                    # The item is on reserve and waiting, but has been
969 +                    # reserved by some other patron.
970 +                } elsif ($restype eq "Reserved") {
971 +
972 +                    # warn "Reserved";
973 +                    # The item is reserved by someone else.
974 +                    if ($cancelreserve) {    # cancel reserves on this item
975 +                        CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
976 +                    }
977 +                }
978 +                if ($cancelreserve) {
979 +                    CancelReserve($res->{'biblionumber'}, 0, $res->{'borrowernumber'});
980 +                } else {
981 +
982 +                    # set waiting reserve to first in reserve queue as book isn't waiting now
983 +                    ModReserve(1, $res->{'biblionumber'}, $res->{'borrowernumber'}, $res->{'branchcode'});
984 +                }
985 +            }
986 +
987 +            # Starting process for transfer job (checking transfert and validate it if we have one)
988              my ($datesent) = GetTransfers($item->{'itemnumber'});
989              if ($datesent) {
990 -        #      updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for visibility of this case (maybe for stats ....)
991 -                my $sth =
992 -                    $dbh->prepare(
993 +
994 +                #      updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for visibility of this case (maybe for stats ....)
995 +                my $sth = $dbh->prepare(
996                      "UPDATE branchtransfers 
997                          SET datearrived = now(),
998                          tobranch = ?,
999                          comments = 'Forced branchtransfer'
1000                      WHERE itemnumber= ? AND datearrived IS NULL"
1001 -                    );
1002 -                $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
1003 +                                       );
1004 +                $sth->execute(C4::Context->userenv->{'branch'}, $item->{'itemnumber'});
1005              }
1006  
1007 -        # Record in the database the fact that the book was issued.
1008 -        my $sth =
1009 -          $dbh->prepare(
1010 +            # Record in the database the fact that the book was issued.
1011 +            my $sth = $dbh->prepare(
1012                  "INSERT INTO issues 
1013                      (borrowernumber, itemnumber,issuedate, date_due, branchcode)
1014                  VALUES (?,?,?,?,?)"
1015 -          );
1016 -        unless ($datedue) {
1017 -            my $itype = ( C4::Context->preference('item-level_itypes') ) ? $biblio->{'itype'} : $biblio->{'itemtype'};
1018 -            $datedue = CalcDateDue( C4::Dates->new( $issuedate, 'iso' ), $itype, $branch, $borrower );
1019 +                                   );
1020 +            unless ($datedue) {
1021 +                my $itype = (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'};
1022 +                $datedue = CalcDateDue(C4::Dates->new($issuedate, 'iso'), $itype, $branch, $borrower);
1023  
1024 -        }
1025 -        $sth->execute(
1026 -            $borrower->{'borrowernumber'},      # borrowernumber
1027 -            $item->{'itemnumber'},              # itemnumber
1028 -            $issuedate,                         # issuedate
1029 -            $datedue->output('iso'),            # date_due
1030 -            C4::Context->userenv->{'branch'}    # branchcode
1031 -        );
1032 -        $sth->finish;
1033 -        if ( C4::Context->preference('ReturnToShelvingCart') ) { ## ReturnToShelvingCart is on, anything issued should be taken off the cart.
1034 -          CartToShelf( $item->{'itemnumber'} );
1035 -        }
1036 -        $item->{'issues'}++;
1037 -        ModItem({ issues           => $item->{'issues'},
1038 -                  holdingbranch    => C4::Context->userenv->{'branch'},
1039 -                  itemlost         => 0,
1040 -                  datelastborrowed => C4::Dates->new()->output('iso'),
1041 -                  onloan           => $datedue->output('iso'),
1042 -                }, $item->{'biblionumber'}, $item->{'itemnumber'});
1043 -        ModDateLastSeen( $item->{'itemnumber'} );
1044 -
1045 -        # If it costs to borrow this book, charge it to the patron's account.
1046 -        my ( $charge, $itemtype ) = GetIssuingCharges(
1047 -            $item->{'itemnumber'},
1048 -            $borrower->{'borrowernumber'}
1049 -        );
1050 -        if ( $charge > 0 ) {
1051 -            AddIssuingCharge(
1052 -                $item->{'itemnumber'},
1053 -                $borrower->{'borrowernumber'}, $charge
1054 -            );
1055 -            $item->{'charge'} = $charge;
1056 -        }
1057 +            }
1058 +            $sth->execute($borrower->{'borrowernumber'},      # borrowernumber
1059 +                          $item->{'itemnumber'},              # itemnumber
1060 +                          $issuedate,                         # issuedate
1061 +                          $datedue->output('iso'),            # date_due
1062 +                          C4::Context->userenv->{'branch'}    # branchcode
1063 +                         );
1064 +            $sth->finish;
1065 +            if (C4::Context->preference('ReturnToShelvingCart')) {    ## ReturnToShelvingCart is on, anything issued should be taken off the cart.
1066 +                CartToShelf($item->{'itemnumber'});
1067 +            }
1068 +            $item->{'issues'}++;
1069 +            ModItem(
1070 +                    {issues           => $item->{'issues'},
1071 +                     holdingbranch    => C4::Context->userenv->{'branch'},
1072 +                     itemlost         => 0,
1073 +                     datelastborrowed => C4::Dates->new()->output('iso'),
1074 +                     onloan           => $datedue->output('iso'),
1075 +                    },
1076 +                    $item->{'biblionumber'},
1077 +                    $item->{'itemnumber'}
1078 +                   );
1079 +            ModDateLastSeen($item->{'itemnumber'});
1080 +
1081 +            # If it costs to borrow this book, charge it to the patron's account.
1082 +            my ($charge, $itemtype) = GetIssuingCharges($item->{'itemnumber'}, $borrower->{'borrowernumber'});
1083 +            if ($charge > 0) {
1084 +                AddIssuingCharge($item->{'itemnumber'}, $borrower->{'borrowernumber'}, $charge);
1085 +                $item->{'charge'} = $charge;
1086 +            }
1087  
1088 -        # Record the fact that this book was issued.
1089 -        &UpdateStats(
1090 -            C4::Context->userenv->{'branch'},
1091 -            'issue', $charge,
1092 -            ($sipmode ? "SIP-$sipmode" : ''), $item->{'itemnumber'},
1093 -            $item->{'itype'}, $borrower->{'borrowernumber'}
1094 -        );
1095 -
1096 -        # Send a checkout slip.
1097 -        my $circulation_alert = 'C4::ItemCirculationAlertPreference';
1098 -        my %conditions = (
1099 -            branchcode   => $branch,
1100 -            categorycode => $borrower->{categorycode},
1101 -            item_type    => $item->{itype},
1102 -            notification => 'CHECKOUT',
1103 -        );
1104 -        if ($circulation_alert->is_enabled_for(\%conditions)) {
1105 -            SendCirculationAlert({
1106 -                type     => 'CHECKOUT',
1107 -                item     => $item,
1108 -                borrower => $borrower,
1109 -                branch   => $branch,
1110 -            });
1111 +            # Record the fact that this book was issued.
1112 +            &UpdateStats(C4::Context->userenv->{'branch'},
1113 +                         'issue', $charge, ($sipmode ? "SIP-$sipmode" : ''),
1114 +                         $item->{'itemnumber'}, $item->{'itype'}, $borrower->{'borrowernumber'});
1115 +
1116 +            # Send a checkout slip.
1117 +            my $circulation_alert = 'C4::ItemCirculationAlertPreference';
1118 +            my %conditions = (branchcode   => $branch,
1119 +                              categorycode => $borrower->{categorycode},
1120 +                              item_type    => $item->{itype},
1121 +                              notification => 'CHECKOUT',
1122 +                             );
1123 +            if ($circulation_alert->is_enabled_for(\%conditions)) {
1124 +                SendCirculationAlert(
1125 +                                     {type     => 'CHECKOUT',
1126 +                                      item     => $item,
1127 +                                      borrower => $borrower,
1128 +                                      branch   => $branch,
1129 +                                     }
1130 +                                    );
1131 +            }
1132          }
1133 -    }
1134  
1135 -    logaction("CIRCULATION", "ISSUE", $borrower->{'borrowernumber'}, $biblio->{'biblionumber'})
1136 -        if C4::Context->preference("IssueLog");
1137 -  }
1138 -  return ($datedue);   # not necessarily the same as when it came in!
1139 +        logaction("CIRCULATION", "ISSUE", $borrower->{'borrowernumber'}, $biblio->{'biblionumber'})
1140 +          if C4::Context->preference("IssueLog");
1141 +    }
1142 +    return ($datedue);    # not necessarily the same as when it came in!
1143  }
1144  
1145  =head2 GetLoanLength
1146 @@ -1118,51 +1096,49 @@ Get loan length for an itemtype, a borrower type and a branch
1147  =cut
1148  
1149  sub GetLoanLength {
1150 -    my ( $borrowertype, $itemtype, $branchcode ) = @_;
1151 +    my ($borrowertype, $itemtype, $branchcode) = @_;
1152      my $dbh = C4::Context->dbh;
1153 -    my $sth =
1154 -      $dbh->prepare(
1155 -"select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1156 -      );
1157 -# warn "in get loan lenght $borrowertype $itemtype $branchcode ";
1158 -# try to find issuelength & return the 1st available.
1159 -# check with borrowertype, itemtype and branchcode, then without one of those parameters
1160 -    $sth->execute( $borrowertype, $itemtype, $branchcode );
1161 +    my $sth = $dbh->prepare("select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null");
1162 +
1163 +    # warn "in get loan lenght $borrowertype $itemtype $branchcode ";
1164 +    # try to find issuelength & return the 1st available.
1165 +    # check with borrowertype, itemtype and branchcode, then without one of those parameters
1166 +    $sth->execute($borrowertype, $itemtype, $branchcode);
1167      my $loanlength = $sth->fetchrow_hashref;
1168      return $loanlength->{issuelength}
1169        if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1170  
1171 -    $sth->execute( $borrowertype, "*", $branchcode );
1172 +    $sth->execute($borrowertype, "*", $branchcode);
1173      $loanlength = $sth->fetchrow_hashref;
1174      return $loanlength->{issuelength}
1175        if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1176  
1177 -    $sth->execute( "*", $itemtype, $branchcode );
1178 +    $sth->execute("*", $itemtype, $branchcode);
1179      $loanlength = $sth->fetchrow_hashref;
1180      return $loanlength->{issuelength}
1181        if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1182  
1183 -    $sth->execute( "*", "*", $branchcode );
1184 +    $sth->execute("*", "*", $branchcode);
1185      $loanlength = $sth->fetchrow_hashref;
1186      return $loanlength->{issuelength}
1187        if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1188  
1189 -    $sth->execute( $borrowertype, $itemtype, "*" );
1190 +    $sth->execute($borrowertype, $itemtype, "*");
1191      $loanlength = $sth->fetchrow_hashref;
1192      return $loanlength->{issuelength}
1193        if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1194  
1195 -    $sth->execute( $borrowertype, "*", "*" );
1196 +    $sth->execute($borrowertype, "*", "*");
1197      $loanlength = $sth->fetchrow_hashref;
1198      return $loanlength->{issuelength}
1199        if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1200  
1201 -    $sth->execute( "*", $itemtype, "*" );
1202 +    $sth->execute("*", $itemtype, "*");
1203      $loanlength = $sth->fetchrow_hashref;
1204      return $loanlength->{issuelength}
1205        if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1206  
1207 -    $sth->execute( "*", "*", "*" );
1208 +    $sth->execute("*", "*", "*");
1209      $loanlength = $sth->fetchrow_hashref;
1210      return $loanlength->{issuelength}
1211        if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1212 @@ -1171,7 +1147,6 @@ sub GetLoanLength {
1213      return 21;
1214  }
1215  
1216 -
1217  =head2 GetHardDueDate
1218  
1219    my ($hardduedate,$hardduedatecompare) = &GetHardDueDate($borrowertype,$itemtype,branchcode)
1220 @@ -1181,50 +1156,47 @@ Get the Hard Due Date and it's comparison for an itemtype, a borrower type and a
1221  =cut
1222  
1223  sub GetHardDueDate {
1224 -    my ( $borrowertype, $itemtype, $branchcode ) = @_;
1225 +    my ($borrowertype, $itemtype, $branchcode) = @_;
1226      my $dbh = C4::Context->dbh;
1227 -    my $sth =
1228 -      $dbh->prepare(
1229 -"select hardduedate, hardduedatecompare from issuingrules where categorycode=? and itemtype=? and branchcode=?"
1230 -      );
1231 -    $sth->execute( $borrowertype, $itemtype, $branchcode );
1232 +    my $sth = $dbh->prepare("select hardduedate, hardduedatecompare from issuingrules where categorycode=? and itemtype=? and branchcode=?");
1233 +    $sth->execute($borrowertype, $itemtype, $branchcode);
1234      my $results = $sth->fetchrow_hashref;
1235 -    return (C4::Dates->new($results->{hardduedate}, 'iso'),$results->{hardduedatecompare})
1236 +    return (C4::Dates->new($results->{hardduedate}, 'iso'), $results->{hardduedatecompare})
1237        if defined($results) && $results->{hardduedate} ne 'NULL';
1238  
1239 -    $sth->execute( $borrowertype, "*", $branchcode );
1240 +    $sth->execute($borrowertype, "*", $branchcode);
1241      $results = $sth->fetchrow_hashref;
1242 -    return (C4::Dates->new($results->{hardduedate}, 'iso'),$results->{hardduedatecompare})
1243 +    return (C4::Dates->new($results->{hardduedate}, 'iso'), $results->{hardduedatecompare})
1244        if defined($results) && $results->{hardduedate} ne 'NULL';
1245  
1246 -    $sth->execute( "*", $itemtype, $branchcode );
1247 +    $sth->execute("*", $itemtype, $branchcode);
1248      $results = $sth->fetchrow_hashref;
1249 -    return (C4::Dates->new($results->{hardduedate}, 'iso'),$results->{hardduedatecompare})
1250 +    return (C4::Dates->new($results->{hardduedate}, 'iso'), $results->{hardduedatecompare})
1251        if defined($results) && $results->{hardduedate} ne 'NULL';
1252  
1253 -    $sth->execute( "*", "*", $branchcode );
1254 +    $sth->execute("*", "*", $branchcode);
1255      $results = $sth->fetchrow_hashref;
1256 -    return (C4::Dates->new($results->{hardduedate}, 'iso'),$results->{hardduedatecompare})
1257 +    return (C4::Dates->new($results->{hardduedate}, 'iso'), $results->{hardduedatecompare})
1258        if defined($results) && $results->{hardduedate} ne 'NULL';
1259  
1260 -    $sth->execute( $borrowertype, $itemtype, "*" );
1261 +    $sth->execute($borrowertype, $itemtype, "*");
1262      $results = $sth->fetchrow_hashref;
1263 -    return (C4::Dates->new($results->{hardduedate}, 'iso'),$results->{hardduedatecompare})
1264 +    return (C4::Dates->new($results->{hardduedate}, 'iso'), $results->{hardduedatecompare})
1265        if defined($results) && $results->{hardduedate} ne 'NULL';
1266  
1267 -    $sth->execute( $borrowertype, "*", "*" );
1268 +    $sth->execute($borrowertype, "*", "*");
1269      $results = $sth->fetchrow_hashref;
1270 -    return (C4::Dates->new($results->{hardduedate}, 'iso'),$results->{hardduedatecompare})
1271 +    return (C4::Dates->new($results->{hardduedate}, 'iso'), $results->{hardduedatecompare})
1272        if defined($results) && $results->{hardduedate} ne 'NULL';
1273  
1274 -    $sth->execute( "*", $itemtype, "*" );
1275 +    $sth->execute("*", $itemtype, "*");
1276      $results = $sth->fetchrow_hashref;
1277 -    return (C4::Dates->new($results->{hardduedate}, 'iso'),$results->{hardduedatecompare})
1278 +    return (C4::Dates->new($results->{hardduedate}, 'iso'), $results->{hardduedatecompare})
1279        if defined($results) && $results->{hardduedate} ne 'NULL';
1280  
1281 -    $sth->execute( "*", "*", "*" );
1282 +    $sth->execute("*", "*", "*");
1283      $results = $sth->fetchrow_hashref;
1284 -    return (C4::Dates->new($results->{hardduedate}, 'iso'),$results->{hardduedatecompare})
1285 +    return (C4::Dates->new($results->{hardduedate}, 'iso'), $results->{hardduedatecompare})
1286        if defined($results) && $results->{hardduedate} ne 'NULL';
1287  
1288      # if no rule is set => return undefined
1289 @@ -1245,42 +1217,42 @@ Returns a hashref from the issuingrules table.
1290  =cut
1291  
1292  sub GetIssuingRule {
1293 -    my ( $borrowertype, $itemtype, $branchcode ) = @_;
1294 +    my ($borrowertype, $itemtype, $branchcode) = @_;
1295      my $dbh = C4::Context->dbh;
1296 -    my $sth =  $dbh->prepare( "select * from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"  );
1297 +    my $sth = $dbh->prepare("select * from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null");
1298      my $irule;
1299  
1300 -       $sth->execute( $borrowertype, $itemtype, $branchcode );
1301 +    $sth->execute($borrowertype, $itemtype, $branchcode);
1302      $irule = $sth->fetchrow_hashref;
1303 -    return $irule if defined($irule) ;
1304 +    return $irule if defined($irule);
1305  
1306 -    $sth->execute( $borrowertype, "*", $branchcode );
1307 +    $sth->execute($borrowertype, "*", $branchcode);
1308      $irule = $sth->fetchrow_hashref;
1309 -    return $irule if defined($irule) ;
1310 +    return $irule if defined($irule);
1311  
1312 -    $sth->execute( "*", $itemtype, $branchcode );
1313 +    $sth->execute("*", $itemtype, $branchcode);
1314      $irule = $sth->fetchrow_hashref;
1315 -    return $irule if defined($irule) ;
1316 +    return $irule if defined($irule);
1317  
1318 -    $sth->execute( "*", "*", $branchcode );
1319 +    $sth->execute("*", "*", $branchcode);
1320      $irule = $sth->fetchrow_hashref;
1321 -    return $irule if defined($irule) ;
1322 +    return $irule if defined($irule);
1323  
1324 -    $sth->execute( $borrowertype, $itemtype, "*" );
1325 +    $sth->execute($borrowertype, $itemtype, "*");
1326      $irule = $sth->fetchrow_hashref;
1327 -    return $irule if defined($irule) ;
1328 +    return $irule if defined($irule);
1329  
1330 -    $sth->execute( $borrowertype, "*", "*" );
1331 +    $sth->execute($borrowertype, "*", "*");
1332      $irule = $sth->fetchrow_hashref;
1333 -    return $irule if defined($irule) ;
1334 +    return $irule if defined($irule);
1335  
1336 -    $sth->execute( "*", $itemtype, "*" );
1337 +    $sth->execute("*", $itemtype, "*");
1338      $irule = $sth->fetchrow_hashref;
1339 -    return $irule if defined($irule) ;
1340 +    return $irule if defined($irule);
1341  
1342 -    $sth->execute( "*", "*", "*" );
1343 +    $sth->execute("*", "*", "*");
1344      $irule = $sth->fetchrow_hashref;
1345 -    return $irule if defined($irule) ;
1346 +    return $irule if defined($irule);
1347  
1348      # if no rule matches,
1349      return undef;
1350 @@ -1319,7 +1291,7 @@ wildcards.
1351  =cut
1352  
1353  sub GetBranchBorrowerCircRule {
1354 -    my $branchcode = shift;
1355 +    my $branchcode   = shift;
1356      my $categorycode = shift;
1357  
1358      my $branch_cat_query = "SELECT maxissueqty
1359 @@ -1353,7 +1325,7 @@ sub GetBranchBorrowerCircRule {
1360      if ($result = $sth->fetchrow_hashref()) {
1361          return $result;
1362      }
1363 -  
1364 +
1365      # try default branch, default borrower category
1366      my $default_query = "SELECT maxissueqty
1367                            FROM default_circ_rules";
1368 @@ -1362,11 +1334,9 @@ sub GetBranchBorrowerCircRule {
1369      if ($result = $sth->fetchrow_hashref()) {
1370          return $result;
1371      }
1372 -    
1373 +
1374      # built-in default circulation rule
1375 -    return {
1376 -        maxissueqty => undef,
1377 -    };
1378 +    return {maxissueqty => undef,};
1379  }
1380  
1381  =head2 GetBranchItemRule
1382 @@ -1395,23 +1365,27 @@ Neither C<$branchcode> nor C<$categorycode> should be '*'.
1383  =cut
1384  
1385  sub GetBranchItemRule {
1386 -    my ( $branchcode, $itemtype ) = @_;
1387 -    my $dbh = C4::Context->dbh();
1388 +    my ($branchcode, $itemtype) = @_;
1389 +    my $dbh    = C4::Context->dbh();
1390      my $result = {};
1391  
1392      my @attempts = (
1393          ['SELECT holdallowed
1394              FROM branch_item_rules
1395              WHERE branchcode = ?
1396 -              AND itemtype = ?', $branchcode, $itemtype],
1397 +              AND itemtype = ?', $branchcode, $itemtype
1398 +        ],
1399          ['SELECT holdallowed
1400              FROM default_branch_circ_rules
1401 -            WHERE branchcode = ?', $branchcode],
1402 +            WHERE branchcode = ?', $branchcode
1403 +        ],
1404          ['SELECT holdallowed
1405              FROM default_branch_item_rules
1406 -            WHERE itemtype = ?', $itemtype],
1407 +            WHERE itemtype = ?', $itemtype
1408 +        ],
1409          ['SELECT holdallowed
1410 -            FROM default_circ_rules'],
1411 +            FROM default_circ_rules'
1412 +        ],
1413      );
1414  
1415      foreach my $attempt (@attempts) {
1416 @@ -1420,13 +1394,11 @@ sub GetBranchItemRule {
1417          # Since branch/category and branch/itemtype use the same per-branch
1418          # defaults tables, we have to check that the key we want is set, not
1419          # just that a row was returned
1420 -        return $result if ( defined( $result->{'holdallowed'} = $dbh->selectrow_array( $query, {}, @bind_params ) ) );
1421 +        return $result if (defined($result->{'holdallowed'} = $dbh->selectrow_array($query, {}, @bind_params)));
1422      }
1423 -    
1424 +
1425      # built-in default circulation rule
1426 -    return {
1427 -        holdallowed => 2,
1428 -    };
1429 +    return {holdallowed => 2,};
1430  }
1431  
1432  =head2 AddReturn
1433 @@ -1504,68 +1476,73 @@ patron who last borrowed the book.
1434  =cut
1435  
1436  sub AddReturn {
1437 -    my ( $barcode, $branch, $exemptfine, $dropbox ) = @_;
1438 +    my ($barcode, $branch, $exemptfine, $dropbox) = @_;
1439      if ($branch and not GetBranchDetail($branch)) {
1440          warn "AddReturn error: branch '$branch' not found.  Reverting to " . C4::Context->userenv->{'branch'};
1441          undef $branch;
1442      }
1443 -    $branch = C4::Context->userenv->{'branch'} unless $branch;  # we trust userenv to be a safe fallback/default
1444 +    $branch = C4::Context->userenv->{'branch'} unless $branch;    # we trust userenv to be a safe fallback/default
1445      my $messages;
1446      my $borrower;
1447      my $biblio;
1448      my $doreturn       = 1;
1449      my $validTransfert = 0;
1450 -    
1451 +
1452      # get information on item
1453 -    my $itemnumber = GetItemnumberFromBarcode( $barcode );
1454 +    my $itemnumber = GetItemnumberFromBarcode($barcode);
1455      unless ($itemnumber) {
1456 -        return (0, { BadBarcode => $barcode }); # no barcode means no item or borrower.  bail out.
1457 +        return (0, {BadBarcode => $barcode});                     # no barcode means no item or borrower.  bail out.
1458      }
1459 -    my $issue  = GetItemIssue($itemnumber);
1460 -#   warn Dumper($iteminformation);
1461 +    my $issue = GetItemIssue($itemnumber);
1462 +
1463 +    #   warn Dumper($iteminformation);
1464      if ($issue and $issue->{borrowernumber}) {
1465          $borrower = C4::Members::GetMemberDetails($issue->{borrowernumber})
1466 -            or die "Data inconsistency: barcode $barcode (itemnumber:$itemnumber) claims to be issued to non-existant borrowernumber '$issue->{borrowernumber}'\n"
1467 -                . Dumper($issue) . "\n";
1468 +          or die "Data inconsistency: barcode $barcode (itemnumber:$itemnumber) claims to be issued to non-existant borrowernumber '$issue->{borrowernumber}'\n"
1469 +          . Dumper($issue) . "\n";
1470      } else {
1471          $messages->{'NotIssued'} = $barcode;
1472 +
1473          # even though item is not on loan, it may still be transferred;  therefore, get current branch info
1474          $doreturn = 0;
1475 +
1476          # No issue, no borrowernumber.  ONLY if $doreturn, *might* you have a $borrower later.
1477      }
1478  
1479      my $item = GetItem($itemnumber) or die "GetItem($itemnumber) failed";
1480 -        # full item data, but no borrowernumber or checkout info (no issue)
1481 -        # we know GetItem should work because GetItemnumberFromBarcode worked
1482 -    my $hbr      = C4::Context->preference("HomeOrHoldingBranchReturn") || "homebranch";
1483 +
1484 +    # full item data, but no borrowernumber or checkout info (no issue)
1485 +    # we know GetItem should work because GetItemnumberFromBarcode worked
1486 +    my $hbr = C4::Context->preference("HomeOrHoldingBranchReturn") || "homebranch";
1487      $hbr = $item->{$hbr} || '';
1488 -        # item must be from items table -- issues table has branchcode and issuingbranch, not homebranch nor holdingbranch
1489 +
1490 +    # item must be from items table -- issues table has branchcode and issuingbranch, not homebranch nor holdingbranch
1491  
1492      my $borrowernumber = $borrower->{'borrowernumber'} || undef;    # we don't know if we had a borrower or not
1493  
1494      # check if the book is in a permanent collection....
1495      # FIXME -- This 'PE' attribute is largely undocumented.  afaict, there's no user interface that reflects this functionality.
1496 -    if ( $hbr ) {
1497 -        my $branches = GetBranches();    # a potentially expensive call for a non-feature.
1498 +    if ($hbr) {
1499 +        my $branches = GetBranches();                               # a potentially expensive call for a non-feature.
1500          $branches->{$hbr}->{PE} and $messages->{'IsPermanent'} = $hbr;
1501      }
1502  
1503      # if indy branches and returning to different branch, refuse the return
1504 -    if ($hbr ne $branch && C4::Context->preference("IndependantBranches")){
1505 -        $messages->{'Wrongbranch'} = {
1506 -            Wrongbranch => $branch,
1507 -            Rightbranch => $hbr,
1508 -        };
1509 +    if ($hbr ne $branch && C4::Context->preference("IndependantBranches")) {
1510 +        $messages->{'Wrongbranch'} = {Wrongbranch => $branch,
1511 +                                      Rightbranch => $hbr,
1512 +                                     };
1513          $doreturn = 0;
1514 +
1515          # bailing out here - in this case, current desired behavior
1516          # is to act as if no return ever happened at all.
1517          # FIXME - even in an indy branches situation, there should
1518          # still be an option for the library to accept the item
1519          # and transfer it to its owning library.
1520 -        return ( $doreturn, $messages, $issue, $borrower );
1521 +        return ($doreturn, $messages, $issue, $borrower);
1522      }
1523  
1524 -    if ( $item->{'wthdrawn'} ) { # book has been cancelled
1525 +    if ($item->{'wthdrawn'}) {    # book has been cancelled
1526          $messages->{'wthdrawn'} = 1;
1527          $doreturn = 0;
1528      }
1529 @@ -1573,12 +1550,13 @@ sub AddReturn {
1530      # case of a return of document (deal with issues and holdingbranch)
1531      if ($doreturn) {
1532          $borrower or warn "AddReturn without current borrower";
1533 -               my $circControlBranch;
1534 +        my $circControlBranch;
1535          if ($dropbox) {
1536 +
1537              # define circControlBranch only if dropbox mode is set
1538              # don't allow dropbox mode to create an invalid entry in issues (issuedate > today)
1539              # FIXME: check issuedate > returndate, factoring in holidays
1540 -            $circControlBranch = _GetCircControlBranch($item,$borrower) unless ( $item->{'issuedate'} eq C4::Dates->today('iso') );;
1541 +            $circControlBranch = _GetCircControlBranch($item, $borrower) unless ($item->{'issuedate'} eq C4::Dates->today('iso'));
1542          }
1543  
1544          if ($borrowernumber) {
1545 @@ -1586,27 +1564,26 @@ sub AddReturn {
1546              $messages->{'WasReturned'} = 1;    # FIXME is the "= 1" right?  This could be the borrower hash.
1547          }
1548  
1549 -        ModItem({ onloan => undef }, $issue->{'biblionumber'}, $item->{'itemnumber'});
1550 +        ModItem({onloan => undef}, $issue->{'biblionumber'}, $item->{'itemnumber'});
1551      }
1552  
1553      # the holdingbranch is updated if the document is returned to another location.
1554      # this is always done regardless of whether the item was on loan or not
1555      if ($item->{'holdingbranch'} ne $branch) {
1556          UpdateHoldingbranch($branch, $item->{'itemnumber'});
1557 -        $item->{'holdingbranch'} = $branch; # update item data holdingbranch too
1558 +        $item->{'holdingbranch'} = $branch;    # update item data holdingbranch too
1559      }
1560 -    ModDateLastSeen( $item->{'itemnumber'} );
1561 +    ModDateLastSeen($item->{'itemnumber'});
1562  
1563      # check if we have a transfer for this document
1564 -    my ($datesent,$frombranch,$tobranch) = GetTransfers( $item->{'itemnumber'} );
1565 +    my ($datesent, $frombranch, $tobranch) = GetTransfers($item->{'itemnumber'});
1566  
1567      # if we have a transfer to do, we update the line of transfers with the datearrived
1568      if ($datesent) {
1569 -        if ( $tobranch eq $branch ) {
1570 -            my $sth = C4::Context->dbh->prepare(
1571 -                "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1572 -            );
1573 -            $sth->execute( $item->{'itemnumber'} );
1574 +        if ($tobranch eq $branch) {
1575 +            my $sth = C4::Context->dbh->prepare("UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL");
1576 +            $sth->execute($item->{'itemnumber'});
1577 +
1578              # if we have a reservation with valid transfer, we can set it's status to 'W'
1579              C4::Reserves::ModReserveStatus($item->{'itemnumber'}, 'W');
1580          } else {
1581 @@ -1625,64 +1602,59 @@ sub AddReturn {
1582      # fix up the overdues in accounts...
1583      if ($borrowernumber) {
1584          my $fix = _FixOverduesOnReturn($borrowernumber, $item->{itemnumber}, $exemptfine, $dropbox);
1585 -        defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $item->{itemnumber}...) failed!";  # zero is OK, check defined
1586 +        defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $item->{itemnumber}...) failed!";    # zero is OK, check defined
1587      }
1588  
1589      # find reserves.....
1590      # if we don't have a reserve with the status W, we launch the Checkreserves routine
1591 -    my ($resfound, $resrec) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
1592 +    my ($resfound, $resrec) = C4::Reserves::CheckReserves($item->{'itemnumber'});
1593      if ($resfound) {
1594 -          $resrec->{'ResFound'} = $resfound;
1595 +        $resrec->{'ResFound'}   = $resfound;
1596          $messages->{'ResFound'} = $resrec;
1597      }
1598  
1599      # update stats?
1600      # Record the fact that this book was returned.
1601 -    UpdateStats(
1602 -        $branch, 'return', '0', '',
1603 -        $item->{'itemnumber'},
1604 -        $biblio->{'itemtype'},
1605 -        $borrowernumber
1606 -    );
1607 +    UpdateStats($branch, 'return', '0', '', $item->{'itemnumber'}, $biblio->{'itemtype'}, $borrowernumber);
1608  
1609      # Send a check-in slip. # NOTE: borrower may be undef.  probably shouldn't try to send messages then.
1610      my $circulation_alert = 'C4::ItemCirculationAlertPreference';
1611 -    my %conditions = (
1612 -        branchcode   => $branch,
1613 -        categorycode => $borrower->{categorycode},
1614 -        item_type    => $item->{itype},
1615 -        notification => 'CHECKIN',
1616 -    );
1617 +    my %conditions = (branchcode   => $branch,
1618 +                      categorycode => $borrower->{categorycode},
1619 +                      item_type    => $item->{itype},
1620 +                      notification => 'CHECKIN',
1621 +                     );
1622      if ($doreturn && $circulation_alert->is_enabled_for(\%conditions)) {
1623 -        SendCirculationAlert({
1624 -            type     => 'CHECKIN',
1625 -            item     => $item,
1626 -            borrower => $borrower,
1627 -            branch   => $branch,
1628 -        });
1629 -    }
1630 -    
1631 +        SendCirculationAlert(
1632 +                             {type     => 'CHECKIN',
1633 +                              item     => $item,
1634 +                              borrower => $borrower,
1635 +                              branch   => $branch,
1636 +                             }
1637 +                            );
1638 +    }
1639 +
1640      logaction("CIRCULATION", "RETURN", $borrowernumber, $item->{'biblionumber'})
1641 -        if C4::Context->preference("ReturnLog");
1642 -    
1643 +      if C4::Context->preference("ReturnLog");
1644 +
1645      # FIXME: make this comment intelligible.
1646      #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1647      #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1648  
1649 -    if (($doreturn or $messages->{'NotIssued'}) and !$resfound and ($branch ne $hbr) and not $messages->{'WrongTransfer'}){
1650 -        if ( C4::Context->preference("AutomaticItemReturn"    ) or
1651 -            (C4::Context->preference("UseBranchTransferLimits") and
1652 -             ! IsBranchTransferAllowed($branch, $hbr, $item->{C4::Context->preference("BranchTransferLimitsType")} )
1653 -           )) {
1654 -            $debug and warn sprintf "about to call ModItemTransfer(%s, %s, %s)", $item->{'itemnumber'},$branch, $hbr;
1655 +    if (($doreturn or $messages->{'NotIssued'}) and !$resfound and ($branch ne $hbr) and not $messages->{'WrongTransfer'}) {
1656 +        if (C4::Context->preference("AutomaticItemReturn")
1657 +            or (C4::Context->preference("UseBranchTransferLimits")
1658 +                and !IsBranchTransferAllowed($branch, $hbr, $item->{C4::Context->preference("BranchTransferLimitsType")}))
1659 +          ) {
1660 +            $debug and warn sprintf "about to call ModItemTransfer(%s, %s, %s)", $item->{'itemnumber'}, $branch, $hbr;
1661              $debug and warn "item: " . Dumper($item);
1662              ModItemTransfer($item->{'itemnumber'}, $branch, $hbr);
1663              $messages->{'WasTransfered'} = 1;
1664          } else {
1665 -            $messages->{'NeedsTransfer'} = 1;   # TODO: instead of 1, specify branchcode that the transfer SHOULD go to, $item->{homebranch}
1666 +            $messages->{'NeedsTransfer'} = 1;    # TODO: instead of 1, specify branchcode that the transfer SHOULD go to, $item->{homebranch}
1667          }
1668      }
1669 -    return ( $doreturn, $messages, $issue, $borrower );
1670 +    return ($doreturn, $messages, $issue, $borrower);
1671  }
1672  
1673  =head2 MarkIssueReturned
1674 @@ -1709,13 +1681,13 @@ routine in C<C4::Accounts>.
1675  =cut
1676  
1677  sub MarkIssueReturned {
1678 -    my ( $borrowernumber, $itemnumber, $dropbox_branch, $returndate, $privacy ) = @_;
1679 +    my ($borrowernumber, $itemnumber, $dropbox_branch, $returndate, $privacy) = @_;
1680      my $dbh   = C4::Context->dbh;
1681      my $query = "UPDATE issues SET returndate=";
1682      my @bind;
1683      if ($dropbox_branch) {
1684 -        my $calendar = C4::Calendar->new( branchcode => $dropbox_branch );
1685 -        my $dropboxdate = $calendar->addDate( C4::Dates->new(), -1 );
1686 +        my $calendar = C4::Calendar->new(branchcode => $dropbox_branch);
1687 +        my $dropboxdate = $calendar->addDate(C4::Dates->new(), -1);
1688          $query .= " ? ";
1689          push @bind, $dropboxdate->output('iso');
1690      } elsif ($returndate) {
1691 @@ -1726,26 +1698,35 @@ sub MarkIssueReturned {
1692      }
1693      $query .= " WHERE  borrowernumber = ?  AND itemnumber = ?";
1694      push @bind, $borrowernumber, $itemnumber;
1695 +
1696      # FIXME transaction
1697 -    my $sth_upd  = $dbh->prepare($query);
1698 +    my $sth_upd = $dbh->prepare($query);
1699      $sth_upd->execute(@bind);
1700 -    my $sth_copy = $dbh->prepare("INSERT INTO old_issues SELECT * FROM issues 
1701 +    my $sth_copy = $dbh->prepare(
1702 +        "INSERT INTO old_issues SELECT * FROM issues 
1703                                    WHERE borrowernumber = ?
1704 -                                  AND itemnumber = ?");
1705 +                                  AND itemnumber = ?"
1706 +                                );
1707      $sth_copy->execute($borrowernumber, $itemnumber);
1708 +
1709      # anonymise patron checkout immediately if $privacy set to 2 and AnonymousPatron is set to a valid borrowernumber
1710 -    if ( $privacy == 2) {
1711 +    if ($privacy == 2) {
1712 +
1713          # The default of 0 does not work due to foreign key constraints
1714          # The anonymisation will fail quietly if AnonymousPatron is not a valid entry
1715          my $anonymouspatron = (C4::Context->preference('AnonymousPatron')) ? C4::Context->preference('AnonymousPatron') : 0;
1716 -        my $sth_ano = $dbh->prepare("UPDATE old_issues SET borrowernumber=?
1717 +        my $sth_ano = $dbh->prepare(
1718 +            "UPDATE old_issues SET borrowernumber=?
1719                                    WHERE borrowernumber = ?
1720 -                                  AND itemnumber = ?");
1721 -       $sth_ano->execute($anonymouspatron, $borrowernumber, $itemnumber);
1722 +                                  AND itemnumber = ?"
1723 +                                   );
1724 +        $sth_ano->execute($anonymouspatron, $borrowernumber, $itemnumber);
1725      }
1726 -    my $sth_del  = $dbh->prepare("DELETE FROM issues
1727 +    my $sth_del = $dbh->prepare(
1728 +        "DELETE FROM issues
1729                                    WHERE borrowernumber = ?
1730 -                                  AND itemnumber = ?");
1731 +                                  AND itemnumber = ?"
1732 +                               );
1733      $sth_del->execute($borrowernumber, $itemnumber);
1734  }
1735  
1736 @@ -1778,10 +1759,8 @@ sub _FixOverduesOnReturn {
1737      my $dbh = C4::Context->dbh;
1738  
1739      # check for overdue fine
1740 -    my $sth = $dbh->prepare(
1741 -"SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1742 -    );
1743 -    $sth->execute( $borrowernumber, $item );
1744 +    my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')");
1745 +    $sth->execute($borrowernumber, $item);
1746  
1747      # alter fine to show that the book has been returned
1748      my $data = $sth->fetchrow_hashref;
1749 @@ -1792,18 +1771,18 @@ sub _FixOverduesOnReturn {
1750      if ($exemptfine) {
1751          $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
1752          if (C4::Context->preference("FinesLog")) {
1753 -            &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
1754 +            &logaction("FINES", 'MODIFY', $borrowernumber, "Overdue forgiven: item $item");
1755          }
1756      } elsif ($dropbox && $data->{lastincrement}) {
1757 -        my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
1758 -        my $amt = $data->{amount} - $data->{lastincrement} ;
1759 +        my $outstanding = $data->{amountoutstanding} - $data->{lastincrement};
1760 +        my $amt         = $data->{amount} - $data->{lastincrement};
1761          if (C4::Context->preference("FinesLog")) {
1762 -            &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
1763 +            &logaction("FINES", 'MODIFY', $borrowernumber, "Dropbox adjustment $amt, item $item");
1764          }
1765 -         $uquery = "update accountlines set accounttype='F' ";
1766 -         if($outstanding  >= 0 && $amt >=0) {
1767 +        $uquery = "update accountlines set accounttype='F' ";
1768 +        if ($outstanding >= 0 && $amt >= 0) {
1769              $uquery .= ", amount = ? , amountoutstanding=? ";
1770 -            unshift @bind, ($amt, $outstanding) ;
1771 +            unshift @bind, ($amt, $outstanding);
1772          }
1773      } else {
1774          $uquery = "update accountlines set accounttype='F' ";
1775 @@ -1827,78 +1806,93 @@ FIXME: Give a positive return value on success.  It might be the $borrowernumber
1776  =cut
1777  
1778  sub _FixAccountForLostAndReturned {
1779 -    my $itemnumber     = shift or return;
1780 +    my $itemnumber = shift or return;
1781      my $borrowernumber = @_ ? shift : undef;
1782 -    my $item_id        = @_ ? shift : $itemnumber;  # Send the barcode if you want that logged in the description
1783 -    my $dbh = C4::Context->dbh;
1784 +    my $item_id        = @_ ? shift : $itemnumber;    # Send the barcode if you want that logged in the description
1785 +    my $dbh            = C4::Context->dbh;
1786 +
1787      # check for charge made for lost book
1788      my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1789      $sth->execute($itemnumber);
1790      my $data = $sth->fetchrow_hashref;
1791 -    $data or return;    # bail if there is nothing to do
1792 +    $data or return;                                  # bail if there is nothing to do
1793  
1794      # writeoff this amount
1795      my $offset;
1796      my $amount = $data->{'amount'};
1797      my $acctno = $data->{'accountno'};
1798 -    my $amountleft;                                             # Starts off undef/zero.
1799 +    my $amountleft;                                   # Starts off undef/zero.
1800      if ($data->{'amountoutstanding'} == $amount) {
1801          $offset     = $data->{'amount'};
1802 -        $amountleft = 0;                                        # Hey, it's zero here, too.
1803 +        $amountleft = 0;                              # Hey, it's zero here, too.
1804      } else {
1805 -        $offset     = $amount - $data->{'amountoutstanding'};   # Um, isn't this the same as ZERO?  We just tested those two things are ==
1806 -        $amountleft = $data->{'amountoutstanding'} - $amount;   # Um, isn't this the same as ZERO?  We just tested those two things are ==
1807 +        $offset     = $amount - $data->{'amountoutstanding'};    # Um, isn't this the same as ZERO?  We just tested those two things are ==
1808 +        $amountleft = $data->{'amountoutstanding'} - $amount;    # Um, isn't this the same as ZERO?  We just tested those two things are ==
1809      }
1810 -    my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1811 +    my $usth = $dbh->prepare(
1812 +        "UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1813          WHERE (borrowernumber = ?)
1814 -        AND (itemnumber = ?) AND (accountno = ?) ");
1815 -    $usth->execute($data->{'borrowernumber'},$itemnumber,$acctno);      # We might be adjusting an account for some OTHER borrowernumber now.  Not the one we passed in.  
1816 -    #check if any credit is left if so writeoff other accounts
1817 +        AND (itemnumber = ?) AND (accountno = ?) "
1818 +                            );
1819 +    $usth->execute($data->{'borrowernumber'}, $itemnumber, $acctno);    # We might be adjusting an account for some OTHER borrowernumber now.  Not the one we passed in.
1820 +                                                                        #check if any credit is left if so writeoff other accounts
1821      my $nextaccntno = getnextacctno($data->{'borrowernumber'});
1822      $amountleft *= -1 if ($amountleft < 0);
1823      if ($amountleft > 0) {
1824 -        my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1825 -                            AND (amountoutstanding >0) ORDER BY date");     # might want to order by amountoustanding ASC (pay smallest first)
1826 +        my $msth = $dbh->prepare(
1827 +            "SELECT * FROM accountlines WHERE (borrowernumber = ?)
1828 +                            AND (amountoutstanding >0) ORDER BY date");                                      # might want to order by amountoustanding ASC (pay smallest first)
1829          $msth->execute($data->{'borrowernumber'});
1830 +
1831          # offset transactions
1832          my $newamtos;
1833          my $accdata;
1834 -        while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1835 +        while (($accdata = $msth->fetchrow_hashref) and ($amountleft > 0)) {
1836              if ($accdata->{'amountoutstanding'} < $amountleft) {
1837                  $newamtos = 0;
1838                  $amountleft -= $accdata->{'amountoutstanding'};
1839 -            }  else {
1840 -                $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1841 +            } else {
1842 +                $newamtos   = $accdata->{'amountoutstanding'} - $amountleft;
1843                  $amountleft = 0;
1844              }
1845              my $thisacct = $accdata->{'accountno'};
1846 +
1847              # FIXME: move prepares outside while loop!
1848 -            my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1849 +            my $usth = $dbh->prepare(
1850 +                "UPDATE accountlines SET amountoutstanding= ?
1851                      WHERE (borrowernumber = ?)
1852 -                    AND (accountno=?)");
1853 -            $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');    # FIXME: '$thisacct' is a string literal!
1854 -            $usth = $dbh->prepare("INSERT INTO accountoffsets
1855 +                    AND (accountno=?)"
1856 +                                    );
1857 +            $usth->execute($newamtos, $data->{'borrowernumber'}, '$thisacct');    # FIXME: '$thisacct' is a string literal!
1858 +            $usth = $dbh->prepare(
1859 +                "INSERT INTO accountoffsets
1860                  (borrowernumber, accountno, offsetaccount,  offsetamount)
1861                  VALUES
1862 -                (?,?,?,?)");
1863 -            $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1864 +                (?,?,?,?)"
1865 +                                 );
1866 +            $usth->execute($data->{'borrowernumber'}, $accdata->{'accountno'}, $nextaccntno, $newamtos);
1867          }
1868 -        $msth->finish;  # $msth might actually have data left
1869 +        $msth->finish;                                                            # $msth might actually have data left
1870      }
1871      $amountleft *= -1 if ($amountleft > 0);
1872      my $desc = "Item Returned " . $item_id;
1873 -    $usth = $dbh->prepare("INSERT INTO accountlines
1874 +    $usth = $dbh->prepare(
1875 +        "INSERT INTO accountlines
1876          (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1877 -        VALUES (?,?,now(),?,?,'CR',?)");
1878 -    $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1879 +        VALUES (?,?,now(),?,?,'CR',?)"
1880 +                         );
1881 +    $usth->execute($data->{'borrowernumber'}, $nextaccntno, 0 - $amount, $desc, $amountleft);
1882      if ($borrowernumber) {
1883 +
1884          # FIXME: same as query above.  use 1 sth for both
1885 -        $usth = $dbh->prepare("INSERT INTO accountoffsets
1886 +        $usth = $dbh->prepare(
1887 +            "INSERT INTO accountoffsets
1888              (borrowernumber, accountno, offsetaccount,  offsetamount)
1889 -            VALUES (?,?,?,?)");
1890 +            VALUES (?,?,?,?)"
1891 +                             );
1892          $usth->execute($borrowernumber, $data->{'accountno'}, $nextaccntno, $offset);
1893      }
1894 -    ModItem({ paidfor => '' }, undef, $itemnumber);
1895 +    ModItem({paidfor => ''}, undef, $itemnumber);
1896      return;
1897  }
1898  
1899 @@ -1924,12 +1918,13 @@ sub _GetCircControlBranch {
1900      my $branch;
1901  
1902      if ($circcontrol eq 'PickupLibrary') {
1903 -        $branch= C4::Context->userenv->{'branch'} if C4::Context->userenv;
1904 +        $branch = C4::Context->userenv->{'branch'} if C4::Context->userenv;
1905      } elsif ($circcontrol eq 'PatronLibrary') {
1906 -        $branch=$borrower->{branchcode};
1907 +        $branch = $borrower->{branchcode};
1908      } else {
1909          my $branchfield = C4::Context->preference('HomeOrHoldingBranch') || 'homebranch';
1910          $branch = $item->{$branchfield};
1911 +
1912          # default to item home branch if holdingbranch is used
1913          # and is not defined
1914          if (!defined($branch) && $branchfield eq 'holdingbranch') {
1915 @@ -1939,11 +1934,6 @@ sub _GetCircControlBranch {
1916      return $branch;
1917  }
1918  
1919 -
1920 -
1921 -
1922 -
1923 -
1924  =head2 GetItemIssue
1925  
1926    $issue = &GetItemIssue($itemnumber);
1927 @@ -1963,7 +1953,8 @@ sub GetItemIssue {
1928          "SELECT *
1929          FROM issues 
1930          LEFT JOIN items ON issues.itemnumber=items.itemnumber
1931 -        WHERE issues.itemnumber=?");
1932 +        WHERE issues.itemnumber=?"
1933 +                                       );
1934      $sth->execute($itemnumber);
1935      my $data = $sth->fetchrow_hashref;
1936      return unless $data;
1937 @@ -1984,13 +1975,13 @@ Returns a hashref
1938  =cut
1939  
1940  sub GetOpenIssue {
1941 -  my ( $itemnumber ) = @_;
1942 +    my ($itemnumber) = @_;
1943  
1944 -  my $dbh = C4::Context->dbh;  
1945 -  my $sth = $dbh->prepare( "SELECT * FROM issues WHERE itemnumber = ? AND returndate IS NULL" );
1946 -  $sth->execute( $itemnumber );
1947 -  my $issue = $sth->fetchrow_hashref();
1948 -  return $issue;
1949 +    my $dbh = C4::Context->dbh;
1950 +    my $sth = $dbh->prepare("SELECT * FROM issues WHERE itemnumber = ? AND returndate IS NULL");
1951 +    $sth->execute($itemnumber);
1952 +    my $issue = $sth->fetchrow_hashref();
1953 +    return $issue;
1954  }
1955  
1956  =head2 GetItemIssues
1957 @@ -2008,10 +1999,10 @@ Returns reference to an array of hashes
1958  =cut
1959  
1960  sub GetItemIssues {
1961 -    my ( $itemnumber, $history ) = @_;
1962 -    
1963 -    my $today = C4::Dates->today('iso');  # get today date
1964 -    my $sql = "SELECT * FROM issues 
1965 +    my ($itemnumber, $history) = @_;
1966 +
1967 +    my $today = C4::Dates->today('iso');    # get today date
1968 +    my $sql   = "SELECT * FROM issues 
1969                JOIN borrowers USING (borrowernumber)
1970                JOIN items     USING (itemnumber)
1971                WHERE issues.itemnumber = ? ";
1972 @@ -2074,7 +2065,7 @@ sub GetBiblioIssues {
1973      $sth->execute($biblionumber, $biblionumber);
1974  
1975      my @issues;
1976 -    while ( my $data = $sth->fetchrow_hashref ) {
1977 +    while (my $data = $sth->fetchrow_hashref) {
1978          push @issues, $data;
1979      }
1980      return \@issues;
1981 @@ -2101,10 +2092,10 @@ WhERE returndate is NULL
1982  AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ?
1983  END_SQL
1984  
1985 -    my @bind_parameters = ( $params->{'days_in_advance'} );
1986 -    
1987 -    my $sth = $dbh->prepare( $statement );
1988 -    $sth->execute( @bind_parameters );
1989 +    my @bind_parameters = ($params->{'days_in_advance'});
1990 +
1991 +    my $sth = $dbh->prepare($statement);
1992 +    $sth->execute(@bind_parameters);
1993      my $upcoming_dues = $sth->fetchall_arrayref({});
1994      $sth->finish;
1995  
1996 @@ -2138,25 +2129,24 @@ already renewed the loan. $error will contain the reason the renewal can not pro
1997  sub CanBookBeRenewed {
1998  
1999      # check renewal status
2000 -    my ( $borrowernumber, $itemnumber, $override_limit ) = @_;
2001 +    my ($borrowernumber, $itemnumber, $override_limit) = @_;
2002      my $dbh       = C4::Context->dbh;
2003      my $renews    = 1;
2004      my $renewokay = 0;
2005 -       my $error;
2006 +    my $error;
2007  
2008      # Look in the issues table for this item, lent to this borrower,
2009      # and not yet returned.
2010  
2011      # Look in the issues table for this item, lent to this borrower,
2012      # and not yet returned.
2013 -    my %branch = (
2014 -            'ItemHomeLibrary' => 'items.homebranch',
2015 -            'PickupLibrary'   => 'items.holdingbranch',
2016 -            'PatronLibrary'   => 'borrowers.branchcode'
2017 -            );
2018 +    my %branch = ('ItemHomeLibrary' => 'items.homebranch',
2019 +                  'PickupLibrary'   => 'items.holdingbranch',
2020 +                  'PatronLibrary'   => 'borrowers.branchcode'
2021 +                 );
2022      my $controlbranch = $branch{C4::Context->preference('CircControl')};
2023 -    my $itype         = C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype';
2024 -    
2025 +    my $itype = C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype';
2026 +
2027      my $sthcount = $dbh->prepare("
2028                     SELECT 
2029                      borrowers.categorycode, biblioitems.itemtype, issues.renewals, renewalsallowed, $controlbranch
2030 @@ -2183,24 +2173,23 @@ sub CanBookBeRenewed {
2031                     LIMIT 1;
2032                    ");
2033  
2034 -    $sthcount->execute( $borrowernumber, $itemnumber );
2035 -    if ( my $data1 = $sthcount->fetchrow_hashref ) {
2036 -        
2037 -        if ( ( $data1->{renewalsallowed} && $data1->{renewalsallowed} > $data1->{renewals} ) || $override_limit ) {
2038 +    $sthcount->execute($borrowernumber, $itemnumber);
2039 +    if (my $data1 = $sthcount->fetchrow_hashref) {
2040 +
2041 +        if (($data1->{renewalsallowed} && $data1->{renewalsallowed} > $data1->{renewals}) || $override_limit) {
2042              $renewokay = 1;
2043 +        } else {
2044 +            $error = "too_many";
2045          }
2046 -        else {
2047 -                       $error="too_many";
2048 -               }
2049 -               
2050 -        my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
2051 +
2052 +        my ($resfound, $resrec) = C4::Reserves::CheckReserves($itemnumber);
2053          if ($resfound) {
2054              $renewokay = 0;
2055 -                       $error="on_reserve"
2056 +            $error     = "on_reserve";
2057          }
2058  
2059      }
2060 -    return ($renewokay,$error);
2061 +    return ($renewokay, $error);
2062  }
2063  
2064  =head2 AddRenewal
2065 @@ -2228,89 +2217,93 @@ from the book's item type.
2066  =cut
2067  
2068  sub AddRenewal {
2069 -    my $borrowernumber  = shift or return undef;
2070 -    my $itemnumber      = shift or return undef;
2071 -    my $branch          = shift;
2072 -    my $datedue         = shift;
2073 +    my $borrowernumber = shift or return undef;
2074 +    my $itemnumber     = shift or return undef;
2075 +    my $branch         = shift;
2076 +    my $datedue        = shift;
2077      my $lastreneweddate = shift || C4::Dates->new()->output('iso');
2078 -    my $item   = GetItem($itemnumber) or return undef;
2079 +    my $item = GetItem($itemnumber) or return undef;
2080      my $biblio = GetBiblioFromItemNumber($itemnumber) or return undef;
2081  
2082      my $dbh = C4::Context->dbh;
2083 +
2084      # Find the issues record for this book
2085 -    my $sth =
2086 -      $dbh->prepare("SELECT * FROM issues
2087 +    my $sth = $dbh->prepare(
2088 +        "SELECT * FROM issues
2089                          WHERE borrowernumber=? 
2090                          AND itemnumber=?"
2091 -      );
2092 -    $sth->execute( $borrowernumber, $itemnumber );
2093 +                           );
2094 +    $sth->execute($borrowernumber, $itemnumber);
2095      my $issuedata = $sth->fetchrow_hashref;
2096      $sth->finish;
2097 -    if($datedue && ! $datedue->output('iso')){
2098 +    if ($datedue && !$datedue->output('iso')) {
2099          warn "Invalid date passed to AddRenewal.";
2100          return undef;
2101      }
2102 +
2103      # If the due date wasn't specified, calculate it by adding the
2104      # book's loan length to today's date or the current due date
2105      # based on the value of the RenewalPeriodBase syspref.
2106      unless ($datedue) {
2107  
2108 -        my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 ) or return undef;
2109 +        my $borrower = C4::Members::GetMemberDetails($borrowernumber, 0) or return undef;
2110          my $itemtype = (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'};
2111  
2112 -        $datedue = (C4::Context->preference('RenewalPeriodBase') eq 'date_due') ?
2113 -                                        C4::Dates->new($issuedata->{date_due}, 'iso') :
2114 -                                        C4::Dates->new();
2115 -        $datedue =  CalcDateDue($datedue,$itemtype,$issuedata->{'branchcode'},$borrower);
2116 +        $datedue =
2117 +          (C4::Context->preference('RenewalPeriodBase') eq 'date_due')
2118 +          ? C4::Dates->new($issuedata->{date_due}, 'iso')
2119 +          : C4::Dates->new();
2120 +        $datedue = CalcDateDue($datedue, $itemtype, $issuedata->{'branchcode'}, $borrower);
2121      }
2122  
2123      # Update the issues record to have the new due date, and a new count
2124      # of how many times it has been renewed.
2125      my $renews = $issuedata->{'renewals'} + 1;
2126 -    $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?, lastreneweddate = ?
2127 +    $sth = $dbh->prepare(
2128 +        "UPDATE issues SET date_due = ?, renewals = ?, lastreneweddate = ?
2129                              WHERE borrowernumber=? 
2130                              AND itemnumber=?"
2131 -    );
2132 -    $sth->execute( $datedue->output('iso'), $renews, $lastreneweddate, $borrowernumber, $itemnumber );
2133 +                        );
2134 +    $sth->execute($datedue->output('iso'), $renews, $lastreneweddate, $borrowernumber, $itemnumber);
2135      $sth->finish;
2136  
2137      # Update the renewal count on the item, and tell zebra to reindex
2138      $renews = $biblio->{'renewals'} + 1;
2139 -    ModItem({ renewals => $renews, onloan => $datedue->output('iso') }, $biblio->{'biblionumber'}, $itemnumber);
2140 +    ModItem({renewals => $renews, onloan => $datedue->output('iso')}, $biblio->{'biblionumber'}, $itemnumber);
2141  
2142      # Charge a new rental fee, if applicable?
2143 -    my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2144 -    if ( $charge > 0 ) {
2145 -        my $accountno = getnextacctno( $borrowernumber );
2146 -        my $item = GetBiblioFromItemNumber($itemnumber);
2147 +    my ($charge, $type) = GetIssuingCharges($itemnumber, $borrowernumber);
2148 +    if ($charge > 0) {
2149 +        my $accountno  = getnextacctno($borrowernumber);
2150 +        my $item       = GetBiblioFromItemNumber($itemnumber);
2151          my $manager_id = 0;
2152 -        $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv; 
2153 +        $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
2154          $sth = $dbh->prepare(
2155 -                "INSERT INTO accountlines
2156 +            "INSERT INTO accountlines
2157                      (date, borrowernumber, accountno, amount, manager_id,
2158                      description,accounttype, amountoutstanding, itemnumber)
2159                      VALUES (now(),?,?,?,?,?,?,?,?)"
2160 -        );
2161 -        $sth->execute( $borrowernumber, $accountno, $charge, $manager_id,
2162 -            "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
2163 -            'Rent', $charge, $itemnumber );
2164 +                            );
2165 +        $sth->execute($borrowernumber, $accountno, $charge, $manager_id, "Renewal of Rental Item $item->{'title'} $item->{'barcode'}", 'Rent', $charge, $itemnumber);
2166          $sth->finish;
2167      }
2168 +
2169      # Log the renewal
2170 -    UpdateStats( $branch, 'renew', $charge, '', $itemnumber, $item->{itype}, $borrowernumber);
2171 -       return $datedue;
2172 +    UpdateStats($branch, 'renew', $charge, '', $itemnumber, $item->{itype}, $borrowernumber);
2173 +    return $datedue;
2174  }
2175  
2176  sub GetRenewCount {
2177 +
2178      # check renewal status
2179 -    my ( $bornum, $itemno ) = @_;
2180 +    my ($bornum, $itemno) = @_;
2181      my $dbh           = C4::Context->dbh;
2182      my $renewcount    = 0;
2183      my $renewsallowed = 0;
2184      my $renewsleft    = 0;
2185  
2186      my $borrower = C4::Members::GetMemberDetails($bornum);
2187 -    my $item     = GetItem($itemno); 
2188 +    my $item     = GetItem($itemno);
2189  
2190      # Look in the issues table for this item, lent to this borrower,
2191      # and not yet returned.
2192 @@ -2320,20 +2313,21 @@ sub GetRenewCount {
2193          "select * from issues
2194                                  where (borrowernumber = ?)
2195                                  and (itemnumber = ?)"
2196 -    );
2197 -    $sth->execute( $bornum, $itemno );
2198 +                           );
2199 +    $sth->execute($bornum, $itemno);
2200      my $data = $sth->fetchrow_hashref;
2201      $renewcount = $data->{'renewals'} if $data->{'renewals'};
2202      $sth->finish;
2203 +
2204      # $item and $borrower should be calculated
2205      my $branchcode = _GetCircControlBranch($item, $borrower);
2206 -    
2207 +
2208      my $issuingrule = GetIssuingRule($borrower->{categorycode}, $item->{itype}, $branchcode);
2209 -    
2210 +
2211      $renewsallowed = $issuingrule->{'renewalsallowed'};
2212      $renewsleft    = $renewsallowed - $renewcount;
2213 -    if($renewsleft < 0){ $renewsleft = 0; }
2214 -    return ( $renewcount, $renewsallowed, $renewsleft );
2215 +    if ($renewsleft < 0) { $renewsleft = 0; }
2216 +    return ($renewcount, $renewsallowed, $renewsleft);
2217  }
2218  
2219  =head2 GetIssuingCharges
2220 @@ -2356,7 +2350,7 @@ if it's a video).
2221  sub GetIssuingCharges {
2222  
2223      # calculate charges due
2224 -    my ( $itemnumber, $borrowernumber ) = @_;
2225 +    my ($itemnumber, $borrowernumber) = @_;
2226      my $charge = 0;
2227      my $dbh    = C4::Context->dbh;
2228      my $item_type;
2229 @@ -2364,18 +2358,19 @@ sub GetIssuingCharges {
2230      # Get the book's item type and rental charge (via its biblioitem).
2231      my $charge_query = 'SELECT itemtypes.itemtype,rentalcharge FROM items
2232          LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber';
2233 -    $charge_query .= (C4::Context->preference('item-level_itypes'))
2234 -        ? ' LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype'
2235 -        : ' LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype';
2236 +    $charge_query .=
2237 +      (C4::Context->preference('item-level_itypes'))
2238 +      ? ' LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype'
2239 +      : ' LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype';
2240  
2241      $charge_query .= ' WHERE items.itemnumber =?';
2242  
2243      my $sth = $dbh->prepare($charge_query);
2244      $sth->execute($itemnumber);
2245 -    if ( my $item_data = $sth->fetchrow_hashref ) {
2246 +    if (my $item_data = $sth->fetchrow_hashref) {
2247          $item_type = $item_data->{itemtype};
2248          $charge    = $item_data->{rentalcharge};
2249 -        my $branch = C4::Branch::mybranch();
2250 +        my $branch         = C4::Branch::mybranch();
2251          my $discount_query = q|SELECT rentaldiscount,
2252              issuingrules.itemtype, issuingrules.branchcode
2253              FROM borrowers
2254 @@ -2384,17 +2379,19 @@ sub GetIssuingCharges {
2255              AND (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
2256              AND (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')|;
2257          my $discount_sth = $dbh->prepare($discount_query);
2258 -        $discount_sth->execute( $borrowernumber, $item_type, $branch );
2259 +        $discount_sth->execute($borrowernumber, $item_type, $branch);
2260          my $discount_rules = $discount_sth->fetchall_arrayref({});
2261 +
2262          if (@{$discount_rules}) {
2263 +
2264              # We may have multiple rules so get the most specific
2265              my $discount = _get_discount_from_rule($discount_rules, $branch, $item_type);
2266 -            $charge = ( $charge * ( 100 - $discount ) ) / 100;
2267 +            $charge = ($charge * (100 - $discount)) / 100;
2268          }
2269      }
2270  
2271 -    $sth->finish; # we havent _explicitly_ fetched all rows
2272 -    return ( $charge, $item_type );
2273 +    $sth->finish;    # we havent _explicitly_ fetched all rows
2274 +    return ($charge, $item_type);
2275  }
2276  
2277  # Select most appropriate discount rule from those returned
2278 @@ -2402,34 +2399,39 @@ sub _get_discount_from_rule {
2279      my ($rules_ref, $branch, $itemtype) = @_;
2280      my $discount;
2281  
2282 -    if (@{$rules_ref} == 1) { # only 1 applicable rule use it
2283 +    if (@{$rules_ref} == 1) {    # only 1 applicable rule use it
2284          $discount = $rules_ref->[0]->{rentaldiscount};
2285          return (defined $discount) ? $discount : 0;
2286      }
2287 +
2288      # could have up to 4 does one match $branch and $itemtype
2289      my @d = grep { $_->{branchcode} eq $branch && $_->{itemtype} eq $itemtype } @{$rules_ref};
2290      if (@d) {
2291          $discount = $d[0]->{rentaldiscount};
2292          return (defined $discount) ? $discount : 0;
2293      }
2294 +
2295      # do we have item type + all branches
2296      @d = grep { $_->{branchcode} eq q{*} && $_->{itemtype} eq $itemtype } @{$rules_ref};
2297      if (@d) {
2298          $discount = $d[0]->{rentaldiscount};
2299          return (defined $discount) ? $discount : 0;
2300      }
2301 +
2302      # do we all item types + this branch
2303      @d = grep { $_->{branchcode} eq $branch && $_->{itemtype} eq q{*} } @{$rules_ref};
2304      if (@d) {
2305          $discount = $d[0]->{rentaldiscount};
2306          return (defined $discount) ? $discount : 0;
2307      }
2308 +
2309      # so all and all (surely we wont get here)
2310      @d = grep { $_->{branchcode} eq q{*} && $_->{itemtype} eq q{*} } @{$rules_ref};
2311      if (@d) {
2312          $discount = $d[0]->{rentaldiscount};
2313          return (defined $discount) ? $discount : 0;
2314      }
2315 +
2316      # none of the above
2317      return 0;
2318  }
2319 @@ -2441,12 +2443,12 @@ sub _get_discount_from_rule {
2320  =cut
2321  
2322  sub AddIssuingCharge {
2323 -    my ( $itemnumber, $borrowernumber, $charge ) = @_;
2324 -    my $dbh = C4::Context->dbh;
2325 -    my $nextaccntno = getnextacctno( $borrowernumber );
2326 -    my $manager_id = 0;
2327 +    my ($itemnumber, $borrowernumber, $charge) = @_;
2328 +    my $dbh         = C4::Context->dbh;
2329 +    my $nextaccntno = getnextacctno($borrowernumber);
2330 +    my $manager_id  = 0;
2331      $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
2332 -    my $query ="
2333 +    my $query = "
2334          INSERT INTO accountlines
2335              (borrowernumber, itemnumber, accountno,
2336              date, amount, description, accounttype,
2337 @@ -2454,7 +2456,7 @@ sub AddIssuingCharge {
2338          VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?,?)
2339      ";
2340      my $sth = $dbh->prepare($query);
2341 -    $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge, $manager_id );
2342 +    $sth->execute($borrowernumber, $itemnumber, $nextaccntno, $charge, $charge, $manager_id);
2343      $sth->finish;
2344  }
2345  
2346 @@ -2493,8 +2495,8 @@ Returns the list of pending transfers between $from and $to branch
2347  =cut
2348  
2349  sub GetTransfersFromTo {
2350 -    my ( $frombranch, $tobranch ) = @_;
2351 -    return unless ( $frombranch && $tobranch );
2352 +    my ($frombranch, $tobranch) = @_;
2353 +    return unless ($frombranch && $tobranch);
2354      my $dbh   = C4::Context->dbh;
2355      my $query = "
2356          SELECT itemnumber,datesent,frombranch
2357 @@ -2504,10 +2506,10 @@ sub GetTransfersFromTo {
2358            AND datearrived IS NULL
2359      ";
2360      my $sth = $dbh->prepare($query);
2361 -    $sth->execute( $frombranch, $tobranch );
2362 +    $sth->execute($frombranch, $tobranch);
2363      my @gettransfers;
2364  
2365 -    while ( my $data = $sth->fetchrow_hashref ) {
2366 +    while (my $data = $sth->fetchrow_hashref) {
2367          push @gettransfers, $data;
2368      }
2369      $sth->finish;
2370 @@ -2522,12 +2524,12 @@ sub GetTransfersFromTo {
2371  
2372  sub DeleteTransfer {
2373      my ($itemnumber) = @_;
2374 -    my $dbh          = C4::Context->dbh;
2375 -    my $sth          = $dbh->prepare(
2376 +    my $dbh = C4::Context->dbh;
2377 +    my $sth = $dbh->prepare(
2378          "DELETE FROM branchtransfers
2379           WHERE itemnumber=?
2380           AND datearrived IS NULL "
2381 -    );
2382 +                           );
2383      $sth->execute($itemnumber);
2384      $sth->finish;
2385  }
2386 @@ -2562,14 +2564,14 @@ sub AnonymiseIssueHistory {
2387      my $anonymouspatron = (C4::Context->preference('AnonymousPatron')) ? C4::Context->preference('AnonymousPatron') : 0;
2388      my @bind_params = ($anonymouspatron, $date);
2389      if (defined $borrowernumber) {
2390 -       $query .= " AND borrowernumber = ?";
2391 -       push @bind_params, $borrowernumber;
2392 +        $query .= " AND borrowernumber = ?";
2393 +        push @bind_params, $borrowernumber;
2394      } else {
2395 -       $query .= " AND (SELECT privacy FROM borrowers WHERE borrowers.borrowernumber=old_issues.borrowernumber) <> 0";
2396 +        $query .= " AND (SELECT privacy FROM borrowers WHERE borrowers.borrowernumber=old_issues.borrowernumber) <> 0";
2397      }
2398      my $sth = $dbh->prepare($query);
2399      $sth->execute(@bind_params);
2400 -    my $rows_affected = $sth->rows;  ### doublecheck row count return function
2401 +    my $rows_affected = $sth->rows;    ### doublecheck row count return function
2402      return $rows_affected;
2403  }
2404  
2405 @@ -2612,30 +2614,32 @@ B<Example>:
2406  
2407  sub SendCirculationAlert {
2408      my ($opts) = @_;
2409 -    my ($type, $item, $borrower, $branch) =
2410 -        ($opts->{type}, $opts->{item}, $opts->{borrower}, $opts->{branch});
2411 -    my %message_name = (
2412 -        CHECKIN  => 'Item_Check_in',
2413 -        CHECKOUT => 'Item_Checkout',
2414 -    );
2415 -    my $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences({
2416 -        borrowernumber => $borrower->{borrowernumber},
2417 -        message_name   => $message_name{$type},
2418 -    });
2419 +    my ($type, $item, $borrower, $branch) = ($opts->{type}, $opts->{item}, $opts->{borrower}, $opts->{branch});
2420 +    my %message_name = (CHECKIN  => 'Item_Check_in',
2421 +                        CHECKOUT => 'Item_Checkout',);
2422 +    my $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences(
2423 +                                                                               {borrowernumber => $borrower->{borrowernumber},
2424 +                                                                                message_name   => $message_name{$type},
2425 +                                                                               }
2426 +                                                                              );
2427      my $letter = C4::Letters::getletter('circulation', $type);
2428      C4::Letters::parseletter($letter, 'biblio',      $item->{biblionumber});
2429      C4::Letters::parseletter($letter, 'biblioitems', $item->{biblionumber});
2430      C4::Letters::parseletter($letter, 'borrowers',   $borrower->{borrowernumber});
2431      C4::Letters::parseletter($letter, 'branches',    $branch);
2432 -    my @transports = @{ $borrower_preferences->{transports} };
2433 +    my @transports = @{$borrower_preferences->{transports}};
2434 +
2435      # warn "no transports" unless @transports;
2436      for (@transports) {
2437 +
2438          # warn "transport: $_";
2439          my $message = C4::Message->find_last_message($borrower, $type, $_);
2440          if (!$message) {
2441 +
2442              #warn "create new message";
2443              C4::Message->enqueue($letter, $borrower, $_);
2444          } else {
2445 +
2446              #warn "append to old message";
2447              $message->append($letter);
2448              $message->update;
2449 @@ -2653,21 +2657,19 @@ This function validate the line of brachtransfer but with the wrong destination
2450  =cut
2451  
2452  sub updateWrongTransfer {
2453 -       my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
2454 -       my $dbh = C4::Context->dbh;     
2455 -# first step validate the actual line of transfert .
2456 -       my $sth =
2457 -               $dbh->prepare(
2458 -                       "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
2459 -               );
2460 -               $sth->execute($FromLibrary,$itemNumber);
2461 -               $sth->finish;
2462 -
2463 -# second step create a new line of branchtransfer to the right location .
2464 -       ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
2465 -
2466 -#third step changing holdingbranch of item
2467 -       UpdateHoldingbranch($FromLibrary,$itemNumber);
2468 +    my ($itemNumber, $waitingAtLibrary, $FromLibrary) = @_;
2469 +    my $dbh = C4::Context->dbh;
2470 +
2471 +    # first step validate the actual line of transfert .
2472 +    my $sth = $dbh->prepare("update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL");
2473 +    $sth->execute($FromLibrary, $itemNumber);
2474 +    $sth->finish;
2475 +
2476 +    # second step create a new line of branchtransfer to the right location .
2477 +    ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
2478 +
2479 +    #third step changing holdingbranch of item
2480 +    UpdateHoldingbranch($FromLibrary, $itemNumber);
2481  }
2482  
2483  =head2 UpdateHoldingbranch
2484 @@ -2679,8 +2681,8 @@ Simple methode for updating hodlingbranch in items BDD line
2485  =cut
2486  
2487  sub UpdateHoldingbranch {
2488 -       my ( $branch,$itemnumber ) = @_;
2489 -    ModItem({ holdingbranch => $branch }, undef, $itemnumber);
2490 +    my ($branch, $itemnumber) = @_;
2491 +    ModItem({holdingbranch => $branch}, undef, $itemnumber);
2492  }
2493  
2494  =head2 CalcDateDue
2495 @@ -2696,50 +2698,56 @@ C<$borrower> = Borrower object
2496  
2497  =cut
2498  
2499 -sub CalcDateDue { 
2500 -       my ($startdate,$itemtype,$branch,$borrower) = @_;
2501 -       my $datedue;
2502 -        my $loanlength = GetLoanLength($borrower->{'categorycode'},$itemtype, $branch);
2503 -
2504 -       # if globalDueDate ON the datedue is set to that date
2505 -       if ( C4::Context->preference('globalDueDate')
2506 -             && ( C4::Context->preference('globalDueDate') =~ C4::Dates->regexp('syspref') ) ) {
2507 -            $datedue = C4::Dates->new( C4::Context->preference('globalDueDate') );
2508 -       } else {
2509 -       # otherwise, calculate the datedue as normal
2510 -               if(C4::Context->preference('useDaysMode') eq 'Days') {  # ignoring calendar
2511 -                       my $timedue = time + ($loanlength) * 86400;
2512 -               #FIXME - assumes now even though we take a startdate 
2513 -                       my @datearr  = localtime($timedue);
2514 -                       $datedue = C4::Dates->new( sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
2515 -               } else {
2516 -                       my $calendar = C4::Calendar->new(  branchcode => $branch );
2517 -                       $datedue = $calendar->addDate($startdate, $loanlength);
2518 -               }
2519 -       }
2520 -
2521 -       # if Hard Due Dates are used, retreive them and apply as necessary
2522 -        my ($hardduedate, $hardduedatecompare) = GetHardDueDate($borrower->{'categorycode'},$itemtype, $branch);
2523 -       if ( $hardduedate && $hardduedate->output('iso') && $hardduedate->output('iso') ne '0000-00-00') {
2524 -            # if the calculated due date is after the 'before' Hard Due Date (ceiling), override
2525 -            if ( $datedue->output( 'iso' ) gt $hardduedate->output( 'iso' ) && $hardduedatecompare == -1) {
2526 -                $datedue = $hardduedate;
2527 +sub CalcDateDue {
2528 +    my ($startdate, $itemtype, $branch, $borrower) = @_;
2529 +    my $datedue;
2530 +    my $loanlength = GetLoanLength($borrower->{'categorycode'}, $itemtype, $branch);
2531 +
2532 +    # if globalDueDate ON the datedue is set to that date
2533 +    if (C4::Context->preference('globalDueDate')
2534 +        && (C4::Context->preference('globalDueDate') =~ C4::Dates->regexp('syspref'))) {
2535 +        $datedue = C4::Dates->new(C4::Context->preference('globalDueDate'));
2536 +    } else {
2537 +
2538 +        # otherwise, calculate the datedue as normal
2539 +        if (C4::Context->preference('useDaysMode') eq 'Days') {    # ignoring calendar
2540 +            my $timedue = time + ($loanlength) * 86400;
2541 +
2542 +            #FIXME - assumes now even though we take a startdate
2543 +            my @datearr = localtime($timedue);
2544 +            $datedue = C4::Dates->new(sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
2545 +        } else {
2546 +            my $calendar = C4::Calendar->new(branchcode => $branch);
2547 +            $datedue = $calendar->addDate($startdate, $loanlength);
2548 +        }
2549 +    }
2550 +
2551 +    # if Hard Due Dates are used, retreive them and apply as necessary
2552 +    my ($hardduedate, $hardduedatecompare) = GetHardDueDate($borrower->{'categorycode'}, $itemtype, $branch);
2553 +    if ($hardduedate && $hardduedate->output('iso') && $hardduedate->output('iso') ne '0000-00-00') {
2554 +
2555 +        # if the calculated due date is after the 'before' Hard Due Date (ceiling), override
2556 +        if ($datedue->output('iso') gt $hardduedate->output('iso') && $hardduedatecompare == -1) {
2557 +            $datedue = $hardduedate;
2558 +
2559              # if the calculated date is before the 'after' Hard Due Date (floor), override
2560 -            } elsif ( $datedue->output( 'iso' ) lt $hardduedate->output( 'iso' ) && $hardduedatecompare == 1) {
2561 -                $datedue = $hardduedate;               
2562 +        } elsif ($datedue->output('iso') lt $hardduedate->output('iso') && $hardduedatecompare == 1) {
2563 +            $datedue = $hardduedate;
2564 +
2565              # if the hard due date is set to 'exactly', overrride
2566 -            } elsif ( $hardduedatecompare == 0) {
2567 -                $datedue = $hardduedate;
2568 -            }
2569 -            # in all other cases, keep the date due as it is
2570 -       }
2571 +        } elsif ($hardduedatecompare == 0) {
2572 +            $datedue = $hardduedate;
2573 +        }
2574  
2575 -       # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
2576 -       if ( C4::Context->preference('ReturnBeforeExpiry') && $datedue->output('iso') gt $borrower->{dateexpiry} ) {
2577 -           $datedue = C4::Dates->new( $borrower->{dateexpiry}, 'iso' );
2578 -       }
2579 +        # in all other cases, keep the date due as it is
2580 +    }
2581  
2582 -       return $datedue;
2583 +    # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
2584 +    if (C4::Context->preference('ReturnBeforeExpiry') && $datedue->output('iso') gt $borrower->{dateexpiry}) {
2585 +        $datedue = C4::Dates->new($borrower->{dateexpiry}, 'iso');
2586 +    }
2587 +
2588 +    return $datedue;
2589  }
2590  
2591  =head2 CheckValidDatedue
2592 @@ -2758,29 +2766,29 @@ C<$loanlength>  = loan length prior to adjustment
2593  =cut
2594  
2595  sub CheckValidDatedue {
2596 -my ($date_due,$itemnumber,$branchcode)=@_;
2597 -my @datedue=split('-',$date_due->output('iso'));
2598 -my $years=$datedue[0];
2599 -my $month=$datedue[1];
2600 -my $day=$datedue[2];
2601 -# die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
2602 -my $dow;
2603 -for (my $i=0;$i<2;$i++){
2604 -    $dow=Day_of_Week($years,$month,$day);
2605 -    ($dow=0) if ($dow>6);
2606 -    my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
2607 -    my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2608 -    my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2609 -        if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
2610 -        $i=0;
2611 -        (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
2612 +    my ($date_due, $itemnumber, $branchcode) = @_;
2613 +    my @datedue = split('-', $date_due->output('iso'));
2614 +    my $years   = $datedue[0];
2615 +    my $month   = $datedue[1];
2616 +    my $day     = $datedue[2];
2617 +
2618 +    # die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
2619 +    my $dow;
2620 +    for (my $i = 0 ; $i < 2 ; $i++) {
2621 +        $dow = Day_of_Week($years, $month, $day);
2622 +        ($dow = 0) if ($dow > 6);
2623 +        my $result = CheckRepeatableHolidays($itemnumber, $dow, $branchcode);
2624 +        my $countspecial = CheckSpecialHolidays($years, $month, $day, $itemnumber, $branchcode);
2625 +        my $countspecialrepeatable = CheckRepeatableSpecialHolidays($month, $day, $itemnumber, $branchcode);
2626 +        if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0')) {
2627 +            $i = 0;
2628 +            (($years, $month, $day) = Add_Delta_Days($years, $month, $day, 1)) if ($i ne '1');
2629          }
2630      }
2631 -    my $newdatedue=C4::Dates->new(sprintf("%04d-%02d-%02d",$years,$month,$day),'iso');
2632 -return $newdatedue;
2633 +    my $newdatedue = C4::Dates->new(sprintf("%04d-%02d-%02d", $years, $month, $day), 'iso');
2634 +    return $newdatedue;
2635  }
2636  
2637 -
2638  =head2 CheckRepeatableHolidays
2639  
2640    $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
2641 @@ -2793,21 +2801,20 @@ C<$branchcode>  = localisation of issue
2642  
2643  =cut
2644  
2645 -sub CheckRepeatableHolidays{
2646 -my($itemnumber,$week_day,$branchcode)=@_;
2647 -my $dbh = C4::Context->dbh;
2648 -my $query = qq|SELECT count(*)  
2649 +sub CheckRepeatableHolidays {
2650 +    my ($itemnumber, $week_day, $branchcode) = @_;
2651 +    my $dbh   = C4::Context->dbh;
2652 +    my $query = qq|SELECT count(*)  
2653         FROM repeatable_holidays 
2654         WHERE branchcode=?
2655         AND weekday=?|;
2656 -my $sth = $dbh->prepare($query);
2657 -$sth->execute($branchcode,$week_day);
2658 -my $result=$sth->fetchrow;
2659 -$sth->finish;
2660 -return $result;
2661 +    my $sth = $dbh->prepare($query);
2662 +    $sth->execute($branchcode, $week_day);
2663 +    my $result = $sth->fetchrow;
2664 +    $sth->finish;
2665 +    return $result;
2666  }
2667  
2668 -
2669  =head2 CheckSpecialHolidays
2670  
2671    $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2672 @@ -2822,21 +2829,21 @@ C<$branchcode>  = localisation of issue
2673  
2674  =cut
2675  
2676 -sub CheckSpecialHolidays{
2677 -my ($years,$month,$day,$itemnumber,$branchcode) = @_;
2678 -my $dbh = C4::Context->dbh;
2679 -my $query=qq|SELECT count(*) 
2680 +sub CheckSpecialHolidays {
2681 +    my ($years, $month, $day, $itemnumber, $branchcode) = @_;
2682 +    my $dbh   = C4::Context->dbh;
2683 +    my $query = qq|SELECT count(*) 
2684              FROM `special_holidays`
2685              WHERE year=?
2686              AND month=?
2687              AND day=?
2688               AND branchcode=?
2689             |;
2690 -my $sth = $dbh->prepare($query);
2691 -$sth->execute($years,$month,$day,$branchcode);
2692 -my $countspecial=$sth->fetchrow ;
2693 -$sth->finish;
2694 -return $countspecial;
2695 +    my $sth = $dbh->prepare($query);
2696 +    $sth->execute($years, $month, $day, $branchcode);
2697 +    my $countspecial = $sth->fetchrow;
2698 +    $sth->finish;
2699 +    return $countspecial;
2700  }
2701  
2702  =head2 CheckRepeatableSpecialHolidays
2703 @@ -2852,36 +2859,34 @@ C<$branchcode>  = localisation of issue
2704  
2705  =cut
2706  
2707 -sub CheckRepeatableSpecialHolidays{
2708 -my ($month,$day,$itemnumber,$branchcode) = @_;
2709 -my $dbh = C4::Context->dbh;
2710 -my $query=qq|SELECT count(*) 
2711 +sub CheckRepeatableSpecialHolidays {
2712 +    my ($month, $day, $itemnumber, $branchcode) = @_;
2713 +    my $dbh   = C4::Context->dbh;
2714 +    my $query = qq|SELECT count(*) 
2715              FROM `repeatable_holidays`
2716              WHERE month=?
2717              AND day=?
2718               AND branchcode=?
2719             |;
2720 -my $sth = $dbh->prepare($query);
2721 -$sth->execute($month,$day,$branchcode);
2722 -my $countspecial=$sth->fetchrow ;
2723 -$sth->finish;
2724 -return $countspecial;
2725 +    my $sth = $dbh->prepare($query);
2726 +    $sth->execute($month, $day, $branchcode);
2727 +    my $countspecial = $sth->fetchrow;
2728 +    $sth->finish;
2729 +    return $countspecial;
2730  }
2731  
2732 -
2733 -
2734 -sub CheckValidBarcode{
2735 -my ($barcode) = @_;
2736 -my $dbh = C4::Context->dbh;
2737 -my $query=qq|SELECT count(*) 
2738 +sub CheckValidBarcode {
2739 +    my ($barcode) = @_;
2740 +    my $dbh       = C4::Context->dbh;
2741 +    my $query     = qq|SELECT count(*) 
2742              FROM items 
2743               WHERE barcode=?
2744             |;
2745 -my $sth = $dbh->prepare($query);
2746 -$sth->execute($barcode);
2747 -my $exist=$sth->fetchrow ;
2748 -$sth->finish;
2749 -return $exist;
2750 +    my $sth = $dbh->prepare($query);
2751 +    $sth->execute($barcode);
2752 +    my $exist = $sth->fetchrow;
2753 +    $sth->finish;
2754 +    return $exist;
2755  }
2756  
2757  =head2 IsBranchTransferAllowed
2758 @@ -2893,24 +2898,24 @@ Code is either an itemtype or collection doe depending on the pref BranchTransfe
2759  =cut
2760  
2761  sub IsBranchTransferAllowed {
2762 -       my ( $toBranch, $fromBranch, $code ) = @_;
2763 -
2764 -       if ( $toBranch eq $fromBranch ) { return 1; } ## Short circuit for speed.
2765 -        
2766 -       my $limitType = C4::Context->preference("BranchTransferLimitsType");   
2767 -       my $dbh = C4::Context->dbh;
2768 -            
2769 -       my $sth = $dbh->prepare("SELECT * FROM branch_transfer_limits WHERE toBranch = ? AND fromBranch = ? AND $limitType = ?");
2770 -       $sth->execute( $toBranch, $fromBranch, $code );
2771 -       my $limit = $sth->fetchrow_hashref();
2772 -                        
2773 -       ## If a row is found, then that combination is not allowed, if no matching row is found, then the combination *is allowed*
2774 -       if ( $limit->{'limitId'} ) {
2775 -               return 0;
2776 -       } else {
2777 -               return 1;
2778 -       }
2779 -}                                                        
2780 +    my ($toBranch, $fromBranch, $code) = @_;
2781 +
2782 +    if ($toBranch eq $fromBranch) { return 1; }    ## Short circuit for speed.
2783 +
2784 +    my $limitType = C4::Context->preference("BranchTransferLimitsType");
2785 +    my $dbh       = C4::Context->dbh;
2786 +
2787 +    my $sth = $dbh->prepare("SELECT * FROM branch_transfer_limits WHERE toBranch = ? AND fromBranch = ? AND $limitType = ?");
2788 +    $sth->execute($toBranch, $fromBranch, $code);
2789 +    my $limit = $sth->fetchrow_hashref();
2790 +
2791 +    ## If a row is found, then that combination is not allowed, if no matching row is found, then the combination *is allowed*
2792 +    if ($limit->{'limitId'}) {
2793 +        return 0;
2794 +    } else {
2795 +        return 1;
2796 +    }
2797 +}
2798  
2799  =head2 CreateBranchTransferLimit
2800  
2801 @@ -2921,14 +2926,14 @@ $code is either itemtype or collection code depending on what the pref BranchTra
2802  =cut
2803  
2804  sub CreateBranchTransferLimit {
2805 -   my ( $toBranch, $fromBranch, $code ) = @_;
2806 -
2807 -   my $limitType = C4::Context->preference("BranchTransferLimitsType");
2808 -   
2809 -   my $dbh = C4::Context->dbh;
2810 -   
2811 -   my $sth = $dbh->prepare("INSERT INTO branch_transfer_limits ( $limitType, toBranch, fromBranch ) VALUES ( ?, ?, ? )");
2812 -   $sth->execute( $code, $toBranch, $fromBranch );
2813 +    my ($toBranch, $fromBranch, $code) = @_;
2814 +
2815 +    my $limitType = C4::Context->preference("BranchTransferLimitsType");
2816 +
2817 +    my $dbh = C4::Context->dbh;
2818 +
2819 +    my $sth = $dbh->prepare("INSERT INTO branch_transfer_limits ( $limitType, toBranch, fromBranch ) VALUES ( ?, ?, ? )");
2820 +    $sth->execute($code, $toBranch, $fromBranch);
2821  }
2822  
2823  =head2 DeleteBranchTransferLimits
2824 @@ -2938,13 +2943,12 @@ sub CreateBranchTransferLimit {
2825  =cut
2826  
2827  sub DeleteBranchTransferLimits {
2828 -   my $dbh = C4::Context->dbh;
2829 -   my $sth = $dbh->prepare("TRUNCATE TABLE branch_transfer_limits");
2830 -   $sth->execute();
2831 +    my $dbh = C4::Context->dbh;
2832 +    my $sth = $dbh->prepare("TRUNCATE TABLE branch_transfer_limits");
2833 +    $sth->execute();
2834  }
2835  
2836 -
2837 -  1;
2838 +1;
2839  
2840  __END__
2841  
2842 diff --git a/Circulation.pm.koha-style b/Circulation.pm.koha-style
2843 index 520c116..d85534c 100644
2844 --- a/Circulation.pm.koha-style
2845 +++ b/Circulation.pm.koha-style
2846 @@ -18,8 +18,8 @@ package C4::Circulation;
2847  # with Koha; if not, write to the Free Software Foundation, Inc.,
2848  # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
2849  
2850 -
2851  use strict;
2852 +
2853  #use warnings; FIXME - Bug 2505
2854  use C4::Context;
2855  use C4::Stats;
2856 @@ -42,63 +42,63 @@ use Date::Calc qw(
2857    Add_Delta_DHMS
2858    Date_to_Days
2859    Day_of_Week
2860 -  Add_Delta_Days       
2861 +  Add_Delta_Days
2862  );
2863  use POSIX qw(strftime);
2864 -use C4::Branch; # GetBranches
2865 -use C4::Log; # logaction
2866 +use C4::Branch;    # GetBranches
2867 +use C4::Log;       # logaction
2868  
2869  use Data::Dumper;
2870  
2871  use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
2872  
2873  BEGIN {
2874 -       require Exporter;
2875 -       $VERSION = 3.02;        # for version checking
2876 -       @ISA    = qw(Exporter);
2877 -
2878 -       # FIXME subs that should probably be elsewhere
2879 -       push @EXPORT, qw(
2880 -               &FixOverduesOnReturn
2881 -               &barcodedecode
2882 -       );
2883 -
2884 -       # subs to deal with issuing a book
2885 -       push @EXPORT, qw(
2886 -               &CanBookBeIssued
2887 -               &CanBookBeRenewed
2888 -               &AddIssue
2889 -               &AddRenewal
2890 -               &GetRenewCount
2891 -               &GetItemIssue
2892 -               &GetItemIssues
2893 -               &GetBorrowerIssues
2894 -               &GetIssuingCharges
2895 -               &GetIssuingRule
2896 -        &GetBranchBorrowerCircRule
2897 -        &GetBranchItemRule
2898 -               &GetBiblioIssues
2899 -               &GetOpenIssue
2900 -               &AnonymiseIssueHistory
2901 -       );
2902 -
2903 -       # subs to deal with returns
2904 -       push @EXPORT, qw(
2905 -               &AddReturn
2906 -        &MarkIssueReturned
2907 -       );
2908 -
2909 -       # subs to deal with transfers
2910 -       push @EXPORT, qw(
2911 -               &transferbook
2912 -               &GetTransfers
2913 -               &GetTransfersFromTo
2914 -               &updateWrongTransfer
2915 -               &DeleteTransfer
2916 -                &IsBranchTransferAllowed
2917 -                &CreateBranchTransferLimit
2918 -                &DeleteBranchTransferLimits
2919 -       );
2920 +    require Exporter;
2921 +    $VERSION = 3.02;           # for version checking
2922 +    @ISA     = qw(Exporter);
2923 +
2924 +    # FIXME subs that should probably be elsewhere
2925 +    push @EXPORT, qw(
2926 +      &FixOverduesOnReturn
2927 +      &barcodedecode
2928 +    );
2929 +
2930 +    # subs to deal with issuing a book
2931 +    push @EXPORT, qw(
2932 +      &CanBookBeIssued
2933 +      &CanBookBeRenewed
2934 +      &AddIssue
2935 +      &AddRenewal
2936 +      &GetRenewCount
2937 +      &GetItemIssue
2938 +      &GetItemIssues
2939 +      &GetBorrowerIssues
2940 +      &GetIssuingCharges
2941 +      &GetIssuingRule
2942 +      &GetBranchBorrowerCircRule
2943 +      &GetBranchItemRule
2944 +      &GetBiblioIssues
2945 +      &GetOpenIssue
2946 +      &AnonymiseIssueHistory
2947 +    );
2948 +
2949 +    # subs to deal with returns
2950 +    push @EXPORT, qw(
2951 +      &AddReturn
2952 +      &MarkIssueReturned
2953 +    );
2954 +
2955 +    # subs to deal with transfers
2956 +    push @EXPORT, qw(
2957 +      &transferbook
2958 +      &GetTransfers
2959 +      &GetTransfersFromTo
2960 +      &updateWrongTransfer
2961 +      &DeleteTransfer
2962 +      &IsBranchTransferAllowed
2963 +      &CreateBranchTransferLimit
2964 +      &DeleteBranchTransferLimits
2965 +    );
2966  }
2967  
2968  =head1 NAME
2969 @@ -138,36 +138,37 @@ System Pref options.
2970  # FIXME -- these plugins should be moved out of Circulation.pm
2971  #
2972  sub barcodedecode {
2973 -    my ($barcode, $filter) = @_;
2974 +    my ( $barcode, $filter ) = @_;
2975      my $branch = C4::Branch::mybranch();
2976      $filter = C4::Context->preference('itemBarcodeInputFilter') unless $filter;
2977 -    $filter or return $barcode;     # ensure filter is defined, else return untouched barcode
2978 -       if ($filter eq 'whitespace') {
2979 -               $barcode =~ s/\s//g;
2980 -       } elsif ($filter eq '