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