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

(-)a/C4/Circulation.pm (-187 / +175 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 2013-2022 of the return. It is ignored when a dropbox_branch is passed in. Link Here
2013
C<$privacy> contains the privacy parameter. If the patron has set privacy to 2,
2030
C<$privacy> contains the privacy parameter. If the patron has set privacy to 2,
2014
the old_issue is immediately anonymised
2031
the old_issue is immediately anonymised
2015
2032
2016
Ideally, this function would be internal to C<C4::Circulation>,
2017
not exported, but it is currently needed by one 
2018
routine in C<C4::Accounts>.
2019
2020
=cut
2033
=cut
2021
2034
2022
sub MarkIssueReturned {
2035
sub MarkIssueReturned {
Lines 2152-2290 Internal function, called only by AddReturn Link Here
2152
=cut
2165
=cut
2153
2166
2154
sub _FixOverduesOnReturn {
2167
sub _FixOverduesOnReturn {
2155
    my ($borrowernumber, $item);
2168
    my ( $params ) = @_;
2156
    unless ($borrowernumber = shift) {
2169
2157
        warn "_FixOverduesOnReturn() not supplied valid borrowernumber";
2170
    my $exemptfine = $params->{exempt_fine};
2158
        return;
2171
    my $dropbox    = $params->{dropbox};
2159
    }
2172
    my $issue      = $params->{issue};
2160
    unless ($item = shift) {
2173
2161
        warn "_FixOverduesOnReturn() not supplied valid itemnumber";
2162
        return;
2163
    }
2164
    my ($exemptfine, $dropbox) = @_;
2165
    my $dbh = C4::Context->dbh;
2174
    my $dbh = C4::Context->dbh;
2166
2175
2167
    # check for overdue fine
2176
    my $schema = Koha::Database->new()->schema;
2168
    my $sth = $dbh->prepare(
2177
    my $fine =
2169
"SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
2178
      $schema->resultset('AccountDebit')
2170
    );
2179
      ->single( { issue_id => $issue->{issue_id}, type => Koha::Accounts::DebitTypes::Fine() } );
2171
    $sth->execute( $borrowernumber, $item );
2172
2180
2173
    # alter fine to show that the book has been returned
2181
    return unless ( $fine );
2174
    my $data = $sth->fetchrow_hashref;
2182
2175
    return 0 unless $data;    # no warning, there's just nothing to fix
2183
    $fine->accruing(0);
2176
2184
2177
    my $uquery;
2178
    my @bind = ($data->{'accountlines_id'});
2179
    if ($exemptfine) {
2185
    if ($exemptfine) {
2180
        $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
2186
        AddCredit(
2181
        if (C4::Context->preference("FinesLog")) {
2187
            {
2182
            &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
2188
                borrower => $fine->borrowernumber(),
2183
        }
2189
                amount   => $fine->amount_original(),
2184
    } elsif ($dropbox && $data->{lastincrement}) {
2190
                debit_id => $fine->debit_id(),
2185
        my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
2191
                type     => Koha::Accounts::CreditTypes::Forgiven(),
2186
        my $amt = $data->{amount} - $data->{lastincrement} ;
2192
            }
2193
        );
2187
        if (C4::Context->preference("FinesLog")) {
2194
        if (C4::Context->preference("FinesLog")) {
2188
            &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
2195
            &logaction(
2189
        }
2196
                "FINES", 'MODIFY',
2190
         $uquery = "update accountlines set accounttype='F' ";
2197
                $issue->{borrowernumber},
2191
         if($outstanding  >= 0 && $amt >=0) {
2198
                "Overdue forgiven: item " . $issue->{itemnumber}
2192
            $uquery .= ", amount = ? , amountoutstanding=? ";
2199
            );
2193
            unshift @bind, ($amt, $outstanding) ;
2194
        }
2200
        }
2195
    } else {
2201
    } elsif ($dropbox && $fine->amount_last_increment() != $fine->amount_original() ) {
2196
        $uquery = "update accountlines set accounttype='F' ";
2202
        if ( C4::Context->preference("FinesLog") ) {
2203
            &logaction( "FINES", 'MODIFY', $issue->{borrowernumber},
2204
                    "Dropbox adjustment "
2205
                  . $fine->amount_last_increment()
2206
                  . ", item " . $issue->{itemnumber} );
2207
        }
2208
        $fine->amount_original(
2209
            $fine->amount_original() - $fine->amount_last_increment() );
2210
        $fine->amount_outstanding(
2211
            $fine->amount_outstanding - $fine->amount_last_increment() );
2212
        $schema->resultset('AccountOffset')->create(
2213
            {
2214
                debit_id => $fine->debit_id(),
2215
                type     => Koha::Accounts::OffsetTypes::Dropbox(),
2216
                amount   => $fine->amount_last_increment() * -1,
2217
            }
2218
        );
2197
    }
2219
    }
2198
    $uquery .= " where (accountlines_id = ?)";
2220
2199
    my $usth = $dbh->prepare($uquery);
2221
    return $fine->update();
2200
    return $usth->execute(@bind);
2201
}
2222
}
2202
2223
2203
=head2 _FixAccountForLostAndReturned
2224
=head2 _FixAccountForLostAndReturned
2204
2225
2205
  &_FixAccountForLostAndReturned($itemnumber, [$borrowernumber, $barcode]);
2226
  &_FixAccountForLostAndReturned($itemnumber);
2206
2207
Calculates the charge for a book lost and returned.
2208
2209
Internal function, not exported, called only by AddReturn.
2210
2227
2211
FIXME: This function reflects how inscrutable fines logic is.  Fix both.
2228
  Refunds a lost item fee in necessary
2212
FIXME: Give a positive return value on success.  It might be the $borrowernumber who received credit, or the amount forgiven.
2213
2229
2214
=cut
2230
=cut
2215
2231
2216
sub _FixAccountForLostAndReturned {
2232
sub _FixAccountForLostAndReturned {
2217
    my $itemnumber     = shift or return;
2233
    my ( $itemnumber ) = @_;
2218
    my $borrowernumber = @_ ? shift : undef;
2234
2219
    my $item_id        = @_ ? shift : $itemnumber;  # Send the barcode if you want that logged in the description
2235
    my $schema = Koha::Database->new()->schema;
2220
    my $dbh = C4::Context->dbh;
2236
2221
    # check for charge made for lost book
2237
    # 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");
2238
    my $issue =
2223
    $sth->execute($itemnumber);
2239
      $schema->resultset('Issue')->single( { itemnumber => $itemnumber } );
2224
    my $data = $sth->fetchrow_hashref;
2240
    $issue ||=
2225
    $data or return;    # bail if there is nothing to do
2241
      $schema->resultset('OldIssue')->single( { itemnumber => $itemnumber } );
2226
    $data->{accounttype} eq 'W' and return;    # Written off
2242
2227
2243
    return unless $issue;
2228
    # writeoff this amount
2244
2229
    my $offset;
2245
    # Find a lost fee for this issue
2230
    my $amount = $data->{'amount'};
2246
    my $debit = $schema->resultset('AccountDebit')->single(
2231
    my $acctno = $data->{'accountno'};
2247
        {
2232
    my $amountleft;                                             # Starts off undef/zero.
2248
            issue_id => $issue->issue_id(),
2233
    if ($data->{'amountoutstanding'} == $amount) {
2249
            type     => Koha::Accounts::DebitTypes::Lost()
2234
        $offset     = $data->{'amount'};
2250
        }
2235
        $amountleft = 0;                                        # Hey, it's zero here, too.
2251
    );
2236
    } else {
2252
2237
        $offset     = $amount - $data->{'amountoutstanding'};   # Um, isn't this the same as ZERO?  We just tested those two things are ==
2253
    return unless $debit;
2238
        $amountleft = $data->{'amountoutstanding'} - $amount;   # Um, isn't this the same as ZERO?  We just tested those two things are ==
2254
2239
    }
2255
    # 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'
2256
    my @credits = $debit->account_offsets->search_related('credit', { 'credit.type' => Koha::Accounts::CreditTypes::Found() });
2241
        WHERE (accountlines_id = ?)");
2257
2242
    $usth->execute($data->{'accountlines_id'});      # We might be adjusting an account for some OTHER borrowernumber now.  Not the one we passed in.
2258
    return if @credits;
2243
    #check if any credit is left if so writeoff other accounts
2259
2244
    my $nextaccntno = getnextacctno($data->{'borrowernumber'});
2260
    # Ok, so we know we have an unrefunded lost item fee, let's refund it
2245
    $amountleft *= -1 if ($amountleft < 0);
2261
    CreditLostItem(
2246
    if ($amountleft > 0) {
2262
        {
2247
        my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
2263
            borrower => $issue->borrower(),
2248
                            AND (amountoutstanding >0) ORDER BY date");     # might want to order by amountoustanding ASC (pay smallest first)
2264
            debit    => $debit
2249
        $msth->execute($data->{'borrowernumber'});
2265
        }
2250
        # offset transactions
2266
    );
2251
        my $newamtos;
2267
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);
2268
    ModItem({ paidfor => '' }, undef, $itemnumber);
2287
    return;
2288
}
2269
}
2289
2270
2290
=head2 _GetCircControlBranch
2271
=head2 _GetCircControlBranch
Lines 2728-2746 sub AddRenewal { Link Here
2728
    # Charge a new rental fee, if applicable?
2709
    # Charge a new rental fee, if applicable?
2729
    my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2710
    my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2730
    if ( $charge > 0 ) {
2711
    if ( $charge > 0 ) {
2731
        my $accountno = getnextacctno( $borrowernumber );
2732
        my $item = GetBiblioFromItemNumber($itemnumber);
2712
        my $item = GetBiblioFromItemNumber($itemnumber);
2733
        my $manager_id = 0;
2713
2734
        $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv; 
2714
        my $borrower =
2735
        $sth = $dbh->prepare(
2715
          Koha::Database->new()->schema->resultset('Borrower')
2736
                "INSERT INTO accountlines
2716
          ->find($borrowernumber);
2737
                    (date, borrowernumber, accountno, amount, manager_id,
2717
2738
                    description,accounttype, amountoutstanding, itemnumber)
2718
        AddDebit(
2739
                    VALUES (now(),?,?,?,?,?,?,?,?)"
2719
            {
2720
                borrower   => $borrower,
2721
                itemnumber => $itemnumber,
2722
                amount     => $charge,
2723
                type       => Koha::Accounts::DebitTypes::Rental(),
2724
                description =>
2725
                  "Renewal of Rental Item $item->{'title'} $item->{'barcode'}"
2726
            }
2740
        );
2727
        );
2741
        $sth->execute( $borrowernumber, $accountno, $charge, $manager_id,
2742
            "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
2743
            'Rent', $charge, $itemnumber );
2744
    }
2728
    }
2745
2729
2746
    # Send a renewal slip according to checkout alert preferencei
2730
    # Send a renewal slip according to checkout alert preferencei
Lines 2959-2983 sub _get_discount_from_rule { Link Here
2959
2943
2960
=head2 AddIssuingCharge
2944
=head2 AddIssuingCharge
2961
2945
2962
  &AddIssuingCharge( $itemno, $borrowernumber, $charge )
2946
  &AddIssuingCharge( $itemnumber, $borrowernumber, $amount )
2963
2947
2964
=cut
2948
=cut
2965
2949
2966
sub AddIssuingCharge {
2950
sub AddIssuingCharge {
2967
    my ( $itemnumber, $borrowernumber, $charge ) = @_;
2951
    my ( $itemnumber, $borrowernumber, $amount ) = @_;
2968
    my $dbh = C4::Context->dbh;
2952
2969
    my $nextaccntno = getnextacctno( $borrowernumber );
2953
    return AddDebit(
2970
    my $manager_id = 0;
2954
        {
2971
    $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
2955
            borrower       => Koha::Database->new()->schema->resultset('Borrower')->find($borrowernumber),
2972
    my $query ="
2956
            itemnumber     => $itemnumber,
2973
        INSERT INTO accountlines
2957
            amount         => $amount,
2974
            (borrowernumber, itemnumber, accountno,
2958
            type           => Koha::Accounts::DebitTypes::Rental(),
2975
            date, amount, description, accounttype,
2959
        }
2976
            amountoutstanding, manager_id)
2960
    );
2977
        VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?,?)
2978
    ";
2979
    my $sth = $dbh->prepare($query);
2980
    $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge, $manager_id );
2981
}
2961
}
2982
2962
2983
=head2 GetTransfers
2963
=head2 GetTransfers
Lines 3496-3525 sub ReturnLostItem{ Link Here
3496
sub LostItem{
3476
sub LostItem{
3497
    my ($itemnumber, $mark_returned) = @_;
3477
    my ($itemnumber, $mark_returned) = @_;
3498
3478
3499
    my $dbh = C4::Context->dbh();
3479
    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
3480
3508
    # If a borrower lost the item, add a replacement cost to the their record
3481
    my $issue =
3509
    if ( my $borrowernumber = $issues->{borrowernumber} ){
3482
      $schema->resultset('Issue')->single( { itemnumber => $itemnumber } );
3510
        my $borrower = C4::Members::GetMemberDetails( $borrowernumber );
3483
3484
    my ( $borrower, $item );
3485
3486
    if ( $issue ) {
3487
        $borrower = $issue->borrower();
3488
        $item     = $issue->item();
3489
    }
3511
3490
3491
    # If a borrower lost the item, add a replacement cost to the their record
3492
    if ( $borrower ){
3512
        if (C4::Context->preference('WhenLostForgiveFine')){
3493
        if (C4::Context->preference('WhenLostForgiveFine')){
3513
            my $fix = _FixOverduesOnReturn($borrowernumber, $itemnumber, 1, 0); # 1, 0 = exemptfine, no-dropbox
3494
            _FixOverduesOnReturn(
3514
            defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $itemnumber...) failed!";  # zero is OK, check defined
3495
                {
3496
                    exempt_fine => 1,
3497
                    dropbox     => 0,
3498
                    issue       => $issue,
3499
                }
3500
            );
3515
        }
3501
        }
3516
        if (C4::Context->preference('WhenLostChargeReplacementFee')){
3502
        if ( C4::Context->preference('WhenLostChargeReplacementFee') ) {
3517
            C4::Accounts::chargelostitem($borrowernumber, $itemnumber, $issues->{'replacementprice'}, "Lost Item $issues->{'title'} $issues->{'barcode'}");
3503
            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
        }
3504
        }
3521
3505
3522
        MarkIssueReturned($borrowernumber,$itemnumber,undef,undef,$borrower->{'privacy'}) if $mark_returned;
3506
        MarkIssueReturned( $borrower->borrowernumber(), $item->itemnumber(), undef, undef, $borrower->privacy() ) if $mark_returned;
3523
    }
3507
    }
3524
}
3508
}
3525
3509
Lines 3637-3646 sub ProcessOfflineIssue { Link Here
3637
sub ProcessOfflinePayment {
3621
sub ProcessOfflinePayment {
3638
    my $operation = shift;
3622
    my $operation = shift;
3639
3623
3640
    my $borrower = C4::Members::GetMemberDetails( undef, $operation->{cardnumber} ); # Get borrower from operation cardnumber
3624
    AddCredit(
3641
    my $amount = $operation->{amount};
3625
        {
3642
3626
            borrower => Koha::Database->new()->schema->resultset('Borrower')
3643
    recordpayment( $borrower->{borrowernumber}, $amount );
3627
              ->single( { cardnumber => $operation->{cardnumber} } ),
3628
            amount => $operation->{amount},
3629
            notes  => 'via offline circulation',
3630
        }
3631
    );
3644
3632
3645
    return "Success."
3633
    return "Success."
3646
}
3634
}
(-)a/C4/ILSDI/Services.pm (-5 / +4 lines)
Lines 24-30 use C4::Members; Link Here
24
use C4::Items;
24
use C4::Items;
25
use C4::Circulation;
25
use C4::Circulation;
26
use C4::Branch;
26
use C4::Branch;
27
use C4::Accounts;
28
use C4::Biblio;
27
use C4::Biblio;
29
use C4::Reserves qw(AddReserve CancelReserve GetReservesFromBiblionumber GetReservesFromBorrowernumber CanBookBeReserved CanItemBeReserved);
28
use C4::Reserves qw(AddReserve CancelReserve GetReservesFromBiblionumber GetReservesFromBorrowernumber CanBookBeReserved CanItemBeReserved);
30
use C4::Context;
29
use C4::Context;
Lines 34-39 use HTML::Entities; Link Here
34
use CGI;
33
use CGI;
35
use DateTime;
34
use DateTime;
36
use C4::Auth;
35
use C4::Auth;
36
use Koha::Database;
37
37
38
=head1 NAME
38
=head1 NAME
39
39
Lines 387-396 sub GetPatronInfo { Link Here
387
387
388
    # Fines management
388
    # Fines management
389
    if ( $cgi->param('show_fines') eq "1" ) {
389
    if ( $cgi->param('show_fines') eq "1" ) {
390
        my @charges;
390
        my @charges =
391
        for ( my $i = 1 ; my @charge = getcharges( $borrowernumber, undef, $i ) ; $i++ ) {
391
          Koha::Database->new()->schema()->resultset('AccountDebit')
392
            push( @charges, @charge );
392
          ->search( { borrowernumber => $borrowernumber } );
393
        }
394
        $borrower->{'fines'}->{'fine'} = \@charges;
393
        $borrower->{'fines'}->{'fine'} = \@charges;
395
    }
394
    }
396
395
(-)a/C4/Members.pm (-134 / +55 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 356-364 sub GetMemberDetails { Link Here
356
    }
354
    }
357
    my $borrower = $sth->fetchrow_hashref;
355
    my $borrower = $sth->fetchrow_hashref;
358
    return unless $borrower;
356
    return unless $borrower;
359
    my ($amount) = GetMemberAccountRecords( $borrowernumber);
357
    $borrower->{amountoutstanding} = $borrower->{account_balance};
360
    $borrower->{'amountoutstanding'} = $amount;
358
    # FIXME - find all references to $borrower->{amountoutstanding}, replace with $borrower->{account_balance}
361
    # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
362
    my $flags = patronflags( $borrower);
359
    my $flags = patronflags( $borrower);
363
    my $accessflagshash;
360
    my $accessflagshash;
364
361
Lines 462-484 The "message" field that comes from the DB is OK. Link Here
462
# FIXME rename this function.
459
# FIXME rename this function.
463
sub patronflags {
460
sub patronflags {
464
    my %flags;
461
    my %flags;
465
    my ( $patroninformation) = @_;
462
    my ($patroninformation) = @_;
466
    my $dbh=C4::Context->dbh;
463
    my $dbh = C4::Context->dbh;
467
    my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
464
    if ( $patroninformation->{account_balance} > 0 ) {
468
    if ( $owing > 0 ) {
469
        my %flaginfo;
465
        my %flaginfo;
470
        my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
466
        my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
471
        $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
467
        $flaginfo{'amount'}  = $patroninformation->{account_balance};
472
        $flaginfo{'amount'}  = sprintf "%.02f", $owing;
468
        if (  $patroninformation->{account_balance} > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
473
        if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
474
            $flaginfo{'noissues'} = 1;
469
            $flaginfo{'noissues'} = 1;
475
        }
470
        }
476
        $flags{'CHARGES'} = \%flaginfo;
471
        $flags{'CHARGES'} = \%flaginfo;
477
    }
472
    }
478
    elsif ( $balance < 0 ) {
473
    elsif ( $patroninformation->{account_balance} < 0 ) {
479
        my %flaginfo;
474
        my %flaginfo;
480
        $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
475
        $flaginfo{'amount'}  = $patroninformation->{account_balance};
481
        $flaginfo{'amount'}  = sprintf "%.02f", $balance;
482
        $flags{'CREDITS'} = \%flaginfo;
476
        $flags{'CREDITS'} = \%flaginfo;
483
    }
477
    }
484
    if (   $patroninformation->{'gonenoaddress'}
478
    if (   $patroninformation->{'gonenoaddress'}
Lines 721-727 sub GetMemberIssuesAndFines { Link Here
721
    $sth->execute($borrowernumber);
715
    $sth->execute($borrowernumber);
722
    my $overdue_count = $sth->fetchrow_arrayref->[0];
716
    my $overdue_count = $sth->fetchrow_arrayref->[0];
723
717
724
    $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
718
    $sth = $dbh->prepare("SELECT account_balance FROM borrowers WHERE borrowernumber = ?");
725
    $sth->execute($borrowernumber);
719
    $sth->execute($borrowernumber);
726
    my $total_fines = $sth->fetchrow_arrayref->[0];
720
    my $total_fines = $sth->fetchrow_arrayref->[0];
727
721
Lines 1207-1263 sub GetAllIssues { Link Here
1207
}
1201
}
1208
1202
1209
1203
1210
=head2 GetMemberAccountRecords
1211
1212
  ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1213
1214
Looks up accounting data for the patron with the given borrowernumber.
1215
1216
C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1217
reference-to-array, where each element is a reference-to-hash; the
1218
keys are the fields of the C<accountlines> table in the Koha database.
1219
C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1220
total amount outstanding for all of the account lines.
1221
1222
=cut
1223
1224
sub GetMemberAccountRecords {
1225
    my ($borrowernumber) = @_;
1226
    my $dbh = C4::Context->dbh;
1227
    my @acctlines;
1228
    my $numlines = 0;
1229
    my $strsth      = qq(
1230
                        SELECT * 
1231
                        FROM accountlines 
1232
                        WHERE borrowernumber=?);
1233
    $strsth.=" ORDER BY date desc,timestamp DESC";
1234
    my $sth= $dbh->prepare( $strsth );
1235
    $sth->execute( $borrowernumber );
1236
1237
    my $total = 0;
1238
    while ( my $data = $sth->fetchrow_hashref ) {
1239
        if ( $data->{itemnumber} ) {
1240
            my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1241
            $data->{biblionumber} = $biblio->{biblionumber};
1242
            $data->{title}        = $biblio->{title};
1243
        }
1244
        $acctlines[$numlines] = $data;
1245
        $numlines++;
1246
        $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1247
    }
1248
    $total /= 1000;
1249
    return ( $total, \@acctlines,$numlines);
1250
}
1251
1252
=head2 GetMemberAccountBalance
1204
=head2 GetMemberAccountBalance
1253
1205
1254
  ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1206
  ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1255
1207
1256
Calculates amount immediately owing by the patron - non-issue charges.
1208
Calculates amount immediately owing by the patron - non-issue charges.
1257
Based on GetMemberAccountRecords.
1258
Charges exempt from non-issue are:
1209
Charges exempt from non-issue are:
1259
* Res (reserves)
1210
* HOLD fees (reserves)
1260
* Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1211
* RENTAL if RentalsInNoissuesCharge syspref is set to false
1261
* Manual invoices if ManInvInNoissuesCharge syspref is set to false
1212
* Manual invoices if ManInvInNoissuesCharge syspref is set to false
1262
1213
1263
=cut
1214
=cut
Lines 1265-1334 Charges exempt from non-issue are: Link Here
1265
sub GetMemberAccountBalance {
1216
sub GetMemberAccountBalance {
1266
    my ($borrowernumber) = @_;
1217
    my ($borrowernumber) = @_;
1267
1218
1268
    my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1219
    my $borrower =
1220
      Koha::Database->new()->schema->resultset('Borrower')
1221
      ->find($borrowernumber);
1269
1222
1270
    my @not_fines = ('Res');
1223
    my @not_fines;
1271
    push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1272
    unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1273
        my $dbh = C4::Context->dbh;
1274
        my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1275
        push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1276
    }
1277
    my %not_fine = map {$_ => 1} @not_fines;
1278
1279
    my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1280
    my $other_charges = 0;
1281
    foreach (@$acctlines) {
1282
        $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1283
    }
1284
1285
    return ( $total, $total - $other_charges, $other_charges);
1286
}
1287
1224
1288
=head2 GetBorNotifyAcctRecord
1225
    push( @not_fines, Koha::Accounts::DebitTypes::Hold() );
1289
1226
1290
  ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1227
    push( @not_fines, Koha::Accounts::DebitTypes::Rental() )
1228
      unless C4::Context->preference('RentalsInNoissuesCharge');
1291
1229
1292
Looks up accounting data for the patron with the given borrowernumber per file number.
1230
    unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1293
1231
        my $dbh           = C4::Context->dbh;
1294
C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1232
        my $man_inv_types = $dbh->selectcol_arrayref(q{
1295
reference-to-array, where each element is a reference-to-hash; the
1233
            SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'
1296
keys are the fields of the C<accountlines> table in the Koha database.
1234
        });
1297
C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1235
        push( @not_fines, @$man_inv_types );
1298
total amount outstanding for all of the account lines.
1236
    }
1299
1300
=cut
1301
1237
1302
sub GetBorNotifyAcctRecord {
1238
    my $other_charges =
1303
    my ( $borrowernumber, $notifyid ) = @_;
1239
      Koha::Database->new()->schema->resultset('AccountDebit')->search(
1304
    my $dbh = C4::Context->dbh;
1240
        {
1305
    my @acctlines;
1241
            borrowernumber => $borrowernumber,
1306
    my $numlines = 0;
1242
            type           => { -in => \@not_fines }
1307
    my $sth = $dbh->prepare(
1308
            "SELECT * 
1309
                FROM accountlines 
1310
                WHERE borrowernumber=? 
1311
                    AND notify_id=? 
1312
                    AND amountoutstanding != '0' 
1313
                ORDER BY notify_id,accounttype
1314
                ");
1315
1316
    $sth->execute( $borrowernumber, $notifyid );
1317
    my $total = 0;
1318
    while ( my $data = $sth->fetchrow_hashref ) {
1319
        if ( $data->{itemnumber} ) {
1320
            my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1321
            $data->{biblionumber} = $biblio->{biblionumber};
1322
            $data->{title}        = $biblio->{title};
1323
        }
1243
        }
1324
        $acctlines[$numlines] = $data;
1244
      )->get_column('amount_outstanding')->sum();
1325
        $numlines++;
1245
1326
        $total += int(100 * $data->{'amountoutstanding'});
1246
    return (
1327
    }
1247
        $borrower->account_balance(),
1328
    $total /= 100;
1248
        $borrower->account_balance() - $other_charges,
1329
    return ( $total, \@acctlines, $numlines );
1249
        $other_charges
1250
    );
1330
}
1251
}
1331
1252
1253
1332
=head2 checkuniquemember (OUEST-PROVENCE)
1254
=head2 checkuniquemember (OUEST-PROVENCE)
1333
1255
1334
  ($result,$categorycode)  = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1256
  ($result,$categorycode)  = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
Lines 2459-2480 Add enrolment fee for a patron if needed. Link Here
2459
2381
2460
sub AddEnrolmentFeeIfNeeded {
2382
sub AddEnrolmentFeeIfNeeded {
2461
    my ( $categorycode, $borrowernumber ) = @_;
2383
    my ( $categorycode, $borrowernumber ) = @_;
2462
    # check for enrollment fee & add it if needed
2384
2463
    my $dbh = C4::Context->dbh;
2385
    my $schema = Koha::Database->new()->schema();
2464
    my $sth = $dbh->prepare(q{
2386
2465
        SELECT enrolmentfee
2387
    my $category = $schema->resultset('Category')->find($categorycode);
2466
        FROM categories
2388
    my $fee      = $category->enrolmentfee();
2467
        WHERE categorycode=?
2389
2468
    });
2390
    if ( $fee && $fee > 0 ) {
2469
    $sth->execute( $categorycode );
2391
        AddDebit(
2470
    if ( $sth->err ) {
2392
            {
2471
        warn sprintf('Database returned the following error: %s', $sth->errstr);
2393
                borrower =>
2472
        return;
2394
                  $schema->resultset('Borrower')->find($borrowernumber),
2473
    }
2395
                type   => Koha::Accounts::DebitTypes::AccountManagementFee(),
2474
    my ($enrolmentfee) = $sth->fetchrow;
2396
                amount => $fee,
2475
    if ($enrolmentfee && $enrolmentfee > 0) {
2397
            }
2476
        # insert fee in patron debts
2398
        );
2477
        C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2478
    }
2399
    }
2479
}
2400
}
2480
2401
(-)a/C4/Overdues.pm (-231 / +116 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 ( $fine->accruing() ) { # Don't update or recreate fines no longer accruing
555
            my $out  = $data->{'amountoutstanding'} + $diff;
519
            if (
556
            my $query = "
520
                sprintf( "%.6f", $fine->amount_original() )
557
                UPDATE accountlines
521
                ne
558
				SET date=now(), amount=?, amountoutstanding=?,
522
                sprintf( "%.6f", $amount ) )
559
					lastincrement=?, accounttype='FU'
523
            {
560
	  			WHERE borrowernumber=?
524
                my $difference = $amount - $fine->amount_original();
561
				AND   itemnumber=?
525
562
				AND   accounttype IN ('FU','O')
526
                $fine->amount_original( $fine->amount_original() + $difference );
563
				AND   description LIKE ?
527
                $fine->amount_outstanding( $fine->amount_outstanding() + $difference );
564
				LIMIT 1 ";
528
                $fine->amount_last_increment($difference);
565
            my $sth2 = $dbh->prepare($query);
529
                $fine->updated_on($timestamp);
566
			# FIXME: BOGUS query cannot ensure uniqueness w/ LIKE %x% !!!
530
                $fine->update();
567
			# 		LIMIT 1 added to prevent multiple affected lines
531
568
			# FIXME: accountlines table needs unique key!! Possibly a combo of borrowernumber and accountline.  
532
                $offset = 1;
569
			# 		But actually, we should just have a regular autoincrementing PK and forget accountline,
533
            }
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
        }
534
        }
578
    } else {
535
    }
579
        my $sth4 = $dbh->prepare(
536
    else {
580
            "SELECT title FROM biblio LEFT JOIN items ON biblio.biblionumber=items.biblionumber WHERE items.itemnumber=?"
537
        my $item = $schema->resultset('Item')->find($itemnumber);
538
539
        $fine = $schema->resultset('AccountDebit')->create(
540
            {
541
                borrowernumber        => $borrowernumber,
542
                itemnumber            => $itemnumber,
543
                issue_id              => $issue_id,
544
                type                  => Koha::Accounts::DebitTypes::Fine(),
545
                accruing              => 1,
546
                amount_original       => $amount,
547
                amount_outstanding    => $amount,
548
                amount_last_increment => $amount,
549
                description           => $item->biblio()->title() . " / Due:$due",
550
                created_on            => $timestamp,
551
            }
581
        );
552
        );
582
        $sth4->execute($itemnum);
553
583
        my $title = $sth4->fetchrow;
554
        $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
    }
555
    }
603
    # logging action
556
604
    &logaction(
557
    $schema->resultset('AccountOffset')->create(
605
        "FINES",
558
        {
606
        $type,
559
            debit_id   => $fine->debit_id(),
560
            amount     => $fine->amount_last_increment(),
561
            created_on => $timestamp,
562
            type       => Koha::Accounts::OffsetTypes::Fine(),
563
        }
564
    ) if $offset;
565
566
    $borrower->account_balance( $borrower->account_balance + $fine->amount_last_increment() );
567
    $borrower->update();
568
569
    logaction( "FINES", Koha::Accounts::DebitTypes::Fine(),
607
        $borrowernumber,
570
        $borrowernumber,
608
        "due=".$due."  amount=".$amount." itemnumber=".$itemnum
571
        "due=" . $due . "  amount=" . $amount . " itemnumber=" . $itemnumber )
609
        ) if C4::Context->preference("FinesLog");
572
      if C4::Context->preference("FinesLog");
610
}
573
}
611
574
612
=head2 BorType
575
=head2 BorType
Lines 647-716 C<$borrowernumber> is the borrowernumber Link Here
647
=cut 
610
=cut 
648
611
649
sub GetFine {
612
sub GetFine {
650
    my ( $itemnum, $borrowernumber ) = @_;
613
    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
614
664
=head2 NumberNotifyId
615
    my $schema = Koha::Database->new()->schema;
665
616
666
    (@notify) = &NumberNotifyId($borrowernumber);
617
    my $amount_outstanding = $schema->resultset('AccountDebit')->search(
667
618
        {
668
Returns amount for all file per borrowers
619
            itemnumber     => $itemnumber,
669
C<@notify> array contains all file per borrowers
620
            borrowernumber => $borrowernumber,
670
621
            type           => Koha::Accounts::DebitTypes::Fine(),
671
C<$notify_id> contains the file number for the borrower number nad item number
622
        },
672
623
    )->get_column('amount_outstanding')->sum();
673
=cut
674
624
675
sub NumberNotifyId{
625
    return $amount_outstanding;
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
690
=head2 AmountNotify
691
692
    ($totalnotify) = &AmountNotify($notifyid);
693
694
Returns amount for all file per borrowers
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
}
626
}
715
627
716
=head2 GetItems
628
=head2 GetItems
Lines 762-788 sub GetBranchcodesWithOverdueRules { Link Here
762
    return @branches;
674
    return @branches;
763
}
675
}
764
676
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
677
=head2 GetOverduesForBranch
787
678
788
Sql request for display all information for branchoverdues.pl
679
Sql request for display all information for branchoverdues.pl
Lines 808-813 sub GetOverduesForBranch { Link Here
808
               biblio.title,
699
               biblio.title,
809
               biblio.author,
700
               biblio.author,
810
               biblio.biblionumber,
701
               biblio.biblionumber,
702
               issues.issue_id,
811
               issues.date_due,
703
               issues.date_due,
812
               issues.returndate,
704
               issues.returndate,
813
               issues.branchcode,
705
               issues.branchcode,
Lines 818-842 sub GetOverduesForBranch { Link Here
818
                items.location,
710
                items.location,
819
                items.itemnumber,
711
                items.itemnumber,
820
            itemtypes.description,
712
            itemtypes.description,
821
         accountlines.notify_id,
713
            account_debits.amount_outstanding
822
         accountlines.notify_level,
714
    FROM  account_debits
823
         accountlines.amountoutstanding
715
    LEFT JOIN issues      ON    issues.itemnumber     = account_debits.itemnumber
824
    FROM  accountlines
716
                          AND   issues.borrowernumber = account_debits.borrowernumber
825
    LEFT JOIN issues      ON    issues.itemnumber     = accountlines.itemnumber
717
    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
718
    LEFT JOIN items       ON     items.itemnumber     = issues.itemnumber
829
    LEFT JOIN biblio      ON      biblio.biblionumber =  items.biblionumber
719
    LEFT JOIN biblio      ON      biblio.biblionumber =  items.biblionumber
830
    LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
720
    LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
831
    LEFT JOIN itemtypes   ON itemtypes.itemtype       = $itype_link
721
    LEFT JOIN itemtypes   ON itemtypes.itemtype       = $itype_link
832
    LEFT JOIN branches    ON  branches.branchcode     = issues.branchcode
722
    LEFT JOIN branches    ON  branches.branchcode     = issues.branchcode
833
    WHERE (accountlines.amountoutstanding  != '0.000000')
723
    WHERE (account_debits.amount_outstanding  != '0.000000')
834
      AND (accountlines.accounttype         = 'FU'      )
724
      AND (account_debits.type = 'FINE')
725
      AND (account_debits.accruing = 1 )
835
      AND (issues.branchcode =  ?   )
726
      AND (issues.branchcode =  ?   )
836
      AND (issues.date_due  < NOW())
727
      AND (issues.date_due  < NOW())
837
    ";
728
    ";
838
    my @getoverdues;
729
    my @getoverdues;
839
    my $i = 0;
840
    my $sth;
730
    my $sth;
841
    if ($location) {
731
    if ($location) {
842
        $sth = $dbh->prepare("$select AND items.location = ? ORDER BY borrowers.surname, borrowers.firstname");
732
        $sth = $dbh->prepare("$select AND items.location = ? ORDER BY borrowers.surname, borrowers.firstname");
Lines 846-857 sub GetOverduesForBranch { Link Here
846
        $sth->execute($branch);
736
        $sth->execute($branch);
847
    }
737
    }
848
    while ( my $data = $sth->fetchrow_hashref ) {
738
    while ( my $data = $sth->fetchrow_hashref ) {
849
    #check if the document has already been notified
739
        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
    }
740
    }
856
    return (@getoverdues);
741
    return (@getoverdues);
857
}
742
}
(-)a/C4/Reports/Guided.pm (-10 / +19 lines)
Lines 92-109 my %table_areas = ( Link Here
92
    CAT  => [ 'items', 'biblioitems', 'biblio' ],
92
    CAT  => [ 'items', 'biblioitems', 'biblio' ],
93
    PAT  => ['borrowers'],
93
    PAT  => ['borrowers'],
94
    ACQ  => [ 'aqorders', 'biblio', 'items' ],
94
    ACQ  => [ 'aqorders', 'biblio', 'items' ],
95
    ACC  => [ 'borrowers', 'accountlines' ],
95
    ACC  => [ 'borrowers', 'account_credits', 'account_debits' ],
96
);
96
);
97
my %keys = (
97
my %keys = (
98
    CIRC => [ 'statistics.borrowernumber=borrowers.borrowernumber',
98
    CIRC => [
99
              'items.itemnumber = statistics.itemnumber',
99
        'statistics.borrowernumber=borrowers.borrowernumber',
100
              'biblioitems.biblioitemnumber = items.biblioitemnumber' ],
100
        'items.itemnumber = statistics.itemnumber',
101
    CAT  => [ 'items.biblioitemnumber=biblioitems.biblioitemnumber',
101
        'biblioitems.biblioitemnumber = items.biblioitemnumber'
102
              'biblioitems.biblionumber=biblio.biblionumber' ],
102
    ],
103
    PAT  => [],
103
    CAT => [
104
    ACQ  => [ 'aqorders.biblionumber=biblio.biblionumber',
104
        'items.biblioitemnumber=biblioitems.biblioitemnumber',
105
              'biblio.biblionumber=items.biblionumber' ],
105
        'biblioitems.biblionumber=biblio.biblionumber'
106
    ACC  => ['borrowers.borrowernumber=accountlines.borrowernumber'],
106
    ],
107
    PAT => [],
108
    ACQ => [
109
        'aqorders.biblionumber=biblio.biblionumber',
110
        'biblio.biblionumber=items.biblionumber'
111
    ],
112
    ACC => [
113
        'borrowers.borrowernumber=account_credits.borrowernumber',
114
        'borrowers.borrowernumber=account_debits.borrowernumber'
115
    ],
107
);
116
);
108
117
109
# have to do someting here to know if its dropdown, free text, date etc
118
# have to do someting here to know if its dropdown, free text, date etc
(-)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 (-4 / +15 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::Accounts::CreditTypes;
25
use Koha::Database;
24
use ILS;
26
use ILS;
25
use parent qw(ILS::Transaction);
27
use parent qw(ILS::Transaction);
26
28
Lines 45-54 sub new { Link Here
45
sub pay {
47
sub pay {
46
    my $self           = shift;
48
    my $self           = shift;
47
    my $borrowernumber = shift;
49
    my $borrowernumber = shift;
48
    my $amt            = shift;
50
    my $amount         = shift;
49
    my $type           = shift;
51
    my $type           = shift;
50
    warn("RECORD:$borrowernumber::$amt");
52
51
    recordpayment( $borrowernumber, $amt,$type );
53
    warn("RECORD:$borrowernumber::$amount");
54
55
    AddCredit(
56
        {
57
            borrower => Koha::Database->new()->schema->resultset('Borrower')->find($borrowernumber),
58
            amount => $amount,
59
            notes  => "via SIP2. Type:$type",
60
            type   => Koha::Accounts::CreditTypes::Payment,
61
        }
62
    );
52
}
63
}
53
64
54
#sub DESTROY {
65
#sub DESTROY {
(-)a/Koha/DateUtils.pm (-1 / +6 lines)
Lines 21-33 use warnings; Link Here
21
use 5.010;
21
use 5.010;
22
use DateTime;
22
use DateTime;
23
use DateTime::Format::DateParse;
23
use DateTime::Format::DateParse;
24
use DateTime::Format::MySQL;
24
use C4::Context;
25
use C4::Context;
25
26
26
use base 'Exporter';
27
use base 'Exporter';
27
use version; our $VERSION = qv('1.0.0');
28
use version; our $VERSION = qv('1.0.0');
28
29
29
our @EXPORT = (
30
our @EXPORT = (
30
    qw( dt_from_string output_pref format_sqldatetime )
31
    qw( dt_from_string output_pref format_sqldatetime get_timestamp )
31
);
32
);
32
33
33
=head1 DateUtils
34
=head1 DateUtils
Lines 190-193 sub format_sqldatetime { Link Here
190
    return q{};
191
    return q{};
191
}
192
}
192
193
194
sub get_timestamp {
195
    return DateTime::Format::MySQL->format_datetime( dt_from_string() );
196
}
197
193
1;
198
1;
(-)a/Koha/Template/Plugin/AuthorisedValues.pm (+2 lines)
Lines 74-76 Kyle M Hall <kyle@bywatersolutions.com> Link Here
74
Jonathan Druart <jonathan.druart@biblibre.com>
74
Jonathan Druart <jonathan.druart@biblibre.com>
75
75
76
=cut
76
=cut
77
78
1;
(-)a/Koha/Template/Plugin/Koha.pm (-1 / +5 lines)
Lines 44-47 sub Preference { Link Here
44
    return C4::Context->preference( $pref );
44
    return C4::Context->preference( $pref );
45
}
45
}
46
46
47
sub Get {
48
    my ( $self, $category, $selected, $opac ) = @_;
49
    return GetAuthorisedValues( $category, $selected, $opac );
50
}
51
47
1;
52
1;
48
- 

Return to bug 6427