Bug 22200: Add Tests for change
[koha-equinox.git] / t / db_dependent / Circulation.t
index eafc2d8..0c12efb 100755 (executable)
 use Modern::Perl;
 use utf8;
 
-use Test::More tests => 124;
+use Test::More tests => 130;
 use Test::MockModule;
 
 use Data::Dumper;
 use DateTime;
+use Time::Fake;
 use POSIX qw( floor );
 use t::lib::Mocks;
 use t::lib::TestBuilder;
@@ -45,6 +46,7 @@ use Koha::CirculationRules;
 use Koha::Subscriptions;
 use Koha::Account::Lines;
 use Koha::Account::Offsets;
+use Koha::ActionLogs;
 
 my $schema = Koha::Database->schema;
 $schema->storage->txn_begin;
@@ -70,8 +72,15 @@ my $library2 = $builder->build({
     source => 'Branch',
 });
 my $itemtype = $builder->build(
-    {   source => 'Itemtype',
-        value  => { notforloan => undef, rentalcharge => 0, defaultreplacecost => undef, processfee => undef }
+    {
+        source => 'Itemtype',
+        value  => {
+            notforloan          => undef,
+            rentalcharge        => 0,
+            rentalcharge_daily => 0,
+            defaultreplacecost  => undef,
+            processfee          => undef
+        }
     }
 )->{itemtype};
 my $patron_category = $builder->build(
@@ -97,6 +106,8 @@ my $borrower = {
     branchcode => $library2->{branchcode}
 };
 
+t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
+
 # No userenv, PickupLibrary
 t::lib::Mocks::mock_preference('IndependentBranches', '0');
 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
@@ -469,32 +480,46 @@ my ( $reused_itemnumber_1, $reused_itemnumber_2 );
     );
 
     t::lib::Mocks::mock_preference('RenewalLog', 0);
-    my $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
-    my $old_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
-    AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
-    my $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
+    my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
+    my %params_renewal = (
+        timestamp => { -like => $date . "%" },
+        module => "CIRCULATION",
+        action => "RENEWAL",
+    );
+    my %params_issue = (
+        timestamp => { -like => $date . "%" },
+        module => "CIRCULATION",
+        action => "ISSUE"
+    );
+    my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
+    my $dt = dt_from_string();
+    Time::Fake->offset( $dt->epoch );
+    my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
+    my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
     is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
+    isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
+    Time::Fake->reset;
 
     t::lib::Mocks::mock_preference('RenewalLog', 1);
-    $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
-    $old_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
+    $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
+    $old_log_size = Koha::ActionLogs->count( \%params_renewal );
     AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
-    $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
+    $new_log_size = Koha::ActionLogs->count( \%params_renewal );
     is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
 
     my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
     is( $fines->count, 2 );
-    is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
-    is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
+    isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
+    isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
     $fines->delete();
 
 
-    my $old_issue_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["ISSUE"]) } );
-    my $old_renew_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
+    my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
+    my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
     AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
-    $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["RENEWAL"]) } );
+    $new_log_size = Koha::ActionLogs->count( \%params_renewal );
     is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
-    $new_log_size =  scalar(@{GetLogs( $date, $date, undef,["CIRCULATION"], ["ISSUE"]) } );
+    $new_log_size = Koha::ActionLogs->count( \%params_issue );
     is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
 
     $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
@@ -662,19 +687,44 @@ my ( $reused_itemnumber_1, $reused_itemnumber_2 );
         C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
         C4::Context->set_preference('OPACFineNoRenewals','10');
         my $fines_amount = 5;
-        C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
+        my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
+        $account->add_debit(
+            {
+                amount      => $fines_amount,
+                interface   => 'test',
+                type        => 'overdue',
+                item_id     => $item_to_auto_renew->{itemnumber},
+                description => "Some fines"
+            }
+        )->status('RETURNED')->store;
         ( $renewokay, $error ) =
           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
 
