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