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