Bug 19014: Unit tests
[koha-ffzg.git] / t / db_dependent / Circulation.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19 use utf8;
20
21 use Test::More tests => 46;
22 use Test::MockModule;
23 use Test::Deep qw( cmp_deeply );
24
25 use Data::Dumper;
26 use DateTime;
27 use Time::Fake;
28 use POSIX qw( floor );
29 use t::lib::Mocks;
30 use t::lib::TestBuilder;
31
32 use C4::Accounts;
33 use C4::Calendar;
34 use C4::Circulation;
35 use C4::Biblio;
36 use C4::Items;
37 use C4::Log;
38 use C4::Reserves;
39 use C4::Overdues qw(UpdateFine CalcFine);
40 use Koha::DateUtils;
41 use Koha::Database;
42 use Koha::Items;
43 use Koha::Checkouts;
44 use Koha::Patrons;
45 use Koha::CirculationRules;
46 use Koha::Subscriptions;
47 use Koha::Account::Lines;
48 use Koha::Account::Offsets;
49 use Koha::ActionLogs;
50
51 sub set_userenv {
52     my ( $library ) = @_;
53     t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
54 }
55
56 sub str {
57     my ( $error, $question, $alert ) = @_;
58     my $s;
59     $s  = %$error    ? ' (error: '    . join( ' ', keys %$error    ) . ')' : '';
60     $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
61     $s .= %$alert    ? ' (alert: '    . join( ' ', keys %$alert    ) . ')' : '';
62     return $s;
63 }
64
65 sub test_debarment_on_checkout {
66     my ($params) = @_;
67     my $item     = $params->{item};
68     my $library  = $params->{library};
69     my $patron   = $params->{patron};
70     my $due_date = $params->{due_date} || dt_from_string;
71     my $return_date = $params->{return_date} || dt_from_string;
72     my $expected_expiration_date = $params->{expiration_date};
73
74     $expected_expiration_date = output_pref(
75         {
76             dt         => $expected_expiration_date,
77             dateformat => 'sql',
78             dateonly   => 1,
79         }
80     );
81     my @caller      = caller;
82     my $line_number = $caller[2];
83     AddIssue( $patron, $item->{barcode}, $due_date );
84
85     my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode}, undef, $return_date );
86     is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
87         or diag('AddReturn returned message ' . Dumper $message );
88     my $debarments = Koha::Patron::Debarments::GetDebarments(
89         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
90     is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
91
92     is( $debarments->[0]->{expiration},
93         $expected_expiration_date, 'Test at line ' . $line_number );
94     Koha::Patron::Debarments::DelUniqueDebarment(
95         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
96 };
97
98 my $schema = Koha::Database->schema;
99 $schema->storage->txn_begin;
100 my $builder = t::lib::TestBuilder->new;
101 my $dbh = C4::Context->dbh;
102
103 # Prevent random failures by mocking ->now
104 my $now_value       = dt_from_string;
105 my $mocked_datetime = Test::MockModule->new('DateTime');
106 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
107
108 # Start transaction
109 $dbh->{RaiseError} = 1;
110
111 my $cache = Koha::Caches->get_instance();
112 $dbh->do(q|DELETE FROM special_holidays|);
113 $dbh->do(q|DELETE FROM repeatable_holidays|);
114 $cache->clear_from_cache('single_holidays');
115
116 # Start with a clean slate
117 $dbh->do('DELETE FROM issues');
118 $dbh->do('DELETE FROM borrowers');
119
120 my $library = $builder->build({
121     source => 'Branch',
122 });
123 my $library2 = $builder->build({
124     source => 'Branch',
125 });
126 my $itemtype = $builder->build(
127     {
128         source => 'Itemtype',
129         value  => {
130             notforloan          => undef,
131             rentalcharge        => 0,
132             rentalcharge_daily => 0,
133             defaultreplacecost  => undef,
134             processfee          => undef
135         }
136     }
137 )->{itemtype};
138 my $patron_category = $builder->build(
139     {
140         source => 'Category',
141         value  => {
142             category_type                 => 'P',
143             enrolmentfee                  => 0,
144             BlockExpiredPatronOpacActions => -1, # Pick the pref value
145         }
146     }
147 );
148
149 my $CircControl = C4::Context->preference('CircControl');
150 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
151
152 my $item = {
153     homebranch => $library2->{branchcode},
154     holdingbranch => $library2->{branchcode}
155 };
156
157 my $borrower = {
158     branchcode => $library2->{branchcode}
159 };
160
161 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
162
163 # No userenv, PickupLibrary
164 t::lib::Mocks::mock_preference('IndependentBranches', '0');
165 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
166 is(
167     C4::Context->preference('CircControl'),
168     'PickupLibrary',
169     'CircControl changed to PickupLibrary'
170 );
171 is(
172     C4::Circulation::_GetCircControlBranch($item, $borrower),
173     $item->{$HomeOrHoldingBranch},
174     '_GetCircControlBranch returned item branch (no userenv defined)'
175 );
176
177 # No userenv, PatronLibrary
178 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
179 is(
180     C4::Context->preference('CircControl'),
181     'PatronLibrary',
182     'CircControl changed to PatronLibrary'
183 );
184 is(
185     C4::Circulation::_GetCircControlBranch($item, $borrower),
186     $borrower->{branchcode},
187     '_GetCircControlBranch returned borrower branch'
188 );
189
190 # No userenv, ItemHomeLibrary
191 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
192 is(
193     C4::Context->preference('CircControl'),
194     'ItemHomeLibrary',
195     'CircControl changed to ItemHomeLibrary'
196 );
197 is(
198     $item->{$HomeOrHoldingBranch},
199     C4::Circulation::_GetCircControlBranch($item, $borrower),
200     '_GetCircControlBranch returned item branch'
201 );
202
203 # Now, set a userenv
204 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
205 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
206
207 # Userenv set, PickupLibrary
208 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
209 is(
210     C4::Context->preference('CircControl'),
211     'PickupLibrary',
212     'CircControl changed to PickupLibrary'
213 );
214 is(
215     C4::Circulation::_GetCircControlBranch($item, $borrower),
216     $library2->{branchcode},
217     '_GetCircControlBranch returned current branch'
218 );
219
220 # Userenv set, PatronLibrary
221 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
222 is(
223     C4::Context->preference('CircControl'),
224     'PatronLibrary',
225     'CircControl changed to PatronLibrary'
226 );
227 is(
228     C4::Circulation::_GetCircControlBranch($item, $borrower),
229     $borrower->{branchcode},
230     '_GetCircControlBranch returned borrower branch'
231 );
232
233 # Userenv set, ItemHomeLibrary
234 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
235 is(
236     C4::Context->preference('CircControl'),
237     'ItemHomeLibrary',
238     'CircControl changed to ItemHomeLibrary'
239 );
240 is(
241     C4::Circulation::_GetCircControlBranch($item, $borrower),
242     $item->{$HomeOrHoldingBranch},
243     '_GetCircControlBranch returned item branch'
244 );
245
246 # Reset initial configuration
247 t::lib::Mocks::mock_preference('CircControl', $CircControl);
248 is(
249     C4::Context->preference('CircControl'),
250     $CircControl,
251     'CircControl reset to its initial value'
252 );
253
254 # Set a simple circ policy
255 $dbh->do('DELETE FROM circulation_rules');
256 Koha::CirculationRules->set_rules(
257     {
258         categorycode => undef,
259         branchcode   => undef,
260         itemtype     => undef,
261         rules        => {
262             reservesallowed => 25,
263             issuelength     => 14,
264             lengthunit      => 'days',
265             renewalsallowed => 1,
266             renewalperiod   => 7,
267             norenewalbefore => undef,
268             auto_renew      => 0,
269             fine            => .10,
270             chargeperiod    => 1,
271         }
272     }
273 );
274
275 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
276 subtest "CanBookBeRenewed tests" => sub {
277     plan tests => 75;
278
279     C4::Context->set_preference('ItemsDeniedRenewal','');
280     # Generate test biblio
281     my $biblio = $builder->build_sample_biblio();
282
283     my $branch = $library2->{branchcode};
284
285     my $item_1 = $builder->build_sample_item(
286         {
287             biblionumber     => $biblio->biblionumber,
288             library          => $branch,
289             replacementprice => 12.00,
290             itype            => $itemtype
291         }
292     );
293     $reused_itemnumber_1 = $item_1->itemnumber;
294
295     my $item_2 = $builder->build_sample_item(
296         {
297             biblionumber     => $biblio->biblionumber,
298             library          => $branch,
299             replacementprice => 23.00,
300             itype            => $itemtype
301         }
302     );
303     $reused_itemnumber_2 = $item_2->itemnumber;
304
305     my $item_3 = $builder->build_sample_item(
306         {
307             biblionumber     => $biblio->biblionumber,
308             library          => $branch,
309             replacementprice => 23.00,
310             itype            => $itemtype
311         }
312     );
313
314     # Create borrowers
315     my %renewing_borrower_data = (
316         firstname =>  'John',
317         surname => 'Renewal',
318         categorycode => $patron_category->{categorycode},
319         branchcode => $branch,
320     );
321
322     my %reserving_borrower_data = (
323         firstname =>  'Katrin',
324         surname => 'Reservation',
325         categorycode => $patron_category->{categorycode},
326         branchcode => $branch,
327     );
328
329     my %hold_waiting_borrower_data = (
330         firstname =>  'Kyle',
331         surname => 'Reservation',
332         categorycode => $patron_category->{categorycode},
333         branchcode => $branch,
334     );
335
336     my %restricted_borrower_data = (
337         firstname =>  'Alice',
338         surname => 'Reservation',
339         categorycode => $patron_category->{categorycode},
340         debarred => '3228-01-01',
341         branchcode => $branch,
342     );
343
344     my %expired_borrower_data = (
345         firstname =>  'Ça',
346         surname => 'Glisse',
347         categorycode => $patron_category->{categorycode},
348         branchcode => $branch,
349         dateexpiry => dt_from_string->subtract( months => 1 ),
350     );
351
352     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
353     my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
354     my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
355     my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
356     my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
357
358     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
359     my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
360     my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
361
362     my $bibitems       = '';
363     my $priority       = '1';
364     my $resdate        = undef;
365     my $expdate        = undef;
366     my $notes          = '';
367     my $checkitem      = undef;
368     my $found          = undef;
369
370     my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
371     my $datedue = dt_from_string( $issue->date_due() );
372     is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
373
374     my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
375     $datedue = dt_from_string( $issue->date_due() );
376     is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
377
378
379     my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
380     is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
381
382     my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
383     is( $renewokay, 1, 'Can renew, no holds for this title or item');
384
385
386     # Biblio-level hold, renewal test
387     AddReserve(
388         {
389             branchcode       => $branch,
390             borrowernumber   => $reserving_borrowernumber,
391             biblionumber     => $biblio->biblionumber,
392             priority         => $priority,
393             reservation_date => $resdate,
394             expiration_date  => $expdate,
395             notes            => $notes,
396             itemnumber       => $checkitem,
397             found            => $found,
398         }
399     );
400
401     # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
402     Koha::CirculationRules->set_rule(
403         {
404             categorycode => undef,
405             branchcode   => undef,
406             itemtype     => undef,
407             rule_name    => 'onshelfholds',
408             rule_value   => '1',
409         }
410     );
411     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
412     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
413     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
414     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
415     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
416
417     # Now let's add an item level hold, we should no longer be able to renew the item
418     my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
419         {
420             borrowernumber => $hold_waiting_borrowernumber,
421             biblionumber   => $biblio->biblionumber,
422             itemnumber     => $item_1->itemnumber,
423             branchcode     => $branch,
424             priority       => 3,
425         }
426     );
427     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
428     is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
429     $hold->delete();
430
431     # Now let's add a waiting hold on the 3rd item, it's no longer available tp check out by just anyone, so we should no longer
432     # be able to renew these items
433     $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
434         {
435             borrowernumber => $hold_waiting_borrowernumber,
436             biblionumber   => $biblio->biblionumber,
437             itemnumber     => $item_3->itemnumber,
438             branchcode     => $branch,
439             priority       => 0,
440             found          => 'W'
441         }
442     );
443     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
444     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
445     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
446     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
447     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
448
449     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
450     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
451     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
452
453     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
454     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
455     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
456
457     my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
458     my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
459     AddIssue($reserving_borrower, $item_3->barcode);
460     my $reserve = $dbh->selectrow_hashref(
461         'SELECT * FROM old_reserves WHERE reserve_id = ?',
462         { Slice => {} },
463         $reserveid
464     );
465     is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
466
467     # Item-level hold, renewal test
468     AddReserve(
469         {
470             branchcode       => $branch,
471             borrowernumber   => $reserving_borrowernumber,
472             biblionumber     => $biblio->biblionumber,
473             priority         => $priority,
474             reservation_date => $resdate,
475             expiration_date  => $expdate,
476             notes            => $notes,
477             itemnumber       => $item_1->itemnumber,
478             found            => $found,
479         }
480     );
481
482     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
483     is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
484     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
485
486     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
487     is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
488
489     # Items can't fill hold for reasons
490     ModItem({ notforloan => 1 }, $biblio->biblionumber, $item_1->itemnumber);
491     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
492     is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
493     ModItem({ notforloan => 0, itype => $itemtype }, $biblio->biblionumber, $item_1->itemnumber);
494
495     # FIXME: Add more for itemtype not for loan etc.
496
497     # Restricted users cannot renew when RestrictionBlockRenewing is enabled
498     my $item_5 = $builder->build_sample_item(
499         {
500             biblionumber     => $biblio->biblionumber,
501             library          => $branch,
502             replacementprice => 23.00,
503             itype            => $itemtype,
504         }
505     );
506     my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
507     is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
508
509     t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
510     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
511     is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
512     ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
513     is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
514
515     # Users cannot renew an overdue item
516     my $item_6 = $builder->build_sample_item(
517         {
518             biblionumber     => $biblio->biblionumber,
519             library          => $branch,
520             replacementprice => 23.00,
521             itype            => $itemtype,
522         }
523     );
524
525     my $item_7 = $builder->build_sample_item(
526         {
527             biblionumber     => $biblio->biblionumber,
528             library          => $branch,
529             replacementprice => 23.00,
530             itype            => $itemtype,
531         }
532     );
533
534     my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
535     is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
536
537     my $now = dt_from_string();
538     my $five_weeks = DateTime::Duration->new(weeks => 5);
539     my $five_weeks_ago = $now - $five_weeks;
540     t::lib::Mocks::mock_preference('finesMode', 'production');
541
542     my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
543     is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
544
545     my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
546     C4::Overdues::UpdateFine(
547         {
548             issue_id       => $passeddatedue1->id(),
549             itemnumber     => $item_7->itemnumber,
550             borrowernumber => $renewing_borrower->{borrowernumber},
551             amount         => $fine,
552             due            => Koha::DateUtils::output_pref($five_weeks_ago)
553         }
554     );
555
556     t::lib::Mocks::mock_preference('RenewalLog', 0);
557     my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
558     my %params_renewal = (
559         timestamp => { -like => $date . "%" },
560         module => "CIRCULATION",
561         action => "RENEWAL",
562     );
563     my %params_issue = (
564         timestamp => { -like => $date . "%" },
565         module => "CIRCULATION",
566         action => "ISSUE"
567     );
568     my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
569     my $dt = dt_from_string();
570     Time::Fake->offset( $dt->epoch );
571     my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
572     my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
573     is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
574     isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
575     Time::Fake->reset;
576
577     t::lib::Mocks::mock_preference('RenewalLog', 1);
578     $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
579     $old_log_size = Koha::ActionLogs->count( \%params_renewal );
580     AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
581     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
582     is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
583
584     my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
585     is( $fines->count, 2, 'AddRenewal left both fines' );
586     isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
587     isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
588     $fines->delete();
589
590
591     my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
592     my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
593     AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
594     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
595     is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
596     $new_log_size = Koha::ActionLogs->count( \%params_issue );
597     is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
598
599     $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
600     $fines->delete();
601
602     t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
603     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
604     is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
605     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
606     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
607
608
609     $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
610     $hold->cancel;
611
612     # Bug 14101
613     # Test automatic renewal before value for "norenewalbefore" in policy is set
614     # In this case automatic renewal is not permitted prior to due date
615     my $item_4 = $builder->build_sample_item(
616         {
617             biblionumber     => $biblio->biblionumber,
618             library          => $branch,
619             replacementprice => 16.00,
620             itype            => $itemtype,
621         }
622     );
623
624     $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
625     ( $renewokay, $error ) =
626       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
627     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
628     is( $error, 'auto_too_soon',
629         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
630     AddReserve(
631         $branch, $reserving_borrowernumber, $biblio->biblionumber,
632         $bibitems,  $priority, $resdate, $expdate, $notes,
633         'a title', $item_4->itemnumber, $found
634     );
635     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
636     is( $renewokay, 0, 'Still should not be able to renew' );
637     is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked' );
638     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
639     is( $renewokay, 0, 'Still should not be able to renew' );
640     is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
641
642
643
644     # Bug 7413
645     # Test premature manual renewal
646     Koha::CirculationRules->set_rule(
647         {
648             categorycode => undef,
649             branchcode   => undef,
650             itemtype     => undef,
651             rule_name    => 'norenewalbefore',
652             rule_value   => '7',
653         }
654     );
655
656     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
657     is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
658     is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
659
660     # Bug 14395
661     # Test 'exact time' setting for syspref NoRenewalBeforePrecision
662     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
663     is(
664         GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
665         $datedue->clone->add( days => -7 ),
666         'Bug 14395: Renewals permitted 7 days before due date, as expected'
667     );
668
669     # Bug 14395
670     # Test 'date' setting for syspref NoRenewalBeforePrecision
671     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
672     is(
673         GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
674         $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
675         'Bug 14395: Renewals permitted 7 days before due date, as expected'
676     );
677
678     # Bug 14101
679     # Test premature automatic renewal
680     ( $renewokay, $error ) =
681       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
682     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
683     is( $error, 'auto_too_soon',
684         'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
685     );
686
687     # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
688     # and test automatic renewal again
689     $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
690     ( $renewokay, $error ) =
691       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
692     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
693     is( $error, 'auto_too_soon',
694         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
695     );
696
697     # Change policy so that loans can be renewed 99 days prior to the due date
698     # and test automatic renewal again
699     $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
700     ( $renewokay, $error ) =
701       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
702     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
703     is( $error, 'auto_renew',
704         'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
705     );
706
707     subtest "too_late_renewal / no_auto_renewal_after" => sub {
708         plan tests => 14;
709         my $item_to_auto_renew = $builder->build(
710             {   source => 'Item',
711                 value  => {
712                     biblionumber  => $biblio->biblionumber,
713                     homebranch    => $branch,
714                     holdingbranch => $branch,
715                 }
716             }
717         );
718
719         my $ten_days_before = dt_from_string->add( days => -10 );
720         my $ten_days_ahead  = dt_from_string->add( days => 10 );
721         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
722
723         Koha::CirculationRules->set_rules(
724             {
725                 categorycode => undef,
726                 branchcode   => undef,
727                 itemtype     => undef,
728                 rules        => {
729                     norenewalbefore       => '7',
730                     no_auto_renewal_after => '9',
731                 }
732             }
733         );
734         ( $renewokay, $error ) =
735           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
736         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
737         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
738
739         Koha::CirculationRules->set_rules(
740             {
741                 categorycode => undef,
742                 branchcode   => undef,
743                 itemtype     => undef,
744                 rules        => {
745                     norenewalbefore       => '7',
746                     no_auto_renewal_after => '10',
747                 }
748             }
749         );
750         ( $renewokay, $error ) =
751           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
752         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
753         is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
754
755         Koha::CirculationRules->set_rules(
756             {
757                 categorycode => undef,
758                 branchcode   => undef,
759                 itemtype     => undef,
760                 rules        => {
761                     norenewalbefore       => '7',
762                     no_auto_renewal_after => '11',
763                 }
764             }
765         );
766         ( $renewokay, $error ) =
767           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
768         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
769         is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
770
771         Koha::CirculationRules->set_rules(
772             {
773                 categorycode => undef,
774                 branchcode   => undef,
775                 itemtype     => undef,
776                 rules        => {
777                     norenewalbefore       => '10',
778                     no_auto_renewal_after => '11',
779                 }
780             }
781         );
782         ( $renewokay, $error ) =
783           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
784         is( $renewokay, 0,            'Do not renew, renewal is automatic' );
785         is( $error,     'auto_renew', 'Cannot renew, renew is automatic' );
786
787         Koha::CirculationRules->set_rules(
788             {
789                 categorycode => undef,
790                 branchcode   => undef,
791                 itemtype     => undef,
792                 rules        => {
793                     norenewalbefore       => '10',
794                     no_auto_renewal_after => undef,
795                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
796                 }
797             }
798         );
799         ( $renewokay, $error ) =
800           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
801         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
802         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
803
804         Koha::CirculationRules->set_rules(
805             {
806                 categorycode => undef,
807                 branchcode   => undef,
808                 itemtype     => undef,
809                 rules        => {
810                     norenewalbefore       => '7',
811                     no_auto_renewal_after => '15',
812                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
813                 }
814             }
815         );
816         ( $renewokay, $error ) =
817           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
818         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
819         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
820
821         Koha::CirculationRules->set_rules(
822             {
823                 categorycode => undef,
824                 branchcode   => undef,
825                 itemtype     => undef,
826                 rules        => {
827                     norenewalbefore       => '10',
828                     no_auto_renewal_after => undef,
829                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
830                 }
831             }
832         );
833         ( $renewokay, $error ) =
834           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
835         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
836         is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
837     };
838
839     subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
840         plan tests => 10;
841         my $item_to_auto_renew = $builder->build({
842             source => 'Item',
843             value => {
844                 biblionumber => $biblio->biblionumber,
845                 homebranch       => $branch,
846                 holdingbranch    => $branch,
847             }
848         });
849
850         my $ten_days_before = dt_from_string->add( days => -10 );
851         my $ten_days_ahead = dt_from_string->add( days => 10 );
852         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
853
854         Koha::CirculationRules->set_rules(
855             {
856                 categorycode => undef,
857                 branchcode   => undef,
858                 itemtype     => undef,
859                 rules        => {
860                     norenewalbefore       => '10',
861                     no_auto_renewal_after => '11',
862                 }
863             }
864         );
865         C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
866         C4::Context->set_preference('OPACFineNoRenewals','10');
867         C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
868         my $fines_amount = 5;
869         my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
870         $account->add_debit(
871             {
872                 amount      => $fines_amount,
873                 interface   => 'test',
874                 type        => 'OVERDUE',
875                 item_id     => $item_to_auto_renew->{itemnumber},
876                 description => "Some fines"
877             }
878         )->status('RETURNED')->store;
879         ( $renewokay, $error ) =
880           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
881         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
882         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
883
884         $account->add_debit(
885             {
886                 amount      => $fines_amount,
887                 interface   => 'test',
888                 type        => 'OVERDUE',
889                 item_id     => $item_to_auto_renew->{itemnumber},
890                 description => "Some fines"
891             }
892         )->status('RETURNED')->store;
893         ( $renewokay, $error ) =
894           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
895         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
896         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
897
898         $account->add_debit(
899             {
900                 amount      => $fines_amount,
901                 interface   => 'test',
902                 type        => 'OVERDUE',
903                 item_id     => $item_to_auto_renew->{itemnumber},
904                 description => "Some fines"
905             }
906         )->status('RETURNED')->store;
907         ( $renewokay, $error ) =
908           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
909         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
910         is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
911
912         $account->add_credit(
913             {
914                 amount      => $fines_amount,
915                 interface   => 'test',
916                 type        => 'PAYMENT',
917                 description => "Some payment"
918             }
919         )->store;
920         ( $renewokay, $error ) =
921           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
922         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
923         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit'  );
924
925         C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
926         ( $renewokay, $error ) =
927           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
928         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
929         is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit'  );
930
931         $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
932         C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
933     };
934
935     subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
936         plan tests => 6;
937         my $item_to_auto_renew = $builder->build({
938             source => 'Item',
939             value => {
940                 biblionumber => $biblio->biblionumber,
941                 homebranch       => $branch,
942                 holdingbranch    => $branch,
943             }
944         });
945
946         Koha::CirculationRules->set_rules(
947             {
948                 categorycode => undef,
949                 branchcode   => undef,
950                 itemtype     => undef,
951                 rules        => {
952                     norenewalbefore       => 10,
953                     no_auto_renewal_after => 11,
954                 }
955             }
956         );
957
958         my $ten_days_before = dt_from_string->add( days => -10 );
959         my $ten_days_ahead = dt_from_string->add( days => 10 );
960
961         # Patron is expired and BlockExpiredPatronOpacActions=0
962         # => auto renew is allowed
963         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
964         my $patron = $expired_borrower;
965         my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
966         ( $renewokay, $error ) =
967           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
968         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
969         is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
970         Koha::Checkouts->find( $checkout->issue_id )->delete;
971
972
973         # Patron is expired and BlockExpiredPatronOpacActions=1
974         # => auto renew is not allowed
975         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
976         $patron = $expired_borrower;
977         $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
978         ( $renewokay, $error ) =
979           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
980         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
981         is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
982         Koha::Checkouts->find( $checkout->issue_id )->delete;
983
984
985         # Patron is not expired and BlockExpiredPatronOpacActions=1
986         # => auto renew is allowed
987         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
988         $patron = $renewing_borrower;
989         $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
990         ( $renewokay, $error ) =
991           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
992         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
993         is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
994         Koha::Checkouts->find( $checkout->issue_id )->delete;
995     };
996
997     subtest "GetLatestAutoRenewDate" => sub {
998         plan tests => 5;
999         my $item_to_auto_renew = $builder->build(
1000             {   source => 'Item',
1001                 value  => {
1002                     biblionumber  => $biblio->biblionumber,
1003                     homebranch    => $branch,
1004                     holdingbranch => $branch,
1005                 }
1006             }
1007         );
1008
1009         my $ten_days_before = dt_from_string->add( days => -10 );
1010         my $ten_days_ahead  = dt_from_string->add( days => 10 );
1011         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1012         Koha::CirculationRules->set_rules(
1013             {
1014                 categorycode => undef,
1015                 branchcode   => undef,
1016                 itemtype     => undef,
1017                 rules        => {
1018                     norenewalbefore       => '7',
1019                     no_auto_renewal_after => '',
1020                     no_auto_renewal_after_hard_limit => undef,
1021                 }
1022             }
1023         );
1024         my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1025         is( $latest_auto_renew_date, undef, 'GetLatestAutoRenewDate should return undef if no_auto_renewal_after or no_auto_renewal_after_hard_limit are not defined' );
1026         my $five_days_before = dt_from_string->add( days => -5 );
1027         Koha::CirculationRules->set_rules(
1028             {
1029                 categorycode => undef,
1030                 branchcode   => undef,
1031                 itemtype     => undef,
1032                 rules        => {
1033                     norenewalbefore       => '10',
1034                     no_auto_renewal_after => '5',
1035                     no_auto_renewal_after_hard_limit => undef,
1036                 }
1037             }
1038         );
1039         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1040         is( $latest_auto_renew_date->truncate( to => 'minute' ),
1041             $five_days_before->truncate( to => 'minute' ),
1042             'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1043         );
1044         my $five_days_ahead = dt_from_string->add( days => 5 );
1045         $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1046         $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1047         $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1048         Koha::CirculationRules->set_rules(
1049             {
1050                 categorycode => undef,
1051                 branchcode   => undef,
1052                 itemtype     => undef,
1053                 rules        => {
1054                     norenewalbefore       => '10',
1055                     no_auto_renewal_after => '15',
1056                     no_auto_renewal_after_hard_limit => undef,
1057                 }
1058             }
1059         );
1060         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1061         is( $latest_auto_renew_date->truncate( to => 'minute' ),
1062             $five_days_ahead->truncate( to => 'minute' ),
1063             'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1064         );
1065         my $two_days_ahead = dt_from_string->add( days => 2 );
1066         Koha::CirculationRules->set_rules(
1067             {
1068                 categorycode => undef,
1069                 branchcode   => undef,
1070                 itemtype     => undef,
1071                 rules        => {
1072                     norenewalbefore       => '10',
1073                     no_auto_renewal_after => '',
1074                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1075                 }
1076             }
1077         );
1078         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1079         is( $latest_auto_renew_date->truncate( to => 'day' ),
1080             $two_days_ahead->truncate( to => 'day' ),
1081             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1082         );
1083         Koha::CirculationRules->set_rules(
1084             {
1085                 categorycode => undef,
1086                 branchcode   => undef,
1087                 itemtype     => undef,
1088                 rules        => {
1089                     norenewalbefore       => '10',
1090                     no_auto_renewal_after => '15',
1091                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1092                 }
1093             }
1094         );
1095         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1096         is( $latest_auto_renew_date->truncate( to => 'day' ),
1097             $two_days_ahead->truncate( to => 'day' ),
1098             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1099         );
1100
1101     };
1102     # Too many renewals
1103
1104     # set policy to forbid renewals
1105     Koha::CirculationRules->set_rules(
1106         {
1107             categorycode => undef,
1108             branchcode   => undef,
1109             itemtype     => undef,
1110             rules        => {
1111                 norenewalbefore => undef,
1112                 renewalsallowed => 0,
1113             }
1114         }
1115     );
1116
1117     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1118     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1119     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1120
1121     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1122     t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1123     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1124
1125     C4::Overdues::UpdateFine(
1126         {
1127             issue_id       => $issue->id(),
1128             itemnumber     => $item_1->itemnumber,
1129             borrowernumber => $renewing_borrower->{borrowernumber},
1130             amount         => 15.00,
1131             type           => q{},
1132             due            => Koha::DateUtils::output_pref($datedue)
1133         }
1134     );
1135
1136     my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
1137     is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1138     is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1139     is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1140     is( $line->amount+0, 15, 'Account line amount is 15.00' );
1141     is( $line->issue_id, $issue->id, 'Account line issue id matches' );
1142
1143     my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1144     is( $offset->type, 'OVERDUE', 'Account offset type is Fine' );
1145     is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1146
1147     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1148     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1149
1150     LostItem( $item_1->itemnumber, 'test', 1 );
1151
1152     $line = Koha::Account::Lines->find($line->id);
1153     is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1154     isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1155
1156     my $item = Koha::Items->find($item_1->itemnumber);
1157     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1158     my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1159     is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1160
1161     my $total_due = $dbh->selectrow_array(
1162         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1163         undef, $renewing_borrower->{borrowernumber}
1164     );
1165
1166     is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1167
1168     C4::Context->dbh->do("DELETE FROM accountlines");
1169
1170     C4::Overdues::UpdateFine(
1171         {
1172             issue_id       => $issue2->id(),
1173             itemnumber     => $item_2->itemnumber,
1174             borrowernumber => $renewing_borrower->{borrowernumber},
1175             amount         => 15.00,
1176             type           => q{},
1177             due            => Koha::DateUtils::output_pref($datedue)
1178         }
1179     );
1180
1181     LostItem( $item_2->itemnumber, 'test', 0 );
1182
1183     my $item2 = Koha::Items->find($item_2->itemnumber);
1184     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1185     ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1186
1187     $total_due = $dbh->selectrow_array(
1188         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1189         undef, $renewing_borrower->{borrowernumber}
1190     );
1191
1192     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1193
1194     my $future = dt_from_string();
1195     $future->add( days => 7 );
1196     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1197     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1198
1199     # Users cannot renew any item if there is an overdue item
1200     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
1201     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
1202     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1203     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
1204     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1205
1206     my $manager = $builder->build_object({ class => "Koha::Patrons" });
1207     t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1208     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1209     $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1210     LostItem( $item_3->itemnumber, 'test', 0 );
1211     my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1212     is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1213     is(
1214         $accountline->description,
1215         sprintf( "%s %s %s",
1216             $item_3->biblio->title  || '',
1217             $item_3->barcode        || '',
1218             $item_3->itemcallnumber || '' ),
1219         "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1220     );
1221 };
1222
1223 subtest "GetUpcomingDueIssues" => sub {
1224     plan tests => 12;
1225
1226     my $branch   = $library2->{branchcode};
1227
1228     #Create another record
1229     my $biblio2 = $builder->build_sample_biblio();
1230
1231     #Create third item
1232     my $item_1 = Koha::Items->find($reused_itemnumber_1);
1233     my $item_2 = Koha::Items->find($reused_itemnumber_2);
1234     my $item_3 = $builder->build_sample_item(
1235         {
1236             biblionumber     => $biblio2->biblionumber,
1237             library          => $branch,
1238             itype            => $itemtype,
1239         }
1240     );
1241
1242
1243     # Create a borrower
1244     my %a_borrower_data = (
1245         firstname =>  'Fridolyn',
1246         surname => 'SOMERS',
1247         categorycode => $patron_category->{categorycode},
1248         branchcode => $branch,
1249     );
1250
1251     my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1252     my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1253
1254     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1255     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1256     my $today = DateTime->today(time_zone => C4::Context->tz());
1257
1258     my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1259     my $datedue = dt_from_string( $issue->date_due() );
1260     my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1261     my $datedue2 = dt_from_string( $issue->date_due() );
1262
1263     my $upcoming_dues;
1264
1265     # GetUpcomingDueIssues tests
1266     for my $i(0..1) {
1267         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1268         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1269     }
1270
1271     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1272     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1273     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1274
1275     for my $i(3..5) {
1276         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1277         is ( scalar( @$upcoming_dues ), 1,
1278             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1279     }
1280
1281     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1282
1283     my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1284
1285     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1286     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1287
1288     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1289     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1290
1291     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1292     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1293
1294     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
1295     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1296
1297     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1298     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1299
1300     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1301     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1302
1303 };
1304
1305 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1306     my $branch   = $library2->{branchcode};
1307
1308     my $biblio = $builder->build_sample_biblio();
1309
1310     #Create third item
1311     my $item = $builder->build_sample_item(
1312         {
1313             biblionumber     => $biblio->biblionumber,
1314             library          => $branch,
1315             itype            => $itemtype,
1316         }
1317     );
1318
1319     # Create a borrower
1320     my %a_borrower_data = (
1321         firstname =>  'Kyle',
1322         surname => 'Hall',
1323         categorycode => $patron_category->{categorycode},
1324         branchcode => $branch,
1325     );
1326
1327     my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1328
1329     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1330     my $issue = AddIssue( $borrower, $item->barcode );
1331     UpdateFine(
1332         {
1333             issue_id       => $issue->id(),
1334             itemnumber     => $item->itemnumber,
1335             borrowernumber => $borrowernumber,
1336             amount         => 0,
1337             type           => q{}
1338         }
1339     );
1340
1341     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1342     my $count = $hr->{count};
1343
1344     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1345 };
1346
1347 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1348     $dbh->do('DELETE FROM issues');
1349     $dbh->do('DELETE FROM items');
1350     $dbh->do('DELETE FROM circulation_rules');
1351     Koha::CirculationRules->set_rules(
1352         {
1353             categorycode => undef,
1354             itemtype     => undef,
1355             branchcode   => undef,
1356             rules        => {
1357                 reservesallowed => 25,
1358                 issuelength     => 14,
1359                 lengthunit      => 'days',
1360                 renewalsallowed => 1,
1361                 renewalperiod   => 7,
1362                 norenewalbefore => undef,
1363                 auto_renew      => 0,
1364                 fine            => .10,
1365                 chargeperiod    => 1,
1366                 maxissueqty     => 20
1367             }
1368         }
1369     );
1370     my $biblio = $builder->build_sample_biblio();
1371
1372     my $item_1 = $builder->build_sample_item(
1373         {
1374             biblionumber     => $biblio->biblionumber,
1375             library          => $library2->{branchcode},
1376             itype            => $itemtype,
1377         }
1378     );
1379
1380     my $item_2= $builder->build_sample_item(
1381         {
1382             biblionumber     => $biblio->biblionumber,
1383             library          => $library2->{branchcode},
1384             itype            => $itemtype,
1385         }
1386     );
1387
1388     my $borrowernumber1 = Koha::Patron->new({
1389         firstname    => 'Kyle',
1390         surname      => 'Hall',
1391         categorycode => $patron_category->{categorycode},
1392         branchcode   => $library2->{branchcode},
1393     })->store->borrowernumber;
1394     my $borrowernumber2 = Koha::Patron->new({
1395         firstname    => 'Chelsea',
1396         surname      => 'Hall',
1397         categorycode => $patron_category->{categorycode},
1398         branchcode   => $library2->{branchcode},
1399     })->store->borrowernumber;
1400
1401     my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1402     my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1403
1404     my $issue = AddIssue( $borrower1, $item_1->barcode );
1405
1406     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1407     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1408
1409     AddReserve(
1410         {
1411             branchcode     => $library2->{branchcode},
1412             borrowernumber => $borrowernumber2,
1413             biblionumber   => $biblio->biblionumber,
1414             priority       => 1,
1415         }
1416     );
1417
1418     Koha::CirculationRules->set_rules(
1419         {
1420             categorycode => undef,
1421             itemtype     => undef,
1422             branchcode   => undef,
1423             rules        => {
1424                 onshelfholds => 0,
1425             }
1426         }
1427     );
1428     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1429     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1430     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1431
1432     Koha::CirculationRules->set_rules(
1433         {
1434             categorycode => undef,
1435             itemtype     => undef,
1436             branchcode   => undef,
1437             rules        => {
1438                 onshelfholds => 0,
1439             }
1440         }
1441     );
1442     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1443     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1444     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1445
1446     Koha::CirculationRules->set_rules(
1447         {
1448             categorycode => undef,
1449             itemtype     => undef,
1450             branchcode   => undef,
1451             rules        => {
1452                 onshelfholds => 1,
1453             }
1454         }
1455     );
1456     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1457     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1458     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1459
1460     Koha::CirculationRules->set_rules(
1461         {
1462             categorycode => undef,
1463             itemtype     => undef,
1464             branchcode   => undef,
1465             rules        => {
1466                 onshelfholds => 1,
1467             }
1468         }
1469     );
1470     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1471     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1472     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1473
1474     # Setting item not checked out to be not for loan but holdable
1475     ModItem({ notforloan => -1 }, $biblio->biblionumber, $item_2->itemnumber);
1476
1477     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1478     is( $renewokay, 0, 'Bug 14337 - Verify the borrower can not renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled but the only available item is notforloan' );
1479 };
1480
1481 {
1482     # Don't allow renewing onsite checkout
1483     my $branch   = $library->{branchcode};
1484
1485     #Create another record
1486     my $biblio = $builder->build_sample_biblio();
1487
1488     my $item = $builder->build_sample_item(
1489         {
1490             biblionumber     => $biblio->biblionumber,
1491             library          => $branch,
1492             itype            => $itemtype,
1493         }
1494     );
1495
1496     my $borrowernumber = Koha::Patron->new({
1497         firstname =>  'fn',
1498         surname => 'dn',
1499         categorycode => $patron_category->{categorycode},
1500         branchcode => $branch,
1501     })->store->borrowernumber;
1502
1503     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1504
1505     my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1506     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1507     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1508     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1509 }
1510
1511 {
1512     my $library = $builder->build({ source => 'Branch' });
1513
1514     my $biblio = $builder->build_sample_biblio();
1515
1516     my $item = $builder->build_sample_item(
1517         {
1518             biblionumber     => $biblio->biblionumber,
1519             library          => $library->{branchcode},
1520             itype            => $itemtype,
1521         }
1522     );
1523
1524     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1525
1526     my $issue = AddIssue( $patron, $item->barcode );
1527     UpdateFine(
1528         {
1529             issue_id       => $issue->id(),
1530             itemnumber     => $item->itemnumber,
1531             borrowernumber => $patron->{borrowernumber},
1532             amount         => 1,
1533             type           => q{}
1534         }
1535     );
1536     UpdateFine(
1537         {
1538             issue_id       => $issue->id(),
1539             itemnumber     => $item->itemnumber,
1540             borrowernumber => $patron->{borrowernumber},
1541             amount         => 2,
1542             type           => q{}
1543         }
1544     );
1545     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1546 }
1547
1548 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1549     plan tests => 24;
1550
1551     my $homebranch    = $builder->build( { source => 'Branch' } );
1552     my $holdingbranch = $builder->build( { source => 'Branch' } );
1553     my $otherbranch   = $builder->build( { source => 'Branch' } );
1554     my $patron_1      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1555     my $patron_2      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1556
1557     my $item = $builder->build_sample_item(
1558         {
1559             homebranch    => $homebranch->{branchcode},
1560             holdingbranch => $holdingbranch->{branchcode},
1561         }
1562     )->unblessed;
1563
1564     set_userenv($holdingbranch);
1565
1566     my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1567     is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1568
1569     my ( $error, $question, $alerts );
1570
1571     # AllowReturnToBranch == anywhere
1572     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1573     ## Test that unknown barcodes don't generate internal server errors
1574     set_userenv($homebranch);
1575     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1576     ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1577     ## Can be issued from homebranch
1578     set_userenv($homebranch);
1579     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1580     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1581     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1582     ## Can be issued from holdingbranch
1583     set_userenv($holdingbranch);
1584     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1585     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1586     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1587     ## Can be issued from another branch
1588     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1589     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1590     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1591
1592     # AllowReturnToBranch == holdingbranch
1593     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1594     ## Cannot be issued from homebranch
1595     set_userenv($homebranch);
1596     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1597     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1598     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1599     is( $error->{branch_to_return},         $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1600     ## Can be issued from holdinbranch
1601     set_userenv($holdingbranch);
1602     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1603     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1604     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1605     ## Cannot be issued from another branch
1606     set_userenv($otherbranch);
1607     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1608     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1609     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1610     is( $error->{branch_to_return},         $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
1611
1612     # AllowReturnToBranch == homebranch
1613     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1614     ## Can be issued from holdinbranch
1615     set_userenv($homebranch);
1616     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1617     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1618     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1619     ## Cannot be issued from holdinbranch
1620     set_userenv($holdingbranch);
1621     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1622     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1623     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1624     is( $error->{branch_to_return},         $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1625     ## Cannot be issued from holdinbranch
1626     set_userenv($otherbranch);
1627     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1628     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1629     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1630     is( $error->{branch_to_return},         $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1631
1632     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1633 };
1634
1635 subtest 'AddIssue & AllowReturnToBranch' => sub {
1636     plan tests => 9;
1637
1638     my $homebranch    = $builder->build( { source => 'Branch' } );
1639     my $holdingbranch = $builder->build( { source => 'Branch' } );
1640     my $otherbranch   = $builder->build( { source => 'Branch' } );
1641     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1642     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1643
1644     my $item = $builder->build_sample_item(
1645         {
1646             homebranch    => $homebranch->{branchcode},
1647             holdingbranch => $holdingbranch->{branchcode},
1648         }
1649     )->unblessed;
1650
1651     set_userenv($holdingbranch);
1652
1653     my $ref_issue = 'Koha::Checkout';
1654     my $issue = AddIssue( $patron_1, $item->{barcode} );
1655
1656     my ( $error, $question, $alerts );
1657
1658     # AllowReturnToBranch == homebranch
1659     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1660     ## Can be issued from homebranch
1661     set_userenv($homebranch);
1662     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
1663     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1664     ## Can be issued from holdinbranch
1665     set_userenv($holdingbranch);
1666     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
1667     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1668     ## Can be issued from another branch
1669     set_userenv($otherbranch);
1670     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
1671     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1672
1673     # AllowReturnToBranch == holdinbranch
1674     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1675     ## Cannot be issued from homebranch
1676     set_userenv($homebranch);
1677     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
1678     ## Can be issued from holdingbranch
1679     set_userenv($holdingbranch);
1680     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
1681     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1682     ## Cannot be issued from another branch
1683     set_userenv($otherbranch);
1684     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
1685
1686     # AllowReturnToBranch == homebranch
1687     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1688     ## Can be issued from homebranch
1689     set_userenv($homebranch);
1690     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
1691     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1692     ## Cannot be issued from holdinbranch
1693     set_userenv($holdingbranch);
1694     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
1695     ## Cannot be issued from another branch
1696     set_userenv($otherbranch);
1697     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
1698     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1699 };
1700
1701 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1702     plan tests => 8;
1703
1704     my $library = $builder->build( { source => 'Branch' } );
1705     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1706     my $item_1 = $builder->build_sample_item(
1707         {
1708             library => $library->{branchcode},
1709         }
1710     )->unblessed;
1711     my $item_2 = $builder->build_sample_item(
1712         {
1713             library => $library->{branchcode},
1714         }
1715     )->unblessed;
1716
1717     my ( $error, $question, $alerts );
1718
1719     # Patron cannot issue item_1, they have overdues
1720     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1721     my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday );    # Add an overdue
1722
1723     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1724     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1725     is( keys(%$error) + keys(%$alerts),  0, 'No key for error and alert' . str($error, $question, $alerts) );
1726     is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1727
1728     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1729     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1730     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1731     is( $error->{USERBLOCKEDOVERDUE},      1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1732
1733     # Patron cannot issue item_1, they are debarred
1734     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1735     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1736     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1737     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1738     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1739
1740     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1741     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1742     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1743     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1744 };
1745
1746 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1747     plan tests => 1;
1748
1749     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1750     my $patron_category_x = $builder->build_object(
1751         {
1752             class => 'Koha::Patron::Categories',
1753             value => { category_type => 'X' }
1754         }
1755     );
1756     my $patron = $builder->build_object(
1757         {
1758             class => 'Koha::Patrons',
1759             value => {
1760                 categorycode  => $patron_category_x->categorycode,
1761                 gonenoaddress => undef,
1762                 lost          => undef,
1763                 debarred      => undef,
1764                 borrowernotes => ""
1765             }
1766         }
1767     );
1768     my $item_1 = $builder->build_sample_item(
1769         {
1770             library => $library->{branchcode},
1771         }
1772     )->unblessed;
1773
1774     my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1775     is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1776
1777     # TODO There are other tests to provide here
1778 };
1779
1780 subtest 'MultipleReserves' => sub {
1781     plan tests => 3;
1782
1783     my $biblio = $builder->build_sample_biblio();
1784
1785     my $branch = $library2->{branchcode};
1786
1787     my $item_1 = $builder->build_sample_item(
1788         {
1789             biblionumber     => $biblio->biblionumber,
1790             library          => $branch,
1791             replacementprice => 12.00,
1792             itype            => $itemtype,
1793         }
1794     );
1795
1796     my $item_2 = $builder->build_sample_item(
1797         {
1798             biblionumber     => $biblio->biblionumber,
1799             library          => $branch,
1800             replacementprice => 12.00,
1801             itype            => $itemtype,
1802         }
1803     );
1804
1805     my $bibitems       = '';
1806     my $priority       = '1';
1807     my $resdate        = undef;
1808     my $expdate        = undef;
1809     my $notes          = '';
1810     my $checkitem      = undef;
1811     my $found          = undef;
1812
1813     my %renewing_borrower_data = (
1814         firstname =>  'John',
1815         surname => 'Renewal',
1816         categorycode => $patron_category->{categorycode},
1817         branchcode => $branch,
1818     );
1819     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1820     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1821     my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1822     my $datedue = dt_from_string( $issue->date_due() );
1823     is (defined $issue->date_due(), 1, "item 1 checked out");
1824     my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1825
1826     my %reserving_borrower_data1 = (
1827         firstname =>  'Katrin',
1828         surname => 'Reservation',
1829         categorycode => $patron_category->{categorycode},
1830         branchcode => $branch,
1831     );
1832     my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1833     AddReserve(
1834         {
1835             branchcode       => $branch,
1836             borrowernumber   => $reserving_borrowernumber1,
1837             biblionumber     => $biblio->biblionumber,
1838             priority         => $priority,
1839             reservation_date => $resdate,
1840             expiration_date  => $expdate,
1841             notes            => $notes,
1842             itemnumber       => $checkitem,
1843             found            => $found,
1844         }
1845     );
1846
1847     my %reserving_borrower_data2 = (
1848         firstname =>  'Kirk',
1849         surname => 'Reservation',
1850         categorycode => $patron_category->{categorycode},
1851         branchcode => $branch,
1852     );
1853     my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1854     AddReserve(
1855         {
1856             branchcode       => $branch,
1857             borrowernumber   => $reserving_borrowernumber2,
1858             biblionumber     => $biblio->biblionumber,
1859             priority         => $priority,
1860             reservation_date => $resdate,
1861             expiration_date  => $expdate,
1862             notes            => $notes,
1863             itemnumber       => $checkitem,
1864             found            => $found,
1865         }
1866     );
1867
1868     {
1869         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1870         is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1871     }
1872
1873     my $item_3 = $builder->build_sample_item(
1874         {
1875             biblionumber     => $biblio->biblionumber,
1876             library          => $branch,
1877             replacementprice => 12.00,
1878             itype            => $itemtype,
1879         }
1880     );
1881
1882     {
1883         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1884         is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1885     }
1886 };
1887
1888 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1889     plan tests => 5;
1890
1891     my $library = $builder->build( { source => 'Branch' } );
1892     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1893
1894     my $biblionumber = $builder->build_sample_biblio(
1895         {
1896             branchcode => $library->{branchcode},
1897         }
1898     )->biblionumber;
1899     my $item_1 = $builder->build_sample_item(
1900         {
1901             biblionumber => $biblionumber,
1902             library      => $library->{branchcode},
1903         }
1904     )->unblessed;
1905
1906     my $item_2 = $builder->build_sample_item(
1907         {
1908             biblionumber => $biblionumber,
1909             library      => $library->{branchcode},
1910         }
1911     )->unblessed;
1912
1913     my ( $error, $question, $alerts );
1914     my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1915
1916     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1917     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1918     cmp_deeply(
1919         { error => $error, alerts => $alerts },
1920         { error => {}, alerts => {} },
1921         'No error or alert should be raised'
1922     );
1923     is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
1924
1925     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1926     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1927     cmp_deeply(
1928         { error => $error, question => $question, alerts => $alerts },
1929         { error => {}, question => {}, alerts => {} },
1930         'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
1931     );
1932
1933     # Add a subscription
1934     Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1935
1936     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1937     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1938     cmp_deeply(
1939         { error => $error, question => $question, alerts => $alerts },
1940         { error => {}, question => {}, alerts => {} },
1941         'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
1942     );
1943
1944     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1945     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1946     cmp_deeply(
1947         { error => $error, question => $question, alerts => $alerts },
1948         { error => {}, question => {}, alerts => {} },
1949         'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
1950     );
1951 };
1952
1953 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1954     plan tests => 8;
1955
1956     my $library = $builder->build( { source => 'Branch' } );
1957     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1958
1959     # Add 2 items
1960     my $biblionumber = $builder->build_sample_biblio(
1961         {
1962             branchcode => $library->{branchcode},
1963         }
1964     )->biblionumber;
1965     my $item_1 = $builder->build_sample_item(
1966         {
1967             biblionumber => $biblionumber,
1968             library      => $library->{branchcode},
1969         }
1970     )->unblessed;
1971     my $item_2 = $builder->build_sample_item(
1972         {
1973             biblionumber => $biblionumber,
1974             library      => $library->{branchcode},
1975         }
1976     )->unblessed;
1977
1978     # And the circulation rule
1979     Koha::CirculationRules->search->delete;
1980     Koha::CirculationRules->set_rules(
1981         {
1982             categorycode => undef,
1983             itemtype     => undef,
1984             branchcode   => undef,
1985             rules        => {
1986                 issuelength => 1,
1987                 firstremind => 1,        # 1 day of grace
1988                 finedays    => 2,        # 2 days of fine per day of overdue
1989                 lengthunit  => 'days',
1990             }
1991         }
1992     );
1993
1994     # Patron cannot issue item_1, they have overdues
1995     my $five_days_ago = dt_from_string->subtract( days => 5 );
1996     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
1997     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
1998     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1999       ;    # Add another overdue
2000
2001     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2002     AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
2003     my $debarments = Koha::Patron::Debarments::GetDebarments(
2004         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2005     is( scalar(@$debarments), 1 );
2006
2007     # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2008     # Same for the others
2009     my $expected_expiration = output_pref(
2010         {
2011             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
2012             dateformat => 'sql',
2013             dateonly   => 1
2014         }
2015     );
2016     is( $debarments->[0]->{expiration}, $expected_expiration );
2017
2018     AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
2019     $debarments = Koha::Patron::Debarments::GetDebarments(
2020         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2021     is( scalar(@$debarments), 1 );
2022     $expected_expiration = output_pref(
2023         {
2024             dt         => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
2025             dateformat => 'sql',
2026             dateonly   => 1
2027         }
2028     );
2029     is( $debarments->[0]->{expiration}, $expected_expiration );
2030
2031     Koha::Patron::Debarments::DelUniqueDebarment(
2032         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2033
2034     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2035     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
2036     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
2037       ;    # Add another overdue
2038     AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
2039     $debarments = Koha::Patron::Debarments::GetDebarments(
2040         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2041     is( scalar(@$debarments), 1 );
2042     $expected_expiration = output_pref(
2043         {
2044             dt         => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
2045             dateformat => 'sql',
2046             dateonly   => 1
2047         }
2048     );
2049     is( $debarments->[0]->{expiration}, $expected_expiration );
2050
2051     AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
2052     $debarments = Koha::Patron::Debarments::GetDebarments(
2053         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2054     is( scalar(@$debarments), 1 );
2055     $expected_expiration = output_pref(
2056         {
2057             dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2058             dateformat => 'sql',
2059             dateonly   => 1
2060         }
2061     );
2062     is( $debarments->[0]->{expiration}, $expected_expiration );
2063 };
2064
2065 subtest 'AddReturn + suspension_chargeperiod' => sub {
2066     plan tests => 21;
2067
2068     my $library = $builder->build( { source => 'Branch' } );
2069     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2070
2071     my $biblionumber = $builder->build_sample_biblio(
2072         {
2073             branchcode => $library->{branchcode},
2074         }
2075     )->biblionumber;
2076     my $item_1 = $builder->build_sample_item(
2077         {
2078             biblionumber => $biblionumber,
2079             library      => $library->{branchcode},
2080         }
2081     )->unblessed;
2082
2083     # And the issuing rule
2084     Koha::CirculationRules->search->delete;
2085     Koha::CirculationRules->set_rules(
2086         {
2087             categorycode => '*',
2088             itemtype     => '*',
2089             branchcode   => '*',
2090             rules        => {
2091                 issuelength => 1,
2092                 firstremind => 0,    # 0 day of grace
2093                 finedays    => 2,    # 2 days of fine per day of overdue
2094                 suspension_chargeperiod => 1,
2095                 lengthunit              => 'days',
2096             }
2097         }
2098     );
2099
2100     my $five_days_ago = dt_from_string->subtract( days => 5 );
2101     # We want to charge 2 days every day, without grace
2102     # With 5 days of overdue: 5 * Z
2103     my $expected_expiration = dt_from_string->add( days => ( 5 * 2 ) / 1 );
2104     test_debarment_on_checkout(
2105         {
2106             item            => $item_1,
2107             library         => $library,
2108             patron          => $patron,
2109             due_date        => $five_days_ago,
2110             expiration_date => $expected_expiration,
2111         }
2112     );
2113
2114     # We want to charge 2 days every 2 days, without grace
2115     # With 5 days of overdue: (5 * 2) / 2
2116     Koha::CirculationRules->set_rule(
2117         {
2118             categorycode => undef,
2119             branchcode   => undef,
2120             itemtype     => undef,
2121             rule_name    => 'suspension_chargeperiod',
2122             rule_value   => '2',
2123         }
2124     );
2125
2126     $expected_expiration = dt_from_string->add( days => floor( 5 * 2 ) / 2 );
2127     test_debarment_on_checkout(
2128         {
2129             item            => $item_1,
2130             library         => $library,
2131             patron          => $patron,
2132             due_date        => $five_days_ago,
2133             expiration_date => $expected_expiration,
2134         }
2135     );
2136
2137     # We want to charge 2 days every 3 days, with 1 day of grace
2138     # With 5 days of overdue: ((5-1) / 3 ) * 2
2139     Koha::CirculationRules->set_rules(
2140         {
2141             categorycode => undef,
2142             branchcode   => undef,
2143             itemtype     => undef,
2144             rules        => {
2145                 suspension_chargeperiod => 3,
2146                 firstremind             => 1,
2147             }
2148         }
2149     );
2150     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2151     test_debarment_on_checkout(
2152         {
2153             item            => $item_1,
2154             library         => $library,
2155             patron          => $patron,
2156             due_date        => $five_days_ago,
2157             expiration_date => $expected_expiration,
2158         }
2159     );
2160
2161     # Use finesCalendar to know if holiday must be skipped to calculate the due date
2162     # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2163     Koha::CirculationRules->set_rules(
2164         {
2165             categorycode => undef,
2166             branchcode   => undef,
2167             itemtype     => undef,
2168             rules        => {
2169                 finedays                => 2,
2170                 suspension_chargeperiod => 1,
2171                 firstremind             => 0,
2172             }
2173         }
2174     );
2175     t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2176     t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2177
2178     # Adding a holiday 2 days ago
2179     my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2180     my $two_days_ago = dt_from_string->subtract( days => 2 );
2181     $calendar->insert_single_holiday(
2182         day             => $two_days_ago->day,
2183         month           => $two_days_ago->month,
2184         year            => $two_days_ago->year,
2185         title           => 'holidayTest-2d',
2186         description     => 'holidayDesc 2 days ago'
2187     );
2188     # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2189     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2190     test_debarment_on_checkout(
2191         {
2192             item            => $item_1,
2193             library         => $library,
2194             patron          => $patron,
2195             due_date        => $five_days_ago,
2196             expiration_date => $expected_expiration,
2197         }
2198     );
2199
2200     # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2201     my $two_days_ahead = dt_from_string->add( days => 2 );
2202     $calendar->insert_single_holiday(
2203         day             => $two_days_ahead->day,
2204         month           => $two_days_ahead->month,
2205         year            => $two_days_ahead->year,
2206         title           => 'holidayTest+2d',
2207         description     => 'holidayDesc 2 days ahead'
2208     );
2209
2210     # Same as above, but we should skip D+2
2211     $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2212     test_debarment_on_checkout(
2213         {
2214             item            => $item_1,
2215             library         => $library,
2216             patron          => $patron,
2217             due_date        => $five_days_ago,
2218             expiration_date => $expected_expiration,
2219         }
2220     );
2221
2222     # Adding another holiday, day of expiration date
2223     my $expected_expiration_dt = dt_from_string($expected_expiration);
2224     $calendar->insert_single_holiday(
2225         day             => $expected_expiration_dt->day,
2226         month           => $expected_expiration_dt->month,
2227         year            => $expected_expiration_dt->year,
2228         title           => 'holidayTest_exp',
2229         description     => 'holidayDesc on expiration date'
2230     );
2231     # Expiration date will be the day after
2232     test_debarment_on_checkout(
2233         {
2234             item            => $item_1,
2235             library         => $library,
2236             patron          => $patron,
2237             due_date        => $five_days_ago,
2238             expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2239         }
2240     );
2241
2242     test_debarment_on_checkout(
2243         {
2244             item            => $item_1,
2245             library         => $library,
2246             patron          => $patron,
2247             return_date     => dt_from_string->add(days => 5),
2248             expiration_date => dt_from_string->add(days => 5 + (5 * 2 - 1) ),
2249         }
2250     );
2251 };
2252
2253 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2254     plan tests => 2;
2255
2256     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2257     my $patron1 = $builder->build_object(
2258         {
2259             class => 'Koha::Patrons',
2260             value => {
2261                 library      => $library->branchcode,
2262                 categorycode => $patron_category->{categorycode}
2263             }
2264         }
2265     );
2266     my $patron2 = $builder->build_object(
2267         {
2268             class => 'Koha::Patrons',
2269             value => {
2270                 library      => $library->branchcode,
2271                 categorycode => $patron_category->{categorycode}
2272             }
2273         }
2274     );
2275
2276     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2277
2278     my $item = $builder->build_sample_item(
2279         {
2280             library      => $library->branchcode,
2281         }
2282     )->unblessed;
2283
2284     my ( $error, $question, $alerts );
2285     my $issue = AddIssue( $patron1->unblessed, $item->{barcode} );
2286
2287     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2288     ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
2289     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' );
2290
2291     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2292     ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
2293     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' );
2294
2295     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2296 };
2297
2298
2299 subtest 'AddReturn | is_overdue' => sub {
2300     plan tests => 5;
2301
2302     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2303     t::lib::Mocks::mock_preference('finesMode', 'production');
2304     t::lib::Mocks::mock_preference('MaxFine', '100');
2305
2306     my $library = $builder->build( { source => 'Branch' } );
2307     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2308     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2309     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2310
2311     my $item = $builder->build_sample_item(
2312         {
2313             library      => $library->{branchcode},
2314             replacementprice => 7
2315         }
2316     )->unblessed;
2317
2318     Koha::CirculationRules->search->delete;
2319     Koha::CirculationRules->set_rules(
2320         {
2321             categorycode => undef,
2322             itemtype     => undef,
2323             branchcode   => undef,
2324             rules        => {
2325                 issuelength  => 6,
2326                 lengthunit   => 'days',
2327                 fine         => 1,        # Charge 1 every day of overdue
2328                 chargeperiod => 1,
2329             }
2330         }
2331     );
2332
2333     my $now   = dt_from_string;
2334     my $one_day_ago   = dt_from_string->subtract( days => 1 );
2335     my $five_days_ago = dt_from_string->subtract( days => 5 );
2336     my $ten_days_ago  = dt_from_string->subtract( days => 10 );
2337     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2338
2339     # No return date specified, today will be used => 10 days overdue charged
2340     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2341     AddReturn( $item->{barcode}, $library->{branchcode} );
2342     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2343     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2344
2345     # specify return date 5 days before => no overdue charged
2346     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
2347     AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
2348     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2349     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2350
2351     # specify return date 5 days later => 5 days overdue charged
2352     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2353     AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
2354     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2355     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2356
2357     # specify return date 5 days later, specify exemptfine => no overdue charge
2358     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2359     AddReturn( $item->{barcode}, $library->{branchcode}, 1, $five_days_ago );
2360     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2361     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2362
2363     subtest 'bug 22877' => sub {
2364
2365         plan tests => 3;
2366
2367         my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago );    # date due was 10d ago
2368
2369         # Fake fines cronjob on this checkout
2370         my ($fine) =
2371           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2372             $ten_days_ago, $now );
2373         UpdateFine(
2374             {
2375                 issue_id       => $issue->issue_id,
2376                 itemnumber     => $item->{itemnumber},
2377                 borrowernumber => $patron->borrowernumber,
2378                 amount         => $fine,
2379                 due            => output_pref($ten_days_ago)
2380             }
2381         );
2382         is( int( $patron->account->balance() ),
2383             10, "Overdue fine of 10 days overdue" );
2384
2385         # Fake longoverdue with charge and not marking returned
2386         LostItem( $item->{itemnumber}, 'cronjob', 0 );
2387         is( int( $patron->account->balance() ),
2388             17, "Lost fine of 7 plus 10 days overdue" );
2389
2390         # Now we return it today
2391         AddReturn( $item->{barcode}, $library->{branchcode} );
2392         is( int( $patron->account->balance() ),
2393             17, "Should have a single 10 days overdue fine and lost charge" );
2394       }
2395 };
2396
2397 subtest '_FixAccountForLostAndReturned' => sub {
2398
2399     plan tests => 5;
2400
2401     t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
2402     t::lib::Mocks::mock_preference( 'WhenLostForgiveFine',          0 );
2403
2404     my $processfee_amount  = 20;
2405     my $replacement_amount = 99.00;
2406     my $item_type          = $builder->build_object(
2407         {   class => 'Koha::ItemTypes',
2408             value => {
2409                 notforloan         => undef,
2410                 rentalcharge       => 0,
2411                 defaultreplacecost => undef,
2412                 processfee         => $processfee_amount,
2413                 rentalcharge_daily => 0,
2414             }
2415         }
2416     );
2417     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2418
2419     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
2420
2421     subtest 'Full write-off tests' => sub {
2422
2423         plan tests => 12;
2424
2425         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2426         my $manager = $builder->build_object({ class => "Koha::Patrons" });
2427         t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
2428
2429         my $item = $builder->build_sample_item(
2430             {
2431                 biblionumber     => $biblio->biblionumber,
2432                 library          => $library->branchcode,
2433                 replacementprice => $replacement_amount,
2434                 itype            => $item_type->itemtype,
2435             }
2436         );
2437
2438         AddIssue( $patron->unblessed, $item->barcode );
2439
2440         # Simulate item marked as lost
2441         ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2442         LostItem( $item->itemnumber, 1 );
2443
2444         my $processing_fee_lines = Koha::Account::Lines->search(
2445             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2446         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2447         my $processing_fee_line = $processing_fee_lines->next;
2448         is( $processing_fee_line->amount + 0,
2449             $processfee_amount, 'The right PROCESSING amount is generated' );
2450         is( $processing_fee_line->amountoutstanding + 0,
2451             $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2452
2453         my $lost_fee_lines = Koha::Account::Lines->search(
2454             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2455         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2456         my $lost_fee_line = $lost_fee_lines->next;
2457         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2458         is( $lost_fee_line->amountoutstanding + 0,
2459             $replacement_amount, 'The right LOST amountoutstanding is generated' );
2460         is( $lost_fee_line->status,
2461             undef, 'The LOST status was not set' );
2462
2463         my $account = $patron->account;
2464         my $debts   = $account->outstanding_debits;
2465
2466         # Write off the debt
2467         my $credit = $account->add_credit(
2468             {   amount => $account->balance,
2469                 type   => 'WRITEOFF',
2470                 interface => 'test',
2471             }
2472         );
2473         $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Writeoff' } );
2474
2475         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2476         is( $credit_return_id, undef, 'No LOST_RETURN account line added' );
2477
2478         $lost_fee_line->discard_changes; # reload from DB
2479         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2480         is( $lost_fee_line->debit_type_code,
2481             'LOST', 'Lost fee now still has account type of LOST' );
2482         is( $lost_fee_line->status, 'RETURNED', "Lost fee now has account status of RETURNED");
2483
2484         is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2485     };
2486
2487     subtest 'Full payment tests' => sub {
2488
2489         plan tests => 13;
2490
2491         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2492
2493         my $item = $builder->build_sample_item(
2494             {
2495                 biblionumber     => $biblio->biblionumber,
2496                 library          => $library->branchcode,
2497                 replacementprice => $replacement_amount,
2498                 itype            => $item_type->itemtype
2499             }
2500         );
2501
2502         AddIssue( $patron->unblessed, $item->barcode );
2503
2504         # Simulate item marked as lost
2505         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2506         LostItem( $item->itemnumber, 1 );
2507
2508         my $processing_fee_lines = Koha::Account::Lines->search(
2509             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2510         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2511         my $processing_fee_line = $processing_fee_lines->next;
2512         is( $processing_fee_line->amount + 0,
2513             $processfee_amount, 'The right PROCESSING amount is generated' );
2514         is( $processing_fee_line->amountoutstanding + 0,
2515             $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2516
2517         my $lost_fee_lines = Koha::Account::Lines->search(
2518             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2519         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2520         my $lost_fee_line = $lost_fee_lines->next;
2521         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2522         is( $lost_fee_line->amountoutstanding + 0,
2523             $replacement_amount, 'The right LOST amountountstanding is generated' );
2524
2525         my $account = $patron->account;
2526         my $debts   = $account->outstanding_debits;
2527
2528         # Write off the debt
2529         my $credit = $account->add_credit(
2530             {   amount => $account->balance,
2531                 type   => 'PAYMENT',
2532                 interface => 'test',
2533             }
2534         );
2535         $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Payment' } );
2536
2537         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2538         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2539
2540         is( $credit_return->credit_type_code, 'LOST_RETURN', 'An account line of type LOST_RETURN is added' );
2541         is( $credit_return->amount + 0,
2542             -99.00, 'The account line of type LOST_RETURN has an amount of -99' );
2543         is( $credit_return->amountoutstanding + 0,
2544             -99.00, 'The account line of type LOST_RETURN has an amountoutstanding of -99' );
2545
2546         $lost_fee_line->discard_changes;
2547         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2548         is( $lost_fee_line->debit_type_code,
2549             'LOST', 'Lost fee now still has account type of LOST' );
2550         is( $lost_fee_line->status, 'RETURNED', "Lost fee now has account status of RETURNED");
2551
2552         is( $patron->account->balance,
2553             -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2554     };
2555
2556     subtest 'Test without payment or write off' => sub {
2557
2558         plan tests => 13;
2559
2560         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2561
2562         my $item = $builder->build_sample_item(
2563             {
2564                 biblionumber     => $biblio->biblionumber,
2565                 library          => $library->branchcode,
2566                 replacementprice => 23.00,
2567                 replacementprice => $replacement_amount,
2568                 itype            => $item_type->itemtype
2569             }
2570         );
2571
2572         AddIssue( $patron->unblessed, $item->barcode );
2573
2574         # Simulate item marked as lost
2575         ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2576         LostItem( $item->itemnumber, 1 );
2577
2578         my $processing_fee_lines = Koha::Account::Lines->search(
2579             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2580         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2581         my $processing_fee_line = $processing_fee_lines->next;
2582         is( $processing_fee_line->amount + 0,
2583             $processfee_amount, 'The right PROCESSING amount is generated' );
2584         is( $processing_fee_line->amountoutstanding + 0,
2585             $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2586
2587         my $lost_fee_lines = Koha::Account::Lines->search(
2588             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2589         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2590         my $lost_fee_line = $lost_fee_lines->next;
2591         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2592         is( $lost_fee_line->amountoutstanding + 0,
2593             $replacement_amount, 'The right LOST amountountstanding is generated' );
2594
2595         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2596         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2597
2598         is( $credit_return->credit_type_code, 'LOST_RETURN', 'An account line of type LOST_RETURN is added' );
2599         is( $credit_return->amount + 0, -99.00, 'The account line of type LOST_RETURN has an amount of -99' );
2600         is( $credit_return->amountoutstanding + 0, 0, 'The account line of type LOST_RETURN has an amountoutstanding of 0' );
2601
2602         $lost_fee_line->discard_changes;
2603         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2604         is( $lost_fee_line->debit_type_code,
2605             'LOST', 'Lost fee now still has account type of LOST' );
2606         is( $lost_fee_line->status, 'RETURNED', "Lost fee now has account status of RETURNED");
2607
2608         is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2609     };
2610
2611     subtest 'Test with partial payement and write off, and remaining debt' => sub {
2612
2613         plan tests => 16;
2614
2615         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2616         my $item = $builder->build_sample_item(
2617             {
2618                 biblionumber     => $biblio->biblionumber,
2619                 library          => $library->branchcode,
2620                 replacementprice => $replacement_amount,
2621                 itype            => $item_type->itemtype
2622             }
2623         );
2624
2625         AddIssue( $patron->unblessed, $item->barcode );
2626
2627         # Simulate item marked as lost
2628         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2629         LostItem( $item->itemnumber, 1 );
2630
2631         my $processing_fee_lines = Koha::Account::Lines->search(
2632             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2633         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2634         my $processing_fee_line = $processing_fee_lines->next;
2635         is( $processing_fee_line->amount + 0,
2636             $processfee_amount, 'The right PROCESSING amount is generated' );
2637         is( $processing_fee_line->amountoutstanding + 0,
2638             $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2639
2640         my $lost_fee_lines = Koha::Account::Lines->search(
2641             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2642         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2643         my $lost_fee_line = $lost_fee_lines->next;
2644         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2645         is( $lost_fee_line->amountoutstanding + 0,
2646             $replacement_amount, 'The right LOST amountountstanding is generated' );
2647
2648         my $account = $patron->account;
2649         is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PROCESSING + L' );
2650
2651         # Partially pay fee
2652         my $payment_amount = 27;
2653         my $payment        = $account->add_credit(
2654             {   amount => $payment_amount,
2655                 type   => 'PAYMENT',
2656                 interface => 'test',
2657             }
2658         );
2659
2660         $payment->apply( { debits => [ $lost_fee_line ], offset_type => 'Payment' } );
2661
2662         # Partially write off fee
2663         my $write_off_amount = 25;
2664         my $write_off        = $account->add_credit(
2665             {   amount => $write_off_amount,
2666                 type   => 'WRITEOFF',
2667                 interface => 'test',
2668             }
2669         );
2670         $write_off->apply( { debits => [ $lost_fee_line ], offset_type => 'Writeoff' } );
2671
2672         is( $account->balance,
2673             $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2674             'Payment and write off applied'
2675         );
2676
2677         # Store the amountoutstanding value
2678         $lost_fee_line->discard_changes;
2679         my $outstanding = $lost_fee_line->amountoutstanding;
2680
2681         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2682         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2683
2684         is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PROCESSING - PAYMENT (LOST_RETURN)' );
2685
2686         $lost_fee_line->discard_changes;
2687         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2688         is( $lost_fee_line->debit_type_code,
2689             'LOST', 'Lost fee now still has account type of LOST' );
2690         is( $lost_fee_line->status, 'RETURNED', "Lost fee now has account status of RETURNED");
2691
2692         is( $credit_return->credit_type_code, 'LOST_RETURN', 'An account line of type LOST_RETURN is added' );
2693         is( $credit_return->amount + 0,
2694             ($payment_amount + $outstanding ) * -1,
2695             'The account line of type LOST_RETURN has an amount equal to the payment + outstanding'
2696         );
2697         is( $credit_return->amountoutstanding + 0,
2698             $payment_amount * -1,
2699             'The account line of type LOST_RETURN has an amountoutstanding equal to the payment'
2700         );
2701
2702         is( $account->balance,
2703             $processfee_amount - $payment_amount,
2704             'The patron balance is the difference between the PROCESSING and the credit'
2705         );
2706     };
2707
2708     subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2709
2710         plan tests => 8;
2711
2712         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2713         my $barcode = 'KD123456793';
2714         my $replacement_amount = 100;
2715         my $processfee_amount  = 20;
2716
2717         my $item_type          = $builder->build_object(
2718             {   class => 'Koha::ItemTypes',
2719                 value => {
2720                     notforloan         => undef,
2721                     rentalcharge       => 0,
2722                     defaultreplacecost => undef,
2723                     processfee         => 0,
2724                     rentalcharge_daily => 0,
2725                 }
2726             }
2727         );
2728         my ( undef, undef, $item_id ) = AddItem(
2729             {   homebranch       => $library->branchcode,
2730                 holdingbranch    => $library->branchcode,
2731                 barcode          => $barcode,
2732                 replacementprice => $replacement_amount,
2733                 itype            => $item_type->itemtype
2734             },
2735             $biblio->biblionumber
2736         );
2737
2738         AddIssue( $patron->unblessed, $barcode );
2739
2740         # Simulate item marked as lost
2741         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item_id );
2742         LostItem( $item_id, 1 );
2743
2744         my $lost_fee_lines = Koha::Account::Lines->search(
2745             { borrowernumber => $patron->id, itemnumber => $item_id, debit_type_code => 'LOST' } );
2746         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2747         my $lost_fee_line = $lost_fee_lines->next;
2748         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2749         is( $lost_fee_line->amountoutstanding + 0,
2750             $replacement_amount, 'The right LOST amountountstanding is generated' );
2751
2752         my $account = $patron->account;
2753         is( $account->balance, $replacement_amount, 'Balance is L' );
2754
2755         # Partially pay fee
2756         my $payment_amount = 27;
2757         my $payment        = $account->add_credit(
2758             {   amount => $payment_amount,
2759                 type   => 'PAYMENT',
2760                 interface => 'test',
2761             }
2762         );
2763         $payment->apply({ debits => [ $lost_fee_line ], offset_type => 'Payment' });
2764
2765         is( $account->balance,
2766             $replacement_amount - $payment_amount,
2767             'Payment applied'
2768         );
2769
2770         my $manual_debit_amount = 80;
2771         $account->add_debit( { amount => $manual_debit_amount, type => 'OVERDUE', interface =>'test' } );
2772
2773         is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
2774
2775         t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
2776
2777         my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2778         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2779
2780         is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PROCESSING - payment (LOST_RETURN)' );
2781
2782         my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, debit_type_code => 'OVERDUE', status => 'UNRETURNED' })->next;
2783         is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
2784     };
2785 };
2786
2787 subtest '_FixOverduesOnReturn' => sub {
2788     plan tests => 11;
2789
2790     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2791     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2792
2793     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2794
2795     my $branchcode  = $library2->{branchcode};
2796
2797     my $item = $builder->build_sample_item(
2798         {
2799             biblionumber     => $biblio->biblionumber,
2800             library          => $branchcode,
2801             replacementprice => 99.00,
2802             itype            => $itemtype,
2803         }
2804     );
2805
2806     my $patron = $builder->build( { source => 'Borrower' } );
2807
2808     ## Start with basic call, should just close out the open fine
2809     my $accountline = Koha::Account::Line->new(
2810         {
2811             borrowernumber => $patron->{borrowernumber},
2812             debit_type_code    => 'OVERDUE',
2813             status         => 'UNRETURNED',
2814             itemnumber     => $item->itemnumber,
2815             amount => 99.00,
2816             amountoutstanding => 99.00,
2817             interface => 'test',
2818         }
2819     )->store();
2820
2821     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
2822
2823     $accountline->_result()->discard_changes();
2824
2825     is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
2826     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
2827     is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
2828
2829     ## Run again, with exemptfine enabled
2830     $accountline->set(
2831         {
2832             debit_type_code    => 'OVERDUE',
2833             status         => 'UNRETURNED',
2834             amountoutstanding => 99.00,
2835         }
2836     )->store();
2837
2838     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
2839
2840     $accountline->_result()->discard_changes();
2841     my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2842
2843     is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
2844     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
2845     is( $accountline->status, 'FORGIVEN', 'Open fine ( account type OVERDUE ) has been set to fine forgiven ( status FORGIVEN )');
2846     is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2847     is( $offset->amount + 0, -99, "Amount of offset is correct" );
2848     my $credit = $offset->credit;
2849     is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
2850     is( $credit->amount + 0, -99, "Credit amount is set correctly" );
2851     is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
2852 };
2853
2854 subtest '_FixAccountForLostAndReturned returns undef if patron is deleted' => sub {
2855     plan tests => 1;
2856
2857     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2858     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2859
2860     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2861
2862     my $branchcode  = $library2->{branchcode};
2863
2864     my $item = $builder->build_sample_item(
2865         {
2866             biblionumber     => $biblio->biblionumber,
2867             library          => $branchcode,
2868             replacementprice => 99.00,
2869             itype            => $itemtype,
2870         }
2871     );
2872
2873     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2874
2875     ## Start with basic call, should just close out the open fine
2876     my $accountline = Koha::Account::Line->new(
2877         {
2878             borrowernumber => $patron->id,
2879             debit_type_code    => 'LOST',
2880             status         => undef,
2881             itemnumber     => $item->itemnumber,
2882             amount => 99.00,
2883             amountoutstanding => 99.00,
2884             interface => 'test',
2885         }
2886     )->store();
2887
2888     $patron->delete();
2889
2890     my $return_value = C4::Circulation::_FixAccountForLostAndReturned( $patron->id, $item->itemnumber );
2891
2892     is( $return_value, undef, "_FixAccountForLostAndReturned returns undef if patron is deleted" );
2893
2894 };
2895
2896 subtest 'Set waiting flag' => sub {
2897     plan tests => 4;
2898
2899     my $library_1 = $builder->build( { source => 'Branch' } );
2900     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2901     my $library_2 = $builder->build( { source => 'Branch' } );
2902     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2903
2904     my $item = $builder->build_sample_item(
2905         {
2906             library      => $library_1->{branchcode},
2907         }
2908     )->unblessed;
2909
2910     set_userenv( $library_2 );
2911     my $reserve_id = AddReserve(
2912         {
2913             branchcode     => $library_2->{branchcode},
2914             borrowernumber => $patron_2->{borrowernumber},
2915             biblionumber   => $item->{biblionumber},
2916             priority       => 1,
2917             itemnumber     => $item->{itemnumber},
2918         }
2919     );
2920
2921     set_userenv( $library_1 );
2922     my $do_transfer = 1;
2923     my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2924     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2925     my $hold = Koha::Holds->find( $reserve_id );
2926     is( $hold->found, 'T', 'Hold is in transit' );
2927
2928     my ( $status ) = CheckReserves($item->{itemnumber});
2929     is( $status, 'Reserved', 'Hold is not waiting yet');
2930
2931     set_userenv( $library_2 );
2932     $do_transfer = 0;
2933     AddReturn( $item->{barcode}, $library_2->{branchcode} );
2934     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2935     $hold = Koha::Holds->find( $reserve_id );
2936     is( $hold->found, 'W', 'Hold is waiting' );
2937     ( $status ) = CheckReserves($item->{itemnumber});
2938     is( $status, 'Waiting', 'Now the hold is waiting');
2939 };
2940
2941 subtest 'Cancel transfers on lost items' => sub {
2942     plan tests => 5;
2943     my $library_1 = $builder->build( { source => 'Branch' } );
2944     my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2945     my $library_2 = $builder->build( { source => 'Branch' } );
2946     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2947     my $biblio = $builder->build_sample_biblio({branchcode => $library->{branchcode}});
2948     my $item   = $builder->build_sample_item({
2949         biblionumber  => $biblio->biblionumber,
2950         library    => $library_1->{branchcode},
2951     });
2952
2953     set_userenv( $library_2 );
2954     my $reserve_id = AddReserve(
2955         {
2956             branchcode     => $library_2->{branchcode},
2957             borrowernumber => $patron_2->{borrowernumber},
2958             biblionumber   => $item->biblionumber,
2959             priority       => 1,
2960             itemnumber     => $item->itemnumber,
2961         }
2962     );
2963
2964     #Return book and add transfer
2965     set_userenv( $library_1 );
2966     my $do_transfer = 1;
2967     my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
2968     ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
2969     C4::Circulation::transferbook( $library_2->{branchcode}, $item->barcode );
2970     my $hold = Koha::Holds->find( $reserve_id );
2971     is( $hold->found, 'T', 'Hold is in transit' );
2972
2973     #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
2974     my ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
2975     is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
2976     my $itemcheck = Koha::Items->find($item->itemnumber);
2977     is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Items holding branch is the transfers origin branch before it is marked as lost' );
2978
2979     #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
2980     ModItem( { itemlost => 1 }, $item->biblionumber, $item->itemnumber );
2981     LostItem( $item->itemnumber, 'test', 1 );
2982     ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
2983     is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
2984     $itemcheck = Koha::Items->find($item->itemnumber);
2985     is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
2986 };
2987
2988 subtest 'CanBookBeIssued | is_overdue' => sub {
2989     plan tests => 3;
2990
2991     # Set a simple circ policy
2992     Koha::CirculationRules->set_rules(
2993         {
2994             categorycode => undef,
2995             branchcode   => undef,
2996             itemtype     => undef,
2997             rules        => {
2998                 maxissueqty     => 1,
2999                 reservesallowed => 25,
3000                 issuelength     => 14,
3001                 lengthunit      => 'days',
3002                 renewalsallowed => 1,
3003                 renewalperiod   => 7,
3004                 norenewalbefore => undef,
3005                 auto_renew      => 0,
3006                 fine            => .10,
3007                 chargeperiod    => 1,
3008             }
3009         }
3010     );
3011
3012     my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
3013     my $ten_days_go  = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
3014     my $library = $builder->build( { source => 'Branch' } );
3015     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
3016
3017     my $item = $builder->build_sample_item(
3018         {
3019             library      => $library->{branchcode},
3020         }
3021     )->unblessed;
3022
3023     my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
3024     my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
3025     is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
3026     my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
3027     is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
3028     is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
3029 };
3030
3031 subtest 'ItemsDeniedRenewal preference' => sub {
3032     plan tests => 18;
3033
3034     C4::Context->set_preference('ItemsDeniedRenewal','');
3035
3036     my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
3037     Koha::CirculationRules->set_rules(
3038         {
3039             categorycode => '*',
3040             itemtype     => '*',
3041             branchcode   => $idr_lib->branchcode,
3042             rules        => {
3043                 reservesallowed => 25,
3044                 issuelength     => 14,
3045                 lengthunit      => 'days',
3046                 renewalsallowed => 10,
3047                 renewalperiod   => 7,
3048                 norenewalbefore => undef,
3049                 auto_renew      => 0,
3050                 fine            => .10,
3051                 chargeperiod    => 1,
3052             }
3053         }
3054     );
3055
3056     my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
3057         homebranch => $idr_lib->branchcode,
3058         withdrawn => 1,
3059         itype => 'HIDE',
3060         location => 'PROC',
3061         itemcallnumber => undef,
3062         itemnotes => "",
3063         }
3064     });
3065     my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
3066         homebranch => $idr_lib->branchcode,
3067         withdrawn => 0,
3068         itype => 'NOHIDE',
3069         location => 'NOPROC'
3070         }
3071     });
3072
3073     my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
3074         branchcode => $idr_lib->branchcode,
3075         }
3076     });
3077     my $future = dt_from_string->add( days => 1 );
3078     my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3079         returndate => undef,
3080         renewals => 0,
3081         auto_renew => 0,
3082         borrowernumber => $idr_borrower->borrowernumber,
3083         itemnumber => $deny_book->itemnumber,
3084         onsite_checkout => 0,
3085         date_due => $future,
3086         }
3087     });
3088     my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3089         returndate => undef,
3090         renewals => 0,
3091         auto_renew => 0,
3092         borrowernumber => $idr_borrower->borrowernumber,
3093         itemnumber => $allow_book->itemnumber,
3094         onsite_checkout => 0,
3095         date_due => $future,
3096         }
3097     });
3098
3099     my $idr_rules;
3100
3101     my ( $idr_mayrenew, $idr_error ) =
3102     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3103     is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3104     is( $idr_error, undef, 'Renewal allowed when no rules' );
3105
3106     $idr_rules="withdrawn: [1]";
3107
3108     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3109     ( $idr_mayrenew, $idr_error ) =
3110     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3111     is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3112     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3113     ( $idr_mayrenew, $idr_error ) =
3114     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3115     is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3116     is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3117
3118     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
3119
3120     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3121     ( $idr_mayrenew, $idr_error ) =
3122     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3123     is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
3124     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
3125     ( $idr_mayrenew, $idr_error ) =
3126     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3127     is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3128     is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3129
3130     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
3131
3132     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3133     ( $idr_mayrenew, $idr_error ) =
3134     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3135     is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
3136     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
3137     ( $idr_mayrenew, $idr_error ) =
3138     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3139     is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3140     is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3141
3142     $idr_rules="itemcallnumber: [NULL]";
3143     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3144     ( $idr_mayrenew, $idr_error ) =
3145     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3146     is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
3147     $idr_rules="itemcallnumber: ['']";
3148     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3149     ( $idr_mayrenew, $idr_error ) =
3150     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3151     is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
3152
3153     $idr_rules="itemnotes: [NULL]";
3154     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3155     ( $idr_mayrenew, $idr_error ) =
3156     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3157     is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
3158     $idr_rules="itemnotes: ['']";
3159     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3160     ( $idr_mayrenew, $idr_error ) =
3161     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3162     is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
3163 };
3164
3165 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
3166     plan tests => 2;
3167
3168     t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3169     my $library = $builder->build( { source => 'Branch' } );
3170     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3171
3172     my $item = $builder->build_sample_item(
3173         {
3174             library      => $library->{branchcode},
3175         }
3176     );
3177
3178     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3179     is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3180     is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3181 };
3182
3183 subtest 'CanBookBeIssued | notforloan' => sub {
3184     plan tests => 2;
3185
3186     t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
3187
3188     my $library = $builder->build( { source => 'Branch' } );
3189     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3190
3191     my $itemtype = $builder->build(
3192         {
3193             source => 'Itemtype',
3194             value  => { notforloan => undef, }
3195         }
3196     );
3197     my $item = $builder->build_sample_item(
3198         {
3199             library  => $library->{branchcode},
3200             itype    => $itemtype->{itemtype},
3201         }
3202     );
3203     $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3204
3205     my ( $issuingimpossible, $needsconfirmation );
3206
3207
3208     subtest 'item-level_itypes = 1' => sub {
3209         plan tests => 6;
3210
3211         t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
3212         # Is for loan at item type and item level
3213         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3214         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3215         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3216
3217         # not for loan at item type level
3218         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3219         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3220         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3221         is_deeply(
3222             $issuingimpossible,
3223             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3224             'Item can not be issued, not for loan at item type level'
3225         );
3226
3227         # not for loan at item level
3228         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3229         $item->notforloan( 1 )->store;
3230         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3231         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3232         is_deeply(
3233             $issuingimpossible,
3234             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3235             'Item can not be issued, not for loan at item type level'
3236         );
3237     };
3238
3239     subtest 'item-level_itypes = 0' => sub {
3240         plan tests => 6;
3241
3242         t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3243
3244         # We set another itemtype for biblioitem
3245         my $itemtype = $builder->build(
3246             {
3247                 source => 'Itemtype',
3248                 value  => { notforloan => undef, }
3249             }
3250         );
3251
3252         # for loan at item type and item level
3253         $item->notforloan(0)->store;
3254         $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3255         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3256         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3257         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3258
3259         # not for loan at item type level
3260         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3261         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3262         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3263         is_deeply(
3264             $issuingimpossible,
3265             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3266             'Item can not be issued, not for loan at item type level'
3267         );
3268
3269         # not for loan at item level
3270         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3271         $item->notforloan( 1 )->store;
3272         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3273         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3274         is_deeply(
3275             $issuingimpossible,
3276             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3277             'Item can not be issued, not for loan at item type level'
3278         );
3279     };
3280
3281     # TODO test with AllowNotForLoanOverride = 1
3282 };
3283
3284 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
3285     plan tests => 1;
3286
3287     t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
3288     my $item = $builder->build_sample_item(
3289         {
3290             onloan => '2018-01-01',
3291         }
3292     );
3293
3294     AddReturn( $item->barcode, $item->homebranch );
3295     $item->discard_changes; # refresh
3296     is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
3297 };
3298
3299
3300 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
3301
3302     plan tests => 11;
3303
3304
3305     t::lib::Mocks::mock_preference('item-level_itypes', 1);
3306
3307     my $issuing_charges = 15;
3308     my $title   = 'A title';
3309     my $author  = 'Author, An';
3310     my $barcode = 'WHATARETHEODDS';
3311
3312     my $circ = Test::MockModule->new('C4::Circulation');
3313     $circ->mock(
3314         'GetIssuingCharges',
3315         sub {
3316             return $issuing_charges;
3317         }
3318     );
3319
3320     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
3321     my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
3322     my $patron   = $builder->build_object({
3323         class => 'Koha::Patrons',
3324         value => { branchcode => $library->id }
3325     });
3326
3327     my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
3328     my ( undef, undef, $item_id ) = AddItem(
3329         {
3330             homebranch       => $library->id,
3331             holdingbranch    => $library->id,
3332             barcode          => $barcode,
3333             replacementprice => 23.00,
3334             itype            => $itemtype->id
3335         },
3336         $biblio->biblionumber
3337     );
3338     my $item = Koha::Items->find( $item_id );
3339
3340     my $context = Test::MockModule->new('C4::Context');
3341     $context->mock( userenv => { branch => $library->id } );
3342
3343     # Check the item out
3344     AddIssue( $patron->unblessed, $item->barcode );
3345     t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
3346     my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3347     my %params_renewal = (
3348         timestamp => { -like => $date . "%" },
3349         module => "CIRCULATION",
3350         action => "RENEWAL",
3351     );
3352     my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
3353     AddRenewal( $patron->id, $item->id, $library->id );
3354     my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3355     is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
3356
3357     my $checkouts = $patron->checkouts;
3358     # The following will fail if run on 00:00:00
3359     unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
3360
3361     my $lines = Koha::Account::Lines->search({
3362         borrowernumber => $patron->id,
3363         itemnumber     => $item->id
3364     });
3365
3366     is( $lines->count, 2 );
3367
3368     my $line = $lines->next;
3369     is( $line->debit_type_code, 'RENT',       'The issue of item with issuing charge generates an accountline of the correct type' );
3370     is( $line->branchcode,  $library->id, 'AddIssuingCharge correctly sets branchcode' );
3371     is( $line->description, '',     'AddIssue does not set a hardcoded description for the accountline' );
3372
3373     $line = $lines->next;
3374     is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
3375     is( $line->branchcode,  $library->id, 'AddRenewal correctly sets branchcode' );
3376     is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
3377
3378     t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
3379
3380     $context = Test::MockModule->new('C4::Context');
3381     $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
3382
3383     $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3384     $old_log_size = Koha::ActionLogs->count( \%params_renewal );
3385     my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
3386     $sth->execute($item->id, $library->id);
3387     my ($old_stats_size) = $sth->fetchrow_array;
3388     AddRenewal( $patron->id, $item->id, $library->id );
3389     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3390     $sth->execute($item->id, $library->id);
3391     my ($new_stats_size) = $sth->fetchrow_array;
3392     is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
3393     is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
3394
3395 };
3396
3397 subtest 'ProcessOfflinePayment() tests' => sub {
3398
3399     plan tests => 4;
3400
3401
3402     my $amount = 123;
3403
3404     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
3405     my $library = $builder->build_object({ class => 'Koha::Libraries' });
3406     my $result  = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
3407
3408     is( $result, 'Success.', 'The right string is returned' );
3409
3410     my $lines = $patron->account->lines;
3411     is( $lines->count, 1, 'line created correctly');
3412
3413     my $line = $lines->next;
3414     is( $line->amount+0, $amount * -1, 'amount picked from params' );
3415     is( $line->branchcode, $library->id, 'branchcode set correctly' );
3416
3417 };
3418
3419 subtest 'Incremented fee tests' => sub {
3420     plan tests => 19;
3421
3422     my $dt = dt_from_string();
3423     Time::Fake->offset( $dt->epoch );
3424
3425     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
3426
3427     my $library =
3428       $builder->build_object( { class => 'Koha::Libraries' } )->store;
3429
3430     my $module = new Test::MockModule('C4::Context');
3431     $module->mock( 'userenv', sub { { branch => $library->id } } );
3432
3433     my $patron = $builder->build_object(
3434         {
3435             class => 'Koha::Patrons',
3436             value => { categorycode => $patron_category->{categorycode} }
3437         }
3438     )->store;
3439
3440     my $itemtype = $builder->build_object(
3441         {
3442             class => 'Koha::ItemTypes',
3443             value => {
3444                 notforloan         => undef,
3445                 rentalcharge       => 0,
3446                 rentalcharge_daily => 1,
3447             }
3448         }
3449     )->store;
3450
3451     my $item = $builder->build_sample_item(
3452         {
3453             library  => $library->{branchcode},
3454             itype    => $itemtype->id,
3455         }
3456     );
3457
3458     is( $itemtype->rentalcharge_daily+0,
3459         1, 'Daily rental charge stored and retreived correctly' );
3460     is( $item->effective_itemtype, $itemtype->id,
3461         "Itemtype set correctly for item" );
3462
3463     my $dt_from     = dt_from_string();
3464     my $dt_to       = dt_from_string()->add( days => 7 );
3465     my $dt_to_renew = dt_from_string()->add( days => 13 );
3466
3467     # Daily Tests
3468     t::lib::Mocks::mock_preference( 'finesCalendar', 'ignoreCalendar' );
3469     my $issue =
3470       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3471     my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3472     is( $accountline->amount+0, 7,
3473 "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar"
3474     );
3475     $accountline->delete();
3476     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3477     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3478     is( $accountline->amount+0, 6,
3479 "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal"
3480     );
3481     $accountline->delete();
3482     $issue->delete();
3483
3484     t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3485     $issue =
3486       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3487     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3488     is( $accountline->amount+0, 7,
3489 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed"
3490     );
3491     $accountline->delete();
3492     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3493     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3494     is( $accountline->amount+0, 6,
3495 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal"
3496     );
3497     $accountline->delete();
3498     $issue->delete();
3499
3500     my $calendar = C4::Calendar->new( branchcode => $library->id );
3501     # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
3502     my $closed_day =
3503         ( $dt_from->day_of_week == 6 ) ? 0
3504       : ( $dt_from->day_of_week == 7 ) ? 1
3505       :                                  $dt_from->day_of_week + 1;
3506     my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
3507     $calendar->insert_week_day_holiday(
3508         weekday     => $closed_day,
3509         title       => 'Test holiday',
3510         description => 'Test holiday'
3511     );
3512     $issue =
3513       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3514     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3515     is( $accountline->amount+0, 6,
3516 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name"
3517     );
3518     $accountline->delete();
3519     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3520     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3521     is( $accountline->amount+0, 5,
3522 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name, for renewal"
3523     );
3524     $accountline->delete();
3525     $issue->delete();
3526
3527     $itemtype->rentalcharge(2)->store;
3528     is( $itemtype->rentalcharge+0, 2,
3529         'Rental charge updated and retreived correctly' );
3530     $issue =
3531       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3532     my $accountlines =
3533       Koha::Account::Lines->search( { itemnumber => $item->id } );
3534     is( $accountlines->count, '2',
3535         "Fixed charge and accrued charge recorded distinctly" );
3536     $accountlines->delete();
3537     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3538     $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
3539     is( $accountlines->count, '2',
3540         "Fixed charge and accrued charge recorded distinctly, for renewal" );
3541     $accountlines->delete();
3542     $issue->delete();
3543     $itemtype->rentalcharge(0)->store;
3544     is( $itemtype->rentalcharge+0, 0,
3545         'Rental charge reset and retreived correctly' );
3546
3547     # Hourly
3548     Koha::CirculationRules->set_rule(
3549         {
3550             categorycode => $patron->categorycode,
3551             itemtype     => $itemtype->id,
3552             branchcode   => $library->id,
3553             rule_name    => 'lengthunit',
3554             rule_value   => 'hours',
3555         }
3556     );
3557
3558     $itemtype->rentalcharge_hourly('0.25')->store();
3559     is( $itemtype->rentalcharge_hourly,
3560         '0.25', 'Hourly rental charge stored and retreived correctly' );
3561
3562     $dt_to       = dt_from_string()->add( hours => 168 );
3563     $dt_to_renew = dt_from_string()->add( hours => 312 );
3564
3565     t::lib::Mocks::mock_preference( 'finesCalendar', 'ignoreCalendar' );
3566     $issue =
3567       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3568     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3569     is( $accountline->amount + 0, 42,
3570         "Hourly rental charge calculated correctly with finesCalendar = ignoreCalendar (168h * 0.25u)" );
3571     $accountline->delete();
3572     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3573     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3574     is( $accountline->amount + 0, 36,
3575         "Hourly rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal (312h - 168h * 0.25u)" );
3576     $accountline->delete();
3577     $issue->delete();
3578
3579     t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3580     $issue =
3581       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3582     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3583     is( $accountline->amount + 0, 36,
3584         "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name (168h - 24h * 0.25u)" );
3585     $accountline->delete();
3586     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3587     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3588     is( $accountline->amount + 0, 30,
3589         "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
3590     $accountline->delete();
3591     $issue->delete();
3592
3593     $calendar->delete_holiday( weekday => $closed_day );
3594     $issue =
3595       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3596     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3597     is( $accountline->amount + 0, 42,
3598         "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed (168h - 0h * 0.25u" );
3599     $accountline->delete();
3600     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3601     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3602     is( $accountline->amount + 0, 36,
3603         "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal (312h - 168h - 0h * 0.25u)" );
3604     $accountline->delete();
3605     $issue->delete();
3606     Time::Fake->reset;
3607 };
3608
3609 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
3610     plan tests => 2;
3611
3612     t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
3613     t::lib::Mocks::mock_preference('item-level_itypes', 1);
3614
3615     my $library =
3616       $builder->build_object( { class => 'Koha::Libraries' } )->store;
3617     my $patron = $builder->build_object(
3618         {
3619             class => 'Koha::Patrons',
3620             value => { categorycode => $patron_category->{categorycode} }
3621         }
3622     )->store;
3623
3624     my $itemtype = $builder->build_object(
3625         {
3626             class => 'Koha::ItemTypes',
3627             value => {
3628                 notforloan             => 0,
3629                 rentalcharge           => 0,
3630                 rentalcharge_daily => 0
3631             }
3632         }
3633     );
3634
3635     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3636     my $item = $builder->build_object(
3637         {
3638             class => 'Koha::Items',
3639             value  => {
3640                 homebranch    => $library->id,
3641                 holdingbranch => $library->id,
3642                 notforloan    => 0,
3643                 itemlost      => 0,
3644                 withdrawn     => 0,
3645                 itype         => $itemtype->id,
3646                 biblionumber  => $biblioitem->{biblionumber},
3647                 biblioitemnumber => $biblioitem->{biblioitemnumber},
3648             }
3649         }
3650     )->store;
3651
3652     my ( $issuingimpossible, $needsconfirmation );
3653     my $dt_from = dt_from_string();
3654     my $dt_due = dt_from_string()->add( days => 3 );
3655
3656     $itemtype->rentalcharge(1)->store;
3657     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3658     is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
3659     $itemtype->rentalcharge('0')->store;
3660     $itemtype->rentalcharge_daily(1)->store;
3661     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3662     is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
3663     $itemtype->rentalcharge_daily('0')->store;
3664 };
3665
3666 subtest "Test Backdating of Returns" => sub {
3667     plan tests => 2;
3668
3669     my $branch = $library2->{branchcode};
3670     my $biblio = $builder->build_sample_biblio();
3671     my $item = $builder->build_sample_item(
3672         {
3673             biblionumber     => $biblio->biblionumber,
3674             library          => $branch,
3675             itype            => $itemtype,
3676         }
3677     );
3678
3679     my %a_borrower_data = (
3680         firstname =>  'Kyle',
3681         surname => 'Hall',
3682         categorycode => $patron_category->{categorycode},
3683         branchcode => $branch,
3684     );
3685     my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
3686     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
3687
3688     my $due_date = dt_from_string;
3689     my $issue = AddIssue( $borrower, $item->barcode, $due_date );
3690     UpdateFine(
3691         {
3692             issue_id          => $issue->id(),
3693             itemnumber        => $item->itemnumber,
3694             borrowernumber    => $borrowernumber,
3695             amount            => .25,
3696             amountoutstanding => .25,
3697             type              => q{}
3698         }
3699     );
3700
3701
3702     my ( undef, $message ) = AddReturn( $item->barcode, $branch, undef, $due_date );
3703
3704     my $accountline = Koha::Account::Lines->find( { issue_id => $issue->id } );
3705     is( $accountline->amountoutstanding+0, 0, 'Fee amount outstanding was reduced to 0' );
3706     is( $accountline->amount+0, 0, 'Fee amount was reduced to 0' );
3707 };
3708
3709 $schema->storage->txn_rollback;
3710 C4::Context->clear_syspref_cache();
3711 $cache->clear_from_cache('single_holidays');