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