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