-        C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
+        $account->add_debit(
+            {
+                amount      => $fines_amount,
+                interface   => 'test',
+                type        => 'overdue',
+                item_id     => $item_to_auto_renew->{itemnumber},
+                description => "Some fines"
+            }
+        )->status('RETURNED')->store;
         ( $renewokay, $error ) =
           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
 
-        C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
+        $account->add_debit(
+            {
+                amount      => $fines_amount,
+                interface   => 'test',
+                type        => 'overdue',
+                item_id     => $item_to_auto_renew->{itemnumber},
+                description => "Some fines"
+            }
+        )->status('RETURNED')->store;
         ( $renewokay, $error ) =
           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
@@ -808,14 +858,14 @@ my ( $reused_itemnumber_1, $reused_itemnumber_2 );
     );
 
     my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
-    is( $line->accounttype, 'FU', 'Account line type is FU' );
-    is( $line->lastincrement, '15.000000', 'Account line last increment is 15.00' );
+    is( $line->accounttype, 'OVERDUE', 'Account line type is OVERDUE' );
+    is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
     is( $line->amountoutstanding, '15.000000', 'Account line amount outstanding is 15.00' );
     is( $line->amount, '15.000000', 'Account line amount is 15.00' );
     is( $line->issue_id, $issue->id, 'Account line issue id matches' );
 
     my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
-    is( $offset->type, 'Fine', 'Account offset type is Fine' );
+    is( $offset->type, 'OVERDUE', 'Account offset type is Fine' );
     is( $offset->amount, '15.000000', 'Account offset amount is 15.00' );
 
     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
@@ -824,7 +874,8 @@ my ( $reused_itemnumber_1, $reused_itemnumber_2 );
     LostItem( $item_1->itemnumber, 'test', 1 );
 
     $line = Koha::Account::Lines->find($line->id);
-    is( $line->accounttype, 'F', 'Account type correctly changed from FU to F' );
+    is( $line->accounttype, 'OVERDUE', 'Account type remains as OVERDUE' );
+    isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
 
     my $item = Koha::Items->find($item_1->itemnumber);
     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
@@ -876,11 +927,21 @@ my ( $reused_itemnumber_1, $reused_itemnumber_2 );
     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
 
+    my $manager = $builder->build_object({ class => "Koha::Patrons" });
+    t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
     $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
     LostItem( $item_3->itemnumber, 'test', 0 );
     my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
     is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
