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