Bug 30110: Fix concatenation during assignements
[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 => 60;
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 => 97;
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     # Recalls
1434     t::lib::Mocks::mock_preference('UseRecalls', 1);
1435     Koha::CirculationRules->set_rules({
1436         categorycode => undef,
1437         branchcode => undef,
1438         itemtype => undef,
1439         rules => {
1440             recalls_allowed => 10,
1441             renewalsallowed => 5,
1442         },
1443     });
1444     my $recall_borrower = $builder->build_object({ class => 'Koha::Patrons' });
1445     my $recall_biblio = $builder->build_object({ class => 'Koha::Biblios' });
1446     my $recall_item1 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $recall_biblio->biblionumber } });
1447     my $recall_item2 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $recall_biblio->biblionumber } });
1448
1449     AddIssue( $renewing_borrower, $recall_item1->barcode );
1450
1451     # item-level and this item: renewal not allowed
1452     my $recall = Koha::Recall->new({
1453         biblionumber => $recall_item1->biblionumber,
1454         itemnumber => $recall_item1->itemnumber,
1455         borrowernumber => $recall_borrower->borrowernumber,
1456         branchcode => $recall_borrower->branchcode,
1457         item_level_recall => 1,
1458     })->store;
1459     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1460     is( $error, 'recalled', 'Cannot renew item that has been recalled' );
1461     $recall->set_cancelled;
1462
1463     # biblio-level requested recall: renewal not allowed
1464     $recall = Koha::Recall->new({
1465         biblionumber => $recall_item1->biblionumber,
1466         itemnumber => undef,
1467         borrowernumber => $recall_borrower->borrowernumber,
1468         branchcode => $recall_borrower->branchcode,
1469         item_level_recall => 0,
1470     })->store;
1471     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1472     is( $error, 'recalled', 'Cannot renew item if biblio is recalled and has no item allocated' );
1473     $recall->set_cancelled;
1474
1475     # item-level and not this item: renewal allowed
1476     $recall = Koha::Recall->new({
1477         biblionumber => $recall_item2->biblionumber,
1478         itemnumber => $recall_item2->itemnumber,
1479         borrowernumber => $recall_borrower->borrowernumber,
1480         branchcode => $recall_borrower->branchcode,
1481         item_level_recall => 1,
1482     })->store;
1483     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1484     is( $renewokay, 1, 'Can renew item if item-level recall on biblio is not on this item' );
1485     $recall->set_cancelled;
1486
1487     # biblio-level waiting recall: renewal allowed
1488     $recall = Koha::Recall->new({
1489         biblionumber => $recall_item1->biblionumber,
1490         itemnumber => undef,
1491         borrowernumber => $recall_borrower->borrowernumber,
1492         branchcode => $recall_borrower->branchcode,
1493         item_level_recall => 0,
1494     })->store;
1495     $recall->set_waiting({ item => $recall_item1 });
1496     ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1497     is( $renewokay, 1, 'Can renew item if biblio-level recall has already been allocated an item' );
1498     $recall->set_cancelled;
1499 };
1500
1501 subtest "GetUpcomingDueIssues" => sub {
1502     plan tests => 12;
1503
1504     my $branch   = $library2->{branchcode};
1505
1506     #Create another record
1507     my $biblio2 = $builder->build_sample_biblio();
1508
1509     #Create third item
1510     my $item_1 = Koha::Items->find($reused_itemnumber_1);
1511     my $item_2 = Koha::Items->find($reused_itemnumber_2);
1512     my $item_3 = $builder->build_sample_item(
1513         {
1514             biblionumber     => $biblio2->biblionumber,
1515             library          => $branch,
1516             itype            => $itemtype,
1517         }
1518     );
1519
1520
1521     # Create a borrower
1522     my %a_borrower_data = (
1523         firstname =>  'Fridolyn',
1524         surname => 'SOMERS',
1525         categorycode => $patron_category->{categorycode},
1526         branchcode => $branch,
1527     );
1528
1529     my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1530     my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1531
1532     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1533     my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1534     my $today = DateTime->today(time_zone => C4::Context->tz());
1535
1536     my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1537     my $datedue = dt_from_string( $issue->date_due() );
1538     my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1539     my $datedue2 = dt_from_string( $issue->date_due() );
1540
1541     my $upcoming_dues;
1542
1543     # GetUpcomingDueIssues tests
1544     for my $i(0..1) {
1545         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1546         is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1547     }
1548
1549     #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1550     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1551     is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1552
1553     for my $i(3..5) {
1554         $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1555         is ( scalar( @$upcoming_dues ), 1,
1556             "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1557     }
1558
1559     # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1560
1561     my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1562
1563     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1564     is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1565
1566     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1567     is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1568
1569     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1570     is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1571
1572     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 }  );
1573     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1574
1575     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1576     is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1577
1578     $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1579     is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1580
1581 };
1582
1583 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1584     my $branch   = $library2->{branchcode};
1585
1586     my $biblio = $builder->build_sample_biblio();
1587
1588     #Create third item
1589     my $item = $builder->build_sample_item(
1590         {
1591             biblionumber     => $biblio->biblionumber,
1592             library          => $branch,
1593             itype            => $itemtype,
1594         }
1595     );
1596
1597     # Create a borrower
1598     my %a_borrower_data = (
1599         firstname =>  'Kyle',
1600         surname => 'Hall',
1601         categorycode => $patron_category->{categorycode},
1602         branchcode => $branch,
1603     );
1604
1605     my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1606
1607     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1608     my $issue = AddIssue( $borrower, $item->barcode );
1609     UpdateFine(
1610         {
1611             issue_id       => $issue->id(),
1612             itemnumber     => $item->itemnumber,
1613             borrowernumber => $borrowernumber,
1614             amount         => 0,
1615             type           => q{}
1616         }
1617     );
1618
1619     my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1620     my $count = $hr->{count};
1621
1622     is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1623 };
1624
1625 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1626     $dbh->do('DELETE FROM issues');
1627     $dbh->do('DELETE FROM items');
1628     $dbh->do('DELETE FROM circulation_rules');
1629     Koha::CirculationRules->set_rules(
1630         {
1631             categorycode => undef,
1632             itemtype     => undef,
1633             branchcode   => undef,
1634             rules        => {
1635                 reservesallowed => 25,
1636                 issuelength     => 14,
1637                 lengthunit      => 'days',
1638                 renewalsallowed => 1,
1639                 renewalperiod   => 7,
1640                 norenewalbefore => undef,
1641                 auto_renew      => 0,
1642                 fine            => .10,
1643                 chargeperiod    => 1,
1644                 maxissueqty     => 20
1645             }
1646         }
1647     );
1648     my $biblio = $builder->build_sample_biblio();
1649
1650     my $item_1 = $builder->build_sample_item(
1651         {
1652             biblionumber     => $biblio->biblionumber,
1653             library          => $library2->{branchcode},
1654             itype            => $itemtype,
1655         }
1656     );
1657
1658     my $item_2= $builder->build_sample_item(
1659         {
1660             biblionumber     => $biblio->biblionumber,
1661             library          => $library2->{branchcode},
1662             itype            => $itemtype,
1663         }
1664     );
1665
1666     my $borrowernumber1 = Koha::Patron->new({
1667         firstname    => 'Kyle',
1668         surname      => 'Hall',
1669         categorycode => $patron_category->{categorycode},
1670         branchcode   => $library2->{branchcode},
1671     })->store->borrowernumber;
1672     my $borrowernumber2 = Koha::Patron->new({
1673         firstname    => 'Chelsea',
1674         surname      => 'Hall',
1675         categorycode => $patron_category->{categorycode},
1676         branchcode   => $library2->{branchcode},
1677     })->store->borrowernumber;
1678
1679     my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1680     my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1681
1682     my $issue = AddIssue( $borrower1, $item_1->barcode );
1683
1684     my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1685     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1686
1687     AddReserve(
1688         {
1689             branchcode     => $library2->{branchcode},
1690             borrowernumber => $borrowernumber2,
1691             biblionumber   => $biblio->biblionumber,
1692             priority       => 1,
1693         }
1694     );
1695
1696     Koha::CirculationRules->set_rules(
1697         {
1698             categorycode => undef,
1699             itemtype     => undef,
1700             branchcode   => undef,
1701             rules        => {
1702                 onshelfholds => 0,
1703             }
1704         }
1705     );
1706     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1707     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1708     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1709
1710     Koha::CirculationRules->set_rules(
1711         {
1712             categorycode => undef,
1713             itemtype     => undef,
1714             branchcode   => undef,
1715             rules        => {
1716                 onshelfholds => 0,
1717             }
1718         }
1719     );
1720     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1721     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1722     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1723
1724     Koha::CirculationRules->set_rules(
1725         {
1726             categorycode => undef,
1727             itemtype     => undef,
1728             branchcode   => undef,
1729             rules        => {
1730                 onshelfholds => 1,
1731             }
1732         }
1733     );
1734     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1735     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1736     is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1737
1738     Koha::CirculationRules->set_rules(
1739         {
1740             categorycode => undef,
1741             itemtype     => undef,
1742             branchcode   => undef,
1743             rules        => {
1744                 onshelfholds => 1,
1745             }
1746         }
1747     );
1748     t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1749     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1750     is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1751
1752     # Setting item not checked out to be not for loan but holdable
1753     $item_2->notforloan(-1)->store;
1754
1755     ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1756     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' );
1757 };
1758
1759 {
1760     # Don't allow renewing onsite checkout
1761     my $branch   = $library->{branchcode};
1762
1763     #Create another record
1764     my $biblio = $builder->build_sample_biblio();
1765
1766     my $item = $builder->build_sample_item(
1767         {
1768             biblionumber     => $biblio->biblionumber,
1769             library          => $branch,
1770             itype            => $itemtype,
1771         }
1772     );
1773
1774     my $borrowernumber = Koha::Patron->new({
1775         firstname =>  'fn',
1776         surname => 'dn',
1777         categorycode => $patron_category->{categorycode},
1778         branchcode => $branch,
1779     })->store->borrowernumber;
1780
1781     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1782
1783     my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1784     my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1785     is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1786     is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1787 }
1788
1789 {
1790     my $library = $builder->build({ source => 'Branch' });
1791
1792     my $biblio = $builder->build_sample_biblio();
1793
1794     my $item = $builder->build_sample_item(
1795         {
1796             biblionumber     => $biblio->biblionumber,
1797             library          => $library->{branchcode},
1798             itype            => $itemtype,
1799         }
1800     );
1801
1802     my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1803
1804     my $issue = AddIssue( $patron, $item->barcode );
1805     UpdateFine(
1806         {
1807             issue_id       => $issue->id(),
1808             itemnumber     => $item->itemnumber,
1809             borrowernumber => $patron->{borrowernumber},
1810             amount         => 1,
1811             type           => q{}
1812         }
1813     );
1814     UpdateFine(
1815         {
1816             issue_id       => $issue->id(),
1817             itemnumber     => $item->itemnumber,
1818             borrowernumber => $patron->{borrowernumber},
1819             amount         => 2,
1820             type           => q{}
1821         }
1822     );
1823     is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1824 }
1825
1826 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1827     plan tests => 24;
1828
1829     my $homebranch    = $builder->build( { source => 'Branch' } );
1830     my $holdingbranch = $builder->build( { source => 'Branch' } );
1831     my $otherbranch   = $builder->build( { source => 'Branch' } );
1832     my $patron_1      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1833     my $patron_2      = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1834
1835     my $item = $builder->build_sample_item(
1836         {
1837             homebranch    => $homebranch->{branchcode},
1838             holdingbranch => $holdingbranch->{branchcode},
1839         }
1840     );
1841
1842     set_userenv($holdingbranch);
1843
1844     my $issue = AddIssue( $patron_1->unblessed, $item->barcode );
1845     is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1846
1847     my ( $error, $question, $alerts );
1848
1849     # AllowReturnToBranch == anywhere
1850     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1851     ## Test that unknown barcodes don't generate internal server errors
1852     set_userenv($homebranch);
1853     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1854     ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1855     ## Can be issued from homebranch
1856     set_userenv($homebranch);
1857     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1858     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1859     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1860     ## Can be issued from holdingbranch
1861     set_userenv($holdingbranch);
1862     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1863     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1864     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1865     ## Can be issued from another branch
1866     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1867     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1868     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1869
1870     # AllowReturnToBranch == holdingbranch
1871     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1872     ## Cannot be issued from homebranch
1873     set_userenv($homebranch);
1874     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1875     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1876     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1877     is( $error->{branch_to_return},         $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1878     ## Can be issued from holdinbranch
1879     set_userenv($holdingbranch);
1880     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1881     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1882     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1883     ## Cannot be issued from another branch
1884     set_userenv($otherbranch);
1885     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1886     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1887     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1888     is( $error->{branch_to_return},         $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
1889
1890     # AllowReturnToBranch == homebranch
1891     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1892     ## Can be issued from holdinbranch
1893     set_userenv($homebranch);
1894     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1895     is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1896     is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1897     ## Cannot be issued from holdinbranch
1898     set_userenv($holdingbranch);
1899     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1900     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1901     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1902     is( $error->{branch_to_return},         $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1903     ## Cannot be issued from holdinbranch
1904     set_userenv($otherbranch);
1905     ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1906     is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1907     is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1908     is( $error->{branch_to_return},         $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1909
1910     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1911 };
1912
1913 subtest 'AddIssue & AllowReturnToBranch' => sub {
1914     plan tests => 9;
1915
1916     my $homebranch    = $builder->build( { source => 'Branch' } );
1917     my $holdingbranch = $builder->build( { source => 'Branch' } );
1918     my $otherbranch   = $builder->build( { source => 'Branch' } );
1919     my $patron_1      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1920     my $patron_2      = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1921
1922     my $item = $builder->build_sample_item(
1923         {
1924             homebranch    => $homebranch->{branchcode},
1925             holdingbranch => $holdingbranch->{branchcode},
1926         }
1927     );
1928
1929     set_userenv($holdingbranch);
1930
1931     my $ref_issue = 'Koha::Checkout';
1932     my $issue = AddIssue( $patron_1, $item->barcode );
1933
1934     my ( $error, $question, $alerts );
1935
1936     # AllowReturnToBranch == homebranch
1937     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1938     ## Can be issued from homebranch
1939     set_userenv($homebranch);
1940     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
1941     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1942     ## Can be issued from holdinbranch
1943     set_userenv($holdingbranch);
1944     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
1945     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1946     ## Can be issued from another branch
1947     set_userenv($otherbranch);
1948     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
1949     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1950
1951     # AllowReturnToBranch == holdinbranch
1952     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1953     ## Cannot be issued from homebranch
1954     set_userenv($homebranch);
1955     is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
1956     ## Can be issued from holdingbranch
1957     set_userenv($holdingbranch);
1958     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
1959     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1960     ## Cannot be issued from another branch
1961     set_userenv($otherbranch);
1962     is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
1963
1964     # AllowReturnToBranch == homebranch
1965     t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1966     ## Can be issued from homebranch
1967     set_userenv($homebranch);
1968     is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
1969     set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1970     ## Cannot be issued from holdinbranch
1971     set_userenv($holdingbranch);
1972     is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
1973     ## Cannot be issued from another branch
1974     set_userenv($otherbranch);
1975     is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
1976     # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1977 };
1978
1979 subtest 'AddIssue | recalls' => sub {
1980     plan tests => 3;
1981
1982     t::lib::Mocks::mock_preference("UseRecalls", 1);
1983     t::lib::Mocks::mock_preference("item-level_itypes", 1);
1984     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1985     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
1986     my $item = $builder->build_sample_item;
1987     Koha::CirculationRules->set_rules({
1988         branchcode => undef,
1989         itemtype => undef,
1990         categorycode => undef,
1991         rules => {
1992             recalls_allowed => 10,
1993         },
1994     });
1995
1996     # checking out item that they have recalled
1997     my $recall1 = Koha::Recall->new(
1998         {   borrowernumber    => $patron1->borrowernumber,
1999             biblionumber      => $item->biblionumber,
2000             itemnumber        => $item->itemnumber,
2001             item_level_recall => 1,
2002             branchcode        => $patron1->branchcode,
2003         }
2004     )->store;
2005     AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall1->recall_id } );
2006     $recall1 = Koha::Recalls->find( $recall1->recall_id );
2007     is( $recall1->fulfilled, 1, 'Recall was fulfilled when patron checked out item' );
2008     AddReturn( $item->barcode, $item->homebranch );
2009
2010     # this item is has a recall request. cancel recall
2011     my $recall2 = Koha::Recall->new(
2012         {   borrowernumber    => $patron2->borrowernumber,
2013             biblionumber      => $item->biblionumber,
2014             itemnumber        => $item->itemnumber,
2015             item_level_recall => 1,
2016             branchcode        => $patron2->branchcode,
2017         }
2018     )->store;
2019     AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall2->recall_id, cancel_recall => 'cancel' } );
2020     $recall2 = Koha::Recalls->find( $recall2->recall_id );
2021     is( $recall2->cancelled, 1, 'Recall was cancelled when patron checked out item' );
2022     AddReturn( $item->barcode, $item->homebranch );
2023
2024     # this item is waiting to fulfill a recall. revert recall
2025     my $recall3 = Koha::Recall->new(
2026         {   borrowernumber    => $patron2->borrowernumber,
2027             biblionumber      => $item->biblionumber,
2028             itemnumber        => $item->itemnumber,
2029             item_level_recall => 1,
2030             branchcode        => $patron2->branchcode,
2031         }
2032     )->store;
2033     $recall3->set_waiting;
2034     AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall3->recall_id, cancel_recall => 'revert' } );
2035     $recall3 = Koha::Recalls->find( $recall3->recall_id );
2036     is( $recall3->requested, 1, 'Recall was reverted from waiting when patron checked out item' );
2037     AddReturn( $item->barcode, $item->homebranch );
2038 };
2039
2040
2041 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
2042     plan tests => 8;
2043
2044     my $library = $builder->build( { source => 'Branch' } );
2045     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2046     my $item_1 = $builder->build_sample_item(
2047         {
2048             library => $library->{branchcode},
2049         }
2050     );
2051     my $item_2 = $builder->build_sample_item(
2052         {
2053             library => $library->{branchcode},
2054         }
2055     );
2056
2057     my ( $error, $question, $alerts );
2058
2059     # Patron cannot issue item_1, they have overdues
2060     my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
2061     my $issue = AddIssue( $patron->unblessed, $item_1->barcode, $yesterday );    # Add an overdue
2062
2063     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
2064     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2065     is( keys(%$error) + keys(%$alerts),  0, 'No key for error and alert' . str($error, $question, $alerts) );
2066     is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
2067
2068     t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
2069     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2070     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
2071     is( $error->{USERBLOCKEDOVERDUE},      1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
2072
2073     # Patron cannot issue item_1, they are debarred
2074     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
2075     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
2076     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2077     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
2078     is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
2079
2080     Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
2081     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2082     is( keys(%$question) + keys(%$alerts),  0, 'No key for question and alert ' . str($error, $question, $alerts) );
2083     is( $error->{USERBLOCKEDNOENDDATE},    '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
2084 };
2085
2086 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
2087     plan tests => 1;
2088
2089     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2090     my $patron_category_x = $builder->build_object(
2091         {
2092             class => 'Koha::Patron::Categories',
2093             value => { category_type => 'X' }
2094         }
2095     );
2096     my $patron = $builder->build_object(
2097         {
2098             class => 'Koha::Patrons',
2099             value => {
2100                 categorycode  => $patron_category_x->categorycode,
2101                 gonenoaddress => undef,
2102                 lost          => undef,
2103                 debarred      => undef,
2104                 borrowernotes => ""
2105             }
2106         }
2107     );
2108     my $item_1 = $builder->build_sample_item(
2109         {
2110             library => $library->{branchcode},
2111         }
2112     );
2113
2114     my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
2115     is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
2116
2117     # TODO There are other tests to provide here
2118 };
2119
2120 subtest 'MultipleReserves' => sub {
2121     plan tests => 3;
2122
2123     my $biblio = $builder->build_sample_biblio();
2124
2125     my $branch = $library2->{branchcode};
2126
2127     my $item_1 = $builder->build_sample_item(
2128         {
2129             biblionumber     => $biblio->biblionumber,
2130             library          => $branch,
2131             replacementprice => 12.00,
2132             itype            => $itemtype,
2133         }
2134     );
2135
2136     my $item_2 = $builder->build_sample_item(
2137         {
2138             biblionumber     => $biblio->biblionumber,
2139             library          => $branch,
2140             replacementprice => 12.00,
2141             itype            => $itemtype,
2142         }
2143     );
2144
2145     my $bibitems       = '';
2146     my $priority       = '1';
2147     my $resdate        = undef;
2148     my $expdate        = undef;
2149     my $notes          = '';
2150     my $checkitem      = undef;
2151     my $found          = undef;
2152
2153     my %renewing_borrower_data = (
2154         firstname =>  'John',
2155         surname => 'Renewal',
2156         categorycode => $patron_category->{categorycode},
2157         branchcode => $branch,
2158     );
2159     my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
2160     my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
2161     my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
2162     my $datedue = dt_from_string( $issue->date_due() );
2163     is (defined $issue->date_due(), 1, "item 1 checked out");
2164     my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
2165
2166     my %reserving_borrower_data1 = (
2167         firstname =>  'Katrin',
2168         surname => 'Reservation',
2169         categorycode => $patron_category->{categorycode},
2170         branchcode => $branch,
2171     );
2172     my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
2173     AddReserve(
2174         {
2175             branchcode       => $branch,
2176             borrowernumber   => $reserving_borrowernumber1,
2177             biblionumber     => $biblio->biblionumber,
2178             priority         => $priority,
2179             reservation_date => $resdate,
2180             expiration_date  => $expdate,
2181             notes            => $notes,
2182             itemnumber       => $checkitem,
2183             found            => $found,
2184         }
2185     );
2186
2187     my %reserving_borrower_data2 = (
2188         firstname =>  'Kirk',
2189         surname => 'Reservation',
2190         categorycode => $patron_category->{categorycode},
2191         branchcode => $branch,
2192     );
2193     my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
2194     AddReserve(
2195         {
2196             branchcode       => $branch,
2197             borrowernumber   => $reserving_borrowernumber2,
2198             biblionumber     => $biblio->biblionumber,
2199             priority         => $priority,
2200             reservation_date => $resdate,
2201             expiration_date  => $expdate,
2202             notes            => $notes,
2203             itemnumber       => $checkitem,
2204             found            => $found,
2205         }
2206     );
2207
2208     {
2209         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2210         is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2211     }
2212
2213     my $item_3 = $builder->build_sample_item(
2214         {
2215             biblionumber     => $biblio->biblionumber,
2216             library          => $branch,
2217             replacementprice => 12.00,
2218             itype            => $itemtype,
2219         }
2220     );
2221
2222     {
2223         my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2224         is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2225     }
2226 };
2227
2228 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2229     plan tests => 5;
2230
2231     my $library = $builder->build( { source => 'Branch' } );
2232     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2233
2234     my $biblionumber = $builder->build_sample_biblio(
2235         {
2236             branchcode => $library->{branchcode},
2237         }
2238     )->biblionumber;
2239     my $item_1 = $builder->build_sample_item(
2240         {
2241             biblionumber => $biblionumber,
2242             library      => $library->{branchcode},
2243         }
2244     );
2245
2246     my $item_2 = $builder->build_sample_item(
2247         {
2248             biblionumber => $biblionumber,
2249             library      => $library->{branchcode},
2250         }
2251     );
2252
2253     my ( $error, $question, $alerts );
2254     my $issue = AddIssue( $patron->unblessed, $item_1->barcode, dt_from_string->add( days => 1 ) );
2255
2256     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2257     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2258     cmp_deeply(
2259         { error => $error, alerts => $alerts },
2260         { error => {}, alerts => {} },
2261         'No error or alert should be raised'
2262     );
2263     is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2264
2265     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2266     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2267     cmp_deeply(
2268         { error => $error, question => $question, alerts => $alerts },
2269         { error => {}, question => {}, alerts => {} },
2270         'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2271     );
2272
2273     # Add a subscription
2274     Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2275
2276     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2277     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2278     cmp_deeply(
2279         { error => $error, question => $question, alerts => $alerts },
2280         { error => {}, question => {}, alerts => {} },
2281         'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2282     );
2283
2284     t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2285     ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2286     cmp_deeply(
2287         { error => $error, question => $question, alerts => $alerts },
2288         { error => {}, question => {}, alerts => {} },
2289         'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2290     );
2291 };
2292
2293 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2294     plan tests => 8;
2295
2296     my $library = $builder->build( { source => 'Branch' } );
2297     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2298
2299     # Add 2 items
2300     my $biblionumber = $builder->build_sample_biblio(
2301         {
2302             branchcode => $library->{branchcode},
2303         }
2304     )->biblionumber;
2305     my $item_1 = $builder->build_sample_item(
2306         {
2307             biblionumber => $biblionumber,
2308             library      => $library->{branchcode},
2309         }
2310     );
2311     my $item_2 = $builder->build_sample_item(
2312         {
2313             biblionumber => $biblionumber,
2314             library      => $library->{branchcode},
2315         }
2316     );
2317
2318     # And the circulation rule
2319     Koha::CirculationRules->search->delete;
2320     Koha::CirculationRules->set_rules(
2321         {
2322             categorycode => undef,
2323             itemtype     => undef,
2324             branchcode   => undef,
2325             rules        => {
2326                 issuelength => 1,
2327                 firstremind => 1,        # 1 day of grace
2328                 finedays    => 2,        # 2 days of fine per day of overdue
2329                 lengthunit  => 'days',
2330             }
2331         }
2332     );
2333
2334     # Patron cannot issue item_1, they have overdues
2335     my $now = dt_from_string;
2336     my $five_days_ago = $now->clone->subtract( days => 5 );
2337     my $ten_days_ago  = $now->clone->subtract( days => 10 );
2338     AddIssue( $patron, $item_1->barcode, $five_days_ago );    # Add an overdue
2339     AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2340       ;    # Add another overdue
2341
2342     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2343     AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2344     my $debarments = Koha::Patron::Debarments::GetDebarments(
2345         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2346     is( scalar(@$debarments), 1 );
2347
2348     # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2349     # Same for the others
2350     my $expected_expiration = output_pref(
2351         {
2352             dt         => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2353             dateformat => 'sql',
2354             dateonly   => 1
2355         }
2356     );
2357     is( $debarments->[0]->{expiration}, $expected_expiration );
2358
2359     AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2360     $debarments = Koha::Patron::Debarments::GetDebarments(
2361         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2362     is( scalar(@$debarments), 1 );
2363     $expected_expiration = output_pref(
2364         {
2365             dt         => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2366             dateformat => 'sql',
2367             dateonly   => 1
2368         }
2369     );
2370     is( $debarments->[0]->{expiration}, $expected_expiration );
2371
2372     Koha::Patron::Debarments::DelUniqueDebarment(
2373         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2374
2375     t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2376     AddIssue( $patron, $item_1->barcode, $five_days_ago );    # Add an overdue
2377     AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2378       ;    # Add another overdue
2379     AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2380     $debarments = Koha::Patron::Debarments::GetDebarments(
2381         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2382     is( scalar(@$debarments), 1 );
2383     $expected_expiration = output_pref(
2384         {
2385             dt         => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2386             dateformat => 'sql',
2387             dateonly   => 1
2388         }
2389     );
2390     is( $debarments->[0]->{expiration}, $expected_expiration );
2391
2392     AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2393     $debarments = Koha::Patron::Debarments::GetDebarments(
2394         { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2395     is( scalar(@$debarments), 1 );
2396     $expected_expiration = output_pref(
2397         {
2398             dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2399             dateformat => 'sql',
2400             dateonly   => 1
2401         }
2402     );
2403     is( $debarments->[0]->{expiration}, $expected_expiration );
2404 };
2405
2406 subtest 'AddReturn + suspension_chargeperiod' => sub {
2407     plan tests => 27;
2408
2409     my $library = $builder->build( { source => 'Branch' } );
2410     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2411
2412     my $biblionumber = $builder->build_sample_biblio(
2413         {
2414             branchcode => $library->{branchcode},
2415         }
2416     )->biblionumber;
2417     my $item_1 = $builder->build_sample_item(
2418         {
2419             biblionumber => $biblionumber,
2420             library      => $library->{branchcode},
2421         }
2422     );
2423
2424     # And the issuing rule
2425     Koha::CirculationRules->search->delete;
2426     Koha::CirculationRules->set_rules(
2427         {
2428             categorycode => '*',
2429             itemtype     => '*',
2430             branchcode   => '*',
2431             rules        => {
2432                 issuelength => 1,
2433                 firstremind => 0,    # 0 day of grace
2434                 finedays    => 2,    # 2 days of fine per day of overdue
2435                 suspension_chargeperiod => 1,
2436                 lengthunit              => 'days',
2437             }
2438         }
2439     );
2440
2441     my $now = dt_from_string;
2442     my $five_days_ago = $now->clone->subtract( days => 5 );
2443     # We want to charge 2 days every day, without grace
2444     # With 5 days of overdue: 5 * Z
2445     my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2446     test_debarment_on_checkout(
2447         {
2448             item            => $item_1,
2449             library         => $library,
2450             patron          => $patron,
2451             due_date        => $five_days_ago,
2452             expiration_date => $expected_expiration,
2453         }
2454     );
2455
2456     # Same with undef firstremind
2457     Koha::CirculationRules->search->delete;
2458     Koha::CirculationRules->set_rules(
2459         {
2460             categorycode => '*',
2461             itemtype     => '*',
2462             branchcode   => '*',
2463             rules        => {
2464                 issuelength => 1,
2465                 firstremind => undef,    # 0 day of grace
2466                 finedays    => 2,    # 2 days of fine per day of overdue
2467                 suspension_chargeperiod => 1,
2468                 lengthunit              => 'days',
2469             }
2470         }
2471     );
2472     {
2473     my $now = dt_from_string;
2474     my $five_days_ago = $now->clone->subtract( days => 5 );
2475     # We want to charge 2 days every day, without grace
2476     # With 5 days of overdue: 5 * Z
2477     my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2478     test_debarment_on_checkout(
2479         {
2480             item            => $item_1,
2481             library         => $library,
2482             patron          => $patron,
2483             due_date        => $five_days_ago,
2484             expiration_date => $expected_expiration,
2485         }
2486     );
2487     }
2488     # We want to charge 2 days every 2 days, without grace
2489     # With 5 days of overdue: (5 * 2) / 2
2490     Koha::CirculationRules->set_rule(
2491         {
2492             categorycode => undef,
2493             branchcode   => undef,
2494             itemtype     => undef,
2495             rule_name    => 'suspension_chargeperiod',
2496             rule_value   => '2',
2497         }
2498     );
2499
2500     $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2501     test_debarment_on_checkout(
2502         {
2503             item            => $item_1,
2504             library         => $library,
2505             patron          => $patron,
2506             due_date        => $five_days_ago,
2507             expiration_date => $expected_expiration,
2508         }
2509     );
2510
2511     # We want to charge 2 days every 3 days, with 1 day of grace
2512     # With 5 days of overdue: ((5-1) / 3 ) * 2
2513     Koha::CirculationRules->set_rules(
2514         {
2515             categorycode => undef,
2516             branchcode   => undef,
2517             itemtype     => undef,
2518             rules        => {
2519                 suspension_chargeperiod => 3,
2520                 firstremind             => 1,
2521             }
2522         }
2523     );
2524     $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2525     test_debarment_on_checkout(
2526         {
2527             item            => $item_1,
2528             library         => $library,
2529             patron          => $patron,
2530             due_date        => $five_days_ago,
2531             expiration_date => $expected_expiration,
2532         }
2533     );
2534
2535     # Use finesCalendar to know if holiday must be skipped to calculate the due date
2536     # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2537     Koha::CirculationRules->set_rules(
2538         {
2539             categorycode => undef,
2540             branchcode   => undef,
2541             itemtype     => undef,
2542             rules        => {
2543                 finedays                => 2,
2544                 suspension_chargeperiod => 1,
2545                 firstremind             => 0,
2546             }
2547         }
2548     );
2549     t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2550     t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2551
2552     # Adding a holiday 2 days ago
2553     my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2554     my $two_days_ago = $now->clone->subtract( days => 2 );
2555     $calendar->insert_single_holiday(
2556         day             => $two_days_ago->day,
2557         month           => $two_days_ago->month,
2558         year            => $two_days_ago->year,
2559         title           => 'holidayTest-2d',
2560         description     => 'holidayDesc 2 days ago'
2561     );
2562     # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2563     $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2564     test_debarment_on_checkout(
2565         {
2566             item            => $item_1,
2567             library         => $library,
2568             patron          => $patron,
2569             due_date        => $five_days_ago,
2570             expiration_date => $expected_expiration,
2571         }
2572     );
2573
2574     # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2575     my $two_days_ahead = $now->clone->add( days => 2 );
2576     $calendar->insert_single_holiday(
2577         day             => $two_days_ahead->day,
2578         month           => $two_days_ahead->month,
2579         year            => $two_days_ahead->year,
2580         title           => 'holidayTest+2d',
2581         description     => 'holidayDesc 2 days ahead'
2582     );
2583
2584     # Same as above, but we should skip D+2
2585     $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2586     test_debarment_on_checkout(
2587         {
2588             item            => $item_1,
2589             library         => $library,
2590             patron          => $patron,
2591             due_date        => $five_days_ago,
2592             expiration_date => $expected_expiration,
2593         }
2594     );
2595
2596     # Adding another holiday, day of expiration date
2597     my $expected_expiration_dt = dt_from_string($expected_expiration);
2598     $calendar->insert_single_holiday(
2599         day             => $expected_expiration_dt->day,
2600         month           => $expected_expiration_dt->month,
2601         year            => $expected_expiration_dt->year,
2602         title           => 'holidayTest_exp',
2603         description     => 'holidayDesc on expiration date'
2604     );
2605     # Expiration date will be the day after
2606     test_debarment_on_checkout(
2607         {
2608             item            => $item_1,
2609             library         => $library,
2610             patron          => $patron,
2611             due_date        => $five_days_ago,
2612             expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2613         }
2614     );
2615
2616     test_debarment_on_checkout(
2617         {
2618             item            => $item_1,
2619             library         => $library,
2620             patron          => $patron,
2621             return_date     => $now->clone->add(days => 5),
2622             expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2623         }
2624     );
2625
2626     test_debarment_on_checkout(
2627         {
2628             item            => $item_1,
2629             library         => $library,
2630             patron          => $patron,
2631             due_date        => $now->clone->add(days => 1),
2632             return_date     => $now->clone->add(days => 5),
2633             expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2634         }
2635     );
2636
2637 };
2638
2639 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2640     plan tests => 2;
2641
2642     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2643     my $patron1 = $builder->build_object(
2644         {
2645             class => 'Koha::Patrons',
2646             value => {
2647                 library      => $library->branchcode,
2648                 categorycode => $patron_category->{categorycode}
2649             }
2650         }
2651     );
2652     my $patron2 = $builder->build_object(
2653         {
2654             class => 'Koha::Patrons',
2655             value => {
2656                 library      => $library->branchcode,
2657                 categorycode => $patron_category->{categorycode}
2658             }
2659         }
2660     );
2661
2662     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2663
2664     my $item = $builder->build_sample_item(
2665         {
2666             library      => $library->branchcode,
2667         }
2668     );
2669
2670     my ( $error, $question, $alerts );
2671     my $issue = AddIssue( $patron1->unblessed, $item->barcode );
2672
2673     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2674     ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2675     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' );
2676
2677     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2678     ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2679     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' );
2680
2681     t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2682 };
2683
2684
2685 subtest 'AddReturn | is_overdue' => sub {
2686     plan tests => 9;
2687
2688     t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2689     t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2690     t::lib::Mocks::mock_preference('finesMode', 'production');
2691     t::lib::Mocks::mock_preference('MaxFine', '100');
2692
2693     my $library = $builder->build( { source => 'Branch' } );
2694     my $patron  = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2695     my $manager = $builder->build_object({ class => "Koha::Patrons" });
2696     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2697
2698     my $item = $builder->build_sample_item(
2699         {
2700             library      => $library->{branchcode},
2701             replacementprice => 7
2702         }
2703     );
2704
2705     Koha::CirculationRules->search->delete;
2706     Koha::CirculationRules->set_rules(
2707         {
2708             categorycode => undef,
2709             itemtype     => undef,
2710             branchcode   => undef,
2711             rules        => {
2712                 issuelength  => 6,
2713                 lengthunit   => 'days',
2714                 fine         => 1,        # Charge 1 every day of overdue
2715                 chargeperiod => 1,
2716             }
2717         }
2718     );
2719
2720     my $now   = dt_from_string;
2721     my $one_day_ago   = $now->clone->subtract( days => 1 );
2722     my $two_days_ago  = $now->clone->subtract( days => 2 );
2723     my $five_days_ago = $now->clone->subtract( days => 5 );
2724     my $ten_days_ago  = $now->clone->subtract( days => 10 );
2725     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2726
2727     # No return date specified, today will be used => 10 days overdue charged
2728     AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2729     AddReturn( $item->barcode, $library->{branchcode} );
2730     is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2731     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2732
2733     # specify return date 5 days before => no overdue charged
2734     AddIssue( $patron->unblessed, $item->barcode, $five_days_ago ); # date due was 5d ago
2735     AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
2736     is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2737     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2738
2739     # specify return date 5 days later => 5 days overdue charged
2740     AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2741     AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
2742     is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2743     Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2744
2745     # specify return date 5 days later, specify exemptfine => no overdue charge
2746     AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2747     AddReturn( $item->barcode, $library->{branchcode}, 1, $five_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     subtest 'bug 22877 | Lost item return' => sub {
2752
2753         plan tests => 3;
2754
2755         my $issue = AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );    # date due was 10d ago
2756
2757         # Fake fines cronjob on this checkout
2758         my ($fine) =
2759           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2760             $ten_days_ago, $now );
2761         UpdateFine(
2762             {
2763                 issue_id       => $issue->issue_id,
2764                 itemnumber     => $item->itemnumber,
2765                 borrowernumber => $patron->borrowernumber,
2766                 amount         => $fine,
2767                 due            => output_pref($ten_days_ago)
2768             }
2769         );
2770         is( int( $patron->account->balance() ),
2771             10, "Overdue fine of 10 days overdue" );
2772
2773         # Fake longoverdue with charge and not marking returned
2774         LostItem( $item->itemnumber, 'cronjob', 0 );
2775         is( int( $patron->account->balance() ),
2776             17, "Lost fine of 7 plus 10 days overdue" );
2777
2778         # Now we return it today
2779         AddReturn( $item->barcode, $library->{branchcode} );
2780         is( int( $patron->account->balance() ),
2781             17, "Should have a single 10 days overdue fine and lost charge" );
2782
2783         # Cleanup
2784         Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2785     };
2786
2787     subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
2788
2789         plan tests => 17;
2790
2791         t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2792
2793         my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago );    # date due was 1d ago
2794
2795         # Fake fines cronjob on this checkout
2796         my ($fine) =
2797           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2798             $one_day_ago, $now );
2799         UpdateFine(
2800             {
2801                 issue_id       => $issue->issue_id,
2802                 itemnumber     => $item->itemnumber,
2803                 borrowernumber => $patron->borrowernumber,
2804                 amount         => $fine,
2805                 due            => output_pref($one_day_ago)
2806             }
2807         );
2808         is( int( $patron->account->balance() ),
2809             1, "Overdue fine of 1 day overdue" );
2810
2811         # Backdated return (dropbox mode example - charge should be removed)
2812         AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
2813         is( int( $patron->account->balance() ),
2814             0, "Overdue fine should be annulled" );
2815         my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2816         is( $lines->count, 0, "Overdue fine accountline has been removed");
2817
2818         $issue = AddIssue( $patron->unblessed, $item->barcode, $two_days_ago );    # date due was 2d ago
2819
2820         # Fake fines cronjob on this checkout
2821         ($fine) =
2822           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2823             $two_days_ago, $now );
2824         UpdateFine(
2825             {
2826                 issue_id       => $issue->issue_id,
2827                 itemnumber     => $item->itemnumber,
2828                 borrowernumber => $patron->borrowernumber,
2829                 amount         => $fine,
2830                 due            => output_pref($one_day_ago)
2831             }
2832         );
2833         is( int( $patron->account->balance() ),
2834             2, "Overdue fine of 2 days overdue" );
2835
2836         # Payment made against fine
2837         $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2838         my $debit = $lines->next;
2839         my $credit = $patron->account->add_credit(
2840             {
2841                 amount    => 2,
2842                 type      => 'PAYMENT',
2843                 interface => 'test',
2844             }
2845         );
2846         $credit->apply( { debits => [$debit] } );
2847
2848         is( int( $patron->account->balance() ),
2849             0, "Overdue fine should be paid off" );
2850         $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2851         is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
2852         my $line = $lines->next;
2853         is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
2854         is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
2855
2856         # Backdated return (dropbox mode example - charge should be removed)
2857         AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
2858         is( int( $patron->account->balance() ),
2859             -1, "Refund credit has been applied" );
2860         $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
2861         is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
2862
2863         $line = $lines->next;
2864         is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
2865         is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
2866         is($line->status,'RETURNED', "Overdue fine is fixed");
2867         $line = $lines->next;
2868         is($line->amount+0,-2, "Original payment amount remains as 2");
2869         is($line->amountoutstanding+0,0, "Original payment remains applied");
2870         $line = $lines->next;
2871         is($line->amount+0,-1, "Refund amount correctly set to 1");
2872         is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
2873
2874         # Cleanup
2875         Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2876     };
2877
2878     subtest 'bug 25417 | backdated return + exemptfine' => sub {
2879
2880         plan tests => 2;
2881
2882         t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2883
2884         my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago );    # date due was 1d ago
2885
2886         # Fake fines cronjob on this checkout
2887         my ($fine) =
2888           CalcFine( $item, $patron->categorycode, $library->{branchcode},
2889             $one_day_ago, $now );
2890         UpdateFine(
2891             {
2892                 issue_id       => $issue->issue_id,
2893                 itemnumber     => $item->itemnumber,
2894                 borrowernumber => $patron->borrowernumber,
2895                 amount         => $fine,
2896                 due            => output_pref($one_day_ago)
2897             }
2898         );
2899         is( int( $patron->account->balance() ),
2900             1, "Overdue fine of 1 day overdue" );
2901
2902         # Backdated return (dropbox mode example - charge should no longer exist)
2903         AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
2904         is( int( $patron->account->balance() ),
2905             0, "Overdue fine should be annulled" );
2906
2907         # Cleanup
2908         Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2909     };
2910
2911     subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
2912         plan tests => 7;
2913
2914         t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
2915
2916         my $due_date = dt_from_string;
2917         my $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
2918
2919         # Add fine
2920         UpdateFine(
2921             {
2922                 issue_id       => $issue->issue_id,
2923                 itemnumber     => $item->itemnumber,
2924                 borrowernumber => $patron->borrowernumber,
2925                 amount         => 0.25,
2926                 due            => output_pref($due_date)
2927             }
2928         );
2929         is( $patron->account->balance(),
2930             0.25, 'Overdue fine of $0.25 recorded' );
2931
2932         # Backdate return to exact due date and time
2933         my ( undef, $message ) =
2934           AddReturn( $item->barcode, $library->{branchcode},
2935             undef, $due_date );
2936
2937         my $accountline =
2938           Koha::Account::Lines->find( { issue_id => $issue->id } );
2939         ok( !$accountline, 'accountline removed as expected' );
2940
2941         # Re-issue
2942         $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
2943
2944         # Add fine
2945         UpdateFine(
2946             {
2947                 issue_id       => $issue->issue_id,
2948                 itemnumber     => $item->itemnumber,
2949                 borrowernumber => $patron->borrowernumber,
2950                 amount         => .25,
2951                 due            => output_pref($due_date)
2952             }
2953         );
2954         is( $patron->account->balance(),
2955             0.25, 'Overdue fine of $0.25 recorded' );
2956
2957         # Partial pay accruing fine
2958         my $lines = Koha::Account::Lines->search(
2959             {
2960                 borrowernumber => $patron->borrowernumber,
2961                 issue_id       => $issue->id
2962             }
2963         );
2964         my $debit  = $lines->next;
2965         my $credit = $patron->account->add_credit(
2966             {
2967                 amount    => .20,
2968                 type      => 'PAYMENT',
2969                 interface => 'test',
2970             }
2971         );
2972         $credit->apply( { debits => [$debit] } );
2973
2974         is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
2975
2976         # Backdate return to exact due date and time
2977         ( undef, $message ) =
2978           AddReturn( $item->barcode, $library->{branchcode},
2979             undef, $due_date );
2980
2981         $lines = Koha::Account::Lines->search(
2982             {
2983                 borrowernumber => $patron->borrowernumber,
2984                 issue_id       => $issue->id
2985             }
2986         );
2987         $accountline = $lines->next;
2988         is( $accountline->amountoutstanding + 0,
2989             0, 'Partially paid fee amount outstanding was reduced to 0' );
2990         is( $accountline->amount + 0,
2991             0, 'Partially paid fee amount was reduced to 0' );
2992         is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
2993
2994         # Cleanup
2995         Koha::Account::Lines->search(
2996             { borrowernumber => $patron->borrowernumber } )->delete;
2997     };
2998
2999     subtest 'enh 23091 | Lost item return policies' => sub {
3000         plan tests => 4;
3001
3002         my $manager = $builder->build_object({ class => "Koha::Patrons" });
3003
3004         my $branchcode_false =
3005           $builder->build( { source => 'Branch' } )->{branchcode};
3006         my $specific_rule_false = $builder->build(
3007             {
3008                 source => 'CirculationRule',
3009                 value  => {
3010                     branchcode   => $branchcode_false,
3011                     categorycode => undef,
3012                     itemtype     => undef,
3013                     rule_name    => 'lostreturn',
3014                     rule_value   => 0
3015                 }
3016             }
3017         );
3018         my $branchcode_refund =
3019           $builder->build( { source => 'Branch' } )->{branchcode};
3020         my $specific_rule_refund = $builder->build(
3021             {
3022                 source => 'CirculationRule',
3023                 value  => {
3024                     branchcode   => $branchcode_refund,
3025                     categorycode => undef,
3026                     itemtype     => undef,
3027                     rule_name    => 'lostreturn',
3028                     rule_value   => 'refund'
3029                 }
3030             }
3031         );
3032         my $branchcode_restore =
3033           $builder->build( { source => 'Branch' } )->{branchcode};
3034         my $specific_rule_restore = $builder->build(
3035             {
3036                 source => 'CirculationRule',
3037                 value  => {
3038                     branchcode   => $branchcode_restore,
3039                     categorycode => undef,
3040                     itemtype     => undef,
3041                     rule_name    => 'lostreturn',
3042                     rule_value   => 'restore'
3043                 }
3044             }
3045         );
3046         my $branchcode_charge =
3047           $builder->build( { source => 'Branch' } )->{branchcode};
3048         my $specific_rule_charge = $builder->build(
3049             {
3050                 source => 'CirculationRule',
3051                 value  => {
3052                     branchcode   => $branchcode_charge,
3053                     categorycode => undef,
3054                     itemtype     => undef,
3055                     rule_name    => 'lostreturn',
3056                     rule_value   => 'charge'
3057                 }
3058             }
3059         );
3060
3061         my $replacement_amount = 99.00;
3062         t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
3063         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
3064         t::lib::Mocks::mock_preference( 'WhenLostForgiveFine',          0 );
3065         t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems',       0 );
3066         t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
3067             'CheckinLibrary' );
3068         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
3069             undef );
3070
3071         subtest 'lostreturn | false' => sub {
3072             plan tests => 12;
3073
3074             t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
3075
3076             my $item = $builder->build_sample_item(
3077                 {
3078                     replacementprice => $replacement_amount
3079                 }
3080             );
3081
3082             # Issue the item
3083             my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3084
3085             # Fake fines cronjob on this checkout
3086             my ($fine) =
3087               CalcFine( $item, $patron->categorycode, $library->{branchcode},
3088                 $ten_days_ago, $now );
3089             UpdateFine(
3090                 {
3091                     issue_id       => $issue->issue_id,
3092                     itemnumber     => $item->itemnumber,
3093                     borrowernumber => $patron->borrowernumber,
3094                     amount         => $fine,
3095                     due            => output_pref($ten_days_ago)
3096                 }
3097             );
3098             my $overdue_fees = Koha::Account::Lines->search(
3099                 {
3100                     borrowernumber  => $patron->id,
3101                     itemnumber      => $item->itemnumber,
3102                     debit_type_code => 'OVERDUE'
3103                 }
3104             );
3105             is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3106             my $overdue_fee = $overdue_fees->next;
3107             is( $overdue_fee->amount + 0,
3108                 10, 'The right OVERDUE amount is generated' );
3109             is( $overdue_fee->amountoutstanding + 0,
3110                 10,
3111                 'The right OVERDUE amountoutstanding is generated' );
3112
3113             # Simulate item marked as lost
3114             $item->itemlost(3)->store;
3115             C4::Circulation::LostItem( $item->itemnumber, 1 );
3116
3117             my $lost_fee_lines = Koha::Account::Lines->search(
3118                 {
3119                     borrowernumber  => $patron->id,
3120                     itemnumber      => $item->itemnumber,
3121                     debit_type_code => 'LOST'
3122                 }
3123             );
3124             is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3125             my $lost_fee_line = $lost_fee_lines->next;
3126             is( $lost_fee_line->amount + 0,
3127                 $replacement_amount, 'The right LOST amount is generated' );
3128             is( $lost_fee_line->amountoutstanding + 0,
3129                 $replacement_amount,
3130                 'The right LOST amountoutstanding is generated' );
3131             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3132
3133             # Return lost item
3134             my ( $returned, $message ) =
3135               AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
3136
3137             $overdue_fee->discard_changes;
3138             is( $overdue_fee->amount + 0,
3139                 10, 'The OVERDUE amount is left intact' );
3140             is( $overdue_fee->amountoutstanding + 0,
3141                 10,
3142                 'The OVERDUE amountoutstanding is left intact' );
3143
3144             $lost_fee_line->discard_changes;
3145             is( $lost_fee_line->amount + 0,
3146                 $replacement_amount, 'The LOST amount is left intact' );
3147             is( $lost_fee_line->amountoutstanding + 0,
3148                 $replacement_amount,
3149                 'The LOST amountoutstanding is left intact' );
3150             # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
3151             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3152         };
3153
3154         subtest 'lostreturn | refund' => sub {
3155             plan tests => 12;
3156
3157             t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
3158
3159             my $item = $builder->build_sample_item(
3160                 {
3161                     replacementprice => $replacement_amount
3162                 }
3163             );
3164
3165             # Issue the item
3166             my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3167
3168             # Fake fines cronjob on this checkout
3169             my ($fine) =
3170               CalcFine( $item, $patron->categorycode, $library->{branchcode},
3171                 $ten_days_ago, $now );
3172             UpdateFine(
3173                 {
3174                     issue_id       => $issue->issue_id,
3175                     itemnumber     => $item->itemnumber,
3176                     borrowernumber => $patron->borrowernumber,
3177                     amount         => $fine,
3178                     due            => output_pref($ten_days_ago)
3179                 }
3180             );
3181             my $overdue_fees = Koha::Account::Lines->search(
3182                 {
3183                     borrowernumber  => $patron->id,
3184                     itemnumber      => $item->itemnumber,
3185                     debit_type_code => 'OVERDUE'
3186                 }
3187             );
3188             is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3189             my $overdue_fee = $overdue_fees->next;
3190             is( $overdue_fee->amount + 0,
3191                 10, 'The right OVERDUE amount is generated' );
3192             is( $overdue_fee->amountoutstanding + 0,
3193                 10,
3194                 'The right OVERDUE amountoutstanding is generated' );
3195
3196             # Simulate item marked as lost
3197             $item->itemlost(3)->store;
3198             C4::Circulation::LostItem( $item->itemnumber, 1 );
3199
3200             my $lost_fee_lines = Koha::Account::Lines->search(
3201                 {
3202                     borrowernumber  => $patron->id,
3203                     itemnumber      => $item->itemnumber,
3204                     debit_type_code => 'LOST'
3205                 }
3206             );
3207             is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3208             my $lost_fee_line = $lost_fee_lines->next;
3209             is( $lost_fee_line->amount + 0,
3210                 $replacement_amount, 'The right LOST amount is generated' );
3211             is( $lost_fee_line->amountoutstanding + 0,
3212                 $replacement_amount,
3213                 'The right LOST amountoutstanding is generated' );
3214             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3215
3216             # Return the lost item
3217             my ( undef, $message ) =
3218               AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
3219
3220             $overdue_fee->discard_changes;
3221             is( $overdue_fee->amount + 0,
3222                 10, 'The OVERDUE amount is left intact' );
3223             is( $overdue_fee->amountoutstanding + 0,
3224                 10,
3225                 'The OVERDUE amountoutstanding is left intact' );
3226
3227             $lost_fee_line->discard_changes;
3228             is( $lost_fee_line->amount + 0,
3229                 $replacement_amount, 'The LOST amount is left intact' );
3230             is( $lost_fee_line->amountoutstanding + 0,
3231                 0,
3232                 'The LOST amountoutstanding is refunded' );
3233             is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3234         };
3235
3236         subtest 'lostreturn | restore' => sub {
3237             plan tests => 13;
3238
3239             t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
3240
3241             my $item = $builder->build_sample_item(
3242                 {
3243                     replacementprice => $replacement_amount
3244                 }
3245             );
3246
3247             # Issue the item
3248             my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode , $ten_days_ago);
3249
3250             # Fake fines cronjob on this checkout
3251             my ($fine) =
3252               CalcFine( $item, $patron->categorycode, $library->{branchcode},
3253                 $ten_days_ago, $now );
3254             UpdateFine(
3255                 {
3256                     issue_id       => $issue->issue_id,
3257                     itemnumber     => $item->itemnumber,
3258                     borrowernumber => $patron->borrowernumber,
3259                     amount         => $fine,
3260                     due            => output_pref($ten_days_ago)
3261                 }
3262             );
3263             my $overdue_fees = Koha::Account::Lines->search(
3264                 {
3265                     borrowernumber  => $patron->id,
3266                     itemnumber      => $item->itemnumber,
3267                     debit_type_code => 'OVERDUE'
3268                 }
3269             );
3270             is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3271             my $overdue_fee = $overdue_fees->next;
3272             is( $overdue_fee->amount + 0,
3273                 10, 'The right OVERDUE amount is generated' );
3274             is( $overdue_fee->amountoutstanding + 0,
3275                 10,
3276                 'The right OVERDUE amountoutstanding is generated' );
3277
3278             # Simulate item marked as lost
3279             $item->itemlost(3)->store;
3280             C4::Circulation::LostItem( $item->itemnumber, 1 );
3281
3282             my $lost_fee_lines = Koha::Account::Lines->search(
3283                 {
3284                     borrowernumber  => $patron->id,
3285                     itemnumber      => $item->itemnumber,
3286                     debit_type_code => 'LOST'
3287                 }
3288             );
3289             is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3290             my $lost_fee_line = $lost_fee_lines->next;
3291             is( $lost_fee_line->amount + 0,
3292                 $replacement_amount, 'The right LOST amount is generated' );
3293             is( $lost_fee_line->amountoutstanding + 0,
3294                 $replacement_amount,
3295                 'The right LOST amountoutstanding is generated' );
3296             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3297
3298             # Simulate refunding overdue fees upon marking item as lost
3299             my $overdue_forgive = $patron->account->add_credit(
3300                 {
3301                     amount     => 10.00,
3302                     user_id    => $manager->borrowernumber,
3303                     library_id => $branchcode_restore,
3304                     interface  => 'test',
3305                     type       => 'FORGIVEN',
3306                     item_id    => $item->itemnumber
3307                 }
3308             );
3309             $overdue_forgive->apply( { debits => [$overdue_fee] } );
3310             $overdue_fee->discard_changes;
3311             is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3312
3313             # Do nothing
3314             my ( undef, $message ) =
3315               AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
3316
3317             $overdue_fee->discard_changes;
3318             is( $overdue_fee->amount + 0,
3319                 10, 'The OVERDUE amount is left intact' );
3320             is( $overdue_fee->amountoutstanding + 0,
3321                 10,
3322                 'The OVERDUE amountoutstanding is restored' );
3323
3324             $lost_fee_line->discard_changes;
3325             is( $lost_fee_line->amount + 0,
3326                 $replacement_amount, 'The LOST amount is left intact' );
3327             is( $lost_fee_line->amountoutstanding + 0,
3328                 0,
3329                 'The LOST amountoutstanding is refunded' );
3330             is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3331         };
3332
3333         subtest 'lostreturn | charge' => sub {
3334             plan tests => 16;
3335
3336             t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
3337
3338             my $item = $builder->build_sample_item(
3339                 {
3340                     replacementprice => $replacement_amount
3341                 }
3342             );
3343
3344             # Issue the item
3345             my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3346
3347             # Fake fines cronjob on this checkout
3348             my ($fine) =
3349               CalcFine( $item, $patron->categorycode, $library->{branchcode},
3350                 $ten_days_ago, $now );
3351             UpdateFine(
3352                 {
3353                     issue_id       => $issue->issue_id,
3354                     itemnumber     => $item->itemnumber,
3355                     borrowernumber => $patron->borrowernumber,
3356                     amount         => $fine,
3357                     due            => output_pref($ten_days_ago)
3358                 }
3359             );
3360             my $overdue_fees = Koha::Account::Lines->search(
3361                 {
3362                     borrowernumber  => $patron->id,
3363                     itemnumber      => $item->itemnumber,
3364                     debit_type_code => 'OVERDUE'
3365                 }
3366             );
3367             is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3368             my $overdue_fee = $overdue_fees->next;
3369             is( $overdue_fee->amount + 0,
3370                 10, 'The right OVERDUE amount is generated' );
3371             is( $overdue_fee->amountoutstanding + 0,
3372                 10,
3373                 'The right OVERDUE amountoutstanding is generated' );
3374
3375             # Simulate item marked as lost
3376             $item->itemlost(3)->store;
3377             C4::Circulation::LostItem( $item->itemnumber, 1 );
3378
3379             my $lost_fee_lines = Koha::Account::Lines->search(
3380                 {
3381                     borrowernumber  => $patron->id,
3382                     itemnumber      => $item->itemnumber,
3383                     debit_type_code => 'LOST'
3384                 }
3385             );
3386             is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3387             my $lost_fee_line = $lost_fee_lines->next;
3388             is( $lost_fee_line->amount + 0,
3389                 $replacement_amount, 'The right LOST amount is generated' );
3390             is( $lost_fee_line->amountoutstanding + 0,
3391                 $replacement_amount,
3392                 'The right LOST amountoutstanding is generated' );
3393             is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3394
3395             # Simulate refunding overdue fees upon marking item as lost
3396             my $overdue_forgive = $patron->account->add_credit(
3397                 {
3398                     amount     => 10.00,
3399                     user_id    => $manager->borrowernumber,
3400                     library_id => $branchcode_charge,
3401                     interface  => 'test',
3402                     type       => 'FORGIVEN',
3403                     item_id    => $item->itemnumber
3404                 }
3405             );
3406             $overdue_forgive->apply( { debits => [$overdue_fee] } );
3407             $overdue_fee->discard_changes;
3408             is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3409
3410             # Do nothing
3411             my ( undef, $message ) =
3412               AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
3413
3414             $lost_fee_line->discard_changes;
3415             is( $lost_fee_line->amount + 0,
3416                 $replacement_amount, 'The LOST amount is left intact' );
3417             is( $lost_fee_line->amountoutstanding + 0,
3418                 0,
3419                 'The LOST amountoutstanding is refunded' );
3420             is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3421
3422             $overdue_fees = Koha::Account::Lines->search(
3423                 {
3424                     borrowernumber  => $patron->id,
3425                     itemnumber      => $item->itemnumber,
3426                     debit_type_code => 'OVERDUE'
3427                 },
3428                 {
3429                     order_by => { '-asc' => 'accountlines_id'}
3430                 }
3431             );
3432             is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
3433             $overdue_fee = $overdue_fees->next;
3434             is( $overdue_fee->amount + 0,
3435                 10, 'The original OVERDUE amount is left intact' );
3436             is( $overdue_fee->amountoutstanding + 0,
3437                 0,
3438                 'The original OVERDUE amountoutstanding is left as forgiven' );
3439             $overdue_fee = $overdue_fees->next;
3440             is( $overdue_fee->amount + 0,
3441                 5, 'The new OVERDUE amount is correct for the backdated return' );
3442             is( $overdue_fee->amountoutstanding + 0,
3443                 5,
3444                 'The new OVERDUE amountoutstanding is correct for the backdated return' );
3445         };
3446     };
3447 };
3448
3449 subtest '_FixOverduesOnReturn' => sub {
3450     plan tests => 14;
3451
3452     my $manager = $builder->build_object({ class => "Koha::Patrons" });
3453     t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3454
3455     my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3456
3457     my $branchcode  = $library2->{branchcode};
3458
3459     my $item = $builder->build_sample_item(
3460         {
3461             biblionumber     => $biblio->biblionumber,
3462             library          => $branchcode,
3463             replacementprice => 99.00,
3464             itype            => $itemtype,
3465         }
3466     );
3467
3468     my $patron = $builder->build( { source => 'Borrower' } );
3469
3470     ## Start with basic call, should just close out the open fine
3471     my $accountline = Koha::Account::Line->new(
3472         {
3473             borrowernumber => $patron->{borrowernumber},
3474             debit_type_code    => 'OVERDUE',
3475             status         => 'UNRETURNED',
3476             itemnumber     => $item->itemnumber,
3477             amount => 99.00,
3478             amountoutstanding => 99.00,
3479             interface => 'test',
3480         }
3481     )->store();
3482
3483     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
3484
3485     $accountline->_result()->discard_changes();
3486
3487     is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
3488     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3489     is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3490
3491     ## Run again, with exemptfine enabled
3492     $accountline->set(
3493         {
3494             debit_type_code    => 'OVERDUE',
3495             status         => 'UNRETURNED',
3496             amountoutstanding => 99.00,
3497         }
3498     )->store();
3499
3500     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3501
3502     $accountline->_result()->discard_changes();
3503     my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'APPLY' })->next();
3504
3505     is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
3506     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3507     is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
3508     is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
3509     is( $offset->amount + 0, -99, "Amount of offset is correct" );
3510     my $credit = $offset->credit;
3511     is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
3512     is( $credit->amount + 0, -99, "Credit amount is set correctly" );
3513     is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
3514
3515     # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
3516     $accountline->set(
3517         {
3518             debit_type_code    => 'OVERDUE',
3519             status         => 'UNRETURNED',
3520             amountoutstanding => 0.00,
3521         }
3522     )->store();
3523     $offset->delete;
3524
3525     C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3526
3527     $accountline->_result()->discard_changes();
3528     $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'CREATE' })->next();
3529     is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
3530     isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3531     is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3532 };
3533
3534 subtest 'Set waiting flag' => sub {
3535     plan tests => 11;
3536
3537     my $library_1 = $builder->build( { source => 'Branch' } );
3538     my $patron_1  = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3539     my $library_2 = $builder->build( { source => 'Branch' } );
3540     my $patron_2  = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3541
3542     my $item = $builder->build_sample_item(
3543         {
3544             library      => $library_1->{branchcode},
3545         }
3546     );
3547
3548     set_userenv( $library_2 );
3549     my $reserve_id = AddReserve(
3550         {
3551             branchcode     => $library_2->{branchcode},
3552             borrowernumber => $patron_2->{borrowernumber},
3553             biblionumber   => $item->biblionumber,
3554             priority       => 1,
3555             itemnumber     => $item->itemnumber,
3556         }
3557     );
3558
3559     set_userenv( $library_1 );
3560     my $do_transfer = 1;
3561     my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3562     ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3563     my $hold = Koha::Holds->find( $reserve_id );
3564     is( $hold->found, 'T', 'Hold is in transit' );
3565
3566     my ( $status ) = CheckReserves($item->itemnumber);
3567     is( $status, 'Transferred', 'Hold is not waiting yet');
3568
3569     set_userenv( $library_2 );
3570     $do_transfer = 0;
3571     AddReturn( $item->barcode, $library_2->{branchcode} );
3572     ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3573     $hold = Koha::Holds->find( $reserve_id );
3574     is( $hold->found, 'W', 'Hold is waiting' );
3575     ( $status ) = CheckReserves($item->itemnumber);
3576     is( $status, 'Waiting', 'Now the hold is waiting');
3577
3578     #Bug 21944 - Waiting transfer checked in at branch other than pickup location
3579     set_userenv( $library_1 );
3580     (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
3581     $hold = Koha::Holds->find( $reserve_id );
3582     is( $hold->found, undef, 'Hold is no longer marked waiting' );
3583     is( $hold->priority, 1,  "Hold is now priority one again");
3584     is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
3585     is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
3586     is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
3587     is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
3588     is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
3589 };
3590
3591 subtest 'Cancel transfers on lost items' => sub {
3592     plan tests => 6;
3593
3594     my $library_to = $builder->build_object( { class => 'Koha::Libraries' } );
3595     my $item   = $builder->build_sample_item();
3596     my $holdingbranch = $item->holdingbranch;
3597     # Historic transfer (datearrived is defined)
3598     my $old_transfer = $builder->build_object(
3599         {
3600             class => 'Koha::Item::Transfers',
3601             value => {
3602                 itemnumber    => $item->itemnumber,
3603                 frombranch    => $holdingbranch,
3604                 tobranch      => $library_to->branchcode,
3605                 reason        => 'Manual',
3606                 datesent      => \'NOW()',
3607                 datearrived   => \'NOW()',
3608                 datecancelled => undef,
3609                 daterequested => \'NOW()'
3610             }
3611         }
3612     );
3613     # Queued transfer (datesent is undefined)
3614     my $transfer_1 = $builder->build_object(
3615         {
3616             class => 'Koha::Item::Transfers',
3617             value => {
3618                 itemnumber    => $item->itemnumber,
3619                 frombranch    => $holdingbranch,
3620                 tobranch      => $library_to->branchcode,
3621                 reason        => 'Manual',
3622                 datesent      => undef,
3623                 datearrived   => undef,
3624                 datecancelled => undef,
3625                 daterequested => \'NOW()'
3626             }
3627         }
3628     );
3629     # In transit transfer (datesent is defined, datearrived and datecancelled are both undefined)
3630     my $transfer_2 = $builder->build_object(
3631         {
3632             class => 'Koha::Item::Transfers',
3633             value => {
3634                 itemnumber    => $item->itemnumber,
3635                 frombranch    => $holdingbranch,
3636                 tobranch      => $library_to->branchcode,
3637                 reason        => 'Manual',
3638                 datesent      => \'NOW()',
3639                 datearrived   => undef,
3640                 datecancelled => undef,
3641                 daterequested => \'NOW()'
3642             }
3643         }
3644     );
3645
3646     # Simulate item being marked as lost
3647     $item->itemlost(1)->store;
3648     LostItem( $item->itemnumber, 'test', 1 );
3649
3650     $transfer_1->discard_changes;
3651     isnt($transfer_1->datecancelled, undef, "Queud transfer was cancelled upon item lost");
3652     is($transfer_1->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
3653     $transfer_2->discard_changes;
3654     isnt($transfer_2->datecancelled, undef, "Active transfer was cancelled upon item lost");
3655     is($transfer_2->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
3656     $old_transfer->discard_changes;
3657     is($old_transfer->datecancelled, undef, "Old transfers are unaffected");
3658     $item->discard_changes;
3659     is($item->holdingbranch, $holdingbranch, "Items holding branch remains unchanged");
3660 };
3661
3662 subtest 'CanBookBeIssued | is_overdue' => sub {
3663     plan tests => 3;
3664
3665     # Set a simple circ policy
3666     Koha::CirculationRules->set_rules(
3667         {
3668             categorycode => undef,
3669             branchcode   => undef,
3670             itemtype     => undef,
3671             rules        => {
3672                 maxissueqty     => 1,
3673                 reservesallowed => 25,
3674                 issuelength     => 14,
3675                 lengthunit      => 'days',
3676                 renewalsallowed => 1,
3677                 renewalperiod   => 7,
3678                 norenewalbefore => undef,
3679                 auto_renew      => 0,
3680                 fine            => .10,
3681                 chargeperiod    => 1,
3682             }
3683         }
3684     );
3685
3686     my $now   = dt_from_string;
3687     my $five_days_go = output_pref({ dt => $now->clone->add( days => 5 ), dateonly => 1});
3688     my $ten_days_go  = output_pref({ dt => $now->clone->add( days => 10), dateonly => 1 });
3689     my $library = $builder->build( { source => 'Branch' } );
3690     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
3691
3692     my $item = $builder->build_sample_item(
3693         {
3694             library      => $library->{branchcode},
3695         }
3696     );
3697
3698     my $issue = AddIssue( $patron->unblessed, $item->barcode, $five_days_go ); # date due was 10d ago
3699     my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
3700     is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
3701     my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->barcode,$ten_days_go, undef, undef, undef);
3702     is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
3703     is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
3704 };
3705
3706 subtest 'ItemsDeniedRenewal preference' => sub {
3707     plan tests => 18;
3708
3709     C4::Context->set_preference('ItemsDeniedRenewal','');
3710
3711     my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
3712     Koha::CirculationRules->set_rules(
3713         {
3714             categorycode => '*',
3715             itemtype     => '*',
3716             branchcode   => $idr_lib->branchcode,
3717             rules        => {
3718                 reservesallowed => 25,
3719                 issuelength     => 14,
3720                 lengthunit      => 'days',
3721                 renewalsallowed => 10,
3722                 renewalperiod   => 7,
3723                 norenewalbefore => undef,
3724                 auto_renew      => 0,
3725                 fine            => .10,
3726                 chargeperiod    => 1,
3727             }
3728         }
3729     );
3730
3731     my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
3732         homebranch => $idr_lib->branchcode,
3733         withdrawn => 1,
3734         itype => 'HIDE',
3735         location => 'PROC',
3736         itemcallnumber => undef,
3737         itemnotes => "",
3738         }
3739     });
3740     my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
3741         homebranch => $idr_lib->branchcode,
3742         withdrawn => 0,
3743         itype => 'NOHIDE',
3744         location => 'NOPROC'
3745         }
3746     });
3747
3748     my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
3749         branchcode => $idr_lib->branchcode,
3750         }
3751     });
3752     my $future = dt_from_string->add( days => 1 );
3753     my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3754         returndate => undef,
3755         renewals => 0,
3756         auto_renew => 0,
3757         borrowernumber => $idr_borrower->borrowernumber,
3758         itemnumber => $deny_book->itemnumber,
3759         onsite_checkout => 0,
3760         date_due => $future,
3761         }
3762     });
3763     my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3764         returndate => undef,
3765         renewals => 0,
3766         auto_renew => 0,
3767         borrowernumber => $idr_borrower->borrowernumber,
3768         itemnumber => $allow_book->itemnumber,
3769         onsite_checkout => 0,
3770         date_due => $future,
3771         }
3772     });
3773
3774     my $idr_rules;
3775
3776     my ( $idr_mayrenew, $idr_error ) =
3777     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3778     is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3779     is( $idr_error, undef, 'Renewal allowed when no rules' );
3780
3781     $idr_rules="withdrawn: [1]";
3782
3783     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3784     ( $idr_mayrenew, $idr_error ) =
3785     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3786     is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3787     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3788     ( $idr_mayrenew, $idr_error ) =
3789     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3790     is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3791     is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3792
3793     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
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 2 rules matched (withdrawn, itype)' );
3799     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
3800     ( $idr_mayrenew, $idr_error ) =
3801     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3802     is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3803     is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3804
3805     $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
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 3 rules matched (withdrawn, itype, location)' );
3811     is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
3812     ( $idr_mayrenew, $idr_error ) =
3813     CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3814     is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3815     is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3816
3817     $idr_rules="itemcallnumber: [NULL]";
3818     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3819     ( $idr_mayrenew, $idr_error ) =
3820     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3821     is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
3822     $idr_rules="itemcallnumber: ['']";
3823     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3824     ( $idr_mayrenew, $idr_error ) =
3825     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3826     is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
3827
3828     $idr_rules="itemnotes: [NULL]";
3829     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3830     ( $idr_mayrenew, $idr_error ) =
3831     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3832     is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
3833     $idr_rules="itemnotes: ['']";
3834     C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3835     ( $idr_mayrenew, $idr_error ) =
3836     CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3837     is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
3838 };
3839
3840 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
3841     plan tests => 2;
3842
3843     t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3844     my $library = $builder->build( { source => 'Branch' } );
3845     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3846
3847     my $item = $builder->build_sample_item(
3848         {
3849             library      => $library->{branchcode},
3850         }
3851     );
3852
3853     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3854     is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3855     is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3856 };
3857
3858 subtest 'CanBookBeIssued | notforloan' => sub {
3859     plan tests => 2;
3860
3861     t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
3862
3863     my $library = $builder->build( { source => 'Branch' } );
3864     my $patron  = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3865
3866     my $itemtype = $builder->build(
3867         {
3868             source => 'Itemtype',
3869             value  => { notforloan => undef, }
3870         }
3871     );
3872     my $item = $builder->build_sample_item(
3873         {
3874             library  => $library->{branchcode},
3875             itype    => $itemtype->{itemtype},
3876         }
3877     );
3878     $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3879
3880     my ( $issuingimpossible, $needsconfirmation );
3881
3882
3883     subtest 'item-level_itypes = 1' => sub {
3884         plan tests => 6;
3885
3886         t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
3887         # Is for loan at item type and item level
3888         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3889         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3890         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3891
3892         # not for loan at item type level
3893         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3894         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3895         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3896         is_deeply(
3897             $issuingimpossible,
3898             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3899             'Item can not be issued, not for loan at item type level'
3900         );
3901
3902         # not for loan at item level
3903         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3904         $item->notforloan( 1 )->store;
3905         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3906         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3907         is_deeply(
3908             $issuingimpossible,
3909             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3910             'Item can not be issued, not for loan at item type level'
3911         );
3912     };
3913
3914     subtest 'item-level_itypes = 0' => sub {
3915         plan tests => 6;
3916
3917         t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3918
3919         # We set another itemtype for biblioitem
3920         my $itemtype = $builder->build(
3921             {
3922                 source => 'Itemtype',
3923                 value  => { notforloan => undef, }
3924             }
3925         );
3926
3927         # for loan at item type and item level
3928         $item->notforloan(0)->store;
3929         $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3930         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3931         is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3932         is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3933
3934         # not for loan at item type level
3935         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3936         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3937         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3938         is_deeply(
3939             $issuingimpossible,
3940             { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3941             'Item can not be issued, not for loan at item type level'
3942         );
3943
3944         # not for loan at item level
3945         Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3946         $item->notforloan( 1 )->store;
3947         ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3948         is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3949         is_deeply(
3950             $issuingimpossible,
3951             { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3952             'Item can not be issued, not for loan at item type level'
3953         );
3954     };
3955
3956     # TODO test with AllowNotForLoanOverride = 1
3957 };
3958
3959 subtest 'CanBookBeIssued | recalls' => sub {
3960     plan tests => 3;
3961
3962     t::lib::Mocks::mock_preference("UseRecalls", 1);
3963     t::lib::Mocks::mock_preference("item-level_itypes", 1);
3964     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
3965     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
3966     my $item = $builder->build_sample_item;
3967     Koha::CirculationRules->set_rules({
3968         branchcode => undef,
3969         itemtype => undef,
3970         categorycode => undef,
3971         rules => {
3972             recalls_allowed => 10,
3973         },
3974     });
3975
3976     # item-level recall
3977     my $recall = Koha::Recall->new(
3978         {   borrowernumber    => $patron1->borrowernumber,
3979             biblionumber      => $item->biblionumber,
3980             itemnumber        => $item->itemnumber,
3981             item_level_recall => 1,
3982             branchcode        => $patron1->branchcode,
3983         }
3984     )->store;
3985
3986     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
3987     is( $needsconfirmation->{RECALLED}->recall_id, $recall->recall_id, "Another patron has placed an item-level recall on this item" );
3988
3989     $recall->set_cancelled;
3990
3991     # biblio-level recall
3992     $recall = Koha::Recall->new(
3993         {   borrowernumber    => $patron1->borrowernumber,
3994             biblionumber      => $item->biblionumber,
3995             itemnumber        => undef,
3996             item_level_recall => 0,
3997             branchcode        => $patron1->branchcode,
3998         }
3999     )->store;
4000
4001     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4002     is( $needsconfirmation->{RECALLED}->recall_id, $recall->recall_id, "Another patron has placed a biblio-level recall and this item is eligible to fill it" );
4003
4004     $recall->set_cancelled;
4005
4006     # biblio-level recall
4007     $recall = Koha::Recall->new(
4008         {   borrowernumber    => $patron1->borrowernumber,
4009             biblionumber      => $item->biblionumber,
4010             itemnumber        => undef,
4011             item_level_recall => 0,
4012             branchcode        => $patron1->branchcode,
4013         }
4014     )->store;
4015     $recall->set_waiting( { item => $item, expirationdate => dt_from_string() } );
4016
4017     my ( undef, undef, undef, $messages ) = CanBookBeIssued( $patron1, $item->barcode, undef, undef, undef, undef );
4018     is( $messages->{RECALLED}, $recall->recall_id, "This book can be issued by this patron and they have placed a recall" );
4019
4020     $recall->set_cancelled;
4021 };
4022
4023 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
4024     plan tests => 1;
4025
4026     t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
4027     my $item = $builder->build_sample_item(
4028         {
4029             onloan => '2018-01-01',
4030         }
4031     );
4032
4033     AddReturn( $item->barcode, $item->homebranch );
4034     $item->discard_changes; # refresh
4035     is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
4036 };
4037
4038 subtest 'AddReturn | recalls' => sub {
4039     plan tests => 3;
4040
4041     t::lib::Mocks::mock_preference("UseRecalls", 1);
4042     t::lib::Mocks::mock_preference("item-level_itypes", 1);
4043     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4044     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4045     my $item1 = $builder->build_sample_item;
4046     Koha::CirculationRules->set_rules({
4047         branchcode => undef,
4048         itemtype => undef,
4049         categorycode => undef,
4050         rules => {
4051             recalls_allowed => 10,
4052         },
4053     });
4054
4055     # this item can fill a recall with pickup at this branch
4056     AddIssue( $patron1->unblessed, $item1->barcode );
4057     my $recall1 = Koha::Recall->new(
4058         {   borrowernumber    => $patron2->borrowernumber,
4059             biblionumber      => $item1->biblionumber,
4060             itemnumber        => $item1->itemnumber,
4061             item_level_recall => 1,
4062             branchcode        => $item1->homebranch,
4063         }
4064     )->store;
4065     my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4066     is( $messages->{RecallFound}->recall_id, $recall1->recall_id, "Recall found" );
4067     $recall1->set_cancelled;
4068
4069     # this item can fill a recall but needs transfer
4070     AddIssue( $patron1->unblessed, $item1->barcode );
4071     $recall1 = Koha::Recall->new(
4072         {   borrowernumber    => $patron2->borrowernumber,
4073             biblionumber      => $item1->biblionumber,
4074             itemnumber        => $item1->itemnumber,
4075             item_level_recall => 1,
4076             branchcode        => $patron2->branchcode,
4077         }
4078     )->store;
4079     ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4080     is( $messages->{RecallNeedsTransfer}, $item1->homebranch, "Recall requiring transfer found" );
4081     $recall1->set_cancelled;
4082
4083     # this item is already in transit, do not ask to transfer
4084     AddIssue( $patron1->unblessed, $item1->barcode );
4085     $recall1 = Koha::Recall->new(
4086         {   borrowernumber    => $patron2->borrowernumber,
4087             biblionumber      => $item1->biblionumber,
4088             itemnumber        => $item1->itemnumber,
4089             item_level_recall => 1,
4090             branchcode        => $patron2->branchcode,
4091         }
4092     )->store;
4093     $recall1->start_transfer;
4094     ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $patron2->branchcode );
4095     is( $messages->{TransferredRecall}->recall_id, $recall1->recall_id, "In transit recall found" );
4096     $recall1->set_cancelled;
4097 };
4098
4099 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
4100
4101     plan tests => 13;
4102
4103
4104     t::lib::Mocks::mock_preference('item-level_itypes', 1);
4105
4106     my $issuing_charges = 15;
4107     my $title   = 'A title';
4108     my $author  = 'Author, An';
4109     my $barcode = 'WHATARETHEODDS';
4110
4111     my $circ = Test::MockModule->new('C4::Circulation');
4112     $circ->mock(
4113         'GetIssuingCharges',
4114         sub {
4115             return $issuing_charges;
4116         }
4117     );
4118
4119     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
4120     my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
4121     my $patron   = $builder->build_object({
4122         class => 'Koha::Patrons',
4123         value => { branchcode => $library->id }
4124     });
4125
4126     my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
4127     my $item_id = Koha::Item->new(
4128         {
4129             biblionumber     => $biblio->biblionumber,
4130             homebranch       => $library->id,
4131             holdingbranch    => $library->id,
4132             barcode          => $barcode,
4133             replacementprice => 23.00,
4134             itype            => $itemtype->id
4135         },
4136     )->store->itemnumber;
4137     my $item = Koha::Items->find( $item_id );
4138
4139     my $context = Test::MockModule->new('C4::Context');
4140     $context->mock( userenv => { branch => $library->id } );
4141
4142     # Check the item out
4143     AddIssue( $patron->unblessed, $item->barcode );
4144
4145     throws_ok {
4146         AddRenewal( $patron->borrowernumber, $item->itemnumber, $library->id, undef, {break=>"the_renewal"} );
4147     } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
4148
4149     t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
4150     my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
4151     my %params_renewal = (
4152         timestamp => { -like => $date . "%" },
4153         module => "CIRCULATION",
4154         action => "RENEWAL",
4155     );
4156     my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
4157     AddRenewal( $patron->id, $item->id, $library->id );
4158     my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4159     is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
4160
4161     my $checkouts = $patron->checkouts;
4162     # The following will fail if run on 00:00:00
4163     unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
4164
4165     my $lines = Koha::Account::Lines->search({
4166         borrowernumber => $patron->id,
4167         itemnumber     => $item->id
4168     });
4169
4170     is( $lines->count, 2 );
4171
4172     my $line = $lines->next;
4173     is( $line->debit_type_code, 'RENT',       'The issue of item with issuing charge generates an accountline of the correct type' );
4174     is( $line->branchcode,  $library->id, 'AddIssuingCharge correctly sets branchcode' );
4175     is( $line->description, '',     'AddIssue does not set a hardcoded description for the accountline' );
4176
4177     $line = $lines->next;
4178     is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
4179     is( $line->branchcode,  $library->id, 'AddRenewal correctly sets branchcode' );
4180     is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
4181
4182     t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
4183
4184     $context = Test::MockModule->new('C4::Context');
4185     $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
4186
4187     my $now = dt_from_string;
4188     $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
4189     $old_log_size = Koha::ActionLogs->count( \%params_renewal );
4190     my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
4191     $sth->execute($item->id, $library->id);
4192     my ($old_stats_size) = $sth->fetchrow_array;
4193     AddRenewal( $patron->id, $item->id, $library->id );
4194     $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4195     $sth->execute($item->id, $library->id);
4196     my ($new_stats_size) = $sth->fetchrow_array;
4197     is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
4198     is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
4199
4200     AddReturn( $item->id, $library->id, undef, $date );
4201     AddIssue( $patron->unblessed, $item->barcode, $now );
4202     AddRenewal( $patron->id, $item->id, $library->id, undef, undef, 1 );
4203     my $lines_skipped = Koha::Account::Lines->search({
4204         borrowernumber => $patron->id,
4205         itemnumber     => $item->id
4206     });
4207     is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
4208
4209 };
4210
4211 subtest 'ProcessOfflinePayment() tests' => sub {
4212
4213     plan tests => 4;
4214
4215
4216     my $amount = 123;
4217
4218     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
4219     my $library = $builder->build_object({ class => 'Koha::Libraries' });
4220     my $result  = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
4221
4222     is( $result, 'Success.', 'The right string is returned' );
4223
4224     my $lines = $patron->account->lines;
4225     is( $lines->count, 1, 'line created correctly');
4226
4227     my $line = $lines->next;
4228     is( $line->amount+0, $amount * -1, 'amount picked from params' );
4229     is( $line->branchcode, $library->id, 'branchcode set correctly' );
4230
4231 };
4232
4233 subtest 'Incremented fee tests' => sub {
4234     plan tests => 19;
4235
4236     my $dt = dt_from_string();
4237     Time::Fake->offset( $dt->epoch );
4238
4239     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
4240
4241     my $library =
4242       $builder->build_object( { class => 'Koha::Libraries' } )->store;
4243
4244     $module->mock( 'userenv', sub { { branch => $library->id } } );
4245
4246     my $patron = $builder->build_object(
4247         {
4248             class => 'Koha::Patrons',
4249             value => { categorycode => $patron_category->{categorycode} }
4250         }
4251     )->store;
4252
4253     my $itemtype = $builder->build_object(
4254         {
4255             class => 'Koha::ItemTypes',
4256             value => {
4257                 notforloan                   => undef,
4258                 rentalcharge                 => 0,
4259                 rentalcharge_daily           => 1,
4260                 rentalcharge_daily_calendar  => 0
4261             }
4262         }
4263     )->store;
4264
4265     my $item = $builder->build_sample_item(
4266         {
4267             library  => $library->{branchcode},
4268             itype    => $itemtype->id,
4269         }
4270     );
4271
4272     is( $itemtype->rentalcharge_daily+0,
4273         1, 'Daily rental charge stored and retreived correctly' );
4274     is( $item->effective_itemtype, $itemtype->id,
4275         "Itemtype set correctly for item" );
4276
4277     my $now         = dt_from_string;
4278     my $dt_from     = $now->clone;
4279     my $dt_to       = $now->clone->add( days => 7 );
4280     my $dt_to_renew = $now->clone->add( days => 13 );
4281
4282     # Daily Tests
4283     my $issue =
4284       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4285     my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4286     is( $accountline->amount+0, 7,
4287 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
4288     );
4289     $accountline->delete();
4290     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4291     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4292     is( $accountline->amount+0, 6,
4293 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
4294     );
4295     $accountline->delete();
4296     $issue->delete();
4297
4298     t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
4299     $itemtype->rentalcharge_daily_calendar(1)->store();
4300     $issue =
4301       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4302     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4303     is( $accountline->amount+0, 7,
4304 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
4305     );
4306     $accountline->delete();
4307     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4308     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4309     is( $accountline->amount+0, 6,
4310 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
4311     );
4312     $accountline->delete();
4313     $issue->delete();
4314
4315     my $calendar = C4::Calendar->new( branchcode => $library->id );
4316     # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
4317     my $closed_day =
4318         ( $dt_from->day_of_week == 6 ) ? 0
4319       : ( $dt_from->day_of_week == 7 ) ? 1
4320       :                                  $dt_from->day_of_week + 1;
4321     my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
4322     $calendar->insert_week_day_holiday(
4323         weekday     => $closed_day,
4324         title       => 'Test holiday',
4325         description => 'Test holiday'
4326     );
4327     $issue =
4328       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4329     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4330     is( $accountline->amount+0, 6,
4331 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
4332     );
4333     $accountline->delete();
4334     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4335     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4336     is( $accountline->amount+0, 5,
4337 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
4338     );
4339     $accountline->delete();
4340     $issue->delete();
4341
4342     $itemtype->rentalcharge(2)->store;
4343     is( $itemtype->rentalcharge+0, 2,
4344         'Rental charge updated and retreived correctly' );
4345     $issue =
4346       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4347     my $accountlines =
4348       Koha::Account::Lines->search( { itemnumber => $item->id } );
4349     is( $accountlines->count, '2',
4350         "Fixed charge and accrued charge recorded distinctly" );
4351     $accountlines->delete();
4352     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4353     $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
4354     is( $accountlines->count, '2',
4355         "Fixed charge and accrued charge recorded distinctly, for renewal" );
4356     $accountlines->delete();
4357     $issue->delete();
4358     $itemtype->rentalcharge(0)->store;
4359     is( $itemtype->rentalcharge+0, 0,
4360         'Rental charge reset and retreived correctly' );
4361
4362     # Hourly
4363     Koha::CirculationRules->set_rule(
4364         {
4365             categorycode => $patron->categorycode,
4366             itemtype     => $itemtype->id,
4367             branchcode   => $library->id,
4368             rule_name    => 'lengthunit',
4369             rule_value   => 'hours',
4370         }
4371     );
4372
4373     $itemtype->rentalcharge_hourly('0.25')->store();
4374     is( $itemtype->rentalcharge_hourly,
4375         '0.25', 'Hourly rental charge stored and retreived correctly' );
4376
4377     $dt_to       = $now->clone->add( hours => 168 );
4378     $dt_to_renew = $now->clone->add( hours => 312 );
4379
4380     $itemtype->rentalcharge_hourly_calendar(0)->store();
4381     $issue =
4382       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4383     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4384     is( $accountline->amount + 0, 42,
4385         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)" );
4386     $accountline->delete();
4387     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4388     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4389     is( $accountline->amount + 0, 36,
4390         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)" );
4391     $accountline->delete();
4392     $issue->delete();
4393
4394     $itemtype->rentalcharge_hourly_calendar(1)->store();
4395     $issue =
4396       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4397     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4398     is( $accountline->amount + 0, 36,
4399         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)" );
4400     $accountline->delete();
4401     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4402     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4403     is( $accountline->amount + 0, 30,
4404         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
4405     $accountline->delete();
4406     $issue->delete();
4407
4408     $calendar->delete_holiday( weekday => $closed_day );
4409     $issue =
4410       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4411     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4412     is( $accountline->amount + 0, 42,
4413         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u" );
4414     $accountline->delete();
4415     AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4416     $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4417     is( $accountline->amount + 0, 36,
4418         "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)" );
4419     $accountline->delete();
4420     $issue->delete();
4421     Time::Fake->reset;
4422 };
4423
4424 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
4425     plan tests => 2;
4426
4427     t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
4428     t::lib::Mocks::mock_preference('item-level_itypes', 1);
4429
4430     my $library =
4431       $builder->build_object( { class => 'Koha::Libraries' } )->store;
4432     my $patron = $builder->build_object(
4433         {
4434             class => 'Koha::Patrons',
4435             value => { categorycode => $patron_category->{categorycode} }
4436         }
4437     )->store;
4438
4439     my $itemtype = $builder->build_object(
4440         {
4441             class => 'Koha::ItemTypes',
4442             value => {
4443                 notforloan             => 0,
4444                 rentalcharge           => 0,
4445                 rentalcharge_daily => 0
4446             }
4447         }
4448     );
4449
4450     my $item = $builder->build_sample_item(
4451         {
4452             library    => $library->id,
4453             notforloan => 0,
4454             itemlost   => 0,
4455             withdrawn  => 0,
4456             itype      => $itemtype->id,
4457         }
4458     )->store;
4459
4460     my ( $issuingimpossible, $needsconfirmation );
4461     my $dt_from = dt_from_string();
4462     my $dt_due = $dt_from->clone->add( days => 3 );
4463
4464     $itemtype->rentalcharge(1)->store;
4465     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4466     is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
4467     $itemtype->rentalcharge('0')->store;
4468     $itemtype->rentalcharge_daily(1)->store;
4469     ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4470     is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
4471     $itemtype->rentalcharge_daily('0')->store;
4472 };
4473
4474 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
4475     plan tests => 1;
4476
4477     t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
4478
4479     my $patron = $builder->build_object(
4480         {
4481             class => 'Koha::Patrons',
4482             value => { categorycode => $patron_category->{categorycode} }
4483         }
4484     )->store;
4485
4486     my $item = $builder->build_sample_item(
4487         {
4488             materials => 'includes DVD',
4489         }
4490     )->store;
4491
4492     my $dt_due = dt_from_string->add( days => 3 );
4493
4494     my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4495     is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
4496 };
4497
4498 subtest 'Do not return on renewal (LOST charge)' => sub {
4499     plan tests => 1;
4500
4501     t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
4502     my $library = $builder->build_object( { class => "Koha::Libraries" } );
4503     my $manager = $builder->build_object( { class => "Koha::Patrons" } );
4504     t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
4505
4506     my $biblio = $builder->build_sample_biblio;
4507
4508     my $item = $builder->build_sample_item(
4509         {
4510             biblionumber     => $biblio->biblionumber,
4511             library          => $library->branchcode,
4512             replacementprice => 99.00,
4513             itype            => $itemtype,
4514         }
4515     );
4516
4517     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
4518     AddIssue( $patron->unblessed, $item->barcode );
4519
4520     my $accountline = Koha::Account::Line->new(
4521         {
4522             borrowernumber    => $patron->borrowernumber,
4523             debit_type_code   => 'LOST',
4524             status            => undef,
4525             itemnumber        => $item->itemnumber,
4526             amount            => 12,
4527             amountoutstanding => 12,
4528             interface         => 'something',
4529         }
4530     )->store();
4531
4532     # AddRenewal doesn't call _FixAccountForLostAndFound
4533     AddIssue( $patron->unblessed, $item->barcode );
4534
4535     is( $patron->checkouts->count, 1,
4536         'Renewal should not return the item even if a LOST payment has been made earlier'
4537     );
4538 };
4539
4540 subtest 'Filling a hold should cancel existing transfer' => sub {
4541     plan tests => 4;
4542
4543     t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
4544
4545     my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
4546     my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
4547     my $patron = $builder->build_object(
4548         {
4549             class => 'Koha::Patrons',
4550             value => {
4551                 categorycode => $patron_category->{categorycode},
4552                 branchcode => $libraryA->branchcode,
4553             }
4554         }
4555     )->store;
4556
4557     my $item = $builder->build_sample_item({
4558         homebranch => $libraryB->branchcode,
4559     });
4560
4561     my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4562     is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
4563     AddReserve({
4564         branchcode     => $libraryA->branchcode,
4565         borrowernumber => $patron->borrowernumber,
4566         biblionumber   => $item->biblionumber,
4567         itemnumber     => $item->itemnumber
4568     });
4569     my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
4570     is( $reserves->count, 1, "Reserve is placed");
4571     ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4572     my $reserve = $reserves->next;
4573     ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
4574     $reserve->discard_changes;
4575     ok( $reserve->found eq 'W', "Reserve is marked waiting" );
4576     is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
4577 };
4578
4579 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
4580
4581     plan tests => 4;
4582
4583     t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4584     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4585     my $patron  = $builder->build_object(
4586         {
4587             class => 'Koha::Patrons',
4588             value => { categorycode => $patron_category->{categorycode} }
4589         }
4590     );
4591
4592     my $biblionumber = $builder->build_sample_biblio(
4593         {
4594             branchcode => $library->branchcode,
4595         }
4596     )->biblionumber;
4597
4598     # And the circulation rule
4599     Koha::CirculationRules->search->delete;
4600     Koha::CirculationRules->set_rules(
4601         {
4602             categorycode => undef,
4603             itemtype     => undef,
4604             branchcode   => undef,
4605             rules        => {
4606                 issuelength => 14,
4607                 lengthunit  => 'days',
4608             }
4609         }
4610     );
4611     $builder->build(
4612         {
4613             source => 'CirculationRule',
4614             value  => {
4615                 branchcode   => undef,
4616                 categorycode => undef,
4617                 itemtype     => undef,
4618                 rule_name    => 'lostreturn',
4619                 rule_value   => 'refund'
4620             }
4621         }
4622     );
4623
4624     subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4625         plan tests => 3;
4626
4627         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4628         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4629
4630         my $lost_on = dt_from_string->subtract( days => 7 )->date;
4631
4632         my $item = $builder->build_sample_item(
4633             {
4634                 biblionumber     => $biblionumber,
4635                 library          => $library->branchcode,
4636                 replacementprice => '42',
4637             }
4638         );
4639         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4640         LostItem( $item->itemnumber, 'cli', 0 );
4641         $item->_result->itemlost(1);
4642         $item->_result->itemlost_on( $lost_on );
4643         $item->_result->update();
4644
4645         my $a = Koha::Account::Lines->search(
4646             {
4647                 itemnumber     => $item->id,
4648                 borrowernumber => $patron->borrowernumber
4649             }
4650         )->next;
4651         ok( $a, "Found accountline for lost fee" );
4652         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4653         my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4654         $a = $a->get_from_storage;
4655         is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4656         $a->delete;
4657     };
4658
4659     subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4660         plan tests => 3;
4661
4662         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4663         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4664
4665         my $lost_on = dt_from_string->subtract( days => 6 )->date;
4666
4667         my $item = $builder->build_sample_item(
4668             {
4669                 biblionumber     => $biblionumber,
4670                 library          => $library->branchcode,
4671                 replacementprice => '42',
4672             }
4673         );
4674         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4675         LostItem( $item->itemnumber, 'cli', 0 );
4676         $item->_result->itemlost(1);
4677         $item->_result->itemlost_on( $lost_on );
4678         $item->_result->update();
4679
4680         my $a = Koha::Account::Lines->search(
4681             {
4682                 itemnumber     => $item->id,
4683                 borrowernumber => $patron->borrowernumber
4684             }
4685         )->next;
4686         ok( $a, "Found accountline for lost fee" );
4687         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4688         my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4689         $a = $a->get_from_storage;
4690         is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4691         $a->delete;
4692     };
4693
4694     subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4695         plan tests => 3;
4696
4697         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4698         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4699
4700         my $lost_on = dt_from_string->subtract( days => 7 )->date;
4701
4702         my $item = $builder->build_sample_item(
4703             {
4704                 biblionumber     => $biblionumber,
4705                 library          => $library->branchcode,
4706                 replacementprice => '42',
4707             }
4708         );
4709         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4710         LostItem( $item->itemnumber, 'cli', 0 );
4711         $item->_result->itemlost(1);
4712         $item->_result->itemlost_on( $lost_on );
4713         $item->_result->update();
4714
4715         my $a = Koha::Account::Lines->search(
4716             {
4717                 itemnumber     => $item->id,
4718                 borrowernumber => $patron->borrowernumber
4719             }
4720         )->next;
4721         ok( $a, "Found accountline for lost fee" );
4722         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4723         my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4724         $a = $a->get_from_storage;
4725         is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4726         $a->delete;
4727     };
4728
4729     subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4730         plan tests => 3;
4731
4732         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4733         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4734
4735         my $lost_on = dt_from_string->subtract( days => 8 )->date;
4736
4737         my $item = $builder->build_sample_item(
4738             {
4739                 biblionumber     => $biblionumber,
4740                 library          => $library->branchcode,
4741                 replacementprice => '42',
4742             }
4743         );
4744         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4745         LostItem( $item->itemnumber, 'cli', 0 );
4746         $item->_result->itemlost(1);
4747         $item->_result->itemlost_on( $lost_on );
4748         $item->_result->update();
4749
4750         my $a = Koha::Account::Lines->search(
4751             {
4752                 itemnumber     => $item->id,
4753                 borrowernumber => $patron->borrowernumber
4754             }
4755         );
4756         $a = $a->next;
4757         ok( $a, "Found accountline for lost fee" );
4758         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4759         my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4760         $a = $a->get_from_storage;
4761         is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4762         $a->delete;
4763     };
4764 };
4765
4766 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
4767
4768     plan tests => 4;
4769
4770     t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4771     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4772     my $patron  = $builder->build_object(
4773         {
4774             class => 'Koha::Patrons',
4775             value => { categorycode => $patron_category->{categorycode} }
4776         }
4777     );
4778     my $patron2  = $builder->build_object(
4779         {
4780             class => 'Koha::Patrons',
4781             value => { categorycode => $patron_category->{categorycode} }
4782         }
4783     );
4784
4785     my $biblionumber = $builder->build_sample_biblio(
4786         {
4787             branchcode => $library->branchcode,
4788         }
4789     )->biblionumber;
4790
4791     # And the circulation rule
4792     Koha::CirculationRules->search->delete;
4793     Koha::CirculationRules->set_rules(
4794         {
4795             categorycode => undef,
4796             itemtype     => undef,
4797             branchcode   => undef,
4798             rules        => {
4799                 issuelength => 14,
4800                 lengthunit  => 'days',
4801             }
4802         }
4803     );
4804     $builder->build(
4805         {
4806             source => 'CirculationRule',
4807             value  => {
4808                 branchcode   => undef,
4809                 categorycode => undef,
4810                 itemtype     => undef,
4811                 rule_name    => 'lostreturn',
4812                 rule_value   => 'refund'
4813             }
4814         }
4815     );
4816
4817     subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4818         plan tests => 3;
4819
4820         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4821         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4822
4823         my $lost_on = dt_from_string->subtract( days => 7 )->date;
4824
4825         my $item = $builder->build_sample_item(
4826             {
4827                 biblionumber     => $biblionumber,
4828                 library          => $library->branchcode,
4829                 replacementprice => '42',
4830             }
4831         );
4832         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4833         LostItem( $item->itemnumber, 'cli', 0 );
4834         $item->_result->itemlost(1);
4835         $item->_result->itemlost_on( $lost_on );
4836         $item->_result->update();
4837
4838         my $a = Koha::Account::Lines->search(
4839             {
4840                 itemnumber     => $item->id,
4841                 borrowernumber => $patron->borrowernumber
4842             }
4843         )->next;
4844         ok( $a, "Found accountline for lost fee" );
4845         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4846         $issue = AddIssue( $patron2->unblessed, $item->barcode );
4847         $a = $a->get_from_storage;
4848         is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4849         $a->delete;
4850         $issue->delete;
4851     };
4852
4853     subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4854         plan tests => 3;
4855
4856         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4857         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4858
4859         my $lost_on = dt_from_string->subtract( days => 6 )->date;
4860
4861         my $item = $builder->build_sample_item(
4862             {
4863                 biblionumber     => $biblionumber,
4864                 library          => $library->branchcode,
4865                 replacementprice => '42',
4866             }
4867         );
4868         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4869         LostItem( $item->itemnumber, 'cli', 0 );
4870         $item->_result->itemlost(1);
4871         $item->_result->itemlost_on( $lost_on );
4872         $item->_result->update();
4873
4874         my $a = Koha::Account::Lines->search(
4875             {
4876                 itemnumber     => $item->id,
4877                 borrowernumber => $patron->borrowernumber
4878             }
4879         )->next;
4880         ok( $a, "Found accountline for lost fee" );
4881         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4882         $issue = AddIssue( $patron2->unblessed, $item->barcode );
4883         $a = $a->get_from_storage;
4884         is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4885         $a->delete;
4886     };
4887
4888     subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4889         plan tests => 3;
4890
4891         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4892         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4893
4894         my $lost_on = dt_from_string->subtract( days => 7 )->date;
4895
4896         my $item = $builder->build_sample_item(
4897             {
4898                 biblionumber     => $biblionumber,
4899                 library          => $library->branchcode,
4900                 replacementprice => '42',
4901             }
4902         );
4903         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4904         LostItem( $item->itemnumber, 'cli', 0 );
4905         $item->_result->itemlost(1);
4906         $item->_result->itemlost_on( $lost_on );
4907         $item->_result->update();
4908
4909         my $a = Koha::Account::Lines->search(
4910             {
4911                 itemnumber     => $item->id,
4912                 borrowernumber => $patron->borrowernumber
4913             }
4914         )->next;
4915         ok( $a, "Found accountline for lost fee" );
4916         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4917         $issue = AddIssue( $patron2->unblessed, $item->barcode );
4918         $a = $a->get_from_storage;
4919         is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4920         $a->delete;
4921     };
4922
4923     subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4924         plan tests => 3;
4925
4926         t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee',   1 );
4927         t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4928
4929         my $lost_on = dt_from_string->subtract( days => 8 )->date;
4930
4931         my $item = $builder->build_sample_item(
4932             {
4933                 biblionumber     => $biblionumber,
4934                 library          => $library->branchcode,
4935                 replacementprice => '42',
4936             }
4937         );
4938         my $issue = AddIssue( $patron->unblessed, $item->barcode );
4939         LostItem( $item->itemnumber, 'cli', 0 );
4940         $item->_result->itemlost(1);
4941         $item->_result->itemlost_on( $lost_on );
4942         $item->_result->update();
4943
4944         my $a = Koha::Account::Lines->search(
4945             {
4946                 itemnumber     => $item->id,
4947                 borrowernumber => $patron->borrowernumber
4948             }
4949         );
4950         $a = $a->next;
4951         ok( $a, "Found accountline for lost fee" );
4952         is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4953         $issue = AddIssue( $patron2->unblessed, $item->barcode );
4954         $a = $a->get_from_storage;
4955         is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4956         $a->delete;
4957     };
4958 };
4959
4960 subtest 'transferbook tests' => sub {
4961     plan tests => 9;
4962
4963     throws_ok
4964     { C4::Circulation::transferbook({}); }
4965     'Koha::Exceptions::MissingParameter',
4966     'Koha::Patron->store raises an exception on missing params';
4967
4968     throws_ok
4969     { C4::Circulation::transferbook({to_branch=>'anything'}); }
4970     'Koha::Exceptions::MissingParameter',
4971     'Koha::Patron->store raises an exception on missing params';
4972
4973     throws_ok
4974     { C4::Circulation::transferbook({from_branch=>'anything'}); }
4975     'Koha::Exceptions::MissingParameter',
4976     'Koha::Patron->store raises an exception on missing params';
4977
4978     my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
4979     is( $doreturn, 0, "No return without barcode");
4980     ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
4981     is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
4982
4983     ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
4984     is( $doreturn, 0, "No return without barcode");
4985     ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
4986     is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
4987
4988 };
4989
4990 subtest 'Checkout should correctly terminate a transfer' => sub {
4991     plan tests => 7;
4992
4993     my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
4994     my $patron_1 = $builder->build_object(
4995         {
4996             class => 'Koha::Patrons',
4997             value => { branchcode => $library_1->branchcode }
4998         }
4999     );
5000     my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
5001     my $patron_2 = $builder->build_object(
5002         {
5003             class => 'Koha::Patrons',
5004             value => { branchcode => $library_2->branchcode }
5005         }
5006     );
5007
5008     my $item = $builder->build_sample_item(
5009         {
5010             library => $library_1->branchcode,
5011         }
5012     );
5013
5014     t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
5015     my $reserve_id = AddReserve(
5016         {
5017             branchcode     => $library_2->branchcode,
5018             borrowernumber => $patron_2->borrowernumber,
5019             biblionumber   => $item->biblionumber,
5020             itemnumber     => $item->itemnumber,
5021             priority       => 1,
5022         }
5023     );
5024
5025     my $do_transfer = 1;
5026     ModItemTransfer( $item->itemnumber, $library_1->branchcode,
5027         $library_2->branchcode, 'Manual' );
5028     ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
5029     GetOtherReserves( $item->itemnumber )
5030       ;    # To put the Reason, it's what does returns.pl...
5031     my $hold = Koha::Holds->find($reserve_id);
5032     is( $hold->found, 'T', 'Hold is in transit' );
5033     my $transfer = $item->get_transfer;
5034     is( $transfer->frombranch, $library_1->branchcode );
5035     is( $transfer->tobranch,   $library_2->branchcode );
5036     is( $transfer->reason,     'Reserve' );
5037
5038     t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
5039     AddIssue( $patron_1->unblessed, $item->barcode );
5040     $transfer = $transfer->get_from_storage;
5041     isnt( $transfer->datearrived, undef );
5042     $hold = $hold->get_from_storage;
5043     is( $hold->found, undef, 'Hold is waiting' );
5044     is( $hold->priority, 1, );
5045 };
5046
5047 subtest 'AddIssue records staff who checked out item if appropriate' => sub  {
5048     plan tests => 2;
5049
5050     $module->mock( 'userenv', sub { { branch => $library->{id} } } );
5051
5052     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5053     my $patron = $builder->build_object(
5054         {
5055             class => 'Koha::Patrons',
5056             value => { categorycode => $patron_category->{categorycode} }
5057         }
5058     );
5059     my $issuer = $builder->build_object(
5060         {
5061             class => 'Koha::Patrons',
5062             value => { categorycode => $patron_category->{categorycode} }
5063         }
5064     );
5065     my $item = $builder->build_sample_item(
5066         {
5067             library  => $library->{branchcode}
5068         }
5069     );
5070
5071     $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->{borrowernumber} } } );
5072
5073     my $dt_from = dt_from_string();
5074     my $dt_to   = dt_from_string()->add( days => 7 );
5075
5076     my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
5077
5078     is( $issue->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
5079
5080     t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
5081
5082     my $issue2 =
5083       AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
5084
5085     is( $issue->issuer, $issuer->{borrowernumber}, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
5086 };
5087
5088 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
5089     plan tests => 2;
5090
5091     my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5092     my $patron_1 = $builder->build_object(
5093         {
5094             class => 'Koha::Patrons',
5095             value => { branchcode => $library_1->branchcode }
5096         }
5097     );
5098     my $patron_2 = $builder->build_object(
5099         {
5100             class => 'Koha::Patrons',
5101             value => { branchcode => $library_1->branchcode }
5102         }
5103     );
5104
5105     my $item = $builder->build_sample_item(
5106         {
5107             library => $library_1->branchcode,
5108         }
5109     );
5110
5111     AddIssue( $patron_1->unblessed, $item->barcode );
5112     ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
5113     AddIssue( $patron_2->unblessed, $item->barcode );
5114     ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
5115 };
5116
5117 subtest "updateWrongTransfer tests" => sub {
5118     plan tests => 5;
5119
5120     my $library1 = $builder->build_object( { class => 'Koha::Libraries' } );
5121     my $library2 = $builder->build_object( { class => 'Koha::Libraries' } );
5122     my $library3 = $builder->build_object( { class => 'Koha::Libraries' } );
5123     my $item     = $builder->build_sample_item(
5124         {
5125             homebranch    => $library1->branchcode,
5126             holdingbranch => $library2->branchcode,
5127             datelastseen  => undef
5128         }
5129     );
5130
5131     my $transfer = $builder->build_object(
5132         {
5133             class => 'Koha::Item::Transfers',
5134             value => {
5135                 itemnumber    => $item->itemnumber,
5136                 frombranch    => $library2->branchcode,
5137                 tobranch      => $library1->branchcode,
5138                 daterequested => dt_from_string,
5139                 datesent      => dt_from_string,
5140                 datecancelled => undef,
5141                 datearrived   => undef,
5142                 reason        => 'Manual'
5143             }
5144         }
5145     );
5146     is( ref($transfer), 'Koha::Item::Transfer', 'Mock transfer added' );
5147
5148     my $new_transfer = C4::Circulation::updateWrongTransfer($item->itemnumber, $library1->branchcode);
5149     is(ref($new_transfer), 'Koha::Item::Transfer', "updateWrongTransfer returns a 'Koha::Item::Transfer' object");
5150     ok( !$new_transfer->in_transit, "New transfer is NOT created as in transit (or cancelled)");
5151
5152     my $original_transfer = $transfer->get_from_storage;
5153     ok( defined($original_transfer->datecancelled), "Original transfer was cancelled");
5154     is( $original_transfer->cancellation_reason, 'WrongTransfer', "Original transfer cancellation reason is 'WrongTransfer'");
5155 };
5156
5157 subtest "SendCirculationAlert" => sub {
5158     plan tests => 2;
5159
5160     # When you would unsuspectingly call this unit test (with perl, not prove), you will be bitten by LOCK.
5161     # LOCK will commit changes and ruin your data
5162     # In order to prevent that, we will add KOHA_TESTING to $ENV; see further Circulation.pm
5163     $ENV{KOHA_TESTING} = 1;
5164
5165     # Setup branch, borrowr, and notice
5166     my $library = $builder->build_object({ class => 'Koha::Libraries' });
5167     set_userenv( $library->unblessed);
5168     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5169     C4::Members::Messaging::SetMessagingPreference({
5170         borrowernumber => $patron->id,
5171         message_transport_types => ['email'],
5172         message_attribute_id => 5
5173     });
5174     my $item = $builder->build_sample_item();
5175     my $checkin_notice = $builder->build_object({
5176         class => 'Koha::Notice::Templates',
5177         value =>{
5178             module => 'circulation',
5179             code => 'CHECKIN',
5180             branchcode => $library->branchcode,
5181             name => 'Test Checkin',
5182             is_html => 0,
5183             content => "Checkins:\n----\n[% biblio.title %]-[% old_checkout.issue_id %]\n----Thank you.",
5184             message_transport_type => 'email',
5185             lang => 'default'
5186         }
5187     })->store;
5188
5189     # Checkout an item, mark it returned, generate a notice
5190     my $issue_1 = AddIssue( $patron->unblessed, $item->barcode);
5191     MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5192     C4::Circulation::SendCirculationAlert({
5193         type => 'CHECKIN',
5194         item => $item->unblessed,
5195         borrower => $patron->unblessed,
5196         branch => $library->branchcode,
5197         issue => $issue_1
5198     });
5199     my $notice = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'CHECKIN' });
5200     is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\nThank you.", 'Letter generated with expected output on first checkin' );
5201
5202     # Checkout an item, mark it returned, generate a notice
5203     my $issue_2 = AddIssue( $patron->unblessed, $item->barcode);
5204     MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5205     C4::Circulation::SendCirculationAlert({
5206         type => 'CHECKIN',
5207         item => $item->unblessed,
5208         borrower => $patron->unblessed,
5209         branch => $library->branchcode,
5210         issue => $issue_2
5211     });
5212     $notice->discard_changes();
5213     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' );
5214
5215 };
5216
5217 subtest "GetSoonestRenewDate tests" => sub {
5218     plan tests => 5;
5219     Koha::CirculationRules->set_rule(
5220         {
5221             categorycode => undef,
5222             branchcode   => undef,
5223             itemtype     => undef,
5224             rule_name    => 'norenewalbefore',
5225             rule_value   => '7',
5226         }
5227     );
5228     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5229     my $item = $builder->build_sample_item();
5230     my $issue = AddIssue( $patron->unblessed, $item->barcode);
5231     my $datedue = dt_from_string( $issue->date_due() );
5232
5233     # Bug 14395
5234     # Test 'exact time' setting for syspref NoRenewalBeforePrecision
5235     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
5236     is(
5237         GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5238         $datedue->clone->add( days => -7 ),
5239         'Bug 14395: Renewals permitted 7 days before due date, as expected'
5240     );
5241
5242     # Bug 14395
5243     # Test 'date' setting for syspref NoRenewalBeforePrecision
5244     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5245     is(
5246         GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5247         $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
5248         'Bug 14395: Renewals permitted 7 days before due date, as expected'
5249     );
5250
5251
5252     Koha::CirculationRules->set_rule(
5253         {
5254             categorycode => undef,
5255             branchcode   => undef,
5256             itemtype     => undef,
5257             rule_name    => 'norenewalbefore',
5258             rule_value   => undef,
5259         }
5260     );
5261
5262     is(
5263         GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5264         dt_from_string,
5265         'Checkouts without auto-renewal can be renewed immediately if no norenewalbefore'
5266     );
5267
5268     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5269     $issue->auto_renew(1)->store;
5270     is(
5271         GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5272         $datedue->clone->truncate( to => 'day' ),
5273         'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5274     );
5275     t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact' );
5276     is(
5277         GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5278         $datedue,
5279         'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5280     );
5281 };
5282
5283 $schema->storage->txn_rollback;
5284 C4::Context->clear_syspref_cache();
5285 $branches = Koha::Libraries->search();
5286 for my $branch ( $branches->next ) {
5287     my $key = $branch->branchcode . "_holidays";
5288     $cache->clear_from_cache($key);
5289 }