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