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