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