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