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