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