Bug 19532: (follow-up) aria-hidden attr on OPAC, and more
[koha.git] / t / db_dependent / Circulation.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19 use utf8;
20
21 use Test::More tests => 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         status => 'R',
1459     })->store;
1460     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1461     is( $error, 'recalled', 'Cannot renew item that has been recalled' );
1462     $recall->set_cancelled;
1463
1464     # biblio-level requested recall: renewal not allowed
1465     $recall = Koha::Recall->new({
1466         biblionumber => $recall_item1->biblionumber,
1467         itemnumber => undef,
1468         borrowernumber => $recall_borrower->borrowernumber,
1469         branchcode => $recall_borrower->branchcode,
1470         item_level_recall => 0,
1471         status => 'R',
1472     })->store;
1473     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1474     is( $error, 'recalled', 'Cannot renew item if biblio is recalled and has no item allocated' );
1475     $recall->set_cancelled;
1476
1477     # item-level and not this item: renewal allowed
1478     $recall = Koha::Recall->new({
1479         biblionumber => $recall_item2->biblionumber,
1480         itemnumber => $recall_item2->itemnumber,
1481         borrowernumber => $recall_borrower->borrowernumber,
1482         branchcode => $recall_borrower->branchcode,
1483         item_level_recall => 1,
1484         status => 'R',
1485     })->store;
1486     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1487     is( $renewokay, 1, 'Can renew item if item-level recall on biblio is not on this item' );
1488     $recall->set_cancelled;
1489
1490     # biblio-level waiting recall: renewal allowed
1491     $recall = Koha::Recall->new({
1492         biblionumber => $recall_item1->biblionumber,
1493         itemnumber => undef,
1494         borrowernumber => $recall_borrower->borrowernumber,
1495         branchcode => $recall_borrower->branchcode,
1496         item_level_recall => 0,
1497         status => 'R',
1498     })->store;
1499     $recall->set_waiting({ item => $recall_item1 });
1500     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1501     is( $renewokay, 1, 'Can renew item if biblio-level recall has already been allocated an item' );
1502     $recall->set_cancelled;
1503 };
1504
1505 subtest "GetUpcomingDueIssues" => sub {
1506     plan tests => 12;
1507
1508     my $branch   = $library2->{branchcode};
1509
1510     #Create another record
1511     my $biblio2 = $builder->build_sample_biblio();
1512
1513     #Create third item
1514     my $item_1 = Koha::Items->find($reused_itemnumber_1);
1515     my $item_2 = Koha::Items->find($reused_itemnumber_2);
1516     my $item_3 = $builder->build_sample_item(
1517         {
1518             biblionumber     => $biblio2->biblionumber,
1519             library          => $branch,
1520             itype            => $itemtype,
1521         }
1522     );
1523
1524
1525     # Create a borrower
1526     my %a_borrower_data = (
1527         firstname =>  'Fridolyn',
1528         surname => 'SOMERS',
1529         categorycode => $patron_category->{categorycode},
1530         branchcode => $branch,
1531     );
1532
1533     my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1534     my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1535
1536     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1537     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1538     my $today = DateTime->today(time_zone => C4::Context->tz());
1539
1540     my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1541     my $datedue = dt_from_string( $issue->date_due() );
1542     my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1543     my $datedue2 = dt_from_string( $issue->date_due() );
1544
1545     my $upcoming_dues;
1546
1547     # GetUpcomingDueIssues tests
1548     for my $i(0..1) {
1549         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1550         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1551     }
1552
1553     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1554     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1555     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1556
1557     for my $i(3..5) {
1558         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1559         is ( scalar( @$upcoming_dues ), 1,
1560             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1561     }
1562
1563     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1564
1565     my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1566
1567     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1568     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1569
1570     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1571     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1572
1573     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1574     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1575
1576     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
1577     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1578
1579     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1580     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1581
1582     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1583     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1584
1585 };
1586
1587 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1588     my $branch   = $library2->{branchcode};
1589
1590     my $biblio = $builder->build_sample_biblio();
1591
1592     #Create third item
1593     my $item = $builder->build_sample_item(
1594         {
1595             biblionumber     => $biblio->biblionumber,
1596             library          => $branch,
1597             itype            => $itemtype,
1598         }
1599     );
1600
1601     # Create a borrower
1602     my %a_borrower_data = (
1603         firstname =>  'Kyle',
1604         surname => 'Hall',
1605         categorycode => $patron_category->{categorycode},
1606         branchcode => $branch,
1607     );
1608
1609     my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1610
1611     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1612     my $issue = AddIssue( $borrower, $item->barcode );
1613     UpdateFine(
1614         {
1615             issue_id       => $issue->id(),
1616             itemnumber     => $item->itemnumber,
1617             borrowernumber => $borrowernumber,
1618             amount         => 0,
1619             type           => q{}
1620         }
1621     );
1622
1623     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1624     my $count = $hr->{count};
1625
1626     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1627 };
1628
1629 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1630     $dbh->do('DELETE FROM issues');
1631     $dbh->do('DELETE FROM items');
1632     $dbh->do('DELETE FROM circulation_rules');
1633     Koha::CirculationRules->set_rules(
1634         {
1635             categorycode => undef,
1636             itemtype     => undef,
1637             branchcode   => undef,
1638             rules        => {
1639                 reservesallowed => 25,
1640                 issuelength     => 14,
1641                 lengthunit      => 'days',
1642                 renewalsallowed => 1,
1643                 renewalperiod   => 7,
1644                 norenewalbefore => undef,
1645                 auto_renew      => 0,
1646                 fine            => .10,
1647                 chargeperiod    => 1,
1648                 maxissueqty     => 20
1649             }
1650         }
1651     );
1652     my $biblio = $builder->build_sample_biblio();
1653
1654     my $item_1 = $builder->build_sample_item(
1655         {
1656             biblionumber     => $biblio->biblionumber,
1657             library          => $library2->{branchcode},
1658             itype            => $itemtype,
1659         }
1660     );
1661
1662     my $item_2= $builder->build_sample_item(
1663         {
1664             biblionumber     => $biblio->biblionumber,
1665             library          => $library2->{branchcode},
1666             itype            => $itemtype,
1667         }
1668     );
1669
1670     my $borrowernumber1 = Koha::Patron->new({
1671         firstname    => 'Kyle',
1672         surname      => 'Hall',
1673         categorycode => $patron_category->{categorycode},
1674         branchcode   => $library2->{branchcode},
1675     })->store->borrowernumber;
1676     my $borrowernumber2 = Koha::Patron->new({
1677         firstname    => 'Chelsea',
1678         surname      => 'Hall',
1679         categorycode => $patron_category->{categorycode},
1680         branchcode   => $library2->{branchcode},
1681     })->store->borrowernumber;
1682
1683     my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1684     my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1685
1686     my $issue = AddIssue( $borrower1, $item_1->barcode );
1687
1688     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1689     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1690
1691     AddReserve(
1692         {
1693             branchcode     => $library2->{branchcode},
1694             borrowernumber => $borrowernumber2,
1695             biblionumber   => $biblio->biblionumber,
1696             priority       => 1,
1697         }
1698     );
1699
1700     Koha::CirculationRules->set_rules(
1701         {
1702             categorycode => undef,
1703             itemtype     => undef,
1704             branchcode   => undef,
1705             rules        => {
1706                 onshelfholds => 0,
1707             }
1708         }
1709     );
1710     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1711     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1712     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1713
1714     Koha::CirculationRules->set_rules(
1715         {
1716             categorycode => undef,
1717             itemtype     => undef,
1718             branchcode   => undef,
1719             rules        => {
1720                 onshelfholds => 0,
1721             }
1722         }
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     => undef,
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     Koha::CirculationRules->set_rules(
1743         {
1744             categorycode => undef,
1745             itemtype     => undef,
1746             branchcode   => undef,
1747             rules        => {
1748                 onshelfholds => 1,
1749             }
1750         }
1751     );
1752     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1753     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1754     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1755
1756     # Setting item not checked out to be not for loan but holdable
1757     $item_2->notforloan(-1)->store;
1758
1759     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1760     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' );
1761 };
1762
1763 {
1764     # Don't allow renewing onsite checkout
1765     my $branch   = $library->{branchcode};
1766
1767     #Create another record
1768     my $biblio = $builder->build_sample_biblio();
1769
1770     my $item = $builder->build_sample_item(
1771         {
1772             biblionumber     => $biblio->biblionumber,
1773             library          => $branch,
1774             itype            => $itemtype,
1775         }
1776     );
1777
1778     my $borrowernumber = Koha::Patron->new({
1779         firstname =>  'fn',
1780         surname => 'dn',
1781         categorycode => $patron_category->{categorycode},
1782         branchcode => $branch,
1783     })->store->borrowernumber;
1784
1785     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1786
1787     my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1788     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1789     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1790     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1791 }
1792
1793 {
1794     my $library = $builder->build({ source => 'Branch' });
1795
1796     my $biblio = $builder->build_sample_biblio();
1797
1798     my $item = $builder->build_sample_item(
1799         {
1800             biblionumber     => $biblio->biblionumber,
1801             library          => $library->{branchcode},
1802             itype            => $itemtype,
1803         }
1804     );
1805
1806     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1807
1808     my $issue = AddIssue( $patron, $item->barcode );
1809     UpdateFine(
1810         {
1811             issue_id       => $issue->id(),
1812             itemnumber     => $item->itemnumber,
1813             borrowernumber => $patron->{borrowernumber},
1814             amount         => 1,
1815             type           => q{}
1816         }
1817     );
1818     UpdateFine(
1819         {
1820             issue_id       => $issue->id(),
1821             itemnumber     => $item->itemnumber,
1822             borrowernumber => $patron->{borrowernumber},
1823             amount         => 2,
1824             type           => q{}
1825         }
1826     );
1827     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1828 }
1829
1830 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1831     plan tests => 24;
1832
1833     my $homebranch    = $builder->build( { source => 'Branch' } );
1834     my $holdingbranch = $builder->build( { source => 'Branch' } );
1835     my $otherbranch   = $builder->build( { source => 'Branch' } );
1836     my $patron_1      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1837     my $patron_2      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1838
1839     my $item = $builder->build_sample_item(
1840         {
1841             homebranch    => $homebranch->{branchcode},
1842             holdingbranch => $holdingbranch->{branchcode},
1843         }
1844     );
1845
1846     set_userenv($holdingbranch);
1847
1848     my $issue = AddIssue( $patron_1->unblessed, $item->barcode );
1849     is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1850
1851     my ( $error, $question, $alerts );
1852
1853     # AllowReturnToBranch == anywhere
1854     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1855     ## Test that unknown barcodes don't generate internal server errors
1856     set_userenv($homebranch);
1857     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1858     ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1859     ## Can be issued from homebranch
1860     set_userenv($homebranch);
1861     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1862     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1863     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1864     ## Can be issued from holdingbranch
1865     set_userenv($holdingbranch);
1866     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1867     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1868     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1869     ## Can be issued from another branch
1870     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1871     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1872     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1873
1874     # AllowReturnToBranch == holdingbranch
1875     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1876     ## Cannot be issued from homebranch
1877     set_userenv($homebranch);
1878     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1879     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1880     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1881     is( $error->{branch_to_return},         $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1882     ## Can be issued from holdinbranch
1883     set_userenv($holdingbranch);
1884     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1885     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1886     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1887     ## Cannot be issued from another branch
1888     set_userenv($otherbranch);
1889     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1890     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1891     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1892     is( $error->{branch_to_return},         $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
1893
1894     # AllowReturnToBranch == homebranch
1895     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1896     ## Can be issued from holdinbranch
1897     set_userenv($homebranch);
1898     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1899     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1900     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1901     ## Cannot be issued from holdinbranch
1902     set_userenv($holdingbranch);
1903     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1904     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1905     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1906     is( $error->{branch_to_return},         $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1907     ## Cannot be issued from holdinbranch
1908     set_userenv($otherbranch);
1909     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1910     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1911     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1912     is( $error->{branch_to_return},         $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1913
1914     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1915 };
1916
1917 subtest 'AddIssue & AllowReturnToBranch' => sub {
1918     plan tests => 9;
1919
1920     my $homebranch    = $builder->build( { source => 'Branch' } );
1921     my $holdingbranch = $builder->build( { source => 'Branch' } );
1922     my $otherbranch   = $builder->build( { source => 'Branch' } );
1923     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1924     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1925
1926     my $item = $builder->build_sample_item(
1927         {
1928             homebranch    => $homebranch->{branchcode},
1929             holdingbranch => $holdingbranch->{branchcode},
1930         }
1931     );
1932
1933     set_userenv($holdingbranch);
1934
1935     my $ref_issue = 'Koha::Checkout';
1936     my $issue = AddIssue( $patron_1, $item->barcode );
1937
1938     my ( $error, $question, $alerts );
1939
1940     # AllowReturnToBranch == homebranch
1941     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1942     ## Can be issued from homebranch
1943     set_userenv($homebranch);
1944     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
1945     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1946     ## Can be issued from holdinbranch
1947     set_userenv($holdingbranch);
1948     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
1949     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1950     ## Can be issued from another branch
1951     set_userenv($otherbranch);
1952     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
1953     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1954
1955     # AllowReturnToBranch == holdinbranch
1956     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1957     ## Cannot be issued from homebranch
1958     set_userenv($homebranch);
1959     is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
1960     ## Can be issued from holdingbranch
1961     set_userenv($holdingbranch);
1962     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
1963     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1964     ## Cannot be issued from another branch
1965     set_userenv($otherbranch);
1966     is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
1967
1968     # AllowReturnToBranch == homebranch
1969     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1970     ## Can be issued from homebranch
1971     set_userenv($homebranch);
1972     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
1973     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1974     ## Cannot be issued from holdinbranch
1975     set_userenv($holdingbranch);
1976     is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
1977     ## Cannot be issued from another branch
1978     set_userenv($otherbranch);
1979     is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
1980     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1981 };
1982
1983 subtest 'AddIssue | recalls' => sub {
1984     plan tests => 3;
1985
1986     t::lib::Mocks::mock_preference("UseRecalls", 1);
1987     t::lib::Mocks::mock_preference("item-level_itypes", 1);
1988     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1989     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1990     my $item = $builder->build_sample_item;
1991     Koha::CirculationRules->set_rules({
1992         branchcode => undef,
1993         itemtype => undef,
1994         categorycode => undef,
1995         rules => {
1996             recalls_allowed => 10,
1997         },
1998     });
1999
2000     # checking out item that they have recalled
2001     my $recall1 = Koha::Recall->new({
2002         borrowernumber => $patron1->borrowernumber,
2003         biblionumber => $item->biblionumber,
2004         itemnumber => $item->itemnumber,
2005         item_level_recall => 1,
2006         branchcode => $patron1->branchcode,
2007         status => 'R',
2008     })->store;
2009     AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall1->recall_id } );
2010     $recall1 = Koha::Recalls->find( $recall1->recall_id );
2011     is( $recall1->finished, 1, 'Recall was fulfilled when patron checked out item' );
2012     AddReturn( $item->barcode, $item->homebranch );
2013
2014     # this item is has a recall request. cancel recall
2015     my $recall2 = Koha::Recall->new({
2016         borrowernumber => $patron2->borrowernumber,
2017         biblionumber => $item->biblionumber,
2018         itemnumber => $item->itemnumber,
2019         item_level_recall => 1,
2020         branchcode => $patron2->branchcode,
2021         status => 'R',
2022     })->store;
2023     AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall2->recall_id, cancel_recall => 'cancel' } );
2024     $recall2 = Koha::Recalls->find( $recall2->recall_id );
2025     is( $recall2->cancelled, 1, 'Recall was cancelled when patron checked out item' );
2026     AddReturn( $item->barcode, $item->homebranch );
2027
2028     # this item is waiting to fulfill a recall. revert recall
2029     my $recall3 = Koha::Recall->new({
2030         borrowernumber => $patron2->borrowernumber,
2031         biblionumber => $item->biblionumber,
2032         itemnumber => $item->itemnumber,
2033         item_level_recall => 1,
2034         branchcode => $patron2->branchcode,
2035         status => 'R',
2036     })->store;
2037     $recall3->set_waiting;
2038     AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall3->recall_id, cancel_recall => 'revert' } );
2039     $recall3 = Koha::Recalls->find( $recall3->recall_id );
2040     is( $recall3->requested, 1, 'Recall was reverted from waiting when patron checked out item' );
2041     AddReturn( $item->barcode, $item->homebranch );
2042 };
2043
2044
2045 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
2046     plan tests => 8;
2047
2048     my $library = $builder->build( { source => 'Branch' } );
2049     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2050     my $item_1 = $builder->build_sample_item(
2051         {
2052             library => $library->{branchcode},
2053         }
2054     );
2055     my $item_2 = $builder->build_sample_item(
2056         {
2057             library => $library->{branchcode},
2058         }
2059     );
2060
2061     my ( $error, $question, $alerts );
2062
2063     # Patron cannot issue item_1, they have overdues
2064     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
2065     my $issue = AddIssue( $patron->unblessed, $item_1->barcode, $yesterday );    # Add an overdue
2066
2067     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
2068     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2069     is( keys(%$error) + keys(%$alerts),  0, 'No key for error and alert' . str($error, $question, $alerts) );
2070     is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
2071
2072     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
2073     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2074     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
2075     is( $error->{USERBLOCKEDOVERDUE},      1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
2076
2077     # Patron cannot issue item_1, they are debarred
2078     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
2079     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
2080     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2081     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
2082     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
2083
2084     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
2085     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2086     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
2087     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
2088 };
2089
2090 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
2091     plan tests => 1;
2092
2093     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2094     my $patron_category_x = $builder->build_object(
2095         {
2096             class => 'Koha::Patron::Categories',
2097             value => { category_type => 'X' }
2098         }
2099     );
2100     my $patron = $builder->build_object(
2101         {
2102             class => 'Koha::Patrons',
2103             value => {
2104                 categorycode  => $patron_category_x->categorycode,
2105                 gonenoaddress => undef,
2106                 lost          => undef,
2107                 debarred      => undef,
2108                 borrowernotes => ""
2109             }
2110         }
2111     );
2112     my $item_1 = $builder->build_sample_item(
2113         {
2114             library => $library->{branchcode},
2115         }
2116     );
2117
2118     my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
2119     is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
2120
2121     # TODO There are other tests to provide here
2122 };
2123
2124 subtest 'MultipleReserves' => sub {
2125     plan tests => 3;
2126
2127     my $biblio = $builder->build_sample_biblio();
2128
2129     my $branch = $library2->{branchcode};
2130
2131     my $item_1 = $builder->build_sample_item(
2132         {
2133             biblionumber     => $biblio->biblionumber,
2134             library          => $branch,
2135             replacementprice => 12.00,
2136             itype            => $itemtype,
2137         }
2138     );
2139
2140     my $item_2 = $builder->build_sample_item(
2141         {
2142             biblionumber     => $biblio->biblionumber,
2143             library          => $branch,
2144             replacementprice => 12.00,
2145             itype            => $itemtype,
2146         }
2147     );
2148
2149     my $bibitems       = '';
2150     my $priority       = '1';
2151     my $resdate        = undef;
2152     my $expdate        = undef;
2153     my $notes          = '';
2154     my $checkitem      = undef;
2155     my $found          = undef;
2156
2157     my %renewing_borrower_data = (
2158         firstname =>  'John',
2159         surname => 'Renewal',
2160         categorycode => $patron_category->{categorycode},
2161         branchcode => $branch,
2162     );
2163     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
2164     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
2165     my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
2166     my $datedue = dt_from_string( $issue->date_due() );
2167     is (defined $issue->date_due(), 1, "item 1 checked out");
2168     my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
2169
2170     my %reserving_borrower_data1 = (
2171         firstname =>  'Katrin',
2172         surname => 'Reservation',
2173         categorycode => $patron_category->{categorycode},
2174         branchcode => $branch,
2175     );
2176     my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
2177     AddReserve(
2178         {
2179             branchcode       => $branch,
2180             borrowernumber   => $reserving_borrowernumber1,
2181             biblionumber     => $biblio->biblionumber,
2182             priority         => $priority,
2183             reservation_date => $resdate,
2184             expiration_date  => $expdate,
2185             notes            => $notes,
2186             itemnumber       => $checkitem,
2187             found            => $found,
2188         }
2189     );
2190
2191     my %reserving_borrower_data2 = (
2192         firstname =>  'Kirk',
2193         surname => 'Reservation',
2194         categorycode => $patron_category->{categorycode},
2195         branchcode => $branch,
2196     );
2197     my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
2198     AddReserve(
2199         {
2200             branchcode       => $branch,
2201             borrowernumber   => $reserving_borrowernumber2,
2202             biblionumber     => $biblio->biblionumber,
2203             priority         => $priority,
2204             reservation_date => $resdate,
2205             expiration_date  => $expdate,
2206             notes            => $notes,
2207             itemnumber       => $checkitem,
2208             found            => $found,
2209         }
2210     );
2211
2212     {
2213         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2214         is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2215     }
2216
2217     my $item_3 = $builder->build_sample_item(
2218         {
2219             biblionumber     => $biblio->biblionumber,
2220             library          => $branch,
2221             replacementprice => 12.00,
2222             itype            => $itemtype,
2223         }
2224     );
2225
2226     {
2227         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2228         is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2229     }
2230 };
2231
2232 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2233     plan tests => 5;
2234
2235     my $library = $builder->build( { source => 'Branch' } );
2236     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2237
2238     my $biblionumber = $builder->build_sample_biblio(
2239         {
2240             branchcode => $library->{branchcode},
2241         }
2242     )->biblionumber;
2243     my $item_1 = $builder->build_sample_item(
2244         {
2245             biblionumber => $biblionumber,
2246             library      => $library->{branchcode},
2247         }
2248     );
2249
2250     my $item_2 = $builder->build_sample_item(
2251         {
2252             biblionumber => $biblionumber,
2253             library      => $library->{branchcode},
2254         }
2255     );
2256
2257     my ( $error, $question, $alerts );
2258     my $issue = AddIssue( $patron->unblessed, $item_1->barcode, dt_from_string->add( days => 1 ) );
2259
2260     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2261     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2262     cmp_deeply(
2263         { error => $error, alerts => $alerts },
2264         { error => {}, alerts => {} },
2265         'No error or alert should be raised'
2266     );
2267     is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2268
2269     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2270     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2271     cmp_deeply(
2272         { error => $error, question => $question, alerts => $alerts },
2273         { error => {}, question => {}, alerts => {} },
2274         'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2275     );
2276
2277     # Add a subscription
2278     Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2279
2280     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2281     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2282     cmp_deeply(
2283         { error => $error, question => $question, alerts => $alerts },
2284         { error => {}, question => {}, alerts => {} },
2285         'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2286     );
2287
2288     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2289     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2290     cmp_deeply(
2291         { error => $error, question => $question, alerts => $alerts },
2292         { error => {}, question => {}, alerts => {} },
2293         'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2294     );
2295 };
2296
2297 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2298     plan tests => 8;
2299
2300     my $library = $builder->build( { source => 'Branch' } );
2301     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2302
2303     # Add 2 items
2304     my $biblionumber = $builder->build_sample_biblio(
2305         {
2306             branchcode => $library->{branchcode},
2307         }
2308     )->biblionumber;
2309     my $item_1 = $builder->build_sample_item(
2310         {
2311             biblionumber => $biblionumber,
2312             library      => $library->{branchcode},
2313         }
2314     );
2315     my $item_2 = $builder->build_sample_item(
2316         {
2317             biblionumber => $biblionumber,
2318             library      => $library->{branchcode},
2319         }
2320     );
2321
2322     # And the circulation rule
2323     Koha::CirculationRules->search->delete;
2324     Koha::CirculationRules->set_rules(
2325         {
2326             categorycode => undef,
2327             itemtype     => undef,
2328             branchcode   => undef,
2329             rules        => {
2330                 issuelength => 1,
2331                 firstremind => 1,        # 1 day of grace
2332                 finedays    => 2,        # 2 days of fine per day of overdue
2333                 lengthunit  => 'days',
2334             }
2335         }
2336     );
2337
2338     # Patron cannot issue item_1, they have overdues
2339     my $now = dt_from_string;
2340     my $five_days_ago = $now->clone->subtract( days => 5 );
2341     my $ten_days_ago  = $now->clone->subtract( days => 10 );
2342     AddIssue( $patron, $item_1->barcode, $five_days_ago );    # Add an overdue
2343     AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2344       ;    # Add another overdue
2345
2346     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2347     AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2348     my $debarments = Koha::Patron::Debarments::GetDebarments(
2349         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2350     is( scalar(@$debarments), 1 );
2351
2352     # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2353     # Same for the others
2354     my $expected_expiration = output_pref(
2355         {
2356             dt         => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2357             dateformat => 'sql',
2358             dateonly   => 1
2359         }
2360     );
2361     is( $debarments->[0]->{expiration}, $expected_expiration );
2362
2363     AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2364     $debarments = Koha::Patron::Debarments::GetDebarments(
2365         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2366     is( scalar(@$debarments), 1 );
2367     $expected_expiration = output_pref(
2368         {
2369             dt         => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2370             dateformat => 'sql',
2371             dateonly   => 1
2372         }
2373     );
2374     is( $debarments->[0]->{expiration}, $expected_expiration );
2375
2376     Koha::Patron::Debarments::DelUniqueDebarment(
2377         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2378
2379     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2380     AddIssue( $patron, $item_1->barcode, $five_days_ago );    # Add an overdue
2381     AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2382       ;    # Add another overdue
2383     AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2384     $debarments = Koha::Patron::Debarments::GetDebarments(
2385         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2386     is( scalar(@$debarments), 1 );
2387     $expected_expiration = output_pref(
2388         {
2389             dt         => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2390             dateformat => 'sql',
2391             dateonly   => 1
2392         }
2393     );
2394     is( $debarments->[0]->{expiration}, $expected_expiration );
2395
2396     AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2397     $debarments = Koha::Patron::Debarments::GetDebarments(
2398         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2399     is( scalar(@$debarments), 1 );
2400     $expected_expiration = output_pref(
2401         {
2402             dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2403             dateformat => 'sql',
2404             dateonly   => 1
2405         }
2406     );
2407     is( $debarments->[0]->{expiration}, $expected_expiration );
2408 };
2409
2410 subtest 'AddReturn + suspension_chargeperiod' => sub {
2411     plan tests => 27;
2412
2413     my $library = $builder->build( { source => 'Branch' } );
2414     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2415
2416     my $biblionumber = $builder->build_sample_biblio(
2417         {
2418             branchcode => $library->{branchcode},
2419         }
2420     )->biblionumber;
2421     my $item_1 = $builder->build_sample_item(
2422         {
2423             biblionumber => $biblionumber,
2424             library      => $library->{branchcode},
2425         }
2426     );
2427
2428     # And the issuing rule
2429     Koha::CirculationRules->search->delete;
2430     Koha::CirculationRules->set_rules(
2431         {
2432             categorycode => '*',
2433             itemtype     => '*',
2434             branchcode   => '*',
2435             rules        => {
2436                 issuelength => 1,
2437                 firstremind => 0,    # 0 day of grace
2438                 finedays    => 2,    # 2 days of fine per day of overdue
2439                 suspension_chargeperiod => 1,
2440                 lengthunit              => 'days',
2441             }
2442         }
2443     );
2444
2445     my $now = dt_from_string;
2446     my $five_days_ago = $now->clone->subtract( days => 5 );
2447     # We want to charge 2 days every day, without grace
2448     # With 5 days of overdue: 5 * Z
2449     my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2450     test_debarment_on_checkout(
2451         {
2452             item            => $item_1,
2453             library         => $library,
2454             patron          => $patron,
2455             due_date        => $five_days_ago,
2456             expiration_date => $expected_expiration,
2457         }
2458     );
2459
2460     # Same with undef firstremind
2461     Koha::CirculationRules->search->delete;
2462     Koha::CirculationRules->set_rules(
2463         {
2464             categorycode => '*',
2465             itemtype     => '*',
2466             branchcode   => '*',
2467             rules        => {
2468                 issuelength => 1,
2469                 firstremind => undef,    # 0 day of grace
2470                 finedays    => 2,    # 2 days of fine per day of overdue
2471                 suspension_chargeperiod => 1,
2472                 lengthunit              => 'days',
2473             }
2474         }
2475     );
2476     {
2477     my $now = dt_from_string;
2478     my $five_days_ago = $now->clone->subtract( days => 5 );
2479     # We want to charge 2 days every day, without grace
2480     # With 5 days of overdue: 5 * Z
2481     my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2482     test_debarment_on_checkout(
2483         {
2484             item            => $item_1,
2485             library         => $library,
2486             patron          => $patron,
2487             due_date        => $five_days_ago,
2488             expiration_date => $expected_expiration,
2489         }
2490     );
2491     }
2492     # We want to charge 2 days every 2 days, without grace
2493     # With 5 days of overdue: (5 * 2) / 2
2494     Koha::CirculationRules->set_rule(
2495         {
2496             categorycode => undef,
2497             branchcode   => undef,
2498             itemtype     => undef,
2499             rule_name    => 'suspension_chargeperiod',
2500             rule_value   => '2',
2501         }
2502     );
2503
2504     $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2505     test_debarment_on_checkout(
2506         {
2507             item            => $item_1,
2508             library         => $library,
2509             patron          => $patron,
2510             due_date        => $five_days_ago,
2511             expiration_date => $expected_expiration,
2512         }
2513     );
2514
2515     # We want to charge 2 days every 3 days, with 1 day of grace
2516     # With 5 days of overdue: ((5-1) / 3 ) * 2
2517     Koha::CirculationRules->set_rules(
2518         {
2519             categorycode => undef,
2520             branchcode   => undef,
2521             itemtype     => undef,
2522             rules        => {
2523                 suspension_chargeperiod => 3,
2524                 firstremind             => 1,
2525             }
2526         }
2527     );
2528     $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2529     test_debarment_on_checkout(
2530         {
2531             item            => $item_1,
2532             library         => $library,
2533             patron          => $patron,
2534             due_date        => $five_days_ago,
2535             expiration_date => $expected_expiration,
2536         }
2537     );
2538
2539     # Use finesCalendar to know if holiday must be skipped to calculate the due date
2540     # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2541     Koha::CirculationRules->set_rules(
2542         {
2543             categorycode => undef,
2544             branchcode   => undef,
2545             itemtype     => undef,
2546             rules        => {
2547                 finedays                => 2,
2548                 suspension_chargeperiod => 1,
2549                 firstremind             => 0,
2550             }
2551         }
2552     );
2553     t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2554     t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2555
2556     # Adding a holiday 2 days ago
2557     my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2558     my $two_days_ago = $now->clone->subtract( days => 2 );
2559     $calendar->insert_single_holiday(
2560         day             => $two_days_ago->day,
2561         month           => $two_days_ago->month,
2562         year            => $two_days_ago->year,
2563         title           => 'holidayTest-2d',
2564         description     => 'holidayDesc 2 days ago'
2565     );
2566     # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2567     $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2568     test_debarment_on_checkout(
2569         {
2570             item            => $item_1,
2571             library         => $library,
2572             patron          => $patron,
2573             due_date        => $five_days_ago,
2574             expiration_date => $expected_expiration,
2575         }
2576     );
2577
2578     # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2579     my $two_days_ahead = $now->clone->add( days => 2 );
2580     $calendar->insert_single_holiday(
2581         day             => $two_days_ahead->day,
2582         month           => $two_days_ahead->month,
2583         year            => $two_days_ahead->year,
2584         title           => 'holidayTest+2d',
2585         description     => 'holidayDesc 2 days ahead'
2586     );
2587
2588     # Same as above, but we should skip D+2
2589     $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2590     test_debarment_on_checkout(
2591         {
2592             item            => $item_1,
2593             library         => $library,
2594             patron          => $patron,
2595             due_date        => $five_days_ago,
2596             expiration_date => $expected_expiration,
2597         }
2598     );
2599
2600     # Adding another holiday, day of expiration date
2601     my $expected_expiration_dt = dt_from_string($expected_expiration);
2602     $calendar->insert_single_holiday(
2603         day             => $expected_expiration_dt->day,
2604         month           => $expected_expiration_dt->month,
2605         year            => $expected_expiration_dt->year,
2606         title           => 'holidayTest_exp',
2607         description     => 'holidayDesc on expiration date'
2608     );
2609     # Expiration date will be the day after
2610     test_debarment_on_checkout(
2611         {
2612             item            => $item_1,
2613             library         => $library,
2614             patron          => $patron,
2615             due_date        => $five_days_ago,
2616             expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2617         }
2618     );
2619
2620     test_debarment_on_checkout(
2621         {
2622             item            => $item_1,
2623             library         => $library,
2624             patron          => $patron,
2625             return_date     => $now->clone->add(days => 5),
2626             expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2627         }
2628     );
2629
2630     test_debarment_on_checkout(
2631         {
2632             item            => $item_1,
2633             library         => $library,
2634             patron          => $patron,
2635             due_date        => $now->clone->add(days => 1),
2636             return_date     => $now->clone->add(days => 5),
2637             expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2638         }
2639     );
2640
2641 };
2642
2643 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2644     plan tests => 2;
2645
2646     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2647     my $patron1 = $builder->build_object(
2648         {
2649             class => 'Koha::Patrons',
2650             value => {
2651                 library      => $library->branchcode,
2652                 categorycode => $patron_category->{categorycode}
2653             }
2654         }
2655     );
2656     my $patron2 = $builder->build_object(
2657         {
2658             class => 'Koha::Patrons',
2659             value => {
2660                 library      => $library->branchcode,
2661                 categorycode => $patron_category->{categorycode}
2662             }
2663         }
2664     );
2665
2666     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2667
2668     my $item = $builder->build_sample_item(
2669         {
2670             library      => $library->branchcode,
2671         }
2672     );
2673
2674     my ( $error, $question, $alerts );
2675     my $issue = AddIssue( $patron1->unblessed, $item->barcode );
2676
2677     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2678     ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2679     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' );
2680
2681     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2682     ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2683     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' );
2684
2685     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2686 };
2687
2688
2689 subtest 'AddReturn | is_overdue' => sub {
2690     plan tests => 9;
2691
2692     t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2693     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2694     t::lib::Mocks::mock_preference('finesMode', 'production');
2695     t::lib::Mocks::mock_preference('MaxFine', '100');
2696
2697     my $library = $builder->build( { source => 'Branch' } );
2698     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2699     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2700     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2701
2702     my $item = $builder->build_sample_item(
2703         {
2704             library      => $library->{branchcode},
2705             replacementprice => 7
2706         }
2707     );
2708
2709     Koha::CirculationRules->search->delete;
2710     Koha::CirculationRules->set_rules(
2711         {
2712             categorycode => undef,
2713             itemtype     => undef,
2714             branchcode   => undef,
2715             rules        => {
2716                 issuelength  => 6,
2717                 lengthunit   => 'days',
2718                 fine         => 1,        # Charge 1 every day of overdue
2719                 chargeperiod => 1,
2720             }
2721         }
2722     );
2723
2724     my $now   = dt_from_string;
2725     my $one_day_ago   = $now->clone->subtract( days => 1 );
2726     my $two_days_ago  = $now->clone->subtract( days => 2 );
2727     my $five_days_ago = $now->clone->subtract( days => 5 );
2728     my $ten_days_ago  = $now->clone->subtract( days => 10 );
2729     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2730
2731     # No return date specified, today will be used => 10 days overdue charged
2732     AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2733     AddReturn( $item->barcode, $library->{branchcode} );
2734     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2735     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2736
2737     # specify return date 5 days before => no overdue charged
2738     AddIssue( $patron->unblessed, $item->barcode, $five_days_ago ); # date due was 5d ago
2739     AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
2740     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2741     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2742
2743     # specify return date 5 days later => 5 days overdue charged
2744     AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2745     AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
2746     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2747     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2748
2749     # specify return date 5 days later, specify exemptfine => no overdue charge
2750     AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2751     AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago );
2752     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2753     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2754
2755     subtest 'bug 22877 | Lost item return' => sub {
2756
2757         plan tests => 3;
2758
2759         my $issue = AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );    # date due was 10d ago
2760
2761         # Fake fines cronjob on this checkout
2762         my ($fine) =
2763           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2764             $ten_days_ago, $now );
2765         UpdateFine(
2766             {
2767                 issue_id       => $issue->issue_id,
2768                 itemnumber     => $item->itemnumber,
2769                 borrowernumber => $patron->borrowernumber,
2770                 amount         => $fine,
2771                 due            => output_pref($ten_days_ago)
2772             }
2773         );
2774         is( int( $patron->account->balance() ),
2775             10, "Overdue fine of 10 days overdue" );
2776
2777         # Fake longoverdue with charge and not marking returned
2778         LostItem( $item->itemnumber, 'cronjob', 0 );
2779         is( int( $patron->account->balance() ),
2780             17, "Lost fine of 7 plus 10 days overdue" );
2781
2782         # Now we return it today
2783         AddReturn( $item->barcode, $library->{branchcode} );
2784         is( int( $patron->account->balance() ),
2785             17, "Should have a single 10 days overdue fine and lost charge" );
2786
2787         # Cleanup
2788         Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2789     };
2790
2791     subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
2792
2793         plan tests => 17;
2794
2795         t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2796
2797         my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago );    # date due was 1d ago
2798
2799         # Fake fines cronjob on this checkout
2800         my ($fine) =
2801           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2802             $one_day_ago, $now );
2803         UpdateFine(
2804             {
2805                 issue_id       => $issue->issue_id,
2806                 itemnumber     => $item->itemnumber,
2807                 borrowernumber => $patron->borrowernumber,
2808                 amount         => $fine,
2809                 due            => output_pref($one_day_ago)
2810             }
2811         );
2812         is( int( $patron->account->balance() ),
2813             1, "Overdue fine of 1 day overdue" );
2814
2815         # Backdated return (dropbox mode example - charge should be removed)
2816         AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
2817         is( int( $patron->account->balance() ),
2818             0, "Overdue fine should be annulled" );
2819         my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2820         is( $lines->count, 0, "Overdue fine accountline has been removed");
2821
2822         $issue = AddIssue( $patron->unblessed, $item->barcode, $two_days_ago );    # date due was 2d ago
2823
2824         # Fake fines cronjob on this checkout
2825         ($fine) =
2826           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2827             $two_days_ago, $now );
2828         UpdateFine(
2829             {
2830                 issue_id       => $issue->issue_id,
2831                 itemnumber     => $item->itemnumber,
2832                 borrowernumber => $patron->borrowernumber,
2833                 amount         => $fine,
2834                 due            => output_pref($one_day_ago)
2835             }
2836         );
2837         is( int( $patron->account->balance() ),
2838             2, "Overdue fine of 2 days overdue" );
2839
2840         # Payment made against fine
2841         $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2842         my $debit = $lines->next;
2843         my $credit = $patron->account->add_credit(
2844             {
2845                 amount    => 2,
2846                 type      => 'PAYMENT',
2847                 interface => 'test',
2848             }
2849         );
2850         $credit->apply( { debits => [$debit] } );
2851
2852         is( int( $patron->account->balance() ),
2853             0, "Overdue fine should be paid off" );
2854         $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2855         is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
2856         my $line = $lines->next;
2857         is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
2858         is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
2859
2860         # Backdated return (dropbox mode example - charge should be removed)
2861         AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
2862         is( int( $patron->account->balance() ),
2863             -1, "Refund credit has been applied" );
2864         $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
2865         is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
2866
2867         $line = $lines->next;
2868         is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
2869         is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
2870         is($line->status,'RETURNED', "Overdue fine is fixed");
2871         $line = $lines->next;
2872         is($line->amount+0,-2, "Original payment amount remains as 2");
2873         is($line->amountoutstanding+0,0, "Original payment remains applied");
2874         $line = $lines->next;
2875         is($line->amount+0,-1, "Refund amount correctly set to 1");
2876         is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
2877
2878         # Cleanup
2879         Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2880     };
2881
2882     subtest 'bug 25417 | backdated return + exemptfine' => sub {
2883
2884         plan tests => 2;
2885
2886         t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2887
2888         my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago );    # date due was 1d ago
2889
2890         # Fake fines cronjob on this checkout
2891         my ($fine) =
2892           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2893             $one_day_ago, $now );
2894         UpdateFine(
2895             {
2896                 issue_id       => $issue->issue_id,
2897                 itemnumber     => $item->itemnumber,
2898                 borrowernumber => $patron->borrowernumber,
2899                 amount         => $fine,
2900                 due            => output_pref($one_day_ago)
2901             }
2902         );
2903         is( int( $patron->account->balance() ),
2904             1, "Overdue fine of 1 day overdue" );
2905
2906         # Backdated return (dropbox mode example - charge should no longer exist)
2907         AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
2908         is( int( $patron->account->balance() ),
2909             0, "Overdue fine should be annulled" );
2910
2911         # Cleanup
2912         Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2913     };
2914
2915     subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
2916         plan tests => 7;
2917
2918         t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
2919
2920         my $due_date = dt_from_string;
2921         my $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
2922
2923         # Add fine
2924         UpdateFine(
2925             {
2926                 issue_id       => $issue->issue_id,
2927                 itemnumber     => $item->itemnumber,
2928                 borrowernumber => $patron->borrowernumber,
2929                 amount         => 0.25,
2930                 due            => output_pref($due_date)
2931             }
2932         );
2933         is( $patron->account->balance(),
2934             0.25, 'Overdue fine of $0.25 recorded' );
2935
2936         # Backdate return to exact due date and time
2937         my ( undef, $message ) =
2938           AddReturn( $item->barcode, $library->{branchcode},
2939             undef, $due_date );
2940
2941         my $accountline =
2942           Koha::Account::Lines->find( { issue_id => $issue->id } );
2943         ok( !$accountline, 'accountline removed as expected' );
2944
2945         # Re-issue
2946         $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
2947
2948         # Add fine
2949         UpdateFine(
2950             {
2951                 issue_id       => $issue->issue_id,
2952                 itemnumber     => $item->itemnumber,
2953                 borrowernumber => $patron->borrowernumber,
2954                 amount         => .25,
2955                 due            => output_pref($due_date)
2956             }
2957         );
2958         is( $patron->account->balance(),
2959             0.25, 'Overdue fine of $0.25 recorded' );
2960
2961         # Partial pay accruing fine
2962         my $lines = Koha::Account::Lines->search(
2963             {
2964                 borrowernumber => $patron->borrowernumber,
2965                 issue_id       => $issue->id
2966             }
2967         );
2968         my $debit  = $lines->next;
2969         my $credit = $patron->account->add_credit(
2970             {
2971                 amount    => .20,
2972                 type      => 'PAYMENT',
2973                 interface => 'test',
2974             }
2975         );
2976         $credit->apply( { debits => [$debit] } );
2977
2978         is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
2979
2980         # Backdate return to exact due date and time
2981         ( undef, $message ) =
2982           AddReturn( $item->barcode, $library->{branchcode},
2983             undef, $due_date );
2984
2985         $lines = Koha::Account::Lines->search(
2986             {
2987                 borrowernumber => $patron->borrowernumber,
2988                 issue_id       => $issue->id
2989             }
2990         );
2991         $accountline = $lines->next;
2992         is( $accountline->amountoutstanding + 0,
2993             0, 'Partially paid fee amount outstanding was reduced to 0' );
2994         is( $accountline->amount + 0,
2995             0, 'Partially paid fee amount was reduced to 0' );
2996         is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
2997
2998         # Cleanup
2999         Koha::Account::Lines->search(
3000             { borrowernumber => $patron->borrowernumber } )->delete;
3001     };
3002
3003     subtest 'enh 23091 | Lost item return policies' => sub {
3004         plan tests => 4;
3005
3006         my $manager = $builder->build_object({ class => "Koha::Patrons" });
3007
3008         my $branchcode_false =
3009           $builder->build( { source => 'Branch' } )->{branchcode};
3010         my $specific_rule_false = $builder->build(
3011             {
3012                 source => 'CirculationRule',
3013                 value  => {
3014                     branchcode   => $branchcode_false,
3015                     categorycode => undef,
3016                     itemtype     => undef,
3017                     rule_name    => 'lostreturn',
3018                     rule_value   => 0
3019                 }
3020             }
3021         );
3022         my $branchcode_refund =
3023           $builder->build( { source => 'Branch' } )->{branchcode};
3024         my $specific_rule_refund = $builder->build(
3025             {
3026                 source => 'CirculationRule',
3027                 value  => {
3028                     branchcode   => $branchcode_refund,
3029                     categorycode => undef,
3030                     itemtype     => undef,
3031                     rule_name    => 'lostreturn',
3032                     rule_value   => 'refund'
3033                 }
3034             }
3035         );
3036         my $branchcode_restore =
3037           $builder->build( { source => 'Branch' } )->{branchcode};
3038         my $specific_rule_restore = $builder->build(
3039             {
3040                 source => 'CirculationRule',
3041                 value  => {
3042                     branchcode   => $branchcode_restore,
3043                     categorycode => undef,
3044                     itemtype     => undef,
3045                     rule_name    => 'lostreturn',
3046                     rule_value   => 'restore'
3047                 }
3048             }
3049         );
3050         my $branchcode_charge =
3051           $builder->build( { source => 'Branch' } )->{branchcode};
3052         my $specific_rule_charge = $builder->build(
3053             {
3054                 source => 'CirculationRule',
3055                 value  => {
3056                     branchcode   => $branchcode_charge,
3057                     categorycode => undef,
3058                     itemtype     => undef,
3059                     rule_name    => 'lostreturn',
3060                     rule_value   => 'charge'
3061                 }
3062             }
3063         );
3064
3065         my $replacement_amount = 99.00;
3066         t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
3067         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
3068         t::lib::Mocks::mock_preference( 'WhenLostForgiveFine',          0 );
3069         t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems',       0 );
3070         t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
3071             'CheckinLibrary' );
3072         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
3073             undef );
3074
3075         subtest 'lostreturn | false' => sub {
3076             plan tests => 12;
3077
3078             t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
3079
3080             my $item = $builder->build_sample_item(
3081                 {
3082                     replacementprice => $replacement_amount
3083                 }
3084             );
3085
3086             # Issue the item
3087             my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3088
3089             # Fake fines cronjob on this checkout
3090             my ($fine) =
3091               CalcFine( $item, $patron->categorycode, $library->{branchcode},
3092                 $ten_days_ago, $now );
3093             UpdateFine(
3094                 {
3095                     issue_id       => $issue->issue_id,
3096                     itemnumber     => $item->itemnumber,
3097                     borrowernumber => $patron->borrowernumber,
3098                     amount         => $fine,
3099                     due            => output_pref($ten_days_ago)
3100                 }
3101             );
3102             my $overdue_fees = Koha::Account::Lines->search(
3103                 {
3104                     borrowernumber  => $patron->id,
3105                     itemnumber      => $item->itemnumber,
3106                     debit_type_code => 'OVERDUE'
3107                 }
3108             );
3109             is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3110             my $overdue_fee = $overdue_fees->next;
3111             is( $overdue_fee->amount + 0,
3112                 10, 'The right OVERDUE amount is generated' );
3113             is( $overdue_fee->amountoutstanding + 0,
3114                 10,
3115                 'The right OVERDUE amountoutstanding is generated' );
3116
3117             # Simulate item marked as lost
3118             $item->itemlost(3)->store;
3119             C4::Circulation::LostItem( $item->itemnumber, 1 );
3120
3121             my $lost_fee_lines = Koha::Account::Lines->search(
3122                 {
3123                     borrowernumber  => $patron->id,
3124                     itemnumber      => $item->itemnumber,
3125                     debit_type_code => 'LOST'
3126                 }
3127             );
3128             is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3129             my $lost_fee_line = $lost_fee_lines->next;
3130             is( $lost_fee_line->amount + 0,
3131                 $replacement_amount, 'The right LOST amount is generated' );
3132             is( $lost_fee_line->amountoutstanding + 0,
3133                 $replacement_amount,
3134                 'The right LOST amountoutstanding is generated' );
3135             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3136
3137             # Return lost item
3138             my ( $returned, $message ) =
3139               AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
3140
3141             $overdue_fee->discard_changes;
3142             is( $overdue_fee->amount + 0,
3143                 10, 'The OVERDUE amount is left intact' );
3144             is( $overdue_fee->amountoutstanding + 0,
3145                 10,
3146                 'The OVERDUE amountoutstanding is left intact' );
3147
3148             $lost_fee_line->discard_changes;
3149             is( $lost_fee_line->amount + 0,
3150                 $replacement_amount, 'The LOST amount is left intact' );
3151             is( $lost_fee_line->amountoutstanding + 0,
3152                 $replacement_amount,
3153                 'The LOST amountoutstanding is left intact' );
3154             # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
3155             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3156         };
3157
3158         subtest 'lostreturn | refund' => sub {
3159             plan tests => 12;
3160
3161             t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
3162
3163             my $item = $builder->build_sample_item(
3164                 {
3165                     replacementprice => $replacement_amount
3166                 }
3167             );
3168
3169             # Issue the item
3170             my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3171
3172             # Fake fines cronjob on this checkout
3173             my ($fine) =
3174               CalcFine( $item, $patron->categorycode, $library->{branchcode},
3175                 $ten_days_ago, $now );
3176             UpdateFine(
3177                 {
3178                     issue_id       => $issue->issue_id,
3179                     itemnumber     => $item->itemnumber,
3180                     borrowernumber => $patron->borrowernumber,
3181                     amount         => $fine,
3182                     due            => output_pref($ten_days_ago)
3183                 }
3184             );
3185             my $overdue_fees = Koha::Account::Lines->search(
3186                 {
3187                     borrowernumber  => $patron->id,
3188                     itemnumber      => $item->itemnumber,
3189                     debit_type_code => 'OVERDUE'
3190                 }
3191             );
3192             is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3193             my $overdue_fee = $overdue_fees->next;
3194             is( $overdue_fee->amount + 0,
3195                 10, 'The right OVERDUE amount is generated' );
3196             is( $overdue_fee->amountoutstanding + 0,
3197                 10,
3198                 'The right OVERDUE amountoutstanding is generated' );
3199
3200             # Simulate item marked as lost
3201             $item->itemlost(3)->store;
3202             C4::Circulation::LostItem( $item->itemnumber, 1 );
3203
3204             my $lost_fee_lines = Koha::Account::Lines->search(
3205                 {
3206                     borrowernumber  => $patron->id,
3207                     itemnumber      => $item->itemnumber,
3208                     debit_type_code => 'LOST'
3209                 }
3210             );
3211             is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3212             my $lost_fee_line = $lost_fee_lines->next;
3213             is( $lost_fee_line->amount + 0,
3214                 $replacement_amount, 'The right LOST amount is generated' );
3215             is( $lost_fee_line->amountoutstanding + 0,
3216                 $replacement_amount,
3217                 'The right LOST amountoutstanding is generated' );
3218             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3219
3220             # Return the lost item
3221             my ( undef, $message ) =
3222               AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
3223
3224             $overdue_fee->discard_changes;
3225             is( $overdue_fee->amount + 0,
3226                 10, 'The OVERDUE amount is left intact' );
3227             is( $overdue_fee->amountoutstanding + 0,
3228                 10,
3229                 'The OVERDUE amountoutstanding is left intact' );
3230
3231             $lost_fee_line->discard_changes;
3232             is( $lost_fee_line->amount + 0,
3233                 $replacement_amount, 'The LOST amount is left intact' );
3234             is( $lost_fee_line->amountoutstanding + 0,
3235                 0,
3236                 'The LOST amountoutstanding is refunded' );
3237             is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3238         };
3239
3240         subtest 'lostreturn | restore' => sub {
3241             plan tests => 13;
3242
3243             t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
3244
3245             my $item = $builder->build_sample_item(
3246                 {
3247                     replacementprice => $replacement_amount
3248                 }
3249             );
3250
3251             # Issue the item
3252             my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode , $ten_days_ago);
3253
3254             # Fake fines cronjob on this checkout
3255             my ($fine) =
3256               CalcFine( $item, $patron->categorycode, $library->{branchcode},
3257                 $ten_days_ago, $now );
3258             UpdateFine(
3259                 {
3260                     issue_id       => $issue->issue_id,
3261                     itemnumber     => $item->itemnumber,
3262                     borrowernumber => $patron->borrowernumber,
3263                     amount         => $fine,
3264                     due            => output_pref($ten_days_ago)
3265                 }
3266             );
3267             my $overdue_fees = Koha::Account::Lines->search(
3268                 {
3269                     borrowernumber  => $patron->id,
3270                     itemnumber      => $item->itemnumber,
3271                     debit_type_code => 'OVERDUE'
3272                 }
3273             );
3274             is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3275             my $overdue_fee = $overdue_fees->next;
3276             is( $overdue_fee->amount + 0,
3277                 10, 'The right OVERDUE amount is generated' );
3278             is( $overdue_fee->amountoutstanding + 0,
3279                 10,
3280                 'The right OVERDUE amountoutstanding is generated' );
3281
3282             # Simulate item marked as lost
3283             $item->itemlost(3)->store;
3284             C4::Circulation::LostItem( $item->itemnumber, 1 );
3285
3286             my $lost_fee_lines = Koha::Account::Lines->search(
3287                 {
3288                     borrowernumber  => $patron->id,
3289                     itemnumber      => $item->itemnumber,
3290                     debit_type_code => 'LOST'
3291                 }
3292             );
3293             is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3294             my $lost_fee_line = $lost_fee_lines->next;
3295             is( $lost_fee_line->amount + 0,
3296                 $replacement_amount, 'The right LOST amount is generated' );
3297             is( $lost_fee_line->amountoutstanding + 0,
3298                 $replacement_amount,
3299                 'The right LOST amountoutstanding is generated' );
3300             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3301
3302             # Simulate refunding overdue fees upon marking item as lost
3303             my $overdue_forgive = $patron->account->add_credit(
3304                 {
3305                     amount     => 10.00,
3306                     user_id    => $manager->borrowernumber,
3307                     library_id => $branchcode_restore,
3308                     interface  => 'test',
3309                     type       => 'FORGIVEN',
3310                     item_id    => $item->itemnumber
3311                 }
3312             );
3313             $overdue_forgive->apply( { debits => [$overdue_fee] } );
3314             $overdue_fee->discard_changes;
3315             is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3316
3317             # Do nothing
3318             my ( undef, $message ) =
3319               AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
3320
3321             $overdue_fee->discard_changes;
3322             is( $overdue_fee->amount + 0,
3323                 10, 'The OVERDUE amount is left intact' );
3324             is( $overdue_fee->amountoutstanding + 0,
3325                 10,
3326                 'The OVERDUE amountoutstanding is restored' );
3327
3328             $lost_fee_line->discard_changes;
3329             is( $lost_fee_line->amount + 0,
3330                 $replacement_amount, 'The LOST amount is left intact' );
3331             is( $lost_fee_line->amountoutstanding + 0,
3332                 0,
3333                 'The LOST amountoutstanding is refunded' );
3334             is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3335         };
3336
3337         subtest 'lostreturn | charge' => sub {
3338             plan tests => 16;
3339
3340             t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
3341
3342             my $item = $builder->build_sample_item(
3343                 {
3344                     replacementprice => $replacement_amount
3345                 }
3346             );
3347
3348             # Issue the item
3349             my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3350
3351             # Fake fines cronjob on this checkout
3352             my ($fine) =
3353               CalcFine( $item, $patron->categorycode, $library->{branchcode},
3354                 $ten_days_ago, $now );
3355             UpdateFine(
3356                 {
3357                     issue_id       => $issue->issue_id,
3358                     itemnumber     => $item->itemnumber,
3359                     borrowernumber => $patron->borrowernumber,
3360                     amount         => $fine,
3361                     due            => output_pref($ten_days_ago)
3362                 }
3363             );
3364             my $overdue_fees = Koha::Account::Lines->search(
3365                 {
3366                     borrowernumber  => $patron->id,
3367                     itemnumber      => $item->itemnumber,
3368                     debit_type_code => 'OVERDUE'
3369                 }
3370             );
3371             is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3372             my $overdue_fee = $overdue_fees->next;
3373             is( $overdue_fee->amount + 0,
3374                 10, 'The right OVERDUE amount is generated' );
3375             is( $overdue_fee->amountoutstanding + 0,
3376                 10,
3377                 'The right OVERDUE amountoutstanding is generated' );
3378
3379             # Simulate item marked as lost
3380             $item->itemlost(3)->store;
3381             C4::Circulation::LostItem( $item->itemnumber, 1 );
3382
3383             my $lost_fee_lines = Koha::Account::Lines->search(
3384                 {
3385                     borrowernumber  => $patron->id,
3386                     itemnumber      => $item->itemnumber,
3387                     debit_type_code => 'LOST'
3388                 }
3389             );
3390             is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3391             my $lost_fee_line = $lost_fee_lines->next;
3392             is( $lost_fee_line->amount + 0,
3393                 $replacement_amount, 'The right LOST amount is generated' );
3394             is( $lost_fee_line->amountoutstanding + 0,
3395                 $replacement_amount,
3396                 'The right LOST amountoutstanding is generated' );
3397             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3398
3399             # Simulate refunding overdue fees upon marking item as lost
3400             my $overdue_forgive = $patron->account->add_credit(
3401                 {
3402                     amount     => 10.00,
3403                     user_id    => $manager->borrowernumber,
3404                     library_id => $branchcode_charge,
3405                     interface  => 'test',
3406                     type       => 'FORGIVEN',
3407                     item_id    => $item->itemnumber
3408                 }
3409             );
3410             $overdue_forgive->apply( { debits => [$overdue_fee] } );
3411             $overdue_fee->discard_changes;
3412             is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3413
3414             # Do nothing
3415             my ( undef, $message ) =
3416               AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
3417
3418             $lost_fee_line->discard_changes;
3419             is( $lost_fee_line->amount + 0,
3420                 $replacement_amount, 'The LOST amount is left intact' );
3421             is( $lost_fee_line->amountoutstanding + 0,
3422                 0,
3423                 'The LOST amountoutstanding is refunded' );
3424             is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3425
3426             $overdue_fees = Koha::Account::Lines->search(
3427                 {
3428                     borrowernumber  => $patron->id,
3429                     itemnumber      => $item->itemnumber,
3430                     debit_type_code => 'OVERDUE'
3431                 },
3432                 {
3433                     order_by => { '-asc' => 'accountlines_id'}
3434                 }
3435             );
3436             is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
3437             $overdue_fee = $overdue_fees->next;
3438             is( $overdue_fee->amount + 0,
3439                 10, 'The original OVERDUE amount is left intact' );
3440             is( $overdue_fee->amountoutstanding + 0,
3441                 0,
3442                 'The original OVERDUE amountoutstanding is left as forgiven' );
3443             $overdue_fee = $overdue_fees->next;
3444             is( $overdue_fee->amount + 0,
3445                 5, 'The new OVERDUE amount is correct for the backdated return' );
3446             is( $overdue_fee->amountoutstanding + 0,
3447                 5,
3448                 'The new OVERDUE amountoutstanding is correct for the backdated return' );
3449         };
3450     };
3451 };
3452
3453 subtest '_FixOverduesOnReturn' => sub {
3454     plan tests => 14;
3455
3456     my $manager = $builder->build_object({ class => "Koha::Patrons" });
3457     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3458
3459     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3460
3461     my $branchcode  = $library2->{branchcode};
3462
3463     my $item = $builder->build_sample_item(
3464         {
3465             biblionumber     => $biblio->biblionumber,
3466             library          => $branchcode,
3467             replacementprice => 99.00,
3468             itype            => $itemtype,
3469         }
3470     );
3471
3472     my $patron = $builder->build( { source => 'Borrower' } );
3473
3474     ## Start with basic call, should just close out the open fine
3475     my $accountline = Koha::Account::Line->new(
3476         {
3477             borrowernumber => $patron->{borrowernumber},
3478             debit_type_code    => 'OVERDUE',
3479             status         => 'UNRETURNED',
3480             itemnumber     => $item->itemnumber,
3481             amount => 99.00,
3482             amountoutstanding => 99.00,
3483             interface => 'test',
3484         }
3485     )->store();
3486
3487     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
3488
3489     $accountline->_result()->discard_changes();
3490
3491     is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
3492     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3493     is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3494
3495     ## Run again, with exemptfine enabled
3496     $accountline->set(
3497         {
3498             debit_type_code    => 'OVERDUE',
3499             status         => 'UNRETURNED',
3500             amountoutstanding => 99.00,
3501         }
3502     )->store();
3503
3504     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3505
3506     $accountline->_result()->discard_changes();
3507     my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'APPLY' })->next();
3508
3509     is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
3510     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3511     is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
3512     is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
3513     is( $offset->amount + 0, -99, "Amount of offset is correct" );
3514     my $credit = $offset->credit;
3515     is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
3516     is( $credit->amount + 0, -99, "Credit amount is set correctly" );
3517     is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
3518
3519     # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
3520     $accountline->set(
3521         {
3522             debit_type_code    => 'OVERDUE',
3523             status         => 'UNRETURNED',
3524             amountoutstanding => 0.00,
3525         }
3526     )->store();
3527     $offset->delete;
3528
3529     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3530
3531     $accountline->_result()->discard_changes();
3532     $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'CREATE' })->next();
3533     is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
3534     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3535     is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3536 };
3537
3538 subtest 'Set waiting flag' => sub {
3539     plan tests => 11;
3540
3541     my $library_1 = $builder->build( { source => 'Branch' } );
3542     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3543     my $library_2 = $builder->build( { source => 'Branch' } );
3544     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3545
3546     my $item = $builder->build_sample_item(
3547         {
3548             library      => $library_1->{branchcode},
3549         }
3550     );
3551
3552     set_userenv( $library_2 );
3553     my $reserve_id = AddReserve(
3554         {
3555             branchcode     => $library_2->{branchcode},
3556             borrowernumber => $patron_2->{borrowernumber},
3557             biblionumber   => $item->biblionumber,
3558             priority       => 1,
3559             itemnumber     => $item->itemnumber,
3560         }
3561     );
3562
3563     set_userenv( $library_1 );
3564     my $do_transfer = 1;
3565     my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3566     ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3567     my $hold = Koha::Holds->find( $reserve_id );
3568     is( $hold->found, 'T', 'Hold is in transit' );
3569
3570     my ( $status ) = CheckReserves($item->itemnumber);
3571     is( $status, 'Transferred', 'Hold is not waiting yet');
3572
3573     set_userenv( $library_2 );
3574     $do_transfer = 0;
3575     AddReturn( $item->barcode, $library_2->{branchcode} );
3576     ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3577     $hold = Koha::Holds->find( $reserve_id );
3578     is( $hold->found, 'W', 'Hold is waiting' );
3579     ( $status ) = CheckReserves($item->itemnumber);
3580     is( $status, 'Waiting', 'Now the hold is waiting');
3581
3582     #Bug 21944 - Waiting transfer checked in at branch other than pickup location
3583     set_userenv( $library_1 );
3584     (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
3585     $hold = Koha::Holds->find( $reserve_id );
3586     is( $hold->found, undef, 'Hold is no longer marked waiting' );
3587     is( $hold->priority, 1,  "Hold is now priority one again");
3588     is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
3589     is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
3590     is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
3591     is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
3592     is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
3593 };
3594
3595 subtest 'Cancel transfers on lost items' => sub {
3596     plan tests => 6;
3597
3598     my $library_to = $builder->build_object( { class => 'Koha::Libraries' } );
3599     my $item   = $builder->build_sample_item();
3600     my $holdingbranch = $item->holdingbranch;
3601     # Historic transfer (datearrived is defined)
3602     my $old_transfer = $builder->build_object(
3603         {
3604             class => 'Koha::Item::Transfers',
3605             value => {
3606                 itemnumber    => $item->itemnumber,
3607                 frombranch    => $holdingbranch,
3608                 tobranch      => $library_to->branchcode,
3609                 reason        => 'Manual',
3610                 datesent      => \'NOW()',
3611                 datearrived   => \'NOW()',
3612                 datecancelled => undef,
3613                 daterequested => \'NOW()'
3614             }
3615         }
3616     );
3617     # Queued transfer (datesent is undefined)
3618     my $transfer_1 = $builder->build_object(
3619         {
3620             class => 'Koha::Item::Transfers',
3621             value => {
3622                 itemnumber    => $item->itemnumber,
3623                 frombranch    => $holdingbranch,
3624                 tobranch      => $library_to->branchcode,
3625                 reason        => 'Manual',
3626                 datesent      => undef,
3627                 datearrived   => undef,
3628                 datecancelled => undef,
3629                 daterequested => \'NOW()'
3630             }
3631         }
3632     );
3633     # In transit transfer (datesent is defined, datearrived and datecancelled are both undefined)
3634     my $transfer_2 = $builder->build_object(
3635         {
3636             class => 'Koha::Item::Transfers',
3637             value => {
3638                 itemnumber    => $item->itemnumber,
3639                 frombranch    => $holdingbranch,
3640                 tobranch      => $library_to->branchcode,
3641                 reason        => 'Manual',
3642                 datesent      => \'NOW()',
3643                 datearrived   => undef,
3644                 datecancelled => undef,
3645                 daterequested => \'NOW()'
3646             }
3647         }
3648     );
3649
3650     # Simulate item being marked as lost
3651     $item->itemlost(1)->store;
3652     LostItem( $item->itemnumber, 'test', 1 );
3653
3654     $transfer_1->discard_changes;
3655     isnt($transfer_1->datecancelled, undef, "Queud transfer was cancelled upon item lost");
3656     is($transfer_1->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
3657     $transfer_2->discard_changes;
3658     isnt($transfer_2->datecancelled, undef, "Active transfer was cancelled upon item lost");
3659     is($transfer_2->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
3660     $old_transfer->discard_changes;
3661     is($old_transfer->datecancelled, undef, "Old transfers are unaffected");
3662     $item->discard_changes;
3663     is($item->holdingbranch, $holdingbranch, "Items holding branch remains unchanged");
3664 };
3665
3666 subtest 'CanBookBeIssued | is_overdue' => sub {
3667     plan tests => 3;
3668
3669     # Set a simple circ policy
3670     Koha::CirculationRules->set_rules(
3671         {
3672             categorycode => undef,
3673             branchcode   => undef,
3674             itemtype     => undef,
3675             rules        => {
3676                 maxissueqty     => 1,
3677                 reservesallowed => 25,
3678                 issuelength     => 14,
3679                 lengthunit      => 'days',
3680                 renewalsallowed => 1,
3681                 renewalperiod   => 7,
3682                 norenewalbefore => undef,
3683                 auto_renew      => 0,
3684                 fine            => .10,
3685                 chargeperiod    => 1,
3686             }
3687         }
3688     );
3689
3690     my $now   = dt_from_string;
3691     my $five_days_go = output_pref({ dt => $now->clone->add( days => 5 ), dateonly => 1});
3692     my $ten_days_go  = output_pref({ dt => $now->clone->add( days => 10), dateonly => 1 });
3693     my $library = $builder->build( { source => 'Branch' } );
3694     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
3695
3696     my $item = $builder->build_sample_item(
3697         {
3698             library      => $library->{branchcode},
3699         }
3700     );
3701
3702     my $issue = AddIssue( $patron->unblessed, $item->barcode, $five_days_go ); # date due was 10d ago
3703     my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
3704     is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
3705     my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->barcode,$ten_days_go, undef, undef, undef);
3706     is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
3707     is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
3708 };
3709
3710 subtest 'ItemsDeniedRenewal preference' => sub {
3711     plan tests => 18;
3712
3713     C4::Context->set_preference('ItemsDeniedRenewal','');
3714
3715     my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
3716     Koha::CirculationRules->set_rules(
3717         {
3718             categorycode => '*',
3719             itemtype     => '*',
3720             branchcode   => $idr_lib->branchcode,
3721             rules        => {
3722                 reservesallowed => 25,
3723                 issuelength     => 14,
3724                 lengthunit      => 'days',
3725                 renewalsallowed => 10,
3726                 renewalperiod   => 7,
3727                 norenewalbefore => undef,
3728                 auto_renew      => 0,
3729                 fine            => .10,
3730                 chargeperiod    => 1,
3731             }
3732         }
3733     );
3734
3735     my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
3736         homebranch => $idr_lib->branchcode,
3737         withdrawn => 1,
3738         itype => 'HIDE',
3739         location => 'PROC',
3740         itemcallnumber => undef,
3741         itemnotes => "",
3742         }
3743     });
3744     my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
3745         homebranch => $idr_lib->branchcode,
3746         withdrawn => 0,
3747         itype => 'NOHIDE',
3748         location => 'NOPROC'
3749         }
3750     });
3751
3752     my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
3753         branchcode => $idr_lib->branchcode,
3754         }
3755     });
3756     my $future = dt_from_string->add( days => 1 );
3757     my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3758         returndate => undef,
3759         renewals => 0,
3760         auto_renew => 0,
3761         borrowernumber => $idr_borrower->borrowernumber,
3762         itemnumber => $deny_book->itemnumber,
3763         onsite_checkout => 0,
3764         date_due => $future,
3765         }
3766     });
3767     my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3768         returndate => undef,
3769         renewals => 0,
3770         auto_renew => 0,
3771         borrowernumber => $idr_borrower->borrowernumber,
3772         itemnumber => $allow_book->itemnumber,
3773         onsite_checkout => 0,
3774         date_due => $future,
3775         }
3776     });
3777
3778     my $idr_rules;
3779
3780     my ( $idr_mayrenew, $idr_error ) =
3781     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3782     is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3783     is( $idr_error, undef, 'Renewal allowed when no rules' );
3784
3785     $idr_rules="withdrawn: [1]";
3786
3787     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3788     ( $idr_mayrenew, $idr_error ) =
3789     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3790     is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3791     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3792     ( $idr_mayrenew, $idr_error ) =
3793     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3794     is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3795     is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3796
3797     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
3798
3799     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3800     ( $idr_mayrenew, $idr_error ) =
3801     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3802     is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
3803     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
3804     ( $idr_mayrenew, $idr_error ) =
3805     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3806     is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3807     is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3808
3809     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
3810
3811     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3812     ( $idr_mayrenew, $idr_error ) =
3813     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3814     is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
3815     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
3816     ( $idr_mayrenew, $idr_error ) =
3817     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3818     is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3819     is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3820
3821     $idr_rules="itemcallnumber: [NULL]";
3822     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3823     ( $idr_mayrenew, $idr_error ) =
3824     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3825     is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
3826     $idr_rules="itemcallnumber: ['']";
3827     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3828     ( $idr_mayrenew, $idr_error ) =
3829     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3830     is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
3831
3832     $idr_rules="itemnotes: [NULL]";
3833     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3834     ( $idr_mayrenew, $idr_error ) =
3835     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3836     is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
3837     $idr_rules="itemnotes: ['']";
3838     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3839     ( $idr_mayrenew, $idr_error ) =
3840     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3841     is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
3842 };
3843
3844 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
3845     plan tests => 2;
3846
3847     t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3848     my $library = $builder->build( { source => 'Branch' } );
3849     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3850
3851     my $item = $builder->build_sample_item(
3852         {
3853             library      => $library->{branchcode},
3854         }
3855     );
3856
3857     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3858     is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3859     is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3860 };
3861
3862 subtest 'CanBookBeIssued | notforloan' => sub {
3863     plan tests => 2;
3864
3865     t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
3866
3867     my $library = $builder->build( { source => 'Branch' } );
3868     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3869
3870     my $itemtype = $builder->build(
3871         {
3872             source => 'Itemtype',
3873             value  => { notforloan => undef, }
3874         }
3875     );
3876     my $item = $builder->build_sample_item(
3877         {
3878             library  => $library->{branchcode},
3879             itype    => $itemtype->{itemtype},
3880         }
3881     );
3882     $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3883
3884     my ( $issuingimpossible, $needsconfirmation );
3885
3886
3887     subtest 'item-level_itypes = 1' => sub {
3888         plan tests => 6;
3889
3890         t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
3891         # Is for loan at item type and item level
3892         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3893         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3894         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3895
3896         # not for loan at item type level
3897         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3898         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3899         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3900         is_deeply(
3901             $issuingimpossible,
3902             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3903             'Item can not be issued, not for loan at item type level'
3904         );
3905
3906         # not for loan at item level
3907         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3908         $item->notforloan( 1 )->store;
3909         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3910         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3911         is_deeply(
3912             $issuingimpossible,
3913             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3914             'Item can not be issued, not for loan at item type level'
3915         );
3916     };
3917
3918     subtest 'item-level_itypes = 0' => sub {
3919         plan tests => 6;
3920
3921         t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3922
3923         # We set another itemtype for biblioitem
3924         my $itemtype = $builder->build(
3925             {
3926                 source => 'Itemtype',
3927                 value  => { notforloan => undef, }
3928             }
3929         );
3930
3931         # for loan at item type and item level
3932         $item->notforloan(0)->store;
3933         $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3934         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3935         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3936         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3937
3938         # not for loan at item type level
3939         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3940         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3941         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3942         is_deeply(
3943             $issuingimpossible,
3944             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3945             'Item can not be issued, not for loan at item type level'
3946         );
3947
3948         # not for loan at item level
3949         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3950         $item->notforloan( 1 )->store;
3951         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3952         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3953         is_deeply(
3954             $issuingimpossible,
3955             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3956             'Item can not be issued, not for loan at item type level'
3957         );
3958     };
3959
3960     # TODO test with AllowNotForLoanOverride = 1
3961 };
3962
3963 subtest 'CanBookBeIssued | recalls' => sub {
3964     plan tests => 3;
3965
3966     t::lib::Mocks::mock_preference("UseRecalls", 1);
3967     t::lib::Mocks::mock_preference("item-level_itypes", 1);
3968     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
3969     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
3970     my $item = $builder->build_sample_item;
3971     Koha::CirculationRules->set_rules({
3972         branchcode => undef,
3973         itemtype => undef,
3974         categorycode => undef,
3975         rules => {
3976             recalls_allowed => 10,
3977         },
3978     });
3979
3980     # item-level recall
3981     my $recall = Koha::Recall->new({
3982         borrowernumber => $patron1->borrowernumber,
3983         biblionumber => $item->biblionumber,
3984         itemnumber => $item->itemnumber,
3985         item_level_recall => 1,
3986         branchcode => $patron1->branchcode,
3987         status => 'R',
3988     })->store;
3989
3990     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
3991     is( $needsconfirmation->{RECALLED}->recall_id, $recall->recall_id, "Another patron has placed an item-level recall on this item" );
3992
3993     $recall->set_cancelled;
3994
3995     # biblio-level recall
3996     $recall = Koha::Recall->new({
3997         borrowernumber => $patron1->borrowernumber,
3998         biblionumber => $item->biblionumber,
3999         itemnumber => undef,
4000         item_level_recall => 0,
4001         branchcode => $patron1->branchcode,
4002         status => 'R',
4003     })->store;
4004
4005     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4006     is( $needsconfirmation->{RECALLED}->recall_id, $recall->recall_id, "Another patron has placed a biblio-level recall and this item is eligible to fill it" );
4007
4008     $recall->set_cancelled;
4009
4010     # biblio-level recall
4011     $recall = Koha::Recall->new({
4012         borrowernumber => $patron1->borrowernumber,
4013         biblionumber => $item->biblionumber,
4014         itemnumber => undef,
4015         item_level_recall => 0,
4016         branchcode => $patron1->branchcode,
4017         status => 'R',
4018     })->store;
4019     $recall->set_waiting({ item => $item, expirationdate => dt_from_string() });
4020
4021     my ( undef, undef, undef, $messages ) = CanBookBeIssued( $patron1, $item->barcode, undef, undef, undef, undef );
4022     is( $messages->{RECALLED}, $recall->recall_id, "This book can be issued by this patron and they have placed a recall" );
4023
4024     $recall->set_cancelled;
4025 };
4026
4027 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
4028     plan tests => 1;
4029
4030     t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
4031     my $item = $builder->build_sample_item(
4032         {
4033             onloan => '2018-01-01',
4034         }
4035     );
4036
4037     AddReturn( $item->barcode, $item->homebranch );
4038     $item->discard_changes; # refresh
4039     is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
4040 };
4041
4042 subtest 'AddReturn | recalls' => sub {
4043     plan tests => 3;
4044
4045     t::lib::Mocks::mock_preference("UseRecalls", 1);
4046     t::lib::Mocks::mock_preference("item-level_itypes", 1);
4047     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4048     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4049     my $item1 = $builder->build_sample_item;
4050     Koha::CirculationRules->set_rules({
4051         branchcode => undef,
4052         itemtype => undef,
4053         categorycode => undef,
4054         rules => {
4055             recalls_allowed => 10,
4056         },
4057     });
4058
4059     # this item can fill a recall with pickup at this branch
4060     AddIssue( $patron1->unblessed, $item1->barcode );
4061     my $recall1 = Koha::Recall->new({
4062         borrowernumber => $patron2->borrowernumber,
4063         biblionumber => $item1->biblionumber,
4064         itemnumber => $item1->itemnumber,
4065         item_level_recall => 1,
4066         branchcode => $item1->homebranch,
4067         status => 'R',
4068     })->store;
4069     my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4070     is( $messages->{RecallFound}->recall_id, $recall1->recall_id, "Recall found" );
4071     $recall1->set_cancelled;
4072
4073     # this item can fill a recall but needs transfer
4074     AddIssue( $patron1->unblessed, $item1->barcode );
4075     $recall1 = Koha::Recall->new({
4076         borrowernumber => $patron2->borrowernumber,
4077         biblionumber => $item1->biblionumber,
4078         itemnumber => $item1->itemnumber,
4079         item_level_recall => 1,
4080         branchcode => $patron2->branchcode,
4081         status => 'R',
4082     })->store;
4083     ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4084     is( $messages->{RecallNeedsTransfer}, $item1->homebranch, "Recall requiring transfer found" );
4085     $recall1->set_cancelled;
4086
4087     # this item is already in transit, do not ask to transfer
4088     AddIssue( $patron1->unblessed, $item1->barcode );
4089     $recall1 = Koha::Recall->new({
4090         borrowernumber => $patron2->borrowernumber,
4091         biblionumber => $item1->biblionumber,
4092         itemnumber => $item1->itemnumber,
4093         item_level_recall => 1,
4094         branchcode => $patron2->branchcode,
4095         status => 'R',
4096     })->store;
4097     $recall1->start_transfer;
4098     ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $patron2->branchcode );
4099     is( $messages->{TransferredRecall}->recall_id, $recall1->recall_id, "In transit recall found" );
4100     $recall1->set_cancelled;
4101 };
4102
4103 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
4104
4105     plan tests => 13;
4106
4107
4108     t::lib::Mocks::mock_preference('item-level_itypes', 1);
4109
4110     my $issuing_charges = 15;
4111     my $title   = 'A title';
4112     my $author  = 'Author, An';
4113     my $barcode = 'WHATARETHEODDS';
4114
4115     my $circ = Test::MockModule->new('C4::Circulation');
4116     $circ->mock(
4117         'GetIssuingCharges',
4118         sub {
4119             return $issuing_charges;
4120         }
4121     );
4122
4123     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
4124     my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
4125     my $patron   = $builder->build_object({
4126         class => 'Koha::Patrons',
4127         value => { branchcode => $library->id }
4128     });
4129
4130     my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
4131     my $item_id = Koha::Item->new(
4132         {
4133             biblionumber     => $biblio->biblionumber,
4134             homebranch       => $library->id,
4135             holdingbranch    => $library->id,
4136             barcode          => $barcode,
4137             replacementprice => 23.00,
4138             itype            => $itemtype->id
4139         },
4140     )->store->itemnumber;
4141     my $item = Koha::Items->find( $item_id );
4142
4143     my $context = Test::MockModule->new('C4::Context');
4144     $context->mock( userenv => { branch => $library->id } );
4145
4146     # Check the item out
4147     AddIssue( $patron->unblessed, $item->barcode );
4148
4149     throws_ok {
4150         AddRenewal( $patron->borrowernumber, $item->itemnumber, $library->id, undef, {break=>"the_renewal"} );
4151     } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
4152
4153     t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
4154     my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
4155     my %params_renewal = (
4156         timestamp => { -like => $date . "%" },
4157         module => "CIRCULATION",
4158         action => "RENEWAL",
4159     );
4160     my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
4161     AddRenewal( $patron->id, $item->id, $library->id );
4162     my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4163     is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
4164
4165     my $checkouts = $patron->checkouts;
4166     # The following will fail if run on 00:00:00
4167     unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
4168
4169     my $lines = Koha::Account::Lines->search({
4170         borrowernumber => $patron->id,
4171         itemnumber     => $item->id
4172     });
4173
4174     is( $lines->count, 2 );
4175
4176     my $line = $lines->next;
4177     is( $line->debit_type_code, 'RENT',       'The issue of item with issuing charge generates an accountline of the correct type' );
4178     is( $line->branchcode,  $library->id, 'AddIssuingCharge correctly sets branchcode' );
4179     is( $line->description, '',     'AddIssue does not set a hardcoded description for the accountline' );
4180
4181     $line = $lines->next;
4182     is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
4183     is( $line->branchcode,  $library->id, 'AddRenewal correctly sets branchcode' );
4184     is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
4185
4186     t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
4187
4188     $context = Test::MockModule->new('C4::Context');
4189     $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
4190
4191     my $now = dt_from_string;
4192     $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
4193     $old_log_size = Koha::ActionLogs->count( \%params_renewal );
4194     my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
4195     $sth->execute($item->id, $library->id);
4196     my ($old_stats_size) = $sth->fetchrow_array;
4197     AddRenewal( $patron->id, $item->id, $library->id );
4198     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4199     $sth->execute($item->id, $library->id);
4200     my ($new_stats_size) = $sth->fetchrow_array;
4201     is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
4202     is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
4203
4204     AddReturn( $item->id, $library->id, undef, $date );
4205     AddIssue( $patron->unblessed, $item->barcode, $now );
4206     AddRenewal( $patron->id, $item->id, $library->id, undef, undef, 1 );
4207     my $lines_skipped = Koha::Account::Lines->search({
4208         borrowernumber => $patron->id,
4209         itemnumber     => $item->id
4210     });
4211     is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
4212
4213 };
4214
4215 subtest 'ProcessOfflinePayment() tests' => sub {
4216
4217     plan tests => 4;
4218
4219
4220     my $amount = 123;
4221
4222     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
4223     my $library = $builder->build_object({ class => 'Koha::Libraries' });
4224     my $result  = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
4225
4226     is( $result, 'Success.', 'The right string is returned' );
4227
4228     my $lines = $patron->account->lines;
4229     is( $lines->count, 1, 'line created correctly');
4230
4231     my $line = $lines->next;
4232     is( $line->amount+0, $amount * -1, 'amount picked from params' );
4233     is( $line->branchcode, $library->id, 'branchcode set correctly' );
4234
4235 };
4236
4237 subtest 'Incremented fee tests' => sub {
4238     plan tests => 19;
4239
4240     my $dt = dt_from_string();
4241     Time::Fake->offset( $dt->epoch );
4242
4243     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
4244
4245     my $library =
4246       $builder->build_object( { class => 'Koha::Libraries' } )->store;
4247
4248     $module->mock( 'userenv', sub { { branch => $library->id } } );
4249
4250     my $patron = $builder->build_object(
4251         {
4252             class => 'Koha::Patrons',
4253             value => { categorycode => $patron_category->{categorycode} }
4254         }
4255     )->store;
4256
4257     my $itemtype = $builder->build_object(
4258         {
4259             class => 'Koha::ItemTypes',
4260             value => {
4261                 notforloan                   => undef,
4262                 rentalcharge                 => 0,
4263                 rentalcharge_daily           => 1,
4264                 rentalcharge_daily_calendar  => 0
4265             }
4266         }
4267     )->store;
4268
4269     my $item = $builder->build_sample_item(
4270         {
4271             library  => $library->{branchcode},
4272             itype    => $itemtype->id,
4273         }
4274     );
4275
4276     is( $itemtype->rentalcharge_daily+0,
4277         1, 'Daily rental charge stored and retreived correctly' );
4278     is( $item->effective_itemtype, $itemtype->id,
4279         "Itemtype set correctly for item" );
4280
4281     my $now         = dt_from_string;
4282     my $dt_from     = $now->clone;
4283     my $dt_to       = $now->clone->add( days => 7 );
4284     my $dt_to_renew = $now->clone->add( days => 13 );
4285
4286     # Daily Tests
4287     my $issue =
4288       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4289     my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4290     is( $accountline->amount+0, 7,
4291 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
4292     );
4293     $accountline->delete();
4294     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4295     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4296     is( $accountline->amount+0, 6,
4297 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
4298     );
4299     $accountline->delete();
4300     $issue->delete();
4301
4302     t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
4303     $itemtype->rentalcharge_daily_calendar(1)->store();
4304     $issue =
4305       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4306     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4307     is( $accountline->amount+0, 7,
4308 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
4309     );
4310     $accountline->delete();
4311     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4312     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4313     is( $accountline->amount+0, 6,
4314 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
4315     );
4316     $accountline->delete();
4317     $issue->delete();
4318
4319     my $calendar = C4::Calendar->new( branchcode => $library->id );
4320     # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
4321     my $closed_day =
4322         ( $dt_from->day_of_week == 6 ) ? 0
4323       : ( $dt_from->day_of_week == 7 ) ? 1
4324       :                                  $dt_from->day_of_week + 1;
4325     my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
4326     $calendar->insert_week_day_holiday(
4327         weekday     => $closed_day,
4328         title       => 'Test holiday',
4329         description => 'Test holiday'
4330     );
4331     $issue =
4332       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4333     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4334     is( $accountline->amount+0, 6,
4335 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
4336     );
4337     $accountline->delete();
4338     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4339     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4340     is( $accountline->amount+0, 5,
4341 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
4342     );
4343     $accountline->delete();
4344     $issue->delete();
4345
4346     $itemtype->rentalcharge(2)->store;
4347     is( $itemtype->rentalcharge+0, 2,
4348         'Rental charge updated and retreived correctly' );
4349     $issue =
4350       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4351     my $accountlines =
4352       Koha::Account::Lines->search( { itemnumber => $item->id } );
4353     is( $accountlines->count, '2',
4354         "Fixed charge and accrued charge recorded distinctly" );
4355     $accountlines->delete();
4356     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4357     $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
4358     is( $accountlines->count, '2',
4359         "Fixed charge and accrued charge recorded distinctly, for renewal" );
4360     $accountlines->delete();
4361     $issue->delete();
4362     $itemtype->rentalcharge(0)->store;
4363     is( $itemtype->rentalcharge+0, 0,
4364         'Rental charge reset and retreived correctly' );
4365
4366     # Hourly
4367     Koha::CirculationRules->set_rule(
4368         {
4369             categorycode => $patron->categorycode,
4370             itemtype     => $itemtype->id,
4371             branchcode   => $library->id,
4372             rule_name    => 'lengthunit',
4373             rule_value   => 'hours',
4374         }
4375     );
4376
4377     $itemtype->rentalcharge_hourly('0.25')->store();
4378     is( $itemtype->rentalcharge_hourly,
4379         '0.25', 'Hourly rental charge stored and retreived correctly' );
4380
4381     $dt_to       = $now->clone->add( hours => 168 );
4382     $dt_to_renew = $now->clone->add( hours => 312 );
4383
4384     $itemtype->rentalcharge_hourly_calendar(0)->store();
4385     $issue =
4386       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4387     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4388     is( $accountline->amount + 0, 42,
4389         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)" );
4390     $accountline->delete();
4391     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4392     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4393     is( $accountline->amount + 0, 36,
4394         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)" );
4395     $accountline->delete();
4396     $issue->delete();
4397
4398     $itemtype->rentalcharge_hourly_calendar(1)->store();
4399     $issue =
4400       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4401     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4402     is( $accountline->amount + 0, 36,
4403         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)" );
4404     $accountline->delete();
4405     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4406     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4407     is( $accountline->amount + 0, 30,
4408         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
4409     $accountline->delete();
4410     $issue->delete();
4411
4412     $calendar->delete_holiday( weekday => $closed_day );
4413     $issue =
4414       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4415     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4416     is( $accountline->amount + 0, 42,
4417         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u" );
4418     $accountline->delete();
4419     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4420     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4421     is( $accountline->amount + 0, 36,
4422         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)" );
4423     $accountline->delete();
4424     $issue->delete();
4425     Time::Fake->reset;
4426 };
4427
4428 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
4429     plan tests => 2;
4430
4431     t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
4432     t::lib::Mocks::mock_preference('item-level_itypes', 1);
4433
4434     my $library =
4435       $builder->build_object( { class => 'Koha::Libraries' } )->store;
4436     my $patron = $builder->build_object(
4437         {
4438             class => 'Koha::Patrons',
4439             value => { categorycode => $patron_category->{categorycode} }
4440         }
4441     )->store;
4442
4443     my $itemtype = $builder->build_object(
4444         {
4445             class => 'Koha::ItemTypes',
4446             value => {
4447                 notforloan             => 0,
4448                 rentalcharge           => 0,
4449                 rentalcharge_daily => 0
4450             }
4451         }
4452     );
4453
4454     my $item = $builder->build_sample_item(
4455         {
4456             library    => $library->id,
4457             notforloan => 0,
4458             itemlost   => 0,
4459             withdrawn  => 0,
4460             itype      => $itemtype->id,
4461         }
4462     )->store;
4463
4464     my ( $issuingimpossible, $needsconfirmation );
4465     my $dt_from = dt_from_string();
4466     my $dt_due = $dt_from->clone->add( days => 3 );
4467
4468     $itemtype->rentalcharge(1)->store;
4469     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4470     is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
4471     $itemtype->rentalcharge('0')->store;
4472     $itemtype->rentalcharge_daily(1)->store;
4473     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4474     is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
4475     $itemtype->rentalcharge_daily('0')->store;
4476 };
4477
4478 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
4479     plan tests => 1;
4480
4481     t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
4482
4483     my $patron = $builder->build_object(
4484         {
4485             class => 'Koha::Patrons',
4486             value => { categorycode => $patron_category->{categorycode} }
4487         }
4488     )->store;
4489
4490     my $item = $builder->build_sample_item(
4491         {
4492             materials => 'includes DVD',
4493         }
4494     )->store;
4495
4496     my $dt_due = dt_from_string->add( days => 3 );
4497
4498     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4499     is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
4500 };
4501
4502 subtest 'Do not return on renewal (LOST charge)' => sub {
4503     plan tests => 1;
4504
4505     t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
4506     my $library = $builder->build_object( { class => "Koha::Libraries" } );
4507     my $manager = $builder->build_object( { class => "Koha::Patrons" } );
4508     t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
4509
4510     my $biblio = $builder->build_sample_biblio;
4511
4512     my $item = $builder->build_sample_item(
4513         {
4514             biblionumber     => $biblio->biblionumber,
4515             library          => $library->branchcode,
4516             replacementprice => 99.00,
4517             itype            => $itemtype,
4518         }
4519     );
4520
4521     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
4522     AddIssue( $patron->unblessed, $item->barcode );
4523
4524     my $accountline = Koha::Account::Line->new(
4525         {
4526             borrowernumber    => $patron->borrowernumber,
4527             debit_type_code   => 'LOST',
4528             status            => undef,
4529             itemnumber        => $item->itemnumber,
4530             amount            => 12,
4531             amountoutstanding => 12,
4532             interface         => 'something',
4533         }
4534     )->store();
4535
4536     # AddRenewal doesn't call _FixAccountForLostAndFound
4537     AddIssue( $patron->unblessed, $item->barcode );
4538
4539     is( $patron->checkouts->count, 1,
4540         'Renewal should not return the item even if a LOST payment has been made earlier'
4541     );
4542 };
4543
4544 subtest 'Filling a hold should cancel existing transfer' => sub {
4545     plan tests => 4;
4546
4547     t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
4548
4549     my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
4550     my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
4551     my $patron = $builder->build_object(
4552         {
4553             class => 'Koha::Patrons',
4554             value => {
4555                 categorycode => $patron_category->{categorycode},
4556                 branchcode => $libraryA->branchcode,
4557             }
4558         }
4559     )->store;
4560
4561     my $item = $builder->build_sample_item({
4562         homebranch => $libraryB->branchcode,
4563     });
4564
4565     my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4566     is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
4567     AddReserve({
4568         branchcode     => $libraryA->branchcode,
4569         borrowernumber => $patron->borrowernumber,
4570         biblionumber   => $item->biblionumber,
4571         itemnumber     => $item->itemnumber
4572     });
4573     my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
4574     is( $reserves->count, 1, "Reserve is placed");
4575     ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4576     my $reserve = $reserves->next;
4577     ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
4578     $reserve->discard_changes;
4579     ok( $reserve->found eq 'W', "Reserve is marked waiting" );
4580     is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
4581 };
4582
4583 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
4584
4585     plan tests => 4;
4586
4587     t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4588     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4589     my $patron  = $builder->build_object(
4590         {
4591             class => 'Koha::Patrons',
4592             value => { categorycode => $patron_category->{categorycode} }
4593         }
4594     );
4595
4596     my $biblionumber = $builder->build_sample_biblio(
4597         {
4598             branchcode => $library->branchcode,
4599         }
4600     )->biblionumber;
4601
4602     # And the circulation rule
4603     Koha::CirculationRules->search->delete;
4604     Koha::CirculationRules->set_rules(
4605         {
4606             categorycode => undef,
4607             itemtype     => undef,
4608             branchcode   => undef,
4609             rules        => {
4610                 issuelength => 14,
4611                 lengthunit  => 'days',
4612             }
4613         }
4614     );
4615     $builder->build(
4616         {
4617             source => 'CirculationRule',
4618             value  => {
4619                 branchcode   => undef,
4620                 categorycode => undef,
4621                 itemtype     => undef,
4622                 rule_name    => 'lostreturn',
4623                 rule_value   => 'refund'
4624             }
4625         }
4626     );
4627
4628     subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4629         plan tests => 3;
4630
4631         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4632         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4633
4634         my $lost_on = dt_from_string->subtract( days => 7 )->date;
4635
4636         my $item = $builder->build_sample_item(
4637             {
4638                 biblionumber     => $biblionumber,
4639                 library          => $library->branchcode,
4640                 replacementprice => '42',
4641             }
4642         );
4643         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4644         LostItem( $item->itemnumber, 'cli', 0 );
4645         $item->_result->itemlost(1);
4646         $item->_result->itemlost_on( $lost_on );
4647         $item->_result->update();
4648
4649         my $a = Koha::Account::Lines->search(
4650             {
4651                 itemnumber     => $item->id,
4652                 borrowernumber => $patron->borrowernumber
4653             }
4654         )->next;
4655         ok( $a, "Found accountline for lost fee" );
4656         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4657         my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4658         $a = $a->get_from_storage;
4659         is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4660         $a->delete;
4661     };
4662
4663     subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4664         plan tests => 3;
4665
4666         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4667         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4668
4669         my $lost_on = dt_from_string->subtract( days => 6 )->date;
4670
4671         my $item = $builder->build_sample_item(
4672             {
4673                 biblionumber     => $biblionumber,
4674                 library          => $library->branchcode,
4675                 replacementprice => '42',
4676             }
4677         );
4678         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4679         LostItem( $item->itemnumber, 'cli', 0 );
4680         $item->_result->itemlost(1);
4681         $item->_result->itemlost_on( $lost_on );
4682         $item->_result->update();
4683
4684         my $a = Koha::Account::Lines->search(
4685             {
4686                 itemnumber     => $item->id,
4687                 borrowernumber => $patron->borrowernumber
4688             }
4689         )->next;
4690         ok( $a, "Found accountline for lost fee" );
4691         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4692         my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4693         $a = $a->get_from_storage;
4694         is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4695         $a->delete;
4696     };
4697
4698     subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4699         plan tests => 3;
4700
4701         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4702         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4703
4704         my $lost_on = dt_from_string->subtract( days => 7 )->date;
4705
4706         my $item = $builder->build_sample_item(
4707             {
4708                 biblionumber     => $biblionumber,
4709                 library          => $library->branchcode,
4710                 replacementprice => '42',
4711             }
4712         );
4713         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4714         LostItem( $item->itemnumber, 'cli', 0 );
4715         $item->_result->itemlost(1);
4716         $item->_result->itemlost_on( $lost_on );
4717         $item->_result->update();
4718
4719         my $a = Koha::Account::Lines->search(
4720             {
4721                 itemnumber     => $item->id,
4722                 borrowernumber => $patron->borrowernumber
4723             }
4724         )->next;
4725         ok( $a, "Found accountline for lost fee" );
4726         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4727         my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4728         $a = $a->get_from_storage;
4729         is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4730         $a->delete;
4731     };
4732
4733     subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4734         plan tests => 3;
4735
4736         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4737         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4738
4739         my $lost_on = dt_from_string->subtract( days => 8 )->date;
4740
4741         my $item = $builder->build_sample_item(
4742             {
4743                 biblionumber     => $biblionumber,
4744                 library          => $library->branchcode,
4745                 replacementprice => '42',
4746             }
4747         );
4748         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4749         LostItem( $item->itemnumber, 'cli', 0 );
4750         $item->_result->itemlost(1);
4751         $item->_result->itemlost_on( $lost_on );
4752         $item->_result->update();
4753
4754         my $a = Koha::Account::Lines->search(
4755             {
4756                 itemnumber     => $item->id,
4757                 borrowernumber => $patron->borrowernumber
4758             }
4759         );
4760         $a = $a->next;
4761         ok( $a, "Found accountline for lost fee" );
4762         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4763         my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4764         $a = $a->get_from_storage;
4765         is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4766         $a->delete;
4767     };
4768 };
4769
4770 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
4771
4772     plan tests => 4;
4773
4774     t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4775     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4776     my $patron  = $builder->build_object(
4777         {
4778             class => 'Koha::Patrons',
4779             value => { categorycode => $patron_category->{categorycode} }
4780         }
4781     );
4782     my $patron2  = $builder->build_object(
4783         {
4784             class => 'Koha::Patrons',
4785             value => { categorycode => $patron_category->{categorycode} }
4786         }
4787     );
4788
4789     my $biblionumber = $builder->build_sample_biblio(
4790         {
4791             branchcode => $library->branchcode,
4792         }
4793     )->biblionumber;
4794
4795     # And the circulation rule
4796     Koha::CirculationRules->search->delete;
4797     Koha::CirculationRules->set_rules(
4798         {
4799             categorycode => undef,
4800             itemtype     => undef,
4801             branchcode   => undef,
4802             rules        => {
4803                 issuelength => 14,
4804                 lengthunit  => 'days',
4805             }
4806         }
4807     );
4808     $builder->build(
4809         {
4810             source => 'CirculationRule',
4811             value  => {
4812                 branchcode   => undef,
4813                 categorycode => undef,
4814                 itemtype     => undef,
4815                 rule_name    => 'lostreturn',
4816                 rule_value   => 'refund'
4817             }
4818         }
4819     );
4820
4821     subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4822         plan tests => 3;
4823
4824         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4825         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4826
4827         my $lost_on = dt_from_string->subtract( days => 7 )->date;
4828
4829         my $item = $builder->build_sample_item(
4830             {
4831                 biblionumber     => $biblionumber,
4832                 library          => $library->branchcode,
4833                 replacementprice => '42',
4834             }
4835         );
4836         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4837         LostItem( $item->itemnumber, 'cli', 0 );
4838         $item->_result->itemlost(1);
4839         $item->_result->itemlost_on( $lost_on );
4840         $item->_result->update();
4841
4842         my $a = Koha::Account::Lines->search(
4843             {
4844                 itemnumber     => $item->id,
4845                 borrowernumber => $patron->borrowernumber
4846             }
4847         )->next;
4848         ok( $a, "Found accountline for lost fee" );
4849         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4850         $issue = AddIssue( $patron2->unblessed, $item->barcode );
4851         $a = $a->get_from_storage;
4852         is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4853         $a->delete;
4854         $issue->delete;
4855     };
4856
4857     subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4858         plan tests => 3;
4859
4860         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4861         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4862
4863         my $lost_on = dt_from_string->subtract( days => 6 )->date;
4864
4865         my $item = $builder->build_sample_item(
4866             {
4867                 biblionumber     => $biblionumber,
4868                 library          => $library->branchcode,
4869                 replacementprice => '42',
4870             }
4871         );
4872         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4873         LostItem( $item->itemnumber, 'cli', 0 );
4874         $item->_result->itemlost(1);
4875         $item->_result->itemlost_on( $lost_on );
4876         $item->_result->update();
4877
4878         my $a = Koha::Account::Lines->search(
4879             {
4880                 itemnumber     => $item->id,
4881                 borrowernumber => $patron->borrowernumber
4882             }
4883         )->next;
4884         ok( $a, "Found accountline for lost fee" );
4885         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4886         $issue = AddIssue( $patron2->unblessed, $item->barcode );
4887         $a = $a->get_from_storage;
4888         is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4889         $a->delete;
4890     };
4891
4892     subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4893         plan tests => 3;
4894
4895         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4896         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4897
4898         my $lost_on = dt_from_string->subtract( days => 7 )->date;
4899
4900         my $item = $builder->build_sample_item(
4901             {
4902                 biblionumber     => $biblionumber,
4903                 library          => $library->branchcode,
4904                 replacementprice => '42',
4905             }
4906         );
4907         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4908         LostItem( $item->itemnumber, 'cli', 0 );
4909         $item->_result->itemlost(1);
4910         $item->_result->itemlost_on( $lost_on );
4911         $item->_result->update();
4912
4913         my $a = Koha::Account::Lines->search(
4914             {
4915                 itemnumber     => $item->id,
4916                 borrowernumber => $patron->borrowernumber
4917             }
4918         )->next;
4919         ok( $a, "Found accountline for lost fee" );
4920         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4921         $issue = AddIssue( $patron2->unblessed, $item->barcode );
4922         $a = $a->get_from_storage;
4923         is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4924         $a->delete;
4925     };
4926
4927     subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4928         plan tests => 3;
4929
4930         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4931         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4932
4933         my $lost_on = dt_from_string->subtract( days => 8 )->date;
4934
4935         my $item = $builder->build_sample_item(
4936             {
4937                 biblionumber     => $biblionumber,
4938                 library          => $library->branchcode,
4939                 replacementprice => '42',
4940             }
4941         );
4942         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4943         LostItem( $item->itemnumber, 'cli', 0 );
4944         $item->_result->itemlost(1);
4945         $item->_result->itemlost_on( $lost_on );
4946         $item->_result->update();
4947
4948         my $a = Koha::Account::Lines->search(
4949             {
4950                 itemnumber     => $item->id,
4951                 borrowernumber => $patron->borrowernumber
4952             }
4953         );
4954         $a = $a->next;
4955         ok( $a, "Found accountline for lost fee" );
4956         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4957         $issue = AddIssue( $patron2->unblessed, $item->barcode );
4958         $a = $a->get_from_storage;
4959         is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4960         $a->delete;
4961     };
4962 };
4963
4964 subtest 'transferbook tests' => sub {
4965     plan tests => 9;
4966
4967     throws_ok
4968     { C4::Circulation::transferbook({}); }
4969     'Koha::Exceptions::MissingParameter',
4970     'Koha::Patron->store raises an exception on missing params';
4971
4972     throws_ok
4973     { C4::Circulation::transferbook({to_branch=>'anything'}); }
4974     'Koha::Exceptions::MissingParameter',
4975     'Koha::Patron->store raises an exception on missing params';
4976
4977     throws_ok
4978     { C4::Circulation::transferbook({from_branch=>'anything'}); }
4979     'Koha::Exceptions::MissingParameter',
4980     'Koha::Patron->store raises an exception on missing params';
4981
4982     my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
4983     is( $doreturn, 0, "No return without barcode");
4984     ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
4985     is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
4986
4987     ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
4988     is( $doreturn, 0, "No return without barcode");
4989     ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
4990     is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
4991
4992 };
4993
4994 subtest 'Checkout should correctly terminate a transfer' => sub {
4995     plan tests => 7;
4996
4997     my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
4998     my $patron_1 = $builder->build_object(
4999         {
5000             class => 'Koha::Patrons',
5001             value => { branchcode => $library_1->branchcode }
5002         }
5003     );
5004     my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
5005     my $patron_2 = $builder->build_object(
5006         {
5007             class => 'Koha::Patrons',
5008             value => { branchcode => $library_2->branchcode }
5009         }
5010     );
5011
5012     my $item = $builder->build_sample_item(
5013         {
5014             library => $library_1->branchcode,
5015         }
5016     );
5017
5018     t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
5019     my $reserve_id = AddReserve(
5020         {
5021             branchcode     => $library_2->branchcode,
5022             borrowernumber => $patron_2->borrowernumber,
5023             biblionumber   => $item->biblionumber,
5024             itemnumber     => $item->itemnumber,
5025             priority       => 1,
5026         }
5027     );
5028
5029     my $do_transfer = 1;
5030     ModItemTransfer( $item->itemnumber, $library_1->branchcode,
5031         $library_2->branchcode, 'Manual' );
5032     ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
5033     GetOtherReserves( $item->itemnumber )
5034       ;    # To put the Reason, it's what does returns.pl...
5035     my $hold = Koha::Holds->find($reserve_id);
5036     is( $hold->found, 'T', 'Hold is in transit' );
5037     my $transfer = $item->get_transfer;
5038     is( $transfer->frombranch, $library_1->branchcode );
5039     is( $transfer->tobranch,   $library_2->branchcode );
5040     is( $transfer->reason,     'Reserve' );
5041
5042     t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
5043     AddIssue( $patron_1->unblessed, $item->barcode );
5044     $transfer = $transfer->get_from_storage;
5045     isnt( $transfer->datearrived, undef );
5046     $hold = $hold->get_from_storage;
5047     is( $hold->found, undef, 'Hold is waiting' );
5048     is( $hold->priority, 1, );
5049 };
5050
5051 subtest 'AddIssue records staff who checked out item if appropriate' => sub  {
5052     plan tests => 2;
5053
5054     $module->mock( 'userenv', sub { { branch => $library->{id} } } );
5055
5056     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5057     my $patron = $builder->build_object(
5058         {
5059             class => 'Koha::Patrons',
5060             value => { categorycode => $patron_category->{categorycode} }
5061         }
5062     );
5063     my $issuer = $builder->build_object(
5064         {
5065             class => 'Koha::Patrons',
5066             value => { categorycode => $patron_category->{categorycode} }
5067         }
5068     );
5069     my $item = $builder->build_sample_item(
5070         {
5071             library  => $library->{branchcode}
5072         }
5073     );
5074
5075     $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->{borrowernumber} } } );
5076
5077     my $dt_from = dt_from_string();
5078     my $dt_to   = dt_from_string()->add( days => 7 );
5079
5080     my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
5081
5082     is( $issue->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
5083
5084     t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
5085
5086     my $issue2 =
5087       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
5088
5089     is( $issue->issuer, $issuer->{borrowernumber}, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
5090 };
5091
5092 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
5093     plan tests => 2;
5094
5095     my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5096     my $patron_1 = $builder->build_object(
5097         {
5098             class => 'Koha::Patrons',
5099             value => { branchcode => $library_1->branchcode }
5100         }
5101     );
5102     my $patron_2 = $builder->build_object(
5103         {
5104             class => 'Koha::Patrons',
5105             value => { branchcode => $library_1->branchcode }
5106         }
5107     );
5108
5109     my $item = $builder->build_sample_item(
5110         {
5111             library => $library_1->branchcode,
5112         }
5113     );
5114
5115     AddIssue( $patron_1->unblessed, $item->barcode );
5116     ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
5117     AddIssue( $patron_2->unblessed, $item->barcode );
5118     ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
5119 };
5120
5121 subtest "updateWrongTransfer tests" => sub {
5122     plan tests => 5;
5123
5124     my $library1 = $builder->build_object( { class => 'Koha::Libraries' } );
5125     my $library2 = $builder->build_object( { class => 'Koha::Libraries' } );
5126     my $library3 = $builder->build_object( { class => 'Koha::Libraries' } );
5127     my $item     = $builder->build_sample_item(
5128         {
5129             homebranch    => $library1->branchcode,
5130             holdingbranch => $library2->branchcode,
5131             datelastseen  => undef
5132         }
5133     );
5134
5135     my $transfer = $builder->build_object(
5136         {
5137             class => 'Koha::Item::Transfers',
5138             value => {
5139                 itemnumber    => $item->itemnumber,
5140                 frombranch    => $library2->branchcode,
5141                 tobranch      => $library1->branchcode,
5142                 daterequested => dt_from_string,
5143                 datesent      => dt_from_string,
5144                 datecancelled => undef,
5145                 datearrived   => undef,
5146                 reason        => 'Manual'
5147             }
5148         }
5149     );
5150     is( ref($transfer), 'Koha::Item::Transfer', 'Mock transfer added' );
5151
5152     my $new_transfer = C4::Circulation::updateWrongTransfer($item->itemnumber, $library1->branchcode);
5153     is(ref($new_transfer), 'Koha::Item::Transfer', "updateWrongTransfer returns a 'Koha::Item::Transfer' object");
5154     ok( !$new_transfer->in_transit, "New transfer is NOT created as in transit (or cancelled)");
5155
5156     my $original_transfer = $transfer->get_from_storage;
5157     ok( defined($original_transfer->datecancelled), "Original transfer was cancelled");
5158     is( $original_transfer->cancellation_reason, 'WrongTransfer', "Original transfer cancellation reason is 'WrongTransfer'");
5159 };
5160
5161 subtest "SendCirculationAlert" => sub {
5162     plan tests => 2;
5163
5164     # When you would unsuspectingly call this unit test (with perl, not prove), you will be bitten by LOCK.
5165     # LOCK will commit changes and ruin your data
5166     # In order to prevent that, we will add KOHA_TESTING to $ENV; see further Circulation.pm
5167     $ENV{KOHA_TESTING} = 1;
5168
5169     # Setup branch, borrowr, and notice
5170     my $library = $builder->build_object({ class => 'Koha::Libraries' });
5171     set_userenv( $library->unblessed);
5172     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5173     C4::Members::Messaging::SetMessagingPreference({
5174         borrowernumber => $patron->id,
5175         message_transport_types => ['email'],
5176         message_attribute_id => 5
5177     });
5178     my $item = $builder->build_sample_item();
5179     my $checkin_notice = $builder->build_object({
5180         class => 'Koha::Notice::Templates',
5181         value =>{
5182             module => 'circulation',
5183             code => 'CHECKIN',
5184             branchcode => $library->branchcode,
5185             name => 'Test Checkin',
5186             is_html => 0,
5187             content => "Checkins:\n----\n[% biblio.title %]-[% old_checkout.issue_id %]\n----Thank you.",
5188             message_transport_type => 'email',
5189             lang => 'default'
5190         }
5191     })->store;
5192
5193     # Checkout an item, mark it returned, generate a notice
5194     my $issue_1 = AddIssue( $patron->unblessed, $item->barcode);
5195     MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5196     C4::Circulation::SendCirculationAlert({
5197         type => 'CHECKIN',
5198         item => $item->unblessed,
5199         borrower => $patron->unblessed,
5200         branch => $library->branchcode,
5201         issue => $issue_1
5202     });
5203     my $notice = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'CHECKIN' });
5204     is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\nThank you.", 'Letter generated with expected output on first checkin' );
5205
5206     # Checkout an item, mark it returned, generate a notice
5207     my $issue_2 = AddIssue( $patron->unblessed, $item->barcode);
5208     MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5209     C4::Circulation::SendCirculationAlert({
5210         type => 'CHECKIN',
5211         item => $item->unblessed,
5212         borrower => $patron->unblessed,
5213         branch => $library->branchcode,
5214         issue => $issue_2
5215     });
5216     $notice->discard_changes();
5217     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' );
5218
5219 };
5220
5221 subtest "GetSoonestRenewDate tests" => sub {
5222     plan tests => 5;
5223     Koha::CirculationRules->set_rule(
5224         {
5225             categorycode => undef,
5226             branchcode   => undef,
5227             itemtype     => undef,
5228             rule_name    => 'norenewalbefore',
5229             rule_value   => '7',
5230         }
5231     );
5232     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5233     my $item = $builder->build_sample_item();
5234     my $issue = AddIssue( $patron->unblessed, $item->barcode);
5235     my $datedue = dt_from_string( $issue->date_due() );
5236
5237     # Bug 14395
5238     # Test 'exact time' setting for syspref NoRenewalBeforePrecision
5239     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
5240     is(
5241         GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5242         $datedue->clone->add( days => -7 ),
5243         'Bug 14395: Renewals permitted 7 days before due date, as expected'
5244     );
5245
5246     # Bug 14395
5247     # Test 'date' setting for syspref NoRenewalBeforePrecision
5248     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5249     is(
5250         GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5251         $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
5252         'Bug 14395: Renewals permitted 7 days before due date, as expected'
5253     );
5254
5255
5256     Koha::CirculationRules->set_rule(
5257         {
5258             categorycode => undef,
5259             branchcode   => undef,
5260             itemtype     => undef,
5261             rule_name    => 'norenewalbefore',
5262             rule_value   => undef,
5263         }
5264     );
5265
5266     is(
5267         GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5268         dt_from_string,
5269         'Checkouts without auto-renewal can be renewed immediately if no norenewalbefore'
5270     );
5271
5272     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5273     $issue->auto_renew(1)->store;
5274     is(
5275         GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5276         $datedue->clone->truncate( to => 'day' ),
5277         'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5278     );
5279     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact' );
5280     is(
5281         GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5282         $datedue,
5283         'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5284     );
5285 };
5286
5287 $schema->storage->txn_rollback;
5288 C4::Context->clear_syspref_cache();
5289 $branches = Koha::Libraries->search();
5290 for my $branch ( $branches->next ) {
5291     my $key = $branch->branchcode . "_holidays";
5292     $cache->clear_from_cache($key);
5293 }