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