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