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