View | Details | Raw Unified | Return to bug 6427
Collapse All | Expand All

(-)a/C4/Circulation.pm (-179 / +167 lines)
Lines 30-36 use C4::Items; Link Here
30
use C4::Members;
30
use C4::Members;
31
use C4::Dates;
31
use C4::Dates;
32
use C4::Dates qw(format_date);
32
use C4::Dates qw(format_date);
33
use C4::Accounts;
33
use Koha::Accounts;
34
use C4::ItemCirculationAlertPreference;
34
use C4::ItemCirculationAlertPreference;
35
use C4::Message;
35
use C4::Message;
36
use C4::Debug;
36
use C4::Debug;
Lines 48-53 use Data::Dumper; Link Here
48
use Koha::DateUtils;
48
use Koha::DateUtils;
49
use Koha::Calendar;
49
use Koha::Calendar;
50
use Koha::Borrower::Debarments;
50
use Koha::Borrower::Debarments;
51
use Koha::Database;
51
use Carp;
52
use Carp;
52
use Date::Calc qw(
53
use Date::Calc qw(
53
  Today
54
  Today
Lines 1273-1279 sub AddIssue { Link Here
1273
        ## If item was lost, it has now been found, reverse any list item charges if neccessary.
1274
        ## If item was lost, it has now been found, reverse any list item charges if neccessary.
1274
        if ( $item->{'itemlost'} ) {
1275
        if ( $item->{'itemlost'} ) {
1275
            if ( C4::Context->preference('RefundLostItemFeeOnReturn' ) ) {
1276
            if ( C4::Context->preference('RefundLostItemFeeOnReturn' ) ) {
1276
                _FixAccountForLostAndReturned( $item->{'itemnumber'}, undef, $item->{'barcode'} );
1277
                _FixAccountForLostAndReturned( $item->{'itemnumber'} );
1277
            }
1278
            }
1278
        }
1279
        }
1279
1280
Lines 1834-1854 sub AddReturn { Link Here
1834
1835
1835
                $type ||= q{};
1836
                $type ||= q{};
1836
1837
1837
                if ( C4::Context->preference('finesMode') eq 'production' ) {
1838
                if ( $amount > 0
1838
                    if ( $amount > 0 ) {
1839
                    && C4::Context->preference('finesMode') eq 'production' )
1839
                        C4::Overdues::UpdateFine( $issue->{itemnumber},
1840
                {
1840
                            $issue->{borrowernumber},
1841
                    C4::Overdues::UpdateFine(
1841
                            $amount, $type, output_pref($datedue) );
1842
                        {
1842
                    }
1843
                            itemnumber     => $issue->{itemnumber},
1843
                    elsif ($return_date) {
1844
                            borrowernumber => $issue->{borrowernumber},
1844
1845
                            amount         => $amount,
1845
                       # Backdated returns may have fines that shouldn't exist,
1846
                            due            => output_pref($datedue),
1846
                       # so in this case, we need to drop those fines to 0
1847
                            issue_id       => $issue->{issue_id}
1847
1848
                        }
1848
                        C4::Overdues::UpdateFine( $issue->{itemnumber},
1849
                    );
1849
                            $issue->{borrowernumber},
1850
                }
1850
                            0, $type, output_pref($datedue) );
1851
                elsif ($return_date) {
1851
                    }
1852
1853
                    # Backdated returns may have fines that shouldn't exist,
1854
                    # so in this case, we need to drop those fines to 0
1855
                    C4::Overdues::UpdateFine(
1856
                        {
1857
                            itemnumber     => $issue->{itemnumber},
1858
                            borrowernumber => $issue->{borrowernumber},
1859
                            amount         => 0,
1860
                            due            => output_pref($datedue),
1861
                            issue_id       => $issue->{issue_id}
1862
                        }
1863
                    );
1852
                }
1864
                }
1853
            }
1865
            }
1854
1866
Lines 1898-1912 sub AddReturn { Link Here
1898
        $messages->{'WasLost'} = 1;
1910
        $messages->{'WasLost'} = 1;
1899
1911
1900
        if ( C4::Context->preference('RefundLostItemFeeOnReturn' ) ) {
1912
        if ( C4::Context->preference('RefundLostItemFeeOnReturn' ) ) {
1901
            _FixAccountForLostAndReturned($item->{'itemnumber'}, $borrowernumber, $barcode);    # can tolerate undef $borrowernumber
1913
            _FixAccountForLostAndReturned( $item->{'itemnumber'} );
1902
            $messages->{'LostItemFeeRefunded'} = 1;
1914
            $messages->{'LostItemFeeRefunded'} = 1;
1903
        }
1915
        }
1904
    }
1916
    }
1905
1917
1906
    # fix up the overdues in accounts...
1918
    # fix up the overdues in accounts...
1907
    if ($borrowernumber) {
1919
    if ($borrowernumber) {
1908
        my $fix = _FixOverduesOnReturn($borrowernumber, $item->{itemnumber}, $exemptfine, $dropbox);
1920
        _FixOverduesOnReturn(
1909
        defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $item->{itemnumber}...) failed!";  # zero is OK, check defined
1921
            {
1922
                exempt_fine => $exemptfine,
1923
                dropbox     => $dropbox,
1924
                issue       => $issue,
1925
            }
1926
        );
1910
        
1927
        
1911
        if ( $issue->{overdue} && $issue->{date_due} ) {
1928
        if ( $issue->{overdue} && $issue->{date_due} ) {
1912
        # fix fine days
1929
        # fix fine days
Lines 2152-2290 Internal function, called only by AddReturn Link Here
2152
=cut
2169
=cut
2153
2170
2154
sub _FixOverduesOnReturn {
2171
sub _FixOverduesOnReturn {
2155
    my ($borrowernumber, $item);
2172
    my ( $params ) = @_;
2156
    unless ($borrowernumber = shift) {
2173
2157
        warn "_FixOverduesOnReturn() not supplied valid borrowernumber";
2174
    my $exemptfine = $params->{exempt_fine};
2158
        return;
2175
    my $dropbox    = $params->{dropbox};
2159
    }
2176
    my $issue      = $params->{issue};
2160
    unless ($item = shift) {
2177
2161
        warn "_FixOverduesOnReturn() not supplied valid itemnumber";
2162
        return;
2163
    }
2164
    my ($exemptfine, $dropbox) = @_;
2165
    my $dbh = C4::Context->dbh;
2178
    my $dbh = C4::Context->dbh;
2166
2179
2167
    # check for overdue fine
2180
    my $schema = Koha::Database->new()->schema;
2168
    my $sth = $dbh->prepare(
2181
    my $fine =
2169
"SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
2182
      $schema->resultset('AccountDebit')
2170
    );
2183
      ->single( { issue_id => $issue->{issue_id}, type => Koha::Accounts::DebitTypes::Fine() } );
2171
    $sth->execute( $borrowernumber, $item );
2172
2184
2173
    # alter fine to show that the book has been returned
2185
    return unless ( $fine );
2174
    my $data = $sth->fetchrow_hashref;
2186
2175
    return 0 unless $data;    # no warning, there's just nothing to fix
2187
    $fine->accruing(0);
2176
2188
2177
    my $uquery;
2178
    my @bind = ($data->{'accountlines_id'});
2179
    if ($exemptfine) {
2189
    if ($exemptfine) {
2180
        $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
2190
        AddCredit(
2181
        if (C4::Context->preference("FinesLog")) {
2191
            {
2182
            &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
2192
                borrower => $fine->borrowernumber(),
2183
        }
2193
                amount   => $fine->amount_original(),
2184
    } elsif ($dropbox && $data->{lastincrement}) {
2194
                debit_id => $fine->debit_id(),
2185
        my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
2195
                type     => Koha::Accounts::CreditTypes::Forgiven(),
2186
        my $amt = $data->{amount} - $data->{lastincrement} ;
2196
            }
2197
        );
2187
        if (C4::Context->preference("FinesLog")) {
2198
        if (C4::Context->preference("FinesLog")) {
2188
            &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
2199
            &logaction(
2189
        }
2200
                "FINES", 'MODIFY',
2190
         $uquery = "update accountlines set accounttype='F' ";
2201
                $issue->{borrowernumber},
2191
         if($outstanding  >= 0 && $amt >=0) {
2202
                "Overdue forgiven: item " . $issue->{itemnumber}
2192
            $uquery .= ", amount = ? , amountoutstanding=? ";
2203
            );
2193
            unshift @bind, ($amt, $outstanding) ;
2194
        }
2204
        }
2195
    } else {
2205
    } elsif ($dropbox && $fine->amount_last_increment() != $fine->amount_original() ) {
2196
        $uquery = "update accountlines set accounttype='F' ";
2206
        if ( C4::Context->preference("FinesLog") ) {
2207
            &logaction( "FINES", 'MODIFY', $issue->{borrowernumber},
2208
                    "Dropbox adjustment "
2209
                  . $fine->amount_last_increment()
2210
                  . ", item " . $issue->{itemnumber} );
2211
        }
2212
        $fine->amount_original(
2213
            $fine->amount_original() - $fine->amount_last_increment() );
2214
        $fine->amount_outstanding(
2215
            $fine->amount_outstanding - $fine->amount_last_increment() );
2216
        $schema->resultset('AccountOffset')->create(
2217
            {
2218
                debit_id => $fine->debit_id(),
2219
                type     => Koha::Accounts::OffsetTypes::Dropbox(),
2220
                amount   => $fine->amount_last_increment() * -1,
2221
            }
2222
        );
2197
    }
2223
    }
2198
    $uquery .= " where (accountlines_id = ?)";
2224
2199
    my $usth = $dbh->prepare($uquery);
2225
    return $fine->update();
2200
    return $usth->execute(@bind);
2201
}
2226
}
2202
2227
2203
=head2 _FixAccountForLostAndReturned
2228
=head2 _FixAccountForLostAndReturned
2204
2229
2205
  &_FixAccountForLostAndReturned($itemnumber, [$borrowernumber, $barcode]);
2230
  &_FixAccountForLostAndReturned($itemnumber);
2206
2231
2207
Calculates the charge for a book lost and returned.
2232
  Refunds a lost item fee in necessary
2208
2209
Internal function, not exported, called only by AddReturn.
2210
2211
FIXME: This function reflects how inscrutable fines logic is.  Fix both.
2212
FIXME: Give a positive return value on success.  It might be the $borrowernumber who received credit, or the amount forgiven.
2213
2233
2214
=cut
2234
=cut
2215
2235
2216
sub _FixAccountForLostAndReturned {
2236
sub _FixAccountForLostAndReturned {
2217
    my $itemnumber     = shift or return;
2237
    my ( $itemnumber ) = @_;
2218
    my $borrowernumber = @_ ? shift : undef;
2238
2219
    my $item_id        = @_ ? shift : $itemnumber;  # Send the barcode if you want that logged in the description
2239
    my $schema = Koha::Database->new()->schema;
2220
    my $dbh = C4::Context->dbh;
2240
2221
    # check for charge made for lost book
2241
    # Find the last issue for this item
2222
    my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE itemnumber = ? AND accounttype IN ('L', 'Rep', 'W') ORDER BY date DESC, accountno DESC");
2242
    my $issue =
2223
    $sth->execute($itemnumber);
2243
      $schema->resultset('Issue')->single( { itemnumber => $itemnumber } );
2224
    my $data = $sth->fetchrow_hashref;
2244
    $issue ||=
2225
    $data or return;    # bail if there is nothing to do
2245
      $schema->resultset('OldIssue')->single( { itemnumber => $itemnumber } );
2226
    $data->{accounttype} eq 'W' and return;    # Written off
2246
2227
2247
    return unless $issue;
2228
    # writeoff this amount
2248
2229
    my $offset;
2249
    # Find a lost fee for this issue
2230
    my $amount = $data->{'amount'};
2250
    my $debit = $schema->resultset('AccountDebit')->single(
2231
    my $acctno = $data->{'accountno'};
2251
        {
2232
    my $amountleft;                                             # Starts off undef/zero.
2252
            issue_id => $issue->issue_id(),
2233
    if ($data->{'amountoutstanding'} == $amount) {
2253
            type     => Koha::Accounts::DebitTypes::Lost()
2234
        $offset     = $data->{'amount'};
2254
        }
2235
        $amountleft = 0;                                        # Hey, it's zero here, too.
2255
    );
2236
    } else {
2256
2237
        $offset     = $amount - $data->{'amountoutstanding'};   # Um, isn't this the same as ZERO?  We just tested those two things are ==
2257
    return unless $debit;
2238
        $amountleft = $data->{'amountoutstanding'} - $amount;   # Um, isn't this the same as ZERO?  We just tested those two things are ==
2258
2239
    }
2259
    # Check for an existing found credit for this debit, if there is one, the fee has already been refunded and we do nothing
2240
    my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
2260
    my @credits = $debit->account_offsets->search_related('credit', { 'credit.type' => Koha::Accounts::CreditTypes::Found() });
2241
        WHERE (accountlines_id = ?)");
2261
2242
    $usth->execute($data->{'accountlines_id'});      # We might be adjusting an account for some OTHER borrowernumber now.  Not the one we passed in.
2262
    return if @credits;
2243
    #check if any credit is left if so writeoff other accounts
2263
2244
    my $nextaccntno = getnextacctno($data->{'borrowernumber'});
2264
    # Ok, so we know we have an unrefunded lost item fee, let's refund it
2245
    $amountleft *= -1 if ($amountleft < 0);
2265
    CreditLostItem(
2246
    if ($amountleft > 0) {
2266
        {
2247
        my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
2267
            borrower => $issue->borrower(),
2248
                            AND (amountoutstanding >0) ORDER BY date");     # might want to order by amountoustanding ASC (pay smallest first)
2268
            debit    => $debit
2249
        $msth->execute($data->{'borrowernumber'});
2269
        }
2250
        # offset transactions
2270
    );
2251
        my $newamtos;
2271
2252
        my $accdata;
2253
        while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
2254
            if ($accdata->{'amountoutstanding'} < $amountleft) {
2255
                $newamtos = 0;
2256
                $amountleft -= $accdata->{'amountoutstanding'};
2257
            }  else {
2258
                $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
2259
                $amountleft = 0;
2260
            }
2261
            my $thisacct = $accdata->{'accountlines_id'};
2262
            # FIXME: move prepares outside while loop!
2263
            my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
2264
                    WHERE (accountlines_id = ?)");
2265
            $usth->execute($newamtos,$thisacct);
2266
            $usth = $dbh->prepare("INSERT INTO accountoffsets
2267
                (borrowernumber, accountno, offsetaccount,  offsetamount)
2268
                VALUES
2269
                (?,?,?,?)");
2270
            $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
2271
        }
2272
    }
2273
    $amountleft *= -1 if ($amountleft > 0);
2274
    my $desc = "Item Returned " . $item_id;
2275
    $usth = $dbh->prepare("INSERT INTO accountlines
2276
        (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
2277
        VALUES (?,?,now(),?,?,'CR',?)");
2278
    $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
2279
    if ($borrowernumber) {
2280
        # FIXME: same as query above.  use 1 sth for both
2281
        $usth = $dbh->prepare("INSERT INTO accountoffsets
2282
            (borrowernumber, accountno, offsetaccount,  offsetamount)
2283
            VALUES (?,?,?,?)");
2284
        $usth->execute($borrowernumber, $data->{'accountno'}, $nextaccntno, $offset);
2285
    }
2286
    ModItem({ paidfor => '' }, undef, $itemnumber);
2272
    ModItem({ paidfor => '' }, undef, $itemnumber);
2287
    return;
2288
}
2273
}
2289
2274
2290
=head2 _GetCircControlBranch
2275
=head2 _GetCircControlBranch
Lines 2728-2746 sub AddRenewal { Link Here
2728
    # Charge a new rental fee, if applicable?
2713
    # Charge a new rental fee, if applicable?
2729
    my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2714
    my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2730
    if ( $charge > 0 ) {
2715
    if ( $charge > 0 ) {
2731
        my $accountno = getnextacctno( $borrowernumber );
2732
        my $item = GetBiblioFromItemNumber($itemnumber);
2716
        my $item = GetBiblioFromItemNumber($itemnumber);
2733
        my $manager_id = 0;
2717
2734
        $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv; 
2718
        my $borrower =
2735
        $sth = $dbh->prepare(
2719
          Koha::Database->new()->schema->resultset('Borrower')
2736
                "INSERT INTO accountlines
2720
          ->find($borrowernumber);
2737
                    (date, borrowernumber, accountno, amount, manager_id,
2721
2738
                    description,accounttype, amountoutstanding, itemnumber)
2722
        AddDebit(
2739
                    VALUES (now(),?,?,?,?,?,?,?,?)"
2723
            {
2724
                borrower   => $borrower,
2725
                itemnumber => $itemnumber,
2726
                amount     => $charge,
2727
                type       => Koha::Accounts::DebitTypes::Rental(),
2728
                description =>
2729
                  "Renewal of Rental Item $item->{'title'} $item->{'barcode'}"
2730
            }
2740
        );
2731
        );
2741
        $sth->execute( $borrowernumber, $accountno, $charge, $manager_id,
2742
            "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
2743
            'Rent', $charge, $itemnumber );
2744
    }
2732
    }
2745
2733
2746
    # Send a renewal slip according to checkout alert preferencei
2734
    # Send a renewal slip according to checkout alert preferencei
Lines 2959-2983 sub _get_discount_from_rule { Link Here
2959
2947
2960
=head2 AddIssuingCharge
2948
=head2 AddIssuingCharge
2961
2949
2962
  &AddIssuingCharge( $itemno, $borrowernumber, $charge )
2950
  &AddIssuingCharge( $itemnumber, $borrowernumber, $amount )
2963
2951
2964
=cut
2952
=cut
2965
2953
2966
sub AddIssuingCharge {
2954
sub AddIssuingCharge {
2967
    my ( $itemnumber, $borrowernumber, $charge ) = @_;
2955
    my ( $itemnumber, $borrowernumber, $amount ) = @_;
2968
    my $dbh = C4::Context->dbh;
2956
2969
    my $nextaccntno = getnextacctno( $borrowernumber );
2957
    return AddDebit(
2970
    my $manager_id = 0;
2958
        {
2971
    $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
2959
            borrower       => Koha::Database->new()->schema->resultset('Borrower')->find($borrowernumber),
2972
    my $query ="
2960
            itemnumber     => $itemnumber,
2973
        INSERT INTO accountlines
2961
            amount         => $amount,
2974
            (borrowernumber, itemnumber, accountno,
2962
            type           => Koha::Accounts::DebitTypes::Rental(),
2975
            date, amount, description, accounttype,
2963
        }
2976
            amountoutstanding, manager_id)
2964
    );
2977
        VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?,?)
2978
    ";
2979
    my $sth = $dbh->prepare($query);
2980
    $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge, $manager_id );
2981
}
2965
}
2982
2966
2983
=head2 GetTransfers
2967
=head2 GetTransfers
Lines 3496-3525 sub ReturnLostItem{ Link Here
3496
sub LostItem{
3480
sub LostItem{
3497
    my ($itemnumber, $mark_returned) = @_;
3481
    my ($itemnumber, $mark_returned) = @_;
3498
3482
3499
    my $dbh = C4::Context->dbh();
3483
    my $schema = Koha::Database->new()->schema;
3500
    my $sth=$dbh->prepare("SELECT issues.*,items.*,biblio.title 
3501
                           FROM issues 
3502
                           JOIN items USING (itemnumber) 
3503
                           JOIN biblio USING (biblionumber)
3504
                           WHERE issues.itemnumber=?");
3505
    $sth->execute($itemnumber);
3506
    my $issues=$sth->fetchrow_hashref();
3507
3484
3508
    # If a borrower lost the item, add a replacement cost to the their record
3485
    my $issue =
3509
    if ( my $borrowernumber = $issues->{borrowernumber} ){
3486
      $schema->resultset('Issue')->single( { itemnumber => $itemnumber } );
3510
        my $borrower = C4::Members::GetMemberDetails( $borrowernumber );
3487
3488
    my ( $borrower, $item );
3489
3490
    if ( $issue ) {
3491
        $borrower = $issue->borrower();
3492
        $item     = $issue->item();
3493
    }
3511
3494
3495
    # If a borrower lost the item, add a replacement cost to the their record
3496
    if ( $borrower ){
3512
        if (C4::Context->preference('WhenLostForgiveFine')){
3497
        if (C4::Context->preference('WhenLostForgiveFine')){
3513
            my $fix = _FixOverduesOnReturn($borrowernumber, $itemnumber, 1, 0); # 1, 0 = exemptfine, no-dropbox
3498
            _FixOverduesOnReturn(
3514
            defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $itemnumber...) failed!";  # zero is OK, check defined
3499
                {
3500
                    exempt_fine => 1,
3501
                    dropbox     => 0,
3502
                    issue       => $issue,
3503
                }
3504
            );
3515
        }
3505
        }
3516
        if (C4::Context->preference('WhenLostChargeReplacementFee')){
3506
        if ( C4::Context->preference('WhenLostChargeReplacementFee') ) {
3517
            C4::Accounts::chargelostitem($borrowernumber, $itemnumber, $issues->{'replacementprice'}, "Lost Item $issues->{'title'} $issues->{'barcode'}");
3507
            DebitLostItem( { borrower => $borrower, issue => $issue } );
3518
            #FIXME : Should probably have a way to distinguish this from an item that really was returned.
3519
            #warn " $issues->{'borrowernumber'}  /  $itemnumber ";
3520
        }
3508
        }
3521
3509
3522
        MarkIssueReturned($borrowernumber,$itemnumber,undef,undef,$borrower->{'privacy'}) if $mark_returned;
3510
        MarkIssueReturned( $borrower->borrowernumber(), $item->itemnumber(), undef, undef, $borrower->privacy() ) if $mark_returned;
3523
    }
3511
    }
3524
}
3512
}
3525
3513
(-)a/C4/Members.pm (-115 / +38 lines)
Lines 29-35 use Date::Calc qw/Today Add_Delta_YM check_date Date_to_Days/; Link Here
29
use C4::Log; # logaction
29
use C4::Log; # logaction
30
use C4::Overdues;
30
use C4::Overdues;
31
use C4::Reserves;
31
use C4::Reserves;
32
use C4::Accounts;
33
use C4::Biblio;
32
use C4::Biblio;
34
use C4::Letters;
33
use C4::Letters;
35
use C4::SQLHelper qw(InsertInTable UpdateInTable SearchInTable);
34
use C4::SQLHelper qw(InsertInTable UpdateInTable SearchInTable);
Lines 42-47 use Koha::Borrower::Debarments qw(IsDebarred); Link Here
42
use Text::Unaccent qw( unac_string );
41
use Text::Unaccent qw( unac_string );
43
use Koha::AuthUtils qw(hash_password);
42
use Koha::AuthUtils qw(hash_password);
44
use Koha::Database;
43
use Koha::Database;
44
use Koha::Accounts::DebitTypes;
45
45
46
our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
46
our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
47
47
Lines 81-88 BEGIN { Link Here
81
        &GetHideLostItemsPreference
81
        &GetHideLostItemsPreference
82
82
83
        &IsMemberBlocked
83
        &IsMemberBlocked
84
        &GetMemberAccountRecords
85
        &GetBorNotifyAcctRecord
86
84
87
        &GetborCatFromCatType
85
        &GetborCatFromCatType
88
        &GetBorrowercategory
86
        &GetBorrowercategory
Lines 462-484 The "message" field that comes from the DB is OK. Link Here
462
# FIXME rename this function.
460
# FIXME rename this function.
463
sub patronflags {
461
sub patronflags {
464
    my %flags;
462
    my %flags;
465
    my ( $patroninformation) = @_;
463
    my ($patroninformation) = @_;
466
    my $dbh=C4::Context->dbh;
464
    my $dbh = C4::Context->dbh;
467
    my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
465
    if ( $patroninformation->{account_balance} > 0 ) {
468
    if ( $owing > 0 ) {
469
        my %flaginfo;
466
        my %flaginfo;
470
        my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
467
        my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
471
        $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
468
        $flaginfo{'amount'}  = $patroninformation->{account_balance};
472
        $flaginfo{'amount'}  = sprintf "%.02f", $owing;
469
        if (  $patroninformation->{account_balance} > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
473
        if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
474
            $flaginfo{'noissues'} = 1;
470
            $flaginfo{'noissues'} = 1;
475
        }
471
        }
476
        $flags{'CHARGES'} = \%flaginfo;
472
        $flags{'CHARGES'} = \%flaginfo;
477
    }
473
    }
478
    elsif ( $balance < 0 ) {
474
    elsif ( $patroninformation->{account_balance} < 0 ) {
479
        my %flaginfo;
475
        my %flaginfo;
480
        $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
476
        $flaginfo{'amount'}  = $patroninformation->{account_balance};
481
        $flaginfo{'amount'}  = sprintf "%.02f", $balance;
482
        $flags{'CREDITS'} = \%flaginfo;
477
        $flags{'CREDITS'} = \%flaginfo;
483
    }
478
    }
484
    if (   $patroninformation->{'gonenoaddress'}
479
    if (   $patroninformation->{'gonenoaddress'}
Lines 721-727 sub GetMemberIssuesAndFines { Link Here
721
    $sth->execute($borrowernumber);
716
    $sth->execute($borrowernumber);
722
    my $overdue_count = $sth->fetchrow_arrayref->[0];
717
    my $overdue_count = $sth->fetchrow_arrayref->[0];
723
718
724
    $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
719
    $sth = $dbh->prepare("SELECT account_balance FROM borrowers WHERE borrowernumber = ?");
725
    $sth->execute($borrowernumber);
720
    $sth->execute($borrowernumber);
726
    my $total_fines = $sth->fetchrow_arrayref->[0];
721
    my $total_fines = $sth->fetchrow_arrayref->[0];
727
722
Lines 1206-1262 sub GetAllIssues { Link Here
1206
}
1201
}
1207
1202
1208
1203
1209
=head2 GetMemberAccountRecords
1210
1211
  ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1212
1213
Looks up accounting data for the patron with the given borrowernumber.
1214
1215
C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1216
reference-to-array, where each element is a reference-to-hash; the
1217
keys are the fields of the C<accountlines> table in the Koha database.
1218
C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1219
total amount outstanding for all of the account lines.
1220
1221
=cut
1222
1223
sub GetMemberAccountRecords {
1224
    my ($borrowernumber) = @_;
1225
    my $dbh = C4::Context->dbh;
1226
    my @acctlines;
1227
    my $numlines = 0;
1228
    my $strsth      = qq(
1229
                        SELECT * 
1230
                        FROM accountlines 
1231
                        WHERE borrowernumber=?);
1232
    $strsth.=" ORDER BY date desc,timestamp DESC";
1233
    my $sth= $dbh->prepare( $strsth );
1234
    $sth->execute( $borrowernumber );
1235
1236
    my $total = 0;
1237
    while ( my $data = $sth->fetchrow_hashref ) {
1238
        if ( $data->{itemnumber} ) {
1239
            my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1240
            $data->{biblionumber} = $biblio->{biblionumber};
1241
            $data->{title}        = $biblio->{title};
1242
        }
1243
        $acctlines[$numlines] = $data;
1244
        $numlines++;
1245
        $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1246
    }
1247
    $total /= 1000;
1248
    return ( $total, \@acctlines,$numlines);
1249
}
1250
1251
=head2 GetMemberAccountBalance
1204
=head2 GetMemberAccountBalance
1252
1205
1253
  ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1206
  ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1254
1207
1255
Calculates amount immediately owing by the patron - non-issue charges.
1208
Calculates amount immediately owing by the patron - non-issue charges.
1256
Based on GetMemberAccountRecords.
1257
Charges exempt from non-issue are:
1209
Charges exempt from non-issue are:
1258
* Res (reserves)
1210
* HOLD fees (reserves)
1259
* Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1211
* RENTAL if RentalsInNoissuesCharge syspref is set to false
1260
* Manual invoices if ManInvInNoissuesCharge syspref is set to false
1212
* Manual invoices if ManInvInNoissuesCharge syspref is set to false
1261
1213
1262
=cut
1214
=cut
Lines 1264-1333 Charges exempt from non-issue are: Link Here
1264
sub GetMemberAccountBalance {
1216
sub GetMemberAccountBalance {
1265
    my ($borrowernumber) = @_;
1217
    my ($borrowernumber) = @_;
1266
1218
1267
    my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1219
    my $borrower =
1220
      Koha::Database->new()->schema->resultset('Borrower')
1221
      ->find($borrowernumber);
1268
1222
1269
    my @not_fines = ('Res');
1223
    my @not_fines;
1270
    push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1271
    unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1272
        my $dbh = C4::Context->dbh;
1273
        my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1274
        push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1275
    }
1276
    my %not_fine = map {$_ => 1} @not_fines;
1277
1224
1278
    my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1225
    push( @not_fines, Koha::Accounts::DebitTypes::Hold() );
1279
    my $other_charges = 0;
1280
    foreach (@$acctlines) {
1281
        $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1282
    }
1283
1284
    return ( $total, $total - $other_charges, $other_charges);
1285
}
1286
1287
=head2 GetBorNotifyAcctRecord
1288
1289
  ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1290
1226
1291
Looks up accounting data for the patron with the given borrowernumber per file number.
1227
    push( @not_fines, Koha::Accounts::DebitTypes::Rental() )
1228
      unless C4::Context->preference('RentalsInNoissuesCharge');
1292
1229
1293
C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1230
    unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1294
reference-to-array, where each element is a reference-to-hash; the
1231
        my $dbh           = C4::Context->dbh;
1295
keys are the fields of the C<accountlines> table in the Koha database.
1232
        my $man_inv_types = $dbh->selectcol_arrayref(
1296
C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1233
            qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'}
1297
total amount outstanding for all of the account lines.
1234
        );
1298
1235
        push( @not_fines, @$man_inv_types );
1299
=cut
1236
    }
1300
1237
1301
sub GetBorNotifyAcctRecord {
1238
    my $other_charges =
1302
    my ( $borrowernumber, $notifyid ) = @_;
1239
      Koha::Database->new()->schema->resultset('AccountDebit')->search(
1303
    my $dbh = C4::Context->dbh;
1240
        {
1304
    my @acctlines;
1241
            borrowernumber => $borrowernumber,
1305
    my $numlines = 0;
1242
            type           => { -not_in => \@not_fines }
1306
    my $sth = $dbh->prepare(
1307
            "SELECT * 
1308
                FROM accountlines 
1309
                WHERE borrowernumber=? 
1310
                    AND notify_id=? 
1311
                    AND amountoutstanding != '0' 
1312
                ORDER BY notify_id,accounttype
1313
                ");
1314
1315
    $sth->execute( $borrowernumber, $notifyid );
1316
    my $total = 0;
1317
    while ( my $data = $sth->fetchrow_hashref ) {
1318
        if ( $data->{itemnumber} ) {
1319
            my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1320
            $data->{biblionumber} = $biblio->{biblionumber};
1321
            $data->{title}        = $biblio->{title};
1322
        }
1243
        }
1323
        $acctlines[$numlines] = $data;
1244
      )->get_column('amount_outstanding')->sum();
1324
        $numlines++;
1245
1325
        $total += int(100 * $data->{'amountoutstanding'});
1246
    return (
1326
    }
1247
        $borrower->account_balance(),
1327
    $total /= 100;
1248
        $borrower->account_balance() - $other_charges,
1328
    return ( $total, \@acctlines, $numlines );
1249
        $other_charges
1250
    );
1329
}
1251
}
1330
1252
1253
1331
=head2 checkuniquemember (OUEST-PROVENCE)
1254
=head2 checkuniquemember (OUEST-PROVENCE)
1332
1255
1333
  ($result,$categorycode)  = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1256
  ($result,$categorycode)  = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
(-)a/C4/Overdues.pm (-231 / +114 lines)
Lines 27-35 use List::MoreUtils qw( uniq ); Link Here
27
27
28
use C4::Circulation;
28
use C4::Circulation;
29
use C4::Context;
29
use C4::Context;
30
use C4::Accounts;
31
use C4::Log; # logaction
30
use C4::Log; # logaction
32
use C4::Debug;
31
use C4::Debug;
32
use Koha::Database;
33
use Koha::DateUtils;
34
use Koha::Accounts::OffsetTypes;
35
use Koha::Accounts::DebitTypes;
33
36
34
use vars qw($VERSION @ISA @EXPORT);
37
use vars qw($VERSION @ISA @EXPORT);
35
38
Lines 43-54 BEGIN { Link Here
43
        &CalcFine
46
        &CalcFine
44
        &Getoverdues
47
        &Getoverdues
45
        &checkoverdues
48
        &checkoverdues
46
        &NumberNotifyId
47
        &AmountNotify
48
        &UpdateFine
49
        &UpdateFine
49
        &GetFine
50
        &GetFine
50
        
51
        
51
        &CheckItemNotify
52
        &GetOverduesForBranch
52
        &GetOverduesForBranch
53
        &RemoveNotifyLine
53
        &RemoveNotifyLine
54
        &AddNotifyLine
54
        &AddNotifyLine
Lines 459-612 sub GetIssuesIteminfo { Link Here
459
459
460
=head2 UpdateFine
460
=head2 UpdateFine
461
461
462
    &UpdateFine($itemnumber, $borrowernumber, $amount, $type, $description);
462
    UpdateFine(
463
        {
464
            itemnumber     => $itemnumber,
465
            borrowernumber => $borrowernumber,
466
            amount         => $amount,
467
            due            => $due,
468
            issue_id       => $issue_id
469
        }
470
    );
463
471
464
(Note: the following is mostly conjecture and guesswork.)
472
Updates the fine owed on an overdue item.
465
473
466
Updates the fine owed on an overdue book.
474
C<$itemnumber> is the items's id.
467
475
468
C<$itemnumber> is the book's item number.
476
C<$borrowernumber> is the id of the patron who currently
477
has the item on loan.
469
478
470
C<$borrowernumber> is the borrower number of the patron who currently
479
C<$amount> is the total amount of the fine owed by the patron.
471
has the book on loan.
472
480
473
C<$amount> is the current amount owed by the patron.
481
C<&UpdateFine> updates the amount owed for a given fine if an issue_id
482
is passed to it. Otherwise, a new fine will be created.
474
483
475
C<$type> will be used in the description of the fine.
484
=cut
476
485
477
C<$description> is a string that must be present in the description of
486
sub UpdateFine {
478
the fine. I think this is expected to be a date in DD/MM/YYYY format.
487
    my ($params) = @_;
479
488
480
C<&UpdateFine> looks up the amount currently owed on the given item
489
    my $itemnumber     = $params->{itemnumber};
481
and sets it to C<$amount>, creating, if necessary, a new entry in the
490
    my $borrowernumber = $params->{borrowernumber};
482
accountlines table of the Koha database.
491
    my $amount         = $params->{amount};
492
    my $due            = $params->{due};
493
    my $issue_id       = $params->{issue_id};
483
494
484
=cut
495
    my $schema = Koha::Database->new()->schema;
485
496
486
#
497
    my $borrower = $schema->resultset('Borrower')->find($borrowernumber);
487
# Question: Why should the caller have to
488
# specify both the item number and the borrower number? A book can't
489
# be on loan to two different people, so the item number should be
490
# sufficient.
491
#
492
# Possible Answer: You might update a fine for a damaged item, *after* it is returned.
493
#
494
sub UpdateFine {
495
    my ( $itemnum, $borrowernumber, $amount, $type, $due ) = @_;
496
	$debug and warn "UpdateFine($itemnum, $borrowernumber, $amount, " . ($type||'""') . ", $due) called";
497
    my $dbh = C4::Context->dbh;
498
    # FIXME - What exactly is this query supposed to do? It looks up an
499
    # entry in accountlines that matches the given item and borrower
500
    # numbers, where the description contains $due, and where the
501
    # account type has one of several values, but what does this _mean_?
502
    # Does it look up existing fines for this item?
503
    # FIXME - What are these various account types? ("FU", "O", "F", "M")
504
	#	"L"   is LOST item
505
	#   "A"   is Account Management Fee
506
	#   "N"   is New Card
507
	#   "M"   is Sundry
508
	#   "O"   is Overdue ??
509
	#   "F"   is Fine ??
510
	#   "FU"  is Fine UPDATE??
511
	#	"Pay" is Payment
512
	#   "REF" is Cash Refund
513
    my $sth = $dbh->prepare(
514
        "SELECT * FROM accountlines
515
        WHERE borrowernumber=?
516
        AND   accounttype IN ('FU','O','F','M')"
517
    );
518
    $sth->execute( $borrowernumber );
519
    my $data;
520
    my $total_amount_other = 0.00;
521
    my $due_qr = qr/$due/;
522
    # Cycle through the fines and
523
    # - find line that relates to the requested $itemnum
524
    # - accumulate fines for other items
525
    # so we can update $itemnum fine taking in account fine caps
526
    while (my $rec = $sth->fetchrow_hashref) {
527
        if ($rec->{itemnumber} == $itemnum && $rec->{description} =~ /$due_qr/) {
528
            if ($data) {
529
                warn "Not a unique accountlines record for item $itemnum borrower $borrowernumber";
530
            } else {
531
                $data = $rec;
532
                next;
533
            }
534
        }
535
        $total_amount_other += $rec->{'amountoutstanding'};
536
    }
537
498
538
    if (my $maxfine = C4::Context->preference('MaxFine')) {
499
    if ( my $maxfine = C4::Context->preference('MaxFine') ) {
539
        if ($total_amount_other + $amount > $maxfine) {
500
        if ( $borrower->account_balance() + $amount > $maxfine ) {
540
            my $new_amount = $maxfine - $total_amount_other;
501
            my $new_amount = $maxfine - $borrower->account_balance();
541
            return if $new_amount <= 0.00;
502
            warn "Reducing fine for item $itemnumber borrower $borrowernumber from $amount to $new_amount - MaxFine reached";
542
            warn "Reducing fine for item $itemnum borrower $borrowernumber from $amount to $new_amount - MaxFine reached";
503
            if ( $new_amount <= 0 ) {
504
                warn "Fine reduced to a non-positive ammount. Fine not created.";
505
                return;
506
            }
543
            $amount = $new_amount;
507
            $amount = $new_amount;
544
        }
508
        }
545
    }
509
    }
546
510
547
    if ( $data ) {
511
    my $timestamp = get_timestamp();
548
512
549
		# we're updating an existing fine.  Only modify if amount changed
513
    my $fine =
550
        # Note that in the current implementation, you cannot pay against an accruing fine
514
      $schema->resultset('AccountDebit')->single( { issue_id => $issue_id, type => Koha::Accounts::DebitTypes::Fine } );
551
        # (i.e. , of accounttype 'FU').  Doing so will break accrual.
515
552
    	if ( $data->{'amount'} != $amount ) {
516
    my $offset = 0;
553
            my $diff = $amount - $data->{'amount'};
517
    if ($fine) {
554
	    #3341: diff could be positive or negative!
518
        if (
555
            my $out  = $data->{'amountoutstanding'} + $diff;
519
            sprintf( "%.6f", $fine->amount_original() )
556
            my $query = "
520
            ne
557
                UPDATE accountlines
521
            sprintf( "%.6f", $amount ) )
558
				SET date=now(), amount=?, amountoutstanding=?,
522
        {
559
					lastincrement=?, accounttype='FU'
523
            my $difference = $amount - $fine->amount_original();
560
	  			WHERE borrowernumber=?
524
561
				AND   itemnumber=?
525
            $fine->amount_original( $fine->amount_original() + $difference );
562
				AND   accounttype IN ('FU','O')
526
            $fine->amount_outstanding( $fine->amount_outstanding() + $difference );
563
				AND   description LIKE ?
527
            $fine->amount_last_increment($difference);
564
				LIMIT 1 ";
528
            $fine->updated_on($timestamp);
565
            my $sth2 = $dbh->prepare($query);
529
            $fine->update();
566
			# FIXME: BOGUS query cannot ensure uniqueness w/ LIKE %x% !!!
530
567
			# 		LIMIT 1 added to prevent multiple affected lines
531
            $offset = 1;
568
			# FIXME: accountlines table needs unique key!! Possibly a combo of borrowernumber and accountline.  
569
			# 		But actually, we should just have a regular autoincrementing PK and forget accountline,
570
			# 		including the bogus getnextaccountno function (doesn't prevent conflict on simultaneous ops).
571
			# FIXME: Why only 2 account types here?
572
			$debug and print STDERR "UpdateFine query: $query\n" .
573
				"w/ args: $amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, \"\%$due\%\"\n";
574
            $sth2->execute($amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, "%$due%");
575
        } else {
576
            #      print "no update needed $data->{'amount'}"
577
        }
532
        }
578
    } else {
533
    }
579
        my $sth4 = $dbh->prepare(
534
    else {
580
            "SELECT title FROM biblio LEFT JOIN items ON biblio.biblionumber=items.biblionumber WHERE items.itemnumber=?"
535
        my $item = $schema->resultset('Item')->find($itemnumber);
536
537
        $fine = $schema->resultset('AccountDebit')->create(
538
            {
539
                borrowernumber        => $borrowernumber,
540
                itemnumber            => $itemnumber,
541
                issue_id              => $issue_id,
542
                type                  => Koha::Accounts::DebitTypes::Fine(),
543
                accruing              => 1,
544
                amount_original       => $amount,
545
                amount_outstanding    => $amount,
546
                amount_last_increment => $amount,
547
                description           => $item->biblio()->title() . " / Due:$due",
548
                created_on            => $timestamp,
549
            }
581
        );
550
        );
582
        $sth4->execute($itemnum);
551
583
        my $title = $sth4->fetchrow;
552
        $offset = 1;
584
585
#         #   print "not in account";
586
#         my $sth3 = $dbh->prepare("Select max(accountno) from accountlines");
587
#         $sth3->execute;
588
# 
589
#         # FIXME - Make $accountno a scalar.
590
#         my @accountno = $sth3->fetchrow_array;
591
#         $sth3->finish;
592
#         $accountno[0]++;
593
# begin transaction
594
		my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
595
		my $desc = ($type ? "$type " : '') . "$title $due";	# FIXEDME, avoid whitespace prefix on empty $type
596
		my $query = "INSERT INTO accountlines
597
		    (borrowernumber,itemnumber,date,amount,description,accounttype,amountoutstanding,lastincrement,accountno)
598
			    VALUES (?,?,now(),?,?,'FU',?,?,?)";
599
		my $sth2 = $dbh->prepare($query);
600
		$debug and print STDERR "UpdateFine query: $query\nw/ args: $borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno\n";
601
        $sth2->execute($borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno);
602
    }
553
    }
603
    # logging action
554
604
    &logaction(
555
    $schema->resultset('AccountOffset')->create(
605
        "FINES",
556
        {
606
        $type,
557
            debit_id   => $fine->debit_id(),
558
            amount     => $fine->amount_last_increment(),
559
            created_on => $timestamp,
560
            type       => Koha::Accounts::OffsetTypes::Fine(),
561
        }
562
    ) if $offset;
563
564
    $borrower->account_balance( $borrower->account_balance + $fine->amount_last_increment() );
565
    $borrower->update();
566
567
    logaction( "FINES", Koha::Accounts::DebitTypes::Fine(),
607
        $borrowernumber,
568
        $borrowernumber,
608
        "due=".$due."  amount=".$amount." itemnumber=".$itemnum
569
        "due=" . $due . "  amount=" . $amount . " itemnumber=" . $itemnumber )
609
        ) if C4::Context->preference("FinesLog");
570
      if C4::Context->preference("FinesLog");
610
}
571
}
611
572
612
=head2 BorType
573
=head2 BorType
Lines 647-716 C<$borrowernumber> is the borrowernumber Link Here
647
=cut 
608
=cut 
648
609
649
sub GetFine {
610
sub GetFine {
650
    my ( $itemnum, $borrowernumber ) = @_;
611
    my ( $itemnumber, $borrowernumber ) = @_;
651
    my $dbh   = C4::Context->dbh();
652
    my $query = q|SELECT sum(amountoutstanding) as fineamount FROM accountlines
653
    where accounttype like 'F%'
654
  AND amountoutstanding > 0 AND itemnumber = ? AND borrowernumber=?|;
655
    my $sth = $dbh->prepare($query);
656
    $sth->execute( $itemnum, $borrowernumber );
657
    my $fine = $sth->fetchrow_hashref();
658
    if ($fine->{fineamount}) {
659
        return $fine->{fineamount};
660
    }
661
    return 0;
662
}
663
664
=head2 NumberNotifyId
665
666
    (@notify) = &NumberNotifyId($borrowernumber);
667
668
Returns amount for all file per borrowers
669
C<@notify> array contains all file per borrowers
670
671
C<$notify_id> contains the file number for the borrower number nad item number
672
673
=cut
674
675
sub NumberNotifyId{
676
    my ($borrowernumber)=@_;
677
    my $dbh = C4::Context->dbh;
678
    my $query=qq|    SELECT distinct(notify_id)
679
            FROM accountlines
680
            WHERE borrowernumber=?|;
681
    my @notify;
682
    my $sth = $dbh->prepare($query);
683
    $sth->execute($borrowernumber);
684
    while ( my ($numberofnotify) = $sth->fetchrow ) {
685
        push( @notify, $numberofnotify );
686
    }
687
    return (@notify);
688
}
689
612
690
=head2 AmountNotify
613
    my $schema = Koha::Database->new()->schema;
691
614
692
    ($totalnotify) = &AmountNotify($notifyid);
615
    my $amount_outstanding = $schema->resultset('AccountDebit')->search(
616
        {
617
            itemnumber     => $itemnumber,
618
            borrowernumber => $borrowernumber,
619
            type           => Koha::Accounts::DebitTypes::Fine(),
620
        },
621
    )->get_column('amount_outstanding')->sum();
693
622
694
Returns amount for all file per borrowers
623
    return $amount_outstanding;
695
C<$notifyid> is the file number
696
697
C<$totalnotify> contains amount of a file
698
699
C<$notify_id> contains the file number for the borrower number and item number
700
701
=cut
702
703
sub AmountNotify{
704
    my ($notifyid,$borrowernumber)=@_;
705
    my $dbh = C4::Context->dbh;
706
    my $query=qq|    SELECT sum(amountoutstanding)
707
            FROM accountlines
708
            WHERE notify_id=? AND borrowernumber = ?|;
709
    my $sth=$dbh->prepare($query);
710
	$sth->execute($notifyid,$borrowernumber);
711
	my $totalnotify=$sth->fetchrow;
712
    $sth->finish;
713
    return ($totalnotify);
714
}
624
}
715
625
716
=head2 GetItems
626
=head2 GetItems
Lines 762-788 sub GetBranchcodesWithOverdueRules { Link Here
762
    return @branches;
672
    return @branches;
763
}
673
}
764
674
765
=head2 CheckItemNotify
766
767
Sql request to check if the document has alreday been notified
768
this function is not exported, only used with GetOverduesForBranch
769
770
=cut
771
772
sub CheckItemNotify {
773
    my ($notify_id,$notify_level,$itemnumber) = @_;
774
    my $dbh = C4::Context->dbh;
775
    my $sth = $dbh->prepare("
776
    SELECT COUNT(*)
777
     FROM notifys
778
    WHERE notify_id    = ?
779
     AND  notify_level = ? 
780
     AND  itemnumber   = ? ");
781
    $sth->execute($notify_id,$notify_level,$itemnumber);
782
    my $notified = $sth->fetchrow;
783
    return ($notified);
784
}
785
786
=head2 GetOverduesForBranch
675
=head2 GetOverduesForBranch
787
676
788
Sql request for display all information for branchoverdues.pl
677
Sql request for display all information for branchoverdues.pl
Lines 808-813 sub GetOverduesForBranch { Link Here
808
               biblio.title,
697
               biblio.title,
809
               biblio.author,
698
               biblio.author,
810
               biblio.biblionumber,
699
               biblio.biblionumber,
700
               issues.issue_id,
811
               issues.date_due,
701
               issues.date_due,
812
               issues.returndate,
702
               issues.returndate,
813
               issues.branchcode,
703
               issues.branchcode,
Lines 818-842 sub GetOverduesForBranch { Link Here
818
                items.location,
708
                items.location,
819
                items.itemnumber,
709
                items.itemnumber,
820
            itemtypes.description,
710
            itemtypes.description,
821
         accountlines.notify_id,
711
            account_debits.amount_outstanding
822
         accountlines.notify_level,
712
    FROM  account_debits
823
         accountlines.amountoutstanding
713
    LEFT JOIN issues      ON    issues.itemnumber     = account_debits.itemnumber
824
    FROM  accountlines
714
                          AND   issues.borrowernumber = account_debits.borrowernumber
825
    LEFT JOIN issues      ON    issues.itemnumber     = accountlines.itemnumber
715
    LEFT JOIN borrowers   ON borrowers.borrowernumber = account_debits.borrowernumber
826
                          AND   issues.borrowernumber = accountlines.borrowernumber
827
    LEFT JOIN borrowers   ON borrowers.borrowernumber = accountlines.borrowernumber
828
    LEFT JOIN items       ON     items.itemnumber     = issues.itemnumber
716
    LEFT JOIN items       ON     items.itemnumber     = issues.itemnumber
829
    LEFT JOIN biblio      ON      biblio.biblionumber =  items.biblionumber
717
    LEFT JOIN biblio      ON      biblio.biblionumber =  items.biblionumber
830
    LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
718
    LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
831
    LEFT JOIN itemtypes   ON itemtypes.itemtype       = $itype_link
719
    LEFT JOIN itemtypes   ON itemtypes.itemtype       = $itype_link
832
    LEFT JOIN branches    ON  branches.branchcode     = issues.branchcode
720
    LEFT JOIN branches    ON  branches.branchcode     = issues.branchcode
833
    WHERE (accountlines.amountoutstanding  != '0.000000')
721
    WHERE (account_debits.amount_outstanding  != '0.000000')
834
      AND (accountlines.accounttype         = 'FU'      )
722
      AND (account_debits.type = 'FINE')
723
      AND (account_debits.accruing = 1 )
835
      AND (issues.branchcode =  ?   )
724
      AND (issues.branchcode =  ?   )
836
      AND (issues.date_due  < NOW())
725
      AND (issues.date_due  < NOW())
837
    ";
726
    ";
838
    my @getoverdues;
727
    my @getoverdues;
839
    my $i = 0;
840
    my $sth;
728
    my $sth;
841
    if ($location) {
729
    if ($location) {
842
        $sth = $dbh->prepare("$select AND items.location = ? ORDER BY borrowers.surname, borrowers.firstname");
730
        $sth = $dbh->prepare("$select AND items.location = ? ORDER BY borrowers.surname, borrowers.firstname");
Lines 846-857 sub GetOverduesForBranch { Link Here
846
        $sth->execute($branch);
734
        $sth->execute($branch);
847
    }
735
    }
848
    while ( my $data = $sth->fetchrow_hashref ) {
736
    while ( my $data = $sth->fetchrow_hashref ) {
849
    #check if the document has already been notified
737
        push( @getoverdues, $data );
850
        my $countnotify = CheckItemNotify($data->{'notify_id'}, $data->{'notify_level'}, $data->{'itemnumber'});
851
        if ($countnotify eq '0') {
852
            $getoverdues[$i] = $data;
853
            $i++;
854
        }
855
    }
738
    }
856
    return (@getoverdues);
739
    return (@getoverdues);
857
}
740
}
(-)a/C4/Reserves.pm (-13 / +10 lines)
Lines 28-34 use C4::Biblio; Link Here
28
use C4::Members;
28
use C4::Members;
29
use C4::Items;
29
use C4::Items;
30
use C4::Circulation;
30
use C4::Circulation;
31
use C4::Accounts;
32
31
33
# for _koha_notify_reserve
32
# for _koha_notify_reserve
34
use C4::Members::Messaging;
33
use C4::Members::Messaging;
Lines 172-190 sub AddReserve { Link Here
172
        $waitingdate = $resdate;
171
        $waitingdate = $resdate;
173
    }
172
    }
174
173
175
    #eval {
176
    # updates take place here
177
    if ( $fee > 0 ) {
174
    if ( $fee > 0 ) {
178
        my $nextacctno = &getnextacctno( $borrowernumber );
175
        AddDebit(
179
        my $query      = qq/
176
            {
180
        INSERT INTO accountlines
177
                borrowernumber => $borrowernumber,
181
            (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
178
                itemnumber     => $checkitem,
182
        VALUES
179
                amount         => $fee,
183
            (?,?,now(),?,?,'Res',?)
180
                type           => Koha::Accounts::DebitTypes::Hold(),
184
    /;
181
                description    => "Hold fee - $title",
185
        my $usth = $dbh->prepare($query);
182
                notes          => "Record ID: $biblionumber",
186
        $usth->execute( $borrowernumber, $nextacctno, $fee,
183
            }
187
            "Reserve Charge - $title", $fee );
184
        );
188
    }
185
    }
189
186
190
    #if ($const eq 'a'){
187
    #if ($const eq 'a'){
(-)a/C4/SIP/ILS/Patron.pm (-1 / +1 lines)
Lines 85-91 sub new { Link Here
85
        hold_ok         => ( !$debarred && !$expired ),
85
        hold_ok         => ( !$debarred && !$expired ),
86
        card_lost       => ( $kp->{lost} || $kp->{gonenoaddress} || $flags->{LOST} ),
86
        card_lost       => ( $kp->{lost} || $kp->{gonenoaddress} || $flags->{LOST} ),
87
        claims_returned => 0,
87
        claims_returned => 0,
88
        fines           => $fines_amount, # GetMemberAccountRecords($kp->{borrowernumber})
88
        fines           => $fines_amount,
89
        fees            => 0,             # currently not distinct from fines
89
        fees            => 0,             # currently not distinct from fines
90
        recall_overdue  => 0,
90
        recall_overdue  => 0,
91
        items_billed    => 0,
91
        items_billed    => 0,
(-)a/C4/SIP/ILS/Transaction/FeePayment.pm (-5 / +18 lines)
Lines 20-26 use strict; Link Here
20
# with Koha; if not, write to the Free Software Foundation, Inc.,
20
# with Koha; if not, write to the Free Software Foundation, Inc.,
21
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22
22
23
use C4::Accounts qw(recordpayment);
23
use Koha::Accounts qw(AddCredit);
24
use Koha::Database;
24
use ILS;
25
use ILS;
25
use parent qw(ILS::Transaction);
26
use parent qw(ILS::Transaction);
26
27
Lines 45-54 sub new { Link Here
45
sub pay {
46
sub pay {
46
    my $self           = shift;
47
    my $self           = shift;
47
    my $borrowernumber = shift;
48
    my $borrowernumber = shift;
48
    my $amt            = shift;
49
    my $amount         = shift;
49
    my $type           = shift;
50
    my $type           = shift;
50
    warn("RECORD:$borrowernumber::$amt");
51
51
    recordpayment( $borrowernumber, $amt,$type );
52
    warn("RECORD:$borrowernumber::$amount");
53
54
    my $borrower =
55
      Koha::Database->new()->schema->resultset('Borrower')
56
      ->find($borrowernumber);
57
58
    AddCredit(
59
        {
60
            borrower => $borrower,
61
            amount   => $amount,
62
            notes    => 'via SIP2',
63
            type     => $type,
64
        }
65
    );
52
}
66
}
53
67
54
#sub DESTROY {
68
#sub DESTROY {
55
- 

Return to bug 6427