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