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