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