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