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