Bug 24474: (QA follow-up) Fix failing test
[koha-ffzg.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 => 47;
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('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2341     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2342     t::lib::Mocks::mock_preference('finesMode', 'production');
2343     t::lib::Mocks::mock_preference('MaxFine', '100');
2344
2345     my $library = $builder->build( { source => 'Branch' } );
2346     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2347     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2348     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2349
2350     my $item = $builder->build_sample_item(
2351         {
2352             library      => $library->{branchcode},
2353             replacementprice => 7
2354         }
2355     )->unblessed;
2356
2357     Koha::CirculationRules->search->delete;
2358     Koha::CirculationRules->set_rules(
2359         {
2360             categorycode => undef,
2361             itemtype     => undef,
2362             branchcode   => undef,
2363             rules        => {
2364                 issuelength  => 6,
2365                 lengthunit   => 'days',
2366                 fine         => 1,        # Charge 1 every day of overdue
2367                 chargeperiod => 1,
2368             }
2369         }
2370     );
2371
2372     my $now   = dt_from_string;
2373     my $one_day_ago   = $now->clone->subtract( days => 1 );
2374     my $five_days_ago = $now->clone->subtract( days => 5 );
2375     my $ten_days_ago  = $now->clone->subtract( days => 10 );
2376     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2377
2378     # No return date specified, today will be used => 10 days overdue charged
2379     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2380     AddReturn( $item->{barcode}, $library->{branchcode} );
2381     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2382     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2383
2384     # specify return date 5 days before => no overdue charged
2385     AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
2386     AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
2387     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2388     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2389
2390     # specify return date 5 days later => 5 days overdue charged
2391     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2392     AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
2393     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2394     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2395
2396     # specify return date 5 days later, specify exemptfine => no overdue charge
2397     AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2398     AddReturn( $item->{barcode}, $library->{branchcode}, 1, $five_days_ago );
2399     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2400     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2401
2402     subtest 'bug 22877' => sub {
2403
2404         plan tests => 3;
2405
2406         my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago );    # date due was 10d ago
2407
2408         # Fake fines cronjob on this checkout
2409         my ($fine) =
2410           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2411             $ten_days_ago, $now );
2412         UpdateFine(
2413             {
2414                 issue_id       => $issue->issue_id,
2415                 itemnumber     => $item->{itemnumber},
2416                 borrowernumber => $patron->borrowernumber,
2417                 amount         => $fine,
2418                 due            => output_pref($ten_days_ago)
2419             }
2420         );
2421         is( int( $patron->account->balance() ),
2422             10, "Overdue fine of 10 days overdue" );
2423
2424         # Fake longoverdue with charge and not marking returned
2425         LostItem( $item->{itemnumber}, 'cronjob', 0 );
2426         is( int( $patron->account->balance() ),
2427             17, "Lost fine of 7 plus 10 days overdue" );
2428
2429         # Now we return it today
2430         AddReturn( $item->{barcode}, $library->{branchcode} );
2431         is( int( $patron->account->balance() ),
2432             17, "Should have a single 10 days overdue fine and lost charge" );
2433       }
2434 };
2435
2436 subtest '_FixAccountForLostAndFound' => sub {
2437
2438     plan tests => 5;
2439
2440     t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
2441     t::lib::Mocks::mock_preference( 'WhenLostForgiveFine',          0 );
2442
2443     my $processfee_amount  = 20;
2444     my $replacement_amount = 99.00;
2445     my $item_type          = $builder->build_object(
2446         {   class => 'Koha::ItemTypes',
2447             value => {
2448                 notforloan         => undef,
2449                 rentalcharge       => 0,
2450                 defaultreplacecost => undef,
2451                 processfee         => $processfee_amount,
2452                 rentalcharge_daily => 0,
2453             }
2454         }
2455     );
2456     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2457
2458     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
2459
2460     subtest 'Full write-off tests' => sub {
2461
2462         plan tests => 12;
2463
2464         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2465         my $manager = $builder->build_object({ class => "Koha::Patrons" });
2466         t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
2467
2468         my $item = $builder->build_sample_item(
2469             {
2470                 biblionumber     => $biblio->biblionumber,
2471                 library          => $library->branchcode,
2472                 replacementprice => $replacement_amount,
2473                 itype            => $item_type->itemtype,
2474             }
2475         );
2476
2477         AddIssue( $patron->unblessed, $item->barcode );
2478
2479         # Simulate item marked as lost
2480         $item->itemlost(3)->store;
2481         LostItem( $item->itemnumber, 1 );
2482
2483         my $processing_fee_lines = Koha::Account::Lines->search(
2484             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2485         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2486         my $processing_fee_line = $processing_fee_lines->next;
2487         is( $processing_fee_line->amount + 0,
2488             $processfee_amount, 'The right PROCESSING amount is generated' );
2489         is( $processing_fee_line->amountoutstanding + 0,
2490             $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2491
2492         my $lost_fee_lines = Koha::Account::Lines->search(
2493             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2494         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2495         my $lost_fee_line = $lost_fee_lines->next;
2496         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2497         is( $lost_fee_line->amountoutstanding + 0,
2498             $replacement_amount, 'The right LOST amountoutstanding is generated' );
2499         is( $lost_fee_line->status,
2500             undef, 'The LOST status was not set' );
2501
2502         my $account = $patron->account;
2503         my $debts   = $account->outstanding_debits;
2504
2505         # Write off the debt
2506         my $credit = $account->add_credit(
2507             {   amount => $account->balance,
2508                 type   => 'WRITEOFF',
2509                 interface => 'test',
2510             }
2511         );
2512         $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Writeoff' } );
2513
2514         my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2515         is( $credit_return_id, undef, 'No LOST_FOUND account line added' );
2516
2517         $lost_fee_line->discard_changes; # reload from DB
2518         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2519         is( $lost_fee_line->debit_type_code,
2520             'LOST', 'Lost fee now still has account type of LOST' );
2521         is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2522
2523         is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2524     };
2525
2526     subtest 'Full payment tests' => sub {
2527
2528         plan tests => 13;
2529
2530         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2531
2532         my $item = $builder->build_sample_item(
2533             {
2534                 biblionumber     => $biblio->biblionumber,
2535                 library          => $library->branchcode,
2536                 replacementprice => $replacement_amount,
2537                 itype            => $item_type->itemtype
2538             }
2539         );
2540
2541         AddIssue( $patron->unblessed, $item->barcode );
2542
2543         # Simulate item marked as lost
2544         $item->itemlost(1)->store;
2545         LostItem( $item->itemnumber, 1 );
2546
2547         my $processing_fee_lines = Koha::Account::Lines->search(
2548             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2549         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2550         my $processing_fee_line = $processing_fee_lines->next;
2551         is( $processing_fee_line->amount + 0,
2552             $processfee_amount, 'The right PROCESSING amount is generated' );
2553         is( $processing_fee_line->amountoutstanding + 0,
2554             $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2555
2556         my $lost_fee_lines = Koha::Account::Lines->search(
2557             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2558         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2559         my $lost_fee_line = $lost_fee_lines->next;
2560         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2561         is( $lost_fee_line->amountoutstanding + 0,
2562             $replacement_amount, 'The right LOST amountountstanding is generated' );
2563
2564         my $account = $patron->account;
2565         my $debts   = $account->outstanding_debits;
2566
2567         # Write off the debt
2568         my $credit = $account->add_credit(
2569             {   amount => $account->balance,
2570                 type   => 'PAYMENT',
2571                 interface => 'test',
2572             }
2573         );
2574         $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Payment' } );
2575
2576         my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2577         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2578
2579         is( $credit_return->credit_type_code, 'LOST_FOUND', 'An account line of type LOST_FOUND is added' );
2580         is( $credit_return->amount + 0,
2581             -99.00, 'The account line of type LOST_FOUND has an amount of -99' );
2582         is( $credit_return->amountoutstanding + 0,
2583             -99.00, 'The account line of type LOST_FOUND has an amountoutstanding of -99' );
2584
2585         $lost_fee_line->discard_changes;
2586         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2587         is( $lost_fee_line->debit_type_code,
2588             'LOST', 'Lost fee now still has account type of LOST' );
2589         is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2590
2591         is( $patron->account->balance,
2592             -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2593     };
2594
2595     subtest 'Test without payment or write off' => sub {
2596
2597         plan tests => 13;
2598
2599         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2600
2601         my $item = $builder->build_sample_item(
2602             {
2603                 biblionumber     => $biblio->biblionumber,
2604                 library          => $library->branchcode,
2605                 replacementprice => 23.00,
2606                 replacementprice => $replacement_amount,
2607                 itype            => $item_type->itemtype
2608             }
2609         );
2610
2611         AddIssue( $patron->unblessed, $item->barcode );
2612
2613         # Simulate item marked as lost
2614         $item->itemlost(3)->store;
2615         LostItem( $item->itemnumber, 1 );
2616
2617         my $processing_fee_lines = Koha::Account::Lines->search(
2618             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2619         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2620         my $processing_fee_line = $processing_fee_lines->next;
2621         is( $processing_fee_line->amount + 0,
2622             $processfee_amount, 'The right PROCESSING amount is generated' );
2623         is( $processing_fee_line->amountoutstanding + 0,
2624             $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2625
2626         my $lost_fee_lines = Koha::Account::Lines->search(
2627             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2628         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2629         my $lost_fee_line = $lost_fee_lines->next;
2630         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2631         is( $lost_fee_line->amountoutstanding + 0,
2632             $replacement_amount, 'The right LOST amountountstanding is generated' );
2633
2634         my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2635         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2636
2637         is( $credit_return->credit_type_code, 'LOST_FOUND', 'An account line of type LOST_FOUND is added' );
2638         is( $credit_return->amount + 0, -99.00, 'The account line of type LOST_FOUND has an amount of -99' );
2639         is( $credit_return->amountoutstanding + 0, 0, 'The account line of type LOST_FOUND has an amountoutstanding of 0' );
2640
2641         $lost_fee_line->discard_changes;
2642         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2643         is( $lost_fee_line->debit_type_code,
2644             'LOST', 'Lost fee now still has account type of LOST' );
2645         is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2646
2647         is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2648     };
2649
2650     subtest 'Test with partial payement and write off, and remaining debt' => sub {
2651
2652         plan tests => 16;
2653
2654         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2655         my $item = $builder->build_sample_item(
2656             {
2657                 biblionumber     => $biblio->biblionumber,
2658                 library          => $library->branchcode,
2659                 replacementprice => $replacement_amount,
2660                 itype            => $item_type->itemtype
2661             }
2662         );
2663
2664         AddIssue( $patron->unblessed, $item->barcode );
2665
2666         # Simulate item marked as lost
2667         $item->itemlost(1)->store;
2668         LostItem( $item->itemnumber, 1 );
2669
2670         my $processing_fee_lines = Koha::Account::Lines->search(
2671             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2672         is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2673         my $processing_fee_line = $processing_fee_lines->next;
2674         is( $processing_fee_line->amount + 0,
2675             $processfee_amount, 'The right PROCESSING amount is generated' );
2676         is( $processing_fee_line->amountoutstanding + 0,
2677             $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2678
2679         my $lost_fee_lines = Koha::Account::Lines->search(
2680             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2681         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2682         my $lost_fee_line = $lost_fee_lines->next;
2683         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2684         is( $lost_fee_line->amountoutstanding + 0,
2685             $replacement_amount, 'The right LOST amountountstanding is generated' );
2686
2687         my $account = $patron->account;
2688         is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PROCESSING + L' );
2689
2690         # Partially pay fee
2691         my $payment_amount = 27;
2692         my $payment        = $account->add_credit(
2693             {   amount => $payment_amount,
2694                 type   => 'PAYMENT',
2695                 interface => 'test',
2696             }
2697         );
2698
2699         $payment->apply( { debits => [ $lost_fee_line ], offset_type => 'Payment' } );
2700
2701         # Partially write off fee
2702         my $write_off_amount = 25;
2703         my $write_off        = $account->add_credit(
2704             {   amount => $write_off_amount,
2705                 type   => 'WRITEOFF',
2706                 interface => 'test',
2707             }
2708         );
2709         $write_off->apply( { debits => [ $lost_fee_line ], offset_type => 'Writeoff' } );
2710
2711         is( $account->balance,
2712             $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2713             'Payment and write off applied'
2714         );
2715
2716         # Store the amountoutstanding value
2717         $lost_fee_line->discard_changes;
2718         my $outstanding = $lost_fee_line->amountoutstanding;
2719
2720         my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2721         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2722
2723         is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PROCESSING - PAYMENT (LOST_FOUND)' );
2724
2725         $lost_fee_line->discard_changes;
2726         is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2727         is( $lost_fee_line->debit_type_code,
2728             'LOST', 'Lost fee now still has account type of LOST' );
2729         is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2730
2731         is( $credit_return->credit_type_code, 'LOST_FOUND', 'An account line of type LOST_FOUND is added' );
2732         is( $credit_return->amount + 0,
2733             ($payment_amount + $outstanding ) * -1,
2734             'The account line of type LOST_FOUND has an amount equal to the payment + outstanding'
2735         );
2736         is( $credit_return->amountoutstanding + 0,
2737             $payment_amount * -1,
2738             'The account line of type LOST_FOUND has an amountoutstanding equal to the payment'
2739         );
2740
2741         is( $account->balance,
2742             $processfee_amount - $payment_amount,
2743             'The patron balance is the difference between the PROCESSING and the credit'
2744         );
2745     };
2746
2747     subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2748
2749         plan tests => 8;
2750
2751         my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2752         my $barcode = 'KD123456793';
2753         my $replacement_amount = 100;
2754         my $processfee_amount  = 20;
2755
2756         my $item_type          = $builder->build_object(
2757             {   class => 'Koha::ItemTypes',
2758                 value => {
2759                     notforloan         => undef,
2760                     rentalcharge       => 0,
2761                     defaultreplacecost => undef,
2762                     processfee         => 0,
2763                     rentalcharge_daily => 0,
2764                 }
2765             }
2766         );
2767         my $item = Koha::Item->new(
2768             {
2769                 biblionumber     => $biblio->biblionumber,
2770                 homebranch       => $library->branchcode,
2771                 holdingbranch    => $library->branchcode,
2772                 barcode          => $barcode,
2773                 replacementprice => $replacement_amount,
2774                 itype            => $item_type->itemtype
2775             },
2776         )->store;
2777
2778         AddIssue( $patron->unblessed, $barcode );
2779
2780         # Simulate item marked as lost
2781         $item->itemlost(1)->store;
2782         LostItem( $item->itemnumber, 1 );
2783
2784         my $lost_fee_lines = Koha::Account::Lines->search(
2785             { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2786         is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2787         my $lost_fee_line = $lost_fee_lines->next;
2788         is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2789         is( $lost_fee_line->amountoutstanding + 0,
2790             $replacement_amount, 'The right LOST amountountstanding is generated' );
2791
2792         my $account = $patron->account;
2793         is( $account->balance, $replacement_amount, 'Balance is L' );
2794
2795         # Partially pay fee
2796         my $payment_amount = 27;
2797         my $payment        = $account->add_credit(
2798             {   amount => $payment_amount,
2799                 type   => 'PAYMENT',
2800                 interface => 'test',
2801             }
2802         );
2803         $payment->apply({ debits => [ $lost_fee_line ], offset_type => 'Payment' });
2804
2805         is( $account->balance,
2806             $replacement_amount - $payment_amount,
2807             'Payment applied'
2808         );
2809
2810         my $manual_debit_amount = 80;
2811         $account->add_debit( { amount => $manual_debit_amount, type => 'OVERDUE', interface =>'test' } );
2812
2813         is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
2814
2815         t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
2816
2817         my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2818         my $credit_return = Koha::Account::Lines->find($credit_return_id);
2819
2820         is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PROCESSING - payment (LOST_FOUND)' );
2821
2822         my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, debit_type_code => 'OVERDUE', status => 'UNRETURNED' })->next;
2823         is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
2824     };
2825 };
2826
2827 subtest '_FixOverduesOnReturn' => sub {
2828     plan tests => 11;
2829
2830     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2831     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2832
2833     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2834
2835     my $branchcode  = $library2->{branchcode};
2836
2837     my $item = $builder->build_sample_item(
2838         {
2839             biblionumber     => $biblio->biblionumber,
2840             library          => $branchcode,
2841             replacementprice => 99.00,
2842             itype            => $itemtype,
2843         }
2844     );
2845
2846     my $patron = $builder->build( { source => 'Borrower' } );
2847
2848     ## Start with basic call, should just close out the open fine
2849     my $accountline = Koha::Account::Line->new(
2850         {
2851             borrowernumber => $patron->{borrowernumber},
2852             debit_type_code    => 'OVERDUE',
2853             status         => 'UNRETURNED',
2854             itemnumber     => $item->itemnumber,
2855             amount => 99.00,
2856             amountoutstanding => 99.00,
2857             interface => 'test',
2858         }
2859     )->store();
2860
2861     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
2862
2863     $accountline->_result()->discard_changes();
2864
2865     is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
2866     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
2867     is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
2868
2869     ## Run again, with exemptfine enabled
2870     $accountline->set(
2871         {
2872             debit_type_code    => 'OVERDUE',
2873             status         => 'UNRETURNED',
2874             amountoutstanding => 99.00,
2875         }
2876     )->store();
2877
2878     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
2879
2880     $accountline->_result()->discard_changes();
2881     my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2882
2883     is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
2884     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
2885     is( $accountline->status, 'FORGIVEN', 'Open fine ( account type OVERDUE ) has been set to fine forgiven ( status FORGIVEN )');
2886     is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2887     is( $offset->amount + 0, -99, "Amount of offset is correct" );
2888     my $credit = $offset->credit;
2889     is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
2890     is( $credit->amount + 0, -99, "Credit amount is set correctly" );
2891     is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
2892 };
2893
2894 subtest '_FixAccountForLostAndFound returns undef if patron is deleted' => sub {
2895     plan tests => 1;
2896
2897     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2898     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2899
2900     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2901
2902     my $branchcode  = $library2->{branchcode};
2903
2904     my $item = $builder->build_sample_item(
2905         {
2906             biblionumber     => $biblio->biblionumber,
2907             library          => $branchcode,
2908             replacementprice => 99.00,
2909             itype            => $itemtype,
2910         }
2911     );
2912
2913     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2914
2915     ## Start with basic call, should just close out the open fine
2916     my $accountline = Koha::Account::Line->new(
2917         {
2918             borrowernumber => $patron->id,
2919             debit_type_code    => 'LOST',
2920             status         => undef,
2921             itemnumber     => $item->itemnumber,
2922             amount => 99.00,
2923             amountoutstanding => 99.00,
2924             interface => 'test',
2925         }
2926     )->store();
2927
2928     $patron->delete();
2929
2930     my $return_value = C4::Circulation::_FixAccountForLostAndFound( $patron->id, $item->itemnumber );
2931
2932     is( $return_value, undef, "_FixAccountForLostAndFound returns undef if patron is deleted" );
2933
2934 };
2935
2936 subtest 'Set waiting flag' => sub {
2937     plan tests => 11;
2938
2939     my $library_1 = $builder->build( { source => 'Branch' } );
2940     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2941     my $library_2 = $builder->build( { source => 'Branch' } );
2942     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2943
2944     my $item = $builder->build_sample_item(
2945         {
2946             library      => $library_1->{branchcode},
2947         }
2948     )->unblessed;
2949
2950     set_userenv( $library_2 );
2951     my $reserve_id = AddReserve(
2952         {
2953             branchcode     => $library_2->{branchcode},
2954             borrowernumber => $patron_2->{borrowernumber},
2955             biblionumber   => $item->{biblionumber},
2956             priority       => 1,
2957             itemnumber     => $item->{itemnumber},
2958         }
2959     );
2960
2961     set_userenv( $library_1 );
2962     my $do_transfer = 1;
2963     my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2964     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2965     my $hold = Koha::Holds->find( $reserve_id );
2966     is( $hold->found, 'T', 'Hold is in transit' );
2967
2968     my ( $status ) = CheckReserves($item->{itemnumber});
2969     is( $status, 'Reserved', 'Hold is not waiting yet');
2970
2971     set_userenv( $library_2 );
2972     $do_transfer = 0;
2973     AddReturn( $item->{barcode}, $library_2->{branchcode} );
2974     ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2975     $hold = Koha::Holds->find( $reserve_id );
2976     is( $hold->found, 'W', 'Hold is waiting' );
2977     ( $status ) = CheckReserves($item->{itemnumber});
2978     is( $status, 'Waiting', 'Now the hold is waiting');
2979
2980     #Bug 21944 - Waiting transfer checked in at branch other than pickup location
2981     set_userenv( $library_1 );
2982     (undef, my $messages, undef, undef ) = AddReturn ( $item->{barcode}, $library_1->{branchcode} );
2983     $hold = Koha::Holds->find( $reserve_id );
2984     is( $hold->found, undef, 'Hold is no longer marked waiting' );
2985     is( $hold->priority, 1,  "Hold is now priority one again");
2986     is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
2987     is( $hold->itemnumber, $item->{itemnumber}, "Hold has retained its' itemnumber");
2988     is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
2989     is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
2990     is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
2991 };
2992
2993 subtest 'Cancel transfers on lost items' => sub {
2994     plan tests => 5;
2995     my $library_1 = $builder->build( { source => 'Branch' } );
2996     my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2997     my $library_2 = $builder->build( { source => 'Branch' } );
2998     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2999     my $biblio = $builder->build_sample_biblio({branchcode => $library->{branchcode}});
3000     my $item   = $builder->build_sample_item({
3001         biblionumber  => $biblio->biblionumber,
3002         library    => $library_1->{branchcode},
3003     });
3004
3005     set_userenv( $library_2 );
3006     my $reserve_id = AddReserve(
3007         {
3008             branchcode     => $library_2->{branchcode},
3009             borrowernumber => $patron_2->{borrowernumber},
3010             biblionumber   => $item->biblionumber,
3011             priority       => 1,
3012             itemnumber     => $item->itemnumber,
3013         }
3014     );
3015
3016     #Return book and add transfer
3017     set_userenv( $library_1 );
3018     my $do_transfer = 1;
3019     my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3020     ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3021     C4::Circulation::transferbook( $library_2->{branchcode}, $item->barcode );
3022     my $hold = Koha::Holds->find( $reserve_id );
3023     is( $hold->found, 'T', 'Hold is in transit' );
3024
3025     #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
3026     my ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
3027     is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
3028     my $itemcheck = Koha::Items->find($item->itemnumber);
3029     is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Items holding branch is the transfers origin branch before it is marked as lost' );
3030
3031     #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
3032     $item->itemlost(1)->store;
3033     LostItem( $item->itemnumber, 'test', 1 );
3034     ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
3035     is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
3036     $itemcheck = Koha::Items->find($item->itemnumber);
3037     is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
3038 };
3039
3040 subtest 'CanBookBeIssued | is_overdue' => sub {
3041     plan tests => 3;
3042
3043     # Set a simple circ policy
3044     Koha::CirculationRules->set_rules(
3045         {
3046             categorycode => undef,
3047             branchcode   => undef,
3048             itemtype     => undef,
3049             rules        => {
3050                 maxissueqty     => 1,
3051                 reservesallowed => 25,
3052                 issuelength     => 14,
3053                 lengthunit      => 'days',
3054                 renewalsallowed => 1,
3055                 renewalperiod   => 7,
3056                 norenewalbefore => undef,
3057                 auto_renew      => 0,
3058                 fine            => .10,
3059                 chargeperiod    => 1,
3060             }
3061         }
3062     );
3063
3064     my $now   = dt_from_string;
3065     my $five_days_go = output_pref({ dt => $now->clone->add( days => 5 ), dateonly => 1});
3066     my $ten_days_go  = output_pref({ dt => $now->clone->add( days => 10), dateonly => 1 });
3067     my $library = $builder->build( { source => 'Branch' } );
3068     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
3069
3070     my $item = $builder->build_sample_item(
3071         {
3072             library      => $library->{branchcode},
3073         }
3074     )->unblessed;
3075
3076     my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
3077     my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
3078     is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
3079     my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
3080     is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
3081     is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
3082 };
3083
3084 subtest 'ItemsDeniedRenewal preference' => sub {
3085     plan tests => 18;
3086
3087     C4::Context->set_preference('ItemsDeniedRenewal','');
3088
3089     my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
3090     Koha::CirculationRules->set_rules(
3091         {
3092             categorycode => '*',
3093             itemtype     => '*',
3094             branchcode   => $idr_lib->branchcode,
3095             rules        => {
3096                 reservesallowed => 25,
3097                 issuelength     => 14,
3098                 lengthunit      => 'days',
3099                 renewalsallowed => 10,
3100                 renewalperiod   => 7,
3101                 norenewalbefore => undef,
3102                 auto_renew      => 0,
3103                 fine            => .10,
3104                 chargeperiod    => 1,
3105             }
3106         }
3107     );
3108
3109     my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
3110         homebranch => $idr_lib->branchcode,
3111         withdrawn => 1,
3112         itype => 'HIDE',
3113         location => 'PROC',
3114         itemcallnumber => undef,
3115         itemnotes => "",
3116         }
3117     });
3118     my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
3119         homebranch => $idr_lib->branchcode,
3120         withdrawn => 0,
3121         itype => 'NOHIDE',
3122         location => 'NOPROC'
3123         }
3124     });
3125
3126     my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
3127         branchcode => $idr_lib->branchcode,
3128         }
3129     });
3130     my $future = dt_from_string->add( days => 1 );
3131     my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3132         returndate => undef,
3133         renewals => 0,
3134         auto_renew => 0,
3135         borrowernumber => $idr_borrower->borrowernumber,
3136         itemnumber => $deny_book->itemnumber,
3137         onsite_checkout => 0,
3138         date_due => $future,
3139         }
3140     });
3141     my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3142         returndate => undef,
3143         renewals => 0,
3144         auto_renew => 0,
3145         borrowernumber => $idr_borrower->borrowernumber,
3146         itemnumber => $allow_book->itemnumber,
3147         onsite_checkout => 0,
3148         date_due => $future,
3149         }
3150     });
3151
3152     my $idr_rules;
3153
3154     my ( $idr_mayrenew, $idr_error ) =
3155     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3156     is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3157     is( $idr_error, undef, 'Renewal allowed when no rules' );
3158
3159     $idr_rules="withdrawn: [1]";
3160
3161     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3162     ( $idr_mayrenew, $idr_error ) =
3163     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3164     is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3165     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3166     ( $idr_mayrenew, $idr_error ) =
3167     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3168     is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3169     is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3170
3171     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
3172
3173     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3174     ( $idr_mayrenew, $idr_error ) =
3175     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3176     is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
3177     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
3178     ( $idr_mayrenew, $idr_error ) =
3179     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3180     is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3181     is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3182
3183     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
3184
3185     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3186     ( $idr_mayrenew, $idr_error ) =
3187     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3188     is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
3189     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
3190     ( $idr_mayrenew, $idr_error ) =
3191     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3192     is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3193     is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3194
3195     $idr_rules="itemcallnumber: [NULL]";
3196     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3197     ( $idr_mayrenew, $idr_error ) =
3198     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3199     is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
3200     $idr_rules="itemcallnumber: ['']";
3201     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3202     ( $idr_mayrenew, $idr_error ) =
3203     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3204     is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
3205
3206     $idr_rules="itemnotes: [NULL]";
3207     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3208     ( $idr_mayrenew, $idr_error ) =
3209     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3210     is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
3211     $idr_rules="itemnotes: ['']";
3212     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3213     ( $idr_mayrenew, $idr_error ) =
3214     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3215     is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
3216 };
3217
3218 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
3219     plan tests => 2;
3220
3221     t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3222     my $library = $builder->build( { source => 'Branch' } );
3223     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3224
3225     my $item = $builder->build_sample_item(
3226         {
3227             library      => $library->{branchcode},
3228         }
3229     );
3230
3231     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3232     is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3233     is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3234 };
3235
3236 subtest 'CanBookBeIssued | notforloan' => sub {
3237     plan tests => 2;
3238
3239     t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
3240
3241     my $library = $builder->build( { source => 'Branch' } );
3242     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3243
3244     my $itemtype = $builder->build(
3245         {
3246             source => 'Itemtype',
3247             value  => { notforloan => undef, }
3248         }
3249     );
3250     my $item = $builder->build_sample_item(
3251         {
3252             library  => $library->{branchcode},
3253             itype    => $itemtype->{itemtype},
3254         }
3255     );
3256     $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3257
3258     my ( $issuingimpossible, $needsconfirmation );
3259
3260
3261     subtest 'item-level_itypes = 1' => sub {
3262         plan tests => 6;
3263
3264         t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
3265         # Is for loan at item type and item level
3266         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3267         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3268         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3269
3270         # not for loan at item type level
3271         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3272         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3273         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3274         is_deeply(
3275             $issuingimpossible,
3276             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3277             'Item can not be issued, not for loan at item type level'
3278         );
3279
3280         # not for loan at item level
3281         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3282         $item->notforloan( 1 )->store;
3283         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3284         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3285         is_deeply(
3286             $issuingimpossible,
3287             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3288             'Item can not be issued, not for loan at item type level'
3289         );
3290     };
3291
3292     subtest 'item-level_itypes = 0' => sub {
3293         plan tests => 6;
3294
3295         t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3296
3297         # We set another itemtype for biblioitem
3298         my $itemtype = $builder->build(
3299             {
3300                 source => 'Itemtype',
3301                 value  => { notforloan => undef, }
3302             }
3303         );
3304
3305         # for loan at item type and item level
3306         $item->notforloan(0)->store;
3307         $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3308         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3309         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3310         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3311
3312         # not for loan at item type level
3313         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3314         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3315         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3316         is_deeply(
3317             $issuingimpossible,
3318             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3319             'Item can not be issued, not for loan at item type level'
3320         );
3321
3322         # not for loan at item level
3323         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3324         $item->notforloan( 1 )->store;
3325         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3326         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3327         is_deeply(
3328             $issuingimpossible,
3329             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3330             'Item can not be issued, not for loan at item type level'
3331         );
3332     };
3333
3334     # TODO test with AllowNotForLoanOverride = 1
3335 };
3336
3337 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
3338     plan tests => 1;
3339
3340     t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
3341     my $item = $builder->build_sample_item(
3342         {
3343             onloan => '2018-01-01',
3344         }
3345     );
3346
3347     AddReturn( $item->barcode, $item->homebranch );
3348     $item->discard_changes; # refresh
3349     is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
3350 };
3351
3352
3353 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
3354
3355     plan tests => 12;
3356
3357
3358     t::lib::Mocks::mock_preference('item-level_itypes', 1);
3359
3360     my $issuing_charges = 15;
3361     my $title   = 'A title';
3362     my $author  = 'Author, An';
3363     my $barcode = 'WHATARETHEODDS';
3364
3365     my $circ = Test::MockModule->new('C4::Circulation');
3366     $circ->mock(
3367         'GetIssuingCharges',
3368         sub {
3369             return $issuing_charges;
3370         }
3371     );
3372
3373     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
3374     my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
3375     my $patron   = $builder->build_object({
3376         class => 'Koha::Patrons',
3377         value => { branchcode => $library->id }
3378     });
3379
3380     my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
3381     my $item_id = Koha::Item->new(
3382         {
3383             biblionumber     => $biblio->biblionumber,
3384             homebranch       => $library->id,
3385             holdingbranch    => $library->id,
3386             barcode          => $barcode,
3387             replacementprice => 23.00,
3388             itype            => $itemtype->id
3389         },
3390     )->store->itemnumber;
3391     my $item = Koha::Items->find( $item_id );
3392
3393     my $context = Test::MockModule->new('C4::Context');
3394     $context->mock( userenv => { branch => $library->id } );
3395
3396     # Check the item out
3397     AddIssue( $patron->unblessed, $item->barcode );
3398     t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
3399     my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3400     my %params_renewal = (
3401         timestamp => { -like => $date . "%" },
3402         module => "CIRCULATION",
3403         action => "RENEWAL",
3404     );
3405     my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
3406     AddRenewal( $patron->id, $item->id, $library->id );
3407     my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3408     is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
3409
3410     my $checkouts = $patron->checkouts;
3411     # The following will fail if run on 00:00:00
3412     unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
3413
3414     my $lines = Koha::Account::Lines->search({
3415         borrowernumber => $patron->id,
3416         itemnumber     => $item->id
3417     });
3418
3419     is( $lines->count, 2 );
3420
3421     my $line = $lines->next;
3422     is( $line->debit_type_code, 'RENT',       'The issue of item with issuing charge generates an accountline of the correct type' );
3423     is( $line->branchcode,  $library->id, 'AddIssuingCharge correctly sets branchcode' );
3424     is( $line->description, '',     'AddIssue does not set a hardcoded description for the accountline' );
3425
3426     $line = $lines->next;
3427     is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
3428     is( $line->branchcode,  $library->id, 'AddRenewal correctly sets branchcode' );
3429     is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
3430
3431     t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
3432
3433     $context = Test::MockModule->new('C4::Context');
3434     $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
3435
3436     my $now = dt_from_string;
3437     $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
3438     $old_log_size = Koha::ActionLogs->count( \%params_renewal );
3439     my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
3440     $sth->execute($item->id, $library->id);
3441     my ($old_stats_size) = $sth->fetchrow_array;
3442     AddRenewal( $patron->id, $item->id, $library->id );
3443     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3444     $sth->execute($item->id, $library->id);
3445     my ($new_stats_size) = $sth->fetchrow_array;
3446     is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
3447     is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
3448
3449     AddReturn( $item->id, $library->id, undef, $date );
3450     AddIssue( $patron->unblessed, $item->barcode, $now );
3451     AddRenewal( $patron->id, $item->id, $library->id, undef, undef, 1 );
3452     my $lines_skipped = Koha::Account::Lines->search({
3453         borrowernumber => $patron->id,
3454         itemnumber     => $item->id
3455     });
3456     is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
3457
3458 };
3459
3460 subtest 'ProcessOfflinePayment() tests' => sub {
3461
3462     plan tests => 4;
3463
3464
3465     my $amount = 123;
3466
3467     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
3468     my $library = $builder->build_object({ class => 'Koha::Libraries' });
3469     my $result  = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
3470
3471     is( $result, 'Success.', 'The right string is returned' );
3472
3473     my $lines = $patron->account->lines;
3474     is( $lines->count, 1, 'line created correctly');
3475
3476     my $line = $lines->next;
3477     is( $line->amount+0, $amount * -1, 'amount picked from params' );
3478     is( $line->branchcode, $library->id, 'branchcode set correctly' );
3479
3480 };
3481
3482 subtest 'Incremented fee tests' => sub {
3483     plan tests => 19;
3484
3485     my $dt = dt_from_string();
3486     Time::Fake->offset( $dt->epoch );
3487
3488     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
3489
3490     my $library =
3491       $builder->build_object( { class => 'Koha::Libraries' } )->store;
3492
3493     my $module = new Test::MockModule('C4::Context');
3494     $module->mock( 'userenv', sub { { branch => $library->id } } );
3495
3496     my $patron = $builder->build_object(
3497         {
3498             class => 'Koha::Patrons',
3499             value => { categorycode => $patron_category->{categorycode} }
3500         }
3501     )->store;
3502
3503     my $itemtype = $builder->build_object(
3504         {
3505             class => 'Koha::ItemTypes',
3506             value => {
3507                 notforloan                   => undef,
3508                 rentalcharge                 => 0,
3509                 rentalcharge_daily           => 1,
3510                 rentalcharge_daily_calendar  => 0
3511             }
3512         }
3513     )->store;
3514
3515     my $item = $builder->build_sample_item(
3516         {
3517             library  => $library->{branchcode},
3518             itype    => $itemtype->id,
3519         }
3520     );
3521
3522     is( $itemtype->rentalcharge_daily+0,
3523         1, 'Daily rental charge stored and retreived correctly' );
3524     is( $item->effective_itemtype, $itemtype->id,
3525         "Itemtype set correctly for item" );
3526
3527     my $now         = dt_from_string;
3528     my $dt_from     = $now->clone;
3529     my $dt_to       = $now->clone->add( days => 7 );
3530     my $dt_to_renew = $now->clone->add( days => 13 );
3531
3532     # Daily Tests
3533     my $issue =
3534       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3535     my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3536     is( $accountline->amount+0, 7,
3537 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
3538     );
3539     $accountline->delete();
3540     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3541     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3542     is( $accountline->amount+0, 6,
3543 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
3544     );
3545     $accountline->delete();
3546     $issue->delete();
3547
3548     t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3549     $itemtype->rentalcharge_daily_calendar(1)->store();
3550     $issue =
3551       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3552     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3553     is( $accountline->amount+0, 7,
3554 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
3555     );
3556     $accountline->delete();
3557     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3558     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3559     is( $accountline->amount+0, 6,
3560 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
3561     );
3562     $accountline->delete();
3563     $issue->delete();
3564
3565     my $calendar = C4::Calendar->new( branchcode => $library->id );
3566     # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
3567     my $closed_day =
3568         ( $dt_from->day_of_week == 6 ) ? 0
3569       : ( $dt_from->day_of_week == 7 ) ? 1
3570       :                                  $dt_from->day_of_week + 1;
3571     my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
3572     $calendar->insert_week_day_holiday(
3573         weekday     => $closed_day,
3574         title       => 'Test holiday',
3575         description => 'Test holiday'
3576     );
3577     $issue =
3578       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3579     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3580     is( $accountline->amount+0, 6,
3581 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
3582     );
3583     $accountline->delete();
3584     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3585     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3586     is( $accountline->amount+0, 5,
3587 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
3588     );
3589     $accountline->delete();
3590     $issue->delete();
3591
3592     $itemtype->rentalcharge(2)->store;
3593     is( $itemtype->rentalcharge+0, 2,
3594         'Rental charge updated and retreived correctly' );
3595     $issue =
3596       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3597     my $accountlines =
3598       Koha::Account::Lines->search( { itemnumber => $item->id } );
3599     is( $accountlines->count, '2',
3600         "Fixed charge and accrued charge recorded distinctly" );
3601     $accountlines->delete();
3602     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3603     $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
3604     is( $accountlines->count, '2',
3605         "Fixed charge and accrued charge recorded distinctly, for renewal" );
3606     $accountlines->delete();
3607     $issue->delete();
3608     $itemtype->rentalcharge(0)->store;
3609     is( $itemtype->rentalcharge+0, 0,
3610         'Rental charge reset and retreived correctly' );
3611
3612     # Hourly
3613     Koha::CirculationRules->set_rule(
3614         {
3615             categorycode => $patron->categorycode,
3616             itemtype     => $itemtype->id,
3617             branchcode   => $library->id,
3618             rule_name    => 'lengthunit',
3619             rule_value   => 'hours',
3620         }
3621     );
3622
3623     $itemtype->rentalcharge_hourly('0.25')->store();
3624     is( $itemtype->rentalcharge_hourly,
3625         '0.25', 'Hourly rental charge stored and retreived correctly' );
3626
3627     $dt_to       = $now->clone->add( hours => 168 );
3628     $dt_to_renew = $now->clone->add( hours => 312 );
3629
3630     $itemtype->rentalcharge_hourly_calendar(0)->store();
3631     $issue =
3632       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3633     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3634     is( $accountline->amount + 0, 42,
3635         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)" );
3636     $accountline->delete();
3637     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3638     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3639     is( $accountline->amount + 0, 36,
3640         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)" );
3641     $accountline->delete();
3642     $issue->delete();
3643
3644     $itemtype->rentalcharge_hourly_calendar(1)->store();
3645     $issue =
3646       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3647     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3648     is( $accountline->amount + 0, 36,
3649         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)" );
3650     $accountline->delete();
3651     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3652     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3653     is( $accountline->amount + 0, 30,
3654         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
3655     $accountline->delete();
3656     $issue->delete();
3657
3658     $calendar->delete_holiday( weekday => $closed_day );
3659     $issue =
3660       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3661     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3662     is( $accountline->amount + 0, 42,
3663         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u" );
3664     $accountline->delete();
3665     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3666     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3667     is( $accountline->amount + 0, 36,
3668         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)" );
3669     $accountline->delete();
3670     $issue->delete();
3671     Time::Fake->reset;
3672 };
3673
3674 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
3675     plan tests => 2;
3676
3677     t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
3678     t::lib::Mocks::mock_preference('item-level_itypes', 1);
3679
3680     my $library =
3681       $builder->build_object( { class => 'Koha::Libraries' } )->store;
3682     my $patron = $builder->build_object(
3683         {
3684             class => 'Koha::Patrons',
3685             value => { categorycode => $patron_category->{categorycode} }
3686         }
3687     )->store;
3688
3689     my $itemtype = $builder->build_object(
3690         {
3691             class => 'Koha::ItemTypes',
3692             value => {
3693                 notforloan             => 0,
3694                 rentalcharge           => 0,
3695                 rentalcharge_daily => 0
3696             }
3697         }
3698     );
3699
3700     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3701     my $item = $builder->build_object(
3702         {
3703             class => 'Koha::Items',
3704             value  => {
3705                 homebranch    => $library->id,
3706                 holdingbranch => $library->id,
3707                 notforloan    => 0,
3708                 itemlost      => 0,
3709                 withdrawn     => 0,
3710                 itype         => $itemtype->id,
3711                 biblionumber  => $biblioitem->{biblionumber},
3712                 biblioitemnumber => $biblioitem->{biblioitemnumber},
3713             }
3714         }
3715     )->store;
3716
3717     my ( $issuingimpossible, $needsconfirmation );
3718     my $dt_from = dt_from_string();
3719     my $dt_due = $dt_from->clone->add( days => 3 );
3720
3721     $itemtype->rentalcharge(1)->store;
3722     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3723     is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
3724     $itemtype->rentalcharge('0')->store;
3725     $itemtype->rentalcharge_daily(1)->store;
3726     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3727     is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
3728     $itemtype->rentalcharge_daily('0')->store;
3729 };
3730
3731 subtest "Test Backdating of Returns" => sub {
3732     plan tests => 2;
3733
3734     my $branch = $library2->{branchcode};
3735     my $biblio = $builder->build_sample_biblio();
3736     my $item = $builder->build_sample_item(
3737         {
3738             biblionumber     => $biblio->biblionumber,
3739             library          => $branch,
3740             itype            => $itemtype,
3741         }
3742     );
3743
3744     my %a_borrower_data = (
3745         firstname =>  'Kyle',
3746         surname => 'Hall',
3747         categorycode => $patron_category->{categorycode},
3748         branchcode => $branch,
3749     );
3750     my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
3751     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
3752
3753     my $due_date = dt_from_string;
3754     my $issue = AddIssue( $borrower, $item->barcode, $due_date );
3755     UpdateFine(
3756         {
3757             issue_id          => $issue->id(),
3758             itemnumber        => $item->itemnumber,
3759             borrowernumber    => $borrowernumber,
3760             amount            => .25,
3761             amountoutstanding => .25,
3762             type              => q{}
3763         }
3764     );
3765
3766
3767     my ( undef, $message ) = AddReturn( $item->barcode, $branch, undef, $due_date );
3768
3769     my $accountline = Koha::Account::Lines->find( { issue_id => $issue->id } );
3770     is( $accountline->amountoutstanding+0, 0, 'Fee amount outstanding was reduced to 0' );
3771     is( $accountline->amount+0, 0, 'Fee amount was reduced to 0' );
3772 };
3773
3774 subtest 'Do not return on renewal (LOST charge)' => sub {
3775     plan tests => 1;
3776
3777     t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
3778     my $library = $builder->build_object( { class => "Koha::Libraries" } );
3779     my $manager = $builder->build_object( { class => "Koha::Patrons" } );
3780     t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
3781
3782     my $biblio = $builder->build_sample_biblio;
3783
3784     my $item = $builder->build_sample_item(
3785         {
3786             biblionumber     => $biblio->biblionumber,
3787             library          => $library->branchcode,
3788             replacementprice => 99.00,
3789             itype            => $itemtype,
3790         }
3791     );
3792
3793     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
3794     AddIssue( $patron->unblessed, $item->barcode );
3795
3796     my $accountline = Koha::Account::Line->new(
3797         {
3798             borrowernumber    => $patron->borrowernumber,
3799             debit_type_code   => 'LOST',
3800             status            => undef,
3801             itemnumber        => $item->itemnumber,
3802             amount            => 12,
3803             amountoutstanding => 12,
3804             interface         => 'something',
3805         }
3806     )->store();
3807
3808     # AddRenewal doesn't call _FixAccountForLostAndFound
3809     AddIssue( $patron->unblessed, $item->barcode );
3810
3811     is( $patron->checkouts->count, 1,
3812         'Renewal should not return the item even if a LOST payment has been made earlier'
3813     );
3814 };
3815
3816 $schema->storage->txn_rollback;
3817 C4::Context->clear_syspref_cache();
3818 $cache->clear_from_cache('single_holidays');