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