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