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