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