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