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