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