e579e78b8e31b594ec23b2cd7d9459e872ecee47
[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 => 46;
22 use Test::MockModule;
23 use Test::Deep qw( cmp_deeply );
24
25 use Data::Dumper;
26 use DateTime;
27 use Time::Fake;
28 use POSIX qw( floor );
29 use t::lib::Mocks;
30 use t::lib::TestBuilder;
31
32 use C4::Accounts;
33 use C4::Calendar;
34 use C4::Circulation;
35 use C4::Biblio;
36 use C4::Items;
37 use C4::Log;
38 use C4::Reserves;
39 use C4::Overdues qw(UpdateFine CalcFine);
40 use Koha::DateUtils;
41 use Koha::Database;
42 use Koha::Items;
43 use Koha::Checkouts;
44 use Koha::Patrons;
45 use Koha::CirculationRules;
46 use Koha::Subscriptions;
47 use Koha::Account::Lines;
48 use Koha::Account::Offsets;
49 use Koha::ActionLogs;
50
51 sub set_userenv {
52     my ( $library ) = @_;
53     t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
54 }
55
56 sub str {
57     my ( $error, $question, $alert ) = @_;
58     my $s;
59     $s  = %$error    ? ' (error: '    . join( ' ', keys %$error    ) . ')' : '';
60     $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
61     $s .= %$alert    ? ' (alert: '    . join( ' ', keys %$alert    ) . ')' : '';
62     return $s;
63 }
64
65 sub test_debarment_on_checkout {
66     my ($params) = @_;
67     my $item     = $params->{item};
68     my $library  = $params->{library};
69     my $patron   = $params->{patron};
70     my $due_date = $params->{due_date} || dt_from_string;
71     my $return_date = $params->{return_date} || dt_from_string;
72     my $expected_expiration_date = $params->{expiration_date};
73
74     $expected_expiration_date = output_pref(
75         {
76             dt         => $expected_expiration_date,
77             dateformat => 'sql',
78             dateonly   => 1,
79         }
80     );
81     my @caller      = caller;
82     my $line_number = $caller[2];
83     AddIssue( $patron, $item->{barcode}, $due_date );
84
85     my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode}, undef, $return_date );
86     is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
87         or diag('AddReturn returned message ' . Dumper $message );
88     my $debarments = Koha::Patron::Debarments::GetDebarments(
89         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
90     is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
91
92     is( $debarments->[0]->{expiration},
93         $expected_expiration_date, 'Test at line ' . $line_number );
94     Koha::Patron::Debarments::DelUniqueDebarment(
95         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
96 };
97
98 my $schema = Koha::Database->schema;
99 $schema->storage->txn_begin;
100 my $builder = t::lib::TestBuilder->new;
101 my $dbh = C4::Context->dbh;
102
103 # Prevent random failures by mocking ->now
104 my $now_value       = dt_from_string;
105 my $mocked_datetime = Test::MockModule->new('DateTime');
106 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
107
108 # Start transaction
109 $dbh->{RaiseError} = 1;
110
111 my $cache = Koha::Caches->get_instance();
112 $dbh->do(q|DELETE FROM special_holidays|);
113 $dbh->do(q|DELETE FROM repeatable_holidays|);
114 $cache->clear_from_cache('single_holidays');
115
116 # Start with a clean slate
117 $dbh->do('DELETE FROM issues');
118 $dbh->do('DELETE FROM borrowers');
119
120 my $library = $builder->build({
121     source => 'Branch',
122 });
123 my $library2 = $builder->build({
124     source => 'Branch',
125 });
126 my $itemtype = $builder->build(
127     {
128         source => 'Itemtype',
129         value  => {
130             notforloan          => undef,
131             rentalcharge        => 0,
132             rentalcharge_daily => 0,
133             defaultreplacecost  => undef,
134             processfee          => undef
135         }
136     }
137 )->{itemtype};
138 my $patron_category = $builder->build(
139     {
140         source => 'Category',
141         value  => {
142             category_type                 => 'P',
143             enrolmentfee                  => 0,
144             BlockExpiredPatronOpacActions => -1, # Pick the pref value
145         }
146     }
147 );
148
149 my $CircControl = C4::Context->preference('CircControl');
150 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
151
152 my $item = {
153     homebranch => $library2->{branchcode},
154     holdingbranch => $library2->{branchcode}
155 };
156
157 my $borrower = {
158     branchcode => $library2->{branchcode}
159 };
160
161 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
162
163 # No userenv, PickupLibrary
164 t::lib::Mocks::mock_preference('IndependentBranches', '0');
165 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
166 is(
167     C4::Context->preference('CircControl'),
168     'PickupLibrary',
169     'CircControl changed to PickupLibrary'
170 );
171 is(
172     C4::Circulation::_GetCircControlBranch($item, $borrower),
173     $item->{$HomeOrHoldingBranch},
174     '_GetCircControlBranch returned item branch (no userenv defined)'
175 );
176
177 # No userenv, PatronLibrary
178 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
179 is(
180     C4::Context->preference('CircControl'),
181     'PatronLibrary',
182     'CircControl changed to PatronLibrary'
183 );
184 is(
185     C4::Circulation::_GetCircControlBranch($item, $borrower),
186     $borrower->{branchcode},
187     '_GetCircControlBranch returned borrower branch'
188 );
189
190 # No userenv, ItemHomeLibrary
191 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
192 is(
193     C4::Context->preference('CircControl'),
194     'ItemHomeLibrary',
195     'CircControl changed to ItemHomeLibrary'
196 );
197 is(
198     $item->{$HomeOrHoldingBranch},
199     C4::Circulation::_GetCircControlBranch($item, $borrower),
200     '_GetCircControlBranch returned item branch'
201 );
202
203 # Now, set a userenv
204 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
205 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
206
207 # Userenv set, PickupLibrary
208 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
209 is(
210     C4::Context->preference('CircControl'),
211     'PickupLibrary',
212     'CircControl changed to PickupLibrary'
213 );
214 is(
215     C4::Circulation::_GetCircControlBranch($item, $borrower),
216     $library2->{branchcode},
217     '_GetCircControlBranch returned current branch'
218 );
219
220 # Userenv set, PatronLibrary
221 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
222 is(
223     C4::Context->preference('CircControl'),
224     'PatronLibrary',
225     'CircControl changed to PatronLibrary'
226 );
227 is(
228     C4::Circulation::_GetCircControlBranch($item, $borrower),
229     $borrower->{branchcode},
230     '_GetCircControlBranch returned borrower branch'
231 );
232
233 # Userenv set, ItemHomeLibrary
234 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
235 is(
236     C4::Context->preference('CircControl'),
237     'ItemHomeLibrary',
238     'CircControl changed to ItemHomeLibrary'
239 );
240 is(
241     C4::Circulation::_GetCircControlBranch($item, $borrower),
242     $item->{$HomeOrHoldingBranch},
243     '_GetCircControlBranch returned item branch'
244 );
245
246 # Reset initial configuration
247 t::lib::Mocks::mock_preference('CircControl', $CircControl);
248 is(
249     C4::Context->preference('CircControl'),
250     $CircControl,
251     'CircControl reset to its initial value'
252 );
253
254 # Set a simple circ policy
255 $dbh->do('DELETE FROM circulation_rules');
256 Koha::CirculationRules->set_rules(
257     {
258         categorycode => undef,
259         branchcode   => undef,
260         itemtype     => undef,
261         rules        => {
262             reservesallowed => 25,
263             issuelength     => 14,
264             lengthunit      => 'days',
265             renewalsallowed => 1,
266             renewalperiod   => 7,
267             norenewalbefore => undef,
268             auto_renew      => 0,
269             fine            => .10,
270             chargeperiod    => 1,
271         }
272     }
273 );
274
275 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
276 subtest "CanBookBeRenewed tests" => sub {
277     plan tests => 77;
278
279     C4::Context->set_preference('ItemsDeniedRenewal','');
280     # Generate test biblio
281     my $biblio = $builder->build_sample_biblio();
282
283     my $branch = $library2->{branchcode};
284
285     my $item_1 = $builder->build_sample_item(
286         {
287             biblionumber     => $biblio->biblionumber,
288             library          => $branch,
289             replacementprice => 12.00,
290             itype            => $itemtype
291         }
292     );
293     $reused_itemnumber_1 = $item_1->itemnumber;
294
295     my $item_2 = $builder->build_sample_item(
296         {
297             biblionumber     => $biblio->biblionumber,
298             library          => $branch,
299             replacementprice => 23.00,
300             itype            => $itemtype
301         }
302     );
303     $reused_itemnumber_2 = $item_2->itemnumber;
304
305     my $item_3 = $builder->build_sample_item(
306         {
307             biblionumber     => $biblio->biblionumber,
308             library          => $branch,
309             replacementprice => 23.00,
310             itype            => $itemtype
311         }
312     );
313
314     # Create borrowers
315     my %renewing_borrower_data = (
316         firstname =>  'John',
317         surname => 'Renewal',
318         categorycode => $patron_category->{categorycode},
319         branchcode => $branch,
320     );
321
322     my %reserving_borrower_data = (
323         firstname =>  'Katrin',
324         surname => 'Reservation',
325         categorycode => $patron_category->{categorycode},
326         branchcode => $branch,
327     );
328
329     my %hold_waiting_borrower_data = (
330         firstname =>  'Kyle',
331         surname => 'Reservation',
332         categorycode => $patron_category->{categorycode},
333         branchcode => $branch,
334     );
335
336     my %restricted_borrower_data = (
337         firstname =>  'Alice',
338         surname => 'Reservation',
339         categorycode => $patron_category->{categorycode},
340         debarred => '3228-01-01',
341         branchcode => $branch,
342     );
343
344     my %expired_borrower_data = (
345         firstname =>  'Ça',
346         surname => 'Glisse',
347         categorycode => $patron_category->{categorycode},
348         branchcode => $branch,
349         dateexpiry => dt_from_string->subtract( months => 1 ),
350     );
351
352     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
353     my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
354     my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
355     my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
356     my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
357
358     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
359     my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
360     my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
361
362     my $bibitems       = '';
363     my $priority       = '1';
364     my $resdate        = undef;
365     my $expdate        = undef;
366     my $notes          = '';
367     my $checkitem      = undef;
368     my $found          = undef;
369
370     my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
371     my $datedue = dt_from_string( $issue->date_due() );
372     is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
373
374     my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
375     $datedue = dt_from_string( $issue->date_due() );
376     is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
377
378
379     my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
380     is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
381
382     my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
383     is( $renewokay, 1, 'Can renew, no holds for this title or item');
384
385
386     # Biblio-level hold, renewal test
387     AddReserve(
388         {
389             branchcode       => $branch,
390             borrowernumber   => $reserving_borrowernumber,
391             biblionumber     => $biblio->biblionumber,
392             priority         => $priority,
393             reservation_date => $resdate,
394             expiration_date  => $expdate,
395             notes            => $notes,
396             itemnumber       => $checkitem,
397             found            => $found,
398         }
399     );
400
401     # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
402     Koha::CirculationRules->set_rule(
403         {
404             categorycode => undef,
405             branchcode   => undef,
406             itemtype     => undef,
407             rule_name    => 'onshelfholds',
408             rule_value   => '1',
409         }
410     );
411     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
412     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
413     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
414     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
415     is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
416
417     # Now let's add an item level hold, we should no longer be able to renew the item
418     my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
419         {
420             borrowernumber => $hold_waiting_borrowernumber,
421             biblionumber   => $biblio->biblionumber,
422             itemnumber     => $item_1->itemnumber,
423             branchcode     => $branch,
424             priority       => 3,
425         }
426     );
427     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
428     is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
429     $hold->delete();
430
431     # 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
432     # be able to renew these items
433     $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
434         {
435             borrowernumber => $hold_waiting_borrowernumber,
436             biblionumber   => $biblio->biblionumber,
437             itemnumber     => $item_3->itemnumber,
438             branchcode     => $branch,
439             priority       => 0,
440             found          => 'W'
441         }
442     );
443     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
444     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
445     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
446     is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
447     t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
448
449     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
450     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
451     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
452
453     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
454     is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
455     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
456
457     my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
458     my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
459     AddIssue($reserving_borrower, $item_3->barcode);
460     my $reserve = $dbh->selectrow_hashref(
461         'SELECT * FROM old_reserves WHERE reserve_id = ?',
462         { Slice => {} },
463         $reserveid
464     );
465     is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
466
467     # Item-level hold, renewal test
468     AddReserve(
469         {
470             branchcode       => $branch,
471             borrowernumber   => $reserving_borrowernumber,
472             biblionumber     => $biblio->biblionumber,
473             priority         => $priority,
474             reservation_date => $resdate,
475             expiration_date  => $expdate,
476             notes            => $notes,
477             itemnumber       => $item_1->itemnumber,
478             found            => $found,
479         }
480     );
481
482     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
483     is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
484     is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
485
486     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
487     is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
488
489     # Items can't fill hold for reasons
490     ModItem({ notforloan => 1 }, $biblio->biblionumber, $item_1->itemnumber);
491     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
492     is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
493     ModItem({ notforloan => 0, itype => $itemtype }, $biblio->biblionumber, $item_1->itemnumber);
494
495     # FIXME: Add more for itemtype not for loan etc.
496
497     # Restricted users cannot renew when RestrictionBlockRenewing is enabled
498     my $item_5 = $builder->build_sample_item(
499         {
500             biblionumber     => $biblio->biblionumber,
501             library          => $branch,
502             replacementprice => 23.00,
503             itype            => $itemtype,
504         }
505     );
506     my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
507     is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
508
509     t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
510     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
511     is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
512     ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
513     is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
514
515     # Users cannot renew an overdue item
516     my $item_6 = $builder->build_sample_item(
517         {
518             biblionumber     => $biblio->biblionumber,
519             library          => $branch,
520             replacementprice => 23.00,
521             itype            => $itemtype,
522         }
523     );
524
525     my $item_7 = $builder->build_sample_item(
526         {
527             biblionumber     => $biblio->biblionumber,
528             library          => $branch,
529             replacementprice => 23.00,
530             itype            => $itemtype,
531         }
532     );
533
534     my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
535     is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
536
537     my $now = dt_from_string();
538     my $five_weeks = DateTime::Duration->new(weeks => 5);
539     my $five_weeks_ago = $now - $five_weeks;
540     t::lib::Mocks::mock_preference('finesMode', 'production');
541
542     my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
543     is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
544
545     my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
546     C4::Overdues::UpdateFine(
547         {
548             issue_id       => $passeddatedue1->id(),
549             itemnumber     => $item_7->itemnumber,
550             borrowernumber => $renewing_borrower->{borrowernumber},
551             amount         => $fine,
552             due            => Koha::DateUtils::output_pref($five_weeks_ago)
553         }
554     );
555
556     t::lib::Mocks::mock_preference('RenewalLog', 0);
557     my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
558     my %params_renewal = (
559         timestamp => { -like => $date . "%" },
560         module => "CIRCULATION",
561         action => "RENEWAL",
562     );
563     my %params_issue = (
564         timestamp => { -like => $date . "%" },
565         module => "CIRCULATION",
566         action => "ISSUE"
567     );
568     my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
569     my $dt = dt_from_string();
570     Time::Fake->offset( $dt->epoch );
571     my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
572     my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
573     is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
574     isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
575     Time::Fake->reset;
576
577     t::lib::Mocks::mock_preference('RenewalLog', 1);
578     $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
579     $old_log_size = Koha::ActionLogs->count( \%params_renewal );
580     AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
581     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
582     is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
583
584     my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
585     is( $fines->count, 2, 'AddRenewal left both fines' );
586     isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
587     isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
588     $fines->delete();
589
590
591     my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
592     my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
593     AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
594     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
595     is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
596     $new_log_size = Koha::ActionLogs->count( \%params_issue );
597     is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
598
599     $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
600     $fines->delete();
601
602     t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
603     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
604     is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
605     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
606     is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
607
608
609     $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
610     $hold->cancel;
611
612     # Bug 14101
613     # Test automatic renewal before value for "norenewalbefore" in policy is set
614     # In this case automatic renewal is not permitted prior to due date
615     my $item_4 = $builder->build_sample_item(
616         {
617             biblionumber     => $biblio->biblionumber,
618             library          => $branch,
619             replacementprice => 16.00,
620             itype            => $itemtype,
621         }
622     );
623
624     $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
625     ( $renewokay, $error ) =
626       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
627     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
628     is( $error, 'auto_too_soon',
629         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
630     AddReserve(
631         {
632             branchcode       => $branch,
633             borrowernumber   => $reserving_borrowernumber,
634             biblionumber     => $biblio->biblionumber,
635             itemnumber       => $bibitems,
636             priority         => $priority,
637             reservation_date => $resdate,
638             expiration_date  => $expdate,
639             notes            => $notes,
640             title            => 'a title',
641             itemnumber       => $item_4->itemnumber,
642             found            => $found
643         }
644     );
645     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
646     is( $renewokay, 0, 'Still should not be able to renew' );
647     is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked' );
648     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
649     is( $renewokay, 0, 'Still should not be able to renew' );
650     is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
651     $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
652     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
653     is( $renewokay, 0, 'Still should not be able to renew' );
654     is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
655     ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
656
657
658
659     # Bug 7413
660     # Test premature manual renewal
661     Koha::CirculationRules->set_rule(
662         {
663             categorycode => undef,
664             branchcode   => undef,
665             itemtype     => undef,
666             rule_name    => 'norenewalbefore',
667             rule_value   => '7',
668         }
669     );
670
671     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
672     is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
673     is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
674
675     # Bug 14395
676     # Test 'exact time' setting for syspref NoRenewalBeforePrecision
677     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
678     is(
679         GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
680         $datedue->clone->add( days => -7 ),
681         'Bug 14395: Renewals permitted 7 days before due date, as expected'
682     );
683
684     # Bug 14395
685     # Test 'date' setting for syspref NoRenewalBeforePrecision
686     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
687     is(
688         GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
689         $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
690         'Bug 14395: Renewals permitted 7 days before due date, as expected'
691     );
692
693     # Bug 14101
694     # Test premature automatic renewal
695     ( $renewokay, $error ) =
696       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
697     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
698     is( $error, 'auto_too_soon',
699         'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
700     );
701
702     # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
703     # and test automatic renewal again
704     $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
705     ( $renewokay, $error ) =
706       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
707     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
708     is( $error, 'auto_too_soon',
709         'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
710     );
711
712     # Change policy so that loans can be renewed 99 days prior to the due date
713     # and test automatic renewal again
714     $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
715     ( $renewokay, $error ) =
716       CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
717     is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
718     is( $error, 'auto_renew',
719         'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
720     );
721
722     subtest "too_late_renewal / no_auto_renewal_after" => sub {
723         plan tests => 14;
724         my $item_to_auto_renew = $builder->build(
725             {   source => 'Item',
726                 value  => {
727                     biblionumber  => $biblio->biblionumber,
728                     homebranch    => $branch,
729                     holdingbranch => $branch,
730                 }
731             }
732         );
733
734         my $ten_days_before = dt_from_string->add( days => -10 );
735         my $ten_days_ahead  = dt_from_string->add( days => 10 );
736         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
737
738         Koha::CirculationRules->set_rules(
739             {
740                 categorycode => undef,
741                 branchcode   => undef,
742                 itemtype     => undef,
743                 rules        => {
744                     norenewalbefore       => '7',
745                     no_auto_renewal_after => '9',
746                 }
747             }
748         );
749         ( $renewokay, $error ) =
750           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
751         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
752         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
753
754         Koha::CirculationRules->set_rules(
755             {
756                 categorycode => undef,
757                 branchcode   => undef,
758                 itemtype     => undef,
759                 rules        => {
760                     norenewalbefore       => '7',
761                     no_auto_renewal_after => '10',
762                 }
763             }
764         );
765         ( $renewokay, $error ) =
766           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
767         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
768         is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
769
770         Koha::CirculationRules->set_rules(
771             {
772                 categorycode => undef,
773                 branchcode   => undef,
774                 itemtype     => undef,
775                 rules        => {
776                     norenewalbefore       => '7',
777                     no_auto_renewal_after => '11',
778                 }
779             }
780         );
781         ( $renewokay, $error ) =
782           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
783         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
784         is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
785
786         Koha::CirculationRules->set_rules(
787             {
788                 categorycode => undef,
789                 branchcode   => undef,
790                 itemtype     => undef,
791                 rules        => {
792                     norenewalbefore       => '10',
793                     no_auto_renewal_after => '11',
794                 }
795             }
796         );
797         ( $renewokay, $error ) =
798           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
799         is( $renewokay, 0,            'Do not renew, renewal is automatic' );
800         is( $error,     'auto_renew', 'Cannot renew, renew is automatic' );
801
802         Koha::CirculationRules->set_rules(
803             {
804                 categorycode => undef,
805                 branchcode   => undef,
806                 itemtype     => undef,
807                 rules        => {
808                     norenewalbefore       => '10',
809                     no_auto_renewal_after => undef,
810                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
811                 }
812             }
813         );
814         ( $renewokay, $error ) =
815           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
816         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
817         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
818
819         Koha::CirculationRules->set_rules(
820             {
821                 categorycode => undef,
822                 branchcode   => undef,
823                 itemtype     => undef,
824                 rules        => {
825                     norenewalbefore       => '7',
826                     no_auto_renewal_after => '15',
827                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
828                 }
829             }
830         );
831         ( $renewokay, $error ) =
832           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
833         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
834         is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
835
836         Koha::CirculationRules->set_rules(
837             {
838                 categorycode => undef,
839                 branchcode   => undef,
840                 itemtype     => undef,
841                 rules        => {
842                     norenewalbefore       => '10',
843                     no_auto_renewal_after => undef,
844                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
845                 }
846             }
847         );
848         ( $renewokay, $error ) =
849           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
850         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
851         is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
852     };
853
854     subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
855         plan tests => 10;
856         my $item_to_auto_renew = $builder->build({
857             source => 'Item',
858             value => {
859                 biblionumber => $biblio->biblionumber,
860                 homebranch       => $branch,
861                 holdingbranch    => $branch,
862             }
863         });
864
865         my $ten_days_before = dt_from_string->add( days => -10 );
866         my $ten_days_ahead = dt_from_string->add( days => 10 );
867         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
868
869         Koha::CirculationRules->set_rules(
870             {
871                 categorycode => undef,
872                 branchcode   => undef,
873                 itemtype     => undef,
874                 rules        => {
875                     norenewalbefore       => '10',
876                     no_auto_renewal_after => '11',
877                 }
878             }
879         );
880         C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
881         C4::Context->set_preference('OPACFineNoRenewals','10');
882         C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
883         my $fines_amount = 5;
884         my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
885         $account->add_debit(
886             {
887                 amount      => $fines_amount,
888                 interface   => 'test',
889                 type        => 'OVERDUE',
890                 item_id     => $item_to_auto_renew->{itemnumber},
891                 description => "Some fines"
892             }
893         )->status('RETURNED')->store;
894         ( $renewokay, $error ) =
895           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
896         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
897         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
898
899         $account->add_debit(
900             {
901                 amount      => $fines_amount,
902                 interface   => 'test',
903                 type        => 'OVERDUE',
904                 item_id     => $item_to_auto_renew->{itemnumber},
905                 description => "Some fines"
906             }
907         )->status('RETURNED')->store;
908         ( $renewokay, $error ) =
909           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
910         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
911         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
912
913         $account->add_debit(
914             {
915                 amount      => $fines_amount,
916                 interface   => 'test',
917                 type        => 'OVERDUE',
918                 item_id     => $item_to_auto_renew->{itemnumber},
919                 description => "Some fines"
920             }
921         )->status('RETURNED')->store;
922         ( $renewokay, $error ) =
923           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
924         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
925         is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
926
927         $account->add_credit(
928             {
929                 amount      => $fines_amount,
930                 interface   => 'test',
931                 type        => 'PAYMENT',
932                 description => "Some payment"
933             }
934         )->store;
935         ( $renewokay, $error ) =
936           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
937         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
938         is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit'  );
939
940         C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
941         ( $renewokay, $error ) =
942           CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
943         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
944         is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit'  );
945
946         $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
947         C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
948     };
949
950     subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
951         plan tests => 6;
952         my $item_to_auto_renew = $builder->build({
953             source => 'Item',
954             value => {
955                 biblionumber => $biblio->biblionumber,
956                 homebranch       => $branch,
957                 holdingbranch    => $branch,
958             }
959         });
960
961         Koha::CirculationRules->set_rules(
962             {
963                 categorycode => undef,
964                 branchcode   => undef,
965                 itemtype     => undef,
966                 rules        => {
967                     norenewalbefore       => 10,
968                     no_auto_renewal_after => 11,
969                 }
970             }
971         );
972
973         my $ten_days_before = dt_from_string->add( days => -10 );
974         my $ten_days_ahead = dt_from_string->add( days => 10 );
975
976         # Patron is expired and BlockExpiredPatronOpacActions=0
977         # => auto renew is allowed
978         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
979         my $patron = $expired_borrower;
980         my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
981         ( $renewokay, $error ) =
982           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
983         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
984         is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
985         Koha::Checkouts->find( $checkout->issue_id )->delete;
986
987
988         # Patron is expired and BlockExpiredPatronOpacActions=1
989         # => auto renew is not allowed
990         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
991         $patron = $expired_borrower;
992         $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
993         ( $renewokay, $error ) =
994           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
995         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
996         is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
997         Koha::Checkouts->find( $checkout->issue_id )->delete;
998
999
1000         # Patron is not expired and BlockExpiredPatronOpacActions=1
1001         # => auto renew is allowed
1002         t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1003         $patron = $renewing_borrower;
1004         $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1005         ( $renewokay, $error ) =
1006           CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
1007         is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1008         is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1009         Koha::Checkouts->find( $checkout->issue_id )->delete;
1010     };
1011
1012     subtest "GetLatestAutoRenewDate" => sub {
1013         plan tests => 5;
1014         my $item_to_auto_renew = $builder->build(
1015             {   source => 'Item',
1016                 value  => {
1017                     biblionumber  => $biblio->biblionumber,
1018                     homebranch    => $branch,
1019                     holdingbranch => $branch,
1020                 }
1021             }
1022         );
1023
1024         my $ten_days_before = dt_from_string->add( days => -10 );
1025         my $ten_days_ahead  = dt_from_string->add( days => 10 );
1026         AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1027         Koha::CirculationRules->set_rules(
1028             {
1029                 categorycode => undef,
1030                 branchcode   => undef,
1031                 itemtype     => undef,
1032                 rules        => {
1033                     norenewalbefore       => '7',
1034                     no_auto_renewal_after => '',
1035                     no_auto_renewal_after_hard_limit => undef,
1036                 }
1037             }
1038         );
1039         my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1040         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' );
1041         my $five_days_before = dt_from_string->add( days => -5 );
1042         Koha::CirculationRules->set_rules(
1043             {
1044                 categorycode => undef,
1045                 branchcode   => undef,
1046                 itemtype     => undef,
1047                 rules        => {
1048                     norenewalbefore       => '10',
1049                     no_auto_renewal_after => '5',
1050                     no_auto_renewal_after_hard_limit => undef,
1051                 }
1052             }
1053         );
1054         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1055         is( $latest_auto_renew_date->truncate( to => 'minute' ),
1056             $five_days_before->truncate( to => 'minute' ),
1057             'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1058         );
1059         my $five_days_ahead = dt_from_string->add( days => 5 );
1060         $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1061         $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1062         $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1063         Koha::CirculationRules->set_rules(
1064             {
1065                 categorycode => undef,
1066                 branchcode   => undef,
1067                 itemtype     => undef,
1068                 rules        => {
1069                     norenewalbefore       => '10',
1070                     no_auto_renewal_after => '15',
1071                     no_auto_renewal_after_hard_limit => undef,
1072                 }
1073             }
1074         );
1075         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1076         is( $latest_auto_renew_date->truncate( to => 'minute' ),
1077             $five_days_ahead->truncate( to => 'minute' ),
1078             'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1079         );
1080         my $two_days_ahead = dt_from_string->add( days => 2 );
1081         Koha::CirculationRules->set_rules(
1082             {
1083                 categorycode => undef,
1084                 branchcode   => undef,
1085                 itemtype     => undef,
1086                 rules        => {
1087                     norenewalbefore       => '10',
1088                     no_auto_renewal_after => '',
1089                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1090                 }
1091             }
1092         );
1093         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1094         is( $latest_auto_renew_date->truncate( to => 'day' ),
1095             $two_days_ahead->truncate( to => 'day' ),
1096             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1097         );
1098         Koha::CirculationRules->set_rules(
1099             {
1100                 categorycode => undef,
1101                 branchcode   => undef,
1102                 itemtype     => undef,
1103                 rules        => {
1104                     norenewalbefore       => '10',
1105                     no_auto_renewal_after => '15',
1106                     no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1107                 }
1108             }
1109         );
1110         $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1111         is( $latest_auto_renew_date->truncate( to => 'day' ),
1112             $two_days_ahead->truncate( to => 'day' ),
1113             'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1114         );
1115
1116     };
1117     # Too many renewals
1118
1119     # set policy to forbid renewals
1120     Koha::CirculationRules->set_rules(
1121         {
1122             categorycode => undef,
1123             branchcode   => undef,
1124             itemtype     => undef,
1125             rules        => {
1126                 norenewalbefore => undef,
1127                 renewalsallowed => 0,
1128             }
1129         }
1130     );
1131
1132     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1133     is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1134     is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1135
1136     # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1137     t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1138     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1139
1140     C4::Overdues::UpdateFine(
1141         {
1142             issue_id       => $issue->id(),
1143             itemnumber     => $item_1->itemnumber,
1144             borrowernumber => $renewing_borrower->{borrowernumber},
1145             amount         => 15.00,
1146             type           => q{},
1147             due            => Koha::DateUtils::output_pref($datedue)
1148         }
1149     );
1150
1151     my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
1152     is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1153     is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1154     is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1155     is( $line->amount+0, 15, 'Account line amount is 15.00' );
1156     is( $line->issue_id, $issue->id, 'Account line issue id matches' );
1157
1158     my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1159     is( $offset->type, 'OVERDUE', 'Account offset type is Fine' );
1160     is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1161
1162     t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1163     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1164
1165     LostItem( $item_1->itemnumber, 'test', 1 );
1166
1167     $line = Koha::Account::Lines->find($line->id);
1168     is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1169     isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1170
1171     my $item = Koha::Items->find($item_1->itemnumber);
1172     ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1173     my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1174     is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1175
1176     my $total_due = $dbh->selectrow_array(
1177         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1178         undef, $renewing_borrower->{borrowernumber}
1179     );
1180
1181     is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1182
1183     C4::Context->dbh->do("DELETE FROM accountlines");
1184
1185     C4::Overdues::UpdateFine(
1186         {
1187             issue_id       => $issue2->id(),
1188             itemnumber     => $item_2->itemnumber,
1189             borrowernumber => $renewing_borrower->{borrowernumber},
1190             amount         => 15.00,
1191             type           => q{},
1192             due            => Koha::DateUtils::output_pref($datedue)
1193         }
1194     );
1195
1196     LostItem( $item_2->itemnumber, 'test', 0 );
1197
1198     my $item2 = Koha::Items->find($item_2->itemnumber);
1199     ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1200     ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1201
1202     $total_due = $dbh->selectrow_array(
1203         'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1204         undef, $renewing_borrower->{borrowernumber}
1205     );
1206
1207     ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1208
1209     my $future = dt_from_string();
1210     $future->add( days => 7 );
1211     my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1212     ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1213
1214     # Users cannot renew any item if there is an overdue item
1215     t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
1216     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
1217     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1218     ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
1219     is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1220
1221     my $manager = $builder->build_object({ class => "Koha::Patrons" });
1222     t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1223     t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1224     $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1225     LostItem( $item_3->itemnumber, 'test', 0 );
1226     my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1227     is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1228     is(
1229         $accountline->description,
1230         sprintf( "%s %s %s",
1231             $item_3->biblio->title  || '',
1232             $item_3->barcode        || '',
1233             $item_3->itemcallnumber || '' ),
1234         "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1235     );
1236 };
1237
1238 subtest "GetUpcomingDueIssues" => sub {
1239     plan tests => 12;
1240
1241     my $branch   = $library2->{branchcode};
1242
1243     #Create another record
1244     my $biblio2 = $builder->build_sample_biblio();
1245
1246     #Create third item
1247     my $item_1 = Koha::Items->find($reused_itemnumber_1);
1248     my $item_2 = Koha::Items->find($reused_itemnumber_2);
1249     my $item_3 = $builder->build_sample_item(
1250         {
1251             biblionumber     => $biblio2->biblionumber,
1252             library          => $branch,
1253             itype            => $itemtype,
1254         }
1255     );
1256
1257
1258     # Create a borrower
1259     my %a_borrower_data = (
1260         firstname =>  'Fridolyn',
1261         surname => 'SOMERS',
1262         categorycode => $patron_category->{categorycode},
1263         branchcode => $branch,
1264     );
1265
1266     my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1267     my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1268
1269     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1270     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1271     my $today = DateTime->today(time_zone => C4::Context->tz());
1272
1273     my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1274     my $datedue = dt_from_string( $issue->date_due() );
1275     my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1276     my $datedue2 = dt_from_string( $issue->date_due() );
1277
1278     my $upcoming_dues;
1279
1280     # GetUpcomingDueIssues tests
1281     for my $i(0..1) {
1282         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1283         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1284     }
1285
1286     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1287     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1288     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1289
1290     for my $i(3..5) {
1291         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1292         is ( scalar( @$upcoming_dues ), 1,
1293             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1294     }
1295
1296     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1297
1298     my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1299
1300     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1301     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1302
1303     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1304     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1305
1306     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1307     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1308
1309     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
1310     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1311
1312     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1313     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1314
1315     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1316     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1317
1318 };
1319
1320 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1321     my $branch   = $library2->{branchcode};
1322
1323     my $biblio = $builder->build_sample_biblio();
1324
1325     #Create third item
1326     my $item = $builder->build_sample_item(
1327         {
1328             biblionumber     => $biblio->biblionumber,
1329             library          => $branch,
1330             itype            => $itemtype,
1331         }
1332     );
1333
1334     # Create a borrower
1335     my %a_borrower_data = (
1336         firstname =>  'Kyle',
1337         surname => 'Hall',
1338         categorycode => $patron_category->{categorycode},
1339         branchcode => $branch,
1340     );
1341
1342     my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1343
1344     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1345     my $issue = AddIssue( $borrower, $item->barcode );
1346     UpdateFine(
1347         {
1348             issue_id       => $issue->id(),
1349             itemnumber     => $item->itemnumber,
1350             borrowernumber => $borrowernumber,
1351             amount         => 0,
1352             type           => q{}
1353         }
1354     );
1355
1356     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1357     my $count = $hr->{count};
1358
1359     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1360 };
1361
1362 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1363     $dbh->do('DELETE FROM issues');
1364     $dbh->do('DELETE FROM items');
1365     $dbh->do('DELETE FROM circulation_rules');
1366     Koha::CirculationRules->set_rules(
1367         {
1368             categorycode => undef,
1369             itemtype     => undef,
1370             branchcode   => undef,
1371             rules        => {
1372                 reservesallowed => 25,
1373                 issuelength     => 14,
1374                 lengthunit      => 'days',
1375                 renewalsallowed => 1,
1376                 renewalperiod   => 7,
1377                 norenewalbefore => undef,
1378                 auto_renew      => 0,
1379                 fine            => .10,
1380                 chargeperiod    => 1,
1381                 maxissueqty     => 20
1382             }
1383         }
1384     );
1385     my $biblio = $builder->build_sample_biblio();
1386
1387     my $item_1 = $builder->build_sample_item(
1388         {
1389             biblionumber     => $biblio->biblionumber,
1390             library          => $library2->{branchcode},
1391             itype            => $itemtype,
1392         }
1393     );
1394
1395     my $item_2= $builder->build_sample_item(
1396         {
1397             biblionumber     => $biblio->biblionumber,
1398             library          => $library2->{branchcode},
1399             itype            => $itemtype,
1400         }
1401     );
1402
1403     my $borrowernumber1 = Koha::Patron->new({
1404         firstname    => 'Kyle',
1405         surname      => 'Hall',
1406         categorycode => $patron_category->{categorycode},
1407         branchcode   => $library2->{branchcode},
1408     })->store->borrowernumber;
1409     my $borrowernumber2 = Koha::Patron->new({
1410         firstname    => 'Chelsea',
1411         surname      => 'Hall',
1412         categorycode => $patron_category->{categorycode},
1413         branchcode   => $library2->{branchcode},
1414     })->store->borrowernumber;
1415
1416     my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1417     my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1418
1419     my $issue = AddIssue( $borrower1, $item_1->barcode );
1420
1421     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1422     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1423
1424     AddReserve(
1425         {
1426             branchcode     => $library2->{branchcode},
1427             borrowernumber => $borrowernumber2,
1428             biblionumber   => $biblio->biblionumber,
1429             priority       => 1,
1430         }
1431     );
1432
1433     Koha::CirculationRules->set_rules(
1434         {
1435             categorycode => undef,
1436             itemtype     => undef,
1437             branchcode   => undef,
1438             rules        => {
1439                 onshelfholds => 0,
1440             }
1441         }
1442     );
1443     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1444     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1445     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1446
1447     Koha::CirculationRules->set_rules(
1448         {
1449             categorycode => undef,
1450             itemtype     => undef,
1451             branchcode   => undef,
1452             rules        => {
1453                 onshelfholds => 0,
1454             }
1455         }
1456     );
1457     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1458     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1459     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1460
1461     Koha::CirculationRules->set_rules(
1462         {
1463             categorycode => undef,
1464             itemtype     => undef,
1465             branchcode   => undef,
1466             rules        => {
1467                 onshelfholds => 1,
1468             }
1469         }
1470     );
1471     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1472     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1473     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1474
1475     Koha::CirculationRules->set_rules(
1476         {
1477             categorycode => undef,
1478             itemtype     => undef,
1479             branchcode   => undef,
1480             rules        => {
1481                 onshelfholds => 1,
1482             }
1483         }
1484     );
1485     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1486     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1487     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1488
1489     # Setting item not checked out to be not for loan but holdable
1490     ModItem({ notforloan => -1 }, $biblio->biblionumber, $item_2->itemnumber);
1491
1492     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1493     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' );
1494 };
1495
1496 {
1497     # Don't allow renewing onsite checkout
1498     my $branch   = $library->{branchcode};
1499
1500     #Create another record
1501     my $biblio = $builder->build_sample_biblio();
1502
1503     my $item = $builder->build_sample_item(
1504         {
1505             biblionumber     => $biblio->biblionumber,
1506             library          => $branch,
1507             itype            => $itemtype,
1508         }
1509     );
1510
1511     my $borrowernumber = Koha::Patron->new({
1512         firstname =>  'fn',
1513         surname => 'dn',
1514         categorycode => $patron_category->{categorycode},
1515         branchcode => $branch,
1516     })->store->borrowernumber;
1517
1518     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1519
1520     my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1521     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1522     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1523     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1524 }
1525
1526 {
1527     my $library = $builder->build({ source => 'Branch' });
1528
1529     my $biblio = $builder->build_sample_biblio();
1530
1531     my $item = $builder->build_sample_item(
1532         {
1533             biblionumber     => $biblio->biblionumber,
1534             library          => $library->{branchcode},
1535             itype            => $itemtype,
1536         }
1537     );
1538
1539     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1540
1541     my $issue = AddIssue( $patron, $item->barcode );
1542     UpdateFine(
1543         {
1544             issue_id       => $issue->id(),
1545             itemnumber     => $item->itemnumber,
1546             borrowernumber => $patron->{borrowernumber},
1547             amount         => 1,
1548             type           => q{}
1549         }
1550     );
1551     UpdateFine(
1552         {
1553             issue_id       => $issue->id(),
1554             itemnumber     => $item->itemnumber,
1555             borrowernumber => $patron->{borrowernumber},
1556             amount         => 2,
1557             type           => q{}
1558         }
1559     );
1560     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1561 }
1562
1563 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1564     plan tests => 24;
1565
1566     my $homebranch    = $builder->build( { source => 'Branch' } );
1567     my $holdingbranch = $builder->build( { source => 'Branch' } );
1568     my $otherbranch   = $builder->build( { source => 'Branch' } );
1569     my $patron_1      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1570     my $patron_2      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1571
1572     my $item = $builder->build_sample_item(
1573         {
1574             homebranch    => $homebranch->{branchcode},
1575             holdingbranch => $holdingbranch->{branchcode},
1576         }
1577     )->unblessed;
1578
1579     set_userenv($holdingbranch);
1580
1581     my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1582     is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1583
1584     my ( $error, $question, $alerts );
1585
1586     # AllowReturnToBranch == anywhere
1587     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1588     ## Test that unknown barcodes don't generate internal server errors
1589     set_userenv($homebranch);
1590     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1591     ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1592     ## Can be issued from homebranch
1593     set_userenv($homebranch);
1594     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1595     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1596     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1597     ## Can be issued from holdingbranch
1598     set_userenv($holdingbranch);
1599     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1600     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1601     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1602     ## Can be issued from another branch
1603     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1604     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1605     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1606
1607     # AllowReturnToBranch == holdingbranch
1608     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1609     ## Cannot be issued from homebranch
1610     set_userenv($homebranch);
1611     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1612     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1613     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1614     is( $error->{branch_to_return},         $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1615     ## Can be issued from holdinbranch
1616     set_userenv($holdingbranch);
1617     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1618     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1619     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1620     ## Cannot be issued from another branch
1621     set_userenv($otherbranch);
1622     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1623     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1624     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1625     is( $error->{branch_to_return},         $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
1626
1627     # AllowReturnToBranch == homebranch
1628     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1629     ## Can be issued from holdinbranch
1630     set_userenv($homebranch);
1631     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1632     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1633     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1634     ## Cannot be issued from holdinbranch
1635     set_userenv($holdingbranch);
1636     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1637     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1638     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1639     is( $error->{branch_to_return},         $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1640     ## Cannot be issued from holdinbranch
1641     set_userenv($otherbranch);
1642     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1643     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1644     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1645     is( $error->{branch_to_return},         $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1646
1647     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1648 };
1649
1650 subtest 'AddIssue & AllowReturnToBranch' => sub {
1651     plan tests => 9;
1652
1653     my $homebranch    = $builder->build( { source => 'Branch' } );
1654     my $holdingbranch = $builder->build( { source => 'Branch' } );
1655     my $otherbranch   = $builder->build( { source => 'Branch' } );
1656     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1657     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1658
1659     my $item = $builder->build_sample_item(
1660         {
1661             homebranch    => $homebranch->{branchcode},
1662             holdingbranch => $holdingbranch->{branchcode},
1663         }
1664     )->unblessed;
1665
1666     set_userenv($holdingbranch);
1667
1668     my $ref_issue = 'Koha::Checkout';
1669     my $issue = AddIssue( $patron_1, $item->{barcode} );
1670
1671     my ( $error, $question, $alerts );
1672
1673     # AllowReturnToBranch == homebranch
1674     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1675     ## Can be issued from homebranch
1676     set_userenv($homebranch);
1677     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
1678     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1679     ## Can be issued from holdinbranch
1680     set_userenv($holdingbranch);
1681     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
1682     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1683     ## Can be issued from another branch
1684     set_userenv($otherbranch);
1685     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
1686     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1687
1688     # AllowReturnToBranch == holdinbranch
1689     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1690     ## Cannot be issued from homebranch
1691     set_userenv($homebranch);
1692     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
1693     ## Can be issued from holdingbranch
1694     set_userenv($holdingbranch);
1695     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
1696     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1697     ## Cannot be issued from another branch
1698     set_userenv($otherbranch);
1699     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
1700
1701     # AllowReturnToBranch == homebranch
1702     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1703     ## Can be issued from homebranch
1704     set_userenv($homebranch);
1705     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
1706     set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1707     ## Cannot be issued from holdinbranch
1708     set_userenv($holdingbranch);
1709     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
1710     ## Cannot be issued from another branch
1711     set_userenv($otherbranch);
1712     is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
1713     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1714 };
1715
1716 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1717     plan tests => 8;
1718
1719     my $library = $builder->build( { source => 'Branch' } );
1720     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1721     my $item_1 = $builder->build_sample_item(
1722         {
1723             library => $library->{branchcode},
1724         }
1725     )->unblessed;
1726     my $item_2 = $builder->build_sample_item(
1727         {
1728             library => $library->{branchcode},
1729         }
1730     )->unblessed;
1731
1732     my ( $error, $question, $alerts );
1733
1734     # Patron cannot issue item_1, they have overdues
1735     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1736     my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday );    # Add an overdue
1737
1738     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1739     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1740     is( keys(%$error) + keys(%$alerts),  0, 'No key for error and alert' . str($error, $question, $alerts) );
1741     is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1742
1743     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1744     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1745     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1746     is( $error->{USERBLOCKEDOVERDUE},      1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1747
1748     # Patron cannot issue item_1, they are debarred
1749     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1750     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1751     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1752     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1753     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1754
1755     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1756     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1757     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
1758     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1759 };
1760
1761 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1762     plan tests => 1;
1763
1764     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1765     my $patron_category_x = $builder->build_object(
1766         {
1767             class => 'Koha::Patron::Categories',
1768             value => { category_type => 'X' }
1769         }
1770     );
1771     my $patron = $builder->build_object(
1772         {
1773             class => 'Koha::Patrons',
1774             value => {
1775                 categorycode  => $patron_category_x->categorycode,
1776                 gonenoaddress => undef,
1777                 lost          => undef,
1778                 debarred      => undef,
1779                 borrowernotes => ""
1780             }
1781         }
1782     );
1783     my $item_1 = $builder->build_sample_item(
1784         {
1785             library => $library->{branchcode},
1786         }
1787     )->unblessed;
1788
1789     my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1790     is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1791
1792     # TODO There are other tests to provide here
1793 };
1794
1795 subtest 'MultipleReserves' => sub {
1796     plan tests => 3;
1797
1798     my $biblio = $builder->build_sample_biblio();
1799
1800     my $branch = $library2->{branchcode};
1801
1802     my $item_1 = $builder->build_sample_item(
1803         {
1804             biblionumber     => $biblio->biblionumber,
1805             library          => $branch,
1806             replacementprice => 12.00,
1807             itype            => $itemtype,
1808         }
1809     );
1810
1811     my $item_2 = $builder->build_sample_item(
1812         {
1813             biblionumber     => $biblio->biblionumber,
1814             library          => $branch,
1815             replacementprice => 12.00,
1816             itype            => $itemtype,
1817         }
1818     );
1819
1820     my $bibitems       = '';
1821     my $priority       = '1';
1822     my $resdate        = undef;
1823     my $expdate        = undef;
1824     my $notes          = '';
1825     my $checkitem      = undef;
1826     my $found          = undef;
1827
1828     my %renewing_borrower_data = (
1829         firstname =>  'John',
1830         surname => 'Renewal',
1831         categorycode => $patron_category->{categorycode},
1832         branchcode => $branch,
1833     );
1834     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1835     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1836     my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1837     my $datedue = dt_from_string( $issue->date_due() );
1838     is (defined $issue->date_due(), 1, "item 1 checked out");
1839     my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1840
1841     my %reserving_borrower_data1 = (
1842         firstname =>  'Katrin',
1843         surname => 'Reservation',
1844         categorycode => $patron_category->{categorycode},
1845         branchcode => $branch,
1846     );
1847     my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1848     AddReserve(
1849         {
1850             branchcode       => $branch,
1851             borrowernumber   => $reserving_borrowernumber1,
1852             biblionumber     => $biblio->biblionumber,
1853             priority         => $priority,
1854             reservation_date => $resdate,
1855             expiration_date  => $expdate,
1856             notes            => $notes,
1857             itemnumber       => $checkitem,
1858             found            => $found,
1859         }
1860     );
1861
1862     my %reserving_borrower_data2 = (
1863         firstname =>  'Kirk',
1864         surname => 'Reservation',
1865         categorycode => $patron_category->{categorycode},
1866         branchcode => $branch,
1867     );
1868     my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1869     AddReserve(
1870         {
1871             branchcode       => $branch,
1872             borrowernumber   => $reserving_borrowernumber2,
1873             biblionumber     => $biblio->biblionumber,
1874             priority         => $priority,
1875             reservation_date => $resdate,
1876             expiration_date  => $expdate,
1877             notes            => $notes,
1878             itemnumber       => $checkitem,
1879             found            => $found,
1880         }
1881     );
1882
1883     {
1884         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1885         is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1886     }
1887
1888     my $item_3 = $builder->build_sample_item(
1889         {
1890             biblionumber     => $biblio->biblionumber,
1891             library          => $branch,
1892             replacementprice => 12.00,
1893             itype            => $itemtype,
1894         }
1895     );
1896
1897     {
1898         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1899         is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1900     }
1901 };
1902
1903 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1904     plan tests => 5;
1905
1906     my $library = $builder->build( { source => 'Branch' } );
1907     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1908
1909     my $biblionumber = $builder->build_sample_biblio(
1910         {
1911             branchcode => $library->{branchcode},
1912         }
1913     )->biblionumber;
1914     my $item_1 = $builder->build_sample_item(
1915         {
1916             biblionumber => $biblionumber,
1917             library      => $library->{branchcode},
1918         }
1919     )->unblessed;
1920
1921     my $item_2 = $builder->build_sample_item(
1922         {
1923             biblionumber => $biblionumber,
1924             library      => $library->{branchcode},
1925         }
1926     )->unblessed;
1927
1928     my ( $error, $question, $alerts );
1929     my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1930
1931     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1932     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1933     cmp_deeply(
1934         { error => $error, alerts => $alerts },
1935         { error => {}, alerts => {} },
1936         'No error or alert should be raised'
1937     );
1938     is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
1939
1940     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1941     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1942     cmp_deeply(
1943         { error => $error, question => $question, alerts => $alerts },
1944         { error => {}, question => {}, alerts => {} },
1945         'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
1946     );
1947
1948     # Add a subscription
1949     Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1950
1951     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1952     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1953     cmp_deeply(
1954         { error => $error, question => $question, alerts => $alerts },
1955         { error => {}, question => {}, alerts => {} },
1956         'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
1957     );
1958
1959     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1960     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1961     cmp_deeply(
1962         { error => $error, question => $question, alerts => $alerts },
1963         { error => {}, question => {}, alerts => {} },
1964         'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
1965     );
1966 };
1967
1968 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1969     plan tests => 8;
1970
1971     my $library = $builder->build( { source => 'Branch' } );
1972     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1973
1974     # Add 2 items
1975     my $biblionumber = $builder->build_sample_biblio(
1976         {
1977             branchcode => $library->{branchcode},
1978         }
1979     )->biblionumber;
1980     my $item_1 = $builder->build_sample_item(
1981         {
1982             biblionumber => $biblionumber,
1983             library      => $library->{branchcode},
1984         }
1985     )->unblessed;
1986     my $item_2 = $builder->build_sample_item(
1987         {
1988             biblionumber => $biblionumber,
1989             library      => $library->{branchcode},
1990         }
1991     )->unblessed;
1992
1993     # And the circulation rule
1994     Koha::CirculationRules->search->delete;
1995     Koha::CirculationRules->set_rules(
1996         {
1997             categorycode => undef,
1998             itemtype     => undef,
1999             branchcode   => undef,
2000             rules        => {
2001                 issuelength => 1,
2002                 firstremind => 1,        # 1 day of grace
2003                 finedays    => 2,        # 2 days of fine per day of overdue
2004                 lengthunit  => 'days',
2005             }
2006         }
2007     );
2008
2009     # Patron cannot issue item_1, they have overdues
2010     my $now = dt_from_string;
2011     my $five_days_ago = $now->clone->subtract( days => 5 );
2012     my $ten_days_ago  = $now->clone->subtract( days => 10 );
2013     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
2014     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
2015       ;    # Add another overdue
2016
2017     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2018     AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, $now );
2019     my $debarments = Koha::Patron::Debarments::GetDebarments(
2020         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2021     is( scalar(@$debarments), 1 );
2022
2023     # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2024     # Same for the others
2025     my $expected_expiration = output_pref(
2026         {
2027             dt         => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2028             dateformat => 'sql',
2029             dateonly   => 1
2030         }
2031     );
2032     is( $debarments->[0]->{expiration}, $expected_expiration );
2033
2034     AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, $now );
2035     $debarments = Koha::Patron::Debarments::GetDebarments(
2036         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2037     is( scalar(@$debarments), 1 );
2038     $expected_expiration = output_pref(
2039         {
2040             dt         => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2041             dateformat => 'sql',
2042             dateonly   => 1
2043         }
2044     );
2045     is( $debarments->[0]->{expiration}, $expected_expiration );
2046
2047     Koha::Patron::Debarments::DelUniqueDebarment(
2048         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2049
2050     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2051     AddIssue( $patron, $item_1->{barcode}, $five_days_ago );    # Add an overdue
2052     AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
2053       ;    # Add another overdue
2054     AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, $now );
2055     $debarments = Koha::Patron::Debarments::GetDebarments(
2056         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2057     is( scalar(@$debarments), 1 );
2058     $expected_expiration = output_pref(
2059         {
2060             dt         => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2061             dateformat => 'sql',
2062             dateonly   => 1
2063         }
2064     );
2065     is( $debarments->[0]->{expiration}, $expected_expiration );
2066
2067     AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, $now );
2068     $debarments = Koha::Patron::Debarments::GetDebarments(
2069         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2070     is( scalar(@$debarments), 1 );
2071     $expected_expiration = output_pref(
2072         {
2073             dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2074             dateformat => 'sql',
2075             dateonly   => 1
2076         }
2077     );
2078     is( $debarments->[0]->{expiration}, $expected_expiration );
2079 };
2080
2081 subtest 'AddReturn + suspension_chargeperiod' => sub {
2082     plan tests => 21;
2083
2084     my $library = $builder->build( { source => 'Branch' } );
2085     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2086
2087     my $biblionumber = $builder->build_sample_biblio(
2088         {
2089             branchcode => $library->{branchcode},
2090         }
2091     )->biblionumber;
2092     my $item_1 = $builder->build_sample_item(
2093         {
2094             biblionumber => $biblionumber,
2095             library      => $library->{branchcode},
2096         }
2097     )->unblessed;
2098
2099     # And the issuing rule
2100     Koha::CirculationRules->search->delete;
2101     Koha::CirculationRules->set_rules(
2102         {
2103             categorycode => '*',
2104             itemtype     => '*',
2105             branchcode   => '*',
2106             rules        => {
2107                 issuelength => 1,
2108                 firstremind => 0,    # 0 day of grace
2109                 finedays    => 2,    # 2 days of fine per day of overdue
2110                 suspension_chargeperiod => 1,
2111                 lengthunit              => 'days',
2112             }
2113         }
2114     );
2115
2116     my $now = dt_from_string;
2117     my $five_days_ago = $now->clone->subtract( days => 5 );
2118     # We want to charge 2 days every day, without grace
2119     # With 5 days of overdue: 5 * Z
2120     my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2121     test_debarment_on_checkout(
2122         {
2123             item            => $item_1,
2124             library         => $library,
2125             patron          => $patron,
2126             due_date        => $five_days_ago,
2127             expiration_date => $expected_expiration,
2128         }
2129     );
2130
2131     # We want to charge 2 days every 2 days, without grace
2132     # With 5 days of overdue: (5 * 2) / 2
2133     Koha::CirculationRules->set_rule(
2134         {
2135             categorycode => undef,
2136             branchcode   => undef,
2137             itemtype     => undef,
2138             rule_name    => 'suspension_chargeperiod',
2139             rule_value   => '2',
2140         }
2141     );
2142
2143     $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2144     test_debarment_on_checkout(
2145         {
2146             item            => $item_1,
2147             library         => $library,
2148             patron          => $patron,
2149             due_date        => $five_days_ago,
2150             expiration_date => $expected_expiration,
2151         }
2152     );
2153
2154     # We want to charge 2 days every 3 days, with 1 day of grace
2155     # With 5 days of overdue: ((5-1) / 3 ) * 2
2156     Koha::CirculationRules->set_rules(
2157         {
2158             categorycode => undef,
2159             branchcode   => undef,
2160             itemtype     => undef,
2161             rules        => {
2162                 suspension_chargeperiod => 3,
2163                 firstremind             => 1,
2164             }
2165         }
2166     );
2167     $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2168     test_debarment_on_checkout(
2169         {
2170             item            => $item_1,
2171             library         => $library,
2172             patron          => $patron,
2173             due_date        => $five_days_ago,
2174             expiration_date => $expected_expiration,
2175         }
2176     );
2177
2178     # Use finesCalendar to know if holiday must be skipped to calculate the due date
2179     # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2180     Koha::CirculationRules->set_rules(
2181         {
2182             categorycode => undef,
2183             branchcode   => undef,
2184             itemtype     => undef,
2185             rules        => {
2186                 finedays                => 2,
2187                 suspension_chargeperiod => 1,
2188                 firstremind             => 0,
2189             }
2190         }
2191     );
2192     t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2193     t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2194
2195     # Adding a holiday 2 days ago
2196     my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2197     my $two_days_ago = $now->clone->subtract( days => 2 );
2198     $calendar->insert_single_holiday(
2199         day             => $two_days_ago->day,
2200         month           => $two_days_ago->month,
2201         year            => $two_days_ago->year,
2202         title           => 'holidayTest-2d',
2203         description     => 'holidayDesc 2 days ago'
2204     );
2205     # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2206     $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2207     test_debarment_on_checkout(
2208         {
2209             item            => $item_1,
2210             library         => $library,
2211             patron          => $patron,
2212             due_date        => $five_days_ago,
2213             expiration_date => $expected_expiration,
2214         }
2215     );
2216
2217     # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2218     my $two_days_ahead = $now->clone->add( days => 2 );
2219     $calendar->insert_single_holiday(
2220         day             => $two_days_ahead->day,
2221         month           => $two_days_ahead->month,
2222         year            => $two_days_ahead->year,
2223         title           => 'holidayTest+2d',
2224         description     => 'holidayDesc 2 days ahead'
2225     );
2226
2227     # Same as above, but we should skip D+2
2228     $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2229     test_debarment_on_checkout(
2230         {
2231             item            => $item_1,
2232             library         => $library,
2233             patron          => $patron,
2234             due_date        => $five_days_ago,
2235             expiration_date => $expected_expiration,
2236         }
2237     );
2238
2239     # Adding another holiday, day of expiration date
2240     my $expected_expiration_dt = dt_from_string($expected_expiration);
2241     $calendar->insert_single_holiday(
2242         day             => $expected_expiration_dt->day,
2243         month           => $expected_expiration_dt->month,
2244         year            => $expected_expiration_dt->year,
2245         title           => 'holidayTest_exp',
2246         description     => 'holidayDesc on expiration date'
2247     );
2248     # Expiration date will be the day after
2249     test_debarment_on_checkout(
2250         {
2251             item            => $item_1,
2252             library         => $library,
2253             patron          => $patron,
2254             due_date        => $five_days_ago,
2255             expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2256         }
2257     );
2258
2259     test_debarment_on_checkout(
2260         {
2261             item            => $item_1,
2262             library         => $library,
2263             patron          => $patron,
2264             return_date     => $now->clone->add(days => 5),
2265             expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2266         }
2267     );
2268 };
2269
2270 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2271     plan tests => 2;
2272
2273     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2274     my $patron1 = $builder->build_object(
2275         {
2276             class => 'Koha::Patrons',
2277             value => {
2278                 library      => $library->branchcode,
2279                 categorycode => $patron_category->{categorycode}
2280             }
2281         }
2282     );
2283     my $patron2 = $builder->build_object(
2284         {
2285             class => 'Koha::Patrons',
2286             value => {
2287                 library      => $library->branchcode,
2288                 categorycode => $patron_category->{categorycode}
2289             }
2290         }
2291     );
2292
2293     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2294
2295     my $item = $builder->build_sample_item(
2296         {
2297             library      => $library->branchcode,
2298         }
2299     )->unblessed;
2300
2301     my ( $error, $question, $alerts );
2302     my $issue = AddIssue( $patron1->unblessed, $item->{barcode} );
2303
2304     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2305     ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
2306     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' );
2307
2308     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2309     ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
2310     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' );
2311
2312     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2313 };
2314
2315
2316 subtest 'AddReturn | is_overdue' => sub {
2317     plan tests => 5;
2318
2319     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2320     t::lib::Mocks::mock_preference('finesMode', 'production');
2321     t::lib::Mocks::mock_preference('MaxFine', '100');
2322
2323     my $library = $builder->build( { source => 'Branch' } );
2324     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2325     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2326     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2327
2328     my $item = $builder->build_sample_item(
2329         {
2330             library      => $library->{branchcode},
2331             replacementprice => 7
2332         }
2333     )->unblessed;
2334
2335     Koha::CirculationRules->search->delete;
2336     Koha::CirculationRules->set_rules(
2337         {
2338             categorycode => undef,
2339             itemtype     => undef,
2340             branchcode   => undef,
2341             rules        => {
2342                 issuelength  => 6,
2343                 lengthunit   => 'days',
2344                 fine         => 1,        # Charge 1 every day of overdue
2345                 chargeperiod => 1,
2346             }
2347         }
2348     );
2349
2350     my $now   = dt_from_string;
2351     my $one_day_ago   = $now->clone->subtract( days => 1 );
2352     my $five_days_ago = $now->clone->subtract( days => 5 );
2353     my $ten_days_ago  = $now->clone->subtract( days => 10 );
2354     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2355
2356     # No return date specified, today will be used => 10 days overdue charged
2357     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2358     AddReturn( $item->{barcode}, $library->{branchcode} );
2359     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2360     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2361
2362     # specify return date 5 days before => no overdue charged
2363     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
2364     AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
2365     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2366     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2367
2368     # specify return date 5 days later => 5 days overdue charged
2369     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2370     AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
2371     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2372     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2373
2374     # specify return date 5 days later, specify exemptfine => no overdue charge
2375     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2376     AddReturn( $item->{barcode}, $library->{branchcode}, 1, $five_days_ago );
2377     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2378     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2379
2380     subtest 'bug 22877' => sub {
2381
2382         plan tests => 3;
2383
2384         my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago );    # date due was 10d ago
2385
2386         # Fake fines cronjob on this checkout
2387         my ($fine) =
2388           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2389             $ten_days_ago, $now );
2390         UpdateFine(
2391             {
2392                 issue_id       => $issue->issue_id,
2393                 itemnumber     => $item->{itemnumber},
2394                 borrowernumber => $patron->borrowernumber,
2395                 amount         => $fine,
2396                 due            => output_pref($ten_days_ago)
2397             }
2398         );
2399         is( int( $patron->account->balance() ),
2400             10, "Overdue fine of 10 days overdue" );
2401
2402         # Fake longoverdue with charge and not marking returned
2403         LostItem( $item->{itemnumber}, 'cronjob', 0 );
2404         is( int( $patron->account->balance() ),
2405             17, "Lost fine of 7 plus 10 days overdue" );
2406
2407         # Now we return it today
2408         AddReturn( $item->{barcode}, $library->{branchcode} );
2409         is( int( $patron->account->balance() ),
2410             17, "Should have a single 10 days overdue fine and lost charge" );
2411       }
2412 };
2413
2414 subtest '_FixAccountForLostAndFound' => sub {
2415
2416     plan tests => 5;
2417
2418     t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
2419     t::lib::Mocks::mock_preference( 'WhenLostForgiveFine',          0 );
2420
2421     my $processfee_amount  = 20;
2422     my $replacement_amount = 99.00;
2423     my $item_type          = $builder->build_object(
2424         {   class => 'Koha::ItemTypes',
2425             value => {
2426                 notforloan         => undef,
2427                 rentalcharge       => 0,
2428                 defaultreplacecost => undef,
2429                 processfee         => $processfee_amount,
2430                 rentalcharge_daily => 0,
2431             }
2432         }
2433     );
2434     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2435
2436     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
2437
2438     subtest 'Full write-off tests' => sub {
2439
2440         plan tests => 12;
2441
2442         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2443         my $manager = $builder->build_object({ class => "Koha::Patrons" });
2444         t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
2445
2446         my $item = $builder->build_sample_item(
2447             {
2448                 biblionumber     => $biblio->biblionumber,
2449                 library          => $library->branchcode,
2450                 replacementprice => $replacement_amount,
2451                 itype            => $item_type->itemtype,
2452             }
2453         );
2454
2455         AddIssue( $patron->unblessed, $item->barcode );
2456
2457         # Simulate item marked as lost
2458         ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2459         LostItem( $item->itemnumber, 1 );
2460
2461         my $processing_fee_lines = Koha::Account::Lines->search(
2462             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2463         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2464         my $processing_fee_line = $processing_fee_lines->next;
2465         is( $processing_fee_line->amount + 0,
2466             $processfee_amount, 'The right PROCESSING amount is generated' );
2467         is( $processing_fee_line->amountoutstanding + 0,
2468             $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2469
2470         my $lost_fee_lines = Koha::Account::Lines->search(
2471             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2472         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2473         my $lost_fee_line = $lost_fee_lines->next;
2474         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2475         is( $lost_fee_line->amountoutstanding + 0,
2476             $replacement_amount, 'The right LOST amountoutstanding is generated' );
2477         is( $lost_fee_line->status,
2478             undef, 'The LOST status was not set' );
2479
2480         my $account = $patron->account;
2481         my $debts   = $account->outstanding_debits;
2482
2483         # Write off the debt
2484         my $credit = $account->add_credit(
2485             {   amount => $account->balance,
2486                 type   => 'WRITEOFF',
2487                 interface => 'test',
2488             }
2489         );
2490         $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Writeoff' } );
2491
2492         my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2493         is( $credit_return_id, undef, 'No LOST_FOUND account line added' );
2494
2495         $lost_fee_line->discard_changes; # reload from DB
2496         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2497         is( $lost_fee_line->debit_type_code,
2498             'LOST', 'Lost fee now still has account type of LOST' );
2499         is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2500
2501         is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2502     };
2503
2504     subtest 'Full payment tests' => sub {
2505
2506         plan tests => 13;
2507
2508         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2509
2510         my $item = $builder->build_sample_item(
2511             {
2512                 biblionumber     => $biblio->biblionumber,
2513                 library          => $library->branchcode,
2514                 replacementprice => $replacement_amount,
2515                 itype            => $item_type->itemtype
2516             }
2517         );
2518
2519         AddIssue( $patron->unblessed, $item->barcode );
2520
2521         # Simulate item marked as lost
2522         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2523         LostItem( $item->itemnumber, 1 );
2524
2525         my $processing_fee_lines = Koha::Account::Lines->search(
2526             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2527         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2528         my $processing_fee_line = $processing_fee_lines->next;
2529         is( $processing_fee_line->amount + 0,
2530             $processfee_amount, 'The right PROCESSING amount is generated' );
2531         is( $processing_fee_line->amountoutstanding + 0,
2532             $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2533
2534         my $lost_fee_lines = Koha::Account::Lines->search(
2535             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2536         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2537         my $lost_fee_line = $lost_fee_lines->next;
2538         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2539         is( $lost_fee_line->amountoutstanding + 0,
2540             $replacement_amount, 'The right LOST amountountstanding is generated' );
2541
2542         my $account = $patron->account;
2543         my $debts   = $account->outstanding_debits;
2544
2545         # Write off the debt
2546         my $credit = $account->add_credit(
2547             {   amount => $account->balance,
2548                 type   => 'PAYMENT',
2549                 interface => 'test',
2550             }
2551         );
2552         $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Payment' } );
2553
2554         my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2555         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2556
2557         is( $credit_return->credit_type_code, 'LOST_FOUND', 'An account line of type LOST_FOUND is added' );
2558         is( $credit_return->amount + 0,
2559             -99.00, 'The account line of type LOST_FOUND has an amount of -99' );
2560         is( $credit_return->amountoutstanding + 0,
2561             -99.00, 'The account line of type LOST_FOUND has an amountoutstanding of -99' );
2562
2563         $lost_fee_line->discard_changes;
2564         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2565         is( $lost_fee_line->debit_type_code,
2566             'LOST', 'Lost fee now still has account type of LOST' );
2567         is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2568
2569         is( $patron->account->balance,
2570             -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2571     };
2572
2573     subtest 'Test without payment or write off' => sub {
2574
2575         plan tests => 13;
2576
2577         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2578
2579         my $item = $builder->build_sample_item(
2580             {
2581                 biblionumber     => $biblio->biblionumber,
2582                 library          => $library->branchcode,
2583                 replacementprice => 23.00,
2584                 replacementprice => $replacement_amount,
2585                 itype            => $item_type->itemtype
2586             }
2587         );
2588
2589         AddIssue( $patron->unblessed, $item->barcode );
2590
2591         # Simulate item marked as lost
2592         ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2593         LostItem( $item->itemnumber, 1 );
2594
2595         my $processing_fee_lines = Koha::Account::Lines->search(
2596             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2597         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2598         my $processing_fee_line = $processing_fee_lines->next;
2599         is( $processing_fee_line->amount + 0,
2600             $processfee_amount, 'The right PROCESSING amount is generated' );
2601         is( $processing_fee_line->amountoutstanding + 0,
2602             $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2603
2604         my $lost_fee_lines = Koha::Account::Lines->search(
2605             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2606         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2607         my $lost_fee_line = $lost_fee_lines->next;
2608         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2609         is( $lost_fee_line->amountoutstanding + 0,
2610             $replacement_amount, 'The right LOST amountountstanding is generated' );
2611
2612         my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2613         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2614
2615         is( $credit_return->credit_type_code, 'LOST_FOUND', 'An account line of type LOST_FOUND is added' );
2616         is( $credit_return->amount + 0, -99.00, 'The account line of type LOST_FOUND has an amount of -99' );
2617         is( $credit_return->amountoutstanding + 0, 0, 'The account line of type LOST_FOUND has an amountoutstanding of 0' );
2618
2619         $lost_fee_line->discard_changes;
2620         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2621         is( $lost_fee_line->debit_type_code,
2622             'LOST', 'Lost fee now still has account type of LOST' );
2623         is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2624
2625         is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2626     };
2627
2628     subtest 'Test with partial payement and write off, and remaining debt' => sub {
2629
2630         plan tests => 16;
2631
2632         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2633         my $item = $builder->build_sample_item(
2634             {
2635                 biblionumber     => $biblio->biblionumber,
2636                 library          => $library->branchcode,
2637                 replacementprice => $replacement_amount,
2638                 itype            => $item_type->itemtype
2639             }
2640         );
2641
2642         AddIssue( $patron->unblessed, $item->barcode );
2643
2644         # Simulate item marked as lost
2645         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2646         LostItem( $item->itemnumber, 1 );
2647
2648         my $processing_fee_lines = Koha::Account::Lines->search(
2649             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2650         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2651         my $processing_fee_line = $processing_fee_lines->next;
2652         is( $processing_fee_line->amount + 0,
2653             $processfee_amount, 'The right PROCESSING amount is generated' );
2654         is( $processing_fee_line->amountoutstanding + 0,
2655             $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2656
2657         my $lost_fee_lines = Koha::Account::Lines->search(
2658             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2659         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2660         my $lost_fee_line = $lost_fee_lines->next;
2661         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2662         is( $lost_fee_line->amountoutstanding + 0,
2663             $replacement_amount, 'The right LOST amountountstanding is generated' );
2664
2665         my $account = $patron->account;
2666         is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PROCESSING + L' );
2667
2668         # Partially pay fee
2669         my $payment_amount = 27;
2670         my $payment        = $account->add_credit(
2671             {   amount => $payment_amount,
2672                 type   => 'PAYMENT',
2673                 interface => 'test',
2674             }
2675         );
2676
2677         $payment->apply( { debits => [ $lost_fee_line ], offset_type => 'Payment' } );
2678
2679         # Partially write off fee
2680         my $write_off_amount = 25;
2681         my $write_off        = $account->add_credit(
2682             {   amount => $write_off_amount,
2683                 type   => 'WRITEOFF',
2684                 interface => 'test',
2685             }
2686         );
2687         $write_off->apply( { debits => [ $lost_fee_line ], offset_type => 'Writeoff' } );
2688
2689         is( $account->balance,
2690             $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2691             'Payment and write off applied'
2692         );
2693
2694         # Store the amountoutstanding value
2695         $lost_fee_line->discard_changes;
2696         my $outstanding = $lost_fee_line->amountoutstanding;
2697
2698         my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2699         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2700
2701         is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PROCESSING - PAYMENT (LOST_FOUND)' );
2702
2703         $lost_fee_line->discard_changes;
2704         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2705         is( $lost_fee_line->debit_type_code,
2706             'LOST', 'Lost fee now still has account type of LOST' );
2707         is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2708
2709         is( $credit_return->credit_type_code, 'LOST_FOUND', 'An account line of type LOST_FOUND is added' );
2710         is( $credit_return->amount + 0,
2711             ($payment_amount + $outstanding ) * -1,
2712             'The account line of type LOST_FOUND has an amount equal to the payment + outstanding'
2713         );
2714         is( $credit_return->amountoutstanding + 0,
2715             $payment_amount * -1,
2716             'The account line of type LOST_FOUND has an amountoutstanding equal to the payment'
2717         );
2718
2719         is( $account->balance,
2720             $processfee_amount - $payment_amount,
2721             'The patron balance is the difference between the PROCESSING and the credit'
2722         );
2723     };
2724
2725     subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2726
2727         plan tests => 8;
2728
2729         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2730         my $barcode = 'KD123456793';
2731         my $replacement_amount = 100;
2732         my $processfee_amount  = 20;
2733
2734         my $item_type          = $builder->build_object(
2735             {   class => 'Koha::ItemTypes',
2736                 value => {
2737                     notforloan         => undef,
2738                     rentalcharge       => 0,
2739                     defaultreplacecost => undef,
2740                     processfee         => 0,
2741                     rentalcharge_daily => 0,
2742                 }
2743             }
2744         );
2745         my $item_id = Koha::Item->new(
2746             {
2747                 biblionumber     => $biblio->biblionumber,
2748                 homebranch       => $library->branchcode,
2749                 holdingbranch    => $library->branchcode,
2750                 barcode          => $barcode,
2751                 replacementprice => $replacement_amount,
2752                 itype            => $item_type->itemtype
2753             },
2754         )->store->itemnumber;
2755
2756         AddIssue( $patron->unblessed, $barcode );
2757
2758         # Simulate item marked as lost
2759         ModItem( { itemlost => 1 }, $biblio->biblionumber, $item_id );
2760         LostItem( $item_id, 1 );
2761
2762         my $lost_fee_lines = Koha::Account::Lines->search(
2763             { borrowernumber => $patron->id, itemnumber => $item_id, debit_type_code => 'LOST' } );
2764         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2765         my $lost_fee_line = $lost_fee_lines->next;
2766         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2767         is( $lost_fee_line->amountoutstanding + 0,
2768             $replacement_amount, 'The right LOST amountountstanding is generated' );
2769
2770         my $account = $patron->account;
2771         is( $account->balance, $replacement_amount, 'Balance is L' );
2772
2773         # Partially pay fee
2774         my $payment_amount = 27;
2775         my $payment        = $account->add_credit(
2776             {   amount => $payment_amount,
2777                 type   => 'PAYMENT',
2778                 interface => 'test',
2779             }
2780         );
2781         $payment->apply({ debits => [ $lost_fee_line ], offset_type => 'Payment' });
2782
2783         is( $account->balance,
2784             $replacement_amount - $payment_amount,
2785             'Payment applied'
2786         );
2787
2788         my $manual_debit_amount = 80;
2789         $account->add_debit( { amount => $manual_debit_amount, type => 'OVERDUE', interface =>'test' } );
2790
2791         is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
2792
2793         t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
2794
2795         my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item_id, $patron->id );
2796         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2797
2798         is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PROCESSING - payment (LOST_FOUND)' );
2799
2800         my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, debit_type_code => 'OVERDUE', status => 'UNRETURNED' })->next;
2801         is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
2802     };
2803 };
2804
2805 subtest '_FixOverduesOnReturn' => sub {
2806     plan tests => 11;
2807
2808     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2809     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2810
2811     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2812
2813     my $branchcode  = $library2->{branchcode};
2814
2815     my $item = $builder->build_sample_item(
2816         {
2817             biblionumber     => $biblio->biblionumber,
2818             library          => $branchcode,
2819             replacementprice => 99.00,
2820             itype            => $itemtype,
2821         }
2822     );
2823
2824     my $patron = $builder->build( { source => 'Borrower' } );
2825
2826     ## Start with basic call, should just close out the open fine
2827     my $accountline = Koha::Account::Line->new(
2828         {
2829             borrowernumber => $patron->{borrowernumber},
2830             debit_type_code    => 'OVERDUE',
2831             status         => 'UNRETURNED',
2832             itemnumber     => $item->itemnumber,
2833             amount => 99.00,
2834             amountoutstanding => 99.00,
2835             interface => 'test',
2836         }
2837     )->store();
2838
2839     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
2840
2841     $accountline->_result()->discard_changes();
2842
2843     is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
2844     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
2845     is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
2846
2847     ## Run again, with exemptfine enabled
2848     $accountline->set(
2849         {
2850             debit_type_code    => 'OVERDUE',
2851             status         => 'UNRETURNED',
2852             amountoutstanding => 99.00,
2853         }
2854     )->store();
2855
2856     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
2857
2858     $accountline->_result()->discard_changes();
2859     my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2860
2861     is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
2862     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
2863     is( $accountline->status, 'FORGIVEN', 'Open fine ( account type OVERDUE ) has been set to fine forgiven ( status FORGIVEN )');
2864     is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2865     is( $offset->amount + 0, -99, "Amount of offset is correct" );
2866     my $credit = $offset->credit;
2867     is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
2868     is( $credit->amount + 0, -99, "Credit amount is set correctly" );
2869     is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
2870 };
2871
2872 subtest '_FixAccountForLostAndFound returns undef if patron is deleted' => sub {
2873     plan tests => 1;
2874
2875     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2876     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2877
2878     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2879
2880     my $branchcode  = $library2->{branchcode};
2881
2882     my $item = $builder->build_sample_item(
2883         {
2884             biblionumber     => $biblio->biblionumber,
2885             library          => $branchcode,
2886             replacementprice => 99.00,
2887             itype            => $itemtype,
2888         }
2889     );
2890
2891     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2892
2893     ## Start with basic call, should just close out the open fine
2894     my $accountline = Koha::Account::Line->new(
2895         {
2896             borrowernumber => $patron->id,
2897             debit_type_code    => 'LOST',
2898             status         => undef,
2899             itemnumber     => $item->itemnumber,
2900             amount => 99.00,
2901             amountoutstanding => 99.00,
2902             interface => 'test',
2903         }
2904     )->store();
2905
2906     $patron->delete();
2907
2908     my $return_value = C4::Circulation::_FixAccountForLostAndFound( $patron->id, $item->itemnumber );
2909
2910     is( $return_value, undef, "_FixAccountForLostAndFound returns undef if patron is deleted" );
2911
2912 };
2913
2914 subtest 'Set waiting flag' => sub {
2915     plan tests => 11;
2916
2917     my $library_1 = $builder->build( { source => 'Branch' } );
2918     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2919     my $library_2 = $builder->build( { source => 'Branch' } );
2920     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2921
2922     my $item = $builder->build_sample_item(
2923         {
2924             library      => $library_1->{branchcode},
2925         }
2926     )->unblessed;
2927
2928     set_userenv( $library_2 );
2929     my $reserve_id = AddReserve(
2930         {
2931             branchcode     => $library_2->{branchcode},
2932             borrowernumber => $patron_2->{borrowernumber},
2933             biblionumber   => $item->{biblionumber},
2934             priority       => 1,
2935             itemnumber     => $item->{itemnumber},
2936         }
2937     );
2938
2939     set_userenv( $library_1 );
2940     my $do_transfer = 1;
2941     my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2942     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2943     my $hold = Koha::Holds->find( $reserve_id );
2944     is( $hold->found, 'T', 'Hold is in transit' );
2945
2946     my ( $status ) = CheckReserves($item->{itemnumber});
2947     is( $status, 'Reserved', 'Hold is not waiting yet');
2948
2949     set_userenv( $library_2 );
2950     $do_transfer = 0;
2951     AddReturn( $item->{barcode}, $library_2->{branchcode} );
2952     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2953     $hold = Koha::Holds->find( $reserve_id );
2954     is( $hold->found, 'W', 'Hold is waiting' );
2955     ( $status ) = CheckReserves($item->{itemnumber});
2956     is( $status, 'Waiting', 'Now the hold is waiting');
2957
2958     #Bug 21944 - Waiting transfer checked in at branch other than pickup location
2959     set_userenv( $library_1 );
2960     (undef, my $messages, undef, undef ) = AddReturn ( $item->{barcode}, $library_1->{branchcode} );
2961     $hold = Koha::Holds->find( $reserve_id );
2962     is( $hold->found, undef, 'Hold is no longer marked waiting' );
2963     is( $hold->priority, 1,  "Hold is now priority one again");
2964     is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
2965     is( $hold->itemnumber, $item->{itemnumber}, "Hold has retained its' itemnumber");
2966     is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
2967     is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
2968     is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
2969 };
2970
2971 subtest 'Cancel transfers on lost items' => sub {
2972     plan tests => 5;
2973     my $library_1 = $builder->build( { source => 'Branch' } );
2974     my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2975     my $library_2 = $builder->build( { source => 'Branch' } );
2976     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2977     my $biblio = $builder->build_sample_biblio({branchcode => $library->{branchcode}});
2978     my $item   = $builder->build_sample_item({
2979         biblionumber  => $biblio->biblionumber,
2980         library    => $library_1->{branchcode},
2981     });
2982
2983     set_userenv( $library_2 );
2984     my $reserve_id = AddReserve(
2985         {
2986             branchcode     => $library_2->{branchcode},
2987             borrowernumber => $patron_2->{borrowernumber},
2988             biblionumber   => $item->biblionumber,
2989             priority       => 1,
2990             itemnumber     => $item->itemnumber,
2991         }
2992     );
2993
2994     #Return book and add transfer
2995     set_userenv( $library_1 );
2996     my $do_transfer = 1;
2997     my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
2998     ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
2999     C4::Circulation::transferbook( $library_2->{branchcode}, $item->barcode );
3000     my $hold = Koha::Holds->find( $reserve_id );
3001     is( $hold->found, 'T', 'Hold is in transit' );
3002
3003     #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
3004     my ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
3005     is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
3006     my $itemcheck = Koha::Items->find($item->itemnumber);
3007     is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Items holding branch is the transfers origin branch before it is marked as lost' );
3008
3009     #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
3010     ModItem( { itemlost => 1 }, $item->biblionumber, $item->itemnumber );
3011     LostItem( $item->itemnumber, 'test', 1 );
3012     ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
3013     is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
3014     $itemcheck = Koha::Items->find($item->itemnumber);
3015     is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
3016 };
3017
3018 subtest 'CanBookBeIssued | is_overdue' => sub {
3019     plan tests => 3;
3020
3021     # Set a simple circ policy
3022     Koha::CirculationRules->set_rules(
3023         {
3024             categorycode => undef,
3025             branchcode   => undef,
3026             itemtype     => undef,
3027             rules        => {
3028                 maxissueqty     => 1,
3029                 reservesallowed => 25,
3030                 issuelength     => 14,
3031                 lengthunit      => 'days',
3032                 renewalsallowed => 1,
3033                 renewalperiod   => 7,
3034                 norenewalbefore => undef,
3035                 auto_renew      => 0,
3036                 fine            => .10,
3037                 chargeperiod    => 1,
3038             }
3039         }
3040     );
3041
3042     my $now   = dt_from_string;
3043     my $five_days_go = output_pref({ dt => $now->clone->add( days => 5 ), dateonly => 1});
3044     my $ten_days_go  = output_pref({ dt => $now->clone->add( days => 10), dateonly => 1 });
3045     my $library = $builder->build( { source => 'Branch' } );
3046     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
3047
3048     my $item = $builder->build_sample_item(
3049         {
3050             library      => $library->{branchcode},
3051         }
3052     )->unblessed;
3053
3054     my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
3055     my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
3056     is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
3057     my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
3058     is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
3059     is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
3060 };
3061
3062 subtest 'ItemsDeniedRenewal preference' => sub {
3063     plan tests => 18;
3064
3065     C4::Context->set_preference('ItemsDeniedRenewal','');
3066
3067     my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
3068     Koha::CirculationRules->set_rules(
3069         {
3070             categorycode => '*',
3071             itemtype     => '*',
3072             branchcode   => $idr_lib->branchcode,
3073             rules        => {
3074                 reservesallowed => 25,
3075                 issuelength     => 14,
3076                 lengthunit      => 'days',
3077                 renewalsallowed => 10,
3078                 renewalperiod   => 7,
3079                 norenewalbefore => undef,
3080                 auto_renew      => 0,
3081                 fine            => .10,
3082                 chargeperiod    => 1,
3083             }
3084         }
3085     );
3086
3087     my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
3088         homebranch => $idr_lib->branchcode,
3089         withdrawn => 1,
3090         itype => 'HIDE',
3091         location => 'PROC',
3092         itemcallnumber => undef,
3093         itemnotes => "",
3094         }
3095     });
3096     my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
3097         homebranch => $idr_lib->branchcode,
3098         withdrawn => 0,
3099         itype => 'NOHIDE',
3100         location => 'NOPROC'
3101         }
3102     });
3103
3104     my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
3105         branchcode => $idr_lib->branchcode,
3106         }
3107     });
3108     my $future = dt_from_string->add( days => 1 );
3109     my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3110         returndate => undef,
3111         renewals => 0,
3112         auto_renew => 0,
3113         borrowernumber => $idr_borrower->borrowernumber,
3114         itemnumber => $deny_book->itemnumber,
3115         onsite_checkout => 0,
3116         date_due => $future,
3117         }
3118     });
3119     my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3120         returndate => undef,
3121         renewals => 0,
3122         auto_renew => 0,
3123         borrowernumber => $idr_borrower->borrowernumber,
3124         itemnumber => $allow_book->itemnumber,
3125         onsite_checkout => 0,
3126         date_due => $future,
3127         }
3128     });
3129
3130     my $idr_rules;
3131
3132     my ( $idr_mayrenew, $idr_error ) =
3133     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3134     is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3135     is( $idr_error, undef, 'Renewal allowed when no rules' );
3136
3137     $idr_rules="withdrawn: [1]";
3138
3139     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3140     ( $idr_mayrenew, $idr_error ) =
3141     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3142     is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3143     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3144     ( $idr_mayrenew, $idr_error ) =
3145     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3146     is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3147     is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3148
3149     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
3150
3151     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3152     ( $idr_mayrenew, $idr_error ) =
3153     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3154     is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
3155     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
3156     ( $idr_mayrenew, $idr_error ) =
3157     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3158     is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3159     is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3160
3161     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
3162
3163     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3164     ( $idr_mayrenew, $idr_error ) =
3165     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3166     is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
3167     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
3168     ( $idr_mayrenew, $idr_error ) =
3169     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3170     is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3171     is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3172
3173     $idr_rules="itemcallnumber: [NULL]";
3174     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3175     ( $idr_mayrenew, $idr_error ) =
3176     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3177     is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
3178     $idr_rules="itemcallnumber: ['']";
3179     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3180     ( $idr_mayrenew, $idr_error ) =
3181     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3182     is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
3183
3184     $idr_rules="itemnotes: [NULL]";
3185     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3186     ( $idr_mayrenew, $idr_error ) =
3187     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3188     is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
3189     $idr_rules="itemnotes: ['']";
3190     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3191     ( $idr_mayrenew, $idr_error ) =
3192     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3193     is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
3194 };
3195
3196 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
3197     plan tests => 2;
3198
3199     t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3200     my $library = $builder->build( { source => 'Branch' } );
3201     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3202
3203     my $item = $builder->build_sample_item(
3204         {
3205             library      => $library->{branchcode},
3206         }
3207     );
3208
3209     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3210     is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3211     is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3212 };
3213
3214 subtest 'CanBookBeIssued | notforloan' => sub {
3215     plan tests => 2;
3216
3217     t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
3218
3219     my $library = $builder->build( { source => 'Branch' } );
3220     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3221
3222     my $itemtype = $builder->build(
3223         {
3224             source => 'Itemtype',
3225             value  => { notforloan => undef, }
3226         }
3227     );
3228     my $item = $builder->build_sample_item(
3229         {
3230             library  => $library->{branchcode},
3231             itype    => $itemtype->{itemtype},
3232         }
3233     );
3234     $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3235
3236     my ( $issuingimpossible, $needsconfirmation );
3237
3238
3239     subtest 'item-level_itypes = 1' => sub {
3240         plan tests => 6;
3241
3242         t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
3243         # Is for loan at item type and item level
3244         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3245         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3246         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3247
3248         # not for loan at item type level
3249         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3250         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3251         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3252         is_deeply(
3253             $issuingimpossible,
3254             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3255             'Item can not be issued, not for loan at item type level'
3256         );
3257
3258         # not for loan at item level
3259         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3260         $item->notforloan( 1 )->store;
3261         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3262         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3263         is_deeply(
3264             $issuingimpossible,
3265             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3266             'Item can not be issued, not for loan at item type level'
3267         );
3268     };
3269
3270     subtest 'item-level_itypes = 0' => sub {
3271         plan tests => 6;
3272
3273         t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3274
3275         # We set another itemtype for biblioitem
3276         my $itemtype = $builder->build(
3277             {
3278                 source => 'Itemtype',
3279                 value  => { notforloan => undef, }
3280             }
3281         );
3282
3283         # for loan at item type and item level
3284         $item->notforloan(0)->store;
3285         $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3286         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3287         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3288         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3289
3290         # not for loan at item type level
3291         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3292         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3293         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3294         is_deeply(
3295             $issuingimpossible,
3296             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3297             'Item can not be issued, not for loan at item type level'
3298         );
3299
3300         # not for loan at item level
3301         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3302         $item->notforloan( 1 )->store;
3303         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3304         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3305         is_deeply(
3306             $issuingimpossible,
3307             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3308             'Item can not be issued, not for loan at item type level'
3309         );
3310     };
3311
3312     # TODO test with AllowNotForLoanOverride = 1
3313 };
3314
3315 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
3316     plan tests => 1;
3317
3318     t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
3319     my $item = $builder->build_sample_item(
3320         {
3321             onloan => '2018-01-01',
3322         }
3323     );
3324
3325     AddReturn( $item->barcode, $item->homebranch );
3326     $item->discard_changes; # refresh
3327     is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
3328 };
3329
3330
3331 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
3332
3333     plan tests => 12;
3334
3335
3336     t::lib::Mocks::mock_preference('item-level_itypes', 1);
3337
3338     my $issuing_charges = 15;
3339     my $title   = 'A title';
3340     my $author  = 'Author, An';
3341     my $barcode = 'WHATARETHEODDS';
3342
3343     my $circ = Test::MockModule->new('C4::Circulation');
3344     $circ->mock(
3345         'GetIssuingCharges',
3346         sub {
3347             return $issuing_charges;
3348         }
3349     );
3350
3351     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
3352     my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
3353     my $patron   = $builder->build_object({
3354         class => 'Koha::Patrons',
3355         value => { branchcode => $library->id }
3356     });
3357
3358     my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
3359     my $item_id = Koha::Item->new(
3360         {
3361             biblionumber     => $biblio->biblionumber,
3362             homebranch       => $library->id,
3363             holdingbranch    => $library->id,
3364             barcode          => $barcode,
3365             replacementprice => 23.00,
3366             itype            => $itemtype->id
3367         },
3368     )->store->itemnumber;
3369     my $item = Koha::Items->find( $item_id );
3370
3371     my $context = Test::MockModule->new('C4::Context');
3372     $context->mock( userenv => { branch => $library->id } );
3373
3374     # Check the item out
3375     AddIssue( $patron->unblessed, $item->barcode );
3376     t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
3377     my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3378     my %params_renewal = (
3379         timestamp => { -like => $date . "%" },
3380         module => "CIRCULATION",
3381         action => "RENEWAL",
3382     );
3383     my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
3384     AddRenewal( $patron->id, $item->id, $library->id );
3385     my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3386     is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
3387
3388     my $checkouts = $patron->checkouts;
3389     # The following will fail if run on 00:00:00
3390     unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
3391
3392     my $lines = Koha::Account::Lines->search({
3393         borrowernumber => $patron->id,
3394         itemnumber     => $item->id
3395     });
3396
3397     is( $lines->count, 2 );
3398
3399     my $line = $lines->next;
3400     is( $line->debit_type_code, 'RENT',       'The issue of item with issuing charge generates an accountline of the correct type' );
3401     is( $line->branchcode,  $library->id, 'AddIssuingCharge correctly sets branchcode' );
3402     is( $line->description, '',     'AddIssue does not set a hardcoded description for the accountline' );
3403
3404     $line = $lines->next;
3405     is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
3406     is( $line->branchcode,  $library->id, 'AddRenewal correctly sets branchcode' );
3407     is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
3408
3409     t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
3410
3411     $context = Test::MockModule->new('C4::Context');
3412     $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
3413
3414     my $now = dt_from_string;
3415     $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
3416     $old_log_size = Koha::ActionLogs->count( \%params_renewal );
3417     my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
3418     $sth->execute($item->id, $library->id);
3419     my ($old_stats_size) = $sth->fetchrow_array;
3420     AddRenewal( $patron->id, $item->id, $library->id );
3421     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3422     $sth->execute($item->id, $library->id);
3423     my ($new_stats_size) = $sth->fetchrow_array;
3424     is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
3425     is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
3426
3427     AddReturn( $item->id, $library->id, undef, $date );
3428     AddIssue( $patron->unblessed, $item->barcode, $now );
3429     AddRenewal( $patron->id, $item->id, $library->id, undef, undef, 1 );
3430     my $lines_skipped = Koha::Account::Lines->search({
3431         borrowernumber => $patron->id,
3432         itemnumber     => $item->id
3433     });
3434     is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
3435
3436 };
3437
3438 subtest 'ProcessOfflinePayment() tests' => sub {
3439
3440     plan tests => 4;
3441
3442
3443     my $amount = 123;
3444
3445     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
3446     my $library = $builder->build_object({ class => 'Koha::Libraries' });
3447     my $result  = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
3448
3449     is( $result, 'Success.', 'The right string is returned' );
3450
3451     my $lines = $patron->account->lines;
3452     is( $lines->count, 1, 'line created correctly');
3453
3454     my $line = $lines->next;
3455     is( $line->amount+0, $amount * -1, 'amount picked from params' );
3456     is( $line->branchcode, $library->id, 'branchcode set correctly' );
3457
3458 };
3459
3460 subtest 'Incremented fee tests' => sub {
3461     plan tests => 19;
3462
3463     my $dt = dt_from_string();
3464     Time::Fake->offset( $dt->epoch );
3465
3466     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
3467
3468     my $library =
3469       $builder->build_object( { class => 'Koha::Libraries' } )->store;
3470
3471     my $module = new Test::MockModule('C4::Context');
3472     $module->mock( 'userenv', sub { { branch => $library->id } } );
3473
3474     my $patron = $builder->build_object(
3475         {
3476             class => 'Koha::Patrons',
3477             value => { categorycode => $patron_category->{categorycode} }
3478         }
3479     )->store;
3480
3481     my $itemtype = $builder->build_object(
3482         {
3483             class => 'Koha::ItemTypes',
3484             value => {
3485                 notforloan         => undef,
3486                 rentalcharge       => 0,
3487                 rentalcharge_daily => 1,
3488             }
3489         }
3490     )->store;
3491
3492     my $item = $builder->build_sample_item(
3493         {
3494             library  => $library->{branchcode},
3495             itype    => $itemtype->id,
3496         }
3497     );
3498
3499     is( $itemtype->rentalcharge_daily+0,
3500         1, 'Daily rental charge stored and retreived correctly' );
3501     is( $item->effective_itemtype, $itemtype->id,
3502         "Itemtype set correctly for item" );
3503
3504     my $now         = dt_from_string;
3505     my $dt_from     = $now->clone;
3506     my $dt_to       = $now->clone->add( days => 7 );
3507     my $dt_to_renew = $now->clone->add( days => 13 );
3508
3509     # Daily Tests
3510     t::lib::Mocks::mock_preference( 'finesCalendar', 'ignoreCalendar' );
3511     my $issue =
3512       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3513     my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3514     is( $accountline->amount+0, 7,
3515 "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar"
3516     );
3517     $accountline->delete();
3518     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3519     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3520     is( $accountline->amount+0, 6,
3521 "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal"
3522     );
3523     $accountline->delete();
3524     $issue->delete();
3525
3526     t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3527     $issue =
3528       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3529     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3530     is( $accountline->amount+0, 7,
3531 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed"
3532     );
3533     $accountline->delete();
3534     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3535     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3536     is( $accountline->amount+0, 6,
3537 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal"
3538     );
3539     $accountline->delete();
3540     $issue->delete();
3541
3542     my $calendar = C4::Calendar->new( branchcode => $library->id );
3543     # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
3544     my $closed_day =
3545         ( $dt_from->day_of_week == 6 ) ? 0
3546       : ( $dt_from->day_of_week == 7 ) ? 1
3547       :                                  $dt_from->day_of_week + 1;
3548     my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
3549     $calendar->insert_week_day_holiday(
3550         weekday     => $closed_day,
3551         title       => 'Test holiday',
3552         description => 'Test holiday'
3553     );
3554     $issue =
3555       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3556     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3557     is( $accountline->amount+0, 6,
3558 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name"
3559     );
3560     $accountline->delete();
3561     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3562     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3563     is( $accountline->amount+0, 5,
3564 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name, for renewal"
3565     );
3566     $accountline->delete();
3567     $issue->delete();
3568
3569     $itemtype->rentalcharge(2)->store;
3570     is( $itemtype->rentalcharge+0, 2,
3571         'Rental charge updated and retreived correctly' );
3572     $issue =
3573       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3574     my $accountlines =
3575       Koha::Account::Lines->search( { itemnumber => $item->id } );
3576     is( $accountlines->count, '2',
3577         "Fixed charge and accrued charge recorded distinctly" );
3578     $accountlines->delete();
3579     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3580     $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
3581     is( $accountlines->count, '2',
3582         "Fixed charge and accrued charge recorded distinctly, for renewal" );
3583     $accountlines->delete();
3584     $issue->delete();
3585     $itemtype->rentalcharge(0)->store;
3586     is( $itemtype->rentalcharge+0, 0,
3587         'Rental charge reset and retreived correctly' );
3588
3589     # Hourly
3590     Koha::CirculationRules->set_rule(
3591         {
3592             categorycode => $patron->categorycode,
3593             itemtype     => $itemtype->id,
3594             branchcode   => $library->id,
3595             rule_name    => 'lengthunit',
3596             rule_value   => 'hours',
3597         }
3598     );
3599
3600     $itemtype->rentalcharge_hourly('0.25')->store();
3601     is( $itemtype->rentalcharge_hourly,
3602         '0.25', 'Hourly rental charge stored and retreived correctly' );
3603
3604     $dt_to       = $now->clone->add( hours => 168 );
3605     $dt_to_renew = $now->clone->add( hours => 312 );
3606
3607     t::lib::Mocks::mock_preference( 'finesCalendar', 'ignoreCalendar' );
3608     $issue =
3609       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3610     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3611     is( $accountline->amount + 0, 42,
3612         "Hourly rental charge calculated correctly with finesCalendar = ignoreCalendar (168h * 0.25u)" );
3613     $accountline->delete();
3614     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3615     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3616     is( $accountline->amount + 0, 36,
3617         "Hourly rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal (312h - 168h * 0.25u)" );
3618     $accountline->delete();
3619     $issue->delete();
3620
3621     t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3622     $issue =
3623       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3624     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3625     is( $accountline->amount + 0, 36,
3626         "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name (168h - 24h * 0.25u)" );
3627     $accountline->delete();
3628     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3629     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3630     is( $accountline->amount + 0, 30,
3631         "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
3632     $accountline->delete();
3633     $issue->delete();
3634
3635     $calendar->delete_holiday( weekday => $closed_day );
3636     $issue =
3637       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3638     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3639     is( $accountline->amount + 0, 42,
3640         "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed (168h - 0h * 0.25u" );
3641     $accountline->delete();
3642     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3643     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3644     is( $accountline->amount + 0, 36,
3645         "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal (312h - 168h - 0h * 0.25u)" );
3646     $accountline->delete();
3647     $issue->delete();
3648     Time::Fake->reset;
3649 };
3650
3651 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
3652     plan tests => 2;
3653
3654     t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
3655     t::lib::Mocks::mock_preference('item-level_itypes', 1);
3656
3657     my $library =
3658       $builder->build_object( { class => 'Koha::Libraries' } )->store;
3659     my $patron = $builder->build_object(
3660         {
3661             class => 'Koha::Patrons',
3662             value => { categorycode => $patron_category->{categorycode} }
3663         }
3664     )->store;
3665
3666     my $itemtype = $builder->build_object(
3667         {
3668             class => 'Koha::ItemTypes',
3669             value => {
3670                 notforloan             => 0,
3671                 rentalcharge           => 0,
3672                 rentalcharge_daily => 0
3673             }
3674         }
3675     );
3676
3677     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3678     my $item = $builder->build_object(
3679         {
3680             class => 'Koha::Items',
3681             value  => {
3682                 homebranch    => $library->id,
3683                 holdingbranch => $library->id,
3684                 notforloan    => 0,
3685                 itemlost      => 0,
3686                 withdrawn     => 0,
3687                 itype         => $itemtype->id,
3688                 biblionumber  => $biblioitem->{biblionumber},
3689                 biblioitemnumber => $biblioitem->{biblioitemnumber},
3690             }
3691         }
3692     )->store;
3693
3694     my ( $issuingimpossible, $needsconfirmation );
3695     my $dt_from = dt_from_string();
3696     my $dt_due = $dt_from->clone->add( days => 3 );
3697
3698     $itemtype->rentalcharge(1)->store;
3699     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3700     is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
3701     $itemtype->rentalcharge('0')->store;
3702     $itemtype->rentalcharge_daily(1)->store;
3703     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3704     is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
3705     $itemtype->rentalcharge_daily('0')->store;
3706 };
3707
3708 subtest "Test Backdating of Returns" => sub {
3709     plan tests => 2;
3710
3711     my $branch = $library2->{branchcode};
3712     my $biblio = $builder->build_sample_biblio();
3713     my $item = $builder->build_sample_item(
3714         {
3715             biblionumber     => $biblio->biblionumber,
3716             library          => $branch,
3717             itype            => $itemtype,
3718         }
3719     );
3720
3721     my %a_borrower_data = (
3722         firstname =>  'Kyle',
3723         surname => 'Hall',
3724         categorycode => $patron_category->{categorycode},
3725         branchcode => $branch,
3726     );
3727     my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
3728     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
3729
3730     my $due_date = dt_from_string;
3731     my $issue = AddIssue( $borrower, $item->barcode, $due_date );
3732     UpdateFine(
3733         {
3734             issue_id          => $issue->id(),
3735             itemnumber        => $item->itemnumber,
3736             borrowernumber    => $borrowernumber,
3737             amount            => .25,
3738             amountoutstanding => .25,
3739             type              => q{}
3740         }
3741     );
3742
3743
3744     my ( undef, $message ) = AddReturn( $item->barcode, $branch, undef, $due_date );
3745
3746     my $accountline = Koha::Account::Lines->find( { issue_id => $issue->id } );
3747     is( $accountline->amountoutstanding+0, 0, 'Fee amount outstanding was reduced to 0' );
3748     is( $accountline->amount+0, 0, 'Fee amount was reduced to 0' );
3749 };
3750
3751 $schema->storage->txn_rollback;
3752 C4::Context->clear_syspref_cache();
3753 $cache->clear_from_cache('single_holidays');