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