Bug 24239: (QA follow-up) Rename date_due => due_date
[koha-ffzg.git] / t / db_dependent / Circulation.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19 use utf8;
20
21 use Test::More tests => 61;
22 use Test::Exception;
23 use Test::MockModule;
24 use Test::Deep qw( cmp_deeply );
25 use Test::Warn;
26
27 use Data::Dumper;
28 use DateTime;
29 use Time::Fake;
30 use POSIX qw( floor );
31 use t::lib::Mocks;
32 use t::lib::TestBuilder;
33
34 use C4::Accounts;
35 use C4::Calendar qw( new insert_single_holiday insert_week_day_holiday delete_holiday );
36 use C4::Circulation qw( AddIssue AddReturn CanBookBeRenewed GetIssuingCharges AddRenewal GetSoonestRenewDate GetLatestAutoRenewDate LostItem GetUpcomingDueIssues CanBookBeIssued AddIssuingCharge MarkIssueReturned ProcessOfflinePayment transferbook updateWrongTransfer );
37 use C4::Biblio;
38 use C4::Items qw( ModItemTransfer );
39 use C4::Log;
40 use C4::Reserves qw( AddReserve ModReserve ModReserveCancelAll ModReserveAffect CheckReserves GetOtherReserves );
41 use C4::Overdues qw( CalcFine UpdateFine get_chargeable_units );
42 use C4::Members::Messaging qw( SetMessagingPreference );
43 use Koha::DateUtils qw( dt_from_string output_pref );
44 use Koha::Database;
45 use Koha::Items;
46 use Koha::Item::Transfers;
47 use Koha::Checkouts;
48 use Koha::Patrons;
49 use Koha::Patron::Debarments qw( GetDebarments AddDebarment DelUniqueDebarment );
50 use Koha::Holds;
51 use Koha::CirculationRules;
52 use Koha::Subscriptions;
53 use Koha::Account::Lines;
54 use Koha::Account::Offsets;
55 use Koha::ActionLogs;
56 use Koha::Notice::Messages;
57 use Koha::Cache::Memory::Lite;
58
59 sub set_userenv {
60     my ( $library ) = @_;
61     t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
62 }
63
64 sub str {
65     my ( $error, $question, $alert ) = @_;
66     my $s;
67     $s  = %$error    ? ' (error: '    . join( ' ', keys %$error    ) . ')' : '';
68     $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
69     $s .= %$alert    ? ' (alert: '    . join( ' ', keys %$alert    ) . ')' : '';
70     return $s;
71 }
72
73 sub test_debarment_on_checkout {
74     my ($params) = @_;
75     my $item     = $params->{item};
76     my $library  = $params->{library};
77     my $patron   = $params->{patron};
78     my $due_date = $params->{due_date} || dt_from_string;
79     my $return_date = $params->{return_date} || dt_from_string;
80     my $expected_expiration_date = $params->{expiration_date};
81
82     $expected_expiration_date = output_pref(
83         {
84             dt         => $expected_expiration_date,
85             dateformat => 'sql',
86             dateonly   => 1,
87         }
88     );
89     my @caller      = caller;
90     my $line_number = $caller[2];
91     AddIssue( $patron, $item->barcode, $due_date );
92
93     my ( undef, $message ) = AddReturn( $item->barcode, $library->{branchcode}, undef, $return_date );
94     is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
95         or diag('AddReturn returned message ' . Dumper $message );
96     my $debarments = Koha::Patron::Debarments::GetDebarments(
97         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
98     is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
99
100     is( $debarments->[0]->{expiration},
101         $expected_expiration_date, 'Test at line ' . $line_number );
102     Koha::Patron::Debarments::DelUniqueDebarment(
103         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
104 };
105
106 my $schema = Koha::Database->schema;
107 $schema->storage->txn_begin;
108 my $builder = t::lib::TestBuilder->new;
109 my $dbh = C4::Context->dbh;
110
111 # Prevent random failures by mocking ->now
112 my $now_value       = dt_from_string;
113 my $mocked_datetime = Test::MockModule->new('DateTime');
114 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
115
116 my $cache = Koha::Caches->get_instance();
117 $dbh->do(q|DELETE FROM special_holidays|);
118 $dbh->do(q|DELETE FROM repeatable_holidays|);
119 my $branches = Koha::Libraries->search();
120 for my $branch ( $branches->next ) {
121     my $key = $branch->branchcode . "_holidays";
122     $cache->clear_from_cache($key);
123 }
124
125 # Start with a clean slate
126 $dbh->do('DELETE FROM issues');
127 $dbh->do('DELETE FROM borrowers');
128
129 # Disable recording of the staff who checked out an item until we're ready for it
130 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 0);
131
132 my $module = Test::MockModule->new('C4::Context');
133
134 my $library = $builder->build({
135     source => 'Branch',
136 });
137 my $library2 = $builder->build({
138     source => 'Branch',
139 });
140 my $itemtype = $builder->build(
141     {
142         source => 'Itemtype',
143         value  => {
144             notforloan          => undef,
145             rentalcharge        => 0,
146             rentalcharge_daily => 0,
147             defaultreplacecost  => undef,
148             processfee          => undef
149         }
150     }
151 )->{itemtype};
152 my $patron_category = $builder->build(
153     {
154         source => 'Category',
155         value  => {
156             category_type                 => 'P',
157             enrolmentfee                  => 0,
158             BlockExpiredPatronOpacActions => -1, # Pick the pref value
159         }
160     }
161 );
162
163 my $CircControl = C4::Context->preference('CircControl');
164 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
165
166 my $item = {
167     homebranch => $library2->{branchcode},
168     holdingbranch => $library2->{branchcode}
169 };
170
171 my $borrower = {
172     branchcode => $library2->{branchcode}
173 };
174
175 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
176
177 # No userenv, PickupLibrary
178 t::lib::Mocks::mock_preference('IndependentBranches', '0');
179 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
180 is(
181     C4::Context->preference('CircControl'),
182     'PickupLibrary',
183     'CircControl changed to PickupLibrary'
184 );
185 is(
186     C4::Circulation::_GetCircControlBranch($item, $borrower),
187     $item->{$HomeOrHoldingBranch},
188     '_GetCircControlBranch returned item branch (no userenv defined)'
189 );
190
191 # No userenv, PatronLibrary
192 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
193 is(
194     C4::Context->preference('CircControl'),
195     'PatronLibrary',
196     'CircControl changed to PatronLibrary'
197 );
198 is(
199     C4::Circulation::_GetCircControlBranch($item, $borrower),
200     $borrower->{branchcode},
201     '_GetCircControlBranch returned borrower branch'
202 );
203
204 # No userenv, ItemHomeLibrary
205 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
206 is(
207     C4::Context->preference('CircControl'),
208     'ItemHomeLibrary',
209     'CircControl changed to ItemHomeLibrary'
210 );
211 is(
212     $item->{$HomeOrHoldingBranch},
213     C4::Circulation::_GetCircControlBranch($item, $borrower),
214     '_GetCircControlBranch returned item branch'
215 );
216
217 # Now, set a userenv
218 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
219 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
220
221 # Userenv set, PickupLibrary
222 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
223 is(
224     C4::Context->preference('CircControl'),
225     'PickupLibrary',
226     'CircControl changed to PickupLibrary'
227 );
228 is(
229     C4::Circulation::_GetCircControlBranch($item, $borrower),
230     $library2->{branchcode},
231     '_GetCircControlBranch returned current branch'
232 );
233
234 # Userenv set, PatronLibrary
235 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
236 is(
237     C4::Context->preference('CircControl'),
238     'PatronLibrary',
239     'CircControl changed to PatronLibrary'
240 );
241 is(
242     C4::Circulation::_GetCircControlBranch($item, $borrower),
243     $borrower->{branchcode},
244     '_GetCircControlBranch returned borrower branch'
245 );
246
247 # Userenv set, ItemHomeLibrary
248 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
249 is(
250     C4::Context->preference('CircControl'),
251     'ItemHomeLibrary',
252     'CircControl changed to ItemHomeLibrary'
253 );
254 is(
255     C4::Circulation::_GetCircControlBranch($item, $borrower),
256     $item->{$HomeOrHoldingBranch},
257     '_GetCircControlBranch returned item branch'
258 );
259
260 # Reset initial configuration
261 t::lib::Mocks::mock_preference('CircControl', $CircControl);
262 is(
263     C4::Context->preference('CircControl'),
264     $CircControl,
265     'CircControl reset to its initial value'
266 );
267
268 # Set a simple circ policy
269 $dbh->do('DELETE FROM circulation_rules');
270 Koha::CirculationRules->set_rules(
271     {
272         categorycode => undef,
273         branchcode   => undef,
274         itemtype     => undef,
275         rules        => {
276             reservesallowed => 25,
277             issuelength     => 14,
278             lengthunit      => 'days',
279             renewalsallowed => 1,
280             renewalperiod   => 7,
281             norenewalbefore => undef,
282             auto_renew      => 0,
283             fine            => .10,
284             chargeperiod    => 1,
285         }
286     }
287 );
288
289 subtest "CanBookBeRenewed AllowRenewalIfOtherItemsAvailable multiple borrowers and items tests" => sub {
290     plan tests => 5;
291
292     #Can only reserve from home branch
293     Koha::CirculationRules->set_rule(
294         {
295             branchcode   => undef,
296             itemtype     => undef,
297             rule_name    => 'holdallowed',
298             rule_value   => 1
299         }
300     );
301     Koha::CirculationRules->set_rule(
302         {
303             branchcode   => undef,
304             categorycode   => undef,
305             itemtype     => undef,
306             rule_name    => 'onshelfholds',
307             rule_value   => 1
308         }
309     );
310
311     # Patrons from three different branches
312     my $patron_borrower = $builder->build_object({ class => 'Koha::Patrons' });
313     my $patron_hold_1   = $builder->build_object({ class => 'Koha::Patrons' });
314     my $patron_hold_2   = $builder->build_object({ class => 'Koha::Patrons' });
315     my $biblio = $builder->build_sample_biblio();
316
317     # Item at each patron branch
318     my $item_1 = $builder->build_sample_item({
319         biblionumber => $biblio->biblionumber,
320         homebranch   => $patron_borrower->branchcode
321     });
322     my $item_2 = $builder->build_sample_item({
323         biblionumber => $biblio->biblionumber,
324         homebranch   => $patron_hold_2->branchcode
325     });
326     my $item_3 = $builder->build_sample_item({
327         biblionumber => $biblio->biblionumber,
328         homebranch   => $patron_hold_1->branchcode
329     });
330
331     my $issue = AddIssue( $patron_borrower->unblessed, $item_1->barcode);
332     my $datedue = dt_from_string( $issue->date_due() );
333     is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
334
335     # Biblio-level holds
336     AddReserve(
337         {
338             branchcode       => $patron_hold_1->branchcode,
339             borrowernumber   => $patron_hold_1->borrowernumber,
340             biblionumber     => $biblio->biblionumber,
341             priority         => 1,
342             reservation_date => dt_from_string(),
343             expiration_date  => undef,
344             itemnumber       => undef,
345             found            => undef,
346         }
347     );
348     AddReserve(
349         {
350             branchcode       => $patron_hold_2->branchcode,
351             borrowernumber   => $patron_hold_2->borrowernumber,
352             biblionumber     => $biblio->biblionumber,
353             priority         => 2,
354             reservation_date => dt_from_string(),
355             expiration_date  => undef,
356             itemnumber       => undef,
357             found            => undef,
358         }
359     );
360     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
361
362     my ( $renewokay, $error ) = CanBookBeRenewed($patron_borrower->borrowernumber, $item_1->itemnumber);
363     is( $renewokay, 0, 'Cannot renew, reserved');
364     is( $error, 'on_reserve', 'Cannot renew, reserved (returned error is on_reserve)');
365
366     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
367
368     ( $renewokay, $error ) = CanBookBeRenewed($patron_borrower->borrowernumber, $item_1->itemnumber);
369     is( $renewokay, 1, 'Can renew, two items available for two holds');
370     is( $error, undef, 'Can renew, each reserve has an item');
371
372
373 };
374
375 subtest "GetIssuingCharges tests" => sub {
376     plan tests => 4;
377     my $branch_discount = $builder->build_object({ class => 'Koha::Libraries' });
378     my $branch_no_discount = $builder->build_object({ class => 'Koha::Libraries' });
379     Koha::CirculationRules->set_rule(
380         {
381             categorycode => undef,
382             branchcode   => $branch_discount->branchcode,
383             itemtype     => undef,
384             rule_name    => 'rentaldiscount',
385             rule_value   => 15
386         }
387     );
388     my $itype_charge = $builder->build_object({
389         class => 'Koha::ItemTypes',
390         value => {
391             rentalcharge => 10
392         }
393     });
394     my $itype_no_charge = $builder->build_object({
395         class => 'Koha::ItemTypes',
396         value => {
397             rentalcharge => 0
398         }
399     });
400     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
401     my $item_1 = $builder->build_sample_item({ itype => $itype_charge->itemtype });
402     my $item_2 = $builder->build_sample_item({ itype => $itype_no_charge->itemtype });
403
404     t::lib::Mocks::mock_userenv({ branchcode => $branch_no_discount->branchcode });
405     # For now the sub always uses the env branch, this should follow CircControl instead
406     my ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
407     is( $charge + 0, 10.00, "Charge fetched correctly when no discount exists");
408     ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
409     is( $charge + 0, 0.00, "Charge fetched correctly when no discount exists and no charge");
410
411     t::lib::Mocks::mock_userenv({ branchcode => $branch_discount->branchcode });
412     # For now the sub always uses the env branch, this should follow CircControl instead
413     ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
414     is( $charge + 0, 8.50, "Charge fetched correctly when discount exists");
415     ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
416     is( $charge + 0, 0.00, "Charge fetched correctly when discount exists and no charge");
417
418 };
419
420 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
421 subtest "CanBookBeRenewed tests" => sub {
422     plan tests => 104;
423
424     C4::Context->set_preference('ItemsDeniedRenewal','');
425     # Generate test biblio
426     my $biblio = $builder->build_sample_biblio();
427
428     my $branch = $library2->{branchcode};
429
430     my $item_1 = $builder->build_sample_item(
431         {
432             biblionumber     => $biblio->biblionumber,
433             library          => $branch,
434             replacementprice => 12.00,
435             itype            => $itemtype
436         }
437     );
438     $reused_itemnumber_1 = $item_1->itemnumber;
439
440     my $item_2 = $builder->build_sample_item(
441         {
442             biblionumber     => $biblio->biblionumber,
443             library          => $branch,
444             replacementprice => 23.00,
445             itype            => $itemtype
446         }
447     );
448     $reused_itemnumber_2 = $item_2->itemnumber;
449
450     my $item_3 = $builder->build_sample_item(
451         {
452             biblionumber     => $biblio->biblionumber,
453             library          => $branch,
454             replacementprice => 23.00,
455             itype            => $itemtype
456         }
457     );
458
459     # Create borrowers
460     my %renewing_borrower_data = (
461         firstname =>  'John',
462         surname => 'Renewal',
463         categorycode => $patron_category->{categorycode},
464         branchcode => $branch,
465     );
466
467     my %reserving_borrower_data = (
468         firstname =>  'Katrin',
469         surname => 'Reservation',
470         categorycode => $patron_category->{categorycode},
471         branchcode => $branch,
472     );
473
474     my %hold_waiting_borrower_data = (
475         firstname =>  'Kyle',
476         surname => 'Reservation',
477         categorycode => $patron_category->{categorycode},
478         branchcode => $branch,
479     );
480
481     my %restricted_borrower_data = (
482         firstname =>  'Alice',
483         surname => 'Reservation',
484         categorycode => $patron_category->{categorycode},
485         debarred => '3228-01-01',
486         branchcode => $branch,
487     );
488
489     my %expired_borrower_data = (
490         firstname =>  'Ça',
491         surname => 'Glisse',
492         categorycode => $patron_category->{categorycode},
493         branchcode => $branch,
494         dateexpiry => dt_from_string->subtract( months => 1 ),
495     );
496
497     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
498     my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
499     my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
500     my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
501     my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
502
503     my $renewing_borrower_obj = Koha::Patrons->find( $renewing_borrowernumber );
504     my $renewing_borrower = $renewing_borrower_obj->unblessed;
505     my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
506     my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
507
508     my $bibitems       = '';
509     my $priority       = '1';
510     my $resdate        = undef;
511     my $expdate        = undef;
512     my $notes          = '';
513     my $checkitem      = undef;
514     my $found          = undef;
515
516     my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
517     my $datedue = dt_from_string( $issue->date_due() );
518     is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
519
520     my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
521     $datedue = dt_from_string( $issue->date_due() );
522     is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
523
524
525     my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
526     is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
527
528     my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
529     is( $renewokay, 1, 'Can renew, no holds for this title or item');
530
531
532     # Biblio-level hold, renewal test
533     AddReserve(
534         {
535             branchcode       => $branch,
536             borrowernumber   => $reserving_borrowernumber,
537             biblionumber     => $biblio->biblionumber,
538             priority         => $priority,
539             reservation_date => $resdate,
540             expiration_date  => $expdate,
541             notes            => $notes,
542             itemnumber       => $checkitem,
543             found            => $found,
544         }
545     );
546
547     # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
548     Koha::CirculationRules->set_rule(
549         {
550             categorycode => undef,
551             branchcode   => undef,
552             itemtype     => undef,
553             rule_name    => 'onshelfholds',
554             rule_value   => '1',
555         }
556     );
557     Koha::CirculationRules->set_rule(
558         {
559             categorycode => undef,
560             branchcode   => undef,
561             itemtype     => undef,
562             rule_name    => 'renewalsallowed',
563             rule_value   => '5',
564         }
565     );
566     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
567     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
568     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
569     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
570     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
571
572     # Now let's add an item level hold, we should no longer be able to renew the item
573     my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
574         {
575             borrowernumber => $hold_waiting_borrowernumber,
576             biblionumber   => $biblio->biblionumber,
577             itemnumber     => $item_1->itemnumber,
578             branchcode     => $branch,
579             priority       => 3,
580         }
581     );
582     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
583     is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
584     $hold->delete();
585
586     # 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
587     # be able to renew these items
588     $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
589         {
590             borrowernumber => $hold_waiting_borrowernumber,
591             biblionumber   => $biblio->biblionumber,
592             itemnumber     => $item_3->itemnumber,
593             branchcode     => $branch,
594             priority       => 0,
595             found          => 'W'
596         }
597     );
598     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
599     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
600     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
601     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
602     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
603
604     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
605     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
606     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
607
608     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
609     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
610     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
611
612     my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
613     my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
614     AddIssue($reserving_borrower, $item_3->barcode);
615     my $reserve = $dbh->selectrow_hashref(
616         'SELECT * FROM old_reserves WHERE reserve_id = ?',
617         { Slice => {} },
618         $reserveid
619     );
620     is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
621
622     # Item-level hold, renewal test
623     AddReserve(
624         {
625             branchcode       => $branch,
626             borrowernumber   => $reserving_borrowernumber,
627             biblionumber     => $biblio->biblionumber,
628             priority         => $priority,
629             reservation_date => $resdate,
630             expiration_date  => $expdate,
631             notes            => $notes,
632             itemnumber       => $item_1->itemnumber,
633             found            => $found,
634         }
635     );
636
637     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
638     is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
639     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
640
641     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
642     is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
643
644     # Items can't fill hold for reasons
645     $item_1->notforloan(1)->store;
646     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
647     is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
648     $item_1->set({notforloan => 0, itype => $itemtype })->store;
649
650     # FIXME: Add more for itemtype not for loan etc.
651
652     # Restricted users cannot renew when RestrictionBlockRenewing is enabled
653     my $item_5 = $builder->build_sample_item(
654         {
655             biblionumber     => $biblio->biblionumber,
656             library          => $branch,
657             replacementprice => 23.00,
658             itype            => $itemtype,
659         }
660     );
661     my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
662     is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
663
664     t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
665     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
666     is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
667     ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
668     is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
669     is( $error, 'restriction', "Correct error returned");
670
671     # Users cannot renew an overdue item
672     my $item_6 = $builder->build_sample_item(
673         {
674             biblionumber     => $biblio->biblionumber,
675             library          => $branch,
676             replacementprice => 23.00,
677             itype            => $itemtype,
678         }
679     );
680
681     my $item_7 = $builder->build_sample_item(
682         {
683             biblionumber     => $biblio->biblionumber,
684             library          => $branch,
685             replacementprice => 23.00,
686             itype            => $itemtype,
687         }
688     );
689
690     my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
691     is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
692
693     my $now = dt_from_string();
694     my $five_weeks = DateTime::Duration->new(weeks => 5);
695     my $five_weeks_ago = $now - $five_weeks;
696     t::lib::Mocks::mock_preference('finesMode', 'production');
697
698     my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
699     is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
700
701     my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
702     C4::Overdues::UpdateFine(
703         {
704             issue_id       => $passeddatedue1->id(),
705             itemnumber     => $item_7->itemnumber,
706             borrowernumber => $renewing_borrower->{borrowernumber},
707             amount         => $fine,
708             due            => Koha::DateUtils::output_pref($five_weeks_ago)
709         }
710     );
711
712     # Make sure fine calculation isn't skipped when adding renewal
713     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
714
715     t::lib::Mocks::mock_preference('RenewalLog', 0);
716     my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
717     my %params_renewal = (
718         timestamp => { -like => $date . "%" },
719         module => "CIRCULATION",
720         action => "RENEWAL",
721     );
722     my %params_issue = (
723         timestamp => { -like => $date . "%" },
724         module => "CIRCULATION",
725         action => "ISSUE"
726     );
727     my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
728     my $dt = dt_from_string();
729     Time::Fake->offset( $dt->epoch );
730     my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
731     my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
732     is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
733     isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
734     Time::Fake->reset;
735
736     t::lib::Mocks::mock_preference('RenewalLog', 1);
737     $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
738     $old_log_size = Koha::ActionLogs->count( \%params_renewal );
739     AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
740     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
741     is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
742
743     my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
744     is( $fines->count, 2, 'AddRenewal left both fines' );
745     isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
746     isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
747     $fines->delete();
748
749     t::lib::Mocks::mock_preference('OverduesBlockRenewing','allow');
750     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
751     is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
752     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
753     is( $renewokay, 1, '(Bug 8236), Can renew, this item is overdue but not pref does not block');
754
755     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
756     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
757     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is not overdue but patron has overdues');
758     is( $error, 'overdue', "Correct error returned");
759     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
760     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue so patron has overdues');
761     is( $error, 'overdue', "Correct error returned");
762
763     t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
764     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
765     is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
766     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
767     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
768     is( $error, 'overdue', "Correct error returned");
769
770
771     my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
772     my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
773     AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
774     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
775     is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
776     $new_log_size = Koha::ActionLogs->count( \%params_issue );
777     is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
778
779     $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
780     $fines->delete();
781
782     $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
783     $hold->cancel;
784
785     # Bug 14101
786     # Test automatic renewal before value for "norenewalbefore" in policy is set
787     # In this case automatic renewal is not permitted prior to due date
788     my $item_4 = $builder->build_sample_item(
789         {
790             biblionumber     => $biblio->biblionumber,
791             library          => $branch,
792             replacementprice => 16.00,
793             itype            => $itemtype,
794         }
795     );
796
797     $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
798     my $info;
799     ( $renewokay, $error, $info ) =
800       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
801     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
802     is( $error, 'auto_too_soon',
803         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
804     is( $info->{soonest_renew_date} , dt_from_string($issue->date_due), "Due date is returned as earliest renewal date when error is 'auto_too_soon'" );
805     AddReserve(
806         {
807             branchcode       => $branch,
808             borrowernumber   => $reserving_borrowernumber,
809             biblionumber     => $biblio->biblionumber,
810             itemnumber       => $bibitems,
811             priority         => $priority,
812             reservation_date => $resdate,
813             expiration_date  => $expdate,
814             notes            => $notes,
815             title            => 'a title',
816             itemnumber       => $item_4->itemnumber,
817             found            => $found
818         }
819     );
820     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
821     is( $renewokay, 0, 'Still should not be able to renew' );
822     is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' );
823     ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, undef, 1 );
824     is( $renewokay, 0, 'Still should not be able to renew' );
825     is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' );
826     is( $info->{soonest_renew_date}, dt_from_string($issue->date_due), "Due date is returned as earliest renewal date when error is 'auto_too_soon'" );
827     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
828     is( $renewokay, 0, 'Still should not be able to renew' );
829     is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
830     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1, 1 );
831     is( $renewokay, 0, 'Still should not be able to renew' );
832     is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
833     $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
834     Koha::Cache::Memory::Lite->flush();
835     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
836     is( $renewokay, 0, 'Still should not be able to renew' );
837     is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
838     ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
839
840
841
842     $renewing_borrower_obj->autorenew_checkouts(0)->store;
843     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
844     is( $renewokay, 1, 'No renewal before is undef, but patron opted out of auto_renewal' );
845     $renewing_borrower_obj->autorenew_checkouts(1)->store;
846
847
848     # Bug 7413
849     # Test premature manual renewal
850     Koha::CirculationRules->set_rule(
851         {
852             categorycode => undef,
853             branchcode   => undef,
854             itemtype     => undef,
855             rule_name    => 'norenewalbefore',
856             rule_value   => '7',
857         }
858     );
859
860     ( $renewokay, $error, $info ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
861     is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
862     is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
863     is( $info->{soonest_renew_date}, dt_from_string($issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
864
865     # Bug 14101
866     # Test premature automatic renewal
867     ( $renewokay, $error, $info ) =
868       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
869     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
870     is( $error, 'auto_too_soon',
871         'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
872     );
873     is( $info->{soonest_renew_date}, dt_from_string($issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'auto_too_soon'");
874
875     $renewing_borrower_obj->autorenew_checkouts(0)->store;
876     ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
877     is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' );
878     is( $error, 'too_soon', 'Error is too_soon, no auto' );
879     is( $info->{soonest_renew_date}, dt_from_string($issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
880     $renewing_borrower_obj->autorenew_checkouts(1)->store;
881
882     # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
883     # and test automatic renewal again
884     $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
885     Koha::Cache::Memory::Lite->flush();
886     ( $renewokay, $error, $info ) =
887       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
888     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
889     is( $error, 'auto_too_soon',
890         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
891     );
892     is( $info->{soonest_renew_date}, dt_from_string($issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
893
894     $renewing_borrower_obj->autorenew_checkouts(0)->store;
895     ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
896     is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' );
897     is( $error, 'too_soon', 'Error is too_soon, no auto' );
898     is( $info->{soonest_renew_date}, dt_from_string($issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
899     $renewing_borrower_obj->autorenew_checkouts(1)->store;
900
901     # Change policy so that loans can be renewed 99 days prior to the due date
902     # and test automatic renewal again
903     $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
904     Koha::Cache::Memory::Lite->flush();
905     ( $renewokay, $error ) =
906       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
907     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
908     is( $error, 'auto_renew',
909         'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
910     );
911
912     $renewing_borrower_obj->autorenew_checkouts(0)->store;
913     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
914     is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' );
915     $renewing_borrower_obj->autorenew_checkouts(1)->store;
916
917     subtest "too_late_renewal / no_auto_renewal_after" => sub {
918         plan tests => 14;
919         my $item_to_auto_renew = $builder->build_sample_item(
920             {
921                 biblionumber => $biblio->biblionumber,
922                 library      => $branch,
923             }
924         );
925
926         my $ten_days_before = dt_from_string->add( days => -10 );
927         my $ten_days_ahead  = dt_from_string->add( days => 10 );
928         AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
929
930         Koha::CirculationRules->set_rules(
931             {
932                 categorycode => undef,
933                 branchcode   => undef,
934                 itemtype     => undef,
935                 rules        => {
936                     norenewalbefore       => '7',
937                     no_auto_renewal_after => '9',
938                 }
939             }
940         );
941         ( $renewokay, $error ) =
942           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
943         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
944         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
945
946         Koha::CirculationRules->set_rules(
947             {
948                 categorycode => undef,
949                 branchcode   => undef,
950                 itemtype     => undef,
951                 rules        => {
952                     norenewalbefore       => '7',
953                     no_auto_renewal_after => '10',
954                 }
955             }
956         );
957         ( $renewokay, $error ) =
958           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
959         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
960         is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
961
962         Koha::CirculationRules->set_rules(
963             {
964                 categorycode => undef,
965                 branchcode   => undef,
966                 itemtype     => undef,
967                 rules        => {
968                     norenewalbefore       => '7',
969                     no_auto_renewal_after => '11',
970                 }
971             }
972         );
973         ( $renewokay, $error ) =
974           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
975         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
976         is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
977
978         Koha::CirculationRules->set_rules(
979             {
980                 categorycode => undef,
981                 branchcode   => undef,
982                 itemtype     => undef,
983                 rules        => {
984                     norenewalbefore       => '10',
985                     no_auto_renewal_after => '11',
986                 }
987             }
988         );
989         ( $renewokay, $error ) =
990           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
991         is( $renewokay, 0,            'Do not renew, renewal is automatic' );
992         is( $error,     'auto_renew', 'Cannot renew, renew is automatic' );
993
994         Koha::CirculationRules->set_rules(
995             {
996                 categorycode => undef,
997                 branchcode   => undef,
998                 itemtype     => undef,
999                 rules        => {
1000                     norenewalbefore       => '10',
1001                     no_auto_renewal_after => undef,
1002                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1003                 }
1004             }
1005         );
1006         ( $renewokay, $error ) =
1007           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1008         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1009         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1010
1011         Koha::CirculationRules->set_rules(
1012             {
1013                 categorycode => undef,
1014                 branchcode   => undef,
1015                 itemtype     => undef,
1016                 rules        => {
1017                     norenewalbefore       => '7',
1018                     no_auto_renewal_after => '15',
1019                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1020                 }
1021             }
1022         );
1023         ( $renewokay, $error ) =
1024           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1025         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1026         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1027
1028         Koha::CirculationRules->set_rules(
1029             {
1030                 categorycode => undef,
1031                 branchcode   => undef,
1032                 itemtype     => undef,
1033                 rules        => {
1034                     norenewalbefore       => '10',
1035                     no_auto_renewal_after => undef,
1036                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
1037                 }
1038             }
1039         );
1040         ( $renewokay, $error ) =
1041           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1042         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1043         is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1044     };
1045
1046     subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
1047         plan tests => 10;
1048         my $item_to_auto_renew = $builder->build_sample_item(
1049             {
1050                 biblionumber => $biblio->biblionumber,
1051                 library      => $branch,
1052             }
1053         );
1054
1055         my $ten_days_before = dt_from_string->add( days => -10 );
1056         my $ten_days_ahead = dt_from_string->add( days => 10 );
1057         AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1058
1059         Koha::CirculationRules->set_rules(
1060             {
1061                 categorycode => undef,
1062                 branchcode   => undef,
1063                 itemtype     => undef,
1064                 rules        => {
1065                     norenewalbefore       => '10',
1066                     no_auto_renewal_after => '11',
1067                 }
1068             }
1069         );
1070         C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
1071         C4::Context->set_preference('OPACFineNoRenewals','10');
1072         C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1073         my $fines_amount = 5;
1074         my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
1075         $account->add_debit(
1076             {
1077                 amount      => $fines_amount,
1078                 interface   => 'test',
1079                 type        => 'OVERDUE',
1080                 item_id     => $item_to_auto_renew->itemnumber,
1081                 description => "Some fines"
1082             }
1083         )->status('RETURNED')->store;
1084         ( $renewokay, $error ) =
1085           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1086         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1087         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
1088
1089         $account->add_debit(
1090             {
1091                 amount      => $fines_amount,
1092                 interface   => 'test',
1093                 type        => 'OVERDUE',
1094                 item_id     => $item_to_auto_renew->itemnumber,
1095                 description => "Some fines"
1096             }
1097         )->status('RETURNED')->store;
1098         ( $renewokay, $error ) =
1099           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1100         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1101         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
1102
1103         $account->add_debit(
1104             {
1105                 amount      => $fines_amount,
1106                 interface   => 'test',
1107                 type        => 'OVERDUE',
1108                 item_id     => $item_to_auto_renew->itemnumber,
1109                 description => "Some fines"
1110             }
1111         )->status('RETURNED')->store;
1112         ( $renewokay, $error ) =
1113           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1114         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1115         is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
1116
1117         $account->add_credit(
1118             {
1119                 amount      => $fines_amount,
1120                 interface   => 'test',
1121                 type        => 'PAYMENT',
1122                 description => "Some payment"
1123             }
1124         )->store;
1125         ( $renewokay, $error ) =
1126           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1127         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1128         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit'  );
1129
1130         C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
1131         ( $renewokay, $error ) =
1132           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1133         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1134         is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit'  );
1135
1136         $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
1137         C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1138     };
1139
1140     subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
1141         plan tests => 6;
1142         my $item_to_auto_renew = $builder->build_sample_item(
1143             {
1144                 biblionumber => $biblio->biblionumber,
1145                 library      => $branch,
1146             }
1147         );
1148
1149         Koha::CirculationRules->set_rules(
1150             {
1151                 categorycode => undef,
1152                 branchcode   => undef,
1153                 itemtype     => undef,
1154                 rules        => {
1155                     norenewalbefore       => 10,
1156                     no_auto_renewal_after => 11,
1157                 }
1158             }
1159         );
1160
1161         my $ten_days_before = dt_from_string->add( days => -10 );
1162         my $ten_days_ahead = dt_from_string->add( days => 10 );
1163
1164         # Patron is expired and BlockExpiredPatronOpacActions=0
1165         # => auto renew is allowed
1166         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
1167         my $patron = $expired_borrower;
1168         my $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1169         ( $renewokay, $error ) =
1170           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1171         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1172         is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
1173         Koha::Checkouts->find( $checkout->issue_id )->delete;
1174
1175
1176         # Patron is expired and BlockExpiredPatronOpacActions=1
1177         # => auto renew is not allowed
1178         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1179         $patron = $expired_borrower;
1180         $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1181         ( $renewokay, $error ) =
1182           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1183         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1184         is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
1185         Koha::Checkouts->find( $checkout->issue_id )->delete;
1186
1187
1188         # Patron is not expired and BlockExpiredPatronOpacActions=1
1189         # => auto renew is allowed
1190         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1191         $patron = $renewing_borrower;
1192         $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1193         ( $renewokay, $error ) =
1194           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1195         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1196         is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1197         Koha::Checkouts->find( $checkout->issue_id )->delete;
1198     };
1199
1200     subtest "GetLatestAutoRenewDate" => sub {
1201         plan tests => 5;
1202         my $item_to_auto_renew = $builder->build_sample_item(
1203             {
1204                 biblionumber => $biblio->biblionumber,
1205                 library      => $branch,
1206             }
1207         );
1208
1209         my $ten_days_before = dt_from_string->add( days => -10 );
1210         my $ten_days_ahead  = dt_from_string->add( days => 10 );
1211         AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1212         Koha::CirculationRules->set_rules(
1213             {
1214                 categorycode => undef,
1215                 branchcode   => undef,
1216                 itemtype     => undef,
1217                 rules        => {
1218                     norenewalbefore       => '7',
1219                     no_auto_renewal_after => '',
1220                     no_auto_renewal_after_hard_limit => undef,
1221                 }
1222             }
1223         );
1224         my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1225         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' );
1226         my $five_days_before = dt_from_string->add( days => -5 );
1227         Koha::CirculationRules->set_rules(
1228             {
1229                 categorycode => undef,
1230                 branchcode   => undef,
1231                 itemtype     => undef,
1232                 rules        => {
1233                     norenewalbefore       => '10',
1234                     no_auto_renewal_after => '5',
1235                     no_auto_renewal_after_hard_limit => undef,
1236                 }
1237             }
1238         );
1239         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1240         is( $latest_auto_renew_date->truncate( to => 'minute' ),
1241             $five_days_before->truncate( to => 'minute' ),
1242             'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1243         );
1244         my $five_days_ahead = dt_from_string->add( days => 5 );
1245         $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1246         $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1247         $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1248         Koha::Cache::Memory::Lite->flush();
1249         Koha::CirculationRules->set_rules(
1250             {
1251                 categorycode => undef,
1252                 branchcode   => undef,
1253                 itemtype     => undef,
1254                 rules        => {
1255                     norenewalbefore       => '10',
1256                     no_auto_renewal_after => '15',
1257                     no_auto_renewal_after_hard_limit => undef,
1258                 }
1259             }
1260         );
1261         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1262         is( $latest_auto_renew_date->truncate( to => 'minute' ),
1263             $five_days_ahead->truncate( to => 'minute' ),
1264             'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1265         );
1266         my $two_days_ahead = dt_from_string->add( days => 2 );
1267         Koha::CirculationRules->set_rules(
1268             {
1269                 categorycode => undef,
1270                 branchcode   => undef,
1271                 itemtype     => undef,
1272                 rules        => {
1273                     norenewalbefore       => '10',
1274                     no_auto_renewal_after => '',
1275                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1276                 }
1277             }
1278         );
1279         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1280         is( $latest_auto_renew_date->truncate( to => 'day' ),
1281             $two_days_ahead->truncate( to => 'day' ),
1282             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1283         );
1284         Koha::CirculationRules->set_rules(
1285             {
1286                 categorycode => undef,
1287                 branchcode   => undef,
1288                 itemtype     => undef,
1289                 rules        => {
1290                     norenewalbefore       => '10',
1291                     no_auto_renewal_after => '15',
1292                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1293                 }
1294             }
1295         );
1296         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1297         is( $latest_auto_renew_date->truncate( to => 'day' ),
1298             $two_days_ahead->truncate( to => 'day' ),
1299             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1300         );
1301
1302     };
1303     # Too many renewals
1304
1305     # set policy to forbid renewals
1306     Koha::CirculationRules->set_rules(
1307         {
1308             categorycode => undef,
1309             branchcode   => undef,
1310             itemtype     => undef,
1311             rules        => {
1312                 norenewalbefore => undef,
1313                 renewalsallowed => 0,
1314             }
1315         }
1316     );
1317
1318     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1319     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1320     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1321
1322     # Too many unseen renewals
1323     Koha::CirculationRules->set_rules(
1324         {
1325             categorycode => undef,
1326             branchcode   => undef,
1327             itemtype     => undef,
1328             rules        => {
1329                 unseen_renewals_allowed => 2,
1330                 renewalsallowed => 10,
1331             }
1332         }
1333     );
1334     t::lib::Mocks::mock_preference('UnseenRenewals', 1);
1335     $dbh->do('UPDATE issues SET unseen_renewals = 2 where borrowernumber = ? AND itemnumber = ?', undef, ($renewing_borrowernumber, $item_1->itemnumber));
1336     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1337     is( $renewokay, 0, 'Cannot renew, 0 unseen renewals allowed');
1338     is( $error, 'too_unseen', 'Cannot renew, returned code is too_unseen');
1339     Koha::CirculationRules->set_rules(
1340         {
1341             categorycode => undef,
1342             branchcode   => undef,
1343             itemtype     => undef,
1344             rules        => {
1345                 norenewalbefore => undef,
1346                 renewalsallowed => 0,
1347             }
1348         }
1349     );
1350     t::lib::Mocks::mock_preference('UnseenRenewals', 0);
1351
1352     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1353     t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1354     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1355
1356     C4::Overdues::UpdateFine(
1357         {
1358             issue_id       => $issue->id(),
1359             itemnumber     => $item_1->itemnumber,
1360             borrowernumber => $renewing_borrower->{borrowernumber},
1361             amount         => 15.00,
1362             type           => q{},
1363             due            => Koha::DateUtils::output_pref($datedue)
1364         }
1365     );
1366
1367     my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
1368     is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1369     is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1370     is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1371     is( $line->amount+0, 15, 'Account line amount is 15.00' );
1372     is( $line->issue_id, $issue->id, 'Account line issue id matches' );
1373
1374     my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1375     is( $offset->type, 'CREATE', 'Account offset type is CREATE' );
1376     is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1377
1378     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1379     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1380
1381     LostItem( $item_1->itemnumber, 'test', 1 );
1382
1383     $line = Koha::Account::Lines->find($line->id);
1384     is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1385     isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1386
1387     my $item = Koha::Items->find($item_1->itemnumber);
1388     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1389     my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1390     is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1391
1392     my $total_due = $dbh->selectrow_array(
1393         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1394         undef, $renewing_borrower->{borrowernumber}
1395     );
1396
1397     is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1398
1399     C4::Context->dbh->do("DELETE FROM accountlines");
1400
1401     C4::Overdues::UpdateFine(
1402         {
1403             issue_id       => $issue2->id(),
1404             itemnumber     => $item_2->itemnumber,
1405             borrowernumber => $renewing_borrower->{borrowernumber},
1406             amount         => 15.00,
1407             type           => q{},
1408             due            => Koha::DateUtils::output_pref($datedue)
1409         }
1410     );
1411
1412     LostItem( $item_2->itemnumber, 'test', 0 );
1413
1414     my $item2 = Koha::Items->find($item_2->itemnumber);
1415     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1416     ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1417
1418     $total_due = $dbh->selectrow_array(
1419         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1420         undef, $renewing_borrower->{borrowernumber}
1421     );
1422
1423     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1424
1425     my $future = dt_from_string();
1426     $future->add( days => 7 );
1427     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1428     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1429
1430     my $manager = $builder->build_object({ class => "Koha::Patrons" });
1431     t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1432     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1433     $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1434     LostItem( $item_3->itemnumber, 'test', 0 );
1435     my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1436     is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1437     is(
1438         $accountline->description,
1439         sprintf( "%s %s %s",
1440             $item_3->biblio->title  || '',
1441             $item_3->barcode        || '',
1442             $item_3->itemcallnumber || '' ),
1443         "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1444     );
1445
1446     # Recalls
1447     t::lib::Mocks::mock_preference('UseRecalls', 1);
1448     Koha::CirculationRules->set_rules({
1449         categorycode => undef,
1450         branchcode => undef,
1451         itemtype => undef,
1452         rules => {
1453             recalls_allowed => 10,
1454             renewalsallowed => 5,
1455         },
1456     });
1457     my $recall_borrower = $builder->build_object({ class => 'Koha::Patrons' });
1458     my $recall_biblio = $builder->build_object({ class => 'Koha::Biblios' });
1459     my $recall_item1 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $recall_biblio->biblionumber } });
1460     my $recall_item2 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $recall_biblio->biblionumber } });
1461
1462     AddIssue( $renewing_borrower, $recall_item1->barcode );
1463
1464     # item-level and this item: renewal not allowed
1465     my $recall = Koha::Recall->new({
1466         biblio_id => $recall_item1->biblionumber,
1467         item_id => $recall_item1->itemnumber,
1468         patron_id => $recall_borrower->borrowernumber,
1469         pickup_library_id => $recall_borrower->branchcode,
1470         item_level => 1,
1471     })->store;
1472     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1473     is( $error, 'recalled', 'Cannot renew item that has been recalled' );
1474     $recall->set_cancelled;
1475
1476     # biblio-level requested recall: renewal not allowed
1477     $recall = Koha::Recall->new({
1478         biblio_id => $recall_item1->biblionumber,
1479         item_id => undef,
1480         patron_id => $recall_borrower->borrowernumber,
1481         pickup_library_id => $recall_borrower->branchcode,
1482         item_level => 0,
1483     })->store;
1484     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1485     is( $error, 'recalled', 'Cannot renew item if biblio is recalled and has no item allocated' );
1486     $recall->set_cancelled;
1487
1488     # item-level and not this item: renewal allowed
1489     $recall = Koha::Recall->new({
1490         biblio_id => $recall_item2->biblionumber,
1491         item_id => $recall_item2->itemnumber,
1492         patron_id => $recall_borrower->borrowernumber,
1493         pickup_library_id => $recall_borrower->branchcode,
1494         item_level => 1,
1495     })->store;
1496     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1497     is( $renewokay, 1, 'Can renew item if item-level recall on biblio is not on this item' );
1498     $recall->set_cancelled;
1499
1500     # biblio-level waiting recall: renewal allowed
1501     $recall = Koha::Recall->new({
1502         biblio_id => $recall_item1->biblionumber,
1503         item_id => undef,
1504         patron_id => $recall_borrower->borrowernumber,
1505         pickup_library_id => $recall_borrower->branchcode,
1506         item_level => 0,
1507     })->store;
1508     $recall->set_waiting({ item => $recall_item1 });
1509     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1510     is( $renewokay, 1, 'Can renew item if biblio-level recall has already been allocated an item' );
1511     $recall->set_cancelled;
1512 };
1513
1514 subtest "GetUpcomingDueIssues" => sub {
1515     plan tests => 12;
1516
1517     my $branch   = $library2->{branchcode};
1518
1519     #Create another record
1520     my $biblio2 = $builder->build_sample_biblio();
1521
1522     #Create third item
1523     my $item_1 = Koha::Items->find($reused_itemnumber_1);
1524     my $item_2 = Koha::Items->find($reused_itemnumber_2);
1525     my $item_3 = $builder->build_sample_item(
1526         {
1527             biblionumber     => $biblio2->biblionumber,
1528             library          => $branch,
1529             itype            => $itemtype,
1530         }
1531     );
1532
1533
1534     # Create a borrower
1535     my %a_borrower_data = (
1536         firstname =>  'Fridolyn',
1537         surname => 'SOMERS',
1538         categorycode => $patron_category->{categorycode},
1539         branchcode => $branch,
1540     );
1541
1542     my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1543     my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1544
1545     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1546     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1547     my $today = DateTime->today(time_zone => C4::Context->tz());
1548
1549     my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1550     my $datedue = dt_from_string( $issue->date_due() );
1551     my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1552     my $datedue2 = dt_from_string( $issue->date_due() );
1553
1554     my $upcoming_dues;
1555
1556     # GetUpcomingDueIssues tests
1557     for my $i(0..1) {
1558         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1559         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1560     }
1561
1562     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1563     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1564     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1565
1566     for my $i(3..5) {
1567         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1568         is ( scalar( @$upcoming_dues ), 1,
1569             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1570     }
1571
1572     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1573
1574     my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1575
1576     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1577     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1578
1579     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1580     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1581
1582     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1583     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1584
1585     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
1586     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1587
1588     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1589     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1590
1591     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1592     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1593
1594 };
1595
1596 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1597     my $branch   = $library2->{branchcode};
1598
1599     my $biblio = $builder->build_sample_biblio();
1600
1601     #Create third item
1602     my $item = $builder->build_sample_item(
1603         {
1604             biblionumber     => $biblio->biblionumber,
1605             library          => $branch,
1606             itype            => $itemtype,
1607         }
1608     );
1609
1610     # Create a borrower
1611     my %a_borrower_data = (
1612         firstname =>  'Kyle',
1613         surname => 'Hall',
1614         categorycode => $patron_category->{categorycode},
1615         branchcode => $branch,
1616     );
1617
1618     my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1619
1620     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1621     my $issue = AddIssue( $borrower, $item->barcode );
1622     UpdateFine(
1623         {
1624             issue_id       => $issue->id(),
1625             itemnumber     => $item->itemnumber,
1626             borrowernumber => $borrowernumber,
1627             amount         => 0,
1628             type           => q{}
1629         }
1630     );
1631
1632     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1633     my $count = $hr->{count};
1634
1635     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1636 };
1637
1638 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1639     plan tests => 13;
1640     my $biblio = $builder->build_sample_biblio();
1641     my $item_1 = $builder->build_sample_item(
1642         {
1643             biblionumber     => $biblio->biblionumber,
1644             library          => $library2->{branchcode},
1645         }
1646     );
1647     my $item_2= $builder->build_sample_item(
1648         {
1649             biblionumber     => $biblio->biblionumber,
1650             library          => $library2->{branchcode},
1651             itype            => $item_1->effective_itemtype,
1652         }
1653     );
1654
1655     Koha::CirculationRules->set_rules(
1656         {
1657             categorycode => undef,
1658             itemtype     => $item_1->effective_itemtype,
1659             branchcode   => undef,
1660             rules        => {
1661                 reservesallowed => 25,
1662                 holds_per_record => 25,
1663                 issuelength     => 14,
1664                 lengthunit      => 'days',
1665                 renewalsallowed => 1,
1666                 renewalperiod   => 7,
1667                 norenewalbefore => undef,
1668                 auto_renew      => 0,
1669                 fine            => .10,
1670                 chargeperiod    => 1,
1671                 maxissueqty     => 20
1672             }
1673         }
1674     );
1675
1676
1677     my $borrowernumber1 = Koha::Patron->new({
1678         firstname    => 'Kyle',
1679         surname      => 'Hall',
1680         categorycode => $patron_category->{categorycode},
1681         branchcode   => $library2->{branchcode},
1682     })->store->borrowernumber;
1683     my $borrowernumber2 = Koha::Patron->new({
1684         firstname    => 'Chelsea',
1685         surname      => 'Hall',
1686         categorycode => $patron_category->{categorycode},
1687         branchcode   => $library2->{branchcode},
1688     })->store->borrowernumber;
1689     my $patron_category_2 = $builder->build(
1690         {
1691             source => 'Category',
1692             value  => {
1693                 category_type                 => 'P',
1694                 enrolmentfee                  => 0,
1695                 BlockExpiredPatronOpacActions => -1, # Pick the pref value
1696             }
1697         }
1698     );
1699     my $borrowernumber3 = Koha::Patron->new({
1700         firstname    => 'Carnegie',
1701         surname      => 'Hall',
1702         categorycode => $patron_category_2->{categorycode},
1703         branchcode   => $library2->{branchcode},
1704     })->store->borrowernumber;
1705
1706     my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1707     my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1708
1709     my $issue = AddIssue( $borrower1, $item_1->barcode );
1710
1711     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1712     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1713
1714     AddReserve(
1715         {
1716             branchcode     => $library2->{branchcode},
1717             borrowernumber => $borrowernumber2,
1718             biblionumber   => $biblio->biblionumber,
1719             priority       => 1,
1720         }
1721     );
1722
1723     Koha::CirculationRules->set_rules(
1724         {
1725             categorycode => undef,
1726             itemtype     => $item_1->effective_itemtype,
1727             branchcode   => undef,
1728             rules        => {
1729                 onshelfholds => 0,
1730             }
1731         }
1732     );
1733     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1734     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1735     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1736
1737     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1738     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1739     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1740
1741     Koha::CirculationRules->set_rules(
1742         {
1743             categorycode => undef,
1744             itemtype     => $item_1->effective_itemtype,
1745             branchcode   => undef,
1746             rules        => {
1747                 onshelfholds => 1,
1748             }
1749         }
1750     );
1751     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1752     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1753     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1754
1755     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1756     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1757     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1758
1759     AddReserve(
1760         {
1761             branchcode     => $library2->{branchcode},
1762             borrowernumber => $borrowernumber3,
1763             biblionumber   => $biblio->biblionumber,
1764             priority       => 1,
1765         }
1766     );
1767
1768     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1769     is( $renewokay, 0, 'Verify the borrower cannot renew with 2 holds on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled and one other item on record' );
1770
1771     my $item_3= $builder->build_sample_item(
1772         {
1773             biblionumber     => $biblio->biblionumber,
1774             library          => $library2->{branchcode},
1775             itype            => $item_1->effective_itemtype,
1776         }
1777     );
1778
1779     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1780     is( $renewokay, 1, 'Verify the borrower cannot renew with 2 holds on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled and two other items on record' );
1781
1782     Koha::CirculationRules->set_rules(
1783         {
1784             categorycode => $patron_category_2->{categorycode},
1785             itemtype     => $item_1->effective_itemtype,
1786             branchcode   => undef,
1787             rules        => {
1788                 reservesallowed => 0,
1789             }
1790         }
1791     );
1792
1793     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1794     is( $renewokay, 0, 'Verify the borrower cannot renew with 2 holds on the record, but only one of those holds can be filled when AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled and two other items on record' );
1795
1796     Koha::CirculationRules->set_rules(
1797         {
1798             categorycode => $patron_category_2->{categorycode},
1799             itemtype     => $item_1->effective_itemtype,
1800             branchcode   => undef,
1801             rules        => {
1802                 reservesallowed => 25,
1803             }
1804         }
1805     );
1806
1807     # Setting item not checked out to be not for loan but holdable
1808     $item_2->notforloan(-1)->store;
1809
1810     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1811     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' );
1812
1813     my $mock_circ = Test::MockModule->new("C4::Circulation");
1814     $mock_circ->mock( CanItemBeReserved => sub {
1815         warn "Checked";
1816         return { status => 'no' }
1817     } );
1818
1819     $item_2->notforloan(0)->store;
1820     $item_3->delete();
1821     # Two items total, one item available, one issued, two holds on record
1822
1823     warnings_are{
1824        ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1825     } [], "CanItemBeReserved not called when there are more possible holds than available items";
1826     is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1827
1828     $item_3 = $builder->build_sample_item(
1829         {
1830             biblionumber     => $biblio->biblionumber,
1831             library          => $library2->{branchcode},
1832             itype            => $item_1->effective_itemtype,
1833         }
1834     );
1835
1836     Koha::CirculationRules->set_rules(
1837         {
1838             categorycode => undef,
1839             itemtype     => $item_1->effective_itemtype,
1840             branchcode   => undef,
1841             rules        => {
1842                 reservesallowed => 0,
1843             }
1844         }
1845     );
1846
1847     warnings_are{
1848        ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1849     } ["Checked","Checked"], "CanItemBeReserved only called once per available item if it returns a negative result for all items for a borrower";
1850     is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1851
1852 };
1853
1854 {
1855     # Don't allow renewing onsite checkout
1856     my $branch   = $library->{branchcode};
1857
1858     #Create another record
1859     my $biblio = $builder->build_sample_biblio();
1860
1861     my $item = $builder->build_sample_item(
1862         {
1863             biblionumber     => $biblio->biblionumber,
1864             library          => $branch,
1865             itype            => $itemtype,
1866         }
1867     );
1868
1869     my $borrowernumber = Koha::Patron->new({
1870         firstname =>  'fn',
1871         surname => 'dn',
1872         categorycode => $patron_category->{categorycode},
1873         branchcode => $branch,
1874     })->store->borrowernumber;
1875
1876     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1877
1878     my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1879     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1880     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1881     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1882 }
1883
1884 {
1885     my $library = $builder->build({ source => 'Branch' });
1886
1887     my $biblio = $builder->build_sample_biblio();
1888
1889     my $item = $builder->build_sample_item(
1890         {
1891             biblionumber     => $biblio->biblionumber,
1892             library          => $library->{branchcode},
1893             itype            => $itemtype,
1894         }
1895     );
1896
1897     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1898
1899     my $issue = AddIssue( $patron, $item->barcode );
1900     UpdateFine(
1901         {
1902             issue_id       => $issue->id(),
1903             itemnumber     => $item->itemnumber,
1904             borrowernumber => $patron->{borrowernumber},
1905             amount         => 1,
1906             type           => q{}
1907         }
1908     );
1909     UpdateFine(
1910         {
1911             issue_id       => $issue->id(),
1912             itemnumber     => $item->itemnumber,
1913             borrowernumber => $patron->{borrowernumber},
1914             amount         => 2,
1915             type           => q{}
1916         }
1917     );
1918     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1919 }
1920
1921 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1922     plan tests => 24;
1923
1924     my $homebranch    = $builder->build( { source => 'Branch' } );
1925     my $holdingbranch = $builder->build( { source => 'Branch' } );
1926     my $otherbranch   = $builder->build( { source => 'Branch' } );
1927     my $patron_1      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1928     my $patron_2      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1929
1930     my $item = $builder->build_sample_item(
1931         {
1932             homebranch    => $homebranch->{branchcode},
1933             holdingbranch => $holdingbranch->{branchcode},
1934         }
1935     );
1936     Koha::CirculationRules->set_rules(
1937         {
1938             categorycode => undef,
1939             itemtype     => $item->effective_itemtype,
1940             branchcode   => undef,
1941             rules        => {
1942                 reservesallowed => 25,
1943                 issuelength     => 14,
1944                 lengthunit      => 'days',
1945                 renewalsallowed => 1,
1946                 renewalperiod   => 7,
1947                 norenewalbefore => undef,
1948                 auto_renew      => 0,
1949                 fine            => .10,
1950                 chargeperiod    => 1,
1951                 maxissueqty     => 20
1952             }
1953         }
1954     );
1955
1956     set_userenv($holdingbranch);
1957
1958     my $issue = AddIssue( $patron_1->unblessed, $item->barcode );
1959     is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1960
1961     my ( $error, $question, $alerts );
1962
1963     # AllowReturnToBranch == anywhere
1964     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1965     ## Test that unknown barcodes don't generate internal server errors
1966     set_userenv($homebranch);
1967     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1968     ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1969     ## Can be issued from homebranch
1970     set_userenv($homebranch);
1971     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1972     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1973     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1974     ## Can be issued from holdingbranch
1975     set_userenv($holdingbranch);
1976     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1977     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1978     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1979     ## Can be issued from another branch
1980     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1981     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1982     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1983
1984     # AllowReturnToBranch == holdingbranch
1985     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1986     ## Cannot be issued from homebranch
1987     set_userenv($homebranch);
1988     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1989     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1990     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1991     is( $error->{branch_to_return},         $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1992     ## Can be issued from holdinbranch
1993     set_userenv($holdingbranch);
1994     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1995     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1996     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1997     ## Cannot be issued from another branch
1998     set_userenv($otherbranch);
1999     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2000     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2001     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2002     is( $error->{branch_to_return},         $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
2003
2004     # AllowReturnToBranch == homebranch
2005     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2006     ## Can be issued from holdinbranch
2007     set_userenv($homebranch);
2008     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2009     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2010     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2011     ## Cannot be issued from holdinbranch
2012     set_userenv($holdingbranch);
2013     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2014     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2015     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2016     is( $error->{branch_to_return},         $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2017     ## Cannot be issued from holdinbranch
2018     set_userenv($otherbranch);
2019     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2020     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2021     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2022     is( $error->{branch_to_return},         $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2023
2024     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2025 };
2026
2027 subtest 'AddIssue & AllowReturnToBranch' => sub {
2028     plan tests => 9;
2029
2030     my $homebranch    = $builder->build( { source => 'Branch' } );
2031     my $holdingbranch = $builder->build( { source => 'Branch' } );
2032     my $otherbranch   = $builder->build( { source => 'Branch' } );
2033     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2034     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2035
2036     my $item = $builder->build_sample_item(
2037         {
2038             homebranch    => $homebranch->{branchcode},
2039             holdingbranch => $holdingbranch->{branchcode},
2040         }
2041     );
2042
2043     set_userenv($holdingbranch);
2044
2045     my $ref_issue = 'Koha::Checkout';
2046     my $issue = AddIssue( $patron_1, $item->barcode );
2047
2048     my ( $error, $question, $alerts );
2049
2050     # AllowReturnToBranch == homebranch
2051     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2052     ## Can be issued from homebranch
2053     set_userenv($homebranch);
2054     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
2055     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2056     ## Can be issued from holdinbranch
2057     set_userenv($holdingbranch);
2058     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
2059     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2060     ## Can be issued from another branch
2061     set_userenv($otherbranch);
2062     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
2063     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2064
2065     # AllowReturnToBranch == holdinbranch
2066     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2067     ## Cannot be issued from homebranch
2068     set_userenv($homebranch);
2069     is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
2070     ## Can be issued from holdingbranch
2071     set_userenv($holdingbranch);
2072     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
2073     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2074     ## Cannot be issued from another branch
2075     set_userenv($otherbranch);
2076     is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
2077
2078     # AllowReturnToBranch == homebranch
2079     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2080     ## Can be issued from homebranch
2081     set_userenv($homebranch);
2082     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
2083     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2084     ## Cannot be issued from holdinbranch
2085     set_userenv($holdingbranch);
2086     is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
2087     ## Cannot be issued from another branch
2088     set_userenv($otherbranch);
2089     is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
2090     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2091 };
2092
2093 subtest 'AddIssue | recalls' => sub {
2094     plan tests => 3;
2095
2096     t::lib::Mocks::mock_preference("UseRecalls", 1);
2097     t::lib::Mocks::mock_preference("item-level_itypes", 1);
2098     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2099     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2100     my $item = $builder->build_sample_item;
2101     Koha::CirculationRules->set_rules({
2102         branchcode => undef,
2103         itemtype => undef,
2104         categorycode => undef,
2105         rules => {
2106             recalls_allowed => 10,
2107         },
2108     });
2109
2110     # checking out item that they have recalled
2111     my $recall1 = Koha::Recall->new(
2112         {   patron_id         => $patron1->borrowernumber,
2113             biblio_id         => $item->biblionumber,
2114             item_id           => $item->itemnumber,
2115             item_level        => 1,
2116             pickup_library_id => $patron1->branchcode,
2117         }
2118     )->store;
2119     AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall1->id } );
2120     $recall1 = Koha::Recalls->find( $recall1->id );
2121     is( $recall1->fulfilled, 1, 'Recall was fulfilled when patron checked out item' );
2122     AddReturn( $item->barcode, $item->homebranch );
2123
2124     # this item is has a recall request. cancel recall
2125     my $recall2 = Koha::Recall->new(
2126         {   patron_id         => $patron2->borrowernumber,
2127             biblio_id         => $item->biblionumber,
2128             item_id           => $item->itemnumber,
2129             item_level        => 1,
2130             pickup_library_id => $patron2->branchcode,
2131         }
2132     )->store;
2133     AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall2->id, cancel_recall => 'cancel' } );
2134     $recall2 = Koha::Recalls->find( $recall2->id );
2135     is( $recall2->cancelled, 1, 'Recall was cancelled when patron checked out item' );
2136     AddReturn( $item->barcode, $item->homebranch );
2137
2138     # this item is waiting to fulfill a recall. revert recall
2139     my $recall3 = Koha::Recall->new(
2140         {   patron_id         => $patron2->borrowernumber,
2141             biblio_id         => $item->biblionumber,
2142             item_id           => $item->itemnumber,
2143             item_level        => 1,
2144             pickup_library_id => $patron2->branchcode,
2145         }
2146     )->store;
2147     $recall3->set_waiting;
2148     AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall3->id, cancel_recall => 'revert' } );
2149     $recall3 = Koha::Recalls->find( $recall3->id );
2150     is( $recall3->requested, 1, 'Recall was reverted from waiting when patron checked out item' );
2151     AddReturn( $item->barcode, $item->homebranch );
2152 };
2153
2154 subtest 'AddIssue & illrequests.due_date' => sub {
2155     plan tests => 2;
2156
2157     t::lib::Mocks::mock_preference( 'ILLModule', 1 );
2158     my $library = $builder->build( { source => 'Branch' } );
2159     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2160     my $item = $builder->build_sample_item();
2161
2162     set_userenv($library);
2163
2164     my $custom_date_due = '9999-12-18 12:34:56';
2165     my $expected_date_due = '9999-12-18 23:59:00';
2166     my $illrequest = Koha::Illrequest->new({
2167         borrowernumber => $patron->borrowernumber,
2168         biblio_id => $item->biblionumber,
2169         branchcode => $library->{'branchcode'},
2170         due_date => $custom_date_due,
2171     })->store;
2172
2173     my $issue = AddIssue( $patron->unblessed, $item->barcode );
2174     is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2175
2176     $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2177     $item = $builder->build_sample_item();
2178     $custom_date_due = '9999-12-19';
2179     $expected_date_due = '9999-12-19 23:59:00';
2180     $illrequest = Koha::Illrequest->new({
2181         borrowernumber => $patron->borrowernumber,
2182         biblio_id => $item->biblionumber,
2183         branchcode => $library->{'branchcode'},
2184         due_date => $custom_date_due,
2185     })->store;
2186
2187     $issue = AddIssue( $patron->unblessed, $item->barcode );
2188     is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2189 };
2190
2191 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
2192     plan tests => 8;
2193
2194     my $library = $builder->build( { source => 'Branch' } );
2195     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2196     my $item_1 = $builder->build_sample_item(
2197         {
2198             library => $library->{branchcode},
2199         }
2200     );
2201     my $item_2 = $builder->build_sample_item(
2202         {
2203             library => $library->{branchcode},
2204         }
2205     );
2206     Koha::CirculationRules->set_rules(
2207         {
2208             categorycode => undef,
2209             itemtype     => undef,
2210             branchcode   => $library->{branchcode},
2211             rules        => {
2212                 reservesallowed => 25,
2213                 issuelength     => 14,
2214                 lengthunit      => 'days',
2215                 renewalsallowed => 1,
2216                 renewalperiod   => 7,
2217                 norenewalbefore => undef,
2218                 auto_renew      => 0,
2219                 fine            => .10,
2220                 chargeperiod    => 1,
2221                 maxissueqty     => 20
2222             }
2223         }
2224     );
2225
2226
2227     my ( $error, $question, $alerts );
2228
2229     # Patron cannot issue item_1, they have overdues
2230     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
2231     my $issue = AddIssue( $patron->unblessed, $item_1->barcode, $yesterday );    # Add an overdue
2232
2233     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
2234     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2235     is( keys(%$error) + keys(%$alerts),  0, 'No key for error and alert' . str($error, $question, $alerts) );
2236     is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
2237
2238     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
2239     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2240     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
2241     is( $error->{USERBLOCKEDOVERDUE},      1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
2242
2243     # Patron cannot issue item_1, they are debarred
2244     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
2245     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
2246     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2247     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
2248     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
2249
2250     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
2251     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2252     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
2253     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
2254 };
2255
2256 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
2257     plan tests => 1;
2258
2259     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2260     my $patron_category_x = $builder->build_object(
2261         {
2262             class => 'Koha::Patron::Categories',
2263             value => { category_type => 'X' }
2264         }
2265     );
2266     my $patron = $builder->build_object(
2267         {
2268             class => 'Koha::Patrons',
2269             value => {
2270                 categorycode  => $patron_category_x->categorycode,
2271                 gonenoaddress => undef,
2272                 lost          => undef,
2273                 debarred      => undef,
2274                 borrowernotes => ""
2275             }
2276         }
2277     );
2278     my $item_1 = $builder->build_sample_item(
2279         {
2280             library => $library->{branchcode},
2281         }
2282     );
2283
2284     my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
2285     is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
2286
2287     # TODO There are other tests to provide here
2288 };
2289
2290 subtest 'MultipleReserves' => sub {
2291     plan tests => 3;
2292
2293     my $biblio = $builder->build_sample_biblio();
2294
2295     my $branch = $library2->{branchcode};
2296
2297     my $item_1 = $builder->build_sample_item(
2298         {
2299             biblionumber     => $biblio->biblionumber,
2300             library          => $branch,
2301             replacementprice => 12.00,
2302             itype            => $itemtype,
2303         }
2304     );
2305
2306     my $item_2 = $builder->build_sample_item(
2307         {
2308             biblionumber     => $biblio->biblionumber,
2309             library          => $branch,
2310             replacementprice => 12.00,
2311             itype            => $itemtype,
2312         }
2313     );
2314
2315     my $bibitems       = '';
2316     my $priority       = '1';
2317     my $resdate        = undef;
2318     my $expdate        = undef;
2319     my $notes          = '';
2320     my $checkitem      = undef;
2321     my $found          = undef;
2322
2323     my %renewing_borrower_data = (
2324         firstname =>  'John',
2325         surname => 'Renewal',
2326         categorycode => $patron_category->{categorycode},
2327         branchcode => $branch,
2328     );
2329     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
2330     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
2331     my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
2332     my $datedue = dt_from_string( $issue->date_due() );
2333     is (defined $issue->date_due(), 1, "item 1 checked out");
2334     my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
2335
2336     my %reserving_borrower_data1 = (
2337         firstname =>  'Katrin',
2338         surname => 'Reservation',
2339         categorycode => $patron_category->{categorycode},
2340         branchcode => $branch,
2341     );
2342     my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
2343     AddReserve(
2344         {
2345             branchcode       => $branch,
2346             borrowernumber   => $reserving_borrowernumber1,
2347             biblionumber     => $biblio->biblionumber,
2348             priority         => $priority,
2349             reservation_date => $resdate,
2350             expiration_date  => $expdate,
2351             notes            => $notes,
2352             itemnumber       => $checkitem,
2353             found            => $found,
2354         }
2355     );
2356
2357     my %reserving_borrower_data2 = (
2358         firstname =>  'Kirk',
2359         surname => 'Reservation',
2360         categorycode => $patron_category->{categorycode},
2361         branchcode => $branch,
2362     );
2363     my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
2364     AddReserve(
2365         {
2366             branchcode       => $branch,
2367             borrowernumber   => $reserving_borrowernumber2,
2368             biblionumber     => $biblio->biblionumber,
2369             priority         => $priority,
2370             reservation_date => $resdate,
2371             expiration_date  => $expdate,
2372             notes            => $notes,
2373             itemnumber       => $checkitem,
2374             found            => $found,
2375         }
2376     );
2377
2378     {
2379         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2380         is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2381     }
2382
2383     my $item_3 = $builder->build_sample_item(
2384         {
2385             biblionumber     => $biblio->biblionumber,
2386             library          => $branch,
2387             replacementprice => 12.00,
2388             itype            => $itemtype,
2389         }
2390     );
2391
2392     {
2393         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2394         is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2395     }
2396 };
2397
2398 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2399     plan tests => 5;
2400
2401     my $library = $builder->build( { source => 'Branch' } );
2402     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2403
2404     my $biblionumber = $builder->build_sample_biblio(
2405         {
2406             branchcode => $library->{branchcode},
2407         }
2408     )->biblionumber;
2409     my $item_1 = $builder->build_sample_item(
2410         {
2411             biblionumber => $biblionumber,
2412             library      => $library->{branchcode},
2413         }
2414     );
2415
2416     my $item_2 = $builder->build_sample_item(
2417         {
2418             biblionumber => $biblionumber,
2419             library      => $library->{branchcode},
2420         }
2421     );
2422
2423     Koha::CirculationRules->set_rules(
2424         {
2425             categorycode => undef,
2426             itemtype     => undef,
2427             branchcode   => $library->{branchcode},
2428             rules        => {
2429                 reservesallowed => 25,
2430                 issuelength     => 14,
2431                 lengthunit      => 'days',
2432                 renewalsallowed => 1,
2433                 renewalperiod   => 7,
2434                 norenewalbefore => undef,
2435                 auto_renew      => 0,
2436                 fine            => .10,
2437                 chargeperiod    => 1,
2438                 maxissueqty     => 20
2439             }
2440         }
2441     );
2442
2443     my ( $error, $question, $alerts );
2444     my $issue = AddIssue( $patron->unblessed, $item_1->barcode, dt_from_string->add( days => 1 ) );
2445
2446     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2447     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2448     cmp_deeply(
2449         { error => $error, alerts => $alerts },
2450         { error => {}, alerts => {} },
2451         'No error or alert should be raised'
2452     );
2453     is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2454
2455     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2456     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2457     cmp_deeply(
2458         { error => $error, question => $question, alerts => $alerts },
2459         { error => {}, question => {}, alerts => {} },
2460         'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2461     );
2462
2463     # Add a subscription
2464     Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2465
2466     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2467     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2468     cmp_deeply(
2469         { error => $error, question => $question, alerts => $alerts },
2470         { error => {}, question => {}, alerts => {} },
2471         'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2472     );
2473
2474     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2475     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2476     cmp_deeply(
2477         { error => $error, question => $question, alerts => $alerts },
2478         { error => {}, question => {}, alerts => {} },
2479         'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2480     );
2481 };
2482
2483 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2484     plan tests => 8;
2485
2486     my $library = $builder->build( { source => 'Branch' } );
2487     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2488
2489     # Add 2 items
2490     my $biblionumber = $builder->build_sample_biblio(
2491         {
2492             branchcode => $library->{branchcode},
2493         }
2494     )->biblionumber;
2495     my $item_1 = $builder->build_sample_item(
2496         {
2497             biblionumber => $biblionumber,
2498             library      => $library->{branchcode},
2499         }
2500     );
2501     my $item_2 = $builder->build_sample_item(
2502         {
2503             biblionumber => $biblionumber,
2504             library      => $library->{branchcode},
2505         }
2506     );
2507
2508     # And the circulation rule
2509     Koha::CirculationRules->search->delete;
2510     Koha::CirculationRules->set_rules(
2511         {
2512             categorycode => undef,
2513             itemtype     => undef,
2514             branchcode   => undef,
2515             rules        => {
2516                 issuelength => 1,
2517                 firstremind => 1,        # 1 day of grace
2518                 finedays    => 2,        # 2 days of fine per day of overdue
2519                 lengthunit  => 'days',
2520             }
2521         }
2522     );
2523
2524     # Patron cannot issue item_1, they have overdues
2525     my $now = dt_from_string;
2526     my $five_days_ago = $now->clone->subtract( days => 5 );
2527     my $ten_days_ago  = $now->clone->subtract( days => 10 );
2528     AddIssue( $patron, $item_1->barcode, $five_days_ago );    # Add an overdue
2529     AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2530       ;    # Add another overdue
2531
2532     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2533     AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2534     my $debarments = Koha::Patron::Debarments::GetDebarments(
2535         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2536     is( scalar(@$debarments), 1 );
2537
2538     # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2539     # Same for the others
2540     my $expected_expiration = output_pref(
2541         {
2542             dt         => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2543             dateformat => 'sql',
2544             dateonly   => 1
2545         }
2546     );
2547     is( $debarments->[0]->{expiration}, $expected_expiration );
2548
2549     AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2550     $debarments = Koha::Patron::Debarments::GetDebarments(
2551         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2552     is( scalar(@$debarments), 1 );
2553     $expected_expiration = output_pref(
2554         {
2555             dt         => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2556             dateformat => 'sql',
2557             dateonly   => 1
2558         }
2559     );
2560     is( $debarments->[0]->{expiration}, $expected_expiration );
2561
2562     Koha::Patron::Debarments::DelUniqueDebarment(
2563         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2564
2565     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2566     AddIssue( $patron, $item_1->barcode, $five_days_ago );    # Add an overdue
2567     AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2568       ;    # Add another overdue
2569     AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2570     $debarments = Koha::Patron::Debarments::GetDebarments(
2571         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2572     is( scalar(@$debarments), 1 );
2573     $expected_expiration = output_pref(
2574         {
2575             dt         => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2576             dateformat => 'sql',
2577             dateonly   => 1
2578         }
2579     );
2580     is( $debarments->[0]->{expiration}, $expected_expiration );
2581
2582     AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2583     $debarments = Koha::Patron::Debarments::GetDebarments(
2584         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2585     is( scalar(@$debarments), 1 );
2586     $expected_expiration = output_pref(
2587         {
2588             dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2589             dateformat => 'sql',
2590             dateonly   => 1
2591         }
2592     );
2593     is( $debarments->[0]->{expiration}, $expected_expiration );
2594 };
2595
2596 subtest 'AddReturn + suspension_chargeperiod' => sub {
2597     plan tests => 27;
2598
2599     my $library = $builder->build( { source => 'Branch' } );
2600     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2601
2602     my $biblionumber = $builder->build_sample_biblio(
2603         {
2604             branchcode => $library->{branchcode},
2605         }
2606     )->biblionumber;
2607     my $item_1 = $builder->build_sample_item(
2608         {
2609             biblionumber => $biblionumber,
2610             library      => $library->{branchcode},
2611         }
2612     );
2613
2614     # And the issuing rule
2615     Koha::CirculationRules->search->delete;
2616     Koha::CirculationRules->set_rules(
2617         {
2618             categorycode => '*',
2619             itemtype     => '*',
2620             branchcode   => '*',
2621             rules        => {
2622                 issuelength => 1,
2623                 firstremind => 0,    # 0 day of grace
2624                 finedays    => 2,    # 2 days of fine per day of overdue
2625                 suspension_chargeperiod => 1,
2626                 lengthunit              => 'days',
2627             }
2628         }
2629     );
2630
2631     my $now = dt_from_string;
2632     my $five_days_ago = $now->clone->subtract( days => 5 );
2633     # We want to charge 2 days every day, without grace
2634     # With 5 days of overdue: 5 * Z
2635     my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2636     test_debarment_on_checkout(
2637         {
2638             item            => $item_1,
2639             library         => $library,
2640             patron          => $patron,
2641             due_date        => $five_days_ago,
2642             expiration_date => $expected_expiration,
2643         }
2644     );
2645
2646     # Same with undef firstremind
2647     Koha::CirculationRules->search->delete;
2648     Koha::CirculationRules->set_rules(
2649         {
2650             categorycode => '*',
2651             itemtype     => '*',
2652             branchcode   => '*',
2653             rules        => {
2654                 issuelength => 1,
2655                 firstremind => undef,    # 0 day of grace
2656                 finedays    => 2,    # 2 days of fine per day of overdue
2657                 suspension_chargeperiod => 1,
2658                 lengthunit              => 'days',
2659             }
2660         }
2661     );
2662     {
2663     my $now = dt_from_string;
2664     my $five_days_ago = $now->clone->subtract( days => 5 );
2665     # We want to charge 2 days every day, without grace
2666     # With 5 days of overdue: 5 * Z
2667     my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2668     test_debarment_on_checkout(
2669         {
2670             item            => $item_1,
2671             library         => $library,
2672             patron          => $patron,
2673             due_date        => $five_days_ago,
2674             expiration_date => $expected_expiration,
2675         }
2676     );
2677     }
2678     # We want to charge 2 days every 2 days, without grace
2679     # With 5 days of overdue: (5 * 2) / 2
2680     Koha::CirculationRules->set_rule(
2681         {
2682             categorycode => undef,
2683             branchcode   => undef,
2684             itemtype     => undef,
2685             rule_name    => 'suspension_chargeperiod',
2686             rule_value   => '2',
2687         }
2688     );
2689
2690     $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2691     test_debarment_on_checkout(
2692         {
2693             item            => $item_1,
2694             library         => $library,
2695             patron          => $patron,
2696             due_date        => $five_days_ago,
2697             expiration_date => $expected_expiration,
2698         }
2699     );
2700
2701     # We want to charge 2 days every 3 days, with 1 day of grace
2702     # With 5 days of overdue: ((5-1) / 3 ) * 2
2703     Koha::CirculationRules->set_rules(
2704         {
2705             categorycode => undef,
2706             branchcode   => undef,
2707             itemtype     => undef,
2708             rules        => {
2709                 suspension_chargeperiod => 3,
2710                 firstremind             => 1,
2711             }
2712         }
2713     );
2714     $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2715     test_debarment_on_checkout(
2716         {
2717             item            => $item_1,
2718             library         => $library,
2719             patron          => $patron,
2720             due_date        => $five_days_ago,
2721             expiration_date => $expected_expiration,
2722         }
2723     );
2724
2725     # Use finesCalendar to know if holiday must be skipped to calculate the due date
2726     # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2727     Koha::CirculationRules->set_rules(
2728         {
2729             categorycode => undef,
2730             branchcode   => undef,
2731             itemtype     => undef,
2732             rules        => {
2733                 finedays                => 2,
2734                 suspension_chargeperiod => 1,
2735                 firstremind             => 0,
2736             }
2737         }
2738     );
2739     t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2740     t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2741
2742     # Adding a holiday 2 days ago
2743     my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2744     my $two_days_ago = $now->clone->subtract( days => 2 );
2745     $calendar->insert_single_holiday(
2746         day             => $two_days_ago->day,
2747         month           => $two_days_ago->month,
2748         year            => $two_days_ago->year,
2749         title           => 'holidayTest-2d',
2750         description     => 'holidayDesc 2 days ago'
2751     );
2752     # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2753     $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2754     test_debarment_on_checkout(
2755         {
2756             item            => $item_1,
2757             library         => $library,
2758             patron          => $patron,
2759             due_date        => $five_days_ago,
2760             expiration_date => $expected_expiration,
2761         }
2762     );
2763
2764     # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2765     my $two_days_ahead = $now->clone->add( days => 2 );
2766     $calendar->insert_single_holiday(
2767         day             => $two_days_ahead->day,
2768         month           => $two_days_ahead->month,
2769         year            => $two_days_ahead->year,
2770         title           => 'holidayTest+2d',
2771         description     => 'holidayDesc 2 days ahead'
2772     );
2773
2774     # Same as above, but we should skip D+2
2775     $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2776     test_debarment_on_checkout(
2777         {
2778             item            => $item_1,
2779             library         => $library,
2780             patron          => $patron,
2781             due_date        => $five_days_ago,
2782             expiration_date => $expected_expiration,
2783         }
2784     );
2785
2786     # Adding another holiday, day of expiration date
2787     my $expected_expiration_dt = dt_from_string($expected_expiration);
2788     $calendar->insert_single_holiday(
2789         day             => $expected_expiration_dt->day,
2790         month           => $expected_expiration_dt->month,
2791         year            => $expected_expiration_dt->year,
2792         title           => 'holidayTest_exp',
2793         description     => 'holidayDesc on expiration date'
2794     );
2795     # Expiration date will be the day after
2796     test_debarment_on_checkout(
2797         {
2798             item            => $item_1,
2799             library         => $library,
2800             patron          => $patron,
2801             due_date        => $five_days_ago,
2802             expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2803         }
2804     );
2805
2806     test_debarment_on_checkout(
2807         {
2808             item            => $item_1,
2809             library         => $library,
2810             patron          => $patron,
2811             return_date     => $now->clone->add(days => 5),
2812             expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2813         }
2814     );
2815
2816     test_debarment_on_checkout(
2817         {
2818             item            => $item_1,
2819             library         => $library,
2820             patron          => $patron,
2821             due_date        => $now->clone->add(days => 1),
2822             return_date     => $now->clone->add(days => 5),
2823             expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2824         }
2825     );
2826
2827 };
2828
2829 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2830     plan tests => 2;
2831
2832     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2833     my $patron1 = $builder->build_object(
2834         {
2835             class => 'Koha::Patrons',
2836             value => {
2837                 library      => $library->branchcode,
2838                 categorycode => $patron_category->{categorycode}
2839             }
2840         }
2841     );
2842     my $patron2 = $builder->build_object(
2843         {
2844             class => 'Koha::Patrons',
2845             value => {
2846                 library      => $library->branchcode,
2847                 categorycode => $patron_category->{categorycode}
2848             }
2849         }
2850     );
2851
2852     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2853
2854     my $item = $builder->build_sample_item(
2855         {
2856             library      => $library->branchcode,
2857         }
2858     );
2859
2860     my ( $error, $question, $alerts );
2861     my $issue = AddIssue( $patron1->unblessed, $item->barcode );
2862
2863     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2864     ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2865     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' );
2866
2867     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2868     ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2869     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' );
2870
2871     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2872 };
2873
2874
2875 subtest 'AddReturn | is_overdue' => sub {
2876     plan tests => 9;
2877
2878     t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2879     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2880     t::lib::Mocks::mock_preference('finesMode', 'production');
2881     t::lib::Mocks::mock_preference('MaxFine', '100');
2882
2883     my $library = $builder->build( { source => 'Branch' } );
2884     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2885     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2886     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2887
2888     my $item = $builder->build_sample_item(
2889         {
2890             library      => $library->{branchcode},
2891             replacementprice => 7
2892         }
2893     );
2894
2895     Koha::CirculationRules->search->delete;
2896     Koha::CirculationRules->set_rules(
2897         {
2898             categorycode => undef,
2899             itemtype     => undef,
2900             branchcode   => undef,
2901             rules        => {
2902                 issuelength  => 6,
2903                 lengthunit   => 'days',
2904                 fine         => 1,        # Charge 1 every day of overdue
2905                 chargeperiod => 1,
2906             }
2907         }
2908     );
2909
2910     my $now   = dt_from_string;
2911     my $one_day_ago   = $now->clone->subtract( days => 1 );
2912     my $two_days_ago  = $now->clone->subtract( days => 2 );
2913     my $five_days_ago = $now->clone->subtract( days => 5 );
2914     my $ten_days_ago  = $now->clone->subtract( days => 10 );
2915     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2916
2917     # No return date specified, today will be used => 10 days overdue charged
2918     AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2919     AddReturn( $item->barcode, $library->{branchcode} );
2920     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2921     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2922
2923     # specify return date 5 days before => no overdue charged
2924     AddIssue( $patron->unblessed, $item->barcode, $five_days_ago ); # date due was 5d ago
2925     AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
2926     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2927     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2928
2929     # specify return date 5 days later => 5 days overdue charged
2930     AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2931     AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
2932     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2933     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2934
2935     # specify return date 5 days later, specify exemptfine => no overdue charge
2936     AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2937     AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago );
2938     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2939     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2940
2941     subtest 'bug 22877 | Lost item return' => sub {
2942
2943         plan tests => 3;
2944
2945         my $issue = AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );    # date due was 10d ago
2946
2947         # Fake fines cronjob on this checkout
2948         my ($fine) =
2949           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2950             $ten_days_ago, $now );
2951         UpdateFine(
2952             {
2953                 issue_id       => $issue->issue_id,
2954                 itemnumber     => $item->itemnumber,
2955                 borrowernumber => $patron->borrowernumber,
2956                 amount         => $fine,
2957                 due            => output_pref($ten_days_ago)
2958             }
2959         );
2960         is( int( $patron->account->balance() ),
2961             10, "Overdue fine of 10 days overdue" );
2962
2963         # Fake longoverdue with charge and not marking returned
2964         LostItem( $item->itemnumber, 'cronjob', 0 );
2965         is( int( $patron->account->balance() ),
2966             17, "Lost fine of 7 plus 10 days overdue" );
2967
2968         # Now we return it today
2969         AddReturn( $item->barcode, $library->{branchcode} );
2970         is( int( $patron->account->balance() ),
2971             17, "Should have a single 10 days overdue fine and lost charge" );
2972
2973         # Cleanup
2974         Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2975     };
2976
2977     subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
2978
2979         plan tests => 17;
2980
2981         t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2982
2983         my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago );    # date due was 1d ago
2984
2985         # Fake fines cronjob on this checkout
2986         my ($fine) =
2987           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2988             $one_day_ago, $now );
2989         UpdateFine(
2990             {
2991                 issue_id       => $issue->issue_id,
2992                 itemnumber     => $item->itemnumber,
2993                 borrowernumber => $patron->borrowernumber,
2994                 amount         => $fine,
2995                 due            => output_pref($one_day_ago)
2996             }
2997         );
2998         is( int( $patron->account->balance() ),
2999             1, "Overdue fine of 1 day overdue" );
3000
3001         # Backdated return (dropbox mode example - charge should be removed)
3002         AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3003         is( int( $patron->account->balance() ),
3004             0, "Overdue fine should be annulled" );
3005         my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3006         is( $lines->count, 0, "Overdue fine accountline has been removed");
3007
3008         $issue = AddIssue( $patron->unblessed, $item->barcode, $two_days_ago );    # date due was 2d ago
3009
3010         # Fake fines cronjob on this checkout
3011         ($fine) =
3012           CalcFine( $item, $patron->categorycode, $library->{branchcode},
3013             $two_days_ago, $now );
3014         UpdateFine(
3015             {
3016                 issue_id       => $issue->issue_id,
3017                 itemnumber     => $item->itemnumber,
3018                 borrowernumber => $patron->borrowernumber,
3019                 amount         => $fine,
3020                 due            => output_pref($one_day_ago)
3021             }
3022         );
3023         is( int( $patron->account->balance() ),
3024             2, "Overdue fine of 2 days overdue" );
3025
3026         # Payment made against fine
3027         $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3028         my $debit = $lines->next;
3029         my $credit = $patron->account->add_credit(
3030             {
3031                 amount    => 2,
3032                 type      => 'PAYMENT',
3033                 interface => 'test',
3034             }
3035         );
3036         $credit->apply( { debits => [$debit] } );
3037
3038         is( int( $patron->account->balance() ),
3039             0, "Overdue fine should be paid off" );
3040         $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3041         is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
3042         my $line = $lines->next;
3043         is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
3044         is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
3045
3046         # Backdated return (dropbox mode example - charge should be removed)
3047         AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
3048         is( int( $patron->account->balance() ),
3049             -1, "Refund credit has been applied" );
3050         $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
3051         is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
3052
3053         $line = $lines->next;
3054         is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
3055         is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
3056         is($line->status,'RETURNED', "Overdue fine is fixed");
3057         $line = $lines->next;
3058         is($line->amount+0,-2, "Original payment amount remains as 2");
3059         is($line->amountoutstanding+0,0, "Original payment remains applied");
3060         $line = $lines->next;
3061         is($line->amount+0,-1, "Refund amount correctly set to 1");
3062         is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
3063
3064         # Cleanup
3065         Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3066     };
3067
3068     subtest 'bug 25417 | backdated return + exemptfine' => sub {
3069
3070         plan tests => 2;
3071
3072         t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3073
3074         my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago );    # date due was 1d ago
3075
3076         # Fake fines cronjob on this checkout
3077         my ($fine) =
3078           CalcFine( $item, $patron->categorycode, $library->{branchcode},
3079             $one_day_ago, $now );
3080         UpdateFine(
3081             {
3082                 issue_id       => $issue->issue_id,
3083                 itemnumber     => $item->itemnumber,
3084                 borrowernumber => $patron->borrowernumber,
3085                 amount         => $fine,
3086                 due            => output_pref($one_day_ago)
3087             }
3088         );
3089         is( int( $patron->account->balance() ),
3090             1, "Overdue fine of 1 day overdue" );
3091
3092         # Backdated return (dropbox mode example - charge should no longer exist)
3093         AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3094         is( int( $patron->account->balance() ),
3095             0, "Overdue fine should be annulled" );
3096
3097         # Cleanup
3098         Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3099     };
3100
3101     subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
3102         plan tests => 7;
3103
3104         t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
3105
3106         my $due_date = dt_from_string;
3107         my $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
3108
3109         # Add fine
3110         UpdateFine(
3111             {
3112                 issue_id       => $issue->issue_id,
3113                 itemnumber     => $item->itemnumber,
3114                 borrowernumber => $patron->borrowernumber,
3115                 amount         => 0.25,
3116                 due            => output_pref($due_date)
3117             }
3118         );
3119         is( $patron->account->balance(),
3120             0.25, 'Overdue fine of $0.25 recorded' );
3121
3122         # Backdate return to exact due date and time
3123         my ( undef, $message ) =
3124           AddReturn( $item->barcode, $library->{branchcode},
3125             undef, $due_date );
3126
3127         my $accountline =
3128           Koha::Account::Lines->find( { issue_id => $issue->id } );
3129         ok( !$accountline, 'accountline removed as expected' );
3130
3131         # Re-issue
3132         $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
3133
3134         # Add fine
3135         UpdateFine(
3136             {
3137                 issue_id       => $issue->issue_id,
3138                 itemnumber     => $item->itemnumber,
3139                 borrowernumber => $patron->borrowernumber,
3140                 amount         => .25,
3141                 due            => output_pref($due_date)
3142             }
3143         );
3144         is( $patron->account->balance(),
3145             0.25, 'Overdue fine of $0.25 recorded' );
3146
3147         # Partial pay accruing fine
3148         my $lines = Koha::Account::Lines->search(
3149             {
3150                 borrowernumber => $patron->borrowernumber,
3151                 issue_id       => $issue->id
3152             }
3153         );
3154         my $debit  = $lines->next;
3155         my $credit = $patron->account->add_credit(
3156             {
3157                 amount    => .20,
3158                 type      => 'PAYMENT',
3159                 interface => 'test',
3160             }
3161         );
3162         $credit->apply( { debits => [$debit] } );
3163
3164         is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
3165
3166         # Backdate return to exact due date and time
3167         ( undef, $message ) =
3168           AddReturn( $item->barcode, $library->{branchcode},
3169             undef, $due_date );
3170
3171         $lines = Koha::Account::Lines->search(
3172             {
3173                 borrowernumber => $patron->borrowernumber,
3174                 issue_id       => $issue->id
3175             }
3176         );
3177         $accountline = $lines->next;
3178         is( $accountline->amountoutstanding + 0,
3179             0, 'Partially paid fee amount outstanding was reduced to 0' );
3180         is( $accountline->amount + 0,
3181             0, 'Partially paid fee amount was reduced to 0' );
3182         is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
3183
3184         # Cleanup
3185         Koha::Account::Lines->search(
3186             { borrowernumber => $patron->borrowernumber } )->delete;
3187     };
3188
3189     subtest 'enh 23091 | Lost item return policies' => sub {
3190         plan tests => 4;
3191
3192         my $manager = $builder->build_object({ class => "Koha::Patrons" });
3193
3194         my $branchcode_false =
3195           $builder->build( { source => 'Branch' } )->{branchcode};
3196         my $specific_rule_false = $builder->build(
3197             {
3198                 source => 'CirculationRule',
3199                 value  => {
3200                     branchcode   => $branchcode_false,
3201                     categorycode => undef,
3202                     itemtype     => undef,
3203                     rule_name    => 'lostreturn',
3204                     rule_value   => 0
3205                 }
3206             }
3207         );
3208         my $branchcode_refund =
3209           $builder->build( { source => 'Branch' } )->{branchcode};
3210         my $specific_rule_refund = $builder->build(
3211             {
3212                 source => 'CirculationRule',
3213                 value  => {
3214                     branchcode   => $branchcode_refund,
3215                     categorycode => undef,
3216                     itemtype     => undef,
3217                     rule_name    => 'lostreturn',
3218                     rule_value   => 'refund'
3219                 }
3220             }
3221         );
3222         my $branchcode_restore =
3223           $builder->build( { source => 'Branch' } )->{branchcode};
3224         my $specific_rule_restore = $builder->build(
3225             {
3226                 source => 'CirculationRule',
3227                 value  => {
3228                     branchcode   => $branchcode_restore,
3229                     categorycode => undef,
3230                     itemtype     => undef,
3231                     rule_name    => 'lostreturn',
3232                     rule_value   => 'restore'
3233                 }
3234             }
3235         );
3236         my $branchcode_charge =
3237           $builder->build( { source => 'Branch' } )->{branchcode};
3238         my $specific_rule_charge = $builder->build(
3239             {
3240                 source => 'CirculationRule',
3241                 value  => {
3242                     branchcode   => $branchcode_charge,
3243                     categorycode => undef,
3244                     itemtype     => undef,
3245                     rule_name    => 'lostreturn',
3246                     rule_value   => 'charge'
3247                 }
3248             }
3249         );
3250
3251         my $replacement_amount = 99.00;
3252         t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
3253         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
3254         t::lib::Mocks::mock_preference( 'WhenLostForgiveFine',          0 );
3255         t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems',       0 );
3256         t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
3257             'CheckinLibrary' );
3258         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
3259             undef );
3260
3261         subtest 'lostreturn | false' => sub {
3262             plan tests => 12;
3263
3264             t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
3265
3266             my $item = $builder->build_sample_item(
3267                 {
3268                     replacementprice => $replacement_amount
3269                 }
3270             );
3271
3272             # Issue the item
3273             my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3274
3275             # Fake fines cronjob on this checkout
3276             my ($fine) =
3277               CalcFine( $item, $patron->categorycode, $library->{branchcode},
3278                 $ten_days_ago, $now );
3279             UpdateFine(
3280                 {
3281                     issue_id       => $issue->issue_id,
3282                     itemnumber     => $item->itemnumber,
3283                     borrowernumber => $patron->borrowernumber,
3284                     amount         => $fine,
3285                     due            => output_pref($ten_days_ago)
3286                 }
3287             );
3288             my $overdue_fees = Koha::Account::Lines->search(
3289                 {
3290                     borrowernumber  => $patron->id,
3291                     itemnumber      => $item->itemnumber,
3292                     debit_type_code => 'OVERDUE'
3293                 }
3294             );
3295             is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3296             my $overdue_fee = $overdue_fees->next;
3297             is( $overdue_fee->amount + 0,
3298                 10, 'The right OVERDUE amount is generated' );
3299             is( $overdue_fee->amountoutstanding + 0,
3300                 10,
3301                 'The right OVERDUE amountoutstanding is generated' );
3302
3303             # Simulate item marked as lost
3304             $item->itemlost(3)->store;
3305             C4::Circulation::LostItem( $item->itemnumber, 1 );
3306
3307             my $lost_fee_lines = Koha::Account::Lines->search(
3308                 {
3309                     borrowernumber  => $patron->id,
3310                     itemnumber      => $item->itemnumber,
3311                     debit_type_code => 'LOST'
3312                 }
3313             );
3314             is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3315             my $lost_fee_line = $lost_fee_lines->next;
3316             is( $lost_fee_line->amount + 0,
3317                 $replacement_amount, 'The right LOST amount is generated' );
3318             is( $lost_fee_line->amountoutstanding + 0,
3319                 $replacement_amount,
3320                 'The right LOST amountoutstanding is generated' );
3321             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3322
3323             # Return lost item
3324             my ( $returned, $message ) =
3325               AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
3326
3327             $overdue_fee->discard_changes;
3328             is( $overdue_fee->amount + 0,
3329                 10, 'The OVERDUE amount is left intact' );
3330             is( $overdue_fee->amountoutstanding + 0,
3331                 10,
3332                 'The OVERDUE amountoutstanding is left intact' );
3333
3334             $lost_fee_line->discard_changes;
3335             is( $lost_fee_line->amount + 0,
3336                 $replacement_amount, 'The LOST amount is left intact' );
3337             is( $lost_fee_line->amountoutstanding + 0,
3338                 $replacement_amount,
3339                 'The LOST amountoutstanding is left intact' );
3340             # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
3341             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3342         };
3343
3344         subtest 'lostreturn | refund' => sub {
3345             plan tests => 12;
3346
3347             t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
3348
3349             my $item = $builder->build_sample_item(
3350                 {
3351                     replacementprice => $replacement_amount
3352                 }
3353             );
3354
3355             # Issue the item
3356             my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3357
3358             # Fake fines cronjob on this checkout
3359             my ($fine) =
3360               CalcFine( $item, $patron->categorycode, $library->{branchcode},
3361                 $ten_days_ago, $now );
3362             UpdateFine(
3363                 {
3364                     issue_id       => $issue->issue_id,
3365                     itemnumber     => $item->itemnumber,
3366                     borrowernumber => $patron->borrowernumber,
3367                     amount         => $fine,
3368                     due            => output_pref($ten_days_ago)
3369                 }
3370             );
3371             my $overdue_fees = Koha::Account::Lines->search(
3372                 {
3373                     borrowernumber  => $patron->id,
3374                     itemnumber      => $item->itemnumber,
3375                     debit_type_code => 'OVERDUE'
3376                 }
3377             );
3378             is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3379             my $overdue_fee = $overdue_fees->next;
3380             is( $overdue_fee->amount + 0,
3381                 10, 'The right OVERDUE amount is generated' );
3382             is( $overdue_fee->amountoutstanding + 0,
3383                 10,
3384                 'The right OVERDUE amountoutstanding is generated' );
3385
3386             # Simulate item marked as lost
3387             $item->itemlost(3)->store;
3388             C4::Circulation::LostItem( $item->itemnumber, 1 );
3389
3390             my $lost_fee_lines = Koha::Account::Lines->search(
3391                 {
3392                     borrowernumber  => $patron->id,
3393                     itemnumber      => $item->itemnumber,
3394                     debit_type_code => 'LOST'
3395                 }
3396             );
3397             is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3398             my $lost_fee_line = $lost_fee_lines->next;
3399             is( $lost_fee_line->amount + 0,
3400                 $replacement_amount, 'The right LOST amount is generated' );
3401             is( $lost_fee_line->amountoutstanding + 0,
3402                 $replacement_amount,
3403                 'The right LOST amountoutstanding is generated' );
3404             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3405
3406             # Return the lost item
3407             my ( undef, $message ) =
3408               AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
3409
3410             $overdue_fee->discard_changes;
3411             is( $overdue_fee->amount + 0,
3412                 10, 'The OVERDUE amount is left intact' );
3413             is( $overdue_fee->amountoutstanding + 0,
3414                 10,
3415                 'The OVERDUE amountoutstanding is left intact' );
3416
3417             $lost_fee_line->discard_changes;
3418             is( $lost_fee_line->amount + 0,
3419                 $replacement_amount, 'The LOST amount is left intact' );
3420             is( $lost_fee_line->amountoutstanding + 0,
3421                 0,
3422                 'The LOST amountoutstanding is refunded' );
3423             is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3424         };
3425
3426         subtest 'lostreturn | restore' => sub {
3427             plan tests => 13;
3428
3429             t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
3430
3431             my $item = $builder->build_sample_item(
3432                 {
3433                     replacementprice => $replacement_amount
3434                 }
3435             );
3436
3437             # Issue the item
3438             my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode , $ten_days_ago);
3439
3440             # Fake fines cronjob on this checkout
3441             my ($fine) =
3442               CalcFine( $item, $patron->categorycode, $library->{branchcode},
3443                 $ten_days_ago, $now );
3444             UpdateFine(
3445                 {
3446                     issue_id       => $issue->issue_id,
3447                     itemnumber     => $item->itemnumber,
3448                     borrowernumber => $patron->borrowernumber,
3449                     amount         => $fine,
3450                     due            => output_pref($ten_days_ago)
3451                 }
3452             );
3453             my $overdue_fees = Koha::Account::Lines->search(
3454                 {
3455                     borrowernumber  => $patron->id,
3456                     itemnumber      => $item->itemnumber,
3457                     debit_type_code => 'OVERDUE'
3458                 }
3459             );
3460             is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3461             my $overdue_fee = $overdue_fees->next;
3462             is( $overdue_fee->amount + 0,
3463                 10, 'The right OVERDUE amount is generated' );
3464             is( $overdue_fee->amountoutstanding + 0,
3465                 10,
3466                 'The right OVERDUE amountoutstanding is generated' );
3467
3468             # Simulate item marked as lost
3469             $item->itemlost(3)->store;
3470             C4::Circulation::LostItem( $item->itemnumber, 1 );
3471
3472             my $lost_fee_lines = Koha::Account::Lines->search(
3473                 {
3474                     borrowernumber  => $patron->id,
3475                     itemnumber      => $item->itemnumber,
3476                     debit_type_code => 'LOST'
3477                 }
3478             );
3479             is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3480             my $lost_fee_line = $lost_fee_lines->next;
3481             is( $lost_fee_line->amount + 0,
3482                 $replacement_amount, 'The right LOST amount is generated' );
3483             is( $lost_fee_line->amountoutstanding + 0,
3484                 $replacement_amount,
3485                 'The right LOST amountoutstanding is generated' );
3486             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3487
3488             # Simulate refunding overdue fees upon marking item as lost
3489             my $overdue_forgive = $patron->account->add_credit(
3490                 {
3491                     amount     => 10.00,
3492                     user_id    => $manager->borrowernumber,
3493                     library_id => $branchcode_restore,
3494                     interface  => 'test',
3495                     type       => 'FORGIVEN',
3496                     item_id    => $item->itemnumber
3497                 }
3498             );
3499             $overdue_forgive->apply( { debits => [$overdue_fee] } );
3500             $overdue_fee->discard_changes;
3501             is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3502
3503             # Do nothing
3504             my ( undef, $message ) =
3505               AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
3506
3507             $overdue_fee->discard_changes;
3508             is( $overdue_fee->amount + 0,
3509                 10, 'The OVERDUE amount is left intact' );
3510             is( $overdue_fee->amountoutstanding + 0,
3511                 10,
3512                 'The OVERDUE amountoutstanding is restored' );
3513
3514             $lost_fee_line->discard_changes;
3515             is( $lost_fee_line->amount + 0,
3516                 $replacement_amount, 'The LOST amount is left intact' );
3517             is( $lost_fee_line->amountoutstanding + 0,
3518                 0,
3519                 'The LOST amountoutstanding is refunded' );
3520             is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3521         };
3522
3523         subtest 'lostreturn | charge' => sub {
3524             plan tests => 16;
3525
3526             t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
3527
3528             my $item = $builder->build_sample_item(
3529                 {
3530                     replacementprice => $replacement_amount
3531                 }
3532             );
3533
3534             # Issue the item
3535             my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3536
3537             # Fake fines cronjob on this checkout
3538             my ($fine) =
3539               CalcFine( $item, $patron->categorycode, $library->{branchcode},
3540                 $ten_days_ago, $now );
3541             UpdateFine(
3542                 {
3543                     issue_id       => $issue->issue_id,
3544                     itemnumber     => $item->itemnumber,
3545                     borrowernumber => $patron->borrowernumber,
3546                     amount         => $fine,
3547                     due            => output_pref($ten_days_ago)
3548                 }
3549             );
3550             my $overdue_fees = Koha::Account::Lines->search(
3551                 {
3552                     borrowernumber  => $patron->id,
3553                     itemnumber      => $item->itemnumber,
3554                     debit_type_code => 'OVERDUE'
3555                 }
3556             );
3557             is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3558             my $overdue_fee = $overdue_fees->next;
3559             is( $overdue_fee->amount + 0,
3560                 10, 'The right OVERDUE amount is generated' );
3561             is( $overdue_fee->amountoutstanding + 0,
3562                 10,
3563                 'The right OVERDUE amountoutstanding is generated' );
3564
3565             # Simulate item marked as lost
3566             $item->itemlost(3)->store;
3567             C4::Circulation::LostItem( $item->itemnumber, 1 );
3568
3569             my $lost_fee_lines = Koha::Account::Lines->search(
3570                 {
3571                     borrowernumber  => $patron->id,
3572                     itemnumber      => $item->itemnumber,
3573                     debit_type_code => 'LOST'
3574                 }
3575             );
3576             is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3577             my $lost_fee_line = $lost_fee_lines->next;
3578             is( $lost_fee_line->amount + 0,
3579                 $replacement_amount, 'The right LOST amount is generated' );
3580             is( $lost_fee_line->amountoutstanding + 0,
3581                 $replacement_amount,
3582                 'The right LOST amountoutstanding is generated' );
3583             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3584
3585             # Simulate refunding overdue fees upon marking item as lost
3586             my $overdue_forgive = $patron->account->add_credit(
3587                 {
3588                     amount     => 10.00,
3589                     user_id    => $manager->borrowernumber,
3590                     library_id => $branchcode_charge,
3591                     interface  => 'test',
3592                     type       => 'FORGIVEN',
3593                     item_id    => $item->itemnumber
3594                 }
3595             );
3596             $overdue_forgive->apply( { debits => [$overdue_fee] } );
3597             $overdue_fee->discard_changes;
3598             is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3599
3600             # Do nothing
3601             my ( undef, $message ) =
3602               AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
3603
3604             $lost_fee_line->discard_changes;
3605             is( $lost_fee_line->amount + 0,
3606                 $replacement_amount, 'The LOST amount is left intact' );
3607             is( $lost_fee_line->amountoutstanding + 0,
3608                 0,
3609                 'The LOST amountoutstanding is refunded' );
3610             is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3611
3612             $overdue_fees = Koha::Account::Lines->search(
3613                 {
3614                     borrowernumber  => $patron->id,
3615                     itemnumber      => $item->itemnumber,
3616                     debit_type_code => 'OVERDUE'
3617                 },
3618                 {
3619                     order_by => { '-asc' => 'accountlines_id'}
3620                 }
3621             );
3622             is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
3623             $overdue_fee = $overdue_fees->next;
3624             is( $overdue_fee->amount + 0,
3625                 10, 'The original OVERDUE amount is left intact' );
3626             is( $overdue_fee->amountoutstanding + 0,
3627                 0,
3628                 'The original OVERDUE amountoutstanding is left as forgiven' );
3629             $overdue_fee = $overdue_fees->next;
3630             is( $overdue_fee->amount + 0,
3631                 5, 'The new OVERDUE amount is correct for the backdated return' );
3632             is( $overdue_fee->amountoutstanding + 0,
3633                 5,
3634                 'The new OVERDUE amountoutstanding is correct for the backdated return' );
3635         };
3636     };
3637 };
3638
3639 subtest '_FixOverduesOnReturn' => sub {
3640     plan tests => 14;
3641
3642     my $manager = $builder->build_object({ class => "Koha::Patrons" });
3643     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3644
3645     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3646
3647     my $branchcode  = $library2->{branchcode};
3648
3649     my $item = $builder->build_sample_item(
3650         {
3651             biblionumber     => $biblio->biblionumber,
3652             library          => $branchcode,
3653             replacementprice => 99.00,
3654             itype            => $itemtype,
3655         }
3656     );
3657
3658     my $patron = $builder->build( { source => 'Borrower' } );
3659
3660     ## Start with basic call, should just close out the open fine
3661     my $accountline = Koha::Account::Line->new(
3662         {
3663             borrowernumber => $patron->{borrowernumber},
3664             debit_type_code    => 'OVERDUE',
3665             status         => 'UNRETURNED',
3666             itemnumber     => $item->itemnumber,
3667             amount => 99.00,
3668             amountoutstanding => 99.00,
3669             interface => 'test',
3670         }
3671     )->store();
3672
3673     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
3674
3675     $accountline->_result()->discard_changes();
3676
3677     is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
3678     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3679     is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3680
3681     ## Run again, with exemptfine enabled
3682     $accountline->set(
3683         {
3684             debit_type_code    => 'OVERDUE',
3685             status         => 'UNRETURNED',
3686             amountoutstanding => 99.00,
3687         }
3688     )->store();
3689
3690     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3691
3692     $accountline->_result()->discard_changes();
3693     my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'APPLY' })->next();
3694
3695     is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
3696     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3697     is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
3698     is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
3699     is( $offset->amount + 0, -99, "Amount of offset is correct" );
3700     my $credit = $offset->credit;
3701     is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
3702     is( $credit->amount + 0, -99, "Credit amount is set correctly" );
3703     is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
3704
3705     # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
3706     $accountline->set(
3707         {
3708             debit_type_code    => 'OVERDUE',
3709             status         => 'UNRETURNED',
3710             amountoutstanding => 0.00,
3711         }
3712     )->store();
3713     $offset->delete;
3714
3715     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3716
3717     $accountline->_result()->discard_changes();
3718     $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'CREATE' })->next();
3719     is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
3720     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3721     is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3722 };
3723
3724 subtest 'Set waiting flag' => sub {
3725     plan tests => 11;
3726
3727     my $library_1 = $builder->build( { source => 'Branch' } );
3728     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3729     my $library_2 = $builder->build( { source => 'Branch' } );
3730     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3731
3732     my $item = $builder->build_sample_item(
3733         {
3734             library      => $library_1->{branchcode},
3735         }
3736     );
3737
3738     set_userenv( $library_2 );
3739     my $reserve_id = AddReserve(
3740         {
3741             branchcode     => $library_2->{branchcode},
3742             borrowernumber => $patron_2->{borrowernumber},
3743             biblionumber   => $item->biblionumber,
3744             priority       => 1,
3745             itemnumber     => $item->itemnumber,
3746         }
3747     );
3748
3749     set_userenv( $library_1 );
3750     my $do_transfer = 1;
3751     my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3752     ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3753     my $hold = Koha::Holds->find( $reserve_id );
3754     is( $hold->found, 'T', 'Hold is in transit' );
3755
3756     my ( $status ) = CheckReserves($item->itemnumber);
3757     is( $status, 'Transferred', 'Hold is not waiting yet');
3758
3759     set_userenv( $library_2 );
3760     $do_transfer = 0;
3761     AddReturn( $item->barcode, $library_2->{branchcode} );
3762     ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3763     $hold = Koha::Holds->find( $reserve_id );
3764     is( $hold->found, 'W', 'Hold is waiting' );
3765     ( $status ) = CheckReserves($item->itemnumber);
3766     is( $status, 'Waiting', 'Now the hold is waiting');
3767
3768     #Bug 21944 - Waiting transfer checked in at branch other than pickup location
3769     set_userenv( $library_1 );
3770     (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
3771     $hold = Koha::Holds->find( $reserve_id );
3772     is( $hold->found, undef, 'Hold is no longer marked waiting' );
3773     is( $hold->priority, 1,  "Hold is now priority one again");
3774     is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
3775     is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
3776     is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
3777     is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
3778     is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
3779 };
3780
3781 subtest 'Cancel transfers on lost items' => sub {
3782     plan tests => 6;
3783
3784     my $library_to = $builder->build_object( { class => 'Koha::Libraries' } );
3785     my $item   = $builder->build_sample_item();
3786     my $holdingbranch = $item->holdingbranch;
3787     # Historic transfer (datearrived is defined)
3788     my $old_transfer = $builder->build_object(
3789         {
3790             class => 'Koha::Item::Transfers',
3791             value => {
3792                 itemnumber    => $item->itemnumber,
3793                 frombranch    => $holdingbranch,
3794                 tobranch      => $library_to->branchcode,
3795                 reason        => 'Manual',
3796                 datesent      => \'NOW()',
3797                 datearrived   => \'NOW()',
3798                 datecancelled => undef,
3799                 daterequested => \'NOW()'
3800             }
3801         }
3802     );
3803     # Queued transfer (datesent is undefined)
3804     my $transfer_1 = $builder->build_object(
3805         {
3806             class => 'Koha::Item::Transfers',
3807             value => {
3808                 itemnumber    => $item->itemnumber,
3809                 frombranch    => $holdingbranch,
3810                 tobranch      => $library_to->branchcode,
3811                 reason        => 'Manual',
3812                 datesent      => undef,
3813                 datearrived   => undef,
3814                 datecancelled => undef,
3815                 daterequested => \'NOW()'
3816             }
3817         }
3818     );
3819     # In transit transfer (datesent is defined, datearrived and datecancelled are both undefined)
3820     my $transfer_2 = $builder->build_object(
3821         {
3822             class => 'Koha::Item::Transfers',
3823             value => {
3824                 itemnumber    => $item->itemnumber,
3825                 frombranch    => $holdingbranch,
3826                 tobranch      => $library_to->branchcode,
3827                 reason        => 'Manual',
3828                 datesent      => \'NOW()',
3829                 datearrived   => undef,
3830                 datecancelled => undef,
3831                 daterequested => \'NOW()'
3832             }
3833         }
3834     );
3835
3836     # Simulate item being marked as lost
3837     $item->itemlost(1)->store;
3838     LostItem( $item->itemnumber, 'test', 1 );
3839
3840     $transfer_1->discard_changes;
3841     isnt($transfer_1->datecancelled, undef, "Queud transfer was cancelled upon item lost");
3842     is($transfer_1->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
3843     $transfer_2->discard_changes;
3844     isnt($transfer_2->datecancelled, undef, "Active transfer was cancelled upon item lost");
3845     is($transfer_2->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
3846     $old_transfer->discard_changes;
3847     is($old_transfer->datecancelled, undef, "Old transfers are unaffected");
3848     $item->discard_changes;
3849     is($item->holdingbranch, $holdingbranch, "Items holding branch remains unchanged");
3850 };
3851
3852 subtest 'CanBookBeIssued | is_overdue' => sub {
3853     plan tests => 3;
3854
3855     # Set a simple circ policy
3856     Koha::CirculationRules->set_rules(
3857         {
3858             categorycode => undef,
3859             branchcode   => undef,
3860             itemtype     => undef,
3861             rules        => {
3862                 maxissueqty     => 1,
3863                 reservesallowed => 25,
3864                 issuelength     => 14,
3865                 lengthunit      => 'days',
3866                 renewalsallowed => 1,
3867                 renewalperiod   => 7,
3868                 norenewalbefore => undef,
3869                 auto_renew      => 0,
3870                 fine            => .10,
3871                 chargeperiod    => 1,
3872             }
3873         }
3874     );
3875
3876     my $now   = dt_from_string()->truncate( to => 'day' );
3877     my $five_days_go = $now->clone->add( days => 5 );
3878     my $ten_days_go  = $now->clone->add( days => 10);
3879     my $library = $builder->build( { source => 'Branch' } );
3880     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
3881
3882     my $item = $builder->build_sample_item(
3883         {
3884             library      => $library->{branchcode},
3885         }
3886     );
3887
3888     my $issue = AddIssue( $patron->unblessed, $item->barcode, $five_days_go ); # date due was 10d ago
3889     my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
3890     is( output_pref({ str => $actualissue->date_due, dateonly => 1}), output_pref({ str => $five_days_go, dateonly => 1}), "First issue works");
3891     my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->barcode,$ten_days_go, undef, undef, undef);
3892     is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
3893     is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
3894 };
3895
3896 subtest 'ItemsDeniedRenewal preference' => sub {
3897     plan tests => 18;
3898
3899     C4::Context->set_preference('ItemsDeniedRenewal','');
3900
3901     my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
3902     Koha::CirculationRules->set_rules(
3903         {
3904             categorycode => '*',
3905             itemtype     => '*',
3906             branchcode   => $idr_lib->branchcode,
3907             rules        => {
3908                 reservesallowed => 25,
3909                 issuelength     => 14,
3910                 lengthunit      => 'days',
3911                 renewalsallowed => 10,
3912                 renewalperiod   => 7,
3913                 norenewalbefore => undef,
3914                 auto_renew      => 0,
3915                 fine            => .10,
3916                 chargeperiod    => 1,
3917             }
3918         }
3919     );
3920
3921     my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
3922         homebranch => $idr_lib->branchcode,
3923         withdrawn => 1,
3924         itype => 'HIDE',
3925         location => 'PROC',
3926         itemcallnumber => undef,
3927         itemnotes => "",
3928         }
3929     });
3930     my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
3931         homebranch => $idr_lib->branchcode,
3932         withdrawn => 0,
3933         itype => 'NOHIDE',
3934         location => 'NOPROC'
3935         }
3936     });
3937
3938     my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
3939         branchcode => $idr_lib->branchcode,
3940         }
3941     });
3942     my $future = dt_from_string->add( days => 1 );
3943     my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3944         returndate => undef,
3945         renewals => 0,
3946         auto_renew => 0,
3947         borrowernumber => $idr_borrower->borrowernumber,
3948         itemnumber => $deny_book->itemnumber,
3949         onsite_checkout => 0,
3950         date_due => $future,
3951         }
3952     });
3953     my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3954         returndate => undef,
3955         renewals => 0,
3956         auto_renew => 0,
3957         borrowernumber => $idr_borrower->borrowernumber,
3958         itemnumber => $allow_book->itemnumber,
3959         onsite_checkout => 0,
3960         date_due => $future,
3961         }
3962     });
3963
3964     my $idr_rules;
3965
3966     my ( $idr_mayrenew, $idr_error ) =
3967     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3968     is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3969     is( $idr_error, undef, 'Renewal allowed when no rules' );
3970
3971     $idr_rules="withdrawn: [1]";
3972
3973     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3974     ( $idr_mayrenew, $idr_error ) =
3975     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3976     is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3977     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3978     ( $idr_mayrenew, $idr_error ) =
3979     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3980     is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3981     is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3982
3983     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
3984
3985     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3986     ( $idr_mayrenew, $idr_error ) =
3987     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3988     is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
3989     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
3990     ( $idr_mayrenew, $idr_error ) =
3991     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3992     is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3993     is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3994
3995     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
3996
3997     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3998     ( $idr_mayrenew, $idr_error ) =
3999     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4000     is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
4001     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
4002     ( $idr_mayrenew, $idr_error ) =
4003     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
4004     is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
4005     is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
4006
4007     $idr_rules="itemcallnumber: [NULL]";
4008     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4009     ( $idr_mayrenew, $idr_error ) =
4010     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4011     is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
4012     $idr_rules="itemcallnumber: ['']";
4013     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4014     ( $idr_mayrenew, $idr_error ) =
4015     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4016     is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
4017
4018     $idr_rules="itemnotes: [NULL]";
4019     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4020     ( $idr_mayrenew, $idr_error ) =
4021     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4022     is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
4023     $idr_rules="itemnotes: ['']";
4024     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4025     ( $idr_mayrenew, $idr_error ) =
4026     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4027     is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
4028 };
4029
4030 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
4031     plan tests => 2;
4032
4033     t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4034     my $library = $builder->build( { source => 'Branch' } );
4035     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4036
4037     my $item = $builder->build_sample_item(
4038         {
4039             library      => $library->{branchcode},
4040         }
4041     );
4042
4043     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4044     is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4045     is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4046 };
4047
4048 subtest 'CanBookBeIssued | notforloan' => sub {
4049     plan tests => 2;
4050
4051     t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
4052
4053     my $library = $builder->build( { source => 'Branch' } );
4054     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4055
4056     my $itemtype = $builder->build(
4057         {
4058             source => 'Itemtype',
4059             value  => { notforloan => undef, }
4060         }
4061     );
4062     my $item = $builder->build_sample_item(
4063         {
4064             library  => $library->{branchcode},
4065             itype    => $itemtype->{itemtype},
4066         }
4067     );
4068     $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4069
4070     my ( $issuingimpossible, $needsconfirmation );
4071
4072
4073     subtest 'item-level_itypes = 1' => sub {
4074         plan tests => 6;
4075
4076         t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
4077         # Is for loan at item type and item level
4078         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4079         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4080         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4081
4082         # not for loan at item type level
4083         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4084         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4085         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4086         is_deeply(
4087             $issuingimpossible,
4088             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4089             'Item can not be issued, not for loan at item type level'
4090         );
4091
4092         # not for loan at item level
4093         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4094         $item->notforloan( 1 )->store;
4095         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4096         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4097         is_deeply(
4098             $issuingimpossible,
4099             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4100             'Item can not be issued, not for loan at item type level'
4101         );
4102     };
4103
4104     subtest 'item-level_itypes = 0' => sub {
4105         plan tests => 6;
4106
4107         t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4108
4109         # We set another itemtype for biblioitem
4110         my $itemtype = $builder->build(
4111             {
4112                 source => 'Itemtype',
4113                 value  => { notforloan => undef, }
4114             }
4115         );
4116
4117         # for loan at item type and item level
4118         $item->notforloan(0)->store;
4119         $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4120         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4121         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4122         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4123
4124         # not for loan at item type level
4125         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4126         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4127         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4128         is_deeply(
4129             $issuingimpossible,
4130             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4131             'Item can not be issued, not for loan at item type level'
4132         );
4133
4134         # not for loan at item level
4135         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4136         $item->notforloan( 1 )->store;
4137         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4138         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4139         is_deeply(
4140             $issuingimpossible,
4141             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4142             'Item can not be issued, not for loan at item type level'
4143         );
4144     };
4145
4146     # TODO test with AllowNotForLoanOverride = 1
4147 };
4148
4149 subtest 'CanBookBeIssued | recalls' => sub {
4150     plan tests => 3;
4151
4152     t::lib::Mocks::mock_preference("UseRecalls", 1);
4153     t::lib::Mocks::mock_preference("item-level_itypes", 1);
4154     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4155     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4156     my $item = $builder->build_sample_item;
4157     Koha::CirculationRules->set_rules({
4158         branchcode => undef,
4159         itemtype => undef,
4160         categorycode => undef,
4161         rules => {
4162             recalls_allowed => 10,
4163         },
4164     });
4165
4166     # item-level recall
4167     my $recall = Koha::Recall->new(
4168         {   patron_id         => $patron1->borrowernumber,
4169             biblio_id         => $item->biblionumber,
4170             item_id           => $item->itemnumber,
4171             item_level        => 1,
4172             pickup_library_id => $patron1->branchcode,
4173         }
4174     )->store;
4175
4176     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4177     is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed an item-level recall on this item" );
4178
4179     $recall->set_cancelled;
4180
4181     # biblio-level recall
4182     $recall = Koha::Recall->new(
4183         {   patron_id         => $patron1->borrowernumber,
4184             biblio_id         => $item->biblionumber,
4185             item_id           => undef,
4186             item_level        => 0,
4187             pickup_library_id => $patron1->branchcode,
4188         }
4189     )->store;
4190
4191     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4192     is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed a biblio-level recall and this item is eligible to fill it" );
4193
4194     $recall->set_cancelled;
4195
4196     # biblio-level recall
4197     $recall = Koha::Recall->new(
4198         {   patron_id         => $patron1->borrowernumber,
4199             biblio_id         => $item->biblionumber,
4200             item_id           => undef,
4201             item_level        => 0,
4202             pickup_library_id => $patron1->branchcode,
4203         }
4204     )->store;
4205     $recall->set_waiting( { item => $item, expirationdate => dt_from_string() } );
4206
4207     my ( undef, undef, undef, $messages ) = CanBookBeIssued( $patron1, $item->barcode, undef, undef, undef, undef );
4208     is( $messages->{RECALLED}, $recall->id, "This book can be issued by this patron and they have placed a recall" );
4209
4210     $recall->set_cancelled;
4211 };
4212
4213 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
4214     plan tests => 1;
4215
4216     t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
4217     my $item = $builder->build_sample_item(
4218         {
4219             onloan => '2018-01-01',
4220         }
4221     );
4222
4223     AddReturn( $item->barcode, $item->homebranch );
4224     $item->discard_changes; # refresh
4225     is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
4226 };
4227
4228 subtest 'AddReturn | recalls' => sub {
4229     plan tests => 3;
4230
4231     t::lib::Mocks::mock_preference("UseRecalls", 1);
4232     t::lib::Mocks::mock_preference("item-level_itypes", 1);
4233     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4234     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4235     my $item1 = $builder->build_sample_item;
4236     Koha::CirculationRules->set_rules({
4237         branchcode => undef,
4238         itemtype => undef,
4239         categorycode => undef,
4240         rules => {
4241             recalls_allowed => 10,
4242         },
4243     });
4244
4245     # this item can fill a recall with pickup at this branch
4246     AddIssue( $patron1->unblessed, $item1->barcode );
4247     my $recall1 = Koha::Recall->new(
4248         {   patron_id         => $patron2->borrowernumber,
4249             biblio_id         => $item1->biblionumber,
4250             item_id           => $item1->itemnumber,
4251             item_level        => 1,
4252             pickup_library_id => $item1->homebranch,
4253         }
4254     )->store;
4255     my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4256     is( $messages->{RecallFound}->id, $recall1->id, "Recall found" );
4257     $recall1->set_cancelled;
4258
4259     # this item can fill a recall but needs transfer
4260     AddIssue( $patron1->unblessed, $item1->barcode );
4261     $recall1 = Koha::Recall->new(
4262         {   patron_id         => $patron2->borrowernumber,
4263             biblio_id         => $item1->biblionumber,
4264             item_id           => $item1->itemnumber,
4265             item_level        => 1,
4266             pickup_library_id => $patron2->branchcode,
4267         }
4268     )->store;
4269     ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4270     is( $messages->{RecallNeedsTransfer}, $item1->homebranch, "Recall requiring transfer found" );
4271     $recall1->set_cancelled;
4272
4273     # this item is already in transit, do not ask to transfer
4274     AddIssue( $patron1->unblessed, $item1->barcode );
4275     $recall1 = Koha::Recall->new(
4276         {   patron_id         => $patron2->borrowernumber,
4277             biblio_id         => $item1->biblionumber,
4278             item_id           => $item1->itemnumber,
4279             item_level        => 1,
4280             pickup_library_id => $patron2->branchcode,
4281         }
4282     )->store;
4283     $recall1->start_transfer;
4284     ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $patron2->branchcode );
4285     is( $messages->{TransferredRecall}->id, $recall1->id, "In transit recall found" );
4286     $recall1->set_cancelled;
4287 };
4288
4289 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
4290
4291     plan tests => 13;
4292
4293
4294     t::lib::Mocks::mock_preference('item-level_itypes', 1);
4295
4296     my $issuing_charges = 15;
4297     my $title   = 'A title';
4298     my $author  = 'Author, An';
4299     my $barcode = 'WHATARETHEODDS';
4300
4301     my $circ = Test::MockModule->new('C4::Circulation');
4302     $circ->mock(
4303         'GetIssuingCharges',
4304         sub {
4305             return $issuing_charges;
4306         }
4307     );
4308
4309     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
4310     my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
4311     my $patron   = $builder->build_object({
4312         class => 'Koha::Patrons',
4313         value => { branchcode => $library->id }
4314     });
4315
4316     my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
4317     my $item_id = Koha::Item->new(
4318         {
4319             biblionumber     => $biblio->biblionumber,
4320             homebranch       => $library->id,
4321             holdingbranch    => $library->id,
4322             barcode          => $barcode,
4323             replacementprice => 23.00,
4324             itype            => $itemtype->id
4325         },
4326     )->store->itemnumber;
4327     my $item = Koha::Items->find( $item_id );
4328
4329     my $context = Test::MockModule->new('C4::Context');
4330     $context->mock( userenv => { branch => $library->id } );
4331
4332     # Check the item out
4333     AddIssue( $patron->unblessed, $item->barcode );
4334
4335     throws_ok {
4336         AddRenewal( $patron->borrowernumber, $item->itemnumber, $library->id, undef, {break=>"the_renewal"} );
4337     } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
4338
4339     t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
4340     my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
4341     my %params_renewal = (
4342         timestamp => { -like => $date . "%" },
4343         module => "CIRCULATION",
4344         action => "RENEWAL",
4345     );
4346     my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
4347     AddRenewal( $patron->id, $item->id, $library->id );
4348     my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4349     is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
4350
4351     my $checkouts = $patron->checkouts;
4352     # The following will fail if run on 00:00:00
4353     unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
4354
4355     my $lines = Koha::Account::Lines->search({
4356         borrowernumber => $patron->id,
4357         itemnumber     => $item->id
4358     });
4359
4360     is( $lines->count, 2 );
4361
4362     my $line = $lines->next;
4363     is( $line->debit_type_code, 'RENT',       'The issue of item with issuing charge generates an accountline of the correct type' );
4364     is( $line->branchcode,  $library->id, 'AddIssuingCharge correctly sets branchcode' );
4365     is( $line->description, '',     'AddIssue does not set a hardcoded description for the accountline' );
4366
4367     $line = $lines->next;
4368     is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
4369     is( $line->branchcode,  $library->id, 'AddRenewal correctly sets branchcode' );
4370     is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
4371
4372     t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
4373
4374     $context = Test::MockModule->new('C4::Context');
4375     $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
4376
4377     my $now = dt_from_string;
4378     $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
4379     $old_log_size = Koha::ActionLogs->count( \%params_renewal );
4380     my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
4381     $sth->execute($item->id, $library->id);
4382     my ($old_stats_size) = $sth->fetchrow_array;
4383     AddRenewal( $patron->id, $item->id, $library->id );
4384     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4385     $sth->execute($item->id, $library->id);
4386     my ($new_stats_size) = $sth->fetchrow_array;
4387     is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
4388     is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
4389
4390     AddReturn( $item->id, $library->id, undef, $date );
4391     AddIssue( $patron->unblessed, $item->barcode, $now );
4392     AddRenewal( $patron->id, $item->id, $library->id, undef, undef, 1 );
4393     my $lines_skipped = Koha::Account::Lines->search({
4394         borrowernumber => $patron->id,
4395         itemnumber     => $item->id
4396     });
4397     is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
4398
4399 };
4400
4401 subtest 'ProcessOfflinePayment() tests' => sub {
4402
4403     plan tests => 4;
4404
4405
4406     my $amount = 123;
4407
4408     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
4409     my $library = $builder->build_object({ class => 'Koha::Libraries' });
4410     my $result  = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
4411
4412     is( $result, 'Success.', 'The right string is returned' );
4413
4414     my $lines = $patron->account->lines;
4415     is( $lines->count, 1, 'line created correctly');
4416
4417     my $line = $lines->next;
4418     is( $line->amount+0, $amount * -1, 'amount picked from params' );
4419     is( $line->branchcode, $library->id, 'branchcode set correctly' );
4420
4421 };
4422
4423 subtest 'Incremented fee tests' => sub {
4424     plan tests => 19;
4425
4426     my $dt = dt_from_string();
4427     Time::Fake->offset( $dt->epoch );
4428
4429     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
4430
4431     my $library =
4432       $builder->build_object( { class => 'Koha::Libraries' } )->store;
4433
4434     $module->mock( 'userenv', sub { { branch => $library->id } } );
4435
4436     my $patron = $builder->build_object(
4437         {
4438             class => 'Koha::Patrons',
4439             value => { categorycode => $patron_category->{categorycode} }
4440         }
4441     )->store;
4442
4443     my $itemtype = $builder->build_object(
4444         {
4445             class => 'Koha::ItemTypes',
4446             value => {
4447                 notforloan                   => undef,
4448                 rentalcharge                 => 0,
4449                 rentalcharge_daily           => 1,
4450                 rentalcharge_daily_calendar  => 0
4451             }
4452         }
4453     )->store;
4454
4455     my $item = $builder->build_sample_item(
4456         {
4457             library  => $library->{branchcode},
4458             itype    => $itemtype->id,
4459         }
4460     );
4461
4462     is( $itemtype->rentalcharge_daily+0,
4463         1, 'Daily rental charge stored and retreived correctly' );
4464     is( $item->effective_itemtype, $itemtype->id,
4465         "Itemtype set correctly for item" );
4466
4467     my $now         = dt_from_string;
4468     my $dt_from     = $now->clone;
4469     my $dt_to       = $now->clone->add( days => 7 );
4470     my $dt_to_renew = $now->clone->add( days => 13 );
4471
4472     # Daily Tests
4473     my $issue =
4474       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4475     my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4476     is( $accountline->amount+0, 7,
4477 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
4478     );
4479     $accountline->delete();
4480     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4481     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4482     is( $accountline->amount+0, 6,
4483 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
4484     );
4485     $accountline->delete();
4486     $issue->delete();
4487
4488     t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
4489     $itemtype->rentalcharge_daily_calendar(1)->store();
4490     $issue =
4491       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4492     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4493     is( $accountline->amount+0, 7,
4494 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
4495     );
4496     $accountline->delete();
4497     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4498     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4499     is( $accountline->amount+0, 6,
4500 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
4501     );
4502     $accountline->delete();
4503     $issue->delete();
4504
4505     my $calendar = C4::Calendar->new( branchcode => $library->id );
4506     # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
4507     my $closed_day =
4508         ( $dt_from->day_of_week == 6 ) ? 0
4509       : ( $dt_from->day_of_week == 7 ) ? 1
4510       :                                  $dt_from->day_of_week + 1;
4511     my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
4512     $calendar->insert_week_day_holiday(
4513         weekday     => $closed_day,
4514         title       => 'Test holiday',
4515         description => 'Test holiday'
4516     );
4517     $issue =
4518       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4519     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4520     is( $accountline->amount+0, 6,
4521 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
4522     );
4523     $accountline->delete();
4524     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4525     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4526     is( $accountline->amount+0, 5,
4527 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
4528     );
4529     $accountline->delete();
4530     $issue->delete();
4531
4532     $itemtype->rentalcharge(2)->store;
4533     is( $itemtype->rentalcharge+0, 2,
4534         'Rental charge updated and retreived correctly' );
4535     $issue =
4536       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4537     my $accountlines =
4538       Koha::Account::Lines->search( { itemnumber => $item->id } );
4539     is( $accountlines->count, '2',
4540         "Fixed charge and accrued charge recorded distinctly" );
4541     $accountlines->delete();
4542     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4543     $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
4544     is( $accountlines->count, '2',
4545         "Fixed charge and accrued charge recorded distinctly, for renewal" );
4546     $accountlines->delete();
4547     $issue->delete();
4548     $itemtype->rentalcharge(0)->store;
4549     is( $itemtype->rentalcharge+0, 0,
4550         'Rental charge reset and retreived correctly' );
4551
4552     # Hourly
4553     Koha::CirculationRules->set_rule(
4554         {
4555             categorycode => $patron->categorycode,
4556             itemtype     => $itemtype->id,
4557             branchcode   => $library->id,
4558             rule_name    => 'lengthunit',
4559             rule_value   => 'hours',
4560         }
4561     );
4562
4563     $itemtype->rentalcharge_hourly('0.25')->store();
4564     is( $itemtype->rentalcharge_hourly,
4565         '0.25', 'Hourly rental charge stored and retreived correctly' );
4566
4567     $dt_to       = $now->clone->add( hours => 168 );
4568     $dt_to_renew = $now->clone->add( hours => 312 );
4569
4570     $itemtype->rentalcharge_hourly_calendar(0)->store();
4571     $issue =
4572       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4573     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4574     is( $accountline->amount + 0, 42,
4575         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)" );
4576     $accountline->delete();
4577     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4578     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4579     is( $accountline->amount + 0, 36,
4580         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)" );
4581     $accountline->delete();
4582     $issue->delete();
4583
4584     $itemtype->rentalcharge_hourly_calendar(1)->store();
4585     $issue =
4586       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4587     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4588     is( $accountline->amount + 0, 36,
4589         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)" );
4590     $accountline->delete();
4591     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4592     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4593     is( $accountline->amount + 0, 30,
4594         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
4595     $accountline->delete();
4596     $issue->delete();
4597
4598     $calendar->delete_holiday( weekday => $closed_day );
4599     $issue =
4600       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4601     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4602     is( $accountline->amount + 0, 42,
4603         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u" );
4604     $accountline->delete();
4605     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4606     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4607     is( $accountline->amount + 0, 36,
4608         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)" );
4609     $accountline->delete();
4610     $issue->delete();
4611     Time::Fake->reset;
4612 };
4613
4614 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
4615     plan tests => 2;
4616
4617     t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
4618     t::lib::Mocks::mock_preference('item-level_itypes', 1);
4619
4620     my $library =
4621       $builder->build_object( { class => 'Koha::Libraries' } )->store;
4622     my $patron = $builder->build_object(
4623         {
4624             class => 'Koha::Patrons',
4625             value => { categorycode => $patron_category->{categorycode} }
4626         }
4627     )->store;
4628
4629     my $itemtype = $builder->build_object(
4630         {
4631             class => 'Koha::ItemTypes',
4632             value => {
4633                 notforloan             => 0,
4634                 rentalcharge           => 0,
4635                 rentalcharge_daily => 0
4636             }
4637         }
4638     );
4639
4640     my $item = $builder->build_sample_item(
4641         {
4642             library    => $library->id,
4643             notforloan => 0,
4644             itemlost   => 0,
4645             withdrawn  => 0,
4646             itype      => $itemtype->id,
4647         }
4648     )->store;
4649
4650     my ( $issuingimpossible, $needsconfirmation );
4651     my $dt_from = dt_from_string();
4652     my $dt_due = $dt_from->clone->add( days => 3 );
4653
4654     $itemtype->rentalcharge(1)->store;
4655     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4656     is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
4657     $itemtype->rentalcharge('0')->store;
4658     $itemtype->rentalcharge_daily(1)->store;
4659     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4660     is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
4661     $itemtype->rentalcharge_daily('0')->store;
4662 };
4663
4664 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
4665     plan tests => 1;
4666
4667     t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
4668
4669     my $patron = $builder->build_object(
4670         {
4671             class => 'Koha::Patrons',
4672             value => { categorycode => $patron_category->{categorycode} }
4673         }
4674     )->store;
4675
4676     my $item = $builder->build_sample_item(
4677         {
4678             materials => 'includes DVD',
4679         }
4680     )->store;
4681
4682     my $dt_due = dt_from_string->add( days => 3 );
4683
4684     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4685     is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
4686 };
4687
4688 subtest 'Do not return on renewal (LOST charge)' => sub {
4689     plan tests => 1;
4690
4691     t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
4692     my $library = $builder->build_object( { class => "Koha::Libraries" } );
4693     my $manager = $builder->build_object( { class => "Koha::Patrons" } );
4694     t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
4695
4696     my $biblio = $builder->build_sample_biblio;
4697
4698     my $item = $builder->build_sample_item(
4699         {
4700             biblionumber     => $biblio->biblionumber,
4701             library          => $library->branchcode,
4702             replacementprice => 99.00,
4703             itype            => $itemtype,
4704         }
4705     );
4706
4707     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
4708     AddIssue( $patron->unblessed, $item->barcode );
4709
4710     my $accountline = Koha::Account::Line->new(
4711         {
4712             borrowernumber    => $patron->borrowernumber,
4713             debit_type_code   => 'LOST',
4714             status            => undef,
4715             itemnumber        => $item->itemnumber,
4716             amount            => 12,
4717             amountoutstanding => 12,
4718             interface         => 'something',
4719         }
4720     )->store();
4721
4722     # AddRenewal doesn't call _FixAccountForLostAndFound
4723     AddIssue( $patron->unblessed, $item->barcode );
4724
4725     is( $patron->checkouts->count, 1,
4726         'Renewal should not return the item even if a LOST payment has been made earlier'
4727     );
4728 };
4729
4730 subtest 'Filling a hold should cancel existing transfer' => sub {
4731     plan tests => 4;
4732
4733     t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
4734
4735     my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
4736     my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
4737     my $patron = $builder->build_object(
4738         {
4739             class => 'Koha::Patrons',
4740             value => {
4741                 categorycode => $patron_category->{categorycode},
4742                 branchcode => $libraryA->branchcode,
4743             }
4744         }
4745     )->store;
4746
4747     my $item = $builder->build_sample_item({
4748         homebranch => $libraryB->branchcode,
4749     });
4750
4751     my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4752     is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
4753     AddReserve({
4754         branchcode     => $libraryA->branchcode,
4755         borrowernumber => $patron->borrowernumber,
4756         biblionumber   => $item->biblionumber,
4757         itemnumber     => $item->itemnumber
4758     });
4759     my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
4760     is( $reserves->count, 1, "Reserve is placed");
4761     ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4762     my $reserve = $reserves->next;
4763     ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
4764     $reserve->discard_changes;
4765     ok( $reserve->found eq 'W', "Reserve is marked waiting" );
4766     is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
4767 };
4768
4769 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
4770
4771     plan tests => 4;
4772
4773     t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4774     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4775     my $patron  = $builder->build_object(
4776         {
4777             class => 'Koha::Patrons',
4778             value => { categorycode => $patron_category->{categorycode} }
4779         }
4780     );
4781
4782     my $biblionumber = $builder->build_sample_biblio(
4783         {
4784             branchcode => $library->branchcode,
4785         }
4786     )->biblionumber;
4787
4788     # And the circulation rule
4789     Koha::CirculationRules->search->delete;
4790     Koha::CirculationRules->set_rules(
4791         {
4792             categorycode => undef,
4793             itemtype     => undef,
4794             branchcode   => undef,
4795             rules        => {
4796                 issuelength => 14,
4797                 lengthunit  => 'days',
4798             }
4799         }
4800     );
4801     $builder->build(
4802         {
4803             source => 'CirculationRule',
4804             value  => {
4805                 branchcode   => undef,
4806                 categorycode => undef,
4807                 itemtype     => undef,
4808                 rule_name    => 'lostreturn',
4809                 rule_value   => 'refund'
4810             }
4811         }
4812     );
4813
4814     subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4815         plan tests => 3;
4816
4817         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4818         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4819
4820         my $lost_on = dt_from_string->subtract( days => 7 )->date;
4821
4822         my $item = $builder->build_sample_item(
4823             {
4824                 biblionumber     => $biblionumber,
4825                 library          => $library->branchcode,
4826                 replacementprice => '42',
4827             }
4828         );
4829         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4830         LostItem( $item->itemnumber, 'cli', 0 );
4831         $item->_result->itemlost(1);
4832         $item->_result->itemlost_on( $lost_on );
4833         $item->_result->update();
4834
4835         my $a = Koha::Account::Lines->search(
4836             {
4837                 itemnumber     => $item->id,
4838                 borrowernumber => $patron->borrowernumber
4839             }
4840         )->next;
4841         ok( $a, "Found accountline for lost fee" );
4842         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4843         my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4844         $a = $a->get_from_storage;
4845         is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4846         $a->delete;
4847     };
4848
4849     subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4850         plan tests => 3;
4851
4852         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4853         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4854
4855         my $lost_on = dt_from_string->subtract( days => 6 )->date;
4856
4857         my $item = $builder->build_sample_item(
4858             {
4859                 biblionumber     => $biblionumber,
4860                 library          => $library->branchcode,
4861                 replacementprice => '42',
4862             }
4863         );
4864         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4865         LostItem( $item->itemnumber, 'cli', 0 );
4866         $item->_result->itemlost(1);
4867         $item->_result->itemlost_on( $lost_on );
4868         $item->_result->update();
4869
4870         my $a = Koha::Account::Lines->search(
4871             {
4872                 itemnumber     => $item->id,
4873                 borrowernumber => $patron->borrowernumber
4874             }
4875         )->next;
4876         ok( $a, "Found accountline for lost fee" );
4877         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4878         my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4879         $a = $a->get_from_storage;
4880         is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4881         $a->delete;
4882     };
4883
4884     subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4885         plan tests => 3;
4886
4887         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4888         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4889
4890         my $lost_on = dt_from_string->subtract( days => 7 )->date;
4891
4892         my $item = $builder->build_sample_item(
4893             {
4894                 biblionumber     => $biblionumber,
4895                 library          => $library->branchcode,
4896                 replacementprice => '42',
4897             }
4898         );
4899         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4900         LostItem( $item->itemnumber, 'cli', 0 );
4901         $item->_result->itemlost(1);
4902         $item->_result->itemlost_on( $lost_on );
4903         $item->_result->update();
4904
4905         my $a = Koha::Account::Lines->search(
4906             {
4907                 itemnumber     => $item->id,
4908                 borrowernumber => $patron->borrowernumber
4909             }
4910         )->next;
4911         ok( $a, "Found accountline for lost fee" );
4912         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4913         my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4914         $a = $a->get_from_storage;
4915         is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4916         $a->delete;
4917     };
4918
4919     subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4920         plan tests => 3;
4921
4922         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4923         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4924
4925         my $lost_on = dt_from_string->subtract( days => 8 )->date;
4926
4927         my $item = $builder->build_sample_item(
4928             {
4929                 biblionumber     => $biblionumber,
4930                 library          => $library->branchcode,
4931                 replacementprice => '42',
4932             }
4933         );
4934         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4935         LostItem( $item->itemnumber, 'cli', 0 );
4936         $item->_result->itemlost(1);
4937         $item->_result->itemlost_on( $lost_on );
4938         $item->_result->update();
4939
4940         my $a = Koha::Account::Lines->search(
4941             {
4942                 itemnumber     => $item->id,
4943                 borrowernumber => $patron->borrowernumber
4944             }
4945         );
4946         $a = $a->next;
4947         ok( $a, "Found accountline for lost fee" );
4948         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4949         my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4950         $a = $a->get_from_storage;
4951         is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4952         $a->delete;
4953     };
4954 };
4955
4956 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
4957
4958     plan tests => 4;
4959
4960     t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4961     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4962     my $patron  = $builder->build_object(
4963         {
4964             class => 'Koha::Patrons',
4965             value => { categorycode => $patron_category->{categorycode} }
4966         }
4967     );
4968     my $patron2  = $builder->build_object(
4969         {
4970             class => 'Koha::Patrons',
4971             value => { categorycode => $patron_category->{categorycode} }
4972         }
4973     );
4974
4975     my $biblionumber = $builder->build_sample_biblio(
4976         {
4977             branchcode => $library->branchcode,
4978         }
4979     )->biblionumber;
4980
4981     # And the circulation rule
4982     Koha::CirculationRules->search->delete;
4983     Koha::CirculationRules->set_rules(
4984         {
4985             categorycode => undef,
4986             itemtype     => undef,
4987             branchcode   => undef,
4988             rules        => {
4989                 issuelength => 14,
4990                 lengthunit  => 'days',
4991             }
4992         }
4993     );
4994     $builder->build(
4995         {
4996             source => 'CirculationRule',
4997             value  => {
4998                 branchcode   => undef,
4999                 categorycode => undef,
5000                 itemtype     => undef,
5001                 rule_name    => 'lostreturn',
5002                 rule_value   => 'refund'
5003             }
5004         }
5005     );
5006
5007     subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5008         plan tests => 3;
5009
5010         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
5011         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5012
5013         my $lost_on = dt_from_string->subtract( days => 7 )->date;
5014
5015         my $item = $builder->build_sample_item(
5016             {
5017                 biblionumber     => $biblionumber,
5018                 library          => $library->branchcode,
5019                 replacementprice => '42',
5020             }
5021         );
5022         my $issue = AddIssue( $patron->unblessed, $item->barcode );
5023         LostItem( $item->itemnumber, 'cli', 0 );
5024         $item->_result->itemlost(1);
5025         $item->_result->itemlost_on( $lost_on );
5026         $item->_result->update();
5027
5028         my $a = Koha::Account::Lines->search(
5029             {
5030                 itemnumber     => $item->id,
5031                 borrowernumber => $patron->borrowernumber
5032             }
5033         )->next;
5034         ok( $a, "Found accountline for lost fee" );
5035         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5036         $issue = AddIssue( $patron2->unblessed, $item->barcode );
5037         $a = $a->get_from_storage;
5038         is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5039         $a->delete;
5040         $issue->delete;
5041     };
5042
5043     subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5044         plan tests => 3;
5045
5046         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
5047         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5048
5049         my $lost_on = dt_from_string->subtract( days => 6 )->date;
5050
5051         my $item = $builder->build_sample_item(
5052             {
5053                 biblionumber     => $biblionumber,
5054                 library          => $library->branchcode,
5055                 replacementprice => '42',
5056             }
5057         );
5058         my $issue = AddIssue( $patron->unblessed, $item->barcode );
5059         LostItem( $item->itemnumber, 'cli', 0 );
5060         $item->_result->itemlost(1);
5061         $item->_result->itemlost_on( $lost_on );
5062         $item->_result->update();
5063
5064         my $a = Koha::Account::Lines->search(
5065             {
5066                 itemnumber     => $item->id,
5067                 borrowernumber => $patron->borrowernumber
5068             }
5069         )->next;
5070         ok( $a, "Found accountline for lost fee" );
5071         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5072         $issue = AddIssue( $patron2->unblessed, $item->barcode );
5073         $a = $a->get_from_storage;
5074         is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5075         $a->delete;
5076     };
5077
5078     subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5079         plan tests => 3;
5080
5081         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
5082         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5083
5084         my $lost_on = dt_from_string->subtract( days => 7 )->date;
5085
5086         my $item = $builder->build_sample_item(
5087             {
5088                 biblionumber     => $biblionumber,
5089                 library          => $library->branchcode,
5090                 replacementprice => '42',
5091             }
5092         );
5093         my $issue = AddIssue( $patron->unblessed, $item->barcode );
5094         LostItem( $item->itemnumber, 'cli', 0 );
5095         $item->_result->itemlost(1);
5096         $item->_result->itemlost_on( $lost_on );
5097         $item->_result->update();
5098
5099         my $a = Koha::Account::Lines->search(
5100             {
5101                 itemnumber     => $item->id,
5102                 borrowernumber => $patron->borrowernumber
5103             }
5104         )->next;
5105         ok( $a, "Found accountline for lost fee" );
5106         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5107         $issue = AddIssue( $patron2->unblessed, $item->barcode );
5108         $a = $a->get_from_storage;
5109         is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5110         $a->delete;
5111     };
5112
5113     subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5114         plan tests => 3;
5115
5116         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
5117         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5118
5119         my $lost_on = dt_from_string->subtract( days => 8 )->date;
5120
5121         my $item = $builder->build_sample_item(
5122             {
5123                 biblionumber     => $biblionumber,
5124                 library          => $library->branchcode,
5125                 replacementprice => '42',
5126             }
5127         );
5128         my $issue = AddIssue( $patron->unblessed, $item->barcode );
5129         LostItem( $item->itemnumber, 'cli', 0 );
5130         $item->_result->itemlost(1);
5131         $item->_result->itemlost_on( $lost_on );
5132         $item->_result->update();
5133
5134         my $a = Koha::Account::Lines->search(
5135             {
5136                 itemnumber     => $item->id,
5137                 borrowernumber => $patron->borrowernumber
5138             }
5139         );
5140         $a = $a->next;
5141         ok( $a, "Found accountline for lost fee" );
5142         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5143         $issue = AddIssue( $patron2->unblessed, $item->barcode );
5144         $a = $a->get_from_storage;
5145         is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5146         $a->delete;
5147     };
5148 };
5149
5150 subtest 'transferbook tests' => sub {
5151     plan tests => 9;
5152
5153     throws_ok
5154     { C4::Circulation::transferbook({}); }
5155     'Koha::Exceptions::MissingParameter',
5156     'Koha::Patron->store raises an exception on missing params';
5157
5158     throws_ok
5159     { C4::Circulation::transferbook({to_branch=>'anything'}); }
5160     'Koha::Exceptions::MissingParameter',
5161     'Koha::Patron->store raises an exception on missing params';
5162
5163     throws_ok
5164     { C4::Circulation::transferbook({from_branch=>'anything'}); }
5165     'Koha::Exceptions::MissingParameter',
5166     'Koha::Patron->store raises an exception on missing params';
5167
5168     my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
5169     is( $doreturn, 0, "No return without barcode");
5170     ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5171     is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
5172
5173     ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
5174     is( $doreturn, 0, "No return without barcode");
5175     ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5176     is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
5177
5178 };
5179
5180 subtest 'Checkout should correctly terminate a transfer' => sub {
5181     plan tests => 7;
5182
5183     my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5184     my $patron_1 = $builder->build_object(
5185         {
5186             class => 'Koha::Patrons',
5187             value => { branchcode => $library_1->branchcode }
5188         }
5189     );
5190     my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
5191     my $patron_2 = $builder->build_object(
5192         {
5193             class => 'Koha::Patrons',
5194             value => { branchcode => $library_2->branchcode }
5195         }
5196     );
5197
5198     my $item = $builder->build_sample_item(
5199         {
5200             library => $library_1->branchcode,
5201         }
5202     );
5203
5204     t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
5205     my $reserve_id = AddReserve(
5206         {
5207             branchcode     => $library_2->branchcode,
5208             borrowernumber => $patron_2->borrowernumber,
5209             biblionumber   => $item->biblionumber,
5210             itemnumber     => $item->itemnumber,
5211             priority       => 1,
5212         }
5213     );
5214
5215     my $do_transfer = 1;
5216     ModItemTransfer( $item->itemnumber, $library_1->branchcode,
5217         $library_2->branchcode, 'Manual' );
5218     ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
5219     GetOtherReserves( $item->itemnumber )
5220       ;    # To put the Reason, it's what does returns.pl...
5221     my $hold = Koha::Holds->find($reserve_id);
5222     is( $hold->found, 'T', 'Hold is in transit' );
5223     my $transfer = $item->get_transfer;
5224     is( $transfer->frombranch, $library_1->branchcode );
5225     is( $transfer->tobranch,   $library_2->branchcode );
5226     is( $transfer->reason,     'Reserve' );
5227
5228     t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
5229     AddIssue( $patron_1->unblessed, $item->barcode );
5230     $transfer = $transfer->get_from_storage;
5231     isnt( $transfer->datearrived, undef );
5232     $hold = $hold->get_from_storage;
5233     is( $hold->found, undef, 'Hold is waiting' );
5234     is( $hold->priority, 1, );
5235 };
5236
5237 subtest 'AddIssue records staff who checked out item if appropriate' => sub  {
5238     plan tests => 2;
5239
5240     $module->mock( 'userenv', sub { { branch => $library->{id} } } );
5241
5242     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5243     my $patron = $builder->build_object(
5244         {
5245             class => 'Koha::Patrons',
5246             value => { categorycode => $patron_category->{categorycode} }
5247         }
5248     );
5249     my $issuer = $builder->build_object(
5250         {
5251             class => 'Koha::Patrons',
5252             value => { categorycode => $patron_category->{categorycode} }
5253         }
5254     );
5255     my $item = $builder->build_sample_item(
5256         {
5257             library  => $library->{branchcode}
5258         }
5259     );
5260
5261     $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->{borrowernumber} } } );
5262
5263     my $dt_from = dt_from_string();
5264     my $dt_to   = dt_from_string()->add( days => 7 );
5265
5266     my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
5267
5268     is( $issue->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
5269
5270     t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
5271
5272     my $issue2 =
5273       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
5274
5275     is( $issue->issuer, $issuer->{borrowernumber}, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
5276 };
5277
5278 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
5279     plan tests => 2;
5280
5281     my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5282     my $patron_1 = $builder->build_object(
5283         {
5284             class => 'Koha::Patrons',
5285             value => { branchcode => $library_1->branchcode }
5286         }
5287     );
5288     my $patron_2 = $builder->build_object(
5289         {
5290             class => 'Koha::Patrons',
5291             value => { branchcode => $library_1->branchcode }
5292         }
5293     );
5294
5295     my $item = $builder->build_sample_item(
5296         {
5297             library => $library_1->branchcode,
5298         }
5299     );
5300
5301     AddIssue( $patron_1->unblessed, $item->barcode );
5302     ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
5303     AddIssue( $patron_2->unblessed, $item->barcode );
5304     ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
5305 };
5306
5307 subtest "updateWrongTransfer tests" => sub {
5308     plan tests => 5;
5309
5310     my $library1 = $builder->build_object( { class => 'Koha::Libraries' } );
5311     my $library2 = $builder->build_object( { class => 'Koha::Libraries' } );
5312     my $library3 = $builder->build_object( { class => 'Koha::Libraries' } );
5313     my $item     = $builder->build_sample_item(
5314         {
5315             homebranch    => $library1->branchcode,
5316             holdingbranch => $library2->branchcode,
5317             datelastseen  => undef
5318         }
5319     );
5320
5321     my $transfer = $builder->build_object(
5322         {
5323             class => 'Koha::Item::Transfers',
5324             value => {
5325                 itemnumber    => $item->itemnumber,
5326                 frombranch    => $library2->branchcode,
5327                 tobranch      => $library1->branchcode,
5328                 daterequested => dt_from_string,
5329                 datesent      => dt_from_string,
5330                 datecancelled => undef,
5331                 datearrived   => undef,
5332                 reason        => 'Manual'
5333             }
5334         }
5335     );
5336     is( ref($transfer), 'Koha::Item::Transfer', 'Mock transfer added' );
5337
5338     my $new_transfer = C4::Circulation::updateWrongTransfer($item->itemnumber, $library1->branchcode);
5339     is(ref($new_transfer), 'Koha::Item::Transfer', "updateWrongTransfer returns a 'Koha::Item::Transfer' object");
5340     ok( !$new_transfer->in_transit, "New transfer is NOT created as in transit (or cancelled)");
5341
5342     my $original_transfer = $transfer->get_from_storage;
5343     ok( defined($original_transfer->datecancelled), "Original transfer was cancelled");
5344     is( $original_transfer->cancellation_reason, 'WrongTransfer', "Original transfer cancellation reason is 'WrongTransfer'");
5345 };
5346
5347 subtest "SendCirculationAlert" => sub {
5348     plan tests => 2;
5349
5350     # When you would unsuspectingly call this unit test (with perl, not prove), you will be bitten by LOCK.
5351     # LOCK will commit changes and ruin your data
5352     # In order to prevent that, we will add KOHA_TESTING to $ENV; see further Circulation.pm
5353     $ENV{KOHA_TESTING} = 1;
5354
5355     # Setup branch, borrowr, and notice
5356     my $library = $builder->build_object({ class => 'Koha::Libraries' });
5357     set_userenv( $library->unblessed);
5358     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5359     C4::Members::Messaging::SetMessagingPreference({
5360         borrowernumber => $patron->id,
5361         message_transport_types => ['email'],
5362         message_attribute_id => 5
5363     });
5364     my $item = $builder->build_sample_item();
5365     my $checkin_notice = $builder->build_object({
5366         class => 'Koha::Notice::Templates',
5367         value =>{
5368             module => 'circulation',
5369             code => 'CHECKIN',
5370             branchcode => $library->branchcode,
5371             name => 'Test Checkin',
5372             is_html => 0,
5373             content => "Checkins:\n----\n[% biblio.title %]-[% old_checkout.issue_id %]\n----Thank you.",
5374             message_transport_type => 'email',
5375             lang => 'default'
5376         }
5377     })->store;
5378
5379     # Checkout an item, mark it returned, generate a notice
5380     my $issue_1 = AddIssue( $patron->unblessed, $item->barcode);
5381     MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5382     C4::Circulation::SendCirculationAlert({
5383         type => 'CHECKIN',
5384         item => $item->unblessed,
5385         borrower => $patron->unblessed,
5386         branch => $library->branchcode,
5387         issue => $issue_1
5388     });
5389     my $notice = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'CHECKIN' });
5390     is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\nThank you.", 'Letter generated with expected output on first checkin' );
5391
5392     # Checkout an item, mark it returned, generate a notice
5393     my $issue_2 = AddIssue( $patron->unblessed, $item->barcode);
5394     MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5395     C4::Circulation::SendCirculationAlert({
5396         type => 'CHECKIN',
5397         item => $item->unblessed,
5398         borrower => $patron->unblessed,
5399         branch => $library->branchcode,
5400         issue => $issue_2
5401     });
5402     $notice->discard_changes();
5403     is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\n".$item->biblio->title."-".$issue_2->id."\nThank you.", 'Letter appended with expected output on second checkin' );
5404
5405 };
5406
5407 subtest "GetSoonestRenewDate tests" => sub {
5408     plan tests => 5;
5409     Koha::CirculationRules->set_rule(
5410         {
5411             categorycode => undef,
5412             branchcode   => undef,
5413             itemtype     => undef,
5414             rule_name    => 'norenewalbefore',
5415             rule_value   => '7',
5416         }
5417     );
5418     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5419     my $item = $builder->build_sample_item();
5420     my $issue = AddIssue( $patron->unblessed, $item->barcode);
5421     my $datedue = dt_from_string( $issue->date_due() );
5422
5423     # Bug 14395
5424     # Test 'exact time' setting for syspref NoRenewalBeforePrecision
5425     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
5426     is(
5427         GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5428         $datedue->clone->add( days => -7 ),
5429         'Bug 14395: Renewals permitted 7 days before due date, as expected'
5430     );
5431
5432     # Bug 14395
5433     # Test 'date' setting for syspref NoRenewalBeforePrecision
5434     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5435     is(
5436         GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5437         $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
5438         'Bug 14395: Renewals permitted 7 days before due date, as expected'
5439     );
5440
5441
5442     Koha::CirculationRules->set_rule(
5443         {
5444             categorycode => undef,
5445             branchcode   => undef,
5446             itemtype     => undef,
5447             rule_name    => 'norenewalbefore',
5448             rule_value   => undef,
5449         }
5450     );
5451
5452     is(
5453         GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5454         dt_from_string,
5455         'Checkouts without auto-renewal can be renewed immediately if no norenewalbefore'
5456     );
5457
5458     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5459     $issue->auto_renew(1)->store;
5460     is(
5461         GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5462         $datedue->clone->truncate( to => 'day' ),
5463         'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5464     );
5465     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact' );
5466     is(
5467         GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5468         $datedue,
5469         'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5470     );
5471 };
5472
5473 $schema->storage->txn_rollback;
5474 C4::Context->clear_syspref_cache();
5475 $branches = Koha::Libraries->search();
5476 for my $branch ( $branches->next ) {
5477     my $key = $branch->branchcode . "_holidays";
5478     $cache->clear_from_cache($key);
5479 }