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