+    is(
+        $accountline->description,
+        sprintf( "%s %s %s",
+            $item_3->biblio->title  || '',
+            $item_3->barcode        || '',
+            $item_3->itemcallnumber || '' ),
+        "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
+    );
   }
 
 {
@@ -1634,8 +1695,7 @@ subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
       ;    # Add another overdue
 
     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
-    AddReturn( $item_1->{barcode}, $library->{branchcode},
-        undef, undef, dt_from_string );
+    AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
     my $debarments = Koha::Patron::Debarments::GetDebarments(
         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
     is( scalar(@$debarments), 1 );
@@ -1651,8 +1711,7 @@ subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
     );
     is( $debarments->[0]->{expiration}, $expected_expiration );
 
-    AddReturn( $item_2->{barcode}, $library->{branchcode},
-        undef, undef, dt_from_string );
+    AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
     $debarments = Koha::Patron::Debarments::GetDebarments(
         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
     is( scalar(@$debarments), 1 );
@@ -1672,8 +1731,7 @@ subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
       ;    # Add another overdue
-    AddReturn( $item_1->{barcode}, $library->{branchcode},
-        undef, undef, dt_from_string );
+    AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
     $debarments = Koha::Patron::Debarments::GetDebarments(
         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
     is( scalar(@$debarments), 1 );
@@ -1686,8 +1744,7 @@ subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
     );
     is( $debarments->[0]->{expiration}, $expected_expiration );
 
-    AddReturn( $item_2->{barcode}, $library->{branchcode},
-        undef, undef, dt_from_string );
+    AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
     $debarments = Koha::Patron::Debarments::GetDebarments(
         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
     is( scalar(@$debarments), 1 );
@@ -1730,7 +1787,6 @@ subtest 'AddReturn + suspension_chargeperiod' => sub {
             categorycode => '*',
             itemtype     => '*',
             branchcode   => '*',
-            maxissueqty  => 99,
             issuelength  => 1,
             firstremind  => 0,        # 0 day of grace
             finedays     => 2,        # 2 days of fine per day of overdue
@@ -1865,6 +1921,64 @@ subtest 'AddReturn + suspension_chargeperiod' => sub {
     );
 };
 
+subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
+    plan tests => 2;
+
+    my $library = $builder->build( { source => 'Branch' } );
+    my $patron1 = $builder->build_object(
+        {
+            class => 'Koha::Patrons',
+            value  => {
+                branchcode => $library->{branchcode},
+                firstname => "Happy",
+                surname => "Gilmore",
+            }
+        }
+    );
+    my $patron2 = $builder->build_object(
+        {
+            class => 'Koha::Patrons',
+            value  => {
+                branchcode => $library->{branchcode},
+                firstname => "Billy",
+                surname => "Madison",
+            }
+        }
+    );
+
+    C4::Context->_new_userenv('xxx');
+    C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, 'Random Library', '', '', '');
+
+    my $biblioitem = $builder->build( { source => 'Biblioitem' } );
+    my $biblionumber = $biblioitem->{biblionumber};
+    my $item = $builder->build(
+        {   source => 'Item',
+            value  => {
+                homebranch    => $library->{branchcode},
+                holdingbranch => $library->{branchcode},
+                notforloan    => 0,
+                itemlost      => 0,
+                withdrawn     => 0,
+                biblionumber  => $biblionumber,
+            }
+        }
+    );
+
+    my ( $error, $question, $alerts );
+    my $issue = AddIssue( $patron1->unblessed, $item->{barcode} );
+
+    t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
+    ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
+    is( $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER question flag should be set if AutoReturnCheckedOutItems is disabled and item is checked out to another' );
+
+    t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
+    ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
+    is( $alerts->{RETURNED_FROM_ANOTHER}->{patron}->borrowernumber, $patron1->borrowernumber, 'RETURNED_FROM_ANOTHER alert flag should be set if AutoReturnCheckedOutItems is enabled and item is checked out to another' );
+
+    t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
+};
+
+
 subtest 'AddReturn | is_overdue' => sub {
     plan tests => 5;
 
@@ -1874,6 +1988,8 @@ subtest 'AddReturn | is_overdue' => sub {
 
     my $library = $builder->build( { source => 'Branch' } );
     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
+    my $manager = $builder->build_object({ class => "Koha::Patrons" });
+    t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
 
     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
     my $item = $builder->build(
@@ -1896,7 +2012,6 @@ subtest 'AddReturn | is_overdue' => sub {
             categorycode => '*',
             itemtype     => '*',
             branchcode   => '*',
-            maxissueqty  => 99,
             issuelength  => 6,
             lengthunit   => 'days',
             fine         => 1, # Charge 1 every day of overdue
@@ -1918,26 +2033,26 @@ subtest 'AddReturn | is_overdue' => sub {
 
     # specify return date 5 days before => no overdue
     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
-    AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $ten_days_ago );
+    AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
 
     # specify return date 5 days later => overdue
     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
-    AddReturn( $item->{barcode}, $library->{branchcode}, undef, undef, $five_days_ago );
+    AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
 
     # specify dropbox date 5 days before => no overdue
     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
-    AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $ten_days_ago );
+    AddReturn( $item->{barcode}, $library->{branchcode}, $ten_days_ago );
     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
 
     # specify dropbox date 5 days later => overdue, or... not
     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
-    AddReturn( $item->{barcode}, $library->{branchcode}, undef, 1, undef, $five_days_ago );
-    is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue in dropbox mode' ); # FIXME? This is weird, the FU fine is created ( _CalculateAndUpdateFine > C4::Overdues::UpdateFine ) then remove later (in _FixOverduesOnReturn). Looks like it is a feature
+    AddReturn( $item->{barcode}, $library->{branchcode}, $five_days_ago );
+    is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue in dropbox mode' ); # FIXME? This is weird, the OVERDUE fine is created ( _CalculateAndUpdateFine > C4::Overdues::UpdateFine ) then remove later (in _FixOverduesOnReturn). Looks like it is a feature
     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
 };
 
@@ -1956,7 +2071,8 @@ subtest '_FixAccountForLostAndReturned' => sub {
                 notforloan         => undef,
                 rentalcharge       => 0,
                 defaultreplacecost => undef,
-                processfee         => $processfee_amount
+                processfee         => $processfee_amount,
+                rentalcharge_daily => 0,
             }
         }
     );
@@ -1969,6 +2085,8 @@ subtest '_FixAccountForLostAndReturned' => sub {
         plan tests => 10;
 
         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
+        my $manager = $builder->build_object({ class => "Koha::Patrons" });
+        t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
 
         my $item = $builder->build_sample_item(
             {
@@ -2008,7 +2126,8 @@ subtest '_FixAccountForLostAndReturned' => sub {
         # Write off the debt
         my $credit = $account->add_credit(
             {   amount => $account->balance,
-                type   => 'writeoff'
+                type   => 'writeoff',
+                interface => 'test',
             }
         );
         $credit->apply( { debits => $debts, offset_type => 'Writeoff' } );
@@ -2068,7 +2187,8 @@ subtest '_FixAccountForLostAndReturned' => sub {
         # Write off the debt
         my $credit = $account->add_credit(
             {   amount => $account->balance,
-                type   => 'payment'
+                type   => 'payment',
+                interface => 'test',
             }
         );
         $credit->apply( { debits => $debts, offset_type => 'Payment' } );
@@ -2188,7 +2308,8 @@ subtest '_FixAccountForLostAndReturned' => sub {
         my $payment_amount = 27;
         my $payment        = $account->add_credit(
             {   amount => $payment_amount,
-                type   => 'payment'
+                type   => 'payment',
+                interface => 'test',
             }
         );
 
@@ -2198,7 +2319,8 @@ subtest '_FixAccountForLostAndReturned' => sub {
         my $write_off_amount = 25;
         my $write_off        = $account->add_credit(
             {   amount => $write_off_amount,
-                type   => 'writeoff'
+                type   => 'writeoff',
+                interface => 'test',
             }
         );
         $write_off->apply( { debits => $lost_fee_lines->reset, offset_type => 'Writeoff' } );
@@ -2253,7 +2375,8 @@ subtest '_FixAccountForLostAndReturned' => sub {
                     notforloan         => undef,
                     rentalcharge       => 0,
                     defaultreplacecost => undef,
-                    processfee         => 0
+                    processfee         => 0,
+                    rentalcharge_daily => 0,
                 }
             }
         );
@@ -2288,7 +2411,8 @@ subtest '_FixAccountForLostAndReturned' => sub {
         my $payment_amount = 27;
         my $payment        = $account->add_credit(
             {   amount => $payment_amount,
-                type   => 'payment'
+                type   => 'payment',
+                interface => 'test',
             }
         );
         $payment->apply({ debits => $lost_fee_lines->reset, offset_type => 'Payment' });
@@ -2298,9 +2422,8 @@ subtest '_FixAccountForLostAndReturned' => sub {
             'Payment applied'
         );
 
-        # TODO use add_debit when time comes
         my $manual_debit_amount = 80;
-        C4::Accounts::manualinvoice( $patron->id, undef, undef, 'FU', $manual_debit_amount );
+        $account->add_debit( { amount => $manual_debit_amount, type => 'overdue', interface =>'test' } );
 
         is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
 
@@ -2311,13 +2434,16 @@ subtest '_FixAccountForLostAndReturned' => sub {
 
         is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PF - payment (CR)' );
 
-        my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, accounttype => 'FU' })->next;
+        my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, accounttype => 'OVERDUE', status => 'UNRETURNED' })->next;
         is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
     };
 };
 
 subtest '_FixOverduesOnReturn' => sub {
-    plan tests => 10;
+    plan tests => 9;
+
+    my $manager = $builder->build_object({ class => "Koha::Patrons" });
+    t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
 
     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
 
@@ -2338,11 +2464,12 @@ subtest '_FixOverduesOnReturn' => sub {
     my $accountline = Koha::Account::Line->new(
         {
             borrowernumber => $patron->{borrowernumber},
-            accounttype    => 'FU',
+            accounttype    => 'OVERDUE',
+            status         => 'UNRETURNED',
             itemnumber     => $item->itemnumber,
             amount => 99.00,
             amountoutstanding => 99.00,
-            lastincrement => 9.00,
+            interface => 'test',
         }
     )->store();
 
@@ -2351,13 +2478,13 @@ subtest '_FixOverduesOnReturn' => sub {
     $accountline->_result()->discard_changes();
 
     is( $accountline->amountoutstanding, '99.000000', 'Fine has the same amount outstanding as previously' );
-    is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
-
+    is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status RETURNED )');
 
     ## Run again, with exemptfine enabled
     $accountline->set(
         {
-            accounttype    => 'FU',
+            accounttype    => 'OVERDUE',
+            status         => 'UNRETURNED',
             amountoutstanding => 99.00,
         }
     )->store();
@@ -2368,27 +2495,13 @@ subtest '_FixOverduesOnReturn' => sub {
     my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
 
     is( $accountline->amountoutstanding + 0, 0, 'Fine has been reduced to 0' );
-    is( $accountline->accounttype, 'FFOR', 'Open fine ( account type FU ) has been set to fine forgiven ( account type FFOR )');
+    is( $accountline->status, 'FORGIVEN', 'Open fine ( account type OVERDUE ) has been set to fine forgiven ( status FORGIVEN )');
     is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
     is( $offset->amount, '-99.000000', "Amount of offset is correct" );
-
-    ## Run again, with dropbox mode enabled
-    $accountline->set(
-        {
-            accounttype    => 'FU',
-            amountoutstanding => 99.00,
-        }
-    )->store();
-
-    C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 0, 1 );
-
-    $accountline->_result()->discard_changes();
-    $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Dropbox' })->next();
-
-    is( $accountline->amountoutstanding + 0, 90, 'Fine has been reduced to 90' );
-    is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
-    is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via dropbox" );
-    is( $offset->amount, '-9.000000', "Amount of offset is correct" );
+    my $credit = $offset->credit;
+    is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
+    is( $credit->amount, '-99.000000', "Credit amount is set correctly" );
+    is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
 };
 
 subtest 'Set waiting flag' => sub {
@@ -2500,12 +2613,12 @@ subtest 'CanBookBeIssued | is_overdue' => sub {
     $dbh->do('DELETE FROM issuingrules');
     $dbh->do(
     q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
-                                    maxissueqty, issuelength, lengthunit,
+                                    issuelength, lengthunit,
                                     renewalsallowed, renewalperiod,
                                     norenewalbefore, auto_renew,
                                     fine, chargeperiod)
           VALUES (?, ?, ?, ?,
-                  ?, ?, ?,
+                  ?, ?,
                   ?, ?,
                   ?, ?,
                   ?, ?
@@ -2513,7 +2626,7 @@ subtest 'CanBookBeIssued | is_overdue' => sub {
         },
         {},
         '*',   '*', '*', 25,
-        1,     14,  'days',
+        14,  'days',
         1,     7,
         undef, 0,
         .10,   1
@@ -2555,12 +2668,12 @@ subtest 'ItemsDeniedRenewal preference' => sub {
     my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
     $dbh->do(
         q{
-        INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, maxissueqty, issuelength, lengthunit, renewalsallowed, renewalperiod,
-                    norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
+        INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
+                    norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
         },
         {},
         '*', $idr_lib->branchcode, '*', 25,
-        20,  14,  'days',
+        14,  'days',
         10,   7,
         undef,  0,
         .10, 1
@@ -2841,6 +2954,8 @@ subtest 'AddRenewal and AddIssuingCharge tests' => sub {
 
     $schema->storage->txn_begin;
 
+    t::lib::Mocks::mock_preference('item-level_itypes', 1);
+
     my $issuing_charges = 15;
     my $title   = 'A title';
     my $author  = 'Author, An';
@@ -2855,7 +2970,7 @@ subtest 'AddRenewal and AddIssuingCharge tests' => sub {
     );
 
     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
-    my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes' });
+    my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
     my $patron   = $builder->build_object({
         class => 'Koha::Patrons',
         value => { branchcode => $library->id }
@@ -2879,12 +2994,16 @@ subtest 'AddRenewal and AddIssuingCharge tests' => sub {
 
     # Check the item out
     AddIssue( $patron->unblessed, $item->barcode );
-
     t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
     my $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
-    my $old_log_size = scalar( @{ GetLogs( $date, $date, undef, ["CIRCULATION"], ["RENEWAL"] ) } );
+    my %params_renewal = (
+        timestamp => { -like => $date . "%" },
+        module => "CIRCULATION",
+        action => "RENEWAL",
+    );
+    my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
     AddRenewal( $patron->id, $item->id, $library->id );
-    my $new_log_size = scalar( @{ GetLogs( $date, $date, undef, ["CIRCULATION"], ["RENEWAL"] ) } );
+    my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
     is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
 
     my $checkouts = $patron->checkouts;
@@ -2893,9 +3012,9 @@ subtest 'AddRenewal and AddIssuingCharge tests' => sub {
 
     t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
     $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
-    $old_log_size = scalar( @{ GetLogs( $date, $date, undef, ["CIRCULATION"], ["RENEWAL"] ) } );
+    $old_log_size = Koha::ActionLogs->count( \%params_renewal );
     AddRenewal( $patron->id, $item->id, $library->id );
-    $new_log_size = scalar( @{ GetLogs( $date, $date, undef, ["CIRCULATION"], ["RENEWAL"] ) } );
+    $new_log_size = Koha::ActionLogs->count( \%params_renewal );
     is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
 
     my $lines = Koha::Account::Lines->search({
@@ -2983,8 +3102,7 @@ sub test_debarment_on_checkout {
     my $line_number = $caller[2];
     AddIssue( $patron, $item->{barcode}, $due_date );
 
-    my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode},
-        undef, undef, $return_date );
+    my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode}, undef, $return_date );
     is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
         or diag('AddReturn returned message ' . Dumper $message );
     my $debarments = Koha::Patron::Debarments::GetDebarments(
@@ -2995,4 +3113,164 @@ sub test_debarment_on_checkout {
         $expected_expiration_date, 'Test at line ' . $line_number );
     Koha::Patron::Debarments::DelUniqueDebarment(
         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
-}
+};
+
+subtest 'Incremented fee tests' => sub {
+    plan tests => 11;
+
+    t::lib::Mocks::mock_preference('item-level_itypes', 1);
+
+    my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store;
+
+    my $module = new Test::MockModule('C4::Context');
+    $module->mock('userenv', sub { { branch => $library->id } });
+
+    my $patron = $builder->build_object(
+        {
+            class => 'Koha::Patrons',
+            value => { categorycode => $patron_category->{categorycode} }
+        }
+    )->store;
+
+    my $itemtype = $builder->build_object(
+        {
+            class => 'Koha::ItemTypes',
+            value  => {
+                notforloan          => undef,
+                rentalcharge        => 0,
+                rentalcharge_daily => 1.000000
+            }
+        }
+    )->store;
+
+    my $biblioitem = $builder->build( { source => 'Biblioitem' } );
+    my $item = $builder->build_object(
+        {
+            class => 'Koha::Items',
+            value => {
+                homebranch       => $library->id,
+                holdingbranch    => $library->id,
+                notforloan       => 0,
+                itemlost         => 0,
+                withdrawn        => 0,
+                itype            => $itemtype->id,
+                biblionumber     => $biblioitem->{biblionumber},
+                biblioitemnumber => $biblioitem->{biblioitemnumber},
+            }
+        }
+    )->store;
+
+    is( $itemtype->rentalcharge_daily, '1.000000', 'Daily rental charge stored and retreived correctly' );
+    is( $item->effective_itemtype, $itemtype->id, "Itemtype set correctly for item");
+
+    my $dt_from = dt_from_string();
+    my $dt_to = dt_from_string()->add( days => 7 );
+    my $dt_to_renew = dt_from_string()->add( days => 13 );
+
+    t::lib::Mocks::mock_preference('finesCalendar', 'ignoreCalendar');
+    my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
+    my $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
+    is( $accountline->amount, '7.000000', "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar" );
+    $accountline->delete();
+    AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
+    $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
+    is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal" );
+    $accountline->delete();
+    $issue->delete();
+
+    t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
+    $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
+    $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
+    is( $accountline->amount, '7.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed" );
+    $accountline->delete();
+    AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
+    $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
+    is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal" );
+    $accountline->delete();
+    $issue->delete();
+
+    my $calendar = C4::Calendar->new( branchcode => $library->id );
+    $calendar->insert_week_day_holiday(
+        weekday     => 3,
+        title       => 'Test holiday',
+        description => 'Test holiday'
+    );
+    $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
+    $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
+    is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays" );
+    $accountline->delete();
+    AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
+    $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
+    is( $accountline->amount, '5.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays, for renewal" );
+    $accountline->delete();
+    $issue->delete();
+
+    $itemtype->rentalcharge('2.000000')->store;
+    is( $itemtype->rentalcharge, '2.000000', 'Rental charge updated and retreived correctly' );
+    $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from);
+    my $accountlines = Koha::Account::Lines->search({ itemnumber => $item->id });
+    is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly");
+    $accountlines->delete();
+    AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
+    $accountlines = Koha::Account::Lines->search({ itemnumber => $item->id });
+    is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly, for renewal");
+    $accountlines->delete();
+    $issue->delete();
+};
+
+subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
+    plan tests => 2;
+
+    t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
+    t::lib::Mocks::mock_preference('item-level_itypes', 1);
+
+    my $library =
+      $builder->build_object( { class => 'Koha::Libraries' } )->store;
+    my $patron = $builder->build_object(
+        {
+            class => 'Koha::Patrons',
+            value => { categorycode => $patron_category->{categorycode} }
+        }
+    )->store;
+
+    my $itemtype = $builder->build_object(
+        {
+            class => 'Koha::ItemTypes',
+            value => {
+                notforloan             => 0,
+                rentalcharge           => 0,
+                rentalcharge_daily => 0
+            }
+        }
+    );
+
+    my $biblioitem = $builder->build( { source => 'Biblioitem' } );
+    my $item = $builder->build_object(
+        {
+            class => 'Koha::Items',
+            value  => {
+                homebranch    => $library->id,
+                holdingbranch => $library->id,
+                notforloan    => 0,
+                itemlost      => 0,
+                withdrawn     => 0,
+                itype         => $itemtype->id,
+                biblionumber  => $biblioitem->{biblionumber},
+                biblioitemnumber => $biblioitem->{biblioitemnumber},
+            }
+        }
+    )->store;
+
+    my ( $issuingimpossible, $needsconfirmation );
+    my $dt_from = dt_from_string();
+    my $dt_due = dt_from_string()->add( days => 3 );
+
+    $itemtype->rentalcharge('1.000000')->store;
+    ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
+    is_deeply( $needsconfirmation, { RENTALCHARGE => '1' }, 'Item needs rentalcharge confirmation to be issued' );
+    $itemtype->rentalcharge('0')->store;
+    $itemtype->rentalcharge_daily('1.000000')->store;
+    ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
+    is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
+    $itemtype->rentalcharge_daily('0')->store;
+};