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

(-)a/C4/Circulation.pm (-187 / +177 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 Koha::Accounts::CreditTypes;
34
use C4::ItemCirculationAlertPreference;
35
use C4::ItemCirculationAlertPreference;
35
use C4::Message;
36
use C4::Message;
36
use C4::Debug;
37
use C4::Debug;
Lines 48-53 use Data::Dumper; Link Here
48
use Koha::DateUtils;
49
use Koha::DateUtils;
49
use Koha::Calendar;
50
use Koha::Calendar;
50
use Koha::Borrower::Debarments;
51
use Koha::Borrower::Debarments;
52
use Koha::Database;
51
use Carp;
53
use Carp;
52
use Date::Calc qw(
54
use Date::Calc qw(
53
  Today
55
  Today
Lines 1280-1286 sub AddIssue { Link Here
1280
        ## If item was lost, it has now been found, reverse any list item charges if neccessary.
1282
        ## If item was lost, it has now been found, reverse any list item charges if neccessary.
1281
        if ( $item->{'itemlost'} ) {
1283
        if ( $item->{'itemlost'} ) {
1282
            if ( C4::Context->preference('RefundLostItemFeeOnReturn' ) ) {
1284
            if ( C4::Context->preference('RefundLostItemFeeOnReturn' ) ) {
1283
                _FixAccountForLostAndReturned( $item->{'itemnumber'}, undef, $item->{'barcode'} );
1285
                _FixAccountForLostAndReturned( $item->{'itemnumber'} );
1284
            }
1286
            }
1285
        }
1287
        }
1286
1288
Lines 1845-1865 sub AddReturn { Link Here
1845
1847
1846
                $type ||= q{};
1848
                $type ||= q{};
1847
1849
1848
                if ( C4::Context->preference('finesMode') eq 'production' ) {
1850
                if ( $amount > 0
1849
                    if ( $amount > 0 ) {
1851
                    && C4::Context->preference('finesMode') eq 'production' )
1850
                        C4::Overdues::UpdateFine( $issue->{itemnumber},
1852
                {
1851
                            $issue->{borrowernumber},
1853
                    C4::Overdues::UpdateFine(
1852
                            $amount, $type, output_pref($datedue) );
1854
                        {
1853
                    }
1855
                            itemnumber     => $issue->{itemnumber},
1854
                    elsif ($return_date) {
1856
                            borrowernumber => $issue->{borrowernumber},
1855
1857
                            amount         => $amount,
1856
                       # Backdated returns may have fines that shouldn't exist,
1858
                            due            => output_pref($datedue),
1857
                       # so in this case, we need to drop those fines to 0
1859
                            issue_id       => $issue->{issue_id}
1858
1860
                        }
1859
                        C4::Overdues::UpdateFine( $issue->{itemnumber},
1861
                    );
1860
                            $issue->{borrowernumber},
1862
                }
1861
                            0, $type, output_pref($datedue) );
1863
                elsif ($return_date) {
1862
                    }
1864
1865
                    # Backdated returns may have fines that shouldn't exist,
1866
                    # so in this case, we need to drop those fines to 0
1867
                    C4::Overdues::UpdateFine(
1868
                        {
1869
                            itemnumber     => $issue->{itemnumber},
1870
                            borrowernumber => $issue->{borrowernumber},
1871
                            amount         => 0,
1872
                            due            => output_pref($datedue),
1873
                            issue_id       => $issue->{issue_id}
1874
                        }
1875
                    );
1863
                }
1876
                }
1864
            }
1877
            }
1865
1878
Lines 1909-1923 sub AddReturn { Link Here
1909
        $messages->{'WasLost'} = 1;
1922
        $messages->{'WasLost'} = 1;
1910
1923
1911
        if ( C4::Context->preference('RefundLostItemFeeOnReturn' ) ) {
1924
        if ( C4::Context->preference('RefundLostItemFeeOnReturn' ) ) {
1912
            _FixAccountForLostAndReturned($item->{'itemnumber'}, $borrowernumber, $barcode);    # can tolerate undef $borrowernumber
1925
            _FixAccountForLostAndReturned( $item->{'itemnumber'} );
1913
            $messages->{'LostItemFeeRefunded'} = 1;
1926
            $messages->{'LostItemFeeRefunded'} = 1;
1914
        }
1927
        }
1915
    }
1928
    }
1916
1929
1917
    # fix up the overdues in accounts...
1930
    # fix up the overdues in accounts...
1918
    if ($borrowernumber) {
1931
    if ($borrowernumber) {
1919
        my $fix = _FixOverduesOnReturn($borrowernumber, $item->{itemnumber}, $exemptfine, $dropbox);
1932
        _FixOverduesOnReturn(
1920
        defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $item->{itemnumber}...) failed!";  # zero is OK, check defined
1933
            {
1934
                exempt_fine => $exemptfine,
1935
                dropbox     => $dropbox,
1936
                issue       => $issue,
1937
            }
1938
        );
1921
        
1939
        
1922
        if ( $issue->{overdue} && $issue->{date_due} ) {
1940
        if ( $issue->{overdue} && $issue->{date_due} ) {
1923
        # fix fine days
1941
        # fix fine days
Lines 2026-2035 of the return. It is ignored when a dropbox_branch is passed in. Link Here
2026
C<$privacy> contains the privacy parameter. If the patron has set privacy to 2,
2044
C<$privacy> contains the privacy parameter. If the patron has set privacy to 2,
2027
the old_issue is immediately anonymised
2045
the old_issue is immediately anonymised
2028
2046
2029
Ideally, this function would be internal to C<C4::Circulation>,
2030
not exported, but it is currently needed by one 
2031
routine in C<C4::Accounts>.
2032
2033
=cut
2047
=cut
2034
2048
2035
sub MarkIssueReturned {
2049
sub MarkIssueReturned {
Lines 2165-2303 Internal function, called only by AddReturn Link Here
2165
=cut
2179
=cut
2166
2180
2167
sub _FixOverduesOnReturn {
2181
sub _FixOverduesOnReturn {
2168
    my ($borrowernumber, $item);
2182
    my ( $params ) = @_;
2169
    unless ($borrowernumber = shift) {
2183
2170
        warn "_FixOverduesOnReturn() not supplied valid borrowernumber";
2184
    my $exemptfine = $params->{exempt_fine};
2171
        return;
2185
    my $dropbox    = $params->{dropbox};
2172
    }
2186
    my $issue      = $params->{issue};
2173
    unless ($item = shift) {
2187
2174
        warn "_FixOverduesOnReturn() not supplied valid itemnumber";
2175
        return;
2176
    }
2177
    my ($exemptfine, $dropbox) = @_;
2178
    my $dbh = C4::Context->dbh;
2188
    my $dbh = C4::Context->dbh;
2179
2189
2180
    # check for overdue fine
2190
    my $schema = Koha::Database->new()->schema;
2181
    my $sth = $dbh->prepare(
2191
    my $fine =
2182
"SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
2192
      $schema->resultset('AccountDebit')
2183
    );
2193
      ->single( { issue_id => $issue->issue_id(), type => Koha::Accounts::DebitTypes::Fine() } );
2184
    $sth->execute( $borrowernumber, $item );
2185
2194
2186
    # alter fine to show that the book has been returned
2195
    return unless ( $fine );
2187
    my $data = $sth->fetchrow_hashref;
2196
2188
    return 0 unless $data;    # no warning, there's just nothing to fix
2197
    $fine->accruing(0);
2189
2198
2190
    my $uquery;
2191
    my @bind = ($data->{'accountlines_id'});
2192
    if ($exemptfine) {
2199
    if ($exemptfine) {
2193
        $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
2200
        AddCredit(
2194
        if (C4::Context->preference("FinesLog")) {
2201
            {
2195
            &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
2202
                borrower => $fine->borrowernumber(),
2196
        }
2203
                amount   => $fine->amount_original(),
2197
    } elsif ($dropbox && $data->{lastincrement}) {
2204
                debit_id => $fine->debit_id(),
2198
        my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
2205
                type     => Koha::Accounts::CreditTypes::Forgiven(),
2199
        my $amt = $data->{amount} - $data->{lastincrement} ;
2206
            }
2207
        );
2200
        if (C4::Context->preference("FinesLog")) {
2208
        if (C4::Context->preference("FinesLog")) {
2201
            &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
2209
            &logaction(
2202
        }
2210
                "FINES", 'MODIFY',
2203
         $uquery = "update accountlines set accounttype='F' ";
2211
                $issue->{borrowernumber},
2204
         if($outstanding  >= 0 && $amt >=0) {
2212
                "Overdue forgiven: item " . $issue->{itemnumber}
2205
            $uquery .= ", amount = ? , amountoutstanding=? ";
2213
            );
2206
            unshift @bind, ($amt, $outstanding) ;
2207
        }
2214
        }
2208
    } else {
2215
    } elsif ($dropbox && $fine->amount_last_increment() != $fine->amount_original() ) {
2209
        $uquery = "update accountlines set accounttype='F' ";
2216
        if ( C4::Context->preference("FinesLog") ) {
2217
            &logaction( "FINES", 'MODIFY', $issue->{borrowernumber},
2218
                    "Dropbox adjustment "
2219
                  . $fine->amount_last_increment()
2220
                  . ", item " . $issue->{itemnumber} );
2221
        }
2222
        $fine->amount_original(
2223
            $fine->amount_original() - $fine->amount_last_increment() );
2224
        $fine->amount_outstanding(
2225
            $fine->amount_outstanding - $fine->amount_last_increment() );
2226
        $schema->resultset('AccountOffset')->create(
2227
            {
2228
                debit_id => $fine->debit_id(),
2229
                type     => Koha::Accounts::OffsetTypes::Dropbox(),
2230
                amount   => $fine->amount_last_increment() * -1,
2231
            }
2232
        );
2210
    }
2233
    }
2211
    $uquery .= " where (accountlines_id = ?)";
2234
2212
    my $usth = $dbh->prepare($uquery);
2235
    return $fine->update();
2213
    return $usth->execute(@bind);
2214
}
2236
}
2215
2237
2216
=head2 _FixAccountForLostAndReturned
2238
=head2 _FixAccountForLostAndReturned
2217
2239
2218
  &_FixAccountForLostAndReturned($itemnumber, [$borrowernumber, $barcode]);
2240
  &_FixAccountForLostAndReturned($itemnumber);
2219
2220
Calculates the charge for a book lost and returned.
2221
2222
Internal function, not exported, called only by AddReturn.
2223
2241
2224
FIXME: This function reflects how inscrutable fines logic is.  Fix both.
2242
  Refunds a lost item fee in necessary
2225
FIXME: Give a positive return value on success.  It might be the $borrowernumber who received credit, or the amount forgiven.
2226
2243
2227
=cut
2244
=cut
2228
2245
2229
sub _FixAccountForLostAndReturned {
2246
sub _FixAccountForLostAndReturned {
2230
    my $itemnumber     = shift or return;
2247
    my ( $itemnumber ) = @_;
2231
    my $borrowernumber = @_ ? shift : undef;
2248
2232
    my $item_id        = @_ ? shift : $itemnumber;  # Send the barcode if you want that logged in the description
2249
    my $schema = Koha::Database->new()->schema;
2233
    my $dbh = C4::Context->dbh;
2250
2234
    # check for charge made for lost book
2251
    # Find the last issue for this item
2235
    my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE itemnumber = ? AND accounttype IN ('L', 'Rep', 'W') ORDER BY date DESC, accountno DESC");
2252
    my $issue =
2236
    $sth->execute($itemnumber);
2253
      $schema->resultset('Issue')->single( { itemnumber => $itemnumber } );
2237
    my $data = $sth->fetchrow_hashref;
2254
    $issue ||=
2238
    $data or return;    # bail if there is nothing to do
2255
      $schema->resultset('OldIssue')->single( { itemnumber => $itemnumber } );
2239
    $data->{accounttype} eq 'W' and return;    # Written off
2256
2240
2257
    return unless $issue;
2241
    # writeoff this amount
2258
2242
    my $offset;
2259
    # Find a lost fee for this issue
2243
    my $amount = $data->{'amount'};
2260
    my $debit = $schema->resultset('AccountDebit')->single(
2244
    my $acctno = $data->{'accountno'};
2261
        {
2245
    my $amountleft;                                             # Starts off undef/zero.
2262
            issue_id => $issue->issue_id(),
2246
    if ($data->{'amountoutstanding'} == $amount) {
2263
            type     => Koha::Accounts::DebitTypes::Lost()
2247
        $offset     = $data->{'amount'};
2264
        }
2248
        $amountleft = 0;                                        # Hey, it's zero here, too.
2265
    );
2249
    } else {
2266
2250
        $offset     = $amount - $data->{'amountoutstanding'};   # Um, isn't this the same as ZERO?  We just tested those two things are ==
2267
    return unless $debit;
2251
        $amountleft = $data->{'amountoutstanding'} - $amount;   # Um, isn't this the same as ZERO?  We just tested those two things are ==
2268
2252
    }
2269
    # Check for an existing found credit for this debit, if there is one, the fee has already been refunded and we do nothing
2253
    my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
2270
    my @credits = $debit->account_offsets->search_related('credit', { 'credit.type' => Koha::Accounts::CreditTypes::Found() });
2254
        WHERE (accountlines_id = ?)");
2271
2255
    $usth->execute($data->{'accountlines_id'});      # We might be adjusting an account for some OTHER borrowernumber now.  Not the one we passed in.
2272
    return if @credits;
2256
    #check if any credit is left if so writeoff other accounts
2273
2257
    my $nextaccntno = getnextacctno($data->{'borrowernumber'});
2274
    # Ok, so we know we have an unrefunded lost item fee, let's refund it
2258
    $amountleft *= -1 if ($amountleft < 0);
2275
    CreditLostItem(
2259
    if ($amountleft > 0) {
2276
        {
2260
        my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
2277
            borrower => $issue->borrower(),
2261
                            AND (amountoutstanding >0) ORDER BY date");     # might want to order by amountoustanding ASC (pay smallest first)
2278
            debit    => $debit
2262
        $msth->execute($data->{'borrowernumber'});
2279
        }
2263
        # offset transactions
2280
    );
2264
        my $newamtos;
2281
2265
        my $accdata;
2266
        while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
2267
            if ($accdata->{'amountoutstanding'} < $amountleft) {
2268
                $newamtos = 0;
2269
                $amountleft -= $accdata->{'amountoutstanding'};
2270
            }  else {
2271
                $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
2272
                $amountleft = 0;
2273
            }
2274
            my $thisacct = $accdata->{'accountlines_id'};
2275
            # FIXME: move prepares outside while loop!
2276
            my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
2277
                    WHERE (accountlines_id = ?)");
2278
            $usth->execute($newamtos,$thisacct);
2279
            $usth = $dbh->prepare("INSERT INTO accountoffsets
2280
                (borrowernumber, accountno, offsetaccount,  offsetamount)
2281
                VALUES
2282
                (?,?,?,?)");
2283
            $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
2284
        }
2285
    }
2286
    $amountleft *= -1 if ($amountleft > 0);
2287
    my $desc = "Item Returned " . $item_id;
2288
    $usth = $dbh->prepare("INSERT INTO accountlines
2289
        (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
2290
        VALUES (?,?,now(),?,?,'CR',?)");
2291
    $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
2292
    if ($borrowernumber) {
2293
        # FIXME: same as query above.  use 1 sth for both
2294
        $usth = $dbh->prepare("INSERT INTO accountoffsets
2295
            (borrowernumber, accountno, offsetaccount,  offsetamount)
2296
            VALUES (?,?,?,?)");
2297
        $usth->execute($borrowernumber, $data->{'accountno'}, $nextaccntno, $offset);
2298
    }
2299
    ModItem({ paidfor => '' }, undef, $itemnumber);
2282
    ModItem({ paidfor => '' }, undef, $itemnumber);
2300
    return;
2301
}
2283
}
2302
2284
2303
=head2 _GetCircControlBranch
2285
=head2 _GetCircControlBranch
Lines 2741-2759 sub AddRenewal { Link Here
2741
    # Charge a new rental fee, if applicable?
2723
    # Charge a new rental fee, if applicable?
2742
    my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2724
    my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2743
    if ( $charge > 0 ) {
2725
    if ( $charge > 0 ) {
2744
        my $accountno = getnextacctno( $borrowernumber );
2745
        my $item = GetBiblioFromItemNumber($itemnumber);
2726
        my $item = GetBiblioFromItemNumber($itemnumber);
2746
        my $manager_id = 0;
2727
2747
        $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv; 
2728
        my $borrower =
2748
        $sth = $dbh->prepare(
2729
          Koha::Database->new()->schema->resultset('Borrower')
2749
                "INSERT INTO accountlines
2730
          ->find($borrowernumber);
2750
                    (date, borrowernumber, accountno, amount, manager_id,
2731
2751
                    description,accounttype, amountoutstanding, itemnumber)
2732
        AddDebit(
2752
                    VALUES (now(),?,?,?,?,?,?,?,?)"
2733
            {
2734
                borrower   => $borrower,
2735
                itemnumber => $itemnumber,
2736
                amount     => $charge,
2737
                type       => Koha::Accounts::DebitTypes::Rental(),
2738
                description =>
2739
                  "Renewal of Rental Item $item->{'title'} $item->{'barcode'}"
2740
            }
2753
        );
2741
        );
2754
        $sth->execute( $borrowernumber, $accountno, $charge, $manager_id,
2755
            "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
2756
            'Rent', $charge, $itemnumber );
2757
    }
2742
    }
2758
2743
2759
    # Send a renewal slip according to checkout alert preferencei
2744
    # Send a renewal slip according to checkout alert preferencei
Lines 2979-3003 sub _get_discount_from_rule { Link Here
2979
2964
2980
=head2 AddIssuingCharge
2965
=head2 AddIssuingCharge
2981
2966
2982
  &AddIssuingCharge( $itemno, $borrowernumber, $charge )
2967
  &AddIssuingCharge( $itemnumber, $borrowernumber, $amount )
2983
2968
2984
=cut
2969
=cut
2985
2970
2986
sub AddIssuingCharge {
2971
sub AddIssuingCharge {
2987
    my ( $itemnumber, $borrowernumber, $charge ) = @_;
2972
    my ( $itemnumber, $borrowernumber, $amount ) = @_;
2988
    my $dbh = C4::Context->dbh;
2973
2989
    my $nextaccntno = getnextacctno( $borrowernumber );
2974
    return AddDebit(
2990
    my $manager_id = 0;
2975
        {
2991
    $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
2976
            borrower       => Koha::Database->new()->schema->resultset('Borrower')->find($borrowernumber),
2992
    my $query ="
2977
            itemnumber     => $itemnumber,
2993
        INSERT INTO accountlines
2978
            amount         => $amount,
2994
            (borrowernumber, itemnumber, accountno,
2979
            type           => Koha::Accounts::DebitTypes::Rental(),
2995
            date, amount, description, accounttype,
2980
        }
2996
            amountoutstanding, manager_id)
2981
    );
2997
        VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?,?)
2998
    ";
2999
    my $sth = $dbh->prepare($query);
3000
    $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge, $manager_id );
3001
}
2982
}
3002
2983
3003
=head2 GetTransfers
2984
=head2 GetTransfers
Lines 3516-3545 sub ReturnLostItem{ Link Here
3516
sub LostItem{
3497
sub LostItem{
3517
    my ($itemnumber, $mark_returned) = @_;
3498
    my ($itemnumber, $mark_returned) = @_;
3518
3499
3519
    my $dbh = C4::Context->dbh();
3500
    my $schema = Koha::Database->new()->schema;
3520
    my $sth=$dbh->prepare("SELECT issues.*,items.*,biblio.title 
3521
                           FROM issues 
3522
                           JOIN items USING (itemnumber) 
3523
                           JOIN biblio USING (biblionumber)
3524
                           WHERE issues.itemnumber=?");
3525
    $sth->execute($itemnumber);
3526
    my $issues=$sth->fetchrow_hashref();
3527
3501
3528
    # If a borrower lost the item, add a replacement cost to the their record
3502
    my $issue =
3529
    if ( my $borrowernumber = $issues->{borrowernumber} ){
3503
      $schema->resultset('Issue')->single( { itemnumber => $itemnumber } );
3530
        my $borrower = C4::Members::GetMemberDetails( $borrowernumber );
3504
3505
    my ( $borrower, $item );
3506
3507
    if ( $issue ) {
3508
        $borrower = $issue->borrower();
3509
        $item     = $issue->item();
3510
    }
3531
3511
3512
    # If a borrower lost the item, add a replacement cost to the their record
3513
    if ( $borrower ){
3532
        if (C4::Context->preference('WhenLostForgiveFine')){
3514
        if (C4::Context->preference('WhenLostForgiveFine')){
3533
            my $fix = _FixOverduesOnReturn($borrowernumber, $itemnumber, 1, 0); # 1, 0 = exemptfine, no-dropbox
3515
            _FixOverduesOnReturn(
3534
            defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $itemnumber...) failed!";  # zero is OK, check defined
3516
                {
3517
                    exempt_fine => 1,
3518
                    dropbox     => 0,
3519
                    issue       => $issue,
3520
                }
3521
            );
3535
        }
3522
        }
3536
        if (C4::Context->preference('WhenLostChargeReplacementFee')){
3523
        if ( C4::Context->preference('WhenLostChargeReplacementFee') ) {
3537
            C4::Accounts::chargelostitem($borrowernumber, $itemnumber, $issues->{'replacementprice'}, "Lost Item $issues->{'title'} $issues->{'barcode'}");
3524
            DebitLostItem( { borrower => $borrower, issue => $issue } );
3538
            #FIXME : Should probably have a way to distinguish this from an item that really was returned.
3539
            #warn " $issues->{'borrowernumber'}  /  $itemnumber ";
3540
        }
3525
        }
3541
3526
3542
        MarkIssueReturned($borrowernumber,$itemnumber,undef,undef,$borrower->{'privacy'}) if $mark_returned;
3527
        MarkIssueReturned( $borrower->borrowernumber(), $item->itemnumber(), undef, undef, $borrower->privacy() ) if $mark_returned;
3543
    }
3528
    }
3544
}
3529
}
3545
3530
Lines 3657-3666 sub ProcessOfflineIssue { Link Here
3657
sub ProcessOfflinePayment {
3642
sub ProcessOfflinePayment {
3658
    my $operation = shift;
3643
    my $operation = shift;
3659
3644
3660
    my $borrower = C4::Members::GetMemberDetails( undef, $operation->{cardnumber} ); # Get borrower from operation cardnumber
3645
    AddCredit(
3661
    my $amount = $operation->{amount};
3646
        {
3662
3647
            borrower => Koha::Database->new()->schema->resultset('Borrower')
3663
    recordpayment( $borrower->{borrowernumber}, $amount );
3648
              ->single( { cardnumber => $operation->{cardnumber} } ),
3649
            amount => $operation->{amount},
3650
            notes  => 'via offline circulation',
3651
            type   => Koha::Accounts::CreditTypes::Payment,
3652
        }
3653
    );
3664
3654
3665
    return "Success."
3655
    return "Success."
3666
}
3656
}
(-)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 463-616 sub GetIssuesIteminfo { Link Here
463
463
464
=head2 UpdateFine
464
=head2 UpdateFine
465
465
466
    &UpdateFine($itemnumber, $borrowernumber, $amount, $type, $description);
466
    UpdateFine(
467
        {
468
            itemnumber     => $itemnumber,
469
            borrowernumber => $borrowernumber,
470
            amount         => $amount,
471
            due            => $due,
472
            issue_id       => $issue_id
473
        }
474
    );
467
475
468
(Note: the following is mostly conjecture and guesswork.)
476
Updates the fine owed on an overdue item.
469
477
470
Updates the fine owed on an overdue book.
478
C<$itemnumber> is the items's id.
471
479
472
C<$itemnumber> is the book's item number.
480
C<$borrowernumber> is the id of the patron who currently
481
has the item on loan.
473
482
474
C<$borrowernumber> is the borrower number of the patron who currently
483
C<$amount> is the total amount of the fine owed by the patron.
475
has the book on loan.
476
484
477
C<$amount> is the current amount owed by the patron.
485
C<&UpdateFine> updates the amount owed for a given fine if an issue_id
486
is passed to it. Otherwise, a new fine will be created.
478
487
479
C<$type> will be used in the description of the fine.
488
=cut
480
489
481
C<$description> is a string that must be present in the description of
490
sub UpdateFine {
482
the fine. I think this is expected to be a date in DD/MM/YYYY format.
491
    my ($params) = @_;
483
492
484
C<&UpdateFine> looks up the amount currently owed on the given item
493
    my $itemnumber     = $params->{itemnumber};
485
and sets it to C<$amount>, creating, if necessary, a new entry in the
494
    my $borrowernumber = $params->{borrowernumber};
486
accountlines table of the Koha database.
495
    my $amount         = $params->{amount};
496
    my $due            = $params->{due};
497
    my $issue_id       = $params->{issue_id};
487
498
488
=cut
499
    my $schema = Koha::Database->new()->schema;
489
500
490
#
501
    my $borrower = $schema->resultset('Borrower')->find($borrowernumber);
491
# Question: Why should the caller have to
492
# specify both the item number and the borrower number? A book can't
493
# be on loan to two different people, so the item number should be
494
# sufficient.
495
#
496
# Possible Answer: You might update a fine for a damaged item, *after* it is returned.
497
#
498
sub UpdateFine {
499
    my ( $itemnum, $borrowernumber, $amount, $type, $due ) = @_;
500
	$debug and warn "UpdateFine($itemnum, $borrowernumber, $amount, " . ($type||'""') . ", $due) called";
501
    my $dbh = C4::Context->dbh;
502
    # FIXME - What exactly is this query supposed to do? It looks up an
503
    # entry in accountlines that matches the given item and borrower
504
    # numbers, where the description contains $due, and where the
505
    # account type has one of several values, but what does this _mean_?
506
    # Does it look up existing fines for this item?
507
    # FIXME - What are these various account types? ("FU", "O", "F", "M")
508
	#	"L"   is LOST item
509
	#   "A"   is Account Management Fee
510
	#   "N"   is New Card
511
	#   "M"   is Sundry
512
	#   "O"   is Overdue ??
513
	#   "F"   is Fine ??
514
	#   "FU"  is Fine UPDATE??
515
	#	"Pay" is Payment
516
	#   "REF" is Cash Refund
517
    my $sth = $dbh->prepare(
518
        "SELECT * FROM accountlines
519
        WHERE borrowernumber=?
520
        AND   accounttype IN ('FU','O','F','M')"
521
    );
522
    $sth->execute( $borrowernumber );
523
    my $data;
524
    my $total_amount_other = 0.00;
525
    my $due_qr = qr/$due/;
526
    # Cycle through the fines and
527
    # - find line that relates to the requested $itemnum
528
    # - accumulate fines for other items
529
    # so we can update $itemnum fine taking in account fine caps
530
    while (my $rec = $sth->fetchrow_hashref) {
531
        if ($rec->{itemnumber} == $itemnum && $rec->{description} =~ /$due_qr/) {
532
            if ($data) {
533
                warn "Not a unique accountlines record for item $itemnum borrower $borrowernumber";
534
            } else {
535
                $data = $rec;
536
                next;
537
            }
538
        }
539
        $total_amount_other += $rec->{'amountoutstanding'};
540
    }
541
502
542
    if (my $maxfine = C4::Context->preference('MaxFine')) {
503
    if ( my $maxfine = C4::Context->preference('MaxFine') ) {
543
        if ($total_amount_other + $amount > $maxfine) {
504
        if ( $borrower->account_balance() + $amount > $maxfine ) {
544
            my $new_amount = $maxfine - $total_amount_other;
505
            my $new_amount = $maxfine - $borrower->account_balance();
545
            return if $new_amount <= 0.00;
506
            warn "Reducing fine for item $itemnumber borrower $borrowernumber from $amount to $new_amount - MaxFine reached";
546
            warn "Reducing fine for item $itemnum borrower $borrowernumber from $amount to $new_amount - MaxFine reached";
507
            if ( $new_amount <= 0 ) {
508
                warn "Fine reduced to a non-positive ammount. Fine not created.";
509
                return;
510
            }
547
            $amount = $new_amount;
511
            $amount = $new_amount;
548
        }
512
        }
549
    }
513
    }
550
514
551
    if ( $data ) {
515
    my $timestamp = get_timestamp();
552
516
553
		# we're updating an existing fine.  Only modify if amount changed
517
    my $fine =
554
        # Note that in the current implementation, you cannot pay against an accruing fine
518
      $schema->resultset('AccountDebit')->single( { issue_id => $issue_id, type => Koha::Accounts::DebitTypes::Fine } );
555
        # (i.e. , of accounttype 'FU').  Doing so will break accrual.
519
556
    	if ( $data->{'amount'} != $amount ) {
520
    my $offset = 0;
557
            my $diff = $amount - $data->{'amount'};
521
    if ($fine) {
558
	    #3341: diff could be positive or negative!
522
        if ( $fine->accruing() ) { # Don't update or recreate fines no longer accruing
559
            my $out  = $data->{'amountoutstanding'} + $diff;
523
            if (
560
            my $query = "
524
                sprintf( "%.6f", $fine->amount_original() )
561
                UPDATE accountlines
525
                ne
562
				SET date=now(), amount=?, amountoutstanding=?,
526
                sprintf( "%.6f", $amount ) )
563
					lastincrement=?, accounttype='FU'
527
            {
564
	  			WHERE borrowernumber=?
528
                my $difference = $amount - $fine->amount_original();
565
				AND   itemnumber=?
529
566
				AND   accounttype IN ('FU','O')
530
                $fine->amount_original( $fine->amount_original() + $difference );
567
				AND   description LIKE ?
531
                $fine->amount_outstanding( $fine->amount_outstanding() + $difference );
568
				LIMIT 1 ";
532
                $fine->amount_last_increment($difference);
569
            my $sth2 = $dbh->prepare($query);
533
                $fine->updated_on($timestamp);
570
			# FIXME: BOGUS query cannot ensure uniqueness w/ LIKE %x% !!!
534
                $fine->update();
571
			# 		LIMIT 1 added to prevent multiple affected lines
535
572
			# FIXME: accountlines table needs unique key!! Possibly a combo of borrowernumber and accountline.  
536
                $offset = 1;
573
			# 		But actually, we should just have a regular autoincrementing PK and forget accountline,
537
            }
574
			# 		including the bogus getnextaccountno function (doesn't prevent conflict on simultaneous ops).
575
			# FIXME: Why only 2 account types here?
576
			$debug and print STDERR "UpdateFine query: $query\n" .
577
				"w/ args: $amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, \"\%$due\%\"\n";
578
            $sth2->execute($amount, $out, $diff, $data->{'borrowernumber'}, $data->{'itemnumber'}, "%$due%");
579
        } else {
580
            #      print "no update needed $data->{'amount'}"
581
        }
538
        }
582
    } else {
539
    }
583
        my $sth4 = $dbh->prepare(
540
    else {
584
            "SELECT title FROM biblio LEFT JOIN items ON biblio.biblionumber=items.biblionumber WHERE items.itemnumber=?"
541
        my $item = $schema->resultset('Item')->find($itemnumber);
542
543
        $fine = $schema->resultset('AccountDebit')->create(
544
            {
545
                borrowernumber        => $borrowernumber,
546
                itemnumber            => $itemnumber,
547
                issue_id              => $issue_id,
548
                type                  => Koha::Accounts::DebitTypes::Fine(),
549
                accruing              => 1,
550
                amount_original       => $amount,
551
                amount_outstanding    => $amount,
552
                amount_last_increment => $amount,
553
                description           => $item->biblio()->title() . " / Due:$due",
554
                created_on            => $timestamp,
555
            }
585
        );
556
        );
586
        $sth4->execute($itemnum);
557
587
        my $title = $sth4->fetchrow;
558
        $offset = 1;
588
589
#         #   print "not in account";
590
#         my $sth3 = $dbh->prepare("Select max(accountno) from accountlines");
591
#         $sth3->execute;
592
# 
593
#         # FIXME - Make $accountno a scalar.
594
#         my @accountno = $sth3->fetchrow_array;
595
#         $sth3->finish;
596
#         $accountno[0]++;
597
# begin transaction
598
		my $nextaccntno = C4::Accounts::getnextacctno($borrowernumber);
599
		my $desc = ($type ? "$type " : '') . "$title $due";	# FIXEDME, avoid whitespace prefix on empty $type
600
		my $query = "INSERT INTO accountlines
601
		    (borrowernumber,itemnumber,date,amount,description,accounttype,amountoutstanding,lastincrement,accountno)
602
			    VALUES (?,?,now(),?,?,'FU',?,?,?)";
603
		my $sth2 = $dbh->prepare($query);
604
		$debug and print STDERR "UpdateFine query: $query\nw/ args: $borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno\n";
605
        $sth2->execute($borrowernumber, $itemnum, $amount, $desc, $amount, $amount, $nextaccntno);
606
    }
559
    }
607
    # logging action
560
608
    &logaction(
561
    $schema->resultset('AccountOffset')->create(
609
        "FINES",
562
        {
610
        $type,
563
            debit_id   => $fine->debit_id(),
564
            amount     => $fine->amount_last_increment(),
565
            created_on => $timestamp,
566
            type       => Koha::Accounts::OffsetTypes::Fine(),
567
        }
568
    ) if $offset;
569
570
    $borrower->account_balance( $borrower->account_balance + $fine->amount_last_increment() );
571
    $borrower->update();
572
573
    logaction( "FINES", Koha::Accounts::DebitTypes::Fine(),
611
        $borrowernumber,
574
        $borrowernumber,
612
        "due=".$due."  amount=".$amount." itemnumber=".$itemnum
575
        "due=" . $due . "  amount=" . $amount . " itemnumber=" . $itemnumber )
613
        ) if C4::Context->preference("FinesLog");
576
      if C4::Context->preference("FinesLog");
614
}
577
}
615
578
616
=head2 BorType
579
=head2 BorType
Lines 651-720 C<$borrowernumber> is the borrowernumber Link Here
651
=cut 
614
=cut 
652
615
653
sub GetFine {
616
sub GetFine {
654
    my ( $itemnum, $borrowernumber ) = @_;
617
    my ( $itemnumber, $borrowernumber ) = @_;
655
    my $dbh   = C4::Context->dbh();
656
    my $query = q|SELECT sum(amountoutstanding) as fineamount FROM accountlines
657
    where accounttype like 'F%'
658
  AND amountoutstanding > 0 AND itemnumber = ? AND borrowernumber=?|;
659
    my $sth = $dbh->prepare($query);
660
    $sth->execute( $itemnum, $borrowernumber );
661
    my $fine = $sth->fetchrow_hashref();
662
    if ($fine->{fineamount}) {
663
        return $fine->{fineamount};
664
    }
665
    return 0;
666
}
667
618
668
=head2 NumberNotifyId
619
    my $schema = Koha::Database->new()->schema;
669
620
670
    (@notify) = &NumberNotifyId($borrowernumber);
621
    my $amount_outstanding = $schema->resultset('AccountDebit')->search(
671
622
        {
672
Returns amount for all file per borrowers
623
            itemnumber     => $itemnumber,
673
C<@notify> array contains all file per borrowers
624
            borrowernumber => $borrowernumber,
674
625
            type           => Koha::Accounts::DebitTypes::Fine(),
675
C<$notify_id> contains the file number for the borrower number nad item number
626
        },
676
627
    )->get_column('amount_outstanding')->sum();
677
=cut
678
628
679
sub NumberNotifyId{
629
    return $amount_outstanding;
680
    my ($borrowernumber)=@_;
681
    my $dbh = C4::Context->dbh;
682
    my $query=qq|    SELECT distinct(notify_id)
683
            FROM accountlines
684
            WHERE borrowernumber=?|;
685
    my @notify;
686
    my $sth = $dbh->prepare($query);
687
    $sth->execute($borrowernumber);
688
    while ( my ($numberofnotify) = $sth->fetchrow ) {
689
        push( @notify, $numberofnotify );
690
    }
691
    return (@notify);
692
}
693
694
=head2 AmountNotify
695
696
    ($totalnotify) = &AmountNotify($notifyid);
697
698
Returns amount for all file per borrowers
699
C<$notifyid> is the file number
700
701
C<$totalnotify> contains amount of a file
702
703
C<$notify_id> contains the file number for the borrower number and item number
704
705
=cut
706
707
sub AmountNotify{
708
    my ($notifyid,$borrowernumber)=@_;
709
    my $dbh = C4::Context->dbh;
710
    my $query=qq|    SELECT sum(amountoutstanding)
711
            FROM accountlines
712
            WHERE notify_id=? AND borrowernumber = ?|;
713
    my $sth=$dbh->prepare($query);
714
	$sth->execute($notifyid,$borrowernumber);
715
	my $totalnotify=$sth->fetchrow;
716
    $sth->finish;
717
    return ($totalnotify);
718
}
630
}
719
631
720
=head2 GetItems
632
=head2 GetItems
Lines 766-792 sub GetBranchcodesWithOverdueRules { Link Here
766
    return @branches;
678
    return @branches;
767
}
679
}
768
680
769
=head2 CheckItemNotify
770
771
Sql request to check if the document has alreday been notified
772
this function is not exported, only used with GetOverduesForBranch
773
774
=cut
775
776
sub CheckItemNotify {
777
    my ($notify_id,$notify_level,$itemnumber) = @_;
778
    my $dbh = C4::Context->dbh;
779
    my $sth = $dbh->prepare("
780
    SELECT COUNT(*)
781
     FROM notifys
782
    WHERE notify_id    = ?
783
     AND  notify_level = ? 
784
     AND  itemnumber   = ? ");
785
    $sth->execute($notify_id,$notify_level,$itemnumber);
786
    my $notified = $sth->fetchrow;
787
    return ($notified);
788
}
789
790
=head2 GetOverduesForBranch
681
=head2 GetOverduesForBranch
791
682
792
Sql request for display all information for branchoverdues.pl
683
Sql request for display all information for branchoverdues.pl
Lines 812-817 sub GetOverduesForBranch { Link Here
812
               biblio.title,
703
               biblio.title,
813
               biblio.author,
704
               biblio.author,
814
               biblio.biblionumber,
705
               biblio.biblionumber,
706
               issues.issue_id,
815
               issues.date_due,
707
               issues.date_due,
816
               issues.returndate,
708
               issues.returndate,
817
               issues.branchcode,
709
               issues.branchcode,
Lines 822-846 sub GetOverduesForBranch { Link Here
822
                items.location,
714
                items.location,
823
                items.itemnumber,
715
                items.itemnumber,
824
            itemtypes.description,
716
            itemtypes.description,
825
         accountlines.notify_id,
717
            account_debits.amount_outstanding
826
         accountlines.notify_level,
718
    FROM  account_debits
827
         accountlines.amountoutstanding
719
    LEFT JOIN issues      ON    issues.itemnumber     = account_debits.itemnumber
828
    FROM  accountlines
720
                          AND   issues.borrowernumber = account_debits.borrowernumber
829
    LEFT JOIN issues      ON    issues.itemnumber     = accountlines.itemnumber
721
    LEFT JOIN borrowers   ON borrowers.borrowernumber = account_debits.borrowernumber
830
                          AND   issues.borrowernumber = accountlines.borrowernumber
831
    LEFT JOIN borrowers   ON borrowers.borrowernumber = accountlines.borrowernumber
832
    LEFT JOIN items       ON     items.itemnumber     = issues.itemnumber
722
    LEFT JOIN items       ON     items.itemnumber     = issues.itemnumber
833
    LEFT JOIN biblio      ON      biblio.biblionumber =  items.biblionumber
723
    LEFT JOIN biblio      ON      biblio.biblionumber =  items.biblionumber
834
    LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
724
    LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
835
    LEFT JOIN itemtypes   ON itemtypes.itemtype       = $itype_link
725
    LEFT JOIN itemtypes   ON itemtypes.itemtype       = $itype_link
836
    LEFT JOIN branches    ON  branches.branchcode     = issues.branchcode
726
    LEFT JOIN branches    ON  branches.branchcode     = issues.branchcode
837
    WHERE (accountlines.amountoutstanding  != '0.000000')
727
    WHERE (account_debits.amount_outstanding  != '0.000000')
838
      AND (accountlines.accounttype         = 'FU'      )
728
      AND (account_debits.type = 'FINE')
729
      AND (account_debits.accruing = 1 )
839
      AND (issues.branchcode =  ?   )
730
      AND (issues.branchcode =  ?   )
840
      AND (issues.date_due  < NOW())
731
      AND (issues.date_due  < NOW())
841
    ";
732
    ";
842
    my @getoverdues;
733
    my @getoverdues;
843
    my $i = 0;
844
    my $sth;
734
    my $sth;
845
    if ($location) {
735
    if ($location) {
846
        $sth = $dbh->prepare("$select AND items.location = ? ORDER BY borrowers.surname, borrowers.firstname");
736
        $sth = $dbh->prepare("$select AND items.location = ? ORDER BY borrowers.surname, borrowers.firstname");
Lines 850-861 sub GetOverduesForBranch { Link Here
850
        $sth->execute($branch);
740
        $sth->execute($branch);
851
    }
741
    }
852
    while ( my $data = $sth->fetchrow_hashref ) {
742
    while ( my $data = $sth->fetchrow_hashref ) {
853
    #check if the document has already been notified
743
        push( @getoverdues, $data );
854
        my $countnotify = CheckItemNotify($data->{'notify_id'}, $data->{'notify_level'}, $data->{'itemnumber'});
855
        if ($countnotify eq '0') {
856
            $getoverdues[$i] = $data;
857
            $i++;
858
        }
859
    }
744
    }
860
    return (@getoverdues);
745
    return (@getoverdues);
861
}
746
}
(-)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